All files / libs/reporting/plan-dashboards/shared/src/lib/custom-charts generate-custom-chart-custom-report.ts

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

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                                                                                                                                                                                                                                             
import { match } from 'ts-pattern';

import { type Period } from '@amalia/payout-definition/periods/types';
import { PlanIsHiddenQueryChoices, type Plan } from '@amalia/payout-definition/plans/types';
import {
  CustomReportAggregationOperation,
  CustomReportFilterOperator,
  CustomReportSourceIdentifier,
  type CustomReport,
  type CustomReportConfigurationField,
  type CustomReportConfigurationGroupBy,
} from '@amalia/reporting/custom-reports/shared';
import {
  isCombinedChartWidgetConfiguration,
  isKpiChartWidgetConfiguration,
  isTargetVsAchievementChartWidgetConfiguration,
  type PlanDashboardCustomChartWidgetConfiguration,
} from '@amalia/reporting/plan-dashboards/types';
import { type UserContract } from '@amalia/tenants/users/types';

/**
 * Generate a custom report configuration based on the provided chart configuration.
 */
export const generateCustomChartCustomReport = (
  planId: Plan['id'],
  userId: UserContract['id'],
  chartConfiguration: PlanDashboardCustomChartWidgetConfiguration,
  periodIds: Period['id'][],
  canViewHiddenPlans: boolean,
): Pick<CustomReport, 'configuration' | 'dataSourceConfiguration' | 'source'> => ({
  source: CustomReportSourceIdentifier.STATEMENT,
  dataSourceConfiguration: {
    planHiddenStatus: canViewHiddenPlans ? PlanIsHiddenQueryChoices.BOTH : PlanIsHiddenQueryChoices.LIVE,
  },
  configuration: {
    sorts: [
      {
        joins: [],
        direction: 'DESC',
        identifier: 'periodStartDate',
      },
    ],

    // Join statement forecast when there is at least one kpi using forecasted values.
    joins: [
      match(chartConfiguration)
        .when(isKpiChartWidgetConfiguration, (config) =>
          config.series.yAxis.joins?.includes('statementAchievedToForecast'),
        )
        .when(isCombinedChartWidgetConfiguration, (config) =>
          config.seriesList.some((series) => series.yAxis.joins?.includes('statementAchievedToForecast')),
        )
        .when(isTargetVsAchievementChartWidgetConfiguration, () => false)
        .exhaustive()
        ? [{ id: 'statementAchievedToForecast', type: 'AUTO' }]
        : null,
    ].filter(Boolean),

    fields: match<typeof chartConfiguration, CustomReportConfigurationField[]>(chartConfiguration)
      .when(isCombinedChartWidgetConfiguration, (config) => [
        { identifier: 'periodStartDate' },
        ...config.seriesList.map((series) => series.yAxis),
      ])
      .when(isKpiChartWidgetConfiguration, (config) => [config.series.yAxis])
      .when(isTargetVsAchievementChartWidgetConfiguration, (config) =>
        [
          {
            identifier: 'periodStartDate',
            aggregation: { operation: CustomReportAggregationOperation.min },
          },
          config.series.achievement,
          config.series.target,
          config.series.earningsAt100Percent,
        ].filter(Boolean),
      )
      .exhaustive(),

    groupBys: match<typeof chartConfiguration, CustomReportConfigurationGroupBy[]>(chartConfiguration)
      .when(
        (config) => isKpiChartWidgetConfiguration(config) || isTargetVsAchievementChartWidgetConfiguration(config),
        () => [{ identifier: 'userId' }],
      )
      .when(isCombinedChartWidgetConfiguration, () => [])
      .exhaustive(),

    filters: [
      // Only get the statements for the user on this plan.
      {
        ors: [
          {
            values: [planId],
            operator: CustomReportFilterOperator.IN,
            identifier: 'planId',
          },
        ],
      },
      {
        ors: [
          {
            values: [userId],
            operator: CustomReportFilterOperator.IN,
            identifier: 'userId',
          },
        ],
      },
      // Filter periods based on the queried timeframe.
      {
        ors: [
          {
            values: periodIds,
            operator: CustomReportFilterOperator.IN,
            identifier: 'periodId',
          },
        ],
      },
    ],
  },
});