@zeniai/client-epic-state 5.0.73 → 5.0.75

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 (69) hide show
  1. package/lib/commonStateTypes/filterPrimitives.d.ts +23 -0
  2. package/lib/commonStateTypes/filterPrimitives.js +21 -0
  3. package/lib/entity/account/accountSelector.d.ts +26 -0
  4. package/lib/entity/account/accountSelector.js +47 -1
  5. package/lib/entity/account/accountState.d.ts +5 -0
  6. package/lib/entity/account/accountState.js +11 -4
  7. package/lib/entity/class/classSelector.d.ts +35 -0
  8. package/lib/entity/class/classSelector.js +50 -0
  9. package/lib/epic.d.ts +2 -1
  10. package/lib/epic.js +2 -1
  11. package/lib/esm/commonStateTypes/filterPrimitives.js +20 -0
  12. package/lib/esm/entity/account/accountSelector.js +46 -1
  13. package/lib/esm/entity/account/accountState.js +7 -1
  14. package/lib/esm/entity/class/classSelector.js +48 -0
  15. package/lib/esm/epic.js +2 -1
  16. package/lib/esm/index.js +14 -8
  17. package/lib/esm/view/companyHealthMetricView/companyHealthMetricViewSelector.js +1 -1
  18. package/lib/esm/view/companyView/helpers/cockpitHelpers.js +1 -1
  19. package/lib/esm/view/companyView/selector/companyManagementViewSelector.js +1 -1
  20. package/lib/esm/view/companyView/selector/companyPortfolioViewSelector.js +1 -1
  21. package/lib/esm/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.js +21 -1
  22. package/lib/esm/view/expenseAutomationView/reducers/transactionsViewReducer.js +127 -14
  23. package/lib/esm/view/expenseAutomationView/selectors/transactionCategorizationSelector.js +127 -12
  24. package/lib/esm/view/expenseAutomationView/transactionFilterHelpers.js +258 -0
  25. package/lib/esm/view/recommendation/fetchEntityRecommendationsForLineUpdateEpic.js +87 -0
  26. package/lib/esm/view/recommendation/recommendationHelper.js +29 -0
  27. package/lib/esm/view/recommendation/recommendationReducer.js +26 -1
  28. package/lib/esm/view/spendManagement/spendManagementFilterHelpers.js +4 -2
  29. package/lib/esm/view/subscriptionView/subscriptionViewSelector.js +1 -1
  30. package/lib/esm/view/taskManager/taskListView/taskListReducer.js +1 -1
  31. package/lib/esm/view/transactionDetail/transactionDetailReducer.js +121 -6
  32. package/lib/esm/view/transactionDetail/transactionDetailSelector.js +22 -0
  33. package/lib/index.d.ts +12 -9
  34. package/lib/index.js +44 -32
  35. package/lib/view/companyHealthMetricView/companyHealthMetricViewSelector.js +1 -1
  36. package/lib/view/companyView/helpers/cockpitHelpers.js +1 -1
  37. package/lib/view/companyView/selector/companyManagementViewSelector.js +1 -1
  38. package/lib/view/companyView/selector/companyPortfolioViewSelector.js +1 -1
  39. package/lib/view/companyView/types/cockpitTypes.d.ts +1 -1
  40. package/lib/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.d.ts +1 -0
  41. package/lib/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.js +23 -2
  42. package/lib/view/expenseAutomationView/reducers/transactionsViewReducer.d.ts +19 -2
  43. package/lib/view/expenseAutomationView/reducers/transactionsViewReducer.js +127 -14
  44. package/lib/view/expenseAutomationView/selectorTypes/transactionsViewSelectorTypes.d.ts +2 -0
  45. package/lib/view/expenseAutomationView/selectors/transactionCategorizationSelector.d.ts +7 -1
  46. package/lib/view/expenseAutomationView/selectors/transactionCategorizationSelector.js +130 -12
  47. package/lib/view/expenseAutomationView/transactionFilterHelpers.d.ts +66 -0
  48. package/lib/view/expenseAutomationView/transactionFilterHelpers.js +262 -0
  49. package/lib/view/expenseAutomationView/types/transactionsViewState.d.ts +3 -0
  50. package/lib/view/recommendation/fetchEntityRecommendationsForLineUpdateEpic.d.ts +9 -0
  51. package/lib/view/recommendation/fetchEntityRecommendationsForLineUpdateEpic.js +91 -0
  52. package/lib/view/recommendation/recommendationHelper.d.ts +9 -0
  53. package/lib/view/recommendation/recommendationHelper.js +31 -1
  54. package/lib/view/recommendation/recommendationReducer.d.ts +20 -1
  55. package/lib/view/recommendation/recommendationReducer.js +27 -2
  56. package/lib/view/spendManagement/billPay/billList/billListState.d.ts +1 -1
  57. package/lib/view/spendManagement/chargeCards/chargeCardPaymentHistory/chargeCardPaymentHistory.d.ts +1 -1
  58. package/lib/view/spendManagement/reimbursement/remiListView/remiListState.d.ts +1 -1
  59. package/lib/view/spendManagement/spendManagementFilterHelpers.d.ts +12 -3
  60. package/lib/view/spendManagement/spendManagementFilterHelpers.js +4 -2
  61. package/lib/view/subscriptionView/subscriptionViewSelector.js +1 -1
  62. package/lib/view/taskManager/taskListView/taskList.d.ts +1 -1
  63. package/lib/view/taskManager/taskListView/taskListReducer.js +1 -1
  64. package/lib/view/transactionDetail/transactionDetailReducer.d.ts +11 -1
  65. package/lib/view/transactionDetail/transactionDetailReducer.js +122 -7
  66. package/lib/view/transactionDetail/transactionDetailSelector.d.ts +2 -0
  67. package/lib/view/transactionDetail/transactionDetailSelector.js +24 -1
  68. package/lib/view/transactionDetail/transactionDetailTypes.d.ts +1 -0
  69. package/package.json +1 -1
@@ -3,7 +3,7 @@ import recordGet from 'lodash/get';
3
3
  import uniq from 'lodash/uniq';
4
4
  import { toMonthYearPeriodId, } from '../../../commonStateTypes/timePeriod';
5
5
  import { isVendorTransaction } from '../../../entity/transaction/stateTypes/vendorTransaction';
6
- import { MAX_SELECTION_LIMIT, checkIfAllLineItemsAreCategoryClassFilled, filterAutoTabLineItems, mergeTabSpecificLineItems, removeTransactionFromTabView, setEntityRecommendationForLineIdInLocalData, toSetAllLineItemsToCategoryClass, toTransactionDetailLocalData, } from '../helpers/transactionCategorizationLocalDataHelper';
6
+ import { filterAutoTabLineItems, mergeTabSpecificLineItems, removeTransactionFromTabView, setEntityRecommendationForLineIdInLocalData, shouldAutoSelectAndAdd, toSetAllLineItemsToCategoryClass, toTransactionDetailLocalData, } from '../helpers/transactionCategorizationLocalDataHelper';
7
7
  import { DEFAULT_COMPLETED_SUB_TAB, } from '../types/completedSubTab';
8
8
  export const initialTransactionTabViewState = {
9
9
  saveStatus: {
@@ -28,6 +28,10 @@ export const initialTransactionTabViewState = {
28
28
  totalCount: {},
29
29
  limit: 10,
30
30
  },
31
+ filters: {
32
+ categoryCombinationOperator: 'AND',
33
+ categories: [],
34
+ },
31
35
  fetchState: 'Not-Started',
32
36
  error: undefined,
33
37
  hasValidState() {
@@ -299,6 +303,12 @@ const expenseAutomationTransactionsView = createSlice({
299
303
  uiState.totalCount;
300
304
  }
301
305
  },
306
+ updateTransactionFilters(draft, action) {
307
+ const { selectedTab, filters } = action.payload;
308
+ // `filters` is non-nullable per the payload type, so no runtime
309
+ // null-check is needed — dropping it removes a dead defensive branch.
310
+ draft.transactionCategorizationView[selectedTab].filters = filters;
311
+ },
302
312
  saveTransactionCategorization: {
303
313
  prepare(selectedTab, transactionIds, cotTrackingByTransactionId, isUncategorizedExpenseCategoryEnabled) {
304
314
  return {
@@ -420,12 +430,9 @@ const expenseAutomationTransactionsView = createSlice({
420
430
  const selectedCheckBoxTransactionIds = draft.transactionCategorizationView[selectedTab]
421
431
  .selectedCheckBoxTransactionIds;
422
432
  if (selectedTransaction != null &&
423
- checkIfAllLineItemsAreCategoryClassFilled(selectedTransaction, newTransactionLocalData, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled) === true && // check if all line items are filled
424
- selectedCheckBoxTransactionIds.length < MAX_SELECTION_LIMIT &&
425
- selectedCheckBoxTransactionIds.includes(transactionId) === false) {
433
+ shouldAutoSelectAndAdd(selectedTransaction, newTransactionLocalData, selectedCheckBoxTransactionIds, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled)) {
426
434
  draft.transactionCategorizationView[selectedTab].selectedCheckBoxTransactionIds = [
427
- ...draft.transactionCategorizationView[selectedTab]
428
- .selectedCheckBoxTransactionIds,
435
+ ...selectedCheckBoxTransactionIds,
429
436
  transactionId,
430
437
  ];
431
438
  }
@@ -508,9 +515,26 @@ const expenseAutomationTransactionsView = createSlice({
508
515
  const transactionLocalData = recordGet(draft.transactionCategorizationView[selectedTab]
509
516
  .transactionReviewLocalDataById, transactionId.id, undefined);
510
517
  if (transactionLocalData != null) {
518
+ const newLocalData = setEntityRecommendationForLineIdInLocalData(draft.transactionCategorizationView[selectedTab], transaction, transactionLocalData.transactionReviewLocalData, entity, lineIds, uncategorizedAccounts, action.payload.recommendationWithCOTByLineId, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled);
519
+ // Release the per-line fetch flag for every line this fetch
520
+ // covered. Done in-place on the freshly returned local data
521
+ // (the helper produces a new mutable object), before we write
522
+ // it back to the draft.
523
+ lineIds.forEach((lineId) => {
524
+ const lineItem = newLocalData.lineItemById[lineId];
525
+ if (lineItem != null) {
526
+ newLocalData.lineItemById[lineId] = {
527
+ ...lineItem,
528
+ categoryClassRecommendationsFetchState: {
529
+ fetchState: 'Completed',
530
+ error: undefined,
531
+ },
532
+ };
533
+ }
534
+ });
511
535
  draft.transactionCategorizationView[selectedTab].transactionReviewLocalDataById[transaction.id] = {
512
536
  transactionId: transaction.id,
513
- transactionReviewLocalData: setEntityRecommendationForLineIdInLocalData(draft.transactionCategorizationView[selectedTab], transaction, transactionLocalData.transactionReviewLocalData, entity, lineIds, uncategorizedAccounts, action.payload.recommendationWithCOTByLineId, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled),
537
+ transactionReviewLocalData: newLocalData,
514
538
  };
515
539
  // Mark transaction as dirty (autofill happened)
516
540
  if (!draft.transactionCategorizationView[selectedTab].transactionIdsWithUnsavedData.includes(transaction.id)) {
@@ -523,6 +547,99 @@ const expenseAutomationTransactionsView = createSlice({
523
547
  }
524
548
  },
525
549
  },
550
+ // Start arm of the line-update recommendations fetch. Flips covered
551
+ // lines to In-Progress AND removes the transaction from
552
+ // selectedCheckBoxTransactionIds — the row is unchecked + disabled
553
+ // until either the success arm (recheck if limit allows) or the
554
+ // failure arm releases the per-line flag.
555
+ markCategoryClassRecommendationsInProgressForCategorization: {
556
+ reducer(draft, action) {
557
+ const { selectedTab, transactionId, lineIds } = action.payload;
558
+ const tab = draft.transactionCategorizationView[selectedTab];
559
+ const transactionLocalData = recordGet(tab.transactionReviewLocalDataById, transactionId.id, undefined);
560
+ if (transactionLocalData != null) {
561
+ lineIds.forEach((lineId) => {
562
+ const lineItem = transactionLocalData.transactionReviewLocalData.lineItemById[lineId];
563
+ if (lineItem != null) {
564
+ transactionLocalData.transactionReviewLocalData.lineItemById[lineId] = {
565
+ ...lineItem,
566
+ categoryClassRecommendationsFetchState: {
567
+ fetchState: 'In-Progress',
568
+ error: undefined,
569
+ },
570
+ };
571
+ }
572
+ });
573
+ }
574
+ // Uncheck on fetch start: the row's existing category/class are
575
+ // stale after a payee change, so we drop the auto-selection until
576
+ // fresh recommendations land.
577
+ if (tab.selectedCheckBoxTransactionIds.includes(transactionId.id)) {
578
+ tab.selectedCheckBoxTransactionIds =
579
+ tab.selectedCheckBoxTransactionIds.filter((id) => id !== transactionId.id);
580
+ }
581
+ },
582
+ prepare(selectedTab, transactionId, lineIds) {
583
+ return { payload: { selectedTab, transactionId, lineIds } };
584
+ },
585
+ },
586
+ // Completed arm. Used by the epic when the HTTP call succeeds but the
587
+ // server returned no per-line recommendations — we still need to
588
+ // release the In-Progress flag so the skeleton resolves. Successful
589
+ // responses with recommendations go through
590
+ // setEntityRecommendationForLineIdsForCategorization instead (which
591
+ // also flips the lines to Completed).
592
+ markCategoryClassRecommendationsCompletedForCategorization: {
593
+ reducer(draft, action) {
594
+ const { selectedTab, transactionId, lineIds } = action.payload;
595
+ const transactionLocalData = recordGet(draft.transactionCategorizationView[selectedTab]
596
+ .transactionReviewLocalDataById, transactionId.id, undefined);
597
+ if (transactionLocalData != null) {
598
+ lineIds.forEach((lineId) => {
599
+ const lineItem = transactionLocalData.transactionReviewLocalData.lineItemById[lineId];
600
+ if (lineItem != null) {
601
+ transactionLocalData.transactionReviewLocalData.lineItemById[lineId] = {
602
+ ...lineItem,
603
+ categoryClassRecommendationsFetchState: {
604
+ fetchState: 'Completed',
605
+ error: undefined,
606
+ },
607
+ };
608
+ }
609
+ });
610
+ }
611
+ },
612
+ prepare(selectedTab, transactionId, lineIds) {
613
+ return { payload: { selectedTab, transactionId, lineIds } };
614
+ },
615
+ },
616
+ // Failure arm. Flips covered lines to Error so the skeleton resolves
617
+ // and downstream UI can react to the failure. The transaction stays
618
+ // unchecked from the start-arm action.
619
+ markCategoryClassRecommendationsFailureForCategorization: {
620
+ reducer(draft, action) {
621
+ const { selectedTab, transactionId, lineIds, error } = action.payload;
622
+ const transactionLocalData = recordGet(draft.transactionCategorizationView[selectedTab]
623
+ .transactionReviewLocalDataById, transactionId.id, undefined);
624
+ if (transactionLocalData != null) {
625
+ lineIds.forEach((lineId) => {
626
+ const lineItem = transactionLocalData.transactionReviewLocalData.lineItemById[lineId];
627
+ if (lineItem != null) {
628
+ transactionLocalData.transactionReviewLocalData.lineItemById[lineId] = {
629
+ ...lineItem,
630
+ categoryClassRecommendationsFetchState: {
631
+ fetchState: 'Error',
632
+ error,
633
+ },
634
+ };
635
+ }
636
+ });
637
+ }
638
+ },
639
+ prepare(selectedTab, transactionId, lineIds, error) {
640
+ return { payload: { selectedTab, transactionId, lineIds, error } };
641
+ },
642
+ },
526
643
  fetchTransactionCategorizationSuccess(draft, action) {
527
644
  const { selectedTab, refreshViewInBackground } = action.payload;
528
645
  if (draft.transactionCategorizationView[selectedTab].fetchState ===
@@ -618,9 +735,7 @@ const expenseAutomationTransactionsView = createSlice({
618
735
  .selectedCheckBoxTransactionIds;
619
736
  if (newTransactionLocalData.customer != null &&
620
737
  newTransactionLocalData.customer.id != null &&
621
- checkIfAllLineItemsAreCategoryClassFilled(selectedTransaction, newTransactionLocalData, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled) === true && // check if all line items are filled
622
- selectedCheckBoxTransactionIds.length < MAX_SELECTION_LIMIT &&
623
- selectedCheckBoxTransactionIds.includes(transactionId) === false) {
738
+ shouldAutoSelectAndAdd(selectedTransaction, newTransactionLocalData, selectedCheckBoxTransactionIds, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled)) {
624
739
  draft.transactionCategorizationView[selectedTab].selectedCheckBoxTransactionIds = [
625
740
  ...selectedCheckBoxTransactionIds,
626
741
  transactionId,
@@ -694,9 +809,7 @@ const expenseAutomationTransactionsView = createSlice({
694
809
  .selectedCheckBoxTransactionIds;
695
810
  if (newTransactionLocalData.vendor != null &&
696
811
  newTransactionLocalData.vendor.id != null &&
697
- checkIfAllLineItemsAreCategoryClassFilled(selectedTransaction, newTransactionLocalData, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled) === true && // check if all line items are filled
698
- selectedCheckBoxTransactionIds.length < MAX_SELECTION_LIMIT &&
699
- selectedCheckBoxTransactionIds.includes(transactionId) === false) {
812
+ shouldAutoSelectAndAdd(selectedTransaction, newTransactionLocalData, selectedCheckBoxTransactionIds, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled)) {
700
813
  draft.transactionCategorizationView[selectedTab].selectedCheckBoxTransactionIds = [
701
814
  ...selectedCheckBoxTransactionIds,
702
815
  transactionId,
@@ -929,5 +1042,5 @@ const expenseAutomationTransactionsView = createSlice({
929
1042
  },
930
1043
  },
931
1044
  });
932
- export const { fetchTransactionCategorization, updateTransactionCategorizationUIState, initializeTransactionCategorizationViewLocalData, saveTransactionCategorizationLocalData, fetchTransactionCategorizationFailure, saveTransactionCategorization, updateTransactionCategorization, updateCurrentSelectedTransactionCategorizationTab, updateTransactionCategorizationCompletedSubTab, updateTransactionCategorizationSaveStatus, markTransactionAsNotMiscategorized, updateStatusForTransactionNotMiscategorizedUpdateForCategorization, updateSelectedVendorForTransaction, updateSelectedCustomerForTransaction, setAllItemsToCategoryClassInLocalDataForCategorization, updateTotalCountForTransactionCategorization, updateParentTotalCountForTab, fetchTransactionCategorizationSuccess, resetOtherTabsFetchState, fetchTransactionCategorizationView, updateSelectedCheckboxTransactionIds, clearExpenseAutomationTransactionsViewPerTabView, clearExpenseAutomationTransactionsView, setEntityRecommendationForLineIdsForCategorization, updateSelectedTransactionId, syncTransactionCategorizationFromDetailSave, backgroundRefetchReviewTab, updateTransactionCategorizationUploadReceiptState, uploadTransactionCategorizationReceiptSuccess, } = expenseAutomationTransactionsView.actions;
1045
+ export const { fetchTransactionCategorization, updateTransactionCategorizationUIState, updateTransactionFilters, initializeTransactionCategorizationViewLocalData, saveTransactionCategorizationLocalData, fetchTransactionCategorizationFailure, saveTransactionCategorization, updateTransactionCategorization, updateCurrentSelectedTransactionCategorizationTab, updateTransactionCategorizationCompletedSubTab, updateTransactionCategorizationSaveStatus, markTransactionAsNotMiscategorized, updateStatusForTransactionNotMiscategorizedUpdateForCategorization, updateSelectedVendorForTransaction, updateSelectedCustomerForTransaction, setAllItemsToCategoryClassInLocalDataForCategorization, updateTotalCountForTransactionCategorization, updateParentTotalCountForTab, fetchTransactionCategorizationSuccess, resetOtherTabsFetchState, fetchTransactionCategorizationView, updateSelectedCheckboxTransactionIds, clearExpenseAutomationTransactionsViewPerTabView, clearExpenseAutomationTransactionsView, setEntityRecommendationForLineIdsForCategorization, markCategoryClassRecommendationsInProgressForCategorization, markCategoryClassRecommendationsCompletedForCategorization, markCategoryClassRecommendationsFailureForCategorization, updateSelectedTransactionId, syncTransactionCategorizationFromDetailSave, backgroundRefetchReviewTab, updateTransactionCategorizationUploadReceiptState, uploadTransactionCategorizationReceiptSuccess, } = expenseAutomationTransactionsView.actions;
933
1046
  export default expenseAutomationTransactionsView.reducer;
@@ -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
86
  const { selectedTransactionCategorizationCompletedSubTab, selectedTransactionCategorizationTab, } = expenseAutomationTransactionsViewState;
14
- const { uiState, refreshStatus, saveStatus, markAsNotMiscategorizedStatus, transactionIdsBySelectedPeriod, transactionReviewLocalDataById, selectedCheckBoxTransactionIds, transactionIdsWithUnsavedData, uploadReceiptStatusById, selectedTransactionId, selectedTransactionLineId, } = expenseAutomationTransactionsViewState.transactionCategorizationView[selectedTransactionCategorizationTab];
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 };
@@ -103,11 +214,13 @@ export function getExpenseAutomationTransactionView(state) {
103
214
  : [];
104
215
  const transactionCompletionStatus = allSteps.find((step) => step.step === 'transaction_categorization')?.completionStatus;
105
216
  const completionStatus = transactionCompletionStatus ?? 'incomplete';
217
+ const inFlightCategoryClassRecommendationsByTransactionId = getCategorizationInFlightRecommendationsByTransactionId(state);
218
+ const hasInFlightCategoryClassRecommendations = getCategorizationHasInFlightRecommendations(state);
106
219
  return {
107
220
  version: 0,
108
221
  fetchState: fetchStatus.fetchState,
109
222
  error: fetchStatus.error,
110
- transactions: transactionsWithCOT,
223
+ transactions: filteredTransactionsWithCOT,
111
224
  selectedCheckBoxTransactionIds,
112
225
  transactionIdsWithUnsavedData,
113
226
  uncategorizedAccounts: uncategorizedIncomeExpense,
@@ -116,9 +229,11 @@ export function getExpenseAutomationTransactionView(state) {
116
229
  classList: allClasses,
117
230
  accountsHierarchyList,
118
231
  classHierarchyList,
232
+ hasInFlightCategoryClassRecommendations,
233
+ inFlightCategoryClassRecommendationsByTransactionId,
119
234
  isAccountingProjectsEnabled,
120
235
  projectList,
121
- transactionLocalData,
236
+ transactionLocalData: filteredTransactionLocalData,
122
237
  uiState,
123
238
  refreshStatus,
124
239
  saveStatus,
@@ -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
+ };