scdashboard 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -2
- package/lib/config.js +57 -0
- package/lib/runlayer.js +73 -0
- package/lib/slack.js +59 -0
- package/lib/snapshot.js +235 -0
- package/package.json +10 -4
- package/public/app.js +820 -0
- package/public/index.html +104 -0
- package/public/styles.css +1115 -0
- package/sc.icon.png +0 -0
- package/server.js +130 -0
package/public/app.js
ADDED
|
@@ -0,0 +1,820 @@
|
|
|
1
|
+
/* ============================================================
|
|
2
|
+
SC Record Hygiene — client
|
|
3
|
+
MODULE REGISTRY
|
|
4
|
+
Each module = { id, title, description, soql, rows(snapshot, sc), checks[], rules[] }
|
|
5
|
+
checks: [{ key, label, run(row) -> {s:'pass'|'warn'|'fail'|'na', m:'message'} }]
|
|
6
|
+
Tabs, tiles, filters and table are generated from the registry.
|
|
7
|
+
============================================================ */
|
|
8
|
+
const TODAY = (() => { const t = new Date(); return new Date(t.getFullYear(), t.getMonth(), t.getDate()); })();
|
|
9
|
+
const SF = 'https://pagerduty.lightning.force.com/lightning/r/';
|
|
10
|
+
|
|
11
|
+
/* ---------- helpers ---------- */
|
|
12
|
+
const d = s => s ? new Date(s + 'T00:00:00') : null;
|
|
13
|
+
const days = (a, b) => Math.round((a - b) / 864e5);
|
|
14
|
+
const fmt = dt => dt ? `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}-${String(dt.getDate()).padStart(2, '0')}` : '—';
|
|
15
|
+
const money = n => n == null ? '—' : (n < 0 ? '-$' : '$') + Math.abs(Math.round(n)).toLocaleString();
|
|
16
|
+
function validDate(y, m, dd) { const t = new Date(y, m - 1, dd); return t.getFullYear() === y && t.getMonth() === m - 1 && t.getDate() === dd ? t : null; }
|
|
17
|
+
/* Extract the date at the start of SC Notes.
|
|
18
|
+
Supports mm/dd/yy, mm/dd/yyyy, yy/mm/dd, yyyy/mm/dd ('/', '-', '.' or space separators, e.g. mm.dd.yyyy, yyyy mm dd),
|
|
19
|
+
and mm/dd or mm-dd with no year. The date may follow 2–3 letter initials (e.g. "CB 11.20.25", "NW - 10/15").
|
|
20
|
+
Day-first dates (dd/mm) are accepted: used when month-first is impossible (e.g. 23/10/2026), or when
|
|
21
|
+
month-first would put the note in the future and day-first would not (e.g. 12/10/2026 → 12 Oct).
|
|
22
|
+
A date with no year is taken as this year, or last year if that would put it in the future. */
|
|
23
|
+
function noteDate(notes) {
|
|
24
|
+
if (!notes) return null;
|
|
25
|
+
const text = notes.trim().replace(/^[A-Za-z]{2,3}(?=[\s:.\-–—]*\d)[\s:.\-–—]*/, ''); // drop leading initials
|
|
26
|
+
// Month-first unless that is invalid or in the future while day-first is valid and not.
|
|
27
|
+
const pick = (y, p, q) => {
|
|
28
|
+
const md = validDate(y, p, q), dm = validDate(y, q, p);
|
|
29
|
+
if (md && (md <= TODAY || !dm || dm > TODAY)) return md;
|
|
30
|
+
return dm || md;
|
|
31
|
+
};
|
|
32
|
+
const mt = text.match(/^(\d{1,4})(?:[\/.-]| +)(\d{1,2})(?:[\/.-]| +)(\d{2,4})(?!\d)/);
|
|
33
|
+
if (mt) {
|
|
34
|
+
const [a, b, c] = [mt[1], mt[2], mt[3]];
|
|
35
|
+
const yr = v => v.length === 2 ? 2000 + +v : +v;
|
|
36
|
+
if (a.length === 4) return validDate(+a, +b, +c); // yyyy/mm/dd
|
|
37
|
+
if (c.length === 4) return pick(+c, +a, +b); // mm/dd/yyyy or dd/mm/yyyy
|
|
38
|
+
// mm/dd/yy first; otherwise the most recent non-future of dd/mm/yy and yy/mm/dd.
|
|
39
|
+
const mdy = validDate(yr(c), +a, +b);
|
|
40
|
+
if (mdy && mdy <= TODAY) return mdy;
|
|
41
|
+
const alts = [validDate(yr(c), +b, +a), validDate(yr(a), +b, +c)].filter(Boolean);
|
|
42
|
+
const past = alts.filter(dt => dt <= TODAY).sort((x, y) => y - x);
|
|
43
|
+
return past[0] || mdy || alts[0] || null;
|
|
44
|
+
}
|
|
45
|
+
const md = text.match(/^(\d{1,2})[\/-](\d{1,2})(?![\/-]?\d)/); // mm/dd or mm-dd (or dd/mm), no year
|
|
46
|
+
if (!md) return null;
|
|
47
|
+
const y = TODAY.getFullYear(), p = +md[1], q = +md[2];
|
|
48
|
+
const inYear = (m, d) => { const dt = validDate(y, m, d); return dt && dt > TODAY ? validDate(y - 1, m, d) : dt; };
|
|
49
|
+
return inYear(p, q) || inYear(q, p);
|
|
50
|
+
}
|
|
51
|
+
const isUrl = s => /^https?:\/\//i.test((s || '').trim());
|
|
52
|
+
const tbd = s => !s || !s.trim() || /^\s*TBD\s*$/i.test(s);
|
|
53
|
+
|
|
54
|
+
/* An SC record is stale when its latest dated SC Note is more than STALE_MONTHS months old. */
|
|
55
|
+
const STALE_MONTHS = 3;
|
|
56
|
+
const STALE_CUTOFF = new Date(TODAY.getFullYear(), TODAY.getMonth() - STALE_MONTHS, TODAY.getDate());
|
|
57
|
+
const isStale = r => { if (r.gap) return false; const nd = noteDate(r.notes); return !!nd && nd < STALE_CUTOFF; };
|
|
58
|
+
|
|
59
|
+
/* Flag SC records whose Sales Lead isn't the Opportunity owner (compared by user Id). */
|
|
60
|
+
function leadMismatch(r) {
|
|
61
|
+
if (r.gap || !r.oppOwnerId) return null;
|
|
62
|
+
if (!r.salesLead) return { m: 'Sales Lead not set', t: `The SC record has no Sales Lead. The Opportunity owner is ${r.owner || 'unknown'}.` };
|
|
63
|
+
if (r.salesLead.id !== r.oppOwnerId) return { m: `Sales Lead: ${r.salesLead.name}`, t: `The SC record's Sales Lead (${r.salesLead.name}) is not the Opportunity owner (${r.owner}).` };
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
const leadFlag = r => { const f = leadMismatch(r); return f ? ` <span class="lead-flag" title="${esc(f.t)}">≠ ${esc(f.m)}</span>` : ''; };
|
|
67
|
+
|
|
68
|
+
/* Opportunity Risk Details (SC record) are shown when SC Status is not Green. */
|
|
69
|
+
const showRisk = r => !r.gap && !/^green$/i.test((r.status || '').trim());
|
|
70
|
+
|
|
71
|
+
/* Snapshot age badge: highlighted when over a day old, strongly when over 3 days. */
|
|
72
|
+
function snapshotAge(fetchedAt) {
|
|
73
|
+
const t = new Date(fetchedAt), hours = (Date.now() - t) / 36e5;
|
|
74
|
+
const label = `Salesforce snapshot ${t.toLocaleString()}`;
|
|
75
|
+
if (hours <= 24) return esc(label);
|
|
76
|
+
const d = Math.floor(hours / 24);
|
|
77
|
+
const cls = hours > 72 ? 'snap-age old' : 'snap-age aging';
|
|
78
|
+
return `<span class="${cls}" title="Click Refresh from Salesforce to update">${esc(label)} · ${d} day${d === 1 ? '' : 's'} old</span>`;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/* "All Solution Consultants": every roster SC's snapshot combined into one view. */
|
|
82
|
+
const ALL = '__all';
|
|
83
|
+
const isAll = () => state.sc === ALL;
|
|
84
|
+
const scLabel = () => isAll() ? 'All Solution Consultants' : (state.scs[state.sc] || '');
|
|
85
|
+
function combinedRows(M, s) {
|
|
86
|
+
if (!s.parts) return M.rows(s, state.sc);
|
|
87
|
+
const rows = s.parts.flatMap(p => M.rows(p.snap, p.sc).map(r => ({ ...r, scName: state.scs[p.sc] })));
|
|
88
|
+
// An opp with an SC record (any SC) drops its "no SC record" rows; the same opp listed for several SCs shows once.
|
|
89
|
+
const withRec = new Set(rows.filter(r => !r.gap).map(r => r.oppId));
|
|
90
|
+
const seen = new Set();
|
|
91
|
+
return rows.filter(r => {
|
|
92
|
+
if (r.gap && withRec.has(r.oppId)) return false;
|
|
93
|
+
if (seen.has(r.id)) return false;
|
|
94
|
+
seen.add(r.id); return true;
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const STAGE_LABEL = { 'Probe/Prepare': 'Tech Discovery', 'Practice/Perform': 'Demo' };
|
|
99
|
+
const srcBadge = r => r.acctSC && r.teamSC ? '<span class="src both">Account SC + Opp Team</span>' : r.acctSC ? '<span class="src acct">Account SC</span>' : r.teamSC ? '<span class="src team">Opp Team</span>' : '<span class="src rec">SC record only</span>';
|
|
100
|
+
|
|
101
|
+
/* ---------- Module 1: rows from the server snapshot ---------- */
|
|
102
|
+
/* SC Notes: use the SC record's Notes; if blank, fall back to the Opportunity's SC Notes field. */
|
|
103
|
+
const blank = s => !s || !String(s).trim();
|
|
104
|
+
function pickNotes(r) {
|
|
105
|
+
if (!blank(r.notes)) return { notes: r.notes, notesSource: 'sc' };
|
|
106
|
+
if (!blank(r.opp.scNotes)) return { notes: r.opp.scNotes, notesSource: 'opp' };
|
|
107
|
+
return { notes: null, notesSource: null };
|
|
108
|
+
}
|
|
109
|
+
const OPP_NOTES_MSG = 'From Opportunity SC Notes';
|
|
110
|
+
function rowsFromSnapshot(snap, sc) {
|
|
111
|
+
const src = s => ({ acctSC: /Account SC/.test(s), teamSC: /Opp Team/.test(s) });
|
|
112
|
+
const opp = o => ({ oppId: o.id, opp: o.name, oppStage: o.stage, oppType: o.type, fc: o.forecast, close: o.closeDate, amt: o.amount, acct: o.account, owner: o.owner, closed: false, won: false, renewal: /^renewal$/i.test((o.type || '').trim()) });
|
|
113
|
+
const recs = snap.records.map(r => ({
|
|
114
|
+
id: r.id, name: r.name, sc, stage: r.stage, reason: r.closedReason, fitReason: r.fitReason, riskDetails: r.riskDetails, salesLead: r.salesLead, oppOwnerId: r.opp.ownerId, start: r.startDate, end: r.endDate, ...pickNotes(r),
|
|
115
|
+
mtr: r.mtr, vp: r.validationPlan, uc: r.useCases, status: r.status, povReviewed: r.povReviewed, pov: r.pov || {},
|
|
116
|
+
blockerCat: r.blockerCategory, blocker: r.blockers, managerNotes: r.managerNotes, ...opp(r.opp), ...src(r.source),
|
|
117
|
+
}));
|
|
118
|
+
const gaps = snap.noRecord.map(o => {
|
|
119
|
+
const other = o.otherRecords || [];
|
|
120
|
+
return {
|
|
121
|
+
id: 'opp-' + o.id, gap: true, sc, pocId: other[0]?.id || null, name: other[0]?.name || null,
|
|
122
|
+
otherSC: other.length ? [...new Set(other.map(x => x.sc))].join(', ') : null,
|
|
123
|
+
stage: null, reason: null, start: null, end: null, notes: null, mtr: null, vp: null, uc: [null, null, null], status: null, povReviewed: null,
|
|
124
|
+
...opp(o), ...src(o.source),
|
|
125
|
+
};
|
|
126
|
+
});
|
|
127
|
+
return [...recs, ...gaps];
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const CHECKS_M1 = [
|
|
131
|
+
{
|
|
132
|
+
key: 'rec', label: 'SC Record', run(r) {
|
|
133
|
+
if (!r.gap) return { s: 'pass', m: r.acctSC ? 'On your account' : 'Assigned to you' };
|
|
134
|
+
if (r.otherSC) return { s: 'warn', m: `Confirm coverage with ${r.otherSC}, or create your own SC record.` };
|
|
135
|
+
return { s: 'fail', m: 'Create an SC record for this opp.' };
|
|
136
|
+
}
|
|
137
|
+
},
|
|
138
|
+
{
|
|
139
|
+
key: 'notes', label: 'SC Notes', run(r) {
|
|
140
|
+
if (!r.notes) return { s: 'fail', m: 'Add SC Notes, starting with today\'s date.' };
|
|
141
|
+
const nd = noteDate(r.notes);
|
|
142
|
+
if (!nd) return { s: 'warn', m: 'Start the latest SC Note with a date (mm/dd/yyyy).' };
|
|
143
|
+
const age = days(TODAY, nd);
|
|
144
|
+
if (nd < STALE_CUTOFF) return { s: 'fail', m: `STALE: last SC Note ${fmt(nd)} (${age}d ago). Update SC Notes` };
|
|
145
|
+
if (age <= 14) return { s: 'pass', m: `Updated ${age}d ago` };
|
|
146
|
+
if (age <= 30) return { s: 'warn', m: `Update SC Notes soon (last ${age}d ago).` };
|
|
147
|
+
return { s: 'fail', m: `Update SC Notes (last ${fmt(nd)}, ${age}d ago).` };
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
{
|
|
151
|
+
key: 'status', label: 'SC Status', run(r) {
|
|
152
|
+
if (/^(Red|Amber|Green)$/i.test((r.status || '').trim())) return { s: 'pass', m: r.status };
|
|
153
|
+
return { s: 'fail', m: r.status ? `Set SC Status to Green, Amber or Red (currently "${r.status}").` : 'Set SC Status to Green, Amber or Red.' };
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
key: 'stage', label: 'SC Stage', run(r) {
|
|
158
|
+
const closeAsk = /please close|should be closed|closing this/i.test(r.notes || '');
|
|
159
|
+
if (r.stage === 'Closed') return r.reason ? { s: 'pass', m: r.reason } : { s: 'fail', m: 'Set the Closed Reason.' };
|
|
160
|
+
if (closeAsk) return { s: 'fail', m: 'Set SC Stage to Closed and add a Closed Reason (notes ask to close).' };
|
|
161
|
+
return { s: 'pass', m: STAGE_LABEL[r.stage] || r.stage };
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
{
|
|
165
|
+
key: 'end', label: 'End Date', run(r) {
|
|
166
|
+
const e = d(r.end);
|
|
167
|
+
if (r.stage === 'Closed') return e ? { s: 'pass', m: r.end } : { s: 'warn', m: 'Set the End Date to the close-out date.' };
|
|
168
|
+
if (!e) return { s: 'fail', m: 'Set an End Date.' };
|
|
169
|
+
if (e < TODAY) return { s: 'fail', m: `Move the End Date forward, or close the SC record (${r.end} is ${days(TODAY, e)}d past).` };
|
|
170
|
+
return { s: 'pass', m: r.end };
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
{
|
|
174
|
+
key: 'uc', label: 'Use Cases 1–3', run(r) {
|
|
175
|
+
const missing = [1, 2, 3].filter((_, i) => tbd(r.uc[i]));
|
|
176
|
+
if (!missing.length) return { s: 'pass', m: '3 of 3 listed' };
|
|
177
|
+
if (missing.length === 3) return !tbd(r.mtr) ? { s: 'warn', m: 'Fill in Use Case 1, 2 and 3 (Minimum Technical Requirements are filled in).' } : { s: 'fail', m: 'Fill in Use Case 1, 2 and 3.' };
|
|
178
|
+
return { s: 'warn', m: `Fill in Use Case ${missing.join(' and ')}.` };
|
|
179
|
+
}
|
|
180
|
+
},
|
|
181
|
+
{
|
|
182
|
+
key: 'vp', label: 'Validation Plan', run(r) {
|
|
183
|
+
const v = (r.vp || '').trim();
|
|
184
|
+
if (/no validation plan needed/i.test(v)) return { s: 'na', m: 'Marked not needed' };
|
|
185
|
+
if (isUrl(v)) {
|
|
186
|
+
const nd = noteDate(r.notes);
|
|
187
|
+
if (r.stage !== 'Closed' && nd && days(TODAY, nd) > 30) return { s: 'warn', m: 'Review and update the Validation Plan (notes are over 30d old).' };
|
|
188
|
+
return { s: 'pass', m: 'Attached' };
|
|
189
|
+
}
|
|
190
|
+
if (v) return { s: 'warn', m: `Replace "${v}" with a link to the Validation Plan.` };
|
|
191
|
+
return { s: 'fail', m: 'Attach the Validation Plan link.' };
|
|
192
|
+
}
|
|
193
|
+
},
|
|
194
|
+
];
|
|
195
|
+
|
|
196
|
+
/* Rule text for each check, shown on the column headers (ⓘ) and in the Rules panel. */
|
|
197
|
+
const CHECK_RULES = {
|
|
198
|
+
rec: 'Fix: no SC record exists for this opp. Review: only another SC has a record; confirm coverage or create your own. The other checks show N/A until a record exists.',
|
|
199
|
+
notes: `Uses the SC record's Notes, or the Opportunity's SC Notes when those are blank. The date is read from the start of the notes (optionally after 2–3 letter initials). Pass: ≤14 days old. Review: 15–30 days old, or no leading date. Fix: no notes, older than 30 days, or stale (older than ${STALE_MONTHS} months).`,
|
|
200
|
+
status: 'Fix: SC Status (Risk) is not Green, Amber or Red, including when it is blank.',
|
|
201
|
+
stage: 'Fix: SC Stage is Closed with no Closed Reason, or the notes ask to close ("please close", "should be closed", "closing this") but the stage is not Closed.',
|
|
202
|
+
end: 'Fix: End Date missing, or in the past while the SC record is not Closed. Review: Closed SC record with no End Date.',
|
|
203
|
+
uc: 'Pass: Use Case 1, 2 and 3 all filled (not "TBD"). Review: some filled, or none filled but Minimum Technical Requirements are. Fix: none filled and no Minimum Technical Requirements.',
|
|
204
|
+
vp: 'Pass: a link is attached (or "No validation plan needed"). Review: text instead of a link, or a link with notes over 30 days old. Fix: no Validation Plan.',
|
|
205
|
+
};
|
|
206
|
+
CHECKS_M1.forEach(c => { c.rule = CHECK_RULES[c.key]; });
|
|
207
|
+
const SALES_LEAD_RULE = "Listed as a Fix in the review email when the SC record's Sales Lead is not the Opportunity owner (yellow label next to Owner).";
|
|
208
|
+
const ruleTip = text => text ? ` <span class="rule-i" tabindex="0" role="note" aria-label="Rule: ${esc(text)}">ⓘ<span class="rule-pop">${esc(text)}</span></span>` : '';
|
|
209
|
+
|
|
210
|
+
const MODULES = [
|
|
211
|
+
{
|
|
212
|
+
id: 'hygiene', title: 'Record Hygiene',
|
|
213
|
+
description: 'Open Opportunities only. Blends SC records assigned to this SC with open opps on Accounts where this SC is the Account Solution Consultant, plus opps where this SC is on the Opportunity Team (Solution_Consultant or Sales Engineer role); opps with no SC record are called out.',
|
|
214
|
+
rows: rowsFromSnapshot, checks: CHECKS_M1,
|
|
215
|
+
rules: [...CHECKS_M1.map(c => [c.label, c.rule]), ['Sales Lead (review email only)', SALES_LEAD_RULE]],
|
|
216
|
+
},
|
|
217
|
+
];
|
|
218
|
+
|
|
219
|
+
/* ============================================================ STATE ============================================================ */
|
|
220
|
+
/* Fiscal quarters: FY starts Feb 1. Q1 Feb–Apr, Q2 May–Jul, Q3 Aug–Oct, Q4 Nov–Jan. FY named for the calendar year it ends in. */
|
|
221
|
+
function fq(dt) { const m = dt.getMonth(), y = dt.getFullYear(); const fm = (m + 11) % 12; const fy = m === 0 ? y : y + 1; return { q: Math.floor(fm / 3) + 1, fy }; }
|
|
222
|
+
function fqKey(o) { return `FY${String(o.fy).slice(2)} Q${o.q}`; }
|
|
223
|
+
function fqRange(o) { const sm = (o.q - 1) * 3 + 1; const y = o.fy - 1; return [new Date(y, sm, 1), new Date(y, sm + 3, 0)]; }
|
|
224
|
+
const QUARTERS = (() => { const out = []; let o = fq(TODAY); for (let i = 0; i < 3; i++) { out.push({ ...o, key: fqKey(o), range: fqRange(o) }); o = o.q === 4 ? { q: 1, fy: o.fy + 1 } : { q: o.q + 1, fy: o.fy }; } return out; })();
|
|
225
|
+
const mon = dt => dt.toLocaleString('en-US', { month: 'short' });
|
|
226
|
+
const quarterOf = s => s ? fqKey(fq(d(s))) : '';
|
|
227
|
+
|
|
228
|
+
const state = {
|
|
229
|
+
visibleIds: new Set(), review: new Set(), rowIndex: new Map(), emails: {},
|
|
230
|
+
view: 'module', mod: MODULES[0].id, sc: null, scs: {}, snap: null, soql: '', loading: false, err: null,
|
|
231
|
+
q: '', checks: new Set(), flags: new Set(), statuses: new Set(), quarters: new Set([QUARTERS[0].key]), fcs: new Set(), renew: 'all', owner: '', open: new Set()
|
|
232
|
+
};
|
|
233
|
+
const toggle = (set, v) => set.has(v) ? set.delete(v) : set.add(v);
|
|
234
|
+
const $ = s => document.querySelector(s);
|
|
235
|
+
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
|
236
|
+
|
|
237
|
+
const api = async (url, opts = {}) => {
|
|
238
|
+
const res = await fetch(url, { headers: { 'Content-Type': 'application/json' }, ...opts, body: opts.body && JSON.stringify(opts.body) });
|
|
239
|
+
const data = await res.json().catch(() => ({}));
|
|
240
|
+
if (!res.ok) throw new Error(data.error || res.statusText);
|
|
241
|
+
return data;
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
function message(text, error = false) {
|
|
245
|
+
const el = $('#message');
|
|
246
|
+
el.hidden = !text;
|
|
247
|
+
el.textContent = text || '';
|
|
248
|
+
el.classList.toggle('error', error);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/* ============================================================ RENDER ============================================================ */
|
|
252
|
+
function renderTabs() {
|
|
253
|
+
$('#tabs').innerHTML = MODULES.map(m => `<button class="tab" role="tab" aria-selected="${state.view === 'module' && m.id === state.mod}" data-id="${m.id}">${esc(m.title)}</button>`).join('')
|
|
254
|
+
+ `<button class="tab" role="tab" aria-selected="${state.view === 'settings'}" data-view="settings">Settings</button>`;
|
|
255
|
+
document.querySelectorAll('.tab[data-id]').forEach(b => b.onclick = () => { state.view = 'module'; state.mod = b.dataset.id; state.checks.clear(); render(); });
|
|
256
|
+
document.querySelector('.tab[data-view=settings]').onclick = () => { state.view = 'settings'; render(); loadSettings(); };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function render() {
|
|
260
|
+
renderTabs();
|
|
261
|
+
const settings = state.view === 'settings';
|
|
262
|
+
$('#settings').hidden = !settings;
|
|
263
|
+
$('#module').hidden = settings;
|
|
264
|
+
$('#dash-controls').style.visibility = settings ? 'hidden' : '';
|
|
265
|
+
if (settings) return;
|
|
266
|
+
|
|
267
|
+
const M = MODULES.find(m => m.id === state.mod);
|
|
268
|
+
const s = state.snap;
|
|
269
|
+
if (!state.sc) {
|
|
270
|
+
$('#asof').textContent = '';
|
|
271
|
+
$('#module').innerHTML = `<div class="empty-state"><b>No Solution Consultants yet.</b><p class="meta">Open the <b>Settings</b> tab and add Salesforce users to fill the dropdown.</p></div>`;
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
// Each piece stays on one line; lines only break between pieces.
|
|
275
|
+
$('#asof').innerHTML = s ? [snapshotAge(s.fetchedAt), ...(s.missing?.length ? [`no snapshot yet: ${esc(s.missing.join(', '))}`] : [])].map(t => `<span class="nw">${t}</span>`).join(' · ') : '';
|
|
276
|
+
if (!s || state.loading || state.err) {
|
|
277
|
+
$('#module').innerHTML = `<div class="empty-state">${state.loading ? `<b>Loading ${esc(state.loadingLabel || scLabel())} from Salesforce…</b><p class="meta">Five queries: SC records, Account SC opps, Opp Team opps, and other SCs' records on those opps.</p>`
|
|
278
|
+
: state.err ? `<b>Couldn't load from Salesforce.</b><p class="meta">${esc(state.err)}</p>`
|
|
279
|
+
: `<b>No snapshot yet for ${esc(scLabel() || 'this SC')}.</b><p class="meta">Click <b>Refresh from Salesforce</b> to pull their records through your Runlayer connection. Set your API key on the Settings tab first.</p>`}</div>`;
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
const base = combinedRows(M, s).map(r => {
|
|
283
|
+
const res = {}; M.checks.forEach(c => res[c.key] = (r.gap && c.key !== 'rec') ? { s: 'na', m: '—' } : c.run(r));
|
|
284
|
+
const fails = Object.values(res).filter(x => x.s === 'fail').length;
|
|
285
|
+
const warns = Object.values(res).filter(x => x.s === 'warn').length;
|
|
286
|
+
return { r, res, fails, warns };
|
|
287
|
+
});
|
|
288
|
+
// Opp owners across every record for this SC (before filters); drop a choice that isn't in this set.
|
|
289
|
+
const owners = [...new Set(base.map(x => x.r.owner).filter(Boolean))].sort((a, b) => a.localeCompare(b));
|
|
290
|
+
if (state.owner && !owners.includes(state.owner)) state.owner = '';
|
|
291
|
+
|
|
292
|
+
// filters (everything except the check tiles) apply to the totals
|
|
293
|
+
const ctx = base.filter(x => {
|
|
294
|
+
if (state.q && !(`${x.r.name || ''} ${x.r.opp} ${x.r.acct} ${x.r.owner || ''} ${x.r.scName || ''}`.toLowerCase().includes(state.q))) return false;
|
|
295
|
+
if (state.flags.has('action') && !x.fails && !x.warns) return false;
|
|
296
|
+
if (state.flags.has('fails') && !x.fails) return false;
|
|
297
|
+
if (state.flags.has('noend') && x.r.end) return false;
|
|
298
|
+
if (state.flags.has('stale') && !isStale(x.r)) return false;
|
|
299
|
+
if (state.flags.has('norec') && !x.r.gap) return false;
|
|
300
|
+
if (state.statuses.size && !state.statuses.has(x.r.status || 'None')) return false;
|
|
301
|
+
if (state.fcs.size && !state.fcs.has(x.r.fc || 'None')) return false;
|
|
302
|
+
if (state.owner && x.r.owner !== state.owner) return false;
|
|
303
|
+
if (state.renew === 'exclude' && x.r.renewal) return false;
|
|
304
|
+
if (state.renew === 'only' && !x.r.renewal) return false;
|
|
305
|
+
if (state.quarters.size) { const cd = d(x.r.close); if (!QUARTERS.some(q => state.quarters.has(q.key) && cd >= q.range[0] && cd <= q.range[1])) return false; }
|
|
306
|
+
return true;
|
|
307
|
+
});
|
|
308
|
+
state.rowIndex = new Map(base.map(x => [x.r.id, x]));
|
|
309
|
+
const noRec = ctx.filter(x => x.r.gap && !x.r.pocId).sort((a, b) => (b.r.amt || 0) - (a.r.amt || 0));
|
|
310
|
+
const ctxMain = ctx.filter(x => !(x.r.gap && !x.r.pocId));
|
|
311
|
+
const tiles = M.checks.map(c => {
|
|
312
|
+
const cnt = { pass: 0, warn: 0, fail: 0, na: 0 }; ctxMain.forEach(x => cnt[x.res[c.key].s]++);
|
|
313
|
+
const tot = ctxMain.length || 1;
|
|
314
|
+
return `<button class="tile" aria-pressed="${state.checks.has(c.key)}" data-k="${c.key}">
|
|
315
|
+
<div class="k">${esc(c.label)}</div>
|
|
316
|
+
<div class="v">${cnt.fail + cnt.warn}<span class="meta"> / ${ctxMain.length} need action</span></div>
|
|
317
|
+
<div class="bar"><i style="width:${cnt.pass / tot * 100}%;background:var(--ok)"></i><i style="width:${cnt.na / tot * 100}%;background:var(--na)"></i><i style="width:${cnt.warn / tot * 100}%;background:var(--warn)"></i><i style="width:${cnt.fail / tot * 100}%;background:var(--bad)"></i></div>
|
|
318
|
+
</button>`;
|
|
319
|
+
}).join('');
|
|
320
|
+
const clean = ctxMain.filter(x => !x.fails && !x.warns).length;
|
|
321
|
+
const pipe = ctxMain.reduce((t, x) => t + (x.r.amt || 0), 0);
|
|
322
|
+
const rows = ctxMain.filter(x => { for (const k of state.checks) if (!['fail', 'warn'].includes(x.res[k].s)) return false; return true; })
|
|
323
|
+
.sort((a, b) => (b.r.amt || 0) - (a.r.amt || 0));
|
|
324
|
+
|
|
325
|
+
const chip = (grp, v, l, on) => `<button class="chip" aria-pressed="${on}" data-g="${grp}" data-v="${esc(v)}">${l}</button>`;
|
|
326
|
+
const qChips = QUARTERS.map((q, i) => chip('quarter', q.key, `${i === 0 ? 'This quarter · ' : ''}${q.key} <span class="meta">${mon(q.range[0])}–${mon(q.range[1])}</span>`, state.quarters.has(q.key))).join('');
|
|
327
|
+
const stChips = ['Green', 'Amber', 'Red', 'None'].map(v => chip('status', v, v === 'None' ? 'No status' : v, state.statuses.has(v))).join('');
|
|
328
|
+
const flChips = [['action', 'Needs action'], ['fails', 'Has a Fix'], ['norec', 'No SC record'], ['noend', 'No SC close date'], ['stale', `Stale (notes > ${STALE_MONTHS} months)`]].map(([v, l]) => chip('flag', v, l, state.flags.has(v))).join('');
|
|
329
|
+
const fcChips = ['Commit', 'Best Case', 'Pipeline', 'Omitted'].map(v => chip('fc', v, v, state.fcs.has(v))).join('');
|
|
330
|
+
const rnChips = [['all', 'Include renewals'], ['exclude', 'Exclude simple renewals'], ['only', 'Renewals only']].map(([v, l]) => `<button class="chip" aria-pressed="${state.renew === v}" data-renew="${v}">${l}</button>`).join('');
|
|
331
|
+
const ownerSel = `<select id="ownerPick" aria-label="Opp owner"><option value="">All owners</option>${owners.map(o => `<option value="${esc(o)}" ${o === state.owner ? 'selected' : ''}>${esc(o)}</option>`).join('')}</select>`;
|
|
332
|
+
const anyOn = state.owner || state.renew !== 'all' || state.fcs.size || state.flags.size || state.checks.size || state.statuses.size || state.quarters.size;
|
|
333
|
+
const COLCHECKS = M.checks.filter(c => !['stage', 'status'].includes(c.key));
|
|
334
|
+
const cols = COLCHECKS.length + 9;
|
|
335
|
+
const reviewBox = id => `<td class="rv"><input type="checkbox" class="rv-box" data-rv="${esc(id)}" ${state.review.has(id) ? 'checked' : ''} aria-label="Mark for review"></td>`;
|
|
336
|
+
// Only ticked rows visible under the current filters count and go into the email.
|
|
337
|
+
state.visibleIds = new Set([...rows, ...noRec].map(x => x.r.id));
|
|
338
|
+
const nMarked = [...state.review].filter(id => state.visibleIds.has(id)).length;
|
|
339
|
+
const nHidden = state.review.size - nMarked;
|
|
340
|
+
// Check-all box per table: acts on the rows visible in that table.
|
|
341
|
+
const tableIds = { main: rows.map(x => x.r.id), norec: noRec.map(x => x.r.id) };
|
|
342
|
+
const allBox = t => `<label class="rv-all-lbl" title="Check or uncheck all visible rows"><input type="checkbox" class="rv-all" data-tbl="${t}" ${tableIds[t].length ? '' : 'disabled'} aria-label="Mark all visible rows for review"><span>All</span></label>`;
|
|
343
|
+
const firstName = (state.scs[state.sc] || '').split(' ')[0];
|
|
344
|
+
$('#module').innerHTML = `
|
|
345
|
+
<p class="sub" style="margin:0 0 12px">${esc(M.description)}</p>
|
|
346
|
+
<div class="summary">
|
|
347
|
+
<div class="tile" style="cursor:default"><div class="k">Records in view</div><div class="v">${ctxMain.length}<span class="meta"> SC records</span></div><div class="meta">${clean} clean · ${noRec.length} opps with no SC record · ${money(pipe + noRec.reduce((t, x) => t + (x.r.amt || 0), 0))} in view</div></div>
|
|
348
|
+
${tiles}
|
|
349
|
+
</div>
|
|
350
|
+
<div class="fgroups">
|
|
351
|
+
<div class="filters"><span class="flbl">Opp close quarter</span>${qChips}</div>
|
|
352
|
+
<div class="filters"><span class="flbl">SC status</span>${stChips}</div>
|
|
353
|
+
<div class="filters"><span class="flbl">Forecast category</span>${fcChips}</div>
|
|
354
|
+
<div class="filters"><span class="flbl">Opp type</span>${rnChips}</div>
|
|
355
|
+
<div class="filters"><label class="flbl" for="ownerPick">Opp owner</label>${ownerSel}</div>
|
|
356
|
+
<div class="filters"><span class="flbl">Show</span>${flChips}
|
|
357
|
+
${[...state.checks].map(k => `<button class="chip" aria-pressed="true" data-g="check" data-v="${k}">${esc(M.checks.find(c => c.key === k).label)} needs action ✕</button>`).join('')}
|
|
358
|
+
${anyOn ? '<button class="chip" id="clrAll">Clear all</button>' : ''}</div>
|
|
359
|
+
<div class="meta">${rows.length} SC records shown · all selected filters apply (quarters and statuses match any selected) · click a row for details</div>
|
|
360
|
+
</div>
|
|
361
|
+
<div class="reviewbar">
|
|
362
|
+
<span><b>${nMarked}</b> marked for review <span class="meta">· ${nHidden ? `${nHidden} more ticked but hidden by filters (not included)` : 'tick the Review box on any row in either table'}</span></span>
|
|
363
|
+
${isAll() ? '<span class="meta">Pick one Solution Consultant to send a review message.</span>' : `<button class="btn" id="emailBtn" ${nMarked ? '' : 'disabled'}>Message ${esc(firstName || 'SC')} for review</button>`}
|
|
364
|
+
${state.review.size ? '<button class="chip" id="clearMarks">Clear marks</button>' : ''}
|
|
365
|
+
</div>
|
|
366
|
+
<div class="tablebox"><table>
|
|
367
|
+
<thead><tr><th class="rv">${allBox('main')}</th><th>SC record / Opportunity${ruleTip(SALES_LEAD_RULE)}</th><th>SC status${ruleTip(CHECK_RULES.status)}</th><th class="stage-col">SC stage · Opp stage${ruleTip(CHECK_RULES.stage)}</th><th>Forecast · type · amount</th><th>Opp close</th><th>SC close</th>${COLCHECKS.map(c => `<th class="ck-${c.key}">${esc(c.label)}${ruleTip(c.rule)}</th>`).join('')}<th>POV Reviewed</th><th>Issues</th></tr></thead>
|
|
368
|
+
<tbody>${rows.length ? rows.map(x => rowHtml(x, M, cols, reviewBox)).join('') : `<tr><td colspan="${cols}" class="empty">Nothing matches. Every record passes this filter.</td></tr>`}</tbody>
|
|
369
|
+
</table></div>
|
|
370
|
+
<h2 class="sec">Opportunities with no SC record <span class="meta">${noRec.length} · ${money(noRec.reduce((t, x) => t + (x.r.amt || 0), 0))}</span></h2>
|
|
371
|
+
<p class="meta" style="margin:0 0 8px">Open opportunities where ${isAll() ? 'one of these Solution Consultants' : esc(state.scs[state.sc])} is the Account Solution Consultant or is on the Opportunity Team as Solution Consultant or Sales Engineer, and no SC record exists. Same filters apply.</p>
|
|
372
|
+
<div class="tablebox"><table class="opps">
|
|
373
|
+
<thead><tr><th class="rv">${allBox('norec')}</th><th>Opportunity</th><th>Owner</th><th>Account</th><th>Stage</th><th>Type</th><th>Forecast</th><th>Close date</th><th>Quarter</th><th style="text-align:right">Amount</th></tr></thead>
|
|
374
|
+
<tbody>${noRec.length ? noRec.map(x => {
|
|
375
|
+
const r = x.r; return `<tr${state.review.has(r.id) ? ' class="marked"' : ''}>${reviewBox(r.id)}
|
|
376
|
+
<td class="name"><a href="${SF}Opportunity/${r.oppId}/view" target="_blank" rel="noopener">${esc(r.opp)}</a><div style="margin-top:3px">${srcBadge(r)}</div></td>
|
|
377
|
+
<td>${esc(r.owner || '—')}</td><td>${esc(r.acct)}</td><td>${esc(r.oppStage)}</td>
|
|
378
|
+
<td>${esc(r.oppType || '—')}${r.renewal ? ' <span class="pill na">Renewal</span>' : ''}</td>
|
|
379
|
+
<td>${esc(r.fc || '—')}</td><td class="mono">${r.close}</td><td class="mono">${quarterOf(r.close)}</td>
|
|
380
|
+
<td class="mono" style="text-align:right">${money(r.amt)}</td></tr>`;
|
|
381
|
+
}).join('') : `<tr><td colspan="10" class="empty">No opportunities without an SC record in this view.</td></tr>`}</tbody>
|
|
382
|
+
</table></div>
|
|
383
|
+
<details class="soql" style="margin-top:14px"><summary>Rules and SOQL for this module</summary>
|
|
384
|
+
<div class="rules">${(M.rules || []).map(([k, v]) => `<div><b>${esc(k)}</b><br>${esc(v)}</div>`).join('')}</div>
|
|
385
|
+
<pre>${esc(state.soql)}</pre></details>`;
|
|
386
|
+
|
|
387
|
+
document.querySelectorAll('.tile[data-k]').forEach(t => t.onclick = () => { toggle(state.checks, t.dataset.k); render(); });
|
|
388
|
+
const G = { quarter: state.quarters, status: state.statuses, flag: state.flags, check: state.checks, fc: state.fcs };
|
|
389
|
+
document.querySelectorAll('[data-renew]').forEach(c => c.onclick = () => { state.renew = c.dataset.renew; render(); });
|
|
390
|
+
$('#ownerPick').onchange = e => { state.owner = e.target.value; render(); };
|
|
391
|
+
document.querySelectorAll('.chip[data-g]').forEach(c => c.onclick = () => { toggle(G[c.dataset.g], c.dataset.v); render(); });
|
|
392
|
+
const clr = $('#clrAll'); if (clr) clr.onclick = () => { Object.values(G).forEach(x => x.clear()); state.renew = 'all'; state.owner = ''; render(); };
|
|
393
|
+
document.querySelectorAll('.rv-all').forEach(cb => {
|
|
394
|
+
const ids = tableIds[cb.dataset.tbl], n = ids.filter(id => state.review.has(id)).length;
|
|
395
|
+
cb.checked = ids.length > 0 && n === ids.length;
|
|
396
|
+
cb.indeterminate = n > 0 && n < ids.length;
|
|
397
|
+
cb.onchange = () => { ids.forEach(id => cb.checked ? state.review.add(id) : state.review.delete(id)); render(); };
|
|
398
|
+
});
|
|
399
|
+
document.querySelectorAll('.rv-box').forEach(cb => cb.onchange = () => { cb.checked ? state.review.add(cb.dataset.rv) : state.review.delete(cb.dataset.rv); render(); });
|
|
400
|
+
const eb = $('#emailBtn'); if (eb) eb.onclick = openEmail;
|
|
401
|
+
const cm = $('#clearMarks'); if (cm) cm.onclick = () => { state.review.clear(); render(); };
|
|
402
|
+
document.querySelectorAll('tr.row').forEach(tr => tr.onclick = e => {
|
|
403
|
+
if (e.target.closest('a, .rv, .peek-btn')) return;
|
|
404
|
+
const id = tr.dataset.id; state.open.has(id) ? state.open.delete(id) : state.open.add(id); render();
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function rowHtml(x, M, cols, reviewBox) {
|
|
409
|
+
const r = x.r;
|
|
410
|
+
const cellIn = v => (v.s === 'pass' || v.s === 'na') ? `<div class="cell-val">${esc(v.m)}</div>` : `<span class="pill ${v.s}">${v.s === 'fail' ? 'Fix' : 'Review'}</span><div class="cell-msg">${esc(v.m)}</div>`;
|
|
411
|
+
const vpLink = isUrl(r.vp) ? `<div><a class="opplink" href="${esc(r.vp.trim())}" target="_blank" rel="noopener">Open Validation Plan</a></div>` : '';
|
|
412
|
+
const cells = M.checks.filter(c => !['stage', 'status'].includes(c.key)).map(c => `<td class="ck-${c.key}">${cellIn(x.res[c.key])}${c.key === 'vp' ? vpLink : ''}${c.key === 'notes' && r.notesSource === 'opp' ? `<div class="notes-src">${OPP_NOTES_MSG}</div>` : ''}</td>`).join('');
|
|
413
|
+
const sv = x.res.stage;
|
|
414
|
+
// Every opp here is open, so show its actual Opportunity stage in the pill.
|
|
415
|
+
const oppState = `<span class="pill na pill-wrap" style="color:var(--accent);background:var(--accent-soft)" title="Opportunity stage">${esc(r.oppStage || '—')}</span>`;
|
|
416
|
+
const stale = isStale(r);
|
|
417
|
+
let html = `<tr class="row${r.gap ? ' gap' : ''}${stale ? ' stale' : ''}${state.review.has(r.id) ? ' marked' : ''}" data-id="${r.id}" aria-expanded="${state.open.has(r.id)}">
|
|
418
|
+
${reviewBox(r.id)}<td class="name">${r.gap
|
|
419
|
+
? (r.pocId ? `<a href="${SF}POC__c/${r.pocId}/view" target="_blank" rel="noopener">${esc(r.name)}</a>${peekBtn(r.pocId, r.name)} <span class="pill warn">SC: ${esc(r.otherSC)}</span>` : `<span class="pill fail">No SC record</span>`)
|
|
420
|
+
: `${stale ? `<div class="stale-badge" title="Latest SC Note is more than ${STALE_MONTHS} months old">⚠ STALE SC RECORD · notes ${fmt(noteDate(r.notes))}</div>` : ''}<a href="${SF}POC__c/${r.id}/view" target="_blank" rel="noopener">${esc(r.name)}</a>${peekBtn(r.id, r.name)}`}
|
|
421
|
+
<div class="meta">Owner: ${esc(r.owner || '—')}${leadFlag(r)}</div>${r.scName ? `<div class="meta">SC: ${esc(r.scName)}</div>` : ''}
|
|
422
|
+
<div class="meta">${esc(r.acct)}</div><div style="margin-top:3px">${srcBadge(r)}</div>
|
|
423
|
+
<div><a class="opplink" href="${SF}Opportunity/${r.oppId}/view" target="_blank" rel="noopener">${esc(r.opp)}</a></div></td>
|
|
424
|
+
<td>${r.status ? `<span class="pill st-${esc(r.status)}">${esc(r.status)}</span>` : '<span class="pill na">None</span>'}${x.res.status && x.res.status.s === 'fail' ? `<div style="margin-top:4px"><span class="pill fail">Fix</span><div class="cell-msg">${esc(x.res.status.m)}</div></div>` : ''}${showRisk(r) ? (blank(r.riskDetails) ? '<div class="risk-preview none">No risk details</div>' : `<div class="risk-preview" title="${esc(r.riskDetails)}">${esc(r.riskDetails.trim().slice(0, 140))}${r.riskDetails.trim().length > 140 ? '…' : ''}</div>`) : ''}</td>
|
|
425
|
+
<td class="stage-col"><div>${r.stage ? esc(STAGE_LABEL[r.stage] || r.stage) : '<span class="meta">—</span>'}</div>${sv && (sv.s === 'fail' || sv.s === 'warn') ? `<span class="pill ${sv.s}" style="margin-top:4px">${sv.s === 'fail' ? 'Fix' : 'Review'}</span><div class="cell-msg">${esc(sv.m)}</div>` : ''}<div class="meta" style="margin-top:4px">Opp: ${oppState}</div>${r.reason && r.reason.trim() ? `<div class="meta" style="margin-top:4px">Closed Reason: <span class="pill warn pill-wrap">${esc(r.reason)}</span></div>${r.fitReason && r.fitReason.trim() ? `<div class="meta" style="margin-top:4px">Partial/No Fit/Canceled Reason: <span class="pill warn pill-wrap">${esc(r.fitReason)}</span></div>` : ''}` : ''}</td>
|
|
426
|
+
<td><div>${esc(r.fc || '—')}</div><div class="meta">${esc(r.oppType || '—')}${r.renewal ? ' <span class="pill na">Renewal</span>' : ''}</div><div class="meta mono">${money(r.amt)}</div></td>
|
|
427
|
+
<td class="mono">${r.close}<div class="meta">${quarterOf(r.close)}</div></td>
|
|
428
|
+
<td class="mono">${r.end || '<span class="meta">—</span>'}${r.end ? `<div class="meta">${quarterOf(r.end)}</div>` : ''}</td>
|
|
429
|
+
${cells}
|
|
430
|
+
<td>${r.povReviewed === null ? '<span class="meta">—</span>' : r.povReviewed ? '<span class="pill pass">On</span>' : '<span class="pill na">Off</span>'}</td>
|
|
431
|
+
<td class="score">${x.fails ? `<span class="pill fail">${x.fails}</span>` : ''} ${x.warns ? `<span class="pill warn">${x.warns}</span>` : ''}${!x.fails && !x.warns ? '<span class="pill pass">Clean</span>' : ''}</td></tr>`;
|
|
432
|
+
if (state.open.has(r.id)) {
|
|
433
|
+
html += `<tr class="detail"><td colspan="${cols}"><div class="dgrid">
|
|
434
|
+
${showRisk(r) ? `<div><h4>Opportunity Risk Details · ${esc(r.status || 'no status')}</h4><pre>${esc(blank(r.riskDetails) ? '— none —' : r.riskDetails)}</pre></div>` : ''}
|
|
435
|
+
<div><h4>SC Notes (full)${r.notesSource === 'opp' ? ' · from the Opportunity' : ''}</h4><pre>${esc(r.notes || '— none —')}</pre></div>
|
|
436
|
+
<div><h4>Use Cases</h4><pre>${r.uc.map((u, i) => `${i + 1}. ${u ? esc(u) : '— empty —'}`).join('\n')}</pre></div>
|
|
437
|
+
${r.managerNotes && r.managerNotes.trim() ? `<div><h4>SC Manager Notes</h4><pre>${esc(r.managerNotes)}</pre></div>` : ''}
|
|
438
|
+
<div><h4>Minimum Technical Requirements</h4><pre>${esc(r.mtr || '— none —')}</pre></div>
|
|
439
|
+
${(r.blockerCat || r.blocker) ? `<div><h4>Blockers</h4><pre>Blocker Category: ${esc(r.blockerCat || '—')}\n\n${esc(r.blocker || '— no details —')}</pre></div>` : ''}
|
|
440
|
+
${r.gap ? '' : `<div><h4>Proof of Value</h4><pre>Status: ${esc(r.pov.status || '—')}
|
|
441
|
+
Start: ${r.pov.start || '—'} End: ${r.pov.end || '—'}
|
|
442
|
+
Manager review: ${r.povReviewed ? `Performed${r.pov.reviewedDate ? ` on ${r.pov.reviewedDate}` : ' (no Reviewed Date)'}` : `Not performed${r.pov.reviewedDate ? ` (Reviewed Date ${r.pov.reviewedDate} is set)` : ''}`}</pre></div>`}
|
|
443
|
+
<div><h4>Record</h4><pre>SC Stage: ${esc(STAGE_LABEL[r.stage] || r.stage || '—')}${r.reason ? '\nClosed Reason: ' + esc(r.reason) : ''}
|
|
444
|
+
Start: ${r.start || '—'} End: ${r.end || '—'}
|
|
445
|
+
Validation Plan: ${isUrl(r.vp) ? '' : esc(r.vp || '—')}</pre>${isUrl(r.vp) ? `<a href="${esc(r.vp.trim())}" target="_blank" rel="noopener">${esc(r.vp)}</a>` : ''}</div>
|
|
446
|
+
</div></td></tr>`;
|
|
447
|
+
}
|
|
448
|
+
return html;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/* ============================================================ REVIEW EMAIL ============================================================ */
|
|
452
|
+
/* Builds a plain-text email to the selected SC listing every row marked for review that is
|
|
453
|
+
visible under the current filters,
|
|
454
|
+
with Salesforce links and the Fix/Review issues from this report. */
|
|
455
|
+
function buildEmail() {
|
|
456
|
+
const M = MODULES.find(m => m.id === state.mod);
|
|
457
|
+
const marked = [...state.review].filter(id => state.visibleIds.has(id)).map(id => state.rowIndex.get(id)).filter(Boolean)
|
|
458
|
+
.sort((a, b) => (b.r.amt || 0) - (a.r.amt || 0));
|
|
459
|
+
// Sales Lead vs Opportunity owner is listed as a Fix here (shown only as a label on the dashboard).
|
|
460
|
+
const leadFix = r => {
|
|
461
|
+
if (!leadMismatch(r)) return [];
|
|
462
|
+
return [r.salesLead
|
|
463
|
+
? ` - Fix: Set the SC record's Sales Lead to the Opportunity owner (${r.owner}); it is currently ${r.salesLead.name}.`
|
|
464
|
+
: ` - Fix: Set the SC record's Sales Lead to the Opportunity owner (${r.owner}).`];
|
|
465
|
+
};
|
|
466
|
+
const notesNote = r => r.notesSource === 'opp' ? [` - Note: No SC Record Notes; the Opportunity's SC Notes were used for this review.`] : [];
|
|
467
|
+
const issuesOf = x => [...leadFix(x.r), ...notesNote(x.r), ...M.checks.map(c => x.res[c.key]).filter(v => v.s === 'fail' || v.s === 'warn')
|
|
468
|
+
.map(v => ` - ${v.s === 'fail' ? 'Fix' : 'Review'}: ${v.m}`)];
|
|
469
|
+
const oppLine = r => `${r.opp} (${r.acct}) · ${money(r.amt)} · ${r.oppStage} · closes ${r.close}`;
|
|
470
|
+
const records = marked.filter(x => !x.r.gap || x.r.pocId);
|
|
471
|
+
const opps = marked.filter(x => x.r.gap && !x.r.pocId);
|
|
472
|
+
const lines = [];
|
|
473
|
+
records.forEach((x, i) => {
|
|
474
|
+
const r = x.r, pocId = r.gap ? r.pocId : r.id;
|
|
475
|
+
lines.push(`${i + 1}. ${r.name}${r.gap ? ` (SC record owned by ${r.otherSC})` : ''}${isStale(r) ? ' [STALE]' : ''}`,
|
|
476
|
+
` Opportunity: ${oppLine(r)}`,
|
|
477
|
+
` Owner: ${r.owner || '—'}`,
|
|
478
|
+
` SC record: ${SF}POC__c/${pocId}/view`,
|
|
479
|
+
` Opportunity: ${SF}Opportunity/${r.oppId}/view`);
|
|
480
|
+
const iss = issuesOf(x);
|
|
481
|
+
lines.push(iss.length ? ' Issues:' : ' Issues: none flagged; please review.', ...iss, '');
|
|
482
|
+
});
|
|
483
|
+
const oppLines = [];
|
|
484
|
+
opps.forEach((x, i) => {
|
|
485
|
+
const r = x.r;
|
|
486
|
+
oppLines.push(`${i + 1}. ${oppLine(r)}`, ` Owner: ${r.owner || '—'}`, ` Opportunity: ${SF}Opportunity/${r.oppId}/view`, ' Issues:', ...issuesOf(x), '');
|
|
487
|
+
});
|
|
488
|
+
const name = state.scs[state.sc] || '';
|
|
489
|
+
const snap = state.snap ? new Date(state.snap.fetchedAt).toLocaleDateString() : '';
|
|
490
|
+
const body = [
|
|
491
|
+
`Hi ${name.split(' ')[0]},`, '',
|
|
492
|
+
`Please review the following ${marked.length === 1 ? 'item' : `${marked.length} items`} in Salesforce. The issues listed come from the SC Record Hygiene report (Salesforce snapshot ${snap}).`, '',
|
|
493
|
+
...(records.length ? [`SC RECORDS (${records.length})`, ...lines] : []),
|
|
494
|
+
...(opps.length ? [`OPPORTUNITIES WITH NO SC RECORD (${opps.length})`, ...oppLines] : []),
|
|
495
|
+
'Thanks!', '',
|
|
496
|
+
].join('\n');
|
|
497
|
+
return { to: state.emails[state.sc] || '', subject: `SC record review: ${marked.length} item${marked.length === 1 ? '' : 's'} to update`, body };
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
function openEmail() {
|
|
501
|
+
const e = buildEmail();
|
|
502
|
+
$('#em-to').value = e.to;
|
|
503
|
+
$('#em-subject').value = e.subject;
|
|
504
|
+
$('#em-body').value = e.body;
|
|
505
|
+
$('#em-msg').textContent = e.to ? '' : `No email address found for ${state.scs[state.sc]} in Salesforce. Enter one above.`;
|
|
506
|
+
$('#email-dlg').showModal();
|
|
507
|
+
}
|
|
508
|
+
const mailtoUrl = () => `mailto:${encodeURIComponent($('#em-to').value.trim())}?subject=${encodeURIComponent($('#em-subject').value)}&body=${encodeURIComponent($('#em-body').value)}`;
|
|
509
|
+
$('#em-open').onclick = () => {
|
|
510
|
+
const url = mailtoUrl();
|
|
511
|
+
// Many mail apps truncate very long mailto links; suggest copying instead.
|
|
512
|
+
$('#em-msg').textContent = url.length > 1900 ? 'This email is long; if your mail app cuts it off, use Copy body and paste it in.' : '';
|
|
513
|
+
window.location.href = url;
|
|
514
|
+
};
|
|
515
|
+
$('#em-copy').onclick = async () => {
|
|
516
|
+
try { await navigator.clipboard.writeText($('#em-body').value); $('#em-msg').textContent = 'Body copied to the clipboard.'; }
|
|
517
|
+
catch { $('#em-body').select(); $('#em-msg').textContent = 'Press Cmd+C to copy the selected text.'; }
|
|
518
|
+
};
|
|
519
|
+
$('#em-close').onclick = () => $('#email-dlg').close();
|
|
520
|
+
|
|
521
|
+
/* Slack: open a DM with the SC (matched by email) and save the text as a draft, or send it. */
|
|
522
|
+
async function slackReview(send) {
|
|
523
|
+
const to = $('#em-to').value.trim(), name = state.scs[state.sc] || '';
|
|
524
|
+
if (send && !confirm(`Send this review message to ${name} in Slack now?`)) return;
|
|
525
|
+
const btns = ['#sl-draft', '#sl-send'].map(s => $(s));
|
|
526
|
+
btns.forEach(b => b.disabled = true);
|
|
527
|
+
$('#em-msg').textContent = send ? 'Sending in Slack…' : 'Creating Slack draft…';
|
|
528
|
+
try {
|
|
529
|
+
const message = `*${$('#em-subject').value}*\n\n${$('#em-body').value}`;
|
|
530
|
+
const r = await api('/api/slack/dm', { method: 'POST', body: { email: to, name, message, send } });
|
|
531
|
+
$('#em-msg').innerHTML = `${send ? `Sent to ${esc(name)} in Slack.` : `Draft saved in your DM with ${esc(name)} (Slack → Drafts & Sent).`} <a href="${esc(r.link)}" target="_blank" rel="noopener">Open the DM in Slack</a>`;
|
|
532
|
+
} catch (err) {
|
|
533
|
+
$('#em-msg').textContent = `Slack: ${err.message}`;
|
|
534
|
+
} finally {
|
|
535
|
+
btns.forEach(b => b.disabled = false);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
$('#sl-draft').onclick = () => slackReview(false);
|
|
539
|
+
$('#sl-send').onclick = () => slackReview(true);
|
|
540
|
+
|
|
541
|
+
/* ============================================================ SC RECORD PREVIEW ============================================================ */
|
|
542
|
+
/* The pop-out icon next to an SC record link opens the record in a separate browser window
|
|
543
|
+
sized to 80% of the screen. Salesforce forbids embedding (frame-ancestors 'self'), so it
|
|
544
|
+
can't be shown inside this page. If the browser still blocks the pop-up, an in-page
|
|
545
|
+
summary of the record is shown instead. */
|
|
546
|
+
const POPOUT_ICON = '<svg viewBox="0 0 16 16" width="13" height="13" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" d="M9 2.5h4.5V7M13.5 2.5 7.5 8.5M12 9.5v3a1 1 0 0 1-1 1H3.5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h3"/></svg>';
|
|
547
|
+
const peekBtn = (id, name) => `<button type="button" class="peek-btn" data-peek="${esc(id)}" title="Open in a Salesforce window" aria-label="Open ${esc(name)} in a Salesforce window">${POPOUT_ICON}</button>`;
|
|
548
|
+
const peek = { win: null };
|
|
549
|
+
function openSfWindow(url) {
|
|
550
|
+
const w = Math.round(screen.availWidth * 0.8), h = Math.round(screen.availHeight * 0.8);
|
|
551
|
+
const left = Math.round((screen.availWidth - w) / 2 + (screen.availLeft || 0));
|
|
552
|
+
const top = Math.round((screen.availHeight - h) / 2 + (screen.availTop || 0));
|
|
553
|
+
// Reuse one named window so repeated hovers don't pile up windows.
|
|
554
|
+
const win = window.open(url, 'sc-record-peek', `popup=yes,width=${w},height=${h},left=${left},top=${top}`);
|
|
555
|
+
if (win) { try { win.resizeTo(w, h); win.moveTo(left, top); } catch { } win.focus(); }
|
|
556
|
+
return win;
|
|
557
|
+
}
|
|
558
|
+
function peekSummary(link) {
|
|
559
|
+
const id = (link.href.match(/POC__c\/([^/]+)/) || [])[1];
|
|
560
|
+
const x = [...state.rowIndex.values()].find(x => x.r.id === id || x.r.pocId === id);
|
|
561
|
+
if (!x) return '<p class="meta">No details for this record in the current snapshot.</p>';
|
|
562
|
+
const r = x.r, M = MODULES.find(m => m.id === state.mod);
|
|
563
|
+
const issues = M.checks.map(c => x.res[c.key]).filter(v => v.s === 'fail' || v.s === 'warn');
|
|
564
|
+
const sec = (t, v) => `<div><h4>${t}</h4><pre>${v}</pre></div>`;
|
|
565
|
+
return `<div class="dgrid">
|
|
566
|
+
${sec('Opportunity', `${esc(r.opp)}\n${esc(r.acct)} · ${money(r.amt)}\n${esc(r.oppStage)} · closes ${r.close}\nOwner: ${esc(r.owner || '—')}`)}
|
|
567
|
+
${sec('SC record', `${r.gap ? `Owned by ${esc(r.otherSC)}` : `Stage: ${esc(STAGE_LABEL[r.stage] || r.stage || '—')}\nStatus: ${esc(r.status || 'None')}\nEnd Date: ${r.end || '—'}${r.reason ? `\nClosed Reason: ${esc(r.reason)}` : ''}`}`)}
|
|
568
|
+
${sec('Issues', issues.length ? issues.map(v => `${v.s === 'fail' ? 'Fix' : 'Review'}: ${esc(v.m)}`).join('\n') : 'None')}
|
|
569
|
+
${r.gap ? '' : sec('SC Notes', esc(r.notes || '— none —'))}
|
|
570
|
+
${r.gap ? '' : sec('Use Cases', r.uc.map((u, i) => `${i + 1}. ${u ? esc(u) : '— empty —'}`).join('\n'))}
|
|
571
|
+
</div>`;
|
|
572
|
+
}
|
|
573
|
+
function showPeek(link) {
|
|
574
|
+
peek.win = openSfWindow(link.href);
|
|
575
|
+
if (peek.win) return;
|
|
576
|
+
// Pop-up blocked: show what we have locally, plus a click-to-open button (clicks are allowed).
|
|
577
|
+
$('#peek-title').textContent = link.textContent.trim() || 'SC record';
|
|
578
|
+
$('#peek-note').hidden = false;
|
|
579
|
+
$('#peek-note').textContent = 'Your browser blocked the Salesforce window. Allow pop-ups for this site (address-bar icon), or use the button.';
|
|
580
|
+
$('#peek-body').innerHTML = peekSummary(link);
|
|
581
|
+
$('#peek-open').onclick = () => { openSfWindow(link.href); $('#peek-dlg').close(); };
|
|
582
|
+
$('#peek-dlg').showModal();
|
|
583
|
+
}
|
|
584
|
+
$('#module').addEventListener('click', e => {
|
|
585
|
+
const btn = e.target.closest('.peek-btn');
|
|
586
|
+
if (!btn) return;
|
|
587
|
+
e.stopPropagation(); // don't expand the row
|
|
588
|
+
const link = btn.previousElementSibling;
|
|
589
|
+
showPeek(link);
|
|
590
|
+
});
|
|
591
|
+
$('#peek-close').onclick = () => $('#peek-dlg').close();
|
|
592
|
+
$('#peek-dlg').addEventListener('click', e => { if (e.target === $('#peek-dlg')) $('#peek-dlg').close(); }); // backdrop click
|
|
593
|
+
|
|
594
|
+
/* ============================================================ DATA ============================================================ */
|
|
595
|
+
/* TODAY, the fiscal quarters and the stale cutoff are fixed when the page loads. If the date has
|
|
596
|
+
changed since then (e.g. a tab left open into a new quarter), reload so filters and checks use today. */
|
|
597
|
+
const LOADED_DAY = TODAY.toDateString();
|
|
598
|
+
function reloadIfNewDay() {
|
|
599
|
+
if (new Date().toDateString() === LOADED_DAY) return false;
|
|
600
|
+
location.reload();
|
|
601
|
+
return true;
|
|
602
|
+
}
|
|
603
|
+
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') reloadIfNewDay(); });
|
|
604
|
+
|
|
605
|
+
async function loadSnapshot() {
|
|
606
|
+
if (reloadIfNewDay()) return;
|
|
607
|
+
state.err = null;
|
|
608
|
+
if (isAll()) {
|
|
609
|
+
const ids = Object.keys(state.scs);
|
|
610
|
+
const got = await Promise.all(ids.map(id => api(`/api/snapshot/${id}`)));
|
|
611
|
+
const parts = ids.map((sc, i) => ({ sc, snap: got[i].snapshot })).filter(p => p.snap);
|
|
612
|
+
state.snap = parts.length ? {
|
|
613
|
+
parts, // age shown is the oldest snapshot in the set
|
|
614
|
+
fetchedAt: parts.map(p => p.snap.fetchedAt).sort()[0],
|
|
615
|
+
missing: ids.filter((id, i) => !got[i].snapshot).map(id => state.scs[id]),
|
|
616
|
+
} : null;
|
|
617
|
+
state.soql = got[0]?.soql || '';
|
|
618
|
+
} else {
|
|
619
|
+
const { snapshot, soql } = await api(`/api/snapshot/${state.sc}`);
|
|
620
|
+
state.snap = snapshot;
|
|
621
|
+
state.soql = soql;
|
|
622
|
+
}
|
|
623
|
+
render();
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
async function refresh() {
|
|
627
|
+
if (reloadIfNewDay()) return;
|
|
628
|
+
const btn = $('#refresh-btn');
|
|
629
|
+
btn.disabled = true;
|
|
630
|
+
state.loading = true; state.err = null; message('');
|
|
631
|
+
render();
|
|
632
|
+
try {
|
|
633
|
+
if (isAll()) {
|
|
634
|
+
// One SC at a time; changes are tagged with the SC's name.
|
|
635
|
+
const ids = Object.keys(state.scs), all = [], counts = {};
|
|
636
|
+
let last = null;
|
|
637
|
+
for (const [i, id] of ids.entries()) {
|
|
638
|
+
state.loadingLabel = `${state.scs[id]} (${i + 1} of ${ids.length})`; render();
|
|
639
|
+
const { snapshot, changes } = await api(`/api/refresh/${id}`, { method: 'POST' });
|
|
640
|
+
all.push(...changes.map(c => ({ ...c, opp: `${state.scs[id]} · ${c.opp}` })));
|
|
641
|
+
Object.entries(snapshot.counts).forEach(([k, v]) => counts[k] = (counts[k] || 0) + v);
|
|
642
|
+
last = snapshot;
|
|
643
|
+
}
|
|
644
|
+
await loadSnapshot();
|
|
645
|
+
showChanges({ ...last, counts }, all);
|
|
646
|
+
} else {
|
|
647
|
+
const { snapshot, changes } = await api(`/api/refresh/${state.sc}`, { method: 'POST' });
|
|
648
|
+
state.snap = snapshot;
|
|
649
|
+
showChanges(snapshot, changes);
|
|
650
|
+
}
|
|
651
|
+
} catch (e) {
|
|
652
|
+
const authError = /invalid api key|401|403|unauthori[sz]ed/i.test(e.message);
|
|
653
|
+
state.err = e.message + (authError ? ' Check your API key on the Settings tab.' : '');
|
|
654
|
+
} finally {
|
|
655
|
+
state.loading = false; state.loadingLabel = null;
|
|
656
|
+
btn.disabled = false;
|
|
657
|
+
render();
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/* Refresh results pop-up: source counts and every change since the previous snapshot. */
|
|
662
|
+
function showChanges(snapshot, changes) {
|
|
663
|
+
const c = snapshot.counts;
|
|
664
|
+
$('#ch-title').textContent = `Refresh results · ${scLabel()}`;
|
|
665
|
+
$('#ch-counts').textContent = `Salesforce snapshot ${new Date(snapshot.fetchedAt).toLocaleString()} · SC records ${c.scRecords}, Account SC opps ${c.accountSc}, Opp Team ${c.oppTeam}, other SCs' records ${c.otherOnAccount + c.otherOnTeam}.`;
|
|
666
|
+
$('#ch-list').innerHTML = changes.length
|
|
667
|
+
? `<p><b>${changes.length} change${changes.length === 1 ? '' : 's'}</b> since the last snapshot</p>
|
|
668
|
+
<div class="tablebox"><table class="opps"><thead><tr><th>Opportunity</th><th>Field</th><th>Was</th><th>Now</th></tr></thead><tbody>
|
|
669
|
+
${changes.map(x => `<tr><td>${esc(x.opp)}</td><td>${esc(x.field)}</td><td>${esc(x.old ?? '')}</td><td>${esc(x.new ?? '')}</td></tr>`).join('')}
|
|
670
|
+
</tbody></table></div>`
|
|
671
|
+
: '<p><b>No changes</b> since the last snapshot.</p>';
|
|
672
|
+
$('#changes-dlg').showModal();
|
|
673
|
+
}
|
|
674
|
+
$('#ch-close').onclick = () => $('#changes-dlg').close();
|
|
675
|
+
$('#changes-dlg').addEventListener('click', e => { if (e.target === $('#changes-dlg')) $('#changes-dlg').close(); });
|
|
676
|
+
|
|
677
|
+
function applyRoster({ users: all, error }) {
|
|
678
|
+
renderRosterList(all);
|
|
679
|
+
if (error) message(`Couldn't look up Salesforce user IDs for the saved names: ${error}`, true);
|
|
680
|
+
const roster = all.filter(r => r.id); // names that matched an active Salesforce user
|
|
681
|
+
state.scs = Object.fromEntries(roster.map(r => [r.id, r.name]));
|
|
682
|
+
state.emails = Object.fromEntries(roster.map(r => [r.id, r.email || '']));
|
|
683
|
+
let saved = null;
|
|
684
|
+
try { saved = localStorage.getItem('scId'); } catch { }
|
|
685
|
+
const prev = state.sc;
|
|
686
|
+
const valid = id => id && (state.scs[id] || (id === ALL && roster.length > 1));
|
|
687
|
+
state.sc = valid(prev) ? prev : (valid(saved) ? saved : roster[0]?.id || null);
|
|
688
|
+
$('#scPick').innerHTML = roster.length
|
|
689
|
+
? (roster.length > 1 ? `<option value="${ALL}" ${isAll() ? 'selected' : ''}>All Solution Consultants</option>` : '')
|
|
690
|
+
+ roster.map(r => `<option value="${r.id}" ${r.id === state.sc ? 'selected' : ''}>${esc(r.name)}</option>`).join('')
|
|
691
|
+
: '<option value="">Add names in Settings</option>';
|
|
692
|
+
$('#scPick').disabled = !roster.length;
|
|
693
|
+
$('#refresh-btn').disabled = !roster.length;
|
|
694
|
+
if (state.sc !== prev) { state.open.clear(); state.review.clear(); state.snap = null; if (state.sc) loadSnapshot(); }
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
async function loadRoster() {
|
|
698
|
+
applyRoster(await api('/api/roster'));
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
function renderRosterList(roster) {
|
|
702
|
+
$('#roster-list').innerHTML = roster.length
|
|
703
|
+
? roster.map(r => `<li><span>${esc(r.name)} ${r.id ? `<span class="meta mono">${esc(r.id)}</span>` : '<span class="pill fail">No Salesforce ID</span>'}</span><button type="button" data-remove="${esc(r.name)}">Remove</button></li>`).join('')
|
|
704
|
+
: '<li class="none">No names yet. Search below to add Salesforce users.</li>';
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/* ============================================================ SETTINGS ============================================================ */
|
|
708
|
+
async function loadSettings() {
|
|
709
|
+
const s = await api('/api/settings');
|
|
710
|
+
$('#host').value = s.runlayerHost;
|
|
711
|
+
$('#server-id').value = s.salesforceServerId;
|
|
712
|
+
$('#api-key').value = '';
|
|
713
|
+
$('#key-status').textContent = s.apiKeySet ? `Saved key: ${s.apiKeyMasked}. Enter a new key to replace it.` : 'No key saved yet.';
|
|
714
|
+
}
|
|
715
|
+
const settingsMsg = (text, sel = '#settings-msg') => { $(sel).textContent = text; };
|
|
716
|
+
|
|
717
|
+
$('#settings-form').addEventListener('submit', async e => {
|
|
718
|
+
e.preventDefault();
|
|
719
|
+
try {
|
|
720
|
+
const r = await api('/api/settings', { method: 'POST', body: { apiKey: $('#api-key').value, runlayerHost: $('#host').value, salesforceServerId: $('#server-id').value } });
|
|
721
|
+
settingsMsg(`Saved. Key: ${r.apiKeyMasked || 'none'}`);
|
|
722
|
+
loadSettings();
|
|
723
|
+
} catch (err) { settingsMsg(err.message); }
|
|
724
|
+
});
|
|
725
|
+
$('#test-btn').addEventListener('click', async () => {
|
|
726
|
+
settingsMsg('Testing…');
|
|
727
|
+
try {
|
|
728
|
+
const r = await api('/api/settings/test', { method: 'POST' });
|
|
729
|
+
settingsMsg(`Connected. Salesforce tools: ${r.tools.join(', ')}`);
|
|
730
|
+
} catch (err) { settingsMsg(`Failed: ${err.message}`); }
|
|
731
|
+
});
|
|
732
|
+
$('#clear-key').addEventListener('click', async () => {
|
|
733
|
+
if (!confirm('Remove the saved API key?')) return;
|
|
734
|
+
await api('/api/settings/key', { method: 'DELETE' });
|
|
735
|
+
settingsMsg('Key removed.');
|
|
736
|
+
loadSettings();
|
|
737
|
+
});
|
|
738
|
+
/* Name lookup: searches Salesforce after 3+ letters, re-running as the text changes. */
|
|
739
|
+
const lookup = { timer: null, seq: 0, results: [], active: -1 };
|
|
740
|
+
function showSuggest(html) {
|
|
741
|
+
const ul = $('#roster-suggest');
|
|
742
|
+
ul.hidden = !html;
|
|
743
|
+
ul.innerHTML = html || '';
|
|
744
|
+
$('#roster-name').setAttribute('aria-expanded', String(!!html));
|
|
745
|
+
}
|
|
746
|
+
function renderSuggest() {
|
|
747
|
+
if (!lookup.results.length) return showSuggest('<li class="info">No matching active users.</li>');
|
|
748
|
+
showSuggest(lookup.results.map((u, i) => {
|
|
749
|
+
const added = !!state.scs[u.id];
|
|
750
|
+
return `<li role="option" class="${added ? 'added' : ''}" data-i="${i}" aria-selected="${i === lookup.active}"><span>${esc(u.name)}</span><span class="meta">${added ? 'Added' : ''}</span></li>`;
|
|
751
|
+
}).join(''));
|
|
752
|
+
}
|
|
753
|
+
$('#roster-name').addEventListener('input', e => {
|
|
754
|
+
const text = e.target.value.trim();
|
|
755
|
+
clearTimeout(lookup.timer);
|
|
756
|
+
const seq = ++lookup.seq;
|
|
757
|
+
if (text.length < 3) { lookup.results = []; showSuggest(text ? '<li class="info">Type at least 3 letters…</li>' : ''); return; }
|
|
758
|
+
showSuggest('<li class="info">Searching…</li>');
|
|
759
|
+
lookup.timer = setTimeout(async () => {
|
|
760
|
+
try {
|
|
761
|
+
const users = await api(`/api/users/search?q=${encodeURIComponent(text)}`);
|
|
762
|
+
if (seq !== lookup.seq) return; // a newer keystroke superseded this search
|
|
763
|
+
lookup.results = users; lookup.active = -1;
|
|
764
|
+
renderSuggest();
|
|
765
|
+
} catch (err) {
|
|
766
|
+
if (seq === lookup.seq) showSuggest(`<li class="info">${esc(err.message)}</li>`);
|
|
767
|
+
}
|
|
768
|
+
}, 300);
|
|
769
|
+
});
|
|
770
|
+
async function addUser(u) {
|
|
771
|
+
if (!u || state.scs[u.id]) return;
|
|
772
|
+
try {
|
|
773
|
+
applyRoster(await api('/api/roster', { method: 'POST', body: { name: u.name } }));
|
|
774
|
+
settingsMsg(`Added ${u.name}.`, '#roster-msg');
|
|
775
|
+
$('#roster-name').value = ''; lookup.results = []; lookup.seq++; showSuggest('');
|
|
776
|
+
} catch (err) { settingsMsg(err.message, '#roster-msg'); }
|
|
777
|
+
}
|
|
778
|
+
$('#roster-suggest').addEventListener('mousedown', e => {
|
|
779
|
+
const li = e.target.closest('li[data-i]');
|
|
780
|
+
if (!li) return;
|
|
781
|
+
e.preventDefault();
|
|
782
|
+
addUser(lookup.results[+li.dataset.i]);
|
|
783
|
+
});
|
|
784
|
+
$('#roster-name').addEventListener('keydown', e => {
|
|
785
|
+
if (!lookup.results.length || $('#roster-suggest').hidden) return;
|
|
786
|
+
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
|
|
787
|
+
e.preventDefault();
|
|
788
|
+
const n = lookup.results.length;
|
|
789
|
+
lookup.active = (lookup.active + (e.key === 'ArrowDown' ? 1 : -1) + n) % n;
|
|
790
|
+
renderSuggest();
|
|
791
|
+
} else if (e.key === 'Enter') {
|
|
792
|
+
e.preventDefault();
|
|
793
|
+
addUser(lookup.results[lookup.active >= 0 ? lookup.active : 0]);
|
|
794
|
+
} else if (e.key === 'Escape') showSuggest('');
|
|
795
|
+
});
|
|
796
|
+
$('#roster-name').addEventListener('blur', () => setTimeout(() => showSuggest(''), 150));
|
|
797
|
+
$('#roster-list').addEventListener('click', async e => {
|
|
798
|
+
const name = e.target.closest('[data-remove]')?.dataset.remove;
|
|
799
|
+
if (!name) return;
|
|
800
|
+
try {
|
|
801
|
+
applyRoster(await api(`/api/roster/${encodeURIComponent(name)}`, { method: 'DELETE' }));
|
|
802
|
+
settingsMsg(`Removed ${name}.`, '#roster-msg');
|
|
803
|
+
} catch (err) { settingsMsg(err.message, '#roster-msg'); }
|
|
804
|
+
});
|
|
805
|
+
|
|
806
|
+
/* ============================================================ EVENTS ============================================================ */
|
|
807
|
+
$('#scPick').onchange = e => {
|
|
808
|
+
state.sc = e.target.value;
|
|
809
|
+
try { localStorage.setItem('scId', state.sc); } catch { }
|
|
810
|
+
state.open.clear(); state.review.clear(); message('');
|
|
811
|
+
loadSnapshot();
|
|
812
|
+
};
|
|
813
|
+
$('#q').oninput = e => { state.q = e.target.value.toLowerCase(); render(); };
|
|
814
|
+
$('#refresh-btn').onclick = refresh;
|
|
815
|
+
|
|
816
|
+
await loadRoster();
|
|
817
|
+
render();
|
|
818
|
+
|
|
819
|
+
// Footer: when the app's code last changed.
|
|
820
|
+
api('/api/version').then(v => { $('#site-foot').textContent = `Code updated ${new Date(v.codeUpdatedAt).toLocaleString()}`; }).catch(() => { });
|