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
+106
View File
@@ -0,0 +1,106 @@
<?php
namespace App\Services;
use App\Models\SupplyRecord;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;
/** Current approved versions only. Dates describe vigency, never renewal or purchase authority. */
final class AgreementFollowup
{
public function authorize(User $actor): User
{
$current = User::query()->findOrFail($actor->id);
abort_unless(auth()->id() === $current->id && $current->tenant_id !== null && $current->tenant_id === $actor->tenant_id, 403);
$planning = app(SupplyPlanning::class);
abort_unless(collect(['supply_read', 'supply_prepare', 'supply_review'])->contains(fn (string $permission) => $planning->allows($current, $permission)), 403);
abort_unless(Schema::hasTable('supply_records'), 503, 'Instalação do fornecimento pendente.');
return $current;
}
/** @return array{search:string,validity:string,expires_by:string} */
public function filters(Request $request): array
{
$v = $request->validate(['search' => 'nullable|string|max:100', 'validity' => 'nullable|in:all,current,expired,future,unknown',
'expires_by' => 'nullable|date_format:Y-m-d', 'page' => 'nullable|integer|min:1|max:1000000']);
return ['search' => trim($v['search'] ?? ''), 'validity' => $v['validity'] ?? 'all', 'expires_by' => $v['expires_by'] ?? ''];
}
/** @param array{search:string,validity:string,expires_by:string} $filters
* @return Builder<SupplyRecord>
*/
public function query(User $actor, array $filters, string $today, string $kind = 'agreement'): Builder
{
abort_unless(in_array($kind, ['agreement', 'contract'], true), 404);
if ($kind === 'contract') {
abort_unless(app(AgreementOrderLimits::class)->ready(), 503);
}
$query = app(SupplyPlanning::class)->latest($kind)->where('tenant_id', $actor->tenant_id)->where('state', 'approved');
if ($filters['search'] !== '') {
$query->where(fn (Builder $q) => $q->whereLike('data->reference', '%'.$filters['search'].'%')
->orWhereLike('snapshot->supplier->name', '%'.$filters['search'].'%')->orWhereLike('snapshot->item->code', '%'.$filters['search'].'%')
->orWhereLike('snapshot->item->name', '%'.$filters['search'].'%')->orWhereLike('snapshot->warehouse->name', '%'.$filters['search'].'%'));
}
if ($filters['validity'] === 'unknown') {
$query->where(fn (Builder $q) => $q->whereNull('data->valid_from')->orWhereNull('data->valid_until')->orWhere('data->valid_from', '')->orWhere('data->valid_until', ''));
} elseif ($filters['validity'] !== 'all') {
$query->whereNotNull('data->valid_from')->where('data->valid_from', '!=', '')->whereNotNull('data->valid_until')->where('data->valid_until', '!=', '');
match ($filters['validity']) {
'current' => $query->where('data->valid_from', '<=', $today)->where('data->valid_until', '>=', $today),
'expired' => $query->where('data->valid_until', '<', $today),
'future' => $query->where('data->valid_from', '>', $today),
default => throw new \InvalidArgumentException('Situação de vigência desconhecida.'),
};
}
if ($filters['expires_by'] !== '') {
$query->where('data->valid_until', '!=', '')->where('data->valid_until', '<=', $filters['expires_by']);
}
return $query;
}
/** @param Collection<int,SupplyRecord> $records
* @return list<array<string,mixed>>
*/
public function rows(Collection $records, string $today): array
{
$counts = app(SupplyPlanning::class)->latest('policy')->where('state', 'approved')->whereIn('data->agreement_key', $records->pluck('record_key'))
->select('data->agreement_key as agreement_key')->selectRaw('COUNT(*) as policy_count')->groupBy('data->agreement_key')->get()
->mapWithKeys(fn (SupplyRecord $record) => [(string) $record->getAttribute('agreement_key') => (int) $record->getAttribute('policy_count')]);
$articles = app(SupplyPlanning::class)->latest('agreement')->where('state', 'approved')->whereIn('data->contract_key', $records->where('kind', 'contract')->pluck('record_key'))
->select('data->contract_key as contract_key')->selectRaw('COUNT(*) as article_count')->groupBy('data->contract_key')->get()
->mapWithKeys(fn (SupplyRecord $record) => [(string) $record->getAttribute('contract_key') => (int) $record->getAttribute('article_count')]);
return array_values($records->map(function (SupplyRecord $record) use ($today, $counts, $articles) {
$from = $this->date($record->data['valid_from'] ?? null);
$until = $this->date($record->data['valid_until'] ?? null);
$validity = $from === null || $until === null ? 'unknown' : ($until < $from ? 'unknown' : ($until < $today ? 'expired' : ($from > $today ? 'future' : 'current')));
return ['id' => $record->id, 'record_key' => $record->record_key, 'version' => $record->version, 'reference' => $record->data['reference'] ?? null,
'supplier' => $record->snapshot['supplier']['name'] ?? null, 'item_code' => $record->snapshot['item']['code'] ?? null,
'item' => $record->snapshot['item']['name'] ?? null, 'warehouse' => $record->snapshot['warehouse']['name'] ?? null,
'valid_from' => $from, 'valid_until' => $until, 'validity' => $validity, 'approved_policies' => $counts->get($record->record_key, 0),
'kind' => $record->kind, 'currency' => $record->data['currency'] ?? null, 'max_order_value_minor' => $record->data['max_order_value_minor'] ?? null,
'periodicity_days' => $record->data['periodicity_days'] ?? null, 'approved_articles' => $articles->get($record->record_key, 0),
'articles_href' => '/compras/fornecimento?view=agreements&linked_contract_key='.$record->record_key,
'href' => '/compras/fornecimento?view='.($record->kind === 'contract' ? 'contracts' : 'agreements').'&record_id='.$record->id.'#supply-record-'.$record->id,
'policies_href' => '/compras/fornecimento?view=calendar&linked_agreement_key='.$record->record_key];
})->all());
}
private function date(mixed $value): ?string
{
if (! is_string($value)) {
return null;
}
$date = \DateTimeImmutable::createFromFormat('!Y-m-d', $value);
return $date !== false && $date->format('Y-m-d') === $value ? $value : null;
}
}
+273
View File
@@ -0,0 +1,273 @@
<?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
* @return array<string,mixed>
*/
public function freeze(User $actor, Quotation $quote, Requisition $request, array $lines, array $bindings): 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');
$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]);
}
}
}
+2 -1
View File
@@ -248,7 +248,8 @@ class AutomaticPurchases
foreach ($request->snapshot['lines'] as $index => $line) {
if ($line['item']['id'] === $item && $p['remaining'][$index] > 0) {
$unreserved += max(0, $p['remaining'][$index] - $p['reserved'][$index]);
$origins[] = ['warehouse_request_id' => $request->id, 'version' => $p['version'], 'line_index' => $index, 'destination' => $line['destination'], 'equipment' => $line['equipment'], 'remaining_milli' => $p['remaining'][$index], 'reserved_milli' => $p['reserved'][$index]];
$origins[] = ['warehouse_request_id' => $request->id, 'version' => $p['version'], 'line_index' => $index, 'destination' => $line['destination'], 'equipment' => $line['equipment'], 'remaining_milli' => $p['remaining'][$index], 'reserved_milli' => $p['reserved'][$index],
...(isset($line['production']) ? ['production' => $line['production']] : [])];
}
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Services;
class CompanyDetails
{
public const FIELDS = [
'legal_name' => 'Denominação social', 'nuel' => 'NUEL', 'address' => 'Endereço',
'nuit' => 'NUIT', 'phone' => 'Telefone', 'email' => 'Email', 'legal_representative' => 'Representante legal',
];
public const BANK_FIELDS = [
'bank' => 'Banco', 'branch' => 'Balcão', 'account_number' => 'Número de conta',
'currency' => 'Moeda', 'nib' => 'NIB', 'iban' => 'IBAN', 'nuib' => 'NUIB', 'account_holder' => 'Titular da conta',
];
public const LOCATION_FIELDS = ['name' => 'Designação', 'address' => 'Endereço', 'phone' => 'Telefone', 'email' => 'Email'];
/** @return array<string,string> */
public function rules(): array
{
$rules = ['reason' => 'required|string|min:10|max:4000'];
foreach (self::FIELDS as $field => $label) {
$rules[$field] = 'present|nullable|string|max:255';
}
$rules['address'] = 'present|nullable|string|max:1000';
$rules['email'] = 'present|nullable|email|max:255';
$rules['nuit'] = 'present|nullable|regex:/^\d{9}$/D';
$rules['bank_accounts'] = 'present|array';
$rules['establishments'] = 'present|array';
foreach (['bank_accounts' => self::BANK_FIELDS, 'establishments' => self::LOCATION_FIELDS] as $collection => $fields) {
$extra = $collection === 'establishments' ? ',kind' : '';
$rules[$collection.'.*'] = 'array:id,'.implode(',', array_keys($fields)).$extra;
$rules[$collection.'.*.id'] = 'required|uuid|distinct';
foreach ($fields as $field => $label) {
$rules[$collection.'.*.'.$field] = 'present|nullable|string|max:'.($field === 'address' ? '1000' : '255');
}
}
$rules['bank_accounts.*.currency'] = 'present|nullable|regex:/^[A-Z]{3}$/D';
$rules['establishments.*.email'] = 'present|nullable|email|max:255';
$rules['establishments.*.name'] = 'required|string|max:255';
$rules['establishments.*.kind'] = 'required|in:headquarters,branch';
return $rules;
}
}
+3
View File
@@ -103,6 +103,9 @@ final class InternalRequisitionPort implements RequisitionPort
public function policy(array $record): array
{
$r = $this->model($record['id']);
if ($r->getAttribute('draft_input') !== null || $r->getAttribute('cost_center_id') === null || $r->needed_by === null || $r->subtotal_minor === null || $r->total_minor === null) {
throw ValidationException::withMessages(['submission' => 'Complete os campos e as linhas do rascunho antes de submeter. Não foram criadas aprovações ou reservas.']);
}
if ($this->actor->department_id !== $r->department_id) {
throw ValidationException::withMessages(['submission' => 'O departamento do solicitante mudou. Reveja o rascunho e o centro de custo antes de submeter.']);
}
+10 -1
View File
@@ -48,7 +48,16 @@ class OrganizationConfiguration
throw ValidationException::withMessages(['version' => 'A parametrização foi alterada. Actualize e compare antes de guardar.']);
}
$before = null;
if ($command === 'profile') {
if ($command === 'company_details') {
abort_unless(Schema::hasColumn('tenants', 'company_details'), 503, 'Instalação dos dados da empresa pendente.');
if (count(array_filter($data['establishments'], fn (array $row) => $row['kind'] === 'headquarters')) > 1) {
throw ValidationException::withMessages(['establishments' => 'Identifique apenas um estabelecimento como sede.']);
}
$company = Tenant::query()->findOrFail($actor->tenant_id);
$before = $company->only(['company_details']);
$company->update(['company_details' => array_intersect_key($data, CompanyDetails::FIELDS + ['bank_accounts' => true, 'establishments' => true])]);
$after = [...$company->only(['company_details']), 'reason' => $data['reason']];
} elseif ($command === 'profile') {
$profile = isset($data['id']) ? DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->where('id', $data['id'])->first() : null;
abort_if(isset($data['id']) && ! $profile, 404);
if ($profile && in_array('admin', $data['permissions'], true) && DB::table('organization_memberships')->where('tenant_id', $actor->tenant_id)->where('profile_id', $profile->id)->where('maintenance', true)->exists()) {
@@ -20,7 +20,8 @@ class ProcurementOperationalInsights
$today = $instant->setTimezone(config('app.timezone'))->startOfDay();
$total = $pending = $missingSubmission = $neededPast = $approved = $withoutQuotes = $withoutOrder = 0;
$oldest = [];
foreach ((clone $query)->reorder()->lazyById(200) as $record) {
$approvalTimes = ['measured' => 0, 'unknown' => 0, 'total_seconds' => 0, 'min_seconds' => null, 'max_seconds' => null];
foreach ((clone $query)->with('steps:id,requisition_id,decision,decided_at')->reorder()->lazyById(200) as $record) {
$total++;
if (in_array($record->status, ['draft', 'pending'], true) && $record->needed_by !== null && $record->needed_by->toDateString() < $today->toDateString()) {
$neededPast++;
@@ -43,6 +44,19 @@ class ProcurementOperationalInsights
}
if ($record->status === 'approved') {
$approved++;
$steps = $record->steps;
$valid = $record->submitted_at !== null && $steps->isNotEmpty() && $steps->every(fn ($step) => $step->decision === 'approved' && $step->decided_at !== null);
$dates = $valid ? $steps->map(fn ($step) => CarbonImmutable::parse($step->decided_at, config('app.timezone'))) : collect();
$end = $dates->max();
if (! $valid || $end === null || $end < $record->submitted_at || $end > $instant || $dates->contains(fn ($date) => $date < $record->submitted_at)) {
$approvalTimes['unknown']++;
} else {
$seconds = $end->getTimestamp() - $record->submitted_at->getTimestamp();
$approvalTimes['measured']++;
$approvalTimes['total_seconds'] += $seconds;
$approvalTimes['min_seconds'] = $approvalTimes['min_seconds'] === null ? $seconds : min($approvalTimes['min_seconds'], $seconds);
$approvalTimes['max_seconds'] = $approvalTimes['max_seconds'] === null ? $seconds : max($approvalTimes['max_seconds'], $seconds);
}
$withoutQuotes += (int) $record->getAttribute('quotations_count') === 0 ? 1 : 0;
$withoutOrder += $record->getAttribute('order_number') === null ? 1 : 0;
}
@@ -51,6 +65,7 @@ class ProcurementOperationalInsights
return ['method' => 'procurement_facts_v1', 'generated_at' => $instant->toIso8601String(), 'processes' => $total,
'pending' => ['count' => $pending, 'unknown_submission_age' => $missingSubmission, 'oldest' => $oldest],
'unapproved_past_needed_date' => $neededPast,
'approval_times' => $approvalTimes,
'approved' => ['count' => $approved, 'without_registered_quotes' => $withoutQuotes, 'without_visible_order' => $withoutOrder]];
}
}
+36
View File
@@ -102,6 +102,42 @@ class ProcurementReviewCsv
}
}
$fulfilment = $report['fulfilment'];
$limits = $report['agreement_limits'] ?? [];
if (! is_array($limits)) {
throw new \UnexpectedValueException('A projecção de acordos deve ser uma lista ou mapa de bases preservadas.');
}
$seen = [];
$seenContracts = [];
foreach ($limits as $binding) {
if (! is_array($binding) || ! isset($binding['agreement_id']) || ! is_int($binding['agreement_id']) || $binding['agreement_id'] < 1) {
throw new \UnexpectedValueException('Base contratual sem identidade válida.');
}
if (isset($seen[$binding['agreement_id']])) {
continue;
}
$seen[$binding['agreement_id']] = true;
if (isset($binding['contract']) && is_array($binding['contract'])) {
$contract = $binding['contract'];
if (! isset($contract['id']) || ! is_int($contract['id']) || $contract['id'] < 1) {
throw new \UnexpectedValueException('Contrato global sem identidade válida.');
}
if (! isset($seenContracts[$contract['id']])) {
$seenContracts[$contract['id']] = true;
$fields('Contrato global por ordem', (string) $contract['id'], [...$contract, 'max_order_value_minor' => $contract['max_order_value_minor'] ?? 'Não definido'], [
'record_key' => 'Identidade do contrato', 'reference' => 'Referência', 'version' => 'Versão preservada', 'currency' => 'Moeda',
'max_order_value_minor' => 'Limite global por ordem (centavos)', 'checked_order_value_minor' => 'Total conferido nesta ordem (centavos)',
]);
}
}
$fields('Acordo por ordem', (string) $binding['agreement_id'], [...$binding,
'basis' => 'Por ordem', 'max_order_value_minor' => $binding['max_order_value_minor'] ?? 'Não definido',
'max_order_quantity_milli' => $binding['max_order_quantity_milli'] ?? 'Não definido'], [
'record_key' => 'Identidade do acordo', 'version' => 'Versão preservada', 'reference' => 'Referência', 'basis' => 'Aplicação do limite',
'currency' => 'Moeda', 'unit' => 'Unidade contratual', 'includes_tax' => 'Inclui impostos',
'max_order_value_minor' => 'Limite por ordem (centavos)', 'max_order_quantity_milli' => 'Limite por ordem (milésimos)',
'checked_order_value_minor' => 'Total conferido nesta ordem (centavos)', 'checked_order_quantity_milli' => 'Quantidade conferida nesta ordem (milésimos)',
]);
}
$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']);
+1
View File
@@ -83,6 +83,7 @@ class ProcurementReviewReport
'opening' => $opening ? [...$opening->only(['id', 'revision', 'reference']), 'source_changed' => $opening->basis_hash !== $basis] : null,
'award' => $award?->only(['id', 'status', 'total_minor']),
'order' => $order?->only(['id', 'number', 'currency', 'total_minor']),
'agreement_limits' => $order?->snapshot['agreement_bindings'] ?? [],
'fulfilment' => [
'receipts' => $receipts, 'finance_visible' => $financeVisible,
'invoices' => $financeVisible ? $invoices->map(fn (Invoice $invoice) => ['id' => $invoice->id, 'number' => $invoice->number, 'status' => $invoice->status, 'issued_on' => $invoice->issued_on, 'total_minor' => (string) $invoice->total_minor, 'currency' => $invoice->snapshot['currency'] ?? null])->all() : null,
+5 -2
View File
@@ -112,9 +112,10 @@ class PurchaseWorkflow
});
}
public function issue(User $user, PurchaseAward $award): PurchaseOrder
/** @param list<array<string,mixed>> $agreementBindings */
public function issue(User $user, PurchaseAward $award, array $agreementBindings = []): PurchaseOrder
{
return DB::transaction(function () use ($user, $award) {
return DB::transaction(function () use ($user, $award, $agreementBindings) {
$this->guard->lockCompany($user);
$user = app(CurrentActor::class)->lock($user, [PurchasingRole::Procurement]);
abort_if(app(OrganizationAccess::class)->maintenanceOnly($user), 403);
@@ -125,6 +126,7 @@ class PurchaseWorkflow
$existing = PurchaseOrder::query()->where('requisition_id', $requisition->id)->first();
if ($existing) {
app(OrderCancellationWorkflow::class)->assertOperational($existing);
app(AgreementOrderLimits::class)->assertReplay($existing, $agreementBindings);
return $existing;
}
@@ -163,6 +165,7 @@ class PurchaseWorkflow
}
}
$snapshot = [
...app(AgreementOrderLimits::class)->freeze($user, $quote, $requisition, $lines, $agreementBindings),
...($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,
+15
View File
@@ -89,6 +89,21 @@ class ReceiptWorkflow
$supplyMappings = Schema::hasTable('supply_records')
? app(SupplyPlanning::class)->latest('delivery')->where('purchase_order_id', $order->id)->get() : collect();
foreach ($requested as $line) {
// Snapshot keys identify requisition lines; resolve the order-line identity explicitly.
$boundOrderLine = empty($order->snapshot['agreement_bindings']) ? null : $order->items()->whereKey($line['purchase_order_item_id'])->first();
$orderBinding = $boundOrderLine === null ? null : ($order->snapshot['agreement_bindings'][$boundOrderLine->requisition_item_id] ?? null);
if ($orderBinding !== null) {
if ((int) ($data['warehouse_id'] ?? 0) !== (int) $orderBinding['warehouse_id'] || (! empty($line['stock_item_id']) && (int) $line['stock_item_id'] !== (int) $orderBinding['stock_item_id'])) {
throw ValidationException::withMessages(['items' => 'Conserve o artigo e armazém do acordo preservado na ordem.']);
}
$line['stock_item_id'] = $orderBinding['stock_item_id'];
if (isset($orderBinding['conversion'])) {
if (isset($line['conversion']) && $line['conversion'] !== $orderBinding['conversion']) {
throw ValidationException::withMessages(['items' => 'Conserve a conversão preservada na ordem.']);
}
$line['conversion'] = $orderBinding['conversion'];
}
}
$mapping = $supplyMappings->first(fn ($record) => $record->data['purchase_order_item_id'] == $line['purchase_order_item_id']);
if ($mapping !== null) {
if ((! empty($line['stock_item_id']) && (int) $line['stock_item_id'] !== $mapping->stock_item_id) || (int) ($data['warehouse_id'] ?? 0) !== $mapping->warehouse_id) {
+86
View File
@@ -0,0 +1,86 @@
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
class RequisitionDraftInput
{
public function available(): bool
{
return Schema::hasColumn('requisitions', 'draft_input');
}
/** @return array<string,mixed> */
public function completeRules(User $user): array
{
return [
'operation_key' => 'nullable|uuid',
'process_version' => 'nullable|integer|min:1',
'cost_center_id' => ['required', 'integer', Rule::exists('cost_centers', 'id')->where('tenant_id', $user->tenant_id)->where('department_id', $user->department_id)],
'priority' => ['required', Rule::in(['normal', 'high', 'urgent'])],
'needed_by' => ['required', 'date_format:Y-m-d', 'after_or_equal:today'],
'justification' => ['required', 'string', 'min:10', 'max:5000'],
'items' => ['required', 'array', 'min:1', 'max:50'],
'items.*.catalogue_entry_id' => 'nullable|integer|min:1',
'items.*.catalogue_version' => 'nullable|required_with:items.*.catalogue_entry_id|integer|min:1',
'items.*.source_line_id' => 'nullable|integer|min:1',
'items.*.description' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:255'],
'items.*.category' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:100'],
'items.*.purchase_type' => ['required_without:items.*.catalogue_entry_id', Rule::in(['consumable', 'service', 'other', 'equipment', 'spare_part'])],
'items.*.equipment_id' => ['exclude_unless:items.*.purchase_type,spare_part', 'required', 'integer', Rule::exists('equipment', 'id')->where('tenant_id', $user->tenant_id)->where('department_id', $user->department_id)],
'items.*.spare_part_id' => ['exclude_unless:items.*.purchase_type,spare_part', 'required', 'integer', Rule::exists('spare_parts', 'id')->where('tenant_id', $user->tenant_id)],
'items.*.production_area' => 'exclude_unless:items.*.purchase_type,equipment|required|string|max:200',
'items.*.downtime_started_at' => 'exclude_unless:items.*.purchase_type,spare_part|nullable|date_format:Y-m-d\TH:i|before_or_equal:now',
'items.*.quantity' => ['required', 'numeric', 'min:0.001', 'max:1000000', 'regex:/^\d+(\.\d{1,3})?$/'],
'items.*.unit' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:30'],
'items.*.unit_price' => ['required', 'numeric', 'min:0.01', 'max:100000000', 'regex:/^\d+(\.\d{1,2})?$/'],
'items.*.tax_rate' => ['required', 'numeric', 'between:0,100', 'regex:/^\d+(\.\d{1,2})?$/'],
];
}
/** @return array<string,mixed> */
public function rules(User $user): array
{
$rules = $this->completeRules($user);
if (! $this->available()) {
return $rules;
}
foreach ($rules as $key => $list) {
$list = is_array($list) ? $list : explode('|', $list);
$rules[$key] = array_values(array_filter($list, fn ($rule) => ! is_string($rule) || (! str_starts_with($rule, 'required') && $rule !== 'after_or_equal:today' && ! ($key === 'justification' && $rule === 'min:10'))));
if (! in_array('nullable', $rules[$key], true)) {
$rules[$key][] = 'nullable';
}
}
$rules['items'] = ['present', 'array', 'max:50'];
return $rules;
}
/** @param array<string,mixed> $data */
public function complete(User $user, array $data): bool
{
return Validator::make($data, $this->completeRules($user))->passes();
}
/** @param array<string,mixed> $data
* @return array<string,mixed>
*/
public function preparation(User $user, array $data): array
{
$keys = [];
foreach (array_keys($this->completeRules($user)) as $key) {
if (str_starts_with($key, 'items.*.')) {
$keys[substr($key, 8)] = true;
}
}
$values = array_intersect_key($data, array_flip(['cost_center_id', 'priority', 'needed_by', 'justification', 'items']));
$values['items'] = array_map(fn (array $line) => array_intersect_key($line, $keys), $data['items']);
return $values;
}
}
+24 -1
View File
@@ -10,6 +10,7 @@ use App\Models\Tenant;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Tempo\Purchasing\Internal\InternalRequisitions;
use Tempo\Purchasing\Internal\RequisitionFailure;
@@ -64,7 +65,10 @@ class RequisitionWorkflow
} else {
abort_unless(app(OrganizationAccess::class)->canRequest($user), 403);
}
if (! $user->department_id || ! CostCenter::query()->whereKey($data['cost_center_id'])->where('department_id', $user->department_id)->exists()) {
$drafts = app(RequisitionDraftInput::class);
$data = Validator::make($data, $drafts->rules($user))->validate();
$incomplete = $drafts->available() && ! $drafts->complete($user, $data);
if (! $user->department_id || ((! $incomplete || ! empty($data['cost_center_id'])) && ! CostCenter::query()->whereKey($data['cost_center_id'] ?? null)->where('department_id', $user->department_id)->exists())) {
throw ValidationException::withMessages(['cost_center_id' => 'O departamento ou centro de custo mudou. Actualize o pedido antes de guardar.']);
}
$requisition = $existing ? Requisition::query()->lockForUpdate()->findOrFail($existing->id) : new Requisition;
@@ -73,6 +77,24 @@ class RequisitionWorkflow
app(ConflictGuard::class)->assertParticipation($user, $requisition);
}
$before = $existing ? $requisition->load('items')->toArray() : null;
if ($incomplete) {
$requisition->fill([
'tenant_id' => $user->tenant_id, 'requester_id' => $user->id, 'department_id' => $user->department_id,
'cost_center_id' => $data['cost_center_id'] ?? null, 'priority' => $data['priority'] ?? 'normal',
'needed_by' => $data['needed_by'] ?? null, 'justification' => $data['justification'] ?? null,
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null,
'draft_input' => ['incomplete' => true, 'values' => $drafts->preparation($user, $data)],
...($existing ? [] : ['comparison_policy' => app(ComparisonPolicy::class)->company(Tenant::query()->findOrFail($user->tenant_id))]),
...(Schema::hasColumn('requisitions', 'process_version') ? ['process_version' => $existing ? (int) $requisition->getAttribute('process_version') + 1 : 1] : []),
])->save();
if (! $existing) {
$requisition->update(['number' => sprintf('REQ-%s-%06d', now()->format('Y'), $requisition->id)]);
}
// Earlier complete lines remain for catalogue identity, never for approval or totals.
$this->audit($executor, $existing ? 'requisition.updated' : 'requisition.created', $requisition, $before, $requisition->fresh()->toArray());
return $requisition;
}
$items = [];
$subtotal = 0;
$tax = 0;
@@ -106,6 +128,7 @@ class RequisitionWorkflow
'cost_center_id' => $data['cost_center_id'], 'priority' => $data['priority'],
'needed_by' => $data['needed_by'], 'justification' => $data['justification'],
'subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax,
...($drafts->available() ? ['draft_input' => null] : []),
...($existing ? [] : ['comparison_policy' => app(ComparisonPolicy::class)->company(Tenant::query()->findOrFail($user->tenant_id))]),
...(Schema::hasColumn('requisitions', 'process_version') ? ['process_version' => $existing ? (int) $requisition->getAttribute('process_version') + 1 : 1] : []),
])->save();
+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'];
+2 -1
View File
@@ -162,7 +162,8 @@ class WarehouseFulfilment
'idempotency_key' => (string) Str::uuid(), 'responsible_id' => $r->created_by, 'warehouse_id' => $r->warehouse_id, 'stock_item_id' => $line['item']['id'],
'quantity' => intdiv($quantity, 1000).'.'.str_pad((string) ($quantity % 1000), 3, '0', STR_PAD_LEFT), 'destination' => $r->snapshot['destination'], 'reason' => 'Saída pela requisição RA-'.$r->id.': '.$data['reason'],
...($line['equipment'] === null ? [] : ['equipment_id' => $line['equipment']['id']])]);
$eventData['lines'][] = ['index' => $index, 'quantity_milli' => $quantity, 'stock_operation_id' => $operation->id];
$eventData['lines'][] = ['index' => $index, 'quantity_milli' => $quantity, 'stock_operation_id' => $operation->id,
...(isset($line['production']) ? ['production' => $line['production']] : [])];
}
$eventData['recipient'] = $r->snapshot['requester'];
}
+15 -2
View File
@@ -27,7 +27,16 @@ class WarehouseRequests
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'warehouse_id' => 'required|integer|min:1', 'cost_center_id' => 'required|integer|min:1',
'destination' => 'required|string|min:3|max:300', 'reason' => 'required|string|min:10|max:4000', 'priority' => 'required|in:normal,urgent',
'lines' => 'required|array|min:1|max:50', 'lines.*.stock_item_id' => 'required|integer|min:1', 'lines.*.quantity' => 'required|string|regex:/^[0-9]{1,6}(\.[0-9]{1,3})?$/D',
'lines.*.use' => 'required|in:internal,equipment', 'lines.*.equipment_id' => 'nullable|integer|min:1'])->validate();
'lines.*.use' => 'required|in:internal,equipment,production', 'lines.*.equipment_id' => 'nullable|integer|min:1',
'lines.*.production_reference' => 'nullable|string|max:120'])->validate();
foreach ($data['lines'] as &$inputLine) {
if ($inputLine['use'] !== 'production' && (($inputLine['production_reference'] ?? null) === null || $inputLine['production_reference'] === '')) {
unset($inputLine['production_reference']);
} elseif ($inputLine['use'] === 'production') {
$inputLine['production_reference'] ??= null;
}
}
unset($inputLine);
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
$old = WarehouseRequest::query()->where('created_by', $actor->id)->where('operation_key', $data['operation_key'])->first();
if ($old !== null) {
@@ -47,6 +56,9 @@ class WarehouseRequests
throw ValidationException::withMessages(['lines.'.$index.'.quantity' => 'A quantidade deve ser positiva.']);
}
$equipment = null;
if ($line['use'] !== 'production' && ($line['production_reference'] ?? null) !== null && $line['production_reference'] !== '') {
throw ValidationException::withMessages(['lines.'.$index.'.production_reference' => 'A referência de produção aplica-se apenas ao destino de produção.']);
}
if ($line['use'] === 'equipment') {
if (empty($line['equipment_id'])) {
throw ValidationException::withMessages(['lines.'.$index.'.equipment_id' => 'Seleccione o equipamento de destino.']);
@@ -60,7 +72,8 @@ class WarehouseRequests
throw ValidationException::withMessages(['lines.'.$index.'.equipment_id' => 'Escolha utilização em equipamento para associar este destino.']);
}
$lines[] = ['item' => $item->only(['id', 'code', 'name', 'unit']), 'quantity_milli' => $quantity, 'use' => $line['use'],
'destination' => $data['destination'], 'equipment' => $equipment?->only(['id', 'code', 'description'])];
'destination' => $data['destination'], 'equipment' => $equipment?->only(['id', 'code', 'description']),
...($line['use'] === 'production' ? ['production' => ['reference' => $line['production_reference'] ?? null, 'verification' => 'user_supplied']] : [])];
}
$record = WarehouseRequest::query()->create(['tenant_id' => $actor->tenant_id, 'created_by' => $actor->id, 'warehouse_id' => $warehouse->id,
'cost_center_id' => $center->id, 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'status' => 'draft', 'created_at' => now(),
+7 -4
View File
@@ -538,7 +538,10 @@ class WorkflowTaskInbox
return [];
}
$rows = [];
foreach (['agreement', 'policy', 'auto_rule', 'history', 'alternative'] as $kind) {
foreach (['contract', 'agreement', 'policy', 'auto_rule', 'history', 'alternative'] as $kind) {
if ($kind === 'contract' && ! app(AgreementOrderLimits::class)->ready()) {
continue;
}
$permission = match ($kind) {
'history' => 'supply_history_review', 'alternative' => 'supply_technical_review', default => 'supply_review'
};
@@ -556,13 +559,13 @@ class WorkflowTaskInbox
continue;
}
$rows[] = ['id' => 'supply:'.$record->id.':review', 'module' => 'supply',
'reference' => trim(($record->snapshot['item']['code'] ?? 'Fornecimento').' '.($record->snapshot['warehouse']['code'] ?? '')),
'reference' => $kind === 'contract' ? $record->data['reference'] : trim(($record->snapshot['item']['code'] ?? 'Fornecimento').' '.($record->snapshot['warehouse']['code'] ?? '')),
'label' => match ($kind) {
'agreement' => 'Conferir acordo de fornecimento', 'policy' => 'Conferir política de reposição', 'history' => 'Conferir histórico de consumo', 'alternative' => 'Conferir alternativa técnica', default => 'Conferir parametrização de compra automática',
'contract' => 'Conferir contrato multiartigo', 'agreement' => 'Conferir acordo de fornecimento', 'policy' => 'Conferir política de reposição', 'history' => 'Conferir histórico de consumo', 'alternative' => 'Conferir alternativa técnica', default => 'Conferir parametrização de compra automática',
}, 'task' => $kind.'_review', 'status' => $record->state, 'blocked' => false, 'created_at' => $this->date($record->created_at), 'due_on' => null,
'href' => $kind === 'auto_rule' ? '/stock/reposicao?rule_id='.$record->id.'#supply-rule-'.$record->id
: '/compras/fornecimento?view='.match ($kind) {
'agreement' => 'agreements', 'history' => 'history', 'alternative' => 'alternatives', default => 'calendar'
'contract' => 'contracts', 'agreement' => 'agreements', 'history' => 'history', 'alternative' => 'alternatives', default => 'calendar'
}.'&record_id='.$record->id.'#supply-record-'.$record->id];
}
}