@zeniai/client-epic-state 5.0.82 → 5.0.83-betaRR1

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 (142) hide show
  1. package/lib/common/aiCfo/aiCfoSuggestedQuestionsPageContext.d.ts +1 -1
  2. package/lib/entity/aiCfo/aiCfoPayload.d.ts +140 -1
  3. package/lib/entity/aiCfo/aiCfoReducer.d.ts +23 -2
  4. package/lib/entity/aiCfo/aiCfoReducer.js +328 -5
  5. package/lib/entity/aiCfo/aiCfoSelector.d.ts +13 -1
  6. package/lib/entity/aiCfo/aiCfoSelector.js +28 -1
  7. package/lib/entity/aiCfo/aiCfoState.d.ts +225 -4
  8. package/lib/entity/aiCfo/aiCfoState.js +30 -1
  9. package/lib/entity/cardPolicy/cardPolicyPayload.d.ts +277 -0
  10. package/lib/entity/cardPolicy/cardPolicyPayload.js +143 -0
  11. package/lib/entity/cardPolicy/cardPolicyReducer.d.ts +19 -0
  12. package/lib/entity/cardPolicy/cardPolicyReducer.js +175 -0
  13. package/lib/entity/cardPolicy/cardPolicySelector.d.ts +32 -0
  14. package/lib/entity/cardPolicy/cardPolicySelector.js +99 -0
  15. package/lib/entity/cardPolicy/cardPolicyState.d.ts +205 -0
  16. package/lib/entity/cardPolicy/cardPolicyState.js +14 -0
  17. package/lib/entity/cardPolicy/extractPolicyDocumentEpic.d.ts +18 -0
  18. package/lib/entity/cardPolicy/extractPolicyDocumentEpic.js +68 -0
  19. package/lib/entity/cardPolicy/fetchCardPolicyVendorOptionsEpic.d.ts +26 -0
  20. package/lib/entity/cardPolicy/fetchCardPolicyVendorOptionsEpic.js +47 -0
  21. package/lib/entity/cardPolicy/policyDocumentExtractionToRecommendationBridgeEpic.d.ts +25 -0
  22. package/lib/entity/cardPolicy/policyDocumentExtractionToRecommendationBridgeEpic.js +39 -0
  23. package/lib/entity/cardPolicy/policyRecommendationFromUploadEpic.d.ts +23 -0
  24. package/lib/entity/cardPolicy/policyRecommendationFromUploadEpic.js +104 -0
  25. package/lib/entity/jeSchedules/jeSchedulesTypes.d.ts +1 -1
  26. package/lib/entity/monthEndCloseChecks/monthEndCloseChecksState.d.ts +1 -1
  27. package/lib/entity/snackbar/snackbarTypes.d.ts +1 -1
  28. package/lib/entity/snackbar/snackbarTypes.js +3 -0
  29. package/lib/entity/tenant/clearAllEpic.d.ts +6 -2
  30. package/lib/entity/tenant/clearAllEpic.js +8 -0
  31. package/lib/epic.d.ts +11 -1
  32. package/lib/epic.js +11 -1
  33. package/lib/esm/entity/aiCfo/aiCfoReducer.js +328 -5
  34. package/lib/esm/entity/aiCfo/aiCfoSelector.js +26 -1
  35. package/lib/esm/entity/aiCfo/aiCfoState.js +27 -0
  36. package/lib/esm/entity/cardPolicy/cardPolicyPayload.js +130 -0
  37. package/lib/esm/entity/cardPolicy/cardPolicyReducer.js +171 -0
  38. package/lib/esm/entity/cardPolicy/cardPolicySelector.js +75 -0
  39. package/lib/esm/entity/cardPolicy/cardPolicyState.js +9 -0
  40. package/lib/esm/entity/cardPolicy/extractPolicyDocumentEpic.js +64 -0
  41. package/lib/esm/entity/cardPolicy/fetchCardPolicyVendorOptionsEpic.js +43 -0
  42. package/lib/esm/entity/cardPolicy/policyDocumentExtractionToRecommendationBridgeEpic.js +35 -0
  43. package/lib/esm/entity/cardPolicy/policyRecommendationFromUploadEpic.js +100 -0
  44. package/lib/esm/entity/snackbar/snackbarTypes.js +3 -0
  45. package/lib/esm/entity/tenant/clearAllEpic.js +8 -0
  46. package/lib/esm/epic.js +11 -1
  47. package/lib/esm/index.js +27 -8
  48. package/lib/esm/reducer.js +12 -0
  49. package/lib/esm/view/aiCfoView/aiCfoViewReducer.js +6 -3
  50. package/lib/esm/view/aiCfoView/epics/createSessionAndSubmitEpic.js +5 -2
  51. package/lib/esm/view/aiCfoView/epics/createSessionEpic.js +2 -1
  52. package/lib/esm/view/aiCfoView/epics/fetchSuggestedQuestionsEpic.js +12 -2
  53. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/cardPolicyDetailReducer.js +70 -0
  54. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/cardPolicyDetailSelector.js +22 -0
  55. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/cardPolicyDetailState.js +1 -0
  56. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/fetchCardPolicyDetailEpic.js +56 -0
  57. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/updateCardPolicyEpic.js +49 -0
  58. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/archiveCardPolicyEpic.js +42 -0
  59. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/cardPolicyListReducer.js +72 -0
  60. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/cardPolicyListSelector.js +21 -0
  61. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/cardPolicyListState.js +1 -0
  62. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/fetchCardPolicyListEpic.js +56 -0
  63. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/createCardPolicyReducer.js +45 -0
  64. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/createCardPolicySelector.js +39 -0
  65. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/createCardPolicyState.js +1 -0
  66. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/createCardPolicyTemplateEpic.js +53 -0
  67. package/lib/esm/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/fetchCardPolicyMccCategoriesEpic.js +25 -0
  68. package/lib/esm/view/spendManagement/chargeCards/chargeCardList/chargeCardListSelector.js +25 -0
  69. package/lib/esm/view/spendManagement/chargeCards/issueChargeCard/aiCardCreationFormDraftTypes.js +1 -0
  70. package/lib/esm/view/spendManagement/chargeCards/issueChargeCard/applyAiCardCreationFormDraftUpdate.js +20 -0
  71. package/lib/esm/view/spendManagement/chargeCards/issueChargeCard/buildAiCardCreationFormDraftSeed.js +62 -0
  72. package/lib/esm/view/spendManagement/chargeCards/issueChargeCard/deriveAiCardRowsFromTeams.js +47 -0
  73. package/lib/esm/view/spendManagement/chargeCards/issueChargeCard/issueChargeCardEpic.js +2 -2
  74. package/lib/esm/view/spendManagement/chargeCards/issueChargeCard/issueChargeCardReducer.js +48 -4
  75. package/lib/esm/view/spendManagement/chargeCards/issueChargeCard/issueChargeCardSelector.js +61 -0
  76. package/lib/esm/view/spendManagement/chargeCards/issueChargeCard/toIssueChargeCardLocalDataFromDraft.js +69 -0
  77. package/lib/index.d.ts +26 -8
  78. package/lib/index.js +141 -13
  79. package/lib/reducer.d.ts +12 -0
  80. package/lib/reducer.js +12 -0
  81. package/lib/view/aiCfoView/aiCfoViewReducer.d.ts +11 -2
  82. package/lib/view/aiCfoView/aiCfoViewReducer.js +6 -3
  83. package/lib/view/aiCfoView/epics/createSessionAndSubmitEpic.js +5 -2
  84. package/lib/view/aiCfoView/epics/createSessionEpic.js +2 -1
  85. package/lib/view/aiCfoView/epics/fetchSuggestedQuestionsEpic.d.ts +8 -1
  86. package/lib/view/aiCfoView/epics/fetchSuggestedQuestionsEpic.js +12 -2
  87. package/lib/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.d.ts +1 -1
  88. package/lib/view/expenseAutomationView/types/reconciliationViewState.d.ts +1 -1
  89. package/lib/view/people/peopleTypes.d.ts +1 -1
  90. package/lib/view/scheduleView/scheduleListView/scheduleListTypes.d.ts +1 -1
  91. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/cardPolicyDetailReducer.d.ts +14 -0
  92. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/cardPolicyDetailReducer.js +74 -0
  93. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/cardPolicyDetailSelector.d.ts +21 -0
  94. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/cardPolicyDetailSelector.js +28 -0
  95. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/cardPolicyDetailState.d.ts +25 -0
  96. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/cardPolicyDetailState.js +2 -0
  97. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/fetchCardPolicyDetailEpic.d.ts +19 -0
  98. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/fetchCardPolicyDetailEpic.js +60 -0
  99. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/updateCardPolicyEpic.d.ts +18 -0
  100. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyDetail/updateCardPolicyEpic.js +53 -0
  101. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/archiveCardPolicyEpic.d.ts +16 -0
  102. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/archiveCardPolicyEpic.js +46 -0
  103. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/cardPolicyListReducer.d.ts +15 -0
  104. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/cardPolicyListReducer.js +76 -0
  105. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/cardPolicyListSelector.d.ts +21 -0
  106. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/cardPolicyListSelector.js +27 -0
  107. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/cardPolicyListState.d.ts +19 -0
  108. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/cardPolicyListState.js +2 -0
  109. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/fetchCardPolicyListEpic.d.ts +19 -0
  110. package/lib/view/spendManagement/chargeCards/cardPolicy/cardPolicyList/fetchCardPolicyListEpic.js +60 -0
  111. package/lib/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/createCardPolicyReducer.d.ts +13 -0
  112. package/lib/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/createCardPolicyReducer.js +49 -0
  113. package/lib/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/createCardPolicySelector.d.ts +32 -0
  114. package/lib/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/createCardPolicySelector.js +46 -0
  115. package/lib/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/createCardPolicyState.d.ts +45 -0
  116. package/lib/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/createCardPolicyState.js +2 -0
  117. package/lib/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/createCardPolicyTemplateEpic.d.ts +25 -0
  118. package/lib/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/createCardPolicyTemplateEpic.js +57 -0
  119. package/lib/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/fetchCardPolicyMccCategoriesEpic.d.ts +15 -0
  120. package/lib/view/spendManagement/chargeCards/cardPolicy/createCardPolicy/fetchCardPolicyMccCategoriesEpic.js +29 -0
  121. package/lib/view/spendManagement/chargeCards/chargeCardList/chargeCardList.d.ts +1 -1
  122. package/lib/view/spendManagement/chargeCards/chargeCardList/chargeCardListSelector.d.ts +14 -0
  123. package/lib/view/spendManagement/chargeCards/chargeCardList/chargeCardListSelector.js +27 -1
  124. package/lib/view/spendManagement/chargeCards/issueChargeCard/aiCardCreationFormDraftTypes.d.ts +79 -0
  125. package/lib/view/spendManagement/chargeCards/issueChargeCard/aiCardCreationFormDraftTypes.js +2 -0
  126. package/lib/view/spendManagement/chargeCards/issueChargeCard/applyAiCardCreationFormDraftUpdate.d.ts +6 -0
  127. package/lib/view/spendManagement/chargeCards/issueChargeCard/applyAiCardCreationFormDraftUpdate.js +24 -0
  128. package/lib/view/spendManagement/chargeCards/issueChargeCard/buildAiCardCreationFormDraftSeed.d.ts +25 -0
  129. package/lib/view/spendManagement/chargeCards/issueChargeCard/buildAiCardCreationFormDraftSeed.js +66 -0
  130. package/lib/view/spendManagement/chargeCards/issueChargeCard/deriveAiCardRowsFromTeams.d.ts +26 -0
  131. package/lib/view/spendManagement/chargeCards/issueChargeCard/deriveAiCardRowsFromTeams.js +51 -0
  132. package/lib/view/spendManagement/chargeCards/issueChargeCard/issueChargeCardEpic.d.ts +2 -2
  133. package/lib/view/spendManagement/chargeCards/issueChargeCard/issueChargeCardEpic.js +1 -1
  134. package/lib/view/spendManagement/chargeCards/issueChargeCard/issueChargeCardReducer.d.ts +12 -2
  135. package/lib/view/spendManagement/chargeCards/issueChargeCard/issueChargeCardReducer.js +49 -5
  136. package/lib/view/spendManagement/chargeCards/issueChargeCard/issueChargeCardSelector.d.ts +42 -0
  137. package/lib/view/spendManagement/chargeCards/issueChargeCard/issueChargeCardSelector.js +68 -1
  138. package/lib/view/spendManagement/chargeCards/issueChargeCard/issueChargeCardState.d.ts +18 -0
  139. package/lib/view/spendManagement/chargeCards/issueChargeCard/toIssueChargeCardLocalDataFromDraft.d.ts +11 -0
  140. package/lib/view/spendManagement/chargeCards/issueChargeCard/toIssueChargeCardLocalDataFromDraft.js +73 -0
  141. package/lib/view/taskManager/taskListView/taskListReducer.d.ts +1 -1
  142. package/package.json +1 -1
@@ -1,9 +1,10 @@
1
1
  import { createSlice } from '@reduxjs/toolkit';
2
2
  import { date as zeniDate } from '../../zeniDayJS';
3
- import { ALL_AI_CFO_ANSWER_RESPONSE_TYPES, toAiCfoAnswerResponseType, toAiCfoAnswerResponseTypeStrict, toAiCfoAnswerStateType, toAiCfoVisualizationTypeStrict, toMessageSender, toMessageType, toYFormatScaleStrict, toYFormatTypeStrict, toYFormatUnitStrict, } from './aiCfoState';
3
+ import { ALL_AI_CFO_ANSWER_RESPONSE_TYPES, CARDS_CREATION_DEFAULT_CARD_OPTION_ID, toAiCfoAnswerResponseType, toAiCfoAnswerResponseTypeStrict, toAiCfoAnswerStateType, toAiCfoVisualizationTypeStrict, toInteractiveFormTypeStrict, toMessageSender, toMessageType, toYFormatScaleStrict, toYFormatTypeStrict, toYFormatUnitStrict, } from './aiCfoState';
4
4
  export const initialAiCfoState = {
5
5
  aiCfoByChatSessionId: {},
6
6
  partialQuestionAnswers: {},
7
+ syntheticAnswersByChatSessionId: {},
7
8
  };
8
9
  // Utility: Merge two arrays of Q&A pairs, combining responses for the same question
9
10
  function mergeQuestionAnswerPairs(existing, newQAs) {
@@ -135,9 +136,216 @@ export const toAiCfoVisualization = (visualization) => {
135
136
  if (visualization.type == null || visualization.data == null) {
136
137
  return undefined;
137
138
  }
139
+ // Reject unknown viz types instead of silently defaulting to `table`.
140
+ // The previous `?? 'table'` fallback funneled any non-strict-union
141
+ // payload into `toAiCfoVisualizationData`, which is the table/chart
142
+ // decoder and dereferences `data.values.map(...)`. Interactive-form
143
+ // payloads (e.g. when the BE ships `type: <new_form_kind>` we don't
144
+ // know about yet) carry no `values`, so that path threw during answer
145
+ // upsert and broke rendering for the whole Q/A. Returning `undefined`
146
+ // matches the existing "missing type / data" guard above — callers
147
+ // already handle a no-visualization answer.
148
+ const normalizedType = toAiCfoVisualizationTypeStrict(visualization.type);
149
+ if (normalizedType == null) {
150
+ return undefined;
151
+ }
152
+ return {
153
+ type: normalizedType,
154
+ data: normalizedType === 'interactive_form'
155
+ ? toInteractiveFormVisualization(visualization.data)
156
+ : toAiCfoVisualizationData(visualization.data),
157
+ };
158
+ };
159
+ const toInteractiveFormVisualization = (data) => {
160
+ // When `form_type` is missing / mistyped, fall back to a payload-shape
161
+ // heuristic instead of blindly defaulting to `cards_creation`. A
162
+ // `card_policy` payload always carries `mode: 'auto' | 'guided' |
163
+ // 'upload'` (see `CardPolicyInitialDataPayload`); a `cards_creation`
164
+ // payload carries `suggested_cards` and never that exact `mode` set.
165
+ // Without this, a card-policy answer with a malformed `form_type`
166
+ // would be decoded as cards_creation, surfacing the wrong interactive
167
+ // form (and wrong submit path) in the UI.
168
+ const formType = toInteractiveFormTypeStrict(data.form_type) ??
169
+ inferInteractiveFormTypeFromPayload(data.payload);
170
+ if (formType === 'card_policy') {
171
+ return {
172
+ formType: 'card_policy',
173
+ payload: toCardPolicyInitialData(data.payload),
174
+ };
175
+ }
176
+ return {
177
+ formType: 'cards_creation',
178
+ payload: toCardsCreationInitialData(data.payload),
179
+ };
180
+ };
181
+ const inferInteractiveFormTypeFromPayload = (payload) => {
182
+ if (payload != null && typeof payload === 'object' && 'mode' in payload) {
183
+ const mode = payload.mode;
184
+ if (mode === 'auto' || mode === 'guided' || mode === 'upload') {
185
+ return 'card_policy';
186
+ }
187
+ }
188
+ return 'cards_creation';
189
+ };
190
+ /**
191
+ * Decode the unified `cards_creation` interactive-form payload into the FE
192
+ * state shape. Both `review` and `create` modes ship the same envelope
193
+ * (`{mode, suggested_cards[]}`); the only thing that varies is how the
194
+ * common derivations are exposed:
195
+ *
196
+ * - `review` (2-step): `is_suggested: true` rows -> `teamRows`; the full
197
+ * universe -> `cardNameOptions` (step-2 swap + step-1 "Add something
198
+ * else" search).
199
+ * - `create` (1-step): `is_suggested: true` rows -> `cardRows` pre-seeded
200
+ * for the step-2 editable table (with `cardOptionId` defaulted to
201
+ * `'virtual'`); the full universe -> `cardNameOptions` (step-2 swap).
202
+ *
203
+ * `cardOptions` (physical / virtual / subscription) is intentionally not
204
+ * derived here — the wire never carries it. The component prop is fed
205
+ * from `AI_CARD_CREATION_VIRTUAL_ONLY_CARD_OPTIONS` at render time. The
206
+ * state field is preserved as `[]` for backward compatibility with
207
+ * consumers that still narrow on it.
208
+ */
209
+ const toCardsCreationInitialData = (payload) => {
210
+ const suggestedCards = payload.suggested_cards ?? [];
211
+ const ordered = [...suggestedCards].sort((a, b) => KIND_RANK[a.card_type] - KIND_RANK[b.card_type]);
212
+ const withUniqueIds = withSynthesizedIds(ordered);
213
+ const suggestedOnly = withUniqueIds.filter(({ card }) => card.is_suggested);
214
+ const cardNameOptions = withUniqueIds.map(({ card, uniqueId }) => ({
215
+ id: uniqueId,
216
+ kind: toCardKind(card.card_type),
217
+ label: card.card_name,
218
+ }));
219
+ const suggestedOwnerUserIdByTeamId = Object.fromEntries(suggestedOnly.map(({ card, uniqueId }) => [
220
+ uniqueId,
221
+ normalizeOwnerId(card.owner_id),
222
+ ]));
223
+ const common = {
224
+ cardNameOptions,
225
+ cardOptions: [],
226
+ suggestedOwnerUserIdByTeamId,
227
+ };
228
+ if (payload.mode === 'create') {
229
+ return {
230
+ ...common,
231
+ mode: 'create',
232
+ cardRows: suggestedOnly.map(({ card, uniqueId }) => ({
233
+ cardKind: toCardKind(card.card_type),
234
+ cardOptionId: CARDS_CREATION_DEFAULT_CARD_OPTION_ID,
235
+ id: uniqueId,
236
+ label: card.card_name,
237
+ recommendedLimit: card.credit_limit > 0 ? card.credit_limit : undefined,
238
+ suggestedOwnerUserId: normalizeOwnerId(card.owner_id),
239
+ })),
240
+ };
241
+ }
138
242
  return {
139
- type: toAiCfoVisualizationTypeStrict(visualization.type) ?? 'table',
140
- data: toAiCfoVisualizationData(visualization.data),
243
+ ...common,
244
+ mode: 'review',
245
+ teamRows: suggestedOnly.map(({ card, uniqueId }) => ({
246
+ avgMonthlySpend: CURRENCY_FORMATTER.format(card.avg_spend),
247
+ cardKind: toCardKind(card.card_type),
248
+ id: uniqueId,
249
+ label: card.card_name,
250
+ recommendedLimit: CURRENCY_FORMATTER.format(card.credit_limit),
251
+ recommendedLimitCadence: 'Monthly',
252
+ })),
253
+ };
254
+ };
255
+ const CURRENCY_FORMATTER = new Intl.NumberFormat('en-US', {
256
+ style: 'currency',
257
+ currency: 'USD',
258
+ maximumFractionDigits: 0,
259
+ });
260
+ /**
261
+ * Normalize the controller's `owner_id` into `string | undefined`. The
262
+ * BE may emit either `null` or `""` to signal "no owner picked"; both
263
+ * collapse to `undefined` so downstream resolvers don't try to look up
264
+ * a user with an empty id.
265
+ */
266
+ const normalizeOwnerId = (ownerId) => ownerId != null && ownerId !== '' ? ownerId : undefined;
267
+ const KIND_RANK = {
268
+ vendor: 0,
269
+ category: 1,
270
+ department: 2,
271
+ };
272
+ const toCardKind = (cardType) => {
273
+ if (cardType === 'department') {
274
+ return 'class';
275
+ }
276
+ if (cardType === 'category') {
277
+ return 'category';
278
+ }
279
+ return 'vendor';
280
+ };
281
+ /**
282
+ * Stamp each suggested card with a stable unique id derived from its
283
+ * `card_name_id`. If two cards in the same payload share the same
284
+ * `card_name_id` (which happens in the current sample payload where
285
+ * `card_name_id` is the literal `"vendor_uuid"`), fall back to a
286
+ * synthesized id `${kind}__${card_name_id}__${index}` so RHF row keying
287
+ * stays unique.
288
+ */
289
+ const withSynthesizedIds = (cards) => {
290
+ const seen = new Set();
291
+ return cards.map((card, index) => {
292
+ const preferred = card.card_name_id;
293
+ if (preferred != null && preferred !== '' && !seen.has(preferred)) {
294
+ seen.add(preferred);
295
+ return { card, uniqueId: preferred };
296
+ }
297
+ const synthesized = `${card.card_type}__${preferred ?? 'unknown'}__${index}`;
298
+ seen.add(synthesized);
299
+ return { card, uniqueId: synthesized };
300
+ });
301
+ };
302
+ const toCardPolicyDraftPolicy = (payload, index) => ({
303
+ id: `draft-${index}`,
304
+ name: payload.name,
305
+ description: payload.description ?? '',
306
+ mode: payload.mode,
307
+ allowedEntity: {
308
+ categoryCodes: payload.allowed_entity?.category_codes ?? [],
309
+ merchantNames: payload.allowed_entity?.merchant_names ?? [],
310
+ },
311
+ blockedEntity: {
312
+ categoryCodes: payload.blocked_entity?.category_codes ?? [],
313
+ merchantNames: payload.blocked_entity?.merchant_names ?? [],
314
+ },
315
+ applyToCards: payload.apply_to_cards ?? [],
316
+ requiredReceiptThreshold: payload.required_receipt_threshold ?? 0,
317
+ spendLimits: {
318
+ transaction: payload.spend_limits?.transaction ?? 0,
319
+ },
320
+ });
321
+ const toCardPolicyStep5Review = (payload) => ({
322
+ draftPolicies: (payload.draft_policies ?? []).map(toCardPolicyDraftPolicy),
323
+ groupingSource: payload.grouping_source ?? 'none',
324
+ prompt: payload.prompt ?? '',
325
+ });
326
+ const toCardPolicyWizardPlan = (payload) => ({
327
+ step5Review: toCardPolicyStep5Review(payload.step_5_review),
328
+ });
329
+ const toCardPolicyUploadSource = (payload) => ({
330
+ confidenceScore: payload.confidence_score,
331
+ fileName: payload.file_name,
332
+ lowConfidenceFields: payload.low_confidence_fields ?? [],
333
+ });
334
+ const toCardPolicyInitialData = (payload) => {
335
+ if (payload.mode === 'upload') {
336
+ return {
337
+ policyKind: 'upload',
338
+ wizardPlan: payload.wizard_plan != null
339
+ ? toCardPolicyWizardPlan(payload.wizard_plan)
340
+ : undefined,
341
+ source: payload.source != null
342
+ ? toCardPolicyUploadSource(payload.source)
343
+ : undefined,
344
+ };
345
+ }
346
+ return {
347
+ policyKind: payload.mode,
348
+ wizardPlan: toCardPolicyWizardPlan(payload.wizard_plan),
141
349
  };
142
350
  };
143
351
  const toAiCfoVisualizationData = (data) => {
@@ -453,10 +661,118 @@ const aiCfo = createSlice({
453
661
  session.questionAnswers.push(qa);
454
662
  }
455
663
  },
664
+ /**
665
+ * Patch the `card_policy` interactive-form payload for a specific
666
+ * answer in a chat session to merge in the wizard plan + upload
667
+ * source metadata returned by
668
+ * `POST /cards/1.0/ai-cfo/policy-recommendation-from-upload`.
669
+ *
670
+ * Dispatched by the recommendation epic after a successful response;
671
+ * the wizard re-renders Steps 2 + 3 of the upload variant once the
672
+ * payload becomes a populated `CardPolicyInitialData` with
673
+ * `policyKind: "upload"` + `wizardPlan` + `source`.
674
+ *
675
+ * No-op when the target answer / chat session / form payload is
676
+ * missing or isn't an upload-mode card-policy interactive form —
677
+ * the bridge epic is best-effort and silently drops in edge cases
678
+ * (e.g. the user closed the chat before recommendation returned).
679
+ */
680
+ updateAiCfoAnswerCardPolicyWizardPlan(draft, action) {
681
+ const { answerId, chatSessionId, source, wizardPlan } = action.payload;
682
+ const session = draft.aiCfoByChatSessionId[chatSessionId];
683
+ if (session == null) {
684
+ return;
685
+ }
686
+ const qa = session.questionAnswers.find((entry) => entry.questionAnswerId === answerId);
687
+ if (qa == null) {
688
+ return;
689
+ }
690
+ for (const response of Object.values(qa.responses)) {
691
+ const visualization = response?.content.visualization;
692
+ if (visualization == null ||
693
+ visualization.type !== 'interactive_form') {
694
+ continue;
695
+ }
696
+ const data = visualization.data;
697
+ if (data.formType !== 'card_policy' ||
698
+ data.payload.policyKind !== 'upload') {
699
+ continue;
700
+ }
701
+ data.payload = {
702
+ ...data.payload,
703
+ wizardPlan,
704
+ source: source ?? data.payload.source,
705
+ };
706
+ }
707
+ },
708
+ /**
709
+ * Append a client-synthesized answer bubble to a chat session. Used by
710
+ * the AI CFO cards/policy create flow to render a "Creating…" placeholder
711
+ * in the drawer while the underlying mutation runs.
712
+ *
713
+ * The caller is responsible for generating a stable `id` (so the same
714
+ * bubble can later be updated in place via `updateSyntheticAiCfoAnswer`
715
+ * once the mutation completes) and a `createdAt` timestamp so the
716
+ * renderer can interleave synthetic bubbles with streamed Q&A pairs in
717
+ * chronological order.
718
+ */
719
+ appendSyntheticAiCfoAnswer(draft, action) {
720
+ const { chatSessionId, id, kind, createdAt, entityIds, sourceQuestionAnswerId, } = action.payload;
721
+ if (draft.syntheticAnswersByChatSessionId[chatSessionId] == null) {
722
+ draft.syntheticAnswersByChatSessionId[chatSessionId] = [];
723
+ }
724
+ draft.syntheticAnswersByChatSessionId[chatSessionId].push({
725
+ id,
726
+ kind,
727
+ entityIds: entityIds ?? [],
728
+ createdAt,
729
+ sourceQuestionAnswerId,
730
+ });
731
+ },
732
+ /**
733
+ * Update an existing synthetic answer bubble in place. Typically called
734
+ * when the create mutation completes: the screen transitions the bubble
735
+ * from `creating_*` to `created_*` and populates `entityIds` with the
736
+ * newly created cards / policy templates.
737
+ *
738
+ * No-op when the target bubble is missing (e.g. the session was cleared
739
+ * before the mutation returned).
740
+ */
741
+ updateSyntheticAiCfoAnswer(draft, action) {
742
+ const { chatSessionId, id, kind, entityIds } = action.payload;
743
+ const list = draft.syntheticAnswersByChatSessionId[chatSessionId];
744
+ if (list == null) {
745
+ return;
746
+ }
747
+ const entry = list.find((item) => item.id === id);
748
+ if (entry == null) {
749
+ return;
750
+ }
751
+ entry.kind = kind;
752
+ if (entityIds != null) {
753
+ entry.entityIds = entityIds;
754
+ }
755
+ },
756
+ /**
757
+ * Remove a single synthetic answer bubble (e.g. when the user manually
758
+ * dismisses it or the mutation errors out and we want to fall back to
759
+ * an inline error snackbar).
760
+ */
761
+ removeSyntheticAiCfoAnswer(draft, action) {
762
+ const { chatSessionId, id } = action.payload;
763
+ const list = draft.syntheticAnswersByChatSessionId[chatSessionId];
764
+ if (list == null) {
765
+ return;
766
+ }
767
+ draft.syntheticAnswersByChatSessionId[chatSessionId] = list.filter((item) => item.id !== id);
768
+ },
769
+ clearSyntheticAiCfoAnswers(draft, action) {
770
+ delete draft.syntheticAnswersByChatSessionId[action.payload];
771
+ },
456
772
  clearSession(draft, action) {
457
773
  const sessionId = action.payload;
458
774
  delete draft.aiCfoByChatSessionId[sessionId];
459
- // Clear partial Q&A if it belongs to the cleared session
775
+ delete draft.syntheticAnswersByChatSessionId[sessionId];
460
776
  if (draft.partialQuestionAnswers?.[sessionId] != null) {
461
777
  draft.partialQuestionAnswers[sessionId] = undefined;
462
778
  }
@@ -464,6 +780,7 @@ const aiCfo = createSlice({
464
780
  clearAiCfo(draft) {
465
781
  draft.aiCfoByChatSessionId = {};
466
782
  draft.partialQuestionAnswers = {};
783
+ draft.syntheticAnswersByChatSessionId = {};
467
784
  },
468
785
  deleteQuestion(draft, action) {
469
786
  const { chatSessionId, questionAnswerId } = action.payload;
@@ -476,6 +793,12 @@ const aiCfo = createSlice({
476
793
  if (idx !== -1) {
477
794
  session.questionAnswers.splice(idx, 1);
478
795
  }
796
+ // Drop synthetic bubbles whose sourceQuestionAnswerId is the deleted Q/A; otherwise "Creating…" / "Created" tiles outlive their Q/A.
797
+ const syntheticAnswers = draft.syntheticAnswersByChatSessionId[chatSessionId];
798
+ if (syntheticAnswers != null) {
799
+ draft.syntheticAnswersByChatSessionId[chatSessionId] =
800
+ syntheticAnswers.filter((answer) => answer.sourceQuestionAnswerId !== questionAnswerId);
801
+ }
479
802
  },
480
803
  },
481
804
  });
@@ -488,5 +811,5 @@ const toChatSession = (chatSessionPayload) => {
488
811
  createdAt: zeniDate(created_at),
489
812
  };
490
813
  };
491
- export const { setNewSession, clearSession, setSessions, setChatHistory, upsertAnswerPayload, upsertOrAddQuestionAnswerPayload, addQuestionPayload, clearAiCfo, deleteQuestion, } = aiCfo.actions;
814
+ export const { setNewSession, clearSession, setSessions, setChatHistory, upsertAnswerPayload, upsertOrAddQuestionAnswerPayload, addQuestionPayload, clearAiCfo, deleteQuestion, updateAiCfoAnswerCardPolicyWizardPlan, appendSyntheticAiCfoAnswer, updateSyntheticAiCfoAnswer, removeSyntheticAiCfoAnswer, clearSyntheticAiCfoAnswers, } = aiCfo.actions;
492
815
  export default aiCfo.reducer;
@@ -32,5 +32,30 @@ export function getAiCfoSelectorView(state) {
32
32
  : [],
33
33
  }))
34
34
  .sort((a, b) => b.chatSession.createdAt.valueOf() - a.chatSession.createdAt.valueOf());
35
- return { allSessionsWithOrderedQuestionAnswers };
35
+ return {
36
+ allSessionsWithOrderedQuestionAnswers,
37
+ syntheticAnswersByChatSessionId: state.syntheticAnswersByChatSessionId ?? {},
38
+ };
39
+ }
40
+ export function getSyntheticAiCfoAnswersForChatSession(state, chatSessionId) {
41
+ const arr = state.syntheticAnswersByChatSessionId?.[chatSessionId] ?? [];
42
+ return arr
43
+ .slice()
44
+ .sort((a, b) => a.createdAt.valueOf() - b.createdAt.valueOf());
45
+ }
46
+ /**
47
+ * Look up the synthetic answer bubble (if any) whose source AI CFO Q/A
48
+ * is `questionAnswerId`. Used by the in-place renderer to swap a Q/A's
49
+ * answer bubble with the "Creating…" / "Created" tile.
50
+ *
51
+ * Returns `undefined` when no synthetic bubble has been dispatched for
52
+ * the answer yet (i.e. the user hasn't submitted the interactive form),
53
+ * or when the chat session has no synthetic entries at all.
54
+ */
55
+ export function getSyntheticAiCfoAnswerByQuestionAnswerId(state, chatSessionId, questionAnswerId) {
56
+ const arr = state.syntheticAnswersByChatSessionId?.[chatSessionId];
57
+ if (arr == null) {
58
+ return undefined;
59
+ }
60
+ return arr.find((answer) => answer.sourceQuestionAnswerId === questionAnswerId);
36
61
  }
@@ -7,7 +7,14 @@ export const ALL_AI_CFO_CHARTS_TYPES = [
7
7
  export const ALL_AI_CFO_VISUALIZATION_TYPES = [
8
8
  ...ALL_AI_CFO_CHARTS_TYPES,
9
9
  'table',
10
+ 'interactive_form',
10
11
  ];
12
+ export const ALL_INTERACTIVE_FORM_TYPES = [
13
+ 'cards_creation',
14
+ 'card_policy',
15
+ ];
16
+ export const toInteractiveFormType = (v) => stringToUnion(v, ALL_INTERACTIVE_FORM_TYPES);
17
+ export const toInteractiveFormTypeStrict = (v) => stringToUnionStrict(v, ALL_INTERACTIVE_FORM_TYPES);
11
18
  export const toAiCfoVisualizationType = (v) => stringToUnion(v, ALL_AI_CFO_VISUALIZATION_TYPES);
12
19
  export const toAiCfoVisualizationTypeStrict = (v) => stringToUnionStrict(v, ALL_AI_CFO_VISUALIZATION_TYPES);
13
20
  export const toAiCfoChartType = (v) => stringToUnion(v, ALL_AI_CFO_CHARTS_TYPES);
@@ -52,9 +59,29 @@ export const toAiCfoAnswerStateType = (v) => stringToUnion(v, ALL_AI_CFO_ANSWER_
52
59
  export const toAiCfoAnswerResponseType = (v) => stringToUnion(v, ALL_AI_CFO_ANSWER_RESPONSE_TYPES);
53
60
  export const toAiCfoAnswerStateTypeStrict = (v) => stringToUnionStrict(v, ALL_AI_CFO_ANSWER_STATE_TYPES);
54
61
  export const toAiCfoAnswerResponseTypeStrict = (v) => stringToUnionStrict(v, ALL_AI_CFO_ANSWER_RESPONSE_TYPES);
62
+ /**
63
+ * Default `cardOptionId` (physical / virtual / subscription) assigned to
64
+ * every seeded card row. The AI Card Creation flow currently issues virtual
65
+ * credit cards only — this constant is kept in sync with
66
+ * `AI_CARD_CREATION_VIRTUAL_ONLY_CARD_OPTIONS` in `zeni-web-app-ui`.
67
+ */
68
+ export const CARDS_CREATION_DEFAULT_CARD_OPTION_ID = 'virtual';
55
69
  const ALL_MESSAGE_SENDERS = ['user', 'agent'];
56
70
  const ALL_MESSAGE_TYPES = ['plain_text', 'json'];
57
71
  export const toMessageSender = (v) => stringToUnion(v, ALL_MESSAGE_SENDERS);
58
72
  export const toMessageType = (v) => stringToUnion(v, ALL_MESSAGE_TYPES);
59
73
  export const toMessageSenderStrict = (v) => stringToUnionStrict(v, ALL_MESSAGE_SENDERS);
60
74
  export const toMessageTypeStrict = (v) => stringToUnionStrict(v, ALL_MESSAGE_TYPES);
75
+ /**
76
+ * Discriminator for client-synthesized AI CFO answer bubbles. These are not
77
+ * Q/A pairs streamed from the backend — they are pushed locally by the AI
78
+ * CFO flow when it kicks off a cards or policy create from an interactive
79
+ * form, so the drawer can render a "Creating…" placeholder and later a
80
+ * "Created" success bubble while the corresponding mutation epic runs.
81
+ */
82
+ export const ALL_SYNTHETIC_AI_CFO_ANSWER_KINDS = [
83
+ 'creating_cards',
84
+ 'creating_policy',
85
+ 'created_cards',
86
+ 'created_policy',
87
+ ];
@@ -0,0 +1,130 @@
1
+ import { date } from '../../zeniDayJS';
2
+ import { toCardPolicyTemplateMode, toCardPolicyTemplateStatus, } from './cardPolicyState';
3
+ export const toMccCategory = (payload) => ({
4
+ count: payload.count,
5
+ mccCodes: payload.mcc_codes ?? [],
6
+ name: payload.name,
7
+ });
8
+ export const toCardPolicyVendorSearchOption = (payload) => ({
9
+ vendorId: payload.vendor_id,
10
+ name: payload.vendor_name,
11
+ });
12
+ export const toCardPolicyStats = (payload) => ({
13
+ activePolicies: payload.active_policies,
14
+ totalCards: payload.total_cards,
15
+ totalTemplates: payload.total_templates,
16
+ });
17
+ export const toCardPolicyTemplateList = (data) => (data.templates ?? []).map((row) => toCardPolicyTemplate(row.data.template));
18
+ const toCardPolicyTemplateEntityList = (payload) => ({
19
+ categoryCodes: payload.category_codes ?? [],
20
+ merchantNames: payload.merchant_names ?? [],
21
+ });
22
+ export const toCardPolicyTemplate = (payload) => ({
23
+ allowedEntity: toCardPolicyTemplateEntityList(payload.allowed_entity),
24
+ appliedCards: payload.applied_cards ?? [],
25
+ blockedEntity: toCardPolicyTemplateEntityList(payload.blocked_entity),
26
+ cardsCount: payload.cards_count,
27
+ categoryRestrictions: payload.category_restrictions ?? [],
28
+ createdAt: date(payload.created_at),
29
+ createdBy: payload.created_by,
30
+ description: payload.description,
31
+ mode: toCardPolicyTemplateMode(payload.mode),
32
+ name: payload.name,
33
+ requiredReceiptThreshold: payload.required_receipt_threshold,
34
+ spendLimits: {
35
+ transaction: payload.spend_limits.transaction,
36
+ },
37
+ status: toCardPolicyTemplateStatus(payload.status),
38
+ templateId: payload.template_id,
39
+ tenantId: payload.tenant_id,
40
+ updatedAt: date(payload.updated_at),
41
+ });
42
+ /**
43
+ * Re-shape a single camelCase create request into the snake_case wire
44
+ * body. Used by the bulk-create mapper to build each entry of the
45
+ * `templates` array, and directly by the update epic (PUT) since the
46
+ * update endpoint still consumes a single object.
47
+ */
48
+ export const toCreateCardPolicyTemplateRequestBody = (request) => ({
49
+ allowed_entity: {
50
+ category_codes: request.allowedEntity.categoryCodes,
51
+ merchant_names: request.allowedEntity.merchantNames,
52
+ },
53
+ apply_to_cards: request.applyToCards,
54
+ blocked_entity: {
55
+ category_codes: request.blockedEntity.categoryCodes,
56
+ merchant_names: request.blockedEntity.merchantNames,
57
+ },
58
+ description: request.description,
59
+ mode: request.mode ?? 'strict',
60
+ name: request.name,
61
+ required_receipt_threshold: request.requiredReceiptThreshold,
62
+ spend_limits: {
63
+ transaction: request.spendLimits.transaction,
64
+ },
65
+ });
66
+ /**
67
+ * Re-shape a bulk create request into the snake_case wire body for
68
+ * `POST /cards/1.0/policy-templates`. Maps each entry through
69
+ * `toCreateCardPolicyTemplateRequestBody` and only emits
70
+ * `source_chat_session_id` when the camelCase counterpart is defined,
71
+ * so manual-create callers don't ship a stray `undefined` over the wire.
72
+ */
73
+ export const toCreateCardPolicyTemplatesRequestBody = (request) => {
74
+ const body = {
75
+ templates: request.templates.map(toCreateCardPolicyTemplateRequestBody),
76
+ };
77
+ if (request.sourceChatSessionId != null) {
78
+ body.source_chat_session_id = request.sourceChatSessionId;
79
+ }
80
+ return body;
81
+ };
82
+ /**
83
+ * Map a single bulk-response error payload to its camelCased view shape.
84
+ * Defensive against missing optional fields (see `BulkCreateCardPolicyTemplateErrorPayload`
85
+ * docstring — the BE contract isn't fully locked yet).
86
+ */
87
+ export const toBulkCreateCardPolicyTemplateError = (payload) => ({
88
+ message: payload.message,
89
+ code: payload.code,
90
+ index: payload.index,
91
+ name: payload.name,
92
+ });
93
+ // Update body uses the exact same wire shape as create — the PUT
94
+ // endpoint is a full replace and was not affected by the bulk migration.
95
+ export const toUpdateCardPolicyTemplateRequestBody = toCreateCardPolicyTemplateRequestBody;
96
+ /**
97
+ * Seed an edit-form draft (`CreateCardPolicyTemplateRequest`) from an
98
+ * existing camelCased `CardPolicyTemplate`. Used by the detail-fetch
99
+ * epic so the edit page can render with the saved values pre-populated.
100
+ */
101
+ export const toCardPolicyEditFormDraft = (template) => ({
102
+ allowedEntity: {
103
+ categoryCodes: [...template.allowedEntity.categoryCodes],
104
+ merchantNames: [...template.allowedEntity.merchantNames],
105
+ },
106
+ applyToCards: [...template.appliedCards],
107
+ blockedEntity: {
108
+ categoryCodes: [...template.blockedEntity.categoryCodes],
109
+ merchantNames: [...template.blockedEntity.merchantNames],
110
+ },
111
+ description: template.description,
112
+ mode: template.mode,
113
+ name: template.name,
114
+ requiredReceiptThreshold: template.requiredReceiptThreshold,
115
+ spendLimits: { transaction: template.spendLimits.transaction },
116
+ });
117
+ export const toExtractedCardPolicyRules = (payload) => ({
118
+ allowedEntity: {
119
+ categoryCodes: payload.allowed_entity?.category_codes ?? [],
120
+ merchantNames: payload.allowed_entity?.merchant_names ?? [],
121
+ },
122
+ blockedEntity: {
123
+ categoryCodes: payload.blocked_entity?.category_codes ?? [],
124
+ merchantNames: payload.blocked_entity?.merchant_names ?? [],
125
+ },
126
+ confidenceScore: payload.confidence_score,
127
+ policyName: payload.policy_name,
128
+ requiredReceiptThreshold: payload.required_receipt_threshold,
129
+ transactionLimit: payload.transaction_limit,
130
+ });