@zeniai/client-epic-state 5.2.10 → 5.2.11-betaAM1

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 (155) 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 +86 -1
  4. package/lib/entity/jeSchedules/jeSchedulesPayload.js +172 -0
  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 +101 -1
  10. package/lib/entity/jeSchedules/jeSchedulesTypes.d.ts +24 -1
  11. package/lib/entity/jeSchedules/jeSchedulesTypes.js +88 -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 +14 -1
  18. package/lib/epic.js +26 -0
  19. package/lib/esm/entity/jeSchedules/jeScheduleHelper.js +6 -0
  20. package/lib/esm/entity/jeSchedules/jeSchedulesPayload.js +172 -1
  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 +78 -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 +26 -0
  27. package/lib/esm/index.js +19 -9
  28. package/lib/esm/reducer.js +3 -0
  29. package/lib/esm/view/companyMonthEndReportView/companyMonthEndReportViewReducer.js +6 -2
  30. package/lib/esm/view/companyMonthEndReportView/companyMonthEndReportViewState.js +4 -0
  31. package/lib/esm/view/companyMonthEndReportView/epics/saveCompanyMonthEndReportEpic.js +10 -6
  32. package/lib/esm/view/companyMonthEndReportView/epics/sendCompanyMonthEndReportEpic.js +9 -5
  33. package/lib/esm/view/companyMonthEndReportView/monthEndTemplateData.js +32 -0
  34. package/lib/esm/view/expenseAutomationView/epics/actualMatching/fetchActualMatchingEpic.js +46 -0
  35. package/lib/esm/view/expenseAutomationView/epics/actualMatching/fetchActualMatchingPageEpic.js +7 -0
  36. package/lib/esm/view/expenseAutomationView/epics/actualMatching/matchAndReverseAccrualsEpic.js +50 -0
  37. package/lib/esm/view/expenseAutomationView/epics/actualMatching/searchMatchAccrualsEpic.js +44 -0
  38. package/lib/esm/view/expenseAutomationView/epics/actualMatching/searchMatchTransactionsEpic.js +44 -0
  39. package/lib/esm/view/expenseAutomationView/epics/common/fetchAllExpenseAutomationTabsEpic.js +30 -10
  40. package/lib/esm/view/expenseAutomationView/epics/common/refreshExpenseAutomationCurrentTabEpic.js +9 -1
  41. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/fetchJeSchedulePageEpic.js +9 -1
  42. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/fetchJeSchedulesEpic.js +41 -5
  43. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/fetchOneTimeAccrualEpic.js +45 -0
  44. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/ignoreRecommendedJeScheduleEpic.js +14 -2
  45. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/newSchedule/createOneTimeAccrualEpic.js +104 -0
  46. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/newSchedule/initializeNewScheduleEpic.js +25 -0
  47. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/newSchedule/saveNewScheduleEpic.js +136 -0
  48. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/newSchedule/searchTransactionsForNewScheduleEpic.js +79 -0
  49. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/oneTimeAccrualActionsEpic.js +157 -0
  50. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/revertJeScheduleEpic.js +111 -0
  51. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/switchJESchedulesTabEpic.js +33 -0
  52. package/lib/esm/view/expenseAutomationView/expenseAutomationViewSelector.js +22 -7
  53. package/lib/esm/view/expenseAutomationView/helpers/newScheduleLocalDataHelper.js +140 -0
  54. package/lib/esm/view/expenseAutomationView/payload/actualMatchingPayload.js +35 -0
  55. package/lib/esm/view/expenseAutomationView/payload/jeSchedulesPayload.js +55 -0
  56. package/lib/esm/view/expenseAutomationView/reducers/actualMatchingViewReducer.js +260 -0
  57. package/lib/esm/view/expenseAutomationView/reducers/jeSchedulesViewReducer.js +314 -29
  58. package/lib/esm/view/expenseAutomationView/selectorTypes/actualMatchingViewSelectorTypes.js +1 -0
  59. package/lib/esm/view/expenseAutomationView/selectorTypes/jeNewScheduleViewSelectorTypes.js +1 -0
  60. package/lib/esm/view/expenseAutomationView/selectors/actualMatchingViewSelector.js +162 -0
  61. package/lib/esm/view/expenseAutomationView/selectors/jeAccountSettingsViewSelector.js +1 -0
  62. package/lib/esm/view/expenseAutomationView/selectors/jeNewScheduleViewSelector.js +106 -0
  63. package/lib/esm/view/expenseAutomationView/selectors/jeSchedulesViewSelector.js +297 -22
  64. package/lib/esm/view/expenseAutomationView/types/actualMatchingViewState.js +22 -0
  65. package/lib/esm/view/expenseAutomationView/types/jeSchedulesViewState.js +8 -5
  66. package/lib/esm/view/scheduleView/scheduleListView/epics/fetchAccruedScheduleListEpic.js +1 -1
  67. package/lib/esm/view/scheduleView/scheduleListView/epics/fetchDownloadSchedulesEpic.js +7 -2
  68. package/lib/esm/view/scheduleView/scheduleListView/scheduleListReducer.js +5 -3
  69. package/lib/index.d.ts +25 -14
  70. package/lib/index.js +119 -51
  71. package/lib/reducer.d.ts +1 -0
  72. package/lib/reducer.js +3 -0
  73. package/lib/rootStateTypes.d.ts +2 -0
  74. package/lib/view/companyMonthEndReportView/companyMonthEndReportViewPayload.d.ts +8 -0
  75. package/lib/view/companyMonthEndReportView/companyMonthEndReportViewReducer.d.ts +6 -2
  76. package/lib/view/companyMonthEndReportView/companyMonthEndReportViewReducer.js +6 -2
  77. package/lib/view/companyMonthEndReportView/companyMonthEndReportViewState.d.ts +2 -0
  78. package/lib/view/companyMonthEndReportView/companyMonthEndReportViewState.js +4 -0
  79. package/lib/view/companyMonthEndReportView/epics/saveCompanyMonthEndReportEpic.js +10 -6
  80. package/lib/view/companyMonthEndReportView/epics/sendCompanyMonthEndReportEpic.js +9 -5
  81. package/lib/view/companyMonthEndReportView/monthEndTemplateData.d.ts +16 -0
  82. package/lib/view/companyMonthEndReportView/monthEndTemplateData.js +36 -0
  83. package/lib/view/expenseAutomationView/epics/actualMatching/fetchActualMatchingEpic.d.ts +9 -0
  84. package/lib/view/expenseAutomationView/epics/actualMatching/fetchActualMatchingEpic.js +50 -0
  85. package/lib/view/expenseAutomationView/epics/actualMatching/fetchActualMatchingPageEpic.d.ts +5 -0
  86. package/lib/view/expenseAutomationView/epics/actualMatching/fetchActualMatchingPageEpic.js +11 -0
  87. package/lib/view/expenseAutomationView/epics/actualMatching/matchAndReverseAccrualsEpic.d.ts +8 -0
  88. package/lib/view/expenseAutomationView/epics/actualMatching/matchAndReverseAccrualsEpic.js +54 -0
  89. package/lib/view/expenseAutomationView/epics/actualMatching/searchMatchAccrualsEpic.d.ts +8 -0
  90. package/lib/view/expenseAutomationView/epics/actualMatching/searchMatchAccrualsEpic.js +48 -0
  91. package/lib/view/expenseAutomationView/epics/actualMatching/searchMatchTransactionsEpic.d.ts +8 -0
  92. package/lib/view/expenseAutomationView/epics/actualMatching/searchMatchTransactionsEpic.js +48 -0
  93. package/lib/view/expenseAutomationView/epics/common/fetchAllExpenseAutomationTabsEpic.d.ts +2 -1
  94. package/lib/view/expenseAutomationView/epics/common/fetchAllExpenseAutomationTabsEpic.js +30 -10
  95. package/lib/view/expenseAutomationView/epics/common/refreshExpenseAutomationCurrentTabEpic.d.ts +2 -1
  96. package/lib/view/expenseAutomationView/epics/common/refreshExpenseAutomationCurrentTabEpic.js +9 -1
  97. package/lib/view/expenseAutomationView/epics/jeSchedule/fetchJeSchedulePageEpic.js +9 -1
  98. package/lib/view/expenseAutomationView/epics/jeSchedule/fetchJeSchedulesEpic.d.ts +3 -2
  99. package/lib/view/expenseAutomationView/epics/jeSchedule/fetchJeSchedulesEpic.js +39 -3
  100. package/lib/view/expenseAutomationView/epics/jeSchedule/fetchOneTimeAccrualEpic.d.ts +21 -0
  101. package/lib/view/expenseAutomationView/epics/jeSchedule/fetchOneTimeAccrualEpic.js +49 -0
  102. package/lib/view/expenseAutomationView/epics/jeSchedule/ignoreRecommendedJeScheduleEpic.js +14 -2
  103. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/createOneTimeAccrualEpic.d.ts +9 -0
  104. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/createOneTimeAccrualEpic.js +108 -0
  105. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/initializeNewScheduleEpic.d.ts +8 -0
  106. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/initializeNewScheduleEpic.js +29 -0
  107. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/saveNewScheduleEpic.d.ts +9 -0
  108. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/saveNewScheduleEpic.js +140 -0
  109. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/searchTransactionsForNewScheduleEpic.d.ts +8 -0
  110. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/searchTransactionsForNewScheduleEpic.js +83 -0
  111. package/lib/view/expenseAutomationView/epics/jeSchedule/oneTimeAccrualActionsEpic.d.ts +13 -0
  112. package/lib/view/expenseAutomationView/epics/jeSchedule/oneTimeAccrualActionsEpic.js +164 -0
  113. package/lib/view/expenseAutomationView/epics/jeSchedule/revertJeScheduleEpic.d.ts +65 -0
  114. package/lib/view/expenseAutomationView/epics/jeSchedule/revertJeScheduleEpic.js +115 -0
  115. package/lib/view/expenseAutomationView/epics/jeSchedule/switchJESchedulesTabEpic.d.ts +7 -0
  116. package/lib/view/expenseAutomationView/epics/jeSchedule/switchJESchedulesTabEpic.js +37 -0
  117. package/lib/view/expenseAutomationView/expenseAutomationViewSelector.js +22 -7
  118. package/lib/view/expenseAutomationView/helpers/newScheduleLocalDataHelper.d.ts +36 -0
  119. package/lib/view/expenseAutomationView/helpers/newScheduleLocalDataHelper.js +145 -0
  120. package/lib/view/expenseAutomationView/helpers/transactionCategorizationLocalDataHelper.d.ts +1 -1
  121. package/lib/view/expenseAutomationView/payload/actualMatchingPayload.d.ts +66 -0
  122. package/lib/view/expenseAutomationView/payload/actualMatchingPayload.js +40 -0
  123. package/lib/view/expenseAutomationView/payload/jeSchedulesPayload.d.ts +72 -3
  124. package/lib/view/expenseAutomationView/payload/jeSchedulesPayload.js +58 -1
  125. package/lib/view/expenseAutomationView/reducers/actualMatchingViewReducer.d.ts +53 -0
  126. package/lib/view/expenseAutomationView/reducers/actualMatchingViewReducer.js +264 -0
  127. package/lib/view/expenseAutomationView/reducers/jeSchedulesViewReducer.d.ts +91 -12
  128. package/lib/view/expenseAutomationView/reducers/jeSchedulesViewReducer.js +316 -29
  129. package/lib/view/expenseAutomationView/reducers/missingReceiptsViewReducer.d.ts +1 -1
  130. package/lib/view/expenseAutomationView/reducers/transactionsViewReducer.d.ts +2 -2
  131. package/lib/view/expenseAutomationView/selectorTypes/actualMatchingViewSelectorTypes.d.ts +58 -0
  132. package/lib/view/expenseAutomationView/selectorTypes/actualMatchingViewSelectorTypes.js +2 -0
  133. package/lib/view/expenseAutomationView/selectorTypes/expenseAutomationViewSelectorTypes.d.ts +2 -0
  134. package/lib/view/expenseAutomationView/selectorTypes/jeAccountSettingsViewSelectorTypes.d.ts +1 -0
  135. package/lib/view/expenseAutomationView/selectorTypes/jeNewScheduleViewSelectorTypes.d.ts +42 -0
  136. package/lib/view/expenseAutomationView/selectorTypes/jeNewScheduleViewSelectorTypes.js +2 -0
  137. package/lib/view/expenseAutomationView/selectorTypes/jeSchedulesSelectorTypes.d.ts +36 -7
  138. package/lib/view/expenseAutomationView/selectors/actualMatchingViewSelector.d.ts +9 -0
  139. package/lib/view/expenseAutomationView/selectors/actualMatchingViewSelector.js +172 -0
  140. package/lib/view/expenseAutomationView/selectors/jeAccountSettingsViewSelector.js +1 -0
  141. package/lib/view/expenseAutomationView/selectors/jeNewScheduleViewSelector.d.ts +21 -0
  142. package/lib/view/expenseAutomationView/selectors/jeNewScheduleViewSelector.js +112 -0
  143. package/lib/view/expenseAutomationView/selectors/jeSchedulesViewSelector.d.ts +34 -0
  144. package/lib/view/expenseAutomationView/selectors/jeSchedulesViewSelector.js +305 -21
  145. package/lib/view/expenseAutomationView/types/actualMatchingViewState.d.ts +76 -0
  146. package/lib/view/expenseAutomationView/types/actualMatchingViewState.js +27 -0
  147. package/lib/view/expenseAutomationView/types/completedSubTab.d.ts +1 -1
  148. package/lib/view/expenseAutomationView/types/jeSchedulesViewState.d.ts +83 -8
  149. package/lib/view/expenseAutomationView/types/jeSchedulesViewState.js +11 -7
  150. package/lib/view/expenseAutomationView/types/reconciliationViewState.d.ts +1 -1
  151. package/lib/view/scheduleView/scheduleListView/epics/fetchAccruedScheduleListEpic.js +1 -1
  152. package/lib/view/scheduleView/scheduleListView/epics/fetchDownloadSchedulesEpic.js +7 -2
  153. package/lib/view/scheduleView/scheduleListView/scheduleListReducer.d.ts +4 -2
  154. package/lib/view/scheduleView/scheduleListView/scheduleListReducer.js +5 -3
  155. package/package.json +1 -1
@@ -0,0 +1,157 @@
1
+ import { from, merge } from 'rxjs';
2
+ import { catchError, filter, mergeMap, takeUntil } from 'rxjs/operators';
3
+ import { 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 } = action.payload;
54
+ const accrual = getJEOneTimeAccrualByKey(generateJEOneTimeAccrualKey(accrualId), state.jeSchedulesState);
55
+ if (accrual?.jeDebitAccountId == null ||
56
+ accrual.jeCreditAccountId == null) {
57
+ // Promote posts a journal entry, so it cannot proceed without both sides of it.
58
+ return from(failureActions('save_schedule', accrualId, 'This accrual is missing an expense or liability account.'));
59
+ }
60
+ // vendor_id, vendor_name and service_month are deliberately absent: promote takes them from
61
+ // the stored draft and ignores them in the body, so sending them would imply a reassignment
62
+ // that never happens.
63
+ const payload = {
64
+ amount,
65
+ memo: accrual.memo,
66
+ je_debit_account_id: accrual.jeDebitAccountId,
67
+ je_credit_account_id: accrual.jeCreditAccountId,
68
+ };
69
+ return zeniAPI
70
+ .putAndGetJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/accruals/${accrualId}`, { ...payload })
71
+ .pipe(mergeMap((response) => {
72
+ if (isSuccessResponse(response) && response.data != null) {
73
+ return from([
74
+ updateJEOneTimeAccruals([response.data.accrual]),
75
+ oneTimeAccrualActionSuccess({ accrualId }),
76
+ openSnackbar({
77
+ messageSection: 'save_schedule',
78
+ messageText: 'success',
79
+ type: 'success',
80
+ variables: [
81
+ {
82
+ variableName: '_vendor_name_',
83
+ variableValue: accrual.vendorName,
84
+ },
85
+ ],
86
+ }),
87
+ ...refreshCurrentPage(state$.value),
88
+ ]);
89
+ }
90
+ return from(failureActions('save_schedule', accrualId, response.status.message, response.status));
91
+ }), catchError((error) => from(failureActions('save_schedule', accrualId, `Promote accrual REST API call errored out ${JSON.stringify(error)}`))),
92
+ // A tenant switch clears the store while this request is still in flight.
93
+ // Without this the old tenant's response is written back into the freshly
94
+ // cleared store and stays on screen under the new tenant.
95
+ takeUntil(actions$.pipe(filter(clearAll.match))));
96
+ }));
97
+ export const ignoreOneTimeAccrualEpic = (actions$, state$, zeniAPI) => actions$.pipe(filter(ignoreOneTimeAccrual.match), mergeMap((action) => {
98
+ const { accrualId, reason, note } = action.payload;
99
+ // `scope` is deliberately never sent: the API returns 400 on it, which is why the design's
100
+ // "Apply to" selector cannot be built yet.
101
+ const payload = {
102
+ reason,
103
+ ...(note != null && note !== '' ? { note } : {}),
104
+ };
105
+ return zeniAPI
106
+ .putAndGetJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/accruals/${accrualId}/ignore`, { ...payload })
107
+ .pipe(mergeMap((response) => {
108
+ if (isSuccessResponse(response) && response.data != null) {
109
+ return from([
110
+ updateJEOneTimeAccruals([response.data.accrual]),
111
+ oneTimeAccrualActionSuccess({ accrualId }),
112
+ openSnackbar({
113
+ messageSection: 'ignore_accrual',
114
+ messageText: 'success',
115
+ type: 'success',
116
+ }),
117
+ ...refreshCurrentPage(state$.value),
118
+ ]);
119
+ }
120
+ return from(failureActions('ignore_accrual', accrualId, response.status.message, response.status));
121
+ }), catchError((error) => from(failureActions('ignore_accrual', accrualId, `Ignore accrual REST API call errored out ${JSON.stringify(error)}`))),
122
+ // A tenant switch clears the store while this request is still in flight.
123
+ // Without this the old tenant's response is written back into the freshly
124
+ // cleared store and stays on screen under the new tenant.
125
+ takeUntil(actions$.pipe(filter(clearAll.match))));
126
+ }));
127
+ export const revertOneTimeAccrualEpic = (actions$, state$, zeniAPI) => actions$.pipe(filter(revertOneTimeAccrual.match), mergeMap((action) => {
128
+ const { accrualId, reason, note } = action.payload;
129
+ // Deletes the accrual's journal entry in QBO and soft-deletes the row. `scope` is never sent:
130
+ // the endpoint 400s on it, exactly as ignore does.
131
+ const payload = {
132
+ reason,
133
+ ...(note != null && note !== '' ? { note } : {}),
134
+ };
135
+ return zeniAPI
136
+ .putAndGetJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/accruals/${accrualId}/revert`, { ...payload })
137
+ .pipe(mergeMap((response) => {
138
+ if (isSuccessResponse(response) && response.data != null) {
139
+ return from([
140
+ updateJEOneTimeAccruals([response.data.accrual]),
141
+ oneTimeAccrualActionSuccess({ accrualId }),
142
+ openSnackbar({
143
+ messageSection: 'revert_accrual',
144
+ messageText: 'success',
145
+ type: 'success',
146
+ }),
147
+ ...refreshCurrentPage(state$.value),
148
+ ]);
149
+ }
150
+ return from(failureActions('revert_accrual', accrualId, response.status.message, response.status));
151
+ }), catchError((error) => from(failureActions('revert_accrual', accrualId, `Revert accrual REST API call errored out ${JSON.stringify(error)}`))),
152
+ // A tenant switch clears the store while this request is still in flight.
153
+ // Without this the old tenant's response is written back into the freshly
154
+ // cleared store and stays on screen under the new tenant.
155
+ takeUntil(actions$.pipe(filter(clearAll.match))));
156
+ }));
157
+ 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,33 @@
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 { fetchActualMatchingPage } from '../../reducers/actualMatchingViewReducer';
6
+ import { fetchJeSchedulesPage, updateJESchedulesUIState, } from '../../reducers/jeSchedulesViewReducer';
7
+ export const switchJESchedulesTabEpic = (actions$, state$) => actions$.pipe(filter(updateJESchedulesUIState.match), filter((action) => action.payload.selectedPageTab != null), mergeMap(() => {
8
+ const state = state$.value;
9
+ const { fetchState, refreshStatus } = state.expenseAutomationJESchedulesViewState;
10
+ if (fetchState === 'In-Progress' ||
11
+ refreshStatus.fetchState === 'In-Progress') {
12
+ return EMPTY;
13
+ }
14
+ const currentTenant = getCurrentTenant(state);
15
+ const selectedPeriod = state.expenseAutomationViewState.selectedPeriodByTenantId[currentTenant.tenantId];
16
+ // convertToPeriod destructures, so an unset period throws and takes this epic's subscription
17
+ // down for the rest of the session -- every later tab switch would then stop refreshing. A
18
+ // skipped refresh is the cheaper failure, as in refreshCurrentPage.
19
+ if (selectedPeriod == null) {
20
+ return EMPTY;
21
+ }
22
+ const period = convertToPeriod(selectedPeriod);
23
+ const timePeriodStart = toAbsoluteDay(period.start);
24
+ const timePeriodEnd = toAbsoluteDay(period.end);
25
+ if (timePeriodStart == null || timePeriodEnd == null) {
26
+ return EMPTY;
27
+ }
28
+ const { selectedPageTab } = state.expenseAutomationJESchedulesViewState.uiState;
29
+ if (selectedPageTab === 'actual_matching') {
30
+ return of(fetchActualMatchingPage({ start: timePeriodStart, end: timePeriodEnd }, true));
31
+ }
32
+ return of(fetchJeSchedulesPage({ start: timePeriodStart, end: timePeriodEnd }, true));
33
+ }));
@@ -4,6 +4,7 @@ import { getMonthEndCloseChecksForATenantForSelectedPeriod } from '../../entity/
4
4
  import { getCurrentTenant, } from '../../entity/tenant/tenantSelector';
5
5
  import { getCompanyMonthEndReportSelectorView } from '../companyMonthEndReportView/companyMonthEndReportViewSelector';
6
6
  import { getMonthEndCloseChecksViewByTenantId, isMonthEndInsightDisabled, } from '../monthEndCloseChecksView/monthEndCloseChecksViewSelector';
7
+ import { getExpenseAutomationActualMatchingView } from './selectors/actualMatchingViewSelector';
7
8
  import { getExpenseAutomationFluxAnalysisView } from './selectors/fluxAnalysisViewSelector';
8
9
  import { getAllSteps } from './selectors/getAllStepsHelper';
9
10
  import { getExpenseAutomationJESchedulesView } from './selectors/jeSchedulesViewSelector';
@@ -21,7 +22,7 @@ const isPreviousStepDisabled = (selectedTransactionCategorizationTab, allSteps,
21
22
  return allSteps[stepIndex - 1].isDisabled;
22
23
  };
23
24
  export function getExpenseAutomationView(state) {
24
- const { expenseAutomationViewState, tenantState, expenseAutomationMissingReceiptsViewState, expenseAutomationJESchedulesViewState, expenseAutomationTransactionsViewState, expenseAutomationReconciliationViewState, monthEndCloseChecksState, companyState, } = state;
25
+ const { expenseAutomationViewState, tenantState, expenseAutomationMissingReceiptsViewState, expenseAutomationJESchedulesViewState, expenseAutomationActualMatchingViewState, expenseAutomationTransactionsViewState, expenseAutomationReconciliationViewState, monthEndCloseChecksState, companyState, } = state;
25
26
  const { loggedInUser, currentTenantId } = tenantState;
26
27
  const currentTenant = getCurrentTenant(state);
27
28
  const { currentSelectedView, selectedPeriodByTenantId } = expenseAutomationViewState;
@@ -42,6 +43,7 @@ export function getExpenseAutomationView(state) {
42
43
  const reconciliation = getExpenseAutomationReconciliationView(state);
43
44
  const expenseAutomationTransactionsView = getExpenseAutomationTransactionView(state);
44
45
  const jeSchedules = getExpenseAutomationJESchedulesView(state);
46
+ const actualMatching = getExpenseAutomationActualMatchingView(state);
45
47
  switch (currentSelectedView) {
46
48
  case 'reconciliation':
47
49
  currentSelectedViewFetchState = reconciliation.fetchStatus;
@@ -54,12 +56,23 @@ export function getExpenseAutomationView(state) {
54
56
  fluxAnalysis.refreshStatus;
55
57
  break;
56
58
  case 'je_schedules':
57
- currentSelectedViewFetchState = {
58
- fetchState: jeSchedules.fetchState,
59
- error: jeSchedules.error,
60
- };
61
- currentSelectedViewBackgroundRefreshFetchState =
62
- jeSchedules.refreshStatus;
59
+ if (expenseAutomationJESchedulesViewState.uiState.selectedPageTab ===
60
+ 'actual_matching') {
61
+ currentSelectedViewFetchState = {
62
+ fetchState: actualMatching.fetchState,
63
+ error: actualMatching.error,
64
+ };
65
+ currentSelectedViewBackgroundRefreshFetchState =
66
+ actualMatching.refreshStatus;
67
+ }
68
+ else {
69
+ currentSelectedViewFetchState = {
70
+ fetchState: jeSchedules.fetchState,
71
+ error: jeSchedules.error,
72
+ };
73
+ currentSelectedViewBackgroundRefreshFetchState =
74
+ jeSchedules.refreshStatus;
75
+ }
63
76
  break;
64
77
  case 'missing_receipts':
65
78
  currentSelectedViewFetchState = {
@@ -91,6 +104,7 @@ export function getExpenseAutomationView(state) {
91
104
  const fetchStateVariables = [
92
105
  expenseAutomationMissingReceiptsViewState,
93
106
  expenseAutomationJESchedulesViewState,
107
+ expenseAutomationActualMatchingViewState,
94
108
  expenseAutomationTransactionsView,
95
109
  expenseAutomationReconciliationViewState,
96
110
  ];
@@ -176,6 +190,7 @@ export function getExpenseAutomationView(state) {
176
190
  ]);
177
191
  return {
178
192
  jeSchedules,
193
+ actualMatching,
179
194
  transactionView: expenseAutomationTransactionsView,
180
195
  missingReceipts,
181
196
  reconciliation,
@@ -0,0 +1,140 @@
1
+ import { toAmount } from '../../../commonStateTypes/amount';
2
+ import { DEFAULT_DATE_FORMAT } from '../../../commonStateTypes/timePeriod';
3
+ import { MONTH_YEAR_FORMAT } from '../../../commonStateTypes/fiscalYearHelpers/formatZeniDateFY';
4
+ import { LAST_SCHEDULE_DAY_OF_MONTH } from '../../../commonStateTypes/timePeriod';
5
+ import { getPostingDateAndStatusForIndex } from '../../scheduleView/scheduleDetailView/scheduleDetailLocalDataHelper';
6
+ import { mapScheduleTransactionToBaseScheduleTransactionPayload, } from '../../scheduleView/scheduleDetailView/scheduleDetailPayload';
7
+ const getNewScheduleMemo = (vendorName, schedulePostingDate, currentPeriod, totalPeriod, assetId) => {
8
+ const addAsset = assetId != null && assetId !== '' ? ` - ${assetId}` : '';
9
+ return `${vendorName} - ${schedulePostingDate.format(MONTH_YEAR_FORMAT)} (${currentPeriod} of ${totalPeriod})${addAsset}`;
10
+ };
11
+ /**
12
+ * Computes the month-by-month JE schedule breakdown for a brand-new schedule
13
+ * (no linked transaction yet) — replicates createNewSchedulesHelper's math
14
+ * (scheduleDetailLocalDataHelper.ts) exactly: lump-sum total split evenly
15
+ * across months with the rounding remainder absorbed by the last month, and a
16
+ * running balance that decrements each month and is forced to exactly 0 on
17
+ * the last row.
18
+ */
19
+ export const computeNewScheduleJeDetails = (localData, totalAmount, vendorName) => {
20
+ const period = localData.selectedMonths;
21
+ const startingMonth = localData.selectedDate;
22
+ if (startingMonth == null || period == null) {
23
+ return [];
24
+ }
25
+ const assetId = 'assetId' in localData ? localData.assetId : undefined;
26
+ const averageAmount = Math.abs(Math.round((totalAmount.amount / period) * 100) / 100);
27
+ const lastMonthAmount = Math.abs(Math.round((Math.abs(totalAmount.amount) - averageAmount * (period - 1)) * 100) / 100);
28
+ let runningBalance = Math.abs(totalAmount.amount);
29
+ const negativeNumbers = totalAmount.amount < 0 || runningBalance < 0;
30
+ const newJeDetails = [];
31
+ for (let index = 0; index < period; index++) {
32
+ if (runningBalance > averageAmount) {
33
+ runningBalance = Math.round((runningBalance - averageAmount) * 100) / 100;
34
+ }
35
+ else {
36
+ runningBalance = 0;
37
+ }
38
+ const amount = index === period - 1 ? lastMonthAmount : averageAmount;
39
+ runningBalance = index === period - 1 ? 0 : runningBalance;
40
+ const schedulePostingDate = startingMonth.add(index, 'month');
41
+ const { postingDate, postingStatus } = getPostingDateAndStatusForIndex(schedulePostingDate.month(), schedulePostingDate.year(), localData.lastDayOfMonth === true
42
+ ? undefined
43
+ : localData.selectedDayOfMonth);
44
+ newJeDetails.push({
45
+ postingDate,
46
+ amount: toAmount(negativeNumbers ? -amount : amount, totalAmount.currencyCode, totalAmount.currencySymbol),
47
+ runningBalance: toAmount(negativeNumbers ? -runningBalance : runningBalance, totalAmount.currencyCode, totalAmount.currencySymbol),
48
+ postingStatus,
49
+ memo: getNewScheduleMemo(vendorName, schedulePostingDate, index + 1, period, assetId),
50
+ jeLink: { type: 'unknown' },
51
+ });
52
+ }
53
+ return newJeDetails;
54
+ };
55
+ const mapNewJeDetailsToScheduledJournalEntryPayload = (jeScheduleDetails) => jeScheduleDetails.map((journalEntry) => ({
56
+ status: {
57
+ code: journalEntry.postingStatus,
58
+ label: journalEntry.postingStatus,
59
+ },
60
+ transaction_memo: journalEntry.memo,
61
+ third_party_id: journalEntry.jeLink.thirdPartyTransactionId ?? null,
62
+ expected_post_date: journalEntry.postingDate.format(DEFAULT_DATE_FORMAT),
63
+ amount: journalEntry.amount.amount,
64
+ balance: journalEntry.runningBalance.amount,
65
+ // Brand-new schedule — there is no prior scheduled-journal-entry history
66
+ // to cross-reference (unlike the legacy edit flow's equivalent mapper).
67
+ scheduled_journal_entry_id: null,
68
+ actual_post_date: null,
69
+ is_platform_generated: null,
70
+ je_schedule_id: null,
71
+ update_time: null,
72
+ create_time: null,
73
+ }));
74
+ /**
75
+ * Builds a savable schedule payload directly from a Base Transaction search
76
+ * result and the New Schedule form's local data — bypassing the legacy
77
+ * getJEScheduledTransactionByJEScheduleTransactionKey selector entirely,
78
+ * since that selector throws unless the entity has already round-tripped
79
+ * through a real GET /1.0/schedules/:id. A brand-new schedule has no such
80
+ * history, so this reads only from data already in hand (the selected
81
+ * transaction/line plus what the user filled into the form).
82
+ */
83
+ export const prepareNewSchedulePayload = (transaction, localData, scheduleType) => {
84
+ if (transaction.thirdPartyTransactionId == null ||
85
+ transaction.thirdPartyTransactionId === '') {
86
+ return { ok: false, reason: 'missing_third_party_id' };
87
+ }
88
+ const scheduleTransaction = transaction;
89
+ const vendorId = localData.selectedVendor?.id ?? transaction.vendorId ?? '';
90
+ const vendorName = localData.selectedVendor?.name ?? transaction.vendorName ?? '';
91
+ if (vendorId === '' || vendorName === '') {
92
+ return { ok: false, reason: 'missing_vendor' };
93
+ }
94
+ const vendor = {
95
+ vendor_id: vendorId,
96
+ vendor_name: vendorName,
97
+ };
98
+ const jeScheduleDetails = computeNewScheduleJeDetails(localData, scheduleTransaction.amount, vendorName);
99
+ const postingDate = localData.selectedDayOfMonth ??
100
+ (localData.lastDayOfMonth === true ? LAST_SCHEDULE_DAY_OF_MONTH : null);
101
+ const firstJEScheduleDate = jeScheduleDetails.length > 0
102
+ ? jeScheduleDetails[0].postingDate.format(DEFAULT_DATE_FORMAT)
103
+ : null;
104
+ const lastJEScheduleDate = jeScheduleDetails.length > 0
105
+ ? jeScheduleDetails[jeScheduleDetails.length - 1].postingDate.format(DEFAULT_DATE_FORMAT)
106
+ : null;
107
+ const isFixedAssets = scheduleType === 'fixed_assets';
108
+ const assetId = 'assetId' in localData ? localData.assetId : undefined;
109
+ const selectedAccumulatedDepreciationCategory = 'selectedAccumulatedDepreciationCategory' in localData
110
+ ? localData.selectedAccumulatedDepreciationCategory
111
+ : undefined;
112
+ const status = { code: 'new', label: 'New' };
113
+ const jeSchedulePayload = {
114
+ status,
115
+ vendor,
116
+ currency_code: scheduleTransaction.currency.currencyCode,
117
+ currency_symbol: scheduleTransaction.currency.currencySymbol,
118
+ period: localData.selectedMonths ?? null,
119
+ je_schedule_type: scheduleType,
120
+ posting_date: postingDate,
121
+ balance: scheduleTransaction.amount.amount,
122
+ start_date: firstJEScheduleDate,
123
+ end_date: lastJEScheduleDate,
124
+ je_credit_accounting_class_id: scheduleTransaction.classBase?.classId ?? null,
125
+ je_credit_account_id: isFixedAssets
126
+ ? (selectedAccumulatedDepreciationCategory ?? null)
127
+ : scheduleTransaction.account.accountId,
128
+ je_debit_account_id: localData.selectedAccount ?? null,
129
+ je_debit_accounting_class_id: localData.selectedClass ?? null,
130
+ other_attributes: assetId != null ? { asset_id: assetId } : {},
131
+ base_transaction: mapScheduleTransactionToBaseScheduleTransactionPayload(scheduleTransaction),
132
+ };
133
+ return {
134
+ ok: true,
135
+ payload: {
136
+ je_schedules: [jeSchedulePayload],
137
+ scheduled_journal_entries: mapNewJeDetailsToScheduledJournalEntryPayload(jeScheduleDetails),
138
+ },
139
+ };
140
+ };
@@ -0,0 +1,35 @@
1
+ import { toString } from '../../../commonStateTypes/timePeriod';
2
+ import { toMatchAndReverseResultStatus, } from '../types/actualMatchingViewState';
3
+ export function toServiceMonthFromPeriod(period) {
4
+ return toString(period.start).slice(0, 7);
5
+ }
6
+ const DEFAULT_CURRENCY_CODE = 'USD';
7
+ const DEFAULT_CURRENCY_SYMBOL = '$';
8
+ export function toActualMatchingTransactionSearchResult(payload) {
9
+ const currencyCode = payload.currency_code ?? DEFAULT_CURRENCY_CODE;
10
+ return {
11
+ transactionId: payload.transaction_id,
12
+ transactionIntegrationId: payload.transaction_integration_id,
13
+ transactionType: payload.transaction_type,
14
+ lineId: payload.line_id,
15
+ vendorId: payload.vendor_id ?? undefined,
16
+ vendorName: payload.vendor_name ?? '',
17
+ amount: payload.total_amount,
18
+ transactionDate: payload.transaction_date,
19
+ accountId: payload.account_id ?? undefined,
20
+ accountName: payload.account_name ?? undefined,
21
+ currencyCode,
22
+ currencySymbol: payload.currency_symbol ??
23
+ (currencyCode === DEFAULT_CURRENCY_CODE
24
+ ? DEFAULT_CURRENCY_SYMBOL
25
+ : currencyCode),
26
+ transactionMemo: payload.transaction_memo ?? undefined,
27
+ };
28
+ }
29
+ export function toMatchAndReverseResult(payload) {
30
+ return {
31
+ accrualId: payload.accrual_id,
32
+ status: toMatchAndReverseResultStatus(payload.status),
33
+ reason: payload.reason ?? undefined,
34
+ };
35
+ }
@@ -1,5 +1,60 @@
1
1
  import { DEFAULT_DATE_FORMAT } from '../../../commonStateTypes/timePeriod';
2
+ import { getClassList } from '../../classList/classListSelector';
2
3
  import { mapScheduleTransactionToBaseScheduleTransactionPayload, mapVendorToVendorPayload, } from '../../scheduleView/scheduleDetailView/scheduleDetailPayload';
4
+ const BALANCE_SHEET_CLASS_LABEL = 'balance_sheet';
5
+ const SERVICE_MONTH_FORMAT = 'YYYY-MM';
6
+ /**
7
+ * The credit line is the accrued liability, which always sits on the balance sheet — the
8
+ * recurring accrued path resolves the same class the same way (see
9
+ * prepareNewScheduleAccruedDetailPayload). Omitted rather than sent empty when the tenant has
10
+ * no balance_sheet class, since the API treats the field as optional.
11
+ */
12
+ export const prepareCreateOneTimeAccrualPayload = (state, localData) => {
13
+ const { classListState, classState } = state;
14
+ const balanceSheetClass = getClassList(classState, classListState).classes.find((accountingClass) => accountingClass.labels?.includes(BALANCE_SHEET_CLASS_LABEL) === true);
15
+ // reverse_next_month alone decides reversal_policy server-side, so reversal_policy is
16
+ // deliberately not sent — the API documents it only as an alternate way to say on_bill_match,
17
+ // and sending both would be two sources of truth for one toggle.
18
+ const reversalFields = localData.reverseNextMonth
19
+ ? {
20
+ reverse_next_month: true,
21
+ expected_reversal_date: getExpectedReversalDate(localData.serviceMonth).format(DEFAULT_DATE_FORMAT),
22
+ }
23
+ : { reverse_next_month: false };
24
+ return {
25
+ vendor_id: localData.vendorId,
26
+ vendor_name: localData.vendorName,
27
+ service_month: localData.serviceMonth.format(SERVICE_MONTH_FORMAT),
28
+ amount: localData.amount,
29
+ memo: localData.memo,
30
+ je_debit_account_id: localData.debitAccountId,
31
+ je_credit_account_id: localData.creditAccountId,
32
+ ...(localData.debitAccountName != null
33
+ ? { je_debit_account_name: localData.debitAccountName }
34
+ : {}),
35
+ ...(localData.creditAccountName != null
36
+ ? { je_credit_account_name: localData.creditAccountName }
37
+ : {}),
38
+ ...(localData.debitClassId != null
39
+ ? { je_debit_accounting_class_id: localData.debitClassId }
40
+ : {}),
41
+ ...(localData.debitClassName != null
42
+ ? { je_debit_accounting_class_name: localData.debitClassName }
43
+ : {}),
44
+ ...(balanceSheetClass != null
45
+ ? {
46
+ je_credit_accounting_class_id: balanceSheetClass.classId,
47
+ je_credit_accounting_class_name: balanceSheetClass.className,
48
+ }
49
+ : {}),
50
+ ...reversalFields,
51
+ };
52
+ };
53
+ /**
54
+ * The API defaults this to the 1st of the month after service_month. We send it explicitly so the
55
+ * date the form promised the user is the date that gets stored.
56
+ */
57
+ export const getExpectedReversalDate = (serviceMonth) => serviceMonth.add(1, 'month').startOf('month');
3
58
  export const prepareIgnoreSchedulePayload = (scheduleType, jeScheduleTransaction, state) => {
4
59
  const { vendorState } = state;
5
60
  const { vendor, currencyCode, currencySymbol, baseTransaction, status, balanceAsOfToday, period, startDate, endDate, jeCredit, jeDebit, } = jeScheduleTransaction;