Download mock-app/modules/o2c/rest.js from EnergyVenom/patchwise-agent-studio: direct link, hf CLI and curl.
- Browser
- Download file 15.6 kB
-
https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/mock-app/modules/o2c/rest.js
- Command line
-
hf download hf://spaces/EnergyVenom/patchwise-agent-studio/mock-app/modules/o2c/rest.js
-
curl -L -o rest.js https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/mock-app/modules/o2c/rest.js
15.6 kB
| ; | |
| // O2C Fusion-style REST facade (resource names from the O2C case YAMLs; attribute names ASSUMED, UNVERIFIED) + internal /api/o2c | |
| // used by automation data recipes. MOCK ONLY. Auth = X-Mock-Role header naming a persona (no credentials). | |
| const express = require('express'); | |
| const S = require('./store'); | |
| const U = require('../../core/ui'); | |
| const { wrap, created } = U; | |
| const { AppError } = require('../../core/errors'); | |
| const STATUS = { DRAFT: 'Draft', PROCESSING: 'Processing', ON_HOLD: 'On Hold', CLOSED: 'Closed' }; | |
| const LINE_STATUS = { DRAFT: 'Draft', AWAITING_SHIPPING: 'Awaiting Shipping', PICK_RELEASED: 'Pick Released', PICKED: 'Picked', SHIPPED: 'Shipped', BILLED: 'Billed', ON_HOLD: 'On Hold' }; | |
| const TRX_STATUS = { COMPLETE: 'Complete', CLOSED: 'Closed' }; | |
| const RCPT_STATUS = { UNAPPLIED: 'Unapplied', APPLIED: 'Applied', CONFIRMED: 'Confirmed' }; | |
| const ok = (role, action) => { if (!S.PERSONAS[role]) throw new AppError(401, 'UNAUTHENTICATED', 'Unknown or missing persona.'); if (!S.can(role, action)) throw new AppError(403, 'FORBIDDEN', `Persona ${role} may not ${action}.`); }; | |
| /** q=Field='v' or q=A='x';B='y' (AND). */ | |
| function filt(items, q) { | |
| if (!q) return items; | |
| const conds = String(q).split(';').map((c) => /^\s*(\w+)\s*=\s*'([^']*)'\s*$/.exec(c)); | |
| if (conds.some((m) => !m)) throw new AppError(400, 'BAD_QUERY', `Unsupported q expression: ${q}`); | |
| return items.filter((x) => conds.every(([, f, v]) => String(x[f]) === v)); | |
| } | |
| const listOut = (items) => ({ items, count: items.length, hasMore: false, limit: 25, offset: 0 }); | |
| const orderOut = (o) => ({ HeaderId: o.id, OrderNumber: o.number, SourceTransactionNumber: o.sourceTxnNumber, SourceTransactionSystem: o.sourceSystem, BusinessUnitName: o.bu, | |
| BuyingPartyName: o.customerName, CustomerPONumber: o.customerPO, StatusCode: o.status === 'DRAFT' ? 'DRAFT' : o.status === 'CLOSED' ? 'CLOSED' : 'OPEN', Status: STATUS[o.status], OnHoldFlag: o.holds.some((h) => h.active), | |
| TotalAmount: o.total, Subtotal: o.subtotal, EstimatedTax: o.tax, RevisionNumber: o.revision || 0, | |
| lines: o.lines.map((l) => ({ LineNumber: l.lineNum, ProductNumber: l.item, OrderedQuantity: l.quantity, OrderedUOM: l.uom, UnitListPrice: l.listPrice, UnitSellingPrice: l.unitSellingPrice, ExtendedAmount: l.extendedAmount, FulfilledQuantity: l.fulfilledQty, ScheduledShipDate: l.scheduledShipDate, RequestedShipDate: l.requestedShipDate, ShipFromOrganization: l.shipFromOrg, BackorderedFlag: !!l.backordered, SplitFromLineNumber: l.splitFrom || null, OrchestrationProcess: l.orchestrationProcess, TaxClassificationCode: l.taxClassification, TaxAmount: l.tax, StatusCode: l.status, Status: LINE_STATUS[l.status] })), | |
| holds: o.holds.map((h) => ({ HoldCode: h.code, HoldName: h.name, ActiveFlag: h.active, HoldComments: h.message, ReleaseComments: h.releaseComments || null })) }); | |
| const invOut = (i) => ({ CustomerTransactionId: i.id, TransactionNumber: i.number, BusinessUnit: i.bu, BillToCustomerName: i.customerName, TransactionSource: i.source, TransactionType: i.type, | |
| TransactionDate: i.trxDate, DueDate: i.dueDate, PaymentTerms: i.paymentTerms, SalesOrder: i.salesOrder, PurchaseOrder: i.purchaseOrder || null, InvoicingRule: i.invoicingRule || null, RevenueSchedulingRule: i.revenueRule || null, TransactionStatus: TRX_STATUS[i.status], InterfaceHeaderAttribute1: i.interfaceHeaderAttribute1 || null, LineAmount: i.subtotal, TaxAmount: i.tax, TotalAmount: i.total, InvoiceBalanceAmount: i.balance, | |
| receivablesInvoiceLines: i.lines.map((l) => ({ LineNumber: l.lineNum, Description: l.description, Quantity: l.quantity, UnitSellingPrice: l.unitPrice, LineAmount: l.amount })), | |
| taxLines: i.taxLines.map((t) => ({ TaxRateCode: t.taxRateCode, TaxRate: t.ratePct, TaxableAmount: t.taxable, TaxAmount: t.amount, Jurisdiction: t.jurisdiction })), | |
| revenueSchedule: (i.revenueSchedule || []).map((r) => ({ Period: r.period, Amount: r.amount, Status: r.status === 'EARNED' ? 'Earned' : 'Unearned' })) }); | |
| // Accounting lines are exposed on the mock's credit memo / adjustment resources (ASSUMED attribute; a pod would use SLA views). | |
| const acctOut = (type, id) => S.accountingFor(type, id).map((l) => ({ Side: l.side, AccountClass: l.accountClass, AccountedAmount: l.accountedAmount })); | |
| const glOf = (type, id) => S.list('sla').some((e) => e.sourceType === type && e.sourceId === id && e.transferred); | |
| const cmOut = (c) => ({ CustomerTransactionId: c.id, TransactionNumber: c.number, BusinessUnit: c.bu, TransactionSource: c.source, TransactionType: c.type, BillToCustomerName: c.customerName, TransactionDate: c.trxDate, | |
| CreditedTransactionNumber: c.creditedTransaction, LineAmount: c.subtotal, TaxAmount: c.tax, TotalAmount: c.total, TransactionStatus: TRX_STATUS[c.status], AccountedFlag: !!c.accounted, TransferredToGLFlag: glOf('Credit Memo', c.id), accountingLines: acctOut('Credit Memo', c.id) }); | |
| const adjOut = (a) => ({ AdjustmentId: a.id, AdjustmentNumber: a.number, TransactionNumber: a.invoiceNumber, ReceivablesActivity: a.activity, Amount: a.amount, Status: a.status, AccountedFlag: !!a.accounted, TransferredToGLFlag: glOf('Adjustment', a.id), accountingLines: acctOut('Adjustment', a.id) }); | |
| const rcptOut = (r) => ({ StandardReceiptId: r.id, ReceiptNumber: r.number, BusinessUnit: r.bu, CustomerName: r.customerName, ReceiptMethod: r.method, ReceiptDate: r.receiptDate, Amount: r.amount, UnappliedAmount: r.unapplied, OnAccountAmount: r.onAccount || 0, Status: RCPT_STATUS[r.status], | |
| CardNumberMasked: r.cardMasked || null, CardToken: r.cardToken || null, | |
| applications: r.applications.map((a) => ({ TransactionNumber: a.invoiceNumber, AmountApplied: a.amount })) }); | |
| // Schema (describe) definitions of the MOCK. O2C-INT-002 checks them against a hand-authored UNVERIFIED contract. | |
| const SCHEMAS = { | |
| salesOrdersForOrderHub: [['HeaderId', 'string'], ['OrderNumber', 'string'], ['SourceTransactionNumber', 'string', true], ['SourceTransactionSystem', 'string', true], ['BusinessUnitName', 'string', true], ['BuyingPartyName', 'string', true], ['CustomerPONumber', 'string'], ['StatusCode', 'string'], ['TotalAmount', 'number'], ['SubmittedFlag', 'boolean']], | |
| receivablesInvoices: [['CustomerTransactionId', 'string'], ['TransactionNumber', 'string'], ['BusinessUnit', 'string', true], ['TransactionSource', 'string', true], ['TransactionType', 'string', true], ['BillToCustomerName', 'string', true], ['TransactionDate', 'date'], ['DueDate', 'date'], ['TransactionStatus', 'string'], ['InvoiceBalanceAmount', 'number']], | |
| standardReceipts: [['StandardReceiptId', 'string'], ['ReceiptNumber', 'string', true], ['BusinessUnit', 'string', true], ['ReceiptMethod', 'string', true], ['Amount', 'number', true], ['CustomerName', 'string'], ['ReceiptDate', 'date'], ['UnappliedAmount', 'number']], | |
| accounts: [['PartyId', 'string'], ['AccountNumber', 'string'], ['AccountName', 'string'], ['OrganizationName', 'string', true], ['AccountEstablishedDate', 'date']], | |
| receivablesAdjustments: [['AdjustmentId', 'string'], ['AdjustmentNumber', 'string'], ['TransactionNumber', 'string', true], ['ReceivablesActivity', 'string', true], ['Amount', 'number', true], ['Status', 'string']], | |
| customerContracts: [['ContractId', 'string'], ['ContractNumber', 'string'], ['SourceDocument', 'string'], ['TotalAmount', 'number']], | |
| receivablesCreditMemos: [['CustomerTransactionId', 'string'], ['TransactionNumber', 'string'], ['BusinessUnit', 'string', true], ['TransactionSource', 'string', true], ['TransactionType', 'string', true], ['BillToCustomerName', 'string', true], ['TransactionDate', 'date']], | |
| }; | |
| const fx = express.Router(); | |
| fx.post('/salesOrdersForOrderHub', wrap((req, role) => { | |
| const b = req.body; | |
| for (const f of ['SourceTransactionNumber', 'SourceTransactionSystem', 'BusinessUnitName', 'BuyingPartyName']) if (!b[f]) throw new AppError(400, 'VALIDATION', `${f} is required.`); | |
| let o = S.createOrder(role, { bu: b.BusinessUnitName, customerName: b.BuyingPartyName, customerPO: b.CustomerPONumber, sourceTxnNumber: b.SourceTransactionNumber, sourceSystem: b.SourceTransactionSystem, | |
| lines: (b.lines || []).map((l) => ({ item: l.ProductNumber, quantity: l.OrderedQuantity })) }); | |
| if (b.SubmittedFlag === true || b.SubmittedFlag === 'true') o = S.submitOrder(role, o.id); | |
| return created(orderOut(o)); | |
| })); | |
| fx.get('/salesOrdersForOrderHub', wrap((req, role) => { ok(role, 'order.view'); return listOut(filt(S.ordersFor(role).map(orderOut), req.query.q)); })); | |
| fx.get('/salesOrdersForOrderHub/:id', wrap((req, role) => { ok(role, 'order.view'); return orderOut(S.findOrder(role, req.params.id)); })); | |
| fx.post('/receivablesInvoices', wrap((req, role) => { | |
| const b = req.body; | |
| return created(invOut(S.createManualInvoice(role, { bu: b.BusinessUnit, source: b.TransactionSource, type: b.TransactionType, customerName: b.BillToCustomerName, trxDate: b.TransactionDate, | |
| lines: (b.receivablesInvoiceLines || []).map((l) => ({ description: l.Description || l.MemoLine, quantity: l.Quantity, unitPrice: l.UnitSellingPrice })) }))); | |
| })); | |
| fx.get('/receivablesInvoices', wrap((req, role) => { ok(role, 'trx.view'); return listOut(filt(S.invoicesFor(role).map(invOut), req.query.q)); })); | |
| fx.get('/receivablesCreditMemos', wrap((req, role) => { ok(role, 'trx.view'); return listOut(filt(S.list('creditMemos').filter((c) => S.buOk(role, c.bu)).map(cmOut), req.query.q)); })); | |
| fx.get('/receivablesAdjustments', wrap((req, role) => { ok(role, 'trx.view'); return listOut(filt(S.list('adjustments').filter((a) => S.buOk(role, S.findInvoice(null, a.invoiceId).bu)).map(adjOut), req.query.q)); })); | |
| fx.get('/customerContracts', wrap((req, role) => { if (!S.PERSONAS[role]) throw new AppError(401, 'UNAUTHENTICATED', 'Unknown or missing persona.'); if (!S.can(role, 'revenue.manage')) throw new AppError(403, 'FORBIDDEN', `Persona ${role} may not view contracts.`); | |
| return listOut(filt(S.list('contracts').map((k) => ({ ContractId: k.id, ContractNumber: k.number, SourceDocument: k.sourceDocument, TotalAmount: k.total, Status: k.status, | |
| lines: k.lines.map((l) => ({ LineNumber: l.lineNum, ItemNumber: l.item, StandaloneSellingPrice: l.ssp, SellingPrice: l.sellingPrice, AllocatedAmount: l.allocatedAmount, SSPPercent: l.sspPct })) })), req.query.q)); })); | |
| fx.get('/standardReceipts', wrap((req, role) => { ok(role, 'receipt.view'); return listOut(filt(S.list('receipts').filter((r) => S.buOk(role, r.bu)).map(rcptOut), req.query.q)); })); | |
| fx.post('/standardReceipts', wrap((req, role) => { const b = req.body; return created(rcptOut(S.createReceipt(role, { number: b.ReceiptNumber, bu: b.BusinessUnit, method: b.ReceiptMethod, amount: b.Amount, customerName: b.CustomerName, receiptDate: b.ReceiptDate }))); })); | |
| fx.get('/accounts', wrap((req, role) => { if (!S.PERSONAS[role]) throw new AppError(401, 'UNAUTHENTICATED', 'Unknown or missing persona.'); if (!S.can(role, 'order.view') && !S.can(role, 'customer.view')) throw new AppError(403, 'FORBIDDEN', `Persona ${role} may not view accounts.`); | |
| return listOut(filt(S.list('customers').filter((c) => S.buOk(role, c.bu)).map((c) => ({ PartyId: c.id, AccountNumber: c.accountNumber, AccountName: c.name, OrganizationName: c.name, Status: c.status === 'ACTIVE' ? 'Active' : c.status, | |
| CreditLimit: c.creditLimit, CreditExposure: S.exposure(c.id), PaymentTerms: c.paymentTerms, ReceiptMethod: c.receiptMethod || null, siteUses: (c.siteUses || []).map((u) => ({ SiteUseCode: u })), | |
| bankAccounts: c.bankAccounts.map((a) => ({ BankName: a.bank, AccountNumberMasked: a.accountMasked })), cards: (c.cards || []).map((k) => ({ CardBrand: k.brand, CardNumberMasked: `************${k.last4}`, CardToken: k.token })) })), req.query.q)); })); | |
| // Shared resource: personas outside O2C (e.g. SCM inventory users) fall through to the SCM pack's inventoryOnhandBalances. | |
| fx.get('/inventoryOnhandBalances', (req, res, next) => (S.PERSONAS[U.roleOf(req)] ? next() : next('router')), wrap((req, role) => { ok(role, 'order.view'); return listOut(filt(S.list('onhand').map((o) => ({ ItemNumber: o.item, OrganizationCode: o.org, OnhandQuantity: o.quantity })), req.query.q)); })); | |
| // ---------------- internal API (camelCase) for recipes | |
| const api = express.Router(); | |
| api.get('/test/seed', wrap(() => S.seedRefs())); | |
| api.get('/config', wrap(() => S.config())); | |
| // O2C-INT-003 stand-in: synthetic OM extension/flexfield inventory (same output keys as DR-O2C-INT-003; read-only). | |
| api.get('/extensions', wrap(() => require('./extensions').inventory())); | |
| api.get('/orders', wrap((req, role) => { ok(role, 'order.view'); return { items: S.ordersFor(role) }; })); | |
| api.get('/orders/:id', wrap((req, role) => { ok(role, 'order.view'); return S.findOrder(role, req.params.id); })); | |
| api.post('/orders', wrap((req, role) => created(S.createOrder(role, req.body)))); | |
| api.post('/orders/:id/submit', wrap((req, role) => S.submitOrder(role, req.params.id))); | |
| api.post('/orders/:id/releaseCreditHold', wrap((req, role) => S.releaseCreditHold(role, req.params.id, req.body.comments))); | |
| api.post('/pickSlips/:number/confirm', wrap((req, role) => S.confirmPickSlip(role, req.params.number, req.body && req.body.pickedQuantity))); | |
| api.post('/customers/:id/payment', wrap((req, role) => S.setPaymentDetails(role, req.params.id, req.body))); | |
| api.get('/shipments', wrap((req, role) => { ok(role, 'order.view'); return { items: S.list('shipments') }; })); | |
| api.post('/shipments/:id/confirm', wrap((req, role) => S.shipConfirm(role, req.params.id))); | |
| api.get('/invoices', wrap((req, role) => { ok(role, 'trx.view'); return { items: S.invoicesFor(role) }; })); | |
| api.post('/invoices', wrap((req, role) => created(S.createManualInvoice(role, req.body)))); | |
| api.post('/invoices/:id/adjustments', wrap((req, role) => created(S.createAdjustment(role, req.params.id, req.body)))); | |
| api.post('/adjustments/:id/approve', wrap((req, role) => S.approveAdjustment(role, req.params.id))); | |
| api.get('/receipts', wrap((req, role) => { ok(role, 'receipt.view'); return { items: S.list('receipts').filter((r) => S.buOk(role, r.bu)) }; })); | |
| api.post('/receipts', wrap((req, role) => created(S.createReceipt(role, req.body)))); | |
| api.post('/receipts/:id/apply', wrap((req, role) => S.applyReceipt(role, req.params.id, req.body.invoiceId, req.body.amount))); | |
| api.post('/lockboxFiles', wrap((req, role) => created(S.stageLockboxFile(role, req.body)))); | |
| api.get('/sla', wrap((req, role) => { ok(role, 'trx.view'); return { items: S.list('sla') }; })); | |
| // P2 recipes (mock only) | |
| api.post('/autoInvoiceLines', wrap((req, role) => created({ items: S.stageAutoInvoiceLines(role, req.body.rows) }))); | |
| api.post('/files', wrap((req, role) => created(S.stageFile(role, req.body)))); | |
| api.post('/revenueSources', wrap((req, role) => created(S.stageRevenueSource(role, req.body)))); | |
| api.post('/invoices/:id/credit', wrap((req, role) => created(S.creditTransaction(role, req.params.id, req.body)))); | |
| api.get('/creditMemos', wrap((req, role) => { ok(role, 'trx.view'); return { items: S.list('creditMemos') }; })); | |
| api.post('/receipts/:id/onAccount', wrap((req, role) => S.applyOnAccount(role, req.params.id, req.body.amount))); | |
| api.get('/collections', wrap((req, role) => { ok(role, 'trx.view'); return { promises: S.list('promises'), disputes: S.list('disputes'), dunning: S.list('dunning'), cmrs: S.list('cmrs') }; })); | |
| api.get('/orders/:id/raw', wrap((req, role) => { ok(role, 'order.view'); return S.findOrder(role, req.params.id); })); | |
| module.exports = { fx, api, SCHEMAS, STATUS, LINE_STATUS, TRX_STATUS, RCPT_STATUS }; | |