'use strict'; // O2C module pack UI (MOCK Oracle Fusion-style Order-to-Cash; NOT Oracle software; synthetic data only). // Page/label names follow the O2C case YAML steps; automation keeps the mapping in automation/src/modules/o2c/labels.ts. const S = require('./store'); const EXT = require('./extensions'); const { STATUS, LINE_STATUS, TRX_STATUS, RCPT_STATUS } = require('./rest'); const U = require('../../core/ui'); const { AppError } = require('../../core/errors'); const { esc, inp, sel, hid, btn, form, table, tr, money, dl, T, back, layout } = U; const page = (fn) => U.page(fn, 'o2c'); const act = (fn) => U.act(fn, 'o2c'); const guard = (role, action) => { if (!S.can(role, action)) throw new AppError(403, 'FORBIDDEN', `You are not authorized to access this page (persona ${role} lacks ${action}).`); }; const today = () => new Date().toISOString().slice(0, 10); const MEMO_LINES = ['ZZ Consulting Services (MOCK)', 'ZZ Support Fee (MOCK)']; const SOURCES_MANUAL = ['ZZ Manual (MOCK)']; const ACTIVITIES = ['ZZ Small Balance Adjustment (MOCK)']; const TASKS = [ ['Create Order', '/o2c/orders/new', (r) => S.can(r, 'order.create') && r !== 'integration_user'], ['Manage Orders', '/o2c/orders', (r) => ['order_entry', 'credit_manager'].includes(r)], ['Manage Credit Holds', '/o2c/credit-holds', (r) => S.can(r, 'credit.release')], ['Confirm Pick Slips', '/o2c/pick-slips', (r) => S.can(r, 'ship.pick')], ['Manage Shipments', '/o2c/shipments', (r) => S.can(r, 'ship.confirm')], ['Create Transaction', '/o2c/transactions/new', (r) => S.can(r, 'trx.create')], ['Manage Transactions', '/o2c/transactions', (r) => ['billing_specialist', 'ar_specialist', 'ar_manager'].includes(r)], ['Create Adjustment', '/o2c/adjustments/new', (r) => S.can(r, 'adj.create')], ['Approve Adjustments', '/o2c/adjustments', (r) => S.can(r, 'adj.approve')], ['Create Receipt', '/o2c/receipts/new', (r) => S.can(r, 'receipt.create')], ['Manage Receipts', '/o2c/receipts', (r) => ['ar_specialist', 'ar_manager'].includes(r)], ['Manage Customers', '/o2c/customers', (r) => S.can(r, 'customer.view')], ['Manage Credit Memo Requests', '/o2c/cmrs', (r) => S.can(r, 'cm.create') || S.can(r, 'cmr.approve')], ['Collections workbench', '/o2c/collections', (r) => S.can(r, 'collections')], ['Manage Price Lists', '/o2c/pricing/price-lists', (r) => S.can(r, 'pricing.admin')], ['Manage Pricing Strategies', '/o2c/pricing/strategies', (r) => S.can(r, 'pricing.admin')], ]; const chk = (name, label) => ``; const custOpts = (role) => S.list('customers').filter((c) => S.buOk(role, c.bu) && c.status === 'ACTIVE').map((c) => c.name); const journal = (lines) => table('Journal Lines', ['Line', 'Side', 'Account Class', 'Amount'], lines.map((l) => tr([l.lineNum, l.side, esc(l.accountClass), money(l.amount)], `data-testid="journal-line"`)), 'journal-lines'); // Tabs are links with role="tab" (server-rendered; the selected tab's panel is the only one rendered). const tabs = (base, list, cur) => `
${list.map((t) => `${esc(t)}`).join(' ')}
`; const panel = (name, html) => `

${esc(name)}

${html}
`; // Actions menu:
with a summary acting as the button; menu items are links (?view=...). const actions = (base, items) => `
Actions
${items.map(([label, view]) => `${esc(label)}`).join('')}
`; const dialog = (name, html) => `

${esc(name)}

${html}
`; const TAX_CLASSES = () => [S.config().standardTaxClassification, S.config().exemptTaxClassification]; // Display text for status codes (PENDING_APPROVAL -> Pending Approval). const Tt = (s) => esc(String(s).toLowerCase().split('_').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ')); const none = (rows) => (rows.length ? '' : '

No results found.

'); function mount(app) { // ---------------- customers (O2C-SEC-005; bank accounts stored masked; ASSUMED SoD in store.js PERMS) app.get('/o2c/customers', page((req, role) => { guard(role, 'customer.view'); const q = req.query.name || ''; const rows = req.query.name !== undefined ? S.customersFor(role, q) : []; return layout(req, role, 'Manage Customers', (S.can(role, 'customer.create') ? `Create` : '') + form('/o2c/customers', inp('name', 'Organization Name', { value: q }) + btn('Search'), 'get') + (req.query.name !== undefined ? table('Customers', ['Organization Name', 'Account Number', 'Business Unit', 'Status'], rows.map((c) => tr([`${esc(c.name)}`, esc(c.accountNumber), esc(c.bu), Tt(c.status)]))) + none(rows) : '')); })); app.get('/o2c/customers/new', page((req, role) => { guard(role, 'customer.create'); return layout(req, role, 'Create Customer', form('/o2c/customers/new', inp('name', 'Organization Name') + inp('accountNumber', 'Account Number') + inp('addressLine1', 'Address Line 1') + `
Site Purposes${chk('billTo', 'Bill-to')} ${chk('shipTo', 'Ship-to')}
` + back('/o2c/customers/new') + btn('Save and Close'))); })); app.post('/o2c/customers/new', act((req, role) => { const c = S.createCustomer(role, req.body); return [`/o2c/customers?name=${encodeURIComponent(c.name)}`, `Customer ${c.name} created: account ${c.accountNumber}, site uses ${c.siteUses.map((u) => (u === 'BILL_TO' ? 'Bill-to' : 'Ship-to')).join(', ')}.`]; })); app.post('/o2c/customers/:id/payment', act((req, role) => { const c = S.setPaymentDetails(role, req.params.id, req.body); return [`/o2c/customers/${c.id}?tab=Payment%20Details`, `Payment details saved: terms ${c.paymentTerms}, receipt method ${c.receiptMethod || 'none'}.`]; })); app.get('/o2c/customers/:id', page((req, role) => { guard(role, 'customer.view'); const c = S.customersFor(role).find((x) => x.id === req.params.id); if (!c) throw new AppError(404, 'NOT_FOUND', `Customer ${req.params.id} not found.`); const base = `/o2c/customers/${c.id}`; const edit = S.can(role, 'customer.bank.edit'); const cur = req.query.tab; return layout(req, role, `Customer ${c.name}`, dl([['Organization Name', esc(c.name), 'o2c-cust-name'], ['Account Number', esc(c.accountNumber), 'o2c-cust-account']]) + tabs(base, ['Payment Details'], cur) + (cur === 'Payment Details' ? panel('Payment Details', dl([['Payment Terms', esc(c.paymentTerms), 'o2c-cust-terms'], ['Receipt Method', esc(c.receiptMethod || ''), 'o2c-cust-receipt-method']]) + (edit ? form(`${base}/payment`, sel('paymentTerms', 'Payment Terms', S.config().paymentTermsList, { value: c.paymentTerms }) + sel('receiptMethod', 'Receipt Method', ['', ...S.RECEIPT_METHODS, S.config().cardReceiptMethod], { value: c.receiptMethod || '' }) + btn('Save and Close')) : '') + table('Cards', ['Card Number', 'Token'], (c.cards || []).map((k) => tr([`************${esc(k.last4)}`, esc(k.token)])), 'cust-cards') + table('Bank Accounts', ['Bank', 'Account Number', 'Currency', 'Primary'], c.bankAccounts.map((a) => tr([esc(a.bank), esc(a.accountMasked), esc(a.currency), a.primary ? 'Yes' : 'No'])), 'cust-bank-accounts') + (edit ? (req.query.create ? dialog('Create Bank Account', form(`${base}/bank-accounts`, inp('bank', 'Bank') + inp('accountNumber', 'Account Number') + hid('__back', base) + btn('Save'))) : `Create`) : '')) : '')); })); app.post('/o2c/customers/:id/bank-accounts', act((req, role) => { const c = S.addCustomerBankAccount(role, req.params.id, req.body); return [`/o2c/customers/${c.id}?tab=Payment%20Details`, `Bank account ${c.bankAccounts[c.bankAccounts.length - 1].accountMasked} created.`]; })); // ---------------- orders app.get('/o2c/orders/new', page((req, role) => { guard(role, 'order.create'); return layout(req, role, 'Create Order', form('/o2c/orders/new', sel('customerName', 'Customer', custOpts(role)) + sel('bu', 'Business Unit', S.PERSONAS[role].bus) + inp('customerPO', 'Purchase Order') + EXT.PAGE_EXTENSIONS.map((f) => sel(f.field, f.label, ['', ...f.values])).join('') + inp('item', 'Search Item', { type: 'search' }) + inp('quantity', 'Quantity', { type: 'number' }) + back('/o2c/orders/new') + btn('Add'))); })); app.post('/o2c/orders/new', act((req, role) => { const b = req.body; const o = S.createOrder(role, { customerName: b.customerName, bu: b.bu, customerPO: b.customerPO, ...Object.fromEntries(EXT.PAGE_EXTENSIONS.map((f) => [f.field, b[f.field]])), lines: [{ item: b.item, quantity: b.quantity }] }); return [`/o2c/orders/${o.id}`, `Line added: item ${b.item}, quantity ${b.quantity}. Order ${o.number} saved as draft.`]; })); app.post('/o2c/orders/:id/lines', act((req, role) => { const o = S.addOrderLine(role, req.params.id, req.body); return [`/o2c/orders/${o.id}`, `Line added: item ${req.body.item}, quantity ${req.body.quantity}.`]; })); app.post('/o2c/orders/:id/submit', act((req, role) => { const o = S.submitOrder(role, req.params.id); return [`/o2c/orders/${o.id}`, `Order ${o.number} submitted. Status ${STATUS[o.status]}.`]; })); app.get('/o2c/orders/:id', page((req, role) => { guard(role, 'order.view'); const o = S.findOrder(role, req.params.id); const ln = req.query.line ? o.lines.find((l) => String(l.lineNum) === String(req.query.line)) : null; const draft = o.status === 'DRAFT' && S.can(role, 'order.create'); const base = `/o2c/orders/${o.id}`; const revising = req.query.revise && S.can(role, 'order.revise') && o.status === 'PROCESSING'; const view = req.query.view; const menu = [...(S.can(role, 'hold.apply') && o.status === 'PROCESSING' ? [['Apply Hold', 'apply-hold']] : []), ...(S.can(role, 'hold.release') && o.holds.some((h) => h.active && h.code === 'MANUAL') ? [['Release Hold', 'release-hold']] : [])]; return layout(req, role, `Order ${o.number}`, dl([['Order', esc(o.number), 'o2c-order-number'], ['Status', STATUS[o.status], 'o2c-order-status'], ['Business Unit', esc(o.bu)], ['Customer', esc(o.customerName), 'o2c-order-customer'], ['Bill-to Site', esc(o.billToSite), 'o2c-bill-to'], ['Ship-to Site', esc(o.shipToSite), 'o2c-ship-to'], ['Purchase Order', esc(o.customerPO)], ['Shipping Instructions', esc(o.shippingInstructions || ''), 'o2c-ship-instructions'], ...EXT.PAGE_EXTENSIONS.map((f) => [f.label, esc((o.ext || {})[f.field] || ''), `o2c-ext-${f.field}`]), ['Subtotal', money(o.subtotal), 'o2c-order-subtotal'], ['Estimated Tax', money(o.tax), 'o2c-order-tax'], ['Total', money(o.total), 'o2c-order-total'], ['Version', String((o.revision || 0) + 1), 'o2c-order-version']]) + (S.can(role, 'order.revise') && o.status === 'PROCESSING' && !revising && o.lines.some((l) => l.status === 'AWAITING_SHIPPING') ? `Revise` : '') + (revising ? `

Revising order ${esc(o.number)}: version ${(o.revision || 0) + 2}.

` : '') + (menu.length ? actions(base, menu) : '') + (view === 'apply-hold' && S.can(role, 'hold.apply') ? dialog('Apply Hold', form(`${base}/hold`, sel('holdName', 'Hold Name', S.config().manualHolds) + inp('comments', 'Comments') + btn('OK'))) : '') + (view === 'release-hold' && S.can(role, 'hold.release') ? dialog('Release Hold', form(`${base}/release-hold`, inp('comments', 'Comments') + btn('OK'))) : '') + table('Order Lines', ['Line', 'Item', 'Quantity', 'Unit List Price', 'Discount', 'Unit Selling Price', 'Extended Amount', 'Status', 'Fulfilled'], o.lines.map((l) => tr([`Line ${l.lineNum}`, esc(l.item), l.quantity, money(l.listPrice), money(l.discountPerUnit), money(l.unitSellingPrice), money(l.extendedAmount), LINE_STATUS[l.status], l.fulfilledQty], `data-testid="order-line-${l.lineNum}"`)), 'order-lines') + (ln && revising ? `
Revise Line ${ln.lineNum}${form(`${base}/revise`, hid('line', ln.lineNum) + inp('quantity', 'Quantity', { type: 'number', value: ln.quantity }) + btn('Submit'))}
` : '') + (ln && !revising ? `

Line ${ln.lineNum}

${tabs(`/o2c/orders/${o.id}?line=${ln.lineNum}`, ['Pricing', 'Tax'], req.query.tab)}` + (req.query.tab === 'Pricing' ? panel('Pricing', table('Price Breakdown', ['Component', 'Amount', 'Rule'], [tr(['List Price', money(ln.listPrice), '']), tr(['Discount', money(-ln.discountPerUnit), esc(ln.discountRule || '')]), tr(['Net Price', money(ln.unitSellingPrice), ''])], 'price-breakdown') + (ln.overridePct !== undefined ? dl([['Override Below Net', `${ln.overridePct.toFixed(2)}%`, 'o2c-line-override-pct'], ['Price Approval', ln.priceApprovalRequired ? 'Required' : 'Not Required', 'o2c-line-price-approval']]) : '') + (draft ? (req.query.override ? dialog('Override Price', form(`${base}/lines/${ln.lineNum}/price`, inp('price', 'Unit Selling Price') + btn('OK'))) : `Override Price`) : '')) : '') + (req.query.tab === 'Tax' ? panel('Tax', table('Line Tax', ['Tax Classification', 'Tax Rate Code', 'Tax Rate', 'Taxable Amount', 'Tax Amount', 'Jurisdiction'], [tr([esc(ln.taxClassification), esc(ln.taxRateCode), `${ln.taxRatePct}%`, money(ln.extendedAmount), money(ln.tax), esc(ln.shipToJurisdiction)])], 'line-tax') + (S.can(role, 'order.create') && ln.billedQty === 0 ? (req.query.edit ? dialog('Edit Tax', form(`/o2c/orders/${o.id}/lines/${ln.lineNum}/tax`, sel('taxClassification', 'Tax Classification', TAX_CLASSES()) + btn('OK'))) : `Edit Tax`) : '')) : '') + '
' : '') + tabs(`/o2c/orders/${o.id}`, ['Fulfillment'], req.query.tab) + (req.query.tab === 'Fulfillment' ? panel('Fulfillment', table('Fulfillment Lines', ['Line', 'Item', 'Quantity', 'Orchestration Process', 'Requested Ship Date', 'Scheduled Ship Date', 'Ship-from Organization', 'Backordered', 'Status'], o.lines.map((l) => tr([l.lineNum, esc(l.item), l.quantity, esc(l.orchestrationProcess), esc(l.requestedShipDate || ''), esc(l.scheduledShipDate || ''), esc(l.shipFromOrg || ''), l.backordered ? 'Yes' : 'No', LINE_STATUS[l.status]])), 'fulfillment-lines')) : '') + ((o.extensionLog || []).length ? table('Extension Log', ['Extension', 'Event', 'Message'], o.extensionLog.map((x) => tr([esc(x.extension), esc(x.event), esc(x.message)])), 'extension-log') : '') + (o.holds.length ? table('Holds', ['Hold', 'Active', 'Details'], o.holds.map((h) => tr([esc(h.name), h.active ? 'Yes' : 'No', esc(h.message)])), 'order-holds') : '') + (draft ? `
Add Line${form(`/o2c/orders/${o.id}/lines`, inp('item', 'Search Item', { type: 'search' }) + inp('quantity', 'Quantity', { type: 'number' }) + btn('Add'))}
${form(`/o2c/orders/${o.id}/submit`, btn('Submit'))}` : '')); })); app.post('/o2c/orders/:id/revise', act((req, role) => { const o = S.reviseOrder(role, req.params.id, req.body.line, req.body.quantity); const l = o.lines.find((x) => String(x.lineNum) === String(req.body.line)); return [`/o2c/orders/${o.id}`, `Revision submitted: order ${o.number} version ${o.revision + 1}, line ${l.lineNum} quantity ${l.quantity} x ${money(l.unitSellingPrice)} = ${money(l.extendedAmount)}; status ${STATUS[o.status]}.`]; })); app.post('/o2c/orders/:id/hold', act((req, role) => { const o = S.applyHold(role, req.params.id, req.body.holdName); return [`/o2c/orders/${o.id}`, `Hold ${req.body.holdName} applied to order ${o.number}; status ${STATUS[o.status]}.`]; })); app.post('/o2c/orders/:id/release-hold', act((req, role) => { const o = S.releaseManualHold(role, req.params.id, req.body.comments); return [`/o2c/orders/${o.id}`, `Hold released on order ${o.number}; status ${STATUS[o.status]}.`]; })); app.post('/o2c/orders/:id/lines/:n/price', act((req, role) => { const r = S.overridePrice(role, req.params.id, req.params.n, Number(req.body.price)); return [`/o2c/orders/${r.order.id}?line=${req.params.n}&tab=Pricing`, `Price override ${money(r.line.unitSellingPrice)} on line ${req.params.n} (${r.pct.toFixed(2)}% below ${money(r.line.listPrice * (1 - r.line.discountPct / 100))}): ${r.withinGuardrail ? 'within guardrail' : `exceeds the ${S.config().overrideGuardrailPct}% guardrail; pricing approval required`}.`]; })); app.post('/o2c/orders/:id/lines/:n/tax', act((req, role) => { const o = S.editLineTax(role, req.params.id, req.params.n, req.body.taxClassification); return [`/o2c/orders/${o.id}?line=${req.params.n}&tab=Tax`, `Line ${req.params.n} tax recalculated: ${money(o.lines.find((l) => String(l.lineNum) === req.params.n).tax)}; order total ${money(o.total)}.`]; })); app.get('/o2c/orders', page((req, role) => { guard(role, 'order.view'); const q = (req.query.order || '').trim(); const rows = q ? S.ordersFor(role).filter((o) => o.number === q) : S.ordersFor(role); return layout(req, role, 'Manage Orders', form('/o2c/orders', inp('order', 'Order', { value: q }) + btn('Search'), 'get') + table('Orders', ['Order', 'Customer', 'Status', 'Total'], rows.map((o) => tr([`${esc(o.number)}`, esc(o.customerName), STATUS[o.status], money(o.total)])), 'orders') + none(rows)); })); // ---------------- credit app.get('/o2c/credit-holds', page((req, role) => { guard(role, 'credit.release'); const q = (req.query.order || '').trim(); const rows = S.ordersFor(role).filter((o) => o.holds.some((h) => h.active && h.code === 'CREDIT_CHECK') && (!q || o.number === q)); return layout(req, role, 'Manage Credit Holds', form('/o2c/credit-holds', inp('order', 'Order', { value: q }) + btn('Search'), 'get') + table('Credit Holds', ['Order', 'Customer', 'Order Total', 'Reason', 'Over Limit By'], rows.map((o) => { const h = o.holds.find((x) => x.active); return tr([`${esc(o.number)}`, esc(o.customerName), money(o.total), esc(h.message), money(h.overBy)]); }), 'credit-holds') + none(rows)); })); app.get('/o2c/credit-holds/:id', page((req, role) => { guard(role, 'credit.release'); const o = S.findOrder(role, req.params.id); const h = o.holds.find((x) => x.code === 'CREDIT_CHECK'); return layout(req, role, `Credit Hold: Order ${o.number}`, dl([['Order', esc(o.number), 'o2c-order-number'], ['Status', STATUS[o.status], 'o2c-order-status'], ['Reason', esc(h ? h.message : '')], ['Over Limit By', money(h && h.overBy)]]) + (h && h.active ? (req.query.release ? dialog('Release Hold', form(`/o2c/credit-holds/${o.id}/release`, inp('comments', 'Comments') + btn('OK'))) : `Release Hold`) : '')); })); app.post('/o2c/credit-holds/:id/release', act((req, role) => { const o = S.releaseCreditHold(role, req.params.id, req.body.comments); return [`/o2c/credit-holds/${o.id}`, `Hold released on order ${o.number}.`]; })); // ---------------- shipping app.get('/o2c/pick-slips', page((req, role) => { guard(role, 'ship.pick'); const q = (req.query.pickSlip || '').trim(); const rows = S.list('pickSlips').filter((p) => !q || p.number === q); return layout(req, role, 'Confirm Pick Slips', form('/o2c/pick-slips', inp('pickSlip', 'Pick Slip', { value: q }) + btn('Search'), 'get') + table('Pick Slips', ['Pick Slip', 'Order', 'Item', 'Requested Quantity', 'Subinventory', 'Status', ''], rows.map((p) => tr([esc(p.number), esc(p.orderNumber), esc(p.lines.map((l) => l.item).join(', ')), p.lines.reduce((a, l) => a + l.quantity, 0), esc(p.lines[0].subinventory || ''), Tt(p.status), p.status === 'RELEASED' ? form(`/o2c/pick-slips/${p.number}/confirm`, (p.lines.length === 1 ? inp('pickedQuantity', 'Picked Quantity', { type: 'number', value: p.lines[0].quantity }) : '') + btn('Confirm')) : ''])), 'pick-slips') + none(rows)); })); app.post('/o2c/pick-slips/:number/confirm', act((req, role) => { const p = S.confirmPickSlip(role, req.params.number, req.body.pickedQuantity); return [`/o2c/pick-slips?pickSlip=${p.number}`, `Pick slip ${p.number} confirmed for quantity ${p.lines.reduce((a, l) => a + l.quantity, 0)}${p.backordered ? `; ${p.backordered} backordered` : ''}.`]; })); app.get('/o2c/shipments', page((req, role) => { guard(role, 'ship.confirm'); const q = (req.query.order || '').trim(); const rows = S.list('shipments').filter((s) => !q || s.orderNumber === q); return layout(req, role, 'Manage Shipments', form('/o2c/shipments', inp('order', 'Order', { value: q }) + btn('Search'), 'get') + table('Shipments', ['Shipment', 'Order', 'Pick Slip', 'Status'], rows.map((s) => tr([`${esc(s.number)}`, esc(s.orderNumber), esc(s.pickSlip), Tt(s.status)])), 'shipments') + none(rows)); })); app.get('/o2c/shipments/:id', page((req, role) => { guard(role, 'ship.confirm'); const s = S.list('shipments').find((x) => x.id === req.params.id); if (!s) throw new AppError(404, 'NOT_FOUND', 'Shipment not found.'); const o = S.findOrder(null, s.orderId); return layout(req, role, `Shipment ${s.number}`, dl([['Shipment', esc(s.number), 'o2c-shipment-number'], ['Status', Tt(s.status), 'o2c-shipment-status'], ['Order', esc(s.orderNumber)], ['Pick Slip', esc(s.pickSlip)], ['Ship-from Organization', esc(s.org)]]) + table('Shipment Lines', ['Line', 'Item', 'Quantity', 'Order Line Status'], s.lines.map((l) => tr([l.lineNum, esc(l.item), l.quantity, `${LINE_STATUS[o.lines.find((x) => x.lineNum === l.lineNum).status]}`]))) + (s.status === 'OPEN' ? form(`/o2c/shipments/${s.id}/confirm`, btn('Ship Confirm')) : '')); })); app.post('/o2c/shipments/:id/confirm', act((req, role) => { const s = S.shipConfirm(role, req.params.id); return [`/o2c/shipments/${s.id}`, `Shipment ${s.number} confirmed.`]; })); // ---------------- transactions const trxSearch = (req, role, title, base, extra = (i) => `${esc(i.number)}`) => { const n = (req.query.trx || '').trim(); const so = (req.query.salesOrder || '').trim(); const searched = !!(n || so); const rows = searched ? S.invoicesFor(role).filter((i) => (!n || i.number === n) && (!so || i.salesOrder === so)) : []; return form(base, inp('trx', 'Transaction Number', { value: n }) + inp('salesOrder', 'Sales Order', { value: so }) + btn('Search'), 'get') + table(title, ['Transaction', 'Customer', 'Sales Order', 'Status', 'Total', 'Balance Due'], rows.map((i) => tr([extra(i), esc(i.customerName), esc(i.salesOrder || ''), TRX_STATUS[i.status], money(i.total), money(i.balance)])), 'transactions') + (searched ? none(rows) : ''); }; app.get('/o2c/transactions', page((req, role) => { guard(role, 'trx.view'); return layout(req, role, 'Manage Transactions', trxSearch(req, role, 'Transactions', '/o2c/transactions')); })); app.get('/o2c/transactions/new', page((req, role) => { guard(role, 'trx.create'); // Rows start hidden; 'Add Row' reveals the next one (the only client-side script in the pack). Each row is a group named 'Line N'. const line = (n) => ``; const addRow = ``; return layout(req, role, 'Create Transaction', form('/o2c/transactions/new', sel('bu', 'Business Unit', S.PERSONAS[role].bus) + sel('source', 'Transaction Source', SOURCES_MANUAL) + sel('type', 'Transaction Type', ['Invoice']) + sel('customerName', 'Bill-to Name', custOpts(role)) + inp('trxDate', 'Transaction Date', { type: 'date', value: today() }) + sel('invoicingRule', 'Invoicing Rule', ['', ...S.config().invoicingRules]) + sel('revenueRule', 'Revenue Scheduling Rule', ['', ...Object.keys(S.config().revenueRules)]) + addRow + line(1) + line(2) + line(3) + back('/o2c/transactions/new') + btn('Complete and Close'))); })); app.post('/o2c/transactions/new', act((req, role) => { const b = req.body; const lines = [1, 2, 3].filter((n) => b[`memo${n}`] || b[`qty${n}`] || b[`price${n}`]).map((n) => ({ description: b[`memo${n}`], quantity: b[`qty${n}`], unitPrice: b[`price${n}`] })); const i = S.createManualInvoice(role, { bu: b.bu, source: b.source, type: b.type, customerName: b.customerName, trxDate: b.trxDate, lines, invoicingRule: b.invoicingRule || undefined, revenueRule: b.revenueRule || undefined }); return [`/o2c/transactions/${i.id}`, `Transaction ${i.number} completed.`]; })); app.get('/o2c/transactions/:id', page((req, role) => { guard(role, 'trx.view'); const i = S.findInvoice(role, req.params.id); const adjs = S.list('adjustments').filter((a) => a.invoiceId === i.id); const cms = S.list('creditMemos').filter((c) => c.creditedTransactionId === i.id); return layout(req, role, `Transaction ${i.number}`, dl([['Transaction Number', esc(i.number), 'o2c-trx-number'], ['Status', TRX_STATUS[i.status], 'o2c-trx-status'], ['Business Unit', esc(i.bu)], ['Bill-to Name', esc(i.customerName)], ['Ship-to Site', esc(i.shipToSite), 'o2c-trx-ship-to'], ['Transaction Source', esc(i.source)], ['Sales Order', esc(i.salesOrder || ''), 'o2c-trx-sales-order'], ['Transaction Date', esc(i.trxDate)], ['Payment Terms', esc(i.paymentTerms)], ['Due Date', esc(i.dueDate), 'o2c-trx-due-date'], ['Subtotal', money(i.subtotal), 'o2c-trx-subtotal'], ['Tax', money(i.tax), 'o2c-trx-tax'], ['Total', money(i.total), 'o2c-trx-total'], ['Balance Due', money(i.balance), 'o2c-trx-balance']]) + tabs(`/o2c/transactions/${i.id}`, ['Lines', 'Tax'], req.query.tab || 'Lines') + (req.query.tab === 'Tax' ? panel('Tax', table('Tax Lines', ['Tax Rate Code', 'Tax Rate', 'Taxable Amount', 'Tax Amount', 'Jurisdiction'], i.taxLines.map((t) => tr([esc(t.taxRateCode), `${t.ratePct}%`, money(t.taxable), money(t.amount), esc(t.jurisdiction)])), 'tax-lines')) : panel('Lines', table('Transaction Lines', ['Line', 'Description', 'Quantity', 'Unit Price', 'Amount'], i.lines.map((l) => tr([l.lineNum, esc(l.description || l.item), l.quantity, money(l.unitPrice), money(l.amount)])), 'trx-lines'))) + table('Adjustments', ['Adjustment', 'Activity', 'Amount', 'Status', 'Created By'], adjs.map((a) => tr([esc(a.number), esc(a.activity), money(a.amount), Tt(a.status), esc(a.createdBy)])), 'adjustments') + (cms.length ? table('Credit Memos', ['Credit Memo', 'Line Amount', 'Tax', 'Total'], cms.map((c) => tr([esc(c.number), money(c.subtotal), money(c.tax), money(c.total)])), 'credit-memos') : '') + (i.revenueSchedule ? table('Revenue Schedule', ['Period', 'Amount', 'Status'], i.revenueSchedule.map((r) => tr([esc(r.period), money(r.amount), r.status === 'EARNED' ? 'Earned' : 'Unearned'])), 'revenue-schedule') : '') + actions(`/o2c/transactions/${i.id}`, [['View Accounting', 'accounting'], ...(S.can(role, 'adj.create') && i.balance > 0 ? [['Create Adjustment', 'adjust']] : []), ...(S.can(role, 'cm.create') && i.balance > 0 ? [['Credit Transaction', 'credit']] : [])]) + (req.query.view === 'credit' && S.can(role, 'cm.create') ? dialog('Credit Transaction', form(`/o2c/transactions/${i.id}/credit`, sel('lineNum', 'Line', i.lines.map((l) => String(l.lineNum))) + inp('quantity', 'Quantity', { type: 'number' }) + btn('Complete and Close'))) : '') + (req.query.view === 'accounting' ? dialog('View Accounting', journal(S.accountingFor('Invoice', i.id))) : '') + (req.query.view === 'adjust' && S.can(role, 'adj.create') ? dialog('Create Adjustment', form(`/o2c/transactions/${i.id}/adjust`, sel('activity', 'Receivables Activity', ACTIVITIES) + inp('amount', 'Adjustment Amount') + btn('Submit'))) : '')); })); app.post('/o2c/transactions/:id/credit', act((req, role) => { const c = S.creditTransaction(role, req.params.id, { lineNum: req.body.lineNum, quantity: req.body.quantity }); const i = S.findInvoice(null, c.creditedTransactionId); return [`/o2c/transactions/${i.id}`, `Credit memo ${c.number} ${money(c.total)} (${money(c.subtotal)} line, ${money(c.tax)} tax) applied; transaction ${i.number} balance ${money(i.balance)}.`]; })); app.post('/o2c/transactions/:id/adjust', act((req, role) => { const a = S.createAdjustment(role, req.params.id, { activity: req.body.activity, amount: Number(req.body.amount) }); return [`/o2c/transactions/${a.invoiceId}`, `Adjustment ${a.number} status ${Tt(a.status)}.`]; })); app.get('/o2c/adjustments/new', page((req, role) => { guard(role, 'adj.create'); return layout(req, role, 'Create Adjustment', '

Find the transaction, then use Create Adjustment on it.

' + trxSearch(req, role, 'Transactions', '/o2c/adjustments/new')); })); app.get('/o2c/adjustments', page((req, role) => { guard(role, 'adj.approve'); const n = (req.query.trx || '').trim(); const rows = S.list('adjustments').filter((a) => a.status === 'PENDING_APPROVAL' && (!n || a.invoiceNumber === n) && S.buOk(role, S.findInvoice(null, a.invoiceId).bu)); return layout(req, role, 'Approve Adjustments', form('/o2c/adjustments', inp('trx', 'Transaction Number', { value: n }) + btn('Search'), 'get') + table('Pending Adjustments', ['Adjustment', 'Transaction', 'Activity', 'Amount', 'Created By', ''], rows.map((a) => tr([esc(a.number), esc(a.invoiceNumber), esc(a.activity), money(a.amount), esc(a.createdBy), form(`/o2c/adjustments/${a.id}/approve`, btn('Approve'))])), 'pending-adjustments') + none(rows)); })); app.post('/o2c/adjustments/:id/approve', act((req, role) => { const a = S.approveAdjustment(role, req.params.id); const i = S.findInvoice(null, a.invoiceId); return [`/o2c/adjustments?trx=${a.invoiceNumber}`, `Adjustment ${a.number} approved; transaction ${i.number} balance ${money(i.balance)}.`]; })); // ---------------- receipts app.get('/o2c/receipts/new', page((req, role) => { guard(role, 'receipt.create'); return layout(req, role, 'Create Receipt', form('/o2c/receipts/new', sel('bu', 'Business Unit', S.PERSONAS[role].bus) + sel('method', 'Receipt Method', S.RECEIPT_METHODS) + inp('number', 'Receipt Number') + inp('amount', 'Entered Amount') + sel('customerName', 'Customer Name', custOpts(role)) + inp('receiptDate', 'Receipt Date', { type: 'date', value: today() }) + back('/o2c/receipts/new') + btn('Save'))); })); app.post('/o2c/receipts/new', act((req, role) => { const b = req.body; const r = S.createReceipt(role, { bu: b.bu, method: b.method, number: b.number || undefined, amount: Number(b.amount), customerName: b.customerName, receiptDate: b.receiptDate }); return [`/o2c/receipts/${r.id}`, `Receipt ${r.number} saved, unapplied ${money(r.unapplied)}.`]; })); app.get('/o2c/receipts/:id', page((req, role) => { guard(role, 'receipt.view'); const r = S.findReceipt(role, req.params.id); const n = (req.query.trx || '').trim(); const so = (req.query.salesOrder || '').trim(); const open = req.query.apply ? S.invoicesFor(role).filter((i) => i.balance > 0 && i.customerId === r.customerId && (!n || i.number === n) && (!so || i.salesOrder === so)) : []; return layout(req, role, `Receipt ${r.number}`, dl([['Receipt Number', esc(r.number), 'o2c-rcpt-number'], ['Status', RCPT_STATUS[r.status], 'o2c-rcpt-status'], ['Customer Name', esc(r.customerName)], ['Receipt Method', esc(r.method)], ['Entered Amount', money(r.amount), 'o2c-rcpt-amount'], ['Unapplied Amount', money(r.unapplied), 'o2c-rcpt-unapplied']]) + table('Applications', ['Transaction', 'Applied Amount'], r.applications.map((a) => tr([esc(a.invoiceNumber), money(a.amount)])), 'applications') + (S.can(role, 'receipt.create') && r.unapplied > 0 ? (req.query.apply ? `
Add Open Receivables${form(`/o2c/receipts/${r.id}`, hid('apply', '1') + inp('trx', 'Transaction Number', { value: n }) + inp('salesOrder', 'Sales Order', { value: so }) + btn('Search'), 'get')} ${table('Open Receivables', ['Transaction', 'Sales Order', 'Balance Due', ''], open.map((i) => tr([esc(i.number), esc(i.salesOrder || ''), money(i.balance), form(`/o2c/receipts/${r.id}/apply`, hid('invoiceId', i.id) + inp('amount', 'Applied Amount', { value: Math.min(i.balance, r.unapplied).toFixed(2) }) + btn('Add'))], `aria-label="${esc(i.number)}"`)), 'open-receivables')}
` : form(`/o2c/receipts/${r.id}`, hid('apply', '1') + btn('Add Open Receivables'), 'get')) : '') + (S.can(role, 'receipt.create') && r.unapplied > 0 && !req.query.apply ? (req.query.onAccount ? dialog('Apply On Account', form(`/o2c/receipts/${r.id}/on-account`, inp('amount', 'Applied Amount', { value: r.unapplied.toFixed(2) }) + btn('OK'))) : form(`/o2c/receipts/${r.id}`, hid('onAccount', '1') + btn('Apply On Account'), 'get')) : '') + (r.onAccount ? dl([['On-Account Amount', money(r.onAccount), 'o2c-rcpt-on-account']]) : '') + (S.can(role, 'receipt.create') ? form(`/o2c/receipts/${r.id}/close`, btn('Save and Close')) : '') + actions(`/o2c/receipts/${r.id}`, [['View Accounting', 'accounting']]) + (req.query.view === 'accounting' ? dialog('View Accounting', journal(S.accountingFor('Receipt', r.id))) : '')); })); app.post('/o2c/receipts/:id/apply', act((req, role) => { const r = S.applyReceipt(role, req.params.id, req.body.invoiceId, req.body.amount !== undefined && req.body.amount !== '' ? Number(req.body.amount) : undefined); const a = r.applications[r.applications.length - 1]; return [`/o2c/receipts/${r.id}`, `Applied ${money(a.amount)} to ${a.invoiceNumber}; unapplied ${money(r.unapplied)}.`]; })); app.post('/o2c/receipts/:id/on-account', act((req, role) => { const r = S.applyOnAccount(role, req.params.id, Number(req.body.amount)); return [`/o2c/receipts/${r.id}`, `On-account ${money(r.onAccount)}; unapplied ${money(r.unapplied)}.`]; })); app.post('/o2c/receipts/:id/close', act((req, role) => { const r = S.findReceipt(role, req.params.id); return [`/o2c/receipts?receipt=${encodeURIComponent(r.number)}`, `Receipt ${r.number} saved: applied ${money(r.amount - r.unapplied)}, unapplied ${money(r.unapplied)}.`]; })); app.get('/o2c/receipts', page((req, role) => { guard(role, 'receipt.view'); const q = (req.query.receipt || '').trim(); const rows = S.list('receipts').filter((r) => S.buOk(role, r.bu) && (!q || r.number === q)); return layout(req, role, 'Manage Receipts', form('/o2c/receipts', inp('receipt', 'Receipt Number', { value: q }) + btn('Search'), 'get') + table('Receipts', ['Receipt Number', 'Customer', 'Amount', 'Unapplied', 'Status'], rows.map((r) => tr([`${esc(r.number)}`, esc(r.customerName), money(r.amount), money(r.unapplied), RCPT_STATUS[r.status]])), 'receipts') + none(rows)); })); // ---------------- credit memo requests (O2C-CM-004; threshold ASSUMED) app.get('/o2c/cmrs', page((req, role) => { if (!S.can(role, 'cm.create') && !S.can(role, 'cmr.approve')) guard(role, 'cm.create'); const rows = S.list('cmrs'); return layout(req, role, 'Manage Credit Memo Requests', (S.can(role, 'cm.create') ? (req.query.create ? `
Create Credit Memo Request${form('/o2c/cmrs', inp('transactionNumber', 'Transaction Number') + inp('amount', 'Amount') + btn('Submit'))}
` : `Create`) : '') + table('Credit Memo Requests', ['Request', 'Transaction', 'Amount', 'Status', 'Approver', 'Credit Memo'], rows.map((r) => tr([`${esc(r.number)}`, esc(r.invoiceNumber), money(r.amount), Tt(r.status), esc(r.approver || ''), esc(r.creditMemo || '')])), 'cmrs') + none(rows)); })); app.post('/o2c/cmrs', act((req, role) => { const r = S.createCmr(role, { transactionNumber: req.body.transactionNumber, amount: Number(req.body.amount) }); return [`/o2c/cmrs/${r.id}`, r.status === 'PENDING_APPROVAL' ? `Credit memo request ${r.number} ${money(r.amount)} routed for approval to ${r.approver}.` : `Credit memo request ${r.number} approved automatically; credit memo ${r.creditMemo}.`]; })); app.get('/o2c/cmrs/:id', page((req, role) => { if (!S.can(role, 'cm.create') && !S.can(role, 'cmr.approve')) guard(role, 'cm.create'); const r = S.list('cmrs').find((x) => x.id === req.params.id); if (!r) throw new AppError(404, 'NOT_FOUND', 'Credit memo request not found.'); const i = S.findInvoice(null, r.invoiceId); return layout(req, role, `Credit Memo Request ${r.number}`, dl([['Request', esc(r.number), 'o2c-cmr-number'], ['Status', Tt(r.status), 'o2c-cmr-status'], ['Transaction', esc(r.invoiceNumber), 'o2c-cmr-trx'], ['Customer', esc(r.customerName)], ['Amount', money(r.amount), 'o2c-cmr-amount'], ['Reason', esc(r.reason)], ['Requested By', esc(r.requestedBy)], ['Credit Memo', esc(r.creditMemo || ''), 'o2c-cmr-cm'], ['Transaction Balance Due', money(i.balance), 'o2c-cmr-trx-balance']]) + table('Transaction Lines', ['Line', 'Description', 'Quantity', 'Unit Price', 'Amount'], i.lines.map((l) => tr([l.lineNum, esc(l.description || l.item), l.quantity, money(l.unitPrice), money(l.amount)])), 'cmr-trx-lines') + (r.status === 'PENDING_APPROVAL' && r.approver === role ? form(`/o2c/cmrs/${r.id}/approve`, btn('Approve')) : '')); })); app.post('/o2c/cmrs/:id/approve', act((req, role) => { const r = S.approveCmr(role, req.params.id); const i = S.findInvoice(null, r.invoiceId); return [`/o2c/cmrs/${r.id}`, `Approved ${r.number}; credit memo ${r.creditMemo} ${money(r.amount)} created; transaction ${i.number} balance ${money(i.balance)}.`]; })); // ---------------- collections (O2C-COL-002) app.get('/o2c/collections', page((req, role) => { guard(role, 'collections'); const q = (req.query.customer || '').trim(); const searched = req.query.customer !== undefined; const inv = searched ? S.openInvoicesOf(q).filter((i) => S.buOk(role, i.bu)) : []; const t = today(); const dpd = (i) => Math.round((new Date(`${t}T00:00:00`) - new Date(`${i.dueDate}T00:00:00`)) / 86400000); const b = `/o2c/collections?customer=${encodeURIComponent(q)}`; return layout(req, role, 'Collections', form('/o2c/collections', inp('customer', 'Customer', { value: q }) + btn('Search'), 'get') + (searched ? table('Open Transactions', ['Transaction', 'Due Date', 'Days Past Due', 'Balance Due', 'Disputed Amount'], inv.map((i) => tr([esc(i.number), esc(i.dueDate), Math.max(0, dpd(i)), money(i.balance), money(S.disputedOf(i.id))])), 'collections-trx') + none(inv) + (inv.length ? (req.query.view === 'promise' ? dialog('Record Promise to Pay', form('/o2c/collections/promise', hid('customer', q) + inp('amount', 'Amount') + inp('promiseDate', 'Promise Date', { type: 'date' }) + btn('Save'))) : req.query.view === 'dispute' ? dialog('Create Dispute', form('/o2c/collections/dispute', hid('customer', q) + inp('amount', 'Amount') + btn('Submit'))) : `Record Promise to Pay Create Dispute`) : '') + table('Promises to Pay', ['Transaction', 'Amount', 'Promise Date', 'Broken Promise Check', 'Status'], S.list('promises').filter((p) => p.customer === q).map((p) => tr([esc(p.invoiceNumber), money(p.amount), esc(p.promiseDate), esc(p.brokenPromiseCheck), Tt(p.status)])), 'promises') + table('Disputes', ['Dispute', 'Transaction', 'Amount', 'Status', 'Approver'], S.list('disputes').filter((d) => d.customer === q).map((d) => tr([esc(d.number), esc(d.invoiceNumber), money(d.amount), Tt(d.status), esc(d.approver || '')])), 'disputes') : '')); })); app.post('/o2c/collections/promise', act((req, role) => { const p = S.recordPromise(role, { customer: req.body.customer, amount: Number(req.body.amount), promiseDate: req.body.promiseDate }); return [`/o2c/collections?customer=${encodeURIComponent(p.customer)}`, `Promise to pay ${money(p.amount)} recorded for ${p.invoiceNumber}; broken-promise check dated ${p.brokenPromiseCheck}.`]; })); app.post('/o2c/collections/dispute', act((req, role) => { const d = S.createDispute(role, { customer: req.body.customer, amount: Number(req.body.amount) }); return [`/o2c/collections?customer=${encodeURIComponent(d.customer)}`, `Dispute ${d.number} ${money(d.amount)} created for ${d.invoiceNumber}; routed for approval to ${d.approver}.`]; })); // ---------------- pricing administration (O2C-PRC-005; read-only views) app.get('/o2c/pricing/price-lists', page((req, role) => { guard(role, 'pricing.admin'); const c = S.config(); const q = (req.query.priceList || '').trim(); const searched = req.query.priceList !== undefined; const rows = searched && c.priceList.toLowerCase().includes(q.toLowerCase()) ? [c.priceList] : []; return layout(req, role, 'Manage Price Lists', form('/o2c/pricing/price-lists', inp('priceList', 'Price List', { value: q }) + btn('Search'), 'get') + (searched ? table('Price Lists', ['Price List', 'Currency', 'Status'], rows.map((n) => tr([`${esc(n)}`, esc(c.currency), 'Active'])), 'price-lists') + none(rows) : '')); })); app.get('/o2c/pricing/price-lists/view', page((req, role) => { guard(role, 'pricing.admin'); const c = S.config(); if (req.query.name !== c.priceList) throw new AppError(404, 'NOT_FOUND', 'Price list not found.'); const items = S.list('items'); return layout(req, role, `Price List ${c.priceList}`, table('Price List Items', ['Item', 'Base Price', 'Currency', 'Start Date', 'Status'], items.map((it) => tr([esc(it.number), money(it.listPrice), esc(c.currency), esc(it.priceStart || '2026-01-01'), 'Active'])), 'price-list-items')); })); app.get('/o2c/pricing/strategies', page((req, role) => { guard(role, 'pricing.admin'); const c = S.config(); const q = (req.query.name || '').trim(); const searched = req.query.name !== undefined; const rows = searched ? S.list('strategyAssignments').filter((a) => a.strategy.toLowerCase().includes(q.toLowerCase())) : []; return layout(req, role, 'Manage Pricing Strategies', form('/o2c/pricing/strategies', inp('name', 'Name', { value: q }) + btn('Search'), 'get') + (searched ? table('Pricing Strategies', ['Strategy', 'Price List', 'Customer', 'Status'], rows.map((a) => tr([esc(a.strategy), esc(a.priceList), esc(a.customer), 'Active'])), 'pricing-strategies') + none(rows) : '')); })); } module.exports = { TASKS, mount };