@streamoid/settings 0.14.0 → 0.15.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/dist/index.js CHANGED
@@ -34,7 +34,9 @@ __export(index_exports, {
34
34
  CreditPoolMemberModal: () => CreditPoolMemberModal,
35
35
  DEFAULT_PERMISSIONS: () => DEFAULT_PERMISSIONS,
36
36
  DEFAULT_USER_LANGUAGE: () => DEFAULT_USER_LANGUAGE,
37
+ EMPTY_USAGE_LOGS_PAGE: () => EMPTY_USAGE_LOGS_PAGE,
37
38
  ExportDateModal: () => ExportDateModal,
39
+ INITIAL_USAGE_LOGS_STATE: () => INITIAL_USAGE_LOGS_STATE,
38
40
  InviteUpdateModal: () => InviteUpdateModal,
39
41
  MemberCreditLimitModal: () => MemberCreditLimitModal,
40
42
  MemberListFrame: () => MemberListFrame,
@@ -67,7 +69,12 @@ __export(index_exports, {
67
69
  TeamsContent: () => TeamsContent,
68
70
  TokensContent: () => TokensContent,
69
71
  URL_TO_TAB: () => URL_TO_TAB,
72
+ USAGE_LOGS_EXPORT_BATCH_SIZE: () => USAGE_LOGS_EXPORT_BATCH_SIZE,
73
+ USAGE_LOGS_EXPORT_EXTRA_REQUESTS: () => USAGE_LOGS_EXPORT_EXTRA_REQUESTS,
74
+ USAGE_LOGS_EXPORT_MAX_ROWS: () => USAGE_LOGS_EXPORT_MAX_ROWS,
75
+ USAGE_LOGS_PAGE_SIZE: () => USAGE_LOGS_PAGE_SIZE,
70
76
  USER_LANGUAGES: () => USER_LANGUAGES,
77
+ UsageLogsPager: () => UsageLogsPager,
71
78
  WORKSPACE_LIST_PAGE_SIZE: () => WORKSPACE_LIST_PAGE_SIZE,
72
79
  WorkspaceGeneralTab: () => WorkspaceGeneralTab,
73
80
  WorkspaceListTab: () => WorkspaceListTab,
@@ -79,6 +86,7 @@ __export(index_exports, {
79
86
  cleanCreditLimitInput: () => cleanCreditLimitInput,
80
87
  cleanPoolValueInput: () => cleanPoolValueInput,
81
88
  countLabel: () => countLabel,
89
+ createUsedByNamesLoader: () => createUsedByNamesLoader,
82
90
  creditCycleUnit: () => creditCycleUnit,
83
91
  creditsMeter: () => creditsMeter,
84
92
  deriveWorkspaceInvitePermission: () => deriveWorkspaceInvitePermission,
@@ -88,6 +96,7 @@ __export(index_exports, {
88
96
  entitlementFromBody: () => entitlementFromBody,
89
97
  entitlementFromFailure: () => entitlementFromFailure,
90
98
  expiryChoiceFor: () => expiryChoiceFor,
99
+ fetchUsageLogsInRange: () => fetchUsageLogsInRange,
91
100
  findBillingError: () => findBillingError,
92
101
  findPoolError: () => findPoolError,
93
102
  formatCreditLimit: () => formatCreditLimit,
@@ -122,8 +131,17 @@ __export(index_exports, {
122
131
  settingsReturnTarget: () => settingsReturnTarget,
123
132
  sharedPoolBannerText: () => sharedPoolBannerText,
124
133
  sharedPoolEndsText: () => sharedPoolEndsText,
134
+ sliceUsageLogsPage: () => sliceUsageLogsPage,
125
135
  sponsoredCreditsText: () => sponsoredCreditsText,
136
+ toCsv: () => toCsv,
126
137
  toLocalDateInput: () => toLocalDateInput,
138
+ usageLogsCsvRows: () => usageLogsCsvRows,
139
+ usageLogsDateRange: () => usageLogsDateRange,
140
+ usageLogsExportFileName: () => usageLogsExportFileName,
141
+ usageLogsPage: () => usageLogsPage,
142
+ usageLogsReducer: () => usageLogsReducer,
143
+ usageLogsReloadPage: () => usageLogsReloadPage,
144
+ usageLogsSpentByOthers: () => usageLogsSpentByOthers,
127
145
  useBillingEntitlement: () => useBillingEntitlement,
128
146
  useSettingsAdapters: () => useSettingsAdapters,
129
147
  useWorkspaceInvitePermission: () => useWorkspaceInvitePermission,
@@ -7897,7 +7915,10 @@ function formatDateRange(date) {
7897
7915
  function ExportDateModal({
7898
7916
  title,
7899
7917
  onClose,
7900
- onExport
7918
+ onExport,
7919
+ busy = false,
7920
+ busyText,
7921
+ notice = null
7901
7922
  }) {
7902
7923
  useOverlayOpen(true, onClose);
7903
7924
  const now = /* @__PURE__ */ new Date();
@@ -7984,6 +8005,7 @@ function ExportDateModal({
7984
8005
  [rangeStart, rangeEnd, isFuture]
7985
8006
  );
7986
8007
  const handleExport = () => {
8008
+ if (busy) return;
7987
8009
  if (rangeStart && rangeEnd) onExport(rangeStart, rangeEnd);
7988
8010
  };
7989
8011
  const getCellVisuals = (cell, idx) => {
@@ -8205,24 +8227,42 @@ function ExportDateModal({
8205
8227
  borderTop: "1px solid var(--alias-border-subtle)"
8206
8228
  },
8207
8229
  children: [
8208
- /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
8209
- "p",
8210
- {
8211
- className: "flex-1 min-w-0 truncate",
8212
- style: {
8213
- fontFamily: "var(--font-family-font-family-body)",
8214
- fontSize: "var(--font-size-font-size-md)",
8215
- fontWeight: 400,
8216
- lineHeight: "var(--line-height-line-height-md)",
8217
- color: "var(--alias-text---icons-primary)"
8218
- },
8219
- children: rangeStart && rangeEnd ? `${formatDateRange(rangeStart)} - ${formatDateRange(rangeEnd)}` : rangeStart ? `${formatDateRange(rangeStart)} - Select end date` : "Select date range"
8220
- }
8221
- ),
8230
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsxs)("div", { className: "flex-1 min-w-0 flex flex-col", children: [
8231
+ /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
8232
+ "p",
8233
+ {
8234
+ className: "min-w-0 truncate",
8235
+ style: {
8236
+ fontFamily: "var(--font-family-font-family-body)",
8237
+ fontSize: "var(--font-size-font-size-md)",
8238
+ fontWeight: 400,
8239
+ lineHeight: "var(--line-height-line-height-md)",
8240
+ color: "var(--alias-text---icons-primary)"
8241
+ },
8242
+ "aria-live": "polite",
8243
+ children: busy && busyText ? busyText : rangeStart && rangeEnd ? `${formatDateRange(rangeStart)} - ${formatDateRange(rangeEnd)}` : rangeStart ? `${formatDateRange(rangeStart)} - Select end date` : "Select date range"
8244
+ }
8245
+ ),
8246
+ notice && !busy && /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
8247
+ "p",
8248
+ {
8249
+ role: "alert",
8250
+ style: {
8251
+ fontFamily: "var(--font-family-font-family-body)",
8252
+ fontSize: "var(--font-size-font-size-sm)",
8253
+ fontWeight: 400,
8254
+ lineHeight: "var(--line-height-line-height-sm)",
8255
+ color: "var(--alias-text---icons-error)"
8256
+ },
8257
+ children: notice
8258
+ }
8259
+ )
8260
+ ] }),
8222
8261
  /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
8223
8262
  "div",
8224
8263
  {
8225
- className: `flex items-center justify-center shrink-0 ${rangeStart && rangeEnd ? "cursor-pointer" : "opacity-50 cursor-not-allowed"}`,
8264
+ className: `flex items-center justify-center shrink-0 ${rangeStart && rangeEnd && !busy ? "cursor-pointer" : "opacity-50 cursor-not-allowed"}`,
8265
+ "aria-disabled": busy || !(rangeStart && rangeEnd),
8226
8266
  style: {
8227
8267
  backgroundColor: "var(--alias-text---icons-primary)",
8228
8268
  borderRadius: "var(--radius-xl)",
@@ -8240,7 +8280,7 @@ function ExportDateModal({
8240
8280
  lineHeight: "var(--line-height-line-height-sm)",
8241
8281
  color: "var(--alias-text---icons-inverse)"
8242
8282
  },
8243
- children: "Export"
8283
+ children: busy ? "Exporting\u2026" : "Export"
8244
8284
  }
8245
8285
  )
8246
8286
  }
@@ -10659,6 +10699,199 @@ async function loadCurrentPlan(fetchCurrentPlan) {
10659
10699
  return { subscription, entitlement, paid: hasPaidFeatures({ entitlement, subscription }) };
10660
10700
  }
10661
10701
 
10702
+ // src/usage-logs.ts
10703
+ var USAGE_LOGS_PAGE_SIZE = 50;
10704
+ var USAGE_LOGS_EXPORT_BATCH_SIZE = 100;
10705
+ var USAGE_LOGS_EXPORT_MAX_ROWS = 2e4;
10706
+ var USAGE_LOGS_EXPORT_EXTRA_REQUESTS = 10;
10707
+ function rowsOf(res) {
10708
+ return Array.isArray(res?.data) ? res.data : [];
10709
+ }
10710
+ function sliceUsageLogsPage(all, page, pageSize = USAGE_LOGS_PAGE_SIZE) {
10711
+ const total = all.length;
10712
+ const totalPages = Math.max(1, Math.ceil(total / pageSize));
10713
+ const safePage = Math.min(Math.max(1, Math.floor(page) || 1), totalPages);
10714
+ return {
10715
+ rows: all.slice((safePage - 1) * pageSize, safePage * pageSize),
10716
+ page: safePage,
10717
+ totalPages,
10718
+ total,
10719
+ unpaged: all
10720
+ };
10721
+ }
10722
+ function usageLogsPage(res, page, pageSize = USAGE_LOGS_PAGE_SIZE) {
10723
+ const data = rowsOf(res);
10724
+ const pagination = res?.pagination;
10725
+ if (!pagination || !Number.isFinite(pagination.total)) {
10726
+ return sliceUsageLogsPage(data, page, pageSize);
10727
+ }
10728
+ const total = Math.max(0, pagination.total);
10729
+ const limit = pagination.limit > 0 ? pagination.limit : pageSize;
10730
+ const totalPages = Math.max(
10731
+ 1,
10732
+ pagination.totalPages > 0 ? pagination.totalPages : Math.ceil(total / limit)
10733
+ );
10734
+ return {
10735
+ rows: data.slice(0, pageSize),
10736
+ page: pagination.page > 0 ? pagination.page : page,
10737
+ totalPages,
10738
+ total,
10739
+ unpaged: null
10740
+ };
10741
+ }
10742
+ var EMPTY_USAGE_LOGS_PAGE = {
10743
+ rows: [],
10744
+ page: 1,
10745
+ totalPages: 1,
10746
+ total: 0,
10747
+ unpaged: null
10748
+ };
10749
+ var INITIAL_USAGE_LOGS_STATE = {
10750
+ logs: EMPTY_USAGE_LOGS_PAGE,
10751
+ requestedPage: 1,
10752
+ loading: false,
10753
+ error: null
10754
+ };
10755
+ function usageLogsReducer(state, action) {
10756
+ switch (action.type) {
10757
+ case "request":
10758
+ return { ...state, requestedPage: action.page, loading: true, error: null };
10759
+ case "loaded":
10760
+ return {
10761
+ logs: action.logs,
10762
+ requestedPage: action.logs.page,
10763
+ loading: false,
10764
+ error: null
10765
+ };
10766
+ case "failed":
10767
+ return { ...state, loading: false, error: action.error };
10768
+ case "turn": {
10769
+ if (!state.logs.unpaged || state.error) return state;
10770
+ const logs = sliceUsageLogsPage(state.logs.unpaged, action.page);
10771
+ return { ...state, logs, requestedPage: logs.page };
10772
+ }
10773
+ case "reset":
10774
+ return INITIAL_USAGE_LOGS_STATE;
10775
+ }
10776
+ }
10777
+ function usageLogsReloadPage(state) {
10778
+ return Math.max(1, Math.floor(state.requestedPage) || 1);
10779
+ }
10780
+ function usageLogsSpentByOthers(logs, workspaceId) {
10781
+ return (logs.unpaged ?? logs.rows).some(
10782
+ (log) => usedByWorkspaceKey(log, workspaceId) !== null
10783
+ );
10784
+ }
10785
+ function createUsedByNamesLoader(save) {
10786
+ let savedFor = null;
10787
+ let inFlight = null;
10788
+ return {
10789
+ async load(workspaceId, fetchCreditPool) {
10790
+ if (savedFor === workspaceId || inFlight?.workspaceId === workspaceId) {
10791
+ return;
10792
+ }
10793
+ const lookup = { workspaceId };
10794
+ inFlight = lookup;
10795
+ try {
10796
+ const pool = await fetchCreditPool();
10797
+ if (inFlight !== lookup) return;
10798
+ if (save(workspaceId, usedByNamesFrom(pool))) savedFor = workspaceId;
10799
+ } catch {
10800
+ } finally {
10801
+ if (inFlight === lookup) inFlight = null;
10802
+ }
10803
+ },
10804
+ reset() {
10805
+ savedFor = null;
10806
+ inFlight = null;
10807
+ }
10808
+ };
10809
+ }
10810
+ function usageLogsExportFileName(start, end) {
10811
+ return `usage_logs_${toLocalDateInput(start)}_${toLocalDateInput(end)}.csv`;
10812
+ }
10813
+ function usageLogsDateRange(start, end) {
10814
+ const from = new Date(start);
10815
+ from.setHours(0, 0, 0, 0);
10816
+ const to = new Date(end);
10817
+ to.setHours(23, 59, 59, 999);
10818
+ return { startDate: from.toISOString(), endDate: to.toISOString() };
10819
+ }
10820
+ async function fetchUsageLogsInRange(fetchUsageLogs, range, {
10821
+ batchSize = USAGE_LOGS_EXPORT_BATCH_SIZE,
10822
+ maxRows = USAGE_LOGS_EXPORT_MAX_ROWS,
10823
+ maxRequests,
10824
+ onProgress,
10825
+ signal
10826
+ } = {}) {
10827
+ const first = await fetchUsageLogs({ ...range, page: 1, limit: batchSize });
10828
+ if (signal?.aborted) return { status: "cancelled" };
10829
+ if (!first?.pagination || !Number.isFinite(first.pagination.total)) {
10830
+ const from = Date.parse(range.startDate);
10831
+ const to = Date.parse(range.endDate);
10832
+ const rows2 = rowsOf(first).filter((row) => {
10833
+ const at = Date.parse(row.createdAt);
10834
+ return at >= from && at <= to;
10835
+ });
10836
+ if (rows2.length > maxRows) return { status: "too-large", total: rows2.length };
10837
+ onProgress?.(rows2.length, rows2.length);
10838
+ return { status: "ok", rows: rows2, total: rows2.length };
10839
+ }
10840
+ let total = Math.max(0, first.pagination.total);
10841
+ if (total > maxRows) return { status: "too-large", total };
10842
+ const limit = first.pagination.limit > 0 ? first.pagination.limit : batchSize;
10843
+ const requestCap = maxRequests ?? Math.ceil(maxRows / limit) + USAGE_LOGS_EXPORT_EXTRA_REQUESTS;
10844
+ const seen = /* @__PURE__ */ new Set();
10845
+ const rows = [];
10846
+ const add = (batch) => {
10847
+ for (const row of batch) {
10848
+ if (rows.length >= maxRows) return;
10849
+ if (seen.has(row._id)) continue;
10850
+ seen.add(row._id);
10851
+ rows.push(row);
10852
+ }
10853
+ };
10854
+ const hasNextAfter = (pagination, page) => typeof pagination?.hasNextPage === "boolean" ? pagination.hasNextPage : page * limit < total;
10855
+ add(rowsOf(first));
10856
+ onProgress?.(rows.length, total);
10857
+ let hasNext = hasNextAfter(first.pagination, 1);
10858
+ let requests = 1;
10859
+ for (let page = 2; hasNext && rows.length < total; page++) {
10860
+ if (requests >= requestCap) {
10861
+ return { status: "incomplete", fetched: rows.length, total };
10862
+ }
10863
+ if (signal?.aborted) return { status: "cancelled" };
10864
+ const res = await fetchUsageLogs({ ...range, page, limit });
10865
+ requests++;
10866
+ if (signal?.aborted) return { status: "cancelled" };
10867
+ if (res?.pagination && Number.isFinite(res.pagination.total)) {
10868
+ total = Math.max(0, res.pagination.total);
10869
+ if (total > maxRows) return { status: "too-large", total };
10870
+ }
10871
+ const batch = rowsOf(res);
10872
+ if (batch.length === 0) break;
10873
+ add(batch);
10874
+ onProgress?.(rows.length, total);
10875
+ hasNext = hasNextAfter(res?.pagination, page);
10876
+ }
10877
+ return { status: "ok", rows, total };
10878
+ }
10879
+ function usageLogsCsvRows(logs, userMap, formatDate5) {
10880
+ return [
10881
+ ["Date", "Type", "Credits", "Service", "User ID"],
10882
+ ...logs.map((log) => [
10883
+ formatDate5(log.createdAt),
10884
+ log.type,
10885
+ log.amount.toLocaleString("en-US"),
10886
+ log.service?.serviceGroupName ?? log.meta?.info ?? "",
10887
+ log.triggeredByUserId != null ? userMap[log.triggeredByUserId] ?? log.triggeredByUserId : ""
10888
+ ])
10889
+ ];
10890
+ }
10891
+ function toCsv(rows) {
10892
+ return rows.map((r) => r.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(",")).join("\n");
10893
+ }
10894
+
10662
10895
  // src/billing-content.tsx
10663
10896
  var import_jsx_runtime29 = require("react/jsx-runtime");
10664
10897
  var DEFAULT_TOPUP_SERVICE = "catalogix";
@@ -11409,6 +11642,7 @@ function BillingTabBar({
11409
11642
  }
11410
11643
  );
11411
11644
  }
11645
+ var BILLING_TABLE_MIN_HEIGHT = 300;
11412
11646
  function InvoiceHistoryTable({
11413
11647
  invoices,
11414
11648
  loading,
@@ -11487,6 +11721,7 @@ function InvoiceHistoryTable({
11487
11721
  {
11488
11722
  className: "flex-1 min-h-0 w-full relative",
11489
11723
  style: {
11724
+ minHeight: BILLING_TABLE_MIN_HEIGHT,
11490
11725
  backgroundColor: "var(--alias-surface-base)",
11491
11726
  borderRadius: "var(--radius-3xl)",
11492
11727
  border: "1px solid var(--alias-border-subtle)",
@@ -11544,6 +11779,8 @@ function UsageLogsTable({
11544
11779
  logs,
11545
11780
  userMap,
11546
11781
  loading,
11782
+ error = null,
11783
+ onRetry,
11547
11784
  currentWorkspaceId = null,
11548
11785
  usedByNames = {}
11549
11786
  }) {
@@ -11574,11 +11811,56 @@ function UsageLogsTable({
11574
11811
  }
11575
11812
  );
11576
11813
  }
11814
+ if (error) {
11815
+ return /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
11816
+ "div",
11817
+ {
11818
+ role: "alert",
11819
+ className: "flex flex-col items-center justify-center w-full",
11820
+ style: {
11821
+ backgroundColor: "var(--alias-surface-base)",
11822
+ borderRadius: "var(--radius-3xl)",
11823
+ border: "1px solid var(--alias-border-subtle)",
11824
+ padding: "var(--spacing-6xl)",
11825
+ gap: "var(--spacing-md)"
11826
+ },
11827
+ children: [
11828
+ /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
11829
+ "span",
11830
+ {
11831
+ style: {
11832
+ fontFamily: "var(--font-family-font-family-body)",
11833
+ fontSize: "var(--font-size-font-size-sm)",
11834
+ fontWeight: 400,
11835
+ lineHeight: "var(--line-height-line-height-sm)",
11836
+ color: "var(--alias-text---icons-muted)",
11837
+ textAlign: "center"
11838
+ },
11839
+ children: [
11840
+ "Couldn't load usage logs. ",
11841
+ error
11842
+ ]
11843
+ }
11844
+ ),
11845
+ onRetry && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
11846
+ import_ui17.ScButton,
11847
+ {
11848
+ text: "Try again",
11849
+ variant: "tertiary",
11850
+ size: "sm",
11851
+ onClick: onRetry
11852
+ }
11853
+ )
11854
+ ]
11855
+ }
11856
+ );
11857
+ }
11577
11858
  return /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
11578
11859
  "div",
11579
11860
  {
11580
11861
  className: "flex-1 min-h-0 w-full relative",
11581
11862
  style: {
11863
+ minHeight: BILLING_TABLE_MIN_HEIGHT,
11582
11864
  backgroundColor: "var(--alias-surface-base)",
11583
11865
  borderRadius: "var(--radius-3xl)",
11584
11866
  border: "1px solid var(--alias-border-subtle)",
@@ -11749,6 +12031,71 @@ function UsageLogsTable({
11749
12031
  }
11750
12032
  );
11751
12033
  }
12034
+ function UsageLogsPager({
12035
+ page,
12036
+ totalPages,
12037
+ total,
12038
+ loading = false,
12039
+ onPageChange
12040
+ }) {
12041
+ if (total <= 0) return null;
12042
+ const canPrevious = !loading && page > 1;
12043
+ const canNext = !loading && page < totalPages;
12044
+ return /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
12045
+ "div",
12046
+ {
12047
+ className: "flex items-center justify-between shrink-0 w-full",
12048
+ style: { gap: "var(--spacing-md)" },
12049
+ children: [
12050
+ /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
12051
+ "span",
12052
+ {
12053
+ style: {
12054
+ color: "var(--alias-text---icons-muted)",
12055
+ fontFamily: "var(--font-family-font-family-body)",
12056
+ fontSize: "var(--font-size-font-size-sm)",
12057
+ lineHeight: "var(--line-height-line-height-sm)"
12058
+ },
12059
+ children: [
12060
+ "Page ",
12061
+ page.toLocaleString("en-US"),
12062
+ " of",
12063
+ " ",
12064
+ totalPages.toLocaleString("en-US"),
12065
+ " \xB7",
12066
+ " ",
12067
+ total.toLocaleString("en-US"),
12068
+ " ",
12069
+ total === 1 ? "log" : "logs"
12070
+ ]
12071
+ }
12072
+ ),
12073
+ totalPages > 1 && /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)("div", { className: "flex items-center", style: { gap: "var(--spacing-md)" }, children: [
12074
+ /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
12075
+ import_ui17.ScButton,
12076
+ {
12077
+ text: "Previous",
12078
+ variant: "tertiary",
12079
+ size: "sm",
12080
+ state: canPrevious ? "default" : "disabled",
12081
+ onClick: canPrevious ? () => onPageChange(page - 1) : void 0
12082
+ }
12083
+ ),
12084
+ /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
12085
+ import_ui17.ScButton,
12086
+ {
12087
+ text: "Next",
12088
+ variant: "tertiary",
12089
+ size: "sm",
12090
+ state: canNext ? "default" : "disabled",
12091
+ onClick: canNext ? () => onPageChange(page + 1) : void 0
12092
+ }
12093
+ )
12094
+ ] })
12095
+ ]
12096
+ }
12097
+ );
12098
+ }
11752
12099
  function BackToBilling({ onClick }) {
11753
12100
  return /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(
11754
12101
  "div",
@@ -11828,6 +12175,9 @@ function BillingContent({
11828
12175
  else setShowSharedCreditsInternal(next);
11829
12176
  };
11830
12177
  const [showExportModal, setShowExportModal] = (0, import_react23.useState)(false);
12178
+ const [exportProgress, setExportProgress] = (0, import_react23.useState)(null);
12179
+ const [exportNotice, setExportNotice] = (0, import_react23.useState)(null);
12180
+ const exportAbortRef = (0, import_react23.useRef)(null);
11831
12181
  const [showBuyCreditsModal, setShowBuyCreditsModal] = (0, import_react23.useState)(false);
11832
12182
  const [subscription, setSubscription] = (0, import_react23.useState)(null);
11833
12183
  const [entitlement, setEntitlement] = (0, import_react23.useState)(
@@ -11839,7 +12189,26 @@ function BillingContent({
11839
12189
  const [products, setProducts] = (0, import_react23.useState)([]);
11840
12190
  const [invoices, setInvoices] = (0, import_react23.useState)([]);
11841
12191
  const [totalCredits, setTotalCredits] = (0, import_react23.useState)(null);
11842
- const [usageLogs, setUsageLogs] = (0, import_react23.useState)([]);
12192
+ const [usageLogsState, dispatchUsageLogs] = (0, import_react23.useReducer)(
12193
+ usageLogsReducer,
12194
+ INITIAL_USAGE_LOGS_STATE
12195
+ );
12196
+ const {
12197
+ logs: usageLogs,
12198
+ loading: loadingUsageLogs,
12199
+ error: usageLogsError
12200
+ } = usageLogsState;
12201
+ const usageLogsRequestRef = (0, import_react23.useRef)(0);
12202
+ const usageLogsStateRef = (0, import_react23.useRef)(usageLogsState);
12203
+ usageLogsStateRef.current = usageLogsState;
12204
+ const workspaceIdRef = (0, import_react23.useRef)(workspaceId);
12205
+ workspaceIdRef.current = workspaceId;
12206
+ const loadUsedByNamesRef = (0, import_react23.useRef)(null);
12207
+ loadUsedByNamesRef.current ??= createUsedByNamesLoader((forWorkspace, names) => {
12208
+ if (forWorkspace !== workspaceIdRef.current) return false;
12209
+ setUsedByNames(names);
12210
+ return true;
12211
+ });
11843
12212
  const [userMap, setUserMap] = (0, import_react23.useState)({});
11844
12213
  const [customPlanCredits, setCustomPlanCredits] = (0, import_react23.useState)(
11845
12214
  null
@@ -11923,8 +12292,68 @@ function BillingContent({
11923
12292
  } catch {
11924
12293
  }
11925
12294
  }, [api]);
12295
+ const ensureUsedByNames = (0, import_react23.useCallback)(
12296
+ (logs) => {
12297
+ const fetchCreditPool = api.fetchCreditPool;
12298
+ if (!fetchCreditPool || !workspaceId || !usageLogsSpentByOthers(logs, workspaceId)) {
12299
+ return;
12300
+ }
12301
+ void loadUsedByNamesRef.current?.load(
12302
+ workspaceId,
12303
+ () => fetchCreditPool.call(api)
12304
+ );
12305
+ },
12306
+ [api, workspaceId]
12307
+ );
12308
+ const loadUsageLogsPage = (0, import_react23.useCallback)(
12309
+ async (page) => {
12310
+ const request = ++usageLogsRequestRef.current;
12311
+ if (!api.fetchUsageLogs) {
12312
+ dispatchUsageLogs({ type: "loaded", logs: EMPTY_USAGE_LOGS_PAGE });
12313
+ return;
12314
+ }
12315
+ dispatchUsageLogs({ type: "request", page });
12316
+ try {
12317
+ const res = await api.fetchUsageLogs({
12318
+ page,
12319
+ limit: USAGE_LOGS_PAGE_SIZE
12320
+ });
12321
+ if (request !== usageLogsRequestRef.current) return;
12322
+ const next = usageLogsPage(res, page);
12323
+ dispatchUsageLogs({ type: "loaded", logs: next });
12324
+ ensureUsedByNames(next);
12325
+ } catch (err) {
12326
+ if (request !== usageLogsRequestRef.current) return;
12327
+ dispatchUsageLogs({
12328
+ type: "failed",
12329
+ error: errorMessage(err, { method: "GET" })
12330
+ });
12331
+ }
12332
+ },
12333
+ [api, ensureUsedByNames]
12334
+ );
12335
+ const goToUsageLogsPage = (0, import_react23.useCallback)(
12336
+ (page) => {
12337
+ if (usageLogs.unpaged && !usageLogsError) {
12338
+ dispatchUsageLogs({ type: "turn", page });
12339
+ ensureUsedByNames(usageLogs);
12340
+ return;
12341
+ }
12342
+ void loadUsageLogsPage(page);
12343
+ },
12344
+ [usageLogs, usageLogsError, loadUsageLogsPage, ensureUsedByNames]
12345
+ );
12346
+ (0, import_react23.useEffect)(() => {
12347
+ if (!loadingUsageLogs && !usageLogsError && usageLogs.unpaged === null && usageLogs.rows.length === 0 && usageLogs.total > 0 && usageLogs.page > usageLogs.totalPages) {
12348
+ void loadUsageLogsPage(usageLogs.totalPages);
12349
+ }
12350
+ }, [usageLogs, loadingUsageLogs, usageLogsError, loadUsageLogsPage]);
11926
12351
  const fetchTableData = (0, import_react23.useCallback)(
11927
12352
  async (tab) => {
12353
+ if (tab === "usage") {
12354
+ await loadUsageLogsPage(usageLogsReloadPage(usageLogsStateRef.current));
12355
+ return;
12356
+ }
11928
12357
  setLoadingTable(true);
11929
12358
  try {
11930
12359
  if (tab === "invoice") {
@@ -11936,25 +12365,14 @@ function BillingContent({
11936
12365
  (item) => item.expiresAt && item.expiresAt.split("T")[0] > today
11937
12366
  ).reduce((total, item) => total + item.amount, 0)
11938
12367
  );
11939
- } else if (api.fetchUsageLogs) {
11940
- const res = await api.fetchUsageLogs();
11941
- const logs = res.data?.length ? res.data : [];
11942
- setUsageLogs(logs);
11943
- if (api.fetchCreditPool && logs.some((log) => usedByWorkspaceKey(log, workspaceId))) {
11944
- const pool = await api.fetchCreditPool().catch(() => null);
11945
- setUsedByNames(usedByNamesFrom(pool));
11946
- }
11947
- } else {
11948
- setUsageLogs([]);
11949
12368
  }
11950
12369
  } catch {
11951
- if (tab === "invoice") setInvoices([]);
11952
- else setUsageLogs([]);
12370
+ setInvoices([]);
11953
12371
  } finally {
11954
12372
  setLoadingTable(false);
11955
12373
  }
11956
12374
  },
11957
- [api, workspaceId]
12375
+ [api, loadUsageLogsPage]
11958
12376
  );
11959
12377
  const handlePlanAction = (0, import_react23.useCallback)(
11960
12378
  async ({ productId, priceId, planName: planName2 }) => {
@@ -12061,6 +12479,11 @@ function BillingContent({
12061
12479
  setProducts([]);
12062
12480
  setTotalCredits(null);
12063
12481
  setCustomPlanCredits(null);
12482
+ usageLogsRequestRef.current++;
12483
+ dispatchUsageLogs({ type: "reset" });
12484
+ usageLogsStateRef.current = INITIAL_USAGE_LOGS_STATE;
12485
+ loadUsedByNamesRef.current?.reset();
12486
+ setUsedByNames({});
12064
12487
  }, [workspaceId]);
12065
12488
  (0, import_react23.useEffect)(() => {
12066
12489
  setInitialFetchTriggered(true);
@@ -12163,35 +12586,74 @@ function BillingContent({
12163
12586
  toast.success(`Opened ${successCount} invoice PDF(s).`);
12164
12587
  }
12165
12588
  } else {
12166
- const filtered = usageLogs.filter((log) => {
12167
- const d = new Date(log.createdAt);
12168
- return d >= startDate && d <= end;
12589
+ await exportUsageLogs(startDate, endDate);
12590
+ }
12591
+ };
12592
+ const closeExportModal = () => {
12593
+ exportAbortRef.current?.abort();
12594
+ exportAbortRef.current = null;
12595
+ setExportProgress(null);
12596
+ setExportNotice(null);
12597
+ setShowExportModal(false);
12598
+ };
12599
+ (0, import_react23.useEffect)(() => () => exportAbortRef.current?.abort(), []);
12600
+ const exportUsageLogs = async (startDate, endDate) => {
12601
+ if (!api.fetchUsageLogs) {
12602
+ toast.info?.("Usage logs are not available in this workspace.");
12603
+ closeExportModal();
12604
+ return;
12605
+ }
12606
+ exportAbortRef.current?.abort();
12607
+ const controller = new AbortController();
12608
+ exportAbortRef.current = controller;
12609
+ setExportNotice(null);
12610
+ setExportProgress({ fetched: 0, total: 0 });
12611
+ const range = usageLogsDateRange(startDate, endDate);
12612
+ try {
12613
+ const result = await fetchUsageLogsInRange(api.fetchUsageLogs, range, {
12614
+ signal: controller.signal,
12615
+ onProgress: (fetched, total) => {
12616
+ if (!controller.signal.aborted) setExportProgress({ fetched, total });
12617
+ }
12169
12618
  });
12170
- if (filtered.length === 0) {
12619
+ if (result.status === "cancelled" || controller.signal.aborted) return;
12620
+ if (result.status === "too-large") {
12621
+ setExportNotice(
12622
+ `${result.total.toLocaleString("en-US")} logs in this range; an export holds up to ${USAGE_LOGS_EXPORT_MAX_ROWS.toLocaleString("en-US")}. Choose a shorter range.`
12623
+ );
12624
+ return;
12625
+ }
12626
+ if (result.status === "incomplete") {
12627
+ setExportNotice(
12628
+ "Usage logs kept changing while exporting, so some were missed. Try again."
12629
+ );
12630
+ return;
12631
+ }
12632
+ if (result.rows.length === 0) {
12171
12633
  toast.info?.("No usage logs found in the selected date range.");
12172
- setShowExportModal(false);
12634
+ closeExportModal();
12173
12635
  return;
12174
12636
  }
12175
- const headers = ["Date", "Type", "Credits", "Service", "User ID"];
12176
- const rows = filtered.map((log) => [
12177
- formatDate3(log.createdAt),
12178
- log.type,
12179
- log.amount.toLocaleString("en-US"),
12180
- log.service?.serviceGroupName ?? log.meta?.info ?? "",
12181
- log.triggeredByUserId != null ? userMap[log.triggeredByUserId] ?? log.triggeredByUserId : ""
12182
- ]);
12183
12637
  downloadCsv(
12184
- [headers, ...rows],
12185
- `usage_logs_${fmtFilename(startDate)}_${fmtFilename(end)}.csv`
12638
+ usageLogsCsvRows(result.rows, userMap, formatDate3),
12639
+ usageLogsExportFileName(startDate, endDate)
12186
12640
  );
12187
- toast.success(`Exported ${filtered.length} log(s).`);
12188
- setShowExportModal(false);
12641
+ toast.success(`Exported ${result.rows.length.toLocaleString("en-US")} log(s).`);
12642
+ closeExportModal();
12643
+ } catch (err) {
12644
+ if (controller.signal.aborted) return;
12645
+ setExportNotice(
12646
+ `Couldn't export usage logs. ${errorMessage(err, { method: "GET" })}`
12647
+ );
12648
+ } finally {
12649
+ if (exportAbortRef.current === controller) {
12650
+ exportAbortRef.current = null;
12651
+ setExportProgress(null);
12652
+ }
12189
12653
  }
12190
12654
  };
12191
12655
  function downloadCsv(rows, filename) {
12192
- const csv = rows.map(
12193
- (r) => r.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(",")
12194
- ).join("\n");
12656
+ const csv = toCsv(rows);
12195
12657
  const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
12196
12658
  const url = URL.createObjectURL(blob);
12197
12659
  const a = document.createElement("a");
@@ -12202,9 +12664,6 @@ function BillingContent({
12202
12664
  document.body.removeChild(a);
12203
12665
  URL.revokeObjectURL(url);
12204
12666
  }
12205
- function fmtFilename(d) {
12206
- return d.toISOString().slice(0, 10);
12207
- }
12208
12667
  async function handleBuyCredits(credits2, price) {
12209
12668
  if (!workspaceId) {
12210
12669
  toast.error("Missing workspace details for credit top-up");
@@ -12657,22 +13116,39 @@ function BillingContent({
12657
13116
  loading: loadingTable,
12658
13117
  workspaceCountry: workspace.current?.country
12659
13118
  }
12660
- ) : /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
12661
- UsageLogsTable,
12662
- {
12663
- logs: usageLogs,
12664
- userMap,
12665
- loading: loadingTable,
12666
- currentWorkspaceId: workspaceId,
12667
- usedByNames
12668
- }
12669
- ),
13119
+ ) : /* @__PURE__ */ (0, import_jsx_runtime29.jsxs)(import_jsx_runtime29.Fragment, { children: [
13120
+ /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
13121
+ UsageLogsTable,
13122
+ {
13123
+ logs: usageLogs.rows,
13124
+ userMap,
13125
+ loading: loadingUsageLogs,
13126
+ error: usageLogsError,
13127
+ onRetry: () => void loadUsageLogsPage(usageLogsState.requestedPage),
13128
+ currentWorkspaceId: workspaceId,
13129
+ usedByNames
13130
+ }
13131
+ ),
13132
+ !usageLogsError && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
13133
+ UsageLogsPager,
13134
+ {
13135
+ page: usageLogs.page,
13136
+ totalPages: usageLogs.totalPages,
13137
+ total: usageLogs.total,
13138
+ loading: loadingUsageLogs,
13139
+ onPageChange: goToUsageLogsPage
13140
+ }
13141
+ )
13142
+ ] }),
12670
13143
  showExportModal && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
12671
13144
  ExportDateModal,
12672
13145
  {
12673
13146
  title: activeTab === "invoice" ? "Export invoices" : "Export log",
12674
- onClose: () => setShowExportModal(false),
12675
- onExport: handleExport
13147
+ onClose: closeExportModal,
13148
+ onExport: handleExport,
13149
+ busy: exportProgress !== null,
13150
+ busyText: exportProgress && exportProgress.total > 0 ? `Fetched ${exportProgress.fetched.toLocaleString("en-US")} of ${exportProgress.total.toLocaleString("en-US")} logs\u2026` : "Fetching logs\u2026",
13151
+ notice: exportNotice
12676
13152
  }
12677
13153
  ),
12678
13154
  showBuyCreditsModal && /* @__PURE__ */ (0, import_jsx_runtime29.jsx)(
@@ -12694,7 +13170,7 @@ function BillingContent({
12694
13170
  "div",
12695
13171
  {
12696
13172
  className: "flex flex-col flex-1 min-w-0 min-h-0 w-full",
12697
- style: { gap: 12 },
13173
+ style: { gap: 12, overflowY: "auto" },
12698
13174
  children: billingInnerContent
12699
13175
  }
12700
13176
  );