@@ -1,5 +1,25 @@
|
||||
# Orientações permanentes do SGC
|
||||
|
||||
## Declarações globais no SGF — âmbito de empresa autorizado
|
||||
|
||||
Autorização expressa recebida: «Autorizar âmbito de empresa, sem concessões persistentes», conforme decisão adicional em docs/proposta-extensao-composicao-sgf.md. Os dois direitos purchasing_conflicts.view/authorise podem ter âmbito de empresa para declarações globais por fornecedor; direitos de unidade não as abrangem. Preservar a competência nativa própria da Direcção, associação explícita e não ambígua empresa SGF/empresa nativa, dados NULL sem classificação automática e direitos base de criação sem concessões adicionais. Sem contas novas, concessões persistentes, operacionais ou publicação. Não voltar a solicitar autorização deste recorte; implementação/testes ainda em curso.
|
||||
|
||||
## Extensão do contrato SGF autorizada — 30/11/2026
|
||||
|
||||
O proprietário autorizou expressamente implementar e testar em isolamento docs/proposta-extensao-composicao-sgf.md e continuar a integração total. Inclui declaração de capacidades validada pelo runtime existente, versões locais qualificadas, levantamento de impedimentos, cancelamento por ciclos e os seis nomes de catálogo propostos, sem atribuições persistentes. Não voltar a pedir esta autorização; os estados «pendente» abaixo são históricos. Não conceder acessos persistentes, alterar instalações operacionais, publicar ou criar aplicações paralelas. Preservar SGC independente e uma autoridade financeira. Em desenvolvimento: ExecutionContext limitado à ligação/execução, pontes dos serviços originais e WorkflowExecution no ReceiptRuntime; implementação ainda exige qualificação e entrega antes de declarar conclusão.
|
||||
|
||||
## Extensão do contrato de execução SGF — proposta pendente, 30/11/2026
|
||||
|
||||
Continuação da integração identificou uma fronteira concreta: ConflictReleases::ready() admite SGC autónomo/testes restritos, não ReceiptRuntime do SGF; cancelamento actual exige versão qualificada e ciclos. Proposta revista em docs/proposta-extensao-composicao-sgf.md e hashes em docs/proofs/sgf-composition-extension-proposal-20261130.json. Ainda não autorizada, implementada ou activada. A autorização anterior do instalador v2 cobre entrega de ficheiros, não esta alteração de contrato de execução. Não contornar ready() mudando APP_ENV, retirar guardas físicas, copiar outro motor ou atribuir competência de Direcção ao administrador/financeiro. Proposta prevê extensão do runtime existente, seis nomes de direitos no catálogo sem atribuições, versões locais qualificadas, ciclos e testes revertidos; zero GRANT/REVOKE ou operacionais. Candidata3d2e9743ecf621d3 inalterada. Verificar resposta do proprietário antes de implementar a extensão; não voltar a pedir autorização se entretanto concedida para este recorte.
|
||||
|
||||
## Seguimento da integração SGF — catálogo administrativo e matriz,30/11/2026
|
||||
|
||||
Continuação expressa sem novas aplicações/publicação/operacionais: o catálogo dos33direitos nativos de Compras/Stock foi incorporado no MESMO AccessOverlay/AdminUiOverlay, preservando os direitos antigos, criação de unidade apenas com unit.view/unit.edit e delegação apenas de direito possuído no âmbito.54verificações PostgreSQL revertidas no livro existenteb4093c6f6707, sem novas contas/concessões persistentes/GRANT/REVOKE. Candidata3d2e9743ecf621d3,169ficheiros/99sobreposições/27fontes de schema,202verificações de recuperação de código; fonte financeira bd787c45e6f91bf0 reutilizada. Não instalada. Hashes/provas/matriz em docs/integracao-total-sgf-20261130.md e docs/proofs/sgf-purchasing-access-delivery-20261130.json. Verificador de inventário apenas de leitura:25componentes,21fontes divergentes/duas ausentes/duas inalteradas,12testes/25asserções; não é aceitação funcional. ConflictReleases, cancelamento de ordens, diferenças posteriores e portabilidade continuam pendentes. Não declarar integração integral concluída, substituir os pins/bindings físicos nem retirar guardas QA por esta entrega. SGC independente e restantes permissões/configuração reais preservadas.
|
||||
|
||||
## Recibos de custo zero na integração SGF — 30/11/2026
|
||||
|
||||
O proprietário autorizou expressamente implementar recibos de custo zero, com revisão independente e testes isolados, preservando SGC autónomo e instalações operacionais. Implementado no MESMO `PayableJournal`, sem lançamento ou movimento adicional; entradas continuam a exigir custo explícito positivo. Candidata privada `MERCHANDISE-V2-6e1b9710e9094c5a`, não instalada, com 202 verificações de recuperação de código; detalhes e hashes em `docs/integracao-total-sgf-20261130.md` e `docs/proofs/sgf-zero-cost-receipts-20261130.json`. FIFO153/CMP155, dados utilizados/restauro, revisão distinta, versões, revogação, relatórios e guardas concorrentes qualificados na regressão existente `b4093c6f6707`, contexto1/2/2; contagens sobrepostas. Cópias SQL transitórias removidas, sem novas bases/contas/demonstrações/GRANT/REVOKE ou publicação. Não repetir a autorização deste incremento; instalação, activação, parametrização real e aceitação operacional continuam separadas. Não enfraquecer a exigência de montantes positivos no diário nem tratar custo desconhecido como zero.
|
||||
|
||||
## Conclusão e uniformização — decisões expressas do proprietário, 29/11/2026
|
||||
|
||||
Pedido: uniformizar local e público, configurar emails, terminar a validação e o desenvolvimento restante. Remetente e destino autorizado para a mensagem de teste: `nala@tempo.co.mz`; não divulgar credenciais. A configuração SMTP local continua a exigir um ficheiro privado com autenticação ou outro mecanismo aprovado; o endereço de email não constitui uma password.
|
||||
|
||||
@@ -32,7 +32,7 @@ class OrderCancellationController extends Controller
|
||||
{
|
||||
$actor = $this->actor($request);
|
||||
$focus = $request->validate(['cancellation_id' => 'nullable|integer|min:1'])['cancellation_id'] ?? null;
|
||||
abort_unless($actor->hasFunctions(['admin', 'procurement', 'finance', 'requester', 'department_head']), 403);
|
||||
abort_unless($workflow->canView($actor), 403);
|
||||
|
||||
return DB::transaction(function () use ($request, $actor, $workflow, $focus) {
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
|
||||
@@ -5,9 +5,11 @@ namespace App\Services;
|
||||
use App\Models\ConflictDeclaration;
|
||||
use App\Models\ConflictRelease;
|
||||
use App\Models\User;
|
||||
use App\Models\Supplier;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Tempo\Purchasing\Composition\ExecutionContext;
|
||||
|
||||
/** Explicit direction authority; no legacy Admin/Finance fallback or automatic expiry. */
|
||||
final class ConflictReleases
|
||||
@@ -16,6 +18,10 @@ final class ConflictReleases
|
||||
{
|
||||
$db = DB::connection();
|
||||
|
||||
if (app()->bound(ExecutionContext::class)) {
|
||||
return app(ExecutionContext::class)->allows('conflict-release', $db) && Schema::hasTable('conflict_releases');
|
||||
}
|
||||
|
||||
if (app(StandaloneRuntime::class)->enabled()) {
|
||||
return app(StandaloneRuntime::class)->feature('conflict-releases', $db) && Schema::hasTable('conflict_releases');
|
||||
}
|
||||
@@ -42,6 +48,13 @@ final class ConflictReleases
|
||||
public function authorise(User $actor, ConflictDeclaration $declaration, array $input): ConflictRelease
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
if (app()->bound(ExecutionContext::class)) {
|
||||
abort_unless(app(ExecutionContext::class)->permits('purchasing_conflicts.authorise', DB::connection()), 403);
|
||||
if ($declaration->requisition_id === null) {
|
||||
abort_unless(app(ExecutionContext::class)->component('conflict-release', DB::connection())['company_authorise'] ?? false, 403);
|
||||
abort_unless($declaration->supplier_id !== null && Supplier::query()->where('tenant_id', $actor->tenant_id)->whereKey($declaration->supplier_id)->exists(), 403);
|
||||
}
|
||||
}
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'reason' => 'required|string|min:10|max:5000'])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
|
||||
|
||||
@@ -49,6 +49,7 @@ class OrderCancellationPolicyWorkflow extends PurchaseControlPolicyWorkflow
|
||||
public function propose(User $user, array $data): PurchaseControlPolicy
|
||||
{
|
||||
$this->enabled();
|
||||
app(OrderCancellationRuntime::class)->assertAction('prepare');
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($user), 403);
|
||||
validator($data, ['previous_id' => 'required|integer|min:0', 'mode' => 'required|in:issued_order', 'enabled' => 'required|boolean',
|
||||
'valid_from' => 'required|date_format:Y-m-d', 'valid_until' => 'required|date_format:Y-m-d|after_or_equal:valid_from', 'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
@@ -59,6 +60,7 @@ class OrderCancellationPolicyWorkflow extends PurchaseControlPolicyWorkflow
|
||||
public function review(User $user, PurchaseControlPolicy $policy, string $decision, string $reason): void
|
||||
{
|
||||
$this->enabled();
|
||||
app(OrderCancellationRuntime::class)->assertAction('approve');
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($user), 403);
|
||||
parent::review($user, $policy, $decision, $reason);
|
||||
}
|
||||
|
||||
@@ -6,14 +6,30 @@ use Illuminate\Support\Facades\DB;
|
||||
use LogicException;
|
||||
use Tempo\Finance\Budget\BudgetContext;
|
||||
use Tempo\Finance\OrderCancellation\CommitmentReversal;
|
||||
use Tempo\Purchasing\Composition\ExecutionContext;
|
||||
|
||||
/** Version selection for the existing additive reversal writer, never another budget ledger. */
|
||||
final class OrderCancellationRuntime
|
||||
{
|
||||
public const MANIFEST_SHA256 = '52df7927aa2689598ce1be92de1483694347a696245704abb9e3925db7abfc0f';
|
||||
|
||||
public function assertAction(string $action): void
|
||||
{
|
||||
if (! in_array($action, ['prepare', 'approve', 'revise'], true)) {
|
||||
throw new LogicException('COMPRAS_CANCELLATION_ACTION');
|
||||
}
|
||||
if (app()->bound(ExecutionContext::class)) {
|
||||
abort_unless(app(ExecutionContext::class)->permits('purchasing_order_cancellations.'.$action, DB::connection()), 403);
|
||||
}
|
||||
}
|
||||
|
||||
public function assertReady(): void
|
||||
{
|
||||
if (app()->bound(ExecutionContext::class)) {
|
||||
$this->compositionRoot();
|
||||
|
||||
return;
|
||||
}
|
||||
$runtime = app(StandaloneRuntime::class);
|
||||
if (! $runtime->enabled()) {
|
||||
return;
|
||||
@@ -56,8 +72,11 @@ final class OrderCancellationRuntime
|
||||
/** Returns whether the writer requires the explicit cycle map in its financial context. */
|
||||
public function load(int $origin): bool
|
||||
{
|
||||
$operational = app(StandaloneRuntime::class)->enabled();
|
||||
if ($operational) {
|
||||
$composed = app()->bound(ExecutionContext::class);
|
||||
$operational = $composed || app(StandaloneRuntime::class)->enabled();
|
||||
if ($composed) {
|
||||
$path = $this->compositionRoot().'/src/CommitmentReversal.php';
|
||||
} elseif ($operational) {
|
||||
$this->assertReady();
|
||||
$path = config('order_cancellation.root').'/src/CommitmentReversal.php';
|
||||
} else {
|
||||
@@ -75,4 +94,23 @@ final class OrderCancellationRuntime
|
||||
|
||||
return $operational;
|
||||
}
|
||||
|
||||
private function compositionRoot(): string
|
||||
{
|
||||
$db = DB::connection();
|
||||
$component = app(ExecutionContext::class)->component('order-cancellation-cycles', $db);
|
||||
if (! hash_equals(self::MANIFEST_SHA256, $component['manifest_sha256']) || ! property_exists(BudgetContext::class, 'requisitionCycles')) {
|
||||
throw new LogicException('COMPRAS_CANCELLATION_COMPOSITION');
|
||||
}
|
||||
foreach (['order_cancellations' => ['operation_key', 'basis_hash', 'status'],
|
||||
'order_cancellation_policies' => ['revision', 'status'], 'order_cancellation_policy_reviews' => ['reviewed_by'],
|
||||
'budget_entries' => ['requisition_cycle'], 'budget_requisition_cycles' => ['cycle', 'state']] as $table => $columns) {
|
||||
if (! $db->getSchemaBuilder()->hasColumns($table, $columns)) {
|
||||
throw new LogicException('COMPRAS_CANCELLATION_SCHEMA');
|
||||
}
|
||||
}
|
||||
self::verifyArtifact($component['root']);
|
||||
|
||||
return $component['root'];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,11 @@ use Tempo\Finance\OrderCancellation\CommitmentReversal;
|
||||
|
||||
class OrderCancellationWorkflow
|
||||
{
|
||||
public function canView(User $actor): bool
|
||||
{
|
||||
return $actor->tenant_id !== null && $actor->hasFunctions(['admin', 'procurement', 'finance', 'requester', 'department_head']);
|
||||
}
|
||||
|
||||
public function canRevise(User $actor, OrderCancellation $record): bool
|
||||
{
|
||||
if (! config('order_cancellation.enabled') || $record->tenant_id !== $actor->tenant_id || $record->status !== 'approved' || $record->revised_requisition_id
|
||||
@@ -124,6 +129,7 @@ class OrderCancellationWorkflow
|
||||
public function request(User $actor, PurchaseOrder $order, array $input): OrderCancellation
|
||||
{
|
||||
$this->enabled();
|
||||
app(OrderCancellationRuntime::class)->assertAction('prepare');
|
||||
$data = validator($input, ['operation_key' => 'required|uuid', 'reason' => 'required|string|min:10|max:4000', 'evidence' => 'required|string|min:10|max:4000'])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$hash = hash('sha256', json_encode([$order->id, $data], JSON_THROW_ON_ERROR));
|
||||
@@ -161,6 +167,7 @@ class OrderCancellationWorkflow
|
||||
public function decide(User $actor, OrderCancellation $record, string $decision, string $reason): void
|
||||
{
|
||||
$this->enabled();
|
||||
app(OrderCancellationRuntime::class)->assertAction('approve');
|
||||
validator(['decision' => $decision, 'reason' => $reason], ['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
DB::transaction(function () use ($actor, $record, $decision, $reason) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
@@ -250,6 +257,7 @@ class OrderCancellationWorkflow
|
||||
public function revise(User $actor, OrderCancellation $record, string $neededBy, string $reason): Requisition
|
||||
{
|
||||
$this->enabled();
|
||||
app(OrderCancellationRuntime::class)->assertAction('revise');
|
||||
validator(['needed_by' => $neededBy, 'reason' => $reason], ['needed_by' => 'required|date_format:Y-m-d|after_or_equal:today', 'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
|
||||
return DB::transaction(function () use ($actor, $record, $neededBy, $reason) {
|
||||
|
||||
@@ -1,5 +1,124 @@
|
||||
# Integração integral de Compras no SGF — execução de 30/11/2026
|
||||
|
||||
## Matriz actual consolidada — conferência das versões
|
||||
|
||||
**Decisão específica pendente:** a [extensão do contrato de execução](proposta-extensao-composicao-sgf.md) concretiza a entrada dos workflows actuais na composição SGF. A análise confirmou que ConflictReleases::ready() não admite hoje o runtime SGF e que o cancelamento requer o componente qualificado por ciclos. A autorização do instalador v2 não altera esses contratos. Não foram removidas guardas, carregadas versões novas, aplicadas migrações ou atribuídos direitos. Fontes/hashes e seis nomes de direitos propostos, sem atribuições: [registo da proposta](proofs/sgf-composition-extension-proposal-20261130.json). A candidata3d2e9743ecf621d3 permanece inalterada. A implementação desta extensão aguarda autorização específica; a análise documental não fecha os percursos funcionais.
|
||||
|
||||
**Candidata corrente deste seguimento:** `MERCHANDISE-V2-3d2e9743ecf621d3`, preparada e não instalada, sucede à6e1b9710e9094c5a acrescentando o catálogo administrativo de direitos nativos. Manifesto SHA-256 `3d2e9743ecf621d3e0113769a5339df7b0a704822d09243ef29a79015034770a`; ZIP `46cfe55141e180565cf7617ec487ca30eacf86494601997bdb466039580a67ac`.169ficheiros/99sobreposições/27fontes de schema; **202 verificações** de aplicação/repetição/recuperação de código. Não introduz schema novo neste incremento. A revisão financeira `bd787c45e6f91bf0` e as suas provas válidas foram reutilizadas.
|
||||
|
||||
O MESMO `AccessOverlay`/`AdminUiOverlay` passou a incluir os33direitos nativos de Compras/Stock e os respectivos rótulos, conservando os nomes do percurso anterior. `select/approve` do adaptador nativo não são renomeados para `propose/confirm`. A interface continua a consumir o catálogo enviado pelo servidor. Criar unidade concede apenas unit.view/unit.edit; gerir acessos exige access.manage, direito delegado no mesmo âmbito e consulta da unidade pelo destinatário. Não se atribuem perfis nativos, correspondências ou capacidades por esta listagem. As guardas de contexto, aprovação independente e flags funcionais permanecem.
|
||||
|
||||
**54 verificações** em PostgreSQL com as identidades sintéticas existentes e rollback:33âmbitos SQL, criação real de unidade sem direitos adicionais, catálogo/rótulos, recusa de nome desconhecido, âmbito empresa indevido, unidade alheia, delegação sem autoridade, destinatário sem consulta, repetição única, revogação imediata, administrador revogado, auditoria e preservação das tabelas. Unidade de ensaio revertida; zero novas contas/concessões persistentes/GRANT/REVOKE. Compilação privada aprovada; revisão visual separada. Os hashes das duas sobreposições ensaiadas e das três fontes de entrega coincidem com a candidata. [Prova de entrega e vínculos](proofs/sgf-purchasing-access-delivery-20261130.json). Recuperação de código: `storage/framework/testing/merchandise-v2-86f3c3a3fbd8/recovery-result.json`.
|
||||
|
||||
Esta matriz prevalece sobre as tabelas históricas seguintes. A candidata de mercadorias `6e1b9710e9094c5a` conserva a qualificação do seu recorte; não certifica automaticamente as versões actuais de todos os processos do SGC.
|
||||
|
||||
Conferência apenas de leitura do pacote nativo da regressão existente: manifesto SHA-256 `7709a3d447d54c17d2fb4be4f9a0f70455c4a38c34e4bb8c643f6b5169071556`, integridade de todos os ficheiros declarados verificada. Na selecção explícita de **25 componentes**, há **21 fontes alteradas**, **duas não transferidas** e **duas sem alteração**. Diferença de hash não prova regressão funcional; exige comparar a alteração e qualificar o percurso afectado. Esta selecção não é um inventário exaustivo de todas as dependências.
|
||||
|
||||
| Percurso/componente | Estado para a integração integral | Fecho necessário |
|
||||
| --- | --- | --- |
|
||||
| Contexto, permissões e identidade actual | Parcialmente transferido; quatro fontes seleccionadas divergentes | Comparar WorkContext, HasWorkContext, CurrentActor e OrganizationAccess, mantendo direitos e isolamento do adaptador SGF |
|
||||
| Requisição → orçamento → aprovação | Percurso anterior aceite; quatro fontes seleccionadas divergentes | Conferir alterações posteriores antes de declarar equivalência com o SGC actual; não recriar os documentos aceites |
|
||||
| Consulta → comparação → adjudicação | Parcialmente transferido; três fontes divergentes | Conferir PurchaseWorkflow, ProposalComparison e ConflictGuard; manter decisão independente |
|
||||
| Levantamento de impedimentos pela Direcção | Pendente: ConflictReleases não consta do pacote conferido | Incorporar serviço, modelo, schema, competência e histórico do circuito existente; nunca eliminar conflitos por adaptação |
|
||||
| Encomenda → recepção | Percurso anterior aceite; ReceiptWorkflow e política de recepção divergentes; ReceiptDocuments sem alteração | Comparar diferenças e adaptar ecrãs/permissões necessários; equipamentos/peças não são uma condição universal do percurso básico, mas os respectivos ramos não ficam aceites por esta conclusão |
|
||||
| Cancelamento de ordens | Pendente: OrderCancellationWorkflow não consta do pacote conferido | Reutilizar cancelamento e reversão orçamental existentes, com versão/política/revisão; não criar outro writer |
|
||||
| Obrigação e dívida a fornecedor | Percurso anterior aceite; duas fontes divergentes | Conferir InvoiceWorkflow e SupplierPayables e preservar autoridade financeira única |
|
||||
| Armazém e reservas internas | Parcialmente transferido; quatro fontes seleccionadas divergentes | Comparar StockWorkflow, WarehouseRequests, WarehouseReservations e WarehouseFulfilment; qualificar alterações efectivamente relevantes |
|
||||
| Reposição e sugestões para revenda | Implementado no recorte ensaiado; duas fontes divergentes e SupplySuggestions sem alteração | Comparar SupplyPlanning/AutomaticPurchases; duas conversões simultâneas continuam sem prova completa, o ensaio de leitor concorrente não as substitui |
|
||||
| Venda, recebimento de cliente e entrega | Implementado no recorte de mercadorias ensaiado | Aceitação das variantes documentais restantes e correspondência transversal com os processos actualizados |
|
||||
| Valorização FIFO/CMP, devolução original, reconciliação, entradas e custo zero | Implementado no recorte qualificado da candidata actual | Preservar provas de custo, arredondamento e recuperação; não voltar a apresentar como decisões pendentes |
|
||||
| Actualização e recuperação de código | Implementado/ensaiado: v2, 202 verificações na candidata actual | Requalificar somente ficheiros alterados pelos próximos incrementos; não activar uma versão |
|
||||
| Recuperação de schema/dados | Ensaiada transaccionalmente, incluindo dados utilizados | Recuperação de servidor, ACL/proprietários e privilégios de instalação não estão demonstrados por rollback na mesma base |
|
||||
| Portabilidade da composição | Pendente | Adaptadores ainda dependem de vínculos, caminhos e guardas físicos do ambiente de regressão. Conservar as guardas; não apresentar a candidata como instalação autónoma pronta para clientes |
|
||||
| Catálogo administrativo de permissões de Compras/Stock | Implementado e ensaiado na preparação da candidata3d2e9743ecf621d3 |54verificações; delegação pelo mecanismo existente, sem concessões persistentes. Instalação/configuração efectiva e restantes catálogos financeiros separados. Três concessões stock.view propostas para a8085 continuam sem aplicação e não são autorizadas por esta tarefa |
|
||||
| Parametrização real, visual, carga e implantação | Etapas separadas, excluídas desta execução | Sem valores empresariais presumidos, novas aplicações, publicação ou alterações operacionais |
|
||||
|
||||
Evidência reproduzível: [inventário das fontes e hashes](proofs/sgf-workflow-inventory-20261130.json). Comando apenas de leitura: `php scripts/sgf-workflow-inventory.php <pasta-do-bundle> 7709a3d447d54c17d2fb4be4f9a0f70455c4a38c34e4bb8c643f6b5169071556`. O verificador não arranca Laravel nem estabelece ligações a bases. Recusa manifesto divergente, ficheiro adulterado, caminhos inseguros e inventários sem hashes de origem. **12 testes/25 asserções** e Pint dirigidos passaram. Nenhuma prova financeira anterior foi repetida.
|
||||
|
||||
Estado global: **parcialmente integrado**. O inventário resolve a ambiguidade documental; os componentes pendentes acima ainda exigem implementação/qualificação e não foram declarados concluídos.
|
||||
|
||||
## Entrega anterior — recibos de custo zero autorizados
|
||||
|
||||
O proprietário autorizou expressamente a [proposta de recibos de custo zero](proposta-custos-zero-sgf.md), com revisão independente e testes isolados. Este incremento está concluído no código e nas provas; não equivale à instalação ou à aceitação operacional da integração integral.
|
||||
|
||||
Candidata privada **MERCHANDISE-V2-6e1b9710e9094c5a**, não instalada: 168 ficheiros/99 sobreposições, 27 fontes de schema sujeitas a recibo separado. Manifesto SHA-256 `6e1b9710e9094c5ab91987a1465e6f2e3e3067af4856e93b0053280bfb380760`; ZIP `6c2bc3501849515ab49db7c5200be7a265f789b3defd1f81bab8a5686fc61037`. Aplicação/repetição/recuperação de código: **202 verificações** na cópia privada, prova `storage/framework/testing/merchandise-v2-957d5d2ef984/recovery-result.json`. Revisão fonte `bd787c45e6f91bf08b2b38a958645c8bfcb5301652452800d10bf6cd6dbd76b8`, ZIP `e4dd24f3450dad3a78ce041c0bf32b004ad52165d822c493c9899b0e7b178a85`; compatibilidade compilada `cab61896c8e4aa47` preservada. Substitui a candidata 815d88bc0f2f7105 neste recorte sem apagar o histórico.
|
||||
|
||||
| Capacidade | Estado actual |
|
||||
| --- | --- |
|
||||
| Custo de saída calculado em 0,00 MZN | Implementado para as saídas tipadas do custo empresarial; só com arredondamento aprovado, origem física e cálculo comum qualificados |
|
||||
| Proposta, revisão e aplicação | Mesmo `PayableJournal`, permissões existentes e outra identidade; confirmação guarda `gl_stock_zero_costs`, sem lançamento, linhas de diário ou novo movimento físico |
|
||||
| Origem e versões | Recibo, revisão, autor/data, motivo e versão conservados; chave repetida recupera o recibo, versão substituída e alteração indevida de custo são recusadas |
|
||||
| Exclusão de duplicações | Um custo por movimento; guarda serializa recibos zero e lançamentos positivos e recusa a segunda inserção |
|
||||
| Custos posteriores e último saldo | Referência de recibo distinta de identificador de lançamento; FIFO/CMP continuam a partir do custo aceite, com acerto exacto na última saída |
|
||||
| Saldo físico sem valor remanescente | Reconciliação independente conserva explicitamente zero, sem inventar recepção gratuita ou custo positivo |
|
||||
| Consulta, relatórios e impressão | Recibos paginados separados dos lançamentos e de custos em falta; totais financeiros continuam a usar apenas linhas reais do diário |
|
||||
| Recuperação | Schema vazio removível; histórico utilizado preservado. Restauro de dados preenchidos e falha parcial ensaiados separadamente da recuperação de código |
|
||||
|
||||
Provas incluídas, sobrepostas e não somáveis como casos únicos: **153** FIFO (`20261130-203737-d83fb894`) e **155** CMP/meio cêntimo (`20261130-203751-65891c96`), com endpoints/controladores reais, Blade, revogação, revisão independente, versão substituída, falsificação zero↔um cêntimo, falha tardia e restauro de dados utilizados. A matemática comum passou **26 testes/83 asserções**; projecção **11/21**; interface simulada **14 testes**. Lint dos ficheiros afectados e formatação das classes novas passaram.
|
||||
|
||||
Regressões preservadas/actualizadas: devolução original com reconciliação/restauro **166** (`20261130-203805-b7652c1e`), entrada positiva/CMP **157** (`20261130-203820-73ca9047`), transferência/reconciliação **163** (`20261130-203835-21f7fea6`), schema/dados **17** (`20261130-203849-194565f3`), serviços **26** (`20261130-203900-041ddf77`). Provas anteriores válidas de revenda **24** e sugestões **43** reutilizadas.
|
||||
|
||||
Concorrência: duas ligações PostgreSQL disputaram a guarda e as restrições reais copiadas para um schema SQL transitório no livro isolado existente. Foram observados bloqueio e recusa da segunda operação nos casos zero/zero, zero/positivo e positivo/zero. A cópia foi removida, sem alterar dados públicos ou privilégios. Este ensaio cobre a exclusão concorrente na BD; cálculo e autorização foram verificados separadamente pelo escritor nativo e pelos controladores. Não é um teste de carga nem de duas sessões HTTP completas.
|
||||
|
||||
Conferência final apenas de leitura: zero schemas SQL transitórios restantes, tabelas novas revertidas, artigo temporário de abertura ausente e perímetro original `2e18acc7c460bd3c1574b13b3bad768e0187941f103f59d41acc3186aee9fcff` preservado. Sem novas bases, demonstrações, contas, GRANT/REVOKE ou publicação. SGC independente e instalações operacionais intactos. A ligação proprietária permanece uma limitação do ensaio; restauro de servidor/ACL/proprietários, revisão visual, carga e parametrização operacional continuam separados. Os estados pendentes abaixo são históricos.
|
||||
|
||||
## Entrega anterior — valorização e recuperação
|
||||
|
||||
Candidata privada **MERCHANDISE-V2-815d88bc0f2f7105**, preparada e não instalada: 166 ficheiros, 97 sobreposições e 26 fontes de schema sujeitas a recibo próprio. Manifesto SHA-256 `815d88bc0f2f7105b0e4783c0b98fff21c0f4fde36f10b717b93da7f10a3c349`; ZIP `d918a6e9908edad20eec86f5f614b1d6e3339d94f91e93a6367f091b7bf84913`. Aplicação, repetição e recuperação de código passaram **198 verificações** na cópia privada, com o instalador e arranque distribuídos. Prova: `storage/framework/testing/merchandise-v2-f4d2b27db9f9/recovery-result.json`. Não equivale a instalação, activação ou aceitação operacional; SGF real permanece em 0.1.1.
|
||||
|
||||
Revisão fonte `723e67e88eff653a9cc7648f3319528276ebd48a4105ff2d94b4b57af815010f`, ZIP `472f8ab3275a93f5e282145a8d1610524afbb468e32b63776764fe42fac18637`; compilação de compatibilidade `cab61896c8e4aa47`, manifesto `ea7bb21a3e3780d84b6f27a4275998b50f8a24f55724cdccffb4bcd39bda972f`, ZIP `6ba573b6241154f8ed73f08d7bd65073036daf7c4b3b373faa9f03ebe1fbde10`. A candidata sucede à `9c182cdaabd8f13f` neste recorte, preservando os pacotes/provas históricos.
|
||||
|
||||
| Capacidade | Estado e prova actual |
|
||||
| --- | --- |
|
||||
| Abertura 4 UN/75 MZN | Ensaio expressamente autorizado concluído e revertido; perímetro original recuperado por hash |
|
||||
| Entradas com custo explícito | Mesmo diário, custo total por movimento, revisão independente; 157 verificações na diferença positiva/CMP |
|
||||
| Devolução pela recepção original | Ligação financeira implementada no mesmo escritor; custo original distinto da taxa antiga, bloqueio de preço livre, replay, falha tardia e revogação conferidos |
|
||||
| Camada original indisponível | Bloqueio até reconciliação independente; nova versão conserva quantidade/valor e identifica a recepção. Prova nativa de camada não identificada e reposição explícita; esgotamento por saídas conferido no cálculo PHP/SQL |
|
||||
| Transferência e venda no destino | Propriedade conferida sem despesa na transferência; reconciliação posterior também ensaiada, 163 verificações |
|
||||
| Schema e dados utilizados | Recuperação dos schemas completos, mais restauro destrutivo revertido das novas tabelas preenchidas, guardas e sequências; falha parcial recuperada sem repetir lançamentos |
|
||||
| Custo de saída arredondado a zero | Bloqueado pelo contrato financeiro actual; decisão específica pendente em [proposta de recibos de custo zero](proposta-custos-zero-sgf.md) |
|
||||
| Instalação/aceitação operacional | Não executadas; configuração real, acessos e revisão visual mantêm etapas próprias |
|
||||
|
||||
Provas financeiras incluídas: FIFO com recuperação de dados utilizados — **166**, execução `20261130-191939-364e83d0`; CMP/devolução/reconciliação — **152**, `20261130-191619-be8771be`; transferência/reconciliação — **163**, `20261130-191632-9a67395b`; diferença positiva/CMP — **157**, `20261130-191645-7156c2af`. Restauro de schemas — **15**, `20261130-191659-85a37153`. Serviços anteriores — 26; políticas de revenda — 24 reutilizadas; sugestões — 43 na execução `20261130-192002-77f00a5f`. São passagens sobrepostas, não um total de casos distintos. Mantêm-se 22 testes/63 asserções do cálculo, 11/21 da projecção e 13 testes focados de interface simulada; não substituem aceitação visual ou testes de carga.
|
||||
|
||||
O restauro das tabelas preenchidas usa exclusivamente a ligação proprietária existente da regressão, incluindo `CREATE/DROP` das estruturas testadas e `ALTER TABLE ... DISABLE/ENABLE TRIGGER USER` durante a reposição dos registos já aceites; as chaves estrangeiras continuam activas. Não se atribuem estes privilégios à aplicação nem se executam GRANT/REVOKE. Esta ligação continua uma limitação conhecida do ensaio, não um modelo de cliente. As provas são transaccionais na mesma base e não cobrem perda do servidor ou restauro de ACL/proprietários.
|
||||
|
||||
A integração integral permanece **parcialmente concluída**. Os estados seguintes são históricos: a ligação financeira de devoluções, os cortes posteriores a transferências e a preparação da candidata entretanto avançaram conforme a matriz acima. Não criar outro motor, juntar bases, publicar ou activar o conector por esta preparação.
|
||||
|
||||
## Seguimento autorizado — variantes e recuperação de schema/dados
|
||||
|
||||
Actualização do seguimento: o ensaio de abertura autorizado está concluído e revertido. A reconciliação de camadas já dispõe de proposta, revisão independente, histórico paginado, ecrã próprio e recibo de recuperação. A distribuição conserva exactamente a quantidade e o valor contabilizados; referências a recepções mantêm o custo original e o restante fica explicitamente identificado como saldo reconciliado. Não cria movimentos ou lançamentos nem altera custos anteriores. As saídas seguintes usam o corte aprovado; versões, política, origem, direitos actuais e identidade são conferidos no servidor e no SQL.
|
||||
|
||||
Provas privadas mais recentes: FIFO com reconciliação `20261130-185630-0e13403c/merchandise-cost-result.json` (160 verificações, incluindo endpoint directo, Blade, consulta sem escrita, recibo privado, colisão de identidade e revogação); CMP `20261130-185245-70c2aa48/merchandise-cost-result.json` (157 verificações, anterior ao último reforço de titularidade do recibo); entrada positiva/CMP `20261130-185506-9e39f6d0/merchandise-cost-result.json` (157 verificações). Não somar passagens sobrepostas. Cálculo comum: 22 testes/63 asserções; projecção: 11 testes/21 asserções; interface de reconciliação: seis testes simulados. Pint e análise estática do cálculo passaram. Revisão visual continua separada.
|
||||
|
||||
Recuperação actualizada: `20261130-185051-7dac1a97/schema-data-recovery.json`, 15 verificações, inclui instalação/remoção de estruturas vazias de custos explícitos e reconciliação, restauro dos dois schemas, linhas e sequências, falhas parciais e rollback final. Não ensaia perda do servidor, restauro de ACL/owners ou instalação operacional.
|
||||
|
||||
Limites ainda abertos: ligação financeira completa de devoluções com preços de recepção diferentes e camadas consumidas; reconciliação após transferências já valorizadas (o corte actual recusa esse histórico); custos financeiros arredondados a zero; preparação da nova candidata e aceitação transversal. Os cálculos PHP/SQL de devolução pela recepção original, incluindo camadas reconciliadas, já têm regressão, mas não equivalem ao percurso financeiro completo. A candidata `9c182cdaabd8f13f` não inclui este seguimento. As descrições «em desenvolvimento» abaixo são estados históricos, não substituem estas limitações actuais.
|
||||
|
||||
O proprietário autorizou expressamente em 30/11 continuar a integração, sem novas demonstrações/publicação, e aprovou duas regras: devoluções a fornecedor pelo custo da recepção original, sem recalcular saídas anteriores, com reconciliação independente de camadas já consumidas; e custo explícito proposto/aprovado por outra identidade para diferenças positivas ou aberturas sem aquisição identificável. Estas decisões não concedem direitos, instalam schema operacional ou parametrizam valores empresariais.
|
||||
|
||||
Autorização adicional expressa: apenas o ensaio revertido do quarto artigo `QA-ABERTURA-20261130`, livro no contexto 1/2/2/armazém12, contagem4UN/custo total75MZN, preparação15/revisão16. Implementado no auxiliar de testes com diário e hashes do perímetro, sem alterar `ComposedMaterialIsolation` nem o perímetro da8085. A prova de abertura passou154verificações em `20261130-181646-80222768/merchandise-cost-result.json`; o perímetro original foi reposto byte a byte (`2e18acc7c460bd3c1574b13b3bad768e0187941f103f59d41acc3186aee9fcff`). Isto não autoriza manter outro artigo/livro, criar contas ou conceder direitos.
|
||||
|
||||
O custo explícito de entradas foi ligado ao MESMO diário: novas propostas/revisões nativas de valor total por movimento, comandos repetíveis no recibo de stock existente, controlos SQL, configuração de contas própria e formulários no razão integrado. O custo não cria recepção fictícia, dívida, pagamento ou novo movimento. Diferença positiva por lotes mantém a quarentena original; não se concedeu poder a um interveniente para libertar o próprio lote. Uma abertura não rastreada usa a contagem/ajuste originais, com aprovação independente do custo; não impõe regras de lotes a artigos sem rastreio. Recuperação de schema vazio ensaiada, remoção de decisões utilizadas recusada. O circuito persistido de reconciliação de camadas ainda está em desenvolvimento; os estados anteriores abaixo são históricos.
|
||||
|
||||
Em desenvolvimento: prefixo de propriedade v2 para transferência interna seguida de venda no destino, sem despesa na expedição/recepção e com dedução única no relatório de propriedade; ajustes negativos previamente conferidos; devoluções valorizadas pela recepção identificada no cálculo comum e na validação SQL. A disponibilidade da camada original é obrigatória; no CMP, sem alocações qualificadas que provem a origem, a disponibilidade incerta após saídas exige reconciliação, sem pressupor uma afectação física. O custo explícito de entradas positivas e a reconciliação persistida ainda estão em implementação. A candidata anterior não inclui este seguimento até nova preparação identificada por hashes.
|
||||
|
||||
Recuperação ensaiada no livro de regressão existente: dumps consistentes de ambos os schemas públicos, reprodução integral dentro de transacções, comparação de todas as linhas/sequências e estruturas, aplicação das migrações novas e falhas parciais. **11 verificações** passaram, prova privada `20261130-174654-1079e69f/schema-data-recovery.json`. A comparação normaliza apenas a conversão equivalente de arrays de literais varchar para text que o PostgreSQL reescreve ao restaurar; não ignora restrições ou valores. As ligações proprietárias existentes, sem CREATEDB/CREATEROLE/superutilizador, foram reutilizadas sem concessões. Não foi criado outro servidor/base/demonstração. Esta prova é restauro transaccional na mesma base isolada, não recuperação após perda do servidor nem restauro de ACL/owners. As bases originais foram repostas por rollback e conferidas.
|
||||
|
||||
## Continuação: sugestões de mercadorias e entrega v2 conferida
|
||||
|
||||
Integrado em desenvolvimento o percurso política de revenda aprovada → sugestão → conferência por outra identidade → requisição em rascunho → submissão/reserva → aprovação. O adaptador reutiliza SupplySuggestions, RequisitionWorkflow e a reserva originais. Estimativas, finalidade e versão aprovada acompanham a origem e o histórico; não se calcula imposto com números de vírgula flutuante na interface. A conversão não submete nem reserva por si mesma.
|
||||
|
||||
O servidor verifica módulo, empresa/unidade, permissões actuais e a origem auditada de cada versão. A mesma referência física não permite consultar outra unidade. O recibo de uma confirmação incerta pode ser recuperado por leitura; só uma resposta explícita de recibo ausente permite repetir o comando original. Revogação bloqueia confirmação e repetição. Alterações por guardar oferecem guardar, descartar ou cancelar; falha mantém a preparação no ecrã.
|
||||
|
||||
Passaram **43 verificações de integração**, **24 de políticas** e **16 testes de interface simulada**. Usaram-se as contas e o livro de regressão existentes, com perfis efémeros revertidos e transportes de mensagens simulados. As linhas anteriores foram conferidas e preservadas; nenhuma concessão persistente, nova instalação ou comunicação externa. Não constitui aceitação visual nem prova de duas conversões simultâneas.
|
||||
|
||||
Candidata actual de código: **MERCHANDISE-V2-9c182cdaabd8f13f**, 155 ficheiros/86 sobreposições; manifesto SHA-256 `9c182cdaabd8f13f17ad94fe891ff41a81ca7e1242135aa53f4af6b9cc1261c0`, ZIP `f428b39507869271cbe220437313ea9ab83f116426d85e282556bcc3b1fd7f47`. Fonte revista `14c43e745471ebef`, compatibilidade compilada `a7cc8cbadcccc00e`. **176 verificações** de aplicação/repetição/recuperação de ficheiros passaram, incluindo o instalador e arranque efectivamente distribuídos. As 22 fontes de schema continuam a exigir prova separada; o recibo do ensaio é sintético. Prova privada: `storage/framework/testing/merchandise-v2-bc812c9c44ba/recovery-result.json`. Substitui a candidata de código 46133eee4f4f5ddb para este recorte, sem apagar as provas históricas.
|
||||
|
||||
Ensaio adicional entre processos: um leitor independente recebeu 503 com espera limitada enquanto o contexto estava bloqueado e 200 após libertação. Não executou comandos de negócio nem demonstra duas conversões simultâneas. Prova do percurso: `suggestion-integration-result.json`, execução privada `20261130-145628-3ece0103`; 43 verificações incluem este ensaio.
|
||||
|
||||
Instalações, configuração e ponteiro operacional preservados. Flags de sugestões e revenda permanecem desligadas por defeito. Continuam pendentes as variantes de valorização de transferências/devoluções/ajustes, recuperação operacional de schema/dados e aceitação transversal; a integração total não é declarada concluída.
|
||||
|
||||
## Continuação: arredondamento aprovado
|
||||
|
||||
O proprietário definiu arredondamento ao cêntimo, metade para cima, com acerto do saldo na última saída. Implementado como opção explícita `half_up_final_balance` na política empresarial, proposta/revisão independente, entrega congelada, cálculo comum e validação SQL do mesmo diário. Políticas anteriores continuam exactas; não se lhes atribui uma regra retroactivamente. A migração preparada, ainda não instalada, valida a regra e impede que a decisão altere o arredondamento proposto. A reversão de schema vazio e a recusa de apagar históricos utilizados foram novamente ensaiadas.
|
||||
@@ -12,6 +131,20 @@ A integração integral **não está concluída**. A conferência encontrou uma
|
||||
|
||||
## Âmbito autorizado e limites
|
||||
|
||||
### Continuação autorizada: entrega v2
|
||||
|
||||
Implementada a extensão aprovada em `docs/proposta-entrega-integracao-sgf-v2.md`, no mesmo `CodeDeployment`. v1 conserva o seu comportamento; v2 exige o predecessor exacto, ampliação declarada, hashes antes/depois e ausência expressa para ficheiros novos. Valida recibos de schema por origem/destino/ficheiros e inclui o hash do recibo no alvo revisto. Recuperação preserva alterações desconhecidas; usa bytes preparados conferidos, sem reler uma origem mutável na aplicação.
|
||||
|
||||
Corrigida a preparação anterior que exigia `sourcing/bootstrap.php` sem incluir a pasta correspondente. A composição v2 já não habilita automaticamente requisições ao carregar código. A composição v1 histórica mantém a sua semântica. O cálculo comum é carregado da própria cópia verificada da candidata, somente quando explicitamente habilitado; uma versão divergente já carregada é recusada. Não cria outro escritor ou dependência de execução da pasta-fonte SGC.
|
||||
|
||||
Candidata de código **MERCHANDISE-V2-46133eee4f4f5ddb**, 147 ficheiros e 78 sobreposições. ZIP SHA-256 `e664273baeef86b0bd96df3df3722acef838932da5d953f52ef6683080d68e1c`; manifesto `46133eee4f4f5ddb789eb3e7d91f1c40960847fe431bacc251f965cad1c87b5d`. Fontes: revisão 336a3885051d0e36 e preparação compilada 1b535581af984ca1. A base de desenvolvimento é Git `fe02d1d5d03c5b02a7aa6602dcfd55c88fb69d96`, com bytes canónicos do Git e manifesto de compilação existente identificado separadamente. Não é uma certificação dos bytes ou do estado da instalação operacional. Uma instalação que já tenha outra entrega exige preparação de transição com o predecessor correspondente; não reutilizar esta candidata inicial como actualização indiscriminada.
|
||||
|
||||
**Verificação:** 24 testes/76 asserções do instalador, quatro/12 do arranque condicionado e 14/38 do cálculo comum passaram. Duas verificações adicionais de links foram ignoradas porque o ambiente não permitiu criar links; nenhum privilégio foi alterado. Falhas em seis etapas duráveis, repetição, reversão em ordem, ficheiros inesperados/adulterados, paths indevidos e recibos divergentes cobertos. Preparação real: **160 verificações** de ficheiros aplicados/restaurados, ausência reposta, repetição, ponteiro preservado e qualificação do próprio instalador/arranque/cálculo distribuídos. Compilação privada e Pint dirigidos aprovados. Sem ligação a base nesta prova de entrega.
|
||||
|
||||
Há 22 fontes de schema que exigem conferência separada. O recibo usado no ensaio é marcado sintético e pertence exclusivamente à cópia privada; não integra o ZIP nem autoriza migrar qualquer base. Não se certificou restauro operacional de dados/schema. Prova: `storage/framework/testing/merchandise-v2-ed79c8ff9bfe/recovery-result.json`. O arquivo 7b67b2a3022b9acd é preliminar e não passou a qualificação posterior do instalador incluído; foi preservado e substituído pela identificação acima, sem instalação.
|
||||
|
||||
**Limites preservados:** nenhum destino instalado, módulo operacional 0.1.1 intacto, sem activação, publicação, GRANT/REVOKE ou concessões persistentes. Continuam necessários os percursos de sugestões/requisições para revenda e a qualificação das variantes de custo; uma entrega de código recuperável não equivale à integração funcional integral concluída.
|
||||
|
||||
### Continuação: políticas de mercadorias para venda
|
||||
|
||||
O adaptador `StockCompletionController` passou a admitir a finalidade original `resale` quando a capacidade separada `merchandise_invoices.resale_planning_enabled` está habilitada. Valor por defeito falso, sem activação de instalações. O ecrã usa as finalidades realmente disponíveis, exige escolha quando existem duas, preserva a finalidade na edição e mostra-a na conferência. A aprovação continua no `SupplyPlanning` original, com identidade independente. Não se criam requisições, movimentos ou lançamentos por guardar/aprovar uma política.
|
||||
@@ -76,18 +209,19 @@ Esta candidata é resultado do preparador anterior reconciliado; a sua existênc
|
||||
|
||||
Este ensaio cobre recuperação de código e ficheiros da candidata; não demonstra recuperação de dados/schema nem aceitação empresarial. Nenhuma alteração de schema integra este incremento.
|
||||
|
||||
## Matriz do restante circuito
|
||||
## Matriz histórica do restante circuito — anterior à conferência das versões
|
||||
|
||||
| Parte | Evidência encontrada | Situação para a integração total |
|
||||
| --- | --- | --- |
|
||||
| Compras até reconhecimento da obrigação | Percurso C01–C10 documentado na instalação 8085 em 04/11 | Reutilizar e conferir diferenças posteriores do SGC; não repetir documentos de prova. |
|
||||
| Actualização e recuperação | Mecanismos existentes; compatibilidade com o host actual corrigida neste incremento | Preparação aprovada no âmbito de ficheiros; instalação excluída. |
|
||||
| Actualização e recuperação | Mesmo instalador com v2 autorizado, predecessor/hash/ausência/recibos; 176 verificações em cópia e arranque incluído | Candidata de código 9c182cdaabd8f13f preparada; compatibilidade/recuperação operacional de schema e dados e instalação excluídas deste ensaio. |
|
||||
| Sugestão e requisição para revenda | Política e estimativas versionadas, decisão independente, conversão/submissão/reserva/aprovação originais; 43 verificações em rollback | Integrado em desenvolvimento, sem activação; duas conversões simultâneas e revisão visual ainda por conferir. |
|
||||
| Venda de mercadorias no SGC | CustomerSales, CustomerDeliveries e SalesStockSource em trabalho paralelo, com livro cr_* comum | Preservar; não copiar o livro nem presumir equivalência com facturas nativas do SGF. |
|
||||
| Facturação existente do SGF | Extensão tipada de mercadorias testada no escritor nativo, com catálogo real | Implementada em desenvolvimento; não activada na demonstração ou instalação operacional. Guardas QA mantidas. |
|
||||
| Dívida e recebimentos de cliente | Recebível, recebimento parcial, afectação e reversão testados no percurso nativo | Integrados em desenvolvimento; sem dinheiro real. Variantes documentais restantes e implantação ainda por aceitar. |
|
||||
| Entrega física da mercadoria | Linha/versionamento/saldo/repetição ligados ao StockWorkflow original | Implementada e ensaiada em rollback; publicação, activação e revisão visual pendentes. |
|
||||
| Contabilidade das mercadorias | Venda e custo pelo mesmo diário; FIFO/CMP, revisão, repetição, recuperação e validação SQL ensaiados | Prefixo qualificado de entradas/saídas. Transferências/devoluções/ajustes e aberturas incompatíveis ficam pendentes; configuração empresarial explícita. |
|
||||
| Equivalência global e entrega | 128 verificações por método, 26 regressões de serviços e pacote privado de revisão | Integração total permanece parcial; sem aceitação global, pacote instalável total ou publicação. Falta a conferência transversal de compras para revenda. |
|
||||
| Equivalência global e entrega | Provas financeiras anteriores válidas preservadas, 24 de políticas, 43 de sugestões e candidata de código v2 recuperável | Integração funcional permanece parcial; variantes de custo e aceitação transversal pendentes, sem publicação. |
|
||||
|
||||
A facturação do SGF ainda tem guardas de conformidade de teste; não foram retiradas. Desenvolver em QA não equivale a habilitar emissão fiscal real. Regras, séries, taxas, contas e correspondências empresariais dependem da parametrização e da autorização da instalação, não de valores de demonstração.
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"format": "tempo.sgf-composition-extension-proposal.v1",
|
||||
"status": "awaiting_specific_contract_authorisation",
|
||||
"implemented": false,
|
||||
"activated": false,
|
||||
"predecessor_manifest_sha256": "3d2e9743ecf621d3e0113769a5339df7b0a704822d09243ef29a79015034770a",
|
||||
"existing_native_bundle_manifest_sha256": "7709a3d447d54c17d2fb4be4f9a0f70455c4a38c34e4bb8c643f6b5169071556",
|
||||
"features": [
|
||||
"conflict-release",
|
||||
"order-cancellation-cycles"
|
||||
],
|
||||
"proposed_unit_rights": [
|
||||
"purchasing_conflicts.view",
|
||||
"purchasing_conflicts.authorise",
|
||||
"purchasing_order_cancellations.view",
|
||||
"purchasing_order_cancellations.prepare",
|
||||
"purchasing_order_cancellations.approve",
|
||||
"purchasing_order_cancellations.revise"
|
||||
],
|
||||
"account_assignments": [],
|
||||
"persistent_grants": 0,
|
||||
"sql_grants": [],
|
||||
"source_pins": {
|
||||
"app/Services/ConflictReleases.php": "2fbe67958d4772d6f7c580456679f3d27385c8780775ed672b9b26d46fd65566",
|
||||
"app/Models/ConflictRelease.php": "bd7fa0ee0a3e901227fb50a7b19d2285a46472842a72b27a3f10aa175e1f52fb",
|
||||
"app/Services/ConflictGuard.php": "b5b7e28a96741e31d99e02a0865d5938ff4345fc88f3a66907b5a0832979f60f",
|
||||
"database/migrations/2026_11_28_000001_create_conflict_releases.php": "a0f24ccc5961de00a3ed0ec9ddb9c6f45db022b2638c0c81c1507306b3f10af4",
|
||||
"app/Services/OrderCancellationWorkflow.php": "1f45c710e45e577d79c164d14254697c604af626ac56612ab44ab78d2a917da7",
|
||||
"app/Services/OrderCancellationRuntime.php": "5a98bb958c0bf5652d986dbdb63604feb4c46b9ee49f0364cde00473a40c20f0",
|
||||
"database/migrations/2026_11_03_000003_create_order_cancellations.php": "c60bf9123b9c9e2ef56687779f1e90b063a34a22d957df5c045dc4d2230f17d3",
|
||||
"packages/order-cancellation/releases/0.2.0-rc.1/manifest.json": "52df7927aa2689598ce1be92de1483694347a696245704abb9e3925db7abfc0f",
|
||||
"packages/order-cancellation/releases/0.2.0-rc.1/src/CommitmentReversal.php": "ecf0028a57b0280cf3a889da29a6e528c7eaa6a876e700b32ff59ac3b3eeb069"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"passed": true,
|
||||
"checks": 176,
|
||||
"candidate": "MERCHANDISE-V2-9c182cdaabd8f13f",
|
||||
"manifest_sha256": "9c182cdaabd8f13f17ad94fe891ff41a81ca7e1242135aa53f4af6b9cc1261c0",
|
||||
"archive_sha256": "f428b39507869271cbe220437313ea9ab83f116426d85e282556bcc3b1fd7f47",
|
||||
"bundled_updater_qualified": true,
|
||||
"bundled_bootstrap_and_cost_qualified": true,
|
||||
"bootstrap_did_not_enable_requisitions": true,
|
||||
"baseline_git_commit": "fe02d1d5d03c5b02a7aa6602dcfd55c88fb69d96",
|
||||
"code_copy": "C:/laragon/www/compras/storage/framework/testing/merchandise-v2-bc812c9c44ba",
|
||||
"schema_or_data_recovery_qualified": false,
|
||||
"synthetic_schema_receipt_only": true,
|
||||
"database_connected": false,
|
||||
"destination_installed": false,
|
||||
"pointer_preserved": "0.1.1",
|
||||
"published": false
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"status": "candidate_prepared_not_installed",
|
||||
"integration_complete": false,
|
||||
"candidate": {
|
||||
"id": "MERCHANDISE-V2-815d88bc0f2f7105",
|
||||
"manifest_sha256": "815d88bc0f2f7105b0e4783c0b98fff21c0f4fde36f10b717b93da7f10a3c349",
|
||||
"archive_sha256": "d918a6e9908edad20eec86f5f614b1d6e3339d94f91e93a6367f091b7bf84913",
|
||||
"source_review_manifest_sha256": "723e67e88eff653a9cc7648f3319528276ebd48a4105ff2d94b4b57af815010f",
|
||||
"source_review_archive_sha256": "472f8ab3275a93f5e282145a8d1610524afbb468e32b63776764fe42fac18637",
|
||||
"compatibility_manifest_sha256": "ea7bb21a3e3780d84b6f27a4275998b50f8a24f55724cdccffb4bcd39bda972f",
|
||||
"baseline_git_commit": "fe02d1d5d03c5b02a7aa6602dcfd55c88fb69d96",
|
||||
"files": 166,
|
||||
"host_overlays": 97,
|
||||
"schema_sources_requiring_separate_receipt": 26,
|
||||
"code_recovery_checks": 198,
|
||||
"code_recovery_proof": "storage/framework/testing/merchandise-v2-f4d2b27db9f9/recovery-result.json"
|
||||
},
|
||||
"isolated_book": {
|
||||
"id": "b4093c6f6707",
|
||||
"scope": [1, 2, 2],
|
||||
"warehouse_id": 12,
|
||||
"temporary_opening_item": "QA-ABERTURA-20261130",
|
||||
"temporary_quantity_milli": 4000,
|
||||
"temporary_amount_minor": 7500,
|
||||
"opening_rehearsal_reverted": true,
|
||||
"material_perimeter_sha256_restored": "2e18acc7c460bd3c1574b13b3bad768e0187941f103f59d41acc3186aee9fcff"
|
||||
},
|
||||
"regression_runs": {
|
||||
"fifo_original_return_reconciliation_used_data_recovery": {"run": "20261130-191939-364e83d0", "checks": 166},
|
||||
"weighted_average_original_return_reconciliation": {"run": "20261130-191619-be8771be", "checks": 152},
|
||||
"transit_and_subsequent_reconciliation": {"run": "20261130-191632-9a67395b", "checks": 163},
|
||||
"positive_input_weighted_average": {"run": "20261130-191645-7156c2af", "checks": 157},
|
||||
"schema_data_restore": {"run": "20261130-191659-85a37153", "checks": 15},
|
||||
"retained_service_finance": {"run": "20261130-191709-afbd6313", "checks": 26},
|
||||
"retained_resale_policy": {"run": "20261130-145429-852ee636", "checks": 24},
|
||||
"suggestion_integration": {"run": "20261130-192002-77f00a5f", "checks": 43}
|
||||
},
|
||||
"counts_overlap_do_not_sum": true,
|
||||
"focused_checks": {"stock_costing_tests": 22, "stock_costing_assertions": 63, "projection_tests": 11, "projection_assertions": 21, "ui_simulated_tests": 13, "stock_costing_static_analysis_errors": 0},
|
||||
"boundaries": {
|
||||
"new_databases": 0,
|
||||
"new_demonstrations": 0,
|
||||
"new_accounts": 0,
|
||||
"persistent_grants": 0,
|
||||
"operational_installation_touched": false,
|
||||
"sgc_operational_data_touched": false,
|
||||
"published": false,
|
||||
"connector_activated": false,
|
||||
"visual_acceptance": false,
|
||||
"new_server_disaster_restore_tested": false,
|
||||
"acl_owner_restore_tested": false
|
||||
},
|
||||
"decision_pending": "docs/proposta-custos-zero-sgf.md",
|
||||
"limitations": [
|
||||
"Zero-rounded outgoing costs remain blocked pending the explicit contract decision.",
|
||||
"The SQL owner connection is an isolated rehearsal limitation, not a client application permission model.",
|
||||
"Used-table recovery and complete-schema restore are transactional rehearsals in the existing isolated databases.",
|
||||
"The native financial return fixture reuses one actual original receipt at a cost different from the legacy rate; multiple-price receipt arithmetic and exhausted-layer refusal are separately qualified in PHP and SQL.",
|
||||
"Operational parametrisation, installation, visual review and load acceptance remain separate."
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
{
|
||||
"format": "tempo.sgf-purchasing-access-delivery.v1",
|
||||
"installed": false,
|
||||
"activated": false,
|
||||
"candidate": "MERCHANDISE-V2-3d2e9743ecf621d3",
|
||||
"manifest_sha256": "3d2e9743ecf621d3e0113769a5339df7b0a704822d09243ef29a79015034770a",
|
||||
"archive_sha256": "46cfe55141e180565cf7617ec487ca30eacf86494601997bdb466039580a67ac",
|
||||
"code_recovery_checks": 202,
|
||||
"code_recovery_proof": "storage/framework/testing/merchandise-v2-86f3c3a3fbd8/recovery-result.json",
|
||||
"financial_review_reused": "bd787c45e6f91bf08b2b38a958645c8bfcb5301652452800d10bf6cd6dbd76b8",
|
||||
"native_access_proof_sha256": "2c146000199edc0538ff69e269bf03f4f22db5481633786ef4a2cd6c21b40f47",
|
||||
"native_access_checks": 54,
|
||||
"native_access_proof": {
|
||||
"passed": true,
|
||||
"checks": [
|
||||
"native SQL scope matches purchasing_requests.view",
|
||||
"native SQL scope matches purchasing_requests.prepare",
|
||||
"native SQL scope matches purchasing_requests.submit",
|
||||
"native SQL scope matches purchasing_requests.approve",
|
||||
"native SQL scope matches purchasing_sourcing.view",
|
||||
"native SQL scope matches purchasing_sourcing.prepare",
|
||||
"native SQL scope matches purchasing_sourcing.evaluate",
|
||||
"native SQL scope matches purchasing_sourcing.select",
|
||||
"native SQL scope matches purchasing_sourcing.approve",
|
||||
"native SQL scope matches purchasing_orders.view",
|
||||
"native SQL scope matches purchasing_orders.issue",
|
||||
"native SQL scope matches purchasing_receipts.view",
|
||||
"native SQL scope matches purchasing_receipts.confirm",
|
||||
"native SQL scope matches purchasing_suppliers.view",
|
||||
"native SQL scope matches purchasing_suppliers.prepare",
|
||||
"native SQL scope matches purchasing_suppliers.review",
|
||||
"native SQL scope matches purchasing_invoices.view",
|
||||
"native SQL scope matches purchasing_invoices.prepare",
|
||||
"native SQL scope matches purchasing_invoices.validate",
|
||||
"native SQL scope matches purchasing_obligations.view",
|
||||
"native SQL scope matches stock.view",
|
||||
"native SQL scope matches stock.operations.prepare",
|
||||
"native SQL scope matches stock.operations.confirm",
|
||||
"native SQL scope matches stock.transfers.receive",
|
||||
"native SQL scope matches stock.lots.review",
|
||||
"native SQL scope matches stock.items.prepare",
|
||||
"native SQL scope matches stock.items.review",
|
||||
"native SQL scope matches stock.planning.view",
|
||||
"native SQL scope matches stock.planning.prepare",
|
||||
"native SQL scope matches stock.planning.review",
|
||||
"native SQL scope matches stock.disposition.view",
|
||||
"native SQL scope matches stock.disposition.prepare",
|
||||
"native SQL scope matches stock.disposition.review",
|
||||
"actual unit creation grants only the two original base rights",
|
||||
"new unit seed never receives module rights automatically",
|
||||
"unknown rights remain forbidden",
|
||||
"existing module right is offered only at its unit scope",
|
||||
"interface receives a concrete action label",
|
||||
"unit right cannot be granted at company scope",
|
||||
"foreign unit cannot receive a module grant",
|
||||
"administrator cannot delegate a right they do not hold",
|
||||
"target must already be allowed to consult that unit",
|
||||
"repeated grant creates one scoped right",
|
||||
"administrative list includes the scoped module grant",
|
||||
"revocation takes immediate effect",
|
||||
"module revocation preserves existing unit access",
|
||||
"revoked administrator cannot list accesses",
|
||||
"revoked administrator cannot repeat a grant",
|
||||
"existing immutable access audit is reused",
|
||||
"rollback preserves permission_grants",
|
||||
"rollback preserves company_memberships",
|
||||
"rollback preserves identity_audit",
|
||||
"rollback preserves units",
|
||||
"rollback preserves users"
|
||||
],
|
||||
"tested_sources": {
|
||||
"resources/js/app.jsx": "45a6a2fc477673ddf9ddd267d2d239cb500270dcf363bbf84c01c57d6ba5b49f",
|
||||
"scripts/sgf-purchasing-access-proof.php": "aeccf8d0a12900ec8ea185723069ef1ab9320ba0850865d22f42f1aaf893ece7",
|
||||
"sgc:integrations/sgf/access/AccessOverlay.php": "b0b32b6545ea104a027dc7a1df1169db712b9b344af35a6bc6787a31a09c8fea",
|
||||
"sgc:integrations/sgf/access/NativeAccessCatalogue.php": "8b8a328846a5c3342a6a4a9e574a9392b9e16470487b837a8a1d993dd7430eb0",
|
||||
"sgc:integrations/sgf/operational/AdminUiOverlay.php": "e76feecbb567e90dda37cd71422511b5769701c331ae47bca5e00ba40a2e92bf"
|
||||
},
|
||||
"prepared_sources": {
|
||||
"app/Modules/Identity/Services/Permissions.php": {
|
||||
"before_sha256": "97a860b632de0cb5022b2d9153261ecfa2211c100961eb6b9e6a09d30f798e63",
|
||||
"after_sha256": "8096322cf25c615647ea669fede7ff08d17f741d9aee7583ed892528b357f085"
|
||||
},
|
||||
"app/Modules/Identity/Services/IdentityWorkflow.php": {
|
||||
"before_sha256": "66da58c37c7e57b45700807b7262a5b5cc9c6e4192231342fa31bb854fc4ee0a",
|
||||
"after_sha256": "9fed5b36934d89a6ba6b4dad3497328e23fc1e21363ad5cfe87bb5dd4db5e9fa"
|
||||
}
|
||||
},
|
||||
"rolled_back": true,
|
||||
"persistent_grants": 0,
|
||||
"new_accounts": 0,
|
||||
"visual_review": false
|
||||
},
|
||||
"candidate_sources_verified": true,
|
||||
"frontend_private_build": true,
|
||||
"visual_review": false,
|
||||
"schema_changes_in_this_increment": false,
|
||||
"financial_proofs_repeated": false,
|
||||
"new_accounts": 0,
|
||||
"persistent_grants": 0,
|
||||
"independent_sgc": true,
|
||||
"global_integration_complete": false
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
{
|
||||
"format": "tempo.sgf-workflow-inventory.v1",
|
||||
"manifest_sha256": "7709a3d447d54c17d2fb4be4f9a0f70455c4a38c34e4bb8c643f6b5169071556",
|
||||
"bundle_integrity": true,
|
||||
"read_only": true,
|
||||
"functional_acceptance": false,
|
||||
"processes": {
|
||||
"context_permissions": {
|
||||
"source_equivalent": false,
|
||||
"components": {
|
||||
"app/Services/WorkContext.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "8bedc8f420d2a67dd54a926b10659b1aa2ca006f75c2bbc2ba8a3b7babd694b1",
|
||||
"accepted_source_sha256": "f1fc39399d6bc0798d08909801ec370b2e6f00cef402c0f84c9b4bc2bd9b5b26"
|
||||
},
|
||||
"app/Models/Concerns/HasWorkContext.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "ffc8dc7bb6f9334a20031531e2fffec16cf063d66caf284b178bab219b02e686",
|
||||
"accepted_source_sha256": "1cdccd697dbbc0dcc7610b8dfba745533c73fb00c6d28ec3f05706c97750cb1d"
|
||||
},
|
||||
"app/Services/CurrentActor.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "ae88aa7313e7a499fb38be9297a5b605cd0949022807f23a91a9e364170a017f",
|
||||
"accepted_source_sha256": "c425b065099d8b29c064edf2d68fc13ed79ece44eca9c810f277255e2b4b5be4"
|
||||
},
|
||||
"app/Services/OrganizationAccess.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "9acc83889c9ada84d0d3e6a60c3088c4850c4c80e2b23d8c85dd6efc8c71278c",
|
||||
"accepted_source_sha256": "fc22e0e53472b83998bdd0b4d48f51b2e2e2d35a2726c9ce669711538812ecb5"
|
||||
}
|
||||
}
|
||||
},
|
||||
"requisition_budget": {
|
||||
"source_equivalent": false,
|
||||
"components": {
|
||||
"app/Services/RequisitionWorkflow.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "17ce02f241d87aaf86be31563b06c097932f6debd5425af539d2f84212471330",
|
||||
"accepted_source_sha256": "b6bf90c760f50a55a2c98c1d8f707ef644a99ad414e13860d64c7b13096e1868"
|
||||
},
|
||||
"app/Services/BudgetWorkflow.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "5c5a69334fc0b803f9dc16f1e5c7472cdaaa4f3d0fe77c480984566bd0f49276",
|
||||
"accepted_source_sha256": "ef6c631fe1543afab2c977d785bc1336dfff6761f00dab7cd22ba8e691c8591c"
|
||||
},
|
||||
"app/Services/InternalRequisitionPort.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "57f9fc7f1fef0256d267c0fdcda365f568d293a1bc246b8bc92e9e96acf5ec53",
|
||||
"accepted_source_sha256": "ea3652f8f4ca6bf3f4ba7704fce77f83315197ff46033581c9a8a2f7e268938c"
|
||||
},
|
||||
"app/Models/Requisition.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "1137b5d78274b56aefea3be97477a0d60ee36163ef133811f33fa2d3c7a47132",
|
||||
"accepted_source_sha256": "411e50450d0148bd2fadab3723484ac09cde98776ac75834dfe811b867b692fe"
|
||||
}
|
||||
}
|
||||
},
|
||||
"sourcing_award": {
|
||||
"source_equivalent": false,
|
||||
"components": {
|
||||
"app/Services/PurchaseWorkflow.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "dabf06852944acbc1f69f0993d77575f2395cd6d83e4071ef7fe1db8e4c71bf0",
|
||||
"accepted_source_sha256": "84f9db1286058087ecb8cf08c64fcd3afc94c91d1509b985b634a3fcafd81295"
|
||||
},
|
||||
"app/Services/ProposalComparison.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "11cb15ad88ac7d66375707df9e05090dd76c2f24092e0220d9657f7847cdaaef",
|
||||
"accepted_source_sha256": "f34e7f736a18ae9e21bba324ebdf738c02cdcc6b4841367a13a5868631cd5dfa"
|
||||
},
|
||||
"app/Services/ConflictGuard.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "b5b7e28a96741e31d99e02a0865d5938ff4345fc88f3a66907b5a0832979f60f",
|
||||
"accepted_source_sha256": "99990d13512f59f488632a5da48409155af0c63bc58d0916ae005217d711ed14"
|
||||
},
|
||||
"app/Services/ConflictReleases.php": {
|
||||
"status": "not_transferred",
|
||||
"source_sha256": "2fbe67958d4772d6f7c580456679f3d27385c8780775ed672b9b26d46fd65566",
|
||||
"accepted_source_sha256": null
|
||||
}
|
||||
}
|
||||
},
|
||||
"orders_receipts": {
|
||||
"source_equivalent": false,
|
||||
"components": {
|
||||
"app/Services/ReceiptWorkflow.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "c8a497769c48fe20b34e8566454ed1f8a5dcc4f16e849d5537d8ac6ea35eda03",
|
||||
"accepted_source_sha256": "a7325d4fdb09d1767d0d4fa3661bcf9b254e8506285080d6063bbed487bb522c"
|
||||
},
|
||||
"app/Services/OrderCancellationWorkflow.php": {
|
||||
"status": "not_transferred",
|
||||
"source_sha256": "1f45c710e45e577d79c164d14254697c604af626ac56612ab44ab78d2a917da7",
|
||||
"accepted_source_sha256": null
|
||||
},
|
||||
"app/Policies/GoodsReceiptPolicy.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "888ba3d9315ad6b361a3086259bf8e9c57854a7dc9d5d732144d5a2674b5a56b",
|
||||
"accepted_source_sha256": "ad29228db8f687e7a5b45f189c5bba50cada24265f54e573f49eb9e41fece391"
|
||||
},
|
||||
"app/Services/ReceiptDocuments.php": {
|
||||
"status": "source_unchanged",
|
||||
"source_sha256": "2f529ccc0c790d5e3c5ccedea974d80bb10eb1c4eeff8e729311649a18230ce1",
|
||||
"accepted_source_sha256": "2f529ccc0c790d5e3c5ccedea974d80bb10eb1c4eeff8e729311649a18230ce1"
|
||||
}
|
||||
}
|
||||
},
|
||||
"obligations": {
|
||||
"source_equivalent": false,
|
||||
"components": {
|
||||
"app/Services/InvoiceWorkflow.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "d9e0aff66f94e8928b19b9cc213b6a274aa307e08494b98643d112ad61a81e85",
|
||||
"accepted_source_sha256": "f1e8530315e33d3c8eb23752699b3bbcba0af5248af478e861f3b3e75a462c11"
|
||||
},
|
||||
"app/Services/SupplierPayables.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "35d4029616e987438f7feedcd98e70fb155f9298e144dac00be5959b92549a4c",
|
||||
"accepted_source_sha256": "1f6afc26040f3a4dd583c3489292351358d213ff743c96f9fb2fd007f770ae0d"
|
||||
}
|
||||
}
|
||||
},
|
||||
"warehouse": {
|
||||
"source_equivalent": false,
|
||||
"components": {
|
||||
"app/Services/StockWorkflow.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "da41a8bc70da8ff5786dc9311f3c1368818d4a89ba8f5e1a1e52fa6e930b5b6b",
|
||||
"accepted_source_sha256": "18ddaa075432b84c0b0ee5241ff56ab9de9aa8e8db4e6132693bc7fd904b3a58"
|
||||
},
|
||||
"app/Services/WarehouseRequests.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "4f33f7cbd508ad895de69a32064469efe954b78bbf083491fcff0f59a569df74",
|
||||
"accepted_source_sha256": "729265408efa13d942f86f0c71370a50ac5286f1f00da3d34daa4eb627e476de"
|
||||
},
|
||||
"app/Services/WarehouseReservations.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "7079a19a40714c2a1ae64a8000d34e7dff50a01abc0e87d275dcad70e0ac4b38",
|
||||
"accepted_source_sha256": "3120eaf6d9c8cedf3c991edcb41133f5107ca62736cea7e082ae4773755ffb54"
|
||||
},
|
||||
"app/Services/WarehouseFulfilment.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "97645402c119f67b4df12a509ef9aefce5510cc1323f8ee02e4cf1b06e2ca709",
|
||||
"accepted_source_sha256": "52130ff23382d10e7244b7b4211734772eb4d66518bb9002fc35dfb99f183c02"
|
||||
}
|
||||
}
|
||||
},
|
||||
"replenishment": {
|
||||
"source_equivalent": false,
|
||||
"components": {
|
||||
"app/Services/SupplyPlanning.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "d52dba0bc2f01119ef28c79dfaf416f77987d8b7c8ad30c6d1f1e2da193ec33c",
|
||||
"accepted_source_sha256": "3086dbc6d8d87904255035c6379b2f7d3ed13f2ba762fa3beaaa7a7ab6ee4c28"
|
||||
},
|
||||
"app/Services/SupplySuggestions.php": {
|
||||
"status": "source_unchanged",
|
||||
"source_sha256": "d6841c3bbe87cb43e3c134cedf4f18c60ab3b0ab6c3f4629e85ff90aa74eeecf",
|
||||
"accepted_source_sha256": "d6841c3bbe87cb43e3c134cedf4f18c60ab3b0ab6c3f4629e85ff90aa74eeecf"
|
||||
},
|
||||
"app/Services/AutomaticPurchases.php": {
|
||||
"status": "source_changed",
|
||||
"source_sha256": "dbb973d7620f8a99bdc4752d975d58c5a684ffe5404b974884c812bff5d47149",
|
||||
"accepted_source_sha256": "24dcdda538bee7e46356f26f93411e4f91e64e13db4bb6b09f88356c8bb18c1c"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"authorisation": "Express approval on 2026-11-30 for zero cost receipts, independent review and isolated tests; no operational installation or publication.",
|
||||
"increment_complete": true,
|
||||
"integration_operationally_accepted": false,
|
||||
"supersedes": "sgf-merchandise-valuation-recovery-20261130.json",
|
||||
"candidate": {
|
||||
"id": "MERCHANDISE-V2-6e1b9710e9094c5a",
|
||||
"manifest_sha256": "6e1b9710e9094c5ab91987a1465e6f2e3e3067af4856e93b0053280bfb380760",
|
||||
"archive_sha256": "6c2bc3501849515ab49db7c5200be7a265f789b3defd1f81bab8a5686fc61037",
|
||||
"review_manifest_sha256": "bd787c45e6f91bf08b2b38a958645c8bfcb5301652452800d10bf6cd6dbd76b8",
|
||||
"review_archive_sha256": "e4dd24f3450dad3a78ce041c0bf32b004ad52165d822c493c9899b0e7b178a85",
|
||||
"compatibility_manifest_sha256": "ea7bb21a3e3780d84b6f27a4275998b50f8a24f55724cdccffb4bcd39bda972f",
|
||||
"baseline_git_commit": "fe02d1d5d03c5b02a7aa6602dcfd55c88fb69d96",
|
||||
"files": 168,
|
||||
"host_overlays": 99,
|
||||
"schema_sources_requiring_separate_receipt": 27,
|
||||
"code_recovery_checks": 202,
|
||||
"code_recovery_proof": "storage/framework/testing/merchandise-v2-957d5d2ef984/recovery-result.json",
|
||||
"installed": false
|
||||
},
|
||||
"scope": {
|
||||
"book": "b4093c6f6707",
|
||||
"tenant_company_unit": [1, 2, 2],
|
||||
"native_writer": "PayableJournal",
|
||||
"zero_receipt_table": "gl_stock_zero_costs",
|
||||
"cost_facts_view": "gl_stock_cost_facts",
|
||||
"zero_receipt_creates_journal": false,
|
||||
"zero_receipt_creates_stock_movement": false,
|
||||
"positive_explicit_input_cost_requirement_preserved": true,
|
||||
"rounding": "half_up_final_balance",
|
||||
"independent_review": true,
|
||||
"separate_journal_and_zero_receipt_identities": true
|
||||
},
|
||||
"native_proofs": {
|
||||
"fifo_zero_below_half_final_residual_concurrency_used_data_restore": {"run": "20261130-203737-d83fb894", "checks": 153},
|
||||
"weighted_average_half_cent_zero_residual_concurrency_used_data_restore": {"run": "20261130-203751-65891c96", "checks": 155},
|
||||
"original_receipt_return_reconciliation": {"run": "20261130-203805-b7652c1e", "checks": 166},
|
||||
"positive_input": {"run": "20261130-203820-73ca9047", "checks": 157},
|
||||
"transit_reconciliation": {"run": "20261130-203835-21f7fea6", "checks": 163},
|
||||
"schema_data_recovery": {"run": "20261130-203849-194565f3", "checks": 17},
|
||||
"retained_service_finance": {"run": "20261130-203900-041ddf77", "checks": 26}
|
||||
},
|
||||
"previous_valid_proofs_reused": {"resale_policy_checks": 24, "suggestion_integration_checks": 43},
|
||||
"counts_overlap_do_not_sum": true,
|
||||
"focused_checks": {"stock_costing_tests": 26, "stock_costing_assertions": 83, "projection_tests": 11, "projection_assertions": 21, "simulated_ui_tests": 14, "php_lint_passed": true, "new_class_formatting_passed": true},
|
||||
"concurrency_scope": {
|
||||
"connections": 2,
|
||||
"actual_exclusion_function_and_constraints_copied": true,
|
||||
"cases": ["zero_zero", "zero_positive", "positive_zero"],
|
||||
"blocking_observed": true,
|
||||
"second_effect_refused": true,
|
||||
"one_temporary_sql_schema_created_and_removed_per_run": true,
|
||||
"financial_authorisation_and_arithmetic_tested_separately_in_native_writer": true,
|
||||
"two_complete_http_sessions_tested": false
|
||||
},
|
||||
"preservation": {
|
||||
"new_databases": 0,
|
||||
"new_demonstrations": 0,
|
||||
"new_accounts": 0,
|
||||
"persistent_grants": 0,
|
||||
"operational_installations_touched": false,
|
||||
"sgc_operational_data_touched": false,
|
||||
"connector_activated": false,
|
||||
"published": false,
|
||||
"temporary_opening_item_absent": true,
|
||||
"remaining_temporary_sql_schemas": 0,
|
||||
"new_receipt_tables_rolled_back": true,
|
||||
"original_material_perimeter_sha256": "2e18acc7c460bd3c1574b13b3bad768e0187941f103f59d41acc3186aee9fcff"
|
||||
},
|
||||
"limitations": [
|
||||
"The zero receipt scope is qualified company stock issues calculated from the approved policy, not arbitrary zero-valued incoming costs.",
|
||||
"The SQL owner connection remains an isolated rehearsal limitation, not the client application privilege model.",
|
||||
"Schema/data restore is transactional in the existing isolated book; server loss and ACL/owner restoration are not qualified.",
|
||||
"Visual review, load testing, real company parametrisation and operational installation remain separate."
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
# Saídas cujo custo arredondado é zero — decisão específica
|
||||
|
||||
## Regra existente e lacuna
|
||||
|
||||
A regra aprovada continua a ser arredondamento ao cêntimo, metade para cima, com acerto na última saída. Uma fracção inferior a meio cêntimo pode, por isso, produzir custo financeiro de 0,00 MZN. O cálculo comum já representa esse resultado; `PayableJournal::capture()` e `CompanyStock::capture()` exigem custo positivo. Não se deve inventar um cêntimo, tratar o custo como desconhecido ou enfraquecer a regra geral do diário.
|
||||
|
||||
## Proposta concreta
|
||||
|
||||
Acrescentar um recibo de valorização zero exclusivamente para saídas cujo cálculo comum, com a política empresarial explicitamente aprovada, produza exactamente zero. Recepção ou ajuste de entrada continua a exigir custo positivo explícito; não se aceita um zero livre introduzido pelo utilizador.
|
||||
|
||||
Reutilizar as propostas, revisão por outra identidade, permissões e comando de aplicação do mesmo núcleo contabilístico. A aplicação confirma novamente contexto, origem física, política, versão e dependências. Regista um recibo imutável, sem criar linhas ou lançamento de valor zero no diário. Não cria outro movimento de stock, documento comercial, dívida ou pagamento.
|
||||
|
||||
Preparar uma tabela aditiva `gl_stock_zero_costs`, com contexto, movimento original, proposta/revisão, versão, autor/data, chave de confirmação e evidência congelada. Impor unicidade por movimento e exclusão mútua com um custo positivo já lançado, inclusive em concorrência. O escritor é o `PayableJournal` existente; não acrescentar outro serviço com autoridade financeira.
|
||||
|
||||
Prefixos, histórico e relatórios distinguem custo zero aprovado de custo em falta, usando a referência do recibo sem inventar um identificador de lançamento. Os custos anteriores permanecem intactos; a última saída conserva o acerto do saldo previsto na regra aprovada.
|
||||
|
||||
## Verificação e recuperação propostas
|
||||
|
||||
Ensaiar FIFO/CMP, fracções inferiores e iguais a meio cêntimo, última saída, repetição, concorrência, revisão independente, revogação, isolamento e falha tardia. Usar apenas o livro de regressão existente e dados revertidos. Recuperar código e schema/dados separadamente: remoção apenas de estrutura vazia; recibos utilizados são preservados. Nenhuma nova conta, concessão, demonstração, publicação ou alteração operacional.
|
||||
|
||||
Estado: **autorizada expressamente em 30/11/2026** — «Autorizo implementar os recibos de custo zero, com revisão independente e testes isolados». Implementação e verificação concluídas na candidata privada, sem instalação, publicação, novas contas ou concessões. Não solicitar novamente esta autorização para o mesmo âmbito. [Entrega, matriz e provas actuais](integracao-total-sgf-20261130.md).
|
||||
@@ -1,6 +1,6 @@
|
||||
# Proposta concreta — extensão do contrato de entrega SGF
|
||||
|
||||
Estado: proposta para decisão; não implementa nem autoriza instalação, publicação ou activação.
|
||||
Estado: implementação e testes autorizados pelo proprietário em 30/11/2026, com a resposta «Autorizar implementação e testes da extensão v2». Instalação, publicação, migrações e concessões nas instalações operacionais continuam excluídas. As secções seguintes conservam a proposta aprovada.
|
||||
|
||||
## Motivo
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# Extensão do contrato de execução de Compras no SGF
|
||||
|
||||
Estado: implementação e testes isolados expressamente autorizados pelo proprietário: «Autorizo implementar e testar em isolamento a extensão do contrato proposta». Em desenvolvimento; não instalada ou activada. Concessões persistentes, instalações operacionais e publicação continuam excluídas. As secções seguintes preservam o âmbito autorizado; não voltar a pedir esta autorização.
|
||||
|
||||
## Impedimento confirmado
|
||||
|
||||
O pacote nativo conferido tem manifesto `7709a3d447d54c17d2fb4be4f9a0f70455c4a38c34e4bb8c643f6b5169071556`. Não inclui ConflictReleases nem OrderCancellationWorkflow. A candidata de entrega corrente continua a ser `3d2e9743ecf621d3`, não instalada; esta proposta não a altera.
|
||||
|
||||
ConflictReleases::ready() admite o SGC autónomo qualificado ou, com opção explícita, o ambiente testing nas bases de teste restritas. O SGF utiliza budget-testing e ReceiptRuntime; não satisfaz esse contrato. Alterar o nome do ambiente para contornar a verificação, duplicar o serviço ou ignorar ready() é inadequado.
|
||||
|
||||
O cancelamento actual verifica a versão do componente CommitmentReversal, a localização da classe carregada e os ciclos orçamentais. O componente legado não deve ser usado quando existem ciclos posteriores. Copiar apenas o workflow sem essas verificações arriscaria libertar um compromisso incorrecto.
|
||||
|
||||
São limites do contrato de execução e da autoridade sobre efeitos orçamentais, distintos do instalador de ficheiros v2 já autorizado. A política do repositório exige autorização explícita para alterar contratos de integração ou arquitectura.
|
||||
|
||||
## Alteração concreta proposta
|
||||
|
||||
1. Estender o mecanismo existente de composição, sem outro motor, loader independente ou aplicação. O ReceiptRuntime continua a verificar a instalação física, a identidade actual, o contexto, as correspondências, o manifesto e uma só versão de classes por processo. A composição anterior permanece suportada sem ampliação implícita de capacidades.
|
||||
2. Introduzir uma declaração versionada de capacidades da composição para os serviços partilhados. Deve identificar: versão do contrato, composição, empresa/unidade, hash do pacote de workflows, hashes das dependências financeiras, hash da compatibilidade de schema, capacidades habilitadas e correspondências explícitas de identidade/direitos. A declaração é validada pelo runtime existente antes da execução; não basta uma opção true nem um nome de ambiente.
|
||||
3. Permitir que os serviços originais reconheçam esse contexto de composição validado. As verificações actuais do SGC autónomo e dos testes permanecem. A capacidade recebida só é válida dentro da execução/contexto que a autorizou; não é uma autorização global ou reutilizável depois de mudar de contexto.
|
||||
4. Distribuir no pacote local as versões qualificadas dos serviços, modelos e dependências de Compras necessárias. Os hashes originais e da transformação de namespace ficam no manifesto. Não renomear strings de regras, SQL ou valores de negócio por substituição textual. A instalação SGF não depende da pasta, serviço ou base de uma instalação SGC.
|
||||
5. Para levantamento de impedimentos, reutilizar ConflictReleases, ConflictRelease, ConflictGuard e a migração existente. Exigir a função nativa conflict_release_authorise e o direito específico no SGF, relidos antes de cada execução. Não inferir competência de Direcção a partir de administrador ou financeiro. Conservar fundamento, declaração, raiz, autor, data e histórico; outros conflitos continuam a bloquear.
|
||||
6. Para cancelamento, reutilizar OrderCancellationWorkflow, as políticas/revisões e o componente de reversão por ciclos 0.2.0-rc.1. Conservar os bloqueios por recepções/documentos, a exclusão do autor e demais intervenientes, as regras de peças e a transacção que liga decisão/reversão/auditoria. Não alterar o montante nem criar outro livro. O manifesto exacto do componente e a classe carregada devem coincidir antes de permitir a operação.
|
||||
7. As capacidades novas ficam desligadas por defeito. A preparação do pacote não activa flags, substitui os vínculos privados existentes, concede direitos ou aplica migrações. Os ensaios são explícitos, sintéticos e revertidos no ambiente de regressão existente; não criam outra aplicação ou demonstração.
|
||||
|
||||
Os valores e hashes conhecidos estão no [registo da proposta](proofs/sgf-composition-extension-proposal-20261130.json). Os hashes ali fixados identificam a origem desta análise; qualquer diferença posterior exige nova conferência antes de preparar a candidata. A lista não pretende certificar toda a cadeia de dependências.
|
||||
|
||||
## Direitos e acessos
|
||||
|
||||
Nomes propostos para o catálogo, sempre ao nível da unidade:
|
||||
|
||||
- purchasing_conflicts.view — consultar declarações e histórico autorizado;
|
||||
- purchasing_conflicts.authorise — autorizar levantamento, também exigindo a competência nativa própria;
|
||||
- purchasing_order_cancellations.view — consultar cancelamentos;
|
||||
- purchasing_order_cancellations.prepare — propor cancelamento;
|
||||
- purchasing_order_cancellations.approve — decidir pelo circuito independente existente;
|
||||
- purchasing_order_cancellations.revise — preparar a revisão permitida após cancelamento.
|
||||
|
||||
Não há atribuições a contas nesta proposta. Estes direitos não substituem os direitos nativos nem concedem competência por estarem no catálogo. Não se reutiliza o direito de emitir encomendas para permitir cancelá-las. A implementação preparará as restrições SQL dos nomes/âmbitos; nenhum GRANT/REVOKE ou alteração efectiva de acessos é solicitado.
|
||||
|
||||
Centros, dotações, políticas empresariais e contas reais não são preenchidos. Utilizam-se as ligações e dados sintéticos da regressão autorizada, preservando a limitação conhecida da ligação proprietária; não se adopta esse privilégio para clientes.
|
||||
|
||||
## Verificação e recuperação a executar após autorização
|
||||
|
||||
- Pacote antigo continua válido; pacote novo divergente, capacidade ausente, schema incompatível ou classe de outra versão são recusados.
|
||||
- Identidade, empresa, unidade, módulo/opção, competência específica, autoria, revogação e acesso directo indevido são testados no servidor.
|
||||
- Levantamento preserva a declaração/histórico, repetições não duplicam a autorização e outros conflitos mantêm o bloqueio.
|
||||
- Cancelamento exige política válida e decisão independente, respeita recepções/documentos/ciclos, e não duplica a libertação orçamental em repetição, concorrência ou falha parcial.
|
||||
- Migrações, dados utilizados e recuperação são qualificados em transacções isoladas; versões anteriores continuam reproduzíveis. Reversão de código não elimina schema com histórico utilizado.
|
||||
- Preparar nova candidata pelo instalador v2 existente e actualizar matriz/hashes/provas. Não repetir provas financeiras sem alterações relevantes.
|
||||
|
||||
## Decisão solicitada
|
||||
|
||||
Autorizar exclusivamente a implementação e os testes isolados desta extensão do contrato de execução, incluindo o catálogo dos seis nomes propostos e as estruturas necessárias nos ensaios revertidos. Não autoriza instalar ou activar a candidata, conceder acessos persistentes, alterar instalações operacionais, publicar, fundir bases ou incluir contratações para terceiros no SGF.
|
||||
|
||||
## Decisão adicional: declarações globais por fornecedor
|
||||
|
||||
Esta secção foi identificada durante a implementação e autorizada separadamente pelo proprietário: «Autorizar âmbito de empresa, sem concessões persistentes». A implementação e os testes deste recorte estão autorizados; nenhuma atribuição a contas ou instalação operacional está autorizada por esta decisão.
|
||||
|
||||
ConflictDeclaration permite supplier_id preenchido e requisition_id NULL. Essas declarações aplicam-se à empresa nativa e não têm origem de unidade. A competência nativa conflict_release_authorise permite à Direcção levantá-las, preservando a raiz e a cadeia de correcções. Atribuí-las automaticamente à unidade activa confundiria uma declaração global com um processo dessa unidade.
|
||||
|
||||
Proposta concreta para implementar/testar, sem concessões persistentes:
|
||||
|
||||
- Admitir também o âmbito de **empresa** para purchasing_conflicts.view e purchasing_conflicts.authorise; os mesmos nomes continuam disponíveis no âmbito de unidade para declarações ligadas a processos autorizados dessa unidade.
|
||||
- Uma concessão de unidade nunca permite consultar ou levantar declarações globais por fornecedor. A presença de NULL não é convertida em atribuição de unidade nem alterada nos dados.
|
||||
- Para os registos globais, exigir a concessão de empresa, empresa nativa explicitamente associada à empresa SGF no manifesto, identidade actual, módulo Compras habilitado e a competência nativa própria da Direcção para autorizar. Associações ambíguas entre empresas bloqueiam a operação.
|
||||
- Manter os direitos base de criação de empresa/unidade, sem atribuir automaticamente estes novos âmbitos a administradores ou outras contas. O catálogo permite delegação apenas por quem possui o mesmo direito no mesmo âmbito.
|
||||
- Preservar o alcance global da declaração: o levantamento de um impedimento global não elimina outros conflitos e fica registado como decisão de empresa. Os processos continuam sujeitos ao respectivo contexto e restantes permissões.
|
||||
- Testar separadamente empresa/unidade, autorias, revogação, leitura e recusa de decisão pelo perfil de consulta, sem alterar instalações operacionais ou perfis persistentes.
|
||||
|
||||
Alternativa: manter exclusivamente os direitos de unidade já autorizados. Nesse caso, as declarações globais continuam bloqueadas e ficam explicitamente fora deste incremento SGF; não se declara esse ramo da matriz concluído.
|
||||
@@ -1,6 +1,31 @@
|
||||
# Transferência de Compras e actualizações do SGF
|
||||
|
||||
## Integração integral incluindo mercadorias — 30/11/2026
|
||||
## Estado consolidado da integração — 30/11/2026
|
||||
|
||||
A candidata corrente é **MERCHANDISE-V2-3d2e9743ecf621d3**, não instalada: acrescenta ao preparador existente o catálogo administrativo dos33direitos nativos de Compras/Stock, sem concessões automáticas ou persistentes.54verificações revertidas em PostgreSQL, compilação privada e202verificações de recuperação de código aprovadas. Manifesto `3d2e9743ecf621d3e0113769a5339df7b0a704822d09243ef29a79015034770a`; ZIP `46cfe55141e180565cf7617ec487ca30eacf86494601997bdb466039580a67ac`. [Prova e vínculos exactos](proofs/sgf-purchasing-access-delivery-20261130.json). A6e abaixo é a entrega anterior de valorização, preservada; não é a candidata corrente deste seguimento.
|
||||
|
||||
A [matriz actual](integracao-total-sgf-20261130.md#matriz-actual-consolidada--conferência-das-versões) distingue os recortes aceites das versões posteriores ainda por integrar. A conferência de 25 componentes do pacote nativo encontrou21 fontes divergentes, duas ausentes e duas inalteradas; não é uma nova prova funcional. Levantamento de impedimentos, cancelamento de ordens, diferenças posteriores dos workflows e portabilidade permanecem pendentes. A candidata `6e1b9710e9094c5a` continua inalterada e não instalada. Estados antigos abaixo não substituem esta matriz. Sem aplicação paralela, publicação, alteração operacional ou dependência nova do SGC em execução.
|
||||
|
||||
## Entrega anterior de mercadorias e custo zero — 30/11/2026
|
||||
|
||||
**Candidata desse incremento:** **MERCHANDISE-V2-6e1b9710e9094c5a**, preparada e não instalada, inclui os recibos de custo zero expressamente autorizados, revisão independente, exclusão de custo duplicado e acerto da última saída. Manifesto `6e1b9710e9094c5ab91987a1465e6f2e3e3067af4856e93b0053280bfb380760`; ZIP `6c2bc3501849515ab49db7c5200be7a265f789b3defd1f81bab8a5686fc61037`. 202 verificações de recuperação de código; provas de schema/dados separadas. [Matriz e limitações actuais](integracao-total-sgf-20261130.md). A decisão sobre recibos de zero está cumprida; as referências pendentes seguintes são históricas. Instalações operacionais e SGC preservados, sem publicação.
|
||||
|
||||
**Estado anterior:** candidata privada **MERCHANDISE-V2-815d88bc0f2f7105**, não instalada, com valorização por recepção original, reconciliação independente e recuperação de dados utilizados. 198 verificações de aplicação/repetição/recuperação de código; schema/dados têm provas separadas. Manifesto `815d88bc0f2f7105b0e4783c0b98fff21c0f4fde36f10b717b93da7f10a3c349`; ZIP `d918a6e9908edad20eec86f5f614b1d6e3339d94f91e93a6367f091b7bf84913`. [Matriz, provas e limites actuais](integracao-total-sgf-20261130.md). A tabela seguinte regista o estado anterior deste seguimento; não substitui a matriz actual. Custo financeiro arredondado a zero continua bloqueado, com decisão específica pendente. SGF real em 0.1.1; nenhuma activação/publicação.
|
||||
|
||||
Seguimento de valorização: abertura autorizada de 4 UN/75 MZN ensaiada e revertida; custos explícitos de entradas e reconciliação independente de camadas implementados no mesmo diário, com ecrã, história e recibo. Prova FIFO/reconciliação: 160 verificações; recuperação transaccional de schema/dados: 15. [Provas e limites actuais](integracao-total-sgf-20261130.md). Devoluções de preços mistos ainda não têm percurso financeiro completo. A candidata indicada abaixo permanece anterior a este seguimento.
|
||||
|
||||
| Capacidade deste seguimento | Estado de desenvolvimento | Limite |
|
||||
| --- | --- | --- |
|
||||
| Abertura sem aquisição identificável | Ensaio autorizado concluído e revertido | 4 UN/75 MZN, artigo temporário removido |
|
||||
| Diferença positiva com custo explícito | Implementada e ensaiada | Outra identidade aprova; quarentena original mantida |
|
||||
| Reconciliação de camadas | Implementada e ensaiada | Conserva quantidade/valor; recusa cortes após transferências valorizadas |
|
||||
| Devolução ao custo da recepção original | Parcial | Cálculo PHP/SQL conferido; ligação financeira completa de preços mistos pendente |
|
||||
| Recuperação de schema e dados | Ensaiada em isolamento | Transaccional na mesma base; ACL/proprietários e perda de servidor excluídos |
|
||||
| Entrega destas alterações | Pendente | Sem nova candidata instalada, activação ou publicação |
|
||||
|
||||
Actualização: sugestões de revenda → conferência independente → requisição → submissão/reserva → aprovação integradas em desenvolvimento, com 43 verificações em rollback e 16 testes de interface simulada. Candidata de código actual **MERCHANDISE-V2-9c182cdaabd8f13f**, 155 ficheiros/86 sobreposições, 176 verificações de recuperação de ficheiros; manifesto `9c182cdaabd8f13f17ad94fe891ff41a81ca7e1242135aa53f4af6b9cc1261c0`, ZIP SHA-256 `f428b39507869271cbe220437313ea9ab83f116426d85e282556bcc3b1fd7f47`. Não instalada; 0.1.1 preservada. [Matriz actual e limites](integracao-total-sgf-20261130.md). Os parágrafos seguintes registam entregas anteriores; não são autorização de instalação nem prova de recuperação de dados/schema.
|
||||
|
||||
Continuação mais recente: o proprietário autorizou a extensão v2 do instalador existente. Preparada **MERCHANDISE-V2-46133eee4f4f5ddb**, 147 ficheiros/78 sobreposições, com compilação privada e 160 verificações de aplicação/recuperação em cópia de código. O próprio instalador e o arranque/cálculo incluídos no pacote foram conferidos. A base declarada é a revisão Git `fe02d1d5d03c5b02a7aa6602dcfd55c88fb69d96` e o manifesto de compilação de desenvolvimento explicitamente identificado; **não certifica a base da instalação operacional**. Recibos de compatibilidade de schema/dados reais continuam obrigatórios e não foram fabricados: o ensaio de ficheiros usou recibo sintético apenas na cópia privada. SGF preservado em 0.1.1, sem instalação, activação ou publicação. Políticas de revenda: 24 verificações PostgreSQL e três de interface aprovadas. [Estado detalhado](integracao-total-sgf-20261130.md). A integração funcional integral continua por concluir.
|
||||
|
||||
O proprietário autorizou a integração total, preservando SGC autónomo, sem novas demonstrações ou publicação, com valorização parametrizável por empresa. [Estado, pacote, matriz e limitações](integracao-total-sgf-20261130.md). Em desenvolvimento: facturação de mercadorias, recebível/recebimento/afectação/reversão, venda e custo no mesmo diário, entrega pelo stock original e política FIFO/CMP. Passaram **128 verificações por método** na regressão existente, com dados/schema/acessos temporários repostos. Pacote privado de revisão **510063ae33b53649**, não instalável nem activado. Custos com transferências/devoluções/ajustes e conferência transversal de compras para revenda continuam pendentes; não declarar integração total concluída. Três novos direitos de leitura na 8085 permanecem por autorizar/conceder. A candidata antiga 8d1af50791bd4878 não contém este incremento. As secções seguintes são históricas.
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
namespace Tempo\Purchasing\Delivery;
|
||||
|
||||
require_once __DIR__.'/NativeAccessCatalogue.php';
|
||||
|
||||
/** Builds a review overlay; never writes to the source host. */
|
||||
final class AccessOverlay
|
||||
{
|
||||
@@ -24,6 +26,11 @@ final class AccessOverlay
|
||||
'purchasing_budget.reinforcement.propose', 'purchasing_budget.reinforcement.review',
|
||||
];
|
||||
|
||||
public static function labels(): array
|
||||
{
|
||||
return self::LABELS + NativeAccessCatalogue::UNIT;
|
||||
}
|
||||
|
||||
public static function prepare(string $host): array
|
||||
{
|
||||
$paths = ['app/Modules/Identity/Services/Permissions.php', 'app/Modules/Identity/Services/IdentityWorkflow.php'];
|
||||
@@ -32,8 +39,10 @@ final class AccessOverlay
|
||||
$source = file_get_contents($host.'/'.$path);
|
||||
$before = hash('sha256', $source);
|
||||
if (str_ends_with($path, '/Permissions.php')) {
|
||||
$source = self::replace($source, "public const UNIT = ['unit.view', 'unit.edit'];", 'public const UNIT = '.var_export(['unit.view', 'unit.edit', ...self::RIGHTS], true).';');
|
||||
$source = self::replace($source, "public const UNIT = ['unit.view', 'unit.edit'];", 'public const UNIT = '.var_export(array_values(array_unique(['unit.view', 'unit.edit', ...self::RIGHTS, ...array_keys(NativeAccessCatalogue::UNIT)])), true).';');
|
||||
$source = self::replace($source, 'public const COMPANY = ', 'public static function companyCatalogue(): array { return [...self::COMPANY, ...'.var_export(NativeAccessCatalogue::COMPANY, true).']; }'."\n\n public const COMPANY = ");
|
||||
} else {
|
||||
$source = str_replace('Permissions::COMPANY', 'Permissions::companyCatalogue()', $source);
|
||||
// Expanding a catalogue must never expand creation-time grants.
|
||||
$source = self::replace($source, 'foreach (Permissions::UNIT as $permission)', "foreach (['unit.view', 'unit.edit'] as \$permission)");
|
||||
$source = self::replace($source,
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace Tempo\Purchasing\Delivery;
|
||||
|
||||
/** Names already consumed by the adapters. Listing a right never grants it. */
|
||||
final class NativeAccessCatalogue
|
||||
{
|
||||
public const COMPANY = ['purchasing_conflicts.view', 'purchasing_conflicts.authorise'];
|
||||
public const UNIT = [
|
||||
'purchasing_conflicts.view' => 'Consultar impedimentos de Compras',
|
||||
'purchasing_conflicts.authorise' => 'Autorizar levantamento de impedimentos',
|
||||
'purchasing_order_cancellations.view' => 'Consultar cancelamentos de encomendas',
|
||||
'purchasing_order_cancellations.prepare' => 'Propor cancelamento de encomenda',
|
||||
'purchasing_order_cancellations.approve' => 'Decidir cancelamento de encomenda',
|
||||
'purchasing_order_cancellations.revise' => 'Rever requisição após cancelamento',
|
||||
'purchasing_requests.view' => 'Consultar requisições de Compras',
|
||||
'purchasing_requests.prepare' => 'Preparar requisições de Compras',
|
||||
'purchasing_requests.submit' => 'Submeter requisições de Compras',
|
||||
'purchasing_requests.approve' => 'Decidir requisições de Compras',
|
||||
'purchasing_sourcing.view' => 'Consultar consultas e adjudicações',
|
||||
'purchasing_sourcing.prepare' => 'Preparar consultas e cotações',
|
||||
'purchasing_sourcing.evaluate' => 'Avaliar cotações',
|
||||
'purchasing_sourcing.select' => 'Propor adjudicação',
|
||||
'purchasing_sourcing.approve' => 'Confirmar adjudicação',
|
||||
'purchasing_orders.view' => 'Consultar encomendas',
|
||||
'purchasing_orders.issue' => 'Emitir encomendas',
|
||||
'purchasing_receipts.view' => 'Consultar recepções',
|
||||
'purchasing_receipts.confirm' => 'Confirmar recepções',
|
||||
'purchasing_suppliers.view' => 'Consultar fornecedores de Compras',
|
||||
'purchasing_suppliers.prepare' => 'Preparar fornecedores de Compras',
|
||||
'purchasing_suppliers.review' => 'Rever fornecedores de Compras',
|
||||
'purchasing_invoices.view' => 'Consultar documentos de fornecedor',
|
||||
'purchasing_invoices.prepare' => 'Preparar documentos de fornecedor',
|
||||
'purchasing_invoices.validate' => 'Validar documentos de fornecedor',
|
||||
'purchasing_obligations.view' => 'Consultar obrigações de Compras',
|
||||
'stock.view' => 'Consultar stock',
|
||||
'stock.operations.prepare' => 'Preparar operações de stock',
|
||||
'stock.operations.confirm' => 'Confirmar operações de stock',
|
||||
'stock.transfers.receive' => 'Receber transferências de stock',
|
||||
'stock.lots.review' => 'Rever lotes de stock',
|
||||
'stock.items.prepare' => 'Preparar artigos de stock',
|
||||
'stock.items.review' => 'Rever artigos de stock',
|
||||
'stock.planning.view' => 'Consultar políticas e sugestões de reposição',
|
||||
'stock.planning.prepare' => 'Preparar políticas de reposição',
|
||||
'stock.planning.review' => 'Rever políticas de reposição',
|
||||
'stock.disposition.view' => 'Consultar devoluções a fornecedor',
|
||||
'stock.disposition.prepare' => 'Preparar devoluções a fornecedor',
|
||||
'stock.disposition.review' => 'Rever devoluções a fornecedor',
|
||||
];
|
||||
}
|
||||
@@ -7,4 +7,14 @@ foreach (['RequisitionPort', 'RequisitionFailure', 'InternalRequisitions'] as $c
|
||||
foreach (['Schema', 'Port', 'Controller'] as $class) {
|
||||
require_once __DIR__.'/'.$class.'.php';
|
||||
}
|
||||
config(['purchasing-internal.candidate_enabled' => true]);
|
||||
(static function (): void {
|
||||
$file = dirname(__DIR__, 3).'/manifest.json';
|
||||
$format = is_file($file) ? (json_decode(file_get_contents($file), true, 32, JSON_THROW_ON_ERROR)['format'] ?? null) : 'tempo.operational-review.v1';
|
||||
if (! in_array($format, ['tempo.operational-review.v1', 'tempo.operational-review.v2'], true)) {
|
||||
throw new RuntimeException('Composição de requisições desconhecida.');
|
||||
}
|
||||
// Preserve the historical v1 bootstrap. A v2 code delivery never enables a capability.
|
||||
if ($format === 'tempo.operational-review.v1') {
|
||||
config(['purchasing-internal.candidate_enabled' => true]);
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -5,17 +5,24 @@ namespace Tempo\Purchasing\Delivery;
|
||||
/** Native administration consumes the server catalogue; no second authority list. */
|
||||
final class AdminUiOverlay
|
||||
{
|
||||
public static function prepare(string $host, array $files): array
|
||||
public static function catalogue(array $files): array
|
||||
{
|
||||
$workflow = 'app/Modules/Identity/Services/IdentityWorkflow.php';
|
||||
$old = "'catalogue' => ['company' => Permissions::COMPANY, 'unit' => Permissions::UNIT]];";
|
||||
$old = "'catalogue' => ['company' => Permissions::companyCatalogue(), 'unit' => Permissions::UNIT]];";
|
||||
$contents = $files[$workflow]['contents'];
|
||||
if (substr_count($contents, $old) !== 1) {
|
||||
throw new \RuntimeException('Catálogo administrativo do host divergiu.');
|
||||
}
|
||||
$contents = str_replace($old, "'catalogue' => ['company' => Permissions::COMPANY, 'unit' => Permissions::UNIT], 'catalogue_labels' => \\Tempo\\Purchasing\\Delivery\\AccessOverlay::LABELS];", $contents);
|
||||
$contents = str_replace($old, "'catalogue' => ['company' => Permissions::companyCatalogue(), 'unit' => Permissions::UNIT], 'catalogue_labels' => \\Tempo\\Purchasing\\Delivery\\AccessOverlay::labels()];", $contents);
|
||||
$files[$workflow]['contents'] = $contents;
|
||||
$files[$workflow]['after_sha256'] = hash('sha256', $contents);
|
||||
|
||||
return $files;
|
||||
}
|
||||
|
||||
public static function prepare(string $host, array $files): array
|
||||
{
|
||||
$files = self::catalogue($files);
|
||||
$node = getenv('SGF_NODE_BINARY') ?: 'node';
|
||||
$process = proc_open([$node, dirname(__DIR__, 3).'/scripts/sgf-admin-ui-build.mjs', $host], [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
|
||||
if (! is_resource($process)) {
|
||||
|
||||
@@ -72,6 +72,85 @@ final class CodeDeployment
|
||||
}
|
||||
}
|
||||
|
||||
private function fileHash(string $relative): ?string
|
||||
{
|
||||
$path = $this->path($relative);
|
||||
if (! file_exists($path)) {
|
||||
return null;
|
||||
}
|
||||
if (! is_file($path)) {
|
||||
throw new \RuntimeException('O destino não é um ficheiro regular.');
|
||||
}
|
||||
|
||||
return hash_file('sha256', $path);
|
||||
}
|
||||
|
||||
private static function v2Path(string $file, bool $overlay): bool
|
||||
{
|
||||
if (str_contains($file, '..') || preg_match('~(^|/)(\.|vendor/|node_modules/|storage/)~i', $file)) {
|
||||
return false;
|
||||
}
|
||||
$host = '~^(app/[A-Za-z0-9_/-]+\.php|config/[A-Za-z0-9_-]+\.php|routes/web\.php|database/(migrations/[A-Za-z0-9_]+\.php|sql/[A-Za-z0-9_-]+\.sql)|resources/views/[A-Za-z0-9_/-]+\.blade\.php|resources/js/[A-Za-z0-9_./-]+\.(jsx?|tsx?)|public/([A-Za-z0-9_-]+\.mjs|build/manifest\.json)|packages/[a-z0-9-]+/(bootstrap\.php|module\.json|README\.md|(src|ui)/[A-Za-z0-9_/-]+\.php))$~D';
|
||||
if (preg_match($host, $file)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return ! $overlay && (bool) preg_match('~^(bootstrap\.php|(integrations|scripts|packages)/[A-Za-z0-9_/-]+\.(php|json|jsx?|mjs|css|md))$~D', $file);
|
||||
}
|
||||
|
||||
private function v2Transition(array $manifest, ?array $old, ?array $previous, string $hash): ?string
|
||||
{
|
||||
$transition = $manifest['composition_transition'];
|
||||
if ($transition['from_manifest_sha256'] !== ($previous['manifest_sha256'] ?? null)) {
|
||||
throw new \RuntimeException('A transição não corresponde à entrega anterior.');
|
||||
}
|
||||
$oldFiles = $old['host_overlays'] ?? [];
|
||||
if (array_diff_key($oldFiles, $manifest['host_overlays']) || array_diff_key($old['support_files'] ?? [], $manifest['support_files'])) {
|
||||
throw new \RuntimeException('A transição não pode retirar ficheiros da composição anterior.');
|
||||
}
|
||||
$added = [];
|
||||
foreach (array_diff_key($manifest['host_overlays'], $oldFiles) as $file => $entry) {
|
||||
$added[$file] = $entry['before_sha256'];
|
||||
}
|
||||
$declared = $transition['added_files'];
|
||||
ksort($added);
|
||||
ksort($declared);
|
||||
if ($added !== $declared) {
|
||||
throw new \RuntimeException('Ampliação da composição não declarada exactamente.');
|
||||
}
|
||||
$schema = [];
|
||||
foreach ($manifest['support_files'] as $file => $after) {
|
||||
if ((str_starts_with($file, 'database/') || preg_match('~Schema\.php$~D', $file)
|
||||
|| in_array($file, ['integrations/sgf/access/AccessOverlay.php', 'integrations/sgf/operational/SqlPrivileges.php', 'integrations/sgf/operational/Installation.php', 'integrations/sgf/operational/budget-contract.json'], true))
|
||||
&& ($old['support_files'][$file] ?? null) !== $after) {
|
||||
$schema[$file] = ['before' => $old['support_files'][$file] ?? null, 'after' => $after];
|
||||
}
|
||||
}
|
||||
$declared = $transition['schema_files'];
|
||||
ksort($schema);
|
||||
ksort($declared);
|
||||
if ($schema !== $declared) {
|
||||
throw new \RuntimeException('Alterações de schema não declaradas exactamente.');
|
||||
}
|
||||
if (! $schema) {
|
||||
return null;
|
||||
}
|
||||
$receiptPath = $this->path('storage/app/private/module-deployments/schema-transition-'.$hash.'.json');
|
||||
$receipt = is_file($receiptPath) ? json_decode(file_get_contents($receiptPath), true, 32, JSON_THROW_ON_ERROR) : [];
|
||||
$changes = $receipt['changes'] ?? [];
|
||||
if (! is_array($changes)) {
|
||||
throw new \RuntimeException('Recibo de schema inválido.');
|
||||
}
|
||||
ksort($changes);
|
||||
if (($receipt['from_manifest_sha256'] ?? null) !== ($previous['manifest_sha256'] ?? null)
|
||||
|| ($receipt['to_manifest_sha256'] ?? null) !== $hash || ($receipt['host'] ?? null) !== $this->host
|
||||
|| ($receipt['schema_verified'] ?? false) !== true || $changes !== $schema) {
|
||||
throw new \RuntimeException('Transição de schema exige recibo exacto e verificado do destino.');
|
||||
}
|
||||
|
||||
return hash_file('sha256', $receiptPath);
|
||||
}
|
||||
|
||||
private function manifest(string $bundle, string $expected): array
|
||||
{
|
||||
if (trim($bundle) === '') {
|
||||
@@ -83,9 +162,30 @@ final class CodeDeployment
|
||||
throw new \RuntimeException('Manifesto divergente.');
|
||||
}
|
||||
$manifest = json_decode($text, true, 32, JSON_THROW_ON_ERROR);
|
||||
if (($manifest['format'] ?? '') !== 'tempo.operational-review.v1') {
|
||||
$v2 = ($manifest['format'] ?? '') === 'tempo.operational-review.v2';
|
||||
if (! $v2 && ($manifest['format'] ?? '') !== 'tempo.operational-review.v1') {
|
||||
throw new \RuntimeException('Formato de entrega desconhecido.');
|
||||
}
|
||||
if ($v2) {
|
||||
$keys = array_keys($manifest);
|
||||
sort($keys);
|
||||
$transition = $manifest['composition_transition'] ?? null;
|
||||
if ($keys !== ['composition_transition', 'format', 'host_overlays', 'support_files']
|
||||
|| ! is_array($transition) || ! is_array($manifest['support_files']) || ! is_array($manifest['host_overlays'])
|
||||
|| ! $manifest['support_files'] || ! $manifest['host_overlays'] || count($manifest['support_files']) > 10000) {
|
||||
throw new \RuntimeException('Contrato v2 inválido.');
|
||||
}
|
||||
$keys = array_keys($transition);
|
||||
sort($keys);
|
||||
if ($keys !== ['added_files', 'from_manifest_sha256', 'schema_files'] || ! is_array($transition['added_files']) || ! is_array($transition['schema_files'])
|
||||
|| ($transition['from_manifest_sha256'] !== null && (! is_string($transition['from_manifest_sha256']) || ! preg_match('/^[a-f0-9]{64}$/D', $transition['from_manifest_sha256'])))) {
|
||||
throw new \RuntimeException('Plano de composição v2 inválido.');
|
||||
}
|
||||
$names = array_map('strtolower', array_keys($manifest['support_files']));
|
||||
if (count($names) !== count(array_unique($names))) {
|
||||
throw new \RuntimeException('Caminhos equivalentes recusados.');
|
||||
}
|
||||
}
|
||||
$expectedFiles = array_fill_keys([...array_keys($manifest['support_files']), 'manifest.json'], true);
|
||||
foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($bundle, \FilesystemIterator::SKIP_DOTS)) as $entry) {
|
||||
$relative = str_replace('\\', '/', substr($entry->getPathname(), strlen($bundle) + 1));
|
||||
@@ -95,13 +195,19 @@ final class CodeDeployment
|
||||
}
|
||||
foreach ($manifest['support_files'] as $file => $hash) {
|
||||
$resolved = str_replace('\\', '/', realpath($bundle.'/'.$file) ?: '');
|
||||
if (str_contains($file, '..') || ! preg_match('~^(bootstrap\.php|(app|packages|integrations|scripts)/[A-Za-z0-9_./-]+|resources/js/(app|PurchasingHome)\.jsx|public/build/manifest\.json)$~D', $file)
|
||||
$allowed = $v2 ? self::v2Path($file, false) : (bool) preg_match('~^(bootstrap\.php|(app|packages|integrations|scripts)/[A-Za-z0-9_./-]+|resources/js/(app|PurchasingHome)\.jsx|public/build/manifest\.json)$~D', $file);
|
||||
if (str_contains($file, '..') || ! $allowed || ! is_string($hash) || ! preg_match('/^[a-f0-9]{64}$/D', $hash)
|
||||
|| ! str_starts_with(strtolower($resolved), strtolower(str_replace('\\', '/', $bundle)).'/') || is_link($bundle.'/'.$file) || ! is_file($bundle.'/'.$file) || ! hash_equals($hash, hash_file('sha256', $bundle.'/'.$file))) {
|
||||
throw new \RuntimeException('Integridade do bundle divergente.');
|
||||
}
|
||||
}
|
||||
foreach ($manifest['host_overlays'] as $file => $hashes) {
|
||||
if ((! str_starts_with($file, 'app/') && ! in_array($file, ['resources/js/app.jsx', 'resources/js/PurchasingHome.jsx', 'public/build/manifest.json'], true)) || ($manifest['support_files'][$file] ?? null) !== $hashes['after_sha256']) {
|
||||
if ($v2 && (! is_array($hashes) || count($hashes) !== 2 || ! array_key_exists('before_sha256', $hashes) || ! isset($hashes['after_sha256'])
|
||||
|| ($hashes['before_sha256'] !== null && (! is_string($hashes['before_sha256']) || ! preg_match('/^[a-f0-9]{64}$/D', $hashes['before_sha256']))))) {
|
||||
throw new \RuntimeException('Baseline v2 inválida.');
|
||||
}
|
||||
$allowed = $v2 ? self::v2Path($file, true) : (str_starts_with($file, 'app/') || in_array($file, ['resources/js/app.jsx', 'resources/js/PurchasingHome.jsx', 'public/build/manifest.json'], true));
|
||||
if (! $allowed || ($manifest['support_files'][$file] ?? null) !== $hashes['after_sha256']) {
|
||||
throw new \RuntimeException('Sobreposição inválida.');
|
||||
}
|
||||
$this->path($file);
|
||||
@@ -114,6 +220,7 @@ final class CodeDeployment
|
||||
{
|
||||
$this->cachePaths();
|
||||
[, $manifest] = $this->manifest($bundle, $manifestHash);
|
||||
$v2 = $manifest['format'] === 'tempo.operational-review.v2';
|
||||
$pointer = $this->path('packages/purchasing/current.json');
|
||||
$pointerHash = hash_file('sha256', $pointer);
|
||||
$previous = $this->current();
|
||||
@@ -128,14 +235,17 @@ final class CodeDeployment
|
||||
}
|
||||
$this->verifyApplied($journal, $previous['deployment_id']);
|
||||
[, $oldManifest] = $this->manifest($this->path('packages/internal-requisitions'), $previous['manifest_sha256']);
|
||||
if (array_keys($oldManifest['host_overlays']) !== array_keys($manifest['host_overlays'])) {
|
||||
if (! $v2 && $oldManifest['format'] === 'tempo.operational-review.v2') {
|
||||
throw new \RuntimeException('Uma composição v2 exige transição v2 explícita.');
|
||||
}
|
||||
if (! $v2 && array_keys($oldManifest['host_overlays']) !== array_keys($manifest['host_overlays'])) {
|
||||
throw new \RuntimeException('Mudança de composição do host exige plano próprio.');
|
||||
}
|
||||
foreach (['integrations/sgf/operational/BudgetSchema.php', 'integrations/sgf/operational/BudgetUiSchema.php', 'integrations/sgf/operational/SqlPrivileges.php', 'integrations/sgf/operational/Installation.php', 'integrations/sgf/operational/budget-contract.json', 'integrations/sgf/internal-requisitions/Schema.php', 'integrations/sgf/access/AccessOverlay.php'] as $file) {
|
||||
foreach ($v2 ? [] : ['integrations/sgf/operational/BudgetSchema.php', 'integrations/sgf/operational/BudgetUiSchema.php', 'integrations/sgf/operational/SqlPrivileges.php', 'integrations/sgf/operational/Installation.php', 'integrations/sgf/operational/budget-contract.json', 'integrations/sgf/internal-requisitions/Schema.php', 'integrations/sgf/access/AccessOverlay.php'] as $file) {
|
||||
if (($oldManifest['support_files'][$file] ?? null) !== ($manifest['support_files'][$file] ?? null)) {
|
||||
$receiptPath=$this->path('storage/app/private/module-deployments/schema-transition-'.$manifestHash.'.json');
|
||||
$receipt=is_file($receiptPath)?json_decode(file_get_contents($receiptPath),true,32,JSON_THROW_ON_ERROR):[];
|
||||
if(($receipt['from_manifest_sha256']??null)!==$previous['manifest_sha256']||($receipt['to_manifest_sha256']??null)!==$manifestHash||($receipt['host']??null)!==$this->host||($receipt['changes'][$file]['before']??null)!==($oldManifest['support_files'][$file]??null)||($receipt['changes'][$file]['after']??null)!==($manifest['support_files'][$file]??null)||($receipt['schema_verified']??false)!==true){
|
||||
$receiptPath = $this->path('storage/app/private/module-deployments/schema-transition-'.$manifestHash.'.json');
|
||||
$receipt = is_file($receiptPath) ? json_decode(file_get_contents($receiptPath), true, 32, JSON_THROW_ON_ERROR) : [];
|
||||
if (($receipt['from_manifest_sha256'] ?? null) !== $previous['manifest_sha256'] || ($receipt['to_manifest_sha256'] ?? null) !== $manifestHash || ($receipt['host'] ?? null) !== $this->host || ($receipt['changes'][$file]['before'] ?? null) !== ($oldManifest['support_files'][$file] ?? null) || ($receipt['changes'][$file]['after'] ?? null) !== ($manifest['support_files'][$file] ?? null) || ($receipt['schema_verified'] ?? false) !== true) {
|
||||
throw new \RuntimeException('Transição de schema exige migração própria e recibo exacto do destino.');
|
||||
}
|
||||
}
|
||||
@@ -143,11 +253,13 @@ final class CodeDeployment
|
||||
} elseif ($previous !== null) {
|
||||
throw new \RuntimeException('Registo activo sem bundle; recuperar a implantação anterior.');
|
||||
}
|
||||
$schemaReceipt = $v2 ? $this->v2Transition($manifest, $oldManifest, $previous, $manifestHash) : null;
|
||||
$before = [];
|
||||
foreach ($manifest['host_overlays'] as $file => $hashes) {
|
||||
$hash = hash_file('sha256', $this->path($file));
|
||||
$expected = $oldManifest === null ? $hashes['before_sha256'] : $oldManifest['host_overlays'][$file]['after_sha256'];
|
||||
if ($oldManifest !== null && $hashes['before_sha256'] !== $oldManifest['host_overlays'][$file]['before_sha256']) {
|
||||
$hash = $this->fileHash($file);
|
||||
$prior = $oldManifest['host_overlays'][$file] ?? null;
|
||||
$expected = $prior === null ? $hashes['before_sha256'] : $prior['after_sha256'];
|
||||
if ($prior !== null && $hashes['before_sha256'] !== ($v2 ? $prior['after_sha256'] : $prior['before_sha256'])) {
|
||||
throw new \RuntimeException('Baseline do host mudou entre versões.');
|
||||
}
|
||||
if ($hash !== $expected) {
|
||||
@@ -155,7 +267,11 @@ final class CodeDeployment
|
||||
}
|
||||
$before[$file] = $hash;
|
||||
}
|
||||
$target = hash('sha256', json_encode([$this->host, $pointerHash, $before, $previous], JSON_THROW_ON_ERROR));
|
||||
$identity = [$this->host, $pointerHash, $before, $previous];
|
||||
if ($v2) {
|
||||
$identity[] = [$manifestHash, $schemaReceipt];
|
||||
}
|
||||
$target = hash('sha256', json_encode($identity, JSON_THROW_ON_ERROR));
|
||||
|
||||
return ['target_sha256' => $target, 'pointer_sha256' => $pointerHash, 'host_files' => $before, 'manifest_sha256' => $manifestHash, 'previous' => $previous, 'deployment_id' => $this->attempt($manifestHash), 'writes' => false];
|
||||
}
|
||||
@@ -357,7 +473,9 @@ final class CodeDeployment
|
||||
'previous' => $plan['previous'],
|
||||
'pointer_sha256' => $plan['pointer_sha256'], 'files' => [], 'cache_files' => [], 'bundle_files' => $manifest['support_files']];
|
||||
foreach ($manifest['host_overlays'] as $file => $hashes) {
|
||||
if ($plan['host_files'][$file] !== null) {
|
||||
self::write($this->path($prefix.'/before/'.$file), file_get_contents($this->path($file)));
|
||||
}
|
||||
$hashes['before_sha256'] = $plan['host_files'][$file];
|
||||
$data['files'][$file] = $hashes;
|
||||
}
|
||||
@@ -371,9 +489,17 @@ final class CodeDeployment
|
||||
$data['cache_files'][$relative] = hash_file('sha256', $cache);
|
||||
}
|
||||
foreach ($manifest['support_files'] as $file => $hash) {
|
||||
self::write($this->path($prefix.'/staged/'.$file), file_get_contents($bundle.'/'.$file));
|
||||
$body = file_get_contents($bundle.'/'.$file);
|
||||
if (! hash_equals($hash, hash('sha256', $body))) {
|
||||
throw new \RuntimeException('Fonte da candidata mudou durante a preparação.');
|
||||
}
|
||||
self::write($this->path($prefix.'/staged/manifest.json'), file_get_contents($bundle.'/manifest.json'));
|
||||
self::write($this->path($prefix.'/staged/'.$file), $body);
|
||||
}
|
||||
$manifestBody = file_get_contents($bundle.'/manifest.json');
|
||||
if (! hash_equals($manifestHash, hash('sha256', $manifestBody))) {
|
||||
throw new \RuntimeException('Manifesto mudou durante a preparação.');
|
||||
}
|
||||
self::write($this->path($prefix.'/staged/manifest.json'), $manifestBody);
|
||||
$this->journal($id, $data);
|
||||
$checkpoint && $checkpoint('prepared');
|
||||
$data['state'] = 'applying';
|
||||
@@ -388,10 +514,14 @@ final class CodeDeployment
|
||||
}
|
||||
$checkpoint && $checkpoint('caches-cleared');
|
||||
foreach ($data['files'] as $file => $hashes) {
|
||||
if (! hash_equals($hashes['before_sha256'], hash_file('sha256', $this->path($file)))) {
|
||||
if ($hashes['before_sha256'] !== $this->fileHash($file)) {
|
||||
throw new \RuntimeException('Ficheiro mudou durante implantação.');
|
||||
}
|
||||
self::write($this->path($file), file_get_contents($bundle.'/'.$file));
|
||||
$body = file_get_contents($this->path($prefix.'/staged/'.$file));
|
||||
if (! hash_equals($hashes['after_sha256'], hash('sha256', $body))) {
|
||||
throw new \RuntimeException('Cópia preparada da candidata divergiu.');
|
||||
}
|
||||
self::write($this->path($file), $body);
|
||||
$checkpoint && $checkpoint('file:'.$file);
|
||||
}
|
||||
// Both resolved paths are checked within the host before this directory move.
|
||||
@@ -428,7 +558,7 @@ final class CodeDeployment
|
||||
}
|
||||
$this->manifest($this->path('packages/internal-requisitions'), $data['manifest_sha256']);
|
||||
foreach ($data['files'] as $file => $hashes) {
|
||||
if (! hash_equals($hashes['after_sha256'], hash_file('sha256', $this->path($file)))) {
|
||||
if ($hashes['after_sha256'] !== $this->fileHash($file)) {
|
||||
throw new \RuntimeException('Código aplicado alterado.');
|
||||
}
|
||||
}
|
||||
@@ -471,10 +601,10 @@ final class CodeDeployment
|
||||
throw new \RuntimeException('Cache mudou após compilação registada.');
|
||||
}
|
||||
foreach ($data['files'] as $file => $hashes) {
|
||||
if (! in_array(hash_file('sha256', $this->path($file)), [$hashes['before_sha256'], $hashes['after_sha256']], true)) {
|
||||
if (! in_array($this->fileHash($file), [$hashes['before_sha256'], $hashes['after_sha256']], true)) {
|
||||
throw new \RuntimeException('Código local alterado; recuperação recusada.');
|
||||
}
|
||||
if (! hash_equals($hashes['before_sha256'], hash_file('sha256', $this->path($prefix.'/before/'.$file)))) {
|
||||
if ($hashes['before_sha256'] !== $this->fileHash($prefix.'/before/'.$file)) {
|
||||
throw new \RuntimeException('Backup de código divergente.');
|
||||
}
|
||||
}
|
||||
@@ -518,8 +648,17 @@ final class CodeDeployment
|
||||
$data['state'] = 'rolling-back';
|
||||
$this->journal($id, $data);
|
||||
foreach ($data['files'] as $file => $hashes) {
|
||||
if (! in_array($this->fileHash($file), [$hashes['before_sha256'], $hashes['after_sha256']], true)) {
|
||||
throw new \RuntimeException('Código mudou durante a recuperação.');
|
||||
}
|
||||
if ($hashes['before_sha256'] === null) {
|
||||
if ($this->fileHash($file) !== null && ! unlink($this->path($file))) {
|
||||
throw new \RuntimeException('Falha ao repor ausência anterior.');
|
||||
}
|
||||
} else {
|
||||
self::write($this->path($file), file_get_contents($this->path($prefix.'/before/'.$file)));
|
||||
}
|
||||
}
|
||||
if ($rebuilt) {
|
||||
foreach ($data['built_cache_files'] as $file => $hash) {
|
||||
self::write($this->path($prefix.'/rollback-cache/'.$file), file_get_contents($this->path($file)));
|
||||
|
||||
@@ -1,6 +1,34 @@
|
||||
<?php
|
||||
|
||||
use Tempo\Purchasing\Inventory\StockCosting;
|
||||
|
||||
// Copied as <local bundle>/bootstrap.php, without a source-project dependency.
|
||||
if (config('merchandise_invoices.costs_enabled') === true) {
|
||||
(static function (): void {
|
||||
if (! is_file(__DIR__.'/manifest.json') || is_link(__DIR__.'/manifest.json') || ! is_readable(__DIR__.'/manifest.json')) {
|
||||
throw new RuntimeException('Manifesto local da composição ausente.');
|
||||
}
|
||||
$relative = 'packages/purchasing/src/StockCosting.php';
|
||||
$manifest = json_decode(file_get_contents(__DIR__.'/manifest.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
$pin = $manifest['support_files'][$relative] ?? null;
|
||||
$file = realpath(__DIR__.'/'.$relative);
|
||||
$base = realpath(__DIR__);
|
||||
if (! in_array($manifest['format'] ?? null, ['tempo.operational-review.v1', 'tempo.operational-review.v2'], true)
|
||||
|| ! is_string($pin) || ! preg_match('/^[a-f0-9]{64}$/D', $pin) || ! $file || ! $base
|
||||
|| ! str_starts_with(strtolower($file), strtolower($base.DIRECTORY_SEPARATOR))
|
||||
|| is_link(__DIR__.'/'.$relative) || ! hash_equals($pin, hash_file('sha256', $file))) {
|
||||
throw new RuntimeException('Cálculo comum da composição ausente ou divergente.');
|
||||
}
|
||||
$class = StockCosting::class;
|
||||
if (class_exists($class, false)) {
|
||||
if (! hash_equals($pin, hash_file('sha256', (new ReflectionClass($class))->getFileName()))) {
|
||||
throw new RuntimeException('Outra versão do cálculo comum já foi carregada.');
|
||||
}
|
||||
} else {
|
||||
require_once $file;
|
||||
}
|
||||
})();
|
||||
}
|
||||
require_once __DIR__.'/integrations/sgf/operational/bootstrap.php';
|
||||
require_once __DIR__.'/integrations/sgf/operational/RuntimeContext.php';
|
||||
require_once __DIR__.'/integrations/sgf/operational/Composition.php';
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
require_once __DIR__.'/src/ReplenishmentProjection.php';
|
||||
require_once __DIR__.'/src/StockCosting.php';
|
||||
require_once __DIR__.'/src/ExecutionContext.php';
|
||||
require_once __DIR__.'/src/QuotationPricing.php';
|
||||
require_once __DIR__.'/src/ProposalScoring.php';
|
||||
require_once __DIR__.'/src/RequisitionPort.php';
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace Tempo\Purchasing\Composition;
|
||||
|
||||
use Closure;
|
||||
use LogicException;
|
||||
|
||||
/** Transaction-scoped evidence supplied by the host runtime, never a permission grant. */
|
||||
final class ExecutionContext
|
||||
{
|
||||
public const CONTRACT = 'COMPRAS-SGF-EXECUTION-v1';
|
||||
|
||||
private ?array $frame = null;
|
||||
|
||||
public function within(array $declaration, object $connection, Closure $verify, Closure $work): mixed
|
||||
{
|
||||
if ($this->frame !== null) {
|
||||
throw new LogicException('COMPOSITION_NESTED_EXECUTION');
|
||||
}
|
||||
self::validate($declaration);
|
||||
$verify();
|
||||
$this->frame = [$declaration, $connection, $verify];
|
||||
try {
|
||||
return $work();
|
||||
} finally {
|
||||
$this->frame = null;
|
||||
}
|
||||
}
|
||||
|
||||
public function allows(string $feature, object $connection): bool
|
||||
{
|
||||
if ($this->frame === null || $this->frame[1] !== $connection) {
|
||||
return false;
|
||||
}
|
||||
($this->frame[2])(); // Re-read identity, context, permissions, pins and schema.
|
||||
|
||||
return array_key_exists($feature, $this->frame[0]['features']);
|
||||
}
|
||||
|
||||
public function component(string $feature, object $connection): array
|
||||
{
|
||||
if (! $this->allows($feature, $connection)) {
|
||||
throw new LogicException('COMPOSITION_CAPABILITY_ABSENT');
|
||||
}
|
||||
|
||||
return $this->frame[0]['features'][$feature];
|
||||
}
|
||||
|
||||
public function permits(string $operation, object $connection): bool
|
||||
{
|
||||
$feature = str_starts_with($operation, 'purchasing_conflicts.') ? 'conflict-release'
|
||||
: (str_starts_with($operation, 'purchasing_order_cancellations.') ? 'order-cancellation-cycles' : null);
|
||||
|
||||
return $feature !== null && $this->allows($feature, $connection) && $this->frame[0]['operation'] === $operation;
|
||||
}
|
||||
|
||||
private static function validate(array $declaration): void
|
||||
{
|
||||
$keys = array_keys($declaration);
|
||||
sort($keys);
|
||||
if ($keys !== ['actor', 'composition', 'contract', 'features', 'generation', 'operation', 'schema_sha256', 'scope', 'workflow_sha256']
|
||||
|| $declaration['contract'] !== self::CONTRACT
|
||||
|| ! is_string($declaration['composition']) || ! preg_match('/^[a-f0-9]{12}$/D', $declaration['composition'])) {
|
||||
throw new LogicException('COMPOSITION_CONTRACT');
|
||||
}
|
||||
if (! is_string($declaration['operation']) || ! preg_match('/^[a-z][a-z0-9_]*(?:\.[a-z0-9_]+)+$/D', $declaration['operation'])) {
|
||||
throw new LogicException('COMPOSITION_OPERATION');
|
||||
}
|
||||
foreach (['generation', 'schema_sha256', 'workflow_sha256'] as $field) {
|
||||
if (! is_string($declaration[$field]) || ! preg_match('/^[a-f0-9]{64}$/D', $declaration[$field])) {
|
||||
throw new LogicException('COMPOSITION_HASH');
|
||||
}
|
||||
}
|
||||
foreach (['scope' => ['tenant_id', 'company_id', 'unit_id'], 'actor' => ['host_id', 'native_id']] as $field => $expected) {
|
||||
if (! is_array($declaration[$field]) || count($declaration[$field]) !== count($expected)
|
||||
|| array_diff($expected, array_keys($declaration[$field]))) {
|
||||
throw new LogicException('COMPOSITION_SCOPE');
|
||||
}
|
||||
foreach ($declaration[$field] as $id) {
|
||||
if (! is_int($id) || $id < 1) {
|
||||
throw new LogicException('COMPOSITION_SCOPE');
|
||||
}
|
||||
}
|
||||
}
|
||||
if (! is_array($declaration['features']) || array_diff(array_keys($declaration['features']), ['conflict-release', 'order-cancellation-cycles'])) {
|
||||
throw new LogicException('COMPOSITION_FEATURE');
|
||||
}
|
||||
foreach ($declaration['features'] as $feature => $component) {
|
||||
if ($feature === 'conflict-release' && $component !== []) {
|
||||
if (! is_array($component) || array_keys($component) !== ['company_view', 'company_authorise']
|
||||
|| ! is_bool($component['company_view']) || ! is_bool($component['company_authorise'])) {
|
||||
throw new LogicException('COMPOSITION_FEATURE');
|
||||
}
|
||||
}
|
||||
if ($feature === 'order-cancellation-cycles'
|
||||
&& (! is_array($component) || array_keys($component) !== ['root', 'manifest_sha256']
|
||||
|| ! is_string($component['root']) || trim($component['root']) === ''
|
||||
|| ! is_string($component['manifest_sha256']) || ! preg_match('/^[a-f0-9]{64}$/D', $component['manifest_sha256']))) {
|
||||
throw new LogicException('COMPOSITION_COMPONENT');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,8 +52,9 @@ final class StockCosting
|
||||
throw new \DomainException('Opening value without stock is inconsistent.');
|
||||
}
|
||||
$layers = [];
|
||||
$origins = [];
|
||||
$head = 0;
|
||||
if ($method === 'fifo') {
|
||||
if ($method === 'fifo' || ($opening['layers'] ?? []) !== []) {
|
||||
$sumQuantity = 0;
|
||||
$sumValue = BigRational::of(0);
|
||||
foreach ($opening['layers'] ?? [] as $layer) {
|
||||
@@ -64,12 +65,22 @@ final class StockCosting
|
||||
}
|
||||
$sumQuantity += $q;
|
||||
$sumValue = $sumValue->plus($v);
|
||||
$layers[] = ['quantity_milli' => $q, 'value' => $v];
|
||||
$reference = $layer['reference'] ?? (count($opening['layers'] ?? []) === 1 ? $opening['reference'] : null);
|
||||
$layers[] = ['quantity_milli' => $q, 'value' => $v, 'reference' => $reference];
|
||||
if (is_string($reference) && trim($reference) !== '') {
|
||||
if (isset($origins[$reference])) {
|
||||
throw new \DomainException('Duplicate opening receipt reference.');
|
||||
}
|
||||
$origins[$reference] = ['available_milli' => $q, 'unit_value' => $v->dividedBy($q)];
|
||||
}
|
||||
}
|
||||
if ($sumQuantity !== $quantity || ! $sumValue->isEqualTo($value)) {
|
||||
throw new \DomainException('FIFO opening requires reconciled historical layers.');
|
||||
}
|
||||
}
|
||||
if ($method === 'weighted_average' && $quantity > 0 && ($opening['layers'] ?? []) === []) {
|
||||
$origins[$opening['reference']] = ['available_milli' => $quantity, 'unit_value' => $value->dividedBy($quantity)];
|
||||
}
|
||||
$last = 0;
|
||||
$results = [];
|
||||
foreach ($movements as $movement) {
|
||||
@@ -86,9 +97,50 @@ final class StockCosting
|
||||
}
|
||||
$quantity += $q;
|
||||
$value = $value->plus($amount);
|
||||
if ($method === 'fifo') {
|
||||
$layers[] = ['quantity_milli' => $q, 'value' => $amount];
|
||||
if (isset($origins[$movement['reference']])) {
|
||||
throw new \DomainException('Duplicate receipt reference.');
|
||||
}
|
||||
$origins[$movement['reference']] = ['available_milli' => $q, 'unit_value' => $amount->dividedBy($q)];
|
||||
if ($method === 'fifo') {
|
||||
$layers[] = ['quantity_milli' => $q, 'value' => $amount, 'reference' => $movement['reference']];
|
||||
}
|
||||
} elseif (($movement['kind'] ?? null) === 'receipt_return') {
|
||||
$reference = $movement['receipt_reference'] ?? null;
|
||||
if (! is_string($reference) || ! isset($origins[$reference]) || $q > $quantity) {
|
||||
throw new \DomainException('An identified original receipt and sufficient stock are required.');
|
||||
}
|
||||
$amount = $origins[$reference]['unit_value']->multipliedBy($q);
|
||||
if ($method === 'fifo') {
|
||||
$index = null;
|
||||
foreach ($layers as $key => $layer) {
|
||||
if ($layer['reference'] === $reference) {
|
||||
$index = $key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($index === null || $layers[$index]['quantity_milli'] < $q) {
|
||||
throw new \DomainException('Original receipt layer already consumed; independently reconciled opening required.');
|
||||
}
|
||||
$layers[$index]['quantity_milli'] -= $q;
|
||||
$layers[$index]['value'] = $layers[$index]['value']->minus($amount);
|
||||
if ($layers[$index]['quantity_milli'] === 0) {
|
||||
unset($layers[$index]);
|
||||
}
|
||||
} elseif ($origins[$reference]['available_milli'] < $q) {
|
||||
throw new \DomainException('Original receipt availability is not proven after prior issues; independent reconciliation required.');
|
||||
}
|
||||
if ($rounding === 'half_up_final_balance') {
|
||||
$amount = $q === $quantity ? $value : $amount->toScale(0, RoundingMode::HalfUp)->toBigRational();
|
||||
}
|
||||
if ($amount->isGreaterThan($value)) {
|
||||
throw new \DomainException('Return exceeds remaining stock value; independent reconciliation required.');
|
||||
}
|
||||
if (array_key_exists('value_minor', $movement) && ! $amount->isEqualTo(self::integer($movement['value_minor']))) {
|
||||
throw new \DomainException('Posted return differs from its original receipt cost; never revalue prior journals.');
|
||||
}
|
||||
$origins[$reference]['available_milli'] -= $q;
|
||||
$quantity -= $q;
|
||||
$value = $value->minus($amount);
|
||||
} elseif (($movement['kind'] ?? null) === 'issue') {
|
||||
if (array_key_exists('value_minor', $movement)) {
|
||||
throw new \InvalidArgumentException('An issue cannot override its calculated cost.');
|
||||
@@ -102,6 +154,9 @@ final class StockCosting
|
||||
} else {
|
||||
$remaining = $q;
|
||||
while ($remaining > 0) {
|
||||
while (! isset($layers[$head])) {
|
||||
$head++;
|
||||
}
|
||||
$take = min($remaining, $layers[$head]['quantity_milli']);
|
||||
$part = $layers[$head]['value']->multipliedBy($take)->dividedBy($layers[$head]['quantity_milli']);
|
||||
$amount = $amount->plus($part);
|
||||
@@ -122,10 +177,20 @@ final class StockCosting
|
||||
}
|
||||
$quantity -= $q;
|
||||
$value = $value->minus($amount);
|
||||
if ($method === 'weighted_average') {
|
||||
// Without qualified lot allocations no receipt may claim units already issued.
|
||||
foreach ($origins as &$origin) {
|
||||
$origin['available_milli'] = max(0, $origin['available_milli'] - $q);
|
||||
}
|
||||
unset($origin);
|
||||
}
|
||||
} else {
|
||||
throw new \InvalidArgumentException('Unknown qualified movement kind.');
|
||||
}
|
||||
$results[] = ['id' => $id, 'reference' => $movement['reference'], 'kind' => $movement['kind'], 'quantity_milli' => $q, 'value' => self::amount($amount)];
|
||||
if ($movement['kind'] === 'receipt_return') {
|
||||
$results[array_key_last($results)]['receipt_reference'] = $movement['receipt_reference'];
|
||||
}
|
||||
}
|
||||
|
||||
return ['method' => $method, 'opening_reference' => $opening['reference'], 'movements' => $results,
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
final class SgfWorkflowExtension
|
||||
{
|
||||
public static function transform(string $php): string
|
||||
{
|
||||
$result = '';
|
||||
foreach (token_get_all($php, TOKEN_PARSE) as $token) {
|
||||
if (! is_array($token)) {
|
||||
$result .= $token;
|
||||
|
||||
continue;
|
||||
}
|
||||
[$type, $text] = $token;
|
||||
if (in_array($type, [T_NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED], true)) {
|
||||
$text = preg_replace('/^(\\\\?)App\\\\/', '$1Tempo\\Purchasing\\Embedded\\', $text);
|
||||
}
|
||||
$result .= $text;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public static function prepare(string $source, string $base, string $baseHash, string $output, array $updates): array
|
||||
{
|
||||
if (! preg_match('/^[a-f0-9]{64}$/D', $baseHash) || is_link($base) || is_link($output)
|
||||
|| ! hash_equals($baseHash, hash_file('sha256', $base.'/manifest.json'))) {
|
||||
throw new LogicException('Workflow predecessor mismatch.');
|
||||
}
|
||||
$manifest = json_decode(file_get_contents($base.'/manifest.json'), true, 64, JSON_THROW_ON_ERROR);
|
||||
$bodies = [];
|
||||
foreach ($manifest['files'] as $path => $hash) {
|
||||
self::path($path);
|
||||
if (is_link($base.'/'.$path) || ! hash_equals($hash, hash_file('sha256', $base.'/'.$path))) {
|
||||
throw new LogicException('Workflow predecessor file mismatch.');
|
||||
}
|
||||
$bodies[$path] = file_get_contents($base.'/'.$path);
|
||||
}
|
||||
foreach ($updates as $path) {
|
||||
self::path($path);
|
||||
if (! str_starts_with($path, 'app/') || is_link($source.'/'.$path) || ! is_file($source.'/'.$path)) {
|
||||
throw new LogicException('Canonical workflow source missing.');
|
||||
}
|
||||
$bytes = file_get_contents($source.'/'.$path);
|
||||
$manifest['originals'][$path] = hash('sha256', $bytes);
|
||||
$bodies[$path] = self::transform($bytes);
|
||||
}
|
||||
ksort($bodies);
|
||||
$manifest['files'] = array_map(fn ($bytes) => hash('sha256', $bytes), $bodies);
|
||||
$manifest['predecessor_sha256'] = $baseHash;
|
||||
$manifest['extension_contract'] = 'COMPRAS-SGF-EXECUTION-v1';
|
||||
$bytes = json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)."\n";
|
||||
$hash = hash('sha256', $bytes);
|
||||
$directory = $output.'/'.substr($hash, 0, 16).'/bundle';
|
||||
foreach ($bodies + ['manifest.json' => $bytes] as $path => $body) {
|
||||
$file = $directory.'/'.$path;
|
||||
if (is_link($file) || (is_file($file) && ! hash_equals(hash('sha256', $body), hash_file('sha256', $file)))) {
|
||||
throw new LogicException('Immutable workflow candidate differs.');
|
||||
}
|
||||
if (! is_dir(dirname($file))) {
|
||||
mkdir(dirname($file), 0700, true);
|
||||
}
|
||||
if (! is_file($file)) {
|
||||
file_put_contents($file, $body);
|
||||
}
|
||||
if (! hash_equals(hash('sha256', $body), hash_file('sha256', $file))) {
|
||||
throw new LogicException('Incomplete workflow candidate.');
|
||||
}
|
||||
}
|
||||
|
||||
return ['directory' => $directory, 'sha256' => $hash, 'predecessor_sha256' => $baseHash, 'updated_sources' => array_intersect_key($manifest['originals'], array_flip($updates))];
|
||||
}
|
||||
|
||||
private static function path(string $path): void
|
||||
{
|
||||
if (! preg_match('~^(app|fortify)/[A-Za-z0-9_/]+\.php$~D', $path)) {
|
||||
throw new LogicException('Unsafe workflow path.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
/** Read-only comparison: an accepted old bundle is not evidence of current workflow equivalence. */
|
||||
final class SgfWorkflowInventory
|
||||
{
|
||||
public static function inspect(string $source, string $bundle, string $manifestHash, array $processes): array
|
||||
{
|
||||
if (! preg_match('/^[a-f0-9]{64}$/D', $manifestHash)) {
|
||||
throw new RuntimeException('Manifest hash required.');
|
||||
}
|
||||
$manifestPath = self::file($bundle, 'manifest.json');
|
||||
if (! hash_equals($manifestHash, hash_file('sha256', $manifestPath))) {
|
||||
throw new RuntimeException('Unrecognised workflow manifest.');
|
||||
}
|
||||
$manifest = json_decode(file_get_contents($manifestPath), true, 64, JSON_THROW_ON_ERROR);
|
||||
if (! is_array($manifest['files'] ?? null) || ! is_array($manifest['originals'] ?? null)) {
|
||||
throw new RuntimeException('Original and distributed hashes required.');
|
||||
}
|
||||
// Check the whole supplied bundle, including dependencies outside the process selection.
|
||||
foreach ($manifest['files'] as $path => $hash) {
|
||||
if (! is_string($hash) || ! preg_match('/^[a-f0-9]{64}$/D', $hash)
|
||||
|| ! hash_equals($hash, hash_file('sha256', self::file($bundle, $path)))) {
|
||||
throw new RuntimeException('Workflow bundle integrity failure.');
|
||||
}
|
||||
}
|
||||
$result = [];
|
||||
foreach ($processes as $process => $paths) {
|
||||
$components = [];
|
||||
foreach ($paths as $path) {
|
||||
self::relative($path);
|
||||
$current = is_file($source.'/'.$path) ? hash_file('sha256', self::file($source, $path)) : null;
|
||||
$original = $manifest['originals'][$path] ?? null;
|
||||
if ($original !== null && (! is_string($original) || ! preg_match('/^[a-f0-9]{64}$/D', $original))) {
|
||||
throw new RuntimeException('Invalid original source hash.');
|
||||
}
|
||||
$status = $current === null ? 'source_missing' : ($original === null || ! isset($manifest['files'][$path])
|
||||
? 'not_transferred' : (hash_equals($original, $current) ? 'source_unchanged' : 'source_changed'));
|
||||
$components[$path] = ['status' => $status, 'source_sha256' => $current, 'accepted_source_sha256' => $original];
|
||||
}
|
||||
$result[$process] = ['source_equivalent' => $components !== [] && count(array_filter($components, fn ($entry) => $entry['status'] !== 'source_unchanged')) === 0, 'components' => $components];
|
||||
}
|
||||
|
||||
return ['format' => 'tempo.sgf-workflow-inventory.v1', 'manifest_sha256' => $manifestHash,
|
||||
'bundle_integrity' => true, 'read_only' => true, 'functional_acceptance' => false, 'processes' => $result];
|
||||
}
|
||||
|
||||
private static function relative(string $path): void
|
||||
{
|
||||
if (! preg_match('#^[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*$#D', $path)
|
||||
|| in_array('..', explode('/', $path), true) || in_array('.', explode('/', $path), true)) {
|
||||
throw new RuntimeException('Invalid workflow path.');
|
||||
}
|
||||
}
|
||||
|
||||
private static function file(string $root, string $path): string
|
||||
{
|
||||
self::relative($path);
|
||||
if (is_link($root)) {
|
||||
throw new RuntimeException('Workflow links are forbidden.');
|
||||
}
|
||||
$base = realpath($root);
|
||||
$file = realpath($root.'/'.$path);
|
||||
$cursor = $root;
|
||||
foreach (explode('/', $path) as $part) {
|
||||
$cursor .= '/'.$part;
|
||||
if (is_link($cursor)) {
|
||||
throw new RuntimeException('Workflow links are forbidden.');
|
||||
}
|
||||
}
|
||||
if (! $base || ! $file || ! is_file($file)
|
||||
|| ! str_starts_with(strtolower($file), strtolower($base.DIRECTORY_SEPARATOR))) {
|
||||
throw new RuntimeException('Workflow file outside the supplied root or missing.');
|
||||
}
|
||||
|
||||
return $file;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
<?php
|
||||
|
||||
// Prepare and rehearse files only. Never boots Laravel, connects to a DB or installs a destination.
|
||||
require dirname(__DIR__).'/integrations/sgf/operational/CodeDeployment.php';
|
||||
|
||||
use Tempo\Purchasing\Delivery\CodeDeployment;
|
||||
|
||||
if ($argc !== 6) {
|
||||
throw new InvalidArgumentException('Pass review directory/hash, compatibility directory/hash and the exact SGF baseline Git commit.');
|
||||
}
|
||||
$root = dirname(__DIR__);
|
||||
$host = realpath($root.'/../sgf-tempo');
|
||||
$review = realpath($argv[1]);
|
||||
$reviewHash = $argv[2];
|
||||
$compat = realpath($argv[3]);
|
||||
$compatHash = $argv[4];
|
||||
$commit = $argv[5];
|
||||
$inside = fn ($path, $base) => $path && $base && str_starts_with(strtolower(str_replace('\\', '/', $path)), strtolower(str_replace('\\', '/', $base)).'/');
|
||||
if (! $host || ! $inside($review, realpath($host.'/storage/framework/testing/merchandise-invoices-20261130/review'))
|
||||
|| ! $inside($compat, realpath($root.'/storage/app/private/candidates')) || ! preg_match('/^[a-f0-9]{40}$/D', $commit)
|
||||
|| ! preg_match('/^[a-f0-9]{64}$/D', $reviewHash) || ! preg_match('/^[a-f0-9]{64}$/D', $compatHash)) {
|
||||
throw new LogicException('Explicit private sources and baseline required.');
|
||||
}
|
||||
$git = function (array $arguments) use ($host): array {
|
||||
$process = proc_open(['git', '-C', $host, ...$arguments], [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
|
||||
if (! is_resource($process)) {
|
||||
throw new RuntimeException('Cannot read Git baseline.');
|
||||
}
|
||||
fclose($pipes[0]);
|
||||
$out = stream_get_contents($pipes[1]);
|
||||
$error = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
|
||||
return [proc_close($process), $out, $error];
|
||||
};
|
||||
[$status, $resolved] = $git(['rev-parse', $commit.'^{commit}']);
|
||||
if ($status !== 0 || trim($resolved) !== $commit) {
|
||||
throw new LogicException('Baseline commit does not exist.');
|
||||
}
|
||||
$blob = function (string $path) use ($git, $commit): ?string {
|
||||
[$status, $text] = $git(['cat-file', 'blob', $commit.':'.$path]);
|
||||
if ($status === 128) {
|
||||
return null;
|
||||
}
|
||||
if ($status !== 0) {
|
||||
throw new RuntimeException('Cannot resolve baseline file: '.$path);
|
||||
}
|
||||
|
||||
return $text;
|
||||
};
|
||||
$read = function (string $directory, string $hash): array {
|
||||
$text = file_get_contents($directory.'/manifest.json');
|
||||
if (! hash_equals($hash, hash('sha256', $text))) {
|
||||
throw new LogicException('Source manifest changed.');
|
||||
}
|
||||
|
||||
return json_decode($text, true, 64, JSON_THROW_ON_ERROR);
|
||||
};
|
||||
$reviewManifest = $read($review, $reviewHash);
|
||||
$compatManifest = $read($compat, $compatHash);
|
||||
if ($reviewManifest['format'] !== 'tempo.integration-review.v1' || $reviewManifest['installable'] !== false || $compatManifest['format'] !== 'tempo.operational-review.v1') {
|
||||
throw new LogicException('Unexpected preparation source.');
|
||||
}
|
||||
(new ReflectionMethod(CodeDeployment::class, 'manifest'))->invoke(new CodeDeployment($host), $compat, $compatHash);
|
||||
$bodies = [];
|
||||
$runtime = [];
|
||||
foreach ($compatManifest['support_files'] as $file => $hash) {
|
||||
$bodies[$file] = file_get_contents($compat.'/'.$file);
|
||||
}
|
||||
if (! isset($bodies['integrations/sgf/operational/CodeDeployment.php'])
|
||||
|| ! hash_equals(hash('sha256', $bodies['integrations/sgf/operational/CodeDeployment.php']), hash_file('sha256', $root.'/integrations/sgf/operational/CodeDeployment.php'))) {
|
||||
throw new LogicException('Refresh compatibility preparation with the tested deployment contract.');
|
||||
}
|
||||
foreach ($reviewManifest['files'] as $file => $hash) {
|
||||
if (str_contains($file, '..') || ! preg_match('~^[A-Za-z0-9_./-]+$~D', $file) || is_link($review.'/'.$file)
|
||||
|| ! $inside(realpath($review.'/'.$file), $review) || ! hash_equals($hash, hash_file('sha256', $review.'/'.$file))) {
|
||||
throw new LogicException('Review source changed.');
|
||||
}
|
||||
$body = file_get_contents($review.'/'.$file);
|
||||
if (str_starts_with($file, 'sgf/')) {
|
||||
$runtime[substr($file, 4)] = $body;
|
||||
} elseif (str_starts_with($file, 'shared/general-ledger/')) {
|
||||
$runtime['packages/general-ledger/'.substr($file, strlen('shared/general-ledger/'))] = $body;
|
||||
} elseif (str_starts_with($file, 'shared/purchasing/src/')) {
|
||||
$destination = 'packages/purchasing/src/'.substr($file, strlen('shared/purchasing/src/'));
|
||||
if (! isset($bodies[$destination]) || ! hash_equals(hash('sha256', $body), hash('sha256', $bodies[$destination]))) {
|
||||
throw new LogicException('Common calculation sources disagree.');
|
||||
}
|
||||
}
|
||||
}
|
||||
// The compiled frontend may contain only the baseline plus explicitly reviewed changes.
|
||||
foreach (['diff', 'ls-files'] as $mode) {
|
||||
$arguments = $mode === 'diff' ? ['diff', '--name-only', $commit, '--', 'resources', 'package.json', 'vite.config.js'] : ['ls-files', '--others', '--exclude-standard', '--', 'resources'];
|
||||
[$status, $paths] = $git($arguments);
|
||||
if ($status !== 0) {
|
||||
throw new RuntimeException('Cannot freeze frontend sources.');
|
||||
}
|
||||
foreach (array_filter(explode("\n", trim($paths))) as $file) {
|
||||
if (! isset($runtime[$file]) || ! hash_equals(hash('sha256', $runtime[$file]), hash_file('sha256', $host.'/'.$file))) {
|
||||
throw new LogicException('Unreviewed frontend change: '.$file);
|
||||
}
|
||||
}
|
||||
}
|
||||
$overlays = [];
|
||||
$beforeBodies = [];
|
||||
$developmentBuild = [];
|
||||
foreach ($runtime as $file => $body) {
|
||||
if (! isset($compatManifest['host_overlays'][$file])) {
|
||||
$bodies[$file] = $body;
|
||||
} elseif ($compatManifest['host_overlays'][$file]['before_sha256'] !== hash('sha256', $body)) {
|
||||
throw new LogicException('Merged overlay used another source: '.$file);
|
||||
}
|
||||
}
|
||||
foreach (array_unique([...array_keys($runtime), ...array_keys($compatManifest['host_overlays'])]) as $file) {
|
||||
$before = $blob($file);
|
||||
if ($file === 'public/build/manifest.json' && $before === null) {
|
||||
$before = file_get_contents($host.'/'.$file);
|
||||
$developmentBuild[$file] = hash('sha256', $before);
|
||||
}
|
||||
if (isset($compatManifest['host_overlays'][$file]) && ! isset($runtime[$file])) {
|
||||
$checkout = file_get_contents($host.'/'.$file);
|
||||
if ($before === null || hash('sha256', $checkout) !== $compatManifest['host_overlays'][$file]['before_sha256']
|
||||
|| str_replace("\r\n", "\n", $before) !== str_replace("\r\n", "\n", $checkout)) {
|
||||
throw new LogicException('Compatibility overlay contains an unreviewed baseline change: '.$file);
|
||||
}
|
||||
}
|
||||
$beforeBodies[$file] = $before;
|
||||
$overlays[$file] = ['before_sha256' => $before === null ? null : hash('sha256', $before), 'after_sha256' => hash('sha256', $bodies[$file])];
|
||||
}
|
||||
$bodies['scripts/merchandise-delivery-metadata.json'] = json_encode(['baseline_git_commit' => $commit, 'baseline_bytes' => 'canonical_git_blobs_and_explicit_development_build_manifest',
|
||||
'development_build_baseline' => $developmentBuild, 'operational_destination_verified' => false, 'source_review_manifest_sha256' => $reviewHash,
|
||||
'source_compatibility_manifest_sha256' => $compatHash, 'installed' => false, 'activated' => false, 'schema_installed' => false,
|
||||
'core_pointer_preserved' => '0.1.1', 'operational_schema_receipt_required' => true], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
|
||||
ksort($bodies);
|
||||
ksort($overlays);
|
||||
$files = array_map(fn ($body) => hash('sha256', $body), $bodies);
|
||||
$added = [];
|
||||
$schema = [];
|
||||
foreach ($overlays as $file => $entry) {
|
||||
$added[$file] = $entry['before_sha256'];
|
||||
}
|
||||
foreach ($files as $file => $hash) {
|
||||
if (str_starts_with($file, 'database/') || preg_match('~Schema\.php$~D', $file)
|
||||
|| in_array($file, ['integrations/sgf/access/AccessOverlay.php', 'integrations/sgf/operational/SqlPrivileges.php', 'integrations/sgf/operational/Installation.php', 'integrations/sgf/operational/budget-contract.json'], true)) {
|
||||
$schema[$file] = ['before' => null, 'after' => $hash];
|
||||
}
|
||||
}
|
||||
$manifest = ['format' => 'tempo.operational-review.v2', 'support_files' => $files, 'host_overlays' => $overlays,
|
||||
'composition_transition' => ['from_manifest_sha256' => null, 'added_files' => $added, 'schema_files' => $schema]];
|
||||
$manifestText = json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)."\n";
|
||||
$hash = hash('sha256', $manifestText);
|
||||
$directory = $root.'/storage/app/private/candidates/MERCHANDISE-V2-'.substr($hash, 0, 16);
|
||||
$write = function (string $path, string $body): void {
|
||||
if (is_file($path) && ! hash_equals(hash('sha256', $body), hash_file('sha256', $path))) {
|
||||
throw new LogicException('Preserve immutable preparation.');
|
||||
}
|
||||
if (! is_dir(dirname($path))) {
|
||||
mkdir(dirname($path), 0700, true);
|
||||
}
|
||||
if (! is_file($path) && file_put_contents($path, $body) !== strlen($body)) {
|
||||
throw new RuntimeException('Incomplete file.');
|
||||
}
|
||||
};
|
||||
foreach ($bodies + ['manifest.json' => $manifestText] as $file => $body) {
|
||||
$write($directory.'/'.$file, $body);
|
||||
}
|
||||
// File-only recovery rehearsal. This synthetic receipt is never included in the candidate.
|
||||
$copy = $root.'/storage/framework/testing/merchandise-v2-'.bin2hex(random_bytes(6));
|
||||
foreach ($beforeBodies as $file => $body) {
|
||||
if ($body !== null) {
|
||||
$write($copy.'/'.$file, $body);
|
||||
}
|
||||
}
|
||||
$pointer = file_get_contents($host.'/packages/purchasing/current.json');
|
||||
if (json_decode($pointer, true, 16, JSON_THROW_ON_ERROR)['version'] !== '0.1.1') {
|
||||
throw new LogicException('Preserve the known module version.');
|
||||
}
|
||||
$write($copy.'/packages/purchasing/current.json', $pointer);
|
||||
$write($copy.'/storage/framework/down', '{}');
|
||||
if (! is_dir($copy.'/bootstrap/cache')) {
|
||||
mkdir($copy.'/bootstrap/cache', 0700, true);
|
||||
}
|
||||
$copy = str_replace('\\', '/', realpath($copy));
|
||||
$receipt = ['from_manifest_sha256' => null, 'to_manifest_sha256' => $hash, 'host' => $copy, 'schema_verified' => true, 'changes' => $schema, 'synthetic_code_only_test' => true];
|
||||
$write($copy.'/storage/app/private/module-deployments/schema-transition-'.$hash.'.json', json_encode($receipt, JSON_THROW_ON_ERROR));
|
||||
$deploy = new CodeDeployment($copy);
|
||||
$plan = $deploy->plan($directory, $hash);
|
||||
$result = $deploy->apply($directory, $hash, $plan['target_sha256'], 'Synthetic file-copy rehearsal', true);
|
||||
$checks = 0;
|
||||
foreach ($overlays as $file => $entry) {
|
||||
if (hash_file('sha256', $copy.'/'.$file) !== $entry['after_sha256']) {
|
||||
throw new LogicException('Applied bytes differ.');
|
||||
} $checks++;
|
||||
}
|
||||
if (! $deploy->apply($directory, $hash, $plan['target_sha256'], 'Synthetic replay', true)['replayed']) {
|
||||
throw new LogicException('Replay failed.');
|
||||
} $checks++;
|
||||
$deploy->rollback($result['deployment_id'], 'Synthetic file recovery', true);
|
||||
foreach ($overlays as $file => $entry) {
|
||||
$actual = is_file($copy.'/'.$file) ? hash_file('sha256', $copy.'/'.$file) : null;
|
||||
if ($actual !== $entry['before_sha256']) {
|
||||
throw new LogicException('Original bytes or absence not restored.');
|
||||
} $checks++;
|
||||
}
|
||||
if (file_get_contents($host.'/packages/purchasing/current.json') !== $pointer || file_get_contents($copy.'/packages/purchasing/current.json') !== $pointer) {
|
||||
throw new LogicException('Module pointer changed.');
|
||||
} $checks++;
|
||||
$runPhp = function (string $script): string {
|
||||
$process = proc_open([PHP_BINARY, '-r', $script], [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
|
||||
if (! is_resource($process)) {
|
||||
throw new RuntimeException('Cannot qualify the delivered code.');
|
||||
}
|
||||
fclose($pipes[0]);
|
||||
$out = stream_get_contents($pipes[1]);
|
||||
$error = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
if (proc_close($process) !== 0) {
|
||||
throw new RuntimeException('Delivered code qualification failed: '.$error);
|
||||
}
|
||||
|
||||
return $out;
|
||||
};
|
||||
$script = 'require '.var_export($directory.'/integrations/sgf/operational/CodeDeployment.php', true).';'
|
||||
.'$deploy=new Tempo\\Purchasing\\Delivery\\CodeDeployment('.var_export($copy, true).');'
|
||||
.'$plan=$deploy->plan('.var_export($directory, true).','.var_export($hash, true).'); echo json_encode($plan["writes"]);';
|
||||
if ($runPhp($script) !== 'false') {
|
||||
throw new LogicException('Bundled updater does not accept its own candidate.');
|
||||
}
|
||||
$checks++;
|
||||
$script = 'require '.var_export($host.'/vendor/autoload.php', true).';'
|
||||
.'Illuminate\\Container\\Container::getInstance()->instance("config",new Illuminate\\Config\\Repository(["merchandise_invoices"=>["costs_enabled"=>true],"purchasing-internal"=>["candidate_enabled"=>false]]));'
|
||||
.'require '.var_export($directory.'/bootstrap.php', true).';'
|
||||
.'if(config("purchasing-internal.candidate_enabled")!==false)throw new RuntimeException("Code activated requisitions");'
|
||||
.'$result=Tempo\\Purchasing\\Inventory\\StockCosting::project("fifo",["reference"=>"synthetic-opening","quantity_milli"=>3000,"value_minor"=>100,"layers"=>[["quantity_milli"=>3000,"value_minor"=>100]]],'
|
||||
.'[["id"=>1,"reference"=>"synthetic-issue","kind"=>"issue","quantity_milli"=>1000],["id"=>2,"reference"=>"synthetic-final","kind"=>"issue","quantity_milli"=>2000]],"half_up_final_balance");'
|
||||
.'if($result["movements"][0]["value"]["amount_minor"]!=="33"||$result["movements"][1]["value"]["amount_minor"]!=="67")throw new RuntimeException("Calculation mismatch");echo "BOOT_AND_COST_OK";';
|
||||
if ($runPhp($script) !== 'BOOT_AND_COST_OK') {
|
||||
throw new LogicException('Incomplete candidate bootstrap.');
|
||||
}
|
||||
$checks++;
|
||||
$archive = $root.'/storage/app/private/candidate-archives/'.basename($directory).'.zip';
|
||||
$zip = new ZipArchive;
|
||||
if (! is_file($archive)) {
|
||||
$temporary = $archive.'.'.bin2hex(random_bytes(4)).'.next';
|
||||
if ($zip->open($temporary, ZipArchive::CREATE | ZipArchive::EXCL) !== true) {
|
||||
throw new RuntimeException('Cannot prepare archive.');
|
||||
}
|
||||
foreach (array_keys($bodies + ['manifest.json' => $manifestText]) as $file) {
|
||||
$zip->addFile($directory.'/'.$file, $file);
|
||||
$zip->setMtimeName($file, 946684800);
|
||||
}
|
||||
if (! $zip->close() || ! rename($temporary, $archive)) {
|
||||
throw new RuntimeException('Cannot finish archive.');
|
||||
}
|
||||
}
|
||||
if ($zip->open($archive, ZipArchive::RDONLY) !== true || $zip->numFiles !== count($bodies) + 1) {
|
||||
throw new LogicException('Unexpected archive.');
|
||||
}
|
||||
foreach ($bodies + ['manifest.json' => $manifestText] as $file => $body) {
|
||||
if (! hash_equals(hash('sha256', $body), hash('sha256', $zip->getFromName($file)))) {
|
||||
throw new LogicException('Archive bytes differ.');
|
||||
}
|
||||
}
|
||||
$zip->close();
|
||||
$proof = ['passed' => true, 'checks' => $checks, 'candidate' => basename($directory), 'manifest_sha256' => $hash, 'archive_sha256' => hash_file('sha256', $archive),
|
||||
'bundled_updater_qualified' => true, 'bundled_bootstrap_and_cost_qualified' => true, 'bootstrap_did_not_enable_requisitions' => true,
|
||||
'baseline_git_commit' => $commit, 'code_copy' => $copy, 'schema_or_data_recovery_qualified' => false, 'synthetic_schema_receipt_only' => true,
|
||||
'database_connected' => false, 'destination_installed' => false, 'pointer_preserved' => '0.1.1', 'published' => false];
|
||||
$write($copy.'/recovery-result.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
echo json_encode(['directory' => $directory, 'archive' => $archive, 'manifest_sha256' => $hash, 'archive_sha256' => $proof['archive_sha256'],
|
||||
'files' => count($files), 'host_overlays' => count($overlays), 'schema_sources_requiring_receipt' => count($schema), 'checks' => $checks, 'proof' => $copy.'/recovery-result.json', 'installed' => false], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)."\n";
|
||||
@@ -1,9 +1,9 @@
|
||||
<?php
|
||||
|
||||
use Tempo\Purchasing\Delivery\AccessOverlay;
|
||||
use Tempo\Purchasing\Delivery\AdminUiOverlay;
|
||||
use Tempo\Purchasing\Delivery\BootOverlay;
|
||||
use Tempo\Purchasing\Delivery\BudgetOverlay;
|
||||
use Tempo\Purchasing\Delivery\AdminUiOverlay;
|
||||
|
||||
require dirname(__DIR__).'/integrations/sgf/access/AccessOverlay.php';
|
||||
require dirname(__DIR__).'/integrations/sgf/operational/BudgetOverlay.php';
|
||||
@@ -18,7 +18,7 @@ $frontend = AdminUiOverlay::prepare($host, $files);
|
||||
$files = $frontend['files'];
|
||||
$root = dirname(__DIR__);
|
||||
$support = [];
|
||||
foreach (['integrations/sgf/operational', 'integrations/sgf/access', 'integrations/sgf/internal-requisitions', 'packages/purchasing/src'] as $directory) {
|
||||
foreach (['integrations/sgf/operational', 'integrations/sgf/access', 'integrations/sgf/internal-requisitions', 'integrations/sgf/sourcing', 'packages/purchasing/src'] as $directory) {
|
||||
foreach (new DirectoryIterator($root.'/'.$directory) as $file) {
|
||||
if ($file->isFile() && ! $file->isLink()) {
|
||||
$support[$directory.'/'.$file->getFilename()] = file_get_contents($file->getPathname());
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
// No Laravel bootstrap, connection, command execution or application configuration mutation.
|
||||
require __DIR__.'/lib/SgfWorkflowInventory.php';
|
||||
if ($argc !== 3) {
|
||||
fwrite(STDERR, "Usage: php scripts/sgf-workflow-inventory.php <accepted-bundle> <manifest-sha256>\n");
|
||||
exit(2);
|
||||
}
|
||||
$processes = [
|
||||
'context_permissions' => ['app/Services/WorkContext.php', 'app/Models/Concerns/HasWorkContext.php', 'app/Services/CurrentActor.php', 'app/Services/OrganizationAccess.php'],
|
||||
'requisition_budget' => ['app/Services/RequisitionWorkflow.php', 'app/Services/BudgetWorkflow.php', 'app/Services/InternalRequisitionPort.php', 'app/Models/Requisition.php'],
|
||||
'sourcing_award' => ['app/Services/PurchaseWorkflow.php', 'app/Services/ProposalComparison.php', 'app/Services/ConflictGuard.php', 'app/Services/ConflictReleases.php'],
|
||||
'orders_receipts' => ['app/Services/ReceiptWorkflow.php', 'app/Services/OrderCancellationWorkflow.php', 'app/Policies/GoodsReceiptPolicy.php', 'app/Services/ReceiptDocuments.php'],
|
||||
'obligations' => ['app/Services/InvoiceWorkflow.php', 'app/Services/SupplierPayables.php'],
|
||||
'warehouse' => ['app/Services/StockWorkflow.php', 'app/Services/WarehouseRequests.php', 'app/Services/WarehouseReservations.php', 'app/Services/WarehouseFulfilment.php'],
|
||||
'replenishment' => ['app/Services/SupplyPlanning.php', 'app/Services/SupplySuggestions.php', 'app/Services/AutomaticPurchases.php'],
|
||||
];
|
||||
try {
|
||||
echo json_encode(SgfWorkflowInventory::inspect(dirname(__DIR__), $argv[1], $argv[2], $processes), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
} catch (Throwable $error) {
|
||||
fwrite(STDERR, $error->getMessage().PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"started_at": "2026-11-30T10:38:47+00:00",
|
||||
"finished_at": "2026-11-30T10:38:47+00:00",
|
||||
"started_at": "2026-11-30T21:03:46+00:00",
|
||||
"finished_at": "2026-11-30T21:03:47+00:00",
|
||||
"scope": "SGC replenishment command",
|
||||
"result": "passed",
|
||||
"exit_code": 0,
|
||||
|
||||
@@ -382,3 +382,38 @@ test('guests cannot consult or submit declarations', function () {
|
||||
$this->get('/conflitos')->assertRedirect('/login');
|
||||
$this->post('/conflitos', personalConflict($this->supplier->id))->assertRedirect('/login');
|
||||
});
|
||||
|
||||
test('composed conflict authority is scoped and never inferred from the environment', function () {
|
||||
require_once dirname(__DIR__, 2).'/packages/purchasing/src/ExecutionContext.php';
|
||||
$execution = new \Tempo\Purchasing\Composition\ExecutionContext;
|
||||
app()->instance(\Tempo\Purchasing\Composition\ExecutionContext::class, $execution);
|
||||
config(['conflict-releases.qa_enabled' => true]);
|
||||
$service = app(\App\Services\ConflictReleases::class);
|
||||
expect($service->ready())->toBeFalse();
|
||||
$this->post('/conflitos', personalConflict($this->supplier->id, $this->r->id))->assertSessionHasNoErrors();
|
||||
$declaration = ConflictDeclaration::query()->firstOrFail();
|
||||
configureConflictDirection($this->admin);
|
||||
$this->actingAs($this->admin);
|
||||
app()->instance('env', 'budget-testing');
|
||||
$metadata = ['contract' => $execution::CONTRACT, 'composition' => 'b4093c6f6707', 'operation' => 'purchasing_conflicts.authorise',
|
||||
'scope' => ['tenant_id' => 1, 'company_id' => 2, 'unit_id' => 2],
|
||||
'actor' => ['host_id' => 15, 'native_id' => $this->admin->id],
|
||||
'generation' => str_repeat('a', 64), 'schema_sha256' => str_repeat('b', 64),
|
||||
'workflow_sha256' => str_repeat('c', 64), 'features' => ['conflict-release' => []]];
|
||||
$input = ['operation_key' => (string) Str::uuid(), 'reason' => 'Autorização sintética de direcção no contexto composto.'];
|
||||
$before = $declaration->getAttributes();
|
||||
try {
|
||||
$execution->within($metadata, DB::connection(), fn () => null, function () use ($service, $input, $declaration) {
|
||||
expect($service->ready())->toBeTrue();
|
||||
$first = $service->authorise($this->admin, $declaration, $input);
|
||||
expect($service->authorise($this->admin, $declaration, $input)->id)->toBe($first->id)
|
||||
->and(ConflictRelease::query()->count())->toBe(1);
|
||||
DB::table('organization_memberships')->where('user_id', $this->admin->id)->delete();
|
||||
expect(fn () => $service->authorise($this->admin, $declaration, $input))->toThrow(\Symfony\Component\HttpKernel\Exception\HttpException::class);
|
||||
});
|
||||
expect($service->ready())->toBeFalse()->and($declaration->fresh()->getAttributes())->toBe($before);
|
||||
} finally {
|
||||
app()->instance('env', 'testing');
|
||||
app()->forgetInstance(\Tempo\Purchasing\Composition\ExecutionContext::class);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
use Tempo\Purchasing\Composition\ExecutionContext;
|
||||
|
||||
require_once dirname(__DIR__, 2).'/packages/purchasing/src/ExecutionContext.php';
|
||||
|
||||
function compositionDeclaration(): array
|
||||
{
|
||||
return ['contract' => ExecutionContext::CONTRACT, 'composition' => 'b4093c6f6707', 'operation' => 'purchasing_conflicts.authorise',
|
||||
'scope' => ['tenant_id' => 1, 'company_id' => 2, 'unit_id' => 2], 'actor' => ['host_id' => 15, 'native_id' => 1],
|
||||
'generation' => str_repeat('a', 64), 'schema_sha256' => str_repeat('b', 64), 'workflow_sha256' => str_repeat('c', 64),
|
||||
'features' => ['conflict-release' => []]];
|
||||
}
|
||||
|
||||
test('capability exists only within the checked connection and execution', function () {
|
||||
$context = new ExecutionContext;
|
||||
$db = new stdClass;
|
||||
$checks = 0;
|
||||
expect($context->allows('conflict-release', $db))->toBeFalse();
|
||||
$result = $context->within(compositionDeclaration(), $db, function () use (&$checks) {
|
||||
$checks++;
|
||||
}, function () use ($context, $db) {
|
||||
expect($context->allows('conflict-release', $db))->toBeTrue()
|
||||
->and($context->allows('conflict-release', new stdClass))->toBeFalse()
|
||||
->and($context->allows('order-cancellation-cycles', $db))->toBeFalse();
|
||||
|
||||
return 'complete';
|
||||
});
|
||||
expect($checks)->toBe(3)->and($result)->toBe('complete')->and($context->allows('conflict-release', $db))->toBeFalse();
|
||||
});
|
||||
|
||||
test('revocation is rechecked and an exception clears the execution', function () {
|
||||
$context = new ExecutionContext;
|
||||
$db = new stdClass;
|
||||
$authorised = true;
|
||||
try {
|
||||
$context->within(compositionDeclaration(), $db, function () use (&$authorised) {
|
||||
if (! $authorised) {
|
||||
throw new RuntimeException('revoked');
|
||||
}
|
||||
}, function () use ($context, $db, &$authorised) {
|
||||
$authorised = false;
|
||||
$context->allows('conflict-release', $db);
|
||||
});
|
||||
} catch (RuntimeException $error) {
|
||||
expect($error->getMessage())->toBe('revoked');
|
||||
}
|
||||
expect($context->allows('conflict-release', $db))->toBeFalse();
|
||||
});
|
||||
|
||||
test('invalid declarations never enter the business closure', function (string $case) {
|
||||
$declaration = compositionDeclaration();
|
||||
match ($case) {
|
||||
'contract' => $declaration['contract'] = 'unknown',
|
||||
'extra' => $declaration['admin'] = true,
|
||||
'hash' => $declaration['workflow_sha256'] = 'unknown',
|
||||
'scope' => $declaration['scope']['unit_id'] = null,
|
||||
'identity' => $declaration['actor']['native_id'] = 0,
|
||||
'feature' => $declaration['features']['all'] = [],
|
||||
'component' => $declaration['features']['order-cancellation-cycles'] = ['root' => '/unknown'],
|
||||
};
|
||||
(new ExecutionContext)->within($declaration, new stdClass, fn () => null, fn () => throw new RuntimeException('business executed'));
|
||||
})->with(['contract', 'extra', 'hash', 'scope', 'identity', 'feature', 'component'])->throws(LogicException::class);
|
||||
|
||||
test('nested execution cannot replace the original authority', function () {
|
||||
$context = new ExecutionContext;
|
||||
$db = new stdClass;
|
||||
$context->within(compositionDeclaration(), $db, fn () => null, function () use ($context, $db) {
|
||||
expect(fn () => $context->within(compositionDeclaration(), $db, fn () => null, fn () => null))->toThrow(LogicException::class);
|
||||
expect($context->allows('conflict-release', $db))->toBeTrue();
|
||||
});
|
||||
expect($context->allows('conflict-release', $db))->toBeFalse();
|
||||
});
|
||||
|
||||
test('read authority cannot execute a write even when the feature is available', function () {
|
||||
$context = new ExecutionContext;
|
||||
$db = new stdClass;
|
||||
$declaration = compositionDeclaration();
|
||||
$declaration['operation'] = 'purchasing_conflicts.view';
|
||||
$context->within($declaration, $db, fn () => null, function () use ($context, $db) {
|
||||
expect($context->allows('conflict-release', $db))->toBeTrue()
|
||||
->and($context->permits('purchasing_conflicts.view', $db))->toBeTrue()
|
||||
->and($context->permits('purchasing_conflicts.authorise', $db))->toBeFalse();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,218 @@
|
||||
<?php
|
||||
|
||||
use Tempo\Purchasing\Delivery\CodeDeployment;
|
||||
|
||||
require_once __DIR__.'/../../integrations/sgf/operational/CodeDeployment.php';
|
||||
|
||||
function deploymentV2Write(string $path, string $body): void
|
||||
{
|
||||
if (! is_dir(dirname($path))) {
|
||||
mkdir(dirname($path), 0700, true);
|
||||
}
|
||||
file_put_contents($path, $body);
|
||||
}
|
||||
|
||||
function deploymentV2Fixture(): array
|
||||
{
|
||||
$root = dirname(__DIR__, 2).'/storage/framework/testing/deployment-v2-'.bin2hex(random_bytes(6));
|
||||
$host = $root.'/host';
|
||||
deploymentV2Write($host.'/app/Existing.php', 'original');
|
||||
deploymentV2Write($host.'/packages/purchasing/current.json', '{"version":"0.1.1"}');
|
||||
deploymentV2Write($host.'/storage/framework/down', '{}');
|
||||
deploymentV2Write($host.'/bootstrap/cache/config.php', '<?php return [];');
|
||||
|
||||
return [$root, $host, new CodeDeployment($host)];
|
||||
}
|
||||
|
||||
function deploymentV2Bundle(string $root, array $bodies, array $before, string $format = 'v2', ?string $from = null, array $added = [], array $schema = []): array
|
||||
{
|
||||
$dir = $root.'/bundle-'.bin2hex(random_bytes(4));
|
||||
$files = [];
|
||||
$overlays = [];
|
||||
foreach ($bodies as $file => $body) {
|
||||
deploymentV2Write($dir.'/'.$file, $body);
|
||||
$files[$file] = hash('sha256', $body);
|
||||
$overlays[$file] = ['before_sha256' => $before[$file], 'after_sha256' => $files[$file]];
|
||||
}
|
||||
$manifest = ['format' => 'tempo.operational-review.'.$format, 'support_files' => $files, 'host_overlays' => $overlays];
|
||||
if ($format === 'v2') {
|
||||
$manifest['composition_transition'] = ['from_manifest_sha256' => $from, 'added_files' => $added, 'schema_files' => $schema];
|
||||
}
|
||||
deploymentV2Write($dir.'/manifest.json', json_encode($manifest, JSON_THROW_ON_ERROR));
|
||||
|
||||
return [$dir, hash_file('sha256', $dir.'/manifest.json')];
|
||||
}
|
||||
|
||||
function deploymentV2Apply(CodeDeployment $deploy, string $dir, string $hash): array
|
||||
{
|
||||
$plan = $deploy->plan($dir, $hash);
|
||||
|
||||
return $deploy->apply($dir, $hash, $plan['target_sha256'], 'Synthetic file-only rehearsal', true);
|
||||
}
|
||||
|
||||
test('v1 still applies replays and restores its exact code cache and module pointer', function () {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
[$dir, $hash] = deploymentV2Bundle($root, ['app/Existing.php' => 'v1'], ['app/Existing.php' => hash('sha256', 'original')], 'v1');
|
||||
$result = deploymentV2Apply($deploy, $dir, $hash);
|
||||
expect(deploymentV2Apply($deploy, $dir, $hash)['replayed'])->toBeTrue();
|
||||
$deploy->rollback($result['deployment_id'], 'Synthetic recovery', true);
|
||||
expect(file_get_contents($host.'/app/Existing.php'))->toBe('original')
|
||||
->and(file_get_contents($host.'/bootstrap/cache/config.php'))->toBe('<?php return [];')
|
||||
->and(file_get_contents($host.'/packages/purchasing/current.json'))->toBe('{"version":"0.1.1"}');
|
||||
});
|
||||
|
||||
test('v2 expands v1 updates new files and recovers their original absence in order', function () {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
[$v1, $h1] = deploymentV2Bundle($root, ['app/Existing.php' => 'v1'], ['app/Existing.php' => hash('sha256', 'original')], 'v1');
|
||||
$first = deploymentV2Apply($deploy, $v1, $h1);
|
||||
[$v2, $h2] = deploymentV2Bundle($root, ['app/Existing.php' => 'v2', 'config/merchandise.php' => '<?php return false;'],
|
||||
['app/Existing.php' => hash('sha256', 'v1'), 'config/merchandise.php' => null], 'v2', $h1, ['config/merchandise.php' => null]);
|
||||
$secondPlan = $deploy->plan($v2, $h2);
|
||||
$second = deploymentV2Apply($deploy, $v2, $h2);
|
||||
expect($deploy->apply($v2, $h2, $secondPlan['target_sha256'], 'Replay same operation', true)['replayed'])->toBeTrue()
|
||||
->and(file_get_contents($host.'/config/merchandise.php'))->toBe('<?php return false;');
|
||||
[$v3, $h3] = deploymentV2Bundle($root, ['app/Existing.php' => 'v3', 'config/merchandise.php' => '<?php return null;'],
|
||||
['app/Existing.php' => hash('sha256', 'v2'), 'config/merchandise.php' => hash('sha256', '<?php return false;')], 'v2', $h2);
|
||||
$third = deploymentV2Apply($deploy, $v3, $h3);
|
||||
$deploy->rollback($third['deployment_id'], 'Recover third', true);
|
||||
expect(file_get_contents($host.'/config/merchandise.php'))->toBe('<?php return false;');
|
||||
$deploy->rollback($second['deployment_id'], 'Recover second', true);
|
||||
expect(file_exists($host.'/config/merchandise.php'))->toBeFalse()
|
||||
->and(file_get_contents($host.'/app/Existing.php'))->toBe('v1');
|
||||
$deploy->rollback($first['deployment_id'], 'Recover first', true);
|
||||
expect(file_get_contents($host.'/app/Existing.php'))->toBe('original');
|
||||
});
|
||||
|
||||
test('v2 rejects an undeclared expansion wrong predecessor or existing supposedly new file', function (string $case) {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
$added = ['config/merchandise.php' => null];
|
||||
if ($case === 'undeclared') {
|
||||
$added = [];
|
||||
}
|
||||
if ($case === 'existing') {
|
||||
deploymentV2Write($host.'/config/merchandise.php', 'preserve');
|
||||
}
|
||||
[$dir, $hash] = deploymentV2Bundle($root, ['config/merchandise.php' => 'new'], ['config/merchandise.php' => null], 'v2', $case === 'predecessor' ? str_repeat('a', 64) : null, $added);
|
||||
expect(fn () => $deploy->plan($dir, $hash))->toThrow(RuntimeException::class);
|
||||
expect(file_get_contents($host.'/app/Existing.php'))->toBe('original');
|
||||
})->with(['undeclared', 'predecessor', 'existing']);
|
||||
|
||||
test('v2 partial failure recovers newly created files without touching unknown edits', function (bool $unknownEdit) {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
[$dir, $hash] = deploymentV2Bundle($root, ['app/New.php' => 'candidate', 'app/Existing.php' => 'updated'],
|
||||
['app/New.php' => null, 'app/Existing.php' => hash('sha256', 'original')], 'v2', null,
|
||||
['app/New.php' => null, 'app/Existing.php' => hash('sha256', 'original')]);
|
||||
$plan = $deploy->plan($dir, $hash);
|
||||
try {
|
||||
$deploy->apply($dir, $hash, $plan['target_sha256'], 'Synthetic interruption', true, function ($point) {
|
||||
if ($point === 'file:app/New.php') {
|
||||
throw new RuntimeException('Synthetic interruption');
|
||||
}
|
||||
});
|
||||
test()->fail('Expected interruption.');
|
||||
} catch (RuntimeException $error) {
|
||||
expect($error->getMessage())->toBe('Synthetic interruption');
|
||||
}
|
||||
if ($unknownEdit) {
|
||||
deploymentV2Write($host.'/app/New.php', 'user edit');
|
||||
expect(fn () => $deploy->rollback($plan['deployment_id'], 'Recover', true))->toThrow(RuntimeException::class)
|
||||
->and(file_get_contents($host.'/app/New.php'))->toBe('user edit');
|
||||
} else {
|
||||
$deploy->rollback($plan['deployment_id'], 'Recover', true);
|
||||
expect(file_exists($host.'/app/New.php'))->toBeFalse();
|
||||
}
|
||||
expect(file_get_contents($host.'/app/Existing.php'))->toBe('original');
|
||||
})->with([false, true]);
|
||||
|
||||
test('v2 requires an exact schema receipt and pins it to the reviewed target', function () {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
$file = 'database/sql/synthetic.sql';
|
||||
$body = '-- synthetic, never executed';
|
||||
$schema = [$file => ['before' => null, 'after' => hash('sha256', $body)]];
|
||||
[$dir, $hash] = deploymentV2Bundle($root, [$file => $body], [$file => null], 'v2', null, [$file => null], $schema);
|
||||
expect(fn () => $deploy->plan($dir, $hash))->toThrow(RuntimeException::class);
|
||||
$receiptPath = $host.'/storage/app/private/module-deployments/schema-transition-'.$hash.'.json';
|
||||
$receipt = ['from_manifest_sha256' => null, 'to_manifest_sha256' => $hash, 'host' => str_replace('\\', '/', realpath($host)), 'schema_verified' => true, 'changes' => $schema];
|
||||
deploymentV2Write($receiptPath, json_encode($receipt, JSON_THROW_ON_ERROR));
|
||||
$plan = $deploy->plan($dir, $hash);
|
||||
$receipt['review_reference'] = 'changed after planning';
|
||||
deploymentV2Write($receiptPath, json_encode($receipt, JSON_THROW_ON_ERROR));
|
||||
expect(fn () => $deploy->apply($dir, $hash, $plan['target_sha256'], 'Synthetic', true))->toThrow(RuntimeException::class);
|
||||
expect(file_exists($host.'/'.$file))->toBeFalse();
|
||||
});
|
||||
|
||||
test('v2 rejects forbidden paths extra content and equivalent Windows paths', function (string $case) {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
[$dir] = deploymentV2Bundle($root, ['app/New.php' => 'candidate'], ['app/New.php' => null], 'v2', null, ['app/New.php' => null]);
|
||||
$manifest = json_decode(file_get_contents($dir.'/manifest.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
if ($case === 'extra') {
|
||||
deploymentV2Write($dir.'/unexpected.php', 'unlisted');
|
||||
} elseif ($case === 'equivalent') {
|
||||
$manifest['support_files']['app/new.php'] = hash('sha256', 'candidate');
|
||||
} elseif ($case === 'hash') {
|
||||
deploymentV2Write($dir.'/app/New.php', 'tampered');
|
||||
} elseif ($case === 'format') {
|
||||
$manifest['format'] = 'tempo.operational-review.v999';
|
||||
} else {
|
||||
$manifest['host_overlays'] = [$case => $manifest['host_overlays']['app/New.php']];
|
||||
}
|
||||
deploymentV2Write($dir.'/manifest.json', json_encode($manifest, JSON_THROW_ON_ERROR));
|
||||
expect(fn () => $deploy->plan($dir, hash_file('sha256', $dir.'/manifest.json')))->toThrow(RuntimeException::class);
|
||||
expect(file_exists($host.'/app/New.php'))->toBeFalse();
|
||||
})->with(['extra', 'equivalent', 'hash', 'format', '../outside.php', '.env', 'public/vendor/secret.php', 'packages/purchasing/current.json', 'routes/console.php']);
|
||||
|
||||
test('v2 update interruption restores the prior bundle at each durable stage', function (string $point) {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
[$v1, $h1] = deploymentV2Bundle($root, ['app/Existing.php' => 'v1'], ['app/Existing.php' => hash('sha256', 'original')], 'v1');
|
||||
$first = deploymentV2Apply($deploy, $v1, $h1);
|
||||
[$v2, $h2] = deploymentV2Bundle($root, ['app/Existing.php' => 'v2', 'public/sgf-new.mjs' => 'candidate'],
|
||||
['app/Existing.php' => hash('sha256', 'v1'), 'public/sgf-new.mjs' => null], 'v2', $h1, ['public/sgf-new.mjs' => null]);
|
||||
$plan = $deploy->plan($v2, $h2);
|
||||
try {
|
||||
$deploy->apply($v2, $h2, $plan['target_sha256'], 'Interrupt update', true, function ($at) use ($point) {
|
||||
if ($at === $point) {
|
||||
throw new RuntimeException('Synthetic interruption');
|
||||
}
|
||||
});
|
||||
test()->fail('Expected interruption.');
|
||||
} catch (RuntimeException $error) {
|
||||
expect($error->getMessage())->toBe('Synthetic interruption');
|
||||
}
|
||||
$deploy->rollback($plan['deployment_id'], 'Recover update', true);
|
||||
expect(file_get_contents($host.'/app/Existing.php'))->toBe('v1')
|
||||
->and(file_exists($host.'/public/sgf-new.mjs'))->toBeFalse()
|
||||
->and(hash_file('sha256', $host.'/packages/internal-requisitions/manifest.json'))->toBe($h1)
|
||||
->and(json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'), true)['deployment_id'])->toBe($first['deployment_id']);
|
||||
})->with(['prepared', 'caches-cleared', 'file:app/Existing.php', 'file:public/sgf-new.mjs', 'previous-bundle-preserved', 'bundle-switched']);
|
||||
|
||||
test('deployment uses the verified staged bytes instead of a mutable source directory', function () {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
[$dir, $hash] = deploymentV2Bundle($root, ['app/New.php' => 'candidate'], ['app/New.php' => null], 'v2', null, ['app/New.php' => null]);
|
||||
$plan = $deploy->plan($dir, $hash);
|
||||
$result = $deploy->apply($dir, $hash, $plan['target_sha256'], 'Stage isolation', true, function ($point) use ($dir) {
|
||||
if ($point === 'prepared') {
|
||||
deploymentV2Write($dir.'/app/New.php', 'source changed after staging');
|
||||
}
|
||||
});
|
||||
expect(file_get_contents($host.'/app/New.php'))->toBe('candidate');
|
||||
$deploy->rollback($result['deployment_id'], 'Recover', true);
|
||||
expect(file_exists($host.'/app/New.php'))->toBeFalse();
|
||||
});
|
||||
|
||||
test('v2 refuses links in either payload or destination', function (string $side) {
|
||||
[$root, $host, $deploy] = deploymentV2Fixture();
|
||||
deploymentV2Write($root.'/outside/New.php', 'preserve outside host');
|
||||
$file = $side === 'host' ? 'app/Linked/New.php' : 'app/New.php';
|
||||
[$dir, $hash] = deploymentV2Bundle($root, [$file => 'candidate'], [$file => null], 'v2', null, [$file => null]);
|
||||
if ($side === 'host') {
|
||||
$linked = @symlink($root.'/outside', $host.'/app/Linked');
|
||||
} else {
|
||||
unlink($dir.'/app/New.php');
|
||||
$linked = @symlink($root.'/outside/New.php', $dir.'/app/New.php');
|
||||
}
|
||||
if (! $linked) {
|
||||
test()->markTestSkipped('Creating symbolic links is unavailable; no privileges were changed.');
|
||||
}
|
||||
expect(fn () => $deploy->plan($dir, $hash))->toThrow(RuntimeException::class);
|
||||
expect(file_get_contents($root.'/outside/New.php'))->toBe('preserve outside host');
|
||||
})->with(['host', 'bundle']);
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
test('composition loads only its verified local calculation when explicitly enabled', function (string $mode) {
|
||||
$root = dirname(__DIR__, 2);
|
||||
$bundle = $root.'/storage/framework/testing/cost-bootstrap-'.bin2hex(random_bytes(6));
|
||||
mkdir($bundle, 0700, true);
|
||||
foreach (['integrations/sgf/operational/bootstrap.php', 'integrations/sgf/operational/RuntimeContext.php', 'integrations/sgf/operational/Composition.php', 'integrations/sgf/sourcing/bootstrap.php'] as $stub) {
|
||||
if (! is_dir(dirname($bundle.'/'.$stub))) {
|
||||
mkdir(dirname($bundle.'/'.$stub), 0700, true);
|
||||
}
|
||||
file_put_contents($bundle.'/'.$stub, '<?php // Test double for unrelated application boot.');
|
||||
}
|
||||
copy($root.'/integrations/sgf/operational/entry.php', $bundle.'/bootstrap.php');
|
||||
$relative = 'packages/purchasing/src/StockCosting.php';
|
||||
mkdir(dirname($bundle.'/'.$relative), 0700, true);
|
||||
copy($root.'/packages/purchasing/src/StockCosting.php', $bundle.'/'.$relative);
|
||||
$pin = hash_file('sha256', $bundle.'/'.$relative);
|
||||
file_put_contents($bundle.'/manifest.json', json_encode(['format' => 'tempo.operational-review.v2', 'support_files' => [$relative => $pin]], JSON_THROW_ON_ERROR));
|
||||
if ($mode === 'tampered') {
|
||||
file_put_contents($bundle.'/'.$relative, '<?php // tampered');
|
||||
}
|
||||
if ($mode === 'disabled') {
|
||||
unlink($bundle.'/'.$relative);
|
||||
}
|
||||
$script = 'require '.var_export($root.'/vendor/autoload.php', true).';'
|
||||
.'Illuminate\\Container\\Container::getInstance()->instance("config", new Illuminate\\Config\\Repository(["merchandise_invoices"=>["costs_enabled"=>'.($mode === 'disabled' ? 'false' : 'true').']]));';
|
||||
if ($mode === 'different_loaded_version') {
|
||||
file_put_contents($bundle.'/different.php', '<?php namespace Tempo\\Purchasing\\Inventory; final class StockCosting {}');
|
||||
$script .= 'require '.var_export($bundle.'/different.php', true).';';
|
||||
}
|
||||
$script .= 'try { require '.var_export($bundle.'/bootstrap.php', true).'; echo "BOOT_OK:".(int)class_exists(Tempo\\Purchasing\\Inventory\\StockCosting::class,false); } catch (RuntimeException $error) { echo "REFUSED:".$error->getMessage(); }';
|
||||
// Subprocess avoids sharing a PHP class definition between composition variants.
|
||||
$process = proc_open([PHP_BINARY, '-r', $script], [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes);
|
||||
expect(is_resource($process))->toBeTrue();
|
||||
fclose($pipes[0]);
|
||||
$out = stream_get_contents($pipes[1]);
|
||||
$error = stream_get_contents($pipes[2]);
|
||||
fclose($pipes[1]);
|
||||
fclose($pipes[2]);
|
||||
expect(proc_close($process))->toBe(0, $error);
|
||||
expect($out)->toStartWith(in_array($mode, ['tampered', 'different_loaded_version'], true) ? 'REFUSED:' : 'BOOT_OK:'.($mode === 'disabled' ? '0' : '1'));
|
||||
})->with(['enabled', 'disabled', 'tampered', 'different_loaded_version']);
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
require_once dirname(__DIR__, 2).'/scripts/lib/SgfWorkflowExtension.php';
|
||||
|
||||
test('workflow namespace transfer preserves rule strings comments and SQL', function () {
|
||||
$source = <<<'PHP'
|
||||
<?php
|
||||
namespace App\Services;
|
||||
use App\Models\User;
|
||||
// App\Models\User is a comment, not a PHP name token.
|
||||
final class Example {
|
||||
public function run(\App\Models\User $user): string {
|
||||
$literal = 'App\Models\User';
|
||||
$sql = "SELECT 'App\\Models\\User'";
|
||||
return $literal;
|
||||
}
|
||||
}
|
||||
PHP;
|
||||
$output = SgfWorkflowExtension::transform($source);
|
||||
expect($output)->toContain('namespace Tempo\Purchasing\Embedded\Services;')
|
||||
->toContain('use Tempo\Purchasing\Embedded\Models\User;')
|
||||
->toContain('run(\Tempo\Purchasing\Embedded\Models\User $user)')
|
||||
->toContain("'App\\Models\\User'")->toContain('// App\Models\User is a comment')
|
||||
->toContain('SELECT \'App\\\\Models\\\\User\'');
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
require_once dirname(__DIR__, 2).'/scripts/lib/SgfWorkflowInventory.php';
|
||||
|
||||
beforeEach(function () {
|
||||
$this->inventoryRoot = sys_get_temp_dir().'/sgf-inventory-'.bin2hex(random_bytes(8));
|
||||
mkdir($this->inventoryRoot.'/source/app', 0700, true);
|
||||
mkdir($this->inventoryRoot.'/bundle/app', 0700, true);
|
||||
file_put_contents($this->inventoryRoot.'/source/app/Workflow.php', '<?php // current');
|
||||
file_put_contents($this->inventoryRoot.'/bundle/app/Workflow.php', '<?php // embedded');
|
||||
$this->manifest = ['files' => ['app/Workflow.php' => hash_file('sha256', $this->inventoryRoot.'/bundle/app/Workflow.php')],
|
||||
'originals' => ['app/Workflow.php' => hash_file('sha256', $this->inventoryRoot.'/source/app/Workflow.php')]];
|
||||
$this->inspect = function (?array $manifest = null, array $paths = ['app/Workflow.php']) {
|
||||
file_put_contents($this->inventoryRoot.'/bundle/manifest.json', json_encode($manifest ?? $this->manifest));
|
||||
|
||||
return SgfWorkflowInventory::inspect($this->inventoryRoot.'/source', $this->inventoryRoot.'/bundle',
|
||||
hash_file('sha256', $this->inventoryRoot.'/bundle/manifest.json'), ['process' => $paths]);
|
||||
};
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->inventoryRoot, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
|
||||
foreach ($iterator as $file) {
|
||||
$file->isDir() && ! $file->isLink() ? rmdir($file->getPathname()) : unlink($file->getPathname());
|
||||
}
|
||||
rmdir($this->inventoryRoot);
|
||||
});
|
||||
|
||||
test('recognises preserved source without claiming functional acceptance', function () {
|
||||
$result = ($this->inspect)();
|
||||
expect($result['processes']['process']['source_equivalent'])->toBeTrue()
|
||||
->and($result['functional_acceptance'])->toBeFalse()->and($result['read_only'])->toBeTrue();
|
||||
});
|
||||
|
||||
test('reports source drift rather than treating old acceptance as current', function () {
|
||||
file_put_contents($this->inventoryRoot.'/source/app/Workflow.php', '<?php // changed');
|
||||
$result = ($this->inspect)();
|
||||
expect($result['processes']['process']['source_equivalent'])->toBeFalse()
|
||||
->and($result['processes']['process']['components']['app/Workflow.php']['status'])->toBe('source_changed');
|
||||
});
|
||||
|
||||
test('distinguishes missing source from untransferred source', function () {
|
||||
file_put_contents($this->inventoryRoot.'/source/app/New.php', '<?php // new');
|
||||
$result = ($this->inspect)(null, ['app/New.php', 'app/Missing.php']);
|
||||
expect($result['processes']['process']['components']['app/New.php']['status'])->toBe('not_transferred')
|
||||
->and($result['processes']['process']['components']['app/Missing.php']['status'])->toBe('source_missing');
|
||||
});
|
||||
|
||||
test('refuses tampering anywhere in the distributed bundle', function () {
|
||||
file_put_contents($this->inventoryRoot.'/bundle/app/Workflow.php', '<?php // tampered');
|
||||
($this->inspect)();
|
||||
})->throws(RuntimeException::class, 'Workflow bundle integrity failure.');
|
||||
|
||||
test('refuses unsafe manifest paths', function (string $path) {
|
||||
($this->inspect)(['files' => [$path => str_repeat('a', 64)], 'originals' => []]);
|
||||
})->with(['../outside.php', '/absolute.php', 'C:/outside.php', 'app/../outside.php', 'app\\outside.php'])
|
||||
->throws(RuntimeException::class, 'Invalid workflow path.');
|
||||
|
||||
test('refuses an unpinned manifest', function () {
|
||||
file_put_contents($this->inventoryRoot.'/bundle/manifest.json', json_encode($this->manifest));
|
||||
SgfWorkflowInventory::inspect($this->inventoryRoot.'/source', $this->inventoryRoot.'/bundle', str_repeat('0', 64), []);
|
||||
})->throws(RuntimeException::class, 'Unrecognised workflow manifest.');
|
||||
|
||||
test('does not accept an original hash without its distributed file', function () {
|
||||
$manifest = $this->manifest;
|
||||
$manifest['files'] = [];
|
||||
$result = ($this->inspect)($manifest);
|
||||
expect($result['processes']['process']['source_equivalent'])->toBeFalse()
|
||||
->and($result['processes']['process']['components']['app/Workflow.php']['status'])->toBe('not_transferred');
|
||||
});
|
||||
|
||||
test('requires both source and distributed inventories', function () {
|
||||
($this->inspect)(['files' => $this->manifest['files']]);
|
||||
})->throws(RuntimeException::class, 'Original and distributed hashes required.');
|
||||
@@ -76,3 +76,61 @@ test('half cent rounds upwards and the last issue receives the residual', functi
|
||||
test('an unrecognised rounding policy cannot silently change costs', function () {
|
||||
expect(fn () => StockCosting::project('fifo', costingOpening(), [], 'automatic'))->toThrow(InvalidArgumentException::class);
|
||||
});
|
||||
|
||||
test('approved zero issues preserve half up and the exact final balance', function (string $method, array $quantities, array $amounts) {
|
||||
$facts = [costingReceipt(1, 1000, 1)];
|
||||
foreach ($quantities as $index => $quantity) {
|
||||
$facts[] = costingIssue($index + 2, $quantity);
|
||||
}
|
||||
$result = StockCosting::project($method, costingOpening(), $facts, 'half_up_final_balance');
|
||||
expect(array_column(array_column(array_slice($result['movements'], 1), 'value'), 'amount_minor'))->toBe($amounts)
|
||||
->and($result['closing']['quantity_milli'])->toBe(0)
|
||||
->and($result['closing']['value']['amount_minor'])->toBe('0')
|
||||
->and($result['stock_written'])->toBeFalse()->and($result['journals_written'])->toBeFalse();
|
||||
})->with([
|
||||
['fifo', [100, 400, 500], ['0', '0', '1']],
|
||||
['weighted_average', [100, 400, 500], ['0', '0', '1']],
|
||||
['fifo', [500, 100, 400], ['1', '0', '0']],
|
||||
['weighted_average', [500, 100, 400], ['1', '0', '0']],
|
||||
]);
|
||||
|
||||
test('supplier return uses its identified receipt rather than the oldest or average price', function (string $method, string $nextCost) {
|
||||
$facts = [costingReceipt(1, 1000, 100), costingReceipt(2, 1000, 300),
|
||||
['id' => 3, 'reference' => 'synthetic-return-3', 'kind' => 'receipt_return', 'quantity_milli' => 500, 'receipt_reference' => 'synthetic-receipt-2', 'value_minor' => 150], costingIssue(4, 500)];
|
||||
$result = StockCosting::project($method, costingOpening(), $facts, 'half_up_final_balance');
|
||||
expect($result['movements'][2]['value']['amount_minor'])->toBe('150')
|
||||
->and($result['movements'][3]['value']['amount_minor'])->toBe($nextCost)
|
||||
->and($result['movements'][0]['value']['amount_minor'])->toBe('100')
|
||||
->and($result['stock_written'])->toBeFalse()->and($result['journals_written'])->toBeFalse();
|
||||
})->with([['fifo', '50'], ['weighted_average', '83']]);
|
||||
|
||||
test('returning an exhausted original layer requires reconciliation without changing prior costs', function (string $method) {
|
||||
$facts = [costingReceipt(1, 1000, 100), costingIssue(2, 1000), costingReceipt(3, 1000, 300),
|
||||
['id' => 4, 'reference' => 'synthetic-return-4', 'kind' => 'receipt_return', 'quantity_milli' => 500, 'receipt_reference' => 'synthetic-receipt-1']];
|
||||
expect(fn () => StockCosting::project($method, costingOpening(), $facts))->toThrow(DomainException::class);
|
||||
expect(StockCosting::project($method, costingOpening(), array_slice($facts, 0, 3))['movements'][1]['value']['amount_minor'])->toBe('100');
|
||||
})->with(['fifo', 'weighted_average']);
|
||||
|
||||
test('FIFO skips a completely returned layer and never consumes its value again', function () {
|
||||
$facts = [costingReceipt(1, 1000, 100), costingReceipt(2, 1000, 300),
|
||||
['id' => 3, 'reference' => 'synthetic-return-3', 'kind' => 'receipt_return', 'quantity_milli' => 1000, 'receipt_reference' => 'synthetic-receipt-1'], costingIssue(4, 1000)];
|
||||
$result = StockCosting::project('fifo', costingOpening(), $facts);
|
||||
expect($result['movements'][3]['value']['amount_minor'])->toBe('300')->and($result['closing']['value']['amount_minor'])->toBe('0');
|
||||
});
|
||||
|
||||
test('an incompatible posted return is refused instead of rewriting a journal', function () {
|
||||
$facts = [costingReceipt(1, 1000, 100), ['id' => 2, 'reference' => 'synthetic-return-2', 'kind' => 'receipt_return', 'quantity_milli' => 500, 'receipt_reference' => 'synthetic-receipt-1', 'value_minor' => 51]];
|
||||
expect(fn () => StockCosting::project('fifo', costingOpening(), $facts))->toThrow(DomainException::class);
|
||||
});
|
||||
|
||||
test('approved reconstructed layers retain receipt cost for a return and conserve the final balance', function (string $method) {
|
||||
$opening = ['reference' => 'approved-opening-1', 'quantity_milli' => 2000, 'value_minor' => 400,
|
||||
'layers' => [['reference' => 'original-receipt-1', 'quantity_milli' => 1000, 'value_minor' => 100],
|
||||
['reference' => 'reconciled-balance-1', 'quantity_milli' => 1000, 'value_minor' => 300]]];
|
||||
$facts = [['id' => 10, 'reference' => 'return-10', 'kind' => 'receipt_return', 'quantity_milli' => 500, 'receipt_reference' => 'original-receipt-1', 'value_minor' => 50], costingIssue(11, 1500)];
|
||||
$result = StockCosting::project($method, $opening, $facts, 'half_up_final_balance');
|
||||
expect($result['movements'][0]['value']['amount_minor'])->toBe('50')
|
||||
->and($result['movements'][1]['value']['amount_minor'])->toBe('350')
|
||||
->and($result['closing']['value']['amount_minor'])->toBe('0')
|
||||
->and($result['closing']['quantity_milli'])->toBe(0);
|
||||
})->with(['fifo', 'weighted_average']);
|
||||
|
||||
Reference in New Issue
Block a user