All files / libs/payout-definition/state/src/lib/rules rule-plan-assignment.queries.ts

0% Statements 0/58
0% Branches 0/1
0% Functions 0/1
0% Lines 0/58

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                                                                                                                     
import { useIsFetching, useIsMutating, useQuery, useQueryClient } from '@tanstack/react-query';
import { useIntl } from 'react-intl';

import { useSnackbars } from '@allshares/studio-design-system';
import { useMutation } from '@amalia/ext/react-query';
import { type Plan, type Rule } from '@amalia/payout-definition/plans/types';

import { plansForecastQueryKeys } from '../plan-forecast/plan-forecast.keys';
import { plansQueryKeys, rulesV2MutationKeys, rulesV2QueryKeys } from '../queries.keys';

import { RulePlanAssignmentApiClient } from './rule-plan-assignment.api-client';

export const useRulePlanConfigurations = (planId?: Plan['id']) =>
  useQuery({
    queryKey: rulesV2QueryKeys.configurations.ofPlan.list(planId!),
    queryFn: () => RulePlanAssignmentApiClient.getRuleConfigurations(planId!),
    enabled: !!planId,
  });

export const useRulePlanConfiguration = (planId: Plan['id'], ruleId: Rule['id']) =>
  useQuery({
    queryKey: rulesV2QueryKeys.configurations.ofPlan.details(planId, ruleId),
    queryFn: () => RulePlanAssignmentApiClient.getRuleConfiguration(planId, ruleId),
  });

export const useUpdateRuleAssignment = ({ ignoreSnack = false }: { ignoreSnack?: boolean } = {}) => {
  const queryClient = useQueryClient();
  const { snackSuccess } = useSnackbars();
  const { formatMessage } = useIntl();

  return useMutation({
    mutationKey: rulesV2MutationKeys.configurations.updateRuleAssignment(),
    mutationFn: RulePlanAssignmentApiClient.updateRuleAssignment,
    onSuccess: async ({ ruleAssignment: { planId } }) => {
      if (!ignoreSnack) {
        snackSuccess(formatMessage({ defaultMessage: 'Rule updated successfully.' }));
      }

      await Promise.all([
        queryClient.invalidateQueries({ queryKey: rulesV2QueryKeys.configurations.all() }),
        queryClient.invalidateQueries({ queryKey: plansForecastQueryKeys.details(planId) }),
        queryClient.invalidateQueries({ queryKey: plansQueryKeys.template.ofPlan(planId) }),
      ]);
    },
  });
};

export const useIsRuleAssignmentLoading = (planId: string): boolean => {
  const isFetching = useIsFetching({
    queryKey: rulesV2QueryKeys.configurations.ofPlan.all(planId),
  });

  const isMutating = useIsMutating({
    mutationKey: rulesV2MutationKeys.configurations.updateRuleAssignment(),
  });

  return !!isFetching || !!isMutating;
};