@zeniai/client-epic-state 5.0.64-betaSS1 → 5.0.65-betaML1

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 (35) 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 +137 -21
  7. package/lib/esm/view/expenseAutomationView/selectors/transactionCategorizationSelector.js +28 -0
  8. package/lib/esm/view/recommendation/fetchEntityRecommendationsForLineUpdateEpic.js +78 -0
  9. package/lib/esm/view/recommendation/recommendationHelper.js +29 -0
  10. package/lib/esm/view/recommendation/recommendationReducer.js +36 -1
  11. package/lib/esm/view/transactionDetail/transactionDetailReducer.js +94 -1
  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/tsconfig.typecheck.tsbuildinfo +1 -0
  16. package/lib/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.d.ts +1 -0
  17. package/lib/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.js +23 -2
  18. package/lib/view/expenseAutomationView/reducers/transactionsViewReducer.d.ts +14 -1
  19. package/lib/view/expenseAutomationView/reducers/transactionsViewReducer.js +137 -21
  20. package/lib/view/expenseAutomationView/selectorTypes/transactionsViewSelectorTypes.d.ts +2 -0
  21. package/lib/view/expenseAutomationView/selectors/transactionCategorizationSelector.d.ts +3 -0
  22. package/lib/view/expenseAutomationView/selectors/transactionCategorizationSelector.js +29 -0
  23. package/lib/view/expenseAutomationView/types/transactionsViewState.d.ts +6 -0
  24. package/lib/view/recommendation/fetchEntityRecommendationsForLineUpdateEpic.d.ts +9 -0
  25. package/lib/view/recommendation/fetchEntityRecommendationsForLineUpdateEpic.js +82 -0
  26. package/lib/view/recommendation/recommendationHelper.d.ts +9 -0
  27. package/lib/view/recommendation/recommendationHelper.js +31 -1
  28. package/lib/view/recommendation/recommendationReducer.d.ts +18 -1
  29. package/lib/view/recommendation/recommendationReducer.js +37 -2
  30. package/lib/view/transactionDetail/transactionDetailReducer.d.ts +11 -1
  31. package/lib/view/transactionDetail/transactionDetailReducer.js +95 -2
  32. package/lib/view/transactionDetail/transactionDetailSelector.d.ts +2 -0
  33. package/lib/view/transactionDetail/transactionDetailSelector.js +24 -1
  34. package/lib/view/transactionDetail/transactionDetailTypes.d.ts +1 -0
  35. 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: {
@@ -65,15 +65,20 @@ export const initialState = {
65
65
  *
66
66
  * Snapshot scope (deliberately narrow):
67
67
  * - Captured: `pageToken`, `totalCount`, `transactionIdsBySelectedPeriod`,
68
- * `fetchState`, `error`. These are the keys the fetch epic's cache check
69
- * reads to decide whether to short-circuit a sub-tab revisit.
68
+ * `fetchState`, `error`, `scrollPosition`. The first five are the keys the
69
+ * fetch epic's cache check reads to decide whether to short-circuit a
70
+ * sub-tab revisit; `scrollPosition` is captured per sub-tab so revisiting
71
+ * restores the user's last offset and switching to a never-visited sub-tab
72
+ * starts at the top instead of inheriting the outgoing sub-tab's offset
73
+ * (which would land the user at a meaningless row index against a
74
+ * completely different list).
70
75
  * - Intentionally NOT captured (left in place on `autoCat` and inherited by
71
76
  * the incoming sub-tab):
72
77
  * - `uiState.searchString`, `uiState.sortKey`, `uiState.sortOrder`,
73
- * `uiState.scrollPosition`, `uiState.nodeCollapseState`,
74
- * `uiState.limit` search and sort are user-applied preferences that
75
- * persist across sub-tabs by design (a search query stays active when
76
- * the user toggles between Manual / AI Accountant).
78
+ * `uiState.nodeCollapseState`, `uiState.limit` — search and sort are
79
+ * user-applied preferences that persist across sub-tabs by design (a
80
+ * search query stays active when the user toggles between Manual / AI
81
+ * Accountant).
77
82
  * - `selectedCheckBoxTransactionIds` — selection state is intentionally
78
83
  * cleared at the action source (the fetch epic / save flow), not
79
84
  * by the snapshot path. Carrying selection across sub-tabs is safe
@@ -100,6 +105,7 @@ function snapshotAutoCategorizedTab(autoCat) {
100
105
  error: autoCat.error,
101
106
  fetchState: normalisedFetchState,
102
107
  pageToken: autoCat.uiState.pageToken,
108
+ scrollPosition: autoCat.uiState.scrollPosition,
103
109
  totalCount: { ...autoCat.uiState.totalCount },
104
110
  transactionIdsBySelectedPeriod,
105
111
  };
@@ -336,6 +342,7 @@ const expenseAutomationTransactionsView = createSlice({
336
342
  if (cached != null) {
337
343
  autoCat.uiState.pageToken = cached.pageToken;
338
344
  autoCat.uiState.totalCount = { ...cached.totalCount };
345
+ autoCat.uiState.scrollPosition = cached.scrollPosition;
339
346
  autoCat.transactionIdsBySelectedPeriod = {
340
347
  ...cached.transactionIdsBySelectedPeriod,
341
348
  };
@@ -346,9 +353,15 @@ const expenseAutomationTransactionsView = createSlice({
346
353
  // Sub-tab has never been visited — clear the active slot so the
347
354
  // view-epic's `fetchState === 'Not-Started' || transactionIds.length
348
355
  // === 0` cache check falls through and triggers a fresh page-1
349
- // fetch for the new dataset.
356
+ // fetch for the new dataset. `scrollPosition` is reset to the top
357
+ // so the incoming list isn't anchored to the outgoing sub-tab's
358
+ // offset (different rows → previous offset is meaningless).
350
359
  autoCat.uiState.pageToken = null;
351
360
  autoCat.uiState.totalCount = {};
361
+ autoCat.uiState.scrollPosition = {
362
+ scrollTop: 0,
363
+ scrollLeft: undefined,
364
+ };
352
365
  autoCat.transactionIdsBySelectedPeriod = {};
353
366
  autoCat.fetchState = 'Not-Started';
354
367
  autoCat.error = undefined;
@@ -407,12 +420,9 @@ const expenseAutomationTransactionsView = createSlice({
407
420
  const selectedCheckBoxTransactionIds = draft.transactionCategorizationView[selectedTab]
408
421
  .selectedCheckBoxTransactionIds;
409
422
  if (selectedTransaction != null &&
410
- checkIfAllLineItemsAreCategoryClassFilled(selectedTransaction, newTransactionLocalData, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled) === true && // check if all line items are filled
411
- selectedCheckBoxTransactionIds.length < MAX_SELECTION_LIMIT &&
412
- selectedCheckBoxTransactionIds.includes(transactionId) === false) {
423
+ shouldAutoSelectAndAdd(selectedTransaction, newTransactionLocalData, selectedCheckBoxTransactionIds, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled)) {
413
424
  draft.transactionCategorizationView[selectedTab].selectedCheckBoxTransactionIds = [
414
- ...draft.transactionCategorizationView[selectedTab]
415
- .selectedCheckBoxTransactionIds,
425
+ ...selectedCheckBoxTransactionIds,
416
426
  transactionId,
417
427
  ];
418
428
  }
@@ -495,9 +505,26 @@ const expenseAutomationTransactionsView = createSlice({
495
505
  const transactionLocalData = recordGet(draft.transactionCategorizationView[selectedTab]
496
506
  .transactionReviewLocalDataById, transactionId.id, undefined);
497
507
  if (transactionLocalData != null) {
508
+ const newLocalData = setEntityRecommendationForLineIdInLocalData(draft.transactionCategorizationView[selectedTab], transaction, transactionLocalData.transactionReviewLocalData, entity, lineIds, uncategorizedAccounts, action.payload.recommendationWithCOTByLineId, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled);
509
+ // Release the per-line fetch flag for every line this fetch
510
+ // covered. Done in-place on the freshly returned local data
511
+ // (the helper produces a new mutable object), before we write
512
+ // it back to the draft.
513
+ lineIds.forEach((lineId) => {
514
+ const lineItem = newLocalData.lineItemById[lineId];
515
+ if (lineItem != null) {
516
+ newLocalData.lineItemById[lineId] = {
517
+ ...lineItem,
518
+ categoryClassRecommendationsFetchState: {
519
+ fetchState: 'Completed',
520
+ error: undefined,
521
+ },
522
+ };
523
+ }
524
+ });
498
525
  draft.transactionCategorizationView[selectedTab].transactionReviewLocalDataById[transaction.id] = {
499
526
  transactionId: transaction.id,
500
- transactionReviewLocalData: setEntityRecommendationForLineIdInLocalData(draft.transactionCategorizationView[selectedTab], transaction, transactionLocalData.transactionReviewLocalData, entity, lineIds, uncategorizedAccounts, action.payload.recommendationWithCOTByLineId, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled),
527
+ transactionReviewLocalData: newLocalData,
501
528
  };
502
529
  // Mark transaction as dirty (autofill happened)
503
530
  if (!draft.transactionCategorizationView[selectedTab].transactionIdsWithUnsavedData.includes(transaction.id)) {
@@ -510,6 +537,99 @@ const expenseAutomationTransactionsView = createSlice({
510
537
  }
511
538
  },
512
539
  },
540
+ // Start arm of the line-update recommendations fetch. Flips covered
541
+ // lines to In-Progress AND removes the transaction from
542
+ // selectedCheckBoxTransactionIds — the row is unchecked + disabled
543
+ // until either the success arm (recheck if limit allows) or the
544
+ // failure arm releases the per-line flag.
545
+ markCategoryClassRecommendationsInProgressForCategorization: {
546
+ reducer(draft, action) {
547
+ const { selectedTab, transactionId, lineIds } = action.payload;
548
+ const tab = draft.transactionCategorizationView[selectedTab];
549
+ const transactionLocalData = recordGet(tab.transactionReviewLocalDataById, transactionId.id, undefined);
550
+ if (transactionLocalData != null) {
551
+ lineIds.forEach((lineId) => {
552
+ const lineItem = transactionLocalData.transactionReviewLocalData.lineItemById[lineId];
553
+ if (lineItem != null) {
554
+ transactionLocalData.transactionReviewLocalData.lineItemById[lineId] = {
555
+ ...lineItem,
556
+ categoryClassRecommendationsFetchState: {
557
+ fetchState: 'In-Progress',
558
+ error: undefined,
559
+ },
560
+ };
561
+ }
562
+ });
563
+ }
564
+ // Uncheck on fetch start: the row's existing category/class are
565
+ // stale after a payee change, so we drop the auto-selection until
566
+ // fresh recommendations land.
567
+ if (tab.selectedCheckBoxTransactionIds.includes(transactionId.id)) {
568
+ tab.selectedCheckBoxTransactionIds =
569
+ tab.selectedCheckBoxTransactionIds.filter((id) => id !== transactionId.id);
570
+ }
571
+ },
572
+ prepare(selectedTab, transactionId, lineIds) {
573
+ return { payload: { selectedTab, transactionId, lineIds } };
574
+ },
575
+ },
576
+ // Completed arm. Used by the epic when the HTTP call succeeds but the
577
+ // server returned no per-line recommendations — we still need to
578
+ // release the In-Progress flag so the skeleton resolves. Successful
579
+ // responses with recommendations go through
580
+ // setEntityRecommendationForLineIdsForCategorization instead (which
581
+ // also flips the lines to Completed).
582
+ markCategoryClassRecommendationsCompletedForCategorization: {
583
+ reducer(draft, action) {
584
+ const { selectedTab, transactionId, lineIds } = action.payload;
585
+ const transactionLocalData = recordGet(draft.transactionCategorizationView[selectedTab]
586
+ .transactionReviewLocalDataById, transactionId.id, undefined);
587
+ if (transactionLocalData != null) {
588
+ lineIds.forEach((lineId) => {
589
+ const lineItem = transactionLocalData.transactionReviewLocalData.lineItemById[lineId];
590
+ if (lineItem != null) {
591
+ transactionLocalData.transactionReviewLocalData.lineItemById[lineId] = {
592
+ ...lineItem,
593
+ categoryClassRecommendationsFetchState: {
594
+ fetchState: 'Completed',
595
+ error: undefined,
596
+ },
597
+ };
598
+ }
599
+ });
600
+ }
601
+ },
602
+ prepare(selectedTab, transactionId, lineIds) {
603
+ return { payload: { selectedTab, transactionId, lineIds } };
604
+ },
605
+ },
606
+ // Failure arm. Flips covered lines to Error so the skeleton resolves
607
+ // and downstream UI can react to the failure. The transaction stays
608
+ // unchecked from the start-arm action.
609
+ markCategoryClassRecommendationsFailureForCategorization: {
610
+ reducer(draft, action) {
611
+ const { selectedTab, transactionId, lineIds, error } = action.payload;
612
+ const transactionLocalData = recordGet(draft.transactionCategorizationView[selectedTab]
613
+ .transactionReviewLocalDataById, transactionId.id, undefined);
614
+ if (transactionLocalData != null) {
615
+ lineIds.forEach((lineId) => {
616
+ const lineItem = transactionLocalData.transactionReviewLocalData.lineItemById[lineId];
617
+ if (lineItem != null) {
618
+ transactionLocalData.transactionReviewLocalData.lineItemById[lineId] = {
619
+ ...lineItem,
620
+ categoryClassRecommendationsFetchState: {
621
+ fetchState: 'Error',
622
+ error,
623
+ },
624
+ };
625
+ }
626
+ });
627
+ }
628
+ },
629
+ prepare(selectedTab, transactionId, lineIds, error) {
630
+ return { payload: { selectedTab, transactionId, lineIds, error } };
631
+ },
632
+ },
513
633
  fetchTransactionCategorizationSuccess(draft, action) {
514
634
  const { selectedTab, refreshViewInBackground } = action.payload;
515
635
  if (draft.transactionCategorizationView[selectedTab].fetchState ===
@@ -605,9 +725,7 @@ const expenseAutomationTransactionsView = createSlice({
605
725
  .selectedCheckBoxTransactionIds;
606
726
  if (newTransactionLocalData.customer != null &&
607
727
  newTransactionLocalData.customer.id != null &&
608
- checkIfAllLineItemsAreCategoryClassFilled(selectedTransaction, newTransactionLocalData, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled) === true && // check if all line items are filled
609
- selectedCheckBoxTransactionIds.length < MAX_SELECTION_LIMIT &&
610
- selectedCheckBoxTransactionIds.includes(transactionId) === false) {
728
+ shouldAutoSelectAndAdd(selectedTransaction, newTransactionLocalData, selectedCheckBoxTransactionIds, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled)) {
611
729
  draft.transactionCategorizationView[selectedTab].selectedCheckBoxTransactionIds = [
612
730
  ...selectedCheckBoxTransactionIds,
613
731
  transactionId,
@@ -681,9 +799,7 @@ const expenseAutomationTransactionsView = createSlice({
681
799
  .selectedCheckBoxTransactionIds;
682
800
  if (newTransactionLocalData.vendor != null &&
683
801
  newTransactionLocalData.vendor.id != null &&
684
- checkIfAllLineItemsAreCategoryClassFilled(selectedTransaction, newTransactionLocalData, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled) === true && // check if all line items are filled
685
- selectedCheckBoxTransactionIds.length < MAX_SELECTION_LIMIT &&
686
- selectedCheckBoxTransactionIds.includes(transactionId) === false) {
802
+ shouldAutoSelectAndAdd(selectedTransaction, newTransactionLocalData, selectedCheckBoxTransactionIds, uncategorizedAccounts, isUncategorizedExpenseCategoryEnabled, isAccountingClassesEnabled)) {
687
803
  draft.transactionCategorizationView[selectedTab].selectedCheckBoxTransactionIds = [
688
804
  ...selectedCheckBoxTransactionIds,
689
805
  transactionId,
@@ -916,5 +1032,5 @@ const expenseAutomationTransactionsView = createSlice({
916
1032
  },
917
1033
  },
918
1034
  });
919
- 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;
1035
+ 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, markCategoryClassRecommendationsInProgressForCategorization, markCategoryClassRecommendationsCompletedForCategorization, markCategoryClassRecommendationsFailureForCategorization, updateSelectedTransactionId, syncTransactionCategorizationFromDetailSave, backgroundRefetchReviewTab, updateTransactionCategorizationUploadReceiptState, uploadTransactionCategorizationReceiptSuccess, } = expenseAutomationTransactionsView.actions;
920
1036
  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';
@@ -8,6 +9,29 @@ import { getAccountList, getNestedAccountListHierarchy, getUncategorizedAccounts
8
9
  import { getClassList, getNestedClassListHierarchy, } from '../../classList/classListSelector';
9
10
  import { getProjectList } from '../../projectList/projectListSelector';
10
11
  import { getAllSteps } from '../selectorTypes/expenseAutomationViewSelectorTypes';
12
+ // Per-transaction "any line is fetching category/class recommendations?"
13
+ // map for the active categorization tab. Memoized on the active tab's
14
+ // transactionReviewLocalDataById reference, so steady state (no fetches
15
+ // in flight) recomputes only when local data changes — and the row-table
16
+ // can read a single map lookup per row instead of re-iterating the
17
+ // row's lineItemById in the render path.
18
+ export const getCategorizationInFlightRecommendationsByTransactionId = createSelector((state) => state.expenseAutomationTransactionsViewState
19
+ .selectedTransactionCategorizationTab, (state) => state.expenseAutomationTransactionsViewState
20
+ .transactionCategorizationView, (selectedTab, transactionCategorizationView) => {
21
+ const tab = transactionCategorizationView[selectedTab];
22
+ const result = {};
23
+ for (const [transactionId, data] of Object.entries(tab.transactionReviewLocalDataById)) {
24
+ const lineItems = Object.values(data.transactionReviewLocalData.lineItemById);
25
+ if (lineItems.some((lineItem) => lineItem.categoryClassRecommendationsFetchState?.fetchState ===
26
+ 'In-Progress')) {
27
+ result[transactionId] = true;
28
+ }
29
+ }
30
+ return result;
31
+ });
32
+ // Page-level "any line on the active tab is in flight?" flag. Drives the
33
+ // list-page Save disable.
34
+ export const getCategorizationHasInFlightRecommendations = createSelector(getCategorizationInFlightRecommendationsByTransactionId, (inFlightByTransactionId) => Object.keys(inFlightByTransactionId).length > 0);
11
35
  export function getExpenseAutomationTransactionView(state) {
12
36
  const { accountState, classState, classListState, accountListState, expenseAutomationTransactionsViewState, expenseAutomationViewState, projectState, projectListState, transactionState, monthEndCloseChecksState, monthEndCloseChecksViewState, } = state;
13
37
  const { selectedTransactionCategorizationCompletedSubTab, selectedTransactionCategorizationTab, } = expenseAutomationTransactionsViewState;
@@ -103,6 +127,8 @@ export function getExpenseAutomationTransactionView(state) {
103
127
  : [];
104
128
  const transactionCompletionStatus = allSteps.find((step) => step.step === 'transaction_categorization')?.completionStatus;
105
129
  const completionStatus = transactionCompletionStatus ?? 'incomplete';
130
+ const inFlightCategoryClassRecommendationsByTransactionId = getCategorizationInFlightRecommendationsByTransactionId(state);
131
+ const hasInFlightCategoryClassRecommendations = getCategorizationHasInFlightRecommendations(state);
106
132
  return {
107
133
  version: 0,
108
134
  fetchState: fetchStatus.fetchState,
@@ -116,6 +142,8 @@ export function getExpenseAutomationTransactionView(state) {
116
142
  classList: allClasses,
117
143
  accountsHierarchyList,
118
144
  classHierarchyList,
145
+ hasInFlightCategoryClassRecommendations,
146
+ inFlightCategoryClassRecommendationsByTransactionId,
119
147
  isAccountingProjectsEnabled,
120
148
  projectList,
121
149
  transactionLocalData,
@@ -0,0 +1,78 @@
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 { entity, amount, transactionDetails, flowType, selectedTab, isFetchCOT, isUncategorizedExpenseCategoryEnabled, } = action.payload;
39
+ const { transactionId, transaction, lineIds } = transactionDetails;
40
+ // Synchronously emit the start arm so the per-line skeleton +
41
+ // row uncheck happen before the HTTP request begins.
42
+ const startAction = flowType === 'categorization' && selectedTab != null
43
+ ? markCategoryClassRecommendationsInProgressForCategorization(selectedTab, transactionId, lineIds)
44
+ : markCategoryClassRecommendationsInProgressForTransactionDetail(transactionId, lineIds);
45
+ const url = buildRecommendationUrl(zeniAPI.apiEndPoints.accountMicroServiceBaseUrl, entity, amount, transactionDetails, isFetchCOT === true);
46
+ const httpStream$ = zeniAPI
47
+ .getJSON(url)
48
+ .pipe(mergeMap((response) => {
49
+ if (!isSuccessResponse(response) || response.data == null) {
50
+ return of(flowType === 'categorization' && selectedTab != null
51
+ ? markCategoryClassRecommendationsFailureForCategorization(selectedTab, transactionId, lineIds, response.status)
52
+ : markCategoryClassRecommendationsFailureForTransactionDetail(transactionId, lineIds, response.status));
53
+ }
54
+ const recommendationWithCOTByLineId = getRecommendationByLineIdWithCOTFromRecommendationPayloadWithCOT(response.data.recommendations, lineIds);
55
+ // HTTP 200 with no per-line recommendations: NOT an error.
56
+ // Flip lines to Completed so the skeleton resolves and
57
+ // downstream UI can treat this as "we tried, nothing to
58
+ // apply".
59
+ if (recommendationWithCOTByLineId == null) {
60
+ return of(flowType === 'categorization' && selectedTab != null
61
+ ? markCategoryClassRecommendationsCompletedForCategorization(selectedTab, transactionId, lineIds)
62
+ : markCategoryClassRecommendationsCompletedForTransactionDetail(transactionId, lineIds));
63
+ }
64
+ const transactionWithCOT = isFetchCOT === true
65
+ ? getTransactionWithCOTFromRecommendations(transaction, recommendationWithCOTByLineId)
66
+ : getTransactionWithCOT(transaction);
67
+ const uncategorizedIncomeExpense = getUncategorizedAccounts(state$.value.accountState, state$.value.accountListState, 'accountList');
68
+ if (flowType === 'categorization' && selectedTab != null) {
69
+ return of(setEntityRecommendationForLineIdsForCategorization(selectedTab, transactionId, transactionWithCOT, lineIds, entity, amount, recommendationWithCOTByLineId, uncategorizedIncomeExpense, isUncategorizedExpenseCategoryEnabled, getIsAccountingClassesEnabled(state$.value)));
70
+ }
71
+ return of(setEntityRecommendationForLineIdsForTransactionDetail(transactionId, transactionWithCOT, lineIds, entity, amount, recommendationWithCOTByLineId, uncategorizedIncomeExpense));
72
+ }), catchError((error) => of(flowType === 'categorization' && selectedTab != null
73
+ ? markCategoryClassRecommendationsFailureForCategorization(selectedTab, transactionId, lineIds, createZeniAPIStatus('Unexpected Error', 'fetchEntityRecommendationsForLineUpdate failed: ' +
74
+ JSON.stringify(error)))
75
+ : markCategoryClassRecommendationsFailureForTransactionDetail(transactionId, lineIds, createZeniAPIStatus('Unexpected Error', 'fetchEntityRecommendationsForLineUpdate failed: ' +
76
+ JSON.stringify(error))))));
77
+ return concat(of(startAction), httpStream$);
78
+ }))));
@@ -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,41 @@ 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(entity, amount, transactionDetails, flowType, selectedTab, isFetchCOT = false, isUncategorizedExpenseCategoryEnabled) {
58
+ return {
59
+ payload: {
60
+ entity,
61
+ amount,
62
+ transactionDetails,
63
+ flowType,
64
+ selectedTab,
65
+ isFetchCOT,
66
+ isUncategorizedExpenseCategoryEnabled,
67
+ },
68
+ };
69
+ },
70
+ },
36
71
  fetchRecommendationByEntityName: {
37
72
  reducer(draft, action) {
38
73
  const { entityName, entityType } = action.payload;
@@ -111,7 +146,7 @@ const recommendation = createSlice({
111
146
  },
112
147
  },
113
148
  });
114
- export const { fetchEntityRecommendationsByTransactionId, fetchRecommendationByEntityName, fetchRecommendationByEntityId, updateRecommendationForEntity, updateRecommendationForEntityFailure, indicateReadyToInitializeRecommendation, clearRecommendation, } = recommendation.actions;
149
+ export const { fetchEntityRecommendationsByTransactionId, fetchEntityRecommendationsForLineUpdate, fetchRecommendationByEntityName, fetchRecommendationByEntityId, updateRecommendationForEntity, updateRecommendationForEntityFailure, indicateReadyToInitializeRecommendation, clearRecommendation, } = recommendation.actions;
115
150
  export default recommendation.reducer;
116
151
  const doUpdateRecommendationForEntity = (draft, entityId, entityType, payload) => {
117
152
  const key = getEntityRecommendationKey(entityType, entityId);
@@ -365,6 +365,21 @@ const transactionDetail = createSlice({
365
365
  const detail = recordGet(draft.transactionDetailById, key, undefined);
366
366
  if (detail != null) {
367
367
  const newLocalData = setEntityRecommendationForLineIdInLocalData(transaction, detail.transactionDetailLocalData, action.payload.entity, lineIds, uncategorizedIncomeExpense, recommendationWithCOTByLineId);
368
+ // Release the per-line fetch flag for every line this fetch
369
+ // covered so the inline skeleton resolves and the page-level
370
+ // Save button can re-enable.
371
+ lineIds.forEach((lineId) => {
372
+ const lineItem = newLocalData.lineItemById[lineId];
373
+ if (lineItem != null) {
374
+ newLocalData.lineItemById[lineId] = {
375
+ ...lineItem,
376
+ categoryClassRecommendationsFetchState: {
377
+ fetchState: 'Completed',
378
+ error: undefined,
379
+ },
380
+ };
381
+ }
382
+ });
368
383
  draft.transactionDetailById[key] = {
369
384
  ...detail,
370
385
  transactionDetailLocalData: newLocalData,
@@ -385,6 +400,84 @@ const transactionDetail = createSlice({
385
400
  };
386
401
  },
387
402
  },
403
+ // Start arm of the line-update recommendations fetch for the detail
404
+ // page. Flips covered lines to In-Progress; detail page has no
405
+ // checkbox, so no auto-uncheck side effect.
406
+ markCategoryClassRecommendationsInProgressForTransactionDetail: {
407
+ reducer(draft, action) {
408
+ const { transactionId, lineIds } = action.payload;
409
+ const key = getTransactionDetailKey(transactionId);
410
+ const detail = recordGet(draft.transactionDetailById, key, undefined);
411
+ if (detail != null) {
412
+ lineIds.forEach((lineId) => {
413
+ const lineItem = detail.transactionDetailLocalData.lineItemById[lineId];
414
+ if (lineItem != null) {
415
+ detail.transactionDetailLocalData.lineItemById[lineId] = {
416
+ ...lineItem,
417
+ categoryClassRecommendationsFetchState: {
418
+ fetchState: 'In-Progress',
419
+ error: undefined,
420
+ },
421
+ };
422
+ }
423
+ });
424
+ }
425
+ },
426
+ prepare(transactionId, lineIds) {
427
+ return { payload: { transactionId, lineIds } };
428
+ },
429
+ },
430
+ // Completed arm. Used when the HTTP call succeeded but the server
431
+ // returned no per-line recommendations — still need to release the
432
+ // In-Progress flag.
433
+ markCategoryClassRecommendationsCompletedForTransactionDetail: {
434
+ reducer(draft, action) {
435
+ const { transactionId, lineIds } = action.payload;
436
+ const key = getTransactionDetailKey(transactionId);
437
+ const detail = recordGet(draft.transactionDetailById, key, undefined);
438
+ if (detail != null) {
439
+ lineIds.forEach((lineId) => {
440
+ const lineItem = detail.transactionDetailLocalData.lineItemById[lineId];
441
+ if (lineItem != null) {
442
+ detail.transactionDetailLocalData.lineItemById[lineId] = {
443
+ ...lineItem,
444
+ categoryClassRecommendationsFetchState: {
445
+ fetchState: 'Completed',
446
+ error: undefined,
447
+ },
448
+ };
449
+ }
450
+ });
451
+ }
452
+ },
453
+ prepare(transactionId, lineIds) {
454
+ return { payload: { transactionId, lineIds } };
455
+ },
456
+ },
457
+ markCategoryClassRecommendationsFailureForTransactionDetail: {
458
+ reducer(draft, action) {
459
+ const { transactionId, lineIds, error } = action.payload;
460
+ const key = getTransactionDetailKey(transactionId);
461
+ const detail = recordGet(draft.transactionDetailById, key, undefined);
462
+ if (detail != null) {
463
+ lineIds.forEach((lineId) => {
464
+ const lineItem = detail.transactionDetailLocalData.lineItemById[lineId];
465
+ if (lineItem != null) {
466
+ detail.transactionDetailLocalData.lineItemById[lineId] = {
467
+ ...lineItem,
468
+ categoryClassRecommendationsFetchState: {
469
+ fetchState: 'Error',
470
+ error,
471
+ },
472
+ };
473
+ }
474
+ });
475
+ }
476
+ },
477
+ prepare(transactionId, lineIds, error) {
478
+ return { payload: { transactionId, lineIds, error } };
479
+ },
480
+ },
388
481
  removeEntityRecommendationForLineIdForTransactionDetail: {
389
482
  reducer(draft, action) {
390
483
  const { transaction, lineId } = action.payload;
@@ -656,7 +749,7 @@ const transactionDetail = createSlice({
656
749
  },
657
750
  },
658
751
  });
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;
752
+ 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
753
  export default transactionDetail.reducer;
661
754
  function getUpdatedEntityLocalData(detail, updates, entity, resetRecommendations, type) {
662
755
  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);
@@ -72,6 +92,7 @@ export const getTransactionDetail = (state, transactionId, fetchLinkedTransactio
72
92
  : [];
73
93
  const transactionDetailAnyUpdateStatus = reduceUpdateFetchStates(transactionDetail);
74
94
  const vendors = getVendorsByVendorIds(vendorState, vendorListState.vendorIds);
95
+ const hasInFlightCategoryClassRecommendations = getDetailInFlightRecommendations(state, transactionId);
75
96
  return {
76
97
  reportId: 'transaction_detail',
77
98
  reportTitle: 'Transaction Detail',
@@ -87,6 +108,7 @@ export const getTransactionDetail = (state, transactionId, fetchLinkedTransactio
87
108
  classHierarchyList,
88
109
  accountsHierarchyList,
89
110
  classList: classList,
111
+ hasInFlightCategoryClassRecommendations,
90
112
  isAccountingClassesEnabled,
91
113
  isAccountingProjectsEnabled,
92
114
  projectList,