280 lines
17 KiB
PHP
280 lines
17 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\PurchaseOrder;
|
|
use App\Models\Quotation;
|
|
use App\Models\Requisition;
|
|
use App\Models\StockItem;
|
|
use App\Models\SupplyRecord;
|
|
use App\Models\User;
|
|
use Brick\Math\BigDecimal;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Validation\ValidationException;
|
|
use Tempo\Inventory\QuantityConversion;
|
|
|
|
/** Owner decision: each order has the full optional limit. No cumulative balance or financial writer. */
|
|
final class AgreementOrderLimits
|
|
{
|
|
public function ready(): bool
|
|
{
|
|
$db = DB::connection();
|
|
|
|
return config('agreement_order_limits.qa_enabled') === true && app()->environment('testing')
|
|
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
|
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()) === 1));
|
|
}
|
|
|
|
/** @param array<string,mixed> $input
|
|
* @return array<string,mixed>
|
|
*/
|
|
public function terms(array $input): array
|
|
{
|
|
foreach (['order_limit_amount', 'order_limit_quantity', 'max_order_value_minor', 'max_order_quantity_milli'] as $field) {
|
|
if (isset($input[$field]) && is_string($input[$field]) && trim($input[$field]) === '') {
|
|
$input[$field] = null;
|
|
}
|
|
}
|
|
if (! array_intersect(['order_limit_amount', 'order_limit_quantity', 'max_order_value_minor', 'max_order_quantity_milli'], array_keys($input))) {
|
|
return [];
|
|
}
|
|
abort_unless($this->ready(), 503, 'Limites por ordem preparados apenas em QA isolada.');
|
|
Validator::make($input, ['order_limit_basis' => 'sometimes|in:per_order'])->validate();
|
|
$result = ['order_limit_basis' => 'per_order'];
|
|
foreach (['amount' => ['max_order_value_minor', 100, 2], 'quantity' => ['max_order_quantity_milli', 1000, 3]] as $name => [$key,$scale,$decimals]) {
|
|
$field = 'order_limit_'.$name;
|
|
if (array_key_exists($field, $input)) {
|
|
$digits = $name === 'amount' ? 11 : 10;
|
|
$v = Validator::make($input, [$field => ['nullable', 'string', 'regex:/^\d{1,'.$digits.'}(\.\d{1,'.$decimals.'})?$/D']])->validate();
|
|
$result[$key] = ($v[$field] ?? null) === null ? null : BigDecimal::of($v[$field])->multipliedBy($scale)->toScale(0)->toInt();
|
|
if ($result[$key] !== null && $result[$key] > 1000000000000) {
|
|
throw ValidationException::withMessages([$field => 'O limite excede o intervalo decimal suportado.']);
|
|
}
|
|
} else {
|
|
$v = Validator::make($input, [$key => 'nullable|integer|min:0|max:1000000000000'])->validate();
|
|
$result[$key] = isset($v[$key]) ? (int) $v[$key] : null;
|
|
}
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
public function canRead(User $actor): bool
|
|
{
|
|
$planning = app(SupplyPlanning::class);
|
|
|
|
return collect(['supply_read', 'supply_prepare', 'supply_review'])->contains(fn (string $p) => $planning->allows($actor, $p));
|
|
}
|
|
|
|
/** @param list<array<string,mixed>> $bindings
|
|
* @return list<array<string,mixed>>
|
|
*/
|
|
private function canonical(array $bindings): array
|
|
{
|
|
$v = Validator::make(['agreement_bindings' => $bindings], [
|
|
'agreement_bindings' => 'array|max:100', 'agreement_bindings.*' => 'array:requisition_item_id,agreement_id,conversion',
|
|
'agreement_bindings.*.requisition_item_id' => 'required|integer|min:1|distinct',
|
|
'agreement_bindings.*.agreement_id' => 'required|integer|min:1',
|
|
'agreement_bindings.*.conversion' => 'sometimes|nullable|array:numerator,denominator,source,version',
|
|
'agreement_bindings.*.conversion.numerator' => ['required_with:agreement_bindings.*.conversion', 'string', 'regex:/^[1-9]\d{0,8}$/D'],
|
|
'agreement_bindings.*.conversion.denominator' => ['required_with:agreement_bindings.*.conversion', 'string', 'regex:/^[1-9]\d{0,8}$/D'],
|
|
'agreement_bindings.*.conversion.source' => 'required_with:agreement_bindings.*.conversion|string|max:500',
|
|
'agreement_bindings.*.conversion.version' => 'required_with:agreement_bindings.*.conversion|string|max:100',
|
|
])->validate();
|
|
$rows = [];
|
|
foreach ($v['agreement_bindings'] as $row) {
|
|
$entry = ['requisition_item_id' => (int) $row['requisition_item_id'], 'agreement_id' => (int) $row['agreement_id']];
|
|
if (! empty($row['conversion'])) {
|
|
$entry['conversion'] = ['numerator' => $row['conversion']['numerator'], 'denominator' => $row['conversion']['denominator'],
|
|
'source' => trim($row['conversion']['source']), 'version' => trim($row['conversion']['version'])];
|
|
}
|
|
$rows[] = $entry;
|
|
}
|
|
usort($rows, fn ($a, $b) => $a['requisition_item_id'] <=> $b['requisition_item_id']);
|
|
|
|
return $rows;
|
|
}
|
|
|
|
/** @param list<array<string,mixed>> $bindings */
|
|
public function assertReplay(PurchaseOrder $order, array $bindings): void
|
|
{
|
|
if ($bindings === []) {
|
|
return;
|
|
} // Native callers may recover an existing order without proposing a new association.
|
|
$hash = hash('sha256', json_encode($this->canonical($bindings), JSON_THROW_ON_ERROR));
|
|
abort_unless(($order->snapshot['agreement_order_input_hash'] ?? null) === $hash, 409, 'A ordem já foi emitida com outra base; não associe acordos retroactivamente.');
|
|
}
|
|
|
|
/** @param list<array<string,mixed>> $lines
|
|
* @param list<array<string,mixed>> $bindings
|
|
* @param list<Requisition> $additionalRequests
|
|
* @return array<string,mixed>
|
|
*/
|
|
public function freeze(User $actor, Quotation $quote, Requisition $request, array $lines, array $bindings, array $additionalRequests = []): array
|
|
{
|
|
if ($bindings === []) {
|
|
return [];
|
|
}
|
|
abort_unless($this->ready() && Schema::hasTable('supply_records'), 503, 'Limites por ordem preparados apenas em QA isolada.');
|
|
abort_unless($this->canRead($actor), 403);
|
|
$bindings = $this->canonical($bindings);
|
|
$sources = $request->items()->get()->keyBy('id');
|
|
foreach ($additionalRequests as $additional) {
|
|
abort_unless($additional->tenant_id === $actor->tenant_id
|
|
&& Requisition::query()->visibleTo($actor)->whereKey($additional->id)->exists(), 403);
|
|
$sources = $sources->concat($additional->items()->get())->keyBy('id');
|
|
}
|
|
$frozen = [];
|
|
$groups = [];
|
|
foreach ($bindings as $binding) {
|
|
$line = collect($lines)->firstWhere('requisition_item_id', $binding['requisition_item_id']);
|
|
$source = $sources->get($binding['requisition_item_id']);
|
|
$agreement = app(SupplyPlanning::class)->latest('agreement')->where('tenant_id', $actor->tenant_id)->whereKey($binding['agreement_id'])->lockForUpdate()->first();
|
|
$this->check($line !== null && $source !== null && $agreement !== null, 'Seleccione uma linha desta ordem e a versão actual do acordo da sua empresa.');
|
|
$stock = StockItem::query()->whereKey($agreement->stock_item_id)->lockForUpdate()->first();
|
|
$this->check($agreement->state === 'approved' && ($agreement->data['valid_from'] ?? '9999-12-31') <= today()->toDateString()
|
|
&& ($agreement->data['valid_until'] ?? '0000-01-01') >= today()->toDateString(), 'O acordo deve estar aprovado e vigente na emissão.');
|
|
$this->check($agreement->supplier_id === $quote->supplier_id && ($agreement->data['currency'] ?? null) === $quote->currency, 'Conserve o fornecedor e a moeda do acordo; não há conversão monetária implícita.');
|
|
$this->check($stock !== null && ($source->catalogue_snapshot['stock_item_id'] ?? null) === $stock->id
|
|
&& ($agreement->snapshot['item'] ?? null) === $stock->only(['id', 'code', 'name', 'unit']), 'A linha deve ter ligação documental ao artigo do acordo e cadastro actual. Não associe por nome.');
|
|
$this->check(($agreement->snapshot['supplier'] ?? null) === $quote->supplier?->only(['id', 'name', 'version']), 'A referência do fornecedor no acordo mudou; reveja o acordo.');
|
|
$quantity = (string) ReceiptWorkflow::milli((string) $line['quantity']);
|
|
$conversion = $binding['conversion'] ?? null;
|
|
if (mb_strtolower(trim($line['unit'])) !== mb_strtolower(trim($stock->unit))) {
|
|
$this->check(is_array($conversion) && trim($conversion['source']) !== '' && trim($conversion['version']) !== '', 'Indique factor, fonte e versão para converter a quantidade à unidade do acordo.');
|
|
$this->loadArithmetic();
|
|
try {
|
|
$quantity = QuantityConversion::toBase($quantity, $conversion['numerator'], $conversion['denominator']);
|
|
} catch (\InvalidArgumentException $e) {
|
|
throw ValidationException::withMessages(['agreement_bindings' => $e->getMessage()]);
|
|
}
|
|
} else {
|
|
$this->check($conversion === null, 'Unidades coincidentes não exigem um factor.');
|
|
}
|
|
$terms = $this->terms($agreement->data);
|
|
$frozen[$source->id] = ['schema' => 'sgc.agreement.order_limit.v1', 'basis' => 'per_order', 'agreement_id' => $agreement->id,
|
|
'record_key' => $agreement->record_key, 'version' => $agreement->version, 'reference' => $agreement->data['reference'], 'currency' => $quote->currency,
|
|
'stock_item_id' => $stock->id, 'warehouse_id' => $agreement->warehouse_id, 'unit' => $stock->unit,
|
|
'document_unit' => $line['unit'], 'document_quantity_milli' => (string) ReceiptWorkflow::milli((string) $line['quantity']),
|
|
'description' => $line['description'],
|
|
'agreement_quantity_milli' => $quantity, 'total_minor' => $line['total_minor'], 'includes_tax' => true,
|
|
'max_order_value_minor' => $terms['max_order_value_minor'] ?? null, 'max_order_quantity_milli' => $terms['max_order_quantity_milli'] ?? null,
|
|
...($conversion === null ? [] : ['conversion' => $conversion])];
|
|
$groups[$agreement->id][] = $frozen[$source->id];
|
|
}
|
|
foreach ($groups as $rows) {
|
|
$value = BigDecimal::zero();
|
|
$quantity = BigDecimal::zero();
|
|
foreach ($rows as $row) {
|
|
$value = $value->plus($row['total_minor']);
|
|
$quantity = $quantity->plus($row['agreement_quantity_milli']);
|
|
}
|
|
$first = $rows[0];
|
|
$this->check($first['max_order_value_minor'] === null || $value->isLessThanOrEqualTo($first['max_order_value_minor']), 'O total com impostos das linhas ligadas excede o limite deste acordo por ordem.');
|
|
$this->check($first['max_order_quantity_milli'] === null || $quantity->isLessThanOrEqualTo($first['max_order_quantity_milli']), 'A quantidade das linhas ligadas excede o limite deste acordo por ordem.');
|
|
foreach ($frozen as &$row) {
|
|
if ($row['agreement_id'] === $first['agreement_id']) {
|
|
$row['checked_order_value_minor'] = $value->toInt();
|
|
$row['checked_order_quantity_milli'] = (string) $quantity;
|
|
}
|
|
}
|
|
unset($row);
|
|
}
|
|
|
|
$contracts = [];
|
|
foreach ($groups as $agreementId => $rows) {
|
|
$agreement = app(SupplyPlanning::class)->latest('agreement')->where('tenant_id', $actor->tenant_id)->whereKey($agreementId)->firstOrFail();
|
|
if (empty($agreement->data['contract_key'])) {
|
|
continue;
|
|
}
|
|
$contract = $this->contract($agreement->data, $actor->tenant_id);
|
|
$this->check(($contract->snapshot['supplier'] ?? null) === $quote->supplier?->only(['id', 'name', 'version']), 'O fornecedor mudou desde a preparação do contrato.');
|
|
$terms = $this->terms($contract->data);
|
|
$contracts[$contract->id] ??= ['id' => $contract->id, 'record_key' => $contract->record_key, 'version' => $contract->version,
|
|
'reference' => $contract->data['reference'], 'currency' => $contract->data['currency'], 'basis' => 'per_order',
|
|
'max_order_value_minor' => $terms['max_order_value_minor'] ?? null, 'checked_order_value_minor' => 0];
|
|
foreach ($rows as $row) {
|
|
$contracts[$contract->id]['checked_order_value_minor'] = BigDecimal::of($contracts[$contract->id]['checked_order_value_minor'])->plus($row['total_minor'])->toInt();
|
|
}
|
|
foreach ($frozen as &$row) {
|
|
if ($row['agreement_id'] === $agreementId) {
|
|
$row['contract_id'] = $contract->id;
|
|
}
|
|
}
|
|
unset($row);
|
|
}
|
|
foreach ($contracts as $contract) {
|
|
$this->check($contract['max_order_value_minor'] === null || $contract['checked_order_value_minor'] <= $contract['max_order_value_minor'], 'O total com impostos dos artigos ligados excede o limite global do contrato nesta ordem.');
|
|
}
|
|
foreach ($frozen as &$row) {
|
|
if (isset($row['contract_id'])) {
|
|
$row['contract'] = $contracts[$row['contract_id']];
|
|
}
|
|
}
|
|
unset($row);
|
|
|
|
return ['agreement_order_input_hash' => hash('sha256', json_encode($bindings, JSON_THROW_ON_ERROR)), 'agreement_bindings' => $frozen];
|
|
}
|
|
|
|
/** @param array<string,mixed> $data */
|
|
public function contract(array $data, int $tenantId): SupplyRecord
|
|
{
|
|
abort_unless($this->ready(), 503);
|
|
$contract = app(SupplyPlanning::class)->latest('contract')->where('tenant_id', $tenantId)
|
|
->where('record_key', $data['contract_key'])->lockForUpdate()->first();
|
|
$this->check($contract !== null && $contract->state === 'approved', 'Seleccione um contrato aprovado e actual da sua empresa.');
|
|
$this->check(! isset($data['contract_version']) || $data['contract_version'] === $contract->version, 'O contrato mudou; devolva e actualize a associação antes de aprovar.');
|
|
$this->check($contract->supplier_id === (int) $data['supplier_id'] && $contract->data['currency'] === $data['currency'], 'O artigo deve conservar o fornecedor e a moeda do contrato.');
|
|
$this->check($data['valid_from'] >= $contract->data['valid_from'] && $data['valid_until'] <= $contract->data['valid_until'], 'A vigência do artigo deve estar contida na vigência do contrato.');
|
|
|
|
return $contract;
|
|
}
|
|
|
|
/** @param list<int|string> $selected
|
|
* @return list<array<string,mixed>>
|
|
*/
|
|
public function options(User $actor, Requisition $request, ?Quotation $quote, string $search = '', array $selected = []): array
|
|
{
|
|
if (! $this->ready() || ! $this->canRead($actor) || $quote === null || ! Schema::hasTable('supply_records')) {
|
|
return [];
|
|
}
|
|
$stockIds = $request->items()->get()->map(fn ($item) => $item->catalogue_snapshot['stock_item_id'] ?? null)->filter()->unique();
|
|
$base = app(SupplyPlanning::class)->latest('agreement')->where('state', 'approved')->where('supplier_id', $quote->supplier_id)
|
|
->whereIn('stock_item_id', $stockIds)->where('data->currency', $quote->currency)->where('data->valid_from', '<=', today()->toDateString())->where('data->valid_until', '>=', today()->toDateString());
|
|
$recent = (clone $base)->when($search !== '', fn ($q) => $q->whereLike('data->reference', '%'.$search.'%'))->orderByDesc('id')->limit(100)->pluck('id');
|
|
|
|
return array_values($base->where(fn ($q) => $q->whereIn('id', $recent)->orWhereIn('id', $selected))->orderByDesc('id')->get()->map(fn ($record) => [
|
|
'id' => $record->id, 'version' => $record->version, 'reference' => $record->data['reference'], 'stock_item_id' => $record->stock_item_id,
|
|
'contract' => $record->snapshot['contract'] ?? null,
|
|
'warehouse' => $record->snapshot['warehouse']['name'] ?? null, 'unit' => $record->snapshot['item']['unit'] ?? null, 'currency' => $record->data['currency'],
|
|
'max_order_value_minor' => $record->data['max_order_value_minor'] ?? null, 'max_order_quantity_milli' => $record->data['max_order_quantity_milli'] ?? null,
|
|
])->all());
|
|
}
|
|
|
|
private function loadArithmetic(): void
|
|
{
|
|
$root = base_path('packages/inventory-write/development');
|
|
$bytes = file_get_contents($root.'/manifest.json');
|
|
if ($bytes === false || ! hash_equals('90cf565537e7fd48eb54a87bcfd6d585cf53239f075764910047838b3b8b4c38', hash('sha256', $bytes))) {
|
|
throw new \LogicException('Artefacto aritmético incompatível.');
|
|
}
|
|
$manifest = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
|
$file = $root.'/src/QuantityConversion.php';
|
|
$hash = hash_file('sha256', $file);
|
|
if (! is_string($hash) || ! hash_equals($manifest['files']['src/QuantityConversion.php'], $hash)) {
|
|
throw new \LogicException('Aritmética alterada.');
|
|
}
|
|
require_once $file;
|
|
}
|
|
|
|
/** @phpstan-assert true $condition */
|
|
private function check(bool $condition, string $message): void
|
|
{
|
|
if (! $condition) {
|
|
throw ValidationException::withMessages(['agreement_bindings' => $message]);
|
|
}
|
|
}
|
|
}
|