@@ -0,0 +1,58 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\CapitalAssignments;
|
||||||
|
use App\Services\CapitalRegister;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class CapitalRegisterController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, CapitalRegister $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$filters = $request->validate(['page' => 'nullable|integer|min:1|max:1000000', 'history' => 'nullable|uuid', 'history_page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
'origins_page' => 'nullable|integer|min:1|max:1000000', 'receipts_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
$props = $service->workspace($actor, $filters['history'] ?? null);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('equipment/capital-register', $props)->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, CapitalRegister $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->save($actor, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Versão do cadastro preservada.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function assignments(Request $request, Requisition $requisition, CapitalAssignments $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$request->validate(['choices_page' => 'nullable|integer|min:1|max:1000000', 'history_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('requisitions/capital-assignments', $service->workspace($actor, $requisition))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function assign(Request $request, Requisition $requisition, CapitalAssignments $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->save($actor, $requisition, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Ligação documental preservada.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ use App\Models\StockMovement;
|
|||||||
use App\Models\StockOperation;
|
use App\Models\StockOperation;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\AdministrativeGeography;
|
use App\Services\AdministrativeGeography;
|
||||||
|
use App\Services\CapitalRegister;
|
||||||
use App\Services\ConflictGuard;
|
use App\Services\ConflictGuard;
|
||||||
use App\Services\CurrentActor;
|
use App\Services\CurrentActor;
|
||||||
use App\Services\EquipmentWarehouseRequests;
|
use App\Services\EquipmentWarehouseRequests;
|
||||||
@@ -117,6 +118,7 @@ class EquipmentController extends Controller
|
|||||||
'departments' => $departments->orderBy('name')->get(['id', 'name']),
|
'departments' => $departments->orderBy('name')->get(['id', 'name']),
|
||||||
'history' => StockOperation::query()->whereNotNull('equipment_id')->whereIn('equipment_id', $equipment->pluck('id'))->latest('id')->paginate(15),
|
'history' => StockOperation::query()->whereNotNull('equipment_id')->whereIn('equipment_id', $equipment->pluck('id'))->latest('id')->paginate(15),
|
||||||
'canManage' => $this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement]),
|
'canManage' => $this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement]),
|
||||||
|
'capitalRegisterReady' => app(CapitalRegister::class)->ready(),
|
||||||
'canConfigure' => $this->actor($request)->hasFunctions([PurchasingRole::Admin]),
|
'canConfigure' => $this->actor($request)->hasFunctions([PurchasingRole::Admin]),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ImportBankSupport;
|
||||||
|
use App\Services\ImportDossier;
|
||||||
|
use Illuminate\Http\RedirectResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class ImportBankSupportController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, SupplyRecord $import, ImportBankSupport $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$request->validate(['bank_current_page' => 'nullable|integer|min:1|max:1000000', 'bank_history_page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
'bank_documents_page' => 'nullable|integer|min:1|max:1000000']);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('supply/import-bank-support', $service->workspace($actor, $import))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, SupplyRecord $import, ImportBankSupport $service): RedirectResponse
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->save($actor, $import, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Acompanhamento documental bancário versionado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function export(Request $request, SupplyRecord $import, ImportBankSupport $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->assertReadable($actor, $import);
|
||||||
|
|
||||||
|
return response()->streamDownload(function () use ($actor, $import, $service) {
|
||||||
|
$output = fopen('php://output', 'w');
|
||||||
|
if ($output === false) {
|
||||||
|
throw new \RuntimeException('Não foi possível exportar o acompanhamento bancário.');
|
||||||
|
}
|
||||||
|
$text = fn ($value) => preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', (string) $value) ? "'".$value : $value;
|
||||||
|
fwrite($output, "\xEF\xBB\xBF");
|
||||||
|
fputcsv($output, ['Acompanhamento documental bancário', 'Gerado em', now()->toIso8601String(), 'Não certifica cumprimento nem executa transferências ou submissões JUE'], ';', '"', '');
|
||||||
|
fputcsv($output, ['Termo', 'Versão', 'Situação registada', 'Documento único / declaração', 'Requisitos conhecidos', 'Tipos e quantidades pedidos', 'Fonte dos requisitos',
|
||||||
|
'Suportes seleccionados', 'Comprovativo de entrega', 'Data efectiva da entrega documentada', 'Fundamento da entrega', 'Prazo documental', 'Fonte do prazo', 'Alertas actuais', 'Motivo'], ';', '"', '');
|
||||||
|
$service->report($actor, $import, function (SupplyRecord $record, array $issues) use ($output, $text) {
|
||||||
|
$documents = [];
|
||||||
|
foreach ($record->snapshot['documents'] as $document) {
|
||||||
|
$documents[$document['id']] = $document;
|
||||||
|
}
|
||||||
|
$reference = fn ($id) => $id === null ? 'Por associar' : ($documents[$id]['reference'] ?? 'Indeterminado');
|
||||||
|
$requirements = [];
|
||||||
|
foreach ($record->data['required_support_counts'] as $type => $count) {
|
||||||
|
$requirements[] = ImportDossier::TYPES[$type].': '.$count;
|
||||||
|
}
|
||||||
|
$state = match ($record->state) {
|
||||||
|
'ready' => 'Documentos reunidos; entrega por documentar', 'documented' => 'Comprovativo de entrega associado', default => 'Documentação incompleta'
|
||||||
|
};
|
||||||
|
fputcsv($output, array_map($text, [$reference($record->data['commitment_document_id']), $record->version, $state,
|
||||||
|
$reference($record->data['declaration_document_id']), $record->data['requirements_known'] ? 'Sim' : 'Desconhecidos',
|
||||||
|
$record->data['requirements_known'] ? (implode(' | ', $requirements) ?: 'Nenhum tipo exigido segundo a fonte registada') : 'Desconhecidos', $record->data['requirements_basis'],
|
||||||
|
implode(' | ', array_map($reference, $record->data['support_document_ids'])), $reference($record->data['submission_document_id']), $record->data['submitted_on'] ?? 'Desconhecida', $record->data['submission_basis'] ?? 'Por indicar',
|
||||||
|
$record->data['due_on'] ?? 'Desconhecido', $record->data['deadline_basis'] ?? 'Não indicado', implode(' | ', $issues), $record->reason]), ';', '"', '');
|
||||||
|
});
|
||||||
|
fclose($output);
|
||||||
|
}, 'suporte-bancario-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,9 +4,11 @@ namespace App\Http\Controllers;
|
|||||||
|
|
||||||
use App\Models\SupplyRecord;
|
use App\Models\SupplyRecord;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Services\ImportBankSupport;
|
||||||
use App\Services\ImportDossier;
|
use App\Services\ImportDossier;
|
||||||
use App\Services\ImportEvidence;
|
use App\Services\ImportEvidence;
|
||||||
use App\Services\ImportParties;
|
use App\Services\ImportParties;
|
||||||
|
use App\Services\ImportReadiness;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Http\UploadedFile;
|
use Illuminate\Http\UploadedFile;
|
||||||
use Inertia\Inertia;
|
use Inertia\Inertia;
|
||||||
@@ -28,7 +30,8 @@ final class ImportDossierController extends Controller
|
|||||||
Inertia::encryptHistory();
|
Inertia::encryptHistory();
|
||||||
$actor = $this->actor($request);
|
$actor = $this->actor($request);
|
||||||
$response = Inertia::render('supply/import-dossier', [...$service->workspace($actor, $import),
|
$response = Inertia::render('supply/import-dossier', [...$service->workspace($actor, $import),
|
||||||
'parties' => app(ImportParties::class)->workspace($actor, $import, $search)])->toResponse($request);
|
'parties' => app(ImportParties::class)->workspace($actor, $import, $search),
|
||||||
|
'bankSupportReady' => app(ImportBankSupport::class)->ready(), 'readinessReady' => app(ImportReadiness::class)->ready()])->toResponse($request);
|
||||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
return $response;
|
return $response;
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Requisition;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ImportEvidence;
|
||||||
|
use App\Services\ImportLegalEstimates;
|
||||||
|
use App\Services\ImportLegalRules;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class ImportLegalController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, Requisition $requisition, ImportLegalRules $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$filters = $request->validate(['rules_page' => 'nullable|integer|min:1|max:1000000', 'legal_history_page' => 'nullable|integer|min:1|max:1000000', 'legal_sources_page' => 'nullable|integer|min:1|max:1000000', 'legal_estimates_page' => 'nullable|integer|min:1|max:1000000',
|
||||||
|
'code' => 'nullable|string|max:40', 'origin' => 'nullable|string|max:120', 'sector' => 'nullable|string|max:160', 'date' => 'nullable|date_format:Y-m-d']);
|
||||||
|
$workspace = $service->workspace($actor, $requisition);
|
||||||
|
$date = $filters['date'] ?? today()->toDateString();
|
||||||
|
$suggestions = empty($filters['code']) ? [] : $service->suggestions($actor, $requisition, $filters['code'], $filters['origin'] ?? '', $filters['sector'] ?? '', $date);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
|
||||||
|
$response = Inertia::render('supply/import-legal', [...$workspace, 'filters' => [...$filters, 'date' => $date], 'suggestions' => $suggestions])->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function store(Request $request, Requisition $requisition, ImportLegalRules $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->workspace($actor, $requisition);
|
||||||
|
$service->save($actor, $request->except('file'), $request->file('file'));
|
||||||
|
|
||||||
|
return back()->with('success', 'Versão da base legal registada.');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function source(Request $request, Requisition $requisition, int $source, ImportLegalRules $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$record = $service->source($actor, $requisition, $source);
|
||||||
|
$bytes = app(ImportEvidence::class)->bytes($record);
|
||||||
|
|
||||||
|
return response($bytes, 200, ['Content-Type' => 'application/octet-stream', 'Content-Disposition' => 'attachment; filename="fonte-legal-'.$record->id.'.'.pathinfo($record->snapshot['evidence']['path'], PATHINFO_EXTENSION).'"',
|
||||||
|
'Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function estimate(Request $request, Requisition $requisition, ImportLegalEstimates $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
$service->save($actor, $requisition, $request->all());
|
||||||
|
|
||||||
|
return back()->with('success', 'Estimativa documentada; sem efeitos financeiros ou pagamentos.');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ImportReadiness;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Inertia\Inertia;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
final class ImportReadinessController extends Controller
|
||||||
|
{
|
||||||
|
public function index(Request $request, SupplyRecord $import, ImportReadiness $service): Response
|
||||||
|
{
|
||||||
|
$actor = $request->user('web');
|
||||||
|
abort_unless($actor instanceof User, 403);
|
||||||
|
Inertia::encryptHistory();
|
||||||
|
$response = Inertia::render('supply/import-readiness', $service->workspace($actor, $import))->toResponse($request);
|
||||||
|
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,6 +13,7 @@ use App\Models\TechnicalReview;
|
|||||||
use App\Models\Tenant;
|
use App\Models\Tenant;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\ApprovalRouting;
|
use App\Services\ApprovalRouting;
|
||||||
|
use App\Services\CapitalRegister;
|
||||||
use App\Services\ComparisonPolicy;
|
use App\Services\ComparisonPolicy;
|
||||||
use App\Services\ConflictGuard;
|
use App\Services\ConflictGuard;
|
||||||
use App\Services\EquipmentWorkflow;
|
use App\Services\EquipmentWorkflow;
|
||||||
@@ -125,6 +126,7 @@ class RequisitionController extends Controller
|
|||||||
'canEdit' => app(OrganizationAccess::class)->canRequest($this->actor($request)) && $requisition->requester_id === $this->actor($request)->id && $requisition->status === 'draft',
|
'canEdit' => app(OrganizationAccess::class)->canRequest($this->actor($request)) && $requisition->requester_id === $this->actor($request)->id && $requisition->status === 'draft',
|
||||||
'importTariffsReady' => app(ImportTariffCodes::class)->ready(),
|
'importTariffsReady' => app(ImportTariffCodes::class)->ready(),
|
||||||
'importEstimatesReady' => app(ImportEstimates::class)->ready(),
|
'importEstimatesReady' => app(ImportEstimates::class)->ready(),
|
||||||
|
'capitalRegisterReady' => app(CapitalRegister::class)->ready(),
|
||||||
'canDecide' => $requisition->canDecide($this->actor($request)),
|
'canDecide' => $requisition->canDecide($this->actor($request)),
|
||||||
'canPrepareDistributions' => app(RequisitionBudgetDistributions::class)->ready() && $requisition->status === 'draft'
|
'canPrepareDistributions' => app(RequisitionBudgetDistributions::class)->ready() && $requisition->status === 'draft'
|
||||||
&& $requisition->requester_id === $this->actor($request)->id && app(OrganizationAccess::class)->canRequest($this->actor($request)),
|
&& $requisition->requester_id === $this->actor($request)->id && app(OrganizationAccess::class)->canRequest($this->actor($request)),
|
||||||
|
|||||||
@@ -5,7 +5,11 @@ namespace App\Models;
|
|||||||
use App\Models\Concerns\BelongsToTenant;
|
use App\Models\Concerns\BelongsToTenant;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
/** @property int $lot_id */
|
/**
|
||||||
|
* @property int $lot_id
|
||||||
|
* @property int $stock_item_id
|
||||||
|
* @property int $warehouse_id
|
||||||
|
*/
|
||||||
class InventoryLotAllocation extends Model
|
class InventoryLotAllocation extends Model
|
||||||
{
|
{
|
||||||
use BelongsToTenant;
|
use BelongsToTenant;
|
||||||
|
|||||||
@@ -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,
|
'documents_checked' => 0, 'files_checked' => 0, 'missing' => 0, 'altered' => 0,
|
||||||
'invalid_reference' => 0, 'unreferenced' => 0, 'reasons' => []];
|
'invalid_reference' => 0, 'unreferenced' => 0, 'reasons' => []];
|
||||||
$disk = Storage::disk('local');
|
$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;
|
$limited = $records->count() > $limit;
|
||||||
$root = realpath($disk->path(''));
|
$root = realpath($disk->path(''));
|
||||||
foreach ($records->take($limit) as $record) {
|
foreach ($records->take($limit) as $record) {
|
||||||
$result['documents_checked']++;
|
$result['documents_checked']++;
|
||||||
$snapshot = json_decode($record->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
$snapshot = json_decode($record->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||||
$evidence = $snapshot['evidence'] ?? [];
|
$evidence = $snapshot['evidence'] ?? [];
|
||||||
$directory = $record->kind === 'import_cost_doc' ? 'import-costs' : 'import-dossier';
|
$directory = match ($record->kind) {
|
||||||
$prefix = $directory.'/'.$record->tenant_id.'/'.$record->purchase_order_id.'/';
|
'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;
|
$path = $evidence['path'] ?? null;
|
||||||
if (($evidence['disk'] ?? null) !== 'local' || ! is_string($path)
|
if (($evidence['disk'] ?? null) !== 'local' || ! is_string($path)
|
||||||
|| ! preg_match('/^[a-f0-9-]{36}$/D', $record->record_key)
|
|| ! 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)
|
|| ! 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'])
|
|| ! 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']++;
|
$result['invalid_reference']++;
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
@@ -69,7 +71,7 @@ final class ImportCostDocumentHealth
|
|||||||
$result['altered']++;
|
$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) {
|
foreach ($disk->getDriver()->listContents($directory, true) as $entry) {
|
||||||
if (! $entry->isFile()) {
|
if (! $entry->isFile()) {
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ final class ImportEstimates
|
|||||||
$latest = $this->current($request);
|
$latest = $this->current($request);
|
||||||
|
|
||||||
return ['requisition' => $request->only(['id', 'number', 'status', 'subtotal_minor', 'tax_minor', 'total_minor']),
|
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),
|
'latest' => $latest, 'nativeChanged' => $latest !== null && $latest->snapshot['native'] !== $this->native($request),
|
||||||
'history' => SupplyRecord::query()->where('kind', 'import_estimate')->where('data->requisition_id', $request->id)
|
'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(),
|
->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($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['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.');
|
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();
|
$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,
|
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.');
|
'O orçamento da estimativa mudou. Reveja a preparação.');
|
||||||
@@ -199,6 +203,8 @@ final class ImportEstimates
|
|||||||
abort_unless($this->ready(), 503);
|
abort_unless($this->ready(), 503);
|
||||||
$data = Validator::make($input, [
|
$data = Validator::make($input, [
|
||||||
'operation_key' => 'required|uuid', 'version' => 'required|integer|min:0', 'budget_id' => 'required|integer|min:1',
|
'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' => '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.*.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',
|
'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('kind', $request->items()->where('purchase_type', 'equipment')->exists() ? 'investment' : 'operating')
|
||||||
->where('year', now()->year)->whereNotNull('approved_by')->firstOrFail();
|
->where('year', now()->year)->whereNotNull('approved_by')->firstOrFail();
|
||||||
$native = $this->native($request);
|
$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));
|
$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 = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_estimate',
|
||||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
||||||
'state' => $plan['complete'] ? 'prepared' : 'incomplete', 'created_by' => $actor->id,
|
'state' => $plan['complete'] ? 'prepared' : 'incomplete', 'created_by' => $actor->id,
|
||||||
'data' => ['requisition_id' => $request->id, 'budget_id' => $budget->id, 'components' => $data['components']],
|
'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()]);
|
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
||||||
app(RequisitionWorkflow::class)->audit($actor, 'import.estimate_prepared', $request, null,
|
app(RequisitionWorkflow::class)->audit($actor, 'import.estimate_prepared', $request, null,
|
||||||
['record_id' => $record->id, 'version' => $record->version, 'complete' => $plan['complete'], 'financial_effects' => false]);
|
['record_id' => $record->id, 'version' => $record->version, 'complete' => $plan['complete'], 'financial_effects' => false]);
|
||||||
|
|||||||
@@ -15,14 +15,15 @@ final class ImportEvidence
|
|||||||
$prefix = match ($record->kind) {
|
$prefix = match ($record->kind) {
|
||||||
'import_cost_doc' => 'import-costs',
|
'import_cost_doc' => 'import-costs',
|
||||||
'import_document' => 'import-dossier',
|
'import_document' => 'import-dossier',
|
||||||
|
'import_legal_source' => 'import-legal',
|
||||||
default => null,
|
default => null,
|
||||||
};
|
};
|
||||||
$path = $evidence['path'] ?? 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)
|
abort_unless($prefix !== null && preg_match('/^[a-f0-9-]{36}$/D', $record->record_key)
|
||||||
&& ($evidence['disk'] ?? null) === 'local' && is_string($path)
|
&& ($evidence['disk'] ?? null) === 'local' && is_string($path)
|
||||||
&& preg_match('/^'.preg_quote($expected, '/').'\.(pdf|jpg|jpeg|png)$/D', $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,
|
&& is_string($evidence['sha256'] ?? null) && preg_match('/^[a-f0-9]{64}$/D', $evidence['sha256']), 409,
|
||||||
'A referência do original privado está incompleta.');
|
'A referência do original privado está incompleta.');
|
||||||
$disk = Storage::disk('local');
|
$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.');
|
'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,
|
$result[$item->id] = ['record_id' => $record->id, 'version' => $record->version,
|
||||||
'requisition_item_id' => $item->id, 'item' => $record->snapshot['item'], 'data' => $record->data,
|
'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);
|
ksort($result, SORT_NUMERIC);
|
||||||
|
|
||||||
@@ -72,7 +73,11 @@ final class ImportTariffCodes
|
|||||||
$stockItems->through(fn ($item) => [...$item->only(['id', 'code', 'name', 'unit']),
|
$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'])]);
|
'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]),
|
'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]),
|
'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'))
|
'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',
|
'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',
|
'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]/',
|
'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']);
|
$data['operation_key'] = strtolower($data['operation_key']);
|
||||||
$hash = hash('sha256', json_encode([$request->id, $data], JSON_THROW_ON_ERROR));
|
$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.');
|
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']];
|
$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';
|
$state = 'proposed';
|
||||||
} else {
|
} 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 !== 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.');
|
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,
|
$payload = [...$old->data, 'confirmed_code' => $code, 'confirmation_source' => $source,
|
||||||
'deviation' => $code !== $old->data['proposed_code'], 'confirmed_by' => $actor->id];
|
'deviation' => $code !== $old->data['proposed_code'], 'confirmed_by' => $actor->id];
|
||||||
$snapshot = [...$old->snapshot, 'confirmed_by' => ['id' => $actor->id, 'name' => $actor->name]];
|
$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);
|
$prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection);
|
||||||
abort_unless(hash_equals($prepared['fingerprint'], $data['fingerprint']), 409, 'A preparação mudou; consulte as origens actuais.');
|
abort_unless(hash_equals($prepared['fingerprint'], $data['fingerprint']), 409, 'A preparação mudou; consulte as origens actuais.');
|
||||||
$this->checkAllocations($actor, $prepared['sources'], $budgetSources);
|
$this->checkAllocations($actor, $prepared['sources'], $budgetSources);
|
||||||
$frames = $requests = $lines = $catalogue = $tariffs = [];
|
$frames = $requests = $lines = $catalogue = $tariffs = $capital = [];
|
||||||
$firstQuote = null;
|
$firstQuote = null;
|
||||||
foreach ($prepared['sources'] as $source) {
|
foreach ($prepared['sources'] as $source) {
|
||||||
$request = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
|
$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.');
|
'Preserve os intervenientes e as referências de cada origem.');
|
||||||
$requested = $request->items()->get()->keyBy('id');
|
$requested = $request->items()->get()->keyBy('id');
|
||||||
$tariffs += app(ImportTariffCodes::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_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) {
|
foreach ($source['items'] as $item) {
|
||||||
$native = $requested->get($item['requisition_item_id']);
|
$native = $requested->get($item['requisition_item_id']);
|
||||||
abort_unless($native !== null, 409);
|
abort_unless($native !== null, 409);
|
||||||
@@ -240,7 +241,7 @@ final class OrderPartsWorkflow
|
|||||||
$exchange = $foreign ? ['exchange_basis' => null,
|
$exchange = $foreign ? ['exchange_basis' => null,
|
||||||
'exchange_sources' => array_map(fn ($s) => ['requisition_id' => $s['requisition_id'], 'exchange_basis' => $s['exchange_basis']], $prepared['sources']),
|
'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'))] : [];
|
'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']),
|
'supplier' => $firstQuote->supplier?->only(['id', 'name', 'nuit', 'contact', 'email', 'phone', 'address']),
|
||||||
'issuer' => $actor->only(['id', 'name']), 'items' => $lines, 'catalogue_sources' => $catalogue,
|
'issuer' => $actor->only(['id', 'name']), 'items' => $lines, 'catalogue_sources' => $catalogue,
|
||||||
'budget_control' => $commit, 'development_only' => true, 'budget_checked' => true,
|
'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'));
|
$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 = [
|
$snapshot = [
|
||||||
|
...($capital === [] ? [] : ['capital_assignments' => $capital]),
|
||||||
...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]),
|
...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]),
|
||||||
...app(AgreementOrderLimits::class)->freeze($user, $quote, $requisition, $lines, $agreementBindings),
|
...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)]),
|
...($quote->exchange_basis === null ? [] : ['exchange_basis' => $quote->exchange_basis, 'reference_amounts' => app(QuotationExchange::class)->amounts($quote)]),
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return ['qa_enabled' => false];
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return ['qa_enabled' => false];
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return ['qa_enabled' => false];
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return ['qa_enabled' => false];
|
||||||
@@ -1,7 +1,17 @@
|
|||||||
# Desenvolvimento do SGC
|
# Desenvolvimento do SGC
|
||||||
|
|
||||||
|
Decisão expressa nesta continuação: projectos e imobilizado terão cadastro próprio em Compras, independente do SGF. Implementação em curso, apenas QA, sem efeitos contabilísticos nem instalação no piloto. Reutilizar as fichas físicas de equipamento existentes; não criar dependência SGF. Revisão bancária nativa posterior gravou versão 2 com comprovativo/data/fundamento sintéticos, conservou versão 1 e retirou os avisos de entrega pendente/prazo de hoje. Ambiente privado encerrado e removido.
|
||||||
|
|
||||||
|
Revisão nativa posterior em Edge: base legal observada a 390/823px sem transbordo horizontal; reutilização explícita da base sintética de 100 MZN gravou versão 2 de 7,50 MZN. Plano anterior conservou a origem escolhida #5 e total 107,50 MZN. Acompanhamento apresentou desconhecidos e pendências bancárias esperados. Servidor/raiz/base QA removidos, separadores do utilizador preservados. Prova ampliada em `proofs/import-legal-amounts-qa.json`. Esta revisão substitui apenas a indicação de revisão ainda não iniciada; impressão e aceitação visual transversal continuam por verificar.
|
||||||
|
|
||||||
## Continuação integral — 27/11/2026
|
## Continuação integral — 27/11/2026
|
||||||
|
|
||||||
|
Estimativa documentada de imposições e adopção no plano nativo também implementadas em QA (`proofs/import-legal-amounts-qa.json`): aritmética decimal exacta, taxas/bases/unidades e condições explícitas, desconhecido indeterminado, fonte/versão preservadas, escolha humana e divisão base/imposto sem pressupor recuperabilidade. Uma imposição não pode ser repetida em duas parcelas ligadas à mesma origem. Publicação futura conserva o período anterior aplicável; fonte retirada exige revisão antes da aprovação. PostgreSQL57/919, concorrência e restauro com cálculo750cêntimos/plano10750cêntimos sintéticos e11originais aprovados, bases removidas; frontend180/180, tipos/PHPStan/check/build privado aprovados. HTTP nativo carregou/descarregou15509234bytes do BR real partilhado com mesmoSHA, login/CSRF/repetição/401/403, sem publicar regras ou efeitos financeiros; servidor/base/raiz privados removidos. PHP global conserva limites anteriores; ensaio privado usou64M/70M. Corrigido identificador interno longo detectado pelo PostgreSQL, com regressão nativa. Não declarar conclusão integral nem parar por este incremento; continuar os requisitos e a revisão visual. O host de navegador está indisponível, mas o Edge nativo foi lançado com êxito; revisão ainda não executada. Piloto e fontes reais preservados.
|
||||||
|
|
||||||
|
Base legal documental e acompanhamento contextual de importação implementados em QA (`proofs/import-legal-readiness-qa.json`). Fontes independentes das regras; exemplares até64MB, citação/vigência, preparação/publicação/retirada pela competência aduaneira existente, sugestão explícita e confirmação/desvio pelo comprador, fonte congelada na requisição/ordem/impressão e alerta de alteração sem reescrever decisões. Acompanhamento reutiliza originais, intervenientes, relatório bancário e recepção efectiva; desconhecido/incompleto explícitos, sem notificações automáticas ou novos efeitos financeiros. PostgreSQL integrado36/337 e delta final da base legalSQLite7/54; protocolo8/38; frontend177/177, tipos/PHPStan/check e build privado aprovados. Concorrência legal e recuperação de11originais/versão publicada/contexto do comprador aprovadas; bases removidas. Legislação já partilhada localizada: inventário8109ficheiros (inclui ocultos); quatro exemplares oficiais reais conferidos em empresaQA sintética, sem publicar regras nem alterar originais. Continuar cálculo documentado de imposições, demais regras/alertas e lacunas transversais; não encerrar a aplicação por este incremento. Navegador novamente indisponível na API actual, sem navegador nativo enumerado; revisão visual permanece pendente. Piloto conserva manifesto1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e, sem instalação/activação.
|
||||||
|
|
||||||
|
Suporte documental bancário concluído em QA: termo ligado ao DU/declaração, tipos e quantidades explícitos, fonte do prazo, data efectiva/comprovativo da entrega, versões, alertas e CSV integral. Desconhecido permanece por indicar; sem activação de regras legais, transferências ou submissões JUE. Prova `proofs/import-bank-support-qa.json`: PostgreSQL39/324, concorrência200/200 e200/409 com um efeito/uma auditoria, recuperação de duas versões bancárias e dez originais privados, bases removidas; frontend172/172, tipos/PHPStan/Pint/check e build privado aprovados. Este delta substitui apenas a pendência de acompanhamento bancário abaixo. Sugestões legais versionadas, revisão visual/móvel/impressão e preparação operacional continuam abertas; não instalar/activar por inferência. Preservar as provas, sem repetir suites aprovadas sem delta.
|
||||||
|
|
||||||
Estimativas: `ImportEstimates`/formulário nativo/ajuda conservam pressupostos por versão antes dos documentos. `BudgetImportEstimate` e capacidade comum opcional reservam apenas extras no diário existente; o percurso nativo usa o custo integral para todos os níveis, sem alterar os bens. Rejeição liberta ambas as reservas na mesma transacção. `reconcileImportEstimate` e formulário de Finanças fazem a libertação parcial e a aplicação documental atomicamente, incluindo várias origens/mesmo plano e planos só de facturas nativas. Guardas preservam identidade, orçamento, revisões e consumo, rejeitam duplicação por outra chave e ignoram paginação na autoridade. A fonte prévia v2 foi congelada apenas num directório QA privado para provar a recusa de downgrade. Prova `proofs/import-estimates-qa.json`: nativoPG6/70, contrato22/156, aprovações32/737, importação40/286, concorrência/recuperação, frontend169/169, tipos/PHPStan/build privado aprovados. Corrigidas as inconsistências do próprio ensaio: identidades de operação distintas, orçamento sintético criado/aprovado por Finanças, agregados PostgreSQL e ajuda contextual em falta. Sem alterações operacionais.
|
Estimativas: `ImportEstimates`/formulário nativo/ajuda conservam pressupostos por versão antes dos documentos. `BudgetImportEstimate` e capacidade comum opcional reservam apenas extras no diário existente; o percurso nativo usa o custo integral para todos os níveis, sem alterar os bens. Rejeição liberta ambas as reservas na mesma transacção. `reconcileImportEstimate` e formulário de Finanças fazem a libertação parcial e a aplicação documental atomicamente, incluindo várias origens/mesmo plano e planos só de facturas nativas. Guardas preservam identidade, orçamento, revisões e consumo, rejeitam duplicação por outra chave e ignoram paginação na autoridade. A fonte prévia v2 foi congelada apenas num directório QA privado para provar a recusa de downgrade. Prova `proofs/import-estimates-qa.json`: nativoPG6/70, contrato22/156, aprovações32/737, importação40/286, concorrência/recuperação, frontend169/169, tipos/PHPStan/build privado aprovados. Corrigidas as inconsistências do próprio ensaio: identidades de operação distintas, orçamento sintético criado/aprovado por Finanças, agregados PostgreSQL e ajuda contextual em falta. Sem alterações operacionais.
|
||||||
|
|
||||||
Delta: `ImportParties` e formulário nativo seleccionam despachante/transitário elegível, com versão do fornecedor e instrução escrita, comprador independente, conflitos, histórico e revalidação logística. Prova `proofs/import-parties-qa.json`: PostgreSQL40/286, concorrência e recuperação de seis originais/duas selecções aprovadas. Correcção do auxiliar CLI preserva os utilizadores sem modificar autenticação real. Despesa por confirmação implementada em `ProcurementPaymentInsights`, leitura auditada através de `SupplierPayables`, painel e CSV próprios; origem externa única, período da confirmação e moedas independentes. Prova `proofs/confirmed-payment-insights-qa.json`: regressãoPG24/515, delta final5/84, frontend2, tipos/PHPStan/build privado aprovados. Sem disponibilização operacional; revisão visual e requisitos restantes continuam abertos.
|
Delta: `ImportParties` e formulário nativo seleccionam despachante/transitário elegível, com versão do fornecedor e instrução escrita, comprador independente, conflitos, histórico e revalidação logística. Prova `proofs/import-parties-qa.json`: PostgreSQL40/286, concorrência e recuperação de seis originais/duas selecções aprovadas. Correcção do auxiliar CLI preserva os utilizadores sem modificar autenticação real. Despesa por confirmação implementada em `ProcurementPaymentInsights`, leitura auditada através de `SupplierPayables`, painel e CSV próprios; origem externa única, período da confirmação e moedas independentes. Prova `proofs/confirmed-payment-insights-qa.json`: regressãoPG24/515, delta final5/84, frontend2, tipos/PHPStan/build privado aprovados. Sem disponibilização operacional; revisão visual e requisitos restantes continuam abertos.
|
||||||
|
|||||||
@@ -1,7 +1,17 @@
|
|||||||
# Matriz reconciliada do SGC — 03/11/2026
|
# Matriz reconciliada do SGC — 03/11/2026
|
||||||
|
|
||||||
|
Decisão expressa nesta continuação: projectos e imobilizado terão cadastro próprio em Compras, independente do SGF. Implementação em curso, apenas QA, sem efeitos contabilísticos nem instalação no piloto. Reutilizar as fichas físicas de equipamento existentes; não criar dependência SGF. Revisão bancária nativa posterior gravou versão 2 com comprovativo/data/fundamento sintéticos, conservou versão 1 e retirou os avisos de entrega pendente/prazo de hoje. Ambiente privado encerrado e removido.
|
||||||
|
|
||||||
|
Revisão nativa posterior em Edge: base legal observada a 390/823px sem transbordo horizontal; reutilização explícita da base sintética de 100 MZN gravou versão 2 de 7,50 MZN. Plano anterior conservou a origem escolhida #5 e total 107,50 MZN. Acompanhamento apresentou desconhecidos e pendências bancárias esperados. Servidor/raiz/base QA removidos, separadores do utilizador preservados. Prova ampliada em `proofs/import-legal-amounts-qa.json`. Esta revisão substitui apenas a indicação de revisão ainda não iniciada; impressão e aceitação visual transversal continuam por verificar.
|
||||||
|
|
||||||
## Continuação integral — 27/11/2026
|
## Continuação integral — 27/11/2026
|
||||||
|
|
||||||
|
Estimativa documentada de imposições e adopção no plano nativo também implementadas em QA (`proofs/import-legal-amounts-qa.json`): aritmética decimal exacta, taxas/bases/unidades e condições explícitas, desconhecido indeterminado, fonte/versão preservadas, escolha humana e divisão base/imposto sem pressupor recuperabilidade. Uma imposição não pode ser repetida em duas parcelas ligadas à mesma origem. Publicação futura conserva o período anterior aplicável; fonte retirada exige revisão antes da aprovação. PostgreSQL57/919, concorrência e restauro com cálculo750cêntimos/plano10750cêntimos sintéticos e11originais aprovados, bases removidas; frontend180/180, tipos/PHPStan/check/build privado aprovados. HTTP nativo carregou/descarregou15509234bytes do BR real partilhado com mesmoSHA, login/CSRF/repetição/401/403, sem publicar regras ou efeitos financeiros; servidor/base/raiz privados removidos. PHP global conserva limites anteriores; ensaio privado usou64M/70M. Corrigido identificador interno longo detectado pelo PostgreSQL, com regressão nativa. Não declarar conclusão integral nem parar por este incremento; continuar os requisitos e a revisão visual. O host de navegador está indisponível, mas o Edge nativo foi lançado com êxito; revisão ainda não executada. Piloto e fontes reais preservados.
|
||||||
|
|
||||||
|
Base legal documental e acompanhamento contextual de importação implementados em QA (`proofs/import-legal-readiness-qa.json`). Fontes independentes das regras; exemplares até64MB, citação/vigência, preparação/publicação/retirada pela competência aduaneira existente, sugestão explícita e confirmação/desvio pelo comprador, fonte congelada na requisição/ordem/impressão e alerta de alteração sem reescrever decisões. Acompanhamento reutiliza originais, intervenientes, relatório bancário e recepção efectiva; desconhecido/incompleto explícitos, sem notificações automáticas ou novos efeitos financeiros. PostgreSQL integrado36/337 e delta final da base legalSQLite7/54; protocolo8/38; frontend177/177, tipos/PHPStan/check e build privado aprovados. Concorrência legal e recuperação de11originais/versão publicada/contexto do comprador aprovadas; bases removidas. Legislação já partilhada localizada: inventário8109ficheiros (inclui ocultos); quatro exemplares oficiais reais conferidos em empresaQA sintética, sem publicar regras nem alterar originais. Continuar cálculo documentado de imposições, demais regras/alertas e lacunas transversais; não encerrar a aplicação por este incremento. Navegador novamente indisponível na API actual, sem navegador nativo enumerado; revisão visual permanece pendente. Piloto conserva manifesto1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e, sem instalação/activação.
|
||||||
|
|
||||||
|
Suporte documental bancário concluído em QA: termo ligado ao DU/declaração, tipos e quantidades explícitos, fonte do prazo, data efectiva/comprovativo da entrega, versões, alertas e CSV integral. Desconhecido permanece por indicar; sem activação de regras legais, transferências ou submissões JUE. Prova `proofs/import-bank-support-qa.json`: PostgreSQL39/324, concorrência200/200 e200/409 com um efeito/uma auditoria, recuperação de duas versões bancárias e dez originais privados, bases removidas; frontend172/172, tipos/PHPStan/Pint/check e build privado aprovados. Este delta substitui apenas a pendência de acompanhamento bancário abaixo. Sugestões legais versionadas, revisão visual/móvel/impressão e preparação operacional continuam abertas; não instalar/activar por inferência. Preservar as provas, sem repetir suites aprovadas sem delta.
|
||||||
|
|
||||||
Estimativa pré-documental integrada em QA: pressupostos versionados, desconhecido distinto de não aplicável, bens nativos preservados, aprovação pelo custo integral, reserva apenas dos encargos e libertação na rejeição. Finanças reconcilia parcelas explícitas com documentos efectivamente conferidos, conservando saldos de outras ordens e sem novo principal de factura. Várias origens podem reconciliar-se no mesmo plano sem repetir o custo efectivo; a paginação não altera a autoridade financeira. PostgreSQL nativo6/70, contrato22/156, regressão de aprovações32/737 e importação/dossiê/logística/saúde40/286 aprovados em bases separadas removidas; contagens não se somam. Concorrência de reserva/reconciliação, recusa dos três motores anteriores e recuperação integral aprovadas, incluindo saldo estimado remanescente e seis originais privados. Frontend169/169, tipos/PHPStan/check/build privado aprovados. Prova `proofs/import-estimates-qa.json`. Fonte canónica e adaptação apenas; sem instalação/activação. Continuam abertos suporte bancário/prazos, sugestões legais versionadas, revisão visual e demais requisitos do produto.
|
Estimativa pré-documental integrada em QA: pressupostos versionados, desconhecido distinto de não aplicável, bens nativos preservados, aprovação pelo custo integral, reserva apenas dos encargos e libertação na rejeição. Finanças reconcilia parcelas explícitas com documentos efectivamente conferidos, conservando saldos de outras ordens e sem novo principal de factura. Várias origens podem reconciliar-se no mesmo plano sem repetir o custo efectivo; a paginação não altera a autoridade financeira. PostgreSQL nativo6/70, contrato22/156, regressão de aprovações32/737 e importação/dossiê/logística/saúde40/286 aprovados em bases separadas removidas; contagens não se somam. Concorrência de reserva/reconciliação, recusa dos três motores anteriores e recuperação integral aprovadas, incluindo saldo estimado remanescente e seis originais privados. Frontend169/169, tipos/PHPStan/check/build privado aprovados. Prova `proofs/import-estimates-qa.json`. Fonte canónica e adaptação apenas; sem instalação/activação. Continuam abertos suporte bancário/prazos, sugestões legais versionadas, revisão visual e demais requisitos do produto.
|
||||||
|
|
||||||
Despesa por período implementada em QA segundo a escolha «pagamentos confirmados»: originais auditados, data de confirmação no fuso da aplicação, moedas separadas, soma exacta, cobertura indeterminada explícita e CSV próprio. O filtro temporal deste indicador não exclui requisições criadas antes da confirmação. As cópias importadas não são somadas de novo; pendentes/rejeitados/preparações não contam. PostgreSQL regressão24/515 e deltaHTTP/CSV5/84 aprovados, bases removidas; dois testes frontend, tipos/PHPStan/check/build privado aprovados. Prova `proofs/confirmed-payment-insights-qa.json`. Não certifica execução bancária nem encerra a análise avançada restante.
|
Despesa por período implementada em QA segundo a escolha «pagamentos confirmados»: originais auditados, data de confirmação no fuso da aplicação, moedas separadas, soma exacta, cobertura indeterminada explícita e CSV próprio. O filtro temporal deste indicador não exclui requisições criadas antes da confirmação. As cópias importadas não são somadas de novo; pendentes/rejeitados/preparações não contam. PostgreSQL regressão24/515 e deltaHTTP/CSV5/84 aprovados, bases removidas; dois testes frontend, tipos/PHPStan/check/build privado aprovados. Prova `proofs/confirmed-payment-insights-qa.json`. Não certifica execução bancária nem encerra a análise avançada restante.
|
||||||
|
|||||||
@@ -1,7 +1,17 @@
|
|||||||
# Continuidade do desenvolvimento do SGC
|
# Continuidade do desenvolvimento do SGC
|
||||||
|
|
||||||
|
Decisão expressa nesta continuação: projectos e imobilizado terão cadastro próprio em Compras, independente do SGF. Implementação em curso, apenas QA, sem efeitos contabilísticos nem instalação no piloto. Reutilizar as fichas físicas de equipamento existentes; não criar dependência SGF. Revisão bancária nativa posterior gravou versão 2 com comprovativo/data/fundamento sintéticos, conservou versão 1 e retirou os avisos de entrega pendente/prazo de hoje. Ambiente privado encerrado e removido.
|
||||||
|
|
||||||
|
Revisão nativa posterior em Edge: base legal observada a 390/823px sem transbordo horizontal; reutilização explícita da base sintética de 100 MZN gravou versão 2 de 7,50 MZN. Plano anterior conservou a origem escolhida #5 e total 107,50 MZN. Acompanhamento apresentou desconhecidos e pendências bancárias esperados. Servidor/raiz/base QA removidos, separadores do utilizador preservados. Prova ampliada em `proofs/import-legal-amounts-qa.json`. Esta revisão substitui apenas a indicação de revisão ainda não iniciada; impressão e aceitação visual transversal continuam por verificar.
|
||||||
|
|
||||||
## Continuação integral — 27/11/2026
|
## Continuação integral — 27/11/2026
|
||||||
|
|
||||||
|
Estimativa documentada de imposições e adopção no plano nativo também implementadas em QA (`proofs/import-legal-amounts-qa.json`): aritmética decimal exacta, taxas/bases/unidades e condições explícitas, desconhecido indeterminado, fonte/versão preservadas, escolha humana e divisão base/imposto sem pressupor recuperabilidade. Uma imposição não pode ser repetida em duas parcelas ligadas à mesma origem. Publicação futura conserva o período anterior aplicável; fonte retirada exige revisão antes da aprovação. PostgreSQL57/919, concorrência e restauro com cálculo750cêntimos/plano10750cêntimos sintéticos e11originais aprovados, bases removidas; frontend180/180, tipos/PHPStan/check/build privado aprovados. HTTP nativo carregou/descarregou15509234bytes do BR real partilhado com mesmoSHA, login/CSRF/repetição/401/403, sem publicar regras ou efeitos financeiros; servidor/base/raiz privados removidos. PHP global conserva limites anteriores; ensaio privado usou64M/70M. Corrigido identificador interno longo detectado pelo PostgreSQL, com regressão nativa. Não declarar conclusão integral nem parar por este incremento; continuar os requisitos e a revisão visual. O host de navegador está indisponível, mas o Edge nativo foi lançado com êxito; revisão ainda não executada. Piloto e fontes reais preservados.
|
||||||
|
|
||||||
|
Base legal documental e acompanhamento contextual de importação implementados em QA (`proofs/import-legal-readiness-qa.json`). Fontes independentes das regras; exemplares até64MB, citação/vigência, preparação/publicação/retirada pela competência aduaneira existente, sugestão explícita e confirmação/desvio pelo comprador, fonte congelada na requisição/ordem/impressão e alerta de alteração sem reescrever decisões. Acompanhamento reutiliza originais, intervenientes, relatório bancário e recepção efectiva; desconhecido/incompleto explícitos, sem notificações automáticas ou novos efeitos financeiros. PostgreSQL integrado36/337 e delta final da base legalSQLite7/54; protocolo8/38; frontend177/177, tipos/PHPStan/check e build privado aprovados. Concorrência legal e recuperação de11originais/versão publicada/contexto do comprador aprovadas; bases removidas. Legislação já partilhada localizada: inventário8109ficheiros (inclui ocultos); quatro exemplares oficiais reais conferidos em empresaQA sintética, sem publicar regras nem alterar originais. Continuar cálculo documentado de imposições, demais regras/alertas e lacunas transversais; não encerrar a aplicação por este incremento. Navegador novamente indisponível na API actual, sem navegador nativo enumerado; revisão visual permanece pendente. Piloto conserva manifesto1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e, sem instalação/activação.
|
||||||
|
|
||||||
|
Suporte documental bancário concluído em QA: termo ligado ao DU/declaração, tipos e quantidades explícitos, fonte do prazo, data efectiva/comprovativo da entrega, versões, alertas e CSV integral. Desconhecido permanece por indicar; sem activação de regras legais, transferências ou submissões JUE. Prova `proofs/import-bank-support-qa.json`: PostgreSQL39/324, concorrência200/200 e200/409 com um efeito/uma auditoria, recuperação de duas versões bancárias e dez originais privados, bases removidas; frontend172/172, tipos/PHPStan/Pint/check e build privado aprovados. Este delta substitui apenas a pendência de acompanhamento bancário abaixo. Sugestões legais versionadas, revisão visual/móvel/impressão e preparação operacional continuam abertas; não instalar/activar por inferência. Preservar as provas, sem repetir suites aprovadas sem delta.
|
||||||
|
|
||||||
Estimativa pré-documental e reconciliação com custos efectivos também concluídas em QA (`proofs/import-estimates-qa.json`). Preservar a capacidade opcional, o saldo estimado por origem, o custo integral nas aprovações e o escritor comum. Não repetir suites aprovadas sem delta: nativoPG6/70, contrato22/156, aprovações32/737, importação40/286, frontend169/169, concorrência e recuperação integral. Fonte e formulário bancário/prazos são a próxima frente; secção10.4 do Word especifica termo de compromisso ligado ao DU/JUE e suporte bancário, mas os seus resumos/prazos não activam regras legais ou execução bancária. O Word mantém o hash aprovado; não foi editado. Rever fontes oficiais e a configuração existente conforme o requisito afectado, sem inventar prazos ou destinatários.
|
Estimativa pré-documental e reconciliação com custos efectivos também concluídas em QA (`proofs/import-estimates-qa.json`). Preservar a capacidade opcional, o saldo estimado por origem, o custo integral nas aprovações e o escritor comum. Não repetir suites aprovadas sem delta: nativoPG6/70, contrato22/156, aprovações32/737, importação40/286, frontend169/169, concorrência e recuperação integral. Fonte e formulário bancário/prazos são a próxima frente; secção10.4 do Word especifica termo de compromisso ligado ao DU/JUE e suporte bancário, mas os seus resumos/prazos não activam regras legais ou execução bancária. O Word mantém o hash aprovado; não foi editado. Rever fontes oficiais e a configuração existente conforme o requisito afectado, sem inventar prazos ou destinatários.
|
||||||
|
|
||||||
Implementados em QA desde a decisão: selecção de intervenientes/instruções escritas (`proofs/import-parties-qa.json`) e indicador/CSV de pagamentos confirmados por data de confirmação (`proofs/confirmed-payment-insights-qa.json`). Preservar estes deltas e os testes aceites; não repetir a escolha da base da despesa. A próxima frente funcional é a estimativa pré-documental e sua integração com aprovação/reserva no núcleo financeiro comum autorizado. A análise avançada restante e a revisão visual não estão concluídas; não instalar/activar por inferência.
|
Implementados em QA desde a decisão: selecção de intervenientes/instruções escritas (`proofs/import-parties-qa.json`) e indicador/CSV de pagamentos confirmados por data de confirmação (`proofs/confirmed-payment-insights-qa.json`). Preservar estes deltas e os testes aceites; não repetir a escolha da base da despesa. A próxima frente funcional é a estimativa pré-documental e sua integração com aprovação/reserva no núcleo financeiro comum autorizado. A análise avançada restante e a revisão visual não estão concluídas; não instalar/activar por inferência.
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
# Entregas por blocos funcionais do SGC
|
# Entregas por blocos funcionais do SGC
|
||||||
|
|
||||||
|
Base legal documental e acompanhamento contextual de importação implementados em QA (`proofs/import-legal-readiness-qa.json`). Fontes independentes das regras; exemplares até64MB, citação/vigência, preparação/publicação/retirada pela competência aduaneira existente, sugestão explícita e confirmação/desvio pelo comprador, fonte congelada na requisição/ordem/impressão e alerta de alteração sem reescrever decisões. Acompanhamento reutiliza originais, intervenientes, relatório bancário e recepção efectiva; desconhecido/incompleto explícitos, sem notificações automáticas ou novos efeitos financeiros. PostgreSQL integrado36/337 e delta final da base legalSQLite7/54; protocolo8/38; frontend177/177, tipos/PHPStan/check e build privado aprovados. Concorrência legal e recuperação de11originais/versão publicada/contexto do comprador aprovadas; bases removidas. Legislação já partilhada localizada: inventário8109ficheiros (inclui ocultos); quatro exemplares oficiais reais conferidos em empresaQA sintética, sem publicar regras nem alterar originais. Continuar cálculo documentado de imposições, demais regras/alertas e lacunas transversais; não encerrar a aplicação por este incremento. Navegador novamente indisponível na API actual, sem navegador nativo enumerado; revisão visual permanece pendente. Piloto conserva manifesto1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e, sem instalação/activação.
|
||||||
|
|
||||||
## Estado reconciliado mais recente - 22/11/2026
|
## Estado reconciliado mais recente - 22/11/2026
|
||||||
|
|
||||||
Ordens parciais/consolidadas em MZN: emissão nativa, origens, recepção, factura com validação independente e cancelamento C2 por Finanças implementados em QA. PostgreSQL 56 testes/498 verificações; delta HTTP final 1/25. A revisão nativa observou uma ordem sintética de 100 MZN, parcelas de 40/60 MZN e apresentação a 390/1000 px. A ferramenta interrompeu o controlo antes da paginação de impressão; restante percurso visual continua pendente. Servidor, base e configuração privados removidos. Prova: `proofs/rq01-multi-order-native-qa.json`. Câmbio por origem, reafectação de Finanças e disponibilização operacional continuam por concluir.
|
Ordens parciais/consolidadas em MZN: emissão nativa, origens, recepção, factura com validação independente e cancelamento C2 por Finanças implementados em QA. PostgreSQL 56 testes/498 verificações; delta HTTP final 1/25. A revisão nativa observou uma ordem sintética de 100 MZN, parcelas de 40/60 MZN e apresentação a 390/1000 px. A ferramenta interrompeu o controlo antes da paginação de impressão; restante percurso visual continua pendente. Servidor, base e configuração privados removidos. Prova: `proofs/rq01-multi-order-native-qa.json`. Câmbio por origem, reafectação de Finanças e disponibilização operacional continuam por concluir.
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
{
|
||||||
|
"date": "2026-11-27",
|
||||||
|
"status": "development_in_isolated_qa_not_installed_not_product_completion",
|
||||||
|
"owner_decision": "Cadastro próprio em Compras, independente do SGF",
|
||||||
|
"implementation": [
|
||||||
|
"Versioned project and asset documentary references owned by Compras",
|
||||||
|
"Existing equipment identities reused without creating duplicate physical records",
|
||||||
|
"Existing equipment register capabilities and department scope reused; no grants",
|
||||||
|
"Immutable codes, archive/history, operation replay and stale-version conflicts",
|
||||||
|
"Explicit draft requisition line assignment by its requester",
|
||||||
|
"Frozen origin in ordinary and partial/consolidated native order snapshots and print",
|
||||||
|
"Later register rename/archive does not rewrite accepted choices or issued orders"
|
||||||
|
],
|
||||||
|
"sqlite_register_and_assignments": {"tests": 7, "assertions": 89, "passed": true},
|
||||||
|
"postgresql_directed_native_integration": {"tests": 11, "assertions": 181, "passed": true, "database_removed": true},
|
||||||
|
"frontend_directed": {"tests": 2, "passed": true},
|
||||||
|
"checks": {"types": "passed", "phpstan": "passed", "scoped_format_lint": "passed", "scoped_pint": "passed", "diff_whitespace": "passed"},
|
||||||
|
"concurrency": {
|
||||||
|
"same_operation": [200, 200], "same_version": [200, 409], "blocked_writers_observed": 2,
|
||||||
|
"new_versions_per_scenario": 1, "audits_per_scenario": 1, "new_files": 0, "database_removed": true,
|
||||||
|
"receipt_protocol_regression": {"tests": 10, "assertions": 46, "passed": true}
|
||||||
|
},
|
||||||
|
"native_edge_review": {
|
||||||
|
"synthetic_project_created_through_native_form": true,
|
||||||
|
"synthetic_line_assignment_saved_through_native_form": true,
|
||||||
|
"assignment_version": 1,
|
||||||
|
"source_version": 1,
|
||||||
|
"history_visible": true,
|
||||||
|
"viewports_observed_px": [390, 823],
|
||||||
|
"private_server_stopped": true, "private_root_removed": true, "database_removed": true,
|
||||||
|
"user_tabs_preserved": true,
|
||||||
|
"layout_follow_up": "Align page padding with native equipment/requisition pages; mobile overflow was not observed."
|
||||||
|
},
|
||||||
|
"private_build": {
|
||||||
|
"path": "storage/framework/testing/sgc-capital-register-qa-20261127",
|
||||||
|
"manifest_sha256": "baaf8095659bb678e449133dfdd07d1862bb89870f8fbcf44fd2d079474faed1",
|
||||||
|
"passed": true
|
||||||
|
},
|
||||||
|
"preserved": {"pilot_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e", "pilot_activated": false, "migration_created": false, "new_financial_or_stock_writer": false, "sgf_dependency": false},
|
||||||
|
"remaining": [
|
||||||
|
"Native receipt-to-asset entry lineage and current correction/return visibility",
|
||||||
|
"Full assignment/account applicability across RQ-01 categories",
|
||||||
|
"Backup/recovery proof for new register and assignments",
|
||||||
|
"Final visual/mobile/print review after remaining implementation",
|
||||||
|
"Other existing matrix gaps and separately scoped operational preparation"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
{
|
||||||
|
"date": "2026-11-27",
|
||||||
|
"status": "implemented_in_isolated_qa_not_installed",
|
||||||
|
"scope": "Documentary bank follow-up: existing commitment, DU/customs declaration, requested counts, explicit deadline source, dated delivery evidence, history, alerts and full-scope CSV",
|
||||||
|
"data": "Synthetic fixtures; unknown requirements/dates remain unknown; no presumed legal deadline",
|
||||||
|
"effects": {
|
||||||
|
"bank_transfer": false,
|
||||||
|
"jue_submission": false,
|
||||||
|
"compliance_certification": false,
|
||||||
|
"new_financial_or_stock_writer": false
|
||||||
|
},
|
||||||
|
"sqlite_directed": {
|
||||||
|
"tests": 10,
|
||||||
|
"assertions": 105,
|
||||||
|
"passed": true,
|
||||||
|
"includes_protocol_unit": true
|
||||||
|
},
|
||||||
|
"postgresql_integration": {
|
||||||
|
"tests": 39,
|
||||||
|
"assertions": 324,
|
||||||
|
"passed": true,
|
||||||
|
"database_removed": true
|
||||||
|
},
|
||||||
|
"concurrency": {
|
||||||
|
"same_operation": [
|
||||||
|
200,
|
||||||
|
200
|
||||||
|
],
|
||||||
|
"conflicting_version": [
|
||||||
|
200,
|
||||||
|
409
|
||||||
|
],
|
||||||
|
"blocked_writers_per_scenario": 2,
|
||||||
|
"new_versions_per_scenario": 1,
|
||||||
|
"audits_per_scenario": 1,
|
||||||
|
"new_files_per_scenario": 0,
|
||||||
|
"originals_verified": true,
|
||||||
|
"database_removed": true
|
||||||
|
},
|
||||||
|
"recovery": {
|
||||||
|
"bank_support_versions_restored": 2,
|
||||||
|
"relationships_restored": true,
|
||||||
|
"replay_without_effect": true,
|
||||||
|
"private_original_versions_restored": 10,
|
||||||
|
"typed_dossier_versions_restored": 8,
|
||||||
|
"selected_party_versions_restored": 2,
|
||||||
|
"previous_tables_preserved": 115,
|
||||||
|
"optional_tables": 2,
|
||||||
|
"post_restore_all_sql_equal": true,
|
||||||
|
"pre_extension_restore_passed": true,
|
||||||
|
"separate_private_root_restored": true,
|
||||||
|
"native_authorized_access_verified": true,
|
||||||
|
"databases_removed": true
|
||||||
|
},
|
||||||
|
"frontend": {
|
||||||
|
"files": 40,
|
||||||
|
"tests": 172,
|
||||||
|
"passed": true,
|
||||||
|
"includes_bank_tests": 3
|
||||||
|
},
|
||||||
|
"checks": {
|
||||||
|
"types": "passed",
|
||||||
|
"phpstan": "passed",
|
||||||
|
"scoped_pint": "passed",
|
||||||
|
"scoped_format_and_lint": "passed",
|
||||||
|
"diff_whitespace": "passed"
|
||||||
|
},
|
||||||
|
"private_build": {
|
||||||
|
"directory": "storage/framework/testing/sgc-import-bank-support-qa-20261127",
|
||||||
|
"exit_code": 0,
|
||||||
|
"manifest_sha256": "55f1cd3adf5382bde4fda5ecca99231cbdd1fdd8b07d46dd166d5c2fb4025a72"
|
||||||
|
},
|
||||||
|
"commands": [
|
||||||
|
"php vendor/bin/pest tests/Feature/ImportBankSupportTest.php tests/Unit/LandedQaReceiptsTest.php",
|
||||||
|
"php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --bank-support-focused",
|
||||||
|
"php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --bank-support-concurrency",
|
||||||
|
"php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --bank-support-recovery",
|
||||||
|
"npx.cmd vitest run",
|
||||||
|
"npm.cmd run types:check",
|
||||||
|
"php vendor/bin/phpstan analyse --no-progress",
|
||||||
|
"npm.cmd run build -- --outDir storage/framework/testing/sgc-import-bank-support-qa-20261127"
|
||||||
|
],
|
||||||
|
"limitations": [
|
||||||
|
"Visual/mobile/print review pending; earlier missing-runtime blocker not retried",
|
||||||
|
"No pilot/operational SGF installation, activation, migration, real data or permission changes",
|
||||||
|
"Versioned legal suggestions and remaining product requirements remain open"
|
||||||
|
],
|
||||||
|
"execution_note": "PowerShell blocked ps1 npm/npx wrappers; cmd launchers passed without policy changes. Overlapping test counts must not be added."
|
||||||
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
{
|
||||||
|
"date": "2026-11-27",
|
||||||
|
"status": "implemented_in_isolated_qa_not_installed_not_product_completion",
|
||||||
|
"scope": [
|
||||||
|
"Explicit versioned charge definitions and MZN bases",
|
||||||
|
"Exact decimal ad-valorem, specific and maximum-of-both estimation",
|
||||||
|
"Unknown rates/bases and unproven non-application remain indeterminate",
|
||||||
|
"Immutable source-linked estimates and deliberate adoption into native import cost preparation",
|
||||||
|
"Explicit budget subtotal/tax split and single-use charge protection",
|
||||||
|
"Future legal periods preserve the earlier applicable publication",
|
||||||
|
"Native lot-availability warnings remain distinct from physical receipt acceptance"
|
||||||
|
],
|
||||||
|
"data": "Calculation tests use synthetic rates, bases and organizations. Real shared official originals were separately consulted and upload-tested; no real rate rules activated.",
|
||||||
|
"postgresql_money_integration": {
|
||||||
|
"tests": 57,
|
||||||
|
"assertions": 919,
|
||||||
|
"passed": true,
|
||||||
|
"database_removed": true
|
||||||
|
},
|
||||||
|
"sqlite_readiness_delta": {
|
||||||
|
"tests": 5,
|
||||||
|
"assertions": 42,
|
||||||
|
"passed": true
|
||||||
|
},
|
||||||
|
"protocol_unit": {
|
||||||
|
"tests": 9,
|
||||||
|
"assertions": 43,
|
||||||
|
"passed": true
|
||||||
|
},
|
||||||
|
"frontend": {
|
||||||
|
"files": 43,
|
||||||
|
"tests": 180,
|
||||||
|
"passed": true
|
||||||
|
},
|
||||||
|
"checks": {
|
||||||
|
"types": "passed",
|
||||||
|
"phpstan": "passed",
|
||||||
|
"scoped_format_lint": "passed",
|
||||||
|
"scoped_pint": "passed",
|
||||||
|
"diff_whitespace": "passed"
|
||||||
|
},
|
||||||
|
"concurrency": {
|
||||||
|
"same_operation": [
|
||||||
|
200,
|
||||||
|
200
|
||||||
|
],
|
||||||
|
"same_version": [
|
||||||
|
200,
|
||||||
|
409
|
||||||
|
],
|
||||||
|
"blocked_writers": 2,
|
||||||
|
"amount_versions_per_scenario": 1,
|
||||||
|
"audits_per_scenario": 1,
|
||||||
|
"new_files": 0,
|
||||||
|
"originals_verified": true,
|
||||||
|
"database_removed": true
|
||||||
|
},
|
||||||
|
"recovery": {
|
||||||
|
"calculated_amount_minor": 750,
|
||||||
|
"native_goods_minor": 10000,
|
||||||
|
"native_cost_plan_total_minor": 10750,
|
||||||
|
"source_provenance_restored": true,
|
||||||
|
"amount_and_native_plan_replay_without_effects": true,
|
||||||
|
"private_originals": 11,
|
||||||
|
"previous_tables_preserved": 115,
|
||||||
|
"optional_tables": 2,
|
||||||
|
"all_sql_equal": true,
|
||||||
|
"pre_extension_recovery": true,
|
||||||
|
"databases_removed": true
|
||||||
|
},
|
||||||
|
"native_http": {
|
||||||
|
"native_fortify_login": true,
|
||||||
|
"csrf_required": true,
|
||||||
|
"real_shared_pdf_bytes": 15509234,
|
||||||
|
"source_sha256": "8bcb278f77d365804d70a51074400af8ad2cdf6c620e5668c8bbd9b31e0d3fd2",
|
||||||
|
"exact_download_and_original_unchanged": true,
|
||||||
|
"one_source_one_audit_after_replay": true,
|
||||||
|
"guest_status": 401,
|
||||||
|
"revoked_status": 403,
|
||||||
|
"rules_published": 0,
|
||||||
|
"financial_stock_unchanged": true,
|
||||||
|
"private_upload_limit": "64M",
|
||||||
|
"private_post_limit": "70M",
|
||||||
|
"global_php_unchanged": true,
|
||||||
|
"server_stopped": true,
|
||||||
|
"private_root_and_database_removed": true
|
||||||
|
},
|
||||||
|
"private_build": {
|
||||||
|
"directory": "storage/framework/testing/sgc-import-legal-amounts-qa-20261127",
|
||||||
|
"manifest_sha256": "76ce989c99f800d50a877f5eff7b7d22f8ed1bfb7de04dc1b73cba614cfa4984",
|
||||||
|
"passed": true
|
||||||
|
},
|
||||||
|
"corrections": [
|
||||||
|
"PostgreSQL caught a 21-character internal kind exceeding the existing 20-character schema; changed to import_legal_amount without a migration. Native HTTP, source queries and recovery now cover it.",
|
||||||
|
"Non-application needs article-specific documentary grounding rather than becoming zero automatically.",
|
||||||
|
"A future publication no longer suppresses an earlier applicable period; no expired replacement fallback.",
|
||||||
|
"Native HTTP test now follows the actual Inertia bootstrap asset version instead of treating a reload response as JSON."
|
||||||
|
],
|
||||||
|
"limitations": [
|
||||||
|
"Real exemptions, rates and procedures must remain tied to their actual scope, sources and periods; no blanket claim of complete source parametrization",
|
||||||
|
"The operational PHP upload/post limits still require scoped installation preparation; only private QA limits were exercised",
|
||||||
|
"Browser host remains unavailable, but native Edge was successfully launched for a separate visual review that has not yet been completed",
|
||||||
|
"Other matrix requirements, operational installation and enterprise acceptance remain open"
|
||||||
|
],
|
||||||
|
"commands": [
|
||||||
|
"php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-amounts-focused",
|
||||||
|
"php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-amount-concurrency",
|
||||||
|
"php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-amount-recovery",
|
||||||
|
"php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-http --legal-corpus-root=<shared-corpus> --legal-http-candidate=<private-candidate> --legal-http-manifest=<validated-hash>"
|
||||||
|
],
|
||||||
|
"native_visual_delta": {
|
||||||
|
"browser": "Native Microsoft Edge",
|
||||||
|
"viewports_observed_px": [
|
||||||
|
390,
|
||||||
|
823
|
||||||
|
],
|
||||||
|
"legal_page_no_horizontal_overflow_observed": true,
|
||||||
|
"explicit_reuse_preserved_base_minor": 10000,
|
||||||
|
"native_form_saved_new_amount_version": 2,
|
||||||
|
"native_form_calculated_minor": 750,
|
||||||
|
"existing_plan_preserved_selected_estimate_id": 5,
|
||||||
|
"existing_plan_total_minor": 10750,
|
||||||
|
"readiness_expected_unknown_and_bank_deadline_pending_visible": true,
|
||||||
|
"scope_limit": "Not a complete visual acceptance: bank editing, print pagination and remaining product flows remain unverified. Empty required reason was blocked by native form validation; server error rendering was not demonstrated.",
|
||||||
|
"private_server_stopped": true,
|
||||||
|
"private_root_removed": true,
|
||||||
|
"isolated_database_removed": true,
|
||||||
|
"user_tabs_preserved": true
|
||||||
|
},
|
||||||
|
"native_bank_visual_delta": {
|
||||||
|
"native_form_saved_version": 2,
|
||||||
|
"state": "documented",
|
||||||
|
"effective_delivery_on": "2026-11-27",
|
||||||
|
"dated_original_and_basis_preserved": true,
|
||||||
|
"previous_version_preserved": true,
|
||||||
|
"pending_delivery_and_due_today_alerts_removed": true,
|
||||||
|
"isolated_environment_removed": true,
|
||||||
|
"bank_execution": false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
{
|
||||||
|
"date": "2026-11-27",
|
||||||
|
"status": "documentary_legal_rules_and_contextual_followup_implemented_in_qa_not_product_completion",
|
||||||
|
"authorization": "Owner requested uninterrupted development to functional completion, preserving separate operational authorization; legislation already shared, located and used",
|
||||||
|
"scope": [
|
||||||
|
"Independent private official-source consultation",
|
||||||
|
"Versioned draft/publication/withdrawal using existing import_customs authority",
|
||||||
|
"Explicit code/origin/sector/date suggestions and native buyer confirmation/deviation",
|
||||||
|
"Frozen source in requisition/new order/print; changed, expired or missing-source warning",
|
||||||
|
"Live logistics, required-document, party, bank and Finance follow-up without notifications"
|
||||||
|
],
|
||||||
|
"postgresql_integration": {
|
||||||
|
"tests": 36,
|
||||||
|
"assertions": 337,
|
||||||
|
"passed": true,
|
||||||
|
"database_removed": true
|
||||||
|
},
|
||||||
|
"final_legal_sqlite_delta": {
|
||||||
|
"tests": 7,
|
||||||
|
"assertions": 54,
|
||||||
|
"passed": true
|
||||||
|
},
|
||||||
|
"protocol_unit": {
|
||||||
|
"tests": 8,
|
||||||
|
"assertions": 38,
|
||||||
|
"passed": true
|
||||||
|
},
|
||||||
|
"concurrency": {
|
||||||
|
"same_operation": [
|
||||||
|
200,
|
||||||
|
200
|
||||||
|
],
|
||||||
|
"same_version": [
|
||||||
|
200,
|
||||||
|
409
|
||||||
|
],
|
||||||
|
"blocked_writers": 2,
|
||||||
|
"rule_versions_per_scenario": 1,
|
||||||
|
"originals_per_scenario": 1,
|
||||||
|
"audits_per_scenario": 1,
|
||||||
|
"originals_verified": true,
|
||||||
|
"database_removed": true
|
||||||
|
},
|
||||||
|
"recovery": {
|
||||||
|
"legal_source_restored": true,
|
||||||
|
"published_version_restored": true,
|
||||||
|
"buyer_context_restored": true,
|
||||||
|
"replay_without_effect": true,
|
||||||
|
"private_original_versions_restored": 11,
|
||||||
|
"typed_dossier_versions_restored": 8,
|
||||||
|
"previous_tables_preserved": 115,
|
||||||
|
"optional_tables": 2,
|
||||||
|
"all_sql_equal": true,
|
||||||
|
"pre_extension_restore": true,
|
||||||
|
"databases_removed": true
|
||||||
|
},
|
||||||
|
"real_sources": {
|
||||||
|
"corpus_root": "C:/Mac/Home/Documents/TEMPO/Portal Tempo/Legislacao",
|
||||||
|
"files_inventoried_including_hidden": 8109,
|
||||||
|
"inventory_metadata_sha256": "446df82acf6918a1ca792e54baeae2703842a1c6d8922be8d2a4f94598393e9c",
|
||||||
|
"sources": [
|
||||||
|
{
|
||||||
|
"reference": "BR251 29/12/2022, Leis17/2022 e19/2022 integral",
|
||||||
|
"bytes": 15509234,
|
||||||
|
"sha256": "8bcb278f77d365804d70a51074400af8ad2cdf6c620e5668c8bbd9b31e0d3fd2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"reference": "BR248 suplemento29/12/2025, Leis7/2025 a12/2025",
|
||||||
|
"bytes": 1002011,
|
||||||
|
"sha256": "a0110696253715567af39c159a21bacfebc32f944fa43a4efd18070d36959e50"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"reference": "Lei28/2022 Lei Cambial",
|
||||||
|
"bytes": 596387,
|
||||||
|
"sha256": "0dba2775dbede3701b8c1f476e1497c0dc2a481d59e7898013aa992d0a3db896"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"reference": "BR57 20/03/2024 Aviso3/GBM/2024",
|
||||||
|
"bytes": 758167,
|
||||||
|
"sha256": "e170d541bf2f21f4070a97d8b1b12a35ec8f5d59a28eb17c50597c5d17656db5"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"native_read_and_original_hashes_verified": true,
|
||||||
|
"financial_stock_unchanged": true,
|
||||||
|
"rules_published": 0,
|
||||||
|
"synthetic_qa_organization_only": true,
|
||||||
|
"database_removed": true
|
||||||
|
},
|
||||||
|
"frontend": {
|
||||||
|
"files": 42,
|
||||||
|
"tests": 177,
|
||||||
|
"passed": true
|
||||||
|
},
|
||||||
|
"checks": {
|
||||||
|
"types": "passed",
|
||||||
|
"phpstan": "passed",
|
||||||
|
"scoped_format_lint": "passed",
|
||||||
|
"scoped_pint": "passed",
|
||||||
|
"diff_whitespace": "passed"
|
||||||
|
},
|
||||||
|
"private_build": {
|
||||||
|
"directory": "storage/framework/testing/sgc-import-legal-readiness-qa-20261127",
|
||||||
|
"manifest_sha256": "36613eecf708866996ab2febe661ed00b3cd1e1508f97998f3779b56c7834b31",
|
||||||
|
"passed": true
|
||||||
|
},
|
||||||
|
"pilot_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e",
|
||||||
|
"corrections": [
|
||||||
|
"Replaced transactional2MB limit for official sources with64MB and regression for full legal publications",
|
||||||
|
"Separated source availability from rule publication to avoid artificial classification/rate data",
|
||||||
|
"Publication cannot replace the prepared original; regression rejects a source swap",
|
||||||
|
"Expected receipt warning follows native effective acceptance rather than customs release alone"
|
||||||
|
],
|
||||||
|
"visual": {
|
||||||
|
"browser_host": "unavailable",
|
||||||
|
"native_browser_inventory": "empty",
|
||||||
|
"review_completed": false,
|
||||||
|
"pdf_source_review": "pypdf extraction and pypdfium2 rendered 2025 amendment pages2-4; page3/4 images inspected; no source modifications"
|
||||||
|
},
|
||||||
|
"limitations": [
|
||||||
|
"Tax estimate calculations and complete source-specific rule parametrization remain open",
|
||||||
|
"Automatic recipients and organizational deadlines are not inferred",
|
||||||
|
"Visual/mobile/print review and other reconciled matrix gaps remain open",
|
||||||
|
"No operational installation/activation, migration or real permissions changed"
|
||||||
|
],
|
||||||
|
"commands": [
|
||||||
|
"php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-focused",
|
||||||
|
"php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-concurrency",
|
||||||
|
"php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-recovery",
|
||||||
|
"php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-corpus --legal-corpus-root=<shared-corpus>"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { Panel } from '@/components/procurement';
|
||||||
|
|
||||||
|
export type FrozenCapitalAssignment = {
|
||||||
|
id: number;
|
||||||
|
version: number;
|
||||||
|
reason: string;
|
||||||
|
snapshot: {
|
||||||
|
item: { description: string };
|
||||||
|
source: {
|
||||||
|
version: number;
|
||||||
|
data: {
|
||||||
|
type: string;
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
reference: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
export default function CapitalAssignmentSummary({
|
||||||
|
records,
|
||||||
|
}: {
|
||||||
|
records?: Record<number, FrozenCapitalAssignment>;
|
||||||
|
}) {
|
||||||
|
const rows = Object.values(records ?? {});
|
||||||
|
if (!rows.length) return null;
|
||||||
|
return (
|
||||||
|
<Panel
|
||||||
|
title="Projectos e imobilizado"
|
||||||
|
description="Referências preservadas na emissão desta ordem."
|
||||||
|
>
|
||||||
|
{rows.map((row) => (
|
||||||
|
<article
|
||||||
|
key={row.id}
|
||||||
|
className="space-y-2 border-b py-3 break-words"
|
||||||
|
>
|
||||||
|
<h3 className="font-semibold">
|
||||||
|
{row.snapshot.item.description}
|
||||||
|
</h3>
|
||||||
|
<p>
|
||||||
|
{row.snapshot.source.data.type === 'project'
|
||||||
|
? 'Projecto'
|
||||||
|
: 'Imobilizado'}{' '}
|
||||||
|
· {row.snapshot.source.data.code} ·{' '}
|
||||||
|
{row.snapshot.source.data.name} · versão{' '}
|
||||||
|
{row.snapshot.source.version}
|
||||||
|
</p>
|
||||||
|
<p>{row.snapshot.source.data.reference}</p>
|
||||||
|
<p>{row.reason}</p>
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
</Panel>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
import { controlClass } from '@/components/procurement';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { estimateMoney } from '@/lib/import-estimate-money';
|
||||||
|
import { money } from '@/types/procurement';
|
||||||
|
|
||||||
|
export type LegalCharge = {
|
||||||
|
key: string;
|
||||||
|
kind: string;
|
||||||
|
label: string;
|
||||||
|
method: string;
|
||||||
|
rate_percent: string | null;
|
||||||
|
specific_minor: number | null;
|
||||||
|
quantity_unit: string | null;
|
||||||
|
basis_reference: string;
|
||||||
|
};
|
||||||
|
export type LegalChargeDraft = {
|
||||||
|
key: string;
|
||||||
|
kind: string;
|
||||||
|
label: string;
|
||||||
|
method: string;
|
||||||
|
rate_percent: string;
|
||||||
|
specific_amount: string;
|
||||||
|
quantity_unit: string;
|
||||||
|
basis_reference: string;
|
||||||
|
};
|
||||||
|
export const chargeDrafts = (charges: LegalCharge[]) =>
|
||||||
|
charges.map((charge): LegalChargeDraft => ({
|
||||||
|
key: charge.key,
|
||||||
|
kind: charge.kind,
|
||||||
|
label: charge.label,
|
||||||
|
method: charge.method,
|
||||||
|
rate_percent: charge.rate_percent ?? '',
|
||||||
|
specific_amount: estimateMoney(charge.specific_minor),
|
||||||
|
quantity_unit: charge.quantity_unit ?? '',
|
||||||
|
basis_reference: charge.basis_reference,
|
||||||
|
}));
|
||||||
|
export function LegalChargeSummary({ charges }: { charges: LegalCharge[] }) {
|
||||||
|
const methods: Record<string, string> = {
|
||||||
|
unknown: 'Por determinar',
|
||||||
|
not_applicable: 'Não aplicável segundo a fonte',
|
||||||
|
ad_valorem: 'Percentagem sobre base em MZN',
|
||||||
|
specific: 'Montante por unidade',
|
||||||
|
maximum: 'Maior valor entre percentagem e montante por unidade',
|
||||||
|
};
|
||||||
|
if (charges.length === 0)
|
||||||
|
return <p>Imposições ainda por parametrizar nesta regra.</p>;
|
||||||
|
return (
|
||||||
|
<div className="grid gap-3">
|
||||||
|
{charges.map((charge) => (
|
||||||
|
<dl key={charge.key} className="rounded border p-3">
|
||||||
|
<dt className="font-medium">{charge.label}</dt>
|
||||||
|
<dd>{methods[charge.method]}</dd>
|
||||||
|
{charge.rate_percent !== null && (
|
||||||
|
<dd>Taxa: {charge.rate_percent}%</dd>
|
||||||
|
)}
|
||||||
|
{charge.specific_minor !== null && (
|
||||||
|
<dd>
|
||||||
|
Taxa específica: {money(charge.specific_minor)} por{' '}
|
||||||
|
{charge.quantity_unit}
|
||||||
|
</dd>
|
||||||
|
)}
|
||||||
|
<dt>Base e condições</dt>
|
||||||
|
<dd>{charge.basis_reference}</dd>
|
||||||
|
</dl>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
export default function LegalChargeFields({
|
||||||
|
charges,
|
||||||
|
onChange,
|
||||||
|
}: {
|
||||||
|
charges: LegalChargeDraft[];
|
||||||
|
onChange: (charges: LegalChargeDraft[]) => void;
|
||||||
|
}) {
|
||||||
|
const change = (index: number, values: Partial<LegalChargeDraft>) =>
|
||||||
|
onChange(
|
||||||
|
charges.map((charge, at) =>
|
||||||
|
at === index ? { ...charge, ...values } : charge,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<fieldset className="space-y-4 rounded border p-4">
|
||||||
|
<legend>Imposições documentadas para estimativa</legend>
|
||||||
|
<p>
|
||||||
|
Sem taxas parametrizadas, os montantes permanecem por
|
||||||
|
determinar. Registe a base legal de cada método; não aplique
|
||||||
|
isenções sem os seus requisitos.
|
||||||
|
</p>
|
||||||
|
{charges.map((charge, index) => (
|
||||||
|
<div
|
||||||
|
key={charge.key}
|
||||||
|
className="grid gap-3 border-b pb-4 sm:grid-cols-2"
|
||||||
|
>
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Imposição
|
||||||
|
<select
|
||||||
|
className={controlClass}
|
||||||
|
value={charge.kind}
|
||||||
|
onChange={(e) =>
|
||||||
|
change(index, { kind: e.target.value })
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="duty">Direitos aduaneiros</option>
|
||||||
|
<option value="ice">ICE</option>
|
||||||
|
<option value="vat">IVA da importação</option>
|
||||||
|
<option value="other">Outro encargo</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Designação
|
||||||
|
<input
|
||||||
|
className={controlClass}
|
||||||
|
required
|
||||||
|
minLength={2}
|
||||||
|
maxLength={120}
|
||||||
|
value={charge.label}
|
||||||
|
onChange={(e) =>
|
||||||
|
change(index, { label: e.target.value })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Método previsto na fonte
|
||||||
|
<select
|
||||||
|
className={controlClass}
|
||||||
|
value={charge.method}
|
||||||
|
onChange={(e) =>
|
||||||
|
change(index, {
|
||||||
|
method: e.target.value,
|
||||||
|
rate_percent: '',
|
||||||
|
specific_amount: '',
|
||||||
|
quantity_unit: '',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="unknown">Por determinar</option>
|
||||||
|
<option value="not_applicable">
|
||||||
|
Não aplicável segundo a fonte
|
||||||
|
</option>
|
||||||
|
<option value="ad_valorem">
|
||||||
|
Percentagem sobre base expressa em MZN
|
||||||
|
</option>
|
||||||
|
<option value="specific">
|
||||||
|
Montante em MZN por unidade
|
||||||
|
</option>
|
||||||
|
<option value="maximum">
|
||||||
|
Maior valor entre percentagem e taxa por unidade
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
{['ad_valorem', 'maximum'].includes(charge.method) && (
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Taxa percentual
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
inputMode="decimal"
|
||||||
|
pattern="[0-9]+([.][0-9]{1,6})?"
|
||||||
|
className={controlClass}
|
||||||
|
value={charge.rate_percent}
|
||||||
|
onChange={(e) =>
|
||||||
|
change(index, {
|
||||||
|
rate_percent: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
{['specific', 'maximum'].includes(charge.method) && (
|
||||||
|
<>
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Taxa específica em MZN por unidade
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
inputMode="decimal"
|
||||||
|
className={controlClass}
|
||||||
|
value={charge.specific_amount}
|
||||||
|
onChange={(e) =>
|
||||||
|
change(index, {
|
||||||
|
specific_amount: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Unidade da taxa específica
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
maxLength={40}
|
||||||
|
className={controlClass}
|
||||||
|
value={charge.quantity_unit}
|
||||||
|
onChange={(e) =>
|
||||||
|
change(index, {
|
||||||
|
quantity_unit: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<label className="grid gap-1 sm:col-span-2">
|
||||||
|
Artigo e condições da base de incidência ou da não
|
||||||
|
aplicação
|
||||||
|
<textarea
|
||||||
|
required
|
||||||
|
minLength={3}
|
||||||
|
maxLength={4000}
|
||||||
|
className={controlClass}
|
||||||
|
value={charge.basis_reference}
|
||||||
|
onChange={(e) =>
|
||||||
|
change(index, {
|
||||||
|
basis_reference: e.target.value,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() =>
|
||||||
|
onChange(charges.filter((_, at) => at !== index))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Retirar desta preparação
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
disabled={charges.length >= 20}
|
||||||
|
onClick={() =>
|
||||||
|
onChange([
|
||||||
|
...charges,
|
||||||
|
{
|
||||||
|
key: crypto.randomUUID(),
|
||||||
|
kind: 'duty',
|
||||||
|
label: '',
|
||||||
|
method: 'unknown',
|
||||||
|
rate_percent: '',
|
||||||
|
specific_amount: '',
|
||||||
|
quantity_unit: '',
|
||||||
|
basis_reference: '',
|
||||||
|
},
|
||||||
|
])
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Acrescentar imposição documentada
|
||||||
|
</Button>
|
||||||
|
</fieldset>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -13,6 +13,16 @@ export type FrozenImportTariff = {
|
|||||||
};
|
};
|
||||||
confirmed_by: { name: string };
|
confirmed_by: { name: string };
|
||||||
reason: string;
|
reason: string;
|
||||||
|
legal_rule?: {
|
||||||
|
version: number;
|
||||||
|
data: {
|
||||||
|
official_reference: string;
|
||||||
|
citation: string;
|
||||||
|
obligations: string;
|
||||||
|
document_types: string[];
|
||||||
|
};
|
||||||
|
context: { date: string; origin_country: string; sector: string };
|
||||||
|
} | null;
|
||||||
};
|
};
|
||||||
export default function ImportTariffSummary({
|
export default function ImportTariffSummary({
|
||||||
records,
|
records,
|
||||||
@@ -42,6 +52,18 @@ export default function ImportTariffSummary({
|
|||||||
</dd>
|
</dd>
|
||||||
<dt>Fonte da confirmação</dt>
|
<dt>Fonte da confirmação</dt>
|
||||||
<dd>{record.data.confirmation_source}</dd>
|
<dd>{record.data.confirmation_source}</dd>
|
||||||
|
{record.legal_rule && (
|
||||||
|
<>
|
||||||
|
<dt>Regra legal aplicada</dt>
|
||||||
|
<dd>
|
||||||
|
{record.legal_rule.data.official_reference}{' '}
|
||||||
|
· {record.legal_rule.data.citation} · versão{' '}
|
||||||
|
{record.legal_rule.version}
|
||||||
|
</dd>
|
||||||
|
<dt>Condições preservadas</dt>
|
||||||
|
<dd>{record.legal_rule.data.obligations}</dd>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
<dt>
|
<dt>
|
||||||
{record.data.deviation
|
{record.data.deviation
|
||||||
? 'Justificação do desvio'
|
? 'Justificação do desvio'
|
||||||
|
|||||||
@@ -37,6 +37,61 @@ function topic(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const journeyHelp: JourneyHelp[] = [
|
export const journeyHelp: JourneyHelp[] = [
|
||||||
|
topic(
|
||||||
|
'import-readiness',
|
||||||
|
'Acompanhar pendências da importação',
|
||||||
|
['supply/import-readiness'],
|
||||||
|
'Reunir os alertas factuais da ordem e abrir o percurso que permite resolver cada pendência.',
|
||||||
|
[
|
||||||
|
'Confira a previsão de recepção utilizável com os marcos logísticos e as quantidades efectivamente aceites.',
|
||||||
|
'Consulte originais em falta ou alterados e os documentos indicados nas fontes legais preservadas.',
|
||||||
|
'Reveja alterações de fontes, intervenientes, instruções e suporte bancário nos respectivos percursos.',
|
||||||
|
'Finanças consulta as preparações de custo pendentes no circuito financeiro existente.',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'Informação desconhecida permanece por determinar e verificações indisponíveis são identificadas.',
|
||||||
|
'A consulta não concede competências, não envia notificações e não certifica cumprimento ou pagamentos.',
|
||||||
|
],
|
||||||
|
'Se a importação mudou, abra a versão actual e volte a conferir as pendências; os originais e decisões anteriores permanecem preservados.',
|
||||||
|
'Abra o percurso relacionado com a pendência e regresse para consultar a situação actualizada.',
|
||||||
|
),
|
||||||
|
topic(
|
||||||
|
'import-legal',
|
||||||
|
'Consultar e manter a base legal de importação',
|
||||||
|
['supply/import-legal'],
|
||||||
|
'Consultar fontes aplicáveis ao código, origem, sector e período e preparar a classificação do artigo.',
|
||||||
|
[
|
||||||
|
'Indique o contexto e a data. Sem correspondência publicada, a regra permanece por determinar.',
|
||||||
|
'Seleccione o artigo e prepare uma proposta com a fonte escolhida; confirme ou justifique o desvio na classificação pautal.',
|
||||||
|
'A área aduaneira conserva exemplar, diploma, citação e vigência antes de validar e publicar a preparação.',
|
||||||
|
'Uma revisão conserva a publicação anterior até nova validação. A retirada impede novas sugestões.',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'Publicar uma fonte não activa cálculos, isenções, pagamentos ou submissões JUE.',
|
||||||
|
'Uma mudança da regra sinaliza a decisão anterior, conservando a fonte e o histórico aplicados.',
|
||||||
|
],
|
||||||
|
'Se a regra mudou ou o exemplar divergiu, preserve a preparação e seleccione uma fonte actual antes da confirmação.',
|
||||||
|
'Regresse à classificação pautal para confirmar a proposta ou justificar o desvio.',
|
||||||
|
),
|
||||||
|
topic(
|
||||||
|
'import-bank-support',
|
||||||
|
'Acompanhar o suporte documental bancário',
|
||||||
|
['supply/import-bank-support'],
|
||||||
|
'Associar o termo de compromisso ao documento único, reunir os suportes solicitados e conservar o comprovativo de entrega ao banco.',
|
||||||
|
[
|
||||||
|
'Seleccione os originais já registados no dossiê; não reintroduza referências ou entidades emitentes.',
|
||||||
|
'Identifique os tipos e quantidades pedidos pelo banco, com a fonte dos requisitos.',
|
||||||
|
'Indique apenas um prazo documentado e a sua fonte; informação desconhecida permanece por indicar.',
|
||||||
|
'Reunir documentos não demonstra entrega. Seleccione o comprovativo de entrega quando estiver disponível.',
|
||||||
|
'Corrija por nova versão e consulte os alertas, o histórico e o CSV do âmbito completo.',
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'A correcção ou perda de um original reabre o alerta; o registo anterior não é apagado.',
|
||||||
|
'O acompanhamento não executa transferências ou submissões na JUE e não certifica cumprimento bancário.',
|
||||||
|
],
|
||||||
|
'Conserve a preparação se a versão mudou. Seleccione explicitamente os novos originais e explique a correcção.',
|
||||||
|
'Consulte os prazos e documentos em falta e prossiga no percurso próprio da importação.',
|
||||||
|
),
|
||||||
topic(
|
topic(
|
||||||
'import-estimate',
|
'import-estimate',
|
||||||
'Preparar o custo estimado da importação',
|
'Preparar o custo estimado da importação',
|
||||||
|
|||||||
@@ -0,0 +1,412 @@
|
|||||||
|
import { Head, Link, useForm } from '@inertiajs/react';
|
||||||
|
import { useEffect, useRef } from 'react';
|
||||||
|
import {
|
||||||
|
FormErrors,
|
||||||
|
PageTitle,
|
||||||
|
Panel,
|
||||||
|
controlClass,
|
||||||
|
} from '@/components/procurement';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
|
||||||
|
type Data = {
|
||||||
|
type: string;
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
department_id: number;
|
||||||
|
equipment_id: number | null;
|
||||||
|
reference: string;
|
||||||
|
};
|
||||||
|
type Record = {
|
||||||
|
id: number;
|
||||||
|
record_key: string;
|
||||||
|
version: number;
|
||||||
|
state: string;
|
||||||
|
data: Data;
|
||||||
|
reason: string;
|
||||||
|
};
|
||||||
|
type Props = {
|
||||||
|
trace?: {
|
||||||
|
orders: { data: { id: number; description: string; quantity: string; unit: string; order_id: number; order_number: string }[]; prev_page_url: string | null; next_page_url: string | null };
|
||||||
|
receipts: { data: { id: number; description: string | null; unit: string | null; receipt_id: number; order_id: number | null; received_on: string | null; quality_status: string; accepted_quantity: string; reversed: boolean; returned_quantity: string }[]; prev_page_url: string | null; next_page_url: string | null };
|
||||||
|
} | null;
|
||||||
|
history: {
|
||||||
|
data: Record[];
|
||||||
|
prev_page_url: string | null;
|
||||||
|
next_page_url: string | null;
|
||||||
|
} | null;
|
||||||
|
records: {
|
||||||
|
data: Record[];
|
||||||
|
prev_page_url: string | null;
|
||||||
|
next_page_url: string | null;
|
||||||
|
};
|
||||||
|
departments: { id: number; name: string }[];
|
||||||
|
equipment: {
|
||||||
|
id: number;
|
||||||
|
code: string;
|
||||||
|
description: string;
|
||||||
|
department_id: number;
|
||||||
|
}[];
|
||||||
|
canManage: boolean;
|
||||||
|
actorId: number;
|
||||||
|
tenantId: number;
|
||||||
|
};
|
||||||
|
export default function CapitalRegister(props: Props) {
|
||||||
|
const url = '/projectos-imobilizado';
|
||||||
|
const form = useForm(
|
||||||
|
`capital-register:${props.tenantId}:${props.actorId}`,
|
||||||
|
{
|
||||||
|
operation_key: '',
|
||||||
|
record_key: null as string | null,
|
||||||
|
version: 0,
|
||||||
|
type: 'project',
|
||||||
|
code: '',
|
||||||
|
name: '',
|
||||||
|
department_id: '',
|
||||||
|
equipment_id: '',
|
||||||
|
reference: '',
|
||||||
|
state: 'active',
|
||||||
|
reason: '',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const ref = useRef<HTMLFormElement>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
const node = ref.current;
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent('sgc:context-dirty', {
|
||||||
|
detail: { form: node, dirty: form.isDirty },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return () => {
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent('sgc:context-dirty', {
|
||||||
|
detail: { form: node, dirty: false },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}, [form.isDirty]);
|
||||||
|
const edit = (record: Record) =>
|
||||||
|
form.setData({
|
||||||
|
...record.data,
|
||||||
|
operation_key: '',
|
||||||
|
record_key: record.record_key,
|
||||||
|
version: record.version,
|
||||||
|
department_id: String(record.data.department_id),
|
||||||
|
equipment_id:
|
||||||
|
record.data.equipment_id === null
|
||||||
|
? ''
|
||||||
|
: String(record.data.equipment_id),
|
||||||
|
state: record.state,
|
||||||
|
reason: '',
|
||||||
|
});
|
||||||
|
return (
|
||||||
|
<div className="mx-auto grid w-full max-w-6xl min-w-0 gap-6 p-5 lg:p-8">
|
||||||
|
<Head title="Projectos e imobilizado" />
|
||||||
|
<PageTitle
|
||||||
|
eyebrow="Cadastro de Compras"
|
||||||
|
title="Projectos e imobilizado"
|
||||||
|
description="Identifique o projecto ou a referência de imobilizado da compra. A ligação ao equipamento reutiliza a ficha física existente."
|
||||||
|
/>
|
||||||
|
<Link className="underline" href="/equipamentos">
|
||||||
|
Consultar equipamentos e peças
|
||||||
|
</Link>
|
||||||
|
<Panel
|
||||||
|
title="Identidades registadas"
|
||||||
|
description="As revisões conservam o código e o histórico. Arquivar impede novas escolhas sem apagar ligações anteriores."
|
||||||
|
>
|
||||||
|
{props.records.data.length === 0 && (
|
||||||
|
<p>Ainda não há registos neste âmbito.</p>
|
||||||
|
)}
|
||||||
|
{props.records.data.map((record) => (
|
||||||
|
<article
|
||||||
|
key={record.id}
|
||||||
|
className="min-w-0 space-y-2 border-b py-4 break-words"
|
||||||
|
>
|
||||||
|
<h3 className="font-semibold">
|
||||||
|
{record.data.code} · {record.data.name}
|
||||||
|
</h3>
|
||||||
|
<p>
|
||||||
|
{record.data.type === 'project'
|
||||||
|
? 'Projecto'
|
||||||
|
: 'Imobilizado'}{' '}
|
||||||
|
·{' '}
|
||||||
|
{record.state === 'active' ? 'Activo' : 'Arquivado'}{' '}
|
||||||
|
· versão {record.version}
|
||||||
|
</p>
|
||||||
|
<p>{record.data.reference}</p>
|
||||||
|
<p>{record.reason}</p>
|
||||||
|
<Link
|
||||||
|
className="underline"
|
||||||
|
preserveState
|
||||||
|
href={`${url}?history=${record.record_key}`}
|
||||||
|
>
|
||||||
|
Consultar versões e origens
|
||||||
|
</Link>
|
||||||
|
{props.canManage && (
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => edit(record)}
|
||||||
|
>
|
||||||
|
Preparar nova versão
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
<nav
|
||||||
|
className="mt-4 flex gap-4"
|
||||||
|
aria-label="Páginas do cadastro"
|
||||||
|
>
|
||||||
|
{props.records.prev_page_url && (
|
||||||
|
<Link preserveState href={props.records.prev_page_url}>
|
||||||
|
Anterior
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{props.records.next_page_url && (
|
||||||
|
<Link preserveState href={props.records.next_page_url}>
|
||||||
|
Seguinte
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</nav>
|
||||||
|
</Panel>
|
||||||
|
{props.history && (
|
||||||
|
<Panel title="Histórico do registo">
|
||||||
|
{props.history.data.map((record) => (
|
||||||
|
<article
|
||||||
|
key={record.id}
|
||||||
|
className="space-y-2 border-b py-4 break-words"
|
||||||
|
>
|
||||||
|
<h3 className="font-semibold">
|
||||||
|
{record.data.code} · versão {record.version}
|
||||||
|
</h3>
|
||||||
|
<p>
|
||||||
|
{record.data.name} ·{' '}
|
||||||
|
{record.state === 'active'
|
||||||
|
? 'Activo'
|
||||||
|
: 'Arquivado'}
|
||||||
|
</p>
|
||||||
|
<p>{record.data.reference}</p>
|
||||||
|
<p>{record.reason}</p>
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
<nav
|
||||||
|
className="mt-4 flex gap-4"
|
||||||
|
aria-label="Páginas do histórico"
|
||||||
|
>
|
||||||
|
{props.history.prev_page_url && (
|
||||||
|
<Link
|
||||||
|
preserveState
|
||||||
|
href={props.history.prev_page_url}
|
||||||
|
>
|
||||||
|
Anterior
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{props.history.next_page_url && (
|
||||||
|
<Link
|
||||||
|
preserveState
|
||||||
|
href={props.history.next_page_url}
|
||||||
|
>
|
||||||
|
Seguinte
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</nav>
|
||||||
|
</Panel>
|
||||||
|
)}
|
||||||
|
{props.trace && <Panel title="Ordens que preservaram esta referência" description="As ligações vêm dos documentos emitidos, incluindo escolhas anteriores a revisões do cadastro.">
|
||||||
|
{props.trace.orders.data.length === 0 && <p>Ainda não há ordens visíveis com esta referência preservada.</p>}
|
||||||
|
{props.trace.orders.data.map(line => <article key={line.id} className="space-y-2 border-b py-3 break-words"><Link className="underline" href={`/ordens/${line.order_id}`}>{line.order_number}</Link><p>{line.description} · {line.quantity} {line.unit}</p></article>)}
|
||||||
|
<nav className="flex gap-4" aria-label="Ordens de origem">{props.trace.orders.prev_page_url && <Link preserveState href={props.trace.orders.prev_page_url}>Anterior</Link>}{props.trace.orders.next_page_url && <Link preserveState href={props.trace.orders.next_page_url}>Seguinte</Link>}</nav>
|
||||||
|
</Panel>}
|
||||||
|
{props.trace && <Panel title="Recepções destas origens" description="A quantidade aceite é a do documento original. Estornos e devoluções actuais são apresentados separadamente; a recepção não certifica capitalização contabilística.">
|
||||||
|
{props.trace.receipts.data.length === 0 && <p>Ainda não há recepções visíveis nestas origens.</p>}
|
||||||
|
{props.trace.receipts.data.map(receipt => <article key={receipt.id} className="space-y-2 border-b py-3 break-words"><h3 className="font-semibold">Recepção #{receipt.receipt_id} · {receipt.description || 'Descrição por conferir'}</h3><p>Data: {receipt.received_on || 'Por conferir'} · Aceite no original: {receipt.accepted_quantity} {receipt.unit || ''}</p><p>Qualidade registada: {receipt.quality_status === 'compliant' ? 'Conforme' : receipt.quality_status === 'quarantined' ? 'Em quarentena' : 'Com divergência'}</p>{receipt.reversed && <p className="font-semibold">Recepção estornada; o original permanece no histórico.</p>}{receipt.returned_quantity !== '0.000' && <p>Devolução ao fornecedor: {receipt.returned_quantity} {receipt.unit || ''}</p>}{receipt.order_id && <Link className="underline" href={`/ordens/${receipt.order_id}`}>Conferir documentos e movimentos da ordem</Link>}</article>)}
|
||||||
|
<nav className="flex gap-4" aria-label="Recepções de origem">{props.trace.receipts.prev_page_url && <Link preserveState href={props.trace.receipts.prev_page_url}>Anterior</Link>}{props.trace.receipts.next_page_url && <Link preserveState href={props.trace.receipts.next_page_url}>Seguinte</Link>}</nav>
|
||||||
|
</Panel>}
|
||||||
|
{props.canManage && (
|
||||||
|
<Panel
|
||||||
|
title={
|
||||||
|
form.data.record_key
|
||||||
|
? `Rever cadastro · versão ${form.data.version}`
|
||||||
|
: 'Novo registo'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<form
|
||||||
|
ref={ref}
|
||||||
|
className="space-y-4"
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const operation =
|
||||||
|
form.data.operation_key || crypto.randomUUID();
|
||||||
|
form.setData('operation_key', operation);
|
||||||
|
form.transform((data) => ({
|
||||||
|
...data,
|
||||||
|
operation_key: operation,
|
||||||
|
equipment_id: data.equipment_id || null,
|
||||||
|
}));
|
||||||
|
form.post(url, {
|
||||||
|
preserveScroll: true,
|
||||||
|
onSuccess: () => {
|
||||||
|
form.reset();
|
||||||
|
form.clearErrors();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<FormErrors errors={form.errors} />
|
||||||
|
<label className="grid gap-2">
|
||||||
|
Tipo
|
||||||
|
<select
|
||||||
|
className={controlClass}
|
||||||
|
disabled={form.data.record_key !== null}
|
||||||
|
value={form.data.type}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData((data) => ({
|
||||||
|
...data,
|
||||||
|
type: e.target.value,
|
||||||
|
equipment_id: '',
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="project">Projecto</option>
|
||||||
|
<option value="asset">Imobilizado</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label className="grid gap-2">
|
||||||
|
Código
|
||||||
|
<input
|
||||||
|
className={controlClass}
|
||||||
|
required
|
||||||
|
readOnly={form.data.record_key !== null}
|
||||||
|
maxLength={40}
|
||||||
|
value={form.data.code}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData('code', e.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="grid gap-2">
|
||||||
|
Designação
|
||||||
|
<input
|
||||||
|
className={controlClass}
|
||||||
|
required
|
||||||
|
maxLength={200}
|
||||||
|
value={form.data.name}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData('name', e.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="grid gap-2">
|
||||||
|
Departamento
|
||||||
|
<select
|
||||||
|
className={controlClass}
|
||||||
|
required
|
||||||
|
value={form.data.department_id}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData((data) => ({
|
||||||
|
...data,
|
||||||
|
department_id: e.target.value,
|
||||||
|
equipment_id: '',
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="">Seleccione</option>
|
||||||
|
{props.departments.map((d) => (
|
||||||
|
<option key={d.id} value={d.id}>
|
||||||
|
{d.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
{form.data.type === 'asset' && (
|
||||||
|
<label className="grid gap-2">
|
||||||
|
Equipamento identificado, quando disponível
|
||||||
|
<select
|
||||||
|
className={controlClass}
|
||||||
|
value={form.data.equipment_id}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData(
|
||||||
|
'equipment_id',
|
||||||
|
e.target.value,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="">
|
||||||
|
Ainda sem ligação à ficha física
|
||||||
|
</option>
|
||||||
|
{props.equipment
|
||||||
|
.filter(
|
||||||
|
(e) =>
|
||||||
|
String(e.department_id) ===
|
||||||
|
form.data.department_id,
|
||||||
|
)
|
||||||
|
.map((e) => (
|
||||||
|
<option key={e.id} value={e.id}>
|
||||||
|
{e.code} · {e.description}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
<label className="grid gap-2">
|
||||||
|
Referência documental
|
||||||
|
<textarea
|
||||||
|
className={controlClass}
|
||||||
|
required
|
||||||
|
maxLength={1000}
|
||||||
|
value={form.data.reference}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData('reference', e.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="grid gap-2">
|
||||||
|
Disponibilidade para novas escolhas
|
||||||
|
<select
|
||||||
|
className={controlClass}
|
||||||
|
value={form.data.state}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData('state', e.target.value)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="active">Activo</option>
|
||||||
|
<option value="archived">Arquivado</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label className="grid gap-2">
|
||||||
|
Motivo desta versão
|
||||||
|
<textarea
|
||||||
|
className={controlClass}
|
||||||
|
required
|
||||||
|
minLength={10}
|
||||||
|
maxLength={4000}
|
||||||
|
value={form.data.reason}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData('reason', e.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
O cadastro conserva referências documentais. Não
|
||||||
|
regista capitalização, depreciação ou movimentos
|
||||||
|
contabilísticos.
|
||||||
|
</p>
|
||||||
|
<Button disabled={form.processing}>
|
||||||
|
Guardar versão do cadastro
|
||||||
|
</Button>
|
||||||
|
{form.data.record_key && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => {
|
||||||
|
form.reset();
|
||||||
|
form.clearErrors();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Preparar outro registo
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
</Panel>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -64,6 +64,7 @@ type History = {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
type Props = {
|
type Props = {
|
||||||
|
capitalRegisterReady?: boolean;
|
||||||
geographyEnabled?: boolean;
|
geographyEnabled?: boolean;
|
||||||
equipmentGeography?: Record<number, GeographyDescription>;
|
equipmentGeography?: Record<number, GeographyDescription>;
|
||||||
geographyFilter?: GeographyDescription;
|
geographyFilter?: GeographyDescription;
|
||||||
@@ -107,6 +108,7 @@ export default function EquipmentPage({
|
|||||||
history,
|
history,
|
||||||
canManage,
|
canManage,
|
||||||
canConfigure,
|
canConfigure,
|
||||||
|
capitalRegisterReady = false,
|
||||||
demo = false,
|
demo = false,
|
||||||
geographyEnabled = false,
|
geographyEnabled = false,
|
||||||
equipmentGeography = {},
|
equipmentGeography = {},
|
||||||
@@ -157,6 +159,11 @@ export default function EquipmentPage({
|
|||||||
description="Cadastro, peças compatíveis, mínimos explícitos e rastreabilidade das saídas."
|
description="Cadastro, peças compatíveis, mínimos explícitos e rastreabilidade das saídas."
|
||||||
/>
|
/>
|
||||||
<InventoryNotice />
|
<InventoryNotice />
|
||||||
|
{capitalRegisterReady && (
|
||||||
|
<Link className="underline" href="/projectos-imobilizado">
|
||||||
|
Projectos e imobilizado
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
{geographyEnabled && !demo && (
|
{geographyEnabled && !demo && (
|
||||||
<Panel title="Localização dos equipamentos">
|
<Panel title="Localização dos equipamentos">
|
||||||
<TerritorialFilter
|
<TerritorialFilter
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { date, money, roleLabels } from '@/types/procurement';
|
|||||||
import { ExchangeSummary } from '@/components/quotation-exchange-panel';
|
import { ExchangeSummary } from '@/components/quotation-exchange-panel';
|
||||||
import type { PurchaseOrder } from '@/types/purchase';
|
import type { PurchaseOrder } from '@/types/purchase';
|
||||||
import ImportTariffSummary from '@/components/import-tariff-summary';
|
import ImportTariffSummary from '@/components/import-tariff-summary';
|
||||||
|
import CapitalAssignmentSummary from '@/components/capital-assignment-summary';
|
||||||
import OrderCancellationRequest, {
|
import OrderCancellationRequest, {
|
||||||
type OrderCancellationState,
|
type OrderCancellationState,
|
||||||
} from '@/components/order-cancellation-request';
|
} from '@/components/order-cancellation-request';
|
||||||
@@ -171,6 +172,9 @@ export default function OrderShow({
|
|||||||
</Link>
|
</Link>
|
||||||
)}
|
)}
|
||||||
<ImportTariffSummary records={snapshot.import_tariffs} />
|
<ImportTariffSummary records={snapshot.import_tariffs} />
|
||||||
|
<CapitalAssignmentSummary
|
||||||
|
records={snapshot.capital_assignments}
|
||||||
|
/>
|
||||||
<div className="grid gap-6 md:grid-cols-2">
|
<div className="grid gap-6 md:grid-cols-2">
|
||||||
{snapshot.investment_rules && (
|
{snapshot.investment_rules && (
|
||||||
<Panel title="Regra de investimento congelada">
|
<Panel title="Regra de investimento congelada">
|
||||||
|
|||||||
@@ -0,0 +1,306 @@
|
|||||||
|
import { Head, Link, useForm } from '@inertiajs/react';
|
||||||
|
import { useEffect, useRef } from 'react';
|
||||||
|
import {
|
||||||
|
FormErrors,
|
||||||
|
PageTitle,
|
||||||
|
Panel,
|
||||||
|
controlClass,
|
||||||
|
} from '@/components/procurement';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
|
||||||
|
type Source = {
|
||||||
|
id: number;
|
||||||
|
version: number;
|
||||||
|
data: { code: string; name: string; type: string; reference: string };
|
||||||
|
};
|
||||||
|
type Assignment = {
|
||||||
|
id: number;
|
||||||
|
version: number;
|
||||||
|
state: string;
|
||||||
|
reason: string;
|
||||||
|
data: { requisition_item_id: number };
|
||||||
|
snapshot: { item: { description: string }; source: Source | null };
|
||||||
|
};
|
||||||
|
type Page<T> = {
|
||||||
|
data: T[];
|
||||||
|
prev_page_url: string | null;
|
||||||
|
next_page_url: string | null;
|
||||||
|
};
|
||||||
|
type Props = {
|
||||||
|
requisition: { id: number; number: string; status: string };
|
||||||
|
items: { id: number; description: string }[];
|
||||||
|
current: Assignment[];
|
||||||
|
history: Page<Assignment>;
|
||||||
|
choices: Page<Source>;
|
||||||
|
canWrite: boolean;
|
||||||
|
actorId: number;
|
||||||
|
tenantId: number;
|
||||||
|
};
|
||||||
|
export default function CapitalAssignments(props: Props) {
|
||||||
|
const url = `/requisicoes/${props.requisition.id}/projectos-imobilizado`;
|
||||||
|
const form = useForm(
|
||||||
|
`capital-assignment:${props.tenantId}:${props.actorId}:${props.requisition.id}`,
|
||||||
|
{
|
||||||
|
operation_key: '',
|
||||||
|
item_id: '',
|
||||||
|
version: 0,
|
||||||
|
capital_id: '',
|
||||||
|
capital_label: '',
|
||||||
|
reason: '',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const ref = useRef<HTMLFormElement>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
const node = ref.current;
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent('sgc:context-dirty', {
|
||||||
|
detail: { form: node, dirty: form.isDirty },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return () => {
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent('sgc:context-dirty', {
|
||||||
|
detail: { form: node, dirty: false },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}, [form.isDirty]);
|
||||||
|
const chooseItem = (id: string) => {
|
||||||
|
const old = props.current.find(
|
||||||
|
(row) => String(row.data.requisition_item_id) === id,
|
||||||
|
);
|
||||||
|
const source = old?.snapshot.source;
|
||||||
|
form.setData({
|
||||||
|
operation_key: '',
|
||||||
|
item_id: id,
|
||||||
|
version: old?.version ?? 0,
|
||||||
|
capital_id: source ? String(source.id) : '',
|
||||||
|
capital_label: source
|
||||||
|
? `${source.data.code} · ${source.data.name} · v${source.version}`
|
||||||
|
: '',
|
||||||
|
reason: '',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<div className="mx-auto grid w-full max-w-6xl min-w-0 gap-6 p-5 lg:p-8">
|
||||||
|
<Head title="Destino por projecto ou imobilizado" />
|
||||||
|
<PageTitle
|
||||||
|
eyebrow={props.requisition.number}
|
||||||
|
title="Projecto ou imobilizado por artigo"
|
||||||
|
description="Seleccione a referência do cadastro próprio de Compras. A ligação preserva a versão escolhida e acompanha as novas ordens."
|
||||||
|
/>
|
||||||
|
<Link
|
||||||
|
className="underline"
|
||||||
|
href={`/requisicoes/${props.requisition.id}`}
|
||||||
|
>
|
||||||
|
Voltar à requisição
|
||||||
|
</Link>
|
||||||
|
<Panel title="Ligações actuais">
|
||||||
|
{props.current.length === 0 && (
|
||||||
|
<p>
|
||||||
|
Ainda não há ligações registadas. As origens anteriores
|
||||||
|
permanecem preservadas.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{props.current.map((row) => (
|
||||||
|
<article
|
||||||
|
key={row.id}
|
||||||
|
className="space-y-2 border-b py-4 break-words"
|
||||||
|
>
|
||||||
|
<h3 className="font-semibold">
|
||||||
|
{row.snapshot.item.description} · versão{' '}
|
||||||
|
{row.version}
|
||||||
|
</h3>
|
||||||
|
<p>
|
||||||
|
{row.state === 'cleared'
|
||||||
|
? 'Ligação retirada explicitamente'
|
||||||
|
: `${row.snapshot.source?.data.code} · ${row.snapshot.source?.data.name} · versão ${row.snapshot.source?.version}`}
|
||||||
|
</p>
|
||||||
|
<p>{row.reason}</p>
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
</Panel>
|
||||||
|
{props.canWrite && (
|
||||||
|
<Panel
|
||||||
|
title="Preparar ligação"
|
||||||
|
description="A escolha é explícita. As distribuições e decisões orçamentais conservam o seu percurso próprio."
|
||||||
|
>
|
||||||
|
<form
|
||||||
|
ref={ref}
|
||||||
|
className="space-y-4"
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const operation =
|
||||||
|
form.data.operation_key || crypto.randomUUID();
|
||||||
|
form.setData('operation_key', operation);
|
||||||
|
form.transform((data) => ({
|
||||||
|
operation_key: operation,
|
||||||
|
item_id: data.item_id,
|
||||||
|
version: data.version,
|
||||||
|
capital_id: data.capital_id || null,
|
||||||
|
reason: data.reason,
|
||||||
|
}));
|
||||||
|
form.post(url, {
|
||||||
|
preserveScroll: true,
|
||||||
|
onSuccess: () => {
|
||||||
|
form.reset();
|
||||||
|
form.clearErrors();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<FormErrors errors={form.errors} />
|
||||||
|
<label className="grid gap-2">
|
||||||
|
Artigo
|
||||||
|
<select
|
||||||
|
required
|
||||||
|
className={controlClass}
|
||||||
|
value={form.data.item_id}
|
||||||
|
onChange={(event) =>
|
||||||
|
chooseItem(event.target.value)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<option value="">Seleccione</option>
|
||||||
|
{props.items.map((item) => (
|
||||||
|
<option key={item.id} value={item.id}>
|
||||||
|
{item.description}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<p>
|
||||||
|
Referência seleccionada:{' '}
|
||||||
|
{form.data.capital_label || 'Sem ligação'} · versão
|
||||||
|
da preparação {form.data.version}
|
||||||
|
</p>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
Reveja o artigo actual antes de guardar. Uma
|
||||||
|
referência arquivada conserva-se no histórico e nas
|
||||||
|
escolhas já aceites; para uma nova ligação, escolha
|
||||||
|
uma versão activa.
|
||||||
|
</p>
|
||||||
|
{props.choices.data.map((source) => (
|
||||||
|
<article
|
||||||
|
key={source.id}
|
||||||
|
className="min-w-0 space-y-2 border-b py-3 break-words"
|
||||||
|
>
|
||||||
|
<p>
|
||||||
|
{source.data.type === 'project'
|
||||||
|
? 'Projecto'
|
||||||
|
: 'Imobilizado'}{' '}
|
||||||
|
· {source.data.code} · {source.data.name} ·
|
||||||
|
versão {source.version}
|
||||||
|
</p>
|
||||||
|
<p>{source.data.reference}</p>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
disabled={!form.data.item_id}
|
||||||
|
onClick={() =>
|
||||||
|
form.setData((data) => ({
|
||||||
|
...data,
|
||||||
|
capital_id: String(source.id),
|
||||||
|
capital_label: `${source.data.code} · ${source.data.name} · v${source.version}`,
|
||||||
|
operation_key: '',
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Escolher {source.data.code}
|
||||||
|
</Button>
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
{props.choices.data.length === 0 && (
|
||||||
|
<p>
|
||||||
|
Não há referências activas no departamento desta
|
||||||
|
requisição.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<nav
|
||||||
|
className="flex gap-4"
|
||||||
|
aria-label="Referências do cadastro"
|
||||||
|
>
|
||||||
|
{props.choices.prev_page_url && (
|
||||||
|
<Link
|
||||||
|
preserveState
|
||||||
|
href={props.choices.prev_page_url}
|
||||||
|
>
|
||||||
|
Anterior
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{props.choices.next_page_url && (
|
||||||
|
<Link
|
||||||
|
preserveState
|
||||||
|
href={props.choices.next_page_url}
|
||||||
|
>
|
||||||
|
Seguinte
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</nav>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
disabled={!form.data.item_id}
|
||||||
|
onClick={() =>
|
||||||
|
form.setData((data) => ({
|
||||||
|
...data,
|
||||||
|
capital_id: '',
|
||||||
|
capital_label: '',
|
||||||
|
operation_key: '',
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Retirar ligação desta preparação
|
||||||
|
</Button>
|
||||||
|
<label className="grid gap-2">
|
||||||
|
Motivo
|
||||||
|
<textarea
|
||||||
|
required
|
||||||
|
minLength={10}
|
||||||
|
maxLength={4000}
|
||||||
|
className={controlClass}
|
||||||
|
value={form.data.reason}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData('reason', e.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<Button
|
||||||
|
disabled={form.processing || !form.data.item_id}
|
||||||
|
>
|
||||||
|
Guardar ligação
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</Panel>
|
||||||
|
)}
|
||||||
|
<Panel title="Histórico preservado">
|
||||||
|
{props.history.data.map((row) => (
|
||||||
|
<article
|
||||||
|
key={row.id}
|
||||||
|
className="space-y-2 border-b py-3 break-words"
|
||||||
|
>
|
||||||
|
<p>
|
||||||
|
{row.snapshot.item.description} · versão{' '}
|
||||||
|
{row.version} ·{' '}
|
||||||
|
{row.snapshot.source
|
||||||
|
? `${row.snapshot.source.data.code} · v${row.snapshot.source.version}`
|
||||||
|
: 'Sem ligação'}
|
||||||
|
</p>
|
||||||
|
<p>{row.reason}</p>
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
<nav className="flex gap-4" aria-label="Histórico das ligações">
|
||||||
|
{props.history.prev_page_url && (
|
||||||
|
<Link preserveState href={props.history.prev_page_url}>
|
||||||
|
Anterior
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{props.history.next_page_url && (
|
||||||
|
<Link preserveState href={props.history.next_page_url}>
|
||||||
|
Seguinte
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</nav>
|
||||||
|
</Panel>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -55,8 +55,10 @@ export default function Show({
|
|||||||
canPrepareDistributions = false,
|
canPrepareDistributions = false,
|
||||||
importTariffsReady = false,
|
importTariffsReady = false,
|
||||||
importEstimatesReady = false,
|
importEstimatesReady = false,
|
||||||
|
capitalRegisterReady = false,
|
||||||
}: {
|
}: {
|
||||||
importEstimatesReady?: boolean;
|
importEstimatesReady?: boolean;
|
||||||
|
capitalRegisterReady?: boolean;
|
||||||
importTariffsReady?: boolean;
|
importTariffsReady?: boolean;
|
||||||
canPrepareDistributions?: boolean;
|
canPrepareDistributions?: boolean;
|
||||||
requisition: Requisition;
|
requisition: Requisition;
|
||||||
@@ -165,6 +167,15 @@ export default function Show({
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
<FormErrors errors={submission.errors} />
|
<FormErrors errors={submission.errors} />
|
||||||
|
{capitalRegisterReady && (
|
||||||
|
<Button asChild variant="outline">
|
||||||
|
<Link
|
||||||
|
href={`/requisicoes/${r.id}/projectos-imobilizado`}
|
||||||
|
>
|
||||||
|
Ligar artigos a projecto ou imobilizado
|
||||||
|
</Link>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
{importEstimatesReady && (
|
{importEstimatesReady && (
|
||||||
<Button asChild variant="outline">
|
<Button asChild variant="outline">
|
||||||
<Link
|
<Link
|
||||||
|
|||||||
@@ -0,0 +1,820 @@
|
|||||||
|
import { Head, Link, router, useForm } from '@inertiajs/react';
|
||||||
|
import { useEffect, useRef } from 'react';
|
||||||
|
import {
|
||||||
|
FormErrors,
|
||||||
|
PageTitle,
|
||||||
|
Panel,
|
||||||
|
controlClass,
|
||||||
|
} from '@/components/procurement';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { date } from '@/types/procurement';
|
||||||
|
|
||||||
|
type Document = {
|
||||||
|
id: number;
|
||||||
|
record_key: string;
|
||||||
|
version: number;
|
||||||
|
data: { type: string; reference: string; issuer_reference: string };
|
||||||
|
};
|
||||||
|
type Frozen = {
|
||||||
|
id: number;
|
||||||
|
type: string;
|
||||||
|
reference: string;
|
||||||
|
version: number;
|
||||||
|
issuer_reference: string;
|
||||||
|
};
|
||||||
|
type BankRecord = {
|
||||||
|
id: number;
|
||||||
|
record_key: string;
|
||||||
|
version: number;
|
||||||
|
state: string;
|
||||||
|
reason: string;
|
||||||
|
issues?: string[];
|
||||||
|
snapshot: { documents: Frozen[] };
|
||||||
|
data: {
|
||||||
|
commitment_document_id: number;
|
||||||
|
declaration_document_id: number | null;
|
||||||
|
support_document_ids: number[];
|
||||||
|
submission_document_id: number | null;
|
||||||
|
submission_basis: string | null;
|
||||||
|
submitted_on: string | null;
|
||||||
|
requirements_known: boolean;
|
||||||
|
required_support_types: string[];
|
||||||
|
required_support_counts: Record<string, number>;
|
||||||
|
requirements_basis: string;
|
||||||
|
due_on: string | null;
|
||||||
|
deadline_basis: string | null;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
type Page<T> = {
|
||||||
|
data: T[];
|
||||||
|
prev_page_url: string | null;
|
||||||
|
next_page_url: string | null;
|
||||||
|
};
|
||||||
|
type Props = {
|
||||||
|
importRecord: { id: number; record_key: string; version: number };
|
||||||
|
order: { id: number; number: string };
|
||||||
|
current: Page<BankRecord>;
|
||||||
|
history: Page<BankRecord>;
|
||||||
|
documents: Page<Document>;
|
||||||
|
types: Record<string, string>;
|
||||||
|
canWrite: boolean;
|
||||||
|
actorId: number;
|
||||||
|
tenantId: number;
|
||||||
|
today?: string;
|
||||||
|
};
|
||||||
|
const stateLabels: Record<string, string> = {
|
||||||
|
tracking: 'Documentação incompleta',
|
||||||
|
ready: 'Documentos reunidos; entrega por documentar',
|
||||||
|
documented: 'Comprovativo de entrega associado',
|
||||||
|
};
|
||||||
|
function Pages({ page }: { page: Page<unknown> }) {
|
||||||
|
return (
|
||||||
|
<nav className="mt-3 flex gap-4" aria-label="Páginas">
|
||||||
|
{page.prev_page_url && (
|
||||||
|
<Link preserveState href={page.prev_page_url}>
|
||||||
|
Anterior
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{page.next_page_url && (
|
||||||
|
<Link preserveState href={page.next_page_url}>
|
||||||
|
Seguinte
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
export default function ImportBankSupport(props: Props) {
|
||||||
|
const url = `/compras/importacoes/${props.importRecord.id}/suporte-bancario`;
|
||||||
|
const form = useForm(
|
||||||
|
`import-bank:${props.tenantId}:${props.actorId}:${props.importRecord.record_key}:${props.importRecord.version}`,
|
||||||
|
{
|
||||||
|
operation_key: '',
|
||||||
|
record_key: null as string | null,
|
||||||
|
version: 0,
|
||||||
|
commitment_document_id: '',
|
||||||
|
commitment_label: '',
|
||||||
|
declaration_document_id: '',
|
||||||
|
declaration_label: '',
|
||||||
|
support: [] as { id: number; reference: string }[],
|
||||||
|
submission_document_id: '',
|
||||||
|
submission_label: '',
|
||||||
|
submission_basis: '',
|
||||||
|
submitted_on: '',
|
||||||
|
requirements_known: false,
|
||||||
|
counts: {} as Record<string, string>,
|
||||||
|
requirements_basis: '',
|
||||||
|
due_on: '',
|
||||||
|
deadline_basis: '',
|
||||||
|
reason: '',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const ref = useRef<HTMLFormElement>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
const node = ref.current;
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent('sgc:context-dirty', {
|
||||||
|
detail: { form: node, dirty: form.isDirty },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
return () => {
|
||||||
|
window.dispatchEvent(
|
||||||
|
new CustomEvent('sgc:context-dirty', {
|
||||||
|
detail: { form: node, dirty: false },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}, [form.isDirty]);
|
||||||
|
const edit = (record: BankRecord) => {
|
||||||
|
const label = (id: number | null) =>
|
||||||
|
record.snapshot.documents.find((doc) => doc.id === id)?.reference ??
|
||||||
|
'';
|
||||||
|
form.setData({
|
||||||
|
operation_key: '',
|
||||||
|
record_key: record.record_key,
|
||||||
|
version: record.version,
|
||||||
|
commitment_document_id: String(record.data.commitment_document_id),
|
||||||
|
commitment_label: label(record.data.commitment_document_id),
|
||||||
|
declaration_document_id:
|
||||||
|
record.data.declaration_document_id === null
|
||||||
|
? ''
|
||||||
|
: String(record.data.declaration_document_id),
|
||||||
|
declaration_label: label(record.data.declaration_document_id),
|
||||||
|
support: record.data.support_document_ids.map((id) => ({
|
||||||
|
id,
|
||||||
|
reference: label(id),
|
||||||
|
})),
|
||||||
|
submission_document_id:
|
||||||
|
record.data.submission_document_id === null
|
||||||
|
? ''
|
||||||
|
: String(record.data.submission_document_id),
|
||||||
|
submission_label: label(record.data.submission_document_id),
|
||||||
|
submission_basis: record.data.submission_basis ?? '',
|
||||||
|
submitted_on: record.data.submitted_on ?? '',
|
||||||
|
requirements_known: record.data.requirements_known,
|
||||||
|
counts: Object.fromEntries(
|
||||||
|
Object.entries(record.data.required_support_counts).map(
|
||||||
|
([type, count]) => [type, String(count)],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
requirements_basis: record.data.requirements_basis,
|
||||||
|
due_on: record.data.due_on ?? '',
|
||||||
|
deadline_basis: record.data.deadline_basis ?? '',
|
||||||
|
reason: '',
|
||||||
|
});
|
||||||
|
form.clearErrors();
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Head title="Suporte documental bancário" />
|
||||||
|
<main className="mx-auto max-w-6xl space-y-5 px-5 py-8">
|
||||||
|
<PageTitle
|
||||||
|
eyebrow="Acompanhamento da importação"
|
||||||
|
title="Suporte documental bancário"
|
||||||
|
description={`Ordem ${props.order.number}. Ligue o termo de compromisso ao documento único e acompanhe os documentos pedidos pelo banco.`}
|
||||||
|
/>
|
||||||
|
<div className="flex flex-wrap gap-4">
|
||||||
|
<Link
|
||||||
|
className="underline"
|
||||||
|
href={`/compras/importacoes/${props.importRecord.id}/documentos`}
|
||||||
|
>
|
||||||
|
Originais do dossiê
|
||||||
|
</Link>
|
||||||
|
<a className="underline" href={`${url}.csv`}>
|
||||||
|
Exportar acompanhamento CSV
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<Panel
|
||||||
|
title="Situação por termo"
|
||||||
|
description="Documentos reunidos não demonstram a entrega ao banco. Um comprovativo registado não certifica cumprimento bancário, nem executa transferência ou submissão na JUE."
|
||||||
|
>
|
||||||
|
{props.current.data.length === 0 && (
|
||||||
|
<p>Ainda não há termos acompanhados neste âmbito.</p>
|
||||||
|
)}
|
||||||
|
{props.current.data.map((record) => (
|
||||||
|
<article
|
||||||
|
key={record.id}
|
||||||
|
className="space-y-2 border-b py-4"
|
||||||
|
>
|
||||||
|
<p className="font-medium">
|
||||||
|
{
|
||||||
|
record.snapshot.documents.find(
|
||||||
|
(doc) =>
|
||||||
|
doc.id ===
|
||||||
|
record.data.commitment_document_id,
|
||||||
|
)?.reference
|
||||||
|
}{' '}
|
||||||
|
· versão {record.version}
|
||||||
|
</p>
|
||||||
|
<p>{stateLabels[record.state] ?? record.state}</p>
|
||||||
|
<p>
|
||||||
|
Prazo:{' '}
|
||||||
|
{record.data.due_on
|
||||||
|
? date(record.data.due_on)
|
||||||
|
: 'Por indicar'}{' '}
|
||||||
|
·{' '}
|
||||||
|
{record.data.deadline_basis ??
|
||||||
|
'Sem prazo presumido'}
|
||||||
|
</p>
|
||||||
|
{(record.issues ?? []).map((issue) => (
|
||||||
|
<p key={issue} role="status">
|
||||||
|
{issue}
|
||||||
|
</p>
|
||||||
|
))}
|
||||||
|
<p>
|
||||||
|
Entrega documentada:{' '}
|
||||||
|
{record.data.submitted_on
|
||||||
|
? date(record.data.submitted_on)
|
||||||
|
: 'Por indicar'}{' '}
|
||||||
|
· {record.data.submission_basis}
|
||||||
|
</p>
|
||||||
|
<p>{record.reason}</p>
|
||||||
|
{props.canWrite && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => edit(record)}
|
||||||
|
>
|
||||||
|
Preparar nova versão
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
<Pages page={props.current} />
|
||||||
|
</Panel>
|
||||||
|
{props.canWrite && (
|
||||||
|
<Panel
|
||||||
|
title={
|
||||||
|
form.data.record_key
|
||||||
|
? `Rever acompanhamento · versão ${form.data.version}`
|
||||||
|
: 'Acompanhar um termo existente'
|
||||||
|
}
|
||||||
|
description="Seleccione os originais já registados. Indique apenas requisitos, prazos e informação novos deste acompanhamento."
|
||||||
|
>
|
||||||
|
<form
|
||||||
|
ref={ref}
|
||||||
|
className="space-y-5"
|
||||||
|
onSubmit={(event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const operation =
|
||||||
|
form.data.operation_key ||
|
||||||
|
crypto.randomUUID();
|
||||||
|
form.setData('operation_key', operation);
|
||||||
|
form.transform((data) => ({
|
||||||
|
operation_key: operation,
|
||||||
|
record_key: data.record_key,
|
||||||
|
version: data.version,
|
||||||
|
commitment_document_id:
|
||||||
|
data.commitment_document_id,
|
||||||
|
declaration_document_id:
|
||||||
|
data.declaration_document_id || null,
|
||||||
|
support_document_ids: data.support.map(
|
||||||
|
(doc) => doc.id,
|
||||||
|
),
|
||||||
|
submission_document_id:
|
||||||
|
data.submission_document_id || null,
|
||||||
|
submission_basis:
|
||||||
|
data.submission_basis || null,
|
||||||
|
submitted_on: data.submission_document_id
|
||||||
|
? data.submitted_on || null
|
||||||
|
: null,
|
||||||
|
requirements_known: data.requirements_known,
|
||||||
|
required_support_types:
|
||||||
|
data.requirements_known
|
||||||
|
? Object.keys(data.counts)
|
||||||
|
: [],
|
||||||
|
required_support_counts:
|
||||||
|
data.requirements_known
|
||||||
|
? data.counts
|
||||||
|
: {},
|
||||||
|
requirements_basis: data.requirements_basis,
|
||||||
|
due_on: data.due_on || null,
|
||||||
|
deadline_basis: data.deadline_basis || null,
|
||||||
|
reason: data.reason,
|
||||||
|
}));
|
||||||
|
form.post(url, {
|
||||||
|
preserveScroll: true,
|
||||||
|
onSuccess: () => {
|
||||||
|
form.reset();
|
||||||
|
router.visit(url, {
|
||||||
|
preserveState: false,
|
||||||
|
preserveScroll: true,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<FormErrors errors={form.errors} />
|
||||||
|
<div className="grid gap-4 md:grid-cols-3">
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Termo de compromisso
|
||||||
|
<select
|
||||||
|
required
|
||||||
|
className={controlClass}
|
||||||
|
value={form.data.commitment_document_id}
|
||||||
|
onChange={(e) => {
|
||||||
|
const doc =
|
||||||
|
props.documents.data.find(
|
||||||
|
(d) =>
|
||||||
|
String(d.id) ===
|
||||||
|
e.target.value,
|
||||||
|
);
|
||||||
|
form.setData((data) => ({
|
||||||
|
...data,
|
||||||
|
commitment_document_id:
|
||||||
|
e.target.value,
|
||||||
|
commitment_label:
|
||||||
|
doc?.data.reference ?? '',
|
||||||
|
}));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">Seleccione</option>
|
||||||
|
{form.data.commitment_document_id &&
|
||||||
|
!props.documents.data.some(
|
||||||
|
(doc) =>
|
||||||
|
String(doc.id) ===
|
||||||
|
form.data
|
||||||
|
.commitment_document_id,
|
||||||
|
) && (
|
||||||
|
<option
|
||||||
|
value={
|
||||||
|
form.data
|
||||||
|
.commitment_document_id
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{form.data.commitment_label}{' '}
|
||||||
|
· seleccionado noutra página
|
||||||
|
</option>
|
||||||
|
)}
|
||||||
|
{props.documents.data
|
||||||
|
.filter(
|
||||||
|
(doc) =>
|
||||||
|
doc.data.type ===
|
||||||
|
'bank_commitment',
|
||||||
|
)
|
||||||
|
.map((doc) => (
|
||||||
|
<option
|
||||||
|
key={doc.id}
|
||||||
|
value={doc.id}
|
||||||
|
>
|
||||||
|
{doc.data.reference} · v
|
||||||
|
{doc.version}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Documento único / declaração
|
||||||
|
<select
|
||||||
|
className={controlClass}
|
||||||
|
value={
|
||||||
|
form.data.declaration_document_id
|
||||||
|
}
|
||||||
|
onChange={(e) => {
|
||||||
|
const doc =
|
||||||
|
props.documents.data.find(
|
||||||
|
(d) =>
|
||||||
|
String(d.id) ===
|
||||||
|
e.target.value,
|
||||||
|
);
|
||||||
|
form.setData((data) => ({
|
||||||
|
...data,
|
||||||
|
declaration_document_id:
|
||||||
|
e.target.value,
|
||||||
|
declaration_label:
|
||||||
|
doc?.data.reference ?? '',
|
||||||
|
}));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">
|
||||||
|
Ainda por associar
|
||||||
|
</option>
|
||||||
|
{form.data.declaration_document_id &&
|
||||||
|
!props.documents.data.some(
|
||||||
|
(doc) =>
|
||||||
|
String(doc.id) ===
|
||||||
|
form.data
|
||||||
|
.declaration_document_id,
|
||||||
|
) && (
|
||||||
|
<option
|
||||||
|
value={
|
||||||
|
form.data
|
||||||
|
.declaration_document_id
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{
|
||||||
|
form.data
|
||||||
|
.declaration_label
|
||||||
|
}{' '}
|
||||||
|
· seleccionado noutra página
|
||||||
|
</option>
|
||||||
|
)}
|
||||||
|
{props.documents.data
|
||||||
|
.filter(
|
||||||
|
(doc) =>
|
||||||
|
doc.data.type ===
|
||||||
|
'customs_declaration',
|
||||||
|
)
|
||||||
|
.map((doc) => (
|
||||||
|
<option
|
||||||
|
key={doc.id}
|
||||||
|
value={doc.id}
|
||||||
|
>
|
||||||
|
{doc.data.reference} · v
|
||||||
|
{doc.version}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Comprovativo de entrega ao banco
|
||||||
|
<select
|
||||||
|
className={controlClass}
|
||||||
|
value={form.data.submission_document_id}
|
||||||
|
onChange={(e) => {
|
||||||
|
const doc =
|
||||||
|
props.documents.data.find(
|
||||||
|
(d) =>
|
||||||
|
String(d.id) ===
|
||||||
|
e.target.value,
|
||||||
|
);
|
||||||
|
form.setData((data) => ({
|
||||||
|
...data,
|
||||||
|
submission_document_id:
|
||||||
|
e.target.value,
|
||||||
|
submission_label:
|
||||||
|
doc?.data.reference ?? '',
|
||||||
|
}));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">
|
||||||
|
Ainda por associar
|
||||||
|
</option>
|
||||||
|
{form.data.submission_document_id &&
|
||||||
|
!props.documents.data.some(
|
||||||
|
(doc) =>
|
||||||
|
String(doc.id) ===
|
||||||
|
form.data
|
||||||
|
.submission_document_id,
|
||||||
|
) && (
|
||||||
|
<option
|
||||||
|
value={
|
||||||
|
form.data
|
||||||
|
.submission_document_id
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{form.data.submission_label}{' '}
|
||||||
|
· seleccionado noutra página
|
||||||
|
</option>
|
||||||
|
)}
|
||||||
|
{props.documents.data
|
||||||
|
.filter(
|
||||||
|
(doc) =>
|
||||||
|
doc.data.type ===
|
||||||
|
'bank_support',
|
||||||
|
)
|
||||||
|
.map((doc) => (
|
||||||
|
<option
|
||||||
|
key={doc.id}
|
||||||
|
value={doc.id}
|
||||||
|
>
|
||||||
|
{doc.data.reference} · v
|
||||||
|
{doc.version}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
{form.data.submission_document_id && (
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Fundamento do comprovativo de entrega
|
||||||
|
<textarea
|
||||||
|
required
|
||||||
|
minLength={3}
|
||||||
|
maxLength={1000}
|
||||||
|
className={controlClass}
|
||||||
|
value={form.data.submission_basis}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData(
|
||||||
|
'submission_basis',
|
||||||
|
e.target.value,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
{form.data.submission_document_id && (
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Data efectiva da entrega documentada
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
required
|
||||||
|
max={props.today}
|
||||||
|
className={controlClass}
|
||||||
|
value={form.data.submitted_on}
|
||||||
|
onChange={(event) =>
|
||||||
|
form.setData(
|
||||||
|
'submitted_on',
|
||||||
|
event.target.value,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
<fieldset className="space-y-3 rounded border p-4">
|
||||||
|
<legend>
|
||||||
|
Documentos de suporte seleccionados
|
||||||
|
</legend>
|
||||||
|
{form.data.support.map((doc) => (
|
||||||
|
<div
|
||||||
|
key={doc.id}
|
||||||
|
className="flex flex-wrap items-center gap-3"
|
||||||
|
>
|
||||||
|
<span>{doc.reference}</span>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
onClick={() =>
|
||||||
|
form.setData(
|
||||||
|
'support',
|
||||||
|
form.data.support.filter(
|
||||||
|
(d) => d.id !== doc.id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Retirar da preparação
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{props.documents.data
|
||||||
|
.filter(
|
||||||
|
(doc) =>
|
||||||
|
doc.data.type !== 'bank_commitment',
|
||||||
|
)
|
||||||
|
.map((doc) => (
|
||||||
|
<label
|
||||||
|
key={doc.id}
|
||||||
|
className="flex gap-2"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={form.data.support.some(
|
||||||
|
(selected) =>
|
||||||
|
selected.id === doc.id,
|
||||||
|
)}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData(
|
||||||
|
'support',
|
||||||
|
e.target.checked
|
||||||
|
? [
|
||||||
|
...form.data
|
||||||
|
.support,
|
||||||
|
{
|
||||||
|
id: doc.id,
|
||||||
|
reference:
|
||||||
|
doc
|
||||||
|
.data
|
||||||
|
.reference,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: form.data.support.filter(
|
||||||
|
(d) =>
|
||||||
|
d.id !==
|
||||||
|
doc.id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
|
{props.types[doc.data.type]} ·{' '}
|
||||||
|
{doc.data.reference} · v
|
||||||
|
{doc.version}
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
<Pages page={props.documents} />
|
||||||
|
</fieldset>
|
||||||
|
<label className="flex gap-2">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={form.data.requirements_known}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData(
|
||||||
|
'requirements_known',
|
||||||
|
e.target.checked,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
Os requisitos documentais pedidos pelo banco
|
||||||
|
estão identificados
|
||||||
|
</label>
|
||||||
|
{form.data.requirements_known && (
|
||||||
|
<fieldset className="grid gap-3 rounded border p-4 sm:grid-cols-2">
|
||||||
|
<legend>
|
||||||
|
Tipos e quantidades pedidos pelo banco
|
||||||
|
</legend>
|
||||||
|
{Object.entries(props.types)
|
||||||
|
.filter(
|
||||||
|
([type]) =>
|
||||||
|
type !== 'bank_commitment',
|
||||||
|
)
|
||||||
|
.map(([type, label]) => (
|
||||||
|
<div
|
||||||
|
key={type}
|
||||||
|
className="space-y-1"
|
||||||
|
>
|
||||||
|
<label className="flex gap-2">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={Object.hasOwn(
|
||||||
|
form.data.counts,
|
||||||
|
type,
|
||||||
|
)}
|
||||||
|
onChange={(e) => {
|
||||||
|
const counts = {
|
||||||
|
...form.data
|
||||||
|
.counts,
|
||||||
|
};
|
||||||
|
if (
|
||||||
|
e.target.checked
|
||||||
|
)
|
||||||
|
counts[type] =
|
||||||
|
'';
|
||||||
|
else
|
||||||
|
delete counts[
|
||||||
|
type
|
||||||
|
];
|
||||||
|
form.setData(
|
||||||
|
'counts',
|
||||||
|
counts,
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{label}
|
||||||
|
</label>
|
||||||
|
{Object.hasOwn(
|
||||||
|
form.data.counts,
|
||||||
|
type,
|
||||||
|
) && (
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Quantidade solicitada
|
||||||
|
<input
|
||||||
|
required
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
max={100}
|
||||||
|
step={1}
|
||||||
|
className={
|
||||||
|
controlClass
|
||||||
|
}
|
||||||
|
value={
|
||||||
|
form.data
|
||||||
|
.counts[
|
||||||
|
type
|
||||||
|
]
|
||||||
|
}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData(
|
||||||
|
'counts',
|
||||||
|
{
|
||||||
|
...form
|
||||||
|
.data
|
||||||
|
.counts,
|
||||||
|
[type]: e
|
||||||
|
.target
|
||||||
|
.value,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</fieldset>
|
||||||
|
)}
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Fonte dos requisitos ou informação ainda em
|
||||||
|
falta
|
||||||
|
<textarea
|
||||||
|
required
|
||||||
|
minLength={3}
|
||||||
|
maxLength={1000}
|
||||||
|
className={controlClass}
|
||||||
|
value={form.data.requirements_basis}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData(
|
||||||
|
'requirements_basis',
|
||||||
|
e.target.value,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2">
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Prazo documental indicado
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
className={controlClass}
|
||||||
|
value={form.data.due_on}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData(
|
||||||
|
'due_on',
|
||||||
|
e.target.value,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Fonte do prazo
|
||||||
|
<textarea
|
||||||
|
required={Boolean(form.data.due_on)}
|
||||||
|
minLength={3}
|
||||||
|
maxLength={1000}
|
||||||
|
className={controlClass}
|
||||||
|
value={form.data.deadline_basis}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData(
|
||||||
|
'deadline_basis',
|
||||||
|
e.target.value,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Motivo desta versão
|
||||||
|
<textarea
|
||||||
|
required
|
||||||
|
minLength={10}
|
||||||
|
maxLength={4000}
|
||||||
|
className={controlClass}
|
||||||
|
value={form.data.reason}
|
||||||
|
onChange={(e) =>
|
||||||
|
form.setData('reason', e.target.value)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<Button disabled={form.processing}>
|
||||||
|
Guardar acompanhamento documental
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
</Panel>
|
||||||
|
)}
|
||||||
|
<Panel title="Histórico preservado">
|
||||||
|
{props.history.data.map((record) => (
|
||||||
|
<article
|
||||||
|
key={record.id}
|
||||||
|
className="space-y-1 border-b py-3"
|
||||||
|
>
|
||||||
|
<p>
|
||||||
|
Versão {record.version} ·{' '}
|
||||||
|
{stateLabels[record.state] ?? record.state}
|
||||||
|
</p>
|
||||||
|
<p>{record.reason}</p>
|
||||||
|
<p>
|
||||||
|
Requisitos:{' '}
|
||||||
|
{record.data.requirements_known
|
||||||
|
? record.data.required_support_types
|
||||||
|
.map(
|
||||||
|
(type) =>
|
||||||
|
`${props.types[type]}: ${record.data.required_support_counts[type]}`,
|
||||||
|
)
|
||||||
|
.join('; ') ||
|
||||||
|
'Nenhum tipo exigido segundo a fonte registada'
|
||||||
|
: 'Ainda desconhecidos'}{' '}
|
||||||
|
· {record.data.requirements_basis}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Entrega documentada:{' '}
|
||||||
|
{record.data.submitted_on
|
||||||
|
? date(record.data.submitted_on)
|
||||||
|
: 'Por indicar'}{' '}
|
||||||
|
· {record.data.submission_basis}
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
Prazo:{' '}
|
||||||
|
{record.data.due_on
|
||||||
|
? date(record.data.due_on)
|
||||||
|
: 'Desconhecido'}{' '}
|
||||||
|
· {record.data.deadline_basis}
|
||||||
|
</p>
|
||||||
|
{record.snapshot.documents.map((doc) => (
|
||||||
|
<p key={doc.id}>
|
||||||
|
<a
|
||||||
|
className="underline"
|
||||||
|
href={`/compras/importacoes/${props.importRecord.id}/documentos/${doc.id}`}
|
||||||
|
>
|
||||||
|
{props.types[doc.type]} ·{' '}
|
||||||
|
{doc.reference} · v{doc.version}
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
))}
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
<Pages page={props.history} />
|
||||||
|
</Panel>
|
||||||
|
</main>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -38,6 +38,8 @@ type Props = {
|
|||||||
actorId: number;
|
actorId: number;
|
||||||
tenantId: number;
|
tenantId: number;
|
||||||
parties?: ImportPartyWorkspace;
|
parties?: ImportPartyWorkspace;
|
||||||
|
bankSupportReady?: boolean;
|
||||||
|
readinessReady?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function Dossier({
|
export default function Dossier({
|
||||||
@@ -49,6 +51,8 @@ export default function Dossier({
|
|||||||
actorId,
|
actorId,
|
||||||
tenantId,
|
tenantId,
|
||||||
parties,
|
parties,
|
||||||
|
bankSupportReady = false,
|
||||||
|
readinessReady = false,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const form = useForm(
|
const form = useForm(
|
||||||
`import-dossier:${tenantId}:${actorId}:${importRecord.record_key}:${importRecord.version}`,
|
`import-dossier:${tenantId}:${actorId}:${importRecord.record_key}:${importRecord.version}`,
|
||||||
@@ -116,6 +120,22 @@ export default function Dossier({
|
|||||||
<Link className="underline" href={`/ordens/${order.id}`}>
|
<Link className="underline" href={`/ordens/${order.id}`}>
|
||||||
Consultar a ordem e as suas origens
|
Consultar a ordem e as suas origens
|
||||||
</Link>
|
</Link>
|
||||||
|
{readinessReady && (
|
||||||
|
<Link
|
||||||
|
className="underline"
|
||||||
|
href={`/compras/importacoes/${importRecord.id}/acompanhamento`}
|
||||||
|
>
|
||||||
|
Consultar alertas e próximos passos
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
{bankSupportReady && (
|
||||||
|
<Link
|
||||||
|
className="underline"
|
||||||
|
href={`/compras/importacoes/${importRecord.id}/suporte-bancario`}
|
||||||
|
>
|
||||||
|
Acompanhar termo e suporte bancário
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
{parties && (
|
{parties && (
|
||||||
<ImportPartySelection
|
<ImportPartySelection
|
||||||
workspace={parties}
|
workspace={parties}
|
||||||
|
|||||||
@@ -33,6 +33,14 @@ type Version = {
|
|||||||
reason: string;
|
reason: string;
|
||||||
data: { budget_id: number; components: Component[] };
|
data: { budget_id: number; components: Component[] };
|
||||||
snapshot: {
|
snapshot: {
|
||||||
|
legal_sources?: Record<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
estimate_id: number;
|
||||||
|
estimate_version: number;
|
||||||
|
charge_key: string;
|
||||||
|
}
|
||||||
|
>;
|
||||||
plan: {
|
plan: {
|
||||||
complete: boolean;
|
complete: boolean;
|
||||||
budget_amount_minor: number | null;
|
budget_amount_minor: number | null;
|
||||||
@@ -47,6 +55,23 @@ type Page<T> = {
|
|||||||
next_page_url: string | null;
|
next_page_url: string | null;
|
||||||
};
|
};
|
||||||
type Props = {
|
type Props = {
|
||||||
|
legalAmounts?: {
|
||||||
|
id: number;
|
||||||
|
version: number;
|
||||||
|
snapshot: {
|
||||||
|
item: { description: string };
|
||||||
|
legal_rule: { data: { official_reference: string } };
|
||||||
|
result: {
|
||||||
|
lines: {
|
||||||
|
key: string;
|
||||||
|
kind: string;
|
||||||
|
label: string;
|
||||||
|
method: string;
|
||||||
|
amount_minor: number | null;
|
||||||
|
}[];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}[];
|
||||||
requisition: {
|
requisition: {
|
||||||
id: number;
|
id: number;
|
||||||
number: string;
|
number: string;
|
||||||
@@ -105,6 +130,12 @@ export default function ImportEstimate(props: Props) {
|
|||||||
subtotal: estimateMoney(row.subtotal_minor),
|
subtotal: estimateMoney(row.subtotal_minor),
|
||||||
tax: estimateMoney(row.tax_minor),
|
tax: estimateMoney(row.tax_minor),
|
||||||
total: estimateMoney(row.total_minor),
|
total: estimateMoney(row.total_minor),
|
||||||
|
legal_estimate_id:
|
||||||
|
latest?.snapshot.legal_sources?.[row.key]?.estimate_id ??
|
||||||
|
(null as number | null),
|
||||||
|
legal_charge_key:
|
||||||
|
latest?.snapshot.legal_sources?.[row.key]?.charge_key ??
|
||||||
|
(null as string | null),
|
||||||
})),
|
})),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -185,6 +216,25 @@ export default function ImportEstimate(props: Props) {
|
|||||||
form.setData('operation_key', operation);
|
form.setData('operation_key', operation);
|
||||||
form.transform((data) => ({
|
form.transform((data) => ({
|
||||||
...data,
|
...data,
|
||||||
|
legal_sources: Object.fromEntries(
|
||||||
|
data.components
|
||||||
|
.filter(
|
||||||
|
(row) =>
|
||||||
|
row.legal_estimate_id !==
|
||||||
|
null &&
|
||||||
|
row.legal_charge_key !==
|
||||||
|
null,
|
||||||
|
)
|
||||||
|
.map((row) => [
|
||||||
|
row.key,
|
||||||
|
{
|
||||||
|
estimate_id:
|
||||||
|
row.legal_estimate_id,
|
||||||
|
charge_key:
|
||||||
|
row.legal_charge_key,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
),
|
||||||
operation_key: operation,
|
operation_key: operation,
|
||||||
components: data.components.map((row) => ({
|
components: data.components.map((row) => ({
|
||||||
key: row.key,
|
key: row.key,
|
||||||
@@ -260,6 +310,174 @@ export default function ImportEstimate(props: Props) {
|
|||||||
<legend>
|
<legend>
|
||||||
{labels[row.kind] ?? row.kind}
|
{labels[row.kind] ?? row.kind}
|
||||||
</legend>
|
</legend>
|
||||||
|
{((props.legalAmounts?.length ?? 0) > 0 ||
|
||||||
|
row.legal_estimate_id !== null) && (
|
||||||
|
<label className="grid gap-1">
|
||||||
|
Reutilizar uma imposição calculada
|
||||||
|
<select
|
||||||
|
className={controlClass}
|
||||||
|
value={
|
||||||
|
row.legal_estimate_id ===
|
||||||
|
null
|
||||||
|
? ''
|
||||||
|
: `${row.legal_estimate_id}:${row.legal_charge_key}`
|
||||||
|
}
|
||||||
|
onChange={(event) => {
|
||||||
|
const candidates = (
|
||||||
|
props.legalAmounts ?? []
|
||||||
|
).flatMap((estimate) =>
|
||||||
|
estimate.snapshot.result.lines
|
||||||
|
.filter(
|
||||||
|
(line) =>
|
||||||
|
line.kind ===
|
||||||
|
row.kind,
|
||||||
|
)
|
||||||
|
.map((line) => ({
|
||||||
|
estimate,
|
||||||
|
line,
|
||||||
|
value: `${estimate.id}:${line.key}`,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
const selected =
|
||||||
|
candidates.find(
|
||||||
|
(candidate) =>
|
||||||
|
candidate.value ===
|
||||||
|
event.target
|
||||||
|
.value,
|
||||||
|
);
|
||||||
|
form.setData(
|
||||||
|
'components',
|
||||||
|
form.data.components.map(
|
||||||
|
(component, at) =>
|
||||||
|
at !== index
|
||||||
|
? component
|
||||||
|
: selected
|
||||||
|
? {
|
||||||
|
...component,
|
||||||
|
legal_estimate_id:
|
||||||
|
selected
|
||||||
|
.estimate
|
||||||
|
.id,
|
||||||
|
legal_charge_key:
|
||||||
|
selected
|
||||||
|
.line
|
||||||
|
.key,
|
||||||
|
status:
|
||||||
|
selected
|
||||||
|
.line
|
||||||
|
.amount_minor ===
|
||||||
|
null
|
||||||
|
? 'unknown'
|
||||||
|
: selected
|
||||||
|
.line
|
||||||
|
.method ===
|
||||||
|
'not_applicable'
|
||||||
|
? 'not_applicable'
|
||||||
|
: 'known',
|
||||||
|
basis: `Estimativa legal #${selected.estimate.id}, versão ${selected.estimate.version}; ${selected.line.label}. Fonte: ${selected.estimate.snapshot.legal_rule.data.official_reference}.`,
|
||||||
|
total: estimateMoney(
|
||||||
|
selected
|
||||||
|
.line
|
||||||
|
.amount_minor,
|
||||||
|
),
|
||||||
|
subtotal:
|
||||||
|
selected
|
||||||
|
.line
|
||||||
|
.amount_minor ===
|
||||||
|
0
|
||||||
|
? '0.00'
|
||||||
|
: '',
|
||||||
|
tax:
|
||||||
|
selected
|
||||||
|
.line
|
||||||
|
.amount_minor ===
|
||||||
|
0
|
||||||
|
? '0.00'
|
||||||
|
: '',
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
...component,
|
||||||
|
legal_estimate_id:
|
||||||
|
null,
|
||||||
|
legal_charge_key:
|
||||||
|
null,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<option value="">
|
||||||
|
Pressuposto manual / retirar
|
||||||
|
ligação e conservar os
|
||||||
|
valores
|
||||||
|
</option>
|
||||||
|
{row.legal_estimate_id !==
|
||||||
|
null &&
|
||||||
|
!(
|
||||||
|
props.legalAmounts ?? []
|
||||||
|
).some(
|
||||||
|
(estimate) =>
|
||||||
|
estimate.id ===
|
||||||
|
row.legal_estimate_id,
|
||||||
|
) && (
|
||||||
|
<option
|
||||||
|
value={`${row.legal_estimate_id}:${row.legal_charge_key}`}
|
||||||
|
>
|
||||||
|
Versão preservada da
|
||||||
|
estimativa #
|
||||||
|
{
|
||||||
|
row.legal_estimate_id
|
||||||
|
}
|
||||||
|
</option>
|
||||||
|
)}
|
||||||
|
{(
|
||||||
|
props.legalAmounts ?? []
|
||||||
|
).flatMap((estimate) =>
|
||||||
|
estimate.snapshot.result.lines
|
||||||
|
.filter(
|
||||||
|
(line) =>
|
||||||
|
line.kind ===
|
||||||
|
row.kind,
|
||||||
|
)
|
||||||
|
.map((line) => (
|
||||||
|
<option
|
||||||
|
key={`${estimate.id}:${line.key}`}
|
||||||
|
value={`${estimate.id}:${line.key}`}
|
||||||
|
>
|
||||||
|
{
|
||||||
|
estimate
|
||||||
|
.snapshot
|
||||||
|
.item
|
||||||
|
.description
|
||||||
|
}{' '}
|
||||||
|
· {line.label} ·
|
||||||
|
estimativa #
|
||||||
|
{estimate.id} v
|
||||||
|
{
|
||||||
|
estimate.version
|
||||||
|
}{' '}
|
||||||
|
·{' '}
|
||||||
|
{line.amount_minor ===
|
||||||
|
null
|
||||||
|
? 'Por determinar'
|
||||||
|
: `${estimateMoney(line.amount_minor)} MZN`}
|
||||||
|
</option>
|
||||||
|
)),
|
||||||
|
)}
|
||||||
|
</select>
|
||||||
|
{row.legal_estimate_id !== null && (
|
||||||
|
<span>
|
||||||
|
O total conserva a fonte
|
||||||
|
seleccionada. Indique
|
||||||
|
explicitamente a divisão
|
||||||
|
entre base e imposto segundo
|
||||||
|
o orçamento. Para alterar o
|
||||||
|
montante, retire primeiro a
|
||||||
|
ligação.
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
<label className="grid gap-1">
|
<label className="grid gap-1">
|
||||||
Situação
|
Situação
|
||||||
<select
|
<select
|
||||||
@@ -366,6 +584,54 @@ export default function ImportEstimate(props: Props) {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
|
<div className="flex flex-wrap gap-3">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
disabled={
|
||||||
|
form.data.components.length >=
|
||||||
|
100
|
||||||
|
}
|
||||||
|
onClick={() =>
|
||||||
|
form.setData('components', [
|
||||||
|
...form.data.components,
|
||||||
|
{
|
||||||
|
key: crypto.randomUUID(),
|
||||||
|
kind: row.kind,
|
||||||
|
status: 'unknown',
|
||||||
|
basis: '',
|
||||||
|
subtotal: '',
|
||||||
|
tax: '',
|
||||||
|
total: '',
|
||||||
|
legal_estimate_id: null,
|
||||||
|
legal_charge_key: null,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Acrescentar parcela desta família
|
||||||
|
</Button>
|
||||||
|
{form.data.components.filter(
|
||||||
|
(component) =>
|
||||||
|
component.kind === row.kind,
|
||||||
|
).length > 1 && (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() =>
|
||||||
|
form.setData(
|
||||||
|
'components',
|
||||||
|
form.data.components.filter(
|
||||||
|
(_, at) =>
|
||||||
|
at !== index,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Retirar parcela da preparação
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
))}
|
))}
|
||||||
<label className="grid gap-1">
|
<label className="grid gap-1">
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,73 @@
|
|||||||
|
import { Head, Link } from '@inertiajs/react';
|
||||||
|
import { PageTitle, Panel } from '@/components/procurement';
|
||||||
|
import { date } from '@/types/procurement';
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
importRecord: { id: number; version: number; state: string };
|
||||||
|
order: { id: number; number: string };
|
||||||
|
expectedUsableOn: string | null;
|
||||||
|
checkedAt: string;
|
||||||
|
complete: boolean;
|
||||||
|
alerts: { key: string; category: string; text: string; href: string }[];
|
||||||
|
};
|
||||||
|
export default function ImportReadiness(props: Props) {
|
||||||
|
return (
|
||||||
|
<main className="mx-auto max-w-5xl space-y-5 px-5 py-8">
|
||||||
|
<Head title="Acompanhamento da importação" />
|
||||||
|
<PageTitle
|
||||||
|
eyebrow={`Ordem ${props.order.number}`}
|
||||||
|
title="Acompanhamento da importação"
|
||||||
|
description="Consulte os documentos em falta, alterações de fontes e próximos passos dos percursos existentes."
|
||||||
|
/>
|
||||||
|
<div className="flex flex-wrap gap-4">
|
||||||
|
<Link
|
||||||
|
className="underline"
|
||||||
|
href={`/compras/importacoes/${props.importRecord.id}/documentos`}
|
||||||
|
>
|
||||||
|
Abrir dossiê
|
||||||
|
</Link>
|
||||||
|
<Link className="underline" href="/compras/fornecimento/import">
|
||||||
|
Voltar às importações
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
<Panel
|
||||||
|
title="Situação actual"
|
||||||
|
description="A consulta não certifica cumprimento legal, não encerra alertas por silêncio e não envia avisos ou executa operações."
|
||||||
|
>
|
||||||
|
<p>
|
||||||
|
Versão logística: {props.importRecord.version} · previsão de
|
||||||
|
recepção utilizável:{' '}
|
||||||
|
{props.expectedUsableOn
|
||||||
|
? date(props.expectedUsableOn)
|
||||||
|
: 'Por indicar'}
|
||||||
|
</p>
|
||||||
|
{!props.complete && (
|
||||||
|
<p role="status">
|
||||||
|
Verificação incompleta: consulte as limitações abaixo
|
||||||
|
antes de concluir a conferência.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{props.alerts.length === 0 && (
|
||||||
|
<p>
|
||||||
|
Sem alertas identificados no âmbito verificado. Conserve
|
||||||
|
a conferência humana dos requisitos aplicáveis.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<div className="mt-4 grid gap-4">
|
||||||
|
{props.alerts.map((alert) => (
|
||||||
|
<article
|
||||||
|
key={alert.key}
|
||||||
|
className="space-y-2 rounded border p-4"
|
||||||
|
>
|
||||||
|
<h2 className="font-medium">{alert.category}</h2>
|
||||||
|
<p>{alert.text}</p>
|
||||||
|
<Link className="underline" href={alert.href}>
|
||||||
|
Abrir percurso relacionado
|
||||||
|
</Link>
|
||||||
|
</article>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</Panel>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
} from '@/components/procurement';
|
} from '@/components/procurement';
|
||||||
|
|
||||||
type RecordVersion = {
|
type RecordVersion = {
|
||||||
|
legal_changed?: boolean;
|
||||||
id: number;
|
id: number;
|
||||||
version: number;
|
version: number;
|
||||||
state: string;
|
state: string;
|
||||||
@@ -38,6 +39,7 @@ type Page<T> = {
|
|||||||
next_page_url: string | null;
|
next_page_url: string | null;
|
||||||
};
|
};
|
||||||
type Props = {
|
type Props = {
|
||||||
|
legalReady?: boolean;
|
||||||
requisition: { id: number; number: string };
|
requisition: { id: number; number: string };
|
||||||
items: {
|
items: {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -142,6 +144,12 @@ function ItemForm({
|
|||||||
? `Confirmado: ${latest.data.confirmed_code} · ${latest.snapshot.confirmed_by?.name ?? 'Comprador registado'}`
|
? `Confirmado: ${latest.data.confirmed_code} · ${latest.snapshot.confirmed_by?.name ?? 'Comprador registado'}`
|
||||||
: 'Código pautal por confirmar pelo comprador.'}
|
: 'Código pautal por confirmar pelo comprador.'}
|
||||||
</p>
|
</p>
|
||||||
|
{latest?.legal_changed && (
|
||||||
|
<p role="status">
|
||||||
|
A fonte legal aplicada foi substituída ou retirada. Reveja a
|
||||||
|
classificação; a decisão anterior permanece no histórico.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
{latest?.snapshot.master && (
|
{latest?.snapshot.master && (
|
||||||
<p>
|
<p>
|
||||||
Proposta reutilizada de {latest.snapshot.master.item.code} ·{' '}
|
Proposta reutilizada de {latest.snapshot.master.item.code} ·{' '}
|
||||||
@@ -368,6 +376,14 @@ export default function ImportTariffs(props: Props) {
|
|||||||
percurso.
|
percurso.
|
||||||
</p>
|
</p>
|
||||||
</Panel>
|
</Panel>
|
||||||
|
{props.legalReady && (
|
||||||
|
<Link
|
||||||
|
className="underline"
|
||||||
|
href={`/requisicoes/${props.requisition.id}/base-legal`}
|
||||||
|
>
|
||||||
|
Consultar base legal e sugestões
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
<Panel title="Localizar material ou código">
|
<Panel title="Localizar material ou código">
|
||||||
<form
|
<form
|
||||||
method="get"
|
method="get"
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import type { CommercialTerms } from '@/components/quotation-commercial-terms';
|
|||||||
import type { ComparisonPolicy } from '@/components/comparison-policy-summary';
|
import type { ComparisonPolicy } from '@/components/comparison-policy-summary';
|
||||||
import type { ExchangeBasis } from '@/components/quotation-exchange-panel';
|
import type { ExchangeBasis } from '@/components/quotation-exchange-panel';
|
||||||
import type { FrozenImportTariff } from '@/components/import-tariff-summary';
|
import type { FrozenImportTariff } from '@/components/import-tariff-summary';
|
||||||
|
import type { FrozenCapitalAssignment } from '@/components/capital-assignment-summary';
|
||||||
|
|
||||||
export type MatrixRow = {
|
export type MatrixRow = {
|
||||||
currency?: string;
|
currency?: string;
|
||||||
@@ -99,6 +100,7 @@ export type PurchaseOrder = {
|
|||||||
total_minor: number;
|
total_minor: number;
|
||||||
items: OrderItem[];
|
items: OrderItem[];
|
||||||
snapshot: {
|
snapshot: {
|
||||||
|
capital_assignments?: Record<number, FrozenCapitalAssignment>;
|
||||||
import_tariffs?: Record<number, FrozenImportTariff>;
|
import_tariffs?: Record<number, FrozenImportTariff>;
|
||||||
budget_checked?: boolean;
|
budget_checked?: boolean;
|
||||||
agreement_bindings?: Record<string, FrozenOrderAgreement>;
|
agreement_bindings?: Record<string, FrozenOrderAgreement>;
|
||||||
|
|||||||
@@ -85,10 +85,23 @@
|
|||||||
limite por ordem: {{ $binding['max_order_quantity_milli'] === null ? 'Não definido' : str_replace('.', ',', (string)\Brick\Math\BigDecimal::of($binding['max_order_quantity_milli'])->dividedBy(1000, 3)) . ' ' . $binding['unit'] }}.</p>
|
limite por ordem: {{ $binding['max_order_quantity_milli'] === null ? 'Não definido' : str_replace('.', ',', (string)\Brick\Math\BigDecimal::of($binding['max_order_quantity_milli'])->dividedBy(1000, 3)) . ' ' . $binding['unit'] }}.</p>
|
||||||
@endforeach
|
@endforeach
|
||||||
@endif
|
@endif
|
||||||
|
@if(!empty($snapshot['capital_assignments']))
|
||||||
|
<h2>Projectos e imobilizado</h2>
|
||||||
|
@foreach($snapshot['capital_assignments'] as $assignment)
|
||||||
|
<p><strong>{{ $assignment['snapshot']['item']['description'] }}</strong><br>
|
||||||
|
{{ $assignment['snapshot']['source']['data']['type'] === 'project' ? 'Projecto' : 'Imobilizado' }}:
|
||||||
|
{{ $assignment['snapshot']['source']['data']['code'] }} · {{ $assignment['snapshot']['source']['data']['name'] }}
|
||||||
|
· versão {{ $assignment['snapshot']['source']['version'] }}<br>
|
||||||
|
{{ $assignment['snapshot']['source']['data']['reference'] }}<br>{{ $assignment['reason'] }}</p>
|
||||||
|
@endforeach
|
||||||
|
@endif
|
||||||
@if(!empty($snapshot['import_tariffs']))
|
@if(!empty($snapshot['import_tariffs']))
|
||||||
<h2>Classificação pautal preservada na emissão</h2>
|
<h2>Classificação pautal preservada na emissão</h2>
|
||||||
@foreach($snapshot['import_tariffs'] as $classification)
|
@foreach($snapshot['import_tariffs'] as $classification)
|
||||||
<p class="pre"><strong>{{ $classification['item']['description'] }}</strong><br>Código confirmado: {{ $classification['data']['confirmed_code'] }} · versão {{ $classification['version'] }} · {{ $classification['confirmed_by']['name'] }}<br>Proposta: {{ $classification['data']['proposed_code'] ?? 'Não indicada' }} · Fonte: {{ $classification['data']['source_reference'] ?? 'Por completar' }}<br>Fonte da confirmação: {{ $classification['data']['confirmation_source'] }}<br>{{ $classification['data']['deviation'] ? 'Justificação do desvio' : 'Motivo' }}: {{ $classification['reason'] }}</p>
|
<p class="pre"><strong>{{ $classification['item']['description'] }}</strong><br>Código confirmado: {{ $classification['data']['confirmed_code'] }} · versão {{ $classification['version'] }} · {{ $classification['confirmed_by']['name'] }}<br>Proposta: {{ $classification['data']['proposed_code'] ?? 'Não indicada' }} · Fonte: {{ $classification['data']['source_reference'] ?? 'Por completar' }}<br>Fonte da confirmação: {{ $classification['data']['confirmation_source'] }}<br>{{ $classification['data']['deviation'] ? 'Justificação do desvio' : 'Motivo' }}: {{ $classification['reason'] }}</p>
|
||||||
|
@if(!empty($classification['legal_rule']))
|
||||||
|
<p class="pre">Regra legal aplicada: {{ $classification['legal_rule']['data']['official_reference'] }} · {{ $classification['legal_rule']['data']['citation'] }} · versão {{ $classification['legal_rule']['version'] }}<br>Condições preservadas: {{ $classification['legal_rule']['data']['obligations'] }}</p>
|
||||||
|
@endif
|
||||||
@endforeach
|
@endforeach
|
||||||
@endif
|
@endif
|
||||||
<h2>Justificação da adjudicação</h2><p class="pre">{{ $snapshot['award']['justification'] }}</p>
|
<h2>Justificação da adjudicação</h2><p class="pre">{{ $snapshot['award']['justification'] }}</p>
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use App\Http\Controllers\AutomaticPurchaseController;
|
|||||||
use App\Http\Controllers\BudgetController;
|
use App\Http\Controllers\BudgetController;
|
||||||
use App\Http\Controllers\BudgetReinforcementController;
|
use App\Http\Controllers\BudgetReinforcementController;
|
||||||
use App\Http\Controllers\CandidatePortalController;
|
use App\Http\Controllers\CandidatePortalController;
|
||||||
|
use App\Http\Controllers\CapitalRegisterController;
|
||||||
use App\Http\Controllers\CommonStockReadController;
|
use App\Http\Controllers\CommonStockReadController;
|
||||||
use App\Http\Controllers\CompanyController;
|
use App\Http\Controllers\CompanyController;
|
||||||
use App\Http\Controllers\ConflictDeclarationController;
|
use App\Http\Controllers\ConflictDeclarationController;
|
||||||
@@ -17,9 +18,12 @@ use App\Http\Controllers\FormalAdmissionController;
|
|||||||
use App\Http\Controllers\FormalRecommendationController;
|
use App\Http\Controllers\FormalRecommendationController;
|
||||||
use App\Http\Controllers\GeneralLedgerController;
|
use App\Http\Controllers\GeneralLedgerController;
|
||||||
use App\Http\Controllers\GoodsReceiptController;
|
use App\Http\Controllers\GoodsReceiptController;
|
||||||
|
use App\Http\Controllers\ImportBankSupportController;
|
||||||
use App\Http\Controllers\ImportDossierController;
|
use App\Http\Controllers\ImportDossierController;
|
||||||
use App\Http\Controllers\ImportEstimateController;
|
use App\Http\Controllers\ImportEstimateController;
|
||||||
use App\Http\Controllers\ImportLandedCostController;
|
use App\Http\Controllers\ImportLandedCostController;
|
||||||
|
use App\Http\Controllers\ImportLegalController;
|
||||||
|
use App\Http\Controllers\ImportReadinessController;
|
||||||
use App\Http\Controllers\ImportTariffController;
|
use App\Http\Controllers\ImportTariffController;
|
||||||
use App\Http\Controllers\InventoryDispositionController;
|
use App\Http\Controllers\InventoryDispositionController;
|
||||||
use App\Http\Controllers\InventoryLotController;
|
use App\Http\Controllers\InventoryLotController;
|
||||||
@@ -139,6 +143,10 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
|
|||||||
Route::post('compras/importacoes/{import}/intervenientes', [ImportDossierController::class, 'selectParty'])->whereNumber('import');
|
Route::post('compras/importacoes/{import}/intervenientes', [ImportDossierController::class, 'selectParty'])->whereNumber('import');
|
||||||
Route::get('compras/importacoes/{import}/documentos/{document}', [ImportDossierController::class, 'evidence'])->whereNumber('import')->whereNumber('document');
|
Route::get('compras/importacoes/{import}/documentos/{document}', [ImportDossierController::class, 'evidence'])->whereNumber('import')->whereNumber('document');
|
||||||
Route::get('requisicoes/{requisition}/classificacao-pautal', [ImportTariffController::class, 'index'])->whereNumber('requisition');
|
Route::get('requisicoes/{requisition}/classificacao-pautal', [ImportTariffController::class, 'index'])->whereNumber('requisition');
|
||||||
|
Route::get('requisicoes/{requisition}/base-legal', [ImportLegalController::class, 'index'])->whereNumber('requisition');
|
||||||
|
Route::post('requisicoes/{requisition}/base-legal', [ImportLegalController::class, 'store'])->whereNumber('requisition');
|
||||||
|
Route::post('requisicoes/{requisition}/base-legal/estimativas', [ImportLegalController::class, 'estimate'])->whereNumber('requisition');
|
||||||
|
Route::get('requisicoes/{requisition}/base-legal/fontes/{source}', [ImportLegalController::class, 'source'])->whereNumber('requisition')->whereNumber('source');
|
||||||
Route::get('requisicoes/{requisition}/estimativa-importacao', [ImportEstimateController::class, 'index'])->whereNumber('requisition');
|
Route::get('requisicoes/{requisition}/estimativa-importacao', [ImportEstimateController::class, 'index'])->whereNumber('requisition');
|
||||||
Route::post('requisicoes/{requisition}/estimativa-importacao', [ImportEstimateController::class, 'store'])->whereNumber('requisition');
|
Route::post('requisicoes/{requisition}/estimativa-importacao', [ImportEstimateController::class, 'store'])->whereNumber('requisition');
|
||||||
Route::post('requisicoes/{requisition}/classificacao-pautal', [ImportTariffController::class, 'store'])->whereNumber('requisition');
|
Route::post('requisicoes/{requisition}/classificacao-pautal', [ImportTariffController::class, 'store'])->whereNumber('requisition');
|
||||||
@@ -146,6 +154,10 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
|
|||||||
Route::post('compras/importacoes/{import}/custos/documentos', [ImportLandedCostController::class, 'document'])->whereNumber('import');
|
Route::post('compras/importacoes/{import}/custos/documentos', [ImportLandedCostController::class, 'document'])->whereNumber('import');
|
||||||
Route::post('compras/importacoes/{import}/custos/preparacao', [ImportLandedCostController::class, 'save'])->whereNumber('import');
|
Route::post('compras/importacoes/{import}/custos/preparacao', [ImportLandedCostController::class, 'save'])->whereNumber('import');
|
||||||
Route::post('compras/importacoes/{import}/custos/{plan}/orcamento', [ImportLandedCostController::class, 'financial'])->whereNumber('import')->whereNumber('plan');
|
Route::post('compras/importacoes/{import}/custos/{plan}/orcamento', [ImportLandedCostController::class, 'financial'])->whereNumber('import')->whereNumber('plan');
|
||||||
|
Route::get('compras/importacoes/{import}/suporte-bancario', [ImportBankSupportController::class, 'index'])->whereNumber('import');
|
||||||
|
Route::get('compras/importacoes/{import}/acompanhamento', [ImportReadinessController::class, 'index'])->whereNumber('import');
|
||||||
|
Route::get('compras/importacoes/{import}/suporte-bancario.csv', [ImportBankSupportController::class, 'export'])->whereNumber('import');
|
||||||
|
Route::post('compras/importacoes/{import}/suporte-bancario', [ImportBankSupportController::class, 'store'])->whereNumber('import');
|
||||||
Route::get('compras/importacoes/{import}/custos/documentos/{document}', [ImportLandedCostController::class, 'evidence'])->whereNumber('import')->whereNumber('document');
|
Route::get('compras/importacoes/{import}/custos/documentos/{document}', [ImportLandedCostController::class, 'evidence'])->whereNumber('import')->whereNumber('document');
|
||||||
Route::get('compras/pesquisa', [ProcurementSearchController::class, 'index'])->name('procurement.search');
|
Route::get('compras/pesquisa', [ProcurementSearchController::class, 'index'])->name('procurement.search');
|
||||||
Route::post('compras/pesquisas-guardadas', [SavedProcurementSearchController::class, 'store'])->name('procurement.saved-searches.store');
|
Route::post('compras/pesquisas-guardadas', [SavedProcurementSearchController::class, 'store'])->name('procurement.saved-searches.store');
|
||||||
@@ -290,6 +302,8 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
|
|||||||
Route::post('orcamentos', [BudgetController::class, 'store'])->name('budgets.store');
|
Route::post('orcamentos', [BudgetController::class, 'store'])->name('budgets.store');
|
||||||
Route::post('orcamentos/{budget}/aprovar', [BudgetController::class, 'approve'])->name('budgets.approve');
|
Route::post('orcamentos/{budget}/aprovar', [BudgetController::class, 'approve'])->name('budgets.approve');
|
||||||
Route::get('equipamentos', [EquipmentController::class, 'index'])->name('equipment.index');
|
Route::get('equipamentos', [EquipmentController::class, 'index'])->name('equipment.index');
|
||||||
|
Route::get('projectos-imobilizado', [CapitalRegisterController::class, 'index'])->name('capital-register.index');
|
||||||
|
Route::post('projectos-imobilizado', [CapitalRegisterController::class, 'store'])->name('capital-register.store');
|
||||||
Route::get('ordens/cancelamentos', [OrderCancellationController::class, 'index']);
|
Route::get('ordens/cancelamentos', [OrderCancellationController::class, 'index']);
|
||||||
Route::post('ordens/{order}/cancelamento', [OrderCancellationController::class, 'request'])->whereNumber('order');
|
Route::post('ordens/{order}/cancelamento', [OrderCancellationController::class, 'request'])->whereNumber('order');
|
||||||
Route::post('ordens/cancelamentos/{cancellation}/decidir', [OrderCancellationController::class, 'decide'])->whereNumber('cancellation');
|
Route::post('ordens/cancelamentos/{cancellation}/decidir', [OrderCancellationController::class, 'decide'])->whereNumber('cancellation');
|
||||||
@@ -354,6 +368,8 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
|
|||||||
Route::put('requisicoes/{requisition}', [RequisitionController::class, 'update'])->name('requisitions.update');
|
Route::put('requisicoes/{requisition}', [RequisitionController::class, 'update'])->name('requisitions.update');
|
||||||
Route::post('requisicoes/{requisition}/submeter', [RequisitionController::class, 'submit'])->name('requisitions.submit');
|
Route::post('requisicoes/{requisition}/submeter', [RequisitionController::class, 'submit'])->name('requisitions.submit');
|
||||||
Route::get('requisicoes/{requisition}/distribuicoes', [RequisitionController::class, 'distributions'])->name('requisitions.distributions');
|
Route::get('requisicoes/{requisition}/distribuicoes', [RequisitionController::class, 'distributions'])->name('requisitions.distributions');
|
||||||
|
Route::get('requisicoes/{requisition}/projectos-imobilizado', [CapitalRegisterController::class, 'assignments'])->name('requisitions.capital');
|
||||||
|
Route::post('requisicoes/{requisition}/projectos-imobilizado', [CapitalRegisterController::class, 'assign'])->name('requisitions.capital.assign');
|
||||||
Route::post('requisicoes/{requisition}/distribuicoes', [RequisitionController::class, 'prepareDistributions'])->name('requisitions.distributions.prepare');
|
Route::post('requisicoes/{requisition}/distribuicoes', [RequisitionController::class, 'prepareDistributions'])->name('requisitions.distributions.prepare');
|
||||||
Route::post('requisicoes/{requisition}/decidir', [RequisitionController::class, 'decide'])->name('requisitions.decide');
|
Route::post('requisicoes/{requisition}/decidir', [RequisitionController::class, 'decide'])->name('requisitions.decide');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -83,6 +83,68 @@ try {
|
|||||||
if (in_array('--dossier-focused', $argv, true)) {
|
if (in_array('--dossier-focused', $argv, true)) {
|
||||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportDossierTest.php', 'tests/Feature/ImportLandedCostsTest.php', 'tests/Feature/OperationalHealthTest.php', 'tests/Feature/SupplyPlanningTest.php']];
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportDossierTest.php', 'tests/Feature/ImportLandedCostsTest.php', 'tests/Feature/OperationalHealthTest.php', 'tests/Feature/SupplyPlanningTest.php']];
|
||||||
}
|
}
|
||||||
|
if (in_array('--bank-support-focused', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportBankSupportTest.php', 'tests/Feature/ImportDossierTest.php', 'tests/Feature/ImportLandedCostsTest.php', 'tests/Feature/SupplyPlanningTest.php']];
|
||||||
|
}
|
||||||
|
if (in_array('--legal-focused', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLegalRulesTest.php', 'tests/Feature/ImportTariffCodesTest.php',
|
||||||
|
'tests/Feature/ImportReadinessTest.php', 'tests/Feature/ImportBankSupportTest.php', 'tests/Feature/OperationalHealthTest.php', 'tests/Feature/ImportDossierTest.php']];
|
||||||
|
}
|
||||||
|
if (in_array('--legal-amounts-focused', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLegalEstimatesTest.php', 'tests/Feature/ImportLegalRulesTest.php',
|
||||||
|
'tests/Feature/ImportEstimatesTest.php', 'tests/Feature/ImportEstimatePlanTest.php', 'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/RequisitionApprovalLevelsTest.php']];
|
||||||
|
}
|
||||||
|
if (in_array('--capital-focused', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/CapitalRegisterTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
|
||||||
|
'--filter=capital|register|line destination|submitted requisitions|confirmed import classifications|partial native order retains']];
|
||||||
|
}
|
||||||
|
if (in_array('--capital-concurrency', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
|
[PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-capital']];
|
||||||
|
}
|
||||||
|
if (in_array('--legal-concurrency', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
|
[PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-legal']];
|
||||||
|
}
|
||||||
|
if (in_array('--legal-amount-concurrency', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
|
[PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-legal-amount']];
|
||||||
|
}
|
||||||
|
if (in_array('--legal-recovery', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
|
[PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'import-legal']];
|
||||||
|
}
|
||||||
|
if (in_array('--legal-amount-recovery', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
|
[PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'import-legal-amount']];
|
||||||
|
}
|
||||||
|
if (in_array('--legal-corpus', $argv, true)) {
|
||||||
|
$corpusArguments = array_values(array_filter($argv, fn ($value) => str_starts_with($value, '--legal-corpus-root=')));
|
||||||
|
if (count($corpusArguments) !== 1) {
|
||||||
|
throw new InvalidArgumentException('Indique exactamente uma pasta de legislação partilhada.');
|
||||||
|
}
|
||||||
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
|
[PHP_BINARY, 'tests/Concurrency/import-legal-corpus-worker.php', $database, 'corpus', substr($corpusArguments[0], strlen('--legal-corpus-root='))]];
|
||||||
|
}
|
||||||
|
if (in_array('--legal-http', $argv, true) || in_array('--legal-native-review', $argv, true)) {
|
||||||
|
$values = [];
|
||||||
|
foreach (['--legal-corpus-root=', '--legal-http-candidate=', '--legal-http-manifest='] as $prefix) {
|
||||||
|
$matches = array_values(array_filter($argv, fn ($value) => str_starts_with($value, $prefix)));
|
||||||
|
if (count($matches) !== 1) {
|
||||||
|
throw new InvalidArgumentException('Indique uma pasta de fontes e uma candidata privada com o seu manifesto validado.');
|
||||||
|
}
|
||||||
|
$values[] = substr($matches[0], strlen($prefix));
|
||||||
|
}
|
||||||
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
|
[PHP_BINARY, 'tests/Concurrency/import-legal-http-worker.php', $database, in_array('--legal-native-review', $argv, true) ? 'legal-review' : 'legal-http', ...$values]];
|
||||||
|
}
|
||||||
|
if (in_array('--bank-support-native-only', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportBankSupportTest.php']];
|
||||||
|
}
|
||||||
|
if (in_array('--bank-support-concurrency', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
|
[PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-bank']];
|
||||||
|
}
|
||||||
if (in_array('--dossier-concurrency', $argv, true)) {
|
if (in_array('--dossier-concurrency', $argv, true)) {
|
||||||
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
[PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-dossier']];
|
[PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-dossier']];
|
||||||
@@ -118,6 +180,10 @@ try {
|
|||||||
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
[PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'import-estimates']];
|
[PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'import-estimates']];
|
||||||
}
|
}
|
||||||
|
if (in_array('--bank-support-recovery', $argv, true)) {
|
||||||
|
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
|
||||||
|
[PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'import-bank-support']];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if ($orderPartsMode) {
|
if ($orderPartsMode) {
|
||||||
$environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control';
|
$environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control';
|
||||||
@@ -218,9 +284,14 @@ try {
|
|||||||
throw new LogicException('Each Pest kernel must use its own disposable PostgreSQL database.');
|
throw new LogicException('Each Pest kernel must use its own disposable PostgreSQL database.');
|
||||||
}
|
}
|
||||||
foreach ($commands as $command) {
|
foreach ($commands as $command) {
|
||||||
$process = new Process($command, dirname(__DIR__), $environment, timeout: 180);
|
$nativeReview = ($command[3] ?? '') === 'legal-review';
|
||||||
$process->run();
|
$process = new Process($command, dirname(__DIR__), $environment, timeout: $nativeReview ? 3660 : 180);
|
||||||
|
$process->run($nativeReview ? function ($type, $buffer) {
|
||||||
|
echo $buffer;
|
||||||
|
} : null);
|
||||||
|
if (! $nativeReview) {
|
||||||
echo $process->getOutput();
|
echo $process->getOutput();
|
||||||
|
}
|
||||||
if (! $process->isSuccessful()) {
|
if (! $process->isSuccessful()) {
|
||||||
echo $process->getErrorOutput();
|
echo $process->getErrorOutput();
|
||||||
throw new RuntimeException('Validação PostgreSQL não aprovada.');
|
throw new RuntimeException('Validação PostgreSQL não aprovada.');
|
||||||
|
|||||||
@@ -2,14 +2,20 @@
|
|||||||
|
|
||||||
use App\Enums\PurchasingRole;
|
use App\Enums\PurchasingRole;
|
||||||
use App\Models\PurchaseOrder;
|
use App\Models\PurchaseOrder;
|
||||||
|
use App\Models\Requisition;
|
||||||
use App\Models\Supplier;
|
use App\Models\Supplier;
|
||||||
use App\Models\SupplyRecord;
|
use App\Models\SupplyRecord;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
use App\Services\CommonBudget;
|
use App\Services\CommonBudget;
|
||||||
|
use App\Services\ImportBankSupport;
|
||||||
use App\Services\ImportCostDocumentHealth;
|
use App\Services\ImportCostDocumentHealth;
|
||||||
use App\Services\ImportDossier;
|
use App\Services\ImportDossier;
|
||||||
|
use App\Services\ImportEstimates;
|
||||||
use App\Services\ImportLandedCosts;
|
use App\Services\ImportLandedCosts;
|
||||||
|
use App\Services\ImportLegalEstimates;
|
||||||
|
use App\Services\ImportLegalRules;
|
||||||
use App\Services\ImportParties;
|
use App\Services\ImportParties;
|
||||||
|
use App\Services\ImportTariffCodes;
|
||||||
use App\Services\SupplyPlanning;
|
use App\Services\SupplyPlanning;
|
||||||
use Illuminate\Contracts\Console\Kernel;
|
use Illuminate\Contracts\Console\Kernel;
|
||||||
use Illuminate\Database\Connection;
|
use Illuminate\Database\Connection;
|
||||||
@@ -34,10 +40,15 @@ if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
|
|||||||
}
|
}
|
||||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
require_once __DIR__.'/../Support/SupplyFixture.php';
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/ImportBankQaFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
|
||||||
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
||||||
$orderPartsAmendment = ($argv[2] ?? '') === 'order-parts-amendment';
|
$orderPartsAmendment = ($argv[2] ?? '') === 'order-parts-amendment';
|
||||||
$orderParts = $orderPartsAmendment || ($argv[2] ?? '') === 'order-parts';
|
$orderParts = $orderPartsAmendment || ($argv[2] ?? '') === 'order-parts';
|
||||||
$importEstimates = ($argv[2] ?? '') === 'import-estimates';
|
$legalAmounts = ($argv[2] ?? '') === 'import-legal-amount';
|
||||||
|
$legalRules = $legalAmounts || ($argv[2] ?? '') === 'import-legal';
|
||||||
|
$bankSupport = $legalRules || ($argv[2] ?? '') === 'import-bank-support';
|
||||||
|
$importEstimates = $bankSupport || ($argv[2] ?? '') === 'import-estimates';
|
||||||
$landedCosts = $importEstimates || ($argv[2] ?? '') === 'landed-costs';
|
$landedCosts = $importEstimates || ($argv[2] ?? '') === 'landed-costs';
|
||||||
$f = receiptFixture();
|
$f = receiptFixture();
|
||||||
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||||
@@ -192,6 +203,51 @@ if ($landedCosts) {
|
|||||||
app(ImportParties::class)->select($partyBuyer, $nativeImport, [...$partyInput, 'operation_key' => (string) Str::uuid(),
|
app(ImportParties::class)->select($partyBuyer, $nativeImport, [...$partyInput, 'operation_key' => (string) Str::uuid(),
|
||||||
'version' => 1, 'instruction_document_id' => $instructionsCorrection->id]);
|
'version' => 1, 'instruction_document_id' => $instructionsCorrection->id]);
|
||||||
$nativeEvidenceRecords = [$nativeDoc, $correction, $typedFirst, $typedCorrection, $instructions, $instructionsCorrection];
|
$nativeEvidenceRecords = [$nativeDoc, $correction, $typedFirst, $typedCorrection, $instructions, $instructionsCorrection];
|
||||||
|
if ($bankSupport) {
|
||||||
|
config(['import-bank-support.qa_enabled' => true]);
|
||||||
|
$bankFixture = importBankQaFixture($partyBuyer, $nativeImport);
|
||||||
|
$bankFirst = app(ImportBankSupport::class)->save($partyBuyer, $nativeImport, $bankFixture['input']);
|
||||||
|
$bankFinalInput = [...$bankFixture['input'], 'operation_key' => (string) Str::uuid(), 'record_key' => $bankFirst->record_key, 'version' => 1,
|
||||||
|
'submission_document_id' => $bankFixture['documents']['delivery']->id, 'submitted_on' => today()->toDateString(),
|
||||||
|
'submission_basis' => 'Synthetic bank delivery receipt recorded on the explicit due date'];
|
||||||
|
$bankFinal = app(ImportBankSupport::class)->save($partyBuyer, $nativeImport, $bankFinalInput);
|
||||||
|
$nativeEvidenceRecords = [...$nativeEvidenceRecords, ...array_values($bankFixture['documents'])];
|
||||||
|
}
|
||||||
|
if ($legalRules) {
|
||||||
|
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
|
||||||
|
supplyGrant($partyBuyer, ['procurement', 'import_prepare', 'import_customs']);
|
||||||
|
$legalService = app(ImportLegalRules::class);
|
||||||
|
$legalDraft = $legalService->save($partyBuyer, importLegalQaInput($legalAmounts ? ['charges' => [importLegalQaCharge()]] : []), importLegalQaFile());
|
||||||
|
$legalPublishInput = ['operation_key' => (string) Str::uuid(), 'record_key' => $legalDraft->record_key, 'version' => 1,
|
||||||
|
'action' => 'publish', 'reason' => 'Synthetic customs publication for the native recovery fixture'];
|
||||||
|
$legalPublished = $legalService->save($partyBuyer, $legalPublishInput);
|
||||||
|
$legalProposal = app(ImportTariffCodes::class)->save($partyBuyer, $f['r'], ['operation_key' => (string) Str::uuid(), 'version' => 0,
|
||||||
|
'action' => 'propose', 'requisition_item_id' => $f['r']->items()->sole()->id,
|
||||||
|
'code' => '1234.56', 'source_reference' => $legalPublished->data['official_reference'].' — '.$legalPublished->data['citation'],
|
||||||
|
'legal_rule_id' => $legalPublished->id, 'legal_match_code' => '1234', 'legal_origin' => 'Synthetic A', 'legal_sector' => 'Synthetic sector',
|
||||||
|
'legal_date' => '2026-11-27', 'reason' => 'Synthetic documentary suggestion preserved for recovery']);
|
||||||
|
$nativeEvidenceRecords[] = $legalService->source($partyBuyer, $f['r'], $legalPublished->snapshot['source_id']);
|
||||||
|
if ($legalAmounts) {
|
||||||
|
config(['import-estimates.qa_enabled' => true]);
|
||||||
|
$legalPlanRequest = $f['r']->replicate();
|
||||||
|
$legalPlanRequest->fill(['number' => 'LEGAL-RECOVERY-'.Str::random(10), 'status' => 'draft']);
|
||||||
|
$legalPlanRequest->save();
|
||||||
|
$legalPlanItem = $f['r']->items()->sole()->replicate();
|
||||||
|
$legalPlanItem->requisition_id = $legalPlanRequest->id;
|
||||||
|
$legalPlanItem->save();
|
||||||
|
$legalAmountInput = importLegalQaAmountInput($legalPlanItem->id, $legalPublished->id);
|
||||||
|
$legalAmountInput['bases']['synthetic-duty']['value_minor'] = 10000;
|
||||||
|
$legalAmount = app(ImportLegalEstimates::class)->save($partyBuyer, $legalPlanRequest, $legalAmountInput);
|
||||||
|
$legalNativeInput = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'budget_id' => $budget,
|
||||||
|
'reason' => 'Synthetic native import preparation; only the documented duty applies in this isolated scenario',
|
||||||
|
'legal_sources' => ['duty' => ['estimate_id' => $legalAmount->id, 'charge_key' => 'synthetic-duty']],
|
||||||
|
'components' => array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => $kind === 'duty' ? 'known' : 'not_applicable',
|
||||||
|
'basis' => 'Explicit synthetic recovery assumptions, not a real import or legal exemption',
|
||||||
|
'subtotal_minor' => $kind === 'duty' ? 750 : null, 'tax_minor' => $kind === 'duty' ? 0 : null,
|
||||||
|
'total_minor' => $kind === 'duty' ? 750 : null], BudgetImportEstimate::KINDS)];
|
||||||
|
$legalNativePlan = app(ImportEstimates::class)->save($partyBuyer, $legalPlanRequest, $legalNativeInput);
|
||||||
|
}
|
||||||
|
}
|
||||||
$evidenceManifest = [];
|
$evidenceManifest = [];
|
||||||
foreach ($nativeEvidenceRecords as $record) {
|
foreach ($nativeEvidenceRecords as $record) {
|
||||||
$evidence = $record->snapshot['evidence'];
|
$evidence = $record->snapshot['evidence'];
|
||||||
@@ -294,11 +350,54 @@ try {
|
|||||||
if ($restoredParty->data['instruction_document_id'] !== $instructionsCorrection->id) {
|
if ($restoredParty->data['instruction_document_id'] !== $instructionsCorrection->id) {
|
||||||
throw new RuntimeException('Restored instruction identity differs: '.get_debug_type($restoredParty->data['instruction_document_id']).'/'.get_debug_type($instructionsCorrection->id));
|
throw new RuntimeException('Restored instruction identity differs: '.get_debug_type($restoredParty->data['instruction_document_id']).'/'.get_debug_type($instructionsCorrection->id));
|
||||||
}
|
}
|
||||||
|
if ($bankSupport) {
|
||||||
|
$bankService = app(ImportBankSupport::class);
|
||||||
|
$bankWorkspace = $bankService->workspace($restoredBuyer, $nativeImport);
|
||||||
|
$bankReplay = $bankService->save($restoredBuyer, $nativeImport, $bankFinalInput);
|
||||||
|
$restoredBank = $bankWorkspace['current']->items()[0];
|
||||||
|
if ($restoredBank['version'] !== 2 || $restoredBank['state'] !== 'documented' || $restoredBank['issues'] !== [] || $bankReplay->id !== $bankFinal->id
|
||||||
|
|| $restoredBank['data']['commitment_document_id'] !== $bankFixture['documents']['term']->id
|
||||||
|
|| $restoredBank['data']['declaration_document_id'] !== $bankFixture['documents']['declaration']->id
|
||||||
|
|| $restoredBank['data']['submission_document_id'] !== $bankFixture['documents']['delivery']->id) {
|
||||||
|
throw new RuntimeException('Bank support relationships, documentary status or original operation replay differ after restore.');
|
||||||
|
}
|
||||||
|
echo json_encode(['bank_support_versions_restored' => 2, 'bank_support_relationships_restored' => true,
|
||||||
|
'bank_support_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||||
|
}
|
||||||
|
if ($legalRules) {
|
||||||
|
$legalService = app(ImportLegalRules::class);
|
||||||
|
$legalSource = $legalService->source($restoredBuyer, $f['r'], $legalPublished->snapshot['source_id']);
|
||||||
|
$restoredProposal = SupplyRecord::query()->findOrFail($legalProposal->id);
|
||||||
|
$legalReplay = $legalService->save($restoredBuyer, $legalPublishInput);
|
||||||
|
$restoredFrozen = $legalService->freeze($legalPublished->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27');
|
||||||
|
if ($legalReplay->id !== $legalPublished->id || $restoredProposal->snapshot['legal_rule'] !== $restoredFrozen
|
||||||
|
|| $legalSource->snapshot['evidence']['sha256'] !== $restoredFrozen['source_sha256']) {
|
||||||
|
throw new RuntimeException('Legal source, publication replay or frozen buyer context differs after restore.');
|
||||||
|
}
|
||||||
|
echo json_encode(['legal_source_restored' => true, 'legal_published_version_restored' => true,
|
||||||
|
'legal_buyer_context_restored' => true, 'legal_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||||
|
if ($legalAmounts) {
|
||||||
|
$restoredRequest = Requisition::query()->findOrFail($legalPlanRequest->id);
|
||||||
|
$amountService = app(ImportLegalEstimates::class);
|
||||||
|
$restoredAmount = $amountService->forPlan($restoredRequest, $legalAmount->id);
|
||||||
|
$amountReplay = $amountService->save($restoredBuyer, $restoredRequest, $legalAmountInput);
|
||||||
|
$nativePlanReplay = app(ImportEstimates::class)->save($restoredBuyer, $restoredRequest, $legalNativeInput);
|
||||||
|
$nativeApproval = app(ImportEstimates::class)->approval($restoredRequest);
|
||||||
|
if ($restoredAmount->snapshot['result']['total_minor'] !== 750 || $amountReplay->id !== $legalAmount->id
|
||||||
|
|| $nativePlanReplay->id !== $legalNativePlan->id || $nativeApproval['plan']['budget_amount_minor'] !== 10750
|
||||||
|
|| $nativePlanReplay->snapshot['legal_sources']['duty']['estimate_id'] !== $legalAmount->id) {
|
||||||
|
throw new RuntimeException('Calculated legal amount, native cost plan, source provenance or replay differs after restore.');
|
||||||
|
}
|
||||||
|
echo json_encode(['legal_amount_minor_restored' => 750, 'legal_amount_replay_without_effects' => true,
|
||||||
|
'native_legal_plan_total_minor' => 10750, 'native_legal_plan_source_restored' => true,
|
||||||
|
'native_legal_plan_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||||
|
}
|
||||||
|
}
|
||||||
$readFingerprint = $fingerprint($restored, $afterColumns);
|
$readFingerprint = $fingerprint($restored, $afterColumns);
|
||||||
if ($readFingerprint !== $after) {
|
if ($readFingerprint !== $after) {
|
||||||
throw new RuntimeException('Native restored read changed tables: '.implode(',', array_keys(array_diff_assoc($readFingerprint, $after))));
|
throw new RuntimeException('Native restored read changed tables: '.implode(',', array_keys(array_diff_assoc($readFingerprint, $after))));
|
||||||
}
|
}
|
||||||
echo json_encode(['private_original_versions_restored' => count($nativeEvidenceRecords), 'typed_dossier_versions_restored' => 4,
|
echo json_encode(['private_original_versions_restored' => count($nativeEvidenceRecords), 'typed_dossier_versions_restored' => count(array_filter($nativeEvidenceRecords, fn ($record) => $record->kind === 'import_document')),
|
||||||
'selected_party_versions_restored' => 2, 'source_loss_detected' => true,
|
'selected_party_versions_restored' => 2, 'source_loss_detected' => true,
|
||||||
'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true,
|
'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true,
|
||||||
'evidence_manifest_sha256' => hash('sha256', json_encode($evidenceManifest, JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR).PHP_EOL;
|
'evidence_manifest_sha256' => hash('sha256', json_encode($evidenceManifest, JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||||
|
|||||||
@@ -1,11 +1,16 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
use App\Enums\PurchasingRole;
|
use App\Enums\PurchasingRole;
|
||||||
|
use App\Models\Requisition;
|
||||||
use App\Models\Supplier;
|
use App\Models\Supplier;
|
||||||
use App\Models\SupplyRecord;
|
use App\Models\SupplyRecord;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Services\CapitalRegister;
|
||||||
|
use App\Services\ImportBankSupport;
|
||||||
use App\Services\ImportDossier;
|
use App\Services\ImportDossier;
|
||||||
use App\Services\ImportEvidence;
|
use App\Services\ImportEvidence;
|
||||||
|
use App\Services\ImportLegalEstimates;
|
||||||
|
use App\Services\ImportLegalRules;
|
||||||
use App\Services\ImportParties;
|
use App\Services\ImportParties;
|
||||||
use App\Services\SupplyPlanning;
|
use App\Services\SupplyPlanning;
|
||||||
use Illuminate\Contracts\Console\Kernel;
|
use Illuminate\Contracts\Console\Kernel;
|
||||||
@@ -24,15 +29,25 @@ if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::con
|
|||||||
|| DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
|
|| DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
|
||||||
throw new LogicException('Dossier contention requires disposable local PostgreSQL QA.');
|
throw new LogicException('Dossier contention requires disposable local PostgreSQL QA.');
|
||||||
}
|
}
|
||||||
config(['import-dossier.qa_enabled' => true]);
|
config(['capital-register.qa_enabled' => true, 'import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true, 'import-tariffs.qa_enabled' => true, 'import-legal.qa_enabled' => true]);
|
||||||
Storage::set('local', Storage::build(['driver' => 'local', 'root' => storage_path('framework/testing/dossier-contention-'.$database), 'throw' => true]));
|
Storage::set('local', Storage::build(['driver' => 'local', 'root' => storage_path('framework/testing/dossier-contention-'.$database), 'throw' => true]));
|
||||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
require_once __DIR__.'/../Support/SupplyFixture.php';
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/ImportBankQaFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
|
||||||
$file = static fn () => UploadedFile::fake()->createWithContent('packing.pdf', "%PDF-1.4\nSynthetic concurrent packing list\n%%EOF");
|
$file = static fn () => UploadedFile::fake()->createWithContent('packing.pdf', "%PDF-1.4\nSynthetic concurrent packing list\n%%EOF");
|
||||||
$partyMode = in_array($argv[2] ?? '', ['prepare-party', 'write-party', 'race-party'], true);
|
$partyMode = in_array($argv[2] ?? '', ['prepare-party', 'write-party', 'race-party'], true);
|
||||||
$recordKind = $partyMode ? 'import_party' : 'import_document';
|
$bankMode = in_array($argv[2] ?? '', ['prepare-bank', 'write-bank', 'race-bank'], true);
|
||||||
$auditAction = $partyMode ? 'import.party_selected' : 'import.document_recorded';
|
$legalMode = in_array($argv[2] ?? '', ['prepare-legal', 'write-legal', 'race-legal'], true);
|
||||||
if (in_array($argv[2] ?? '', ['prepare', 'prepare-party'], true)) {
|
$amountMode = in_array($argv[2] ?? '', ['prepare-amount', 'write-amount', 'race-legal-amount'], true);
|
||||||
|
$capitalMode = in_array($argv[2] ?? '', ['prepare-capital', 'write-capital', 'race-capital'], true);
|
||||||
|
$recordKind = $amountMode ? 'import_legal_amount' : ($legalMode ? 'import_legal_rule' : ($bankMode ? 'import_bank_support' : ($partyMode ? 'import_party' : 'import_document')));
|
||||||
|
$auditAction = $amountMode ? 'import.legal_estimate_recorded' : ($legalMode ? 'import.legal_save' : ($bankMode ? 'import.bank_support_recorded' : ($partyMode ? 'import.party_selected' : 'import.document_recorded')));
|
||||||
|
if ($capitalMode) {
|
||||||
|
$recordKind = 'capital_register';
|
||||||
|
$auditAction = 'capital.register_recorded';
|
||||||
|
}
|
||||||
|
if (in_array($argv[2] ?? '', ['prepare', 'prepare-party', 'prepare-bank', 'prepare-legal', 'prepare-amount', 'prepare-capital'], true)) {
|
||||||
$f = receiptFixture();
|
$f = receiptFixture();
|
||||||
supplyGrant($f['issuer'], ['procurement', 'import_prepare']);
|
supplyGrant($f['issuer'], ['procurement', 'import_prepare']);
|
||||||
auth()->guard()->setUser($f['issuer']);
|
auth()->guard()->setUser($f['issuer']);
|
||||||
@@ -42,7 +57,38 @@ if (in_array($argv[2] ?? '', ['prepare', 'prepare-party'], true)) {
|
|||||||
$data = ['operation_key' => (string) Str::uuid(), 'type' => 'packing_list', 'reference' => 'PACK-PARALLEL',
|
$data = ['operation_key' => (string) Str::uuid(), 'type' => 'packing_list', 'reference' => 'PACK-PARALLEL',
|
||||||
'issuer_reference' => 'Synthetic supplier', 'reason' => 'Synthetic concurrent original document registration.'];
|
'issuer_reference' => 'Synthetic supplier', 'reason' => 'Synthetic concurrent original document registration.'];
|
||||||
$actor = $f['issuer'];
|
$actor = $f['issuer'];
|
||||||
if ($partyMode) {
|
if ($capitalMode) {
|
||||||
|
$data = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'type' => 'project', 'code' => 'CONCURRENT-QA',
|
||||||
|
'name' => 'Projecto sintético concorrente', 'department_id' => $f['department']->id, 'equipment_id' => null,
|
||||||
|
'reference' => 'Documento sintético de concorrência', 'state' => 'active', 'reason' => 'Cadastro independente em concorrência real de testes'];
|
||||||
|
if (($argv[3] ?? '') === 'same_version') {
|
||||||
|
$old = app(CapitalRegister::class)->save($actor, $data);
|
||||||
|
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'record_key' => $old->record_key, 'version' => 1];
|
||||||
|
}
|
||||||
|
} elseif ($amountMode) {
|
||||||
|
supplyGrant($actor, ['procurement', 'import_prepare', 'import_customs']);
|
||||||
|
$draft = app(ImportLegalRules::class)->save($actor, importLegalQaInput(['charges' => [importLegalQaCharge()]]), importLegalQaFile());
|
||||||
|
$rule = app(ImportLegalRules::class)->save($actor, ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key,
|
||||||
|
'version' => 1, 'action' => 'publish', 'reason' => 'Synthetic reviewed tax definition for concurrent estimates']);
|
||||||
|
$data = importLegalQaAmountInput($f['r']->items()->sole()->id, $rule->id);
|
||||||
|
if (($argv[3] ?? '') === 'same_version') {
|
||||||
|
app(ImportLegalEstimates::class)->save($actor, $f['r'], $data);
|
||||||
|
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'version' => 1];
|
||||||
|
}
|
||||||
|
} elseif ($legalMode) {
|
||||||
|
supplyGrant($actor, ['procurement', 'import_prepare', 'import_customs']);
|
||||||
|
$data = importLegalQaInput();
|
||||||
|
if (($argv[3] ?? '') === 'same_version') {
|
||||||
|
$old = app(ImportLegalRules::class)->save($actor, $data, importLegalQaFile());
|
||||||
|
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'record_key' => $old->record_key, 'version' => 1];
|
||||||
|
}
|
||||||
|
} elseif ($bankMode) {
|
||||||
|
$data = importBankQaFixture($actor, $import)['input'];
|
||||||
|
if (($argv[3] ?? '') === 'same_version') {
|
||||||
|
$old = app(ImportBankSupport::class)->save($actor, $import, $data);
|
||||||
|
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'record_key' => $old->record_key, 'version' => 1];
|
||||||
|
}
|
||||||
|
} elseif ($partyMode) {
|
||||||
$actor = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Procurement]);
|
$actor = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Procurement]);
|
||||||
supplyGrant($actor, ['procurement', 'import_prepare']);
|
supplyGrant($actor, ['procurement', 'import_prepare']);
|
||||||
auth()->guard()->setUser($actor);
|
auth()->guard()->setUser($actor);
|
||||||
@@ -63,32 +109,35 @@ if (in_array($argv[2] ?? '', ['prepare', 'prepare-party'], true)) {
|
|||||||
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'record_key' => $old->record_key, 'version' => 1,
|
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'record_key' => $old->record_key, 'version' => 1,
|
||||||
'reference' => 'PACK-CORRECTED'];
|
'reference' => 'PACK-CORRECTED'];
|
||||||
}
|
}
|
||||||
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $actor->id, 'import' => $import->id, 'data' => $data,
|
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $actor->id, 'import' => $import->id, 'request' => $f['r']->id, 'data' => $data,
|
||||||
'records_before' => SupplyRecord::query()->where('kind', $recordKind)->count(),
|
'records_before' => SupplyRecord::query()->where('kind', $recordKind)->count(),
|
||||||
'audits_before' => DB::table('audit_logs')->where('tenant_id', $f['tenant']->id)->where('action', $auditAction)->count(),
|
'audits_before' => DB::table('audit_logs')->where('tenant_id', $f['tenant']->id)->where('action', $auditAction)->count(),
|
||||||
'files_before' => count(Storage::disk('local')->allFiles())], JSON_THROW_ON_ERROR);
|
'files_before' => count(Storage::disk('local')->allFiles())], JSON_THROW_ON_ERROR);
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
if (in_array($argv[2] ?? '', ['write', 'write-party'], true)) {
|
if (in_array($argv[2] ?? '', ['write', 'write-party', 'write-bank', 'write-legal', 'write-amount', 'write-capital'], true)) {
|
||||||
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
|
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
|
||||||
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_dossier_write_'.getmypid()]);
|
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_dossier_write_'.getmypid()]);
|
||||||
$actor = User::query()->findOrFail($input['actor']);
|
$actor = User::query()->findOrFail($input['actor']);
|
||||||
auth()->guard()->setUser($actor);
|
auth()->guard()->setUser($actor);
|
||||||
try {
|
try {
|
||||||
$import = SupplyRecord::query()->findOrFail($input['import']);
|
$import = SupplyRecord::query()->findOrFail($input['import']);
|
||||||
$record = $partyMode ? app(ImportParties::class)->select($actor, $import, $input['data'])
|
$record = $capitalMode ? app(CapitalRegister::class)->save($actor, $input['data']) : ($amountMode ? app(ImportLegalEstimates::class)->save($actor, Requisition::query()->findOrFail($input['request']), $input['data']) : ($legalMode ? app(ImportLegalRules::class)->save($actor, $input['data'], importLegalQaFile()) : ($bankMode ? app(ImportBankSupport::class)->save($actor, $import, $input['data'])
|
||||||
: app(ImportDossier::class)->record($actor, $import, $input['data'], $file());
|
: ($partyMode ? app(ImportParties::class)->select($actor, $import, $input['data'])
|
||||||
|
: app(ImportDossier::class)->record($actor, $import, $input['data'], $file())))));
|
||||||
echo json_encode(['status' => 200, 'id' => $record->id], JSON_THROW_ON_ERROR);
|
echo json_encode(['status' => 200, 'id' => $record->id], JSON_THROW_ON_ERROR);
|
||||||
} catch (HttpExceptionInterface $error) {
|
} catch (HttpExceptionInterface $error) {
|
||||||
echo json_encode(['status' => $error->getStatusCode()], JSON_THROW_ON_ERROR);
|
echo json_encode(['status' => $error->getStatusCode()], JSON_THROW_ON_ERROR);
|
||||||
}
|
}
|
||||||
exit;
|
exit;
|
||||||
}
|
}
|
||||||
if (! in_array($argv[2] ?? '', ['race-dossier', 'race-party'], true)) {
|
if (! in_array($argv[2] ?? '', ['race-dossier', 'race-party', 'race-bank', 'race-legal', 'race-legal-amount', 'race-capital'], true)) {
|
||||||
throw new InvalidArgumentException('Unknown dossier worker mode.');
|
throw new InvalidArgumentException('Unknown dossier worker mode.');
|
||||||
}
|
}
|
||||||
foreach (['same_operation', 'same_version'] as $scenario) {
|
foreach (['same_operation', 'same_version'] as $scenario) {
|
||||||
$prepare = new Process([PHP_BINARY, __FILE__, $database, $partyMode ? 'prepare-party' : 'prepare', $scenario], dirname(__DIR__, 2), timeout: 30);
|
$prepareMode = $capitalMode ? 'prepare-capital' : ($amountMode ? 'prepare-amount' : ($legalMode ? 'prepare-legal' : ($bankMode ? 'prepare-bank' : ($partyMode ? 'prepare-party' : 'prepare'))));
|
||||||
|
$writeMode = $capitalMode ? 'write-capital' : ($amountMode ? 'write-amount' : ($legalMode ? 'write-legal' : ($bankMode ? 'write-bank' : ($partyMode ? 'write-party' : 'write'))));
|
||||||
|
$prepare = new Process([PHP_BINARY, __FILE__, $database, $prepareMode, $scenario], dirname(__DIR__, 2), timeout: 30);
|
||||||
$prepare->mustRun();
|
$prepare->mustRun();
|
||||||
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||||
$db = DB::connection();
|
$db = DB::connection();
|
||||||
@@ -101,7 +150,7 @@ foreach (['same_operation', 'same_version'] as $scenario) {
|
|||||||
if ($scenario === 'same_version' && $index === 1) {
|
if ($scenario === 'same_version' && $index === 1) {
|
||||||
$workerInput['data']['operation_key'] = (string) Str::uuid();
|
$workerInput['data']['operation_key'] = (string) Str::uuid();
|
||||||
}
|
}
|
||||||
$worker = new Process([PHP_BINARY, __FILE__, $database, $partyMode ? 'write-party' : 'write', json_encode($workerInput, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
|
$worker = new Process([PHP_BINARY, __FILE__, $database, $writeMode, json_encode($workerInput, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
|
||||||
$workers[] = $worker;
|
$workers[] = $worker;
|
||||||
$worker->start();
|
$worker->start();
|
||||||
}
|
}
|
||||||
@@ -131,11 +180,11 @@ foreach (['same_operation', 'same_version'] as $scenario) {
|
|||||||
$records = DB::table('supply_records')->where('tenant_id', $input['tenant'])->where('kind', $recordKind)->count() - $input['records_before'];
|
$records = DB::table('supply_records')->where('tenant_id', $input['tenant'])->where('kind', $recordKind)->count() - $input['records_before'];
|
||||||
$audits = DB::table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', $auditAction)->count() - $input['audits_before'];
|
$audits = DB::table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', $auditAction)->count() - $input['audits_before'];
|
||||||
$files = count(Storage::disk('local')->allFiles()) - $input['files_before'];
|
$files = count(Storage::disk('local')->allFiles()) - $input['files_before'];
|
||||||
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $records !== 1 || $audits !== 1 || $files !== ($partyMode ? 0 : 1)) {
|
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $records !== 1 || $audits !== 1 || $files !== ($capitalMode || $partyMode || $bankMode || $amountMode ? 0 : 1)) {
|
||||||
throw new RuntimeException('Dossier contention must preserve one document version, one original and one audit.');
|
throw new RuntimeException('Dossier contention must preserve one document version, one original and one audit.');
|
||||||
}
|
}
|
||||||
auth()->guard()->setUser(User::query()->findOrFail($input['actor']));
|
auth()->guard()->setUser(User::query()->findOrFail($input['actor']));
|
||||||
foreach (SupplyRecord::query()->where('kind', 'import_document')->get() as $record) {
|
foreach (SupplyRecord::query()->whereIn('kind', ['import_document', 'import_legal_source'])->get() as $record) {
|
||||||
app(ImportEvidence::class)->bytes($record);
|
app(ImportEvidence::class)->bytes($record);
|
||||||
}
|
}
|
||||||
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
|
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Services\ImportEvidence;
|
||||||
|
use App\Services\ImportLegalRules;
|
||||||
|
use Illuminate\Contracts\Console\Kernel;
|
||||||
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\File;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
require __DIR__.'/../../vendor/autoload.php';
|
||||||
|
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||||
|
$app->make(Kernel::class)->bootstrap();
|
||||||
|
$database = $argv[1] ?? '';
|
||||||
|
$root = realpath($argv[3] ?? '');
|
||||||
|
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|
||||||
|
|| DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)
|
||||||
|
|| $root === false || ! is_dir($root)) {
|
||||||
|
throw new LogicException('Real-source preparation requires a supplied corpus and disposable local PostgreSQL QA.');
|
||||||
|
}
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
|
||||||
|
$directory = storage_path('framework/testing/legal-corpus-'.$database);
|
||||||
|
Storage::set('local', Storage::build(['driver' => 'local', 'root' => $directory, 'throw' => true]));
|
||||||
|
$inventory = [];
|
||||||
|
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS)) as $entry) {
|
||||||
|
if ($entry->isFile()) {
|
||||||
|
$inventory[] = ['path' => str_replace('\\', '/', substr($entry->getPathname(), strlen($root) + 1)), 'bytes' => $entry->getSize()];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
usort($inventory, fn ($a, $b) => strcmp($a['path'], $b['path']));
|
||||||
|
$patterns = [
|
||||||
|
'Legislacao/2022/12 Dezembro/series-i/br-series-i-29-12-2022-*.pdf' => 'BR I Série 251, 29/12/2022 — Leis 17/2022 e 19/2022, exemplar integral',
|
||||||
|
'novas/BR_248_I_SERIE_SUPLEMENTO_2025.pdf' => 'BR I Série 248, suplemento de 29/12/2025 — Leis 7/2025 a 12/2025',
|
||||||
|
'lei-nr-28-2022-de-29-de-dezembro-lei-cambial.pdf' => 'BR I Série 251, suplemento de 29/12/2022 — Lei 28/2022, Lei Cambial',
|
||||||
|
'Legislacao/2024/03 */series-i/br-series-i-20-03-2024-*.pdf' => 'BR I Série 57, 20/03/2024 — Aviso 3/GBM/2024, normas e procedimentos cambiais',
|
||||||
|
];
|
||||||
|
$f = receiptFixture();
|
||||||
|
supplyGrant($f['issuer'], ['procurement', 'import_customs']);
|
||||||
|
auth()->guard()->setUser($f['issuer']);
|
||||||
|
$fingerprint = fn () => [DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()];
|
||||||
|
$before = $fingerprint();
|
||||||
|
$sources = [];
|
||||||
|
try {
|
||||||
|
foreach ($patterns as $pattern => $reference) {
|
||||||
|
$matches = glob(str_replace('\\', '/', $root).'/'.$pattern);
|
||||||
|
if ($matches === false || count($matches) !== 1) {
|
||||||
|
throw new RuntimeException('The selected corpus reference is missing or ambiguous: '.$reference);
|
||||||
|
}
|
||||||
|
$path = $matches[0];
|
||||||
|
$checksum = hash_file('sha256', $path);
|
||||||
|
$input = ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
|
||||||
|
'official_reference' => $reference, 'reason' => 'Fonte oficial real partilhada pelo proprietário; preparação exclusivamente em empresa e base QA sintéticas, sem publicar regras'];
|
||||||
|
$file = new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true);
|
||||||
|
$record = app(ImportLegalRules::class)->save($f['issuer'], $input, $file);
|
||||||
|
$resolved = app(ImportLegalRules::class)->source($f['issuer'], $f['r'], $record->id);
|
||||||
|
if (hash('sha256', app(ImportEvidence::class)->bytes($resolved)) !== $checksum || hash_file('sha256', $path) !== $checksum
|
||||||
|
|| app(ImportLegalRules::class)->save($f['issuer'], $input, $file)->id !== $record->id) {
|
||||||
|
throw new RuntimeException('The original, private source or idempotent replay differs.');
|
||||||
|
}
|
||||||
|
$sources[] = ['reference' => $reference, 'relative_path' => str_replace('\\', '/', substr($path, strlen($root) + 1)),
|
||||||
|
'bytes' => filesize($path), 'sha256' => $checksum, 'native_authorized_download_verified' => true];
|
||||||
|
}
|
||||||
|
if ($fingerprint() !== $before || SupplyRecord::query()->where('kind', 'import_legal_rule')->exists()) {
|
||||||
|
throw new RuntimeException('Registering sources must not publish rules or create financial/stock effects.');
|
||||||
|
}
|
||||||
|
echo json_encode(['shared_corpus_files_inventoried' => count($inventory), 'inventory_metadata_sha256' => hash('sha256', json_encode($inventory, JSON_THROW_ON_ERROR)),
|
||||||
|
'real_official_sources_prepared' => $sources, 'rules_published' => 0, 'originals_unchanged' => true,
|
||||||
|
'financial_and_stock_unchanged' => true, 'synthetic_qa_organization_only' => true], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||||
|
} finally {
|
||||||
|
$resolved = realpath($directory);
|
||||||
|
$boundary = realpath(storage_path('framework/testing'));
|
||||||
|
if ($resolved !== false && $boundary !== false && str_starts_with(str_replace('\\', '/', $resolved), str_replace('\\', '/', $boundary).'/legal-corpus-compras_receipts_test_')) {
|
||||||
|
File::deleteDirectory($resolved);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\CommonBudget;
|
||||||
|
use App\Services\ImportBankSupport;
|
||||||
|
use App\Services\ImportEstimates;
|
||||||
|
use App\Services\ImportLegalEstimates;
|
||||||
|
use App\Services\ImportLegalRules;
|
||||||
|
use App\Services\SupplyPlanning;
|
||||||
|
use GuzzleHttp\Client;
|
||||||
|
use GuzzleHttp\Cookie\CookieJar;
|
||||||
|
use GuzzleHttp\Exception\ConnectException;
|
||||||
|
use Illuminate\Contracts\Console\Kernel;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\File;
|
||||||
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Symfony\Component\Process\Process;
|
||||||
|
use Tempo\Finance\Budget\BudgetImportEstimate;
|
||||||
|
|
||||||
|
require __DIR__.'/../../vendor/autoload.php';
|
||||||
|
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||||
|
$app->make(Kernel::class)->bootstrap();
|
||||||
|
$database = $argv[1] ?? '';
|
||||||
|
$corpus = realpath($argv[3] ?? '');
|
||||||
|
$candidateRelative = $argv[4] ?? '';
|
||||||
|
$candidateHash = $argv[5] ?? '';
|
||||||
|
$reviewMode = ($argv[2] ?? '') === 'legal-review';
|
||||||
|
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|
||||||
|
|| DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)
|
||||||
|
|| $corpus === false || ! preg_match('~^storage/framework/testing/[A-Za-z0-9_-]+$~D', $candidateRelative)
|
||||||
|
|| ! preg_match('/^[a-f0-9]{64}$/D', $candidateHash) || hash_file('sha256', base_path($candidateRelative.'/manifest.json')) !== $candidateHash) {
|
||||||
|
throw new LogicException('HTTP source review requires a supplied corpus, validated private candidate and disposable PostgreSQL.');
|
||||||
|
}
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/ImportBankQaFixture.php';
|
||||||
|
$files = glob(str_replace('\\', '/', $corpus).'/Legislacao/2022/12 Dezembro/series-i/br-series-i-29-12-2022-*.pdf');
|
||||||
|
if ($files === false || count($files) !== 1 || filesize($files[0]) <= 2097152) {
|
||||||
|
throw new LogicException('Select the complete shared official journal, not a small extracted example.');
|
||||||
|
}
|
||||||
|
$path = $files[0];
|
||||||
|
$originalHash = hash_file('sha256', $path);
|
||||||
|
$f = receiptFixture();
|
||||||
|
supplyGrant($f['issuer'], ['procurement', 'import_customs']);
|
||||||
|
auth()->guard()->setUser($f['issuer']);
|
||||||
|
$password = Str::random(48);
|
||||||
|
$f['issuer']->forceFill(['password' => Hash::make($password)])->save();
|
||||||
|
$fingerprint = fn () => [DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()];
|
||||||
|
$before = $fingerprint();
|
||||||
|
$directory = storage_path('framework/testing/legal-http-'.$database);
|
||||||
|
foreach (['public', 'storage/framework/sessions', 'storage/framework/views', 'storage/framework/cache/data', 'storage/logs', 'storage/app/private'] as $relative) {
|
||||||
|
File::ensureDirectoryExists($directory.'/'.$relative);
|
||||||
|
}
|
||||||
|
File::copyDirectory(base_path($candidateRelative), $directory.'/public/build');
|
||||||
|
$socket = stream_socket_server('tcp://127.0.0.1:0', $errorCode, $error);
|
||||||
|
if ($socket === false) {
|
||||||
|
throw new RuntimeException('Unable to reserve a loopback QA port.');
|
||||||
|
}
|
||||||
|
$address = stream_socket_get_name($socket, false);
|
||||||
|
fclose($socket);
|
||||||
|
$port = substr($address, strrpos($address, ':') + 1);
|
||||||
|
$url = 'http://'.($reviewMode ? 'localhost' : '127.0.0.1').':'.$port;
|
||||||
|
$server = new Process([PHP_BINARY, '-d', 'upload_max_filesize=64M', '-d', 'post_max_size=70M', '-S', '127.0.0.1:'.$port,
|
||||||
|
'tests/Support/import-legal-http-router.php'], base_path(), ['APP_ENV' => 'testing', 'APP_DEBUG' => 'false',
|
||||||
|
'APP_URL' => $url, 'ASSET_URL' => $url, 'SGC_LEGAL_HTTP_QA_ROOT' => $directory, 'SGC_LEGAL_HTTP_QA_PORT' => $port,
|
||||||
|
'SESSION_COOKIE' => 'sgc_legal_http_'.substr($database, -12), 'SESSION_DRIVER' => 'file'], timeout: null);
|
||||||
|
$client = new Client(['base_uri' => $url, 'cookies' => $cookies = new CookieJar, 'http_errors' => false, 'allow_redirects' => false,
|
||||||
|
'timeout' => 20, 'expect' => false]);
|
||||||
|
$result = null;
|
||||||
|
try {
|
||||||
|
$server->start();
|
||||||
|
$ready = false;
|
||||||
|
$deadline = microtime(true) + 10;
|
||||||
|
do {
|
||||||
|
try {
|
||||||
|
$ready = $client->get('/up')->getStatusCode() === 200;
|
||||||
|
} catch (ConnectException) {
|
||||||
|
usleep(50000);
|
||||||
|
}
|
||||||
|
} while (! $ready && $server->isRunning() && microtime(true) < $deadline);
|
||||||
|
if (! $ready || $client->get('/login')->getStatusCode() !== 200) {
|
||||||
|
throw new RuntimeException('Private native HTTP login page unavailable.');
|
||||||
|
}
|
||||||
|
$token = fn () => rawurldecode($cookies->getCookieByName('XSRF-TOKEN')?->getValue() ?? '');
|
||||||
|
if ($token() === '') {
|
||||||
|
throw new RuntimeException('Native session did not issue a CSRF cookie.');
|
||||||
|
}
|
||||||
|
$login = $client->post('/login', ['headers' => ['Accept' => 'application/json', 'X-XSRF-TOKEN' => $token()],
|
||||||
|
'form_params' => ['email' => $f['issuer']->email, 'password' => $password]]);
|
||||||
|
if (! in_array($login->getStatusCode(), [200, 302, 303], true)) {
|
||||||
|
throw new RuntimeException('Native synthetic Fortify login failed: '.$login->getStatusCode());
|
||||||
|
}
|
||||||
|
$route = '/requisicoes/'.$f['r']->id.'/base-legal';
|
||||||
|
$headers = ['Accept' => 'application/json', 'X-XSRF-TOKEN' => $token(), 'Referer' => $url.$route];
|
||||||
|
$negative = $client->post($route, ['headers' => ['Accept' => 'application/json'], 'json' => ['action' => 'source']]);
|
||||||
|
if ($negative->getStatusCode() !== 419) {
|
||||||
|
throw new RuntimeException('Native HTTP source requests must require CSRF: '.$negative->getStatusCode());
|
||||||
|
}
|
||||||
|
$input = ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => '0',
|
||||||
|
'official_reference' => 'BR I Série 251 de 29/12/2022 — exemplar integral real partilhado',
|
||||||
|
'reason' => 'Ensaio HTTP estritamente QA com exemplar oficial real, empresa e conta sintéticas; sem publicar regras'];
|
||||||
|
foreach ([1, 2] as $attempt) {
|
||||||
|
$multipart = array_map(fn ($name) => ['name' => $name, 'contents' => $input[$name]], array_keys($input));
|
||||||
|
$multipart[] = ['name' => 'file', 'contents' => fopen($path, 'rb'), 'filename' => basename($path), 'headers' => ['Content-Type' => 'application/pdf']];
|
||||||
|
$response = $client->post($route, ['headers' => $headers, 'multipart' => $multipart]);
|
||||||
|
if (! in_array($response->getStatusCode(), [302, 303], true)) {
|
||||||
|
throw new RuntimeException('Native large-source multipart upload failed: '.$response->getStatusCode());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$initial = $client->get($route);
|
||||||
|
if ($initial->getStatusCode() !== 200 || ! preg_match('~<script[^>]*data-page="[^"]+"[^>]*>(.*?)</script>~s', (string) $initial->getBody(), $initialData)) {
|
||||||
|
throw new RuntimeException('Native source page bootstrap unavailable: '.$initial->getStatusCode());
|
||||||
|
}
|
||||||
|
$initialPage = json_decode($initialData[1], true, 64, JSON_THROW_ON_ERROR);
|
||||||
|
$page = $client->get($route, ['headers' => ['X-Inertia' => 'true', 'X-Inertia-Version' => $initialPage['version'], 'Accept' => 'text/html, application/xhtml+xml']]);
|
||||||
|
if ($page->getStatusCode() !== 200 || ! str_contains($page->getHeaderLine('Content-Type'), 'application/json')) {
|
||||||
|
throw new RuntimeException('Native Inertia page did not accept its bootstrap version: '.$page->getStatusCode());
|
||||||
|
}
|
||||||
|
$props = json_decode((string) $page->getBody(), true, 64, JSON_THROW_ON_ERROR)['props'] ?? [];
|
||||||
|
$source = SupplyRecord::query()->where('kind', 'import_legal_source')->sole();
|
||||||
|
$download = $client->get($route.'/fontes/'.$source->id);
|
||||||
|
$guest = new Client(['base_uri' => $url, 'http_errors' => false, 'allow_redirects' => false, 'timeout' => 10]);
|
||||||
|
$anonymous = $guest->get($route.'/fontes/'.$source->id, ['headers' => ['Accept' => 'application/json']]);
|
||||||
|
if ($page->getStatusCode() !== 200 || ($props['sources']['total'] ?? null) !== 1 || ($props['rules']['total'] ?? null) !== 0
|
||||||
|
|| $download->getStatusCode() !== 200 || hash('sha256', (string) $download->getBody()) !== $originalHash
|
||||||
|
|| hash_file('sha256', $path) !== $originalHash || $anonymous->getStatusCode() !== 401
|
||||||
|
|| DB::table('audit_logs')->where('tenant_id', $f['tenant']->id)->where('action', 'import.legal_source_recorded')->count() !== 1
|
||||||
|
|| $fingerprint() !== $before) {
|
||||||
|
throw new RuntimeException('Native source scope, large bytes, idempotence, authentication or financial preservation not demonstrated.');
|
||||||
|
}
|
||||||
|
DB::table('organization_memberships')->where('user_id', $f['issuer']->id)->delete();
|
||||||
|
$revoked = $client->get($route.'/fontes/'.$source->id, ['headers' => ['Accept' => 'application/json']]);
|
||||||
|
if ($revoked->getStatusCode() !== 403) {
|
||||||
|
throw new RuntimeException('Native download did not revalidate revoked QA authority.');
|
||||||
|
}
|
||||||
|
$result = ['native_legal_http_login' => true, 'csrf_required' => true, 'large_multipart_upload_bytes' => filesize($path),
|
||||||
|
'original_sha256' => $originalHash, 'original_unchanged' => true, 'exact_native_download' => true, 'one_source_one_audit_after_replay' => true,
|
||||||
|
'guest_status' => 401, 'revoked_status' => 403, 'rules_published' => 0, 'financial_stock_unchanged' => true,
|
||||||
|
'private_upload_limit' => '64M', 'private_post_limit' => '70M', 'global_php_config_unchanged' => true];
|
||||||
|
if ($reviewMode) {
|
||||||
|
// Existing factory password is confined to guarded, disposable synthetic QA identities.
|
||||||
|
$reviewer = $f['otherReceiver'];
|
||||||
|
supplyGrant($reviewer, ['procurement', 'requester', 'import_read', 'import_prepare', 'import_customs']);
|
||||||
|
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true, 'import-estimates.qa_enabled' => true,
|
||||||
|
'import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true, 'import-readiness.qa_enabled' => true]);
|
||||||
|
Storage::set('local', Storage::build(['driver' => 'local', 'root' => $directory.'/storage/app/private', 'throw' => true]));
|
||||||
|
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||||
|
$approver = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||||
|
supplyGrant($author, ['finance']);
|
||||||
|
supplyGrant($approver, ['finance']);
|
||||||
|
auth()->guard()->setUser($author);
|
||||||
|
$budget = app(CommonBudget::class)->for($author)->create(['cost_center_id' => $f['r']->cost_center_id, 'year' => (int) now()->year,
|
||||||
|
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 1000000, 'reason' => 'Dotação estritamente sintética da revisão nativa']);
|
||||||
|
auth()->guard()->setUser($approver);
|
||||||
|
app(CommonBudget::class)->for($approver)->approve($budget);
|
||||||
|
auth()->guard()->setUser($reviewer);
|
||||||
|
$draftRequest = $f['r']->replicate();
|
||||||
|
$draftRequest->fill(['number' => 'VISUAL-LEGAL-'.Str::random(8), 'requester_id' => $reviewer->id, 'status' => 'draft']);
|
||||||
|
$draftRequest->save();
|
||||||
|
$draftItem = $f['r']->items()->sole()->replicate();
|
||||||
|
$draftItem->requisition_id = $draftRequest->id;
|
||||||
|
$draftItem->save();
|
||||||
|
$legalDraft = app(ImportLegalRules::class)->save($reviewer, importLegalQaInput(['title' => 'Regra de ensaio — dados fictícios', 'charges' => [importLegalQaCharge()]]), importLegalQaFile());
|
||||||
|
$legalRule = app(ImportLegalRules::class)->save($reviewer, ['operation_key' => (string) Str::uuid(), 'record_key' => $legalDraft->record_key,
|
||||||
|
'version' => 1, 'action' => 'publish', 'reason' => 'Publicação de dados estritamente fictícios para revisão nativa isolada']);
|
||||||
|
$amountInput = importLegalQaAmountInput($draftItem->id, $legalRule->id);
|
||||||
|
$amountInput['bases']['synthetic-duty']['value_minor'] = 10000;
|
||||||
|
$amount = app(ImportLegalEstimates::class)->save($reviewer, $draftRequest, $amountInput);
|
||||||
|
app(ImportEstimates::class)->save($reviewer, $draftRequest, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'budget_id' => $budget,
|
||||||
|
'reason' => 'Plano fictício apenas com direitos neste cenário; sem reserva ou submissão', 'legal_sources' => ['duty' => ['estimate_id' => $amount->id, 'charge_key' => 'synthetic-duty']],
|
||||||
|
'components' => array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => $kind === 'duty' ? 'known' : 'not_applicable',
|
||||||
|
'basis' => 'Pressuposto estritamente sintético desta revisão, não isenção real', 'subtotal_minor' => $kind === 'duty' ? 750 : null,
|
||||||
|
'tax_minor' => $kind === 'duty' ? 0 : null, 'total_minor' => $kind === 'duty' ? 750 : null], BudgetImportEstimate::KINDS)]);
|
||||||
|
$import = app(SupplyPlanning::class)->save($reviewer, 'import', supplyInput(['purchase_order_id' => $f['order']->id, 'purpose' => 'internal',
|
||||||
|
'jurisdiction' => 'Âmbito fictício QA', 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Regime fictício QA']));
|
||||||
|
$bank = importBankQaFixture($reviewer, $import);
|
||||||
|
app(ImportBankSupport::class)->save($reviewer, $import, $bank['input']);
|
||||||
|
$stopFile = $directory.'/stop';
|
||||||
|
echo json_encode(['private_review_running' => true, 'url' => $url, 'stop_file' => $stopFile,
|
||||||
|
'synthetic_user' => $reviewer->email, 'draft_request' => $draftRequest->id, 'import' => $import->id,
|
||||||
|
'legal_url' => $url.'/requisicoes/'.$draftRequest->id.'/base-legal?'.http_build_query(['code' => '1234', 'origin' => 'Synthetic A', 'sector' => 'Synthetic sector', 'date' => '2026-11-27']),
|
||||||
|
'private_candidate_manifest' => $candidateHash, 'pilot_assets_changed' => false], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||||
|
$deadline = microtime(true) + 3600;
|
||||||
|
while (! is_file($stopFile) && microtime(true) < $deadline) {
|
||||||
|
if (! $server->isRunning()) {
|
||||||
|
throw new RuntimeException('Private native review server stopped unexpectedly.');
|
||||||
|
}
|
||||||
|
$server->getIncrementalOutput();
|
||||||
|
$server->getIncrementalErrorOutput();
|
||||||
|
usleep(100000);
|
||||||
|
}
|
||||||
|
$result['private_native_review_stopped'] = true;
|
||||||
|
}
|
||||||
|
} catch (Throwable $error) {
|
||||||
|
$summary = 'No native exception log.';
|
||||||
|
$log = $directory.'/storage/logs/laravel.log';
|
||||||
|
if (is_file($log) && preg_match_all('/testing\.ERROR: ([^\r\n]+)/', file_get_contents($log), $matches) && $matches[1] !== []) {
|
||||||
|
$summary = substr(str_replace($password, '[synthetic credential redacted]', end($matches[1])), 0, 300);
|
||||||
|
}
|
||||||
|
throw new RuntimeException($error->getMessage().' Native diagnostic: '.$summary);
|
||||||
|
} finally {
|
||||||
|
$server->stop();
|
||||||
|
$resolved = realpath($directory);
|
||||||
|
$boundary = realpath(storage_path('framework/testing'));
|
||||||
|
if ($resolved !== false && $boundary !== false && str_replace('\\', '/', $resolved) === str_replace('\\', '/', $boundary).'/legal-http-'.$database) {
|
||||||
|
File::deleteDirectory($resolved);
|
||||||
|
}
|
||||||
|
if ($result !== null) {
|
||||||
|
echo json_encode([...$result, 'private_http_server_stopped' => true, 'private_http_root_removed' => ! is_dir($directory)], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\CriticalityLevel;
|
||||||
|
use App\Models\Equipment;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Services\CapitalAssignments;
|
||||||
|
use App\Services\CapitalRegister;
|
||||||
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Inertia\Testing\AssertableInertia as Assert;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
config(['capital-register.qa_enabled' => true]);
|
||||||
|
$this->withoutVite();
|
||||||
|
$this->f = receiptFixture();
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
$this->input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
|
||||||
|
'type' => 'project', 'code' => 'PRJ-QA', 'name' => 'Projecto estritamente sintético',
|
||||||
|
'department_id' => $this->f['department']->id, 'equipment_id' => null,
|
||||||
|
'reference' => 'Documento fictício para cadastro independente de Compras', 'state' => 'active',
|
||||||
|
'reason' => 'Preparação de referência sintética para testes de compras'];
|
||||||
|
});
|
||||||
|
|
||||||
|
test('own project register versions preserves identity and replay without financial or stock effects', function () {
|
||||||
|
$service = app(CapitalRegister::class);
|
||||||
|
$before = [];
|
||||||
|
foreach (['budget_entries', 'stock_movements', 'invoices', 'purchase_orders'] as $table) {
|
||||||
|
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
||||||
|
}
|
||||||
|
$first = $service->save($this->f['issuer'], $this->input);
|
||||||
|
expect($first->version)->toBe(1)->and($first->snapshot['source_system'])->toBe('compras');
|
||||||
|
expect($service->save($this->f['issuer'], $this->input)->id)->toBe($first->id);
|
||||||
|
$archive = [...$this->input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1, 'state' => 'archived'];
|
||||||
|
$second = $service->save($this->f['issuer'], $archive);
|
||||||
|
expect($second->version)->toBe(2)->and($second->state)->toBe('archived')
|
||||||
|
->and($first->fresh()->state)->toBe('active')->and(SupplyRecord::query()->where('kind', 'capital_register')->count())->toBe(2);
|
||||||
|
foreach ($before as $table => $rows) {
|
||||||
|
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
|
||||||
|
}
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], [...$archive, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid()]))->toThrow(ValidationException::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('register rejects reused operation content and renaming a permanent code', function () {
|
||||||
|
$service = app(CapitalRegister::class);
|
||||||
|
$first = $service->save($this->f['issuer'], $this->input);
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'name' => 'Conteúdo diferente']))->toThrow(HttpException::class);
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(),
|
||||||
|
'record_key' => $first->record_key, 'version' => 1, 'code' => 'OUTRO']))->toThrow(ValidationException::class);
|
||||||
|
expect(SupplyRecord::query()->where('kind', 'capital_register')->count())->toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('asset references reuse a physical equipment identity and reject duplicate or removed links', function () {
|
||||||
|
$level = CriticalityLevel::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['issuer']->id, 'created_at' => now(), 'code' => 'QA', 'name' => 'Ensaio', 'criteria' => 'Só fixture sintética', 'is_critical' => false]);
|
||||||
|
$equipment = Equipment::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['issuer']->id, 'code' => 'EQ-QA', 'description' => 'Equipamento físico sintético',
|
||||||
|
'area' => 'Área sintética', 'status' => 'active', 'department_id' => $this->f['department']->id, 'criticality_level_id' => $level->id]);
|
||||||
|
$input = [...$this->input, 'type' => 'asset', 'code' => 'ASSET-QA', 'equipment_id' => $equipment->id];
|
||||||
|
$service = app(CapitalRegister::class);
|
||||||
|
$first = $service->save($this->f['issuer'], $input);
|
||||||
|
expect($first->snapshot['equipment']['id'])->toBe($equipment->id)->and(Equipment::query()->count())->toBe(1);
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'code' => 'OTHER-QA']))->toThrow(ValidationException::class);
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1, 'equipment_id' => null]))->toThrow(ValidationException::class);
|
||||||
|
$this->get('/projectos-imobilizado?history='.$first->record_key)->assertOk()->assertInertia(fn (Assert $page) => $page->has('history.data', 1));
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'code' => ['invalid']]))->toThrow(ValidationException::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('native register page is encrypted private paginated and gated off outside QA', function () {
|
||||||
|
app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
|
||||||
|
$this->get('/projectos-imobilizado')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
|
||||||
|
->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
|
||||||
|
->assertInertia(fn (Assert $page) => $page->component('equipment/capital-register')
|
||||||
|
->has('records.data', 1)->where('records.data.0.data.code', 'PRJ-QA')->where('canManage', true));
|
||||||
|
config(['capital-register.qa_enabled' => false]);
|
||||||
|
$this->get('/projectos-imobilizado')->assertStatus(503);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('native register revalidates operator and hides foreign department identity without creating versions', function () {
|
||||||
|
$service = app(CapitalRegister::class);
|
||||||
|
$first = $service->save($this->f['issuer'], $this->input);
|
||||||
|
$this->actingAs($this->f['receiver']);
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
$other = receiptFixture();
|
||||||
|
$this->actingAs($other['issuer']);
|
||||||
|
$this->get('/projectos-imobilizado')->assertOk()->assertInertia(fn (Assert $page) => $page->has('records.data', 0));
|
||||||
|
$this->post('/projectos-imobilizado', [...$this->input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1])->assertNotFound();
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
expect(SupplyRecord::query()->where('kind', 'capital_register')->count())->toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('line destination freezes the chosen project version and preserves it after archival without financial effects', function () {
|
||||||
|
$register = app(CapitalRegister::class);
|
||||||
|
$source = $register->save($this->f['issuer'], $this->input);
|
||||||
|
$this->f['r']->update(['status' => 'draft']);
|
||||||
|
$item = $this->f['r']->items()->firstOrFail();
|
||||||
|
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $item->id,
|
||||||
|
'capital_id' => $source->id, 'reason' => 'Escolha de destino sintético da linha da requisição'];
|
||||||
|
$service = app(CapitalAssignments::class);
|
||||||
|
$first = $service->save($this->f['issuer'], $this->f['r'], $input);
|
||||||
|
expect($first->state)->toBe('linked')->and($service->save($this->f['issuer'], $this->f['r'], $input)->id)->toBe($first->id);
|
||||||
|
$register->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(),
|
||||||
|
'record_key' => $source->record_key, 'version' => 1, 'state' => 'archived', 'name' => 'Designação posterior sintética']);
|
||||||
|
$frozen = $service->freezeForItems($this->f['issuer'], [$item->id]);
|
||||||
|
expect($frozen[$item->id]['snapshot']['source']['version'])->toBe(1)
|
||||||
|
->and($frozen[$item->id]['snapshot']['source']['data']['name'])->toBe($this->input['name']);
|
||||||
|
$this->get('/requisicoes/'.$this->f['r']->id.'/projectos-imobilizado')->assertOk()
|
||||||
|
->assertInertia(fn (Assert $page) => $page->component('requisitions/capital-assignments')->where('canWrite', true)->has('choices.data', 0)->has('current', 1));
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1]))->toThrow(ModelNotFoundException::class);
|
||||||
|
expect(DB::table('budget_entries')->count())->toBe(0)->and(DB::table('stock_movements')->count())->toBe(0);
|
||||||
|
$item->update(['description' => 'Artigo alterado após a escolha']);
|
||||||
|
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
|
||||||
|
$cleared = $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'capital_id' => null]);
|
||||||
|
expect($cleared->state)->toBe('cleared')->and($service->freezeForItems($this->f['issuer'], [$item->id]))->toBe([])
|
||||||
|
->and($first->fresh()->state)->toBe('linked');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('submitted requisitions reject new line destinations and stale versions do not replace choices', function () {
|
||||||
|
$source = app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
|
||||||
|
$item = $this->f['r']->items()->firstOrFail();
|
||||||
|
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $item->id, 'capital_id' => $source->id,
|
||||||
|
'reason' => 'Escolha documental sintética preservando decisões anteriores'];
|
||||||
|
$service = app(CapitalAssignments::class);
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], $input))->toThrow(HttpException::class);
|
||||||
|
$this->f['r']->update(['status' => 'draft']);
|
||||||
|
$service->save($this->f['issuer'], $this->f['r'], $input);
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'capital_id' => null]))->toThrow(HttpException::class);
|
||||||
|
config(['capital-register.qa_enabled' => false]);
|
||||||
|
expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
|
||||||
|
expect(SupplyRecord::query()->where('kind', 'capital_assignment')->count())->toBe(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ImportBankSupport;
|
||||||
|
use App\Services\ImportDossier;
|
||||||
|
use App\Services\SupplyPlanning;
|
||||||
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||||
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Inertia\Testing\AssertableInertia;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
|
||||||
|
function bankSupportOriginal(object $test, string $type, string $reference, ?SupplyRecord $previous = null): SupplyRecord
|
||||||
|
{
|
||||||
|
return app(ImportDossier::class)->record($test->f['issuer'], $test->import, ['operation_key' => (string) Str::uuid(), 'type' => $type,
|
||||||
|
'record_key' => $previous?->record_key, 'version' => $previous?->version ?? 0, 'reference' => $reference,
|
||||||
|
'issuer_reference' => 'Synthetic issuing entity', 'issued_on' => today()->toDateString(), 'notes' => 'Synthetic bank-support evidence only.',
|
||||||
|
'reason' => 'Preservar original sintético para o acompanhamento bancário'],
|
||||||
|
UploadedFile::fake()->createWithContent('bank-support.pdf', "%PDF-1.4\nSynthetic original ".$reference."\n%%EOF"));
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
config(['import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true]);
|
||||||
|
Storage::fake('local');
|
||||||
|
$this->withoutVite();
|
||||||
|
$this->f = receiptFixture();
|
||||||
|
supplyGrant($this->f['issuer'], ['procurement', 'import_prepare']);
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
$this->import = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput([
|
||||||
|
'purchase_order_id' => $this->f['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Synthetic bank-support jurisdiction',
|
||||||
|
'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary regime']));
|
||||||
|
$this->term = bankSupportOriginal($this, 'bank_commitment', 'BANK-TERM-QA');
|
||||||
|
$this->declaration = bankSupportOriginal($this, 'customs_declaration', 'DU-QA');
|
||||||
|
$this->invoice = bankSupportOriginal($this, 'commercial_invoice', 'INVOICE-QA-1');
|
||||||
|
$this->input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
|
||||||
|
'commitment_document_id' => $this->term->id, 'declaration_document_id' => $this->declaration->id,
|
||||||
|
'support_document_ids' => [$this->invoice->id], 'requirements_known' => true,
|
||||||
|
'required_support_types' => ['commercial_invoice'], 'required_support_counts' => ['commercial_invoice' => 2],
|
||||||
|
'requirements_basis' => 'Synthetic bank request explicitly asks for two commercial invoices',
|
||||||
|
'submission_document_id' => null, 'submission_basis' => null, 'submitted_on' => null,
|
||||||
|
'due_on' => today()->subDay()->toDateString(), 'deadline_basis' => 'Explicit synthetic bank letter deadline, not a legal default',
|
||||||
|
'reason' => 'Acompanhamento estritamente documental e sintético'];
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bank support preserves exact requested counts versions and original delivery evidence without payment or JUE effects', function () {
|
||||||
|
$service = app(ImportBankSupport::class);
|
||||||
|
$before = [DB::table('stock_movements')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), $this->import->fresh()->getAttributes()];
|
||||||
|
$first = $service->save($this->f['issuer'], $this->import, $this->input);
|
||||||
|
expect($first->state)->toBe('tracking')->and($service->save($this->f['issuer'], $this->import, $this->input)->id)->toBe($first->id)
|
||||||
|
->and(implode(' ', $service->issues($first)))->toContain('Factura comercial (1)', 'Prazo documental ultrapassado', 'não demonstra a entrega');
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
|
||||||
|
$invoice = bankSupportOriginal($this, 'commercial_invoice', 'INVOICE-QA-2');
|
||||||
|
$secondInput = [...$this->input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1,
|
||||||
|
'support_document_ids' => [$this->invoice->id, $invoice->id]];
|
||||||
|
$ready = $service->save($this->f['issuer'], $this->import, $secondInput);
|
||||||
|
expect($ready->state)->toBe('ready')->and(implode(' ', $service->issues($ready)))->toContain('Prazo documental ultrapassado');
|
||||||
|
$delivery = bankSupportOriginal($this, 'bank_support', 'BANK-DELIVERY-QA-1');
|
||||||
|
$thirdInput = [...$secondInput, 'operation_key' => (string) Str::uuid(), 'version' => 2,
|
||||||
|
'submission_document_id' => $delivery->id, 'submission_basis' => 'Synthetic documentary delivery receipt; no live bank action', 'submitted_on' => today()->toDateString()];
|
||||||
|
$documented = $service->save($this->f['issuer'], $this->import, $thirdInput);
|
||||||
|
expect($documented->state)->toBe('documented')->and($service->issues($documented))->toBe(['Entrega documentada após o prazo indicado.'])
|
||||||
|
->and($documented->snapshot['bank_transfer_executed'])->toBeFalse()->and($documented->snapshot['jue_submission_executed'])->toBeFalse()
|
||||||
|
->and($documented->snapshot['bank_compliance_certified'])->toBeFalse();
|
||||||
|
$correction = bankSupportOriginal($this, 'bank_support', 'BANK-DELIVERY-QA-2', $delivery);
|
||||||
|
expect(implode(' ', $service->issues($documented)))->toContain('foi corrigido', 'Prazo documental ultrapassado');
|
||||||
|
$fourth = $service->save($this->f['issuer'], $this->import, [...$thirdInput, 'operation_key' => (string) Str::uuid(), 'version' => 3, 'submission_document_id' => $correction->id]);
|
||||||
|
expect($fourth->version)->toBe(4)->and($service->issues($fourth))->toBe(['Entrega documentada após o prazo indicado.'])->and($first->fresh()->state)->toBe('tracking')
|
||||||
|
->and([DB::table('stock_movements')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), $this->import->fresh()->getAttributes()])->toBe($before);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unknown bank requirements and deadlines stay unknown and cannot silently become a completed or zero-day obligation', function () {
|
||||||
|
$record = app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input,
|
||||||
|
'requirements_known' => false, 'required_support_types' => [], 'required_support_counts' => [], 'declaration_document_id' => null,
|
||||||
|
'due_on' => null, 'deadline_basis' => null]);
|
||||||
|
expect($record->state)->toBe('tracking')->and($record->data['due_on'])->toBeNull()
|
||||||
|
->and(implode(' ', app(ImportBankSupport::class)->issues($record)))->toContain('desconhecidos', 'Prazo documental ainda por indicar');
|
||||||
|
expect(fn () => app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input, 'deadline_basis' => ' ']))->toThrow(HttpException::class);
|
||||||
|
expect(fn () => app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input, 'required_support_counts' => []]))->toThrow(HttpException::class);
|
||||||
|
$delivery = bankSupportOriginal($this, 'bank_support', 'DELIVERY-UNKNOWN-DATE');
|
||||||
|
expect(fn () => app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input,
|
||||||
|
'submission_document_id' => $delivery->id, 'submission_basis' => 'Synthetic delivery evidence with no event date']))->toThrow(HttpException::class);
|
||||||
|
expect(fn () => app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input,
|
||||||
|
'submission_document_id' => $delivery->id, 'submission_basis' => 'Synthetic delivery cannot be recorded as already occurred tomorrow',
|
||||||
|
'submitted_on' => today()->addDay()->toDateString()]))->toThrow(ValidationException::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bank follow-up rejects foreign documents wrong types stale versions and withdrawn write authority', function () {
|
||||||
|
$service = app(ImportBankSupport::class);
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'commitment_document_id' => $this->invoice->id]))->toThrow(HttpException::class);
|
||||||
|
$record = $service->save($this->f['issuer'], $this->import, $this->input);
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'record_key' => $record->record_key, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
|
||||||
|
$other = receiptFixture();
|
||||||
|
supplyGrant($other['issuer'], ['procurement', 'import_prepare']);
|
||||||
|
$this->actingAs($other['issuer']);
|
||||||
|
$otherImport = app(SupplyPlanning::class)->save($other['issuer'], 'import', supplyInput([
|
||||||
|
'purchase_order_id' => $other['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Other synthetic jurisdiction',
|
||||||
|
'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary regime']));
|
||||||
|
$otherDocument = bankSupportOriginal((object) ['f' => $other, 'import' => $otherImport], 'bank_commitment', 'OTHER-BANK-TERM');
|
||||||
|
expect(fn () => $service->save($other['issuer'], $this->import, $this->input))->toThrow(ModelNotFoundException::class);
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
|
||||||
|
'commitment_document_id' => $otherDocument->id]))->toThrow(ModelNotFoundException::class);
|
||||||
|
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->delete();
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('native bank entry consultation and full-scope CSV share source data permissions and formula-safe references', function () {
|
||||||
|
$term = bankSupportOriginal($this, 'bank_commitment', '=SYNTHETIC-REFERENCE');
|
||||||
|
$input = [...$this->input, 'commitment_document_id' => $term->id];
|
||||||
|
$url = '/compras/importacoes/'.$this->import->id.'/suporte-bancario';
|
||||||
|
$this->post($url, $input)->assertRedirect();
|
||||||
|
$record = SupplyRecord::query()->where('kind', 'import_bank_support')->where('operation_key', $input['operation_key'])->firstOrFail();
|
||||||
|
$this->post($url, $input)->assertRedirect();
|
||||||
|
expect(SupplyRecord::query()->where('kind', 'import_bank_support')->count())->toBe(1);
|
||||||
|
$tables = ['users', 'supply_records', 'audit_logs', 'budget_entries', 'invoices', 'stock_movements'];
|
||||||
|
$before = [];
|
||||||
|
foreach ($tables as $table) {
|
||||||
|
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
||||||
|
}
|
||||||
|
$this->get($url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
|
||||||
|
->assertInertia(fn (AssertableInertia $page) => $page->component('supply/import-bank-support')
|
||||||
|
->where('canWrite', true)->where('current.data.0.id', $record->id)->where('current.data.0.data.required_support_counts.commercial_invoice', 2)
|
||||||
|
->missing('current.data.0.snapshot.documents.0.path'));
|
||||||
|
$csv = $this->get($url.'.csv?bank_current_page=999999')->assertOk()->assertDownload();
|
||||||
|
expect($csv->streamedContent())->toContain("'=SYNTHETIC-REFERENCE", 'Factura comercial: 2', 'Prazo documental ultrapassado')
|
||||||
|
->not->toContain('import-dossier/', 'account_identifier');
|
||||||
|
foreach ($tables as $table) {
|
||||||
|
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($before[$table]);
|
||||||
|
}
|
||||||
|
$viewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||||
|
supplyGrant($viewer, ['finance']);
|
||||||
|
$this->actingAs($viewer)->get($url)->assertOk()->assertInertia(fn (AssertableInertia $page) => $page->where('canWrite', false));
|
||||||
|
$this->post($url, [...$input, 'operation_key' => (string) Str::uuid()])->assertForbidden();
|
||||||
|
config(['import-bank-support.qa_enabled' => false]);
|
||||||
|
$this->get($url)->assertStatus(503);
|
||||||
|
});
|
||||||
@@ -9,6 +9,8 @@ use App\Models\User;
|
|||||||
use App\Services\CommonBudget;
|
use App\Services\CommonBudget;
|
||||||
use App\Services\ImportEstimates;
|
use App\Services\ImportEstimates;
|
||||||
use App\Services\ImportLandedCosts;
|
use App\Services\ImportLandedCosts;
|
||||||
|
use App\Services\ImportLegalEstimates;
|
||||||
|
use App\Services\ImportLegalRules;
|
||||||
use App\Services\ImportTariffCodes;
|
use App\Services\ImportTariffCodes;
|
||||||
use App\Services\RequisitionWorkflow;
|
use App\Services\RequisitionWorkflow;
|
||||||
use App\Services\SupplyPlanning;
|
use App\Services\SupplyPlanning;
|
||||||
@@ -24,6 +26,7 @@ use Tempo\Finance\Budget\BudgetImportEstimate;
|
|||||||
|
|
||||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
require_once __DIR__.'/../Support/SupplyFixture.php';
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
|
||||||
|
|
||||||
beforeEach(function () {
|
beforeEach(function () {
|
||||||
if (! class_exists(BudgetImportEstimate::class)) {
|
if (! class_exists(BudgetImportEstimate::class)) {
|
||||||
@@ -54,6 +57,58 @@ beforeEach(function () {
|
|||||||
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS)];
|
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS)];
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('native import cost assumptions reuse exact legal charges once with explicit tax split and immutable source provenance', function () {
|
||||||
|
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
|
||||||
|
Storage::fake('local');
|
||||||
|
supplyGrant($this->f['issuer'], ['procurement', 'import_customs']);
|
||||||
|
$rules = app(ImportLegalRules::class);
|
||||||
|
$draft = $rules->save($this->f['issuer'], importLegalQaInput(['charges' => [[
|
||||||
|
'key' => 'synthetic-duty', 'kind' => 'duty', 'label' => 'Synthetic duty', 'method' => 'ad_valorem', 'rate_percent' => '7.5',
|
||||||
|
'specific_minor' => null, 'quantity_unit' => null, 'basis_reference' => 'Synthetic explicit customs-value basis',
|
||||||
|
]]]), importLegalQaFile());
|
||||||
|
$rule = $rules->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key,
|
||||||
|
'version' => 1, 'action' => 'publish', 'reason' => 'Synthetic rate publication for native estimate integration']);
|
||||||
|
$legal = app(ImportLegalEstimates::class)->save($this->f['issuer'], $this->draft, ['operation_key' => (string) Str::uuid(), 'version' => 0,
|
||||||
|
'requisition_item_id' => $this->draft->items()->sole()->id, 'rule_id' => $rule->id, 'match_code' => '1234', 'origin' => 'Synthetic A',
|
||||||
|
'sector' => 'Synthetic sector', 'date' => '2026-11-27', 'bases' => ['synthetic-duty' => ['value_minor' => 10000,
|
||||||
|
'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic declared customs valuation']], 'reason' => 'Synthetic exact charge adoption fixture']);
|
||||||
|
$input = $this->input;
|
||||||
|
foreach ($input['components'] as &$component) {
|
||||||
|
$component['status'] = $component['kind'] === 'duty' ? 'known' : 'not_applicable';
|
||||||
|
$component['basis'] = 'Explicit synthetic assumptions; other costs do not apply in this test';
|
||||||
|
if ($component['kind'] === 'duty') {
|
||||||
|
$component['subtotal_minor'] = 750;
|
||||||
|
$component['tax_minor'] = 0;
|
||||||
|
$component['total_minor'] = 750;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unset($component);
|
||||||
|
$input['legal_sources'] = ['duty' => ['estimate_id' => $legal->id, 'charge_key' => 'synthetic-duty']];
|
||||||
|
$native = app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input);
|
||||||
|
expect($native->snapshot['plan']['budget_amount_minor'])->toBe(10750)
|
||||||
|
->and($native->snapshot['legal_sources']['duty']['estimate_id'])->toBe($legal->id)
|
||||||
|
->and($native->snapshot['legal_sources']['duty']['legal_rule']['id'])->toBe($rule->id)
|
||||||
|
->and(DB::table('budget_entries')->count())->toBe(0);
|
||||||
|
$changed = [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1];
|
||||||
|
foreach ($changed['components'] as &$component) {
|
||||||
|
if ($component['kind'] === 'duty') {
|
||||||
|
$component['subtotal_minor'] = 751;
|
||||||
|
$component['total_minor'] = 751;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unset($component);
|
||||||
|
expect(fn () => app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $changed))->toThrow(HttpException::class);
|
||||||
|
$duplicate = [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1];
|
||||||
|
$duty = array_values(array_filter($duplicate['components'], fn ($component) => $component['kind'] === 'duty'))[0];
|
||||||
|
$duplicate['components'][] = [...$duty, 'key' => 'duty-again'];
|
||||||
|
$duplicate['legal_sources']['duty-again'] = $duplicate['legal_sources']['duty'];
|
||||||
|
expect(fn () => app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $duplicate))->toThrow(HttpException::class);
|
||||||
|
$rules->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $rule->record_key,
|
||||||
|
'version' => 2, 'action' => 'withdraw', 'reason' => 'Synthetic withdrawal before native approval requires explicit review']);
|
||||||
|
expect(fn () => app(ImportEstimates::class)->approval($this->draft))->toThrow(HttpException::class);
|
||||||
|
expect(DB::table('budget_entries')->count())->toBe(0)->and($native->fresh()->snapshot['plan']['budget_amount_minor'])->toBe(10750);
|
||||||
|
});
|
||||||
|
|
||||||
test('native draft assumptions preserve unknowns originals and versions without financial or stock effects', function () {
|
test('native draft assumptions preserve unknowns originals and versions without financial or stock effects', function () {
|
||||||
$service = app(ImportEstimates::class);
|
$service = app(ImportEstimates::class);
|
||||||
$before = $this->draft->fresh()->getAttributes();
|
$before = $this->draft->fresh()->getAttributes();
|
||||||
|
|||||||
@@ -0,0 +1,84 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Services\ImportLegalAmounts;
|
||||||
|
use App\Services\ImportLegalEstimates;
|
||||||
|
use App\Services\ImportLegalRules;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
|
||||||
|
|
||||||
|
function legalCharge(array $overrides = []): array
|
||||||
|
{
|
||||||
|
return [...['key' => 'synthetic-duty', 'kind' => 'duty', 'label' => 'Synthetic duty', 'method' => 'ad_valorem',
|
||||||
|
'rate_percent' => '7.5', 'specific_minor' => null, 'quantity_unit' => null,
|
||||||
|
'basis_reference' => 'Synthetic customs-value basis; not an approved real legal rule'], ...$overrides];
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
|
||||||
|
Storage::fake('local');
|
||||||
|
$this->withoutVite();
|
||||||
|
$this->f = receiptFixture();
|
||||||
|
supplyGrant($this->f['issuer'], ['procurement', 'import_customs']);
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ad valorem specific and the greater-value method use exact decimals and documented units', function () {
|
||||||
|
$amounts = app(ImportLegalAmounts::class);
|
||||||
|
$base = ['value_minor' => 10001, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic explicit customs valuation'];
|
||||||
|
$result = $amounts->calculate([legalCharge()], ['synthetic-duty' => $base]);
|
||||||
|
expect($result['total_minor'])->toBe(750)->and($result['financial_effects'])->toBeFalse();
|
||||||
|
$specific = legalCharge(['method' => 'specific', 'rate_percent' => null, 'specific_minor' => 125, 'quantity_unit' => 'KG']);
|
||||||
|
expect($amounts->calculate([$specific], ['synthetic-duty' => [...$base, 'value_minor' => null, 'quantity' => '1.500', 'quantity_unit' => 'KG']])['total_minor'])->toBe(188);
|
||||||
|
$maximum = legalCharge(['method' => 'maximum', 'specific_minor' => 1000, 'quantity_unit' => 'KG']);
|
||||||
|
expect($amounts->calculate([$maximum], ['synthetic-duty' => [...$base, 'quantity' => '1.500', 'quantity_unit' => 'KG']])['total_minor'])->toBe(1500);
|
||||||
|
expect($amounts->calculate([$maximum], ['synthetic-duty' => [...$base, 'quantity' => '0.100', 'quantity_unit' => 'KG']])['total_minor'])->toBe(750);
|
||||||
|
expect(fn () => $amounts->calculate([$maximum], ['synthetic-duty' => [...$base, 'quantity' => '1.5', 'quantity_unit' => 'BOX']]))->toThrow(ValidationException::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unknown rates and missing bases never become zero while explicit non-application and zero rates remain distinct', function () {
|
||||||
|
$amounts = app(ImportLegalAmounts::class);
|
||||||
|
$unknown = legalCharge(['key' => 'unknown', 'method' => 'unknown', 'rate_percent' => null]);
|
||||||
|
$zero = legalCharge(['key' => 'zero', 'rate_percent' => '0']);
|
||||||
|
$notApplicable = legalCharge(['key' => 'not-applicable', 'method' => 'not_applicable', 'rate_percent' => null]);
|
||||||
|
$result = $amounts->calculate([$unknown, $zero, $notApplicable], ['zero' => ['value_minor' => 10000, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic declared base'],
|
||||||
|
'not-applicable' => ['value_minor' => null, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic documentary proof that all non-application prerequisites are met']]);
|
||||||
|
expect($result['complete'])->toBeFalse()->and($result['total_minor'])->toBeNull()->and($result['known_subtotal_minor'])->toBe(0)
|
||||||
|
->and(array_column($result['lines'], 'amount_minor'))->toBe([null, 0, 0]);
|
||||||
|
expect($amounts->calculate([], [])['total_minor'])->toBeNull();
|
||||||
|
expect($amounts->calculate([$notApplicable], [])['total_minor'])->toBeNull();
|
||||||
|
expect($amounts->calculate([legalCharge()], [])['total_minor'])->toBeNull();
|
||||||
|
expect(fn () => $amounts->definitions([legalCharge(['method' => 'unknown'])]))->toThrow(ValidationException::class);
|
||||||
|
expect(fn () => $amounts->calculate([legalCharge()], ['synthetic-duty' => ['value_minor' => 10000, 'quantity' => null, 'quantity_unit' => null, 'source' => null]]))->toThrow(ValidationException::class);
|
||||||
|
expect(fn () => $amounts->calculate([legalCharge(['rate_percent' => '10000'])], ['synthetic-duty' => ['value_minor' => 100000000000000, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic overflow boundary']]))->toThrow(ValidationException::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('native estimates freeze source bases and calculated results without reserving funds and reject stale versions', function () {
|
||||||
|
$rules = app(ImportLegalRules::class);
|
||||||
|
$draft = $rules->save($this->f['issuer'], importLegalQaInput(['charges' => [legalCharge()]]), importLegalQaFile());
|
||||||
|
$rule = $rules->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1,
|
||||||
|
'action' => 'publish', 'reason' => 'Synthetic explicit customs rate review for estimates']);
|
||||||
|
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'requisition_item_id' => $this->f['r']->items()->sole()->id,
|
||||||
|
'rule_id' => $rule->id, 'match_code' => '1234', 'origin' => 'Synthetic A', 'sector' => 'Synthetic sector', 'date' => '2026-11-27',
|
||||||
|
'bases' => ['synthetic-duty' => ['value_minor' => 10001, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic exact customs valuation']],
|
||||||
|
'reason' => 'Synthetic estimate with explicit source and no financial effects'];
|
||||||
|
$before = [DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()];
|
||||||
|
$url = '/requisicoes/'.$this->f['r']->id.'/base-legal/estimativas';
|
||||||
|
$this->post($url, $input)->assertRedirect();
|
||||||
|
$service = app(ImportLegalEstimates::class);
|
||||||
|
$record = $service->save($this->f['issuer'], $this->f['r'], $input);
|
||||||
|
expect($record->snapshot['result']['total_minor'])->toBe(750)->and($record->snapshot['legal_rule']['id'])->toBe($rule->id)
|
||||||
|
->and($service->save($this->f['issuer'], $this->f['r'], $input)->id)->toBe($record->id);
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
|
||||||
|
$second = $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'bases' => []]);
|
||||||
|
expect($second->state)->toBe('indeterminate')->and($second->snapshot['result']['total_minor'])->toBeNull()
|
||||||
|
->and($record->fresh()->snapshot['result']['total_minor'])->toBe(750)
|
||||||
|
->and($service->forPlan($this->f['r'], $record->id)->id)->toBe($record->id)
|
||||||
|
->and([DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()])->toBe($before);
|
||||||
|
});
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Enums\PurchasingRole;
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ImportEvidence;
|
||||||
|
use App\Services\ImportLegalRules;
|
||||||
|
use App\Services\ImportTariffCodes;
|
||||||
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||||
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
|
||||||
|
function legalRuleInput(array $overrides = []): array
|
||||||
|
{
|
||||||
|
return [...['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'action' => 'save',
|
||||||
|
'title' => 'Synthetic tariff rule', 'official_reference' => 'Synthetic official edition QA only',
|
||||||
|
'official_url' => 'https://example.test/official-qa.pdf', 'citation' => 'Synthetic article 1, page 2',
|
||||||
|
'valid_from' => '2026-01-01', 'valid_until' => '2026-12-31', 'match_code' => '1234', 'suggested_code' => '1234.56',
|
||||||
|
'origin_country' => 'Synthetic A', 'sector' => 'Synthetic sector', 'obligations' => 'Synthetic duty conditions; no real tax activated',
|
||||||
|
'document_types' => ['licence'], 'reason' => 'Synthetic legal configuration; not an approved real legal rule'], ...$overrides];
|
||||||
|
}
|
||||||
|
|
||||||
|
function legalRuleFile(): UploadedFile
|
||||||
|
{
|
||||||
|
return UploadedFile::fake()->createWithContent('source.pdf', "%PDF-1.4\nSynthetic official source for QA only\n%%EOF");
|
||||||
|
}
|
||||||
|
|
||||||
|
function publishLegalRule(User $actor, SupplyRecord $draft): SupplyRecord
|
||||||
|
{
|
||||||
|
return app(ImportLegalRules::class)->save($actor, ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key,
|
||||||
|
'version' => $draft->version, 'action' => 'publish', 'reason' => 'Synthetic customs review and publication of the prepared rule']);
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
config(['import-tariffs.qa_enabled' => true, 'import-legal.qa_enabled' => true]);
|
||||||
|
Storage::fake('local');
|
||||||
|
$this->withoutVite();
|
||||||
|
$this->f = receiptFixture();
|
||||||
|
supplyGrant($this->f['issuer'], ['procurement', 'import_customs']);
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legal publication preserves sources versions periods scope and previous publication during a draft revision', function () {
|
||||||
|
$service = app(ImportLegalRules::class);
|
||||||
|
$before = [DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()];
|
||||||
|
$input = legalRuleInput();
|
||||||
|
$file = legalRuleFile();
|
||||||
|
$draft = $service->save($this->f['issuer'], $input, $file);
|
||||||
|
expect($service->save($this->f['issuer'], $input, $file)->id)->toBe($draft->id);
|
||||||
|
$find = fn ($origin = 'Synthetic A', $sector = 'Synthetic sector', $date = '2026-11-27') => $service->suggestions($this->f['issuer'], $this->f['r'], '1234', $origin, $sector, $date);
|
||||||
|
expect($find())->toBe([]);
|
||||||
|
$published = publishLegalRule($this->f['issuer'], $draft);
|
||||||
|
expect($find()[0]['id'])->toBe($published->id)->and($find(''))->toBe([])->and($find('Synthetic A', ''))->toBe([])
|
||||||
|
->and($find('Synthetic A', 'Synthetic sector', '2027-01-01'))->toBe([])
|
||||||
|
->and($find('Synthetic A', 'Synthetic sector', '2026-01-01'))->toHaveCount(1)
|
||||||
|
->and($find('Synthetic A', 'Synthetic sector', '2026-12-31'))->toHaveCount(1);
|
||||||
|
$frozen = $service->freeze($published->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27');
|
||||||
|
$next = $service->save($this->f['issuer'], legalRuleInput(['record_key' => $published->record_key, 'version' => 2, 'suggested_code' => '1234.57']));
|
||||||
|
expect($find()[0]['id'])->toBe($published->id)->and($service->changed($frozen))->toBeFalse();
|
||||||
|
$new = publishLegalRule($this->f['issuer'], $next);
|
||||||
|
expect($service->changed($frozen))->toBeTrue()->and($frozen['data']['suggested_code'])->toBe('1234.56')
|
||||||
|
->and($published->fresh()->data['suggested_code'])->toBe('1234.56');
|
||||||
|
$service->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $new->record_key, 'version' => 4,
|
||||||
|
'action' => 'withdraw', 'reason' => 'Synthetic withdrawal without deleting original sources or applied decisions']);
|
||||||
|
expect($find())->toBe([])->and(Storage::disk('local')->allFiles())->toHaveCount(1)
|
||||||
|
->and([DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()])->toBe($before);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('buyer proposal freezes legal context and confirmation permits a reasoned deviation while changes require a current source', function () {
|
||||||
|
$service = app(ImportLegalRules::class);
|
||||||
|
$published = publishLegalRule($this->f['issuer'], $service->save($this->f['issuer'], legalRuleInput(), legalRuleFile()));
|
||||||
|
$tariffs = app(ImportTariffCodes::class);
|
||||||
|
$input = ['operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => 0, 'requisition_item_id' => $this->f['r']->items()->sole()->id,
|
||||||
|
'code' => '1234.56', 'source_reference' => $published->data['official_reference'].' — '.$published->data['citation'], 'legal_rule_id' => $published->id,
|
||||||
|
'legal_match_code' => '1234', 'legal_origin' => 'Synthetic A', 'legal_sector' => 'Synthetic sector', 'legal_date' => '2026-11-27',
|
||||||
|
'reason' => 'Synthetic buyer selection of a documented suggestion'];
|
||||||
|
$proposal = $tariffs->save($this->f['issuer'], $this->f['r'], $input);
|
||||||
|
$confirmed = $tariffs->save($this->f['issuer'], $this->f['r'], ['operation_key' => (string) Str::uuid(), 'action' => 'confirm', 'version' => 1,
|
||||||
|
'requisition_item_id' => $input['requisition_item_id'], 'code' => '1234.59', 'source_reference' => 'Synthetic technical classification reference',
|
||||||
|
'reason' => 'Synthetic buyer explains the documented deviation from the suggested code']);
|
||||||
|
expect($confirmed->data['deviation'])->toBeTrue()->and($confirmed->snapshot['legal_rule']['id'])->toBe($published->id)
|
||||||
|
->and($confirmed->snapshot['calculations_activated'])->toBeFalse()->and($proposal->fresh()->state)->toBe('proposed');
|
||||||
|
expect($tariffs->freezeForItems($this->f['issuer'], [$input['requisition_item_id']])[$input['requisition_item_id']]['legal_rule'])->toBe($confirmed->snapshot['legal_rule']);
|
||||||
|
$tariffs->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 2]);
|
||||||
|
$draft = $service->save($this->f['issuer'], legalRuleInput(['record_key' => $published->record_key, 'version' => 2]));
|
||||||
|
publishLegalRule($this->f['issuer'], $draft);
|
||||||
|
expect(fn () => $tariffs->save($this->f['issuer'], $this->f['r'], ['operation_key' => (string) Str::uuid(), 'action' => 'confirm', 'version' => 3,
|
||||||
|
'requisition_item_id' => $input['requisition_item_id'], 'code' => '1234.56', 'source_reference' => 'Synthetic source', 'reason' => 'Synthetic obsolete-source confirmation must fail']))->toThrow(HttpException::class);
|
||||||
|
expect($tariffs->workspace($this->f['issuer'], $this->f['r'])['latest']->first()->legal_changed)->toBeTrue();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legal management rejects stale operations foreign access revoked permissions and missing or altered original bytes', function () {
|
||||||
|
$service = app(ImportLegalRules::class);
|
||||||
|
$input = legalRuleInput();
|
||||||
|
$draft = $service->save($this->f['issuer'], $input, legalRuleFile());
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], [...$input, 'title' => 'Changed title'], legalRuleFile()))->toThrow(HttpException::class);
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], legalRuleInput(['record_key' => $draft->record_key])))->toThrow(HttpException::class);
|
||||||
|
$viewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Procurement]);
|
||||||
|
supplyGrant($viewer, ['procurement']);
|
||||||
|
$this->actingAs($viewer);
|
||||||
|
expect(fn () => publishLegalRule($viewer, $draft))->toThrow(HttpException::class);
|
||||||
|
$foreign = receiptFixture();
|
||||||
|
supplyGrant($foreign['issuer'], ['procurement', 'import_customs']);
|
||||||
|
$this->actingAs($foreign['issuer']);
|
||||||
|
expect(fn () => $service->source($foreign['issuer'], $foreign['r'], $draft->snapshot['source_id']))->toThrow(ModelNotFoundException::class);
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
$source = $service->source($this->f['issuer'], $this->f['r'], $draft->snapshot['source_id']);
|
||||||
|
Storage::disk('local')->put($source->snapshot['evidence']['path'], 'altered');
|
||||||
|
expect(fn () => publishLegalRule($this->f['issuer'], $draft))->toThrow(HttpException::class);
|
||||||
|
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->delete();
|
||||||
|
expect(fn () => $service->workspace($this->f['issuer'], $this->f['r']))->toThrow(HttpException::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('native legal forms keep sources private and allow source download and explicit human publication only', function () {
|
||||||
|
$url = '/requisicoes/'.$this->f['r']->id.'/base-legal';
|
||||||
|
$this->post($url, [...legalRuleInput(), 'file' => legalRuleFile()])->assertRedirect();
|
||||||
|
$draft = SupplyRecord::query()->where('kind', 'import_legal_rule')->sole();
|
||||||
|
$this->get($url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private');
|
||||||
|
$source = app(ImportLegalRules::class)->source($this->f['issuer'], $this->f['r'], $draft->snapshot['source_id']);
|
||||||
|
$download = $this->get($url.'/fontes/'.$source->id)->assertOk()->assertHeader('X-Content-Type-Options', 'nosniff');
|
||||||
|
expect($download->getContent())->toBe(app(ImportEvidence::class)->bytes($source));
|
||||||
|
$this->getJson($url.'?rules_page=0')->assertUnprocessable();
|
||||||
|
config(['import-legal.qa_enabled' => false]);
|
||||||
|
$this->get($url)->assertStatus(503);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('missing source alerts an already applied rule and changed source metadata requires a new original', function () {
|
||||||
|
$service = app(ImportLegalRules::class);
|
||||||
|
$draft = $service->save($this->f['issuer'], legalRuleInput(), legalRuleFile());
|
||||||
|
$published = publishLegalRule($this->f['issuer'], $draft);
|
||||||
|
$frozen = $service->freeze($published->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27');
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], legalRuleInput(['record_key' => $published->record_key, 'version' => 2,
|
||||||
|
'official_reference' => 'Different synthetic source without its original'])))->toThrow(HttpException::class);
|
||||||
|
$source = $service->source($this->f['issuer'], $this->f['r'], $frozen['source_id']);
|
||||||
|
Storage::disk('local')->delete($source->snapshot['evidence']['path']);
|
||||||
|
expect($service->changed($frozen))->toBeTrue();
|
||||||
|
expect(fn () => $service->freeze($published->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27'))->toThrow(HttpException::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an official source larger than a transactional attachment remains consultable without truncation', function () {
|
||||||
|
$bytes = "%PDF-1.4\n".str_repeat('Synthetic legal publication page bytes ', 70000)."\n%%EOF";
|
||||||
|
$service = app(ImportLegalRules::class);
|
||||||
|
$draft = $service->save($this->f['issuer'], legalRuleInput(), UploadedFile::fake()->createWithContent('large-source.pdf', $bytes));
|
||||||
|
$source = $service->source($this->f['issuer'], $this->f['r'], $draft->snapshot['source_id']);
|
||||||
|
expect(strlen($bytes))->toBeGreaterThan(2097152)->and(app(ImportEvidence::class)->bytes($source))->toBe($bytes);
|
||||||
|
expect(publishLegalRule($this->f['issuer'], $draft)->snapshot['source_sha256'])->toBe(hash('sha256', $bytes));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a shared official source is independently consultable and reused without inventing a code or publishing a rule', function () {
|
||||||
|
$service = app(ImportLegalRules::class);
|
||||||
|
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'action' => 'source',
|
||||||
|
'official_reference' => 'Synthetic complete official journal; no rule or inferred rate',
|
||||||
|
'reason' => 'Retain the synthetic official publication independently of its later use'];
|
||||||
|
$source = $service->save($this->f['issuer'], $input, legalRuleFile());
|
||||||
|
expect($service->save($this->f['issuer'], $input, legalRuleFile())->id)->toBe($source->id)
|
||||||
|
->and($source->kind)->toBe('import_legal_source')->and($source->data['official_url'])->toBeNull()
|
||||||
|
->and(SupplyRecord::query()->where('kind', 'import_legal_rule')->count())->toBe(0);
|
||||||
|
$rule = $service->save($this->f['issuer'], legalRuleInput(['source_id' => $source->id,
|
||||||
|
'official_reference' => $source->data['official_reference'], 'official_url' => null]));
|
||||||
|
expect($rule->snapshot['source_id'])->toBe($source->id)->and(Storage::disk('local')->allFiles())->toHaveCount(1)
|
||||||
|
->and($service->workspace($this->f['issuer'], $this->f['r'])['sources']->total())->toBe(1);
|
||||||
|
$other = $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'official_reference' => 'Another synthetic official source'], legalRuleFile());
|
||||||
|
expect(fn () => $service->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $rule->record_key, 'version' => 1,
|
||||||
|
'action' => 'publish', 'source_id' => $other->id, 'reason' => 'A publication decision cannot silently replace the prepared original']))->toThrow(HttpException::class);
|
||||||
|
expect(publishLegalRule($this->f['issuer'], $rule)->snapshot['source_id'])->toBe($source->id);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('publishing a future period preserves the earlier applicable period without resurrecting an expired replacement', function () {
|
||||||
|
$service = app(ImportLegalRules::class);
|
||||||
|
$first = publishLegalRule($this->f['issuer'], $service->save($this->f['issuer'], legalRuleInput(), legalRuleFile()));
|
||||||
|
$future = publishLegalRule($this->f['issuer'], $service->save($this->f['issuer'], legalRuleInput(['record_key' => $first->record_key, 'version' => 2,
|
||||||
|
'valid_from' => '2027-01-01', 'valid_until' => '2027-06-30', 'suggested_code' => '1234.57'])));
|
||||||
|
$find = fn ($date) => $service->suggestions($this->f['issuer'], $this->f['r'], '1234', 'Synthetic A', 'Synthetic sector', $date);
|
||||||
|
expect($find('2026-11-27')[0]['id'])->toBe($first->id)->and($find('2027-01-01')[0]['id'])->toBe($future->id)
|
||||||
|
->and($find('2027-07-01'))->toBe([])
|
||||||
|
->and($service->freeze($first->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27')['id'])->toBe($first->id);
|
||||||
|
});
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Services\ImportBankSupport;
|
||||||
|
use App\Services\ImportDossier;
|
||||||
|
use App\Services\ImportLegalRules;
|
||||||
|
use App\Services\ImportReadiness;
|
||||||
|
use App\Services\InventoryLots;
|
||||||
|
use App\Services\ReceiptWorkflow;
|
||||||
|
use App\Services\SupplyPlanning;
|
||||||
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Inertia\Testing\AssertableInertia as Assert;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
|
||||||
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
|
||||||
|
require_once __DIR__.'/../Support/ImportBankQaFixture.php';
|
||||||
|
|
||||||
|
beforeEach(function () {
|
||||||
|
config(['import-readiness.qa_enabled' => true, 'import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true,
|
||||||
|
'import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
|
||||||
|
Storage::fake('local');
|
||||||
|
$this->withoutVite();
|
||||||
|
$this->f = receiptFixture();
|
||||||
|
supplyGrant($this->f['issuer'], ['procurement', 'import_prepare', 'import_customs']);
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
$this->import = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput([
|
||||||
|
'purchase_order_id' => $this->f['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Synthetic readiness jurisdiction',
|
||||||
|
'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic regime',
|
||||||
|
'expected_usable_on' => today()->subDay()->toDateString()]));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('current import alerts distinguish unknown requirements and the expected receipt from customs release without side effects', function () {
|
||||||
|
$service = app(ImportReadiness::class);
|
||||||
|
$before = [];
|
||||||
|
foreach (['supply_records', 'audit_logs', 'budget_entries', 'stock_movements', 'invoices', 'workflow_notices'] as $table) {
|
||||||
|
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
||||||
|
}
|
||||||
|
$workspace = $service->workspace($this->f['issuer'], $this->import);
|
||||||
|
expect(array_column($workspace['alerts'], 'key'))->toContain('expected-due', 'classification-unknown', 'parties-unknown', 'bank-unknown')
|
||||||
|
->and($workspace['complete'])->toBeTrue()->and($workspace['financialEffects'])->toBeFalse()->and($workspace['automaticNotifications'])->toBeFalse();
|
||||||
|
foreach ($before as $table => $rows) {
|
||||||
|
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
|
||||||
|
}
|
||||||
|
$planning = app(SupplyPlanning::class);
|
||||||
|
$transit = $planning->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic transit', 'event_date' => today()->toDateString()], 'transit', $this->import));
|
||||||
|
$arrived = $planning->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic arrival', 'event_date' => today()->toDateString()], 'arrive', $transit));
|
||||||
|
expect(array_column($service->workspace($this->f['issuer'], $arrived)['alerts'], 'key'))->toContain('customs-pending');
|
||||||
|
supplyGrant($this->f['receiver'], ['warehouse', 'import_customs', 'import_read']);
|
||||||
|
$this->actingAs($this->f['receiver']);
|
||||||
|
$released = $planning->save($this->f['receiver'], 'import', supplyInput(['evidence' => 'Synthetic independent release', 'event_date' => today()->toDateString()], 'release', $arrived));
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
expect(array_column($service->workspace($this->f['issuer'], $released)['alerts'], 'key'))->toContain('expected-due')->not->toContain('customs-pending');
|
||||||
|
$this->actingAs($this->f['receiver']);
|
||||||
|
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
expect(array_column($service->workspace($this->f['issuer'], $released)['alerts'], 'key'))->not->toContain('expected-due');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('document requirements come from the frozen rule and missing or altered evidence reopens the live alert', function () {
|
||||||
|
$legal = app(ImportLegalRules::class);
|
||||||
|
$draft = $legal->save($this->f['issuer'], importLegalQaInput(), importLegalQaFile());
|
||||||
|
$published = $legal->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1,
|
||||||
|
'action' => 'publish', 'reason' => 'Synthetic customs source publication for current alerts']);
|
||||||
|
$frozen = $legal->freeze($published->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27');
|
||||||
|
// Construct an issued-order fixture; no production order is rewritten.
|
||||||
|
DB::table('purchase_orders')->where('id', $this->f['order']->id)->update(['snapshot' => json_encode([...$this->f['order']->snapshot,
|
||||||
|
'import_tariffs' => [['record_id' => 999, 'item' => ['description' => 'Synthetic classified item'],
|
||||||
|
'data' => ['requisition_id' => $this->f['r']->id], 'legal_rule' => $frozen]]], JSON_THROW_ON_ERROR)]);
|
||||||
|
$service = app(ImportReadiness::class);
|
||||||
|
expect(array_column($service->workspace($this->f['issuer'], $this->import)['alerts'], 'key'))->toContain('required-licence');
|
||||||
|
$document = app(ImportDossier::class)->record($this->f['issuer'], $this->import, ['operation_key' => (string) Str::uuid(), 'type' => 'licence',
|
||||||
|
'reference' => 'LICENCE-QA', 'issuer_reference' => 'Synthetic issuer', 'reason' => 'Synthetic licence for documentary readiness'],
|
||||||
|
UploadedFile::fake()->createWithContent('licence.pdf', "%PDF-1.4\nSynthetic licence\n%%EOF"));
|
||||||
|
expect(array_column($service->workspace($this->f['issuer'], $this->import)['alerts'], 'key'))->not->toContain('required-licence');
|
||||||
|
Storage::disk('local')->put($document->snapshot['evidence']['path'], 'altered');
|
||||||
|
expect(array_column($service->workspace($this->f['issuer'], $this->import)['alerts'], 'key'))->toContain('required-licence', 'document-'.$document->id);
|
||||||
|
$legal->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $published->record_key, 'version' => 2,
|
||||||
|
'action' => 'withdraw', 'reason' => 'Synthetic withdrawal alerts the existing decision without deleting it']);
|
||||||
|
expect(array_column($service->workspace($this->f['issuer'], $this->import)['alerts'], 'key'))->toContain('legal-changed-999');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bank pending alerts reuse the native report and disappear after dated documentary delivery', function () {
|
||||||
|
$fixture = importBankQaFixture($this->f['issuer'], $this->import);
|
||||||
|
$bank = app(ImportBankSupport::class);
|
||||||
|
$first = $bank->save($this->f['issuer'], $this->import, $fixture['input']);
|
||||||
|
$service = app(ImportReadiness::class);
|
||||||
|
$bankAlerts = fn () => array_values(array_filter($service->workspace($this->f['issuer'], $this->import)['alerts'], fn ($alert) => $alert['category'] === 'Suporte bancário'));
|
||||||
|
expect($bankAlerts())->not->toBeEmpty();
|
||||||
|
$bank->save($this->f['issuer'], $this->import, [...$fixture['input'], 'operation_key' => (string) Str::uuid(),
|
||||||
|
'record_key' => $first->record_key, 'version' => 1, 'submission_document_id' => $fixture['documents']['delivery']->id,
|
||||||
|
'submitted_on' => today()->toDateString(), 'submission_basis' => 'Synthetic documentary delivery evidence']);
|
||||||
|
expect($bankAlerts())->toBe([]);
|
||||||
|
config(['import-bank-support.qa_enabled' => false]);
|
||||||
|
$workspace = $service->workspace($this->f['issuer'], $this->import);
|
||||||
|
expect($workspace['complete'])->toBeFalse()->and(array_column($workspace['alerts'], 'key'))->toContain('bank-unavailable');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('native follow-up revalidates current identity company context versions and private response headers', function () {
|
||||||
|
$url = '/compras/importacoes/'.$this->import->id.'/acompanhamento';
|
||||||
|
$this->get($url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
|
||||||
|
->assertInertia(fn (Assert $page) => $page->component('supply/import-readiness')->where('automaticNotifications', false));
|
||||||
|
$foreign = receiptFixture();
|
||||||
|
supplyGrant($foreign['issuer'], ['procurement', 'import_read']);
|
||||||
|
$this->actingAs($foreign['issuer'])->get($url)->assertNotFound();
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->delete();
|
||||||
|
expect(fn () => app(ImportReadiness::class)->workspace($this->f['issuer'], $this->import))->toThrow(HttpException::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accepted receipt in quarantine remains an availability alert until native independent quality release', function () {
|
||||||
|
$planning = app(SupplyPlanning::class);
|
||||||
|
$transit = $planning->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic transit', 'event_date' => today()->toDateString()], 'transit', $this->import));
|
||||||
|
$arrived = $planning->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic arrival', 'event_date' => today()->toDateString()], 'arrive', $transit));
|
||||||
|
supplyGrant($this->f['issuer'], ['inventory_lot_prepare']);
|
||||||
|
$lots = app(InventoryLots::class);
|
||||||
|
$setup = $lots->save($this->f['issuer'], supplyInput(['stock_item_id' => $this->f['stock']->id, 'warehouse_id' => $this->f['warehouse']->id,
|
||||||
|
'requires_expiry' => false, 'minimum_remaining_days' => 0, 'lots' => [], 'quarantine_on_receipt' => true], 'prepare'));
|
||||||
|
supplyGrant($this->f['receiver'], ['warehouse', 'import_customs', 'inventory_lot_review']);
|
||||||
|
$this->actingAs($this->f['receiver']);
|
||||||
|
$lots->save($this->f['receiver'], supplyInput([], 'activate', $setup));
|
||||||
|
$released = $planning->save($this->f['receiver'], 'import', supplyInput(['evidence' => 'Synthetic independent release', 'event_date' => today()->toDateString()], 'release', $arrived));
|
||||||
|
$input = receiptPayload($this->f, '1.000');
|
||||||
|
$input['items'][0]['lots'] = [['code' => 'QA-LOT', 'no_expiry' => true]];
|
||||||
|
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], $input);
|
||||||
|
$lot = $lots->context($this->f['stock']->id, $this->f['warehouse']->id)['lots'][0];
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
$alerts = app(ImportReadiness::class)->workspace($this->f['issuer'], $released)['alerts'];
|
||||||
|
expect(array_column($alerts, 'key'))->toContain('stock-held-'.$lot['id'].'-'.$this->f['warehouse']->id);
|
||||||
|
supplyGrant($this->f['otherReceiver'], ['warehouse', 'inventory_lot_release']);
|
||||||
|
$this->actingAs($this->f['otherReceiver']);
|
||||||
|
$lots->save($this->f['otherReceiver'], supplyInput(['lot_id' => $lot['id'], 'warehouse_id' => $this->f['warehouse']->id,
|
||||||
|
'state_version' => $lot['state_version']], 'release', SupplyRecord::query()->findOrFail($lot['metadata_id'])));
|
||||||
|
$this->actingAs($this->f['issuer']);
|
||||||
|
expect(array_column(app(ImportReadiness::class)->workspace($this->f['issuer'], $released)['alerts'], 'key'))->not->toContain('stock-held-'.$lot['id'].'-'.$this->f['warehouse']->id);
|
||||||
|
});
|
||||||
@@ -31,6 +31,8 @@ use App\Models\User;
|
|||||||
use App\Models\Warehouse;
|
use App\Models\Warehouse;
|
||||||
use App\Services\AgreementOrderLimits;
|
use App\Services\AgreementOrderLimits;
|
||||||
use App\Services\BudgetWorkflow;
|
use App\Services\BudgetWorkflow;
|
||||||
|
use App\Services\CapitalAssignments;
|
||||||
|
use App\Services\CapitalRegister;
|
||||||
use App\Services\CommonBudget;
|
use App\Services\CommonBudget;
|
||||||
use App\Services\ComparisonPolicy;
|
use App\Services\ComparisonPolicy;
|
||||||
use App\Services\ConflictGuard;
|
use App\Services\ConflictGuard;
|
||||||
@@ -71,6 +73,67 @@ require_once __DIR__.'/../Support/SupplyFixture.php';
|
|||||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||||
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
|
||||||
|
|
||||||
|
function nativeCapitalAssignment(object $test): array
|
||||||
|
{
|
||||||
|
config(['capital-register.qa_enabled' => true]);
|
||||||
|
$test->actingAs($test->buyer);
|
||||||
|
$input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'type' => 'project',
|
||||||
|
'code' => 'PRJ-NATIVE-QA', 'name' => 'Projecto sintético da ordem', 'department_id' => $test->department->id,
|
||||||
|
'equipment_id' => null, 'reference' => 'Documento sintético de investimento', 'state' => 'active', 'reason' => 'Cadastro estritamente sintético da ligação à ordem'];
|
||||||
|
$source = app(CapitalRegister::class)->save($test->buyer, $input);
|
||||||
|
// Extend the pre-approved synthetic fixture with a choice made while it was a draft.
|
||||||
|
$test->r->update(['status' => 'draft']);
|
||||||
|
$test->actingAs($test->owner);
|
||||||
|
$assignment = app(CapitalAssignments::class)->save($test->owner, $test->r, ['operation_key' => (string) Str::uuid(),
|
||||||
|
'version' => 0, 'item_id' => $test->item->id, 'capital_id' => $source->id, 'reason' => 'Destino documental escolhido pelo requisitante sintético']);
|
||||||
|
$test->r->update(['status' => 'approved']);
|
||||||
|
$test->actingAs($test->buyer);
|
||||||
|
|
||||||
|
return [$source, $assignment, $input];
|
||||||
|
}
|
||||||
|
|
||||||
|
test('native order preserves the capital destination and print after the independent register is archived', function () {
|
||||||
|
[$source, $assignment, $input] = nativeCapitalAssignment($this);
|
||||||
|
$award = selectPurchaseAward($this);
|
||||||
|
$order = issuePurchaseOrder($this, $award);
|
||||||
|
expect($order->snapshot['capital_assignments'][$this->item->id]['id'])->toBe($assignment->id)
|
||||||
|
->and($order->total_minor)->toBe($award->total_minor);
|
||||||
|
app(CapitalRegister::class)->save($this->buyer, [...$input, 'operation_key' => (string) Str::uuid(),
|
||||||
|
'record_key' => $source->record_key, 'version' => 1, 'name' => 'Nome posterior ao documento', 'state' => 'archived']);
|
||||||
|
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('PRJ-NATIVE-QA')->assertSee('Projecto sintético da ordem')->assertDontSee('Nome posterior ao documento');
|
||||||
|
expect($order->fresh()->snapshot['capital_assignments'][$this->item->id]['snapshot']['source']['version'])->toBe(1);
|
||||||
|
$this->withoutVite();
|
||||||
|
$this->get('/projectos-imobilizado?history='.$source->record_key)->assertOk()
|
||||||
|
->assertInertia(fn (Assert $page) => $page->has('trace.orders.data', 1)->where('trace.orders.data.0.order_number', $order->number)->has('trace.receipts.data', 0));
|
||||||
|
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
|
||||||
|
$this->actingAs($receiver);
|
||||||
|
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'CAPITAL-QA', 'name' => 'Armazém sintético']);
|
||||||
|
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'CAPITAL-QA', 'name' => 'Artigo sintético', 'unit' => 'un']);
|
||||||
|
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'CAPITAL-NATIVE-RECEIPT',
|
||||||
|
'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id,
|
||||||
|
'items' => [['purchase_order_item_id' => $order->items()->sole()->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]]);
|
||||||
|
$this->actingAs($this->buyer);
|
||||||
|
$before = DB::table('stock_movements')->get()->toJson();
|
||||||
|
$this->get('/projectos-imobilizado?history='.$source->record_key)->assertOk()
|
||||||
|
->assertInertia(fn (Assert $page) => $page->has('trace.receipts.data', 1)->where('trace.receipts.data.0.receipt_id', $receipt->id)
|
||||||
|
->where('trace.receipts.data.0.accepted_quantity', '1.000')->where('trace.receipts.data.0.returned_quantity', '0.000')->where('trace.receipts.data.0.reversed', false));
|
||||||
|
expect(DB::table('stock_movements')->get()->toJson())->toBe($before);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('native partial order freezes the same explicit capital origin without changing its financial allocation', function () {
|
||||||
|
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
||||||
|
$this->markTestSkipped('Select the approved isolated-QA common source for native order parts.');
|
||||||
|
}
|
||||||
|
[, $assignment] = nativeCapitalAssignment($this);
|
||||||
|
$award = nativeOrderPartsAward($this);
|
||||||
|
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
|
||||||
|
$this->actingAs($this->buyer);
|
||||||
|
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, $input);
|
||||||
|
expect($order->snapshot['capital_assignments'][$this->item->id]['id'])->toBe($assignment->id)
|
||||||
|
->and($order->total_minor)->toBe(4000)->and(DB::table('budget_order_commands')->count())->toBe(1);
|
||||||
|
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('PRJ-NATIVE-QA');
|
||||||
|
});
|
||||||
|
|
||||||
test('confirmed import classifications freeze in a newly issued native order and survive later proposals', function () {
|
test('confirmed import classifications freeze in a newly issued native order and survive later proposals', function () {
|
||||||
config(['import-tariffs.qa_enabled' => true]);
|
config(['import-tariffs.qa_enabled' => true]);
|
||||||
$tariffs = app(ImportTariffCodes::class);
|
$tariffs = app(ImportTariffCodes::class);
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Models\SupplyRecord;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Services\ImportDossier;
|
||||||
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
/** Synthetic originals only; caller supplies an authorised native import-preparation actor.
|
||||||
|
* @return array{documents:array<string,SupplyRecord>,input:array<string,mixed>}
|
||||||
|
*/
|
||||||
|
function importBankQaFixture(User $actor, SupplyRecord $import): array
|
||||||
|
{
|
||||||
|
$db = DB::connection();
|
||||||
|
if (! 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())))) {
|
||||||
|
throw new LogicException('Bank evidence fixtures require isolated QA.');
|
||||||
|
}
|
||||||
|
$documents = [];
|
||||||
|
foreach (['term' => 'bank_commitment', 'declaration' => 'customs_declaration', 'invoice' => 'commercial_invoice', 'delivery' => 'bank_support'] as $key => $type) {
|
||||||
|
$reference = 'BANK-QA-'.$key.'-'.Str::random(8);
|
||||||
|
$documents[$key] = app(ImportDossier::class)->record($actor, $import, ['operation_key' => (string) Str::uuid(), 'type' => $type,
|
||||||
|
'reference' => $reference, 'issuer_reference' => 'Synthetic bank evidence issuer', 'issued_on' => today()->toDateString(),
|
||||||
|
'reason' => 'Original estritamente sintético de suporte documental bancário'],
|
||||||
|
UploadedFile::fake()->createWithContent('bank-'.$key.'.pdf', "%PDF-1.4\nSynthetic evidence ".$reference."\n%%EOF"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ['documents' => $documents, 'input' => ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
|
||||||
|
'commitment_document_id' => $documents['term']->id, 'declaration_document_id' => $documents['declaration']->id,
|
||||||
|
'support_document_ids' => [$documents['invoice']->id], 'requirements_known' => true, 'required_support_types' => ['commercial_invoice'],
|
||||||
|
'required_support_counts' => ['commercial_invoice' => 1], 'requirements_basis' => 'Explicit synthetic bank letter requests one invoice',
|
||||||
|
'submission_document_id' => null, 'submission_basis' => null, 'submitted_on' => null,
|
||||||
|
'due_on' => today()->toDateString(), 'deadline_basis' => 'Explicit synthetic bank letter deadline', 'reason' => 'Acompanhamento bancário exclusivamente sintético']];
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Http\UploadedFile;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
|
||||||
|
/** Synthetic rules only. Never seed official rates or a customer's configuration. */
|
||||||
|
function importLegalQaInput(array $overrides = []): array
|
||||||
|
{
|
||||||
|
$db = DB::connection();
|
||||||
|
if (! 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())))) {
|
||||||
|
throw new LogicException('Legal fixtures require isolated QA.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'action' => 'save',
|
||||||
|
'title' => 'Synthetic tariff rule', 'official_reference' => 'Synthetic official edition QA only',
|
||||||
|
'official_url' => 'https://example.test/official-qa.pdf', 'citation' => 'Synthetic article 1, page 2',
|
||||||
|
'valid_from' => '2026-01-01', 'valid_until' => '2026-12-31', 'match_code' => '1234', 'suggested_code' => '1234.56',
|
||||||
|
'origin_country' => 'Synthetic A', 'sector' => 'Synthetic sector', 'obligations' => 'Synthetic conditions only; no real tax activated',
|
||||||
|
'document_types' => ['licence'], 'reason' => 'Synthetic legal configuration; not an approved real legal rule'], ...$overrides];
|
||||||
|
}
|
||||||
|
|
||||||
|
function importLegalQaFile(): UploadedFile
|
||||||
|
{
|
||||||
|
return UploadedFile::fake()->createWithContent('source.pdf', "%PDF-1.4\nSynthetic official source for QA only\n%%EOF");
|
||||||
|
}
|
||||||
|
|
||||||
|
function importLegalQaCharge(): array
|
||||||
|
{
|
||||||
|
return ['key' => 'synthetic-duty', 'kind' => 'duty', 'label' => 'Synthetic duty', 'method' => 'ad_valorem',
|
||||||
|
'rate_percent' => '7.5', 'specific_minor' => null, 'quantity_unit' => null,
|
||||||
|
'basis_reference' => 'Synthetic explicit customs valuation; no real rate configured'];
|
||||||
|
}
|
||||||
|
|
||||||
|
function importLegalQaAmountInput(int $itemId, int $ruleId): array
|
||||||
|
{
|
||||||
|
return ['operation_key' => (string) Str::uuid(), 'version' => 0, 'requisition_item_id' => $itemId, 'rule_id' => $ruleId,
|
||||||
|
'match_code' => '1234', 'origin' => 'Synthetic A', 'sector' => 'Synthetic sector', 'date' => '2026-11-27',
|
||||||
|
'bases' => ['synthetic-duty' => ['value_minor' => 10001, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic exact declared valuation']],
|
||||||
|
'reason' => 'Synthetic legal charge estimate without financial or stock effects'];
|
||||||
|
}
|
||||||
@@ -43,12 +43,12 @@ function landedQaReceiptsVerified(array $command, string $output): bool
|
|||||||
&& (! in_array($mode, ['race-estimate', 'race-estimate-reconcile'], true) || $contains(fn ($row) => ($row['old_estimate_runtime_rejected'] ?? false) === true
|
&& (! in_array($mode, ['race-estimate', 'race-estimate-reconcile'], true) || $contains(fn ($row) => ($row['old_estimate_runtime_rejected'] ?? false) === true
|
||||||
&& ($row['runtime_landed_version'] ?? null) === 'COMMON-BUDGET-LANDED-COST-QA-v2' && ($row['status'] ?? null) === 503));
|
&& ($row['runtime_landed_version'] ?? null) === 'COMMON-BUDGET-LANDED-COST-QA-v2' && ($row['status'] ?? null) === 503));
|
||||||
}
|
}
|
||||||
if (in_array($mode, ['race-dossier', 'race-party'], true)) {
|
if (in_array($mode, ['race-dossier', 'race-party', 'race-bank', 'race-legal', 'race-legal-amount', 'race-capital'], true)) {
|
||||||
foreach (['same_operation', 'same_version'] as $scenario) {
|
foreach (['same_operation', 'same_version'] as $scenario) {
|
||||||
$matches = array_values(array_filter($records, fn ($row) => ($row['scenario'] ?? null) === $scenario));
|
$matches = array_values(array_filter($records, fn ($row) => ($row['scenario'] ?? null) === $scenario));
|
||||||
if (count($matches) !== 1 || ($matches[0]['blocked_writers_observed'] ?? 0) < 2
|
if (count($matches) !== 1 || ($matches[0]['blocked_writers_observed'] ?? 0) < 2
|
||||||
|| ($matches[0]['documents_created'] ?? 0) !== 1 || ($matches[0]['audits'] ?? 0) !== 1
|
|| ($matches[0]['documents_created'] ?? 0) !== 1 || ($matches[0]['audits'] ?? 0) !== 1
|
||||||
|| ($matches[0]['files_created'] ?? -1) !== ($mode === 'race-party' ? 0 : 1) || ($matches[0]['all_originals_verified'] ?? false) !== true
|
|| ($matches[0]['files_created'] ?? -1) !== (in_array($mode, ['race-party', 'race-bank', 'race-legal-amount', 'race-capital'], true) ? 0 : 1) || ($matches[0]['all_originals_verified'] ?? false) !== true
|
||||||
|| ($matches[0]['statuses'] ?? null) !== ($scenario === 'same_operation' ? [200, 200] : [200, 409])) {
|
|| ($matches[0]['statuses'] ?? null) !== ($scenario === 'same_operation' ? [200, 200] : [200, 409])) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -56,17 +56,41 @@ function landedQaReceiptsVerified(array $command, string $output): bool
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (in_array($mode, ['landed-costs', 'import-estimates'], true)) {
|
if (in_array($mode, ['landed-costs', 'import-estimates', 'import-bank-support', 'import-legal', 'import-legal-amount'], true)) {
|
||||||
return ($mode !== 'import-estimates' || $contains(fn ($row) => ($row['estimate_source_remainder_restored'] ?? null) === 1000 && ($row['estimate_original_replay_without_effects'] ?? false) === true))
|
return ($mode === 'landed-costs' || $contains(fn ($row) => ($row['estimate_source_remainder_restored'] ?? null) === 1000 && ($row['estimate_original_replay_without_effects'] ?? false) === true))
|
||||||
|
&& ($mode !== 'import-legal-amount' || $contains(fn ($row) => ($row['legal_amount_minor_restored'] ?? null) === 750 && ($row['legal_amount_replay_without_effects'] ?? false) === true
|
||||||
|
&& ($row['native_legal_plan_total_minor'] ?? null) === 10750 && ($row['native_legal_plan_source_restored'] ?? false) === true && ($row['native_legal_plan_replay_without_effects'] ?? false) === true))
|
||||||
|
&& (! in_array($mode, ['import-legal', 'import-legal-amount'], true) || $contains(fn ($row) => ($row['legal_source_restored'] ?? false) === true && ($row['legal_published_version_restored'] ?? false) === true
|
||||||
|
&& ($row['legal_buyer_context_restored'] ?? false) === true && ($row['legal_replay_without_effects'] ?? false) === true))
|
||||||
|
&& (! in_array($mode, ['import-bank-support', 'import-legal', 'import-legal-amount'], true) || $contains(fn ($row) => ($row['bank_support_versions_restored'] ?? null) === 2
|
||||||
|
&& ($row['bank_support_relationships_restored'] ?? false) === true && ($row['bank_support_replay_without_effects'] ?? false) === true))
|
||||||
&& $contains(fn ($row) => ($row['post_extension_restore_all_tables_equal'] ?? false) === true
|
&& $contains(fn ($row) => ($row['post_extension_restore_all_tables_equal'] ?? false) === true
|
||||||
&& ($row['recovered_operation_replay_no_effects'] ?? false) === true && ($row['pre_extension_schema_data_balance_restored'] ?? false) === true)
|
&& ($row['recovered_operation_replay_no_effects'] ?? false) === true && ($row['pre_extension_schema_data_balance_restored'] ?? false) === true)
|
||||||
&& $contains(fn ($row) => ($row['private_original_versions_restored'] ?? 0) === 6 && ($row['typed_dossier_versions_restored'] ?? 0) === 4
|
&& $contains(fn ($row) => ($row['private_original_versions_restored'] ?? 0) === (in_array($mode, ['import-legal', 'import-legal-amount'], true) ? 11 : ($mode === 'import-bank-support' ? 10 : 6)) && ($row['typed_dossier_versions_restored'] ?? 0) === (in_array($mode, ['import-bank-support', 'import-legal', 'import-legal-amount'], true) ? 8 : 4)
|
||||||
&& ($row['selected_party_versions_restored'] ?? 0) === 2
|
&& ($row['selected_party_versions_restored'] ?? 0) === 2
|
||||||
&& ($row['source_loss_detected'] ?? false) === true
|
&& ($row['source_loss_detected'] ?? false) === true
|
||||||
&& ($row['separate_private_root_restored'] ?? false) === true && ($row['native_authorized_evidence_resolved'] ?? false) === true)
|
&& ($row['separate_private_root_restored'] ?? false) === true && ($row['native_authorized_evidence_resolved'] ?? false) === true)
|
||||||
&& $contains(fn ($row) => ($row['isolated_restore_removed'] ?? false) === true);
|
&& $contains(fn ($row) => ($row['isolated_restore_removed'] ?? false) === true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (in_array($mode, ['legal-http', 'legal-review'], true)) {
|
||||||
|
return $contains(fn ($row) => ($row['native_legal_http_login'] ?? false) === true && ($row['csrf_required'] ?? false) === true
|
||||||
|
&& ($row['large_multipart_upload_bytes'] ?? 0) > 2097152 && ($row['original_unchanged'] ?? false) === true
|
||||||
|
&& ($row['exact_native_download'] ?? false) === true && ($row['one_source_one_audit_after_replay'] ?? false) === true
|
||||||
|
&& ($row['guest_status'] ?? null) === 401 && ($row['revoked_status'] ?? null) === 403 && ($row['rules_published'] ?? null) === 0
|
||||||
|
&& ($row['financial_stock_unchanged'] ?? false) === true && ($row['global_php_config_unchanged'] ?? false) === true
|
||||||
|
&& ($row['private_http_server_stopped'] ?? false) === true && ($row['private_http_root_removed'] ?? false) === true);
|
||||||
|
}
|
||||||
|
if ($mode === 'corpus') {
|
||||||
|
return $contains(fn ($row) => ($row['shared_corpus_files_inventoried'] ?? 0) > 0 && count($row['real_official_sources_prepared'] ?? []) === 4
|
||||||
|
&& is_string($row['inventory_metadata_sha256'] ?? null) && preg_match('/^[a-f0-9]{64}$/D', $row['inventory_metadata_sha256']) === 1
|
||||||
|
&& count(array_filter($row['real_official_sources_prepared'], fn ($source) => is_string($source['sha256'] ?? null)
|
||||||
|
&& preg_match('/^[a-f0-9]{64}$/D', $source['sha256']) === 1 && ($source['bytes'] ?? 0) > 0
|
||||||
|
&& ($source['native_authorized_download_verified'] ?? false) === true)) === 4
|
||||||
|
&& ($row['rules_published'] ?? null) === 0 && ($row['originals_unchanged'] ?? false) === true
|
||||||
|
&& ($row['financial_and_stock_unchanged'] ?? false) === true && ($row['synthetic_qa_organization_only'] ?? false) === true);
|
||||||
|
}
|
||||||
|
|
||||||
return $mode === 'pest' && $contains(fn ($row) => ($row['tool'] ?? null) === 'pest' && ($row['result'] ?? null) === 'passed'
|
return $mode === 'pest' && $contains(fn ($row) => ($row['tool'] ?? null) === 'pest' && ($row['result'] ?? null) === 'passed'
|
||||||
&& ($row['tests'] ?? 0) > 0 && ($row['passed'] ?? 0) === $row['tests']);
|
&& ($row['tests'] ?? 0) > 0 && ($row['passed'] ?? 0) === $row['tests']);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
// Private HTTP composition only. Real Fortify login and CSRF middleware remain in the native routes.
|
||||||
|
$root = realpath(getenv('SGC_LEGAL_HTTP_QA_ROOT') ?: '');
|
||||||
|
$database = getenv('DB_DATABASE') ?: '';
|
||||||
|
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
|
||||||
|
if (getenv('APP_ENV') !== 'testing' || getenv('DB_HOST') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)
|
||||||
|
|| ($_SERVER['REMOTE_ADDR'] ?? '') !== '127.0.0.1' || ($_SERVER['SERVER_PORT'] ?? '') != getenv('SGC_LEGAL_HTTP_QA_PORT')
|
||||||
|
|| $root === false || $boundary === false || str_replace('\\', '/', $root) !== str_replace('\\', '/', $boundary).'/legal-http-'.$database) {
|
||||||
|
http_response_code(503);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
require __DIR__.'/../../vendor/autoload.php';
|
||||||
|
$public = $root.'/public';
|
||||||
|
$requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
|
||||||
|
$asset = realpath($public.'/'.ltrim(rawurldecode($requestPath), '/'));
|
||||||
|
$types = ['js' => 'text/javascript', 'css' => 'text/css', 'svg' => 'image/svg+xml', 'png' => 'image/png', 'ico' => 'image/x-icon', 'woff' => 'font/woff', 'woff2' => 'font/woff2'];
|
||||||
|
if ($asset !== false && is_file($asset) && str_starts_with(str_replace('\\', '/', $asset), str_replace('\\', '/', $public).'/')
|
||||||
|
&& isset($types[pathinfo($asset, PATHINFO_EXTENSION)])) {
|
||||||
|
header('Content-Type: '.$types[pathinfo($asset, PATHINFO_EXTENSION)]);
|
||||||
|
readfile($asset);
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||||
|
$app->useStoragePath($root.'/storage');
|
||||||
|
$app->usePublicPath($root.'/public');
|
||||||
|
$app->booted(function () use ($root, $database) {
|
||||||
|
if (config('database.default') !== 'pgsql' || config('database.connections.pgsql.database') !== $database) {
|
||||||
|
abort(503);
|
||||||
|
}
|
||||||
|
config(['capital-register.qa_enabled' => true, 'import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true,
|
||||||
|
'import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true, 'import-readiness.qa_enabled' => true, 'import-estimates.qa_enabled' => true,
|
||||||
|
'session.driver' => 'file', 'session.files' => $root.'/storage/framework/sessions', 'session.domain' => null,
|
||||||
|
'session.secure' => false, 'cache.default' => 'array']);
|
||||||
|
});
|
||||||
|
$app->handleRequest(Request::capture());
|
||||||
@@ -1,5 +1,19 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
|
test('capital register contention requires both actual lock receipts and one immutable version per scenario', function () {
|
||||||
|
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-capital'];
|
||||||
|
$rows = [];
|
||||||
|
foreach (['same_operation' => [200, 200], 'same_version' => [200, 409]] as $scenario => $statuses) {
|
||||||
|
$rows[] = ['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => 2, 'documents_created' => 1,
|
||||||
|
'audits' => 1, 'files_created' => 0, 'all_originals_verified' => true];
|
||||||
|
}
|
||||||
|
$output = implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $rows));
|
||||||
|
expect(landedQaReceiptsVerified($command, $output))->toBeTrue();
|
||||||
|
expect(landedQaReceiptsVerified($command, json_encode($rows[0], JSON_THROW_ON_ERROR)))->toBeFalse();
|
||||||
|
$rows[1]['documents_created'] = 2;
|
||||||
|
expect(landedQaReceiptsVerified($command, implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $rows))))->toBeFalse();
|
||||||
|
});
|
||||||
|
|
||||||
require_once __DIR__.'/../Support/LandedQaReceipts.php';
|
require_once __DIR__.'/../Support/LandedQaReceipts.php';
|
||||||
|
|
||||||
test('estimate contention receipts require all native uniqueness races and explicit estimate effects', function () {
|
test('estimate contention receipts require all native uniqueness races and explicit estimate effects', function () {
|
||||||
@@ -74,6 +88,15 @@ test('restore completion requires the restored replay original snapshot and data
|
|||||||
expect(landedQaReceiptsVerified($estimateCommand, $existingRecovery."\n".json_encode([
|
expect(landedQaReceiptsVerified($estimateCommand, $existingRecovery."\n".json_encode([
|
||||||
'estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true,
|
'estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true,
|
||||||
], JSON_THROW_ON_ERROR)))->toBeTrue();
|
], JSON_THROW_ON_ERROR)))->toBeTrue();
|
||||||
|
$bankCommand = [...array_slice($command, 0, 3), 'import-bank-support'];
|
||||||
|
$bankPrivate = [...$privateFiles, 'private_original_versions_restored' => 10, 'typed_dossier_versions_restored' => 8];
|
||||||
|
$bankOutput = $databaseOnly."\n".json_encode($bankPrivate, JSON_THROW_ON_ERROR)."\n".json_encode([
|
||||||
|
'estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true,
|
||||||
|
], JSON_THROW_ON_ERROR);
|
||||||
|
expect(landedQaReceiptsVerified($bankCommand, $bankOutput))->toBeFalse();
|
||||||
|
expect(landedQaReceiptsVerified($bankCommand, $bankOutput."\n".json_encode([
|
||||||
|
'bank_support_versions_restored' => 2, 'bank_support_relationships_restored' => true, 'bank_support_replay_without_effects' => true,
|
||||||
|
], JSON_THROW_ON_ERROR)))->toBeTrue();
|
||||||
$missingTyped = $privateFiles;
|
$missingTyped = $privateFiles;
|
||||||
unset($missingTyped['typed_dossier_versions_restored']);
|
unset($missingTyped['typed_dossier_versions_restored']);
|
||||||
expect(landedQaReceiptsVerified($command, $databaseOnly."\n".json_encode($missingTyped, JSON_THROW_ON_ERROR)))->toBeFalse();
|
expect(landedQaReceiptsVerified($command, $databaseOnly."\n".json_encode($missingTyped, JSON_THROW_ON_ERROR)))->toBeFalse();
|
||||||
@@ -101,6 +124,75 @@ test('dossier contention requires both races one original and verified bytes', f
|
|||||||
}
|
}
|
||||||
unset($row);
|
unset($row);
|
||||||
expect(landedQaReceiptsVerified($partyCommand, $encode($rows)))->toBeTrue();
|
expect(landedQaReceiptsVerified($partyCommand, $encode($rows)))->toBeTrue();
|
||||||
|
$bankCommand = [...array_slice($partyCommand, 0, 3), 'race-bank'];
|
||||||
|
expect(landedQaReceiptsVerified($bankCommand, $encode($rows)))->toBeTrue();
|
||||||
$rows[1]['files_created'] = 1;
|
$rows[1]['files_created'] = 1;
|
||||||
expect(landedQaReceiptsVerified($partyCommand, $encode($rows)))->toBeFalse();
|
expect(landedQaReceiptsVerified($partyCommand, $encode($rows)))->toBeFalse();
|
||||||
|
expect(landedQaReceiptsVerified($bankCommand, $encode($rows)))->toBeFalse();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legal contention and recovery require original source publication and frozen buyer context receipts', function () {
|
||||||
|
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-legal'];
|
||||||
|
$rows = [];
|
||||||
|
foreach (['same_operation', 'same_version'] as $scenario) {
|
||||||
|
$rows[] = ['scenario' => $scenario, 'statuses' => $scenario === 'same_operation' ? [200, 200] : [200, 409],
|
||||||
|
'blocked_writers_observed' => 2, 'documents_created' => 1, 'audits' => 1, 'files_created' => 1, 'all_originals_verified' => true];
|
||||||
|
}
|
||||||
|
$encode = fn ($records) => implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $records));
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
|
||||||
|
$rows[1]['files_created'] = 0;
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
|
||||||
|
$command[3] = 'import-legal';
|
||||||
|
$rows = [['post_extension_restore_all_tables_equal' => true, 'recovered_operation_replay_no_effects' => true,
|
||||||
|
'pre_extension_schema_data_balance_restored' => true, 'isolated_restore_removed' => true,
|
||||||
|
'estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true,
|
||||||
|
'bank_support_versions_restored' => 2, 'bank_support_relationships_restored' => true, 'bank_support_replay_without_effects' => true,
|
||||||
|
'private_original_versions_restored' => 11, 'typed_dossier_versions_restored' => 8, 'selected_party_versions_restored' => 2,
|
||||||
|
'source_loss_detected' => true, 'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true]];
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
|
||||||
|
$rows[] = ['legal_source_restored' => true, 'legal_published_version_restored' => true, 'legal_buyer_context_restored' => true, 'legal_replay_without_effects' => true];
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
|
||||||
|
unset($rows[1]['legal_buyer_context_restored']);
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('real corpus receipts require hashes verified native originals and no rule publication', function () {
|
||||||
|
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'corpus'];
|
||||||
|
$row = ['shared_corpus_files_inventoried' => 4, 'inventory_metadata_sha256' => str_repeat('a', 64),
|
||||||
|
'real_official_sources_prepared' => array_fill(0, 4, ['sha256' => str_repeat('b', 64), 'bytes' => 100, 'native_authorized_download_verified' => true]),
|
||||||
|
'rules_published' => 0, 'originals_unchanged' => true, 'financial_and_stock_unchanged' => true, 'synthetic_qa_organization_only' => true];
|
||||||
|
$encode = fn ($value) => json_encode($value, JSON_THROW_ON_ERROR);
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($row)))->toBeTrue();
|
||||||
|
$row['real_official_sources_prepared'][0]['native_authorized_download_verified'] = false;
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($row)))->toBeFalse();
|
||||||
|
$row['real_official_sources_prepared'][0]['native_authorized_download_verified'] = true;
|
||||||
|
$row['rules_published'] = 1;
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($row)))->toBeFalse();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legal amount receipts require both contention cases and recovery of the exact native source-linked cost total', function () {
|
||||||
|
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-legal-amount'];
|
||||||
|
$rows = [];
|
||||||
|
foreach (['same_operation', 'same_version'] as $scenario) {
|
||||||
|
$rows[] = ['scenario' => $scenario, 'statuses' => $scenario === 'same_operation' ? [200, 200] : [200, 409],
|
||||||
|
'blocked_writers_observed' => 2, 'documents_created' => 1, 'audits' => 1, 'files_created' => 0, 'all_originals_verified' => true];
|
||||||
|
}
|
||||||
|
$encode = fn ($records) => implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $records));
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
|
||||||
|
$rows[0]['files_created'] = 1;
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
|
||||||
|
$command[3] = 'import-legal-amount';
|
||||||
|
$rows = [['post_extension_restore_all_tables_equal' => true, 'recovered_operation_replay_no_effects' => true,
|
||||||
|
'pre_extension_schema_data_balance_restored' => true, 'isolated_restore_removed' => true,
|
||||||
|
'estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true,
|
||||||
|
'bank_support_versions_restored' => 2, 'bank_support_relationships_restored' => true, 'bank_support_replay_without_effects' => true,
|
||||||
|
'private_original_versions_restored' => 11, 'typed_dossier_versions_restored' => 8, 'selected_party_versions_restored' => 2,
|
||||||
|
'source_loss_detected' => true, 'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true,
|
||||||
|
'legal_source_restored' => true, 'legal_published_version_restored' => true, 'legal_buyer_context_restored' => true, 'legal_replay_without_effects' => true]];
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
|
||||||
|
$rows[] = ['legal_amount_minor_restored' => 750, 'legal_amount_replay_without_effects' => true,
|
||||||
|
'native_legal_plan_total_minor' => 10750, 'native_legal_plan_source_restored' => true, 'native_legal_plan_replay_without_effects' => true];
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
|
||||||
|
$rows[1]['native_legal_plan_total_minor'] = 10751;
|
||||||
|
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import { App } from '@inertiajs/react';
|
||||||
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
|
import { expect, test } from 'vitest';
|
||||||
|
import CapitalRegister from '../../resources/js/pages/equipment/capital-register';
|
||||||
|
import CapitalAssignments from '../../resources/js/pages/requisitions/capital-assignments';
|
||||||
|
import CapitalAssignmentSummary from '../../resources/js/components/capital-assignment-summary';
|
||||||
|
|
||||||
|
const source = {
|
||||||
|
id: 2,
|
||||||
|
version: 3,
|
||||||
|
record_key: 'source',
|
||||||
|
state: 'archived',
|
||||||
|
reason: 'Synthetic archive reason',
|
||||||
|
data: {
|
||||||
|
type: 'project',
|
||||||
|
code: 'PRJ-QA',
|
||||||
|
name: '<script>QA</script>',
|
||||||
|
reference: 'Frozen documentary reference',
|
||||||
|
department_id: 1,
|
||||||
|
equipment_id: null,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const page = <T,>(data: T[]) => ({
|
||||||
|
data,
|
||||||
|
prev_page_url: null,
|
||||||
|
next_page_url: null,
|
||||||
|
});
|
||||||
|
const assignment = {
|
||||||
|
id: 5,
|
||||||
|
version: 1,
|
||||||
|
state: 'linked',
|
||||||
|
reason: 'Synthetic deliberate assignment',
|
||||||
|
data: { requisition_item_id: 1 },
|
||||||
|
snapshot: { item: { description: 'Synthetic item' }, source },
|
||||||
|
};
|
||||||
|
function render(
|
||||||
|
component: typeof CapitalRegister | typeof CapitalAssignments,
|
||||||
|
props: object,
|
||||||
|
) {
|
||||||
|
return renderToStaticMarkup(
|
||||||
|
<App
|
||||||
|
initialComponent={component}
|
||||||
|
initialPage={{
|
||||||
|
component: 'qa',
|
||||||
|
url: '/qa',
|
||||||
|
version: null,
|
||||||
|
clearHistory: false,
|
||||||
|
encryptHistory: true,
|
||||||
|
props: { errors: {}, ...props },
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
test('read-only capital register preserves archived identity and history without management forms', () => {
|
||||||
|
const html = render(CapitalRegister, {
|
||||||
|
records: page([source]),
|
||||||
|
history: page([source]),
|
||||||
|
departments: [],
|
||||||
|
equipment: [],
|
||||||
|
canManage: false,
|
||||||
|
actorId: 1,
|
||||||
|
tenantId: 1,
|
||||||
|
});
|
||||||
|
expect(html).toContain('Arquivado');
|
||||||
|
expect(html).toContain('Histórico do registo');
|
||||||
|
expect(html).toContain('<script>QA</script>');
|
||||||
|
expect(html).not.toContain('<form');
|
||||||
|
});
|
||||||
|
test('approved requisitions display the preserved source independently of available new choices', () => {
|
||||||
|
const html = render(CapitalAssignments, {
|
||||||
|
requisition: { id: 1, number: 'REQ-QA', status: 'approved' },
|
||||||
|
items: [],
|
||||||
|
current: [assignment],
|
||||||
|
choices: page([]),
|
||||||
|
history: page([assignment]),
|
||||||
|
canWrite: false,
|
||||||
|
actorId: 1,
|
||||||
|
tenantId: 1,
|
||||||
|
});
|
||||||
|
expect(html).toContain('PRJ-QA');
|
||||||
|
expect(html).toContain('versão 3');
|
||||||
|
expect(html).not.toContain('<form');
|
||||||
|
const frozen = renderToStaticMarkup(
|
||||||
|
<CapitalAssignmentSummary records={{ 1: assignment }} />,
|
||||||
|
);
|
||||||
|
expect(frozen).toContain('Frozen documentary reference');
|
||||||
|
expect(frozen).toContain('<script>QA</script>');
|
||||||
|
expect(renderToStaticMarkup(<CapitalAssignmentSummary />)).toBe('');
|
||||||
|
});
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
import { App } from '@inertiajs/react';
|
||||||
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
|
import { expect, test } from 'vitest';
|
||||||
|
import BankSupport from '@/pages/supply/import-bank-support';
|
||||||
|
|
||||||
|
function renderBankSupport(canWrite: boolean, dated = false) {
|
||||||
|
const record = {
|
||||||
|
id: 2,
|
||||||
|
record_key: 'synthetic-bank-key',
|
||||||
|
version: 1,
|
||||||
|
state: dated ? 'documented' : 'ready',
|
||||||
|
reason: 'Synthetic bank evidence',
|
||||||
|
data: {
|
||||||
|
commitment_document_id: 1,
|
||||||
|
declaration_document_id: 3,
|
||||||
|
support_document_ids: [4, 5],
|
||||||
|
submission_document_id: dated ? 6 : null,
|
||||||
|
submission_basis: dated
|
||||||
|
? 'Explicit synthetic delivery evidence'
|
||||||
|
: null,
|
||||||
|
submitted_on: dated ? '2026-11-26' : null,
|
||||||
|
requirements_known: true,
|
||||||
|
required_support_types: ['commercial_invoice'],
|
||||||
|
required_support_counts: { commercial_invoice: 2 },
|
||||||
|
requirements_basis: 'Explicit synthetic bank request',
|
||||||
|
due_on: dated ? '2026-11-27' : null,
|
||||||
|
deadline_basis: dated
|
||||||
|
? 'Explicit synthetic bank request deadline'
|
||||||
|
: null,
|
||||||
|
},
|
||||||
|
snapshot: {
|
||||||
|
documents: [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
version: 1,
|
||||||
|
type: 'bank_commitment',
|
||||||
|
reference: '<script>private term</script>',
|
||||||
|
issuer_reference: 'Synthetic bank',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 3,
|
||||||
|
version: 1,
|
||||||
|
type: 'customs_declaration',
|
||||||
|
reference: 'DU-QA',
|
||||||
|
issuer_reference: 'Synthetic issuer',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 4,
|
||||||
|
version: 1,
|
||||||
|
type: 'commercial_invoice',
|
||||||
|
reference: 'INVOICE-QA-1',
|
||||||
|
issuer_reference: 'Synthetic supplier',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 5,
|
||||||
|
version: 1,
|
||||||
|
type: 'commercial_invoice',
|
||||||
|
reference: 'INVOICE-QA-2',
|
||||||
|
issuer_reference: 'Synthetic supplier',
|
||||||
|
},
|
||||||
|
...(dated
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
id: 6,
|
||||||
|
version: 1,
|
||||||
|
type: 'bank_support',
|
||||||
|
reference: 'DELIVERY-QA',
|
||||||
|
issuer_reference: 'Synthetic bank',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
issues: dated
|
||||||
|
? []
|
||||||
|
: [
|
||||||
|
'Falta o comprovativo de entrega ao banco.',
|
||||||
|
'Prazo documental ainda por indicar.',
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const page = { data: [record], prev_page_url: null, next_page_url: null };
|
||||||
|
return renderToStaticMarkup(
|
||||||
|
<App
|
||||||
|
initialComponent={BankSupport}
|
||||||
|
initialPage={{
|
||||||
|
component: 'supply/import-bank-support',
|
||||||
|
url: '/qa',
|
||||||
|
version: null,
|
||||||
|
clearHistory: false,
|
||||||
|
encryptHistory: true,
|
||||||
|
props: {
|
||||||
|
errors: {},
|
||||||
|
importRecord: {
|
||||||
|
id: 1,
|
||||||
|
record_key: 'synthetic-import-key',
|
||||||
|
version: 1,
|
||||||
|
},
|
||||||
|
order: { id: 1, number: 'QA' },
|
||||||
|
current: page,
|
||||||
|
history: page,
|
||||||
|
documents: {
|
||||||
|
data: [],
|
||||||
|
prev_page_url: null,
|
||||||
|
next_page_url: '/qa?bank_documents_page=2',
|
||||||
|
},
|
||||||
|
types: {
|
||||||
|
bank_commitment: 'Termo de compromisso',
|
||||||
|
commercial_invoice: 'Factura comercial',
|
||||||
|
bank_support: 'Suporte bancário',
|
||||||
|
},
|
||||||
|
canWrite,
|
||||||
|
actorId: 3,
|
||||||
|
tenantId: 2,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
test('bank consultation and report links preserve unknown deadlines requested counts and the delivery distinction', () => {
|
||||||
|
const html = renderBankSupport(false);
|
||||||
|
expect(html).toContain('Documentos reunidos; entrega por documentar');
|
||||||
|
expect(html).toContain('Factura comercial: 2');
|
||||||
|
expect(html).toContain('Prazo: Por indicar');
|
||||||
|
expect(html).toContain('suporte-bancario.csv');
|
||||||
|
expect(html).toContain('<script>private term</script>');
|
||||||
|
expect(html).not.toContain('<form');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bank date presentation follows the shared local format and preserves the actual documentary delivery date', () => {
|
||||||
|
const html = renderBankSupport(false, true);
|
||||||
|
expect(html).toContain('Prazo: 27/11/2026');
|
||||||
|
expect(html).toContain('Entrega documentada: 26/11/2026');
|
||||||
|
expect(html).toContain('Comprovativo de entrega associado');
|
||||||
|
expect(html).not.toContain('entrega por documentar');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bank preparation reuses existing originals and does not apply a generic legal deadline', () => {
|
||||||
|
const html = renderBankSupport(true);
|
||||||
|
expect(html).toContain('Seleccione os originais já registados');
|
||||||
|
expect(html).toContain('Fonte dos requisitos ou informação ainda em falta');
|
||||||
|
expect(html).not.toContain('30 dias');
|
||||||
|
});
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import { App } from '@inertiajs/react';
|
||||||
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
|
import { expect, test } from 'vitest';
|
||||||
|
import ImportEstimate from '@/pages/supply/import-estimate';
|
||||||
|
|
||||||
|
function renderPlan(linked = false) {
|
||||||
|
const page = { data: [], prev_page_url: null, next_page_url: null };
|
||||||
|
const source = {
|
||||||
|
id: 4,
|
||||||
|
version: 2,
|
||||||
|
snapshot: {
|
||||||
|
item: { description: 'Synthetic valued item' },
|
||||||
|
legal_rule: {
|
||||||
|
data: { official_reference: 'Preserved official source' },
|
||||||
|
},
|
||||||
|
result: {
|
||||||
|
lines: [
|
||||||
|
{
|
||||||
|
key: 'duty-line',
|
||||||
|
kind: 'duty',
|
||||||
|
label: 'Synthetic documented duty',
|
||||||
|
method: 'ad_valorem',
|
||||||
|
amount_minor: 750,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return renderToStaticMarkup(
|
||||||
|
<App
|
||||||
|
initialComponent={ImportEstimate}
|
||||||
|
initialPage={{
|
||||||
|
component: 'supply/import-estimate',
|
||||||
|
url: '/qa',
|
||||||
|
version: null,
|
||||||
|
clearHistory: false,
|
||||||
|
encryptHistory: true,
|
||||||
|
props: {
|
||||||
|
errors: {},
|
||||||
|
requisition: {
|
||||||
|
id: 1,
|
||||||
|
number: 'QA',
|
||||||
|
status: 'draft',
|
||||||
|
total_minor: 10000,
|
||||||
|
},
|
||||||
|
actorId: 2,
|
||||||
|
tenantId: 3,
|
||||||
|
canPrepare: true,
|
||||||
|
nativeChanged: false,
|
||||||
|
budgets: page,
|
||||||
|
history: page,
|
||||||
|
legalAmounts: [source],
|
||||||
|
latest: linked
|
||||||
|
? {
|
||||||
|
id: 5,
|
||||||
|
version: 1,
|
||||||
|
state: 'prepared',
|
||||||
|
reason: 'Synthetic scenario',
|
||||||
|
data: {
|
||||||
|
budget_id: 1,
|
||||||
|
components: [
|
||||||
|
{
|
||||||
|
key: 'duty',
|
||||||
|
kind: 'duty',
|
||||||
|
status: 'known',
|
||||||
|
basis: 'Preserved selected calculation',
|
||||||
|
subtotal_minor: 750,
|
||||||
|
tax_minor: 0,
|
||||||
|
total_minor: 750,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
snapshot: {
|
||||||
|
plan: {
|
||||||
|
complete: true,
|
||||||
|
budget_amount_minor: 10750,
|
||||||
|
known_total_minor: 10750,
|
||||||
|
unknown: [],
|
||||||
|
},
|
||||||
|
legal_sources: {
|
||||||
|
duty: {
|
||||||
|
estimate_id: 4,
|
||||||
|
estimate_version: 2,
|
||||||
|
charge_key: 'duty-line',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
test('native import preparation offers legal source reuse and additional parcels without silently selecting a value', () => {
|
||||||
|
const html = renderPlan();
|
||||||
|
expect(html).toContain('Reutilizar uma imposição calculada');
|
||||||
|
expect(html).toContain('Synthetic valued item');
|
||||||
|
expect(html).toContain('7.50 MZN');
|
||||||
|
expect(html).toContain('Acrescentar parcela desta família');
|
||||||
|
expect(html).not.toContain('O total conserva a fonte seleccionada');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a preserved legal amount retains explicit budget tax treatment and a deliberate manual-detach action', () => {
|
||||||
|
const html = renderPlan(true);
|
||||||
|
expect(html).toContain('O total conserva a fonte seleccionada');
|
||||||
|
expect(html).toContain('divisão entre base e imposto');
|
||||||
|
expect(html).toContain('retirar ligação e conservar os valores');
|
||||||
|
expect(html.match(/<option[^>]*value="4:duty-line"[^>]*>/)?.[0]).toContain(
|
||||||
|
'selected=""',
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import { App } from '@inertiajs/react';
|
||||||
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
|
import { expect, test } from 'vitest';
|
||||||
|
import Legal from '../../resources/js/pages/supply/import-legal';
|
||||||
|
|
||||||
|
function renderLegal(canManage: boolean, withRule = true, withCharges = false) {
|
||||||
|
const data = {
|
||||||
|
title: '<script>synthetic rule</script>',
|
||||||
|
official_reference: 'Synthetic official edition',
|
||||||
|
official_url: 'https://example.test/source.pdf',
|
||||||
|
citation: 'Article QA',
|
||||||
|
valid_from: '2026-01-01',
|
||||||
|
valid_until: null,
|
||||||
|
match_code: '1234',
|
||||||
|
suggested_code: '1234.56',
|
||||||
|
origin_country: null,
|
||||||
|
sector: null,
|
||||||
|
obligations: 'Synthetic conditions only',
|
||||||
|
document_types: ['licence'],
|
||||||
|
charges: withCharges
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
key: 'synthetic-duty',
|
||||||
|
kind: 'duty',
|
||||||
|
label: 'Synthetic duty',
|
||||||
|
method: 'maximum',
|
||||||
|
rate_percent: '7.500000',
|
||||||
|
specific_minor: 125,
|
||||||
|
quantity_unit: 'KG',
|
||||||
|
basis_reference:
|
||||||
|
'Synthetic explicit valuation and quantity basis',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [],
|
||||||
|
};
|
||||||
|
const rule = {
|
||||||
|
id: 1,
|
||||||
|
record_key: 'qa',
|
||||||
|
version: 2,
|
||||||
|
state: 'published',
|
||||||
|
data,
|
||||||
|
reason: 'Synthetic publication',
|
||||||
|
source_url: '/requisicoes/1/base-legal/fontes/1',
|
||||||
|
};
|
||||||
|
const page = {
|
||||||
|
data: withRule ? [rule] : [],
|
||||||
|
prev_page_url: null,
|
||||||
|
next_page_url: null,
|
||||||
|
};
|
||||||
|
return renderToStaticMarkup(
|
||||||
|
<App
|
||||||
|
initialComponent={Legal}
|
||||||
|
initialPage={{
|
||||||
|
component: 'supply/import-legal',
|
||||||
|
url: '/qa',
|
||||||
|
version: null,
|
||||||
|
clearHistory: false,
|
||||||
|
encryptHistory: true,
|
||||||
|
props: {
|
||||||
|
errors: {},
|
||||||
|
requisition: { id: 1, number: 'QA' },
|
||||||
|
rules: page,
|
||||||
|
history: page,
|
||||||
|
suggestions: withRule
|
||||||
|
? [{ id: 1, version: 2, data, source_sha256: 'qa' }]
|
||||||
|
: [],
|
||||||
|
items: [{ id: 1, description: 'Synthetic item' }],
|
||||||
|
classifications: [],
|
||||||
|
canManage,
|
||||||
|
canPropose: canManage,
|
||||||
|
actorId: 1,
|
||||||
|
tenantId: 1,
|
||||||
|
types: { licence: 'Licença ou autorização' },
|
||||||
|
filters: { code: '1234', date: '2026-11-27' },
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
test('legal consultation escapes titles preserves periods and offers verified-source downloads without management controls', () => {
|
||||||
|
const html = renderLegal(false);
|
||||||
|
expect(html).toContain('<script>synthetic rule</script>');
|
||||||
|
expect(html).toContain('01/01/2026');
|
||||||
|
expect(html).toContain('sem termo final indicado');
|
||||||
|
expect(html).toContain('/base-legal/fontes/1');
|
||||||
|
expect(html).not.toContain('Guardar preparação para validação aduaneira');
|
||||||
|
expect(html).not.toContain('Preparar proposta com esta fonte');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('legal preparation makes documentary scope and human publication explicit', () => {
|
||||||
|
const html = renderLegal(true);
|
||||||
|
expect(html).toContain('Preparar proposta com esta fonte');
|
||||||
|
expect(html).toContain('Preparar nova versão');
|
||||||
|
expect(html).toContain('Guardar preparação para validação aduaneira');
|
||||||
|
expect(html).toContain('Exemplar oficial');
|
||||||
|
expect(html).toContain('Licença ou autorização');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('no matching rule never becomes an assumed zero tax or exemption', () => {
|
||||||
|
const html = renderLegal(false, false);
|
||||||
|
expect(html).toContain('Sem regra publicada correspondente');
|
||||||
|
expect(html).toContain('Não foram presumidos código, taxa ou isenção');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('documented charges expose their methods rates units and input provenance before estimating', () => {
|
||||||
|
const html = renderLegal(true, true, true);
|
||||||
|
expect(html).toContain(
|
||||||
|
'Maior valor entre percentagem e montante por unidade',
|
||||||
|
);
|
||||||
|
expect(html).toContain('7.500000%');
|
||||||
|
expect(html).toContain('Taxa específica:');
|
||||||
|
expect(html).toContain('Quantidade em KG');
|
||||||
|
expect(html).toContain('Origem do valor ou da quantidade');
|
||||||
|
expect(html).toContain('Calcular e preservar estimativa');
|
||||||
|
});
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { App } from '@inertiajs/react';
|
||||||
|
import { renderToStaticMarkup } from 'react-dom/server';
|
||||||
|
import { expect, test } from 'vitest';
|
||||||
|
import Readiness from '../../resources/js/pages/supply/import-readiness';
|
||||||
|
import ImportTariffSummary from '../../resources/js/components/import-tariff-summary';
|
||||||
|
|
||||||
|
test('import follow-up preserves incomplete checks actionable links and unknown dates without rendering financial operations', () => {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<App
|
||||||
|
initialComponent={Readiness}
|
||||||
|
initialPage={{
|
||||||
|
component: 'supply/import-readiness',
|
||||||
|
url: '/qa',
|
||||||
|
version: null,
|
||||||
|
clearHistory: false,
|
||||||
|
encryptHistory: true,
|
||||||
|
props: {
|
||||||
|
errors: {},
|
||||||
|
importRecord: { id: 1, version: 2, state: 'arrived' },
|
||||||
|
order: { id: 1, number: 'QA' },
|
||||||
|
expectedUsableOn: null,
|
||||||
|
checkedAt: '2026-11-27',
|
||||||
|
complete: false,
|
||||||
|
alerts: [
|
||||||
|
{
|
||||||
|
key: 'missing',
|
||||||
|
category: 'Documentos',
|
||||||
|
text: '<script>Missing synthetic licence</script>',
|
||||||
|
href: '/compras/importacoes/1/documentos',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
expect(html).toContain('Verificação incompleta');
|
||||||
|
expect(html).toContain('Por indicar');
|
||||||
|
expect(html).toContain(
|
||||||
|
'<script>Missing synthetic licence</script>',
|
||||||
|
);
|
||||||
|
expect(html).toContain('/compras/importacoes/1/documentos');
|
||||||
|
expect(html).not.toContain('<form');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('issued classification displays the frozen legal citation and obligations rather than the current catalogue', () => {
|
||||||
|
const html = renderToStaticMarkup(
|
||||||
|
<ImportTariffSummary
|
||||||
|
records={{
|
||||||
|
1: {
|
||||||
|
record_id: 1,
|
||||||
|
version: 2,
|
||||||
|
item: {
|
||||||
|
description: 'Synthetic item',
|
||||||
|
quantity: '1',
|
||||||
|
unit: 'KG',
|
||||||
|
},
|
||||||
|
data: {
|
||||||
|
proposed_code: '1234',
|
||||||
|
confirmed_code: '1234',
|
||||||
|
source_reference: 'Source',
|
||||||
|
confirmation_source: 'Confirmed source',
|
||||||
|
deviation: false,
|
||||||
|
},
|
||||||
|
confirmed_by: { name: 'Synthetic buyer' },
|
||||||
|
reason: 'Synthetic decision',
|
||||||
|
legal_rule: {
|
||||||
|
version: 5,
|
||||||
|
data: {
|
||||||
|
official_reference: 'Preserved official edition',
|
||||||
|
citation: 'Article QA',
|
||||||
|
obligations: 'Preserved documentary conditions',
|
||||||
|
document_types: ['licence'],
|
||||||
|
},
|
||||||
|
context: {
|
||||||
|
date: '2026-11-27',
|
||||||
|
origin_country: 'Synthetic A',
|
||||||
|
sector: 'Synthetic sector',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
expect(html).toContain('Preserved official edition');
|
||||||
|
expect(html).toContain('Article QA');
|
||||||
|
expect(html).toContain('versão 5');
|
||||||
|
expect(html).toContain('Preserved documentary conditions');
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user