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:
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Application\Contracts;
|
||||
|
||||
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskImage;
|
||||
use App\Modules\Jobs\Domain\ValueObjects\StoredTaskImage;
|
||||
|
||||
/**
|
||||
* Keeps the files of task images: a downscaled, upright JPEG without
|
||||
* metadata (no location) and its thumbnail.
|
||||
*/
|
||||
interface TaskImageFiles
|
||||
{
|
||||
/**
|
||||
* Stores the image read from the uploaded file.
|
||||
*
|
||||
* @throws InvalidTaskImage
|
||||
*/
|
||||
public function store(string $uploadedFilePath, int $taskId): StoredTaskImage;
|
||||
|
||||
/**
|
||||
* Removes the files; missing files are ignored.
|
||||
*
|
||||
* @param list<string> $paths
|
||||
*/
|
||||
public function delete(array $paths): void;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Application\Contracts;
|
||||
|
||||
use App\Modules\Jobs\Application\DTOs\TaskImageFile;
|
||||
use App\Modules\Jobs\Application\DTOs\TaskImageSummary;
|
||||
|
||||
interface TaskImageQueries
|
||||
{
|
||||
/**
|
||||
* The task's images, oldest first; empty when the task belongs to
|
||||
* another job.
|
||||
*
|
||||
* @return list<TaskImageSummary>
|
||||
*/
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Application\DTOs;
|
||||
|
||||
/**
|
||||
* The stored file of a task image and the name it is downloaded with.
|
||||
*/
|
||||
final readonly class TaskImageFile
|
||||
{
|
||||
public function __construct(
|
||||
public string $path,
|
||||
public string $downloadName,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Application\DTOs;
|
||||
|
||||
/**
|
||||
* A task image with its uploader's name, without file paths. The time is
|
||||
* in the business time zone as "Y-m-d H:i".
|
||||
*/
|
||||
final readonly class TaskImageSummary
|
||||
{
|
||||
public function __construct(
|
||||
public int $id,
|
||||
public ?int $uploaderId,
|
||||
public string $uploaderName,
|
||||
public ?string $caption,
|
||||
public string $originalName,
|
||||
public string $uploadedAt,
|
||||
public int $width,
|
||||
public int $height,
|
||||
) {}
|
||||
}
|
||||
@@ -28,5 +28,6 @@ final readonly class TaskSummary
|
||||
public ?string $plannedFrom = null,
|
||||
public ?string $plannedTo = null,
|
||||
public int $commentCount = 0,
|
||||
public int $imageCount = 0,
|
||||
) {}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Application\Services;
|
||||
|
||||
use App\Modules\Jobs\Domain\Contracts\TaskImageRepository;
|
||||
use App\Modules\Jobs\Domain\Contracts\TaskRepository;
|
||||
use App\Modules\Jobs\Domain\Entities\TaskImage;
|
||||
use App\Modules\Jobs\Domain\Exceptions\TaskImageNotFound;
|
||||
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
|
||||
|
||||
/**
|
||||
* Finds an image only through its task and the task's job, so a page of
|
||||
* one job never changes another job's images.
|
||||
*/
|
||||
final readonly class TaskImageFinder
|
||||
{
|
||||
public function __construct(
|
||||
private TaskRepository $tasks,
|
||||
private TaskImageRepository $images,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws TaskNotFound
|
||||
* @throws TaskImageNotFound
|
||||
*/
|
||||
public function find(int $jobId, int $taskId, int $imageId): TaskImage
|
||||
{
|
||||
$this->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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Application\UseCases;
|
||||
|
||||
use App\Modules\Jobs\Application\Contracts\TaskImageFiles;
|
||||
use App\Modules\Jobs\Application\Services\TaskImageFinder;
|
||||
use App\Modules\Jobs\Domain\Contracts\TaskImageRepository;
|
||||
use App\Modules\Jobs\Domain\Entities\TaskImage;
|
||||
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskImage;
|
||||
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskImageCaption;
|
||||
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
|
||||
use App\Modules\Jobs\Domain\ValueObjects\TaskImageCaption;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Sends an image to a task: its files are stored first and removed again
|
||||
* if the image cannot be saved.
|
||||
*/
|
||||
final class AddTaskImage
|
||||
{
|
||||
public function __construct(
|
||||
private TaskImageFinder $finder,
|
||||
private TaskImageRepository $images,
|
||||
private TaskImageFiles $files,
|
||||
private TransactionManager $transactions,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return int The new image's id.
|
||||
*
|
||||
* @throws TaskNotFound
|
||||
* @throws InvalidTaskImage
|
||||
* @throws InvalidTaskImageCaption
|
||||
*/
|
||||
public function execute(int $jobId, int $taskId, int $userId, string $uploadedFilePath, string $originalName, ?string $caption): int
|
||||
{
|
||||
$caption = TaskImageCaption::fromNullable($caption);
|
||||
$this->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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Application\UseCases;
|
||||
|
||||
use App\Modules\Jobs\Application\Services\TaskImageFinder;
|
||||
use App\Modules\Jobs\Domain\Contracts\TaskImageRepository;
|
||||
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\Shared\Application\Contracts\TransactionManager;
|
||||
|
||||
/**
|
||||
* Changes or clears the caption of the user's own image.
|
||||
*/
|
||||
final class ChangeTaskImageCaption
|
||||
{
|
||||
public function __construct(
|
||||
private TaskImageFinder $finder,
|
||||
private TaskImageRepository $images,
|
||||
private TransactionManager $transactions,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws TaskNotFound
|
||||
* @throws TaskImageNotFound
|
||||
* @throws NotTaskImageUploader
|
||||
* @throws InvalidTaskImageCaption
|
||||
*/
|
||||
public function execute(int $jobId, int $taskId, int $imageId, int $userId, ?string $caption): void
|
||||
{
|
||||
$caption = TaskImageCaption::fromNullable($caption);
|
||||
|
||||
$this->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);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Application\UseCases;
|
||||
|
||||
use App\Modules\Jobs\Application\Contracts\TaskImageFiles;
|
||||
use App\Modules\Jobs\Application\Services\TaskImageFinder;
|
||||
use App\Modules\Jobs\Domain\Contracts\TaskImageRepository;
|
||||
use App\Modules\Jobs\Domain\Exceptions\NotTaskImageUploader;
|
||||
use App\Modules\Jobs\Domain\Exceptions\TaskImageNotFound;
|
||||
use App\Modules\Jobs\Domain\Exceptions\TaskNotFound;
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
|
||||
/**
|
||||
* Removes the user's own image, or anyone's when the user may remove
|
||||
* others' images (admin and management), and then its files.
|
||||
*/
|
||||
final class RemoveTaskImage
|
||||
{
|
||||
public function __construct(
|
||||
private TaskImageFinder $finder,
|
||||
private TaskImageRepository $images,
|
||||
private TaskImageFiles $files,
|
||||
private TransactionManager $transactions,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws TaskNotFound
|
||||
* @throws TaskImageNotFound
|
||||
* @throws NotTaskImageUploader
|
||||
*/
|
||||
public function execute(int $jobId, int $taskId, int $imageId, int $userId, bool $mayRemoveOthers): void
|
||||
{
|
||||
$paths = $this->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Domain\Contracts;
|
||||
|
||||
use App\Modules\Jobs\Domain\Entities\TaskImage;
|
||||
|
||||
interface TaskImageRepository
|
||||
{
|
||||
/**
|
||||
* Null when the image does not exist or belongs to another task.
|
||||
*/
|
||||
public function findForTask(int $taskId, int $imageId): ?TaskImage;
|
||||
|
||||
/**
|
||||
* The files of all the task's images, for removing them with the task.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function filePathsOfTask(int $taskId): array;
|
||||
|
||||
public function save(TaskImage $image): TaskImage;
|
||||
|
||||
public function delete(TaskImage $image): void;
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Domain\Entities;
|
||||
|
||||
use App\Modules\Jobs\Domain\Exceptions\NotTaskImageUploader;
|
||||
use App\Modules\Jobs\Domain\ValueObjects\StoredTaskImage;
|
||||
use App\Modules\Jobs\Domain\ValueObjects\TaskImageCaption;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* An image sent to a task. Its uploader may change the caption and remove
|
||||
* it; others may only remove it, and only when allowed to remove anyone's
|
||||
* images.
|
||||
*/
|
||||
final class TaskImage
|
||||
{
|
||||
private function __construct(
|
||||
private ?int $id,
|
||||
private int $taskId,
|
||||
private ?int $uploaderId,
|
||||
private StoredTaskImage $file,
|
||||
private string $originalName,
|
||||
private ?TaskImageCaption $caption,
|
||||
private DateTimeImmutable $uploadedAt,
|
||||
) {}
|
||||
|
||||
public static function create(int $taskId, int $uploaderId, StoredTaskImage $file, string $originalName, ?TaskImageCaption $caption, DateTimeImmutable $at): self
|
||||
{
|
||||
$originalName = trim($originalName);
|
||||
|
||||
return new self(null, $taskId, $uploaderId, $file, mb_substr($originalName === '' ? 'kuva.jpg' : $originalName, 0, 255), $caption, $at);
|
||||
}
|
||||
|
||||
/**
|
||||
* The uploader is null when the user no longer exists.
|
||||
*/
|
||||
public static function reconstitute(int $id, int $taskId, ?int $uploaderId, StoredTaskImage $file, string $originalName, ?TaskImageCaption $caption, DateTimeImmutable $uploadedAt): self
|
||||
{
|
||||
return new self($id, $taskId, $uploaderId, $file, $originalName, $caption, $uploadedAt);
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws NotTaskImageUploader
|
||||
*/
|
||||
public function changeCaption(int $userId, ?TaskImageCaption $caption): void
|
||||
{
|
||||
$this->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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
/**
|
||||
* The uploaded file could not be read as an image.
|
||||
*/
|
||||
final class InvalidTaskImage extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The uploaded file is not a readable image.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InvalidTaskImageCaption extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('An image caption may be at most 255 characters.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
/**
|
||||
* Only the uploader changes an image's caption; others than the uploader
|
||||
* may remove it only when they may remove anyone's images.
|
||||
*/
|
||||
final class NotTaskImageUploader extends DomainException
|
||||
{
|
||||
public function __construct(public readonly int $imageId, public readonly int $userId)
|
||||
{
|
||||
parent::__construct("User {$userId} did not upload image {$imageId}.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
/**
|
||||
* The image does not exist or belongs to another task or job.
|
||||
*/
|
||||
final class TaskImageNotFound extends DomainException
|
||||
{
|
||||
public function __construct(public readonly int $taskId, public readonly int $imageId)
|
||||
{
|
||||
parent::__construct("Image {$imageId} of task {$taskId} was not found.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Domain\ValueObjects;
|
||||
|
||||
/**
|
||||
* Where a task image's files are kept and the size of the full image.
|
||||
*/
|
||||
final readonly class StoredTaskImage
|
||||
{
|
||||
public function __construct(
|
||||
public string $path,
|
||||
public string $thumbnailPath,
|
||||
public int $width,
|
||||
public int $height,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function paths(): array
|
||||
{
|
||||
return [$this->path, $this->thumbnailPath];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Jobs\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskImageCaption;
|
||||
|
||||
/**
|
||||
* The optional caption of a task image, also its alternative text.
|
||||
*/
|
||||
final readonly class TaskImageCaption
|
||||
{
|
||||
public const int MAX_LENGTH = 255;
|
||||
|
||||
private function __construct(public string $value) {}
|
||||
|
||||
/**
|
||||
* Null for an empty caption.
|
||||
*
|
||||
* @throws InvalidTaskImageCaption
|
||||
*/
|
||||
public static function fromNullable(?string $value): ?self
|
||||
{
|
||||
$value = trim(preg_replace('/\s+/u', ' ', (string) $value) ?? (string) $value);
|
||||
|
||||
if ($value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (mb_strlen($value) > self::MAX_LENGTH) {
|
||||
throw new InvalidTaskImageCaption;
|
||||
}
|
||||
|
||||
return new self($value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Jobs\Infrastructure\Files;
|
||||
|
||||
use App\Modules\Jobs\Application\Contracts\TaskImageFiles;
|
||||
use App\Modules\Jobs\Domain\Exceptions\InvalidTaskImage;
|
||||
use App\Modules\Jobs\Domain\ValueObjects\StoredTaskImage;
|
||||
use GdImage;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Task image files on the private local disk, made with GD: the image is
|
||||
* turned upright by its EXIF orientation, scaled down and saved again as a
|
||||
* JPEG, which leaves out all metadata (such as the location) and anything
|
||||
* else embedded in the upload.
|
||||
*/
|
||||
class GdTaskImageFiles implements TaskImageFiles
|
||||
{
|
||||
public const string DISK = 'local';
|
||||
|
||||
public const int MAX_SIZE = 2560;
|
||||
|
||||
public const int THUMBNAIL_SIZE = 400;
|
||||
|
||||
/**
|
||||
* Larger images would not fit in memory when decoded.
|
||||
*/
|
||||
private const int MAX_PIXELS = 50_000_000;
|
||||
|
||||
private const int QUALITY = 82;
|
||||
|
||||
public function store(string $uploadedFilePath, int $taskId): StoredTaskImage
|
||||
{
|
||||
$image = $this->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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Jobs\Infrastructure\Persistence\Eloquent;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Table;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Persistence model of a task image, used only inside the Jobs
|
||||
* Infrastructure layer.
|
||||
*
|
||||
* @property int $id
|
||||
* @property int $task_id
|
||||
* @property int|null $user_id
|
||||
* @property string $path
|
||||
* @property string $thumbnail_path
|
||||
* @property string $original_name
|
||||
* @property string|null $caption
|
||||
* @property int $width
|
||||
* @property int $height
|
||||
* @property CarbonImmutable $created_at
|
||||
*/
|
||||
#[Table('task_images')]
|
||||
#[Fillable(['task_id', 'user_id', 'path', 'thumbnail_path', 'original_name', 'caption', 'width', 'height', 'created_at'])]
|
||||
class TaskImageModel extends Model
|
||||
{
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'task_id' => 'integer',
|
||||
'user_id' => 'integer',
|
||||
'width' => 'integer',
|
||||
'height' => 'integer',
|
||||
'created_at' => 'immutable_datetime',
|
||||
'updated_at' => 'immutable_datetime',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Jobs\Application\Contracts\TaskImageQueries;
|
||||
use App\Modules\Jobs\Application\DTOs\TaskImageFile;
|
||||
use App\Modules\Jobs\Application\DTOs\TaskImageSummary;
|
||||
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskImageModel;
|
||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class EloquentTaskImageQueries implements TaskImageQueries
|
||||
{
|
||||
public function __construct(private UserAccountQueries $users) {}
|
||||
|
||||
public function imagesOf(int $jobId, int $taskId): array
|
||||
{
|
||||
$models = $this->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<TaskImageModel>
|
||||
*/
|
||||
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));
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Modules\Jobs\Domain\Contracts\TaskImageRepository;
|
||||
use App\Modules\Jobs\Domain\Entities\TaskImage;
|
||||
use App\Modules\Jobs\Domain\ValueObjects\StoredTaskImage;
|
||||
use App\Modules\Jobs\Domain\ValueObjects\TaskImageCaption;
|
||||
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\TaskImageModel;
|
||||
use DateTimeImmutable;
|
||||
|
||||
class EloquentTaskImageRepository implements TaskImageRepository
|
||||
{
|
||||
public function findForTask(int $taskId, int $imageId): ?TaskImage
|
||||
{
|
||||
$model = TaskImageModel::query()->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),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Jobs\Presentation\Http\Controllers;
|
||||
|
||||
use App\Modules\Jobs\Application\Contracts\TaskImageQueries;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* A task image or its thumbnail from the private disk, to those who see the
|
||||
* job; with ?download=1 it is saved as a file under its original name.
|
||||
*/
|
||||
class ShowTaskImage
|
||||
{
|
||||
public function __invoke(Request $request, int $job, int $task, int $image, string $size, TaskImageQueries $images): Response
|
||||
{
|
||||
Gate::authorize('jobs.view-job', $job);
|
||||
|
||||
$file = $images->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);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
<dd>{{ $task->commentCount }}</dd>
|
||||
</div>
|
||||
@endif
|
||||
@if ($task->imageCount > 0)
|
||||
<div class="flex flex-wrap gap-x-1">
|
||||
<dt class="font-medium">{{ __('jobs.tasks.images.title') }}:</dt>
|
||||
<dd>{{ $task->imageCount }}</dd>
|
||||
</div>
|
||||
@endif
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
@@ -456,6 +463,8 @@ new class extends Component
|
||||
|
||||
<livewire:jobs::task-comments :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'comments-'.$task->id" />
|
||||
|
||||
<livewire:jobs::task-images :job-id="$job->id" :task-id="$task->id" :task-title="$task->title" :wire:key="'images-'.$task->id" />
|
||||
|
||||
<div class="flex flex-wrap items-end gap-3">
|
||||
@if ($canChangeStatus)
|
||||
<div class="w-full sm:w-56">
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Jobs\Application\Contracts\TaskImageQueries;
|
||||
use App\Modules\Jobs\Application\DTOs\TaskImageSummary;
|
||||
use App\Modules\Jobs\Application\UseCases\AddTaskImage;
|
||||
use App\Modules\Jobs\Application\UseCases\ChangeTaskImageCaption;
|
||||
use App\Modules\Jobs\Application\UseCases\RemoveTaskImage;
|
||||
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 Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
|
||||
use Livewire\WithFileUploads;
|
||||
|
||||
/**
|
||||
* A task's images on the job page (spec 8.2, K26), e.g. photos taken with
|
||||
* a phone: everyone who may comment on the task sends images; uploaders
|
||||
* change their captions and remove them, admin and management remove
|
||||
* anyone's. The server stores a downscaled copy without metadata.
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
use WithFileUploads;
|
||||
|
||||
/**
|
||||
* The largest accepted upload in kilobytes.
|
||||
*/
|
||||
public const int MAX_KILOBYTES = 12288;
|
||||
|
||||
#[Locked]
|
||||
public int $jobId;
|
||||
|
||||
#[Locked]
|
||||
public int $taskId;
|
||||
|
||||
#[Locked]
|
||||
public string $taskTitle = '';
|
||||
|
||||
/**
|
||||
* @var TemporaryUploadedFile|null
|
||||
*/
|
||||
public $photo = null;
|
||||
|
||||
public string $caption = '';
|
||||
|
||||
/**
|
||||
* The image whose caption is being changed, if any.
|
||||
*/
|
||||
#[Locked]
|
||||
public ?int $editingImageId = null;
|
||||
|
||||
public string $editingCaption = '';
|
||||
|
||||
/**
|
||||
* The image the remove dialog asks about.
|
||||
*/
|
||||
#[Locked]
|
||||
public ?int $removalImageId = null;
|
||||
|
||||
public string $message = '';
|
||||
|
||||
public function mount(int $jobId, int $taskId, string $taskTitle): void
|
||||
{
|
||||
$this->authorize('jobs.view-job', $jobId);
|
||||
|
||||
$this->jobId = $jobId;
|
||||
$this->taskId = $taskId;
|
||||
$this->taskTitle = $taskTitle;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<TaskImageSummary>
|
||||
*/
|
||||
#[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. --}}
|
||||
<section aria-label="{{ __('jobs.tasks.images.list_of', ['title' => $taskTitle]) }}" class="space-y-2">
|
||||
@php($canUpload = Gate::allows('jobs.update-task-status', $jobId))
|
||||
|
||||
<h4 class="font-medium">
|
||||
{{ __('jobs.tasks.images.title') }}
|
||||
@if ($this->images !== [])
|
||||
<span class="font-normal">({{ count($this->images) }})</span>
|
||||
@endif
|
||||
</h4>
|
||||
|
||||
<p role="status" aria-live="polite" class="text-sm">
|
||||
<span wire:loading.remove wire:target="photo, add">{{ $message }}</span>
|
||||
<span wire:loading wire:target="photo">{{ __('jobs.tasks.images.uploading') }}</span>
|
||||
<span wire:loading wire:target="add">{{ __('jobs.tasks.images.saving') }}</span>
|
||||
</p>
|
||||
|
||||
@if ($this->images === [])
|
||||
<p class="text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.images.empty') }}</p>
|
||||
@else
|
||||
<ul class="grid grid-cols-1 gap-4 min-[360px]:grid-cols-2 lg:grid-cols-3">
|
||||
@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']))
|
||||
<li wire:key="task-image-{{ $image->id }}" class="min-w-0 space-y-2">
|
||||
<figure class="space-y-1">
|
||||
<a
|
||||
href="{{ $fullUrl }}"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
class="block rounded-md focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:focus-visible:outline-blue-400"
|
||||
>
|
||||
<img
|
||||
src="{{ route('jobs.tasks.images.show', [$jobId, $taskId, $image->id, 'thumbnail']) }}"
|
||||
alt="{{ $alt }}"
|
||||
width="{{ $thumbWidth }}"
|
||||
height="{{ $thumbHeight }}"
|
||||
loading="lazy"
|
||||
class="h-auto w-full rounded-md border border-zinc-200 bg-zinc-100 dark:border-zinc-700 dark:bg-zinc-800"
|
||||
/>
|
||||
<span class="sr-only">{{ __('jobs.tasks.images.opens_in_new_tab') }}</span>
|
||||
</a>
|
||||
<figcaption class="text-sm break-words">
|
||||
@if ($image->caption !== null)
|
||||
<span class="block">{{ $image->caption }}</span>
|
||||
@endif
|
||||
<span class="block text-zinc-600 dark:text-zinc-300">
|
||||
{{ $this->uploaderName($image) }}, <time datetime="{{ str_replace(' ', 'T', $image->uploadedAt) }}">{{ $this->formatTime($image->uploadedAt) }}</time>
|
||||
</span>
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
@if ($editingImageId === $image->id)
|
||||
<form wire:submit="saveEdit" class="space-y-2">
|
||||
<x-input id="image-caption-edit-{{ $image->id }}" wire:model="editingCaption" :label="__('jobs.tasks.images.caption')" maxlength="255" />
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<x-button submit sm icon="check" :text="__('jobs.tasks.images.save')" />
|
||||
<x-button wire:click="cancelEdit" subtle color="black" sm :text="__('jobs.tasks.images.cancel')" />
|
||||
</div>
|
||||
</form>
|
||||
@else
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<a
|
||||
href="{{ $fullUrl }}?download=1"
|
||||
aria-label="{{ __('jobs.tasks.images.download_named', ['image' => $alt]) }}"
|
||||
class="inline-flex min-h-6 items-center rounded-md px-2 py-1 text-sm font-medium text-zinc-900 underline hover:no-underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:text-zinc-100 dark:focus-visible:outline-blue-400"
|
||||
>{{ __('jobs.tasks.images.download') }}</a>
|
||||
|
||||
@if ($canUpload && $this->isOwn($image))
|
||||
<x-button
|
||||
id="image-edit-button-{{ $image->id }}"
|
||||
wire:click="startEdit({{ $image->id }})"
|
||||
subtle
|
||||
color="black"
|
||||
sm
|
||||
icon="pencil"
|
||||
:text="__('jobs.tasks.images.edit_caption')"
|
||||
:aria-label="__('jobs.tasks.images.edit_caption_named', ['image' => $alt])"
|
||||
/>
|
||||
@endif
|
||||
@if ($canUpload && $this->mayRemove($image))
|
||||
<x-button
|
||||
wire:click="confirmRemoval({{ $image->id }})"
|
||||
subtle
|
||||
color="black"
|
||||
sm
|
||||
icon="trash"
|
||||
:text="__('jobs.tasks.images.remove')"
|
||||
:aria-label="__('jobs.tasks.images.remove_named', ['image' => $alt])"
|
||||
/>
|
||||
@endif
|
||||
</div>
|
||||
@endif
|
||||
</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
@endif
|
||||
|
||||
@if ($canUpload)
|
||||
<form wire:submit="add" class="space-y-3">
|
||||
<div class="space-y-1">
|
||||
<label for="image-new-{{ $taskId }}" class="block text-sm font-semibold text-zinc-700 dark:text-zinc-300">{{ __('jobs.tasks.images.new') }}</label>
|
||||
<p id="image-new-{{ $taskId }}-hint" class="text-sm text-zinc-600 dark:text-zinc-300">{{ __('jobs.tasks.images.hint', ['size' => $this::MAX_KILOBYTES / 1024]) }}</p>
|
||||
<input
|
||||
type="file"
|
||||
id="image-new-{{ $taskId }}"
|
||||
wire:model="photo"
|
||||
accept="image/jpeg,image/png,image/webp,image/gif"
|
||||
aria-describedby="image-new-{{ $taskId }}-hint @error('photo') image-new-{{ $taskId }}-error @enderror"
|
||||
@error('photo') aria-invalid="true" @enderror
|
||||
class="block w-full max-w-md rounded-md text-sm text-zinc-900 file:me-3 file:min-h-9 file:cursor-pointer file:rounded-md file:border-0 file:bg-zinc-200 file:px-3 file:py-2 file:font-medium file:text-zinc-900 hover:file:bg-zinc-300 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:text-zinc-100 dark:file:bg-zinc-700 dark:file:text-zinc-100 dark:hover:file:bg-zinc-600 dark:focus-visible:outline-blue-400"
|
||||
/>
|
||||
@error('photo')
|
||||
<p id="image-new-{{ $taskId }}-error" class="text-sm text-red-700 dark:text-red-400">{{ $message }}</p>
|
||||
@enderror
|
||||
</div>
|
||||
|
||||
<div class="max-w-md">
|
||||
<x-input id="image-caption-new-{{ $taskId }}" wire:model="caption" :label="__('jobs.tasks.images.caption_optional')" maxlength="255" />
|
||||
</div>
|
||||
|
||||
<x-button
|
||||
submit
|
||||
sm
|
||||
icon="photo"
|
||||
:text="__('jobs.tasks.images.add')"
|
||||
:aria-label="__('jobs.tasks.images.add_named', ['title' => $taskTitle])"
|
||||
wire:loading.attr="disabled"
|
||||
wire:target="photo, add"
|
||||
/>
|
||||
</form>
|
||||
|
||||
<x-confirm-dialog id="remove-image-dialog-{{ $taskId }}" :title="__('jobs.tasks.images.remove_title')">
|
||||
<p>{{ __('jobs.tasks.images.remove_question') }}</p>
|
||||
|
||||
<x-slot:actions>
|
||||
<x-button id="remove-image-confirm-{{ $taskId }}" wire:click="remove" color="red" icon="trash" :text="__('jobs.tasks.images.remove')" />
|
||||
</x-slot:actions>
|
||||
</x-confirm-dialog>
|
||||
@endif
|
||||
</section>
|
||||
@@ -1,5 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Jobs\Presentation\Http\Controllers\ShowTaskImage;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::middleware(['web', 'auth', 'can:jobs.view'])
|
||||
@@ -16,4 +17,8 @@ Route::middleware(['web', 'auth', 'can:jobs.view'])
|
||||
Route::livewire('/{job}/tasks/create', 'jobs::task-form')->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');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user