commit melhorias compras3
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-22 10:56:58 +02:00
parent 4fac443dda
commit efd97e265b
130 changed files with 8917 additions and 363 deletions
+40 -4
View File
@@ -34,7 +34,7 @@ class SupplyPlanning
/** Eligibility to confer, not a promise that changed sources permit approval. */
public function canReview(User $actor, SupplyRecord $record, string $action = 'approve'): bool
{
if (! in_array($record->kind, ['agreement', 'policy'], true) || ! in_array($action, ['approve', 'return', 'suspend'], true)
if (! in_array($record->kind, ['agreement', 'contract', 'policy'], true) || ($record->kind === 'contract' && ! app(AgreementOrderLimits::class)->ready()) || ! in_array($action, ['approve', 'return', 'suspend'], true)
|| ! $this->independentReviewer($actor, $record)) {
return false;
}
@@ -69,6 +69,12 @@ class SupplyPlanning
&& $agreement->stock_item_id === $policy->stock_item_id && $agreement->warehouse_id === $policy->warehouse_id
&& $agreement->data['valid_from'] <= $date && $agreement->data['valid_until'] >= $date && $supplier !== null && $supplier->eligible()
&& $supplier->only(['id', 'name', 'version']) === $agreement->snapshot['supplier'];
if ($valid && ! empty($agreement->data['contract_key'])) {
$header = $this->latest('contract')->where('record_key', $agreement->data['contract_key'])->first();
$valid = $header !== null && $header->state === 'approved' && $header->version === ($agreement->data['contract_version'] ?? null)
&& $header->supplier_id === $agreement->supplier_id && $header->data['currency'] === $agreement->data['currency']
&& $header->data['valid_from'] <= $date && $header->data['valid_until'] >= $date;
}
if (! $valid) {
$projection = [...$projection, 'lead_time_available' => false, 'lead_time_issue' => 'O acordo, fornecedor ou validação documental deixou de sustentar o prazo aprovado. Reconfirme o fornecimento; as datas de pedir/encomendar ficam por determinar.',
'request_date' => null, 'order_date' => null, 'reorder_point_milli' => null];
@@ -90,7 +96,10 @@ class SupplyPlanning
if (in_array($kind, ['reservation', 'delivery', 'alternative'], true)) {
return app(SupplyCoordination::class)->save($actor, $kind, $input);
}
abort_unless(in_array($kind, ['policy', 'agreement', 'import'], true), 404);
abort_unless(in_array($kind, ['policy', 'agreement', 'contract', 'import'], true), 404);
if ($kind === 'contract') {
abort_unless(app(AgreementOrderLimits::class)->ready(), 503, 'Contratos multiartigo preparados apenas em QA isolada.');
}
abort_unless(Schema::hasTable('supply_records'), 503, 'Instalação do fornecimento pendente.');
return DB::transaction(function () use ($actor, $kind, $input) {
@@ -124,6 +133,9 @@ class SupplyPlanning
$agreement = $this->latest('agreement')->where('record_key', $data['agreement_key'])->firstOrFail();
$this->check($agreement->state === 'approved' && $agreement->stock_item_id === (int) $data['stock_item_id'] && $agreement->warehouse_id === (int) $data['warehouse_id'], 'data.agreement_key', 'Seleccione um acordo aprovado deste artigo/local.');
$this->check($agreement->data['lead_days'] !== null && $agreement->data['valid_from'] <= today()->toDateString() && $agreement->data['valid_until'] >= today()->toDateString(), 'data.agreement_key', 'O acordo deve estar vigente e ter prazo conhecido.');
if (! empty($agreement->data['contract_key'])) {
app(AgreementOrderLimits::class)->contract($agreement->data, $actor->tenant_id);
}
$data['lead_days'] = $agreement->data['lead_days'];
$data['origin'] = $agreement->data['origin'];
$data['agreement_version'] = $agreement->version;
@@ -131,6 +143,9 @@ class SupplyPlanning
} else {
$this->check($old !== null, 'action', 'Guarde primeiro a preparação.');
$data = $old->data;
if (in_array($kind, ['agreement', 'contract'], true)) {
app(AgreementOrderLimits::class)->terms($data);
}
if ($kind !== 'import') {
$this->check(in_array($action, ['approve', 'return', 'suspend'], true), 'action', 'Acção incompatível com este registo.');
$this->check($this->independentReviewer($actor, $old), 'action', 'A conferência exige uma pessoa que não tenha preparado esta versão ou as anteriores.');
@@ -156,11 +171,15 @@ class SupplyPlanning
if ($order !== null) {
app(OrderCancellationWorkflow::class)->assertOperational($order);
}
if ($kind === 'agreement' && $state === 'approved') {
if (in_array($kind, ['agreement', 'contract'], true) && $state === 'approved') {
$this->check($supplier !== null && $supplier->eligible(), 'supplier_id', 'O fornecedor deve estar activo e com revisão documental vigente.');
$this->check(! app(ConflictGuard::class)->hasConflict($actor->id, $supplier->id, null), 'supplier_id', 'Existe conflito declarado com este fornecedor.');
$this->check(($old->snapshot['supplier'] ?? null) === $supplier->only(['id', 'name', 'version']), 'supplier_id', 'O fornecedor mudou desde a preparação. Devolva e actualize a versão.');
}
if ($kind === 'agreement' && ! empty($data['contract_key']) && in_array($action, ['save', 'approve'], true)) {
$contract = app(AgreementOrderLimits::class)->contract($data, $actor->tenant_id);
$data['contract_version'] = $contract->version;
}
if ($kind === 'policy' && $state === 'approved') {
if (($data['forecast_method'] ?? 'manual') === 'historical') {
$history = app(SupplyHistory::class)->reference($data);
@@ -169,6 +188,9 @@ class SupplyPlanning
if (! empty($data['agreement_key'])) {
$agreement = $this->latest('agreement')->where('record_key', $data['agreement_key'])->firstOrFail();
$this->check($agreement->state === 'approved' && $agreement->version === $data['agreement_version'], 'action', 'O acordo mudou desde a preparação. Devolva e seleccione a versão actual.');
if (! empty($agreement->data['contract_key'])) {
app(AgreementOrderLimits::class)->contract($agreement->data, $actor->tenant_id);
}
}
$clash = $this->latest('policy')->where('state', 'approved')->where('stock_item_id', $item->id)->where('warehouse_id', $warehouse->id)->where('record_key', '!=', $old->record_key)->exists();
$this->check(! $clash, 'action', 'Suspenda a política anterior deste artigo/local antes de aprovar a substituição.');
@@ -184,6 +206,11 @@ class SupplyPlanning
}
$snapshot = $action === 'save' ? ['prepared_by' => $actor->id, 'contributors' => array_values(array_unique([...($old?->snapshot['contributors'] ?? []), $actor->id])), 'item' => $item?->only(['id', 'code', 'name', 'unit']), 'warehouse' => $warehouse?->only(['id', 'code', 'name']),
'supplier' => $supplier?->only(['id', 'name', 'version']), 'order' => $order?->only(['id', 'number', 'currency', 'supplier_id', 'total_minor'])] : $old->snapshot;
if ($action === 'save' && $kind === 'agreement' && ! empty($data['contract_key'])) {
$header = app(AgreementOrderLimits::class)->contract($data, $actor->tenant_id);
$snapshot['contract'] = ['id' => $header->id, 'record_key' => $header->record_key, 'version' => $header->version, 'reference' => $header->data['reference'],
'currency' => $header->data['currency'], 'max_order_value_minor' => $header->data['max_order_value_minor'] ?? null];
}
if ($state === 'approved') {
$this->check($snapshot['item'] === $item?->only(['id', 'code', 'name', 'unit']), 'action', 'O cadastro do artigo mudou. Devolva e actualize a preparação.');
}
@@ -223,7 +250,10 @@ class SupplyPlanning
'daily_milli' => 'nullable|integer|min:0|max:1000000000', 'lead_days' => 'required|integer|min:0|max:3650', 'approval_days' => 'required|integer|min:0|max:365',
'horizon_days' => 'required|integer|min:1|max:366', 'minimum_milli' => 'required|integer|min:0|max:1000000000', 'pack_milli' => 'required|integer|min:1|max:1000000000',
'basis' => 'required|string|min:5|max:2000'],
'agreement' => ['stock_item_id' => 'required|integer|min:1', 'warehouse_id' => 'required|integer|min:1', 'supplier_id' => 'required|integer|min:1',
'contract' => ['supplier_id' => 'required|integer|min:1', 'reference' => 'required|string|max:200',
'currency' => 'required|regex:/^[A-Z]{3}$/', 'valid_from' => 'required|date_format:Y-m-d', 'valid_until' => 'required|date_format:Y-m-d|after_or_equal:valid_from',
'periodicity_days' => 'nullable|integer|min:1|max:3650'],
'agreement' => ['contract_key' => 'nullable|uuid', 'stock_item_id' => 'required|integer|min:1', 'warehouse_id' => 'required|integer|min:1', 'supplier_id' => 'required|integer|min:1',
'habitual' => 'required|boolean', 'valid_from' => 'required|date_format:Y-m-d', 'valid_until' => 'required|date_format:Y-m-d|after_or_equal:valid_from',
'origin' => 'required|in:local,import', 'currency' => 'required|regex:/^[A-Z]{3}$/', 'price_minor' => 'nullable|integer|min:0|max:1000000000000',
'lead_days' => 'nullable|integer|min:0|max:3650', 'reference' => 'required|string|max:200'],
@@ -233,6 +263,12 @@ class SupplyPlanning
default => throw new \InvalidArgumentException('Tipo de fornecimento desconhecido.'),
};
$data = Validator::make($input, $rules)->validate();
if (in_array($kind, ['agreement', 'contract'], true)) {
$data = [...$data, ...app(AgreementOrderLimits::class)->terms($input)];
}
if ($kind === 'contract') {
$this->check(($data['max_order_quantity_milli'] ?? null) === null, 'data.order_limit_quantity', 'O limite de quantidade pertence a cada artigo, não ao conjunto de unidades distintas.');
}
if ($predecessor !== null) {
$this->check((int) $data['stock_item_id'] === $predecessor->stock_item_id && (int) $data['warehouse_id'] === $predecessor->warehouse_id, 'data.stock_item_id', 'A política reutilizada mantém o artigo e local de origem.');
$data['predecessor_version'] = (int) $data['predecessor_version'];