diff --git a/CLAUDE.md b/CLAUDE.md index f3939a0..06ab029 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project -An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: ``, ``), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; workflow templates of work types with ordered steps, read through `WorkflowTemplateQueries`, from which Jobs' `AddTasksFromWorkflowTemplate` makes a job's tasks, each with its own assignee and, by default, scheduled to end on its due date with the estimate booked backwards from it (`TaskPlanner::planBackwards`, not before today); hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks with one assignee (`tasks.assignee_user_id`) and members (`task_members`, who see the task among their own but get no bookings), task checklists, task comments (`jobs::task-comments`: anyone with `jobs.update-task-status` comments, authors edit and remove their own, `jobs.remove-any-task-comment` removes anyone's), and the task calendar `jobs::calendar`: a Gantt of tasks on their assignee's row where `ScheduleTask` moves a task's planned period and assignee and `TaskPlanner`/`TaskScheduler` book its estimate into `task_bookings` for the assignee only, split over working days with the rest moved to the next working day past the daily maximum `jobs.daily_capacity_hours`) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) `Billing` (the monthly billing material (its running number `billing_exports.number` is reserved only when it is created, so discarded drafts leave no gaps, and a draft has none): a draft of invoices made of done jobs and monthly fee jobs (one line per unbilled month up to the draft's month, each such job an invoice of its own), management's billable hours, and on creation invoice lines with price snapshots, downloadable as a semicolon CSV with amounts in whole cents and the VAT rate in tenths of a percent (`billing.csv`, with consumers' identity codes for those who may see them); reads and marks hours, expenses and jobs through its `BillingJobs`/`BillingHours`/`BillingExpenses`/`BillingPrices` ports, which call those modules' queries and the use cases `MarkJobHoursBilled`, `MarkJobExpensesBilled` and `ChangeJobStatus`) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users). +An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: ``, ``), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; workflow templates of work types with ordered steps, read through `WorkflowTemplateQueries`, from which Jobs' `AddTasksFromWorkflowTemplate` makes a job's tasks, each with its own assignee and, by default, scheduled to end on its due date with the estimate booked backwards from it (`TaskPlanner::planBackwards`, not before today); hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks with one assignee (`tasks.assignee_user_id`) and members (`task_members`, who see the task among their own but get no bookings), task checklists, task comments (`jobs::task-comments`: anyone with `jobs.update-task-status` comments, authors edit and remove their own, `jobs.remove-any-task-comment` removes anyone's), task images (`jobs::task-images`, same rules with `jobs.remove-any-task-image`; `GdTaskImageFiles` stores an upright, at most 2560 px JPEG without EXIF and a 400 px thumbnail under `task-images/` on the private `local` disk, served only through `ShowTaskImage` after `jobs.view-job`; `RemoveTask` also deletes the files), and the task calendar `jobs::calendar`: a Gantt of tasks on their assignee's row where `ScheduleTask` moves a task's planned period and assignee and `TaskPlanner`/`TaskScheduler` book its estimate into `task_bookings` for the assignee only, split over working days with the rest moved to the next working day past the daily maximum `jobs.daily_capacity_hours`) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) `Billing` (the monthly billing material (its running number `billing_exports.number` is reserved only when it is created, so discarded drafts leave no gaps, and a draft has none): a draft of invoices made of done jobs and monthly fee jobs (one line per unbilled month up to the draft's month, each such job an invoice of its own), management's billable hours, and on creation invoice lines with price snapshots, downloadable as a semicolon CSV with amounts in whole cents and the VAT rate in tenths of a percent (`billing.csv`, with consumers' identity codes for those who may see them); reads and marks hours, expenses and jobs through its `BillingJobs`/`BillingHours`/`BillingExpenses`/`BillingPrices` ports, which call those modules' queries and the use cases `MarkJobHoursBilled`, `MarkJobExpensesBilled` and `ChangeJobStatus`) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users). - **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec. - **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification is in Finnish. The UI is in Finnish (default) and English: every UI string lives in `lang/fi/*.php` **and** `lang/en/*.php` with the same keys and placeholders (`tests/Unit/TranslationFilesTest.php` fails otherwise). Number, money and date formats stay Finnish in both languages; the quick sale receipt is always Finnish. @@ -23,7 +23,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap - **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`. - **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages. - Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules. -- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `jobs.remove-any-task-comment`, `time.use`, `time.book`, `time.approve`, `time.approve-others`, `time.cancel-approval`, `jobs.unlock`, `catalog.view-prices`, `expenses.use`, `expenses.record`, `expenses.record-for-others`, `expenses.change`, `expenses.see-amount`, `sales.use`, `sales.view-all`, `sales.view-sale`, `sales.credit`, `sales.close-day`, `sales.reopen-day`, `billing.manage`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. +- **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`, `catalog.manage`, `jobs.view`, `jobs.view-job`, `jobs.manage`, `jobs.archive`, `jobs.set-billing-status`, `jobs.manage-tasks`, `jobs.update-task-status`, `jobs.remove-any-task-comment`, `jobs.remove-any-task-image`, `time.use`, `time.book`, `time.approve`, `time.approve-others`, `time.cancel-approval`, `jobs.unlock`, `catalog.view-prices`, `expenses.use`, `expenses.record`, `expenses.record-for-others`, `expenses.change`, `expenses.see-amount`, `sales.use`, `sales.view-all`, `sales.view-sale`, `sales.credit`, `sales.close-day`, `sales.reopen-day`, `billing.manage`, and in `Users` `money.prices`, `money.expenses`, `money.quotes`, `money.billing` for the personal money permissions of specification 2.3). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. - **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). Login allows 5 failed attempts a minute per email + IP and 20 per IP; the forgot-password page 5 requests a minute per IP. - **Main menu**: the layout renders the groups of `App\View\MainMenu` (Työt, Oma kirjaus, Asiakkaat ja myynti, Hallinto, Ylläpito) as disclosure popovers (`resources/views/components/nav-group.blade.php`). A new page is added to `MainMenu::definition()` with the Gate ability of its route; groups with no allowed links disappear. - **Holidays** are Shared: `Shared\Application\UseCases\HolidayCalendar` gives the Finnish public holidays (`FinnishHolidays`, calculated) minus those the admin took out of use plus company days off (`holiday_overrides`), edited on `shared::holidays` (`/settings/holidays`, gate `settings.manage`). diff --git a/app/Modules/Jobs/Application/Contracts/TaskImageFiles.php b/app/Modules/Jobs/Application/Contracts/TaskImageFiles.php new file mode 100644 index 0000000..41f86f9 --- /dev/null +++ b/app/Modules/Jobs/Application/Contracts/TaskImageFiles.php @@ -0,0 +1,29 @@ + $paths + */ + public function delete(array $paths): void; +} diff --git a/app/Modules/Jobs/Application/Contracts/TaskImageQueries.php b/app/Modules/Jobs/Application/Contracts/TaskImageQueries.php new file mode 100644 index 0000000..74b6def --- /dev/null +++ b/app/Modules/Jobs/Application/Contracts/TaskImageQueries.php @@ -0,0 +1,26 @@ + + */ + public function imagesOf(int $jobId, int $taskId): array; + + /** + * Where the full image or its thumbnail is kept, for showing it after + * the job's visibility is checked; null when the image does not belong + * to the task and job. + */ + public function fileOf(int $jobId, int $taskId, int $imageId, bool $thumbnail): ?TaskImageFile; +} diff --git a/app/Modules/Jobs/Application/DTOs/TaskImageFile.php b/app/Modules/Jobs/Application/DTOs/TaskImageFile.php new file mode 100644 index 0000000..c6c14cf --- /dev/null +++ b/app/Modules/Jobs/Application/DTOs/TaskImageFile.php @@ -0,0 +1,16 @@ +ensureTask($jobId, $taskId); + + return $this->images->findForTask($taskId, $imageId) ?? throw new TaskImageNotFound($taskId, $imageId); + } + + /** + * @throws TaskNotFound + */ + public function ensureTask(int $jobId, int $taskId): void + { + if ($this->tasks->findForJob($jobId, $taskId) === null) { + throw new TaskNotFound($jobId, $taskId); + } + } +} diff --git a/app/Modules/Jobs/Application/UseCases/AddTaskImage.php b/app/Modules/Jobs/Application/UseCases/AddTaskImage.php new file mode 100644 index 0000000..2dc29f1 --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/AddTaskImage.php @@ -0,0 +1,59 @@ +finder->ensureTask($jobId, $taskId); + + $stored = $this->files->store($uploadedFilePath, $taskId); + + try { + return $this->transactions->run(function () use ($jobId, $taskId, $userId, $stored, $originalName, $caption): int { + $this->finder->ensureTask($jobId, $taskId); + + return (int) $this->images->save(TaskImage::create($taskId, $userId, $stored, $originalName, $caption, $this->clock->now()))->id(); + }); + } catch (Throwable $exception) { + $this->files->delete($stored->paths()); + + throw $exception; + } + } +} diff --git a/app/Modules/Jobs/Application/UseCases/ChangeTaskImageCaption.php b/app/Modules/Jobs/Application/UseCases/ChangeTaskImageCaption.php new file mode 100644 index 0000000..d70cac2 --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/ChangeTaskImageCaption.php @@ -0,0 +1,44 @@ +transactions->run(function () use ($jobId, $taskId, $imageId, $userId, $caption): void { + $image = $this->finder->find($jobId, $taskId, $imageId); + $image->changeCaption($userId, $caption); + + $this->images->save($image); + }); + } +} diff --git a/app/Modules/Jobs/Application/UseCases/RemoveTask.php b/app/Modules/Jobs/Application/UseCases/RemoveTask.php index df1882d..700881b 100644 --- a/app/Modules/Jobs/Application/UseCases/RemoveTask.php +++ b/app/Modules/Jobs/Application/UseCases/RemoveTask.php @@ -4,14 +4,16 @@ declare(strict_types=1); namespace App\Modules\Jobs\Application\UseCases; +use App\Modules\Jobs\Application\Contracts\TaskImageFiles; use App\Modules\Jobs\Application\Contracts\TaskUsage; +use App\Modules\Jobs\Domain\Contracts\TaskImageRepository; use App\Modules\Jobs\Domain\Contracts\TaskRepository; use App\Modules\Jobs\Domain\Exceptions\TaskHasTimeEntries; use App\Modules\Jobs\Domain\Exceptions\TaskNotFound; use App\Modules\Shared\Application\Contracts\TransactionManager; /** - * Deletes a task that has no time entries. + * Deletes a task that has no time entries, and then its images' files. */ final class RemoveTask { @@ -19,6 +21,8 @@ final class RemoveTask private TaskRepository $tasks, private TaskUsage $usage, private TransactionManager $transactions, + private TaskImageRepository $images, + private TaskImageFiles $imageFiles, ) {} /** @@ -27,14 +31,19 @@ final class RemoveTask */ public function execute(int $jobId, int $taskId): void { - $this->transactions->run(function () use ($jobId, $taskId): void { + $imagePaths = $this->transactions->run(function () use ($jobId, $taskId): array { $task = $this->tasks->findForJob($jobId, $taskId) ?? throw new TaskNotFound($jobId, $taskId); if ($this->usage->hasTimeEntries($taskId)) { throw new TaskHasTimeEntries; } + $imagePaths = $this->images->filePathsOfTask($taskId); $this->tasks->delete($task); + + return $imagePaths; }); + + $this->imageFiles->delete($imagePaths); } } diff --git a/app/Modules/Jobs/Application/UseCases/RemoveTaskImage.php b/app/Modules/Jobs/Application/UseCases/RemoveTaskImage.php new file mode 100644 index 0000000..7dfd7a7 --- /dev/null +++ b/app/Modules/Jobs/Application/UseCases/RemoveTaskImage.php @@ -0,0 +1,46 @@ +transactions->run(function () use ($jobId, $taskId, $imageId, $userId, $mayRemoveOthers): array { + $image = $this->finder->find($jobId, $taskId, $imageId); + $image->ensureRemovableBy($userId, $mayRemoveOthers); + + $this->images->delete($image); + + return $image->file()->paths(); + }); + + $this->files->delete($paths); + } +} diff --git a/app/Modules/Jobs/Domain/Contracts/TaskImageRepository.php b/app/Modules/Jobs/Domain/Contracts/TaskImageRepository.php new file mode 100644 index 0000000..a3f2e94 --- /dev/null +++ b/app/Modules/Jobs/Domain/Contracts/TaskImageRepository.php @@ -0,0 +1,26 @@ + + */ + public function filePathsOfTask(int $taskId): array; + + public function save(TaskImage $image): TaskImage; + + public function delete(TaskImage $image): void; +} diff --git a/app/Modules/Jobs/Domain/Entities/TaskImage.php b/app/Modules/Jobs/Domain/Entities/TaskImage.php new file mode 100644 index 0000000..056f008 --- /dev/null +++ b/app/Modules/Jobs/Domain/Entities/TaskImage.php @@ -0,0 +1,108 @@ +ensureUploader($userId); + + $this->caption = $caption; + } + + /** + * @throws NotTaskImageUploader + */ + public function ensureRemovableBy(int $userId, bool $mayRemoveOthers): void + { + if (! $mayRemoveOthers) { + $this->ensureUploader($userId); + } + } + + public function id(): ?int + { + return $this->id; + } + + public function taskId(): int + { + return $this->taskId; + } + + public function uploaderId(): ?int + { + return $this->uploaderId; + } + + public function file(): StoredTaskImage + { + return $this->file; + } + + public function originalName(): string + { + return $this->originalName; + } + + public function caption(): ?TaskImageCaption + { + return $this->caption; + } + + public function uploadedAt(): DateTimeImmutable + { + return $this->uploadedAt; + } + + /** + * @throws NotTaskImageUploader + */ + private function ensureUploader(int $userId): void + { + if ($this->uploaderId !== $userId) { + throw new NotTaskImageUploader((int) $this->id, $userId); + } + } +} diff --git a/app/Modules/Jobs/Domain/Exceptions/InvalidTaskImage.php b/app/Modules/Jobs/Domain/Exceptions/InvalidTaskImage.php new file mode 100644 index 0000000..32f3995 --- /dev/null +++ b/app/Modules/Jobs/Domain/Exceptions/InvalidTaskImage.php @@ -0,0 +1,18 @@ + + */ + public function paths(): array + { + return [$this->path, $this->thumbnailPath]; + } +} diff --git a/app/Modules/Jobs/Domain/ValueObjects/TaskImageCaption.php b/app/Modules/Jobs/Domain/ValueObjects/TaskImageCaption.php new file mode 100644 index 0000000..ba275b5 --- /dev/null +++ b/app/Modules/Jobs/Domain/ValueObjects/TaskImageCaption.php @@ -0,0 +1,37 @@ + self::MAX_LENGTH) { + throw new InvalidTaskImageCaption; + } + + return new self($value); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Files/GdTaskImageFiles.php b/app/Modules/Jobs/Infrastructure/Files/GdTaskImageFiles.php new file mode 100644 index 0000000..4121913 --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Files/GdTaskImageFiles.php @@ -0,0 +1,149 @@ +upright($this->read($uploadedFilePath), $uploadedFilePath); + + try { + $full = $this->scaled($image, self::MAX_SIZE); + $thumbnail = $this->scaled($image, self::THUMBNAIL_SIZE); + + $name = 'task-images/'.$taskId.'/'.Str::uuid()->toString(); + $stored = new StoredTaskImage($name.'.jpg', $name.'-thumb.jpg', imagesx($full), imagesy($full)); + + Storage::disk(self::DISK)->put($stored->path, $this->jpeg($full)); + Storage::disk(self::DISK)->put($stored->thumbnailPath, $this->jpeg($thumbnail)); + + return $stored; + } finally { + imagedestroy($image); + } + } + + public function delete(array $paths): void + { + if ($paths !== []) { + Storage::disk(self::DISK)->delete($paths); + } + } + + /** + * @throws InvalidTaskImage + */ + private function read(string $path): GdImage + { + $info = @getimagesize($path); + + if ($info === false || $info[0] < 1 || $info[1] < 1 || $info[0] * $info[1] > self::MAX_PIXELS) { + throw new InvalidTaskImage; + } + + $image = match ($info[2]) { + IMAGETYPE_JPEG => @imagecreatefromjpeg($path), + IMAGETYPE_PNG => @imagecreatefrompng($path), + IMAGETYPE_GIF => @imagecreatefromgif($path), + IMAGETYPE_WEBP => @imagecreatefromwebp($path), + default => false, + }; + + if ($image === false) { + throw new InvalidTaskImage; + } + + // Transparent parts become white, as JPEG has no transparency. + $flat = imagecreatetruecolor(imagesx($image), imagesy($image)); + imagefill($flat, 0, 0, (int) imagecolorallocate($flat, 255, 255, 255)); + imagecopy($flat, $image, 0, 0, 0, 0, imagesx($image), imagesy($image)); + imagedestroy($image); + + return $flat; + } + + /** + * Phone cameras save photos sideways and tell the right way up in EXIF. + */ + private function upright(GdImage $image, string $path): GdImage + { + $exif = function_exists('exif_read_data') ? @exif_read_data($path) : false; + $orientation = is_array($exif) ? (int) ($exif['Orientation'] ?? 1) : 1; + + $rotated = match ($orientation) { + 3 => imagerotate($image, 180, 0), + 5, 6 => imagerotate($image, -90, 0), + 7, 8 => imagerotate($image, 90, 0), + default => $image, + }; + + if ($rotated === false) { + return $image; + } + + if (in_array($orientation, [2, 5, 7], true)) { + imageflip($rotated, IMG_FLIP_HORIZONTAL); + } elseif ($orientation === 4) { + imageflip($rotated, IMG_FLIP_VERTICAL); + } + + if ($rotated !== $image) { + imagedestroy($image); + } + + return $rotated; + } + + /** + * A copy whose longer side is at most the given size. + */ + private function scaled(GdImage $image, int $maxSize): GdImage + { + $width = imagesx($image); + $height = imagesy($image); + $ratio = min(1, $maxSize / max($width, $height)); + $newWidth = max(1, (int) round($width * $ratio)); + $newHeight = max(1, (int) round($height * $ratio)); + + $copy = imagecreatetruecolor($newWidth, $newHeight); + imagecopyresampled($copy, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height); + + return $copy; + } + + private function jpeg(GdImage $image): string + { + ob_start(); + imagejpeg($image, null, self::QUALITY); + imagedestroy($image); + + return (string) ob_get_clean(); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskImageModel.php b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskImageModel.php new file mode 100644 index 0000000..da6c35f --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Eloquent/TaskImageModel.php @@ -0,0 +1,43 @@ + + */ + protected function casts(): array + { + return [ + 'task_id' => 'integer', + 'user_id' => 'integer', + 'width' => 'integer', + 'height' => 'integer', + 'created_at' => 'immutable_datetime', + 'updated_at' => 'immutable_datetime', + ]; + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskImageQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskImageQueries.php new file mode 100644 index 0000000..7854d85 --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskImageQueries.php @@ -0,0 +1,61 @@ +ofTask($jobId, $taskId)->orderBy('id')->get(); + $names = $this->users->namesByIds($models->pluck('user_id')->filter()->unique()->values()->all()); + + return $models + ->map(fn (TaskImageModel $model): TaskImageSummary => new TaskImageSummary( + $model->id, + $model->user_id, + $model->user_id === null ? '' : ($names[$model->user_id] ?? ''), + $model->caption, + $model->original_name, + $model->created_at->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'), + $model->width, + $model->height, + )) + ->values() + ->all(); + } + + public function fileOf(int $jobId, int $taskId, int $imageId, bool $thumbnail): ?TaskImageFile + { + $model = $this->ofTask($jobId, $taskId)->find($imageId); + + if ($model === null) { + return null; + } + + // The stored file is always a JPEG, whatever the original was. + $name = pathinfo($model->original_name, PATHINFO_FILENAME); + + return new TaskImageFile($thumbnail ? $model->thumbnail_path : $model->path, ($name === '' ? 'kuva' : $name).'.jpg'); + } + + /** + * @return Builder + */ + private function ofTask(int $jobId, int $taskId): Builder + { + return TaskImageModel::query() + ->where('task_id', $taskId) + ->whereExists(fn ($query) => $query->selectRaw('1')->from('tasks') + ->whereColumn('tasks.id', 'task_images.task_id') + ->where('tasks.customer_job_id', $jobId)); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskImageRepository.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskImageRepository.php new file mode 100644 index 0000000..224805f --- /dev/null +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskImageRepository.php @@ -0,0 +1,67 @@ +where('task_id', $taskId)->find($imageId); + + return $model === null ? null : $this->toEntity($model); + } + + public function filePathsOfTask(int $taskId): array + { + return TaskImageModel::query() + ->where('task_id', $taskId) + ->get(['path', 'thumbnail_path']) + ->flatMap(fn (TaskImageModel $model): array => [$model->path, $model->thumbnail_path]) + ->values() + ->all(); + } + + public function save(TaskImage $image): TaskImage + { + $model = $image->id() === null ? new TaskImageModel : TaskImageModel::query()->findOrFail($image->id()); + + $model->fill([ + 'task_id' => $image->taskId(), + 'user_id' => $image->uploaderId(), + 'path' => $image->file()->path, + 'thumbnail_path' => $image->file()->thumbnailPath, + 'original_name' => $image->originalName(), + 'caption' => $image->caption()?->value, + 'width' => $image->file()->width, + 'height' => $image->file()->height, + 'created_at' => $image->uploadedAt(), + ])->save(); + + return $this->toEntity($model->refresh()); + } + + public function delete(TaskImage $image): void + { + TaskImageModel::query()->whereKey($image->id())->delete(); + } + + private function toEntity(TaskImageModel $model): TaskImage + { + return TaskImage::reconstitute( + $model->id, + $model->task_id, + $model->user_id, + new StoredTaskImage($model->path, $model->thumbnail_path, $model->width, $model->height), + $model->original_name, + TaskImageCaption::fromNullable($model->caption), + DateTimeImmutable::createFromInterface($model->created_at), + ); + } +} diff --git a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php index 787bf1b..b58af59 100644 --- a/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php +++ b/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentTaskQueries.php @@ -152,6 +152,11 @@ class EloquentTaskQueries implements TaskQueries ->groupBy('task_id') ->selectRaw('task_id, count(*) as aggregate') ->pluck('aggregate', 'task_id'); + $imageCounts = DB::table('task_images') + ->whereIn('task_id', $models->pluck('id')->all()) + ->groupBy('task_id') + ->selectRaw('task_id, count(*) as aggregate') + ->pluck('aggregate', 'task_id'); $workTypeNames = []; foreach ($models->pluck('work_type_id')->unique() as $workTypeId) { @@ -176,6 +181,7 @@ class EloquentTaskQueries implements TaskQueries plannedFrom: $model->planned_from?->format('Y-m-d'), plannedTo: $model->planned_to?->format('Y-m-d'), commentCount: (int) ($commentCounts[$model->id] ?? 0), + imageCount: (int) ($imageCounts[$model->id] ?? 0), ))->values()->all(); } } diff --git a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php index a38fd62..6987546 100644 --- a/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php +++ b/app/Modules/Jobs/Infrastructure/Providers/JobsServiceProvider.php @@ -9,6 +9,8 @@ use App\Modules\Jobs\Application\Contracts\ChecklistQueries; use App\Modules\Jobs\Application\Contracts\CustomerJobQueries; use App\Modules\Jobs\Application\Contracts\TaskCalendarQueries; use App\Modules\Jobs\Application\Contracts\TaskCommentQueries; +use App\Modules\Jobs\Application\Contracts\TaskImageFiles; +use App\Modules\Jobs\Application\Contracts\TaskImageQueries; use App\Modules\Jobs\Application\Contracts\TaskQueries; use App\Modules\Jobs\Application\Contracts\TaskUsage; use App\Modules\Jobs\Domain\Contracts\ChecklistItemRepository; @@ -16,9 +18,11 @@ use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository; use App\Modules\Jobs\Domain\Contracts\JobNumberSequence; use App\Modules\Jobs\Domain\Contracts\TaskBookingRepository; use App\Modules\Jobs\Domain\Contracts\TaskCommentRepository; +use App\Modules\Jobs\Domain\Contracts\TaskImageRepository; use App\Modules\Jobs\Domain\Contracts\TaskRepository; use App\Modules\Jobs\Infrastructure\CustomerReferencesFromJobs; use App\Modules\Jobs\Infrastructure\CustomerRowUsageFromJobs; +use App\Modules\Jobs\Infrastructure\Files\GdTaskImageFiles; use App\Modules\Jobs\Infrastructure\NothingUsesTasks; use App\Modules\Jobs\Infrastructure\Persistence\DatabaseJobNumberSequence; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentChecklistItemRepository; @@ -29,6 +33,8 @@ use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskBooking use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskCalendarQueries; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskCommentQueries; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskCommentRepository; +use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskImageQueries; +use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskImageRepository; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskQueries; use App\Modules\Jobs\Infrastructure\Persistence\Repositories\EloquentTaskRepository; use App\Modules\Users\Domain\Enums\Role; @@ -58,6 +64,9 @@ class JobsServiceProvider extends ServiceProvider ChecklistQueries::class => EloquentChecklistQueries::class, TaskCommentRepository::class => EloquentTaskCommentRepository::class, TaskCommentQueries::class => EloquentTaskCommentQueries::class, + TaskImageRepository::class => EloquentTaskImageRepository::class, + TaskImageQueries::class => EloquentTaskImageQueries::class, + TaskImageFiles::class => GdTaskImageFiles::class, // Replaced by the TimeTracking module, which knows which tasks have time entries. TaskUsage::class => NothingUsesTasks::class, ]; @@ -106,6 +115,10 @@ class JobsServiceProvider extends ServiceProvider // their own comments, and admin and management may remove anyone's. Gate::define('jobs.remove-any-task-comment', $isManager); + // Images on tasks likewise: anyone who comments sends images, uploaders change captions and + // remove their own images, and admin and management may remove anyone's. + Gate::define('jobs.remove-any-task-image', $isManager); + // "Lasku luotu" and "Laskutettu" are set when invoicing: management or the job's biller. // The argument is the job's biller (user id), when known. Gate::define('jobs.set-billing-status', fn (User $user, ?int $billerUserId = null): bool => $isManager($user) diff --git a/app/Modules/Jobs/Presentation/Http/Controllers/ShowTaskImage.php b/app/Modules/Jobs/Presentation/Http/Controllers/ShowTaskImage.php new file mode 100644 index 0000000..c26e850 --- /dev/null +++ b/app/Modules/Jobs/Presentation/Http/Controllers/ShowTaskImage.php @@ -0,0 +1,32 @@ +fileOf($job, $task, $image, $size === 'thumbnail') ?? abort(404); + $disk = Storage::disk('local'); + + abort_unless($disk->exists($file->path), 404); + + $headers = ['Content-Type' => 'image/jpeg', 'Cache-Control' => 'private, max-age=86400']; + + return $request->boolean('download') + ? $disk->download($file->path, $file->downloadName, $headers) + : $disk->response($file->path, $file->downloadName, $headers); + } +} diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php index f1a7d08..12efc25 100644 --- a/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php +++ b/app/Modules/Jobs/Presentation/Livewire/⚡show.blade.php @@ -81,9 +81,10 @@ new class extends Component } /** - * A task's comments changed: the task cards show their number. + * A task's comments or images changed: the task cards show their number. */ #[On('task-comments-changed')] + #[On('task-images-changed')] public function refreshTasks(): void { unset($this->tasks); @@ -419,6 +420,12 @@ new class extends Component
{{ $task->commentCount }}
@endif + @if ($task->imageCount > 0) +
+
{{ __('jobs.tasks.images.title') }}:
+
{{ $task->imageCount }}
+
+ @endif @@ -456,6 +463,8 @@ new class extends Component + +
@if ($canChangeStatus)
diff --git a/app/Modules/Jobs/Presentation/Livewire/⚡task-images.blade.php b/app/Modules/Jobs/Presentation/Livewire/⚡task-images.blade.php new file mode 100644 index 0000000..f8bd4f7 --- /dev/null +++ b/app/Modules/Jobs/Presentation/Livewire/⚡task-images.blade.php @@ -0,0 +1,464 @@ +authorize('jobs.view-job', $jobId); + + $this->jobId = $jobId; + $this->taskId = $taskId; + $this->taskTitle = $taskTitle; + } + + /** + * @return list + */ + #[Computed] + public function images(): array + { + return app(TaskImageQueries::class)->imagesOf($this->jobId, $this->taskId); + } + + public function add(AddTaskImage $addImage): void + { + $this->authorize('jobs.update-task-status', $this->jobId); + $this->resetErrorBag(); + + $this->validate( + ['photo' => ['required', 'file', 'image', 'mimes:jpg,jpeg,png,webp,gif', 'max:'.self::MAX_KILOBYTES]], + [ + 'photo.required' => __('jobs.tasks.images.errors.photo_required'), + 'photo.file' => __('jobs.tasks.images.errors.not_image'), + 'photo.image' => __('jobs.tasks.images.errors.not_image'), + 'photo.mimes' => __('jobs.tasks.images.errors.not_image'), + 'photo.max' => __('jobs.tasks.images.errors.too_large', ['size' => self::MAX_KILOBYTES / 1024]), + ], + ); + + /** @var TemporaryUploadedFile $photo */ + $photo = $this->photo; + + try { + $addImage->execute($this->jobId, $this->taskId, (int) auth()->id(), (string) $photo->getRealPath(), $photo->getClientOriginalName(), $this->caption); + } catch (InvalidTaskImageCaption) { + $this->addError('caption', __('jobs.tasks.images.errors.invalid_caption')); + + return; + } catch (InvalidTaskImage) { + $this->addError('photo', __('jobs.tasks.images.errors.not_image')); + + return; + } catch (TaskNotFound) { + $this->notFound(); + + return; + } + + $photo->delete(); + $this->reset('photo', 'caption'); + $this->changed(__('jobs.tasks.images.added')); + } + + public function startEdit(int $imageId): void + { + $this->authorize('jobs.update-task-status', $this->jobId); + + $image = $this->image($imageId); + + if ($image === null) { + return; + } + + if (! $this->isOwn($image)) { + $this->message = __('jobs.tasks.images.errors.not_uploader'); + + return; + } + + $this->editingImageId = $image->id; + $this->editingCaption = $image->caption ?? ''; + $this->resetErrorBag(); + $this->js("document.getElementById('image-caption-edit-{$image->id}')?.focus()"); + } + + public function saveEdit(ChangeTaskImageCaption $changeCaption): void + { + $this->authorize('jobs.update-task-status', $this->jobId); + $this->resetErrorBag(); + + if ($this->editingImageId === null) { + return; + } + + try { + $changeCaption->execute($this->jobId, $this->taskId, $this->editingImageId, (int) auth()->id(), $this->editingCaption); + } catch (InvalidTaskImageCaption) { + $this->addError('editingCaption', __('jobs.tasks.images.errors.invalid_caption')); + + return; + } catch (NotTaskImageUploader) { + $this->cancelEdit(); + $this->message = __('jobs.tasks.images.errors.not_uploader'); + + return; + } catch (TaskNotFound|TaskImageNotFound) { + $this->reset('editingImageId', 'editingCaption'); + $this->notFound(); + + return; + } + + $this->cancelEdit(); + $this->changed(__('jobs.tasks.images.caption_saved')); + } + + public function cancelEdit(): void + { + $imageId = $this->editingImageId; + + $this->reset('editingImageId', 'editingCaption'); + $this->resetErrorBag(); + + if ($imageId !== null) { + $this->js("document.getElementById('image-edit-button-{$imageId}')?.focus()"); + } + } + + public function confirmRemoval(int $imageId): void + { + $this->authorize('jobs.update-task-status', $this->jobId); + + $image = $this->image($imageId); + + if ($image === null) { + return; + } + + if (! $this->mayRemove($image)) { + $this->message = __('jobs.tasks.images.errors.not_uploader'); + + return; + } + + $this->removalImageId = $image->id; + $this->js("document.getElementById('remove-image-dialog-{$this->taskId}').showModal()"); + } + + public function remove(RemoveTaskImage $removeImage): void + { + $this->authorize('jobs.update-task-status', $this->jobId); + + if ($this->removalImageId === null) { + return; + } + + $imageId = $this->removalImageId; + $this->reset('removalImageId'); + $this->js("document.getElementById('remove-image-dialog-{$this->taskId}').close()"); + + try { + $removeImage->execute($this->jobId, $this->taskId, $imageId, (int) auth()->id(), Gate::allows('jobs.remove-any-task-image')); + } catch (NotTaskImageUploader) { + $this->message = __('jobs.tasks.images.errors.not_uploader'); + + return; + } catch (TaskNotFound|TaskImageNotFound) { + $this->notFound(); + + return; + } + + if ($this->editingImageId === $imageId) { + $this->reset('editingImageId', 'editingCaption'); + } + + $this->changed(__('jobs.tasks.images.removed')); + + // The removed image's buttons are gone: move focus to the field for a new image. + $this->js("document.getElementById('image-new-{$this->taskId}')?.focus()"); + } + + public function isOwn(TaskImageSummary $image): bool + { + return $image->uploaderId !== null && $image->uploaderId === (int) auth()->id(); + } + + public function mayRemove(TaskImageSummary $image): bool + { + return $this->isOwn($image) || Gate::allows('jobs.remove-any-task-image'); + } + + /** + * "25.11.2026 klo 14.05" from "2026-11-25 14:05". + */ + public function formatTime(string $moment): string + { + $time = CarbonImmutable::createFromFormat('Y-m-d H:i', $moment); + + return __('jobs.tasks.comments.at', ['date' => $time->format('j.n.Y'), 'time' => $time->format('H.i')]); + } + + public function uploaderName(TaskImageSummary $image): string + { + return $image->uploaderName === '' ? __('jobs.tasks.comments.unknown_author') : $image->uploaderName; + } + + /** + * The caption, or which image it is, who sent it and when. + */ + public function altText(TaskImageSummary $image, int $number): string + { + return $image->caption ?? __('jobs.tasks.images.alt', [ + 'number' => $number, + 'uploader' => $this->uploaderName($image), + 'at' => $this->formatTime($image->uploadedAt), + ]); + } + + /** + * @return array{0: int, 1: int} + */ + public function thumbnailSize(TaskImageSummary $image): array + { + $ratio = min(1, 400 / max($image->width, $image->height, 1)); + + return [max(1, (int) round($image->width * $ratio)), max(1, (int) round($image->height * $ratio))]; + } + + private function image(int $imageId): ?TaskImageSummary + { + foreach ($this->images as $image) { + if ($image->id === $imageId) { + return $image; + } + } + + $this->notFound(); + + return null; + } + + /** + * Refreshes the list and tells the job page, whose task cards show the + * number of images. + */ + private function changed(string $message): void + { + unset($this->images); + $this->message = $message; + $this->dispatch('task-images-changed'); + } + + private function notFound(): void + { + $this->changed(__('jobs.tasks.images.not_found')); + } +}; +?> + +{{-- Named by the task, so the images of a job's tasks are distinguishable landmarks. --}} +
+ @php($canUpload = Gate::allows('jobs.update-task-status', $jobId)) + +

+ {{ __('jobs.tasks.images.title') }} + @if ($this->images !== []) + ({{ count($this->images) }}) + @endif +

+ +

+ {{ $message }} + {{ __('jobs.tasks.images.uploading') }} + {{ __('jobs.tasks.images.saving') }} +

+ + @if ($this->images === []) +

{{ __('jobs.tasks.images.empty') }}

+ @else +
    + @foreach ($this->images as $index => $image) + @php($alt = $this->altText($image, $index + 1)) + @php([$thumbWidth, $thumbHeight] = $this->thumbnailSize($image)) + @php($fullUrl = route('jobs.tasks.images.show', [$jobId, $taskId, $image->id, 'full'])) +
  • +
    + + {{ $alt }} + {{ __('jobs.tasks.images.opens_in_new_tab') }} + +
    + @if ($image->caption !== null) + {{ $image->caption }} + @endif + + {{ $this->uploaderName($image) }}, + +
    +
    + + @if ($editingImageId === $image->id) +
    + +
    + + +
    + + @else +
    + {{ __('jobs.tasks.images.download') }} + + @if ($canUpload && $this->isOwn($image)) + + @endif + @if ($canUpload && $this->mayRemove($image)) + + @endif +
    + @endif +
  • + @endforeach +
+ @endif + + @if ($canUpload) +
+
+ +

{{ __('jobs.tasks.images.hint', ['size' => $this::MAX_KILOBYTES / 1024]) }}

+ + @error('photo') +

{{ $message }}

+ @enderror +
+ +
+ +
+ + + + + +

{{ __('jobs.tasks.images.remove_question') }}

+ + + + +
+ @endif +
diff --git a/app/Modules/Jobs/Presentation/Routes/web.php b/app/Modules/Jobs/Presentation/Routes/web.php index ef34f47..74ec53a 100644 --- a/app/Modules/Jobs/Presentation/Routes/web.php +++ b/app/Modules/Jobs/Presentation/Routes/web.php @@ -1,5 +1,6 @@ whereNumber('job')->name('tasks.create'); Route::livewire('/{job}/tasks/from-template', 'jobs::tasks-from-template')->whereNumber('job')->name('tasks.from-template'); Route::livewire('/{job}/tasks/{task}/edit', 'jobs::task-form')->whereNumber(['job', 'task'])->name('tasks.edit'); + Route::get('/{job}/tasks/{task}/images/{image}/{size}', ShowTaskImage::class) + ->whereNumber(['job', 'task', 'image']) + ->whereIn('size', ['full', 'thumbnail']) + ->name('tasks.images.show'); }); diff --git a/config/livewire.php b/config/livewire.php new file mode 100644 index 0000000..1f586b3 --- /dev/null +++ b/config/livewire.php @@ -0,0 +1,284 @@ + [ + resource_path('views/components'), + resource_path('views/livewire'), + ], + + /* + |--------------------------------------------------------------------------- + | Component Namespaces + |--------------------------------------------------------------------------- + | + | This value sets default namespaces that will be used to resolve view-based + | components like single-file and multi-file components. These folders'll + | also be referenced when creating new components via the make command. + | + */ + + 'component_namespaces' => [ + 'layouts' => resource_path('views/layouts'), + 'pages' => resource_path('views/pages'), + ], + + /* + |--------------------------------------------------------------------------- + | Page Layout + |--------------------------------------------------------------------------- + | The view that will be used as the layout when rendering a single component as + | an entire page via `Route::livewire('/post/create', 'pages::create-post')`. + | In this case, the content of pages::create-post will render into $slot. + | + */ + + 'component_layout' => 'layouts::app', + + /* + |--------------------------------------------------------------------------- + | Lazy Loading Placeholder + |--------------------------------------------------------------------------- + | Livewire allows you to lazy load components that would otherwise slow down + | the initial page load. Every component can have a custom placeholder or + | you can define the default placeholder view for all components below. + | + */ + + 'component_placeholder' => null, // Example: 'placeholders::skeleton' + + /* + |--------------------------------------------------------------------------- + | Make Command + |--------------------------------------------------------------------------- + | This value determines the default configuration for the artisan make command + | You can configure the component type (sfc, mfc, class) and whether to use + | the high-voltage (⚡) emoji as a prefix in the sfc|mfc component names. + | + */ + + 'make_command' => [ + 'type' => 'sfc', // Options: 'sfc', 'mfc', 'class' + 'emoji' => true, // Options: true, false + 'with' => [ + 'js' => false, + 'css' => false, + 'test' => false, + ], + ], + + /* + |--------------------------------------------------------------------------- + | Class Namespace + |--------------------------------------------------------------------------- + | + | This value sets the root class namespace for Livewire component classes in + | your application. This value will change where component auto-discovery + | finds components. It's also referenced by the file creation commands. + | + */ + + 'class_namespace' => 'App\\Livewire', + + /* + |--------------------------------------------------------------------------- + | Class Path + |--------------------------------------------------------------------------- + | + | This value is used to specify the path where Livewire component class files + | are created when running creation commands like `artisan make:livewire`. + | This path is customizable to match your projects directory structure. + | + */ + + 'class_path' => app_path('Livewire'), + + /* + |--------------------------------------------------------------------------- + | View Path + |--------------------------------------------------------------------------- + | + | This value is used to specify where Livewire component Blade templates are + | stored when running file creation commands like `artisan make:livewire`. + | It is also used if you choose to omit a component's render() method. + | + */ + + 'view_path' => resource_path('views/livewire'), + + /* + |--------------------------------------------------------------------------- + | Temporary File Uploads + |--------------------------------------------------------------------------- + | + | Livewire handles file uploads by storing uploads in a temporary directory + | before the file is stored permanently. All file uploads are directed to + | a global endpoint for temporary storage. You may configure this below: + | + */ + + 'temporary_file_upload' => [ + 'disk' => env('LIVEWIRE_TEMPORARY_FILE_UPLOAD_DISK'), // Example: 'local', 's3' | Default: 'default' + // Up to PHP's upload_max_filesize (40 MB), so that the page's own, smaller limits + // (e.g. 12 MB for task images) give their translated messages. + 'rules' => ['required', 'file', 'max:40960'], + 'directory' => null, // Example: 'tmp' | Default: 'livewire-tmp' + 'middleware' => null, // Example: 'throttle:5,1' | Default: 'throttle:60,1' + 'preview_mimes' => [ // Supported file types for temporary pre-signed file URLs... + 'png', 'gif', 'bmp', 'svg', 'wav', 'mp4', + 'mov', 'avi', 'wmv', 'mp3', 'm4a', + 'jpg', 'jpeg', 'mpga', 'webp', 'wma', + ], + 'max_upload_time' => 5, // Max duration (in minutes) before an upload is invalidated... + 'cleanup' => true, // Should cleanup temporary uploads older than 24 hrs... + ], + + /* + |--------------------------------------------------------------------------- + | Render On Redirect + |--------------------------------------------------------------------------- + | + | This value determines if Livewire will run a component's `render()` method + | after a redirect has been triggered using something like `redirect(...)` + | Setting this to true will render the view once more before redirecting + | + */ + + 'render_on_redirect' => false, + + /* + |--------------------------------------------------------------------------- + | Eloquent Model Binding + |--------------------------------------------------------------------------- + | + | Previous versions of Livewire supported binding directly to eloquent model + | properties using wire:model by default. However, this behavior has been + | deemed too "magical" and has therefore been put under a feature flag. + | + */ + + 'legacy_model_binding' => false, + + /* + |--------------------------------------------------------------------------- + | Auto-inject Frontend Assets + |--------------------------------------------------------------------------- + | + | By default, Livewire automatically injects its JavaScript and CSS into the + | and of pages containing Livewire components. By disabling + | this behavior, you need to use @livewireStyles and @livewireScripts. + | + */ + + 'inject_assets' => true, + + /* + |--------------------------------------------------------------------------- + | Navigate (SPA mode) + |--------------------------------------------------------------------------- + | + | By adding `wire:navigate` to links in your Livewire application, Livewire + | will prevent the default link handling and instead request those pages + | via AJAX, creating an SPA-like effect. Configure this behavior here. + | + */ + + 'navigate' => [ + 'show_progress_bar' => true, + 'progress_bar_color' => '#2299dd', + ], + + /* + |--------------------------------------------------------------------------- + | HTML Morph Markers + |--------------------------------------------------------------------------- + | + | Livewire intelligently "morphs" existing HTML into the newly rendered HTML + | after each update. To make this process more reliable, Livewire injects + | "markers" into the rendered Blade surrounding @if, @class & @foreach. + | + */ + + 'inject_morph_markers' => true, + + /* + |--------------------------------------------------------------------------- + | Smart Wire Keys + |--------------------------------------------------------------------------- + | + | Livewire uses loops and keys used within loops to generate smart keys that + | are applied to nested components that don't have them. This makes using + | nested components more reliable by ensuring that they all have keys. + | + */ + + 'smart_wire_keys' => true, + + /* + |--------------------------------------------------------------------------- + | Pagination Theme + |--------------------------------------------------------------------------- + | + | When enabling Livewire's pagination feature by using the `WithPagination` + | trait, Livewire will use Tailwind templates to render pagination views + | on the page. If you want Bootstrap CSS, you can specify: "bootstrap" + | + */ + + 'pagination_theme' => 'tailwind', + + /* + |--------------------------------------------------------------------------- + | Release Token + |--------------------------------------------------------------------------- + | + | This token is stored client-side and sent along with each request to check + | a users session to see if a new release has invalidated it. If there is + | a mismatch it will throw an error and prompt for a browser refresh. + | + */ + + 'release_token' => 'a', + + /* + |--------------------------------------------------------------------------- + | CSP Safe + |--------------------------------------------------------------------------- + | + | This config is used to determine if Livewire will use the CSP-safe version + | of Alpine in its bundle. This is useful for applications that are using + | strict Content Security Policy (CSP) to protect against XSS attacks. + | + */ + + 'csp_safe' => false, + + /* + |--------------------------------------------------------------------------- + | Payload Guards + |--------------------------------------------------------------------------- + | + | These settings protect against malicious or oversized payloads that could + | cause denial of service. The default values should feel reasonable for + | most web applications. Each can be set to null to disable the limit. + | + */ + + 'payload' => [ + 'max_size' => 1024 * 1024, // 1MB - maximum request payload size in bytes + 'max_nesting_depth' => 10, // Maximum depth of dot-notation property paths + 'max_calls' => 50, // Maximum method calls per request + 'max_components' => 200, // Maximum components per batch request + ], +]; diff --git a/database/migrations/2026_11_25_053801_create_task_images_table.php b/database/migrations/2026_11_25_053801_create_task_images_table.php new file mode 100644 index 0000000..0990777 --- /dev/null +++ b/database/migrations/2026_11_25_053801_create_task_images_table.php @@ -0,0 +1,39 @@ +id(); + $table->foreignId('task_id')->constrained()->cascadeOnDelete(); + $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete(); + $table->string('path'); + $table->string('thumbnail_path'); + $table->string('original_name'); + $table->string('caption')->nullable(); + $table->unsignedInteger('width'); + $table->unsignedInteger('height'); + $table->timestamps(); + + $table->index(['task_id', 'id']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('task_images'); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index 9d85068..35ead70 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -371,7 +371,7 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up - `task_members`: `task_id`, `user_id` (tehtävän jäsenet; tekijä on `tasks.assignee_user_id`) *(olemassa)* - `task_checklist_items` *(V3)*: `task_id`, `text`, `is_done`, `sort_order` - `task_comments` *(V3, olemassa)*: `task_id`, `user_id`, `body`, `edited_at` (kirjoittaja muokkaa ja poistaa omiaan, pääkäyttäjä ja johto poistavat kenen tahansa) -- `task_images` *(V3)*: `task_id`, `user_id`, `path`, `original_name` +- `task_images` *(V3, olemassa)*: `task_id`, `user_id`, `path`, `thumbnail_path`, `original_name`, `caption`, `width`, `height` (palvelin tallentaa enintään 2560 px JPEG-kopion ilman EXIF-tietoja ja 400 px pikkukuvan yksityiselle levylle; lähettäjä muokkaa kuvatekstiä ja poistaa omansa, pääkäyttäjä ja johto poistavat kenen tahansa) **TimeTracking** - `time_entries`: `user_id`, `task_id`, `customer_job_id` (denormalisoitu), `work_type_id` (tehtävän työtehtävä kirjaushetkellä), `worked_on`, `hours`, `note` *(olemassa; uniikki käyttäjä + tehtävä + päivä)*, `approved_at`, `approved_by`, `billing_export_id` (laskuaineisto, jolla tunnit laskutettiin) *(V2, olemassa)* @@ -409,7 +409,7 @@ Tunnit kirjataan tehtäville, joten perustehtävät ja palveluyksiköiden työte Hinnasto ja tuotteet, rahakentät ja henkilökohtaiset näkyvyysoikeudet, kulut, tuntien hyväksyntä ja lukitus, laskuaineiston vienti Fennoaan (CSV/Excel), kuukausilaskutusrivit, pikamyynti. **Vaihe 3 – tehtävien hallinta** -Tarkistuslistat *(valmis)*, kommentit *(valmis)*, kuvat, työnkulkupohjat *(valmis)*, tehtäväkalenteri henkilöittäin ja arkipyhät *(valmis; korvaa tehtävien Kanban-sarakkeet, K34)*, kenttien yksinkertaistus palveluyksiköittäin. +Tarkistuslistat *(valmis)*, kommentit *(valmis)*, kuvat *(valmis)*, työnkulkupohjat *(valmis)*, tehtäväkalenteri henkilöittäin ja arkipyhät *(valmis; korvaa tehtävien Kanban-sarakkeet, K34)*, kenttien yksinkertaistus palveluyksiköittäin. **Vaihe 4 – laajennukset** Alihankkijoiden näkymät ja rajaukset, raportit, ilmoitukset, Fennoa-rajapinta, PWA. diff --git a/lang/en/jobs.php b/lang/en/jobs.php index 0a5d75c..bf4491e 100644 --- a/lang/en/jobs.php +++ b/lang/en/jobs.php @@ -147,6 +147,42 @@ return [ 'not_author' => 'You can edit and remove only your own comments.', ], ], + 'images' => [ + 'title' => 'Images', + 'list_of' => 'Images: :title', + 'empty' => 'No images.', + 'new' => 'Send an image', + 'hint' => 'JPEG, PNG, WebP or GIF, at most :size MB. On a phone you can take a photo with the camera.', + 'caption' => 'Caption', + 'caption_optional' => 'Caption (optional)', + 'add' => 'Send image', + 'add_named' => 'Send image to task :title', + 'uploading' => 'Uploading the image…', + 'saving' => 'Saving the image…', + 'alt' => 'Image :number, sent by :uploader :at', + 'opens_in_new_tab' => '(opens in a new tab)', + 'download' => 'Download', + 'download_named' => 'Download image: :image', + 'edit_caption' => 'Edit caption', + 'edit_caption_named' => 'Edit caption: :image', + 'save' => 'Save', + 'cancel' => 'Cancel', + 'remove' => 'Remove', + 'remove_named' => 'Remove image: :image', + 'remove_title' => 'Remove the image?', + 'remove_question' => 'The image will be removed permanently.', + 'added' => 'Image sent.', + 'caption_saved' => 'Caption saved.', + 'removed' => 'Image removed.', + 'not_found' => 'The image was not found. Refresh the page.', + 'errors' => [ + 'photo_required' => 'Choose an image.', + 'not_image' => 'The file is not an image. Choose a JPEG, PNG, WebP or GIF image.', + 'too_large' => 'An image may be at most :size MB.', + 'invalid_caption' => 'A caption may be at most 255 characters.', + 'not_uploader' => 'You can edit and remove only images you sent.', + ], + ], 'errors' => [ 'title_required' => 'Enter the task name.', 'invalid_title' => 'The name may be at most 255 characters.', diff --git a/lang/fi/jobs.php b/lang/fi/jobs.php index 298d910..8b63105 100644 --- a/lang/fi/jobs.php +++ b/lang/fi/jobs.php @@ -147,6 +147,42 @@ return [ 'not_author' => 'Voit muokata ja poistaa vain omia kommenttejasi.', ], ], + 'images' => [ + 'title' => 'Kuvat', + 'list_of' => 'Kuvat: :title', + 'empty' => 'Ei kuvia.', + 'new' => 'Lähetä kuva', + 'hint' => 'JPEG, PNG, WebP tai GIF, enintään :size Mt. Puhelimessa voit ottaa kuvan kameralla.', + 'caption' => 'Kuvateksti', + 'caption_optional' => 'Kuvateksti (vapaaehtoinen)', + 'add' => 'Lähetä kuva', + 'add_named' => 'Lähetä kuva tehtävälle :title', + 'uploading' => 'Ladataan kuvaa…', + 'saving' => 'Tallennetaan kuvaa…', + 'alt' => 'Kuva :number, lähettänyt :uploader :at', + 'opens_in_new_tab' => '(avautuu uuteen välilehteen)', + 'download' => 'Lataa', + 'download_named' => 'Lataa kuva: :image', + 'edit_caption' => 'Muokkaa kuvatekstiä', + 'edit_caption_named' => 'Muokkaa kuvatekstiä: :image', + 'save' => 'Tallenna', + 'cancel' => 'Peruuta', + 'remove' => 'Poista', + 'remove_named' => 'Poista kuva: :image', + 'remove_title' => 'Poistetaanko kuva?', + 'remove_question' => 'Kuva poistetaan pysyvästi.', + 'added' => 'Kuva lähetetty.', + 'caption_saved' => 'Kuvateksti tallennettu.', + 'removed' => 'Kuva poistettu.', + 'not_found' => 'Kuvaa ei löytynyt. Päivitä sivu.', + 'errors' => [ + 'photo_required' => 'Valitse kuva.', + 'not_image' => 'Tiedosto ei ole kuva. Valitse JPEG-, PNG-, WebP- tai GIF-kuva.', + 'too_large' => 'Kuva voi olla enintään :size Mt.', + 'invalid_caption' => 'Kuvateksti voi olla enintään 255 merkkiä.', + 'not_uploader' => 'Voit muokata ja poistaa vain itse lähettämiäsi kuvia.', + ], + ], 'errors' => [ 'title_required' => 'Anna tehtävän nimi.', 'invalid_title' => 'Nimen pituus voi olla enintään 255 merkkiä.', diff --git a/tests/Browser/JobsAccessibilityTest.php b/tests/Browser/JobsAccessibilityTest.php index ae4c4c7..31f0c58 100644 --- a/tests/Browser/JobsAccessibilityTest.php +++ b/tests/Browser/JobsAccessibilityTest.php @@ -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(); diff --git a/tests/Fakes/FakeTaskImageFiles.php b/tests/Fakes/FakeTaskImageFiles.php new file mode 100644 index 0000000..b204457 --- /dev/null +++ b/tests/Fakes/FakeTaskImageFiles.php @@ -0,0 +1,38 @@ + */ + 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]); + } + } +} diff --git a/tests/Fakes/InMemoryTaskImageRepository.php b/tests/Fakes/InMemoryTaskImageRepository.php new file mode 100644 index 0000000..4e75e19 --- /dev/null +++ b/tests/Fakes/InMemoryTaskImageRepository.php @@ -0,0 +1,53 @@ + */ + 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()]); + } +} diff --git a/tests/Feature/Modules/Jobs/TaskImagesTest.php b/tests/Feature/Modules/Jobs/TaskImagesTest.php new file mode 100644 index 0000000..5de1770 --- /dev/null +++ b/tests/Feature/Modules/Jobs/TaskImagesTest.php @@ -0,0 +1,182 @@ +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([]); +}); diff --git a/tests/Unit/Modules/Jobs/Application/TaskImageUseCasesTest.php b/tests/Unit/Modules/Jobs/Application/TaskImageUseCasesTest.php new file mode 100644 index 0000000..06eff3b --- /dev/null +++ b/tests/Unit/Modules/Jobs/Application/TaskImageUseCasesTest.php @@ -0,0 +1,103 @@ +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([]); +}); diff --git a/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php b/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php index 00b7c30..5464c70 100644 --- a/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php +++ b/tests/Unit/Modules/Jobs/Application/TaskUseCasesTest.php @@ -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'))); });