@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
/** Explicit native broker/forwarder selection with retained written instructions. */
|
||||
final class ImportParties
|
||||
{
|
||||
public const ROLES = ['broker' => 'Despachante aduaneiro', 'forwarder' => 'Transitário'];
|
||||
|
||||
public function canSelect(User $actor, PurchaseOrder $order): bool
|
||||
{
|
||||
if (! $actor->hasFunctions(['procurement']) || ! $actor->hasFunctions(['import_prepare'])
|
||||
|| app(OrganizationAccess::class)->maintenanceOnly($actor)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return ! Requisition::query()->whereIn('id', app(OrderPartsAccess::class)->origins($order))->where('requester_id', $actor->id)->exists();
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, SupplyRecord $import, string $search = ''): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $import, $search): array {
|
||||
[$actor, $current, $order] = app(ImportDossier::class)->context($actor, $import);
|
||||
$canSelect = $this->canSelect($actor, $order);
|
||||
$parties = SupplyRecord::query()->where('kind', 'import_party')->where('purchase_order_id', $order->id)
|
||||
->where('snapshot->import_key', $current->record_key)->latest('id')
|
||||
->paginate(10, ['id', 'record_key', 'version', 'data', 'snapshot', 'reason', 'created_at', 'created_by'], 'parties_page')->withQueryString();
|
||||
$currentParties = app(SupplyPlanning::class)->latest('import_party')->where('purchase_order_id', $order->id)
|
||||
->where('snapshot->import_key', $current->record_key)->get();
|
||||
$currentParties = $currentParties->map(fn ($record) => [...$record->only(['id', 'record_key', 'version', 'data', 'snapshot', 'reason']),
|
||||
'issues' => $this->issues($actor, $order, $record)]);
|
||||
$suppliers = Supplier::query()->when(! $canSelect, fn ($q) => $q->whereRaw('1=0'))->where('status', 'active')->where('blocked', false)
|
||||
->where('next_review', '>=', today())->when($search !== '', fn ($q) => $q->where(fn ($match) => $match
|
||||
->whereRaw('LOWER(name) LIKE ?', ['%'.addcslashes(mb_strtolower($search), '%_\\').'%'])
|
||||
->orWhereRaw('LOWER(nuit) LIKE ?', ['%'.addcslashes(mb_strtolower($search), '%_\\').'%'])))
|
||||
->orderBy('name')->orderBy('id')->paginate(20, ['id', 'name', 'nuit', 'version'], 'party_suppliers_page')->withQueryString();
|
||||
$instructions = app(SupplyPlanning::class)->latest('import_document')->where('purchase_order_id', $order->id)
|
||||
->where('snapshot->import_key', $current->record_key)->where('data->type', 'written_instructions')
|
||||
->latest('id')->paginate(20, ['id', 'record_key', 'version', 'data'], 'instructions_page')->withQueryString();
|
||||
|
||||
return ['roles' => self::ROLES, 'canSelect' => $canSelect, 'search' => $search, 'suppliers' => $suppliers,
|
||||
'instructions' => $instructions, 'current' => $currentParties, 'history' => $parties];
|
||||
});
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
private function issues(User $actor, PurchaseOrder $order, SupplyRecord $record): array
|
||||
{
|
||||
$issues = [];
|
||||
$supplier = Supplier::query()->whereKey($record->data['supplier_id'])->first();
|
||||
if ($supplier === null || ! $supplier->eligible() || $supplier->only(['id', 'name', 'nuit', 'version']) !== $record->snapshot['supplier']) {
|
||||
$issues[] = 'O cadastro ou a elegibilidade da entidade mudou; confira a selecção.';
|
||||
}
|
||||
foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
|
||||
$request = Requisition::query()->whereKey($origin)->firstOrFail();
|
||||
if (app(ConflictGuard::class)->processBlocked($request, $record->data['supplier_id'], $actor)) {
|
||||
$issues[] = 'Existe um conflito de interesses activo com a entidade seleccionada.';
|
||||
break;
|
||||
}
|
||||
}
|
||||
$latest = app(SupplyPlanning::class)->latest('import_document')->where('record_key', $record->snapshot['instructions']['record_key'])->first();
|
||||
if ($latest === null || $latest->id !== $record->data['instruction_document_id']) {
|
||||
$issues[] = 'As instruções escritas têm uma versão diferente; confira a selecção.';
|
||||
} else {
|
||||
try {
|
||||
app(ImportEvidence::class)->bytes($latest);
|
||||
} catch (HttpExceptionInterface) {
|
||||
$issues[] = 'O original das instruções está indisponível ou alterado.';
|
||||
}
|
||||
}
|
||||
|
||||
return $issues;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function select(User $actor, SupplyRecord $import, array $input): SupplyRecord
|
||||
{
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'role' => 'required|in:broker,forwarder',
|
||||
'version' => 'required|integer|min:0', 'supplier_id' => 'required|integer|min:1', 'supplier_version' => 'required|integer|min:1',
|
||||
'instruction_document_id' => 'required|integer|min:1', 'reason' => 'required|string|min:10|max:4000', 'no_conflict' => 'required|accepted'])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$hash = hash('sha256', json_encode([$import->record_key, $data], JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $import, $data, $hash): SupplyRecord {
|
||||
[$actor, $current, $order] = app(ImportDossier::class)->context($actor, $import, true);
|
||||
abort_unless($this->canSelect($actor, $order), 403, 'A selecção cabe ao comprador, distinto dos requisitantes das origens.');
|
||||
$replay = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($replay !== null) {
|
||||
abort_unless($replay->kind === 'import_party' && $replay->created_by === $actor->id && hash_equals($replay->input_hash, $hash), 409);
|
||||
|
||||
return $replay;
|
||||
}
|
||||
$previous = SupplyRecord::query()->where('kind', 'import_party')->where('purchase_order_id', $order->id)
|
||||
->where('snapshot->import_key', $current->record_key)->where('data->role', $data['role'])->latest('version')->lockForUpdate()->first();
|
||||
abort_unless((int) $data['version'] === ($previous->version ?? 0), 409, 'A selecção mudou. Consulte a versão actual.');
|
||||
$supplier = Supplier::query()->whereKey($data['supplier_id'])->lockForUpdate()->firstOrFail();
|
||||
abort_unless($supplier->version === (int) $data['supplier_version'], 409, 'O cadastro da entidade mudou. Consulte a versão actual antes de seleccionar.');
|
||||
abort_unless($supplier->eligible(), 422, 'Seleccione uma entidade activa e elegível no cadastro.');
|
||||
foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
|
||||
$request = Requisition::query()->whereKey($origin)->firstOrFail();
|
||||
app(ConflictGuard::class)->assertProcess($request, $supplier->id, $actor);
|
||||
}
|
||||
$instructions = app(ImportDossier::class)->evidence($actor, $current, (int) $data['instruction_document_id']);
|
||||
abort_unless($instructions->data['type'] === 'written_instructions'
|
||||
&& app(SupplyPlanning::class)->latest('import_document')->where('record_key', $instructions->record_key)->value('id') === $instructions->id, 409,
|
||||
'Seleccione a versão actual das instruções escritas desta importação.');
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_party',
|
||||
'record_key' => $previous->record_key ?? (string) Str::uuid(), 'version' => ($previous->version ?? 0) + 1,
|
||||
'state' => 'selected', 'purchase_order_id' => $order->id, 'supplier_id' => $supplier->id, 'created_by' => $actor->id,
|
||||
'data' => ['role' => $data['role'], 'supplier_id' => $supplier->id, 'instruction_document_id' => $instructions->id],
|
||||
'snapshot' => ['import_key' => $current->record_key, 'import_version' => $current->version, 'supersedes' => $previous->id ?? null,
|
||||
'supplier' => $supplier->only(['id', 'name', 'nuit', 'version']),
|
||||
'instructions' => $instructions->only(['id', 'record_key', 'version', 'data']),
|
||||
'financial_effects' => false, 'no_conflict' => true],
|
||||
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
||||
foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'import.party_selected', Requisition::query()->whereKey($origin)->firstOrFail(), null,
|
||||
['record_id' => $record->id, 'role' => $data['role'], 'supplier_id' => $supplier->id, 'version' => $record->version, 'no_conflict' => true]);
|
||||
}
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
public function assertCurrent(User $actor, PurchaseOrder $order, string $importKey): void
|
||||
{
|
||||
$parties = app(SupplyPlanning::class)->latest('import_party')->where('purchase_order_id', $order->id)->where('snapshot->import_key', $importKey)->get();
|
||||
if ($parties->isEmpty()) {
|
||||
return; // Historic imports without a selected party retain their existing workflow.
|
||||
}
|
||||
abort_unless(app(ImportDossier::class)->ready(), 503, 'Preserve a capacidade de consulta dos intervenientes seleccionados.');
|
||||
foreach ($parties as $record) {
|
||||
abort_unless($this->issues($actor, $order, $record) === [], 409, 'Confira a entidade seleccionada, os conflitos e a versão das instruções antes de continuar.');
|
||||
$instructions = SupplyRecord::query()->whereKey($record->data['instruction_document_id'])->firstOrFail();
|
||||
app(ImportEvidence::class)->bytes($instructions);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user