@@ -22,7 +22,7 @@ final class ImportLegalAmounts
|
||||
'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.*.specific_minor' => ['present', 'nullable', 'regex:/^\d{1,15}(\.\d{1,6})?$/', 'numeric', 'min:0', 'max:100000000000000'],
|
||||
'charges.*.quantity_unit' => 'present|nullable|string|max:40',
|
||||
'charges.*.basis_reference' => 'required|string|min:3|max:4000',
|
||||
])->validate();
|
||||
@@ -34,8 +34,21 @@ final class ImportLegalAmounts
|
||||
|| ($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.']);
|
||||
}
|
||||
$coefficient = null;
|
||||
if ($specific) {
|
||||
if (! is_int($charge['specific_minor']) && ! is_string($charge['specific_minor'])) {
|
||||
throw ValidationException::withMessages(['charges.'.$index.'.specific_minor' => 'Indique a taxa específica como decimal exacto, sem conversão binária.']);
|
||||
}
|
||||
$decimal = BigDecimal::of($charge['specific_minor'])->strippedOfTrailingZeros();
|
||||
if ($decimal->isGreaterThan('100000000000000')) {
|
||||
throw ValidationException::withMessages(['charges.'.$index.'.specific_minor' => 'A taxa específica excede o limite suportado.']);
|
||||
}
|
||||
// Keep the canonical integer representation of all previous rules.
|
||||
// Fractional cents belong to the coefficient, not a rounded payment.
|
||||
$coefficient = str_contains((string) $decimal, '.') ? (string) $decimal : $decimal->toInt();
|
||||
}
|
||||
$result[] = [...$charge, 'rate_percent' => $percent ? (string) BigDecimal::of($charge['rate_percent'])->toScale(6) : null,
|
||||
'specific_minor' => $specific ? (int) $charge['specific_minor'] : null];
|
||||
'specific_minor' => $coefficient];
|
||||
}
|
||||
|
||||
return $result;
|
||||
|
||||
@@ -9,7 +9,7 @@ final class ImportLegalReferenceDrafts
|
||||
{
|
||||
public const EDITION_SHA256 = 'a0110696253715567af39c159a21bacfebc32f944fa43a4efd18070d36959e50';
|
||||
|
||||
/** Page 2180-(4), Annex to Law 8/2025: exact codes and general rates, not preferential rates. */
|
||||
/** Annex to Law 8/2025, pages 2180-(4) to (7): exact codes and general rates, never preferential eligibility. */
|
||||
private const ROWS = [
|
||||
['3506.91.10', 'Adesivos à base de polímeros ou borracha', '20'],
|
||||
['3506.91.20', 'Silicone para selagem de painéis solares', '20'],
|
||||
@@ -22,6 +22,43 @@ final class ImportLegalReferenceDrafts
|
||||
['7408.29.10', 'Tira metálica para soldadura de painéis solares', '7.5'],
|
||||
['7408.29.90', 'Outros fios de cobre da subposição 7408.29', '7.5'],
|
||||
['7604.10.10', 'Kit de perfis de alumínio para emolduração de painéis solares', '7.5'],
|
||||
['7604.10.90', 'Outras barras e perfis de alumínio não ligado', '7.5', 5],
|
||||
['7612.90.10', 'Recipientes de alumínio para armazenamento e transporte de líquidos', '7.5', 5],
|
||||
['7612.90.90', 'Outros recipientes da subposição 7612.90', '7.5', 5],
|
||||
['8451.80.10', 'Máquina de lavagem de vidros de painéis solares até 500 Wp', '5', 5, 'K'],
|
||||
['8451.80.90', 'Outras máquinas da subposição 8451.80', '5', 5, 'K'],
|
||||
['8461.90.10', 'Máquina de corte de tiras metálicas para soldadura de painéis solares', '5', 5, 'K'],
|
||||
['8461.90.20', 'Máquina de corte de telas EVA e de protecção traseira de painéis solares', '5', 5, 'K'],
|
||||
['8461.90.90', 'Outras máquinas da subposição 8461.90', '5', 5, 'K'],
|
||||
['8479.89.10', 'Máquina pneumática de silicone para selagem de painéis solares até 12 bares', '7.5', 5],
|
||||
['8479.89.90', 'Outras máquinas da subposição 8479.89', '7.5', 5],
|
||||
['8486.20.10', 'Máquina de tabulações e longarinas para formação e transporte de fileiras de células solares', '7.5', 6],
|
||||
['8486.20.20', 'Máquina de laminagem de painéis solares', '7.5', 6],
|
||||
['8486.20.30', 'Máquina de colocação de moldura nos painéis solares', '7.5', 6],
|
||||
['8486.20.90', 'Outras máquinas da subposição 8486.20', '7.5', 6],
|
||||
['8486.40.10', 'Máquina de aplicação de cantos para emolduração de painéis solares', '7.5', 6],
|
||||
['8486.40.90', 'Outras máquinas da subposição 8486.40', '7.5', 6],
|
||||
['8536.90.10', 'Caixa de junção de terminais de painel solar com isolamento mínimo IP 67', '7.5', 6],
|
||||
['8536.90.90', 'Outros aparelhos da subposição 8536.90', '7.5', 6],
|
||||
['8541.42.10', 'Células solares policristalinas e monocristalinas não montadas em módulos ou painéis', '7.5', 6],
|
||||
['8541.42.90', 'Outras células fotovoltaicas da subposição 8541.42', '7.5', 6],
|
||||
['8702.40.10', 'Autocarros com motor eléctrico para transporte de 40 ou mais pessoas', '5', 6, 'K'],
|
||||
['8702.40.90', 'Outros veículos da subposição 8702.40', '5', 6, 'K'],
|
||||
['8703.80.10', 'Automóveis com motor eléctrico e capacidade de bateria até 62 kWh', '20', 7],
|
||||
['8703.80.90', 'Outros automóveis da subposição 8703.80', '20', 7],
|
||||
['8704.21.10', 'Cabine dupla e caixa aberta, diesel, até 5 t e inferior a 3200 cm³, novos ou usados até 7 anos', '5', 7],
|
||||
['8704.21.20', 'Cabine dupla e caixa aberta, diesel, até 5 t e inferior a 3200 cm³, usados há mais de 7 anos', '5', 7],
|
||||
['8704.21.30', 'Cabine dupla e caixa aberta, diesel, até 5 t e superior a 3200 cm³, novos ou usados até 7 anos', '5', 7],
|
||||
['8704.21.40', 'Cabine dupla e caixa aberta, diesel, até 5 t e superior a 3200 cm³, usados há mais de 7 anos', '5', 7],
|
||||
['8704.31.10', 'Cabine dupla e caixa aberta, ignição por faísca, até 5 t, novos ou usados até 7 anos', '5', 7],
|
||||
['8704.31.20', 'Cabine dupla e caixa aberta, ignição por faísca, até 5 t, usados há mais de 7 anos', '5', 7],
|
||||
['8716.80.10', 'Outros veículos não autopropulsionados, carroças de tracção', '5', 7, 'K'],
|
||||
['8716.80.90', 'Outros veículos da subposição 8716.80', '5', 7, 'K'],
|
||||
['9031.49.10', 'Máquinas de teste de qualidade de painéis solares', '7.5', 7],
|
||||
['9031.49.20', 'Máquinas de teste de células solares', '7.5', 7],
|
||||
['9031.49.90', 'Outros instrumentos e aparelhos da subposição 9031.49', '7.5', 7],
|
||||
['9507.90.10', 'Artigos para pesca à linha da subposição 9507.90', '5', 7, 'K'],
|
||||
['9507.90.90', 'Outros artigos da subposição 9507.90', '5', 7, 'K'],
|
||||
];
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
@@ -33,16 +70,24 @@ final class ImportLegalReferenceDrafts
|
||||
// Reuse native original verification; a remembered hash alone cannot vouch for changed bytes.
|
||||
app(ImportEvidence::class)->bytes($source);
|
||||
$drafts = [];
|
||||
foreach (self::ROWS as [$code, $description, $rate]) {
|
||||
$citation = 'Lei 8/2025, de 29 de Dezembro, artigo 2 e anexo, BR I Série 248, suplemento, página 2180-(4), código '.$code.'; início de vigência: artigo 4.';
|
||||
foreach (self::ROWS as $row) {
|
||||
[$code, $description, $rate] = $row;
|
||||
$page = $row[3] ?? 4;
|
||||
$class = $row[4] ?? null;
|
||||
$citation = 'Lei 8/2025, de 29 de Dezembro, artigo 2 e anexo, BR I Série 248, suplemento, página 2180-('.$page.'), código '.$code.'; início de vigência: artigo 4.';
|
||||
$drafts[] = ['source_id' => $source->id, 'source_sha256' => self::EDITION_SHA256,
|
||||
'code' => $code, 'description' => $description, 'rate_percent' => $rate,
|
||||
'documentary_class' => $class,
|
||||
'title' => 'Taxa geral documental — '.$code,
|
||||
'official_reference' => $source->data['official_reference'], 'official_url' => $source->data['official_url'] ?? null,
|
||||
'citation' => $citation, 'valid_from' => '2026-01-01',
|
||||
'obligations' => 'Confirmar a descrição completa e as condições no exemplar. Esta preparação transcreve apenas a taxa geral da página 2180-(4); não determina preferência de origem, isenção, ICE, IVA, sobretaxa ou alterações posteriores. Documentar o regime e a base de tributação antes de utilizar uma estimativa.',
|
||||
'obligations' => 'Confirmar a descrição completa, unidades e condições na página 2180-('.$page.') do exemplar. '.($class === 'K' ? 'O anexo indica classe K; isso não comprova elegibilidade para um benefício. ' : '').(str_starts_with($code, '8704.') ? 'O artigo 2, n.º 2, limita a retirada da classe K da posição 87.04 aos bens de capital para investimento; não presumir o destino ou o regime. ' : '').'Esta preparação transcreve apenas a taxa geral; não determina preferência de origem, isenção, ICE, IVA, sobretaxa ou alterações posteriores. Documentar o regime e a base de tributação antes de utilizar uma estimativa.',
|
||||
'charges' => [['key' => 'general_duty', 'kind' => 'duty', 'label' => 'Direitos aduaneiros — taxa geral do exemplar',
|
||||
'method' => 'ad_valorem', 'rate_percent' => $rate, 'specific_minor' => null, 'quantity_unit' => null, 'basis_reference' => $citation]]];
|
||||
'method' => 'ad_valorem', 'rate_percent' => $rate, 'specific_minor' => null, 'quantity_unit' => null, 'basis_reference' => $citation],
|
||||
...array_map(fn (array $charge) => ['key' => $charge[0], 'kind' => $charge[1], 'label' => $charge[2],
|
||||
'method' => 'unknown', 'rate_percent' => null, 'specific_minor' => null, 'quantity_unit' => null,
|
||||
'basis_reference' => 'Não determinado por este excerto: conferir incidência, regime, base e período nas respectivas fontes antes de aplicar ou declarar não aplicável.'],
|
||||
[['ice_pending', 'ice', 'ICE — por determinar'], ['vat_pending', 'vat', 'IVA — por determinar'], ['other_pending', 'other', 'Outras imposições — por conferir']])]];
|
||||
}
|
||||
|
||||
return $drafts;
|
||||
|
||||
@@ -128,9 +128,19 @@ final class RequisitionExpiry
|
||||
$basisField = is_array($rules) && is_bool($rules['approval_includes_tax'] ?? null)
|
||||
? ($rules['approval_includes_tax'] ? 'total_minor' : 'subtotal_minor') : null;
|
||||
$approvalAmount = is_array($basis) && $basisField !== null ? ($basis[$basisField] ?? null) : null;
|
||||
$steps = array_map(static function (array $step): array {
|
||||
// ApprovalStep preserves SQL timestamps without a cast. Attach the
|
||||
// application timezone in the read DTO, never rewrite the snapshot.
|
||||
$value = $step['decided_at'] ?? null;
|
||||
if (is_string($value) && preg_match('/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?$/D', $value)) {
|
||||
$step['decided_at'] = CarbonImmutable::parse($value, (string) config('app.timezone'))->toIso8601String();
|
||||
}
|
||||
|
||||
return $step;
|
||||
}, $row->snapshot['steps']);
|
||||
|
||||
return ['id' => $row->id, 'data' => $row->data, 'reason' => $row->reason,
|
||||
'request' => $row->snapshot['request'], 'steps' => $row->snapshot['steps'], 'created_at' => $row->created_at,
|
||||
'request' => $row->snapshot['request'], 'steps' => $steps, 'created_at' => $row->created_at,
|
||||
'items' => $items, 'rules' => is_array($rules) ? Arr::only($rules, ['first_limit_minor', 'second_limit_minor', 'approval_includes_tax', 'rules_provisional', 'routing_plan_revision']) : [],
|
||||
'approval_amount_minor' => is_int($approvalAmount) && $approvalAmount >= 0 ? $approvalAmount : null,
|
||||
'approval_uses_separate_basis' => is_array($rules) && is_array($rules['approval_basis'] ?? null)];
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
# D1 — consulta de metadados dos módulos
|
||||
|
||||
## Exportação privada separada — preparação QA de 28/11/2026
|
||||
|
||||
A decisão do proprietário acrescenta uma autoridade privada própria para Compras, stock, finanças e configuração. As quatro competências `audit_private_purchasing_read`, `audit_private_stock_read`, `audit_private_finance_read` e `audit_private_configuration_read` são independentes e configuráveis pelos mecanismos existentes; não foram atribuídas a utilizadores reais. Administração, Finanças ou `audit_metadata_read` não as conferem por herança. A capacidade continua desligada fora do ambiente QA autorizado.
|
||||
|
||||
Em `/auditoria/privada`, o operador selecciona as famílias autorizadas e prepara expressamente um ZIP. A preparação recuperada não executa comandos. O manifesto identifica fontes, colunas ausentes, contagens e hashes; distingue componentes não instalados de conjuntos vazios. A exportação conserva factos financeiros registados, sem calcular novos saldos. Bancos completos, documentos bancários específicos, conteúdo privado de Pessoas, credenciais e caminhos internos ficam excluídos. Os originais empresariais incluídos mantêm os seus bytes; não se afirma anonimização de texto livre ou certificação documental.
|
||||
|
||||
Cada pacote pertence ao seu criador e contexto. Geração, repetição e descarga conferem a autoridade actual; ficheiro ausente ou alterado impede a entrega. Repetir a mesma operação conserva o original e não regenera silenciosamente um pacote perdido. A descarga usa uma cópia dos bytes verificados, para uma alteração posterior do armazenamento não mudar a resposta já preparada.
|
||||
|
||||
Para preservar estes pacotes, uma cópia de recuperação deve conservar conjuntamente os registos `private_audit_exports` e os ficheiros privados `audit-exports/<empresa>/<criador>/<identificador>/auditoria.zip` no disco local configurado. Uma cópia apenas da base não contém os bytes do ZIP. A reposição deve conservar caminho relativo, tamanho, SHA-256 e manifesto originais, sem criar uma nova exportação ou alterar a autoridade. Foi ensaiada em QA a perda e reposição exacta de um arquivo a partir de outro disco privado, com metadados e auditoria intactos; isto não equivale a um restauro integral de SQL e ficheiros nem autoriza intervir no piloto.
|
||||
|
||||
Provas e limites: `proofs/audit-export-scope-proposal.json`. A consulta de metadados descrita abaixo conserva o seu âmbito e funcionamento.
|
||||
|
||||
27/11/2026: investigação por referência exacta da requisição integrada com acção/utilizador/período e CSV integral do mesmo conjunto. A ligação ao processo só aparece quando o utilizador também tem acesso nativo a esse processo; a competência de metadados continua sem o conceder. O histórico da requisição liga à consulta de eventos apenas com essa competência explícita. O cabeçalho do CSV conserva os critérios aplicados, mantendo as quatro colunas de dados.
|
||||
|
||||
Verificação deste delta: SQLite11/363 e PostgreSQL11/363, frontend12dirigidos, tipos/PHPStan/check/Pint/build privado aprovados. Integração directa dos controladores no ensaio PostgreSQL confirmou três transacções com `transaction_read_only=on`, sem alterar fontes/perfis/stock/orçamento; não é prova de navegador. Exemplo com perfis exclusivamente sintéticos preparado e removido. Prova `proofs/audit-metadata.json`, delta de investigação. Sem concessões no piloto ou exportação de conteúdo privado.
|
||||
@@ -13,3 +25,6 @@ Paginação de25eventos pela ordem de registo,começando pelos mais antigos. Fil
|
||||
Esta consulta não é exportação integral de auditoria,arquivo inviolável,retenção,assinatura ou monitorização de acessos. Não escreve eventos pela mera consulta nem certifica protecção contra administradoresSQL. Os campos omitidos não são reconstruídos por esta funcionalidade. Volume elevado e revisão visual têm validação própria pendente.
|
||||
|
||||
Sem migração ou novas permissões no piloto. A inclusão do menu é condicionada à competência; a recusaHTTP do piloto é esperada enquanto a atribuição não for autorizada. Provas audit-metadata.json,audit-metadata-pg.json e audit-metadata-http.json.
|
||||
|
||||
|
||||
28/11/2026 — recuperação conjunta de auditoria privada demonstrada: pg_dump/pg_restore para outra base e identidade não privilegiada,138tabelas/colunas/linhas iguais; ficheiros restaurados de cópia separada com a árvore original indisponível. ZIP das quatro famílias e original sintético preservam bytes/hash; repetição sem efeitos e revogação actual recusada. Bases77d3a97ec523/a546c3b9d7b8,roles,cluster e raiz próprios removidos. Comando --private-audit-recovery --integrated-schema --frozen-runtime no runner existente; prova audit-export-scope-proposal.json. Sem instalação ou alteração operacional.
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
# Desenvolvimento do SGC
|
||||
|
||||
28/11/2026 — fecho dirigido visual/financeiro: ordem sintética50linhas/100MZN conferida em3páginas,cabeçalhos repetidos,linhas inteiras e total preservado; impressão cancelada. Percurso HTTP409verificações/51POST/7perfis na candidata bc1e3207: pedido/ordem/factura100MZN,pagamentos40+60MZN,saldo0,consumo100MZN,stock1un/1movimento,sem diário contabilístico ou transferência. Edge390×526 confirmou imputa??es,recusa39/40MZN com campos preservados,revisão40MZN v2 e histórico v1,relatório100MZN/2imputados/0por imputar e factura liquidada. Requisitante conserva etapas financeiras reservadas/403; recusa agora em português com regresso ao painel,teste1/12 e revisão desktop/móvel aprovados. Provas product-review-20261122.json e rq01-account-assignment-qa.json. Todos os ambientes/separadoresQA removidos,piloto/SGF e separador original preservados. Não equivale a aceitação integral ou instalação.
|
||||
|
||||
28/11/2026 — revisão real corrigiu dois defeitos: histórico de decisão sem fuso era mostrado duas horas antes (DTO agora explicita o fuso, sem alterar originais); detalhe da requisição alargava a página móvel (coluna redimensionável e deslocação limitada à tabela). PostgreSQL3/300,PHPStan0,Pint aprovados; frontend8/2ficheiros,tipos/check/build aprovados. Edge390×526 confirmou datas coerentes,100MZN originais/120MZN da nova submissção,tabela com coluna final alcançável e texto sem corte. AtribuiçãoQA-100 recusou99/100MZN,preservou campos e gravou100/100MZN como v1. Provas requisition-expiry-qa.json e rq01-account-assignment-qa.json. Buildbc1e32071d667b3d3b71e2e7a9822f52ce617cd35bd314bef9b2967e22d45835/183entradas fixado no runner; ambientesQA removidos,piloto/SGF e separador original preservados. Restam revisão transversal e aceitação integral.
|
||||
|
||||
28/11/2026 — recuperação conjunta de auditoria privada demonstrada: pg_dump/pg_restore para outra base e identidade não privilegiada,138tabelas/colunas/linhas iguais; ficheiros restaurados de cópia separada com a árvore original indisponível. ZIP das quatro famílias e original sintético preservam bytes/hash; repetição sem efeitos e revogação actual recusada. Bases77d3a97ec523/a546c3b9d7b8,roles,cluster e raiz próprios removidos. Comando --private-audit-recovery --integrated-schema --frozen-runtime no runner existente; prova audit-export-scope-proposal.json. Sem instalação ou alteração operacional.
|
||||
|
||||
28/11/2026 — revisão nativa retomada e demonstrada em QA isolado: preparação legal3506.91.20 gravada como v1/Em preparação, sem publicação; selecção móvel, aviso de saída e recuperação por Voltar/Avançar conferidos. Exportação privada das quatro famílias gerada e descarregada pela conta sintética própria; manifesto/hash/tamanho e menu legíveis a390×526. Ordem de produção QA-VISUAL-PROD-20261128 registada pelo procurement após configuração expressa na empresa sintética; referência, local, autor e descrição apresentados na lista móvel. Urgência histórica conserva recusa de redução. Corrigida mensagem que confundia ausência de regras com ausência de fontes; regressão14/2ficheiros. Build visual8a30171b051303e1df299157cea7684c5276846560c9b42c8c782b2ed89dc272/183entradas. HTTP legal final48propostas confirmado na prova, substituindo contagem11do incremento anterior. Base/roleQA removidas; separadorQA fechado e separador original preservado. Esta evidência substitui o bloqueio anterior da ferramenta apenas nos percursos descritos; restantes percursos, impressão e aceitação integral continuam abertos. Provas existentes import-legal-readiness-qa.json e audit-export-scope-proposal.json; piloto/SGF intactos.
|
||||
|
||||
28/11/2026 — propostas documentais da base legal:48códigos das páginas2180-(4)a(7) do anexo da Lei8/2025 reutilizáveis pela área aduaneira apenas com o exemplar exacto verificado (SHAa0110696...). Selecção expressa preenche preparação editável; não publica, não sobrepõe preenchimento recuperado e não activa cálculos. Taxa geral conhecida não determina ICE/IVA/outras imposições: permanecem desconhecidos e impedem total completo por inferência. Fonte alterada retira propostas com aviso sem impedir as restantes consultas. SQLite10/94 e PG10/94, base removida; HTTP nativo confirmou fonte integral1.002.011bytes,11propostas,repetição,descarga exacta,CSRF e revogação,sem efeitos financeiros/stock ou publicação; recursos removidos. Protocolo QA corrigido com15/68,frontend integral382/84ficheiros antes da expansão e16dirigidos depois,tipos/PHPStan0/check/Pint/build aprovados. Manifesto08f42ca3be0d40d8cb78d5bc9bb8b3a4800df846eeacc98a6e57f2fa022e7e14/183entradas. Prova existente `proofs/import-legal-readiness-qa.json`. Não representa pauta consolidada ou cobertura integral do acervo. Piloto/SGF preservados; controlo visual interrompido pela ferramenta por não conseguir confirmar URL, apesar da sessão desbloqueada; sem aceitação visual.
|
||||
|
||||
28/11/2026 — exportação privada de auditoria implementada em QA para Compras, stock, finanças e configuração, conforme decisão expressa. Quatro competências próprias independentes, sem herança de Admin/Finanças/metadados; bancos completos e Pessoas separados. ZIP privado imutável com manifesto, fontes/contagens/colunas ausentes, NDJSON integral e originais verificados; snapshot readonly, UUID idempotente, hashes, descarga autenticada dos bytes conferidos e limpeza só de ficheiros próprios. SQLite15/493, PG15/493 (base removida), frontend24/2ficheiros, tipos/PHPStan0/check/Pint/build aprovados. HTTP nativo270/quatro sessões/20assets,138tabelas intactas no intervalo de consultas; geração/repetição/ZIP conferidos após esse intervalo, recursos removidos. Manifesto fa87e37a3626ef75d22b5248dce9a0af2bad68c967e6f99bb64bc426a68f6aaf,183entradas. Prova: `proofs/audit-export-scope-proposal.json`. Substitui a pendência histórica de escolha das famílias/exportador abaixo; não voltar a perguntar o âmbito. Sem concessões reais, instalação/activação, alteração do piloto/SGF ou aceitação visual/integral. Originais mantêm bytes; não se afirma anonimização de texto livre ou certificação.
|
||||
|
||||
28/11/2026: corrigido erro de acesso introduzido no novo cadastro: apenas metadados nao permitem consultar ordens; leitores autorizados do processo recebem so as origens ligadas. Regressao SQLite1/24 e PostgreSQL1/24, base removida; PHPStan0 e HTTP final234/três sessoes/19assets/137tabelas intactas, sem comandos. Log storage/logs/operational-urgent-http-final-20261128.log; fonte/manifesto privado b712f509 preservados.
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
# Matriz reconciliada do SGC — 03/11/2026
|
||||
|
||||
28/11/2026 — fecho dirigido visual/financeiro: ordem sintética50linhas/100MZN conferida em3páginas,cabeçalhos repetidos,linhas inteiras e total preservado; impressão cancelada. Percurso HTTP409verificações/51POST/7perfis na candidata bc1e3207: pedido/ordem/factura100MZN,pagamentos40+60MZN,saldo0,consumo100MZN,stock1un/1movimento,sem diário contabilístico ou transferência. Edge390×526 confirmou imputa??es,recusa39/40MZN com campos preservados,revisão40MZN v2 e histórico v1,relatório100MZN/2imputados/0por imputar e factura liquidada. Requisitante conserva etapas financeiras reservadas/403; recusa agora em português com regresso ao painel,teste1/12 e revisão desktop/móvel aprovados. Provas product-review-20261122.json e rq01-account-assignment-qa.json. Todos os ambientes/separadoresQA removidos,piloto/SGF e separador original preservados. Não equivale a aceitação integral ou instalação.
|
||||
|
||||
28/11/2026 — revisão real corrigiu dois defeitos: histórico de decisão sem fuso era mostrado duas horas antes (DTO agora explicita o fuso, sem alterar originais); detalhe da requisição alargava a página móvel (coluna redimensionável e deslocação limitada à tabela). PostgreSQL3/300,PHPStan0,Pint aprovados; frontend8/2ficheiros,tipos/check/build aprovados. Edge390×526 confirmou datas coerentes,100MZN originais/120MZN da nova submissção,tabela com coluna final alcançável e texto sem corte. AtribuiçãoQA-100 recusou99/100MZN,preservou campos e gravou100/100MZN como v1. Provas requisition-expiry-qa.json e rq01-account-assignment-qa.json. Buildbc1e32071d667b3d3b71e2e7a9822f52ce617cd35bd314bef9b2967e22d45835/183entradas fixado no runner; ambientesQA removidos,piloto/SGF e separador original preservados. Restam revisão transversal e aceitação integral.
|
||||
|
||||
28/11/2026 — recuperação conjunta de auditoria privada demonstrada: pg_dump/pg_restore para outra base e identidade não privilegiada,138tabelas/colunas/linhas iguais; ficheiros restaurados de cópia separada com a árvore original indisponível. ZIP das quatro famílias e original sintético preservam bytes/hash; repetição sem efeitos e revogação actual recusada. Bases77d3a97ec523/a546c3b9d7b8,roles,cluster e raiz próprios removidos. Comando --private-audit-recovery --integrated-schema --frozen-runtime no runner existente; prova audit-export-scope-proposal.json. Sem instalação ou alteração operacional.
|
||||
|
||||
28/11/2026 — revisão nativa retomada e demonstrada em QA isolado: preparação legal3506.91.20 gravada como v1/Em preparação, sem publicação; selecção móvel, aviso de saída e recuperação por Voltar/Avançar conferidos. Exportação privada das quatro famílias gerada e descarregada pela conta sintética própria; manifesto/hash/tamanho e menu legíveis a390×526. Ordem de produção QA-VISUAL-PROD-20261128 registada pelo procurement após configuração expressa na empresa sintética; referência, local, autor e descrição apresentados na lista móvel. Urgência histórica conserva recusa de redução. Corrigida mensagem que confundia ausência de regras com ausência de fontes; regressão14/2ficheiros. Build visual8a30171b051303e1df299157cea7684c5276846560c9b42c8c782b2ed89dc272/183entradas. HTTP legal final48propostas confirmado na prova, substituindo contagem11do incremento anterior. Base/roleQA removidas; separadorQA fechado e separador original preservado. Esta evidência substitui o bloqueio anterior da ferramenta apenas nos percursos descritos; restantes percursos, impressão e aceitação integral continuam abertos. Provas existentes import-legal-readiness-qa.json e audit-export-scope-proposal.json; piloto/SGF intactos.
|
||||
|
||||
28/11/2026: preparações empresariais recuperadas por actor/empresa/contexto/permissões/versão/fonte: arranque/equipa, perfis separados entre novo/edição, atribuições por pessoa, activação, regras/IVA/comparação, dados bancários/locais, opções contratadas, inteligência/plano IA e alçadas. Palavras-passe excluídas pelo Inertia instalado; omissão não gera falso aviso nem input indefinido. Referência geográfica original congelada, sem a actualizar mantendo edição antiga. Frontend38em7ficheiros, nativos71/764, tipos/PHPStan/check/Pint/diff/build aprovados. Candidata `sgc-company-preparation-final-qa-20261128`, manifestodf4e07d422af16897581371283d9730f41076ad2888d1e4911bdd7cadbb92c5f,180entradas sem faltas; runner fixado. HTTP final213verificações/três sessões/17assets/136tabelas intactas, ambientes removidos. Falha inicial era transporte do verificador Node (!paused): corpos agora consumidos antes de devolver clone; regressão Node1passou com2MiB/fecho sem comprimento, cookies/204/redireccionamento. Runtime interrompido c218afc04aae removido sob guardas; b3antigo preservado. Prova `company_preparation_delta_20261128` em `proofs/requisition-history.json`. Recuperação não executa concessões/activações; piloto/SGF intactos. Reconciliar agora formulários nucleares restantes, sem repetir baterias sem delta; visual/decisões pendentes, aplicação integral activa.
|
||||
|
||||
28/11/2026: contraditório, medidas de melhoria e validação da ficha conservam preparações por actor/empresa/contexto/competência/avaliação/registo/versão/modo de relatório. UUID de criação recuperável entre tentativas; sucesso limpa apenas a preparação concluída e preserva estado dos outros registos, que reconstituem a versão nativa quando muda. Conferência em formulário não submetido automaticamente, botões explícitos. Validação separada do upload; nenhum File adicionado ao histórico. Frontend14em3ficheiros, percursos nativos32/360, tipos/check/diff/build aprovados. Build privado `sgc-supplier-followup-preparation-qa-20261128`, manifesto46a86de9590ceb084b8a9b04abc7782404780044a38cc0982b399dad9bdc88c2,180entradas sem faltas, anteriores preservados. Prova `supplier_followup_preparation_delta_20261128` em `proofs/requisition-history.json`; runner permanece43fc8077/provaHTTP200, sem nova prova HTTP/visual deste build. Próxima frente delimitada: preparações da configuração empresarial, preservando versões, confirmações, perfis e nenhuma concessão por recuperação. Piloto/SGF preservados; aplicação integral activa.
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
# Continuidade do desenvolvimento do SGC
|
||||
|
||||
28/11/2026 — fecho dirigido visual/financeiro: ordem sintética50linhas/100MZN conferida em3páginas,cabeçalhos repetidos,linhas inteiras e total preservado; impressão cancelada. Percurso HTTP409verificações/51POST/7perfis na candidata bc1e3207: pedido/ordem/factura100MZN,pagamentos40+60MZN,saldo0,consumo100MZN,stock1un/1movimento,sem diário contabilístico ou transferência. Edge390×526 confirmou imputa??es,recusa39/40MZN com campos preservados,revisão40MZN v2 e histórico v1,relatório100MZN/2imputados/0por imputar e factura liquidada. Requisitante conserva etapas financeiras reservadas/403; recusa agora em português com regresso ao painel,teste1/12 e revisão desktop/móvel aprovados. Provas product-review-20261122.json e rq01-account-assignment-qa.json. Todos os ambientes/separadoresQA removidos,piloto/SGF e separador original preservados. Não equivale a aceitação integral ou instalação.
|
||||
|
||||
28/11/2026 — revisão real corrigiu dois defeitos: histórico de decisão sem fuso era mostrado duas horas antes (DTO agora explicita o fuso, sem alterar originais); detalhe da requisição alargava a página móvel (coluna redimensionável e deslocação limitada à tabela). PostgreSQL3/300,PHPStan0,Pint aprovados; frontend8/2ficheiros,tipos/check/build aprovados. Edge390×526 confirmou datas coerentes,100MZN originais/120MZN da nova submissção,tabela com coluna final alcançável e texto sem corte. AtribuiçãoQA-100 recusou99/100MZN,preservou campos e gravou100/100MZN como v1. Provas requisition-expiry-qa.json e rq01-account-assignment-qa.json. Buildbc1e32071d667b3d3b71e2e7a9822f52ce617cd35bd314bef9b2967e22d45835/183entradas fixado no runner; ambientesQA removidos,piloto/SGF e separador original preservados. Restam revisão transversal e aceitação integral.
|
||||
|
||||
28/11/2026 — recuperação conjunta de auditoria privada demonstrada: pg_dump/pg_restore para outra base e identidade não privilegiada,138tabelas/colunas/linhas iguais; ficheiros restaurados de cópia separada com a árvore original indisponível. ZIP das quatro famílias e original sintético preservam bytes/hash; repetição sem efeitos e revogação actual recusada. Bases77d3a97ec523/a546c3b9d7b8,roles,cluster e raiz próprios removidos. Comando --private-audit-recovery --integrated-schema --frozen-runtime no runner existente; prova audit-export-scope-proposal.json. Sem instalação ou alteração operacional.
|
||||
|
||||
28/11/2026 — revisão nativa retomada e demonstrada em QA isolado: preparação legal3506.91.20 gravada como v1/Em preparação, sem publicação; selecção móvel, aviso de saída e recuperação por Voltar/Avançar conferidos. Exportação privada das quatro famílias gerada e descarregada pela conta sintética própria; manifesto/hash/tamanho e menu legíveis a390×526. Ordem de produção QA-VISUAL-PROD-20261128 registada pelo procurement após configuração expressa na empresa sintética; referência, local, autor e descrição apresentados na lista móvel. Urgência histórica conserva recusa de redução. Corrigida mensagem que confundia ausência de regras com ausência de fontes; regressão14/2ficheiros. Build visual8a30171b051303e1df299157cea7684c5276846560c9b42c8c782b2ed89dc272/183entradas. HTTP legal final48propostas confirmado na prova, substituindo contagem11do incremento anterior. Base/roleQA removidas; separadorQA fechado e separador original preservado. Esta evidência substitui o bloqueio anterior da ferramenta apenas nos percursos descritos; restantes percursos, impressão e aceitação integral continuam abertos. Provas existentes import-legal-readiness-qa.json e audit-export-scope-proposal.json; piloto/SGF intactos.
|
||||
|
||||
28/11/2026 — propostas documentais da base legal:48códigos das páginas2180-(4)a(7) do anexo da Lei8/2025 reutilizáveis pela área aduaneira apenas com o exemplar exacto verificado (SHAa0110696...). Selecção expressa preenche preparação editável; não publica, não sobrepõe preenchimento recuperado e não activa cálculos. Taxa geral conhecida não determina ICE/IVA/outras imposições: permanecem desconhecidos e impedem total completo por inferência. Fonte alterada retira propostas com aviso sem impedir as restantes consultas. SQLite10/94 e PG10/94, base removida; HTTP nativo confirmou fonte integral1.002.011bytes,11propostas,repetição,descarga exacta,CSRF e revogação,sem efeitos financeiros/stock ou publicação; recursos removidos. Protocolo QA corrigido com15/68,frontend integral382/84ficheiros antes da expansão e16dirigidos depois,tipos/PHPStan0/check/Pint/build aprovados. Manifesto08f42ca3be0d40d8cb78d5bc9bb8b3a4800df846eeacc98a6e57f2fa022e7e14/183entradas. Prova existente `proofs/import-legal-readiness-qa.json`. Não representa pauta consolidada ou cobertura integral do acervo. Piloto/SGF preservados; controlo visual interrompido pela ferramenta por não conseguir confirmar URL, apesar da sessão desbloqueada; sem aceitação visual.
|
||||
|
||||
28/11/2026 — exportação privada de auditoria implementada em QA para Compras, stock, finanças e configuração, conforme decisão expressa. Quatro competências próprias independentes, sem herança de Admin/Finanças/metadados; bancos completos e Pessoas separados. ZIP privado imutável com manifesto, fontes/contagens/colunas ausentes, NDJSON integral e originais verificados; snapshot readonly, UUID idempotente, hashes, descarga autenticada dos bytes conferidos e limpeza só de ficheiros próprios. SQLite15/493, PG15/493 (base removida), frontend24/2ficheiros, tipos/PHPStan0/check/Pint/build aprovados. HTTP nativo270/quatro sessões/20assets,138tabelas intactas no intervalo de consultas; geração/repetição/ZIP conferidos após esse intervalo, recursos removidos. Manifesto fa87e37a3626ef75d22b5248dce9a0af2bad68c967e6f99bb64bc426a68f6aaf,183entradas. Prova: `proofs/audit-export-scope-proposal.json`. Substitui a pendência histórica de escolha das famílias/exportador abaixo; não voltar a perguntar o âmbito. Sem concessões reais, instalação/activação, alteração do piloto/SGF ou aceitação visual/integral. Originais mantêm bytes; não se afirma anonimização de texto livre ou certificação.
|
||||
|
||||
28/11/2026: corrigido erro de acesso introduzido no novo cadastro: apenas metadados nao permitem consultar ordens; leitores autorizados do processo recebem so as origens ligadas. Regressao SQLite1/24 e PostgreSQL1/24, base removida; PHPStan0 e HTTP final234/três sessoes/19assets/137tabelas intactas, sem comandos. Log storage/logs/operational-urgent-http-final-20261128.log; fonte/manifesto privado b712f509 preservados.
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# Entregas por blocos funcionais do SGC
|
||||
|
||||
28/11/2026 — fecho dirigido visual/financeiro: ordem sintética50linhas/100MZN conferida em3páginas,cabeçalhos repetidos,linhas inteiras e total preservado; impressão cancelada. Percurso HTTP409verificações/51POST/7perfis na candidata bc1e3207: pedido/ordem/factura100MZN,pagamentos40+60MZN,saldo0,consumo100MZN,stock1un/1movimento,sem diário contabilístico ou transferência. Edge390×526 confirmou imputa??es,recusa39/40MZN com campos preservados,revisão40MZN v2 e histórico v1,relatório100MZN/2imputados/0por imputar e factura liquidada. Requisitante conserva etapas financeiras reservadas/403; recusa agora em português com regresso ao painel,teste1/12 e revisão desktop/móvel aprovados. Provas product-review-20261122.json e rq01-account-assignment-qa.json. Todos os ambientes/separadoresQA removidos,piloto/SGF e separador original preservados. Não equivale a aceitação integral ou instalação.
|
||||
|
||||
28/11/2026 — revisão nativa retomada e demonstrada em QA isolado: preparação legal3506.91.20 gravada como v1/Em preparação, sem publicação; selecção móvel, aviso de saída e recuperação por Voltar/Avançar conferidos. Exportação privada das quatro famílias gerada e descarregada pela conta sintética própria; manifesto/hash/tamanho e menu legíveis a390×526. Ordem de produção QA-VISUAL-PROD-20261128 registada pelo procurement após configuração expressa na empresa sintética; referência, local, autor e descrição apresentados na lista móvel. Urgência histórica conserva recusa de redução. Corrigida mensagem que confundia ausência de regras com ausência de fontes; regressão14/2ficheiros. Build visual8a30171b051303e1df299157cea7684c5276846560c9b42c8c782b2ed89dc272/183entradas. HTTP legal final48propostas confirmado na prova, substituindo contagem11do incremento anterior. Base/roleQA removidas; separadorQA fechado e separador original preservado. Esta evidência substitui o bloqueio anterior da ferramenta apenas nos percursos descritos; restantes percursos, impressão e aceitação integral continuam abertos. Provas existentes import-legal-readiness-qa.json e audit-export-scope-proposal.json; piloto/SGF intactos.
|
||||
|
||||
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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"date": "2026-11-27",
|
||||
"status": "implemented_in_qa_functional_verification_passed_operational_activation_and_visual_pending",
|
||||
"status": "implemented_in_qa_functional_and_bounded_native_visual_verification_passed_operational_activation_pending",
|
||||
"owner_private_family_decision_20261128": {
|
||||
"exact_reply": "Compras, stock, finanças e configuração; bancos completos e Pessoas ficam separados",
|
||||
"included": [
|
||||
@@ -94,10 +94,10 @@
|
||||
"assertions": 493
|
||||
},
|
||||
"postgresql": {
|
||||
"tests": 15,
|
||||
"passed": 15,
|
||||
"assertions": 493,
|
||||
"database": "compras_receipts_test_3c9809d21aab",
|
||||
"tests": 16,
|
||||
"passed": 16,
|
||||
"assertions": 498,
|
||||
"database": "compras_receipts_test_de3f9447a4ff",
|
||||
"removed": true
|
||||
},
|
||||
"frontend": {
|
||||
@@ -122,7 +122,7 @@
|
||||
"entries": 183,
|
||||
"missing_files_or_imports": 0
|
||||
},
|
||||
"limits": "QA only; no pilot migration, actual grants, activation, SGF writes or visual/mobile/physical print acceptance. People formalisation remains deferred.",
|
||||
"limits": "QA only; no pilot migration, actual grants, activation or SGF writes. Bounded native desktop/mobile generation and download now demonstrated; full application and physical print acceptance remain open. People formalisation remains deferred.",
|
||||
"help_delta": {
|
||||
"frontend_tests": 10,
|
||||
"files": 2,
|
||||
@@ -140,6 +140,63 @@
|
||||
"Same-company fully authorised auditors cannot read another creator package.",
|
||||
"Output parent components reject symlinks and must remain within the owned private QA storage."
|
||||
],
|
||||
"pilot_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e"
|
||||
"pilot_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e",
|
||||
"private_archive_recovery_delta": {
|
||||
"sqlite_tests": 6,
|
||||
"assertions": 438,
|
||||
"passed": 6,
|
||||
"missing_archive_detected": true,
|
||||
"no_silent_regeneration": true,
|
||||
"exact_bytes_restored_from_separate_private_fake_disk": true,
|
||||
"metadata_and_audit_unchanged": true,
|
||||
"not_a_full_sql_file_restore": true
|
||||
}
|
||||
},
|
||||
"native_visual_delta_20261128": {
|
||||
"date": "2026-11-28",
|
||||
"environment": "same owned isolated QA",
|
||||
"native_fortify_login": true,
|
||||
"profile": "synthetic dedicated private auditor",
|
||||
"families": [
|
||||
"purchases",
|
||||
"stock",
|
||||
"finance",
|
||||
"configuration"
|
||||
],
|
||||
"default_selection_empty": true,
|
||||
"explicit_purpose_and_selection_required": true,
|
||||
"package_id": 1,
|
||||
"bytes": 998596,
|
||||
"displayed_sha256": "aaa18e0f58252b5262430408763e41c5d7502865b6f1186b249c74be09bf2e14",
|
||||
"native_download_completed_filename": "auditoria-1.zip",
|
||||
"physical_download_path_inspected": false,
|
||||
"mobile_viewport": {
|
||||
"width": 390,
|
||||
"height": 526
|
||||
},
|
||||
"hash_wrapped_and_download_visible": true,
|
||||
"mobile_menu_export_entry_visible": true,
|
||||
"metadata_authority_not_inferred": true,
|
||||
"successful_form_reset": true,
|
||||
"full_application_acceptance": false,
|
||||
"qa_database_and_role_removed": true,
|
||||
"original_user_tab_preserved": true
|
||||
},
|
||||
"sql_and_private_files_recovery_delta_20261128": {
|
||||
"command": "node scripts/requisition-ledger-qa-check.mjs --private-audit-recovery --integrated-schema --frozen-runtime",
|
||||
"source_database": "compras_receipts_test_77d3a97ec523",
|
||||
"restored_database": "compras_receipts_test_a546c3b9d7b8",
|
||||
"separate_non_privileged_restore_identity": true,
|
||||
"tables_columns_and_rows_equal": 138,
|
||||
"four_family_archive_bytes_and_sha256_preserved": true,
|
||||
"synthetic_original_and_archived_copy_preserved": true,
|
||||
"idempotent_replay_without_effects": true,
|
||||
"current_revocation_refused": true,
|
||||
"source_file_tree_renamed_unavailable_during_verification": true,
|
||||
"restored_files_copied_from_separate_backup_tree": true,
|
||||
"all_databases_roles_cluster_and_owned_root_removed": true,
|
||||
"syntax_pint_node_check_diff_passed": true,
|
||||
"operational_changes": false,
|
||||
"limits": "Synthetic QA only; does not certify a production backup schedule, recovery SLA or actual operational installation."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,13 +111,49 @@
|
||||
"Expected receipt warning follows native effective acceptance rather than customs release alone"
|
||||
],
|
||||
"visual": {
|
||||
"browser_host": "unavailable",
|
||||
"native_browser_inventory": "empty",
|
||||
"browser_host": "native Edge available",
|
||||
"native_browser_inventory": "native window selected",
|
||||
"review_completed": false,
|
||||
"pdf_source_review": "pypdf extraction and pypdfium2 rendered 2025 amendment pages2-4; page3/4 images inspected; no source modifications"
|
||||
"pdf_source_review": "pypdf extraction and pypdfium2 rendered 2025 amendment pages2-4; page3/4 images inspected; no source modifications",
|
||||
"previous_browser_unavailable_observation_superseded": true,
|
||||
"latest_bounded_review": {
|
||||
"date": "2026-11-28",
|
||||
"environment": "isolated synthetic QA; native Edge second tab only",
|
||||
"url": "http://localhost:49217",
|
||||
"mobile_viewport": {
|
||||
"width": 390,
|
||||
"height": 526
|
||||
},
|
||||
"native_login": true,
|
||||
"saved_rule_version": 1,
|
||||
"saved_rule_state": "draft / Em preparação",
|
||||
"code": "3506.91.20",
|
||||
"source_id": 17,
|
||||
"rules_published": 0,
|
||||
"observed": [
|
||||
"Native selection prefilled editable source, citation, start date and general duty20%; other taxes remained unknown.",
|
||||
"Saved preparation displayed version1 and draft state; explicit reset after successful save.",
|
||||
"Mobile selection usable; occupied preparation prevented replacement.",
|
||||
"Native leave warning observed; back then forward recovered the exact preparation title and code.",
|
||||
"Saved rule, source text, cards and controls readable at390px without observed lateral clipping.",
|
||||
"Corrected empty rules message so it no longer claims that no sources exist."
|
||||
],
|
||||
"targeted_regression": {
|
||||
"passed": 14,
|
||||
"files": 2
|
||||
},
|
||||
"full_application_acceptance": false,
|
||||
"physical_print_review": false,
|
||||
"cleanup": {
|
||||
"database_removed": true,
|
||||
"role_removed": true,
|
||||
"qa_tab_closed": true,
|
||||
"original_user_tab_preserved": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"limitations": [
|
||||
"Tax estimate calculations and complete source-specific rule parametrization remain open",
|
||||
"The earlier calculation-implementation gap is superseded by import-legal-amounts-qa.json; complete source-specific legal parametrization, other taxes and later amendments remain separate coverage.",
|
||||
"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"
|
||||
@@ -127,5 +163,152 @@
|
||||
"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>"
|
||||
]
|
||||
],
|
||||
"reference_drafts_delta_20261128": {
|
||||
"status": "implemented_and_verified_in_isolated_qa_no_rule_publication",
|
||||
"source": {
|
||||
"relative_path": "novas/BR_248_I_SERIE_SUPLEMENTO_2025.pdf",
|
||||
"sha256": "a0110696253715567af39c159a21bacfebc32f944fa43a4efd18070d36959e50",
|
||||
"bytes": 1002011,
|
||||
"law": "8/2025",
|
||||
"pages_visually_reviewed": [
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6,
|
||||
7,
|
||||
8
|
||||
],
|
||||
"covered_page": "2180-(4) to 2180-(7), full Law 8/2025 Annex",
|
||||
"effective_from_declared_by_article_4": "2026-01-01"
|
||||
},
|
||||
"behaviour": [
|
||||
"Forty-eight documentary tariff drafts cover every code in the Law 8/2025 Annex; exact source bytes required; not a consolidated tariff or later-amendment claim.",
|
||||
"Existing customs preparation authority, tenant visibility and original evidence verification preserved. No new source grant.",
|
||||
"Explicit selection fills editable native draft; occupied or remembered preparations prevent replacement, deliberate local reset offered.",
|
||||
"General duty only is known from this excerpt; ICE, VAT and other charges remain explicitly unknown, so a partial known subtotal is not a complete total.",
|
||||
"Corrupted matching source yields a bounded warning and no reference drafts; the rest of the legal workspace remains available. No native storage paths returned.",
|
||||
"Class K and article2 paragraph2 investment restriction for87.04 retained as documentary conditions, never automatic benefit eligibility."
|
||||
],
|
||||
"sqlite": {
|
||||
"tests": 10,
|
||||
"assertions": 94,
|
||||
"passed": 10
|
||||
},
|
||||
"native_http": {
|
||||
"database": "compras_receipts_test_3eec359001d8",
|
||||
"removed": true,
|
||||
"native_fortify_login": true,
|
||||
"csrf_refused": true,
|
||||
"source_bytes": 1002011,
|
||||
"verified_download": true,
|
||||
"replay_one_source_one_event": true,
|
||||
"guest_status": 401,
|
||||
"revoked_status": 403,
|
||||
"reference_drafts": 48,
|
||||
"rules_published": 0,
|
||||
"financial_stock_unchanged": true,
|
||||
"server_and_root_removed": true
|
||||
},
|
||||
"frontend": {
|
||||
"all_files": 84,
|
||||
"passed": 382,
|
||||
"targeted_legal_and_help_tests": 16,
|
||||
"targeted_files": 3,
|
||||
"all_tests_before_annex_expansion": 382,
|
||||
"targeted_legal_and_help_tests_after_annex_expansion": 16,
|
||||
"targeted_files_after_annex_expansion": 3
|
||||
},
|
||||
"receipt_protocol": {
|
||||
"tests": 15,
|
||||
"assertions": 68,
|
||||
"passed": 15,
|
||||
"correction": "The first native HTTP run passed its behaviour checks but was rejected by the protocol because the new mode was not registered. Added strict edition/hash/size/count checks and incomplete-receipt regressions; rerun passed. The old large-source receipt still requires over 2 MiB.",
|
||||
"note": "Final expected draft count48; the earlier count11 and its HTTP proof describe the preceding page4-only increment."
|
||||
},
|
||||
"build": {
|
||||
"directory": "storage/framework/testing/sgc-legal-annex-qa-20261128",
|
||||
"manifest_sha256": "08f42ca3be0d40d8cb78d5bc9bb8b3a4800df846eeacc98a6e57f2fa022e7e14",
|
||||
"entries": 183
|
||||
},
|
||||
"checks": [
|
||||
"types passed",
|
||||
"targeted frontend formatting and lint passed",
|
||||
"PHPStan zero errors",
|
||||
"Pint passed"
|
||||
],
|
||||
"limits": [
|
||||
"This is an edition-specific documentary excerpt, not a consolidated or complete Mozambican tariff database.",
|
||||
"Preferential origin, exemptions, other taxes and later amendments are not inferred. Native publication and any actual operational activation remain deliberate separate steps.",
|
||||
"No pilot installation, real rights, financial effects or SGF changes. Native desktop/mobile/save/history review completed only for the recorded legal preparation flow; full application and print acceptance remain open."
|
||||
],
|
||||
"source_code_reconciliation": {
|
||||
"original_annex_codes": 48,
|
||||
"implemented_codes": 48,
|
||||
"missing": [],
|
||||
"extra": []
|
||||
},
|
||||
"postgresql": {
|
||||
"tests": 10,
|
||||
"assertions": 94,
|
||||
"passed": 10,
|
||||
"database": "compras_receipts_test_d179cf5d7490",
|
||||
"removed": true
|
||||
},
|
||||
"native_http_page4_only_previous_run": {
|
||||
"database": "compras_receipts_test_e2addc3374fd",
|
||||
"removed": true,
|
||||
"native_fortify_login": true,
|
||||
"csrf_refused": true,
|
||||
"source_bytes": 1002011,
|
||||
"verified_download": true,
|
||||
"replay_one_source_one_event": true,
|
||||
"guest_status": 401,
|
||||
"revoked_status": 403,
|
||||
"reference_drafts": 11,
|
||||
"rules_published": 0,
|
||||
"financial_stock_unchanged": true,
|
||||
"server_and_root_removed": true
|
||||
},
|
||||
"native_visual": {
|
||||
"date": "2026-11-28",
|
||||
"environment": "isolated synthetic QA; native Edge second tab only",
|
||||
"url": "http://localhost:49217",
|
||||
"mobile_viewport": {
|
||||
"width": 390,
|
||||
"height": 526
|
||||
},
|
||||
"native_login": true,
|
||||
"saved_rule_version": 1,
|
||||
"saved_rule_state": "draft / Em preparação",
|
||||
"code": "3506.91.20",
|
||||
"source_id": 17,
|
||||
"rules_published": 0,
|
||||
"observed": [
|
||||
"Native selection prefilled editable source, citation, start date and general duty20%; other taxes remained unknown.",
|
||||
"Saved preparation displayed version1 and draft state; explicit reset after successful save.",
|
||||
"Mobile selection usable; occupied preparation prevented replacement.",
|
||||
"Native leave warning observed; back then forward recovered the exact preparation title and code.",
|
||||
"Saved rule, source text, cards and controls readable at390px without observed lateral clipping.",
|
||||
"Corrected empty rules message so it no longer claims that no sources exist."
|
||||
],
|
||||
"targeted_regression": {
|
||||
"passed": 14,
|
||||
"files": 2
|
||||
},
|
||||
"full_application_acceptance": false,
|
||||
"physical_print_review": false,
|
||||
"cleanup": {
|
||||
"database_removed": true,
|
||||
"role_removed": true,
|
||||
"qa_tab_closed": true,
|
||||
"original_user_tab_preserved": true
|
||||
}
|
||||
},
|
||||
"build_for_visual_review": {
|
||||
"directory": "storage/framework/testing/sgc-legal-annex-review-qa-20261128",
|
||||
"manifest_sha256": "8a30171b051303e1df299157cea7684c5276846560c9b42c8c782b2ed89dc272",
|
||||
"entries": 183
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,13 +16,36 @@
|
||||
],
|
||||
"correction": "Safe list references and explicit incomplete-original detail/print path. No reconstruction from mutable current records, no invented financial amounts or approvals, no data rewrite.",
|
||||
"validation": {
|
||||
"order_documents_sqlite": {"tests": 14, "assertions": 406, "log": "storage/logs/order-document-compatibility.txt"},
|
||||
"order_documents_postgres": {"tests": 14, "assertions": 406, "isolated_database_removed": true, "log": "storage/logs/order-document-compatibility-pg.txt"},
|
||||
"order_frontend": {"tests": 2},
|
||||
"search_and_help_frontend": {"tests": 11},
|
||||
"financial_search_postgres": {"tests": 6, "assertions": 210, "isolated_database_removed": true},
|
||||
"search_and_order_focused_sqlite": {"tests": 7, "assertions": 237},
|
||||
"pilot_http": {"checks": 6, "business_commands": false},
|
||||
"order_documents_sqlite": {
|
||||
"tests": 14,
|
||||
"assertions": 406,
|
||||
"log": "storage/logs/order-document-compatibility.txt"
|
||||
},
|
||||
"order_documents_postgres": {
|
||||
"tests": 14,
|
||||
"assertions": 406,
|
||||
"isolated_database_removed": true,
|
||||
"log": "storage/logs/order-document-compatibility-pg.txt"
|
||||
},
|
||||
"order_frontend": {
|
||||
"tests": 2
|
||||
},
|
||||
"search_and_help_frontend": {
|
||||
"tests": 11
|
||||
},
|
||||
"financial_search_postgres": {
|
||||
"tests": 6,
|
||||
"assertions": 210,
|
||||
"isolated_database_removed": true
|
||||
},
|
||||
"search_and_order_focused_sqlite": {
|
||||
"tests": 7,
|
||||
"assertions": 237
|
||||
},
|
||||
"pilot_http": {
|
||||
"checks": 6,
|
||||
"business_commands": false
|
||||
},
|
||||
"typescript": "passed",
|
||||
"phpstan": "passed_zero_errors",
|
||||
"build": "passed",
|
||||
@@ -32,5 +55,49 @@
|
||||
"pilot_business_operations": false,
|
||||
"financial_search_activation": false,
|
||||
"whole_product_visual_coverage": false,
|
||||
"enterprise_acceptance": false
|
||||
"enterprise_acceptance": false,
|
||||
"multipage_native_print_delta_20261128": {
|
||||
"environment": "owned isolated synthetic QA",
|
||||
"fixture": "50 pre-issued synthetic fixture lines; not a native issuance proof",
|
||||
"total_minor": 10000,
|
||||
"per_line_minor": 200,
|
||||
"native_edge_preview_pages": 3,
|
||||
"table_headers_repeated": true,
|
||||
"observed_rows_not_split": true,
|
||||
"final_subtotal_and_total_mzn": 100,
|
||||
"original_incomplete_notice_preserved": true,
|
||||
"preview_cancelled": true,
|
||||
"physical_print_or_pdf_export": false,
|
||||
"database_and_role_removed": true,
|
||||
"own_tab_closed_original_user_tab_preserved": true,
|
||||
"runner": "--native-review --integrated-schema --frozen-runtime --print-pagination-preview",
|
||||
"syntax_and_pint": "passed"
|
||||
},
|
||||
"localized_forbidden_delta_20261128": {
|
||||
"cause": "Native requester refusal displayed only English Forbidden and no return navigation.",
|
||||
"change": "Standalone Portuguese403view with static generic text, responsive layout, keyboard focus and dashboard return. No exception, financial, bank, actor or URL details interpolated. No permission or JSON handler changes.",
|
||||
"test": {
|
||||
"file": "tests/Feature/ExpenseAllocationsTest.php",
|
||||
"tests": 1,
|
||||
"assertions": 12,
|
||||
"passed": true,
|
||||
"html_forbidden_and_financial_privacy": true,
|
||||
"json_forbidden_unchanged": true,
|
||||
"pint": "passed"
|
||||
},
|
||||
"native": {
|
||||
"desktop": true,
|
||||
"mobile": {
|
||||
"width": 390,
|
||||
"height": 526
|
||||
},
|
||||
"denied_route": "/auditoria/privada",
|
||||
"synthetic_profile": "requester",
|
||||
"dashboard_return_verified": true,
|
||||
"same_authenticated_identity_after_return": true,
|
||||
"qa_database_and_role_removed": true,
|
||||
"own_tab_closed_original_user_tab_preserved": true
|
||||
},
|
||||
"scope": "Presentation only, in QA; no new entitlement or operational publication."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,13 +5,62 @@
|
||||
"implementation": "Optional lower urgent_minimum_proposals in native versioned company comparison policy, frozen only for newly created requests. UrgentQuotationBasis privately records the applicable approved item/warehouse minimum policy, use context, native free/usable stock at the threshold event, original line, actor, date and current cycle. All lines need matching evidence; otherwise ordinary quotation counts remain. Changed line/cycle/policy does not reuse evidence. Native comparison fingerprint and normal/partial/consolidated order snapshots preserve the selected evidence. Stock evidence is a historical threshold event, not an automatic stock movement, expiry or business approval.",
|
||||
"authority": "Current native quotation preparation authority to record; current native process/quotation readers may consult the projected evidence without gaining recording rights. Revocation, hidden requests and closed awards remain guarded. QA-only and disabled by default.",
|
||||
"verification": {
|
||||
"postgres": { "tests": 6, "assertions": 139, "passed": true, "normal_and_partial_issue": true, "independent_evaluators": 2, "eligible_suppliers": 1, "ordinary_minimum": 3, "explicit_urgent_minimum": 1, "synthetic_normal_order_mzn": 100, "synthetic_partial_order_mzn": 40, "database_removed": "compras_receipts_test_61471f295692" },
|
||||
"sqlite": { "tests": 6, "passed": 5, "skipped": 1, "assertions": 122, "skip_reason": "Published legacy budget runtime lacks partial-order capability; actual partial issuance passed with the pinned private composition on PostgreSQL." },
|
||||
"frontend": { "tests": 46, "files": 4, "passed": true },
|
||||
"typescript": "passed", "phpstan_errors": 0, "frontend_format_lint": "9 files passed", "pint": "passed",
|
||||
"private_build": "storage/framework/testing/sgc-urgent-stock-qa-20261128", "manifest_sha256": "b712f509fb0ff1179fc9d007abbef0a3c2d5f97f575b558cbc49f47d06dc9894", "manifest_entries": 182, "missing_assets_or_imports": 0,
|
||||
"native_readonly_http": { "checks": 234, "prior_same_asset_run_checks": 233, "fortify_sessions": 3, "verified_page_assets": 19, "unchanged_tables_in_read_window": 137, "operational_order_and_urgent_stock_pages": true, "requester_refusals": true, "metadata_order_register_refused": true, "business_commands_sent": 0, "owned_database_and_role_removed": true, "browser_visual_acceptance": false, "log": "storage/logs/operational-urgent-http-final-20261128.log" },
|
||||
"operational_access_regression": { "sqlite_tests": 1, "sqlite_assertions": 24, "postgres_tests": 1, "postgres_assertions": 24, "passed": true, "database_removed": "compras_receipts_test_26a90e083ce1", "correction": "Own new register originally accepted any nonempty permission list. Explicit register authority now excludes metadata-only actors. Authorised process readers receive only linked order origins, never unrelated register rows. PHPStan passed again without suppressions." },
|
||||
"postgres": {
|
||||
"tests": 6,
|
||||
"assertions": 139,
|
||||
"passed": true,
|
||||
"normal_and_partial_issue": true,
|
||||
"independent_evaluators": 2,
|
||||
"eligible_suppliers": 1,
|
||||
"ordinary_minimum": 3,
|
||||
"explicit_urgent_minimum": 1,
|
||||
"synthetic_normal_order_mzn": 100,
|
||||
"synthetic_partial_order_mzn": 40,
|
||||
"database_removed": "compras_receipts_test_61471f295692"
|
||||
},
|
||||
"sqlite": {
|
||||
"tests": 6,
|
||||
"passed": 5,
|
||||
"skipped": 1,
|
||||
"assertions": 122,
|
||||
"skip_reason": "Published legacy budget runtime lacks partial-order capability; actual partial issuance passed with the pinned private composition on PostgreSQL."
|
||||
},
|
||||
"frontend": {
|
||||
"tests": 46,
|
||||
"files": 4,
|
||||
"passed": true
|
||||
},
|
||||
"typescript": "passed",
|
||||
"phpstan_errors": 0,
|
||||
"frontend_format_lint": "9 files passed",
|
||||
"pint": "passed",
|
||||
"private_build": "storage/framework/testing/sgc-urgent-stock-qa-20261128",
|
||||
"manifest_sha256": "b712f509fb0ff1179fc9d007abbef0a3c2d5f97f575b558cbc49f47d06dc9894",
|
||||
"manifest_entries": 182,
|
||||
"missing_assets_or_imports": 0,
|
||||
"native_readonly_http": {
|
||||
"checks": 234,
|
||||
"prior_same_asset_run_checks": 233,
|
||||
"fortify_sessions": 3,
|
||||
"verified_page_assets": 19,
|
||||
"unchanged_tables_in_read_window": 137,
|
||||
"operational_order_and_urgent_stock_pages": true,
|
||||
"requester_refusals": true,
|
||||
"metadata_order_register_refused": true,
|
||||
"business_commands_sent": 0,
|
||||
"owned_database_and_role_removed": true,
|
||||
"browser_visual_acceptance": false,
|
||||
"log": "storage/logs/operational-urgent-http-final-20261128.log"
|
||||
},
|
||||
"operational_access_regression": {
|
||||
"sqlite_tests": 1,
|
||||
"sqlite_assertions": 24,
|
||||
"postgres_tests": 1,
|
||||
"postgres_assertions": 24,
|
||||
"passed": true,
|
||||
"database_removed": "compras_receipts_test_26a90e083ce1",
|
||||
"correction": "Own new register originally accepted any nonempty permission list. Explicit register authority now excludes metadata-only actors. Authorised process readers receive only linked order origins, never unrelated register rows. PHPStan passed again without suppressions."
|
||||
},
|
||||
"own_test_corrections": "Used the actual receiptPayload helper and the existing native 404 for a warehouse actor without process visibility; an authorised Finance reader separately proved 403 for recording and read-only evidence access. Added the omitted explicit normal/partial dataset. No application access was relaxed to satisfy those assertions."
|
||||
},
|
||||
"limits": "Pilot/SGF, real accounts/grants and operational deployment untouched. New HTTP run is read-only and does not replace the separate native financial command journey or physical browser/print acceptance. Metadata audit scope unchanged; private export scope remains a separate owner choice."
|
||||
@@ -347,5 +396,36 @@
|
||||
"product_rules_changed": false,
|
||||
"operational_changes": false,
|
||||
"limits": "Does not certify all order-parts writers or browser/operational acceptance."
|
||||
},
|
||||
"historical_decision_timezone_delta_20261128": {
|
||||
"cause": "ApprovalStep has no datetime cast; preserved decided_at is a naive SQL timestamp. Browser interpreted it as local while submission and return timestamps had an explicit UTC offset. Native review showed a two-hour discrepancy.",
|
||||
"change": "Read DTO adds the configured application timezone only to naive SQL decision timestamps; original rows and frozen snapshots remain unchanged. Already qualified timestamps and absent decisions are preserved.",
|
||||
"postgresql": {
|
||||
"command": "node scripts/requisition-ledger-qa-check.mjs --expiry-history-only --integrated-schema --frozen-runtime",
|
||||
"tests": 3,
|
||||
"passed": 3,
|
||||
"assertions": 300,
|
||||
"database_and_role_removed": true
|
||||
},
|
||||
"static": {
|
||||
"phpstan_errors": 0,
|
||||
"pint": "passed",
|
||||
"node_syntax": "passed"
|
||||
},
|
||||
"native_review": {
|
||||
"desktop": true,
|
||||
"mobile_viewport": {
|
||||
"width": 390,
|
||||
"height": 526
|
||||
},
|
||||
"original_submission_and_approval_both_displayed": "28/11/2026, 17:41:48",
|
||||
"return_displayed": "28/11/2026, 18:12:48",
|
||||
"historical_total_mzn": 100,
|
||||
"new_submission_total_mzn": 120,
|
||||
"historical_rules_and_items_expanded": true,
|
||||
"current_document_return_link_verified": true,
|
||||
"financial_or_decision_writes": false
|
||||
},
|
||||
"scope": "Isolated synthetic QA only; no change to deadlines, decisions, financial effects, original timestamps or operational data."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,10 +4,29 @@
|
||||
"implementation": "OperationalOrders, private register/workspace, company-selected origin mode, separate production_order_prepare and maintenance_order_prepare capabilities without grants. Immutable original orders and versioned per-line links; source preserved in ordinary and partial/consolidated native order snapshots, screen and print. Guarded QA-only, disabled by default, using existing supply_records without schema extension.",
|
||||
"stock_use": "Existing item/warehouse minimum remains company-defined. Optional usage_context explains nature/use in the versioned stock policy; no universal value or automatic calculation was imposed.",
|
||||
"verification": {
|
||||
"sqlite_register_and_supply": { "tests": 12, "assertions": 136, "passed": true },
|
||||
"postgres_register_and_native_orders": { "tests": 6, "assertions": 115, "passed": true, "partial_issue_included": true, "database_removed": "compras_receipts_test_f2d7b42d73c1" },
|
||||
"postgres_stock_use": { "tests": 1, "assertions": 5, "passed": true, "database_removed": "compras_receipts_test_b3d1427bd9f8" },
|
||||
"frontend": { "tests": 36, "files": 3, "passed": true },
|
||||
"sqlite_register_and_supply": {
|
||||
"tests": 12,
|
||||
"assertions": 136,
|
||||
"passed": true
|
||||
},
|
||||
"postgres_register_and_native_orders": {
|
||||
"tests": 6,
|
||||
"assertions": 115,
|
||||
"passed": true,
|
||||
"partial_issue_included": true,
|
||||
"database_removed": "compras_receipts_test_f2d7b42d73c1"
|
||||
},
|
||||
"postgres_stock_use": {
|
||||
"tests": 1,
|
||||
"assertions": 5,
|
||||
"passed": true,
|
||||
"database_removed": "compras_receipts_test_b3d1427bd9f8"
|
||||
},
|
||||
"frontend": {
|
||||
"tests": 36,
|
||||
"files": 3,
|
||||
"passed": true
|
||||
},
|
||||
"phpstan_errors": 0,
|
||||
"format_and_lint": "9 frontend files passed; PHP Pint passed",
|
||||
"private_build": "storage/framework/testing/sgc-operational-orders-qa-20261128",
|
||||
@@ -458,5 +477,118 @@
|
||||
},
|
||||
"log": "storage/logs/payment-preparation-office-http-20261128.log",
|
||||
"scope": "Final private frontend candidate, including native payment registration/review workspaces. Earlier 399 checks remain their dated proof; overlapping counts are not summed. New office business commands use real native HTTP; synthetic reference fixtures remain separate. All owned temporary runtime resources removed."
|
||||
},
|
||||
"native_mobile_account_and_detail_delta_20261128": {
|
||||
"environment": "isolated synthetic QA; native Edge",
|
||||
"viewport": {
|
||||
"width": 390,
|
||||
"height": 526
|
||||
},
|
||||
"detail_layout": {
|
||||
"cause": "Implicit mobile grid track and automatic minimum width of its content column allowed the table to enlarge the whole page.",
|
||||
"change": "Explicit single mobile track and shrinkable content columns retain local TableViewport scrolling.",
|
||||
"justification_wraps_without_lateral_clipping": true,
|
||||
"last_table_column_reached_by_native_horizontal_scroll": true,
|
||||
"totals_and_other_cards_remain_in_place": true
|
||||
},
|
||||
"account_assignment": {
|
||||
"draft_request_id": 2,
|
||||
"line_id": 2,
|
||||
"source": "common chart in own Compras QA database",
|
||||
"account": "QA-100",
|
||||
"invalid_base_mzn": 99,
|
||||
"line_base_and_total_mzn": 100,
|
||||
"mismatch_refused_and_fields_retained": true,
|
||||
"corrected_base_and_total_mzn": 100,
|
||||
"saved_version": 1,
|
||||
"version_and_reason_visible": true,
|
||||
"no_real_grants_or_operational_changes": true
|
||||
},
|
||||
"checks": {
|
||||
"frontend_tests": 8,
|
||||
"frontend_files": 2,
|
||||
"types": "passed",
|
||||
"targeted_format_and_lint": "passed",
|
||||
"private_build": "passed",
|
||||
"manifest_entries": 183,
|
||||
"missing_files_or_imports": 0
|
||||
},
|
||||
"build": {
|
||||
"path": "storage/framework/testing/sgc-requisition-mobile-review-qa-20261128",
|
||||
"sha256": "bc1e32071d667b3d3b71e2e7a9822f52ce617cd35bd314bef9b2967e22d45835"
|
||||
},
|
||||
"cleanup": {
|
||||
"database_and_role_removed": true,
|
||||
"own_qa_tab_closed": true,
|
||||
"original_user_tab_preserved": true
|
||||
},
|
||||
"limits": "Bounded native mobile review, not full application acceptance or operational activation. No general ledger journal, physical stock movement or payment was executed by the attribution.",
|
||||
"native_readonly_http_after_correction": {
|
||||
"checks": 270,
|
||||
"fortify_sessions": 4,
|
||||
"tables_unchanged_in_read_window": 138,
|
||||
"assets_verified": 20,
|
||||
"audit_export_posts_including_replay": 2,
|
||||
"private_download_verified": true,
|
||||
"business_commands": 0,
|
||||
"owned_resources_removed": true,
|
||||
"manifest_sha256": "bc1e32071d667b3d3b71e2e7a9822f52ce617cd35bd314bef9b2967e22d45835"
|
||||
}
|
||||
},
|
||||
"office_native_visual_delta_20261128": {
|
||||
"status": "bounded_native_finance_and_requester_visual_review_completed_in_isolated_qa",
|
||||
"seed_command": "node scripts/requisition-ledger-qa-check.mjs --native-review --native-office-preview --integrated-schema --frozen-runtime --review-minutes=60",
|
||||
"native_http": {
|
||||
"checks": 409,
|
||||
"post_requests": 51,
|
||||
"fortify_sessions": 7,
|
||||
"request_id": 7,
|
||||
"order_id": 2,
|
||||
"invoice_id": 1,
|
||||
"payment_ids": [
|
||||
1,
|
||||
2
|
||||
],
|
||||
"request_order_invoice_total_minor": 10000,
|
||||
"confirmed_payments_minor": [
|
||||
4000,
|
||||
6000
|
||||
],
|
||||
"outstanding_minor": 0,
|
||||
"budget_consumed_minor": 10000,
|
||||
"budget_available_minor": 90000,
|
||||
"stock_quantity_milli": 1000,
|
||||
"stock_movements": 1,
|
||||
"journals": 0,
|
||||
"explicit_finance_category_total_minor": 10000,
|
||||
"selector_self_final_approval_refused": true,
|
||||
"all_mutations_via_native_http": true
|
||||
},
|
||||
"visual": {
|
||||
"finance_desktop": true,
|
||||
"finance_mobile": {
|
||||
"width": 390,
|
||||
"height": 526
|
||||
},
|
||||
"partial_payment_amounts_and_category_versions_readable": true,
|
||||
"invalid_39_mzn_attribution_to_40_mzn_payment_refused": true,
|
||||
"fields_and_version1_preserved_after_error": true,
|
||||
"corrected_40_mzn_attribution_saved_as_version2": true,
|
||||
"versions1_and2_preserved": true,
|
||||
"second_payment_60_mzn_version1_preserved": true,
|
||||
"report_confirmed_spend_and_category_mzn": 100,
|
||||
"report_imputed_payments": 2,
|
||||
"report_unallocated_payments": 0,
|
||||
"paid_invoice_confirmed100_pending0_visible": true,
|
||||
"requester_process_finance_steps_access_reserved": true,
|
||||
"requester_direct_financial_page_status": 403
|
||||
},
|
||||
"manifest_sha256": "bc1e32071d667b3d3b71e2e7a9822f52ce617cd35bd314bef9b2967e22d45835",
|
||||
"cleanup": {
|
||||
"database_and_role_removed": true,
|
||||
"own_browser_tab_closed": true,
|
||||
"original_user_tab_preserved": true
|
||||
},
|
||||
"limits": "Synthetic records only. No bank transfer, operational financial effect, SGF write, installation or full application acceptance. The read-only financial snapshot belongs to the HTTP seed; no separate post-visual SQL snapshot is claimed."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { estimateMoney } from '@/lib/import-estimate-money';
|
||||
import { money } from '@/types/procurement';
|
||||
import {
|
||||
specificRateLabel,
|
||||
specificRateMoney,
|
||||
} from '@/lib/import-legal-specific-rate';
|
||||
|
||||
export type LegalCharge = {
|
||||
key: string;
|
||||
@@ -9,7 +11,7 @@ export type LegalCharge = {
|
||||
label: string;
|
||||
method: string;
|
||||
rate_percent: string | null;
|
||||
specific_minor: number | null;
|
||||
specific_minor: number | string | null;
|
||||
quantity_unit: string | null;
|
||||
basis_reference: string;
|
||||
};
|
||||
@@ -30,7 +32,7 @@ export const chargeDrafts = (charges: LegalCharge[]) =>
|
||||
label: charge.label,
|
||||
method: charge.method,
|
||||
rate_percent: charge.rate_percent ?? '',
|
||||
specific_amount: estimateMoney(charge.specific_minor),
|
||||
specific_amount: specificRateMoney(charge.specific_minor),
|
||||
quantity_unit: charge.quantity_unit ?? '',
|
||||
basis_reference: charge.basis_reference,
|
||||
}));
|
||||
@@ -55,7 +57,8 @@ export function LegalChargeSummary({ charges }: { charges: LegalCharge[] }) {
|
||||
)}
|
||||
{charge.specific_minor !== null && (
|
||||
<dd>
|
||||
Taxa específica: {money(charge.specific_minor)} por{' '}
|
||||
Taxa específica:{' '}
|
||||
{specificRateLabel(charge.specific_minor)} por{' '}
|
||||
{charge.quantity_unit}
|
||||
</dd>
|
||||
)}
|
||||
@@ -181,6 +184,11 @@ export default function LegalChargeFields({
|
||||
})
|
||||
}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Até oito casas decimais. A taxa é
|
||||
preservada; apenas o montante calculado é
|
||||
arredondado a cêntimos.
|
||||
</span>
|
||||
</label>
|
||||
<label className="grid gap-1">
|
||||
Unidade da taxa específica
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/** Exact documentary coefficients; monetary amounts keep their existing cent precision. */
|
||||
export const specificRateMinor = (value: string): number | string | null => {
|
||||
if (!/^\d{1,13}(?:[.,]\d{1,8})?$/.test(value)) return null;
|
||||
const [whole, fraction = ''] = value.replace(',', '.').split('.');
|
||||
const digits = BigInt(whole + fraction.padEnd(2, '0')).toString();
|
||||
const scale = Math.max(fraction.length - 2, 0);
|
||||
if (scale === 0) return Number(digits);
|
||||
const padded = digits.padStart(scale + 1, '0');
|
||||
const decimals = padded.slice(-scale).replace(/0+$/, '');
|
||||
return decimals
|
||||
? `${padded.slice(0, -scale)}.${decimals}`
|
||||
: Number(padded.slice(0, -scale));
|
||||
};
|
||||
|
||||
export const specificRateMoney = (value: number | string | null): string => {
|
||||
if (value === null) return '';
|
||||
const raw = String(value);
|
||||
if (!/^\d{1,15}(?:\.\d{1,6})?$/.test(raw)) return '';
|
||||
const [whole, fraction = ''] = raw.split('.');
|
||||
const scale = fraction.length + 2;
|
||||
const digits = BigInt(whole + fraction)
|
||||
.toString()
|
||||
.padStart(scale + 1, '0');
|
||||
const decimals = digits.slice(-scale).replace(/0+$/, '').padEnd(2, '0');
|
||||
return `${digits.slice(0, -scale)}.${decimals}`;
|
||||
};
|
||||
|
||||
export const specificRateLabel = (value: number | string | null): string => {
|
||||
const amount = specificRateMoney(value);
|
||||
return amount === '' ? 'Por determinar' : `${amount.replace('.', ',')} MZN`;
|
||||
};
|
||||
@@ -242,10 +242,12 @@ export const journeyHelp: JourneyHelp[] = [
|
||||
'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.',
|
||||
'Quando o exemplar conferido tem propostas documentais disponíveis, escolha deliberadamente o código para preencher uma preparação editável. Conclua ou limpe primeiro uma preparação já preenchida.',
|
||||
'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.',
|
||||
'As propostas do anexo da Lei 8/2025, páginas 2180-(4) a (7), transcrevem apenas as taxas gerais dessa edição, com início em 01/01/2026. Não consolidam alterações posteriores nem determinam preferências, isenções, ICE ou IVA.',
|
||||
'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.',
|
||||
|
||||
@@ -477,8 +477,8 @@ export default function Show({
|
||||
</ActionBar>
|
||||
</div>
|
||||
))}
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
<div className="space-y-6 lg:col-span-2">
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
|
||||
<div className="min-w-0 space-y-6 lg:col-span-2">
|
||||
<Panel title="Detalhes do pedido">
|
||||
<dl className="grid gap-5 text-sm sm:grid-cols-3">
|
||||
<div>
|
||||
@@ -715,7 +715,7 @@ export default function Show({
|
||||
</Panel>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-6">
|
||||
<div className="min-w-0 space-y-6">
|
||||
{approvalRouting &&
|
||||
approvalRouting.status !== 'inactive' && (
|
||||
<Panel
|
||||
|
||||
@@ -14,6 +14,10 @@ import LegalChargeFields, {
|
||||
type LegalChargeDraft,
|
||||
} from '@/components/import-legal-charges';
|
||||
import { estimateMinor, estimateMoney } from '@/lib/import-estimate-money';
|
||||
import {
|
||||
specificRateLabel,
|
||||
specificRateMinor,
|
||||
} from '@/lib/import-legal-specific-rate';
|
||||
import { date, money } from '@/types/procurement';
|
||||
|
||||
type LegalData = {
|
||||
@@ -427,7 +431,8 @@ function ChargeEstimate({
|
||||
{['specific', 'maximum'].includes(charge.method) && (
|
||||
<label className="grid gap-1">
|
||||
Quantidade em {charge.quantity_unit} · taxa{' '}
|
||||
{money(charge.specific_minor)} por unidade
|
||||
{specificRateLabel(charge.specific_minor)} por
|
||||
unidade
|
||||
<input
|
||||
inputMode="decimal"
|
||||
className={controlClass}
|
||||
@@ -750,11 +755,15 @@ export default function ImportLegal(props: Props) {
|
||||
))}
|
||||
</Panel>
|
||||
<Panel
|
||||
title="Regras e fontes preservadas"
|
||||
title="Regras preparadas e publicadas"
|
||||
description="Uma nova preparação conserva a última publicação até ser validada. Retirar uma regra impede novas sugestões e conserva as decisões anteriores."
|
||||
>
|
||||
{props.rules.data.length === 0 && (
|
||||
<p>Ainda não existem fontes neste âmbito.</p>
|
||||
<p>
|
||||
Ainda não existem regras neste âmbito. Os diplomas
|
||||
disponíveis para consulta são apresentados
|
||||
separadamente.
|
||||
</p>
|
||||
)}
|
||||
{props.rules.data.map((rule) => (
|
||||
<article key={rule.id} className="space-y-2 border-b py-4">
|
||||
@@ -893,12 +902,13 @@ export default function ImportLegal(props: Props) {
|
||||
Preparar a partir do exemplar oficial
|
||||
</h3>
|
||||
<p className="text-sm">
|
||||
Transcrição da página 2180-(4) da Lei 8/2025,
|
||||
com início em 01/01/2026. Inclui apenas a taxa
|
||||
geral dessa edição; não é uma pauta consolidada
|
||||
nem determina isenções, preferências ou outras
|
||||
imposições. A preparação continua editável e
|
||||
exige gravação e decisão expressas.
|
||||
Transcrição do anexo da Lei 8/2025, páginas
|
||||
2180-(4) a (7), com início em 01/01/2026. Inclui
|
||||
apenas a taxa geral dessa edição; não é uma
|
||||
pauta consolidada nem determina isenções,
|
||||
preferências ou outras imposições. A preparação
|
||||
continua editável e exige gravação e decisão
|
||||
expressas.
|
||||
</p>
|
||||
{form.isDirty && (
|
||||
<p className="text-sm">
|
||||
@@ -907,56 +917,75 @@ export default function ImportLegal(props: Props) {
|
||||
existente será conservado.
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-2">
|
||||
{props.referenceDrafts?.map((draft) => (
|
||||
<Button
|
||||
key={`${draft.source_id}:${draft.code}`}
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-auto justify-start text-left whitespace-normal"
|
||||
disabled={
|
||||
<label className="grid gap-1">
|
||||
Código do anexo e fonte
|
||||
<select
|
||||
className={controlClass}
|
||||
value=""
|
||||
disabled={
|
||||
form.isDirty ||
|
||||
form.processing ||
|
||||
form.data.record_key !== null
|
||||
}
|
||||
onChange={(event) => {
|
||||
if (
|
||||
form.isDirty ||
|
||||
form.processing ||
|
||||
form.data.record_key !== null
|
||||
}
|
||||
onClick={() => {
|
||||
form.setData({
|
||||
...form.data,
|
||||
operation_key: '',
|
||||
record_key: null,
|
||||
version: 0,
|
||||
action: 'save',
|
||||
title: draft.title,
|
||||
official_reference:
|
||||
draft.official_reference,
|
||||
official_url:
|
||||
draft.official_url ?? '',
|
||||
citation: draft.citation,
|
||||
valid_from: draft.valid_from,
|
||||
valid_until: '',
|
||||
match_code: draft.code,
|
||||
suggested_code: draft.code,
|
||||
origin_country: '',
|
||||
sector: '',
|
||||
obligations: draft.obligations,
|
||||
document_types: [],
|
||||
reason: '',
|
||||
file: null,
|
||||
source_id: String(
|
||||
draft.source_id,
|
||||
),
|
||||
charges: chargeDrafts(
|
||||
draft.charges,
|
||||
),
|
||||
});
|
||||
form.clearErrors();
|
||||
}}
|
||||
>
|
||||
{draft.code} — {draft.description} —
|
||||
taxa geral {draft.rate_percent}%
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
return;
|
||||
const draft =
|
||||
props.referenceDrafts?.find(
|
||||
(item) =>
|
||||
`${item.source_id}:${item.code}` ===
|
||||
event.target.value,
|
||||
);
|
||||
if (!draft) return;
|
||||
form.setData({
|
||||
...form.data,
|
||||
operation_key: '',
|
||||
record_key: null,
|
||||
version: 0,
|
||||
action: 'save',
|
||||
title: draft.title,
|
||||
official_reference:
|
||||
draft.official_reference,
|
||||
official_url:
|
||||
draft.official_url ?? '',
|
||||
citation: draft.citation,
|
||||
valid_from: draft.valid_from,
|
||||
valid_until: '',
|
||||
match_code: draft.code,
|
||||
suggested_code: draft.code,
|
||||
origin_country: '',
|
||||
sector: '',
|
||||
obligations: draft.obligations,
|
||||
document_types: [],
|
||||
reason: '',
|
||||
file: null,
|
||||
source_id: String(draft.source_id),
|
||||
charges: chargeDrafts(
|
||||
draft.charges,
|
||||
),
|
||||
});
|
||||
form.clearErrors();
|
||||
}}
|
||||
>
|
||||
<option value="">
|
||||
Seleccione para preencher uma preparação
|
||||
</option>
|
||||
{props.referenceDrafts?.map((draft) => (
|
||||
<option
|
||||
key={`${draft.source_id}:${draft.code}`}
|
||||
value={`${draft.source_id}:${draft.code}`}
|
||||
>
|
||||
{draft.code} — {draft.description} —
|
||||
taxa geral {draft.rate_percent}% —
|
||||
fonte #{draft.source_id}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
<form
|
||||
@@ -983,7 +1012,7 @@ export default function ImportLegal(props: Props) {
|
||||
specific_minor:
|
||||
charge.specific_amount === ''
|
||||
? null
|
||||
: estimateMinor(
|
||||
: specificRateMinor(
|
||||
charge.specific_amount,
|
||||
),
|
||||
quantity_unit: charge.quantity_unit || null,
|
||||
@@ -1151,13 +1180,15 @@ export default function ImportLegal(props: Props) {
|
||||
<Button disabled={form.processing}>
|
||||
Guardar preparação para validação aduaneira
|
||||
</Button>
|
||||
{form.data.record_key && (
|
||||
{(form.isDirty || form.data.record_key) && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => form.reset()}
|
||||
>
|
||||
Preparar outra regra
|
||||
{form.data.record_key
|
||||
? 'Preparar outra regra'
|
||||
: 'Limpar preparação'}
|
||||
</Button>
|
||||
)}
|
||||
</form>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="pt-MZ">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title>Acesso reservado · SGC</title>
|
||||
<style>
|
||||
:root { color-scheme: light dark; font-family: system-ui, sans-serif; }
|
||||
body { margin: 0; background: #f7f9f9; color: #172524; }
|
||||
main { box-sizing: border-box; width: min(100%, 40rem); margin: 12vh auto; padding: 1.5rem; overflow-wrap: anywhere; }
|
||||
.brand { color: #0b6b62; font-weight: 600; }
|
||||
.code { margin-top: 3rem; color: #54625f; }
|
||||
h1 { font-size: clamp(1.75rem, 5vw, 2.5rem); line-height: 1.2; }
|
||||
p { line-height: 1.6; }
|
||||
a { display: inline-block; margin-top: 1rem; padding: .75rem 1rem; border-radius: .5rem; background: #0b6b62; color: white; text-decoration: none; font-weight: 600; }
|
||||
a:focus-visible { outline: 3px solid #168b80; outline-offset: 4px; }
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body { background: #101b19; color: #f1f6f4; }
|
||||
.brand { color: #85d3c8; }
|
||||
.code { color: #b3c2bd; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main aria-labelledby="access-title">
|
||||
<p class="brand">SGC · Sistema de Gestão de Contratações</p>
|
||||
<p class="code">403</p>
|
||||
<h1 id="access-title">Acesso reservado</h1>
|
||||
<p>A sua conta não tem acesso a esta área.</p>
|
||||
<p>Regresse ao painel para continuar nas opções disponíveis.</p>
|
||||
<a href="{{ url('/dashboard') }}">Voltar ao painel</a>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -90,9 +90,6 @@ try {
|
||||
$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-reference-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLegalReferenceDraftsTest.php', 'tests/Feature/ImportLegalRulesTest.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']];
|
||||
@@ -176,6 +173,9 @@ try {
|
||||
if (in_array('--private-audit-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PrivateAuditExporterTest.php', 'tests/Feature/PrivateAuditSourcesTest.php', 'tests/Feature/PrivateAuditAccessTest.php']];
|
||||
}
|
||||
if (in_array('--legal-reference-focused', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLegalReferenceDraftsTest.php', 'tests/Feature/ImportLegalRulesTest.php']];
|
||||
}
|
||||
if (in_array('--requisition-cycles-import-regression', $argv, true)) {
|
||||
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportEstimatesTest.php', 'tests/Feature/ImportLandedCostsTest.php']];
|
||||
}
|
||||
@@ -282,7 +282,7 @@ try {
|
||||
$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) || in_array('--expiry-native-review', $argv, true)) {
|
||||
if (in_array('--legal-http', $argv, true) || in_array('--legal-reference-http', $argv, true) || in_array('--legal-native-review', $argv, true) || in_array('--expiry-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)));
|
||||
@@ -292,7 +292,7 @@ try {
|
||||
$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('--expiry-native-review', $argv, true) ? 'expiry-review' : (in_array('--legal-native-review', $argv, true) ? 'legal-review' : 'legal-http'), ...$values]];
|
||||
[PHP_BINARY, 'tests/Concurrency/import-legal-http-worker.php', $database, in_array('--legal-reference-http', $argv, true) ? 'legal-reference-http' : (in_array('--expiry-native-review', $argv, true) ? 'expiry-review' : (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']];
|
||||
|
||||
@@ -8,6 +8,14 @@ import { createServer } from 'node:net';
|
||||
|
||||
const id = crypto.randomBytes(6).toString('hex');
|
||||
const workspace = path.resolve('C:/laragon/www/compras');
|
||||
const reviewDurationArgs = process.argv.filter(flag => flag.startsWith('--review-minutes='));
|
||||
const reviewDurationMinutes = reviewDurationArgs.length === 0 ? 20 : Number(reviewDurationArgs[0].slice('--review-minutes='.length));
|
||||
if (reviewDurationArgs.length > 1 || !Number.isInteger(reviewDurationMinutes) || reviewDurationMinutes < 1 || reviewDurationMinutes > 60 || (reviewDurationArgs.length > 0 && !process.argv.includes('--native-review'))) throw Error('Native review duration must be one explicit value from1to60minutes');
|
||||
if (process.argv.includes('--legal-reference-preview') && (!process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime') || !process.argv.some(flag => ['--native-review', '--native-review-http-only'].includes(flag)))) throw Error('Legal preview requires the owned native review with complete pinned private composition');
|
||||
if (process.argv.includes('--private-audit-recovery') && (!process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime') || process.argv.some(flag => ['--recovery-only', '--race-only', '--native-review', '--native-review-http-only'].includes(flag)))) throw Error('Private audit recovery requires its own complete pinned isolated composition');
|
||||
if (process.argv.includes('--print-pagination-preview') && (!process.argv.includes('--native-review') || !process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime'))) throw Error('Print pagination requires the owned native preview and complete pinned composition');
|
||||
if (process.argv.includes('--native-office-preview') && (!process.argv.includes('--native-review') || !process.argv.includes('--integrated-schema') || !process.argv.includes('--frozen-runtime') || process.argv.some(flag => ['--print-pagination-preview', '--legal-reference-preview'].includes(flag)))) throw Error('Office preview requires its own complete pinned native QA composition');
|
||||
if (process.argv.includes('--specific-rate-preview') && (!process.argv.includes('--legal-reference-preview') || !process.argv.includes('--native-review'))) throw Error('Specific coefficient preview requires the owned legal native review');
|
||||
if (path.resolve(process.cwd()) !== workspace) throw Error('Compras workspace required');
|
||||
if (process.argv.includes('--integrated-cycles-only') && !process.argv.includes('--integrated-schema')) throw Error('Integrated cycles require the complete isolated schema composition');
|
||||
if (process.argv.includes('--integrated-orders-only') && !process.argv.includes('--integrated-schema')) throw Error('Integrated orders require the complete isolated schema composition');
|
||||
@@ -108,7 +116,10 @@ try {
|
||||
COMMON_BUDGET_PATH: frozenRuntime ? path.join(budgetRoot, 'budget-control') : 'C:/laragon/www/sgf-tempo/packages/budget-control',
|
||||
RQ01_LEDGER_QA_SOURCE: frozenRuntime ? path.join(financeRoot, 'general-ledger') : 'C:/laragon/www/sgf-tempo/packages/general-ledger',
|
||||
RQ01_LEDGER_INTEGRATED_SCHEMA: process.argv.includes('--integrated-schema') ? '1' : '0',
|
||||
RQ01_NATIVE_OFFICE_JOURNEY: process.argv.includes('--native-office-http-only') ? '1' : '0' };
|
||||
RQ01_NATIVE_OFFICE_JOURNEY: process.argv.some(flag => ['--native-office-http-only', '--native-office-preview'].includes(flag)) ? '1' : '0',
|
||||
RQ01_QA_LEGAL_REFERENCE: process.argv.includes('--legal-reference-preview') ? '1' : '0',
|
||||
RQ01_QA_SPECIFIC_RATE: process.argv.includes('--specific-rate-preview') ? '1' : '0',
|
||||
RQ01_QA_PRINT_PAGINATION: process.argv.includes('--print-pagination-preview') ? '1' : '0' };
|
||||
delete environment.COMMON_FINANCE_BUNDLE_ROOT;
|
||||
delete environment.COMMON_FINANCE_BUNDLE_SHA256;
|
||||
if (frozenRuntime) {
|
||||
@@ -116,11 +127,13 @@ try {
|
||||
environment.COMMON_FINANCE_BUNDLE_SHA256 = financePin;
|
||||
}
|
||||
const raceOnly = process.argv.includes('--race-only');
|
||||
const recoveryOnly = process.argv.includes('--recovery-only');
|
||||
const auditRecovery = process.argv.includes('--private-audit-recovery');
|
||||
const recoveryOnly = process.argv.includes('--recovery-only') || auditRecovery;
|
||||
const nativeAuditSchemaOnly = process.argv.includes('--audit-schema-only');
|
||||
const nativeFixtureOnly = process.argv.includes('--native-review-fixture-only');
|
||||
const nativeHttpOnly = process.argv.includes('--native-review-http-only');
|
||||
const nativeOfficeOnly = process.argv.includes('--native-office-http-only');
|
||||
const nativeOfficePreview = process.argv.includes('--native-office-preview');
|
||||
const nativeOfficeOnly = process.argv.includes('--native-office-http-only') || nativeOfficePreview;
|
||||
const nativeReview = process.argv.includes('--native-review') || nativeFixtureOnly || nativeHttpOnly || nativeOfficeOnly || nativeAuditSchemaOnly;
|
||||
const setupOnly = raceOnly || recoveryOnly || nativeReview;
|
||||
const args = setupOnly ? ['artisan', 'migrate', '--force', '--no-interaction'] : process.argv.includes('--integrated-release-journeys') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', 'tests/Feature/RequisitionBudgetCyclesTest.php', 'tests/Feature/PurchaseAwardOrderTest.php', 'tests/Feature/ImportLandedCostsTest.php', '--filter=RequisitionBudgetCyclesTest|ImportLandedCostsTest|native office purchase|native partial-order|native consolidated order|native delivery analysis'] : process.argv.includes('--integrated-import-costs-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/ImportLandedCostsTest.php'] : process.argv.includes('--integrated-orders-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=native partial-order|native consolidated order|native delivery analysis'] : process.argv.includes('--integrated-cycles-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php'] : process.argv.includes('--office-process-only') ? ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', '--filter=native office purchase'] : ['vendor/bin/pest', '--compact', 'tests/Feature/RequisitionLedgerAccountsTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
|
||||
@@ -137,6 +150,10 @@ try {
|
||||
if (setupOnly) throw Error('Private controllers are focused native Pest regressions');
|
||||
args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=budget consultations|purchase control preparations');
|
||||
}
|
||||
if (process.argv.includes('--expiry-history-only')) {
|
||||
if (setupOnly || !frozenRuntime || !process.argv.includes('--integrated-schema')) throw Error('Expiry history regression requires the complete pinned isolated composition');
|
||||
args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php', '--filter=native expiry returns the same request');
|
||||
}
|
||||
const result = spawnSync('php', args, {
|
||||
cwd: process.cwd(), windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: environment,
|
||||
});
|
||||
@@ -153,13 +170,15 @@ try {
|
||||
}
|
||||
if (result.status === 0 && recoveryOnly) {
|
||||
const worker = (mode, env, payload = null) => {
|
||||
const args = ['tests/Concurrency/requisition-account-worker.php', env.DB_DATABASE, mode];
|
||||
const args = [auditRecovery ? 'tests/Concurrency/private-audit-recovery-worker.php' : 'tests/Concurrency/requisition-account-worker.php', env.DB_DATABASE, mode];
|
||||
if (payload !== null) args.push(JSON.stringify(payload));
|
||||
const result = spawnSync('php', args, { cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env });
|
||||
if (result.status !== 0) throw Error('Account recovery worker failed: ' + (result.stderr || result.stdout || '').replaceAll(password, '[private]'));
|
||||
return JSON.parse(result.stdout);
|
||||
};
|
||||
const fixture = worker('prepare-recovery', environment);
|
||||
const recoveryEnvironment = auditRecovery ? { ...environment, SGC_REQUISITION_QA_ROOT: root } : environment;
|
||||
const fixture = worker(auditRecovery ? 'prepare' : 'prepare-recovery', recoveryEnvironment);
|
||||
if (auditRecovery) fs.cpSync(path.join(root, 'audit-source-files'), path.join(root, 'audit-backup-files'), { recursive: true, errorOnExist: true, force: false });
|
||||
const pgCommand = (binary, args, env) => {
|
||||
const result = spawnSync(path.join(pg, binary), args, { windowsHide: true, encoding: 'utf8',
|
||||
env: { ...process.env, PGHOST: '127.0.0.1', PGPORT: '55439', PGUSER: env.DB_USERNAME, PGPASSWORD: env.DB_PASSWORD } });
|
||||
@@ -176,9 +195,16 @@ try {
|
||||
sql(`CREATE DATABASE ${targetDatabase} OWNER ${targetRole};`);
|
||||
restoreDatabase = targetDatabase;
|
||||
sql(`REVOKE ALL ON DATABASE ${targetDatabase} FROM PUBLIC;`);
|
||||
const restoredEnvironment = { ...environment, DB_DATABASE: targetDatabase, DB_USERNAME: targetRole, DB_PASSWORD: restoredPassword };
|
||||
const restoredEnvironment = { ...recoveryEnvironment, DB_DATABASE: targetDatabase, DB_USERNAME: targetRole, DB_PASSWORD: restoredPassword };
|
||||
pgCommand('pg_restore.exe', ['--no-owner', '--no-acl', '--exit-on-error', '--dbname='+targetDatabase, dump], restoredEnvironment);
|
||||
console.log(JSON.stringify(worker('verify-recovery', restoredEnvironment, fixture)));
|
||||
if (auditRecovery) {
|
||||
// All paths are literal children of the guarded newly-created task root.
|
||||
if (path.dirname(path.resolve(root)) !== privateParent || path.basename(root) !== `rq01-ledger-qa-${id}`) throw Error('Audit recovery root refused');
|
||||
fs.renameSync(path.join(root, 'audit-source-files'), path.join(root, 'audit-source-unavailable'));
|
||||
fs.cpSync(path.join(root, 'audit-backup-files'), path.join(root, 'audit-restored-files'), { recursive: true, errorOnExist: true, force: false });
|
||||
}
|
||||
console.log(JSON.stringify({ source_database: database, restored_database: targetDatabase,
|
||||
...worker(auditRecovery ? 'verify' : 'verify-recovery', restoredEnvironment, fixture) }));
|
||||
}
|
||||
if (result.status === 0 && nativeReview) {
|
||||
for (const relative of ['public', 'storage/framework/sessions', 'storage/framework/views', 'storage/framework/cache/data', 'storage/logs', 'storage/app/private']) {
|
||||
@@ -191,10 +217,10 @@ try {
|
||||
if (seed.status !== 0) throw Error('Native review fixture failed: '+(seed.stderr || seed.stdout || '').replaceAll(password, '[private]'));
|
||||
const fixture = JSON.parse(seed.stdout);
|
||||
fs.writeFileSync(path.join(root, 'native-review.json'), JSON.stringify(fixture));
|
||||
const assets = path.join(privateParent, 'sgc-private-audit-help-qa-20261128');
|
||||
const assets = path.join(privateParent, 'sgc-legal-specific-precision-qa-20261128');
|
||||
const manifest = fs.readFileSync(path.join(assets, 'manifest.json'));
|
||||
const manifestHash = crypto.createHash('sha256').update(manifest).digest('hex');
|
||||
if (manifestHash !== 'fa87e37a3626ef75d22b5248dce9a0af2bad68c967e6f99bb64bc426a68f6aaf') throw Error('Unexpected private review manifest');
|
||||
if (manifestHash !== '9d415ba790aa602b36372d310a4eaa3426670fc521f15efb4166d782e170ac8e') throw Error('Unexpected private review manifest');
|
||||
for (const entry of Object.values(JSON.parse(manifest))) {
|
||||
if (!fs.existsSync(path.join(assets, entry.file))) throw Error('Private review asset missing');
|
||||
}
|
||||
@@ -256,7 +282,8 @@ try {
|
||||
return JSON.parse(state.stdout);
|
||||
}, value => console.log(JSON.stringify(value)));
|
||||
console.log(JSON.stringify({ private_native_office_http_verified: true, ...result, private_manifest_sha256: manifestHash }));
|
||||
} else if (nativeHttpOnly) {
|
||||
}
|
||||
if (nativeHttpOnly) {
|
||||
const { verifyNativeReviewHttp } = await import('./requisition-native-http-check.mjs');
|
||||
const pageAssets = ['resources/js/pages/audit/private.tsx', 'resources/js/pages/supply/index.tsx', 'resources/js/pages/purchase-controls/index.tsx', 'resources/js/pages/purchase-controls/orders.tsx', 'resources/js/pages/budgets/index.tsx', 'resources/js/pages/conflicts/index.tsx', 'resources/js/pages/conflicts/show.tsx', 'resources/js/pages/payments/index.tsx', 'resources/js/pages/stock/index.tsx', 'resources/js/pages/stock/operations.tsx', 'resources/js/pages/stock/lots.tsx', 'resources/js/pages/stock/reversals.tsx', 'resources/js/pages/stock/dispositions.tsx', 'resources/js/pages/equipment/index.tsx', 'resources/js/pages/investment/index.tsx', 'resources/js/pages/company/parameters.tsx', 'resources/js/pages/company/index.tsx', 'resources/js/pages/company/setup.tsx', 'resources/js/pages/requisitions/operational-orders.tsx', 'resources/js/pages/requisitions/urgent-stock.tsx']
|
||||
.map(key => JSON.parse(manifest)[key]);
|
||||
@@ -271,10 +298,10 @@ try {
|
||||
},
|
||||
});
|
||||
console.log(JSON.stringify({ private_native_http_verified: true, ...result, private_manifest_sha256: manifestHash }));
|
||||
} else {
|
||||
} else if (!nativeOfficeOnly || nativeOfficePreview) {
|
||||
const stopFile = path.join(root, 'stop-review');
|
||||
console.log(JSON.stringify({ private_native_review_running: true, url, stop_file: stopFile, ...fixture, private_manifest_sha256: manifestHash }));
|
||||
const until = Date.now() + 20 * 60 * 1000;
|
||||
console.log(JSON.stringify({ private_native_review_running: true, url, stop_file: stopFile, review_minutes: reviewDurationMinutes, ...fixture, private_manifest_sha256: manifestHash }));
|
||||
const until = Date.now() + reviewDurationMinutes * 60 * 1000;
|
||||
while (!fs.existsSync(stopFile) && Date.now() < until) {
|
||||
if (reviewServer.exitCode !== null) throw Error('Private native review stopped unexpectedly');
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
|
||||
@@ -223,6 +223,7 @@ export async function verifyOfficePurchaseHttp(origin, fixture, readState, progr
|
||||
&& !Object.hasOwn(report.props, 'invoices') && !Object.hasOwn(report.props, 'payments') && !Object.hasOwn(report.props, 'bank_snapshot'), 'requester process does not disclose financial or bank records');
|
||||
for (const client of Object.values(clients)) await client.logout();
|
||||
return { checks, native_post_requests: commands, fortify_sessions: Object.keys(clients).length,
|
||||
request_id: requestId, order_id: orderId, invoice_id: invoiceId, payment_ids: current.payments.map(p => p.id),
|
||||
request_total_minor: current.request.total_minor, order_total_minor: current.order.total_minor, invoice_total_minor: current.invoice.total_minor,
|
||||
confirmed_payments_minor: current.payments.map(p => p.amount_minor), outstanding_minor: current.invoice.outstanding_minor,
|
||||
budget_consumed_minor: current.budget.balance.consumed_minor, budget_available_minor: current.budget.balance.available_minor,
|
||||
|
||||
@@ -8,6 +8,8 @@ use App\Services\ImportBankSupport;
|
||||
use App\Services\ImportEstimates;
|
||||
use App\Services\ImportLegalEstimates;
|
||||
use App\Services\ImportLegalRules;
|
||||
use App\Services\RequisitionExpiry;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use App\Services\SupplyPlanning;
|
||||
use GuzzleHttp\Client;
|
||||
use GuzzleHttp\Cookie\CookieJar;
|
||||
@@ -29,6 +31,7 @@ $corpus = realpath($argv[3] ?? '');
|
||||
$candidateRelative = $argv[4] ?? '';
|
||||
$candidateHash = $argv[5] ?? '';
|
||||
$expiryReview = ($argv[2] ?? '') === 'expiry-review';
|
||||
$referenceHttp = ($argv[2] ?? '') === 'legal-reference-http';
|
||||
$reviewMode = ($argv[2] ?? '') === 'legal-review' || $expiryReview;
|
||||
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)
|
||||
@@ -40,8 +43,9 @@ 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) {
|
||||
$files = $referenceHttp ? [$corpus.'/novas/BR_248_I_SERIE_SUPLEMENTO_2025.pdf']
|
||||
: glob(str_replace('\\', '/', $corpus).'/Legislacao/2022/12 Dezembro/series-i/br-series-i-29-12-2022-*.pdf');
|
||||
if ($files === false || count($files) !== 1 || ! is_file($files[0]) || filesize($files[0]) < 1 || (! $referenceHttp && filesize($files[0]) <= 2097152)) {
|
||||
throw new LogicException('Select the complete shared official journal, not a small extracted example.');
|
||||
}
|
||||
$path = $files[0];
|
||||
@@ -103,7 +107,7 @@ try {
|
||||
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',
|
||||
'official_reference' => $referenceHttp ? 'BR I Série 248, suplemento, 29/12/2025 — exemplar integral real partilhado' : '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));
|
||||
@@ -124,6 +128,9 @@ try {
|
||||
}
|
||||
$props = json_decode((string) $page->getBody(), true, 64, JSON_THROW_ON_ERROR)['props'] ?? [];
|
||||
$source = SupplyRecord::query()->where('kind', 'import_legal_source')->sole();
|
||||
if (count($props['referenceDrafts'] ?? []) !== ($referenceHttp ? 48 : 0) || ($props['referenceDraftWarnings'] ?? []) !== []) {
|
||||
throw new RuntimeException('The native legal workspace did not preserve the edition-specific documentary draft scope.');
|
||||
}
|
||||
$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']]);
|
||||
@@ -143,6 +150,7 @@ try {
|
||||
'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];
|
||||
$result['documentary_reference_drafts'] = count($props['referenceDrafts'] ?? []);
|
||||
if ($reviewMode) {
|
||||
// Existing factory password is confined to guarded, disposable synthetic QA identities.
|
||||
$reviewer = $f['otherReceiver'];
|
||||
@@ -188,10 +196,10 @@ try {
|
||||
supplyGrant($reviewer, ['admin', 'procurement', 'requester', 'import_read', 'import_prepare', 'import_customs']);
|
||||
$head = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
|
||||
supplyGrant($head, ['department_head']);
|
||||
app(\App\Services\RequisitionExpiry::class)->savePolicy($reviewer, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
|
||||
app(RequisitionExpiry::class)->savePolicy($reviewer, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
|
||||
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => null, 'profile_ids' => []]],
|
||||
'reason' => 'Política estritamente sintética para revisão visual do ciclo']);
|
||||
$workflow = app(\App\Services\RequisitionWorkflow::class);
|
||||
$workflow = app(RequisitionWorkflow::class);
|
||||
$expiryRequest = $workflow->save($reviewer, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id, 'priority' => 'normal',
|
||||
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Ensaio visual sintético da devolução e nova submissão',
|
||||
'items' => [['description' => 'Material sintético do ciclo', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
use App\Models\PrivateAuditExport;
|
||||
use App\Models\SupplierDocument;
|
||||
use App\Models\User;
|
||||
use App\Services\PrivateAuditAccess;
|
||||
use App\Services\PrivateAuditExporter;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
use Tempo\Finance\GeneralLedger\LedgerSchema;
|
||||
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
$root = realpath(getenv('SGC_REQUISITION_QA_ROOT') ?: '');
|
||||
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
|
||||
$mode = $argv[2] ?? '';
|
||||
$database = $argv[1] ?? '';
|
||||
if ($root === false || $boundary === false || dirname($root) !== $boundary
|
||||
|| ! preg_match('/^rq01-ledger-qa-[a-f0-9]{12}$/D', basename($root))
|
||||
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)
|
||||
|| ! in_array($mode, ['prepare', 'verify'], true)) {
|
||||
throw new LogicException('Owned private audit recovery root required.');
|
||||
}
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->useStoragePath($root.'/audit-worker-storage');
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql'
|
||||
|| DB::connection()->getConfig('host') !== '127.0.0.1'
|
||||
|| (string) DB::connection()->getConfig('port') !== '55439'
|
||||
|| DB::connection()->getDatabaseName() !== $database) {
|
||||
throw new LogicException('Only the owned synthetic PostgreSQL recovery is permitted.');
|
||||
}
|
||||
require_once __DIR__.'/../Support/RequisitionLedgerQaRuntime.php';
|
||||
$source = requisitionLedgerQaSource();
|
||||
if ($source === null || getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') !== '1') {
|
||||
throw new LogicException('Complete private composition required.');
|
||||
}
|
||||
require_once $source.'/bootstrap.php';
|
||||
LedgerSchema::assertSynthetic(DB::connection());
|
||||
config(['private-audit.qa_enabled' => true]);
|
||||
$files = $root.($mode === 'prepare' ? '/audit-source-files' : '/audit-restored-files');
|
||||
foreach (['local', 'supplier_documents', 'receipt_documents'] as $disk) {
|
||||
config(['filesystems.disks.'.$disk => ['driver' => 'local', 'root' => $files.'/'.$disk, 'throw' => true]]);
|
||||
Storage::forgetDisk($disk);
|
||||
}
|
||||
$snapshot = static function (): array {
|
||||
return DB::transaction(function () {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
$frames = [];
|
||||
foreach (DB::select("select tablename from pg_tables where schemaname='public' order by tablename") as $table) {
|
||||
$name = str_replace('"', '""', $table->tablename);
|
||||
$rows = DB::select('select row_to_json(t)::text as row from "'.$name.'" t order by row_to_json(t)::text');
|
||||
$frames[$table->tablename] = hash('sha256', json_encode([DB::getSchemaBuilder()->getColumnListing($table->tablename), array_column($rows, 'row')], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
return $frames;
|
||||
});
|
||||
};
|
||||
$service = app(PrivateAuditExporter::class);
|
||||
if ($mode === 'prepare') {
|
||||
LedgerSchema::install(DB::connection());
|
||||
require_once __DIR__.'/../Support/IntegratedPurchasingQaSchema.php';
|
||||
integratedPurchasingQaSchema();
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||
$f = receiptFixture();
|
||||
$actor = $f['issuer'];
|
||||
auth()->guard()->setUser($actor);
|
||||
supplyGrant($actor, array_column(PrivateAuditAccess::FAMILIES, 'permission'));
|
||||
$bytes = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6E4sAAAAASUVORK5CYII=');
|
||||
$path = $actor->tenant_id.'/'.$f['order']->supplier_id.'/synthetic-recovery.png';
|
||||
Storage::disk('supplier_documents')->put($path, $bytes);
|
||||
$document = SupplierDocument::query()->create(['tenant_id' => $actor->tenant_id, 'supplier_id' => $f['order']->supplier_id,
|
||||
'uploaded_by' => $actor->id, 'document_type' => 'other', 'original_name' => 'synthetic-recovery.png', 'path' => $path,
|
||||
'mime_type' => 'image/png', 'size' => strlen($bytes), 'sha256' => hash('sha256', $bytes)]);
|
||||
$input = ['operation_key' => (string) Str::uuid(), 'families' => array_keys(PrivateAuditAccess::FAMILIES), 'purpose' => 'Synthetic SQL and private files recovery verification'];
|
||||
$export = $service->generate($actor, $input);
|
||||
$service->verifiedPath($actor, $export);
|
||||
echo json_encode(['actor' => $actor->id, 'export' => $export->id, 'input' => $input, 'sha256' => $export->sha256,
|
||||
'size' => $export->size, 'document' => $document->id, 'source_sha256' => hash('sha256', $bytes), 'snapshot' => $snapshot()], JSON_THROW_ON_ERROR);
|
||||
exit;
|
||||
}
|
||||
$fixture = json_decode($argv[3], true, 64, JSON_THROW_ON_ERROR);
|
||||
if ($snapshot() !== $fixture['snapshot']) {
|
||||
throw new RuntimeException('Restored audit database differs in tables, columns or rows.');
|
||||
}
|
||||
$actor = User::query()->findOrFail($fixture['actor']);
|
||||
auth()->guard()->setUser($actor);
|
||||
$export = PrivateAuditExport::query()->findOrFail($fixture['export']);
|
||||
$path = $service->verifiedPath($actor, $export);
|
||||
$document = SupplierDocument::query()->findOrFail($fixture['document']);
|
||||
if (hash_file('sha256', $path) !== $fixture['sha256'] || filesize($path) !== $fixture['size']
|
||||
|| hash('sha256', Storage::disk('supplier_documents')->get($document->path)) !== $fixture['source_sha256']
|
||||
|| $service->generate($actor, $fixture['input'])->id !== $export->id) {
|
||||
throw new RuntimeException('Restored archive, original or replay differs.');
|
||||
}
|
||||
$zip = new ZipArchive;
|
||||
if ($zip->open($path, ZipArchive::RDONLY) !== true) {
|
||||
throw new RuntimeException('Restored archive cannot be read.');
|
||||
}
|
||||
try {
|
||||
if (hash('sha256', $zip->getFromName('originais/purchasing/supplier_documents/'.$document->id.'.png')) !== $fixture['source_sha256']) {
|
||||
throw new RuntimeException('Original inside restored archive differs.');
|
||||
}
|
||||
} finally {
|
||||
$zip->close();
|
||||
}
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
DB::table('organization_memberships')->where('user_id', $actor->id)->update(['expires_at' => now()->subMinute()]);
|
||||
try {
|
||||
$service->verifiedPath($actor, $export);
|
||||
throw new RuntimeException('Restored archive ignored current revoked authority.');
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
if ($error->getStatusCode() !== 403) {
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
DB::rollBack();
|
||||
}
|
||||
if ($snapshot() !== $fixture['snapshot']) {
|
||||
throw new RuntimeException('Audit recovery verification changed restored facts.');
|
||||
}
|
||||
echo json_encode(['tables_equal' => count($fixture['snapshot']), 'archive_bytes_and_hash_equal' => true,
|
||||
'original_file_and_archived_copy_equal' => true, 'replay_without_effects' => true,
|
||||
'current_revocation_refused' => true, 'sql_and_separate_private_files_restored' => true,
|
||||
'source_file_tree_absent_during_verification' => ! is_dir($root.'/audit-source-files'), 'operational_changes' => false], JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -39,7 +39,7 @@ config(['requisition-accounts.qa_enabled' => true]);
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
if ($mode === 'prepare-native-review') {
|
||||
require_once __DIR__.'/../Support/RequisitionAccountsNativeReview.php';
|
||||
echo json_encode(requisitionAccountsNativeReviewFixture(getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1', getenv('RQ01_NATIVE_OFFICE_JOURNEY') === '1'), JSON_THROW_ON_ERROR);
|
||||
echo json_encode(requisitionAccountsNativeReviewFixture(getenv('RQ01_LEDGER_INTEGRATED_SCHEMA') === '1', getenv('RQ01_NATIVE_OFFICE_JOURNEY') === '1', getenv('RQ01_QA_LEGAL_REFERENCE') === '1', getenv('RQ01_QA_PRINT_PAGINATION') === '1'), JSON_THROW_ON_ERROR);
|
||||
exit;
|
||||
}
|
||||
if ($mode === 'describe-private-audit-schema') {
|
||||
|
||||
@@ -110,6 +110,17 @@ test('allocation enforces current Finance access and refuses unavailable or unau
|
||||
expect(SupplyRecord::query()->where('kind', 'expense_allocation')->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('denied expense attribution provides a Portuguese return path without exposing the financial source or changing JSON refusals', function () {
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$url = '/pagamentos/'.$this->payment->id.'/categorias';
|
||||
$this->get($url)->assertForbidden()->assertSee('Acesso reservado')->assertSee('Voltar ao painel')
|
||||
->assertSee('lang="pt-MZ"', false)->assertDontSee($this->f['invoice']->number)
|
||||
->assertDontSee('TEST-PAY-ACCOUNT')->assertDontSee('TEST-EXT-01');
|
||||
$this->getJson($url)->assertForbidden()->assertJsonStructure(['message'])
|
||||
->assertDontSee('<!DOCTYPE html>', false)->assertDontSee('TEST-PAY-ACCOUNT');
|
||||
expect(SupplyRecord::query()->where('kind', 'expense_allocation')->count())->toBe(0);
|
||||
});
|
||||
|
||||
test('incomplete confirmation or missing allocation audit keeps analytical attribution indeterminate', function () {
|
||||
$actor = $this->f['validator'];
|
||||
$this->service->save($actor, $this->payment->id, $this->input);
|
||||
|
||||
@@ -59,6 +59,50 @@ test('unknown rates and missing bases never become zero while explicit non-appli
|
||||
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('specific coefficients preserve fractional cents and round only the final exact charge', function () {
|
||||
$amounts = app(ImportLegalAmounts::class);
|
||||
$charge = legalCharge(['method' => 'specific', 'rate_percent' => null, 'specific_minor' => '1.33', 'quantity_unit' => 'g']);
|
||||
// Synthetic quantity: 600 L * 10.6 g/100 ml * 10 = 63600 g.
|
||||
// Coefficient0.0133 MZN/g corresponds exactly to1.33 cents/g.
|
||||
$base = ['value_minor' => null, 'quantity' => '63600.000000', 'quantity_unit' => 'g', 'source' => 'Synthetic documented quantity and concentration; no implicit conversion'];
|
||||
expect($amounts->definitions([$charge])[0]['specific_minor'])->toBe('1.33')
|
||||
->and($amounts->calculate([$charge], ['synthetic-duty' => $base])['total_minor'])->toBe(84588)
|
||||
->and($amounts->calculate([[...$charge, 'specific_minor' => '0.99']], ['synthetic-duty' => $base])['total_minor'])->toBe(62964);
|
||||
foreach (['0.499999' => 0, '0.500000' => 1] as $coefficient => $expected) {
|
||||
expect($amounts->calculate([[...$charge, 'specific_minor' => $coefficient]], ['synthetic-duty' => [...$base, 'quantity' => '1']])['total_minor'])->toBe($expected);
|
||||
}
|
||||
expect($amounts->definitions([[...$charge, 'specific_minor' => '125.000000']])[0]['specific_minor'])->toBe(125);
|
||||
foreach (['0.0000001', '1e2', '-0.1', '100000000000000.000001', 0.99] as $invalid) {
|
||||
expect(fn () => $amounts->definitions([[...$charge, 'specific_minor' => $invalid]]))->toThrow(ValidationException::class);
|
||||
}
|
||||
$maximum = [...$charge, 'method' => 'maximum', 'rate_percent' => '7.5', 'specific_minor' => '0.99'];
|
||||
expect($amounts->calculate([$maximum], ['synthetic-duty' => [...$base, 'value_minor' => 10001, 'quantity' => '1000']])['total_minor'])->toBe(990);
|
||||
});
|
||||
|
||||
test('native fractional specific estimates preserve the coefficient source and replay without financial effects', function () {
|
||||
$rules = app(ImportLegalRules::class);
|
||||
$charge = legalCharge(['method' => 'specific', 'rate_percent' => null, 'specific_minor' => '0.99', 'quantity_unit' => 'g']);
|
||||
$draft = $rules->save($this->f['issuer'], importLegalQaInput(['charges' => [$charge]]), importLegalQaFile());
|
||||
$rule = $rules->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1,
|
||||
'action' => 'publish', 'reason' => 'Synthetic fractional coefficient verification, no real tax activation']);
|
||||
$before = [];
|
||||
foreach (['budget_entries', 'invoices', 'stock_movements'] as $table) {
|
||||
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
|
||||
}
|
||||
$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' => null, 'quantity' => '63600', 'quantity_unit' => 'g', 'source' => 'Synthetic explicit sugar mass']],
|
||||
'reason' => 'Synthetic exact coefficient estimate without a budget or stock effect'];
|
||||
$service = app(ImportLegalEstimates::class);
|
||||
$record = $service->save($this->f['issuer'], $this->f['r'], $input);
|
||||
expect($rule->data['charges'][0]['specific_minor'])->toBe('0.99')
|
||||
->and($record->snapshot['result']['total_minor'])->toBe(62964)
|
||||
->and($service->save($this->f['issuer'], $this->f['r'], $input)->id)->toBe($record->id);
|
||||
foreach ($before as $table => $rows) {
|
||||
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
|
||||
}
|
||||
});
|
||||
|
||||
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());
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<?php
|
||||
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Services\ImportLegalAmounts;
|
||||
use App\Services\ImportLegalReferenceDrafts;
|
||||
use App\Services\ImportLegalRules;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
@@ -36,7 +37,7 @@ test('a supplied official edition offers exact documentary drafts without publis
|
||||
new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true));
|
||||
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
|
||||
$drafts = $workspace['referenceDrafts'];
|
||||
expect($drafts)->toHaveCount(11)
|
||||
expect($drafts)->toHaveCount(48)
|
||||
->and(array_column($drafts, 'code'))->toContain('3506.91.20', '7604.10.10')
|
||||
->and($drafts[0]['rate_percent'])->toBe('20')
|
||||
->and($drafts[2]['rate_percent'])->toBe('7.5')
|
||||
@@ -44,9 +45,28 @@ test('a supplied official edition offers exact documentary drafts without publis
|
||||
->and($drafts[0]['citation'])->toContain('2180-(4)')
|
||||
->and($drafts[0]['source_id'])->toBe($source->id)
|
||||
->and($drafts[0]['charges'][0]['kind'])->toBe('duty')
|
||||
->and($drafts[0]['charges'])->toHaveCount(4)
|
||||
->and($workspace['referenceDraftWarnings'])->toBe([])
|
||||
->and(SupplyRecord::query()->where('kind', 'import_legal_rule')->count())->toBe(0)
|
||||
->and(json_encode($workspace['sources'], JSON_THROW_ON_ERROR))->not->toContain('import-legal/');
|
||||
expect(array_unique(array_column($drafts, 'code')))->toHaveCount(48);
|
||||
$capital = collect($drafts)->firstWhere('code', '8451.80.10');
|
||||
$vehicle = collect($drafts)->firstWhere('code', '8704.21.10');
|
||||
$last = collect($drafts)->firstWhere('code', '9507.90.90');
|
||||
expect($capital['rate_percent'])->toBe('5')->and($capital['documentary_class'])->toBe('K')
|
||||
->and($capital['obligations'])->toContain('não comprova elegibilidade')
|
||||
->and($capital['citation'])->toContain('2180-(5)')
|
||||
->and($vehicle['documentary_class'])->toBeNull()
|
||||
->and($vehicle['obligations'])->toContain('bens de capital para investimento')
|
||||
->and($last['citation'])->toContain('2180-(7)')
|
||||
->and($last['rate_percent'])->toBe('5');
|
||||
// A purely illustrative 100 MZN base is not a real import, debt or complete tax assessment.
|
||||
$estimate = app(ImportLegalAmounts::class)->calculate($drafts[0]['charges'], ['general_duty' => [
|
||||
'value_minor' => 10000, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Explicit synthetic 100 MZN unit-test base']]);
|
||||
expect($estimate['known_subtotal_minor'])->toBe(2000)
|
||||
->and($estimate['complete'])->toBeFalse()
|
||||
->and($estimate['total_minor'])->toBeNull()
|
||||
->and($estimate['financial_effects'])->toBeFalse();
|
||||
foreach ($before as $table => $rows) {
|
||||
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
|
||||
}
|
||||
|
||||
@@ -157,3 +157,27 @@ test('private audit packages remain personal to their creator even within the sa
|
||||
$this->withoutVite()->get('/auditoria/privada')->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['exports']['data'] === []);
|
||||
expect(PrivateAuditExport::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('private audit detects a missing archive and accepts only the exact recovered private bytes without regenerating history', function () {
|
||||
Storage::fake('audit_recovery');
|
||||
$input = ['operation_key' => (string) Str::uuid(), 'families' => ['configuration']];
|
||||
$service = app(PrivateAuditExporter::class);
|
||||
$export = $service->generate($this->actor, $input);
|
||||
$archive = Storage::disk('local')->get($export->path);
|
||||
Storage::disk('audit_recovery')->put('original.zip', $archive);
|
||||
$before = DB::table('private_audit_exports')->where('id', $export->id)->first();
|
||||
$events = DB::table('audit_logs')->count();
|
||||
// Remove only the known generated file in the disposable fake QA disk.
|
||||
Storage::disk('local')->delete($export->path);
|
||||
try {
|
||||
$service->generate($this->actor, $input);
|
||||
test()->fail('Missing historical packages must not be silently regenerated.');
|
||||
} catch (HttpException $error) {
|
||||
expect($error->getStatusCode())->toBe(409);
|
||||
}
|
||||
Storage::disk('local')->put($export->path, Storage::disk('audit_recovery')->get('original.zip'));
|
||||
expect($service->generate($this->actor, $input)->id)->toBe($export->id)
|
||||
->and(hash_file('sha256', $service->verifiedPath($this->actor, $export)))->toBe($export->sha256)
|
||||
->and(DB::table('private_audit_exports')->where('id', $export->id)->first())->toEqual($before)
|
||||
->and(DB::table('audit_logs')->count())->toBe($events);
|
||||
});
|
||||
|
||||
@@ -511,6 +511,8 @@ test('native expiry returns the same request and preserves the approved stage be
|
||||
->where('history.data.0.rules.first_limit_minor', 5000)->where('history.data.0.rules.approval_includes_tax', true)
|
||||
->where('history.data.0.approval_amount_minor', 10000)->where('history.data.0.approval_uses_separate_basis', false)
|
||||
->where('history.data.0.steps.0.approver_id', $head->id)->where('history.data.0.steps.0.comment', 'Conferência sintética do primeiro nível')
|
||||
->where('history.data.0.steps.0.decided_at', CarbonImmutable::parse($approved['decided_at'], config('app.timezone'))->toIso8601String())
|
||||
->where('history.data.0.steps.1.decided_at', null)
|
||||
->missing('history.data.0.rules.timing')->missing('history.data.0.items.0.category_context'));
|
||||
foreach ($beforeHistoryRead as $table => $rows) {
|
||||
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
|
||||
|
||||
@@ -120,9 +120,14 @@ function landedQaReceiptsVerified(array $command, string $output): bool
|
||||
&& $contains(fn ($row) => ($row['isolated_restore_removed'] ?? false) === true);
|
||||
}
|
||||
|
||||
if (in_array($mode, ['legal-http', 'legal-review', 'expiry-review'], true)) {
|
||||
if (in_array($mode, ['legal-http', 'legal-reference-http', 'legal-review', 'expiry-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
|
||||
&& ($mode === 'legal-reference-http'
|
||||
? (($row['large_multipart_upload_bytes'] ?? null) === 1002011
|
||||
&& ($row['original_sha256'] ?? null) === 'a0110696253715567af39c159a21bacfebc32f944fa43a4efd18070d36959e50'
|
||||
&& ($row['documentary_reference_drafts'] ?? null) === 48)
|
||||
: ($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
|
||||
|
||||
@@ -5,6 +5,8 @@ use App\Http\Controllers\AuditMetadataController;
|
||||
use App\Models\CostCenter;
|
||||
use App\Models\User;
|
||||
use App\Services\CommonBudget;
|
||||
use App\Services\ImportLegalReferenceDrafts;
|
||||
use App\Services\ImportLegalRules;
|
||||
use App\Services\PrivateAuditAccess;
|
||||
use App\Services\PurchaseControlPolicyWorkflow;
|
||||
use App\Services\RequisitionAccountAssignments;
|
||||
@@ -17,13 +19,14 @@ use App\Services\WarehouseRequests;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tempo\Finance\GeneralLedger\LedgerSchema;
|
||||
|
||||
/** Strictly guarded native synthetic composition; no real identities, source data or grants. */
|
||||
function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $officeJourney = false): array
|
||||
function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $officeJourney = false, bool $legalReference = false, bool $printPagination = false): array
|
||||
{
|
||||
LedgerSchema::install(DB::connection());
|
||||
$composition = null;
|
||||
@@ -33,7 +36,9 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
|
||||
} else {
|
||||
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
|
||||
}
|
||||
$f = receiptFixture();
|
||||
$f = receiptFixture(categories: $printPagination
|
||||
? array_map(fn (int $line) => 'Categoria sintética de paginação '.str_pad((string) $line, 2, '0', STR_PAD_LEFT), range(1, 50))
|
||||
: ['Material']);
|
||||
$f['tenant']->update(['name' => 'QA isolada de Compras — contas e urgências']);
|
||||
config(['requisition-expiry.qa_enabled' => true, 'urgent-reviews.qa_enabled' => true, 'requisition-accounts.qa_enabled' => true,
|
||||
'agreement_order_limits.qa_enabled' => true, 'procurement_search.supply_metadata_enabled' => true,
|
||||
@@ -43,6 +48,9 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
|
||||
$functions = ['reviewer' => ['admin', 'procurement', 'requester', 'supply_prepare', 'warehouse_request_prepare', 'audit_metadata_read'], 'requester' => ['requester'],
|
||||
'head' => ['department_head', 'supply_review', 'warehouse_request_review'], 'finance' => ['finance'], 'auditor' => ['audit_metadata_read']];
|
||||
$functions['private_auditor'] = array_column(PrivateAuditAccess::FAMILIES, 'permission');
|
||||
if ($legalReference) {
|
||||
$functions['reviewer'][] = 'import_customs';
|
||||
}
|
||||
if ($officeJourney) {
|
||||
$functions += ['office_requester' => ['requester'], 'office_finance_reviewer' => ['finance'], 'office_warehouse' => ['warehouse'],
|
||||
'office_procurement_reviewer' => ['procurement']];
|
||||
@@ -249,7 +257,30 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
|
||||
}
|
||||
}
|
||||
|
||||
$legalReferenceRoute = null;
|
||||
if ($legalReference) {
|
||||
$path = 'C:/Mac/Home/Documents/TEMPO/Portal Tempo/Legislacao/novas/BR_248_I_SERIE_SUPLEMENTO_2025.pdf';
|
||||
if (! $integrated || ! is_file($path) || hash_file('sha256', $path) !== ImportLegalReferenceDrafts::EDITION_SHA256) {
|
||||
throw new LogicException('The owned legal preview requires the exact supplied official edition and integrated synthetic schema.');
|
||||
}
|
||||
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
|
||||
auth()->guard()->setUser($people['reviewer']);
|
||||
app(ImportLegalRules::class)->save($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
|
||||
'official_reference' => 'BR I Série 248, suplemento, 29/12/2025 — Lei 8/2025',
|
||||
'reason' => 'Exemplar oficial partilhado para consulta e preparação em ambiente exclusivamente QA sintético; nenhuma regra publicada.'],
|
||||
new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true));
|
||||
$legalReferenceRoute = '/requisicoes/'.$f['r']->id.'/base-legal';
|
||||
if (getenv('RQ01_QA_SPECIFIC_RATE') === '1') {
|
||||
require_once __DIR__.'/ImportLegalQaFixture.php';
|
||||
app(ImportLegalRules::class)->save($people['reviewer'], ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
|
||||
'official_reference' => 'Exemplar sintético QA — sem diploma ou validade fiscal',
|
||||
'reason' => 'Fonte sintética separada, registada pelo serviço nativo apenas para conferir precisão decimal; nenhuma taxa publicada.'], importLegalQaFile());
|
||||
}
|
||||
}
|
||||
|
||||
return ['tenant_id' => $f['tenant']->id, 'synthetic_login' => $people['reviewer']->email,
|
||||
'print_pagination' => $printPagination ? ['order_route' => '/ordens/'.$f['order']->id.'/imprimir', 'lines' => 50, 'total_minor' => 10000, 'fixture_only_not_native_issuance' => true] : null,
|
||||
'legal_reference_route' => $legalReferenceRoute,
|
||||
'office_journey' => $office,
|
||||
'integrated_optional_schema' => $composition,
|
||||
'synthetic_private_audit_login' => $people['private_auditor']->email, 'synthetic_metadata_login' => $people['auditor']->email, 'synthetic_requester_login' => $people['requester']->email,
|
||||
|
||||
@@ -44,5 +44,8 @@ $app->booted(function () use ($root, $database) {
|
||||
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'native-http-office-qa',
|
||||
'expense-allocations.qa_enabled' => true]);
|
||||
}
|
||||
if (getenv('RQ01_QA_LEGAL_REFERENCE') === '1') {
|
||||
config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
|
||||
}
|
||||
});
|
||||
$app->handleRequest(Request::capture());
|
||||
|
||||
@@ -217,6 +217,23 @@ test('legal contention and recovery require original source publication and froz
|
||||
expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
|
||||
});
|
||||
|
||||
test('documentary reference HTTP receipts require the exact edition full draft count and native preservation', function () {
|
||||
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'legal-reference-http'];
|
||||
$row = ['native_legal_http_login' => true, 'csrf_required' => true, 'large_multipart_upload_bytes' => 1002011,
|
||||
'original_sha256' => 'a0110696253715567af39c159a21bacfebc32f944fa43a4efd18070d36959e50', 'documentary_reference_drafts' => 48,
|
||||
'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,
|
||||
'global_php_config_unchanged' => true, 'private_http_server_stopped' => true, 'private_http_root_removed' => true];
|
||||
expect(landedQaReceiptsVerified($command, json_encode($row, JSON_THROW_ON_ERROR)))->toBeTrue();
|
||||
foreach (['original_sha256', 'documentary_reference_drafts', 'financial_stock_unchanged', 'rules_published', 'private_http_root_removed'] as $field) {
|
||||
$incomplete = $row;
|
||||
unset($incomplete[$field]);
|
||||
expect(landedQaReceiptsVerified($command, json_encode($incomplete, JSON_THROW_ON_ERROR)))->toBeFalse();
|
||||
}
|
||||
$command[3] = 'legal-http';
|
||||
expect(landedQaReceiptsVerified($command, json_encode($row, JSON_THROW_ON_ERROR)))->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),
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import {
|
||||
chargeDrafts,
|
||||
LegalChargeSummary,
|
||||
} from '@/components/import-legal-charges';
|
||||
import {
|
||||
specificRateLabel,
|
||||
specificRateMinor,
|
||||
specificRateMoney,
|
||||
} from '@/lib/import-legal-specific-rate';
|
||||
|
||||
test.each([
|
||||
['1.25', 125],
|
||||
['1,25', 125],
|
||||
['0.0099', '0.99'],
|
||||
['0.0133', '1.33'],
|
||||
['0.00000001', '0.000001'],
|
||||
['000.00990000', '0.99'],
|
||||
['0', 0],
|
||||
] as const)(
|
||||
'preserves exact documentary coefficient %s in minor units',
|
||||
(input, minor) => {
|
||||
expect(specificRateMinor(input)).toBe(minor);
|
||||
expect(specificRateMinor(specificRateMoney(minor))).toBe(minor);
|
||||
},
|
||||
);
|
||||
|
||||
test.each(['', '-1', '1e2', '0.000000001', '10000000000000', '1.2.3', 'NaN'])(
|
||||
'invalid MZN coefficient cannot be reinterpreted as a valid cent coefficient: %s',
|
||||
(input) => expect(specificRateMinor(input)).toBeNull(),
|
||||
);
|
||||
|
||||
test('fractional cent coefficients survive revision and remain visible without monetary rounding', () => {
|
||||
const charge = {
|
||||
key: 'synthetic-specific',
|
||||
kind: 'ice',
|
||||
label: 'Coeficiente documental sintético',
|
||||
method: 'specific',
|
||||
rate_percent: null,
|
||||
specific_minor: '0.99',
|
||||
quantity_unit: 'g',
|
||||
basis_reference: 'Fonte sintética, sem activação fiscal',
|
||||
};
|
||||
expect(chargeDrafts([charge])[0].specific_amount).toBe('0.0099');
|
||||
expect(specificRateLabel('0.99')).toBe('0,0099 MZN');
|
||||
const html = renderToStaticMarkup(
|
||||
<LegalChargeSummary charges={[charge]} />,
|
||||
);
|
||||
expect(html).toContain('0,0099 MZN');
|
||||
expect(html).not.toContain('0,00 MZN');
|
||||
expect(specificRateMoney(125)).toBe('1.25');
|
||||
expect(specificRateMoney(null)).toBe('');
|
||||
});
|
||||
@@ -1,7 +1,8 @@
|
||||
import { App } from '@inertiajs/react';
|
||||
import { App, router } from '@inertiajs/react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import { afterEach, expect, test, vi } from 'vitest';
|
||||
import Legal from '../../resources/js/pages/supply/import-legal';
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
function renderLegal(
|
||||
canManage: boolean,
|
||||
@@ -108,12 +109,49 @@ test('official reference preparation is explicit and only available to the custo
|
||||
expect(allowed).toContain('3506.91.20');
|
||||
expect(allowed).toContain('taxa geral 20%');
|
||||
expect(allowed).toContain('não é uma pauta consolidada');
|
||||
expect(allowed).toContain('não substituir');
|
||||
expect(allowed).toContain('Ainda não existem regras neste âmbito.');
|
||||
expect(allowed).not.toContain('Ainda não existem fontes neste âmbito.');
|
||||
const reader = renderLegal(false, false, false, true);
|
||||
expect(reader).not.toContain('Preparar a partir do exemplar oficial');
|
||||
expect(reader).not.toContain('Silicone para selagem');
|
||||
});
|
||||
|
||||
test('remembered legal preparation is preserved and disables replacement by official reference drafts', () => {
|
||||
vi.spyOn(router, 'restore').mockImplementation((key) =>
|
||||
key === 'legal-rule:1:1:1:data'
|
||||
? {
|
||||
operation_key: 'c1111111-1111-4111-8111-111111111111',
|
||||
record_key: null,
|
||||
version: 0,
|
||||
action: 'save',
|
||||
title: 'PRESERVED-DELIBERATE-TITLE',
|
||||
official_reference: '',
|
||||
official_url: '',
|
||||
citation: '',
|
||||
valid_from: '',
|
||||
valid_until: '',
|
||||
match_code: '',
|
||||
suggested_code: '',
|
||||
origin_country: '',
|
||||
sector: '',
|
||||
obligations: '',
|
||||
document_types: [],
|
||||
reason: '',
|
||||
file: null,
|
||||
source_id: '',
|
||||
charges: [],
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
const post = vi.spyOn(router, 'post');
|
||||
const html = renderLegal(true, false, false, true);
|
||||
expect(html).toContain('PRESERVED-DELIBERATE-TITLE');
|
||||
expect(html).toContain('O preenchimento existente será conservado');
|
||||
expect(html).toContain('Limpar preparação');
|
||||
expect(html).toMatch(/<select[^>]*disabled[^>]*>/);
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
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>');
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 362 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 320 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 187 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 471 KiB |
@@ -0,0 +1,47 @@
|
||||
%PDF-1.3
|
||||
%âãÏÓ
|
||||
1 0 obj
|
||||
<<
|
||||
/Producer (pypdf)
|
||||
/Title (Synthetic QA coefficient precision specimen\073 no legal validity)
|
||||
/Subject (Test only\073 no statutory tax rate\054 liability or operational publication)
|
||||
>>
|
||||
endobj
|
||||
2 0 obj
|
||||
<<
|
||||
/Type /Pages
|
||||
/Count 1
|
||||
/Kids [ 4 0 R ]
|
||||
>>
|
||||
endobj
|
||||
3 0 obj
|
||||
<<
|
||||
/Type /Catalog
|
||||
/Pages 2 0 R
|
||||
>>
|
||||
endobj
|
||||
4 0 obj
|
||||
<<
|
||||
/Type /Page
|
||||
/Resources <<
|
||||
>>
|
||||
/MediaBox [ 0.0 0.0 595 842 ]
|
||||
/Parent 2 0 R
|
||||
>>
|
||||
endobj
|
||||
xref
|
||||
0 5
|
||||
0000000000 65535 f
|
||||
0000000015 00000 n
|
||||
0000000217 00000 n
|
||||
0000000276 00000 n
|
||||
0000000325 00000 n
|
||||
trailer
|
||||
<<
|
||||
/Size 5
|
||||
/Root 3 0 R
|
||||
/Info 1 0 R
|
||||
>>
|
||||
startxref
|
||||
419
|
||||
%%EOF
|
||||
Reference in New Issue
Block a user