All files / libs/reporting/dashboards/components/src/lib/home-legacy DashboardPage.tsx

100% Statements 29/29
85.71% Branches 30/35
100% Functions 5/5
100% Lines 27/27

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 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376                                                                                            15x           15x 47x 47x 47x 47x 47x   47x   47x 47x   47x                                   47x           47x               47x     47x             47x 25x           25x 15x     10x 36x 10x   10x     47x   25x         47x             47x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import { css, useTheme } from '@emotion/react';
import { isEmpty } from 'lodash-es';
import { Fragment, memo, useMemo } from 'react';
import { FormattedMessage, useIntl } from 'react-intl';
import { generatePath, useLocation } from 'react-router-dom';
 
import {
  Breadcrumbs,
  ButtonLink,
  Filters,
  Group,
  PageHeader,
  Stack,
  Typography,
  type FilterSelectOption,
} from '@allshares/studio-design-system';
import { routes } from '@amalia/core/routes';
import { convertTimestampToUtcDate } from '@amalia/ext/dates';
import { dayjs } from '@amalia/ext/dayjs';
import { useStateInStorage } from '@amalia/ext/react/hooks';
import { canViewDashboardsV2 } from '@amalia/kernel/auth/shared';
import { useAbilityContext, useAuthenticatedContext } from '@amalia/kernel/auth/state';
import { type CurrencyValue } from '@amalia/kernel/monetary/types';
import { PeriodSelector } from '@amalia/payout-definition/periods/components';
import { RelativePeriodKeyword, type Period } from '@amalia/payout-definition/periods/types';
import { useOverTimeData } from '@amalia/reporting/dashboards/state';
import { DashboardBreadcrumbSelector } from '@amalia/reporting/dashboards-v2/components';
import { DASHBOARD_LEGACY_ID } from '@amalia/reporting/dashboards-v2/types';
import { useCurrentCompany } from '@amalia/tenants/companies/state';
import { useAuthorizedProfiles } from '@amalia/tenants/users/profile/state';
import { UserRole } from '@amalia/tenants/users/types';
 
import { useFillCurrentYearPeriodsRecords } from '../payout-and-performance-chart/chart/hooks/useFillCurrentYearPeriodsRecords';
 
import { BenchmarkByPlanWidget } from './benchmark-by-plan-widget/BenchmarkByPlanWidget';
import { BenchmarkByRuleWidget } from './benchmark-by-rule-widget/BenchmarkByRuleWidget';
import { DashboardKpi } from './dashboard-kpi/DashboardKpi';
import { EarningsCards } from './earnings-card/EarningsCard';
import { LeaderBoardWidget } from './leaderboard-widget/LeaderBoardWidget';
import { PaymentsWidget } from './payments-widget/PaymentsWidget';
import { PayoutAndPerformanceChartWidget } from './payout-and-performance-chart-widget/PayoutAndPerformanceChartWidget';
import { type PayoutMode } from './payout-and-performance-chart-widget/PayoutAndPerformanceChartWidget.types';
import { useHomepageFilters } from './useHomepageFilters';
import { usePlanKpis } from './usePlanKpis';
import { UsersBadgesWidget } from './users-badges-widget/UsersBadgesWidget';
 
const PAYOUT_MODE_LOCAL_STORAGE_KEY = 'payout-and-performance-chart-payout-mode';
 
type DashboardPageProps = {
  readonly currentPeriod?: Period;
};
 
export const DashboardPage = memo(function DashboardPage({ currentPeriod }: DashboardPageProps) {
  const theme = useTheme();
  const ability = useAbilityContext();
  const { data: company } = useCurrentCompany();
  const { authenticatedContext } = useAuthenticatedContext();
  const { pathname } = useLocation();
 
  const isHomePage = pathname === routes.HOME;
 
  const { formatMessage } = useIntl();
  const { data: allUsers } = useAuthorizedProfiles();
 
  const [payoutMode, setPayoutMode] = useStateInStorage<PayoutMode>(
    PAYOUT_MODE_LOCAL_STORAGE_KEY,
    RelativePeriodKeyword.CURRENT_YEAR,
  );
 
  const {
    userOptions,
    teamOptions,
    planOptions,
    usersSelected,
    plansSelected,
    teamsSelected,
    period,
    currentPeriodDate,
    handlePlansChange,
    handleTeamsChange,
    handleUsersChange,
    onPeriodChange,
  } = useHomepageFilters(authenticatedContext, currentPeriod);
 
  const {
    data: overtime,
    isLoading: isLoadingOvertime,
    isError: isErrorLoading,
  } = useOverTimeData({
    periodIds: [payoutMode],
    referenceDate: currentPeriodDate,
    userIds: usersSelected,
    planIds: plansSelected,
    teamIds: teamsSelected,
  });
 
  const { kpi1, kpi2, isLoadingPlanKpis } = usePlanKpis(period?.id, usersSelected, plansSelected, teamsSelected);
 
  /* Admin and managers can see a global view with plans performance, whereas employees will see a personal view */
  const showGlobalAchievementView = [
    UserRole.ADMIN,
    UserRole.MANAGER,
    UserRole.READ_ONLY_ADMIN,
    UserRole.READ_ONLY_MANAGER,
  ].includes(authenticatedContext.user.role);
 
  const [currentPeriodEarning, previousPeriodEarning] = useMemo(() => {
    const defaultValue = {
      ruleMetricPeriod__month: period?.endDate
        ? dayjs.utc(convertTimestampToUtcDate(period.endDate)).format('MM/YYYY')
        : period?.name,
      ruleMetricPayment__value: { value: 0, symbol: company.currency } as CurrencyValue,
    };
    if (!period || !overtime) {
      return [defaultValue, defaultValue];
    }
 
    const nameOfLastMonthOfPeriod = dayjs.utc(convertTimestampToUtcDate(period.endDate)).format('MM/YYYY');
    const currentIndex = overtime.records.findIndex((r) => r.ruleMetricPeriod__month === nameOfLastMonthOfPeriod);
    const previousIndex = currentIndex > 1 ? currentIndex - 1 : 0;
 
    return [overtime.records[currentIndex] || defaultValue, overtime.records[previousIndex] || defaultValue];
  }, [company, overtime, period]);
 
  const currency = useMemo(
    () =>
      overtime?.records.filter(Boolean).find((r) => !!r.ruleMetricPayment__value?.symbol)?.ruleMetricPayment__value
        ?.symbol || company.currency,
    [overtime, company.currency],
  );
 
  const { statistics, isRecordActiveFn } = useFillCurrentYearPeriodsRecords({
    statistics: overtime,
    frequency: period?.frequency,
    period,
    enabled: payoutMode === RelativePeriodKeyword.CURRENT_YEAR,
  });
 
  return (
    <Fragment>
      <PageHeader>
        {!currentPeriod && (
          <PageHeader.Row
            left={
              <Breadcrumbs
                back={
                  canViewDashboardsV2(ability) ? (
                    <Breadcrumbs.BackLink
                      label={formatMessage({ defaultMessage: 'Go back to dashboard list' })}
                      to={generatePath(routes.DASHBOARDS_V2)}
                    />
                  ) : undefined
                }
              >
                <DashboardBreadcrumbSelector dashboardId={DASHBOARD_LEGACY_ID} />
 
                <PeriodSelector
                  frequency={authenticatedContext.user.company.statementFrequency}
                  timestamp={period?.startDate ?? 0}
                  onPeriodChange={onPeriodChange}
                />
              </Breadcrumbs>
            }
          />
        )}
        <PageHeader.Row
          left={
            <Typography variant="heading1Bold">
              <FormattedMessage defaultMessage="Payout Overview" />
            </Typography>
          }
          right={
            !!isHomePage && (
              <ButtonLink
                to={generatePath(routes.DASHBOARD)}
                variant="primary-light"
              >
                <FormattedMessage defaultMessage="View in dashboard" />
              </ButtonLink>
            )
          }
        />
        <PageHeader.Row
          left={
            <Filters>
              <Filters.FilterSelect<FilterSelectOption<string>, true>
                isMultiple
                isStatic
                allSelectedLabel={formatMessage({ defaultMessage: 'All users' })}
                id="users"
                label={formatMessage({ defaultMessage: 'Users' })}
                options={userOptions}
                title={formatMessage({ defaultMessage: 'Filter users' })}
                value={usersSelected}
                onChange={handleUsersChange}
              />
              <Filters.FilterSelect<FilterSelectOption<string>, true>
                isMultiple
                isStatic
                allSelectedLabel={formatMessage({ defaultMessage: 'All plans' })}
                disabled={false}
                id="plan"
                label={formatMessage({ defaultMessage: 'Plan' })}
                options={planOptions}
                title={formatMessage({ defaultMessage: 'Filter plans' })}
                value={plansSelected}
                onChange={handlePlansChange}
              />
              <Filters.FilterSelect<FilterSelectOption<string>, true>
                isMultiple
                isStatic
                allSelectedLabel={formatMessage({ defaultMessage: 'All teams' })}
                disabled={false}
                id="team"
                label={formatMessage({ defaultMessage: 'Team' })}
                options={teamOptions}
                title={formatMessage({ defaultMessage: 'Filter teams' })}
                value={teamsSelected}
                onChange={handleTeamsChange}
              />
            </Filters>
          }
        />
      </PageHeader>
 
      <Stack
        gap={16}
        css={css`
          margin-top: 24px;
        `}
      >
        <Group
          wrap
          gap={16}
        >
          <Stack
            gap={16}
            css={css`
              min-width: 700px;
              flex: 2;
            `}
          >
            <Group
              gap={16}
              justify="space-between"
              css={css`
                height: 150px;
                > * {
                  flex: 1;
                }
              `}
            >
              <div>
                <EarningsCards
                  currentPeriodEarning={currentPeriodEarning.ruleMetricPayment__value}
                  period={currentPeriodEarning.ruleMetricPeriod__month}
                  previousPeriodEarning={previousPeriodEarning.ruleMetricPayment__value}
                  user={authenticatedContext.user}
                />
              </div>
 
              <div>
                <DashboardKpi
                  color={theme.ds.colors.primary[400]}
                  label={kpi1.label}
                  loading={isLoadingPlanKpis}
                  value={kpi1.value}
                  emptyMessage={
                    isEmpty(plansSelected)
                      ? formatMessage({ defaultMessage: 'Filter on a plan to have this data' })
                      : undefined
                  }
                />
              </div>
 
              <div>
                <DashboardKpi
                  color={theme.ds.colors.primary[200]}
                  label={kpi2.label}
                  loading={isLoadingPlanKpis}
                  value={kpi2.value}
                  emptyMessage={
                    isEmpty(plansSelected)
                      ? formatMessage({ defaultMessage: 'Filter on a plan to have this data' })
                      : undefined
                  }
                />
              </div>
            </Group>
 
            {!!showGlobalAchievementView && (
              <div>
                <BenchmarkByPlanWidget
                  period={period}
                  selectedPlanIds={plansSelected}
                  selectedTeamIds={teamsSelected}
                  selectedUserIds={usersSelected}
                />
              </div>
            )}
 
            <div
              css={css`
                min-height: 450px;
              `}
            >
              <PayoutAndPerformanceChartWidget
                currency={currency}
                isErrorLoading={isErrorLoading}
                isLoading={isLoadingOvertime}
                isRecordActiveFn={isRecordActiveFn}
                payoutMode={payoutMode}
                setPayoutMode={setPayoutMode}
                statistics={statistics ?? undefined}
              />
            </div>
          </Stack>
 
          {!!showGlobalAchievementView && !!period && (
            <div
              css={css`
                flex: 1;
              `}
            >
              <LeaderBoardWidget
                allUsers={allUsers}
                periodId={period.id}
                selectedPlanIds={plansSelected}
                selectedTeamIds={teamsSelected}
                selectedUserIds={usersSelected}
              />
            </div>
          )}
 
          {!showGlobalAchievementView && (
            <div
              css={css`
                flex: 1;
              `}
            >
              <BenchmarkByRuleWidget
                selectedPlanIds={plansSelected}
                selectedTeamIds={teamsSelected}
                user={authenticatedContext.user}
              />
            </div>
          )}
        </Group>
 
        <div
          css={css`
            &:empty {
              display: none;
            }
          `}
        >
          <UsersBadgesWidget
            period={period}
            selectedPlanIds={plansSelected}
            selectedUsersIds={usersSelected}
          />
        </div>
 
        <div>
          <PaymentsWidget
            periodId={period?.id}
            selectedPlanIds={plansSelected}
            selectedTeamIds={teamsSelected}
            selectedUserIds={usersSelected}
          />
        </div>
      </Stack>
    </Fragment>
  );
});