@@ -0,0 +1,181 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Quotation;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Brick\Math\RoundingMode;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Explicit frozen process rates. No market lookup, payment execution or inferred rate. */
|
||||
class QuotationExchange
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
return Schema::hasTable('quotation_exchange_rates') && Schema::hasColumn('quotations', 'exchange_basis');
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function rates(Requisition $request): array
|
||||
{
|
||||
if (! $this->ready()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(DB::table('quotation_exchange_rates')->where('tenant_id', $request->tenant_id)->where('requisition_id', $request->id)->orderBy('currency')->get()
|
||||
->map(fn ($row) => $this->snapshot($row))->all());
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function record(User $actor, Requisition $request, array $input): void
|
||||
{
|
||||
abort_unless($this->ready(), 503, 'A estrutura de câmbio ainda não está instalada neste ambiente.');
|
||||
if (isset($input['source']) && is_string($input['source'])) {
|
||||
$input['source'] = trim($input['source']);
|
||||
}
|
||||
$data = Validator::make($input, [
|
||||
'operation_id' => 'required|uuid', 'currency' => ['required', 'regex:/^[A-Z]{3}$/', 'not_in:MZN'],
|
||||
'rate' => ['required', 'regex:/^\d{1,8}(\.\d{1,10})?$/', 'numeric', 'gt:0'],
|
||||
'quoted_on' => 'required|date_format:Y-m-d|before_or_equal:today',
|
||||
'source' => 'required|string|min:3|max:1000',
|
||||
])->validate();
|
||||
$data['rate'] = (string) BigDecimal::of($data['rate'])->toScale(10);
|
||||
$data['source'] = trim($data['source']);
|
||||
$hash = hash('sha256', json_encode([$request->id, $data['currency'], $data['rate'], $data['quoted_on'], $data['source']], JSON_THROW_ON_ERROR));
|
||||
DB::transaction(function () use ($actor, $request, $data, $hash) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Finance]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$request = Requisition::query()->visibleTo($actor)->lockForUpdate()->findOrFail($request->id);
|
||||
app(ConflictGuard::class)->assertParticipation($actor, $request);
|
||||
$existing = DB::table('quotation_exchange_rates')->where('tenant_id', $actor->tenant_id)->where('operation_id', $data['operation_id'])->first();
|
||||
if ($existing !== null) {
|
||||
abort_unless($existing->recorded_by === $actor->id && hash_equals($existing->payload_hash, $hash), 409, 'A referência de operação já foi utilizada com outros dados.');
|
||||
|
||||
return;
|
||||
}
|
||||
abort_unless($request->status === 'approved' && ! PurchaseAward::query()->where('requisition_id', $request->id)->exists(), 409, 'O registo de taxas exige processo aprovado, ainda sem adjudicação.');
|
||||
if (DB::table('quotation_exchange_rates')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->where('currency', $data['currency'])->exists()) {
|
||||
throw ValidationException::withMessages(['currency' => 'A taxa desta moeda já está congelada neste processo.']);
|
||||
}
|
||||
$id = DB::table('quotation_exchange_rates')->insertGetId([
|
||||
'tenant_id' => $actor->tenant_id, 'requisition_id' => $request->id, 'recorded_by' => $actor->id,
|
||||
'currency' => $data['currency'], 'rate' => $data['rate'], 'quoted_on' => $data['quoted_on'], 'source' => $data['source'],
|
||||
'operation_id' => $data['operation_id'], 'payload_hash' => $hash, 'created_at' => now(),
|
||||
]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'quotation.exchange_rate_recorded', $request, null,
|
||||
['id' => $id, 'currency' => $data['currency'], 'rate' => $data['rate'], 'quoted_on' => $data['quoted_on'], 'source' => $data['source'], 'operation_id' => $data['operation_id']]);
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
public function basis(Requisition $request, string $currency): ?array
|
||||
{
|
||||
if ($currency === 'MZN') {
|
||||
return null;
|
||||
}
|
||||
abort_unless($this->ready(), 503);
|
||||
$row = DB::table('quotation_exchange_rates')->where('tenant_id', $request->tenant_id)->where('requisition_id', $request->id)->where('currency', $currency)->first();
|
||||
if ($row === null) {
|
||||
throw ValidationException::withMessages(['currency' => 'Finanças deve registar a taxa, data e fonte desta moeda para o processo.']);
|
||||
}
|
||||
|
||||
return $this->snapshot($row);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function snapshot(\stdClass $row): array
|
||||
{
|
||||
return ['schema' => 'sgc.quotation.exchange.v1', 'id' => (int) $row->id, 'tenant_id' => (int) $row->tenant_id,
|
||||
'requisition_id' => (int) $row->requisition_id, 'currency' => $row->currency, 'rate' => (string) BigDecimal::of((string) $row->rate)->toScale(10),
|
||||
'quoted_on' => $row->quoted_on, 'source' => $row->source, 'recorded_by' => (int) $row->recorded_by,
|
||||
'rounding' => 'subtotal_and_tax_half_up_cent', 'reference_currency' => 'MZN'];
|
||||
}
|
||||
|
||||
public function convert(int $minor, string $rate): int
|
||||
{
|
||||
if ($minor < 0 || ! preg_match('/^\d{1,8}(\.\d{1,10})?$/', $rate) || ! BigDecimal::of($rate)->isGreaterThan(0)) {
|
||||
throw new \InvalidArgumentException('Montante ou taxa de câmbio inválidos.');
|
||||
}
|
||||
$result = BigDecimal::of($minor)->multipliedBy($rate)->toScale(0, RoundingMode::HalfUp);
|
||||
if ($result->isGreaterThan(100000000000000)) {
|
||||
throw new \InvalidArgumentException('O valor convertido excede o limite suportado.');
|
||||
}
|
||||
|
||||
return $result->toInt();
|
||||
}
|
||||
|
||||
/** @return array{subtotal_minor:int,tax_minor:int,total_minor:int} */
|
||||
public function amounts(Quotation $quote): array
|
||||
{
|
||||
$basis = $quote->exchange_basis;
|
||||
if ($quote->currency === 'MZN') {
|
||||
abort_unless($basis === null, 409, 'Base cambial incompatível com proposta em MZN.');
|
||||
|
||||
return ['subtotal_minor' => $quote->subtotal_minor, 'tax_minor' => $quote->tax_minor, 'total_minor' => $quote->total_minor];
|
||||
}
|
||||
$request = Requisition::query()->findOrFail($quote->requisition_id);
|
||||
abort_unless(is_array($basis) && $basis === $this->basis($request, $quote->currency), 409, 'A base cambial não corresponde à taxa congelada no processo.');
|
||||
try {
|
||||
$subtotal = $this->convert($quote->subtotal_minor, $basis['rate']);
|
||||
$tax = $this->convert($quote->tax_minor, $basis['rate']);
|
||||
} catch (\InvalidArgumentException) {
|
||||
throw ValidationException::withMessages(['currency' => 'O valor convertido excede o limite suportado.']);
|
||||
}
|
||||
if ($subtotal < 1 || $subtotal + $tax > 100000000000000) {
|
||||
throw ValidationException::withMessages(['currency' => 'O valor convertido deve ser positivo e estar dentro do limite suportado.']);
|
||||
}
|
||||
|
||||
return ['subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax];
|
||||
}
|
||||
|
||||
/** @return array{subtotal_minor:int,tax_minor:int,total_minor:int} */
|
||||
public function orderAmounts(PurchaseOrder $order, int $subtotal, int $tax): array
|
||||
{
|
||||
abort_unless($subtotal >= 0 && $tax >= 0, 409);
|
||||
if ($order->currency === 'MZN') {
|
||||
abort_unless(($order->snapshot['exchange_basis'] ?? null) === null, 409, 'Base cambial incompatível com ordem em MZN.');
|
||||
|
||||
return ['subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax];
|
||||
}
|
||||
$request = Requisition::query()->findOrFail($order->requisition_id);
|
||||
$basis = $order->snapshot['exchange_basis'] ?? null;
|
||||
abort_unless(is_array($basis) && $basis === $this->basis($request, $order->currency), 409, 'Base cambial da ordem indisponível ou inconsistente.');
|
||||
$fullNet = $this->convert($order->subtotal_minor, $basis['rate']);
|
||||
$fullTax = $this->convert($order->tax_minor, $basis['rate']);
|
||||
abort_unless($order->total_minor === $order->subtotal_minor + $order->tax_minor
|
||||
&& ($order->snapshot['reference_amounts'] ?? null) === ['subtotal_minor' => $fullNet, 'tax_minor' => $fullTax, 'total_minor' => $fullNet + $fullTax],
|
||||
409, 'Os valores da ordem não correspondem à referência cambial congelada.');
|
||||
$net = $this->convert($subtotal, $basis['rate']);
|
||||
$vat = $this->convert($tax, $basis['rate']);
|
||||
|
||||
return ['subtotal_minor' => $net, 'tax_minor' => $vat, 'total_minor' => $net + $vat];
|
||||
}
|
||||
|
||||
/** Cumulative conversion preserves the order's frozen MZN commitment across partial invoices.
|
||||
* @return array{subtotal_minor:int,tax_minor:int,total_minor:int}
|
||||
*/
|
||||
public function invoiceAmounts(PurchaseOrder $order, Invoice $invoice): array
|
||||
{
|
||||
if ($order->currency === 'MZN') {
|
||||
return ['subtotal_minor' => $invoice->subtotal_minor, 'tax_minor' => $invoice->tax_minor, 'total_minor' => $invoice->total_minor];
|
||||
}
|
||||
$previous = DB::table('invoices')->where('tenant_id', $order->tenant_id)->where('purchase_order_id', $order->id)
|
||||
->where('status', 'validated')->where('id', '!=', $invoice->id)
|
||||
->selectRaw('COALESCE(SUM(subtotal_minor), 0) AS net, COALESCE(SUM(tax_minor), 0) AS vat')->first();
|
||||
$before = $this->orderAmounts($order, (int) $previous->net, (int) $previous->vat);
|
||||
$after = $this->orderAmounts($order, (int) $previous->net + $invoice->subtotal_minor, (int) $previous->vat + $invoice->tax_minor);
|
||||
|
||||
return ['subtotal_minor' => $after['subtotal_minor'] - $before['subtotal_minor'],
|
||||
'tax_minor' => $after['tax_minor'] - $before['tax_minor'], 'total_minor' => $after['total_minor'] - $before['total_minor']];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user