@@ -58,6 +58,7 @@ test.each([null, 0])(
|
||||
initialComponent={AgreementFollowup}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain('data-query-form="true"');
|
||||
expect(html).toContain('Vigência dos contratos globais');
|
||||
expect(html).toContain('kind=contract');
|
||||
expect(html).toContain('2 artigo(s) aprovado(s) ligado(s)');
|
||||
|
||||
@@ -53,6 +53,7 @@ function render(allowed: boolean) {
|
||||
|
||||
test('audit investigation carries applied criteria into the whole-scope CSV and escapes the reference', () => {
|
||||
const html = render(false);
|
||||
expect(html).toContain('data-query-form="true"');
|
||||
expect(html).toContain('Referência exacta da requisição');
|
||||
expect(html).toContain('QA<REQ>%_');
|
||||
expect(html).toContain(
|
||||
|
||||
@@ -4,7 +4,21 @@ import { afterEach, expect, test, vi } from 'vitest';
|
||||
import Invoices from '@/pages/invoices/index';
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
function render(actorId = 7) {
|
||||
test.each([true, false])(
|
||||
'invoice consultation has a focusable document destination and separates registration (%s)',
|
||||
(canManage) => {
|
||||
const html = render(7, canManage);
|
||||
expect(html).toContain('href="#invoice-documents"');
|
||||
expect(html).toContain('id="invoice-documents" tabindex="-1"');
|
||||
expect(html).toContain('lg:scroll-mt-72');
|
||||
expect(html.includes('href="#invoice-registration"')).toBe(canManage);
|
||||
expect(html.includes('id="invoice-registration"')).toBe(canManage);
|
||||
expect(html).toContain('Sem facturas disponíveis para esta ordem.');
|
||||
expect(html).not.toContain('Sem facturas registadas nesta empresa.');
|
||||
},
|
||||
);
|
||||
|
||||
function render(actorId = 7, canManage = true) {
|
||||
return renderToStaticMarkup(
|
||||
<App
|
||||
initialComponent={Invoices}
|
||||
@@ -18,7 +32,7 @@ function render(actorId = 7) {
|
||||
errors: {},
|
||||
auth: { user: { id: actorId, tenant_id: 3 } },
|
||||
focusOrderId: 2,
|
||||
canManage: true,
|
||||
canManage,
|
||||
invoices: {
|
||||
data: [],
|
||||
current_page: 1,
|
||||
|
||||
@@ -65,6 +65,28 @@ test('read-only capital register preserves archived identity and history without
|
||||
expect(html).toContain('Histórico do registo');
|
||||
expect(html).toContain('<script>QA</script>');
|
||||
expect(html).not.toContain('<form');
|
||||
expect(html).not.toContain('href="#capital-preparation"');
|
||||
expect(html).toContain('?history=source#capital-history');
|
||||
expect(html).toContain('id="capital-history"');
|
||||
});
|
||||
|
||||
test('capital editor links land on a focusable preparation without submitting or changing the original', () => {
|
||||
const html = render(CapitalRegister, {
|
||||
records: page([source]),
|
||||
history: null,
|
||||
departments: [],
|
||||
equipment: [],
|
||||
canManage: true,
|
||||
actorId: 1,
|
||||
tenantId: 1,
|
||||
});
|
||||
expect(html.match(/href="#capital-preparation"/g)).toHaveLength(2);
|
||||
expect(html).toMatch(
|
||||
/<section[^>]*id="capital-preparation"[^>]*tabindex="-1"/,
|
||||
);
|
||||
expect(html).toContain('Preparar nova versão');
|
||||
expect(html).toContain('PRJ-QA');
|
||||
expect(html).not.toContain('id="capital-history"');
|
||||
});
|
||||
test('approved requisitions display the preserved source independently of available new choices', () => {
|
||||
const html = render(CapitalAssignments, {
|
||||
|
||||
@@ -100,6 +100,44 @@ function render(
|
||||
/>,
|
||||
);
|
||||
}
|
||||
test.each([true, false])(
|
||||
'parameter shortcuts target only sections present in the current environment (%s)',
|
||||
(ready) => {
|
||||
const html = render('parameters', {
|
||||
ready,
|
||||
expiryReady: ready,
|
||||
urgentReviewsReady: ready,
|
||||
});
|
||||
const navigation = html.match(
|
||||
/<nav aria-label="Áreas da parametrização"[\s\S]*?<\/nav>/,
|
||||
)?.[0];
|
||||
expect(navigation).toBeDefined();
|
||||
const targets = [...navigation!.matchAll(/href="#([^"]+)"/g)].map(
|
||||
(match) => match[1],
|
||||
);
|
||||
expect(new Set(targets).size).toBe(targets.length);
|
||||
for (const id of targets) {
|
||||
expect(html.split(`id="${id}"`)).toHaveLength(2);
|
||||
expect(html).toMatch(new RegExp(`id="${id}" tabindex="-1"`));
|
||||
}
|
||||
expect(targets).toContain('company-details');
|
||||
expect(targets).toContain('approval-levels');
|
||||
expect(targets.includes('company-comparison')).toBe(ready);
|
||||
expect(targets.includes('company-users')).toBe(ready);
|
||||
expect(targets).not.toContain('company-geography');
|
||||
expect(targets).not.toContain('company-ai-plan');
|
||||
expect(targets).not.toContain('company-work-contexts');
|
||||
expect(navigation!.includes('/administracao/prazos-aprovacao')).toBe(
|
||||
ready,
|
||||
);
|
||||
expect(navigation!.includes('/administracao/revisao-urgencias')).toBe(
|
||||
ready,
|
||||
);
|
||||
expect(html).toContain('lg:scroll-mt-72');
|
||||
expect(html.indexOf('<h1')).toBeLessThan(html.indexOf('<nav'));
|
||||
},
|
||||
);
|
||||
|
||||
test.each([
|
||||
['department', { name: 'DEPARTMENT-PREP-QA' }, 'DEPARTMENT-PREP-QA'],
|
||||
[
|
||||
|
||||
@@ -35,6 +35,7 @@ function render(
|
||||
authorised_at: string;
|
||||
reason: string;
|
||||
} | null = null,
|
||||
overrides: Record<string, unknown> = {},
|
||||
) {
|
||||
return renderToStaticMarkup(
|
||||
<App
|
||||
@@ -67,11 +68,37 @@ function render(
|
||||
},
|
||||
suppliers: [{ id: 1, name: 'Synthetic supplier' }],
|
||||
requisitions: [],
|
||||
...overrides,
|
||||
},
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
test('declaration list distinguishes a released chain from an active independent impediment without changing the original statement', () => {
|
||||
const post = vi.spyOn(router, 'post');
|
||||
const html = render(false, 7, 4, 'finance', true, 3, false, null, {
|
||||
declarations: {
|
||||
data: [
|
||||
declaration,
|
||||
{ ...declaration, id: 4, previous_id: 3, root_id: 3 },
|
||||
{ ...declaration, id: 5 },
|
||||
{ ...declaration, id: 6, has_conflict: false },
|
||||
],
|
||||
prev_page_url: null,
|
||||
next_page_url: null,
|
||||
},
|
||||
releasedRoots: [3],
|
||||
});
|
||||
expect(html.match(/Impedimento levantado pela direcção/g)).toHaveLength(2);
|
||||
expect(html.match(/Impedimento activo/g)).toHaveLength(1);
|
||||
expect(html.match(/Conflito registado/g)).toHaveLength(3);
|
||||
expect(html).toContain('Ausência declarada');
|
||||
expect(html).toContain('autorização expressa da direcção');
|
||||
expect(html).not.toContain('nem retirada de conflitos nesta etapa');
|
||||
expect(html).not.toContain('os restantes perfis consultam apenas');
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
});
|
||||
test('direction release preparation requires explicit capability and never submits on recovery', () => {
|
||||
vi.spyOn(router, 'restore').mockImplementation((key) =>
|
||||
key ===
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { App } from '@inertiajs/react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import Dashboard from '@/pages/dashboard';
|
||||
import Requisitions from '@/pages/requisitions/index';
|
||||
|
||||
test('dashboard distinguishes visible pending requests from personal decisions and links to the corresponding lists', () => {
|
||||
const Screen = () => (
|
||||
<Dashboard
|
||||
company={null}
|
||||
stats={{
|
||||
total: 7,
|
||||
pending: 3,
|
||||
approved: 2,
|
||||
approvedMinor: 10000,
|
||||
awaitingMe: 0,
|
||||
}}
|
||||
recent={[]}
|
||||
approvals={[]}
|
||||
/>
|
||||
);
|
||||
const html = renderToStaticMarkup(
|
||||
<App
|
||||
initialComponent={Screen}
|
||||
initialPage={{
|
||||
component: 'dashboard',
|
||||
url: '/dashboard',
|
||||
version: null,
|
||||
clearHistory: false,
|
||||
encryptHistory: true,
|
||||
props: { errors: {}, publicNavigation: true },
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain('href="/requisicoes?status=pending"');
|
||||
expect(html.match(/href="\/requisicoes\?status=approved"/g)).toHaveLength(
|
||||
2,
|
||||
);
|
||||
expect(html).toContain('href="/requisicoes?view=approvals"');
|
||||
expect(html).toContain('Requisições que aguardam a sua decisão: 0');
|
||||
expect(html).not.toContain('À espera da sua aprovação');
|
||||
expect(html).not.toContain('Nova requisição');
|
||||
});
|
||||
|
||||
test.each([
|
||||
[
|
||||
{ view: 'approvals' },
|
||||
'Não há requisições com uma etapa disponível para a sua decisão',
|
||||
],
|
||||
[
|
||||
{ view: 'approvals', status: 'pending' },
|
||||
'Nenhum pedido corresponde aos filtros neste conjunto',
|
||||
],
|
||||
])(
|
||||
'empty requisition lists explain the selected scope (%j)',
|
||||
(filters, message) => {
|
||||
const Screen = () => (
|
||||
<Requisitions
|
||||
requisitions={{
|
||||
data: [],
|
||||
total: 0,
|
||||
current_page: 1,
|
||||
last_page: 1,
|
||||
prev_page_url: null,
|
||||
next_page_url: null,
|
||||
}}
|
||||
filters={filters}
|
||||
/>
|
||||
);
|
||||
const html = renderToStaticMarkup(
|
||||
<App
|
||||
initialComponent={Screen}
|
||||
initialPage={{
|
||||
component: 'requisitions/index',
|
||||
url: '/requisicoes',
|
||||
version: null,
|
||||
clearHistory: false,
|
||||
encryptHistory: true,
|
||||
props: { errors: {} },
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain(message);
|
||||
expect(html).not.toContain('aparecem aqui depois de criados');
|
||||
},
|
||||
);
|
||||
@@ -1,14 +1,73 @@
|
||||
import { App, router } from '@inertiajs/react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { afterEach, expect, test, vi } from 'vitest';
|
||||
import Legal from '../../resources/js/pages/supply/import-legal';
|
||||
import Legal, {
|
||||
revealInvalidLegalField,
|
||||
} from '../../resources/js/pages/supply/import-legal';
|
||||
|
||||
test('incomplete legal preparation reveals the first invalid field below the fixed header', () => {
|
||||
const callbacks: FrameRequestCallback[] = [];
|
||||
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
|
||||
callbacks.push(callback);
|
||||
return callbacks.length;
|
||||
});
|
||||
const field = { focus: vi.fn(), scrollIntoView: vi.fn() };
|
||||
const form = {
|
||||
querySelector: vi.fn((selector: string) =>
|
||||
selector === 'input:invalid, select:invalid, textarea:invalid'
|
||||
? field
|
||||
: { tagName: 'FIELDSET' },
|
||||
),
|
||||
};
|
||||
try {
|
||||
revealInvalidLegalField({
|
||||
currentTarget: form,
|
||||
target: field,
|
||||
} as never);
|
||||
revealInvalidLegalField({ currentTarget: form, target: {} } as never);
|
||||
expect(callbacks).toHaveLength(1);
|
||||
expect(field.scrollIntoView).not.toHaveBeenCalled();
|
||||
callbacks[0](0);
|
||||
expect(field.focus).toHaveBeenCalledWith({ preventScroll: true });
|
||||
expect(field.scrollIntoView).toHaveBeenCalledWith({
|
||||
block: 'center',
|
||||
behavior: 'instant',
|
||||
});
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
test.each([true, false])(
|
||||
'legal shortcuts target present focusable sections without exposing management (%s)',
|
||||
(canManage) => {
|
||||
const html = renderLegal(canManage);
|
||||
const navigation = html.match(
|
||||
/<nav aria-label="Áreas da base legal de importação"[\s\S]*?<\/nav>/,
|
||||
)?.[0];
|
||||
expect(navigation).toBeDefined();
|
||||
const targets = [...navigation!.matchAll(/href="#([^"]+)"/g)].map(
|
||||
(match) => match[1],
|
||||
);
|
||||
for (const id of targets) {
|
||||
expect(html.split(`id="${id}"`)).toHaveLength(2);
|
||||
expect(html).toMatch(new RegExp(`id="${id}" tabindex="-1"`));
|
||||
}
|
||||
expect(targets.includes('legal-rule-editor')).toBe(canManage);
|
||||
expect(targets).not.toContain('legal-decision');
|
||||
expect(html).toContain('data-query-form="true"');
|
||||
if (canManage) expect(html).toContain('href="#legal-rule-editor"');
|
||||
},
|
||||
);
|
||||
|
||||
function renderLegal(
|
||||
canManage: boolean,
|
||||
withRule = true,
|
||||
withCharges = false,
|
||||
withReference = false,
|
||||
iceReference = false,
|
||||
vatReference = false,
|
||||
) {
|
||||
const data = {
|
||||
title: '<script>synthetic rule</script>',
|
||||
@@ -68,18 +127,46 @@ function renderLegal(
|
||||
? [
|
||||
{
|
||||
source_id: 8,
|
||||
code: '3506.91.20',
|
||||
description:
|
||||
'Silicone para selagem de painéis solares',
|
||||
rate_percent: '20',
|
||||
title: 'Taxa geral documental',
|
||||
official_reference: 'Lei 8/2025',
|
||||
code: iceReference
|
||||
? '8703.80.10'
|
||||
: '3506.91.20',
|
||||
description: iceReference
|
||||
? 'Automóveis unicamente eléctricos, bateria até 62 kWh'
|
||||
: 'Silicone para selagem de painéis solares',
|
||||
rate_percent: iceReference ? '5' : '20',
|
||||
rate_label: iceReference
|
||||
? 'ICE 5%'
|
||||
: undefined,
|
||||
valid_until: iceReference
|
||||
? '2027-12-31'
|
||||
: undefined,
|
||||
title: iceReference
|
||||
? 'ICE documental'
|
||||
: 'Taxa geral documental',
|
||||
official_reference: iceReference
|
||||
? 'Lei 7/2025, 2.º suplemento'
|
||||
: 'Lei 8/2025',
|
||||
official_url: null,
|
||||
citation: 'Página 2180-(4)',
|
||||
citation: iceReference
|
||||
? 'Página 2180-(22)'
|
||||
: 'Página 2180-(4)',
|
||||
valid_from: '2026-01-01',
|
||||
obligations:
|
||||
'Conferir o exemplar e o regime aplicável',
|
||||
charges: [],
|
||||
...(vatReference
|
||||
? {
|
||||
code: 'IVA_ART17',
|
||||
label: 'IVA — taxa normal; completar código e base',
|
||||
match_code: '',
|
||||
suggested_code: '',
|
||||
rate_percent: '16',
|
||||
rate_label:
|
||||
'16% — base por documentar',
|
||||
valid_from: '2023-01-01',
|
||||
valid_until: null,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
]
|
||||
: [],
|
||||
@@ -116,6 +203,24 @@ test('official reference preparation is explicit and only available to the custo
|
||||
expect(reader).not.toContain('Silicone para selagem');
|
||||
});
|
||||
|
||||
test('ICE reference labels remain distinct from general customs duty', () => {
|
||||
const html = renderLegal(true, false, false, true, true);
|
||||
expect(html).toContain('ICE 5%');
|
||||
expect(html).not.toContain('taxa geral 5%');
|
||||
expect(html).toContain('fonte, citação e período');
|
||||
expect(html).toContain('não é uma pauta consolidada');
|
||||
});
|
||||
|
||||
test('the general VAT template has a human label and leaves item classification to explicit preparation', () => {
|
||||
const post = vi.spyOn(router, 'post');
|
||||
const html = renderLegal(true, false, false, true, false, true);
|
||||
expect(html).toContain('IVA — taxa normal; completar código e base');
|
||||
expect(html).toContain('16% — base por documentar');
|
||||
expect(html).not.toContain('IVA_ART17 —');
|
||||
expect(html).not.toMatch(/<input[^>]*value="IVA_ART17"/);
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('remembered legal preparation is preserved and disables replacement by official reference drafts', () => {
|
||||
vi.spyOn(router, 'restore').mockImplementation((key) =>
|
||||
key === 'legal-rule:1:1:1:data'
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { App } from '@inertiajs/react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import ImportTariffs from '@/pages/supply/import-tariffs';
|
||||
|
||||
test.each([false, true])(
|
||||
'tariff lookup remains a consultation while business forms respect authority (%s)',
|
||||
(canWrite) => {
|
||||
const page = { data: [], prev_page_url: null, next_page_url: null };
|
||||
const html = renderToStaticMarkup(
|
||||
<App
|
||||
initialComponent={ImportTariffs}
|
||||
initialPage={{
|
||||
component: 'supply/import-tariffs',
|
||||
url: '/requisicoes/1/classificacao-pautal',
|
||||
version: null,
|
||||
clearHistory: false,
|
||||
encryptHistory: true,
|
||||
props: {
|
||||
errors: {},
|
||||
requisition: { id: 1, number: 'REQ-QA' },
|
||||
actorId: 2,
|
||||
tenantId: 3,
|
||||
legalReady: true,
|
||||
canPropose: canWrite,
|
||||
canConfirm: canWrite,
|
||||
masterSearch: 'QA<123',
|
||||
items: [
|
||||
{
|
||||
id: 4,
|
||||
description: 'Material QA',
|
||||
quantity: '1',
|
||||
unit: 'un',
|
||||
},
|
||||
],
|
||||
latest: [],
|
||||
history: page,
|
||||
masters: page,
|
||||
stockItems: page,
|
||||
},
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
const forms = html.match(/<form\b[^>]*>/g) ?? [];
|
||||
expect(
|
||||
forms.filter((form) => form.includes('data-query-form="true"')),
|
||||
).toHaveLength(1);
|
||||
expect(forms.find((form) => form.includes('method="get"'))).toContain(
|
||||
'data-query-form="true"',
|
||||
);
|
||||
expect(forms).toHaveLength(canWrite ? 2 : 1);
|
||||
expect(html).toContain('QA<123');
|
||||
expect(html).toContain('/requisicoes/1/base-legal');
|
||||
expect(html).not.toContain('data-query-form="true" data-preparation');
|
||||
},
|
||||
);
|
||||
@@ -29,6 +29,7 @@ function render(
|
||||
canConfigure = true,
|
||||
allowedTypes = ['production', 'maintenance'],
|
||||
linked = false,
|
||||
selected = false,
|
||||
) {
|
||||
return renderToStaticMarkup(
|
||||
<App
|
||||
@@ -58,6 +59,7 @@ function render(
|
||||
data: { mode: 'procurement' },
|
||||
},
|
||||
canConfigure,
|
||||
selectedOrderId: selected ? source.id : null,
|
||||
allowedTypes,
|
||||
departments: [{ id: 1, name: 'Synthetic department' }],
|
||||
orders: {
|
||||
@@ -78,6 +80,17 @@ function render(
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
test('a selected operational source is directly focusable and provides the return to the complete authorised registry', () => {
|
||||
const html = render(7, false, [], false, true);
|
||||
expect(html).toContain('A consultar uma ordem específica');
|
||||
expect(html).toContain('href="/ordens-operacionais"');
|
||||
expect(html).toContain('Ver todas as ordens disponíveis');
|
||||
expect(html).toContain('id="op-order-5"');
|
||||
expect(html).toContain('tabindex="-1"');
|
||||
expect(html).toContain('lg:scroll-mt-72');
|
||||
expect(html).not.toContain('<script>private-test</script>');
|
||||
});
|
||||
test('order preparation restores only its actor context and policy without automatic creation', () => {
|
||||
const identity =
|
||||
'procurement-preparations:4:7:procurement.internal:procurement,requester:operational-orders:1:1:production,maintenance:true:0:false';
|
||||
|
||||
@@ -2,6 +2,7 @@ import { expect, test } from 'vitest';
|
||||
import {
|
||||
connectedDirtyForms,
|
||||
markPreparationDirty,
|
||||
usesGenericPreparationTracking,
|
||||
} from '@/lib/preparation-forms';
|
||||
|
||||
function form(connected = true): HTMLFormElement {
|
||||
@@ -23,6 +24,43 @@ function root(forms: HTMLFormElement[]): Pick<Document, 'querySelectorAll'> {
|
||||
} as unknown as Pick<Document, 'querySelectorAll'>;
|
||||
}
|
||||
|
||||
test('consultation filters remain outside unsaved business preparations after deferred navigation while other edits stay protected', async () => {
|
||||
const query = form();
|
||||
query.setAttribute('data-query-form', 'true');
|
||||
markPreparationDirty(query, true);
|
||||
const tracked = new Set([query]);
|
||||
await Promise.resolve();
|
||||
expect(connectedDirtyForms(tracked, root([query]))).toEqual([]);
|
||||
const business = form();
|
||||
markPreparationDirty(business, true);
|
||||
tracked.add(business);
|
||||
expect(connectedDirtyForms(tracked, root([query, business]))).toEqual([
|
||||
business,
|
||||
]);
|
||||
markPreparationDirty(business, false);
|
||||
expect(connectedDirtyForms(tracked, root([query, business]))).toEqual([]);
|
||||
});
|
||||
|
||||
test('generic input tracking cannot re-dirty a managed form after its own state clears during event propagation', () => {
|
||||
const managed = form();
|
||||
const legacy = form();
|
||||
expect(usesGenericPreparationTracking(legacy)).toBe(true);
|
||||
markPreparationDirty(managed, true, true);
|
||||
expect(connectedDirtyForms([managed], root([managed]))).toEqual([managed]);
|
||||
markPreparationDirty(managed, false, true);
|
||||
if (usesGenericPreparationTracking(managed))
|
||||
markPreparationDirty(managed, true);
|
||||
expect(connectedDirtyForms([managed], root([managed]))).toEqual([]);
|
||||
if (usesGenericPreparationTracking(legacy))
|
||||
markPreparationDirty(legacy, true);
|
||||
expect(
|
||||
connectedDirtyForms([managed, legacy], root([managed, legacy])),
|
||||
).toEqual([legacy]);
|
||||
const query = form();
|
||||
query.setAttribute('data-query-form', 'true');
|
||||
expect(usesGenericPreparationTracking(query)).toBe(false);
|
||||
});
|
||||
|
||||
test('a restored dirty preparation is protected even before any input event or listener registration', () => {
|
||||
const restored = form();
|
||||
markPreparationDirty(restored, true);
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
import { App } from '@inertiajs/react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import { ProcurementMenuResults } from '@/components/procurement-menu-results';
|
||||
import {
|
||||
procurementNavigation,
|
||||
activeProcurementEntry,
|
||||
type ProcurementGroup,
|
||||
} from '@/lib/procurement-navigation';
|
||||
import {
|
||||
matchesMenuSearch,
|
||||
searchProcurementMenu,
|
||||
} from '@/lib/procurement-menu-search';
|
||||
|
||||
test.each([
|
||||
'/compras/fornecimento',
|
||||
'/compras/fornecimento?view=agreements&record_id=12',
|
||||
'/compras/fornecimento?view=contracts&record_id=7#supply-record-7',
|
||||
'/compras/acordos/vigencia?validity=current',
|
||||
'/compras/acordos/vigencia?kind=contract&search=QA&page=2',
|
||||
])(
|
||||
'supply agreements and contracts retain authorised menu context: %s',
|
||||
(path) => {
|
||||
for (const role of [
|
||||
'admin',
|
||||
'supply_read',
|
||||
'supply_prepare',
|
||||
'supply_review',
|
||||
]) {
|
||||
expect(
|
||||
activeProcurementEntry(
|
||||
procurementNavigation([role], false),
|
||||
path,
|
||||
),
|
||||
).toBe('supply_agreements');
|
||||
}
|
||||
expect(
|
||||
activeProcurementEntry(
|
||||
procurementNavigation(['requester'], false),
|
||||
path,
|
||||
),
|
||||
).not.toBe('supply_agreements');
|
||||
expect(
|
||||
activeProcurementEntry(
|
||||
procurementNavigation(['admin'], false, ['/dashboard']),
|
||||
path,
|
||||
),
|
||||
).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
test('supply menu synonyms find only the existing authorised destination', () => {
|
||||
const groups = procurementNavigation(['supply_read'], false);
|
||||
for (const term of [
|
||||
'acordos',
|
||||
'CONTRATOS',
|
||||
'vigencia',
|
||||
'fornecimento contrato',
|
||||
]) {
|
||||
expect(
|
||||
searchProcurementMenu(groups, term).flatMap((group) =>
|
||||
group.entries.map((entry) => entry.id),
|
||||
),
|
||||
).toEqual(['supply_agreements']);
|
||||
expect(
|
||||
searchProcurementMenu(
|
||||
procurementNavigation(['requester'], false),
|
||||
term,
|
||||
),
|
||||
).toEqual([]);
|
||||
}
|
||||
expect(
|
||||
activeProcurementEntry(groups, '/compras/fornecimento?view=calendar'),
|
||||
).toBe('supply_calendar');
|
||||
});
|
||||
|
||||
test.each([
|
||||
'/administracao/prazos-aprovacao',
|
||||
'/administracao/revisao-urgencias?history=2',
|
||||
])(
|
||||
'approval policy subpages retain their authorised administration context: %s',
|
||||
(path) => {
|
||||
expect(
|
||||
activeProcurementEntry(
|
||||
procurementNavigation(['admin'], false),
|
||||
path,
|
||||
),
|
||||
).toBe('organization_parameters');
|
||||
expect(
|
||||
activeProcurementEntry(
|
||||
procurementNavigation(['requester'], false),
|
||||
path,
|
||||
),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
activeProcurementEntry(
|
||||
procurementNavigation(['finance'], false),
|
||||
path,
|
||||
),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
activeProcurementEntry(
|
||||
procurementNavigation(['admin'], false, ['/dashboard']),
|
||||
path,
|
||||
),
|
||||
).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
test.each(['classificacao-pautal', 'base-legal', 'estimativa-importacao'])(
|
||||
'import process pages retain the authorised import menu context: %s',
|
||||
(page) => {
|
||||
const path = `/requisicoes/7/${page}`;
|
||||
expect(
|
||||
activeProcurementEntry(
|
||||
procurementNavigation(['import_customs'], false),
|
||||
path,
|
||||
),
|
||||
).toBe('supply_imports');
|
||||
expect(
|
||||
activeProcurementEntry(
|
||||
procurementNavigation(['requester'], false),
|
||||
path,
|
||||
),
|
||||
).not.toBe('supply_imports');
|
||||
expect(
|
||||
activeProcurementEntry(
|
||||
procurementNavigation(['admin'], false, ['/dashboard']),
|
||||
path,
|
||||
),
|
||||
).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
test.each([
|
||||
'documentos',
|
||||
'documentos/18',
|
||||
'suporte-bancario',
|
||||
'acompanhamento',
|
||||
'custos',
|
||||
])(
|
||||
'import documentary page highlights only an existing authorised import entry: %s',
|
||||
(page) => {
|
||||
const path = `/compras/importacoes/17/${page}`;
|
||||
expect(
|
||||
activeProcurementEntry(
|
||||
procurementNavigation(['import_prepare'], false),
|
||||
path,
|
||||
),
|
||||
).toBe('supply_imports');
|
||||
expect(
|
||||
activeProcurementEntry(
|
||||
procurementNavigation(['requester'], false),
|
||||
path,
|
||||
),
|
||||
).not.toBe('supply_imports');
|
||||
expect(
|
||||
activeProcurementEntry(
|
||||
procurementNavigation(['admin'], false, ['/dashboard']),
|
||||
path,
|
||||
),
|
||||
).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
test('capital register menu is gated by readiness and native reading roles and highlights its history route', () => {
|
||||
for (const permission of [
|
||||
'admin',
|
||||
'procurement',
|
||||
'finance',
|
||||
'department_head',
|
||||
'warehouse',
|
||||
'requester',
|
||||
]) {
|
||||
for (const ready of [false, true]) {
|
||||
const groups = procurementNavigation(
|
||||
[permission],
|
||||
false,
|
||||
undefined,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
ready,
|
||||
);
|
||||
const results = searchProcurementMenu(groups, 'projeto patrimonio');
|
||||
expect(
|
||||
results.flatMap((group) =>
|
||||
group.entries.map((entry) => entry.id),
|
||||
),
|
||||
).toEqual(
|
||||
ready && permission !== 'requester' ? ['capital_register'] : [],
|
||||
);
|
||||
if (ready && permission !== 'requester') {
|
||||
expect(
|
||||
activeProcurementEntry(
|
||||
groups,
|
||||
'/projectos-imobilizado?history=qa',
|
||||
),
|
||||
).toBe('capital_register');
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('menu search finds the authorised import route by singular name, accents and separate words', () => {
|
||||
const groups = procurementNavigation(['import_customs'], false);
|
||||
const before = JSON.stringify(groups);
|
||||
for (const query of [
|
||||
'IMPORTAÇÃO',
|
||||
'aduaneira compras',
|
||||
'transitario',
|
||||
'pauta',
|
||||
]) {
|
||||
expect(
|
||||
searchProcurementMenu(groups, query).flatMap((g) =>
|
||||
g.entries.map((e) => e.id),
|
||||
),
|
||||
).toEqual(['supply_imports']);
|
||||
}
|
||||
expect(JSON.stringify(groups)).toBe(before);
|
||||
});
|
||||
|
||||
test('synonyms cannot reveal audit, finance or operational routes outside the existing authority and flags', () => {
|
||||
const groups = procurementNavigation(['requester'], false);
|
||||
for (const query of ['auditoria privada', 'facturas', 'oficina'])
|
||||
expect(searchProcurementMenu(groups, query)).toEqual([]);
|
||||
const privateGroups = procurementNavigation(
|
||||
['audit_private_stock_read'],
|
||||
false,
|
||||
undefined,
|
||||
false,
|
||||
false,
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
searchProcurementMenu(privateGroups, 'exportar auditoria').flatMap(
|
||||
(g) => g.entries.map((e) => e.id),
|
||||
),
|
||||
).toEqual(['audit_private']);
|
||||
});
|
||||
|
||||
test('empty search preserves every current entry and dashboard matching accepts words in either order', () => {
|
||||
const groups = procurementNavigation('admin', true);
|
||||
expect(searchProcurementMenu(groups, ' ')).toEqual(groups);
|
||||
expect(
|
||||
matchesMenuSearch('Painel inicial Visão geral', 'GERAL painel'),
|
||||
).toBe(true);
|
||||
expect(
|
||||
matchesMenuSearch('Painel inicial Visão geral', 'sem correspondência'),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
function renderResults(groups: ProcurementGroup[], dashboard = false) {
|
||||
const Screen = () => (
|
||||
<ProcurementMenuResults
|
||||
groups={groups}
|
||||
dashboard={dashboard}
|
||||
onNavigate={() => {}}
|
||||
onEscape={() => {}}
|
||||
/>
|
||||
);
|
||||
return renderToStaticMarkup(
|
||||
<App
|
||||
initialComponent={Screen}
|
||||
initialPage={{
|
||||
component: 'qa/menu',
|
||||
url: '/dashboard',
|
||||
version: null,
|
||||
clearHistory: false,
|
||||
encryptHistory: true,
|
||||
props: { errors: {} },
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
test('desktop results expose direct links, their area and a clear live empty state', () => {
|
||||
const groups = searchProcurementMenu(
|
||||
procurementNavigation(['import_customs'], false),
|
||||
'importacao',
|
||||
);
|
||||
const html = renderResults(groups);
|
||||
expect(html).toContain('1 opção disponível');
|
||||
expect(html).toContain('href="/compras/fornecimento?view=imports"');
|
||||
expect(html).toContain('Importação');
|
||||
expect(html).toContain('Resultados da pesquisa do menu');
|
||||
expect(renderResults([])).toContain('Nenhuma opção encontrada');
|
||||
expect(renderResults([])).toContain('role="status"');
|
||||
expect(renderResults(groups, true)).toContain('2 opções disponíveis');
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
import { App } from '@inertiajs/react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import ProcurementReports from '@/pages/reports/procurement';
|
||||
|
||||
test.each([false, true])(
|
||||
'report shortcuts have matching sections and preserve the filtered report without exposing absent financial sections (%s)',
|
||||
(operational) => {
|
||||
const Screen = () => (
|
||||
<ProcurementReports
|
||||
records={{
|
||||
data: [],
|
||||
total: 0,
|
||||
current_page: 1,
|
||||
last_page: 1,
|
||||
prev_page_url: null,
|
||||
next_page_url: null,
|
||||
}}
|
||||
counts={{}}
|
||||
filters={{ status: 'pending', department_id: 7 }}
|
||||
departments={[]}
|
||||
generatedAt="2026-11-28T12:00:00Z"
|
||||
insights={
|
||||
operational
|
||||
? {
|
||||
method: 'procurement_facts_v1',
|
||||
generated_at: '2026-11-28T12:00:00Z',
|
||||
processes: 0,
|
||||
pending: {
|
||||
count: 0,
|
||||
unknown_submission_age: 0,
|
||||
oldest: [],
|
||||
},
|
||||
unapproved_past_needed_date: 0,
|
||||
approved: {
|
||||
count: 0,
|
||||
without_registered_quotes: 0,
|
||||
without_visible_order: 0,
|
||||
},
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
const html = renderToStaticMarkup(
|
||||
<App
|
||||
initialComponent={Screen}
|
||||
initialPage={{
|
||||
component: 'reports/procurement',
|
||||
url: '/relatorios?status=pending&department_id=7',
|
||||
version: null,
|
||||
clearHistory: false,
|
||||
encryptHistory: true,
|
||||
props: { errors: {} },
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain('aria-label="Secções dos relatórios"');
|
||||
expect(html).toContain('href="#report-filters"');
|
||||
expect(html).toContain('id="report-filters"');
|
||||
// The sticky workspace header previously covered anchor destinations.
|
||||
for (const target of html.matchAll(
|
||||
/<section\b[^>]*id="report-[^"]+"[^>]*>/g,
|
||||
)) {
|
||||
expect(target[0]).toContain('tabindex="-1"');
|
||||
expect(target[0]).toContain('scroll-mt-24 lg:scroll-mt-72');
|
||||
}
|
||||
expect(html.includes('href="#report-operational"')).toBe(operational);
|
||||
expect(html.includes('id="report-operational"')).toBe(operational);
|
||||
for (const absent of [
|
||||
'payables',
|
||||
'deliveries',
|
||||
'payments',
|
||||
'contracts',
|
||||
]) {
|
||||
expect(html).not.toContain(`href="#report-${absent}"`);
|
||||
expect(html).not.toContain(`id="report-${absent}"`);
|
||||
}
|
||||
expect(html).toContain(
|
||||
'/relatorios/compras.csv?status=pending&department_id=7',
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -3,6 +3,177 @@ import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import Search from '@/pages/search/procurement';
|
||||
|
||||
test('operational search exposes the native selected-order destination and a registration state without private source bodies', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<App
|
||||
initialComponent={Search}
|
||||
initialPage={{
|
||||
component: 'search/procurement',
|
||||
url: '/compras/pesquisa?q=OP',
|
||||
version: null,
|
||||
clearHistory: false,
|
||||
encryptHistory: true,
|
||||
props: {
|
||||
errors: {},
|
||||
term: 'OP',
|
||||
operationalOrderSearchAvailable: true,
|
||||
groups: [
|
||||
{
|
||||
key: 'operational_orders',
|
||||
title: 'Ordens de produção e manutenção',
|
||||
records: {
|
||||
total: 16,
|
||||
current_page: 1,
|
||||
last_page: 2,
|
||||
prev_page_url: null,
|
||||
next_page_url:
|
||||
'/compras/pesquisa?q=OP&operational_orders_page=2',
|
||||
data: [
|
||||
{
|
||||
id: 5,
|
||||
title: 'Produção OP-QA · v1',
|
||||
detail: 'recorded',
|
||||
href: '/ordens-operacionais?order_id=5#op-order-5',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain('/ordens-operacionais?order_id=5#op-order-5');
|
||||
expect(html).toContain('Registada');
|
||||
expect(html).toContain('operational_orders_page=2');
|
||||
expect(html).toContain('ordem de origem autorizada');
|
||||
});
|
||||
|
||||
test.each([0, 1])(
|
||||
'search places matching areas before collapsed empty areas and reports an entirely empty scope (%i)',
|
||||
(total) => {
|
||||
const empty = {
|
||||
total: 0,
|
||||
current_page: 1,
|
||||
last_page: 1,
|
||||
prev_page_url: null,
|
||||
next_page_url: null,
|
||||
data: [],
|
||||
};
|
||||
const html = renderToStaticMarkup(
|
||||
<App
|
||||
initialComponent={Search}
|
||||
initialPage={{
|
||||
component: 'search/procurement',
|
||||
url: '/compras/pesquisa?q=CAP',
|
||||
version: null,
|
||||
clearHistory: false,
|
||||
encryptHistory: true,
|
||||
props: {
|
||||
errors: {},
|
||||
term: 'CAP',
|
||||
groups: [
|
||||
{
|
||||
key: 'requests',
|
||||
title: 'Requisições',
|
||||
records: empty,
|
||||
},
|
||||
{
|
||||
key: 'capital',
|
||||
title: 'Projectos e imobilizado',
|
||||
records: {
|
||||
...empty,
|
||||
total,
|
||||
data: total
|
||||
? [
|
||||
{
|
||||
id: 1,
|
||||
title: 'PROJECT-HIT',
|
||||
detail: 'active',
|
||||
href: '/projectos-imobilizado?history=qa',
|
||||
},
|
||||
]
|
||||
: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain('Áreas sem resultados');
|
||||
expect(html).toContain('data-query-form="true"');
|
||||
expect(html).not.toContain('<details open');
|
||||
expect(
|
||||
html.includes(
|
||||
'Não foram encontrados resultados para esta pesquisa',
|
||||
),
|
||||
).toBe(total === 0);
|
||||
if (total)
|
||||
expect(html.indexOf('PROJECT-HIT')).toBeLessThan(
|
||||
html.indexOf('Áreas sem resultados'),
|
||||
);
|
||||
expect(html).not.toContain('Requisições (0)');
|
||||
},
|
||||
);
|
||||
|
||||
test.each([false, true])(
|
||||
'capital search presents only supplied register metadata and its native history destination (%s)',
|
||||
(available) => {
|
||||
const html = renderToStaticMarkup(
|
||||
<App
|
||||
initialComponent={Search}
|
||||
initialPage={{
|
||||
component: 'search/procurement',
|
||||
url: '/compras/pesquisa?q=CAP',
|
||||
version: null,
|
||||
clearHistory: false,
|
||||
encryptHistory: true,
|
||||
props: {
|
||||
errors: {},
|
||||
term: 'CAP',
|
||||
capitalSearchAvailable: available,
|
||||
groups: available
|
||||
? [
|
||||
{
|
||||
key: 'capital',
|
||||
title: 'Projectos e imobilizado',
|
||||
records: {
|
||||
total: 16,
|
||||
current_page: 1,
|
||||
last_page: 2,
|
||||
prev_page_url: null,
|
||||
next_page_url:
|
||||
'/compras/pesquisa?q=CAP&capital_page=2',
|
||||
data: [
|
||||
{
|
||||
id: 8,
|
||||
title: 'Projecto CAP <QA> · v2',
|
||||
detail: 'archived',
|
||||
href: '/projectos-imobilizado?history=qa-record',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
: [],
|
||||
},
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expect(html.includes('Projectos e imobilizado')).toBe(available);
|
||||
expect(html.includes('próprios de Compras')).toBe(available);
|
||||
expect(html.includes('/projectos-imobilizado?history=qa-record')).toBe(
|
||||
available,
|
||||
);
|
||||
if (available) {
|
||||
expect(html).toContain('Projecto CAP <QA> · v2');
|
||||
expect(html).toContain('Arquivado');
|
||||
expect(html).toContain('capital_page=2');
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test('warehouse search preserves the distinct internal reference event state and result page', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<App
|
||||
|
||||
@@ -27,7 +27,7 @@ const order = {
|
||||
};
|
||||
|
||||
function render(
|
||||
component: typeof Orders | typeof Show,
|
||||
component: Parameters<typeof App>[0]['initialComponent'],
|
||||
props: Record<string, unknown>,
|
||||
) {
|
||||
return renderToStaticMarkup(
|
||||
@@ -64,3 +64,117 @@ test('incomplete detail identifies the missing original and preserves documented
|
||||
expect(html).toContain('/ordens/1/imprimir');
|
||||
expect(html).not.toContain('Aprovações do valor final');
|
||||
});
|
||||
|
||||
test.each([
|
||||
{
|
||||
state: 'issued',
|
||||
enabled: true,
|
||||
canRequest: true,
|
||||
form: true,
|
||||
text: 'Ordem emitida.',
|
||||
},
|
||||
{
|
||||
state: 'issued',
|
||||
enabled: true,
|
||||
canRequest: false,
|
||||
form: false,
|
||||
text: 'Ordem emitida.',
|
||||
},
|
||||
{
|
||||
state: 'cancellation_pending',
|
||||
enabled: false,
|
||||
canRequest: false,
|
||||
form: false,
|
||||
text: 'Cancelamento pendente.',
|
||||
},
|
||||
{
|
||||
state: 'cancelled',
|
||||
enabled: true,
|
||||
canRequest: false,
|
||||
form: false,
|
||||
text: 'Ordem cancelada.',
|
||||
},
|
||||
])(
|
||||
'legacy detail preserves operational cancellation status and server authority ($state/$canRequest)',
|
||||
({ state, enabled, canRequest, form, text }) => {
|
||||
const html = render(Show, {
|
||||
order,
|
||||
history: [],
|
||||
snapshotComplete: false,
|
||||
orderCancellation: { state, enabled, canRequest },
|
||||
});
|
||||
expect(html).toContain('Estado operacional e cancelamento');
|
||||
expect(html).toContain(text);
|
||||
expect(html.includes('Pedir cancelamento integral')).toBe(form);
|
||||
expect(html).toContain('Documento original incompleto');
|
||||
expect(html).toContain('Artigo preservado');
|
||||
expect(html).toContain('100,00');
|
||||
expect(html).not.toContain('Aprovações do valor final');
|
||||
},
|
||||
);
|
||||
|
||||
test.each([false, true])(
|
||||
'existing order documents expose only server-authorised related destinations (%s)',
|
||||
(finance) => {
|
||||
const html = render(Show, {
|
||||
order,
|
||||
history: [],
|
||||
snapshotComplete: false,
|
||||
financialDocumentsHref: finance
|
||||
? '/facturas?purchase_order_id=1'
|
||||
: null,
|
||||
relatedProcesses: [
|
||||
{ id: 4, number: 'REQ<QA>', href: '/requisicoes/4/processo' },
|
||||
{
|
||||
id: 7,
|
||||
number: 'REQ-SECOND-QA',
|
||||
href: '/requisicoes/7/processo',
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(html).toContain('Documentos relacionados da ordem');
|
||||
expect(html).toContain('href="/requisicoes/4/processo"');
|
||||
expect(html).toContain('href="/requisicoes/7/processo"');
|
||||
expect(html).toContain('REQ<QA>');
|
||||
expect(html.includes('/facturas?purchase_order_id=1')).toBe(finance);
|
||||
expect(html).toContain('Artigo preservado');
|
||||
},
|
||||
);
|
||||
import ReceiptShow from '@/pages/receipts/show';
|
||||
|
||||
test.each([false, true])(
|
||||
'receipt detail retains the original and only offers the financial link supplied by the server (%s)',
|
||||
(finance) => {
|
||||
const html = render(ReceiptShow, {
|
||||
receipt: {
|
||||
id: 8,
|
||||
number: 'REC-QA',
|
||||
purchase_order_id: 1,
|
||||
delivery_note: 'GUIA-QA',
|
||||
received_on: '2026-11-28',
|
||||
confirmed_at: '2026-11-28T12:00:00Z',
|
||||
status: 'complete',
|
||||
snapshot: {
|
||||
order: { id: 1, number: 'OC-QA' },
|
||||
supplier: { name: 'Fornecedor QA' },
|
||||
receiver: { name: 'Armazém QA' },
|
||||
warehouse: null,
|
||||
},
|
||||
items: [],
|
||||
},
|
||||
movements: [],
|
||||
financialDocumentsHref: finance
|
||||
? '/facturas?purchase_order_id=1#invoice-documents'
|
||||
: null,
|
||||
});
|
||||
expect(
|
||||
html.includes(
|
||||
'href="/facturas?purchase_order_id=1#invoice-documents"',
|
||||
),
|
||||
).toBe(finance);
|
||||
expect(html).toContain('GUIA-QA');
|
||||
expect(html).toContain('Recepção total aceite');
|
||||
expect(html).toContain('/recepcoes/8/imprimir');
|
||||
expect(html).toContain('/ordens/1/recepcoes');
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { App } from '@inertiajs/react';
|
||||
import type { Page } from '@inertiajs/core';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { renderToString } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import { QuotationCommercialTerms } from '@/components/quotation-commercial-terms';
|
||||
@@ -23,7 +24,7 @@ const policy = {
|
||||
weights: { price: 40, quality: 20, delivery: 15, history: 15, payment: 10 },
|
||||
};
|
||||
function render(
|
||||
Component: typeof Comparison | typeof QuotationExchangePanel,
|
||||
Component: ComponentProps<typeof App>['initialComponent'],
|
||||
props: Record<string, unknown>,
|
||||
) {
|
||||
const page = {
|
||||
@@ -39,6 +40,54 @@ function render(
|
||||
);
|
||||
}
|
||||
|
||||
test.each([true, false])(
|
||||
'related quotation stages remain grouped and preserve conditional urgency access (%s)',
|
||||
(urgent) => {
|
||||
const html = render(Comparison, {
|
||||
requisition: {
|
||||
id: 42,
|
||||
number: 'REQ-42',
|
||||
justification: 'Synthetic navigation QA',
|
||||
items: [],
|
||||
},
|
||||
suppliers: [],
|
||||
quotations: [],
|
||||
canCreate: false,
|
||||
canEvaluate: false,
|
||||
ready: false,
|
||||
topIds: [],
|
||||
comparisonPolicy: {
|
||||
...policy,
|
||||
...(urgent ? { urgent_minimum_proposals: 1 } : {}),
|
||||
},
|
||||
urgentQuotationReady: urgent,
|
||||
});
|
||||
const group = html.match(
|
||||
/<details[^>]*>[\s\S]*?Outras etapas e documentos do processo[\s\S]*?<\/details>/,
|
||||
)?.[0];
|
||||
expect(group).toBeDefined();
|
||||
expect(group).not.toMatch(/<details[^>]*\bopen\b/);
|
||||
expect(group).toContain(
|
||||
'aria-label="Etapas e documentos relacionados"',
|
||||
);
|
||||
expect(group).toContain('grid gap-3 sm:grid-cols-2');
|
||||
for (const path of [
|
||||
'abertura',
|
||||
'qualificacao',
|
||||
'admissao',
|
||||
'recomendacao',
|
||||
'relatorio',
|
||||
]) {
|
||||
expect(group).toContain(`/requisicoes/42/${path}`);
|
||||
}
|
||||
expect(group).toContain('href="/requisicoes/42"');
|
||||
expect(group).toContain('href="/conflitos"');
|
||||
expect(group?.includes('/requisicoes/42/urgencia-stock')).toBe(urgent);
|
||||
expect(html).toContain('href="/requisicoes/42/adjudicacao"');
|
||||
expect(html).toContain('Comparação ainda incompleta.');
|
||||
},
|
||||
);
|
||||
|
||||
test.each([true, false])(
|
||||
'process rates retain provenance and restrict the finance form (%s)',
|
||||
(canRecord) => {
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import { App, router } from '@inertiajs/react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { afterEach, expect, test, vi } from 'vitest';
|
||||
import Evaluation from '@/pages/suppliers/evaluation';
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
const payload = {
|
||||
title: 'Avaliação QA',
|
||||
nature: 'goods',
|
||||
scope: 'Âmbito sintético.',
|
||||
period_start: '2026-11-28',
|
||||
period_end: '2026-11-28',
|
||||
order_ids: [],
|
||||
criteria: [],
|
||||
conclusion: 'Conclusão original.',
|
||||
critical_occurrences: '',
|
||||
critical_evidence: '',
|
||||
};
|
||||
const identity =
|
||||
'procurement-preparations:4:7:procurement.internal:procurement:supplier-evaluation:1:3';
|
||||
function render(
|
||||
kind: 'evidence' | 'decision',
|
||||
actor = 7,
|
||||
tenant = 4,
|
||||
context = 'procurement.internal',
|
||||
version = 3,
|
||||
reportOnly = false,
|
||||
) {
|
||||
return renderToStaticMarkup(
|
||||
<App
|
||||
initialComponent={Evaluation}
|
||||
initialPage={{
|
||||
component: 'suppliers/evaluation',
|
||||
url: '/fornecedores/avaliacoes/1',
|
||||
version: null,
|
||||
clearHistory: false,
|
||||
encryptHistory: true,
|
||||
props: {
|
||||
errors: {},
|
||||
auth: { user: { id: actor, tenant_id: tenant } },
|
||||
workContext: { active: context },
|
||||
organizationAccess: { permissions: ['procurement'] },
|
||||
reportOnly,
|
||||
canEdit: kind === 'evidence' && !reportOnly,
|
||||
canReview: kind === 'decision' && !reportOnly,
|
||||
canRevise: false,
|
||||
nextRevisionId: null,
|
||||
orders: [],
|
||||
people: {},
|
||||
history: {
|
||||
data: [],
|
||||
total: 0,
|
||||
prev_page_url: null,
|
||||
next_page_url: null,
|
||||
},
|
||||
generatedAt: '2026-11-28T12:00:00Z',
|
||||
improvements: { ready: false, records: [] },
|
||||
responses: { ready: false, records: [] },
|
||||
evaluation: {
|
||||
id: 1,
|
||||
supplier_id: 2,
|
||||
revision: 1,
|
||||
version,
|
||||
status: kind === 'evidence' ? 'draft' : 'review',
|
||||
previous_id: null,
|
||||
created_by: 9,
|
||||
contributors: [9],
|
||||
supplier_snapshot: {
|
||||
id: 2,
|
||||
name: 'Fornecedor QA',
|
||||
nuit: '123456789',
|
||||
},
|
||||
payload,
|
||||
review_reason: null,
|
||||
reviewed_at: null,
|
||||
reviewed_by: null,
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
test.each(['evidence', 'decision'] as const)(
|
||||
'%s navigation targets only present focusable sections and preserves report boundaries',
|
||||
(kind) => {
|
||||
for (const reportOnly of [false, true]) {
|
||||
const html = render(
|
||||
kind,
|
||||
7,
|
||||
4,
|
||||
'procurement.internal',
|
||||
3,
|
||||
reportOnly,
|
||||
);
|
||||
const navigation = html.match(
|
||||
/<nav aria-label="Áreas da avaliação do fornecedor"[\s\S]*?<\/nav>/,
|
||||
)?.[0];
|
||||
expect(navigation).toBeDefined();
|
||||
const targets = [...navigation!.matchAll(/href="#([^"]+)"/g)].map(
|
||||
(match) => match[1],
|
||||
);
|
||||
for (const id of targets) {
|
||||
expect(html.split(`id="${id}"`)).toHaveLength(2);
|
||||
expect(html).toContain(`id="${id}" tabindex="-1"`);
|
||||
}
|
||||
expect(targets).toContain('evaluation-evidence');
|
||||
expect(targets).toContain('evaluation-improvements');
|
||||
expect(targets).toContain('evaluation-responses');
|
||||
expect(targets.includes('evaluation-review')).toBe(
|
||||
kind === 'decision' && !reportOnly,
|
||||
);
|
||||
expect(targets.includes('evaluation-history')).toBe(!reportOnly);
|
||||
expect(targets).not.toContain('evaluation-last-review');
|
||||
expect(targets).not.toContain('evaluation-revision');
|
||||
expect(html).toContain(
|
||||
'class="rounded-xl border bg-card p-4 print:hidden"',
|
||||
);
|
||||
expect(html).not.toContain('<details open');
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test.each(['evidence', 'decision'] as const)(
|
||||
'%s preparation recovers only for the same actor company context and source version without submitting',
|
||||
(kind) => {
|
||||
vi.spyOn(router, 'restore').mockImplementation((key) =>
|
||||
key === `${identity}:${kind}:data`
|
||||
? kind === 'evidence'
|
||||
? {
|
||||
version: 3,
|
||||
payload: {
|
||||
...payload,
|
||||
conclusion: 'PRIVATE-QA-PREPARATION',
|
||||
},
|
||||
}
|
||||
: { version: 3, reason: 'PRIVATE-QA-PREPARATION' }
|
||||
: undefined,
|
||||
);
|
||||
const post = vi.spyOn(router, 'post');
|
||||
const put = vi.spyOn(router, 'put');
|
||||
expect(render(kind)).toContain('PRIVATE-QA-PREPARATION');
|
||||
expect(render(kind)).toContain('data-preparation-dirty="true"');
|
||||
expect(render(kind, 8)).not.toContain('PRIVATE-QA-PREPARATION');
|
||||
expect(render(kind, 7, 5)).not.toContain('PRIVATE-QA-PREPARATION');
|
||||
expect(render(kind, 7, 4, 'finance')).not.toContain(
|
||||
'PRIVATE-QA-PREPARATION',
|
||||
);
|
||||
expect(render(kind, 7, 4, 'procurement.internal', 4)).not.toContain(
|
||||
'PRIVATE-QA-PREPARATION',
|
||||
);
|
||||
expect(
|
||||
render(kind, 7, 4, 'procurement.internal', 3, true),
|
||||
).not.toContain('PRIVATE-QA-PREPARATION');
|
||||
expect(post).not.toHaveBeenCalled();
|
||||
expect(put).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
test('a clean recovered evidence form is not dirty because object keys changed order', () => {
|
||||
vi.spyOn(router, 'restore').mockImplementation((key) =>
|
||||
key === `${identity}:evidence:data`
|
||||
? {
|
||||
version: 3,
|
||||
payload: Object.fromEntries(
|
||||
Object.entries(payload).reverse(),
|
||||
),
|
||||
}
|
||||
: undefined,
|
||||
);
|
||||
expect(render('evidence')).not.toContain('data-preparation-dirty="true"');
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { App } from '@inertiajs/react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import Evaluation from '@/pages/suppliers/evaluation';
|
||||
|
||||
test.each([false, true])(
|
||||
'report preserves the decision and identifies only the recorded reviewer (%s)',
|
||||
(knownName) => {
|
||||
const html = renderToStaticMarkup(
|
||||
<App
|
||||
initialComponent={Evaluation}
|
||||
initialPage={{
|
||||
component: 'suppliers/evaluation',
|
||||
url: '/fornecedores/avaliacoes/1/relatorio',
|
||||
version: null,
|
||||
clearHistory: false,
|
||||
encryptHistory: true,
|
||||
props: {
|
||||
errors: {},
|
||||
reportOnly: true,
|
||||
canEdit: false,
|
||||
canReview: false,
|
||||
canRevise: false,
|
||||
nextRevisionId: null,
|
||||
orders: [],
|
||||
people: knownName ? { 7: 'Revisor <QA>' } : {},
|
||||
history: {
|
||||
data: [],
|
||||
total: 0,
|
||||
prev_page_url: null,
|
||||
next_page_url: null,
|
||||
},
|
||||
generatedAt: '2026-11-28T12:00:00Z',
|
||||
improvements: { ready: false, records: [] },
|
||||
responses: { ready: false, records: [] },
|
||||
evaluation: {
|
||||
id: 1,
|
||||
supplier_id: 2,
|
||||
revision: 1,
|
||||
version: 3,
|
||||
status: 'approved',
|
||||
previous_id: null,
|
||||
created_by: 4,
|
||||
contributors: [4],
|
||||
supplier_snapshot: {
|
||||
id: 2,
|
||||
name: 'Fornecedor QA',
|
||||
nuit: '123456789',
|
||||
},
|
||||
payload: {
|
||||
title: 'Avaliação QA',
|
||||
nature: 'goods',
|
||||
scope: 'Âmbito sintético.',
|
||||
period_start: '2026-11-28',
|
||||
period_end: '2026-11-28',
|
||||
order_ids: [],
|
||||
criteria: [],
|
||||
conclusion: 'Conclusão preservada.',
|
||||
critical_occurrences: '',
|
||||
critical_evidence: '',
|
||||
},
|
||||
review_reason: 'Fundamento preservado.',
|
||||
reviewed_by: 7,
|
||||
reviewed_at: '2026-11-28T12:00:00Z',
|
||||
},
|
||||
},
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
expect(html).toContain('Última decisão documentada');
|
||||
expect(html).toContain('href="#evaluation-last-review"');
|
||||
expect(html).toContain('id="evaluation-last-review" tabindex="-1"');
|
||||
expect(html).not.toContain('href="#evaluation-history"');
|
||||
expect(html).toContain('Fundamento preservado.');
|
||||
expect(html).toContain(knownName ? 'Revisor <QA>' : '#7');
|
||||
expect(html).not.toContain('Revisor <QA>');
|
||||
expect(html).not.toContain('2026-11-28T12:00:00Z');
|
||||
expect(html).not.toContain('<form');
|
||||
const decisionGroup = html.match(
|
||||
/<div class="print:break-inside-avoid">([\s\S]*?)<\/section><\/div>/,
|
||||
)?.[1];
|
||||
expect(decisionGroup).toContain('Fundamento preservado.');
|
||||
expect(decisionGroup).toContain(
|
||||
knownName ? 'Revisor <QA>' : '#7',
|
||||
);
|
||||
expect(decisionGroup).toContain(
|
||||
new Date('2026-11-28T12:00:00Z').toLocaleString('pt-MZ'),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -62,6 +62,96 @@ function render(overrides = {}, actor = 7, tenant = 4) {
|
||||
);
|
||||
}
|
||||
|
||||
test('contract workspace names its own preparation and document reference with separated navigation', () => {
|
||||
const html = render({
|
||||
kind: 'contract',
|
||||
view: 'contracts',
|
||||
orderLimitsReady: true,
|
||||
records: [
|
||||
{
|
||||
...record,
|
||||
kind: 'contract',
|
||||
data: {
|
||||
...record.data,
|
||||
reference: '<script>QA-CONTRACT</script>',
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(html).toContain('Novo contrato com vários artigos');
|
||||
expect(html).not.toContain('Novo acordo de fornecimento');
|
||||
expect(html).toContain('Contrato <script>QA-CONTRACT</script>');
|
||||
expect(html).not.toContain('<script>QA-CONTRACT</script>');
|
||||
const navigation = html.match(
|
||||
/<nav aria-label="Consultas e cadastros de fornecimento"[\s\S]*?<\/nav>/,
|
||||
)?.[0];
|
||||
expect(navigation).toContain('flex flex-wrap gap-x-4 gap-y-2');
|
||||
expect(navigation).toContain('/compras/acordos/vigencia?kind=contract');
|
||||
expect(navigation).toContain('/compras/fornecimento?view=agreements');
|
||||
});
|
||||
|
||||
test('contract without a documentary reference stays explicit and read-only users get no preparation', () => {
|
||||
const html = render({
|
||||
kind: 'contract',
|
||||
view: 'contracts',
|
||||
canPrepare: false,
|
||||
records: [
|
||||
{
|
||||
...record,
|
||||
data: { reference: '' },
|
||||
canApprove: false,
|
||||
canReturn: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(html).toContain('Contrato sem referência indicada');
|
||||
expect(html).not.toContain('Novo contrato com vários artigos');
|
||||
expect(html).not.toContain('Abrir preparação');
|
||||
expect(render()).toContain('Novo acordo de fornecimento');
|
||||
});
|
||||
|
||||
test('supply guidance follows the current area and keeps customs responsibilities in imports', () => {
|
||||
const areas = [
|
||||
[
|
||||
'contracts',
|
||||
'contract',
|
||||
'limites globais',
|
||||
'Compras prepara os contratos',
|
||||
],
|
||||
[
|
||||
'agreements',
|
||||
'agreement',
|
||||
'condições de fornecimento',
|
||||
'Compras prepara os acordos',
|
||||
],
|
||||
[
|
||||
'calendar',
|
||||
'policy',
|
||||
'parâmetros de stock',
|
||||
'Compras prepara as políticas',
|
||||
],
|
||||
];
|
||||
for (const [view, kind, description, responsibility] of areas) {
|
||||
const html = render({ view, kind, records: [], canPrepare: false });
|
||||
expect(html).toContain(description);
|
||||
expect(html).toContain(responsibility);
|
||||
expect(html).not.toContain('responsável aduaneiro');
|
||||
expect(html).not.toContain('Logística acompanha');
|
||||
}
|
||||
const imports = render({
|
||||
view: 'imports',
|
||||
kind: 'import',
|
||||
records: [],
|
||||
canPrepare: false,
|
||||
orderLimitsReady: true,
|
||||
});
|
||||
expect(imports).toContain('Acompanhe as ordens importadas');
|
||||
expect(imports).toContain('Logística acompanha embarque e chegada');
|
||||
expect(imports).toContain('responsável aduaneiro');
|
||||
expect(imports).not.toContain('Compras prepara os contratos');
|
||||
expect(imports).not.toContain('Consultas e cadastros de fornecimento');
|
||||
});
|
||||
|
||||
test('new supply preparation restores without saving and is isolated by identity, source and capabilities', () => {
|
||||
vi.spyOn(router, 'restore').mockImplementation((key) =>
|
||||
key === `${identity()}:prepare:data`
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { App } from '@inertiajs/react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import Availability from '@/pages/stock/availability';
|
||||
|
||||
test.each([true, false])(
|
||||
'availability explains the actual reservation capability and preserves unknown balances (%s)',
|
||||
(ready) => {
|
||||
const Screen = () => (
|
||||
<Availability
|
||||
filters={{ warehouse_id: 1 }}
|
||||
warehouses={[]}
|
||||
warehouse={{ name: 'Armazém QA' }}
|
||||
checkedAt="2026-11-28T12:00:00Z"
|
||||
planningVisible={false}
|
||||
reservationsAvailable={ready}
|
||||
rows={{
|
||||
total: 1,
|
||||
prev_page_url: null,
|
||||
next_page_url: null,
|
||||
data: [
|
||||
{
|
||||
id: 1,
|
||||
code: 'QA-1',
|
||||
name: 'Material sintético',
|
||||
unit: 'un',
|
||||
physical_milli: 10000,
|
||||
usable_milli: 10000,
|
||||
blocked_milli: null,
|
||||
lot_control: false,
|
||||
reconciled: true,
|
||||
planned_milli: null,
|
||||
minimum_milli: null,
|
||||
at_minimum: false,
|
||||
physical_commitment_milli: ready ? 3000 : null,
|
||||
free_milli: ready ? 7000 : null,
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>
|
||||
);
|
||||
const html = renderToStaticMarkup(
|
||||
<App
|
||||
initialComponent={Screen}
|
||||
initialPage={{
|
||||
component: 'stock/availability',
|
||||
url: '/stock/disponibilidade?warehouse_id=1',
|
||||
version: null,
|
||||
props: { errors: {} },
|
||||
}}
|
||||
/>,
|
||||
).replace(/\s+/g, ' ');
|
||||
expect(html).toContain('data-query-form="true"');
|
||||
expect(html).not.toContain('ainda não estão implementados');
|
||||
if (ready) {
|
||||
expect(html).toContain('menos as reservas físicas registadas');
|
||||
expect(html).not.toContain('Saldo livre por determinar');
|
||||
} else {
|
||||
expect(html).toContain(
|
||||
'reservas físicas não estão disponíveis nesta consulta',
|
||||
);
|
||||
expect(html).toContain('Saldo livre por determinar');
|
||||
}
|
||||
expect(html).toContain('Sem acesso ao planeamento');
|
||||
},
|
||||
);
|
||||
Reference in New Issue
Block a user