commit compras3 2711
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-27 18:56:24 +02:00
parent 930064269e
commit 9cf9764710
87 changed files with 2856 additions and 195 deletions
+43
View File
@@ -87,3 +87,46 @@ test('approved requisitions display the preserved source independently of availa
expect(frozen).toContain('<script>QA</script>');
expect(renderToStaticMarkup(<CapitalAssignmentSummary />)).toBe('');
});
test('capital lineage distinguishes the original receipt from current returns and reversal', () => {
const html = render(CapitalRegister, {
records: page([source]),
history: page([source]),
departments: [],
equipment: [],
canManage: false,
actorId: 1,
tenantId: 1,
trace: {
orders: page([
{
id: 7,
description: 'Synthetic item',
quantity: '2.000',
unit: 'un',
order_id: 8,
order_number: 'OC-QA',
},
]),
receipts: page([
{
id: 9,
description: 'Synthetic item',
unit: 'un',
receipt_id: 10,
order_id: 8,
received_on: '2026-11-27',
quality_status: 'compliant',
accepted_quantity: '2.000',
reversed: true,
returned_quantity: '1.000',
},
]),
},
});
expect(html).toContain('Aceite no original: 2.000');
expect(html).toContain('Devolução ao fornecedor: 1.000');
expect(html).toContain('Recepção estornada');
expect(html).toContain('/ordens/8');
expect(html).not.toContain('<form');
});
+249
View File
@@ -0,0 +1,249 @@
import fs from 'node:fs';
import path from 'node:path';
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import {
ActionBar,
FormErrors,
PageTitle,
Panel,
TableViewport,
} from '@/components/procurement';
import RequisitionForm from '@/pages/requisitions/form';
import SupplierEdit from '@/pages/suppliers/edit';
import ProcurementReports from '@/pages/reports/procurement';
import type { Supplier } from '@/types/procurement';
function render(
component: Parameters<typeof App>[0]['initialComponent'],
props: object,
) {
const html = renderToStaticMarkup(
<App
initialComponent={component}
initialPage={{
component: 'qa',
url: '/qa',
version: 'presentation',
clearHistory: false,
encryptHistory: true,
props: { errors: {}, ...props },
}}
/>,
);
if (process.env.SGC_PRESENTATION_PREVIEW) {
const root = path.resolve(process.env.SGC_PRESENTATION_PREVIEW);
const allowed = path.resolve('storage/framework/testing') + path.sep;
if (!root.startsWith(allowed))
throw Error('Private preview path required');
fs.mkdirSync(root, { recursive: true });
const name =
component === RequisitionForm
? 'requisition'
: component === SupplierEdit
? 'supplier'
: 'report';
fs.writeFileSync(
path.join(root, name + '.html'),
'<!doctype html><html lang="pt-MZ"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>SGC - ' +
name +
' - dados sinteticos</title><link rel="stylesheet" href="/preview.css"><body><aside style="padding:12px;background:#fef3c7">Pre-visualizacao estatica isolada com dados sinteticos; sem gravacao.</aside>' +
html +
'</body></html>',
);
}
return html;
}
test('shared panels have distinct accessible titles and preserve their own content', () => {
const html = renderToStaticMarkup(
<>
<Panel title="Dados gerais">
<input name="reference" defaultValue="SINTETICO" />
</Panel>
<Panel title="Historico">
<p>Versao original</p>
</Panel>
</>,
);
const headings = [...html.matchAll(/<h2 id="([^"]+)"/g)].map(
(match) => match[1],
);
expect(new Set(headings).size).toBe(2);
for (const id of headings)
expect(html).toContain(`aria-labelledby="${id}"`);
expect(html).toContain('name="reference"');
expect(html).toContain('Versao original');
});
test('shared actions preserve submission and disabled semantics without adding commands', () => {
const html = renderToStaticMarkup(
<form>
<ActionBar align="end">
<a href="/requisicoes">Cancelar</a>
<button type="submit" disabled>
Guardar rascunho
</button>
</ActionBar>
</form>,
);
expect(html).toContain('role="group"');
expect(html).toContain('href="/requisicoes"');
expect(html).toContain('type="submit" disabled');
expect(html.match(/<button/g)).toHaveLength(1);
});
test('wide result viewport preserves table headers, cells and escaped user text', () => {
const html = renderToStaticMarkup(
<TableViewport label="Resultados autorizados">
<table>
<thead>
<tr>
<th>Referencia</th>
<th>Valor</th>
</tr>
</thead>
<tbody>
<tr>
<td>{'<script>synthetic</script>'}</td>
<td>100,00 MZN</td>
</tr>
</tbody>
</table>
</TableViewport>,
);
expect(html).toContain('tabindex="0"');
expect(html).toContain('aria-label="Resultados autorizados"');
expect(html).toContain('&lt;script&gt;synthetic&lt;/script&gt;');
expect(html).toContain('<td>100,00 MZN</td>');
expect(html.match(/<th>/g)).toHaveLength(2);
});
test('title keeps the single page heading without inserting an empty action area', () => {
const html = renderToStaticMarkup(
<PageTitle
eyebrow="Compras"
title="Nova requisicao"
description="Preparacao sintetica"
/>,
);
expect(html.match(/<h1 /g)).toHaveLength(1);
expect(html).not.toContain('sgc-page-actions');
});
test('shared validation keeps every error and the existing help action', () => {
const html = renderToStaticMarkup(
<FormErrors
errors={{
'items.0.quantity': 'Quantidade invalida',
currency: 'Moeda por indicar',
}}
/>,
);
expect(html).toContain('role="alert"');
expect(html).toContain('Quantidade invalida');
expect(html).toContain('Moeda por indicar');
expect(html).toContain('type="button"');
});
test.each([false, true])(
'requisition preserves existing save guard with incomplete drafts %s',
(incompleteDraftsAvailable) => {
const html = render(RequisitionForm, {
costCenters: [],
requisition: null,
incompleteDraftsAvailable,
});
expect(html).toContain('Guardar rascunho');
expect(html).toContain('sgc-action-bar');
const save = html.slice(
html.lastIndexOf('<button'),
html.lastIndexOf('</button>'),
);
expect(
/\sdisabled(?:=|[ >])/.test(save.slice(0, save.indexOf('>') + 1)),
).toBe(!incompleteDraftsAvailable);
},
);
test('supplier editing keeps the financial revalidation warning and cancellation destination', () => {
const supplier = {
id: 7,
name: 'Fornecedor SINTETICO',
nuit: '',
contact: '',
email: '',
phone: '',
address: '',
category: '',
beneficiaries: '',
document_references: '',
diligence_notes: '',
next_review: '2026-12-01',
blocked: false,
version: 3,
} as Supplier;
const html = render(SupplierEdit, { supplier });
expect(html).toContain('/fornecedores/7');
expect(html).toContain('Guardar alterações');
expect(html).toContain('retiram a validação actual');
expect(html).toContain('sgc-action-bar');
});
test('procurement report retains applied export filters, result scope and both pagination destinations', () => {
const html = render(ProcurementReports, {
records: {
data: [],
total: 0,
current_page: 2,
last_page: 3,
prev_page_url: '/relatorios?status=approved&page=1',
next_page_url: '/relatorios?status=approved&page=3',
},
filters: { status: 'approved', department_id: 9 },
departments: [{ id: 9, name: 'Departamento SINTETICO' }],
counts: {},
generatedAt: '2026-11-27T12:00:00Z',
});
expect(html).toContain(
'/relatorios/compras.csv?status=approved&amp;department_id=9',
);
expect(html).toContain('/relatorios?status=approved&amp;page=1');
expect(html).toContain('/relatorios?status=approved&amp;page=3');
expect(html).toContain('âmbito autorizado');
expect(html).toContain('sgc-table-viewport');
});
test('populated report keeps every authorised row and its process/report actions', () => {
const records = {
data: Array.from({ length: 25 }, (_, i) => ({
id: 100 + i,
number: `REQ-SINTETICA-${i + 1}`,
status: 'approved',
created_at: '2026-11-27T12:00:00Z',
needed_by: '2026-12-01',
department: 'Departamento sintetico de aprovisionamento',
requester: 'Utilizador sintetico',
total_minor: '10000',
quotations_count: 3,
order_number: null,
})),
total: 75,
current_page: 2,
last_page: 3,
prev_page_url: '/relatorios?page=1',
next_page_url: '/relatorios?page=3',
};
const html = render(ProcurementReports, {
records,
filters: {},
departments: [],
counts: {},
generatedAt: '2026-11-27T12:00:00Z',
});
expect(html.match(/Acompanhar processo/g)).toHaveLength(25);
expect(html.match(/Gerar relatório de conferência/g)).toHaveLength(25);
expect(html).toContain('REQ-SINTETICA-25');
expect(html).toContain('/requisicoes/124/relatorio');
});
+251
View File
@@ -0,0 +1,251 @@
import fs from 'node:fs';
import path from 'node:path';
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import ReviewReport from '@/pages/purchases/review-report';
import Improvements from '@/pages/reports/supplier-improvements';
import PeopleReports from '@/pages/people/reports';
import WarehouseRequests from '@/pages/stock/requests';
import BankSupport from '@/pages/supply/import-bank-support';
const stamp = '2026-11-27T12:00:00Z';
const page = <T,>(data: T[]) => ({
data,
from: data.length ? 1 : null,
to: data.length || null,
total: data.length,
current_page: 1,
last_page: 1,
prev_page_url: null,
next_page_url: null,
});
function render(
component: Parameters<typeof App>[0]['initialComponent'],
props: object,
name: string,
) {
const html = renderToStaticMarkup(
<App
initialComponent={component}
initialPage={{
component: 'qa',
url: '/qa',
version: 'screen-review',
clearHistory: false,
encryptHistory: true,
props: { errors: {}, ...props },
}}
/>,
);
const folder = process.env.SGC_REVIEW_PREVIEW;
if (folder) {
const root = path.resolve(folder);
if (
!root.startsWith(
path.resolve('storage/framework/testing') + path.sep,
)
)
throw Error('Private preview required');
fs.mkdirSync(root, { recursive: true });
fs.writeFileSync(
path.join(root, name + '.html'),
'<!doctype html><html lang="pt-MZ"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>SGC QA ' +
name +
'</title><link rel="stylesheet" href="/preview.css"><body><aside class="print:hidden" style="padding:12px;background:#fef3c7">Pre-visualizacao isolada; dados sinteticos; sem gravacao.</aside>' +
html +
'</body></html>',
);
}
return html;
}
const policy = {
revision: 1,
configured: true,
minimum_proposals: 3,
minimum_evaluators: 2,
weights: { price: 40, quality: 20, delivery: 20, history: 10, payment: 10 },
};
test('long review report preserves all proposals, original amounts and finance visibility restriction', () => {
const rows = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
reference: 'QA-PROPOSTA-' + String(i + 1).padStart(3, '0'),
supplier: 'Fornecedor SINTETICO ' + (i + 1),
currency: 'MZN',
subtotal_minor: 10000,
tax_minor: 1600,
total_minor: 11600,
delivery_days: 15,
valid_until: '2026-12-31',
evaluation_count: 2,
score_minor: null,
eligible: false,
ineligibility_reasons: [
'Condicao sintetica por completar; nenhuma adjudicacao automatica.',
],
is_top: false,
weights: policy.weights,
}));
const report = {
generated_at: stamp,
generated_by: 'Operador SINTETICO',
company: 'Empresa SINTETICA',
requisition: {
id: 42,
number: 'REQ-SINTETICA-42',
status: 'approved',
justification:
'Necessidade sintetica para ensaio de impressao; sem operacao.',
department: 'Departamento SINTETICO',
requester: 'Requisitante SINTETICO',
},
comparison: { ready: false, top_count: 0, rows, policy },
recommendation: null,
admission: null,
qualification: null,
opening: null,
award: null,
order: null,
fulfilment: {
receipts: [],
finance_visible: false,
invoices: null,
payments: null,
},
};
const html = render(ReviewReport, { report }, 'review');
for (const row of rows) expect(html).toContain(row.reference);
expect(html).toContain('report-fulfilment');
expect(html).not.toContain('QA-FACTURA-PRIVADA');
});
test('improvement report preserves details on every visible row without changing their disclosure state', () => {
const rows = Array.from({ length: 30 }, (_, i) => ({
id: i + 1,
evaluation_id: 50 + i,
revision: 1,
supplier: 'Fornecedor SINTETICO ' + (i + 1),
responsible: 'Responsavel SINTETICO',
title: 'QA-MEDIDA-' + String(i + 1).padStart(3, '0'),
description:
'Descricao sintetica da medida de melhoria e acompanhamento da entrega com verificacao independente.',
due_on: '2026-12-01',
status: 'open',
version: 1,
overdue: false,
result: 'QA-RESULTADO-' + String(i + 1).padStart(3, '0'),
evidence: 'QA-EVIDENCIA-' + String(i + 1).padStart(3, '0'),
review_reason: 'Conferencia sintetica preservada.',
}));
const html = render(
Improvements,
{
records: page(rows),
filters: {},
counts: { open: 30 },
overdue: 0,
suppliers: [],
responsibles: [],
today: '2026-11-27',
generatedAt: stamp,
},
'improvements',
);
for (const row of rows) {
expect(html).toContain(row.title);
expect(html).toContain(row.evidence);
}
expect(html).not.toContain('<details open');
});
test('people deadline report retains all tasks and preserves visibility of unknown deadlines', () => {
const items = Array.from({ length: 35 }, (_, i) => ({
id: 'task-' + i,
reference: 'QA-PESSOAS-' + String(i + 1).padStart(3, '0'),
title: 'Processo SINTETICO ' + (i + 1),
category: 'task',
label: 'Conferencia sintetica',
responsibility: 'Responsavel SINTETICO',
due_on: null,
days_overdue: null,
href: '/pessoas/' + (i + 1),
}));
const html = render(
PeopleReports,
{
deadlineReport: {
as_of: '2026-11-27',
window: 'all',
total_items: 35,
matching_processes: 35,
processes_considered: 35,
tasks: 35,
approvals: 0,
alerts: 0,
without_deadline: 35,
overdue_items: 0,
items,
pagination: page([]),
},
selectionMetrics: {},
applicationMetrics: {},
filters: { view: 'deadlines' },
kinds: ['staff', 'service'],
generatedAt: stamp,
summary: [],
processes: page([]),
},
'people',
);
for (const item of items) expect(html).toContain(item.reference);
expect(html).toContain('Sem prazo');
});
test.each([true, false])(
'warehouse preparation remains conditional on its existing permission (%s)',
(canPrepare) => {
const html = render(
WarehouseRequests,
{
filters: {
view: 'all',
state: '',
search: '',
warehouse_id: null,
},
views: [],
states: {},
checkedAt: stamp,
ready: true,
canPrepare,
items: [],
warehouses: [],
costCenters: [],
equipment: [],
records: page([]),
},
canPrepare ? 'warehouse' : 'warehouse-read',
);
expect(html.includes('Preparar rascunho')).toBe(canPrepare);
},
);
test.each([true, false])(
'bank documentary editing remains conditional on its existing permission (%s)',
(canWrite) => {
const html = render(
BankSupport,
{
importRecord: { id: 5, record_key: 'synthetic', version: 1 },
order: { id: 2, number: 'OC-SINTETICA' },
current: page([]),
history: page([]),
documents: page([]),
types: { commitment: 'Termo sintetico' },
canWrite,
actorId: 1,
tenantId: 1,
today: '2026-11-27',
},
canWrite ? 'bank' : 'bank-read',
);
expect(html).toContain('Suporte documental bancário');
expect(html.includes('<form')).toBe(canWrite);
},
);