Skip to content

Commit

Permalink
Merge branch 'staging' into TM-1605_site_landing_page_progress_goals
Browse files Browse the repository at this point in the history
  • Loading branch information
LimberHope committed Jan 30, 2025
2 parents f3ade9f + 275f9d7 commit 40c3f9f
Show file tree
Hide file tree
Showing 28 changed files with 403 additions and 185 deletions.
6 changes: 3 additions & 3 deletions src/admin/components/Actions/ListActionsCreateFilter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import { Button, CreateButton, FilterButton, TopToolbar } from "react-admin";
import { When } from "react-if";

interface ListActionsCreateFilterProps {
isSuperAdmin?: boolean;
canCreateUser?: boolean;
onExport?: () => void;
}

const ListActionsCreateFilter = ({ isSuperAdmin, onExport }: ListActionsCreateFilterProps) => (
const ListActionsCreateFilter = ({ canCreateUser, onExport }: ListActionsCreateFilterProps) => (
<TopToolbar>
<When condition={isSuperAdmin}>
<When condition={canCreateUser}>
<CreateButton className="filter-button-page-admin" />
</When>
<FilterButton className="filter-button-page-admin" />
Expand Down
26 changes: 25 additions & 1 deletion src/admin/components/Actions/ShowActions.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Box, Typography } from "@mui/material";
import { get } from "lodash";
import { useMemo } from "react";
import {
Button,
DeleteWithConfirmButton,
Expand All @@ -13,6 +14,7 @@ import {
} from "react-admin";
import { When } from "react-if";

import { useGetUserRole } from "@/admin/hooks/useGetUserRole";
import Icon, { IconNames } from "@/components/extensive/Icon/Icon";

import ShowTitle from "../ShowTitle";
Expand All @@ -38,6 +40,7 @@ const ShowActions = ({
toggleTestStatus,
deleteProps = {}
}: IProps) => {
const { isFrameworkAdmin, isSuperAdmin, role } = useGetUserRole();
const record = useRecordContext<any>();
const resource = useResourceContext();

Expand All @@ -48,6 +51,27 @@ const ShowActions = ({
deleteProps.confirmContent = `You are about to delete this ${resourceName}. This action will permanently remove the item from the system, and it cannot be undone. Are you sure you want to delete this item?`;
}

const showEdit = useMemo(() => {
if (resource === "user") {
if (isSuperAdmin) {
return true;
}
if (record?.role === "admin-super") {
return false;
}
if (record?.role === "project-developer" || record?.role === "project-manager") {
return true;
}
if (isFrameworkAdmin) {
if (record?.role === role) {
return true;
}
return false;
}
}
return record && hasEdit;
}, [record, resource, hasEdit, isFrameworkAdmin, isSuperAdmin]);

return (
<Box sx={{ display: "flex", alignItems: "center" }}>
<When condition={resource === "siteReport" || resource === "nurseryReport"}>
Expand Down Expand Up @@ -78,7 +102,7 @@ const ShowActions = ({
icon={<Icon className="h-5 w-5" name={IconNames.TRASH_PA} />}
/>
)}
{record && hasEdit && (
{showEdit && (
<EditButton
className="!text-sm !font-semibold !capitalize !text-blueCustom-900 lg:!text-base wide:!text-md"
icon={<Icon className="h-6 w-6" name={IconNames.EDIT} />}
Expand Down
16 changes: 4 additions & 12 deletions src/admin/components/EntityEdit/EntityEdit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,10 @@ import WizardForm from "@/components/extensive/WizardForm";
import LoadingContainer from "@/components/generic/Loading/LoadingContainer";
import EntityProvider from "@/context/entity.provider";
import FrameworkProvider, { Framework } from "@/context/framework.provider";
import {
GetV2FormsENTITYUUIDResponse,
useGetV2FormsENTITYUUID,
usePutV2FormsENTITYUUID
} from "@/generated/apiComponents";
import { GetV2FormsENTITYUUIDResponse, useGetV2FormsENTITYUUID } from "@/generated/apiComponents";
import { normalizedFormData } from "@/helpers/customForms";
import { pluralEntityNameToSingular } from "@/helpers/entity";
import { useFormUpdate } from "@/hooks/useFormUpdate";
import {
useGetCustomFormSteps,
useNormalizedFormDefaultValue
Expand All @@ -39,7 +36,7 @@ export const EntityEdit = () => {
const entityName = ResourceEntityMapping[resource] as EntityName;
const entityUUID = id as string;

const { mutate: updateEntity, error, isSuccess, isLoading: isUpdating } = usePutV2FormsENTITYUUID({});
const { updateEntity, error, isSuccess, isUpdating } = useFormUpdate(entityName, entityUUID);

const {
data: formResponse,
Expand Down Expand Up @@ -79,12 +76,7 @@ export const EntityEdit = () => {
steps={formSteps!}
errors={error}
onBackFirstStep={() => navigate("..")}
onChange={data =>
updateEntity({
pathParams: { uuid: entityUUID, entity: entityName },
body: { answers: normalizedFormData(data, formSteps!) }
})
}
onChange={data => updateEntity({ answers: normalizedFormData(data, formSteps!) })}
formStatus={isSuccess ? "saved" : isUpdating ? "saving" : undefined}
onSubmit={() => navigate(createPath({ resource, id, type: "show" }))}
defaultValues={defaultValues}
Expand Down
3 changes: 2 additions & 1 deletion src/admin/hooks/useGetUserRole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export const useGetUserRole = () => {
role: user.primaryRole,
isSuperAdmin: user.primaryRole === "admin-super",
isPPCAdmin: user.primaryRole === "admin-ppc",
isPPCTerrafundAdmin: user.primaryRole === "admin-terrafund"
isPPCTerrafundAdmin: user.primaryRole === "admin-terrafund",
isFrameworkAdmin: user.primaryRole && user.primaryRole.includes("admin-")
};
};
16 changes: 13 additions & 3 deletions src/admin/modules/user/components/UserCreate.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useMemo } from "react";
import {
AutocompleteInput,
Create,
Expand All @@ -13,6 +14,7 @@ import { useGetUserRole } from "@/admin/hooks/useGetUserRole";
import {
countriesChoices,
directFrameworkChoices,
frameworkAdminPrimaryRoleChoices,
frameworkChoices,
userPrimaryRoleChoices
} from "@/admin/modules/user/const";
Expand All @@ -21,7 +23,7 @@ import { validateForm } from "@/admin/utils/forms";
import modules from "../..";

const UserCreate = () => {
const { isSuperAdmin } = useGetUserRole();
const { isFrameworkAdmin, isSuperAdmin, role } = useGetUserRole();

const schemaObject: any = {
first_name: yup.string().nullable().required("First Name is required"),
Expand All @@ -34,10 +36,18 @@ const UserCreate = () => {
country: yup.string().nullable()
};

if (isSuperAdmin) {
if (isFrameworkAdmin) {
schemaObject.role = yup.string().required("Role is required");
}

const roleChoices = useMemo(() => {
if (isSuperAdmin) {
return userPrimaryRoleChoices;
}

return [...frameworkAdminPrimaryRoleChoices, userPrimaryRoleChoices.find(choice => choice.id === role)];
}, [isFrameworkAdmin]);

return (
<Create title="Create User">
<SimpleForm validate={validateForm(yup.object(schemaObject))}>
Expand All @@ -56,7 +66,7 @@ const UserCreate = () => {
<AutocompleteInput label="Organisation" optionText="name" fullWidth />
</ReferenceInput>

{isSuperAdmin && <SelectInput source="role" label="Role" choices={userPrimaryRoleChoices} fullWidth />}
{isFrameworkAdmin && <SelectInput source="role" label="Role" choices={roleChoices} fullWidth />}

<SelectInput source="program" label="Program" choices={frameworkChoices} fullWidth />

Expand Down
14 changes: 11 additions & 3 deletions src/admin/modules/user/components/UserEdit.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useMemo } from "react";
import {
AutocompleteInput,
Edit,
Expand All @@ -13,6 +14,7 @@ import { useGetUserRole } from "@/admin/hooks/useGetUserRole";
import {
countriesChoices,
directFrameworkChoices,
frameworkAdminPrimaryRoleChoices,
frameworkChoices,
userPrimaryRoleChoices
} from "@/admin/modules/user/const";
Expand All @@ -22,7 +24,7 @@ import modules from "../..";
import UserTitle from "./UserTitle";

const UserEdit = () => {
const { isSuperAdmin } = useGetUserRole();
const { isFrameworkAdmin, isSuperAdmin, role } = useGetUserRole();
const schemaObject: any = {
first_name: yup.string().nullable().required(),
last_name: yup.string().nullable().required(),
Expand All @@ -32,7 +34,13 @@ const UserEdit = () => {
organisation: yup.object()
};

if (isSuperAdmin) schemaObject.role = yup.string().required();
const roleChoices = useMemo(() => {
if (isSuperAdmin) {
return userPrimaryRoleChoices;
}

return [...frameworkAdminPrimaryRoleChoices, userPrimaryRoleChoices.find(choice => choice.id === role)];
}, [isFrameworkAdmin]);

return (
<Edit title={<UserTitle />} mutationMode="pessimistic" actions={false}>
Expand All @@ -51,7 +59,7 @@ const UserEdit = () => {
<AutocompleteInput label="Organisation" optionText="name" fullWidth />
</ReferenceInput>

{isSuperAdmin && <SelectInput source="role" label="Role" choices={userPrimaryRoleChoices} fullWidth />}
{isFrameworkAdmin && <SelectInput source="role" label="Role" choices={roleChoices} fullWidth />}
<SelectInput source="program" label="Program" choices={frameworkChoices} fullWidth />
<SelectInput source="country" label="Country" choices={countriesChoices} fullWidth />
<SelectArrayInput
Expand Down
7 changes: 5 additions & 2 deletions src/admin/modules/user/components/UserList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ const UserDataGrid = () => {

export const UserList = () => {
const [exporting, setExporting] = useState<boolean>(false);
const { isSuperAdmin } = useGetUserRole();
const { isFrameworkAdmin } = useGetUserRole();

const userDataProvider = useDataProvider<UserDataProvider>();

Expand All @@ -108,7 +108,10 @@ export const UserList = () => {
</Text>
</Stack>

<List actions={<ListActionsCreateFilter isSuperAdmin={isSuperAdmin} onExport={handleExport} />} filters={filters}>
<List
actions={<ListActionsCreateFilter canCreateUser={isFrameworkAdmin} onExport={handleExport} />}
filters={filters}
>
<UserDataGrid />
</List>

Expand Down
11 changes: 11 additions & 0 deletions src/admin/modules/user/const.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import { getCountriesOptions } from "@/constants/options/countries";
import { Framework } from "@/context/framework.provider";

export const frameworkAdminPrimaryRoleChoices = [
{
id: "project-developer",
name: "Project Developer"
},
{
id: "project-manager",
name: "Project Manager"
}
];

export const userPrimaryRoleChoices = [
{
id: "admin-ppc",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
fetchPostV2TerrafundUploadShapefileValidate
} from "@/generated/apiComponents";
import { FileType, UploadedFile } from "@/types/common";
import { getErrorMessageFromPayload } from "@/utils/errors";

const ValidatePolygonFileShow: FC = () => {
const { openModal, closeModal } = useModalContext();
Expand Down Expand Up @@ -95,7 +96,8 @@ const ValidatePolygonFileShow: FC = () => {
}
openNotification("error", errorMessage, t("Error uploading file"));
} else {
openNotification("error", t("An unknown error occurred"), t("Error uploading file"));
const errorMessage = getErrorMessageFromPayload(error);
openNotification("error", t("Error uploading file"), t(errorMessage));
}
}
hideLoader();
Expand Down
2 changes: 1 addition & 1 deletion src/components/elements/ImageGallery/ImageGallery.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -428,7 +428,7 @@ const ImageGallery = ({
defaultPageSize={defaultPageSize}
hasPageSizeSelector
invertSelect
isImageGallery
galleryType={"imageGallery"}
/>
</div>
</>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,16 @@ const TreeSpeciesInput = (props: TreeSpeciesInputProps) => {
props.withPreviousCounts && (isReport || (isEntity && ["sites", "nurseries"].includes(entityName)));
const displayPreviousCounts = props.withPreviousCounts && isReport;
const hasCountActive = props.withNumbers;
const totalReportedColumn =
collection === "nursery-seedling"
? t("NEW SEEDLINGS PRODUCED THIS REPORT:")
: isReport
? t("TOTAL PLANTED THIS REPORT:")
: hasCountActive
? t("TREES TO BE PLANTED:")
: "";
const totalToDateColumn =
collection === "nursery-seedling" ? t("TOTAL SEEDLINGS PRODUCED TO DATE:") : t("TOTAL PLANTED TO DATE:");

const entity = (handleBaseEntityTrees ? entityName : undefined) as EstablishmentEntityType;
const uuid = handleBaseEntityTrees ? entityUuid : undefined;
Expand Down Expand Up @@ -304,7 +314,7 @@ const TreeSpeciesInput = (props: TreeSpeciesInputProps) => {
</div>
<div className={classNames({ "border-r pr-6": displayPreviousCounts })} ref={refPlanted}>
<Text variant="text-14-bold" className="uppercase text-black">
{isReport ? t("TOTAL PLANTED THIS REPORT:") : hasCountActive ? t("TREES TO BE PLANTED:") : ""}
{totalReportedColumn}
</Text>
<Text variant="text-20-bold" className="text-primary">
{hasCountActive
Expand All @@ -317,7 +327,7 @@ const TreeSpeciesInput = (props: TreeSpeciesInputProps) => {
<When condition={displayPreviousCounts}>
<div>
<Text variant="text-14-bold" className="uppercase text-black">
{t("TOTAL PLANTED TO DATE:")}
{totalToDateColumn}
</Text>
<Text variant="text-20-bold" className="text-primary">
{totalWithPrevious.toLocaleString()}
Expand Down
31 changes: 30 additions & 1 deletion src/components/elements/Map-mapbox/Map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import ViewImageCarousel from "./MapControls/ViewImageCarousel";
import { ZoomControl } from "./MapControls/ZoomControl";
import {
addBorderCountry,
addBorderLandscape,
addDeleteLayer,
addFilterOnLayer,
addGeojsonToDraw,
Expand All @@ -67,6 +68,7 @@ import {
addSourcesToLayers,
drawTemporaryPolygon,
removeBorderCountry,
removeBorderLandscape,
removeMediaLayer,
removePopups,
startDrawing,
Expand Down Expand Up @@ -121,6 +123,7 @@ interface MapProps extends Omit<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>
listViewProjects?: any;
role?: any;
selectedCountry?: string | null;
selectedLandscapes?: string[];
setLoader?: (value: boolean) => void;
setIsLoadingDelayedJob?: (value: boolean) => void;
isLoadingDelayedJob?: boolean;
Expand Down Expand Up @@ -172,7 +175,16 @@ export const MapContainer = ({
const [sourcesAdded, setSourcesAdded] = useState<boolean>(false);
const [viewImages, setViewImages] = useState(false);
const [currentStyle, setCurrentStyle] = useState(MapStyle.Satellite);
const { polygonsData, bbox, setPolygonFromMap, polygonFromMap, sitePolygonData, selectedCountry, setLoader } = props;
const {
polygonsData,
bbox,
setPolygonFromMap,
polygonFromMap,
sitePolygonData,
selectedCountry,
selectedLandscapes,
setLoader
} = props;
const context = useSitePolygonData();
const contextMapArea = useMapAreaContext();
const dashboardContext = useDashboardContext();
Expand Down Expand Up @@ -311,6 +323,23 @@ export const MapContainer = ({
});
}
}, [selectedCountry, styleLoaded, sourcesAdded]);
useEffect(() => {
if (!map.current || !sourcesAdded) return;
const setupBorders = () => {
if (selectedLandscapes && selectedLandscapes.length > 0) {
addBorderLandscape(map.current, selectedLandscapes);
} else {
removeBorderLandscape(map.current);
}
};
if (map.current.isStyleLoaded()) {
setupBorders();
} else {
map.current.once("render", () => {
setupBorders();
});
}
}, [selectedLandscapes, styleLoaded, sourcesAdded]);
useEffect(() => {
const projectUUID = router.query.uuid as string;
const isProjectPath = router.isReady && router.asPath.includes("project");
Expand Down
Loading

0 comments on commit 40c3f9f

Please sign in to comment.