243 lines
16 KiB
PHP
243 lines
16 KiB
PHP
<?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;
|
|
}
|
|
}
|