@zeniai/client-epic-state 4.19.94 → 4.19.95

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 (122) hide show
  1. package/lib/entity/account/accountPayload.d.ts +2 -0
  2. package/lib/entity/account/accountPayload.js +2 -0
  3. package/lib/entity/account/accountState.d.ts +2 -0
  4. package/lib/entity/depositAccount/depositAccount.d.ts +1 -1
  5. package/lib/entity/depositAccount/depositAccount.js +8 -1
  6. package/lib/entity/reimbursement/reimbursementPayload.d.ts +2 -0
  7. package/lib/entity/reimbursement/reimbursementPayload.js +7 -0
  8. package/lib/entity/reimbursement/reimbursementState.d.ts +2 -0
  9. package/lib/entity/snackbar/snackbarTypes.d.ts +1 -1
  10. package/lib/entity/snackbar/snackbarTypes.js +1 -0
  11. package/lib/entity/task/taskPayload.d.ts +1 -0
  12. package/lib/entity/task/taskPayload.js +1 -0
  13. package/lib/entity/task/taskState.d.ts +1 -0
  14. package/lib/entity/userGroups/userGroupsPayload.d.ts +7 -0
  15. package/lib/entity/userGroups/userGroupsPayload.js +10 -0
  16. package/lib/entity/userGroups/userGroupsReducer.d.ts +8 -0
  17. package/lib/entity/userGroups/userGroupsReducer.js +29 -0
  18. package/lib/entity/userGroups/userGroupsSelector.d.ts +4 -0
  19. package/lib/entity/userGroups/userGroupsSelector.js +12 -0
  20. package/lib/entity/userGroups/userGroupsState.d.ts +9 -0
  21. package/lib/entity/userGroups/userGroupsState.js +2 -0
  22. package/lib/epic.d.ts +12 -1
  23. package/lib/epic.js +12 -1
  24. package/lib/esm/entity/account/accountPayload.js +2 -0
  25. package/lib/esm/entity/depositAccount/depositAccount.js +8 -1
  26. package/lib/esm/entity/reimbursement/reimbursementPayload.js +7 -0
  27. package/lib/esm/entity/snackbar/snackbarTypes.js +1 -0
  28. package/lib/esm/entity/task/taskPayload.js +1 -0
  29. package/lib/esm/entity/userGroups/userGroupsPayload.js +7 -0
  30. package/lib/esm/entity/userGroups/userGroupsReducer.js +25 -0
  31. package/lib/esm/entity/userGroups/userGroupsSelector.js +8 -0
  32. package/lib/esm/entity/userGroups/userGroupsState.js +1 -0
  33. package/lib/esm/epic.js +12 -1
  34. package/lib/esm/index.js +9 -3
  35. package/lib/esm/reducer.js +6 -0
  36. package/lib/esm/view/expenseAutomationView/bulkUploadTiming.js +10 -0
  37. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/bulkUploadReceiptsEpic.js +29 -0
  38. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/confirmBulkUploadMatchEpic.js +49 -0
  39. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/fetchBulkUploadBatchDetailsEpic.js +40 -0
  40. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/fetchBulkUploadBatchesEpic.js +47 -0
  41. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/fetchCompletedTransactionsEpic.js +61 -0
  42. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/fetchMoreBatchDetailsEpic.js +33 -0
  43. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/fetchMultipleBatchDetailsEpic.js +56 -0
  44. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/searchTransactionsForManualMatchEpic.js +77 -0
  45. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/uploadMissingReceiptSuccessEpic.js +7 -5
  46. package/lib/esm/view/expenseAutomationView/epics/missingReceipts/watchBulkUploadBatchStatusEpic.js +79 -0
  47. package/lib/esm/view/expenseAutomationView/epics/transactionCategorization/uploadTransactionReceiptSuccessEpic.js +24 -0
  48. package/lib/esm/view/expenseAutomationView/payload/missingReceiptsPayload.js +189 -1
  49. package/lib/esm/view/expenseAutomationView/reducers/missingReceiptsViewReducer.js +433 -2
  50. package/lib/esm/view/expenseAutomationView/reducers/transactionsViewReducer.js +23 -1
  51. package/lib/esm/view/expenseAutomationView/selectors/missingReceiptsSelector.js +244 -1
  52. package/lib/esm/view/expenseAutomationView/selectors/transactionCategorizationSelector.js +2 -1
  53. package/lib/esm/view/expenseAutomationView/types/missingReceiptsViewState.js +44 -0
  54. package/lib/esm/view/expenseAutomationView/types/transactionsViewState.js +2 -1
  55. package/lib/esm/view/taskManager/taskDetailView/taskDetailSelector.js +1 -1
  56. package/lib/esm/view/taskManager/taskListView/epics/bulkUpdateTaskListEpic.js +1 -0
  57. package/lib/esm/view/taskManager/taskListView/taskListSelector.js +3 -1
  58. package/lib/esm/view/userGroupListView/userGroupListViewReducer.js +65 -0
  59. package/lib/esm/view/userGroupListView/userGroupListViewSelector.js +16 -0
  60. package/lib/esm/view/userGroupListView/userGroupListViewState.js +1 -0
  61. package/lib/esm/view/userListView/fetchUserListByTypeEpic.js +11 -0
  62. package/lib/esm/zeniAPI.js +0 -2
  63. package/lib/index.d.ts +8 -4
  64. package/lib/index.js +82 -32
  65. package/lib/reducer.d.ts +6 -0
  66. package/lib/reducer.js +6 -0
  67. package/lib/tsconfig.typecheck.tsbuildinfo +1 -0
  68. package/lib/view/expenseAutomationView/bulkUploadTiming.d.ts +10 -0
  69. package/lib/view/expenseAutomationView/bulkUploadTiming.js +13 -0
  70. package/lib/view/expenseAutomationView/epics/missingReceipts/bulkUploadReceiptsEpic.d.ts +18 -0
  71. package/lib/view/expenseAutomationView/epics/missingReceipts/bulkUploadReceiptsEpic.js +33 -0
  72. package/lib/view/expenseAutomationView/epics/missingReceipts/confirmBulkUploadMatchEpic.d.ts +7 -0
  73. package/lib/view/expenseAutomationView/epics/missingReceipts/confirmBulkUploadMatchEpic.js +53 -0
  74. package/lib/view/expenseAutomationView/epics/missingReceipts/fetchBulkUploadBatchDetailsEpic.d.ts +8 -0
  75. package/lib/view/expenseAutomationView/epics/missingReceipts/fetchBulkUploadBatchDetailsEpic.js +44 -0
  76. package/lib/view/expenseAutomationView/epics/missingReceipts/fetchBulkUploadBatchesEpic.d.ts +7 -0
  77. package/lib/view/expenseAutomationView/epics/missingReceipts/fetchBulkUploadBatchesEpic.js +51 -0
  78. package/lib/view/expenseAutomationView/epics/missingReceipts/fetchCompletedTransactionsEpic.d.ts +8 -0
  79. package/lib/view/expenseAutomationView/epics/missingReceipts/fetchCompletedTransactionsEpic.js +65 -0
  80. package/lib/view/expenseAutomationView/epics/missingReceipts/fetchMoreBatchDetailsEpic.d.ts +8 -0
  81. package/lib/view/expenseAutomationView/epics/missingReceipts/fetchMoreBatchDetailsEpic.js +37 -0
  82. package/lib/view/expenseAutomationView/epics/missingReceipts/fetchMultipleBatchDetailsEpic.d.ts +9 -0
  83. package/lib/view/expenseAutomationView/epics/missingReceipts/fetchMultipleBatchDetailsEpic.js +61 -0
  84. package/lib/view/expenseAutomationView/epics/missingReceipts/searchTransactionsForManualMatchEpic.d.ts +14 -0
  85. package/lib/view/expenseAutomationView/epics/missingReceipts/searchTransactionsForManualMatchEpic.js +81 -0
  86. package/lib/view/expenseAutomationView/epics/missingReceipts/uploadMissingReceiptSuccessEpic.js +7 -5
  87. package/lib/view/expenseAutomationView/epics/missingReceipts/watchBulkUploadBatchStatusEpic.d.ts +25 -0
  88. package/lib/view/expenseAutomationView/epics/missingReceipts/watchBulkUploadBatchStatusEpic.js +85 -0
  89. package/lib/view/expenseAutomationView/epics/transactionCategorization/uploadTransactionReceiptSuccessEpic.d.ts +7 -0
  90. package/lib/view/expenseAutomationView/epics/transactionCategorization/uploadTransactionReceiptSuccessEpic.js +28 -0
  91. package/lib/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.d.ts +1 -1
  92. package/lib/view/expenseAutomationView/payload/missingReceiptsPayload.d.ts +118 -0
  93. package/lib/view/expenseAutomationView/payload/missingReceiptsPayload.js +201 -0
  94. package/lib/view/expenseAutomationView/reducers/missingReceiptsViewReducer.d.ts +76 -3
  95. package/lib/view/expenseAutomationView/reducers/missingReceiptsViewReducer.js +434 -2
  96. package/lib/view/expenseAutomationView/reducers/transactionsViewReducer.d.ts +11 -3
  97. package/lib/view/expenseAutomationView/reducers/transactionsViewReducer.js +24 -2
  98. package/lib/view/expenseAutomationView/selectorTypes/missingReceiptsSelectorTypes.d.ts +69 -1
  99. package/lib/view/expenseAutomationView/selectorTypes/transactionsViewSelectorTypes.d.ts +1 -0
  100. package/lib/view/expenseAutomationView/selectors/missingReceiptsSelector.d.ts +1 -1
  101. package/lib/view/expenseAutomationView/selectors/missingReceiptsSelector.js +243 -0
  102. package/lib/view/expenseAutomationView/selectors/transactionCategorizationSelector.js +2 -1
  103. package/lib/view/expenseAutomationView/types/missingReceiptsViewState.d.ts +142 -0
  104. package/lib/view/expenseAutomationView/types/missingReceiptsViewState.js +54 -1
  105. package/lib/view/expenseAutomationView/types/transactionsViewState.d.ts +2 -1
  106. package/lib/view/expenseAutomationView/types/transactionsViewState.js +2 -1
  107. package/lib/view/taskManager/taskDetailView/taskDetailSelector.js +1 -1
  108. package/lib/view/taskManager/taskListView/epics/bulkUpdateTaskListEpic.d.ts +1 -0
  109. package/lib/view/taskManager/taskListView/epics/bulkUpdateTaskListEpic.js +1 -0
  110. package/lib/view/taskManager/taskListView/taskListSelector.d.ts +2 -0
  111. package/lib/view/taskManager/taskListView/taskListSelector.js +3 -1
  112. package/lib/view/userGroupListView/userGroupListViewReducer.d.ts +23 -0
  113. package/lib/view/userGroupListView/userGroupListViewReducer.js +69 -0
  114. package/lib/view/userGroupListView/userGroupListViewSelector.d.ts +7 -0
  115. package/lib/view/userGroupListView/userGroupListViewSelector.js +20 -0
  116. package/lib/view/userGroupListView/userGroupListViewState.d.ts +8 -0
  117. package/lib/view/userGroupListView/userGroupListViewState.js +2 -0
  118. package/lib/view/userListView/fetchUserListByTypeEpic.d.ts +3 -1
  119. package/lib/view/userListView/fetchUserListByTypeEpic.js +11 -0
  120. package/lib/view/userListView/userListViewPayload.d.ts +2 -0
  121. package/lib/zeniAPI.js +0 -2
  122. package/package.json +2 -2
@@ -0,0 +1,56 @@
1
+ import { EMPTY, concat, from, of } from 'rxjs';
2
+ import { catchError, filter, mergeMap } from 'rxjs/operators';
3
+ import { updateTransactions } from '../../../../entity/transaction/transactionReducer';
4
+ import { createZeniAPIStatus, isSuccessResponse, } from '../../../../responsePayload';
5
+ import { extractTransactionPayloadsFromBatchFiles, filterBatchListItemsForBatchDetailsFetch, isBatchDetailsApiStatusCompleted, shouldFetchBatchDetailsForBatchId, toBatchDetails, } from '../../payload/missingReceiptsPayload';
6
+ import { batchDetailFetchFailed, fetchBulkUploadBatchDetails, fetchBulkUploadBatchesSuccess, fetchMoreBatchDetailsComplete, setInitialBatchDetailsLoading, storeBatchDetails, } from '../../reducers/missingReceiptsViewReducer';
7
+ const INITIAL_BATCH_PAGE_SIZE = 5;
8
+ export function fetchBatchDetailsByIds(batchIds, zeniAPI) {
9
+ if (batchIds.length === 0) {
10
+ return EMPTY;
11
+ }
12
+ return from(batchIds).pipe(mergeMap((batchId) => zeniAPI
13
+ .getJSON(`${zeniAPI.apiEndPoints.communicationAgentMicroServiceBaseUrl}/1.0/batches/${batchId}`)
14
+ .pipe(mergeMap((response) => {
15
+ if (!isSuccessResponse(response) ||
16
+ response.data == null ||
17
+ !isBatchDetailsApiStatusCompleted(response.data.status)) {
18
+ return EMPTY;
19
+ }
20
+ const actions = [];
21
+ const transactionPayloads = extractTransactionPayloadsFromBatchFiles(response.data.files);
22
+ if (transactionPayloads.length > 0) {
23
+ actions.push(updateTransactions(transactionPayloads, (value) => value.transaction_id));
24
+ }
25
+ actions.push(storeBatchDetails(toBatchDetails(response.data, zeniAPI.apiEndPoints.fileMicroServiceBaseUrl)));
26
+ return from(actions);
27
+ }), catchError((error) => {
28
+ console.error(`Failed to fetch batch details for ${batchId}:`, createZeniAPIStatus('Unexpected Error', 'Fetch batch details errored out: ' + JSON.stringify(error)));
29
+ return of(batchDetailFetchFailed({ batchId }));
30
+ })), 5));
31
+ }
32
+ export const fetchMultipleBatchDetailsEpic = (actions$, state$, zeniAPI) => actions$.pipe(filter(fetchBulkUploadBatchesSuccess.match), mergeMap((action) => {
33
+ const batchList = action.payload.batchList;
34
+ const { batchDetailsById } = state$.value.expenseAutomationMissingReceiptsViewState.bulkUpload;
35
+ /** Only completed list rows may trigger batch-details API; preserve platform order. */
36
+ const completedBatchesMissingDetails = filterBatchListItemsForBatchDetailsFetch(batchList).filter((batch) => batchDetailsById[batch.batchId] == null);
37
+ const completedBatchIds = completedBatchesMissingDetails.map((batch) => batch.batchId);
38
+ const batchIdsToFetch = completedBatchIds.slice(0, INITIAL_BATCH_PAGE_SIZE);
39
+ if (batchIdsToFetch.length === 0) {
40
+ /**
41
+ * List refresh can complete while no row is `completed` yet (multi-fetch skips), or
42
+ * `currentBatchId` may not appear in the filtered list but still needs `GET /batches/:id`.
43
+ * Fall back to the single-batch-details epic so `phase` and details can resolve.
44
+ */
45
+ const bulkUpload = state$.value.expenseAutomationMissingReceiptsViewState.bulkUpload;
46
+ const currentId = bulkUpload.currentBatchId;
47
+ if (currentId != null &&
48
+ bulkUpload.phase === 'matching' &&
49
+ bulkUpload.batchDetailsById[currentId] == null &&
50
+ shouldFetchBatchDetailsForBatchId(bulkUpload.batchStatusById, bulkUpload.batchListByPeriod, currentId)) {
51
+ return of(fetchBulkUploadBatchDetails());
52
+ }
53
+ return EMPTY;
54
+ }
55
+ return concat(of(setInitialBatchDetailsLoading()), fetchBatchDetailsByIds(batchIdsToFetch, zeniAPI), of(fetchMoreBatchDetailsComplete()));
56
+ }));
@@ -0,0 +1,77 @@
1
+ import { EMPTY, from, merge, of } from 'rxjs';
2
+ import { catchError, debounceTime, filter, mergeMap, switchMap, } from 'rxjs/operators';
3
+ import { convertToPeriod } from '../../../../commonStateTypes/timePeriod';
4
+ import { getCurrentTenant } from '../../../../entity/tenant/tenantSelector';
5
+ import { updateTransactions } from '../../../../entity/transaction/transactionReducer';
6
+ import { createZeniAPIStatus, isSuccessResponse, } from '../../../../responsePayload';
7
+ import { supportedTransactionPayloadToManualSearchResult } from '../../payload/missingReceiptsPayload';
8
+ import { searchTransactionsForManualMatch, searchTransactionsForManualMatchFailure, searchTransactionsForManualMatchSuccess, } from '../../reducers/missingReceiptsViewReducer';
9
+ import { toTransactionsSortKey } from '../../types/transactionsViewState';
10
+ /**
11
+ * `auto_categorized` for manual transaction search (Unmatched).
12
+ * Backend contract TBD — align with `fetchTransactionCategorizationEpic` (`selectedTab === 'autoCategorized'`)
13
+ * when the expense-automation API documents the intended filter for this flow.
14
+ */
15
+ export const MANUAL_TRANSACTION_SEARCH_AUTO_CATEGORIZED = false;
16
+ export const searchTransactionsForManualMatchEpic = (actions$, state$, zeniAPI) => {
17
+ const searchActions$ = actions$.pipe(filter(searchTransactionsForManualMatch.match));
18
+ const pagination$ = searchActions$.pipe(filter((action) => action.payload.pageToken != null));
19
+ /**
20
+ * No API for empty or 1-char queries; immediate merge so switchMap cancels any in-flight HTTP.
21
+ */
22
+ const newSearchTooShortOrClear$ = searchActions$.pipe(filter((action) => action.payload.pageToken == null &&
23
+ action.payload.query.trim().length < 2));
24
+ const newSearchDebounced$ = searchActions$.pipe(filter((action) => action.payload.pageToken == null &&
25
+ action.payload.query.trim().length >= 2), debounceTime(300));
26
+ return merge(pagination$, newSearchTooShortOrClear$, newSearchDebounced$).pipe(switchMap((action) => {
27
+ const { query, pageToken } = action.payload;
28
+ if (pageToken == null && query.trim().length < 2) {
29
+ return EMPTY;
30
+ }
31
+ const state = state$.value;
32
+ const { expenseAutomationViewState: { selectedPeriodByTenantId }, expenseAutomationMissingReceiptsViewState: { bulkUpload: { manualSearch, sortKey, sortOrder }, }, } = state;
33
+ const currentTenant = getCurrentTenant(state);
34
+ const selectedPeriod = selectedPeriodByTenantId[currentTenant.tenantId];
35
+ if (selectedPeriod == null) {
36
+ return of(searchTransactionsForManualMatchFailure({
37
+ error: createZeniAPIStatus('Unexpected Error', 'Manual search requires a selected accounting period.'),
38
+ }));
39
+ }
40
+ const period = convertToPeriod(selectedPeriod);
41
+ const queryParam = {
42
+ start_date: period.start,
43
+ end_date: period.end,
44
+ auto_categorized: MANUAL_TRANSACTION_SEARCH_AUTO_CATEGORIZED,
45
+ sort_by: toTransactionsSortKey(sortKey),
46
+ sort_order: sortOrder === 'ascending' ? 'asc' : 'desc',
47
+ page_token: pageToken ?? null,
48
+ page_size: manualSearch.pageSize,
49
+ search_text: query,
50
+ };
51
+ return zeniAPI
52
+ .getJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/expense-automation/transactions?query=${encodeURIComponent(JSON.stringify(queryParam))}`)
53
+ .pipe(mergeMap((response) => {
54
+ if (isSuccessResponse(response) && response.data != null) {
55
+ const { transactions, next_page_token, total_count } = response.data;
56
+ const append = pageToken != null;
57
+ const results = transactions.map(supportedTransactionPayloadToManualSearchResult);
58
+ const actionsOut = [
59
+ updateTransactions(transactions, (value) => value.transaction_id, 'merge'),
60
+ searchTransactionsForManualMatchSuccess({
61
+ append,
62
+ nextPageToken: next_page_token ?? null,
63
+ results,
64
+ totalCount: total_count,
65
+ }),
66
+ ];
67
+ return from(actionsOut);
68
+ }
69
+ return of(searchTransactionsForManualMatchFailure({
70
+ error: response.status,
71
+ }));
72
+ }), catchError((error) => of(searchTransactionsForManualMatchFailure({
73
+ error: createZeniAPIStatus('Unexpected Error', 'Search transactions for manual match errored: ' +
74
+ JSON.stringify(error)),
75
+ }))));
76
+ }));
77
+ };
@@ -12,11 +12,13 @@ export const uploadMissingReceiptSuccessEpic = (actions$, state$) => actions$.pi
12
12
  updateActions.push(updateTransaction(transactionPayload.transaction_id, transactionPayload, updateType));
13
13
  if (currentTenant != null) {
14
14
  const monthEndChecksPeriod = selectedPeriodByTenantId[currentTenant.tenantId];
15
- updateActions.push(fetchMonthEndCloseChecks({
16
- tenantId: currentTenant.tenantId,
17
- period: monthEndChecksPeriod,
18
- refreshViewInBackground: true,
19
- }));
15
+ if (monthEndChecksPeriod != null) {
16
+ updateActions.push(fetchMonthEndCloseChecks({
17
+ tenantId: currentTenant.tenantId,
18
+ period: monthEndChecksPeriod,
19
+ refreshViewInBackground: true,
20
+ }));
21
+ }
20
22
  }
21
23
  return from(updateActions);
22
24
  }));
@@ -0,0 +1,79 @@
1
+ import { EMPTY, from, merge, of, timer } from 'rxjs';
2
+ import { catchError, debounceTime, filter, mergeMap, switchMap, takeUntil, } from 'rxjs/operators';
3
+ import { openSnackbar } from '../../../../entity/snackbar/snackbarReducer';
4
+ import { updateTransactions } from '../../../../entity/transaction/transactionReducer';
5
+ import { isSuccessResponse } from '../../../../responsePayload';
6
+ import { BULK_UPLOAD_AUTOMATCHING_TIMEOUT_MS } from '../../bulkUploadTiming';
7
+ import { extractTransactionPayloadsFromBatchFiles, isBatchDetailsApiStatusCompleted, toBatchDetails, } from '../../payload/missingReceiptsPayload';
8
+ import { bulkUploadAutomatchingTimedOut, bulkUploadReceiptsSuccess, clearBulkUpload, fetchBulkUploadBatchDetailsSuccess, fetchBulkUploadBatches, pusherBatchStatusUpdate, requestMissingReceiptsTabNavigation, } from '../../reducers/missingReceiptsViewReducer';
9
+ /** First poll after upload; then interval while batch not resolved via Pusher or API. */
10
+ const FALLBACK_FIRST_DELAY_MS = 30000;
11
+ const FALLBACK_POLL_INTERVAL_MS = 10000;
12
+ /**
13
+ * On Pusher batch completion: refresh batch list (then fetchMultipleBatchDetailsEpic runs),
14
+ * and request switching to the Unmatched tab. Debounced to reduce duplicate refreshes.
15
+ */
16
+ export const pusherBatchStatusCompletionEpic = (actions$) => actions$.pipe(filter(pusherBatchStatusUpdate.match), filter((action) => action.payload.status === 'completed'), debounceTime(300), mergeMap(() => from([
17
+ fetchBulkUploadBatches({
18
+ cacheOverride: true,
19
+ invalidateBatchDetailsCache: true,
20
+ }),
21
+ requestMissingReceiptsTabNavigation({ tab: 'unmatched' }),
22
+ ])));
23
+ /**
24
+ * If Pusher and batch-details are delayed beyond {@link BULK_UPLOAD_AUTOMATCHING_TIMEOUT_MS},
25
+ * force `phase` to `completed` (dismiss automatching banner) and refresh the batch list.
26
+ * Cancels when the batch completes normally, bulk state is cleared, or another upload supersedes.
27
+ */
28
+ export const bulkUploadAutomatchingTimeoutEpic = (actions$, state$) => actions$.pipe(filter(bulkUploadReceiptsSuccess.match), mergeMap((action) => {
29
+ const { batchId } = action.payload;
30
+ return timer(BULK_UPLOAD_AUTOMATCHING_TIMEOUT_MS).pipe(mergeMap(() => {
31
+ const bulk = state$.value.expenseAutomationMissingReceiptsViewState.bulkUpload;
32
+ if (bulk.phase !== 'matching' || bulk.currentBatchId !== batchId) {
33
+ return EMPTY;
34
+ }
35
+ return from([
36
+ bulkUploadAutomatchingTimedOut(batchId),
37
+ fetchBulkUploadBatches({ cacheOverride: true }),
38
+ ]);
39
+ }), takeUntil(merge(actions$.pipe(filter(clearBulkUpload.match)), actions$.pipe(filter(pusherBatchStatusUpdate.match), filter((a) => a.payload.batchId === batchId &&
40
+ a.payload.status === 'completed')), actions$.pipe(filter(fetchBulkUploadBatchDetailsSuccess.match), filter((a) => a.payload.batchId === batchId)))));
41
+ }));
42
+ /**
43
+ * Fallback polling when Pusher is slow or unavailable. Network errors on a poll tick show one
44
+ * error snackbar per upload session (first failure only) so the user is not spammed every
45
+ * interval; Pusher or a later successful poll still completes the flow.
46
+ */
47
+ export const pollBulkUploadBatchStatusEpic = (actions$, _state$, zeniAPI) => actions$.pipe(filter(bulkUploadReceiptsSuccess.match), mergeMap((action) => {
48
+ const { batchId } = action.payload;
49
+ let pollErrorNotified = false;
50
+ return timer(FALLBACK_FIRST_DELAY_MS, FALLBACK_POLL_INTERVAL_MS).pipe(takeUntil(merge(actions$.pipe(filter(clearBulkUpload.match)), actions$.pipe(filter(pusherBatchStatusUpdate.match), filter((action) => action.payload.batchId === batchId)), actions$.pipe(filter(fetchBulkUploadBatchDetailsSuccess.match), filter((action) => action.payload.batchId === batchId)), actions$.pipe(filter(bulkUploadAutomatchingTimedOut.match), filter((action) => action.payload.batchId === batchId)))), switchMap(() => zeniAPI
51
+ .getJSON(`${zeniAPI.apiEndPoints.communicationAgentMicroServiceBaseUrl}/1.0/batches/${batchId}`)
52
+ .pipe(mergeMap((response) => {
53
+ /** Same batch-details URL; polls until `status` is completed (Pusher may win first). */
54
+ if (isSuccessResponse(response) && response.data != null) {
55
+ if (isBatchDetailsApiStatusCompleted(response.data.status)) {
56
+ const actions = [];
57
+ const transactionPayloads = extractTransactionPayloadsFromBatchFiles(response.data.files);
58
+ if (transactionPayloads.length > 0) {
59
+ actions.push(updateTransactions(transactionPayloads, (value) => value.transaction_id));
60
+ }
61
+ actions.push(fetchBulkUploadBatchDetailsSuccess(toBatchDetails(response.data, zeniAPI.apiEndPoints.fileMicroServiceBaseUrl)));
62
+ actions.push(fetchBulkUploadBatches({ cacheOverride: true }));
63
+ actions.push(requestMissingReceiptsTabNavigation({ tab: 'unmatched' }));
64
+ return from(actions);
65
+ }
66
+ }
67
+ return EMPTY;
68
+ }), catchError(() => {
69
+ if (!pollErrorNotified) {
70
+ pollErrorNotified = true;
71
+ return of(openSnackbar({
72
+ messageSection: 'receipts_upload',
73
+ messageText: 'failed',
74
+ type: 'error',
75
+ }));
76
+ }
77
+ return EMPTY;
78
+ }))));
79
+ }));
@@ -0,0 +1,24 @@
1
+ import { from } from 'rxjs';
2
+ import { filter, mergeMap } from 'rxjs/operators';
3
+ import { getCurrentTenant } from '../../../../entity/tenant/tenantSelector';
4
+ import { updateTransaction } from '../../../../entity/transaction/transactionReducer';
5
+ import { fetchMonthEndCloseChecks } from '../../../monthEndCloseChecksView/monthEndCloseChecksViewReducer';
6
+ import { uploadTransactionCategorizationReceiptSuccess } from '../../reducers/transactionsViewReducer';
7
+ export const uploadTransactionReceiptSuccessEpic = (actions$, state$) => actions$.pipe(filter(uploadTransactionCategorizationReceiptSuccess.match), mergeMap((action) => {
8
+ const { transactionPayload, updateType } = action.payload;
9
+ const updateActions = [];
10
+ const currentTenant = getCurrentTenant(state$.value);
11
+ const selectedPeriodByTenantId = state$.value.expenseAutomationViewState.selectedPeriodByTenantId;
12
+ updateActions.push(updateTransaction(transactionPayload.transaction_id, transactionPayload, updateType));
13
+ if (currentTenant != null) {
14
+ const monthEndChecksPeriod = selectedPeriodByTenantId[currentTenant.tenantId];
15
+ if (monthEndChecksPeriod != null) {
16
+ updateActions.push(fetchMonthEndCloseChecks({
17
+ tenantId: currentTenant.tenantId,
18
+ period: monthEndChecksPeriod,
19
+ refreshViewInBackground: true,
20
+ }));
21
+ }
22
+ }
23
+ return from(updateActions);
24
+ }));
@@ -1 +1,189 @@
1
- export {};
1
+ import { toURL } from '../../../commonPayloadTypes/urlPayload';
2
+ import { toAmount } from '../../../commonStateTypes/amount';
3
+ import { getTransactionPayloadAmount, } from '../../../entity/transaction/payloadTypes/transactionPayload';
4
+ import { toBatchFileStatus, toBatchStatusValue, toMatchSource, } from '../types/missingReceiptsViewState';
5
+ // -- Converter functions --
6
+ /**
7
+ * Maps batch-details API `files[].status` strings to canonical {@link BatchFileStatus}.
8
+ * Legacy aliases are supported during rollout; unknown strings map to `failed` so Redux never
9
+ * holds untyped status values.
10
+ */
11
+ export function parseBatchFileStatus(raw) {
12
+ const normalizedStatus = raw.trim().toLowerCase().replace(/-/g, '_');
13
+ switch (normalizedStatus) {
14
+ case 'exact_match':
15
+ case 'matched':
16
+ return 'exact_match';
17
+ case 'possible_matches':
18
+ case 'possible_match':
19
+ case 'possiblematch':
20
+ case 'un_matched':
21
+ case 'unmatched':
22
+ return 'possible_matches';
23
+ case 'no_match':
24
+ case 'nomatch':
25
+ return 'no_match';
26
+ case 'failed':
27
+ return 'failed';
28
+ default:
29
+ return 'failed';
30
+ }
31
+ }
32
+ export function toBatchFile(payload, filesEndPoint) {
33
+ return {
34
+ attachmentId: payload.attachment_id,
35
+ candidates: payload.candidates?.map((candidate) => ({
36
+ transactionId: candidate.transaction_id,
37
+ matchScore: candidate.match_score,
38
+ })),
39
+ fileDownloadUrl: payload.file_id != null && filesEndPoint != null
40
+ ? `${filesEndPoint}/1.0/files/${payload.file_id}?query=${encodeURIComponent(JSON.stringify({ download_file: true }))}`
41
+ : null,
42
+ fileId: payload.file_id,
43
+ filePreviewUrl: payload.file_preview_url,
44
+ filename: payload.filename,
45
+ matchSource: payload.match_source != null
46
+ ? toMatchSource(payload.match_source)
47
+ : undefined,
48
+ matchedTransactionId: payload.matched_transaction?.transaction_id,
49
+ status: toBatchFileStatus(payload.status),
50
+ };
51
+ }
52
+ export function extractTransactionPayloadsFromBatchFiles(files) {
53
+ const seen = new Set();
54
+ const payloads = [];
55
+ for (const file of files) {
56
+ if (file.matched_transaction != null) {
57
+ const id = file.matched_transaction.transaction_id;
58
+ if (!seen.has(id)) {
59
+ seen.add(id);
60
+ payloads.push(matchedTransactionPayloadToSupportedTransactionPayload(file.matched_transaction));
61
+ }
62
+ }
63
+ if (file.candidates != null) {
64
+ for (const candidate of file.candidates) {
65
+ const id = candidate.transaction_id;
66
+ if (!seen.has(id)) {
67
+ seen.add(id);
68
+ payloads.push(matchedTransactionPayloadToSupportedTransactionPayload(candidate));
69
+ }
70
+ }
71
+ }
72
+ }
73
+ return payloads;
74
+ }
75
+ function matchedTransactionPayloadToSupportedTransactionPayload(payload) {
76
+ return {
77
+ transaction_id: payload.transaction_id,
78
+ transaction_type: payload.transaction_type ?? 'expense',
79
+ transaction_date: payload.transaction_date ?? '',
80
+ currency_code: payload.currency_code,
81
+ total_amount: payload.amount,
82
+ vendor_name: payload.vendor_name,
83
+ logo: payload.vendor_logo == null ? undefined : toURL(payload.vendor_logo),
84
+ };
85
+ }
86
+ export function toBatchSummary(payload) {
87
+ return {
88
+ failed: payload.failed,
89
+ matched: payload.matched,
90
+ noMatch: payload.no_match,
91
+ possibleMatches: payload.possible_matches,
92
+ total: payload.total,
93
+ };
94
+ }
95
+ export function toBatchDetails(payload, filesEndPoint) {
96
+ return {
97
+ batchId: payload.batch_id,
98
+ createdAt: payload.created_at,
99
+ files: payload.files.map((file) => toBatchFile(file, filesEndPoint)),
100
+ status: toBatchStatusValue(payload.status),
101
+ summary: toBatchSummary(payload.summary),
102
+ };
103
+ }
104
+ /** Batch list `status` is a string from the API — compare case-insensitively. */
105
+ export function isBatchListStatusCompleted(status) {
106
+ return status.toLowerCase() === 'completed';
107
+ }
108
+ /**
109
+ * Subset of the get-all-batches (`/batches?query=...`) list that is eligible for
110
+ * `GET /batches/:batchId` details fetches. The stored list may include pending, failed, or other
111
+ * statuses for UI; only `completed` rows should trigger batch-details requests.
112
+ */
113
+ export function filterBatchListItemsForBatchDetailsFetch(batches) {
114
+ return batches.filter((batch) => isBatchListStatusCompleted(batch.status));
115
+ }
116
+ /**
117
+ * Batch details API response `status` field — only completed payloads should be stored from
118
+ * multi-batch fetch paths (list can be briefly stale vs. live processing state).
119
+ */
120
+ export function isBatchDetailsApiStatusCompleted(status) {
121
+ return status.toLowerCase() === 'completed';
122
+ }
123
+ export function findBatchListItemForBatchId(batchListByPeriod, batchId) {
124
+ for (const list of Object.values(batchListByPeriod)) {
125
+ const found = list.find((batch) => batch.batchId === batchId);
126
+ if (found != null) {
127
+ return found;
128
+ }
129
+ }
130
+ return undefined;
131
+ }
132
+ /**
133
+ * Whether it is appropriate to call `GET .../batches/:id` for details.
134
+ * Skips when live batch status or batch list row indicates the batch is not completed yet.
135
+ * When status is unknown in both sources, allows the request (e.g. dispatch before list refresh).
136
+ */
137
+ export function shouldFetchBatchDetailsForBatchId(batchStatusById, batchListByPeriod, batchId) {
138
+ const live = batchStatusById[batchId]?.status;
139
+ if (live === 'completed') {
140
+ return true;
141
+ }
142
+ if (live === 'pending' || live === 'processing') {
143
+ return false;
144
+ }
145
+ const listItem = findBatchListItemForBatchId(batchListByPeriod, batchId);
146
+ if (listItem != null && !isBatchListStatusCompleted(listItem.status)) {
147
+ return false;
148
+ }
149
+ return true;
150
+ }
151
+ export function toBatchListItem(payload) {
152
+ return {
153
+ batchId: payload.batch_id,
154
+ createdAt: payload.created_at,
155
+ failedCount: payload.failed_count,
156
+ matchedCount: payload.matched_count,
157
+ noMatchCount: payload.no_match_count,
158
+ possibleMatchesCount: payload.possible_matches_count,
159
+ status: payload.status,
160
+ totalFiles: payload.total_files,
161
+ };
162
+ }
163
+ /**
164
+ * Amount shown in the Unmatched tab manual-search list: **first line only** when `lines` exist.
165
+ * Falls back to transaction-level totals via {@link getTransactionPayloadAmount} when there is
166
+ * no line or no line amount (same currency fields as the rest of the transaction payload).
167
+ */
168
+ function getManualSearchListAmountFromPayload(payload) {
169
+ const lineAmount = payload.lines?.[0]?.amount;
170
+ if (lineAmount != null) {
171
+ return toAmount(lineAmount, payload.currency_code, payload.currency_symbol);
172
+ }
173
+ return getTransactionPayloadAmount(payload);
174
+ }
175
+ /** Maps expense-automation transaction rows to manual-search list rows (Unmatched tab). */
176
+ export function supportedTransactionPayloadToManualSearchResult(payload) {
177
+ const amountPayload = getManualSearchListAmountFromPayload(payload);
178
+ return {
179
+ amount: amountPayload.amount,
180
+ currencyCode: amountPayload.currencyCode,
181
+ entityId: payload.vendor_id ?? payload.customer_id ?? '',
182
+ memo: payload.transaction_memo ?? '',
183
+ transactionDate: payload.transaction_date,
184
+ transactionId: payload.transaction_id,
185
+ transactionType: payload.transaction_type,
186
+ vendorName: payload.vendor_name ?? '',
187
+ vendorLogo: toURL(payload.logo)?.href,
188
+ };
189
+ }