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,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)
|
||||
|
||||
Reference in New Issue
Block a user