@zeniai/client-epic-state 5.0.80 → 5.0.81-betaAD01

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 (196) hide show
  1. package/lib/commonStateTypes/cacheOverrideFetchReducer.d.ts +17 -0
  2. package/lib/commonStateTypes/cacheOverrideFetchReducer.js +20 -0
  3. package/lib/commonStateTypes/filterPrimitives.d.ts +23 -0
  4. package/lib/commonStateTypes/filterPrimitives.js +21 -0
  5. package/lib/commonStateTypes/pusherActions.d.ts +11 -0
  6. package/lib/commonStateTypes/pusherActions.js +6 -0
  7. package/lib/coreEpics.js +1 -1
  8. package/lib/entity/account/accountSelector.d.ts +27 -1
  9. package/lib/entity/account/accountSelector.js +47 -1
  10. package/lib/entity/account/accountState.d.ts +6 -1
  11. package/lib/entity/account/accountState.js +11 -4
  12. package/lib/entity/account/subAccountSelector.d.ts +1 -1
  13. package/lib/entity/aiAccountantCustomer/aiAccountantCustomerPayload.js +1 -3
  14. package/lib/entity/aiAccountantCustomer/aiAccountantCustomerReducer.js +1 -2
  15. package/lib/entity/aiAccountantCustomer/aiAccountantCustomerSelector.d.ts +1 -1
  16. package/lib/entity/aiCfo/aiCfoPayload.d.ts +2 -0
  17. package/lib/entity/aiCfo/aiCfoReducer.d.ts +1 -1
  18. package/lib/entity/aiCfo/aiCfoReducer.js +33 -3
  19. package/lib/entity/aiCfo/aiCfoSelector.js +13 -1
  20. package/lib/entity/aiCfo/aiCfoState.d.ts +2 -0
  21. package/lib/entity/chargeCard/chargeCardReducer.d.ts +19 -2
  22. package/lib/entity/chargeCard/chargeCardReducer.js +35 -2
  23. package/lib/entity/chargeCardTransaction/chargeCardTransactionReducer.d.ts +14 -1
  24. package/lib/entity/chargeCardTransaction/chargeCardTransactionReducer.js +36 -2
  25. package/lib/entity/class/classSelector.d.ts +35 -0
  26. package/lib/entity/class/classSelector.js +50 -0
  27. package/lib/entity/sectionProjectView/sectionProjectViewReducer.d.ts +1 -1
  28. package/lib/entity/sectionProjectView/sectionProjectViewSelector.js +1 -1
  29. package/lib/entity/tenant/SessionManager.js +6 -3
  30. package/lib/entity/tenant/clearAllEpic.d.ts +2 -2
  31. package/lib/entity/tenant/clearAllEpic.js +2 -2
  32. package/lib/entity/tenant/epic/saveAPIKeyConnectionEpic.js +6 -2
  33. package/lib/entity/tenant/epic/saveOAuthConnectionEpic.js +6 -2
  34. package/lib/entity/tenant/tenantReducer.js +6 -1
  35. package/lib/entity/transaction/payloadTypes/transactionLinePayload.js +3 -1
  36. package/lib/epic.d.ts +12 -11
  37. package/lib/epic.js +13 -12
  38. package/lib/esm/commonStateTypes/cacheOverrideFetchReducer.js +16 -0
  39. package/lib/esm/commonStateTypes/filterPrimitives.js +20 -0
  40. package/lib/esm/commonStateTypes/pusherActions.js +3 -0
  41. package/lib/esm/coreEpics.js +1 -1
  42. package/lib/esm/entity/account/accountSelector.js +46 -1
  43. package/lib/esm/entity/account/accountState.js +7 -1
  44. package/lib/esm/entity/aiAccountantCustomer/aiAccountantCustomerPayload.js +1 -3
  45. package/lib/esm/entity/aiAccountantCustomer/aiAccountantCustomerReducer.js +1 -2
  46. package/lib/esm/entity/aiCfo/aiCfoReducer.js +32 -2
  47. package/lib/esm/entity/aiCfo/aiCfoSelector.js +13 -1
  48. package/lib/esm/entity/chargeCard/chargeCardReducer.js +34 -1
  49. package/lib/esm/entity/chargeCardTransaction/chargeCardTransactionReducer.js +35 -1
  50. package/lib/esm/entity/class/classSelector.js +48 -0
  51. package/lib/esm/entity/sectionProjectView/sectionProjectViewSelector.js +1 -1
  52. package/lib/esm/entity/tenant/SessionManager.js +4 -1
  53. package/lib/esm/entity/tenant/clearAllEpic.js +2 -2
  54. package/lib/esm/entity/tenant/epic/saveAPIKeyConnectionEpic.js +6 -2
  55. package/lib/esm/entity/tenant/epic/saveOAuthConnectionEpic.js +6 -2
  56. package/lib/esm/entity/tenant/tenantReducer.js +6 -1
  57. package/lib/esm/entity/transaction/payloadTypes/transactionLinePayload.js +3 -1
  58. package/lib/esm/epic.js +13 -12
  59. package/lib/esm/index.js +33 -23
  60. package/lib/esm/reducer.js +2 -2
  61. package/lib/esm/view/aiAccountantView/epics/fetchAiAccountantCustomersEpic.js +2 -5
  62. package/lib/esm/view/aiAccountantView/epics/fetchAiAccountantJobsEpic.js +2 -5
  63. package/lib/esm/view/aiAccountantView/epics/triggerAiAccountantJobEpic.js +4 -1
  64. package/lib/esm/view/aiCfoView/aiCfoViewReducer.js +11 -1
  65. package/lib/esm/view/aiCfoView/epics/updateChatSessionPinEpic.js +46 -0
  66. package/lib/esm/view/companyHealthMetricView/companyHealthMetricViewSelector.js +1 -1
  67. package/lib/esm/view/companyTaskManagerView/companyTaskManagerViewSelector.js +1 -1
  68. package/lib/esm/view/companyTaskManagerView/epics/fetchTaskManagerMetricsEpic.js +1 -1
  69. package/lib/esm/view/companyView/helpers/cockpitHelpers.js +1 -1
  70. package/lib/esm/view/companyView/selector/companyManagementViewSelector.js +1 -1
  71. package/lib/esm/view/companyView/selector/companyPortfolioViewSelector.js +1 -1
  72. package/lib/esm/view/creditAgentView/creditAgentViewReducer.js +1 -16
  73. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/fetchBulkUploadBatchesEpic.js +2 -2
  74. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/fetchCompletedTransactionsEpic.js +2 -1
  75. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/restoreBulkUploadAutomatchingOnMountEpic.js +8 -6
  76. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/searchTransactionsForManualMatchEpic.js +7 -1
  77. package/lib/esm/view/expenseAutomationView/epics/transactionCategorization/fetchTransactionCategorizationEpic.js +11 -1
  78. package/lib/esm/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.js +21 -1
  79. package/lib/esm/view/expenseAutomationView/reducers/missingReceiptsViewReducer.js +2 -1
  80. package/lib/esm/view/expenseAutomationView/reducers/transactionsViewReducer.js +253 -14
  81. package/lib/esm/view/expenseAutomationView/selectors/transactionCategorizationSelector.js +147 -13
  82. package/lib/esm/view/expenseAutomationView/transactionFilterHelpers.js +258 -0
  83. package/lib/esm/view/expenseAutomationView/types/completedSubTab.js +17 -0
  84. package/lib/esm/view/expenseAutomationView/types/missingReceiptsViewState.js +0 -2
  85. package/lib/esm/view/financeStatement/financeStatementSelector.js +1 -1
  86. package/lib/esm/view/recommendation/fetchEntityRecommendationsForLineUpdateEpic.js +87 -0
  87. package/lib/esm/view/recommendation/recommendationHelper.js +29 -0
  88. package/lib/esm/view/recommendation/recommendationReducer.js +26 -1
  89. package/lib/esm/view/spendManagement/chargeCards/cashbackDetail/cashbackDetailReducer.js +3 -2
  90. package/lib/esm/view/spendManagement/chargeCards/chargeCardConfig/chargeCardConfigReducer.js +3 -2
  91. package/lib/esm/view/spendManagement/chargeCards/chargeCardDetail/chargeCardDetailReducer.js +55 -18
  92. package/lib/esm/view/spendManagement/chargeCards/chargeCardDetail/fetchChargeCardDetailEpic.js +16 -2
  93. package/lib/esm/view/spendManagement/chargeCards/chargeCardDetail/fetchChargeCardDetailPageEpic.js +5 -4
  94. package/lib/esm/view/spendManagement/chargeCards/chargeCardList/chargeCardListReducer.js +26 -9
  95. package/lib/esm/view/spendManagement/chargeCards/chargeCardList/fetchChargeCardListPageEpic.js +9 -6
  96. package/lib/esm/view/spendManagement/chargeCards/chargeCardPaymentHistory/chargeCardPaymentHistoryReducer.js +3 -2
  97. package/lib/esm/view/spendManagement/chargeCards/chargeCardPaymentHistory/fetchChargeCardPaymentPageEpic.js +1 -1
  98. package/lib/esm/view/spendManagement/chargeCards/chargeCardRepaymentDetail/chargeCardRepaymentDetailReducer.js +7 -3
  99. package/lib/esm/view/spendManagement/spendManagementFilterHelpers.js +4 -2
  100. package/lib/esm/view/subscriptionView/subscriptionViewSelector.js +1 -1
  101. package/lib/esm/view/taskManager/cannedResponsesView/epics/fetchCannedResponsesEpic.js +1 -1
  102. package/lib/esm/view/taskManager/cannedResponsesView/epics/saveCannedResponseEpic.js +1 -1
  103. package/lib/esm/view/taskManager/taskDetailView/epics/unsnoozeTaskEpic.js +1 -1
  104. package/lib/esm/view/taskManager/taskListView/taskListReducer.js +1 -1
  105. package/lib/esm/view/transactionDetail/transactionDetailReducer.js +121 -6
  106. package/lib/esm/view/transactionDetail/transactionDetailSelector.js +29 -1
  107. package/lib/index.d.ts +33 -26
  108. package/lib/index.js +86 -60
  109. package/lib/reducer.d.ts +2 -2
  110. package/lib/reducer.js +2 -2
  111. package/lib/view/aiAccountantView/aiAccountantViewPayload.d.ts +2 -2
  112. package/lib/view/aiAccountantView/aiAccountantViewReducer.d.ts +1 -1
  113. package/lib/view/aiAccountantView/epics/fetchAiAccountantCustomersEpic.js +2 -5
  114. package/lib/view/aiAccountantView/epics/fetchAiAccountantJobsEpic.js +2 -5
  115. package/lib/view/aiAccountantView/epics/triggerAiAccountantJobEpic.js +4 -1
  116. package/lib/view/aiCfoView/aiCfoViewReducer.d.ts +4 -1
  117. package/lib/view/aiCfoView/aiCfoViewReducer.js +12 -2
  118. package/lib/view/aiCfoView/epics/updateChatSessionPinEpic.d.ts +8 -0
  119. package/lib/view/aiCfoView/epics/updateChatSessionPinEpic.js +50 -0
  120. package/lib/view/companyHealthMetricView/companyHealthMetricViewSelector.js +1 -1
  121. package/lib/view/companyTaskManagerView/companyTaskManagerViewSelector.d.ts +1 -1
  122. package/lib/view/companyTaskManagerView/companyTaskManagerViewSelector.js +1 -1
  123. package/lib/view/companyView/helpers/cockpitHelpers.js +1 -1
  124. package/lib/view/companyView/selector/companyManagementViewSelector.js +1 -1
  125. package/lib/view/companyView/selector/companyPortfolioViewSelector.js +1 -1
  126. package/lib/view/companyView/types/cockpitTypes.d.ts +1 -1
  127. package/lib/view/creditAgentView/creditAgentViewPayload.d.ts +0 -3
  128. package/lib/view/creditAgentView/creditAgentViewReducer.d.ts +1 -1
  129. package/lib/view/creditAgentView/creditAgentViewReducer.js +2 -17
  130. package/lib/view/creditAgentView/creditAgentViewState.d.ts +0 -5
  131. package/lib/view/expenseAutomationView/epics/missingReceipts/fetchBulkUploadBatchesEpic.js +2 -2
  132. package/lib/view/expenseAutomationView/epics/missingReceipts/fetchCompletedTransactionsEpic.js +2 -1
  133. package/lib/view/expenseAutomationView/epics/missingReceipts/restoreBulkUploadAutomatchingOnMountEpic.js +8 -6
  134. package/lib/view/expenseAutomationView/epics/missingReceipts/searchTransactionsForManualMatchEpic.js +7 -1
  135. package/lib/view/expenseAutomationView/epics/transactionCategorization/fetchTransactionCategorizationEpic.d.ts +2 -2
  136. package/lib/view/expenseAutomationView/epics/transactionCategorization/fetchTransactionCategorizationEpic.js +10 -0
  137. package/lib/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.d.ts +2 -1
  138. package/lib/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.js +23 -2
  139. package/lib/view/expenseAutomationView/payload/transactionCategorizationPayload.d.ts +21 -0
  140. package/lib/view/expenseAutomationView/reducers/missingReceiptsViewReducer.d.ts +2 -1
  141. package/lib/view/expenseAutomationView/reducers/missingReceiptsViewReducer.js +2 -1
  142. package/lib/view/expenseAutomationView/reducers/transactionsViewReducer.d.ts +28 -5
  143. package/lib/view/expenseAutomationView/reducers/transactionsViewReducer.js +253 -14
  144. package/lib/view/expenseAutomationView/selectorTypes/missingReceiptsSelectorTypes.d.ts +2 -1
  145. package/lib/view/expenseAutomationView/selectorTypes/transactionsViewSelectorTypes.d.ts +16 -0
  146. package/lib/view/expenseAutomationView/selectors/transactionCategorizationSelector.d.ts +7 -1
  147. package/lib/view/expenseAutomationView/selectors/transactionCategorizationSelector.js +150 -13
  148. package/lib/view/expenseAutomationView/transactionFilterHelpers.d.ts +66 -0
  149. package/lib/view/expenseAutomationView/transactionFilterHelpers.js +262 -0
  150. package/lib/view/expenseAutomationView/types/completedSubTab.d.ts +10 -0
  151. package/lib/view/expenseAutomationView/types/completedSubTab.js +21 -0
  152. package/lib/view/expenseAutomationView/types/missingReceiptsViewState.d.ts +1 -2
  153. package/lib/view/expenseAutomationView/types/missingReceiptsViewState.js +1 -4
  154. package/lib/view/expenseAutomationView/types/transactionsViewState.d.ts +44 -2
  155. package/lib/view/financeStatement/financeStatementSelector.js +1 -1
  156. package/lib/view/profitAndLossProjectView/profitAndLossProjectViewSelectorTypes.d.ts +1 -1
  157. package/lib/view/recommendation/fetchEntityRecommendationsForLineUpdateEpic.d.ts +9 -0
  158. package/lib/view/recommendation/fetchEntityRecommendationsForLineUpdateEpic.js +91 -0
  159. package/lib/view/recommendation/recommendationHelper.d.ts +9 -0
  160. package/lib/view/recommendation/recommendationHelper.js +31 -1
  161. package/lib/view/recommendation/recommendationReducer.d.ts +20 -1
  162. package/lib/view/recommendation/recommendationReducer.js +27 -2
  163. package/lib/view/spendManagement/billPay/billList/billListState.d.ts +1 -1
  164. package/lib/view/spendManagement/chargeCards/cashbackDetail/cashbackDetailReducer.d.ts +3 -1
  165. package/lib/view/spendManagement/chargeCards/cashbackDetail/cashbackDetailReducer.js +3 -2
  166. package/lib/view/spendManagement/chargeCards/chargeCardConfig/chargeCardConfigReducer.d.ts +3 -1
  167. package/lib/view/spendManagement/chargeCards/chargeCardConfig/chargeCardConfigReducer.js +3 -2
  168. package/lib/view/spendManagement/chargeCards/chargeCardDetail/chargeCardDetailReducer.js +55 -18
  169. package/lib/view/spendManagement/chargeCards/chargeCardDetail/fetchChargeCardDetailEpic.js +16 -2
  170. package/lib/view/spendManagement/chargeCards/chargeCardDetail/fetchChargeCardDetailPageEpic.js +5 -4
  171. package/lib/view/spendManagement/chargeCards/chargeCardList/chargeCardListReducer.d.ts +18 -3
  172. package/lib/view/spendManagement/chargeCards/chargeCardList/chargeCardListReducer.js +27 -10
  173. package/lib/view/spendManagement/chargeCards/chargeCardList/fetchChargeCardListPageEpic.js +9 -6
  174. package/lib/view/spendManagement/chargeCards/chargeCardPaymentHistory/chargeCardPaymentHistory.d.ts +1 -1
  175. package/lib/view/spendManagement/chargeCards/chargeCardPaymentHistory/chargeCardPaymentHistoryReducer.d.ts +3 -1
  176. package/lib/view/spendManagement/chargeCards/chargeCardPaymentHistory/chargeCardPaymentHistoryReducer.js +3 -2
  177. package/lib/view/spendManagement/chargeCards/chargeCardPaymentHistory/fetchChargeCardPaymentPageEpic.js +1 -1
  178. package/lib/view/spendManagement/chargeCards/chargeCardRepaymentDetail/chargeCardRepaymentDetailReducer.d.ts +3 -1
  179. package/lib/view/spendManagement/chargeCards/chargeCardRepaymentDetail/chargeCardRepaymentDetailReducer.js +7 -3
  180. package/lib/view/spendManagement/reimbursement/remiListView/remiListState.d.ts +1 -1
  181. package/lib/view/spendManagement/spendManagementFilterHelpers.d.ts +12 -3
  182. package/lib/view/spendManagement/spendManagementFilterHelpers.js +4 -2
  183. package/lib/view/subscriptionView/subscriptionViewSelector.js +1 -1
  184. package/lib/view/taskManager/taskListView/taskList.d.ts +1 -1
  185. package/lib/view/taskManager/taskListView/taskListReducer.js +1 -1
  186. package/lib/view/transactionDetail/transactionDetailReducer.d.ts +11 -1
  187. package/lib/view/transactionDetail/transactionDetailReducer.js +122 -7
  188. package/lib/view/transactionDetail/transactionDetailSelector.d.ts +2 -0
  189. package/lib/view/transactionDetail/transactionDetailSelector.js +31 -2
  190. package/lib/view/transactionDetail/transactionDetailTypes.d.ts +1 -0
  191. package/lib/view/zeniOAuthView/zeniOAuthSelector.d.ts +1 -1
  192. package/package.json +9 -4
  193. package/lib/esm/view/creditAgentView/epics/fetchCreditAgentAccessEpic.js +0 -13
  194. package/lib/tsconfig.typecheck.tsbuildinfo +0 -1
  195. package/lib/view/creditAgentView/epics/fetchCreditAgentAccessEpic.d.ts +0 -11
  196. package/lib/view/creditAgentView/epics/fetchCreditAgentAccessEpic.js +0 -17
@@ -1,17 +1,90 @@
1
+ import { createSelector } from '@reduxjs/toolkit';
1
2
  import omit from 'lodash/omit';
2
3
  import { reduceAllFetchState, reduceAnyFetchState, } from '../../../commonStateTypes/reduceFetchState';
3
4
  import { toMonthYearPeriodId } from '../../../commonStateTypes/timePeriod';
4
5
  import { getCurrentTenant, getIsAccountingClassesEnabled, getIsAccountingProjectsEnabled, } from '../../../entity/tenant/tenantSelector';
5
6
  import { getTransactionWithCOT } from '../../../entity/transaction/transactionHelper';
6
7
  import { getSupportedTransactionsByIds } from '../../../entity/transaction/transactionSelector';
8
+ import { applyTransactionFilters, } from '../transactionFilterHelpers';
7
9
  import { getAccountList, getNestedAccountListHierarchy, getUncategorizedAccounts, } from '../../accountList/accountListSelector';
8
10
  import { getClassList, getNestedClassListHierarchy, } from '../../classList/classListSelector';
9
11
  import { getProjectList } from '../../projectList/projectListSelector';
10
12
  import { getAllSteps } from '../selectorTypes/expenseAutomationViewSelectorTypes';
13
+ // Walks the tab's transactionReviewLocalDataById map and returns
14
+ // `{ [transactionId]: true }` for every transaction that has at least
15
+ // one line whose targeted-fetch is In-Progress. Pulled out as a plain
16
+ // function so each tab's createSelector can share it.
17
+ const computeCategorizationInFlightRecommendations = (transactionReviewLocalDataById) => {
18
+ const result = {};
19
+ if (transactionReviewLocalDataById == null) {
20
+ return result;
21
+ }
22
+ for (const [transactionId, data] of Object.entries(transactionReviewLocalDataById)) {
23
+ const lineItems = Object.values(data.transactionReviewLocalData.lineItemById);
24
+ if (lineItems.some((lineItem) => lineItem.categoryClassRecommendationsFetchState?.fetchState ===
25
+ 'In-Progress')) {
26
+ result[transactionId] = true;
27
+ }
28
+ }
29
+ return result;
30
+ };
31
+ // Per-tab createSelector instances. Each one is memoized on its OWN tab's
32
+ // transactionReviewLocalDataById reference. Switching tabs A->B->A no
33
+ // longer busts the memo for tab A — the dispatcher below just returns
34
+ // whichever per-tab selector matches the active tab, and reselect keeps
35
+ // the prior result alive as long as the underlying slice ref is stable.
36
+ const getReviewInFlightRecommendationsByTransactionId = createSelector((state) => state.expenseAutomationTransactionsViewState.transactionCategorizationView
37
+ .review.transactionReviewLocalDataById, computeCategorizationInFlightRecommendations);
38
+ const getAutoCategorizedInFlightRecommendationsByTransactionId = createSelector((state) => state.expenseAutomationTransactionsViewState.transactionCategorizationView
39
+ .autoCategorized.transactionReviewLocalDataById, computeCategorizationInFlightRecommendations);
40
+ // Per-transaction "any line is fetching category/class recommendations?"
41
+ // map for the active categorization tab. Dispatches to the per-tab
42
+ // memoized selector above so steady state (no fetches in flight)
43
+ // recomputes only when the active tab's local data changes; tab switches
44
+ // are O(1) cache lookups.
45
+ //
46
+ // `default` guards against the union "lying" at runtime: `TransactionsTab`
47
+ // is produced via `stringToUnion`, which falls back to `s as StringUnion`
48
+ // for unrecognized strings, so an unexpected value can land in state. The
49
+ // downstream `getCategorizationHasInFlightRecommendations` calls
50
+ // `Object.keys` on this result, so we must always return an object.
51
+ export const getCategorizationInFlightRecommendationsByTransactionId = (state) => {
52
+ const tab = state.expenseAutomationTransactionsViewState
53
+ .selectedTransactionCategorizationTab;
54
+ switch (tab) {
55
+ case 'review':
56
+ return getReviewInFlightRecommendationsByTransactionId(state);
57
+ case 'autoCategorized':
58
+ return getAutoCategorizedInFlightRecommendationsByTransactionId(state);
59
+ default:
60
+ return {};
61
+ }
62
+ };
63
+ // Page-level "any line on the active tab is in flight?" flag. Drives the
64
+ // list-page Save disable.
65
+ export const getCategorizationHasInFlightRecommendations = createSelector(getCategorizationInFlightRecommendationsByTransactionId, (inFlightByTransactionId) => Object.keys(inFlightByTransactionId).length > 0);
66
+ export const toTransactionView = (transaction, transactionLocalData) => {
67
+ return {
68
+ id: transaction.id,
69
+ date: transaction.date,
70
+ amount: transaction.amount,
71
+ vendorName: transaction.vendorName,
72
+ customerName: transaction.customerName,
73
+ vendorId: transaction.vendorId,
74
+ customerId: transaction.customerId,
75
+ description: transaction.description,
76
+ memo: transaction.memo,
77
+ type: transaction.type,
78
+ typeName: transaction.typeName,
79
+ createTime: transaction.createTime,
80
+ transaction: transaction,
81
+ transactionLocalData,
82
+ };
83
+ };
11
84
  export function getExpenseAutomationTransactionView(state) {
12
85
  const { accountState, classState, classListState, accountListState, expenseAutomationTransactionsViewState, expenseAutomationViewState, projectState, projectListState, transactionState, monthEndCloseChecksState, monthEndCloseChecksViewState, } = state;
13
- const { selectedTransactionCategorizationTab } = expenseAutomationTransactionsViewState;
14
- const { uiState, refreshStatus, saveStatus, markAsNotMiscategorizedStatus, transactionIdsBySelectedPeriod, transactionReviewLocalDataById, selectedCheckBoxTransactionIds, transactionIdsWithUnsavedData, uploadReceiptStatusById, selectedTransactionId, selectedTransactionLineId, } = expenseAutomationTransactionsViewState.transactionCategorizationView[selectedTransactionCategorizationTab];
86
+ const { selectedTransactionCategorizationCompletedSubTab, selectedTransactionCategorizationTab, } = expenseAutomationTransactionsViewState;
87
+ const { uiState, refreshStatus, saveStatus, markAsNotMiscategorizedStatus, transactionIdsBySelectedPeriod, transactionReviewLocalDataById, selectedCheckBoxTransactionIds, transactionIdsWithUnsavedData, uploadReceiptStatusById, selectedTransactionId, selectedTransactionLineId, filters, } = expenseAutomationTransactionsViewState.transactionCategorizationView[selectedTransactionCategorizationTab];
15
88
  const uncategorizedIncomeExpense = getUncategorizedAccounts(accountState, accountListState, 'accountList');
16
89
  const accountList = getAccountList(accountState, accountListState, 'accountList');
17
90
  const classList = getClassList(classState, classListState);
@@ -30,20 +103,58 @@ export function getExpenseAutomationTransactionView(state) {
30
103
  ? transactionIdsBySelectedPeriod[monthYearPeriodId]
31
104
  : null;
32
105
  const transactionIds = transactionIdsForSelectedPeriod ?? [];
33
- const transactionLocalData = transactionIds
34
- .map((transactionId) => {
106
+ const transactions = getSupportedTransactionsByIds(transactionState, transactionIds);
107
+ const transactionsWithCOT = transactions.map((transaction) => getTransactionWithCOT(transaction));
108
+ const transactionLocalDataMap = new Map();
109
+ transactionIds.forEach((transactionId) => {
35
110
  const transactionData = transactionReviewLocalDataById[transactionId];
36
111
  if (transactionData != null) {
37
- return {
112
+ transactionLocalDataMap.set(transactionId, {
38
113
  transactionId,
39
114
  transactionReviewLocalData: transactionData.transactionReviewLocalData,
40
- };
115
+ });
41
116
  }
42
- return null;
43
- })
44
- .filter((transaction) => transaction != null);
45
- const transactions = getSupportedTransactionsByIds(transactionState, transactionIds);
46
- const transactionsWithCOT = transactions.map((transaction) => getTransactionWithCOT(transaction));
117
+ });
118
+ // Step 2: Convert to TransactionView and apply advanced filters
119
+ const transactionViews = transactionsWithCOT.map((transaction) => {
120
+ const localData = transactionLocalDataMap.get(transaction.id);
121
+ return toTransactionView(transaction, localData);
122
+ });
123
+ // Apply TC-specific filters (lives under expenseAutomationView, independent
124
+ // of the Spend Management filter pipeline).
125
+ const filteredTransactionViews = applyTransactionFilters(transactionViews, filters);
126
+ // Convert back to TransactionWithCOT for return
127
+ const filteredTransactionsWithCOT = filteredTransactionViews.map((view) => view.transaction);
128
+ // Get transactionLocalData for filtered transactions
129
+ // Also include transactionLocalData for transactions that don't exist in transactionState
130
+ // but have local data (to match original behavior)
131
+ const filteredTransactionIds = new Set(filteredTransactionViews.map((view) => view.id));
132
+ // Pre-compute the membership set once. The previous implementation called
133
+ // `transactions.some(t => t.id === transactionId)` inside the per-id loop,
134
+ // turning the pipeline into O(n × m) — measurable on tenants with large
135
+ // transaction lists since this selector runs on every Redux dispatch.
136
+ const transactionExistsById = new Set(transactions.map((t) => t.id));
137
+ // `.flatMap` returns `X[]` directly when the callback returns `[]` for the
138
+ // skip case, so we don't need the trailing `.filter((d): d is X => …)` type
139
+ // predicate that the previous `map → filter` pipeline required.
140
+ const filteredTransactionLocalData = transactionIds.flatMap((transactionId) => {
141
+ const transactionData = transactionReviewLocalDataById[transactionId];
142
+ if (transactionData == null) {
143
+ return [];
144
+ }
145
+ // Include if transaction is in filtered results, or if transaction doesn't exist in state
146
+ // (to maintain backward compatibility with tests)
147
+ const transactionExists = transactionExistsById.has(transactionId);
148
+ if (filteredTransactionIds.has(transactionId) || !transactionExists) {
149
+ return [
150
+ {
151
+ transactionId,
152
+ transactionReviewLocalData: transactionData.transactionReviewLocalData,
153
+ },
154
+ ];
155
+ }
156
+ return [];
157
+ });
47
158
  const monthEndFetchState = monthYearPeriodId != null
48
159
  ? (monthEndCloseChecksViewState.monthEndCloseChecksViewByTenantId[currentTenant.tenantId]?.[monthYearPeriodId] ?? { fetchState: 'Not-Started', error: undefined })
49
160
  : { fetchState: 'Not-Started', error: undefined };
@@ -63,10 +174,27 @@ export function getExpenseAutomationTransactionView(state) {
63
174
  .uiState.totalCount;
64
175
  const totalCountByAutoCat = expenseAutomationTransactionsViewState.transactionCategorizationView
65
176
  .autoCategorized.uiState.totalCount;
177
+ // Per-(sub-)tab counts powering pagination, in-list "showing X of Y", and
178
+ // any save/refresh round-trips. Sourced from `uiState.totalCount` which
179
+ // mirrors the response's `total_count` for whatever tab/sub-tab the user is
180
+ // viewing (e.g. only the Manual sub-tab rows for Completed → Manual).
66
181
  const totalCountByTab = {
67
182
  review: monthYearPeriodId != null ? totalCountByReview[monthYearPeriodId] : 0,
68
183
  autoCategorized: monthYearPeriodId != null ? totalCountByAutoCat[monthYearPeriodId] : 0,
69
184
  };
185
+ // Parent-tab badge counts. Sourced from `parent_tab_total_count` in the
186
+ // listing response and used exclusively by the navbar / tab strip badges.
187
+ // Independent of which Completed sub-tab is active so the badge stays
188
+ // stable across sub-tab switches.
189
+ const parentTotalCountByTab = expenseAutomationTransactionsViewState.parentTotalCountByTab;
190
+ const parentTabTotalCountByTab = {
191
+ review: monthYearPeriodId != null
192
+ ? (parentTotalCountByTab.review[monthYearPeriodId] ?? 0)
193
+ : 0,
194
+ autoCategorized: monthYearPeriodId != null
195
+ ? (parentTotalCountByTab.autoCategorized[monthYearPeriodId] ?? 0)
196
+ : 0,
197
+ };
70
198
  const fetchStateByTab = {
71
199
  review: {
72
200
  fetchState: expenseAutomationTransactionsViewState.transactionCategorizationView
@@ -86,11 +214,13 @@ export function getExpenseAutomationTransactionView(state) {
86
214
  : [];
87
215
  const transactionCompletionStatus = allSteps.find((step) => step.step === 'transaction_categorization')?.completionStatus;
88
216
  const completionStatus = transactionCompletionStatus ?? 'incomplete';
217
+ const inFlightCategoryClassRecommendationsByTransactionId = getCategorizationInFlightRecommendationsByTransactionId(state);
218
+ const hasInFlightCategoryClassRecommendations = getCategorizationHasInFlightRecommendations(state);
89
219
  return {
90
220
  version: 0,
91
221
  fetchState: fetchStatus.fetchState,
92
222
  error: fetchStatus.error,
93
- transactions: transactionsWithCOT,
223
+ transactions: filteredTransactionsWithCOT,
94
224
  selectedCheckBoxTransactionIds,
95
225
  transactionIdsWithUnsavedData,
96
226
  uncategorizedAccounts: uncategorizedIncomeExpense,
@@ -99,18 +229,22 @@ export function getExpenseAutomationTransactionView(state) {
99
229
  classList: allClasses,
100
230
  accountsHierarchyList,
101
231
  classHierarchyList,
232
+ hasInFlightCategoryClassRecommendations,
233
+ inFlightCategoryClassRecommendationsByTransactionId,
102
234
  isAccountingProjectsEnabled,
103
235
  projectList,
104
- transactionLocalData,
236
+ transactionLocalData: filteredTransactionLocalData,
105
237
  uiState,
106
238
  refreshStatus,
107
239
  saveStatus,
108
240
  markAsNotMiscategorizedStatus,
109
241
  completionStatus,
110
242
  totalCountByTab,
243
+ parentTabTotalCountByTab,
111
244
  fetchStateByTransactionTabs: fetchStateByTab,
112
245
  uploadReceiptStatusById,
113
246
  selectedTransactionId,
114
247
  selectedTransactionLineId,
248
+ selectedTransactionCategorizationCompletedSubTab,
115
249
  };
116
250
  }
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Narrowing type-guard for "has a non-empty string here". Used in place of
3
+ * raw `if (foo)` truthiness checks on `string | null | undefined` values so
4
+ * the `@typescript-eslint/strict-boolean-expressions` lint stays clean —
5
+ * empty strings should explicitly fall through to the next candidate
6
+ * (vendorName → customerName → localData.vendor.name → ...) rather than
7
+ * being implicitly coerced to falsy.
8
+ */
9
+ const isNonEmptyString = (s) => s != null && s !== '';
10
+ /**
11
+ * First line item in UI order. `lineItemById` is a Record whose iteration
12
+ * order is not guaranteed to match what the user sees; `sortedLineItems`
13
+ * is the canonical ordering used by the categorization list/detail views.
14
+ */
15
+ const getFirstLineItemFromReviewLocalData = (localData) => {
16
+ const { sortedLineItems, lineItemById } = localData;
17
+ if (sortedLineItems.length > 0) {
18
+ return lineItemById[sortedLineItems[0]];
19
+ }
20
+ const lineItems = Object.values(lineItemById);
21
+ return lineItems.length > 0 ? lineItems[0] : undefined;
22
+ };
23
+ export const TRANSACTION_FILTER_CATEGORIES = [
24
+ { value: 'payment_account_name', type: 'dropdown' },
25
+ { value: 'payment_account_type', type: 'dropdown' },
26
+ { value: 'payee', type: 'searchAutocomplete' },
27
+ { value: 'category', type: 'dropdown' },
28
+ { value: 'class', type: 'dropdown' },
29
+ { value: 'amount', type: 'numberRange' },
30
+ ];
31
+ /**
32
+ * Resolve the comparable value for a transaction against a given filter field.
33
+ * Returns undefined when the transaction doesn't carry the field — callers
34
+ * decide whether absence counts as a match (for 'not_equal' it does).
35
+ */
36
+ const getCategoryValueForTransaction = (key, transaction) => {
37
+ switch (key) {
38
+ case 'amount': {
39
+ // Prefer transactionLocalData line items (sum). Fall back to lines on
40
+ // the transaction itself. Final fallback: transaction-level amount.
41
+ const localDataForAmount = transaction.transactionLocalData?.transactionReviewLocalData;
42
+ if (localDataForAmount?.lineItemById) {
43
+ const lineItems = Object.values(localDataForAmount.lineItemById);
44
+ if (lineItems.length > 0) {
45
+ return lineItems.reduce((sum, lineItem) => sum + (lineItem.amount?.amount ?? 0), 0);
46
+ }
47
+ }
48
+ if (transaction.transaction.lines &&
49
+ transaction.transaction.lines.length > 0) {
50
+ return transaction.transaction.lines.reduce((sum, line) => sum + (line.amount?.amount ?? 0), 0);
51
+ }
52
+ return transaction.amount.amount;
53
+ }
54
+ case 'payee': {
55
+ if (isNonEmptyString(transaction.vendorName)) {
56
+ return transaction.vendorName;
57
+ }
58
+ if (isNonEmptyString(transaction.customerName)) {
59
+ return transaction.customerName;
60
+ }
61
+ const localData = transaction.transactionLocalData?.transactionReviewLocalData;
62
+ const vendorName = localData?.vendor?.name;
63
+ if (isNonEmptyString(vendorName)) {
64
+ return vendorName;
65
+ }
66
+ const customerName = localData?.customer?.name;
67
+ if (isNonEmptyString(customerName)) {
68
+ return customerName;
69
+ }
70
+ return undefined;
71
+ }
72
+ case 'payment_account_name': {
73
+ // Match what TransactionCategorizationListRow renders for the cell.
74
+ return transaction.transaction.account?.accountName;
75
+ }
76
+ case 'payment_account_type': {
77
+ // Raw `paymentType` enum ("credit_card" / "check" / "cash"). Dropdown
78
+ // option values use the same enum; row uses `paymentTypeName` for the
79
+ // human label.
80
+ return transaction.transaction.paymentType;
81
+ }
82
+ case 'category': {
83
+ const localDataForCategory = transaction.transactionLocalData?.transactionReviewLocalData;
84
+ if (localDataForCategory != null) {
85
+ const firstLineItem = getFirstLineItemFromReviewLocalData(localDataForCategory);
86
+ const accountId = firstLineItem?.account?.accountId;
87
+ if (isNonEmptyString(accountId)) {
88
+ return accountId;
89
+ }
90
+ const qboId = firstLineItem?.account?.qboId;
91
+ if (isNonEmptyString(qboId)) {
92
+ return qboId;
93
+ }
94
+ const accountName = firstLineItem?.account?.accountName;
95
+ if (isNonEmptyString(accountName)) {
96
+ return accountName;
97
+ }
98
+ }
99
+ const firstLineForCategory = transaction.transaction.lines?.[0];
100
+ if (firstLineForCategory?.type ===
101
+ 'transaction_with_account_and_class_line' ||
102
+ firstLineForCategory?.type ===
103
+ 'transaction_with_product_or_service_line' ||
104
+ firstLineForCategory?.type === 'journal_entry_transaction_line') {
105
+ const account = firstLineForCategory.account;
106
+ return account?.accountId ?? account?.qboId ?? account?.accountName;
107
+ }
108
+ return undefined;
109
+ }
110
+ case 'class': {
111
+ const localDataForClass = transaction.transactionLocalData?.transactionReviewLocalData;
112
+ if (localDataForClass != null) {
113
+ const firstLineItemForClass = getFirstLineItemFromReviewLocalData(localDataForClass);
114
+ const classId = firstLineItemForClass?.class?.classId;
115
+ if (isNonEmptyString(classId)) {
116
+ return classId;
117
+ }
118
+ const qboId = firstLineItemForClass?.class?.qboId;
119
+ if (isNonEmptyString(qboId)) {
120
+ return qboId;
121
+ }
122
+ const className = firstLineItemForClass?.class?.className;
123
+ if (isNonEmptyString(className)) {
124
+ return className;
125
+ }
126
+ }
127
+ const firstLineForClass = transaction.transaction.lines?.[0];
128
+ if (firstLineForClass?.type === 'transaction_with_account_and_class_line' ||
129
+ firstLineForClass?.type ===
130
+ 'transaction_with_product_or_service_line' ||
131
+ firstLineForClass?.type === 'journal_entry_transaction_line') {
132
+ const classData = firstLineForClass.class;
133
+ return classData?.classId ?? classData?.qboId ?? classData?.className;
134
+ }
135
+ return undefined;
136
+ }
137
+ default:
138
+ return undefined;
139
+ }
140
+ };
141
+ /**
142
+ * TC-only amount matcher. Supports all five operators TC defines, including
143
+ * the legacy "1000<->5000" range-string form (kept for backward compatibility
144
+ * with persisted filter state that may still contain that encoding).
145
+ *
146
+ * The `'equal' | 'not_equal'` branch matches if `amount` equals ANY of the
147
+ * configured values (consistent with how non-amount filters interpret a
148
+ * multi-value `values` array). `.some()` over the values array also makes
149
+ * the empty-values case behave correctly — empty array → `matched = false`
150
+ * — though in practice `applyTransactionFilters` strips empty-values
151
+ * categories before they reach this matcher. The trailing
152
+ * `op === 'not_equal' ? !matched : matched` line inverts for `not_equal`.
153
+ */
154
+ const matchAmount = (amount, category) => {
155
+ const op = category.matchingOperator;
156
+ const values = category.values;
157
+ let matched = false;
158
+ if (op === 'in_between') {
159
+ if (values.length >= 2) {
160
+ const min = Number(values[0]);
161
+ const max = Number(values[1]);
162
+ matched = amount >= min && amount <= max;
163
+ }
164
+ }
165
+ else if (op === 'less_than') {
166
+ if (values.length >= 1) {
167
+ matched = amount < Number(values[0]);
168
+ }
169
+ }
170
+ else if (op === 'greater_than') {
171
+ if (values.length >= 1) {
172
+ matched = amount > Number(values[0]);
173
+ }
174
+ }
175
+ else if (op === 'equal' || op === 'not_equal') {
176
+ matched = values.some((v) => {
177
+ const s = String(v);
178
+ // Backward compatibility: legacy "low<->high" range-string form
179
+ // persisted under `matchingOperator: 'equal'`.
180
+ if (s.includes('<->')) {
181
+ const parts = s.split('<->');
182
+ return (amount >= Number(parts[0] ?? '') && amount <= Number(parts[1] ?? ''));
183
+ }
184
+ return amount === Number(v);
185
+ });
186
+ }
187
+ return op === 'not_equal' ? !matched : matched;
188
+ };
189
+ const transactionMatchesCategory = (transaction, category) => {
190
+ const value = getCategoryValueForTransaction(category.field, transaction);
191
+ if (value == null) {
192
+ // Absent-value semantics — pinning these down explicitly so the
193
+ // asymmetry isn't surprising:
194
+ //
195
+ // not_equal: a missing value IS NOT EQUAL to any candidate, so the
196
+ // transaction matches the filter (passes through).
197
+ // equal: a missing value is not equal to any candidate, so the
198
+ // transaction does NOT match (filtered out).
199
+ // less_than / greater_than: SQL-style three-valued logic — comparing
200
+ // against a missing value is "unknown", which we treat as
201
+ // "does not match" (filtered out). A user setting
202
+ // "amount < $1000" probably wants transactions with a
203
+ // concrete amount that satisfies the bound, not rows
204
+ // where the amount can't be determined.
205
+ // in_between: same as the single-sided comparators — missing values
206
+ // are filtered out.
207
+ //
208
+ // Only the `not_equal` branch returns `true` here; everything else
209
+ // falls through to the `false` below.
210
+ return category.matchingOperator === 'not_equal';
211
+ }
212
+ if (category.field === 'amount') {
213
+ return matchAmount(Number(value), category);
214
+ }
215
+ const valueStr = value.toString();
216
+ const valueInList = category.values.some((v) => v.toString() === valueStr);
217
+ return category.matchingOperator === 'not_equal' ? !valueInList : valueInList;
218
+ };
219
+ /**
220
+ * TC-only equivalent of `applyAdvancedFiltersOnList`. Filters a list of
221
+ * `TransactionView` items against a `TransactionFilters` object using the
222
+ * AND/OR combination semantics from `categoryCombinationOperator`.
223
+ *
224
+ * Independent of `view/spendManagement` — keeps the TC filter pipeline cleanly
225
+ * inside the Expense Automation feature group.
226
+ */
227
+ export const applyTransactionFilters = (transactions, filters) => {
228
+ if (filters?.categories == null || filters.categories.length === 0) {
229
+ return transactions;
230
+ }
231
+ // Mirrors the predicate used by `getTransactionAppliedFiltersCount` on the
232
+ // webc side. A half-filled category — e.g. `in_between` with only the
233
+ // `min` typed — would otherwise survive the filter pass and produce zero
234
+ // matches because `Number("")` collapses to `0`, artificially emptying
235
+ // the list while editing. Skipping such categories keeps the filtered
236
+ // view stable while the user finishes typing.
237
+ const activeCategories = filters.categories.filter((c) => {
238
+ if (c.field == null || c.values.length === 0) {
239
+ return false;
240
+ }
241
+ if (c.field === 'amount' && c.matchingOperator === 'in_between') {
242
+ return (c.values.length >= 2 &&
243
+ String(c.values[0] ?? '').trim() !== '' &&
244
+ String(c.values[1] ?? '').trim() !== '');
245
+ }
246
+ return String(c.values[0] ?? '').trim() !== '';
247
+ });
248
+ if (activeCategories.length === 0) {
249
+ return transactions;
250
+ }
251
+ const op = filters.categoryCombinationOperator;
252
+ return transactions.filter((txn) => {
253
+ if (op === 'AND') {
254
+ return activeCategories.every((cat) => transactionMatchesCategory(txn, cat));
255
+ }
256
+ return activeCategories.some((cat) => transactionMatchesCategory(txn, cat));
257
+ });
258
+ };
@@ -0,0 +1,17 @@
1
+ import { stringToUnion } from '../../../commonStateTypes/stringToUnion';
2
+ /**
3
+ * Sub-tabs that can appear under any "Completed" tab in the Expense Automation
4
+ * surface (Transaction Categorization Completed and Missing Receipts Completed
5
+ * both use this exact union). Forwarded verbatim to listing APIs as `sub_tab`
6
+ * / `match_type`. `'all'` preserves parent-tab semantics on the backend.
7
+ */
8
+ const COMPLETED_SUB_TABS = ['all', 'ai_accountant', 'manual'];
9
+ export const toCompletedSubTab = (v) => stringToUnion(v.trim().toLowerCase(), COMPLETED_SUB_TABS);
10
+ /**
11
+ * "No sub-tab filter" sentinel — single source of truth for the default
12
+ * value of {@link CompletedSubTab}. Use this constant in initial slice
13
+ * state and at any call site that needs to fall back to the parent-tab
14
+ * listing semantics (review tab requests, manual-search overrides, etc.)
15
+ * so a future rename of the union doesn't require chasing literals.
16
+ */
17
+ export const DEFAULT_COMPLETED_SUB_TAB = 'all';
@@ -39,8 +39,6 @@ const BULK_UPLOAD_RESULTS_TABS = ['completed', 'unmatched'];
39
39
  export const toBulkUploadResultsTab = (v) => stringToUnion(v.trim().toLowerCase(), BULK_UPLOAD_RESULTS_TABS);
40
40
  const MISSING_RECEIPTS_TABS = ['missing', 'completed', 'unmatched'];
41
41
  export const toMissingReceiptsTab = (v) => stringToUnion(v.trim().toLowerCase(), MISSING_RECEIPTS_TABS);
42
- const COMPLETED_SUB_TABS = ['all', 'ai_accountant', 'manual'];
43
- export const toCompletedSubTab = (v) => stringToUnion(v.trim().toLowerCase(), COMPLETED_SUB_TABS);
44
42
  const MATCH_SOURCES = ['ai', 'manual'];
45
43
  export const toMatchSource = (v) => stringToUnion(v.trim().toLowerCase(), MATCH_SOURCES);
46
44
  const BULK_UPLOAD_SORT_KEYS = [
@@ -2,6 +2,7 @@ import { createSelector } from '@reduxjs/toolkit';
2
2
  import { stripCompareAdditionalBalanceTypes } from '../../commonStateTypes/coaBalance/coaBalanceType';
3
3
  import { newBalancesFilter, newBalancesFilterForDateRange, } from '../../commonStateTypes/coaBalance/coaBalancesFilter';
4
4
  import { newBalancesFilterClassesView } from '../../commonStateTypes/coaBalance/coaBalancesFilterClassesView';
5
+ import { newBalancesFilterProjectView } from '../../commonStateTypes/coaBalance/coaBalancesFilterProjectView';
5
6
  import { getNumberOfPeriods, } from '../../commonStateTypes/dataAvailable';
6
7
  import { reduceAnyCompletedFetchState } from '../../commonStateTypes/reduceFetchState';
7
8
  import { toTimeframeTick, } from '../../commonStateTypes/timeframeTick';
@@ -9,7 +10,6 @@ import { extractThisPeriod } from '../../commonStateTypes/viewAndReport/thisPeri
9
10
  import { getBalanceSheet } from '../balanceSheet/balanceSheetSelector';
10
11
  import { getCashFlow } from '../cashFlow/cashFlowSelector';
11
12
  import { getProfitAndLossReport, } from '../profitAndLoss/profitAndLossSelector';
12
- import { newBalancesFilterProjectView } from '../../commonStateTypes/coaBalance/coaBalancesFilterProjectView';
13
13
  import { getProfitAndLossClassesHorizontalView } from '../profitAndLossClassesView/profitAndLossClassesByClassHorizontalSelector';
14
14
  import { getProfitAndLossClassesView } from '../profitAndLossClassesView/profitAndLossClassesViewSelector';
15
15
  import { getProfitAndLossProjectView } from '../profitAndLossProjectView/profitAndLossProjectViewSelector';
@@ -0,0 +1,87 @@
1
+ import { concat, of, timer } from 'rxjs';
2
+ import { catchError, debounce, filter, groupBy, mergeMap, switchMap, } from 'rxjs/operators';
3
+ import { getIsAccountingClassesEnabled } from '../../entity/tenant/tenantSelector';
4
+ import { getTransactionWithCOT, getTransactionWithCOTFromRecommendations, } from '../../entity/transaction/transactionHelper';
5
+ import { createZeniAPIStatus, isSuccessResponse } from '../../responsePayload';
6
+ import { getUncategorizedAccounts } from '../accountList/accountListSelector';
7
+ import { markCategoryClassRecommendationsCompletedForCategorization, markCategoryClassRecommendationsFailureForCategorization, markCategoryClassRecommendationsInProgressForCategorization, setEntityRecommendationForLineIdsForCategorization, } from '../expenseAutomationView/reducers/transactionsViewReducer';
8
+ import { markCategoryClassRecommendationsCompletedForTransactionDetail, markCategoryClassRecommendationsFailureForTransactionDetail, markCategoryClassRecommendationsInProgressForTransactionDetail, setEntityRecommendationForLineIdsForTransactionDetail, } from '../transactionDetail/transactionDetailReducer';
9
+ import { buildRecommendationUrl, getRecommendationByLineIdWithCOTFromRecommendationPayloadWithCOT, } from './recommendationHelper';
10
+ import { fetchEntityRecommendationsForLineUpdate } from './recommendationReducer';
11
+ // Close the per-target groupBy bucket after this much idle time so inactive
12
+ // groups don't accumulate forever (each group holds a Subject + a chain of
13
+ // active subscribers; without a duration selector groupBy retains them for
14
+ // the lifetime of the source observable, which is the lifetime of the app).
15
+ // Picked at 60s to leave a generous window for re-fetches on the same
16
+ // payee/transaction/line target while still bounding memory.
17
+ const GROUP_INACTIVITY_TIMEOUT_MS = 60000;
18
+ // Build the groupBy key. Same flow + same transaction + same line set
19
+ // share a target so switchMap can cancel an in-flight prior fetch. Use
20
+ // NUL (\u0000) as separator because it can never appear in transaction
21
+ // or line ids (vs the `|` used in an earlier WIP which collides with
22
+ // pipe-delimited synthetic ids).
23
+ const SEPARATOR = '\u0000';
24
+ const toGroupKey = (flowType, transactionId, lineIds) => `${flowType}${SEPARATOR}${transactionId}${SEPARATOR}${[...lineIds]
25
+ .sort((a, b) => a.localeCompare(b))
26
+ .join(SEPARATOR)}`;
27
+ // Targeted recommendations fetch that drives the per-line skeleton, the
28
+ // list-page row-checkbox uncheck/recheck, and the page-level Save
29
+ // disable.
30
+ //
31
+ // Concurrency model:
32
+ // - groupBy by (flowType, transactionId, sorted lineIds) so distinct
33
+ // targets run in parallel.
34
+ // - inside each group, switchMap so a re-fetch on the SAME target
35
+ // cancels any prior in-flight request for that target.
36
+ // - groupBy duration selector closes idle groups to bound memory.
37
+ export const fetchEntityRecommendationsForLineUpdateEpic = (actions$, state$, zeniAPI) => actions$.pipe(filter(fetchEntityRecommendationsForLineUpdate.match), groupBy((action) => toGroupKey(action.payload.flowType, action.payload.transactionDetails.transactionId.id, action.payload.transactionDetails.lineIds), undefined, (group$) => group$.pipe(debounce(() => timer(GROUP_INACTIVITY_TIMEOUT_MS)))), mergeMap((group$) => group$.pipe(switchMap((action) => {
38
+ const payload = action.payload;
39
+ const { transactionId, transaction, lineIds } = payload.transactionDetails;
40
+ const { entity, amount, isFetchCOT, isUncategorizedExpenseCategoryEnabled, } = payload;
41
+ // Synchronously emit the start arm so the per-line skeleton +
42
+ // row uncheck happen before the HTTP request begins. The
43
+ // discriminated-union payload narrows `payload.selectedTab` to
44
+ // a non-optional `TransactionsTab` inside the `'categorization'`
45
+ // branch, so no defensive fallthrough is needed.
46
+ const startAction = payload.flowType === 'categorization'
47
+ ? markCategoryClassRecommendationsInProgressForCategorization(payload.selectedTab, transactionId, lineIds)
48
+ : markCategoryClassRecommendationsInProgressForTransactionDetail(transactionId, lineIds);
49
+ const url = buildRecommendationUrl(zeniAPI.apiEndPoints.accountMicroServiceBaseUrl, entity, amount, payload.transactionDetails, isFetchCOT === true);
50
+ const httpStream$ = zeniAPI
51
+ .getJSON(url)
52
+ .pipe(mergeMap((response) => {
53
+ if (!isSuccessResponse(response) || response.data == null) {
54
+ return of(payload.flowType === 'categorization'
55
+ ? markCategoryClassRecommendationsFailureForCategorization(payload.selectedTab, transactionId, lineIds, response.status)
56
+ : markCategoryClassRecommendationsFailureForTransactionDetail(transactionId, lineIds, response.status));
57
+ }
58
+ const recommendationWithCOTByLineId = getRecommendationByLineIdWithCOTFromRecommendationPayloadWithCOT(response.data.recommendations, lineIds);
59
+ // HTTP 200 with no per-line recommendations: NOT an error.
60
+ // Flip lines to Completed so the skeleton resolves and
61
+ // downstream UI can treat this as "we tried, nothing to
62
+ // apply".
63
+ if (recommendationWithCOTByLineId == null) {
64
+ return of(payload.flowType === 'categorization'
65
+ ? markCategoryClassRecommendationsCompletedForCategorization(payload.selectedTab, transactionId, lineIds)
66
+ : markCategoryClassRecommendationsCompletedForTransactionDetail(transactionId, lineIds));
67
+ }
68
+ const transactionWithCOT = isFetchCOT === true
69
+ ? getTransactionWithCOTFromRecommendations(transaction, recommendationWithCOTByLineId)
70
+ : getTransactionWithCOT(transaction);
71
+ const uncategorizedIncomeExpense = getUncategorizedAccounts(state$.value.accountState, state$.value.accountListState, 'accountList');
72
+ if (payload.flowType === 'categorization') {
73
+ return of(setEntityRecommendationForLineIdsForCategorization(payload.selectedTab, transactionId, transactionWithCOT, lineIds, entity, amount, recommendationWithCOTByLineId, uncategorizedIncomeExpense, isUncategorizedExpenseCategoryEnabled, getIsAccountingClassesEnabled(state$.value)));
74
+ }
75
+ return of(setEntityRecommendationForLineIdsForTransactionDetail(transactionId, transactionWithCOT, lineIds, entity, amount, recommendationWithCOTByLineId, uncategorizedIncomeExpense));
76
+ }), catchError((error) => {
77
+ const errorMessage = 'fetchEntityRecommendationsForLineUpdate failed: ' +
78
+ (error instanceof Error
79
+ ? error.message
80
+ : JSON.stringify(error));
81
+ const status = createZeniAPIStatus('Unexpected Error', errorMessage);
82
+ return of(payload.flowType === 'categorization'
83
+ ? markCategoryClassRecommendationsFailureForCategorization(payload.selectedTab, transactionId, lineIds, status)
84
+ : markCategoryClassRecommendationsFailureForTransactionDetail(transactionId, lineIds, status));
85
+ }));
86
+ return concat(of(startAction), httpStream$);
87
+ }))));