import crypto from 'node:crypto'; import { createNativeInertiaClient } from './lib/native-inertia-client.mjs'; /** Same 100 MZN illustrative office scenario as the native Pest journey, through real HTTP sessions. */ export async function verifyOfficePurchaseHttp(origin, fixture, readState, progress) { const office = fixture.office_journey; if (!office || fixture.synthetic_only !== true || typeof readState !== 'function') throw Error('Dedicated synthetic office HTTP fixture required'); let checks = 0; let commands = 0; let phase = 'login'; const check = (condition, label) => { if (!condition) throw Error(`Office HTTP verification failed [${phase}]: ${label}`); checks++; }; const stage = name => { phase = name; progress?.({ office_http_phase: name, checks }); }; const clients = {}; for (const [name, actor] of Object.entries(office.actors)) { clients[name] = createNativeInertiaClient(origin, check); await clients[name].login(actor.email); } const { owner, buyer, head, finance, reviewer, warehouse, procurement_reviewer: procurementReviewer } = clients; const state = async () => { const source = await readState(); if (source.budget !== null) { // The common balance contract takes a lock. Use its native authorised endpoint, never a second calculator. const page = await finance.page('/orcamentos', 'budgets/index'); const budget = page.props.budgets.find(row => Number(row.id) === Number(source.budget.id)); const fields = ['approved_total_minor', 'reinforced_minor', 'reserved_minor', 'committed_minor', 'consumed_minor', 'available_minor']; check(budget !== undefined && fields.every(field => Object.hasOwn(budget, field)), 'native authoritative budget balance fields'); const after = await readState(); check(after.financial_fingerprint === source.financial_fingerprint, 'native balance consultation has no financial effects'); after.budget.balance = Object.fromEntries(fields.map(field => [field, budget[field]])); return after; } return source; }; const post = async (client, route, data, expected = 302) => { commands++; return client.post(route, data, expected); }; const date = days => new Date(Date.parse(fixture.clock) + days * 86400000).toISOString().slice(0, 10); const roles = { department_head: head, procurement: buyer, finance: reviewer }; const awardRoles = { ...roles, procurement: procurementReviewer }; let selectorRefused = false; let current = await state(); check(current.request === null && current.budget === null && current.stock === null, 'dedicated purchase references are initially unused'); stage('budget'); check((await owner.request('/orcamentos')).status === 403, 'requester cannot read company budget data'); await post(finance, '/orcamentos', { cost_center_id: office.cost_center_id, year: Number(date(0).slice(0, 4)), kind: 'operating', includes_tax: true, amount: '1000.00', reason: 'Dotação exclusivamente sintética do percurso HTTP, sem valores reais' }); current = await state(); check(current.budget !== null && Number(current.budget.created_by) === office.actors.finance.id, 'native budget issuer'); await post(finance, `/orcamentos/${current.budget.id}/aprovar`, {}, 403); check((await state()).budget.approved_by === null, 'budget issuer cannot approve their own allocation'); await post(reviewer, `/orcamentos/${current.budget.id}/aprovar`, {}); current = await state(); check(Number(current.budget.approved_by) === office.actors.reviewer.id && Number(current.budget.balance.available_minor) === 100000, 'independent native budget approval'); stage('request_and_accounts'); await post(owner, '/requisicoes', { operation_key: crypto.randomUUID(), cost_center_id: office.cost_center_id, priority: 'normal', needed_by: date(7), justification: 'Compra HTTP exclusivamente sintética; taxa ilustrativa zero, sem regra fiscal real', items: [{ description: 'Material de escritório HTTP QA', category: office.category, purchase_type: 'consumable', production_area: null, quantity: '1.000', unit: 'un', unit_price: '100.00', tax_rate: '0.00', procurement_category: 'office_equipment', category_reason: 'Aquisição de escritório exclusivamente sintética para testar o percurso HTTP' }] }); current = await state(); const requestId = current.request.id; const lineId = current.request.items[0].id; let capital = null; if (office.capital_register) { await post(buyer, '/projectos-imobilizado', { operation_key: crypto.randomUUID(), record_key: null, version: 0, type: 'project', code: office.capital_register.code, name: 'Projecto exclusivamente sintético do percurso HTTP', department_id: office.capital_register.department_id, equipment_id: null, reference: 'Origem documental fictícia de ensaio', state: 'active', reason: 'Cadastro próprio de Compras para conferir rastreabilidade sem dados reais' }); const register = await buyer.page('/projectos-imobilizado', 'equipment/capital-register'); capital = register.props.records.data.find(row => row.data.code === office.capital_register.code); check(capital !== undefined && capital.version === 1, 'own project created through native HTTP'); const choices = await owner.page(`/requisicoes/${requestId}/projectos-imobilizado`, 'requisitions/capital-assignments'); check(choices.props.canWrite && choices.props.choices.data.some(row => row.id === capital.id), 'request owner sees the native capital destination'); await post(owner, `/requisicoes/${requestId}/projectos-imobilizado`, { operation_key: crypto.randomUUID(), version: 0, item_id: lineId, capital_id: capital.id, reason: 'Destino explícito da linha para o projecto estritamente sintético' }); check((await owner.request('/projectos-imobilizado')).status === 403, 'assignment visibility does not grant the requester access to the register'); } const accountPage = await owner.page(`/requisicoes/${requestId}/contas`, 'requisitions/accounts'); const account = accountPage.props.accounts.data[0]; check(account !== undefined, 'actual common movement account available'); await post(owner, `/requisicoes/${requestId}/contas`, { operation_key: crypto.randomUUID(), version: 0, item_id: lineId, basis_hash: accountPage.props.items[0].basis_hash, reason: 'Imputação documental explícita na base própria do percurso HTTP QA', allocations: [{ account_id: account.id, source_hash: account.source_hash, subtotal: '100.00', total: '100.00' }] }); current = await state(); const submit = { operation_key: crypto.randomUUID(), process_version: current.request.process_version }; await post(owner, `/requisicoes/${requestId}/submeter`, submit); await post(owner, `/requisicoes/${requestId}/submeter`, submit); current = await state(); check(current.request.status === 'pending' && Number(current.budget.balance.reserved_minor) === 10000, 'submission replay preserves one native reserve'); await post(owner, `/requisicoes/${requestId}/decidir`, { operation_key: crypto.randomUUID(), process_version: current.request.process_version, decision: 'approved', comment: 'Tentativa própria exclusivamente sintética, que deve ser recusada' }, 403); for (let level = 0; current.request.status === 'pending' && level < 8; level++) { const step = current.request.steps.find(s => s.decision === 'pending'); check(step !== undefined && roles[step.role] !== undefined, 'frozen request level has a native eligible actor'); await post(roles[step.role], `/requisicoes/${requestId}/decidir`, { operation_key: crypto.randomUUID(), process_version: current.request.process_version, decision: 'approved', comment: 'Conferência independente do pedido HTTP exclusivamente sintético' }); current = await state(); } check(current.request.status === 'approved', 'native request circuit completed'); stage('suppliers_and_quotes'); for (let index = 0; index < 3; index++) { const nuit = String(300000001 + index); await post(buyer, '/fornecedores', { name: `Fornecedor HTTP QA ${index + 1}`, nuit, contact: 'Contacto sintético', email: `office-http-${index}@example.invalid`, phone: '123456789', address: 'Morada exclusivamente sintética', category: office.category, beneficiaries: 'Beneficiário exclusivamente sintético', document_references: 'Referências fictícias de ensaio', diligence_notes: 'Preparação de dados sintéticos sem fornecedor real', blocked: false, next_review: date(365) }); current = await state(); const supplier = current.suppliers.find(s => s.nuit === nuit); check(supplier !== undefined, 'native supplier created'); await post(finance, `/fornecedores/${supplier.id}/validar`, { version: supplier.version, status: 'active', comment: 'Conferência financeira independente de dados exclusivamente sintéticos' }); await post(buyer, `/requisicoes/${requestId}/cotacoes`, { currency: 'MZN', supplier_id: supplier.id, reference: `HTTP-OFFICE-QUOTE-${index + 1}`, delivery_days: 5, valid_until: date(30), payment_terms: 'Condições exclusivamente sintéticas de trinta dias', no_conflict: true, items: [{ requisition_item_id: lineId, unit_price: `${100 + index * 10}.00`, discount_type: 'none', discount_value: '0.00' }] }); current = await state(); const quote = current.quotes.find(q => q.supplier_id === supplier.id); check(quote !== undefined, 'native quote created'); for (const evaluator of [head, reviewer]) await post(evaluator, `/cotacoes/${quote.id}/avaliar`, { quality: '5', history: '5', payment: '5', comment: 'Avaliação independente exclusivamente sintética do percurso HTTP', no_conflict: true }); } current = await state(); check(current.quotes.length === 3 && Number(current.quotes[0].total_minor) === 10000, 'three independently evaluated native quotations'); stage('award_and_order'); await post(buyer, `/requisicoes/${requestId}/adjudicacao`, { quotation_id: current.quotes[0].id, justification: 'Escolha exclusivamente sintética da proposta com maior pontuação pelo circuito nativo', delivery_date: date(7), delivery_location: 'Armazém exclusivamente sintético de ensaio HTTP' }); current = await state(); const awardId = current.award.id; for (let level = 0; current.award.status !== 'approved' && level < 8; level++) { const step = current.award.steps.find(s => s.decision === 'pending'); check(step !== undefined && awardRoles[step.role] !== undefined, 'final-value level has a native eligible actor'); if (step.role === 'procurement') { await post(buyer, `/adjudicacoes/${awardId}/decidir`, { decision: 'approved', comment: 'Tentativa do próprio selector exclusivamente sintética, que deve ser recusada' }, 403); current = await state(); check(current.award.steps.find(row => row.id === step.id)?.decision === 'pending', 'selector refusal preserves the pending independent decision'); selectorRefused = true; } await post(awardRoles[step.role], `/adjudicacoes/${awardId}/decidir`, { decision: 'approved', comment: 'Conferência independente do valor final exclusivamente sintético HTTP' }); current = await state(); } check(current.award.status === 'approved' && selectorRefused, 'native final-value approvals completed by an independent buyer'); await post(buyer, `/adjudicacoes/${awardId}/emitir`, {}); current = await state(); const orderId = current.order.id; const orderLineId = current.order.items[0].id; const issued = current.financial_fingerprint; await post(buyer, `/adjudicacoes/${awardId}/emitir`, {}); current = await state(); check(current.order.id === orderId && current.financial_fingerprint === issued, 'order replay has no financial or document effect'); check(Number(current.order.total_minor) === 10000 && current.order.account_assignments[lineId].data.allocations[0].account.id === account.id, 'order preserves exact amount and native chart attribution'); check(current.order.budget_checked === true, 'new order preserves the budget authority confirmation already returned at issuance'); if (capital) check(current.order.capital_assignments[lineId].snapshot.source.record_key === capital.record_key && current.order.capital_assignments[lineId].snapshot.source.version === 1, 'issued order preserves the exact native project version'); const financialDocumentsHref = `/facturas?purchase_order_id=${orderId}#invoice-documents`; const financeOrder = await finance.page(`/ordens/${orderId}`, 'purchases/show'); check(financeOrder.props.financialDocumentsHref === financialDocumentsHref && financeOrder.props.relatedProcesses.some(source => source.id === requestId && source.href === `/requisicoes/${requestId}/processo`), 'order navigation preserves exact financial and process context'); const printRoute = `/ordens/${orderId}/imprimir`; const printHeaders = { 'X-Inertia': 'true', ...(financeOrder.version === null ? {} : { 'X-Inertia-Version': financeOrder.version }) }; const printNavigation = await finance.request(printRoute, { headers: printHeaders }); check(printNavigation.status === 409 && printNavigation.headers.get('x-inertia-location') === printRoute, 'authorised print navigation requests the complete HTML document'); const printDocument = await finance.request(printRoute); check(printDocument.status === 200 && (await printDocument.text()).includes('Controlo orçamental registado na emissão.'), 'native controlled print preserves the actual budget confirmation'); const privatePrint = await owner.request(printRoute, { headers: printHeaders }); check(privatePrint.status === 403 && !privatePrint.headers.has('x-inertia-location'), 'requester receives no print redirect without native order access'); const buyerOrder = await buyer.page(`/ordens/${orderId}`, 'purchases/show'); // This synthetic buyer also has Admin; use the independent Procurement-only reviewer to test redaction. const independentOrder = await procurementReviewer.page(`/ordens/${orderId}`, 'purchases/show'); check(buyerOrder.props.financialDocumentsHref === financialDocumentsHref && independentOrder.props.financialDocumentsHref === null, 'order financial link follows native Admin/Finance access without Procurement inheritance'); stage('receipt_and_invoice'); const financeReceipt = await finance.page(`/ordens/${orderId}/recepcoes`, 'receipts/order'); const warehouseReceipt = await warehouse.page(`/ordens/${orderId}/recepcoes`, 'receipts/order'); check(financeReceipt.props.financialDocumentsHref === financialDocumentsHref && warehouseReceipt.props.financialDocumentsHref === null, 'receipt navigation exposes financial context only to the native reader'); await post(warehouse, '/stock/artigos', { code: 'HTTP-OFFICE-QA', name: 'Material de escritório HTTP QA', unit: 'un' }); current = await state(); const receipt = { idempotency_key: crypto.randomUUID(), delivery_note: 'HTTP-OFFICE-DELIVERY-QA', received_on: date(0), warehouse_id: office.warehouse_id, items: [{ purchase_order_item_id: orderLineId, received_quantity: '1.000', accepted_quantity: '1.000', quality_status: 'compliant', stock_item_id: current.stock.id }] }; await post(warehouse, `/ordens/${orderId}/recepcoes`, receipt, 201); current = await state(); const received = current.financial_fingerprint; const confirmedReceiptId = current.order.receipts[0].id; const financialReceiptDetail = await finance.page(`/recepcoes/${confirmedReceiptId}`, 'receipts/show'); const warehouseReceiptDetail = await warehouse.page(`/recepcoes/${confirmedReceiptId}`, 'receipts/show'); check(financialReceiptDetail.props.financialDocumentsHref === financialDocumentsHref && warehouseReceiptDetail.props.financialDocumentsHref === null, 'confirmed receipt detail offers the exact financial context only to its native reader'); current = await state(); check(current.financial_fingerprint === received, 'receipt detail consultation preserves financial and stock sources'); await post(warehouse, `/ordens/${orderId}/recepcoes`, receipt, 200); current = await state(); check(current.financial_fingerprint === received && current.order.receipts.length === 1 && current.stock.movements === 1 && current.stock.quantity_milli === 1000, 'receipt replay preserves one physical movement'); await post(finance, `/ordens/${orderId}/facturas`, { number: 'HTTP-OFFICE-INVOICE-QA', issued_on: date(0), subtotal: '100.00', tax: '0.00', total: '100.00', items: [{ purchase_order_item_id: orderLineId, quantity: '1.000', unit: 'un', unit_price: '100.00', tax_rate: '0.00' }] }); current = await state(); const invoiceId = current.invoice.id; await post(finance, `/facturas/${invoiceId}/validar`, {}, 403); current = await state(); check(current.invoice.status === 'pending', 'invoice author cannot validate their own invoice'); await post(reviewer, `/facturas/${invoiceId}/validar`, {}); current = await state(); check(current.invoice.status === 'validated' && Number(current.budget.balance.consumed_minor) === 10000 && Number(current.budget.balance.available_minor) === 90000, 'native invoice validation consumes the exact commitment'); const consumedBudget = JSON.stringify(current.budget.balance); stage('bank_and_partial_payment'); const supplierId = current.quotes[0].supplier_id; await post(buyer, `/fornecedores/${supplierId}/dados-bancarios`, { account_key: crypto.randomUUID(), previous_id: 0, bank_name: 'Banco exclusivamente sintético HTTP QA', country: 'MZ', currency: 'MZN', beneficiary: 'Titular exclusivamente sintético', account_identifier: 'HTTP-OFFICE-ACCOUNT-QA', evidence_reference: 'Evidência bancária fictícia para o ensaio HTTP', reason: 'Preparação de conta fictícia sem operação bancária real' }); current = await state(); const bankId = current.bank.id; for (const bankReviewer of [finance, reviewer]) await post(bankReviewer, `/fornecedores/${supplierId}/dados-bancarios/${bankId}/validar`, { decision: 'approved', independently_verified: true, reason: 'Conferência independente de evidência exclusivamente sintética HTTP' }); current = await state(); check(current.bank.approved_reviews === 2, 'two independent native bank reviews'); const payment = { supplier_bank_detail_id: bankId, amount: '40.00', paid_on: date(0), external_reference: 'HTTP-OFFICE-PARTIAL-QA', evidence_reference: 'Registo exclusivamente sintético de pagamento externo parcial, sem execução bancária' }; await post(finance, `/facturas/${invoiceId}/pagamentos`, payment); current = await state(); const paymentId = current.payments[0].id; const reviewPage = await reviewer.page(`/pagamentos?payment_id=${paymentId}`, 'payments/index'); check(reviewPage.props.payments.data[0].canReview === true && reviewPage.props.focusPaymentId === paymentId, 'independent native payment review workspace'); const registrationPage = await finance.page(`/pagamentos?invoice_id=${invoiceId}`, 'payments/index'); check(registrationPage.props.focusInvoiceId === invoiceId && registrationPage.props.invoices[0].outstanding_minor === 10000, 'native payment registration workspace uses the authoritative invoice balance'); const pending = current.financial_fingerprint; await post(finance, `/facturas/${invoiceId}/pagamentos`, payment); current = await state(); check(current.payments.length === 1 && current.financial_fingerprint === pending, 'payment registration replay has no financial effect'); await post(finance, `/pagamentos/${paymentId}/conferir`, { decision: 'confirmed', independently_verified: true, reason: 'Tentativa própria exclusivamente sintética que deve ser recusada' }, 403); check((await reviewer.request(`/pagamentos/${paymentId}/categorias`)).status === 409, 'unconfirmed payment cannot be attributed to expense categories'); await post(reviewer, `/pagamentos/${paymentId}/conferir`, { decision: 'confirmed', independently_verified: true, reason: 'Conferência independente de evidência fictícia de pagamento parcial' }); current = await state(); check(current.payments[0].status === 'confirmed' && current.invoice.outstanding_minor === 6000, 'confirmed partial payment preserves the exact outstanding amount'); const overpay = await post(finance, `/facturas/${invoiceId}/pagamentos`, { ...payment, amount: '60.01', external_reference: 'HTTP-OFFICE-OVERPAY-QA' }, 422); check(Object.hasOwn((await overpay.json()).errors ?? {}, 'payment'), 'overpayment is refused by the native financial rule'); const attribute = async (id, amount) => { const page = await reviewer.page(`/pagamentos/${id}/categorias`, 'payments/expense-allocation'); const before = (await state()).financial_fingerprint; const data = { operation_key: crypto.randomUUID(), version: page.props.current?.version ?? 0, fingerprint: page.props.fingerprint, reason: 'Imputação explícita de Finanças de pagamento exclusivamente sintético HTTP', allocations: [{ category: office.category, amount }] }; await post(reviewer, `/pagamentos/${id}/categorias`, data); await post(reviewer, `/pagamentos/${id}/categorias`, data); check((await state()).financial_fingerprint === before, 'explicit attribution and its replay never change financial or stock sources'); }; await attribute(paymentId, '40.00'); stage('settlement_and_privacy'); await post(finance, `/facturas/${invoiceId}/pagamentos`, { ...payment, amount: '60.00', external_reference: 'HTTP-OFFICE-FINAL-QA' }); current = await state(); const finalPaymentId = current.payments.find(p => p.id !== paymentId).id; await post(reviewer, `/pagamentos/${finalPaymentId}/conferir`, { decision: 'confirmed', independently_verified: true, reason: 'Conferência independente do saldo exclusivamente sintético HTTP' }); await attribute(finalPaymentId, '60.00'); current = await state(); check(current.invoice.outstanding_minor === 0 && current.payments.length === 2 && current.payments.every(p => p.status === 'confirmed'), 'two independently confirmed payments settle exactly 100 MZN'); check(String(current.analytics.currencies[0].amount_minor) === '10000' && current.analytics.coverage.confirmed_payments === 2 && String(current.analytics.category_attribution.groups.data[0].amount_minor) === '10000', 'native confirmed-payment analytics and explicit category attribution agree'); check(JSON.stringify(current.budget.balance) === consumedBudget && current.stock.quantity_milli === 1000 && current.stock.movements === 1 && current.journals === 0, 'settlement preserves budget consumption, stock and documentary chart boundary'); const process = await owner.request(`/requisicoes/${requestId}/processo`, { headers: { 'X-Inertia': 'true' } }); check(process.status === 200, 'requester native process route'); const report = await process.json(); check(report.props.stages[7].state === 'restricted' && report.props.stages[8].state === 'restricted' && !Object.hasOwn(report.props, 'invoices') && !Object.hasOwn(report.props, 'payments') && !Object.hasOwn(report.props, 'bank_snapshot'), 'requester process does not disclose financial or bank records'); if (capital) { stage('project_trace'); const beforeTrace = current.financial_fingerprint; const trace = await finance.page(`/projectos-imobilizado?history=${capital.record_key}`, 'equipment/capital-register'); check(trace.props.trace.orders.data.some(row => row.order_id === orderId), 'project trace reaches its actual issued order'); check(trace.props.trace.receipts.data.some(row => row.order_id === orderId), 'project trace reaches its actual physical receipt'); check(trace.props.history.data[0].record_key === capital.record_key && trace.props.history.data[0].version === 1, 'project history remains its native version'); current = await state(); check(current.financial_fingerprint === beforeTrace, 'project trace consultation changes no financial or stock source'); } for (const client of Object.values(clients)) await client.logout(); return { checks, native_post_requests: commands, fortify_sessions: Object.keys(clients).length, request_id: requestId, order_id: orderId, invoice_id: invoiceId, payment_ids: current.payments.map(p => p.id), request_total_minor: current.request.total_minor, order_total_minor: current.order.total_minor, invoice_total_minor: current.invoice.total_minor, confirmed_payments_minor: current.payments.map(p => p.amount_minor), outstanding_minor: current.invoice.outstanding_minor, budget_consumed_minor: current.budget.balance.consumed_minor, budget_available_minor: current.budget.balance.available_minor, order_budget_checked: current.order.budget_checked, stock_quantity_milli: current.stock.quantity_milli, stock_movements: current.stock.movements, journals: current.journals, explicit_finance_category_total_minor: current.analytics.category_attribution.groups.data[0].amount_minor, all_business_mutations_via_native_http: true, assertions_use_readonly_transactions: true, budget_balance_via_native_http: true, selector_self_final_approval_refused: selectorRefused, synthetic_only: true, project_trace: capital ? { record_key: capital.record_key, code: capital.data.code, version: capital.version, order_id: orderId } : null, real_bank_or_sgf_operations: false, browser_visual_acceptance: false }; }