Add images to tasks

Everyone who may comment on a task sends images to it, e.g. photos
taken with a phone. The server stores an upright, at most 2560 px JPEG
without EXIF data (no location) and a 400 px thumbnail on the private
disk, served only to those who see the job. Uploaders change captions
(also the alt text) and remove their own images; admin and management
may remove anyone's (jobs.remove-any-task-image). Removing a task also
removes its image files.

Livewire's temporary upload limit is raised to PHP's 40 MB so that the
page's own 12 MB limit gives a translated message.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-25 07:46:53 +02:00
co-authored by Claude Sonnet 5.5
parent 4fb8ea1c5f
commit ae8172898d
40 changed files with 2250 additions and 8 deletions
+56
View File
@@ -7,12 +7,15 @@ use App\Modules\Catalog\Application\UseCases\AddWorkflowTemplate;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\ServiceUnitModel;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use App\Modules\Jobs\Application\Contracts\TaskImageFiles;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\ChecklistItemModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskCommentModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskImageModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
uses(RefreshDatabase::class);
@@ -164,6 +167,9 @@ it('has no accessibility issues on a job with tasks and on the task form', funct
ChecklistItemModel::query()->create(['task_id' => $task->id, 'text' => 'Mikit', 'sort_order' => 2]);
TaskCommentModel::query()->create(['task_id' => $task->id, 'user_id' => $this->user->id, 'body' => 'Valot ok.
Mikit puuttuu.', 'edited_at' => now()]);
Storage::fake('local');
$stored = app(TaskImageFiles::class)->store(browserTestImage(), $task->id);
TaskImageModel::query()->create(['task_id' => $task->id, 'user_id' => $this->user->id, 'path' => $stored->path, 'thumbnail_path' => $stored->thumbnailPath, 'original_name' => 'valot.png', 'caption' => 'Valot paikallaan', 'width' => $stored->width, 'height' => $stored->height]);
$url = match ($page) {
'job page' => route('jobs.show', $this->job->id),
@@ -315,6 +321,56 @@ it('adds, edits and removes a task comment with the keyboard', function () {
expect(TaskCommentModel::query()->count())->toBe(0);
});
/**
* A small PNG file for sending as a task image.
*/
function browserTestImage(): string
{
$image = imagecreatetruecolor(120, 80);
imagefill($image, 0, 0, (int) imagecolorallocate($image, 30, 120, 200));
$path = tempnam(sys_get_temp_dir(), 'img').'.png';
imagepng($image, $path);
return $path;
}
it('recaptions and removes a task image with the keyboard', function () {
Storage::fake('local');
$this->job->update(['status' => 'order']);
$workType = WorkTypeModel::query()->where('name', 'videokuvaus')->sole();
$task = TaskModel::factory()
->create(['customer_job_id' => $this->job->id, 'work_type_id' => $workType->id, 'title' => 'Kuvauspäivä']);
// Sending is covered by the feature tests: the browser plugin's test server keeps a
// multipart field named files[] under that literal key, so Livewire receives no upload.
$stored = app(TaskImageFiles::class)->store(browserTestImage(), $task->id);
TaskImageModel::query()->create(['task_id' => $task->id, 'user_id' => $this->user->id, 'path' => $stored->path, 'thumbnail_path' => $stored->thumbnailPath, 'original_name' => 'valot.png', 'caption' => 'Valot paikallaan', 'width' => $stored->width, 'height' => $stored->height]);
$page = visit(route('jobs.show', $this->job->id))
->click('#task-toggle-'.$task->id)
->assertVisible('img[alt="Valot paikallaan"]')
->assertScript("document.querySelector('img[alt=\"Valot paikallaan\"]').naturalWidth > 0", true)
->assertSeeIn('#task-'.$task->id.'-title + dl', 'Kuvat:');
$imageId = TaskImageModel::query()->sole()->id;
$page->keys('#image-edit-button-'.$imageId, 'Enter')
->assertScript('document.activeElement.id', 'image-caption-edit-'.$imageId)
->type('#image-caption-edit-'.$imageId, 'Lavasteet')
->keys('#image-caption-edit-'.$imageId, 'Enter')
->assertSee('Kuvateksti tallennettu.')
->assertScript('document.activeElement.id', 'image-edit-button-'.$imageId)
->keys('[aria-label="Poista kuva: Lavasteet"]', 'Enter')
->assertScript("document.getElementById('remove-image-dialog-{$task->id}').open", true)
->assertNoAccessibilityIssues(level: 2)
->click('#remove-image-confirm-'.$task->id)
->assertSee('Kuva poistettu.')
->assertScript('document.activeElement.id', 'image-new-'.$task->id)
->assertNoAccessibilityIssues(level: 2);
expect(TaskImageModel::query()->count())->toBe(0);
});
it('adds tasks from a workflow template with the keyboard, without accessibility issues', function (string $device, string $colorScheme) {
$this->job->update(['status' => 'order']);
$workType = WorkTypeModel::query()->where('name', 'videokuvaus')->sole();
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace Tests\Fakes;
use App\Modules\Jobs\Application\Contracts\TaskImageFiles;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskImage;
use App\Modules\Jobs\Domain\ValueObjects\StoredTaskImage;
class FakeTaskImageFiles implements TaskImageFiles
{
/** @var array<string, true> */
public array $files = [];
private int $counter = 0;
public function store(string $uploadedFilePath, int $taskId): StoredTaskImage
{
if (str_ends_with($uploadedFilePath, '.txt')) {
throw new InvalidTaskImage;
}
$this->counter++;
$stored = new StoredTaskImage("task-images/{$taskId}/{$this->counter}.jpg", "task-images/{$taskId}/{$this->counter}-thumb.jpg", 2560, 1920);
foreach ($stored->paths() as $path) {
$this->files[$path] = true;
}
return $stored;
}
public function delete(array $paths): void
{
foreach ($paths as $path) {
unset($this->files[$path]);
}
}
}
@@ -0,0 +1,53 @@
<?php
namespace Tests\Fakes;
use App\Modules\Jobs\Domain\Contracts\TaskImageRepository;
use App\Modules\Jobs\Domain\Entities\TaskImage;
class InMemoryTaskImageRepository implements TaskImageRepository
{
/** @var array<int, TaskImage> */
public array $images = [];
public bool $failOnSave = false;
private int $nextId = 1;
public function findForTask(int $taskId, int $imageId): ?TaskImage
{
$image = $this->images[$imageId] ?? null;
return $image !== null && $image->taskId() === $taskId ? clone $image : null;
}
public function filePathsOfTask(int $taskId): array
{
$paths = [];
foreach ($this->images as $image) {
if ($image->taskId() === $taskId) {
array_push($paths, ...$image->file()->paths());
}
}
return $paths;
}
public function save(TaskImage $image): TaskImage
{
if ($this->failOnSave) {
throw new \RuntimeException('Saving failed.');
}
$id = $image->id() ?? $this->nextId++;
$this->images[$id] = TaskImage::reconstitute($id, $image->taskId(), $image->uploaderId(), $image->file(), $image->originalName(), $image->caption(), $image->uploadedAt());
return clone $this->images[$id];
}
public function delete(TaskImage $image): void
{
unset($this->images[$image->id()]);
}
}
@@ -0,0 +1,182 @@
<?php
use App\Models\User;
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
use App\Modules\Jobs\Infrastructure\Files\GdTaskImageFiles;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskImageModel;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
Storage::fake('local');
$this->employee = User::factory()->create(['name' => 'Eetu Esimerkki']);
$this->actingAs($this->employee);
$this->job = CustomerJobModel::factory()->create(['status' => 'order', 'responsible_user_id' => $this->employee->id]);
$workType = WorkTypeModel::query()->where('name', 'graafinen työ')->sole();
$this->task = TaskModel::factory()->create(['customer_job_id' => $this->job->id, 'work_type_id' => $workType->id, 'title' => 'Mainoskuvat']);
$this->params = ['jobId' => $this->job->id, 'taskId' => $this->task->id, 'taskTitle' => 'Mainoskuvat'];
});
/**
* Sends an image through the page as the signed-in user.
*/
function uploadTaskImage(array $params, UploadedFile $file, string $caption = ''): TaskImageModel
{
Livewire::test('jobs::task-images', $params)
->set('photo', $file)
->set('caption', $caption)
->call('add')
->assertHasNoErrors();
return TaskImageModel::query()->latest('id')->firstOrFail();
}
/**
* A JPEG whose EXIF says it must be turned 90° clockwise (orientation 6),
* as phone cameras save upright photos.
*/
function sidewaysJpeg(int $width, int $height): string
{
$image = imagecreatetruecolor($width, $height);
ob_start();
imagejpeg($image);
$jpeg = (string) ob_get_clean();
$tiff = 'II*'."\0".pack('V', 8).pack('v', 1).pack('vvVv', 0x0112, 3, 1, 6)."\0\0".pack('V', 0);
$exif = 'Exif'."\0\0".$tiff;
$path = tempnam(sys_get_temp_dir(), 'exif').'.jpg';
file_put_contents($path, substr($jpeg, 0, 2)."\xFF\xE1".pack('n', strlen($exif) + 2).$exif.substr($jpeg, 2));
return $path;
}
it('stores a downscaled image and a thumbnail without metadata and shows them on the job page', function () {
$image = uploadTaskImage($this->params, UploadedFile::fake()->image('valot.jpg', 4000, 3000), 'Valot paikallaan');
[$width, $height] = getimagesizefromstring(Storage::disk('local')->get($image->path));
[$thumbWidth] = getimagesizefromstring(Storage::disk('local')->get($image->thumbnail_path));
expect([$width, $height])->toBe([2560, 1920])
->and([$image->width, $image->height])->toBe([2560, 1920])
->and($thumbWidth)->toBe(400)
->and($image->caption)->toBe('Valot paikallaan')
->and($image->original_name)->toBe('valot.jpg')
->and($image->user_id)->toBe($this->employee->id);
$this->get(route('jobs.show', $this->job->id))
->assertOk()
->assertSee('Kuvat:')
->assertSee('alt="Valot paikallaan"', false)
->assertSee(route('jobs.tasks.images.show', [$this->job->id, $this->task->id, $image->id, 'thumbnail']));
});
it('turns a sideways phone photo upright and leaves out its EXIF data', function () {
$stored = (new GdTaskImageFiles)->store(sidewaysJpeg(40, 20), $this->task->id);
$bytes = Storage::disk('local')->get($stored->path);
expect(getimagesizefromstring($bytes)[0])->toBe(20)
->and(getimagesizefromstring($bytes)[1])->toBe(40)
->and(str_contains($bytes, 'Exif'))->toBeFalse();
});
it('shows Finnish errors for a missing, non-image and too large file', function () {
Livewire::test('jobs::task-images', $this->params)
->call('add')
->assertSee('Valitse kuva.')
->set('photo', UploadedFile::fake()->create('muistio.pdf', 10, 'application/pdf'))
->call('add')
->assertSee('Tiedosto ei ole kuva.')
->set('photo', UploadedFile::fake()->image('iso.jpg')->size(13000))
->call('add')
->assertSee('Kuva voi olla enintään 12 Mt.')
->set('photo', UploadedFile::fake()->image('kuva.jpg'))
->set('caption', str_repeat('a', 256))
->call('add')
->assertSee('Kuvateksti voi olla enintään 255 merkkiä.');
expect(TaskImageModel::query()->count())->toBe(0)
->and(Storage::disk('local')->allFiles('task-images'))->toBe([]);
});
it('serves the image to those who see the job, and downloads it under its own name', function () {
$image = uploadTaskImage($this->params, UploadedFile::fake()->image('valot.png', 50, 50));
$this->get(route('jobs.tasks.images.show', [$this->job->id, $this->task->id, $image->id, 'full']))
->assertOk()
->assertHeader('Content-Type', 'image/jpeg');
$this->get(route('jobs.tasks.images.show', [$this->job->id, $this->task->id, $image->id, 'full']).'?download=1')
->assertDownload('valot.jpg');
$otherJob = CustomerJobModel::factory()->create();
$this->get(route('jobs.tasks.images.show', [$otherJob->id, $this->task->id, $image->id, 'full']))->assertNotFound();
$this->actingAs(User::factory()->subcontractor()->create());
$this->get(route('jobs.tasks.images.show', [$this->job->id, $this->task->id, $image->id, 'thumbnail']))->assertForbidden();
});
it('lets the uploader change the caption and remove the image with its files', function () {
$image = uploadTaskImage($this->params, UploadedFile::fake()->image('valot.jpg'));
Livewire::test('jobs::task-images', $this->params)
->call('startEdit', $image->id)
->set('editingCaption', 'Lavasteet')
->call('saveEdit')
->assertSee('Kuvateksti tallennettu.')
->assertSet('editingImageId', null)
->call('confirmRemoval', $image->id)
->assertSet('removalImageId', $image->id)
->call('remove')
->assertSee('Kuva poistettu.')
->assertDispatched('task-images-changed');
expect(TaskImageModel::query()->count())->toBe(0)
->and(Storage::disk('local')->allFiles('task-images'))->toBe([]);
});
it('lets management remove but not recaption another user\'s image, and others neither', function () {
$image = uploadTaskImage($this->params, UploadedFile::fake()->image('valot.jpg'));
$this->actingAs(User::factory()->create());
Livewire::test('jobs::task-images', $this->params)
->assertDontSee('Poista kuva')
->call('confirmRemoval', $image->id)
->assertSet('removalImageId', null)
->assertSee('Voit muokata ja poistaa vain itse lähettämiäsi kuvia.');
$this->actingAs(User::factory()->management()->create());
Livewire::test('jobs::task-images', $this->params)
->assertDontSee('Muokkaa kuvatekstiä')
->call('confirmRemoval', $image->id)
->call('remove')
->assertSee('Kuva poistettu.');
expect(TaskImageModel::query()->count())->toBe(0);
});
it('lets an attached subcontractor send images but forbids a job they are not attached to', function () {
$subcontractor = User::factory()->subcontractor()->create();
TaskModel::factory()->assignedTo([$subcontractor->id])->create(['customer_job_id' => $this->job->id, 'work_type_id' => $this->task->work_type_id]);
$this->actingAs($subcontractor);
expect(uploadTaskImage($this->params, UploadedFile::fake()->image('valmis.jpg'))->user_id)->toBe($subcontractor->id);
$this->actingAs(User::factory()->subcontractor()->create());
Livewire::test('jobs::task-images', $this->params)->assertForbidden();
});
it('removes the image files with their task', function () {
uploadTaskImage($this->params, UploadedFile::fake()->image('valot.jpg'));
Livewire::test('jobs::show', ['job' => $this->job->id])
->call('confirmTaskRemoval', $this->task->id)
->call('removeTask');
expect(TaskImageModel::query()->count())->toBe(0)
->and(Storage::disk('local')->allFiles('task-images'))->toBe([]);
});
@@ -0,0 +1,103 @@
<?php
use App\Modules\Jobs\Application\Services\TaskImageFinder;
use App\Modules\Jobs\Application\UseCases\AddTaskImage;
use App\Modules\Jobs\Application\UseCases\ChangeTaskImageCaption;
use App\Modules\Jobs\Application\UseCases\RemoveTask;
use App\Modules\Jobs\Application\UseCases\RemoveTaskImage;
use App\Modules\Jobs\Domain\Entities\Task;
use App\Modules\Jobs\Domain\Enums\TaskStatus;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskImage;
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskImageCaption;
use App\Modules\Jobs\Domain\Exceptions\NotTaskImageUploader;
use App\Modules\Jobs\Domain\Exceptions\TaskImageNotFound;
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
use App\Modules\Jobs\Domain\ValueObjects\TaskImageCaption;
use App\Modules\Jobs\Domain\ValueObjects\TaskTitle;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeTaskImageFiles;
use Tests\Fakes\FakeTaskUsage;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryTaskImageRepository;
use Tests\Fakes\InMemoryTaskRepository;
beforeEach(function () {
$this->tasks = new InMemoryTaskRepository;
$this->images = new InMemoryTaskImageRepository;
$this->files = new FakeTaskImageFiles;
$transactions = new FakeTransactionManager;
$finder = new TaskImageFinder($this->tasks, $this->images);
$this->jobId = 5;
$this->taskId = (int) $this->tasks->save(Task::reconstitute(1, $this->jobId, 11, new TaskTitle('Kuvaus'), null, TaskStatus::Waiting, null, null, null, [], 10))->id();
$this->add = new AddTaskImage($finder, $this->images, $this->files, $transactions, new FakeClock(new DateTimeImmutable('2026-11-25')));
$this->changeCaption = new ChangeTaskImageCaption($finder, $this->images, $transactions);
$this->remove = new RemoveTaskImage($finder, $this->images, $this->files, $transactions);
$this->removeTask = new RemoveTask($this->tasks, new FakeTaskUsage, $transactions, $this->images, $this->files);
});
it('treats an empty caption as none and rejects too long captions', function () {
expect(TaskImageCaption::fromNullable(' '))->toBeNull()
->and(TaskImageCaption::fromNullable(null))->toBeNull()
->and(TaskImageCaption::fromNullable(" Valot \n paikallaan ")?->value)->toBe('Valot paikallaan')
->and(fn () => TaskImageCaption::fromNullable(str_repeat('a', 256)))->toThrow(InvalidTaskImageCaption::class);
});
it('adds an image with its files, uploader, caption and time', function () {
$imageId = $this->add->execute($this->jobId, $this->taskId, 10, '/tmp/upload.jpg', 'IMG_1234.HEIC.jpg', 'Valot');
$image = $this->images->images[$imageId];
expect($image->uploaderId())->toBe(10)
->and($image->caption()?->value)->toBe('Valot')
->and($image->originalName())->toBe('IMG_1234.HEIC.jpg')
->and($image->uploadedAt()->format('Y-m-d H:i'))->toBe('2026-11-25 12:00')
->and(array_keys($this->files->files))->toBe($image->file()->paths());
});
it('stores no files for an unreadable image, an invalid caption or a task of another job', function () {
expect(fn () => $this->add->execute($this->jobId, $this->taskId, 10, '/tmp/upload.txt', 'muistio.txt', null))->toThrow(InvalidTaskImage::class)
->and(fn () => $this->add->execute($this->jobId, $this->taskId, 10, '/tmp/upload.jpg', 'kuva.jpg', str_repeat('a', 256)))->toThrow(InvalidTaskImageCaption::class)
->and(fn () => $this->add->execute(99, $this->taskId, 10, '/tmp/upload.jpg', 'kuva.jpg', null))->toThrow(TaskNotFound::class)
->and($this->files->files)->toBe([]);
});
it('removes the stored files when the image cannot be saved', function () {
$this->images->failOnSave = true;
expect(fn () => $this->add->execute($this->jobId, $this->taskId, 10, '/tmp/upload.jpg', 'kuva.jpg', null))->toThrow(RuntimeException::class)
->and($this->files->files)->toBe([]);
});
it('lets only the uploader change or clear the caption', function () {
$imageId = $this->add->execute($this->jobId, $this->taskId, 10, '/tmp/upload.jpg', 'kuva.jpg', null);
$this->changeCaption->execute($this->jobId, $this->taskId, $imageId, 10, 'Lavasteet');
expect($this->images->images[$imageId]->caption()?->value)->toBe('Lavasteet');
$this->changeCaption->execute($this->jobId, $this->taskId, $imageId, 10, '');
expect($this->images->images[$imageId]->caption())->toBeNull()
->and(fn () => $this->changeCaption->execute($this->jobId, $this->taskId, $imageId, 12, 'Toisen'))->toThrow(NotTaskImageUploader::class);
});
it('lets the uploader remove an image with its files, and others only when they may remove anyone\'s', function () {
$own = $this->add->execute($this->jobId, $this->taskId, 10, '/tmp/a.jpg', 'a.jpg', null);
$other = $this->add->execute($this->jobId, $this->taskId, 10, '/tmp/b.jpg', 'b.jpg', null);
expect(fn () => $this->remove->execute($this->jobId, $this->taskId, $other, 12, false))->toThrow(NotTaskImageUploader::class);
$this->remove->execute($this->jobId, $this->taskId, $own, 10, false);
$this->remove->execute($this->jobId, $this->taskId, $other, 12, true);
expect($this->images->images)->toBe([])
->and($this->files->files)->toBe([])
->and(fn () => $this->remove->execute($this->jobId, $this->taskId, $own, 10, true))->toThrow(TaskImageNotFound::class);
});
it('removes the files of the images of a removed task', function () {
$this->add->execute($this->jobId, $this->taskId, 10, '/tmp/a.jpg', 'a.jpg', null);
$this->removeTask->execute($this->jobId, $this->taskId);
expect($this->files->files)->toBe([]);
});
@@ -27,12 +27,14 @@ use Tests\Fakes\FakeCatalogQueries;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakeCustomerQueries;
use Tests\Fakes\FakeSettings;
use Tests\Fakes\FakeTaskImageFiles;
use Tests\Fakes\FakeTaskUsage;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\FakeUserAccountQueries;
use Tests\Fakes\InMemoryCustomerJobRepository;
use Tests\Fakes\InMemoryHolidayOverrides;
use Tests\Fakes\InMemoryTaskBookingRepository;
use Tests\Fakes\InMemoryTaskImageRepository;
use Tests\Fakes\InMemoryTaskRepository;
beforeEach(function () {
@@ -66,7 +68,7 @@ beforeEach(function () {
$this->clearSchedule = new ClearTaskSchedule($this->tasks, $this->planner, $transactions);
$this->changeTaskStatus = new ChangeTaskStatus($this->tasks, $transactions);
$this->usage = new FakeTaskUsage;
$this->removeTask = new RemoveTask($this->tasks, $this->usage, $transactions);
$this->removeTask = new RemoveTask($this->tasks, $this->usage, $transactions, new InMemoryTaskImageRepository, new FakeTaskImageFiles);
$this->changeJobStatus = new ChangeJobStatus($this->jobs, $transactions, new FakeClock(new DateTimeImmutable('2026-05-01')));
});