@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\RequisitionItem;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Explicit documentary destination per line. Budget allocations retain their native authority. */
|
||||
final class CapitalAssignments
|
||||
{
|
||||
/** @return array{User,Requisition} */
|
||||
private function context(User $actor, Requisition $request): array
|
||||
{
|
||||
abort_unless(app(CapitalRegister::class)->ready(), 503);
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$request = Requisition::query()->visibleTo($actor)->lockForUpdate()->findOrFail($request->id);
|
||||
|
||||
return [$actor, $request];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, Requisition $request): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $request) {
|
||||
[$actor, $request] = $this->context($actor, $request);
|
||||
|
||||
return ['requisition' => $request->only(['id', 'number', 'status']), 'items' => $request->items()->orderBy('id')->get(['id', 'description']),
|
||||
'current' => app(SupplyPlanning::class)->latest('capital_assignment')->where('data->requisition_id', $request->id)->get(),
|
||||
'choices' => app(SupplyPlanning::class)->latest('capital_register')->where('state', 'active')->where('data->department_id', $request->department_id)
|
||||
->orderBy('data->code')->paginate(15, ['id', 'version', 'data'], 'choices_page')->withQueryString(),
|
||||
'history' => SupplyRecord::query()->where('kind', 'capital_assignment')->where('data->requisition_id', $request->id)
|
||||
->latest('id')->paginate(15, ['*'], 'history_page')->withQueryString(),
|
||||
'canWrite' => $request->status === 'draft' && $request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor)
|
||||
&& ! app(ConflictGuard::class)->participationBlocked($actor, $request),
|
||||
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, Requisition $request, array $input): SupplyRecord
|
||||
{
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0',
|
||||
'item_id' => 'required|integer|min:1', 'capital_id' => 'present|nullable|integer|min:1', 'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$hash = hash('sha256', json_encode([$request->id, $data], JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $request, $data, $hash) {
|
||||
[$actor, $request] = $this->context($actor, $request);
|
||||
abort_unless($request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor), 403);
|
||||
app(ConflictGuard::class)->assertParticipation($actor, $request);
|
||||
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($retry !== null) {
|
||||
abort_unless($retry->kind === 'capital_assignment' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||
|
||||
return $retry;
|
||||
}
|
||||
abort_unless($request->status === 'draft', 403);
|
||||
$item = $request->items()->whereKey($data['item_id'])->firstOrFail();
|
||||
$old = app(SupplyPlanning::class)->latest('capital_assignment')->where('data->requisition_item_id', $item->id)->first();
|
||||
abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'A ligação mudou. Reveja a versão actual.');
|
||||
$source = $data['capital_id'] === null ? null : app(SupplyPlanning::class)->latest('capital_register')->where('state', 'active')
|
||||
->where('data->department_id', $request->department_id)->whereKey($data['capital_id'])->firstOrFail();
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'capital_assignment',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
||||
'state' => $source === null ? 'cleared' : 'linked', 'created_by' => $actor->id,
|
||||
'data' => ['requisition_id' => $request->id, 'requisition_item_id' => $item->id, 'capital_id' => $source?->id],
|
||||
'snapshot' => ['item' => $this->item($item), 'source' => $source?->only(['id', 'record_key', 'version', 'state', 'data', 'snapshot']), 'financial_effects' => false],
|
||||
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'capital.assignment_recorded', $request, $old?->toArray(), ['record' => $record->toArray()]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function item(RequisitionItem $item): array
|
||||
{
|
||||
return $item->only(['id', 'description', 'unit', 'quantity', 'purchase_type', 'equipment_id', 'category_context']);
|
||||
}
|
||||
|
||||
/** Preserve accepted choices even after a later rename/archive. New choices require a current active source.
|
||||
* @param list<int> $itemIds
|
||||
* @return array<int,array<string,mixed>>
|
||||
*/
|
||||
public function freezeForItems(User $actor, array $itemIds): array
|
||||
{
|
||||
abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
|
||||
if (! Schema::hasTable('supply_records')) {
|
||||
return [];
|
||||
}
|
||||
$records = app(SupplyPlanning::class)->latest('capital_assignment')->whereIn('data->requisition_item_id', $itemIds)->where('state', 'linked')->get();
|
||||
if ($records->isEmpty()) {
|
||||
return [];
|
||||
}
|
||||
abort_unless(app(CapitalRegister::class)->ready(), 503, 'Preserve a capacidade das ligações a projectos e imobilizado antes de emitir a ordem.');
|
||||
$result = [];
|
||||
foreach ($records as $record) {
|
||||
$item = RequisitionItem::query()->whereKey($record->data['requisition_item_id'])->firstOrFail();
|
||||
Requisition::query()->visibleTo($actor)->whereKey($item->requisition_id)->firstOrFail();
|
||||
abort_unless($record->snapshot['item'] === $this->item($item), 409, 'O artigo mudou. Reveja a ligação ao projecto ou imobilizado.');
|
||||
$result[$item->id] = $record->only(['id', 'version', 'data', 'snapshot', 'reason']);
|
||||
}
|
||||
ksort($result, SORT_NUMERIC);
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Department;
|
||||
use App\Models\Equipment;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Compras-owned documentary register; never creates an accounting asset or SGF dependency. */
|
||||
final class CapitalRegister
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
$db = DB::connection();
|
||||
|
||||
return config('capital-register.qa_enabled') === true && app()->environment('testing')
|
||||
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
||||
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
|
||||
&& preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())));
|
||||
}
|
||||
|
||||
private function actor(User $actor, bool $write = false): User
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
// Reuse the native equipment register's capabilities and departmental scope.
|
||||
abort_unless($actor->hasFunctions($write ? ['admin', 'warehouse', 'procurement']
|
||||
: ['admin', 'warehouse', 'procurement', 'finance', 'department_head']), 403);
|
||||
|
||||
return $actor;
|
||||
}
|
||||
|
||||
/** @return Builder<SupplyRecord> */
|
||||
private function visible(User $actor): Builder
|
||||
{
|
||||
return app(SupplyPlanning::class)->latest('capital_register')
|
||||
->when($actor->departmentScoped(), fn ($q) => $q->where('data->department_id', $actor->department_id));
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, ?string $historyKey = null): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $historyKey) {
|
||||
$actor = $this->actor($actor);
|
||||
if ($historyKey !== null) {
|
||||
$this->visible($actor)->where('record_key', $historyKey)->firstOrFail();
|
||||
}
|
||||
$departments = Department::query()->when($actor->departmentScoped(), fn ($q) => $q->whereKey($actor->department_id));
|
||||
$equipment = Equipment::query()->when($actor->departmentScoped(), fn ($q) => $q->where('department_id', $actor->department_id));
|
||||
|
||||
return ['records' => $this->visible($actor)->orderBy('data->code')->paginate(15)->withQueryString(),
|
||||
'history' => $historyKey === null ? null : SupplyRecord::query()->where('kind', 'capital_register')->where('record_key', $historyKey)
|
||||
->orderByDesc('version')->paginate(15, ['*'], 'history_page')->withQueryString(),
|
||||
'trace' => $historyKey === null ? null : app(CapitalTrace::class)->workspace($actor, $historyKey),
|
||||
'departments' => $departments->orderBy('name')->get(['id', 'name']),
|
||||
'equipment' => $equipment->orderBy('code')->get(['id', 'code', 'description', 'department_id']),
|
||||
'canManage' => $actor->hasFunctions(['admin', 'warehouse', 'procurement']),
|
||||
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, array $input): SupplyRecord
|
||||
{
|
||||
$input = array_map(fn ($v) => is_string($v) ? trim($v) : $v, $input);
|
||||
$input['code'] = is_string($input['code'] ?? null) ? Str::upper($input['code']) : ($input['code'] ?? null);
|
||||
$data = Validator::make(['record_key' => null, 'equipment_id' => null, ...$input], [
|
||||
'operation_key' => 'required|uuid', 'record_key' => 'present|nullable|uuid', 'version' => 'required|integer|min:0',
|
||||
'type' => 'required|in:project,asset', 'code' => ['required', 'string', 'regex:/^[A-Z0-9][A-Z0-9._-]{0,39}$/D'],
|
||||
'name' => 'required|string|min:3|max:200', 'department_id' => 'required|integer|min:1',
|
||||
'equipment_id' => 'nullable|integer|min:1', 'reference' => 'required|string|min:3|max:1000',
|
||||
'state' => 'required|in:active,archived', 'reason' => 'required|string|min:10|max:4000',
|
||||
])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $data, $hash) {
|
||||
$actor = $this->actor($actor, true);
|
||||
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($retry !== null) {
|
||||
abort_unless($retry->kind === 'capital_register' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||
|
||||
return $retry;
|
||||
}
|
||||
$old = $data['record_key'] === null ? null : $this->visible($actor)->where('record_key', $data['record_key'])->firstOrFail();
|
||||
abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'O cadastro mudou. Reveja a versão actual.');
|
||||
$department = Department::query()->when($actor->departmentScoped(), fn ($q) => $q->whereKey($actor->department_id))->whereKey($data['department_id'])->firstOrFail();
|
||||
if ($old !== null && ($old->data['type'] !== $data['type'] || $old->data['code'] !== $data['code'])) {
|
||||
throw ValidationException::withMessages(['code' => 'Preserve o tipo e o código da identidade já registada.']);
|
||||
}
|
||||
if ($old === null && SupplyRecord::query()->where('kind', 'capital_register')->where('data->type', $data['type'])->where('data->code', $data['code'])->exists()) {
|
||||
throw ValidationException::withMessages(['code' => 'Este código já existe, incluindo no histórico arquivado.']);
|
||||
}
|
||||
$equipment = null;
|
||||
if ($data['equipment_id'] !== null) {
|
||||
abort_unless($data['type'] === 'asset', 422);
|
||||
$equipment = Equipment::query()->where('department_id', $department->id)->whereKey($data['equipment_id'])->firstOrFail();
|
||||
if (SupplyRecord::query()->where('kind', 'capital_register')->where('data->equipment_id', $equipment->id)
|
||||
->when($old !== null, fn ($q) => $q->where('record_key', '!=', $old->record_key))->exists()) {
|
||||
throw ValidationException::withMessages(['equipment_id' => 'Este equipamento já está identificado noutra referência de imobilizado.']);
|
||||
}
|
||||
if ($old !== null && ($old->data['equipment_id'] ?? null) !== null && (int) $data['equipment_id'] !== $old->data['equipment_id']) {
|
||||
throw ValidationException::withMessages(['equipment_id' => 'Preserve a ligação ao equipamento já identificado.']);
|
||||
}
|
||||
} elseif (($old?->data['equipment_id'] ?? null) !== null) {
|
||||
throw ValidationException::withMessages(['equipment_id' => 'Preserve a ligação ao equipamento já identificado.']);
|
||||
}
|
||||
$canonical = ['type' => $data['type'], 'code' => $data['code'], 'name' => $data['name'], 'department_id' => $department->id,
|
||||
'equipment_id' => $equipment?->id, 'reference' => $data['reference']];
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'capital_register',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
||||
'state' => $data['state'], 'created_by' => $actor->id, 'data' => $canonical,
|
||||
'snapshot' => ['department' => $department->only(['id', 'name']), 'equipment' => $equipment?->only(['id', 'code', 'description', 'version']),
|
||||
'accounting_effects' => false, 'source_system' => 'compras'],
|
||||
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'capital.register_recorded', null, $old?->toArray(), ['record' => $record->toArray()]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\GoodsReceipt;
|
||||
use App\Models\GoodsReceiptItem;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Read the actual issued snapshot, never infer an asset origin from a current draft assignment. */
|
||||
final class CapitalTrace
|
||||
{
|
||||
private function lines(User $actor, string $key): Builder
|
||||
{
|
||||
$query = DB::table('purchase_order_items as line')->join('purchase_orders as document', 'document.id', '=', 'line.purchase_order_id')
|
||||
->where('line.tenant_id', $actor->tenant_id)->where('document.tenant_id', $actor->tenant_id)
|
||||
->whereIn('document.id', PurchaseOrder::query()->visibleTo($actor)->select('id'));
|
||||
if (DB::getDriverName() === 'pgsql') {
|
||||
$query->whereRaw("document.snapshot::jsonb -> 'capital_assignments' -> line.requisition_item_id::text -> 'snapshot' -> 'source' ->> 'record_key' = ?", [$key]);
|
||||
} elseif (DB::getDriverName() === 'sqlite') {
|
||||
$query->whereRaw("json_extract(document.snapshot, '$.capital_assignments.' || line.requisition_item_id || '.snapshot.source.record_key') = ?", [$key]);
|
||||
} else {
|
||||
abort(503, 'A consulta de origens requer um motor verificado.');
|
||||
}
|
||||
return $query;
|
||||
}
|
||||
|
||||
/** The caller has already checked the current register identity's visibility.
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function workspace(User $actor, string $key): array
|
||||
{
|
||||
abort_unless(app(CapitalRegister::class)->ready() && auth()->id() === $actor->id && DB::transactionLevel() > 0, 403);
|
||||
$lines = $this->lines($actor, $key);
|
||||
$orders = (clone $lines)->orderBy('line.id')->paginate(15,
|
||||
['line.id', 'line.description', 'line.quantity', 'line.unit', 'document.id as order_id', 'document.number as order_number'], 'origins_page')->withQueryString();
|
||||
$receipts = GoodsReceiptItem::query()->whereIn('purchase_order_item_id', (clone $lines)->select('line.id'))
|
||||
->orderBy('id')->paginate(15, ['id', 'goods_receipt_id', 'purchase_order_item_id', 'snapshot', 'accepted_milli', 'quality_status'], 'receipts_page')->withQueryString();
|
||||
$documents = GoodsReceipt::query()->whereIn('id', $receipts->getCollection()->pluck('goods_receipt_id'))->get()->keyBy('id');
|
||||
$receipts->through(function (GoodsReceiptItem $item) use ($documents) {
|
||||
$document = $documents->get($item->goods_receipt_id);
|
||||
return ['id' => $item->id, 'description' => $item->snapshot['order_item']['description'] ?? null, 'unit' => $item->snapshot['order_item']['unit'] ?? null,
|
||||
'receipt_id' => $item->goods_receipt_id, 'order_id' => $document?->purchase_order_id,
|
||||
'received_on' => $document?->received_on->toDateString(), 'quality_status' => $item->quality_status,
|
||||
'accepted_quantity' => (string) BigDecimal::of($item->accepted_milli)->dividedBy(1000, 3),
|
||||
'reversed' => app(InventoryReversals::class)->receiptReversed($item->id),
|
||||
'returned_quantity' => (string) BigDecimal::of(app(InventoryDispositions::class)->returnedForReceipt($item->id))->dividedBy(1000, 3)];
|
||||
});
|
||||
return ['orders' => $orders, 'receipts' => $receipts];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
/** Documentary bank follow-up only: no transfer, JUE submission or legal deadline activation. */
|
||||
final class ImportBankSupport
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
return config('import-bank-support.qa_enabled') === true && app(ImportDossier::class)->ready();
|
||||
}
|
||||
|
||||
public function assertReadable(User $actor, SupplyRecord $import): void
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
DB::transaction(fn () => app(ImportDossier::class)->context($actor, $import));
|
||||
}
|
||||
|
||||
/** @param \Closure(SupplyRecord,list<string>):void $consume */
|
||||
public function report(User $actor, SupplyRecord $import, \Closure $consume): void
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
DB::transaction(function () use ($actor, $import, $consume) {
|
||||
[, $current, $order] = app(ImportDossier::class)->context($actor, $import);
|
||||
$records = app(SupplyPlanning::class)->latest('import_bank_support')->where('purchase_order_id', $order->id)->where('snapshot->import_key', $current->record_key);
|
||||
foreach ($records->lazyById(100) as $record) {
|
||||
$consume($record, $this->issues($record));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, SupplyRecord $import): array
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
|
||||
return DB::transaction(function () use ($actor, $import) {
|
||||
[$actor, $current, $order] = app(ImportDossier::class)->context($actor, $import);
|
||||
$base = SupplyRecord::query()->where('kind', 'import_bank_support')->where('purchase_order_id', $order->id)->where('snapshot->import_key', $current->record_key);
|
||||
$latest = (clone $base)->whereIn('id', app(SupplyPlanning::class)->latest('import_bank_support')->select('id'))->latest('id')
|
||||
->paginate(10, ['*'], 'bank_current_page')->withQueryString();
|
||||
$latest->through(fn ($record) => [...$record->toArray(), 'issues' => $this->issues($record)]);
|
||||
|
||||
return ['importRecord' => $current->only(['id', 'record_key', 'version']), 'order' => $order->only(['id', 'number']),
|
||||
'current' => $latest, 'history' => (clone $base)->latest('id')->paginate(10, ['id', 'record_key', 'version', 'state', 'data', 'snapshot', 'reason', 'created_at'], 'bank_history_page')->withQueryString(),
|
||||
'documents' => app(SupplyPlanning::class)->latest('import_document')->where('purchase_order_id', $order->id)->where('snapshot->import_key', $current->record_key)
|
||||
->latest('id')->paginate(20, ['id', 'record_key', 'version', 'data'], 'bank_documents_page')->withQueryString(),
|
||||
'types' => ImportDossier::TYPES, 'canWrite' => $actor->hasFunctions(['import_prepare']),
|
||||
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id, 'today' => today()->toDateString()];
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, SupplyRecord $import, array $input): SupplyRecord
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
foreach (['requirements_basis', 'deadline_basis', 'submission_basis', 'reason'] as $field) {
|
||||
if (isset($input[$field]) && is_string($input[$field])) {
|
||||
$input[$field] = trim($input[$field]);
|
||||
}
|
||||
}
|
||||
$types = array_diff(array_keys(ImportDossier::TYPES), ['bank_commitment']);
|
||||
$data = Validator::make(['record_key' => null, ...$input], [
|
||||
'operation_key' => 'required|uuid', 'record_key' => 'present|nullable|uuid', 'version' => 'required|integer|min:0',
|
||||
'commitment_document_id' => 'required|integer|min:1', 'declaration_document_id' => 'present|nullable|integer|min:1',
|
||||
'submission_document_id' => 'present|nullable|integer|min:1', 'submission_basis' => 'present|nullable|string|min:3|max:1000',
|
||||
'submitted_on' => 'present|nullable|date_format:Y-m-d|before_or_equal:today',
|
||||
'support_document_ids' => 'present|array|list|max:100', 'support_document_ids.*' => 'required|integer|min:1|distinct',
|
||||
'requirements_known' => 'required|boolean', 'required_support_types' => 'present|array|list|max:14',
|
||||
'required_support_types.*' => ['required', 'distinct', Rule::in($types)], 'requirements_basis' => 'required|string|min:3|max:1000',
|
||||
'required_support_counts' => 'present|array|max:14', 'required_support_counts.*' => 'required|integer|min:1|max:100',
|
||||
'due_on' => 'present|nullable|date_format:Y-m-d', 'deadline_basis' => 'present|nullable|string|min:3|max:1000',
|
||||
'reason' => 'required|string|min:10|max:4000',
|
||||
])->validate();
|
||||
$data['version'] = (int) $data['version'];
|
||||
$data['commitment_document_id'] = (int) $data['commitment_document_id'];
|
||||
$data['declaration_document_id'] = $data['declaration_document_id'] === null ? null : (int) $data['declaration_document_id'];
|
||||
$data['submission_document_id'] = $data['submission_document_id'] === null ? null : (int) $data['submission_document_id'];
|
||||
$data['support_document_ids'] = array_map('intval', $data['support_document_ids']);
|
||||
$data['requirements_known'] = (bool) $data['requirements_known'];
|
||||
sort($data['support_document_ids'], SORT_NUMERIC);
|
||||
sort($data['required_support_types'], SORT_STRING);
|
||||
$data['required_support_counts'] = array_map('intval', $data['required_support_counts']);
|
||||
ksort($data['required_support_counts']);
|
||||
abort_unless(array_keys($data['required_support_counts']) === $data['required_support_types'] && array_sum($data['required_support_counts']) <= 100, 422,
|
||||
'Indique a quantidade explícita de cada tipo de documento solicitado pelo banco.');
|
||||
abort_unless($data['requirements_known'] || $data['required_support_types'] === [], 422, 'Requisitos desconhecidos não podem ser apresentados como uma lista confirmada.');
|
||||
abort_if($data['due_on'] !== null && (! is_string($data['deadline_basis']) || mb_strlen($data['deadline_basis']) < 3), 422, 'Indique a fonte do prazo documental, sem aplicar um prazo genérico.');
|
||||
abort_if($data['submission_document_id'] !== null && (! is_string($data['submission_basis']) || mb_strlen($data['submission_basis']) < 3), 422, 'Identifique o fundamento do comprovativo de entrega documental.');
|
||||
abort_unless(($data['submission_document_id'] === null) === ($data['submitted_on'] === null), 422,
|
||||
'Associe o comprovativo e a data efectiva da entrega documental; não presuma a data pelo carregamento do ficheiro.');
|
||||
$hash = hash('sha256', json_encode([$import->record_key, $data], JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $import, $data, $hash) {
|
||||
[$actor, $current, $order] = app(ImportDossier::class)->context($actor, $import, true);
|
||||
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($retry !== null) {
|
||||
abort_unless($retry->kind === 'import_bank_support' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||
|
||||
return $retry;
|
||||
}
|
||||
$old = $data['record_key'] === null ? null : SupplyRecord::query()->where('kind', 'import_bank_support')->where('record_key', $data['record_key'])->latest('version')->firstOrFail();
|
||||
abort_unless($data['version'] === ($old->version ?? 0), 409, 'O acompanhamento bancário mudou. Consulte a versão actual.');
|
||||
if ($old !== null) {
|
||||
abort_unless($old->purchase_order_id === $order->id && $old->snapshot['import_key'] === $current->record_key, 404);
|
||||
}
|
||||
$documents = [];
|
||||
$commitment = $this->document($current, $data['commitment_document_id']);
|
||||
abort_unless($commitment->data['type'] === 'bank_commitment', 422, 'Seleccione um termo de compromisso tipificado.');
|
||||
$documents[$commitment->id] = $this->freeze($commitment);
|
||||
if ($data['declaration_document_id'] !== null) {
|
||||
$declaration = $this->document($current, $data['declaration_document_id']);
|
||||
abort_unless($declaration->data['type'] === 'customs_declaration', 422, 'Seleccione o documento único ou a declaração aduaneira.');
|
||||
$documents[$declaration->id] = $this->freeze($declaration);
|
||||
}
|
||||
foreach ($data['support_document_ids'] as $id) {
|
||||
$document = $this->document($current, $id);
|
||||
abort_unless($document->data['type'] !== 'bank_commitment', 422);
|
||||
$documents[$document->id] = $this->freeze($document);
|
||||
}
|
||||
if ($data['submission_document_id'] !== null) {
|
||||
$submission = $this->document($current, $data['submission_document_id']);
|
||||
abort_unless($submission->data['type'] === 'bank_support', 422, 'Seleccione o comprovativo documental de entrega ao banco.');
|
||||
$documents[$submission->id] = $this->freeze($submission);
|
||||
}
|
||||
if ($old === null) {
|
||||
abort_if(app(SupplyPlanning::class)->latest('import_bank_support')->where('purchase_order_id', $order->id)
|
||||
->where('data->commitment_key', $commitment->record_key)->exists(), 409, 'O termo já tem acompanhamento. Versione o registo existente.');
|
||||
} else {
|
||||
abort_unless($old->data['commitment_key'] === $commitment->record_key, 409, 'Uma correcção conserva a identidade do termo de compromisso.');
|
||||
}
|
||||
$payload = array_diff_key($data, array_flip(['operation_key', 'record_key', 'version', 'reason']));
|
||||
$payload['commitment_key'] = $commitment->record_key;
|
||||
$snapshot = ['import_key' => $current->record_key, 'documents' => array_values($documents), 'supersedes' => $old?->id,
|
||||
'bank_transfer_executed' => false, 'jue_submission_executed' => false, 'bank_compliance_certified' => false];
|
||||
$complete = $data['requirements_known'] && $data['declaration_document_id'] !== null
|
||||
&& $this->missingRequirements($data, array_values($documents)) === [];
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_bank_support',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
||||
'state' => $complete ? ($data['submission_document_id'] !== null ? 'documented' : 'ready') : 'tracking', 'purchase_order_id' => $order->id, 'created_by' => $actor->id,
|
||||
'data' => $payload, 'snapshot' => $snapshot, 'reason' => $data['reason'], 'operation_key' => $data['operation_key'],
|
||||
'input_hash' => $hash, 'created_at' => now()]);
|
||||
foreach (app(OrderPartsAccess::class)->origins($order) as $id) {
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'import.bank_support_recorded', Requisition::query()->whereKey($id)->firstOrFail(), null,
|
||||
['record_id' => $record->id, 'version' => $record->version, 'state' => $record->state, 'bank_transfer_executed' => false, 'jue_submission_executed' => false]);
|
||||
}
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
private function document(SupplyRecord $import, int $id): SupplyRecord
|
||||
{
|
||||
$document = SupplyRecord::query()->where('kind', 'import_document')->where('purchase_order_id', $import->purchase_order_id)
|
||||
->where('snapshot->import_key', $import->record_key)->findOrFail($id);
|
||||
abort_unless(SupplyRecord::query()->where('kind', 'import_document')->where('record_key', $document->record_key)->latest('version')->value('id') === $document->id, 409,
|
||||
'Seleccione a versão actual do documento, conservando o original anterior.');
|
||||
app(ImportEvidence::class)->bytes($document);
|
||||
|
||||
return $document;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function freeze(SupplyRecord $document): array
|
||||
{
|
||||
return ['id' => $document->id, 'record_key' => $document->record_key, 'version' => $document->version,
|
||||
'type' => $document->data['type'], 'reference' => $document->data['reference'], 'issuer_reference' => $document->data['issuer_reference'],
|
||||
'sha256' => $document->snapshot['evidence']['sha256']];
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function issues(SupplyRecord $record): array
|
||||
{
|
||||
$issues = [];
|
||||
if (! $record->data['requirements_known']) {
|
||||
$issues[] = 'Requisitos de suporte ainda desconhecidos.';
|
||||
}
|
||||
if ($record->data['declaration_document_id'] === null) {
|
||||
$issues[] = 'Falta associar o documento único ou a declaração aduaneira.';
|
||||
}
|
||||
if ($record->data['submission_document_id'] === null) {
|
||||
$issues[] = 'Falta associar o comprovativo de entrega documental ao banco; reunir documentos não demonstra a entrega.';
|
||||
}
|
||||
$issues = [...$issues, ...$this->missingRequirements($record->data, $record->snapshot['documents'])];
|
||||
$import = SupplyRecord::query()->where('kind', 'import')->where('record_key', $record->snapshot['import_key'])->latest('version')->firstOrFail();
|
||||
foreach ($record->snapshot['documents'] as $frozen) {
|
||||
try {
|
||||
$document = $this->document($import, $frozen['id']);
|
||||
if ($this->freeze($document) !== $frozen) {
|
||||
$issues[] = 'O original '.$frozen['reference'].' divergiu da versão preservada.';
|
||||
}
|
||||
} catch (HttpExceptionInterface|ModelNotFoundException $error) {
|
||||
$issues[] = 'O original '.$frozen['reference'].' está em falta, alterado ou foi corrigido; reveja a associação.';
|
||||
}
|
||||
}
|
||||
$pending = $issues !== [];
|
||||
if ($record->data['due_on'] === null) {
|
||||
$issues[] = 'Prazo documental ainda por indicar; não foi presumido um prazo legal.';
|
||||
} else {
|
||||
if ($record->data['submitted_on'] !== null && $record->data['submitted_on'] > $record->data['due_on']) {
|
||||
$issues[] = 'Entrega documentada após o prazo indicado.';
|
||||
}
|
||||
if ($pending && $record->data['due_on'] < today()->toDateString()) {
|
||||
$issues[] = 'Prazo documental ultrapassado.';
|
||||
} elseif ($pending && $record->data['due_on'] === today()->toDateString()) {
|
||||
$issues[] = 'O prazo documental termina hoje.';
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($issues));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data
|
||||
* @param list<array<string,mixed>> $documents
|
||||
* @return list<string>
|
||||
*/
|
||||
private function missingRequirements(array $data, array $documents): array
|
||||
{
|
||||
$support = array_filter($documents, fn ($document) => in_array($document['id'], $data['support_document_ids'], true)
|
||||
|| $document['id'] === $data['declaration_document_id']);
|
||||
$counts = array_count_values(array_column($support, 'type'));
|
||||
$issues = [];
|
||||
foreach ($data['required_support_counts'] as $type => $required) {
|
||||
$missing = $required - ($counts[$type] ?? 0);
|
||||
if ($missing > 0) {
|
||||
$issues[] = 'Documento em falta: '.ImportDossier::TYPES[$type].' ('.$missing.').';
|
||||
}
|
||||
}
|
||||
|
||||
return $issues;
|
||||
}
|
||||
}
|
||||
@@ -25,22 +25,24 @@ final class ImportCostDocumentHealth
|
||||
'documents_checked' => 0, 'files_checked' => 0, 'missing' => 0, 'altered' => 0,
|
||||
'invalid_reference' => 0, 'unreferenced' => 0, 'reasons' => []];
|
||||
$disk = Storage::disk('local');
|
||||
$records = DB::table('supply_records')->whereIn('kind', ['import_cost_doc', 'import_document'])->orderBy('id')->limit($limit + 1)->get();
|
||||
$records = DB::table('supply_records')->whereIn('kind', ['import_cost_doc', 'import_document', 'import_legal_source'])->orderBy('id')->limit($limit + 1)->get();
|
||||
$limited = $records->count() > $limit;
|
||||
$root = realpath($disk->path(''));
|
||||
foreach ($records->take($limit) as $record) {
|
||||
$result['documents_checked']++;
|
||||
$snapshot = json_decode($record->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||
$evidence = $snapshot['evidence'] ?? [];
|
||||
$directory = $record->kind === 'import_cost_doc' ? 'import-costs' : 'import-dossier';
|
||||
$prefix = $directory.'/'.$record->tenant_id.'/'.$record->purchase_order_id.'/';
|
||||
$directory = match ($record->kind) {
|
||||
'import_cost_doc' => 'import-costs', 'import_legal_source' => 'import-legal', default => 'import-dossier'
|
||||
};
|
||||
$prefix = $directory.'/'.$record->tenant_id.'/'.($record->kind === 'import_legal_source' ? '' : $record->purchase_order_id.'/');
|
||||
$path = $evidence['path'] ?? null;
|
||||
if (($evidence['disk'] ?? null) !== 'local' || ! is_string($path)
|
||||
|| ! preg_match('/^[a-f0-9-]{36}$/D', $record->record_key)
|
||||
|| ! preg_match('/^'.preg_quote($prefix.$record->record_key.'-'.$record->version, '/').'\.(pdf|jpg|jpeg|png)$/D', $path)
|
||||
|| ! is_int($evidence['size'] ?? null) || $evidence['size'] < 1 || $evidence['size'] > 2097152
|
||||
|| ! is_int($evidence['size'] ?? null) || $evidence['size'] < 1 || $evidence['size'] > ($record->kind === 'import_legal_source' ? 67108864 : 2097152)
|
||||
|| ! is_string($evidence['sha256'] ?? null) || ! preg_match('/^[a-f0-9]{64}$/D', $evidence['sha256'])
|
||||
|| ! DB::table('purchase_orders')->where('tenant_id', $record->tenant_id)->where('id', $record->purchase_order_id)->exists()) {
|
||||
|| ($record->kind !== 'import_legal_source' && ! DB::table('purchase_orders')->where('tenant_id', $record->tenant_id)->where('id', $record->purchase_order_id)->exists())) {
|
||||
$result['invalid_reference']++;
|
||||
|
||||
continue;
|
||||
@@ -69,7 +71,7 @@ final class ImportCostDocumentHealth
|
||||
$result['altered']++;
|
||||
}
|
||||
}
|
||||
foreach (['import-costs' => 'import_cost_doc', 'import-dossier' => 'import_document'] as $directory => $kind) {
|
||||
foreach (['import-costs' => 'import_cost_doc', 'import-dossier' => 'import_document', 'import-legal' => 'import_legal_source'] as $directory => $kind) {
|
||||
foreach ($disk->getDriver()->listContents($directory, true) as $entry) {
|
||||
if (! $entry->isFile()) {
|
||||
continue;
|
||||
|
||||
@@ -48,6 +48,7 @@ final class ImportEstimates
|
||||
$latest = $this->current($request);
|
||||
|
||||
return ['requisition' => $request->only(['id', 'number', 'status', 'subtotal_minor', 'tax_minor', 'total_minor']),
|
||||
'legalAmounts' => app(ImportLegalRules::class)->ready() ? app(SupplyPlanning::class)->latest('import_legal_amount')->where('data->requisition_id', $request->id)->get() : [],
|
||||
'latest' => $latest, 'nativeChanged' => $latest !== null && $latest->snapshot['native'] !== $this->native($request),
|
||||
'history' => SupplyRecord::query()->where('kind', 'import_estimate')->where('data->requisition_id', $request->id)
|
||||
->latest('version')->paginate(10, ['id', 'version', 'state', 'reason', 'data', 'snapshot', 'created_at'], 'estimate_page')->withQueryString(),
|
||||
@@ -74,6 +75,9 @@ final class ImportEstimates
|
||||
abort_unless($this->ready(), 503, 'Preserve a capacidade de estimativa de importação antes de submeter.');
|
||||
abort_unless($record->snapshot['native'] === $this->native($request), 409, 'A requisição mudou. Reveja e versione a estimativa antes de submeter.');
|
||||
abort_unless($record->snapshot['plan']['complete'] === true, 422, 'Existem custos de importação desconhecidos. Complete os pressupostos antes da aprovação e reserva.');
|
||||
foreach ($record->snapshot['legal_sources'] ?? [] as $source) {
|
||||
app(ImportLegalEstimates::class)->forPlan($request, $source['estimate_id']);
|
||||
}
|
||||
$budget = Budget::query()->whereKey($record->data['budget_id'])->firstOrFail();
|
||||
abort_unless($budget->approved_by !== null && $budget->only(['id', 'cost_center_id', 'year', 'kind', 'includes_tax']) === $record->snapshot['budget'], 409,
|
||||
'O orçamento da estimativa mudou. Reveja a preparação.');
|
||||
@@ -199,6 +203,8 @@ final class ImportEstimates
|
||||
abort_unless($this->ready(), 503);
|
||||
$data = Validator::make($input, [
|
||||
'operation_key' => 'required|uuid', 'version' => 'required|integer|min:0', 'budget_id' => 'required|integer|min:1',
|
||||
'legal_sources' => 'sometimes|array|max:100', 'legal_sources.*' => 'required|array:estimate_id,charge_key',
|
||||
'legal_sources.*.estimate_id' => 'required|integer|min:1', 'legal_sources.*.charge_key' => 'required|string|max:100',
|
||||
'components' => 'required|array|list|min:6|max:100', 'components.*' => 'required|array:key,kind,status,basis,subtotal_minor,tax_minor,total_minor',
|
||||
'components.*.key' => 'required|string|max:100', 'components.*.kind' => 'required|string',
|
||||
'components.*.status' => 'required|in:known,unknown,not_applicable', 'components.*.basis' => 'required|string|min:3|max:4000',
|
||||
@@ -237,12 +243,32 @@ final class ImportEstimates
|
||||
->where('kind', $request->items()->where('purchase_type', 'equipment')->exists() ? 'investment' : 'operating')
|
||||
->where('year', now()->year)->whereNotNull('approved_by')->firstOrFail();
|
||||
$native = $this->native($request);
|
||||
$legalSources = [];
|
||||
$usedLegalLines = [];
|
||||
foreach ($data['legal_sources'] ?? [] as $componentKey => $source) {
|
||||
$estimate = app(ImportLegalEstimates::class)->forPlan($request, (int) $source['estimate_id']);
|
||||
$lines = array_values(array_filter($estimate->snapshot['result']['lines'], fn ($line) => $line['key'] === $source['charge_key']));
|
||||
$components = array_values(array_filter($data['components'], fn ($component) => $component['key'] === $componentKey));
|
||||
$identity = $estimate->id.':'.$source['charge_key'];
|
||||
abort_unless(count($lines) === 1 && count($components) === 1 && ! isset($usedLegalLines[$identity]), 422, 'Seleccione uma componente e use cada imposição calculada uma única vez.');
|
||||
$line = $lines[0];
|
||||
$component = $components[0];
|
||||
abort_unless($component['kind'] === $line['kind'], 422, 'A família do encargo deve corresponder à imposição seleccionada.');
|
||||
$amount = $line['amount_minor'];
|
||||
abort_unless($amount === null ? $component['status'] === 'unknown'
|
||||
: ($component['status'] === 'known' && $component['total_minor'] === $amount)
|
||||
|| ($line['method'] === 'not_applicable' && $component['status'] === 'not_applicable' && $amount === 0), 422,
|
||||
'O total ou a situação diverge da estimativa legal. Retire explicitamente a ligação para preparar um pressuposto manual.');
|
||||
$usedLegalLines[$identity] = true;
|
||||
$legalSources[$componentKey] = ['estimate_id' => $estimate->id, 'estimate_version' => $estimate->version, 'charge_key' => $line['key'],
|
||||
'amount_minor' => $amount, 'legal_rule' => $estimate->snapshot['legal_rule']];
|
||||
}
|
||||
$plan = app(CommonBudget::class)->execute(fn () => BudgetImportEstimate::reconcile($native, $data['components'], (bool) $budget->includes_tax));
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_estimate',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
||||
'state' => $plan['complete'] ? 'prepared' : 'incomplete', 'created_by' => $actor->id,
|
||||
'data' => ['requisition_id' => $request->id, 'budget_id' => $budget->id, 'components' => $data['components']],
|
||||
'snapshot' => ['native' => $native, 'plan' => $plan, 'budget' => $budget->only(['id', 'cost_center_id', 'year', 'kind', 'includes_tax'])],
|
||||
'snapshot' => ['native' => $native, 'plan' => $plan, 'budget' => $budget->only(['id', 'cost_center_id', 'year', 'kind', 'includes_tax']), 'legal_sources' => $legalSources],
|
||||
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'import.estimate_prepared', $request, null,
|
||||
['record_id' => $record->id, 'version' => $record->version, 'complete' => $plan['complete'], 'financial_effects' => false]);
|
||||
|
||||
@@ -15,14 +15,15 @@ final class ImportEvidence
|
||||
$prefix = match ($record->kind) {
|
||||
'import_cost_doc' => 'import-costs',
|
||||
'import_document' => 'import-dossier',
|
||||
'import_legal_source' => 'import-legal',
|
||||
default => null,
|
||||
};
|
||||
$path = $evidence['path'] ?? null;
|
||||
$expected = $prefix.'/'.$record->tenant_id.'/'.$record->purchase_order_id.'/'.$record->record_key.'-'.$record->version;
|
||||
$expected = $prefix.'/'.$record->tenant_id.'/'.($record->kind === 'import_legal_source' ? '' : $record->purchase_order_id.'/').$record->record_key.'-'.$record->version;
|
||||
abort_unless($prefix !== null && preg_match('/^[a-f0-9-]{36}$/D', $record->record_key)
|
||||
&& ($evidence['disk'] ?? null) === 'local' && is_string($path)
|
||||
&& preg_match('/^'.preg_quote($expected, '/').'\.(pdf|jpg|jpeg|png)$/D', $path)
|
||||
&& is_int($evidence['size'] ?? null) && $evidence['size'] > 0 && $evidence['size'] <= 2097152
|
||||
&& is_int($evidence['size'] ?? null) && $evidence['size'] > 0 && $evidence['size'] <= ($record->kind === 'import_legal_source' ? 67108864 : 2097152)
|
||||
&& is_string($evidence['sha256'] ?? null) && preg_match('/^[a-f0-9]{64}$/D', $evidence['sha256']), 409,
|
||||
'A referência do original privado está incompleta.');
|
||||
$disk = Storage::disk('local');
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Brick\Math\BigDecimal;
|
||||
use Brick\Math\RoundingMode;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Pure MZN estimates. Definitions and bases are explicit; no tax, bank or journal execution. */
|
||||
final class ImportLegalAmounts
|
||||
{
|
||||
/** @param array<mixed> $definitions
|
||||
* @return list<array<string,mixed>>
|
||||
*/
|
||||
public function definitions(array $definitions): array
|
||||
{
|
||||
$data = Validator::make(['charges' => $definitions], [
|
||||
'charges' => 'present|array|list|max:20',
|
||||
'charges.*' => 'required|array:key,kind,label,method,rate_percent,specific_minor,quantity_unit,basis_reference',
|
||||
'charges.*.key' => 'required|string|max:100|distinct', 'charges.*.label' => 'required|string|min:2|max:120',
|
||||
'charges.*.kind' => 'required|in:duty,ice,vat,other',
|
||||
'charges.*.method' => 'required|in:unknown,not_applicable,ad_valorem,specific,maximum',
|
||||
'charges.*.rate_percent' => ['present', 'nullable', 'regex:/^\d{1,4}(\.\d{1,6})?$/', 'numeric', 'min:0', 'max:10000'],
|
||||
'charges.*.specific_minor' => 'present|nullable|integer|min:0|max:100000000000000',
|
||||
'charges.*.quantity_unit' => 'present|nullable|string|max:40',
|
||||
'charges.*.basis_reference' => 'required|string|min:3|max:4000',
|
||||
])->validate();
|
||||
$result = [];
|
||||
foreach ($data['charges'] as $index => $charge) {
|
||||
$percent = in_array($charge['method'], ['ad_valorem', 'maximum'], true);
|
||||
$specific = in_array($charge['method'], ['specific', 'maximum'], true);
|
||||
if (($charge['rate_percent'] !== null) !== $percent || ($charge['specific_minor'] !== null) !== $specific
|
||||
|| ($specific && trim($charge['quantity_unit'] ?? '') === '')) {
|
||||
throw ValidationException::withMessages(['charges.'.$index => 'Indique exactamente as taxas e a unidade do método documentado; desconhecido ou não aplicável não presume uma taxa.']);
|
||||
}
|
||||
$result[] = [...$charge, 'rate_percent' => $percent ? (string) BigDecimal::of($charge['rate_percent'])->toScale(6) : null,
|
||||
'specific_minor' => $specific ? (int) $charge['specific_minor'] : null];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** @param list<array<string,mixed>> $definitions
|
||||
* @param array<string,array<string,mixed>> $bases
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function calculate(array $definitions, array $bases): array
|
||||
{
|
||||
$definitions = $this->definitions($definitions);
|
||||
$bases = $this->bases($bases);
|
||||
if (array_diff(array_keys($bases), array_column($definitions, 'key')) !== []) {
|
||||
throw ValidationException::withMessages(['bases' => 'As bases devem corresponder às imposições da versão seleccionada.']);
|
||||
}
|
||||
$lines = [];
|
||||
$known = 0;
|
||||
$complete = $definitions !== [];
|
||||
foreach ($definitions as $charge) {
|
||||
$base = $bases[$charge['key']] ?? null;
|
||||
$value = $base['value_minor'] ?? null;
|
||||
$quantity = $base['quantity'] ?? null;
|
||||
if (($value !== null || $quantity !== null) && mb_strlen(trim($base['source'] ?? '')) < 3) {
|
||||
throw ValidationException::withMessages(['bases.'.$charge['key'].'.source' => 'Indique a origem do valor ou da quantidade efectivamente usados.']);
|
||||
}
|
||||
$percent = in_array($charge['method'], ['ad_valorem', 'maximum'], true);
|
||||
$specific = in_array($charge['method'], ['specific', 'maximum'], true);
|
||||
if ($specific && $quantity !== null && ($base['quantity_unit'] ?? null) !== $charge['quantity_unit']) {
|
||||
throw ValidationException::withMessages(['bases.'.$charge['key'] => 'A unidade da quantidade deve coincidir com a taxa específica; não foi presumida uma conversão.']);
|
||||
}
|
||||
$amount = null;
|
||||
if ($charge['method'] === 'not_applicable') {
|
||||
$amount = mb_strlen(trim($base['source'] ?? '')) >= 3 ? 0 : null;
|
||||
} elseif ($charge['method'] !== 'unknown' && (! $percent || $value !== null) && (! $specific || $quantity !== null)) {
|
||||
$adValorem = $percent ? BigDecimal::of($value)->multipliedBy($charge['rate_percent'])->dividedBy(100, 8, RoundingMode::Unnecessary) : BigDecimal::zero();
|
||||
$perUnit = $specific ? BigDecimal::of($quantity)->multipliedBy($charge['specific_minor']) : BigDecimal::zero();
|
||||
$calculated = ($charge['method'] === 'specific' || ($charge['method'] === 'maximum' && $perUnit->isGreaterThan($adValorem))) ? $perUnit : $adValorem;
|
||||
$rounded = $calculated->toScale(0, RoundingMode::HalfUp);
|
||||
if ($rounded->isGreaterThan(100000000000000) || $rounded->plus($known)->isGreaterThan(100000000000000)) {
|
||||
throw ValidationException::withMessages(['bases' => 'A estimativa excede o limite monetário suportado. Reveja as bases e as unidades.']);
|
||||
}
|
||||
$amount = $rounded->toInt();
|
||||
}
|
||||
$complete = $complete && $amount !== null;
|
||||
$known += $amount ?? 0;
|
||||
$lines[] = ['key' => $charge['key'], 'kind' => $charge['kind'], 'label' => $charge['label'], 'method' => $charge['method'],
|
||||
'amount_minor' => $amount, 'basis_reference' => $charge['basis_reference'], 'input' => $base];
|
||||
}
|
||||
|
||||
return ['currency' => 'MZN', 'lines' => $lines, 'complete' => $complete, 'known_subtotal_minor' => $known,
|
||||
'total_minor' => $complete ? $known : null, 'financial_effects' => false, 'rounding' => 'HALF_UP_PER_CHARGE'];
|
||||
}
|
||||
|
||||
/** @param array<string,array<string,mixed>> $bases
|
||||
* @return array<string,array<string,mixed>>
|
||||
*/
|
||||
public function bases(array $bases): array
|
||||
{
|
||||
Validator::make(['bases' => $bases], ['bases' => 'present|array|max:20',
|
||||
'bases.*' => 'required|array:value_minor,quantity,quantity_unit,source',
|
||||
'bases.*.value_minor' => 'present|nullable|integer|min:0|max:100000000000000',
|
||||
'bases.*.quantity' => ['present', 'nullable', 'string', 'regex:/^\d{1,12}(\.\d{1,6})?$/'],
|
||||
'bases.*.quantity_unit' => 'present|nullable|string|max:40', 'bases.*.source' => 'nullable|string|min:3|max:1000'])->validate();
|
||||
foreach ($bases as &$base) {
|
||||
$base['value_minor'] = $base['value_minor'] === null ? null : (int) $base['value_minor'];
|
||||
foreach (['quantity_unit', 'source'] as $field) {
|
||||
$base[$field] = trim($base[$field] ?? '') === '' ? null : trim($base[$field]);
|
||||
}
|
||||
}
|
||||
unset($base);
|
||||
|
||||
return $bases;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Immutable documentary tax estimates. Native import budget preparation retains its own writer and approval. */
|
||||
final class ImportLegalEstimates
|
||||
{
|
||||
public function forPlan(Requisition $request, int $id): SupplyRecord
|
||||
{
|
||||
abort_unless(app(ImportLegalRules::class)->ready(), 503, 'Preserve a consulta das fontes usadas na estimativa.');
|
||||
$record = SupplyRecord::query()->where('kind', 'import_legal_amount')->where('data->requisition_id', $request->id)->findOrFail($id);
|
||||
$item = $request->items()->whereKey($record->data['requisition_item_id'])->firstOrFail();
|
||||
abort_unless($record->snapshot['item'] === $item->only(['id', 'description', 'unit', 'quantity']), 409,
|
||||
'O artigo mudou. Reveja a fonte antes de usar os montantes.');
|
||||
$rule = $record->snapshot['legal_rule'];
|
||||
app(ImportLegalRules::class)->freeze($rule['id'], $rule['context']['code'], $rule['context']['origin_country'], $rule['context']['sector'], $rule['context']['date']);
|
||||
abort_unless(app(ImportLegalAmounts::class)->calculate($rule['data']['charges'] ?? [], $record->data['bases']) === $record->snapshot['result'], 409,
|
||||
'A estimativa diverge das bases e taxas preservadas.');
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, Requisition $request, array $input): SupplyRecord
|
||||
{
|
||||
abort_unless(app(ImportLegalRules::class)->ready(), 503);
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0',
|
||||
'requisition_item_id' => 'required|integer|min:1', 'rule_id' => 'required|integer|min:1',
|
||||
'match_code' => 'required|string|max:40', 'origin' => 'nullable|string|max:120', 'sector' => 'nullable|string|max:160',
|
||||
'date' => 'required|date_format:Y-m-d', 'bases' => 'present|array|max:20', 'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
foreach (['version', 'rule_id', 'requisition_item_id'] as $field) {
|
||||
$data[$field] = (int) $data[$field];
|
||||
}
|
||||
$data['bases'] = app(ImportLegalAmounts::class)->bases($data['bases']);
|
||||
$hash = hash('sha256', json_encode([$request->id, $data], JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $request, $data, $hash) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$request = Requisition::query()->visibleTo($actor)->lockForUpdate()->findOrFail($request->id);
|
||||
app(ConflictGuard::class)->assertParticipation($actor, $request);
|
||||
$item = $request->items()->whereKey($data['requisition_item_id'])->firstOrFail();
|
||||
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($retry !== null) {
|
||||
abort_unless($retry->kind === 'import_legal_amount' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||
|
||||
return $retry;
|
||||
}
|
||||
$old = app(SupplyPlanning::class)->latest('import_legal_amount')->where('data->requisition_id', $request->id)
|
||||
->where('data->requisition_item_id', $item->id)->first();
|
||||
abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'A estimativa do artigo mudou. Consulte a versão actual e preserve as suas bases.');
|
||||
$rule = app(ImportLegalRules::class)->freeze((int) $data['rule_id'], $data['match_code'], $data['origin'] ?? '', $data['sector'] ?? '', $data['date']);
|
||||
$result = app(ImportLegalAmounts::class)->calculate($rule['data']['charges'] ?? [], $data['bases']);
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_legal_amount',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
||||
'state' => $result['complete'] ? 'calculated' : 'indeterminate', 'created_by' => $actor->id,
|
||||
'data' => ['requisition_id' => $request->id, 'requisition_item_id' => $item->id, 'bases' => $data['bases']],
|
||||
'snapshot' => ['item' => $item->only(['id', 'description', 'unit', 'quantity']), 'legal_rule' => $rule, 'result' => $result, 'supersedes' => $old?->id],
|
||||
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'import.legal_estimate_recorded', $request, null,
|
||||
['record_id' => $record->id, 'version' => $record->version, 'state' => $record->state, 'financial_effects' => false]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
/** Human-reviewed documentary suggestions. Publication never activates a tax or payment calculation. */
|
||||
final class ImportLegalRules
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
return config('import-legal.qa_enabled') === true && app(ImportTariffCodes::class)->ready();
|
||||
}
|
||||
|
||||
private function actor(User $actor): User
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
abort_unless($actor->hasFunctions(['import_read', 'import_prepare', 'import_customs', PurchasingRole::Procurement]), 403);
|
||||
|
||||
return $actor;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, Requisition $request): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $request) {
|
||||
$actor = $this->actor($actor);
|
||||
$request = Requisition::query()->visibleTo($actor)->findOrFail($request->id);
|
||||
$rules = app(SupplyPlanning::class)->latest('import_legal_rule')->latest('id')
|
||||
->paginate(15, ['id', 'record_key', 'version', 'state', 'data', 'snapshot', 'reason'], 'rules_page')->withQueryString();
|
||||
$rules->through(fn ($rule) => [...$rule->toArray(), 'source_url' => '/requisicoes/'.$request->id.'/base-legal/fontes/'.$rule->snapshot['source_id']]);
|
||||
|
||||
return ['requisition' => $request->only(['id', 'number']), 'rules' => $rules,
|
||||
'sources' => SupplyRecord::query()->where('kind', 'import_legal_source')->latest('id')
|
||||
->paginate(15, ['id', 'data', 'created_at'], 'legal_sources_page')->withQueryString(),
|
||||
'items' => $request->items()->orderBy('id')->get(['id', 'description']),
|
||||
'classifications' => app(SupplyPlanning::class)->latest('import_tariff')->where('data->requisition_id', $request->id)->get(['version', 'data']),
|
||||
'canPropose' => $actor->hasFunctions([PurchasingRole::Procurement]),
|
||||
'estimates' => app(SupplyPlanning::class)->latest('import_legal_amount')->where('data->requisition_id', $request->id)->get(),
|
||||
'estimateHistory' => SupplyRecord::query()->where('kind', 'import_legal_amount')->where('data->requisition_id', $request->id)->latest('id')
|
||||
->paginate(15, ['id', 'record_key', 'version', 'state', 'data', 'snapshot', 'reason'], 'legal_estimates_page')->withQueryString(),
|
||||
'history' => SupplyRecord::query()->where('kind', 'import_legal_rule')->latest('id')
|
||||
->paginate(15, ['id', 'record_key', 'version', 'state', 'data', 'reason', 'created_at'], 'legal_history_page')->withQueryString(),
|
||||
'canManage' => $actor->hasFunctions(['import_customs']), 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id,
|
||||
'types' => ImportDossier::TYPES];
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, array $input, ?UploadedFile $file = null): SupplyRecord
|
||||
{
|
||||
$input = array_map(fn ($value) => is_string($value) ? trim($value) : $value, $input);
|
||||
$input['official_url'] = ($input['official_url'] ?? '') === '' ? null : $input['official_url'];
|
||||
$data = Validator::make(['record_key' => null, 'document_types' => [], 'charges' => [], ...$input, 'file' => $file], [
|
||||
'operation_key' => 'required|uuid', 'record_key' => 'present|nullable|uuid', 'version' => 'required|integer|min:0',
|
||||
'action' => 'required|in:source,save,publish,withdraw', 'reason' => 'required|string|min:10|max:4000',
|
||||
'source_id' => 'nullable|integer|min:1',
|
||||
'title' => 'required_if:action,save|nullable|string|min:3|max:200',
|
||||
'official_reference' => 'required_if:action,save,source|nullable|string|min:3|max:1000',
|
||||
'official_url' => 'nullable|url:http,https|max:2000',
|
||||
'citation' => 'required_if:action,save|nullable|string|min:3|max:4000',
|
||||
'valid_from' => 'required_if:action,save|nullable|date_format:Y-m-d',
|
||||
'valid_until' => 'nullable|date_format:Y-m-d|after_or_equal:valid_from',
|
||||
'match_code' => 'required_if:action,save|nullable|string|max:40|not_regex:/[\x00-\x1F\x7F]/',
|
||||
'suggested_code' => 'required_if:action,save|nullable|string|max:40|not_regex:/[\x00-\x1F\x7F]/',
|
||||
'origin_country' => 'nullable|string|max:120', 'sector' => 'nullable|string|max:160',
|
||||
'obligations' => 'required_if:action,save|nullable|string|min:3|max:4000',
|
||||
'document_types' => 'present|array|list|max:14',
|
||||
'document_types.*' => ['required', 'distinct', Rule::in(array_keys(ImportDossier::TYPES))],
|
||||
'charges' => 'present|array|list|max:20',
|
||||
'file' => 'nullable|file|mimes:pdf,jpg,jpeg,png|extensions:pdf,jpg,jpeg,png|max:65536',
|
||||
])->validate();
|
||||
unset($data['file']);
|
||||
$data['charges'] = app(ImportLegalAmounts::class)->definitions($data['charges']);
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$checksum = $file === null ? null : hash_file('sha256', $file->getPathname());
|
||||
$hash = hash('sha256', json_encode([$data, $checksum], JSON_THROW_ON_ERROR));
|
||||
$newPath = '';
|
||||
try {
|
||||
return DB::transaction(function () use ($actor, $data, $hash, $file, &$newPath) {
|
||||
$actor = $this->actor($actor);
|
||||
abort_unless($actor->hasFunctions(['import_customs']), 403);
|
||||
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($retry !== null) {
|
||||
abort_unless($retry->kind === ($data['action'] === 'source' ? 'import_legal_source' : 'import_legal_rule') && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||
|
||||
return $retry;
|
||||
}
|
||||
if ($data['action'] === 'source') {
|
||||
abort_unless($file !== null && $data['record_key'] === null && (int) $data['version'] === 0 && empty($data['source_id']), 422);
|
||||
$source = $this->storeSource($actor, $data, $file, $hash, $data['operation_key'], $newPath);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'import.legal_source_recorded', null, null, ['source_id' => $source->id, 'calculations_activated' => false]);
|
||||
|
||||
return $source;
|
||||
}
|
||||
$old = $data['record_key'] === null ? null : app(SupplyPlanning::class)->latest('import_legal_rule')->where('record_key', $data['record_key'])->firstOrFail();
|
||||
abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'A regra mudou. Consulte a versão actual e preserve a preparação.');
|
||||
$sourceId = $data['source_id'] ?? $old?->snapshot['source_id'] ?? null;
|
||||
if ($data['action'] === 'save') {
|
||||
abort_unless($file !== null || $sourceId !== null, 422, 'Conserve o exemplar oficial antes da publicação.');
|
||||
if ($file === null) {
|
||||
$existingSource = SupplyRecord::query()->where('kind', 'import_legal_source')->whereKey($sourceId)->firstOrFail();
|
||||
abort_unless($data['official_reference'] === $existingSource->data['official_reference'] && ($data['official_url'] ?? null) === ($existingSource->data['official_url'] ?? null), 422,
|
||||
'Uma fonte diferente exige o respectivo exemplar; pode alterar a citação dentro do mesmo exemplar.');
|
||||
}
|
||||
if ($file !== null) {
|
||||
abort_if(! empty($data['source_id']), 422, 'Seleccione um exemplar existente ou carregue um novo.');
|
||||
$source = $this->storeSource($actor, $data, $file, $hash, (string) Str::uuid(), $newPath);
|
||||
$sourceId = $source->id;
|
||||
}
|
||||
$payload = array_diff_key($data, array_flip(['operation_key', 'record_key', 'version', 'action', 'reason']));
|
||||
$state = 'draft';
|
||||
} else {
|
||||
abort_unless($old !== null && ($data['action'] === 'publish' ? $old->state === 'draft' : $old->state !== 'withdrawn'), 409);
|
||||
abort_unless($file === null && empty($data['source_id']), 422, 'A decisão conserva o exemplar da preparação; altere a fonte numa nova preparação.');
|
||||
$payload = $old->data;
|
||||
$state = $data['action'] === 'publish' ? 'published' : 'withdrawn';
|
||||
}
|
||||
$source = SupplyRecord::query()->where('kind', 'import_legal_source')->whereKey($sourceId)->firstOrFail();
|
||||
app(ImportEvidence::class)->bytes($source);
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_legal_rule',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
||||
'state' => $state, 'created_by' => $actor->id, 'data' => $payload,
|
||||
'snapshot' => ['source_id' => $source->id, 'source_sha256' => $source->snapshot['evidence']['sha256'],
|
||||
'supersedes' => $old?->id, 'calculations_activated' => false, 'reviewed_by' => $state === 'published' ? $actor->id : null],
|
||||
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'import.legal_'.$data['action'], null, null,
|
||||
['record_id' => $record->id, 'version' => $record->version, 'state' => $state, 'source_id' => $source->id, 'calculations_activated' => false]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
} catch (\Throwable $error) {
|
||||
if ($newPath !== '' && ! SupplyRecord::query()->where('snapshot->evidence->path', $newPath)->exists()) {
|
||||
Storage::disk('local')->delete($newPath);
|
||||
}
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $data */
|
||||
private function storeSource(User $actor, array $data, UploadedFile $file, string $hash, string $operation, string &$newPath): SupplyRecord
|
||||
{
|
||||
$key = (string) Str::uuid();
|
||||
$stored = $file->storeAs('import-legal/'.$actor->tenant_id, $key.'-1.'.$file->extension(), 'local');
|
||||
abort_unless(is_string($stored) && $file->getSize() > 0, 503);
|
||||
$newPath = $stored;
|
||||
$checksum = hash_file('sha256', $file->getPathname());
|
||||
abort_unless(is_string($checksum), 503);
|
||||
$source = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_legal_source',
|
||||
'record_key' => $key, 'version' => 1, 'state' => 'recorded', 'created_by' => $actor->id,
|
||||
'data' => ['official_reference' => $data['official_reference'], 'official_url' => $data['official_url'] ?? null],
|
||||
'snapshot' => ['evidence' => ['disk' => 'local', 'path' => $newPath, 'sha256' => $checksum,
|
||||
'size' => $file->getSize(), 'mime_type' => $file->getMimeType()]],
|
||||
'reason' => $data['reason'], 'operation_key' => $operation, 'input_hash' => $hash, 'created_at' => now()]);
|
||||
app(ImportEvidence::class)->bytes($source);
|
||||
|
||||
return $source;
|
||||
}
|
||||
|
||||
/** @return Builder<SupplyRecord> */
|
||||
private function published(?string $date = null)
|
||||
{
|
||||
$date ??= today()->toDateString();
|
||||
|
||||
return SupplyRecord::query()->where('kind', 'import_legal_rule')->whereIn('id', SupplyRecord::query()
|
||||
->where('kind', 'import_legal_rule')->whereIn('state', ['published', 'withdrawn'])
|
||||
->where(fn ($query) => $query->where('state', 'withdrawn')->orWhere('data->valid_from', '<=', $date))
|
||||
->selectRaw('MAX(id)')->groupBy('record_key'))
|
||||
->where('state', 'published');
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function suggestions(User $actor, Requisition $request, string $code, string $origin, string $sector, string $date): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $request, $code, $origin, $sector, $date) {
|
||||
$actor = $this->actor($actor);
|
||||
Requisition::query()->visibleTo($actor)->findOrFail($request->id);
|
||||
Validator::make(['date' => $date], ['date' => 'required|date_format:Y-m-d'])->validate();
|
||||
|
||||
return array_values($this->published($date)->where('data->match_code', $code)->orderBy('id')->get()->filter(fn ($rule) => $this->applies($rule, $origin, $sector, $date))
|
||||
->map(fn ($rule) => ['id' => $rule->id, 'version' => $rule->version, 'data' => $rule->data,
|
||||
'source_sha256' => $rule->snapshot['source_sha256']])->all());
|
||||
});
|
||||
}
|
||||
|
||||
private function applies(SupplyRecord $rule, string $origin, string $sector, string $date): bool
|
||||
{
|
||||
return $rule->data['valid_from'] <= $date && (($rule->data['valid_until'] ?? null) === null || $rule->data['valid_until'] >= $date)
|
||||
&& (empty($rule->data['origin_country']) || mb_strtolower($rule->data['origin_country']) === mb_strtolower(trim($origin)))
|
||||
&& (empty($rule->data['sector']) || mb_strtolower($rule->data['sector']) === mb_strtolower(trim($sector)));
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function freeze(int $id, string $code, string $origin, string $sector, string $date): array
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
$rule = SupplyRecord::query()->where('kind', 'import_legal_rule')->findOrFail($id);
|
||||
abort_unless($this->published($date)->whereKey($id)->exists(), 409,
|
||||
'A regra foi substituída, retirada ou ainda não foi publicada para este período. Consulte as fontes preservadas e prepare a versão aplicável.');
|
||||
abort_unless($rule->data['match_code'] === $code && $this->applies($rule, $origin, $sector, $date), 409, 'A regra não corresponde ao contexto ou ao período indicado.');
|
||||
$source = SupplyRecord::query()->where('kind', 'import_legal_source')->whereKey($rule->snapshot['source_id'])->firstOrFail();
|
||||
app(ImportEvidence::class)->bytes($source);
|
||||
|
||||
return ['id' => $rule->id, 'record_key' => $rule->record_key, 'version' => $rule->version, 'data' => $rule->data,
|
||||
'source_id' => $source->id, 'source_sha256' => $source->snapshot['evidence']['sha256'],
|
||||
'context' => ['code' => $code, 'origin_country' => $origin, 'sector' => $sector, 'date' => $date]];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $frozen */
|
||||
public function changed(array $frozen): bool
|
||||
{
|
||||
if (! $this->ready()) {
|
||||
return true;
|
||||
}
|
||||
$rule = $this->published()->where('record_key', $frozen['record_key'])->first();
|
||||
|
||||
if ($rule === null || $rule->id !== $frozen['id'] || ! $this->applies($rule, $frozen['context']['origin_country'], $frozen['context']['sector'], today()->toDateString())) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
$source = SupplyRecord::query()->where('kind', 'import_legal_source')->whereKey($rule->snapshot['source_id'])->firstOrFail();
|
||||
app(ImportEvidence::class)->bytes($source);
|
||||
} catch (HttpExceptionInterface|ModelNotFoundException) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function source(User $actor, Requisition $request, int $id): SupplyRecord
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $request, $id) {
|
||||
$actor = $this->actor($actor);
|
||||
Requisition::query()->visibleTo($actor)->findOrFail($request->id);
|
||||
$source = SupplyRecord::query()->where('kind', 'import_legal_source')->findOrFail($id);
|
||||
app(ImportEvidence::class)->bytes($source);
|
||||
|
||||
return $source;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\GoodsReceiptItem;
|
||||
use App\Models\InventoryLotAllocation;
|
||||
use App\Models\StockMovement;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
/** Current factual follow-up. No new obligation, approval, notification recipient or financial effect. */
|
||||
final class ImportReadiness
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
return config('import-readiness.qa_enabled') === true && app(ImportDossier::class)->ready();
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, SupplyRecord $import): array
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
|
||||
return DB::transaction(function () use ($actor, $import) {
|
||||
[$actor, $current, $order] = app(ImportDossier::class)->context($actor, $import);
|
||||
$base = '/compras/importacoes/'.$current->id;
|
||||
$alerts = [];
|
||||
$add = function (string $key, string $category, string $text, string $href) use (&$alerts) {
|
||||
$alerts[] = ['key' => $key, 'category' => $category, 'text' => $text, 'href' => $href];
|
||||
};
|
||||
$expected = $current->data['expected_usable_on'] ?? null;
|
||||
$receipts = app(ReceiptWorkflow::class)->progress($order);
|
||||
if ($expected === null) {
|
||||
$add('expected-unknown', 'Por determinar', 'Data de recepção utilizável prevista ainda por indicar.', '/compras/fornecimento/import');
|
||||
} elseif ($receipts['state'] !== 'complete' && $expected <= today()->toDateString()) {
|
||||
$add('expected-due', 'Logística', $expected < today()->toDateString()
|
||||
? 'A previsão de recepção utilizável foi ultrapassada; confira os marcos logísticos.'
|
||||
: 'A recepção utilizável está prevista para hoje; confira os marcos logísticos.', '/compras/fornecimento/import');
|
||||
}
|
||||
if (in_array($current->state, ['arrived', 'held'], true)) {
|
||||
$add('customs-pending', 'Logística', 'A mercadoria ainda não tem libertação aduaneira registada; a chegada não demonstra stock utilizável.', '/compras/fornecimento/import');
|
||||
}
|
||||
$linkedLots = InventoryLotAllocation::query()->whereIn('stock_movement_id', StockMovement::query()->select('id')
|
||||
->whereIn('goods_receipt_item_id', GoodsReceiptItem::query()->select('id')->whereIn('purchase_order_item_id', $order->items()->select('id'))))->pluck('lot_id');
|
||||
$lotLocations = InventoryLotAllocation::query()->whereIn('lot_id', $linkedLots)->get(['lot_id', 'stock_item_id', 'warehouse_id'])
|
||||
->groupBy(fn ($row) => $row->stock_item_id.':'.$row->warehouse_id);
|
||||
$lotsComplete = true;
|
||||
foreach ($lotLocations as $locations) {
|
||||
$first = $locations->firstOrFail();
|
||||
$context = app(InventoryLots::class)->context($first->stock_item_id, $first->warehouse_id);
|
||||
if ($context === null || ! $context['reconciled']) {
|
||||
$lotsComplete = false;
|
||||
$add('stock-unverified-'.$first->stock_item_id.'-'.$first->warehouse_id, 'Verificação incompleta', 'A disponibilidade por lotes ligados à recepção requer conferência no armazém.', '/ordens/'.$order->id);
|
||||
} else {
|
||||
foreach ($context['lots'] as $lot) {
|
||||
if ($locations->contains('lot_id', $lot['id']) && $lot['quantity_milli'] > 0 && $lot['usable_milli'] === 0) {
|
||||
$add('stock-held-'.$lot['id'].'-'.$first->warehouse_id, 'Disponibilidade', 'Há saldo não utilizável num lote ligado às recepções desta ordem; confira a identificação, validade e libertação de qualidade no armazém.', '/ordens/'.$order->id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
$documents = app(SupplyPlanning::class)->latest('import_document')->where('purchase_order_id', $order->id)
|
||||
->where('snapshot->import_key', $current->record_key)->orderBy('id')->limit(201)->get();
|
||||
$documentsComplete = $documents->count() <= 200;
|
||||
$complete = $documentsComplete && $lotsComplete;
|
||||
$validTypes = [];
|
||||
foreach ($documents->take(200) as $document) {
|
||||
try {
|
||||
app(ImportEvidence::class)->bytes($document);
|
||||
$validTypes[] = $document->data['type'];
|
||||
} catch (HttpExceptionInterface) {
|
||||
$add('document-'.$document->id, 'Documentos', 'Original indisponível ou alterado: '.$document->data['reference'].'.', $base.'/documentos');
|
||||
}
|
||||
}
|
||||
if (! $documentsComplete) {
|
||||
$add('documents-incomplete', 'Verificação incompleta', 'O acompanhamento verificou os primeiros 200 originais actuais. Consulte o dossiê completo antes de concluir a conferência.', $base.'/documentos');
|
||||
}
|
||||
$requirements = [];
|
||||
$classifications = $order->snapshot['import_tariffs'] ?? [];
|
||||
foreach ($classifications as $classification) {
|
||||
$requestId = $classification['data']['requisition_id'] ?? $order->requisition_id;
|
||||
$legal = $classification['legal_rule'] ?? null;
|
||||
if ($legal === null) {
|
||||
$add('legal-unknown-'.$classification['record_id'], 'Por determinar', 'Requisitos legais ainda por associar ao artigo '.$classification['item']['description'].'.', '/requisicoes/'.$requestId.'/base-legal');
|
||||
|
||||
continue;
|
||||
}
|
||||
if (app(ImportLegalRules::class)->changed($legal)) {
|
||||
$add('legal-changed-'.$classification['record_id'], 'Fonte legal', 'A regra aplicada ao artigo '.$classification['item']['description'].' mudou, terminou ou ficou indisponível. A decisão preservada requer revisão.', '/requisicoes/'.$requestId.'/classificacao-pautal');
|
||||
}
|
||||
$requirements = [...$requirements, ...$legal['data']['document_types']];
|
||||
}
|
||||
if ($classifications === []) {
|
||||
$add('classification-unknown', 'Por determinar', 'Não há classificação pautal preservada nesta ordem. Consulte as origens antes de determinar os requisitos aplicáveis.', '/ordens/'.$order->id);
|
||||
}
|
||||
foreach (array_unique($requirements) as $type) {
|
||||
if (! in_array($type, $validTypes, true)) {
|
||||
$add('required-'.$type, 'Documentos', 'Documento indicado na fonte aplicada ainda não disponível: '.ImportDossier::TYPES[$type].'.', $base.'/documentos');
|
||||
}
|
||||
}
|
||||
$parties = app(ImportParties::class)->workspace($actor, $current)['current'];
|
||||
if ($parties->isEmpty()) {
|
||||
$add('parties-unknown', 'Por determinar', 'Despachante ou transitário e respectivas instruções ainda por associar; não foram presumidos intervenientes.', $base.'/documentos');
|
||||
}
|
||||
foreach ($parties as $party) {
|
||||
foreach ($party['issues'] as $index => $issue) {
|
||||
$add('party-'.$party['id'].'-'.$index, 'Intervenientes', $issue, $base.'/documentos');
|
||||
}
|
||||
}
|
||||
if (app(ImportBankSupport::class)->ready()) {
|
||||
$terms = 0;
|
||||
app(ImportBankSupport::class)->report($actor, $current, function ($record, $issues) use (&$terms, $add, $base) {
|
||||
$terms++;
|
||||
foreach ($issues as $index => $issue) {
|
||||
$add('bank-'.$record->id.'-'.$index, 'Suporte bancário', $issue, $base.'/suporte-bancario');
|
||||
}
|
||||
});
|
||||
if ($terms === 0) {
|
||||
$add('bank-unknown', 'Por determinar', 'Aplicabilidade e acompanhamento do termo bancário ainda por registar; não foi presumido um prazo.', $base.'/suporte-bancario');
|
||||
}
|
||||
} else {
|
||||
$complete = false;
|
||||
$add('bank-unavailable', 'Verificação incompleta', 'A consulta do acompanhamento bancário está indisponível neste ambiente.', $base.'/documentos');
|
||||
}
|
||||
if ($actor->hasFunctions(['finance'])) {
|
||||
$plans = app(SupplyPlanning::class)->latest('import_cost_plan')->where('purchase_order_id', $order->id)->get(['id', 'state']);
|
||||
if ($plans->isEmpty()) {
|
||||
$add('cost-unknown', 'Por determinar', 'Custos efectivos ainda sem preparação neste âmbito; a ausência de valores não significa custo zero.', $base.'/custos');
|
||||
}
|
||||
foreach ($plans as $plan) {
|
||||
if (in_array($plan->state, ['draft', 'returned'], true)) {
|
||||
$add('cost-'.$plan->id, 'Conferência financeira', 'A preparação dos custos efectivos aguarda conferência ou correcção no percurso financeiro.', $base.'/custos');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return ['importRecord' => $current->only(['id', 'record_key', 'version', 'state']), 'order' => $order->only(['id', 'number']),
|
||||
'expectedUsableOn' => $expected, 'checkedAt' => now()->toIso8601String(), 'complete' => $complete,
|
||||
'alerts' => $alerts, 'financialEffects' => false, 'automaticNotifications' => false];
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -39,7 +39,8 @@ final class ImportTariffCodes
|
||||
'Confirme a classificação pautal actual de cada artigo importado antes de emitir a ordem.');
|
||||
$result[$item->id] = ['record_id' => $record->id, 'version' => $record->version,
|
||||
'requisition_item_id' => $item->id, 'item' => $record->snapshot['item'], 'data' => $record->data,
|
||||
'source' => $record->snapshot['master'] ?? null, 'confirmed_by' => $record->snapshot['confirmed_by'], 'reason' => $record->reason];
|
||||
'source' => $record->snapshot['master'] ?? null, 'legal_rule' => $record->snapshot['legal_rule'] ?? null,
|
||||
'confirmed_by' => $record->snapshot['confirmed_by'], 'reason' => $record->reason];
|
||||
}
|
||||
ksort($result, SORT_NUMERIC);
|
||||
|
||||
@@ -72,7 +73,11 @@ final class ImportTariffCodes
|
||||
$stockItems->through(fn ($item) => [...$item->only(['id', 'code', 'name', 'unit']),
|
||||
'tariff' => app(SupplyPlanning::class)->latest('stock_tariff')->where('stock_item_id', $item->id)->first(['id', 'version', 'data'])]);
|
||||
|
||||
return ['requisition' => $request->only(['id', 'number', 'status']), 'items' => $request->items()->orderBy('id')->get(['id', 'description', 'unit', 'quantity']),
|
||||
$latest->each(function ($record) {
|
||||
$record->setAttribute('legal_changed', isset($record->snapshot['legal_rule']) && app(ImportLegalRules::class)->changed($record->snapshot['legal_rule']));
|
||||
});
|
||||
|
||||
return ['legalReady' => app(ImportLegalRules::class)->ready(), 'requisition' => $request->only(['id', 'number', 'status']), 'items' => $request->items()->orderBy('id')->get(['id', 'description', 'unit', 'quantity']),
|
||||
'latest' => $latest, 'history' => $history, 'stockItems' => $stockItems, 'canPropose' => ($actor->id === $request->requester_id && app(OrganizationAccess::class)->canRequest($actor)) || $actor->hasFunctions([PurchasingRole::Procurement]),
|
||||
'canConfirm' => $actor->hasFunctions([PurchasingRole::Procurement]),
|
||||
'masters' => app(SupplyPlanning::class)->latest('stock_tariff')->when(! $materialsVisible, fn ($q) => $q->whereRaw('1 = 0'))->whereIn('stock_item_id', StockItem::query()->select('id'))
|
||||
@@ -89,7 +94,10 @@ final class ImportTariffCodes
|
||||
'version' => 'required|integer|min:0', 'reason' => 'required|string|min:10|max:4000',
|
||||
'stock_item_id' => 'required_if:action,master|nullable|integer|min:1', 'requisition_item_id' => 'required_unless:action,master|nullable|integer|min:1',
|
||||
'master_id' => 'nullable|integer|min:1', 'code' => 'required_unless:action,propose|nullable|string|max:40|not_regex:/[\x00-\x1F\x7F]/',
|
||||
'source_reference' => 'required_unless:action,propose|nullable|string|max:2000'])->validate();
|
||||
'source_reference' => 'required_unless:action,propose|nullable|string|max:2000',
|
||||
'legal_rule_id' => 'nullable|integer|min:1', 'legal_match_code' => 'required_with:legal_rule_id|nullable|string|max:40',
|
||||
'legal_origin' => 'nullable|string|max:120', 'legal_sector' => 'nullable|string|max:160',
|
||||
'legal_date' => 'required_with:legal_rule_id|nullable|date_format:Y-m-d'])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$hash = hash('sha256', json_encode([$request->id, $data], JSON_THROW_ON_ERROR));
|
||||
|
||||
@@ -133,10 +141,23 @@ final class ImportTariffCodes
|
||||
abort_unless($code === $master->data['code'] && $source === $master->data['source_reference'], 409, 'Aplique explicitamente o código e a fonte do cadastro ou conserve uma proposta manual.');
|
||||
$snapshot['master'] = ['id' => $master->id, 'version' => $master->version, 'item' => $master->snapshot['item']];
|
||||
}
|
||||
if (! empty($data['legal_rule_id'])) {
|
||||
abort_unless($buyer && empty($data['master_id']), 403);
|
||||
$legal = app(ImportLegalRules::class)->freeze((int) $data['legal_rule_id'], $data['legal_match_code'],
|
||||
$data['legal_origin'] ?? '', $data['legal_sector'] ?? '', $data['legal_date']);
|
||||
abort_unless($code === $legal['data']['suggested_code'] && $source === $legal['data']['official_reference'].' — '.$legal['data']['citation'], 409,
|
||||
'Aplique explicitamente o código e a citação da regra seleccionada.');
|
||||
$snapshot['legal_rule'] = $legal;
|
||||
}
|
||||
$state = 'proposed';
|
||||
} else {
|
||||
abort_unless($old !== null && $old->state === 'proposed' && empty($data['master_id']) && $code !== '' && $source !== '', 409, 'Seleccione uma proposta actual e indique código e fonte da confirmação.');
|
||||
abort_unless($old->snapshot['item'] === $snapshot['item'], 409, 'O artigo mudou. Prepare uma proposta actual.');
|
||||
if (isset($old->snapshot['legal_rule'])) {
|
||||
$legal = $old->snapshot['legal_rule'];
|
||||
app(ImportLegalRules::class)->freeze($legal['id'], $legal['context']['code'], $legal['context']['origin_country'],
|
||||
$legal['context']['sector'], $legal['context']['date']);
|
||||
}
|
||||
$payload = [...$old->data, 'confirmed_code' => $code, 'confirmation_source' => $source,
|
||||
'deviation' => $code !== $old->data['proposed_code'], 'confirmed_by' => $actor->id];
|
||||
$snapshot = [...$old->snapshot, 'confirmed_by' => ['id' => $actor->id, 'name' => $actor->name]];
|
||||
|
||||
@@ -195,7 +195,7 @@ final class OrderPartsWorkflow
|
||||
$prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection);
|
||||
abort_unless(hash_equals($prepared['fingerprint'], $data['fingerprint']), 409, 'A preparação mudou; consulte as origens actuais.');
|
||||
$this->checkAllocations($actor, $prepared['sources'], $budgetSources);
|
||||
$frames = $requests = $lines = $catalogue = $tariffs = [];
|
||||
$frames = $requests = $lines = $catalogue = $tariffs = $capital = [];
|
||||
$firstQuote = null;
|
||||
foreach ($prepared['sources'] as $source) {
|
||||
$request = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
|
||||
@@ -208,6 +208,7 @@ final class OrderPartsWorkflow
|
||||
'Preserve os intervenientes e as referências de cada origem.');
|
||||
$requested = $request->items()->get()->keyBy('id');
|
||||
$tariffs += app(ImportTariffCodes::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
||||
$capital += app(CapitalAssignments::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
||||
foreach ($source['items'] as $item) {
|
||||
$native = $requested->get($item['requisition_item_id']);
|
||||
abort_unless($native !== null, 409);
|
||||
@@ -240,7 +241,7 @@ final class OrderPartsWorkflow
|
||||
$exchange = $foreign ? ['exchange_basis' => null,
|
||||
'exchange_sources' => array_map(fn ($s) => ['requisition_id' => $s['requisition_id'], 'exchange_basis' => $s['exchange_basis']], $prepared['sources']),
|
||||
'reference_amounts' => app(OrderPartsExchange::class)->sum(array_column($prepared['sources'], 'reference_amounts'))] : [];
|
||||
$snapshot = [...$frames[0], ...$limits, ...$exchange, ...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]), 'company' => Tenant::query()->whereKey($actor->tenant_id)->firstOrFail()->only(['id', 'name']),
|
||||
$snapshot = [...$frames[0], ...$limits, ...$exchange, ...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]), ...($capital === [] ? [] : ['capital_assignments' => $capital]), 'company' => Tenant::query()->whereKey($actor->tenant_id)->firstOrFail()->only(['id', 'name']),
|
||||
'supplier' => $firstQuote->supplier?->only(['id', 'name', 'nuit', 'contact', 'email', 'phone', 'address']),
|
||||
'issuer' => $actor->only(['id', 'name']), 'items' => $lines, 'catalogue_sources' => $catalogue,
|
||||
'budget_control' => $commit, 'development_only' => true, 'budget_checked' => true,
|
||||
|
||||
@@ -170,7 +170,9 @@ class PurchaseWorkflow
|
||||
}
|
||||
}
|
||||
$tariffs = app(ImportTariffCodes::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
||||
$capital = app(CapitalAssignments::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
||||
$snapshot = [
|
||||
...($capital === [] ? [] : ['capital_assignments' => $capital]),
|
||||
...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]),
|
||||
...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)]),
|
||||
|
||||
Reference in New Issue
Block a user