scdashboard 0.0.0-stage → 1.0.1
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 +9 -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/README.md
CHANGED
|
@@ -1,3 +1,29 @@
|
|
|
1
|
-
#
|
|
1
|
+
# SC Record Hygiene
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Node app that shows, for one Solution Consultant at a time, their open opportunities (current fiscal quarter plus the next two), whether each one has an SC record (`POC__c`), and what needs fixing. Salesforce data comes through the Runlayer MCP proxy.
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
## Quick start (no setup needed)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
npm install
|
|
10
|
+
npm start # http://localhost:4000 (PORT=... to change)
|
|
11
|
+
|
|
12
|
+
1. Open **Settings** and paste your Runlayer Personal API Key, then click **Test connection**.
|
|
13
|
+
2. On the dashboard, pick an SC and click **Refresh from Salesforce**.
|
|
14
|
+
|
|
15
|
+
Everything is saved in `data/` (git-ignored, owner-only permissions), and the two settings files are created on first start: `runlayer.json` holds the Runlayer API key, `config.json` the Runlayer host and Salesforce server ID, `roster.json` the SC names, and `snapshot.json` the Salesforce data. The server listens on 127.0.0.1 only.
|
|
16
|
+
|
|
17
|
+
### 1. Personal API key (Settings page, not an env var)
|
|
18
|
+
|
|
19
|
+
Create one in the Runlayer dashboard under **Settings → Personal API keys**
|
|
20
|
+
(shown only once), then paste it into this app's **Settings → Runlayer API
|
|
21
|
+
key** field. It's stored server-side in `data/runlayer.json` (gitignored,
|
|
22
|
+
`0600` permissions, never redisplayed once saved — only a masked last-4
|
|
23
|
+
badge is shown) and used on every calendar call via the `x-runlayer-api-key`
|
|
24
|
+
header.
|
|
25
|
+
|
|
26
|
+
### 2. Roster (Settings page)
|
|
27
|
+
|
|
28
|
+
`/settings` lets you add/remove the email addresses on the roster,
|
|
29
|
+
persisted to `data/roster.json`. It is a simple list of SC names as entered in Salesforce.
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Persisted settings, split across two owner-only files in data/:
|
|
2
|
+
// config.json – connection settings (Runlayer host, Salesforce server id)
|
|
3
|
+
// runlayer.json – Runlayer Personal API Key
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
const DATA_DIR = path.resolve(import.meta.dirname, '..', 'data');
|
|
8
|
+
const CONFIG_FILE = path.join(DATA_DIR, 'config.json');
|
|
9
|
+
const KEY_FILE = path.join(DATA_DIR, 'runlayer.json');
|
|
10
|
+
|
|
11
|
+
const DEFAULTS = {
|
|
12
|
+
runlayerHost: 'https://pagerduty.runlayer.com',
|
|
13
|
+
salesforceServerId: 'dd751e29-daeb-4cdb-a331-ffdde299f3e1',
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
function readJson(file) {
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
19
|
+
} catch {
|
|
20
|
+
return {};
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function writeJson(file, data) {
|
|
25
|
+
fs.mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 });
|
|
26
|
+
fs.writeFileSync(file, JSON.stringify(data, null, 2), { mode: 0o600 });
|
|
27
|
+
fs.chmodSync(file, 0o600);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Create both files on start if needed, and move an API key left in
|
|
31
|
+
// config.json by older versions into runlayer.json.
|
|
32
|
+
export function initConfig() {
|
|
33
|
+
const cfg = readJson(CONFIG_FILE);
|
|
34
|
+
const key = readJson(KEY_FILE);
|
|
35
|
+
const legacyKey = cfg.apiKey;
|
|
36
|
+
delete cfg.apiKey;
|
|
37
|
+
if (!fs.existsSync(KEY_FILE) || (legacyKey && !key.apiKey)) writeJson(KEY_FILE, { apiKey: key.apiKey || legacyKey || '' });
|
|
38
|
+
if (!fs.existsSync(CONFIG_FILE) || legacyKey !== undefined) writeJson(CONFIG_FILE, { ...DEFAULTS, ...cfg });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function loadConfig() {
|
|
42
|
+
return { ...DEFAULTS, ...readJson(CONFIG_FILE), apiKey: readJson(KEY_FILE).apiKey || '' };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function saveConfig(patch) {
|
|
46
|
+
const { apiKey, ...settings } = patch;
|
|
47
|
+
if (apiKey !== undefined) writeJson(KEY_FILE, { apiKey });
|
|
48
|
+
if (Object.keys(settings).length) writeJson(CONFIG_FILE, { ...DEFAULTS, ...readJson(CONFIG_FILE), ...settings });
|
|
49
|
+
return loadConfig();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function maskKey(key) {
|
|
53
|
+
if (!key) return '';
|
|
54
|
+
return key.length <= 8 ? '••••' : `${key.slice(0, 4)}••••${key.slice(-4)}`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export { DATA_DIR };
|
package/lib/runlayer.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Minimal Runlayer MCP client: connects to the Salesforce server through the
|
|
2
|
+
// Runlayer proxy using a Personal API Key and runs SOQL.
|
|
3
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
4
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
5
|
+
import { loadConfig } from './config.js';
|
|
6
|
+
|
|
7
|
+
async function connect() {
|
|
8
|
+
const cfg = loadConfig();
|
|
9
|
+
if (!cfg.apiKey) throw new Error('No Runlayer API key set. Add one on the Settings page.');
|
|
10
|
+
const url = new URL(`${cfg.runlayerHost.replace(/\/$/, '')}/api/v1/proxy/${cfg.salesforceServerId}/mcp`);
|
|
11
|
+
const transport = new StreamableHTTPClientTransport(url, {
|
|
12
|
+
requestInit: { headers: { 'x-runlayer-api-key': cfg.apiKey } },
|
|
13
|
+
});
|
|
14
|
+
const client = new Client({ name: 'scdashboard', version: '1.0.0' });
|
|
15
|
+
await client.connect(transport);
|
|
16
|
+
return client;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function findTool(tools, re) {
|
|
20
|
+
const t = tools.find((x) => re.test(x.name));
|
|
21
|
+
if (!t) throw new Error(`Salesforce tool matching ${re} not found. Available: ${tools.map((x) => x.name).join(', ')}`);
|
|
22
|
+
return t.name;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// Pull a JSON payload out of an MCP tool result.
|
|
26
|
+
function parseResult(res) {
|
|
27
|
+
if (res.isError) {
|
|
28
|
+
const msg = (res.content || []).map((c) => c.text).join('\n');
|
|
29
|
+
throw new Error(msg || 'Salesforce tool returned an error');
|
|
30
|
+
}
|
|
31
|
+
if (res.structuredContent) return res.structuredContent;
|
|
32
|
+
const text = (res.content || []).filter((c) => c.type === 'text').map((c) => c.text).join('');
|
|
33
|
+
try {
|
|
34
|
+
return JSON.parse(text);
|
|
35
|
+
} catch {
|
|
36
|
+
const m = text.match(/[[{][\s\S]*[\]}]/);
|
|
37
|
+
if (m) return JSON.parse(m[0]);
|
|
38
|
+
throw new Error(`Unexpected Salesforce response: ${text.slice(0, 300)}`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function recordsOf(payload) {
|
|
43
|
+
if (Array.isArray(payload)) return payload;
|
|
44
|
+
for (const k of ['records', 'result', 'data']) {
|
|
45
|
+
if (payload?.[k]) return recordsOf(payload[k]);
|
|
46
|
+
}
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function withSalesforce(fn) {
|
|
51
|
+
const client = await connect();
|
|
52
|
+
try {
|
|
53
|
+
const { tools } = await client.listTools();
|
|
54
|
+
const soqlTool = findTool(tools, /soql/i);
|
|
55
|
+
// Use the tool's own argument name for the SOQL string (e.g. "q").
|
|
56
|
+
const schema = tools.find((t) => t.name === soqlTool).inputSchema || {};
|
|
57
|
+
const argName = schema.required?.[0] || Object.keys(schema.properties || {})[0] || 'q';
|
|
58
|
+
const query = async (soql) => {
|
|
59
|
+
const res = await client.callTool({ name: soqlTool, arguments: { [argName]: soql } });
|
|
60
|
+
return recordsOf(parseResult(res));
|
|
61
|
+
};
|
|
62
|
+
return await fn({ query, tools });
|
|
63
|
+
} finally {
|
|
64
|
+
await client.close().catch(() => {});
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export async function testConnection() {
|
|
69
|
+
return withSalesforce(async ({ query, tools }) => {
|
|
70
|
+
const rows = await query('SELECT Id FROM User LIMIT 1');
|
|
71
|
+
return { ok: true, tools: tools.map((t) => t.name), sampleRows: rows.length };
|
|
72
|
+
});
|
|
73
|
+
}
|
package/lib/slack.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Slack via the Runlayer MCP proxy: find a user by email, open a DM, and draft or send a message.
|
|
2
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
3
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
4
|
+
import { loadConfig } from './config.js';
|
|
5
|
+
|
|
6
|
+
const SLACK_SERVER_ID = '7f4756a0-b998-420e-b0cb-9967549991ec';
|
|
7
|
+
|
|
8
|
+
async function withSlack(fn) {
|
|
9
|
+
const cfg = loadConfig();
|
|
10
|
+
if (!cfg.apiKey) throw new Error('No Runlayer API key set. Add one on the Settings page.');
|
|
11
|
+
const url = new URL(`${cfg.runlayerHost.replace(/\/$/, '')}/api/v1/proxy/${cfg.slackServerId || SLACK_SERVER_ID}/mcp`);
|
|
12
|
+
const transport = new StreamableHTTPClientTransport(url, {
|
|
13
|
+
requestInit: { headers: { 'x-runlayer-api-key': cfg.apiKey } },
|
|
14
|
+
});
|
|
15
|
+
const client = new Client({ name: 'scdashboard', version: '1.0.0' });
|
|
16
|
+
await client.connect(transport);
|
|
17
|
+
const call = async (name, args) => {
|
|
18
|
+
const res = await client.callTool({ name, arguments: args });
|
|
19
|
+
const text = (res.content || []).filter((c) => c.type === 'text').map((c) => c.text).join('');
|
|
20
|
+
if (res.isError) throw new Error(text || `Slack ${name} failed`);
|
|
21
|
+
return text;
|
|
22
|
+
};
|
|
23
|
+
try {
|
|
24
|
+
return await fn(call);
|
|
25
|
+
} finally {
|
|
26
|
+
await client.close().catch(() => {});
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Search results look like: "1. corbin (he/him) - U02DZQZ4SV8 - cmills@pagerduty.com - Title"
|
|
31
|
+
async function findUserId(call, email, name) {
|
|
32
|
+
const want = email.toLowerCase();
|
|
33
|
+
const words = [email.split('@')[0], ...String(name || '').split(/\s+/)].filter((w) => w && w.length > 1);
|
|
34
|
+
for (const word of [...new Set(words)]) {
|
|
35
|
+
const text = await call('slack_search_users', { keywords: [word], limit: 20, response_format: 'concise' });
|
|
36
|
+
for (const m of text.matchAll(/\b(U[A-Z0-9]{6,})\b\s*-\s*([^\s]+@[^\s]+)/g)) {
|
|
37
|
+
if (m[2].toLowerCase() === want) return m[1];
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
throw new Error(`No Slack user found with email ${email}.`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Open a DM with the user who has `email` and either save `message` as a draft
|
|
45
|
+
* (default) or send it. Returns the DM channel id and a link that opens it.
|
|
46
|
+
*/
|
|
47
|
+
export async function slackDm({ email, name, message, send = false }) {
|
|
48
|
+
if (!email) throw new Error('No email address for this SC.');
|
|
49
|
+
if (!message?.trim()) throw new Error('The message is empty.');
|
|
50
|
+
return withSlack(async (call) => {
|
|
51
|
+
const userId = await findUserId(call, email, name);
|
|
52
|
+
const conv = await call('slack_create_conversation', { user_ids: [userId] });
|
|
53
|
+
const channelId = (conv.match(/\b(D[A-Z0-9]{6,})\b/) || conv.match(/\b([CG][A-Z0-9]{6,})\b/) || [])[1];
|
|
54
|
+
if (!channelId) throw new Error(`Couldn't open a Slack DM: ${conv.slice(0, 200)}`);
|
|
55
|
+
if (send) await call('slack_send_message', { channel_id: channelId, message });
|
|
56
|
+
else await call('slack_send_message_draft', { channel_id: channelId, message });
|
|
57
|
+
return { userId, channelId, sent: send, link: `https://slack.com/app_redirect?channel=${channelId}` };
|
|
58
|
+
});
|
|
59
|
+
}
|
package/lib/snapshot.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
// Builds and persists the per-SC Salesforce snapshot.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { DATA_DIR } from './config.js';
|
|
5
|
+
import { withSalesforce } from './runlayer.js';
|
|
6
|
+
|
|
7
|
+
const SNAPSHOT_FILE = path.join(DATA_DIR, 'snapshot.json');
|
|
8
|
+
|
|
9
|
+
// Fiscal year starts Feb 1; FY is named for the calendar year it ends in.
|
|
10
|
+
export function fiscalQuarter(d) {
|
|
11
|
+
const date = typeof d === 'string' ? new Date(`${d}T00:00:00Z`) : d;
|
|
12
|
+
const m = date.getUTCMonth(); // 0 = Jan
|
|
13
|
+
const idx = (m - 1 + 12) % 12; // 0 = Feb
|
|
14
|
+
const fy = m === 0 ? date.getUTCFullYear() : date.getUTCFullYear() + 1;
|
|
15
|
+
return { fy, q: Math.floor(idx / 3) + 1, label: `FY${String(fy).slice(-2)} Q${Math.floor(idx / 3) + 1}` };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function quarterStart(fy, q) {
|
|
19
|
+
// Q1 starts Feb 1 of (fy - 1)
|
|
20
|
+
const monthsFromFeb = (q - 1) * 3;
|
|
21
|
+
return new Date(Date.UTC(fy - 1, 1 + monthsFromFeb, 1));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const iso = (d) => d.toISOString().slice(0, 10);
|
|
25
|
+
|
|
26
|
+
// Number of fiscal quarters collected: the current one plus the next two.
|
|
27
|
+
export const QUARTER_COUNT = 3;
|
|
28
|
+
|
|
29
|
+
export function dateWindow(today = new Date()) {
|
|
30
|
+
let { fy, q } = fiscalQuarter(today);
|
|
31
|
+
const starts = [];
|
|
32
|
+
for (let i = 0; i < QUARTER_COUNT; i++) {
|
|
33
|
+
starts.push(quarterStart(fy, q));
|
|
34
|
+
[fy, q] = q === 4 ? [fy + 1, 1] : [fy, q + 1];
|
|
35
|
+
}
|
|
36
|
+
const last = starts[starts.length - 1];
|
|
37
|
+
const end = new Date(Date.UTC(last.getUTCFullYear(), last.getUTCMonth() + 3, 0));
|
|
38
|
+
return { qStart: iso(starts[0]), qEnd: iso(end), quarters: starts.map((d) => fiscalQuarter(d).label) };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const ROLES = "('Solution_Consultant','Sales Engineer')";
|
|
42
|
+
const safeId = (id) => {
|
|
43
|
+
if (!/^[a-zA-Z0-9]{15,18}$/.test(id)) throw new Error('Invalid Salesforce user id');
|
|
44
|
+
return id;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const SC_FIELDS = `Id, Name, POC_Stage__c, Closed_Reason__c, Start_Date__c, End_Date__c, Notes__c,
|
|
48
|
+
Use_Case_inc_3_Whys__c, UseCase1__c, UseCase2__c, UseCase3__c, Risk__c,
|
|
49
|
+
Link_to_PagerDuty_POV__c, Test_Plan_Included__c, BlockerCategory__c, Blockers__c, SC_Manager_Notes__c,
|
|
50
|
+
Partial_Or_No_Fit_Reason__c, Risk_Details__c, ProofOfValueStatus__c, POVStartDate__c, POVEndDate__c, ReviewedDate__c,
|
|
51
|
+
Opportunity__c, Opportunity__r.Name, Opportunity__r.StageName, Opportunity__r.Type,
|
|
52
|
+
Opportunity__r.ForecastCategoryName, Opportunity__r.CloseDate, Opportunity__r.Amount,
|
|
53
|
+
Opportunity__r.Owner.Name, Opportunity__r.OwnerId, Opportunity__r.Account.Name, Opportunity__r.SC_Notes__c,
|
|
54
|
+
Sales_Lead__c, Sales_Lead__r.Name`;
|
|
55
|
+
|
|
56
|
+
export function queries(scId, { qStart, qEnd }) {
|
|
57
|
+
const id = safeId(scId);
|
|
58
|
+
const acctOpps = `SELECT Id FROM Opportunity WHERE IsClosed = false AND Account.Solution_Consultant__c = '${id}' AND CloseDate >= ${qStart} AND CloseDate <= ${qEnd}`;
|
|
59
|
+
const teamOpps = `SELECT OpportunityId FROM OpportunityTeamMember WHERE UserId = '${id}' AND TeamMemberRole IN ${ROLES} AND Opportunity.IsClosed = false AND Opportunity.CloseDate >= ${qStart} AND Opportunity.CloseDate <= ${qEnd}`;
|
|
60
|
+
return {
|
|
61
|
+
scRecords: `SELECT ${SC_FIELDS} FROM POC__c WHERE Solution_Consultant__c = '${id}' AND Opportunity__r.IsClosed = false AND Opportunity__r.CloseDate >= ${qStart} AND Opportunity__r.CloseDate <= ${qEnd}`,
|
|
62
|
+
accountSc: `SELECT Id, Name, StageName, Type, ForecastCategoryName, CloseDate, Amount, Account.Name, Owner.Name FROM Opportunity WHERE IsClosed = false AND Account.Solution_Consultant__c = '${id}' AND CloseDate >= ${qStart} AND CloseDate <= ${qEnd}`,
|
|
63
|
+
oppTeam: `SELECT OpportunityId, TeamMemberRole, Opportunity.Name, Opportunity.StageName, Opportunity.Type, Opportunity.ForecastCategoryName, Opportunity.CloseDate, Opportunity.Amount, Opportunity.Account.Name, Opportunity.Owner.Name FROM OpportunityTeamMember WHERE UserId = '${id}' AND Opportunity.IsClosed = false AND TeamMemberRole IN ${ROLES} AND Opportunity.CloseDate >= ${qStart} AND Opportunity.CloseDate <= ${qEnd}`,
|
|
64
|
+
otherOnAccount: `SELECT Id, Name, Opportunity__c, Solution_Consultant__r.Name FROM POC__c WHERE Solution_Consultant__c != '${id}' AND Opportunity__c IN (${acctOpps})`,
|
|
65
|
+
otherOnTeam: `SELECT Id, Name, Opportunity__c, Solution_Consultant__r.Name FROM POC__c WHERE Solution_Consultant__c != '${id}' AND Opportunity__c IN (${teamOpps})`,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Rich-text fields (e.g. Opportunity.SC_Notes__c) arrive as HTML; turn them into plain text.
|
|
70
|
+
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ', '#39': "'" };
|
|
71
|
+
function htmlToText(html) {
|
|
72
|
+
if (!html) return null;
|
|
73
|
+
return String(html)
|
|
74
|
+
.replace(/<\s*br\s*\/?>/gi, '\n')
|
|
75
|
+
.replace(/<\/\s*(p|div|li|h[1-6]|tr)\s*>/gi, '\n')
|
|
76
|
+
.replace(/<\s*li[^>]*>/gi, '• ')
|
|
77
|
+
.replace(/<[^>]+>/g, '')
|
|
78
|
+
.replace(/&(#\d+|#x[0-9a-f]+|\w+);/gi, (m, e) => e[0] === '#'
|
|
79
|
+
? String.fromCodePoint(e[1].toLowerCase() === 'x' ? parseInt(e.slice(2), 16) : +e.slice(1))
|
|
80
|
+
: ENTITIES[e.toLowerCase()] ?? m)
|
|
81
|
+
.replace(/[ \t]+\n/g, '\n')
|
|
82
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
83
|
+
.trim() || null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const oppFrom = (o, id) => ({
|
|
87
|
+
id,
|
|
88
|
+
name: o?.Name ?? '',
|
|
89
|
+
stage: o?.StageName ?? '',
|
|
90
|
+
type: o?.Type ?? '',
|
|
91
|
+
forecast: o?.ForecastCategoryName ?? '',
|
|
92
|
+
closeDate: o?.CloseDate ?? null,
|
|
93
|
+
amount: o?.Amount ?? 0,
|
|
94
|
+
owner: o?.Owner?.Name ?? '',
|
|
95
|
+
ownerId: o?.OwnerId ?? null,
|
|
96
|
+
scNotes: htmlToText(o?.SC_Notes__c),
|
|
97
|
+
account: o?.Account?.Name ?? '',
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
function sourceTag(inAcct, inTeam) {
|
|
101
|
+
if (inAcct && inTeam) return 'Account SC + Opp Team';
|
|
102
|
+
if (inAcct) return 'Account SC';
|
|
103
|
+
if (inTeam) return 'Opp Team';
|
|
104
|
+
return 'SC record only';
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function fetchSc(scId) {
|
|
108
|
+
const win = dateWindow();
|
|
109
|
+
const q = queries(scId, win);
|
|
110
|
+
const raw = await withSalesforce(async ({ query }) => {
|
|
111
|
+
const [scRecords, accountSc, oppTeam, otherOnAccount, otherOnTeam] = await Promise.all([
|
|
112
|
+
query(q.scRecords), query(q.accountSc), query(q.oppTeam), query(q.otherOnAccount), query(q.otherOnTeam),
|
|
113
|
+
]);
|
|
114
|
+
return { scRecords, accountSc, oppTeam, otherOnAccount, otherOnTeam };
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
const acctIds = new Set(raw.accountSc.map((o) => o.Id));
|
|
118
|
+
const teamIds = new Set(raw.oppTeam.map((t) => t.OpportunityId));
|
|
119
|
+
const opps = new Map();
|
|
120
|
+
for (const o of raw.accountSc) opps.set(o.Id, oppFrom(o, o.Id));
|
|
121
|
+
for (const t of raw.oppTeam) if (!opps.has(t.OpportunityId)) opps.set(t.OpportunityId, oppFrom(t.Opportunity, t.OpportunityId));
|
|
122
|
+
|
|
123
|
+
const records = raw.scRecords.map((r) => ({
|
|
124
|
+
id: r.Id,
|
|
125
|
+
name: r.Name,
|
|
126
|
+
stage: r.POC_Stage__c,
|
|
127
|
+
closedReason: r.Closed_Reason__c,
|
|
128
|
+
fitReason: r.Partial_Or_No_Fit_Reason__c,
|
|
129
|
+
riskDetails: r.Risk_Details__c,
|
|
130
|
+
salesLead: r.Sales_Lead__c ? { id: r.Sales_Lead__c, name: r.Sales_Lead__r?.Name ?? '' } : null,
|
|
131
|
+
startDate: r.Start_Date__c,
|
|
132
|
+
endDate: r.End_Date__c,
|
|
133
|
+
notes: r.Notes__c,
|
|
134
|
+
mtr: r.Use_Case_inc_3_Whys__c,
|
|
135
|
+
useCases: [r.UseCase1__c, r.UseCase2__c, r.UseCase3__c],
|
|
136
|
+
status: r.Risk__c,
|
|
137
|
+
validationPlan: r.Link_to_PagerDuty_POV__c,
|
|
138
|
+
povReviewed: !!r.Test_Plan_Included__c,
|
|
139
|
+
pov: {
|
|
140
|
+
status: r.ProofOfValueStatus__c,
|
|
141
|
+
start: r.POVStartDate__c,
|
|
142
|
+
end: r.POVEndDate__c,
|
|
143
|
+
reviewedDate: r.ReviewedDate__c,
|
|
144
|
+
},
|
|
145
|
+
blockerCategory: r.BlockerCategory__c,
|
|
146
|
+
blockers: r.Blockers__c,
|
|
147
|
+
managerNotes: r.SC_Manager_Notes__c,
|
|
148
|
+
opp: oppFrom(r.Opportunity__r, r.Opportunity__c),
|
|
149
|
+
source: sourceTag(acctIds.has(r.Opportunity__c), teamIds.has(r.Opportunity__c)),
|
|
150
|
+
}));
|
|
151
|
+
|
|
152
|
+
const covered = new Set(records.map((r) => r.opp.id));
|
|
153
|
+
const others = new Map();
|
|
154
|
+
for (const p of [...raw.otherOnAccount, ...raw.otherOnTeam]) {
|
|
155
|
+
const list = others.get(p.Opportunity__c) || [];
|
|
156
|
+
if (!list.some((x) => x.id === p.Id)) list.push({ id: p.Id, name: p.Name, sc: p.Solution_Consultant__r?.Name ?? 'another SC' });
|
|
157
|
+
others.set(p.Opportunity__c, list);
|
|
158
|
+
}
|
|
159
|
+
const noRecord = [...opps.values()]
|
|
160
|
+
.filter((o) => !covered.has(o.id))
|
|
161
|
+
.map((o) => ({ ...o, source: sourceTag(acctIds.has(o.id), teamIds.has(o.id)), otherRecords: others.get(o.id) || [] }));
|
|
162
|
+
|
|
163
|
+
return {
|
|
164
|
+
scId,
|
|
165
|
+
window: win,
|
|
166
|
+
fetchedAt: new Date().toISOString(),
|
|
167
|
+
counts: Object.fromEntries(Object.entries(raw).map(([k, v]) => [k, v.length])),
|
|
168
|
+
records,
|
|
169
|
+
noRecord,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function loadSnapshots() {
|
|
174
|
+
try {
|
|
175
|
+
return JSON.parse(fs.readFileSync(SNAPSHOT_FILE, 'utf8'));
|
|
176
|
+
} catch {
|
|
177
|
+
return {};
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Compare two snapshots for one SC and list what changed.
|
|
182
|
+
export function diff(prev, next) {
|
|
183
|
+
if (!prev) return [];
|
|
184
|
+
const changes = [];
|
|
185
|
+
const fields = ['stage', 'type', 'forecast', 'closeDate', 'amount'];
|
|
186
|
+
const index = (s) => {
|
|
187
|
+
const m = new Map();
|
|
188
|
+
for (const r of s.records) m.set(r.opp.id, { ...r.opp, scStage: r.stage, scNotes: r.notes });
|
|
189
|
+
for (const o of s.noRecord) if (!m.has(o.id)) m.set(o.id, o);
|
|
190
|
+
return m;
|
|
191
|
+
};
|
|
192
|
+
const a = index(prev), b = index(next);
|
|
193
|
+
for (const [id, o] of b) {
|
|
194
|
+
const old = a.get(id);
|
|
195
|
+
if (!old) { changes.push({ opp: o.name, field: 'added', old: '', new: o.stage }); continue; }
|
|
196
|
+
for (const f of fields) {
|
|
197
|
+
const changed = f === 'amount' ? Math.abs((old[f] || 0) - (o[f] || 0)) > 1 : old[f] !== o[f];
|
|
198
|
+
if (changed) changes.push({ opp: o.name, field: f, old: old[f], new: o[f] });
|
|
199
|
+
}
|
|
200
|
+
if ('scStage' in o && old.scStage !== o.scStage) changes.push({ opp: o.name, field: 'SC stage', old: old.scStage, new: o.scStage });
|
|
201
|
+
if ('scNotes' in o && 'scNotes' in old && old.scNotes !== o.scNotes) changes.push({ opp: o.name, field: 'SC notes', old: '…', new: 'updated' });
|
|
202
|
+
}
|
|
203
|
+
for (const [id, o] of a) if (!b.has(id)) changes.push({ opp: o.name, field: 'removed (closed or out of window)', old: o.stage, new: '' });
|
|
204
|
+
const prevNoRec = new Set(prev.noRecord.map((o) => o.id));
|
|
205
|
+
for (const r of next.records) if (prevNoRec.has(r.opp.id)) changes.push({ opp: r.opp.name, field: 'SC record', old: 'none', new: r.name });
|
|
206
|
+
return changes;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export async function refreshSc(scId) {
|
|
210
|
+
const all = loadSnapshots();
|
|
211
|
+
const next = await fetchSc(scId);
|
|
212
|
+
const changes = diff(all[scId], next);
|
|
213
|
+
all[scId] = next;
|
|
214
|
+
fs.mkdirSync(DATA_DIR, { recursive: true, mode: 0o700 });
|
|
215
|
+
fs.writeFileSync(SNAPSHOT_FILE, JSON.stringify(all), { mode: 0o600 });
|
|
216
|
+
return { snapshot: next, changes };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Active users whose first name, last name or full name starts with the text.
|
|
220
|
+
export async function searchUsers(text) {
|
|
221
|
+
const t = String(text).slice(0, 80).replace(/[\\'%_]/g, (c) => `\\${c}`);
|
|
222
|
+
return withSalesforce(({ query }) => query(
|
|
223
|
+
`SELECT Id, Name FROM User WHERE IsActive = true AND UserType = 'Standard' AND (Name LIKE '${t}%' OR FirstName LIKE '${t}%' OR LastName LIKE '${t}%') ORDER BY Name LIMIT 15`,
|
|
224
|
+
));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Salesforce user Id and email for a list of full names (active users only).
|
|
228
|
+
export async function lookupUserIds(names) {
|
|
229
|
+
if (!names.length) return new Map();
|
|
230
|
+
const list = names.map((n) => `'${String(n).replace(/[\\']/g, (c) => `\\${c}`)}'`).join(', ');
|
|
231
|
+
const rows = await withSalesforce(({ query }) => query(
|
|
232
|
+
`SELECT Id, Name, Email FROM User WHERE IsActive = true AND Name IN (${list})`,
|
|
233
|
+
));
|
|
234
|
+
return new Map(rows.map((u) => [u.Name, { id: u.Id, email: u.Email }]));
|
|
235
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "scdashboard",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "SC Record Hygiene dashboard backed by Salesforce via Runlayer",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "server.js",
|
|
7
|
+
"dependencies": {
|
|
8
|
+
"@modelcontextprotocol/sdk": "^1.12.0",
|
|
9
|
+
"express": "^4.21.2"
|
|
10
|
+
}
|
|
11
|
+
}
|