148 lines
9.8 KiB
PHP
148 lines
9.8 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\PurchaseOrder;
|
|
use App\Models\Requisition;
|
|
use App\Models\SupplyRecord;
|
|
use App\Models\User;
|
|
use Illuminate\Http\UploadedFile;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Support\Str;
|
|
|
|
/** Versioned documentary originals. No customs submission, payment or legal conclusion. */
|
|
final class ImportDossier
|
|
{
|
|
public const TYPES = [
|
|
'commercial_invoice' => 'Factura comercial', 'packing_list' => 'Lista de embalagem',
|
|
'transport_document' => 'Documento de transporte', 'insurance' => 'Seguro',
|
|
'origin_certificate' => 'Certificado de origem', 'licence' => 'Licença ou autorização',
|
|
'customs_declaration' => 'Declaração aduaneira ou documento único', 'customs_assessment' => 'Liquidação aduaneira',
|
|
'payment_evidence' => 'Comprovativo documental de pagamento', 'customs_release' => 'Documento de libertação',
|
|
'bank_commitment' => 'Termo de compromisso bancário', 'bank_support' => 'Documento de suporte bancário',
|
|
'written_instructions' => 'Instruções escritas', 'other' => 'Outro documento',
|
|
];
|
|
|
|
public function ready(): bool
|
|
{
|
|
$db = DB::connection();
|
|
|
|
return config('import-dossier.qa_enabled') === true && app()->environment('testing')
|
|
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
|
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())));
|
|
}
|
|
|
|
/** @return array{User,SupplyRecord,PurchaseOrder} */
|
|
public function context(User $actor, SupplyRecord $import, bool $write = false): array
|
|
{
|
|
abort_unless($this->ready(), 503);
|
|
app(ConflictGuard::class)->lockCompany($actor);
|
|
$actor = app(CurrentActor::class)->lock($actor);
|
|
abort_unless($actor->hasFunctions($write ? ['import_prepare'] : ['import_read', 'import_prepare', 'finance']), 403);
|
|
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
|
$current = SupplyRecord::query()->where('kind', 'import')->where('record_key', $import->record_key)->latest('version')->lockForUpdate()->firstOrFail();
|
|
abort_unless($current->id === $import->id, 409, 'A importação mudou. Consulte a versão actual.');
|
|
$order = PurchaseOrder::query()->visibleTo($actor)->whereKey($current->purchase_order_id)->lockForUpdate()->firstOrFail();
|
|
app(OrderPartsAccess::class)->assertProcess($actor, $order);
|
|
|
|
return [$actor, $current, $order];
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function workspace(User $actor, SupplyRecord $import): array
|
|
{
|
|
return DB::transaction(function () use ($actor, $import): array {
|
|
[$actor, $current, $order] = $this->context($actor, $import);
|
|
$documents = SupplyRecord::query()->where('kind', 'import_document')->where('purchase_order_id', $order->id)
|
|
->where('snapshot->import_key', $current->record_key)->latest('id')
|
|
->paginate(20, ['id', 'record_key', 'version', 'state', 'created_by', 'created_at', 'data', 'reason', 'snapshot'])->withQueryString();
|
|
$latestIds = app(SupplyPlanning::class)->latest('import_document')->where('purchase_order_id', $order->id)->pluck('id')->all();
|
|
$documents->through(fn ($record) => [...$record->only(['id', 'record_key', 'version', 'state', 'created_by', 'created_at', 'data', 'reason']),
|
|
'current' => in_array($record->id, $latestIds, true), 'supersedes' => $record->snapshot['supersedes'], 'sha256' => $record->snapshot['evidence']['sha256']]);
|
|
|
|
return ['importRecord' => $current->only(['id', 'record_key', 'version']), 'order' => $order->only(['id', 'number']),
|
|
'documents' => $documents, 'types' => self::TYPES, 'canWrite' => $actor->hasFunctions(['import_prepare']),
|
|
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
|
});
|
|
}
|
|
|
|
/** @param array<string,mixed> $input */
|
|
public function record(User $actor, SupplyRecord $import, array $input, UploadedFile $file): SupplyRecord
|
|
{
|
|
abort_unless($this->ready(), 503);
|
|
$data = Validator::make(['record_key' => null, 'version' => 0, ...$input, 'file' => $file], [
|
|
'operation_key' => 'required|uuid', 'record_key' => 'present|nullable|uuid', 'version' => 'required|integer|min:0',
|
|
'type' => 'required|in:'.implode(',', array_keys(self::TYPES)), 'reference' => 'required|string|min:1|max:180',
|
|
'issued_on' => 'nullable|date_format:Y-m-d', 'issuer_reference' => 'required|string|min:1|max:180',
|
|
'notes' => 'nullable|string|max:4000', 'reason' => 'required|string|min:10|max:4000',
|
|
'file' => 'required|file|mimes:pdf,jpg,jpeg,png|extensions:pdf,jpg,jpeg,png|max:2048',
|
|
])->validate();
|
|
unset($data['file']);
|
|
$data['operation_key'] = strtolower($data['operation_key']);
|
|
$data['reference'] = trim($data['reference']);
|
|
$data['issuer_reference'] = trim($data['issuer_reference']);
|
|
abort_unless($data['reference'] !== '' && $data['issuer_reference'] !== '', 422);
|
|
$sha = hash_file('sha256', $file->getPathname());
|
|
abort_unless(is_string($sha) && $file->getSize() > 0, 422);
|
|
$hash = hash('sha256', json_encode([$import->record_key, $data, $sha], JSON_THROW_ON_ERROR));
|
|
$newPath = null;
|
|
try {
|
|
return DB::transaction(function () use ($actor, $import, $data, $file, $sha, $hash, &$newPath): SupplyRecord {
|
|
[$actor, $current, $order] = $this->context($actor, $import, true);
|
|
$replay = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
|
if ($replay !== null) {
|
|
abort_unless($replay->kind === 'import_document' && $replay->created_by === $actor->id && hash_equals($replay->input_hash, $hash), 409);
|
|
|
|
return $replay;
|
|
}
|
|
$previous = $data['record_key'] === null ? null : SupplyRecord::query()->where('kind', 'import_document')
|
|
->where('record_key', $data['record_key'])->latest('version')->lockForUpdate()->firstOrFail();
|
|
abort_unless((int) $data['version'] === ($previous->version ?? 0), 409, 'O documento mudou. Consulte a versão actual.');
|
|
if ($previous !== null) {
|
|
abort_unless($previous->purchase_order_id === $order->id && $previous->snapshot['import_key'] === $current->record_key
|
|
&& $previous->data['type'] === $data['type'], 409, 'Uma correcção conserva a importação e o tipo documental.');
|
|
}
|
|
abort_if(SupplyRecord::query()->where('kind', 'import_document')->where('purchase_order_id', $order->id)
|
|
->when($previous !== null, fn ($q) => $q->where('record_key', '!=', $previous->record_key))
|
|
->where('data->type', $data['type'])->where('data->reference', $data['reference'])
|
|
->where('data->issuer_reference', $data['issuer_reference'])->exists(), 409, 'Documento já registado. Consulte ou corrija a versão existente.');
|
|
$key = $previous->record_key ?? (string) Str::uuid();
|
|
$version = ($previous->version ?? 0) + 1;
|
|
$newPath = $file->storeAs('import-dossier/'.$actor->tenant_id.'/'.$order->id, $key.'-'.$version.'.'.$file->extension(), 'local');
|
|
abort_unless(is_string($newPath), 503, 'Não foi possível conservar o original privado.');
|
|
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_document', 'record_key' => $key,
|
|
'version' => $version, 'state' => 'recorded', 'purchase_order_id' => $order->id, 'created_by' => $actor->id,
|
|
'data' => array_diff_key($data, array_flip(['operation_key', 'record_key', 'version', 'reason'])),
|
|
'snapshot' => ['import_key' => $current->record_key, 'import_version' => $current->version, 'supersedes' => $previous->id ?? null,
|
|
'evidence' => ['disk' => 'local', 'path' => $newPath, 'sha256' => $sha, 'size' => $file->getSize(), 'mime_type' => $file->getMimeType()],
|
|
'financial_effects' => false, 'external_submission' => false],
|
|
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
|
app(ImportEvidence::class)->bytes($record);
|
|
app(RequisitionWorkflow::class)->audit($actor, 'import.document_recorded', Requisition::query()->whereKey($order->requisition_id)->firstOrFail(), null,
|
|
['record_id' => $record->id, 'record_key' => $record->record_key, 'version' => $version, 'type' => $data['type'], 'sha256' => $sha, 'financial_effects' => false]);
|
|
|
|
return $record;
|
|
});
|
|
} catch (\Throwable $error) {
|
|
if (is_string($newPath) && ! DB::table('supply_records')->where('tenant_id', $actor->tenant_id)->where('snapshot->evidence->path', $newPath)->exists()) {
|
|
Storage::disk('local')->delete($newPath);
|
|
}
|
|
throw $error;
|
|
}
|
|
}
|
|
|
|
public function evidence(User $actor, SupplyRecord $import, int $id): SupplyRecord
|
|
{
|
|
return DB::transaction(function () use ($actor, $import, $id): SupplyRecord {
|
|
[, $current, $order] = $this->context($actor, $import);
|
|
$document = SupplyRecord::query()->where('kind', 'import_document')->where('purchase_order_id', $order->id)
|
|
->where('snapshot->import_key', $current->record_key)->whereKey($id)->firstOrFail();
|
|
app(ImportEvidence::class)->bytes($document);
|
|
|
|
return $document;
|
|
});
|
|
}
|
|
}
|