File size: 25,647 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
'use strict';
/*

 * P2P procurement depth (P2 cases P2P-AGR-001..003, CFL-001, CTL-002, NEG-001, INT-016/017): blanket purchase agreements with price

 * breaks / amount limits / controls, orders released against them, agreement import + released-amount recalculation, negotiations

 * (styles, templates, response rules), terms templates (default per document type, revisions), procurement-depth REST resources and

 * ESS jobs. MOCK; NOT Oracle software; synthetic data. ASSUMED rules: price break by order quantity on the agreement; over-release check =

 * stored released + new order amount <= amount limit; expired agreement -> 'Closed for Receiving'; terms template default per document

 * type in ZZ BU1, new documents capture the default template revision at creation; negotiation style ZZ Sealed RFQ = sealed, no partial

 * quantity; ESS job names for INT-017 are ASSUMED (DR-PRD-INT-001.ess_jobs is empty).

 */
const express = require('express');
const U = require('../../core/ui');
const { err, AppError } = require('../../core/errors');
const { r2, list, filt, files } = require('../../core/kit');
const { esc, inp, sel, hid, btn, form, table, tr, money, dl, layout } = U;

const PERSONAS = { terms_library_admin: { label: 'Terms Library Administrator', bus: [] } };
const BUYERS = ['buyer', 'category_manager'];
const STYLES = { 'ZZ Sealed RFQ': { sealed: true, partialQuantity: false, label: 'Sealed; partial quantity not allowed' }, 'ZZ Open Auction': { sealed: false, partialQuantity: true, label: 'Open; partial quantity allowed' } };
const NEG_TEMPLATES = ['ZZ Template'];
const DOC_TYPES = ['Purchase Order', 'Contract', 'Negotiation', 'Purchase Agreement'];
const CLAUSE_LIB = ['ZZ Limitation of Liability'];
const F = files();
let db;
const nextId = (k) => (db.seq[k] = (db.seq[k] || 0) + 1);
const today = () => new Date().toISOString().slice(0, 10);
const addDays = (n) => { const d = new Date(); d.setDate(d.getDate() + n); return d.toISOString().slice(0, 10); };
function reset() {
  F.reset();
  db = { seq: {}, agreements: [], orders: [], negotiations: [], templates: [],
    negResponses: [{ NegotiationNumber: 'ZZ-NEG-A-001', Supplier: 'ZZ Supplier A (MOCK)', ResponseNumber: 'ZZ-RSP-001', ResponseStatus: 'Active', ResponseAmount: 12000, Currency: 'USD' }],
    qualResponses: [{ QuestionnaireNumber: 'ZZ-QST-A-001', Supplier: 'ZZ Supplier A (MOCK)', QuestionCode: 'ZZ-ISO9001', Question: 'ZZ ISO 9001 certified? (MOCK)', Response: 'Yes', ResponseStatus: 'Accepted' }] };
  mkAgreement({ number: 'ZZ-BPA-001', description: 'ZZ Toner BPA (MOCK)', supplier: 'ZZ Supplier A (MOCK)', breaks: [{ min: 1, price: 10 }, { min: 100, price: 9 }], limit: 5000, lines: [{ item: 'ZZ-TONER (MOCK)', price: 10 }] });
  // DR-PRD-AGR-001: released 4,500.00 backed by one seeded release order (500 x 9.00).
  db.orders.push({ id: 'BPO-SEED', number: 'ZZ-BPO-SEED-001', agreement: 'ZZ-BPA-001', supplier: 'ZZ Supplier A (MOCK)', bu: 'ZZ BU1', quantity: 500, price: 9, amount: 4500, terms: null, by: 'SYSTEM' });
  db.agreements[0].released = 4500;
  mkTemplate({ name: 'ZZ Contract Terms (MOCK)', docType: 'Contract', clauses: ['ZZ Standard Payment Terms (MOCK)'] });
  mkTemplate({ name: 'ZZ Negotiation Terms (MOCK)', docType: 'Negotiation', clauses: ['ZZ Bid Validity (MOCK)'] });
}
function mkAgreement({ number, description = '', supplier = 'ZZ Supplier A (MOCK)', breaks, limit, lines = [], bus = ['ZZ BU1', 'ZZ BU2'], autoPo = true, expiry = addDays(180), source = null }) {
  const a = { id: `BPA-ZZ-${nextId('BPA')}`, number: number || `ZZ-BPA-${100 + db.seq.BPA}`, description, supplier, breaks: breaks || [{ min: 1, price: (lines[0] || {}).price || 0 }], limit: r2(limit), released: 0, lines, bus, autoPo, expiry, source };
  db.agreements.push(a); return a;
}
const status = (a) => (a.expiry < today() ? 'Closed for Receiving' : 'Open');
function findAgreement(id) { const a = db.agreements.find((x) => x.id === id || x.number === id); if (!a) throw err(404, 'NOT_FOUND', `Agreement ${id} not found.`); return a; }
const priceFor = (a, qty) => [...a.breaks].sort((x, y) => y.min - x.min).find((b) => qty >= b.min).price;
const releasedFromOrders = (a) => r2(db.orders.filter((o) => o.agreement === a.number).reduce((s, o) => s + o.amount, 0));
// Terms templates
function mkTemplate({ name, docType, clauses = [], bu = 'ZZ BU1', by = 'SYSTEM' }) {
  const t = { id: `TT-${nextId('TT')}`, name, docType, bu, revisions: [{ rev: 1, clauses: [...clauses], status: by === 'SYSTEM' ? 'Active' : 'Draft' }], by, isDefault: by === 'SYSTEM' };
  db.templates.push(t); return t;
}
const activeRev = (t) => [...t.revisions].reverse().find((r) => r.status === 'Active');
function defaultTerms(docType, bu = 'ZZ BU1') {
  const t = [...db.templates].reverse().find((x) => x.docType === docType && x.bu === bu && x.isDefault && activeRev(x)); if (!t) return null;
  const r = activeRev(t); return { template: t.name, rev: r.rev, clauses: [...r.clauses] };
}
function findTemplate(id) { const t = db.templates.find((x) => x.id === id || x.name === id); if (!t) throw err(404, 'NOT_FOUND', `Terms template ${id} not found.`); return t; }
const needTla = (role) => { if (role !== 'terms_library_admin') throw new AppError(403, 'FORBIDDEN', `Persona ${role} may not maintain terms templates.`); };
function draftTemplate(role, { name, docType }) {
  needTla(role); if (!name) throw err(400, 'VALIDATION', 'Name is required.'); if (!DOC_TYPES.includes(docType)) throw err(400, 'VALIDATION', 'Document Type is required.');
  if (db.templates.find((t) => t.name === name)) throw err(409, 'DUPLICATE', `Template ${name} already exists.`);
  return mkTemplate({ name, docType, by: role });
}
function addClause(role, id) { needTla(role); const t = findTemplate(id); const r = t.revisions[t.revisions.length - 1]; if (r.status !== 'Draft') throw err(409, 'INVALID_STATE', 'Only draft revisions can be edited.'); r.clauses.push(CLAUSE_LIB[0]); return t; }
function submitTemplate(role, id) {
  needTla(role); const t = findTemplate(id); const r = t.revisions[t.revisions.length - 1];
  if (r.status !== 'Draft') throw err(409, 'INVALID_STATE', `Template ${t.name} revision ${r.rev} is ${r.status}.`); if (!r.clauses.length) throw err(400, 'VALIDATION', 'Add at least one clause.');
  t.revisions.filter((x) => x.status === 'Active').forEach((x) => { x.status = 'Superseded'; }); r.status = 'Active'; // ASSUMED: auto-approved on submit
  db.templates.filter((x) => x.docType === t.docType && x.bu === t.bu).forEach((x) => { x.isDefault = false; }); t.isDefault = true; return t;
}
function reviseTemplate(role, id) {
  needTla(role); const t = findTemplate(id); const cur = activeRev(t); if (!cur) throw err(409, 'INVALID_STATE', 'No active revision to revise.');
  t.revisions.push({ rev: cur.rev + 1, clauses: [...cur.clauses, `ZZ Revision ${cur.rev + 1} Note (MOCK)`], status: 'Draft' }); return submitTemplate(role, id);
}
// Orders against agreements
function createOrder(role, { agreement, quantity, bu = 'ZZ BU1' }) {
  if (!BUYERS.includes(role)) throw new AppError(403, 'FORBIDDEN', `Persona ${role} may not create orders.`);
  const a = findAgreement(agreement); const qty = Number(quantity); if (!(qty > 0)) throw err(400, 'VALIDATION', 'Quantity must be greater than zero.');
  if (status(a) !== 'Open') throw err(409, 'AGREEMENT_CLOSED', `Agreement ${a.number} is ${status(a)}; no new releases.`);
  if (!a.bus.includes(bu)) throw err(403, 'BU_ACCESS', `Agreement ${a.number} is not enabled for ${bu}.`);
  const price = priceFor(a, qty); const amount = r2(qty * price);
  if (r2(a.released + amount) > a.limit) throw err(409, 'OVER_RELEASE', `Over-release prevented: agreement ${a.number} amount limit ${a.limit.toFixed(2)} with ${a.released.toFixed(2)} released; ${qty} x ${price.toFixed(2)} = ${amount.toFixed(2)} would exceed.`);
  const o = { id: `BPO-${nextId('BPO')}`, number: `ZZ-BPO-${1000 + db.seq.BPO}`, agreement: a.number, supplier: a.supplier, bu, quantity: qty, price, amount, terms: defaultTerms('Purchase Order', bu), by: role };
  a.released = r2(a.released + amount); db.orders.push(o); return o;
}
function findOrder(id) { const o = db.orders.find((x) => x.id === id || x.number === id); if (!o) throw err(404, 'NOT_FOUND', `Order ${id} not found.`); return o; }
function importAgreements(role, { dataFile }) {
  if (!BUYERS.includes(role) && role !== 'integration_user') throw new AppError(403, 'FORBIDDEN', 'Not authorized to import agreements.');
  const rows = F.rows(dataFile); const made = [];
  for (const num of [...new Set(rows.map((r) => r.AgreementNumber))]) {
    const rs = rows.filter((r) => r.AgreementNumber === num); if (db.agreements.find((a) => a.number === num)) throw err(409, 'DUPLICATE', `Agreement ${num} already exists.`);
    made.push(mkAgreement({ number: num, description: 'Imported (MOCK)', supplier: rs[0].Supplier, limit: Number(rs[0].AmountLimit), lines: rs.map((r) => ({ item: r.Item, price: Number(r.Price) })) }));
  }
  return { agreements: made, lines: made.reduce((s, a) => s + a.lines.length, 0) };
}
function recalcReleased(role, { agreement }) {
  if (!BUYERS.includes(role) && role !== 'integration_user') throw new AppError(403, 'FORBIDDEN', 'Not authorized to recalculate released amounts.');
  const a = findAgreement(agreement); const before = a.released; a.released = releasedFromOrders(a);
  return { agreement: a, before, after: a.released, orders: db.orders.filter((o) => o.agreement === a.number).length };
}
// Negotiations
function createNegotiation(role, { style, template, title }) {
  if (role !== 'category_manager') throw new AppError(403, 'FORBIDDEN', `Persona ${role} may not create negotiations.`);
  if (!STYLES[style]) throw err(400, 'VALIDATION', 'Style is required.'); if (!NEG_TEMPLATES.includes(template)) throw err(400, 'VALIDATION', 'Template is required.');
  const n = { id: `NEG-${nextId('NEG')}`, number: `ZZ-NEG-${2000 + db.seq.NEG}`, title: title || 'ZZ Negotiation (MOCK)', style, template, rules: STYLES[style], terms: defaultTerms('Negotiation'), status: 'Draft' };
  db.negotiations.push(n); return n;
}
function findNegotiation(id) { const n = db.negotiations.find((x) => x.id === id || x.number === id); if (!n) throw err(404, 'NOT_FOUND', `Negotiation ${id} not found.`); return n; }
function validateNegotiation(n) { const e = []; if (!n.terms) e.push('negotiation terms missing'); if (!n.rules) e.push('response rules missing'); return e; }
function publishNegotiation(role, id) {
  const n = findNegotiation(id); if (role !== 'category_manager') throw new AppError(403, 'FORBIDDEN', 'Only the category manager publishes negotiations.');
  const e = validateNegotiation(n); if (e.length) throw err(400, 'VALIDATION', `Cannot publish: ${e.join('; ')}.`); n.status = 'Published'; n.publishedAt = new Date().toISOString(); return n;
}
const PROC_ROLES = ['buyer', 'category_manager', 'integration_user'];
const PROCESSES = {
  'Import Blanket Agreements': { roles: PROC_ROLES, run: (role, p, proc) => { const r = importAgreements(role, p); proc.log = `Imported ${r.agreements.length} agreement(s) with ${r.lines} line(s): ${r.agreements.map((a) => a.number).join(', ')}.`; } },
  'Recalculate Released Amount': { roles: PROC_ROLES, run: (role, p, proc) => { const r = recalcReleased(role, p); proc.log = `Agreement ${r.agreement.number}: released amount ${r.after.toFixed(2)} recalculated from ${r.orders} order(s) (was ${r.before.toFixed(2)}); matches POs.`; } },
  'Requalify Suppliers': { roles: PROC_ROLES, run: (role, p, proc) => { proc.log = `Requalification: ${db.qualResponses.length} questionnaire response(s) evaluated; 0 qualification(s) expired.`; } },
  'Run Spend Classification Batch': { roles: PROC_ROLES, run: (role, p, proc) => { proc.log = `Spend classification: ${db.orders.length} agreement order line(s) classified; 0 unclassified.`; } },
  'Validate Negotiation': { roles: PROC_ROLES, run: (role, p, proc) => { const n = findNegotiation(p.negotiation); const e = validateNegotiation(n); if (e.length) throw err(400, 'VALIDATION', e.join('; ')); proc.log = `Negotiation ${n.number}: 0 validation errors.`; } },
  'Publish Negotiation': { roles: ['category_manager'], run: (role, p, proc) => { const n = publishNegotiation(role, p.negotiation); proc.log = `Negotiation ${n.number} published (${n.rules.label}).`; } },
  'Build Procurement Text Index': { roles: PROC_ROLES, run: (role, p, proc) => { proc.log = `Text index rebuilt: ${db.agreements.length} agreement(s), ${db.negotiations.length} negotiation(s) indexed.`; } },
};
const SCHEMAS = {
  purchaseAgreements: [['AgreementNumber', 'string'], ['Supplier', 'string'], ['Status', 'string'], ['AmountLimit', 'number'], ['ReleasedAmount', 'number'], ['AutomaticPOCreationFlag', 'boolean'], ['BusinessUnitAccess', 'string'], ['ExpirationDate', 'date'], ['SourceContract', 'string']],
  contractTerms: [['DocumentType', 'string'], ['DocumentNumber', 'string'], ['TemplateName', 'string'], ['TemplateRevision', 'number'], ['ClauseTitle', 'string']],
  supplierNegotiationResponses: [['NegotiationNumber', 'string'], ['Supplier', 'string'], ['ResponseNumber', 'string'], ['ResponseStatus', 'string'], ['ResponseAmount', 'number'], ['Currency', 'string']],
  supplierQualificationQuestionResponses: [['QuestionnaireNumber', 'string'], ['Supplier', 'string'], ['QuestionCode', 'string'], ['Question', 'string'], ['Response', 'string'], ['ResponseStatus', 'string']],
};
const agrOut = (a) => ({ AgreementNumber: a.number, Description: a.description, Supplier: a.supplier, Status: status(a), AmountLimit: a.limit, ReleasedAmount: a.released, AutomaticPOCreationFlag: a.autoPo, BusinessUnitAccess: a.bus.join(', '), ExpirationDate: a.expiry, SourceContract: a.source,
  lines: a.lines.map((l, i) => ({ LineNumber: i + 1, Item: l.item, Price: l.price })), priceBreaks: a.breaks.map((b) => ({ MinimumQuantity: b.min, Price: b.price })) });
function termsRows() {
  const PC = require('./contracts');
  const rows = [];
  const push = (DocumentType, DocumentNumber, t) => (t ? t.clauses.map((c) => rows.push({ DocumentType, DocumentNumber, TemplateName: t.template, TemplateRevision: t.rev, ClauseTitle: c })) : null);
  db.orders.forEach((o) => push('Purchase Order', o.number, o.terms)); db.negotiations.forEach((n) => push('Negotiation', n.number, n.terms));
  PC.list().forEach((c) => (c.terms ? push('Contract', c.number, { ...c.terms, clauses: c.clauses.map((x) => x.title) }) : null));
  return rows;
}
const INTEGRATION = ['integration_user', 'buyer', 'category_manager', 'contract_author'];
const okInt = (role) => { if (!INTEGRATION.includes(role)) throw new AppError(403, 'FORBIDDEN', `Persona ${role} is not authorized.`); };
const fx = express.Router();
fx.get('/purchaseAgreements', U.wrap((req, role) => { okInt(role); return list(filt(db.agreements.map(agrOut), req.query.q)); }));
fx.get('/contractTerms', U.wrap((req, role) => { okInt(role); return list(filt(termsRows(), req.query.q)); }));
fx.get('/supplierNegotiationResponses', U.wrap((req, role) => { okInt(role); return list(filt(db.negResponses, req.query.q)); }));
fx.get('/supplierQualificationQuestionResponses', U.wrap((req, role) => { okInt(role); return list(filt(db.qualResponses, req.query.q)); }));

const termsTable = (t) => (t ? `<p>Terms template <strong data-testid="terms-template">${esc(t.template)}</strong> revision <strong data-testid="terms-rev">${t.rev}</strong></p>` + table('Clauses', ['Clause'], t.clauses.map((c) => tr([esc(c)]))) : '<p data-testid="terms-template">No default terms template.</p>');
const tabs = (base, cur, names) => `<div role="tablist">${names.map(([k, n]) => `<a role="tab" aria-selected="${cur === k}" href="${base}?tab=${k}">${esc(n)}</a>`).join(' ')}</div>`;
const need = (ok, role) => { if (!ok) throw new AppError(403, 'FORBIDDEN', `You are not authorized to access this page (persona ${role}).`); };
const TASKS = [
  ['Purchase Agreements', '/p2p/agreements', (r) => BUYERS.includes(r)],
  ['Negotiations', '/p2p/negotiations', (r) => r === 'category_manager'],
  ['Terms Templates', '/p2p/terms-templates', (r) => r === 'terms_library_admin'],
];
function mount(app, rest) {
  const api = express.Router();
  api.post('/files', U.wrap((req, role) => U.created(F.stage(role, req.body))));
  api.post('/agreements', U.wrap((req, role) => { need(BUYERS.includes(role), role); return U.created(mkAgreement(req.body)); }));
  api.post('/orders', U.wrap((req, role) => U.created(createOrder(role, req.body))));
  api.get('/agreements/:id', U.wrap((req, role) => { okInt(role); return agrOut(findAgreement(req.params.id)); }));
  app.use('/api/p2p-depth', api);
  app.use(rest, fx);
  // ---- agreements
  app.get('/p2p/agreements', U.page((req, role) => { need(BUYERS.includes(role), role); const q = (req.query.agreement || '').trim();
    const rows = db.agreements.filter((a) => !q || a.number === q); const one = q && rows.length === 1 ? rows[0] : null;
    return layout(req, role, 'Purchase Agreements', form('/p2p/agreements', inp('agreement', 'Agreement', { value: q }) + btn('Search'), 'get') +
      table('Agreements', ['Agreement', 'Supplier', 'Amount Limit', 'Released Amount', 'Status'], rows.map((a) => tr([esc(a.number), esc(a.supplier), money(a.limit), money(a.released), status(a)]))) +
      (one ? `<section aria-label="Controls"><h2>Controls</h2>${dl([['Automatic PO Creation', one.autoPo ? 'Yes' : 'No', 'agr-auto-po'], ['Business Unit Access', esc(one.bus.join(', ')), 'agr-bu-access'], ['Expiration Date', esc(one.expiry), 'agr-expiry'], ['Status', status(one), 'agr-status'], ['Status After Expiration', 'Closed for Receiving', 'agr-after-expiry']])}</section>` +
        table('Price Breaks', ['Minimum Quantity', 'Price'], one.breaks.map((b) => tr([b.min, money(b.price)]))) : '') + (q && !rows.length ? '<p data-testid="no-results">No results found.</p>' : '')); }, 'p2p'));
  // ---- orders against agreements (Create Order button on Manage Orders)
  app.get('/p2p/agreement-orders/new', U.page((req, role) => { need(BUYERS.includes(role), role);
    const opts = db.agreements.filter((a) => status(a) === 'Open').map((a) => [a.number, a.number]);
    const data = Object.fromEntries(db.agreements.map((a) => [a.number, { breaks: a.breaks, limit: a.limit, released: a.released }]));
    const js = `<script>const AG=${JSON.stringify(data)};function calc(){const a=AG[document.getElementById('bpo-agr').value];const q=Number(document.getElementById('bpo-qty').value)||0;if(!a||!q){return;}const p=[...a.breaks].sort((x,y)=>y.min-x.min).find(b=>q>=b.min).price;const amt=Math.round(q*p*100)/100;document.querySelector('[data-testid=bpo-price]').textContent=p.toFixed(2);document.querySelector('[data-testid=bpo-amount]').textContent=amt.toFixed(2);document.querySelector('[data-testid=bpo-limit-check]').textContent=(a.released+amt>a.limit)?('Over-release: limit '+a.limit.toFixed(2)+' with '+a.released.toFixed(2)+' released; '+q+' x '+p.toFixed(2)+' = '+amt.toFixed(2)+' would exceed'):'Within agreement limit';}</script>`;
    const agrSel = `<div class="f"><label for="bpo-agr">Source Agreement</label> <select id="bpo-agr" name="agreement" onchange="calc()"><option value=""></option>${opts.map(([v, t]) => `<option value="${esc(v)}">${esc(t)}</option>`).join('')}</select></div>`;
    return layout(req, role, 'Create Order', form('/p2p/agreement-orders/new', agrSel +
      `<div class="f"><label for="bpo-qty">Quantity</label> <input id="bpo-qty" name="quantity" type="number" min="1" oninput="calc()"></div>` + sel('bu', 'Procurement BU', ['ZZ BU1', 'ZZ BU2']) +
      `<p>Price: <span data-testid="bpo-price"></span>; Amount: <span data-testid="bpo-amount"></span>; <span data-testid="bpo-limit-check"></span></p>` + hid('__back', '/p2p/agreement-orders/new') + btn('Create')) + js); }, 'p2p'));
  app.post('/p2p/agreement-orders/new', U.act((req, role) => { const o = createOrder(role, req.body); return [`/p2p/agreement-orders/${o.id}`, `Order ${o.number} created against ${o.agreement}: ${o.quantity} x ${o.price.toFixed(2)} = ${o.amount.toFixed(2)}.`]; }, 'p2p'));
  app.get('/p2p/agreement-orders/:id', U.page((req, role) => { need(BUYERS.includes(role), role); const o = findOrder(req.params.id); const tab = req.query.tab || 'general';
    return layout(req, role, `Order ${o.number}`, tabs(`/p2p/agreement-orders/${o.id}`, tab, [['general', 'General'], ['terms', 'Contract Terms']]) +
      (tab === 'terms' ? termsTable(o.terms) : dl([['Order', esc(o.number), 'bpo-number'], ['Source Agreement', esc(o.agreement)], ['Procurement BU', esc(o.bu)], ['Quantity', o.quantity], ['Price', money(o.price), 'bpo-order-price'], ['Amount', money(o.amount), 'bpo-order-amount']]))); }, 'p2p'));
  // ---- negotiations
  app.get('/p2p/negotiations', U.page((req, role) => { need(role === 'category_manager', role);
    return layout(req, role, 'Negotiations', form('/p2p/negotiations/new', btn('Create Negotiation'), 'get') + table('Negotiations', ['Negotiation', 'Style', 'Status'], db.negotiations.map((n) => tr([`<a href="/p2p/negotiations/${n.id}">${esc(n.number)}</a>`, esc(n.style), esc(n.status)])))); }, 'p2p'));
  app.get('/p2p/negotiations/new', U.page((req, role) => { need(role === 'category_manager', role);
    return layout(req, role, 'Create Negotiation', form('/p2p/negotiations/new', sel('style', 'Style', ['', ...Object.keys(STYLES)]) + sel('template', 'Template', ['', ...NEG_TEMPLATES]) + hid('__back', '/p2p/negotiations/new') + btn('Publish'))); }, 'p2p'));
  app.post('/p2p/negotiations/new', U.act((req, role) => { const n = createNegotiation(role, req.body); publishNegotiation(role, n.id); return [`/p2p/negotiations/${n.id}`, `Negotiation ${n.number} published.`]; }, 'p2p'));
  app.get('/p2p/negotiations/:id', U.page((req, role) => { need(role === 'category_manager', role); const n = findNegotiation(req.params.id); const tab = req.query.tab || 'general';
    return layout(req, role, `Negotiation ${n.number}`, tabs(`/p2p/negotiations/${n.id}`, tab, [['general', 'General'], ['terms', 'Contract Terms']]) +
      (tab === 'terms' ? termsTable(n.terms) : dl([['Negotiation', esc(n.number), 'neg-number'], ['Style', esc(n.style)], ['Template', esc(n.template)], ['Status', esc(n.status), 'neg-status']]) +
        `<section aria-label="Response Rules"><h2>Response Rules</h2><p data-testid="neg-rules">${n.rules.sealed ? 'Sealed responses' : 'Open responses'}; partial quantity ${n.rules.partialQuantity ? 'allowed' : 'not allowed'}</p></section>`)); }, 'p2p'));
  // ---- terms templates
  app.get('/p2p/terms-templates', U.page((req, role) => { need(role === 'terms_library_admin', role); const q = (req.query.template || '').trim();
    const rows = db.templates.filter((t) => !q || t.name === q);
    return layout(req, role, 'Terms Templates', form('/p2p/terms-templates', inp('template', 'Template', { value: q }) + btn('Search'), 'get') + form('/p2p/terms-templates/new', btn('Create Terms Template'), 'get') +
      table('Terms Templates', ['Template', 'Document Type', 'Revision', 'Status', 'Default', 'Actions'], rows.map((t) => { const r = t.revisions[t.revisions.length - 1];
        return tr([`<a href="/p2p/terms-templates/${t.id}">${esc(t.name)}</a>`, esc(t.docType), r.rev, esc(r.status), t.isDefault ? 'Yes' : 'No', activeRev(t) ? form(`/p2p/terms-templates/${t.id}/revise`, hid('__back', '/p2p/terms-templates') + btn('Revise')) : '']); }))); }, 'p2p'));
  app.get('/p2p/terms-templates/new', U.page((req, role) => { need(role === 'terms_library_admin', role);
    return layout(req, role, 'Create Terms Template', form('/p2p/terms-templates/new', inp('name', 'Name') + sel('docType', 'Document Type', ['', ...DOC_TYPES]) + hid('__back', '/p2p/terms-templates/new') + btn('Add Clause'))); }, 'p2p'));
  app.post('/p2p/terms-templates/new', U.act((req, role) => { const t = draftTemplate(role, req.body); addClause(role, t.id); return [`/p2p/terms-templates/${t.id}`, `Clause ${CLAUSE_LIB[0]} added to ${t.name}.`]; }, 'p2p'));
  app.get('/p2p/terms-templates/:id', U.page((req, role) => { need(role === 'terms_library_admin', role); const t = findTemplate(req.params.id); const r = t.revisions[t.revisions.length - 1];
    return layout(req, role, `Terms Template ${t.name}`, dl([['Template', esc(t.name), 'tt-name'], ['Document Type', esc(t.docType)], ['Revision', r.rev, 'tt-rev'], ['Status', esc(r.status), 'tt-status'], ['Default', t.isDefault ? `Yes (${esc(t.bu)})` : 'No', 'tt-default']]) +
      table('Clauses', ['Clause'], r.clauses.map((c) => tr([esc(c)]))) + (r.status === 'Draft' ? form(`/p2p/terms-templates/${t.id}/submit`, hid('__back', `/p2p/terms-templates/${t.id}`) + btn('Submit')) : '')); }, 'p2p'));
  app.post('/p2p/terms-templates/:id/submit', U.act((req, role) => { const t = submitTemplate(role, req.params.id); return [`/p2p/terms-templates/${t.id}`, `Template ${t.name} revision ${activeRev(t).rev} approved and activated; default for ${t.docType} in ${t.bu}.`]; }, 'p2p'));
  app.post('/p2p/terms-templates/:id/revise', U.act((req, role) => { const t = reviseTemplate(role, req.params.id); return [`/p2p/terms-templates?template=${encodeURIComponent(t.name)}`, `Template ${t.name} revision ${activeRev(t).rev} approved; new documents use revision ${activeRev(t).rev}.`]; }, 'p2p'));
}
reset();
module.exports = { PERSONAS, TASKS, PROCESSES, SCHEMAS, mount, reset, mkAgreement, defaultTerms, findAgreement, list: (k) => db[k] };