38 lines
1.6 KiB
PHP
38 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\User;
|
|
|
|
/** Only a current authorised read of an issued invoice can construct this source. */
|
|
final readonly class SalesStockSource
|
|
{
|
|
/** @param array<string,mixed> $snapshot */
|
|
private function __construct(public array $snapshot) {}
|
|
|
|
public static function for(User $actor, int $invoiceId, int $lineNumber, int $quantity): self
|
|
{
|
|
abort_unless($invoiceId > 0 && $lineNumber > 0 && $quantity > 0, 422);
|
|
$invoice = app(CustomerSales::class)->engine($actor)->deliveryInvoice($invoiceId);
|
|
$selected = null;
|
|
foreach ($invoice['lines'] as $line) {
|
|
if ($line['line_no'] === $lineNumber) {
|
|
$selected = $line;
|
|
break;
|
|
}
|
|
}
|
|
abort_unless(is_array($selected) && is_int($selected['stock_item_id'] ?? null)
|
|
&& $quantity <= $selected['quantity_milli'], 409, 'Seleccione uma linha de stock da factura emitida e a quantidade ainda por entregar.');
|
|
|
|
return new self(['invoice_id' => $invoiceId, 'invoice_reference' => $invoice['reference'], 'invoice_revision' => $invoice['revision'],
|
|
'client' => $invoice['client'], 'line_no' => $lineNumber, 'stock_item_id' => $selected['stock_item_id'],
|
|
'invoice_quantity_milli' => $selected['quantity_milli'], 'quantity_milli' => $quantity]);
|
|
}
|
|
|
|
public function verify(User $actor): void
|
|
{
|
|
$current = self::for($actor, $this->snapshot['invoice_id'], $this->snapshot['line_no'], $this->snapshot['quantity_milli']);
|
|
abort_unless($current->snapshot === $this->snapshot, 409, 'A origem da entrega mudou; reabra a factura.');
|
|
}
|
|
}
|