commit melhorias compras3
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-22 10:56:58 +02:00
parent 4fac443dda
commit efd97e265b
130 changed files with 8917 additions and 363 deletions
+135
View File
@@ -0,0 +1,135 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import AgreementFollowup from '@/pages/supply/agreement-followup';
test.each([null, 0])(
'global contract report keeps its scope and distinguishes absent limit from %s',
(limit) => {
const html = renderToStaticMarkup(
<App
initialPage={{
component: 'supply/agreement-followup',
url: '/compras/acordos/vigencia?kind=contract',
version: null,
props: {
kind: 'contract',
asOf: '2026-11-22',
filters: {
search: '',
validity: 'current',
expires_by: '',
},
records: {
total: 1,
current_page: 1,
last_page: 1,
prev_page_url: null,
next_page_url: null,
data: [
{
id: 1,
record_key: 'header',
version: 2,
reference: 'CONTRATO-QA',
supplier: 'Fornecedor sintético',
currency: 'MZN',
max_order_value_minor: limit,
periodicity_days: null,
approved_articles: 2,
valid_from: '2026-11-22',
valid_until: '2026-12-22',
validity: 'current',
approved_policies: 0,
item_code: null,
item: null,
warehouse: null,
href: '/compras/fornecimento?view=contracts&record_id=1',
articles_href:
'/compras/fornecimento?view=agreements&linked_contract_key=header',
policies_href: '/unused',
},
],
},
},
clearHistory: false,
encryptHistory: true,
}}
initialComponent={AgreementFollowup}
/>,
);
expect(html).toContain('Vigência dos contratos globais');
expect(html).toContain('kind=contract');
expect(html).toContain('2 artigo(s) aprovado(s) ligado(s)');
expect(html).toContain('Consultar artigos ligados');
expect(html).toContain('linked_contract_key=header');
expect(html).toContain('Cada ordem pode usar o limite completo');
expect(html).toContain('Não gera ordens automáticas');
expect(html).not.toContain('Código não disponível');
expect(html).not.toContain('href="/unused"');
expect(html.includes('Limite global por ordem: Não definido')).toBe(
limit === null,
);
},
);
test('agreement followup keeps explicit filters in the csv and distinguishes documentary vigency from purchase authority', () => {
const html = renderToStaticMarkup(
<App
initialPage={{
component: 'supply/agreement-followup',
url: '/compras/acordos/vigencia',
version: null,
props: {
asOf: '2026-11-21',
filters: {
search: 'FROZEN',
validity: 'expired',
expires_by: '2026-11-30',
},
records: {
total: 27,
current_page: 2,
last_page: 2,
prev_page_url:
'/compras/acordos/vigencia?page=1&search=FROZEN',
next_page_url: null,
data: [
{
id: 4,
record_key: 'synthetic',
version: 2,
reference: '<unsafe>',
supplier: 'Fornecedor sintético',
item_code: 'TEST-ITEM',
item: 'Artigo',
warehouse: 'Armazém',
valid_from: null,
valid_until: null,
validity: 'unknown',
approved_policies: 2,
href: '/compras/fornecimento?view=agreements&record_id=4',
policies_href:
'/compras/fornecimento?view=calendar&linked_agreement_key=synthetic',
},
],
},
errors: {},
},
clearHistory: false,
encryptHistory: true,
}}
initialComponent={AgreementFollowup}
/>,
);
expect(html).toContain('Vigência dos acordos');
expect(html).toContain('não renova acordos');
expect(html).toContain('search=FROZEN');
expect(html).toContain('expires_by=2026-11-30');
expect(html).toContain('política(s) aprovada(s) ligada(s)');
expect(html).toContain('Datas indeterminadas');
expect(html).toContain('Início: Não disponível');
expect(html).toContain('&lt;unsafe&gt;');
expect(html).not.toContain('<unsafe>');
expect(html).toContain('linked_agreement_key=synthetic');
});
@@ -0,0 +1,106 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import AgreementOrderBindings, {
AgreementOrderLimitSummary,
} from '@/components/agreement-order-bindings';
import type { FrozenOrderAgreement } from '@/types/purchase';
const option = {
contract: {
reference: 'CONTRATO-GLOBAL-ANTES-EMISSAO',
version: 2,
currency: 'MZN',
max_order_value_minor: 20000,
},
id: 7,
version: 2,
reference: 'ACORDO-QA',
stock_item_id: 3,
warehouse: 'Armazém de teste',
unit: 'un',
currency: 'MZN',
max_order_value_minor: 10000,
max_order_quantity_milli: 1000,
};
test('issue form makes association explicit and describes a full limit for each order', () => {
const html = renderToStaticMarkup(
<AgreementOrderBindings
requestId={1}
lines={[
{
id: 4,
description: 'Artigo sintético',
stock_item_id: 3,
unit: 'un',
},
]}
options={[option]}
value={[{ requisition_item_id: 4, agreement_id: 7 }]}
onChange={() => {}}
/>,
);
expect(html).toContain('Cada ordem pode utilizar o limite completo');
expect(html).toContain('sem somar outras ordens');
expect(html).toContain('ACORDO-QA');
expect(html).toContain('Sem acordo associado');
expect(html).toContain('Pesquisar acordos');
expect(html).toContain('CONTRATO-GLOBAL-ANTES-EMISSAO');
expect(html).toContain('Soma todos os artigos ligados ao mesmo contrato');
expect(html).toContain('type="button"');
});
test('a missing selected version is visibly unavailable and a catalogue identity is required instead of a name match', () => {
const html = renderToStaticMarkup(
<AgreementOrderBindings
requestId={1}
lines={[
{
id: 4,
description: 'Artigo sintético',
stock_item_id: null,
unit: 'un',
},
]}
options={[]}
value={[{ requisition_item_id: 4, agreement_id: 7 }]}
onChange={() => {}}
/>,
);
expect(html).toContain('Selecção já não disponível');
expect(html).toContain('disabled');
expect(html).toContain('o nome da linha não comprova essa ligação');
});
test('order summary uses frozen group totals once per agreement and keeps absence separate from zero', () => {
const row: FrozenOrderAgreement = {
contract: {
id: 5,
reference: 'CONTRATO-GLOBAL-QA',
version: 2,
currency: 'MZN',
max_order_value_minor: null,
checked_order_value_minor: 20000,
},
agreement_id: 7,
record_key: 'synthetic',
version: 2,
reference: 'ACORDO-QA',
unit: 'un',
currency: 'MZN',
checked_order_value_minor: 0,
checked_order_quantity_milli: '2000',
max_order_value_minor: null,
max_order_quantity_milli: 0,
};
const html = renderToStaticMarkup(
<AgreementOrderLimitSummary bindings={{ 1: row, 2: row }} />,
);
expect(html.match(/ACORDO-QA/g)).toHaveLength(1);
expect(html.match(/CONTRATO-GLOBAL-QA/g)).toHaveLength(1);
expect(html).toContain('Total com impostos dos artigos ligados');
expect(html).toContain('Não definido');
expect(html).toContain('2,000 un');
expect(html).toContain('0,000 un');
expect(html).toContain('sem acumular outras ordens');
expect(renderToStaticMarkup(<AgreementOrderLimitSummary />)).toBe('');
});
+94
View File
@@ -0,0 +1,94 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import { CompanyDetailsSettings } from '@/components/company-details-settings';
function render(ready: boolean) {
return renderToStaticMarkup(
<App
initialComponent={CompanyDetailsSettings}
initialPage={{
component: 'company/parameters',
url: '/administracao/parametrizacao',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
ready,
version: 3,
errors: {},
details: {
legal_name: 'Empresa sintética <QA>',
nuit: '001234567',
bank_accounts: [
{
id: 'a',
bank: 'Banco sintético A',
account_number: '00001234',
currency: 'MZN',
},
{
id: 'b',
bank: 'Banco sintético B',
account_number: '00005678',
currency: 'USD',
},
],
establishments: [
{
id: 'c',
kind: 'headquarters',
name: 'Sede sintética',
address: 'Endereço A',
},
{
id: 'd',
kind: 'branch',
name: 'Sucursal sintética',
address: 'Endereço B',
},
],
},
},
}}
/>,
);
}
test('company form presents distinct accounts and establishments with Portuguese labels and preserved identifiers', () => {
const html = render(true);
for (const text of [
'Denominação social',
'NUEL',
'NUIT',
'Representante legal',
'Balcão',
'Número de conta',
'NIB',
'IBAN',
'NUIB',
'Titular da conta',
'00001234',
'00005678',
'MZN',
'USD',
'Endereço A',
'Endereço B',
'Adicionar estabelecimento',
'Adicionar conta bancária',
]) {
expect(html).toContain(text);
}
expect(html).toContain('Empresa sintética &lt;QA&gt;');
expect(html).toContain('id="bank-a-account_number"');
expect(html).toContain('id="bank-b-account_number"');
expect(html).toContain('id="establishment-c-name"');
expect(html).toContain('id="establishment-d-name"');
});
test('uninstalled schema explains availability without presenting a form that cannot save', () => {
const html = render(false);
expect(html).toContain('Instalação dos campos da empresa pendente');
expect(html).not.toContain('<form');
expect(html).not.toContain('00001234');
});
@@ -0,0 +1,67 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import RequisitionForm from '@/pages/requisitions/form';
import { money, date } from '@/types/procurement';
test('incomplete draft restores the supplied line and missing amounts without inventing zero prices', () => {
const html = renderToStaticMarkup(
<App
initialComponent={RequisitionForm}
initialPage={{
component: 'requisitions/form',
url: '/requisicoes/9/editar',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
internalRequisitionReady: true,
incompleteDraftsAvailable: true,
costCenters: [],
requisition: {
id: 9,
process_version: 1,
number: 'QA-DRAFT-9',
status: 'draft',
priority: 'normal',
needed_by: null,
justification: 'Ini',
cost_center_id: null,
subtotal_minor: null,
tax_minor: null,
total_minor: null,
created_at: '2026-11-22',
items: [],
steps: [],
draft_input: {
incomplete: true,
values: {
justification: 'Ini',
items: [
{
description: 'Preparação recuperada',
quantity: null,
unit_price: null,
tax_rate: '16.00',
},
],
},
},
},
},
}}
/>,
);
expect(html).toContain('Preparação recuperada');
expect(html).toMatch(/novalidate=""/i);
expect(html).toContain('Por completar');
expect(html).not.toContain('value="null"');
expect(html).not.toContain('value="0.00"');
});
test('unknown money and dates are distinguishable from a genuine zero value', () => {
expect(money(null)).toBe('Por completar');
expect(date(null)).toBe('Por completar');
expect(money(0)).not.toBe('Por completar');
});
+177
View File
@@ -0,0 +1,177 @@
import { readdirSync } from 'node:fs';
import { join, relative } from 'node:path';
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import JourneyHelpPanel, {
JourneyHelpContent,
} from '@/components/journey-help';
import { FormErrors } from '@/components/procurement';
import {
helpAudience,
helpForJourney,
journeyHelp,
searchJourneyHelp,
recoveryHints,
} from '@/lib/journey-help';
function pageFiles(root: string): string[] {
return readdirSync(root, { withFileTypes: true }).flatMap((entry) =>
entry.isDirectory()
? pageFiles(join(root, entry.name))
: entry.name.endsWith('.tsx')
? [join(root, entry.name)]
: [],
);
}
test('multiarticle contract preparation has guidance for its global limit and independent article quantities', () => {
const help = helpForJourney(
'supply/index',
'/compras/fornecimento?view=contracts',
);
expect(help.id).toBe('supply-contract');
expect(help.checks.join(' ')).toContain(
'Cada ordem pode usar o limite completo',
);
expect(help.checks.join(' ')).toContain(
'Não some quantidades de unidades diferentes',
);
});
test('every operational page has a specific guide rather than silently falling back to generic instructions', () => {
const root = join(process.cwd(), 'resources/js/pages');
const pages = pageFiles(root)
.map((file) =>
relative(root, file)
.replace(/\\/g, '/')
.replace(/\.tsx$/, ''),
)
.filter((name) => !name.startsWith('preview/'));
const missing = pages.filter(
(name) => !journeyHelp.some((topic) => topic.pages.includes(name)),
);
expect(missing).toEqual([]);
expect(new Set(journeyHelp.map((topic) => topic.id)).size).toBe(
journeyHelp.length,
);
for (const name of pages)
expect(helpForJourney(name, '/').audience).toBe(helpAudience(name));
});
test('the supply guide follows the actual stage including imports calendar and technical alternatives', () => {
expect(
helpForJourney('supply/index', '/compras/fornecimento?view=imports').id,
).toBe('supply-import');
expect(
helpForJourney('supply/index', '/compras/fornecimento?view=calendar')
.id,
).toBe('supply-calendar');
expect(
helpForJourney('supply/index', '/compras/fornecimento?view=agreements')
.id,
).toBe('supply-agreement');
expect(
helpForJourney(
'supply/coordination',
'/compras/fornecimento?view=alternatives',
'alternative',
).id,
).toBe('supply-alternative');
});
test('search is local accent insensitive and confines candidate and authentication help to their own audience', () => {
expect(searchJourneyHelp('FACTURACAO', 'staff')).toEqual([]);
expect(
searchJourneyHelp('factura moeda', 'staff').map((topic) => topic.id),
).toContain('payment');
expect(
searchJourneyHelp('conversao', 'staff').map((topic) => topic.id),
).toContain('receipt');
expect(
searchJourneyHelp('candidatura', 'candidate').every(
(topic) => topic.audience === 'candidate',
),
).toBe(true);
expect(searchJourneyHelp('adjudicacao', 'candidate')).toEqual([]);
expect(searchJourneyHelp('conta', 'auth').map((topic) => topic.id)).toEqual(
['authentication'],
);
});
test('guidance separates payment evidence selection physical receipt and commercial quantities', () => {
const payment = renderToStaticMarkup(
<JourneyHelpContent
topic={helpForJourney('payments/index', '/')}
hasErrors
/>,
);
expect(payment).toContain('não executa uma transferência bancária');
expect(payment).toContain('mesma moeda');
expect(payment).toContain('Há dados por conferir');
const people = renderToStaticMarkup(
<JourneyHelpContent topic={helpForJourney('people/show', '/')} />,
);
expect(people).toContain('não comprovam assinatura ou admissão');
const invoice = renderToStaticMarkup(
<JourneyHelpContent topic={helpForJourney('invoices/index', '/')} />,
);
expect(invoice).toContain('não substitui a quantidade comercial');
});
test('validation help never submits a form and every guide includes recovery and a next action', () => {
const html = renderToStaticMarkup(
<FormErrors errors={{ quantity: 'Confira a quantidade.' }} />,
);
expect(html).toContain('role="alert"');
expect(html).toContain('type="button"');
expect(html).toContain('Consultar ajuda para corrigir e continuar');
expect(html).toContain('Confira a unidade e a quantidade ainda pendente');
for (const topic of journeyHelp) {
expect(topic.steps.length).toBeGreaterThan(0);
expect(topic.checks.length).toBeGreaterThan(0);
expect(topic.recovery.length).toBeGreaterThan(20);
expect(topic.next.length).toBeGreaterThan(20);
}
});
test('field hints address stale submissions quantities lots and bank choice without echoing private data', () => {
expect(
recoveryHints(['items.0.accepted_quantity', 'version']).join(' '),
).toContain('histórico antes de voltar a confirmar');
expect(recoveryHints(['supplier_bank_detail_id'])[0]).toContain(
'na moeda da factura',
);
expect(recoveryHints(['items.0.lots.0.expires_on'])[0]).toContain(
'unidade física',
);
expect(recoveryHints(['private_note'])).toEqual([]);
expect(
recoveryHints(['version', 'quantity', 'bank_id', 'lots']).length,
).toBe(2);
});
test('the contextual trigger is available within the current Inertia page without exposing form values', () => {
const html = renderToStaticMarkup(
<App
initialPage={{
component: 'candidate/profile',
url: '/candidaturas/perfil',
version: null,
props: {
errors: { name: 'Erro' },
privateNote: 'PRIVATE-FORM-CONTENT',
},
clearHistory: false,
encryptHistory: true,
}}
initialComponent={JourneyHelpPanel}
/>,
);
expect(html).toContain(
'Abrir ajuda desta etapa: Preparar o perfil de candidatura',
);
expect(html).toContain('Há dados por conferir');
expect(html).not.toContain('PRIVATE-FORM-CONTENT');
expect(html).not.toContain('adjudicação');
});
@@ -35,6 +35,13 @@ test.each([0, 2])(
],
},
unapproved_past_needed_date: 1,
approval_times: {
measured: 2,
unknown: 1,
total_seconds: 14400,
min_seconds: 3600,
max_seconds: 10800,
},
approved: {
count: 1,
without_registered_quotes: 0,
@@ -56,6 +63,9 @@ test.each([0, 2])(
expect(html).toContain('7 dias de calendário');
expect(html).toContain('não comprova atraso de entrega');
expect(html).toContain('não significam propostas válidas');
expect(html).toContain('Tempos de aprovação concluída');
expect(html).toContain('Média: 2 h');
expect(html).toContain('Não representa dias úteis');
}
expect(html).not.toContain('<form');
},
@@ -0,0 +1,68 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Search from '@/pages/search/procurement';
test('process search separates result groups escapes text and retains page links', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Search}
initialPage={{
component: 'search/procurement',
url: '/compras/pesquisa?q=QA',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
term: 'QA',
groups: [
{
key: 'requests',
title: 'Requisições',
records: {
total: 16,
current_page: 1,
last_page: 2,
prev_page_url: null,
next_page_url:
'/compras/pesquisa?q=QA&requests_page=2',
data: [
{
id: 7,
title: 'QA <original>',
detail: 'draft',
href: '/requisicoes/7',
},
],
},
},
],
},
}}
/>,
);
expect(html).toContain('QA &lt;original&gt;');
expect(html).toContain('Rascunho');
expect(html).toContain('q=QA&amp;requests_page=2');
expect(html).toContain('/requisicoes/7');
expect(html).toContain('ainda não pesquisa Pessoas, facturas');
});
test('empty search explains the minimum input rather than implying that the database is empty', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Search}
initialPage={{
component: 'search/procurement',
url: '/compras/pesquisa',
version: null,
clearHistory: false,
encryptHistory: true,
props: { errors: {}, term: '', groups: [] },
}}
/>,
);
expect(html).toContain('Introduza pelo menos dois caracteres');
expect(html).not.toContain('Nenhum resultado no seu âmbito');
});
+221
View File
@@ -0,0 +1,221 @@
import { afterEach, expect, test, vi } from 'vitest';
import { departureUrl, protectDepartures } from '@/lib/unsaved-navigation';
const state = vi.hoisted(() => ({
before: null as ((event: any) => void) | null,
visit: vi.fn(),
off: vi.fn(),
}));
vi.mock('@inertiajs/react', () => ({
router: {
on: (_name: string, callback: (event: any) => void) => {
state.before = callback;
return state.off;
},
visit: state.visit,
},
}));
afterEach(() => {
vi.unstubAllGlobals();
vi.clearAllMocks();
});
function fixture() {
const doc = new EventTarget();
const win = Object.assign(new EventTarget(), {
location: {
href: 'http://localhost/requisicoes/criar',
assign: vi.fn(),
},
});
class Link {
href = 'http://localhost/fornecedores?search=QA';
target = '';
download = false;
closest() {
return this;
}
hasAttribute(name: string) {
return name === 'download' && this.download;
}
}
vi.stubGlobal('document', doc);
vi.stubGlobal('window', win);
vi.stubGlobal('Element', Link);
let dirty = true;
let proceed: (() => void) | undefined;
const prompt = vi.fn((next: () => void) => {
proceed = next;
});
const cleanup = protectDepartures(() => dirty, prompt);
const link = new Link();
const click = (extra: Record<string, unknown> = {}) => {
const event = new Event('click', { cancelable: true });
Object.defineProperties(
event,
Object.fromEntries(
Object.entries({
target: link,
button: 0,
ctrlKey: false,
metaKey: false,
shiftKey: false,
altKey: false,
...extra,
}).map(([key, value]) => [key, { value }]),
),
);
doc.dispatchEvent(event);
return event;
};
return {
doc,
win,
link,
prompt,
click,
cleanup,
clean: () => {
dirty = false;
},
proceed: () => proceed?.(),
};
}
test('a dirty form blocks departure to suppliers until the user chooses to leave, retaining the exact destination', () => {
const f = fixture();
expect(f.click().defaultPrevented).toBe(true);
expect(f.win.location.assign).not.toHaveBeenCalled();
expect(f.prompt).toHaveBeenCalledOnce();
f.clean();
f.proceed();
expect(f.win.location.assign).toHaveBeenCalledWith(
'http://localhost/fornecedores?search=QA',
);
f.cleanup();
});
test.each([
{ ctrlKey: true },
{ metaKey: true },
{ shiftKey: true },
{ altKey: true },
{ button: 1 },
])(
'new-tab and modified clicks do not abandon the current form: %j',
(extra) => {
const f = fixture();
expect(f.click(extra).defaultPrevented).toBe(false);
expect(f.prompt).not.toHaveBeenCalled();
f.cleanup();
},
);
test('downloads, other targets, same-page anchors and clean forms continue normally', () => {
const f = fixture();
f.link.download = true;
expect(f.click().defaultPrevented).toBe(false);
f.link.download = false;
f.link.target = '_blank';
expect(f.click().defaultPrevented).toBe(false);
f.link.target = '';
f.link.href = `${f.win.location.href}#linhas`;
expect(f.click().defaultPrevented).toBe(false);
f.link.href = 'http://localhost/stock';
f.clean();
expect(f.click().defaultPrevented).toBe(false);
expect(f.prompt).not.toHaveBeenCalled();
f.cleanup();
});
test('programmatic GET navigation is deferred with filters preserved while saving POST is allowed', () => {
const f = fixture();
const visit = {
method: 'get',
url: new URL('http://localhost/relatorios'),
data: { status: 'pending' },
preserveScroll: true,
};
const preventDefault = vi.fn();
state.before?.({ detail: { visit }, preventDefault });
expect(preventDefault).toHaveBeenCalledOnce();
expect(state.visit).not.toHaveBeenCalled();
f.clean();
f.proceed();
expect(state.visit).toHaveBeenCalledWith(visit.url, visit);
f.cleanup();
const g = fixture();
const allowSave = vi.fn();
state.before?.({
detail: { visit: { ...visit, method: 'post' } },
preventDefault: allowSave,
});
expect(allowSave).not.toHaveBeenCalled();
expect(g.prompt).not.toHaveBeenCalled();
g.cleanup();
});
test('reload prompts while dirty, and cleanup removes the listeners', () => {
const f = fixture();
const reload = new Event('beforeunload', { cancelable: true });
f.win.dispatchEvent(reload);
expect(reload.defaultPrevented).toBe(true);
f.cleanup();
const next = new Event('beforeunload', { cancelable: true });
f.win.dispatchEvent(next);
expect(next.defaultPrevented).toBe(false);
expect(state.off).toHaveBeenCalledOnce();
});
test('departure resolution retains filters and ignores fragment-only, external and non-HTTP links', () => {
expect(
departureUrl('http://localhost/requisicoes?view=mine', '?view=all'),
).toBe('http://localhost/requisicoes?view=all');
expect(
departureUrl('http://localhost/requisicoes?view=mine', '#ajuda'),
).toBeNull();
expect(
departureUrl(
'http://localhost/requisicoes',
'mailto:qa@example.invalid',
),
).toBeNull();
expect(
departureUrl('http://localhost/requisicoes', 'https://example.invalid'),
).toBeNull();
});
test('submitting a GET search does not guard its own values but still protects another edited form', async () => {
const f = fixture();
f.cleanup();
class Form {}
vi.stubGlobal('HTMLFormElement', Form);
const own = new Form();
let anotherDirty = false;
const prompt = vi.fn();
const cleanup = protectDepartures(
(except) => anotherDirty || except !== own,
prompt,
);
const submit = new Event('submit');
Object.defineProperty(submit, 'target', { value: own });
f.doc.dispatchEvent(submit);
const preventDefault = vi.fn();
const event = {
detail: {
visit: {
method: 'get',
url: new URL('http://localhost/compras/pesquisa?q=QA'),
},
},
preventDefault,
};
state.before?.(event);
expect(preventDefault).not.toHaveBeenCalled();
anotherDirty = true;
state.before?.(event);
expect(preventDefault).toHaveBeenCalledOnce();
expect(prompt).toHaveBeenCalledOnce();
await Promise.resolve();
cleanup();
});
@@ -0,0 +1,92 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Requests from '@/pages/stock/requests';
test('production use is available and the stored declared reference is escaped without suggesting external validation', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Requests}
initialPage={{
component: 'stock/requests',
url: '/stock/requisicoes',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
filters: {
view: 'all',
state: '',
search: '',
warehouse_id: null,
},
views: [],
states: {},
checkedAt: '2026-11-22T12:00:00Z',
ready: true,
canPrepare: true,
items: [],
warehouses: [],
costCenters: [],
equipment: [],
records: {
total: 1,
prev_page_url: null,
next_page_url: null,
data: [
{
id: 9,
status: 'draft',
snapshot: {
requester: { name: 'QA' },
warehouse: { name: 'QA' },
cost_center: { code: 'QA', name: 'QA' },
destination: 'Linha QA',
reason: 'Synthetic data',
priority: 'normal',
lines: [
{
item: {
id: 1,
code: 'QA',
name: 'Insumo QA',
unit: 'kg',
},
quantity_milli: 1000,
use: 'production',
destination: 'Linha QA',
equipment: null,
production: {
reference: 'OP-<QA>',
verification: 'user_supplied',
},
},
],
},
health: {
lines: [],
needs_reservation: false,
needs_check: false,
unconfirmed_deliveries: 0,
delivery_ready: false,
},
actions: {
canSubmit: false,
canReview: false,
canDeliver: false,
canManageReservation: false,
canReceive: false,
},
},
],
},
},
}}
/>,
);
expect(html).toContain('value="production"');
expect(html).toContain('Insumos para produção');
expect(html).toContain('Referência declarada: OP-&lt;QA&gt;');
expect(html).not.toContain('OP-<QA>');
});