@zeniai/client-epic-state 5.1.57-betaDI1 → 5.1.57-betaRD2

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 (100) hide show
  1. package/lib/coreEpics.js +2 -3
  2. package/lib/entity/chargeCard/chargeCard.d.ts +1 -1
  3. package/lib/entity/jeSchedules/jeSchedulesPayload.d.ts +2 -0
  4. package/lib/entity/jeSchedules/jeSchedulesPayload.js +2 -0
  5. package/lib/entity/jeSchedules/jeSchedulesSelector.d.ts +4 -0
  6. package/lib/entity/jeSchedules/jeSchedulesSelector.js +11 -1
  7. package/lib/entity/jeSchedules/jeSchedulesState.d.ts +2 -0
  8. package/lib/entity/tenant/clearAllEpic.d.ts +1 -3
  9. package/lib/entity/tenant/clearAllEpic.js +0 -4
  10. package/lib/entity/transaction/scheduleTransactionHelper.d.ts +15 -0
  11. package/lib/entity/transaction/scheduleTransactionHelper.js +43 -0
  12. package/lib/epic.d.ts +5 -2
  13. package/lib/epic.js +5 -2
  14. package/lib/esm/coreEpics.js +2 -3
  15. package/lib/esm/entity/jeSchedules/jeSchedulesPayload.js +2 -0
  16. package/lib/esm/entity/jeSchedules/jeSchedulesSelector.js +11 -1
  17. package/lib/esm/entity/tenant/clearAllEpic.js +0 -4
  18. package/lib/esm/entity/transaction/scheduleTransactionHelper.js +39 -0
  19. package/lib/esm/epic.js +5 -2
  20. package/lib/esm/index.js +7 -9
  21. package/lib/esm/reducer.js +0 -6
  22. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/fetchJeSchedulesEpic.js +15 -2
  23. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/newSchedule/initializeNewScheduleEpic.js +21 -0
  24. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/newSchedule/saveNewScheduleEpic.js +110 -0
  25. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/newSchedule/searchTransactionsForNewScheduleEpic.js +53 -0
  26. package/lib/esm/view/expenseAutomationView/epics/jeSchedule/switchJESchedulesTabEpic.js +22 -0
  27. package/lib/esm/view/expenseAutomationView/helpers/newScheduleLocalDataHelper.js +152 -0
  28. package/lib/esm/view/expenseAutomationView/reducers/jeSchedulesViewReducer.js +126 -6
  29. package/lib/esm/view/expenseAutomationView/selectorTypes/jeNewScheduleViewSelectorTypes.js +1 -0
  30. package/lib/esm/view/expenseAutomationView/selectors/jeNewScheduleViewSelector.js +71 -0
  31. package/lib/esm/view/expenseAutomationView/selectors/jeSchedulesViewSelector.js +65 -11
  32. package/lib/esm/view/expenseAutomationView/types/jeSchedulesViewState.js +3 -6
  33. package/lib/esm/view/settingsView/epic/fetchNotificationSettingsEpic.js +2 -21
  34. package/lib/esm/view/settingsView/epic/saveNotificationSettingsEpic.js +1 -2
  35. package/lib/esm/view/settingsView/settingsViewHelpers.js +2 -3
  36. package/lib/index.d.ts +9 -12
  37. package/lib/index.js +58 -56
  38. package/lib/reducer.d.ts +0 -6
  39. package/lib/reducer.js +0 -6
  40. package/lib/view/common/recurringViewHelper.d.ts +2 -2
  41. package/lib/view/expenseAutomationView/epics/jeSchedule/fetchJeSchedulesEpic.js +14 -1
  42. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/initializeNewScheduleEpic.d.ts +8 -0
  43. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/initializeNewScheduleEpic.js +25 -0
  44. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/saveNewScheduleEpic.d.ts +45 -0
  45. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/saveNewScheduleEpic.js +114 -0
  46. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/searchTransactionsForNewScheduleEpic.d.ts +8 -0
  47. package/lib/view/expenseAutomationView/epics/jeSchedule/newSchedule/searchTransactionsForNewScheduleEpic.js +57 -0
  48. package/lib/view/expenseAutomationView/epics/jeSchedule/switchJESchedulesTabEpic.d.ts +6 -0
  49. package/lib/view/expenseAutomationView/epics/jeSchedule/switchJESchedulesTabEpic.js +26 -0
  50. package/lib/view/expenseAutomationView/helpers/newScheduleLocalDataHelper.d.ts +43 -0
  51. package/lib/view/expenseAutomationView/helpers/newScheduleLocalDataHelper.js +158 -0
  52. package/lib/view/expenseAutomationView/payload/jeSchedulesPayload.d.ts +1 -0
  53. package/lib/view/expenseAutomationView/reducers/jeSchedulesViewReducer.d.ts +36 -8
  54. package/lib/view/expenseAutomationView/reducers/jeSchedulesViewReducer.js +128 -7
  55. package/lib/view/expenseAutomationView/selectorTypes/jeNewScheduleViewSelectorTypes.d.ts +25 -0
  56. package/lib/view/expenseAutomationView/selectorTypes/jeNewScheduleViewSelectorTypes.js +2 -0
  57. package/lib/view/expenseAutomationView/selectorTypes/jeSchedulesSelectorTypes.d.ts +29 -4
  58. package/lib/view/expenseAutomationView/selectors/jeNewScheduleViewSelector.d.ts +10 -0
  59. package/lib/view/expenseAutomationView/selectors/jeNewScheduleViewSelector.js +76 -0
  60. package/lib/view/expenseAutomationView/selectors/jeSchedulesViewSelector.js +65 -11
  61. package/lib/view/expenseAutomationView/types/jeSchedulesViewState.d.ts +53 -6
  62. package/lib/view/expenseAutomationView/types/jeSchedulesViewState.js +5 -8
  63. package/lib/view/settingsView/epic/fetchNotificationSettingsEpic.d.ts +1 -9
  64. package/lib/view/settingsView/epic/fetchNotificationSettingsEpic.js +2 -21
  65. package/lib/view/settingsView/epic/saveNotificationSettingsEpic.js +1 -2
  66. package/lib/view/settingsView/settingsViewHelpers.d.ts +1 -1
  67. package/lib/view/settingsView/settingsViewHelpers.js +2 -3
  68. package/lib/view/settingsView/settingsViewPayload.d.ts +0 -4
  69. package/lib/view/settingsView/settingsViewState.d.ts +1 -1
  70. package/package.json +1 -1
  71. package/lib/entity/notificationRegistry/notificationRegistryPayload.d.ts +0 -18
  72. package/lib/entity/notificationRegistry/notificationRegistryPayload.js +0 -28
  73. package/lib/entity/notificationRegistry/notificationRegistryReducer.d.ts +0 -6
  74. package/lib/entity/notificationRegistry/notificationRegistryReducer.js +0 -26
  75. package/lib/entity/notificationRegistry/notificationRegistrySelector.d.ts +0 -2
  76. package/lib/entity/notificationRegistry/notificationRegistrySelector.js +0 -10
  77. package/lib/entity/notificationRegistry/notificationRegistryState.d.ts +0 -31
  78. package/lib/entity/notificationRegistry/notificationRegistryState.js +0 -10
  79. package/lib/esm/entity/notificationRegistry/notificationRegistryPayload.js +0 -24
  80. package/lib/esm/entity/notificationRegistry/notificationRegistryReducer.js +0 -22
  81. package/lib/esm/entity/notificationRegistry/notificationRegistrySelector.js +0 -6
  82. package/lib/esm/entity/notificationRegistry/notificationRegistryState.js +0 -5
  83. package/lib/esm/view/notificationPreferencesView/epics/saveNotificationPreferencesEpic.js +0 -103
  84. package/lib/esm/view/notificationPreferencesView/notificationPreferencesEndpoint.js +0 -5
  85. package/lib/esm/view/notificationPreferencesView/notificationPreferencesViewPayload.js +0 -36
  86. package/lib/esm/view/notificationPreferencesView/notificationPreferencesViewReducer.js +0 -222
  87. package/lib/esm/view/notificationPreferencesView/notificationPreferencesViewSelector.js +0 -25
  88. package/lib/esm/view/notificationPreferencesView/notificationPreferencesViewState.js +0 -4
  89. package/lib/view/notificationPreferencesView/epics/saveNotificationPreferencesEpic.d.ts +0 -34
  90. package/lib/view/notificationPreferencesView/epics/saveNotificationPreferencesEpic.js +0 -107
  91. package/lib/view/notificationPreferencesView/notificationPreferencesEndpoint.d.ts +0 -2
  92. package/lib/view/notificationPreferencesView/notificationPreferencesEndpoint.js +0 -9
  93. package/lib/view/notificationPreferencesView/notificationPreferencesViewPayload.d.ts +0 -7
  94. package/lib/view/notificationPreferencesView/notificationPreferencesViewPayload.js +0 -41
  95. package/lib/view/notificationPreferencesView/notificationPreferencesViewReducer.d.ts +0 -30
  96. package/lib/view/notificationPreferencesView/notificationPreferencesViewReducer.js +0 -226
  97. package/lib/view/notificationPreferencesView/notificationPreferencesViewSelector.d.ts +0 -7
  98. package/lib/view/notificationPreferencesView/notificationPreferencesViewSelector.js +0 -32
  99. package/lib/view/notificationPreferencesView/notificationPreferencesViewState.d.ts +0 -14
  100. package/lib/view/notificationPreferencesView/notificationPreferencesViewState.js +0 -8
@@ -37,7 +37,6 @@ import jeSchedules, { initialState as initialJESchedulesState, } from './entity/
37
37
  import merchant, { initialState as initialMerchantState, } from './entity/merchant/merchantReducer';
38
38
  import monthEndCloseChecks, { initialState as initialMonthEndCloseChecksState, } from './entity/monthEndCloseChecks/monthEndCloseChecksReducer';
39
39
  import notification, { initialState as initialNotificationState, } from './entity/notification/notificationReducer';
40
- import notificationRegistry, { initialState as initialNotificationRegistryState, } from './entity/notificationRegistry/notificationRegistryReducer';
41
40
  import onboardingCustomer, { initialState as initialOnboardingCustomerState, } from './entity/onboardingCustomer/onboardingCustomerReducer';
42
41
  import paymentAccount, { initialState as initialPaymentAccountState, } from './entity/paymentAccount/paymentAccountReducer';
43
42
  import paymentInstrument, { initialState as initialPaymentInstrumentState, } from './entity/paymentInstrument/paymentInstrumentReducer';
@@ -122,7 +121,6 @@ import monthEndCloseChecksView, { initialState as initialMonthEndCloseChecksView
122
121
  import netBurnOrIncome, { initialState as initialNetBurnOrIncomeWithForecastState, } from './view/netBurnOrIncome/netBurnOrIncomeReducer';
123
122
  import netBurnOrIncomeClassesView, { initialState as initialNetBurnOrIncomeClassesViewState, } from './view/netBurnOrIncomeClassesView/netBurnOrIncomeClassesViewReducer';
124
123
  import netBurnOrIncomeStoryCard, { initialState as initialNetBurnOrIncomeStoryCardState, } from './view/netBurnOrIncomeStoryCard/netBurnOrIncomeStoryCardReducer';
125
- import notificationPreferencesView, { initialState as initialNotificationPreferencesViewState, } from './view/notificationPreferencesView/notificationPreferencesViewReducer';
126
124
  import notificationView, { initialState as initialNotificationViewState, } from './view/notificationView/notificationViewReducer';
127
125
  import onboardingCockpitView, { initialState as initialOnboardingCockpitViewState, } from './view/onboardingView/cockpitView/onboardingCockpitViewReducer';
128
126
  import onboardingCustomerView, { initialState as initialOnboardingCustomerViewState, } from './view/onboardingView/customerView/onboardingCustomerViewReducer';
@@ -389,8 +387,6 @@ const initialViewsState = {
389
387
  netBurnOrIncomeClassesViewState: initialNetBurnOrIncomeClassesViewState,
390
388
  netBurnOrIncomeState: initialNetBurnOrIncomeWithForecastState,
391
389
  netBurnOrIncomeStoryCardState: initialNetBurnOrIncomeStoryCardState,
392
- notificationPreferencesViewState: initialNotificationPreferencesViewState,
393
- notificationRegistryState: initialNotificationRegistryState,
394
390
  notificationViewState: initialNotificationViewState,
395
391
  onboardingCockpitViewState: initialOnboardingCockpitViewState,
396
392
  onboardingCustomerViewState: initialOnboardingCustomerViewState,
@@ -631,8 +627,6 @@ const viewReducers = {
631
627
  netBurnOrIncomeClassesViewState: netBurnOrIncomeClassesView,
632
628
  netBurnOrIncomeState: netBurnOrIncome,
633
629
  netBurnOrIncomeStoryCardState: netBurnOrIncomeStoryCard,
634
- notificationPreferencesViewState: notificationPreferencesView,
635
- notificationRegistryState: notificationRegistry,
636
630
  notificationViewState: notificationView,
637
631
  onboardingCockpitViewState: onboardingCockpitView,
638
632
  onboardingCustomerViewState: onboardingCustomerView,
@@ -1,9 +1,11 @@
1
1
  import { from, of } from 'rxjs';
2
2
  import { catchError, filter, mergeMap } from 'rxjs/operators';
3
- import { toString } from '../../../../commonStateTypes/timePeriod';
3
+ import { DEFAULT_DATE_FORMAT } from '../../../../commonStateTypes/fiscalYearHelpers/formatZeniDateFY';
4
+ import { toAbsoluteDay, toString } from '../../../../commonStateTypes/timePeriod';
4
5
  import { updateJESchedules, updateJESchedulesDetails, } from '../../../../entity/jeSchedules/jeSchedulesReducer';
5
6
  import { getCurrentTenant } from '../../../../entity/tenant/tenantSelector';
6
7
  import { createZeniAPIStatus, isSuccessResponse, } from '../../../../responsePayload';
8
+ import { date } from '../../../../zeniDayJS';
7
9
  import { fetchJeSchedules, fetchJeSchedulesFailure, fetchJeSchedulesSuccess, initializeJeScheduleLocalData, } from '../../reducers/jeSchedulesViewReducer';
8
10
  export const fetchJeSchedulesEpic = (actions$, state$, zeniAPI) => actions$.pipe(filter(fetchJeSchedules.match), mergeMap((action) => {
9
11
  const state = state$.value;
@@ -11,9 +13,20 @@ export const fetchJeSchedulesEpic = (actions$, state$, zeniAPI) => actions$.pipe
11
13
  const { period, refreshViewInBackground } = action.payload;
12
14
  const currentTenant = getCurrentTenant(state);
13
15
  const selectedPeriod = selectedPeriodByTenantId[currentTenant.tenantId];
16
+ const isClosePeriodTab = state.expenseAutomationJESchedulesViewState.uiState.selectedPageTab ===
17
+ 'schedules';
18
+ const existingEndDate = toAbsoluteDay(date(toString(period.start))
19
+ .subtract(1, 'month')
20
+ .endOf('month')
21
+ .format(DEFAULT_DATE_FORMAT));
14
22
  const queryParam = {
15
23
  start_date: toString(period.start),
16
- end_date: toString(period.end),
24
+ end_date: isClosePeriodTab || existingEndDate == null
25
+ ? toString(period.end)
26
+ : toString(existingEndDate),
27
+ ...(isClosePeriodTab
28
+ ? { close_period_start_date: toString(period.start) }
29
+ : {}),
17
30
  };
18
31
  return zeniAPI
19
32
  .getJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/expenses_automation/je_schedules?query=${encodeURIComponent(JSON.stringify(queryParam))}`)
@@ -0,0 +1,21 @@
1
+ import { from } from 'rxjs';
2
+ import { filter, mergeMap } from 'rxjs/operators';
3
+ import { fetchAccountList } from '../../../../accountList/accountListReducer';
4
+ import { fetchClassList } from '../../../../classList/classListReducer';
5
+ import { getAccountsTypesForScheduleEpics } from '../../../../scheduleView/scheduleListView/scheduleListHelper';
6
+ import { clearSearchTransactionsForNewSchedule, initializeNewSchedule, resetNewScheduleLocalData, } from '../../../reducers/jeSchedulesViewReducer';
7
+ export const initializeNewScheduleEpic = (actions$, state$) => actions$.pipe(filter(initializeNewSchedule.match), mergeMap((action) => {
8
+ const newScheduleActions = [];
9
+ const accountType = getAccountsTypesForScheduleEpics();
10
+ const { accountListState, classListState } = state$.value;
11
+ if (accountListState.byReportId[accountType.accountListKey]?.fetchState ===
12
+ 'Not-Started') {
13
+ newScheduleActions.push(fetchAccountList(accountType.accountListKey, true, false, false, false, accountType.allowedAccountList));
14
+ }
15
+ if (classListState.fetchState === 'Not-Started') {
16
+ newScheduleActions.push(fetchClassList());
17
+ }
18
+ newScheduleActions.push(resetNewScheduleLocalData({ scheduleType: action.payload.scheduleType }));
19
+ newScheduleActions.push(clearSearchTransactionsForNewSchedule());
20
+ return from(newScheduleActions);
21
+ }));
@@ -0,0 +1,110 @@
1
+ import { from } from 'rxjs';
2
+ import { catchError, filter, mergeMap } from 'rxjs/operators';
3
+ import { updateJESchedules, updateJESchedulesDetails, } from '../../../../../entity/jeSchedules/jeSchedulesReducer';
4
+ import { openSnackbar } from '../../../../../entity/snackbar/snackbarReducer';
5
+ import { getSupportedTransactionById } from '../../../../../entity/transaction/transactionSelector';
6
+ import { createZeniAPIStatus, isSuccessResponse, } from '../../../../../responsePayload';
7
+ import { prepareNewSchedulePayload, } from '../../../helpers/newScheduleLocalDataHelper';
8
+ import { resetNewScheduleLocalData, saveNewSchedule, saveNewScheduleFailure, saveNewScheduleSuccess, } from '../../../reducers/jeSchedulesViewReducer';
9
+ const FAILURE_REASON_MESSAGES = {
10
+ multi_line_not_supported: 'This transaction has multiple lines and cannot be scheduled yet.',
11
+ missing_third_party_id: 'This transaction is missing a QuickBooks reference and cannot be scheduled.',
12
+ missing_vendor: 'Select a vendor before saving this schedule.',
13
+ };
14
+ export const saveNewScheduleEpic = (actions$, state$, zeniAPI) => actions$.pipe(filter(saveNewSchedule.match), mergeMap((action) => {
15
+ const { scheduleType } = action.payload;
16
+ const state = state$.value;
17
+ const localData = state.expenseAutomationJESchedulesViewState.newSchedule
18
+ .newScheduleState[scheduleType];
19
+ const transactionId = localData.selectedBaseTransactionId?.id;
20
+ const transaction = transactionId != null
21
+ ? getSupportedTransactionById(state.transactionState, transactionId)
22
+ : undefined;
23
+ if (transaction == null) {
24
+ return from([
25
+ saveNewScheduleFailure({
26
+ status: createZeniAPIStatus('Unexpected Error', 'No base transaction selected for this schedule.'),
27
+ }),
28
+ openSnackbar({
29
+ messageSection: 'create_schedule',
30
+ messageText: 'failed',
31
+ type: 'error',
32
+ variables: [
33
+ {
34
+ variableName: '_api-error_',
35
+ variableValue: 'No base transaction selected.',
36
+ },
37
+ ],
38
+ }),
39
+ ]);
40
+ }
41
+ const result = prepareNewSchedulePayload(transaction, localData, scheduleType);
42
+ if (!result.ok) {
43
+ const message = FAILURE_REASON_MESSAGES[result.reason];
44
+ return from([
45
+ saveNewScheduleFailure({
46
+ status: createZeniAPIStatus('Unexpected Error', message),
47
+ }),
48
+ openSnackbar({
49
+ messageSection: 'create_schedule',
50
+ messageText: 'failed',
51
+ type: 'error',
52
+ variables: [{ variableName: '_api-error_', variableValue: message }],
53
+ }),
54
+ ]);
55
+ }
56
+ const vendorName = localData.selectedVendor?.name ?? transaction.vendorName ?? '';
57
+ const queryParam = {
58
+ je_schedule_type: scheduleType,
59
+ };
60
+ const payload = { ...result.payload };
61
+ return zeniAPI
62
+ .postAndGetJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/schedules?query=${encodeURIComponent(JSON.stringify(queryParam))}`, payload)
63
+ .pipe(mergeMap((response) => {
64
+ if (isSuccessResponse(response) && response.data != null) {
65
+ return from([
66
+ updateJESchedules(response.data.je_schedules),
67
+ updateJESchedulesDetails(response.data.je_schedules, response.data.scheduled_journal_entries),
68
+ resetNewScheduleLocalData({ scheduleType }),
69
+ saveNewScheduleSuccess(),
70
+ openSnackbar({
71
+ messageSection: 'create_schedule',
72
+ messageText: 'success',
73
+ type: 'success',
74
+ variables: [
75
+ { variableName: '_vendor_name_', variableValue: vendorName },
76
+ ],
77
+ }),
78
+ ]);
79
+ }
80
+ return from([
81
+ saveNewScheduleFailure({ status: response.status }),
82
+ openSnackbar({
83
+ messageSection: 'create_schedule',
84
+ messageText: 'failed',
85
+ type: 'error',
86
+ variables: [
87
+ {
88
+ variableName: '_api-error_',
89
+ variableValue: response.status.message,
90
+ },
91
+ ],
92
+ }),
93
+ ]);
94
+ }), catchError((error) => from([
95
+ openSnackbar({
96
+ messageSection: 'create_schedule',
97
+ messageText: 'failed',
98
+ type: 'error',
99
+ variables: [
100
+ {
101
+ variableName: '_api-error_',
102
+ variableValue: JSON.stringify(error),
103
+ },
104
+ ],
105
+ }),
106
+ saveNewScheduleFailure({
107
+ status: createZeniAPIStatus('Unexpected Error', `Save New Schedule REST API call errored out ${JSON.stringify(error)}`),
108
+ }),
109
+ ])));
110
+ }));
@@ -0,0 +1,53 @@
1
+ import { EMPTY, from, merge, of } from 'rxjs';
2
+ import { catchError, debounceTime, filter, mergeMap, switchMap, } from 'rxjs/operators';
3
+ import { updateTransactions } from '../../../../../entity/transaction/transactionReducer';
4
+ import { createZeniAPIStatus, isSuccessResponse, } from '../../../../../responsePayload';
5
+ import { searchTransactionsForNewSchedule, searchTransactionsForNewScheduleFailure, searchTransactionsForNewScheduleSuccess, } from '../../../reducers/jeSchedulesViewReducer';
6
+ import { DEFAULT_COMPLETED_SUB_TAB } from '../../../types/completedSubTab';
7
+ import { MIN_NEW_SCHEDULE_SEARCH_LENGTH } from '../../../types/jeSchedulesViewState';
8
+ import { toTransactionsSortKey } from '../../../types/transactionsViewState';
9
+ /** Dropdown-sized result set — no pagination for Base Transaction search. */
10
+ const NEW_SCHEDULE_SEARCH_PAGE_SIZE = 10;
11
+ export const searchTransactionsForNewScheduleEpic = (actions$, _state$, zeniAPI) => {
12
+ const searchActions$ = actions$.pipe(filter(searchTransactionsForNewSchedule.match));
13
+ /** No API for empty or 1-char queries; immediate merge so switchMap cancels any in-flight HTTP. */
14
+ const newSearchTooShortOrClear$ = searchActions$.pipe(filter((action) => action.payload.query.trim().length < MIN_NEW_SCHEDULE_SEARCH_LENGTH));
15
+ const newSearchDebounced$ = searchActions$.pipe(filter((action) => action.payload.query.trim().length >= MIN_NEW_SCHEDULE_SEARCH_LENGTH), debounceTime(300));
16
+ return merge(newSearchTooShortOrClear$, newSearchDebounced$).pipe(switchMap((action) => {
17
+ const query = action.payload.query.trim();
18
+ if (query.length < MIN_NEW_SCHEDULE_SEARCH_LENGTH) {
19
+ return EMPTY;
20
+ }
21
+ const queryParam = {
22
+ start_date: null,
23
+ end_date: null,
24
+ auto_categorized: false,
25
+ sort_by: toTransactionsSortKey('date'),
26
+ sort_order: 'desc',
27
+ page_token: null,
28
+ page_size: NEW_SCHEDULE_SEARCH_PAGE_SIZE,
29
+ search_text: query,
30
+ sub_tab: DEFAULT_COMPLETED_SUB_TAB,
31
+ };
32
+ return zeniAPI
33
+ .getJSON(`${zeniAPI.apiEndPoints.accountMicroServiceBaseUrl}/1.0/expense-automation/transactions?query=${encodeURIComponent(JSON.stringify(queryParam))}`)
34
+ .pipe(mergeMap((response) => {
35
+ if (isSuccessResponse(response) && response.data != null) {
36
+ const { transactions } = response.data;
37
+ const actionsOut = [
38
+ updateTransactions(transactions, (value) => value.transaction_id, 'merge'),
39
+ searchTransactionsForNewScheduleSuccess({
40
+ searchResults: transactions.map((transaction) => transaction.transaction_id),
41
+ }),
42
+ ];
43
+ return from(actionsOut);
44
+ }
45
+ return of(searchTransactionsForNewScheduleFailure({
46
+ status: response.status,
47
+ }));
48
+ }), catchError((error) => of(searchTransactionsForNewScheduleFailure({
49
+ status: createZeniAPIStatus('Unexpected Error', 'Search transactions for new schedule errored: ' +
50
+ JSON.stringify(error)),
51
+ }))));
52
+ }));
53
+ };
@@ -0,0 +1,22 @@
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
+ const period = convertToPeriod(selectedPeriod);
16
+ const timePeriodStart = toAbsoluteDay(period.start);
17
+ const timePeriodEnd = toAbsoluteDay(period.end);
18
+ if (timePeriodStart == null || timePeriodEnd == null) {
19
+ return EMPTY;
20
+ }
21
+ return of(fetchJeSchedulesPage({ start: timePeriodStart, end: timePeriodEnd }, true));
22
+ }));
@@ -0,0 +1,152 @@
1
+ import { toAmount } from '../../../commonStateTypes/amount';
2
+ import { DEFAULT_DATE_FORMAT } from '../../../commonStateTypes/fiscalYearHelpers/formatZeniDateFY';
3
+ import { MONTH_YEAR_FORMAT } from '../../../commonStateTypes/fiscalYearHelpers/formatZeniDateFY';
4
+ import { LAST_SCHEDULE_DAY_OF_MONTH } from '../../../commonStateTypes/timePeriod';
5
+ import { mapSupportedTransactionLineToScheduleTransaction } from '../../../entity/transaction/scheduleTransactionHelper';
6
+ import { getPostingDateAndStatusForIndex } from '../../scheduleView/scheduleDetailView/scheduleDetailLocalDataHelper';
7
+ import { mapScheduleTransactionToBaseScheduleTransactionPayload, } from '../../scheduleView/scheduleDetailView/scheduleDetailPayload';
8
+ const getNewScheduleMemo = (vendorName, schedulePostingDate, currentPeriod, totalPeriod, assetId) => {
9
+ const addAsset = assetId != null && assetId !== '' ? ` - ${assetId}` : '';
10
+ return `${vendorName} - ${schedulePostingDate.format(MONTH_YEAR_FORMAT)} (${currentPeriod} of ${totalPeriod})${addAsset}`;
11
+ };
12
+ /**
13
+ * Computes the month-by-month JE schedule breakdown for a brand-new schedule
14
+ * (no linked transaction yet) — replicates createNewSchedulesHelper's math
15
+ * (scheduleDetailLocalDataHelper.ts) exactly: lump-sum total split evenly
16
+ * across months with the rounding remainder absorbed by the last month, and a
17
+ * running balance that decrements each month and is forced to exactly 0 on
18
+ * the last row.
19
+ */
20
+ export const computeNewScheduleJeDetails = (localData, totalAmount, vendorName) => {
21
+ const period = localData.selectedMonths;
22
+ const startingMonth = localData.selectedDate;
23
+ if (startingMonth == null || period == null) {
24
+ return [];
25
+ }
26
+ const assetId = 'assetId' in localData ? localData.assetId : undefined;
27
+ const averageAmount = Math.abs(Math.round((totalAmount.amount / period) * 100) / 100);
28
+ const lastMonthAmount = Math.abs(Math.round((Math.abs(totalAmount.amount) - averageAmount * (period - 1)) * 100) / 100);
29
+ let runningBalance = Math.abs(totalAmount.amount);
30
+ const negativeNumbers = totalAmount.amount < 0 || runningBalance < 0;
31
+ const newJeDetails = [];
32
+ for (let index = 0; index < period; index++) {
33
+ if (runningBalance > averageAmount) {
34
+ runningBalance = Math.round((runningBalance - averageAmount) * 100) / 100;
35
+ }
36
+ else {
37
+ runningBalance = 0;
38
+ }
39
+ const amount = index === period - 1 ? lastMonthAmount : averageAmount;
40
+ runningBalance = index === period - 1 ? 0 : runningBalance;
41
+ const schedulePostingDate = startingMonth.add(index, 'month');
42
+ const { postingDate, postingStatus } = getPostingDateAndStatusForIndex(schedulePostingDate.month(), schedulePostingDate.year(), localData.lastDayOfMonth === true
43
+ ? undefined
44
+ : localData.selectedDayOfMonth);
45
+ newJeDetails.push({
46
+ postingDate,
47
+ amount: toAmount(negativeNumbers ? -amount : amount, totalAmount.currencyCode, totalAmount.currencySymbol),
48
+ runningBalance: toAmount(negativeNumbers ? -runningBalance : runningBalance, totalAmount.currencyCode, totalAmount.currencySymbol),
49
+ postingStatus,
50
+ memo: getNewScheduleMemo(vendorName, schedulePostingDate, index + 1, period, assetId),
51
+ jeLink: { type: 'unknown' },
52
+ });
53
+ }
54
+ return newJeDetails;
55
+ };
56
+ /**
57
+ * Whether a Base Transaction search result can be selected for a new
58
+ * schedule this round — restricted to single-line transactions since the
59
+ * search/list endpoint's `lines` may not reflect the transaction's full line
60
+ * set, and there is no line-picker UI yet.
61
+ */
62
+ export const isSupportedTransactionSelectableForNewSchedule = (transaction) => transaction.totalLinesCount === 1 && transaction.lines?.length === 1;
63
+ const mapNewJeDetailsToScheduledJournalEntryPayload = (jeScheduleDetails) => jeScheduleDetails.map((journalEntry) => ({
64
+ status: {
65
+ code: journalEntry.postingStatus,
66
+ label: journalEntry.postingStatus,
67
+ },
68
+ transaction_memo: journalEntry.memo,
69
+ third_party_id: journalEntry.jeLink.thirdPartyTransactionId ?? null,
70
+ expected_post_date: journalEntry.postingDate.format(DEFAULT_DATE_FORMAT),
71
+ amount: journalEntry.amount.amount,
72
+ balance: journalEntry.runningBalance.amount,
73
+ // Brand-new schedule — there is no prior scheduled-journal-entry history
74
+ // to cross-reference (unlike the legacy edit flow's equivalent mapper).
75
+ scheduled_journal_entry_id: null,
76
+ actual_post_date: null,
77
+ is_platform_generated: null,
78
+ je_schedule_id: null,
79
+ update_time: null,
80
+ create_time: null,
81
+ }));
82
+ /**
83
+ * Builds a savable schedule payload directly from a Base Transaction search
84
+ * result and the New Schedule form's local data — bypassing the legacy
85
+ * getJEScheduledTransactionByJEScheduleTransactionKey selector entirely,
86
+ * since that selector throws unless the entity has already round-tripped
87
+ * through a real GET /1.0/schedules/:id. A brand-new schedule has no such
88
+ * history, so this reads only from data already in hand (the selected
89
+ * transaction/line plus what the user filled into the form).
90
+ */
91
+ export const prepareNewSchedulePayload = (transaction, localData, scheduleType) => {
92
+ const [firstLine] = transaction.lines ?? [];
93
+ if (!isSupportedTransactionSelectableForNewSchedule(transaction) ||
94
+ firstLine == null) {
95
+ return { ok: false, reason: 'multi_line_not_supported' };
96
+ }
97
+ const scheduleTransaction = mapSupportedTransactionLineToScheduleTransaction(transaction, firstLine.id);
98
+ if (scheduleTransaction == null) {
99
+ return { ok: false, reason: 'missing_third_party_id' };
100
+ }
101
+ const vendorId = localData.selectedVendor?.id ?? transaction.vendorId ?? '';
102
+ const vendorName = localData.selectedVendor?.name ?? transaction.vendorName ?? '';
103
+ if (vendorId === '' || vendorName === '') {
104
+ return { ok: false, reason: 'missing_vendor' };
105
+ }
106
+ const vendor = {
107
+ vendor_id: vendorId,
108
+ vendor_name: vendorName,
109
+ };
110
+ const jeScheduleDetails = computeNewScheduleJeDetails(localData, scheduleTransaction.amount, vendorName);
111
+ const postingDate = localData.selectedDayOfMonth ??
112
+ (localData.lastDayOfMonth === true ? LAST_SCHEDULE_DAY_OF_MONTH : null);
113
+ const firstJEScheduleDate = jeScheduleDetails.length > 0
114
+ ? jeScheduleDetails[0].postingDate.format(DEFAULT_DATE_FORMAT)
115
+ : null;
116
+ const lastJEScheduleDate = jeScheduleDetails.length > 0
117
+ ? jeScheduleDetails[jeScheduleDetails.length - 1].postingDate.format(DEFAULT_DATE_FORMAT)
118
+ : null;
119
+ const isFixedAssets = scheduleType === 'fixed_assets';
120
+ const assetId = 'assetId' in localData ? localData.assetId : undefined;
121
+ const selectedAccumulatedDepreciationCategory = 'selectedAccumulatedDepreciationCategory' in localData
122
+ ? localData.selectedAccumulatedDepreciationCategory
123
+ : undefined;
124
+ const status = { code: 'new', label: 'New' };
125
+ const jeSchedulePayload = {
126
+ status,
127
+ vendor,
128
+ currency_code: scheduleTransaction.currency.currencyCode,
129
+ currency_symbol: scheduleTransaction.currency.currencySymbol,
130
+ period: localData.selectedMonths ?? null,
131
+ je_schedule_type: scheduleType,
132
+ posting_date: postingDate,
133
+ balance: scheduleTransaction.amount.amount,
134
+ start_date: firstJEScheduleDate,
135
+ end_date: lastJEScheduleDate,
136
+ je_credit_accounting_class_id: scheduleTransaction.classBase?.classId ?? null,
137
+ je_credit_account_id: isFixedAssets
138
+ ? (selectedAccumulatedDepreciationCategory ?? null)
139
+ : scheduleTransaction.account.accountId,
140
+ je_debit_account_id: localData.selectedAccount ?? null,
141
+ je_debit_accounting_class_id: localData.selectedClass ?? null,
142
+ other_attributes: assetId != null ? { asset_id: assetId } : {},
143
+ base_transaction: mapScheduleTransactionToBaseScheduleTransactionPayload(scheduleTransaction),
144
+ };
145
+ return {
146
+ ok: true,
147
+ payload: {
148
+ je_schedules: [jeSchedulePayload],
149
+ scheduled_journal_entries: mapNewJeDetailsToScheduledJournalEntryPayload(jeScheduleDetails),
150
+ },
151
+ };
152
+ };
@@ -4,6 +4,7 @@ import { toMonthYearPeriodId, } from '../../../commonStateTypes/timePeriod';
4
4
  import { mapAccountBasePayloadToAccountBase, mapAccountMetadataPayloadToAccountMetadata, } from '../../../entity/account/accountPayload';
5
5
  import { getJEScheduleTransactionDetailKeyPayload, } from '../../../entity/jeSchedules/jeSchedulesPayload';
6
6
  import { mapAccountTypeRecommendationPayloadToAccountRecommendationByType, } from '../../accountMappingView/accountTypeRecommendation/accountTypeRecommendationPayload';
7
+ import { MIN_NEW_SCHEDULE_SEARCH_LENGTH, } from '../types/jeSchedulesViewState';
7
8
  export const accountSettingsInitialState = {
8
9
  localData: {
9
10
  selectedPrepaidExpensesAccountIds: [],
@@ -35,6 +36,19 @@ export const accountSettingsInitialState = {
35
36
  accruedExpensesNestedAccountListHierarchy: [],
36
37
  accruedExpensesRecommendations: [],
37
38
  };
39
+ export const getBaseNewScheduleLocalData = (scheduleType) => ({
40
+ scheduleType,
41
+ jeScheduleDetails: [],
42
+ });
43
+ export const newScheduleInitialState = {
44
+ fixed_assets: getBaseNewScheduleLocalData('fixed_assets'),
45
+ prepaid_expenses: getBaseNewScheduleLocalData('prepaid_expenses'),
46
+ };
47
+ export const searchTransactionsInitialState = {
48
+ searchResults: [],
49
+ fetchState: 'Not-Started',
50
+ error: undefined,
51
+ };
38
52
  export const initialState = {
39
53
  jeScheduleTransactionKeysByPeriod: {},
40
54
  failedJeScheduleTransactionKeysByPeriod: {},
@@ -42,9 +56,12 @@ export const initialState = {
42
56
  ignoreStatusById: {},
43
57
  jeScheduleLocalDataById: {},
44
58
  uiState: {
45
- searchString: '',
59
+ createdGroupCollapsed: false,
60
+ pendingGroupCollapsed: false,
46
61
  scrollPosition: { scrollTop: 0, scrollLeft: undefined },
47
- selectedMainTab: 'pending_review',
62
+ searchString: '',
63
+ selectedJETypeFilter: null,
64
+ selectedPageTab: 'schedules',
48
65
  sortKey: 'transactionDate',
49
66
  sortOrder: 'descending',
50
67
  totalCount: 0,
@@ -55,6 +72,13 @@ export const initialState = {
55
72
  error: undefined,
56
73
  },
57
74
  accountSettings: accountSettingsInitialState,
75
+ newSchedule: {
76
+ newScheduleState: newScheduleInitialState,
77
+ saveStatus: { fetchState: 'Not-Started', error: undefined },
78
+ searchTransactions: searchTransactionsInitialState,
79
+ fetchState: 'Not-Started',
80
+ error: undefined,
81
+ },
58
82
  fetchState: 'Not-Started',
59
83
  error: undefined,
60
84
  hasValidState() {
@@ -121,8 +145,8 @@ const expenseAutomationJESchedulesView = createSlice({
121
145
  else {
122
146
  draft.fetchState = 'Error';
123
147
  draft.error = status;
148
+ draft.jeScheduleTransactionKeysByPeriod[toMonthYearPeriodId(selectedPeriod)] = [];
124
149
  }
125
- draft.jeScheduleTransactionKeysByPeriod[toMonthYearPeriodId(selectedPeriod)] = [];
126
150
  },
127
151
  retryJeSchedule(draft, action) {
128
152
  const { scheduledJournalEntryID } = action.payload;
@@ -368,6 +392,91 @@ const expenseAutomationJESchedulesView = createSlice({
368
392
  clearJeAccountSettingsLocalData(draft) {
369
393
  draft.accountSettings.localData = accountSettingsInitialState.localData;
370
394
  },
395
+ initializeNewSchedule: {
396
+ prepare({ scheduleType, }) {
397
+ return { payload: { scheduleType } };
398
+ },
399
+ reducer() {
400
+ // Purely an epic-trigger action — the epic fans out the account/class
401
+ // list fetches plus resetNewScheduleLocalData.
402
+ },
403
+ },
404
+ resetNewScheduleLocalData: {
405
+ prepare({ scheduleType, }) {
406
+ return { payload: { scheduleType } };
407
+ },
408
+ reducer(draft, action) {
409
+ const { scheduleType } = action.payload;
410
+ draft.newSchedule.newScheduleState[scheduleType] =
411
+ getBaseNewScheduleLocalData(scheduleType);
412
+ },
413
+ },
414
+ updateNewScheduleLocalData(draft, action) {
415
+ const { scheduleType, localData } = action.payload;
416
+ draft.newSchedule.newScheduleState[scheduleType] = {
417
+ ...draft.newSchedule.newScheduleState[scheduleType],
418
+ ...localData,
419
+ };
420
+ },
421
+ searchTransactionsForNewSchedule: {
422
+ prepare({ query }) {
423
+ return { payload: { query } };
424
+ },
425
+ reducer(draft, action) {
426
+ const trimmed = action.payload.query.trim();
427
+ // Cleared or too-short query: no API (see epic) — reset immediately.
428
+ if (trimmed.length < MIN_NEW_SCHEDULE_SEARCH_LENGTH) {
429
+ draft.newSchedule.searchTransactions = searchTransactionsInitialState;
430
+ return;
431
+ }
432
+ draft.newSchedule.searchTransactions = {
433
+ ...draft.newSchedule.searchTransactions,
434
+ searchString: action.payload.query,
435
+ fetchState: 'In-Progress',
436
+ };
437
+ },
438
+ },
439
+ searchTransactionsForNewScheduleSuccess(draft, action) {
440
+ draft.newSchedule.searchTransactions = {
441
+ ...draft.newSchedule.searchTransactions,
442
+ searchResults: action.payload.searchResults,
443
+ fetchState: 'Completed',
444
+ error: undefined,
445
+ };
446
+ },
447
+ searchTransactionsForNewScheduleFailure(draft, action) {
448
+ draft.newSchedule.searchTransactions = {
449
+ ...draft.newSchedule.searchTransactions,
450
+ fetchState: 'Error',
451
+ error: action.payload.status,
452
+ };
453
+ },
454
+ clearSearchTransactionsForNewSchedule(draft) {
455
+ draft.newSchedule.searchTransactions = searchTransactionsInitialState;
456
+ },
457
+ saveNewSchedule: {
458
+ prepare({ scheduleType, }) {
459
+ return { payload: { scheduleType } };
460
+ },
461
+ reducer(draft) {
462
+ draft.newSchedule.saveStatus = {
463
+ fetchState: 'In-Progress',
464
+ error: undefined,
465
+ };
466
+ },
467
+ },
468
+ saveNewScheduleSuccess(draft) {
469
+ draft.newSchedule.saveStatus = {
470
+ fetchState: 'Completed',
471
+ error: undefined,
472
+ };
473
+ },
474
+ saveNewScheduleFailure(draft, action) {
475
+ draft.newSchedule.saveStatus = {
476
+ fetchState: 'Error',
477
+ error: action.payload.status,
478
+ };
479
+ },
371
480
  updateJESchedulesUIState(draft, action) {
372
481
  if (action.payload.sortKey != null) {
373
482
  draft.uiState.sortKey = action.payload.sortKey;
@@ -381,16 +490,27 @@ const expenseAutomationJESchedulesView = createSlice({
381
490
  if (action.payload.scrollPosition != null) {
382
491
  draft.uiState.scrollPosition = action.payload.scrollPosition;
383
492
  }
384
- if (action.payload.selectedMainTab != null) {
385
- draft.uiState.selectedMainTab = action.payload.selectedMainTab;
493
+ if (action.payload.selectedPageTab != null) {
494
+ draft.uiState.selectedPageTab = action.payload.selectedPageTab;
386
495
  }
387
496
  },
497
+ updateJEScheduleTypeFilter(draft, action) {
498
+ draft.uiState.selectedJETypeFilter = action.payload;
499
+ },
500
+ toggleJEPendingGroupCollapsed(draft) {
501
+ draft.uiState.pendingGroupCollapsed =
502
+ !draft.uiState.pendingGroupCollapsed;
503
+ },
504
+ toggleJECreatedGroupCollapsed(draft) {
505
+ draft.uiState.createdGroupCollapsed =
506
+ !draft.uiState.createdGroupCollapsed;
507
+ },
388
508
  clearExpenseAutomationJESchedulesView(draft) {
389
509
  Object.assign(draft, initialState);
390
510
  },
391
511
  },
392
512
  });
393
- export const { clearExpenseAutomationJESchedulesView, clearJeAccountSettingsLocalData, clearJeScheduleLocalData, fetchAccountSettingsListForAccountTypes, fetchJeSchedules, fetchJeSchedulesFailure, fetchJeSchedulesPage, fetchJeSchedulesSuccess, fetchRecommendationForAccountSettings, ignoreRecommendedJeSchedule, ignoreRecommendedJeScheduleFailure, ignoreRecommendedJeScheduleSuccess, initializeAccountSettingsView, initializeJeScheduleLocalData, removeFailedJeScheduleTransactionKey, removeJeScheduleLocalDataById, removeJeScheduleTransactionKey, retryJeSchedule, retryJeScheduleFailure, retryJeScheduleSuccess, saveAccountSettings, saveAccountSettingsFailure, saveAccountSettingsLocalData, saveAccountSettingsSuccess, updateAccountSettingsListForAccountTypes, updateAccountSettingsListForAccountTypesFailure, updateJESchedulesUIState, updateJeScheduleLocalDataById, updateJeScheduleTransactionKeys, updateRecommendationForAccountSettings, updateRecommendationForAccountSettingsFailure, } = expenseAutomationJESchedulesView.actions;
513
+ export const { clearExpenseAutomationJESchedulesView, clearJeAccountSettingsLocalData, clearJeScheduleLocalData, clearSearchTransactionsForNewSchedule, fetchAccountSettingsListForAccountTypes, fetchJeSchedules, fetchJeSchedulesFailure, fetchJeSchedulesPage, fetchJeSchedulesSuccess, fetchRecommendationForAccountSettings, ignoreRecommendedJeSchedule, ignoreRecommendedJeScheduleFailure, ignoreRecommendedJeScheduleSuccess, initializeAccountSettingsView, initializeJeScheduleLocalData, initializeNewSchedule, removeFailedJeScheduleTransactionKey, removeJeScheduleLocalDataById, removeJeScheduleTransactionKey, resetNewScheduleLocalData, retryJeSchedule, retryJeScheduleFailure, retryJeScheduleSuccess, saveAccountSettings, saveAccountSettingsFailure, saveAccountSettingsLocalData, saveAccountSettingsSuccess, saveNewSchedule, saveNewScheduleFailure, saveNewScheduleSuccess, searchTransactionsForNewSchedule, searchTransactionsForNewScheduleFailure, searchTransactionsForNewScheduleSuccess, toggleJECreatedGroupCollapsed, toggleJEPendingGroupCollapsed, updateAccountSettingsListForAccountTypes, updateAccountSettingsListForAccountTypesFailure, updateJESchedulesUIState, updateJEScheduleTypeFilter, updateJeScheduleLocalDataById, updateJeScheduleTransactionKeys, updateNewScheduleLocalData, updateRecommendationForAccountSettings, updateRecommendationForAccountSettingsFailure, } = expenseAutomationJESchedulesView.actions;
394
514
  export default expenseAutomationJESchedulesView.reducer;
395
515
  const doUpdateRecommendationForAccountSettings = (draft, payload) => {
396
516
  const { prepaidExpensesRecommendations, fixedAssetsRecommendations, accruedExpensesRecommendations, } = mapAccountTypeRecommendationPayloadToAccountRecommendationByType(payload);