Jobs billed by a fixed monthly fee get a monthly fee field, kept behind the quotes permission like the quoted amount. A billing material now has a billing month: a new draft adds every monthly fee job with something to bill, each on an invoice of its own, and bills one line for every unbilled month from the job's start up to the billing month (or its end or completion), so skipped months are caught up and no month is billed twice. Their expenses are billed alongside, their hours are covered by the fee and marked billed, and the job keeps running. Co-Authored-By: Claude Opus 5.5 <[email protected]>
334 lines
13 KiB
PHP
334 lines
13 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\JobBillingInfo;
|
|
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\Domain\Enums\PaymentBasis;
|
|
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] ?? '',
|
|
quotedAmountCents: $model->quoted_amount_cents,
|
|
monthlyFeeCents: $model->monthly_fee_cents,
|
|
completedAt: $model->completed_at?->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'),
|
|
);
|
|
}
|
|
|
|
public function billingInfoWithStatus(JobStatus $status): array
|
|
{
|
|
return array_values($this->billingInfo(CustomerJobModel::query()->where('status', $status)->orderBy('number')->get()));
|
|
}
|
|
|
|
public function billingInfoMonthly(): array
|
|
{
|
|
return array_values($this->billingInfo(CustomerJobModel::query()
|
|
->where('payment_basis', PaymentBasis::MonthlyFee)
|
|
->whereIn('status', [JobStatus::Order, JobStatus::InProduction, JobStatus::OnHold, JobStatus::Done])
|
|
->orderBy('number')
|
|
->get()));
|
|
}
|
|
|
|
public function billingInfoOf(array $ids): array
|
|
{
|
|
return $ids === [] ? [] : $this->billingInfo(CustomerJobModel::query()->whereIn('id', $ids)->orderBy('number')->get());
|
|
}
|
|
|
|
/**
|
|
* @param Collection<int, CustomerJobModel> $models
|
|
* @return array<int, JobBillingInfo>
|
|
*/
|
|
private function billingInfo(Collection $models): array
|
|
{
|
|
$customerNames = $this->customers->namesByIds($models->pluck('customer_id')->unique()->values()->all());
|
|
$billingUnitNames = [];
|
|
$result = [];
|
|
$timezone = (string) config('app.business_timezone');
|
|
|
|
foreach ($models as $model) {
|
|
if ($model->billing_unit_id !== null && ! isset($billingUnitNames[$model->customer_id])) {
|
|
$billingUnitNames[$model->customer_id] = [];
|
|
foreach ($this->customers->billingUnitsOf($model->customer_id) as $unit) {
|
|
$billingUnitNames[$model->customer_id][$unit->id] = $unit->name;
|
|
}
|
|
}
|
|
|
|
$result[$model->id] = new JobBillingInfo(
|
|
$model->id,
|
|
$model->number,
|
|
$model->name,
|
|
$model->customer_id,
|
|
$customerNames[$model->customer_id] ?? '',
|
|
$model->status,
|
|
$model->payment_basis,
|
|
$model->quoted_amount_cents,
|
|
$model->customer_reference,
|
|
$model->billing_unit_id,
|
|
$model->billing_unit_id === null ? null : ($billingUnitNames[$model->customer_id][$model->billing_unit_id] ?? null),
|
|
$model->monthly_fee_cents,
|
|
$model->starts_on?->format('Y-m-d'),
|
|
$model->due_on?->format('Y-m-d'),
|
|
$model->completed_at?->setTimezone($timezone)->format('Y-m-d'),
|
|
$model->created_at->setTimezone($timezone)->format('Y-m-d'),
|
|
);
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|