'use strict'; /* * MOCK PPM (Project Portfolio Management: costing, contracts, billing, revenue) store. NOT Oracle software; synthetic data only. * ASSUMED (UNVERIFIED) rules from tests/cases/ppm + tests/data-recipes/ppm: BU 'ZZ PPM BU (MOCK)'; cost rate 50.00/h; bill rate 80.00/h * (schedule 'ZZ Bill Rates (MOCK)'); T&M contract limit = contract amount (hard revenue limit); labor accounting Dr project expense * 01-000-6500 / Cr labor clearing 01-000-2400; cost adjustments apply immediately and carry a review approval that the creator cannot give (SoD). * Payroll costs come from seeded payroll cost files until the HCM pack exists (decision 9 Oct 2026). Supplier costs come from P2P invoices * (validated + accounted) whose project coding is held in a mock side table (P2P mock invoices have no project distribution fields). * Project invoices transfer to the O2C pack (AutoInvoice) with InterfaceHeaderAttribute1 = project invoice number. */ const { err } = require('../../core/errors'); const { r2, files, today } = require('../../core/kit'); const P2P = require('../p2p/store'); const O2C = require('../o2c/store'); const BU = 'ZZ PPM BU (MOCK)'; const LABOR_SOURCE = 'ZZ Payroll (MOCK)'; const LABOR_TYPE = 'ZZ Labor (MOCK)'; const SUPPLIER_TYPE = 'ZZ Supplier Cost (MOCK)'; const RATES = { cost: { 'ZZ-EMP-1': 50, 'ZZ-EMP-2': 50 }, bill: 80, schedule: 'ZZ Bill Rates (MOCK)' }; const ACCT = { expense: '01-000-6500', laborClearing: '01-000-2400' }; const CONTRACT_TYPE = 'ZZ T&M Contract (MOCK)'; const CUSTOMER = 'ZZ_O2C_CUST (MOCK)'; const PERSONAS = { project_manager: { label: 'Project Manager (MOCK)', bus: [] }, project_manager_2: { label: 'Project Manager 2 (MOCK)', bus: [] }, project_accountant: { label: 'Project Accountant (MOCK)', bus: [] }, project_accountant_2: { label: 'Project Accountant 2 (MOCK)', bus: [] }, billing_specialist_ppm: { label: 'Project Billing Specialist (MOCK)', bus: [] }, contract_admin: { label: 'Project Contract Administrator (MOCK)', bus: [] }, contract_approver: { label: 'Contract Approver (MOCK)', bus: [] }, }; const PERMS = { 'project.view': ['project_manager', 'project_manager_2', 'project_accountant', 'project_accountant_2', 'billing_specialist_ppm', 'contract_admin'], 'cost.manage': ['project_accountant', 'project_accountant_2'], 'contract.create': ['contract_admin'], 'contract.approve': ['contract_approver'], 'billing.manage': ['billing_specialist_ppm'], 'revenue.run': ['project_accountant'], }; const can = (role, a) => (PERMS[a] || []).includes(role); const assertCan = (role, a) => { if (!PERSONAS[role]) throw err(401, 'UNAUTHENTICATED', 'Unknown persona.'); if (!can(role, a)) throw err(403, 'FORBIDDEN', `Persona ${role} is not authorized to ${a}.`); }; const FILES = files(); let db; const seq = (k) => { db.seq[k] = (db.seq[k] || 0) + 1; return db.seq[k]; }; function reset() { FILES.reset(); db = { seq: {}, projects: [], unprocessed: [], items: [], adjustments: [], contracts: [], invoices: [], revenue: [], apCoding: [], importedAp: new Set() }; db.projects.push({ number: 'ZZ-PRJ-001', name: 'ZZ T&M project (MOCK)', bu: BU, manager: 'project_manager', tasks: ['1.1', '1.2'], status: 'ACTIVE' }); db.projects.push({ number: 'ZZ-PRJ-OTHER', name: 'ZZ other PM project (MOCK)', bu: BU, manager: 'project_manager_2', tasks: ['1.1'], status: 'ACTIVE' }); } // Project security (ASSUMED): project managers see only projects they manage; accountants/billing/contract roles see all in the BU. const visible = (role, p) => !role.startsWith('project_manager') || p.manager === role; function project(role, n) { const p = db.projects.find((x) => x.number === n); if (!p || (role && !visible(role, p))) throw err(404, 'NOT_FOUND', `Project ${n} not found.`); return p; } const projectsFor = (role, q) => db.projects.filter((p) => visible(role, p) && (!q || p.number === q)); function createProject(role, b) { const n = b.number || `ZZ-PRJ-${String(seq('PRJ')).padStart(4, '0')}`; if (db.projects.some((p) => p.number === n)) throw err(409, 'DUPLICATE', `Project ${n} exists.`); const p = { number: n, name: b.name || `${n} (MOCK)`, bu: BU, manager: b.manager || 'project_manager', tasks: ['1.1', '1.2'], status: 'ACTIVE' }; db.projects.push(p); return p; } // ---- costing function importPayroll(role, p) { assertCan(role, 'cost.manage'); if (p.businessUnit && p.businessUnit !== BU) throw err(400, 'VALIDATION', `Business unit ${p.businessUnit} not found.`); const rows = FILES.pending().flatMap((f) => { f.imported = true; return FILES.rows(f.name); }); rows.forEach((r) => { const pr = project(null, r.ProjectNumber); if (!pr.tasks.includes(r.TaskNumber)) throw err(400, 'VALIDATION', `Task ${r.TaskNumber} not found on ${pr.number}.`); db.unprocessed.push({ id: `ZZUT${seq('UT')}`, source: LABOR_SOURCE, type: LABOR_TYPE, project: pr.number, task: r.TaskNumber, person: r.EmployeeNumber, qty: Number(r.Hours), date: r.Date || today(), uom: 'Hours' }); }); return rows; } function processCosts(role, p) { assertCan(role, 'cost.manage'); if (p.businessUnit && p.businessUnit !== BU) throw err(400, 'VALIDATION', `Business unit ${p.businessUnit} not found.`); const todo = db.unprocessed.filter((u) => !p.transactionSource || u.source === p.transactionSource); const done = []; const errors = []; for (const u of todo) { if (u.type === LABOR_TYPE) { const rate = RATES.cost[u.person]; if (!rate) { u.error = `No cost rate for ${u.person}.`; errors.push(u); continue; } u.rawCost = r2(u.qty * rate); u.rate = rate; } db.items.push({ id: `ZZEI${String(seq('EI')).padStart(5, '0')}`, project: u.project, task: u.task, type: u.type, source: u.source, person: u.person || null, qty: u.qty, uom: u.uom, rate: u.rate || null, rawCost: r2(u.rawCost), date: u.date, document: u.document || null, status: 'COSTED', billed: false, revenueRecognized: false, accounting: null, adjustment: null }); done.push(u); } db.unprocessed = db.unprocessed.filter((u) => !done.includes(u)); return { done, errors, left: db.unprocessed.filter((u) => !p.transactionSource || u.source === p.transactionSource).length }; } function codeApInvoice(role, b) { // stand-in: project coding for a P2P invoice (mock P2P invoices carry no project distribution fields) if (!['ap_specialist', 'project_accountant', 'integration_user'].includes(role)) throw err(403, 'FORBIDDEN', 'Not authorized.'); project(null, b.project); db.apCoding.push({ invoiceNumber: b.invoiceNumber, project: b.project, task: b.task || '1.1', type: b.expenditureType || SUPPLIER_TYPE }); return db.apCoding[db.apCoding.length - 1]; } function importAp(role, p) { assertCan(role, 'cost.manage'); if (p.transactionSource && p.transactionSource !== 'Payables') throw err(400, 'VALIDATION', `Transaction source ${p.transactionSource} is not supported by Import Costs.`); const out = []; for (const c of db.apCoding) { const inv = P2P.list('invoices').find((i) => i.invoiceNumber === c.invoiceNumber); if (!inv || db.importedAp.has(inv.id)) continue; if (inv.validationStatus !== 'VALIDATED' || !inv.accounted) continue; // only validated + accounted Payables costs are imported db.importedAp.add(inv.id); const amt = r2(inv.lines.reduce((a, l) => a + l.amount, 0)); const u = { id: `ZZUT${seq('UT')}`, source: 'Payables', type: c.type, project: c.project, task: c.task, qty: 1, uom: 'Each', rawCost: amt, date: today(), document: inv.invoiceNumber }; db.unprocessed.push(u); out.push(u); } return out; } function transferItem(role, id, b) { assertCan(role, 'cost.manage'); const it = db.items.find((x) => x.id === id); if (!it) throw err(404, 'NOT_FOUND', `Expenditure item ${id} not found.`); const pr = project(null, it.project); if (!pr.tasks.includes(b.task) || b.task === it.task) throw err(400, 'VALIDATION', `Task ${b.task} is not a valid transfer target.`); const q = Number(b.qty); if (!(q > 0) || q > it.qty) throw err(400, 'VALIDATION', `Quantity ${b.qty} exceeds item quantity ${it.qty}.`); if (it.billed) throw err(409, 'INVALID_STATE', 'Billed items cannot be transferred.'); const cost = r2(q * (it.rate || it.rawCost / it.qty)); const adj = { number: `ZZ-ADJ-${String(seq('ADJ')).padStart(4, '0')}`, type: 'Transfer', itemId: it.id, fromTask: it.task, toTask: b.task, qty: q, cost, createdBy: role, status: 'PENDING_APPROVAL' }; const neg = { ...it, id: `ZZEI${String(seq('EI')).padStart(5, '0')}`, qty: -q, rawCost: -cost, adjustment: adj.number, accounting: null }; const pos = { ...it, id: `ZZEI${String(seq('EI')).padStart(5, '0')}`, task: b.task, qty: q, rawCost: cost, adjustment: adj.number, accounting: null }; db.items.push(neg, pos); db.adjustments.push(adj); return { adj, neg, pos }; } function approveAdjustment(role, n) { assertCan(role, 'cost.manage'); const a = db.adjustments.find((x) => x.number === n); if (!a) throw err(404, 'NOT_FOUND', `Adjustment ${n} not found.`); if (a.createdBy === role) throw err(403, 'SOD_VIOLATION', 'You cannot approve a cost adjustment you created (segregation of duties).'); if (a.status !== 'PENDING_APPROVAL') throw err(409, 'INVALID_STATE', `Adjustment ${n} is ${a.status}.`); a.status = 'APPROVED'; a.approvedBy = role; return a; } // ---- contracts function createContract(role, b) { assertCan(role, 'contract.create'); if (b.type !== CONTRACT_TYPE) throw err(400, 'VALIDATION', `Contract type ${b.type} not found.`); if (!O2C.customerFor(b.customer)) throw err(400, 'VALIDATION', `Customer ${b.customer} not found.`); const pr = project(null, b.project); const amt = Number(b.amount); if (!(amt > 0)) throw err(400, 'VALIDATION', 'Amount must be greater than zero.'); if (b.billPlan !== `T&M at ${RATES.schedule}`) throw err(400, 'VALIDATION', `Bill plan ${b.billPlan} not found.`); if (b.revenuePlan !== 'T&M') throw err(400, 'VALIDATION', `Revenue plan ${b.revenuePlan} not found.`); const c = { number: `ZZ-CTR-${String(seq('CTR')).padStart(4, '0')}`, type: b.type, customer: b.customer, amount: r2(amt), billPlan: b.billPlan, revenuePlan: b.revenuePlan, project: pr.number, status: 'DRAFT', approver: null, createdBy: role }; db.contracts.push(c); return c; } function submitContract(role, n) { assertCan(role, 'contract.create'); const c = contract(n); if (c.status !== 'DRAFT') throw err(409, 'INVALID_STATE', `Contract ${n} is ${c.status}.`); c.status = 'PENDING_APPROVAL'; c.approver = 'contract_approver'; return c; } function approveContract(role, n) { assertCan(role, 'contract.approve'); const c = contract(n); if (c.status !== 'PENDING_APPROVAL' || c.approver !== role) throw err(409, 'INVALID_STATE', `Contract ${n} is not awaiting your approval.`); c.status = 'ACTIVE'; c.approver = null; c.approvedBy = role; return c; } function contract(n) { const c = db.contracts.find((x) => x.number === n); if (!c) throw err(404, 'NOT_FOUND', `Contract ${n} not found.`); return c; } const activeContract = (n) => { const c = contract(n); if (c.status !== 'ACTIVE') throw err(409, 'INVALID_STATE', `Contract ${n} is ${c.status}; it must be Active.`); return c; }; const billableLabor = (c, through) => db.items.filter((i) => i.project === c.project && i.type === LABOR_TYPE && i.status === 'COSTED' && (!through || i.date <= through)); // ---- billing and revenue (rate-based T&M) function generateInvoices(role, p) { assertCan(role, 'billing.manage'); const c = activeContract(p.contract); const items = billableLabor(c, p.throughDate).filter((i) => !i.billed); if (!items.length) return null; const lines = items.map((i, k) => ({ lineNum: k + 1, itemId: i.id, qty: i.qty, rate: RATES.bill, amount: r2(i.qty * RATES.bill) })); const amount = r2(lines.reduce((a, l) => a + l.amount, 0)); const billedSoFar = db.invoices.filter((x) => x.contract === c.number).reduce((a, x) => a + x.amount, 0); if (billedSoFar + amount > c.amount) throw err(409, 'LIMIT', `Invoice limit ${c.amount.toFixed(2)} would be exceeded.`); items.forEach((i) => { i.billed = true; }); const inv = { number: `ZZ-PINV-${String(seq('PINV')).padStart(4, '0')}`, contract: c.number, customer: c.customer, amount, lines, status: 'DRAFT', transferred: false, arNumber: null }; db.invoices.push(inv); return inv; } function invoice(n) { const i = db.invoices.find((x) => x.number === n); if (!i) throw err(404, 'NOT_FOUND', `Project invoice ${n} not found.`); return i; } function approveInvoice(role, n) { assertCan(role, 'billing.manage'); const i = invoice(n); if (i.status !== 'DRAFT' && i.status !== 'SUBMITTED') throw err(409, 'INVALID_STATE', `Invoice ${n} is ${i.status}.`); i.status = 'APPROVED'; return i; } function releaseInvoice(role, n) { assertCan(role, 'billing.manage'); const i = invoice(n); if (i.status !== 'APPROVED') throw err(409, 'INVALID_STATE', `Invoice ${n} is ${i.status}; only approved invoices can be released.`); i.status = 'RELEASED'; return i; } function transferToAr(role, p) { assertCan(role, 'billing.manage'); if (p.request && p.request !== 'Transfer Invoices to Oracle Fusion Receivables and Import') throw err(400, 'VALIDATION', `Request ${p.request} not supported.`); const todo = db.invoices.filter((i) => i.status === 'RELEASED' && !i.transferred); const imported = []; const rejected = []; for (const i of todo) { try { const ar = O2C.createInvoiceRaw({ customerName: i.customer, bu: 'O2C-US1', source: 'ZZ Projects (MOCK)', type: 'Invoice', interfaceRef: i.number, taxOverride: 0, lines: i.lines.map((l) => ({ description: `Project labor ${l.qty} h`, quantity: l.qty, unitPrice: l.rate })) }); Object.assign(i, { transferred: true, arNumber: ar.number, status: 'ACCEPTED' }); imported.push(i); } catch (e) { i.transferError = e.message; rejected.push(i); } } return { imported, rejected }; } function generateRevenue(role, p) { assertCan(role, 'revenue.run'); const c = activeContract(p.contract); const items = billableLabor(c).filter((i) => !i.revenueRecognized); const recognized = db.revenue.filter((r) => r.contract === c.number).reduce((a, r) => a + r.amount, 0); let amt = r2(items.reduce((a, i) => a + i.qty * RATES.bill, 0)); const hours = r2(items.reduce((a, i) => a + i.qty, 0)); let capped = false; if (recognized + amt > c.amount) { amt = r2(c.amount - recognized); capped = true; } items.forEach((i) => { i.revenueRecognized = true; }); const ev = { contract: c.number, amount: amt, hours, capped, period: today().slice(0, 7) }; db.revenue.push(ev); return { ev, total: r2(recognized + amt), limit: c.amount }; } // ---- Create Accounting: Project Costing (labor only; supplier costs were accounted in Payables) function createAccounting(role, p) { if (!['project_accountant', 'project_accountant_2'].includes(role)) throw err(403, 'FORBIDDEN', `Persona ${role} cannot run Create Accounting for Project Costing.`); const mode = String(p.mode || p.accountingMode || 'Final'); const tr = String(p.transferToGL || 'No') === 'Yes'; const post = String(p.postInGL || 'No') === 'Yes'; const todo = db.items.filter((i) => i.type === LABOR_TYPE && i.status === 'COSTED' && !i.accounting); if (mode === 'Final') todo.forEach((i) => { const a = Math.abs(i.rawCost); const dr = i.rawCost >= 0; i.accounting = { status: 'ACCOUNTED', transferred: tr, posted: tr && post, lines: [{ cls: 'Project Expense', account: ACCT.expense, dr: dr ? a : 0, cr: dr ? 0 : a }, { cls: 'Labor Clearing', account: ACCT.laborClearing, dr: dr ? 0 : a, cr: dr ? a : 0 }] }; }); return { todo, mode, tr, post }; } const PROCESSES = { 'Import Payroll Costs': { roles: PERMS['cost.manage'], run: (role, p, proc) => { const r = importPayroll(role, p); proc.log = `${r.length} labor row(s) imported.`; } }, 'Import and Process Cost Transactions': { roles: PERMS['cost.manage'], run: (role, p, proc) => { const r = processCosts(role, p); proc.log = `${r.done.length} ${p.transactionSource === LABOR_SOURCE ? 'labor ' : ''}transaction(s) costed; ${r.left} unprocessed.${r.errors.map((e) => ` ${e.person}: ${e.error}`).join('')}`; } }, 'Import Costs': { roles: PERMS['cost.manage'], run: (role, p, proc) => { const r = importAp(role, p); proc.log = `${r.length} Payables cost(s) imported: ${r.map((u) => `${u.document} ${u.rawCost.toFixed(2)}`).join(', ') || 'none'}.`; } }, 'Process Cost Transactions': { roles: PERMS['cost.manage'], run: (role, p, proc) => { const r = processCosts(role, p); proc.log = `${r.done.length} transaction(s) costed; ${r.left} unprocessed.`; } }, 'Generate Invoices': { roles: PERMS['billing.manage'], run: (role, p, proc) => { const i = generateInvoices(role, p); proc.log = i ? `Draft invoice ${i.number}: ${i.lines.reduce((a, l) => a + l.qty, 0)} hours x ${RATES.bill.toFixed(2)} bill rate = ${i.amount.toFixed(2)}.` : 'No billable transactions.'; } }, 'Submit Interface Streamline Request': { roles: PERMS['billing.manage'], run: (role, p, proc) => { const r = transferToAr(role, p); proc.log = `${r.imported.length + r.rejected.length} invoice(s) transferred (${r.imported.map((i) => `${i.number} ${i.amount.toFixed(2)}`).join(', ') || 'none'}); AutoInvoice imported ${r.imported.length}, rejected ${r.rejected.length}.`; } }, 'Generate Revenue': { roles: PERMS['revenue.run'], run: (role, p, proc) => { const r = generateRevenue(role, p); proc.log = `Revenue ${r.ev.amount.toFixed(2)} (${r.ev.hours} x ${RATES.bill.toFixed(2)}) recognized for period ${r.ev.period}; revenue limit ${r.limit.toFixed(2)} ${r.ev.capped ? 'reached' : 'not exceeded'}.`; } }, 'Create Accounting__ppm': { name: 'Create Accounting', roles: ['project_accountant', 'project_accountant_2'], dispatch: { param: 'subledger', value: 'Project Costing' }, run: (role, p, proc) => { const r = createAccounting(role, p); proc.log = `Project Costing: ${r.todo.length} expenditure item(s) accounted in ${r.mode} mode; transferred to GL: ${r.tr ? 'Yes' : 'No'}; posted: ${r.post ? 'Yes' : 'No'}.`; } }, }; reset(); module.exports = { PERSONAS, PERMS, can, assertCan, BU, LABOR_SOURCE, LABOR_TYPE, SUPPLIER_TYPE, RATES, ACCT, CONTRACT_TYPE, CUSTOMER, PROCESSES, FILES, reset, project, projectsFor, createProject, transferItem, approveAdjustment, codeApInvoice, createContract, submitContract, approveContract, contract, invoice, approveInvoice, releaseInvoice, generateInvoices, list: (k) => db[k] };