optimal-cli 0.1.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 +175 -0
- package/dist/bin/optimal.d.ts +2 -0
- package/dist/bin/optimal.js +995 -0
- package/dist/lib/budget/projections.d.ts +115 -0
- package/dist/lib/budget/projections.js +384 -0
- package/dist/lib/budget/scenarios.d.ts +93 -0
- package/dist/lib/budget/scenarios.js +214 -0
- package/dist/lib/cms/publish-blog.d.ts +62 -0
- package/dist/lib/cms/publish-blog.js +74 -0
- package/dist/lib/cms/strapi-client.d.ts +123 -0
- package/dist/lib/cms/strapi-client.js +213 -0
- package/dist/lib/config.d.ts +55 -0
- package/dist/lib/config.js +206 -0
- package/dist/lib/infra/deploy.d.ts +29 -0
- package/dist/lib/infra/deploy.js +58 -0
- package/dist/lib/infra/migrate.d.ts +34 -0
- package/dist/lib/infra/migrate.js +103 -0
- package/dist/lib/kanban.d.ts +46 -0
- package/dist/lib/kanban.js +118 -0
- package/dist/lib/newsletter/distribute.d.ts +52 -0
- package/dist/lib/newsletter/distribute.js +193 -0
- package/dist/lib/newsletter/generate-insurance.d.ts +42 -0
- package/dist/lib/newsletter/generate-insurance.js +36 -0
- package/dist/lib/newsletter/generate.d.ts +104 -0
- package/dist/lib/newsletter/generate.js +571 -0
- package/dist/lib/returnpro/anomalies.d.ts +64 -0
- package/dist/lib/returnpro/anomalies.js +166 -0
- package/dist/lib/returnpro/audit.d.ts +32 -0
- package/dist/lib/returnpro/audit.js +147 -0
- package/dist/lib/returnpro/diagnose.d.ts +52 -0
- package/dist/lib/returnpro/diagnose.js +281 -0
- package/dist/lib/returnpro/kpis.d.ts +32 -0
- package/dist/lib/returnpro/kpis.js +192 -0
- package/dist/lib/returnpro/templates.d.ts +48 -0
- package/dist/lib/returnpro/templates.js +229 -0
- package/dist/lib/returnpro/upload-income.d.ts +25 -0
- package/dist/lib/returnpro/upload-income.js +235 -0
- package/dist/lib/returnpro/upload-netsuite.d.ts +37 -0
- package/dist/lib/returnpro/upload-netsuite.js +566 -0
- package/dist/lib/returnpro/upload-r1.d.ts +48 -0
- package/dist/lib/returnpro/upload-r1.js +398 -0
- package/dist/lib/social/post-generator.d.ts +83 -0
- package/dist/lib/social/post-generator.js +333 -0
- package/dist/lib/social/publish.d.ts +66 -0
- package/dist/lib/social/publish.js +226 -0
- package/dist/lib/social/scraper.d.ts +67 -0
- package/dist/lib/social/scraper.js +361 -0
- package/dist/lib/supabase.d.ts +4 -0
- package/dist/lib/supabase.js +20 -0
- package/dist/lib/transactions/delete-batch.d.ts +60 -0
- package/dist/lib/transactions/delete-batch.js +203 -0
- package/dist/lib/transactions/ingest.d.ts +43 -0
- package/dist/lib/transactions/ingest.js +555 -0
- package/dist/lib/transactions/stamp.d.ts +51 -0
- package/dist/lib/transactions/stamp.js +524 -0
- package/package.json +50 -0
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Budget projection calculator for FY26 planning
|
|
3
|
+
*
|
|
4
|
+
* Ported from wes-dashboard/src/lib/projections/calculator.ts
|
|
5
|
+
* Pure TypeScript — no React, no framework deps.
|
|
6
|
+
*
|
|
7
|
+
* Supports two adjustment types:
|
|
8
|
+
* - Percentage: projected = actual * (1 + rate/100)
|
|
9
|
+
* - Flat: projected = actual + flatAmount
|
|
10
|
+
*
|
|
11
|
+
* Supports both unit AND average retail projections for revenue forecasting.
|
|
12
|
+
*
|
|
13
|
+
* Data sources:
|
|
14
|
+
* - Supabase `fpa_wes_imports` table (ReturnPro instance)
|
|
15
|
+
* - JSON file from stdin or --file flag
|
|
16
|
+
*/
|
|
17
|
+
export interface CheckedInUnitsSummary {
|
|
18
|
+
programCode: string;
|
|
19
|
+
masterProgram: string;
|
|
20
|
+
masterProgramId: number | null;
|
|
21
|
+
clientId: number | null;
|
|
22
|
+
clientName: string;
|
|
23
|
+
unitCount: number;
|
|
24
|
+
countMethod: 'Unit' | 'Pallet';
|
|
25
|
+
avgRetail?: number;
|
|
26
|
+
monthLabel?: string;
|
|
27
|
+
}
|
|
28
|
+
export interface ProjectionEntry {
|
|
29
|
+
programCode: string;
|
|
30
|
+
masterProgram: string;
|
|
31
|
+
masterProgramId: number | null;
|
|
32
|
+
clientId: number | null;
|
|
33
|
+
clientName: string;
|
|
34
|
+
actualUnits: number;
|
|
35
|
+
adjustmentType: 'percentage' | 'flat';
|
|
36
|
+
adjustmentValue: number;
|
|
37
|
+
projectedUnits: number;
|
|
38
|
+
avgRetail?: number;
|
|
39
|
+
avgRetailAdjustmentType: 'percentage' | 'flat';
|
|
40
|
+
avgRetailAdjustmentValue: number;
|
|
41
|
+
projectedAvgRetail?: number;
|
|
42
|
+
}
|
|
43
|
+
export interface ProjectionInput {
|
|
44
|
+
actualUnits: number;
|
|
45
|
+
adjustmentType: 'percentage' | 'flat';
|
|
46
|
+
adjustmentValue: number;
|
|
47
|
+
}
|
|
48
|
+
export interface ProjectionTotals {
|
|
49
|
+
totalActual: number;
|
|
50
|
+
totalProjected: number;
|
|
51
|
+
percentageChange: number;
|
|
52
|
+
absoluteChange: number;
|
|
53
|
+
actualRevenue: number;
|
|
54
|
+
projectedRevenue: number;
|
|
55
|
+
revenueChange: number;
|
|
56
|
+
revenuePercentChange: number;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Calculate projected units based on adjustment type and value.
|
|
60
|
+
*/
|
|
61
|
+
export declare function calculateProjection(input: ProjectionInput): number;
|
|
62
|
+
/**
|
|
63
|
+
* Calculate projected average retail price.
|
|
64
|
+
*/
|
|
65
|
+
export declare function calculateAvgRetailProjection(actualAvgRetail: number | undefined, adjustmentType: 'percentage' | 'flat', adjustmentValue: number): number | undefined;
|
|
66
|
+
/**
|
|
67
|
+
* Convert checked-in units summary to projection entries with default values (0% change).
|
|
68
|
+
*/
|
|
69
|
+
export declare function initializeProjections(summary: CheckedInUnitsSummary[]): ProjectionEntry[];
|
|
70
|
+
/**
|
|
71
|
+
* Update a single projection entry's units.
|
|
72
|
+
*/
|
|
73
|
+
export declare function updateProjection(entry: ProjectionEntry, adjustmentType: 'percentage' | 'flat', adjustmentValue: number): ProjectionEntry;
|
|
74
|
+
/**
|
|
75
|
+
* Update a single projection entry's average retail.
|
|
76
|
+
*/
|
|
77
|
+
export declare function updateAvgRetailProjection(entry: ProjectionEntry, adjustmentType: 'percentage' | 'flat', adjustmentValue: number): ProjectionEntry;
|
|
78
|
+
/**
|
|
79
|
+
* Apply a uniform unit adjustment to all projections.
|
|
80
|
+
*/
|
|
81
|
+
export declare function applyUniformAdjustment(projections: ProjectionEntry[], adjustmentType: 'percentage' | 'flat', adjustmentValue: number): ProjectionEntry[];
|
|
82
|
+
/**
|
|
83
|
+
* Apply a uniform avg retail adjustment to all projections.
|
|
84
|
+
*/
|
|
85
|
+
export declare function applyUniformAvgRetailAdjustment(projections: ProjectionEntry[], adjustmentType: 'percentage' | 'flat', adjustmentValue: number): ProjectionEntry[];
|
|
86
|
+
/**
|
|
87
|
+
* Calculate totals for projection summary including revenue.
|
|
88
|
+
*/
|
|
89
|
+
export declare function calculateTotals(projections: ProjectionEntry[]): ProjectionTotals;
|
|
90
|
+
/**
|
|
91
|
+
* Group projections by client name.
|
|
92
|
+
*/
|
|
93
|
+
export declare function groupProjectionsByClient(projections: ProjectionEntry[]): Map<string, ProjectionEntry[]>;
|
|
94
|
+
/**
|
|
95
|
+
* Export projections to CSV format with unit + avgRetail + inventory value data.
|
|
96
|
+
*/
|
|
97
|
+
export declare function exportToCSV(projections: ProjectionEntry[]): string;
|
|
98
|
+
/**
|
|
99
|
+
* Fetch FY25 actuals from fpa_wes_imports on the ReturnPro Supabase instance.
|
|
100
|
+
* Aggregates across all months for a given fiscal year and user,
|
|
101
|
+
* returning one CheckedInUnitsSummary per master program.
|
|
102
|
+
*/
|
|
103
|
+
export declare function fetchWesImports(options?: {
|
|
104
|
+
fiscalYear?: number;
|
|
105
|
+
userId?: string;
|
|
106
|
+
}): Promise<CheckedInUnitsSummary[]>;
|
|
107
|
+
/**
|
|
108
|
+
* Parse a JSON file (array of CheckedInUnitsSummary) as an alternative data source.
|
|
109
|
+
* Accepts raw JSON string (e.g., from stdin or file read).
|
|
110
|
+
*/
|
|
111
|
+
export declare function parseSummaryFromJson(json: string): CheckedInUnitsSummary[];
|
|
112
|
+
/**
|
|
113
|
+
* Format projections as a Bloomberg-dense markdown table.
|
|
114
|
+
*/
|
|
115
|
+
export declare function formatProjectionTable(projections: ProjectionEntry[]): string;
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Budget projection calculator for FY26 planning
|
|
3
|
+
*
|
|
4
|
+
* Ported from wes-dashboard/src/lib/projections/calculator.ts
|
|
5
|
+
* Pure TypeScript — no React, no framework deps.
|
|
6
|
+
*
|
|
7
|
+
* Supports two adjustment types:
|
|
8
|
+
* - Percentage: projected = actual * (1 + rate/100)
|
|
9
|
+
* - Flat: projected = actual + flatAmount
|
|
10
|
+
*
|
|
11
|
+
* Supports both unit AND average retail projections for revenue forecasting.
|
|
12
|
+
*
|
|
13
|
+
* Data sources:
|
|
14
|
+
* - Supabase `fpa_wes_imports` table (ReturnPro instance)
|
|
15
|
+
* - JSON file from stdin or --file flag
|
|
16
|
+
*/
|
|
17
|
+
import { getSupabase } from '../supabase.js';
|
|
18
|
+
// --- Core calculation functions ---
|
|
19
|
+
/**
|
|
20
|
+
* Calculate projected units based on adjustment type and value.
|
|
21
|
+
*/
|
|
22
|
+
export function calculateProjection(input) {
|
|
23
|
+
const { actualUnits, adjustmentType, adjustmentValue } = input;
|
|
24
|
+
if (adjustmentType === 'percentage') {
|
|
25
|
+
return Math.round(actualUnits * (1 + adjustmentValue / 100));
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
return Math.max(0, actualUnits + adjustmentValue);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Calculate projected average retail price.
|
|
33
|
+
*/
|
|
34
|
+
export function calculateAvgRetailProjection(actualAvgRetail, adjustmentType, adjustmentValue) {
|
|
35
|
+
if (actualAvgRetail == null)
|
|
36
|
+
return undefined;
|
|
37
|
+
if (adjustmentType === 'percentage') {
|
|
38
|
+
return actualAvgRetail * (1 + adjustmentValue / 100);
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
return Math.max(0, actualAvgRetail + adjustmentValue);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Convert checked-in units summary to projection entries with default values (0% change).
|
|
46
|
+
*/
|
|
47
|
+
export function initializeProjections(summary) {
|
|
48
|
+
return (summary ?? []).map((item) => {
|
|
49
|
+
const units = typeof item.unitCount === 'number' ? item.unitCount : 0;
|
|
50
|
+
const retail = typeof item.avgRetail === 'number' ? item.avgRetail : undefined;
|
|
51
|
+
return {
|
|
52
|
+
programCode: item.programCode ?? '',
|
|
53
|
+
masterProgram: item.masterProgram ?? '',
|
|
54
|
+
masterProgramId: item.masterProgramId ?? null,
|
|
55
|
+
clientId: item.clientId ?? null,
|
|
56
|
+
clientName: item.clientName ?? 'Unknown',
|
|
57
|
+
actualUnits: units,
|
|
58
|
+
adjustmentType: 'percentage',
|
|
59
|
+
adjustmentValue: 0,
|
|
60
|
+
projectedUnits: units,
|
|
61
|
+
avgRetail: retail,
|
|
62
|
+
avgRetailAdjustmentType: 'percentage',
|
|
63
|
+
avgRetailAdjustmentValue: 0,
|
|
64
|
+
projectedAvgRetail: retail,
|
|
65
|
+
};
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Update a single projection entry's units.
|
|
70
|
+
*/
|
|
71
|
+
export function updateProjection(entry, adjustmentType, adjustmentValue) {
|
|
72
|
+
const projectedUnits = calculateProjection({
|
|
73
|
+
actualUnits: entry.actualUnits,
|
|
74
|
+
adjustmentType,
|
|
75
|
+
adjustmentValue,
|
|
76
|
+
});
|
|
77
|
+
return { ...entry, adjustmentType, adjustmentValue, projectedUnits };
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Update a single projection entry's average retail.
|
|
81
|
+
*/
|
|
82
|
+
export function updateAvgRetailProjection(entry, adjustmentType, adjustmentValue) {
|
|
83
|
+
const projectedAvgRetail = calculateAvgRetailProjection(entry.avgRetail, adjustmentType, adjustmentValue);
|
|
84
|
+
return {
|
|
85
|
+
...entry,
|
|
86
|
+
avgRetailAdjustmentType: adjustmentType,
|
|
87
|
+
avgRetailAdjustmentValue: adjustmentValue,
|
|
88
|
+
projectedAvgRetail,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Apply a uniform unit adjustment to all projections.
|
|
93
|
+
*/
|
|
94
|
+
export function applyUniformAdjustment(projections, adjustmentType, adjustmentValue) {
|
|
95
|
+
return projections.map((entry) => updateProjection(entry, adjustmentType, adjustmentValue));
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Apply a uniform avg retail adjustment to all projections.
|
|
99
|
+
*/
|
|
100
|
+
export function applyUniformAvgRetailAdjustment(projections, adjustmentType, adjustmentValue) {
|
|
101
|
+
return projections.map((entry) => updateAvgRetailProjection(entry, adjustmentType, adjustmentValue));
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Calculate totals for projection summary including revenue.
|
|
105
|
+
*/
|
|
106
|
+
export function calculateTotals(projections) {
|
|
107
|
+
const totalActual = projections.reduce((sum, p) => sum + p.actualUnits, 0);
|
|
108
|
+
const totalProjected = projections.reduce((sum, p) => sum + p.projectedUnits, 0);
|
|
109
|
+
const absoluteChange = totalProjected - totalActual;
|
|
110
|
+
const percentageChange = totalActual > 0
|
|
111
|
+
? ((totalProjected - totalActual) / totalActual) * 100
|
|
112
|
+
: 0;
|
|
113
|
+
const actualRevenue = projections.reduce((sum, p) => {
|
|
114
|
+
if (p.avgRetail != null)
|
|
115
|
+
return sum + p.actualUnits * p.avgRetail;
|
|
116
|
+
return sum;
|
|
117
|
+
}, 0);
|
|
118
|
+
const projectedRevenue = projections.reduce((sum, p) => {
|
|
119
|
+
if (p.projectedAvgRetail != null)
|
|
120
|
+
return sum + p.projectedUnits * p.projectedAvgRetail;
|
|
121
|
+
return sum;
|
|
122
|
+
}, 0);
|
|
123
|
+
const revenueChange = projectedRevenue - actualRevenue;
|
|
124
|
+
const revenuePercentChange = actualRevenue > 0
|
|
125
|
+
? ((projectedRevenue - actualRevenue) / actualRevenue) * 100
|
|
126
|
+
: 0;
|
|
127
|
+
return {
|
|
128
|
+
totalActual,
|
|
129
|
+
totalProjected,
|
|
130
|
+
percentageChange,
|
|
131
|
+
absoluteChange,
|
|
132
|
+
actualRevenue,
|
|
133
|
+
projectedRevenue,
|
|
134
|
+
revenueChange,
|
|
135
|
+
revenuePercentChange,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Group projections by client name.
|
|
140
|
+
*/
|
|
141
|
+
export function groupProjectionsByClient(projections) {
|
|
142
|
+
const groups = new Map();
|
|
143
|
+
for (const p of projections) {
|
|
144
|
+
const list = groups.get(p.clientName) ?? [];
|
|
145
|
+
list.push(p);
|
|
146
|
+
groups.set(p.clientName, list);
|
|
147
|
+
}
|
|
148
|
+
return groups;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Export projections to CSV format with unit + avgRetail + inventory value data.
|
|
152
|
+
*/
|
|
153
|
+
export function exportToCSV(projections) {
|
|
154
|
+
const headers = [
|
|
155
|
+
'Program Code',
|
|
156
|
+
'Master Program',
|
|
157
|
+
'Client',
|
|
158
|
+
'2025 Actual Units',
|
|
159
|
+
'Unit Adj Type',
|
|
160
|
+
'Unit Adj Value',
|
|
161
|
+
'2026 Projected Units',
|
|
162
|
+
'Unit Change',
|
|
163
|
+
'Unit Change %',
|
|
164
|
+
'2025 Avg Retail',
|
|
165
|
+
'Retail Adj Type',
|
|
166
|
+
'Retail Adj Value',
|
|
167
|
+
'2026 Projected Retail',
|
|
168
|
+
'Retail Change',
|
|
169
|
+
'Retail Change %',
|
|
170
|
+
'2025 Inventory Value',
|
|
171
|
+
'2026 Projected Inv. Value',
|
|
172
|
+
'Inv. Value Change',
|
|
173
|
+
'Inv. Value Change %',
|
|
174
|
+
];
|
|
175
|
+
const rows = projections.map((p) => {
|
|
176
|
+
const unitChange = p.projectedUnits - p.actualUnits;
|
|
177
|
+
const unitChangePct = p.actualUnits > 0
|
|
178
|
+
? ((unitChange / p.actualUnits) * 100).toFixed(1)
|
|
179
|
+
: '0.0';
|
|
180
|
+
const retailChange = (p.projectedAvgRetail ?? 0) - (p.avgRetail ?? 0);
|
|
181
|
+
const retailChangePct = p.avgRetail != null && p.avgRetail > 0
|
|
182
|
+
? ((retailChange / p.avgRetail) * 100).toFixed(1)
|
|
183
|
+
: '0.0';
|
|
184
|
+
const actualRev = p.avgRetail != null ? p.actualUnits * p.avgRetail : 0;
|
|
185
|
+
const projRev = p.projectedAvgRetail != null
|
|
186
|
+
? p.projectedUnits * p.projectedAvgRetail
|
|
187
|
+
: 0;
|
|
188
|
+
const revChange = projRev - actualRev;
|
|
189
|
+
const revChangePct = actualRev > 0 ? ((revChange / actualRev) * 100).toFixed(1) : '0.0';
|
|
190
|
+
return [
|
|
191
|
+
csvEscape(p.programCode),
|
|
192
|
+
csvEscape(p.masterProgram),
|
|
193
|
+
csvEscape(p.clientName),
|
|
194
|
+
p.actualUnits,
|
|
195
|
+
p.adjustmentType,
|
|
196
|
+
p.adjustmentType === 'percentage'
|
|
197
|
+
? `${p.adjustmentValue}%`
|
|
198
|
+
: p.adjustmentValue,
|
|
199
|
+
p.projectedUnits,
|
|
200
|
+
unitChange,
|
|
201
|
+
`${unitChangePct}%`,
|
|
202
|
+
p.avgRetail != null ? `$${p.avgRetail.toFixed(2)}` : '',
|
|
203
|
+
p.avgRetailAdjustmentType,
|
|
204
|
+
p.avgRetailAdjustmentType === 'percentage'
|
|
205
|
+
? `${p.avgRetailAdjustmentValue}%`
|
|
206
|
+
: `$${p.avgRetailAdjustmentValue}`,
|
|
207
|
+
p.projectedAvgRetail != null
|
|
208
|
+
? `$${p.projectedAvgRetail.toFixed(2)}`
|
|
209
|
+
: '',
|
|
210
|
+
p.avgRetail != null ? `$${retailChange.toFixed(2)}` : '',
|
|
211
|
+
p.avgRetail != null ? `${retailChangePct}%` : '',
|
|
212
|
+
actualRev > 0 ? `$${actualRev.toFixed(2)}` : '',
|
|
213
|
+
projRev > 0 ? `$${projRev.toFixed(2)}` : '',
|
|
214
|
+
actualRev > 0 ? `$${revChange.toFixed(2)}` : '',
|
|
215
|
+
actualRev > 0 ? `${revChangePct}%` : '',
|
|
216
|
+
].join(',');
|
|
217
|
+
});
|
|
218
|
+
return [headers.join(','), ...rows].join('\n');
|
|
219
|
+
}
|
|
220
|
+
// --- Data fetching ---
|
|
221
|
+
const PAGE_SIZE = 1000;
|
|
222
|
+
/**
|
|
223
|
+
* Fetch FY25 actuals from fpa_wes_imports on the ReturnPro Supabase instance.
|
|
224
|
+
* Aggregates across all months for a given fiscal year and user,
|
|
225
|
+
* returning one CheckedInUnitsSummary per master program.
|
|
226
|
+
*/
|
|
227
|
+
export async function fetchWesImports(options) {
|
|
228
|
+
const sb = getSupabase('returnpro');
|
|
229
|
+
const fy = options?.fiscalYear ?? 2025;
|
|
230
|
+
const summaryMap = new Map();
|
|
231
|
+
let from = 0;
|
|
232
|
+
while (true) {
|
|
233
|
+
let query = sb
|
|
234
|
+
.from('fpa_wes_imports')
|
|
235
|
+
.select(`
|
|
236
|
+
program_code,
|
|
237
|
+
master_program_id,
|
|
238
|
+
actual_units_prior_year,
|
|
239
|
+
projected_units,
|
|
240
|
+
avg_retail_prior_year,
|
|
241
|
+
projected_avg_retail,
|
|
242
|
+
unit_adj_type,
|
|
243
|
+
unit_adj_value,
|
|
244
|
+
retail_adj_type,
|
|
245
|
+
retail_adj_value,
|
|
246
|
+
dim_master_program(master_name, client_id, dim_client(client_name))
|
|
247
|
+
`)
|
|
248
|
+
.eq('fiscal_year', fy)
|
|
249
|
+
.order('master_program_id')
|
|
250
|
+
.range(from, from + PAGE_SIZE - 1);
|
|
251
|
+
if (options?.userId) {
|
|
252
|
+
query = query.eq('user_id', options.userId);
|
|
253
|
+
}
|
|
254
|
+
const { data, error } = await query;
|
|
255
|
+
if (error)
|
|
256
|
+
throw new Error(`Fetch fpa_wes_imports failed: ${error.message}`);
|
|
257
|
+
if (!data || data.length === 0)
|
|
258
|
+
break;
|
|
259
|
+
for (const row of data) {
|
|
260
|
+
const mpId = row.master_program_id;
|
|
261
|
+
const existing = summaryMap.get(mpId);
|
|
262
|
+
const units = row.actual_units_prior_year ?? row.projected_units ?? 0;
|
|
263
|
+
const retail = row.avg_retail_prior_year ?? null;
|
|
264
|
+
if (existing) {
|
|
265
|
+
existing.totalUnits += units;
|
|
266
|
+
if (retail != null) {
|
|
267
|
+
existing.retailSum += retail;
|
|
268
|
+
existing.retailCount += 1;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
else {
|
|
272
|
+
const dim = row.dim_master_program;
|
|
273
|
+
summaryMap.set(mpId, {
|
|
274
|
+
programCode: row.program_code ?? '',
|
|
275
|
+
masterProgram: dim?.master_name ?? '',
|
|
276
|
+
masterProgramId: mpId,
|
|
277
|
+
clientId: dim?.client_id ?? null,
|
|
278
|
+
clientName: dim?.dim_client?.client_name ?? 'Unknown',
|
|
279
|
+
totalUnits: units,
|
|
280
|
+
retailSum: retail ?? 0,
|
|
281
|
+
retailCount: retail != null ? 1 : 0,
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if (data.length < PAGE_SIZE)
|
|
286
|
+
break;
|
|
287
|
+
from += PAGE_SIZE;
|
|
288
|
+
}
|
|
289
|
+
const results = [];
|
|
290
|
+
for (const entry of summaryMap.values()) {
|
|
291
|
+
results.push({
|
|
292
|
+
programCode: entry.programCode,
|
|
293
|
+
masterProgram: entry.masterProgram,
|
|
294
|
+
masterProgramId: entry.masterProgramId,
|
|
295
|
+
clientId: entry.clientId,
|
|
296
|
+
clientName: entry.clientName,
|
|
297
|
+
unitCount: entry.totalUnits,
|
|
298
|
+
countMethod: 'Unit',
|
|
299
|
+
avgRetail: entry.retailCount > 0
|
|
300
|
+
? entry.retailSum / entry.retailCount
|
|
301
|
+
: undefined,
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
results.sort((a, b) => a.clientName.localeCompare(b.clientName) || a.masterProgram.localeCompare(b.masterProgram));
|
|
305
|
+
return results;
|
|
306
|
+
}
|
|
307
|
+
/**
|
|
308
|
+
* Parse a JSON file (array of CheckedInUnitsSummary) as an alternative data source.
|
|
309
|
+
* Accepts raw JSON string (e.g., from stdin or file read).
|
|
310
|
+
*/
|
|
311
|
+
export function parseSummaryFromJson(json) {
|
|
312
|
+
const data = JSON.parse(json);
|
|
313
|
+
if (!Array.isArray(data)) {
|
|
314
|
+
throw new Error('Expected a JSON array of CheckedInUnitsSummary objects');
|
|
315
|
+
}
|
|
316
|
+
return data;
|
|
317
|
+
}
|
|
318
|
+
// --- Formatting helpers ---
|
|
319
|
+
function csvEscape(s) {
|
|
320
|
+
if (s.includes(',') || s.includes('"') || s.includes('\n')) {
|
|
321
|
+
return `"${s.replace(/"/g, '""')}"`;
|
|
322
|
+
}
|
|
323
|
+
return s;
|
|
324
|
+
}
|
|
325
|
+
function fmtCompact(n) {
|
|
326
|
+
const abs = Math.abs(n);
|
|
327
|
+
const sign = n < 0 ? '-' : '';
|
|
328
|
+
if (abs >= 1_000_000)
|
|
329
|
+
return `${sign}$${(abs / 1_000_000).toFixed(1)}M`;
|
|
330
|
+
if (abs >= 1_000)
|
|
331
|
+
return `${sign}$${(abs / 1_000).toFixed(1)}K`;
|
|
332
|
+
return `${sign}$${abs.toFixed(0)}`;
|
|
333
|
+
}
|
|
334
|
+
function fmtUnits(n) {
|
|
335
|
+
if (Math.abs(n) >= 1_000_000)
|
|
336
|
+
return `${(n / 1_000_000).toFixed(2)}M`;
|
|
337
|
+
if (Math.abs(n) >= 1_000)
|
|
338
|
+
return `${(n / 1_000).toFixed(1)}K`;
|
|
339
|
+
return String(n);
|
|
340
|
+
}
|
|
341
|
+
function fmtDelta(pct) {
|
|
342
|
+
const arrow = pct >= 0 ? '\u2191' : '\u2193';
|
|
343
|
+
return `${arrow}${pct >= 0 ? '+' : ''}${pct.toFixed(1)}%`;
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Format projections as a Bloomberg-dense markdown table.
|
|
347
|
+
*/
|
|
348
|
+
export function formatProjectionTable(projections) {
|
|
349
|
+
if (projections.length === 0)
|
|
350
|
+
return 'No projection data.';
|
|
351
|
+
const totals = calculateTotals(projections);
|
|
352
|
+
const lines = [];
|
|
353
|
+
// Summary header
|
|
354
|
+
lines.push(`FY25 Actual: ${fmtUnits(totals.totalActual)} units | FY26 Projected: ${fmtUnits(totals.totalProjected)} units | ${fmtDelta(totals.percentageChange)}`);
|
|
355
|
+
if (totals.actualRevenue > 0) {
|
|
356
|
+
lines.push(`Revenue: ${fmtCompact(totals.actualRevenue)} -> ${fmtCompact(totals.projectedRevenue)} | ${fmtDelta(totals.revenuePercentChange)}`);
|
|
357
|
+
}
|
|
358
|
+
lines.push('');
|
|
359
|
+
// Table
|
|
360
|
+
lines.push('| Client | Program | FY25 Units | FY26 Units | Delta | Avg Retail | Proj Retail | Rev Delta |');
|
|
361
|
+
lines.push('|--------|---------|------------|------------|-------|------------|-------------|-----------|');
|
|
362
|
+
for (const p of projections) {
|
|
363
|
+
const unitDelta = p.projectedUnits - p.actualUnits;
|
|
364
|
+
const unitPct = p.actualUnits > 0
|
|
365
|
+
? ((unitDelta / p.actualUnits) * 100).toFixed(1)
|
|
366
|
+
: '0.0';
|
|
367
|
+
const deltaStr = `${unitDelta >= 0 ? '+' : ''}${fmtUnits(unitDelta)} (${unitPct}%)`;
|
|
368
|
+
const retailStr = p.avgRetail != null ? `$${p.avgRetail.toFixed(2)}` : '-';
|
|
369
|
+
const projRetailStr = p.projectedAvgRetail != null
|
|
370
|
+
? `$${p.projectedAvgRetail.toFixed(2)}`
|
|
371
|
+
: '-';
|
|
372
|
+
const actualRev = p.avgRetail != null ? p.actualUnits * p.avgRetail : 0;
|
|
373
|
+
const projRev = p.projectedAvgRetail != null
|
|
374
|
+
? p.projectedUnits * p.projectedAvgRetail
|
|
375
|
+
: 0;
|
|
376
|
+
const revDelta = projRev - actualRev;
|
|
377
|
+
const revDeltaStr = actualRev > 0
|
|
378
|
+
? `${revDelta >= 0 ? '+' : ''}${fmtCompact(revDelta)}`
|
|
379
|
+
: '-';
|
|
380
|
+
lines.push(`| ${p.clientName} | ${p.programCode} | ${fmtUnits(p.actualUnits)} | ${fmtUnits(p.projectedUnits)} | ${deltaStr} | ${retailStr} | ${projRetailStr} | ${revDeltaStr} |`);
|
|
381
|
+
}
|
|
382
|
+
lines.push(`\n${projections.length} programs`);
|
|
383
|
+
return lines.join('\n');
|
|
384
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Budget scenario manager — save, load, list, compare, and delete named scenarios.
|
|
3
|
+
*
|
|
4
|
+
* Scenarios are stored as JSON files on disk at:
|
|
5
|
+
* /home/optimal/optimal-cli/data/scenarios/{name}.json
|
|
6
|
+
*
|
|
7
|
+
* Each scenario captures a full snapshot of projected units after applying
|
|
8
|
+
* a uniform adjustment to the live fpa_wes_imports data.
|
|
9
|
+
*/
|
|
10
|
+
import 'dotenv/config';
|
|
11
|
+
export interface SaveScenarioOptions {
|
|
12
|
+
name: string;
|
|
13
|
+
adjustmentType: 'percentage' | 'flat';
|
|
14
|
+
adjustmentValue: number;
|
|
15
|
+
fiscalYear?: number;
|
|
16
|
+
userId?: string;
|
|
17
|
+
description?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface ScenarioData {
|
|
20
|
+
name: string;
|
|
21
|
+
createdAt: string;
|
|
22
|
+
adjustmentType: 'percentage' | 'flat';
|
|
23
|
+
adjustmentValue: number;
|
|
24
|
+
description?: string;
|
|
25
|
+
projections: Array<{
|
|
26
|
+
programCode: string;
|
|
27
|
+
masterProgram: string;
|
|
28
|
+
actualUnits: number;
|
|
29
|
+
projectedUnits: number;
|
|
30
|
+
}>;
|
|
31
|
+
totals: {
|
|
32
|
+
totalActual: number;
|
|
33
|
+
totalProjected: number;
|
|
34
|
+
percentageChange: number;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export interface ScenarioSummary {
|
|
38
|
+
name: string;
|
|
39
|
+
createdAt: string;
|
|
40
|
+
adjustmentType: string;
|
|
41
|
+
adjustmentValue: number;
|
|
42
|
+
description?: string;
|
|
43
|
+
totalProjected: number;
|
|
44
|
+
percentageChange: number;
|
|
45
|
+
}
|
|
46
|
+
export interface ComparisonResult {
|
|
47
|
+
scenarioNames: string[];
|
|
48
|
+
programs: Array<{
|
|
49
|
+
programCode: string;
|
|
50
|
+
masterProgram: string;
|
|
51
|
+
actual: number;
|
|
52
|
+
projectedByScenario: Record<string, number>;
|
|
53
|
+
}>;
|
|
54
|
+
totalsByScenario: Record<string, {
|
|
55
|
+
totalProjected: number;
|
|
56
|
+
percentageChange: number;
|
|
57
|
+
}>;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Save current projections as a named scenario to disk.
|
|
61
|
+
*
|
|
62
|
+
* Fetches live data via fetchWesImports, applies the given adjustment,
|
|
63
|
+
* calculates totals, and writes the result as JSON.
|
|
64
|
+
*
|
|
65
|
+
* @returns The absolute path to the saved scenario file.
|
|
66
|
+
*/
|
|
67
|
+
export declare function saveScenario(opts: SaveScenarioOptions): Promise<string>;
|
|
68
|
+
/**
|
|
69
|
+
* Load a saved scenario from disk by name.
|
|
70
|
+
*
|
|
71
|
+
* Accepts the original name (will be sanitized) or the sanitized form.
|
|
72
|
+
*/
|
|
73
|
+
export declare function loadScenario(name: string): Promise<ScenarioData>;
|
|
74
|
+
/**
|
|
75
|
+
* List all saved scenarios, returning lightweight summary objects.
|
|
76
|
+
*
|
|
77
|
+
* Scenarios with unreadable or malformed files are silently skipped.
|
|
78
|
+
*/
|
|
79
|
+
export declare function listScenarios(): Promise<ScenarioSummary[]>;
|
|
80
|
+
/**
|
|
81
|
+
* Compare two or more scenarios side by side.
|
|
82
|
+
*
|
|
83
|
+
* For each program that appears in any of the loaded scenarios, the result
|
|
84
|
+
* includes the actual unit count and the projected units from each scenario.
|
|
85
|
+
* Programs missing from a given scenario will have projectedUnits of 0.
|
|
86
|
+
*/
|
|
87
|
+
export declare function compareScenarios(names: string[]): Promise<ComparisonResult>;
|
|
88
|
+
/**
|
|
89
|
+
* Delete a scenario file from disk.
|
|
90
|
+
*
|
|
91
|
+
* Throws if the scenario does not exist.
|
|
92
|
+
*/
|
|
93
|
+
export declare function deleteScenario(name: string): Promise<void>;
|