@zeniai/client-epic-state 5.0.74 → 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 (34) hide show
  1. package/lib/epic.d.ts +2 -1
  2. package/lib/epic.js +2 -1
  3. package/lib/esm/epic.js +2 -1
  4. package/lib/esm/index.js +6 -6
  5. package/lib/esm/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.js +21 -1
  6. package/lib/esm/view/expenseAutomationView/reducers/transactionsViewReducer.js +117 -14
  7. package/lib/esm/view/expenseAutomationView/selectors/transactionCategorizationSelector.js +58 -0
  8. package/lib/esm/view/recommendation/fetchEntityRecommendationsForLineUpdateEpic.js +87 -0
  9. package/lib/esm/view/recommendation/recommendationHelper.js +29 -0
  10. package/lib/esm/view/recommendation/recommendationReducer.js +26 -1
  11. package/lib/esm/view/transactionDetail/transactionDetailReducer.js +121 -6
  12. package/lib/esm/view/transactionDetail/transactionDetailSelector.js +22 -0
  13. package/lib/index.d.ts +7 -6
  14. package/lib/index.js +35 -32
  15. package/lib/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.d.ts +1 -0
  16. package/lib/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.js +23 -2
  17. package/lib/view/expenseAutomationView/reducers/transactionsViewReducer.d.ts +14 -1
  18. package/lib/view/expenseAutomationView/reducers/transactionsViewReducer.js +117 -14
  19. package/lib/view/expenseAutomationView/selectorTypes/transactionsViewSelectorTypes.d.ts +2 -0
  20. package/lib/view/expenseAutomationView/selectors/transactionCategorizationSelector.d.ts +3 -0
  21. package/lib/view/expenseAutomationView/selectors/transactionCategorizationSelector.js +60 -1
  22. package/lib/view/expenseAutomationView/types/transactionsViewState.d.ts +1 -0
  23. package/lib/view/recommendation/fetchEntityRecommendationsForLineUpdateEpic.d.ts +9 -0
  24. package/lib/view/recommendation/fetchEntityRecommendationsForLineUpdateEpic.js +91 -0
  25. package/lib/view/recommendation/recommendationHelper.d.ts +9 -0
  26. package/lib/view/recommendation/recommendationHelper.js +31 -1
  27. package/lib/view/recommendation/recommendationReducer.d.ts +20 -1
  28. package/lib/view/recommendation/recommendationReducer.js +27 -2
  29. package/lib/view/transactionDetail/transactionDetailReducer.d.ts +11 -1
  30. package/lib/view/transactionDetail/transactionDetailReducer.js +122 -7
  31. package/lib/view/transactionDetail/transactionDetailSelector.d.ts +2 -0
  32. package/lib/view/transactionDetail/transactionDetailSelector.js +24 -1
  33. package/lib/view/transactionDetail/transactionDetailTypes.d.ts +1 -0
  34. 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: {
@@ -430,12 +430,9 @@ const expenseAutomationTransactionsView = createSlice({
430
430
  const selectedCheckBoxTransactionIds = draft.transactionCategorizationView[selectedTab]
431
431
  .selectedCheckBoxTransactionIds;
432
432
  if (selectedTransaction != null &&
433
- checkIfAllLineItemsAreCategoryClassFilled(selectedTransaction, newTransactionLocalData, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled) === true && // check if all line items are filled
434
- selectedCheckBoxTransactionIds.length < MAX_SELECTION_LIMIT &&
435
- selectedCheckBoxTransactionIds.includes(transactionId) === false) {
433
+ shouldAutoSelectAndAdd(selectedTransaction, newTransactionLocalData, selectedCheckBoxTransactionIds, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled)) {
436
434
  draft.transactionCategorizationView[selectedTab].selectedCheckBoxTransactionIds = [
437
- ...draft.transactionCategorizationView[selectedTab]
438
- .selectedCheckBoxTransactionIds,
435
+ ...selectedCheckBoxTransactionIds,
439
436
  transactionId,
440
437
  ];
441
438
  }
@@ -518,9 +515,26 @@ const expenseAutomationTransactionsView = createSlice({
518
515
  const transactionLocalData = recordGet(draft.transactionCategorizationView[selectedTab]
519
516
  .transactionReviewLocalDataById, transactionId.id, undefined);
520
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
+ });
521
535
  draft.transactionCategorizationView[selectedTab].transactionReviewLocalDataById[transaction.id] = {
522
536
  transactionId: transaction.id,
523
- transactionReviewLocalData: setEntityRecommendationForLineIdInLocalData(draft.transactionCategorizationView[selectedTab], transaction, transactionLocalData.transactionReviewLocalData, entity, lineIds, uncategorizedAccounts, action.payload.recommendationWithCOTByLineId, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled),
537
+ transactionReviewLocalData: newLocalData,
524
538
  };
525
539
  // Mark transaction as dirty (autofill happened)
526
540
  if (!draft.transactionCategorizationView[selectedTab].transactionIdsWithUnsavedData.includes(transaction.id)) {
@@ -533,6 +547,99 @@ const expenseAutomationTransactionsView = createSlice({
533
547
  }
534
548
  },
535
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
+ },
536
643
  fetchTransactionCategorizationSuccess(draft, action) {
537
644
  const { selectedTab, refreshViewInBackground } = action.payload;
538
645
  if (draft.transactionCategorizationView[selectedTab].fetchState ===
@@ -628,9 +735,7 @@ const expenseAutomationTransactionsView = createSlice({
628
735
  .selectedCheckBoxTransactionIds;
629
736
  if (newTransactionLocalData.customer != null &&
630
737
  newTransactionLocalData.customer.id != null &&
631
- checkIfAllLineItemsAreCategoryClassFilled(selectedTransaction, newTransactionLocalData, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled) === true && // check if all line items are filled
632
- selectedCheckBoxTransactionIds.length < MAX_SELECTION_LIMIT &&
633
- selectedCheckBoxTransactionIds.includes(transactionId) === false) {
738
+ shouldAutoSelectAndAdd(selectedTransaction, newTransactionLocalData, selectedCheckBoxTransactionIds, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled)) {
634
739
  draft.transactionCategorizationView[selectedTab].selectedCheckBoxTransactionIds = [
635
740
  ...selectedCheckBoxTransactionIds,
636
741
  transactionId,
@@ -704,9 +809,7 @@ const expenseAutomationTransactionsView = createSlice({
704
809
  .selectedCheckBoxTransactionIds;
705
810
  if (newTransactionLocalData.vendor != null &&
706
811
  newTransactionLocalData.vendor.id != null &&
707
- checkIfAllLineItemsAreCategoryClassFilled(selectedTransaction, newTransactionLocalData, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled) === true && // check if all line items are filled
708
- selectedCheckBoxTransactionIds.length < MAX_SELECTION_LIMIT &&
709
- selectedCheckBoxTransactionIds.includes(transactionId) === false) {
812
+ shouldAutoSelectAndAdd(selectedTransaction, newTransactionLocalData, selectedCheckBoxTransactionIds, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled)) {
710
813
  draft.transactionCategorizationView[selectedTab].selectedCheckBoxTransactionIds = [
711
814
  ...selectedCheckBoxTransactionIds,
712
815
  transactionId,
@@ -939,5 +1042,5 @@ const expenseAutomationTransactionsView = createSlice({
939
1042
  },
940
1043
  },
941
1044
  });
942
- 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, 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;
943
1046
  export default expenseAutomationTransactionsView.reducer;
@@ -1,3 +1,4 @@
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';
@@ -9,6 +10,59 @@ import { getAccountList, getNestedAccountListHierarchy, getUncategorizedAccounts
9
10
  import { getClassList, getNestedClassListHierarchy, } from '../../classList/classListSelector';
10
11
  import { getProjectList } from '../../projectList/projectListSelector';
11
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);
12
66
  export const toTransactionView = (transaction, transactionLocalData) => {
13
67
  return {
14
68
  id: transaction.id,
@@ -160,6 +214,8 @@ export function getExpenseAutomationTransactionView(state) {
160
214
  : [];
161
215
  const transactionCompletionStatus = allSteps.find((step) => step.step === 'transaction_categorization')?.completionStatus;
162
216
  const completionStatus = transactionCompletionStatus ?? 'incomplete';
217
+ const inFlightCategoryClassRecommendationsByTransactionId = getCategorizationInFlightRecommendationsByTransactionId(state);
218
+ const hasInFlightCategoryClassRecommendations = getCategorizationHasInFlightRecommendations(state);
163
219
  return {
164
220
  version: 0,
165
221
  fetchState: fetchStatus.fetchState,
@@ -173,6 +229,8 @@ export function getExpenseAutomationTransactionView(state) {
173
229
  classList: allClasses,
174
230
  accountsHierarchyList,
175
231
  classHierarchyList,
232
+ hasInFlightCategoryClassRecommendations,
233
+ inFlightCategoryClassRecommendationsByTransactionId,
176
234
  isAccountingProjectsEnabled,
177
235
  projectList,
178
236
  transactionLocalData: filteredTransactionLocalData,
@@ -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
+ }))));
@@ -1,4 +1,5 @@
1
1
  import { transformRecommendation, transformRecommendationWithCOT, } from '../../entity/transaction/payloadTypes/transactionPayload';
2
+ import { getActualTransactionID } from '../transactionDetail/transactionDetailState';
2
3
  export const getRecommendationFromRecommendationPayload = (payload) => {
3
4
  if (payload == null || payload.length === 0) {
4
5
  return undefined;
@@ -37,6 +38,34 @@ export const getRecommendationWithCOTFromRecommendationPayloadWithCOT = (payload
37
38
  });
38
39
  return recommendations;
39
40
  };
41
+ // Pluralized URL segment for entity types. Mirrors the legacy
42
+ // fetchEntityRecommendationsByTransactionIdEpic.toEntityTypeURL.
43
+ const toEntityTypeUrlSegment = (entityType) => `${entityType}s`;
44
+ // Build the recommendations URL for a single entity + transaction target.
45
+ // Centralizes the URL shape so the legacy
46
+ // fetchEntityRecommendationsByTransactionIdEpic and the new
47
+ // fetchEntityRecommendationsForLineUpdateEpic stay in lockstep.
48
+ export const buildRecommendationUrl = (accountMicroServiceBaseUrl, entity, amount, transactionDetails, isFetchCOT) => {
49
+ const entityQuery = {
50
+ entity_name: entity.name,
51
+ entity_type: entity.type,
52
+ };
53
+ // Entity-id-null case: server expects entity_name / entity_type query
54
+ // instead of the {entityType}/{qboId}/recommendations path.
55
+ if (entity.qboId === entity.name) {
56
+ return `${accountMicroServiceBaseUrl}/1.0/recommendations?query=${encodeURIComponent(JSON.stringify(entityQuery))}`;
57
+ }
58
+ const query = {
59
+ amount,
60
+ transaction_id: getActualTransactionID(transactionDetails.transactionId.id),
61
+ transaction_type: transactionDetails.transaction.type,
62
+ line_ids: transactionDetails.lineIds,
63
+ };
64
+ if (isFetchCOT === true) {
65
+ query.include_cot = true;
66
+ }
67
+ return `${accountMicroServiceBaseUrl}/1.0/${toEntityTypeUrlSegment(entity.type)}/${entity.qboId}/recommendations?query=${encodeURIComponent(JSON.stringify(query))}`;
68
+ };
40
69
  export const getRecommendationByLineIdWithCOTFromRecommendationPayloadWithCOT = (recommendationPayload, lineIds) => {
41
70
  if (recommendationPayload.length === 0) {
42
71
  return undefined;
@@ -33,6 +33,31 @@ const recommendation = createSlice({
33
33
  };
34
34
  },
35
35
  },
36
+ // Targeted recommendations fetch fired when the user changes the
37
+ // payee/customer on a single transaction line (or the JE sibling set
38
+ // for that change). Routed by `fetchEntityRecommendationsForLineUpdateEpic`
39
+ // which uses groupBy + switchMap to keep fetches for distinct targets
40
+ // running in parallel while same-target re-fetches still cancel each
41
+ // other. The flowType discriminator selects the categorization vs
42
+ // detail slice for the per-line In-Progress / Completed / Error state.
43
+ fetchEntityRecommendationsForLineUpdate: {
44
+ reducer(draft, action) {
45
+ const { entity } = action.payload;
46
+ const key = getEntityRecommendationKey(entity.type, entity.id);
47
+ // Unconditional flip to In-Progress; the previous variant only
48
+ // seeded when missing, which left stale fetchStates when a prior
49
+ // fetch had already populated the entity entry.
50
+ draft.recommendationByEntity[key] = {
51
+ ...(draft.recommendationByEntity[key] ??
52
+ initialEntityRecommendationState),
53
+ fetchState: 'In-Progress',
54
+ error: undefined,
55
+ };
56
+ },
57
+ prepare(args) {
58
+ return { payload: args };
59
+ },
60
+ },
36
61
  fetchRecommendationByEntityName: {
37
62
  reducer(draft, action) {
38
63
  const { entityName, entityType } = action.payload;
@@ -111,7 +136,7 @@ const recommendation = createSlice({
111
136
  },
112
137
  },
113
138
  });
114
- export const { fetchEntityRecommendationsByTransactionId, fetchRecommendationByEntityName, fetchRecommendationByEntityId, updateRecommendationForEntity, updateRecommendationForEntityFailure, indicateReadyToInitializeRecommendation, clearRecommendation, } = recommendation.actions;
139
+ export const { fetchEntityRecommendationsByTransactionId, fetchEntityRecommendationsForLineUpdate, fetchRecommendationByEntityName, fetchRecommendationByEntityId, updateRecommendationForEntity, updateRecommendationForEntityFailure, indicateReadyToInitializeRecommendation, clearRecommendation, } = recommendation.actions;
115
140
  export default recommendation.reducer;
116
141
  const doUpdateRecommendationForEntity = (draft, entityId, entityType, payload) => {
117
142
  const key = getEntityRecommendationKey(entityType, entityId);
@@ -238,12 +238,34 @@ const transactionDetail = createSlice({
238
238
  saveTransactionDetailLocalData(draft, action) {
239
239
  const key = getTransactionDetailKey(action.payload.transactionId);
240
240
  const detail = recordGet(draft.transactionDetailById, key, undefined);
241
- if (detail != null) {
242
- draft.transactionDetailById[key] = {
243
- ...detail,
244
- transactionDetailLocalData: action.payload.transactionLocalData,
245
- };
241
+ if (detail == null) {
242
+ return;
246
243
  }
244
+ const incoming = action.payload.transactionLocalData;
245
+ const prevById = detail.transactionDetailLocalData.lineItemById;
246
+ // Per-line `categoryClassRecommendationsFetchState` is owned by the
247
+ // recommendation epic/reducers (markInProgress / markCompleted /
248
+ // markFailure / setEntityRecommendationForLineIdsForTransactionDetail).
249
+ // Callers that rebuild `transactionLocalData` from a UI snapshot will
250
+ // typically have an out-of-date copy of this field (e.g. payee-change
251
+ // captures the snapshot before the epic's start arm runs and would
252
+ // otherwise clobber In-Progress back to undefined). Treat the field as
253
+ // sticky: only let the caller override it when they explicitly set it.
254
+ const mergedLineItemById = {};
255
+ Object.entries(incoming.lineItemById ?? {}).forEach(([lineId, line]) => {
256
+ mergedLineItemById[lineId] = {
257
+ ...line,
258
+ categoryClassRecommendationsFetchState: line.categoryClassRecommendationsFetchState ??
259
+ prevById?.[lineId]?.categoryClassRecommendationsFetchState,
260
+ };
261
+ });
262
+ draft.transactionDetailById[key] = {
263
+ ...detail,
264
+ transactionDetailLocalData: {
265
+ ...incoming,
266
+ lineItemById: mergedLineItemById,
267
+ },
268
+ };
247
269
  },
248
270
  saveTransactionDetail(draft, action) {
249
271
  const key = getTransactionDetailKey(action.payload.transactionId);
@@ -365,6 +387,21 @@ const transactionDetail = createSlice({
365
387
  const detail = recordGet(draft.transactionDetailById, key, undefined);
366
388
  if (detail != null) {
367
389
  const newLocalData = setEntityRecommendationForLineIdInLocalData(transaction, detail.transactionDetailLocalData, action.payload.entity, lineIds, uncategorizedIncomeExpense, recommendationWithCOTByLineId);
390
+ // Release the per-line fetch flag for every line this fetch
391
+ // covered so the inline skeleton resolves and the page-level
392
+ // Save button can re-enable.
393
+ lineIds.forEach((lineId) => {
394
+ const lineItem = newLocalData.lineItemById[lineId];
395
+ if (lineItem != null) {
396
+ newLocalData.lineItemById[lineId] = {
397
+ ...lineItem,
398
+ categoryClassRecommendationsFetchState: {
399
+ fetchState: 'Completed',
400
+ error: undefined,
401
+ },
402
+ };
403
+ }
404
+ });
368
405
  draft.transactionDetailById[key] = {
369
406
  ...detail,
370
407
  transactionDetailLocalData: newLocalData,
@@ -385,6 +422,84 @@ const transactionDetail = createSlice({
385
422
  };
386
423
  },
387
424
  },
425
+ // Start arm of the line-update recommendations fetch for the detail
426
+ // page. Flips covered lines to In-Progress; detail page has no
427
+ // checkbox, so no auto-uncheck side effect.
428
+ markCategoryClassRecommendationsInProgressForTransactionDetail: {
429
+ reducer(draft, action) {
430
+ const { transactionId, lineIds } = action.payload;
431
+ const key = getTransactionDetailKey(transactionId);
432
+ const detail = recordGet(draft.transactionDetailById, key, undefined);
433
+ if (detail != null) {
434
+ lineIds.forEach((lineId) => {
435
+ const lineItem = detail.transactionDetailLocalData.lineItemById[lineId];
436
+ if (lineItem != null) {
437
+ detail.transactionDetailLocalData.lineItemById[lineId] = {
438
+ ...lineItem,
439
+ categoryClassRecommendationsFetchState: {
440
+ fetchState: 'In-Progress',
441
+ error: undefined,
442
+ },
443
+ };
444
+ }
445
+ });
446
+ }
447
+ },
448
+ prepare(transactionId, lineIds) {
449
+ return { payload: { transactionId, lineIds } };
450
+ },
451
+ },
452
+ // Completed arm. Used when the HTTP call succeeded but the server
453
+ // returned no per-line recommendations — still need to release the
454
+ // In-Progress flag.
455
+ markCategoryClassRecommendationsCompletedForTransactionDetail: {
456
+ reducer(draft, action) {
457
+ const { transactionId, lineIds } = action.payload;
458
+ const key = getTransactionDetailKey(transactionId);
459
+ const detail = recordGet(draft.transactionDetailById, key, undefined);
460
+ if (detail != null) {
461
+ lineIds.forEach((lineId) => {
462
+ const lineItem = detail.transactionDetailLocalData.lineItemById[lineId];
463
+ if (lineItem != null) {
464
+ detail.transactionDetailLocalData.lineItemById[lineId] = {
465
+ ...lineItem,
466
+ categoryClassRecommendationsFetchState: {
467
+ fetchState: 'Completed',
468
+ error: undefined,
469
+ },
470
+ };
471
+ }
472
+ });
473
+ }
474
+ },
475
+ prepare(transactionId, lineIds) {
476
+ return { payload: { transactionId, lineIds } };
477
+ },
478
+ },
479
+ markCategoryClassRecommendationsFailureForTransactionDetail: {
480
+ reducer(draft, action) {
481
+ const { transactionId, lineIds, error } = action.payload;
482
+ const key = getTransactionDetailKey(transactionId);
483
+ const detail = recordGet(draft.transactionDetailById, key, undefined);
484
+ if (detail != null) {
485
+ lineIds.forEach((lineId) => {
486
+ const lineItem = detail.transactionDetailLocalData.lineItemById[lineId];
487
+ if (lineItem != null) {
488
+ detail.transactionDetailLocalData.lineItemById[lineId] = {
489
+ ...lineItem,
490
+ categoryClassRecommendationsFetchState: {
491
+ fetchState: 'Error',
492
+ error,
493
+ },
494
+ };
495
+ }
496
+ });
497
+ }
498
+ },
499
+ prepare(transactionId, lineIds, error) {
500
+ return { payload: { transactionId, lineIds, error } };
501
+ },
502
+ },
388
503
  removeEntityRecommendationForLineIdForTransactionDetail: {
389
504
  reducer(draft, action) {
390
505
  const { transaction, lineId } = action.payload;
@@ -656,7 +771,7 @@ const transactionDetail = createSlice({
656
771
  },
657
772
  },
658
773
  });
659
- export const { downloadAccountingProviderAttachment, downloadAccountingProviderAttachmentSuccess, downloadAccountingProviderAttachmentFailure, fetchTransactionDetail, updateTransactionDetailFetchState, removeTransactionDetail, clearTransactionDetail, uploadMissingAttachmentSuccess, updateTransactionDetail, updateTransactionDetailSaveStatus, clearTransactionDetailSaveStatus, markTransactionAsNotMiscategorized, deleteTransactionAttachment, deleteTransactionAttachmentFailure, deleteTransactionAttachmentSuccess, updateStatusForTransactionNotMiscategorizedUpdate, updateStatusConsolidatedSaveTransactionDetail, updateTransactionStateIfUpdateActionNotAllowed, saveTransactionDetail, initializeTransactionDetailLocalData, saveTransactionDetailLocalData, clearTransactionDetailLocalData, resetLineItemsCategoryClassInLocalData, setAllLineItemsToCategoryClassInLocalData, setAllLineItemsLocalDataIsUpdateAllChecked, setEntityRecommendationForLineIdsForTransactionDetail, removeEntityRecommendationForLineIdForTransactionDetail, updateSelectedVendor, updateSelectedCustomer, resetVendor, resetSelectedCustomer, updateLocalDataWithTransactionsUpdateWithVendorCheckbox, updateVendorToAllLineItems, resetAllLineItemsToVendor, updateLatestSelectedEntity, updateVendorBulkRecommendationsFetchStatus, setIsVendorUpdateAllChecked, } = transactionDetail.actions;
774
+ export const { downloadAccountingProviderAttachment, downloadAccountingProviderAttachmentSuccess, downloadAccountingProviderAttachmentFailure, fetchTransactionDetail, updateTransactionDetailFetchState, removeTransactionDetail, clearTransactionDetail, uploadMissingAttachmentSuccess, updateTransactionDetail, updateTransactionDetailSaveStatus, clearTransactionDetailSaveStatus, markTransactionAsNotMiscategorized, deleteTransactionAttachment, deleteTransactionAttachmentFailure, deleteTransactionAttachmentSuccess, updateStatusForTransactionNotMiscategorizedUpdate, updateStatusConsolidatedSaveTransactionDetail, updateTransactionStateIfUpdateActionNotAllowed, saveTransactionDetail, initializeTransactionDetailLocalData, saveTransactionDetailLocalData, clearTransactionDetailLocalData, resetLineItemsCategoryClassInLocalData, setAllLineItemsToCategoryClassInLocalData, setAllLineItemsLocalDataIsUpdateAllChecked, setEntityRecommendationForLineIdsForTransactionDetail, markCategoryClassRecommendationsInProgressForTransactionDetail, markCategoryClassRecommendationsCompletedForTransactionDetail, markCategoryClassRecommendationsFailureForTransactionDetail, removeEntityRecommendationForLineIdForTransactionDetail, updateSelectedVendor, updateSelectedCustomer, resetVendor, resetSelectedCustomer, updateLocalDataWithTransactionsUpdateWithVendorCheckbox, updateVendorToAllLineItems, resetAllLineItemsToVendor, updateLatestSelectedEntity, updateVendorBulkRecommendationsFetchStatus, setIsVendorUpdateAllChecked, } = transactionDetail.actions;
660
775
  export default transactionDetail.reducer;
661
776
  function getUpdatedEntityLocalData(detail, updates, entity, resetRecommendations, type) {
662
777
  const key = type === 'customer' ? 'customerUpdates' : 'vendorUpdates';
@@ -10,6 +10,26 @@ import { getAccountList, getNestedAccountListHierarchy, } from '../accountList/a
10
10
  import { getClassList, getNestedClassListHierarchy, } from '../classList/classListSelector';
11
11
  import { getProjectList, } from '../projectList/projectListSelector';
12
12
  import { getAllLinkedTransactions, getTransactionDetailKey, initialSupportedTransactionDetail, } from './transactionDetailState';
13
+ // "Any line on this transaction is fetching category/class recommendations?"
14
+ // Inlined as a plain function because the upstream selector
15
+ // `getTransactionDetail` is also un-memoized and the iteration is O(lines)
16
+ // — typically <10. Exported standalone so consumers that only need the
17
+ // flag (e.g. footer save-disable) can avoid materializing the whole
18
+ // detail report.
19
+ export const getDetailInFlightRecommendations = (state, transactionId) => {
20
+ const detailKey = getTransactionDetailKey(transactionId);
21
+ const detail = recordGet(state.transactionDetailState.transactionDetailById, detailKey, undefined);
22
+ if (detail == null) {
23
+ return false;
24
+ }
25
+ for (const lineItem of Object.values(detail.transactionDetailLocalData.lineItemById)) {
26
+ if (lineItem.categoryClassRecommendationsFetchState?.fetchState ===
27
+ 'In-Progress') {
28
+ return true;
29
+ }
30
+ }
31
+ return false;
32
+ };
13
33
  export const getTransactionDetail = (state, transactionId, fetchLinkedTransactions = true) => {
14
34
  const { transactionDetailState, transactionState, vendorState, vendorListState, accountState, classState, classListState, accountListState, projectState, projectListState, } = state;
15
35
  const detailKey = getTransactionDetailKey(transactionId);
@@ -78,6 +98,7 @@ export const getTransactionDetail = (state, transactionId, fetchLinkedTransactio
78
98
  : [];
79
99
  const transactionDetailAnyUpdateStatus = reduceUpdateFetchStates(transactionDetail);
80
100
  const vendors = getVendorsByVendorIds(vendorState, vendorListState.vendorIds);
101
+ const hasInFlightCategoryClassRecommendations = getDetailInFlightRecommendations(state, transactionId);
81
102
  return {
82
103
  reportId: 'transaction_detail',
83
104
  reportTitle: 'Transaction Detail',
@@ -93,6 +114,7 @@ export const getTransactionDetail = (state, transactionId, fetchLinkedTransactio
93
114
  classHierarchyList,
94
115
  accountsHierarchyList,
95
116
  classList: classList,
117
+ hasInFlightCategoryClassRecommendations,
96
118
  isAccountingClassesEnabled,
97
119
  isAccountingProjectsEnabled,
98
120
  projectList,