@gloom-sh/terminal 0.20.14 → 0.20.16

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.
Files changed (144) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/index.ts +54 -0
  3. package/src/api-client/install-experiments.ts +8 -7
  4. package/src/api-client/paths.ts +2 -1
  5. package/src/api-client/product-waitlist.ts +63 -0
  6. package/src/api-client/request.ts +4 -2
  7. package/src/api-client/types/billing.ts +45 -0
  8. package/src/api-client/yearly-plan.ts +132 -0
  9. package/src/app/global-shortcuts.ts +5 -3
  10. package/src/app/pane-runtime/index.tsx +2 -2
  11. package/src/app/pane-runtime/plugin-bindings.ts +3 -1
  12. package/src/app/pane-runtime/ticker-open-runtime.ts +6 -1
  13. package/src/app/since-last-visit/keys.ts +26 -0
  14. package/src/app/since-last-visit/model.ts +266 -0
  15. package/src/app/since-last-visit/strip.tsx +193 -0
  16. package/src/app/since-last-visit/use-since-last-visit.ts +289 -0
  17. package/src/app/since-last-visit/visit-tracker.ts +191 -0
  18. package/src/app.tsx +15 -0
  19. package/src/cli/commands/market.ts +8 -4
  20. package/src/cli/commands/system.ts +29 -1
  21. package/src/cli/commands/ticker.ts +12 -5
  22. package/src/cli/desktop-pane-shot-api-policy.ts +4 -1
  23. package/src/cli/desktop-pane-shot-browser.ts +2 -1
  24. package/src/cli/desktop-pane-shot-view.ts +3 -7
  25. package/src/cli/desktop-pane-shot.ts +26 -28
  26. package/src/cli/help.ts +1 -0
  27. package/src/cli/history-rows.ts +24 -0
  28. package/src/cli/index.ts +4 -0
  29. package/src/cli/options.ts +29 -1
  30. package/src/cli/pane-functions/catalog.ts +41 -4
  31. package/src/cli/pane-functions/function-help.ts +1 -1
  32. package/src/cli/pane-functions/headless.ts +63 -1
  33. package/src/cli/pane-functions/index.ts +2 -2
  34. package/src/cli/pane-functions/resolver.ts +43 -0
  35. package/src/cli/pane-functions/screenshot-payload.ts +3 -0
  36. package/src/cli/report-tables.ts +20 -5
  37. package/src/cli/shot-temp-dir.ts +30 -0
  38. package/src/cli/suffixed-listing-rows.ts +11 -0
  39. package/src/components/chart/composite/composite-chart.tsx +3 -3
  40. package/src/components/command-bar/commands/direct/index.ts +31 -8
  41. package/src/components/command-bar/commands/registry.ts +7 -0
  42. package/src/components/command-bar/routes/root/command-items.ts +8 -0
  43. package/src/components/command-bar/routes/root/results.ts +16 -0
  44. package/src/components/company-logo.tsx +10 -3
  45. package/src/components/data-table/sections.ts +6 -1
  46. package/src/components/layout/pane/title.ts +6 -2
  47. package/src/components/layout/shell/index.tsx +5 -1
  48. package/src/components/layout/shell/ticker-link-menu.ts +12 -9
  49. package/src/components/ticker/badge/format.ts +12 -3
  50. package/src/components/ticker/badge/index.tsx +9 -3
  51. package/src/components/ticker/list-table-view.tsx +119 -17
  52. package/src/components/ui/data-table/display-columns.ts +16 -0
  53. package/src/components/ui/data-table/index.tsx +40 -9
  54. package/src/components/ui/data-table/types.ts +14 -0
  55. package/src/core/state/app/layout-reducer.ts +3 -1
  56. package/src/core/state/app/layout.ts +2 -2
  57. package/src/data/config/layout.ts +14 -0
  58. package/src/data/config/store/normalize.ts +11 -1
  59. package/src/i18n/es.ts +38 -0
  60. package/src/i18n/ja.ts +38 -0
  61. package/src/i18n/ko.ts +38 -0
  62. package/src/i18n/zh-cn.ts +38 -0
  63. package/src/i18n/zh-tw.ts +38 -0
  64. package/src/layout/pane-follow.ts +141 -4
  65. package/src/layout/pane-layout-move.ts +10 -7
  66. package/src/layout/ticker-navigation.ts +13 -19
  67. package/src/layout/ticker-retarget.ts +3 -2
  68. package/src/market-data/market/index-level.ts +19 -0
  69. package/src/plugins/builtin/account-management/keyboard.ts +14 -0
  70. package/src/plugins/builtin/account-management/model.ts +2 -0
  71. package/src/plugins/builtin/account-management/pane.tsx +79 -7
  72. package/src/plugins/builtin/account-management/payment-recovery-row.tsx +97 -0
  73. package/src/plugins/builtin/account-management/yearly-plan-row.tsx +359 -0
  74. package/src/plugins/builtin/awards/pane.tsx +6 -8
  75. package/src/plugins/builtin/changelog/index.tsx +6 -44
  76. package/src/plugins/builtin/changelog/versions.ts +17 -68
  77. package/src/plugins/builtin/cloud/askg/executor.ts +2 -1
  78. package/src/plugins/builtin/cloud/askg/sources.ts +2 -1
  79. package/src/plugins/builtin/cpi/pane.tsx +1 -1
  80. package/src/plugins/builtin/debt-maturities/model.ts +1 -1
  81. package/src/plugins/builtin/earnings/board-table.ts +1 -1
  82. package/src/plugins/builtin/earnings/board.tsx +36 -16
  83. package/src/plugins/builtin/earnings/highlight.ts +47 -0
  84. package/src/plugins/builtin/earnings/history-table.ts +1 -1
  85. package/src/plugins/builtin/earnings/index.tsx +1 -1
  86. package/src/plugins/builtin/earnings-calls/pane.tsx +2 -2
  87. package/src/plugins/builtin/estimate-revisions/model.ts +1 -1
  88. package/src/plugins/builtin/exposure/index.tsx +1 -1
  89. package/src/plugins/builtin/macro-day/model.ts +6 -4
  90. package/src/plugins/builtin/market-valuation/detail.tsx +3 -3
  91. package/src/plugins/builtin/market-valuation/headless.ts +11 -4
  92. package/src/plugins/builtin/market-valuation/pane.tsx +3 -1
  93. package/src/plugins/builtin/market-valuation/view.ts +14 -0
  94. package/src/plugins/builtin/news/wire/news/detail-view.tsx +20 -8
  95. package/src/plugins/builtin/pe-band/pane.tsx +1 -1
  96. package/src/plugins/builtin/portfolio-list/cli/render.ts +8 -1
  97. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +176 -17
  98. package/src/plugins/builtin/portfolio-list/pane/groups.tsx +220 -0
  99. package/src/plugins/builtin/portfolio-list/pane/index.tsx +90 -15
  100. package/src/plugins/builtin/portfolio-list/table.tsx +13 -1
  101. package/src/plugins/builtin/research/corporate-actions-pane.tsx +4 -2
  102. package/src/plugins/builtin/research/relative-valuation-headless.ts +15 -5
  103. package/src/plugins/builtin/research/relative-valuation-model.ts +7 -1
  104. package/src/plugins/builtin/research/relative-valuation-pane.tsx +7 -4
  105. package/src/plugins/builtin/shared/headless-options.ts +1 -1
  106. package/src/plugins/builtin/social-mentions/model.ts +2 -2
  107. package/src/plugins/builtin/thirteenf/pane.tsx +1 -1
  108. package/src/plugins/builtin/ticker-detail/financials/model.ts +51 -16
  109. package/src/plugins/builtin/ticker-detail/financials/nopat.ts +16 -0
  110. package/src/plugins/builtin/ticker-detail/financials/ratios.ts +44 -13
  111. package/src/plugins/builtin/ticker-detail/financials/schema.ts +33 -2
  112. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +4 -2
  113. package/src/plugins/builtin/ticker-detail/headless-schema.ts +30 -4
  114. package/src/plugins/builtin/ticker-detail/headless.ts +254 -34
  115. package/src/plugins/builtin/ticker-detail/overview/model.ts +7 -3
  116. package/src/plugins/builtin/ticker-detail/pharma-signals/eligibility.ts +32 -0
  117. package/src/plugins/builtin/ticker-detail/pharma-signals/tab.tsx +162 -0
  118. package/src/plugins/builtin/ticker-detail/pharma-signals/waitlist.ts +126 -0
  119. package/src/plugins/builtin/ticker-detail/research-groups.ts +6 -4
  120. package/src/plugins/builtin/ticker-detail/research-tabs.ts +11 -0
  121. package/src/portfolio/column-values.ts +20 -8
  122. package/src/portfolio/suffixed-listings.ts +3 -1
  123. package/src/portfolio/watchlist-groups.ts +212 -0
  124. package/src/react/ticker-source.ts +3 -1
  125. package/src/renderers/dom/styles.css +7 -0
  126. package/src/state/app/bootstrap.ts +11 -0
  127. package/src/state/app/context/index.tsx +6 -0
  128. package/src/sync/collections-contributor.ts +5 -2
  129. package/src/sync/config-merge.ts +10 -2
  130. package/src/sync/sanitize.ts +28 -0
  131. package/src/telemetry/usage-counts.ts +17 -0
  132. package/src/time-series/chart-seed.ts +1 -1
  133. package/src/time-series/financial-period-coverage.ts +4 -12
  134. package/src/time-series/parsed-history-cache.ts +1 -1
  135. package/src/time-series/resolve.ts +1 -1
  136. package/src/time-series/use-chart-resolution.ts +6 -1
  137. package/src/types/config.ts +32 -0
  138. package/src/types/headless.ts +5 -0
  139. package/src/types/plugin-context.ts +5 -0
  140. package/src/types/ticker.ts +14 -0
  141. package/src/ui/ascii-font.ts +1 -4
  142. package/src/utils/async-deadline.ts +2 -2
  143. package/src/utils/csv.ts +44 -5
  144. package/src/utils/futures-generic.ts +3 -0
@@ -74,6 +74,8 @@ import { deleteAccountConfirmingSession } from "./delete-account";
74
74
  import { endTrialAfterWarning } from "./trial-cancel";
75
75
  import { CalendarAccountTab } from "./calendar-tab";
76
76
  import { InviteRow } from "./invite-row";
77
+ import { PaymentRecoveryRow, usePaymentRecovery } from "./payment-recovery-row";
78
+ import { YearlyPlanRow, useYearlyPlan } from "./yearly-plan-row";
77
79
  import { useAccountManagementFooter } from "./footer";
78
80
  import { useAccountManagementKeyboard } from "./keyboard";
79
81
  import {
@@ -130,8 +132,9 @@ const ACCOUNT_TAB_FIELD_ORDER: Record<AccountManagementTab, AccountFieldKey[]> =
130
132
  ],
131
133
  // Its actions are footer hints; the tab owns its footer.
132
134
  calendar: [],
133
- // Cancel Trial shows only while a trial runs, the invite once it loaded.
134
- pro: ["upgradeAction", "cancelTrialAction", "inviteCopyAction"],
135
+ // Cancel Trial shows only while a trial runs, the yearly row while it has
136
+ // an action, Not Now while its review is open, the invite once it loaded.
137
+ pro: ["upgradeAction", "cancelTrialAction", "yearlyPlanAction", "yearlyPlanDismissAction", "inviteCopyAction"],
135
138
  // The Teams tab owns its own keyboard handling (a list, not form fields).
136
139
  teams: [],
137
140
  // Remote assistants allowed to drive this terminal; a list with its own footer.
@@ -241,6 +244,7 @@ export function AccountManagementPane({ focused, width, height }: PaneProps) {
241
244
  );
242
245
  const [message, setMessage] = useState<{ tone: "info" | "success" | "error"; text: string } | null>(null);
243
246
  const [busy, setBusy] = useState<AccountBusy>(null);
247
+ const paymentRecovery = usePaymentRecovery(hasSession && activeTab === "pro", sessionMarker);
244
248
 
245
249
  // A requested tab switches the open pane; one requested before it mounted wins over the restored tab once.
246
250
  useEffect(() => subscribeRequestedAccountManagementTab((tab) => {
@@ -268,13 +272,33 @@ export function AccountManagementPane({ focused, width, height }: PaneProps) {
268
272
  // Chat's card settings show once the server keeps them; the desks only while showing them is on.
269
273
  const chatCardSupported = profile?.showLocalTime !== undefined;
270
274
  const planAccess = useMemo(() => resolvePlanAccess(profile), [profile]);
275
+ // A paid switch changes the plan on the server: the session and the tab follow it.
276
+ const refreshAfterYearlySwitch = useCallback(() => {
277
+ void chatController.refreshSession().catch(logFailure("account-management.pane", "Refresh yearly account session failed"));
278
+ void apiClient.getAccountProfile().then(
279
+ (nextProfile) => { if (nextProfile) setProfile(nextProfile); },
280
+ logFailure("account-management.pane", "Refresh yearly account profile failed"),
281
+ );
282
+ }, []);
283
+ // An opened review lands on Not Now, in the same update that draws it: no
284
+ // render ever has Pay active on open, so a held Enter never pays.
285
+ const focusYearlyDismiss = useCallback(() => setActiveField("yearlyPlanDismissAction"), []);
286
+ // Only a paying Pro subscriber is asked; the server decides who may switch.
287
+ const yearlyPlan = useYearlyPlan(
288
+ hasSession && activeTab === "pro" && planAccess.isPayingPro && !paymentRecovery.visible && !paymentRecovery.checking,
289
+ sessionMarker,
290
+ refreshAfterYearlySwitch,
291
+ focusYearlyDismiss,
292
+ );
271
293
  const fieldOrder = useMemo(() => ACCOUNT_TAB_FIELD_ORDER[activeTab].filter((field) => {
272
294
  if (field === "showLocalTime" || field === "showDesks") return chatCardSupported;
273
295
  if (field === "desks") return chatCardSupported && draft.showDesks;
274
296
  if (field === "cancelTrialAction") return planAccess.isTrialActive;
297
+ if (field === "yearlyPlanAction") return yearlyPlan.primary !== null;
298
+ if (field === "yearlyPlanDismissAction") return yearlyPlan.reviewing;
275
299
  if (field === "inviteCopyAction") return invite !== null;
276
300
  return true;
277
- }), [activeTab, chatCardSupported, draft.showDesks, invite, planAccess.isTrialActive]);
301
+ }), [activeTab, chatCardSupported, draft.showDesks, invite, planAccess.isTrialActive, yearlyPlan.primary, yearlyPlan.reviewing]);
278
302
  const accountTabs = ACCOUNT_TAB_DEFS.map((tab) => ({ ...tab, label: t(tab.label) }));
279
303
 
280
304
  const planPrice = useMemo(() => formatCloudMonthlyPrice(pricing), [language, pricing]);
@@ -722,6 +746,11 @@ export function AccountManagementPane({ focused, width, height }: PaneProps) {
722
746
  const startUpgrade = useCloudUpgradeAction("acm");
723
747
  const openUpgrade = useCallback(() => {
724
748
  setActiveField("upgradeAction");
749
+ if (paymentRecovery.checking) return;
750
+ if (paymentRecovery.visible) {
751
+ paymentRecovery.pay();
752
+ return;
753
+ }
725
754
  if (busy) return;
726
755
  let opening = false;
727
756
  void startUpgrade({
@@ -735,7 +764,7 @@ export function AccountManagementPane({ focused, width, height }: PaneProps) {
735
764
  setBusy(null);
736
765
  setMessage(null);
737
766
  });
738
- }, [busy, startUpgrade]);
767
+ }, [busy, startUpgrade, paymentRecovery.visible, paymentRecovery.pay, paymentRecovery.checking]);
739
768
 
740
769
  const deleteAccount = useCallback(async () => {
741
770
  setActiveField("deleteAccountAction");
@@ -848,6 +877,16 @@ export function AccountManagementPane({ focused, width, height }: PaneProps) {
848
877
  setActiveField,
849
878
  setDraftValue,
850
879
  turnOffEmailAlerts,
880
+ yearlyPlanAction: () => {
881
+ setActiveField("yearlyPlanAction");
882
+ yearlyPlan.primary?.();
883
+ },
884
+ dismissYearlyReview: yearlyPlan.reviewing
885
+ ? () => {
886
+ yearlyPlan.dismiss();
887
+ setActiveField("yearlyPlanAction");
888
+ }
889
+ : null,
851
890
  });
852
891
 
853
892
  const textField = (key: "username" | "name" | "company" | "title" | "publicEmail" | "xAccount", label: string, placeholder: string) => (
@@ -1067,14 +1106,24 @@ export function AccountManagementPane({ focused, width, height }: PaneProps) {
1067
1106
  width={contentWidth}
1068
1107
  activePlan={planAccess.hasProAccess ? "pro" : "free"}
1069
1108
  />
1070
- <Box flexDirection="row" gap={1}>
1109
+ {paymentRecovery.visible ? (
1110
+ <PaymentRecoveryRow
1111
+ active={activeField === "upgradeAction"}
1112
+ busy={paymentRecovery.busy}
1113
+ message={paymentRecovery.message}
1114
+ labelWidth={formLabelWidth}
1115
+ nodeRef={fieldNodeRef("upgradeAction")}
1116
+ onPay={openUpgrade}
1117
+ onFocus={() => setActiveField("upgradeAction")}
1118
+ />
1119
+ ) : <Box flexDirection="row" gap={1}>
1071
1120
  <Box ref={fieldNodeRef("upgradeAction")} flexDirection="row">
1072
1121
  <Button
1073
1122
  label={planAccess.isPayingPro ? t("Manage Pro") : busy === "billing" ? t("Opening...") : t("Upgrade to Pro")}
1074
1123
  variant={planAccess.isPayingPro ? "secondary" : "primary"}
1075
1124
  active={activeField === "upgradeAction"}
1076
1125
  onPress={openUpgrade}
1077
- disabled={!!busy}
1126
+ disabled={!!busy || paymentRecovery.checking}
1078
1127
  />
1079
1128
  </Box>
1080
1129
  {planAccess.isTrialActive ? (
@@ -1088,7 +1137,30 @@ export function AccountManagementPane({ focused, width, height }: PaneProps) {
1088
1137
  />
1089
1138
  </Box>
1090
1139
  ) : null}
1091
- </Box>
1140
+ </Box>}
1141
+ {paymentRecovery.visible ? null : (
1142
+ <YearlyPlanRow
1143
+ view={yearlyPlan.view}
1144
+ busy={yearlyPlan.busy}
1145
+ message={yearlyPlan.message}
1146
+ width={contentWidth}
1147
+ labelWidth={formLabelWidth}
1148
+ primaryActive={activeField === "yearlyPlanAction"}
1149
+ dismissActive={activeField === "yearlyPlanDismissAction"}
1150
+ primaryRef={fieldNodeRef("yearlyPlanAction")}
1151
+ dismissRef={fieldNodeRef("yearlyPlanDismissAction")}
1152
+ onPrimary={yearlyPlan.primary ? () => {
1153
+ setActiveField("yearlyPlanAction");
1154
+ yearlyPlan.primary?.();
1155
+ } : null}
1156
+ onDismiss={() => {
1157
+ yearlyPlan.dismiss();
1158
+ setActiveField("yearlyPlanAction");
1159
+ }}
1160
+ onFocusPrimary={() => setActiveField("yearlyPlanAction")}
1161
+ onFocusDismiss={() => setActiveField("yearlyPlanDismissAction")}
1162
+ />
1163
+ )}
1092
1164
  {invite ? (
1093
1165
  <InviteRow
1094
1166
  invite={invite}
@@ -0,0 +1,97 @@
1
+ import { useCallback, useEffect, useRef, useState, type Ref } from "react";
2
+ import { apiClient } from "../../../api-client";
3
+ import { Button, FieldLabel } from "../../../components";
4
+ import { t } from "../../../i18n";
5
+ import { colors } from "../../../theme/colors";
6
+ import { Box, Text, useRendererHost, type BoxRenderable } from "../../../ui";
7
+
8
+ export function usePaymentRecovery(enabled: boolean, sessionMarker: string) {
9
+ const renderer = useRendererHost();
10
+ const [status, setStatus] = useState<string | null>(null);
11
+ const [message, setMessage] = useState<string | null>(null);
12
+ const [busy, setBusy] = useState(false);
13
+ const [loaded, setLoaded] = useState(false);
14
+ const generation = useRef(0);
15
+ const opening = useRef<number | null>(null);
16
+ const refreshSequence = useRef(0);
17
+ const visible = status === "past_due" || status === "unpaid";
18
+
19
+ const refresh = useCallback(async (current: number) => {
20
+ if (generation.current !== current) return;
21
+ const sequence = ++refreshSequence.current;
22
+ try {
23
+ const plan = await apiClient.getCloudAccountPlan();
24
+ if (generation.current === current && refreshSequence.current === sequence) setStatus(plan.subscription?.status ?? null);
25
+ } catch {
26
+ if (generation.current === current && refreshSequence.current === sequence) setMessage(t("Could not refresh your account. Try again."));
27
+ } finally {
28
+ if (generation.current === current && refreshSequence.current === sequence) setLoaded(true);
29
+ }
30
+ }, []);
31
+
32
+ useEffect(() => {
33
+ const current = ++generation.current;
34
+ setStatus(null);
35
+ setMessage(null);
36
+ setBusy(false);
37
+ setLoaded(false);
38
+ if (enabled) void refresh(current).catch(() => setMessage(t("Could not refresh your account. Try again.")));
39
+ return () => { generation.current++; };
40
+ }, [enabled, sessionMarker, refresh]);
41
+
42
+ useEffect(() => {
43
+ if (!enabled || !visible) return;
44
+ const current = generation.current;
45
+ const timer = setInterval(() => { void refresh(current).catch(() => setMessage(t("Could not refresh your account. Try again."))); }, 5_000);
46
+ return () => clearInterval(timer);
47
+ }, [enabled, visible, refresh]);
48
+
49
+ const pay = useCallback(async () => {
50
+ if (opening.current === generation.current || !enabled || !visible) return;
51
+ opening.current = generation.current;
52
+ setBusy(true);
53
+ setMessage(null);
54
+ const current = generation.current;
55
+ try {
56
+ const { url } = await apiClient.createInvoicePayment();
57
+ if (generation.current !== current) return;
58
+ const opened = await renderer.openExternal(url);
59
+ if (generation.current === current) {
60
+ setMessage(opened === false ? t("Could not open invoice payment. Try again.") : t("Invoice opened in your browser."));
61
+ }
62
+ } catch {
63
+ if (generation.current === current) setMessage(t("Could not open invoice payment. Try again."));
64
+ } finally {
65
+ await refresh(current);
66
+ if (opening.current === current) opening.current = null;
67
+ if (generation.current === current) setBusy(false);
68
+ }
69
+ }, [enabled, visible, renderer, refresh]);
70
+
71
+ const openPayment = useCallback(() => {
72
+ void pay().catch(() => setMessage(t("Could not open invoice payment. Try again.")));
73
+ }, [pay]);
74
+
75
+ return { visible, busy, message, pay: openPayment, checking: enabled && !loaded };
76
+ }
77
+
78
+ export function PaymentRecoveryRow({ active, busy, message, labelWidth, nodeRef, onPay, onFocus }: {
79
+ active: boolean;
80
+ busy: boolean;
81
+ message: string | null;
82
+ labelWidth: number;
83
+ nodeRef?: Ref<BoxRenderable>;
84
+ onPay: () => void;
85
+ onFocus: () => void;
86
+ }) {
87
+ return (
88
+ <Box ref={nodeRef} flexDirection="row" gap={1} onMouseDown={onFocus}>
89
+ <FieldLabel label={t("Payment")} active={active} width={labelWidth} />
90
+ <Box flexDirection="column" flexShrink={1} minWidth={0} gap={1}>
91
+ <Text fg={colors.text} wrapMode="word">{t("Your Pro payment did not go through.")}</Text>
92
+ <Button label={busy ? t("Opening...") : t("Pay invoice")} active={active} disabled={busy} onPress={onPay} />
93
+ {message ? <Text fg={colors.textDim} wrapMode="word">{message}</Text> : null}
94
+ </Box>
95
+ </Box>
96
+ );
97
+ }
@@ -0,0 +1,359 @@
1
+ import { useCallback, useEffect, useRef, useState, type Ref } from "react";
2
+ import {
3
+ apiClient,
4
+ yearlyRefusalCode,
5
+ type CloudYearlyOffer,
6
+ type CloudYearlyPlanStatus,
7
+ type CloudYearlyResult,
8
+ type CloudYearlyReview,
9
+ } from "../../../api-client";
10
+ import { Button, FieldLabel, KeyValueRow } from "../../../components";
11
+ import { t, tf } from "../../../i18n";
12
+ import { colors } from "../../../theme/colors";
13
+ import { Box, Text, TextAttributes, useRendererHost, type BoxRenderable } from "../../../ui";
14
+ import { formatDetailDate, formatShortDate } from "../../../utils/datetime-format";
15
+
16
+ /**
17
+ * The Pro tab's offer to move a monthly Pro subscription to yearly billing:
18
+ * the offer, the exact review of the charge, and the outcome, all inline.
19
+ * The server decides who may switch and what it costs; the row never says a
20
+ * switch is done before the server reports it paid.
21
+ */
22
+
23
+ /** Exact cents, as on an invoice: $567.29, $630.00. */
24
+ function formatExactUsd(cents: number): string {
25
+ return `$${(cents / 100).toFixed(2)}`;
26
+ }
27
+
28
+ /** Whole dollars when exact, for the offer line: $630, $210. */
29
+ function formatOfferUsd(cents: number): string {
30
+ return cents % 100 === 0 ? `$${cents / 100}` : formatExactUsd(cents);
31
+ }
32
+
33
+ function yearlyOfferText(offer: CloudYearlyOffer): string {
34
+ return tf("Yearly is {yearly} a year, {savings} less than twelve monthly payments of {monthly} ({twelve}).", {
35
+ yearly: formatOfferUsd(offer.yearlyAmount),
36
+ savings: formatOfferUsd(offer.savingsAmount),
37
+ monthly: formatOfferUsd(offer.monthlyAmount),
38
+ twelve: formatOfferUsd(offer.twelveMonthlyAmount),
39
+ });
40
+ }
41
+
42
+ /** What the server's refusals mean here, in the app's language. */
43
+ function refusalMessage(code: string | null): string {
44
+ switch (code) {
45
+ case "review_changed": return t("The total changed since you reviewed it. Review it again.");
46
+ case "review_expired": return t("This total has expired. Review it again.");
47
+ case "review_invalid": return t("This review is no longer valid. Review the switch again.");
48
+ case "busy": return t("Your switch is already going through. Refresh in a moment.");
49
+ case "pending": return t("Your switch to yearly is waiting for its payment.");
50
+ case "unavailable": return t("Yearly billing can't be set up for this plan here. Your plan is unchanged.");
51
+ case "failed": return t("The switch didn't go through and your plan is unchanged. Try again in a minute.");
52
+ default: return t("We couldn't confirm the switch. Refresh your account before trying again.");
53
+ }
54
+ }
55
+
56
+ export type YearlyPlanView =
57
+ | { kind: "hidden" }
58
+ | { kind: "offer"; offer: CloudYearlyOffer }
59
+ | { kind: "review"; review: CloudYearlyReview }
60
+ | { kind: "pending"; invoiceUrl: string | null; expiresAt: string | null }
61
+ | { kind: "result"; result: CloudYearlyResult };
62
+
63
+ /**
64
+ * `onReviewOpened` runs in the same update that shows the review, so the
65
+ * caller can move the keyboard to Not Now before any render has the payment
66
+ * active.
67
+ */
68
+ export function useYearlyPlan(enabled: boolean, sessionMarker: string, onSwitched: () => void, onReviewOpened: () => void) {
69
+ const renderer = useRendererHost();
70
+ const [status, setStatus] = useState<CloudYearlyPlanStatus | null>(null);
71
+ const [review, setReview] = useState<CloudYearlyReview | null>(null);
72
+ const [result, setResult] = useState<CloudYearlyResult | null>(null);
73
+ const [busy, setBusy] = useState<"review" | "confirm" | "invoice" | null>(null);
74
+ const [message, setMessage] = useState<string | null>(null);
75
+ const generation = useRef(0);
76
+ // One confirmation at a time, whatever presses arrive while it is out.
77
+ const confirming = useRef(false);
78
+
79
+ const load = useCallback(async (current: number) => {
80
+ try {
81
+ const next = await apiClient.getCloudYearlyPlan();
82
+ if (generation.current !== current) return;
83
+ setStatus(next);
84
+ // A payment the row was waiting on is now the server's status to tell.
85
+ setResult((shown) => shown?.state === "switched" ? shown : null);
86
+ } catch {
87
+ // Intentional ignore: without an answer the row stays hidden; the plan is unchanged.
88
+ if (generation.current === current) setStatus(null);
89
+ }
90
+ }, []);
91
+
92
+ useEffect(() => {
93
+ const current = ++generation.current;
94
+ setStatus(null);
95
+ setReview(null);
96
+ setBusy(null);
97
+ setMessage(null);
98
+ if (enabled) void load(current).catch(() => setStatus(null));
99
+ else setResult((shown) => shown?.state === "switched" ? shown : null);
100
+ return () => { generation.current++; };
101
+ }, [enabled, sessionMarker, load]);
102
+
103
+ const openReview = useCallback(async () => {
104
+ if (busy) return;
105
+ const current = generation.current;
106
+ setBusy("review");
107
+ setMessage(null);
108
+ try {
109
+ const next = await apiClient.previewCloudYearlyPlan();
110
+ if (generation.current === current) {
111
+ // One batched update: a key held down never finds Pay active on open.
112
+ setReview(next);
113
+ onReviewOpened();
114
+ }
115
+ } catch (error) {
116
+ if (generation.current !== current) return;
117
+ const code = yearlyRefusalCode(error);
118
+ setMessage(code ? refusalMessage(code) : t("Couldn't work out the yearly total. Try again in a minute."));
119
+ if (code) await load(current);
120
+ } finally {
121
+ if (generation.current === current) setBusy(null);
122
+ }
123
+ }, [busy, load, onReviewOpened]);
124
+
125
+ const confirm = useCallback(async () => {
126
+ if (!review || confirming.current) return;
127
+ confirming.current = true;
128
+ const current = generation.current;
129
+ setBusy("confirm");
130
+ setMessage(null);
131
+ try {
132
+ const answer = await apiClient.confirmCloudYearlyPlan(review.token);
133
+ if (generation.current !== current) return;
134
+ setReview(null);
135
+ setResult(answer);
136
+ if (answer.state === "switched") onSwitched();
137
+ } catch (error) {
138
+ if (generation.current !== current) return;
139
+ const code = yearlyRefusalCode(error);
140
+ setMessage(refusalMessage(code));
141
+ // A total that moved or ran out: show the new one, never charge the old.
142
+ if (code !== "busy") {
143
+ setReview(null);
144
+ await load(current);
145
+ }
146
+ } finally {
147
+ confirming.current = false;
148
+ if (generation.current === current) setBusy(null);
149
+ }
150
+ }, [load, onSwitched, review]);
151
+
152
+ const dismiss = useCallback(() => {
153
+ if (busy === "confirm") return;
154
+ setReview(null);
155
+ setMessage(null);
156
+ }, [busy]);
157
+
158
+ const pendingUrl = result?.state === "payment_required"
159
+ ? result.invoiceUrl
160
+ : status?.state === "pending" ? status.invoiceUrl : null;
161
+ const openInvoice = useCallback(async () => {
162
+ if (!pendingUrl || busy) return;
163
+ const current = generation.current;
164
+ setBusy("invoice");
165
+ try {
166
+ const opened = await renderer.openExternal(pendingUrl);
167
+ if (generation.current === current) {
168
+ setMessage(opened === false ? t("Could not open invoice payment. Try again.") : t("Invoice opened in your browser."));
169
+ }
170
+ } catch {
171
+ if (generation.current === current) setMessage(t("Could not open invoice payment. Try again."));
172
+ } finally {
173
+ if (generation.current === current) setBusy(null);
174
+ }
175
+ }, [busy, pendingUrl, renderer]);
176
+
177
+ let view: YearlyPlanView = { kind: "hidden" };
178
+ if (result) view = { kind: "result", result };
179
+ else if (review) view = { kind: "review", review };
180
+ else if (status?.state === "pending") view = { kind: "pending", invoiceUrl: status.invoiceUrl, expiresAt: status.expiresAt };
181
+ else if (status?.state === "available") view = { kind: "offer", offer: status.offer };
182
+ if (!enabled && view.kind !== "result") view = { kind: "hidden" };
183
+
184
+ /** What Enter on the row's first action does now, if anything. */
185
+ const primary = view.kind === "offer"
186
+ ? () => { void openReview().catch(() => setMessage(t("Couldn't work out the yearly total. Try again in a minute."))); }
187
+ : view.kind === "review"
188
+ ? () => { void confirm().catch(() => setMessage(refusalMessage(null))); }
189
+ : pendingUrl && (view.kind === "pending" || view.kind === "result")
190
+ ? () => { void openInvoice().catch(() => setMessage(t("Could not open invoice payment. Try again."))); }
191
+ : null;
192
+
193
+ return { view, busy, message, primary, dismiss, reviewing: view.kind === "review" };
194
+ }
195
+
196
+ function ReviewLines({ review, width }: { review: CloudYearlyReview; width: number }) {
197
+ const lineWidth = Math.max(24, Math.min(width, 56));
198
+ return (
199
+ <Box flexDirection="column" width={lineWidth}>
200
+ <KeyValueRow
201
+ label={tf("Yearly Pro, today to {date}", { date: formatShortDate(review.renewsAt) })}
202
+ value={formatExactUsd(review.yearlyAmount)}
203
+ width={lineWidth}
204
+ align="right"
205
+ emphasis={false}
206
+ />
207
+ <KeyValueRow
208
+ label={t("Credit for the rest of this month")}
209
+ value={review.credit > 0 ? `-${formatExactUsd(review.credit)}` : formatExactUsd(0)}
210
+ width={lineWidth}
211
+ align="right"
212
+ emphasis={false}
213
+ />
214
+ {review.tax > 0 ? (
215
+ <KeyValueRow label={t("Tax")} value={formatExactUsd(review.tax)} width={lineWidth} align="right" emphasis={false} />
216
+ ) : null}
217
+ {review.balanceApplied > 0 ? (
218
+ <KeyValueRow label={t("Account credit")} value={`-${formatExactUsd(review.balanceApplied)}`} width={lineWidth} align="right" emphasis={false} />
219
+ ) : null}
220
+ <KeyValueRow label={t("Due today")} value={formatExactUsd(review.amountDue)} width={lineWidth} align="right" />
221
+ </Box>
222
+ );
223
+ }
224
+
225
+ function renewalText(review: CloudYearlyReview): string {
226
+ const params = { amount: formatExactUsd(review.renewalAmount), date: formatShortDate(review.renewsAt) };
227
+ return review.renewalTaxed
228
+ ? tf("Then {amount} a year plus tax, renewing {date}.", params)
229
+ : tf("Then {amount} a year, renewing {date}.", params);
230
+ }
231
+
232
+ function PaymentNeeded({ expiresAt }: { expiresAt: string | null }) {
233
+ return (
234
+ <Text fg={colors.text} wrapMode="word">
235
+ {[
236
+ t("Your switch to yearly needs the payment confirmed. You stay on monthly billing until it is paid."),
237
+ expiresAt ? tf("Unpaid by {date}, the switch is dropped.", { date: formatDetailDate(expiresAt) }) : "",
238
+ ].filter(Boolean).join(" ")}
239
+ </Text>
240
+ );
241
+ }
242
+
243
+ function resultText(result: Extract<CloudYearlyResult, { state: "switched" | "processing" }>): string {
244
+ if (result.state === "processing") return t("Your payment is processing. You move to yearly billing once it clears.");
245
+ return [
246
+ t("You're on yearly billing."),
247
+ result.amountPaid !== null ? tf("Paid {amount} today.", { amount: formatExactUsd(result.amountPaid) }) : "",
248
+ result.renewsAt ? tf("Renews {date} at {amount}.", { date: formatShortDate(result.renewsAt), amount: formatExactUsd(result.renewalAmount) }) : "",
249
+ ].filter(Boolean).join(" ");
250
+ }
251
+
252
+ /**
253
+ * The row as it draws for one state. Two actions while reviewing: the
254
+ * payment, and Not Now, which the keyboard lands on first so a second Enter
255
+ * never pays by itself.
256
+ */
257
+ export function YearlyPlanRow({
258
+ view,
259
+ busy,
260
+ message,
261
+ width,
262
+ labelWidth,
263
+ primaryActive,
264
+ dismissActive,
265
+ primaryRef,
266
+ dismissRef,
267
+ onPrimary,
268
+ onDismiss,
269
+ onFocusPrimary,
270
+ onFocusDismiss,
271
+ }: {
272
+ view: YearlyPlanView;
273
+ busy: "review" | "confirm" | "invoice" | null;
274
+ message: string | null;
275
+ width: number;
276
+ labelWidth: number;
277
+ primaryActive: boolean;
278
+ dismissActive: boolean;
279
+ primaryRef?: Ref<BoxRenderable>;
280
+ dismissRef?: Ref<BoxRenderable>;
281
+ onPrimary: (() => void) | null;
282
+ onDismiss: () => void;
283
+ onFocusPrimary: () => void;
284
+ onFocusDismiss: () => void;
285
+ }) {
286
+ if (view.kind === "hidden" && !message) return null;
287
+ const bodyWidth = Math.max(20, width - labelWidth - 1);
288
+ const pendingUrl = view.kind === "pending"
289
+ ? view.invoiceUrl
290
+ : view.kind === "result" && view.result.state === "payment_required" ? view.result.invoiceUrl : null;
291
+ return (
292
+ <Box flexDirection="row" gap={1}>
293
+ <FieldLabel label={t("Yearly")} active={primaryActive || dismissActive} width={labelWidth} />
294
+ <Box flexDirection="column" flexShrink={1} minWidth={0} gap={1} width={bodyWidth}>
295
+ {view.kind === "offer" ? (
296
+ <>
297
+ <Text fg={colors.text} wrapMode="word">{yearlyOfferText(view.offer)}</Text>
298
+ <Box ref={primaryRef} flexDirection="row" onMouseDown={onFocusPrimary}>
299
+ <Button
300
+ label={busy === "review" ? t("Loading...") : t("Review Yearly")}
301
+ active={primaryActive}
302
+ disabled={!!busy}
303
+ onPress={() => onPrimary?.()}
304
+ />
305
+ </Box>
306
+ </>
307
+ ) : null}
308
+ {view.kind === "review" ? (
309
+ <>
310
+ <Text fg={colors.text} attributes={TextAttributes.BOLD}>{t("Switch to yearly billing")}</Text>
311
+ <ReviewLines review={view.review} width={bodyWidth} />
312
+ <Text fg={colors.textDim} wrapMode="word">
313
+ {`${renewalText(view.review)} ${t("Your saved payment method is charged today, and your plan stays monthly until it is paid.")}`}
314
+ </Text>
315
+ <Box flexDirection="row" gap={1}>
316
+ <Box ref={primaryRef} flexDirection="row" onMouseDown={onFocusPrimary}>
317
+ <Button
318
+ label={busy === "confirm"
319
+ ? t("Switching...")
320
+ : view.review.amountDue > 0
321
+ ? tf("Pay {amount} and Switch", { amount: formatExactUsd(view.review.amountDue) })
322
+ : t("Switch to Yearly")}
323
+ variant="primary"
324
+ active={primaryActive}
325
+ disabled={!!busy}
326
+ onPress={() => onPrimary?.()}
327
+ />
328
+ </Box>
329
+ <Box ref={dismissRef} flexDirection="row" onMouseDown={onFocusDismiss}>
330
+ <Button
331
+ label={t("Not Now")}
332
+ active={dismissActive}
333
+ disabled={busy === "confirm"}
334
+ onPress={onDismiss}
335
+ />
336
+ </Box>
337
+ </Box>
338
+ </>
339
+ ) : null}
340
+ {view.kind === "pending" ? <PaymentNeeded expiresAt={view.expiresAt} /> : null}
341
+ {view.kind === "result" && view.result.state === "payment_required" ? <PaymentNeeded expiresAt={view.result.expiresAt} /> : null}
342
+ {view.kind === "result" && view.result.state !== "payment_required" ? (
343
+ <Text fg={colors.text} wrapMode="word">{resultText(view.result)}</Text>
344
+ ) : null}
345
+ {pendingUrl ? (
346
+ <Box ref={primaryRef} flexDirection="row" onMouseDown={onFocusPrimary}>
347
+ <Button
348
+ label={busy === "invoice" ? t("Opening...") : t("Confirm Payment")}
349
+ active={primaryActive}
350
+ disabled={!!busy}
351
+ onPress={() => onPrimary?.()}
352
+ />
353
+ </Box>
354
+ ) : null}
355
+ {message ? <Text fg={colors.textDim} wrapMode="word">{message}</Text> : null}
356
+ </Box>
357
+ </Box>
358
+ );
359
+ }
@@ -6,7 +6,7 @@ import { Badge, ChartTableHeader, DataTableView, Notice, PageStackView, PaneStat
6
6
  usePaneNoticeFooter, usePaneStatusFooter, usePaneTabs, useQueryBarSearch, useTableLoadMore, type DataTableColumn, type PaneHint, type QueryBarFilter } from "../../../components";
7
7
  import { usePaneRefreshKey } from "../../../components/data-table/table-pane";
8
8
  import { formatCompactAxis } from "../../../components/chart-table";
9
- import { missingCell, shareCell, withoutQuietColumns } from "../shared/research-cells";
9
+ import { missingCell, shareCell } from "../shared/research-cells";
10
10
  import { useAsyncResource, useAutoRefresh, usePaneSettingValue, usePluginAppActions, usePluginPaneState } from "../../../public/react";
11
11
  import { usePaneTickerIdentity } from "../../../state/hooks/pane-ticker";
12
12
  import { useThemeColors } from "../../../theme/theme-context";
@@ -49,8 +49,8 @@ const rowDate = (row: AwardRow) => new Date(`${row.awardDate}T00:00:00Z`);
49
49
  const COLUMN = {
50
50
  date: { id: "date", label: "Date", width: 11, align: "left" }, recipient: { id: "recipient", label: "Awardee", width: 26, flexGrow: 1, align: "left" },
51
51
  ticker: { id: "ticker", label: "Ticker", width: 10, align: "left" }, currency: { id: "currency", label: "CCY", width: 5, align: "left" },
52
- value: { id: "value", label: "Value", width: 11, align: "right" }, obligated: { id: "obligated", label: "Obligated", width: 11, align: "right" },
53
- ceiling: { id: "ceiling", label: "Ceiling", width: 11, align: "right" }, agency: { id: "agency", label: "Agency", width: 24, align: "left" },
52
+ value: { id: "value", label: "Value", width: 11, align: "right", omitWhenEmpty: true }, obligated: { id: "obligated", label: "Obligated", width: 11, align: "right", omitWhenEmpty: true },
53
+ ceiling: { id: "ceiling", label: "Ceiling", width: 11, align: "right", omitWhenEmpty: true }, agency: { id: "agency", label: "Agency", width: 24, align: "left" },
54
54
  country: { id: "country", label: "Country", width: 8, align: "left" }, period: { id: "period", label: "Performance period", width: 24, align: "left" },
55
55
  title: { id: "title", label: "Contract", width: 36, flexGrow: 1, align: "left" },
56
56
  dateBasis: { id: "dateBasis", label: "Date basis", width: 14, align: "left" },
@@ -59,8 +59,6 @@ const COLUMN = {
59
59
  // shows the contract; the period and date basis follow.
60
60
  const FEED_COLUMNS: DataTableColumn[] = [COLUMN.date, COLUMN.recipient, COLUMN.ticker, COLUMN.title, COLUMN.agency, COLUMN.currency,
61
61
  COLUMN.value, COLUMN.obligated, COLUMN.ceiling, COLUMN.country, COLUMN.period, COLUMN.dateBasis];
62
- /** Amounts a source never reports (UK and EU notices have no obligation or ceiling) leave a column of dashes. */
63
- const QUIET_AMOUNTS = { obligated: [MISSING_VALUE], ceiling: [MISSING_VALUE] } as const;
64
62
  const EVENT_COLUMNS: DataTableColumn[] = [COLUMN.date, COLUMN.recipient, COLUMN.ticker,
65
63
  { id: "ratio", label: "% revenue", width: 11, align: "right" }, COLUMN.currency, { ...COLUMN.value, label: "Compared value" },
66
64
  { id: "revenue", label: "Annual revenue", width: 14, align: "right" }, { id: "basis", label: "Value basis", width: 13, align: "left" },
@@ -68,8 +66,8 @@ const EVENT_COLUMNS: DataTableColumn[] = [COLUMN.date, COLUMN.recipient, COLUMN.
68
66
  // The share leads the figures: concentration is what these views are for.
69
67
  const AGG_COLUMNS: DataTableColumn[] = [
70
68
  { id: "label", label: "Agency", width: 30, flexGrow: 1, align: "left" }, { id: "currency", label: "CCY", width: 5, align: "left" },
71
- { id: "share", label: "Share %", width: 24, align: "right" }, { id: "obligated", label: "Obligated", width: 12, align: "right" }, { id: "value", label: "Value", width: 12, align: "right" },
72
- { id: "ceiling", label: "Ceiling", width: 12, align: "right" },
69
+ { id: "share", label: "Share %", width: 24, align: "right" }, { ...COLUMN.obligated, width: 12 }, { ...COLUMN.value, width: 12 },
70
+ { ...COLUMN.ceiling, width: 12 },
73
71
  { id: "contracts", label: "Awards", width: 8, align: "right" },
74
72
  { id: "scope", label: "Scope", width: 27, align: "left" },
75
73
  ];
@@ -220,7 +218,7 @@ function AwardsView({ width, height, focused, symbol }: PaneProps & { symbol: st
220
218
  view={tab === "sectors" ? { value: leaderView, options: [{ value: "companies", label: "Companies" }, { value: "sectors", label: "Sectors" }], onChange: setLeaderView } : undefined} />;
221
219
  const columns = showLeaders ? LEADER_COLUMNS.filter((column) => column.id !== "scope" && column.id !== "currency")
222
220
  : aggregated ? AGG_COLUMNS.filter((column) => column.id !== "scope" && column.id !== "currency").map((column) => column.id === "label" ? { ...column, label: tab === "agencies" ? "Agency" : "Sector" } : column)
223
- : tab === "events" ? EVENT_COLUMNS : withoutQuietColumns(FEED_COLUMNS, rows, (row, id) => (id === "obligated" ? row.obligatedAmount : row.ceilingAmount) ?? MISSING_VALUE, QUIET_AMOUNTS);
221
+ : tab === "events" ? EVENT_COLUMNS : FEED_COLUMNS;
224
222
  const maxShare = Math.max(0, ...items.map((item) => item.kind === "aggregate" || item.kind === "leader" ? item.row.sharePercent ?? 0 : 0));
225
223
  // A preview's cohorts are the latest of any company, so they never chart as the ticker's.
226
224
  const charted = data?.locked ? [] : series;