commit melhorias compras1
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-21 21:04:40 +02:00
parent 976271f948
commit 12dd6df28a
108 changed files with 4391 additions and 408 deletions
+6 -4
View File
@@ -82,15 +82,17 @@ class ExternalPaymentWorkflow
$request = Requisition::query()->findOrFail($order->requisition_id);
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $user);
$supplier = Supplier::query()->lockForUpdate()->findOrFail($order->supplier_id);
$bank = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->first();
$bank = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->whereKey($bankId)->first();
$bankWorkflow = app(SupplierBankWorkflow::class);
if ($bank) {
User::query()->where('tenant_id', $user->tenant_id)->whereIn('id', SupplierBankReview::query()->where('supplier_bank_detail_id', $bank->id)->select('reviewed_by'))->orderBy('id')->lockForUpdate()->get();
}
if (! $bank || $bank->id !== $bankId || app(SupplierBankWorkflow::class)->state($supplier) !== 'approved') {
if (! $bank || $bankWorkflow->latest($supplier, $bank->account_key)?->id !== $bankId || $bankWorkflow->state($supplier, $bank->account_key) !== 'approved') {
$this->invalid('A versão bancária actual deve ter duas validações elegíveis. Actualize a ficha; não reutilize uma versão substituída.');
}
if ($bank->currency !== $order->currency || $order->currency !== 'MZN') {
$this->invalid('A moeda da conta deve coincidir com a factura. Câmbio não suportado.');
app(QuotationExchange::class)->orderAmounts($order, $order->subtotal_minor, $order->tax_minor);
if ($bank->currency !== $order->currency || ($invoice->snapshot['currency'] ?? 'MZN') !== $order->currency) {
$this->invalid('A moeda da conta deve coincidir com a factura e a ordem. Não é executada conversão bancária.');
}
return $bank;
+3 -1
View File
@@ -100,7 +100,9 @@ class FormalRecommendation
$admissions = [];
foreach ($comparison['rows'] as $row) {
// Freeze the decision inputs without supplier contacts or private documents.
$rows[] = [...array_intersect_key($row, array_flip(['id', 'supplier_id', 'reference', 'currency', 'subtotal_minor', 'tax_minor', 'total_minor', 'delivery_days', 'valid_until', 'payment_terms', 'weights', 'eligible', 'ineligibility_reasons', 'evaluation_count', 'score_minor', 'items', 'evaluations', 'qualified_evaluations'])), 'supplier_name' => $row['supplier']['name'] ?? 'Fornecedor indisponível'];
$rows[] = [...array_intersect_key($row, array_flip(['id', 'supplier_id', 'reference', 'currency', 'subtotal_minor', 'tax_minor', 'total_minor', 'delivery_days', 'valid_until', 'payment_terms', 'weights', 'eligible', 'ineligibility_reasons', 'evaluation_count', 'score_minor', 'items', 'evaluations', 'qualified_evaluations'])),
...($row['exchange_basis'] === null ? [] : ['exchange_basis' => $row['exchange_basis'], 'reference_amounts' => $row['reference_amounts']]),
'supplier_name' => $row['supplier']['name'] ?? 'Fornecedor indisponível'];
$decision = AdmissionDecision::query()->where('admission_adoption_id', $adoption->id ?? 0)->where('quotation_id', $row['id'])->latest('revision')->first();
$admissions[] = ['quotation_id' => $row['id'], 'basis' => $admission->basis($request, $row['id']), 'decision' => $decision?->toArray(), 'reviews' => AdmissionReview::query()->where('admission_decision_id', $decision->id ?? 0)->orderBy('id')->get()->toArray()];
}
+11 -2
View File
@@ -60,7 +60,7 @@ class InventoryDispositions
$reversed = app(InventoryReversals::class)->corrections('operation');
return (int) app(SupplyPlanning::class)->latest('stock_event')->where('state', 'executed')->whereJsonContains('data->kind', 'supplier_return')
->whereJsonContains('data->purchase_order_item_id', $line)->get()->reject(fn ($r) => isset($reversed[$r->data['stock_operation_id']]))->sum(fn ($r) => $r->data['quantity_milli']);
->whereJsonContains('data->purchase_order_item_id', $line)->get()->reject(fn ($r) => isset($reversed[$r->data['stock_operation_id']]))->sum(fn ($r) => $r->data['document_quantity_milli'] ?? $r->data['quantity_milli']);
}
/** Minimal receipt facts for the existing Finance reconciliation screen.
@@ -114,9 +114,15 @@ class InventoryDispositions
$this->check(($source['lot']['origin']['receipt_item_id'] ?? null) === $line->id, 'data.receipt_item_id', 'O lote deve ter origem comprovada nesta linha de recepção; igualdade de código não prova a origem.');
}
$returned = $this->returnedForReceipt($line->id);
$this->check($returned + $data['quantity_milli'] <= $line->accepted_milli, 'data.quantity', 'A soma das devoluções não pode exceder a quantidade originalmente aceite.');
$conversion = app(ReceiptQuantityConversion::class);
$this->check($returned + $data['quantity_milli'] <= $conversion->physicalAccepted($line), 'data.quantity', 'A soma das devoluções não pode exceder a quantidade física originalmente aceite.');
$documentQuantity = $conversion->documentary($line, $data['quantity_milli']);
$source['receipt'] = ['id' => $receipt->id, 'number' => $receipt->number, 'item_id' => $line->id, 'purchase_order_item_id' => $line->purchase_order_item_id,
'purchase_order_id' => $order->id, 'order_number' => $order->number, 'supplier_id' => $order->supplier_id, 'supplier_name' => $receipt->snapshot['supplier']['name'], 'accepted_milli' => $line->accepted_milli];
if (isset($line->snapshot['quantity_conversion'])) {
$source['receipt']['quantity_conversion'] = $line->snapshot['quantity_conversion'];
$source['receipt']['document_quantity_milli'] = $documentQuantity;
}
$observed['previously_returned_milli'] = $returned;
}
@@ -168,6 +174,9 @@ class InventoryDispositions
$snapshot = $this->basis($data);
$snapshot['contributors'] = array_values(array_unique([...($old?->snapshot['contributors'] ?? []), $actor->id]));
$data['purchase_order_item_id'] = $snapshot['source']['receipt']['purchase_order_item_id'] ?? null;
if (isset($snapshot['source']['receipt']['document_quantity_milli'])) {
$data['document_quantity_milli'] = $snapshot['source']['receipt']['document_quantity_milli'];
}
$state = 'draft';
} else {
$this->check($old !== null, 'action', 'Prepare primeiro o processo.');
+3 -2
View File
@@ -104,8 +104,9 @@ class InvestmentWorkflow
return null;
}
$policy = $this->requireCurrent();
$amount = $policy->includes_tax ? $quotation->total_minor : $quotation->subtotal_minor;
if ($amount > $policy->ceiling_minor || $quotation->currency !== 'MZN') {
$reference = app(QuotationExchange::class)->amounts($quotation);
$amount = $policy->includes_tax ? $reference['total_minor'] : $reference['subtotal_minor'];
if ($amount > $policy->ceiling_minor) {
throw ValidationException::withMessages(['investment' => 'O total do processo excede o tecto de investimento da empresa ou usa moeda não suportada. Não há dispensa automática.']);
}
app(EquipmentWorkflow::class)->assertTechnical($request);
+11 -6
View File
@@ -105,12 +105,13 @@ class InvoiceWorkflow
$request = Requisition::query()->findOrFail($order->requisition_id);
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $user);
$number = Str::upper(Str::squish($data['number']));
SgfInvoiceDispatches::assertLocalRegistration($user->tenant_id,$order->supplier_id,$number);
SgfInvoiceDispatches::assertLocalRegistration($user->tenant_id, $order->supplier_id, $number);
if ($number === '' || Invoice::query()->where('supplier_id', $order->supplier_id)->where('number', $number)->exists()) {
$this->invalid('Número de factura vazio ou já registado para este fornecedor.');
}
if ($order->status !== 'issued' || $order->currency !== 'MZN' || substr($data['issued_on'], 0, 4) !== now()->format('Y') || $data['issued_on'] > today()->format('Y-m-d') || $data['issued_on'] < substr((string) $order->getRawOriginal('issued_at'), 0, 10)) {
$this->invalid('Factura deve referir ordem emitida em MZN, com data válida no exercício actual e posterior à emissão.');
app(QuotationExchange::class)->orderAmounts($order, $order->subtotal_minor, $order->tax_minor);
if ($order->status !== 'issued' || substr($data['issued_on'], 0, 4) !== now()->format('Y') || $data['issued_on'] > today()->format('Y-m-d') || $data['issued_on'] < substr((string) $order->getRawOriginal('issued_at'), 0, 10)) {
$this->invalid('Factura deve referir ordem emitida, com data válida no exercício actual e posterior à emissão.');
}
$lines = $this->lines($order, $data['items']);
$subtotal = array_sum(array_column($lines, 'subtotal_minor'));
@@ -120,7 +121,9 @@ class InvoiceWorkflow
$this->invalid('Totais da factura divergem da conferência com a ordem e recepção. Verifique os arredondamentos das facturas parciais.');
}
}
$invoice = Invoice::query()->create(['tenant_id' => $user->tenant_id, 'purchase_order_id' => $order->id, 'supplier_id' => $order->supplier_id, 'created_by' => $user->id, 'number' => $number, 'issued_on' => $data['issued_on'], 'subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax, 'snapshot' => ['supplier' => $order->snapshot['supplier'], 'order_number' => $order->number, 'author' => $user->only(['id', 'name']), 'currency' => 'MZN', 'development_only' => true, 'matching_tolerance' => 'zero', 'rounding' => 'cumulative_half_up']]);
$invoice = Invoice::query()->create(['tenant_id' => $user->tenant_id, 'purchase_order_id' => $order->id, 'supplier_id' => $order->supplier_id, 'created_by' => $user->id, 'number' => $number, 'issued_on' => $data['issued_on'], 'subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax, 'snapshot' => ['supplier' => $order->snapshot['supplier'], 'order_number' => $order->number, 'author' => $user->only(['id', 'name']), 'currency' => $order->currency,
...($order->currency === 'MZN' ? [] : ['exchange_basis' => $order->snapshot['exchange_basis']]),
'development_only' => true, 'matching_tolerance' => 'zero', 'rounding' => 'cumulative_half_up']]);
$invoice->items()->createMany($lines);
app(RequisitionWorkflow::class)->audit($user, 'invoice.created', $request, null, $invoice->load('items')->toArray());
@@ -158,9 +161,11 @@ class InvoiceWorkflow
}
}
$adapter = app(CommonBudget::class);
$effect = $adapter->execute(fn () => $adapter->for($user)->consume($request->id, $invoice->id, (int) $invoice->total_minor, (int) $invoice->subtotal_minor));
$reference = app(QuotationExchange::class)->invoiceAmounts($order, $invoice);
$effect = $adapter->execute(fn () => $adapter->for($user)->consume($request->id, $invoice->id, $reference['total_minor'], $reference['subtotal_minor']));
$invoice->update(['status' => 'validated', 'validated_by' => $user->id, 'validated_at' => now()]);
app(RequisitionWorkflow::class)->audit($user, 'invoice.validated', $request, null, ['invoice_id' => $invoice->id] + $effect);
app(RequisitionWorkflow::class)->audit($user, 'invoice.validated', $request, null, ['invoice_id' => $invoice->id,
...($order->currency === 'MZN' ? [] : ['reference_amounts' => $reference, 'exchange_basis' => $order->snapshot['exchange_basis']])] + $effect);
});
}
}
+3 -2
View File
@@ -82,9 +82,10 @@ class OrderCancellationWorkflow
private function source(PurchaseOrder $order): void
{
if ($order->getRawOriginal('status') !== 'issued' || $order->currency !== 'MZN' || GoodsReceipt::query()->where('purchase_order_id', $order->id)->exists()
app(QuotationExchange::class)->orderAmounts($order, $order->subtotal_minor, $order->tax_minor);
if ($order->getRawOriginal('status') !== 'issued' || GoodsReceipt::query()->where('purchase_order_id', $order->id)->exists()
|| Invoice::query()->where('purchase_order_id', $order->id)->exists()) {
throw ValidationException::withMessages(['order' => 'Este circuito exige ordem emitida em MZN sem qualquer recepção, factura ou pagamento.']);
throw ValidationException::withMessages(['order' => 'Este circuito exige ordem emitida sem qualquer recepção, factura ou pagamento.']);
}
}
+131
View File
@@ -0,0 +1,131 @@
<?php
namespace App\Services;
/** Exports only the already authorised projection, without reading other sources. */
class ProcurementReviewCsv
{
/** @param array<string,mixed> $report */
public function render(array $report): string
{
$file = fopen('php://temp', 'w+');
if ($file === false) {
throw new \RuntimeException('Não foi possível preparar a exportação.');
}
$write = static function (array $cells) use ($file): void {
$safe = array_map(static function (mixed $value): string {
$text = $value === null ? 'Não disponível' : (is_bool($value) ? ($value ? 'Sim' : 'Não') : (string) $value);
return preg_match('/^[\s\x00-\x1F]*[=+\-@]/u', $text) ? "'".$text : $text;
}, $cells);
if (fputcsv($file, $safe, ';', '"', '') === false) {
throw new \RuntimeException('Não foi possível escrever a exportação.');
}
};
$fields = static function (string $section, string $reference, array $source, array $labels) use ($write): void {
foreach ($labels as $key => $label) {
$write([$section, $reference, $label, $source[$key] ?? null]);
}
};
try {
fwrite($file, "\xEF\xBB\xBF");
$write(['Secção', 'Registo', 'Campo', 'Valor']);
$fields('Consulta', '', $report, ['company' => 'Empresa', 'generated_at' => 'Consultado em', 'generated_by' => 'Consultado por']);
$write(['Consulta', '', 'Natureza', 'Consulta actual; não constitui decisão, assinatura ou autorização financeira.']);
$fields('Pedido', '', $report['requisition'], ['id' => 'Identificador', 'number' => 'Referência', 'status' => 'Estado', 'justification' => 'Fundamentação', 'department' => 'Departamento', 'requester' => 'Solicitante']);
$comparison = $report['comparison'];
$fields('Comparação actual', '', $comparison, ['ready' => 'Comparação completa', 'top_count' => 'Propostas com maior pontuação']);
$fields('Regra de comparação', '', $comparison['policy'], ['revision' => 'Versão', 'configured' => 'Configuração explícita', 'minimum_proposals' => 'Mínimo de propostas', 'minimum_evaluators' => 'Mínimo de avaliadores']);
$criteria = ['price' => 'Preço', 'quality' => 'Qualidade', 'delivery' => 'Entrega', 'history' => 'Histórico', 'payment' => 'Pagamento'];
$fields('Ponderações da regra (%)', '', $comparison['policy']['weights'], $criteria);
foreach ($comparison['rows'] as $row) {
$ref = (string) $row['id'];
$fields('Proposta actual', $ref, $row, ['reference' => 'Referência', 'supplier' => 'Fornecedor', 'currency' => 'Moeda', 'subtotal_minor' => 'Subtotal (centavos)', 'tax_minor' => 'IVA (centavos)', 'total_minor' => 'Total (centavos)', 'delivery_days' => 'Prazo de entrega (dias)', 'valid_until' => 'Válida até', 'eligible' => 'Elegível na consulta', 'evaluation_count' => 'Avaliações elegíveis', 'score_minor' => 'Pontuação (centésimos de 10)', 'is_top' => 'Maior pontuação numa comparação completa']);
$fields('Ponderações da proposta (%)', $ref, $row['weights'], $criteria);
if (isset($row['exchange_basis'])) {
$fields('Taxa congelada da proposta', $ref, $row['exchange_basis'], ['id' => 'Registo da taxa', 'currency' => 'Moeda original', 'rate' => 'MZN por unidade original', 'quoted_on' => 'Data da taxa', 'source' => 'Fonte', 'recorded_by' => 'Registada por (utilizador)', 'rounding' => 'Arredondamento']);
if ($row['reference_amounts'] !== null) {
$fields('Referência em MZN', $ref, $row['reference_amounts'], ['subtotal_minor' => 'Subtotal (centavos MZN)', 'tax_minor' => 'IVA (centavos MZN)', 'total_minor' => 'Total (centavos MZN)']);
}
}
foreach ($row['ineligibility_reasons'] as $reason) {
$write(['Proposta actual', $ref, 'Motivo de inelegibilidade', $reason]);
}
if ($row['commercial_terms'] !== null) {
$terms = $row['commercial_terms'];
$fields('Condições económicas', $ref, $terms, ['version' => 'Versão', 'discount_basis' => 'Base do desconto', 'rounding' => 'Arredondamento']);
foreach ($terms['lines'] as $line) {
$fields('Desconto por linha', $ref.':'.$line['requisition_item_id'], $line, ['gross_unit_minor' => 'Preço unitário antes do desconto (centavos)', 'discount_type' => 'Tipo', 'discount_value' => 'Valor informado', 'net_unit_minor' => 'Preço unitário líquido (centavos)']);
}
}
}
foreach (['admission' => 'Regime de admissão', 'recommendation' => 'Regime de recomendação'] as $key => $section) {
$record = $report[$key];
$write([$section, '', 'Adopção registada', $record !== null]);
if ($record !== null) {
$fields($section, (string) $record['id'], $record, ['revision' => 'Versão', 'reason' => 'Fundamentação']);
$fields($section, (string) $record['id'], $record['snapshot'], ['policy_revision' => 'Versão da política', 'required_count' => 'Confirmações independentes']);
foreach ($record['snapshot']['roles'] as $role) {
$write([$section, (string) $record['id'], 'Função prevista', $role]);
}
}
}
$qualification = $report['qualification'];
$write(['Qualificação documental', '', 'Versão registada', $qualification !== null]);
if ($qualification !== null) {
$ref = (string) $qualification['id'];
$fields('Qualificação documental', $ref, $qualification, ['revision' => 'Versão', 'created_at' => 'Registada em', 'author' => 'Autor', 'reason' => 'Fundamentação', 'is_current' => 'Base corresponde às propostas actuais']);
foreach ($qualification['criteria'] as $criterion) {
$fields('Requisito documental', $ref.':'.$criterion['id'], $criterion, ['label' => 'Requisito', 'category' => 'Categoria', 'required' => 'Obrigatório']);
}
foreach ($qualification['proposals'] as $proposal) {
$fields('Proposta na qualificação', (string) $proposal['id'], $proposal, ['reference' => 'Referência preservada', 'supplier' => 'Fornecedor preservado']);
foreach ($proposal['analyses'] as $analysis) {
$ref = $proposal['id'].':'.$analysis['id'];
$fields('Análise documental', $ref, $analysis, ['revision' => 'Versão', 'created_at' => 'Registada em', 'reason' => 'Fundamentação']);
$fields('Analista preservado', $ref, $analysis['analyst'], ['name' => 'Nome', 'profile_label' => 'Perfil', 'purchasing_role' => 'Função']);
foreach ($analysis['answers'] as $answer) {
$fields('Resposta documental', $ref.':'.$answer['criterion_id'], $answer, ['result' => 'Resultado', 'evidence' => 'Evidência', 'reason' => 'Fundamentação']);
}
}
}
}
foreach (['opening' => 'Abertura', 'award' => 'Adjudicação', 'order' => 'Ordem'] as $key => $section) {
$record = $report[$key];
$write([$section, '', 'Registo disponível', $record !== null]);
if ($record !== null) {
$fields($section, (string) $record['id'], $record, match ($key) {
'opening' => ['revision' => 'Versão', 'reference' => 'Referência', 'source_changed' => 'Base difere das propostas actuais'],
'award' => ['status' => 'Estado', 'total_minor' => 'Total (centavos)'],
default => ['number' => 'Referência', 'currency' => 'Moeda', 'total_minor' => 'Total (centavos)'],
});
}
}
$fulfilment = $report['fulfilment'];
$write(['Recepções', '', 'Registos disponíveis', count($fulfilment['receipts'])]);
foreach ($fulfilment['receipts'] as $receipt) {
$fields('Recepção', (string) $receipt['id'], $receipt, ['received_on' => 'Recebida em', 'delivery_note' => 'Guia']);
}
$write(['Execução financeira', '', 'Consulta autorizada', $fulfilment['finance_visible']]);
if ($fulfilment['finance_visible']) {
foreach (['invoices' => 'Factura', 'payments' => 'Pagamento externo'] as $key => $section) {
$write([$section, '', 'Registos disponíveis', count($fulfilment[$key])]);
foreach ($fulfilment[$key] as $record) {
$fields($section, (string) $record['id'], $record, $key === 'invoices'
? ['number' => 'Referência', 'status' => 'Estado', 'issued_on' => 'Emitida em', 'total_minor' => 'Total (centavos)', 'currency' => 'Moeda']
: ['invoice_id' => 'Factura de origem', 'status' => 'Estado', 'paid_on' => 'Data informada', 'amount_minor' => 'Montante (centavos)', 'currency' => 'Moeda']);
}
}
}
rewind($file);
$content = stream_get_contents($file);
if ($content === false) {
throw new \RuntimeException('Não foi possível ler a exportação.');
}
return $content;
} finally {
fclose($file);
}
}
}
+1
View File
@@ -40,6 +40,7 @@ class ProcurementReviewReport
...array_intersect_key($row, array_flip(['id', 'reference', 'currency', 'subtotal_minor', 'tax_minor', 'total_minor', 'delivery_days', 'valid_until', 'weights', 'eligible', 'ineligibility_reasons', 'evaluation_count', 'score_minor', 'commercial_terms'])),
'supplier' => $row['supplier']['name'] ?? 'Fornecedor indisponível',
'is_top' => $comparison['ready'] && in_array($row['id'], $comparison['top_ids'], true),
...($row['exchange_basis'] === null ? [] : ['exchange_basis' => $row['exchange_basis'], 'reference_amounts' => $row['reference_amounts']]),
];
}
$openingWorkflow = app(ProposalOpeningWorkflow::class);
+13 -2
View File
@@ -11,6 +11,7 @@ use Brick\Math\BigDecimal;
use Brick\Math\Exception\MathException;
use Brick\Math\RoundingMode;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Tempo\Purchasing\Economic\ProposalScoring;
class ProposalComparison
@@ -27,6 +28,12 @@ class ProposalComparison
$rows = [];
foreach ($quotes as $quote) {
$reasons = [];
$reference = null;
try {
$reference = app(QuotationExchange::class)->amounts($quote);
} catch (\InvalidArgumentException|HttpExceptionInterface|ValidationException $error) {
$reasons[] = 'Base cambial ausente, inválida ou incompatível com o processo.';
}
if ($adopted && ! app(FormalAdmission::class)->admitted($requisition, $quote->id)) {
$reasons[] = 'O regime adoptado exige admissão confirmada na base actual.';
}
@@ -51,10 +58,13 @@ class ProposalComparison
'eligible' => $reasons === [], 'ineligibility_reasons' => $reasons,
'qualified_evaluations' => $evaluations->toArray(), 'evaluation_count' => $evaluations->count(),
'score' => null, 'score_minor' => null,
'reference_amounts' => $reference,
'exchange_basis' => $quote->exchange_basis,
];
}
$eligible = array_values(array_filter($rows, fn ($row) => $row['eligible']));
$ranking = (new ProposalScoring)->rank($rows, $policy['minimum_evaluators']);
$rankingRows = array_map(fn ($row) => [...$row, 'subtotal_minor' => $row['reference_amounts']['subtotal_minor'] ?? $row['subtotal_minor']], $rows);
$ranking = (new ProposalScoring)->rank($rankingRows, $policy['minimum_evaluators']);
$topIds = $ranking['top_ids'];
foreach ($rows as &$row) {
if (isset($ranking['scores'][$row['id']])) {
@@ -72,6 +82,7 @@ class ProposalComparison
'qualified_ids' => array_column($row['qualified_evaluations'], 'id'),
'eligible' => $row['eligible'], 'score_minor' => $row['score_minor'],
...($row['commercial_terms'] === null ? [] : ['commercial_terms' => $row['commercial_terms']]),
...($row['exchange_basis'] === null ? [] : ['exchange_basis' => $row['exchange_basis'], 'reference_amounts' => $row['reference_amounts']]),
];
}
if ($requisition->comparison_policy !== null) {
@@ -128,7 +139,7 @@ class ProposalComparison
private function validAmounts(Quotation $quote, Requisition $requisition): bool
{
if ($quote->currency !== 'MZN' || $quote->delivery_days < 1 || $quote->subtotal_minor <= 0 || $quote->total_minor > 100000000000000) {
if (! preg_match('/^[A-Z]{3}$/', $quote->currency) || $quote->delivery_days < 1 || $quote->subtotal_minor <= 0 || $quote->total_minor > 100000000000000) {
return false;
}
$requested = $requisition->items()->get()->keyBy('id');
+1
View File
@@ -23,6 +23,7 @@ class ProposalOpeningWorkflow
...$quote->only(['id', 'reference', 'currency', 'subtotal_minor', 'tax_minor', 'total_minor', 'delivery_days', 'valid_until', 'payment_terms']),
'supplier' => $quote->supplier?->only(['id', 'name', 'nuit']),
...($quote->commercial_terms === null ? [] : ['commercial_terms' => $quote->commercial_terms]),
...($quote->exchange_basis === null ? [] : ['exchange_basis' => $quote->exchange_basis]),
'items' => $quote->items->map(fn ($item) => $item->only(['requisition_item_id', 'description', 'quantity', 'unit_price_minor', 'tax_rate', 'subtotal_minor', 'tax_minor', 'total_minor']))->all(),
])->all());
}
+8 -5
View File
@@ -42,18 +42,19 @@ class PurchaseWorkflow
$admission = app(FormalAdmission::class)->selection($requisition, $quote->id);
$recommendation = app(FormalRecommendation::class)->selection($requisition, $quote->id);
$investment = app(InvestmentWorkflow::class)->check($requisition, $quote);
app(BudgetWorkflow::class)->record($user, $requisition, 'award', $quote->total_minor, $quote->subtotal_minor);
$reference = app(QuotationExchange::class)->amounts($quote);
app(BudgetWorkflow::class)->record($user, $requisition, 'award', $reference['total_minor'], $reference['subtotal_minor']);
$award = PurchaseAward::query()->create([
'tenant_id' => $user->tenant_id, 'requisition_id' => $requisition->id, 'quotation_id' => $quote->id,
'created_by' => $user->id, 'justification' => $data['justification'], 'delivery_date' => $data['delivery_date'],
'delivery_location' => $data['delivery_location'], 'status' => 'pending',
'subtotal_minor' => $quote->subtotal_minor, 'tax_minor' => $quote->tax_minor, 'total_minor' => $quote->total_minor,
...$reference,
'approval_snapshot' => $rules, 'decision_matrix' => $result['rows'], 'comparison_hash' => $result['fingerprint'],
'investment_snapshot' => $investment,
'admission_snapshot' => $admission,
'recommendation_snapshot' => $recommendation,
]);
$roles = $this->roles($rules, $rules['approval_includes_tax'] ? $quote->total_minor : $quote->subtotal_minor, $requisition->items()->where('purchase_type', 'equipment')->exists());
$roles = $this->roles($rules, $rules['approval_includes_tax'] ? $reference['total_minor'] : $reference['subtotal_minor'], $requisition->items()->where('purchase_type', 'equipment')->exists());
foreach ($roles as $position => $role) {
$award->approvals()->create(['tenant_id' => $user->tenant_id, 'position' => $position + 1, 'role' => $role]);
}
@@ -162,9 +163,10 @@ class PurchaseWorkflow
}
}
$snapshot = [
...($quote->exchange_basis === null ? [] : ['exchange_basis' => $quote->exchange_basis, 'reference_amounts' => app(QuotationExchange::class)->amounts($quote)]),
...($catalogueSources === [] ? [] : ['catalogue_sources' => $catalogueSources]),
'development_only' => true, 'budget_checked' => false,
'budget_control' => app(BudgetWorkflow::class)->record($user, $requisition, 'commit', $quote->total_minor, $quote->subtotal_minor),
'budget_control' => app(BudgetWorkflow::class)->record($user, $requisition, 'commit', $award->total_minor, $award->subtotal_minor),
'investment_rules' => $award->investment_snapshot,
'equipment_requests' => $requisition->items()->where('purchase_type', 'equipment')->get()->map(fn ($line) => $line->only(['id', 'description', 'production_area']))->all(),
'company' => Tenant::query()->findOrFail($user->tenant_id)->only(['id', 'name']),
@@ -216,8 +218,9 @@ class PurchaseWorkflow
if (app(FormalRecommendation::class)->selection($requisition, $quote->id) !== $award->recommendation_snapshot) {
throw ValidationException::withMessages(['recommendation' => 'A recomendação já não corresponde à base da adjudicação. Prepare a revisão autorizada antes de emitir.']);
}
$reference = app(QuotationExchange::class)->amounts($quote);
if ($result['fingerprint'] !== $award->comparison_hash || $award->approval_snapshot !== $rules ||
$quote->subtotal_minor !== $award->subtotal_minor || $quote->tax_minor !== $award->tax_minor || $quote->total_minor !== $award->total_minor) {
$reference['subtotal_minor'] !== $award->subtotal_minor || $reference['tax_minor'] !== $award->tax_minor || $reference['total_minor'] !== $award->total_minor) {
throw ValidationException::withMessages(['comparison' => 'A base da adjudicação mudou. As aprovações anteriores não autorizam a emissão com dados diferentes.']);
}
+181
View File
@@ -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']];
}
}
@@ -0,0 +1,86 @@
<?php
namespace App\Services;
use App\Models\GoodsReceiptItem;
use App\Models\PurchaseOrderItem;
use App\Models\StockItem;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Tempo\Inventory\QuantityConversion;
/** Host basis frozen on first accepted receipt of this order line/article. */
final class ReceiptQuantityConversion
{
/** @param array<string,mixed>|null $input
* @return array<string,mixed>|null
*/
public function freeze(User $actor, PurchaseOrderItem $line, StockItem $stock, int $accepted, ?array $input): ?array
{
$same = mb_strtolower(trim($stock->unit)) === mb_strtolower(trim($line->unit));
foreach (GoodsReceiptItem::query()->where('purchase_order_item_id', $line->id)->where('accepted_milli', '>', 0)->get() as $previous) {
$frozen = $previous->snapshot['quantity_conversion'] ?? null;
if (is_array($frozen) && ($same || $frozen['stock_item_id'] !== $stock->id || $frozen['stock_unit'] !== $stock->unit || $frozen['document_unit'] !== $line->unit)) {
throw ValidationException::withMessages(['items' => 'O artigo e as unidades já estão congelados nesta linha.']);
}
}
if ($same) {
if ($input !== null) {
throw ValidationException::withMessages(['items' => 'Unidades coincidentes não exigem um factor de conversão.']);
}
return null;
}
if (config('inventory_conversion.qa_enabled') !== true || ! app()->environment('testing')) {
throw ValidationException::withMessages(['items' => 'A conversão de unidades está preparada apenas para QA.']);
}
$v = Validator::make($input ?? [], [
'numerator' => ['required', 'string', 'regex:/^[1-9]\d{0,8}$/D'],
'denominator' => ['required', 'string', 'regex:/^[1-9]\d{0,8}$/D'],
'source' => 'required|string|max:500', 'version' => 'required|string|max:100',
])->validate();
$basis = ['schema' => 'inventory.quantity.v1', 'stock_item_id' => $stock->id, 'document_unit' => $line->unit, 'stock_unit' => $stock->unit,
'numerator' => $v['numerator'], 'denominator' => $v['denominator'], 'source' => trim($v['source']), 'version' => trim($v['version'])];
if ($basis['source'] === '' || $basis['version'] === '') {
throw ValidationException::withMessages(['items' => 'Indique fonte e versão da conversão.']);
}
foreach (GoodsReceiptItem::query()->where('purchase_order_item_id', $line->id)->where('accepted_milli', '>', 0)->get() as $previous) {
$frozen = $previous->snapshot['quantity_conversion'] ?? null;
if (! is_array($frozen) || array_intersect_key($frozen, $basis) !== $basis) {
throw ValidationException::withMessages(['items' => 'Conserve artigo, unidades, factor, fonte e versão já congelados nesta linha.']);
}
}
// Load and validate the same writer artifact before using its arithmetic; never a second implementation.
app(ReceiptStockMovement::class)->for($actor);
try {
$physical = QuantityConversion::toBase((string) $accepted, $basis['numerator'], $basis['denominator']);
} catch (\InvalidArgumentException $e) {
throw ValidationException::withMessages(['items' => $e->getMessage()]);
}
return [...$basis, 'accepted_document_milli' => (string) $accepted, 'accepted_stock_milli' => $physical];
}
public function physicalAccepted(GoodsReceiptItem $line): int
{
$basis = $line->snapshot['quantity_conversion'] ?? null;
return $basis === null ? $line->accepted_milli : (int) $basis['accepted_stock_milli'];
}
public function documentary(GoodsReceiptItem $line, int $physical): int
{
$basis = $line->snapshot['quantity_conversion'] ?? null;
if ($basis === null) {
return $physical;
}
abort_unless(config('inventory_conversion.qa_enabled') === true, 503, 'Convers?o ainda n?o instalada.');
app(ReceiptStockMovement::class)->load();
try {
return (int) QuantityConversion::fromBase((string) $physical, $basis['numerator'], $basis['denominator']);
} catch (\InvalidArgumentException $e) {
throw ValidationException::withMessages(['data.quantity' => $e->getMessage()]);
}
}
}
+43 -11
View File
@@ -5,24 +5,56 @@ namespace App\Services;
use App\Enums\PurchasingRole;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Tempo\Inventory\ReceiptMovementWriter;
/** Called only within ReceiptWorkflow's company-locked transaction. */
final class ReceiptStockMovement
{
public function for(User $actor): \Tempo\Inventory\ReceiptMovementWriter
public function load(): void
{
$root=base_path('packages/inventory-write/releases/0.1.0');
if(!is_file($root.'/manifest.json')||!hash_equals('f0b99e591f9a4df135e685f64ceffad77bed259222debe0f34c20f95e3cad800',hash_file('sha256',$root.'/manifest.json')))
$root = base_path('packages/inventory-write/releases/0.1.0');
$pin = 'f0b99e591f9a4df135e685f64ceffad77bed259222debe0f34c20f95e3cad800';
$files = ['bootstrap.php', 'src/ReceiptMovementWriter.php'];
if (config('inventory_conversion.qa_enabled') === true) {
abort_unless(app()->environment('testing'), 503, 'Extensão de conversão limitada a QA.');
$connection = DB::connection();
abort_unless(($connection->getDriverName() === 'sqlite' && $connection->getDatabaseName() === ':memory:')
|| ($connection->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $connection->getDatabaseName())), 503, 'Base QA isolada obrigatória.');
$root = base_path('packages/inventory-write/development');
$pin = '90cf565537e7fd48eb54a87bcfd6d585cf53239f075764910047838b3b8b4c38';
$files[] = 'src/QuantityConversion.php';
}
$bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false;
if (! is_string($bytes) || ! hash_equals($pin, hash('sha256', $bytes))) {
throw new \LogicException('Pacote de recepção incompatível; não executar outro escritor.');
$manifest=json_decode(file_get_contents($root.'/manifest.json'),true,512,JSON_THROW_ON_ERROR);
foreach(['bootstrap.php','src/ReceiptMovementWriter.php'] as $file)
if(!is_file($root.'/'.$file)||!hash_equals($manifest['files'][$file]??'',hash_file('sha256',$root.'/'.$file)))throw new \LogicException('Pacote de recepção alterado.');
}
$manifest = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
foreach ($files as $file) {
$actual = is_file($root.'/'.$file) ? hash_file('sha256', $root.'/'.$file) : false;
if (! is_string($actual) || ! hash_equals($manifest['files'][$file] ?? '', $actual)) {
throw new \LogicException('Pacote de recepção alterado.');
}
}
if (class_exists(ReceiptMovementWriter::class, false)) {
$loaded = (new \ReflectionClass(ReceiptMovementWriter::class))->getFileName();
if (! is_string($loaded) || realpath($loaded) !== realpath($root.'/src/ReceiptMovementWriter.php')) {
throw new \LogicException('Escritor já carregado de outra versão; use um kernel QA separado.');
}
}
require_once $root.'/bootstrap.php';
$schema=match(DB::connection()->getDriverName()){
'pgsql'=>'public','sqlite'=>'main','mysql','mariadb'=>DB::connection()->getDatabaseName(),
default=>throw new \LogicException('Driver de inventário não suportado.'),
}
public function for(User $actor): ReceiptMovementWriter
{
$this->load();
$schema = match (DB::connection()->getDriverName()) {
'pgsql' => 'public','sqlite' => 'main','mysql','mariadb' => DB::connection()->getDatabaseName(),
default => throw new \LogicException('Driver de inventário não suportado.'),
};
return new \Tempo\Inventory\ReceiptMovementWriter(DB::connection(),$schema,(int)$actor->tenant_id,(int)$actor->id,
function () use ($actor) {app(CurrentActor::class)->lock($actor,[PurchasingRole::Warehouse]);});
return new ReceiptMovementWriter(DB::connection(), $schema, (int) $actor->tenant_id, (int) $actor->id,
function () use ($actor) {
app(CurrentActor::class)->lock($actor, [PurchasingRole::Warehouse]);
});
}
}
+7 -3
View File
@@ -84,7 +84,7 @@ class ReceiptWorkflow
throw ValidationException::withMessages(['delivery_note' => 'Indique a guia de remessa do fornecedor.']);
}
$inputs = [];
/** @var list<array{purchase_order_item_id: int, received_quantity: string, accepted_quantity: string, quality_status: string, stock_item_id?: int|null, notes?: string|null, lots?:list<array<string,mixed>>}> $requested */
/** @var list<array{purchase_order_item_id: int, received_quantity: string, accepted_quantity: string, quality_status: string, stock_item_id?: int|null, notes?: string|null, conversion?:array<string,mixed>|null, lots?:list<array<string,mixed>>}> $requested */
$requested = $data['items'];
$supplyMappings = Schema::hasTable('supply_records')
? app(SupplyPlanning::class)->latest('delivery')->where('purchase_order_id', $order->id)->get() : collect();
@@ -108,6 +108,7 @@ class ReceiptWorkflow
}
$inputs[] = [
...(! empty($line['lots']) ? ['lots' => $line['lots']] : []),
...(! empty($line['conversion']) ? ['conversion' => $line['conversion']] : []),
'purchase_order_item_id' => $line['purchase_order_item_id'],
'received_milli' => self::milli($line['received_quantity']), 'accepted_milli' => self::milli($line['accepted_quantity']),
'quality_status' => $line['quality_status'], 'stock_item_id' => $line['stock_item_id'] ?? null,
@@ -188,9 +189,11 @@ class ReceiptWorkflow
if (! $physical && $source->purchase_type !== 'service') {
throw ValidationException::withMessages(['items' => 'Este tipo de artigo exige controlos adicionais ainda não implementados.']);
}
if ($physical && $accepted > 0 && (! $warehouse || ! $stockItem || Str::lower(trim($stockItem->unit)) !== Str::lower(trim($source->unit)))) {
throw ValidationException::withMessages(['items' => 'Para bens aceites, indique armazém e artigo de stock com a mesma unidade da ordem. Não há conversões automáticas.']);
if ($physical && $accepted > 0 && (! $warehouse || ! $stockItem)) {
throw ValidationException::withMessages(['items' => 'Para bens aceites, indique armazém e artigo de stock.']);
}
$conversion = $physical && $accepted > 0 && $stockItem !== null
? app(ReceiptQuantityConversion::class)->freeze($user, $source, $stockItem, $accepted, $input['conversion'] ?? null) : null;
if (! $physical && $stockItem !== null) {
throw ValidationException::withMessages(['items' => 'Serviços não geram existências nem recebem artigo de stock.']);
}
@@ -204,6 +207,7 @@ class ReceiptWorkflow
'stock_item' => $stockItem?->only(['id', 'code', 'name', 'unit']),
'warehouse' => $warehouse?->only(['id', 'code', 'name']),
'physical' => $physical,
...($conversion === null ? [] : ['quantity_conversion' => $conversion]),
'equipment_id' => $source->equipment_id, 'spare_part_id' => $source->spare_part_id,
],
];
+285 -159
View File
@@ -1,186 +1,312 @@
<?php
namespace App\Services;
use App\Models\{User,Supplier,Invoice};
use Illuminate\Support\Facades\{Crypt,DB,Schema,Validator};
use App\Models\Invoice;
use App\Models\Supplier;
use App\Models\User;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Tempo\SgcInvoiceClient\InvoiceClient;
/** Durable source intent and audit. No native invoice, payment, budget or stock writer. */
final class SgfInvoiceDispatches
{
public function actor(User $actor,bool $locked=false):User
public function actor(User $actor, bool $locked = false): User
{
abort_unless(config('sgf_invoice.workspace_enabled')===true,404);
abort_unless(auth()->id()===$actor->id&&$actor->tenant_id!==null,403);
if($locked)app(ConflictGuard::class)->lockCompany($actor);
$q=User::where('tenant_id',$actor->tenant_id)->whereKey($actor->id);if($locked)$q->lockForUpdate();$user=$q->firstOrFail();
abort_unless($user->hasFunctions(['finance'])&&!app(OrganizationAccess::class)->maintenanceOnly($user),403);
abort_unless(Schema::hasTable('sgf_invoice_dispatches')&&Schema::hasTable('sgf_invoice_dispatch_events'),503,'Estrutura de envio ainda não instalada.');
abort_unless(config('sgf_invoice.workspace_enabled') === true, 404);
abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
if ($locked) {
app(ConflictGuard::class)->lockCompany($actor);
}
$q = User::where('tenant_id', $actor->tenant_id)->whereKey($actor->id);
if ($locked) {
$q->lockForUpdate();
}$user = $q->firstOrFail();
abort_unless($user->hasFunctions(['finance']) && ! app(OrganizationAccess::class)->maintenanceOnly($user), 403);
abort_unless(Schema::hasTable('sgf_invoice_dispatches') && Schema::hasTable('sgf_invoice_dispatch_events'), 503, 'Estrutura de envio ainda não instalada.');
return $user;
}
public static function assertLocalRegistration(int $tenant,int $supplier,string $number):void
public static function assertLocalRegistration(int $tenant, int $supplier, string $number): void
{
// Keep the claim even if the workspace/transport is later disabled.
if(Schema::hasTable('sgf_invoice_dispatches')&&DB::table('sgf_invoice_dispatches')->where(['tenant_id'=>$tenant,'supplier_id'=>$supplier,'number'=>$number])->exists())
throw ValidationException::withMessages(['invoice'=>'Documento reservado ao envio SGF; consultar o recibo, sem segundo registo local.']);
}
public function mappings(User $actor):array
{
$this->actor($actor);$out=[];
foreach(config('sgf_invoice.connections',[])as$c=>$connection)if(($connection['source_scope']['tenant_id']??null)===$actor->tenant_id)
foreach($connection['mappings']??[]as$m=>$entry)if(($entry['approved']??false)===true)$out[]=['connection'=>$c,'id'=>$m,'label'=>$entry['label']??$m,'mapping'=>$entry['mapping']];
return $out;
}
private function mapping(User $actor,string $connection,string $id):array
{
$all=config('sgf_invoice.connections',[]);$c=$all[$connection]??null;$m=$c['mappings'][$id]??null;
abort_unless(is_array($c)&&($c['source_scope']['tenant_id']??null)===$actor->tenant_id&&is_array($m)&&($m['approved']??false)===true,403);
abort_if(array_diff(array_keys($m),['approved','label','source_supplier_id','mapping','approved_by','approved_at']),503,'Configuração de mapeamento inválida.');
abort_unless(($m['mapping']['source_scope']['tenant_id']??null)===$actor->tenant_id&&($m['mapping']['authority']??null)==='sgf_only',403);
abort_unless(is_int($m['source_supplier_id']??null)&&Supplier::where('tenant_id',$actor->tenant_id)->whereKey($m['source_supplier_id'])->exists(),403);
return $m;
}
private function checkSource(object $row,User $actor):array
{
$m=$this->mapping($actor,$row->connection_id,$row->mapping_id);
abort_unless(hash_equals($row->mapping_hash,self::hash($m)),409,'O mapeamento mudou; exige nova conferência.');
abort_if(Invoice::where('tenant_id',$actor->tenant_id)->where('supplier_id',$row->supplier_id)->where('number',$row->number)->exists(),409,'Documento já registado no SGC. Não reenviar.');
return $m;
}
private function validated(array $input):array
{
$d=Validator::make($input,['reference'=>'required|string|min:2|max:120','connection_id'=>'required|string|max:64','mapping_id'=>'required|string|max:64','reason'=>'required|string|min:10|max:2000',
'document'=>'required|array:number,issued_on,subtotal,tax,total,items','document.number'=>'required|string|max:100','document.issued_on'=>'required|date_format:Y-m-d',
'document.subtotal'=>'required|string|regex:/^\d{1,12}\.\d{2}$/D','document.tax'=>'required|string|regex:/^\d{1,12}\.\d{2}$/D','document.total'=>'required|string|regex:/^\d{1,12}\.\d{2}$/D',
'document.items'=>'required|array|min:1|max:50','document.items.*'=>'array:source_line_ref,quantity,unit,unit_price,tax_rate',
'document.items.*.source_line_ref'=>'required|string|max:120|distinct','document.items.*.quantity'=>'required|string|regex:/^\d{1,9}(\.\d{1,3})?$/D',
'document.items.*.unit'=>'required|string|max:20','document.items.*.unit_price'=>'required|string|regex:/^\d{1,12}\.\d{2}$/D','document.items.*.tax_rate'=>'required|string|regex:/^\d{1,3}(\.\d{1,2})?$/D'])->validate();
abort_if(array_diff(array_keys($input),array_keys($d)),422);
return $d;
}
public function create(User $actor,array $input):int
{
$d=$this->validated($input);
return DB::transaction(function()use($actor,$d){
$user=$this->actor($actor,true);$m=$this->mapping($user,$d['connection_id'],$d['mapping_id']);$doc=$d['document'];$doc['number']=Str::upper(Str::squish($doc['number']));
$ids=[];foreach($doc['items']as$item){$id=$m['mapping']['lines'][$item['source_line_ref']]??null;abort_unless(is_int($id)&&$id>0&&!in_array($id,$ids,true),422,'Linha sem mapeamento explícito.');$ids[]=$id;}
abort_if(Invoice::where('tenant_id',$user->tenant_id)->where('supplier_id',$m['source_supplier_id'])->where('number',$doc['number'])->exists(),409,'Documento já registado no SGC.');
abort_if(DB::table('sgf_invoice_dispatches')->where('tenant_id',$user->tenant_id)->where(fn($q)=>$q->where('reference',$d['reference'])->orWhere(fn($q)=>$q->where('supplier_id',$m['source_supplier_id'])->where('number',$doc['number'])))->exists(),409,'Já existe uma intenção para esta fonte.');
$id=DB::table('sgf_invoice_dispatches')->insertGetId(['tenant_id'=>$user->tenant_id,'supplier_id'=>$m['source_supplier_id'],'reference'=>$d['reference'],'number'=>$doc['number'],
'connection_id'=>$d['connection_id'],'mapping_id'=>$d['mapping_id'],'mapping_snapshot'=>json_encode($m,JSON_THROW_ON_ERROR),'mapping_hash'=>self::hash($m),
'document'=>json_encode($doc,JSON_THROW_ON_ERROR),'reason'=>$d['reason'],'created_by'=>$user->id,'created_at'=>now('UTC'),'updated_at'=>now('UTC')]);
$row=$this->row($user,$id);$this->event($row,$user,'draft.created',$d['reason'],null);return $id;
});
}
public function revise(User $actor,int $id,int $version,array $input):object
{
$d=$this->validated($input);
return DB::transaction(function()use($actor,$id,$version,$d){
$user=$this->actor($actor,true);$row=$this->row($user,$id,true);
abort_unless((int)$row->version===$version&&!$row->ever_sending&&$row->phase!=='received_pending'
&&(!$row->lease_until||now('UTC')->gte($row->lease_until)),409,'Fonte já enviada/em curso ou versão alterada.');
abort_unless($d['reference']===$row->reference,422,'Referência de origem imutável.');
$m=$this->mapping($user,$d['connection_id'],$d['mapping_id']);$doc=$d['document'];$doc['number']=Str::upper(Str::squish($doc['number']));
$used=[];foreach($doc['items']as$item){$line=$m['mapping']['lines'][$item['source_line_ref']]??null;abort_unless(is_int($line)&&!in_array($line,$used,true),422);$used[]=$line;}
abort_if(Invoice::where('tenant_id',$user->tenant_id)->where('supplier_id',$m['source_supplier_id'])->where('number',$doc['number'])->exists()
||DB::table('sgf_invoice_dispatches')->where('tenant_id',$user->tenant_id)->where('supplier_id',$m['source_supplier_id'])->where('number',$doc['number'])->where('id','<>',$id)->exists(),409,'Documento já reservado/registado.');
return $this->update($row,$user,['supplier_id'=>$m['source_supplier_id'],'number'=>$doc['number'],'connection_id'=>$d['connection_id'],'mapping_id'=>$d['mapping_id'],
'mapping_snapshot'=>json_encode($m,JSON_THROW_ON_ERROR),'mapping_hash'=>self::hash($m),'document'=>json_encode($doc,JSON_THROW_ON_ERROR),'reason'=>$d['reason'],
'source_version'=>$row->source_version+1,'phase'=>'draft','operation_key'=>null,'state_ciphertext'=>null,'approval_hash'=>null,'lease_id'=>null,'lease_until'=>null], 'draft.revised',$d['reason']);
});
}
public function row(User $actor,int $id,bool $locked=false):object
{
$q=DB::table('sgf_invoice_dispatches')->where('tenant_id',$actor->tenant_id)->where('id',$id);if($locked)$q->lockForUpdate();
$row=$q->first();abort_unless($row,404);return $row;
}
private function summary(object $row):array
{
$state=$this->state($row);
return ['id'=>$row->id,'reference'=>$row->reference,'number'=>$row->number,'version'=>(int)$row->version,'source_version'=>(int)$row->source_version,
'phase'=>$row->phase,'mapping_hash'=>$row->mapping_hash,'document_hash'=>self::hash(json_decode($row->document,true)),
'document'=>json_decode($row->document,true),'mapping_snapshot'=>json_decode($row->mapping_snapshot,true),'reason'=>$row->reason,
'operation_key'=>$row->operation_key,'approval_hash'=>$row->approval_hash,'ever_sending'=>(bool)$row->ever_sending,
'intent_hash'=>$state['intent']['intent_hash']??null,'impact_hash'=>isset($state['impact'])?self::hash($state['impact']):null,
'preview_actor_id'=>$row->preview_actor_id,'source_context_hash'=>$row->source_context_hash,
'receipt'=>$row->receipt?json_decode($row->receipt,true):null];
}
private function event(object $row,User $actor,string $action,string $reason,?array $before):void
{
DB::table('sgf_invoice_dispatch_events')->insert(['dispatch_id'=>$row->id,'tenant_id'=>$row->tenant_id,'version'=>$row->version,'actor_id'=>$actor->id,
'action'=>$action,'reason'=>$reason,'before_state'=>$before?json_encode($before,JSON_THROW_ON_ERROR):null,'after_state'=>json_encode($this->summary($row),JSON_THROW_ON_ERROR),'created_at'=>now('UTC')]);
}
private function update(object $row,User $actor,array $changes,string $action,string $reason):object
{
$before=$this->summary($row);$changes+=['version'=>$row->version+1,'updated_at'=>now('UTC')];
DB::table('sgf_invoice_dispatches')->where('id',$row->id)->where('tenant_id',$row->tenant_id)->update($changes);
$next=$this->row($actor,$row->id);$this->event($next,$actor,$action,$reason,$before);return $next;
}
private function state(object $row):?array{return $row->state_ciphertext?json_decode(Crypt::decryptString($row->state_ciphertext),true,128,JSON_THROW_ON_ERROR):null;}
private function contextHash(User $actor):string
{
return self::hash([$actor->tenant_id,request()->hasSession()?request()->session()->get('work_context'):null]);
if (Schema::hasTable('sgf_invoice_dispatches') && DB::table('sgf_invoice_dispatches')->where(['tenant_id' => $tenant, 'supplier_id' => $supplier, 'number' => $number])->exists()) {
throw ValidationException::withMessages(['invoice' => 'Documento reservado ao envio SGF; consultar o recibo, sem segundo registo local.']);
}
}
public function dispatch(User $actor,int $id,int $version,string $action,string $reason,?string $approval):object
/** @return list<array<string,mixed>> */
public function mappings(User $actor): array
{
abort_unless(in_array($action,['preview','confirm','recover'],true),422);
abort_unless(config('sgf_invoice.enabled')===true,423,'Transporte desligado; o rascunho permanece conservado.');
Validator::make(['reason'=>$reason],['reason'=>'required|string|min:10|max:2000'])->validate();
// Commit the intent/decision/lease BEFORE network. Neither DB locks nor an HTTP retry may silently duplicate a decision.
[$row,$client,$state,$m,$lease]=DB::transaction(function()use($actor,$id,$version,$action,$reason,$approval){
$user=$this->actor($actor,true);$row=$this->row($user,$id,true);abort_unless((int)$row->version===$version,409,'Versão desactualizada.');
abort_unless(!$row->lease_until||now('UTC')->gte($row->lease_until),409,'Operação em curso; aguarde e consulte o estado.');
abort_if($row->phase==='received_pending',409,'Recibo já conservado.');$m=$this->checkSource($row,$user);
$client=app(SgfInvoiceGateway::class)->clientFor($user,$row->connection_id);$state=$this->state($row);
if($state){
$expected=$client->intent($m['mapping'],['reference'=>$row->reference,'version'=>(string)$row->source_version,'state'=>'unregistered_draft','document'=>json_decode($row->document,true)],$row->operation_key,$row->reason);
if(($state['intent']['intent_hash']??null)!==$expected['intent_hash']){
abort_unless($action==='preview',409,'Ligação ou contexto mudaram; exige nova conferência.');
$state=['intent'=>$expected,'phase'=>'draft'];
$this->actor($actor);
$out = [];
foreach (config('sgf_invoice.connections', []) as $c => $connection) {
if (($connection['source_scope']['tenant_id'] ?? null) === $actor->tenant_id) {
foreach ($connection['mappings'] ?? [] as $m => $entry) {
if (($entry['approved'] ?? false) === true) {
$out[] = ['connection' => $c, 'id' => $m, 'label' => $entry['label'] ?? $m, 'mapping' => $entry['mapping']];
}
}
}
$lease=(string)Str::uuid();$changes=['lease_id'=>$lease,'lease_until'=>now('UTC')->addSeconds(120),'phase'=>$action==='preview'?'previewing':'sending'];
if($action==='preview'){
$changes+=['preview_actor_id'=>$user->id,'source_context_hash'=>$this->contextHash($user)];
if(!$state){$key=(string)Str::uuid();$intent=$client->intent($m['mapping'],['reference'=>$row->reference,'version'=>(string)$row->source_version,'state'=>'unregistered_draft','document'=>json_decode($row->document,true)],$key,$row->reason);$state=['intent'=>$intent,'phase'=>'draft'];$changes['operation_key']=$key;}
}elseif($action==='confirm'){
abort_unless($row->phase==='previewed'&&$state&&is_string($approval)&&hash_equals($state['approval_hash']??'',$approval),409,'Aprovar individualmente a prévia actual.');
abort_unless((int)$row->preview_actor_id===$user->id&&$row->source_context_hash===$this->contextHash($user),409,'Operador ou contexto mudaram; conferir novamente.');
$changes+=['ever_sending'=>true,'approval_hash'=>$approval];
}else{
abort_unless((bool)$row->ever_sending&&in_array($row->phase,['sending','uncertain','blocked','review_required','not_sent'],true)&&$state&&$row->approval_hash,409,'Sem confirmação anterior para recuperar.');
$state['phase']='uncertain';$approval=$row->approval_hash;
}
return $out;
}
/** @return array<string,mixed> */
private function mapping(User $actor, string $connection, string $id): array
{
$all = config('sgf_invoice.connections', []);
$c = $all[$connection] ?? null;
$m = $c['mappings'][$id] ?? null;
abort_unless(is_array($c) && ($c['source_scope']['tenant_id'] ?? null) === $actor->tenant_id && is_array($m) && ($m['approved'] ?? false) === true, 403);
abort_if(array_diff(array_keys($m), ['approved', 'label', 'source_supplier_id', 'mapping', 'approved_by', 'approved_at']) !== [], 503, 'Configuração de mapeamento inválida.');
abort_unless(($m['mapping']['source_scope']['tenant_id'] ?? null) === $actor->tenant_id && ($m['mapping']['authority'] ?? null) === 'sgf_only', 403);
abort_unless(is_int($m['source_supplier_id'] ?? null) && Supplier::where('tenant_id', $actor->tenant_id)->whereKey($m['source_supplier_id'])->exists(), 403);
return $m;
}
/** @return array<string,mixed> */
private function checkSource(\stdClass $row, User $actor): array
{
$m = $this->mapping($actor, $row->connection_id, $row->mapping_id);
abort_unless(hash_equals($row->mapping_hash, self::hash($m)), 409, 'O mapeamento mudou; exige nova conferência.');
abort_if(Invoice::where('tenant_id', $actor->tenant_id)->where('supplier_id', $row->supplier_id)->where('number', $row->number)->exists(), 409, 'Documento já registado no SGC. Não reenviar.');
return $m;
}
/** @param array<string,mixed> $input
* @return array<string,mixed>
*/
private function validated(array $input): array
{
$d = Validator::make($input, ['reference' => 'required|string|min:2|max:120', 'connection_id' => 'required|string|max:64', 'mapping_id' => 'required|string|max:64', 'reason' => 'required|string|min:10|max:2000',
'document' => 'required|array:number,issued_on,subtotal,tax,total,items', 'document.number' => 'required|string|max:100', 'document.issued_on' => 'required|date_format:Y-m-d',
'document.subtotal' => 'required|string|regex:/^\d{1,12}\.\d{2}$/D', 'document.tax' => 'required|string|regex:/^\d{1,12}\.\d{2}$/D', 'document.total' => 'required|string|regex:/^\d{1,12}\.\d{2}$/D',
'document.items' => 'required|array|min:1|max:50', 'document.items.*' => 'array:source_line_ref,quantity,unit,unit_price,tax_rate',
'document.items.*.source_line_ref' => 'required|string|max:120|distinct', 'document.items.*.quantity' => 'required|string|regex:/^\d{1,9}(\.\d{1,3})?$/D',
'document.items.*.unit' => 'required|string|max:20', 'document.items.*.unit_price' => 'required|string|regex:/^\d{1,12}\.\d{2}$/D', 'document.items.*.tax_rate' => 'required|string|regex:/^\d{1,3}(\.\d{1,2})?$/D'])->validate();
abort_if(array_diff(array_keys($input), array_keys($d)) !== [], 422);
return $d;
}
/** @param array<string,mixed> $input */
public function create(User $actor, array $input): int
{
$d = $this->validated($input);
return DB::transaction(function () use ($actor, $d) {
$user = $this->actor($actor, true);
$m = $this->mapping($user, $d['connection_id'], $d['mapping_id']);
$doc = $d['document'];
$doc['number'] = Str::upper(Str::squish($doc['number']));
$ids = [];
foreach ($doc['items'] as $item) {
$id = $m['mapping']['lines'][$item['source_line_ref']] ?? null;
abort_unless(is_int($id) && $id > 0 && ! in_array($id, $ids, true), 422, 'Linha sem mapeamento explícito.');
$ids[] = $id;
}
$changes['state_ciphertext']=Crypt::encryptString(json_encode($state,JSON_THROW_ON_ERROR));
$row=$this->update($row,$user,$changes,$action==='confirm'?'decision.confirmed':($action==='recover'?'recovery.started':'preview.started'),$reason);
return [$row,$client,$state,$m,$lease];
});
try{
if($action==='preview')$result=array_replace($state,$client->preview($state['intent'],(string)$row->source_version,\Tempo\SgcInvoiceClient\InvoiceClient::mappingHash($m['mapping'])));
else $result=$client->confirm($state,$action==='confirm'?$approval:$row->approval_hash,(string)$row->source_version,\Tempo\SgcInvoiceClient\InvoiceClient::mappingHash($m['mapping']));
}catch(\Throwable){$result=array_replace($state,['phase'=>$action==='preview'?'not_sent':'uncertain','error'=>'DELIVERY_NOT_CONFIRMED']);}
return DB::transaction(function()use($actor,$id,$lease,$result,$reason){
app(ConflictGuard::class)->lockCompany($actor);$current=$this->row($actor,$id,true);
abort_unless($current->lease_id===$lease,409,'Operação recuperada por outra sessão; actualizar.');
$allowed=['previewed','received_pending','uncertain','blocked','review_required','not_sent'];
$phase=in_array($result['phase']??null,$allowed,true)?$result['phase']:'uncertain';
return $this->update($current,$actor,['phase'=>$phase,'lease_id'=>null,'lease_until'=>null,
'state_ciphertext'=>Crypt::encryptString(json_encode($result,JSON_THROW_ON_ERROR)),
'receipt'=>isset($result['receipt'])?json_encode($result['receipt'],JSON_THROW_ON_ERROR):null], 'transport.observed',$reason);
abort_if(Invoice::where('tenant_id', $user->tenant_id)->where('supplier_id', $m['source_supplier_id'])->where('number', $doc['number'])->exists(), 409, 'Documento já registado no SGC.');
abort_if(DB::table('sgf_invoice_dispatches')->where('tenant_id', $user->tenant_id)->where(fn ($q) => $q->where('reference', $d['reference'])->orWhere(fn ($q) => $q->where('supplier_id', $m['source_supplier_id'])->where('number', $doc['number'])))->exists(), 409, 'Já existe uma intenção para esta fonte.');
$id = DB::table('sgf_invoice_dispatches')->insertGetId(['tenant_id' => $user->tenant_id, 'supplier_id' => $m['source_supplier_id'], 'reference' => $d['reference'], 'number' => $doc['number'],
'connection_id' => $d['connection_id'], 'mapping_id' => $d['mapping_id'], 'mapping_snapshot' => json_encode($m, JSON_THROW_ON_ERROR), 'mapping_hash' => self::hash($m),
'document' => json_encode($doc, JSON_THROW_ON_ERROR), 'reason' => $d['reason'], 'created_by' => $user->id, 'created_at' => now('UTC'), 'updated_at' => now('UTC')]);
$row = $this->row($user, $id);
$this->event($row, $user, 'draft.created', $d['reason'], null);
return $id;
});
}
public function presentation(User $actor,object $row):array
/** @param array<string,mixed> $input */
public function revise(User $actor, int $id, int $version, array $input): \stdClass
{
$this->actor($actor);$state=$this->state($row);$out=$this->summary($row);
return array_replace($out,['connection_id'=>$row->connection_id,'mapping_id'=>$row->mapping_id,'document'=>json_decode($row->document,true),'reason'=>$row->reason,
'impact'=>$state['impact']??null,'approval_hash'=>$row->phase==='previewed'?($state['approval_hash']??null):null,
'lease_until'=>$row->lease_until]);
$d = $this->validated($input);
return DB::transaction(function () use ($actor, $id, $version, $d) {
$user = $this->actor($actor, true);
$row = $this->row($user, $id, true);
abort_unless((int) $row->version === $version && ! $row->ever_sending && $row->phase !== 'received_pending'
&& (! $row->lease_until || now('UTC')->gte($row->lease_until)), 409, 'Fonte já enviada/em curso ou versão alterada.');
abort_unless($d['reference'] === $row->reference, 422, 'Referência de origem imutável.');
$m = $this->mapping($user, $d['connection_id'], $d['mapping_id']);
$doc = $d['document'];
$doc['number'] = Str::upper(Str::squish($doc['number']));
$used = [];
foreach ($doc['items'] as $item) {
$line = $m['mapping']['lines'][$item['source_line_ref']] ?? null;
abort_unless(is_int($line) && ! in_array($line, $used, true), 422);
$used[] = $line;
}
abort_if(Invoice::where('tenant_id', $user->tenant_id)->where('supplier_id', $m['source_supplier_id'])->where('number', $doc['number'])->exists()
|| DB::table('sgf_invoice_dispatches')->where('tenant_id', $user->tenant_id)->where('supplier_id', $m['source_supplier_id'])->where('number', $doc['number'])->where('id', '<>', $id)->exists(), 409, 'Documento já reservado/registado.');
return $this->update($row, $user, ['supplier_id' => $m['source_supplier_id'], 'number' => $doc['number'], 'connection_id' => $d['connection_id'], 'mapping_id' => $d['mapping_id'],
'mapping_snapshot' => json_encode($m, JSON_THROW_ON_ERROR), 'mapping_hash' => self::hash($m), 'document' => json_encode($doc, JSON_THROW_ON_ERROR), 'reason' => $d['reason'],
'source_version' => $row->source_version + 1, 'phase' => 'draft', 'operation_key' => null, 'state_ciphertext' => null, 'approval_hash' => null, 'lease_id' => null, 'lease_until' => null], 'draft.revised', $d['reason']);
});
}
public static function hash(mixed $v):string
public function row(User $actor, int $id, bool $locked = false): \stdClass
{
$normalise=function($x)use(&$normalise){if(!is_array($x))return $x;if(!array_is_list($x))ksort($x,SORT_STRING);foreach($x as&$item)$item=$normalise($item);return $x;};
return hash('sha256',json_encode($normalise($v),JSON_THROW_ON_ERROR|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
$q = DB::table('sgf_invoice_dispatches')->where('tenant_id', $actor->tenant_id)->where('id', $id);
if ($locked) {
$q->lockForUpdate();
}
$row = $q->first();
abort_unless($row !== null, 404);
return $row;
}
/** @return array<string,mixed> */
private function summary(\stdClass $row): array
{
$state = $this->state($row);
return ['id' => $row->id, 'reference' => $row->reference, 'number' => $row->number, 'version' => (int) $row->version, 'source_version' => (int) $row->source_version,
'phase' => $row->phase, 'mapping_hash' => $row->mapping_hash, 'document_hash' => self::hash(json_decode($row->document, true)),
'document' => json_decode($row->document, true), 'mapping_snapshot' => json_decode($row->mapping_snapshot, true), 'reason' => $row->reason,
'operation_key' => $row->operation_key, 'approval_hash' => $row->approval_hash, 'ever_sending' => (bool) $row->ever_sending,
'intent_hash' => $state['intent']['intent_hash'] ?? null, 'impact_hash' => isset($state['impact']) ? self::hash($state['impact']) : null,
'preview_actor_id' => $row->preview_actor_id, 'source_context_hash' => $row->source_context_hash,
'receipt' => $row->receipt ? json_decode($row->receipt, true) : null];
}
/** @param array<string,mixed>|null $before */
private function event(\stdClass $row, User $actor, string $action, string $reason, ?array $before): void
{
DB::table('sgf_invoice_dispatch_events')->insert(['dispatch_id' => $row->id, 'tenant_id' => $row->tenant_id, 'version' => $row->version, 'actor_id' => $actor->id,
'action' => $action, 'reason' => $reason, 'before_state' => $before ? json_encode($before, JSON_THROW_ON_ERROR) : null, 'after_state' => json_encode($this->summary($row), JSON_THROW_ON_ERROR), 'created_at' => now('UTC')]);
}
/** @param array<string,mixed> $changes */
private function update(\stdClass $row, User $actor, array $changes, string $action, string $reason): \stdClass
{
$before = $this->summary($row);
$changes += ['version' => $row->version + 1, 'updated_at' => now('UTC')];
DB::table('sgf_invoice_dispatches')->where('id', $row->id)->where('tenant_id', $row->tenant_id)->update($changes);
$next = $this->row($actor, $row->id);
$this->event($next, $actor, $action, $reason, $before);
return $next;
}
/** @return array<string,mixed>|null */
private function state(\stdClass $row): ?array
{
return $row->state_ciphertext ? json_decode(Crypt::decryptString($row->state_ciphertext), true, 128, JSON_THROW_ON_ERROR) : null;
}
private function contextHash(User $actor): string
{
return self::hash([$actor->tenant_id, request()->hasSession() ? request()->session()->get('work_context') : null]);
}
public function dispatch(User $actor, int $id, int $version, string $action, string $reason, ?string $approval): \stdClass
{
abort_unless(in_array($action, ['preview', 'confirm', 'recover'], true), 422);
abort_unless(config('sgf_invoice.enabled') === true, 423, 'Transporte desligado; o rascunho permanece conservado.');
Validator::make(['reason' => $reason], ['reason' => 'required|string|min:10|max:2000'])->validate();
// Commit the intent/decision/lease BEFORE network. Neither DB locks nor an HTTP retry may silently duplicate a decision.
[$row,$client,$state,$m,$lease] = DB::transaction(function () use ($actor, $id, $version, $action, $reason, $approval) {
$user = $this->actor($actor, true);
$row = $this->row($user, $id, true);
abort_unless((int) $row->version === $version, 409, 'Versão desactualizada.');
abort_unless(! $row->lease_until || now('UTC')->gte($row->lease_until), 409, 'Operação em curso; aguarde e consulte o estado.');
abort_if($row->phase === 'received_pending', 409, 'Recibo já conservado.');
$m = $this->checkSource($row, $user);
$client = app(SgfInvoiceGateway::class)->clientFor($user, $row->connection_id);
$state = $this->state($row);
if ($state) {
$expected = $client->intent($m['mapping'], ['reference' => $row->reference, 'version' => (string) $row->source_version, 'state' => 'unregistered_draft', 'document' => json_decode($row->document, true)], $row->operation_key, $row->reason);
if (($state['intent']['intent_hash'] ?? null) !== $expected['intent_hash']) {
abort_unless($action === 'preview', 409, 'Ligação ou contexto mudaram; exige nova conferência.');
$state = ['intent' => $expected, 'phase' => 'draft'];
}
}
$lease = (string) Str::uuid();
$changes = ['lease_id' => $lease, 'lease_until' => now('UTC')->addSeconds(120), 'phase' => $action === 'preview' ? 'previewing' : 'sending'];
if ($action === 'preview') {
$changes += ['preview_actor_id' => $user->id, 'source_context_hash' => $this->contextHash($user)];
if (! $state) {
$key = (string) Str::uuid();
$intent = $client->intent($m['mapping'], ['reference' => $row->reference, 'version' => (string) $row->source_version, 'state' => 'unregistered_draft', 'document' => json_decode($row->document, true)], $key, $row->reason);
$state = ['intent' => $intent, 'phase' => 'draft'];
$changes['operation_key'] = $key;
}
} elseif ($action === 'confirm') {
abort_unless($row->phase === 'previewed' && $state && is_string($approval) && hash_equals($state['approval_hash'] ?? '', $approval), 409, 'Aprovar individualmente a prévia actual.');
abort_unless((int) $row->preview_actor_id === $user->id && $row->source_context_hash === $this->contextHash($user), 409, 'Operador ou contexto mudaram; conferir novamente.');
$changes += ['ever_sending' => true, 'approval_hash' => $approval];
} else {
abort_unless((bool) $row->ever_sending && in_array($row->phase, ['sending', 'uncertain', 'blocked', 'review_required', 'not_sent'], true) && $state && $row->approval_hash, 409, 'Sem confirmação anterior para recuperar.');
$state['phase'] = 'uncertain';
$approval = $row->approval_hash;
}
$changes['state_ciphertext'] = Crypt::encryptString(json_encode($state, JSON_THROW_ON_ERROR));
$row = $this->update($row, $user, $changes, $action === 'confirm' ? 'decision.confirmed' : ($action === 'recover' ? 'recovery.started' : 'preview.started'), $reason);
return [$row, $client, $state, $m, $lease];
});
try {
if ($action === 'preview') {
$result = array_replace($state, $client->preview($state['intent'], (string) $row->source_version, InvoiceClient::mappingHash($m['mapping'])));
} else {
$result = $client->confirm($state, $action === 'confirm' ? $approval : $row->approval_hash, (string) $row->source_version, InvoiceClient::mappingHash($m['mapping']));
}
} catch (\Throwable) {
$result = array_replace($state, ['phase' => $action === 'preview' ? 'not_sent' : 'uncertain', 'error' => 'DELIVERY_NOT_CONFIRMED']);
}
return DB::transaction(function () use ($actor, $id, $lease, $result, $reason) {
app(ConflictGuard::class)->lockCompany($actor);
$current = $this->row($actor, $id, true);
abort_unless($current->lease_id === $lease, 409, 'Operação recuperada por outra sessão; actualizar.');
$allowed = ['previewed', 'received_pending', 'uncertain', 'blocked', 'review_required', 'not_sent'];
$phase = in_array($result['phase'] ?? null, $allowed, true) ? $result['phase'] : 'uncertain';
return $this->update($current, $actor, ['phase' => $phase, 'lease_id' => null, 'lease_until' => null,
'state_ciphertext' => Crypt::encryptString(json_encode($result, JSON_THROW_ON_ERROR)),
'receipt' => isset($result['receipt']) ? json_encode($result['receipt'], JSON_THROW_ON_ERROR) : null], 'transport.observed', $reason);
});
}
/** @return array<string,mixed> */
public function presentation(User $actor, \stdClass $row): array
{
$this->actor($actor);
$state = $this->state($row);
$out = $this->summary($row);
return array_replace($out,['connection_id' => $row->connection_id, 'mapping_id' => $row->mapping_id, 'document' => json_decode($row->document,true), 'reason' => $row->reason,
'impact' => $state['impact'] ?? null, 'approval_hash' => $row->phase === 'previewed' ? ($state['approval_hash'] ?? null) : null,
'lease_until' => $row->lease_until]);
}
public static function hash(mixed $v): string
{
$normalise = function ($x) use (&$normalise) {
if (! is_array($x)) {
return $x;
}if (! array_is_list($x)) {
ksort($x,SORT_STRING);
}foreach ($x as &$item) {
$item = $normalise($item);
}
return $x;
};
return hash('sha256',json_encode($normalise($v),JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}
}
+5 -2
View File
@@ -18,10 +18,13 @@ final class SgfInvoiceGateway
abort_unless(($c['source_scope']['tenant_id']??null)===$current->tenant_id&&$current->hasFunctions(['finance'])
&&!app(OrganizationAccess::class)->maintenanceOnly($current),403);
$path=config('sgf_invoice.client_package');$pin=config('sgf_invoice.client_package_sha256');
$actual=is_string($path)&&is_file($path)?hash_file('sha256',$path):false;
if(!is_string($path)||is_link($path)||!is_file($path)||!is_string($pin)||!preg_match('/^[a-f0-9]{64}$/D',$pin)
||!hash_equals($pin,hash_file('sha256',$path)))throw new LogicException('Verified client package required.');
||!is_string($actual)||!hash_equals($pin,$actual))throw new LogicException('Verified client package required.');
if(class_exists(\Tempo\SgcInvoiceClient\InvoiceClient::class,false)){
if(!hash_equals($pin,hash_file('sha256',(new \ReflectionClass(\Tempo\SgcInvoiceClient\InvoiceClient::class))->getFileName())))throw new LogicException('Client version changed; restart separately.');
$loaded=(new \ReflectionClass(\Tempo\SgcInvoiceClient\InvoiceClient::class))->getFileName();
$loadedHash=is_string($loaded)&&is_file($loaded)?hash_file('sha256',$loaded):false;
if(!is_string($loadedHash)||!hash_equals($pin,$loadedHash))throw new LogicException('Client version changed; restart separately.');
}else require_once $path;
$configurationHash=hash('sha256',json_encode($c,JSON_THROW_ON_ERROR));
return new \Tempo\SgcInvoiceClient\InvoiceClient($c['client_id'],$c['token'],$c['context_version'],$c['source_scope'],$c['target_scope'],
+7 -3
View File
@@ -10,9 +10,13 @@ final class StockIssueMovement
public function for(User $actor): \Tempo\Inventory\IssueMovementWriter
{
$root=base_path('packages/inventory-issue/releases/0.1.0');
if(!is_file($root.'/manifest.json')||!hash_equals('3c24d9e9fb99bfbb274077495c3a42ddb7eccab06b5c6a956cd739b2bc9b56f0',hash_file('sha256',$root.'/manifest.json')))throw new \LogicException('Pacote de saída incompatível.');
$m=json_decode(file_get_contents($root.'/manifest.json'),true,512,JSON_THROW_ON_ERROR);
foreach(['bootstrap.php','src/IssueMovementWriter.php'] as $f)if(!is_file($root.'/'.$f)||!hash_equals($m['files'][$f]??'',hash_file('sha256',$root.'/'.$f)))throw new \LogicException('Pacote de saída alterado.');
$bytes=is_file($root.'/manifest.json')?file_get_contents($root.'/manifest.json'):false;
if(!is_string($bytes)||!hash_equals('3c24d9e9fb99bfbb274077495c3a42ddb7eccab06b5c6a956cd739b2bc9b56f0',hash('sha256',$bytes)))throw new \LogicException('Pacote de saída incompatível.');
$m=json_decode($bytes,true,512,JSON_THROW_ON_ERROR);
foreach(['bootstrap.php','src/IssueMovementWriter.php'] as $f) {
$actual=is_file($root.'/'.$f)?hash_file('sha256',$root.'/'.$f):false;
if(!is_string($actual)||!hash_equals($m['files'][$f]??'',$actual))throw new \LogicException('Pacote de saída alterado.');
}
require_once $root.'/bootstrap.php';
$schema=match(DB::connection()->getDriverName()){'pgsql'=>'public','sqlite'=>'main','mysql','mariadb'=>DB::connection()->getDatabaseName(),default=>throw new \LogicException('Driver não suportado.')};
return new \Tempo\Inventory\IssueMovementWriter(DB::connection(),$schema,(int)$actor->tenant_id,(int)$actor->id,function()use($actor){app(CurrentActor::class)->lock($actor,[PurchasingRole::Warehouse]);});
+1
View File
@@ -280,6 +280,7 @@ class StockWorkflow
{
if($type==='issue'&&$operation->kind==='issue'){
$writer=app(StockIssueMovement::class)->for($actor);$result=$writer->write($operation->id,$writer->preview($operation->id));
if(!is_int($result['movement_id']??null)||$result['movement_id']<1)throw new \LogicException('Referência de movimento devolvida pelo escritor incompatível.');
return StockMovement::query()->findOrFail($result['movement_id']);
}
return StockMovement::query()->create(['tenant_id' => $actor->tenant_id, 'stock_operation_id' => $operation->id, 'stock_item_id' => $operation->stock_item_id, 'warehouse_id' => $warehouse, 'equipment_id' => $operation->equipment_id, 'spare_part_id' => $operation->spare_part_id, 'moved_by' => $actor->id, 'movement_type' => $type, 'quantity_milli' => $quantity, 'snapshot' => [...$operation->snapshot, 'warehouse' => Warehouse::query()->findOrFail($warehouse)->only(['id', 'code', 'name']), 'reference' => $operation->reference, 'reason' => $operation->reason], 'moved_at' => now()]);
+73 -6
View File
@@ -7,14 +7,54 @@ use App\Models\Supplier;
use App\Models\SupplierBankDetail;
use App\Models\SupplierBankReview;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
class SupplierBankWorkflow
{
public function multipleReady(): bool
{
return Schema::hasColumn('supplier_bank_details', 'account_key');
}
/** @return Builder<SupplierBankDetail> */
public function account(Supplier $supplier, ?string $key = null): Builder
{
$query = SupplierBankDetail::query()->where('tenant_id', $supplier->tenant_id)->where('supplier_id', $supplier->id);
if ($this->multipleReady()) {
$query->where('account_key', $key);
} else {
abort_unless($key === null, 503, 'A estrutura de contas independentes ainda não está instalada.');
}
return $query;
}
public function latest(Supplier $supplier, ?string $key = null): ?SupplierBankDetail
{
return $this->account($supplier, $key)->latest('revision')->first();
}
/** @return Collection<int,SupplierBankDetail> */
public function currentAccounts(Supplier $supplier): Collection
{
$query = SupplierBankDetail::query()->where('tenant_id', $supplier->tenant_id)->where('supplier_id', $supplier->id);
if (! $this->multipleReady()) {
return $query->latest('revision')->limit(1)->get();
}
return $query->whereIn('revision', fn ($q) => $q->from('supplier_bank_details')->where('tenant_id', $supplier->tenant_id)
->where('supplier_id', $supplier->id)->groupBy('account_key')->selectRaw('MAX(revision)'))
->orderBy('revision')->get();
}
private function actor(User $user, Supplier $supplier): void
{
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null && $supplier->tenant_id === $user->tenant_id, 403);
abort_if(app(OrganizationAccess::class)->maintenanceOnly($user), 403);
if (app(ConflictGuard::class)->hasConflict($user->id, $supplier->id, null)) {
throw ValidationException::withMessages(['bank' => 'Conflito de interesses com este fornecedor.']);
}
@@ -31,11 +71,24 @@ class SupplierBankWorkflow
$user = app(CurrentActor::class)->lock($user, [PurchasingRole::Procurement]);
$supplier = Supplier::query()->lockForUpdate()->findOrFail($supplier->id);
$this->actor($user, $supplier);
$latest = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->first();
$key = validator($data, ['account_key' => 'nullable|uuid'])->validate()['account_key'] ?? null;
$key = $key === null ? null : strtolower($key);
$latest = $this->latest($supplier, $key);
$fields = ['bank_name', 'country', 'currency', 'beneficiary', 'account_identifier', 'evidence_reference', 'reason'];
if ($key !== null && (int) $data['previous_id'] === 0 && $latest !== null) {
$original = $this->account($supplier, $key)->oldest('revision')->firstOrFail();
if ($original->created_by === $user->id
&& array_map(fn ($field) => $original->$field, $fields) === array_map(fn ($field) => $data[$field] ?? null, $fields)) {
return $original;
}
throw ValidationException::withMessages(['account_key' => 'A identidade desta conta já foi utilizada com outros dados.']);
}
if ((int) $data['previous_id'] !== ($latest->id ?? 0)) {
throw ValidationException::withMessages(['previous_id' => 'Dados bancários alterados. Reabra a ficha antes de propor outra versão.']);
}
$detail = SupplierBankDetail::query()->create(['tenant_id' => $user->tenant_id, 'supplier_id' => $supplier->id, 'created_by' => $user->id, 'revision' => ($latest->revision ?? 0) + 1, ...array_intersect_key($data, array_flip(['bank_name', 'country', 'currency', 'beneficiary', 'account_identifier', 'evidence_reference', 'reason'])), 'created_at' => now()]);
$revision = (int) SupplierBankDetail::query()->where('supplier_id', $supplier->id)->max('revision') + 1;
$detail = SupplierBankDetail::query()->create(['tenant_id' => $user->tenant_id, 'supplier_id' => $supplier->id, 'created_by' => $user->id, 'revision' => $revision,
...($key === null ? [] : ['account_key' => $key]), ...array_intersect_key($data, array_flip($fields)), 'created_at' => now()]);
app(RequisitionWorkflow::class)->audit($user, 'supplier.bank_proposed', null, null, ['supplier_id' => $supplier->id, 'bank_detail_id' => $detail->id, 'revision' => $detail->revision]);
return $detail;
@@ -53,8 +106,8 @@ class SupplierBankWorkflow
$user = app(CurrentActor::class)->lock($user, [PurchasingRole::Finance]);
$supplier = Supplier::query()->lockForUpdate()->findOrFail($detail->supplier_id);
$this->actor($user, $supplier);
$latest = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->firstOrFail();
if ($latest->id !== $detail->id) {
$latest = $this->latest($supplier, $detail->account_key);
if ($latest === null || $latest->id !== $detail->id) {
throw ValidationException::withMessages(['bank' => 'Versão substituída. Reveja os dados bancários actuais.']);
}
$existing = SupplierBankReview::query()->where('supplier_bank_detail_id', $detail->id)->where('reviewed_by', $user->id)->first();
@@ -74,9 +127,9 @@ class SupplierBankWorkflow
}
/** Re-evaluate inside the payment transaction in the future; UI readiness is not authorisation. */
public function state(Supplier $supplier): string
public function state(Supplier $supplier, ?string $key = null): string
{
$detail = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->first();
$detail = $this->latest($supplier, $key);
if (! $detail) {
return 'missing';
}
@@ -99,4 +152,18 @@ class SupplierBankWorkflow
return 'approved';
}
public function canReview(User $actor, SupplierBankDetail $detail): bool
{
if ($actor->tenant_id !== $detail->tenant_id || $actor->id === $detail->created_by || ! $actor->hasFunctions([PurchasingRole::Finance])
|| app(OrganizationAccess::class)->maintenanceOnly($actor)
|| SupplierBankReview::query()->where('supplier_bank_detail_id', $detail->id)->where('reviewed_by', $actor->id)->exists()) {
return false;
}
$supplier = Supplier::query()->find($detail->supplier_id);
return $supplier !== null && $supplier->eligible() && $this->latest($supplier, $detail->account_key)?->id === $detail->id
&& ! app(ConflictGuard::class)->hasConflict($actor->id, $supplier->id, null)
&& $this->state($supplier, $detail->account_key) === 'pending';
}
}
+14 -3
View File
@@ -53,7 +53,14 @@ final class SupplierPayablePage
$now = $adapter->readContext($user);
abort_unless($now['scope'] === $context['scope'] && $now['person'] === $context['person'], 409, 'Identidade/contexto alterado; reabra a consulta.');
};
$engine = new Payables(DB::connection(), $actor->id, $context['person'], $scope,
// The default local engine is deliberately older than the optional paged
// composition. Negotiate the checked runtime capability, without replacing it.
$definition = new \ReflectionClass(Payables::class);
$constructor = $definition->getConstructor();
abort_unless($constructor !== null && $constructor->getNumberOfParameters() >= 8 && $constructor->getNumberOfRequiredParameters() <= 8
&& $definition->hasMethod('listingPage'), 503,
'Pacote financeiro sem autorização de leitura paginada; composição explícita pendente.');
$engine = $definition->newInstanceArgs([DB::connection(), $actor->id, $context['person'], $scope,
static function () {
throw new \LogicException('Snapshots de consulta nunca executam comandos.');
},
@@ -65,8 +72,12 @@ final class SupplierPayablePage
}
return $history;
} : null, $read);
$data = $engine->listingPage(array_keys($documents), (int) ($options['proposal_page'] ?? 1), (int) ($options['event_page'] ?? 1), $size);
} : null, $read]);
$listing = $definition->getMethod('listingPage');
abort_unless($listing->isPublic() && $listing->getNumberOfRequiredParameters() <= 4 && $listing->getNumberOfParameters() >= 4,
503, 'Pacote financeiro sem leitura paginada compatível.');
$data = $listing->invoke($engine, array_keys($documents), (int) ($options['proposal_page'] ?? 1), (int) ($options['event_page'] ?? 1), $size);
abort_unless(is_array($data), 503, 'Resposta de leitura paginada incompatível.');
$data['pagination']['documents'] = ['page' => $pager->currentPage(), 'last_page' => $pager->lastPage(), 'total' => $pager->total(), 'per_page' => $pager->perPage()];
$data['listing_query'] = ['page' => $page, 'per_page' => $size, 'q' => $text, 'recognition' => $recognition, 'proposal_page' => (int) ($options['proposal_page'] ?? 1), 'event_page' => (int) ($options['event_page'] ?? 1)];
if ($invoiceId !== null) {
+1 -1
View File
@@ -18,7 +18,7 @@ class WarehouseReservations
public function committed(int $item, int $warehouse): int
{
return $this->ready() ? (int) DB::table('warehouse_reservations')->where('tenant_id', auth()->user()?->tenant_id ?? app(ReplenishmentRun::class)->tenantId())->where('stock_item_id', $item)->where('warehouse_id', $warehouse)->sum('quantity_milli') : 0;
return $this->ready() ? (int) DB::table('warehouse_reservations')->where('tenant_id', auth()->user()->tenant_id ?? app(ReplenishmentRun::class)->tenantId())->where('stock_item_id', $item)->where('warehouse_id', $warehouse)->sum('quantity_milli') : 0;
}
/** @return array<int,int> */
+32 -1
View File
@@ -15,6 +15,7 @@ use App\Models\Quotation;
use App\Models\RecommendationAttempt;
use App\Models\Requisition;
use App\Models\Supplier;
use App\Models\SupplierBankDetail;
use App\Models\SupplierEvaluation;
use App\Models\SupplierImprovement;
use App\Models\SupplierResponse;
@@ -26,6 +27,36 @@ use Illuminate\Support\Facades\Schema;
/** Current tasks delegated to the existing module authorities, never another workflow. */
class WorkflowTaskInbox
{
/** @return list<array<string,mixed>> */
private function bankReviews(User $actor): array
{
if (! $actor->hasFunctions(['finance']) || ! Schema::hasTable('supplier_bank_details')) {
return [];
}
$workflow = app(SupplierBankWorkflow::class);
$multiple = $workflow->multipleReady();
$query = SupplierBankDetail::query()->whereNotExists(function ($q) use ($multiple) {
$q->selectRaw('1')->from('supplier_bank_details as newer')->whereColumn('newer.tenant_id', 'supplier_bank_details.tenant_id')
->whereColumn('newer.supplier_id', 'supplier_bank_details.supplier_id')->whereColumn('newer.revision', '>', 'supplier_bank_details.revision');
if ($multiple) {
$q->where(fn ($scope) => $scope->whereColumn('newer.account_key', 'supplier_bank_details.account_key')
->orWhere(fn ($legacy) => $legacy->whereNull('newer.account_key')->whereNull('supplier_bank_details.account_key')));
}
});
$rows = [];
foreach ($query->lazyById(100) as $detail) {
if (! $workflow->canReview($actor, $detail)) {
continue;
}
$rows[] = ['id' => 'supplier-bank:'.$detail->id.':review', 'module' => 'finance', 'reference' => 'Fornecedor #'.$detail->supplier_id,
'label' => 'Conferir dados bancários · versão '.$detail->revision, 'task' => 'supplier_bank_review', 'status' => 'pending', 'blocked' => false,
'created_at' => $this->date($detail->created_at), 'due_on' => null,
'href' => '/fornecedores/'.$detail->supplier_id.'/dados-bancarios'.($detail->account_key === null ? '' : '?account='.rawurlencode($detail->account_key))];
}
return $rows;
}
/** @return list<array<string,mixed>> */
public function build(User $actor, string $area): array
{
@@ -36,7 +67,7 @@ class WorkflowTaskInbox
}
$rows = $area === 'people' ? $this->people($actor) : [...$this->purchases($actor), ...$this->suppliers($actor), ...$this->quotations($actor), ...$this->documentary($actor), ...$this->formalReviews($actor), ...$this->supply($actor), ...$this->suggestions($actor), ...$this->awards($actor), ...$this->warehouse($actor), ...$this->inventoryCorrections($actor), ...$this->lotSetups($actor), ...$this->finance($actor)];
if ($area === 'procurement') {
$rows = [...$rows, ...$this->supplierImprovements($actor), ...$this->supplierQuality($actor), ...$this->supplyFollowUp($actor), ...$this->lotQuality($actor)];
$rows = [...$rows, ...$this->supplierImprovements($actor), ...$this->supplierQuality($actor), ...$this->supplyFollowUp($actor), ...$this->lotQuality($actor), ...$this->bankReviews($actor)];
if (config('order_cancellation.enabled') && Schema::hasTable('order_cancellations')) {
foreach (OrderCancellation::query()->where('status', 'pending')->lazyById(100) as $record) {
if (app(OrderCancellationWorkflow::class)->canDecide($actor, $record)) {