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]>
This commit is contained in:
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|||||||
|
|
||||||
## Project
|
## Project
|
||||||
|
|
||||||
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) `Billing` (the monthly billing material: a draft of invoices made of done jobs, management's billable hours, and on creation invoice lines with price snapshots; reads and marks hours, expenses and jobs through its `BillingJobs`/`BillingHours`/`BillingExpenses`/`BillingPrices` ports, which call those modules' queries and the use cases `MarkJobHoursBilled`, `MarkJobExpensesBilled` and `ChangeJobStatus`) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users).
|
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), TallStackUI 4 (Blade components, no prefix: `<x-input>`, `<x-button>`), Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users`, `Customers`, `Catalog` (service units, services and work types, managed on the Pohjatiedot page; hourly rates, products and the mileage rate on the Hinnasto page, read through `PriceListQueries`, never `CatalogQueries`) `Jobs` (customer jobs: numbering, members, tags, links, history, tasks) `TimeTracking` (hours on tasks: weekly sheet and task booking page) `Expenses` (expenses on jobs with cost, markup and billed amount; reads jobs and prices through its own `ExpenseJobs`/`ExpensePricing` ports) `Billing` (the monthly billing material: a draft of invoices made of done jobs and monthly fee jobs (one line per unbilled month up to the draft's month, each such job an invoice of its own), management's billable hours, and on creation invoice lines with price snapshots; reads and marks hours, expenses and jobs through its `BillingJobs`/`BillingHours`/`BillingExpenses`/`BillingPrices` ports, which call those modules' queries and the use cases `MarkJobHoursBilled`, `MarkJobExpensesBilled` and `ChangeJobStatus`) and `Sales` (quick sales of consumer products at the counter, credits and cash days; its `QuickSaleHours` port books product durations through Jobs' `ProvideQuickSaleTask` (the yearly "Pikamyynnit" job) and TimeTracking's `AddTaskHours`)); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users).
|
||||||
|
|
||||||
- **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec.
|
- **The specification is `docs/maarittely.md`** (Finnish). It defines roles and the permission table, money visibility, customers, customer jobs (*asiakastyö*) with fields and enum keys, Kanban, tasks, time entries, expenses, the service unit → service → work type hierarchy and pricing, Fennoa billing export, the data model, the phases with phase 1 in detail, and open questions. Read it before designing any domain feature. `määrittely.txt` is the original description with the customer's answers to questions 1–53, referenced as *(K12)* in the spec.
|
||||||
- **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification and the UI are in Finnish. Keep UI strings in translation files from the start.
|
- **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification and the UI are in Finnish. Keep UI strings in translation files from the start.
|
||||||
|
|||||||
@@ -12,11 +12,19 @@ use App\Modules\Billing\Application\DTOs\BillableJob;
|
|||||||
interface BillingJobs
|
interface BillingJobs
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* Done jobs, by job number.
|
* Jobs that may go on a material: done jobs, and monthly fee jobs that
|
||||||
|
* are running or done, by job number.
|
||||||
*
|
*
|
||||||
* @return list<BillableJob>
|
* @return list<BillableJob>
|
||||||
*/
|
*/
|
||||||
public function done(): array;
|
public function candidates(): array;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Monthly fee jobs that are running or done, by job number.
|
||||||
|
*
|
||||||
|
* @return list<BillableJob>
|
||||||
|
*/
|
||||||
|
public function monthly(): array;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param list<int> $jobIds
|
* @param list<int> $jobIds
|
||||||
|
|||||||
@@ -9,7 +9,9 @@ use App\Modules\Billing\Domain\ValueObjects\DraftJob;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* A customer job as billing sees it. A null mode means the job is not
|
* A customer job as billing sees it. A null mode means the job is not
|
||||||
* billed this way (not billable, or billed monthly).
|
* billed on a material. A monthly fee job runs from $billingStartsOn
|
||||||
|
* (its start or creation day) to $billingEndsOn (its last day or the day
|
||||||
|
* it was done), if that is set.
|
||||||
*/
|
*/
|
||||||
final readonly class BillableJob
|
final readonly class BillableJob
|
||||||
{
|
{
|
||||||
@@ -27,7 +29,10 @@ final readonly class BillableJob
|
|||||||
public ?string $customerReference,
|
public ?string $customerReference,
|
||||||
public ?BillingMode $mode,
|
public ?BillingMode $mode,
|
||||||
public ?int $quotedAmountCents,
|
public ?int $quotedAmountCents,
|
||||||
public bool $isDone,
|
public bool $inBillableStatus,
|
||||||
|
public ?int $monthlyFeeCents = null,
|
||||||
|
public string $billingStartsOn = '',
|
||||||
|
public ?string $billingEndsOn = null,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -40,6 +45,6 @@ final readonly class BillableJob
|
|||||||
|
|
||||||
public function toDraftJob(): DraftJob
|
public function toDraftJob(): DraftJob
|
||||||
{
|
{
|
||||||
return new DraftJob($this->id, $this->customerId, $this->billingUnitId, $this->customerReference);
|
return new DraftJob($this->id, $this->customerId, $this->billingUnitId, $this->customerReference, [], $this->mode === BillingMode::MonthlyFee);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,8 +9,9 @@ use App\Modules\Billing\Domain\ValueObjects\InvoiceTotals;
|
|||||||
use DateTimeImmutable;
|
use DateTimeImmutable;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A billing material for its page: a draft with its preview and the done
|
* A billing material for its page: a draft with its preview and the jobs
|
||||||
* jobs that may be added, or a created material with its lines.
|
* that may be added, or a created material with its lines. The period
|
||||||
|
* (Y-m) is the month monthly fees are billed up to.
|
||||||
*/
|
*/
|
||||||
final readonly class ExportView
|
final readonly class ExportView
|
||||||
{
|
{
|
||||||
@@ -21,6 +22,7 @@ final readonly class ExportView
|
|||||||
public function __construct(
|
public function __construct(
|
||||||
public int $id,
|
public int $id,
|
||||||
public ExportStatus $status,
|
public ExportStatus $status,
|
||||||
|
public string $period,
|
||||||
public DateTimeImmutable $createdAt,
|
public DateTimeImmutable $createdAt,
|
||||||
public string $createdByName,
|
public string $createdByName,
|
||||||
public ?DateTimeImmutable $finalizedAt,
|
public ?DateTimeImmutable $finalizedAt,
|
||||||
|
|||||||
@@ -10,23 +10,26 @@ use App\Modules\Billing\Application\DTOs\HourlyRate;
|
|||||||
use App\Modules\Billing\Application\DTOs\JobHours;
|
use App\Modules\Billing\Application\DTOs\JobHours;
|
||||||
use App\Modules\Billing\Domain\Enums\BillingMode;
|
use App\Modules\Billing\Domain\Enums\BillingMode;
|
||||||
use App\Modules\Billing\Domain\Enums\NotBillableReason;
|
use App\Modules\Billing\Domain\Enums\NotBillableReason;
|
||||||
|
use App\Modules\Billing\Domain\ValueObjects\BillingMonths;
|
||||||
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
|
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
|
||||||
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
|
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* What a job may bill and its invoice lines (spec 12): hours per work type
|
* What a job may bill and its invoice lines (spec 12): hours per work type
|
||||||
* at the hourly rates, or the quoted fixed price once, and the billable
|
* at the hourly rates, the quoted fixed price once, or the monthly fee of
|
||||||
* expenses separately. Only approved hours are billed.
|
* every unbilled month (spec 5.5), and the billable expenses separately.
|
||||||
|
* Only approved hours are billed; a fixed price or a monthly fee covers them.
|
||||||
*/
|
*/
|
||||||
final class BillingRules
|
final class BillingRules
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
* @param list<BillableExpense> $expenses
|
* @param list<BillableExpense> $expenses
|
||||||
* @param array<int, HourlyRate> $rates
|
* @param array<int, HourlyRate> $rates
|
||||||
|
* @param list<string> $unbilledMonths For a monthly fee job, as Y-m.
|
||||||
*/
|
*/
|
||||||
public function reasonNotBillable(BillableJob $job, JobHours $hours, array $expenses, bool $fixedPriceBilled, array $rates): ?NotBillableReason
|
public function reasonNotBillable(BillableJob $job, JobHours $hours, array $expenses, bool $fixedPriceBilled, array $rates, array $unbilledMonths = []): ?NotBillableReason
|
||||||
{
|
{
|
||||||
if (! $job->isDone) {
|
if (! $job->inBillableStatus) {
|
||||||
return NotBillableReason::WrongStatus;
|
return NotBillableReason::WrongStatus;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,6 +41,14 @@ final class BillingRules
|
|||||||
return NotBillableReason::MissingIdentityCode;
|
return NotBillableReason::MissingIdentityCode;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($job->mode === BillingMode::MonthlyFee) {
|
||||||
|
if ($job->monthlyFeeCents === null) {
|
||||||
|
return NotBillableReason::MissingMonthlyFee;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $unbilledMonths === [] && $expenses === [] ? NotBillableReason::NothingToBill : null;
|
||||||
|
}
|
||||||
|
|
||||||
if ($job->mode === BillingMode::FixedPrice) {
|
if ($job->mode === BillingMode::FixedPrice) {
|
||||||
if (! $fixedPriceBilled && $job->quotedAmountCents === null) {
|
if (! $fixedPriceBilled && $job->quotedAmountCents === null) {
|
||||||
return NotBillableReason::MissingQuotedAmount;
|
return NotBillableReason::MissingQuotedAmount;
|
||||||
@@ -76,18 +87,26 @@ final class BillingRules
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* The job's lines: hours per work type by name (management's billable
|
* The job's lines: hours per work type by name (management's billable
|
||||||
* hours or the approved ones) or the fixed price, then the expenses.
|
* hours or the approved ones), the fixed price or the monthly fees,
|
||||||
|
* then the expenses.
|
||||||
*
|
*
|
||||||
* @param array<int, int> $approvedByWorkType
|
* @param array<int, int> $approvedByWorkType
|
||||||
* @param list<BillableExpense> $expenses
|
* @param list<BillableExpense> $expenses
|
||||||
* @param array<int, HourlyRate> $rates
|
* @param array<int, HourlyRate> $rates
|
||||||
|
* @param list<string> $unbilledMonths For a monthly fee job, as Y-m.
|
||||||
* @return list<InvoiceLine>
|
* @return list<InvoiceLine>
|
||||||
*/
|
*/
|
||||||
public function lines(BillableJob $job, DraftJob $draftJob, array $approvedByWorkType, array $expenses, bool $fixedPriceBilled, array $rates, int $vatBasisPoints): array
|
public function lines(BillableJob $job, DraftJob $draftJob, array $approvedByWorkType, array $expenses, bool $fixedPriceBilled, array $rates, int $vatBasisPoints, array $unbilledMonths = []): array
|
||||||
{
|
{
|
||||||
$lines = [];
|
$lines = [];
|
||||||
|
|
||||||
if ($job->mode === BillingMode::FixedPrice) {
|
if ($job->mode === BillingMode::MonthlyFee) {
|
||||||
|
if ($job->monthlyFeeCents !== null) {
|
||||||
|
foreach ($unbilledMonths as $month) {
|
||||||
|
$lines[] = InvoiceLine::monthlyFee($job->id, $month, BillingMonths::label($month).' '.$job->label(), $job->monthlyFeeCents, $vatBasisPoints);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} elseif ($job->mode === BillingMode::FixedPrice) {
|
||||||
if (! $fixedPriceBilled && $job->quotedAmountCents !== null) {
|
if (! $fixedPriceBilled && $job->quotedAmountCents !== null) {
|
||||||
$lines[] = InvoiceLine::fixedPrice($job->id, $job->label(), $job->quotedAmountCents, $vatBasisPoints);
|
$lines[] = InvoiceLine::fixedPrice($job->id, $job->label(), $job->quotedAmountCents, $vatBasisPoints);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,12 +13,17 @@ use App\Modules\Billing\Application\DTOs\BillableJob;
|
|||||||
use App\Modules\Billing\Application\DTOs\HourlyRate;
|
use App\Modules\Billing\Application\DTOs\HourlyRate;
|
||||||
use App\Modules\Billing\Application\DTOs\JobHours;
|
use App\Modules\Billing\Application\DTOs\JobHours;
|
||||||
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
|
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
|
||||||
|
use App\Modules\Billing\Domain\Enums\BillingMode;
|
||||||
use App\Modules\Billing\Domain\Enums\NotBillableReason;
|
use App\Modules\Billing\Domain\Enums\NotBillableReason;
|
||||||
|
use App\Modules\Billing\Domain\ValueObjects\BillingMonths;
|
||||||
|
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
|
||||||
|
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* What the given jobs have to bill right now, read once for a page or a
|
* What the given jobs have to bill right now, read once for a page or a
|
||||||
* use case: the jobs, their unbilled hours and expenses, whose fixed price
|
* use case: the jobs, their unbilled hours and expenses, whose fixed price
|
||||||
* is already billed, the hourly rates and the VAT rate.
|
* and which monthly fees are already billed, the hourly rates, the VAT
|
||||||
|
* rate and the material's month.
|
||||||
*/
|
*/
|
||||||
final class BillingSnapshot
|
final class BillingSnapshot
|
||||||
{
|
{
|
||||||
@@ -39,6 +44,11 @@ final class BillingSnapshot
|
|||||||
|
|
||||||
public int $vatBasisPoints = 0;
|
public int $vatBasisPoints = 0;
|
||||||
|
|
||||||
|
/** @var array<int, list<string>> */
|
||||||
|
public array $billedMonths = [];
|
||||||
|
|
||||||
|
public string $period = '';
|
||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
private BillingJobs $billingJobs,
|
private BillingJobs $billingJobs,
|
||||||
private BillingHours $billingHours,
|
private BillingHours $billingHours,
|
||||||
@@ -49,12 +59,14 @@ final class BillingSnapshot
|
|||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
* @param string $period Y-m: the material's month.
|
||||||
* @param list<int> $jobIds
|
* @param list<int> $jobIds
|
||||||
* @param list<BillableJob> $knownJobs Jobs already read, e.g. the done ones.
|
* @param list<BillableJob> $knownJobs Jobs already read, e.g. the candidates.
|
||||||
*/
|
*/
|
||||||
public function load(array $jobIds, array $knownJobs = []): self
|
public function load(string $period, array $jobIds, array $knownJobs = []): self
|
||||||
{
|
{
|
||||||
$snapshot = clone $this;
|
$snapshot = clone $this;
|
||||||
|
$snapshot->period = $period;
|
||||||
|
|
||||||
foreach ($knownJobs as $job) {
|
foreach ($knownJobs as $job) {
|
||||||
$snapshot->jobs[$job->id] = $job;
|
$snapshot->jobs[$job->id] = $job;
|
||||||
@@ -67,6 +79,7 @@ final class BillingSnapshot
|
|||||||
$snapshot->hours = $this->billingHours->forJobs($ids);
|
$snapshot->hours = $this->billingHours->forJobs($ids);
|
||||||
$snapshot->expenses = $this->billingExpenses->forJobs($ids);
|
$snapshot->expenses = $this->billingExpenses->forJobs($ids);
|
||||||
$snapshot->fixedPriceBilled = array_fill_keys($this->exports->fixedPriceBilledJobIds($ids), true);
|
$snapshot->fixedPriceBilled = array_fill_keys($this->exports->fixedPriceBilledJobIds($ids), true);
|
||||||
|
$snapshot->billedMonths = $this->exports->billedMonths($ids);
|
||||||
$snapshot->rates = $this->prices->hourlyRates();
|
$snapshot->rates = $this->prices->hourlyRates();
|
||||||
$snapshot->vatBasisPoints = $this->prices->defaultVatBasisPoints();
|
$snapshot->vatBasisPoints = $this->prices->defaultVatBasisPoints();
|
||||||
|
|
||||||
@@ -93,7 +106,34 @@ final class BillingSnapshot
|
|||||||
|
|
||||||
public function reasonNotBillable(BillableJob $job): ?NotBillableReason
|
public function reasonNotBillable(BillableJob $job): ?NotBillableReason
|
||||||
{
|
{
|
||||||
return $this->rules->reasonNotBillable($job, $this->hoursOf($job->id), $this->expensesOf($job->id), $this->isFixedPriceBilled($job->id), $this->rates);
|
return $this->rules->reasonNotBillable($job, $this->hoursOf($job->id), $this->expensesOf($job->id), $this->isFixedPriceBilled($job->id), $this->rates, $this->unbilledMonthsOf($job));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The months (Y-m) a monthly fee job still has to bill up to the material's month.
|
||||||
|
*
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
public function unbilledMonthsOf(BillableJob $job): array
|
||||||
|
{
|
||||||
|
if ($job->mode !== BillingMode::MonthlyFee || $job->billingStartsOn === '') {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return BillingMonths::unbilled($job->billingStartsOn, $job->billingEndsOn, $this->period, $this->billedMonths[$job->id] ?? []);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The job's lines with the given hours and expenses (those just marked
|
||||||
|
* billed when the material is created).
|
||||||
|
*
|
||||||
|
* @param array<int, int> $approvedByWorkType
|
||||||
|
* @param list<BillableExpense> $expenses
|
||||||
|
* @return list<InvoiceLine>
|
||||||
|
*/
|
||||||
|
public function linesOf(BillableJob $job, DraftJob $draftJob, array $approvedByWorkType, array $expenses): array
|
||||||
|
{
|
||||||
|
return $this->rules->lines($job, $draftJob, $approvedByWorkType, $expenses, $this->isFixedPriceBilled($job->id), $this->rates, $this->vatBasisPoints, $this->unbilledMonthsOf($job));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -42,8 +42,8 @@ final class ExportViews
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
$done = $export->isDraft() ? $this->jobs->done() : [];
|
$candidates = $export->isDraft() ? $this->jobs->candidates() : [];
|
||||||
$snapshot = $this->snapshots->load($export->jobIds(), $done);
|
$snapshot = $this->snapshots->load($export->period(), $export->jobIds(), $candidates);
|
||||||
$onDraft = array_flip($export->jobIds());
|
$onDraft = array_flip($export->jobIds());
|
||||||
|
|
||||||
$invoices = [];
|
$invoices = [];
|
||||||
@@ -52,7 +52,7 @@ final class ExportViews
|
|||||||
}
|
}
|
||||||
|
|
||||||
$available = [];
|
$available = [];
|
||||||
foreach ($done as $job) {
|
foreach ($candidates as $job) {
|
||||||
if (! isset($onDraft[$job->id])) {
|
if (! isset($onDraft[$job->id])) {
|
||||||
$hours = $snapshot->hoursOf($job->id);
|
$hours = $snapshot->hoursOf($job->id);
|
||||||
$available[] = new AvailableJob(
|
$available[] = new AvailableJob(
|
||||||
@@ -71,6 +71,7 @@ final class ExportViews
|
|||||||
return new ExportView(
|
return new ExportView(
|
||||||
(int) $export->id(),
|
(int) $export->id(),
|
||||||
$export->status(),
|
$export->status(),
|
||||||
|
$export->period(),
|
||||||
$export->createdAt(),
|
$export->createdAt(),
|
||||||
$names[$export->createdBy()] ?? '',
|
$names[$export->createdBy()] ?? '',
|
||||||
$export->finalizedAt(),
|
$export->finalizedAt(),
|
||||||
@@ -121,7 +122,7 @@ final class ExportViews
|
|||||||
}
|
}
|
||||||
|
|
||||||
$hours = $snapshot->hoursOf($job->id);
|
$hours = $snapshot->hoursOf($job->id);
|
||||||
$lines = $snapshot->rules->lines($job, $draftJob, $hours->approvedByWorkType, $snapshot->expensesOf($job->id), $snapshot->isFixedPriceBilled($job->id), $snapshot->rates, $snapshot->vatBasisPoints);
|
$lines = $snapshot->linesOf($job, $draftJob, $hours->approvedByWorkType, $snapshot->expensesOf($job->id));
|
||||||
|
|
||||||
$rows = [];
|
$rows = [];
|
||||||
foreach ($snapshot->rules->sortedByName($hours->approvedByWorkType, $snapshot->rates) as $workTypeId => $approved) {
|
foreach ($snapshot->rules->sortedByName($hours->approvedByWorkType, $snapshot->rates) as $workTypeId => $approved) {
|
||||||
|
|||||||
@@ -15,7 +15,8 @@ use App\Modules\Billing\Domain\Exceptions\JobNotBillable;
|
|||||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds a done job to the draft as an invoice of its own, if it has
|
* Adds a done job (or a running monthly fee job) to the draft as an
|
||||||
|
* invoice of its own, if it has
|
||||||
* something to bill and nothing stops it from being billed.
|
* something to bill and nothing stops it from being billed.
|
||||||
*/
|
*/
|
||||||
final class AddJobToDraft
|
final class AddJobToDraft
|
||||||
@@ -40,7 +41,7 @@ final class AddJobToDraft
|
|||||||
public function execute(int $exportId, int $jobId): void
|
public function execute(int $exportId, int $jobId): void
|
||||||
{
|
{
|
||||||
$this->changeDraft($exportId, function (BillingExport $export) use ($jobId): void {
|
$this->changeDraft($exportId, function (BillingExport $export) use ($jobId): void {
|
||||||
$snapshot = $this->snapshots->load([$jobId]);
|
$snapshot = $this->snapshots->load($export->period(), [$jobId]);
|
||||||
$job = $snapshot->jobs[$jobId] ?? throw new JobNotBillable($jobId, NotBillableReason::WrongStatus);
|
$job = $snapshot->jobs[$jobId] ?? throw new JobNotBillable($jobId, NotBillableReason::WrongStatus);
|
||||||
$reason = $snapshot->reasonNotBillable($job);
|
$reason = $snapshot->reasonNotBillable($job);
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ use App\Modules\Billing\Application\Contracts\BillingJobs;
|
|||||||
use App\Modules\Billing\Application\DTOs\BillableExpense;
|
use App\Modules\Billing\Application\DTOs\BillableExpense;
|
||||||
use App\Modules\Billing\Application\Services\BillingSnapshot;
|
use App\Modules\Billing\Application\Services\BillingSnapshot;
|
||||||
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
|
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
|
||||||
|
use App\Modules\Billing\Domain\Enums\BillingMode;
|
||||||
use App\Modules\Billing\Domain\Enums\NotBillableReason;
|
use App\Modules\Billing\Domain\Enums\NotBillableReason;
|
||||||
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
|
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
|
||||||
use App\Modules\Billing\Domain\Exceptions\ExportEmpty;
|
use App\Modules\Billing\Domain\Exceptions\ExportEmpty;
|
||||||
@@ -22,7 +23,8 @@ use App\Modules\Users\Application\Contracts\Clock;
|
|||||||
* Creates the billing material from its draft (spec 12), all or nothing:
|
* Creates the billing material from its draft (spec 12), all or nothing:
|
||||||
* checks every job again, marks the approved hours and billable expenses
|
* checks every job again, marks the approved hours and billable expenses
|
||||||
* billed, forms the invoice lines from what was marked with the current
|
* billed, forms the invoice lines from what was marked with the current
|
||||||
* prices, and moves the jobs to "Lasku luotu".
|
* prices, and moves the jobs to "Lasku luotu". Monthly fee jobs keep
|
||||||
|
* running, so their status stays.
|
||||||
*/
|
*/
|
||||||
final class FinalizeBillingExport
|
final class FinalizeBillingExport
|
||||||
{
|
{
|
||||||
@@ -50,7 +52,7 @@ final class FinalizeBillingExport
|
|||||||
$export = $this->exports->findById($exportId, lock: true) ?? throw new BillingExportNotFound($exportId);
|
$export = $this->exports->findById($exportId, lock: true) ?? throw new BillingExportNotFound($exportId);
|
||||||
$export->ensureDraft();
|
$export->ensureDraft();
|
||||||
|
|
||||||
$snapshot = $this->snapshots->load($export->jobIds());
|
$snapshot = $this->snapshots->load($export->period(), $export->jobIds());
|
||||||
|
|
||||||
foreach ($export->jobIds() as $jobId) {
|
foreach ($export->jobIds() as $jobId) {
|
||||||
$job = $snapshot->jobs[$jobId] ?? throw new JobNotBillable($jobId, NotBillableReason::WrongStatus);
|
$job = $snapshot->jobs[$jobId] ?? throw new JobNotBillable($jobId, NotBillableReason::WrongStatus);
|
||||||
@@ -72,8 +74,11 @@ final class FinalizeBillingExport
|
|||||||
fn (BillableExpense $expense): bool => isset($billedExpenseIds[$expense->id]),
|
fn (BillableExpense $expense): bool => isset($billedExpenseIds[$expense->id]),
|
||||||
));
|
));
|
||||||
|
|
||||||
$linesByJob[$job->id] = $snapshot->rules->lines($job, $draftJob, $billedHours, $billedExpenses, $snapshot->isFixedPriceBilled($job->id), $snapshot->rates, $snapshot->vatBasisPoints);
|
$linesByJob[$job->id] = $snapshot->linesOf($job, $draftJob, $billedHours, $billedExpenses);
|
||||||
$this->jobs->markInvoiced($job->id, $actorUserId);
|
|
||||||
|
if ($job->mode !== BillingMode::MonthlyFee) {
|
||||||
|
$this->jobs->markInvoiced($job->id, $actorUserId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
$export->finalize($linesByJob, $actorUserId, $this->clock->now());
|
$export->finalize($linesByJob, $actorUserId, $this->clock->now());
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ declare(strict_types=1);
|
|||||||
|
|
||||||
namespace App\Modules\Billing\Application\UseCases;
|
namespace App\Modules\Billing\Application\UseCases;
|
||||||
|
|
||||||
|
use App\Modules\Billing\Application\Contracts\BillingJobs;
|
||||||
|
use App\Modules\Billing\Application\Services\BillingSnapshot;
|
||||||
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
|
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
|
||||||
use App\Modules\Billing\Domain\Entities\BillingExport;
|
use App\Modules\Billing\Domain\Entities\BillingExport;
|
||||||
use App\Modules\Billing\Domain\Exceptions\DraftAlreadyOpen;
|
use App\Modules\Billing\Domain\Exceptions\DraftAlreadyOpen;
|
||||||
@@ -11,13 +13,17 @@ use App\Modules\Shared\Application\Contracts\TransactionManager;
|
|||||||
use App\Modules\Users\Application\Contracts\Clock;
|
use App\Modules\Users\Application\Contracts\Clock;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Opens a new billing material draft. There is one draft at a time, so
|
* Opens a new billing material draft for the current month, with every
|
||||||
* two people never bill the same jobs on separate drafts.
|
* monthly fee job that has something to bill already on it (spec 5.5),
|
||||||
|
* each an invoice of its own. There is one draft at a time, so two people
|
||||||
|
* never bill the same jobs on separate drafts.
|
||||||
*/
|
*/
|
||||||
final class OpenBillingDraft
|
final class OpenBillingDraft
|
||||||
{
|
{
|
||||||
public function __construct(
|
public function __construct(
|
||||||
private BillingExportRepository $exports,
|
private BillingExportRepository $exports,
|
||||||
|
private BillingJobs $jobs,
|
||||||
|
private BillingSnapshot $snapshots,
|
||||||
private TransactionManager $transactions,
|
private TransactionManager $transactions,
|
||||||
private Clock $clock,
|
private Clock $clock,
|
||||||
) {}
|
) {}
|
||||||
@@ -34,7 +40,17 @@ final class OpenBillingDraft
|
|||||||
throw new DraftAlreadyOpen;
|
throw new DraftAlreadyOpen;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (int) $this->exports->save(BillingExport::startDraft($actorUserId, $this->clock->now()))->id();
|
$export = BillingExport::startDraft($actorUserId, $this->clock->today());
|
||||||
|
$monthly = $this->jobs->monthly();
|
||||||
|
$snapshot = $this->snapshots->load($export->period(), [], $monthly);
|
||||||
|
|
||||||
|
foreach ($monthly as $job) {
|
||||||
|
if ($snapshot->reasonNotBillable($job) === null) {
|
||||||
|
$export->addJob($job->toDraftJob());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (int) $this->exports->save($export)->id();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Modules\Billing\Application\UseCases;
|
||||||
|
|
||||||
|
use App\Modules\Billing\Domain\Contracts\BillingExportRepository;
|
||||||
|
use App\Modules\Billing\Domain\Entities\BillingExport;
|
||||||
|
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
|
||||||
|
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
|
||||||
|
use App\Modules\Billing\Domain\Exceptions\InvalidBillingPeriod;
|
||||||
|
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the month (Y-m) up to which the draft bills monthly fees.
|
||||||
|
*/
|
||||||
|
final class SetBillingPeriod
|
||||||
|
{
|
||||||
|
use ChangesDraft;
|
||||||
|
|
||||||
|
public function __construct(BillingExportRepository $exports, TransactionManager $transactions)
|
||||||
|
{
|
||||||
|
$this->exports = $exports;
|
||||||
|
$this->transactions = $transactions;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws BillingExportNotFound
|
||||||
|
* @throws ExportNotDraft
|
||||||
|
* @throws InvalidBillingPeriod
|
||||||
|
*/
|
||||||
|
public function execute(int $exportId, string $period): void
|
||||||
|
{
|
||||||
|
$this->changeDraft($exportId, function (BillingExport $export) use ($period): void {
|
||||||
|
$export->changePeriod($period);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -33,4 +33,12 @@ interface BillingExportRepository
|
|||||||
* @return list<int>
|
* @return list<int>
|
||||||
*/
|
*/
|
||||||
public function fixedPriceBilledJobIds(array $jobIds): array;
|
public function fixedPriceBilledJobIds(array $jobIds): array;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The months (Y-m) whose monthly fee is on a created material, by job.
|
||||||
|
*
|
||||||
|
* @param list<int> $jobIds
|
||||||
|
* @return array<int, list<string>>
|
||||||
|
*/
|
||||||
|
public function billedMonths(array $jobIds): array;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +8,11 @@ use App\Modules\Billing\Domain\Enums\ExportStatus;
|
|||||||
use App\Modules\Billing\Domain\Exceptions\ExportEmpty;
|
use App\Modules\Billing\Domain\Exceptions\ExportEmpty;
|
||||||
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
|
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
|
||||||
use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours;
|
use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours;
|
||||||
|
use App\Modules\Billing\Domain\Exceptions\InvalidBillingPeriod;
|
||||||
use App\Modules\Billing\Domain\Exceptions\InvoicesCannotMerge;
|
use App\Modules\Billing\Domain\Exceptions\InvoicesCannotMerge;
|
||||||
use App\Modules\Billing\Domain\Exceptions\JobAlreadyInDraft;
|
use App\Modules\Billing\Domain\Exceptions\JobAlreadyInDraft;
|
||||||
use App\Modules\Billing\Domain\Exceptions\JobNotInDraft;
|
use App\Modules\Billing\Domain\Exceptions\JobNotInDraft;
|
||||||
|
use App\Modules\Billing\Domain\ValueObjects\BillingMonths;
|
||||||
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
|
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
|
||||||
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
|
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
|
||||||
use DateTimeImmutable;
|
use DateTimeImmutable;
|
||||||
@@ -29,6 +31,7 @@ final class BillingExport
|
|||||||
private function __construct(
|
private function __construct(
|
||||||
private ?int $id,
|
private ?int $id,
|
||||||
private ExportStatus $status,
|
private ExportStatus $status,
|
||||||
|
private string $period,
|
||||||
private int $createdBy,
|
private int $createdBy,
|
||||||
private DateTimeImmutable $createdAt,
|
private DateTimeImmutable $createdAt,
|
||||||
private ?int $finalizedBy,
|
private ?int $finalizedBy,
|
||||||
@@ -36,17 +39,37 @@ final class BillingExport
|
|||||||
private array $invoices,
|
private array $invoices,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A new draft billing monthly fees up to the current month.
|
||||||
|
*/
|
||||||
public static function startDraft(int $createdBy, DateTimeImmutable $now): self
|
public static function startDraft(int $createdBy, DateTimeImmutable $now): self
|
||||||
{
|
{
|
||||||
return new self(null, ExportStatus::Draft, $createdBy, $now, null, null, []);
|
return new self(null, ExportStatus::Draft, $now->format('Y-m'), $createdBy, $now, null, null, []);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param list<BillingInvoice> $invoices
|
* @param list<BillingInvoice> $invoices
|
||||||
*/
|
*/
|
||||||
public static function reconstitute(int $id, ExportStatus $status, int $createdBy, DateTimeImmutable $createdAt, ?int $finalizedBy, ?DateTimeImmutable $finalizedAt, array $invoices): self
|
public static function reconstitute(int $id, ExportStatus $status, string $period, int $createdBy, DateTimeImmutable $createdAt, ?int $finalizedBy, ?DateTimeImmutable $finalizedAt, array $invoices): self
|
||||||
{
|
{
|
||||||
return new self($id, $status, $createdBy, $createdAt, $finalizedBy, $finalizedAt, $invoices);
|
return new self($id, $status, $period, $createdBy, $createdAt, $finalizedBy, $finalizedAt, $invoices);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets the month (Y-m) up to which monthly fees are billed.
|
||||||
|
*
|
||||||
|
* @throws ExportNotDraft
|
||||||
|
* @throws InvalidBillingPeriod
|
||||||
|
*/
|
||||||
|
public function changePeriod(string $period): void
|
||||||
|
{
|
||||||
|
$this->ensureDraft();
|
||||||
|
$this->period = BillingMonths::ensureValid($period);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function period(): string
|
||||||
|
{
|
||||||
|
return $this->period;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -50,6 +50,10 @@ final class BillingInvoice
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($other->ownInvoice || $job->ownInvoice) {
|
||||||
|
return MergeRefusal::MonthlyFeeAlone;
|
||||||
|
}
|
||||||
|
|
||||||
if ($other->customerId !== $job->customerId) {
|
if ($other->customerId !== $job->customerId) {
|
||||||
return MergeRefusal::DifferentCustomer;
|
return MergeRefusal::DifferentCustomer;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,11 +5,13 @@ declare(strict_types=1);
|
|||||||
namespace App\Modules\Billing\Domain\Enums;
|
namespace App\Modules\Billing\Domain\Enums;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* How a job is billed: its hours per work type at the hourly rates, or its
|
* How a job is billed: its hours per work type at the hourly rates, its
|
||||||
* quoted fixed price as one line. Expenses are billed separately either way.
|
* quoted fixed price as one line, or its monthly fee for every month.
|
||||||
|
* Expenses are billed separately in every case.
|
||||||
*/
|
*/
|
||||||
enum BillingMode: string
|
enum BillingMode: string
|
||||||
{
|
{
|
||||||
case Hours = 'hours';
|
case Hours = 'hours';
|
||||||
case FixedPrice = 'fixed_price';
|
case FixedPrice = 'fixed_price';
|
||||||
|
case MonthlyFee = 'monthly_fee';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,4 +12,5 @@ enum LineKind: string
|
|||||||
case Hours = 'hours';
|
case Hours = 'hours';
|
||||||
case FixedPrice = 'fixed_price';
|
case FixedPrice = 'fixed_price';
|
||||||
case Expense = 'expense';
|
case Expense = 'expense';
|
||||||
|
case MonthlyFee = 'monthly_fee';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,4 +12,7 @@ enum MergeRefusal: string
|
|||||||
case DifferentCustomer = 'different_customer';
|
case DifferentCustomer = 'different_customer';
|
||||||
case DifferentBillingUnit = 'different_billing_unit';
|
case DifferentBillingUnit = 'different_billing_unit';
|
||||||
case DifferentReference = 'different_reference';
|
case DifferentReference = 'different_reference';
|
||||||
|
|
||||||
|
/** Monthly fee contracts are billed on invoices of their own (K22). */
|
||||||
|
case MonthlyFeeAlone = 'monthly_fee_alone';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,10 +9,10 @@ namespace App\Modules\Billing\Domain\Enums;
|
|||||||
*/
|
*/
|
||||||
enum NotBillableReason: string
|
enum NotBillableReason: string
|
||||||
{
|
{
|
||||||
/** The job is not done. */
|
/** The job is not done (or for a monthly fee, not running). */
|
||||||
case WrongStatus = 'wrong_status';
|
case WrongStatus = 'wrong_status';
|
||||||
|
|
||||||
/** Not billable, billed monthly, or the internal customer. */
|
/** Not billable, or the internal customer. */
|
||||||
case NotBillableBasis = 'not_billable_basis';
|
case NotBillableBasis = 'not_billable_basis';
|
||||||
|
|
||||||
/** A consumer customer without a personal identity code. */
|
/** A consumer customer without a personal identity code. */
|
||||||
@@ -24,6 +24,9 @@ enum NotBillableReason: string
|
|||||||
/** A fixed price job without a quoted amount. */
|
/** A fixed price job without a quoted amount. */
|
||||||
case MissingQuotedAmount = 'missing_quoted_amount';
|
case MissingQuotedAmount = 'missing_quoted_amount';
|
||||||
|
|
||||||
/** No approved hours, expenses or fixed price left to bill. */
|
/** A monthly fee job without a monthly fee. */
|
||||||
|
case MissingMonthlyFee = 'missing_monthly_fee';
|
||||||
|
|
||||||
|
/** No approved hours, expenses, fixed price or months left to bill. */
|
||||||
case NothingToBill = 'nothing_to_bill';
|
case NothingToBill = 'nothing_to_bill';
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Modules\Billing\Domain\Exceptions;
|
||||||
|
|
||||||
|
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||||
|
|
||||||
|
final class InvalidBillingPeriod extends DomainException
|
||||||
|
{
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
parent::__construct('The billing month is invalid.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Modules\Billing\Domain\ValueObjects;
|
||||||
|
|
||||||
|
use App\Modules\Billing\Domain\Exceptions\InvalidBillingPeriod;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The months a monthly fee job still has to bill (spec 5.5): from the month
|
||||||
|
* it starts to the material's month, or to the month it ends or was done
|
||||||
|
* if that is earlier, leaving out months already billed. Months are Y-m.
|
||||||
|
*/
|
||||||
|
final class BillingMonths
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* @param string $startsOn Y-m-d: the job's start (or creation) day.
|
||||||
|
* @param string|null $endsOn Y-m-d: the job's last day or completion day, if any.
|
||||||
|
* @param string $period Y-m: the material's month.
|
||||||
|
* @param list<string> $billed Months billed before, as Y-m.
|
||||||
|
* @return list<string>
|
||||||
|
*/
|
||||||
|
public static function unbilled(string $startsOn, ?string $endsOn, string $period, array $billed): array
|
||||||
|
{
|
||||||
|
$end = $endsOn === null ? $period : min($period, substr($endsOn, 0, 7));
|
||||||
|
$billedMonths = array_flip($billed);
|
||||||
|
$months = [];
|
||||||
|
|
||||||
|
for ($month = substr($startsOn, 0, 7); $month <= $end; $month = self::next($month)) {
|
||||||
|
if (! isset($billedMonths[$month])) {
|
||||||
|
$months[] = $month;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $months;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws InvalidBillingPeriod
|
||||||
|
*/
|
||||||
|
public static function ensureValid(string $period): string
|
||||||
|
{
|
||||||
|
if (preg_match('/^(\d{4})-(0[1-9]|1[0-2])$/', $period) !== 1) {
|
||||||
|
throw new InvalidBillingPeriod;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $period;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "11/2026" for "2026-11".
|
||||||
|
*/
|
||||||
|
public static function label(string $month): string
|
||||||
|
{
|
||||||
|
return ((int) substr($month, 5, 2)).'/'.substr($month, 0, 4);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static function next(string $month): string
|
||||||
|
{
|
||||||
|
$year = (int) substr($month, 0, 4);
|
||||||
|
$number = (int) substr($month, 5, 2) + 1;
|
||||||
|
|
||||||
|
if ($number > 12) {
|
||||||
|
$year++;
|
||||||
|
$number = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return sprintf('%04d-%02d', $year, $number);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,7 @@ use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours;
|
|||||||
* A job on a draft invoice: who it bills (customer, billing unit, the
|
* A job on a draft invoice: who it bills (customer, billing unit, the
|
||||||
* customer's reference) and management's billable hours per work type.
|
* customer's reference) and management's billable hours per work type.
|
||||||
* A work type without its own billable hours bills its approved hours.
|
* A work type without its own billable hours bills its approved hours.
|
||||||
|
* A monthly fee job is always an invoice of its own.
|
||||||
*/
|
*/
|
||||||
final readonly class DraftJob
|
final readonly class DraftJob
|
||||||
{
|
{
|
||||||
@@ -25,6 +26,7 @@ final readonly class DraftJob
|
|||||||
public ?int $billingUnitId,
|
public ?int $billingUnitId,
|
||||||
public ?string $reference,
|
public ?string $reference,
|
||||||
public array $billableQuarters = [],
|
public array $billableQuarters = [],
|
||||||
|
public bool $ownInvoice = false,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -42,7 +44,7 @@ final readonly class DraftJob
|
|||||||
$billable[$workTypeId] = $quarters;
|
$billable[$workTypeId] = $quarters;
|
||||||
}
|
}
|
||||||
|
|
||||||
return new self($this->jobId, $this->customerId, $this->billingUnitId, $this->reference, $billable);
|
return new self($this->jobId, $this->customerId, $this->billingUnitId, $this->reference, $billable, $this->ownInvoice);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ use App\Modules\Billing\Domain\Enums\LineKind;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* A line of an invoice, without VAT: a work type's billable hours at its
|
* A line of an invoice, without VAT: a work type's billable hours at its
|
||||||
* hourly rate, a job's fixed price, or an expense. Prices and descriptions
|
* hourly rate, a job's fixed price, a month's fee, or an expense. Prices and descriptions
|
||||||
* are snapshots taken when the material is formed.
|
* are snapshots taken when the material is formed.
|
||||||
*/
|
*/
|
||||||
final readonly class InvoiceLine
|
final readonly class InvoiceLine
|
||||||
@@ -24,6 +24,7 @@ final readonly class InvoiceLine
|
|||||||
public int $unitPriceCents,
|
public int $unitPriceCents,
|
||||||
public int $vatBasisPoints,
|
public int $vatBasisPoints,
|
||||||
public int $netCents,
|
public int $netCents,
|
||||||
|
public ?string $period = null,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -51,6 +52,14 @@ final readonly class InvoiceLine
|
|||||||
return new self($jobId, LineKind::FixedPrice, null, null, $description, null, null, $amountCents, $vatBasisPoints, $amountCents);
|
return new self($jobId, LineKind::FixedPrice, null, null, $description, null, null, $amountCents, $vatBasisPoints, $amountCents);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The fee of one month (Y-m).
|
||||||
|
*/
|
||||||
|
public static function monthlyFee(int $jobId, string $period, string $description, int $amountCents, int $vatBasisPoints): self
|
||||||
|
{
|
||||||
|
return new self($jobId, LineKind::MonthlyFee, null, null, $description, null, null, $amountCents, $vatBasisPoints, $amountCents, $period);
|
||||||
|
}
|
||||||
|
|
||||||
public static function expense(int $jobId, int $expenseId, string $description, int $amountCents, int $vatBasisPoints): self
|
public static function expense(int $jobId, int $expenseId, string $description, int $amountCents, int $vatBasisPoints): self
|
||||||
{
|
{
|
||||||
return new self($jobId, LineKind::Expense, null, $expenseId, $description, null, null, $amountCents, $vatBasisPoints, $amountCents);
|
return new self($jobId, LineKind::Expense, null, $expenseId, $description, null, null, $amountCents, $vatBasisPoints, $amountCents);
|
||||||
|
|||||||
@@ -21,15 +21,30 @@ use App\Modules\Jobs\Domain\Enums\PaymentBasis;
|
|||||||
*/
|
*/
|
||||||
class JobsForBilling implements BillingJobs
|
class JobsForBilling implements BillingJobs
|
||||||
{
|
{
|
||||||
|
/** Statuses in which a monthly fee job is billed: running or done. */
|
||||||
|
private const array MONTHLY_STATUSES = [JobStatus::Order, JobStatus::InProduction, JobStatus::OnHold, JobStatus::Done];
|
||||||
|
|
||||||
public function __construct(
|
public function __construct(
|
||||||
private CustomerJobQueries $jobs,
|
private CustomerJobQueries $jobs,
|
||||||
private CustomerQueries $customers,
|
private CustomerQueries $customers,
|
||||||
private ChangeJobStatus $changeStatus,
|
private ChangeJobStatus $changeStatus,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
public function done(): array
|
public function candidates(): array
|
||||||
{
|
{
|
||||||
return $this->toBillable($this->jobs->billingInfoWithStatus(JobStatus::Done));
|
$jobs = [];
|
||||||
|
foreach ([...$this->jobs->billingInfoWithStatus(JobStatus::Done), ...$this->jobs->billingInfoMonthly()] as $job) {
|
||||||
|
$jobs[$job->id] = $job;
|
||||||
|
}
|
||||||
|
|
||||||
|
uasort($jobs, fn (JobBillingInfo $a, JobBillingInfo $b): int => strcmp($a->number, $b->number));
|
||||||
|
|
||||||
|
return $this->toBillable(array_values($jobs));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function monthly(): array
|
||||||
|
{
|
||||||
|
return $this->toBillable($this->jobs->billingInfoMonthly());
|
||||||
}
|
}
|
||||||
|
|
||||||
public function find(array $jobIds): array
|
public function find(array $jobIds): array
|
||||||
@@ -65,6 +80,13 @@ class JobsForBilling implements BillingJobs
|
|||||||
|
|
||||||
return array_map(function (JobBillingInfo $job) use ($customers): BillableJob {
|
return array_map(function (JobBillingInfo $job) use ($customers): BillableJob {
|
||||||
$customer = $customers[$job->customerId] ?? null;
|
$customer = $customers[$job->customerId] ?? null;
|
||||||
|
$mode = match ($job->paymentBasis) {
|
||||||
|
PaymentBasis::FixedQuote => BillingMode::FixedPrice,
|
||||||
|
PaymentBasis::MonthlyFee => BillingMode::MonthlyFee,
|
||||||
|
PaymentBasis::NotBillable => null,
|
||||||
|
default => BillingMode::Hours,
|
||||||
|
};
|
||||||
|
$ends = array_filter([$job->dueOn, $job->completedOn]);
|
||||||
|
|
||||||
return new BillableJob(
|
return new BillableJob(
|
||||||
$job->id,
|
$job->id,
|
||||||
@@ -78,13 +100,12 @@ class JobsForBilling implements BillingJobs
|
|||||||
$job->billingUnitId,
|
$job->billingUnitId,
|
||||||
$job->billingUnitName,
|
$job->billingUnitName,
|
||||||
$job->customerReference,
|
$job->customerReference,
|
||||||
match ($job->paymentBasis) {
|
$mode,
|
||||||
PaymentBasis::FixedQuote => BillingMode::FixedPrice,
|
|
||||||
PaymentBasis::NotBillable, PaymentBasis::MonthlyFee => null,
|
|
||||||
default => BillingMode::Hours,
|
|
||||||
},
|
|
||||||
$job->quotedAmountCents,
|
$job->quotedAmountCents,
|
||||||
$job->status === JobStatus::Done,
|
$mode === BillingMode::MonthlyFee ? in_array($job->status, self::MONTHLY_STATUSES, true) : $job->status === JobStatus::Done,
|
||||||
|
$job->monthlyFeeCents,
|
||||||
|
$job->startsOn ?? $job->createdOn,
|
||||||
|
$ends === [] ? null : min($ends),
|
||||||
);
|
);
|
||||||
}, $jobs);
|
}, $jobs);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,13 +14,14 @@ use Illuminate\Support\Carbon;
|
|||||||
*
|
*
|
||||||
* @property int $id
|
* @property int $id
|
||||||
* @property ExportStatus $status
|
* @property ExportStatus $status
|
||||||
|
* @property string|null $period Y-m
|
||||||
* @property int $created_by
|
* @property int $created_by
|
||||||
* @property int|null $finalized_by
|
* @property int|null $finalized_by
|
||||||
* @property Carbon|null $finalized_at
|
* @property Carbon|null $finalized_at
|
||||||
* @property Carbon $created_at
|
* @property Carbon $created_at
|
||||||
*/
|
*/
|
||||||
#[Table('billing_exports')]
|
#[Table('billing_exports')]
|
||||||
#[Fillable(['status', 'created_by', 'finalized_by', 'finalized_at'])]
|
#[Fillable(['status', 'period', 'created_by', 'finalized_by', 'finalized_at'])]
|
||||||
class BillingExportModel extends Model
|
class BillingExportModel extends Model
|
||||||
{
|
{
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -18,10 +18,11 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
|||||||
* @property int $customer_id
|
* @property int $customer_id
|
||||||
* @property int|null $billing_unit_id
|
* @property int|null $billing_unit_id
|
||||||
* @property string|null $customer_reference
|
* @property string|null $customer_reference
|
||||||
|
* @property bool $own_invoice
|
||||||
* @property int $sort_order
|
* @property int $sort_order
|
||||||
*/
|
*/
|
||||||
#[Table('billing_invoice_jobs')]
|
#[Table('billing_invoice_jobs')]
|
||||||
#[Fillable(['billing_invoice_id', 'customer_job_id', 'customer_id', 'billing_unit_id', 'customer_reference', 'sort_order'])]
|
#[Fillable(['billing_invoice_id', 'customer_job_id', 'customer_id', 'billing_unit_id', 'customer_reference', 'own_invoice', 'sort_order'])]
|
||||||
class BillingInvoiceJobModel extends Model
|
class BillingInvoiceJobModel extends Model
|
||||||
{
|
{
|
||||||
public $timestamps = false;
|
public $timestamps = false;
|
||||||
@@ -44,6 +45,7 @@ class BillingInvoiceJobModel extends Model
|
|||||||
'customer_job_id' => 'integer',
|
'customer_job_id' => 'integer',
|
||||||
'customer_id' => 'integer',
|
'customer_id' => 'integer',
|
||||||
'billing_unit_id' => 'integer',
|
'billing_unit_id' => 'integer',
|
||||||
|
'own_invoice' => 'boolean',
|
||||||
'sort_order' => 'integer',
|
'sort_order' => 'integer',
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ use Illuminate\Database\Eloquent\Model;
|
|||||||
* @property LineKind $kind
|
* @property LineKind $kind
|
||||||
* @property int|null $work_type_id
|
* @property int|null $work_type_id
|
||||||
* @property int|null $expense_id
|
* @property int|null $expense_id
|
||||||
|
* @property string|null $period Y-m
|
||||||
* @property string $description
|
* @property string $description
|
||||||
* @property int|null $recorded_quarters
|
* @property int|null $recorded_quarters
|
||||||
* @property int|null $quantity_quarters
|
* @property int|null $quantity_quarters
|
||||||
@@ -26,7 +27,7 @@ use Illuminate\Database\Eloquent\Model;
|
|||||||
*/
|
*/
|
||||||
#[Table('billing_lines')]
|
#[Table('billing_lines')]
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'billing_invoice_id', 'customer_job_id', 'kind', 'work_type_id', 'expense_id', 'description',
|
'billing_invoice_id', 'customer_job_id', 'kind', 'work_type_id', 'expense_id', 'period', 'description',
|
||||||
'recorded_quarters', 'quantity_quarters', 'unit_price_cents', 'vat_basis_points', 'net_cents', 'sort_order',
|
'recorded_quarters', 'quantity_quarters', 'unit_price_cents', 'vat_basis_points', 'net_cents', 'sort_order',
|
||||||
])]
|
])]
|
||||||
class BillingLineModel extends Model
|
class BillingLineModel extends Model
|
||||||
|
|||||||
+21
@@ -46,6 +46,7 @@ class EloquentBillingExportRepository implements BillingExportRepository
|
|||||||
|
|
||||||
$model->fill([
|
$model->fill([
|
||||||
'status' => $export->status(),
|
'status' => $export->status(),
|
||||||
|
'period' => $export->period(),
|
||||||
'created_by' => $export->createdBy(),
|
'created_by' => $export->createdBy(),
|
||||||
'finalized_by' => $export->finalizedBy(),
|
'finalized_by' => $export->finalizedBy(),
|
||||||
'finalized_at' => $export->finalizedAt()?->format('Y-m-d H:i:s'),
|
'finalized_at' => $export->finalizedAt()?->format('Y-m-d H:i:s'),
|
||||||
@@ -75,6 +76,7 @@ class EloquentBillingExportRepository implements BillingExportRepository
|
|||||||
'customer_id' => $job->customerId,
|
'customer_id' => $job->customerId,
|
||||||
'billing_unit_id' => $job->billingUnitId,
|
'billing_unit_id' => $job->billingUnitId,
|
||||||
'customer_reference' => $job->reference,
|
'customer_reference' => $job->reference,
|
||||||
|
'own_invoice' => $job->ownInvoice,
|
||||||
'sort_order' => $jobOrder,
|
'sort_order' => $jobOrder,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -94,6 +96,7 @@ class EloquentBillingExportRepository implements BillingExportRepository
|
|||||||
'kind' => $line->kind,
|
'kind' => $line->kind,
|
||||||
'work_type_id' => $line->workTypeId,
|
'work_type_id' => $line->workTypeId,
|
||||||
'expense_id' => $line->expenseId,
|
'expense_id' => $line->expenseId,
|
||||||
|
'period' => $line->period,
|
||||||
'description' => mb_substr($line->description, 0, 255),
|
'description' => mb_substr($line->description, 0, 255),
|
||||||
'recorded_quarters' => $line->recordedQuarters,
|
'recorded_quarters' => $line->recordedQuarters,
|
||||||
'quantity_quarters' => $line->quantityQuarters,
|
'quantity_quarters' => $line->quantityQuarters,
|
||||||
@@ -129,6 +132,21 @@ class EloquentBillingExportRepository implements BillingExportRepository
|
|||||||
->all();
|
->all();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function billedMonths(array $jobIds): array
|
||||||
|
{
|
||||||
|
if ($jobIds === []) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
$months = [];
|
||||||
|
|
||||||
|
foreach (BillingLineModel::query()->whereIn('customer_job_id', $jobIds)->where('kind', LineKind::MonthlyFee)->whereNotNull('period')->get(['customer_job_id', 'period']) as $line) {
|
||||||
|
$months[$line->customer_job_id][] = (string) $line->period;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $months;
|
||||||
|
}
|
||||||
|
|
||||||
private function toEntity(BillingExportModel $model): BillingExport
|
private function toEntity(BillingExportModel $model): BillingExport
|
||||||
{
|
{
|
||||||
$invoices = $model->invoices->map(fn (BillingInvoiceModel $invoice): BillingInvoice => BillingInvoice::reconstitute(
|
$invoices = $model->invoices->map(fn (BillingInvoiceModel $invoice): BillingInvoice => BillingInvoice::reconstitute(
|
||||||
@@ -138,6 +156,7 @@ class EloquentBillingExportRepository implements BillingExportRepository
|
|||||||
$job->billing_unit_id,
|
$job->billing_unit_id,
|
||||||
$job->customer_reference,
|
$job->customer_reference,
|
||||||
$job->hours->mapWithKeys(fn (BillingJobHoursModel $hours): array => [$hours->work_type_id => $hours->billable_quarters])->all(),
|
$job->hours->mapWithKeys(fn (BillingJobHoursModel $hours): array => [$hours->work_type_id => $hours->billable_quarters])->all(),
|
||||||
|
$job->own_invoice,
|
||||||
))->values()->all(),
|
))->values()->all(),
|
||||||
$invoice->lines->map(fn (BillingLineModel $line): InvoiceLine => new InvoiceLine(
|
$invoice->lines->map(fn (BillingLineModel $line): InvoiceLine => new InvoiceLine(
|
||||||
$line->customer_job_id,
|
$line->customer_job_id,
|
||||||
@@ -150,12 +169,14 @@ class EloquentBillingExportRepository implements BillingExportRepository
|
|||||||
$line->unit_price_cents,
|
$line->unit_price_cents,
|
||||||
$line->vat_basis_points,
|
$line->vat_basis_points,
|
||||||
$line->net_cents,
|
$line->net_cents,
|
||||||
|
$line->period,
|
||||||
))->values()->all(),
|
))->values()->all(),
|
||||||
))->values()->all();
|
))->values()->all();
|
||||||
|
|
||||||
return BillingExport::reconstitute(
|
return BillingExport::reconstitute(
|
||||||
$model->id,
|
$model->id,
|
||||||
$model->status,
|
$model->status,
|
||||||
|
$model->period ?? $model->created_at->format('Y-m'),
|
||||||
$model->created_by,
|
$model->created_by,
|
||||||
DateTimeImmutable::createFromInterface($model->created_at),
|
DateTimeImmutable::createFromInterface($model->created_at),
|
||||||
$model->finalized_by,
|
$model->finalized_by,
|
||||||
|
|||||||
@@ -10,12 +10,15 @@ use App\Modules\Billing\Application\UseCases\MoveJobToInvoice;
|
|||||||
use App\Modules\Billing\Application\UseCases\RemoveJobFromDraft;
|
use App\Modules\Billing\Application\UseCases\RemoveJobFromDraft;
|
||||||
use App\Modules\Billing\Application\UseCases\SeparateJob;
|
use App\Modules\Billing\Application\UseCases\SeparateJob;
|
||||||
use App\Modules\Billing\Application\UseCases\SetBillableHours;
|
use App\Modules\Billing\Application\UseCases\SetBillableHours;
|
||||||
|
use App\Modules\Billing\Application\UseCases\SetBillingPeriod;
|
||||||
use App\Modules\Billing\Domain\Enums\BillingMode;
|
use App\Modules\Billing\Domain\Enums\BillingMode;
|
||||||
use App\Modules\Billing\Domain\Enums\LineKind;
|
use App\Modules\Billing\Domain\Enums\LineKind;
|
||||||
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
|
use App\Modules\Billing\Domain\Exceptions\BillingExportNotFound;
|
||||||
use App\Modules\Billing\Domain\Exceptions\ExportEmpty;
|
use App\Modules\Billing\Domain\Exceptions\ExportEmpty;
|
||||||
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
|
use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
|
||||||
use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours;
|
use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours;
|
||||||
|
use App\Modules\Billing\Domain\Exceptions\InvalidBillingPeriod;
|
||||||
|
use App\Modules\Billing\Domain\ValueObjects\BillingMonths;
|
||||||
use App\Modules\Billing\Domain\Exceptions\InvoicesCannotMerge;
|
use App\Modules\Billing\Domain\Exceptions\InvoicesCannotMerge;
|
||||||
use App\Modules\Billing\Domain\Exceptions\JobAlreadyInDraft;
|
use App\Modules\Billing\Domain\Exceptions\JobAlreadyInDraft;
|
||||||
use App\Modules\Billing\Domain\Exceptions\JobNotBillable;
|
use App\Modules\Billing\Domain\Exceptions\JobNotBillable;
|
||||||
@@ -120,6 +123,26 @@ new class extends Component
|
|||||||
unset($this->export);
|
unset($this->export);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function savePeriod(string $value, SetBillingPeriod $setBillingPeriod): void
|
||||||
|
{
|
||||||
|
$this->authorize('billing.manage');
|
||||||
|
$this->resetErrorBag('period');
|
||||||
|
$this->statusMessage = '';
|
||||||
|
$this->errorMessage = '';
|
||||||
|
|
||||||
|
try {
|
||||||
|
$setBillingPeriod->execute($this->exportId, mb_substr(trim($value), 0, 7));
|
||||||
|
unset($this->export);
|
||||||
|
$this->statusMessage = __('billing.export.period_saved', ['month' => BillingMonths::label($this->export->period)]);
|
||||||
|
} catch (InvalidBillingPeriod) {
|
||||||
|
$this->addError('period', __('billing.errors.period'));
|
||||||
|
} catch (ExportNotDraft|BillingExportNotFound $exception) {
|
||||||
|
$this->errorMessage = $this->errorText($exception, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
unset($this->export);
|
||||||
|
}
|
||||||
|
|
||||||
public function confirmFinalize(): void
|
public function confirmFinalize(): void
|
||||||
{
|
{
|
||||||
$this->authorize('billing.manage');
|
$this->authorize('billing.manage');
|
||||||
@@ -304,6 +327,23 @@ new class extends Component
|
|||||||
<p id="billing-error" tabindex="-1" role="alert" class="text-sm font-medium text-red-700 focus:outline-none dark:text-red-400">{{ $errorMessage }}</p>
|
<p id="billing-error" tabindex="-1" role="alert" class="text-sm font-medium text-red-700 focus:outline-none dark:text-red-400">{{ $errorMessage }}</p>
|
||||||
|
|
||||||
@if ($export->isDraft())
|
@if ($export->isDraft())
|
||||||
|
<div class="max-w-xs space-y-1">
|
||||||
|
<label for="billing-period" class="block text-sm font-semibold">{{ __('billing.export.period') }}</label>
|
||||||
|
<input
|
||||||
|
id="billing-period"
|
||||||
|
type="month"
|
||||||
|
value="{{ $export->period }}"
|
||||||
|
wire:change="savePeriod($event.target.value)"
|
||||||
|
aria-describedby="billing-period-help @error('period') billing-period-error @enderror"
|
||||||
|
@error('period') aria-invalid="true" @enderror
|
||||||
|
class="w-full rounded-md border border-zinc-400 bg-white px-2 py-1.5 text-zinc-900 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 aria-invalid:border-red-700 dark:border-zinc-500 dark:bg-zinc-900 dark:text-zinc-100 dark:aria-invalid:border-red-400 dark:[color-scheme:dark]"
|
||||||
|
/>
|
||||||
|
<p id="billing-period-help" class="text-xs text-zinc-600 dark:text-zinc-300">{{ __('billing.export.period_help') }}</p>
|
||||||
|
@error('period')
|
||||||
|
<p id="billing-period-error" class="text-xs text-red-700 dark:text-red-400">{{ $message }}</p>
|
||||||
|
@enderror
|
||||||
|
</div>
|
||||||
|
|
||||||
@if ($export->hasProblems())
|
@if ($export->hasProblems())
|
||||||
<p class="flex items-start gap-2 rounded-lg border border-amber-700 p-4 text-sm dark:border-amber-400">
|
<p class="flex items-start gap-2 rounded-lg border border-amber-700 p-4 text-sm dark:border-amber-400">
|
||||||
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
|
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
|
||||||
@@ -352,7 +392,7 @@ new class extends Component
|
|||||||
</p>
|
</p>
|
||||||
@endif
|
@endif
|
||||||
|
|
||||||
@if ($export->isDraft() && $job->unapprovedQuarters > 0)
|
@if ($export->isDraft() && $job->unapprovedQuarters > 0 && $job->mode !== BillingMode::MonthlyFee)
|
||||||
<p class="flex items-start gap-2 text-sm">
|
<p class="flex items-start gap-2 text-sm">
|
||||||
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
|
<x-icon name="exclamation-triangle" class="size-5 shrink-0" aria-hidden="true" />
|
||||||
<span>
|
<span>
|
||||||
@@ -363,7 +403,34 @@ new class extends Component
|
|||||||
@endif
|
@endif
|
||||||
|
|
||||||
@if ($export->isDraft())
|
@if ($export->isDraft())
|
||||||
@if ($job->mode === BillingMode::FixedPrice)
|
@if ($job->mode === BillingMode::MonthlyFee)
|
||||||
|
@php($months = $this->linesOfKind($job, LineKind::MonthlyFee))
|
||||||
|
@if ($months === [])
|
||||||
|
<p class="text-sm">{{ __('billing.jobs.no_months') }}</p>
|
||||||
|
@else
|
||||||
|
<table class="w-full text-sm">
|
||||||
|
<caption class="mb-1 text-left font-medium">{{ __('billing.jobs.months_caption', ['job' => $job->label()]) }}</caption>
|
||||||
|
<thead>
|
||||||
|
<tr class="border-b border-zinc-300 text-left dark:border-zinc-600">
|
||||||
|
<th scope="col" class="py-2 pr-3">{{ __('billing.jobs.month') }}</th>
|
||||||
|
<th scope="col" class="py-2 text-right">{{ __('billing.jobs.amount') }}</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody class="divide-y divide-zinc-200 dark:divide-zinc-700">
|
||||||
|
@foreach ($months as $line)
|
||||||
|
<tr wire:key="month-{{ $job->jobId }}-{{ $line->period }}">
|
||||||
|
<td class="py-2 pr-3">{{ BillingMonths::label((string) $line->period) }}</td>
|
||||||
|
<td class="py-2 text-right whitespace-nowrap">{{ $this->money($line->netCents) }}</td>
|
||||||
|
</tr>
|
||||||
|
@endforeach
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
@endif
|
||||||
|
@php($approved = array_sum(array_map(fn ($row) => $row->approvedQuarters, $job->hours)))
|
||||||
|
@if ($approved > 0)
|
||||||
|
<p class="text-sm">{{ __('billing.jobs.monthly_hours', ['hours' => $this->hours($approved)]) }}</p>
|
||||||
|
@endif
|
||||||
|
@elseif ($job->mode === BillingMode::FixedPrice)
|
||||||
@php($fixed = $this->linesOfKind($job, LineKind::FixedPrice))
|
@php($fixed = $this->linesOfKind($job, LineKind::FixedPrice))
|
||||||
<p class="text-sm">
|
<p class="text-sm">
|
||||||
{{ $fixed === [] ? __('billing.jobs.fixed_price_billed') : __('billing.jobs.fixed_price', ['amount' => $this->money($fixed[0]->netCents)]) }}
|
{{ $fixed === [] ? __('billing.jobs.fixed_price_billed') : __('billing.jobs.fixed_price', ['amount' => $this->money($fixed[0]->netCents)]) }}
|
||||||
|
|||||||
@@ -50,6 +50,14 @@ interface CustomerJobQueries
|
|||||||
*/
|
*/
|
||||||
public function billingInfoWithStatus(JobStatus $status): array;
|
public function billingInfoWithStatus(JobStatus $status): array;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Billing details of the jobs billed by a monthly fee that may be
|
||||||
|
* billed now (ordered, in production, on hold or done), by job number.
|
||||||
|
*
|
||||||
|
* @return list<JobBillingInfo>
|
||||||
|
*/
|
||||||
|
public function billingInfoMonthly(): array;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Billing details of the given jobs, keyed by id; unknown ids are left out.
|
* Billing details of the given jobs, keyed by id; unknown ids are left out.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -42,5 +42,6 @@ final readonly class CustomerJobData
|
|||||||
public array $links = [],
|
public array $links = [],
|
||||||
public ?string $quotedAmount = null,
|
public ?string $quotedAmount = null,
|
||||||
public bool $setsQuotedAmount = false,
|
public bool $setsQuotedAmount = false,
|
||||||
|
public ?string $monthlyFee = null,
|
||||||
) {}
|
) {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ final readonly class CustomerJobDetails
|
|||||||
public string $createdAt,
|
public string $createdAt,
|
||||||
public string $createdByName,
|
public string $createdByName,
|
||||||
public ?int $quotedAmountCents = null,
|
public ?int $quotedAmountCents = null,
|
||||||
|
public ?int $monthlyFeeCents = null,
|
||||||
public ?string $completedAt = null,
|
public ?string $completedAt = null,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ use App\Modules\Jobs\Domain\Enums\PaymentBasis;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* A customer job as billing sees it: who is billed, under which billing
|
* A customer job as billing sees it: who is billed, under which billing
|
||||||
* unit and reference, and how (payment basis, quoted amount without VAT).
|
* unit and reference, and how (payment basis, quoted amount and monthly
|
||||||
|
* fee without VAT), and for monthly fees the months it runs.
|
||||||
*/
|
*/
|
||||||
final readonly class JobBillingInfo
|
final readonly class JobBillingInfo
|
||||||
{
|
{
|
||||||
@@ -25,5 +26,10 @@ final readonly class JobBillingInfo
|
|||||||
public ?string $customerReference,
|
public ?string $customerReference,
|
||||||
public ?int $billingUnitId,
|
public ?int $billingUnitId,
|
||||||
public ?string $billingUnitName,
|
public ?string $billingUnitName,
|
||||||
|
public ?int $monthlyFeeCents = null,
|
||||||
|
public ?string $startsOn = null,
|
||||||
|
public ?string $dueOn = null,
|
||||||
|
public ?string $completedOn = null,
|
||||||
|
public string $createdOn = '',
|
||||||
) {}
|
) {}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ use App\Modules\Jobs\Domain\Enums\JobStatus;
|
|||||||
use App\Modules\Jobs\Domain\Enums\PaymentBasis;
|
use App\Modules\Jobs\Domain\Enums\PaymentBasis;
|
||||||
use App\Modules\Jobs\Domain\Enums\Priority;
|
use App\Modules\Jobs\Domain\Enums\Priority;
|
||||||
use App\Modules\Jobs\Domain\Exceptions\InvalidJobReference;
|
use App\Modules\Jobs\Domain\Exceptions\InvalidJobReference;
|
||||||
|
use App\Modules\Jobs\Domain\Exceptions\InvalidMonthlyFee;
|
||||||
use App\Modules\Jobs\Domain\ValueObjects\EstimatedHours;
|
use App\Modules\Jobs\Domain\ValueObjects\EstimatedHours;
|
||||||
use App\Modules\Jobs\Domain\ValueObjects\JobDetails;
|
use App\Modules\Jobs\Domain\ValueObjects\JobDetails;
|
||||||
use App\Modules\Jobs\Domain\ValueObjects\JobLink;
|
use App\Modules\Jobs\Domain\ValueObjects\JobLink;
|
||||||
@@ -73,9 +74,22 @@ final class JobDetailsFactory
|
|||||||
tags: array_map(fn (string $tag): Tag => new Tag($tag), $data->tags),
|
tags: array_map(fn (string $tag): Tag => new Tag($tag), $data->tags),
|
||||||
links: array_map(fn (array $link): JobLink => new JobLink($link['title'], $link['url']), $data->links),
|
links: array_map(fn (array $link): JobLink => new JobLink($link['title'], $link['url']), $data->links),
|
||||||
quotedAmount: $data->setsQuotedAmount ? Money::parse((string) $data->quotedAmount) : $current?->quotedAmount,
|
quotedAmount: $data->setsQuotedAmount ? Money::parse((string) $data->quotedAmount) : $current?->quotedAmount,
|
||||||
|
monthlyFee: $data->setsQuotedAmount ? self::monthlyFee($data->monthlyFee) : $current?->monthlyFee,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @throws InvalidMonthlyFee
|
||||||
|
*/
|
||||||
|
private static function monthlyFee(?string $value): ?Money
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
return Money::parse((string) $value);
|
||||||
|
} catch (InvalidMoneyAmount) {
|
||||||
|
throw new InvalidMonthlyFee;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private function checkReferences(CustomerJobData $data, ?JobDetails $current): void
|
private function checkReferences(CustomerJobData $data, ?JobDetails $current): void
|
||||||
{
|
{
|
||||||
if ($this->customers->findSummary($data->customerId) === null) {
|
if ($this->customers->findSummary($data->customerId) === null) {
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Modules\Jobs\Domain\Exceptions;
|
||||||
|
|
||||||
|
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||||
|
|
||||||
|
final class InvalidMonthlyFee extends DomainException
|
||||||
|
{
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
parent::__construct('The monthly fee is not a valid amount.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -60,6 +60,7 @@ final readonly class JobDetails
|
|||||||
array $tags,
|
array $tags,
|
||||||
public array $links,
|
public array $links,
|
||||||
public ?Money $quotedAmount = null,
|
public ?Money $quotedAmount = null,
|
||||||
|
public ?Money $monthlyFee = null,
|
||||||
) {
|
) {
|
||||||
$serviceUnitIds = array_values(array_unique($serviceUnitIds));
|
$serviceUnitIds = array_values(array_unique($serviceUnitIds));
|
||||||
|
|
||||||
@@ -97,7 +98,7 @@ final readonly class JobDetails
|
|||||||
$this->kind, $status, $this->priority, $this->paymentBasis, $this->estimatedHours,
|
$this->kind, $status, $this->priority, $this->paymentBasis, $this->estimatedHours,
|
||||||
$this->customerReference, $this->instructions, $this->responsibleUserId, $this->contactUserId,
|
$this->customerReference, $this->instructions, $this->responsibleUserId, $this->contactUserId,
|
||||||
$this->customerContactId, $this->billerUserId, $this->billingUnitId, $this->memberUserIds,
|
$this->customerContactId, $this->billerUserId, $this->billingUnitId, $this->memberUserIds,
|
||||||
$this->tags, $this->links, $this->quotedAmount,
|
$this->tags, $this->links, $this->quotedAmount, $this->monthlyFee,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -109,7 +110,7 @@ final readonly class JobDetails
|
|||||||
$this->kind, $this->status, $this->priority, $this->paymentBasis, $this->estimatedHours,
|
$this->kind, $this->status, $this->priority, $this->paymentBasis, $this->estimatedHours,
|
||||||
$this->customerReference, $this->instructions, $this->responsibleUserId, $this->contactUserId,
|
$this->customerReference, $this->instructions, $this->responsibleUserId, $this->contactUserId,
|
||||||
$this->customerContactId, $this->billerUserId, $this->billingUnitId, $this->memberUserIds,
|
$this->customerContactId, $this->billerUserId, $this->billingUnitId, $this->memberUserIds,
|
||||||
$this->tags, $this->links, $this->quotedAmount,
|
$this->tags, $this->links, $this->quotedAmount, $this->monthlyFee,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,6 +153,7 @@ final readonly class JobDetails
|
|||||||
'payment_basis' => $this->paymentBasis?->value,
|
'payment_basis' => $this->paymentBasis?->value,
|
||||||
'estimated_hours' => $this->estimatedHours?->format(),
|
'estimated_hours' => $this->estimatedHours?->format(),
|
||||||
'quoted_amount' => $this->quotedAmount === null ? null : (string) $this->quotedAmount->cents,
|
'quoted_amount' => $this->quotedAmount === null ? null : (string) $this->quotedAmount->cents,
|
||||||
|
'monthly_fee' => $this->monthlyFee === null ? null : (string) $this->monthlyFee->cents,
|
||||||
'customer_reference' => $this->customerReference,
|
'customer_reference' => $this->customerReference,
|
||||||
'instructions' => $this->instructions,
|
'instructions' => $this->instructions,
|
||||||
'responsible_user' => (string) $this->responsibleUserId,
|
'responsible_user' => (string) $this->responsibleUserId,
|
||||||
|
|||||||
@@ -42,6 +42,7 @@ use Illuminate\Database\Eloquent\Model;
|
|||||||
* @property int|null $billing_unit_id
|
* @property int|null $billing_unit_id
|
||||||
* @property int $created_by
|
* @property int $created_by
|
||||||
* @property int|null $quoted_amount_cents
|
* @property int|null $quoted_amount_cents
|
||||||
|
* @property int|null $monthly_fee_cents
|
||||||
* @property CarbonImmutable|null $completed_at
|
* @property CarbonImmutable|null $completed_at
|
||||||
* @property int|null $quick_sale_year
|
* @property int|null $quick_sale_year
|
||||||
* @property CarbonImmutable $created_at
|
* @property CarbonImmutable $created_at
|
||||||
@@ -49,7 +50,7 @@ use Illuminate\Database\Eloquent\Model;
|
|||||||
#[Table('customer_jobs')]
|
#[Table('customer_jobs')]
|
||||||
#[Fillable([
|
#[Fillable([
|
||||||
'number', 'name', 'description', 'customer_id', 'starts_on', 'due_on', 'planned_from', 'planned_to',
|
'number', 'name', 'description', 'customer_id', 'starts_on', 'due_on', 'planned_from', 'planned_to',
|
||||||
'kind', 'status', 'priority', 'payment_basis', 'estimated_hours', 'quoted_amount_cents', 'customer_reference', 'instructions',
|
'kind', 'status', 'priority', 'payment_basis', 'estimated_hours', 'quoted_amount_cents', 'monthly_fee_cents', 'customer_reference', 'instructions',
|
||||||
'responsible_user_id', 'contact_user_id', 'customer_contact_id', 'biller_user_id', 'billing_unit_id', 'created_by', 'completed_at',
|
'responsible_user_id', 'contact_user_id', 'customer_contact_id', 'biller_user_id', 'billing_unit_id', 'created_by', 'completed_at',
|
||||||
])]
|
])]
|
||||||
#[UseFactory(CustomerJobFactory::class)]
|
#[UseFactory(CustomerJobFactory::class)]
|
||||||
@@ -66,6 +67,7 @@ class CustomerJobModel extends Model
|
|||||||
return [
|
return [
|
||||||
'customer_id' => 'integer',
|
'customer_id' => 'integer',
|
||||||
'quoted_amount_cents' => 'integer',
|
'quoted_amount_cents' => 'integer',
|
||||||
|
'monthly_fee_cents' => 'integer',
|
||||||
'quick_sale_year' => 'integer',
|
'quick_sale_year' => 'integer',
|
||||||
'completed_at' => 'immutable_datetime',
|
'completed_at' => 'immutable_datetime',
|
||||||
'starts_on' => 'immutable_date',
|
'starts_on' => 'immutable_date',
|
||||||
|
|||||||
+17
@@ -12,6 +12,7 @@ use App\Modules\Jobs\Application\DTOs\JobChangeEntry;
|
|||||||
use App\Modules\Jobs\Application\DTOs\JobListFilter;
|
use App\Modules\Jobs\Application\DTOs\JobListFilter;
|
||||||
use App\Modules\Jobs\Application\DTOs\NamedId;
|
use App\Modules\Jobs\Application\DTOs\NamedId;
|
||||||
use App\Modules\Jobs\Domain\Enums\JobStatus;
|
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\Eloquent\CustomerJobModel;
|
||||||
use App\Modules\Jobs\Infrastructure\Persistence\JobInvolvement;
|
use App\Modules\Jobs\Infrastructure\Persistence\JobInvolvement;
|
||||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||||
@@ -181,6 +182,7 @@ class EloquentCustomerJobQueries implements CustomerJobQueries
|
|||||||
createdAt: $model->created_at->format('Y-m-d H:i'),
|
createdAt: $model->created_at->format('Y-m-d H:i'),
|
||||||
createdByName: $userNames[$model->created_by] ?? '',
|
createdByName: $userNames[$model->created_by] ?? '',
|
||||||
quotedAmountCents: $model->quoted_amount_cents,
|
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'),
|
completedAt: $model->completed_at?->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -190,6 +192,15 @@ class EloquentCustomerJobQueries implements CustomerJobQueries
|
|||||||
return array_values($this->billingInfo(CustomerJobModel::query()->where('status', $status)->orderBy('number')->get()));
|
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
|
public function billingInfoOf(array $ids): array
|
||||||
{
|
{
|
||||||
return $ids === [] ? [] : $this->billingInfo(CustomerJobModel::query()->whereIn('id', $ids)->orderBy('number')->get());
|
return $ids === [] ? [] : $this->billingInfo(CustomerJobModel::query()->whereIn('id', $ids)->orderBy('number')->get());
|
||||||
@@ -204,6 +215,7 @@ class EloquentCustomerJobQueries implements CustomerJobQueries
|
|||||||
$customerNames = $this->customers->namesByIds($models->pluck('customer_id')->unique()->values()->all());
|
$customerNames = $this->customers->namesByIds($models->pluck('customer_id')->unique()->values()->all());
|
||||||
$billingUnitNames = [];
|
$billingUnitNames = [];
|
||||||
$result = [];
|
$result = [];
|
||||||
|
$timezone = (string) config('app.business_timezone');
|
||||||
|
|
||||||
foreach ($models as $model) {
|
foreach ($models as $model) {
|
||||||
if ($model->billing_unit_id !== null && ! isset($billingUnitNames[$model->customer_id])) {
|
if ($model->billing_unit_id !== null && ! isset($billingUnitNames[$model->customer_id])) {
|
||||||
@@ -225,6 +237,11 @@ class EloquentCustomerJobQueries implements CustomerJobQueries
|
|||||||
$model->customer_reference,
|
$model->customer_reference,
|
||||||
$model->billing_unit_id,
|
$model->billing_unit_id,
|
||||||
$model->billing_unit_id === null ? null : ($billingUnitNames[$model->customer_id][$model->billing_unit_id] ?? null),
|
$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'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+2
@@ -44,6 +44,7 @@ class EloquentCustomerJobRepository implements CustomerJobRepository
|
|||||||
'payment_basis' => $details->paymentBasis,
|
'payment_basis' => $details->paymentBasis,
|
||||||
'estimated_hours' => $details->estimatedHours?->value,
|
'estimated_hours' => $details->estimatedHours?->value,
|
||||||
'quoted_amount_cents' => $details->quotedAmount?->cents,
|
'quoted_amount_cents' => $details->quotedAmount?->cents,
|
||||||
|
'monthly_fee_cents' => $details->monthlyFee?->cents,
|
||||||
'completed_at' => $job->completedAt()?->format('Y-m-d H:i:s'),
|
'completed_at' => $job->completedAt()?->format('Y-m-d H:i:s'),
|
||||||
'customer_reference' => $details->customerReference,
|
'customer_reference' => $details->customerReference,
|
||||||
'instructions' => $details->instructions,
|
'instructions' => $details->instructions,
|
||||||
@@ -163,6 +164,7 @@ class EloquentCustomerJobRepository implements CustomerJobRepository
|
|||||||
->map(fn ($row): JobLink => new JobLink((string) $row->title, (string) $row->url))
|
->map(fn ($row): JobLink => new JobLink((string) $row->title, (string) $row->url))
|
||||||
->all(),
|
->all(),
|
||||||
quotedAmount: $model->quoted_amount_cents === null ? null : Money::fromCents($model->quoted_amount_cents),
|
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(
|
return CustomerJob::reconstitute(
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ use App\Modules\Jobs\Domain\Exceptions\InvalidEstimatedHours;
|
|||||||
use App\Modules\Jobs\Domain\Exceptions\InvalidJobLink;
|
use App\Modules\Jobs\Domain\Exceptions\InvalidJobLink;
|
||||||
use App\Modules\Jobs\Domain\Exceptions\InvalidJobName;
|
use App\Modules\Jobs\Domain\Exceptions\InvalidJobName;
|
||||||
use App\Modules\Jobs\Domain\Exceptions\InvalidJobReference;
|
use App\Modules\Jobs\Domain\Exceptions\InvalidJobReference;
|
||||||
|
use App\Modules\Jobs\Domain\Exceptions\InvalidMonthlyFee;
|
||||||
use App\Modules\Jobs\Domain\Exceptions\InvalidTag;
|
use App\Modules\Jobs\Domain\Exceptions\InvalidTag;
|
||||||
use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart;
|
use App\Modules\Jobs\Domain\Exceptions\PlanEndsBeforeStart;
|
||||||
use App\Modules\Jobs\Domain\Exceptions\ServiceUnitRequired;
|
use App\Modules\Jobs\Domain\Exceptions\ServiceUnitRequired;
|
||||||
@@ -62,6 +63,8 @@ class JobForm extends Form
|
|||||||
*/
|
*/
|
||||||
public string $quoted_amount = '';
|
public string $quoted_amount = '';
|
||||||
|
|
||||||
|
public string $monthly_fee = '';
|
||||||
|
|
||||||
public string $customer_reference = '';
|
public string $customer_reference = '';
|
||||||
|
|
||||||
public string $instructions = '';
|
public string $instructions = '';
|
||||||
@@ -101,6 +104,7 @@ class JobForm extends Form
|
|||||||
$this->payment_basis = $job->paymentBasis->value ?? '';
|
$this->payment_basis = $job->paymentBasis->value ?? '';
|
||||||
$this->estimated_hours = $job->estimatedHours ?? '';
|
$this->estimated_hours = $job->estimatedHours ?? '';
|
||||||
$this->quoted_amount = $job->quotedAmountCents === null || ! Gate::allows('money.quotes') ? '' : Money::fromCents($job->quotedAmountCents)->inputValue();
|
$this->quoted_amount = $job->quotedAmountCents === null || ! Gate::allows('money.quotes') ? '' : Money::fromCents($job->quotedAmountCents)->inputValue();
|
||||||
|
$this->monthly_fee = $job->monthlyFeeCents === null || ! Gate::allows('money.quotes') ? '' : Money::fromCents($job->monthlyFeeCents)->inputValue();
|
||||||
$this->customer_reference = $job->customerReference ?? '';
|
$this->customer_reference = $job->customerReference ?? '';
|
||||||
$this->instructions = $job->instructions ?? '';
|
$this->instructions = $job->instructions ?? '';
|
||||||
$this->responsible_user_id = (string) $job->responsible->id;
|
$this->responsible_user_id = (string) $job->responsible->id;
|
||||||
@@ -146,6 +150,7 @@ class JobForm extends Form
|
|||||||
links: array_values(array_filter($this->links, fn (array $link): bool => trim($link['title']) !== '' || trim($link['url']) !== '')),
|
links: array_values(array_filter($this->links, fn (array $link): bool => trim($link['title']) !== '' || trim($link['url']) !== '')),
|
||||||
quotedAmount: $text($this->quoted_amount),
|
quotedAmount: $text($this->quoted_amount),
|
||||||
setsQuotedAmount: Gate::allows('money.quotes'),
|
setsQuotedAmount: Gate::allows('money.quotes'),
|
||||||
|
monthlyFee: $this->payment_basis === PaymentBasis::MonthlyFee->value ? $text($this->monthly_fee) : null,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,6 +166,7 @@ class JobForm extends Form
|
|||||||
$exception instanceof PlanEndsBeforeStart => ['planned_to', 'jobs.errors.plan_ends_before_start'],
|
$exception instanceof PlanEndsBeforeStart => ['planned_to', 'jobs.errors.plan_ends_before_start'],
|
||||||
$exception instanceof InvalidEstimatedHours => ['estimated_hours', 'jobs.errors.invalid_hours'],
|
$exception instanceof InvalidEstimatedHours => ['estimated_hours', 'jobs.errors.invalid_hours'],
|
||||||
$exception instanceof InvalidMoneyAmount => ['quoted_amount', 'jobs.errors.invalid_amount'],
|
$exception instanceof InvalidMoneyAmount => ['quoted_amount', 'jobs.errors.invalid_amount'],
|
||||||
|
$exception instanceof InvalidMonthlyFee => ['monthly_fee', 'jobs.errors.invalid_amount'],
|
||||||
$exception instanceof InvalidTag => ['tags', 'jobs.errors.invalid_tag'],
|
$exception instanceof InvalidTag => ['tags', 'jobs.errors.invalid_tag'],
|
||||||
$exception instanceof InvalidJobLink => ['links', 'jobs.errors.invalid_link'],
|
$exception instanceof InvalidJobLink => ['links', 'jobs.errors.invalid_link'],
|
||||||
$exception instanceof InvalidJobReference => [self::referenceField($exception->field), 'jobs.errors.invalid_reference'],
|
$exception instanceof InvalidJobReference => [self::referenceField($exception->field), 'jobs.errors.invalid_reference'],
|
||||||
@@ -201,6 +207,7 @@ class JobForm extends Form
|
|||||||
'payment_basis' => ['nullable', Rule::enum(PaymentBasis::class)],
|
'payment_basis' => ['nullable', Rule::enum(PaymentBasis::class)],
|
||||||
'estimated_hours' => ['nullable', 'numeric', 'min:0', 'max:99999'],
|
'estimated_hours' => ['nullable', 'numeric', 'min:0', 'max:99999'],
|
||||||
'quoted_amount' => ['nullable', 'string', 'max:20'],
|
'quoted_amount' => ['nullable', 'string', 'max:20'],
|
||||||
|
'monthly_fee' => ['nullable', 'string', 'max:20'],
|
||||||
'customer_reference' => ['nullable', 'string', 'max:255'],
|
'customer_reference' => ['nullable', 'string', 'max:255'],
|
||||||
'instructions' => ['nullable', 'string', 'max:10000'],
|
'instructions' => ['nullable', 'string', 'max:10000'],
|
||||||
'responsible_user_id' => ['required', 'integer'],
|
'responsible_user_id' => ['required', 'integer'],
|
||||||
@@ -240,6 +247,7 @@ class JobForm extends Form
|
|||||||
'estimated_hours.min' => __('jobs.errors.invalid_hours'),
|
'estimated_hours.min' => __('jobs.errors.invalid_hours'),
|
||||||
'estimated_hours.max' => __('jobs.errors.invalid_hours'),
|
'estimated_hours.max' => __('jobs.errors.invalid_hours'),
|
||||||
'quoted_amount.max' => __('jobs.errors.invalid_amount'),
|
'quoted_amount.max' => __('jobs.errors.invalid_amount'),
|
||||||
|
'monthly_fee.max' => __('jobs.errors.invalid_amount'),
|
||||||
'customer_reference.max' => __('jobs.errors.too_long', ['max' => 255]),
|
'customer_reference.max' => __('jobs.errors.too_long', ['max' => 255]),
|
||||||
'instructions.max' => __('jobs.errors.too_long', ['max' => 10000]),
|
'instructions.max' => __('jobs.errors.too_long', ['max' => 10000]),
|
||||||
'responsible_user_id.required' => __('jobs.errors.responsible_required'),
|
'responsible_user_id.required' => __('jobs.errors.responsible_required'),
|
||||||
|
|||||||
@@ -342,7 +342,7 @@ new class extends Component
|
|||||||
@endforeach
|
@endforeach
|
||||||
</x-select.native>
|
</x-select.native>
|
||||||
|
|
||||||
<x-select.native wire:model="form.payment_basis" :label="__('jobs.fields.payment_basis')" :aria-label="__('jobs.fields.payment_basis')">
|
<x-select.native wire:model.live="form.payment_basis" :label="__('jobs.fields.payment_basis')" :aria-label="__('jobs.fields.payment_basis')">
|
||||||
<option value="">{{ __('jobs.fields.no_payment_basis') }}</option>
|
<option value="">{{ __('jobs.fields.no_payment_basis') }}</option>
|
||||||
@foreach (PaymentBasis::cases() as $basis)
|
@foreach (PaymentBasis::cases() as $basis)
|
||||||
<option value="{{ $basis->value }}">{{ __('jobs.payment_bases.'.$basis->value) }}</option>
|
<option value="{{ $basis->value }}">{{ __('jobs.payment_bases.'.$basis->value) }}</option>
|
||||||
@@ -367,6 +367,16 @@ new class extends Component
|
|||||||
:label="__('jobs.fields.quoted_amount_input')"
|
:label="__('jobs.fields.quoted_amount_input')"
|
||||||
:hint="__('jobs.fields.quoted_amount_description')"
|
:hint="__('jobs.fields.quoted_amount_description')"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
@if ($form->payment_basis === 'monthly_fee')
|
||||||
|
<x-input
|
||||||
|
wire:model="form.monthly_fee"
|
||||||
|
inputmode="decimal"
|
||||||
|
autocomplete="off"
|
||||||
|
:label="__('jobs.fields.monthly_fee_input')"
|
||||||
|
:hint="__('jobs.fields.monthly_fee_description')"
|
||||||
|
/>
|
||||||
|
@endif
|
||||||
@endcan
|
@endcan
|
||||||
</div>
|
</div>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
|
|||||||
@@ -67,7 +67,7 @@ new class extends Component
|
|||||||
// Changes of the quoted amount are shown only to those who may see quotes (spec 5.7).
|
// Changes of the quoted amount are shown only to those who may see quotes (spec 5.7).
|
||||||
return Gate::allows('money.quotes')
|
return Gate::allows('money.quotes')
|
||||||
? $changes
|
? $changes
|
||||||
: array_values(array_filter($changes, fn (JobChangeEntry $change): bool => $change->field !== 'quoted_amount'));
|
: array_values(array_filter($changes, fn (JobChangeEntry $change): bool => ! in_array($change->field, ['quoted_amount', 'monthly_fee'], true)));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -171,7 +171,7 @@ new class extends Component
|
|||||||
|
|
||||||
return match ($field) {
|
return match ($field) {
|
||||||
'starts_on', 'due_on', 'planned_from', 'planned_to' => $this->formatDate($value),
|
'starts_on', 'due_on', 'planned_from', 'planned_to' => $this->formatDate($value),
|
||||||
'quoted_amount' => Money::fromCents((int) $value)->format(),
|
'quoted_amount', 'monthly_fee' => Money::fromCents((int) $value)->format(),
|
||||||
'kind' => __('jobs.kinds.'.$value),
|
'kind' => __('jobs.kinds.'.$value),
|
||||||
'status' => __('jobs.statuses.'.$value),
|
'status' => __('jobs.statuses.'.$value),
|
||||||
'priority' => __('jobs.priorities.'.$value),
|
'priority' => __('jobs.priorities.'.$value),
|
||||||
@@ -245,6 +245,11 @@ new class extends Component
|
|||||||
@can('money.quotes')
|
@can('money.quotes')
|
||||||
<dt class="font-medium">{{ __('jobs.fields.quoted_amount') }}</dt>
|
<dt class="font-medium">{{ __('jobs.fields.quoted_amount') }}</dt>
|
||||||
<dd>{{ $job->quotedAmountCents === null ? __('jobs.not_set') : Money::fromCents($job->quotedAmountCents)->format().' '.__('jobs.vat_excluded') }}</dd>
|
<dd>{{ $job->quotedAmountCents === null ? __('jobs.not_set') : Money::fromCents($job->quotedAmountCents)->format().' '.__('jobs.vat_excluded') }}</dd>
|
||||||
|
|
||||||
|
@if ($job->paymentBasis?->value === 'monthly_fee' || $job->monthlyFeeCents !== null)
|
||||||
|
<dt class="font-medium">{{ __('jobs.fields.monthly_fee') }}</dt>
|
||||||
|
<dd>{{ $job->monthlyFeeCents === null ? __('jobs.not_set') : Money::fromCents($job->monthlyFeeCents)->format().' '.__('jobs.vat_excluded') }}</dd>
|
||||||
|
@endif
|
||||||
@endcan
|
@endcan
|
||||||
|
|
||||||
<dt class="font-medium">{{ __('jobs.fields.customer_reference') }}</dt>
|
<dt class="font-medium">{{ __('jobs.fields.customer_reference') }}</dt>
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Monthly fees (spec 5.5): a job's monthly fee, the month a billing
|
||||||
|
* material bills up to, that a monthly fee job is an invoice of its own,
|
||||||
|
* and the month of each monthly fee line, so no month is billed twice.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::table('customer_jobs', function (Blueprint $table) {
|
||||||
|
$table->unsignedInteger('monthly_fee_cents')->nullable()->after('quoted_amount_cents');
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('billing_exports', function (Blueprint $table) {
|
||||||
|
$table->char('period', 7)->nullable()->after('status');
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('billing_invoice_jobs', function (Blueprint $table) {
|
||||||
|
$table->boolean('own_invoice')->default(false)->after('customer_reference');
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('billing_lines', function (Blueprint $table) {
|
||||||
|
$table->char('period', 7)->nullable()->after('expense_id');
|
||||||
|
|
||||||
|
$table->index(['customer_job_id', 'kind', 'period']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::table('billing_lines', function (Blueprint $table) {
|
||||||
|
$table->dropIndex(['customer_job_id', 'kind', 'period']);
|
||||||
|
$table->dropColumn('period');
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('billing_invoice_jobs', function (Blueprint $table) {
|
||||||
|
$table->dropColumn('own_invoice');
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('billing_exports', function (Blueprint $table) {
|
||||||
|
$table->dropColumn('period');
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::table('customer_jobs', function (Blueprint $table) {
|
||||||
|
$table->dropColumn('monthly_fee_cents');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
+13
-7
@@ -120,6 +120,7 @@ Nimi, sähköposti, rooli (yksi per käyttäjä, *K13*), aktiivinen, harjoitteli
|
|||||||
| Maksuperuste | `payment_basis` | ks. 5.5 |
|
| Maksuperuste | `payment_basis` | ks. 5.5 |
|
||||||
| Arvioidut tunnit | `estimated_hours` | *(K24)* |
|
| Arvioidut tunnit | `estimated_hours` | *(K24)* |
|
||||||
| Budjetti / tarjoussumma | `quoted_amount_cents` | Rahamäärä ALV 0; näkyy ja muokattavissa vain Tarjoukset-oikeudella (2.3), muiden tallennus säilyttää sen *(K24, valmis)* |
|
| Budjetti / tarjoussumma | `quoted_amount_cents` | Rahamäärä ALV 0; näkyy ja muokattavissa vain Tarjoukset-oikeudella (2.3), muiden tallennus säilyttää sen *(K24, valmis)* |
|
||||||
|
| Kuukausihinta | `monthly_fee_cents` | Rahamäärä ALV 0 kk-laskutuksen työlle; lomakkeella vain, kun maksuperuste on kiinteä kk-laskutus; näkyvyys ja muokkaus kuten tarjoussummalla *(K22, valmis)* |
|
||||||
| Asiakkaan viite (PO) | `customer_reference` | *(K24)* |
|
| Asiakkaan viite (PO) | `customer_reference` | *(K24)* |
|
||||||
| Tagit | `tags` | Haku listasta tai uuden lisäys, joka tallentuu listaan *(K25)* |
|
| Tagit | `tags` | Haku listasta tai uuden lisäys, joka tallentuu listaan *(K25)* |
|
||||||
| Linkit | `links` | Linkit tiedostoihin (Drive, Dropbox ym.), otsikko + URL *(K26)* |
|
| Linkit | `links` | Linkit tiedostoihin (Drive, Dropbox ym.), otsikko + URL *(K26)* |
|
||||||
@@ -184,6 +185,10 @@ Väri ei koskaan yksin kerro tietoa: prioriteetti näytetään aina myös teksti
|
|||||||
|
|
||||||
Toistaiseksi jatkuvalle työlle, jonka maksuperuste on kiinteä kk-laskutus, syntyy laskuaineistoon automaattisesti rivi joka kuukausi. Ylläpidon kuukausisopimuslaskut laskutetaan omina laskuinaan *(K22)*.
|
Toistaiseksi jatkuvalle työlle, jonka maksuperuste on kiinteä kk-laskutus, syntyy laskuaineistoon automaattisesti rivi joka kuukausi. Ylläpidon kuukausisopimuslaskut laskutetaan omina laskuinaan *(K22)*.
|
||||||
|
|
||||||
|
- Uusi laskuaineiston luonnos lisää automaattisesti jokaisen laskutettavan kk-laskutuksen työn (tila tilattu, tuotannossa, odottaa tai valmis), kukin omaksi laskukseen; niitä ei voi yhdistää muiden töiden kanssa *(valmis)*.
|
||||||
|
- Laskulle tulee kuukausihinnan rivi jokaisesta laskuttamattomasta kuukaudesta työn aloituskuukaudesta (tai luontikuukaudesta) aineiston laskutuskuukauteen asti, mutta ei päättymispäivän tai valmistumisen jälkeen. Väliin jääneet kuukaudet tulevat mukaan, eikä mitään kuukautta laskuteta kahdesti *(valmis)*.
|
||||||
|
- Laskutettavat kulut tulevat samalle laskulle eriteltyinä. Tunnit kuuluvat kuukausihintaan: ne merkitään laskutetuiksi mutta eivät tule riveille. Työn tila ei muutu muodostuksessa, koska työ jatkuu *(valmis)*.
|
||||||
|
|
||||||
### 5.6 Jäsenet
|
### 5.6 Jäsenet
|
||||||
|
|
||||||
| Kenttä | Koodissa | Kuka |
|
| Kenttä | Koodissa | Kuka |
|
||||||
@@ -317,7 +322,7 @@ Hierarkiaa muokataan pohjatietojen hallinnasta.
|
|||||||
- Aineiston muodostus asettaa töille tilan "Lasku luotu" ja merkitsee rivit laskutetuiksi, jotta niitä ei laskuteta kahdesti.
|
- Aineiston muodostus asettaa töille tilan "Lasku luotu" ja merkitsee rivit laskutetuiksi, jotta niitä ei laskuteta kahdesti.
|
||||||
- Aineistoon tulevat vain **hyväksytyt** tunnit. Hyväksymättömät tunnit näytetään luonnoksessa varoituksena linkillä hyväksyntään; ne jäävät laskuttamatta, kun työ siirtyy tilaan Lasku luotu *(valmis)*.
|
- Aineistoon tulevat vain **hyväksytyt** tunnit. Hyväksymättömät tunnit näytetään luonnoksessa varoituksena linkillä hyväksyntään; ne jäävät laskuttamatta, kun työ siirtyy tilaan Lasku luotu *(valmis)*.
|
||||||
- **Kiinteä tarjous**: laskulle tulee yksi rivi, jonka summa on työn tarjoussumma (veroton), vain kerran. Hyväksytyt tunnit näytetään tietona ja merkitään laskutetuiksi. Kulut tulevat eriteltyinä *(valmis)*.
|
- **Kiinteä tarjous**: laskulle tulee yksi rivi, jonka summa on työn tarjoussumma (veroton), vain kerran. Hyväksytyt tunnit näytetään tietona ja merkitään laskutetuiksi. Kulut tulevat eriteltyinä *(valmis)*.
|
||||||
- Laskuttamatta jätetään työt, joiden maksuperuste on "ei laskuteta" tai kuukausilaskutus, sisäisen asiakkaan työt, kuluttajat ilman henkilötunnusta ja työt, joiden työtehtävältä puuttuu tuntihinta; syy näytetään johdolle *(valmis)*.
|
- Laskuttamatta jätetään työt, joiden maksuperuste on "ei laskuteta", sisäisen asiakkaan työt, kuluttajat ilman henkilötunnusta ja työt, joiden työtehtävältä puuttuu tuntihinta; syy näytetään johdolle *(valmis)*.
|
||||||
- Laskutetut tunnit pysyvät hyväksyttyinä (hyväksynnän peruminen ohittaa ne), eikä laskutettua kulua voi muuttaa tai poistaa *(valmis)*.
|
- Laskutetut tunnit pysyvät hyväksyttyinä (hyväksynnän peruminen ohittaa ne), eikä laskutettua kulua voi muuttaa tai poistaa *(valmis)*.
|
||||||
|
|
||||||
## 13. Ilmoitukset ja raportit *(K52, K53)*
|
## 13. Ilmoitukset ja raportit *(K52, K53)*
|
||||||
@@ -348,7 +353,7 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up
|
|||||||
- `settings` *(V2, olemassa)*: `key` (uniikki, omistajamoduulin etuliite, esim. `catalog.mileage_rate_cents`), `value` (esim. km-hinta, työajanseuranta päällä)
|
- `settings` *(V2, olemassa)*: `key` (uniikki, omistajamoduulin etuliite, esim. `catalog.mileage_rate_cents`), `value` (esim. km-hinta, työajanseuranta päällä)
|
||||||
|
|
||||||
**Jobs** (asiakastyöt)
|
**Jobs** (asiakastyöt)
|
||||||
- `customer_jobs`: `number`, `name`, `description`, `customer_id`, `starts_on`, `due_on`, `planned_from`, `planned_to`, `kind`, `status`, `priority`, `payment_basis`, `estimated_hours`, `customer_reference`, `instructions`, `responsible_user_id`, `contact_user_id`, `customer_contact_id`, `biller_user_id`, `billing_unit_id`, `created_by` *(olemassa)*; `quoted_amount_cents`, `completed_at` (asetetaan, kun työ saavuttaa lukitsevan tilan; tyhjennetään, kun lukitus avataan), `quick_sale_year` (uniikki; merkitsee vuoden pikamyyntityön) *(V2, olemassa)*
|
- `customer_jobs`: `number`, `name`, `description`, `customer_id`, `starts_on`, `due_on`, `planned_from`, `planned_to`, `kind`, `status`, `priority`, `payment_basis`, `estimated_hours`, `customer_reference`, `instructions`, `responsible_user_id`, `contact_user_id`, `customer_contact_id`, `biller_user_id`, `billing_unit_id`, `created_by` *(olemassa)*; `quoted_amount_cents`, `monthly_fee_cents`, `completed_at` (asetetaan, kun työ saavuttaa lukitsevan tilan; tyhjennetään, kun lukitus avataan), `quick_sale_year` (uniikki; merkitsee vuoden pikamyyntityön) *(V2, olemassa)*
|
||||||
- `job_number_sequences`: `year`, `last_number`
|
- `job_number_sequences`: `year`, `last_number`
|
||||||
- `customer_job_service_unit`: `customer_job_id`, `service_unit_id`
|
- `customer_job_service_unit`: `customer_job_id`, `service_unit_id`
|
||||||
- `customer_job_members`: `customer_job_id`, `user_id`
|
- `customer_job_members`: `customer_job_id`, `user_id`
|
||||||
@@ -377,11 +382,11 @@ Taulut ja tärkeimmät sarakkeet. Kaikissa tauluissa on `id` ja `created_at`/`up
|
|||||||
- `cash_days`: `day` (uniikki), `closed_by`, `closed_at`, `sale_count`, `cash_cents`, `card_cents`, `total_cents`, `reopened_by`, `reopened_at`; `cash_day_vat_totals`: `cash_day_id`, `vat_basis_points`, `gross_cents`, `net_cents`, `vat_cents`
|
- `cash_days`: `day` (uniikki), `closed_by`, `closed_at`, `sale_count`, `cash_cents`, `card_cents`, `total_cents`, `reopened_by`, `reopened_at`; `cash_day_vat_totals`: `cash_day_id`, `vat_basis_points`, `gross_cents`, `net_cents`, `vat_cents`
|
||||||
|
|
||||||
**Billing** *(V2, olemassa)*
|
**Billing** *(V2, olemassa)*
|
||||||
- `billing_exports`: `status` (`draft`/`created`; luonnoksia yksi kerrallaan), `created_by`, `finalized_by`, `finalized_at` (vientitiedosto lisätään Fennoa-viennin osassa)
|
- `billing_exports`: `status` (`draft`/`created`; luonnoksia yksi kerrallaan), `period` (laskutuskuukausi `Y-m`), `created_by`, `finalized_by`, `finalized_at` (vientitiedosto lisätään Fennoa-viennin osassa)
|
||||||
- `billing_invoices`: `billing_export_id`, `customer_id`, `billing_unit_id`, `customer_reference` (laskun töiden yhteinen PO-viite, jos on), `sort_order`
|
- `billing_invoices`: `billing_export_id`, `customer_id`, `billing_unit_id`, `customer_reference` (laskun töiden yhteinen PO-viite, jos on), `sort_order`
|
||||||
- `billing_invoice_jobs`: `billing_invoice_id`, `customer_job_id`, työn `customer_id`, `billing_unit_id` ja `customer_reference` lisäyshetkellä, `sort_order` (työ on aineistossa vain yhdellä laskulla)
|
- `billing_invoice_jobs`: `billing_invoice_id`, `customer_job_id`, työn `customer_id`, `billing_unit_id` ja `customer_reference` lisäyshetkellä, `own_invoice` (kk-laskutuksen työ on aina oma laskunsa), `sort_order` (työ on aineistossa vain yhdellä laskulla)
|
||||||
- `billing_job_hours`: `billing_invoice_job_id`, `work_type_id`, `billable_quarters` (johdon kirjaama laskutettava määrä; ilman riviä laskutetaan hyväksytyt tunnit)
|
- `billing_job_hours`: `billing_invoice_job_id`, `work_type_id`, `billable_quarters` (johdon kirjaama laskutettava määrä; ilman riviä laskutetaan hyväksytyt tunnit)
|
||||||
- `billing_lines` (muodostuksessa): `billing_invoice_id`, `customer_job_id`, `kind` (`hours`/`fixed_price`/`expense`; kuukausirivit myöhemmin), `work_type_id`, `expense_id`, `description`, `recorded_quarters` (hyväksytyt tunnit), `quantity_quarters` (laskutettu määrä), `unit_price_cents`, `vat_basis_points`, `net_cents`, `sort_order`
|
- `billing_lines` (muodostuksessa): `billing_invoice_id`, `customer_job_id`, `kind` (`hours`/`fixed_price`/`monthly_fee`/`expense`), `work_type_id`, `expense_id`, `period` (kuukausirivin kuukausi), `description`, `recorded_quarters` (hyväksytyt tunnit), `quantity_quarters` (laskutettu määrä), `unit_price_cents`, `vat_basis_points`, `net_cents`, `sort_order`
|
||||||
|
|
||||||
## 15. Vaiheistus
|
## 15. Vaiheistus
|
||||||
|
|
||||||
@@ -482,11 +487,12 @@ Jokainen sivu täyttää saavutettavuusvaatimukset ja saa selaintestin (vaalea/t
|
|||||||
- Valikon "Pikamyynti" (`/sales/new`) puhelimelle sopiva lomake: tuotepainikkeet, myynnin lista määrineen (muutokset ja yhteissumma ilmoitetaan ruudunlukijalle), maksutapa ja vapaaehtoinen asiakas. Tallennuksen jälkeen lomake tyhjenee ja ilmoitus kertoo myynnin numeron, summan ja kirjatut tunnit sekä linkin PDF-kuittiin. Myynnit-sivulla on kuittilinkki jokaisella rivillä.
|
- Valikon "Pikamyynti" (`/sales/new`) puhelimelle sopiva lomake: tuotepainikkeet, myynnin lista määrineen (muutokset ja yhteissumma ilmoitetaan ruudunlukijalle), maksutapa ja vapaaehtoinen asiakas. Tallennuksen jälkeen lomake tyhjenee ja ilmoitus kertoo myynnin numeron, summan ja kirjatut tunnit sekä linkin PDF-kuittiin. Myynnit-sivulla on kuittilinkki jokaisella rivillä.
|
||||||
- Myynnit-sivu (`/sales?paiva=VVVV-KK-PP`): päivän myynnit (työntekijä näkee omansa, johto kaikkien ja voi suodattaa myyjän mukaan), hyvitys vahvistusdialogissa, kassapäivän tila, saldo ja ALV-erittely, päättäminen ja johdolle uudelleen avaaminen vahvistusdialogissa, muistutus päättämättömistä aiemmista päivistä.
|
- Myynnit-sivu (`/sales?paiva=VVVV-KK-PP`): päivän myynnit (työntekijä näkee omansa, johto kaikkien ja voi suodattaa myyjän mukaan), hyvitys vahvistusdialogissa, kassapäivän tila, saldo ja ALV-erittely, päättäminen ja johdolle uudelleen avaaminen vahvistusdialogissa, muistutus päättämättömistä aiemmista päivistä.
|
||||||
|
|
||||||
### 17.7 Laskuaineisto *(valmis, Fennoa-vienti ja kuukausirivit tulossa)*
|
### 17.7 Laskuaineisto *(valmis, Fennoa-vienti tulossa)*
|
||||||
- Valikon "Laskutus" (`/billing`, pääkäyttäjä ja johto): laskuaineistot (tila, laskujen ja töiden määrä, veroton summa) sekä uuden luonnoksen aloitus tai avoimen jatkaminen.
|
- Valikon "Laskutus" (`/billing`, pääkäyttäjä ja johto): laskuaineistot (tila, laskujen ja töiden määrä, veroton summa) sekä uuden luonnoksen aloitus tai avoimen jatkaminen.
|
||||||
- Luonnos (`/billing/{aineisto}`): valmiit työt lisätään yksitellen, ja jokainen on aluksi oma laskunsa. Työn voi siirtää toiselle laskulle, jos asiakas, laskutusyksikkö ja viite sallivat (luku 12), tehdä siitä taas oman laskun tai poistaa. Laskutettavat tunnit kirjataan työtehtävittäin (oletuksena hyväksytyt tunnit). Jokaisella laskulla on veroton summa, ALV kannoittain ja verollinen summa (oletus-ALV-kanta). Muutokset tallentuvat heti.
|
- Luonnos (`/billing/{aineisto}`): valmiit työt lisätään yksitellen, ja jokainen on aluksi oma laskunsa. Työn voi siirtää toiselle laskulle, jos asiakas, laskutusyksikkö ja viite sallivat (luku 12), tehdä siitä taas oman laskun tai poistaa. Laskutettavat tunnit kirjataan työtehtävittäin (oletuksena hyväksytyt tunnit). Jokaisella laskulla on veroton summa, ALV kannoittain ja verollinen summa (oletus-ALV-kanta). Muutokset tallentuvat heti.
|
||||||
- "Muodosta aineisto" vahvistusdialogissa tarkistaa työt uudelleen, merkitsee hyväksytyt tunnit ja laskutettavat kulut laskutetuiksi, muodostaa rivit hinnan ja ALV:n tilannekuvineen ja siirtää työt tilaan Lasku luotu. Muodostettu aineisto näytetään lukutilassa riveineen. Luonnoksen voi hylätä, jolloin mitään ei laskuteta.
|
- "Muodosta aineisto" vahvistusdialogissa tarkistaa työt uudelleen, merkitsee hyväksytyt tunnit ja laskutettavat kulut laskutetuiksi, muodostaa rivit hinnan ja ALV:n tilannekuvineen ja siirtää työt tilaan Lasku luotu. Muodostettu aineisto näytetään lukutilassa riveineen. Luonnoksen voi hylätä, jolloin mitään ei laskuteta.
|
||||||
- Tulossa: CSV/Excel-vienti Fennoan tuontimuotoon (avoin kysymys 4) ja kuukausilaskutusrivit.
|
- Luonnoksella on laskutuskuukausi (oletuksena kuluva kuukausi), johon asti kk-laskutuksen työt laskutetaan; kuukauden vaihto laskee esikatselun uudelleen (5.5).
|
||||||
|
- Tulossa: CSV/Excel-vienti Fennoan tuontimuotoon (avoin kysymys 4).
|
||||||
|
|
||||||
## 18. Avoimet kysymykset
|
## 18. Avoimet kysymykset
|
||||||
|
|
||||||
|
|||||||
+18
-6
@@ -11,28 +11,32 @@ return [
|
|||||||
'modes' => [
|
'modes' => [
|
||||||
'hours' => 'Tuntityö',
|
'hours' => 'Tuntityö',
|
||||||
'fixed_price' => 'Kiinteä hinta',
|
'fixed_price' => 'Kiinteä hinta',
|
||||||
'none' => 'Ei laskuteta näin',
|
'monthly_fee' => 'Kuukausihinta',
|
||||||
|
'none' => 'Ei laskuteta aineistolla',
|
||||||
],
|
],
|
||||||
|
|
||||||
'kinds' => [
|
'kinds' => [
|
||||||
'hours' => 'Tunnit',
|
'hours' => 'Tunnit',
|
||||||
'fixed_price' => 'Kiinteä hinta',
|
'fixed_price' => 'Kiinteä hinta',
|
||||||
'expense' => 'Kulu',
|
'expense' => 'Kulu',
|
||||||
|
'monthly_fee' => 'Kuukausihinta',
|
||||||
],
|
],
|
||||||
|
|
||||||
'reasons' => [
|
'reasons' => [
|
||||||
'wrong_status' => 'Työ ei ole valmis.',
|
'wrong_status' => 'Työ ei ole valmis.',
|
||||||
'not_billable_basis' => 'Työtä ei laskuteta aineistolla (ei laskuteta, kuukausilaskutus tai sisäinen asiakas).',
|
'not_billable_basis' => 'Työtä ei laskuteta aineistolla (ei laskutettava tai sisäinen asiakas).',
|
||||||
|
'missing_monthly_fee' => 'Kuukausilaskutuksen työltä puuttuu kuukausihinta.',
|
||||||
'missing_identity_code' => 'Asiakkaan henkilötunnus puuttuu.',
|
'missing_identity_code' => 'Asiakkaan henkilötunnus puuttuu.',
|
||||||
'missing_hourly_rate' => 'Tuntihinta puuttuu: :names',
|
'missing_hourly_rate' => 'Tuntihinta puuttuu: :names',
|
||||||
'missing_quoted_amount' => 'Kiinteän hinnan työltä puuttuu tarjoussumma.',
|
'missing_quoted_amount' => 'Kiinteän hinnan työltä puuttuu tarjoussumma.',
|
||||||
'nothing_to_bill' => 'Ei laskutettavaa: ei hyväksyttyjä tunteja eikä laskutettavia kuluja.',
|
'nothing_to_bill' => 'Ei laskutettavaa: ei hyväksyttyjä tunteja, laskuttamattomia kuukausia eikä laskutettavia kuluja.',
|
||||||
],
|
],
|
||||||
|
|
||||||
'merge_refusals' => [
|
'merge_refusals' => [
|
||||||
'different_customer' => 'Töillä on eri asiakas.',
|
'different_customer' => 'Töillä on eri asiakas.',
|
||||||
'different_billing_unit' => 'Töillä on eri laskutusyksikkö.',
|
'different_billing_unit' => 'Töillä on eri laskutusyksikkö.',
|
||||||
'different_reference' => 'Töillä on eri asiakkaan viite.',
|
'different_reference' => 'Töillä on eri asiakkaan viite.',
|
||||||
|
'monthly_fee_alone' => 'Kuukausilaskutuksen työ laskutetaan omalla laskullaan.',
|
||||||
],
|
],
|
||||||
|
|
||||||
'index' => [
|
'index' => [
|
||||||
@@ -69,6 +73,9 @@ return [
|
|||||||
'discard_text' => 'Luonnos poistetaan. Mitään ei ole vielä laskutettu, joten työt pysyvät ennallaan.',
|
'discard_text' => 'Luonnos poistetaan. Mitään ei ole vielä laskutettu, joten työt pysyvät ennallaan.',
|
||||||
'discarded' => 'Luonnos hylätty.',
|
'discarded' => 'Luonnos hylätty.',
|
||||||
'problems' => 'Kaikkia töitä ei voi laskuttaa. Korjaa tai poista merkityt työt ennen muodostusta.',
|
'problems' => 'Kaikkia töitä ei voi laskuttaa. Korjaa tai poista merkityt työt ennen muodostusta.',
|
||||||
|
'period' => 'Laskutuskuukausi',
|
||||||
|
'period_help' => 'Kuukausilaskutuksen työt laskutetaan tähän kuukauteen asti, myös väliin jääneet kuukaudet.',
|
||||||
|
'period_saved' => 'Laskutuskuukausi on nyt :month.',
|
||||||
],
|
],
|
||||||
|
|
||||||
'invoices' => [
|
'invoices' => [
|
||||||
@@ -104,6 +111,10 @@ return [
|
|||||||
'fixed_price' => 'Kiinteä hinta: :amount',
|
'fixed_price' => 'Kiinteä hinta: :amount',
|
||||||
'fixed_price_billed' => 'Kiinteä hinta on jo laskutettu aiemmalla aineistolla.',
|
'fixed_price_billed' => 'Kiinteä hinta on jo laskutettu aiemmalla aineistolla.',
|
||||||
'fixed_hours' => 'Hyväksytyt tunnit :hours h näytetään tietona ja merkitään laskutetuiksi.',
|
'fixed_hours' => 'Hyväksytyt tunnit :hours h näytetään tietona ja merkitään laskutetuiksi.',
|
||||||
|
'monthly_hours' => 'Hyväksytyt tunnit :hours h kuuluvat kuukausihintaan, ja ne merkitään laskutetuiksi.',
|
||||||
|
'months_caption' => 'Laskutettavat kuukaudet: :job',
|
||||||
|
'month' => 'Kuukausi',
|
||||||
|
'no_months' => 'Ei laskuttamattomia kuukausia.',
|
||||||
'no_hours' => 'Ei hyväksyttyjä laskuttamattomia tunteja.',
|
'no_hours' => 'Ei hyväksyttyjä laskuttamattomia tunteja.',
|
||||||
'expenses_caption' => 'Kulut: :job',
|
'expenses_caption' => 'Kulut: :job',
|
||||||
'expense' => 'Kulu',
|
'expense' => 'Kulu',
|
||||||
@@ -132,9 +143,9 @@ return [
|
|||||||
],
|
],
|
||||||
|
|
||||||
'available' => [
|
'available' => [
|
||||||
'title' => 'Valmiit työt',
|
'title' => 'Laskutettavat työt',
|
||||||
'intro' => 'Valmiit työt, joita ei ole luonnoksessa. Jokainen lisätty työ on aluksi oma laskunsa.',
|
'intro' => 'Valmiit työt ja kuukausilaskutuksen työt, joita ei ole luonnoksessa. Jokainen lisätty työ on aluksi oma laskunsa.',
|
||||||
'none' => 'Ei muita valmiita töitä.',
|
'none' => 'Ei muita laskutettavia töitä.',
|
||||||
'columns' => [
|
'columns' => [
|
||||||
'job' => 'Työ',
|
'job' => 'Työ',
|
||||||
'customer' => 'Asiakas',
|
'customer' => 'Asiakas',
|
||||||
@@ -159,5 +170,6 @@ return [
|
|||||||
'not_in_draft' => 'Työ ei ole aineistossa.',
|
'not_in_draft' => 'Työ ei ole aineistossa.',
|
||||||
'not_billable' => 'Työtä :job ei voi laskuttaa: :reason',
|
'not_billable' => 'Työtä :job ei voi laskuttaa: :reason',
|
||||||
'hours' => 'Anna tunnit neljännestunnin tarkkuudella, esimerkiksi 12,5 tai 3,25.',
|
'hours' => 'Anna tunnit neljännestunnin tarkkuudella, esimerkiksi 12,5 tai 3,25.',
|
||||||
|
'period' => 'Valitse kuukausi.',
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -129,6 +129,9 @@ return [
|
|||||||
'quoted_amount' => 'Budjetti / tarjoussumma',
|
'quoted_amount' => 'Budjetti / tarjoussumma',
|
||||||
'quoted_amount_input' => 'Budjetti / tarjoussumma (€, ALV 0)',
|
'quoted_amount_input' => 'Budjetti / tarjoussumma (€, ALV 0)',
|
||||||
'quoted_amount_description' => 'Veroton summa, esim. 4500. Näkyy vain niille, joilla on oikeus tarjouksiin.',
|
'quoted_amount_description' => 'Veroton summa, esim. 4500. Näkyy vain niille, joilla on oikeus tarjouksiin.',
|
||||||
|
'monthly_fee' => 'Kuukausihinta',
|
||||||
|
'monthly_fee_input' => 'Kuukausihinta (€, ALV 0)',
|
||||||
|
'monthly_fee_description' => 'Laskutetaan laskuaineistolla joka kuukausi työn aloituskuukaudesta alkaen. Näkyy vain niille, joilla on oikeus tarjouksiin.',
|
||||||
'completed_at' => 'Valmistunut',
|
'completed_at' => 'Valmistunut',
|
||||||
'customer_reference' => 'Asiakkaan viite (PO)',
|
'customer_reference' => 'Asiakkaan viite (PO)',
|
||||||
'instructions' => 'Ohjeistus',
|
'instructions' => 'Ohjeistus',
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Modules\Billing\Infrastructure\Persistence\Eloquent\BillingExportModel;
|
use App\Modules\Billing\Application\UseCases\OpenBillingDraft;
|
||||||
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
|
use App\Modules\Catalog\Infrastructure\Persistence\Eloquent\WorkTypeModel;
|
||||||
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
|
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
|
||||||
use App\Modules\Expenses\Infrastructure\Persistence\Eloquent\ExpenseModel;
|
use App\Modules\Expenses\Infrastructure\Persistence\Eloquent\ExpenseModel;
|
||||||
@@ -31,7 +31,17 @@ beforeEach(function () {
|
|||||||
|
|
||||||
ExpenseModel::factory()->create(['customer_job_id' => $this->jobs[0]->id, 'description' => 'Paperi']);
|
ExpenseModel::factory()->create(['customer_job_id' => $this->jobs[0]->id, 'description' => 'Paperi']);
|
||||||
|
|
||||||
$this->exportId = BillingExportModel::query()->create(['status' => 'draft', 'created_by' => $this->manager->id])->id;
|
CustomerJobModel::factory()->create([
|
||||||
|
'name' => 'Ylläpito',
|
||||||
|
'customer_id' => $customer->id,
|
||||||
|
'status' => JobStatus::InProduction,
|
||||||
|
'payment_basis' => 'monthly_fee',
|
||||||
|
'monthly_fee_cents' => 9900,
|
||||||
|
'starts_on' => now()->subMonths(2)->toDateString(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// Opening the draft adds the monthly fee job.
|
||||||
|
$this->exportId = app(OpenBillingDraft::class)->execute($this->manager->id);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('has no accessibility issues on the billing pages', function (string $page, string $device, string $colorScheme) {
|
it('has no accessibility issues on the billing pages', function (string $page, string $device, string $colorScheme) {
|
||||||
@@ -59,18 +69,19 @@ it('adds and combines jobs and creates the material', function () {
|
|||||||
$page->click('[wire\\:click="add('.$first->id.')"]')
|
$page->click('[wire\\:click="add('.$first->id.')"]')
|
||||||
->assertSee('lisätty aineistoon')
|
->assertSee('lisätty aineistoon')
|
||||||
->click('[wire\\:click="add('.$second->id.')"]')
|
->click('[wire\\:click="add('.$second->id.')"]')
|
||||||
->assertSee('Lasku 2: Asiakas Oy')
|
->assertSee('Lasku 3: Asiakas Oy')
|
||||||
|
->assertSee('Laskutettavat kuukaudet')
|
||||||
->assertSee('Hyväksymättömiä tunteja 1 h')
|
->assertSee('Hyväksymättömiä tunteja 1 h')
|
||||||
->assertNoAccessibilityIssues(level: 2)
|
->assertNoAccessibilityIssues(level: 2)
|
||||||
->select('[wire\\:model="moveTargets.'.$second->id.'"]', (string) $first->id)
|
->select('[wire\\:model="moveTargets.'.$second->id.'"]', (string) $first->id)
|
||||||
->click('[wire\\:click="move('.$second->id.')"]')
|
->click('[wire\\:click="move('.$second->id.')"]')
|
||||||
->assertSee('siirretty laskulle')
|
->assertSee('siirretty laskulle')
|
||||||
->assertDontSee('Lasku 2: Asiakas Oy')
|
->assertDontSee('Lasku 3: Asiakas Oy')
|
||||||
->click('Muodosta aineisto')
|
->click('Muodosta aineisto')
|
||||||
->assertSee('Muodostetaanko laskuaineisto?')
|
->assertSee('Muodostetaanko laskuaineisto?')
|
||||||
->assertNoAccessibilityIssues(level: 2)
|
->assertNoAccessibilityIssues(level: 2)
|
||||||
->click('#finalize-dialog button:last-child')
|
->click('#finalize-dialog button:last-child')
|
||||||
->assertSee('Laskuaineisto muodostettu: 1 laskua.')
|
->assertSee('Laskuaineisto muodostettu: 2 laskua.')
|
||||||
->assertSee('Laskutetut h')
|
->assertSee('Laskutetut h')
|
||||||
->assertNoAccessibilityIssues(level: 2);
|
->assertNoAccessibilityIssues(level: 2);
|
||||||
|
|
||||||
|
|||||||
@@ -225,3 +225,73 @@ it('keeps everyone but management out', function (string $role) {
|
|||||||
|
|
||||||
$this->get(route('billing.index'))->assertForbidden();
|
$this->get(route('billing.index'))->assertForbidden();
|
||||||
})->with(['employee', 'intern', 'subcontractor']);
|
})->with(['employee', 'intern', 'subcontractor']);
|
||||||
|
|
||||||
|
it('bills every unbilled month of a monthly fee job on an invoice of its own and keeps the job running', function () {
|
||||||
|
$this->travelTo(now()->setDate(2026, 11, 20)->setTime(12, 0));
|
||||||
|
|
||||||
|
$maintenance = doneJob([
|
||||||
|
'name' => 'Ylläpito',
|
||||||
|
'status' => JobStatus::InProduction,
|
||||||
|
'payment_basis' => 'monthly_fee',
|
||||||
|
'monthly_fee_cents' => 9900,
|
||||||
|
'starts_on' => '2026-09-10',
|
||||||
|
], [$this->layout->id => 2]);
|
||||||
|
ExpenseModel::factory()->create(['customer_job_id' => $maintenance->id, 'description' => 'Lisenssi', 'billed_amount_cents' => 1500]);
|
||||||
|
$other = doneJob([], [$this->layout->id => 1]);
|
||||||
|
|
||||||
|
$exportId = openDraft();
|
||||||
|
|
||||||
|
$page = Livewire::test('billing::export', ['export' => $exportId])
|
||||||
|
->assertSee('9/2026')
|
||||||
|
->assertSee('Hyväksytyt tunnit 2 h kuuluvat kuukausihintaan')
|
||||||
|
->call('savePeriod', '2026-10')
|
||||||
|
->assertSet('statusMessage', 'Laskutuskuukausi on nyt 10/2026.')
|
||||||
|
->assertDontSee('11/2026')
|
||||||
|
->call('savePeriod', '2026-13')
|
||||||
|
->assertHasErrors(['period'])
|
||||||
|
->call('savePeriod', '2026-11')
|
||||||
|
->call('add', $other->id)
|
||||||
|
->set("moveTargets.{$other->id}", (string) $maintenance->id)
|
||||||
|
->call('move', $other->id)
|
||||||
|
->assertSet('errorMessage', 'Kuukausilaskutuksen työ laskutetaan omalla laskullaan.');
|
||||||
|
|
||||||
|
expect($page->get('export')->invoices)->toHaveCount(2)
|
||||||
|
->and($page->get('export')->invoices[0]->mergeTargets[$maintenance->id])->toBe([]);
|
||||||
|
|
||||||
|
$page->call('finalize')->assertSet('errorMessage', '');
|
||||||
|
|
||||||
|
$monthly = BillingLineModel::query()->where('customer_job_id', $maintenance->id)->orderBy('sort_order')->get();
|
||||||
|
expect($monthly->map->only(['kind', 'period', 'net_cents'])->all())->toBe([
|
||||||
|
['kind' => LineKind::MonthlyFee, 'period' => '2026-09', 'net_cents' => 9900],
|
||||||
|
['kind' => LineKind::MonthlyFee, 'period' => '2026-10', 'net_cents' => 9900],
|
||||||
|
['kind' => LineKind::MonthlyFee, 'period' => '2026-11', 'net_cents' => 9900],
|
||||||
|
['kind' => LineKind::Expense, 'period' => null, 'net_cents' => 1500],
|
||||||
|
])
|
||||||
|
->and($maintenance->refresh()->status)->toBe(JobStatus::InProduction)
|
||||||
|
->and($other->refresh()->status)->toBe(JobStatus::Invoiced)
|
||||||
|
->and(TimeEntryModel::query()->where('customer_job_id', $maintenance->id)->value('billing_export_id'))->toBe($exportId);
|
||||||
|
|
||||||
|
// The same month again bills nothing; the next month bills one row.
|
||||||
|
$next = openDraft();
|
||||||
|
expect(DB::table('billing_invoice_jobs')->count())->toBe(2);
|
||||||
|
|
||||||
|
$this->travelTo(now()->setDate(2026, 12, 5));
|
||||||
|
Livewire::test('billing::export', ['export' => $next])
|
||||||
|
->assertSee('Ei laskutettavaa')
|
||||||
|
->call('savePeriod', '2026-12')
|
||||||
|
->call('add', $maintenance->id)
|
||||||
|
->assertSet('errorMessage', '')
|
||||||
|
->call('finalize');
|
||||||
|
|
||||||
|
expect(BillingLineModel::query()->where('customer_job_id', $maintenance->id)->where('kind', LineKind::MonthlyFee)->pluck('period')->all())
|
||||||
|
->toBe(['2026-09', '2026-10', '2026-11', '2026-12']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not bill a monthly fee job without a monthly fee', function () {
|
||||||
|
$job = doneJob(['status' => JobStatus::InProduction, 'payment_basis' => 'monthly_fee']);
|
||||||
|
|
||||||
|
Livewire::test('billing::export', ['export' => openDraft()])
|
||||||
|
->assertSee('Kuukausilaskutuksen työltä puuttuu kuukausihinta.')
|
||||||
|
->call('add', $job->id)
|
||||||
|
->assertSet('errorMessage', fn (string $message) => str_contains($message, 'kuukausihinta'));
|
||||||
|
});
|
||||||
|
|||||||
@@ -91,3 +91,32 @@ it('records when a job is done and clears it when management opens the lock', fu
|
|||||||
Livewire::test('jobs::board')->set('mine', false)->call('moveJob', $this->job->id, 'in_production');
|
Livewire::test('jobs::board')->set('mine', false)->call('moveJob', $this->job->id, 'in_production');
|
||||||
expect($this->job->refresh()->completed_at)->toBeNull();
|
expect($this->job->refresh()->completed_at)->toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('keeps the monthly fee of a monthly fee job with its history, behind the quotes permission', function () {
|
||||||
|
$this->actingAs(User::factory()->management()->create());
|
||||||
|
|
||||||
|
Livewire::test('jobs::form', ['job' => $this->job->id])
|
||||||
|
->assertDontSee('Kuukausihinta (€, ALV 0)')
|
||||||
|
->set('form.payment_basis', 'monthly_fee')
|
||||||
|
->assertSee('Kuukausihinta (€, ALV 0)')
|
||||||
|
->set('form.monthly_fee', '12,345')
|
||||||
|
->call('save')
|
||||||
|
->assertHasErrors(['form.monthly_fee' => [__('jobs.errors.invalid_amount')]])
|
||||||
|
->set('form.monthly_fee', '99,90')
|
||||||
|
->call('save')
|
||||||
|
->assertHasNoErrors();
|
||||||
|
|
||||||
|
expect($this->job->refresh()->monthly_fee_cents)->toBe(9990);
|
||||||
|
|
||||||
|
$this->get(route('jobs.show', $this->job->id))
|
||||||
|
->assertSee('Kuukausihinta')
|
||||||
|
->assertSee("99,90\u{00A0}€", false);
|
||||||
|
|
||||||
|
$this->actingAs(User::factory()->employee()->create());
|
||||||
|
|
||||||
|
$this->get(route('jobs.show', $this->job->id))->assertDontSee('Kuukausihinta');
|
||||||
|
|
||||||
|
Livewire::test('jobs::form', ['job' => $this->job->id])->set('form.name', 'Ylläpito')->call('save')->assertHasNoErrors();
|
||||||
|
|
||||||
|
expect($this->job->refresh()->monthly_fee_cents)->toBe(9990);
|
||||||
|
});
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ use App\Modules\Billing\Domain\Exceptions\ExportNotDraft;
|
|||||||
use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours;
|
use App\Modules\Billing\Domain\Exceptions\InvalidBillableHours;
|
||||||
use App\Modules\Billing\Domain\Exceptions\InvoicesCannotMerge;
|
use App\Modules\Billing\Domain\Exceptions\InvoicesCannotMerge;
|
||||||
use App\Modules\Billing\Domain\Exceptions\JobAlreadyInDraft;
|
use App\Modules\Billing\Domain\Exceptions\JobAlreadyInDraft;
|
||||||
|
use App\Modules\Billing\Domain\ValueObjects\BillingMonths;
|
||||||
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
|
use App\Modules\Billing\Domain\ValueObjects\DraftJob;
|
||||||
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
|
use App\Modules\Billing\Domain\ValueObjects\InvoiceLine;
|
||||||
use App\Modules\Billing\Domain\ValueObjects\InvoiceTotals;
|
use App\Modules\Billing\Domain\ValueObjects\InvoiceTotals;
|
||||||
@@ -41,7 +42,10 @@ function billableJob(int $id, BillingMode $mode = BillingMode::Hours, array $ove
|
|||||||
'customerReference' => null,
|
'customerReference' => null,
|
||||||
'mode' => $mode,
|
'mode' => $mode,
|
||||||
'quotedAmountCents' => null,
|
'quotedAmountCents' => null,
|
||||||
'isDone' => true,
|
'inBillableStatus' => true,
|
||||||
|
'monthlyFeeCents' => null,
|
||||||
|
'billingStartsOn' => '2026-09-15',
|
||||||
|
'billingEndsOn' => null,
|
||||||
], $overrides);
|
], $overrides);
|
||||||
|
|
||||||
return new BillableJob(...$values);
|
return new BillableJob(...$values);
|
||||||
@@ -150,7 +154,7 @@ it('tells why a job cannot be billed', function (BillableJob $job, JobHours $hou
|
|||||||
expect((new BillingRules)->reasonNotBillable($job, $hours, $expenses, $fixedBilled, $rates))->toBe($reason);
|
expect((new BillingRules)->reasonNotBillable($job, $hours, $expenses, $fixedBilled, $rates))->toBe($reason);
|
||||||
})->with([
|
})->with([
|
||||||
'billable hours' => [billableJob(1), new JobHours(1, [1 => 4]), [], false, null],
|
'billable hours' => [billableJob(1), new JobHours(1, [1 => 4]), [], false, null],
|
||||||
'not done' => [billableJob(1, overrides: ['isDone' => false]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::WrongStatus],
|
'not done' => [billableJob(1, overrides: ['inBillableStatus' => false]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::WrongStatus],
|
||||||
'billed monthly or not billable' => [billableJob(1, overrides: ['mode' => null]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::NotBillableBasis],
|
'billed monthly or not billable' => [billableJob(1, overrides: ['mode' => null]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::NotBillableBasis],
|
||||||
'internal customer' => [billableJob(1, overrides: ['isInternal' => true]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::NotBillableBasis],
|
'internal customer' => [billableJob(1, overrides: ['isInternal' => true]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::NotBillableBasis],
|
||||||
'consumer without a code' => [billableJob(1, overrides: ['isConsumer' => true]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::MissingIdentityCode],
|
'consumer without a code' => [billableJob(1, overrides: ['isConsumer' => true]), new JobHours(1, [1 => 4]), [], false, NotBillableReason::MissingIdentityCode],
|
||||||
@@ -163,6 +167,55 @@ it('tells why a job cannot be billed', function (BillableJob $job, JobHours $hou
|
|||||||
'fixed price billed before' => [billableJob(1, BillingMode::FixedPrice, ['quotedAmountCents' => 100000]), new JobHours(1, [1 => 4]), [], true, NotBillableReason::NothingToBill],
|
'fixed price billed before' => [billableJob(1, BillingMode::FixedPrice, ['quotedAmountCents' => 100000]), new JobHours(1, [1 => 4]), [], true, NotBillableReason::NothingToBill],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
it('tells why a monthly fee job cannot be billed', function (array $overrides, array $months, array $expenses, ?NotBillableReason $reason) {
|
||||||
|
$job = billableJob(1, BillingMode::MonthlyFee, $overrides);
|
||||||
|
|
||||||
|
expect((new BillingRules)->reasonNotBillable($job, new JobHours(1, [2 => 8]), $expenses, false, [], $months))->toBe($reason);
|
||||||
|
})->with([
|
||||||
|
'months to bill' => [['monthlyFeeCents' => 9900], ['2026-11'], [], null],
|
||||||
|
'no monthly fee' => [[], ['2026-11'], [], NotBillableReason::MissingMonthlyFee],
|
||||||
|
'every month billed' => [['monthlyFeeCents' => 9900], [], [], NotBillableReason::NothingToBill],
|
||||||
|
'only expenses' => [['monthlyFeeCents' => 9900], [], [new BillableExpense(5, 1, 'Paperi', 500)], null],
|
||||||
|
'not running' => [['monthlyFeeCents' => 9900, 'inBillableStatus' => false], ['2026-11'], [], NotBillableReason::WrongStatus],
|
||||||
|
]);
|
||||||
|
|
||||||
|
it('bills every unbilled month of a monthly fee job and its expenses, not its hours', function () {
|
||||||
|
$job = billableJob(1, BillingMode::MonthlyFee, ['name' => 'Ylläpito', 'monthlyFeeCents' => 9900]);
|
||||||
|
|
||||||
|
$lines = (new BillingRules)->lines($job, $job->toDraftJob(), [1 => 8], [new BillableExpense(5, 1, 'Paperi', 500)], false, [1 => new HourlyRate(1, 'Taitto', 8000)], 2550, ['2026-10', '2026-11']);
|
||||||
|
|
||||||
|
expect(array_map(fn (InvoiceLine $line): array => [$line->kind, $line->period, $line->description, $line->netCents], $lines))->toBe([
|
||||||
|
[LineKind::MonthlyFee, '2026-10', '10/2026 2026-0001 Ylläpito', 9900],
|
||||||
|
[LineKind::MonthlyFee, '2026-11', '11/2026 2026-0001 Ylläpito', 9900],
|
||||||
|
[LineKind::Expense, null, 'Paperi', 500],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('counts the months from the start to the material, the last day or completion, leaving out billed ones', function (?string $endsOn, string $period, array $billed, array $months) {
|
||||||
|
expect(BillingMonths::unbilled('2026-09-15', $endsOn, $period, $billed))->toBe($months);
|
||||||
|
})->with([
|
||||||
|
'up to the material' => [null, '2026-11', [], ['2026-09', '2026-10', '2026-11']],
|
||||||
|
'billed months left out' => [null, '2026-11', ['2026-09', '2026-10'], ['2026-11']],
|
||||||
|
'ends before the material' => ['2026-10-31', '2026-12', [], ['2026-09', '2026-10']],
|
||||||
|
'over the year end' => [null, '2027-01', ['2026-09', '2026-10'], ['2026-11', '2026-12', '2027-01']],
|
||||||
|
'material before the start' => [null, '2026-08', [], []],
|
||||||
|
]);
|
||||||
|
|
||||||
|
it('keeps a monthly fee job on an invoice of its own', function () {
|
||||||
|
$export = draft();
|
||||||
|
$export->addJob(new DraftJob(1, 10, null, null));
|
||||||
|
$export->addJob(new DraftJob(2, 10, null, null, [], ownInvoice: true));
|
||||||
|
|
||||||
|
try {
|
||||||
|
$export->moveJob(2, 1);
|
||||||
|
$this->fail('The jobs were combined.');
|
||||||
|
} catch (InvoicesCannotMerge $exception) {
|
||||||
|
expect($exception->refusal)->toBe(MergeRefusal::MonthlyFeeAlone);
|
||||||
|
}
|
||||||
|
|
||||||
|
$export->moveJob(1, 2);
|
||||||
|
})->throws(InvoicesCannotMerge::class);
|
||||||
|
|
||||||
it('forms hour lines by work type name with the billable hours, then the expenses', function () {
|
it('forms hour lines by work type name with the billable hours, then the expenses', function () {
|
||||||
$rates = [1 => new HourlyRate(1, 'Taitto', 8000), 2 => new HourlyRate(2, 'Kuvaus', 10000)];
|
$rates = [1 => new HourlyRate(1, 'Taitto', 8000), 2 => new HourlyRate(2, 'Kuvaus', 10000)];
|
||||||
$draftJob = (new DraftJob(1, 1, null, null))->withBillableQuarters(1, 6);
|
$draftJob = (new DraftJob(1, 1, null, null))->withBillableQuarters(1, 6);
|
||||||
|
|||||||
Reference in New Issue
Block a user