Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 | import { createContext, memo, useCallback, useContext, useMemo, type ReactElement } from 'react'; import { CalculationStatus, isBeingReviewed, type CalculationRequest, type EngineError, type Statement, } from '@amalia/core/types'; import { useShallowObjectMemo } from '@amalia/ext/react/hooks'; import { useUrlState, type UseUrlStateValue } from '@amalia/ext/react-router-dom'; import { assert } from '@amalia/ext/typescript'; import { useCalculation, type LaunchCalculation } from '@amalia/payout-calculation/statements/components'; import { useStatementByPlanPeriodUser } from '@amalia/payout-calculation/statements/state'; import { getCurrentPeriodInListOfPeriods } from '@amalia/payout-definition/periods/shared'; import { type Period } from '@amalia/payout-definition/periods/types'; import { type Plan } from '@amalia/payout-definition/plans/types'; import { usePeriods, usePlan, usePlanTemplate } from '@amalia/payout-definition/state'; import { type UserContract } from '@amalia/tenants/users/types'; import { useDesignerDrawerContext } from '../drawer/PlanHubRuleDesignerDrawer.context'; import { usePlanHubRuleDesignerContext } from '../PlanHubRuleDesigner.context'; import { type TokenInError } from './rule-designer-compute.types'; import { useTokenInError } from './use-token-in-error'; type RuleDesignerComputeContextType = Pick< ReturnType<typeof useCalculation>, | 'calculationRequest' | 'canCompute' | 'currentlyRunningCalculations' | 'isCurrentStatementComputing' | 'statementsToCompute' | 'stopCalculation' > & { period: Period | null; setPeriodId: UseUrlStateValue<Period['id'] | null>[1]; userId: UserContract['id'] | null; setUserId: UseUrlStateValue<UserContract['id'] | null>[1]; tokenInError: TokenInError | null; statement?: Statement; isStatementLoading: boolean; hasNoStatement: boolean; fetchStatementError?: Error | null; isReviewOngoing?: boolean; error?: EngineError; launchCalculation: LaunchCalculation; }; const RuleDesignerComputeContext = createContext<RuleDesignerComputeContextType | null>(null); export const useRuleDesignerComputeContext = () => { const context = useContext(RuleDesignerComputeContext); assert(context, 'Not in a RuleDesignerComputeContext'); return context; }; interface RuleDesignerComputeContextProviderProps { readonly children: ReactElement; } // If it's the first time assigning someone to a plan that doesn't compute // actual and forecasted at the same time, compute them both for that // specific situation. export const shouldComputeForecast = (plan?: Plan, statement?: Statement | null) => !statement && !!plan && plan.isForecasted && !plan.calculateBothStatements; export const RuleDesignerComputeContextProvider = memo(function RuleDesignerComputeContextProvider({ children, }: RuleDesignerComputeContextProviderProps) { const { planId } = usePlanHubRuleDesignerContext(); const { data: plan } = usePlan(planId); const [periodId, setPeriodId] = useUrlState<Period['id'] | null>('periodId', null); const { periodsList, isSuccess: arePeriodsLoaded } = usePeriods(); const period = useMemo(() => { if (!arePeriodsLoaded || !plan) { return undefined; } if (periodId) { return periodsList.find((p) => p.id === periodId); } return getCurrentPeriodInListOfPeriods(periodsList, plan.frequency, new Date()); }, [periodsList, arePeriodsLoaded, periodId, plan]); const [userId, setUserId] = useUrlState<UserContract['id'] | null>('userId', null); const { data: statement, error: fetchStatementError, isFetching: isStatementLoading, status: statementStatus, } = useStatementByPlanPeriodUser(planId, userId ?? undefined, period?.id); const calculationRequest = useMemo( () => ({ planIds: [planId], userIds: userId ? [userId] : [], periodId: period?.id, // If the user just got assigned to plan, compute achieved first then forecast. shouldComputeForecast: shouldComputeForecast(plan, statement), }) satisfies CalculationRequest, [userId, period, planId, plan, statement], ); const { launchCalculation, lastCalculation, stopCalculation, isCurrentStatementComputing, currentlyRunningCalculations, statementsToCompute, } = useCalculation( calculationRequest, // If the statement doesn't exist yet, provide values, so we can render the CircularLoader // if we're waiting for a statement to be computed for the first time. statement ?? { plan, period, user: userId ? { id: userId } : undefined }, ); const { data: planTemplateWithError } = usePlanTemplate(planId); const error: EngineError | undefined = useMemo(() => { // If the error from the latest computation is applicable to the current statement, show it here. if ( // Last calculation in error lastCalculation?.status === CalculationStatus.ERROR && // Computing exactly one statement lastCalculation.total === 1 && // Of the current user lastCalculation.descriptor.at(0)?.batches.at(0)?.users.at(0)?.id === userId && // And the current period. lastCalculation.descriptor.at(0)?.periodId === period?.id ) { return lastCalculation.errorMetadata ?? undefined; } // Else display error from the statement computation, then from the plan template calculation. return statement?.error ?? planTemplateWithError?.error ?? undefined; }, [lastCalculation, statement, planTemplateWithError, userId, period]); const isReviewOngoing = useMemo(() => (statement ? isBeingReviewed(statement) : undefined), [statement]); const { setAtLeastOneTokenSavedSinceLastComputeFalse } = useDesignerDrawerContext(); const launchCalculationProxy = useCallback<LaunchCalculation>( (...args) => { setAtLeastOneTokenSavedSinceLastComputeFalse(); return launchCalculation(...args); }, [setAtLeastOneTokenSavedSinceLastComputeFalse, launchCalculation], ); const { getTokenInError } = useTokenInError(); const tokenInError = useMemo(() => getTokenInError(error?.context), [getTokenInError, error]); return ( <RuleDesignerComputeContext.Provider value={useShallowObjectMemo({ isStatementLoading, period: period ?? null, setPeriodId, userId, setUserId, hasNoStatement: !statement && statementStatus === 'success', statement: statement ?? undefined, fetchStatementError, tokenInError, isReviewOngoing, error, lastCalculation, launchCalculation: launchCalculationProxy, // Cannot compute if the plan is archived or without choosing a user first. canCompute: !!userId && !plan?.archived, calculationRequest, isCurrentStatementComputing, stopCalculation, currentlyRunningCalculations, statementsToCompute, })} > {children} </RuleDesignerComputeContext.Provider> ); }); |