Add the billing material with drafts, combined invoices and billed marks

Management builds the monthly billing material (laskuaineisto) as a
draft: done jobs are added as invoices of their own, combined when the
customer, billing unit and reference allow it, and their billable hours
are set per work type. Creating the material checks the jobs again,
marks the approved hours and billable expenses billed, forms invoice
lines with price and VAT snapshots and moves the jobs to "Lasku luotu".
Fixed price jobs bill their quoted amount once. Billed hours keep their
approval and billed expenses can no longer change. The Fennoa export
and monthly fee lines come later.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-24 13:08:24 +02:00
co-authored by Claude Opus 5.5
parent 6de5d9bef1
commit 97bd23bed5
98 changed files with 4887 additions and 22 deletions
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\Contracts;
use App\Modules\TimeTracking\Application\DTOs\ApprovalWeek;
use App\Modules\TimeTracking\Application\DTOs\JobBillingHours;
use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary;
use App\Modules\TimeTracking\Application\DTOs\WeekSheet;
@@ -41,4 +42,14 @@ interface TimeEntryQueries
* @return list<ApprovalWeek>
*/
public function approvedWeeks(string $sinceMonday): array;
/**
* Unbilled hours of the jobs for billing: approved hours by work type,
* and the hours still waiting for approval. Keyed by job id; every job
* asked for is included.
*
* @param list<int> $jobIds
* @return array<int, JobBillingHours>
*/
public function billingHours(array $jobIds): array;
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\DTOs;
/**
* A job's unbilled hours for billing, in quarters of an hour.
*/
final readonly class JobBillingHours
{
/**
* @param array<int, int> $approvedQuartersByWorkType Approved, unbilled hours keyed by work type id.
* @param int $unapprovedQuarters Hours still waiting for approval.
*/
public function __construct(
public int $jobId,
public array $approvedQuartersByWorkType,
public int $unapprovedQuarters,
) {}
}
@@ -10,7 +10,8 @@ use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository;
/**
* Cancels the approval of a user's week so the hours can be corrected.
* Only management may do this; the caller checks it.
* Billed hours keep their approval. Only management may do this; the
* caller checks it.
*/
final class CancelWeekApproval
{
@@ -31,7 +32,7 @@ final class CancelWeekApproval
$cancelled = 0;
foreach ($this->entries->forUserBetween($userId, $start, $start->modify('+6 days')) as $entry) {
if (! $entry->isApproved()) {
if (! $entry->isApproved() || $entry->isBilled()) {
continue;
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Modules\TimeTracking\Application\UseCases;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\TimeTracking\Domain\Contracts\TimeEntryRepository;
/**
* Marks a job's approved, unbilled hours billed on a billing material, so
* they are never billed twice. Hours waiting for approval are left as they
* are. The caller (billing) checks who may do this.
*/
final class MarkJobHoursBilled
{
public function __construct(
private TimeEntryRepository $entries,
private TransactionManager $transactions,
) {}
/**
* @return array<int, int> The quarters marked billed, keyed by work type id.
*/
public function execute(int $jobId, int $billingExportId): array
{
return $this->transactions->run(function () use ($jobId, $billingExportId): array {
$quarters = [];
foreach ($this->entries->approvedUnbilledForJob($jobId) as $entry) {
$entry->markBilled($billingExportId);
$this->entries->save($entry);
$quarters[$entry->workTypeId()] = ($quarters[$entry->workTypeId()] ?? 0) + $entry->hours()->quarters;
}
return $quarters;
});
}
}
@@ -27,6 +27,13 @@ interface TimeEntryRepository
public function delete(TimeEntry $entry): void;
/**
* The job's approved entries that are not billed yet.
*
* @return list<TimeEntry>
*/
public function approvedUnbilledForJob(int $jobId): array;
/**
* The user's recorded quarters of an hour on the day, all tasks.
*/
@@ -11,7 +11,8 @@ use DateTimeImmutable;
/**
* A user's hours on one task on one day (one entry per day). The job and
* work type are copied from the task when the entry is made, for billing.
* Approved hours are locked until management cancels the approval.
* Approved hours are locked until management cancels the approval; billed
* hours (on a billing material) stay approved for good.
*/
final class TimeEntry
{
@@ -26,6 +27,7 @@ final class TimeEntry
private ?string $note,
private ?int $approvedBy = null,
private ?DateTimeImmutable $approvedAt = null,
private ?int $billingExportId = null,
) {}
public static function create(int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note = null): self
@@ -33,9 +35,9 @@ final class TimeEntry
return new self(null, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, self::text($note));
}
public static function reconstitute(int $id, int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note, ?int $approvedBy = null, ?DateTimeImmutable $approvedAt = null): self
public static function reconstitute(int $id, int $userId, int $taskId, int $jobId, int $workTypeId, DateTimeImmutable $workedOn, WorkedHours $hours, ?string $note, ?int $approvedBy = null, ?DateTimeImmutable $approvedAt = null, ?int $billingExportId = null): self
{
return new self($id, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, $note, $approvedBy, $approvedAt);
return new self($id, $userId, $taskId, $jobId, $workTypeId, $workedOn, $hours, $note, $approvedBy, $approvedAt, $billingExportId);
}
/**
@@ -75,12 +77,39 @@ final class TimeEntry
$this->approvedAt = $approvedAt;
}
/**
* Cancels the approval, unless the hours are billed.
*/
public function cancelApproval(): void
{
if ($this->isBilled()) {
return;
}
$this->approvedBy = null;
$this->approvedAt = null;
}
/**
* Marks approved hours billed on the given billing material.
*/
public function markBilled(int $billingExportId): void
{
if ($this->isApproved() && ! $this->isBilled()) {
$this->billingExportId = $billingExportId;
}
}
public function isBilled(): bool
{
return $this->billingExportId !== null;
}
public function billingExportId(): ?int
{
return $this->billingExportId;
}
public function isApproved(): bool
{
return $this->approvedAt !== null;
@@ -21,9 +21,10 @@ use Illuminate\Database\Eloquent\Model;
* @property string|null $note
* @property CarbonImmutable|null $approved_at
* @property int|null $approved_by
* @property int|null $billing_export_id
*/
#[Table('time_entries')]
#[Fillable(['user_id', 'task_id', 'customer_job_id', 'work_type_id', 'worked_on', 'hours', 'note', 'approved_at', 'approved_by'])]
#[Fillable(['user_id', 'task_id', 'customer_job_id', 'work_type_id', 'worked_on', 'hours', 'note', 'approved_at', 'approved_by', 'billing_export_id'])]
#[UseFactory(TimeEntryFactory::class)]
class TimeEntryModel extends Model
{
@@ -43,6 +44,7 @@ class TimeEntryModel extends Model
'worked_on' => 'immutable_date',
'approved_at' => 'immutable_datetime',
'approved_by' => 'integer',
'billing_export_id' => 'integer',
];
}
@@ -5,6 +5,7 @@ namespace App\Modules\TimeTracking\Infrastructure\Persistence\Repositories;
use App\Modules\Jobs\Application\Contracts\TaskQueries;
use App\Modules\TimeTracking\Application\Contracts\TimeEntryQueries;
use App\Modules\TimeTracking\Application\DTOs\ApprovalWeek;
use App\Modules\TimeTracking\Application\DTOs\JobBillingHours;
use App\Modules\TimeTracking\Application\DTOs\TimeEntrySummary;
use App\Modules\TimeTracking\Application\DTOs\WeekApproval;
use App\Modules\TimeTracking\Application\DTOs\WeekRow;
@@ -68,6 +69,34 @@ class EloquentTimeEntryQueries implements TimeEntryQueries
return new WeekSheet($days, $rows, $dayTotals, array_sum($dayTotals), (int) $unapproved, $this->latestApproval($entries));
}
public function billingHours(array $jobIds): array
{
$approved = array_fill_keys($jobIds, []);
$unapproved = array_fill_keys($jobIds, 0);
if ($jobIds !== []) {
$entries = TimeEntryModel::query()
->whereIn('customer_job_id', $jobIds)
->whereNull('billing_export_id')
->get(['customer_job_id', 'work_type_id', 'hours', 'approved_at']);
foreach ($entries as $entry) {
if ($entry->approved_at === null) {
$unapproved[$entry->customer_job_id] += $entry->quarters();
} else {
$approved[$entry->customer_job_id][$entry->work_type_id] = ($approved[$entry->customer_job_id][$entry->work_type_id] ?? 0) + $entry->quarters();
}
}
}
$result = [];
foreach ($jobIds as $jobId) {
$result[$jobId] = new JobBillingHours($jobId, $approved[$jobId], $unapproved[$jobId]);
}
return $result;
}
public function entriesForTask(int $taskId, int $userId): array
{
return TimeEntryModel::query()
@@ -42,6 +42,7 @@ class EloquentTimeEntryRepository implements TimeEntryRepository
'note' => $entry->note(),
'approved_by' => $entry->approvedBy(),
'approved_at' => $entry->approvedAt()?->format('Y-m-d H:i:s'),
'billing_export_id' => $entry->billingExportId(),
])->save();
return $this->toEntity($model->refresh());
@@ -64,6 +65,20 @@ class EloquentTimeEntryRepository implements TimeEntryRepository
TimeEntryModel::query()->whereKey($entry->id())->delete();
}
public function approvedUnbilledForJob(int $jobId): array
{
return TimeEntryModel::query()
->where('customer_job_id', $jobId)
->whereNotNull('approved_at')
->whereNull('billing_export_id')
->orderBy('worked_on')
->orderBy('id')
->get()
->map(fn (TimeEntryModel $model): TimeEntry => $this->toEntity($model))
->values()
->all();
}
public function quartersOn(int $userId, DateTimeImmutable $day, ?int $exceptEntryId = null): int
{
return (int) round((float) TimeEntryModel::query()
@@ -86,6 +101,7 @@ class EloquentTimeEntryRepository implements TimeEntryRepository
$model->note,
$model->approved_by,
$model->approved_at === null ? null : DateTimeImmutable::createFromInterface($model->approved_at),
$model->billing_export_id,
);
}
}