@zeniai/client-epic-state 5.2.13 → 5.2.14-betaRD0

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 (126) hide show
  1. package/lib/entity/jeSchedules/jeScheduleHelper.d.ts +1 -0
  2. package/lib/entity/jeSchedules/jeScheduleHelper.js +7 -0
  3. package/lib/entity/jeSchedules/jeSchedulesPayload.d.ts +78 -1
  4. package/lib/entity/jeSchedules/jeSchedulesPayload.js +183 -4
  5. package/lib/entity/jeSchedules/jeSchedulesReducer.d.ts +4 -2
  6. package/lib/entity/jeSchedules/jeSchedulesReducer.js +30 -2
  7. package/lib/entity/jeSchedules/jeSchedulesSelector.d.ts +11 -2
  8. package/lib/entity/jeSchedules/jeSchedulesSelector.js +38 -3
  9. package/lib/entity/jeSchedules/jeSchedulesState.d.ts +123 -1
  10. package/lib/entity/jeSchedules/jeSchedulesTypes.d.ts +24 -1
  11. package/lib/entity/jeSchedules/jeSchedulesTypes.js +96 -1
  12. package/lib/entity/snackbar/snackbarTypes.d.ts +1 -1
  13. package/lib/entity/snackbar/snackbarTypes.js +3 -0
  14. package/lib/entity/transaction/payloadTypes/scheduleTransactionPayload.d.ts +2 -0
  15. package/lib/entity/transaction/payloadTypes/scheduleTransactionPayload.js +2 -0
  16. package/lib/entity/transaction/stateTypes/scheduleTransaction.d.ts +2 -0
  17. package/lib/epic.d.ts +9 -1
  18. package/lib/epic.js +16 -0
  19. package/lib/esm/entity/jeSchedules/jeScheduleHelper.js +6 -0
  20. package/lib/esm/entity/jeSchedules/jeSchedulesPayload.js +183 -5
  21. package/lib/esm/entity/jeSchedules/jeSchedulesReducer.js +30 -2
  22. package/lib/esm/entity/jeSchedules/jeSchedulesSelector.js +36 -2
  23. package/lib/esm/entity/jeSchedules/jeSchedulesTypes.js +86 -0
  24. package/lib/esm/entity/snackbar/snackbarTypes.js +3 -0
  25. package/lib/esm/entity/transaction/payloadTypes/scheduleTransactionPayload.js +2 -0
  26. package/lib/esm/epic.js +16 -0
  27. package/lib/esm/index.js +17 -11
  28. package/lib/esm/view/expenseAutomationView/epics/common/fetchAllExpenseAutomationTabsEpic.js +6 -3
  29. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/fetchJeSchedulePageEpic.js +9 -1
  30. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/fetchJeSchedulesEpic.js +41 -5
  31. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/fetchOneTimeAccrualEpic.js +45 -0
  32. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/ignoreRecommendedJeScheduleEpic.js +14 -2
  33. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/newSchedule/createOneTimeAccrualEpic.js +104 -0
  34. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/newSchedule/initializeNewScheduleEpic.js +25 -0
  35. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/newSchedule/saveNewScheduleEpic.js +138 -0
  36. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/newSchedule/searchTransactionsForNewScheduleEpic.js +79 -0
  37. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/oneTimeAccrualActionsEpic.js +180 -0
  38. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/revertJeScheduleEpic.js +111 -0
  39. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/switchJESchedulesTabEpic.js +28 -0
  40. package/lib/esm/view/expenseAutomationView/helpers/newScheduleLocalDataHelper.js +140 -0
  41. package/lib/esm/view/expenseAutomationView/payload/jeSchedulesPayload.js +55 -0
  42. package/lib/esm/view/expenseAutomationView/reducers/jeSchedulesViewReducer.js +319 -29
  43. package/lib/esm/view/expenseAutomationView/selectorTypes/jeNewScheduleViewSelectorTypes.js +1 -0
  44. package/lib/esm/view/expenseAutomationView/selectors/jeAccountSettingsViewSelector.js +1 -0
  45. package/lib/esm/view/expenseAutomationView/selectors/jeNewScheduleViewSelector.js +106 -0
  46. package/lib/esm/view/expenseAutomationView/selectors/jeSchedulesViewSelector.js +327 -22
  47. package/lib/esm/view/expenseAutomationView/types/jeSchedulesViewState.js +5 -6
  48. package/lib/esm/view/invoicing/editInvoicingCatalogItemDetailView/catalogDetailEditPayload.js +24 -7
  49. package/lib/esm/view/invoicing/editInvoicingCatalogItemDetailView/editInvoicingCatalogItemDetailViewPayload.js +1 -1
  50. package/lib/esm/view/invoicing/editInvoicingCatalogItemDetailView/editInvoicingCatalogItemDetailViewReducer.js +8 -1
  51. package/lib/esm/view/invoicing/editInvoicingCatalogItemDetailView/editInvoicingCatalogItemDetailViewSelector.js +42 -8
  52. package/lib/esm/view/invoicing/editInvoicingCatalogItemDetailView/invoicingCatalogSubFamilyEpics.js +8 -2
  53. package/lib/esm/view/invoicing/editInvoicingCatalogItemDetailView/saveInvoicingCatalogItemEpic.js +19 -10
  54. package/lib/esm/view/invoicing/invoicingCatalogItemDetailView/invoicingCatalogItemDetailViewSelector.js +2 -0
  55. package/lib/esm/view/invoicing/invoicingQboView/epics/fetchInvoicingAccountingPickersEpic.js +0 -1
  56. package/lib/esm/view/invoicing/invoicingQboView/invoicingQboViewSelector.js +15 -36
  57. package/lib/esm/view/scheduleView/scheduleListView/epics/fetchAccruedScheduleListEpic.js +1 -1
  58. package/lib/esm/view/scheduleView/scheduleListView/epics/fetchDownloadSchedulesEpic.js +7 -2
  59. package/lib/esm/view/scheduleView/scheduleListView/scheduleListReducer.js +5 -3
  60. package/lib/index.d.ts +24 -18
  61. package/lib/index.js +93 -48
  62. package/lib/view/expenseAutomationView/epics/common/fetchAllExpenseAutomationTabsEpic.js +6 -3
  63. package/lib/view/expenseAutomationView/epics/jeSchedule/fetchJeSchedulePageEpic.js +9 -1
  64. package/lib/view/expenseAutomationView/epics/jeSchedule/fetchJeSchedulesEpic.d.ts +3 -2
  65. package/lib/view/expenseAutomationView/epics/jeSchedule/fetchJeSchedulesEpic.js +39 -3
  66. package/lib/view/expenseAutomationView/epics/jeSchedule/fetchOneTimeAccrualEpic.d.ts +21 -0
  67. package/lib/view/expenseAutomationView/epics/jeSchedule/fetchOneTimeAccrualEpic.js +49 -0
  68. package/lib/view/expenseAutomationView/epics/jeSchedule/ignoreRecommendedJeScheduleEpic.js +14 -2
  69. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/createOneTimeAccrualEpic.d.ts +9 -0
  70. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/createOneTimeAccrualEpic.js +108 -0
  71. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/initializeNewScheduleEpic.d.ts +8 -0
  72. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/initializeNewScheduleEpic.js +29 -0
  73. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/saveNewScheduleEpic.d.ts +9 -0
  74. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/saveNewScheduleEpic.js +142 -0
  75. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/searchTransactionsForNewScheduleEpic.d.ts +8 -0
  76. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/searchTransactionsForNewScheduleEpic.js +83 -0
  77. package/lib/view/expenseAutomationView/epics/jeSchedule/oneTimeAccrualActionsEpic.d.ts +13 -0
  78. package/lib/view/expenseAutomationView/epics/jeSchedule/oneTimeAccrualActionsEpic.js +187 -0
  79. package/lib/view/expenseAutomationView/epics/jeSchedule/revertJeScheduleEpic.d.ts +65 -0
  80. package/lib/view/expenseAutomationView/epics/jeSchedule/revertJeScheduleEpic.js +115 -0
  81. package/lib/view/expenseAutomationView/epics/jeSchedule/switchJESchedulesTabEpic.d.ts +6 -0
  82. package/lib/view/expenseAutomationView/epics/jeSchedule/switchJESchedulesTabEpic.js +32 -0
  83. package/lib/view/expenseAutomationView/helpers/newScheduleLocalDataHelper.d.ts +36 -0
  84. package/lib/view/expenseAutomationView/helpers/newScheduleLocalDataHelper.js +145 -0
  85. package/lib/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.d.ts +1 -1
  86. package/lib/view/expenseAutomationView/payload/jeSchedulesPayload.d.ts +86 -3
  87. package/lib/view/expenseAutomationView/payload/jeSchedulesPayload.js +58 -1
  88. package/lib/view/expenseAutomationView/reducers/jeSchedulesViewReducer.d.ts +93 -12
  89. package/lib/view/expenseAutomationView/reducers/jeSchedulesViewReducer.js +321 -29
  90. package/lib/view/expenseAutomationView/reducers/missingReceiptsViewReducer.d.ts +1 -1
  91. package/lib/view/expenseAutomationView/reducers/transactionsViewReducer.d.ts +2 -2
  92. package/lib/view/expenseAutomationView/selectorTypes/jeAccountSettingsViewSelectorTypes.d.ts +1 -0
  93. package/lib/view/expenseAutomationView/selectorTypes/jeNewScheduleViewSelectorTypes.d.ts +42 -0
  94. package/lib/view/expenseAutomationView/selectorTypes/jeNewScheduleViewSelectorTypes.js +2 -0
  95. package/lib/view/expenseAutomationView/selectorTypes/jeSchedulesSelectorTypes.d.ts +41 -7
  96. package/lib/view/expenseAutomationView/selectors/jeAccountSettingsViewSelector.js +1 -0
  97. package/lib/view/expenseAutomationView/selectors/jeNewScheduleViewSelector.d.ts +21 -0
  98. package/lib/view/expenseAutomationView/selectors/jeNewScheduleViewSelector.js +112 -0
  99. package/lib/view/expenseAutomationView/selectors/jeSchedulesViewSelector.d.ts +34 -0
  100. package/lib/view/expenseAutomationView/selectors/jeSchedulesViewSelector.js +335 -21
  101. package/lib/view/expenseAutomationView/types/completedSubTab.d.ts +1 -1
  102. package/lib/view/expenseAutomationView/types/jeSchedulesViewState.d.ts +83 -8
  103. package/lib/view/expenseAutomationView/types/jeSchedulesViewState.js +8 -8
  104. package/lib/view/expenseAutomationView/types/reconciliationViewState.d.ts +1 -1
  105. package/lib/view/invoicing/editInvoicingCatalogItemDetailView/catalogDetailEditPayload.d.ts +13 -21
  106. package/lib/view/invoicing/editInvoicingCatalogItemDetailView/catalogDetailEditPayload.js +24 -7
  107. package/lib/view/invoicing/editInvoicingCatalogItemDetailView/editInvoicingCatalogItemDetailViewPayload.d.ts +7 -0
  108. package/lib/view/invoicing/editInvoicingCatalogItemDetailView/editInvoicingCatalogItemDetailViewPayload.js +4 -3
  109. package/lib/view/invoicing/editInvoicingCatalogItemDetailView/editInvoicingCatalogItemDetailViewReducer.d.ts +18 -9
  110. package/lib/view/invoicing/editInvoicingCatalogItemDetailView/editInvoicingCatalogItemDetailViewReducer.js +9 -2
  111. package/lib/view/invoicing/editInvoicingCatalogItemDetailView/editInvoicingCatalogItemDetailViewSelector.d.ts +15 -5
  112. package/lib/view/invoicing/editInvoicingCatalogItemDetailView/editInvoicingCatalogItemDetailViewSelector.js +43 -8
  113. package/lib/view/invoicing/editInvoicingCatalogItemDetailView/editInvoicingCatalogItemDetailViewState.d.ts +24 -0
  114. package/lib/view/invoicing/editInvoicingCatalogItemDetailView/invoicingCatalogSubFamilyEpics.d.ts +1 -1
  115. package/lib/view/invoicing/editInvoicingCatalogItemDetailView/invoicingCatalogSubFamilyEpics.js +8 -2
  116. package/lib/view/invoicing/editInvoicingCatalogItemDetailView/saveInvoicingCatalogItemEpic.js +18 -9
  117. package/lib/view/invoicing/invoicingCatalogItemDetailView/invoicingCatalogItemDetailViewSelector.d.ts +6 -0
  118. package/lib/view/invoicing/invoicingCatalogItemDetailView/invoicingCatalogItemDetailViewSelector.js +2 -0
  119. package/lib/view/invoicing/invoicingQboView/epics/fetchInvoicingAccountingPickersEpic.js +0 -1
  120. package/lib/view/invoicing/invoicingQboView/invoicingQboViewSelector.d.ts +13 -13
  121. package/lib/view/invoicing/invoicingQboView/invoicingQboViewSelector.js +17 -38
  122. package/lib/view/scheduleView/scheduleListView/epics/fetchAccruedScheduleListEpic.js +1 -1
  123. package/lib/view/scheduleView/scheduleListView/epics/fetchDownloadSchedulesEpic.js +7 -2
  124. package/lib/view/scheduleView/scheduleListView/scheduleListReducer.d.ts +4 -2
  125. package/lib/view/scheduleView/scheduleListView/scheduleListReducer.js +5 -3
  126. package/package.json +1 -1
@@ -0,0 +1,138 @@
1
+ import { from } from 'rxjs';
2
+ import { catchError, filter, mergeMap, takeUntil } from 'rxjs/operators';
3
+ import { convertToPeriod, toAbsoluteDay, } from '../../../../../commonStateTypes/timePeriod';
4
+ import { getCurrentTenant } from '../../../../../entity/tenant/tenantSelector';
5
+ import { clearAll } from '../../../../../rootActions';
6
+ import { updateJESchedules, updateJESchedulesDetails, } from '../../../../../entity/jeSchedules/jeSchedulesReducer';
7
+ import { getJEScheduleTransactionKey } from '../../../../../entity/jeSchedules/jeSchedulesTypes';
8
+ import { openSnackbar } from '../../../../../entity/snackbar/snackbarReducer';
9
+ import { getScheduleTransactionById } from '../../../../../entity/transaction/transactionSelector';
10
+ import { createZeniAPIStatus, isSuccessResponse, } from '../../../../../responsePayload';
11
+ import { prepareNewSchedulePayload, } from '../../../helpers/newScheduleLocalDataHelper';
12
+ import { fetchJeSchedules, resetNewScheduleLocalData, saveNewSchedule, saveNewScheduleFailure, saveNewScheduleSuccess, } from '../../../reducers/jeSchedulesViewReducer';
13
+ const FAILURE_REASON_MESSAGES = {
14
+ missing_third_party_id: 'This transaction is missing a QuickBooks reference and cannot be scheduled.',
15
+ // The form cannot satisfy this: the vendor field is hard-disabled and inherited from the base
16
+ // transaction, so the fix is on the transaction, not here.
17
+ missing_vendor: 'This transaction has no vendor and cannot be scheduled. Add a vendor to the transaction first.',
18
+ };
19
+ export const saveNewScheduleEpic = (actions$, state$, zeniAPI) => actions$.pipe(filter(saveNewSchedule.match), mergeMap((action) => {
20
+ const { scheduleType } = action.payload;
21
+ const state = state$.value;
22
+ const localData = state.expenseAutomationJESchedulesViewState.newSchedule
23
+ .newScheduleState[scheduleType];
24
+ const { selectedBaseTransactionId } = localData;
25
+ const transaction = selectedBaseTransactionId != null
26
+ ? getScheduleTransactionById(state.transactionState, getJEScheduleTransactionKey(selectedBaseTransactionId))
27
+ : undefined;
28
+ if (transaction == null) {
29
+ return from([
30
+ saveNewScheduleFailure({
31
+ status: createZeniAPIStatus('Unexpected Error', 'No base transaction selected for this schedule.'),
32
+ }),
33
+ openSnackbar({
34
+ messageSection: 'create_schedule',
35
+ messageText: 'failed',
36
+ type: 'error',
37
+ variables: [
38
+ {
39
+ variableName: '_api-error_',
40
+ variableValue: 'No base transaction selected.',
41
+ },
42
+ ],
43
+ }),
44
+ ]);
45
+ }
46
+ const result = prepareNewSchedulePayload(transaction, localData, scheduleType);
47
+ if (!result.ok) {
48
+ const message = FAILURE_REASON_MESSAGES[result.reason];
49
+ return from([
50
+ saveNewScheduleFailure({
51
+ status: createZeniAPIStatus('Unexpected Error', message),
52
+ }),
53
+ openSnackbar({
54
+ messageSection: 'create_schedule',
55
+ messageText: 'failed',
56
+ type: 'error',
57
+ variables: [{ variableName: '_api-error_', variableValue: message }],
58
+ }),
59
+ ]);
60
+ }
61
+ const vendorName = localData.selectedVendor?.name ?? transaction.vendorName ?? '';
62
+ const queryParam = {
63
+ je_schedule_type: scheduleType,
64
+ };
65
+ const payload = { ...result.payload };
66
+ // convertToPeriod destructures, so an unset period would throw here and take the epic
67
+ // subscription down for the whole session -- a missed refresh is the cheaper failure.
68
+ const selectedMonthYear = state.expenseAutomationViewState.selectedPeriodByTenantId[getCurrentTenant(state).tenantId];
69
+ const selectedPeriod = selectedMonthYear != null
70
+ ? convertToPeriod(selectedMonthYear)
71
+ : undefined;
72
+ const periodStart = selectedPeriod != null
73
+ ? toAbsoluteDay(selectedPeriod.start)
74
+ : undefined;
75
+ const periodEnd = selectedPeriod != null ? toAbsoluteDay(selectedPeriod.end) : undefined;
76
+ return zeniAPI
77
+ .postAndGetJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/schedules?query=${encodeURIComponent(JSON.stringify(queryParam))}`, payload)
78
+ .pipe(mergeMap((response) => {
79
+ if (isSuccessResponse(response) && response.data != null) {
80
+ const successActions = [
81
+ updateJESchedules(response.data.je_schedules),
82
+ updateJESchedulesDetails(response.data.je_schedules, response.data.scheduled_journal_entries),
83
+ resetNewScheduleLocalData({ scheduleType }),
84
+ saveNewScheduleSuccess(),
85
+ openSnackbar({
86
+ messageSection: 'create_schedule',
87
+ messageText: 'success',
88
+ type: 'success',
89
+ variables: [
90
+ { variableName: '_vendor_name_', variableValue: vendorName },
91
+ ],
92
+ }),
93
+ ];
94
+ // Writing the entity is not enough: the list reads
95
+ // jeScheduleTransactionKeysByPeriodAndTab, which is rebuilt wholesale per fetch, so
96
+ // without this the new schedule stays invisible until some later fetch. The page
97
+ // only refetches when the save also changes tab, so saving from the tab the row
98
+ // lands on showed nothing. Same reasoning as createOneTimeAccrualEpic.
99
+ if (periodStart != null && periodEnd != null) {
100
+ successActions.push(fetchJeSchedules({ start: periodStart, end: periodEnd }, true));
101
+ }
102
+ return from(successActions);
103
+ }
104
+ return from([
105
+ saveNewScheduleFailure({ status: response.status }),
106
+ openSnackbar({
107
+ messageSection: 'create_schedule',
108
+ messageText: 'failed',
109
+ type: 'error',
110
+ variables: [
111
+ {
112
+ variableName: '_api-error_',
113
+ variableValue: response.status.message,
114
+ },
115
+ ],
116
+ }),
117
+ ]);
118
+ }), catchError((error) => from([
119
+ openSnackbar({
120
+ messageSection: 'create_schedule',
121
+ messageText: 'failed',
122
+ type: 'error',
123
+ variables: [
124
+ {
125
+ variableName: '_api-error_',
126
+ variableValue: JSON.stringify(error),
127
+ },
128
+ ],
129
+ }),
130
+ saveNewScheduleFailure({
131
+ status: createZeniAPIStatus('Unexpected Error', `Save New Schedule REST API call errored out ${JSON.stringify(error)}`),
132
+ }),
133
+ ])),
134
+ // A tenant switch clears the store while this request is still in flight.
135
+ // Without this the old tenant's response is written back into the freshly
136
+ // cleared store and stays on screen under the new tenant.
137
+ takeUntil(actions$.pipe(filter(clearAll.match))));
138
+ }));
@@ -0,0 +1,79 @@
1
+ import { EMPTY, from, merge, of } from 'rxjs';
2
+ import { catchError, debounceTime, filter, mergeMap, switchMap, } from 'rxjs/operators';
3
+ import { getJEScheduleTransactionKey } from '../../../../../entity/jeSchedules/jeSchedulesTypes';
4
+ import { toTransactionType } from '../../../../../entity/transaction/stateTypes/transactionType';
5
+ import { updateScheduleTransactions } from '../../../../../entity/transaction/transactionReducer';
6
+ import { createZeniAPIStatus, isSuccessResponse, } from '../../../../../responsePayload';
7
+ import { searchTransactionsForNewSchedule, searchTransactionsForNewScheduleFailure, searchTransactionsForNewScheduleSuccess, } from '../../../reducers/jeSchedulesViewReducer';
8
+ import { MIN_NEW_SCHEDULE_SEARCH_LENGTH } from '../../../types/jeSchedulesViewState';
9
+ /**
10
+ * Dropdown-sized result set. The endpoint is paginated — it takes a `page_token` $skip offset and
11
+ * returns `next_page_token` — but nothing here reads or sends those, so this is the whole result
12
+ * set the form ever sees. 20 rather than the backend's default of 10 because a text search for one
13
+ * known transaction was running out of room; the cap server-side is 100 if this needs raising again
14
+ * before infinite scroll is wired up.
15
+ */
16
+ const NEW_SCHEDULE_SEARCH_PAGE_SIZE = 20;
17
+ /** Fallback when the backend sends a null currency for a search result. */
18
+ const DEFAULT_CURRENCY_CODE = 'USD';
19
+ const DEFAULT_CURRENCY_SYMBOL = '$';
20
+ export const searchTransactionsForNewScheduleEpic = (actions$, _state$, zeniAPI) => {
21
+ const searchActions$ = actions$.pipe(filter(searchTransactionsForNewSchedule.match));
22
+ /** No API for empty or 1-char queries; immediate merge so switchMap cancels any in-flight HTTP. */
23
+ const newSearchTooShortOrClear$ = searchActions$.pipe(filter((action) => action.payload.query.trim().length < MIN_NEW_SCHEDULE_SEARCH_LENGTH));
24
+ const newSearchDebounced$ = searchActions$.pipe(filter((action) => action.payload.query.trim().length >= MIN_NEW_SCHEDULE_SEARCH_LENGTH), debounceTime(300));
25
+ return merge(newSearchTooShortOrClear$, newSearchDebounced$).pipe(switchMap((action) => {
26
+ const query = action.payload.query.trim();
27
+ if (query.length < MIN_NEW_SCHEDULE_SEARCH_LENGTH) {
28
+ return EMPTY;
29
+ }
30
+ const queryParam = {
31
+ page_size: NEW_SCHEDULE_SEARCH_PAGE_SIZE,
32
+ search_text: query,
33
+ je_schedule_type: action.payload.scheduleType,
34
+ };
35
+ return zeniAPI
36
+ .getJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/schedules/base_transaction_search?query=${encodeURIComponent(JSON.stringify(queryParam))}`)
37
+ .pipe(mergeMap((response) => {
38
+ if (isSuccessResponse(response) && response.data != null) {
39
+ const { transactions } = response.data;
40
+ const transactionsPerCurrency = {};
41
+ transactions.forEach((transaction) => {
42
+ const { currency_code, currency_symbol } = transaction;
43
+ const currencyCode = currency_code ?? DEFAULT_CURRENCY_CODE;
44
+ const existing = transactionsPerCurrency[currencyCode];
45
+ transactionsPerCurrency[currencyCode] =
46
+ existing != null
47
+ ? {
48
+ currencySymbol: existing.currencySymbol,
49
+ transactions: [...existing.transactions, transaction],
50
+ }
51
+ : {
52
+ currencySymbol: currency_code == null
53
+ ? DEFAULT_CURRENCY_SYMBOL
54
+ : currency_symbol,
55
+ transactions: [transaction],
56
+ };
57
+ });
58
+ const actionsOut = Object.keys(transactionsPerCurrency).map((currencyCode) => {
59
+ const perCurrency = transactionsPerCurrency[currencyCode];
60
+ return updateScheduleTransactions(perCurrency.transactions, currencyCode, perCurrency.currencySymbol, 'merge');
61
+ });
62
+ actionsOut.push(searchTransactionsForNewScheduleSuccess({
63
+ searchResults: transactions.map((transaction) => getJEScheduleTransactionKey({
64
+ id: transaction.transaction_id,
65
+ type: toTransactionType(transaction.transaction_type),
66
+ lineId: transaction.line_id,
67
+ })),
68
+ }));
69
+ return from(actionsOut);
70
+ }
71
+ return of(searchTransactionsForNewScheduleFailure({
72
+ status: response.status,
73
+ }));
74
+ }), catchError((error) => of(searchTransactionsForNewScheduleFailure({
75
+ status: createZeniAPIStatus('Unexpected Error', 'Search transactions for new schedule errored: ' +
76
+ JSON.stringify(error)),
77
+ }))));
78
+ }));
79
+ };
@@ -0,0 +1,180 @@
1
+ import { from, merge } from 'rxjs';
2
+ import { catchError, filter, mergeMap, takeUntil } from 'rxjs/operators';
3
+ import { DEFAULT_DATE_FORMAT, convertToPeriod, toAbsoluteDay, } from '../../../../commonStateTypes/timePeriod';
4
+ import { generateJEOneTimeAccrualKey } from '../../../../entity/jeSchedules/jeScheduleHelper';
5
+ import { updateJEOneTimeAccruals } from '../../../../entity/jeSchedules/jeSchedulesReducer';
6
+ import { getJEOneTimeAccrualByKey } from '../../../../entity/jeSchedules/jeSchedulesSelector';
7
+ import { openSnackbar } from '../../../../entity/snackbar/snackbarReducer';
8
+ import { getCurrentTenant } from '../../../../entity/tenant/tenantSelector';
9
+ import { clearAll } from '../../../../rootActions';
10
+ import { createZeniAPIStatus, isSuccessResponse, } from '../../../../responsePayload';
11
+ import { fetchJeSchedules, ignoreOneTimeAccrual, oneTimeAccrualActionFailure, oneTimeAccrualActionSuccess, promoteOneTimeAccrual, revertOneTimeAccrual, } from '../../reducers/jeSchedulesViewReducer';
12
+ /**
13
+ * The page the accrual came from, so a promoted or ignored row lands in the right bucket. Guarded
14
+ * because convertToPeriod destructures: an unset period would throw and take the epic subscription
15
+ * down for the session, and a missed refresh is the cheaper failure.
16
+ *
17
+ * Read state$.value at response time rather than the snapshot taken when the action was dispatched:
18
+ * if the user changes month while the request is in flight, the snapshot refreshes the month they
19
+ * have left and the month they are now looking at stays stale.
20
+ */
21
+ function refreshCurrentPage(state) {
22
+ const selectedMonthYear = state.expenseAutomationViewState.selectedPeriodByTenantId[getCurrentTenant(state).tenantId];
23
+ if (selectedMonthYear == null) {
24
+ return [];
25
+ }
26
+ const period = convertToPeriod(selectedMonthYear);
27
+ const start = toAbsoluteDay(period.start);
28
+ const end = toAbsoluteDay(period.end);
29
+ if (start == null || end == null) {
30
+ return [];
31
+ }
32
+ return [fetchJeSchedules({ start, end }, true)];
33
+ }
34
+ function failureActions(
35
+ // Per action, not fixed: every failure used to read "Save schedule failed", so skipping or
36
+ // reverting an accrual reported an operation the user had not performed.
37
+ messageSection, accrualId, message, status) {
38
+ return [
39
+ oneTimeAccrualActionFailure({
40
+ accrualId,
41
+ status: status ?? createZeniAPIStatus('Unexpected Error', message),
42
+ }),
43
+ openSnackbar({
44
+ messageSection,
45
+ messageText: 'failed',
46
+ type: 'error',
47
+ variables: [{ variableName: '_api-error_', variableValue: message }],
48
+ }),
49
+ ];
50
+ }
51
+ export const promoteOneTimeAccrualEpic = (actions$, state$, zeniAPI) => actions$.pipe(filter(promoteOneTimeAccrual.match), mergeMap((action) => {
52
+ const state = state$.value;
53
+ const { accrualId, amount, edits } = action.payload;
54
+ const accrual = getJEOneTimeAccrualByKey(generateJEOneTimeAccrualKey(accrualId), state.jeSchedulesState);
55
+ // An edited value wins; anything untouched falls back to the stored draft, which is what the
56
+ // list's inline Post sends.
57
+ const debitAccountId = edits?.jeDebitAccountId ?? accrual?.jeDebitAccountId;
58
+ const creditAccountId = edits?.jeCreditAccountId ?? accrual?.jeCreditAccountId;
59
+ if (debitAccountId == null || creditAccountId == null) {
60
+ // Promote posts a journal entry, so it cannot proceed without both sides of it.
61
+ return from(failureActions('save_schedule', accrualId, 'This accrual is missing an expense or liability account.'));
62
+ }
63
+ // vendor_id, vendor_name and service_month are deliberately absent: promote takes them from
64
+ // the stored draft and ignores them in the body, so sending them would imply a reassignment
65
+ // that never happens.
66
+ // Untouched falls back to the stored policy, so posting without editing cannot silently
67
+ // flip a scheduled reversal to on-bill-match.
68
+ const reverseNextMonth = edits?.reverseNextMonth ??
69
+ accrual?.reversalPolicy === 'scheduled_date';
70
+ const expectedReversalDate = edits?.expectedReversalDate ?? accrual?.expectedReversalDate;
71
+ const debitClassId = edits?.jeDebitAccountingClassId ?? accrual?.jeDebitAccountingClassId;
72
+ const debitClassName = edits?.jeDebitAccountingClassName ??
73
+ accrual?.jeDebitAccountingClassName;
74
+ const payload = {
75
+ amount,
76
+ memo: edits?.memo ?? accrual?.memo ?? '',
77
+ je_debit_account_id: debitAccountId,
78
+ je_credit_account_id: creditAccountId,
79
+ ...(debitClassId != null ? { je_debit_accounting_class_id: debitClassId } : {}),
80
+ ...(debitClassName != null
81
+ ? { je_debit_accounting_class_name: debitClassName }
82
+ : {}),
83
+ // Mirrors the create payload: reverse_next_month alone decides the policy, and the date is
84
+ // only meaningful when it is true -- agent-je derives the reversal from the bill otherwise.
85
+ reverse_next_month: reverseNextMonth,
86
+ ...(reverseNextMonth && expectedReversalDate != null
87
+ ? {
88
+ expected_reversal_date: expectedReversalDate.format(DEFAULT_DATE_FORMAT),
89
+ }
90
+ : {}),
91
+ };
92
+ return zeniAPI
93
+ .putAndGetJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/accruals/${accrualId}`, { ...payload })
94
+ .pipe(mergeMap((response) => {
95
+ if (isSuccessResponse(response) && response.data != null) {
96
+ return from([
97
+ updateJEOneTimeAccruals([response.data.accrual]),
98
+ oneTimeAccrualActionSuccess({ accrualId }),
99
+ openSnackbar({
100
+ messageSection: 'save_schedule',
101
+ messageText: 'success',
102
+ type: 'success',
103
+ variables: [
104
+ {
105
+ variableName: '_vendor_name_',
106
+ variableValue: accrual?.vendorName ?? '',
107
+ },
108
+ ],
109
+ }),
110
+ ...refreshCurrentPage(state$.value),
111
+ ]);
112
+ }
113
+ return from(failureActions('save_schedule', accrualId, response.status.message, response.status));
114
+ }), catchError((error) => from(failureActions('save_schedule', accrualId, `Promote accrual REST API call errored out ${JSON.stringify(error)}`))),
115
+ // A tenant switch clears the store while this request is still in flight.
116
+ // Without this the old tenant's response is written back into the freshly
117
+ // cleared store and stays on screen under the new tenant.
118
+ takeUntil(actions$.pipe(filter(clearAll.match))));
119
+ }));
120
+ export const ignoreOneTimeAccrualEpic = (actions$, state$, zeniAPI) => actions$.pipe(filter(ignoreOneTimeAccrual.match), mergeMap((action) => {
121
+ const { accrualId, reason, note } = action.payload;
122
+ // `scope` is deliberately never sent: the API returns 400 on it, which is why the design's
123
+ // "Apply to" selector cannot be built yet.
124
+ const payload = {
125
+ reason,
126
+ ...(note != null && note !== '' ? { note } : {}),
127
+ };
128
+ return zeniAPI
129
+ .putAndGetJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/accruals/${accrualId}/ignore`, { ...payload })
130
+ .pipe(mergeMap((response) => {
131
+ if (isSuccessResponse(response) && response.data != null) {
132
+ return from([
133
+ updateJEOneTimeAccruals([response.data.accrual]),
134
+ oneTimeAccrualActionSuccess({ accrualId }),
135
+ openSnackbar({
136
+ messageSection: 'ignore_accrual',
137
+ messageText: 'success',
138
+ type: 'success',
139
+ }),
140
+ ...refreshCurrentPage(state$.value),
141
+ ]);
142
+ }
143
+ return from(failureActions('ignore_accrual', accrualId, response.status.message, response.status));
144
+ }), catchError((error) => from(failureActions('ignore_accrual', accrualId, `Ignore accrual REST API call errored out ${JSON.stringify(error)}`))),
145
+ // A tenant switch clears the store while this request is still in flight.
146
+ // Without this the old tenant's response is written back into the freshly
147
+ // cleared store and stays on screen under the new tenant.
148
+ takeUntil(actions$.pipe(filter(clearAll.match))));
149
+ }));
150
+ export const revertOneTimeAccrualEpic = (actions$, state$, zeniAPI) => actions$.pipe(filter(revertOneTimeAccrual.match), mergeMap((action) => {
151
+ const { accrualId, reason, note } = action.payload;
152
+ // Deletes the accrual's journal entry in QBO and soft-deletes the row. `scope` is never sent:
153
+ // the endpoint 400s on it, exactly as ignore does.
154
+ const payload = {
155
+ reason,
156
+ ...(note != null && note !== '' ? { note } : {}),
157
+ };
158
+ return zeniAPI
159
+ .putAndGetJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/accruals/${accrualId}/revert`, { ...payload })
160
+ .pipe(mergeMap((response) => {
161
+ if (isSuccessResponse(response) && response.data != null) {
162
+ return from([
163
+ updateJEOneTimeAccruals([response.data.accrual]),
164
+ oneTimeAccrualActionSuccess({ accrualId }),
165
+ openSnackbar({
166
+ messageSection: 'revert_accrual',
167
+ messageText: 'success',
168
+ type: 'success',
169
+ }),
170
+ ...refreshCurrentPage(state$.value),
171
+ ]);
172
+ }
173
+ return from(failureActions('revert_accrual', accrualId, response.status.message, response.status));
174
+ }), catchError((error) => from(failureActions('revert_accrual', accrualId, `Revert accrual REST API call errored out ${JSON.stringify(error)}`))),
175
+ // A tenant switch clears the store while this request is still in flight.
176
+ // Without this the old tenant's response is written back into the freshly
177
+ // cleared store and stays on screen under the new tenant.
178
+ takeUntil(actions$.pipe(filter(clearAll.match))));
179
+ }));
180
+ export const oneTimeAccrualActionsEpic = (actions$, state$, zeniAPI) => merge(promoteOneTimeAccrualEpic(actions$, state$, zeniAPI), ignoreOneTimeAccrualEpic(actions$, state$, zeniAPI), revertOneTimeAccrualEpic(actions$, state$, zeniAPI));
@@ -0,0 +1,111 @@
1
+ import { from } from 'rxjs';
2
+ import { catchError, filter, mergeMap, takeUntil } from 'rxjs/operators';
3
+ import { openSnackbar } from '../../../../entity/snackbar/snackbarReducer';
4
+ import { getCurrentTenant } from '../../../../entity/tenant/tenantSelector';
5
+ import { clearAll } from '../../../../rootActions';
6
+ import { createZeniAPIStatus, isSuccessResponse, } from '../../../../responsePayload';
7
+ import { fetchMonthEndCloseChecks } from '../../../monthEndCloseChecksView/monthEndCloseChecksViewReducer';
8
+ import { removeJeAccruedScheduleKey, removeJeScheduleTransactionKey, revertJeSchedule, revertJeScheduleFailure, revertJeScheduleSuccess, } from '../../reducers/jeSchedulesViewReducer';
9
+ /**
10
+ * Undo a posted prepaid / fixed-asset / accrued schedule: deletes its posted QBO journal entry, then
11
+ * soft-deletes the scheduled entries and the schedule itself.
12
+ *
13
+ * Two or more posted journal entries answer 409 and leave the schedule intact, so the failure is
14
+ * surfaced rather than swallowed. Accrued has one extra rejection of its own — the endpoint refuses
15
+ * once a bill has been linked, because the reversal is already on the books — and that arrives the
16
+ * same way, as an error on the row.
17
+ *
18
+ * A one-time accrual is not this action: it is a Mongo row behind the accruals gateway, and goes
19
+ * through revertOneTimeAccrual instead. So `accrued_expenses` here always means an accrued
20
+ * *schedule*, which is what makes it a safe discriminator for the removal below.
21
+ */
22
+ export const revertJeScheduleEpic = (actions$, state$, zeniAPI) => actions$.pipe(filter(revertJeSchedule.match), mergeMap((action) => {
23
+ const state = state$.value;
24
+ const { expenseAutomationViewState: { selectedPeriodByTenantId }, } = state;
25
+ const { jeScheduleId, jeScheduleTransactionKey, reason, note, scheduleType } = action.payload;
26
+ const currentTenant = getCurrentTenant(state);
27
+ const selectedPeriod = selectedPeriodByTenantId[currentTenant.tenantId];
28
+ // Feedback nested under je_schedules[0], the same shape ignore takes -- the two endpoints were
29
+ // made symmetric server-side. A flat {reason, note} body, which this epic used to send while
30
+ // revert validated the whole body as feedback, now answers 400 "Request body must contain at
31
+ // least one of je_schedules".
32
+ //
33
+ // Only the id and the feedback: the rest of the fat blob is read from Datastore, not the
34
+ // request. The id is optional server-side but sent anyway, because it is validated against the
35
+ // URL and so turns a mismatch into a 400 rather than a revert of the wrong schedule.
36
+ // `action` is stamped server-side.
37
+ const payload = {
38
+ je_schedules: [
39
+ {
40
+ je_schedule_id: jeScheduleId,
41
+ feedback: {
42
+ reason,
43
+ ...(note != null && note !== '' ? { note } : {}),
44
+ },
45
+ },
46
+ ],
47
+ };
48
+ return zeniAPI
49
+ .putAndGetJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/schedules/${jeScheduleId}/revert`, payload)
50
+ .pipe(mergeMap((response) => {
51
+ if (isSuccessResponse(response) && response.data != null) {
52
+ // Deliberately not written to the entity store. A reverted schedule is soft-deleted,
53
+ // so the endpoint returns its flat entity json -- `vendor_id` as a bare field, no
54
+ // nested `vendor` or `base_transaction` -- rather than the list DTO those mappers
55
+ // expect. Feeding it to updateJESchedules threw inside doUpdateVendors on
56
+ // `payload.vendor.vendor_id`, and because that happens mid-dispatch it killed the
57
+ // rest of this array: the row kept spinning and no snackbar appeared. The row is
58
+ // removed from the list below regardless, so there is nothing worth storing.
59
+ return from([
60
+ revertJeScheduleSuccess({ jeScheduleTransactionKey }),
61
+ // Accrued keys live in their own per-tab map, so the transaction-key removal cannot
62
+ // reach them -- a reverted accrued schedule would sit on the list until the next
63
+ // fetch. The key carried here is a JEScheduleKey for that type.
64
+ scheduleType === 'accrued_expenses'
65
+ ? removeJeAccruedScheduleKey(jeScheduleTransactionKey)
66
+ : removeJeScheduleTransactionKey(jeScheduleTransactionKey, selectedPeriod),
67
+ fetchMonthEndCloseChecks({
68
+ tenantId: currentTenant.tenantId,
69
+ period: selectedPeriod,
70
+ refreshViewInBackground: true,
71
+ }),
72
+ openSnackbar({
73
+ messageSection: 'revert_schedule',
74
+ messageText: 'success',
75
+ type: 'success',
76
+ }),
77
+ ]);
78
+ }
79
+ return from([
80
+ revertJeScheduleFailure({
81
+ jeScheduleTransactionKey,
82
+ status: response.status,
83
+ }),
84
+ openSnackbar({
85
+ messageSection: 'revert_schedule',
86
+ messageText: 'failed',
87
+ type: 'error',
88
+ variables: [
89
+ {
90
+ variableName: '_api-error_',
91
+ variableValue: response.status.message,
92
+ },
93
+ ],
94
+ }),
95
+ ]);
96
+ }), catchError((error) => from([
97
+ revertJeScheduleFailure({
98
+ jeScheduleTransactionKey,
99
+ status: createZeniAPIStatus('Unexpected Error', `Revert schedule REST API call errored out ${JSON.stringify(error)}`),
100
+ }),
101
+ openSnackbar({
102
+ messageSection: 'revert_schedule',
103
+ messageText: 'failed',
104
+ type: 'error',
105
+ }),
106
+ ])),
107
+ // A tenant switch clears the store while this request is still in flight.
108
+ // Without this the old tenant's response is written back into the freshly
109
+ // cleared store and stays on screen under the new tenant.
110
+ takeUntil(actions$.pipe(filter(clearAll.match))));
111
+ }));
@@ -0,0 +1,28 @@
1
+ import { EMPTY, of } from 'rxjs';
2
+ import { filter, mergeMap } from 'rxjs/operators';
3
+ import { convertToPeriod, toAbsoluteDay, } from '../../../../commonStateTypes/timePeriod';
4
+ import { getCurrentTenant } from '../../../../entity/tenant/tenantSelector';
5
+ import { fetchJeSchedulesPage, updateJESchedulesUIState, } from '../../reducers/jeSchedulesViewReducer';
6
+ export const switchJESchedulesTabEpic = (actions$, state$) => actions$.pipe(filter(updateJESchedulesUIState.match), filter((action) => action.payload.selectedPageTab != null), mergeMap(() => {
7
+ const state = state$.value;
8
+ const { fetchState, refreshStatus } = state.expenseAutomationJESchedulesViewState;
9
+ if (fetchState === 'In-Progress' ||
10
+ refreshStatus.fetchState === 'In-Progress') {
11
+ return EMPTY;
12
+ }
13
+ const currentTenant = getCurrentTenant(state);
14
+ const selectedPeriod = state.expenseAutomationViewState.selectedPeriodByTenantId[currentTenant.tenantId];
15
+ // convertToPeriod destructures, so an unset period throws and takes this epic's subscription
16
+ // down for the rest of the session -- every later tab switch would then stop refreshing. A
17
+ // skipped refresh is the cheaper failure, as in refreshCurrentPage.
18
+ if (selectedPeriod == null) {
19
+ return EMPTY;
20
+ }
21
+ const period = convertToPeriod(selectedPeriod);
22
+ const timePeriodStart = toAbsoluteDay(period.start);
23
+ const timePeriodEnd = toAbsoluteDay(period.end);
24
+ if (timePeriodStart == null || timePeriodEnd == null) {
25
+ return EMPTY;
26
+ }
27
+ return of(fetchJeSchedulesPage({ start: timePeriodStart, end: timePeriodEnd }, true));
28
+ }));