Files
petriandClaude Opus 5.5 5f9423a3c3 Add monthly fee billing lines to the billing material
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]>
2026-11-24 13:23:46 +02:00

179 lines
7.7 KiB
PHP

<?php
namespace App\Modules\Jobs\Infrastructure\Persistence\Repositories;
use App\Modules\Jobs\Domain\Contracts\CustomerJobRepository;
use App\Modules\Jobs\Domain\Entities\CustomerJob;
use App\Modules\Jobs\Domain\ValueObjects\EstimatedHours;
use App\Modules\Jobs\Domain\ValueObjects\JobDetails;
use App\Modules\Jobs\Domain\ValueObjects\JobLink;
use App\Modules\Jobs\Domain\ValueObjects\JobName;
use App\Modules\Jobs\Domain\ValueObjects\JobNumber;
use App\Modules\Jobs\Domain\ValueObjects\Tag;
use App\Modules\Jobs\Infrastructure\Persistence\Eloquent\CustomerJobModel;
use App\Modules\Shared\Domain\ValueObjects\Money;
use DateTimeImmutable;
use Illuminate\Support\Facades\DB;
class EloquentCustomerJobRepository implements CustomerJobRepository
{
public function findById(int $id): ?CustomerJob
{
$model = CustomerJobModel::query()->find($id);
return $model === null ? null : $this->toEntity($model);
}
public function save(CustomerJob $job): CustomerJob
{
$details = $job->details();
$model = $job->id() === null ? new CustomerJobModel : CustomerJobModel::query()->findOrFail($job->id());
$model->fill([
'number' => $job->number()->format(),
'name' => $details->name->value,
'description' => $details->description,
'customer_id' => $details->customerId,
'starts_on' => $details->startsOn?->format('Y-m-d'),
'due_on' => $details->dueOn?->format('Y-m-d'),
'planned_from' => $details->plannedFrom?->format('Y-m-d'),
'planned_to' => $details->plannedTo?->format('Y-m-d'),
'kind' => $details->kind,
'status' => $details->status,
'priority' => $details->priority,
'payment_basis' => $details->paymentBasis,
'estimated_hours' => $details->estimatedHours?->value,
'quoted_amount_cents' => $details->quotedAmount?->cents,
'monthly_fee_cents' => $details->monthlyFee?->cents,
'completed_at' => $job->completedAt()?->format('Y-m-d H:i:s'),
'customer_reference' => $details->customerReference,
'instructions' => $details->instructions,
'responsible_user_id' => $details->responsibleUserId,
'contact_user_id' => $details->contactUserId,
'customer_contact_id' => $details->customerContactId,
'biller_user_id' => $details->billerUserId,
'billing_unit_id' => $details->billingUnitId,
'created_by' => $job->createdBy(),
])->save();
$this->syncPivot('customer_job_service_unit', 'service_unit_id', $model->id, $details->serviceUnitIds);
$this->syncPivot('customer_job_members', 'user_id', $model->id, $details->memberUserIds);
$this->syncPivot('customer_job_tag', 'tag_id', $model->id, $this->tagIds($details->tags));
DB::table('customer_job_links')->where('customer_job_id', $model->id)->delete();
DB::table('customer_job_links')->insert(array_map(fn (int $index, JobLink $link): array => [
'customer_job_id' => $model->id,
'title' => $link->title,
'url' => $link->url,
'sort_order' => $index + 1,
], array_keys($details->links), $details->links));
return $this->toEntity($model->refresh());
}
public function findQuickSaleJob(int $year): ?CustomerJob
{
$model = CustomerJobModel::query()->where('quick_sale_year', $year)->first();
return $model === null ? null : $this->toEntity($model);
}
public function markAsQuickSaleJob(int $jobId, int $year): void
{
CustomerJobModel::query()->whereKey($jobId)->update(['quick_sale_year' => $year]);
}
public function recordChanges(int $jobId, int $userId, array $changes): void
{
$now = now();
DB::table('customer_job_changes')->insert(array_map(fn ($change): array => [
'customer_job_id' => $jobId,
'user_id' => $userId,
'field' => $change->field,
'old_value' => $change->oldValue,
'new_value' => $change->newValue,
'created_at' => $now,
], $changes));
}
/**
* @param list<int> $ids
*/
private function syncPivot(string $table, string $column, int $jobId, array $ids): void
{
DB::table($table)->where('customer_job_id', $jobId)->whereNotIn($column, $ids)->delete();
DB::table($table)->insertOrIgnore(array_map(fn (int $id): array => ['customer_job_id' => $jobId, $column => $id], $ids));
}
/**
* Ids of the tags, adding names not seen before to the shared tag list.
*
* @param list<Tag> $tags
* @return list<int>
*/
private function tagIds(array $tags): array
{
$ids = [];
foreach ($tags as $tag) {
$existing = DB::table('tags')->whereRaw('LOWER(name) = ?', [mb_strtolower($tag->value)])->value('id');
$ids[] = (int) ($existing ?? DB::table('tags')->insertGetId(['name' => $tag->value, 'created_at' => now(), 'updated_at' => now()]));
}
return $ids;
}
private function toEntity(CustomerJobModel $model): CustomerJob
{
$date = fn ($value): ?DateTimeImmutable => $value === null ? null : (DateTimeImmutable::createFromFormat('!Y-m-d', $value->format('Y-m-d')) ?: null);
$details = new JobDetails(
name: new JobName($model->name),
description: $model->description,
customerId: $model->customer_id,
serviceUnitIds: DB::table('customer_job_service_unit')->where('customer_job_id', $model->id)->pluck('service_unit_id')->map(fn ($id): int => (int) $id)->all(),
startsOn: $date($model->starts_on),
dueOn: $date($model->due_on),
plannedFrom: $date($model->planned_from),
plannedTo: $date($model->planned_to),
kind: $model->kind,
status: $model->status,
priority: $model->priority,
paymentBasis: $model->payment_basis,
estimatedHours: $model->estimated_hours === null ? null : new EstimatedHours((float) $model->estimated_hours),
customerReference: $model->customer_reference,
instructions: $model->instructions,
responsibleUserId: $model->responsible_user_id,
contactUserId: $model->contact_user_id,
customerContactId: $model->customer_contact_id,
billerUserId: $model->biller_user_id,
billingUnitId: $model->billing_unit_id,
memberUserIds: DB::table('customer_job_members')->where('customer_job_id', $model->id)->pluck('user_id')->map(fn ($id): int => (int) $id)->all(),
tags: DB::table('customer_job_tag')
->join('tags', 'tags.id', '=', 'customer_job_tag.tag_id')
->where('customer_job_id', $model->id)
->orderBy('tags.name')
->pluck('tags.name')
->map(fn ($name): Tag => new Tag((string) $name))
->all(),
links: DB::table('customer_job_links')
->where('customer_job_id', $model->id)
->orderBy('sort_order')
->get()
->map(fn ($row): JobLink => new JobLink((string) $row->title, (string) $row->url))
->all(),
quotedAmount: $model->quoted_amount_cents === null ? null : Money::fromCents($model->quoted_amount_cents),
monthlyFee: $model->monthly_fee_cents === null ? null : Money::fromCents($model->monthly_fee_cents),
);
return CustomerJob::reconstitute(
$model->id,
JobNumber::fromString($model->number),
$details,
$model->created_by,
$model->completed_at === null ? null : DateTimeImmutable::createFromInterface($model->completed_at),
);
}
}