commit compras1 2811
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-28 07:11:35 +02:00
parent d58b75c87a
commit eb32c74c56
202 changed files with 17463 additions and 1526 deletions
@@ -0,0 +1,120 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import OrderAmendment from '@/pages/purchases/order-parts-amendment';
import DistributionAmendment from '@/pages/purchases/distribution-amendment';
afterEach(() => vi.restoreAllMocks());
const allocation = {
allocation_key: 'synthetic-allocation',
line_id: 8,
centre_id: 9,
subtotal: '100.00',
total: '100.00',
};
const source = {
origin: 3,
version: 1,
plan_hash: 'synthetic-plan',
allocations: [allocation],
};
const preparedSource = {
...source,
allocations: source.allocations.map(
({ allocation_key, subtotal, total }) => ({
allocation_key,
subtotal,
total,
}),
),
};
const order = { id: 2, number: 'OC-QA', currency: 'MZN' };
function render(parts: boolean, actor = 7, plan = 'synthetic-plan') {
const component = parts ? OrderAmendment : DistributionAmendment;
return renderToStaticMarkup(
<App
initialComponent={component}
initialPage={{
component: 'purchases/amendment',
url: '/ordens/2/reafectacao',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: 4 } },
order,
history: [],
sources: [{ ...source, plan_hash: plan }],
planHash: plan,
version: 1,
options: [
{
...allocation,
line_label: 'Synthetic line',
centre_label: 'Synthetic centre',
},
],
},
}}
/>,
);
}
test.each([true, false])(
'restored Finance preparation remains dirty without submitting (%s)',
(parts) => {
const key = parts
? 'order-parts-amendment:4:7:2:3:1:synthetic-plan:data'
: 'distribution-amendment:4:7:2:synthetic-plan:data';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: '00000000-0000-4000-8000-000000000001',
reason: 'FINANCE-QA-NOT-SUBMITTED',
...(parts
? { sources: [preparedSource] }
: {
expected_plan_hash: 'synthetic-plan',
budget_distribution_preparation: [allocation],
}),
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render(parts);
expect(html).toContain('FINANCE-QA-NOT-SUBMITTED');
expect(html).toContain('data-preparation-dirty="true"');
expect(render(parts, 8)).not.toContain('FINANCE-QA-NOT-SUBMITTED');
expect(render(parts, 7, 'new-plan')).not.toContain(
'FINANCE-QA-NOT-SUBMITTED',
);
expect(post).not.toHaveBeenCalled();
},
);
test.each([true, false])(
'regenerated operation identity alone does not mark Finance preparation dirty (%s)',
(parts) => {
const key = parts
? 'order-parts-amendment:4:7:2:3:1:synthetic-plan:data'
: 'distribution-amendment:4:7:2:synthetic-plan:data';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: '00000000-0000-4000-8000-000000000001',
reason: '',
...(parts
? { sources: [preparedSource] }
: {
expected_plan_hash: 'synthetic-plan',
budget_distribution_preparation: [allocation],
}),
}
: undefined,
);
expect(render(parts)).toContain('data-preparation-dirty="false"');
},
);
+66
View File
@@ -0,0 +1,66 @@
import { App } from '@inertiajs/react';
import type { ComponentProps } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import ApprovalTimeouts from '@/pages/organization/approval-timeouts';
test('optional urgent timing has no default values and keeps explicit recipients visible for urgent-only escalation', () => {
const props: ComponentProps<typeof ApprovalTimeouts> = {
actorId: 1,
tenantId: 1,
roles: { department_head: 'Chefia' },
profiles: [{ id: 2, name: 'Perfil sintético' }],
history: { data: [], prev_page_url: null, next_page_url: null },
current: {
id: 3,
version: 1,
state: 'active',
reason: 'Política sintética',
data: {
enabled: true,
levels: [
{
role: 'department_head',
expire_minutes: 30,
reminder_minutes: 10,
escalation_minutes: null,
profile_ids: [],
},
],
},
},
};
function render() {
function Screen() {
return <ApprovalTimeouts {...props} />;
}
return renderToStaticMarkup(
<App
initialComponent={Screen}
initialPage={{
component: 'organization/approval-timeouts',
url: '/administracao/prazos-aprovacao',
version: 'qa',
clearHistory: false,
encryptHistory: true,
props: { errors: {} },
}}
/>,
);
}
const unconfigured = render();
expect(unconfigured).toContain('Prazos reduzidos para urgências');
expect(unconfigured).not.toMatch(/<details[^>]*open=/);
expect(unconfigured).not.toContain('Perfis destinatários do escalamento');
props.current!.data.levels[0] = {
...props.current!.data.levels[0],
urgent_expire_minutes: 5,
urgent_reminder_minutes: 1,
urgent_escalation_minutes: 2,
profile_ids: [2],
};
const configured = render();
expect(configured).toMatch(/<details[^>]*open=/);
expect(configured).toContain('Perfis destinatários do escalamento');
expect(configured).toContain('Perfil sintético');
});
@@ -0,0 +1,71 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Metadata from '@/pages/audit/metadata';
function render(allowed: boolean) {
return renderToStaticMarkup(
<App
initialComponent={Metadata}
initialPage={{
component: 'audit/metadata',
url: '/auditoria/eventos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
filters: {
request_reference: 'QA<REQ>%_',
action: '0',
actor_id: 7,
from: '2026-11-01',
to: '2026-11-01',
page: 2,
},
requestContext: allowed
? {
number: 'QA<REQ>%_',
href: '/requisicoes/7#requisition-history',
}
: null,
events: {
data: [
{
id: 4,
action: '0',
created_at: '2026-11-01T12:00:00Z',
user_id: 7,
},
],
total: 131,
current_page: 2,
last_page: 6,
prev_page_url:
'/auditoria/eventos?request_reference=QA&page=1',
next_page_url: null,
},
},
}}
/>,
);
}
test('audit investigation carries applied criteria into the whole-scope CSV and escapes the reference', () => {
const html = render(false);
expect(html).toContain('Referência exacta da requisição');
expect(html).toContain('QA&lt;REQ&gt;%_');
expect(html).toContain(
'/auditoria/eventos.csv?request_reference=QA%3CREQ%3E%25_&amp;action=0&amp;actor_id=7&amp;from=2026-11-01&amp;to=2026-11-01',
);
expect(html).not.toContain('/requisicoes/7');
expect(html).not.toContain('PRIVATE-');
});
test('only an independently authorised native process locator is rendered', () => {
const html = render(true);
expect(html).toContain('href="/requisicoes/7#requisition-history"');
expect(html).toContain(
'Consultar o processo e o histórico de QA&lt;REQ&gt;%_',
);
});
+137
View File
@@ -0,0 +1,137 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Budgets from '@/pages/budgets/index';
afterEach(() => vi.restoreAllMocks());
const identity = 'budgets:4:7:finance:admin,finance';
function render(
actor = 7,
tenant = 4,
context = 'finance',
permissions = ['finance', 'admin'],
budgetId = 3,
reviewId = 9,
) {
return renderToStaticMarkup(
<App
initialComponent={Budgets}
initialPage={{
component: 'budgets/index',
url: '/orcamentos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
organizationAccess: { permissions },
centers: [{ id: 1, code: 'CC-QA', name: 'Synthetic' }],
budgets: [
{
id: budgetId,
cost_center_id: 1,
year: 2026,
amount_minor: 10000,
reserved_minor: 0,
committed_minor: 0,
consumed_minor: 0,
available_minor: 10000,
created_by: 8,
approved_by: 8,
reason: 'Synthetic budget',
includes_tax: false,
reinforced_minor: 0,
approved_total_minor: 10000,
kind: 'operating',
},
],
reinforcements: {
data: [
{
id: reviewId,
budget_id: budgetId,
reference: 'QA',
amount_minor: 1000,
reason: 'Synthetic reinforcement',
status: 'pending',
created_by: 99,
reviewed_by: null,
review_reason: null,
},
],
prev_page_url: null,
next_page_url: null,
},
},
}}
/>,
);
}
test.each([
[
'allocation',
{
cost_center_id: '1',
year: 2026,
amount: '123.45',
reason: 'ALLOCATION-DRAFT-QA',
includes_tax: '0',
kind: 'investment',
},
'ALLOCATION-DRAFT-QA',
],
[
'reinforcement:3',
{
reference: 'REF-QA',
amount: '12.34',
reason: 'REINFORCEMENT-DRAFT-QA',
},
'REINFORCEMENT-DRAFT-QA',
],
[
'reinforcement-review:9',
{ decision: 'rejected', reason: 'REVIEW-DRAFT-QA' },
'REVIEW-DRAFT-QA',
],
])(
'budget %s preparation restores only its private actor/company/context/capability scope without a command',
(suffix, data, marker) => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:${suffix}:data` ? data : undefined,
);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html.match(new RegExp(marker, 'g'))).toHaveLength(1);
expect(html).toContain('data-preparation-dirty="true"');
expect(render(8)).not.toContain(marker);
expect(render(7, 5)).not.toContain(marker);
expect(render(7, 4, 'procurement.internal')).not.toContain(marker);
expect(render(7, 4, 'finance', ['finance'])).not.toContain(marker);
expect(render(7, 4, 'finance', ['admin', 'finance'])).toContain(marker);
if (suffix.startsWith('reinforcement:'))
expect(
render(7, 4, 'finance', ['admin', 'finance'], 4),
).not.toContain(marker);
if (suffix.startsWith('reinforcement-review:'))
expect(
render(7, 4, 'finance', ['admin', 'finance'], 3, 10),
).not.toContain(marker);
expect(post).not.toHaveBeenCalled();
},
);
test('unchanged budget forms are clean and do not choose the company tax or classification decision', () => {
vi.spyOn(router, 'restore').mockReturnValue(undefined);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).not.toContain('data-preparation-dirty="true"');
expect(html.match(/data-preparation-dirty="false"/g)).toHaveLength(3);
expect(
html.match(/<option value="" selected="">Decisão da empresa/g),
).toHaveLength(2);
expect(post).not.toHaveBeenCalled();
});
@@ -0,0 +1,250 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import { CompanyDetailsSettings } from '@/components/company-details-settings';
import { WorkContextSettings } from '@/components/work-context-settings';
import { IntelligenceSettings } from '@/components/intelligence-settings';
import { AiPlanSettings } from '@/components/ai-plan-settings';
import { RequisitionApprovalSettings } from '@/components/requisition-approval-settings';
import { CompanyAdministrativeLocation } from '@/components/administrative-location';
afterEach(() => vi.restoreAllMocks());
const base = 'procurement-preparations:4:7:procurement.internal:admin';
const context = {
enforced: false,
active: 'procurement.internal',
available: ['procurement.internal'],
purchased: ['procurement.internal'],
paths: [],
sharedPaths: [],
permissions: [],
options: {
'procurement.internal': {
area: 'procurement',
areaLabel: 'Compras',
label: 'Compras internas',
operational: true,
},
},
};
const plan = {
state: 'draft' as const,
provider: 'none' as const,
model: '',
domains: [],
data_scopes: [],
monthly_budget_usd: '1.00',
monthly_requests: 10,
max_input_bytes: 1000,
max_output_tokens: 1000,
};
const components = {
details: CompanyDetailsSettings,
context: WorkContextSettings,
intelligence: IntelligenceSettings,
ai: AiPlanSettings,
approvals: RequisitionApprovalSettings,
geography: CompanyAdministrativeLocation,
};
function render(
kind: keyof typeof components,
overrides = {},
actor = 7,
tenant = 4,
active = 'procurement.internal',
) {
return renderToStaticMarkup(
<App
initialComponent={components[kind]}
initialPage={{
component: 'test',
url: '/test',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active },
organizationAccess: { permissions: ['admin'] },
version: 1,
ready: true,
details: null,
context,
enabled: [],
policy: {
revision: 1,
configured: true,
procurement_brief: true,
people_brief: true,
},
plan:
kind === 'approvals'
? {
revision: 1,
enabled: false,
quorum: 'one_eligible',
levels: [],
}
: plan,
profiles: [
{
id: 2,
name: 'Approval QA',
permissions: ['requisition_approve'],
},
],
costCenters: [],
domains: {},
scopes: {},
geography: null,
...overrides,
},
}}
/>,
);
}
test.each([
[
'details',
'company-details:1:true',
{
legal_name: 'COMPANY-POLICY-PREP-QA',
nuel: '',
address: '',
nuit: '',
phone: '',
email: '',
legal_representative: '',
bank_accounts: [],
establishments: [],
version: 1,
reason: 'Prepared company data',
},
],
[
'context',
'work-contexts:1:procurement.internal',
{
version: 1,
enabled: ['procurement.internal'],
confirm: true,
reason: 'COMPANY-POLICY-PREP-QA',
},
],
[
'intelligence',
'intelligence:1:true:1',
{
version: 1,
procurement_brief: true,
people_brief: true,
reason: 'COMPANY-POLICY-PREP-QA',
},
],
[
'ai',
'ai-plan:1:true',
{
version: 1,
provider: 'none',
model: 'COMPANY-POLICY-PREP-QA',
domains: [],
data_scopes: [],
monthly_budget_usd: '1.00',
monthly_requests: 10,
max_input_bytes: 1000,
max_output_tokens: 1000,
reason: 'Prepared plan only',
},
],
[
'approvals',
'approval-settings:1:1:true',
{
version: 1,
enabled: false,
levels: [],
reason: 'COMPANY-POLICY-PREP-QA',
},
],
] as const)(
'%s preparation is private version scoped and never applies a company policy on recovery',
(kind, scope, prepared) => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:${scope}:data` ? prepared : undefined,
);
const post = vi.spyOn(router, 'post');
expect(render(kind)).toContain('COMPANY-POLICY-PREP-QA');
expect(render(kind)).toContain('data-preparation-dirty="true"');
expect(render(kind, {}, 8)).not.toContain('COMPANY-POLICY-PREP-QA');
expect(render(kind, {}, 7, 5)).not.toContain('COMPANY-POLICY-PREP-QA');
expect(render(kind, {}, 7, 4, 'finance')).not.toContain(
'COMPANY-POLICY-PREP-QA',
);
expect(render(kind, { version: 2 })).not.toContain(
'COMPANY-POLICY-PREP-QA',
);
expect(post).not.toHaveBeenCalled();
},
);
test('approval preparation cannot cross a native plan revision', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:approval-settings:1:1:true:data`
? {
version: 1,
enabled: false,
levels: [],
reason: 'APPROVAL-DRAFT-QA',
}
: undefined,
);
expect(render('approvals')).toContain('APPROVAL-DRAFT-QA');
expect(
render('approvals', {
plan: {
revision: 2,
enabled: false,
quorum: 'one_eligible',
levels: [],
},
}),
).not.toContain('APPROVAL-DRAFT-QA');
});
test('company location preparation stays bound to its original concurrency reference', () => {
const reference = {
country: 'MZ',
catalogue: 'qa-catalogue',
record_id: '11',
};
const geography = { reference, path: [], requires_review: false };
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:company-location:${JSON.stringify(reference)}:data`
? {
geography_reference: { ...reference, record_id: '12' },
expected_reference: reference,
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('geography', { geography })).toContain(
'data-preparation-dirty="true"',
);
expect(
render('geography', {
geography: {
...geography,
reference: { ...reference, record_id: '13' },
},
}),
).toContain('data-preparation-dirty="false"');
expect(render('geography', { geography }, 8)).toContain(
'data-preparation-dirty="false"',
);
expect(post).not.toHaveBeenCalled();
});
test('unchanged company policy forms stay clean', () => {
vi.spyOn(router, 'restore').mockReturnValue(undefined);
for (const kind of Object.keys(components) as (keyof typeof components)[])
expect(render(kind)).not.toContain('data-preparation-dirty="true"');
});
+303
View File
@@ -0,0 +1,303 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Setup from '@/pages/company/setup';
import Team from '@/pages/company/index';
import Parameters from '@/pages/company/parameters';
afterEach(() => vi.restoreAllMocks());
const base = 'procurement-preparations:4:7:procurement.internal:admin';
const root = `${base}:company-parameters:1:true:true`;
const comparison = {
revision: 1,
configured: true,
minimum_proposals: 3,
minimum_evaluators: 2,
weights: { price: 40, quality: 20, delivery: 15, history: 15, payment: 10 },
};
const profile = {
id: 2,
name: 'Original finance profile',
permissions: ['finance'],
work_contexts: [],
};
const parameterProps = {
companyDetails: null,
companyDetailsReady: false,
ready: true,
active: true,
version: 1,
permissions: {
admin: 'Administração',
finance: 'Finanças',
requester: 'Requisitante',
},
profiles: [profile],
memberships: [],
users: [
{
id: 8,
name: 'Existing QA',
email: 'existing@example.test',
department_id: 1,
},
],
departments: [{ id: 1, name: 'Department QA' }],
costCenters: [{ id: 1, code: 'CC-QA', name: 'Centre QA' }],
companyRules: {
first_limit: '100.00',
second_limit: '1000.00',
includes_tax: true,
provisional: false,
default_tax_rate: '16',
},
comparisonPolicy: comparison,
};
function render(
kind: 'setup' | 'team' | 'parameters',
overrides = {},
actor = 7,
tenant: number | null = 4,
context = 'procurement.internal',
) {
return renderToStaticMarkup(
<App
initialComponent={
kind === 'setup' ? Setup : kind === 'team' ? Team : Parameters
}
initialPage={{
component: `company/${kind}`,
url: '/empresa',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
organizationAccess: { permissions: ['admin'] },
...(kind === 'parameters'
? parameterProps
: {
company: {
id: 4,
name: 'Company QA',
first_limit_minor: 10000,
second_limit_minor: 100000,
approval_includes_tax: true,
rules_provisional: false,
},
departments: [{ id: 1, name: 'Department QA' }],
costCenters: [],
users: [],
roles: [
{ value: 'requester', label: 'Requisitante' },
],
}),
...overrides,
},
}}
/>,
);
}
test.each([
['department', { name: 'DEPARTMENT-PREP-QA' }, 'DEPARTMENT-PREP-QA'],
[
'center',
{ department_id: '1', code: 'CENTER-PREP-QA', name: 'Centre' },
'CENTER-PREP-QA',
],
[
'user',
{
version: 1,
name: 'USER-PREP-QA',
email: 'prepared@example.test',
department_id: '1',
profile_ids: [2],
reason: 'Synthetic account proposal',
},
'USER-PREP-QA',
],
[
'rules',
{
version: 1,
first_limit: '100.00',
second_limit: '1000.00',
includes_tax: false,
reason: 'RULES-PREP-QA',
},
'RULES-PREP-QA',
],
[
'tax',
{ version: 1, default_tax_rate: '16', reason: 'TAX-PREP-QA' },
'TAX-PREP-QA',
],
[
'comparison',
{
version: 1,
minimum_proposals: 3,
minimum_evaluators: 2,
weights: comparison.weights,
reason: 'COMPARISON-PREP-QA',
},
'COMPARISON-PREP-QA',
],
] as const)(
'company %s preparation is isolated by actor company context and exact configuration version without a command',
(suffix, data, marker) => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${root}:${suffix}:data` ? data : undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('parameters')).toContain(marker);
expect(render('parameters')).toContain('data-preparation-dirty="true"');
expect(render('parameters', {}, 9)).not.toContain(marker);
expect(render('parameters', {}, 7, 5)).not.toContain(marker);
expect(render('parameters', {}, 7, 4, 'finance')).not.toContain(marker);
expect(render('parameters', { version: 2 })).not.toContain(marker);
expect(post).not.toHaveBeenCalled();
},
);
test('profile preparation follows selected source while the original profile remains unchanged', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${root}:selected-profile`
? '2'
: k === `${root}:profile:2:data`
? {
version: 1,
id: '2',
name: 'PROFILE-PREP-QA',
permissions: ['finance'],
work_contexts: [],
}
: undefined,
);
expect(render('parameters')).toContain('PROFILE-PREP-QA');
expect(render('parameters')).toContain('Original finance profile');
expect(render('parameters', { version: 2 })).not.toContain(
'PROFILE-PREP-QA',
);
expect(render('parameters', { profiles: [] })).toContain(
'Perfil seleccionado indisponível',
);
});
test('access assignment preparation follows its person and native version without granting access', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:company-assignment:8:1:data`
? {
version: 1,
user_id: 8,
profile_ids: [2],
maintenance: false,
expires_at: '',
reason: 'ASSIGNMENT-PREP-QA',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('parameters')).toContain('ASSIGNMENT-PREP-QA');
expect(render('parameters', { version: 2 })).not.toContain(
'ASSIGNMENT-PREP-QA',
);
expect(render('parameters', { users: [] })).not.toContain(
'ASSIGNMENT-PREP-QA',
);
expect(post).not.toHaveBeenCalled();
});
test('activation preparation remains explicit and does not activate the company on restore', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:company-parameters:1:false:true:activate:data`
? { version: 1, confirm: true, reason: 'ACTIVATION-PREP-QA' }
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('parameters', { active: false })).toContain(
'ACTIVATION-PREP-QA',
);
expect(render('parameters', { active: false, version: 2 })).not.toContain(
'ACTIVATION-PREP-QA',
);
expect(post).not.toHaveBeenCalled();
});
test('bootstrap restores company metadata for the exact account and leaves passwords empty', () => {
const key =
'procurement-preparations:null:7:procurement.internal:admin:company-setup';
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${key}:data`
? {
name: 'SETUP-PREP-QA',
department: 'Department',
second_name: 'Second QA',
second_email: 'second@example.test',
first_limit: '100.00',
second_limit: '1000.00',
includes_tax: true,
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render('setup', {}, 7, null);
expect(html).toContain('SETUP-PREP-QA');
expect(html.match(/type="password"[^>]*value=""/g)).toHaveLength(2);
expect(render('setup', {}, 9, null)).not.toContain('SETUP-PREP-QA');
expect(post).not.toHaveBeenCalled();
});
test('legacy team account metadata is private without restoring a password', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:company-team:4:user:data`
? {
name: 'TEAM-PREP-QA',
email: 'team@example.test',
department_id: '1',
purchasing_role: 'requester',
}
: undefined,
);
const html = render('team');
expect(html).toContain('TEAM-PREP-QA');
expect(html.match(/type="password"[^>]*value=""/g)).toHaveLength(2);
expect(render('team', {}, 9)).not.toContain('TEAM-PREP-QA');
});
test('omitted non-remembered password fields do not make clean metadata dirty', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${root}:user:data`
? {
version: 1,
name: '',
email: '',
department_id: '',
profile_ids: [],
reason: '',
}
: k === `${base}:company-team:4:user:data`
? {
name: '',
email: '',
department_id: '',
purchasing_role: 'requester',
}
: k ===
'procurement-preparations:null:7:procurement.internal:admin:company-setup:data'
? {
name: '',
department: '',
second_name: '',
second_email: '',
first_limit: '',
second_limit: '',
includes_tax: true,
}
: undefined,
);
const parameters = render('parameters');
expect(parameters).not.toContain('data-preparation-dirty="true"');
expect(parameters.match(/type="password"[^>]*value=""/g)).toHaveLength(2);
expect(render('team')).not.toContain('data-preparation-dirty="true"');
expect(render('setup', {}, 7, null)).not.toContain(
'data-preparation-dirty="true"',
);
});
@@ -0,0 +1,120 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Conflicts from '@/pages/conflicts/index';
import History from '@/pages/conflicts/show';
afterEach(() => vi.restoreAllMocks());
const identity = 'conflicts:4:7:finance:finance';
const declaration = {
id: 3,
user_id: 7,
supplier_id: 1,
requisition_id: null,
has_conflict: true,
known_since: '2026-01-01',
declared_at: '2026-11-28T00:00:00Z',
reason: 'Original synthetic conflict',
previous_id: null,
root_id: null,
author: { name: 'Synthetic actor' },
supplier: { name: 'Synthetic supplier' },
requisition: null,
};
function render(
history = false,
actor = 7,
tenant = 4,
context = 'finance',
canCorrect = true,
sourceId = 3,
) {
return renderToStaticMarkup(
<App
initialComponent={history ? History : Conflicts}
initialPage={{
component: history ? 'conflicts/show' : 'conflicts/index',
url: '/conflitos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: {
user: {
id: actor,
tenant_id: tenant,
name: 'Synthetic actor',
},
},
workContext: { active: context },
organizationAccess: { permissions: ['finance'] },
history: [{ ...declaration, id: sourceId }],
canCorrect,
declarations: {
data: [],
prev_page_url: null,
next_page_url: null,
},
suppliers: [{ id: 1, name: 'Synthetic supplier' }],
requisitions: [],
},
}}
/>,
);
}
test('personal declaration preparation remains private to its actor company and context without submitting', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:new:data`
? {
scope: 'supplier',
supplier_id: '1',
requisition_id: '',
has_conflict: '1',
known_since: '2026-01-01',
reason: 'PERSONAL-DRAFT-QA',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('PERSONAL-DRAFT-QA');
expect(render()).toContain('data-preparation-dirty="true"');
expect(render(false, 8)).not.toContain('PERSONAL-DRAFT-QA');
expect(render(false, 7, 5)).not.toContain('PERSONAL-DRAFT-QA');
expect(render(false, 7, 4, 'procurement.internal')).not.toContain(
'PERSONAL-DRAFT-QA',
);
expect(post).not.toHaveBeenCalled();
});
test('correction preparation follows the immutable source version and current correction authority', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:correction:3:${declaration.declared_at}:true:data`
? {
reason: 'CORRECTION-DRAFT-QA',
known_since: '2026-02-01',
}
: undefined,
);
const put = vi.spyOn(router, 'put');
const html = render(true);
expect(html).toContain('CORRECTION-DRAFT-QA');
expect(html).toContain('Original synthetic conflict');
expect(html).toContain('data-preparation-dirty="true"');
expect(render(true, 8)).not.toContain('CORRECTION-DRAFT-QA');
expect(render(true, 7, 5)).not.toContain('CORRECTION-DRAFT-QA');
expect(render(true, 7, 4, 'finance', false)).not.toContain(
'CORRECTION-DRAFT-QA',
);
expect(render(true, 7, 4, 'finance', true, 4)).not.toContain(
'CORRECTION-DRAFT-QA',
);
expect(put).not.toHaveBeenCalled();
});
test('unchanged declaration and correction do not mark a preparation dirty', () => {
vi.spyOn(router, 'restore').mockReturnValue(undefined);
expect(render()).toContain('data-preparation-dirty="false"');
expect(render(true)).toContain('data-preparation-dirty="false"');
expect(render(true, 7, 4, 'finance', false)).not.toContain(
'data-preparation-dirty',
);
});
+76
View File
@@ -0,0 +1,76 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import {
ProcurementDeliveryInsights,
type DeliveryInsights,
} from '@/components/procurement-delivery-insights';
test('delivery review preserves unknown dates, native quantities and independent filters', () => {
const data: DeliveryInsights = {
view: 'attention',
coverage: { unknown: 1 },
pending_lines: 1,
unknown_lines: 1,
unverified_receipt_lines: 1,
records: {
current_page: 2,
last_page: 3,
total: 41,
data: [
{
id: 4,
number: 'OC-QA-4',
state: 'unknown',
pending_lines: 1,
unknown_lines: 1,
unverified_receipt_lines: 1,
late_days: null,
quality_pending: false,
href: '/ordens/4',
late_lines: [],
},
],
},
};
const html = renderToStaticMarkup(
<ProcurementDeliveryInsights
data={data}
pageHref="/relatorios?status=approved&supplier_page=2"
exportHref="/relatorios/entregas.csv?status=approved"
/>,
);
expect(html).toContain('Maior atraso documentado: por determinar');
expect(html).not.toContain('0 dia(s)');
expect(html).toContain('datas de recepção');
expect(html).toContain(
'status=approved&amp;supplier_page=2&amp;delivery_state=attention&amp;delivery_page=3',
);
expect(html).toContain('/relatorios/entregas.csv?status=approved');
data.records.data[0] = {
...data.records.data[0],
state: 'completed_late',
late_days: 2,
quality_pending: true,
late_lines: [
{
id: 8,
description: 'Peça & suporte',
unit: 'kg',
promised_on: '2026-11-20',
completed_on: '2026-11-22',
pending_quantity: '0.000',
},
],
};
const completed = renderToStaticMarkup(
<ProcurementDeliveryInsights
data={data}
pageHref="/relatorios"
exportHref="/relatorios/entregas.csv"
/>,
);
expect(completed).toContain('2 dia(s)');
expect(completed).toContain('qualidade ou aceitação permanece pendente');
expect(completed).toContain('0.000 kg');
expect(completed).toContain('Peça &amp; suporte');
});
@@ -0,0 +1,144 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import { QuotationExchangePanel } from '@/components/quotation-exchange-panel';
import Cancellation from '@/components/order-cancellation-request';
afterEach(() => vi.restoreAllMocks());
const identity = 'procurement-preparations:4:7:finance:finance';
function render(
exchange: boolean,
overrides = {},
actor = 7,
tenant = 4,
context = 'finance',
) {
return renderToStaticMarkup(
<App
initialComponent={exchange ? QuotationExchangePanel : Cancellation}
initialPage={{
component: 'test',
url: '/test',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
organizationAccess: { permissions: ['finance'] },
requisitionId: 3,
processVersion: 2,
rates: [],
canRecord: true,
orderId: 11,
state: { enabled: true, state: 'issued', canRequest: true },
...overrides,
},
}}
/>,
);
}
test('documentary FX preparation follows process version and capability without freezing a rate', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:quotation-exchange:3:2:true:data`
? {
operation_id: 'saved-qa-operation',
currency: 'USD',
rate: '60.1234567890',
quoted_on: '2026-11-28',
source: 'FX-PREPARATION-QA',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render(true)).toContain('FX-PREPARATION-QA');
expect(render(true)).toContain('data-preparation-dirty="true"');
expect(render(true, {}, 8)).not.toContain('FX-PREPARATION-QA');
expect(render(true, {}, 7, 5)).not.toContain('FX-PREPARATION-QA');
expect(render(true, {}, 7, 4, 'procurement.internal')).not.toContain(
'FX-PREPARATION-QA',
);
expect(render(true, { requisitionId: 4 })).not.toContain(
'FX-PREPARATION-QA',
);
expect(render(true, { processVersion: 3 })).not.toContain(
'FX-PREPARATION-QA',
);
expect(render(true, { canRecord: false })).not.toContain(
'FX-PREPARATION-QA',
);
expect(
render(true, {
rates: [
{
id: 8,
currency: 'EUR',
rate: '70',
quoted_on: '2026-11-28',
source: 'Synthetic prior basis',
recorded_by: 9,
},
],
}),
).toContain('FX-PREPARATION-QA');
expect(post).not.toHaveBeenCalled();
});
test('cancellation request preparation is isolated by order and current native eligibility', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:order-cancellation:11:true:issued:true:data`
? {
operation_key: 'saved-qa-operation',
reason: 'CANCELLATION-PREPARATION-QA',
evidence: 'Synthetic documentary evidence',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render(false)).toContain('CANCELLATION-PREPARATION-QA');
expect(render(false)).toContain('data-preparation-dirty="true"');
expect(render(false, {}, 8)).not.toContain('CANCELLATION-PREPARATION-QA');
expect(render(false, {}, 7, 5)).not.toContain(
'CANCELLATION-PREPARATION-QA',
);
expect(render(false, {}, 7, 4, 'warehouse')).not.toContain(
'CANCELLATION-PREPARATION-QA',
);
expect(render(false, { orderId: 12 })).not.toContain(
'CANCELLATION-PREPARATION-QA',
);
for (const state of [
{ enabled: true, state: 'issued', canRequest: false },
{ enabled: false, state: 'issued', canRequest: false },
{ enabled: true, state: 'cancellation_pending', canRequest: false },
]) {
expect(render(false, { state })).not.toContain(
'CANCELLATION-PREPARATION-QA',
);
}
expect(post).not.toHaveBeenCalled();
});
test.each([true, false])(
'restored UUID alone stays clean for documentary command exchange=%s',
(exchange) => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:quotation-exchange:3:2:true:data`
? {
operation_id: 'saved-qa-operation',
currency: '',
rate: '',
quoted_on: '',
source: '',
}
: k ===
`${identity}:order-cancellation:11:true:issued:true:data`
? {
operation_key: 'saved-qa-operation',
reason: '',
evidence: '',
}
: undefined,
);
expect(render(exchange)).toContain('data-preparation-dirty="false"');
},
);
@@ -0,0 +1,74 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import EquipmentShow from '@/pages/equipment/show';
const page = {
data: [],
total: 0,
current_page: 1,
last_page: 1,
prev_page_url: null,
next_page_url: null,
};
function render(
reference: {
record_key: string;
code: string;
name: string;
version: number;
state: string;
href: string;
} | null,
) {
return renderToStaticMarkup(
<App
initialComponent={EquipmentShow}
initialPage={{
component: 'equipment/show',
url: '/equipamentos/1',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
equipment: {
id: 1,
code: 'EQ-QA',
description: 'Equipamento sintético',
area: 'Ensaio',
status: 'active',
},
purchases: page,
movements: page,
capitalReference: reference,
},
}}
/>,
);
}
test('equipment shows an explicit current asset reference and its existing purchase trace without rewriting its origins', () => {
const html = render({
record_key: 'qa-key',
code: 'ASSET-QA',
name: 'Nome actual <QA>',
version: 2,
state: 'archived',
href: '/projectos-imobilizado?history=qa-key',
});
expect(html).toContain('ASSET-QA');
expect(html).toContain('Nome actual &lt;QA&gt;');
expect(html).toContain('versão 2 · arquivada');
expect(html).toContain('href="/projectos-imobilizado?history=qa-key"');
expect(html).toContain('Consultar aquisição e recepções');
expect(html).toContain('documentos de compra conservam a referência');
expect(html).toContain('Requisições de compra associadas');
});
test('an unavailable or unauthorized asset reference does not introduce an empty panel or action', () => {
const html = render(null);
expect(html).not.toContain('Imobilizado no cadastro de Compras');
expect(html).not.toContain('Consultar aquisição e recepções');
expect(html).toContain('Equipamento sintético');
});
@@ -0,0 +1,188 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Equipment, { EquipmentDemo } from '@/pages/equipment/index';
afterEach(() => vi.restoreAllMocks());
const identity = 'inventory-events:4:7:warehouse:/equipamentos:true:true:false';
const asset = {
id: 3,
version: 2,
code: 'EQ-QA',
description: 'Original synthetic equipment',
area: 'Production',
serial_number: null,
department_id: 1,
stock_item_id: null,
criticality_level_id: 1,
status: 'active',
};
const part = {
id: 4,
version: 2,
stock_item_id: 1,
criticality_level_id: 1,
minimum_milli: 1000,
balance_milli: 0,
below_minimum: true,
};
function render(overrides = {}, actor = 7, tenant = 4, context = 'warehouse') {
return renderToStaticMarkup(
<App
initialComponent={Equipment}
initialPage={{
component: 'equipment/index',
url: '/equipamentos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
equipment: [asset],
parts: [part],
levels: [
{
id: 1,
code: 'L-QA',
name: 'Synthetic level',
criteria: 'Synthetic criteria',
is_critical: true,
},
],
links: [],
items: [
{
id: 1,
code: 'ITEM-QA',
name: 'Synthetic item',
unit: 'un',
},
],
departments: [{ id: 1, name: 'Production' }],
history: {
data: [],
prev_page_url: null,
next_page_url: null,
},
canManage: true,
canConfigure: true,
...overrides,
},
}}
/>,
);
}
test('asset preparation follows selected immutable source and never overwrites the original catalogue display', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:selected-asset`
? '3'
: k === `${identity}:asset:3:2:data`
? {
geography_reference: null,
id: '3',
version: '2',
code: 'PRIVATE-ASSET-DRAFT',
description: 'Prepared description',
area: 'Production',
serial_number: '',
department_id: '1',
stock_item_id: '',
criticality_level_id: '1',
status: 'stopped',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('PRIVATE-ASSET-DRAFT');
expect(render()).toContain('Original synthetic equipment');
expect(render()).toContain('data-preparation-dirty="true"');
expect(render({ equipment: [{ ...asset, version: 3 }] })).not.toContain(
'PRIVATE-ASSET-DRAFT',
);
expect(render({}, 8)).not.toContain('PRIVATE-ASSET-DRAFT');
expect(render({}, 7, 5)).not.toContain('PRIVATE-ASSET-DRAFT');
expect(render({}, 7, 4, 'finance')).not.toContain('PRIVATE-ASSET-DRAFT');
expect(render({ canManage: false })).not.toContain('PRIVATE-ASSET-DRAFT');
expect(post).not.toHaveBeenCalled();
});
test('part preparation restores by selected part and version independently of asset editing', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:selected-part`
? '4'
: k === `${identity}:part:4:2:data`
? {
id: '4',
version: '2',
stock_item_id: '1',
criticality_level_id: '1',
minimum_quantity: '4.567',
}
: undefined,
);
expect(render()).toContain('value="4.567"');
expect(render()).toContain('data-preparation-dirty="true"');
expect(render({ parts: [{ ...part, version: 3 }] })).not.toContain(
'value="4.567"',
);
expect(render({}, 8)).not.toContain('value="4.567"');
});
test('category preparation does not confer configuration rights', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:category:data`
? {
code: 'CAT-QA',
name: 'CATEGORY-DRAFT-QA',
criteria: 'Synthetic criterion',
is_critical: '1',
}
: undefined,
);
expect(render()).toContain('CATEGORY-DRAFT-QA');
expect(render({ canConfigure: false })).not.toContain('CATEGORY-DRAFT-QA');
});
test('equipment part association preparation retains explicit native selections without associating them', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:association:data`
? { equipment_id: '3', spare_part_id: '4' }
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('<option value="3" selected=""');
expect(render()).toContain('<option value="4" selected=""');
expect(post).not.toHaveBeenCalled();
});
test('a remembered source absent from the native catalogue cannot turn into a new record implicitly', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:selected-asset`
? '99'
: k === `${identity}:selected-part`
? '98'
: undefined,
);
const html = render();
expect(html.match(/Ficha seleccionada indisponível/g)).toHaveLength(2);
expect(html).not.toContain('Guardar equipamento');
});
test('equipment demonstration renders without private identity and unmodified private forms are clean', () => {
vi.spyOn(router, 'restore').mockReturnValue(undefined);
const post = vi.spyOn(router, 'post');
expect(render()).not.toContain('data-preparation-dirty="true"');
expect(
renderToStaticMarkup(
<App
initialComponent={EquipmentDemo}
initialPage={{
component: 'preview/index',
url: '/preview',
version: null,
clearHistory: false,
encryptHistory: false,
props: { errors: {} },
}}
/>,
),
).toContain('Equipamentos e peças sobressalentes');
expect(post).not.toHaveBeenCalled();
});
+40
View File
@@ -0,0 +1,40 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import { FormErrors } from '@/components/procurement';
import { focusFormError } from '@/lib/form-error-focus';
afterEach(() => vi.unstubAllGlobals());
test('only mapped validation errors offer field links and all messages remain escaped', () => {
const html = renderToStaticMarkup(
<FormErrors
errors={{ quantity: '<Quantidade>', version: 'Actualize a versão' }}
targets={{ quantity: 'quantity-line-a' }}
/>,
);
expect(html).toContain('href="#quantity-line-a"');
expect(html).toContain('&lt;Quantidade&gt;');
expect(html).not.toContain('href="#version"');
expect(html).toContain('Actualize a versão');
});
test('field navigation opens collapsed ancestors before focusing and scrolling', () => {
const steps: string[] = [];
const details = {
tagName: 'DETAILS',
parentElement: null,
setAttribute: (name: string) => steps.push(name),
};
const target = {
parentElement: { tagName: 'DIV', parentElement: details },
focus: () => steps.push('focus'),
scrollIntoView: () => steps.push('scroll'),
};
vi.stubGlobal('document', {
getElementById: (id: string) => (id === 'field' ? target : null),
});
expect(focusFormError('missing')).toBe(false);
expect(steps).toEqual([]);
expect(focusFormError('field')).toBe(true);
expect(steps).toEqual(['open', 'focus', 'scroll']);
});
@@ -0,0 +1,135 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import { InventoryEventActions } from '@/components/inventory-event-actions';
afterEach(() => vi.restoreAllMocks());
function render(
action: string,
overrides = {},
actor = 7,
tenant = 4,
context = 'warehouse',
) {
const props = {
route: '/stock/estornos',
record: { record_key: 'record-qa', version: 2 },
choices: [{ value: action, label: 'Explicit synthetic action' }],
today: '2026-11-28',
data: { lot_id: 5 },
...overrides,
};
return renderToStaticMarkup(
<App
initialComponent={InventoryEventActions}
initialPage={{
component: 'stock/reversals',
url: '/stock/estornos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
actorId: actor,
workContext: { active: context },
...props,
},
}}
/>,
);
}
const key = (action: string) =>
`inventory-events:4:7:warehouse:/stock/estornos:record-qa:2:${action}:[["lot_id",5]]:${action}:data`;
test.each(['approve', 'execute', 'hold'])(
'%s preparation follows actor context source version and eligible action without executing',
(action) => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === key(action)
? {
operation_key: 'saved-operation-qa',
record_key: 'record-qa',
version: 2,
action,
reason: 'INVENTORY-PREPARATION-QA',
data: {
lot_id: 5,
...(action === 'execute'
? {
event_on: '2026-11-27',
evidence: 'Synthetic physical evidence',
}
: {}),
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render(action)).toContain('INVENTORY-PREPARATION-QA');
expect(render(action)).toContain('data-preparation-dirty="true"');
expect(render(action, {}, 8)).not.toContain('INVENTORY-PREPARATION-QA');
expect(render(action, {}, 7, 5)).not.toContain(
'INVENTORY-PREPARATION-QA',
);
expect(render(action, {}, 7, 4, 'finance')).not.toContain(
'INVENTORY-PREPARATION-QA',
);
expect(
render(action, { record: { record_key: 'record-qa', version: 3 } }),
).not.toContain('INVENTORY-PREPARATION-QA');
expect(render(action, { route: '/stock/lotes' })).not.toContain(
'INVENTORY-PREPARATION-QA',
);
expect(render(action, { data: { lot_id: 6 } })).not.toContain(
'INVENTORY-PREPARATION-QA',
);
expect(render(action, { choices: [] })).not.toContain(
'INVENTORY-PREPARATION-QA',
);
expect(post).not.toHaveBeenCalled();
},
);
test('restored operation key alone does not mark stock preparation dirty', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === key('hold')
? {
operation_key: 'saved-operation-qa',
record_key: 'record-qa',
version: 2,
action: 'hold',
reason: '',
data: { lot_id: 5 },
}
: undefined,
);
expect(render('hold')).toContain('data-preparation-dirty="false"');
});
test('explicit action selection restores only while that exact capability set remains available', () => {
const identity =
'inventory-events:4:7:warehouse:/stock/estornos:record-qa:2:approve,return:[["lot_id",5]]';
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:action`
? 'return'
: k === `${identity}:return:data`
? {
operation_key: 'qa-operation',
record_key: 'record-qa',
version: 2,
action: 'return',
reason: 'RETURN-PREPARATION-QA',
data: { lot_id: 5 },
}
: undefined,
);
const choices = [
{ value: 'approve', label: 'Approve' },
{ value: 'return', label: 'Return' },
];
expect(render('approve', { choices })).toContain('RETURN-PREPARATION-QA');
expect(render('approve', { choices: [...choices].reverse() })).toContain(
'RETURN-PREPARATION-QA',
);
expect(render('approve', { choices: [choices[0]] })).not.toContain(
'RETURN-PREPARATION-QA',
);
});
@@ -0,0 +1,220 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Lots from '@/pages/stock/lots';
import Reversals from '@/pages/stock/reversals';
import Dispositions from '@/pages/stock/dispositions';
afterEach(() => vi.restoreAllMocks());
const cases = [
[
'lots',
'/stock/lotes',
{
stock_item_id: '1',
warehouse_id: '2',
requires_expiry: true,
quarantine_on_receipt: true,
minimum_remaining_days: '7',
lots: [],
},
],
[
'reversals',
'/stock/estornos',
{
reference: 'SOURCE-DRAFT-QA',
source_kind: 'operation',
source_operation_id: '99',
receipt_item_id: '',
},
],
[
'dispositions',
'/stock/ocorrencias',
{
kind: 'supplier_return',
stock_item_id: '1',
warehouse_id: '2',
lot_id: '',
receipt_item_id: '99',
quantity: '1',
reference: 'SOURCE-DRAFT-QA',
},
],
] as const;
function render(
kind: string,
overrides = {},
actor = 7,
tenant = 4,
context = 'warehouse',
) {
return renderToStaticMarkup(
<App
initialComponent={
kind === 'lots'
? Lots
: kind === 'reversals'
? Reversals
: Dispositions
}
initialPage={{
component: `stock/${kind}`,
url: '/stock',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
actorId: actor,
ready: true,
capabilities: { prepare: true },
records: [],
history: kind === 'lots' ? [] : {},
contexts: {},
items: [
{
id: 1,
code: 'ITEM-QA',
name: 'Synthetic item',
unit: 'un',
},
],
warehouses: [
{ id: 2, code: 'WH-QA', name: 'Synthetic warehouse' },
],
receipts: [],
operations: [],
lots: [],
filters: { search: '', state: '' },
today: '2026-11-28',
canViewReversals: false,
canViewDispositions: false,
canViewOperations: false,
...overrides,
},
}}
/>,
);
}
test.each(cases)(
'%s preparation restores only its actor/company/context and preserves the source pending lookup',
(kind, route, data) => {
const key = `inventory-events:4:7:warehouse:${route}:prepare:new:0:new:[["prepare",true]]:data`;
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === key
? {
operation_key: 'saved-qa-operation',
version: 0,
action: kind === 'lots' ? 'prepare' : 'save',
reason: 'PRIVATE-STOCK-DRAFT-QA',
data,
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render(kind);
expect(html).toContain('PRIVATE-STOCK-DRAFT-QA');
expect(html).toContain('data-preparation-dirty="true"');
if (kind !== 'lots')
expect(html).toContain(
'Origem seleccionada — pesquisar para conferir disponibilidade',
);
expect(render(kind, {}, 8)).not.toContain('PRIVATE-STOCK-DRAFT-QA');
expect(render(kind, {}, 7, 5)).not.toContain('PRIVATE-STOCK-DRAFT-QA');
expect(render(kind, {}, 7, 4, 'finance')).not.toContain(
'PRIVATE-STOCK-DRAFT-QA',
);
expect(
render(kind, { capabilities: { prepare: false } }),
).not.toContain('PRIVATE-STOCK-DRAFT-QA');
expect(post).not.toHaveBeenCalled();
},
);
test('lot identification preparation follows the immutable metadata version and current native authority', () => {
const record = {
id: 1,
record_key: 'setup-qa',
version: 1,
kind: 'setup',
state: 'active',
reason: 'Original setup',
created_at: '2026-11-28',
data: {
stock_item_id: 1,
warehouse_id: 2,
requires_expiry: true,
minimum_remaining_days: 0,
quarantine_on_receipt: true,
lots: [],
},
snapshot: {
contributors: [],
actor: { name: 'Synthetic' },
item: { code: 'ITEM-QA', name: 'Synthetic item', unit: 'un' },
warehouse: { name: 'Synthetic warehouse' },
balance: { quantity: 1000, version: 1 },
},
};
const lot = {
id: 5,
record_key: 'lot-qa',
version: 2,
metadata_id: 5,
data: {
code: 'ORIGINAL-QA',
expires_on: '2027-01-01',
no_expiry: false,
quantity_milli: 1000,
},
quantity_milli: 1000,
usable_milli: 0,
eligible: false,
state: 'held',
state_version: 1,
contributors: [],
last_usable_on: null,
quality_released: false,
canIdentify: true,
canRelease: false,
canHold: false,
};
const props = (version = 2, canIdentify = true) => ({
records: [record],
contexts: {
'setup-qa': {
reconciled: true,
physical: { quantity: 1000 },
usable_milli: 0,
blocked_milli: 1000,
lots: [{ ...lot, version, canIdentify }],
},
},
});
vi.spyOn(router, 'restore').mockImplementation((k) =>
k ===
'inventory-events:4:7:warehouse:/stock/lotes:identify:lot-qa:2:data'
? {
operation_key: 'qa-operation',
record_key: 'lot-qa',
version: 2,
action: 'identify',
reason: 'IDENTIFY-DRAFT-QA',
data: {
code: 'NEW-CODE-QA',
expires_on: '2027-02-01',
no_expiry: false,
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('lots', props())).toContain('IDENTIFY-DRAFT-QA');
expect(render('lots', props())).toContain('ORIGINAL-QA');
expect(render('lots', props(3))).not.toContain('IDENTIFY-DRAFT-QA');
expect(render('lots', props(2, false))).not.toContain('IDENTIFY-DRAFT-QA');
expect(post).not.toHaveBeenCalled();
});
@@ -0,0 +1,100 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Investment from '@/pages/investment/index';
afterEach(() => vi.restoreAllMocks());
const identity = 'investment:4:7:finance:true:admin';
function render(
overrides = {},
actor = 7,
tenant = 4,
context = 'finance',
id = 3,
) {
return renderToStaticMarkup(
<App
initialComponent={Investment}
initialPage={{
component: 'investment/index',
url: '/regras-investimento',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
organizationAccess: { permissions: ['admin'] },
canManage: true,
policies: [
{
id,
created_by: 9,
revision: 1,
status: 'pending',
mode: 'ceiling',
scope: 'process_total',
currency: 'MZN',
ceiling_minor: 10000,
includes_tax: true,
valid_from: '2026-11-01',
valid_until: '2026-12-31',
reason: 'Synthetic policy',
},
],
reviews: [],
currentPolicyId: null,
...overrides,
},
}}
/>,
);
}
test.each([
[
'proposal:3',
{
previous_id: 3,
mode: 'ceiling',
scope: 'process_total',
currency: 'MZN',
ceiling: '123.45',
includes_tax: '0',
valid_from: '2026-12-01',
valid_until: '2026-12-31',
reason: 'INVESTMENT-DRAFT-QA',
},
],
['review:3', { decision: 'rejected', reason: 'INVESTMENT-DRAFT-QA' }],
])(
'%s preparation stays private to identity capability and immutable predecessor or policy',
(suffix, data) => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${identity}:${suffix}:data` ? data : undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('INVESTMENT-DRAFT-QA');
expect(render()).toContain('data-preparation-dirty="true"');
expect(render({}, 8)).not.toContain('INVESTMENT-DRAFT-QA');
expect(render({}, 7, 5)).not.toContain('INVESTMENT-DRAFT-QA');
expect(render({}, 7, 4, 'procurement.internal')).not.toContain(
'INVESTMENT-DRAFT-QA',
);
expect(render({}, 7, 4, 'finance', 4)).not.toContain(
'INVESTMENT-DRAFT-QA',
);
expect(render({ canManage: false })).not.toContain(
'INVESTMENT-DRAFT-QA',
);
expect(post).not.toHaveBeenCalled();
},
);
test('unmodified policy preparation stays clean and leaves company parameters undecided', () => {
vi.spyOn(router, 'restore').mockReturnValue(undefined);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).not.toContain('data-preparation-dirty="true"');
expect(html).toContain('value="" selected=""');
expect(post).not.toHaveBeenCalled();
});
+156
View File
@@ -0,0 +1,156 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Payments from '@/pages/payments/index';
afterEach(() => vi.restoreAllMocks());
const base = 'payments:4:7:finance:finance';
const identity = `${base}:true:all:all`;
const invoice = {
id: 3,
number: 'INV-QA',
supplier_id: 1,
supplier_name: 'Synthetic supplier',
total_minor: 10000,
outstanding_minor: 10000,
currency: 'MZN',
bank_id: 5,
bank_revision: 2,
bank_state: 'approved',
banks: [
{
id: 5,
revision: 2,
label: 'Synthetic bank',
currency: 'MZN',
state: 'approved',
},
],
};
function render(overrides = {}, actor = 7, tenant = 4, context = 'finance') {
return renderToStaticMarkup(
<App
initialComponent={Payments}
initialPage={{
component: 'payments/index',
url: '/pagamentos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
organizationAccess: { permissions: ['finance'] },
canManage: true,
invoices: [invoice],
payments: {
data: [
{
id: 9,
invoice_id: 3,
created_by: 8,
status: 'pending',
amount_minor: 4000,
currency: 'MZN',
paid_on: '2026-11-28',
external_reference: null,
evidence_reference: null,
supplier_bank_detail_id: 5,
canReview: true,
},
],
prev_page_url: null,
next_page_url: null,
},
...overrides,
},
}}
/>,
);
}
test('external payment preparation restores its selected invoice without carrying values to another source or bank version', () => {
vi.spyOn(router, 'restore').mockImplementation((key) => {
if (key === `${identity}:invoice`) return '3';
if (
key ===
`${identity}:registration:3:5:2:approved:10000:5.2.approved:data`
)
return {
supplier_bank_detail_id: 5,
amount: '40.00',
paid_on: '2026-11-28',
external_reference: 'EXTERNAL-DRAFT-QA',
evidence_reference: 'Synthetic documentary evidence',
};
return undefined;
});
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).toContain('EXTERNAL-DRAFT-QA');
expect(html).toContain('value="3" selected=""');
expect(html).toContain('form="external-payment-registration"');
expect(html).toContain('<form id="external-payment-registration"');
expect(html).toContain('data-preparation-dirty="true"');
expect(render({}, 8)).not.toContain('EXTERNAL-DRAFT-QA');
expect(render({}, 7, 5)).not.toContain('EXTERNAL-DRAFT-QA');
expect(render({}, 7, 4, 'procurement.internal')).not.toContain(
'EXTERNAL-DRAFT-QA',
);
expect(render({ invoices: [{ ...invoice, id: 4 }] })).not.toContain(
'EXTERNAL-DRAFT-QA',
);
expect(
render({ invoices: [{ ...invoice, bank_revision: 3 }] }),
).not.toContain('EXTERNAL-DRAFT-QA');
expect(
render({ invoices: [{ ...invoice, outstanding_minor: 6000 }] }),
).not.toContain('EXTERNAL-DRAFT-QA');
expect(render({ canManage: false })).not.toContain('EXTERNAL-DRAFT-QA');
expect(post).not.toHaveBeenCalled();
});
test('independent review restores only its pending payment and remains separate from registration', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${base}:review:9:pending:4000:5:true:data`
? {
decision: 'rejected',
reason: 'REVIEW-DRAFT-QA',
independently_verified: true,
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('REVIEW-DRAFT-QA');
expect(render()).toContain('data-preparation-dirty="true"');
expect(render({}, 8)).not.toContain('REVIEW-DRAFT-QA');
expect(render({}, 7, 5)).not.toContain('REVIEW-DRAFT-QA');
expect(render({}, 7, 4, 'procurement.internal')).not.toContain(
'REVIEW-DRAFT-QA',
);
expect(
render({
payments: { data: [], prev_page_url: null, next_page_url: null },
}),
).not.toContain('REVIEW-DRAFT-QA');
expect(post).not.toHaveBeenCalled();
});
test('missing or settled remembered invoice is explicit and cannot enable registration', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:invoice` ? '3' : undefined,
);
for (const invoices of [[], [{ ...invoice, outstanding_minor: 0 }]]) {
const html = render({ invoices });
expect(html).toContain(
'Factura seleccionada indisponível ou sem saldo',
);
expect(html).toMatch(
/<button[^>]*disabled=""[^>]*>Registar para conferência independente/,
);
}
});
test('unmodified payment forms remain clean without sending a command', () => {
vi.spyOn(router, 'restore').mockReturnValue(undefined);
const post = vi.spyOn(router, 'post');
expect(render()).not.toContain('data-preparation-dirty="true"');
expect(post).not.toHaveBeenCalled();
});
+72
View File
@@ -0,0 +1,72 @@
import { expect, test } from 'vitest';
import {
connectedDirtyForms,
markPreparationDirty,
} from '@/lib/preparation-forms';
function form(connected = true): HTMLFormElement {
const attributes = new Map<string, string>();
return {
isConnected: connected,
setAttribute: (key: string, value: string) =>
attributes.set(key, value),
getAttribute: (key: string) => attributes.get(key) ?? null,
} as unknown as HTMLFormElement;
}
function root(forms: HTMLFormElement[]): Pick<Document, 'querySelectorAll'> {
return {
querySelectorAll: () =>
forms.filter(
(node) =>
node.getAttribute('data-preparation-dirty') === 'true',
),
} as unknown as Pick<Document, 'querySelectorAll'>;
}
test('a restored dirty preparation is protected even before any input event or listener registration', () => {
const restored = form();
markPreparationDirty(restored, true);
expect(connectedDirtyForms([], root([restored]))).toEqual([restored]);
expect(connectedDirtyForms(new Set([restored]), root([restored]))).toEqual([
restored,
]);
});
test('cleaned unmounted and explicitly discarded preparations do not leave false guards', () => {
const cleaned = form();
const unmounted = form(false);
const legacy = form();
markPreparationDirty(cleaned, false);
markPreparationDirty(unmounted, true);
expect(
connectedDirtyForms(
[cleaned, unmounted, legacy],
root([cleaned, unmounted]),
),
).toEqual([legacy]);
markPreparationDirty(legacy, false);
expect(
connectedDirtyForms(
[cleaned, unmounted, legacy],
root([cleaned, unmounted, legacy]),
),
).toEqual([]);
});
test('one submitted form does not remove another dirty preparation from the departure check', () => {
const submitted = form();
const other = form();
markPreparationDirty(submitted, true);
markPreparationDirty(other, true);
expect(
connectedDirtyForms([], root([submitted, other])).some(
(node) => node !== submitted,
),
).toBe(true);
markPreparationDirty(other, false);
expect(
connectedDirtyForms([], root([submitted, other])).some(
(node) => node !== submitted,
),
).toBe(false);
});
@@ -3,6 +3,102 @@ import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Search from '@/pages/search/procurement';
test('warehouse search preserves the distinct internal reference event state and result page', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Search}
initialPage={{
component: 'search/procurement',
url: '/compras/pesquisa?q=RA-9',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
term: 'RA-9',
warehouseRequestSearchAvailable: true,
groups: [
{
key: 'warehouse_requests',
title: 'Requisições internas de armazém',
records: {
total: 16,
current_page: 1,
last_page: 2,
prev_page_url: null,
next_page_url:
'/compras/pesquisa?q=RA&warehouse_requests_page=2',
data: [
{
id: 9,
title: 'RA-9',
detail: 'partial',
href: '/stock/requisicoes/9',
},
],
},
},
],
},
}}
/>,
);
expect(html).toContain('Requisições internas de armazém');
expect(html).toContain('RA-9');
expect(html).toContain('Entrega parcial');
expect(html).toContain('warehouse_requests_page=2');
expect(html).toContain('/stock/requisicoes/9');
expect(html).toContain('nome do requisitante preservado');
});
test('supply reference search shows current versions native targets and its own pagination', () => {
const html = renderToStaticMarkup(
<App
initialComponent={Search}
initialPage={{
component: 'search/procurement',
url: '/compras/pesquisa?q=AG',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
term: 'AG',
supplySearchAvailable: true,
groups: [
{
key: 'agreements',
title: 'Acordos',
records: {
total: 16,
current_page: 1,
last_page: 2,
prev_page_url: null,
next_page_url:
'/compras/pesquisa?q=AG&agreements_page=2',
data: [
{
id: 5,
title: 'AG <QA> · v2',
detail: 'suspended',
href: '/compras/fornecimento?view=agreements&record_id=5#supply-record-5',
},
],
},
},
],
},
}}
/>,
);
expect(html).toContain('AG &lt;QA&gt; · v2');
expect(html).toContain('Suspenso');
expect(html).toContain('agreements_page=2');
expect(html).toContain('view=agreements&amp;record_id=5#supply-record-5');
expect(html).toContain('nome do fornecedor preservado');
expect(html).not.toContain('acesso financeiro');
});
test('process search separates result groups escapes text and retains page links', () => {
const html = renderToStaticMarkup(
<App
@@ -0,0 +1,276 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Controls from '@/pages/purchase-controls/index';
import Orders from '@/pages/purchase-controls/orders';
afterEach(() => vi.restoreAllMocks());
const permissions = ['admin', 'finance', 'procurement'];
const policy = {
id: 3,
revision: 2,
status: 'pending',
created_by: 9,
enabled: false,
valid_from: '2026-11-01',
valid_until: '2026-12-31',
canReview: true,
};
const original = {
role: 'configured',
actorId: 7,
permissions,
policies: [policy],
reviews: [],
awards: [{ id: 4, requisition_id: 8, status: 'approved' }],
cancellations: [],
sources: [{ id: 7, number: 'REQ-QA', revision_id: null }],
};
const order = {
id: 11,
order_number: 'PO-QA',
purchase_order_id: 23,
source_href: '/ordens/23',
status: 'pending',
reason: 'Original synthetic request',
evidence: 'Synthetic evidence',
review_reason: null,
revised_requisition_id: null,
canDecide: true,
canRevise: false,
};
const issued = {
canAdminister: true,
policies: [policy],
records: {
data: [
order,
{
...order,
id: 12,
status: 'approved',
canDecide: false,
canRevise: true,
},
],
prev_page_url: null,
next_page_url: null,
},
};
const originalKey = 'purchase-controls:4:7:legacy:admin,finance,procurement';
const issuedKey = 'order-cancellations:4:7:legacy:true';
function render(
kind: 'original' | 'issued',
overrides = {},
actor = 7,
tenant = 4,
) {
return renderToStaticMarkup(
<App
initialComponent={kind === 'original' ? Controls : Orders}
initialPage={{
component:
kind === 'original'
? 'purchase-controls/index'
: 'purchase-controls/orders',
url:
kind === 'original'
? '/revisao-compras'
: '/ordens/cancelamentos',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
...(kind === 'original' ? original : issued),
actorId: actor,
...overrides,
},
}}
/>,
);
}
test('unissued cancellation preparation restores once for its award without requesting cancellation', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${originalKey}:reason:/adjudicacoes/4/cancelamento:false:data`
? { reason: 'CANCELLATION-REQUEST-QA', decision: 'approved' }
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render('original');
expect(html.match(/CANCELLATION-REQUEST-QA/g)).toHaveLength(1);
expect(html).toContain('data-preparation-dirty="true"');
expect(render('original', {}, 8)).not.toContain('CANCELLATION-REQUEST-QA');
expect(render('original', {}, 7, 5)).not.toContain(
'CANCELLATION-REQUEST-QA',
);
expect(
render('original', { workContext: { active: 'procurement.internal' } }),
).not.toContain('CANCELLATION-REQUEST-QA');
expect(
render('original', {
awards: [{ id: 5, requisition_id: 8, status: 'approved' }],
}),
).not.toContain('CANCELLATION-REQUEST-QA');
expect(
render('original', {
permissions: ['procurement', 'admin', 'finance'],
}),
).toContain('CANCELLATION-REQUEST-QA');
expect(post).not.toHaveBeenCalled();
});
test('unissued policy proposal stays separate from policy review and from a later predecessor', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${originalKey}:policy:3:data`
? {
previous_id: 3,
mode: 'unissued_award',
enabled: true,
valid_from: '2026-12-01',
valid_until: '2026-12-31',
reason: 'POLICY-PROPOSAL-QA',
}
: key ===
`${originalKey}:reason:/revisao-compras/politicas/3/decidir:true:data`
? { reason: 'INDEPENDENT-POLICY-REVIEW-QA', decision: 'rejected' }
: undefined,
);
const html = render('original');
expect(html).toContain('POLICY-PROPOSAL-QA');
expect(html).toContain('INDEPENDENT-POLICY-REVIEW-QA');
expect(html).toContain('<option value="rejected" selected="">');
expect(
render('original', { policies: [{ ...policy, id: 4 }] }),
).not.toContain('POLICY-PROPOSAL-QA');
expect(
render('original', { permissions: ['finance', 'procurement'] }),
).not.toContain('POLICY-PROPOSAL-QA');
expect(
render('original', { permissions: ['finance', 'procurement'] }),
).not.toContain('INDEPENDENT-POLICY-REVIEW-QA');
});
test('unissued revision conserves only the new date and justification for the same cancelled source', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${originalKey}:revision:7:data`
? {
needed_by: '2026-12-15',
justification: 'NEW-REQUEST-JUSTIFICATION-QA',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('original')).toContain('NEW-REQUEST-JUSTIFICATION-QA');
expect(render('original')).toContain('value="2026-12-15"');
expect(
render('original', {
sources: [{ id: 8, number: 'OTHER-QA', revision_id: null }],
}),
).not.toContain('NEW-REQUEST-JUSTIFICATION-QA');
expect(
render('original', {
sources: [{ id: 7, number: 'REQ-QA', revision_id: 99 }],
}),
).not.toContain('NEW-REQUEST-JUSTIFICATION-QA');
expect(post).not.toHaveBeenCalled();
});
test('issued order decision restores independently without confirming or cancelling automatically', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${issuedKey}:decision:/ordens/cancelamentos/11/decidir:data`
? { decision: 'approved', reason: 'ISSUED-ORDER-DECISION-QA' }
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('issued')).toContain('ISSUED-ORDER-DECISION-QA');
expect(render('issued')).toContain('<option value="approved" selected="">');
expect(render('issued', {}, 8)).not.toContain('ISSUED-ORDER-DECISION-QA');
expect(render('issued', {}, 7, 5)).not.toContain(
'ISSUED-ORDER-DECISION-QA',
);
expect(
render('issued', { workContext: { active: 'procurement.internal' } }),
).not.toContain('ISSUED-ORDER-DECISION-QA');
expect(
render('issued', {
records: {
...issued.records,
data: [{ ...order, canDecide: false }],
},
}),
).not.toContain('ISSUED-ORDER-DECISION-QA');
expect(post).not.toHaveBeenCalled();
});
test('issued policy proposal and its independent review cannot reuse each other or the next policy', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${issuedKey}:policy:3:data`
? {
previous_id: 3,
mode: 'issued_order',
enabled: true,
valid_from: '2026-12-01',
valid_until: '2026-12-31',
reason: 'ISSUED-POLICY-PROPOSAL-QA',
}
: key ===
`${issuedKey}:decision:/ordens/cancelamentos/politicas/3/decidir:data`
? { decision: 'rejected', reason: 'ISSUED-POLICY-REVIEW-QA' }
: undefined,
);
expect(render('issued')).toContain('ISSUED-POLICY-PROPOSAL-QA');
expect(render('issued')).toContain('ISSUED-POLICY-REVIEW-QA');
expect(
render('issued', { policies: [{ ...policy, id: 4 }] }),
).not.toContain('ISSUED-POLICY-PROPOSAL-QA');
expect(
render('issued', { policies: [{ ...policy, canReview: false }] }),
).not.toContain('ISSUED-POLICY-REVIEW-QA');
expect(render('issued', { canAdminister: false })).not.toContain(
'ISSUED-POLICY-PROPOSAL-QA',
);
});
test('issued revision preparation is tied to the approved cancellation and disappears once linked', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${issuedKey}:revision:12:approved:0:data`
? {
needed_by: '2026-12-16',
reason: 'ISSUED-REVISION-PREPARATION-QA',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('issued')).toContain('ISSUED-REVISION-PREPARATION-QA');
expect(
render('issued', {
records: {
...issued.records,
data: [
{ ...issued.records.data[1], revised_requisition_id: 99 },
],
},
}),
).not.toContain('ISSUED-REVISION-PREPARATION-QA');
expect(
render('issued', {
records: {
...issued.records,
data: [{ ...issued.records.data[1], id: 13 }],
},
}),
).not.toContain('ISSUED-REVISION-PREPARATION-QA');
expect(post).not.toHaveBeenCalled();
});
test.each(['original', 'issued'] as const)(
'empty %s preparations stay clean and do not enable a policy',
(kind) => {
const html = render(kind);
expect(html).not.toContain('data-preparation-dirty="true"');
expect(html).not.toContain('checked=""');
},
);
+203
View File
@@ -0,0 +1,203 @@
import { App, router } from '@inertiajs/react';
import type { ComponentProps } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Comparison from '@/pages/quotations/show';
import { QuotationEvaluationForm } from '@/components/quotation-evaluation-form';
afterEach(() => vi.restoreAllMocks());
const policy = {
revision: 1,
configured: true,
minimum_proposals: 3,
minimum_evaluators: 2,
weights: { price: 40, quality: 20, delivery: 15, history: 15, payment: 10 },
};
const data = {
currency: 'USD',
supplier_id: '7',
reference: 'QA-PREPARACAO-EXACTA',
delivery_days: '8',
valid_until: '2026-12-15',
payment_terms: 'Texto sintético por guardar',
no_conflict: false,
items: [
{
requisition_item_id: 10,
unit_price: '12.34',
discount_type: 'amount',
discount_value: '0.20',
},
],
};
function renderComparison(
tenant = 3,
actor = 7,
version = 4,
canCreate = true,
choicesAvailable = true,
) {
const props: ComponentProps<typeof Comparison> = {
requisition: {
id: 42,
process_version: version,
number: 'REQ-QA-42',
justification: 'Dados sintéticos',
items: [
{
id: 10,
description: 'Artigo sintético',
quantity: '1.000',
tax_rate: '16.00',
unit_price_minor: 100,
total_minor: 116,
},
],
},
quotations: [],
suppliers: choicesAvailable
? [{ id: 7, name: 'Fornecedor sintético' }]
: [],
canCreate,
canEvaluate: false,
ready: false,
topIds: [],
comparisonPolicy: policy,
exchangeAvailable: true,
exchangeRates: choicesAvailable
? [
{
id: 2,
currency: 'USD',
rate: '60.0000000000',
quoted_on: '2026-11-27',
source: 'Fonte sintética',
recorded_by: 9,
},
]
: [],
};
return renderToStaticMarkup(
<App
initialComponent={Comparison}
initialPage={{
component: 'quotations/show',
url: '/requisicoes/42/cotacoes',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
...props,
},
}}
/>,
);
}
test('quotation preparation restores original currency prices discounts and text without saving or opening an unauthorized form', () => {
const spy = vi.spyOn(router, 'post');
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'quotation-preparation:3:7:42:4:adding'
? true
: key === 'quotation-preparation:3:7:42:4:data'
? data
: undefined,
);
const html = renderComparison();
expect(html).toContain('QA-PREPARACAO-EXACTA');
expect(html).toContain('Texto sintético por guardar');
expect(html).toContain('value="12.34"');
expect(html).toContain('value="0.20"');
expect(html).toContain('value="USD" selected');
expect(renderComparison(3, 7, 4, false)).not.toContain(
'QA-PREPARACAO-EXACTA',
);
expect(spy).not.toHaveBeenCalled();
});
test('quotation preparation never crosses actor company or source version', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'quotation-preparation:3:7:42:4:adding'
? true
: key === 'quotation-preparation:3:7:42:4:data'
? data
: undefined,
);
expect(renderComparison(3, 8)).not.toContain('QA-PREPARACAO-EXACTA');
expect(renderComparison(4, 7)).not.toContain('QA-PREPARACAO-EXACTA');
expect(renderComparison(3, 7, 5)).not.toContain('QA-PREPARACAO-EXACTA');
});
test('a remembered unavailable supplier or currency remains explicit without inventing eligibility or an exchange rate', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'quotation-preparation:3:7:42:4:adding'
? true
: key === 'quotation-preparation:3:7:42:4:data'
? data
: undefined,
);
const html = renderComparison(3, 7, 4, true, false);
expect(html).toContain('value="USD" selected');
expect(html).toContain('taxa indisponível nesta consulta');
expect(html).toContain('Fornecedor preservado · confirme a elegibilidade');
expect(html).toContain('QA-PREPARACAO-EXACTA');
expect(html).not.toContain('taxa 0 MZN');
});
function renderEvaluation(quotationId: number, actor = 7, tenant = 3) {
function Screen() {
return (
<QuotationEvaluationForm
requisitionId={42}
quotationId={quotationId}
/>
);
}
return renderToStaticMarkup(
<App
initialComponent={Screen}
initialPage={{
component: 'quotations/show',
url: '/requisicoes/42/cotacoes',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
},
}}
/>,
);
}
test('each independent proposal evaluation recovers only its own remembered preparation', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'quotation-evaluation:3:7:42:11:data'
? {
quality: '8.25',
history: '6',
payment: '7',
comment: 'Fundamento sintético por guardar da proposta onze',
no_conflict: false,
}
: undefined,
);
expect(renderEvaluation(11)).toContain(
'Fundamento sintético por guardar da proposta onze',
);
expect(renderEvaluation(11)).toContain('value="8.25"');
expect(renderEvaluation(12)).not.toContain(
'Fundamento sintético por guardar da proposta onze',
);
expect(renderEvaluation(11, 8)).not.toContain(
'Fundamento sintético por guardar da proposta onze',
);
expect(renderEvaluation(11, 7, 4)).not.toContain(
'Fundamento sintético por guardar da proposta onze',
);
});
+195
View File
@@ -0,0 +1,195 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import ReceiveOrder from '@/pages/receipts/order';
import {
receiptPreparationChanged,
receiptPreparationKey,
} from '@/lib/receipt-preparation';
import type { ReceiptProgress } from '@/types/inventory';
afterEach(() => vi.restoreAllMocks());
const progress: ReceiptProgress = {
state: 'not_received',
has_divergences: false,
lines: [
{
id: 10,
description: 'Artigo sintético',
unit: 'UN',
purchase_type: 'consumable',
ordered_milli: 10000,
received_milli: 0,
accepted_milli: 0,
rejected_milli: 0,
delivery_pending_milli: 10000,
acceptance_pending_milli: 10000,
stock_item_id: 1,
},
],
};
const data = {
idempotency_key: '11111111-1111-4111-8111-111111111111',
delivery_note: 'GUIA-QA-POR-GUARDAR',
received_on: '2026-11-27',
warehouse_id: '1',
items: [
{
include: true,
purchase_order_item_id: 10,
received_quantity: '0.600',
accepted_quantity: '0.500',
quality_status: 'reservations',
notes: 'Conferência sintética por guardar',
stock_item_id: '1',
conversion: {
numerator: '',
denominator: '',
source: '',
version: '',
},
lots: [],
},
],
};
function render(
tenant = 3,
actor = 7,
order = 42,
source = progress,
canConfirm = true,
) {
return renderToStaticMarkup(
<App
initialComponent={ReceiveOrder}
initialPage={{
component: 'receipts/order',
url: `/ordens/${order}/recepcoes`,
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
order: { id: order, number: 'OC-QA-42' },
supplier_name: 'Fornecedor sintético',
progress: source,
receipts: [],
warehouses: [
{ id: 1, code: 'ARM-QA', name: 'Armazém sintético' },
],
stockItems: [
{
id: 1,
code: 'ART-QA',
name: 'Artigo sintético',
unit: 'UN',
},
],
canConfirm,
lotScopes: [],
},
}}
/>,
);
}
test('receipt preparation restores selected line quantities notes and document without an automatic receipt', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${receiptPreparationKey(3, 7, 42, progress)}:data`
? data
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).toContain('GUIA-QA-POR-GUARDAR');
expect(html).toContain('value="0.600"');
expect(html).toContain('value="0.500"');
expect(html).toContain('value="reservations" selected');
expect(html).toContain('Conferência sintética por guardar');
expect(render(3, 7, 42, progress, false)).not.toContain(
'GUIA-QA-POR-GUARDAR',
);
expect(post).not.toHaveBeenCalled();
});
test('receipt preparation stays with its actor tenant order and physical progress', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${receiptPreparationKey(3, 7, 42, progress)}:data`
? data
: undefined,
);
expect(render(4)).not.toContain('GUIA-QA-POR-GUARDAR');
expect(render(3, 8)).not.toContain('GUIA-QA-POR-GUARDAR');
expect(render(3, 7, 43)).not.toContain('GUIA-QA-POR-GUARDAR');
const changed = {
...progress,
state: 'partial',
has_divergences: true,
lines: [
{
...progress.lines[0],
received_milli: 600,
accepted_milli: 500,
rejected_milli: 100,
delivery_pending_milli: 9400,
acceptance_pending_milli: 9500,
},
],
};
expect(render(3, 7, 42, changed)).not.toContain('GUIA-QA-POR-GUARDAR');
expect(
receiptPreparationKey(3, 7, 42, {
...changed,
lines: [
{
...changed.lines[0],
supplier_returned_milli: 300,
effective_accepted_milli: 200,
acceptance_pending_milli: 9800,
},
],
}),
).not.toBe(receiptPreparationKey(3, 7, 42, changed));
});
test('only a regenerated receipt UUID is clean while changed quantities and lot preparation remain dirty', () => {
expect(
receiptPreparationChanged(data, {
...data,
idempotency_key: '22222222-2222-4222-8222-222222222222',
}),
).toBe(false);
expect(
receiptPreparationChanged(data, {
...data,
items: [{ ...data.items[0], accepted_quantity: '0.400' }],
}),
).toBe(true);
expect(
receiptPreparationChanged(data, {
...data,
items: [
{
...data.items[0],
lots: [
{
code: 'LOTE-QA',
quantity: '0.500',
expires_on: '',
no_expiry: true,
},
],
},
],
}),
).toBe(true);
expect(
receiptPreparationChanged(data, {
...data,
delivery_note: 'Outra guia sintética',
}),
).toBe(true);
});
@@ -0,0 +1,104 @@
import { App } from '@inertiajs/react';
import type { ComponentProps } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Accounts from '@/pages/requisitions/accounts';
import Summary from '@/components/requisition-account-summary';
const account = {
id: 7,
code: 'QA-7',
label: 'Conta & material',
currency: 'MZN',
source_hash: 'a'.repeat(64),
};
const props: ComponentProps<typeof Accounts> = {
requisition: { id: 1, number: 'REQ-QA', status: 'draft' },
actorId: 1,
tenantId: 1,
canWrite: true,
search: '',
items: [
{
id: 2,
description: 'Material sintético',
subtotal_minor: '10000',
total_minor: '10000',
basis_hash: 'b'.repeat(64),
},
],
accounts: {
data: [account],
prev_page_url: null,
next_page_url: '/requisicoes/1/contas?accounts_page=2',
},
current: [],
history: { data: [], prev_page_url: null, next_page_url: null },
};
function render(value: typeof props) {
function Screen() {
return <Accounts {...value} />;
}
return renderToStaticMarkup(
<App
initialComponent={Screen}
initialPage={{
component: 'requisitions/accounts',
url: '/requisicoes/1/contas',
version: 'qa',
clearHistory: false,
encryptHistory: true,
props: { errors: {} },
}}
/>,
);
}
test('account assignment begins with an explicit line and preserves catalogue pagination', () => {
const html = render(props);
expect(html).toContain('Seleccione a linha');
expect(html).toContain('Adicionar conta à linha');
expect(html).toContain('/requisicoes/1/contas?accounts_page=2');
expect(html).toContain('Conta &amp; material');
expect(html).not.toContain('Reutilizar parcelas actuais');
expect(html).not.toContain('Base sem IVA (MZN)');
});
test('read-only history keeps exact original money and does not expose an editing form', () => {
const row = {
id: 9,
version: 2,
reason: 'Conferência sintética',
data: {
requisition_item_id: 2,
allocations: [
{
account,
subtotal_minor: '9007199254740993',
total_minor: '9007199254740993',
},
],
},
};
const html = render({
...props,
canWrite: false,
accounts: null,
current: [row],
history: { data: [row], prev_page_url: null, next_page_url: null },
});
expect(html).toContain('90.071.992.547.409,93 MZN');
expect(html).toContain('Versão 2');
expect(html).not.toContain('Guardar versão');
expect(html).not.toContain('Adicionar conta à linha');
const summary = renderToStaticMarkup(
<Summary
records={{
'2': {
...row,
snapshot: { line: { description: 'Necessidade original' } },
},
}}
/>,
);
expect(summary).toContain('90.071.992.547.409,93 MZN');
expect(summary).toContain('não representam valores contabilizados');
});
@@ -69,6 +69,8 @@ test('explicit RQ01 group conditions are separate from original article categori
expect(html).toContain('Categorias exactas do artigo');
expect(html).toContain('Equipamento de escritório');
expect(html).toContain('Maquinaria');
expect(html).toContain('Preparar nível de direcção para maquinaria');
expect(html).toContain('qualquer valor e centro de custo');
expect(html).toContain('não são classificados automaticamente');
const groups = html.slice(
html.indexOf('Categoria da necessidade (RQ-01)'),
@@ -76,6 +78,9 @@ test('explicit RQ01 group conditions are separate from original article categori
);
expect(groups).toContain('checked=""');
expect(render(true)).not.toContain('Categoria da necessidade (RQ-01)');
expect(render(true)).not.toContain(
'Preparar nível de direcção para maquinaria',
);
});
test('approval settings retain exact threshold and selected revoked profiles so the administrator can reconcile the plan', () => {
@@ -0,0 +1,74 @@
import { App } from '@inertiajs/react';
import type { ComponentProps } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import RequisitionShow from '@/pages/requisitions/show';
test.each([false, true])(
'draft review keeps advisory submission and exposes audit navigation only with its explicit capability (%s)',
(canReadAuditMetadata) => {
const props: ComponentProps<typeof RequisitionShow> = {
requisition: {
id: 1,
number: 'REQ-QA-1',
status: 'draft',
priority: 'normal',
needed_by: '2026-12-01',
justification: 'Somente dados sintéticos',
cost_center_id: 1,
subtotal_minor: 10000,
tax_minor: 0,
total_minor: 10000,
created_at: '2026-11-27T10:00:00Z',
items: [],
steps: [],
},
comparisonPolicy: {
revision: 1,
configured: false,
minimum_proposals: 3,
minimum_evaluators: 1,
weights: {
price: 40,
quality: 20,
delivery: 20,
history: 10,
payment: 10,
},
},
canEdit: true,
canReadAuditMetadata,
canDecide: false,
conflictBlocked: false,
audit: [],
duplicateHints: {
matches: [{ id: 2, number: 'REQ-QA-2', status: 'pending' }],
complete: false,
},
};
function Screen() {
return <RequisitionShow {...props} />;
}
const html = renderToStaticMarkup(
<App
initialComponent={Screen}
initialPage={{
component: 'requisitions/show',
url: '/requisicoes/1',
version: 'qa',
clearHistory: false,
encryptHistory: true,
props: { errors: {} },
}}
/>,
);
expect(html).toContain('Conferir possíveis pedidos repetidos');
expect(html).toContain('href="/requisicoes/2"');
expect(html).toContain('não bloqueia a submissão');
expect(html).toContain('100 candidatos');
expect(html).toContain('Submeter');
expect(
html.includes('/auditoria/eventos?request_reference=REQ-QA-1'),
).toBe(canReadAuditMetadata);
},
);
@@ -0,0 +1,35 @@
import { expect, test } from 'vitest';
import vectors from '../Fixtures/requisition-estimates.json';
import { requisitionEstimate } from '@/lib/requisition-estimate';
test.each(vectors)(
'preserves exact native line rounding: $minor',
({ lines, minor }) => {
expect(requisitionEstimate(lines)).toBe(minor);
},
);
test.each(['', '-1', '1e2', '0', '1.0001', '1000001', 'x'])(
'keeps invalid or incomplete quantity indeterminate: %s',
(quantity) => {
expect(
requisitionEstimate([{ quantity, unit_price: '1', tax_rate: '0' }]),
).toBeNull();
},
);
test('requires complete valid lines while accepting leading zeros and calculated zero', () => {
expect(requisitionEstimate([])).toBeNull();
for (const field of ['unit_price', 'tax_rate']) {
expect(
requisitionEstimate([
{ quantity: '1', unit_price: '1', tax_rate: '0', [field]: '' },
]),
).toBeNull();
}
expect(
requisitionEstimate([
{ quantity: '000.001', unit_price: '00.01', tax_rate: '00.00' },
]),
).toBe('0');
});
+169 -25
View File
@@ -1,15 +1,15 @@
import { App } from "@inertiajs/react";
import { renderToStaticMarkup } from "react-dom/server";
import { expect, test } from "vitest";
import Expiry from "../../resources/js/pages/requisitions/expiry";
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Expiry from '../../resources/js/pages/requisitions/expiry';
function render(extra: object) {
return renderToStaticMarkup(
<App
initialComponent={Expiry}
initialPage={{
component: "requisitions/expiry",
url: "/requisicoes/1/prazos",
component: 'requisitions/expiry',
url: '/requisicoes/1/prazos',
version: null,
clearHistory: false,
encryptHistory: true,
@@ -17,13 +17,13 @@ function render(extra: object) {
errors: {},
requisition: {
id: 1,
number: "REQ-QA",
status: "draft",
number: 'REQ-QA',
status: 'draft',
process_version: 4,
approval_cycle: 2,
},
deadline: {
state: "inactive",
state: 'inactive',
step_id: null,
expires_at: null,
basis_hash: null,
@@ -38,14 +38,14 @@ function render(extra: object) {
{
id: 1,
data: { cycle: 1, next_cycle: 2 },
reason: "<script>synthetic</script>",
request: { number: "REQ-QA" },
reason: '<script>synthetic</script>',
request: { number: 'REQ-QA' },
steps: [
{
id: 1,
position: 1,
role: "department_head",
decision: "approved",
role: 'department_head',
decision: 'approved',
},
],
},
@@ -60,26 +60,170 @@ function render(extra: object) {
);
}
test("returned owner sees the same draft and preserved approval without expiry controls", () => {
test('returned owner sees the same draft and preserved approval without expiry controls', () => {
const html = render({});
expect(html).toContain("/requisicoes/1/editar");
expect(html).toContain("Aprovação preservada");
expect(html).toContain("&lt;script&gt;synthetic&lt;/script&gt;");
expect(html).not.toContain("<form");
expect(html).toContain('/requisicoes/1/editar');
expect(html).toContain('Aprovação preservada');
expect(html).toContain('&lt;script&gt;synthetic&lt;/script&gt;');
expect(html).not.toContain('<form');
});
test("a pending configured deadline exposes due actions only when allowed", () => {
test('prior cycle exposes the original document rules and independent decision without reusing it in the new submission', () => {
const html = render({
history: {
prev_page_url: null,
next_page_url: null,
data: [
{
id: 8,
data: { cycle: 1, next_cycle: 2 },
created_at: '2026-11-27T12:31:00Z',
reason: 'Devolução sintética',
request: {
number: 'REQ-QA',
priority: 'normal',
submitted_at: '2026-11-27T12:00:00Z',
needed_by: '2026-12-01',
justification: 'ORIGINAL-QA-JUSTIFICATION',
subtotal_minor: 10000,
tax_minor: 0,
total_minor: 10000,
},
rules: {
first_limit_minor: 5000,
second_limit_minor: 20000,
approval_includes_tax: false,
rules_provisional: true,
},
items: [
{
id: 3,
description: 'ORIGINAL-QA-ITEM',
quantity: '1.000',
unit: 'un',
unit_price_minor: 10000,
tax_rate: '0.00',
subtotal_minor: 10000,
tax_minor: 0,
total_minor: 10000,
},
],
steps: [
{
id: 4,
position: 1,
role: 'configured_1',
routing: { name: 'Direcção preservada' },
decision: 'approved',
approver_id: 7,
decided_at: '2026-11-27T12:05:00Z',
comment: '<script>ORIGINAL-QA-DECISION</script>',
},
{
id: 5,
position: 2,
role: 'procurement',
decision: 'pending',
},
],
},
],
},
});
expect(html).toContain('ORIGINAL-QA-JUSTIFICATION');
expect(html).toContain('ORIGINAL-QA-ITEM');
expect(html).toContain('100,00');
expect(html).toContain('sem IVA');
expect(html).toContain('Regras provisórias na submissão original');
expect(html).toContain('Direcção preservada');
expect(html).toContain('Utilizador #7');
expect(html).toContain('&lt;script&gt;ORIGINAL-QA-DECISION&lt;/script&gt;');
expect(html).toContain('Etapa pendente no momento da devolução');
expect(html).toContain('não são as aprovações da nova');
expect(html).not.toContain('<form');
});
test('missing historical values remain unknown instead of becoming zero or current rules', () => {
const html = render({});
expect(html).toContain('Não preservado');
expect(html).toContain('Artigos não preservados neste registo');
expect(html).not.toContain('0,00');
expect(html).not.toContain('Regras provisórias na submissão original');
});
test('historical routing amount remains distinct from goods and a preserved zero remains zero', () => {
const history = {
prev_page_url: null,
next_page_url: null,
data: [
{
id: 8,
data: { cycle: 1, next_cycle: 2 },
reason: 'Synthetic source',
request: {
number: 'REQ-QA',
subtotal_minor: 10000,
tax_minor: 0,
total_minor: 10000,
},
approval_amount_minor: 11000,
approval_uses_separate_basis: true,
rules: {
approval_includes_tax: true,
routing_plan_revision: 3,
},
steps: [],
items: [],
},
],
};
const html = render({ history });
expect(html).toContain('100,00');
expect(html).toContain('110,00');
expect(html).toContain('Base adicional preservada');
expect(html).toContain('Plano de encaminhamento · versão 3');
const zero = render({
history: {
...history,
data: [{ ...history.data[0], approval_amount_minor: 0 }],
},
});
expect(zero).toContain('Valor usado no encaminhamento: 0,00');
});
test('a pending configured deadline exposes due actions only when allowed', () => {
const html = render({
canEdit: false,
canCheck: true,
deadline: {
state: "running",
state: 'running',
step_id: 2,
expires_at: "2026-11-27T12:30:00Z",
basis_hash: "a".repeat(64),
expires_at: '2026-11-27T12:30:00Z',
basis_hash: 'a'.repeat(64),
},
});
expect(html).toContain("Verificar e executar acções devidas");
expect(html).not.toContain("Rever rascunho");
expect(html).not.toContain("Devolver ao requisitante</button>");
expect(html).toContain('Verificar e executar acções devidas');
expect(html).not.toContain('Rever rascunho');
expect(html).not.toContain('Devolver ao requisitante</button>');
});
test('urgent deadline explains the frozen shorter policy without exposing a new approval grant', () => {
const html = render({
canEdit: false,
canCheck: true,
deadline: {
state: 'running',
step_id: 2,
timing: 'urgent_override',
expires_at: '2026-11-27T12:05:00Z',
reminder_at: '2026-11-27T12:01:00Z',
escalation_at: '2026-11-27T12:02:00Z',
basis_hash: 'a'.repeat(64),
},
});
expect(html).toContain(
'Prazos reduzidos para urgência, preservados na submissão.',
);
expect(html).toContain('Escalamento previsto');
expect(html).not.toContain('Aprovar');
});
+52 -2
View File
@@ -113,7 +113,7 @@ const restored = {
],
};
function render(userId = 7, tenantId = 3) {
function render(userId = 7, tenantId = 3, errors: Record<string, string> = {}) {
return renderToStaticMarkup(
<App
initialComponent={RequisitionForm}
@@ -124,7 +124,7 @@ function render(userId = 7, tenantId = 3) {
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
errors,
auth: { user: { id: userId, tenant_id: tenantId } },
internalRequisitionReady: true,
incompleteDraftsAvailable: true,
@@ -145,6 +145,27 @@ test('native remembered history restores unfinished fields and line values witho
expect(html).toContain('Artigo ainda por gravar');
expect(html).toContain('value="2.000"');
expect(html).not.toContain('value="0.00"');
expect(html).toContain('Por completar');
expect(html).toContain('data-preparation-dirty="true"');
});
test('the native form displays the exact half-cent estimate from remembered decimal inputs', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'requisition:3:7:new:0:data'
? {
...restored,
items: [
{
...restored.items[0],
quantity: '0.29',
unit_price: '0.50',
tax_rate: '0',
},
],
}
: undefined,
);
expect(render()).toContain('0,15 MZN');
});
test('remembered preparation is separated by user and company', () => {
@@ -152,5 +173,34 @@ test('remembered preparation is separated by user and company', () => {
key === 'requisition:3:7:new:0:data' ? restored : undefined,
);
expect(render(8, 3)).not.toContain('Artigo ainda por gravar');
expect(render(8, 3)).toContain('data-preparation-dirty="false"');
expect(render(7, 4)).not.toContain('Artigo ainda por gravar');
});
test('native validation links address the restored line and retain process errors without a false field destination', () => {
const errors = {
'items.0.quantity': 'Corrija a quantidade',
'items.0.equipment_id': 'Confira o equipamento',
cost_center_id: 'Escolha o centro',
process_version: 'Actualize a versão',
};
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'requisition:3:7:new:0:data'
? restored
: key === 'requisition:3:7:new:0:errors'
? errors
: undefined,
);
const html = render(7, 3, errors);
expect(html).toContain('href="#quantity-kept-line"');
expect(html).toContain('id="quantity-kept-line"');
expect(html).toContain('href="#requisition-line-kept-line"');
expect(html).toContain('id="requisition-line-kept-line"');
expect(html).toContain('href="#cost-center"');
expect(html).toContain('aria-describedby="error-items.0.quantity"');
expect(html).toContain('id="error-items.0.quantity"');
expect(html).toContain('id="error-items.0.equipment_id"');
expect(html).toContain('id="error-cost_center_id"');
expect(html).not.toContain('href="#process_version"');
expect(html).toContain('Actualize a versão');
});
@@ -0,0 +1,66 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import {
SubmissionPreviewDetails,
RequisitionSubmissionConfirmation,
type SubmissionPreview,
} from '@/components/requisition-submission-confirmation';
const preview: SubmissionPreview = {
state: 'planned',
process_version: 3,
subtotal_minor: '10000',
total_minor: '11600',
approval_amount_minor: '13000',
includes_tax: true,
provisional_rules: true,
import_basis: true,
steps: [
{ role: 'department_head', label: null },
{ role: 'configured_1', label: 'Direcção <QA>' },
],
};
test('confirmation names the exact document and approval bases and ordered routing without treating preview as submission', () => {
const html = renderToStaticMarkup(
<SubmissionPreviewDetails number="REQ-QA-1" preview={preview} />,
);
expect(html).toContain('116,00 MZN');
expect(html).toContain('130,00 MZN');
expect(html).toContain('estimativa de importação');
expect(html).toContain('provisórias');
expect(html).toContain('Chefe de departamento');
expect(html).toContain('Direcção &lt;QA&gt;');
expect(html).toContain('não cria reservas nem aprovações');
expect(html).not.toContain('configured_1');
});
test('unknown routing does not display a zero or invent approval stages', () => {
const html = renderToStaticMarkup(
<SubmissionPreviewDetails
number="REQ-QA-2"
preview={{ state: 'unavailable', message: 'Reveja a estimativa' }}
/>,
);
expect(html).toContain('Reveja a estimativa');
expect(html).not.toContain('0,00 MZN');
expect(html).not.toContain('<ol');
});
test('opening confirmation does not invoke the submission callback during rendering', () => {
let submitted = false;
const html = renderToStaticMarkup(
<RequisitionSubmissionConfirmation
number="REQ-QA-1"
preview={preview}
processing={false}
errors={[]}
onConfirm={() => {
submitted = true;
}}
/>,
);
expect(submitted).toBe(false);
expect(html).toContain('Submeter para aprovação');
expect(html).not.toContain('Confirmar e submeter');
});
@@ -0,0 +1,239 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Stock from '@/pages/stock/index';
import Operations, { OperationsDemo } from '@/pages/stock/operations';
vi.mock('@/components/administrative-location', () => ({
AdministrativeLocation: ({ value }: { value: unknown }) => (
<div>{JSON.stringify(value)}</div>
),
}));
afterEach(() => vi.restoreAllMocks());
const base = 'inventory-events:4:7:warehouse';
const operationIdentity = `${base}:/stock/operacoes:true:false`;
const initialOperation = {
kind: 'issue',
reference: '',
idempotency_key: 'saved-qa-operation',
stock_item_id: '1',
warehouse_id: '2',
destination_warehouse_id: '',
responsible_id: '',
destination: '',
reason: '',
quantity: '',
count_id: '',
ledger_version: 0,
equipment_id: '',
};
function render(
operations = false,
overrides = {},
actor = 7,
tenant = 4,
context = 'warehouse',
) {
return renderToStaticMarkup(
<App
initialComponent={operations ? Operations : Stock}
initialPage={{
component: operations ? 'stock/operations' : 'stock/index',
url: '/stock',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
items: [
{
id: 1,
code: 'ITEM-QA',
name: 'Synthetic item',
unit: 'un',
},
],
warehouses: [
{ id: 2, code: 'WH-QA', name: 'Synthetic warehouse' },
],
balances: [],
movements: {
data: [],
prev_page_url: null,
next_page_url: null,
},
filters: {},
canManage: true,
users: [],
operations: {
data: [],
prev_page_url: null,
next_page_url: null,
},
counts: [],
canOperate: true,
...overrides,
},
}}
/>,
);
}
test.each([
[
'item',
{ code: 'NEW-ITEM-QA', name: 'PRIVATE-CATALOGUE-DRAFT', unit: 'un' },
],
[
'warehouse',
{
code: 'NEW-WH-QA',
name: 'PRIVATE-CATALOGUE-DRAFT',
geography_reference: null,
},
],
])(
'stock %s preparation remains isolated from other actors companies contexts and capabilities',
(suffix, data) => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:/stock:catalogue:true:false:${suffix}:data`
? data
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('PRIVATE-CATALOGUE-DRAFT');
expect(render()).toContain('data-preparation-dirty="true"');
expect(render(false, {}, 8)).not.toContain('PRIVATE-CATALOGUE-DRAFT');
expect(render(false, {}, 7, 5)).not.toContain(
'PRIVATE-CATALOGUE-DRAFT',
);
expect(render(false, {}, 7, 4, 'finance')).not.toContain(
'PRIVATE-CATALOGUE-DRAFT',
);
expect(render(false, { canManage: false })).not.toContain(
'PRIVATE-CATALOGUE-DRAFT',
);
expect(post).not.toHaveBeenCalled();
},
);
test('warehouse location preparation preserves the expected original reference and is source scoped', () => {
const reference = {
catalogue: 'qa-catalogue',
record_id: '11',
country: 'MZ',
};
vi.spyOn(router, 'restore').mockImplementation((k) =>
k ===
`${base}:/stock/warehouse-location:2:${JSON.stringify(reference)}:data`
? {
expected_reference: reference,
geography_reference: {
...reference,
record_id: 'PRIVATE-LOCATION-QA',
},
}
: undefined,
);
const props = {
geographyEnabled: true,
warehouseGeography: { 2: { reference, path: [] } },
};
expect(render(false, props)).toContain('PRIVATE-LOCATION-QA');
expect(render(false, props)).toContain('data-preparation-dirty="true"');
expect(
render(false, {
...props,
warehouseGeography: {
2: { reference: { ...reference, record_id: '12' }, path: [] },
},
}),
).not.toContain('PRIVATE-LOCATION-QA');
expect(render(false, props, 8)).not.toContain('PRIVATE-LOCATION-QA');
});
test('stock movement preparation retains native idempotency data only in the authorised actor context', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${operationIdentity}:data`
? {
...initialOperation,
reference: 'PRIVATE-MOVEMENT-QA',
quantity: '1.234',
reason: 'Synthetic physical evidence',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render(true)).toContain('PRIVATE-MOVEMENT-QA');
expect(render(true)).toContain('data-preparation-dirty="true"');
expect(render(true, {}, 8)).not.toContain('PRIVATE-MOVEMENT-QA');
expect(render(true, {}, 7, 5)).not.toContain('PRIVATE-MOVEMENT-QA');
expect(render(true, {}, 7, 4, 'finance')).not.toContain(
'PRIVATE-MOVEMENT-QA',
);
expect(render(true, { canOperate: false })).not.toContain(
'PRIVATE-MOVEMENT-QA',
);
expect(post).not.toHaveBeenCalled();
});
test('lot count input recovery requires the exact native baseline hash', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${operationIdentity}:data`
? { ...initialOperation, kind: 'count' }
: k === `${operationIdentity}:lot-count-inputs`
? {
'baseline-qa': [
{
lot_id: 5,
new_key: null,
quantity: '7.321',
code: 'LOT-QA',
expires_on: '2027-01-01',
no_expiry: false,
},
],
}
: undefined,
);
const source = {
stock_item_id: 1,
warehouse_id: 2,
hash: 'baseline-qa',
lots: [
{
lot_id: 5,
metadata_id: 5,
quantity_milli: 1000,
code: 'LOT-QA',
expires_on: '2027-01-01',
no_expiry: false,
},
],
};
expect(render(true, { lotCounts: [source] })).toContain('value="7.321"');
expect(
render(true, { lotCounts: [{ ...source, hash: 'new-baseline-qa' }] }),
).not.toContain('value="7.321"');
});
test('restored idempotency alone stays clean and the demonstration remains independently renderable', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${operationIdentity}:data` ? initialOperation : undefined,
);
const post = vi.spyOn(router, 'post');
expect(render(true)).toContain('data-preparation-dirty="false"');
expect(
renderToStaticMarkup(
<App
initialComponent={OperationsDemo}
initialPage={{
component: 'preview/index',
url: '/preview',
version: null,
clearHistory: false,
encryptHistory: false,
props: { errors: {} },
}}
/>,
),
).toContain('Saídas, transferências e inventários');
expect(post).not.toHaveBeenCalled();
});
@@ -0,0 +1,123 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Bank from '@/pages/suppliers/bank';
afterEach(() => vi.restoreAllMocks());
const identity = 'supplier-bank:4:7:2:legacy:3:true:true';
const proposal = {
previous_id: 3,
account_key: null,
bank_name: 'BANK-QA-NOT-SUBMITTED',
country: 'MZ',
currency: 'MZN',
beneficiary: 'Synthetic beneficiary',
account_identifier: 'SYNTHETIC-IDENTIFIER',
evidence_reference: 'Synthetic evidence',
reason: 'Unsubmitted synthetic proposal',
};
function render(
actor = 7,
tenant = 4,
version = 3,
canPropose = true,
canReview = true,
accountKey: string | null = null,
) {
return renderToStaticMarkup(
<App
initialComponent={Bank}
initialPage={{
component: 'suppliers/bank',
url: '/fornecedores/2/dados-bancarios',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
actorId: actor,
supplier: { id: 2, name: 'Synthetic supplier' },
currentId: version,
state: 'pending',
accountKey,
multiAccountsAvailable: true,
current: {
id: version,
revision: 1,
bank_name: 'Current synthetic bank',
country: 'MZ',
currency: 'MZN',
beneficiary: 'Current synthetic beneficiary',
account_identifier: 'CURRENT-QA',
evidence_reference: 'Current synthetic evidence',
reason: 'Current synthetic reason',
},
history: [],
reviews: [],
canPropose,
canReview,
},
}}
/>,
);
}
test('unsubmitted bank proposal is restored privately without proposing or reviewing automatically', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:proposal:data` ? proposal : undefined,
);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).toContain('BANK-QA-NOT-SUBMITTED');
expect(html).toContain('SYNTHETIC-IDENTIFIER');
expect(html).toContain('data-preparation-dirty="true"');
expect(post).not.toHaveBeenCalled();
expect(render(8)).not.toContain('BANK-QA-NOT-SUBMITTED');
expect(render(7, 5)).not.toContain('BANK-QA-NOT-SUBMITTED');
expect(render(7, 4, 4)).not.toContain('BANK-QA-NOT-SUBMITTED');
expect(render(7, 4, 3, false)).not.toContain('BANK-QA-NOT-SUBMITTED');
expect(
render(7, 4, 3, true, true, '00000000-0000-4000-8000-000000000002'),
).not.toContain('BANK-QA-NOT-SUBMITTED');
});
test('independent account preparation restores its pending identity and mode without creating the account', () => {
const accountKey = '00000000-0000-4000-8000-000000000002';
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:adding`
? true
: key === `${identity}:proposal:data`
? { ...proposal, previous_id: 0, account_key: accountKey }
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).toContain('Propor conta independente');
expect(html).toContain('BANK-QA-NOT-SUBMITTED');
expect(post).not.toHaveBeenCalled();
});
test('bank review preparation remains tied to the same reviewer and exact bank version', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity}:review:data`
? {
decision: 'rejected',
reason: 'REVIEW-QA-NOT-SUBMITTED',
independently_verified: true,
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('REVIEW-QA-NOT-SUBMITTED');
expect(render(8)).not.toContain('REVIEW-QA-NOT-SUBMITTED');
expect(render(7, 4, 4)).not.toContain('REVIEW-QA-NOT-SUBMITTED');
expect(render(7, 4, 3, true, false)).not.toContain(
'REVIEW-QA-NOT-SUBMITTED',
);
expect(post).not.toHaveBeenCalled();
});
test('empty bank preparation stays clean', () => {
expect(render()).not.toContain('data-preparation-dirty="true"');
});
@@ -0,0 +1,303 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Responses from '@/components/supplier-responses';
import Improvements from '@/components/supplier-improvements';
import Supplier from '@/pages/suppliers/show';
afterEach(() => vi.restoreAllMocks());
const base = 'procurement-preparations:4:7:procurement.internal:procurement';
const response = {
id: 11,
version: 2,
status: 'draft',
payload: {
title: 'Original response',
received_on: '2026-11-28',
source_reference: 'REF-QA',
statement: 'Original statement',
},
decision: null,
created_by: 9,
reviewed_by: null,
reviewed_at: null,
review_reason: null,
canEdit: true,
canReview: false,
};
const measure = {
id: 12,
version: 2,
status: 'open',
title: 'Original measure',
description: 'Original plan',
responsible_id: 9,
due_on: '2026-12-31',
result: null,
evidence: null,
reviewed_by: null,
review_reason: null,
reviewed_at: null,
canPlan: true,
canExecute: true,
canReview: true,
};
const supplier = {
id: 13,
version: 2,
name: 'Synthetic supplier',
nuit: '123456789',
contact: 'Synthetic',
email: 'qa@example.test',
phone: '123',
address: 'Synthetic location',
category: 'Other',
beneficiaries: 'Synthetic',
document_references: 'REF-QA',
diligence_notes: 'Synthetic',
blocked: false,
next_review: '2027-01-01',
status: 'active',
review_comment: null,
};
function render(
kind: 'responses' | 'improvements' | 'supplier',
overrides = {},
actor = 7,
tenant = 4,
context = 'procurement.internal',
) {
const data =
kind === 'responses'
? {
ready: true,
canCreate: true,
records: [response],
history: null,
}
: {
ready: true,
canCreate: true,
records: [measure],
assignees: [
{ id: 7, name: 'Current' },
{ id: 9, name: 'Other' },
],
today: '2026-11-28',
history: null,
};
return renderToStaticMarkup(
<App
initialComponent={
kind === 'responses'
? Responses
: kind === 'improvements'
? Improvements
: Supplier
}
initialPage={{
component: 'test',
url: '/test',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
workContext: { active: context },
organizationAccess: { permissions: ['procurement'] },
data,
evaluationId: 3,
names: { 7: 'Current', 9: 'Other' },
reportOnly: false,
generatedAt: '2026-11-28T00:00:00Z',
supplier,
documents: [],
canEdit: true,
canDocuments: true,
canReview: true,
...overrides,
},
}}
/>,
);
}
test.each([
[
'responses',
':create',
{
payload: {
title: 'PRIVATE-SUPPLIER-PREPARATION',
received_on: '2026-11-28',
source_reference: 'REF-QA',
statement: 'Prepared statement',
},
},
],
[
'responses',
':record:11:2:draft:true:false:edit',
{
version: 2,
payload: {
...response.payload,
statement: 'PRIVATE-SUPPLIER-PREPARATION',
},
},
],
[
'improvements',
':create',
{
title: 'PRIVATE-SUPPLIER-PREPARATION',
description: 'Prepared plan',
responsible_id: '7',
due_on: '2026-12-31',
},
],
[
'improvements',
':record:12:2:open:true:true:true:plan',
{
version: 2,
title: 'PRIVATE-SUPPLIER-PREPARATION',
description: 'Prepared plan',
responsible_id: '7',
due_on: '2026-12-31',
reason: 'Synthetic reason',
},
],
[
'improvements',
':record:12:2:open:true:true:true:progress',
{
version: 2,
result: 'PRIVATE-SUPPLIER-PREPARATION',
evidence: 'Synthetic evidence',
},
],
[
'improvements',
':record:12:2:open:true:true:true:decision',
{ version: 2, reason: 'PRIVATE-SUPPLIER-PREPARATION' },
],
] as const)(
'%s %s preparation stays in its actor/company/context/evaluation and outside report mode',
(kind, suffix, prepared) => {
const identity = `${base}:supplier-${kind}:3:true:true:false`;
const restore = vi
.spyOn(router, 'restore')
.mockImplementation((k) =>
k === `${identity}${suffix}:data`
? prepared
: k === `${identity}:operation`
? '11111111-1111-4111-8111-111111111111'
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render(kind)).toContain('PRIVATE-SUPPLIER-PREPARATION');
expect(render(kind)).toContain('data-preparation-dirty="true"');
expect(render(kind, {}, 8)).not.toContain(
'PRIVATE-SUPPLIER-PREPARATION',
);
expect(render(kind, {}, 7, 5)).not.toContain(
'PRIVATE-SUPPLIER-PREPARATION',
);
expect(render(kind, {}, 7, 4, 'finance')).not.toContain(
'PRIVATE-SUPPLIER-PREPARATION',
);
expect(render(kind, { evaluationId: 4 })).not.toContain(
'PRIVATE-SUPPLIER-PREPARATION',
);
expect(render(kind, { reportOnly: true })).not.toContain(
'PRIVATE-SUPPLIER-PREPARATION',
);
if (suffix.startsWith(':record')) {
const data =
kind === 'responses'
? {
ready: true,
canCreate: true,
records: [{ ...response, version: 3 }],
history: null,
}
: {
ready: true,
canCreate: true,
records: [{ ...measure, version: 3 }],
assignees: [],
today: '2026-11-28',
history: null,
};
expect(render(kind, { data })).not.toContain(
'PRIVATE-SUPPLIER-PREPARATION',
);
}
expect(restore).toHaveBeenCalledWith(`${identity}:operation`);
expect(post).not.toHaveBeenCalled();
},
);
test('independent response analysis is source/version scoped without replacing the original record', () => {
const reviewing = {
...response,
status: 'review',
canEdit: false,
canReview: true,
};
const data = {
ready: true,
canCreate: true,
records: [reviewing],
history: null,
};
vi.spyOn(router, 'restore').mockImplementation((k) =>
k ===
`${base}:supplier-responses:3:true:true:false:record:11:2:review:false:true:review:data`
? {
version: 2,
outcome: 'accepted',
reason: 'RESPONSE-REVIEW-QA',
follow_up: 'Synthetic follow-up',
response_reference: 'REF-QA',
}
: undefined,
);
expect(render('responses', { data })).toContain('RESPONSE-REVIEW-QA');
expect(render('responses', { data })).toContain('Original statement');
expect(
render('responses', {
data: { ...data, records: [{ ...reviewing, version: 3 }] },
}),
).not.toContain('RESPONSE-REVIEW-QA');
expect(
render('responses', {
data: { ...data, records: [{ ...reviewing, canReview: false }] },
}),
).not.toContain('RESPONSE-REVIEW-QA');
});
test('supplier validation preparation follows its exact native version without remembering uploads', () => {
vi.spyOn(router, 'restore').mockImplementation((k) =>
k === `${base}:supplier-review:13:2:data`
? { status: 'active', comment: 'SUPPLIER-REVIEW-QA' }
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render('supplier')).toContain('SUPPLIER-REVIEW-QA');
expect(
render('supplier', { supplier: { ...supplier, version: 3 } }),
).not.toContain('SUPPLIER-REVIEW-QA');
expect(render('supplier', { canReview: false })).not.toContain(
'SUPPLIER-REVIEW-QA',
);
expect(render('supplier', {}, 8)).not.toContain('SUPPLIER-REVIEW-QA');
expect(post).not.toHaveBeenCalled();
});
test('unchanged native supplier forms remain clean', () => {
vi.spyOn(router, 'restore').mockReturnValue(undefined);
expect(render('responses')).not.toContain('data-preparation-dirty="true"');
expect(render('improvements')).not.toContain(
'data-preparation-dirty="true"',
);
expect(render('supplier')).not.toContain('data-preparation-dirty="true"');
});
@@ -0,0 +1,85 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import EditSupplier from '@/pages/suppliers/edit';
import type { Supplier } from '@/types/supplier';
afterEach(() => vi.restoreAllMocks());
const supplier: Supplier = {
id: 42,
name: 'Fornecedor sintético',
nuit: '123456789',
contact: 'Contacto sintético',
email: 'qa@example.invalid',
phone: '123456789',
address: 'Morada sintética',
category: 'Material',
beneficiaries: 'Beneficiário sintético',
document_references: 'Referências documentais sintéticas',
diligence_notes: 'Conferência sintética anterior',
next_review: '2027-01-01',
blocked: false,
version: 1,
status: 'active',
review_comment: null,
};
const preparation = {
geography_reference: null,
name: 'NOME-QA-POR-GUARDAR',
nuit: supplier.nuit,
contact: supplier.contact,
email: supplier.email,
phone: supplier.phone,
address: 'Morada por guardar',
category: supplier.category,
beneficiaries: supplier.beneficiaries,
document_references: supplier.document_references,
diligence_notes: 'Preparação de diligência ainda não submetida',
next_review: supplier.next_review,
blocked: false,
version: 1,
};
function render(tenant = 3, actor = 7, id = 42, version = 1) {
return renderToStaticMarkup(
<App
initialComponent={EditSupplier}
initialPage={{
component: 'suppliers/edit',
url: `/fornecedores/${id}/editar`,
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
supplier: { ...supplier, id, version },
},
}}
/>,
);
}
test('supplier editing recovers the same private preparation without renewing diligence or saving automatically', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'supplier-preparation:3:7:42:1:data' ? preparation : undefined,
);
const put = vi.spyOn(router, 'put');
const html = render();
expect(html).toContain('NOME-QA-POR-GUARDAR');
expect(html).toContain('Morada por guardar');
expect(html).toContain('Preparação de diligência ainda não submetida');
expect(html).toContain('Alterações à ficha retiram a validação actual');
expect(put).not.toHaveBeenCalled();
});
test('supplier preparation does not cross actor company supplier identity or a changed server version', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'supplier-preparation:3:7:42:1:data' ? preparation : undefined,
);
expect(render(4)).not.toContain('NOME-QA-POR-GUARDAR');
expect(render(3, 8)).not.toContain('NOME-QA-POR-GUARDAR');
expect(render(3, 7, 43)).not.toContain('NOME-QA-POR-GUARDAR');
expect(render(3, 7, 42, 2)).not.toContain('NOME-QA-POR-GUARDAR');
});
@@ -0,0 +1,243 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Coordination from '@/pages/supply/coordination';
afterEach(() => vi.restoreAllMocks());
const props = {
kind: 'delivery',
ready: true,
canPrepare: true,
canReview: true,
conversionQaEnabled: true,
eligible: {},
pending: {},
records: [],
history: {},
items: [{ id: 1, code: 'QA', name: 'Synthetic item', unit: 'un' }],
warehouses: [],
requestLines: [],
orderLines: [
{
id: 3,
label: 'Synthetic source',
unit: 'box',
stock_item_id: 1,
quantity_milli: 2000,
},
],
operations: [],
};
function render(overrides = {}, actor = 7, tenant = 4) {
return renderToStaticMarkup(
<App
initialComponent={Coordination}
initialPage={{
component: 'supply/coordination',
url: '/compras/fornecimento?view=deliveries',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
...props,
...overrides,
},
}}
/>,
);
}
test('confirmed delivery preparation restores documentary quantity and explicit conversion independently', () => {
const key =
'supply-coordination:4:7:delivery:true:true:true:true:new:0:new::prepare';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === `${key}:data`
? {
operation_key: 'synthetic-delivery',
version: 0,
action: 'save',
reason: 'DELIVERY-EVIDENCE-QA',
data: {
purchase_order_item_id: '3',
stock_item_id: '1',
warehouse_id: '',
quantity: '1.500',
expected_on: '2026-12-15',
confirmed_on: '2026-11-28',
evidence: 'SYNTHETIC-CARRIER-QA',
},
}
: candidate === `${key}:conversion`
? {
numerator: '12',
denominator: '1',
source: 'UNSUBMITTED-CONVERSION-SOURCE',
version: 'source-v2',
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).toContain('value="1.500"');
expect(html).toContain('UNSUBMITTED-CONVERSION-SOURCE');
expect(html).toContain('source-v2');
expect(html).toContain('data-preparation-dirty="true"');
expect(render({}, 8)).not.toContain('UNSUBMITTED-CONVERSION-SOURCE');
expect(render({}, 7, 5)).not.toContain('UNSUBMITTED-CONVERSION-SOURCE');
expect(render({ conversionQaEnabled: false })).not.toContain(
'DELIVERY-EVIDENCE-QA',
);
expect(render({ canReview: false })).not.toContain('DELIVERY-EVIDENCE-QA');
expect(post).not.toHaveBeenCalled();
});
test.each(['reservation', 'alternative'])(
'%s preparation restores in its own source journey',
(kind) => {
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate ===
`supply-coordination:4:7:${kind}:true:true:true:true:new:0:new::prepare:data`
? {
operation_key: 'synthetic-prepare',
version: 0,
action: 'save',
reason: 'COORDINATION-PREPARATION-QA',
data: {
stock_item_id: '1',
warehouse_id: '',
quantity: '1.500',
needed_on: '2026-12-15',
reference: 'Synthetic reference',
compatibility: 'pending',
application: 'Synthetic machine',
evidence: 'Synthetic evidence',
conditions: 'Synthetic conditions',
factor_numerator: 1,
factor_denominator: 1,
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render({ kind })).toContain('COORDINATION-PREPARATION-QA');
expect(render()).not.toContain('COORDINATION-PREPARATION-QA');
expect(post).not.toHaveBeenCalled();
},
);
test('coordination data and conversion never cross the active work context', () => {
const key =
'supply-coordination:4:7:delivery:true:true:true:true:new:0:new::context:procurement.internal:prepare';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === `${key}:data`
? {
operation_key: 'synthetic-context',
version: 0,
action: 'save',
reason: 'CONTEXT-SPECIFIC-DELIVERY-QA',
data: {
purchase_order_item_id: '3',
stock_item_id: '1',
warehouse_id: '',
quantity: '1.500',
expected_on: '2026-12-15',
confirmed_on: '2026-11-28',
evidence: 'Synthetic evidence',
},
}
: candidate === `${key}:conversion`
? {
numerator: '12',
denominator: '1',
source: 'CONTEXT-SPECIFIC-CONVERSION-QA',
version: 'v2',
}
: undefined,
);
const html = render({ workContext: { active: 'procurement.internal' } });
expect(html).toContain('CONTEXT-SPECIFIC-DELIVERY-QA');
expect(html).toContain('CONTEXT-SPECIFIC-CONVERSION-QA');
const other = render({
workContext: { active: 'procurement.third_party' },
});
expect(other).not.toContain('CONTEXT-SPECIFIC-DELIVERY-QA');
expect(other).not.toContain('CONTEXT-SPECIFIC-CONVERSION-QA');
expect(render()).not.toContain('CONTEXT-SPECIFIC-DELIVERY-QA');
});
const record = {
id: 9,
record_key: 'qa-reservation',
version: 2,
state: 'active',
reason: 'Original synthetic reservation',
created_at: '2026-11-28',
canApprove: false,
canReturn: false,
canSuspend: false,
canEdit: true,
canFulfil: true,
canCancel: true,
data: {
stock_item_id: 1,
warehouse_id: 2,
quantity_milli: 2000,
applications: [],
},
snapshot: {
item: { code: 'QA', name: 'Synthetic item', unit: 'un' },
warehouse: { name: 'Synthetic warehouse' },
},
};
test('unsubmitted fulfilment restores only for the same pending quantity and eligible version', () => {
const key =
'supply-coordination:4:7:reservation:true:true:true:true:qa-reservation:2:active:2000:action:false:false:false:true:true:true:data';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: 'synthetic-fulfilment',
record_key: record.record_key,
version: 2,
action: 'fulfil',
reason: 'PENDING-ALLOCATION-QA',
quantity: '0.500',
data: { stock_operation_id: '12', quantity_milli: 0 },
}
: undefined,
);
const base = {
kind: 'reservation',
records: [record],
pending: { 'qa-reservation': 2000 },
operations: [
{
id: 12,
reference: 'Synthetic issue',
stock_item_id: 1,
warehouse_id: 2,
quantity_milli: 500,
},
],
};
const post = vi.spyOn(router, 'post');
expect(render(base)).toContain('PENDING-ALLOCATION-QA');
expect(render(base)).toContain('value="0.500"');
expect(
render({ ...base, pending: { 'qa-reservation': 1500 } }),
).not.toContain('PENDING-ALLOCATION-QA');
expect(
render({ ...base, records: [{ ...record, version: 3 }] }),
).not.toContain('PENDING-ALLOCATION-QA');
expect(
render({ ...base, records: [{ ...record, canFulfil: false }] }),
).not.toContain('PENDING-ALLOCATION-QA');
expect(post).not.toHaveBeenCalled();
});
test.each(['delivery', 'reservation', 'alternative'])(
'unchanged %s preparation is clean',
(kind) => {
expect(render({ kind })).not.toContain('data-preparation-dirty="true"');
},
);
@@ -0,0 +1,343 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import History from '@/pages/supply/history';
import Suggestions from '@/pages/supply/suggestions';
afterEach(() => vi.restoreAllMocks());
const historyProps = {
ready: true,
actorId: 7,
canPrepare: true,
canReview: true,
records: [],
history: {},
items: [],
warehouses: [],
defaultPeriod: { from: '2026-10-01', until: '2026-10-31' },
};
const suggestionProps = {
ready: true,
actorId: 7,
canPrepare: true,
canReview: true,
canConvert: true,
records: [],
policies: [
{
key: 'policy-qa',
version: 2,
label: 'Synthetic policy',
issue: null,
unit_price: '12.50',
tax_rate: '0.00',
},
],
excess: {},
costCenters: [],
requestLinks: {},
history: {},
};
function render(
kind: 'history' | 'suggestions',
overrides = {},
actor = 7,
tenant = 4,
) {
return renderToStaticMarkup(
<App
initialComponent={kind === 'history' ? History : Suggestions}
initialPage={{
component: `supply/${kind}`,
url: `/compras/fornecimento?view=${kind}`,
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
...(kind === 'history' ? historyProps : suggestionProps),
actorId: actor,
...overrides,
},
}}
/>,
);
}
test('consumption evidence and its explicit period restore without calculating or approving', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === 'supply-history:4:7:true:true:true:new:0:new:prepare:data'
? {
operation_key: 'synthetic-history',
version: 0,
action: 'save',
reason: 'HISTORY-EVIDENCE-QA',
data: {
stock_item_id: '',
warehouse_id: '',
purpose: 'internal',
period_from: '2026-09-01',
period_until: '2026-09-30',
quality: 'incomplete',
pattern: 'seasonal',
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render('history');
expect(html).toContain('HISTORY-EVIDENCE-QA');
expect(html).toContain('value="2026-09-01"');
expect(html).toContain('<option value="incomplete" selected="">');
expect(html).toContain('data-preparation-dirty="true"');
expect(render('history', {}, 8)).not.toContain('HISTORY-EVIDENCE-QA');
expect(render('history', {}, 7, 5)).not.toContain('HISTORY-EVIDENCE-QA');
expect(render('history', { canReview: false })).not.toContain(
'HISTORY-EVIDENCE-QA',
);
expect(post).not.toHaveBeenCalled();
});
test('suggestion restores one policy selection with its deliberately edited estimates and manual plan', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key ===
'supply-suggestion:4:7:true:true:true:true:new:0:new:prepare:data'
? {
operation_key: 'synthetic-suggestion',
version: 0,
action: 'save',
reason: 'SUGGESTION-EVIDENCE-QA',
data: {
policy_key: 'policy-qa',
unit_price: '14.25',
tax_rate: '0.00',
quantity: '3.500',
delivery_on: '2026-12-15',
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render('suggestions');
expect(html).toContain('<option value="policy-qa" selected="">');
expect(html).toContain('value="14.25"');
expect(html).toContain('value="0.00"');
expect(html).toContain('value="3.500"');
expect(html).toContain('value="2026-12-15"');
expect(html).toContain('SUGGESTION-EVIDENCE-QA');
expect(render('suggestions', {}, 8)).not.toContain(
'SUGGESTION-EVIDENCE-QA',
);
expect(render('suggestions', {}, 7, 5)).not.toContain(
'SUGGESTION-EVIDENCE-QA',
);
expect(render('suggestions', { canConvert: false })).not.toContain(
'SUGGESTION-EVIDENCE-QA',
);
expect(post).not.toHaveBeenCalled();
});
test('a restored policy outside the current search remains visibly selected without inventing eligibility', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key ===
'supply-suggestion:4:7:true:true:true:true:new:0:new:prepare:data'
? {
operation_key: 'synthetic-suggestion',
version: 0,
action: 'save',
reason: 'Pending explicit policy verification',
data: {
policy_key: 'not-in-current-results',
unit_price: '14.25',
tax_rate: '0.00',
quantity: '',
delivery_on: '',
},
}
: undefined,
);
expect(render('suggestions', { policies: [] })).toContain(
'<option value="not-in-current-results" selected="">',
);
expect(render('suggestions', { policies: [] })).toContain(
'procurar para conferir',
);
});
test.each(['history', 'suggestions'] as const)(
'empty %s preparations remain clean',
(kind) => {
expect(render(kind)).not.toContain('data-preparation-dirty="true"');
},
);
test.each(['history', 'suggestions'] as const)(
'%s preparation is isolated by active work context',
(kind) => {
const key =
kind === 'history'
? 'supply-history:4:7:true:true:true:new:0:new:context:procurement.internal:prepare:data'
: 'supply-suggestion:4:7:true:true:true:true:new:0:new:context:procurement.internal:prepare:data';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: 'synthetic-context',
version: 0,
action: 'save',
reason: 'CONTEXT-SPECIFIC-FOLLOWUP-QA',
data:
kind === 'history'
? {
stock_item_id: '',
warehouse_id: '',
purpose: 'internal',
period_from: '2026-10-01',
period_until: '2026-10-31',
quality: 'unknown',
pattern: 'unknown',
}
: {
policy_key: 'policy-qa',
unit_price: '12.50',
tax_rate: '0.00',
quantity: '',
delivery_on: '',
},
}
: undefined,
);
expect(
render(kind, { workContext: { active: 'procurement.internal' } }),
).toContain('CONTEXT-SPECIFIC-FOLLOWUP-QA');
expect(
render(kind, {
workContext: { active: 'procurement.third_party' },
}),
).not.toContain('CONTEXT-SPECIFIC-FOLLOWUP-QA');
expect(render(kind)).not.toContain('CONTEXT-SPECIFIC-FOLLOWUP-QA');
},
);
const baseRecord = {
id: 9,
record_key: 'qa-record',
version: 2,
state: 'draft',
reason: 'Original synthetic evidence',
created_at: '2026-11-28',
canApprove: true,
canReturn: true,
canSuspend: false,
canConvert: false,
canCancel: true,
canClose: false,
};
const snapshot = {
item: { code: 'QA', name: 'Synthetic item', unit: 'un' },
warehouse: { name: 'Synthetic warehouse' },
contributors: [],
actor: { name: 'Synthetic author' },
};
const historyRecord = {
...baseRecord,
data: {
stock_item_id: 1,
warehouse_id: 2,
purpose: 'internal',
period_from: '2026-10-01',
period_until: '2026-10-31',
quality: 'complete',
pattern: 'regular',
},
snapshot: {
...snapshot,
analysis: {
days: 31,
total_milli: 1000,
daily_mean_milli: '32.258064516',
active_days: 1,
zero_balance_days: 0,
negative_balance_days: 0,
invalid_issue: false,
opening_milli: 2000,
movement_count: 1,
movement_types: { issue: 1 },
convention: 'Synthetic analysis',
series: [],
},
},
};
const suggestionRecord = {
...baseRecord,
data: {
policy_key: 'policy-qa',
policy_version: 2,
quantity_milli: 1000,
delivery_on: '2026-12-15',
unit_price: '12.50',
tax_rate: '0.00',
manual_plan: true,
price_source: 'Synthetic estimate',
tax_source: 'Illustrative zero',
},
snapshot: {
...snapshot,
prepared_on: '2026-11-28',
balance: { quantity: 2000 },
policy: { purpose: 'internal', origin: 'local' },
events: { reservations: [], receipts: [], warnings: [] },
projection: { available: true, series: [] },
},
};
test.each(['history', 'suggestions'] as const)(
'%s independent decision recovers only for the same source and eligibility',
(kind) => {
const key =
kind === 'history'
? 'supply-history:4:7:true:true:true:qa-record:2:draft:decision:true:true:false:data'
: 'supply-suggestion:4:7:true:true:true:true:qa-record:2:draft:decision:true:true:false:true:false:false:data';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: 'synthetic-decision',
record_key: 'qa-record',
version: 2,
action: 'return',
reason: 'INDEPENDENT-DECISION-QA',
data:
kind === 'history'
? { confirm_scope: false }
: {
cost_center_id: '',
confirm_exception: false,
},
}
: undefined,
);
const source = kind === 'history' ? historyRecord : suggestionRecord;
const post = vi.spyOn(router, 'post');
const html = render(kind, { records: [source] });
expect(html).toContain('INDEPENDENT-DECISION-QA');
expect(html).toContain('data-preparation-dirty="true"');
expect(
render(kind, { records: [{ ...source, version: 3 }] }),
).not.toContain('INDEPENDENT-DECISION-QA');
expect(
render(kind, { records: [{ ...source, canReturn: false }] }),
).not.toContain('INDEPENDENT-DECISION-QA');
expect(render(kind, { records: [source] }, 8)).not.toContain(
'INDEPENDENT-DECISION-QA',
);
if (kind === 'suggestions')
expect(
render(kind, {
records: [source],
excess: { 'qa-record': true },
}),
).not.toContain('INDEPENDENT-DECISION-QA');
expect(post).not.toHaveBeenCalled();
},
);
+285
View File
@@ -0,0 +1,285 @@
import { App, router } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { afterEach, expect, test, vi } from 'vitest';
import Supply from '@/pages/supply/index';
afterEach(() => vi.restoreAllMocks());
const record = {
id: 9,
record_key: 'synthetic-agreement',
version: 2,
state: 'draft',
data: { reference: 'Original reference', currency: 'MZN' },
reason: 'Original synthetic preparation',
created_at: '2026-11-28T00:00:00Z',
snapshot: {},
canApprove: true,
canReturn: true,
canSuspend: false,
};
const props = {
kind: 'agreement',
view: 'agreements',
ready: true,
orderLimitsReady: false,
asOf: '2026-11-28',
canPrepare: true,
canReview: true,
canCustoms: false,
records: [record],
history: {},
projections: {},
items: [],
warehouses: [],
suppliers: [],
orders: [],
histories: [],
agreements: [],
contracts: [],
};
function identity(key = 'new', version = 0, state = 'new') {
return `supply:4:7:agreement:agreements:::true:true:true:false:false:${key}:${version}:${state}`;
}
function render(overrides = {}, actor = 7, tenant = 4) {
return renderToStaticMarkup(
<App
initialComponent={Supply}
initialPage={{
component: 'supply/index',
url: '/compras/fornecimento?view=agreements',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
auth: { user: { id: actor, tenant_id: tenant } },
...props,
...overrides,
},
}}
/>,
);
}
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`
? {
operation_key: 'synthetic-pending-command',
version: 0,
action: 'save',
reason: 'UNSUBMITTED-SUPPLY-QA',
data: {
reference: 'PRIVATE-SUPPLY-REFERENCE',
currency: 'MZN',
habitual: true,
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render();
expect(html).toContain('PRIVATE-SUPPLY-REFERENCE');
expect(html).toContain('data-preparation-dirty="true"');
expect(render({}, 8)).not.toContain('PRIVATE-SUPPLY-REFERENCE');
expect(render({}, 7, 5)).not.toContain('PRIVATE-SUPPLY-REFERENCE');
for (const change of [
{ kind: 'contract', view: 'contracts' },
{ linkedContractKey: 'another-contract' },
{ linkedAgreementKey: 'another-agreement' },
{ canReview: false },
{ canCustoms: true },
{ orderLimitsReady: true },
]) {
expect(render(change)).not.toContain('PRIVATE-SUPPLY-REFERENCE');
}
expect(post).not.toHaveBeenCalled();
});
test('editing a supply version restores separately from a new preparation or later version', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity(record.record_key, 2, 'draft')}:prepare:data`
? {
operation_key: 'synthetic-edit-command',
record_key: record.record_key,
version: 2,
action: 'save',
reason: 'EDIT-PREPARATION-QA',
data: { reference: 'EDITED-REFERENCE-QA', currency: 'MZN' },
}
: undefined,
);
const html = render();
expect(html.match(/EDITED-REFERENCE-QA/g)).toHaveLength(1);
expect(render({ records: [{ ...record, version: 3 }] })).not.toContain(
'EDITED-REFERENCE-QA',
);
expect(
render({ records: [{ ...record, record_key: 'other-record' }] }),
).not.toContain('EDITED-REFERENCE-QA');
});
test('independent review restores its selected action and reason only for the exact authorised version', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key ===
`${identity(record.record_key, 2, 'draft')}:action:true:true:false:data`
? {
operation_key: 'synthetic-review-command',
record_key: record.record_key,
version: 2,
action: 'return',
reason: 'UNSUBMITTED-REVIEW-QA',
data: { evidence: '', event_date: '' },
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render()).toContain('UNSUBMITTED-REVIEW-QA');
expect(render()).toContain('<option value="return" selected="">');
expect(
render({ records: [{ ...record, canReturn: false }] }),
).not.toContain('UNSUBMITTED-REVIEW-QA');
expect(render({ records: [{ ...record, version: 3 }] })).not.toContain(
'UNSUBMITTED-REVIEW-QA',
);
expect(
render({ records: [{ ...record, state: 'approved' }] }),
).not.toContain('UNSUBMITTED-REVIEW-QA');
expect(render({}, 8)).not.toContain('UNSUBMITTED-REVIEW-QA');
expect(post).not.toHaveBeenCalled();
});
test('unchanged supply forms remain clean despite newly generated command identities', () => {
expect(render()).not.toContain('data-preparation-dirty="true"');
});
test('active work contexts never share an unsubmitted supply preparation', () => {
vi.spyOn(router, 'restore').mockImplementation((key) =>
key === `${identity()}:context:procurement.internal:prepare:data`
? {
operation_key: 'synthetic-context-command',
version: 0,
action: 'save',
reason: 'CONTEXT-SPECIFIC-SUPPLY-QA',
data: {
reference: 'Synthetic internal preparation',
currency: 'MZN',
habitual: true,
},
}
: undefined,
);
expect(
render({ workContext: { active: 'procurement.internal' } }),
).toContain('CONTEXT-SPECIFIC-SUPPLY-QA');
expect(
render({ workContext: { active: 'procurement.third_party' } }),
).not.toContain('CONTEXT-SPECIFIC-SUPPLY-QA');
expect(render()).not.toContain('CONTEXT-SPECIFIC-SUPPLY-QA');
});
test.each([
['contract', 'contracts'],
['policy', 'calendar'],
['import', 'imports'],
])(
'restores %s preparation in its own journey without a command',
(kind, view) => {
const key = `supply:4:7:${kind}:${view}:::true:true:true:false:false:new:0:new:prepare:data`;
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: 'synthetic-pending-command',
version: 0,
action: 'save',
reason: 'SHARED-PREPARATION-QA',
data: {
reference: 'Synthetic reference',
currency: 'MZN',
jurisdiction: 'Synthetic jurisdiction',
purpose: 'internal',
safety: '0',
minimum: '0',
pack: '1',
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
expect(render({ kind, view, records: [] })).toContain(
'SHARED-PREPARATION-QA',
);
expect(render()).not.toContain('SHARED-PREPARATION-QA');
expect(post).not.toHaveBeenCalled();
},
);
test('replacement policy restores a new proposal without overwriting its approved predecessor', () => {
const key =
'supply:4:7:policy:calendar:::true:true:true:false:false:synthetic-agreement:2:approved:copy:data';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: 'synthetic-replacement-command',
version: 0,
action: 'save',
reason: 'REPLACEMENT-ONLY-QA',
data: {
purpose: 'internal',
basis: 'NEW-POLICY-BASIS-QA',
safety: '0',
minimum: '0',
pack: '1',
},
}
: undefined,
);
const html = render({
kind: 'policy',
view: 'calendar',
records: [{ ...record, state: 'approved' }],
});
expect(html).toContain('NEW-POLICY-BASIS-QA');
expect(html).toContain('Original synthetic preparation');
expect(html).toContain('data-preparation-dirty="true"');
expect(
render({
kind: 'policy',
view: 'calendar',
records: [{ ...record, state: 'approved', version: 3 }],
}),
).not.toContain('NEW-POLICY-BASIS-QA');
});
test('logistics preparation restores its dated evidence without registering the milestone', () => {
const key =
'supply:4:7:import:imports:::true:true:true:true:false:synthetic-agreement:2:transit:action:true:true:false:data';
vi.spyOn(router, 'restore').mockImplementation((candidate) =>
candidate === key
? {
operation_key: 'synthetic-logistics-command',
record_key: record.record_key,
version: 2,
action: 'arrive',
reason: 'LOGISTICS-PREPARATION-QA',
data: {
evidence: 'UNSUBMITTED-SHIPPING-EVIDENCE',
event_date: '2026-11-27',
},
}
: undefined,
);
const post = vi.spyOn(router, 'post');
const html = render({
kind: 'import',
view: 'imports',
canCustoms: true,
records: [{ ...record, state: 'transit' }],
});
expect(html).toContain('UNSUBMITTED-SHIPPING-EVIDENCE');
expect(html).toContain('value="2026-11-27"');
expect(html).toContain('<option value="arrive" selected="">');
expect(html).toContain('data-preparation-dirty="true"');
expect(post).not.toHaveBeenCalled();
});
+127
View File
@@ -0,0 +1,127 @@
import { App } from '@inertiajs/react';
import type { ComponentProps } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Review from '@/pages/requisitions/urgent-review';
import Queue from '@/pages/requisitions/urgent-reviews';
import Policy from '@/pages/organization/urgent-review-policy';
function render(
component: Parameters<typeof App>[0]['initialComponent'],
props: object,
) {
return renderToStaticMarkup(
<App
initialComponent={component}
initialPage={{
component: 'qa',
url: '/requisicoes/urgencias/revisoes',
version: 'qa',
clearHistory: false,
encryptHistory: true,
props: { errors: {}, ...props },
}}
/>,
);
}
const props: ComponentProps<typeof Review> = {
actorId: 1,
tenantId: 1,
canReview: true,
currentVerified: true,
current: null,
history: { data: [], prev_page_url: null, next_page_url: null },
source: {
cycle: 1,
outcome: 'expired',
fingerprint: 'a'.repeat(64),
closed_at: '2026-11-27T12:00:00Z',
request: {
id: 3,
number: 'REQ-QA',
justification: 'Necessidade original <script>de teste</script>',
total_minor: '9007199254740993',
},
items: [
{
id: 1,
description: 'Material original',
quantity: '1.000',
unit: 'un',
total_minor: '9007199254740993',
},
],
steps: [
{
id: 1,
role: 'department_head',
decision: 'pending',
comment: null,
},
],
},
};
test('expired cycle review distinguishes its original values from a later preparation and escapes source text', () => {
const html = render(Review, props);
expect(html).toContain('90.071.992.547.409,93 MZN');
expect(html).toContain('Estes dados pertencem ao ciclo expirado');
expect(html).toContain('Sem decisão antes da conclusão do ciclo');
expect(html).toContain('&lt;script&gt;de teste&lt;/script&gt;');
expect(html).toContain('Registar revisão posterior');
expect(html).not.toContain('Aprovar');
});
test('unverified historical review is identified without offering a new approval or review command', () => {
const html = render(Review, {
...props,
canReview: false,
currentVerified: false,
current: {
id: 7,
version: 1,
data: { notes: 'Texto sintético preservado' },
snapshot: { fingerprint: 'a'.repeat(64) },
},
});
expect(html).toContain('não é apresentado como revisto');
expect(html).toContain('Texto sintético preservado');
expect(html).not.toContain('<form');
});
test('review queue keeps coverage and its own pagination while profile designation remains explicit', () => {
const html = render(Queue, {
coverage: { pending: 1, reviewed: 2, indeterminate: 1 },
state: 'pending',
canReview: false,
canConfigure: true,
records: {
data: [
{
key: '3:1',
number: 'REQ-QA',
cycle: 1,
outcome: 'expired',
status: 'pending',
closed_at: '2026-11-27T12:00:00Z',
href: '/requisicoes/3/ciclos/1/revisao-urgencia',
},
],
total: 21,
current_page: 1,
last_page: 2,
},
});
expect(html).toContain('Origem por conferir');
expect(html).toContain(
'/requisicoes/urgencias/revisoes?state=pending&amp;page=2',
);
expect(html).toContain('Expirada e devolvida ao requisitante');
const settings = render(Policy, {
actorId: 1,
tenantId: 1,
current: null,
profiles: [],
history: { data: [], prev_page_url: null, next_page_url: null },
});
expect(settings).toContain('não concede permissões');
expect(settings).toContain('incluindo rejeição ou expiração');
expect(settings).toContain('Configure os perfis da empresa');
});