Files
Toiminnanohjaus/app/Modules/Jobs/Infrastructure/Persistence/Repositories/EloquentCustomerJobQueries.php
T
petriandClaude Opus 5.5 54d98d9d2f Add expenses on customer jobs
- New Expenses module: purchases (materials, other) with a description
  and cost, and mileage priced with the price list's mileage rate.
- Who paid and whether the expense is billed are separate: an employee's
  own payments are reimbursed elsewhere. A billed expense has a markup
  and a billed amount, cost plus markup unless given.
- A job's expenses page lists, adds, edits and removes them; amounts of
  others' expenses need the expenses permission, own ones always show.
  Done jobs lock their expenses.
- The Kulut menu shows the user's own expenses by month. Management
  records subcontractors' expenses, which they see but cannot change.
- The price list gets a default markup for new purchases.
- Number fields that update a calculation now use wire:model.live.blur:
  in Livewire 4 plain .blur no longer sends the value to the server,
  which also fixes the product form's VAT calculation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 08:11:27 +02:00

268 lines
10 KiB
PHP

<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Catalog\Application\Contracts\CatalogQueries;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Jobs\Application\Contracts\CustomerJobQueries;
use App\Modules\Jobs\Application\DTOs\CustomerJobDetails;
use App\Modules\Jobs\Application\DTOs\CustomerJobSummary;
use App\Modules\Jobs\Application\DTOs\JobChangeEntry;
use App\Modules\Jobs\Application\DTOs\JobListFilter;
use App\Modules\Jobs\Application\DTOs\NamedId;
use App\Modules\Jobs\Domain\Enums\JobStatus;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Jobs\Infrastructure\Persistence\JobInvolvement;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
/**
* Names of customers, users, contacts and service units come from those
* modules' query contracts, never from their tables.
*/
class EloquentCustomerJobQueries implements CustomerJobQueries
{
public function __construct(
private CustomerQueries $customers,
private UserAccountQueries $users,
private CatalogQueries $catalog,
) {}
public function paginate(JobListFilter $filter, int $perPage = 25): LengthAwarePaginator
{
$page = $this->filtered($filter)
->orderByRaw('due_on IS NULL')
->orderBy('due_on')
->orderByDesc('id')
->paginate($perPage);
$toSummary = $this->summaryMapper(collect($page->items()));
return $page->through($toSummary);
}
public function board(JobListFilter $filter, int $limitPerStatus = 100): array
{
$board = [];
foreach (JobStatus::kanbanStatuses() as $status) {
$board[$status->value] = [];
}
$models = $this->filtered(new JobListFilter(
search: $filter->search,
priority: $filter->priority,
serviceUnitId: $filter->serviceUnitId,
mineForUserId: $filter->mineForUserId,
onlyMemberUserId: $filter->onlyMemberUserId,
))
->orderByRaw('due_on IS NULL')
->orderBy('due_on')
->orderByDesc('id')
->get();
$toSummary = $this->summaryMapper($models);
foreach ($models as $model) {
if (isset($board[$model->status->value]) && count($board[$model->status->value]) < $limitPerStatus) {
$board[$model->status->value][] = $toSummary($model);
}
}
return $board;
}
/**
* Turns job rows into summaries, with customer and user names looked up
* once for all rows.
*
* @param Collection<int, CustomerJobModel> $models
* @return \Closure(CustomerJobModel): CustomerJobSummary
*/
private function summaryMapper(Collection $models): \Closure
{
$customerNames = $this->customers->namesByIds($models->pluck('customer_id')->unique()->values()->all());
$userNames = $this->users->namesByIds($models->pluck('responsible_user_id')->unique()->values()->all());
return fn (CustomerJobModel $model): CustomerJobSummary => new CustomerJobSummary(
$model->id,
$model->number,
$model->name,
$model->customer_id,
$customerNames[$model->customer_id] ?? '',
$model->status,
$model->priority,
$model->due_on?->format('Y-m-d'),
$userNames[$model->responsible_user_id] ?? '',
$model->biller_user_id,
);
}
public function summariesByIds(array $ids): array
{
if ($ids === []) {
return [];
}
$models = CustomerJobModel::query()->whereIn('id', $ids)->get();
$toSummary = $this->summaryMapper($models);
$summaries = [];
foreach ($models as $model) {
$summaries[$model->id] = $toSummary($model);
}
return $summaries;
}
public function findDetails(int $id): ?CustomerJobDetails
{
$model = CustomerJobModel::query()->find($id);
if ($model === null) {
return null;
}
$memberIds = DB::table('customer_job_members')->where('customer_job_id', $id)->pluck('user_id')->map(fn ($id): int => (int) $id)->all();
$userIds = array_values(array_filter([$model->responsible_user_id, $model->contact_user_id, $model->biller_user_id, $model->created_by, ...$memberIds]));
$userNames = $this->users->namesByIds(array_values(array_unique($userIds)));
$user = fn (?int $userId): ?NamedId => $userId === null ? null : new NamedId($userId, $userNames[$userId] ?? '');
$serviceUnitIds = DB::table('customer_job_service_unit')->where('customer_job_id', $id)->pluck('service_unit_id')->map(fn ($id): int => (int) $id)->all();
$serviceUnits = [];
foreach ($this->catalog->serviceUnitNames($serviceUnitIds) as $unitId => $name) {
$serviceUnits[] = new NamedId((int) $unitId, $name);
}
$contact = $model->customer_contact_id === null ? null : $this->customers->findContact($model->customer_id, $model->customer_contact_id);
$billingUnit = $model->billing_unit_id === null ? null : $this->customers->findBillingUnit($model->customer_id, $model->billing_unit_id);
return new CustomerJobDetails(
id: $model->id,
number: $model->number,
name: $model->name,
description: $model->description,
customer: new NamedId($model->customer_id, $this->customers->namesByIds([$model->customer_id])[$model->customer_id] ?? ''),
serviceUnits: $serviceUnits,
startsOn: $model->starts_on?->format('Y-m-d'),
dueOn: $model->due_on?->format('Y-m-d'),
plannedFrom: $model->planned_from?->format('Y-m-d'),
plannedTo: $model->planned_to?->format('Y-m-d'),
kind: $model->kind,
status: $model->status,
priority: $model->priority,
paymentBasis: $model->payment_basis,
estimatedHours: $model->estimated_hours === null ? null : rtrim(rtrim($model->estimated_hours, '0'), '.'),
customerReference: $model->customer_reference,
instructions: $model->instructions,
responsible: $user($model->responsible_user_id) ?? new NamedId($model->responsible_user_id, ''),
contactUser: $user($model->contact_user_id),
customerContact: $contact === null ? null : new NamedId($contact->id, $contact->name),
biller: $user($model->biller_user_id),
billingUnit: $billingUnit === null ? null : new NamedId($billingUnit->id, $billingUnit->name),
members: array_values(array_map(fn (int $memberId): NamedId => new NamedId($memberId, $userNames[$memberId] ?? ''), $memberIds)),
tags: DB::table('customer_job_tag')
->join('tags', 'tags.id', '=', 'customer_job_tag.tag_id')
->where('customer_job_id', $id)
->orderBy('tags.name')
->pluck('tags.name')
->map(fn ($name): string => (string) $name)
->all(),
links: DB::table('customer_job_links')
->where('customer_job_id', $id)
->orderBy('sort_order')
->get()
->map(fn ($row): array => ['title' => (string) $row->title, 'url' => (string) $row->url])
->all(),
createdAt: $model->created_at->format('Y-m-d H:i'),
createdByName: $userNames[$model->created_by] ?? '',
);
}
public function changes(int $jobId): array
{
$rows = DB::table('customer_job_changes')->where('customer_job_id', $jobId)->orderByDesc('id')->get();
$userNames = $this->users->namesByIds($rows->pluck('user_id')->map(fn ($id): int => (int) $id)->unique()->values()->all());
return $rows->map(fn ($row): JobChangeEntry => new JobChangeEntry(
(string) $row->field,
$row->old_value,
$row->new_value,
$userNames[(int) $row->user_id] ?? '',
(string) $row->created_at,
))->values()->all();
}
public function tagSuggestions(string $term = '', int $limit = 20): array
{
$term = trim($term);
return DB::table('tags')
->when($term !== '', fn ($query) => $query->where('name', 'like', '%'.addcslashes($term, '%_\\').'%'))
->orderBy('name')
->limit($limit)
->pluck('name')
->map(fn ($name): string => (string) $name)
->all();
}
public function isMember(int $jobId, int $userId): bool
{
return $this->involving(CustomerJobModel::query()->whereKey($jobId), $userId)->exists();
}
/**
* @return Builder<CustomerJobModel>
*/
private function filtered(JobListFilter $filter): Builder
{
$query = CustomerJobModel::query();
$search = trim((string) $filter->search);
if ($search !== '') {
$pattern = '%'.addcslashes($search, '%_\\').'%';
$customerIds = array_map(fn ($customer): int => $customer->id, $this->customers->search($search, 50));
$query->where(fn (Builder $query) => $query
->where('number', 'like', $pattern)
->orWhere('name', 'like', $pattern)
->orWhereIn('customer_id', $customerIds));
}
if ($filter->status !== null) {
$query->where('status', $filter->status);
} elseif (! $filter->includeArchived) {
$query->where('status', '!=', JobStatus::Archived->value);
}
if ($filter->priority !== null) {
$query->where('priority', $filter->priority);
}
if ($filter->serviceUnitId !== null) {
$query->whereIn('id', DB::table('customer_job_service_unit')->select('customer_job_id')->where('service_unit_id', $filter->serviceUnitId));
}
foreach (array_filter([$filter->mineForUserId, $filter->onlyMemberUserId]) as $userId) {
$this->involving($query, $userId);
}
return $query;
}
/**
* Restricts to jobs where the user is responsible, contact, biller,
* member or an assignee of one of the job's tasks.
*
* @param Builder<CustomerJobModel> $query
* @return Builder<CustomerJobModel>
*/
private function involving(Builder $query, int $userId): Builder
{
return JobInvolvement::restrict($query, $userId);
}
}