File size: 8,854 Bytes
af1bee9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | 'use strict';
/*
* Shared shell of the MOCK Fusion-style app (NOT Oracle software; synthetic data; no credentials).
* Owns: persona login, Tasks navigation, Notifications worklist, Scheduled Processes, /api/test/reset, /api/health,
* and GET /fscmRestApi/resources/11.13.18.05/<resource>/describe for every registered schema.
* Module packs are discovered from mock-app/modules/<id>/index.js (folders starting with "_" are templates and skipped).
* MOCK_MODULES=p2p,o2c limits which packs load (default: all).
*/
const fs = require('fs'); const path = require('path');
const express = require('express');
const R = require('./registry');
const U = require('./ui');
const { esc, inp, sel, hid, btn, form, table, tr, money, T, layout, page, act, wrap, created } = U;
const REST_BASE = '/fscmRestApi/resources/11.13.18.05';
function loadPacks(dir = path.join(__dirname, '..', 'modules')) {
const only = (process.env.MOCK_MODULES || '').split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);
return fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.name.startsWith('_') && fs.existsSync(path.join(dir, d.name, 'index.js')))
.map((d) => d.name).sort().filter((n) => !only.length || only.includes(n)).map((n) => require(path.join(dir, n, 'index.js')));
}
function buildApp(packs = loadPacks()) {
packs.forEach(R.register);
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// ---------------- shared internal API
const api = express.Router();
api.get('/health', (req, res) => res.json({ status: 'UP', app: 'mock-fusion', modules: R.packs().map((p) => ({ id: p.id, name: p.name, idPrefix: p.idPrefix })), note: 'local mock, not Oracle Fusion' }));
api.post('/test/reset', (req, res) => res.json(R.reset()));
api.post('/test/ess-durations', wrap((req) => R.setSimDurations(req.body))); // MOCK-only: simulated ESS durations in minutes (SLA-breach scenarios)
api.get('/modules', (req, res) => res.json({ items: R.packs().map((p) => ({ id: p.id, name: p.name, idPrefix: p.idPrefix, personas: Object.keys(p.personas || {}), processes: (p.processes || []).map((d) => d.name), resources: Object.keys(p.schemas || {}) })) }));
api.get('/processes', wrap((req, role) => { if (!R.persona(role)) throw new R.AppError(401, 'UNAUTHENTICATED', 'Unknown persona.'); return { items: R.processes() }; }));
api.get('/processes/:id', wrap((req, role) => { if (!R.persona(role)) throw new R.AppError(401, 'UNAUTHENTICATED', 'Unknown persona.'); const p = R.process(req.params.id); if (!p) throw new R.AppError(404, 'NOT_FOUND', 'Process not found.'); return p; }));
api.post('/processes', wrap((req, role) => created(R.submitProcess(role, req.body))));
// Co-worker Scout endpoints (additive). The mock is ALWAYS a test environment; release is settable for patch-watch demos.
const pod = { release: null };
api.get('/pod/about', (req, res) => res.json({ release: pod.release || process.env.MOCK_RELEASE || '26C', environment: 'test', is_mock: true, note: 'local mock, not Oracle Fusion' }));
api.post('/test/pod/release', (req, res) => {
const r = String((req.body && req.body.release) || '').trim();
if (!r || r.length > 40) return res.status(400).json({ error: 'VALIDATION', message: 'release must be 1-40 chars' });
pod.release = r; res.json({ release: pod.release, note: 'mock-only release override' });
});
app.use('/api', api);
// ---------------- shared REST describe (mounted before pack routers so /<res>/describe never hits /<res>/:id)
const fx = express.Router();
fx.get('/:resource/describe', wrap((req, role) => {
if (!R.persona(role)) throw new R.AppError(401, 'UNAUTHENTICATED', 'Unknown persona.');
const s = R.state.schemas[req.params.resource]; if (!s) throw new R.AppError(404, 'NOT_FOUND', `Resource ${req.params.resource} not found.`);
return { Resources: { [req.params.resource]: { module: s.module, attributes: s.attrs.map(([n, t, m]) => ({ name: n, type: t, mandatory: !!m })) } } };
}));
app.use(REST_BASE, fx);
// ---------------- login / home / worklist
app.get('/login', (req, res) => res.send(layout(req, null, 'Sign In', form('/login', sel('role', 'Persona', R.roles().map((r) => [r, R.persona(r).label])) + btn('Sign In'))).html));
app.post('/login', (req, res) => {
if (!R.persona(req.body.role)) return res.redirect('/login?error=Unknown%20persona');
res.setHeader('Set-Cookie', `mock_role=${req.body.role}; Path=/; ${process.env.MOCK_COOKIE_ATTRS || 'SameSite=Lax'}`); res.redirect('/');
});
app.post('/logout', (req, res) => { res.setHeader('Set-Cookie', 'mock_role=; Path=/; Max-Age=0'); res.redirect('/login'); });
app.get('/', page((req, role) => { const p = R.persona(role); return layout(req, role, 'Home', `<p>Welcome, ${esc(p.label)}. Business units: ${p.bus.join(', ')}. Modules: <span data-testid="persona-modules">${p.modules.join(', ')}</span>.</p>`); }));
app.get('/worklist', page((req, role) => layout(req, role, 'Notifications', table('Notifications', ['Document', 'Type', 'Task', 'Amount'],
R.worklist(role).map((t) => tr([`<a href="${t.href}">${esc(t.docNumber)}</a>`, esc(t.docType), T(t.kind), money(t.amount)], `data-testid="task-${t.docNumber}"`))))));
// ---------------- scheduled processes (shared ESS-style log; parameters = union declared by packs)
R.state.tasks.push({ module: 'core', label: 'Scheduled Processes', href: '/scheduled-processes', allowed: (r) => R.processesFor(r).length > 0 });
const paramField = (d) => d.type === 'select' ? sel(d.name, d.label, typeof d.options === 'function' ? d.options() : d.options) : inp(d.name, d.label, { type: d.type || 'text', value: d.value || '' });
app.get('/scheduled-processes', page((req, role) => {
const mine = R.processesFor(role);
if (!mine.length) throw new R.AppError(403, 'FORBIDDEN', `You are not authorized to access this page (persona ${role} may not run scheduled processes).`);
const rows = R.processes().slice().reverse().map((p) => tr([p.id, esc(p.name), `<span data-testid="process-status-${p.id}">${T(p.status)}</span>`, esc(p.log)], `data-testid="process-${p.id}"`));
const sched = req.query.new ? `<fieldset aria-label="Schedule New Process"><legend>Schedule New Process</legend>${form('/scheduled-processes', sel('name', 'Name', mine.map((d) => d.name)) +
`<fieldset><legend>Process Details</legend>${R.state.params.map(paramField).join('')}</fieldset>` + btn('Submit'))}</fieldset>` : '';
return layout(req, role, 'Scheduled Processes', form('/scheduled-processes', hid('new', '1') + btn('Schedule New Process'), 'get') + sched + table('Processes', ['Process ID', 'Name', 'Status', 'Log'], rows, 'processes-table'));
}));
app.post('/scheduled-processes', act((req, role) => {
const params = {}; for (const d of R.state.params) { const v = req.body[d.name]; if (v !== undefined && v !== '') params[d.name] = v; }
const p = R.submitProcess(role, { name: req.body.name, params });
return ['/scheduled-processes', `Process ${p.id} submitted.`];
}));
// ---------------- shared journals (GL batches contributed by packs; source = Payables, Receivables, ...)
R.state.tasks.push({ module: 'core', label: 'Manage Journals', href: '/journals', allowed: (r) => R.journalRoles().includes(r) });
app.get('/journals', page((req, role) => {
if (!R.journalRoles().includes(role)) throw new R.AppError(403, 'FORBIDDEN', `You are not authorized to access this page (persona ${role} may not view journals).`);
const src = (req.query.source || '').trim().toLowerCase(); const bn = (req.query.batch || '').trim();
const batches = R.journalBatches().filter((b) => (!src || String(b.source).toLowerCase() === src) && (!bn || b.name === bn));
return layout(req, role, 'Manage Journals', form('/journals', inp('batch', 'Journal Batch', { value: bn }) + inp('source', 'Source', { value: req.query.source || '' }) + btn('Search'), 'get') +
batches.map((b) => `<section aria-label="${esc(b.name)}" data-testid="batch-${b.id}"><h2>${b.href ? `<a href="${b.href}">${esc(b.name)}</a>` : esc(b.name)}</h2>${U.dl([['Source', esc(b.source)], ['Batch Status', b.status, `batch-status-${b.id}`], ['Accounting Date', b.accountingDate]])}
${table(`Journal Lines ${b.name}`, ['Source', 'Side', 'Account Class', 'Accounted (USD)'], b.lines.map((l) => tr([esc(l.source), l.side, esc(l.accountClass), money(l.accountedAmount)], `data-testid="journal-line"`)))}</section>`).join(''));
}));
// ---------------- module packs
for (const p of R.packs()) if (p.mount) p.mount({ app, rest: REST_BASE, ui: U, registry: R });
return app;
}
module.exports = { buildApp, loadPacks, REST_BASE };
|