Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TM-1734] Projects in v3. #930

Merged
merged 14 commits into from
Feb 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ When adding a new **service** app to the v3 API:
* Follow directions below for all namespaces and resources in the new service

When adding a new **namespace** to the V3 API:
* In `geneated/v3/utils.ts`, add namespace -> service URL mapping to `V3_NAMESPACES`
* In `generated/v3/utils.ts`, add namespace -> service URL mapping to `V3_NAMESPACES`

When adding a new **resource** to the v3 API:
* The resource needs to be specified in shape of the redux API store. In `apiSlice.ts`, add the new
Expand Down
46 changes: 16 additions & 30 deletions src/admin/apiProvider/dataProviders/projectDataProvider.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,36 @@
import { DataProvider } from "react-admin";
import { DataProvider, HttpError } from "react-admin";

import { loadFullProject, loadProjectIndex } from "@/connections/Entity";
import {
DeleteV2AdminProjectsUUIDError,
fetchDeleteV2AdminProjectsUUID,
fetchGetV2AdminProjects,
fetchGetV2AdminProjectsMulti,
fetchGetV2ENTITYUUID,
GetV2AdminProjectsError,
GetV2AdminProjectsMultiError,
GetV2ENTITYUUIDError
GetV2AdminProjectsMultiError
} from "@/generated/apiComponents";

import { getFormattedErrorForRA } from "../utils/error";
import { apiListResponseToRAListResult, raListParamsToQueryParams } from "../utils/listing";

const projectSortableList = ["name", "organisation_name", "planting_start_date"];
import { entitiesListResult, raConnectionProps } from "../utils/listing";

// @ts-ignore
export const projectDataProvider: DataProvider = {
// @ts-expect-error until we can get the whole DataProvider on Project DTOs
async getList(_, params) {
try {
const response = await fetchGetV2AdminProjects({
queryParams: raListParamsToQueryParams(params, projectSortableList)
});

return apiListResponseToRAListResult(response);
} catch (err) {
throw getFormattedErrorForRA(err as GetV2AdminProjectsError);
const connection = await loadProjectIndex(raConnectionProps(params));
if (connection.fetchFailure != null) {
throw new HttpError(connection.fetchFailure.message, connection.fetchFailure.statusCode);
}

return entitiesListResult(connection);
},

// @ts-ignore
// @ts-expect-error until we can get the whole DataProvider on Project DTOs
async getOne(_, params) {
try {
const response = await fetchGetV2ENTITYUUID({
pathParams: {
entity: "projects",
uuid: params.id
}
});

// @ts-ignore
return { data: { ...response.data, id: response.data.uuid } };
} catch (err) {
throw getFormattedErrorForRA(err as GetV2ENTITYUUIDError);
const { entity: project, fetchFailure } = await loadFullProject({ uuid: params.id });
if (fetchFailure != null) {
throw new HttpError(fetchFailure.message, fetchFailure.statusCode);
}

return { data: { ...project, id: project!.uuid } };
},

// @ts-ignore
Expand Down
22 changes: 22 additions & 0 deletions src/admin/apiProvider/utils/listing.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { GetListParams, GetListResult } from "react-admin";

import { EntityIndexConnection, EntityIndexConnectionProps, EntityLightDto } from "@/connections/Entity";

interface ListQueryParams extends Record<string, unknown> {
search?: string;
filter?: string;
Expand All @@ -16,6 +18,21 @@ const getFilterKey = (original: string, replace?: { key: string; replaceWith: st
return replace.replaceWith;
};

export const raConnectionProps = (params: GetListParams) => {
const queryParams: EntityIndexConnectionProps = {
pageSize: params.pagination.perPage,
pageNumber: params.pagination.page,
filter: params.filter
};

if (params.sort.field != null) {
queryParams.sortField = params.sort.field;
queryParams.sortDirection = (params.sort.order as "ASC" | "DESC") ?? "ASC";
}

return queryParams;
};

export const raListParamsToQueryParams = (
params: GetListParams,
sortableList?: string[],
Expand Down Expand Up @@ -61,6 +78,11 @@ interface ApiListResponse {
meta?: any;
}

export const entitiesListResult = <T extends EntityLightDto>({ entities, indexTotal }: EntityIndexConnection<T>) => ({
data: entities?.map(entity => ({ ...entity, id: entity.uuid })),
total: indexTotal
});

export const apiListResponseToRAListResult = (response: ApiListResponse): GetListResult => {
return {
data: response?.data?.map(item => ({ ...item, id: item.uuid })) || [],
Expand Down
5 changes: 4 additions & 1 deletion src/admin/components/Actions/ShowActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,10 @@ const ShowActions = ({
className="!text-sm !font-semibold !capitalize lg:!text-base wide:!text-md"
onClick={() => toggleTestStatus(record)}
>
<Icon className="h-5 w-5" name={record?.is_test ? IconNames.SORT_DOWN : IconNames.SORT_UP} />
<Icon
className="h-5 w-5"
name={record?.is_test || record?.isTest ? IconNames.SORT_DOWN : IconNames.SORT_UP}
/>
</Button>
)}
{canEdit && hasDelete && (
Expand Down
25 changes: 16 additions & 9 deletions src/admin/components/Dialogs/StatusChangeModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
usePostV2AdminENTITYUUIDReminder,
usePutV2AdminENTITYUUIDSTATUS
} from "@/generated/apiComponents";
import ApiSlice, { RESOURCES, ResourceType } from "@/store/apiSlice";
import { optionToChoices } from "@/utils/options";

interface StatusChangeModalProps extends DialogProps {
Expand All @@ -44,24 +45,24 @@ const StatusChangeModal = ({ handleClose, status, ...dialogProps }: StatusChange
const { openNotification } = useNotificationContext();
const t = useT();

const resourceName = (() => {
const [resourceName, v3Resource] = useMemo(() => {
switch (resource as keyof typeof modules) {
case "project":
return "projects";
return ["projects", "projects"];
case "site":
return "sites";
return ["sites", "sites"];
case "nursery":
return "nurseries";
return ["nurseries", "nurseries"];
case "projectReport":
return "project-reports";
return ["project-reports", "projectReports"];
case "siteReport":
return "site-reports";
return ["site-reports", "siteReports"];
case "nurseryReport":
return "nursery-reports";
return ["nursery-reports", "nurseryReports"];
default:
return resource;
return [resource, resource];
}
})();
}, [resource]);

const dialogTitle = (() => {
let name;
Expand Down Expand Up @@ -124,6 +125,12 @@ const StatusChangeModal = ({ handleClose, status, ...dialogProps }: StatusChange

const { mutateAsync, isLoading } = usePutV2AdminENTITYUUIDSTATUS({
onSuccess: () => {
const type = v3Resource as ResourceType;
if (RESOURCES.includes(type)) {
// Temporary until the entity update goes through v3. Then the prune isn't needed, and the
// refetch() will pull the updated resource from the store without an API request.
ApiSlice.pruneCache(type, [record.id]);
}
refetch();
}
});
Expand Down
7 changes: 3 additions & 4 deletions src/admin/components/Fields/FrameworkField.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import { FC } from "react";
import { FunctionField } from "react-admin";

import { useFrameworkChoices } from "@/constants/options/frameworks";

const FrameworkField: FC = () => {
const FrameworkField = ({ prop = "framework_key" }: { prop?: string }) => {
const frameworkChoices = useFrameworkChoices();

return (
<FunctionField
source="framework_key"
source={prop}
label="Framework"
render={(record: any) =>
frameworkChoices.find((framework: any) => framework.id === record?.framework_key)?.name || record?.framework_key
frameworkChoices.find((framework: any) => framework.id === record?.[prop])?.name || record?.[prop]
}
sortable={false}
/>
Expand Down
9 changes: 9 additions & 0 deletions src/admin/components/Fields/ReadableStatusField.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { FunctionField } from "react-admin";

import { STATUS_MAP } from "@/components/elements/Status/constants/statusMap";

const ReadableStatusField = ({ prop }: { prop: string }) => (
<FunctionField source={prop} render={(record: any) => (record[prop] == null ? null : STATUS_MAP[record[prop]])} />
);

export default ReadableStatusField;
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import { When } from "react-if";

import Text from "@/components/elements/Text/Text";
import { AuditStatusResponse, ProjectLiteRead } from "@/generated/apiSchemas";
import { ProjectLightDto } from "@/generated/v3/entityService/entityServiceSchemas";

import AuditLogTable from "./AuditLogTable";

export interface SiteAuditLogProjectStatusProps {
record?: ProjectLiteRead | null;
record?: ProjectLiteRead | ProjectLightDto | null;
auditLogData?: { data: AuditStatusResponse[] };
auditData?: { entity: string; entity_uuid: string };
refresh?: () => void;
Expand All @@ -31,7 +32,7 @@ const SiteAuditLogProjectStatus: FC<SiteAuditLogProjectStatusProps> = ({
</Text>
</div>
<When condition={viewPD}>
<Text variant="text-16-bold">History and Discussion for {record && record?.name}</Text>
<Text variant="text-16-bold">History and Discussion for {record?.name}</Text>
{auditLogData && <AuditLogTable auditLogData={auditLogData} auditData={auditData} refresh={refresh} />}
</When>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,35 +22,35 @@ const HighLevelMetics: FC = () => {
<Stack gap={3}>
<ContextCondition frameworksShow={[Framework.TF]}>
<Labeled label="Jobs Created" sx={inlineLabelSx}>
<NumberField source="total_jobs_created" emptyText="0" />
<NumberField source="totalJobsCreated" emptyText="0" />
</Labeled>
</ContextCondition>
<ContextCondition frameworksShow={[Framework.PPC]}>
<Labeled label="Workdays Created (Old Calculation)" sx={inlineLabelSx}>
<NumberField source="self_reported_workday_count" emptyText="0" />
<NumberField source="selfReportedWorkdayCount" emptyText="0" />
</Labeled>
<Labeled label="Workdays Created (New Calculation)" sx={inlineLabelSx}>
<NumberField source="workday_count" emptyText="0" />
<NumberField source="workdayCount" emptyText="0" />
</Labeled>
<Labeled label="Workdays Created (Combined - PD View)" sx={inlineLabelSx}>
<NumberField source="combined_workday_count" emptyText="0" />
<NumberField source="combinedWorkdayCount" emptyText="0" />
</Labeled>
</ContextCondition>
<Labeled label="Trees Planted" sx={inlineLabelSx}>
<NumberField source="trees_planted_count" emptyText="0" />
<NumberField source="treesPlantedCount" emptyText="0" />
</Labeled>
<ContextCondition frameworksShow={[Framework.PPC]}>
<Labeled label="Seeds Planted" sx={inlineLabelSx}>
<NumberField source="seeds_planted_count" emptyText="0" />
<NumberField source="seedsPlantedCount" emptyText="0" />
</Labeled>
</ContextCondition>
<Labeled label="Hectares Under Restoration" sx={inlineLabelSx}>
<NumberField source="total_hectares_restored_sum" emptyText="0" />
<NumberField source="totalHectaresRestoredSum" emptyText="0" />
</Labeled>
<ContextCondition frameworksShow={[Framework.PPC]}>
<Labeled label="Trees Restored" sx={inlineLabelSx}>
<NumberField
source="trees_restored_ppc"
source="treesRestoredPpc"
emptyText="0"
options={{ minimumFractionDigits: 0, maximumFractionDigits: 0 }}
/>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Check } from "@mui/icons-material";
import { Box, Button, Card, Divider, Grid, Stack, Typography } from "@mui/material";
import { FC, useState } from "react";
import { BooleanField, Labeled, TextField, useShowContext } from "react-admin";
import { Labeled, TextField, useShowContext } from "react-admin";

import StatusChangeModal from "@/admin/components/Dialogs/StatusChangeModal";
import FrameworkField from "@/admin/components/Fields/FrameworkField";
import ReadableStatusField from "@/admin/components/Fields/ReadableStatusField";

const ProjectOverview: FC = () => {
const [statusModal, setStatusModal] = useState<"approve" | "moreinfo" | undefined>();
Expand All @@ -21,31 +22,25 @@ const ProjectOverview: FC = () => {
<Grid spacing={2} marginBottom={2} container>
<Grid item xs={8}>
<Labeled label="Organisation">
<TextField source="organisation.name" />
<TextField source="organisationName" />
</Labeled>
</Grid>

<Grid xs={4} item>
<Labeled label="Status">
<TextField source="readable_status" />
</Labeled>
</Grid>

<Grid xs={4} item>
<Labeled label="Monitored Data">
<BooleanField source="has_monitoring_data" looseValue />
<ReadableStatusField prop="status" />
</Labeled>
</Grid>

<Grid xs={4} item>
<Labeled label="Funding Programme">
<FrameworkField />
<FrameworkField prop="frameworkKey" />
</Labeled>
</Grid>

<Grid xs={4} item>
<Labeled label="Change Request Status">
<TextField source="readable_update_request_status" />
<ReadableStatusField prop="updateRequestStatus" />
</Labeled>
</Grid>
</Grid>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ const QuickActions: FC = () => {

<Stack gap={3}>
<Labeled label="Total Sites" sx={inlineLabelSx}>
<NumberField source="total_sites" />
<NumberField source="totalSites" />
</Labeled>
<Button variant="outlined" onClick={() => handleNavigate("site")}>
View Sites
Expand All @@ -83,7 +83,7 @@ const QuickActions: FC = () => {
<ContextCondition frameworksHide={[Framework.PPC]}>
<Stack gap={3}>
<Labeled label="Total Nurseries" sx={inlineLabelSx}>
<NumberField source="total_nurseries" />
<NumberField source="totalNurseries" />
</Labeled>
<Button variant="outlined" onClick={() => handleNavigate("nursery")}>
View Nurseries
Expand All @@ -97,10 +97,10 @@ const QuickActions: FC = () => {

<Stack gap={3}>
<Labeled label="Total Project Reports" sx={inlineLabelSx}>
<NumberField source="total_project_reports" />
<NumberField source="totalProjectReports" />
</Labeled>
<Labeled label="Total Overdue Reports" sx={inlineLabelSx}>
<NumberField source="total_overdue_reports" />
<NumberField source="totalOverdueReports" />
</Labeled>
<Button variant="outlined" onClick={() => handleNavigate("projectReport")}>
View Reports
Expand Down
Loading