@@ -1,5 +1,18 @@
|
||||
# Integração das instruções do repositório
|
||||
|
||||
## Produto único e entrega local/pública — decisão permanente do proprietário, 29/11/2026
|
||||
|
||||
Instrução expressa: «a partir de agora e para sempre o conteudo desenvolvido é o apresentado e disponibilizado localmente e publico sem aplicações paralelas e sem simulações de desenvolvimento incompleto».
|
||||
|
||||
- Compras é uma única aplicação, com a mesma entrega funcional apresentada e disponibilizada localmente e no endereço público. Não criar produtos, edições ou aplicações paralelas de piloto, demonstração ou desenvolvimento para substituir essa entrega.
|
||||
- Cada funcionalidade desenvolvida deve ser integrada no produto e conferida nos dois destinos. Código isolado, menus, botões, ecrãs ilustrativos ou simulações de funcionalidades incompletas não constituem uma entrega concluída.
|
||||
- Concluir e demonstrar os percursos reais e as relações entre módulos. Manter as pendências efectivas identificadas na matriz existente até estarem implementadas, integradas e verificadas; não anunciar como disponível uma operação ainda não executável.
|
||||
- Usar o mesmo código e componentes aprovados, reconciliando manifestos, funcionalidades, navegação e configuração necessária entre local e público. Preservar dados, histórico, acessos e decisões já aprovadas; diferenças de perfil ou empresa não justificam perder funcionalidades anteriormente entregues.
|
||||
- A empresa de exemplo com dados sintéticos já autorizada é configuração do mesmo produto. Testes técnicos isolados continuam a verificar a entrega, sem se tornarem outra aplicação apresentada ao proprietário ou ao cliente.
|
||||
- As autorizações existentes continuam válidas no seu âmbito. Esta orientação não autoriza copiar dados reais para divulgação pública, alterar competências por inferência, eliminar instalações/dados ou executar operações financeiras externas. Uma decisão concreta em falta deve ser delimitada, prosseguindo o restante trabalho autorizado.
|
||||
|
||||
Esta decisão substitui escolhas anteriores de implementação que apresentavam entregas fragmentadas como versões alternativas do produto. Não declara concluídas as pendências existentes.
|
||||
|
||||
Política comum integrada em 13 de Novembro de 2026. As regras técnicas e decisões anteriores abaixo identificadas continuam em vigor, com o seu âmbito e autorizações originais. Esta integração documental não autoriza operações de negócio, alterações de dados, permissões, migrações, activação ou publicação.
|
||||
|
||||
**Leitura técnica obrigatória:** consultar `AGENTS.tecnico.md`, nesta raiz, antes de modificar o produto. O ficheiro contém integralmente as instruções anteriores, preservadas sem alterações; é parte integrante destas instruções, embora não seja carregado automaticamente como AGENTS.md. Ler as regras permanentes e as decisões mais recentes aplicáveis à tarefa; pesquisar o histórico e abrir as referências necessárias para determinar o estado e as autorizações efectivas. Não presumir autorização, ausência de regra ou conclusão por não ter lido a secção correspondente. Reutilizar o contexto já lido enquanto continuar válido.
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
# Orientações permanentes do SGC
|
||||
|
||||
## 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.
|
||||
|
||||
Venda para terceiros deve estar disponível também em Compras autónomo, usando o núcleo comum. Esta decisão amplia a anterior «Saída de stock — consumo interno e venda a terceiros», que limitava a venda à composição SGF. Preservar uma única autoridade financeira/física pelos componentes comuns, a operação independente de Compras e SGF e os históricos existentes. Não activar as composições artificiais de vendas identificadas como SIM/QA para as apresentar como implementação operacional.
|
||||
|
||||
Nas contratações para terceiros, a decisão final e a confirmação do contrato pertencem à Direcção da empresa prestadora do serviço de contratação. Identificar a entidade cliente no processo e preservar a distinção entre contratante/prestadora e cliente, o acesso por processo e a imutabilidade da origem. Reutilizar o circuito existente, sem admissão ou envio automático a RH.
|
||||
|
||||
- Continuação autorizada de10/11/2026: ecrã/persistência do envioSGF entregues, ver `docs/sgf-invoice-workspace.md`. Migração000001 de10/11 preparada, NÃO aplicada ao piloto; duas tabelas novas só no livro QA existenteb4093c6f6707. Configuração workspace/transporte false, ligações vazias. Rascunho/intent/decisão/recibo auditados, estado cifrado, eventos append-only, SQL25/25, fonte/mapeamento/version/operador/contexto revalidados, lease120s com commit local antes da rede, recuperação conservaUUID/cut. Writer nativo bloqueia documento reservado mesmo desligado; não reenviarInvoice local nem criar dívida/stock/pagamento paralelo.20 casos únicos/142 asserções SQLite e14 verificações PG entre kernels/processos no receptorQAda77bb730751, sem servidor/base/role/demo nova. Duas facturas pendentes no receptor; dados/sequências antigos da origem e8085 intactos. Tipos/TSX privado/Blade passaram; sem build/activação de assets do piloto, nova conta/concessão/MFA/publicação/checkpoint. Novo pacote inactivo3bb99e866f52965dbb7d; instalação/configuração/activação exigem decisão própria. Ecrã/persistência já não pendentes no âmbito anterior; preservar provas e trabalho alheio.
|
||||
|
||||
- Preparação expressa de10/11/2026 para SGC→SGF8085, sem activar/publicar: ver `docs/sgf-invoice-preparation.md` e `C:/laragon/www/sgf-tempo/docs/SGC_8085_INTEGRATION_PREPARATION.md`. `SgfInvoiceGateway` e configuração novos, desligados, pacote/hashNULL/ligações vazias; sem listener/job/rota, migração, segredo ou concessão. Cliente portátil aceita só `unregistered_draft`/autoridade SGF única e mapeamentos explícitos; não reenviar `Invoice` já registadas ou duplicar autoridade financeira.16 Unit/46 asserções e seis verificações de contrato no livro de regressão SGF existente; sem comandos no piloto ou8085. Persistência/ecrã de envio/decisão/recibo ainda necessários antes de utilizar; não presumir instalação ou activação por existir gateway/pacote preparado. Preservar workflows, configurações, dados, MFA/geografia e demais aprovações existentes.
|
||||
|
||||
@@ -57,7 +57,7 @@ class SgcDeliveryCheck extends Command
|
||||
$clean = false;
|
||||
}
|
||||
foreach ($enabled as $key) {
|
||||
if (! (WorkContext::OPTIONS[$key]['operational'] ?? false)) {
|
||||
if (! WorkContext::operational($key)) {
|
||||
$this->error('Percurso operacional ainda pendente: '.$key);
|
||||
$clean = false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\BusinessClient;
|
||||
use App\Services\BusinessClients;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final class BusinessClientController extends Controller
|
||||
{
|
||||
public function index(Request $request, BusinessClients $clients): Response
|
||||
{
|
||||
$actor = $this->staffIdentity($request);
|
||||
abort_unless($clients->ready(), 503);
|
||||
abort_unless($clients->canRead($actor), 403);
|
||||
$filters = $request->validate(['search' => 'nullable|string|max:180', 'page' => 'nullable|integer|min:1']);
|
||||
$query = BusinessClient::query()->where('tenant_id', $actor->tenant_id)
|
||||
->select(['id', 'client_key', 'code', 'name', 'tax_number', 'address', 'email', 'active', 'version']);
|
||||
if (trim($filters['search'] ?? '') !== '') {
|
||||
$query->where(fn ($q) => $q->where('name', 'like', '%'.$filters['search'].'%')->orWhere('code', 'like', '%'.$filters['search'].'%'));
|
||||
}
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('company/clients', ['clients' => $query->orderBy('name')->paginate(20)->withQueryString(),
|
||||
'filters' => $filters, 'canManage' => $clients->canManage($actor)])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function store(Request $request, BusinessClients $clients): Response
|
||||
{
|
||||
$clients->save($this->staffIdentity($request), null, $request->all());
|
||||
|
||||
return redirect('/empresa/clientes')->with('success', 'Cliente registado.');
|
||||
}
|
||||
|
||||
public function update(Request $request, int $client, BusinessClients $clients): Response
|
||||
{
|
||||
$clients->save($this->staffIdentity($request), $client, $request->all());
|
||||
|
||||
return redirect('/empresa/clientes')->with('success', 'Cliente actualizado; os processos anteriores conservam a sua identificação original.');
|
||||
}
|
||||
}
|
||||
@@ -7,10 +7,12 @@ use App\Models\PeopleProcess;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\AiPreparationPlan;
|
||||
use App\Services\BusinessClients;
|
||||
use App\Services\CandidateTriage;
|
||||
use App\Services\IntelligencePolicy;
|
||||
use App\Services\PeopleAccess;
|
||||
use App\Services\PeopleClarifications;
|
||||
use App\Services\PeopleContractFormalization;
|
||||
use App\Services\PeopleEvidenceBrief;
|
||||
use App\Services\PeopleForms;
|
||||
use App\Services\PeopleHiring;
|
||||
@@ -18,10 +20,12 @@ use App\Services\PeopleOperationalInsights;
|
||||
use App\Services\PeopleProcessProjection;
|
||||
use App\Services\PeopleRegistry;
|
||||
use App\Services\PeopleWorkdesk;
|
||||
use App\Services\WorkContext;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
@@ -37,6 +41,7 @@ class PeopleHiringController extends Controller
|
||||
$kinds = $workflow->kinds($this->actor($request));
|
||||
abort_unless($kinds !== [], 403);
|
||||
$availableKinds = $kinds;
|
||||
$clientMode = app(WorkContext::class)->active($request) === 'people.third_party';
|
||||
$filter = $request->validate(['kind' => 'nullable|in:service,staff', 'search' => 'nullable|string|max:100', 'status' => ['nullable', Rule::in(PeopleWorkdesk::STATES)],
|
||||
'from' => 'nullable|date_format:Y-m-d', 'to' => ['nullable', 'date_format:Y-m-d', Rule::when($request->filled('from'), 'after_or_equal:from')]]);
|
||||
if (isset($filter['kind'])) {
|
||||
@@ -47,8 +52,11 @@ class PeopleHiringController extends Controller
|
||||
$query = app(PeopleAccess::class)->visible(PeopleProcess::query()->whereIn('kind', $kinds), $this->actor($request));
|
||||
if (($filter['search'] ?? '') !== '') {
|
||||
$search = $filter['search'];
|
||||
$query->where(function ($q) use ($search) {
|
||||
$query->where(function ($q) use ($search, $clientMode) {
|
||||
$q->whereLike('title', '%'.$search.'%');
|
||||
if ($clientMode) {
|
||||
$q->orWhere('rules->client->name', 'like', '%'.$search.'%')->orWhere('rules->client->code', 'like', '%'.$search.'%');
|
||||
}
|
||||
if (preg_match('/^(?:PES-)?([1-9][0-9]*)$/D', $search, $matches)) {
|
||||
$reference = filter_var($matches[1], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
||||
if ($reference !== false) {
|
||||
@@ -67,14 +75,18 @@ class PeopleHiringController extends Controller
|
||||
$query->whereDate('created_at', '<=', $filter['to']);
|
||||
}
|
||||
$workdesk = $ready ? app(PeopleWorkdesk::class)->build(clone $query, $this->actor($request)) : null;
|
||||
$processes = $ready ? (clone $query)->select(['id', 'title', 'kind', 'status', 'closes_on', 'created_at', 'rules'])->latest('id')->paginate(15)->withQueryString()
|
||||
->through(fn (PeopleProcess $process) => [...$process->only(['id', 'title', 'kind', 'status', 'closes_on', 'created_at']),
|
||||
...($clientMode ? ['client' => array_intersect_key($process->rules['client'] ?? [], array_flip(['id', 'code', 'name', 'version']))] : [])]) : null;
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('people/index', ['ready' => $ready, 'kinds' => $kinds, 'availableKinds' => $availableKinds,
|
||||
'filters' => $filter, 'workdesk' => $workdesk, 'insights' => $workdesk === null ? null : app(PeopleOperationalInsights::class)->build($workdesk),
|
||||
'clientMode' => $clientMode, 'clients' => $clientMode ? app(BusinessClients::class)->choices($this->actor($request)) : [],
|
||||
'company' => Tenant::query()->findOrFail($this->actor($request)->tenant_id)->only(['name']),
|
||||
'canPrepare' => array_values(array_filter($availableKinds, fn ($kind) => $workflow->allowed($this->actor($request), $kind, 'prepare'))),
|
||||
'formFields' => ['staff' => PeopleForms::STAFF, 'service' => PeopleForms::SERVICE],
|
||||
'administration' => $ready && $this->actor($request)->hasFunctions(['admin']) ? PeopleProcess::query()->whereIn('kind', $kinds)->orderByDesc('id')->get(['id', 'kind', 'status']) : [],
|
||||
'processes' => $ready ? (clone $query)->select(['id', 'title', 'kind', 'status', 'closes_on', 'created_at'])->latest('id')->paginate(15)->withQueryString() : null])->toResponse($request);
|
||||
'processes' => $processes])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
@@ -107,8 +119,9 @@ class PeopleHiringController extends Controller
|
||||
'canPrepare' => $workflow->allowed($this->actor($request), $record->kind, 'prepare') && $access->can($this->actor($request), $record, 'prepare'),
|
||||
'canViewElectronicSources' => app(CandidateTriage::class)->canRead($this->actor($request), $record),
|
||||
'canReview' => $workflow->allowed($this->actor($request), $record->kind, 'review') && $access->can($this->actor($request), $record, 'review') && $this->actor($request)->id !== $record->created_by,
|
||||
'canApprove' => $workflow->allowed($this->actor($request), $record->kind, 'review') && $access->can($this->actor($request), $record, 'approve') && ! in_array($this->actor($request)->id, $workflow->decisionContributors($record), true),
|
||||
'canApprove' => $workflow->canConfirm($this->actor($request), $record) && ! in_array($this->actor($request)->id, $workflow->decisionContributors($record), true),
|
||||
'canContract' => $workflow->allowed($this->actor($request), $record->kind, 'prepare') && $access->can($this->actor($request), $record, 'contract'),
|
||||
'canFormalize' => app(PeopleContractFormalization::class)->can($this->actor($request), $record),
|
||||
'canManage' => $access->manages($this->actor($request), $record),
|
||||
'history' => AuditLog::query()->where('action', 'like', 'people.%')->where('after->id', $record->id)->orderBy('id')->get(['id', 'action', 'user_id', 'created_at'])])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
@@ -126,8 +139,8 @@ class PeopleHiringController extends Controller
|
||||
$record = PeopleProcess::query()->findOrFail($process);
|
||||
$data = $projection->read($this->actor($request), $record);
|
||||
|
||||
return response()->json(['schema' => 'sgc.people.process-dossier.v1', 'exported_at' => now()->toIso8601String(),
|
||||
'effect' => 'preparation_only',
|
||||
return response()->json(['schema' => $record->status === 'contract_formalized' ? 'sgc.people.process-dossier.v2' : 'sgc.people.process-dossier.v1', 'exported_at' => now()->toIso8601String(),
|
||||
'effect' => $record->status === 'contract_formalized' ? 'signed_contract_record_only' : 'preparation_only',
|
||||
'process' => Arr::only($data['process'], ['id', 'kind', 'title', 'purpose', 'closes_on', 'status', 'version', 'selected_application_id', 'rules', 'selection', 'contract']),
|
||||
'candidates' => $data['candidates']])
|
||||
->header('Content-Disposition', 'attachment; filename="PES-'.$record->id.'-dossier-v'.$record->version.'.json"')
|
||||
@@ -167,6 +180,26 @@ class PeopleHiringController extends Controller
|
||||
return redirect('/pessoas/'.$record->id);
|
||||
}
|
||||
|
||||
public function formalize(Request $request, int $process, PeopleContractFormalization $service): Response
|
||||
{
|
||||
$record = $service->confirm($this->actor($request), $process, $request->all());
|
||||
|
||||
return redirect('/pessoas/'.$record->id);
|
||||
}
|
||||
|
||||
public function signedContract(Request $request, int $process): Response
|
||||
{
|
||||
$record = PeopleProcess::query()->findOrFail($process);
|
||||
$data = app(PeopleProcessProjection::class)->read($this->actor($request), $record);
|
||||
abort_unless(isset($data['process']['contract']['signed_document']) && $record->status === 'contract_formalized', 404);
|
||||
$document = $record->contract['signed_document'];
|
||||
$disk = Storage::disk('people_contracts');
|
||||
abort_unless($disk->exists($document['path']) && hash_equals($document['sha256'], hash('sha256', $disk->get($document['path']))), 409);
|
||||
|
||||
return $disk->download($document['path'], 'contrato-assinado-'.$record->id.'.pdf', [
|
||||
'Cache-Control' => 'private, no-store', 'X-Content-Type-Options' => 'nosniff']);
|
||||
}
|
||||
|
||||
public function store(Request $request, PeopleHiring $workflow): Response
|
||||
{
|
||||
abort_unless(Schema::hasTable('people_processes'), 503);
|
||||
|
||||
@@ -10,6 +10,7 @@ use App\Services\PeopleDeadlineReport;
|
||||
use App\Services\PeopleHiring;
|
||||
use App\Services\PeopleSelectionReport;
|
||||
use App\Services\PeopleWorkdesk;
|
||||
use App\Services\WorkContext;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -38,6 +39,7 @@ class PeopleReportController extends Controller
|
||||
'to' => ['nullable', 'date_format:Y-m-d', Rule::when($request->filled('from'), 'after_or_equal:from')],
|
||||
]);
|
||||
$query = app(PeopleAccess::class)->visible(PeopleProcess::query()->whereIn('kind', $kinds), $actor);
|
||||
$clientMode = app(WorkContext::class)->active($request) === 'people.third_party';
|
||||
foreach (['kind', 'status'] as $field) {
|
||||
if (! empty($filters[$field])) {
|
||||
$query->where($field, $filters[$field]);
|
||||
@@ -45,8 +47,11 @@ class PeopleReportController extends Controller
|
||||
}
|
||||
if (! empty($filters['search'])) {
|
||||
$search = $filters['search'];
|
||||
$query->where(function ($q) use ($search) {
|
||||
$query->where(function ($q) use ($search, $clientMode) {
|
||||
$q->whereLike('title', '%'.$search.'%');
|
||||
if ($clientMode) {
|
||||
$q->orWhere('rules->client->name', 'like', '%'.$search.'%')->orWhere('rules->client->code', 'like', '%'.$search.'%');
|
||||
}
|
||||
if (preg_match('/^(?:PES-)?([1-9][0-9]*)$/D', $search, $matches)) {
|
||||
$id = filter_var($matches[1], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
|
||||
if ($id !== false) {
|
||||
@@ -61,7 +66,9 @@ class PeopleReportController extends Controller
|
||||
if (! empty($filters['to'])) {
|
||||
$query->whereDate('created_at', '<=', $filters['to']);
|
||||
}
|
||||
$columns = ['id', 'title', 'kind', 'status', 'closes_on', 'created_at'];
|
||||
$baseColumns = ['id', 'title', 'kind', 'status', 'closes_on', 'created_at'];
|
||||
$columns = [...$baseColumns, ...($clientMode ? ['rules'] : [])];
|
||||
$displayTitle = static fn (PeopleProcess $process): string => $process->title.($clientMode && isset($process->rules['client']['name']) ? ' · Cliente: '.$process->rules['client']['name'] : '');
|
||||
$page = $request->routeIs('people.reports.csv') ? null : (clone $query)->latest('id')->paginate(25, $columns)->withQueryString();
|
||||
$applications = ($filters['view'] ?? 'processes') === 'applications';
|
||||
$selections = ($filters['view'] ?? 'processes') === 'selections';
|
||||
@@ -89,7 +96,7 @@ class PeopleReportController extends Controller
|
||||
} elseif ($request->routeIs('people.reports.csv')) {
|
||||
// Materialise within the read-only snapshot; streaming runs after the transaction.
|
||||
$rows = (clone $query)->orderBy('id')->get($columns);
|
||||
$response = response()->streamDownload(function () use ($rows, $applications, $selections, $metrics) {
|
||||
$response = response()->streamDownload(function () use ($rows, $applications, $selections, $metrics, $displayTitle) {
|
||||
$file = fopen('php://output', 'w');
|
||||
if ($file === false) {
|
||||
throw new \RuntimeException('Não foi possível abrir a exportação.');
|
||||
@@ -99,7 +106,8 @@ class PeopleReportController extends Controller
|
||||
$selectionColumns = ['Situação da selecção', 'Proposta em', 'Decisão em', 'Pendência', 'Acesso à minuta', 'Referência da minuta', 'Minuta preparada em', 'Início previsto na minuta'];
|
||||
fputcsv($file, ['Referência', 'Título', 'Percurso', 'Estado', 'Fecho de candidaturas', 'Criado em', ...($applications ? $extra : ($selections ? $selectionColumns : []))], ';', '"', '');
|
||||
foreach ($rows as $row) {
|
||||
$title = preg_match('/^[\s]*[=+@-]/u', $row->title) ? "'".$row->title : $row->title;
|
||||
$title = $displayTitle($row);
|
||||
$title = preg_match('/^[\s]*[=+@-]/u', $title) ? "'".$title : $title;
|
||||
$counts = $metrics[$row->id] ?? [];
|
||||
$values = $applications ? array_values(array_map(fn ($value) => $value === null ? 'Sem acesso' : ($value === 'selection_snapshot' ? 'Selecção preservada' : ($value === 'current_eligibility' ? 'Elegibilidade actual' : $value)), $counts)) : [];
|
||||
if ($selections) {
|
||||
@@ -111,6 +119,7 @@ class PeopleReportController extends Controller
|
||||
}, 'relatorio-pessoas.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||
} else {
|
||||
$summary = (clone $query)->selectRaw('kind, status, count(*) as total')->groupBy('kind', 'status')->get();
|
||||
$page?->through(fn (PeopleProcess $process) => [...$process->only($baseColumns), 'title' => $displayTitle($process)]);
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('people/reports', [
|
||||
'filters' => $filters, 'kinds' => $kinds, 'summary' => $summary,
|
||||
@@ -151,6 +160,6 @@ class PeopleReportController extends Controller
|
||||
private static function states(): array
|
||||
{
|
||||
return ['draft' => 'Abertura por conferir', 'open' => 'Recepção de candidaturas', 'assessment' => 'Avaliação',
|
||||
'selection_review' => 'Selecção por conferir', 'selected' => 'Selecção aprovada', 'contract_draft' => 'Minuta contratual preparada'];
|
||||
'selection_review' => 'Selecção por conferir', 'selected' => 'Selecção aprovada', 'contract_draft' => 'Minuta contratual preparada', 'contract_formalized' => 'Contrato formalizado'];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,9 @@ final class PrivateAuditController extends Controller
|
||||
{
|
||||
$scope = $access->current($this->staffIdentity($request));
|
||||
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||
$exports = PrivateAuditExport::query()->where('created_by', $scope['actor']->id)->where('work_context', $scope['context'])->latest('id')->paginate(20)
|
||||
$legacyIds = $access->legacyExportIds($scope['actor'], $scope['context']);
|
||||
$exports = PrivateAuditExport::query()->where('created_by', $scope['actor']->id)
|
||||
->where(fn ($query) => $query->where('work_context', $scope['context'])->orWhereIn('id', $legacyIds))->latest('id')->paginate(20)
|
||||
->through(fn (PrivateAuditExport $export) => ['id' => $export->id, 'families' => $export->families,
|
||||
'created_at' => $export->created_at, 'size' => $export->size, 'sha256' => $export->sha256,
|
||||
'download_url' => '/auditoria/privada/'.$export->id.'/download']);
|
||||
|
||||
@@ -17,10 +17,11 @@ class EnsureWorkContext
|
||||
if ($user instanceof User && $contexts->enforced($user) && ($area = WorkContext::area($request->path())) !== null) {
|
||||
$key = $contexts->active($request);
|
||||
abort_unless($key !== null && WorkContext::OPTIONS[$key]['area'] === $area, 403, 'Seleccione uma área e opção autorizadas no Painel Inicial.');
|
||||
if (! WorkContext::OPTIONS[$key]['operational'] && $request->isMethod('GET')) {
|
||||
if (! WorkContext::operational($key) && $request->isMethod('GET')) {
|
||||
return redirect('/dashboard');
|
||||
}
|
||||
abort_unless(WorkContext::OPTIONS[$key]['operational'], 409, 'O percurso operacional desta opção ainda está em implementação.');
|
||||
abort_unless(WorkContext::operational($key), 409, 'O percurso operacional desta opção ainda está em implementação.');
|
||||
abort_unless(WorkContext::allowsPath($key, $request->path()), 403, 'Seleccione o contexto de origem desta operação.');
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
|
||||
@@ -19,7 +19,7 @@ class PublicDevelopmentNavigation
|
||||
}
|
||||
$path = '/'.$request->path();
|
||||
if ($request->path() === '/') {
|
||||
return redirect('/dashboard');
|
||||
return $next($request);
|
||||
}
|
||||
if (! isset(PublicNavigation::PAGES[$path])) {
|
||||
return $next($request);
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/** @property int $id
|
||||
* @property int $tenant_id
|
||||
* @property int $version
|
||||
* @property bool $active
|
||||
* @property string $client_key
|
||||
* @property string $code
|
||||
* @property string $name
|
||||
* @property string|null $tax_number
|
||||
* @property string $creation_hash
|
||||
* @property int $created_by
|
||||
*/
|
||||
class BusinessClient extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
|
||||
protected $guarded = ['id'];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['active' => 'boolean', 'version' => 'integer'];
|
||||
}
|
||||
}
|
||||
@@ -30,7 +30,7 @@ trait HasWorkContext
|
||||
if ($actor instanceof User && app(WorkContext::class)->enforced($actor)) {
|
||||
$key = app(WorkContext::class)->active(request());
|
||||
$area = $model->getTable() === 'people_processes' ? 'people' : 'procurement';
|
||||
abort_unless($key !== null && WorkContext::OPTIONS[$key]['operational'] && WorkContext::OPTIONS[$key]['area'] === $area, 403);
|
||||
abort_unless($key !== null && WorkContext::operational($key) && WorkContext::OPTIONS[$key]['area'] === $area, 403);
|
||||
$model->setAttribute('work_context_key', $key);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\BusinessClient;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/** Company-owned client identities; frozen process snapshots never follow later edits. */
|
||||
final class BusinessClients
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
return Schema::hasTable('business_clients');
|
||||
}
|
||||
|
||||
public function canRead(User $actor): bool
|
||||
{
|
||||
return $actor->tenant_id !== null && $actor->hasFunctions(['admin', 'procurement', 'finance', ...PeopleHiring::PERMISSIONS]);
|
||||
}
|
||||
|
||||
public function canManage(User $actor): bool
|
||||
{
|
||||
return $actor->tenant_id !== null && $actor->hasFunctions(['admin']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor);
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function choices(User $actor): array
|
||||
{
|
||||
if (! $this->ready() || ! $this->canRead($actor)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(BusinessClient::query()->where('tenant_id', $actor->tenant_id)->where('active', true)->orderBy('name')
|
||||
->get(['id', 'client_key', 'code', 'name', 'tax_number', 'version'])
|
||||
->map(fn (BusinessClient $client): array => $client->only(['id', 'client_key', 'code', 'name', 'tax_number', 'version']))->all());
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function snapshot(User $actor, int $id, int $version): array
|
||||
{
|
||||
abort_unless($this->ready() && $this->canRead($actor), 403);
|
||||
$client = BusinessClient::query()->where('tenant_id', $actor->tenant_id)->whereKey($id)->lockForUpdate()->firstOrFail();
|
||||
abort_unless($client->active && $client->version === $version, 409, 'O cliente mudou ou foi desactivado. Actualize a selecção antes de continuar.');
|
||||
|
||||
return $client->only(['id', 'client_key', 'code', 'name', 'tax_number', 'version']);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $candidate, ?int $id, array $input): BusinessClient
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
|
||||
return DB::transaction(function () use ($candidate, $id, $input): BusinessClient {
|
||||
app(ConflictGuard::class)->lockCompany($candidate);
|
||||
$actor = app(CurrentActor::class)->lock($candidate);
|
||||
abort_unless($this->canManage($actor), 403);
|
||||
$record = $id === null ? null : BusinessClient::query()->where('tenant_id', $actor->tenant_id)->lockForUpdate()->findOrFail($id);
|
||||
$existing = $record === null && is_string($input['client_key'] ?? null) && Str::isUuid($input['client_key'])
|
||||
? BusinessClient::query()->where('tenant_id', $actor->tenant_id)->where('client_key', $input['client_key'])->first() : null;
|
||||
foreach (['code', 'name', 'tax_number', 'address', 'email', 'reason'] as $field) {
|
||||
if (is_string($input[$field] ?? null)) {
|
||||
$input[$field] = trim($input[$field]);
|
||||
}
|
||||
}
|
||||
$data = Validator::make($input, [
|
||||
'client_key' => $record === null ? 'required|uuid' : 'prohibited',
|
||||
'version' => $record === null ? 'prohibited' : 'required|integer|min:1',
|
||||
'code' => ['required', 'string', 'max:40', ...($existing === null ? [Rule::unique('business_clients')->where('tenant_id', $actor->tenant_id)->ignore($record?->id)] : [])],
|
||||
'name' => 'required|string|min:2|max:180', 'tax_number' => 'nullable|string|max:40',
|
||||
'address' => 'nullable|string|max:2000', 'email' => 'nullable|email|max:254',
|
||||
'active' => 'required|boolean', 'reason' => 'required|string|min:10|max:4000',
|
||||
])->validate();
|
||||
$fields = array_intersect_key($data, array_flip(['code', 'name', 'tax_number', 'address', 'email', 'active']));
|
||||
$fields += ['tax_number' => null, 'address' => null, 'email' => null];
|
||||
$fields['active'] = (bool) $fields['active'];
|
||||
$hash = hash('sha256', json_encode($fields, JSON_THROW_ON_ERROR));
|
||||
if ($record === null) {
|
||||
if ($existing !== null) {
|
||||
abort_unless($existing->created_by === $actor->id && hash_equals($existing->creation_hash, $hash), 409);
|
||||
|
||||
return $existing;
|
||||
}
|
||||
} else {
|
||||
abort_unless($record->version === (int) $data['version'], 409, 'O cliente foi alterado. Actualize antes de guardar.');
|
||||
}
|
||||
$before = $record?->attributesToArray();
|
||||
if ($record === null) {
|
||||
$record = BusinessClient::query()->create([...$fields, 'tenant_id' => $actor->tenant_id, 'client_key' => $data['client_key'],
|
||||
'created_by' => $actor->id, 'creation_hash' => $hash, 'version' => 1]);
|
||||
} else {
|
||||
$record->fill([...$fields, 'version' => $record->version + 1])->save();
|
||||
}
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'business.client_saved', null, $before,
|
||||
['client' => $record->attributesToArray(), 'reason' => $data['reason']]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\StockOperation;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
/** Invoice-linked evidence around the existing lot/reservation/physical issue workflow. */
|
||||
final class CustomerDeliveries
|
||||
{
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function record(User $actor, array $input): array
|
||||
{
|
||||
abort_unless(app(CustomerSales::class)->ready() && Schema::hasTable('customer_deliveries'), 503);
|
||||
app(CustomerSales::class)->assertCan($actor, 'delivery');
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'invoice_id' => 'required|integer|min:1',
|
||||
'line_no' => 'required|integer|between:1,50', 'warehouse_id' => 'required|integer|min:1',
|
||||
'quantity' => 'required|string|regex:/^[0-9]{1,6}(\.[0-9]{1,3})?$/D', 'reference' => 'required|string|max:120',
|
||||
'reason' => 'required|string|min:10|max:2000'])->validate();
|
||||
foreach (['invoice_id', 'line_no', 'warehouse_id'] as $field) {
|
||||
$data[$field] = (int) $data[$field];
|
||||
}
|
||||
$quantity = ReceiptWorkflow::milli($data['quantity']);
|
||||
|
||||
return DB::transaction(function () use ($actor, $data, $quantity): array {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$current = app(CurrentActor::class)->lock($actor, [PurchasingRole::Warehouse]);
|
||||
abort_unless(app(CustomerSales::class)->can($current, 'delivery'), 403);
|
||||
$source = SalesStockSource::for($current, $data['invoice_id'], $data['line_no'], $quantity);
|
||||
$hash = hash('sha256', json_encode([$data, $source->snapshot], JSON_THROW_ON_ERROR));
|
||||
$old = DB::table('customer_deliveries')->where('tenant_id', $current->tenant_id)->where('operation_key', $data['operation_key'])->lockForUpdate()->first();
|
||||
if ($old !== null) {
|
||||
abort_unless((int) $old->created_by === $current->id, 403);
|
||||
abort_unless(hash_equals($old->payload_hash, $hash), 409, 'A chave de entrega já foi utilizada com outro conteúdo.');
|
||||
|
||||
return ['id' => (int) $old->id, 'stock_operation_id' => (int) $old->stock_operation_id, 'replayed' => true];
|
||||
}
|
||||
$delivered = DB::table('customer_deliveries')->where('tenant_id', $current->tenant_id)->where('invoice_id', $data['invoice_id'])
|
||||
->where('invoice_line_no', $data['line_no'])->sum('quantity_milli');
|
||||
abort_unless($quantity <= $source->snapshot['invoice_quantity_milli'] - (int) $delivered, 409,
|
||||
'A quantidade excede o saldo da linha facturada ainda por entregar.');
|
||||
$operation = app(StockWorkflow::class)->record($current, ['kind' => 'issue', 'reference' => $data['reference'],
|
||||
'idempotency_key' => $data['operation_key'], 'responsible_id' => $current->id, 'warehouse_id' => $data['warehouse_id'],
|
||||
'stock_item_id' => $source->snapshot['stock_item_id'], 'quantity' => $data['quantity'], 'reason' => $data['reason'],
|
||||
'destination' => $source->snapshot['client']['name'].' · '.$source->snapshot['invoice_reference']], $source);
|
||||
$id = DB::table('customer_deliveries')->insertGetId(['tenant_id' => $current->tenant_id, 'company_id' => 0, 'unit_id' => 0,
|
||||
'invoice_id' => $data['invoice_id'], 'invoice_line_no' => $data['line_no'], 'stock_operation_id' => $operation->id,
|
||||
'quantity_milli' => $quantity, 'operation_key' => $data['operation_key'], 'payload_hash' => $hash,
|
||||
'created_by' => $current->id, 'reason' => $data['reason'], 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($current, 'sales.delivered', null, null,
|
||||
['delivery_id' => $id, 'invoice_id' => $data['invoice_id'], 'line_no' => $data['line_no'], 'stock_operation_id' => $operation->id, 'quantity_milli' => $quantity]);
|
||||
|
||||
return ['id' => $id, 'stock_operation_id' => $operation->id, 'replayed' => false];
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, ?int $invoiceId = null): array
|
||||
{
|
||||
$actor = app(CustomerSales::class)->assertCan($actor, 'delivery_view');
|
||||
$engine = app(CustomerSales::class)->engine($actor);
|
||||
abort_unless(app(CustomerSales::class)->can($actor, 'delivery_view') && Schema::hasTable('customer_deliveries'), 403);
|
||||
$query = DB::table('cr_invoices')->where(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0]);
|
||||
if ($invoiceId !== null) {
|
||||
$query->where('id', $invoiceId);
|
||||
}
|
||||
$invoices = [];
|
||||
foreach ($query->orderByDesc('id')->limit(20)->pluck('id') as $id) {
|
||||
$invoice = $engine->deliveryInvoice((int) $id);
|
||||
foreach ($invoice['lines'] as &$line) {
|
||||
$line['delivered_milli'] = (int) DB::table('customer_deliveries')->where('tenant_id', $actor->tenant_id)->where('invoice_id', $id)
|
||||
->where('invoice_line_no', $line['line_no'])->sum('quantity_milli');
|
||||
$line['remaining_milli'] = $line['quantity_milli'] - $line['delivered_milli'];
|
||||
}
|
||||
unset($line);
|
||||
$invoices[] = $invoice;
|
||||
}
|
||||
$deliveries = DB::table('customer_deliveries')->where('tenant_id', $actor->tenant_id)
|
||||
->when($invoiceId !== null, fn ($query) => $query->where('invoice_id', $invoiceId))->orderByDesc('id')->limit(20)->get();
|
||||
$operations = StockOperation::query()->where('tenant_id', $actor->tenant_id)->whereIn('id', $deliveries->pluck('stock_operation_id'))
|
||||
->get(['id', 'reference', 'warehouse_id'])->keyBy('id');
|
||||
|
||||
return ['invoices' => $invoices, 'deliveries' => $deliveries->map(fn ($delivery) => ['id' => (int) $delivery->id,
|
||||
'invoice_id' => (int) $delivery->invoice_id, 'line_no' => (int) $delivery->invoice_line_no,
|
||||
'quantity_milli' => (int) $delivery->quantity_milli, 'created_at' => $delivery->created_at,
|
||||
'stock_operation_id' => (int) $delivery->stock_operation_id, 'reference' => $operations->get($delivery->stock_operation_id)?->reference])->all()];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Database\Connection;
|
||||
|
||||
/** Explicit host evidence only; stock remains owned by the existing common movement writer. */
|
||||
final class CustomerDeliverySchema
|
||||
{
|
||||
public static function install(Connection $db, \Closure $verifyInstallation): void
|
||||
{
|
||||
$verifyInstallation($db);
|
||||
if ($db->getDriverName() !== 'pgsql' || $db->getSchemaBuilder()->hasTable('customer_deliveries')
|
||||
|| ! $db->getSchemaBuilder()->hasTable('cr_invoices') || ! $db->getSchemaBuilder()->hasTable('stock_operations')) {
|
||||
throw new \LogicException('CUSTOMER_DELIVERY_SCHEMA_CONTEXT');
|
||||
}
|
||||
$db->transaction(function () use ($db): void {
|
||||
$db->unprepared(<<<'SQL'
|
||||
CREATE TABLE customer_deliveries(
|
||||
id bigserial PRIMARY KEY,tenant_id bigint NOT NULL REFERENCES tenants(id),company_id bigint NOT NULL DEFAULT 0 CHECK(company_id=0),unit_id bigint NOT NULL DEFAULT 0 CHECK(unit_id=0),
|
||||
invoice_id bigint NOT NULL,invoice_line_no integer NOT NULL CHECK(invoice_line_no BETWEEN 1 AND 50),stock_operation_id bigint NOT NULL REFERENCES stock_operations(id),
|
||||
quantity_milli bigint NOT NULL CHECK(quantity_milli>0),operation_key uuid NOT NULL,payload_hash char(64) NOT NULL,created_by bigint NOT NULL REFERENCES users(id),reason text NOT NULL,created_at timestamp NOT NULL,
|
||||
UNIQUE(tenant_id,operation_key),UNIQUE(stock_operation_id),FOREIGN KEY(invoice_id,tenant_id,company_id,unit_id) REFERENCES cr_invoices(id,tenant_id,company_id,unit_id)
|
||||
);
|
||||
CREATE FUNCTION customer_delivery_guard() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE i cr_invoices%ROWTYPE; o stock_operations%ROWTYPE; line jsonb; delivered bigint; movements bigint; physical bigint;
|
||||
BEGIN
|
||||
SELECT * INTO STRICT i FROM cr_invoices WHERE id=NEW.invoice_id AND tenant_id=NEW.tenant_id AND company_id=NEW.company_id AND unit_id=NEW.unit_id FOR UPDATE;
|
||||
SELECT * INTO STRICT o FROM stock_operations WHERE id=NEW.stock_operation_id AND tenant_id=NEW.tenant_id;
|
||||
line := i.snapshot->'amounts'->'lines'->(NEW.invoice_line_no-1);
|
||||
SELECT coalesce(sum(quantity_milli),0) INTO delivered FROM customer_deliveries WHERE tenant_id=NEW.tenant_id AND company_id=NEW.company_id AND unit_id=NEW.unit_id AND invoice_id=NEW.invoice_id AND invoice_line_no=NEW.invoice_line_no;
|
||||
SELECT count(*),coalesce(sum(quantity_milli),0) INTO movements,physical FROM stock_movements WHERE tenant_id=NEW.tenant_id AND stock_operation_id=o.id AND warehouse_id=o.warehouse_id AND stock_item_id=o.stock_item_id AND movement_type='issue';
|
||||
IF line IS NULL OR (line->>'line_no')::integer IS DISTINCT FROM NEW.invoice_line_no
|
||||
OR (line->>'stock_item_id')::bigint IS DISTINCT FROM o.stock_item_id
|
||||
OR delivered>(line->>'quantity_milli')::bigint-NEW.quantity_milli
|
||||
OR o.kind<>'issue' OR o.quantity_milli<>NEW.quantity_milli OR o.created_by<>NEW.created_by
|
||||
OR (o.snapshot->'sales_invoice'->>'invoice_id')::bigint IS DISTINCT FROM i.id
|
||||
OR (o.snapshot->'sales_invoice'->>'line_no')::integer IS DISTINCT FROM NEW.invoice_line_no
|
||||
OR o.snapshot->'sales_invoice'->>'invoice_revision' IS DISTINCT FROM i.revision
|
||||
OR movements<>1 OR physical<>-NEW.quantity_milli
|
||||
THEN RAISE EXCEPTION 'CUSTOMER_DELIVERY_SOURCE_OR_QUANTITY_MISMATCH' USING ERRCODE='23514'; END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER customer_delivery_guard BEFORE INSERT ON customer_deliveries FOR EACH ROW EXECUTE FUNCTION customer_delivery_guard();
|
||||
CREATE FUNCTION customer_delivery_preserve() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'CUSTOMER_DELIVERY_APPEND_ONLY'; END $$;
|
||||
CREATE TRIGGER customer_delivery_preserve BEFORE UPDATE OR DELETE ON customer_deliveries FOR EACH ROW EXECUTE FUNCTION customer_delivery_preserve();
|
||||
SQL);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\BusinessClient;
|
||||
use App\Models\StockItem;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Tempo\Finance\GeneralLedger\LedgerSchema;
|
||||
use Tempo\Finance\GeneralLedger\Receivables;
|
||||
use Tempo\Finance\GeneralLedger\ReceivablesSchema;
|
||||
|
||||
/** Native actor/catalogue adapter. All customer financial writes belong to the common core. */
|
||||
final class CustomerSales
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
if (config('third_party.sales_enabled') !== true || ! class_exists(Receivables::class, false)
|
||||
|| ! Schema::hasTable('business_clients') || ! Schema::hasTable('cr_invoices')) {
|
||||
return false;
|
||||
}
|
||||
$runtime = app(StandaloneRuntime::class);
|
||||
if ($runtime->enabled()) {
|
||||
return $runtime->feature('standalone-sales', DB::connection());
|
||||
}
|
||||
if (app()->environment('testing') && config('customer_sales.qa_enabled') === true && DB::getDriverName() === 'pgsql') {
|
||||
LedgerSchema::assertSynthetic(DB::connection());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function actor(User $actor, bool $lock = false): User
|
||||
{
|
||||
abort_unless($this->ready() && auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
|
||||
$fresh = $lock ? app(CurrentActor::class)->lock($actor) : User::query()->where('tenant_id', $actor->tenant_id)->findOrFail($actor->id);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($fresh), 403);
|
||||
$contexts = app(WorkContext::class);
|
||||
if ($contexts->enforced($fresh)) {
|
||||
abort_unless(app()->bound('request') && request()->hasSession() && $contexts->active(request()) === 'procurement.sales', 403,
|
||||
'Seleccione Venda para terceiros no Painel Inicial.');
|
||||
}
|
||||
|
||||
return $fresh;
|
||||
}
|
||||
|
||||
private function person(User $actor): string
|
||||
{
|
||||
if (Schema::hasTable('pa_access')) {
|
||||
$people = DB::table('pa_access')->where(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $actor->id])
|
||||
->distinct()->pluck('person')->all();
|
||||
abort_if(count($people) > 1, 409, 'A identidade financeira do operador tem correspondências divergentes.');
|
||||
if ($people !== []) {
|
||||
abort_unless(is_string($people[0]) && trim($people[0]) !== '', 409);
|
||||
|
||||
return $people[0];
|
||||
}
|
||||
}
|
||||
|
||||
return 'compras-user:'.$actor->tenant_id.':'.$actor->id;
|
||||
}
|
||||
|
||||
public function can(User $actor, string $action): bool
|
||||
{
|
||||
$roles = match ($action) {
|
||||
'series' => [PurchasingRole::Admin],
|
||||
'invoice_prepare', 'invoice_issue' => [PurchasingRole::Procurement],
|
||||
'invoice_review', 'receipts_view', 'receipt_prepare', 'receipt_decide', 'allocation_prepare', 'allocation_decide', 'reversal_prepare', 'reversal_decide' => [PurchasingRole::Finance],
|
||||
'delivery_view', 'delivery' => [PurchasingRole::Warehouse],
|
||||
'view' => [PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::Admin],
|
||||
default => [],
|
||||
};
|
||||
|
||||
return $roles !== [] && $actor->hasFunctions($roles) && ! app(OrganizationAccess::class)->maintenanceOnly($actor);
|
||||
}
|
||||
|
||||
public function assertCan(User $actor, string $action): User
|
||||
{
|
||||
$current = $this->actor($actor);
|
||||
abort_unless($this->can($current, $action), 403);
|
||||
|
||||
return $current;
|
||||
}
|
||||
|
||||
public function engine(User $actor): Receivables
|
||||
{
|
||||
$fresh = $this->actor($actor);
|
||||
$person = $this->person($fresh);
|
||||
$scope = ['tenant_id' => (int) $fresh->tenant_id, 'company_id' => 0, 'unit_id' => 0];
|
||||
|
||||
return new Receivables(DB::connection(), $scope, $fresh->id, $person,
|
||||
function (string $action) use ($fresh, $person): void {
|
||||
$current = $this->actor($fresh, ! in_array($action, ['view', 'receipts_view', 'delivery_view'], true));
|
||||
abort_unless($this->person($current) === $person, 409, 'A identidade do operador mudou; reabra o documento.');
|
||||
abort_unless($this->can($current, $action), 403);
|
||||
}, fn () => app(ConflictGuard::class)->lockCompany($fresh),
|
||||
fn (string $kind, array $input) => $this->source($fresh, $kind, $input));
|
||||
}
|
||||
|
||||
/** @return array{actor:User,scope:array<string,int>,person:string} */
|
||||
public function financialContext(User $actor): array
|
||||
{
|
||||
$fresh = $this->actor($actor);
|
||||
abort_unless($fresh->hasFunctions([PurchasingRole::Finance, PurchasingRole::Admin]), 403);
|
||||
$scope = ['tenant_id' => (int) $fresh->tenant_id, 'company_id' => 0, 'unit_id' => 0];
|
||||
$person = $this->person($fresh);
|
||||
abort_unless(DB::table('pa_access')->where($scope)->where(['user_id' => $fresh->id, 'action' => 'view', 'person' => $person])->exists(), 403);
|
||||
|
||||
return ['actor' => $fresh, 'scope' => $scope, 'person' => $person];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
private function source(User $actor, string $kind, array $input): array
|
||||
{
|
||||
abort_unless(in_array($kind, ['invoice', 'receipt'], true), 403);
|
||||
$client = BusinessClient::query()->where('tenant_id', $actor->tenant_id)->whereKey($input['client_id'])->lockForUpdate()->firstOrFail();
|
||||
abort_unless($client->version === $input['client_version'] && ($kind !== 'invoice' || $client->active), 409,
|
||||
'O cliente mudou ou deixou de aceitar novas operações; actualize a selecção.');
|
||||
$snapshot = $client->only(['id', 'code', 'name', 'tax_number', 'address', 'version']);
|
||||
if ($kind === 'receipt') {
|
||||
return ['client' => $snapshot];
|
||||
}
|
||||
$lines = [];
|
||||
foreach ($input['lines'] as $line) {
|
||||
$item = StockItem::query()->where('tenant_id', $actor->tenant_id)->whereKey($line['stock_item_id'])->lockForUpdate()->firstOrFail();
|
||||
$lines[] = [...$line, ...$item->only(['id', 'code', 'name', 'unit']), 'stock_item_id' => $item->getKey()];
|
||||
}
|
||||
$company = Tenant::query()->findOrFail($actor->tenant_id);
|
||||
|
||||
return ['client' => $snapshot, 'lines' => $lines, 'issuer' => ['id' => $company->id, 'name' => $company->name,
|
||||
...array_intersect_key($company->company_details ?? [], array_flip(['legal_name', 'nuit', 'address', 'phone', 'email']))]];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function command(User $actor, string $action, array $input): array
|
||||
{
|
||||
$this->assertCan($actor, $action);
|
||||
$rules = match ($action) {
|
||||
'series' => ['series_key' => 'required|string|max:80', 'prefix' => 'required|string|max:80', 'starts_on' => 'required|date_format:Y-m-d',
|
||||
'ends_on' => 'required|date_format:Y-m-d|after_or_equal:starts_on', 'first_number' => 'required|integer|min:1'],
|
||||
'invoice_prepare' => ['client_id' => 'required|integer|min:1', 'client_version' => 'required|integer|min:1',
|
||||
'series_key' => 'required|string|max:80', 'issued_on' => 'required|date_format:Y-m-d', 'due_on' => 'required|date_format:Y-m-d|after_or_equal:issued_on',
|
||||
'lines' => 'required|array|min:1|max:50', 'lines.*.stock_item_id' => 'required|integer|min:1',
|
||||
'lines.*.quantity' => 'required|string|regex:/^[0-9]{1,6}(\.[0-9]{1,3})?$/D',
|
||||
'lines.*.unit_price' => 'required|string|regex:/^[0-9]{1,9}(\.[0-9]{1,2})?$/D',
|
||||
'lines.*.tax_rate' => 'required|string|regex:/^[0-9]{1,3}(\.[0-9]{1,4})?$/D', 'lines.*.tax_basis' => 'required|string|max:1000'],
|
||||
'invoice_review' => ['proposal_id' => 'required|integer|min:1', 'revision' => 'required|string|size:64', 'decision' => 'required|in:approved,rejected'],
|
||||
'invoice_issue' => ['proposal_id' => 'required|integer|min:1', 'revision' => 'required|string|size:64'],
|
||||
'receipt_prepare' => ['client_id' => 'required|integer|min:1', 'client_version' => 'required|integer|min:1',
|
||||
'amount' => 'required|string|regex:/^[0-9]{1,12}(\.[0-9]{1,2})?$/D', 'received_on' => 'required|date_format:Y-m-d', 'reference' => 'required|string|max:180'],
|
||||
'allocation_prepare' => ['invoice_id' => 'required|integer|min:1', 'receipt_id' => 'required|integer|min:1',
|
||||
'amount' => 'required|string|regex:/^[0-9]{1,12}(\.[0-9]{1,2})?$/D'],
|
||||
'reversal_prepare' => ['allocation_id' => 'required|integer|min:1'],
|
||||
'receipt_decide', 'allocation_decide', 'reversal_decide' => ['proposal_id' => 'required|integer|min:1', 'revision' => 'required|string|size:64', 'decision' => 'required|in:confirmed,rejected'],
|
||||
default => throw new \InvalidArgumentException('Comando de venda desconhecido.'),
|
||||
};
|
||||
$data = Validator::make($input, $rules + ['operation_key' => 'required|uuid', 'reason' => 'required|string|min:10|max:2000'])->validate();
|
||||
$key = $data['operation_key'];
|
||||
unset($data['operation_key']);
|
||||
foreach (['client_id', 'client_version', 'first_number', 'proposal_id', 'invoice_id', 'receipt_id', 'allocation_id'] as $field) {
|
||||
if (isset($data[$field])) {
|
||||
$data[$field] = (int) $data[$field];
|
||||
}
|
||||
}
|
||||
if (isset($data['amount'])) {
|
||||
$data['amount_minor'] = BigDecimal::of($data['amount'])->multipliedBy(100)->toInt();
|
||||
unset($data['amount']);
|
||||
}
|
||||
if (isset($data['lines'])) {
|
||||
$data['lines'] = array_map(fn ($line) => ['stock_item_id' => (int) $line['stock_item_id'],
|
||||
'quantity_milli' => ReceiptWorkflow::milli($line['quantity']),
|
||||
'unit_price_minor' => BigDecimal::of($line['unit_price'])->multipliedBy(100)->toInt(),
|
||||
'tax_rate' => $line['tax_rate'], 'tax_basis' => trim($line['tax_basis'])], $data['lines']);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($actor, $action, $data, $key): array {
|
||||
$result = $this->engine($actor)->command($action, $data, $key);
|
||||
if (! $result['replayed']) {
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'sales.'.$action, null, null, ['result' => $result, 'reason' => $data['reason']]);
|
||||
}
|
||||
|
||||
return $result;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,7 @@ class OrganizationAccess
|
||||
'finance' => 'Conferência e operações financeiras',
|
||||
'warehouse' => 'Recepção e operações de armazém',
|
||||
'admin' => 'Administrar a empresa, utilizadores e parametrização',
|
||||
'people_contract_formalize' => 'Direcção: confirmar contrato assinado de Pessoas',
|
||||
'people_service_prepare' => 'Preparar contratação de prestadores individuais',
|
||||
'people_service_review' => 'Avaliar e conferir contratação de prestadores individuais',
|
||||
'people_staff_prepare' => 'Preparar recrutamento de trabalhadores',
|
||||
|
||||
@@ -76,6 +76,9 @@ class PeopleAccess
|
||||
$target = User::query()->where('tenant_id', $actor->tenant_id)->where('id', $data['user_id'])->firstOrFail();
|
||||
abort_unless($data['scopes'] === [] || app(PeopleHiring::class)->allowed($target, $record->kind), 422, 'Atribua primeiro um perfil compatível com este percurso na parametrização da empresa.');
|
||||
foreach ($data['scopes'] as $scope) {
|
||||
if ($scope === 'approve' && app(ThirdPartyHiring::class)->isClientProcess($record) && ! app(ThirdPartyHiring::class)->direction($target)) {
|
||||
throw ValidationException::withMessages(['scopes' => 'A decisão final para o cliente exige a autoridade de Direcção da prestadora.']);
|
||||
}
|
||||
$function = match ($scope) {
|
||||
'review', 'approve' => 'review', 'prepare', 'contract' => 'prepare', default => null
|
||||
};
|
||||
|
||||
@@ -12,7 +12,7 @@ class PeopleApplicationReport
|
||||
/** @return array<string,int|string|null> */
|
||||
public function counts(PeopleProcess $process, User $actor): array
|
||||
{
|
||||
$frozen = in_array($process->status, ['selected', 'contract_draft'], true);
|
||||
$frozen = in_array($process->status, ['selected', 'contract_draft', 'contract_formalized'], true);
|
||||
$rows = $frozen ? ($process->selection['rows'] ?? []) : app(PeopleHiring::class)->matrix($process);
|
||||
$complete = count(array_filter($rows, fn ($row) => $row['score_minor'] !== null));
|
||||
$started = count(array_filter($rows, fn ($row) => $row['evaluation_count'] > 0));
|
||||
|
||||
@@ -93,13 +93,13 @@ class PeopleClarifications
|
||||
$users = User::query()->where('tenant_id', $process->tenant_id)->orderBy('name')->get()->filter(fn ($user) => $this->eligibleResponsible($user, $process))->map(fn ($user) => $user->only(['id', 'name']))->values()->all();
|
||||
}
|
||||
|
||||
return ['ready' => true, 'items' => $items, 'sources' => $sources, 'users' => $users, 'preservedDecision' => in_array($process->status, ['selected', 'contract_draft'], true)];
|
||||
return ['ready' => true, 'items' => $items, 'sources' => $sources, 'users' => $users, 'preservedDecision' => in_array($process->status, ['selected', 'contract_draft', 'contract_formalized'], true)];
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function sources(User $actor, PeopleProcess $process): array
|
||||
{
|
||||
if (! Schema::hasTable('people_clarifications') || ! in_array($process->status, ['assessment', 'selection_review', 'selected', 'contract_draft'], true) || ! $this->canRaise($actor, $process)) {
|
||||
if (! Schema::hasTable('people_clarifications') || ! in_array($process->status, ['assessment', 'selection_review', 'selected', 'contract_draft', 'contract_formalized'], true) || ! $this->canRaise($actor, $process)) {
|
||||
return [];
|
||||
}
|
||||
$existing = DB::table('people_clarifications')->where('tenant_id', $process->tenant_id)->where('people_process_id', $process->id)->get(['people_review_id', 'criterion_index']);
|
||||
@@ -139,7 +139,7 @@ class PeopleClarifications
|
||||
$data['responsible_id'] = $responsible->id;
|
||||
}
|
||||
if ($command === 'create') {
|
||||
abort_unless(in_array($process->status, ['assessment', 'selection_review', 'selected', 'contract_draft'], true), 409);
|
||||
abort_unless(in_array($process->status, ['assessment', 'selection_review', 'selected', 'contract_draft', 'contract_formalized'], true), 409);
|
||||
$data += Validator::make($input, ['operation_key' => 'required|uuid', 'review_id' => 'required|integer|min:1', 'criterion_index' => 'required|integer|between:0,19'])->validate();
|
||||
$review = DB::table('people_reviews as r')->join('people_applications as a', 'a.id', '=', 'r.people_application_id')->where('r.tenant_id', $process->tenant_id)->where('a.people_process_id', $process->id)->where('r.id', $data['review_id'])->first(['r.id', 'r.answers', 'a.id as application_id']);
|
||||
abort_unless($review !== null, 404);
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\PeopleProcess;
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Direction records signed evidence; no employee admission or external dispatch. */
|
||||
final class PeopleContractFormalization
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
return Schema::hasTable('migrations') && DB::table('migrations')->where('migration', '2026_11_29_000003_allow_signed_people_contract')->exists();
|
||||
}
|
||||
|
||||
public function can(User $actor, PeopleProcess $record): bool
|
||||
{
|
||||
$access = app(PeopleAccess::class);
|
||||
|
||||
return $this->ready() && $actor->tenant_id === $record->tenant_id
|
||||
&& ! app(OrganizationAccess::class)->maintenanceOnly($actor)
|
||||
&& in_array('people_contract_formalize', app(OrganizationAccess::class)->permissions($actor), true)
|
||||
&& $access->can($actor, $record, 'view')
|
||||
&& ($access->can($actor, $record, 'contract') || $access->can($actor, $record, 'contract_view'));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function confirm(User $actor, int $id, array $input): PeopleProcess
|
||||
{
|
||||
abort_unless($this->ready(), 503, 'A instalação da formalização contratual está pendente.');
|
||||
$created = null;
|
||||
try {
|
||||
return DB::transaction(function () use ($actor, $id, $input, &$created) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$fresh = app(CurrentActor::class)->lock($actor);
|
||||
$record = PeopleProcess::query()->where('tenant_id', $fresh->tenant_id)->lockForUpdate()->findOrFail($id);
|
||||
abort_unless($this->can($fresh, $record), 403);
|
||||
$data = Validator::make($input, ['version' => 'required|integer|min:1', 'operation_key' => 'required|uuid',
|
||||
'signed_on' => 'required|date_format:Y-m-d|before_or_equal:today', 'reference' => 'required|string|max:200',
|
||||
'reason' => 'required|string|min:10|max:4000', 'no_conflict' => 'accepted',
|
||||
'signed_document' => 'required|file|mimes:pdf|max:10240'])->validate();
|
||||
/** @var UploadedFile $file */
|
||||
$file = $data['signed_document'];
|
||||
$digest = hash_file('sha256', $file->getRealPath());
|
||||
abort_unless(is_string($digest), 503, 'Não foi possível conferir o documento assinado.');
|
||||
$hash = hash('sha256', json_encode([$data['signed_on'], $data['reference'], $data['reason'], $digest], JSON_THROW_ON_ERROR));
|
||||
if (($record->contract['formalization_operation_key'] ?? null) === $data['operation_key']) {
|
||||
abort_unless(hash_equals($record->contract['formalization_hash'], $hash), 409);
|
||||
|
||||
return $record;
|
||||
}
|
||||
abort_unless($record->version === (int) $data['version'], 409, 'O processo mudou. Actualize antes de confirmar.');
|
||||
abort_unless($record->status === 'contract_draft' && ($record->contract['status'] ?? null) === 'draft'
|
||||
&& $record->selected_application_id !== null, 409, 'Prepare a minuta após a selecção aprovada.');
|
||||
$disk = Storage::disk('people_contracts');
|
||||
$path = $file->storeAs($record->tenant_id.'/'.$record->id, Str::uuid().'.pdf', 'people_contracts');
|
||||
$created = $path;
|
||||
abort_unless(is_string($path) && hash_equals($digest, hash('sha256', $disk->get($path))), 503);
|
||||
$before = app(PeopleHiring::class)->snapshot($record);
|
||||
$record->contract = [...$record->contract, 'status' => 'formalized', 'signed_on' => $data['signed_on'],
|
||||
'signed_reference' => $data['reference'], 'formalized_at' => now()->toIso8601String(), 'formalized_by' => $fresh->id,
|
||||
'formalization_reason' => $data['reason'], 'formalization_operation_key' => $data['operation_key'], 'formalization_hash' => $hash,
|
||||
'signed_document' => ['path' => $path, 'sha256' => $digest, 'bytes' => $file->getSize()]];
|
||||
$record->status = 'contract_formalized';
|
||||
$record->version++;
|
||||
$record->save();
|
||||
$after = app(PeopleHiring::class)->snapshot($record);
|
||||
unset($after['contract']['signed_document']['path']);
|
||||
app(RequisitionWorkflow::class)->audit($fresh, 'people.contract_formalized', null, $before, $after);
|
||||
|
||||
return $record;
|
||||
});
|
||||
} catch (\Throwable $error) {
|
||||
if (is_string($created)) {
|
||||
Storage::disk('people_contracts')->delete($created);
|
||||
}
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,11 +19,14 @@ class PeopleContractHandoff
|
||||
&& ! empty($process->contract['reference'])
|
||||
&& $process->selected_application_id !== null, 409, 'A ligação a RH exige contrato interno formalizado.');
|
||||
|
||||
$contract = $process->contract;
|
||||
unset($contract['signed_document']['path'], $contract['formalization_operation_key'], $contract['formalization_hash']);
|
||||
|
||||
return ['schema' => 'sgc.people.contract_formalized.v1',
|
||||
'idempotency_key' => 'sgc:'.$process->tenant_id.':people:'.$process->id.':contract:'.$process->version,
|
||||
'tenant_id' => $process->tenant_id, 'process_id' => $process->id, 'process_version' => $process->version,
|
||||
'application_id' => $process->selected_application_id, 'kind' => $process->kind,
|
||||
'work_context_key' => $process->getAttribute('work_context_key'),
|
||||
'contract' => $process->contract];
|
||||
'contract' => $contract];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,20 +22,21 @@ class PeopleEvidenceBrief
|
||||
$rules = $process['rules'];
|
||||
$add('rules', count($rules['criteria']).' critérios preservados; mínimo de '.$rules['minimum_reviews'].' avaliações independentes por candidatura. Estes requisitos não comprovam que todas as avaliações já foram feitas.',
|
||||
'#people-report-scope', 'Âmbito e critérios preservados', 'process.rules', $rules);
|
||||
$frozen = $process['selection'] !== null && in_array($process['status'], ['selection_review', 'selected', 'contract_draft'], true);
|
||||
$frozen = $process['selection'] !== null && in_array($process['status'], ['selection_review', 'selected', 'contract_draft', 'contract_formalized'], true);
|
||||
$rows = $frozen ? $process['selection']['rows'] : $candidates;
|
||||
$add('candidates', count($rows).' candidaturas constam da '.($frozen ? 'base de selecção preservada apresentada no relatório.' : 'matriz actual apresentada no relatório.').' A pontuação não constitui selecção automática.',
|
||||
'#people-report-candidates', 'Candidaturas e avaliação', $frozen ? 'process.selection.rows' : 'candidates', $rows);
|
||||
if ($process['selection'] !== null) {
|
||||
$approved = in_array($process['status'], ['selected', 'contract_draft'], true);
|
||||
$approved = in_array($process['status'], ['selected', 'contract_draft', 'contract_formalized'], true);
|
||||
$text = $approved ? 'Existe uma selecção aprovada e preservada; não equivale a contrato assinado ou admissão efectiva.' :
|
||||
($process['status'] === 'selection_review' ? 'Existe uma proposta de selecção pendente de conferência independente.' : 'A proposta de selecção foi devolvida para nova análise; não está aprovada.');
|
||||
$add('selection', $text,
|
||||
'#people-report-selection', 'Fundamento da selecção', 'process.selection', [$process['status'], $process['selection']]);
|
||||
}
|
||||
if ($contractVisible && $process['contract'] !== null) {
|
||||
$add('contract', 'Consta uma minuta contratual de preparação interna, sem confirmação de assinatura ou admissão efectiva.',
|
||||
'#people-report-contract', 'Minuta contratual', 'process.contract', $process['contract']);
|
||||
$formalized = $process['status'] === 'contract_formalized' && ($process['contract']['status'] ?? null) === 'formalized';
|
||||
$add('contract', $formalized ? 'Consta contrato assinado, com comprovativo e confirmação registada pela direcção. A admissão efectiva mantém registo separado.' : 'Consta uma minuta contratual de preparação interna, sem confirmação de assinatura ou admissão efectiva.',
|
||||
'#people-report-contract', $formalized ? 'Contrato formalizado' : 'Minuta contratual', 'process.contract', $process['contract']);
|
||||
}
|
||||
if ($clarifications['ready']) {
|
||||
$pending = count(array_filter($clarifications['items'], fn ($item) => $item['status'] !== 'resolved'));
|
||||
|
||||
@@ -30,6 +30,12 @@ class PeopleHiring
|
||||
return array_values(array_filter(['service', 'staff'], fn ($kind) => $this->allowed($actor, $kind)));
|
||||
}
|
||||
|
||||
public function canConfirm(User $actor, PeopleProcess $record): bool
|
||||
{
|
||||
return $this->allowed($actor, $record->kind, 'review') && app(PeopleAccess::class)->can($actor, $record, 'approve')
|
||||
&& (! app(ThirdPartyHiring::class)->isClientProcess($record) || app(ThirdPartyHiring::class)->direction($actor));
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function snapshot(PeopleProcess $record): array
|
||||
{
|
||||
@@ -88,9 +94,13 @@ class PeopleHiring
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
if ($command === 'create') {
|
||||
$context = app(ThirdPartyHiring::class)->creationContext($actor);
|
||||
$clientRules = $context === 'people.third_party'
|
||||
? ['client_id' => 'required|integer|min:1', 'client_version' => 'required|integer|min:1']
|
||||
: ['client_id' => 'prohibited', 'client_version' => 'prohibited'];
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'kind' => 'required|in:service,staff', 'title' => 'required|string|min:3|max:200',
|
||||
'purpose' => 'required|string|min:10|max:5000', 'closes_on' => 'required|date_format:Y-m-d|after_or_equal:today', 'minimum_reviews' => 'required|integer|between:1,20',
|
||||
'criteria' => 'required|array|min:1|max:20', 'criteria.*.label' => 'required|string|max:150|distinct', 'criteria.*.weight' => 'required|integer|between:1,100'])->validate();
|
||||
'criteria' => 'required|array|min:1|max:20', 'criteria.*.label' => 'required|string|max:150|distinct', 'criteria.*.weight' => 'required|integer|between:1,100', ...$clientRules])->validate();
|
||||
abort_unless($this->allowed($actor, $data['kind'], 'prepare'), 403);
|
||||
if (array_sum(array_column($data['criteria'], 'weight')) !== 100) {
|
||||
throw ValidationException::withMessages(['criteria' => 'As ponderações dos critérios devem somar 100%.']);
|
||||
@@ -100,18 +110,19 @@ class PeopleHiring
|
||||
$data['annex'] = $annex;
|
||||
}
|
||||
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||
$existing = PeopleProcess::query()->where('operation_key', $data['operation_key'])->first();
|
||||
$existing = PeopleProcess::query()->withoutGlobalScope('work_context')->where('tenant_id', $actor->tenant_id)->where('operation_key', $data['operation_key'])->first();
|
||||
if ($existing) {
|
||||
abort_unless($existing->created_by === $actor->id && $existing->creation_hash === $hash, 409);
|
||||
abort_unless($existing->created_by === $actor->id && $existing->creation_hash === $hash && $existing->getAttribute('work_context_key') === $context, 409);
|
||||
|
||||
return $existing;
|
||||
}
|
||||
$submissionForm = app(SubmissionForms::class)->opportunity($actor->tenant_id, $data['kind']);
|
||||
$client = $context === 'people.third_party' ? app(ThirdPartyHiring::class)->clientRules($actor, (int) $data['client_id'], (int) $data['client_version']) : [];
|
||||
$record = PeopleProcess::query()->create(['tenant_id' => $actor->tenant_id, 'created_by' => $actor->id,
|
||||
'operation_key' => $data['operation_key'], 'creation_hash' => $hash, 'kind' => $data['kind'], 'title' => $data['title'],
|
||||
'purpose' => $data['purpose'], 'closes_on' => $data['closes_on'], 'rules' => ['minimum_reviews' => (int) $data['minimum_reviews'],
|
||||
'criteria' => array_map(fn ($criterion) => ['label' => trim($criterion['label']), 'weight' => (int) $criterion['weight']], $data['criteria']),
|
||||
...($annex === null ? [] : ['annex' => $annex]), ...($submissionForm === null ? [] : ['submission_form' => $submissionForm])]]);
|
||||
...$client, ...($annex === null ? [] : ['annex' => $annex]), ...($submissionForm === null ? [] : ['submission_form' => $submissionForm])]]);
|
||||
DB::table('people_access_states')->insert(['tenant_id' => $record->tenant_id, 'people_process_id' => $record->id, 'version' => 1]);
|
||||
app(PeopleAccess::class)->insert($record, $actor->id, ['view', 'prepare', 'contract', 'manage', ...(! empty($annex['fields']['financial']) ? ['financial'] : [])], 'Preparação assumida ao criar o processo.');
|
||||
$before = null;
|
||||
@@ -129,6 +140,9 @@ class PeopleHiring
|
||||
'open', 'evaluate' => 'review', 'confirm' => 'approve', 'contract' => 'contract', default => 'prepare'
|
||||
};
|
||||
abort_unless(app(PeopleAccess::class)->can($actor, $record, $scope), 403);
|
||||
if ($command === 'confirm') {
|
||||
abort_unless($this->canConfirm($actor, $record), 403, 'A decisão final para o cliente compete à Direcção da prestadora.');
|
||||
}
|
||||
if ($command === 'open') {
|
||||
Validator::make($input, ['no_conflict' => 'accepted'])->validate();
|
||||
abort_unless($record->status === 'draft' && $record->created_by !== $actor->id, 403, 'A abertura exige conferente distinto do preparador.');
|
||||
|
||||
@@ -15,6 +15,7 @@ class PeopleProcessProjection
|
||||
abort_unless($access->can($actor, $record, 'view'), 403);
|
||||
$workflow = app(PeopleHiring::class);
|
||||
$snapshot = $workflow->snapshot($record);
|
||||
unset($snapshot['contract']['signed_document']['path'], $snapshot['contract']['formalization_operation_key'], $snapshot['contract']['formalization_hash']);
|
||||
$rows = $workflow->matrix($record);
|
||||
if (! $access->can($actor, $record, 'financial')) {
|
||||
unset($snapshot['rules']['annex']['fields']['financial']);
|
||||
|
||||
@@ -15,7 +15,7 @@ class PeopleSelectionReport
|
||||
$selection = $process->selection ?? [];
|
||||
$state = match ($process->status) {
|
||||
'selection_review' => 'Proposta por conferir',
|
||||
'selected', 'contract_draft' => 'Selecção aprovada',
|
||||
'selected', 'contract_draft', 'contract_formalized' => 'Selecção aprovada',
|
||||
default => ($selection['outcome'] ?? null) === 'returned' ? 'Proposta devolvida' : 'Sem proposta de selecção',
|
||||
};
|
||||
$pending = match ($process->status) {
|
||||
@@ -24,6 +24,7 @@ class PeopleSelectionReport
|
||||
'selection_review' => 'Conferir proposta por pessoa independente',
|
||||
'selected' => 'Preparar minuta contratual',
|
||||
'contract_draft' => 'Minuta preparada; formalização não registada neste percurso',
|
||||
'contract_formalized' => 'Contrato assinado confirmado pela direcção',
|
||||
default => 'Consultar processo',
|
||||
};
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ use Illuminate\Support\Facades\Schema;
|
||||
|
||||
class PeopleWorkdesk
|
||||
{
|
||||
public const STATES = ['draft', 'open', 'assessment', 'selection_review', 'selected', 'contract_draft'];
|
||||
public const STATES = ['draft', 'open', 'assessment', 'selection_review', 'selected', 'contract_draft', 'contract_formalized'];
|
||||
|
||||
/** @param Builder<PeopleProcess> $query
|
||||
* @return array<string,mixed>
|
||||
@@ -29,14 +29,18 @@ class PeopleWorkdesk
|
||||
foreach ((clone $query)->orderBy('id')->lazyById(100) as $record) {
|
||||
$total++;
|
||||
// Preparing a draft does not close a hiring process or prove a signed contract.
|
||||
$active++;
|
||||
$active += $record->status === 'contract_formalized' ? 0 : 1;
|
||||
$contractDrafts += $record->status === 'contract_draft' ? 1 : 0;
|
||||
$scopes = $access->scopes($actor, $record);
|
||||
$prepare = ! $maintenance && in_array('prepare', $scopes, true) && $workflow->allowed($actor, $record->kind, 'prepare');
|
||||
$review = ! $maintenance && in_array('review', $scopes, true) && $workflow->allowed($actor, $record->kind, 'review');
|
||||
$approve = ! $maintenance && in_array('approve', $scopes, true) && $workflow->allowed($actor, $record->kind, 'review');
|
||||
$approve = ! $maintenance && $workflow->canConfirm($actor, $record);
|
||||
$contract = ! $maintenance && in_array('contract', $scopes, true) && $workflow->allowed($actor, $record->kind, 'prepare');
|
||||
$base = ['process_id' => $record->id, 'reference' => 'PES-'.$record->id, 'title' => $record->title, 'kind' => $record->kind, 'status' => $record->status];
|
||||
$title = $record->title;
|
||||
if (app(ThirdPartyHiring::class)->isClientProcess($record) && isset($record->rules['client']['name'])) {
|
||||
$title .= ' · Cliente: '.$record->rules['client']['name'];
|
||||
}
|
||||
$base = ['process_id' => $record->id, 'reference' => 'PES-'.$record->id, 'title' => $title, 'kind' => $record->kind, 'status' => $record->status];
|
||||
$pendingTriage = in_array($record->status, ['open', 'assessment'], true) ? app(CandidateTriage::class)->pending($record) : 0;
|
||||
$item = fn (string $action, string $label, ?string $due = null, ?int $application = null) => [...$base,
|
||||
'id' => $record->id.':'.$action.($application === null ? '' : ':'.$application), 'action' => $action, 'label' => $label, 'due_on' => $due,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\PrivateAuditExport;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
@@ -31,6 +32,26 @@ final class PrivateAuditAccess
|
||||
&& Schema::hasTable('private_audit_exports');
|
||||
}
|
||||
|
||||
/** Exact historical archives approved for the installation's context transition.
|
||||
* @return list<int>
|
||||
*/
|
||||
public function legacyExportIds(User $actor, string $context): array
|
||||
{
|
||||
if ($context !== 'procurement.internal' || auth()->id() !== $actor->id || $actor->tenant_id === null) {
|
||||
return [];
|
||||
}
|
||||
$pins = config('private-audit.legacy_export_transitions.'.$actor->tenant_id, []);
|
||||
if (! is_array($pins) || $pins === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(PrivateAuditExport::query()->where('tenant_id', $actor->tenant_id)->where('created_by', $actor->id)->where('work_context', 'legacy')
|
||||
->whereIn('id', array_keys($pins))->get(['id', 'sha256'])
|
||||
->filter(fn (PrivateAuditExport $export) => is_string($pins[$export->id] ?? null)
|
||||
&& preg_match('/^[a-f0-9]{64}$/D', $pins[$export->id]) === 1 && hash_equals($pins[$export->id], $export->sha256))
|
||||
->map(fn (PrivateAuditExport $export) => (int) $export->id)->all());
|
||||
}
|
||||
|
||||
/** @return array{actor:User,context:string,granted:list<string>} */
|
||||
public function current(User $candidate): array
|
||||
{
|
||||
|
||||
@@ -139,7 +139,9 @@ final class PrivateAuditExporter
|
||||
$scope = app(PrivateAuditAccess::class)->authorise($candidate, $export->families);
|
||||
$actor = $scope['actor'];
|
||||
abort_unless($export->tenant_id === $actor->tenant_id && $export->created_by === $actor->id, 404);
|
||||
abort_unless($scope['context'] === $export->work_context, 409, 'Seleccione o contexto original da exportação.');
|
||||
abort_unless($scope['context'] === $export->work_context
|
||||
|| in_array($export->id, app(PrivateAuditAccess::class)->legacyExportIds($actor, $scope['context']), true),
|
||||
409, 'Seleccione o contexto original da exportação.');
|
||||
$prefix = 'audit-exports/'.$actor->tenant_id.'/'.$actor->id.'/';
|
||||
abort_unless(preg_match('/^'.preg_quote($prefix, '/').'[a-f0-9-]{36}\/auditoria\.zip$/D', $export->path) === 1, 409);
|
||||
$disk = Storage::disk('local');
|
||||
|
||||
@@ -8,7 +8,7 @@ use Illuminate\Support\Str;
|
||||
use LogicException;
|
||||
use RuntimeException;
|
||||
|
||||
/** Only new, individually tracked files in an owned QA workspace; never recursive deletion. */
|
||||
/** Only new, individually tracked files in private application storage. */
|
||||
final class PrivateAuditFiles
|
||||
{
|
||||
public readonly string $relative;
|
||||
@@ -24,12 +24,15 @@ final class PrivateAuditFiles
|
||||
public function __construct(User $actor)
|
||||
{
|
||||
$disk = Storage::disk('local');
|
||||
$boundary = realpath(base_path('storage/framework/testing'));
|
||||
$operational = app(StandaloneRuntime::class)->enabled();
|
||||
abort_if($operational && ! app(PrivateAuditAccess::class)->ready(), 503);
|
||||
$boundary = realpath($operational ? storage_path() : base_path('storage/framework/testing'));
|
||||
$storageRoot = realpath($disk->path(''));
|
||||
abort_unless($actor->id === auth()->id() && $actor->tenant_id !== null && $boundary !== false && $storageRoot !== false
|
||||
&& $this->within($storageRoot, $boundary), 503, 'A exportação requer armazenamento QA isolado.');
|
||||
$public = realpath(public_path());
|
||||
abort_if($public !== false && $this->within($storageRoot, $public), 503, 'O pacote de auditoria não pode usar armazenamento público.');
|
||||
&& $this->within($storageRoot, $boundary), 503, 'A exportação requer armazenamento privado da aplicação.');
|
||||
foreach ([realpath(public_path()), realpath(storage_path('app/public'))] as $public) {
|
||||
abort_if($public !== false && ($storageRoot === $public || $this->within($storageRoot, $public)), 503, 'O pacote de auditoria não pode usar armazenamento público.');
|
||||
}
|
||||
$this->relative = 'audit-exports/'.$actor->tenant_id.'/'.$actor->id.'/'.Str::uuid();
|
||||
$this->root = $disk->path($this->relative);
|
||||
$parent = $storageRoot;
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
|
||||
/** Only a current authorised read of an issued invoice can construct this source. */
|
||||
final readonly class SalesStockSource
|
||||
{
|
||||
/** @param array<string,mixed> $snapshot */
|
||||
private function __construct(public array $snapshot) {}
|
||||
|
||||
public static function for(User $actor, int $invoiceId, int $lineNumber, int $quantity): self
|
||||
{
|
||||
abort_unless($invoiceId > 0 && $lineNumber > 0 && $quantity > 0, 422);
|
||||
$invoice = app(CustomerSales::class)->engine($actor)->deliveryInvoice($invoiceId);
|
||||
$selected = null;
|
||||
foreach ($invoice['lines'] as $line) {
|
||||
if ($line['line_no'] === $lineNumber) {
|
||||
$selected = $line;
|
||||
break;
|
||||
}
|
||||
}
|
||||
abort_unless(is_array($selected) && is_int($selected['stock_item_id'] ?? null)
|
||||
&& $quantity <= $selected['quantity_milli'], 409, 'Seleccione uma linha de stock da factura emitida e a quantidade ainda por entregar.');
|
||||
|
||||
return new self(['invoice_id' => $invoiceId, 'invoice_reference' => $invoice['reference'], 'invoice_revision' => $invoice['revision'],
|
||||
'client' => $invoice['client'], 'line_no' => $lineNumber, 'stock_item_id' => $selected['stock_item_id'],
|
||||
'invoice_quantity_milli' => $selected['quantity_milli'], 'quantity_milli' => $quantity]);
|
||||
}
|
||||
|
||||
public function verify(User $actor): void
|
||||
{
|
||||
$current = self::for($actor, $this->snapshot['invoice_id'], $this->snapshot['line_no'], $this->snapshot['quantity_milli']);
|
||||
abort_unless($current->snapshot === $this->snapshot, 409, 'A origem da entrega mudou; reabra a factura.');
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,8 @@ final class StandaloneInstallation
|
||||
}
|
||||
$settings = config('standalone-runtime');
|
||||
$settings['enabled'] = true;
|
||||
$settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true);
|
||||
$selected = (new StandaloneArtifact)->verify($settings['root'], $settings['manifest_sha256']);
|
||||
$settings['features'] = array_fill_keys(array_values(array_intersect(StandaloneRuntime::FEATURES, $selected['manifest']['capabilities'])), true);
|
||||
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
|
||||
$artifact = $runtime->artifact();
|
||||
$runtime->assertLoadedPackages(allowMissing: true);
|
||||
|
||||
@@ -12,7 +12,7 @@ final class StandaloneRuntime
|
||||
'urgent-reviews', 'urgent-quotations', 'conflict-releases', 'private-audit', 'expense-allocations',
|
||||
'agreement-order-limits', 'order-parts', 'import-tariffs', 'import-legal', 'import-dossier',
|
||||
'import-bank-support', 'import-readiness', 'import-estimates', 'import-landed-costs', 'budget-distributions',
|
||||
'supplier-payables', 'general-ledger', 'supplier-settlements', 'general-ledger-cycle', 'finance-configuration'];
|
||||
'supplier-payables', 'general-ledger', 'supplier-settlements', 'general-ledger-cycle', 'finance-configuration', 'standalone-sales'];
|
||||
|
||||
/** @var array{root:string,manifest:array<string,mixed>,paths:array<string,string>}|null */
|
||||
private ?array $artifact = null;
|
||||
@@ -85,6 +85,16 @@ final class StandaloneRuntime
|
||||
}
|
||||
}
|
||||
if (! $allowMissing) {
|
||||
if ($this->requested('standalone-sales')) {
|
||||
foreach (['ReceivablesSchema' => ['CONTRACT', 'COMMON-RECEIVABLES-v1'],
|
||||
'ConfiguredSales' => ['CONTRACT', 'COMMON-LEDGER-CONFIGURED-SALES-v1'],
|
||||
'CustomerInvoiceMath' => ['POLICY', 'COMMON-CUSTOMER-LINE-AMOUNTS-v1']] as $type => [$constant, $value]) {
|
||||
$class = 'Tempo\\Finance\\GeneralLedger\\'.$type;
|
||||
if (! class_exists($class, false) || (new \ReflectionClass($class))->getConstant($constant) !== $value) {
|
||||
throw new LogicException('COMPRAS_RUNTIME_CUSTOMER_CONTRACT');
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($this->requested('finance-configuration')) {
|
||||
$configuration = 'Tempo\\Finance\\GeneralLedger\\LedgerConfiguration';
|
||||
if (! class_exists($configuration, false) || (new \ReflectionClass($configuration))->getConstant('VERSION') !== 'COMMON-FINANCE-CONFIGURATION-v1') {
|
||||
|
||||
@@ -14,7 +14,8 @@ final class StandaloneSchema
|
||||
foreach (['import-legal' => ['import-tariffs'], 'import-bank-support' => ['import-dossier'],
|
||||
'import-readiness' => ['import-dossier'], 'general-ledger' => ['supplier-payables'],
|
||||
'supplier-settlements' => ['supplier-payables'], 'general-ledger-cycle' => ['general-ledger', 'supplier-settlements'],
|
||||
'finance-configuration' => ['supplier-payables', 'general-ledger']] as $feature => $dependencies) {
|
||||
'finance-configuration' => ['supplier-payables', 'general-ledger'],
|
||||
'standalone-sales' => ['general-ledger-cycle', 'finance-configuration']] as $feature => $dependencies) {
|
||||
foreach ($dependencies as $dependency) {
|
||||
if (($features[$feature] ?? false) === true && ($features[$dependency] ?? false) !== true) {
|
||||
throw new LogicException('COMPRAS_RUNTIME_FEATURE_DEPENDENCY:'.$feature.':'.$dependency);
|
||||
@@ -28,6 +29,16 @@ final class StandaloneSchema
|
||||
continue;
|
||||
}
|
||||
$required = match ($feature) {
|
||||
'standalone-sales' => ['business_clients' => ['id', 'tenant_id', 'version'],
|
||||
'cr_series' => ['id', 'tenant_id', 'company_id', 'unit_id', 'series_key'],
|
||||
'cr_invoice_proposals' => ['id', 'revision', 'snapshot'], 'cr_invoice_reviews' => ['id', 'proposal_id', 'decision'],
|
||||
'cr_invoices' => ['id', 'client_id', 'reference', 'total_minor', 'snapshot'],
|
||||
'cr_receipt_proposals' => ['id', 'client_id', 'amount_minor'], 'cr_receipt_decisions' => ['id', 'proposal_id', 'decision'],
|
||||
'cr_allocation_proposals' => ['id', 'invoice_id', 'receipt_id', 'amount_minor'], 'cr_allocation_decisions' => ['id', 'proposal_id', 'decision'],
|
||||
'cr_reversal_proposals' => ['id', 'allocation_id'], 'cr_reversal_decisions' => ['id', 'proposal_id', 'decision'],
|
||||
'cr_commands' => ['id', 'operation_key', 'request_hash'], 'cr_events' => ['id', 'kind', 'entity_id'],
|
||||
'gl_configured_sales' => ['contract', 'original_validator_sha256'], 'gl_rules' => ['tax_account_id'],
|
||||
'customer_deliveries' => ['id', 'tenant_id', 'invoice_id', 'invoice_line_no', 'stock_operation_id', 'quantity_milli']],
|
||||
'capital-register' => ['equipment' => ['id', 'tenant_id', 'department_id']],
|
||||
'private-audit' => ['private_audit_exports' => ['id', 'tenant_id']],
|
||||
'conflict-releases' => ['conflict_releases' => ['id', 'tenant_id']],
|
||||
|
||||
@@ -27,7 +27,7 @@ class StockWorkflow
|
||||
}
|
||||
|
||||
/** @param array{kind: string, reference: string, idempotency_key: string, responsible_id: int, warehouse_id: int, stock_item_id: int, destination_warehouse_id?: int, quantity: string, reason: string, destination?: string, count_id?: int, ledger_version?: int, equipment_id?: int,lot_counts?:list<array<string,mixed>>,lot_version?:string} $data */
|
||||
public function record(User $actor, array $data): StockOperation
|
||||
public function record(User $actor, array $data, ?SalesStockSource $sale = null): StockOperation
|
||||
{
|
||||
if (! in_array($data['kind'], ['issue', 'transfer', 'count', 'adjustment'], true)) {
|
||||
throw ValidationException::withMessages(['kind' => 'Esta operação exige o seu próprio percurso de preparação e aprovação.']);
|
||||
@@ -35,11 +35,17 @@ class StockWorkflow
|
||||
$roles = $data['kind'] === 'adjustment' ? [PurchasingRole::Warehouse, 'inventory_adjust_review'] : [PurchasingRole::Warehouse];
|
||||
abort_unless($actor->tenant_id !== null && $actor->hasFunctions($roles) && auth()->id() === $actor->id, 403);
|
||||
|
||||
return DB::transaction(function () use ($actor, $data) {
|
||||
return DB::transaction(function () use ($actor, $data, $sale) {
|
||||
// Same first lock as receipts: includes empty balances and concurrent receipts.
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
abort_unless($actor->hasFunctions($data['kind'] === 'adjustment' ? [PurchasingRole::Warehouse, 'inventory_adjust_review'] : [PurchasingRole::Warehouse]), 403);
|
||||
if ($sale !== null) {
|
||||
$sale->verify($actor);
|
||||
abort_unless($data['kind'] === 'issue' && $data['stock_item_id'] === $sale->snapshot['stock_item_id']
|
||||
&& ReceiptWorkflow::milli($data['quantity']) === $sale->snapshot['quantity_milli'], 409);
|
||||
$data['sales_invoice'] = $sale->snapshot;
|
||||
}
|
||||
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||
$existing = StockOperation::query()->where('idempotency_key', $data['idempotency_key'])->first();
|
||||
if ($existing) {
|
||||
@@ -57,7 +63,7 @@ class StockWorkflow
|
||||
$item = StockItem::query()->findOrFail($data['stock_item_id']);
|
||||
$equipment = $data['kind'] === 'issue' && isset($data['equipment_id']) ? Equipment::query()->findOrFail($data['equipment_id']) : null;
|
||||
$part = $data['kind'] === 'issue' ? SparePart::query()->where('stock_item_id', $item->id)->first() : null;
|
||||
if ($part) {
|
||||
if ($part && $sale === null) {
|
||||
if (! $equipment) {
|
||||
throw ValidationException::withMessages(['equipment_id' => 'Seleccione o equipamento de destino associado à peça.']);
|
||||
}
|
||||
@@ -125,7 +131,7 @@ class StockWorkflow
|
||||
'equipment_id' => $equipment?->id, 'spare_part_id' => $part?->id,
|
||||
'payload_hash' => $hash, 'destination' => $data['destination'] ?? null, 'reason' => $data['reason'],
|
||||
'quantity_milli' => $quantity, 'theoretical_milli' => $balance['quantity'], 'ledger_version' => $balance['version'], 'recorded_at' => now(),
|
||||
'snapshot' => [...$lotSnapshot, 'actor' => $actor->only(['id', 'name']), 'responsible' => $responsible->only(['id', 'name']), 'stock_item' => $item->only(['id', 'code', 'name', 'unit']), 'warehouse' => $warehouse->only(['id', 'code', 'name']), 'destination_warehouse' => $destination?->only(['id', 'code', 'name']), 'equipment' => $equipment?->toArray(), 'spare_part' => $part?->toArray(), 'difference_milli' => $quantity - $balance['quantity'], 'budget_checked' => false, 'development_only' => app(StandaloneRuntime::class)->syntheticOnly()],
|
||||
'snapshot' => [...$lotSnapshot, ...($sale === null ? [] : ['sales_invoice' => $sale->snapshot]), 'actor' => $actor->only(['id', 'name']), 'responsible' => $responsible->only(['id', 'name']), 'stock_item' => $item->only(['id', 'code', 'name', 'unit']), 'warehouse' => $warehouse->only(['id', 'code', 'name']), 'destination_warehouse' => $destination?->only(['id', 'code', 'name']), 'equipment' => $equipment?->toArray(), 'spare_part' => $part?->toArray(), 'difference_milli' => $quantity - $balance['quantity'], 'budget_checked' => false, 'development_only' => app(StandaloneRuntime::class)->syntheticOnly()],
|
||||
]);
|
||||
if ($adjustment !== null) {
|
||||
foreach ([['decrease_milli', -1, 'adjustment_out'], ['increase_milli', 1, 'adjustment_in']] as [$key, $sign, $type]) {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\PeopleProcess;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
|
||||
/** Client identity and the provider's Direction authority in the existing hiring lifecycle. */
|
||||
final class ThirdPartyHiring
|
||||
{
|
||||
public function creationContext(User $actor): string
|
||||
{
|
||||
$contexts = app(WorkContext::class);
|
||||
$key = $contexts->enforced($actor) && app()->bound('request') && request()->hasSession()
|
||||
? $contexts->active(request()) : 'people.internal';
|
||||
abort_unless(in_array($key, ['people.internal', 'people.third_party'], true) && WorkContext::operational($key), 403);
|
||||
|
||||
return $key;
|
||||
}
|
||||
|
||||
public function isClientProcess(PeopleProcess $record): bool
|
||||
{
|
||||
return $record->getAttribute('work_context_key') === 'people.third_party';
|
||||
}
|
||||
|
||||
public function direction(User $actor): bool
|
||||
{
|
||||
// The existing separately assigned Direction authority never follows from Admin.
|
||||
return in_array('people_contract_formalize', app(OrganizationAccess::class)->permissions($actor), true)
|
||||
&& ! app(OrganizationAccess::class)->maintenanceOnly($actor);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function clientRules(User $actor, int $client, int $version): array
|
||||
{
|
||||
$snapshot = app(BusinessClients::class)->snapshot($actor, $client, $version);
|
||||
$provider = Tenant::query()->findOrFail($actor->tenant_id);
|
||||
|
||||
return ['client' => $snapshot, 'provider' => ['tenant_id' => $actor->tenant_id, 'name' => $provider->name],
|
||||
'decision_authority' => 'provider_direction'];
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,18 @@ class WorkContext
|
||||
'people.third_party' => ['area' => 'people', 'areaLabel' => 'Pessoas e contratações', 'label' => 'Contratações para terceiros', 'operational' => false],
|
||||
];
|
||||
|
||||
public static function operational(string $key): bool
|
||||
{
|
||||
if ($key === 'procurement.sales') {
|
||||
return app(CustomerSales::class)->ready();
|
||||
}
|
||||
if ($key === 'people.third_party') {
|
||||
return config('third_party.people_enabled') === true && Schema::hasTable('business_clients');
|
||||
}
|
||||
|
||||
return self::OPTIONS[$key]['operational'] ?? false;
|
||||
}
|
||||
|
||||
/** @return list<string> */
|
||||
public function purchased(User $user): array
|
||||
{
|
||||
@@ -147,14 +159,20 @@ class WorkContext
|
||||
if ($area === null) {
|
||||
$sharedPaths[] = $path;
|
||||
}
|
||||
if ($area === null || ($active !== null && self::OPTIONS[$active]['operational'] && self::OPTIONS[$active]['area'] === $area)) {
|
||||
if ($area === null || ($active !== null && self::operational($active) && self::OPTIONS[$active]['area'] === $area && self::allowsPath($active, $path))) {
|
||||
$paths[] = $path;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$options = self::OPTIONS;
|
||||
foreach ($options as $key => &$option) {
|
||||
$option['operational'] = self::operational($key);
|
||||
}
|
||||
unset($option);
|
||||
|
||||
return ['enforced' => $enabled, 'active' => $active, 'paths' => $paths, 'sharedPaths' => $sharedPaths, 'permissions' => $permissions,
|
||||
'options' => self::OPTIONS, 'available' => $enabled ? $this->available($user) : [],
|
||||
'options' => $options, 'available' => $enabled ? $this->available($user) : [],
|
||||
'purchased' => $user instanceof User ? $this->purchased($user) : []];
|
||||
}
|
||||
|
||||
@@ -167,4 +185,18 @@ class WorkContext
|
||||
|
||||
return $path === '/pessoas' || str_starts_with($path, '/pessoas/') ? 'people' : 'procurement';
|
||||
}
|
||||
|
||||
public static function allowsPath(string $key, string $path): bool
|
||||
{
|
||||
$path = '/'.ltrim(explode('?', $path)[0], '/');
|
||||
if (self::area($path) === null) {
|
||||
return true;
|
||||
}
|
||||
$salesPath = $path === '/vendas' || str_starts_with($path, '/vendas/');
|
||||
if ($key === 'procurement.sales') {
|
||||
return $salesPath || $path === '/general-ledger' || str_starts_with($path, '/general-ledger/');
|
||||
}
|
||||
|
||||
return ! $salesPath;
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -15,6 +15,8 @@ return [
|
||||
|
||||
'name' => env('APP_NAME', 'Laravel'),
|
||||
|
||||
'demonstration' => env('COMPRAS_DEMONSTRATION', false),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application Environment
|
||||
|
||||
@@ -29,6 +29,13 @@ return [
|
||||
*/
|
||||
|
||||
'disks' => [
|
||||
'people_contracts' => [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('app/people-contracts'),
|
||||
'visibility' => 'private',
|
||||
'serve' => false,
|
||||
'throw' => true,
|
||||
],
|
||||
'receipt_documents' => [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('app/receipt-documents'),
|
||||
@@ -55,7 +62,7 @@ return [
|
||||
|
||||
'local' => [
|
||||
'driver' => 'local',
|
||||
'root' => storage_path('app/private'),
|
||||
'root' => env('COMPRAS_PRIVATE_STORAGE_PATH', storage_path('app/private')),
|
||||
'serve' => true,
|
||||
'throw' => false,
|
||||
'report' => false,
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
<?php
|
||||
|
||||
return ['qa_enabled' => false];
|
||||
return [
|
||||
'qa_enabled' => false,
|
||||
// Explicit installation transition receipt: tenant => immutable export ID => original SHA-256.
|
||||
'legacy_export_transitions' => json_decode(env('COMPRAS_AUDIT_LEGACY_TRANSITIONS', '{}'), true, 32, JSON_THROW_ON_ERROR),
|
||||
];
|
||||
|
||||
@@ -9,6 +9,7 @@ return [
|
||||
'installation_id' => env('COMPRAS_RUNTIME_INSTALLATION_ID'),
|
||||
'synthetic_only' => env('COMPRAS_RUNTIME_SYNTHETIC_ONLY', true),
|
||||
'features' => [
|
||||
'standalone-sales' => env('SGC_STANDALONE_SALES_ENABLED', false),
|
||||
'supplier-payables' => env('COMPRAS_SUPPLIER_PAYABLES_ENABLED', false),
|
||||
'general-ledger' => env('COMPRAS_GENERAL_LEDGER_ENABLED', false),
|
||||
'general-ledger-cycle' => env('COMPRAS_GENERAL_LEDGER_CYCLE_ENABLED', false),
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'people_enabled' => env('SGC_PEOPLE_THIRD_PARTY_ENABLED', false),
|
||||
'sales_enabled' => env('SGC_STANDALONE_SALES_ENABLED', false),
|
||||
];
|
||||
@@ -10,6 +10,7 @@ return new class extends Migration
|
||||
public function up(): void
|
||||
{
|
||||
$this->guardSqlite();
|
||||
$triggers = $this->sqliteTriggers();
|
||||
Schema::table('requisitions', function (Blueprint $table) {
|
||||
$table->foreignId('cost_center_id')->nullable()->change();
|
||||
$table->date('needed_by')->nullable()->change();
|
||||
@@ -19,6 +20,7 @@ return new class extends Migration
|
||||
$table->unsignedBigInteger('total_minor')->nullable()->change();
|
||||
$table->json('draft_input')->nullable();
|
||||
});
|
||||
$this->restoreSqliteTriggers($triggers);
|
||||
if (DB::getDriverName() === 'pgsql') {
|
||||
DB::statement("ALTER TABLE requisitions ADD CONSTRAINT requisitions_complete_before_submission CHECK (status IN ('draft', 'cancelled') OR (cost_center_id IS NOT NULL AND needed_by IS NOT NULL AND justification IS NOT NULL AND subtotal_minor IS NOT NULL AND tax_minor IS NOT NULL AND total_minor IS NOT NULL AND draft_input IS NULL))");
|
||||
}
|
||||
@@ -30,6 +32,7 @@ return new class extends Migration
|
||||
throw new LogicException('Complete ou preserve os rascunhos antes de reverter a estrutura; não substituir dados em falta por valores fictícios.');
|
||||
}
|
||||
$this->guardSqlite();
|
||||
$triggers = $this->sqliteTriggers();
|
||||
if (DB::getDriverName() === 'pgsql') {
|
||||
DB::statement('ALTER TABLE requisitions DROP CONSTRAINT requisitions_complete_before_submission');
|
||||
}
|
||||
@@ -42,6 +45,25 @@ return new class extends Migration
|
||||
$table->unsignedBigInteger('total_minor')->nullable(false)->change();
|
||||
$table->dropColumn('draft_input');
|
||||
});
|
||||
$this->restoreSqliteTriggers($triggers);
|
||||
}
|
||||
|
||||
/** @return array<string, string> */
|
||||
private function sqliteTriggers(): array
|
||||
{
|
||||
return DB::getDriverName() === 'sqlite'
|
||||
? DB::table('sqlite_master')->where('type', 'trigger')->where('tbl_name', 'requisitions')->pluck('sql', 'name')->all()
|
||||
: [];
|
||||
}
|
||||
|
||||
/** @param array<string, string> $triggers */
|
||||
private function restoreSqliteTriggers(array $triggers): void
|
||||
{
|
||||
foreach ($triggers as $name => $sql) {
|
||||
if (! DB::table('sqlite_master')->where('type', 'trigger')->where('name', $name)->exists()) {
|
||||
DB::unprepared($sql);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function guardSqlite(): void
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
$added = ['status', 'signed_on', 'signed_reference', 'formalized_at', 'formalized_by', 'formalization_reason',
|
||||
'formalization_operation_key', 'formalization_hash', 'signed_document'];
|
||||
if (DB::getDriverName() === 'pgsql') {
|
||||
$keys = "ARRAY['".implode("','", $added)."']";
|
||||
DB::unprepared("CREATE OR REPLACE FUNCTION sgc_preserve_people_process() RETURNS trigger LANGUAGE plpgsql AS \$\$ BEGIN
|
||||
IF TG_OP = 'DELETE' OR OLD.status = 'contract_formalized' THEN RAISE EXCEPTION 'Preservar processo e contrato'; END IF;
|
||||
IF OLD.status = 'contract_draft' AND (
|
||||
NEW.status <> 'contract_formalized' OR NEW.version <> OLD.version + 1
|
||||
OR (to_jsonb(NEW) - ARRAY['status','version','contract','updated_at']) IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['status','version','contract','updated_at'])
|
||||
OR (NEW.contract::jsonb - {$keys}) IS DISTINCT FROM (OLD.contract::jsonb - 'status')
|
||||
OR NEW.contract::jsonb->>'status' IS DISTINCT FROM 'formalized'
|
||||
OR NEW.contract::jsonb->>'formalized_by' IS NULL
|
||||
OR NEW.contract::jsonb->'signed_document'->>'sha256' IS NULL
|
||||
) THEN RAISE EXCEPTION 'Preservar minuta e seleccao'; END IF;
|
||||
IF ROW(NEW.tenant_id,NEW.created_by,NEW.kind,NEW.title,NEW.purpose,NEW.closes_on,NEW.rules::text,NEW.operation_key,NEW.creation_hash)
|
||||
IS DISTINCT FROM ROW(OLD.tenant_id,OLD.created_by,OLD.kind,OLD.title,OLD.purpose,OLD.closes_on,OLD.rules::text,OLD.operation_key,OLD.creation_hash)
|
||||
THEN RAISE EXCEPTION 'Preservar regras e ambito do processo'; END IF;
|
||||
RETURN NEW; END \$\$;");
|
||||
} elseif (DB::getDriverName() === 'sqlite') {
|
||||
$paths = "'$.".implode("','$.", $added)."'";
|
||||
DB::unprepared('DROP TRIGGER preserve_people_process_update');
|
||||
DB::unprepared("CREATE TRIGGER preserve_people_process_update BEFORE UPDATE ON people_processes WHEN
|
||||
OLD.status = 'contract_formalized'
|
||||
OR (OLD.status = 'contract_draft' AND (
|
||||
NEW.status <> 'contract_formalized' OR NEW.version <> OLD.version + 1
|
||||
OR NEW.opened_by IS NOT OLD.opened_by OR NEW.confirmed_by IS NOT OLD.confirmed_by
|
||||
OR NEW.selected_application_id IS NOT OLD.selected_application_id OR NEW.selection IS NOT OLD.selection OR NEW.created_at IS NOT OLD.created_at
|
||||
OR json_remove(NEW.contract,{$paths}) IS NOT json_remove(OLD.contract,'$.status')
|
||||
OR json_extract(NEW.contract,'$.status') IS NOT 'formalized'
|
||||
OR json_extract(NEW.contract,'$.formalized_by') IS NULL
|
||||
OR json_extract(NEW.contract,'$.signed_document.sha256') IS NULL))
|
||||
OR NEW.tenant_id IS NOT OLD.tenant_id OR NEW.created_by IS NOT OLD.created_by OR NEW.kind IS NOT OLD.kind OR NEW.title IS NOT OLD.title
|
||||
OR NEW.purpose IS NOT OLD.purpose OR NEW.closes_on IS NOT OLD.closes_on OR NEW.rules IS NOT OLD.rules
|
||||
OR NEW.operation_key IS NOT OLD.operation_key OR NEW.creation_hash IS NOT OLD.creation_hash
|
||||
BEGIN SELECT RAISE(ABORT, 'Preservar regras e processo'); END;");
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
throw new LogicException('Preservar contratos formalizados e evidências.');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('business_clients', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('tenant_id')->constrained('tenants');
|
||||
$table->uuid('client_key');
|
||||
$table->string('code', 40);
|
||||
$table->string('name', 180);
|
||||
$table->string('tax_number', 40)->nullable();
|
||||
$table->text('address')->nullable();
|
||||
$table->string('email', 254)->nullable();
|
||||
$table->boolean('active')->default(true);
|
||||
$table->unsignedInteger('version')->default(1);
|
||||
$table->foreignId('created_by')->constrained('users');
|
||||
$table->string('creation_hash', 64);
|
||||
$table->timestamps();
|
||||
$table->unique(['tenant_id', 'client_key']);
|
||||
$table->unique(['tenant_id', 'code']);
|
||||
$table->unique(['id', 'tenant_id']);
|
||||
});
|
||||
if (DB::getDriverName() === 'pgsql') {
|
||||
DB::unprepared("CREATE FUNCTION sgc_preserve_business_client() RETURNS trigger LANGUAGE plpgsql AS \$\$ BEGIN
|
||||
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Preservar identidade do cliente'; END IF;
|
||||
IF ROW(NEW.tenant_id,NEW.client_key,NEW.created_by,NEW.creation_hash,NEW.created_at)
|
||||
IS DISTINCT FROM ROW(OLD.tenant_id,OLD.client_key,OLD.created_by,OLD.creation_hash,OLD.created_at)
|
||||
OR NEW.version <> OLD.version + 1 THEN RAISE EXCEPTION 'Preservar identidade e versao do cliente'; END IF;
|
||||
RETURN NEW; END \$\$;
|
||||
CREATE TRIGGER sgc_preserve_business_client BEFORE UPDATE OR DELETE ON business_clients FOR EACH ROW EXECUTE FUNCTION sgc_preserve_business_client();");
|
||||
} elseif (DB::getDriverName() === 'sqlite') {
|
||||
DB::unprepared("CREATE TRIGGER sgc_preserve_business_client_update BEFORE UPDATE ON business_clients WHEN
|
||||
NEW.tenant_id IS NOT OLD.tenant_id OR NEW.client_key IS NOT OLD.client_key OR NEW.created_by IS NOT OLD.created_by
|
||||
OR NEW.creation_hash IS NOT OLD.creation_hash OR NEW.created_at IS NOT OLD.created_at OR NEW.version <> OLD.version + 1
|
||||
BEGIN SELECT RAISE(ABORT, 'Preservar identidade e versao do cliente'); END;
|
||||
CREATE TRIGGER sgc_preserve_business_client_delete BEFORE DELETE ON business_clients
|
||||
BEGIN SELECT RAISE(ABORT, 'Preservar identidade do cliente'); END;");
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
throw new LogicException('Preservar clientes e identidades congeladas nos processos.');
|
||||
}
|
||||
};
|
||||
@@ -1,5 +1,21 @@
|
||||
# Desenvolvimento do SGC
|
||||
|
||||
30/11/2026 — integrada e instalada nos dois destinos a entrega `compras-e4e3196d1877e804`: clientes próprios, contratação para clientes com Direcção da prestadora e redireccionamento das antigas consultas ilustrativas para o produto real. Provas e incidente corrigido descritos em `orientacoes-continuidade.md`;72/1882SQLite,72/1882PG,10frontend,17/94navegação+4/8redireccionamentos, tipos/lint/PHPStan/build aprovados. Dois ciclos HTTP sintéticos públicos completos até confirmação documental, sem contrato real/admissão/RH. Não repetir fixtures nem confundir esta entrega com conclusão de vendas autónomas, SMTP local ou do pedido integral.
|
||||
|
||||
29/11/2026 — reposição pública da referência8005 expressamente solicitada e executada: política com quatro contextos e nove perfis associados pelos serviços nativos, sem mudar competências ou145tabelas protegidas. Edge autenticado mostrou o mesmo painel, selecçãoComprasinternas, menus e duas requisições. Activar contextos ocultava arquivos de auditoria anteriores classificados `legacy`; corrigido com recibo explícito por empresa/ID/hash, mesma autoria e competências actuais, sem modificar ou regenerar arquivos. Regressão recusa pin errado, outro autor, outra área e competência revogada; três ZIPs públicos descarregados com hashes originais, três recusas não autorizadas. Também preservados triggers SQLite ao reconstruir a tabela vazia de requisições. SQLite44/482+13/525 ePG57/1007 passaram, base/role isoladas removidas; PHPStan0/Pint,945fontes/185assets/três componentes conferidos. Oito rótulos sintéticos corrigidos sem alteração de autenticação. Entrega `compras-47dfeee7485db877`; prova `compras-pilot-reference-restored.json`. Opções para terceiros mantêm os limites do piloto, sem as declarar concluídas.
|
||||
|
||||
29/11/2026 — falha de percurso reportada pelo proprietário: a apresentação e as listas públicas vazias deram a impressão de desaparecimento das funcionalidades. Corrigida entrada principal para login/painel, mantendo a apresentação opcional em `/apresentacao` e os caminhos públicos anteriores com aviso e botões explícitos de acesso. Entrega instalada `compras-e5c8c140738b6e1e`, quatro fontes alteradas, sem mudanças em dados/configuração/permissões. Conferidos 14 destinos autenticados com componentes e conteúdo efectivo, além da revisão nativa da entrada e botões. Regressão36/700 e48frontend, tipos/lint/Pint/build/185assets aprovados. Salvaguarda anterior em `/var/backups/compras-presentation-20261129/access-fix`; provas `compras-access-fix.json` e `compras-workspace-visibility.json`.
|
||||
|
||||
## 29/11/2026 — uma entrega integrada de Compras
|
||||
|
||||
Referência instalada: `compras-a2711a98b34fceb3`, https://compras.tempo.co.mz. A página inicial apresenta as seis áreas e conduz ao acesso normal; os percursos públicos existentes foram preservados. Corrigido o middleware que ocultava a página inicial quando a consulta pública estava activa: regressão de 18 testes/650 asserções aprovada. O verificador da entrega passou nove testes, incluindo adulteração, caminhos inválidos, componentes incompletos e diferenças LF/CRLF. A compilação, os 185 assets servidos e os 945 ficheiros de fonte instalados coincidem com o manifesto; três componentes aprovados conferidos sem dependência de execução do SGF.
|
||||
|
||||
Auditoria usa armazenamento privado próprio de operação; sete ficheiros antigos copiados com hashes idênticos e origem conservada, sem migração de registos. Nova exportação nativa com 136 membros conferida após a mudança. Formalização de Pessoas instalada com autoridade da Direcção e dossier v2, comprovativo privado e sem admissão automática. Serviço Linux único inicia/reinicia e conserva as regras empresariais existentes. Actualizador preserva o contexto seleccionado e verifica a mesma entrega antes da activação. Código, configuração e arquivos têm salvaguarda privada para reversão.
|
||||
|
||||
Piloto/QA são ambientes de trabalho e verificação do mesmo produto. A empresa sintética autorizada permite apresentar a aplicação instalada; não cria outra edição. Os estados históricos abaixo são substituídos apenas pelas constatações correntes registadas na matriz existente. JUE/bancos externos, reinício integral do servidor e aceitação empresarial real não estão certificados por estes ensaios.
|
||||
|
||||
29/11/2026 — ligação SSH por chave confirmada e interface pública reconciliada por consulta: manifesto c3ac2c64 e 185 ficheiros remotos correspondem à candidata autorizada. Os 185 assets passaram também por HTTPS; entrada pública actual e isolamento financeiro do anónimo preservados. Nenhuma reinstalação ou escrita remota foi necessária. Provas `analytics-print-remote-readonly.json`, `analytics-print-publication-http.json` e estado actualizado em `analytics-print-publication.json`. Pendência pública anterior superada; aplicação integral permanece aberta.
|
||||
|
||||
29/11/2026 — análise de despesa demonstrada emQA autónoma com login normal: pagamento/afectação preparados pelos serviços nativos; soma39MZN recusada conservando valores,15MZN Material+25MZN Serviços gravados por Finanças como versão1. Relatório conserva40MZN e ambas categorias;153tabelas protegidas intactas, uma imputação/uma auditoria, sem alterar fontes financeiras.390×526/100% legível em formulário/tabelas; impressão de seis folhas mantém título/explicação/categorias juntos na página3 após correcção de quebra. Contexto da afectação passa a Finanças apenas com entrada já autorizada, contagem singular corrigida.37testes/7ficheiros, tipos/lint/formatação/build aprovados. Manifestoc3ac2c64/185assets publicado no piloto por autorização específica, manifesto/chunks anteriores salvaguardados;24capacidades/56GETs e185respostas/hash aprovados, settings/env intactos. Publicação pública autorizada mas NÃO executada: domínio serve instalação distinta, entrada anterior e404para novosassets. Corrigida a suposição anterior de actualização partilhada automática; ligação administrativa existente solicitada, sem repetir tentativasSSH anteriores sem mudança de condição. Provas `procurement-analytics-qa.json`, `analytics-print-publication[-http].json`. Base/roleQA removidos, três separadores anteriores preservados. Aplicação integral continua aberta.
|
||||
|
||||
29/11/2026 — revisão nativa de `/ordens/1/imprimir` e `/recepcoes/1/imprimir` no piloto: ordem antiga OC-TEST-wKzfEhxT9Y conserva aviso de original incompleto e totais10000+1600=11600MZN; recepçãoREC-2026-000001 conserva recebido/aceite1,000 e rejeitado0,000, origem e referências disponíveis. Cada pré-visualização coube numa folha, sem cortes observados; ambas canceladas, sem impressão física.390×526/100% confirmou totais da ordem e tabela/referências da recepção; cabeçalhos da tabela quebram nas colunas. Ferramentas/separador próprios fechados e três separadores anteriores preservados. Sem gravações de negócio; conferência PostgreSQL só leitura conserva149tabelas e apenas a fila técnica avança pela tarefa autorizada. Prova `product-review-20261122.json#native_pilot_order_receipt_print_20261129`. Não representa impressão de documentos com anexos, estornos ou confirmação integral dos restantes relatórios.
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# Integração integral de Compras no SGF — execução de 30/11/2026
|
||||
|
||||
## Âmbito autorizado e limites
|
||||
|
||||
O proprietário autorizou a integração integral, incluindo aquisição de mercadorias para venda, reutilizando a facturação e a contabilidade do SGF, preservando o SGC autónomo. Não autorizou novas demonstrações ou publicação. Os roteiros de contratação de pessoas para terceiros permanecem exclusivos do SGC. Não activar integrações remotas, instalar schema, conceder acessos ou publicar por arrasto.
|
||||
|
||||
O circuito pretendido é: necessidade → requisição/reserva/aprovação → fornecedores/cotações/comparação/adjudicação → ordem → recepção/stock → factura de fornecedor/obrigação → mercadorias para venda → factura de cliente → entrega/saída de stock → recebível/recebimento/afectação → contabilidade e relatórios. Manter uma autoridade por documento, movimento, dívida e lançamento. Não copiar os dados de desenvolvimento para uma instalação empresarial.
|
||||
|
||||
## Resultado deste incremento: preparação de transferência corrigida
|
||||
|
||||
### Continuação: mercadorias e política de valorização por empresa
|
||||
|
||||
Actualização de 30/11: a escolha global do método deixou de estar pendente. O proprietário determinou **parametrização por empresa**. Foram preparados FIFO e custo médio ponderado, sem opção implícita, com proposta, revisão independente, versão e histórico. Uma alteração não recalcula movimentos históricos. A configuração não cria outro livro físico ou financeiro.
|
||||
|
||||
No código SGF, a facturação multilinha foi ampliada com referências tipadas ao catálogo físico autorizado. Mantém os escritores existentes de factura, numeração, PDF, recebível e lançamento de venda. As mercadorias não são cadastradas como serviços fictícios. A entrega usa o StockWorkflow existente e liga cada saída à linha e versão exactas da factura, com saldo por entregar e recuperação pela mesma chave. Corrigida a referência das entregas parciais para não colidir entre entregas distintas.
|
||||
|
||||
**Prova actual:** 41 verificações no livro de regressão preexistente, com catálogo nativo real e alterações temporárias integralmente repostas. Factura sintética 232 MZN (base 200 e regra artificial 16%), recebível e origem de lançamento nativos; saída parcial real; repetição; armazém indevido; acesso directo inexistente; revogação inclusive na repetição; falha depois do movimento físico e recuperação atómica. Schema, função anterior, referências de acesso e linhas de negócio do ensaio foram revertidos. Sequências PostgreSQL podem avançar durante ensaios revertidos. Isto não equivale a recuperação de uma instalação operacional a partir de backups.
|
||||
|
||||
Passaram também 26 verificações do percurso anterior de serviços, 24 verificações simuladas da interface multilinha, oito testes/24 asserções da política e nove testes/25 asserções do cálculo exacto FIFO/CMP. A compilação privada anterior deste incremento permanece válida para os componentes React; os novos controladores JavaScript autónomos têm validação separada. Sem revisão visual ou nova prova de concorrência entre processos.
|
||||
|
||||
O cálculo comum `packages/purchasing/src/StockCosting.php` está preparado e testado, **ainda sem ligação operacional à emissão do lançamento de custo**. Exige abertura/custos qualificados; fracções de cêntimo são assinaladas para parametrização, sem arredondamento inventado. O SGF bloqueia a utilização da taxa fixa QA nos novos movimentos de venda. Não apresentar este bloqueio como valorização contabilística concluída.
|
||||
|
||||
Na 8085 foi feita apenas leitura dos acessos: faltam exactamente três concessões `stock.view`, aos IDs 8, 9 e 13, no contexto 1/2/2, e correspondências de leitura restritas. Nenhuma concessão persistente foi executada; nenhum GRANT/REVOKE SQL, nova conta, demonstração, instalação, migração persistente ou publicação. Detalhes de acesso, recuperação e limitações: `C:/laragon/www/sgf-tempo/docs/SGF_MERCHANDISE_INTEGRATION_20261130.md`.
|
||||
|
||||
As secções de preparação de transferência abaixo conservam a evidência do primeiro incremento. A candidata 8d1af50791bd4878 **não contém** o novo circuito e não foi activada.
|
||||
|
||||
Não é a integração integral concluída nem uma versão pronta para instalar. A preparação existente falhava antes de gerar a candidata: BootOverlay exigia a lista histórica de apenas dois prefixos, embora o SGF já contivesse as capacidades posteriores; o gerador frontend acrescentava uma segunda declaração requisitions, impedindo a compilação.
|
||||
|
||||
Corrigidos ambos os pontos, conservando os prefixos, ligações, condições de capacidade/permissão e estados vazios existentes. A preparação é repetível e recusa listas executáveis/ambíguas ou condições desconhecidas; não adopta silenciosamente fontes arbitrárias. As fontes efectivas do SGF foram somente lidas. Não foram copiados ou alterados os ficheiros financeiros em curso nos dois produtos.
|
||||
|
||||
Ficheiros: integrations/sgf/operational/BootOverlay.php; scripts/sgf-admin-ui-build.mjs; scripts/lib/sgf-purchasing-home-overlay.mjs. Regressões: tests/Unit/SgfBootOverlayTest.php e tests/scripts/sgf-purchasing-home-overlay.test.mjs. O ensaio scripts/sgf-integration-recovery-check.php reutiliza CodeDeployment, sem um segundo mecanismo de instalação.
|
||||
|
||||
## Candidata de compatibilidade, não instalada
|
||||
|
||||
- OPERATIONAL-CANDIDATE-8d1af50791bd4878.
|
||||
- ZIP privado: storage/app/private/candidate-archives/OPERATIONAL-CANDIDATE-8d1af50791bd4878.zip.
|
||||
- SHA-256 ZIP: 200d0ea4eda0d6871f65fc37ff793fed2185aba045a8e605271b94af37b233fd.
|
||||
- SHA-256 manifesto: 23d98de207cda7397180c6e4dc5946f22739b2b8f4be55a43fc254abf1db08db.
|
||||
|
||||
Esta candidata é resultado do preparador anterior reconciliado; a sua existência não certifica todos os percursos actuais nem acrescenta o circuito de vendas. Não aplicar como se fosse a integração total. A candidata técnica preliminar 05daee4b0bf079c9 foi conservada, não activada; a identificação acima sucede-lhe após formatação e verificação final.
|
||||
|
||||
## Verificação executada
|
||||
|
||||
- Cinco testes PHP / oito asserções e três testes Node aprovados: host histórico, navegação ampliada, repetição sem duplicação, manutenção das guardas actuais e recusa de fontes desconhecidas.
|
||||
- Compilação privada do frontend SGF aprovada, usando dependências existentes; nenhum npm install/update, watcher ou build activo substituído.
|
||||
- Quarenta verificações de preparação/aplicação/repetição/reversão em cópias exclusivas de ficheiros: bytes anteriores restaurados e fontes/ponteiro reais do SGF preservados. Sem ligação a bases, serviços, roles, concessões, migrações ou novas demonstrações. Prova: docs/proofs/sgf-total-integration-recovery-20261130.json.
|
||||
- Pint dirigido aprovado. Não se repetiram os percursos financeiros, emissões ou operações das demonstrações.
|
||||
|
||||
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
|
||||
|
||||
| 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. |
|
||||
| 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 de mercadoria testado no percurso nativo | Reconhecimento ligado; recebimento/afectação e correcções de mercadorias ainda sem nova aceitação integrada. |
|
||||
| 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 | Lançamento de venda nativo qualificado; política empresarial FIFO/CMP e cálculo exacto preparados | Custo da saída ainda não ligado ao escritor financeiro. Abertura, custos, arredondamento e correspondências exigem configuração explícita; não presumir zero. |
|
||||
| Equivalência global e entrega | 41 verificações desta extensão e 26 regressões dos serviços | Integração total permanece parcial; não há aceitação global, pacote total instalado ou 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.
|
||||
|
||||
## Decisões e acessos
|
||||
|
||||
O método será parametrizável por empresa, conforme decisão do proprietário. Não é necessária outra escolha global. A disponibilidade de um método no produto não configura uma empresa nem autoriza retroavaliar o seu stock. A proposta concreta de três direitos de leitura e das suas correspondências está no relatório SGF; continua sem aplicação persistente.
|
||||
|
||||
Estado: parcialmente implementado. SGC autónomo e trabalho paralelo preservados. Faltam ligação contabilística do custo, aceitação dos restantes percursos afectados, empacotamento e recuperação completa antes de qualquer implantação. Não há instalação/publicação nem activação operacional autorizada por esta entrega.
|
||||
@@ -1,5 +1,37 @@
|
||||
# Matriz reconciliada do SGC — 03/11/2026
|
||||
|
||||
30/11/2026 — estado corrente substitui as pendências históricas de contratação para terceiros abaixo: `compras-e4e3196d1877e804` disponível local/público, cadastro de clientes próprio, versão/identidade preservada e decisão final/formalização pela Direcção da prestadora. Dois percursos HTTP públicos reais com dados sintéticos (serviçoPES2/trabalhadorPES3) chegaram ao contrato formalizado, com documento descarregado/hash conferido e recusa no contexto interno. SQLite e PostgreSQL72/1882 cada, frontend10, tipos/lint/PHPStan/build; instalação local com restauro150/preservação143, pública com prova de recuperação148. Ver `compras-client-hiring-http.json`, `compras-client-registry-isolation.json` e relato do incidente/correcção em `orientacoes-continuidade.md`. Endereços ilustrativos antigos agora redireccionam para operações reais;17/94+4/8testes. Vendas autónomas, SMTP local e validações finais ainda abertas; esta entrada não encerra a matriz inteira.
|
||||
|
||||
## Referência do piloto reposta no público — 29/11/2026
|
||||
|
||||
Pedido expresso «eu quero o que esta no piloto» executado na empresa sintética já autorizada, entrega `compras-47dfeee7485db877`. Política e associações de contexto configuradas pelos comandos nativos: mesmo painel `work-context`, quatro escolhas e mesmos limites operacionais do piloto. Nove perfis mantêm as competências;145tabelas não relacionadas conservadas na transacção. A diferença de painel referida nos parágrafos históricos seguintes está resolvida.24módulos activos e336rotas funcionais coincidem;185assets/945fontes/três componentes conferidos.
|
||||
|
||||
Edge autenticado por login normal mostrou as quatro opções; Compras internas abriu os menus e a lista com duas requisições. Sessão pública deixada nessa área, separadores locais preservados. Verificações HTTP de selecção, cruzamento indevido e opções não operacionais passaram. Os três arquivos de auditoria anteriores continuam visíveis/descarregáveis, por recibo delimitado de ID/hash, mantendo autor/empresa/competências actuais e bytes/registos originais. Corrigida a preservação dos triggers SQLite numa reconstrução de schema vazio; sem migração nova em PostgreSQL. SQLite44/482+13/525, PostgreSQL57/1007, PHPStan0/Pint e reconciliação financeira passaram. Oito rótulos sintéticos com caracteres corrompidos corrigidos pelos nomes já existentes dos titulares, sem alterar permissões ou autenticação. Prova corrente `compras-pilot-reference-restored.json`.
|
||||
|
||||
Venda para terceiros e contratações para terceiros mantêm exactamente a situação do piloto: opções disponíveis, percurso operacional ainda não implementado. A reposição do piloto não declara esses percursos nem todos os requisitos da aplicação concluídos.
|
||||
|
||||
29/11/2026 — comparação directa solicitada pelo proprietário entre o piloto8005 e a instalação pública:24capacidades standalone activas em ambos,336pares rota/método funcionais idênticos e nenhuma diferença de controladores. Isso comprova presença/configuração dos módulos, não uma repetição integral de todos os percursos. Diferença real ainda aberta: política de contexto do piloto tem quatro opções; a empresa sintética pública ficou sem política e mostra a visão geral antiga. Venda para terceiros e contratações para terceiros têm `operational=false` no mesmo código de ambos os ambientes: a presença dos botões no piloto não demonstra implementação desses percursos. Não declarar equivalência integral ou apresentar estas opções como concluídas. Prova `compras-local-public-availability.json`; comparação só de leitura, sem novas concessões.
|
||||
|
||||
29/11/2026 — correcção de acesso instalada como `compras-e5c8c140738b6e1e`, sucedendo à consolidação abaixo: endereço principal abre login/painel conforme a sessão; apresentação conservada em `/apresentacao`, consulta pública assinalada e com botões de entrada. O diagnóstico de 14 destinos autenticados confirmou componentes, colecções com registos e acções por perfil, sem alterar dados ou direitos. Backend36/700, frontend48, tipos/lint/Pint/build e185assets passaram. Provas `compras-access-fix.json` e `compras-workspace-visibility.json`. A leitura anónima vazia não constitui perda de funcionalidades ou prova de que a conta do proprietário tem acesso: usar a identidade/contexto equivalente e não substituir essa conferência por HTTP200.
|
||||
|
||||
## Estado corrente — produto único instalado, 29/11/2026
|
||||
|
||||
A entrega de referência é `compras-a2711a98b34fceb3`, em https://compras.tempo.co.mz, com entrada de trabalho em `/login`. Código, interface e componentes são conferidos pelo mesmo `compras-release.json`: 945 ficheiros de fonte, 185 assets e três componentes aprovados. Piloto e QA conservam dados e provas anteriores como ambientes de verificação; não constituem edições comerciais alternativas. A empresa de exemplo é parametrização com dados sintéticos do mesmo produto.
|
||||
|
||||
| Área | Estado demonstrado na instalação pública |
|
||||
| --- | --- |
|
||||
| Compras e relações entre módulos | Requisição, aprovação, três fornecedores/cotações, adjudicação, emissão, recepção, stock e factura percorridos pelos serviços nativos; consultas HTTP autenticadas por dez perfis, 32 destinos, aprovadas. Projectos/imobilizado e ordens operacionais mantêm cadastro próprio. |
|
||||
| Finanças | Reconhecimento e diário comum equilibrados: factura 1.000 MZN, pagamento sintético confirmado 400 MZN, saldo 600 MZN; imputação explícita por Finanças de 400 MZN à categoria. Sem duplicação ou execução bancária externa. |
|
||||
| Auditoria privada | Autoridade própria e quatro famílias aprovadas, ZIP de 136 membros conferido byte a byte; descarga sem competência recusada. Novo arquivo criado no armazenamento privado operacional, fora de QA; arquivos anteriores preservados. Bancos completos e Pessoas permanecem separados. |
|
||||
| Pessoas | Registo do contrato assinado confirmado pela Direcção; comprovativo privado, controlo de acesso e hash demonstrados. O dossier formalizado usa contrato v2; não representa admissão ou envio a RH. |
|
||||
| Importações/JUE/bancos | Dossiê e suporte bancário documentais operacionais, cinco PDFs sintéticos consultáveis por acesso normal e integridade conferida. Não há integração externa JUE/bancária demonstrada: depende da identificação do serviço e respectivo contrato/acesso de testes. |
|
||||
| Operação | Um serviço/timer Linux `compras-operations`, independente da sessão Windows; arranque/reinício passaram. Verifica a entrega antes de processar prazos/reposição. Reinício integral do servidor e capacidade máxima não foram ensaiados. |
|
||||
| Publicação | Actualizador conserva a configuração/storage da instalação seleccionada e recusa fonte, compilação ou componentes incompatíveis. Não executa nova publicação de um Git remoto antigo sem manifesto integrado. Salvaguarda privada e recuperação anterior preservadas. |
|
||||
|
||||
Estas constatações substituem as pendências históricas de instalação pública, parametrização sintética, auditoria privada apenas em QA, formalização apenas em minuta e ausência de serviço sem sessão. Os registos abaixo conservam o contexto da sua data; não reabrem essas pendências. A aceitação integral de todos os requisitos não resulta apenas desta consolidação. Provas: `compras-release-http.json`, `compras-release-profiles.json`, `compras-release-evidence.json` e `compras-release-consolidation.json` em `docs/proofs`.
|
||||
|
||||
29/11/2026 — pendência pública da interface superada: acesso SSH por chave instalada pelo proprietário confirmado; manifesto autorizado c3ac2c64 e 185 ficheiros exactos encontrados na instalação remota. Conferência HTTPS dos 185 assets e da entrada pública aprovada, com identidade anónima e navegação financeira privada preservadas. Sem escrita remota nesta verificação. Provas `analytics-print-remote-readonly.json` e `analytics-print-publication-http.json`; estado actualizado em `analytics-print-publication.json`. Não encerra a aplicação integral nem a aceitação empresarial.
|
||||
|
||||
29/11/2026 — análise de despesa demonstrada emQA autónoma com login normal: pagamento/afectação preparados pelos serviços nativos; soma39MZN recusada conservando valores,15MZN Material+25MZN Serviços gravados por Finanças como versão1. Relatório conserva40MZN e ambas categorias;153tabelas protegidas intactas, uma imputação/uma auditoria, sem alterar fontes financeiras.390×526/100% legível em formulário/tabelas; impressão de seis folhas mantém título/explicação/categorias juntos na página3 após correcção de quebra. Contexto da afectação passa a Finanças apenas com entrada já autorizada, contagem singular corrigida.37testes/7ficheiros, tipos/lint/formatação/build aprovados. Manifestoc3ac2c64/185assets publicado no piloto por autorização específica, manifesto/chunks anteriores salvaguardados;24capacidades/56GETs e185respostas/hash aprovados, settings/env intactos. Publicação pública autorizada mas NÃO executada: domínio serve instalação distinta, entrada anterior e404para novosassets. Corrigida a suposição anterior de actualização partilhada automática; ligação administrativa existente solicitada, sem repetir tentativasSSH anteriores sem mudança de condição. Provas `procurement-analytics-qa.json`, `analytics-print-publication[-http].json`. Base/roleQA removidos, três separadores anteriores preservados. Aplicação integral continua aberta.
|
||||
|
||||
29/11/2026 — revisão nativa de `/ordens/1/imprimir` e `/recepcoes/1/imprimir` no piloto: ordem antiga OC-TEST-wKzfEhxT9Y conserva aviso de original incompleto e totais10000+1600=11600MZN; recepçãoREC-2026-000001 conserva recebido/aceite1,000 e rejeitado0,000, origem e referências disponíveis. Cada pré-visualização coube numa folha, sem cortes observados; ambas canceladas, sem impressão física.390×526/100% confirmou totais da ordem e tabela/referências da recepção; cabeçalhos da tabela quebram nas colunas. Ferramentas/separador próprios fechados e três separadores anteriores preservados. Sem gravações de negócio; conferência PostgreSQL só leitura conserva149tabelas e apenas a fila técnica avança pela tarefa autorizada. Prova `product-review-20261122.json#native_pilot_order_receipt_print_20261129`. Não representa impressão de documentos com anexos, estornos ou confirmação integral dos restantes relatórios.
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
# Operação da reposição periódica do SGC
|
||||
|
||||
29/11/2026 — instalação seleccionada `compras-47dfeee7485db877`, painel do piloto reposto com os contextos explícitos da empresa de exemplo. O mesmo `compras-operations.service` voltou a executar com saída0 e timer activo após a configuração. Salvaguarda corrente em `/var/backups/compras-presentation-20261129/pilot-aligned-current`: `.env` privado, dump legível e pacote integral; anteriores de contexto/código em `context-alignment` e `context-audit-preservation`. Não remover o recibo `COMPRAS_AUDIT_LEGACY_TRANSITIONS` durante actualizações: mantém acessíveis só os três arquivos históricos exactos, com as verificações de autoridade intactas. O diagnóstico financeiro CLI usa sessão de contexto em memória e transacção PostgreSQL de leitura; não é um atalho de autenticação publicado. A correcção do schema SQLite destina-se a reconstruções futuras com tabela vazia e não executou nova migração em PostgreSQL. Prova corrente `compras-pilot-reference-restored.json`.
|
||||
|
||||
29/11/2026 — referência actual `compras-e5c8c140738b6e1e`, após correcção do percurso de acesso. Mesmo serviço/timer, configuração, base e componentes; quatro fontes e assets actualizados com cópia anterior em `/var/backups/compras-presentation-20261129/access-fix`. O verificador instalado aprovou945fontes,185assets e três componentes antes e depois da publicação. A reversão deste delta repõe as quatro fontes, manifestos e identidade anteriores; não exige restauro de dados. Prova `compras-access-fix.json`.
|
||||
|
||||
## Instalação pública corrente — 29/11/2026
|
||||
|
||||
`compras-operations.timer` está activo e habilitado no servidor da instalação seleccionada por `/var/www/compras-deploy/current`. O serviço único executa `sgc:approval-deadlines-tick` e `sgc:replenishment-tick` como `www-data`, após conferir fonte, assets e componentes com `scripts/verify-compras-release.php --installed`. O timer anterior de apresentação foi desabilitado; arranque e reinício do serviço terminaram com estado zero. Não depende de sessão Windows; não confundir este ensaio com reinício integral do servidor, que não foi realizado.
|
||||
|
||||
O actualizador `/var/www/deploy/compras-tempo-deploy.sh` conserva `.env` e storage da instalação seleccionada e recusa entregas sem manifesto compatível. Salvaguardas privadas da consolidação em `/var/backups/compras-presentation-20261129/consolidation`, incluindo publicador anterior, ficheiros alterados e configuração. O delta corrente em `current/` inclui código, storage, dump, unidades e publicador; não expor esses arquivos. A prova anterior de restauro completo permanece válida para o schema sem alterações desta consolidação. As instruções Windows seguintes conservam o seu âmbito interno e histórico.
|
||||
|
||||
29/11/2026 — reposição recorrente do piloto instalada/activa sob a autorização dos componentes necessários: `Compras-Pilot-Replenishment`, utilizador actual com sessão iniciada, privilégios limitados, php-win, minuto técnico/logon, não sobreposição e limite60s. Reutiliza exclusivamente `sgc:replenishment-tick`, exclusão nativa/recuperação durável/heartbeat da instalação; sem renovar regras ou criar parâmetros. Passagens automáticas e solicitada terminaram com0;149tabelas intactas, apenas acompanhamento de `replenishment_work` alterado. Nenhuma nova requisição, decisão, política, concessão ou movimento. Salvaguarda privada restaurada com150tabelas idênticas e base/role temporárias removidas. Diagnóstico integrado actual passou em PostgreSQL só leitura.19testes/132asserções e regressão XML1/5, PHPStan0/Pint aprovados. Correcção própria: exportação nativa omite defaults limitados e resolve SID em alias; comparação conserva identidade/privilégios/frequência sem re-registar tarefa. Tentativa inicial recusada por pin antes do arranque da aplicação; provas distinguem essa recusa das passagens finais aprovadas. Provas `replenishment-task-installation.json`, `replenishment-task-definition-fix.json`, `replenishment-task-recovery.json` e `pilot-operations-current.json`. Conferência actual de inventário conserva150tabelas durante a consulta, sem exigir que a fila operacional permaneça eternamente no estado da instalação; prova de instalação original preservada, nova prova `inventory-conversion-pilot-current-check.json`. Não repetir instalação. Reinício/logoff real e serviço de produção sem sessão continuam separados; aplicação integral continua aberta.
|
||||
|
||||
## Estado desta entrega
|
||||
|
||||
@@ -1,5 +1,43 @@
|
||||
# Continuidade do desenvolvimento do SGC
|
||||
|
||||
30/11/2026 — trabalho seguinte de vendas autónomas em curso, ainda não instalado/activado: extensão do núcleo canónico `C:/laragon/www/sgf-tempo/packages/general-ledger` com `ConfiguredSales.php`, `ConfiguredSalesSchema.php`, `CustomerInvoiceMath.php`, `ReceivablesSchema.php`, `Receivables.php`; bootstrap/PayableJournal/LedgerConfiguration apenas com a ligação tipada/configuração nova. Comparados com o runtime804833: só essas alterações desta tarefa, sem transportar mudanças alheias. `--configured-sales-ledger-only` em `requisition-ledger-qa-check.mjs` verifica `ConfiguredSalesLedgerTest` e `CustomerReceivablesTest` numa base/role/cluster descartáveis; última passagem11/60, PHPStan dos cinco ficheiros novos0. Novas consultas de privacidade armazém/recebimentos adicionadas depois dessa passagem; executar antes de empacotar. Emissão→recebimento→imputação4000→estorno→três lançamentos pelo escritor existente demonstrados, com livro fornecedor anterior preservado; nenhuma base SGF/pública/local activa recebeu este schema financeiro. Não apresentar o núcleo isolado como circuito de vendas concluído. Próximo: adaptador/controlo de contexto, formulários reais, entrega física pelo StockWorkflow/IssueMovementWriter existentes, regras contabilísticas no UI comum, pacote derivado do804833 apenas com o delta aprovado e actualização preservadora do mesmo produto. SMTP local continua pendente da configuração privada.
|
||||
|
||||
30/11/2026 — entrega corrente única `compras-e4e3196d1877e804`, instalada localmente8005 e em compras.tempo.co.mz:952fontes/186assets/três componentes preservados. Cadastro próprio de clientes e contratação para terceiros agora operacionais, com identidade congelada e decisão/contrato pela Direcção da prestadora. HTTP público autenticado concluiu serviçoPES2 e trabalhadorPES3 até contrato formalizado, documentos com hashes conferidos e acesso interno recusado; pessoas/contratos são inteiramente sintéticos, sem admissão/envioRH. Não repetir esses comandos: estado privado de continuação em `client-hiring-native-progress.private.json`. SQLite72/1882 e PostgreSQL72/1882,10testes frontend, tipos/PHPStan/lint/build passaram. Local: restauro150tabelas/preservação143; contexto e página para clientes observados no Edge. Os endereços antigos `/consulta` e `/proposta/*` encaminham para funcionalidades reais, mantendo autenticação;17/94+4/8testes. Provas `compras-client-hiring-http.json`, `compras-local-client-hiring.json`, `compras-public-client-hiring-installation.json`.
|
||||
|
||||
Incidente corrigido nesta entrega: auxiliar novo herdou `name=pgsql` ao compor a ligação de restauro, criando a tabela vazia `business_clients` no destino activo em vez da cópia; nenhum cliente nem registo anterior alterado. A reposição de `.env` também perdeu leitura pelo grupo da aplicação, causando HTTP500 temporário; repostos640/root:www-data e cache, HTTP200. Corrigido o auxiliar para remover o nome herdado e conferir nome/base antes de escrever. Regressão executável `prove-client-registry-recovery.py` demonstrou migração apenas na cópia inicialmente sem tabela, registo de migração correcto,148tabelas anteriores preservadas e destino activo intacto. Estrutura activa comparada exactamente com a migração (SHA4187827c43b41406db7b959f093cc8b2761b04406b268690718e025d3f2e1474); registada pelo repositório nativo sem apagar/recriar tabela. Prova `compras-client-registry-isolation.json`, salvaguardas privadas `client-hiring` e `client-hiring-installed`. Instalação final passou verificação integral e HTTP de quatro contextos,14consultas por perfil e três arquivos originais de auditoria.
|
||||
|
||||
Pedido global continua aberto: vendas autónomas no núcleo comum ainda por implementar; não activar `LedgerSales`/`SalesSchema`SIM, que fixam contasQA e recusam livros povoados. SMTP local continua dependente da configuração privada solicitada; email público já entregue a nala. Conferência visual observou atalho «Nova requisição» no contextoPessoas: ajustar apresentação contextual na próxima entrega, sem retirar permissões. Manter pendências de validação móvel/impressão/operação que ainda não tenham prova suficiente. Não anunciar a aplicação inteira concluída por esta entrega.
|
||||
|
||||
29/11/2026 — continuação actual expressamente solicitada: uniformizar local/público, emails, validação e dois circuitos para terceiros. Decisões recebidas: remetente/teste `nala@tempo.co.mz`; vendas também em Compras autónomo com núcleo comum; decisão e contrato de contratações para clientes pela Direcção da prestadora. Ver decisão nova em `AGENTS.tecnico.md`. Email público configurado no MTA existente e uma mensagem localizada na caixa autorizada; prova `compras-public-mail.json`. SMTP local sem autenticação configurada: perguntado o caminho da configuração privada, sem pedir passwords no chat. Uniformização local inicial aplicada após restauro idêntico150tabelas e preservação143tabelas de negócio: geografia operacional apenas em schema, formalização de Pessoas e mesmo build185assets, sem mudar configurações/permissões; prova `compras-local-unification.json`. O âmbito continua aberto, não confundir estas etapas com conclusão do pedido inteiro.
|
||||
|
||||
## Regra permanente de entrega — decisão do proprietário, 29/11/2026
|
||||
|
||||
Uma única aplicação Compras: o conteúdo desenvolvido deve ser integrado, apresentado e disponibilizado localmente e no público, com a mesma entrega funcional. Não criar aplicações ou edições paralelas nem substituir operações incompletas por simulações apresentadas como produto. Só concluir uma funcionalidade após integrar e conferir os seus percursos e relações nos dois destinos. Reconciliar código, componentes, manifestos, navegação e configuração, preservando os dados e acessos existentes. A empresa de exemplo aprovada permanece configuração do mesmo produto. Aplicar a decisão permanente registada em `AGENTS.md` e manter as pendências reais na matriz existente; o registo da decisão não as encerra.
|
||||
|
||||
## Estado corrente: mesmo painel e módulos do piloto — 29/11/2026
|
||||
|
||||
Usar `compras-47dfeee7485db877` em https://compras.tempo.co.mz/dashboard. A selecção de contextos já foi reposta por pedido expresso do proprietário: quatro opções, perfis associados e competências preservadas; não voltar a pedir esta autorização nem apresentar a antiga políticaNULL como pendência actual. A empresa sintética permanece a escolhida para apresentação. A sessão Edge pública foi autenticada e deixada em Compras internas, com duas requisições visíveis; os separadores locais permanecem intactos.
|
||||
|
||||
Prova corrente `compras-pilot-reference-restored.json`, incluindo57testes PG/1007asserções, consulta nativa e verificações de recusa. Preservar `COMPRAS_AUDIT_LEGACY_TRANSITIONS`: recibo privado dos três arquivos exactos anteriores, não uma permissão geral para conteúdo legado. Autor original, empresa, famílias actuais e hashes continuam obrigatórios; não reescrever arquivos ou os seus contextos históricos. Os rótulos sintéticos foram corrigidos por comandos nativos, sem alterar passwords/emails. As limitações das duas opções para terceiros são as mesmas do piloto e continuam abertas.
|
||||
|
||||
29/11/2026 — disponibilidade piloto/público comparada directamente (`compras-local-public-availability.json`):24capacidades e336rotas funcionais coincidem. A configuração de contextos da empresa pública não reproduz o painel local; continua a ser uma pendência concreta, não eliminação dos módulos. Os percursos de venda/contratação para terceiros estão marcados não operacionais em ambos. Reconciliar a política empresarial e as associações de contexto pelos mecanismos nativos, preservando permissões, registos e limites; preparar/verificar o impacto de activar a selecção antes de alterar o acesso efectivo. Não confundir comparações de código, HTTP200, disponibilidade por perfil e conclusão funcional integral.
|
||||
|
||||
## Correcção corrente de acesso — 29/11/2026
|
||||
|
||||
Entrega seleccionada `compras-e5c8c140738b6e1e`, substituindo `compras-a2711a98b34fceb3` apenas em quatro fontes e no build correspondente. `/` conduz o visitante a `/login` e a sessão autenticada a `/dashboard`. A página institucional permanece em `/apresentacao`; a consulta pública existente conserva os caminhos, com aviso explícito de ausência de sessão e botões de entrada. Não apresentar listas públicas vazias como estado dos dados empresariais.
|
||||
|
||||
Diagnóstico autenticado verificou conteúdo e acções em 14 destinos de cinco perfis: duas requisições, duas ordens, recepção/stock, factura, orçamento, relatórios, cinco documentos e processo de Pessoas presentes. Nenhuma alteração de dados, configuração, contas ou permissões. Os logins da empresa de exemplo estão no ficheiro privado já indicado; não confundir uma conta anterior com uma conta da empresa sintética nem criar concessões para contornar o acesso. Testes: 36/700 backend, 48 frontend, tipos, lint, Pint, build e 185 hashes públicos aprovados. Provas `compras-access-fix.json` e `compras-workspace-visibility.json`. A página de apresentação e os números do parágrafo anterior não constituem demonstração da sessão empresarial no navegador; a revisão nativa desta correcção confirmou o destino de entrada e os botões visíveis.
|
||||
|
||||
## Referência corrente — 29/11/2026
|
||||
|
||||
Usar a única entrega `compras-a2711a98b34fceb3`, instalada em https://compras.tempo.co.mz, e o manifesto `compras-release.json`. O acesso para apresentação é `/login`, com os perfis da empresa de exemplo já configurada; credenciais apenas no ficheiro privado `C:/laragon/data/compras/secrets/presentation-access-20261129.private.json`. Não copiar credenciais para documentação ou provas. Não criar outra versão comercial, empresa ou base para repetir o que está instalado.
|
||||
|
||||
Instalação pública, interface, autoridade de auditoria, contrato formalizado pela Direcção e operação periódica Linux já demonstrados; não pedir novamente essas autorizações. Código/185 assets/componentes conferidos, 32 consultas por dez perfis aprovadas, auditoria privada gerada e descarregada, documentos privados e saldos reconciliados. Provas correntes em `compras-release-*.json`; consultar o resumo corrente da matriz antes de interpretar pendências históricas. QA/piloto e originais permanecem preservados como ambientes internos.
|
||||
|
||||
JUE e bancos têm percurso documental instalado. Uma ligação externa efectiva exige identificar serviço/banco, especificação, endpoint e acesso de testes; não criar um simulador e apresentá-lo como integração. A escolha entre percurso documental da apresentação e ligação externa de testes já foi perguntada e ainda não foi respondida. Não repetir perguntas sobre empresa sintética ou autoridade da Direcção.
|
||||
|
||||
29/11/2026 — acesso SSH por chave dedicada confirmado após instalação pelo proprietário. Conferência remota só de leitura encontrou a candidata autorizada já presente: manifesto c3ac2c64 e 185 ficheiros com hashes exactos. O domínio público serve a nova entrada e os 185 assets por HTTPS com os hashes aprovados; identidade anónima e navegação financeira privada preservadas. Não foi necessário reinstalar ou escrever no servidor nesta conferência. A pendência de ligação/publicação referida abaixo está superada, sem atribuir a esta conferência a execução anterior da publicação. Provas `analytics-print-remote-readonly.json` e `analytics-print-publication-http.json`; estado reconciliado em `analytics-print-publication.json`. Revisão visual restante da auditoria e aceitação empresarial continuam separadas; aplicação integral não declarada concluída.
|
||||
|
||||
29/11/2026 — análise de despesa demonstrada emQA autónoma com login normal: pagamento/afectação preparados pelos serviços nativos; soma39MZN recusada conservando valores,15MZN Material+25MZN Serviços gravados por Finanças como versão1. Relatório conserva40MZN e ambas categorias;153tabelas protegidas intactas, uma imputação/uma auditoria, sem alterar fontes financeiras.390×526/100% legível em formulário/tabelas; impressão de seis folhas mantém título/explicação/categorias juntos na página3 após correcção de quebra. Contexto da afectação passa a Finanças apenas com entrada já autorizada, contagem singular corrigida.37testes/7ficheiros, tipos/lint/formatação/build aprovados. Manifestoc3ac2c64/185assets publicado no piloto por autorização específica, manifesto/chunks anteriores salvaguardados;24capacidades/56GETs e185respostas/hash aprovados, settings/env intactos. Publicação pública autorizada mas NÃO executada: domínio serve instalação distinta, entrada anterior e404para novosassets. Corrigida a suposição anterior de actualização partilhada automática; ligação administrativa existente solicitada, sem repetir tentativasSSH anteriores sem mudança de condição. Provas `procurement-analytics-qa.json`, `analytics-print-publication[-http].json`. Base/roleQA removidos, três separadores anteriores preservados. Aplicação integral continua aberta.
|
||||
|
||||
29/11/2026 — revisão nativa de `/ordens/1/imprimir` e `/recepcoes/1/imprimir` no piloto: ordem antiga OC-TEST-wKzfEhxT9Y conserva aviso de original incompleto e totais10000+1600=11600MZN; recepçãoREC-2026-000001 conserva recebido/aceite1,000 e rejeitado0,000, origem e referências disponíveis. Cada pré-visualização coube numa folha, sem cortes observados; ambas canceladas, sem impressão física.390×526/100% confirmou totais da ordem e tabela/referências da recepção; cabeçalhos da tabela quebram nas colunas. Ferramentas/separador próprios fechados e três separadores anteriores preservados. Sem gravações de negócio; conferência PostgreSQL só leitura conserva149tabelas e apenas a fila técnica avança pela tarefa autorizada. Prova `product-review-20261122.json#native_pilot_order_receipt_print_20261129`. Não representa impressão de documentos com anexos, estornos ou confirmação integral dos restantes relatórios.
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"date": "2026-11-29T17:10:07.239Z",
|
||||
"state": "pilot_passed_public_installation_pending",
|
||||
"date": "2026-11-29T17:54:10.058Z",
|
||||
"state": "passed",
|
||||
"pilot_asset_responses_and_hashes": 185,
|
||||
"public_domain_html_delivers_new_entry": false,
|
||||
"public_domain_html_delivers_new_entry": true,
|
||||
"public_anonymous_identity_preserved": true,
|
||||
"private_finance_navigation_not_exposed_publicly": true,
|
||||
"new_grants_or_business_operations": false
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"date": "2026-11-29T17:07:03+00:00",
|
||||
"state": "partially_published",
|
||||
"state": "passed",
|
||||
"authorization": "analytics-print-publication-authorization.json",
|
||||
"manifest_sha256": "c3ac2c6443d73c228a3a8e8e96f2f32bb130fa5e5b03b2b284b02007c5502022",
|
||||
"previous_manifest_sha256": "8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b",
|
||||
@@ -11,9 +11,12 @@
|
||||
"public_runtime_activation": false,
|
||||
"application_complete": false,
|
||||
"pilot_state": "passed",
|
||||
"public_state": "pending_existing_administrative_connection",
|
||||
"public_html_still_previous_entry": true,
|
||||
"public_new_assets_status": 404,
|
||||
"public_state": "verified_existing_authorized_candidate",
|
||||
"public_html_still_previous_entry": false,
|
||||
"public_new_assets_status": 200,
|
||||
"public_installation_distinct_from_local_pilot": true,
|
||||
"previous_shared_installation_assumption_corrected": true
|
||||
"previous_shared_installation_assumption_corrected": true,
|
||||
"remote_readonly_verification": "analytics-print-remote-readonly.json",
|
||||
"public_assets_verified": 185,
|
||||
"remote_publication_performed_in_this_verification": false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"resolved_release": "/var/www/compras-deploy/releases/20261129-174929-96b30368bc74-8fKHrPgF",
|
||||
"manifest_sha256": "c3ac2c6443d73c228a3a8e8e96f2f32bb130fa5e5b03b2b284b02007c5502022",
|
||||
"assets_checked": 185,
|
||||
"asset_errors": [],
|
||||
"remote_writes": false,
|
||||
"date": "2026-11-29T17:55:06.259Z",
|
||||
"public_assets_http_and_hashes": 185
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"state": "installed_and_verified",
|
||||
"release_id": "compras-e5c8c140738b6e1e",
|
||||
"previous_release_id": "compras-a2711a98b34fceb3",
|
||||
"changed_files": [
|
||||
"resources/js/components/sgc-workspace-shell.tsx",
|
||||
"resources/js/pages/auth/login.tsx",
|
||||
"resources/js/pages/home.tsx",
|
||||
"routes/web.php"
|
||||
],
|
||||
"backup": "/var/backups/compras-presentation-20261129/access-fix",
|
||||
"data_settings_permissions_changed": false,
|
||||
"guest_root": "/login",
|
||||
"authenticated_root": "/dashboard",
|
||||
"public_presentation": "/apresentacao",
|
||||
"public_screens_preserved_with_visible_login": true,
|
||||
"date": "2026-11-29",
|
||||
"backend": {
|
||||
"tests": 36,
|
||||
"assertions": 700,
|
||||
"state": "passed"
|
||||
},
|
||||
"frontend_tests": 48,
|
||||
"types_lint_pint_build": "passed",
|
||||
"public_assets_verified": 185,
|
||||
"native_browser": {
|
||||
"guest_root_opens_login": true,
|
||||
"public_login_buttons_visible": true,
|
||||
"authenticated_browser_session_demonstrated": false
|
||||
},
|
||||
"authenticated_content_proof": "compras-workspace-visibility.json",
|
||||
"account_scope": "Existing sample-company accounts; no identity or permission changes",
|
||||
"superseded_by": "compras-pilot-reference-restored.json"
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"state": "installed",
|
||||
"release_id": "compras-47dfeee7485db877",
|
||||
"backup": "/var/backups/compras-presentation-20261129/context-audit-preservation",
|
||||
"exact_historical_archives": 3,
|
||||
"archive_bytes_manifest_context_and_database_rows_changed": false,
|
||||
"profile_permissions_changed": false,
|
||||
"same_original_author_and_current_family_authorities_required": true,
|
||||
"other_legacy_archives_allowed": false
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"state": "passed",
|
||||
"normal_authenticated_http": true,
|
||||
"synthetic_client_id": 1,
|
||||
"checks": [
|
||||
{
|
||||
"kind": "service",
|
||||
"process_id": 2,
|
||||
"status": "contract_formalized",
|
||||
"client_identity_preserved": true,
|
||||
"provider_direction_confirmed": true,
|
||||
"internal_context_access_refused": true,
|
||||
"signed_document_hash_verified": true
|
||||
},
|
||||
{
|
||||
"kind": "staff",
|
||||
"process_id": 3,
|
||||
"status": "contract_formalized",
|
||||
"client_identity_preserved": true,
|
||||
"provider_direction_confirmed": true,
|
||||
"internal_context_access_refused": true,
|
||||
"signed_document_hash_verified": true
|
||||
}
|
||||
],
|
||||
"employee_admission_or_external_dispatch": false
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"state": "passed",
|
||||
"migration_connection_name": "registry_upgrade",
|
||||
"restore_initially_without_registry": {
|
||||
"database": "compras_client_restore_cd696fb17c93",
|
||||
"connection_name": "registry_upgrade",
|
||||
"exists": false,
|
||||
"schema_sha256": null,
|
||||
"migration_recorded": false,
|
||||
"client_count": null
|
||||
},
|
||||
"recovered_registry": {
|
||||
"database": "compras_client_restore_cd696fb17c93",
|
||||
"connection_name": "registry_upgrade",
|
||||
"exists": true,
|
||||
"schema_sha256": "4187827c43b41406db7b959f093cc8b2761b04406b268690718e025d3f2e1474",
|
||||
"migration_recorded": true,
|
||||
"client_count": 0
|
||||
},
|
||||
"active_registry_unchanged": true,
|
||||
"active_empty_schema_matches_native_migration": true,
|
||||
"recovery_database_removed": true,
|
||||
"recovery_upgrade": {
|
||||
"state": "passed",
|
||||
"mode": "recovery_copy",
|
||||
"existing_business_tables_preserved": 148,
|
||||
"client_records_created": 0,
|
||||
"permissions_changed": false,
|
||||
"migration": "database/migrations/2026_11_29_000004_create_business_clients.php"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"state": "passed",
|
||||
"release_id": "compras-e4e3196d1877e804",
|
||||
"backup": "C:\/laragon\/data\/compras\/backups\/local-public-unification-20261129-212846-1e3d9d",
|
||||
"restored_tables_verified": 150,
|
||||
"protected_business_tables_preserved": 143,
|
||||
"selected_migrations_applied": [
|
||||
"database\/migrations\/2026_11_29_000004_create_business_clients.php"
|
||||
],
|
||||
"frontend_assets": 186,
|
||||
"settings_users_permissions_and_original_columns_preserved": false,
|
||||
"public_or_sgf_database_changed": false,
|
||||
"original_settings_users_permissions_and_original_columns_preserved": true,
|
||||
"added_configuration": {
|
||||
"SGC_PEOPLE_THIRD_PARTY_ENABLED": true
|
||||
},
|
||||
"temporary_restore_database_removed": true
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"date": "2026-11-29",
|
||||
"state": "compared_with_configuration_difference",
|
||||
"local_url": "http://127.0.0.1:8005/dashboard",
|
||||
"public_url": "https://compras.tempo.co.mz",
|
||||
"public_release_id": "compras-e5c8c140738b6e1e",
|
||||
"method": "Independent Laravel bootstrap against each installed configuration; PostgreSQL connection read-only; no business commands, identity changes or grants",
|
||||
"standalone_features_enabled_local": 24,
|
||||
"standalone_features_enabled_public": 24,
|
||||
"feature_differences": [],
|
||||
"functional_route_method_pairs_local": 336,
|
||||
"functional_route_method_pairs_public": 336,
|
||||
"functional_route_action_differences": [],
|
||||
"excluded_route_scope": "Local evaluation entries and underscore-prefixed tooling",
|
||||
"local_company_context_policy": {
|
||||
"revision": 1,
|
||||
"enabled": [
|
||||
"procurement.internal",
|
||||
"procurement.sales",
|
||||
"people.internal",
|
||||
"people.third_party"
|
||||
]
|
||||
},
|
||||
"public_company_context_policy": null,
|
||||
"confirmed_difference": "Local authenticated dashboard selects work contexts; public sample-company dashboard uses the legacy overview because its work-context policy was not configured",
|
||||
"operational_contexts_in_both_codebases": [
|
||||
"procurement.internal",
|
||||
"people.internal"
|
||||
],
|
||||
"not_operational_in_either_codebase": [
|
||||
"procurement.sales",
|
||||
"people.third_party"
|
||||
],
|
||||
"authenticated_content_check": "compras-workspace-visibility.json",
|
||||
"public_access_fix": "compras-access-fix.json",
|
||||
"all_workflows_reexecuted_by_this_comparison": false,
|
||||
"whole_product_or_full_pilot_equivalence_claimed": false,
|
||||
"configuration_permissions_or_business_data_changed": false,
|
||||
"superseded_by": "compras-pilot-reference-restored.json"
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"state": "passed",
|
||||
"release_id": "compras-47dfeee7485db877",
|
||||
"backup": "C:\/laragon\/data\/compras\/backups\/local-public-unification-20261129-210236-b1c704",
|
||||
"restored_tables_verified": 150,
|
||||
"protected_business_tables_preserved": 143,
|
||||
"selected_migrations_applied": [
|
||||
"database\/migrations\/2026_11_03_000005_add_operational_geography_references.php",
|
||||
"database\/migrations\/2026_11_29_000003_allow_signed_people_contract.php"
|
||||
],
|
||||
"frontend_assets": 185,
|
||||
"settings_users_permissions_and_original_columns_preserved": true,
|
||||
"public_or_sgf_database_changed": false,
|
||||
"temporary_restore_database_removed": true
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"state": "passed",
|
||||
"release_id": "compras-47dfeee7485db877",
|
||||
"backup": "/var/backups/compras-presentation-20261129/pilot-aligned-current",
|
||||
"current_dump_readable": true,
|
||||
"prior_full_schema_restore_preserved": true,
|
||||
"new_schema_migrations": false,
|
||||
"storage_bytes_preserved_and_download_verified": true,
|
||||
"recurring_service_after_context_alignment": "passed",
|
||||
"hashes": {
|
||||
"database.dump": "20a3016a28890b56de6f3716c934b625476cf0feb4a963ebf7632d1ce613654a",
|
||||
"product.zip": "a7e4473e1417b444a42a484f1ddf4f0fc03b64874cb9c304ef74181b30745940"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"state": "passed",
|
||||
"company_id": 2,
|
||||
"context_options": [
|
||||
"procurement.internal",
|
||||
"procurement.sales",
|
||||
"people.internal",
|
||||
"people.third_party"
|
||||
],
|
||||
"administration_available_contexts": [
|
||||
"procurement.internal",
|
||||
"procurement.sales",
|
||||
"people.internal",
|
||||
"people.third_party"
|
||||
],
|
||||
"profiles_aligned": 9,
|
||||
"profile_permissions_and_names_preserved": true,
|
||||
"unrelated_tables_preserved": 145,
|
||||
"native_configuration_commands": true,
|
||||
"operational_flags_preserved": {
|
||||
"procurement.internal": true,
|
||||
"procurement.sales": false,
|
||||
"people.internal": true,
|
||||
"people.third_party": false
|
||||
},
|
||||
"original_pilot_or_previous_public_database_changed": false
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"state": "passed",
|
||||
"release_id": "compras-47dfeee7485db877",
|
||||
"same_four_pilot_choices": true,
|
||||
"normal_credential_login": true,
|
||||
"checks": [
|
||||
{
|
||||
"context": "procurement.internal",
|
||||
"selected_on_dashboard": true,
|
||||
"operational": true,
|
||||
"internal_records_visible": true,
|
||||
"cross_context_or_unimplemented_operation_refused": true
|
||||
},
|
||||
{
|
||||
"context": "procurement.sales",
|
||||
"selected_on_dashboard": true,
|
||||
"operational": false,
|
||||
"internal_records_visible": false,
|
||||
"cross_context_or_unimplemented_operation_refused": true
|
||||
},
|
||||
{
|
||||
"context": "people.internal",
|
||||
"selected_on_dashboard": true,
|
||||
"operational": true,
|
||||
"internal_records_visible": true,
|
||||
"cross_context_or_unimplemented_operation_refused": true
|
||||
},
|
||||
{
|
||||
"context": "people.third_party",
|
||||
"selected_on_dashboard": true,
|
||||
"operational": false,
|
||||
"internal_records_visible": false,
|
||||
"cross_context_or_unimplemented_operation_refused": true
|
||||
}
|
||||
],
|
||||
"buyer_people_context_refused": true,
|
||||
"original_audit_archives_visible_and_download_hashes_verified": 3,
|
||||
"unauthorized_archive_downloads_refused": 3,
|
||||
"business_mutations_executed": false,
|
||||
"third_party_options_claimed_complete": false
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"date": "2026-11-29",
|
||||
"state": "installed_and_verified",
|
||||
"authorization": "Owner: eu quero o que esta no piloto; prior public installation and synthetic-company decisions preserved",
|
||||
"release_id": "compras-47dfeee7485db877",
|
||||
"public_url": "https://compras.tempo.co.mz/dashboard",
|
||||
"reference": "http://127.0.0.1:8005/dashboard",
|
||||
"sample_company_preserved": true,
|
||||
"standalone_modules_active_in_both": 24,
|
||||
"functional_route_method_pairs_matching": 336,
|
||||
"same_dashboard_component": "work-context",
|
||||
"same_four_choices": ["procurement.internal", "procurement.sales", "people.internal", "people.third_party"],
|
||||
"public_policy_revision": 1,
|
||||
"profiles_aligned_by_native_configuration": 9,
|
||||
"profile_business_permissions_preserved": true,
|
||||
"unrelated_database_tables_preserved_during_alignment": 145,
|
||||
"existing_generated_label_encoding_repaired": 8,
|
||||
"passwords_emails_and_memberships_changed": false,
|
||||
"backend_sqlite": {"batches": [{"tests": 44, "assertions": 482}, {"tests": 13, "assertions": 525}], "state": "passed"},
|
||||
"backend_postgresql": {"tests": 57, "assertions": 1007, "state": "passed", "isolated_database_and_role_removed": true},
|
||||
"phpstan_errors": 0,
|
||||
"pint_and_diff_check": "passed",
|
||||
"installed_source_files_verified": 945,
|
||||
"https_frontend_files_verified": 185,
|
||||
"approved_components_verified": 3,
|
||||
"authenticated_http_content": "compras-workspace-visibility.json",
|
||||
"context_selection_and_refusal_checks": "compras-pilot-contexts-http.json",
|
||||
"historical_audit_archives_restored_with_original_hashes": 3,
|
||||
"historical_audit_archive_rows_bytes_and_manifests_changed": false,
|
||||
"historical_audit_access": "Exact export IDs/SHA-256 transition receipt; original author, tenant and current family authority still required",
|
||||
"financial_read_only_check": {"invoice_minor": 100000, "payment_minor": 40000, "remaining_minor": 60000, "journal_debit_minor": 100000, "journal_credit_minor": 100000, "stock_milli": 10000, "state": "passed", "mode": "CLI with memory-only configured context session"},
|
||||
"native_edge": {"normal_login": true, "four_choice_dashboard_observed": true, "internal_procurement_selected": true, "menus_observed": ["Compras", "Armazem e activos", "Financas", "Administracao", "Relatorios"], "requisition_list_opened": true, "requisitions_visible": 2, "left_authenticated_in_public_procurement": true, "original_local_tabs_preserved": true, "password_saved_in_browser_by_agent": false},
|
||||
"recovery_directory": "/var/backups/compras-presentation-20261129/pilot-aligned-current",
|
||||
"previous_configuration_and_source_backups": ["/var/backups/compras-presentation-20261129/context-alignment", "/var/backups/compras-presentation-20261129/context-audit-preservation"],
|
||||
"recurring_service_after_alignment": "passed",
|
||||
"preserved_pilot_limitations": ["procurement.sales and people.third_party remain non-operational, as in the pilot", "No external JUE or bank submission executed"],
|
||||
"all_application_requirements_claimed_complete": false,
|
||||
"test_harness_note": "An overlapping SQLite/PostgreSQL fake-storage run interfered with test files; serial reruns passed. No active installation storage was used by these tests."
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"state": "passed",
|
||||
"release_id": "compras-e4e3196d1877e804",
|
||||
"backup": "/var/backups/compras-presentation-20261129/client-hiring-installed",
|
||||
"same_selected_application": true,
|
||||
"recovery_copy_upgrade": {
|
||||
"state": "passed",
|
||||
"mode": "recovery_copy",
|
||||
"existing_business_tables_preserved": 148,
|
||||
"client_records_created": 0,
|
||||
"permissions_changed": false,
|
||||
"migration": "database/migrations/2026_11_29_000004_create_business_clients.php"
|
||||
},
|
||||
"selected_schema_upgrade": {
|
||||
"state": "passed",
|
||||
"mode": "exact_empty_schema_reconciled",
|
||||
"schema_sha256": "4187827c43b41406db7b959f093cc8b2761b04406b268690718e025d3f2e1474",
|
||||
"existing_business_data_changed": false,
|
||||
"permissions_changed": false
|
||||
},
|
||||
"new_configuration": {
|
||||
"SGC_PEOPLE_THIRD_PARTY_ENABLED": true
|
||||
},
|
||||
"existing_permissions_changed": false,
|
||||
"external_financial_or_hr_dispatch": false,
|
||||
"temporary_recovery_database_removed": true
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"state": "delivered_to_mailbox",
|
||||
"sender": "nala@tempo.co.mz",
|
||||
"recipient": "nala@tempo.co.mz",
|
||||
"transport": "sendmail",
|
||||
"queue_identifiers": [
|
||||
"4jczzZ2TSZz13KlK"
|
||||
],
|
||||
"matching_mail_log_records": 1,
|
||||
"mailbox_delivery_records": 0,
|
||||
"targeted_test_message_found_in_authorized_mailbox": true,
|
||||
"mailbox_other_messages_or_message_bodies_read": false,
|
||||
"test_messages_sent": 1,
|
||||
"business_or_credential_data_sent": false
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"product": "compras",
|
||||
"release_id": "compras-e4e3196d1877e804",
|
||||
"archive": "C:\\laragon\\www\\compras\\storage\\app\\private\\compras-release-client-hiring.zip",
|
||||
"files": 1215,
|
||||
"sha256": "e6ecf82d0943fab658c65fff6b5d9c1c194104e743c38b158eb87fa8fe091e79",
|
||||
"credentials_or_business_data": false
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"state": "passed",
|
||||
"release_id": "compras-a2711a98b34fceb3",
|
||||
"backup": "/var/backups/compras-presentation-20261129/consolidation/current",
|
||||
"private_files_verified_in_backup": 8,
|
||||
"database_archive_readable": true,
|
||||
"full_database_restore": "prior final-backup.json, no schema delta",
|
||||
"hashes": {
|
||||
"database.dump": "bd5612a9e7a77aec4578c21b29ee1e671d6fde531970238bc4fc002ddae8fe0d",
|
||||
"storage.tar.gz": "3713e4da48a2ec8603f8e786137d6468d5bde024a9d3c7972a845e2aca1a67cc",
|
||||
"code.tar.gz": "80d585ea6a2f8442dece7c8b8f55db23375e973c4d331d328896662149c045ff"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
{
|
||||
"date": "2026-11-29",
|
||||
"product": "compras",
|
||||
"state": "installed_and_verified",
|
||||
"whole_product_acceptance": "not_claimed",
|
||||
"release_id": "compras-a2711a98b34fceb3",
|
||||
"public_url": "https://compras.tempo.co.mz",
|
||||
"login_path": "/login",
|
||||
"sample_company_is_product_configuration": true,
|
||||
"separate_commercial_editions_created": false,
|
||||
"same_selected_installation_preserved": true,
|
||||
"manifest": "compras-release.json",
|
||||
"source_files_verified": 945,
|
||||
"frontend_assets_verified": 185,
|
||||
"approved_component_manifests_verified": 3,
|
||||
"release_verifier_tests": {
|
||||
"passed": 9,
|
||||
"failed": 0
|
||||
},
|
||||
"public_entry_regression": {
|
||||
"tests": 18,
|
||||
"assertions": 650,
|
||||
"state": "passed"
|
||||
},
|
||||
"navigation_frontend_tests": {
|
||||
"passed": 48,
|
||||
"state": "passed_before_final_server_install"
|
||||
},
|
||||
"private_storage_pg_integration": {
|
||||
"tests": 15,
|
||||
"assertions": 264,
|
||||
"state": "passed"
|
||||
},
|
||||
"native_authenticated_http": {
|
||||
"profiles": 10,
|
||||
"destinations": 32,
|
||||
"state": "passed"
|
||||
},
|
||||
"audit_after_storage_change": {
|
||||
"id": 3,
|
||||
"verified_zip_members": 136,
|
||||
"unauthorized_download": 403
|
||||
},
|
||||
"private_files_preserved_before_new_audit": 7,
|
||||
"private_files_verified_in_current_backup": 8,
|
||||
"financial_reconciliation": {
|
||||
"currency": "MZN",
|
||||
"invoice_minor": 100000,
|
||||
"confirmed_payment_minor": 40000,
|
||||
"remaining_minor": 60000,
|
||||
"journal_debit_minor": 100000,
|
||||
"journal_credit_minor": 100000,
|
||||
"explicit_finance_category_minor": 40000,
|
||||
"stock_milli": 10000,
|
||||
"duplicate_or_external_payments": false,
|
||||
"read_only": true,
|
||||
"synthetic": true
|
||||
},
|
||||
"people": {
|
||||
"formalized_by_company_direction": true,
|
||||
"private_document_hash_verified": true,
|
||||
"unauthorized_download_refused": true,
|
||||
"employee_admission_or_rh_dispatch": false,
|
||||
"confirmation_and_replay_evidence": "prior native exercise; current read and hash rechecked"
|
||||
},
|
||||
"recurring_operations": {
|
||||
"single_timer": "compras-operations.timer",
|
||||
"active_and_enabled": true,
|
||||
"previous_demo_timer_disabled": true,
|
||||
"start_and_restart": "passed",
|
||||
"checks_selected_release_before_business_commands": true,
|
||||
"windows_session_required": false,
|
||||
"full_host_reboot_tested": false
|
||||
},
|
||||
"publisher": {
|
||||
"selected_configuration_and_storage_preserved": true,
|
||||
"source_assets_and_components_checked_before_activation": true,
|
||||
"shell_syntax": "passed",
|
||||
"git_remote_deployment_triggered": false
|
||||
},
|
||||
"native_edge_review": {
|
||||
"public_home_loaded": true,
|
||||
"six_operational_areas": true,
|
||||
"login_links": true,
|
||||
"original_tabs_preserved": true
|
||||
},
|
||||
"original_environment_sha256_unchanged": "1d192e2b379ef3ed5f5908ea73bb58c204b3b400ce7cce124c48926a6b71958b",
|
||||
"backup": "compras-release-backup.json",
|
||||
"artifact": "compras-release-artifact.json",
|
||||
"related_proofs": [
|
||||
"compras-release-http.json",
|
||||
"compras-release-profiles.json",
|
||||
"compras-release-evidence.json",
|
||||
"compras-release-operations.json"
|
||||
],
|
||||
"not_demonstrated": [
|
||||
"External bank or JUE service integration: service specification and test access not supplied",
|
||||
"Full host reboot",
|
||||
"Maximum production capacity",
|
||||
"Real-company configuration and integral business acceptance"
|
||||
],
|
||||
"superseded_by": "compras-access-fix.json"
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"state": "passed",
|
||||
"origin": "https://compras.tempo.co.mz",
|
||||
"normal_login_sessions": 4,
|
||||
"audit_export_id": 3,
|
||||
"audit_zip_sha256": "d742323d5fc7671aee60f36f7a3e484228746d398dcea0e85e98966f14f67766",
|
||||
"audit_zip_members_verified": 136,
|
||||
"audit_unauthorized_download_refused": true,
|
||||
"people_formalized_by_direction": true,
|
||||
"admin_without_direction_authority_refused": true,
|
||||
"formalization_replay_one_effect": true,
|
||||
"signed_document_hash_verified": true,
|
||||
"signed_document_private_path_redacted": true,
|
||||
"unauthorized_contract_download_refused": true,
|
||||
"employee_admission_or_rh_dispatch": false
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"state": "passed",
|
||||
"product": "compras",
|
||||
"release_id": "compras-e4e3196d1877e804",
|
||||
"public_url": "https://compras.tempo.co.mz",
|
||||
"assets_verified": 186,
|
||||
"real_product_entry": true,
|
||||
"login_entry": true,
|
||||
"anonymous_private_identity_or_financial_access": false
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"state": "passed",
|
||||
"release_id": "compras-16385e173ebb322f",
|
||||
"private_files_preserved": {
|
||||
"import-dossier/2/2/ad1de182-3b6a-487e-bbca-f62d140eed0a-1.pdf": "b34501857ab4b2ab118e5154d1d492071b65db77b1913712f5b47fb98b8ace89",
|
||||
"import-dossier/2/2/c24a3652-9bc4-4633-b0a2-98d48d87d9d5-1.pdf": "ad82af71641c00c9ffa6eb9d3a41e819fababbc443a965eb559a50537afff278",
|
||||
"import-dossier/2/2/a097f5e3-7e67-4e09-8555-a818736ec852-1.pdf": "5ba7ac6d6be13e700b19df26353470654d18a35d2deddee14500c08cc455914a",
|
||||
"import-dossier/2/2/21487f5b-bd83-494b-9948-7b043db341b9-1.pdf": "da22b0f5ee65b3d87dab78ea41a800c0d963c6c122acc758d7c9c0acb5685bd3",
|
||||
"import-dossier/2/2/7614dc7b-8d6a-4f29-9426-fb607947fe60-1.pdf": "d471caaa766b9bfe9a510fe90a1098ccd59cbbd9297aee783d38e0f178bd419a",
|
||||
"audit-exports/2/18/194edbc1-dd5f-4807-95de-020ce2fbe0b0/auditoria.zip": "624c1ae1268573e52f73d228d777d0c47080778202ee29e1991dc9152f0ea117",
|
||||
"audit-exports/2/18/8aa2dea7-dd53-43fb-bc77-2a27c888c3de/auditoria.zip": "c883335f6d73eca41422e0f5fb67d1bbc3548ce70497f9b441f4ab0b9970ea1c"
|
||||
},
|
||||
"private_root": "/var/www/compras-deploy/demonstration-20261129/storage/app/private",
|
||||
"previous_private_root_preserved": true,
|
||||
"single_timer": "compras-operations.timer",
|
||||
"start_and_restart": "passed",
|
||||
"business_records_migrated": false
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
{
|
||||
"state": "passed",
|
||||
"origin": "https://compras.tempo.co.mz",
|
||||
"normal_login_sessions": 10,
|
||||
"checks": [
|
||||
{
|
||||
"profile": "admin",
|
||||
"path": "/dashboard",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "admin",
|
||||
"path": "/administracao/parametrizacao",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "admin",
|
||||
"path": "/pessoas",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "admin",
|
||||
"path": "/pessoas/relatorios",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "admin",
|
||||
"path": "/pessoas/relatorios?view=selections",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "admin",
|
||||
"path": "/relatorios",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "requester",
|
||||
"path": "/dashboard",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "requester",
|
||||
"path": "/requisicoes",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "requester",
|
||||
"path": "/requisicoes/1",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/dashboard",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/fornecedores",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/cotacoes",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/ordens",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/ordens-operacionais",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/projectos-imobilizado",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/compras/importacoes/12/documentos",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/compras/importacoes/12/suporte-bancario",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/compras/importacoes/12/suporte-bancario.csv",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/compras/importacoes/12/documentos/13",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/compras/importacoes/12/documentos/14",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/compras/importacoes/12/documentos/15",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/compras/importacoes/12/documentos/16",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/compras/importacoes/12/documentos/17",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "finance",
|
||||
"path": "/dashboard",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "finance",
|
||||
"path": "/relatorios",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "finance",
|
||||
"path": "/orcamentos",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "warehouse",
|
||||
"path": "/dashboard",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "warehouse",
|
||||
"path": "/recepcoes",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "auditor",
|
||||
"path": "/dashboard",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "auditor",
|
||||
"path": "/auditoria/privada",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "direction",
|
||||
"path": "/dashboard",
|
||||
"status": 200
|
||||
},
|
||||
{
|
||||
"profile": "direction",
|
||||
"path": "/pessoas",
|
||||
"status": 200
|
||||
}
|
||||
],
|
||||
"synthetic_only": true,
|
||||
"authentication_shortcuts": false,
|
||||
"errors": []
|
||||
}
|
||||
@@ -0,0 +1,460 @@
|
||||
{
|
||||
"environment": "http://127.0.0.1:8005",
|
||||
"scope": "existing authorised records only",
|
||||
"rows": [
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/ordens",
|
||||
"status": 200,
|
||||
"component": "purchases/index",
|
||||
"visible_page_records": 1
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/recepcoes",
|
||||
"status": 200,
|
||||
"component": "receipts/index",
|
||||
"visible_page_records": 1
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/stock",
|
||||
"status": 200,
|
||||
"component": "stock/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/stock/requisicoes",
|
||||
"status": 200,
|
||||
"component": "stock/requests",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/equipamentos",
|
||||
"status": 200,
|
||||
"component": "equipment/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/orcamentos",
|
||||
"status": 200,
|
||||
"component": "budgets/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/facturas",
|
||||
"status": 200,
|
||||
"component": "invoices/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/pagamentos",
|
||||
"status": 200,
|
||||
"component": "payments/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/planeamento",
|
||||
"status": 200,
|
||||
"component": "planning/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/revisao-compras",
|
||||
"status": 200,
|
||||
"component": "purchase-controls/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/relatorios",
|
||||
"status": 200,
|
||||
"component": "reports/procurement",
|
||||
"visible_page_records": 2
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/relatorios/medidas-fornecedores",
|
||||
"status": 200,
|
||||
"component": "reports/supplier-improvements",
|
||||
"visible_page_records": 1
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/compras/fornecimento?view=calendar",
|
||||
"status": 200,
|
||||
"component": "supply/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/compras/fornecimento?view=imports",
|
||||
"status": 200,
|
||||
"component": "supply/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/compras/acordos/vigencia",
|
||||
"status": 200,
|
||||
"component": "supply/agreement-followup",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/pessoas",
|
||||
"status": 200,
|
||||
"component": "people/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/pessoas/tarefas",
|
||||
"status": 200,
|
||||
"component": "workflow/tasks",
|
||||
"visible_page_records": null
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/pessoas/relatorios",
|
||||
"status": 200,
|
||||
"component": "people/reports",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "admin",
|
||||
"path": "/pessoas/cadastro",
|
||||
"status": 200,
|
||||
"component": "people/registry",
|
||||
"visible_page_records": null
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/ordens",
|
||||
"status": 200,
|
||||
"component": "purchases/index",
|
||||
"visible_page_records": 1
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/recepcoes",
|
||||
"status": 200,
|
||||
"component": "receipts/index",
|
||||
"visible_page_records": 1
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/stock",
|
||||
"status": 200,
|
||||
"component": "stock/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/stock/requisicoes",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/equipamentos",
|
||||
"status": 200,
|
||||
"component": "equipment/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/orcamentos",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/facturas",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/pagamentos",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/planeamento",
|
||||
"status": 200,
|
||||
"component": "planning/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/revisao-compras",
|
||||
"status": 200,
|
||||
"component": "purchase-controls/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/relatorios",
|
||||
"status": 200,
|
||||
"component": "reports/procurement",
|
||||
"visible_page_records": 2
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/relatorios/medidas-fornecedores",
|
||||
"status": 200,
|
||||
"component": "reports/supplier-improvements",
|
||||
"visible_page_records": 1
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/compras/fornecimento?view=calendar",
|
||||
"status": 200,
|
||||
"component": "supply/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/compras/fornecimento?view=imports",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "procurement",
|
||||
"path": "/compras/acordos/vigencia",
|
||||
"status": 200,
|
||||
"component": "supply/agreement-followup",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/ordens",
|
||||
"status": 200,
|
||||
"component": "purchases/index",
|
||||
"visible_page_records": 1
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/recepcoes",
|
||||
"status": 200,
|
||||
"component": "receipts/index",
|
||||
"visible_page_records": 1
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/stock",
|
||||
"status": 200,
|
||||
"component": "stock/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/stock/requisicoes",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/equipamentos",
|
||||
"status": 200,
|
||||
"component": "equipment/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/orcamentos",
|
||||
"status": 200,
|
||||
"component": "budgets/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/facturas",
|
||||
"status": 200,
|
||||
"component": "invoices/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/pagamentos",
|
||||
"status": 200,
|
||||
"component": "payments/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/planeamento",
|
||||
"status": 200,
|
||||
"component": "planning/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/revisao-compras",
|
||||
"status": 200,
|
||||
"component": "purchase-controls/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/relatorios",
|
||||
"status": 200,
|
||||
"component": "reports/procurement",
|
||||
"visible_page_records": 2
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/relatorios/medidas-fornecedores",
|
||||
"status": 200,
|
||||
"component": "reports/supplier-improvements",
|
||||
"visible_page_records": 1
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/compras/fornecimento?view=calendar",
|
||||
"status": 200,
|
||||
"component": "supply/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/compras/fornecimento?view=imports",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "finance",
|
||||
"path": "/compras/acordos/vigencia",
|
||||
"status": 200,
|
||||
"component": "supply/agreement-followup",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/ordens",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/recepcoes",
|
||||
"status": 200,
|
||||
"component": "receipts/index",
|
||||
"visible_page_records": 1
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/stock",
|
||||
"status": 200,
|
||||
"component": "stock/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/stock/requisicoes",
|
||||
"status": 200,
|
||||
"component": "stock/requests",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/equipamentos",
|
||||
"status": 200,
|
||||
"component": "equipment/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/orcamentos",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/facturas",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/pagamentos",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/planeamento",
|
||||
"status": 200,
|
||||
"component": "planning/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/revisao-compras",
|
||||
"status": 200,
|
||||
"component": "purchase-controls/index",
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/relatorios",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/relatorios/medidas-fornecedores",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/compras/fornecimento?view=calendar",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/compras/fornecimento?view=imports",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
},
|
||||
{
|
||||
"role": "warehouse",
|
||||
"path": "/compras/acordos/vigencia",
|
||||
"status": 403,
|
||||
"component": null,
|
||||
"visible_page_records": 0
|
||||
}
|
||||
],
|
||||
"print_paths": [
|
||||
"/ordens/1/imprimir",
|
||||
"/recepcoes/1/imprimir"
|
||||
],
|
||||
"business_commands": false,
|
||||
"visual_review": false
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
{
|
||||
"state": "passed",
|
||||
"release_id": "compras-47dfeee7485db877",
|
||||
"authenticated_root_redirects_to_dashboard": true,
|
||||
"authenticated_workspace_checks": [
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/dashboard",
|
||||
"status": 200,
|
||||
"component": "work-context",
|
||||
"authenticated": true,
|
||||
"collections": {},
|
||||
"flags": {
|
||||
"canRequest": true,
|
||||
"payablesAvailable": false,
|
||||
"orderCancellationAvailable": true,
|
||||
"operationalOrdersAvailable": true,
|
||||
"privateAuditAvailable": true,
|
||||
"capitalRegisterAvailable": true
|
||||
},
|
||||
"context_enforced": true
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/requisicoes",
|
||||
"status": 200,
|
||||
"component": "requisitions/index",
|
||||
"authenticated": true,
|
||||
"collections": {
|
||||
"requisitions": {
|
||||
"rows": 2,
|
||||
"total": 2
|
||||
}
|
||||
},
|
||||
"flags": {
|
||||
"canRequest": true,
|
||||
"payablesAvailable": false,
|
||||
"orderCancellationAvailable": true,
|
||||
"operationalOrdersAvailable": true,
|
||||
"privateAuditAvailable": true,
|
||||
"capitalRegisterAvailable": true
|
||||
},
|
||||
"context_enforced": true
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/cotacoes",
|
||||
"status": 200,
|
||||
"component": "quotations/index",
|
||||
"authenticated": true,
|
||||
"collections": {
|
||||
"requisitions": {
|
||||
"rows": 2,
|
||||
"total": 2
|
||||
}
|
||||
},
|
||||
"flags": {
|
||||
"canRequest": true,
|
||||
"payablesAvailable": false,
|
||||
"orderCancellationAvailable": true,
|
||||
"operationalOrdersAvailable": true,
|
||||
"privateAuditAvailable": true,
|
||||
"capitalRegisterAvailable": true
|
||||
},
|
||||
"context_enforced": true
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/ordens",
|
||||
"status": 200,
|
||||
"component": "purchases/index",
|
||||
"authenticated": true,
|
||||
"collections": {
|
||||
"orders": {
|
||||
"rows": 2,
|
||||
"total": 2
|
||||
},
|
||||
"awards": {
|
||||
"rows": 2,
|
||||
"total": 2
|
||||
}
|
||||
},
|
||||
"flags": {
|
||||
"canRequest": true,
|
||||
"payablesAvailable": false,
|
||||
"orderCancellationAvailable": true,
|
||||
"operationalOrdersAvailable": true,
|
||||
"privateAuditAvailable": true,
|
||||
"capitalRegisterAvailable": true,
|
||||
"partsAvailable": true
|
||||
},
|
||||
"context_enforced": true
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/ordens/1",
|
||||
"status": 200,
|
||||
"component": "purchases/show",
|
||||
"authenticated": true,
|
||||
"collections": {},
|
||||
"flags": {
|
||||
"canRequest": true,
|
||||
"payablesAvailable": false,
|
||||
"orderCancellationAvailable": true,
|
||||
"operationalOrdersAvailable": true,
|
||||
"privateAuditAvailable": true,
|
||||
"capitalRegisterAvailable": true,
|
||||
"canAmendOrderParts": false
|
||||
},
|
||||
"context_enforced": true
|
||||
},
|
||||
{
|
||||
"profile": "procurement",
|
||||
"path": "/compras/importacoes/12/documentos",
|
||||
"status": 200,
|
||||
"component": "supply/import-dossier",
|
||||
"authenticated": true,
|
||||
"collections": {
|
||||
"documents": {
|
||||
"rows": 5,
|
||||
"total": 5
|
||||
}
|
||||
},
|
||||
"flags": {
|
||||
"canRequest": true,
|
||||
"payablesAvailable": false,
|
||||
"orderCancellationAvailable": true,
|
||||
"operationalOrdersAvailable": true,
|
||||
"privateAuditAvailable": true,
|
||||
"capitalRegisterAvailable": true,
|
||||
"canWrite": true
|
||||
},
|
||||
"context_enforced": true
|
||||
},
|
||||
{
|
||||
"profile": "warehouse",
|
||||
"path": "/recepcoes",
|
||||
"status": 200,
|
||||
"component": "receipts/index",
|
||||
"authenticated": true,
|
||||
"collections": {
|
||||
"orders": {
|
||||
"rows": 2,
|
||||
"total": 2
|
||||
},
|
||||
"receipts": {
|
||||
"rows": 1,
|
||||
"total": 1
|
||||
}
|
||||
},
|
||||
"flags": {
|
||||
"canRequest": false,
|
||||
"payablesAvailable": false,
|
||||
"orderCancellationAvailable": true,
|
||||
"operationalOrdersAvailable": true,
|
||||
"privateAuditAvailable": true,
|
||||
"capitalRegisterAvailable": true
|
||||
},
|
||||
"context_enforced": true
|
||||
},
|
||||
{
|
||||
"profile": "warehouse",
|
||||
"path": "/stock",
|
||||
"status": 200,
|
||||
"component": "stock/index",
|
||||
"authenticated": true,
|
||||
"collections": {
|
||||
"items": {
|
||||
"rows": 1
|
||||
},
|
||||
"balances": {
|
||||
"rows": 1
|
||||
},
|
||||
"movements": {
|
||||
"rows": 1,
|
||||
"total": 1
|
||||
}
|
||||
},
|
||||
"flags": {
|
||||
"canRequest": false,
|
||||
"payablesAvailable": false,
|
||||
"orderCancellationAvailable": true,
|
||||
"operationalOrdersAvailable": true,
|
||||
"privateAuditAvailable": true,
|
||||
"capitalRegisterAvailable": true,
|
||||
"canManage": true
|
||||
},
|
||||
"context_enforced": true
|
||||
},
|
||||
{
|
||||
"profile": "finance",
|
||||
"path": "/facturas",
|
||||
"status": 200,
|
||||
"component": "invoices/index",
|
||||
"authenticated": true,
|
||||
"collections": {
|
||||
"invoices": {
|
||||
"rows": 1,
|
||||
"total": 1
|
||||
},
|
||||
"orders": {
|
||||
"rows": 2
|
||||
}
|
||||
},
|
||||
"flags": {
|
||||
"canRequest": false,
|
||||
"payablesAvailable": true,
|
||||
"orderCancellationAvailable": true,
|
||||
"operationalOrdersAvailable": true,
|
||||
"privateAuditAvailable": true,
|
||||
"capitalRegisterAvailable": true,
|
||||
"sgfDispatchAvailable": false,
|
||||
"canManage": true
|
||||
},
|
||||
"context_enforced": true
|
||||
},
|
||||
{
|
||||
"profile": "finance",
|
||||
"path": "/orcamentos",
|
||||
"status": 200,
|
||||
"component": "budgets/index",
|
||||
"authenticated": true,
|
||||
"collections": {
|
||||
"budgets": {
|
||||
"rows": 1
|
||||
},
|
||||
"reinforcements": {
|
||||
"rows": 0,
|
||||
"total": 0
|
||||
}
|
||||
},
|
||||
"flags": {
|
||||
"canRequest": false,
|
||||
"payablesAvailable": true,
|
||||
"orderCancellationAvailable": true,
|
||||
"operationalOrdersAvailable": true,
|
||||
"privateAuditAvailable": true,
|
||||
"capitalRegisterAvailable": true
|
||||
},
|
||||
"context_enforced": true
|
||||
},
|
||||
{
|
||||
"profile": "finance",
|
||||
"path": "/relatorios",
|
||||
"status": 200,
|
||||
"component": "reports/procurement",
|
||||
"authenticated": true,
|
||||
"collections": {
|
||||
"records": {
|
||||
"rows": 2,
|
||||
"total": 2
|
||||
}
|
||||
},
|
||||
"flags": {
|
||||
"canRequest": false,
|
||||
"payablesAvailable": true,
|
||||
"orderCancellationAvailable": true,
|
||||
"operationalOrdersAvailable": true,
|
||||
"privateAuditAvailable": true,
|
||||
"capitalRegisterAvailable": true
|
||||
},
|
||||
"context_enforced": true
|
||||
},
|
||||
{
|
||||
"profile": "direction",
|
||||
"path": "/pessoas",
|
||||
"status": 200,
|
||||
"component": "people/index",
|
||||
"authenticated": true,
|
||||
"collections": {
|
||||
"processes": {
|
||||
"rows": 1,
|
||||
"total": 1
|
||||
}
|
||||
},
|
||||
"flags": {
|
||||
"canRequest": false,
|
||||
"payablesAvailable": false,
|
||||
"orderCancellationAvailable": true,
|
||||
"operationalOrdersAvailable": true,
|
||||
"privateAuditAvailable": true,
|
||||
"capitalRegisterAvailable": false,
|
||||
"ready": true
|
||||
},
|
||||
"context_enforced": true
|
||||
},
|
||||
{
|
||||
"profile": "direction",
|
||||
"path": "/pessoas/1",
|
||||
"status": 200,
|
||||
"component": "people/show",
|
||||
"authenticated": true,
|
||||
"collections": {},
|
||||
"flags": {
|
||||
"canRequest": false,
|
||||
"payablesAvailable": false,
|
||||
"orderCancellationAvailable": true,
|
||||
"operationalOrdersAvailable": true,
|
||||
"privateAuditAvailable": true,
|
||||
"capitalRegisterAvailable": false,
|
||||
"canPrepare": false,
|
||||
"canViewElectronicSources": false,
|
||||
"canReview": false,
|
||||
"canApprove": true,
|
||||
"canContract": false,
|
||||
"canFormalize": true,
|
||||
"canManage": false
|
||||
},
|
||||
"context_enforced": true
|
||||
},
|
||||
{
|
||||
"profile": "auditor",
|
||||
"path": "/auditoria/privada",
|
||||
"status": 200,
|
||||
"component": "audit/private",
|
||||
"authenticated": true,
|
||||
"collections": {
|
||||
"exports": {
|
||||
"rows": 3,
|
||||
"total": 3
|
||||
}
|
||||
},
|
||||
"flags": {
|
||||
"canRequest": false,
|
||||
"payablesAvailable": false,
|
||||
"orderCancellationAvailable": true,
|
||||
"operationalOrdersAvailable": true,
|
||||
"privateAuditAvailable": true,
|
||||
"capitalRegisterAvailable": false
|
||||
},
|
||||
"context_enforced": true
|
||||
}
|
||||
],
|
||||
"business_data_changed": false,
|
||||
"permissions_changed": false
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
{
|
||||
"manifest_sha256": "40e05731bf13a7e18c06becb4e1fc5e364d57a4c2e67d9df09efa50bc52da243",
|
||||
"archive_sha256": "1aa6aeb4b915cc7512efbd6e6934b446dade7e2b51014f8a56372389317e8259",
|
||||
"referenced_asset_files": 185,
|
||||
"files": {
|
||||
"assets/Combination-Cf-uZSDM.js": "cb6de0edf2a5bc431766866135d9c8868a5671cd0bcc7894cfd8d425db1ea41d",
|
||||
"assets/access-BBfd79uk.js": "3f24b5ed1555aec69d943d9065d9026e63811b49205069a4b35b8afdf30ce396",
|
||||
"assets/access-Ba6-kT12.js": "092e60c1b57c1fecd2b0510a00af0122db3660d144afc51e57af8bd043c805e5",
|
||||
"assets/accounts-CFQAT90U.js": "6bafc30448f1b50cbb5518a8193335eda42ab92de7d3bb4834312e3835df8176",
|
||||
"assets/administrative-location-DNTlGGhQ.js": "366b5d86ce4c4c0a349a256e7a3afcc64415a3c00cac3a518c9b95b47e5266b1",
|
||||
"assets/admission-B4_sUfPZ.js": "386c689c4541914f9d0adb488a4ceff7f80ee7d64e50b06834393425345a4ee3",
|
||||
"assets/admission-Dt9aLRHT.js": "306b6d3be4ac535dc0c14b377b729f37eeb677713af0add83f45b69e12421874",
|
||||
"assets/admission-policy-CVwC6PGA.js": "04927c45cad964317edc1775ca4e420353aef744275db2f31747301f6cdc48a0",
|
||||
"assets/agreement-followup-CTZAWyDy.js": "048a6009f27be1eab142dfcfb3722b9989e5621aecb49cfe50cd65242c45681e",
|
||||
"assets/agreement-order-bindings-CI2C5CIq.js": "631a6f7e413faf01c55de0a785005c0a9ebc223c4ac4a7b79eb602eecf3ca3e0",
|
||||
"assets/ai-preparation-preview-DXG9BgBt.js": "96db7d2aeb5aac283b5e7df3f5647f46f8676266a617fecf2f2791dc1e3468b4",
|
||||
"assets/app-BBfXPNdJ.js": "cae4fc5ed621cd241dcb75c6d8ea90a5d81ff52f8c312e39f2f26db01261ff76",
|
||||
"assets/app-Cw7kTAYA.css": "e434bac0a92dcabd61eea57a8947a50cc9bf5fd4dc380e93afb3cf1020a812de",
|
||||
"assets/appearance-DtHfEkYX.js": "ced493a0bfad154218eb8104f2668a6c5e293aca4bbea0bef9c2e24eff7f0d32",
|
||||
"assets/approval-timeouts-U_QCLClV.js": "4d1894d70f281363b123e2186f8e055674afd9f230f2f5d60a5a08ff18eea067",
|
||||
"assets/arrow-right-jQM5Ljhm.js": "460657b89c0a22dd8c648c59408ab9b5d89cda0a2f77fdb5aafb5d4cd81ee047",
|
||||
"assets/availability-BCJ226SS.js": "d3f9a85e37b8721e72bf11b7fb249d0537ed1a978681215cd7cbc5cf94173331",
|
||||
"assets/award-DB1_PMWc.js": "0fd2d68415315b3cdd4983c791e452ed1643b74fb735ae318b19e30f9cb2a4c2",
|
||||
"assets/bank-CZmrPDBl.js": "c4916ba8b98f07ceda23b78e19f7c1e7ba5aa4a0af37e58508e77fabf9ab252c",
|
||||
"assets/budget-distribution-fields-BT7T8Tz2.js": "c81437b8edfcdb2e09d983481441093bdcbfb873590e12062e9820410fa4cfcb",
|
||||
"assets/budgets-Bi_IodfK.js": "371306d2ff13dfe0e42abb36e755440b88eb894a8cd23d15cbc7cacaed3e6fe6",
|
||||
"assets/button-CSyysFhi.js": "a0c7c2d62ff1c139a6b5e6ff2e4c7cc778682337a935a3eee0e2df5ac36607b9",
|
||||
"assets/candidate-availability-BBYAjwDY.js": "848c1b093b9016d4dbbc7795f44c281eb3776bfebf82b2a84ca943c70f5df1aa",
|
||||
"assets/candidate-documents-DzSJVuya.js": "3f5131f76ab32a1477614e2318e09a5fbe736f5b6fc75fe306fdba5802f28482",
|
||||
"assets/candidate-portal-D_qlgQu_.js": "99e1a4dfe620c236750153d5dda607ef1f7f11422ec015b5872e5045727a8559",
|
||||
"assets/capital-assignments-BQRTWLQi.js": "9340f115437822986d3a549742c1b7a98fbe0d797b1ddf1fb652e50a9afcf45e",
|
||||
"assets/capital-register-YtRTWOD5.js": "62f1f74278ffd5609b3f46bbf7a81e73aece6861ae6e115daf6bb7aa94c5f307",
|
||||
"assets/catalogue-C7MXItgF.js": "062d588eb732dca98ab40c97f3ea76e519739ba93079d0c4f9a526b711b117f2",
|
||||
"assets/check-B0y1oDcN.js": "2b0f7b1e72a08a1106cae81a5910d88a308d1bc92c729def81b0c38b743c7c59",
|
||||
"assets/clock-3-Cy_zSYUr.js": "b8bf146f2a287cd2bf356687ab0dfdcb0bef6f0213bfda494985dd98d97d20a0",
|
||||
"assets/company-Cda4Q5Nz.js": "874bdc0f5867c5603a32d36e39dcd4e5309f67f910639408de6eef1021624381",
|
||||
"assets/comparison-policy-summary-C80JsjfA.js": "13b64488a4166adec1678d172588b46cf6834382c575b87054c49ba587b69fa8",
|
||||
"assets/confirm-password-COF6TKQD.js": "cf126d4bb65976c2b05f054900a26037611af2eaa3f5ab5c3737dfe0bd33d844",
|
||||
"assets/conflict-BelUpYxR.js": "19efa315d126114e8d34439393364583a3fc1b735b3afc41f401c3da8aaf33b4",
|
||||
"assets/conflicts-CHBtF8cM.js": "a08005603adcf1506731a963c2b12b41444e848429c6221de1347f6677e0f17a",
|
||||
"assets/coordination-Dm2EsI7m.js": "a47b6645238eac041fd478647bcf9265dbd0cedb9037619cf0271be0d0c0d6f5",
|
||||
"assets/correction-source-search-CE1Ay7Tz.js": "0b3a65d76e994b4820c1daa3c930e4b8bbdb042e69df868fafff0ffff64e0bc3",
|
||||
"assets/createLucideIcon-Bl2ij0Zm.js": "88026a98f925baf2a85f5c6091f3dce5d35689ec432417ba87ac3fba450aa326",
|
||||
"assets/dashboard-D_JNuESm.js": "8a98decfa0b9df67d4a9657114162b0aa5d92501ba11ab7b43b460067a3a759c",
|
||||
"assets/dispositions-DR-H2aTc.js": "adcaf4aa564822fa159646d4d05d9b9f94f5dce9ebf42dc3e3f8fc560b0003e8",
|
||||
"assets/dist-Bm7wFECT.js": "ec7a8f48099bdb15bd706858c566dff3c664ea77420b2973463f9482c5c66aa0",
|
||||
"assets/dist-Cxy2kTRX.js": "7884e24de234f6d592ec16f228c0eaba69ee5adf28fcbedb0d59383d184958c8",
|
||||
"assets/dist-DSfJglKD.js": "7e5239388df8e9e9251bc5d432701c3a1798b8940371f88e42683e6426f0c6f2",
|
||||
"assets/distribution-amendment-BDw2tmf5.js": "7f32a4d93a9975361721f1fc3ba9f98687e377100b82f0820a333e3dc2eaf5c1",
|
||||
"assets/distributions-B4Ku_8FA.js": "566f44420a2a5fe2bbdc020576a2b7ac3d4b349c5791b12bbef1156de4b7a508",
|
||||
"assets/download-d-ik75sA.js": "ac23d0b10fe748b8664965a4ebb479336cbc75e4d08e570577e5f70519bfde1c",
|
||||
"assets/edit-Cq2B19Sz.js": "ac50d841332c42d1b21141aad6247d549edaac905b0a28073646061a10980b20",
|
||||
"assets/entry-BkwwMsbZ.js": "685d91560d11b3482eea1c17332aaff565aa65dba512245cd768e511f82a7662",
|
||||
"assets/equipment-t4YFlsTI.js": "c249fbd35f6e2e8a679d798878bbd0efe0de4e4b9e9310d2cfb34b455ddc9d86",
|
||||
"assets/evaluation-D_YVu544.js": "079466cb3c413eca736a064f055bf69e2466ac9e141ff07b1727c7a70bcebc2d",
|
||||
"assets/evaluations-eKaAW0dK.js": "865cb66cf741750848382e6665f589b50d899e36c74985d0ab6f6237f5d7e8db",
|
||||
"assets/expense-allocation-D8hs9E3I.js": "bc221c1eddee2c78d8196e2d79f089fdf95053951943596f7d3e7005b625b188",
|
||||
"assets/expiry-BP6Ramr4.js": "0b0c959f5587972431274ab55750b97a19f49aa1240c908b8c69886692d41842",
|
||||
"assets/eye-BcFYyvf-.js": "eccd97f0bfeab1e54e9d1abdcd96184794449a6b6277d096598489f52f61e9cf",
|
||||
"assets/file-text-BMumQ0Wt.js": "9af4fdf5c0527694f24719af17256ac1ebb7061ddd738e5135fdd411f5b3a3ac",
|
||||
"assets/finance-CIzNf4Ud.js": "72be0363c942288103b774cc80fac7cf12d501eb2862b80e45b5b255b3951e07",
|
||||
"assets/fonts-C9MNnjVw.css": "3846a9bb60bfad92960eadcccaf0b4e129d74b11d48791506c8d1a827a385cc8",
|
||||
"assets/forgot-password-DCXJC_E_.js": "a5b121e52ab4cd21d7d7bf1ae2497b27ef73b65d222b4dcf2ed4bcb095bfe195",
|
||||
"assets/form-DTXqtU1q.js": "e8e8d26e0ae7091072c03e6f171cd4b989010e88ded7b7d9df203b6e69a72966",
|
||||
"assets/geography-review-LHH-cwEC.js": "fec7a43dda29145adceae072df64a583fa0b3d7476d9b533d50815bb11eebf24",
|
||||
"assets/history-D3Z7TJSH.js": "e332bd880ef5abaa15949e6ec33edcd1d1191a5074791cb0d0a8667fdb9cc11d",
|
||||
"assets/home-C8zre5vh.js": "227f56bfd0a918c51a0b5745c450ab7d15026d4c3c64df95b31df2711b34a897",
|
||||
"assets/import-bank-support-B5V4fmwy.js": "31c2e92bb3564415f7da635b15c984ec62c2a5bb2cbcaa13c464c621b97170be",
|
||||
"assets/import-costs-C7bVIm2C.js": "ff2e8bb3c1bcadada94fd678821d4cb000b9ba18c7b0edb71d33a7a21c708921",
|
||||
"assets/import-dossier-DI43Wz_w.js": "35fc33759bcee8a095f007433e4038d6f2333220ebda6fb9b02585309058a375",
|
||||
"assets/import-estimate-DfTWawl6.js": "66e8d1a8a3837f4a32013680cd586bae5677d0b26bdc4d3a17eab7532e7c9964",
|
||||
"assets/import-estimate-money-C8In-mMc.js": "a55799be92061737217e27d9d22baf042cd085b35da5c49f64ef8abb819205a5",
|
||||
"assets/import-legal-SuIuYu8O.js": "f01b7b636f42d7ada82fb4b648b2ec154565d039cc506bba60d3b156d46f6a72",
|
||||
"assets/import-readiness-BOEjwGvz.js": "35f9cd49c66e6330316d30b3d998adf7b4562b4a7fac3084a3cc2f13058d8858",
|
||||
"assets/import-tariff-summary-CZgW7X3m.js": "8ba6abe82126b6c815437c6cb5d6ccd8253090539b40400c1df9e761ea64971e",
|
||||
"assets/import-tariffs-BFrRT5qr.js": "b4681f8b7c8927152df9567b776b1460733e8c8d29ae646d9e16ed69cb5e6d2e",
|
||||
"assets/input-error-B1DjHZT7.js": "00286fd9e30543b59027b37606d63c96944efdf4f58339aba7afd0cd08629ace",
|
||||
"assets/instrument-sans-400-normal-D1W7dsQl.woff": "797bd3eaa70edbd4757650ab44dad75fbfbfdf18bacedb4b71022c04621d30ad",
|
||||
"assets/instrument-sans-400-normal-DRC__1Mx.woff2": "9a91efaa3599a6ef01b2f49e9ec670e3a2f39baeef09c73198f1052cf3bb0850",
|
||||
"assets/instrument-sans-500-normal-Dk9ku72i.woff2": "9d3547da16d950d12a677c772a3ff9b69846e60e7dcd1b5efd540993f7286532",
|
||||
"assets/instrument-sans-500-normal-Z6ESRlEs.woff": "bd6a8dc8b0dc0cced0c32d3eda93f0e0e82c58ddefea8b53b3307b0c48da3089",
|
||||
"assets/instrument-sans-600-normal-B7fBEWYG.woff2": "efb770916eda95a0e31d80cccde9651d4e8617010b21220e9f227c4820d675da",
|
||||
"assets/instrument-sans-600-normal-B9e8oLYv.woff": "9b4ce1f2b26be7cb087fd87d6f99a202136292ec820af75bd38ab9e53895cf28",
|
||||
"assets/inventory-B5h3Ukug.js": "4e5464e66e4f4436f82f06de10587dbde46c3b7c92d964b09eaa31e6d9f4fb2e",
|
||||
"assets/inventory-BF2HrsoH.js": "fa3e4a56bae767f93e7f7d0202c4efecc8d08583c0ca6761db8560acda64ddc9",
|
||||
"assets/inventory-correction-filters-CWn788td.js": "5bfb7efed986f3b9aa3a1ff86d554e2706ca891649b17aa9d12d27edf55f98e9",
|
||||
"assets/inventory-demo-CHQ1V2y4.js": "e55482a5313f2dbd3839ff24c2b7b9f70d1ab9a2a83f69bceebaa8ae6a217081",
|
||||
"assets/inventory-event-actions-DhoZbooY.js": "a97e6a34b96f4d40952c1c9d884ea51c3222aaa60edae5e01b148c8e8971f93e",
|
||||
"assets/investment-DMCXoFFu.js": "1c45a796b03563a91961e4f9ea84bde7cabaddc97cb8f39e2fbce3a4af921046",
|
||||
"assets/invoices-DCMs2Gl8.js": "fbfbf53b5cba440e2feb22511887c8f98d1f0f9a555ab53de483974647283c04",
|
||||
"assets/jsx-runtime-Cjjuc_0N.js": "239501f6701a312b0fbef99c9067ea0d62f11aeeb3a8b388ec4c7528b0493500",
|
||||
"assets/label-Dn4U5SHB.js": "d273f9faf668fc6fc998709fa86dbb3d424a23271725cc48a9b88a8b2d8e399c",
|
||||
"assets/loader-circle-YS2_4W2r.js": "4648de3680be9df8d38d808bb954b6cee541cf3b376321926a10c3edddb96345",
|
||||
"assets/login-Dv0B_cXu.js": "bfdc79544308a40ded053ab5e9990d6cbe32480065f9ff01d65422bec440568d",
|
||||
"assets/lots-7dZCljkQ.js": "edaeb8906d74b38395d285a43b8ea58f6034c5232c74d3626cd6ce9d716ad08b",
|
||||
"assets/metadata-C-fJTc47.js": "e443bbaef407d3fd5e82b8dfaaf4bd744dedf025c73923a79f10de12ceb9011d",
|
||||
"assets/notices-Bv6f8IP4.js": "69e57320cd83192d09fb3fe350803d6cf3abae93713c1b859425de3907d625e6",
|
||||
"assets/opening-D9ljmCiJ.js": "171c54c3bac72d43fdcbe86ac41f3d905e296405d529e48335738a2e52cc8371",
|
||||
"assets/operational-orders-D9vbu8NF.js": "cb1ede976090d71029ceaf9ec4c3b7f9ef4a2c5e42f5ef3703bff72da7000651",
|
||||
"assets/operations-ys4DaHFu.js": "be33edb0590d7d6a52d5257906ee4e17b859cb50eb7b12ca20d9f9804140f425",
|
||||
"assets/opportunity-BBqAxnoG.js": "c71a0080bd9f8618115935b23d3b4ccc012ee60651ec589f22ad46b1bd1052c5",
|
||||
"assets/order-document-links-CY7gGohw.js": "a94c6e359ec9ab4cb143177522e2822c9aaacc462f636ab5fccfe09c45cdc43c",
|
||||
"assets/order-parts-CW5t2gcS.js": "4bf1d746291eded17bfeceaedcfbab1f4daf5fe0f384739196110a8f98b5db9b",
|
||||
"assets/order-parts-amendment-D9vAbTeR.js": "ab397c62d5d0d37a5f156606fcabb109fd62437b02cf62c8b0510ccc1e244148",
|
||||
"assets/order-woOEir0F.js": "5688268fdef80f4e628c6c0a6fadd89f769e347eff78898cd38412591f228dc8",
|
||||
"assets/orders-ChPSbQlR.js": "8d81aa77d6197c68dee6a47493f45218ab47136825d01ab620d231484594c284",
|
||||
"assets/package-check--ZYjz2oi.js": "ce6074fe092e03473ff914cfe088a47acd57852fe4faef54f239fd04ccd6ab83",
|
||||
"assets/parameters-vXtSLFRb.js": "9029b8a852ce685a081a366fdaf428b8c387e1871d29fc8ca36ea680564a2ebb",
|
||||
"assets/parts-DuB9J76Z.js": "34b2d43bade6510485a0f88348dd888ba1604fcbb1c6634768db329874b3f8d1",
|
||||
"assets/password-DSVT9zkL.js": "e9f8a7ef9b436a3e046d49f9ab56bdb4ca736bc98f69fc89efe36ec0a9bd08aa",
|
||||
"assets/password-input-gk4p0ZXp.js": "184ab97250bba05204227204b062a5a48599d484f4f3469e9973c1d823186d4c",
|
||||
"assets/payments-DrzTmwPA.js": "6d15313ddbc0025cef52183b74b5abf2b1843f19bf982349b3f79b31feec1eaf",
|
||||
"assets/pencil--NTa5x5n.js": "ffc5e9c22501ed8196d21f31e016d351f91796821392ec9942716d7a70b9c022",
|
||||
"assets/people-D7klMhWn.js": "c0d571592e746839537770f32b0a32c0dab175818aaef07e1d561d5236ba503a",
|
||||
"assets/people-hiring-0ebERuf_.js": "443ff16989484ecbb7576eb060a5339fccd2fc720015d72a2af828e91d12461c",
|
||||
"assets/pilot-BKLijacx.js": "0719890d0cb6a42827d8247224bc11dd53f158c4d727d193a190accd46941041",
|
||||
"assets/planning-CRZSz8Jz.js": "061f7206f5a349ab9742e3d615bcc1d83ab91724598c41bf62e7a6e5956f0c74",
|
||||
"assets/preview-CQN_xhiR.js": "8576255ca8a005a703b9752bedc5f27b6d86bdb4e23b44d9e42805d441b3608c",
|
||||
"assets/principal-BL6s4y-I.js": "f5b4e9a2b0351d8025beadf12f10354b1de43c802ed2e8b10f3c9503697cc21a",
|
||||
"assets/printer-D0Qc0KdJ.js": "6a29144df3944867ae389bb8e8194205099314ffa04c41f0fb054226f27b3566",
|
||||
"assets/private-DGZs-6QU.js": "01e908cd175a5a7f484e3d1168f80b7e76d753f2e8274e68a13a0ff57a9dfde5",
|
||||
"assets/process-C5LAVzsa.js": "26c718bbab69df745211ab574ccbcd556330127c2d1a7cf6fcead4488e375d9f",
|
||||
"assets/procurement-C7ktYiSj.js": "a1e6c9b7b4b59d21318930a90859644ebaabd2b0afa311d95f5e1e2fd4e810e1",
|
||||
"assets/procurement-CQQHmWJT.js": "730cb65cce7c1f126f3b1ded040a545b4045b3c6fea643bbedca87abbe922907",
|
||||
"assets/procurement-DDhv64ZJ.js": "b52ce34c45bb9a22e3b1b9b73339ece9160d60377ba45651bfd786452e331896",
|
||||
"assets/procurement-payable-insights-1iErQTPy.js": "c07f8ce5e90b6b25f2650df1a4a2ecabb23156f114d6d0238326bae32607d342",
|
||||
"assets/profile-BO6fwzJe.js": "e1053954f616d7631df41873e86edbdbcf29a80c86743968df70fb1f0d6c2edd",
|
||||
"assets/profile-DtV8k2ws.js": "d940a37bd9421a535b143121943f4cc11921781d72fc183053c291bb6df2c743",
|
||||
"assets/purchase-controls-OiZOcga_.js": "440612075b70dcdc3829800e5c0d2ed9e50c9f2108e175acdbdb7616c6008ffa",
|
||||
"assets/purchases-CRj-RLSL.js": "c33f90df5f1fd332af28275b6ec903b260f1bf8289db071f377c76adfba2fcec",
|
||||
"assets/qualification-YpxSpPHD.js": "b2b8ae03297e41f5b6295ffff141a01e4c567eef1fe95c25c0f547d5605f1590",
|
||||
"assets/qualification-dyeU2qAf.js": "96f8e8db998b2d772d333f965a450ea68ca6cbc97f0c48e89b48e7b94f362d81",
|
||||
"assets/quotation-exchange-panel-Cbi5W9x5.js": "774598cada0b9d01f36e5529f0f05415a0330e21c5d07762a67b6a0515a5600a",
|
||||
"assets/quotations-B9gbo1b6.js": "e78a604fbaab252e47d14c6ee4499b4aaba2c195c495691cffb7d84644224e7e",
|
||||
"assets/receipt-CX6COlya.js": "a20578c41e007f6000ff25baf9e53e7c39312d6541432b98edaa66d2355461d8",
|
||||
"assets/receipt-conversion-tRv4-edG.js": "f5aaa139b86a683bd08e04f1fc3f4bbf6edc6d4e75566004c955ccd8b55882b5",
|
||||
"assets/receipts-Bujr0Rok.js": "36127513c50d7ffefca5eb3231be98a77cd2d00821d268874fd6db6d9fdf919e",
|
||||
"assets/recommendation-CKjWrXMF.js": "78df2b5266d6c4ac86c0f9a3a978e7169d988c574b002265805e204166bed55e",
|
||||
"assets/recommendation-DN2MlfS4.js": "9cdad16d7cfaa5b8c0358e10e7f09306cf4adfc5f3a9e967a521bc8f0a6844aa",
|
||||
"assets/recommendation-policy-B5Z-9Y3K.js": "8b47cbeec2f500721e5934fca0efc90e940c4752e8876d2d0af48ee76ec86f8a",
|
||||
"assets/register-DmKBA3wx.js": "5a867e34e4233689baf337d6af2a0b3cef2b77775cc9a51b65db08f2c1a1657d",
|
||||
"assets/registry-CP0powGI.js": "d672ab3e30c26accc6a6bc64aadb8bc20e222f0100d1058c876d6f330578d4cc",
|
||||
"assets/replenishment-FeCHwB_U.js": "a52b048055f957a0764dd9a765dea38282f05795e84ca48ba92e5770e9e88705",
|
||||
"assets/reports-CIQakShd.js": "a401f156b3e9ff66eecf70f558c801ee1609e8492028b7fe4a7a798d1b88ed6d",
|
||||
"assets/request-CCOHYcE9.js": "8ecf8609599d894319775c4fd76b289f6a7860055956e31adf3c11cdf703aa71",
|
||||
"assets/requests-D9wtMV8s.js": "b266163f1873c03154babc350f48577ec99fca966b9881ca1973fac12c9bd784",
|
||||
"assets/requisition-category-fields--qtM_RtA.js": "4370eddecbf6ae0a63e5d2e920ca5ac7ef3def861943c87811a87ee4c9f37cc7",
|
||||
"assets/requisition-history-Dsahm4kA.js": "cd35dcf01ae95f608899009f3795ba78255ef294566e97ca24b70204ff2fa033",
|
||||
"assets/requisitions-DKmGw_FG.js": "d470a46efbf4d5fa8d70ebde5a7a1014edca83073d4b64d2ea87121dbfbd4235",
|
||||
"assets/reset-password-DvPZrCxl.js": "88c31fe2e3315412709f36eb02b3c4973cdce93a8b098a4ae7a5f98efa51e00a",
|
||||
"assets/returns-BWcPdCp0.js": "2373267afe6d851543338d5d1d37c6acebb0a0871de286461a40079c15eaf4a2",
|
||||
"assets/reversals-ywOB9qI9.js": "2e9a4111735acae3016b7622b5ee9f146dff9a7e532ba135c4607c7ab7fa2c45",
|
||||
"assets/review-report-DbSQA4vu.js": "588d5b00e3735ef15248c3af5d3fee17b3d5503765a704abcfbea34c052d53a2",
|
||||
"assets/rolldown-runtime-WkwZ5CU-.js": "2629f2ad3cb75a57d98de697127f5af7d777ef572bbcdfa6e3ce8f438cd4527e",
|
||||
"assets/security-8d0pnY7s.js": "84e35376ab3d8634228c1c6afff2901f471bde993f4e55e0eeb8d3f8d4212695",
|
||||
"assets/setup-DrqKQlj-.js": "328ce0d609332a1678be6bc18549c8e90263dfea78e931afad82142ae63b3318",
|
||||
"assets/show-B-8rBjLp.js": "a47529c2aa9fb33864c8bfbe9dc58e6cba8c58e04639507d0eb905d96217c80e",
|
||||
"assets/show-B2vzdAj2.js": "ce2c7a777ac9137f4a4f124923723df474d65dbe4f11264176d472b8defd0402",
|
||||
"assets/show-Bs6yOF_8.js": "375bbd9c96d245005966789816d6598ce98939bde4bae0f2442d8411b05ee9a3",
|
||||
"assets/show-CR2G4dF9.js": "b417f635af5555bdf9eb8d204fbb0490cee9df5c7f319b1e442f7f489590520b",
|
||||
"assets/show-CtWeRU-M.js": "a8e55700717b4913fe79037b472d8d85514598f3de4fbe9a02a270ca9e8b0f6c",
|
||||
"assets/show-ZKa1_Q1U.js": "0acd6ec0cf4c5a443ff9193c725547e812008a58c0bca2ca778a490070beb657",
|
||||
"assets/show-eRVpdVKe.js": "b323bd35da0b686979612840cc7e05455aafee4dc79d5999ca00bc5bbf79d84c",
|
||||
"assets/show-pmIVe1Rh.js": "9055e5af66638de49b5dfa90f48ad5d0bdc1dcbef3033bef67feeaf5a3dbd096",
|
||||
"assets/spinner-CpJAdIKb.js": "9c8f8fb08c631cae61ecdf41cd766fbc3e777fd184fa707b6351c3d460eef059",
|
||||
"assets/stock-D8unj1Pt.js": "121f57e2c946ae9461f8f62122a44795722e60b644fb013f8dd6eab2ad8f2231",
|
||||
"assets/submission-forms-HDZ1ETdR.js": "a9baa3d4a0f8fe6c3fd48c7993fb8273cce37bcc19d4729b8e2d06e124cf6c28",
|
||||
"assets/submissions-BFoJ6Ym4.js": "f5036add4fc77b4a43fdd3bc35f4de13320c0adb9fee5e1fb2a5942e310a2dc3",
|
||||
"assets/suggestions-BW3LSUQO.js": "950b70c5d0e38b9e0e6f6b0a3ceec6318c4fd8030227c42f7e280a01cd3c94c9",
|
||||
"assets/supplier-DbZ754P4.js": "5617827f9283736a34edb62fe4ea4e6c8df48961c617dd66f416fb054dd92ab4",
|
||||
"assets/supplier-evaluation-fields-CBrfp4dg.js": "ea2be93546d54e121cacffd105ed23fcbc0db34b2e26f7107c9ba47785c6fed6",
|
||||
"assets/supplier-improvements-B4CrAiE1.js": "668c155f358e8d21db9c3b2640c91e2eda47b965c046f1f487331450d33a758b",
|
||||
"assets/suppliers-BOPAV7Tz.js": "c116c47686bd1f3cc57ae01348e94da1d1ba5b66a50edb8713e934e375b05e40",
|
||||
"assets/supply-C7pHQxVb.js": "97f7ad00c3137d2854259a528208d1100f009eeb984765d6364daf2246b2aad6",
|
||||
"assets/supply-pagination-CnzjlbVc.js": "8537e2e4e48a836f41a2b2176f635ced2b1c62734485d1109bc4469168a1cb28",
|
||||
"assets/tasks-jTodf67P.js": "87d0a6a3942d04ab028e3c4b707f6d994be5507b52d0c1f2d676eeb32187fa56",
|
||||
"assets/territorial-filter-BjAG-54l.js": "58e8d5e9dd99bb926326ea1549da48b8f27f67b9b48012b2b7e4b404e11536fc",
|
||||
"assets/text-link-CydDNIng.js": "9ddf76c1a4d33cb5d25315e38395f2893250091a23c156adc582bbb2bcad85b9",
|
||||
"assets/two-factor-challenge-z9NNqRg_.js": "204a96c82b7cc437f3d0fa284867e801b5e4acfbb4504a3086a572b7c0c75f8f",
|
||||
"assets/urgent-review-Cvgf-OD_.js": "f70c5143ef77a2d0fa60d3963710b7b773e2cc2c23818c6948abfd85c8656e79",
|
||||
"assets/urgent-review-policy-DcZNGXIB.js": "91dae78dd83cc7890eb4eac59300ec06bd7ba720b45e099916f55a8fc755fb4f",
|
||||
"assets/urgent-reviews-C5BPcbwm.js": "86fc65337af2f0614b5f939239b11321e4f3bc3db934a260eab931970c55f149",
|
||||
"assets/urgent-stock-DjcfVBGF.js": "e6c82ef7c6499d7a02b882284884e7744c152613c3e9598cbb02cdf2aa1831c5",
|
||||
"assets/use-inventory-preparation-identity-DcCfUMXu.js": "43e5cb96c4ef1bd19574442166c972db05be7d25e5f5ba76a8a0086646eaa0f8",
|
||||
"assets/use-preparation-dirty-DUFO3lA8.js": "71185254b4437677434005b81b547d7958c0f1deb2e8455246dd143d77e6d9fa",
|
||||
"assets/use-procurement-preparation-identity-NZ7gcqOB.js": "09315e79db9d28ab8e584c1e6978ee3da38a849f1be28c0499301e1b3f98d115",
|
||||
"assets/utils-DJPu_GY6.js": "7b162681baff9e9a115823fd6070404fcaddf53d058b311edbe98be7f2662ef4",
|
||||
"assets/wayfinder-Dp7PqxvV.js": "3d4c90228fda731e37f541f3087fdf5387d9d59433e35b267b64a97196f70781",
|
||||
"assets/welcome-BfeofjVp.js": "0ec4d0b4cd0164f8f59740344f9476d03d0f9416032de6078077f6ec27a5010b",
|
||||
"assets/work-context-5jBjYMYb.js": "178d3d9ed6a7726b49c3938e7c1d2e8e71a2dbcc8e65ef0f58308693065216bf"
|
||||
},
|
||||
"state": "passed",
|
||||
"public_assets_responses_and_hashes": 185,
|
||||
"date": "2026-11-29T18:42:27.695Z",
|
||||
"public_entry_current": true,
|
||||
"demonstration_banner_present": true
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"date": "2026-11-30T06:05:47+00:00",
|
||||
"candidate": "OPERATIONAL-CANDIDATE-8d1af50791bd4878",
|
||||
"manifest_sha256": "23d98de207cda7397180c6e4dc5946f22739b2b8f4be55a43fc254abf1db08db",
|
||||
"passed": true,
|
||||
"checks": [
|
||||
"source unchanged app\/Modules\/Identity\/Services\/Permissions.php",
|
||||
"source unchanged app\/Modules\/Identity\/Services\/IdentityWorkflow.php",
|
||||
"source unchanged app\/Modules\/Purchasing\/BudgetAdapter.php",
|
||||
"source unchanged app\/Modules\/Purchasing\/BudgetWorkspace.php",
|
||||
"source unchanged app\/Providers\/AppServiceProvider.php",
|
||||
"source unchanged app\/Shared\/Context\/ModuleNavigation.php",
|
||||
"source unchanged resources\/js\/app.jsx",
|
||||
"source unchanged resources\/js\/PurchasingHome.jsx",
|
||||
"source unchanged public\/build\/manifest.json",
|
||||
"plan read only",
|
||||
"candidate applied app\/Modules\/Identity\/Services\/Permissions.php",
|
||||
"candidate applied app\/Modules\/Identity\/Services\/IdentityWorkflow.php",
|
||||
"candidate applied app\/Modules\/Purchasing\/BudgetAdapter.php",
|
||||
"candidate applied app\/Modules\/Purchasing\/BudgetWorkspace.php",
|
||||
"candidate applied app\/Providers\/AppServiceProvider.php",
|
||||
"candidate applied app\/Shared\/Context\/ModuleNavigation.php",
|
||||
"candidate applied resources\/js\/app.jsx",
|
||||
"candidate applied resources\/js\/PurchasingHome.jsx",
|
||||
"candidate applied public\/build\/manifest.json",
|
||||
"retry idempotent",
|
||||
"rollback completed",
|
||||
"previous code restored app\/Modules\/Identity\/Services\/Permissions.php",
|
||||
"actual host preserved app\/Modules\/Identity\/Services\/Permissions.php",
|
||||
"previous code restored app\/Modules\/Identity\/Services\/IdentityWorkflow.php",
|
||||
"actual host preserved app\/Modules\/Identity\/Services\/IdentityWorkflow.php",
|
||||
"previous code restored app\/Modules\/Purchasing\/BudgetAdapter.php",
|
||||
"actual host preserved app\/Modules\/Purchasing\/BudgetAdapter.php",
|
||||
"previous code restored app\/Modules\/Purchasing\/BudgetWorkspace.php",
|
||||
"actual host preserved app\/Modules\/Purchasing\/BudgetWorkspace.php",
|
||||
"previous code restored app\/Providers\/AppServiceProvider.php",
|
||||
"actual host preserved app\/Providers\/AppServiceProvider.php",
|
||||
"previous code restored app\/Shared\/Context\/ModuleNavigation.php",
|
||||
"actual host preserved app\/Shared\/Context\/ModuleNavigation.php",
|
||||
"previous code restored resources\/js\/app.jsx",
|
||||
"actual host preserved resources\/js\/app.jsx",
|
||||
"previous code restored resources\/js\/PurchasingHome.jsx",
|
||||
"actual host preserved resources\/js\/PurchasingHome.jsx",
|
||||
"previous code restored public\/build\/manifest.json",
|
||||
"actual host preserved public\/build\/manifest.json",
|
||||
"actual host pointer preserved"
|
||||
],
|
||||
"file_copy": "C:\\laragon\\www\\compras\/storage\/framework\/testing\/sgf-integration-recovery-957d7a0af945",
|
||||
"database_connected": false,
|
||||
"schema_changed": false,
|
||||
"destination_installed": false,
|
||||
"new_demo": false,
|
||||
"services_restarted": false,
|
||||
"business_flow_acceptance": false
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
# Transferência de Compras e actualizações do SGF
|
||||
|
||||
## Integração integral incluindo mercadorias — 30/11/2026
|
||||
|
||||
O proprietário autorizou avançar com a integração total, preservando SGC autónomo, sem novas demonstrações ou publicação, com valorização parametrizável por empresa. [Estado, candidata, matriz e limitações](integracao-total-sgf-20261130.md). Facturação tipada de mercadorias, recebível, lançamento de venda e entrega pelo stock original foram ensaiados com catálogo nativo no livro de regressão existente: 41 verificações, com reposição dos dados/schema/acessos temporários. Política FIFO/CMP preparada; ligação contabilística do custo ainda pendente. Três novos direitos de leitura na 8085 identificados, não concedidos. A candidata privada anterior 8d1af50791bd4878 não contém este incremento, não foi instalada e não representa a integração total concluída. As secções seguintes são históricas e não substituem esta delimitação.
|
||||
|
||||
## Consultas/cotações/adjudicação — estado actual, 02/11/2026
|
||||
|
||||
[Entrega para revisão, mapeamento, hashes, testes e recuperação](consultas-adjudicacao-sgf.md). Candidata **`OPERATIONAL-CANDIDATE-040fb0cb67a77d61`**, ZIP SHA-256 `dfb122bc4532ce730d500ddec0112fe4d93cb1197fa5aef21b576f4049e7312a`, manifesto `040fb0cb67a77d618011bc7ab365c53d3d4b1a787c4c0c0a2d54f315b3658e58`.
|
||||
|
||||
@@ -14,10 +14,35 @@ final class BootOverlay
|
||||
if (str_ends_with($path, 'AppServiceProvider.php')) {
|
||||
$old = '$this->app->scoped(CompanyContext::class';
|
||||
$new = "if (is_file(base_path('packages/internal-requisitions/bootstrap.php'))) { require_once base_path('packages/internal-requisitions/bootstrap.php'); }\n ".$old;
|
||||
$source = self::replace($source, $old, $new);
|
||||
$source = self::replace($source, "public function boot(): void\n {", "public function boot(): void\n {\n if (is_file(base_path('packages/internal-requisitions/bootstrap.php'))) { \$this->loadRoutesFrom(base_path('packages/internal-requisitions/integrations/sgf/operational/routes.php')); }");
|
||||
if (! str_contains($source, "base_path('packages/internal-requisitions/bootstrap.php')")) {
|
||||
$source = self::replace($source, $old, $new);
|
||||
} elseif (substr_count($source, $new) !== 1) {
|
||||
throw new \RuntimeException('Arranque de Compras divergente; reconciliar antes de preparar.');
|
||||
}
|
||||
$boot = "public function boot(): void\n {";
|
||||
$mounted = $boot."\n if (is_file(base_path('packages/internal-requisitions/bootstrap.php'))) { \$this->loadRoutesFrom(base_path('packages/internal-requisitions/integrations/sgf/operational/routes.php')); }";
|
||||
if (! str_contains($source, 'packages/internal-requisitions/integrations/sgf/operational/routes.php')) {
|
||||
$source = self::replace($source, $boot, $mounted);
|
||||
} elseif (substr_count($source, $mounted) !== 1) {
|
||||
throw new \RuntimeException('Rotas de Compras divergentes; reconciliar antes de preparar.');
|
||||
}
|
||||
} else {
|
||||
$source = self::replace($source, "'purchasing'=>['purchasing_budget.', 'supplier_payables.']", "'purchasing'=>['purchasing_budget.', 'purchasing_requisitions.', 'supplier_payables.']");
|
||||
$count = 0;
|
||||
$source = preg_replace_callback("~('purchasing'\\s*=>\\s*\\[)([^\\[\\]]*)(\\])~", static function (array $match): string {
|
||||
// Extend only the declared prefix list; preserve every later host capability.
|
||||
if (! preg_match("~^\\s*'[a-z_]+\\.'(?:\\s*,\\s*'[a-z_]+\\.')*\\s*,?\\s*$~", $match[2])
|
||||
|| ! str_contains($match[2], "'purchasing_budget.'") || ! str_contains($match[2], "'supplier_payables.'")) {
|
||||
throw new \RuntimeException('Navegação de Compras divergente; lista explícita requerida.');
|
||||
}
|
||||
if (str_contains($match[2], "'purchasing_requisitions.'")) {
|
||||
return $match[0];
|
||||
}
|
||||
|
||||
return $match[1]."'purchasing_requisitions.', ".$match[2].$match[3];
|
||||
}, $source, -1, $count);
|
||||
if ($source === null || $count !== 1) {
|
||||
throw new \RuntimeException('Navegação de Compras ausente ou ambígua; reconciliar antes de preparar.');
|
||||
}
|
||||
}
|
||||
$result[$path] = ['before_sha256' => $hash, 'after_sha256' => hash('sha256', $source), 'contents' => $source];
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<?php
|
||||
|
||||
require_once __DIR__.'/src/ReplenishmentProjection.php';
|
||||
require_once __DIR__.'/src/StockCosting.php';
|
||||
require_once __DIR__.'/src/QuotationPricing.php';
|
||||
require_once __DIR__.'/src/ProposalScoring.php';
|
||||
require_once __DIR__.'/src/RequisitionPort.php';
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace Tempo\Purchasing\Inventory;
|
||||
|
||||
use Brick\Math\BigRational;
|
||||
|
||||
/** Exact calculation over qualified facts. No stock balance or financial writer. */
|
||||
final class StockCosting
|
||||
{
|
||||
public const METHODS = ['fifo', 'weighted_average'];
|
||||
|
||||
private static function integer(mixed $value, bool $positive = false): int
|
||||
{
|
||||
if (! is_int($value) || $value < ($positive ? 1 : 0)) {
|
||||
throw new \InvalidArgumentException('Qualified integer quantity/value required.');
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
private static function amount(BigRational $value): array
|
||||
{
|
||||
$numerator = $value->getNumerator();
|
||||
$denominator = $value->getDenominator();
|
||||
$gcd = $numerator->gcd($denominator);
|
||||
$numerator = $numerator->quotient($gcd);
|
||||
$denominator = $denominator->quotient($gcd);
|
||||
$exact = $denominator->isEqualTo(1);
|
||||
|
||||
return ['numerator' => (string) $numerator, 'denominator' => (string) $denominator,
|
||||
'amount_minor' => $exact ? (string) $numerator : null, 'rounding_required' => ! $exact];
|
||||
}
|
||||
|
||||
public static function project(string $method, array $opening, array $movements): array
|
||||
{
|
||||
if (! in_array($method, self::METHODS, true) || ! is_string($opening['reference'] ?? null) || trim($opening['reference']) === '') {
|
||||
throw new \InvalidArgumentException('Explicit method and qualified opening reference required.');
|
||||
}
|
||||
$quantity = self::integer($opening['quantity_milli'] ?? null);
|
||||
$value = BigRational::of(self::integer($opening['value_minor'] ?? null));
|
||||
if ($quantity === 0 && ! $value->isZero()) {
|
||||
throw new \DomainException('Opening value without stock is inconsistent.');
|
||||
}
|
||||
$layers = [];
|
||||
$head = 0;
|
||||
if ($method === 'fifo') {
|
||||
$sumQuantity = 0;
|
||||
$sumValue = BigRational::of(0);
|
||||
foreach ($opening['layers'] ?? [] as $layer) {
|
||||
$q = self::integer($layer['quantity_milli'] ?? null, true);
|
||||
$v = BigRational::of(self::integer($layer['value_minor'] ?? null));
|
||||
if ($q > PHP_INT_MAX - $sumQuantity) {
|
||||
throw new \OverflowException('Opening quantity too large.');
|
||||
}
|
||||
$sumQuantity += $q;
|
||||
$sumValue = $sumValue->plus($v);
|
||||
$layers[] = ['quantity_milli' => $q, 'value' => $v];
|
||||
}
|
||||
if ($sumQuantity !== $quantity || ! $sumValue->isEqualTo($value)) {
|
||||
throw new \DomainException('FIFO opening requires reconciled historical layers.');
|
||||
}
|
||||
}
|
||||
$last = 0;
|
||||
$results = [];
|
||||
foreach ($movements as $movement) {
|
||||
$id = self::integer($movement['id'] ?? null, true);
|
||||
$q = self::integer($movement['quantity_milli'] ?? null, true);
|
||||
if ($id <= $last || ! is_string($movement['reference'] ?? null) || trim($movement['reference']) === '') {
|
||||
throw new \DomainException('Movements require unique ascending IDs and source references.');
|
||||
}
|
||||
$last = $id;
|
||||
if (($movement['kind'] ?? null) === 'receipt') {
|
||||
$amount = BigRational::of(self::integer($movement['value_minor'] ?? null));
|
||||
if ($q > PHP_INT_MAX - $quantity) {
|
||||
throw new \OverflowException('Stock quantity too large.');
|
||||
}
|
||||
$quantity += $q;
|
||||
$value = $value->plus($amount);
|
||||
if ($method === 'fifo') {
|
||||
$layers[] = ['quantity_milli' => $q, 'value' => $amount];
|
||||
}
|
||||
} elseif (($movement['kind'] ?? null) === 'issue') {
|
||||
if (array_key_exists('value_minor', $movement)) {
|
||||
throw new \InvalidArgumentException('An issue cannot override its calculated cost.');
|
||||
}
|
||||
if ($q > $quantity) {
|
||||
throw new \DomainException('Incomplete receipts/opening or insufficient stock; do not assume zero cost.');
|
||||
}
|
||||
$amount = BigRational::of(0);
|
||||
if ($method === 'weighted_average') {
|
||||
$amount = $value->multipliedBy($q)->dividedBy($quantity);
|
||||
} else {
|
||||
$remaining = $q;
|
||||
while ($remaining > 0) {
|
||||
$take = min($remaining, $layers[$head]['quantity_milli']);
|
||||
$part = $layers[$head]['value']->multipliedBy($take)->dividedBy($layers[$head]['quantity_milli']);
|
||||
$amount = $amount->plus($part);
|
||||
$layers[$head]['quantity_milli'] -= $take;
|
||||
$layers[$head]['value'] = $layers[$head]['value']->minus($part);
|
||||
$remaining -= $take;
|
||||
if ($layers[$head]['quantity_milli'] === 0) {
|
||||
unset($layers[$head]);
|
||||
$head++;
|
||||
}
|
||||
}
|
||||
}
|
||||
$quantity -= $q;
|
||||
$value = $value->minus($amount);
|
||||
} else {
|
||||
throw new \InvalidArgumentException('Unknown qualified movement kind.');
|
||||
}
|
||||
$results[] = ['id' => $id, 'reference' => $movement['reference'], 'kind' => $movement['kind'], 'quantity_milli' => $q, 'value' => self::amount($amount)];
|
||||
}
|
||||
|
||||
return ['method' => $method, 'opening_reference' => $opening['reference'], 'movements' => $results,
|
||||
'closing' => ['quantity_milli' => $quantity, 'value' => self::amount($value)],
|
||||
'stock_written' => false, 'journals_written' => false];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { useForm } from '@inertiajs/react';
|
||||
import { Panel, FormErrors, controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
export function PeopleContractFormalization({
|
||||
id,
|
||||
version,
|
||||
}: {
|
||||
id: number;
|
||||
version: number;
|
||||
}) {
|
||||
const form = useForm<{
|
||||
version: number;
|
||||
operation_key: string;
|
||||
reference: string;
|
||||
signed_on: string;
|
||||
reason: string;
|
||||
no_conflict: boolean;
|
||||
signed_document: File | null;
|
||||
}>({
|
||||
version,
|
||||
operation_key: crypto.randomUUID(),
|
||||
reference: '',
|
||||
signed_on: '',
|
||||
reason: '',
|
||||
no_conflict: false,
|
||||
signed_document: null,
|
||||
});
|
||||
return (
|
||||
<Panel title="Confirmar contrato assinado — Direcção">
|
||||
<form
|
||||
className="space-y-4"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (!form.processing)
|
||||
form.post(`/pessoas/${id}/formalizar`, {
|
||||
forceFormData: true,
|
||||
preserveState: 'errors',
|
||||
preserveScroll: true,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
<label className="block">
|
||||
Referência do contrato assinado
|
||||
<input
|
||||
required
|
||||
maxLength={200}
|
||||
className={controlClass}
|
||||
value={form.data.reference}
|
||||
onChange={(event) =>
|
||||
form.setData('reference', event.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Data da assinatura
|
||||
<input
|
||||
required
|
||||
type="date"
|
||||
className={controlClass}
|
||||
value={form.data.signed_on}
|
||||
onChange={(event) =>
|
||||
form.setData('signed_on', event.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Contrato assinado (PDF, até 10 MB)
|
||||
<input
|
||||
required
|
||||
type="file"
|
||||
accept="application/pdf"
|
||||
className={controlClass}
|
||||
onChange={(event) =>
|
||||
form.setData(
|
||||
'signed_document',
|
||||
event.target.files?.[0] ?? null,
|
||||
)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
Fundamento da confirmação
|
||||
<textarea
|
||||
required
|
||||
minLength={10}
|
||||
maxLength={4000}
|
||||
className={controlClass}
|
||||
value={form.data.reason}
|
||||
onChange={(event) =>
|
||||
form.setData('reason', event.target.value)
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="flex items-start gap-2">
|
||||
<input
|
||||
required
|
||||
type="checkbox"
|
||||
checked={form.data.no_conflict}
|
||||
onChange={(event) =>
|
||||
form.setData('no_conflict', event.target.checked)
|
||||
}
|
||||
/>
|
||||
Confirmo a assinatura e a ausência de conflito de interesses
|
||||
nesta intervenção.
|
||||
</label>
|
||||
<Button disabled={form.processing} type="submit">
|
||||
Confirmar formalização
|
||||
</Button>
|
||||
</form>
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
@@ -343,11 +343,15 @@ export function SgcWorkspaceShell({ children }: { children: ReactNode }) {
|
||||
</div>
|
||||
)}
|
||||
{publicNavigation && (
|
||||
<p className="border-b bg-background p-3 text-center text-sm">
|
||||
Consulta pública de desenvolvimento · Sem organização
|
||||
seleccionada e sem registos privados. Alterações exigem
|
||||
autenticação.
|
||||
</p>
|
||||
<div className="flex flex-wrap items-center justify-center gap-3 border-b bg-amber-50 px-4 py-3 text-sm text-amber-950">
|
||||
<p>
|
||||
Consulta pública sem sessão. Os registos e as acções da
|
||||
empresa ficam disponíveis depois de entrar.
|
||||
</p>
|
||||
<Button asChild size="sm">
|
||||
<Link href="/login">Entrar na aplicação</Link>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<a
|
||||
href="#sgc-main"
|
||||
@@ -496,6 +500,11 @@ export function SgcWorkspaceShell({ children }: { children: ReactNode }) {
|
||||
</div>
|
||||
{searchField()}
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{!user && (
|
||||
<Button asChild size="sm">
|
||||
<Link href="/login">Entrar</Link>
|
||||
</Button>
|
||||
)}
|
||||
{page.props.canRequest === true && (
|
||||
<Button
|
||||
asChild
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Link } from '@inertiajs/react';
|
||||
import AppLogoIcon from '@/components/app-logo-icon';
|
||||
import { home } from '@/routes';
|
||||
import type { AuthLayoutProps } from '@/types';
|
||||
|
||||
@@ -17,8 +16,11 @@ export default function AuthSimpleLayout({
|
||||
href={home()}
|
||||
className="flex flex-col items-center gap-2 font-medium"
|
||||
>
|
||||
<div className="mb-1 flex h-9 w-9 items-center justify-center rounded-md">
|
||||
<AppLogoIcon className="size-9 fill-current text-[var(--foreground)] dark:text-white" />
|
||||
<div
|
||||
aria-label="SGC"
|
||||
className="mb-1 flex h-10 w-10 items-center justify-center rounded-xl bg-rose-600 text-sm font-bold text-white"
|
||||
>
|
||||
SGC
|
||||
</div>
|
||||
<span className="sr-only">{title}</span>
|
||||
</Link>
|
||||
|
||||
@@ -530,6 +530,12 @@ export function procurementNavigation(
|
||||
path: '/administracao/parametrizacao',
|
||||
roles: ['admin'],
|
||||
},
|
||||
{
|
||||
id: 'business_clients',
|
||||
label: 'Clientes',
|
||||
path: '/empresa/clientes',
|
||||
roles: ['admin'],
|
||||
},
|
||||
{
|
||||
id: 'admission_policy',
|
||||
label: 'Política de admissão',
|
||||
|
||||
@@ -22,9 +22,7 @@ export default function Login({ status, canResetPassword }: Props) {
|
||||
<Head title="Entrar" />
|
||||
|
||||
<Button asChild variant="outline" className="mb-5 w-full">
|
||||
<TextLink href="/consulta">
|
||||
Consultar demonstração sem entrar
|
||||
</TextLink>
|
||||
<TextLink href="/apresentacao">Conhecer a aplicação</TextLink>
|
||||
</Button>
|
||||
|
||||
<Form
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
import { Form, Head, Link, router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
import { PageTitle, Panel, controlClass } from '@/components/procurement';
|
||||
import { Button } from '@/components/ui/button';
|
||||
|
||||
type Client = {
|
||||
id: number;
|
||||
client_key: string;
|
||||
code: string;
|
||||
name: string;
|
||||
tax_number: string | null;
|
||||
address: string | null;
|
||||
email: string | null;
|
||||
active: boolean;
|
||||
version: number;
|
||||
};
|
||||
function Fields({ client, prefix }: { client?: Client; prefix: string }) {
|
||||
return (
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
{(
|
||||
[
|
||||
['code', 'Código', 40],
|
||||
['name', 'Nome da entidade cliente', 180],
|
||||
['tax_number', 'Identificação fiscal', 40],
|
||||
['email', 'Email institucional', 254],
|
||||
] as const
|
||||
).map(([field, label, max]) => (
|
||||
<label
|
||||
key={field}
|
||||
className="grid gap-1 text-sm"
|
||||
htmlFor={`${prefix}-${field}`}
|
||||
>
|
||||
{label}
|
||||
<input
|
||||
id={`${prefix}-${field}`}
|
||||
className={controlClass}
|
||||
name={field}
|
||||
type={field === 'email' ? 'email' : 'text'}
|
||||
defaultValue={client?.[field] ?? ''}
|
||||
required={field === 'code' || field === 'name'}
|
||||
maxLength={max}
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
<label
|
||||
className="grid gap-1 text-sm sm:col-span-2"
|
||||
htmlFor={`${prefix}-address`}
|
||||
>
|
||||
Morada
|
||||
<textarea
|
||||
id={`${prefix}-address`}
|
||||
className={controlClass}
|
||||
name="address"
|
||||
defaultValue={client?.address ?? ''}
|
||||
maxLength={2000}
|
||||
/>
|
||||
</label>
|
||||
<label className="grid gap-1 text-sm" htmlFor={`${prefix}-active`}>
|
||||
Situação
|
||||
<select
|
||||
id={`${prefix}-active`}
|
||||
className={controlClass}
|
||||
name="active"
|
||||
defaultValue={client?.active === false ? '0' : '1'}
|
||||
>
|
||||
<option value="1">Activo</option>
|
||||
<option value="0">Inactivo</option>
|
||||
</select>
|
||||
</label>
|
||||
<label
|
||||
className="grid gap-1 text-sm sm:col-span-2"
|
||||
htmlFor={`${prefix}-reason`}
|
||||
>
|
||||
Fundamento
|
||||
<textarea
|
||||
id={`${prefix}-reason`}
|
||||
className={controlClass}
|
||||
name="reason"
|
||||
required
|
||||
minLength={10}
|
||||
maxLength={4000}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export default function Clients({
|
||||
clients,
|
||||
canManage,
|
||||
filters,
|
||||
}: {
|
||||
clients: {
|
||||
data: Client[];
|
||||
current_page: number;
|
||||
last_page: number;
|
||||
prev_page_url: string | null;
|
||||
next_page_url: string | null;
|
||||
};
|
||||
canManage: boolean;
|
||||
filters: { search?: string };
|
||||
}) {
|
||||
const [createKey, setCreateKey] = useState(() => crypto.randomUUID());
|
||||
return (
|
||||
<>
|
||||
<Head title="Clientes" />
|
||||
<div className="mx-auto flex w-full max-w-7xl flex-col gap-6 p-5 lg:p-8">
|
||||
<PageTitle
|
||||
eyebrow="Cadastro da empresa"
|
||||
title="Clientes"
|
||||
description="Entidades clientes dos serviços de contratação e das operações comerciais. Cada processo conserva a identificação aceite na sua preparação."
|
||||
/>
|
||||
<Panel title="Entidades registadas">
|
||||
<form
|
||||
className="mb-5 flex flex-wrap gap-3"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
const data = new FormData(event.currentTarget);
|
||||
const search = data.get('search');
|
||||
router.get('/empresa/clientes', {
|
||||
search: typeof search === 'string' ? search : '',
|
||||
});
|
||||
}}
|
||||
>
|
||||
<input
|
||||
name="search"
|
||||
aria-label="Procurar cliente"
|
||||
className={controlClass}
|
||||
defaultValue={filters.search ?? ''}
|
||||
placeholder="Código ou nome"
|
||||
maxLength={180}
|
||||
/>
|
||||
<Button type="submit">Procurar</Button>
|
||||
</form>
|
||||
<div className="space-y-4">
|
||||
{clients.data.map((client) => (
|
||||
<details
|
||||
key={`${client.id}-${client.version}`}
|
||||
className="rounded-lg border p-4"
|
||||
>
|
||||
<summary className="cursor-pointer text-sm font-medium">
|
||||
{client.code} · {client.name} ·{' '}
|
||||
{client.active ? 'Activo' : 'Inactivo'}
|
||||
</summary>
|
||||
{canManage ? (
|
||||
<Form
|
||||
action={`/empresa/clientes/${client.id}`}
|
||||
method="patch"
|
||||
className="mt-5 space-y-4"
|
||||
>
|
||||
{({ errors, processing }) => (
|
||||
<>
|
||||
<input
|
||||
type="hidden"
|
||||
name="version"
|
||||
value={client.version}
|
||||
/>
|
||||
{Object.values(errors).map(
|
||||
(error, index) => (
|
||||
<p
|
||||
key={index}
|
||||
role="alert"
|
||||
className="text-sm text-red-700"
|
||||
>
|
||||
{String(error)}
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
<Fields
|
||||
client={client}
|
||||
prefix={`client-${client.id}`}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={processing}
|
||||
>
|
||||
Guardar alterações
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Form>
|
||||
) : (
|
||||
<dl className="mt-4 grid gap-2 text-sm">
|
||||
{client.tax_number && (
|
||||
<div>
|
||||
<dt>Identificação fiscal</dt>
|
||||
<dd>{client.tax_number}</dd>
|
||||
</div>
|
||||
)}
|
||||
{client.address && (
|
||||
<div>
|
||||
<dt>Morada</dt>
|
||||
<dd>{client.address}</dd>
|
||||
</div>
|
||||
)}
|
||||
{client.email && (
|
||||
<div>
|
||||
<dt>Email institucional</dt>
|
||||
<dd>{client.email}</dd>
|
||||
</div>
|
||||
)}
|
||||
</dl>
|
||||
)}
|
||||
</details>
|
||||
))}
|
||||
{clients.data.length === 0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Sem clientes neste resultado.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<nav
|
||||
aria-label="Páginas de clientes"
|
||||
className="mt-5 flex flex-wrap items-center gap-4 text-sm"
|
||||
>
|
||||
{clients.prev_page_url && (
|
||||
<Link href={clients.prev_page_url}>Anterior</Link>
|
||||
)}
|
||||
<span>
|
||||
Página {clients.current_page} de {clients.last_page}
|
||||
</span>
|
||||
{clients.next_page_url && (
|
||||
<Link href={clients.next_page_url}>Seguinte</Link>
|
||||
)}
|
||||
</nav>
|
||||
</Panel>
|
||||
{canManage && (
|
||||
<Panel title="Registar cliente">
|
||||
<Form
|
||||
key={createKey}
|
||||
action="/empresa/clientes"
|
||||
method="post"
|
||||
className="space-y-4"
|
||||
onSuccess={() => setCreateKey(crypto.randomUUID())}
|
||||
>
|
||||
{({ errors, processing }) => (
|
||||
<>
|
||||
<input
|
||||
type="hidden"
|
||||
name="client_key"
|
||||
value={createKey}
|
||||
/>
|
||||
{Object.values(errors).map(
|
||||
(error, index) => (
|
||||
<p
|
||||
key={index}
|
||||
role="alert"
|
||||
className="text-sm text-red-700"
|
||||
>
|
||||
{String(error)}
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
<Fields prefix="new-client" />
|
||||
<Button type="submit" disabled={processing}>
|
||||
Registar cliente
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Form>
|
||||
</Panel>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
+50
-22
@@ -16,8 +16,8 @@ const areas = [
|
||||
description:
|
||||
'Registe necessidades e acompanhe as decisões de cada departamento.',
|
||||
icon: ClipboardList,
|
||||
href: '/consulta/requisicoes',
|
||||
label: 'Explorar requisições',
|
||||
href: '/login',
|
||||
label: 'Entrar para gerir requisições',
|
||||
step: '01',
|
||||
},
|
||||
{
|
||||
@@ -25,8 +25,8 @@ const areas = [
|
||||
description:
|
||||
'Compare propostas, fundamente a escolha e acompanhe as ordens de compra.',
|
||||
icon: Users,
|
||||
href: '/consulta/fornecedores',
|
||||
label: 'Explorar fornecedores',
|
||||
href: '/login',
|
||||
label: 'Entrar para gerir compras',
|
||||
step: '02',
|
||||
},
|
||||
{
|
||||
@@ -34,10 +34,37 @@ const areas = [
|
||||
description:
|
||||
'Confira as entregas, registe a qualidade e consulte as existências aceites.',
|
||||
icon: PackageCheck,
|
||||
href: '/consulta/recepcoes',
|
||||
label: 'Explorar recepção',
|
||||
href: '/login',
|
||||
label: 'Entrar para gerir o armazém',
|
||||
step: '03',
|
||||
},
|
||||
{
|
||||
title: 'Orçamento e finanças',
|
||||
description:
|
||||
'Controle dotações e acompanhe facturas, pagamentos registados e contabilidade.',
|
||||
icon: FileCheck2,
|
||||
href: '/login',
|
||||
label: 'Entrar para gerir finanças',
|
||||
step: '04',
|
||||
},
|
||||
{
|
||||
title: 'Importações',
|
||||
description:
|
||||
'Organize o dossiê e acompanhe os documentos aduaneiros e o suporte bancário.',
|
||||
icon: ClipboardList,
|
||||
href: '/login',
|
||||
label: 'Entrar para acompanhar importações',
|
||||
step: '05',
|
||||
},
|
||||
{
|
||||
title: 'Pessoas e contratações',
|
||||
description:
|
||||
'Acompanhe candidaturas, avaliações, selecção e formalização de contratos.',
|
||||
icon: Users,
|
||||
href: '/login',
|
||||
label: 'Entrar para gerir contratações',
|
||||
step: '06',
|
||||
},
|
||||
];
|
||||
|
||||
export default function Home() {
|
||||
@@ -48,7 +75,7 @@ export default function Home() {
|
||||
<header className="border-b">
|
||||
<div className="mx-auto flex max-w-7xl flex-wrap items-center justify-between gap-4 px-6 py-5 lg:px-10">
|
||||
<Link href="/" className="flex items-center gap-3">
|
||||
<span className="grid size-10 place-items-center rounded-xl bg-teal-800 text-lg font-semibold text-white">
|
||||
<span className="grid size-10 place-items-center rounded-xl bg-rose-600 text-lg font-semibold text-white">
|
||||
SGC
|
||||
</span>
|
||||
<div>
|
||||
@@ -72,10 +99,10 @@ export default function Home() {
|
||||
Início
|
||||
</Link>
|
||||
<Link
|
||||
href="/consulta"
|
||||
href="#areas-title"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
Demonstração
|
||||
Funcionalidades
|
||||
</Link>
|
||||
<Button asChild>
|
||||
<Link href="/login">
|
||||
@@ -102,9 +129,9 @@ export default function Home() {
|
||||
<p className="mt-6 max-w-xl text-base leading-7 text-muted-foreground">
|
||||
Um percurso organizado para a sua equipa:
|
||||
necessidades, fornecedores, prestadores,
|
||||
recrutamento, decisões e entregas. Escolha a
|
||||
área em que quer trabalhar ou conheça primeiro
|
||||
os exemplos de demonstração.
|
||||
recrutamento, decisões e entregas, ligados ao
|
||||
acompanhamento do orçamento e das finanças.
|
||||
Escolha a área em que quer trabalhar.
|
||||
</p>
|
||||
<div className="mt-8 flex flex-wrap gap-3">
|
||||
<Button
|
||||
@@ -112,21 +139,22 @@ export default function Home() {
|
||||
size="lg"
|
||||
className="bg-teal-800 text-white hover:bg-teal-900"
|
||||
>
|
||||
<Link href="/consulta">
|
||||
Explorar a demonstração{' '}
|
||||
<Link href="/login">
|
||||
Entrar na aplicação{' '}
|
||||
<ArrowRight className="size-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
<Button asChild size="lg" variant="outline">
|
||||
<Link href="/login">
|
||||
Aceder ao espaço de trabalho
|
||||
<Link href="#areas-title">
|
||||
Conhecer as funcionalidades
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
<p className="mt-5 flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<ShieldCheck className="size-4 shrink-0" />
|
||||
Demonstração com dados fictícios. O espaço de
|
||||
trabalho exige autenticação.
|
||||
O espaço de trabalho exige autenticação e
|
||||
apresenta os registos autorizados para o seu
|
||||
perfil.
|
||||
</p>
|
||||
</div>
|
||||
<div className="rounded-2xl border bg-muted/25 p-6 sm:p-8">
|
||||
@@ -201,10 +229,10 @@ export default function Home() {
|
||||
</h2>
|
||||
</div>
|
||||
<Link
|
||||
href="/consulta"
|
||||
href="/login"
|
||||
className="inline-flex items-center gap-2 text-sm font-medium text-teal-700 dark:text-teal-400"
|
||||
>
|
||||
Ver todos os módulos{' '}
|
||||
Aceder aos módulos{' '}
|
||||
<ArrowRight className="size-4" />
|
||||
</Link>
|
||||
</div>
|
||||
@@ -261,8 +289,8 @@ export default function Home() {
|
||||
</span>
|
||||
<span>
|
||||
Consulte no processo as decisões e o controlo
|
||||
orçamental. Documentos de desenvolvimento não
|
||||
autorizam compras reais.
|
||||
orçamental, com os acessos definidos para cada
|
||||
interveniente.
|
||||
</span>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
@@ -126,6 +126,8 @@ export default function PeopleIndex({
|
||||
insights,
|
||||
filters = {},
|
||||
company,
|
||||
clientMode = false,
|
||||
clients = [],
|
||||
}: {
|
||||
ready: boolean;
|
||||
availableKinds?: string[];
|
||||
@@ -133,6 +135,8 @@ export default function PeopleIndex({
|
||||
insights?: OperationalInsights | null;
|
||||
filters?: Filters;
|
||||
company?: { name: string };
|
||||
clientMode?: boolean;
|
||||
clients?: { id: number; code: string; name: string; version: number }[];
|
||||
administration?: { id: number; kind: string; status: string }[];
|
||||
formFields?: Record<string, Record<string, string>>;
|
||||
kinds: string[];
|
||||
@@ -144,12 +148,15 @@ export default function PeopleIndex({
|
||||
kind: string;
|
||||
status: string;
|
||||
closes_on: string;
|
||||
client?: { code: string; name: string };
|
||||
}[];
|
||||
links: { url: string | null; label: string; active: boolean }[];
|
||||
};
|
||||
}) {
|
||||
const form = useForm({
|
||||
operation_key: crypto.randomUUID(),
|
||||
client_id: '',
|
||||
client_version: '',
|
||||
kind:
|
||||
filters.kind && canPrepare.includes(filters.kind)
|
||||
? filters.kind
|
||||
@@ -182,8 +189,16 @@ export default function PeopleIndex({
|
||||
<div className="mx-auto max-w-6xl space-y-6 p-5 lg:p-8">
|
||||
<PageTitle
|
||||
eyebrow="Organização"
|
||||
title="Pessoas e contratações"
|
||||
description="Contratação de prestadores individuais e recrutamento de trabalhadores, com critérios próprios e decisão independente."
|
||||
title={
|
||||
clientMode
|
||||
? 'Contratações para clientes'
|
||||
: 'Pessoas e contratações'
|
||||
}
|
||||
description={
|
||||
clientMode
|
||||
? 'Processos da entidade cliente, conduzidos pela prestadora. A decisão final e a confirmação do contrato competem à Direcção da prestadora.'
|
||||
: 'Contratação de prestadores individuais e recrutamento de trabalhadores, com critérios próprios e decisão independente.'
|
||||
}
|
||||
action={
|
||||
ready ? (
|
||||
<ActionBar>
|
||||
@@ -440,6 +455,12 @@ export default function PeopleIndex({
|
||||
<strong>
|
||||
PES-{p.id} · {p.title}
|
||||
</strong>
|
||||
{p.client && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Cliente: {p.client.code} ·{' '}
|
||||
{p.client.name}
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
{kinds[p.kind]} ·{' '}
|
||||
{peopleStates[p.status] ?? p.status}{' '}
|
||||
@@ -485,7 +506,16 @@ export default function PeopleIndex({
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
form.transform((values) => ({
|
||||
...values,
|
||||
...Object.fromEntries(
|
||||
Object.entries(values).filter(
|
||||
([key]) =>
|
||||
clientMode ||
|
||||
![
|
||||
'client_id',
|
||||
'client_version',
|
||||
].includes(key),
|
||||
),
|
||||
),
|
||||
annex: {
|
||||
...values.annex,
|
||||
fields: Object.fromEntries(
|
||||
@@ -503,11 +533,93 @@ export default function PeopleIndex({
|
||||
},
|
||||
}));
|
||||
form.post('/pessoas', {
|
||||
onSuccess: () => form.reset(),
|
||||
onSuccess: () => {
|
||||
form.reset();
|
||||
form.setData(
|
||||
'operation_key',
|
||||
crypto.randomUUID(),
|
||||
);
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<FormErrors errors={form.errors} />
|
||||
{clientMode && (
|
||||
<div className="space-y-2 rounded-lg border p-4">
|
||||
<label
|
||||
className="grid gap-1"
|
||||
htmlFor="people-client"
|
||||
>
|
||||
Entidade cliente
|
||||
<select
|
||||
id="people-client"
|
||||
name="client_id"
|
||||
className={controlClass}
|
||||
value={form.data.client_id}
|
||||
required
|
||||
onChange={(event) => {
|
||||
const client =
|
||||
clients.find(
|
||||
(row) =>
|
||||
String(
|
||||
row.id,
|
||||
) ===
|
||||
event.target
|
||||
.value,
|
||||
);
|
||||
form.setData(
|
||||
(values) => ({
|
||||
...values,
|
||||
client_id:
|
||||
event.target
|
||||
.value,
|
||||
client_version:
|
||||
client
|
||||
? String(
|
||||
client.version,
|
||||
)
|
||||
: '',
|
||||
}),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<option value="">
|
||||
Escolher cliente
|
||||
</option>
|
||||
{clients.map((client) => (
|
||||
<option
|
||||
key={client.id}
|
||||
value={client.id}
|
||||
>
|
||||
{client.code} ·{' '}
|
||||
{client.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
A identificação do cliente fica
|
||||
preservada neste processo.{' '}
|
||||
<Link
|
||||
href="/empresa/clientes"
|
||||
className="underline"
|
||||
>
|
||||
Consultar cadastro de
|
||||
clientes
|
||||
</Link>
|
||||
</p>
|
||||
{clients.length === 0 && (
|
||||
<p
|
||||
role="status"
|
||||
className="text-sm"
|
||||
>
|
||||
Registe ou active um cliente
|
||||
no cadastro antes de
|
||||
preparar o processo.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<label className="block">
|
||||
Percurso
|
||||
<select
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { CandidateAvailability } from '@/components/candidate-availability';
|
||||
import { PeopleContractFormalization } from '@/components/people-contract-formalization';
|
||||
import type { AvailabilityLocation } from '@/components/candidate-availability';
|
||||
import { Head, Link, useForm, usePage } from '@inertiajs/react';
|
||||
import {
|
||||
@@ -26,6 +27,9 @@ type Process = {
|
||||
version: number;
|
||||
closes_on: string;
|
||||
rules: {
|
||||
client?: { code: string; name: string; version: number };
|
||||
provider?: { tenant_id: number; name: string };
|
||||
decision_authority?: string;
|
||||
submission_form?: {
|
||||
id: number;
|
||||
version: number;
|
||||
@@ -61,6 +65,10 @@ type Process = {
|
||||
starts_on: string;
|
||||
terms: string;
|
||||
status: string;
|
||||
signed_on?: string;
|
||||
signed_reference?: string;
|
||||
formalized_by?: number;
|
||||
signed_document?: { sha256: string; bytes: number };
|
||||
};
|
||||
};
|
||||
type Candidate = {
|
||||
@@ -104,6 +112,7 @@ const states: Record<string, string> = {
|
||||
selection_review: 'Selecção por conferir',
|
||||
selected: 'Selecção aprovada',
|
||||
contract_draft: 'Minuta contratual preparada',
|
||||
contract_formalized: 'Contrato formalizado',
|
||||
};
|
||||
const commands: Record<string, string> = {
|
||||
open: 'Conferir e abrir',
|
||||
@@ -531,6 +540,7 @@ export default function PeopleShow({
|
||||
canReview,
|
||||
canApprove = false,
|
||||
canContract = false,
|
||||
canFormalize = false,
|
||||
canManage = false,
|
||||
formFields = {},
|
||||
clarifications,
|
||||
@@ -546,6 +556,7 @@ export default function PeopleShow({
|
||||
canReview: boolean;
|
||||
canApprove?: boolean;
|
||||
canContract?: boolean;
|
||||
canFormalize?: boolean;
|
||||
canManage?: boolean;
|
||||
formFields?: Record<string, string>;
|
||||
clarifications?: ClarificationData;
|
||||
@@ -569,7 +580,12 @@ export default function PeopleShow({
|
||||
];
|
||||
const rows =
|
||||
p.selection &&
|
||||
['selection_review', 'selected', 'contract_draft'].includes(p.status)
|
||||
[
|
||||
'selection_review',
|
||||
'selected',
|
||||
'contract_draft',
|
||||
'contract_formalized',
|
||||
].includes(p.status)
|
||||
? p.selection.rows
|
||||
: candidates;
|
||||
return (
|
||||
@@ -593,6 +609,21 @@ export default function PeopleShow({
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
{p.rules.client && (
|
||||
<Panel
|
||||
title={`Cliente · ${p.rules.client.code} · ${p.rules.client.name}`}
|
||||
>
|
||||
<p className="text-sm">
|
||||
Prestadora: {p.rules.provider?.name}. A decisão
|
||||
final e a confirmação do contrato competem à
|
||||
Direcção da prestadora.
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Identificação do cliente preservada na versão{' '}
|
||||
{p.rules.client.version}.
|
||||
</p>
|
||||
</Panel>
|
||||
)}
|
||||
<Link className="underline" href="/pessoas">
|
||||
Voltar a Pessoas e contratações
|
||||
</Link>
|
||||
@@ -836,7 +867,11 @@ export default function PeopleShow({
|
||||
{p.contract && (
|
||||
<Panel
|
||||
id="people-report-contract"
|
||||
title="Minuta contratual — preparação interna"
|
||||
title={
|
||||
p.contract.status === 'formalized'
|
||||
? 'Contrato formalizado'
|
||||
: 'Minuta contratual — preparação interna'
|
||||
}
|
||||
>
|
||||
<p>
|
||||
{p.contract.reference} · início proposto{' '}
|
||||
@@ -845,13 +880,38 @@ export default function PeopleShow({
|
||||
<p className="whitespace-pre-wrap">
|
||||
{p.contract.terms}
|
||||
</p>
|
||||
<p className="mt-3 text-sm">
|
||||
Não comprova assinatura ou contratação concluída.
|
||||
</p>
|
||||
{p.contract.status === 'formalized' ? (
|
||||
<div className="mt-3 space-y-2 text-sm">
|
||||
<p>
|
||||
Assinatura: {p.contract.signed_on} ·{' '}
|
||||
{p.contract.signed_reference} · Confirmado
|
||||
pela direcção, pessoa #
|
||||
{p.contract.formalized_by}
|
||||
</p>
|
||||
<a
|
||||
className="underline"
|
||||
href={`/pessoas/${p.id}/contrato-assinado`}
|
||||
>
|
||||
Descarregar contrato assinado
|
||||
</a>
|
||||
</div>
|
||||
) : (
|
||||
<p className="mt-3 text-sm">
|
||||
Não comprova assinatura ou contratação
|
||||
concluída.
|
||||
</p>
|
||||
)}
|
||||
</Panel>
|
||||
)}
|
||||
<PeopleClarifications processId={p.id} data={clarifications} />
|
||||
<div className="space-y-6 print:hidden">
|
||||
{canFormalize && p.status === 'contract_draft' && (
|
||||
<PeopleContractFormalization
|
||||
key={`formalize-${p.version}`}
|
||||
id={p.id}
|
||||
version={p.version}
|
||||
/>
|
||||
)}
|
||||
{actions.map((command) => (
|
||||
<div
|
||||
id={`people-${command}`}
|
||||
|
||||
@@ -43,6 +43,11 @@
|
||||
</x-inertia::head>
|
||||
</head>
|
||||
<body class="font-sans antialiased">
|
||||
@if(config('app.demonstration'))
|
||||
<aside aria-label="Ambiente de demonstração" style="padding:8px 16px;background:#fff3cd;color:#513c06;text-align:center;font:14px system-ui">
|
||||
Empresa de exemplo · Dados fictícios · Sem pagamentos ou submissões externas
|
||||
</aside>
|
||||
@endif
|
||||
@if(app()->environment('payable-testing'))
|
||||
<nav aria-label="Avaliação local" style="padding:10px 20px;background:#e1f1eb;color:#183d35;font:16px system-ui"><a href="/avaliar">Explorar Compras / acesso de proprietário</a> · Ambiente de testes</nav>
|
||||
@endif
|
||||
|
||||
+13
-14
@@ -2,25 +2,24 @@
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Inertia\Inertia;
|
||||
|
||||
// Public visual consultation. No business records or authenticated identities.
|
||||
Route::inertia('proposta/principal', 'preview/principal', ['auth' => ['user' => null]])->name('preview.principal');
|
||||
Route::inertia('proposta/qualificacao', 'preview/qualification', ['auth' => ['user' => null]])->name('preview.qualification');
|
||||
Route::inertia('proposta/admissao', 'preview/admission', ['auth' => ['user' => null]])->name('preview.admission');
|
||||
Route::inertia('proposta/recomendacao', 'preview/recommendation', ['auth' => ['user' => null]])->name('preview.recommendation');
|
||||
// Preserve old links while using actual application permissions and records.
|
||||
$destinations = ['overview' => '/dashboard', 'requests' => '/requisicoes', 'suppliers' => '/fornecedores',
|
||||
'quotes' => '/requisicoes', 'conflicts' => '/conflitos', 'orders' => '/ordens', 'receipts' => '/recepcoes',
|
||||
'stock' => '/stock', 'operations' => '/stock/operacoes', 'equipment' => '/equipamentos', 'invoices' => '/facturas',
|
||||
'bank' => '/fornecedores', 'payments' => '/pagamentos', 'reinforcements' => '/orcamentos',
|
||||
'investment' => '/regras-investimento', 'appearance' => '/settings/appearance'];
|
||||
foreach (['principal', 'qualificacao', 'admissao', 'recomendacao'] as $stage) {
|
||||
Route::redirect('proposta/'.$stage, $stage === 'principal' ? '/dashboard' : '/requisicoes')->name('preview.'.$stage);
|
||||
}
|
||||
|
||||
Route::get('consulta', function (Request $request) {
|
||||
Route::get('consulta', function (Request $request) use ($destinations) {
|
||||
$screen = $request->query('ecra', 'overview');
|
||||
$allowed = ['overview', 'requests', 'suppliers', 'quotes', 'conflicts', 'orders', 'receipts', 'stock', 'operations', 'equipment', 'invoices', 'bank', 'payments', 'reinforcements', 'investment', 'appearance'];
|
||||
|
||||
return Inertia::render('preview/index', [
|
||||
'auth' => ['user' => null],
|
||||
'initialScreen' => in_array($screen, $allowed, true) ? $screen : 'overview',
|
||||
]);
|
||||
return redirect(is_string($screen) ? ($destinations[$screen] ?? '/dashboard') : '/dashboard');
|
||||
})->name('preview');
|
||||
|
||||
Route::get('consulta/{screen}', function (string $screen) {
|
||||
Route::get('consulta/{screen}', function (string $screen) use ($destinations) {
|
||||
$screens = ['requisicoes' => 'requests', 'fornecedores' => 'suppliers', 'cotacoes' => 'quotes', 'conflitos' => 'conflicts', 'ordens' => 'orders', 'recepcoes' => 'receipts', 'stock' => 'stock', 'aparencia' => 'appearance'];
|
||||
$screens['operacoes-stock'] = 'operations';
|
||||
$screens['equipamentos'] = 'equipment';
|
||||
@@ -31,5 +30,5 @@ Route::get('consulta/{screen}', function (string $screen) {
|
||||
$screens['investimento'] = 'investment';
|
||||
abort_unless(isset($screens[$screen]), 404);
|
||||
|
||||
return Inertia::render('preview/index', ['auth' => ['user' => null], 'initialScreen' => $screens[$screen]]);
|
||||
return redirect($destinations[$screens[$screen]]);
|
||||
})->name('preview.screen');
|
||||
|
||||
+8
-1
@@ -6,6 +6,7 @@ use App\Http\Controllers\AuditMetadataController;
|
||||
use App\Http\Controllers\AutomaticPurchaseController;
|
||||
use App\Http\Controllers\BudgetController;
|
||||
use App\Http\Controllers\BudgetReinforcementController;
|
||||
use App\Http\Controllers\BusinessClientController;
|
||||
use App\Http\Controllers\CandidatePortalController;
|
||||
use App\Http\Controllers\CapitalRegisterController;
|
||||
use App\Http\Controllers\CommonFinanceAdministrationController;
|
||||
@@ -97,8 +98,9 @@ Route::get('/', function (Request $request) {
|
||||
return redirect('/dashboard');
|
||||
}
|
||||
|
||||
return inertia('home', ['auth' => ['user' => null]]);
|
||||
return redirect($request->user('web') !== null ? '/dashboard' : '/login');
|
||||
})->name('home');
|
||||
Route::get('apresentacao', fn () => inertia('home', ['auth' => ['user' => null]]))->name('presentation');
|
||||
require __DIR__.'/preview.php';
|
||||
|
||||
Route::get('candidaturas/{company}/divisao-administrativa', [CandidatePortalController::class, 'geography'])->whereNumber('company')->middleware('throttle:60,1');
|
||||
@@ -122,6 +124,9 @@ Route::post('candidaturas/{company}/sair', [CandidatePortalController::class, 'l
|
||||
Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(function () {
|
||||
Route::post('contexto', [WorkContextController::class, 'select'])->name('work-context.select');
|
||||
Route::get('dashboard', [RequisitionController::class, 'dashboard'])->name('dashboard');
|
||||
Route::get('empresa/clientes', [BusinessClientController::class, 'index']);
|
||||
Route::post('empresa/clientes', [BusinessClientController::class, 'store']);
|
||||
Route::patch('empresa/clientes/{client}', [BusinessClientController::class, 'update'])->whereNumber('client');
|
||||
Route::get('empresa/iniciar', [CompanyController::class, 'setup'])->name('company.setup');
|
||||
Route::post('empresa/iniciar', [CompanyController::class, 'store'])->name('company.store');
|
||||
|
||||
@@ -228,6 +233,8 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
|
||||
Route::post('auditoria/privada', [PrivateAuditController::class, 'store']);
|
||||
Route::get('auditoria/privada/{export}/download', [PrivateAuditController::class, 'download']);
|
||||
Route::get('pessoas/{process}/dossier.json', [PeopleHiringController::class, 'dossier'])->whereNumber('process');
|
||||
Route::post('pessoas/{process}/formalizar', [PeopleHiringController::class, 'formalize'])->whereNumber('process');
|
||||
Route::get('pessoas/{process}/contrato-assinado', [PeopleHiringController::class, 'signedContract'])->whereNumber('process');
|
||||
Route::post('pessoas/{process}/{command}', [PeopleHiringController::class, 'command'])->whereNumber('process')->whereIn('command', ['open', 'apply', 'close', 'evaluate', 'select', 'confirm', 'contract']);
|
||||
Route::get('administracao/parametrizacao', [OrganizationConfigurationController::class, 'index'])->name('organization.parameters');
|
||||
Route::post('administracao/parametrizacao/{command}', [OrganizationConfigurationController::class, 'command'])->whereIn('command', ['profile', 'user', 'assign', 'activate', 'rules', 'tax', 'comparison', 'intelligence', 'ai_plan', 'work_contexts', 'company_details', 'approval_levels']);
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Backup, isolated recovery and atomic selection of the expressly authorised synthetic demo."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import secrets
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
|
||||
def run(args, **kwargs):
|
||||
result = subprocess.run(args, text=True, capture_output=True, **kwargs)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"Command failed: {args[0]} {args[1:3]}\n{result.stderr[-1200:]}\n{result.stdout[-1200:]}")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def sql(database, statement):
|
||||
return run(['runuser', '-u', 'postgres', '--', 'psql', '-X', '-v', 'ON_ERROR_STOP=1', '-At', '-d', database, '-c', statement]).strip()
|
||||
|
||||
|
||||
def frames(database):
|
||||
tables = sql(database, "SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename").splitlines()
|
||||
result = {}
|
||||
for table in tables:
|
||||
assert table.replace('_', '').isalnum()
|
||||
result[table] = sql(database, 'SELECT md5(COALESCE(string_agg(j,chr(10) ORDER BY j),\'\')) FROM (SELECT row_to_json(t)::text AS j FROM "'+table+'" t) s')
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
assert os.geteuid() == 0 and sys.argv[1] == '--activate-authorized-synthetic'
|
||||
base = Path('/var/www/compras-deploy')
|
||||
demo = base / 'demonstration-20261129'
|
||||
release = base / 'releases/presentation-20261129'
|
||||
previous = Path((demo / 'previous-release.txt').read_text())
|
||||
assert (base / 'current').resolve() == previous
|
||||
assert json.loads((demo / 'evidence-check.json').read_text())['state'] == 'passed'
|
||||
finance = run(['php', 'scripts/check-public-demo-finance.php', '--read-only'], cwd=release)
|
||||
assert json.loads(finance)['state'] == 'passed'
|
||||
(demo / 'finance-check.json').write_text(finance)
|
||||
http = run(['python3', '/root/check-public-demonstration.py', '--check-authorized-synthetic'])
|
||||
assert json.loads(http)['state'] == 'passed'
|
||||
(demo / 'staging-http-check.json').write_text(http)
|
||||
backup = Path('/var/backups/compras-presentation-20261129')
|
||||
assert not backup.exists(), 'Do not overwrite an existing deployment backup'
|
||||
backup.mkdir(mode=0o700)
|
||||
shutil.copy2(previous / '.env', backup / 'previous.env.private')
|
||||
(backup / 'previous-release.txt').write_text(str(previous))
|
||||
previous_hash = hashlib.sha256((previous / '.env').read_bytes()).hexdigest()
|
||||
for database, name in [('compras_db', 'previous.dump'), ('compras_demo_20261129', 'demonstration.dump')]:
|
||||
with (backup / name).open('xb') as out:
|
||||
result = subprocess.run(['runuser', '-u', 'postgres', '--', 'pg_dump', '-Fc', '-d', database], stdout=out, stderr=subprocess.PIPE)
|
||||
assert result.returncode == 0, result.stderr.decode()[:500]
|
||||
run(['pg_restore', '--list', str(backup / name)])
|
||||
original = frames('compras_demo_20261129')
|
||||
recovery = 'compras_demo_recovery_20261129'
|
||||
assert not sql('postgres', f"SELECT datname FROM pg_database WHERE datname='{recovery}'")
|
||||
recovery_role = 'compras_demo_recovery_app_20261129'
|
||||
recovery_password = secrets.token_hex(32)
|
||||
sql('postgres', f"CREATE ROLE {recovery_role} LOGIN PASSWORD '{recovery_password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS")
|
||||
run(['runuser', '-u', 'postgres', '--', 'createdb', '-O', recovery_role, recovery])
|
||||
try:
|
||||
restore_env = {**os.environ, 'PGPASSWORD': recovery_password}
|
||||
with (backup / 'demonstration.dump').open('rb') as source:
|
||||
restored = subprocess.run(['pg_restore', '-h', '127.0.0.1', '-U', recovery_role, '--no-owner', '--no-acl', '-d', recovery],
|
||||
stdin=source, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=restore_env)
|
||||
assert restored.returncode == 0, restored.stderr.decode()[:800]
|
||||
assert frames(recovery) == original, 'Synthetic backup recovery mismatch'
|
||||
recovery_env = {**os.environ, 'DB_DATABASE': recovery, 'DB_USERNAME': recovery_role, 'DB_PASSWORD': recovery_password,
|
||||
'APP_CONFIG_CACHE': str(demo / 'storage/framework/cache/recovery-config.php'),
|
||||
'COMPRAS_RUNTIME_ENABLED': 'false', 'COMPRAS_RUNTIME_PREPARE_ONLY': 'true', 'COMPRAS_RUNTIME_INSTALLATION_ID': str(uuid.uuid4())}
|
||||
run(['php', 'artisan', 'compras:runtime:prepare', '--expected-database='+recovery, '--expected-role='+recovery_role,
|
||||
'--operator=Tempo presentation recovery', '--reason=Explicit synthetic restoration and new installation binding verification', '--rebind', '--apply'], cwd=release, env=recovery_env)
|
||||
rebound = frames(recovery)
|
||||
assert {k:v for k,v in rebound.items() if k != 'compras_runtime_installations'} == {k:v for k,v in original.items() if k != 'compras_runtime_installations'}
|
||||
recovery_env.update({'COMPRAS_RUNTIME_ENABLED': 'true', 'COMPRAS_RUNTIME_PREPARE_ONLY': 'false'})
|
||||
boot = "require 'vendor/autoload.php';$a=require 'bootstrap/app.php';$a->make(Illuminate\\Contracts\\Console\\Kernel::class)->bootstrap();$r=app(App\\Services\\StandaloneRuntime::class);foreach($r::FEATURES as $f){if(!$r->feature($f,Illuminate\\Support\\Facades\\DB::connection()))throw new LogicException('Recovery capability unavailable');}echo '24 recovery capabilities verified';"
|
||||
assert run(['php', '-r', boot], cwd=release, env=recovery_env) == '24 recovery capabilities verified'
|
||||
finally:
|
||||
run(['runuser', '-u', 'postgres', '--', 'dropdb', recovery])
|
||||
sql('postgres', f'DROP ROLE {recovery_role}')
|
||||
units = Path('/etc/systemd/system')
|
||||
service = units / 'compras-demo-operations.service'
|
||||
timer = units / 'compras-demo-operations.timer'
|
||||
assert not service.exists() and not timer.exists(), 'Do not replace an existing service'
|
||||
service.write_text(f'''[Unit]
|
||||
Description=Compras synthetic presentation recurring operations
|
||||
After=postgresql.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=www-data
|
||||
Group=www-data
|
||||
WorkingDirectory={release}
|
||||
ExecStart=/usr/bin/php artisan sgc:approval-deadlines-tick
|
||||
ExecStart=/usr/bin/php artisan sgc:replenishment-tick
|
||||
TimeoutStartSec=60
|
||||
UMask=0077
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ReadWritePaths={demo}/storage
|
||||
''')
|
||||
timer.write_text('''[Unit]
|
||||
Description=Compras synthetic presentation minute observation
|
||||
|
||||
[Timer]
|
||||
OnBootSec=60
|
||||
OnUnitActiveSec=60
|
||||
Unit=compras-demo-operations.service
|
||||
AccuracySec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
''')
|
||||
run(['systemd-analyze', 'verify', str(service), str(timer)])
|
||||
run(['systemctl', 'daemon-reload'])
|
||||
run(['systemctl', 'start', service.name])
|
||||
before_restart = frames('compras_demo_20261129')
|
||||
run(['systemctl', 'restart', service.name])
|
||||
after_restart = frames('compras_demo_20261129')
|
||||
changed = [name for name in before_restart if before_restart[name] != after_restart[name]]
|
||||
assert set(changed).issubset({'replenishment_work'}), changed
|
||||
assert run(['systemctl', 'show', service.name, '-p', 'ExecMainStatus', '--value']).strip() == '0'
|
||||
assert hashlib.sha256((previous / '.env').read_bytes()).hexdigest() == previous_hash
|
||||
assert (base / 'current').resolve() == previous
|
||||
temporary = base / 'current.presentation.tmp'
|
||||
assert not temporary.exists() and not temporary.is_symlink()
|
||||
temporary.symlink_to(release, target_is_directory=True)
|
||||
os.replace(temporary, base / 'current')
|
||||
try:
|
||||
run(['systemctl', 'enable', '--now', timer.name])
|
||||
public = run(['python3', '/root/check-public-demonstration.py', '--check-authorized-synthetic', 'https://compras.tempo.co.mz'])
|
||||
assert json.loads(public)['state'] == 'passed'
|
||||
(demo / 'public-http-check.json').write_text(public)
|
||||
except BaseException:
|
||||
run(['systemctl', 'disable', '--now', timer.name])
|
||||
temporary.symlink_to(previous, target_is_directory=True)
|
||||
os.replace(temporary, base / 'current')
|
||||
raise
|
||||
result = {'state': 'passed', 'domain': 'https://compras.tempo.co.mz', 'release': str(release), 'previous_release': str(previous),
|
||||
'synthetic_database': 'compras_demo_20261129', 'previous_database_unchanged_by_deployment': True, 'previous_env_hash_preserved': previous_hash,
|
||||
'backup': str(backup), 'synthetic_recovery_tables_exact': len(original), 'recovery_database_removed': True,
|
||||
'recovery_new_native_binding_and_24_capabilities_verified': True, 'recovery_business_tables_preserved_after_rebind': True,
|
||||
'worker_runs_as': 'www-data', 'worker_restart_exit': 0, 'business_tables_unchanged_by_worker_restart': True,
|
||||
'worker_restart_changed_tables': changed, 'interactive_windows_session_required': False, 'timer_enabled': True,
|
||||
'host_reboot_executed': False, 'jue_or_bank_external_execution': False}
|
||||
(demo / 'activation.json').write_text(json.dumps(result, indent=2))
|
||||
print(json.dumps(result, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Apply the existing local functional capabilities to the same public product."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
root = Path('/var/www/compras-deploy/current').resolve()
|
||||
assert root == Path('/var/www/compras-deploy/releases/presentation-20261129')
|
||||
snapshot = json.loads(subprocess.check_output(['/usr/bin/php', str(root/'scripts/compare-compras-installation.php'), '--public-read-only']))
|
||||
assert all(snapshot['history_schema'].values()) and len(snapshot['features']) == 24 and all(snapshot['features'].values())
|
||||
env = (root/'.env').resolve()
|
||||
assert env == Path('/var/www/compras-deploy/demonstration-20261129/.env')
|
||||
backup = Path('/var/backups/compras-presentation-20261129/unified-functional-flags')
|
||||
backup.mkdir(mode=0o700, exist_ok=False)
|
||||
shutil.copy2(env, backup/'selected.env.private')
|
||||
(backup/'selected.env.private').chmod(0o600)
|
||||
updates = {'COMMON_PAYABLES_ENABLED': 'true', 'COMMON_PAYABLES_HISTORY_ENABLED': 'true', 'SGC_GEOGRAPHY_ENABLED': 'true',
|
||||
'SGC_PROCUREMENT_FINANCE_SEARCH_ENABLED': 'true', 'SGC_REQUISITION_APPROVAL_LEVELS_ENABLED': 'true',
|
||||
'SGC_PUBLIC_NAVIGATION': 'false'}
|
||||
lines = env.read_text().splitlines()
|
||||
for key, value in updates.items():
|
||||
matches = [i for i, line in enumerate(lines) if line.startswith(key+'=')]
|
||||
assert len(matches) <= 1
|
||||
if matches:
|
||||
lines[matches[0]] = key+'='+value
|
||||
else:
|
||||
lines.append(key+'='+value)
|
||||
temp = env.with_name(env.name+'.functional-next')
|
||||
temp.write_text('\n'.join(lines)+'\n')
|
||||
attrs = env.stat()
|
||||
temp.chmod(attrs.st_mode & 0o777)
|
||||
os.chown(temp, attrs.st_uid, attrs.st_gid)
|
||||
os.replace(temp, env)
|
||||
try:
|
||||
subprocess.run(['runuser', '-u', 'www-data', '--', '/usr/bin/php', 'artisan', 'config:cache'], cwd=root, check=True)
|
||||
after = json.loads(subprocess.check_output(['/usr/bin/php', str(root/'scripts/compare-compras-installation.php'), '--public-read-only']))
|
||||
for key in ['common-payables.enabled', 'common-payables.history_enabled', 'geography.enabled',
|
||||
'procurement_search.finance_metadata_enabled', 'requisition_approval.enabled']:
|
||||
assert after['deployment_flags'][key] is True
|
||||
assert after['deployment_flags']['public_navigation.enabled'] is False
|
||||
except BaseException:
|
||||
shutil.copyfile(backup/'selected.env.private', env)
|
||||
subprocess.run(['runuser', '-u', 'www-data', '--', '/usr/bin/php', 'artisan', 'config:cache'], cwd=root, check=True)
|
||||
raise
|
||||
proof = {'state': 'passed', 'settings_aligned': updates, 'company_rules_and_permissions_changed': False,
|
||||
'business_data_changed': False, 'original_archives_and_runtime_components_preserved': True,
|
||||
'backup': str(backup), 'anonymous_business_pages': 'normal authenticated application access'}
|
||||
(backup/'result.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof))
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\OrganizationConfiguration;
|
||||
use App\Services\WorkContext;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
require dirname(__DIR__).'/vendor/autoload.php';
|
||||
$app = require dirname(__DIR__).'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
if (($argv[1] ?? '') !== '--align-authorized-synthetic' || config('app.demonstration') !== true
|
||||
|| DB::connection()->getDatabaseName() !== 'compras_demo_20261129') {
|
||||
throw new LogicException('Only the authorised public sample company may be aligned.');
|
||||
}
|
||||
$backup = '/var/backups/compras-presentation-20261129/context-alignment';
|
||||
if (! is_file($backup.'/selected.env.private') || ! is_file($backup.'/database.dump')) {
|
||||
throw new LogicException('Private recovery files required before changing configuration.');
|
||||
}
|
||||
$result = DB::transaction(function () use ($backup): array {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ');
|
||||
$actor = User::query()->where('email', 'admin@demo.compras.tempo.co.mz')->sole();
|
||||
if ($actor->tenant_id !== 2) {
|
||||
throw new LogicException('Unexpected company.');
|
||||
}
|
||||
auth()->guard()->setUser($actor);
|
||||
$company = Tenant::query()->whereKey(2)->lockForUpdate()->firstOrFail();
|
||||
if ($company->work_context_policy !== null) {
|
||||
throw new LogicException('Preserve an already configured company.');
|
||||
}
|
||||
$options = array_keys(WorkContext::OPTIONS);
|
||||
if (app(WorkContext::class)->purchased($actor) !== $options) {
|
||||
throw new LogicException('The selected installation must expose the same four pilot contexts.');
|
||||
}
|
||||
$profiles = DB::table('organization_profiles')->where('tenant_id', 2)->orderBy('id')->get();
|
||||
$excluded = ['tenants', 'organization_profiles', 'organization_access', 'audit_logs',
|
||||
'sessions', 'cache', 'cache_locks', 'jobs', 'failed_jobs', 'job_batches'];
|
||||
$tables = collect(DB::select('select tablename from pg_tables where schemaname=current_schema()'))->pluck('tablename')->diff($excluded)->sort()->values();
|
||||
$digest = static function () use ($tables): array {
|
||||
$values = [];
|
||||
foreach ($tables as $table) {
|
||||
$rows = DB::table($table)->get()->map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR))->sort()->values()->all();
|
||||
$values[$table] = hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
return $values;
|
||||
};
|
||||
$before = $digest();
|
||||
file_put_contents($backup.'/contexts.before.private.json', json_encode(['company' => $company->toArray(), 'profiles' => $profiles->all(), 'protected_table_hashes' => $before], JSON_THROW_ON_ERROR));
|
||||
chmod($backup.'/contexts.before.private.json', 0600);
|
||||
$service = app(OrganizationConfiguration::class);
|
||||
foreach ($profiles as $profile) {
|
||||
$service->execute($actor, 'profile', ['version' => DB::table('organization_access')->where('tenant_id', 2)->value('version'),
|
||||
'id' => $profile->id, 'name' => $profile->name, 'permissions' => json_decode($profile->permissions, true, 32, JSON_THROW_ON_ERROR),
|
||||
'work_contexts' => $options, 'reason' => 'Reposicao expressamente pedida do painel do piloto na empresa sintetica, sem alterar competencias.']);
|
||||
}
|
||||
$service->execute($actor, 'work_contexts', ['version' => DB::table('organization_access')->where('tenant_id', 2)->value('version'),
|
||||
'enabled' => $options, 'confirm' => true, 'reason' => 'Aplicar o mesmo painel de contextos do piloto, por pedido expresso do proprietario.']);
|
||||
foreach ($profiles as $profile) {
|
||||
$after = DB::table('organization_profiles')->where('id', $profile->id)->first();
|
||||
if ($after->name !== $profile->name || json_decode($after->permissions, true) !== json_decode($profile->permissions, true)
|
||||
|| json_decode($after->work_contexts, true) !== $options) {
|
||||
throw new LogicException('Profile competencies must remain unchanged.');
|
||||
}
|
||||
}
|
||||
if ($digest() !== $before) {
|
||||
throw new LogicException('An unrelated table changed; roll back the entire alignment.');
|
||||
}
|
||||
$available = app(WorkContext::class)->available($actor->fresh());
|
||||
if ($available !== $options) {
|
||||
throw new LogicException('Administration must see the same four pilot choices.');
|
||||
}
|
||||
|
||||
return ['state' => 'passed', 'company_id' => 2, 'context_options' => $options, 'administration_available_contexts' => $available,
|
||||
'profiles_aligned' => $profiles->count(), 'profile_permissions_and_names_preserved' => true,
|
||||
'unrelated_tables_preserved' => count($before), 'native_configuration_commands' => true,
|
||||
'operational_flags_preserved' => array_map(fn ($v) => $v['operational'], WorkContext::OPTIONS),
|
||||
'original_pilot_or_previous_public_database_changed' => false];
|
||||
});
|
||||
file_put_contents($backup.'/result.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Assemble one immutable Compras delivery, without settings, business data or credentials."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import stat
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
root = Path.cwd().resolve()
|
||||
manifest_bytes = (root / 'compras-release.json').read_bytes()
|
||||
manifest = json.loads(manifest_bytes)
|
||||
assert len(sys.argv) == 6, 'frontend-directory output.zip finance-root inventory-root cancellation-root'
|
||||
frontend = Path(sys.argv[1]).resolve()
|
||||
output = Path(sys.argv[2]).resolve()
|
||||
assert not output.exists(), 'Never overwrite a frozen delivery'
|
||||
entries = {'compras-release.json': manifest_bytes}
|
||||
exact = set(manifest.get('exact_source_files', []))
|
||||
|
||||
|
||||
def add(name, source, expected, normalise=False):
|
||||
assert not Path(name).is_absolute() and '..' not in Path(name).parts and name not in entries
|
||||
assert source.is_file() and not source.is_symlink()
|
||||
data = source.read_bytes()
|
||||
assert hashlib.sha256(data.replace(b'\r\n', b'\n') if normalise else data).hexdigest() == expected, name
|
||||
entries[name] = data
|
||||
|
||||
|
||||
for name, digest in manifest['source_files'].items():
|
||||
add(name, root / name, digest, manifest.get('source_eol') == 'lf' and name not in exact)
|
||||
add('public/build/manifest.json', frontend / 'manifest.json', manifest['frontend']['manifest_sha256'])
|
||||
add('public/build/fonts-manifest.json', frontend / 'fonts-manifest.json', manifest['frontend']['fonts_manifest_sha256'])
|
||||
for name, digest in manifest['frontend']['files'].items():
|
||||
add('public/build/'+name, frontend / name, digest)
|
||||
for definition, label, directory in zip(manifest['components'], ['finance', 'inventory', 'cancellation'], sys.argv[3:], strict=True):
|
||||
component = Path(directory).resolve()
|
||||
add('runtime/'+label+'/manifest.json', component / 'manifest.json', definition['manifest_sha256'])
|
||||
definition = json.loads((component / 'manifest.json').read_bytes())
|
||||
files = definition['files']
|
||||
files = {entry['file']: entry['sha256'] for entry in files} if isinstance(files, list) else files
|
||||
for name, digest in files.items():
|
||||
assert (component / name).resolve().is_relative_to(component)
|
||||
add('runtime/'+label+'/'+name, component / name, digest)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
with zipfile.ZipFile(output, 'x', zipfile.ZIP_DEFLATED) as archive:
|
||||
for directory in ['bootstrap/cache/', 'storage/app/private/', 'storage/app/public/', 'storage/framework/cache/data/', 'storage/framework/sessions/', 'storage/framework/views/', 'storage/logs/']:
|
||||
entry = zipfile.ZipInfo(directory); entry.external_attr = (stat.S_IFDIR | 0o750) << 16
|
||||
archive.writestr(entry, b'')
|
||||
for name, data in sorted(entries.items()):
|
||||
entry = zipfile.ZipInfo(name); entry.external_attr = (stat.S_IFREG | 0o644) << 16
|
||||
archive.writestr(entry, data, compress_type=zipfile.ZIP_DEFLATED)
|
||||
proof = {'product': 'compras', 'release_id': manifest['release_id'], 'archive': str(output), 'files': len(entries),
|
||||
'sha256': hashlib.sha256(output.read_bytes()).hexdigest(), 'credentials_or_business_data': False}
|
||||
Path('docs/proofs/compras-release-artifact.json').write_text(json.dumps(proof, indent=2)+'\n', encoding='utf-8')
|
||||
print(json.dumps(proof))
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Private recovery delta for the single installed release, without exporting credentials."""
|
||||
from pathlib import Path
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import tarfile
|
||||
|
||||
root = Path('/var/www/compras-deploy/current').resolve()
|
||||
assert root == Path('/var/www/compras-deploy/releases/presentation-20261129')
|
||||
identity = json.loads((root/'compras-release.json').read_text())['release_id']
|
||||
assert identity == 'compras-a2711a98b34fceb3'
|
||||
destination = Path('/var/backups/compras-presentation-20261129/consolidation/current')
|
||||
destination.mkdir(mode=0o700, exist_ok=False)
|
||||
shutil.copy2((root/'.env').resolve(), destination/'selected.env.private')
|
||||
(destination/'selected.env.private').chmod(0o600)
|
||||
with (destination/'database.dump').open('xb') as stream:
|
||||
subprocess.run(['runuser', '-u', 'postgres', '--', 'pg_dump', '-Fc', '-d', 'compras_demo_20261129'], stdout=stream, check=True)
|
||||
subprocess.run(['pg_restore', '--list', str(destination/'database.dump')], stdout=subprocess.DEVNULL, check=True)
|
||||
subprocess.run(['tar', '-czf', str(destination/'storage.tar.gz'), '-C', str((root/'storage').resolve()), '.'], check=True)
|
||||
subprocess.run(['tar', '-czf', str(destination/'code.tar.gz'), '--exclude=./storage', '--exclude=./.env', '--exclude=./bootstrap/cache/config.php', '-C', str(root), '.'], check=True)
|
||||
private = (root/'storage').resolve()/'app/private'
|
||||
verified = 0
|
||||
with tarfile.open(destination/'storage.tar.gz') as archive:
|
||||
for source in private.rglob('*'):
|
||||
assert not source.is_symlink()
|
||||
if source.is_file():
|
||||
name = './'+str(source.relative_to((root/'storage').resolve()))
|
||||
assert hashlib.sha256(archive.extractfile(name).read()).hexdigest() == hashlib.sha256(source.read_bytes()).hexdigest()
|
||||
verified += 1
|
||||
for name in ['compras-operations.service', 'compras-operations.timer']:
|
||||
shutil.copy2(Path('/etc/systemd/system')/name, destination/name)
|
||||
shutil.copy2('/var/www/deploy/compras-tempo-deploy.sh', destination/'publisher.sh')
|
||||
proof = {'state': 'passed', 'release_id': identity, 'backup': str(destination), 'private_files_verified_in_backup': verified,
|
||||
'database_archive_readable': True, 'full_database_restore': 'prior final-backup.json, no schema delta',
|
||||
'hashes': {name: hashlib.sha256((destination/name).read_bytes()).hexdigest() for name in ['database.dump', 'storage.tar.gz', 'code.tar.gz']}}
|
||||
(destination/'result.json').write_text(json.dumps(proof, indent=2)+'\n')
|
||||
print(json.dumps(proof))
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Private final synthetic backup and recovery; no changes to the selected live installation."""
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import uuid
|
||||
|
||||
s = importlib.util.spec_from_file_location('activation', '/root/activate-public-demonstration.py')
|
||||
m = importlib.util.module_from_spec(s); s.loader.exec_module(m)
|
||||
assert os.geteuid() == 0 and sys.argv[1] == '--backup-authorized-synthetic'
|
||||
base = Path('/var/www/compras-deploy')
|
||||
demo = base / 'demonstration-20261129'
|
||||
release = base / 'releases/presentation-20261129'
|
||||
assert (base / 'current').resolve() == release
|
||||
backup = Path('/var/backups/compras-presentation-20261129/final')
|
||||
if backup.exists():
|
||||
assert '--resume-owned-backup' in sys.argv and not (demo / 'final-backup.json').exists(), 'Preserve completed recovery evidence'
|
||||
assert (backup / 'demonstration.env.private').read_bytes() == (demo / '.env').read_bytes()
|
||||
assert all((backup / name).is_file() for name in ['database.dump', 'storage.tar.gz', 'code.tar.gz'])
|
||||
m.run(['pg_restore', '--list', str(backup / 'database.dump')])
|
||||
else:
|
||||
backup.mkdir(mode=0o700)
|
||||
shutil.copy2(demo / '.env', backup / 'demonstration.env.private')
|
||||
os.chmod(backup / 'demonstration.env.private', 0o600)
|
||||
with (backup / 'database.dump').open('xb') as stream:
|
||||
result = subprocess.run(['runuser', '-u', 'postgres', '--', 'pg_dump', '-Fc', '-d', 'compras_demo_20261129'], stdout=stream, stderr=subprocess.PIPE)
|
||||
assert result.returncode == 0, result.stderr.decode()[:500]
|
||||
m.run(['tar', '-czf', str(backup / 'storage.tar.gz'), '-C', str(demo / 'storage'), '.'])
|
||||
m.run(['tar', '-czf', str(backup / 'code.tar.gz'), '--exclude=./storage', '--exclude=./.env', '--exclude=./bootstrap/cache/config.php', '-C', str(release), '.'])
|
||||
files = backup / 'recovered-storage'; files.mkdir(mode=0o700, exist_ok=True)
|
||||
verified_files = 0
|
||||
with tarfile.open(backup / 'storage.tar.gz') as archive:
|
||||
for member in archive.getmembers():
|
||||
assert not Path(member.name).is_absolute() and '..' not in Path(member.name).parts and (member.isfile() or member.isdir())
|
||||
target = files / member.name
|
||||
assert not target.is_symlink() and (target.resolve() == files.resolve() or target.resolve().is_relative_to(files.resolve()))
|
||||
if member.isfile() and target.exists():
|
||||
assert hashlib.sha256(target.read_bytes()).digest() == hashlib.sha256(archive.extractfile(member).read()).digest()
|
||||
archive.extractall(files)
|
||||
for member in archive.getmembers():
|
||||
if member.isfile():
|
||||
assert hashlib.sha256(archive.extractfile(member).read()).digest() == hashlib.sha256((files / member.name).read_bytes()).digest()
|
||||
verified_files += 1
|
||||
technical = {'sessions', 'cache', 'cache_locks', 'jobs', 'failed_jobs', 'job_batches', 'replenishment_work'}
|
||||
original = m.frames('compras_demo_20261129')
|
||||
recovery = 'compras_demo_final_recovery_20261129'
|
||||
role = 'compras_demo_final_recovery_app'
|
||||
password = secrets.token_hex(32)
|
||||
assert not m.sql('postgres', f"SELECT datname FROM pg_database WHERE datname='{recovery}'")
|
||||
m.sql('postgres', f"CREATE ROLE {role} LOGIN PASSWORD '{password}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS")
|
||||
m.run(['runuser', '-u', 'postgres', '--', 'createdb', '-O', role, recovery])
|
||||
try:
|
||||
with (backup / 'database.dump').open('rb') as source:
|
||||
restored = subprocess.run(['pg_restore', '-h', '127.0.0.1', '-U', role, '--no-owner', '--no-acl', '-d', recovery],
|
||||
stdin=source, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={**os.environ, 'PGPASSWORD': password})
|
||||
assert restored.returncode == 0, restored.stderr.decode()[:800]
|
||||
before = m.frames(recovery)
|
||||
assert {k:v for k,v in before.items() if k not in technical} == {k:v for k,v in original.items() if k not in technical}
|
||||
environment = {**os.environ, 'DB_DATABASE': recovery, 'DB_USERNAME': role, 'DB_PASSWORD': password,
|
||||
'APP_CONFIG_CACHE': str(demo / 'storage/framework/cache/final-recovery-config.php'),
|
||||
'COMPRAS_RUNTIME_ENABLED': 'false', 'COMPRAS_RUNTIME_PREPARE_ONLY': 'true', 'COMPRAS_RUNTIME_INSTALLATION_ID': str(uuid.uuid4())}
|
||||
m.run(['php', 'artisan', 'compras:runtime:prepare', '--expected-database='+recovery, '--expected-role='+role,
|
||||
'--operator=Tempo final presentation recovery', '--reason=Final synthetic presentation recovery with preserved original documents', '--rebind', '--apply'], cwd=release, env=environment)
|
||||
after = m.frames(recovery)
|
||||
assert {k:v for k,v in after.items() if k != 'compras_runtime_installations'} == {k:v for k,v in before.items() if k != 'compras_runtime_installations'}
|
||||
environment.update({'COMPRAS_RUNTIME_ENABLED': 'true', 'COMPRAS_RUNTIME_PREPARE_ONLY': 'false'})
|
||||
boot = "require 'vendor/autoload.php';$a=require 'bootstrap/app.php';$a->make(Illuminate\\Contracts\\Console\\Kernel::class)->bootstrap();$r=app(App\\Services\\StandaloneRuntime::class);foreach($r::FEATURES as $f){if(!$r->feature($f,Illuminate\\Support\\Facades\\DB::connection()))throw new LogicException('Recovery capability unavailable');}echo '24 recovery capabilities verified';"
|
||||
assert m.run(['php', '-r', boot], cwd=release, env=environment) == '24 recovery capabilities verified'
|
||||
finally:
|
||||
m.run(['runuser', '-u', 'postgres', '--', 'dropdb', recovery])
|
||||
m.sql('postgres', 'DROP ROLE '+role)
|
||||
assert (base / 'current').resolve() == release
|
||||
proof = {'state': 'passed', 'private_backup': str(backup), 'database_tables': len(before),
|
||||
'business_tables_equal_after_restore': len([k for k in before if k not in technical]), 'all_tables_preserved_after_native_rebind_except_installation_history': True,
|
||||
'restored_capabilities': 24, 'storage_files_restored_and_hashed': verified_files, 'temporary_database_and_role_removed': True,
|
||||
'live_configuration_or_database_replaced': False, 'hashes': {name: hashlib.sha256((backup/name).read_bytes()).hexdigest()
|
||||
for name in ['database.dump', 'storage.tar.gz', 'code.tar.gz']}}
|
||||
(demo / 'final-backup.json').write_text(json.dumps(proof, indent=2))
|
||||
print(json.dumps(proof, indent=2))
|
||||
@@ -0,0 +1,48 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const frontend = process.argv[2];
|
||||
assert.ok(frontend, 'Provide the verified frontend build directory.');
|
||||
const roots = ['app', 'bootstrap', 'config', 'database', 'resources', 'routes', 'integrations', 'packages', 'public',
|
||||
'composer.json', 'composer.lock', 'package.json', 'package-lock.json', 'artisan', '.gitattributes', '.env.example',
|
||||
'scripts/verify-compras-release.php', 'scripts/build-compras-release.mjs', 'scripts/archive-compras-release.py', 'scripts/deployment/compras-tempo-deploy.sh'];
|
||||
const listed = ['git', 'ls-files'];
|
||||
const tracked = execFileSync(listed[0], [...listed.slice(1), '-z', '--', ...roots], { encoding: 'utf8' }).split('\0');
|
||||
const added = execFileSync('git', ['ls-files', '--others', '--exclude-standard', '-z', '--', ...roots], { encoding: 'utf8' }).split('\0');
|
||||
const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
|
||||
const source = {};
|
||||
const exact = [];
|
||||
for (const file of [...new Set([...tracked, ...added])].filter(Boolean).sort()) {
|
||||
if (file.startsWith('bootstrap/cache/') || file.startsWith('public/build/')) continue;
|
||||
const info = await fs.lstat(file);
|
||||
if (!info.isFile() || info.isSymbolicLink()) continue;
|
||||
const bytes = await fs.readFile(file);
|
||||
const pinned = file.startsWith('packages/budget-control/') || file.startsWith('packages/payables/')
|
||||
|| file === 'resources/data/geography/cartografia-moz.json' || bytes.includes(0);
|
||||
if (pinned) exact.push(file);
|
||||
source[file] = hash(pinned ? bytes : Buffer.from(bytes.toString('utf8').replaceAll('\r\n', '\n')));
|
||||
}
|
||||
const buildBytes = await fs.readFile(path.join(frontend, 'manifest.json'));
|
||||
const build = JSON.parse(buildBytes);
|
||||
const assets = {};
|
||||
for (const entry of Object.values(build)) {
|
||||
for (const file of [entry.file, ...(entry.css ?? []), ...(entry.assets ?? [])]) {
|
||||
assert.ok(file.startsWith('assets/') && !file.includes('..'));
|
||||
assets[file] = hash(await fs.readFile(path.join(frontend, file)));
|
||||
}
|
||||
}
|
||||
const manifest = { contract: 'compras.release.v1', product: 'compras', source_eol: 'lf', exact_source_files: exact,
|
||||
source_files: source, frontend: { manifest_sha256: hash(buildBytes), entry: build['resources/js/app.tsx'].file,
|
||||
fonts_manifest_sha256: hash(await fs.readFile(path.join(frontend, 'fonts-manifest.json'))),
|
||||
files: Object.fromEntries(Object.entries(assets).sort(([a], [b]) => a.localeCompare(b, 'en'))) },
|
||||
components: [
|
||||
{ setting: 'COMPRAS_RUNTIME_ROOT', manifest_sha256: '80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7' },
|
||||
{ setting: 'COMPRAS_INVENTORY_ROOT', manifest_sha256: '8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd' },
|
||||
{ setting: 'COMPRAS_ORDER_CANCELLATION_ROOT', manifest_sha256: '52df7927aa2689598ce1be92de1483694347a696245704abb9e3925db7abfc0f' },
|
||||
] };
|
||||
manifest.release_id = 'compras-'+hash(JSON.stringify(manifest)).slice(0, 16);
|
||||
await fs.writeFile('compras-release.json', JSON.stringify(manifest, null, 2)+'\n');
|
||||
console.log(JSON.stringify({ release_id: manifest.release_id, source_files: Object.keys(source).length, asset_files: Object.keys(assets).length }));
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user