@meyicloud/meyi-cost-server 1.5.0 → 1.6.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.
@@ -1,12 +1,9 @@
1
1
  import { nextScheduleRun, reportRange } from "../lib/cost-analysis-schedule.js";
2
- import { createCostAnalysisPdf } from "../services/cost-analysis-pdf.service.js";
3
-
4
2
  export class CostAnalysisReportWorker {
5
- constructor({ repository, analysisService, logger = console, env = process.env, pdfGenerator = createCostAnalysisPdf }) {
3
+ constructor({ repository, analyserService, logger = console, env = process.env }) {
6
4
  this.repository = repository;
7
- this.analysisService = analysisService;
5
+ this.analyserService = analyserService;
8
6
  this.logger = logger;
9
- this.pdfGenerator = pdfGenerator;
10
7
  this.enabled = String(env.COST_AI_ENABLED || "").toLowerCase() === "true";
11
8
  this.pollMs = Math.max(Number(env.COST_AI_REPORT_POLL_INTERVAL_MS || 60_000), 10_000);
12
9
  this.leaseMs = Math.max(Number(env.COST_AI_REPORT_LEASE_MS || 30 * 60_000), 60_000);
@@ -25,10 +22,14 @@ export class CostAnalysisReportWorker {
25
22
  const claimed = await this.repository.markRunning(report.id);
26
23
  if (!claimed) return this.repository.setNextRun(schedule.tenant_id, nextRunAt, false, schedule.next_run_at);
27
24
  try {
28
- const req = { body: { force: true }, headers: {}, user: { tenant_id: schedule.tenant_id, tenantId: schedule.tenant_id } };
29
- const analysis = await this.analysisService.analyze(req, range);
30
- const pdf = await this.pdfGenerator(analysis);
31
- await this.repository.complete(report.id, analysis, pdf);
25
+ const result = await this.analyserService.execute({
26
+ tenantId: schedule.tenant_id,
27
+ reportId: report.id,
28
+ range,
29
+ frequency: schedule.frequency,
30
+ onStarted: (taskArn) => this.repository.setTaskArn(report.id, taskArn),
31
+ });
32
+ await this.repository.completeExternal(report.id, result);
32
33
  await this.repository.setNextRun(schedule.tenant_id, nextRunAt, true, schedule.next_run_at);
33
34
  } catch (error) {
34
35
  await this.repository.fail(report.id, error);
@@ -1,116 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import { round } from "./cost-utils.js";
3
-
4
- const text = (value, max = 1200) => String(value || "").trim().slice(0, max);
5
- const severity = (value) => ["low", "medium", "high"].includes(value) ? value : "medium";
6
-
7
- function median(values) {
8
- const sorted = values.filter(Number.isFinite).sort((a, b) => a - b);
9
- if (!sorted.length) return null;
10
- const middle = Math.floor(sorted.length / 2);
11
- return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
12
- }
13
-
14
- function deltaRows(current = [], previous = [], limit = 8) {
15
- const before = new Map(previous.map((item) => [item.label, Number(item.amount || 0)]));
16
- return current.slice(0, limit).map((item) => {
17
- const currentAmount = Number(item.amount || 0);
18
- const previousAmount = before.get(item.label) || 0;
19
- return {
20
- label: text(item.label, 160),
21
- current: round(currentAmount),
22
- previous: round(previousAmount),
23
- change: round(currentAmount - previousAmount),
24
- changePercentage: previousAmount > 0 ? round((currentAmount - previousAmount) / previousAmount * 100) : null,
25
- sharePercentage: Number.isFinite(Number(item.percentage)) ? round(Number(item.percentage)) : null,
26
- };
27
- }).sort((a, b) => Math.abs(b.change) - Math.abs(a.change));
28
- }
29
-
30
- export function buildCostFacts({ current, previous }) {
31
- const currentTotal = round(current.totalCost || 0);
32
- const previousTotal = round(previous.totalCost || 0);
33
- const change = round(currentTotal - previousTotal);
34
- const changePercentage = previousTotal > 0 ? round(change / previousTotal * 100) : null;
35
- const historicalTotals = (current.trends || [])
36
- .filter((item) => String(item.month || "") < String(current.period?.Start || ""))
37
- .map((item) => Number(item.amount || 0))
38
- .filter((value) => value > 0);
39
- const baseline = median(historicalTotals);
40
- const currentVsBaseline = baseline && baseline > 0 ? round((currentTotal - baseline) / baseline * 100) : null;
41
- const serviceChanges = deltaRows(current.topServices, previous.topServices);
42
- const accountChanges = deltaRows(current.topAccounts, previous.topAccounts, 6);
43
- const topServiceShare = Number(current.topServices?.[0]?.percentage || 0);
44
- const calculatedSignals = [];
45
-
46
- if (changePercentage != null && Math.abs(changePercentage) >= 10) {
47
- calculatedSignals.push({
48
- severity: Math.abs(changePercentage) >= 25 ? "high" : "medium",
49
- kind: "period_change",
50
- message: `Spend ${changePercentage > 0 ? "increased" : "decreased"} ${Math.abs(changePercentage)}% compared with the preceding period.`,
51
- });
52
- }
53
- if (currentVsBaseline != null && currentVsBaseline >= 25 && historicalTotals.length >= 3) {
54
- calculatedSignals.push({ severity: "high", kind: "baseline_anomaly", message: `Spend is ${currentVsBaseline}% above the historical monthly median.` });
55
- }
56
- if (topServiceShare >= 50) {
57
- calculatedSignals.push({ severity: "medium", kind: "service_concentration", message: `${text(current.topServices[0]?.label, 160)} represents ${round(topServiceShare)}% of spend.` });
58
- }
59
-
60
- return {
61
- period: current.period,
62
- comparisonPeriod: previous.period,
63
- currency: current.currency || "USD",
64
- dataSource: current.dataSource,
65
- currentTotal,
66
- previousTotal,
67
- change,
68
- changePercentage,
69
- activeAccounts: Number(current.activeAccounts || 0),
70
- activeResources: current.activeResources == null ? null : Number(current.activeResources),
71
- historyMonths: historicalTotals.length,
72
- historicalMonthlyMedian: baseline == null ? null : round(baseline),
73
- currentVsBaselinePercentage: currentVsBaseline,
74
- serviceChanges,
75
- accountChanges,
76
- topRegions: (current.topRegions || []).slice(0, 6).map((item) => ({ label: text(item.label, 160), amount: round(item.amount || 0), sharePercentage: round(item.percentage || 0) })),
77
- calculatedSignals,
78
- limitations: historicalTotals.length < 3 ? ["Fewer than three non-zero monthly data points are available, so anomaly confidence is limited."] : [],
79
- };
80
- }
81
-
82
- export function redactFactsForModel(facts) {
83
- return {
84
- ...facts,
85
- accountChanges: facts.accountChanges.map((item, index) => ({ ...item, label: `Account ${index + 1}` })),
86
- };
87
- }
88
-
89
- export function analysisFingerprint(facts, modelId) {
90
- return createHash("sha256").update(JSON.stringify({ facts, modelId })).digest("hex");
91
- }
92
-
93
- export function parseAnalysisResponse(value) {
94
- const raw = String(value || "").trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
95
- const start = raw.indexOf("{");
96
- const end = raw.lastIndexOf("}");
97
- if (start < 0 || end <= start) throw new Error("The AI response did not contain a JSON object");
98
- const parsed = JSON.parse(raw.slice(start, end + 1));
99
- const summary = text(parsed.summary, 3000);
100
- const findings = Array.isArray(parsed.findings) ? parsed.findings.slice(0, 6).map((item) => ({
101
- severity: severity(item?.severity),
102
- title: text(item?.title, 160),
103
- explanation: text(item?.explanation, 1000),
104
- evidence: text(item?.evidence, 500),
105
- estimatedImpact: Number.isFinite(Number(item?.estimatedImpact)) ? round(Number(item.estimatedImpact)) : null,
106
- })).filter((item) => item.title && item.explanation) : [];
107
- const recommendations = Array.isArray(parsed.recommendations) ? parsed.recommendations.slice(0, 6).map((item) => ({
108
- priority: Math.min(Math.max(Number(item?.priority) || 2, 1), 3),
109
- title: text(item?.title, 160),
110
- action: text(item?.action, 800),
111
- rationale: text(item?.rationale, 600),
112
- })).filter((item) => item.title && item.action) : [];
113
- const limitations = Array.isArray(parsed.limitations) ? parsed.limitations.slice(0, 5).map((item) => text(item, 400)).filter(Boolean) : [];
114
- if (!summary || !findings.length || !recommendations.length) throw new Error("The AI response was missing required analysis fields");
115
- return { summary, findings, recommendations, limitations };
116
- }
@@ -1,239 +0,0 @@
1
- import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
2
-
3
- /**
4
- * One calling convention over the LLM providers the Cost plugin supports.
5
- *
6
- * Bedrock authenticates with SigV4 and is subject to account-level model
7
- * access; the direct Anthropic and OpenAI providers authenticate with an API
8
- * key and are not. That difference is the whole reason this abstraction exists
9
- * - a deployment blocked on Bedrock model access can still run analysis
10
- * against a key.
11
- *
12
- * Every provider takes the same call shape and returns { text }. Nothing above
13
- * this file knows which one answered.
14
- */
15
-
16
- export const PROVIDER_BEDROCK = "bedrock";
17
- export const PROVIDER_ANTHROPIC = "anthropic";
18
- export const PROVIDER_OPENAI = "openai";
19
-
20
- const ANTHROPIC_VERSION = "2023-06-01";
21
- const DEFAULT_TIMEOUT_MS = 120_000;
22
-
23
- /**
24
- * Provider names arrive from a database row that a human filled in through a
25
- * dropdown ("AWS Bedrock", "Anthropic", "OpenAI"), so normalise loosely rather
26
- * than demanding an exact token.
27
- */
28
- export function normalizeProviderName(value) {
29
- const name = String(value || "").trim().toLowerCase();
30
- if (!name) return PROVIDER_BEDROCK;
31
- if (name.includes("bedrock")) return PROVIDER_BEDROCK;
32
- if (name.includes("anthropic") || name.includes("claude")) return PROVIDER_ANTHROPIC;
33
- if (name.includes("openai") || name.includes("gpt")) return PROVIDER_OPENAI;
34
- return name;
35
- }
36
-
37
- function providerError(message, { name = "CostAiProviderError", statusCode = 502, cause } = {}) {
38
- const error = new Error(message);
39
- error.name = name;
40
- error.statusCode = statusCode;
41
- if (cause) error.cause = cause;
42
- return error;
43
- }
44
-
45
- /**
46
- * Read an HTTP error body without letting a provider's error text leak a key
47
- * back to the caller. Bodies are truncated: some providers echo request context.
48
- */
49
- async function readErrorBody(response) {
50
- try {
51
- const text = await response.text();
52
- return String(text || "").slice(0, 500);
53
- } catch {
54
- return "";
55
- }
56
- }
57
-
58
- async function postJson(url, { headers, body, timeoutMs }) {
59
- const controller = new AbortController();
60
- const timer = setTimeout(() => controller.abort(), timeoutMs);
61
- try {
62
- return await fetch(url, {
63
- method: "POST",
64
- headers: { "content-type": "application/json", ...headers },
65
- body: JSON.stringify(body),
66
- signal: controller.signal,
67
- });
68
- } catch (error) {
69
- if (error.name === "AbortError") {
70
- throw providerError(`The model did not respond within ${Math.round(timeoutMs / 1000)}s`, { name: "CostAiTimeoutError", statusCode: 504 });
71
- }
72
- throw providerError(`Could not reach the model endpoint: ${error.message}`, { cause: error });
73
- } finally {
74
- clearTimeout(timer);
75
- }
76
- }
77
-
78
- /**
79
- * Shared by both Bedrock auth modes: Converse wire shape in, plain text out.
80
- *
81
- * Undefined sampling parameters are omitted rather than sent as null. Claude
82
- * Haiku 4.5 and Sonnet 4.5 reject a request that carries both temperature and
83
- * topP - "cannot both be specified for this model" - so the caller sends one.
84
- */
85
- function converseRequestBody({ system, messages, maxTokens, temperature, topP }) {
86
- const inferenceConfig = { maxTokens };
87
- if (temperature !== undefined && temperature !== null) inferenceConfig.temperature = temperature;
88
- if (topP !== undefined && topP !== null) inferenceConfig.topP = topP;
89
- return {
90
- system: [{ text: system }],
91
- messages: messages.map((message) => ({ role: message.role, content: [{ text: message.text }] })),
92
- inferenceConfig,
93
- };
94
- }
95
-
96
- function converseResponseText(payload) {
97
- return (payload?.output?.message?.content || []).map((item) => item.text || "").join("\n");
98
- }
99
-
100
- /**
101
- * Bedrock with an API key (the ABSK... long-term or short-term keys issued in
102
- * the Bedrock console). These are bearer tokens, not SigV4 credentials, so the
103
- * AWS SDK cannot use them without the process-wide AWS_BEARER_TOKEN_BEDROCK
104
- * variable - unusable here, because the token is per tenant and this process
105
- * serves many. Calling the Converse REST endpoint directly keeps it per request.
106
- *
107
- * Authentication only. Model entitlement is still granted per AWS account, so a
108
- * key cannot reach a model the account has not been approved for.
109
- */
110
- function createBedrockBearerProvider({ modelId, region, apiKey, timeoutMs }) {
111
- if (!region) throw providerError("Bedrock with an API key requires a region", { name: "CostAiConfigError", statusCode: 400 });
112
- const endpoint = `https://bedrock-runtime.${region}.amazonaws.com/model/${encodeURIComponent(modelId)}/converse`;
113
- return {
114
- provider: PROVIDER_BEDROCK,
115
- modelId,
116
- region,
117
- authMode: "api-key",
118
- async converse(request) {
119
- const response = await postJson(endpoint, {
120
- headers: { authorization: `Bearer ${apiKey}` },
121
- timeoutMs,
122
- body: converseRequestBody(request),
123
- });
124
- if (!response.ok) {
125
- // 404 here is Bedrock's shape for "account not entitled to this model",
126
- // not a missing endpoint. Pass the message through so the UI can show it.
127
- throw providerError(`Bedrock returned ${response.status}: ${await readErrorBody(response)}`, {
128
- statusCode: response.status === 429 ? 429 : 502,
129
- });
130
- }
131
- return { text: converseResponseText(await response.json()) };
132
- },
133
- };
134
- }
135
-
136
- /**
137
- * Bedrock with SigV4. The original behaviour: the ambient credential chain (the
138
- * ECS task role) unless explicit access keys are supplied, which is how a
139
- * customer points the plugin at their own account.
140
- */
141
- function createBedrockProvider({ modelId, region, apiKey, accessKeyId, secretAccessKey, sessionToken, client, timeoutMs }) {
142
- // An injected client is a test seam and must win, so check it before the key.
143
- if (!client && apiKey) return createBedrockBearerProvider({ modelId, region, apiKey, timeoutMs });
144
- const credentials = accessKeyId && secretAccessKey
145
- ? { accessKeyId, secretAccessKey, ...(sessionToken ? { sessionToken } : {}) }
146
- : undefined;
147
- const runtime = client || new BedrockRuntimeClient({ region, ...(credentials ? { credentials } : {}) });
148
- return {
149
- provider: PROVIDER_BEDROCK,
150
- modelId,
151
- region,
152
- authMode: credentials ? "access-keys" : "ambient",
153
- async converse(request) {
154
- const response = await runtime.send(new ConverseCommand({ modelId, ...converseRequestBody(request) }));
155
- return { text: converseResponseText(response) };
156
- },
157
- };
158
- }
159
-
160
- function createAnthropicProvider({ modelId, apiKey, baseUrl, timeoutMs }) {
161
- if (!apiKey) throw providerError("The Anthropic provider requires an API key", { name: "CostAiConfigError", statusCode: 400 });
162
- const endpoint = `${String(baseUrl || "https://api.anthropic.com").replace(/\/+$/, "")}/v1/messages`;
163
- return {
164
- provider: PROVIDER_ANTHROPIC,
165
- modelId,
166
- region: null,
167
- async converse({ system, messages, maxTokens, temperature, topP }) {
168
- const response = await postJson(endpoint, {
169
- headers: { "x-api-key": apiKey, "anthropic-version": ANTHROPIC_VERSION },
170
- timeoutMs,
171
- body: {
172
- model: modelId,
173
- max_tokens: maxTokens,
174
- ...(temperature === undefined || temperature === null ? {} : { temperature }),
175
- ...(topP === undefined || topP === null ? {} : { top_p: topP }),
176
- system,
177
- messages: messages.map((message) => ({ role: message.role, content: message.text })),
178
- },
179
- });
180
- if (!response.ok) {
181
- throw providerError(`Anthropic API returned ${response.status}: ${await readErrorBody(response)}`, { statusCode: response.status === 429 ? 429 : 502 });
182
- }
183
- const payload = await response.json();
184
- return { text: (payload.content || []).map((item) => item.text || "").join("\n") };
185
- },
186
- };
187
- }
188
-
189
- function createOpenAiProvider({ modelId, apiKey, baseUrl, timeoutMs }) {
190
- if (!apiKey) throw providerError("The OpenAI provider requires an API key", { name: "CostAiConfigError", statusCode: 400 });
191
- const endpoint = `${String(baseUrl || "https://api.openai.com").replace(/\/+$/, "")}/v1/chat/completions`;
192
- return {
193
- provider: PROVIDER_OPENAI,
194
- modelId,
195
- region: null,
196
- async converse({ system, messages, maxTokens, temperature, topP }) {
197
- const response = await postJson(endpoint, {
198
- headers: { authorization: `Bearer ${apiKey}` },
199
- timeoutMs,
200
- body: {
201
- model: modelId,
202
- max_completion_tokens: maxTokens,
203
- ...(temperature === undefined || temperature === null ? {} : { temperature }),
204
- ...(topP === undefined || topP === null ? {} : { top_p: topP }),
205
- messages: [
206
- { role: "system", content: system },
207
- ...messages.map((message) => ({ role: message.role, content: message.text })),
208
- ],
209
- },
210
- });
211
- if (!response.ok) {
212
- throw providerError(`OpenAI API returned ${response.status}: ${await readErrorBody(response)}`, { statusCode: response.status === 429 ? 429 : 502 });
213
- }
214
- const payload = await response.json();
215
- return { text: (payload.choices || []).map((choice) => choice.message?.content || "").join("\n") };
216
- },
217
- };
218
- }
219
-
220
- /**
221
- * @param {object} config
222
- * @param {string} config.provider bedrock | anthropic | openai (loose match)
223
- * @param {string} config.modelId
224
- * @param {string} [config.apiKey] required for anthropic and openai
225
- * @param {string} [config.region] bedrock only
226
- * @param {string} [config.accessKeyId] bedrock only; omit for ambient creds
227
- * @param {string} [config.secretAccessKey] bedrock only
228
- * @param {string} [config.baseUrl] overrides the provider endpoint
229
- * @param {object} [config.client] inject a Bedrock client, for tests
230
- */
231
- export function createLlmProvider(config = {}) {
232
- const provider = normalizeProviderName(config.provider);
233
- const timeoutMs = Math.max(Number(config.timeoutMs || DEFAULT_TIMEOUT_MS), 1_000);
234
- if (!config.modelId) throw providerError("A model id is required", { name: "CostAiConfigError", statusCode: 400 });
235
- if (provider === PROVIDER_BEDROCK) return createBedrockProvider({ ...config, timeoutMs });
236
- if (provider === PROVIDER_ANTHROPIC) return createAnthropicProvider({ ...config, timeoutMs });
237
- if (provider === PROVIDER_OPENAI) return createOpenAiProvider({ ...config, timeoutMs });
238
- throw providerError(`Unsupported AI provider "${config.provider}"`, { name: "CostAiConfigError", statusCode: 400 });
239
- }
@@ -1,50 +0,0 @@
1
- import { sql } from "drizzle-orm";
2
- import { rows } from "../lib/cost-utils.js";
3
-
4
- export class CostAnalysisRepository {
5
- constructor({ db, qSchema }) {
6
- this.db = db;
7
- this.table = `${qSchema}.cost_ai_analyses`;
8
- }
9
-
10
- async findCached(tenantId, fingerprint, maxAgeMs) {
11
- const result = rows(await this.db.execute(sql`
12
- SELECT * FROM ${sql.raw(this.table)}
13
- WHERE tenant_id = ${tenantId} AND input_fingerprint = ${fingerprint}
14
- AND created_at >= now() - (${Math.max(maxAgeMs, 0)} * interval '1 millisecond')
15
- ORDER BY created_at DESC LIMIT 1
16
- `));
17
- return result[0] || null;
18
- }
19
-
20
- async latest(tenantId) {
21
- const result = rows(await this.db.execute(sql`
22
- SELECT * FROM ${sql.raw(this.table)}
23
- WHERE tenant_id = ${tenantId}
24
- ORDER BY created_at DESC LIMIT 1
25
- `));
26
- return result[0] || null;
27
- }
28
-
29
- async countRecent(tenantId, windowMs) {
30
- const result = rows(await this.db.execute(sql`
31
- SELECT COUNT(*)::integer AS count FROM ${sql.raw(this.table)}
32
- WHERE tenant_id = ${tenantId}
33
- AND created_at >= now() - (${Math.max(windowMs, 0)} * interval '1 millisecond')
34
- `));
35
- return Number(result[0]?.count || 0);
36
- }
37
-
38
- async save({ id, tenantId, requestedBy, fingerprint, modelId, source, period, facts, result }) {
39
- const inserted = rows(await this.db.execute(sql`
40
- INSERT INTO ${sql.raw(this.table)}
41
- (id, tenant_id, requested_by, input_fingerprint, model_id, data_source,
42
- period_start, period_end, facts, result)
43
- VALUES
44
- (${id}, ${tenantId}, ${requestedBy}, ${fingerprint}, ${modelId}, ${source},
45
- ${period.Start}, ${period.End}, ${JSON.stringify(facts)}::jsonb, ${JSON.stringify(result)}::jsonb)
46
- RETURNING *
47
- `));
48
- return inserted[0];
49
- }
50
- }
@@ -1,7 +0,0 @@
1
- import { sql } from "drizzle-orm";
2
-
3
- export async function installCostAnalysisSchema(db, qSchema) {
4
- await db.execute(sql.raw(`CREATE TABLE IF NOT EXISTS ${qSchema}.cost_ai_analyses (id text PRIMARY KEY, tenant_id text NOT NULL, requested_by text, input_fingerprint text NOT NULL, model_id text NOT NULL, data_source text, period_start date NOT NULL, period_end date NOT NULL, facts jsonb NOT NULL, result jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now())`));
5
- await db.execute(sql.raw(`CREATE INDEX IF NOT EXISTS cost_ai_analyses_tenant_created_idx ON ${qSchema}.cost_ai_analyses (tenant_id, created_at DESC)`));
6
- await db.execute(sql.raw(`CREATE INDEX IF NOT EXISTS cost_ai_analyses_cache_idx ON ${qSchema}.cost_ai_analyses (tenant_id, input_fingerprint, created_at DESC)`));
7
- }
@@ -1,39 +0,0 @@
1
- import { getCurOverview } from "./cur.service.js";
2
- import { iso } from "../lib/cost-utils.js";
3
-
4
- function previousRange(range) {
5
- const start = new Date(`${range.Start}T00:00:00Z`);
6
- const end = new Date(`${range.End}T00:00:00Z`);
7
- const duration = end.getTime() - start.getTime();
8
- return { Start: iso(new Date(start.getTime() - duration)), End: range.Start };
9
- }
10
-
11
- function trendRange(range) {
12
- const start = new Date(`${range.Start}T00:00:00Z`);
13
- start.setUTCMonth(start.getUTCMonth() - 11, 1);
14
- return { Start: iso(start), End: range.End };
15
- }
16
-
17
- export class CostAnalysisDataService {
18
- constructor({ curProvider }) {
19
- this.curProvider = curProvider;
20
- }
21
-
22
- async load(context, range) {
23
- const prior = previousRange(range);
24
- const history = trendRange(range);
25
- const [current, previous] = await Promise.all([
26
- this.loadPeriod(context, range, history),
27
- this.loadPeriod(context, prior, prior),
28
- ]);
29
- return { current, previous };
30
- }
31
-
32
- async loadPeriod(context, range, historyRange) {
33
- const { tenant, accounts } = context;
34
- const names = new Map(accounts.map((item) => [item.id, item.name]));
35
- return this.curProvider.run(context, (client, config) => getCurOverview({
36
- client, config, tenant, range, trendRange: historyRange, accountNames: names,
37
- }));
38
- }
39
- }
@@ -1,42 +0,0 @@
1
- import PDFDocument from "pdfkit";
2
-
3
- const money = (value, currency = "USD") => new Intl.NumberFormat("en-US", { style: "currency", currency }).format(Number(value || 0));
4
-
5
- export function createCostAnalysisPdf(analysis) {
6
- return new Promise((resolve, reject) => {
7
- const doc = new PDFDocument({ size: "A4", margin: 48, info: { Title: "Meyi Connect AI Cost Analysis", Author: "Meyi Connect" } });
8
- const chunks = [];
9
- doc.on("data", (chunk) => chunks.push(chunk));
10
- doc.on("end", () => resolve(Buffer.concat(chunks)));
11
- doc.on("error", reject);
12
- const ensure = (height = 80) => { if (doc.y + height > doc.page.height - 48) doc.addPage(); };
13
- const inclusiveEnd = new Date(`${analysis.period.End}T00:00:00Z`);
14
- inclusiveEnd.setUTCDate(inclusiveEnd.getUTCDate() - 1);
15
- doc.font("Helvetica-Bold").fontSize(20).fillColor("#122235").text("AI Cost Analysis");
16
- doc.moveDown(0.35).font("Helvetica").fontSize(9).fillColor("#53657a").text(`Generated ${new Date(analysis.generatedAt).toUTCString()} | AWS CUR | ${analysis.period.Start} to ${inclusiveEnd.toISOString().slice(0, 10)}`);
17
- doc.moveDown(1).font("Helvetica-Bold").fontSize(12).fillColor("#122235").text("Executive summary");
18
- doc.moveDown(0.35).font("Helvetica").fontSize(10).fillColor("#27384a").text(analysis.summary, { lineGap: 3 });
19
- doc.moveDown(1).font("Helvetica-Bold").fontSize(12).fillColor("#122235").text("Cost facts");
20
- doc.moveDown(0.35).font("Helvetica").fontSize(10).fillColor("#27384a");
21
- doc.text(`Period spend: ${money(analysis.facts.currentTotal, analysis.facts.currency)}`);
22
- doc.text(`Previous period: ${money(analysis.facts.previousTotal, analysis.facts.currency)}`);
23
- doc.text(`Change: ${money(analysis.facts.change, analysis.facts.currency)} (${analysis.facts.changePercentage == null ? "no baseline" : `${analysis.facts.changePercentage}%`})`);
24
- doc.moveDown(1).font("Helvetica-Bold").fontSize(12).fillColor("#122235").text("Key findings");
25
- for (const finding of analysis.findings || []) {
26
- ensure();
27
- doc.moveDown(0.5).font("Helvetica-Bold").fontSize(10).fillColor("#122235").text(`${String(finding.severity).toUpperCase()}: ${finding.title}`);
28
- doc.font("Helvetica").fillColor("#27384a").text(finding.explanation, { lineGap: 2 });
29
- doc.fontSize(9).fillColor("#53657a").text(`Evidence: ${finding.evidence}`);
30
- }
31
- ensure();
32
- doc.moveDown(1).font("Helvetica-Bold").fontSize(12).fillColor("#122235").text("Recommended actions");
33
- for (const item of [...(analysis.recommendations || [])].sort((a, b) => a.priority - b.priority)) {
34
- ensure();
35
- doc.moveDown(0.5).font("Helvetica-Bold").fontSize(10).fillColor("#122235").text(`${item.priority}. ${item.title}`);
36
- doc.font("Helvetica").fillColor("#27384a").text(item.action, { lineGap: 2 });
37
- doc.fontSize(9).fillColor("#53657a").text(item.rationale);
38
- }
39
- doc.moveDown(1).font("Helvetica-Oblique").fontSize(8).fillColor("#6b7785").text("AI recommendations are advisory. Review them before changing AWS resources.");
40
- doc.end();
41
- });
42
- }