File size: 13,370 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
103
104
105
'use strict';
// PPM pack REST facade, internal API and UI (MOCK Fusion-style; NOT Oracle software; synthetic data). Labels follow the PPM case YAML steps
// (no ui-glossary ppm: section yet); automation keeps them in automation/src/modules/ppm/labels.ts.
const express = require('express');
const S = require('./store');
const O2C = require('../o2c/store');
const U = require('../../core/ui');
const { list, filt } = require('../../core/kit');
const { AppError } = require('../../core/errors');
const { esc, inp, sel, hid, btn, form, table, tr, money, dl, layout, wrap, created } = U;
const page = (fn) => U.page(fn, 'ppm');
const act = (fn) => U.act(fn, 'ppm');
const guard = (role, a) => { if (!S.can(role, a)) throw new AppError(403, 'FORBIDDEN', `You are not authorized to access this page (persona ${role} lacks ${a}).`); };
const none = (rows) => (rows.length ? '' : '<p data-testid="no-results">No results found.</p>');
const T = (s) => esc(String(s || '').toLowerCase().split('_').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' '));
const linkBtn = (href, label) => `<a role="button" href="${href}">${esc(label)}</a>`;
const yn = (b) => (b ? 'Y' : 'N');
/** Search form inside a role=search landmark named after its field (several searches can share a page). */
const search = (action, name, label, value) => `<div role="search" aria-label="${esc(label)}">${form(action, inp(name, label, { value: value || '' }) + btn('Search'), 'get')}</div>`;

const TASKS = [
  ['Manage Projects', '/ppm/projects', (r) => S.can(r, 'project.view')],
  ['Manage Project Costs', '/ppm/costs', (r) => S.can(r, 'cost.manage')],
  ['Manage Project Contracts', '/ppm/contracts', (r) => S.can(r, 'contract.create') || S.can(r, 'contract.approve')],
  ['Manage Project Invoices', '/ppm/billing', (r) => S.can(r, 'billing.manage')],
];
const SCHEMAS = {
  projects: [['ProjectNumber', 'string', true], ['ProjectName', 'string'], ['ProjectManager', 'string'], ['BusinessUnit', 'string']],
  projectExpenditureItems: [['ExpenditureItemId', 'string'], ['ProjectNumber', 'string'], ['TaskNumber', 'string'], ['ExpenditureType', 'string'], ['TransactionSource', 'string'], ['Quantity', 'number'], ['RawCost', 'number'], ['DocumentNumber', 'string'], ['Status', 'string'], ['AccountingStatus', 'string']],
  projectContractInvoices: [['InvoiceNumber', 'string'], ['ContractNumber', 'string'], ['InvoiceAmount', 'number'], ['InvoiceStatus', 'string'], ['ARTransactionNumber', 'string']],
  projectContractRevenue: [['ContractNumber', 'string'], ['RevenueAmount', 'number'], ['RevenueLimit', 'number'], ['LimitExceeded', 'string']],
};
const itemOut = (i, expand) => ({ ExpenditureItemId: i.id, ProjectNumber: i.project, TaskNumber: i.task, ExpenditureType: i.type, TransactionSource: i.source, PersonNumber: i.person, Quantity: i.qty, UnitOfMeasure: i.uom,
  RawCost: i.rawCost, ExpenditureItemDate: i.date, DocumentNumber: i.document, Status: T(i.status), AdjustmentNumber: i.adjustment, AccountingStatus: i.accounting ? 'Accounted' : 'Unaccounted',
  TransferredToGL: yn(i.accounting && i.accounting.transferred), PostedFlag: yn(i.accounting && i.accounting.posted),
  ...(expand ? { distributions: (i.accounting ? i.accounting.lines : []).map((l, k) => ({ LineNumber: k + 1, AccountClass: l.cls, Account: l.account, EnteredDr: l.dr, EnteredCr: l.cr })) } : {}) });
const pvis = (role) => (role === 'integration_user' ? S.list('projects') : S.projectsFor(role)).map((p) => p.number);
const view = (role) => { if (!S.can(role, 'project.view') && role !== 'integration_user') throw new AppError(403, 'FORBIDDEN', 'Not authorized.'); };
const fx = express.Router();
fx.get('/projects', wrap((req, role) => { view(role); return list(filt(S.list('projects').filter((p) => pvis(role).includes(p.number)).map((p) => ({ ProjectNumber: p.number, ProjectName: p.name, ProjectManager: S.PERSONAS[p.manager].label, BusinessUnit: p.bu })), req.query.q)); }));
fx.get('/projectExpenditureItems', wrap((req, role) => { view(role); const ex = String(req.query.expand || '').includes('distributions');
  return list(filt(S.list('items').filter((i) => pvis(role).includes(i.project)).map((i) => itemOut(i, ex)), req.query.q)); }));
fx.get('/projectContractInvoices', wrap((req, role) => { view(role); return list(filt(S.list('invoices').map((i) => ({ InvoiceNumber: i.number, ContractNumber: i.contract, InvoiceAmount: i.amount, InvoiceStatus: T(i.status), ARTransactionNumber: i.arNumber,
  lines: i.lines.map((l) => ({ LineNumber: l.lineNum, ExpenditureItemId: l.itemId, Quantity: l.qty, BillRate: l.rate, Amount: l.amount })) })), req.query.q)); }));
fx.get('/projectContractRevenue', wrap((req, role) => { view(role); return list(filt(S.list('contracts').map((c) => { const amt = S.list('revenue').filter((r) => r.contract === c.number).reduce((a, r) => a + r.amount, 0);
  return { ContractNumber: c.number, RevenueAmount: Math.round(amt * 100) / 100, RevenueLimit: c.amount, LimitExceeded: amt > c.amount ? 'Y' : 'N' }; }), req.query.q)); }));
const api = express.Router();
api.get('/refs', wrap(() => ({ bu: S.BU, laborSource: S.LABOR_SOURCE, laborType: S.LABOR_TYPE, supplierType: S.SUPPLIER_TYPE, rates: S.RATES, contractType: S.CONTRACT_TYPE, customer: S.CUSTOMER, accounts: S.ACCT })));
api.post('/files', wrap((req, role) => { if (!S.can(role, 'cost.manage')) throw new AppError(403, 'FORBIDDEN', 'Not authorized.'); return created(S.FILES.stage(role, req.body)); }));
api.post('/projects', wrap((req, role) => { if (!S.can(role, 'cost.manage')) throw new AppError(403, 'FORBIDDEN', 'Not authorized.'); return created(S.createProject(role, req.body)); }));
api.post('/apInvoiceCoding', wrap((req, role) => created(S.codeApInvoice(role, req.body))));
api.post('/contracts', wrap((req, role) => created(S.createContract(role, req.body))));
api.post('/contracts/:n/submit', wrap((req, role) => S.submitContract(role, req.params.n)));
api.post('/contracts/:n/approve', wrap((req, role) => S.approveContract(role, req.params.n)));
api.post('/invoices/:n/approve', wrap((req, role) => S.approveInvoice(role, req.params.n)));
api.post('/adjustments/:n/approve', wrap((req, role) => S.approveAdjustment(role, req.params.n)));
api.post('/items/:id/transfer', wrap((req, role) => S.transferItem(role, req.params.id, req.body)));

function mount(app, rest) {
  app.use('/api/ppm', api);
  app.use(rest, fx);
  // Projects (project security)
  app.get('/ppm/projects', page((req, role) => { guard(role, 'project.view'); const q = req.query.project; const rows = q !== undefined ? S.projectsFor(role, q) : [];
    return layout(req, role, 'Projects', search('/ppm/projects', 'project', 'Project', q) +
      (q !== undefined ? table('Projects', ['Project', 'Name', 'Project Manager'], rows.map((p) => tr([esc(p.number), esc(p.name), esc(S.PERSONAS[p.manager].label)]))) + none(rows) : '')); }));
  // Project Costs: expenditure items, transfer, cost adjustments (review approval with SoD)
  const label = (i) => (i.person ? `${i.person} ${i.qty} hours` : `${i.document || i.id} ${money(i.rawCost)}`);
  app.get('/ppm/costs', page((req, role) => { guard(role, 'cost.manage'); const q = req.query.project; const a = req.query.adjustment;
    const items = q !== undefined ? S.list('items').filter((i) => (!q || i.project === q)) : []; const adjs = a !== undefined ? S.list('adjustments').filter((x) => !a || x.number === a) : [];
    return layout(req, role, 'Project Costs', search('/ppm/costs', 'project', 'Project', q) +
      (q !== undefined ? table('Expenditure Items', ['Item', 'Task', 'Expenditure Type', 'Quantity', 'Raw Cost', 'Status'], items.map((i) => tr([`<a href="/ppm/costs/items/${i.id}">${esc(label(i))}</a>`, esc(i.task), esc(i.type), i.qty, money(i.rawCost), T(i.status)]))) + none(items) : '') +
      `<section aria-label="Cost Adjustments"><h2>Cost Adjustments</h2>${search('/ppm/costs', 'adjustment', 'Adjustment', a)}` +
      (a !== undefined ? table('Cost Adjustments', ['Adjustment', 'Type', 'Quantity', 'Amount', 'Created By', 'Status', 'Action'], adjs.map((x) => tr([esc(x.number), esc(x.type), x.qty, money(x.cost), esc(S.PERSONAS[x.createdBy].label), T(x.status),
        x.status !== 'PENDING_APPROVAL' ? '' : x.createdBy === role ? 'Cannot approve own adjustment (segregation of duties)' : form(`/ppm/costs/adjustments/${x.number}/approve`, btn('Approve'))]))) + none(adjs) : '') + '</section>'); }));
  app.post('/ppm/costs/adjustments/:n/approve', act((req, role) => { const x = S.approveAdjustment(role, req.params.n); return [`/ppm/costs?adjustment=${x.number}`, `Adjustment ${x.number} approved.`]; }));
  app.get('/ppm/costs/items/:id', page((req, role) => { guard(role, 'cost.manage'); const i = S.list('items').find((x) => x.id === req.params.id); if (!i) throw new AppError(404, 'NOT_FOUND', 'Expenditure item not found.');
    const pr = S.project(null, i.project);
    return layout(req, role, `Expenditure Item ${i.id}`, dl([['Item', esc(i.id), 'ppm-ei-id'], ['Project', esc(i.project)], ['Task', esc(i.task), 'ppm-ei-task'], ['Quantity', i.qty, 'ppm-ei-qty'], ['Raw Cost', money(i.rawCost), 'ppm-ei-raw']]) +
      (req.query.transfer ? `<fieldset role="group" aria-label="Transfer"><legend>Transfer</legend>${form(`/ppm/costs/items/${i.id}/transfer`, sel('task', 'Task', pr.tasks.filter((t) => t !== i.task)) + inp('qty', 'Quantity', { type: 'number', attrs: 'step="any"' }) + hid('__back', `/ppm/costs/items/${i.id}`) + btn('Submit'))}</fieldset>`
        : linkBtn(`/ppm/costs/items/${i.id}?transfer=1`, 'Transfer'))); }));
  app.post('/ppm/costs/items/:id/transfer', act((req, role) => { const r = S.transferItem(role, req.params.id, req.body);
    return [`/ppm/costs?project=${r.pos.project}`, `Transfer ${r.adj.number}: ${r.neg.qty} h (${money(r.neg.rawCost)}) on ${r.neg.task}, +${r.pos.qty} h (+${money(r.pos.rawCost)}) on ${r.pos.task}.`]; }));
  // Contracts
  app.get('/ppm/contracts', page((req, role) => { if (!S.can(role, 'contract.create') && !S.can(role, 'contract.approve') && !S.can(role, 'project.view')) guard(role, 'contract.create');
    const rows = S.list('contracts');
    return layout(req, role, 'Project Contracts', (S.can(role, 'contract.create') ? linkBtn('/ppm/contracts/new', 'Create Contract') : '') +
      table('Contracts', ['Contract', 'Customer', 'Amount', 'Status'], rows.map((c) => tr([`<a href="/ppm/contracts/${c.number}">${esc(c.number)}</a>`, esc(c.customer), money(c.amount), T(c.status)]))) + none(rows)); }));
  app.get('/ppm/contracts/new', page((req, role) => { guard(role, 'contract.create');
    return layout(req, role, 'Create Contract', form('/ppm/contracts/new', sel('type', 'Contract Type', [S.CONTRACT_TYPE]) + sel('customer', 'Customer', O2C.list('customers').map((c) => c.name)) + inp('amount', 'Amount') +
      sel('billPlan', 'Bill Plan', [`T&M at ${S.RATES.schedule}`]) + sel('revenuePlan', 'Revenue Plan', ['T&M']) + inp('project', 'Project', { attrs: 'list="ppm-projects" role="combobox"' }) +
      `<datalist id="ppm-projects">${S.list('projects').map((p) => `<option value="${esc(p.number)}">`).join('')}</datalist>` + hid('__back', '/ppm/contracts/new') + btn('Submit'))); }));
  app.post('/ppm/contracts/new', act((req, role) => { const c = S.submitContract(role, S.createContract(role, req.body).number); return [`/ppm/contracts/${c.number}`, `Contract ${c.number} submitted for approval.`]; }));
  app.get('/ppm/contracts/:n', page((req, role) => { if (!S.can(role, 'contract.create') && !S.can(role, 'contract.approve') && !S.can(role, 'project.view')) guard(role, 'contract.create'); const c = S.contract(req.params.n);
    return layout(req, role, `Contract ${c.number}`, dl([['Contract', esc(c.number), 'ppm-ctr-number'], ['Status', T(c.status), 'ppm-ctr-status'], ['Contract Type', esc(c.type)], ['Customer', esc(c.customer), 'ppm-ctr-customer'], ['Amount', money(c.amount), 'ppm-ctr-amount']]) +
      table('Contract Lines', ['Line', 'Project', 'Bill Plan', 'Revenue Plan', 'Amount'], [tr([1, esc(c.project), esc(c.billPlan), esc(c.revenuePlan), money(c.amount)])]) +
      (c.status === 'PENDING_APPROVAL' && c.approver === role ? form(`/ppm/contracts/${c.number}/approve`, btn('Approve')) : '')); }));
  app.post('/ppm/contracts/:n/approve', act((req, role) => { const c = S.approveContract(role, req.params.n); return [`/ppm/contracts/${c.number}`, `Contract ${c.number} approved; status Active.`]; }));
  // Project billing
  app.get('/ppm/billing', page((req, role) => { guard(role, 'billing.manage'); const q = req.query.invoice; const rows = q !== undefined ? S.list('invoices').filter((i) => !q || i.number === q) : [];
    return layout(req, role, 'Project Billing', search('/ppm/billing', 'invoice', 'Invoice', q) +
      (q !== undefined ? table('Project Invoices', ['Invoice', 'Contract', 'Amount', 'Status', 'Actions'], rows.map((i) => tr([esc(i.number), esc(i.contract), money(i.amount), T(i.status), i.status === 'APPROVED' ? form(`/ppm/billing/${i.number}/release`, btn('Release')) : '']))) + none(rows) : '')); }));
  app.post('/ppm/billing/:n/release', act((req, role) => { const i = S.releaseInvoice(role, req.params.n); return [`/ppm/billing?invoice=${i.number}`, `Invoice ${i.number} released.`]; }));
}
module.exports = { TASKS, SCHEMAS, mount };