@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
@@ -0,0 +1,262 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.applyTransactionFilters = exports.TRANSACTION_FILTER_CATEGORIES = void 0;
4
+ /**
5
+ * Narrowing type-guard for "has a non-empty string here". Used in place of
6
+ * raw `if (foo)` truthiness checks on `string | null | undefined` values so
7
+ * the `@typescript-eslint/strict-boolean-expressions` lint stays clean —
8
+ * empty strings should explicitly fall through to the next candidate
9
+ * (vendorName → customerName → localData.vendor.name → ...) rather than
10
+ * being implicitly coerced to falsy.
11
+ */
12
+ const isNonEmptyString = (s) => s != null && s !== '';
13
+ /**
14
+ * First line item in UI order. `lineItemById` is a Record whose iteration
15
+ * order is not guaranteed to match what the user sees; `sortedLineItems`
16
+ * is the canonical ordering used by the categorization list/detail views.
17
+ */
18
+ const getFirstLineItemFromReviewLocalData = (localData) => {
19
+ const { sortedLineItems, lineItemById } = localData;
20
+ if (sortedLineItems.length > 0) {
21
+ return lineItemById[sortedLineItems[0]];
22
+ }
23
+ const lineItems = Object.values(lineItemById);
24
+ return lineItems.length > 0 ? lineItems[0] : undefined;
25
+ };
26
+ exports.TRANSACTION_FILTER_CATEGORIES = [
27
+ { value: 'payment_account_name', type: 'dropdown' },
28
+ { value: 'payment_account_type', type: 'dropdown' },
29
+ { value: 'payee', type: 'searchAutocomplete' },
30
+ { value: 'category', type: 'dropdown' },
31
+ { value: 'class', type: 'dropdown' },
32
+ { value: 'amount', type: 'numberRange' },
33
+ ];
34
+ /**
35
+ * Resolve the comparable value for a transaction against a given filter field.
36
+ * Returns undefined when the transaction doesn't carry the field — callers
37
+ * decide whether absence counts as a match (for 'not_equal' it does).
38
+ */
39
+ const getCategoryValueForTransaction = (key, transaction) => {
40
+ switch (key) {
41
+ case 'amount': {
42
+ // Prefer transactionLocalData line items (sum). Fall back to lines on
43
+ // the transaction itself. Final fallback: transaction-level amount.
44
+ const localDataForAmount = transaction.transactionLocalData?.transactionReviewLocalData;
45
+ if (localDataForAmount?.lineItemById) {
46
+ const lineItems = Object.values(localDataForAmount.lineItemById);
47
+ if (lineItems.length > 0) {
48
+ return lineItems.reduce((sum, lineItem) => sum + (lineItem.amount?.amount ?? 0), 0);
49
+ }
50
+ }
51
+ if (transaction.transaction.lines &&
52
+ transaction.transaction.lines.length > 0) {
53
+ return transaction.transaction.lines.reduce((sum, line) => sum + (line.amount?.amount ?? 0), 0);
54
+ }
55
+ return transaction.amount.amount;
56
+ }
57
+ case 'payee': {
58
+ if (isNonEmptyString(transaction.vendorName)) {
59
+ return transaction.vendorName;
60
+ }
61
+ if (isNonEmptyString(transaction.customerName)) {
62
+ return transaction.customerName;
63
+ }
64
+ const localData = transaction.transactionLocalData?.transactionReviewLocalData;
65
+ const vendorName = localData?.vendor?.name;
66
+ if (isNonEmptyString(vendorName)) {
67
+ return vendorName;
68
+ }
69
+ const customerName = localData?.customer?.name;
70
+ if (isNonEmptyString(customerName)) {
71
+ return customerName;
72
+ }
73
+ return undefined;
74
+ }
75
+ case 'payment_account_name': {
76
+ // Match what TransactionCategorizationListRow renders for the cell.
77
+ return transaction.transaction.account?.accountName;
78
+ }
79
+ case 'payment_account_type': {
80
+ // Raw `paymentType` enum ("credit_card" / "check" / "cash"). Dropdown
81
+ // option values use the same enum; row uses `paymentTypeName` for the
82
+ // human label.
83
+ return transaction.transaction.paymentType;
84
+ }
85
+ case 'category': {
86
+ const localDataForCategory = transaction.transactionLocalData?.transactionReviewLocalData;
87
+ if (localDataForCategory != null) {
88
+ const firstLineItem = getFirstLineItemFromReviewLocalData(localDataForCategory);
89
+ const accountId = firstLineItem?.account?.accountId;
90
+ if (isNonEmptyString(accountId)) {
91
+ return accountId;
92
+ }
93
+ const qboId = firstLineItem?.account?.qboId;
94
+ if (isNonEmptyString(qboId)) {
95
+ return qboId;
96
+ }
97
+ const accountName = firstLineItem?.account?.accountName;
98
+ if (isNonEmptyString(accountName)) {
99
+ return accountName;
100
+ }
101
+ }
102
+ const firstLineForCategory = transaction.transaction.lines?.[0];
103
+ if (firstLineForCategory?.type ===
104
+ 'transaction_with_account_and_class_line' ||
105
+ firstLineForCategory?.type ===
106
+ 'transaction_with_product_or_service_line' ||
107
+ firstLineForCategory?.type === 'journal_entry_transaction_line') {
108
+ const account = firstLineForCategory.account;
109
+ return account?.accountId ?? account?.qboId ?? account?.accountName;
110
+ }
111
+ return undefined;
112
+ }
113
+ case 'class': {
114
+ const localDataForClass = transaction.transactionLocalData?.transactionReviewLocalData;
115
+ if (localDataForClass != null) {
116
+ const firstLineItemForClass = getFirstLineItemFromReviewLocalData(localDataForClass);
117
+ const classId = firstLineItemForClass?.class?.classId;
118
+ if (isNonEmptyString(classId)) {
119
+ return classId;
120
+ }
121
+ const qboId = firstLineItemForClass?.class?.qboId;
122
+ if (isNonEmptyString(qboId)) {
123
+ return qboId;
124
+ }
125
+ const className = firstLineItemForClass?.class?.className;
126
+ if (isNonEmptyString(className)) {
127
+ return className;
128
+ }
129
+ }
130
+ const firstLineForClass = transaction.transaction.lines?.[0];
131
+ if (firstLineForClass?.type === 'transaction_with_account_and_class_line' ||
132
+ firstLineForClass?.type ===
133
+ 'transaction_with_product_or_service_line' ||
134
+ firstLineForClass?.type === 'journal_entry_transaction_line') {
135
+ const classData = firstLineForClass.class;
136
+ return classData?.classId ?? classData?.qboId ?? classData?.className;
137
+ }
138
+ return undefined;
139
+ }
140
+ default:
141
+ return undefined;
142
+ }
143
+ };
144
+ /**
145
+ * TC-only amount matcher. Supports all five operators TC defines, including
146
+ * the legacy "1000<->5000" range-string form (kept for backward compatibility
147
+ * with persisted filter state that may still contain that encoding).
148
+ *
149
+ * The `'equal' | 'not_equal'` branch matches if `amount` equals ANY of the
150
+ * configured values (consistent with how non-amount filters interpret a
151
+ * multi-value `values` array). `.some()` over the values array also makes
152
+ * the empty-values case behave correctly — empty array → `matched = false`
153
+ * — though in practice `applyTransactionFilters` strips empty-values
154
+ * categories before they reach this matcher. The trailing
155
+ * `op === 'not_equal' ? !matched : matched` line inverts for `not_equal`.
156
+ */
157
+ const matchAmount = (amount, category) => {
158
+ const op = category.matchingOperator;
159
+ const values = category.values;
160
+ let matched = false;
161
+ if (op === 'in_between') {
162
+ if (values.length >= 2) {
163
+ const min = Number(values[0]);
164
+ const max = Number(values[1]);
165
+ matched = amount >= min && amount <= max;
166
+ }
167
+ }
168
+ else if (op === 'less_than') {
169
+ if (values.length >= 1) {
170
+ matched = amount < Number(values[0]);
171
+ }
172
+ }
173
+ else if (op === 'greater_than') {
174
+ if (values.length >= 1) {
175
+ matched = amount > Number(values[0]);
176
+ }
177
+ }
178
+ else if (op === 'equal' || op === 'not_equal') {
179
+ matched = values.some((v) => {
180
+ const s = String(v);
181
+ // Backward compatibility: legacy "low<->high" range-string form
182
+ // persisted under `matchingOperator: 'equal'`.
183
+ if (s.includes('<->')) {
184
+ const parts = s.split('<->');
185
+ return (amount >= Number(parts[0] ?? '') && amount <= Number(parts[1] ?? ''));
186
+ }
187
+ return amount === Number(v);
188
+ });
189
+ }
190
+ return op === 'not_equal' ? !matched : matched;
191
+ };
192
+ const transactionMatchesCategory = (transaction, category) => {
193
+ const value = getCategoryValueForTransaction(category.field, transaction);
194
+ if (value == null) {
195
+ // Absent-value semantics — pinning these down explicitly so the
196
+ // asymmetry isn't surprising:
197
+ //
198
+ // not_equal: a missing value IS NOT EQUAL to any candidate, so the
199
+ // transaction matches the filter (passes through).
200
+ // equal: a missing value is not equal to any candidate, so the
201
+ // transaction does NOT match (filtered out).
202
+ // less_than / greater_than: SQL-style three-valued logic — comparing
203
+ // against a missing value is "unknown", which we treat as
204
+ // "does not match" (filtered out). A user setting
205
+ // "amount < $1000" probably wants transactions with a
206
+ // concrete amount that satisfies the bound, not rows
207
+ // where the amount can't be determined.
208
+ // in_between: same as the single-sided comparators — missing values
209
+ // are filtered out.
210
+ //
211
+ // Only the `not_equal` branch returns `true` here; everything else
212
+ // falls through to the `false` below.
213
+ return category.matchingOperator === 'not_equal';
214
+ }
215
+ if (category.field === 'amount') {
216
+ return matchAmount(Number(value), category);
217
+ }
218
+ const valueStr = value.toString();
219
+ const valueInList = category.values.some((v) => v.toString() === valueStr);
220
+ return category.matchingOperator === 'not_equal' ? !valueInList : valueInList;
221
+ };
222
+ /**
223
+ * TC-only equivalent of `applyAdvancedFiltersOnList`. Filters a list of
224
+ * `TransactionView` items against a `TransactionFilters` object using the
225
+ * AND/OR combination semantics from `categoryCombinationOperator`.
226
+ *
227
+ * Independent of `view/spendManagement` — keeps the TC filter pipeline cleanly
228
+ * inside the Expense Automation feature group.
229
+ */
230
+ const applyTransactionFilters = (transactions, filters) => {
231
+ if (filters?.categories == null || filters.categories.length === 0) {
232
+ return transactions;
233
+ }
234
+ // Mirrors the predicate used by `getTransactionAppliedFiltersCount` on the
235
+ // webc side. A half-filled category — e.g. `in_between` with only the
236
+ // `min` typed — would otherwise survive the filter pass and produce zero
237
+ // matches because `Number("")` collapses to `0`, artificially emptying
238
+ // the list while editing. Skipping such categories keeps the filtered
239
+ // view stable while the user finishes typing.
240
+ const activeCategories = filters.categories.filter((c) => {
241
+ if (c.field == null || c.values.length === 0) {
242
+ return false;
243
+ }
244
+ if (c.field === 'amount' && c.matchingOperator === 'in_between') {
245
+ return (c.values.length >= 2 &&
246
+ String(c.values[0] ?? '').trim() !== '' &&
247
+ String(c.values[1] ?? '').trim() !== '');
248
+ }
249
+ return String(c.values[0] ?? '').trim() !== '';
250
+ });
251
+ if (activeCategories.length === 0) {
252
+ return transactions;
253
+ }
254
+ const op = filters.categoryCombinationOperator;
255
+ return transactions.filter((txn) => {
256
+ if (op === 'AND') {
257
+ return activeCategories.every((cat) => transactionMatchesCategory(txn, cat));
258
+ }
259
+ return activeCategories.some((cat) => transactionMatchesCategory(txn, cat));
260
+ });
261
+ };
262
+ exports.applyTransactionFilters = applyTransactionFilters;
@@ -16,6 +16,7 @@ import { VendorBase } from '../../../entity/vendor/vendorState';
16
16
  import { ZeniAPIStatus } from '../../../responsePayload';
17
17
  import { ZeniDate } from '../../../zeniDayJS';
18
18
  import { EntityRecommendationKey } from '../../recommendation/recommendationState';
19
+ import { TransactionFilters } from '../transactionFilterHelpers';
19
20
  import { TransactionDetailKey } from '../../transactionDetail/transactionDetailState';
20
21
  import { CompletedSubTab } from './completedSubTab';
21
22
  export declare const toTransactionsSortKey: (v: string) => "date" | "amount" | "vendor" | "project" | "category" | "class" | "payment_account" | "transaction_type" | "memo_and_receipt";
@@ -48,6 +49,7 @@ export interface TransactionCategorizationLineItemData extends TransactionLineBa
48
49
  transactionId: ID;
49
50
  account?: AccountBase;
50
51
  categorizationStatus?: CategorizationStatusType;
52
+ categoryClassRecommendationsFetchState?: FetchStateAndError;
51
53
  class?: ClassBase;
52
54
  customer?: CustomerBase;
53
55
  item?: ProductOrService;
@@ -93,6 +95,7 @@ export interface SupportedTransactionCategorization {
93
95
  }
94
96
  export declare const initialSupportedTransactionCategorization: SupportedTransactionCategorization;
95
97
  export interface TransactionsTabViewState extends FetchedState {
98
+ filters: TransactionFilters;
96
99
  markAsNotMiscategorizedStatus: FetchStateAndError;
97
100
  refreshStatus: FetchStateAndError;
98
101
  saveStatus: FetchStateAndError;
@@ -0,0 +1,9 @@
1
+ import { ActionsObservable, StateObservable } from 'redux-observable';
2
+ import { Observable } from 'rxjs';
3
+ import { RootState } from '../../reducer';
4
+ import { ZeniAPI } from '../../zeniAPI';
5
+ import { markCategoryClassRecommendationsCompletedForCategorization, markCategoryClassRecommendationsFailureForCategorization, markCategoryClassRecommendationsInProgressForCategorization, setEntityRecommendationForLineIdsForCategorization } from '../expenseAutomationView/reducers/transactionsViewReducer';
6
+ import { markCategoryClassRecommendationsCompletedForTransactionDetail, markCategoryClassRecommendationsFailureForTransactionDetail, markCategoryClassRecommendationsInProgressForTransactionDetail, setEntityRecommendationForLineIdsForTransactionDetail } from '../transactionDetail/transactionDetailReducer';
7
+ import { fetchEntityRecommendationsForLineUpdate } from './recommendationReducer';
8
+ export type ActionType = ReturnType<typeof fetchEntityRecommendationsForLineUpdate> | ReturnType<typeof markCategoryClassRecommendationsInProgressForCategorization> | ReturnType<typeof markCategoryClassRecommendationsCompletedForCategorization> | ReturnType<typeof markCategoryClassRecommendationsFailureForCategorization> | ReturnType<typeof markCategoryClassRecommendationsInProgressForTransactionDetail> | ReturnType<typeof markCategoryClassRecommendationsCompletedForTransactionDetail> | ReturnType<typeof markCategoryClassRecommendationsFailureForTransactionDetail> | ReturnType<typeof setEntityRecommendationForLineIdsForCategorization> | ReturnType<typeof setEntityRecommendationForLineIdsForTransactionDetail>;
9
+ export declare const fetchEntityRecommendationsForLineUpdateEpic: (actions$: ActionsObservable<ActionType>, state$: StateObservable<RootState>, zeniAPI: ZeniAPI) => Observable<ActionType>;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fetchEntityRecommendationsForLineUpdateEpic = void 0;
4
+ const rxjs_1 = require("rxjs");
5
+ const operators_1 = require("rxjs/operators");
6
+ const tenantSelector_1 = require("../../entity/tenant/tenantSelector");
7
+ const transactionHelper_1 = require("../../entity/transaction/transactionHelper");
8
+ const responsePayload_1 = require("../../responsePayload");
9
+ const accountListSelector_1 = require("../accountList/accountListSelector");
10
+ const transactionsViewReducer_1 = require("../expenseAutomationView/reducers/transactionsViewReducer");
11
+ const transactionDetailReducer_1 = require("../transactionDetail/transactionDetailReducer");
12
+ const recommendationHelper_1 = require("./recommendationHelper");
13
+ const recommendationReducer_1 = require("./recommendationReducer");
14
+ // Close the per-target groupBy bucket after this much idle time so inactive
15
+ // groups don't accumulate forever (each group holds a Subject + a chain of
16
+ // active subscribers; without a duration selector groupBy retains them for
17
+ // the lifetime of the source observable, which is the lifetime of the app).
18
+ // Picked at 60s to leave a generous window for re-fetches on the same
19
+ // payee/transaction/line target while still bounding memory.
20
+ const GROUP_INACTIVITY_TIMEOUT_MS = 60000;
21
+ // Build the groupBy key. Same flow + same transaction + same line set
22
+ // share a target so switchMap can cancel an in-flight prior fetch. Use
23
+ // NUL (\u0000) as separator because it can never appear in transaction
24
+ // or line ids (vs the `|` used in an earlier WIP which collides with
25
+ // pipe-delimited synthetic ids).
26
+ const SEPARATOR = '\u0000';
27
+ const toGroupKey = (flowType, transactionId, lineIds) => `${flowType}${SEPARATOR}${transactionId}${SEPARATOR}${[...lineIds]
28
+ .sort((a, b) => a.localeCompare(b))
29
+ .join(SEPARATOR)}`;
30
+ // Targeted recommendations fetch that drives the per-line skeleton, the
31
+ // list-page row-checkbox uncheck/recheck, and the page-level Save
32
+ // disable.
33
+ //
34
+ // Concurrency model:
35
+ // - groupBy by (flowType, transactionId, sorted lineIds) so distinct
36
+ // targets run in parallel.
37
+ // - inside each group, switchMap so a re-fetch on the SAME target
38
+ // cancels any prior in-flight request for that target.
39
+ // - groupBy duration selector closes idle groups to bound memory.
40
+ const fetchEntityRecommendationsForLineUpdateEpic = (actions$, state$, zeniAPI) => actions$.pipe((0, operators_1.filter)(recommendationReducer_1.fetchEntityRecommendationsForLineUpdate.match), (0, operators_1.groupBy)((action) => toGroupKey(action.payload.flowType, action.payload.transactionDetails.transactionId.id, action.payload.transactionDetails.lineIds), undefined, (group$) => group$.pipe((0, operators_1.debounce)(() => (0, rxjs_1.timer)(GROUP_INACTIVITY_TIMEOUT_MS)))), (0, operators_1.mergeMap)((group$) => group$.pipe((0, operators_1.switchMap)((action) => {
41
+ const payload = action.payload;
42
+ const { transactionId, transaction, lineIds } = payload.transactionDetails;
43
+ const { entity, amount, isFetchCOT, isUncategorizedExpenseCategoryEnabled, } = payload;
44
+ // Synchronously emit the start arm so the per-line skeleton +
45
+ // row uncheck happen before the HTTP request begins. The
46
+ // discriminated-union payload narrows `payload.selectedTab` to
47
+ // a non-optional `TransactionsTab` inside the `'categorization'`
48
+ // branch, so no defensive fallthrough is needed.
49
+ const startAction = payload.flowType === 'categorization'
50
+ ? (0, transactionsViewReducer_1.markCategoryClassRecommendationsInProgressForCategorization)(payload.selectedTab, transactionId, lineIds)
51
+ : (0, transactionDetailReducer_1.markCategoryClassRecommendationsInProgressForTransactionDetail)(transactionId, lineIds);
52
+ const url = (0, recommendationHelper_1.buildRecommendationUrl)(zeniAPI.apiEndPoints.accountMicroServiceBaseUrl, entity, amount, payload.transactionDetails, isFetchCOT === true);
53
+ const httpStream$ = zeniAPI
54
+ .getJSON(url)
55
+ .pipe((0, operators_1.mergeMap)((response) => {
56
+ if (!(0, responsePayload_1.isSuccessResponse)(response) || response.data == null) {
57
+ return (0, rxjs_1.of)(payload.flowType === 'categorization'
58
+ ? (0, transactionsViewReducer_1.markCategoryClassRecommendationsFailureForCategorization)(payload.selectedTab, transactionId, lineIds, response.status)
59
+ : (0, transactionDetailReducer_1.markCategoryClassRecommendationsFailureForTransactionDetail)(transactionId, lineIds, response.status));
60
+ }
61
+ const recommendationWithCOTByLineId = (0, recommendationHelper_1.getRecommendationByLineIdWithCOTFromRecommendationPayloadWithCOT)(response.data.recommendations, lineIds);
62
+ // HTTP 200 with no per-line recommendations: NOT an error.
63
+ // Flip lines to Completed so the skeleton resolves and
64
+ // downstream UI can treat this as "we tried, nothing to
65
+ // apply".
66
+ if (recommendationWithCOTByLineId == null) {
67
+ return (0, rxjs_1.of)(payload.flowType === 'categorization'
68
+ ? (0, transactionsViewReducer_1.markCategoryClassRecommendationsCompletedForCategorization)(payload.selectedTab, transactionId, lineIds)
69
+ : (0, transactionDetailReducer_1.markCategoryClassRecommendationsCompletedForTransactionDetail)(transactionId, lineIds));
70
+ }
71
+ const transactionWithCOT = isFetchCOT === true
72
+ ? (0, transactionHelper_1.getTransactionWithCOTFromRecommendations)(transaction, recommendationWithCOTByLineId)
73
+ : (0, transactionHelper_1.getTransactionWithCOT)(transaction);
74
+ const uncategorizedIncomeExpense = (0, accountListSelector_1.getUncategorizedAccounts)(state$.value.accountState, state$.value.accountListState, 'accountList');
75
+ if (payload.flowType === 'categorization') {
76
+ return (0, rxjs_1.of)((0, transactionsViewReducer_1.setEntityRecommendationForLineIdsForCategorization)(payload.selectedTab, transactionId, transactionWithCOT, lineIds, entity, amount, recommendationWithCOTByLineId, uncategorizedIncomeExpense, isUncategorizedExpenseCategoryEnabled, (0, tenantSelector_1.getIsAccountingClassesEnabled)(state$.value)));
77
+ }
78
+ return (0, rxjs_1.of)((0, transactionDetailReducer_1.setEntityRecommendationForLineIdsForTransactionDetail)(transactionId, transactionWithCOT, lineIds, entity, amount, recommendationWithCOTByLineId, uncategorizedIncomeExpense));
79
+ }), (0, operators_1.catchError)((error) => {
80
+ const errorMessage = 'fetchEntityRecommendationsForLineUpdate failed: ' +
81
+ (error instanceof Error
82
+ ? error.message
83
+ : JSON.stringify(error));
84
+ const status = (0, responsePayload_1.createZeniAPIStatus)('Unexpected Error', errorMessage);
85
+ return (0, rxjs_1.of)(payload.flowType === 'categorization'
86
+ ? (0, transactionsViewReducer_1.markCategoryClassRecommendationsFailureForCategorization)(payload.selectedTab, transactionId, lineIds, status)
87
+ : (0, transactionDetailReducer_1.markCategoryClassRecommendationsFailureForTransactionDetail)(transactionId, lineIds, status));
88
+ }));
89
+ return (0, rxjs_1.concat)((0, rxjs_1.of)(startAction), httpStream$);
90
+ }))));
91
+ exports.fetchEntityRecommendationsForLineUpdateEpic = fetchEntityRecommendationsForLineUpdateEpic;
@@ -1,8 +1,17 @@
1
1
  import { RecommendationPayload, RecommendationPayloadWithCOT } from '../../commonPayloadTypes/recommendationPayload';
2
2
  import { ID } from '../../commonStateTypes/common';
3
3
  import { Recommendation, RecommendationWithCOT } from '../../commonStateTypes/recommendationBase';
4
+ import { Entity } from '../../entity/genericEntity/entity';
4
5
  import { RecommendationByLineId, RecommendationWithCOTByLineId } from '../../entity/transaction/stateTypes/transaction';
6
+ import { SupportedTransaction } from '../../entity/transaction/transactionState';
5
7
  export declare const getRecommendationFromRecommendationPayload: (payload: RecommendationPayload[]) => Recommendation[] | undefined;
6
8
  export declare const getRecommendationByLineIdFromRecommendationPayload: (recommendationPayload: RecommendationPayload[], lineIds: ID[]) => RecommendationByLineId | undefined;
7
9
  export declare const getRecommendationWithCOTFromRecommendationPayloadWithCOT: (payload: RecommendationPayloadWithCOT[]) => RecommendationWithCOT[] | undefined;
10
+ export declare const buildRecommendationUrl: (accountMicroServiceBaseUrl: string, entity: Entity, amount: number, transactionDetails: {
11
+ lineIds: ID[];
12
+ transaction: SupportedTransaction;
13
+ transactionId: {
14
+ id: string;
15
+ };
16
+ }, isFetchCOT: boolean) => string;
8
17
  export declare const getRecommendationByLineIdWithCOTFromRecommendationPayloadWithCOT: (recommendationPayload: RecommendationPayloadWithCOT[], lineIds: ID[]) => RecommendationWithCOTByLineId | undefined;
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getRecommendationByLineIdWithCOTFromRecommendationPayloadWithCOT = exports.getRecommendationWithCOTFromRecommendationPayloadWithCOT = exports.getRecommendationByLineIdFromRecommendationPayload = exports.getRecommendationFromRecommendationPayload = void 0;
3
+ exports.getRecommendationByLineIdWithCOTFromRecommendationPayloadWithCOT = exports.buildRecommendationUrl = exports.getRecommendationWithCOTFromRecommendationPayloadWithCOT = exports.getRecommendationByLineIdFromRecommendationPayload = exports.getRecommendationFromRecommendationPayload = void 0;
4
4
  const transactionPayload_1 = require("../../entity/transaction/payloadTypes/transactionPayload");
5
+ const transactionDetailState_1 = require("../transactionDetail/transactionDetailState");
5
6
  const getRecommendationFromRecommendationPayload = (payload) => {
6
7
  if (payload == null || payload.length === 0) {
7
8
  return undefined;
@@ -43,6 +44,35 @@ const getRecommendationWithCOTFromRecommendationPayloadWithCOT = (payload) => {
43
44
  return recommendations;
44
45
  };
45
46
  exports.getRecommendationWithCOTFromRecommendationPayloadWithCOT = getRecommendationWithCOTFromRecommendationPayloadWithCOT;
47
+ // Pluralized URL segment for entity types. Mirrors the legacy
48
+ // fetchEntityRecommendationsByTransactionIdEpic.toEntityTypeURL.
49
+ const toEntityTypeUrlSegment = (entityType) => `${entityType}s`;
50
+ // Build the recommendations URL for a single entity + transaction target.
51
+ // Centralizes the URL shape so the legacy
52
+ // fetchEntityRecommendationsByTransactionIdEpic and the new
53
+ // fetchEntityRecommendationsForLineUpdateEpic stay in lockstep.
54
+ const buildRecommendationUrl = (accountMicroServiceBaseUrl, entity, amount, transactionDetails, isFetchCOT) => {
55
+ const entityQuery = {
56
+ entity_name: entity.name,
57
+ entity_type: entity.type,
58
+ };
59
+ // Entity-id-null case: server expects entity_name / entity_type query
60
+ // instead of the {entityType}/{qboId}/recommendations path.
61
+ if (entity.qboId === entity.name) {
62
+ return `${accountMicroServiceBaseUrl}/1.0/recommendations?query=${encodeURIComponent(JSON.stringify(entityQuery))}`;
63
+ }
64
+ const query = {
65
+ amount,
66
+ transaction_id: (0, transactionDetailState_1.getActualTransactionID)(transactionDetails.transactionId.id),
67
+ transaction_type: transactionDetails.transaction.type,
68
+ line_ids: transactionDetails.lineIds,
69
+ };
70
+ if (isFetchCOT === true) {
71
+ query.include_cot = true;
72
+ }
73
+ return `${accountMicroServiceBaseUrl}/1.0/${toEntityTypeUrlSegment(entity.type)}/${entity.qboId}/recommendations?query=${encodeURIComponent(JSON.stringify(query))}`;
74
+ };
75
+ exports.buildRecommendationUrl = buildRecommendationUrl;
46
76
  const getRecommendationByLineIdWithCOTFromRecommendationPayloadWithCOT = (recommendationPayload, lineIds) => {
47
77
  if (recommendationPayload.length === 0) {
48
78
  return undefined;
@@ -4,7 +4,26 @@ import { Entity, EntityType } from '../../entity/genericEntity/entity';
4
4
  import { TransactionID } from '../../entity/transaction/stateTypes/transaction';
5
5
  import { SupportedTransaction } from '../../entity/transaction/transactionState';
6
6
  import { ZeniAPIStatus } from '../../responsePayload';
7
+ import { TransactionsTab } from '../expenseAutomationView/types/transactionsViewState';
7
8
  import { EntityRecommendationState } from './recommendationState';
9
+ export type RecommendationLineUpdateFlowType = 'categorization' | 'detail';
10
+ type FetchEntityRecommendationsForLineUpdateCommonPayload = {
11
+ amount: number;
12
+ entity: Entity;
13
+ transactionDetails: {
14
+ lineIds: ID[];
15
+ transaction: SupportedTransaction;
16
+ transactionId: TransactionID;
17
+ };
18
+ isFetchCOT?: boolean;
19
+ isUncategorizedExpenseCategoryEnabled?: boolean;
20
+ };
21
+ export type FetchEntityRecommendationsForLineUpdatePayload = (FetchEntityRecommendationsForLineUpdateCommonPayload & {
22
+ flowType: 'categorization';
23
+ selectedTab: TransactionsTab;
24
+ }) | (FetchEntityRecommendationsForLineUpdateCommonPayload & {
25
+ flowType: 'detail';
26
+ });
8
27
  export declare const initialState: EntityRecommendationState;
9
28
  export declare const fetchEntityRecommendationsByTransactionId: import("@reduxjs/toolkit").ActionCreatorWithPreparedPayload<[entity: Entity, amount: number, transactionDetails: {
10
29
  lineIds: ID[];
@@ -22,7 +41,7 @@ export declare const fetchEntityRecommendationsByTransactionId: import("@reduxjs
22
41
  isTransactionCategorizationFlow: any;
23
42
  isFetchCOT: any;
24
43
  isUncategorizedExpenseCategoryEnabled: boolean | undefined;
25
- }, "recommendation/fetchEntityRecommendationsByTransactionId", never, never>, fetchRecommendationByEntityName: import("@reduxjs/toolkit").ActionCreatorWithPreparedPayload<[entityName: string, entityType: EntityType], {
44
+ }, "recommendation/fetchEntityRecommendationsByTransactionId", never, never>, fetchEntityRecommendationsForLineUpdate: import("@reduxjs/toolkit").ActionCreatorWithPreparedPayload<[args: FetchEntityRecommendationsForLineUpdatePayload], FetchEntityRecommendationsForLineUpdatePayload, "recommendation/fetchEntityRecommendationsForLineUpdate", never, never>, fetchRecommendationByEntityName: import("@reduxjs/toolkit").ActionCreatorWithPreparedPayload<[entityName: string, entityType: EntityType], {
26
45
  entityName: string;
27
46
  entityType: EntityType;
28
47
  }, "recommendation/fetchRecommendationByEntityName", never, never>, fetchRecommendationByEntityId: import("@reduxjs/toolkit").ActionCreatorWithPreparedPayload<[entityId: string, entityType: EntityType], {
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  var _a;
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.clearRecommendation = exports.indicateReadyToInitializeRecommendation = exports.updateRecommendationForEntityFailure = exports.updateRecommendationForEntity = exports.fetchRecommendationByEntityId = exports.fetchRecommendationByEntityName = exports.fetchEntityRecommendationsByTransactionId = exports.initialState = void 0;
4
+ exports.clearRecommendation = exports.indicateReadyToInitializeRecommendation = exports.updateRecommendationForEntityFailure = exports.updateRecommendationForEntity = exports.fetchRecommendationByEntityId = exports.fetchRecommendationByEntityName = exports.fetchEntityRecommendationsForLineUpdate = exports.fetchEntityRecommendationsByTransactionId = exports.initialState = void 0;
5
5
  const toolkit_1 = require("@reduxjs/toolkit");
6
6
  const recommendationState_1 = require("./recommendationState");
7
7
  exports.initialState = {
@@ -37,6 +37,31 @@ const recommendation = (0, toolkit_1.createSlice)({
37
37
  };
38
38
  },
39
39
  },
40
+ // Targeted recommendations fetch fired when the user changes the
41
+ // payee/customer on a single transaction line (or the JE sibling set
42
+ // for that change). Routed by `fetchEntityRecommendationsForLineUpdateEpic`
43
+ // which uses groupBy + switchMap to keep fetches for distinct targets
44
+ // running in parallel while same-target re-fetches still cancel each
45
+ // other. The flowType discriminator selects the categorization vs
46
+ // detail slice for the per-line In-Progress / Completed / Error state.
47
+ fetchEntityRecommendationsForLineUpdate: {
48
+ reducer(draft, action) {
49
+ const { entity } = action.payload;
50
+ const key = (0, recommendationState_1.getEntityRecommendationKey)(entity.type, entity.id);
51
+ // Unconditional flip to In-Progress; the previous variant only
52
+ // seeded when missing, which left stale fetchStates when a prior
53
+ // fetch had already populated the entity entry.
54
+ draft.recommendationByEntity[key] = {
55
+ ...(draft.recommendationByEntity[key] ??
56
+ recommendationState_1.initialEntityRecommendationState),
57
+ fetchState: 'In-Progress',
58
+ error: undefined,
59
+ };
60
+ },
61
+ prepare(args) {
62
+ return { payload: args };
63
+ },
64
+ },
40
65
  fetchRecommendationByEntityName: {
41
66
  reducer(draft, action) {
42
67
  const { entityName, entityType } = action.payload;
@@ -115,7 +140,7 @@ const recommendation = (0, toolkit_1.createSlice)({
115
140
  },
116
141
  },
117
142
  });
118
- _a = recommendation.actions, exports.fetchEntityRecommendationsByTransactionId = _a.fetchEntityRecommendationsByTransactionId, exports.fetchRecommendationByEntityName = _a.fetchRecommendationByEntityName, exports.fetchRecommendationByEntityId = _a.fetchRecommendationByEntityId, exports.updateRecommendationForEntity = _a.updateRecommendationForEntity, exports.updateRecommendationForEntityFailure = _a.updateRecommendationForEntityFailure, exports.indicateReadyToInitializeRecommendation = _a.indicateReadyToInitializeRecommendation, exports.clearRecommendation = _a.clearRecommendation;
143
+ _a = recommendation.actions, exports.fetchEntityRecommendationsByTransactionId = _a.fetchEntityRecommendationsByTransactionId, exports.fetchEntityRecommendationsForLineUpdate = _a.fetchEntityRecommendationsForLineUpdate, exports.fetchRecommendationByEntityName = _a.fetchRecommendationByEntityName, exports.fetchRecommendationByEntityId = _a.fetchRecommendationByEntityId, exports.updateRecommendationForEntity = _a.updateRecommendationForEntity, exports.updateRecommendationForEntityFailure = _a.updateRecommendationForEntityFailure, exports.indicateReadyToInitializeRecommendation = _a.indicateReadyToInitializeRecommendation, exports.clearRecommendation = _a.clearRecommendation;
119
144
  exports.default = recommendation.reducer;
120
145
  const doUpdateRecommendationForEntity = (draft, entityId, entityType, payload) => {
121
146
  const key = (0, recommendationState_1.getEntityRecommendationKey)(entityType, entityId);
@@ -45,7 +45,7 @@ export interface BillPayFilters {
45
45
  }
46
46
  export interface BillPayFilterCategory {
47
47
  field: BillListViewFilterCategoryField;
48
- matchingOperator: 'equal' | 'not-equal';
48
+ matchingOperator: 'equal' | 'not_equal';
49
49
  values: (string | ZeniDate)[];
50
50
  valuesCombinationOperator: 'ANY';
51
51
  }
@@ -36,7 +36,7 @@ export interface PaymentHistoryFilters {
36
36
  }
37
37
  export interface PaymentHistoryFilterCategory {
38
38
  field: PaymentHistoryFilterCategoryField;
39
- matchingOperator: 'equal' | 'not-equal';
39
+ matchingOperator: 'equal' | 'not_equal';
40
40
  values: (string | ZeniDate)[];
41
41
  valuesCombinationOperator: 'ANY';
42
42
  }
@@ -46,7 +46,7 @@ export interface ReimbursementFilters {
46
46
  }
47
47
  export interface ReimbursementFilterCategory {
48
48
  field: RemiListViewFilterCategoryField;
49
- matchingOperator: 'equal' | 'not-equal';
49
+ matchingOperator: 'equal' | 'not_equal';
50
50
  values: (string | ZeniDate)[];
51
51
  valuesCombinationOperator: 'ANY';
52
52
  }
@@ -1,3 +1,4 @@
1
+ import { CategoryCombinationOperator, FilterCategoryType } from '../../commonStateTypes/filterPrimitives';
1
2
  import { TimePeriod } from '../../commonStateTypes/timePeriod';
2
3
  import { UserRoleType } from '../../entity/userRole/userRoleType';
3
4
  import { RootState } from '../../reducer';
@@ -12,12 +13,20 @@ import { ReimbursementView } from './reimbursement/remiListView/remiListSelector
12
13
  import { ReimbursementFilters, RemiListViewFilterCategoryField } from './reimbursement/remiListView/remiListState';
13
14
  export type SpendManagementFiltersType = BillPayFilters | ReimbursementFilters | TaskListFilters | PaymentHistoryFilters;
14
15
  export type SpendManagementFilterEntityType = 'bill_pay' | 'reimbursement' | 'task_management' | 'charge_card_payment_history';
15
- export type FilterCategoryType = 'searchAutocomplete' | 'user' | 'dateRange' | 'numberRange' | 'dropdown';
16
+ /**
17
+ * Re-exported here so consumers of `spendManagementFilterHelpers` keep
18
+ * their existing import path stable after the primitives moved to
19
+ * `commonStateTypes/filterPrimitives`. Downstream files (`taskList`,
20
+ * `remiListState`, `chargeCardPaymentHistory`, `billListState`) and the
21
+ * CES barrel still pull `CategoryCombinationOperator` / `FilterCategoryType`
22
+ * from this module — the source of truth is upstream but the surface is
23
+ * unchanged.
24
+ */
25
+ export type { CategoryCombinationOperator, FilterCategoryType };
16
26
  export interface MatchingOperatorDropdownOption {
17
27
  label: 'is' | 'is not';
18
- value: 'equal' | 'not-equal';
28
+ value: 'equal' | 'not_equal';
19
29
  }
20
- export type CategoryCombinationOperator = 'AND' | 'OR';
21
30
  export interface BillPayFilterCategoryDropdownOption {
22
31
  value: BillListViewFilterCategoryField;
23
32
  multiple?: boolean;
@@ -14,6 +14,8 @@ const helpers_1 = require("./helpers");
14
14
  const remiListSelector_1 = require("./reimbursement/remiListView/remiListSelector");
15
15
  const remiListState_1 = require("./reimbursement/remiListView/remiListState");
16
16
  //filters items against filter values representing a range. ex: date (from-to), amount(1k<-->5k)
17
+ // Spend Management uses only equal/not_equal — TC amount operators
18
+ // (inBetween, lessThan, greaterThan) live in the TC filter pipeline.
17
19
  const filterItemOnRangeCategoryType = (valueForItem, currentFilter) => {
18
20
  let doesItemFallInValueRange = false;
19
21
  const filterField = currentFilter.field;
@@ -47,7 +49,7 @@ const filterItemOnCategoriesWithSingleValue = (categoryValue, currentFilter, ran
47
49
  return filterItemOnRangeCategoryType(categoryValue, currentFilter);
48
50
  }
49
51
  // if filter category is not rangeType
50
- if (currentFilter.matchingOperator === 'not-equal') {
52
+ if (currentFilter.matchingOperator === 'not_equal') {
51
53
  return currentFilter.values.indexOf(categoryValue.toString()) === -1;
52
54
  }
53
55
  return currentFilter.values.indexOf(categoryValue.toString()) > -1;
@@ -121,7 +123,7 @@ const applyAdvancedFiltersOnList = (entity, allItems, filters, filteredItems = [
121
123
  ? getCategoryValueForTaskList(key, item)
122
124
  : getCategoryValueForPaymentHistory(key, item);
123
125
  if (categoryValue == null) {
124
- if (currentFilter.matchingOperator === 'not-equal') {
126
+ if (currentFilter.matchingOperator === 'not_equal') {
125
127
  return true;
126
128
  }
127
129
  return false;
@@ -217,7 +217,7 @@ const applyAdvancedFiltersOnCompaniesList = (allCompanies, filters, filteredComp
217
217
  const key = currentFilter.field;
218
218
  const categoryValue = getCategoryValueForCompany(key, company);
219
219
  if (categoryValue == null) {
220
- if (currentFilter.matchingOperator === 'not-equal') {
220
+ if (currentFilter.matchingOperator === 'not_equal') {
221
221
  return true;
222
222
  }
223
223
  return false;