Download mock-app/modules/p2p/rest.js from EnergyVenom/patchwise-agent-studio: direct link, hf CLI and curl.
- Browser
- Download file 18.3 kB
-
https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/mock-app/modules/p2p/rest.js
- Command line
-
hf download hf://spaces/EnergyVenom/patchwise-agent-studio/mock-app/modules/p2p/rest.js
-
curl -L -o rest.js https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/mock-app/modules/p2p/rest.js
18.3 kB
| ; | |
| // Fusion-style REST facade (shapes loosely modelled on public Oracle Fusion REST naming) + internal /api used by test recipes. | |
| // MOCK ONLY. Auth = X-Mock-Role header naming a persona (no credentials, no secrets). | |
| // Health, reset, scheduled processes and describe() are served by the shared shell (core/shell.js). | |
| const express = require('express'); | |
| const S = require('./store'); | |
| const { roleOf, wrap, created } = require('../../core/ui'); | |
| const readable = (role) => { S.assertRole(role); }; | |
| // ---------------- internal API (camelCase) ---------------- | |
| const api = express.Router(); | |
| api.get('/test/config', wrap(() => S.config())); | |
| api.patch('/test/config', wrap((req) => S.setConfig(req.body))); | |
| api.get('/test/seed', wrap(() => S.seedRefs())); | |
| api.get('/personas', wrap(() => ({ personas: S.PERSONAS, permissions: S.PERMS }))); | |
| const coll = { suppliers: 'suppliers', requisitions: 'requisitions', purchaseOrders: 'purchaseOrders', receipts: 'receipts', invoices: 'invoices', | |
| payments: 'payments', pprs: 'pprs', paymentFiles: 'paymentFiles', tasks: 'tasks', sla: 'sla', glBatches: 'glBatches', bankAccounts: 'bankAccounts', items: 'items', periods: 'periods' }; | |
| const view = { purchaseOrders: S.poView, invoices: S.invoiceView }; | |
| const buScoped = { requisitions: true, purchaseOrders: true }; | |
| for (const [path, key] of Object.entries(coll)) { | |
| api.get(`/${path}`, wrap((req, role) => { readable(role); let items = S.list(key); if (buScoped[key]) items = items.filter((x) => S.buOk(role, x.bu)); return { items: items.map(view[key] || ((x) => x)) }; })); | |
| api.get(`/${path}/:id`, wrap((req, role) => { readable(role); const x = S.find(key, req.params.id, path); if (buScoped[key] && !S.buOk(role, x.bu)) throw new S.AppError(404, 'NOT_FOUND', `${path} ${req.params.id} not found.`); return (view[key] || ((y) => y))(x); })); | |
| } | |
| api.post('/suppliers', wrap((req, role) => created(S.createSupplier(role, req.body)))); | |
| api.patch('/suppliers/:id', wrap((req, role) => S.setSupplierStatus(role, req.params.id, req.body.status))); | |
| api.post('/suppliers/:id/bankAccounts', wrap((req, role) => created(S.addSupplierBankAccount(role, req.params.id, req.body)))); | |
| api.post('/requisitions', wrap((req, role) => created(S.createRequisition(role, req.body)))); | |
| api.post('/requisitions/:id/submit', wrap((req, role) => S.submitRequisition(role, req.params.id))); | |
| api.post('/requisitions/:id/:action(approve|reject|requestInfo)', wrap((req, role) => S.reqApprovalAction(role, req.params.id, { approve: 'APPROVE', reject: 'REJECT', requestInfo: 'REQUEST_INFO' }[req.params.action], req.body.comment))); | |
| api.post('/requisitions/:id/respond', wrap((req, role) => S.reqRespondInfo(role, req.params.id, req.body.response))); | |
| api.post('/purchaseOrders', wrap((req, role) => created(req.body.requisitionId ? S.createPoFromRequisition(role, req.body) : S.createPo(role, req.body)))); | |
| api.post('/purchaseOrders/:id/submit', wrap((req, role) => S.submitPo(role, req.params.id))); | |
| api.post('/purchaseOrders/:id/:action(approve|reject|requestInfo)', wrap((req, role) => S.poApprovalAction(role, req.params.id, { approve: 'APPROVE', reject: 'REJECT', requestInfo: 'REQUEST_INFO' }[req.params.action], req.body.comment))); | |
| api.post('/purchaseOrders/:id/respond', wrap((req, role) => S.poRespondInfo(role, req.params.id, req.body.response))); | |
| api.post('/purchaseOrders/:id/cancel', wrap((req, role) => S.cancelPo(role, req.params.id, req.body.reason))); | |
| api.post('/receipts', wrap((req, role) => created(S.createReceipt(role, req.body)))); | |
| api.post('/invoices', wrap((req, role) => created(S.createInvoice(role, req.body)))); | |
| api.post('/invoices/:id/validate', wrap((req, role) => S.invoiceView(S.validateInvoice(role, req.params.id)))); | |
| api.post('/invoices/:id/lines/:n', wrap((req, role) => S.invoiceView(S.updateInvoiceLine(role, req.params.id, req.params.n, req.body)))); | |
| api.post('/invoices/:id/holds', wrap((req, role) => S.invoiceView(S.placeHold(role, req.params.id, req.body)))); | |
| api.post('/invoices/:id/releaseHold', wrap((req, role) => S.invoiceView(S.releaseHold(role, req.params.id, req.body)))); | |
| api.post('/invoices/:id/initiateApproval', wrap((req, role) => S.invoiceView(S.initiateInvoiceApproval(role, req.params.id)))); | |
| api.post('/invoices/:id/:action(approve|reject)', wrap((req, role) => S.invoiceView(S.invoiceApprovalAction(role, req.params.id, req.params.action.toUpperCase(), req.body.comment)))); | |
| api.post('/pprs', wrap((req, role) => created(S.submitPpr(role, req.body)))); | |
| api.post('/pprs/:id/resume', wrap((req, role) => S.resumePpr(role, req.params.id))); | |
| api.get('/paymentFiles/:id/content', (req, res) => { | |
| try { S.assertRole(roleOf(req)); const f = S.find('paymentFiles', req.params.id, 'Payment file'); res.type(f.contentType).send(f.content); } | |
| catch (e) { res.status(e.status || 500).json({ message: e.message }); } | |
| }); | |
| api.get('/mailbox/:persona', wrap((req) => ({ items: S.mailFor(req.params.persona) }))); | |
| // ---------------- Fusion-style facade (PascalCase) ---------------- | |
| const fx = express.Router(); | |
| const STATUS_TXT = { INCOMPLETE: 'INCOMPLETE', PENDING_APPROVAL: 'PENDING APPROVAL', APPROVED: 'APPROVED', REJECTED: 'REJECTED', INFO_REQUESTED: 'PENDING APPROVAL', OPEN: 'OPEN', DRAFT: 'INCOMPLETE', CANCELLED: 'CANCELED' }; | |
| const VAL_TXT = { VALIDATED: 'Validated', NOT_VALIDATED: 'Not validated', NEEDS_REVALIDATION: 'Needs revalidation' }; | |
| const APPR_TXT = { NOT_REQUIRED: 'Not required', REQUIRED: 'Required', INITIATED: 'Initiated', WORKFLOW_APPROVED: 'Workflow approved', MANUALLY_APPROVED: 'Manually approved', REJECTED: 'Rejected', NOT_YET_DETERMINED: 'Not yet determined' }; | |
| function parseQ(q) { | |
| if (!q) return null; | |
| const m = /^\s*(\w+)\s*=\s*'([^']*)'\s*$/.exec(q); | |
| if (!m) throw new S.AppError(400, 'BAD_QUERY', `Unsupported q expression: ${q}`); | |
| return { field: m[1], value: m[2] }; | |
| } | |
| const listOut = (items) => ({ items, count: items.length, hasMore: false, limit: 25, offset: 0 }); | |
| function reqOut(r) { | |
| return { RequisitionHeaderId: r.id, Requisition: r.number, RequisitioningBU: r.bu, Description: r.description, DocumentStatus: STATUS_TXT[r.status] || r.status, | |
| PreparerPersona: r.preparer, DeliverToLocationCode: r.deliverToLocation || null, Amount: r.amount, | |
| lines: r.lines.map((l) => ({ RequisitionLineNumber: l.lineNum, LineNumber: l.lineNum, Item: l.itemCode, ItemDescription: l.description, Quantity: l.quantity, Price: l.unitPrice, Amount: l.amount, OrderNumber: l.poNumber })) }; | |
| } | |
| function poOut(po) { | |
| const v = S.poView(po); | |
| return { POHeaderId: v.id, OrderNumber: v.number, ProcurementBU: v.bu, Supplier: v.supplierName, Status: STATUS_TXT[v.status] || v.status, Ordered: v.amount, CurrencyCode: v.currency, MatchApprovalLevel: v.matchType, | |
| SourceAgreementNumber: v.agreementId, | |
| lines: v.lines.map((l) => ({ LineNumber: l.lineNum, Item: l.itemCode, Description: l.description, Quantity: l.quantity, Price: l.unitPrice, Ordered: l.amount, | |
| schedules: [{ ScheduleNumber: 1, Quantity: l.quantity, QuantityReceived: l.receivedQty, QuantityBilled: l.billedQty, AmountBilled: l.billedAmount, | |
| Status: l.receivedQty >= l.quantity ? 'CLOSED FOR RECEIVING' : 'OPEN' }] })) }; | |
| } | |
| function invOut(i) { | |
| const v = S.invoiceView(i); | |
| return { InvoiceId: v.id, InvoiceNumber: v.invoiceNumber, BusinessUnit: v.bu, Supplier: v.supplierName, InvoiceAmount: v.headerAmount, InvoiceCurrency: v.currency, ConversionRate: v.conversionRate, | |
| InvoiceSource: v.source, AccountingDate: v.accountingDate, ValidationStatus: VAL_TXT[v.validationStatus], ApprovalStatus: APPR_TXT[v.approvalStatus], | |
| PaidStatus: v.paymentStatus === 'PAID' ? 'Paid' : 'Unpaid', AmountPaid: v.amountPaid, AccountingStatus: v.accounted ? 'Accounted' : 'Unaccounted', | |
| invoiceLines: v.lines.map((l) => ({ LineNumber: l.lineNum, LineType: { ITEM: 'Item', TAX: 'Tax', AWT: 'Withholding tax' }[l.type], LineAmount: l.amount, Quantity: l.quantity, UnitPrice: l.unitPrice, | |
| PurchaseOrderNumber: l.poLineNum ? v.poNumber : null, PurchaseOrderLineNumber: l.poLineNum, TaxRateCode: l.taxRateCode || null, | |
| invoiceDistributions: l.distributions.map((d) => ({ DistributionCombination: d.account, DistributionAmount: d.amount })) })), | |
| invoiceHolds: [...v.holds.map((h) => ({ HoldName: h.name, HoldCode: h.code, HoldReason: h.message, ReleaseName: null })), | |
| ...v.releasedHolds.map((h) => ({ HoldName: h.name, HoldCode: h.code, HoldReason: h.message, ReleaseName: h.releaseName, ReleaseReason: h.releaseReason }))] }; | |
| } | |
| function supOut(s) { return { SupplierId: s.id, Supplier: s.name, Status: s.status, BusinessRelationship: s.businessRelationship, TaxOrganizationType: s.taxOrganizationType }; } | |
| const filt = (items, q, map) => { const p = parseQ(q); return p ? items.filter((x) => String(map(x)[p.field]) === p.value) : items; }; | |
| // Schema (describe) definitions of the MOCK. P2P-INT-006 checks them against a hand-authored UNVERIFIED contract (automation/fixtures/contracts/). | |
| const SCHEMAS = { | |
| purchaseRequisitions: [['RequisitionHeaderId', 'string'], ['Requisition', 'string'], ['RequisitioningBU', 'string', true], ['PreparerEmail', 'string'], ['Description', 'string'], ['DocumentStatus', 'string'], ['DeliverToLocationCode', 'string'], ['Amount', 'number']], | |
| purchaseOrders: [['POHeaderId', 'string'], ['OrderNumber', 'string'], ['ProcurementBU', 'string', true], ['Supplier', 'string', true], ['SupplierSite', 'string'], ['Status', 'string'], ['Ordered', 'number'], ['CurrencyCode', 'string'], ['MatchApprovalLevel', 'string']], | |
| suppliers: [['SupplierId', 'string'], ['Supplier', 'string', true], ['Status', 'string'], ['BusinessRelationship', 'string'], ['TaxOrganizationType', 'string']], | |
| invoices: [['InvoiceId', 'string'], ['InvoiceNumber', 'string', true], ['InvoiceAmount', 'number', true], ['BusinessUnit', 'string', true], ['Supplier', 'string', true], ['SupplierSite', 'string'], ['InvoiceCurrency', 'string'], ['InvoiceDate', 'date'], ['ValidationStatus', 'string'], ['ApprovalStatus', 'string'], ['PaidStatus', 'string'], ['AccountingDate', 'date'], ['InvoiceSource', 'string']], | |
| receivingReceiptRequests: [['ReceiptNumber', 'string'], ['OrganizationCode', 'string', true], ['ProcessingStatusCode', 'string']], | |
| }; | |
| // describe() for SCHEMAS is served by the shell from the pack registration (index.js). | |
| const bodyNum = (v, f) => { if (v === undefined || v === null || v === '' || !Number.isFinite(Number(v))) throw new S.AppError(400, 'VALIDATION', `${f} must be a number.`); return Number(v); }; | |
| const supId = (name) => { const s = S.supplierByName(name); if (!s) throw new S.AppError(400, 'VALIDATION', `Supplier ${name} not found.`); return s.id; }; | |
| fx.post('/purchaseRequisitions', wrap((req, role) => { | |
| const b = req.body; | |
| if (!b.RequisitioningBU) throw new S.AppError(400, 'VALIDATION', 'RequisitioningBU is required.'); | |
| const lines = (b.lines || []).map((l) => ({ itemCode: l.Item || null, description: l.ItemDescription, quantity: l.Quantity, unitPrice: l.Price, chargeAccount: l.ChargeAccount })); | |
| const r = S.createRequisition(role, { bu: b.RequisitioningBU, description: b.Description, deliverToLocation: b.DeliverToLocationCode || (b.lines || [])[0]?.DeliverToLocationCode, needByDate: b.NeedByDate, lines }); | |
| return created(reqOut(r)); | |
| })); | |
| fx.get('/purchaseRequisitions', wrap((req, role) => { readable(role); return listOut(filt(S.list('requisitions').filter((r) => S.buOk(role, r.bu)).map(reqOut), req.query.q, (x) => x)); })); | |
| fx.get('/purchaseRequisitions/:id', wrap((req, role) => { readable(role); const r = S.find('requisitions', req.params.id); if (!S.buOk(role, r.bu)) throw new S.AppError(404, 'NOT_FOUND', 'Not found.'); return reqOut(r); })); | |
| fx.post('/purchaseRequisitions/:id/action/submitRequisition', wrap((req, role) => reqOut(S.submitRequisition(role, req.params.id)))); | |
| fx.post('/draftPurchaseOrders', wrap((req, role) => { | |
| const b = req.body; | |
| const po = S.createPo(role, { bu: b.ProcurementBU, supplierId: supId(b.Supplier), matchType: b.MatchApprovalLevel || '3-WAY', | |
| lines: (b.lines || []).map((l) => ({ itemCode: l.Item, description: l.Description || l.Item, quantity: l.Quantity, unitPrice: l.Price })) }); | |
| return created(poOut(po)); | |
| })); | |
| fx.post('/draftPurchaseOrders/:id/action/submit', wrap((req, role) => poOut(S.submitPo(role, req.params.id)))); | |
| fx.get('/purchaseOrders', wrap((req, role) => { readable(role); return listOut(filt(S.list('purchaseOrders').filter((p) => S.buOk(role, p.bu)).map(poOut), req.query.q, (x) => x)); })); | |
| fx.post('/suppliers', wrap((req, role) => created(supOut(S.createSupplier(role, { name: req.body.Supplier, businessRelationship: req.body.BusinessRelationship, taxOrganizationType: req.body.TaxOrganizationType }))))); | |
| fx.get('/suppliers', wrap((req, role) => { readable(role); return listOut(filt(S.list('suppliers').map(supOut), req.query.q, (x) => x)); })); | |
| // Personas outside P2P (SCM receiving_agent / scm_integration) fall through to the SCM receiving interface (queued, processed by the Receiving Transaction Processor). | |
| fx.post('/receivingReceiptRequests', (req, res, next) => (S.PERSONAS[require('../../core/ui').roleOf(req)] ? next() : next('router')), wrap((req, role) => { | |
| const ls = req.body.lines || []; | |
| if (!ls.length) throw new S.AppError(400, 'VALIDATION', 'At least one line is required.'); | |
| const po = S.list('purchaseOrders').find((p) => p.number === ls[0].DocumentNumber); | |
| if (!po) throw new S.AppError(400, 'VALIDATION', `Purchase order ${ls[0].DocumentNumber} not found.`); | |
| const rc = S.createReceipt(role, { poId: po.id, lines: ls.map((l) => ({ lineNum: l.DocumentLineNumber, quantity: l.Quantity })) }); | |
| return created({ ReceiptNumber: rc.number, OrganizationCode: req.body.OrganizationCode || 'MOCK-ORG', ProcessingStatusCode: 'SUCCESS' }); | |
| })); | |
| function invFromRest(b, role) { | |
| const amount = bodyNum(b.InvoiceAmount, 'InvoiceAmount'); | |
| const lines = b.invoiceLines || []; | |
| const poNum = (lines.find((l) => l.PurchaseOrderNumber) || {}).PurchaseOrderNumber; | |
| const po = poNum ? S.list('purchaseOrders').find((p) => p.number === poNum) : null; | |
| if (poNum && !po) throw new S.AppError(400, 'VALIDATION', `Purchase order ${poNum} not found.`); | |
| const common = { invoiceNumber: b.InvoiceNumber, bu: b.BusinessUnit || 'US1', amount, currency: b.InvoiceCurrency, invoiceDate: b.InvoiceDate, accountingDate: b.AccountingDate, source: b.InvoiceSource, conversionRate: b.ConversionRate }; | |
| if (!b.Supplier && !po) throw new S.AppError(400, 'VALIDATION', 'Supplier is required.'); | |
| if (po) return { ...common, poId: po.id, lines: lines.filter((l) => l.PurchaseOrderNumber).map((l) => ({ poLineNum: l.PurchaseOrderLineNumber || 1, quantity: l.Quantity, unitPrice: l.UnitPrice })) }; | |
| const ds = lines.find((l) => l.DistributionSet); | |
| if (ds) return { ...common, supplierId: supId(b.Supplier), distributionSet: ds.DistributionSet }; | |
| return { ...common, supplierId: supId(b.Supplier), lines: lines.length ? lines.map((l) => ({ amount: l.LineAmount, account: l.DistributionCombination || '01-000-6100-0000' })) : [{ amount, account: '01-000-6100-0000' }] }; | |
| } | |
| fx.post('/invoices', wrap((req, role) => created(invOut(S.createInvoice(role, invFromRest(req.body, role)))))); | |
| fx.get('/invoices', wrap((req, role) => { readable(role); return listOut(filt(S.list('invoices').map(invOut), req.query.q, (x) => x)); })); | |
| fx.post('/invoices/action/validateInvoice', wrap((req, role) => { | |
| const inv = S.list('invoices').find((i) => i.invoiceNumber === req.body.InvoiceNumber && (!req.body.BusinessUnit || i.bu === req.body.BusinessUnit)); | |
| if (!inv) throw new S.AppError(404, 'NOT_FOUND', `Invoice ${req.body.InvoiceNumber} not found.`); | |
| return invOut(S.validateInvoice(role, inv.id)); | |
| })); | |
| // FBDI stand-in: DocumentContent = base64 CSV (NOT a real FBDI zip / UCM upload). Rows grouped by InvoiceNumber. | |
| // Jobs owned by other packs (e.g. R2R 'Import Journals') pass through to the next router. | |
| fx.post('/erpintegrations', (req, res, next) => (req.body && req.body.OperationName === 'importBulkData' && req.body.JobName !== 'Import Payables Invoices' ? next('router') : next())); | |
| fx.post('/erpintegrations', wrap((req, role) => { | |
| const b = req.body; | |
| if (b.OperationName !== 'importBulkData') throw new S.AppError(400, 'VALIDATION', 'Only OperationName importBulkData is supported by the mock.'); | |
| if (b.JobName !== 'Import Payables Invoices') throw new S.AppError(400, 'VALIDATION', `Job ${b.JobName} not supported by the mock.`); | |
| const csv = Buffer.from(String(b.DocumentContent || ''), 'base64').toString('utf8').trim().split(/\r?\n/); | |
| const head = csv.shift().split(','); | |
| const rows = csv.map((l) => Object.fromEntries(l.split(',').map((v, i) => [head[i], v]))); | |
| const groups = {}; | |
| rows.forEach((r) => { (groups[r.InvoiceNumber] = groups[r.InvoiceNumber] || []).push(r); }); | |
| for (const [num, ls] of Object.entries(groups)) { | |
| const h = ls[0]; const po = h.PONumber ? S.list('purchaseOrders').find((p) => p.number === h.PONumber) : null; | |
| const payload = { invoiceNumber: num, amount: Number(h.InvoiceAmount), bu: 'US1' }; | |
| if (po) Object.assign(payload, { poId: po.id, lines: ls.map((l) => ({ poLineNum: Number(l.POLine || 1), quantity: Number(l.Quantity), unitPrice: Number(l.UnitPrice) })) }); | |
| else if (h.DistributionSet) Object.assign(payload, { supplierId: supId(h.Supplier), distributionSet: h.DistributionSet }); | |
| else Object.assign(payload, { supplierId: supId(h.Supplier), lines: ls.map((l) => ({ amount: Number(l.LineAmount), account: l.DistributionCombination || '01-000-6100-0000' })) }); | |
| S.stageInterfaceInvoice('integration_user', { ...payload, source: 'FBDI_STAND_IN' }); | |
| } | |
| const p = S.submitProcess(role, { name: 'Import Payables Invoices', params: { source: 'FBDI_STAND_IN' } }); | |
| return { ReqstId: p.id, JobName: b.JobName, Status: p.status, Log: p.log, Result: p.result }; | |
| })); | |
| fx.get('/payablesPayments', wrap((req, role) => { readable(role); return listOut(S.list('payments').map((p) => ({ PaymentNumber: p.number, PaymentAmount: p.amount, PaymentCurrency: p.currency, PaymentStatus: p.status }))); })); | |
| module.exports = { api, fx, roleOf, SCHEMAS }; | |