@burdenoff/microfe-billing 2026.1028.1 → 2026.1030.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aiSpend.js","names":[],"sources":["../../../../../src/billing/modules/usage/utils/aiSpend.ts"],"sourcesContent":["/**\n * Workspace AI spend in US dollars (BOFF-10273).\n *\n * wspace-prompts-svc keeps an AI ledger row for every platform-key AI call, with\n * its cost in USD micro-dollars. `promptUsageBreakdownV2` sums that ledger for the\n * workspace in the request context, and reports money as a decimal string of\n * micro-dollars because integer money does not drift in a rollup and a total can\n * exceed a GraphQL Int. These helpers keep the value as a BigInt until the last\n * step and then render dollars, so the usage page shows what AI cost the\n * workspace rather than only how many credits it used.\n */\n\nexport type AiSpendWindow = 'month' | '30d' | '7d';\n\nexport const AI_SPEND_WINDOWS: ReadonlyArray<{ value: AiSpendWindow; label: string }> = [\n { value: 'month', label: 'This month' },\n { value: '30d', label: 'Last 30 days' },\n { value: '7d', label: 'Last 7 days' },\n];\n\nconst MICRO_PER_USD = 1_000_000n;\nconst DAY_MS = 86_400_000;\n\n/** Parse a micro-dollar decimal string; anything missing or malformed reads as zero. */\nexport function parseMicroUsd(value: string | null | undefined): bigint {\n if (!value || !/^-?\\d+$/.test(value)) return 0n;\n return BigInt(value);\n}\n\n/**\n * Render micro-dollars as USD. Amounts under one cent keep four decimals so a\n * workspace that spent USD 0.0042 does not read as zero, and anything above\n * zero but under USD 0.0001 reads as \"<$0.0001\".\n */\nexport function formatMicroUsd(value: string | bigint | null | undefined): string {\n const micro = typeof value === 'bigint' ? value : parseMicroUsd(value);\n const negative = micro < 0n;\n const abs = negative ? -micro : micro;\n const sign = negative ? '-' : '';\n if (abs > 0n && abs < 100n) return `${negative ? '>-' : '<'}$0.0001`;\n if (abs > 0n && abs < 10_000n) {\n const whole = abs / MICRO_PER_USD;\n const fraction = ((abs % MICRO_PER_USD) / 100n).toString().padStart(4, '0');\n return `${sign}$${whole.toString()}.${fraction}`;\n }\n const cents = (abs + 5_000n) / 10_000n;\n const dollars = cents / 100n;\n const rest = (cents % 100n).toString().padStart(2, '0');\n return `${sign}$${dollars.toLocaleString('en-US')}.${rest}`;\n}\n\n/**\n * The [from, to) range for a window. `to` is the start of the next UTC minute,\n * so renders inside one minute share an Apollo cache key; \"month\" starts at\n * 00:00 UTC on the first of the current UTC month, matching how the AI credit\n * quota resets.\n */\nexport function aiSpendRange(\n window: AiSpendWindow,\n now: Date = new Date()\n): { from: string; to: string } {\n const end = new Date(now.getTime());\n end.setUTCSeconds(0, 0);\n end.setUTCMinutes(end.getUTCMinutes() + 1);\n let start: Date;\n if (window === 'month') {\n start = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));\n } else {\n const days = window === '7d' ? 7 : 30;\n start = new Date(end.getTime() - days * DAY_MS);\n }\n return { from: start.toISOString(), to: end.toISOString() };\n}\n\n/** The money part of one breakdown row, as the gateway returns it. */\nexport interface AiSpendBreakdownRowInput {\n productKey: string | null;\n attempts: string;\n costMicroUsd: {\n knownSubtotal: string | null;\n knownAttempts: string;\n missingAttempts: string;\n };\n}\n\nexport interface AiSpendProductRow {\n productKey: string;\n attempts: number;\n /** Calls whose ledger row carries no cost (for example bring-your-own-key calls). */\n unpricedAttempts: number;\n costMicroUsd: bigint;\n}\n\nexport interface AiSpendSummary {\n totalMicroUsd: bigint;\n attempts: number;\n unpricedAttempts: number;\n products: AiSpendProductRow[];\n}\n\nfunction toCount(value: string | null | undefined): number {\n if (!value || !/^\\d+$/.test(value)) return 0;\n const parsed = Number(value);\n return Number.isSafeInteger(parsed) ? parsed : Number.MAX_SAFE_INTEGER;\n}\n\n/**\n * Fold a per-product breakdown into the panel's model: the workspace total and\n * one row per product, highest cost first (ties by name so the order is stable).\n */\nexport function summarizeAiSpend(rows: ReadonlyArray<AiSpendBreakdownRowInput>): AiSpendSummary {\n const products: AiSpendProductRow[] = rows.map((row) => ({\n productKey: row.productKey && row.productKey.trim() ? row.productKey : 'unattributed',\n attempts: toCount(row.attempts),\n unpricedAttempts: toCount(row.costMicroUsd.missingAttempts),\n costMicroUsd: parseMicroUsd(row.costMicroUsd.knownSubtotal),\n }));\n products.sort((a, b) => {\n if (a.costMicroUsd !== b.costMicroUsd) return a.costMicroUsd > b.costMicroUsd ? -1 : 1;\n return a.productKey.localeCompare(b.productKey);\n });\n return {\n totalMicroUsd: products.reduce((sum, row) => sum + row.costMicroUsd, 0n),\n attempts: products.reduce((sum, row) => sum + row.attempts, 0),\n unpricedAttempts: products.reduce((sum, row) => sum + row.unpricedAttempts, 0),\n products,\n };\n}\n\n/** A product key as a readable label: \"coolandlovely\" -> \"Coolandlovely\", \"ai_studio\" -> \"Ai Studio\". */\nexport function formatProductKey(productKey: string): string {\n if (productKey === 'unattributed') return 'Unattributed';\n return productKey\n .split(/[-_.]/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(' ');\n}\n\ninterface ErrorWithGraphQLDetails {\n message?: string;\n errors?: ReadonlyArray<{ message?: string; extensions?: Record<string, unknown> }>;\n graphQLErrors?: ReadonlyArray<{ message?: string; extensions?: Record<string, unknown> }>;\n}\n\n/**\n * True when the gateway refused the query because the caller lacks permission\n * to read the workspace's AI ledger. The panel then stays hidden instead of\n * showing an error to members who were never meant to see spend.\n */\nexport function isAiSpendPermissionError(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false;\n const details = error as ErrorWithGraphQLDetails;\n const entries = [...(details.errors ?? []), ...(details.graphQLErrors ?? [])];\n if (\n entries.some((entry) => {\n const code = entry.extensions?.code;\n return code === 'FORBIDDEN' || code === 'UNAUTHENTICATED';\n })\n ) {\n return true;\n }\n const messages = [details.message ?? '', ...entries.map((entry) => entry.message ?? '')]\n .join(' ')\n .toLowerCase();\n return (\n messages.includes('forbidden') ||\n messages.includes('permission denied') ||\n messages.includes('not authorized') ||\n messages.includes('missing permission')\n );\n}\n"],"mappings":";AAc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,MAAM,MAAU;EACtB,IAAM,IAAO,EAAM,YAAY;EAC/B,OAAO,MAAS,eAAe,MAAS;CAC1C,CAAC,GAED,OAAO;CAET,IAAM,IAAW,CAAC,EAAQ,WAAW,IAAI,GAAG,EAAQ,KAAK,MAAU,EAAM,WAAW,EAAE,CAAC,EACpF,KAAK,GAAG,EACR,YAAY;CACf,OACE,EAAS,SAAS,WAAW,KAC7B,EAAS,SAAS,mBAAmB,KACrC,EAAS,SAAS,gBAAgB,KAClC,EAAS,SAAS,oBAAoB;AAE1C"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-billing",
3
- "version": "2026.1028.1",
3
+ "version": "2026.1030.1",
4
4
  "description": "Billing microfrontend for Burdenoff products",
5
5
  "type": "module",
6
6
  "files": [