Skip to content

Commit

Permalink
fix: some refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
9sneha-n committed Oct 3, 2024
1 parent b8a56d7 commit 17db20c
Show file tree
Hide file tree
Showing 7 changed files with 104 additions and 103 deletions.
100 changes: 43 additions & 57 deletions src/data/repositories/PerformanceOverviewD2Repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import _ from "../../domain/entities/generic/Collection";
import { Future } from "../../domain/entities/generic/Future";
import {
eventTrackerCountsIndicatorMap,
INDICATORS_717_PERFORMANCE,
PERFORMANCE_METRICS_717_IDS,
IndicatorsId,
} from "./consts/PerformanceOverviewConstants";
import moment from "moment";
Expand All @@ -21,17 +21,11 @@ import {
HazardNames,
PerformanceOverviewMetrics,
DiseaseNames,
PerformanceMetrics717,
} from "../../domain/entities/disease-outbreak-event/PerformanceOverviewMetrics";
import { AlertSynchronizationData } from "../../domain/entities/alert/AlertData";
import { OrgUnit } from "../../domain/entities/OrgUnit";

export type Indicator717PerformanceBaseAttrs = {
id: string;
name: string;
type: "count" | "percent";
value: number;
};

const formatDate = (date: Date): string => {
const year = date.getFullYear();
const month = ("0" + (date.getMonth() + 1)).slice(-2);
Expand All @@ -40,7 +34,6 @@ const formatDate = (date: Date): string => {
};

const DEFAULT_END_DATE: string = formatDate(new Date());

const DEFAULT_START_DATE = "2000-01-01";

export class PerformanceOverviewD2Repository implements PerformanceOverviewRepository {
Expand Down Expand Up @@ -151,27 +144,26 @@ export class PerformanceOverviewD2Repository implements PerformanceOverviewRepos
diseaseOutbreakEvents: DiseaseOutbreakEventBaseAttrs[]
): FutureData<PerformanceOverviewMetrics[]> {
return apiToFuture(
this.api.get<AnalyticsResponse>(
`/analytics/enrollments/query/${RTSL_ZEBRA_PROGRAM_ID}`,
{
enrollmentDate: "LAST_12_MONTHS,THIS_MONTH",
dimension: [
IndicatorsId.suspectedDisease,
IndicatorsId.hazardType,
IndicatorsId.event,
IndicatorsId.era1,
IndicatorsId.era2,
IndicatorsId.era3,
IndicatorsId.era4,
IndicatorsId.era5,
IndicatorsId.era6,
IndicatorsId.era7,
IndicatorsId.detect7d,
IndicatorsId.notify1d,
IndicatorsId.respond7d,
],
}
)
this.api.analytics.getEnrollmentsQuery({
programId: RTSL_ZEBRA_PROGRAM_ID,
dimension: [
IndicatorsId.suspectedDisease,
IndicatorsId.hazardType,
IndicatorsId.event,
IndicatorsId.era1,
IndicatorsId.era2,
IndicatorsId.era3,
IndicatorsId.era4,
IndicatorsId.era5,
IndicatorsId.era6,
IndicatorsId.era7,
IndicatorsId.detect7d,
IndicatorsId.notify1d,
IndicatorsId.respond7d,
],
startDate: DEFAULT_START_DATE,
endDate: DEFAULT_END_DATE,
})
).flatMap(indicatorsProgramFuture => {
const mappedIndicators =
indicatorsProgramFuture?.rows.map((row: string[]) =>
Expand Down Expand Up @@ -216,43 +208,37 @@ export class PerformanceOverviewD2Repository implements PerformanceOverviewRepos
});
}

get717Performance(): FutureData<Indicator717PerformanceBaseAttrs[]> {
get717Performance(): FutureData<PerformanceMetrics717[]> {
const transformData = (
data: string[][],
indicators717Performance: typeof INDICATORS_717_PERFORMANCE
): Indicator717PerformanceBaseAttrs[] => {
return data.flatMap(([id, , value]) => {
const indicator = indicators717Performance.find(d => d.id === id);
if (!indicator || !value) {
return [];
}

// Ensure the type is either 'count' or 'percent'
const type: "count" | "percent" =
indicator.type === "count" || indicator.type === "percent"
? indicator.type
: "count"; // Default to 'count' if type is not valid

return [
{
performanceMetric717Response: string[][],
indicators717Performance: PerformanceMetrics717[]
): PerformanceMetrics717[] => {
return _(
performanceMetric717Response.map(([id, value]) => {
const indicator = indicators717Performance.find(d => d.id === id);
if (!indicator || !value) {
return undefined;
}
return {
...indicator,
value: parseFloat(value),
type, // Set the valid type here with narrowed types
},
];
});
type: indicator.type,
};
})
)
.compact()
.value();
};

return apiToFuture(
this.api.analytics.get({
dimension: [
`dx:${INDICATORS_717_PERFORMANCE.map(({ id }) => id).join(";")}`,
"pe:THIS_YEAR",
],
dimension: [`dx:${PERFORMANCE_METRICS_717_IDS.map(({ id }) => id).join(";")}`],
startDate: DEFAULT_START_DATE,
endDate: DEFAULT_END_DATE,
includeMetadataDetails: true,
})
).map(res => {
return transformData(res.rows, INDICATORS_717_PERFORMANCE) || [];
return transformData(res.rows, PERFORMANCE_METRICS_717_IDS) || [];
});
}

Expand Down
3 changes: 2 additions & 1 deletion src/data/repositories/consts/PerformanceOverviewConstants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
DiseaseNames,
HazardNames,
IncidentStatus,
PerformanceMetrics717,
} from "../../../domain/entities/disease-outbreak-event/PerformanceOverviewMetrics";
import { Id } from "../../../domain/entities/Ref";

Expand Down Expand Up @@ -265,7 +266,7 @@ export const eventTrackerCountsIndicatorMap: EventTrackerCountIndicator[] = [
{ id: "gRcZNqpKyYg", type: "hazard", name: "Environmental", incidentStatus: "Respond" },
];

export const INDICATORS_717_PERFORMANCE = [
export const PERFORMANCE_METRICS_717_IDS: PerformanceMetrics717[] = [
{ id: "VWazDAQ15Uw", name: "detection", type: "percent" }, // % of number of alerts that were detected within 7 days of date of emergence
{ id: "jnJHR2D0cN3", name: "detection", type: "count" }, // Number of alerts notified to public health authorities within 1 day of detection

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,10 @@ type HazardCounts = BaseCounts & {
};

export type TotalCardCounts = DiseaseCounts | HazardCounts;

export type PerformanceMetrics717 = {
id: string;
name: string;
type: "count" | "percent";
value?: number;
};
4 changes: 2 additions & 2 deletions src/domain/repositories/PerformanceOverviewRepository.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { FutureData } from "../../data/api-futures";
import { Indicator717PerformanceBaseAttrs } from "../../data/repositories/PerformanceOverviewD2Repository";
import { DiseaseOutbreakEventBaseAttrs } from "../entities/disease-outbreak-event/DiseaseOutbreakEvent";
import {
TotalCardCounts,
PerformanceOverviewMetrics,
PerformanceMetrics717,
} from "../entities/disease-outbreak-event/PerformanceOverviewMetrics";

export interface PerformanceOverviewRepository {
Expand All @@ -16,5 +16,5 @@ export interface PerformanceOverviewRepository {
multiSelectFilters?: Record<string, string[]>,
dateRangeFilter?: string[]
): FutureData<TotalCardCounts[]>;
get717Performance(): FutureData<Indicator717PerformanceBaseAttrs[]>;
get717Performance(): FutureData<PerformanceMetrics717[]>;
}
4 changes: 2 additions & 2 deletions src/domain/usecases/Get717PerformanceUseCase.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { FutureData } from "../../data/api-futures";
import { Indicator717PerformanceBaseAttrs } from "../../data/repositories/PerformanceOverviewD2Repository";
import { PerformanceMetrics717 } from "../entities/disease-outbreak-event/PerformanceOverviewMetrics";
import { PerformanceOverviewRepository } from "../repositories/PerformanceOverviewRepository";

export class Get717PerformanceUseCase {
Expand All @@ -9,7 +9,7 @@ export class Get717PerformanceUseCase {
}
) {}

public execute(): FutureData<Indicator717PerformanceBaseAttrs[]> {
public execute(): FutureData<PerformanceMetrics717[]> {
return this.options.performanceOverviewRepository.get717Performance();
}
}
2 changes: 1 addition & 1 deletion src/webapp/pages/dashboard/DashboardPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export const DashboardPage: React.FC = React.memo(() => {
editRiskAssessmentColumns,
} = usePerformanceOverview();

const { performanceIndicators } = use717Performance(multiSelectFilters);
const { performanceIndicators } = use717Performance();
const { cardCounts } = useCardCounts(
singleSelectFilters,
multiSelectFilters,
Expand Down
87 changes: 47 additions & 40 deletions src/webapp/pages/dashboard/use717Performance.ts
Original file line number Diff line number Diff line change
@@ -1,66 +1,73 @@
import { useEffect, useState } from "react";
import { useCallback, useEffect, useState } from "react";
import { useAppContext } from "../../contexts/app-context";
import _ from "../../../domain/entities/generic/Collection";
import { StatsCardProps } from "../../components/stats-card/StatsCard";
import { Indicator717PerformanceBaseAttrs } from "../../../data/repositories/PerformanceOverviewD2Repository";
import { PerformanceMetrics717 } from "../../../domain/entities/disease-outbreak-event/PerformanceOverviewMetrics";

type CardColors = StatsCardProps["color"];
export type PerformanceIndicator717 = {
performanceIndicators: {
title: string;
percent: number;
count: number;
color: StatsCardProps["color"];
color: CardColors;
}[];
isLoading: boolean;
};

export type Order = { name: string; direction: "asc" | "desc" };

export function use717Performance(filters: Record<string, string[]>): PerformanceIndicator717 {
export function use717Performance(): PerformanceIndicator717 {
const { compositionRoot } = useAppContext();

const [performanceIndicators, setPerformanceIndicators] = useState<
PerformanceIndicator717["performanceIndicators"]
>([]);
const [isLoading, setIsLoading] = useState(false);
const transformData = (performanceIndicators: Indicator717PerformanceBaseAttrs[]) => {
const performanceIndicatorsByName = _(performanceIndicators).reduce(
(acc: Record<string, typeof performanceIndicators>, indicator) => {
const key = indicator.name;
const existingGroup = acc[key] || [];
acc[key] = [...existingGroup, indicator];
return acc;
},
{} as Record<string, typeof performanceIndicators>
);
return Object.entries(performanceIndicatorsByName).map(([key, values]) => {
const percentObj = values.find(item => item.type === "percent");
const countObj = values.find(item => item.type === "count");

const percent = percentObj ? percentObj.value : 0;
const count = countObj ? countObj.value : 0;
const getColor = useCallback((key: string, percent: number): CardColors => {
if (key === "allTargets") {
return "grey";
} else if (percent >= 50) {
return "green";
} else if (percent > 0) {
return "red";
}
return "normal";
}, []);

let color: "green" | "red" | "grey" | "normal" | undefined;
if (key === "allTargets") {
color = "grey";
} else if (percent >= 50) {
color = "green";
} else if (percent > 0) {
color = "red";
}
const transformData = useCallback(
(performanceIndicators: PerformanceMetrics717[]) => {
const performanceIndicatorsByName = _(performanceIndicators).reduce(
(acc: Record<string, typeof performanceIndicators>, indicator) => {
const key = indicator.name;
const existingGroup = acc[key] || [];
acc[key] = [...existingGroup, indicator];
return acc;
},
{} as Record<string, typeof performanceIndicators>
);
return Object.entries(performanceIndicatorsByName).map(([key, values]) => {
const percentObj = values.find(item => item.type === "percent");
const countObj = values.find(item => item.type === "count");

const title = key
.replace(/([A-Z])/g, match => ` ${match}`)
.replace(/^./, match => match.toUpperCase())
.trim();
return {
title: title,
percent: percent,
count: count,
color: color,
};
});
};
const percent = percentObj?.value ?? 0;
const count = countObj?.value ?? 0;

const title = key
.replace(/([A-Z])/g, match => ` ${match}`)
.replace(/^./, match => match.toUpperCase())
.trim();
return {
title: title,
percent: percent,
count: count,
color: getColor(key, percent),
};
});
},
[getColor]
);

useEffect(() => {
setIsLoading(true);
Expand All @@ -74,7 +81,7 @@ export function use717Performance(filters: Record<string, string[]>): Performanc
setIsLoading(false);
}
);
}, [compositionRoot.performanceOverview.get717Performance, filters]);
}, [compositionRoot.performanceOverview.get717Performance, transformData]);

return {
performanceIndicators,
Expand Down

0 comments on commit 17db20c

Please sign in to comment.