Remove unused imports and changed and improved layout design and responsiveness in some components and fixed some bugs.
This commit is contained in:
@@ -5,192 +5,329 @@ import Separator from "@/components/Low/Separator";
|
||||
import { Grading, Step } from "@/interfaces";
|
||||
import { Entity } from "@/interfaces/entity";
|
||||
import { User } from "@/interfaces/user";
|
||||
import { CEFR_STEPS, GENERAL_STEPS, IELTS_STEPS, TOFEL_STEPS } from "@/resources/grading";
|
||||
import { mapBy } from "@/utils";
|
||||
import {
|
||||
CEFR_STEPS,
|
||||
GENERAL_STEPS,
|
||||
IELTS_STEPS,
|
||||
TOFEL_STEPS,
|
||||
} from "@/resources/grading";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import axios from "axios";
|
||||
import clsx from "clsx";
|
||||
import { Divider } from "primereact/divider";
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
Dispatch,
|
||||
memo,
|
||||
SetStateAction,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useState,
|
||||
} from "react";
|
||||
import { BsPlusCircle, BsTrash } from "react-icons/bs";
|
||||
import { toast } from "react-toastify";
|
||||
|
||||
const areStepsOverlapped = (steps: Step[]) => {
|
||||
for (let i = 0; i < steps.length; i++) {
|
||||
if (i === 0) continue;
|
||||
for (let i = 0; i < steps.length; i++) {
|
||||
if (i === 0) continue;
|
||||
|
||||
const step = steps[i];
|
||||
const previous = steps[i - 1];
|
||||
const step = steps[i];
|
||||
const previous = steps[i - 1];
|
||||
|
||||
if (previous.max >= step.min) return true;
|
||||
}
|
||||
if (previous.max >= step.min) return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
return false;
|
||||
};
|
||||
interface RowProps {
|
||||
min: number;
|
||||
max: number;
|
||||
index: number;
|
||||
label: string;
|
||||
isLast: boolean;
|
||||
isLoading: boolean;
|
||||
setSteps: Dispatch<SetStateAction<Step[]>>;
|
||||
addRow: (index: number) => void;
|
||||
}
|
||||
|
||||
function GradingRow({
|
||||
min,
|
||||
max,
|
||||
label,
|
||||
index,
|
||||
isLoading,
|
||||
isLast,
|
||||
setSteps,
|
||||
addRow,
|
||||
}: RowProps) {
|
||||
const onChangeMin = useCallback(
|
||||
(e: string) => {
|
||||
setSteps((prev) =>
|
||||
prev.map((x, i) => (i === index ? { ...x, min: parseInt(e) } : x))
|
||||
);
|
||||
},
|
||||
[index, setSteps]
|
||||
);
|
||||
|
||||
const onChangeMax = useCallback(
|
||||
(e: string) => {
|
||||
setSteps((prev) =>
|
||||
prev.map((x, i) => (i === index ? { ...x, max: parseInt(e) } : x))
|
||||
);
|
||||
},
|
||||
[index, setSteps]
|
||||
);
|
||||
|
||||
const onChangeLabel = useCallback(
|
||||
(e: string) => {
|
||||
setSteps((prev) =>
|
||||
prev.map((x, i) => (i === index ? { ...x, label: e } : x))
|
||||
);
|
||||
},
|
||||
[index, setSteps]
|
||||
);
|
||||
|
||||
const onAddRow = useCallback(() => addRow(index), [addRow, index]);
|
||||
|
||||
const removeRow = useCallback(
|
||||
() => setSteps((prev) => prev.filter((_, i) => i !== index)),
|
||||
[index, setSteps]
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="grid grid-cols-3 gap-4 w-full">
|
||||
<Input
|
||||
label="Min. Percentage"
|
||||
value={min}
|
||||
type="number"
|
||||
disabled={index === 0 || isLoading}
|
||||
onChange={onChangeMin}
|
||||
name="min"
|
||||
/>
|
||||
<Input
|
||||
label="Grade"
|
||||
value={label}
|
||||
type="text"
|
||||
disabled={isLoading}
|
||||
onChange={onChangeLabel}
|
||||
name="min"
|
||||
/>
|
||||
<Input
|
||||
label="Max. Percentage"
|
||||
value={max}
|
||||
type="number"
|
||||
disabled={isLast || isLoading}
|
||||
onChange={onChangeMax}
|
||||
name="max"
|
||||
/>
|
||||
</div>
|
||||
{index !== 0 && !isLast && (
|
||||
<button
|
||||
disabled={isLoading}
|
||||
className="pt-9 text-xl group"
|
||||
onClick={removeRow}
|
||||
>
|
||||
<div className="w-full h-full flex items-center justify-center group-hover:bg-neutral-200 rounded-full p-3 transition ease-in-out duration-300">
|
||||
<BsTrash />
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!isLast && (
|
||||
<Button
|
||||
className="w-full flex items-center justify-center"
|
||||
disabled={isLoading}
|
||||
onClick={onAddRow}
|
||||
>
|
||||
<BsPlusCircle />
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
const GradingRowMemo = memo(GradingRow);
|
||||
interface Props {
|
||||
user: User;
|
||||
entitiesGrading: Grading[];
|
||||
entities: Entity[]
|
||||
mutate: () => void
|
||||
user: User;
|
||||
entitiesGrading: Grading[];
|
||||
entities: Entity[];
|
||||
mutate: () => void;
|
||||
}
|
||||
|
||||
export default function CorporateGradingSystem({ user, entitiesGrading = [], entities = [], mutate }: Props) {
|
||||
const [entity, setEntity] = useState(entitiesGrading[0]?.entity || undefined)
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [steps, setSteps] = useState<Step[]>([]);
|
||||
const [otherEntities, setOtherEntities] = useState<string[]>([])
|
||||
export default function CorporateGradingSystem({
|
||||
user,
|
||||
entitiesGrading = [],
|
||||
entities = [],
|
||||
mutate,
|
||||
}: Props) {
|
||||
const [entity, setEntity] = useState(entitiesGrading[0]?.entity || undefined);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [steps, setSteps] = useState<Step[]>([]);
|
||||
const [otherEntities, setOtherEntities] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (entity) {
|
||||
const entitySteps = entitiesGrading.find(e => e.entity === entity)!.steps
|
||||
setSteps(entitySteps || [])
|
||||
}
|
||||
}, [entitiesGrading, entity])
|
||||
useEffect(() => {
|
||||
if (entity) {
|
||||
const entitySteps = entitiesGrading.find(
|
||||
(e) => e.entity === entity
|
||||
)!.steps;
|
||||
setSteps(entitySteps || []);
|
||||
}
|
||||
}, [entitiesGrading, entity]);
|
||||
|
||||
const saveGradingSystem = () => {
|
||||
if (!steps.every((x) => x.min < x.max)) return toast.error("One of your steps has a minimum threshold inferior to its superior threshold.");
|
||||
if (areStepsOverlapped(steps)) return toast.error("There seems to be an overlap in one of your steps.");
|
||||
if (
|
||||
steps.reduce((acc, curr) => {
|
||||
return acc - (curr.max - curr.min + 1);
|
||||
}, 100) > 0
|
||||
)
|
||||
return toast.error("There seems to be an open interval in your steps.");
|
||||
const saveGradingSystem = () => {
|
||||
if (!steps.every((x) => x.min < x.max))
|
||||
return toast.error(
|
||||
"One of your steps has a minimum threshold inferior to its superior threshold."
|
||||
);
|
||||
if (areStepsOverlapped(steps))
|
||||
return toast.error("There seems to be an overlap in one of your steps.");
|
||||
if (
|
||||
steps.reduce((acc, curr) => {
|
||||
return acc - (curr.max - curr.min + 1);
|
||||
}, 100) > 0
|
||||
)
|
||||
return toast.error("There seems to be an open interval in your steps.");
|
||||
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.post("/api/grading", { user: user.id, entity, steps })
|
||||
.then(() => toast.success("Your grading system has been saved!"))
|
||||
.then(mutate)
|
||||
.catch(() => toast.error("Something went wrong, please try again later"))
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.post("/api/grading", { user: user.id, entity, steps })
|
||||
.then(() => toast.success("Your grading system has been saved!"))
|
||||
.then(mutate)
|
||||
.catch(() => toast.error("Something went wrong, please try again later"))
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
const applyToOtherEntities = () => {
|
||||
if (!steps.every((x) => x.min < x.max)) return toast.error("One of your steps has a minimum threshold inferior to its superior threshold.");
|
||||
if (areStepsOverlapped(steps)) return toast.error("There seems to be an overlap in one of your steps.");
|
||||
if (
|
||||
steps.reduce((acc, curr) => {
|
||||
return acc - (curr.max - curr.min + 1);
|
||||
}, 100) > 0
|
||||
)
|
||||
return toast.error("There seems to be an open interval in your steps.");
|
||||
const applyToOtherEntities = () => {
|
||||
if (!steps.every((x) => x.min < x.max))
|
||||
return toast.error(
|
||||
"One of your steps has a minimum threshold inferior to its superior threshold."
|
||||
);
|
||||
if (areStepsOverlapped(steps))
|
||||
return toast.error("There seems to be an overlap in one of your steps.");
|
||||
if (
|
||||
steps.reduce((acc, curr) => {
|
||||
return acc - (curr.max - curr.min + 1);
|
||||
}, 100) > 0
|
||||
)
|
||||
return toast.error("There seems to be an open interval in your steps.");
|
||||
|
||||
if (otherEntities.length === 0) return toast.error("Select at least one entity")
|
||||
if (otherEntities.length === 0)
|
||||
return toast.error("Select at least one entity");
|
||||
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.post("/api/grading/multiple", { user: user.id, entities: otherEntities, steps })
|
||||
.then(() => toast.success("Your grading system has been saved!"))
|
||||
.then(mutate)
|
||||
.catch(() => toast.error("Something went wrong, please try again later"))
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.post("/api/grading/multiple", {
|
||||
user: user.id,
|
||||
entities: otherEntities,
|
||||
steps,
|
||||
})
|
||||
.then(() => toast.success("Your grading system has been saved!"))
|
||||
.then(mutate)
|
||||
.catch(() => toast.error("Something went wrong, please try again later"))
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 border p-4 border-mti-gray-platinum rounded-xl">
|
||||
<label className="font-normal text-base text-mti-gray-dim">Grading System</label>
|
||||
<div className={clsx("flex flex-col gap-4")}>
|
||||
<label className="font-normal text-base text-mti-gray-dim">Entity</label>
|
||||
<Select
|
||||
defaultValue={{ value: (entities || [])[0]?.id, label: (entities || [])[0]?.label }}
|
||||
options={entities.map((e) => ({ value: e.id, label: e.label }))}
|
||||
onChange={(e) => setEntity(e?.value || undefined)}
|
||||
isClearable={checkAccess(user, ["admin", "developer"])}
|
||||
/>
|
||||
</div>
|
||||
const addRow = useCallback((index: number) => {
|
||||
setSteps((prev) => {
|
||||
const item = {
|
||||
min: prev[index === 0 ? 0 : index - 1].max + 1,
|
||||
max: prev[index + 1].min - 1,
|
||||
label: "",
|
||||
};
|
||||
return [
|
||||
...prev.slice(0, index + 1),
|
||||
item,
|
||||
...prev.slice(index + 1, prev.length),
|
||||
];
|
||||
});
|
||||
}, []);
|
||||
|
||||
{entities.length > 1 && (
|
||||
<>
|
||||
<Separator />
|
||||
<label className="font-normal text-base text-mti-gray-dim">Apply this grading system to other entities</label>
|
||||
<Select
|
||||
options={entities.map((e) => ({ value: e.id, label: e.label }))}
|
||||
onChange={(e) => !e ? setOtherEntities([]) : setOtherEntities(e.map(o => o.value!))}
|
||||
isMulti
|
||||
/>
|
||||
<Button onClick={applyToOtherEntities} isLoading={isLoading} disabled={isLoading || otherEntities.length === 0} variant="outline">
|
||||
Apply to {otherEntities.length} other entities
|
||||
</Button>
|
||||
<Separator />
|
||||
</>
|
||||
)}
|
||||
return (
|
||||
<div className="flex flex-col gap-4 border p-4 border-mti-gray-platinum rounded-xl">
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Grading System
|
||||
</label>
|
||||
<div className={clsx("flex flex-col gap-4")}>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Entity
|
||||
</label>
|
||||
<Select
|
||||
defaultValue={{
|
||||
value: (entities || [])[0]?.id,
|
||||
label: (entities || [])[0]?.label,
|
||||
}}
|
||||
options={entities.map((e) => ({ value: e.id, label: e.label }))}
|
||||
onChange={(e) => setEntity(e?.value || undefined)}
|
||||
isClearable={checkAccess(user, ["admin", "developer"])}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<label className="font-normal text-base text-mti-gray-dim">Preset Systems</label>
|
||||
<div className="grid grid-cols-4 gap-4">
|
||||
<Button variant="outline" onClick={() => setSteps(CEFR_STEPS)}>
|
||||
CEFR
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setSteps(GENERAL_STEPS)}>
|
||||
General English
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setSteps(IELTS_STEPS)}>
|
||||
IELTS
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setSteps(TOFEL_STEPS)}>
|
||||
TOFEL iBT
|
||||
</Button>
|
||||
</div>
|
||||
{entities.length > 1 && (
|
||||
<>
|
||||
<Separator />
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Apply this grading system to other entities
|
||||
</label>
|
||||
<Select
|
||||
options={entities.map((e) => ({ value: e.id, label: e.label }))}
|
||||
onChange={(e) =>
|
||||
!e
|
||||
? setOtherEntities([])
|
||||
: setOtherEntities(e.map((o) => o.value!))
|
||||
}
|
||||
isMulti
|
||||
/>
|
||||
<Button
|
||||
onClick={applyToOtherEntities}
|
||||
isLoading={isLoading}
|
||||
disabled={isLoading || otherEntities.length === 0}
|
||||
variant="outline"
|
||||
>
|
||||
Apply to {otherEntities.length} other entities
|
||||
</Button>
|
||||
<Separator />
|
||||
</>
|
||||
)}
|
||||
|
||||
{steps.map((step, index) => (
|
||||
<>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="grid grid-cols-3 gap-4 w-full" key={step.min}>
|
||||
<Input
|
||||
label="Min. Percentage"
|
||||
value={step.min}
|
||||
type="number"
|
||||
disabled={index === 0 || isLoading}
|
||||
onChange={(e) => setSteps((prev) => prev.map((x, i) => (i === index ? { ...x, min: parseInt(e) } : x)))}
|
||||
name="min"
|
||||
/>
|
||||
<Input
|
||||
label="Grade"
|
||||
value={step.label}
|
||||
type="text"
|
||||
disabled={isLoading}
|
||||
onChange={(e) => setSteps((prev) => prev.map((x, i) => (i === index ? { ...x, label: e } : x)))}
|
||||
name="min"
|
||||
/>
|
||||
<Input
|
||||
label="Max. Percentage"
|
||||
value={step.max}
|
||||
type="number"
|
||||
disabled={index === steps.length - 1 || isLoading}
|
||||
onChange={(e) => setSteps((prev) => prev.map((x, i) => (i === index ? { ...x, max: parseInt(e) } : x)))}
|
||||
name="max"
|
||||
/>
|
||||
</div>
|
||||
{index !== 0 && index !== steps.length - 1 && (
|
||||
<button
|
||||
disabled={isLoading}
|
||||
className="pt-9 text-xl group"
|
||||
onClick={() => setSteps((prev) => prev.filter((_, i) => i !== index))}>
|
||||
<div className="w-full h-full flex items-center justify-center group-hover:bg-neutral-200 rounded-full p-3 transition ease-in-out duration-300">
|
||||
<BsTrash />
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<label className="font-normal text-base text-mti-gray-dim">
|
||||
Preset Systems
|
||||
</label>
|
||||
<div className="grid grid-cols-4 gap-4">
|
||||
<Button variant="outline" onClick={() => setSteps(CEFR_STEPS)}>
|
||||
CEFR
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setSteps(GENERAL_STEPS)}>
|
||||
General English
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setSteps(IELTS_STEPS)}>
|
||||
IELTS
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setSteps(TOFEL_STEPS)}>
|
||||
TOFEL iBT
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{index < steps.length - 1 && (
|
||||
<Button
|
||||
className="w-full flex items-center justify-center"
|
||||
disabled={isLoading}
|
||||
onClick={() => {
|
||||
const item = { min: steps[index === 0 ? 0 : index - 1].max + 1, max: steps[index + 1].min - 1, label: "" };
|
||||
setSteps((prev) => [...prev.slice(0, index + 1), item, ...prev.slice(index + 1, steps.length)]);
|
||||
}}>
|
||||
<BsPlusCircle />
|
||||
</Button>
|
||||
)}
|
||||
</>
|
||||
))}
|
||||
{steps.map((step, index) => (
|
||||
<GradingRowMemo
|
||||
key={index}
|
||||
min={step.min}
|
||||
max={step.max}
|
||||
label={step.label}
|
||||
index={index}
|
||||
isLoading={isLoading}
|
||||
isLast={index === steps.length - 1}
|
||||
setSteps={setSteps}
|
||||
addRow={addRow}
|
||||
/>
|
||||
))}
|
||||
|
||||
<Button onClick={saveGradingSystem} isLoading={isLoading} disabled={isLoading} className="mt-8">
|
||||
Save Grading System
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
<Button
|
||||
onClick={saveGradingSystem}
|
||||
isLoading={isLoading}
|
||||
disabled={isLoading}
|
||||
className="mt-8"
|
||||
>
|
||||
Save Grading System
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,12 @@ import clsx from "clsx";
|
||||
import { capitalize } from "lodash";
|
||||
import moment from "moment";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { BsCheck, BsCheckCircle, BsFillExclamationOctagonFill, BsTrash } from "react-icons/bs";
|
||||
import {
|
||||
BsCheck,
|
||||
BsCheckCircle,
|
||||
BsFillExclamationOctagonFill,
|
||||
BsTrash,
|
||||
} from "react-icons/bs";
|
||||
import { toast } from "react-toastify";
|
||||
import { countries, TCountries } from "countries-list";
|
||||
import countryCodes from "country-codes-list";
|
||||
@@ -24,426 +29,597 @@ import { WithLabeledEntities } from "@/interfaces/entity";
|
||||
import Table from "@/components/High/Table";
|
||||
import useEntities from "@/hooks/useEntities";
|
||||
import { useAllowedEntities } from "@/hooks/useEntityPermissions";
|
||||
import { findAllowedEntities } from "@/utils/permissions";
|
||||
|
||||
const columnHelper = createColumnHelper<WithLabeledEntities<User>>();
|
||||
const searchFields = [["name"], ["email"], ["entities", ""]];
|
||||
|
||||
export default function UserList({
|
||||
user,
|
||||
filters = [],
|
||||
type,
|
||||
renderHeader,
|
||||
user,
|
||||
filters = [],
|
||||
type,
|
||||
renderHeader,
|
||||
}: {
|
||||
user: User;
|
||||
filters?: ((user: User) => boolean)[];
|
||||
type?: Type;
|
||||
renderHeader?: (total: number) => JSX.Element;
|
||||
user: User;
|
||||
filters?: ((user: User) => boolean)[];
|
||||
type?: Type;
|
||||
renderHeader?: (total: number) => JSX.Element;
|
||||
}) {
|
||||
const [showDemographicInformation, setShowDemographicInformation] = useState(false);
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [showDemographicInformation, setShowDemographicInformation] =
|
||||
useState(false);
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
|
||||
const { users, reload } = useEntitiesUsers(type)
|
||||
const { entities } = useEntities()
|
||||
const { users, isLoading, reload } = useEntitiesUsers(type);
|
||||
const { entities } = useEntities();
|
||||
|
||||
const isAdmin = useMemo(() => ["admin", "developer"].includes(user?.type), [user?.type])
|
||||
const isAdmin = useMemo(
|
||||
() => ["admin", "developer"].includes(user?.type),
|
||||
[user?.type]
|
||||
);
|
||||
|
||||
const entitiesViewStudents = useAllowedEntities(user, entities, "view_students")
|
||||
const entitiesEditStudents = useAllowedEntities(user, entities, "edit_students")
|
||||
const entitiesDeleteStudents = useAllowedEntities(user, entities, "delete_students")
|
||||
const entitiesViewStudents = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"view_students"
|
||||
);
|
||||
const entitiesEditStudents = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"edit_students"
|
||||
);
|
||||
const entitiesDeleteStudents = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"delete_students"
|
||||
);
|
||||
|
||||
const entitiesViewTeachers = useAllowedEntities(user, entities, "view_teachers")
|
||||
const entitiesEditTeachers = useAllowedEntities(user, entities, "edit_teachers")
|
||||
const entitiesDeleteTeachers = useAllowedEntities(user, entities, "delete_teachers")
|
||||
const entitiesViewTeachers = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"view_teachers"
|
||||
);
|
||||
const entitiesEditTeachers = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"edit_teachers"
|
||||
);
|
||||
const entitiesDeleteTeachers = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"delete_teachers"
|
||||
);
|
||||
|
||||
const entitiesViewCorporates = useAllowedEntities(user, entities, "view_corporates")
|
||||
const entitiesEditCorporates = useAllowedEntities(user, entities, "edit_corporates")
|
||||
const entitiesDeleteCorporates = useAllowedEntities(user, entities, "delete_corporates")
|
||||
const entitiesViewCorporates = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"view_corporates"
|
||||
);
|
||||
const entitiesEditCorporates = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"edit_corporates"
|
||||
);
|
||||
const entitiesDeleteCorporates = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"delete_corporates"
|
||||
);
|
||||
|
||||
const entitiesViewMasterCorporates = useAllowedEntities(user, entities, "view_mastercorporates")
|
||||
const entitiesEditMasterCorporates = useAllowedEntities(user, entities, "edit_mastercorporates")
|
||||
const entitiesDeleteMasterCorporates = useAllowedEntities(user, entities, "delete_mastercorporates")
|
||||
const entitiesViewMasterCorporates = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"view_mastercorporates"
|
||||
);
|
||||
const entitiesEditMasterCorporates = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"edit_mastercorporates"
|
||||
);
|
||||
const entitiesDeleteMasterCorporates = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"delete_mastercorporates"
|
||||
);
|
||||
|
||||
const entitiesDownloadUsers = useAllowedEntities(user, entities, "download_user_list")
|
||||
const entitiesDownloadUsers = useAllowedEntities(
|
||||
user,
|
||||
entities,
|
||||
"download_user_list"
|
||||
);
|
||||
|
||||
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
|
||||
const router = useRouter();
|
||||
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
|
||||
const router = useRouter();
|
||||
|
||||
const expirationDateColor = (date: Date) => {
|
||||
const momentDate = moment(date);
|
||||
const today = moment(new Date());
|
||||
const expirationDateColor = (date: Date) => {
|
||||
const momentDate = moment(date);
|
||||
const today = moment(new Date());
|
||||
|
||||
if (today.isAfter(momentDate)) return "!text-mti-red-light font-bold line-through";
|
||||
if (today.add(1, "weeks").isAfter(momentDate)) return "!text-mti-red-light";
|
||||
if (today.add(2, "weeks").isAfter(momentDate)) return "!text-mti-rose-light";
|
||||
if (today.add(1, "months").isAfter(momentDate)) return "!text-mti-orange-light";
|
||||
};
|
||||
if (today.isAfter(momentDate))
|
||||
return "!text-mti-red-light font-bold line-through";
|
||||
if (today.add(1, "weeks").isAfter(momentDate)) return "!text-mti-red-light";
|
||||
if (today.add(2, "weeks").isAfter(momentDate))
|
||||
return "!text-mti-rose-light";
|
||||
if (today.add(1, "months").isAfter(momentDate))
|
||||
return "!text-mti-orange-light";
|
||||
};
|
||||
|
||||
const allowedUsers = useMemo(() => users.filter((u) => {
|
||||
if (isAdmin) return true
|
||||
if (u.id === user?.id) return false
|
||||
const allowedUsers = useMemo(
|
||||
() =>
|
||||
users.filter((u) => {
|
||||
if (isAdmin) return true;
|
||||
if (u.id === user?.id) return false;
|
||||
|
||||
switch (u.type) {
|
||||
case "student": return mapBy((u.entities || []), 'id').some((id) => mapBy(entitiesViewStudents, 'id').includes(id))
|
||||
case "teacher": return mapBy((u.entities || []), 'id').some((id) => mapBy(entitiesViewTeachers, 'id').includes(id))
|
||||
case 'corporate': return mapBy((u.entities || []), 'id').some((id) => mapBy(entitiesViewCorporates, 'id').includes(id))
|
||||
case 'mastercorporate': return mapBy((u.entities || []), 'id').some((id) => mapBy(entitiesViewMasterCorporates, 'id').includes(id))
|
||||
default: return false
|
||||
}
|
||||
})
|
||||
, [entitiesViewCorporates, entitiesViewMasterCorporates, entitiesViewStudents, entitiesViewTeachers, isAdmin, user?.id, users])
|
||||
switch (u.type) {
|
||||
case "student":
|
||||
return mapBy(u.entities || [], "id").some((id) =>
|
||||
mapBy(entitiesViewStudents, "id").includes(id)
|
||||
);
|
||||
case "teacher":
|
||||
return mapBy(u.entities || [], "id").some((id) =>
|
||||
mapBy(entitiesViewTeachers, "id").includes(id)
|
||||
);
|
||||
case "corporate":
|
||||
return mapBy(u.entities || [], "id").some((id) =>
|
||||
mapBy(entitiesViewCorporates, "id").includes(id)
|
||||
);
|
||||
case "mastercorporate":
|
||||
return mapBy(u.entities || [], "id").some((id) =>
|
||||
mapBy(entitiesViewMasterCorporates, "id").includes(id)
|
||||
);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}),
|
||||
[
|
||||
entitiesViewCorporates,
|
||||
entitiesViewMasterCorporates,
|
||||
entitiesViewStudents,
|
||||
entitiesViewTeachers,
|
||||
isAdmin,
|
||||
user?.id,
|
||||
users,
|
||||
]
|
||||
);
|
||||
|
||||
const displayUsers = useMemo(() =>
|
||||
filters.length > 0 ? filters.reduce((d, f) => d.filter(f), allowedUsers) : allowedUsers,
|
||||
[filters, allowedUsers])
|
||||
const displayUsers = useMemo(
|
||||
() =>
|
||||
filters.length > 0
|
||||
? filters.reduce((d, f) => d.filter(f), allowedUsers)
|
||||
: allowedUsers,
|
||||
[filters, allowedUsers]
|
||||
);
|
||||
|
||||
const deleteAccount = (user: User) => {
|
||||
if (!confirm(`Are you sure you want to delete ${user.name}'s account?`)) return;
|
||||
const deleteAccount = (user: User) => {
|
||||
if (!confirm(`Are you sure you want to delete ${user.name}'s account?`))
|
||||
return;
|
||||
|
||||
axios
|
||||
.delete<{ ok: boolean }>(`/api/user?id=${user.id}`)
|
||||
.then(() => {
|
||||
toast.success("User deleted successfully!");
|
||||
reload()
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong!", { toastId: "delete-error" });
|
||||
})
|
||||
.finally(reload);
|
||||
};
|
||||
axios
|
||||
.delete<{ ok: boolean }>(`/api/user?id=${user.id}`)
|
||||
.then(() => {
|
||||
toast.success("User deleted successfully!");
|
||||
reload();
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong!", { toastId: "delete-error" });
|
||||
})
|
||||
.finally(reload);
|
||||
};
|
||||
|
||||
const verifyAccount = (user: User) => {
|
||||
axios
|
||||
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, {
|
||||
...user,
|
||||
isVerified: true,
|
||||
})
|
||||
.then(() => {
|
||||
toast.success("User verified successfully!");
|
||||
reload();
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong!", { toastId: "update-error" });
|
||||
});
|
||||
};
|
||||
const verifyAccount = (user: User) => {
|
||||
axios
|
||||
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, {
|
||||
...user,
|
||||
isVerified: true,
|
||||
})
|
||||
.then(() => {
|
||||
toast.success("User verified successfully!");
|
||||
reload();
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong!", { toastId: "update-error" });
|
||||
});
|
||||
};
|
||||
|
||||
const toggleDisableAccount = (user: User) => {
|
||||
if (
|
||||
!confirm(
|
||||
`Are you sure you want to ${user.status === "disabled" ? "enable" : "disable"} ${user.name
|
||||
}'s account? This change is usually related to their payment state.`,
|
||||
)
|
||||
)
|
||||
return;
|
||||
const toggleDisableAccount = (user: User) => {
|
||||
if (
|
||||
!confirm(
|
||||
`Are you sure you want to ${
|
||||
user.status === "disabled" ? "enable" : "disable"
|
||||
} ${
|
||||
user.name
|
||||
}'s account? This change is usually related to their payment state.`
|
||||
)
|
||||
)
|
||||
return;
|
||||
|
||||
axios
|
||||
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, {
|
||||
...user,
|
||||
status: user.status === "disabled" ? "active" : "disabled",
|
||||
})
|
||||
.then(() => {
|
||||
toast.success(`User ${user.status === "disabled" ? "enabled" : "disabled"} successfully!`);
|
||||
reload();
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong!", { toastId: "update-error" });
|
||||
});
|
||||
};
|
||||
axios
|
||||
.post<{ user?: User; ok?: boolean }>(`/api/users/update?id=${user.id}`, {
|
||||
...user,
|
||||
status: user.status === "disabled" ? "active" : "disabled",
|
||||
})
|
||||
.then(() => {
|
||||
toast.success(
|
||||
`User ${
|
||||
user.status === "disabled" ? "enabled" : "disabled"
|
||||
} successfully!`
|
||||
);
|
||||
reload();
|
||||
})
|
||||
.catch(() => {
|
||||
toast.error("Something went wrong!", { toastId: "update-error" });
|
||||
});
|
||||
};
|
||||
|
||||
const getEditPermission = (type: Type) => {
|
||||
if (type === "student") return entitiesEditStudents
|
||||
if (type === "teacher") return entitiesEditTeachers
|
||||
if (type === "corporate") return entitiesEditCorporates
|
||||
if (type === "mastercorporate") return entitiesEditMasterCorporates
|
||||
const getEditPermission = (type: Type) => {
|
||||
if (type === "student") return entitiesEditStudents;
|
||||
if (type === "teacher") return entitiesEditTeachers;
|
||||
if (type === "corporate") return entitiesEditCorporates;
|
||||
if (type === "mastercorporate") return entitiesEditMasterCorporates;
|
||||
|
||||
return []
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
const getDeletePermission = (type: Type) => {
|
||||
if (type === "student") return entitiesDeleteStudents
|
||||
if (type === "teacher") return entitiesDeleteTeachers
|
||||
if (type === "corporate") return entitiesDeleteCorporates
|
||||
if (type === "mastercorporate") return entitiesDeleteMasterCorporates
|
||||
const getDeletePermission = (type: Type) => {
|
||||
if (type === "student") return entitiesDeleteStudents;
|
||||
if (type === "teacher") return entitiesDeleteTeachers;
|
||||
if (type === "corporate") return entitiesDeleteCorporates;
|
||||
if (type === "mastercorporate") return entitiesDeleteMasterCorporates;
|
||||
|
||||
return []
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
const canEditUser = (u: User) =>
|
||||
isAdmin || u.entities.some(e => mapBy(getEditPermission(u.type), 'id').includes(e.id))
|
||||
const canEditUser = (u: User) =>
|
||||
isAdmin ||
|
||||
u.entities.some((e) =>
|
||||
mapBy(getEditPermission(u.type), "id").includes(e.id)
|
||||
);
|
||||
|
||||
const canDeleteUser = (u: User) =>
|
||||
isAdmin || u.entities.some(e => mapBy(getDeletePermission(u.type), 'id').includes(e.id))
|
||||
const canDeleteUser = (u: User) =>
|
||||
isAdmin ||
|
||||
u.entities.some((e) =>
|
||||
mapBy(getDeletePermission(u.type), "id").includes(e.id)
|
||||
);
|
||||
|
||||
const actionColumn = ({ row }: { row: { original: User } }) => {
|
||||
const canEdit = canEditUser(row.original)
|
||||
const canDelete = canDeleteUser(row.original)
|
||||
const actionColumn = ({ row }: { row: { original: User } }) => {
|
||||
const canEdit = canEditUser(row.original);
|
||||
const canDelete = canDeleteUser(row.original);
|
||||
|
||||
return (
|
||||
<div className="flex gap-4">
|
||||
{!row.original.isVerified && canEdit && (
|
||||
<div data-tip="Verify User" className="cursor-pointer tooltip" onClick={() => verifyAccount(row.original)}>
|
||||
<BsCheck className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
</div>
|
||||
)}
|
||||
{canEdit && (
|
||||
<div
|
||||
data-tip={row.original.status === "disabled" ? "Enable User" : "Disable User"}
|
||||
className="cursor-pointer tooltip"
|
||||
onClick={() => toggleDisableAccount(row.original)}>
|
||||
{row.original.status === "disabled" ? (
|
||||
<BsCheckCircle className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
) : (
|
||||
<BsFillExclamationOctagonFill className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{canDelete && (
|
||||
<div data-tip="Delete" className="cursor-pointer tooltip" onClick={() => deleteAccount(row.original)}>
|
||||
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
return (
|
||||
<div className="flex gap-4">
|
||||
{!row.original.isVerified && canEdit && (
|
||||
<div
|
||||
data-tip="Verify User"
|
||||
className="cursor-pointer tooltip"
|
||||
onClick={() => verifyAccount(row.original)}
|
||||
>
|
||||
<BsCheck className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
</div>
|
||||
)}
|
||||
{canEdit && (
|
||||
<div
|
||||
data-tip={
|
||||
row.original.status === "disabled"
|
||||
? "Enable User"
|
||||
: "Disable User"
|
||||
}
|
||||
className="cursor-pointer tooltip"
|
||||
onClick={() => toggleDisableAccount(row.original)}
|
||||
>
|
||||
{row.original.status === "disabled" ? (
|
||||
<BsCheckCircle className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
) : (
|
||||
<BsFillExclamationOctagonFill className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{canDelete && (
|
||||
<div
|
||||
data-tip="Delete"
|
||||
className="cursor-pointer tooltip"
|
||||
onClick={() => deleteAccount(row.original)}
|
||||
>
|
||||
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const demographicColumns = [
|
||||
columnHelper.accessor("name", {
|
||||
header: "Name",
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
canEditUser(row.original) &&
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer",
|
||||
)}
|
||||
onClick={() =>
|
||||
canEditUser(row.original) ? setSelectedUser(row.original) : null
|
||||
}>
|
||||
{getValue()}
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("demographicInformation.country", {
|
||||
header: "Country",
|
||||
cell: (info) =>
|
||||
info.getValue()
|
||||
? `${countryCodes.findOne("countryCode" as any, info.getValue())?.flag} ${countries[info.getValue() as unknown as keyof TCountries]?.name
|
||||
} (+${countryCodes.findOne("countryCode" as any, info.getValue())?.countryCallingCode})`
|
||||
: "N/A",
|
||||
}),
|
||||
columnHelper.accessor("demographicInformation.phone", {
|
||||
header: "Phone",
|
||||
cell: (info) => info.getValue() || "N/A",
|
||||
enableSorting: true,
|
||||
}),
|
||||
columnHelper.accessor(
|
||||
(x) =>
|
||||
x.type === "corporate" || x.type === "mastercorporate" ? x.demographicInformation?.position : x.demographicInformation?.employment,
|
||||
{
|
||||
id: "employment",
|
||||
header: "Employment",
|
||||
cell: (info) => (info.row.original.type === "corporate" ? info.getValue() : capitalize(info.getValue())) || "N/A",
|
||||
enableSorting: true,
|
||||
},
|
||||
),
|
||||
columnHelper.accessor("lastLogin", {
|
||||
header: "Last Login",
|
||||
cell: (info) => (!!info.getValue() ? moment(info.getValue()).format("YYYY-MM-DD HH:mm") : "N/A"),
|
||||
}),
|
||||
columnHelper.accessor("demographicInformation.gender", {
|
||||
header: "Gender",
|
||||
cell: (info) => capitalize(info.getValue()) || "N/A",
|
||||
enableSorting: true,
|
||||
}),
|
||||
{
|
||||
header: (
|
||||
<span className="cursor-pointer" onClick={() => setShowDemographicInformation((prev) => !prev)}>
|
||||
Switch
|
||||
</span>
|
||||
),
|
||||
id: "actions",
|
||||
cell: actionColumn,
|
||||
sortable: false
|
||||
},
|
||||
];
|
||||
const demographicColumns = [
|
||||
columnHelper.accessor("name", {
|
||||
header: "Name",
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
canEditUser(row.original) &&
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer"
|
||||
)}
|
||||
onClick={() =>
|
||||
canEditUser(row.original) ? setSelectedUser(row.original) : null
|
||||
}
|
||||
>
|
||||
{getValue()}
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("demographicInformation.country", {
|
||||
header: "Country",
|
||||
cell: (info) =>
|
||||
info.getValue()
|
||||
? `${
|
||||
countryCodes.findOne("countryCode" as any, info.getValue())?.flag
|
||||
} ${
|
||||
countries[info.getValue() as unknown as keyof TCountries]?.name
|
||||
} (+${
|
||||
countryCodes.findOne("countryCode" as any, info.getValue())
|
||||
?.countryCallingCode
|
||||
})`
|
||||
: "N/A",
|
||||
}),
|
||||
columnHelper.accessor("demographicInformation.phone", {
|
||||
header: "Phone",
|
||||
cell: (info) => info.getValue() || "N/A",
|
||||
enableSorting: true,
|
||||
}),
|
||||
columnHelper.accessor(
|
||||
(x) =>
|
||||
x.type === "corporate" || x.type === "mastercorporate"
|
||||
? x.demographicInformation?.position
|
||||
: x.demographicInformation?.employment,
|
||||
{
|
||||
id: "employment",
|
||||
header: "Employment",
|
||||
cell: (info) =>
|
||||
(info.row.original.type === "corporate"
|
||||
? info.getValue()
|
||||
: capitalize(info.getValue())) || "N/A",
|
||||
enableSorting: true,
|
||||
}
|
||||
),
|
||||
columnHelper.accessor("lastLogin", {
|
||||
header: "Last Login",
|
||||
cell: (info) =>
|
||||
!!info.getValue()
|
||||
? moment(info.getValue()).format("YYYY-MM-DD HH:mm")
|
||||
: "N/A",
|
||||
}),
|
||||
columnHelper.accessor("demographicInformation.gender", {
|
||||
header: "Gender",
|
||||
cell: (info) => capitalize(info.getValue()) || "N/A",
|
||||
enableSorting: true,
|
||||
}),
|
||||
{
|
||||
header: (
|
||||
<span
|
||||
className="cursor-pointer"
|
||||
onClick={() => setShowDemographicInformation((prev) => !prev)}
|
||||
>
|
||||
Switch
|
||||
</span>
|
||||
),
|
||||
id: "actions",
|
||||
cell: actionColumn,
|
||||
sortable: false,
|
||||
},
|
||||
];
|
||||
|
||||
const defaultColumns = [
|
||||
columnHelper.accessor("name", {
|
||||
header: "Name",
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
canEditUser(row.original) &&
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer",
|
||||
)}
|
||||
onClick={() =>
|
||||
canEditUser(row.original) ? setSelectedUser(row.original) : null
|
||||
}>
|
||||
{getValue()}
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("email", {
|
||||
header: "E-mail",
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
canEditUser(row.original) &&
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer",
|
||||
)}
|
||||
onClick={() => (canEditUser(row.original) ? setSelectedUser(row.original) : null)}>
|
||||
{getValue()}
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("type", {
|
||||
header: "Type",
|
||||
cell: (info) => USER_TYPE_LABELS[info.getValue()],
|
||||
}),
|
||||
columnHelper.accessor("studentID", {
|
||||
header: "Student ID",
|
||||
cell: (info) => info.getValue() || "N/A",
|
||||
}),
|
||||
columnHelper.accessor("entities", {
|
||||
header: "Entities",
|
||||
cell: ({ getValue }) => mapBy(getValue(), 'label').join(', '),
|
||||
}),
|
||||
columnHelper.accessor("subscriptionExpirationDate", {
|
||||
header: "Expiration",
|
||||
cell: (info) => (
|
||||
<span className={clsx(info.getValue() ? expirationDateColor(moment(info.getValue()).toDate()) : "")}>
|
||||
{!info.getValue() ? "No expiry date" : moment(info.getValue()).format("DD/MM/YYYY")}
|
||||
</span>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("isVerified", {
|
||||
header: "Verified",
|
||||
cell: (info) => (
|
||||
<div className="flex gap-3 items-center text-mti-gray-dim text-sm self-center">
|
||||
<div
|
||||
className={clsx(
|
||||
"w-6 h-6 rounded-md flex items-center justify-center border border-mti-purple-light bg-white",
|
||||
"transition duration-300 ease-in-out",
|
||||
info.getValue() && "!bg-mti-purple-light ",
|
||||
)}>
|
||||
<BsCheck color="white" className="w-full h-full" />
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
{
|
||||
header: (
|
||||
<span className="cursor-pointer" onClick={() => setShowDemographicInformation((prev) => !prev)}>
|
||||
Switch
|
||||
</span>
|
||||
),
|
||||
id: "actions",
|
||||
cell: actionColumn,
|
||||
sortable: false
|
||||
},
|
||||
];
|
||||
const defaultColumns = [
|
||||
columnHelper.accessor("name", {
|
||||
header: "Name",
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
canEditUser(row.original) &&
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer"
|
||||
)}
|
||||
onClick={() =>
|
||||
canEditUser(row.original) ? setSelectedUser(row.original) : null
|
||||
}
|
||||
>
|
||||
{getValue()}
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("email", {
|
||||
header: "E-mail",
|
||||
cell: ({ row, getValue }) => (
|
||||
<div
|
||||
className={clsx(
|
||||
canEditUser(row.original) &&
|
||||
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer"
|
||||
)}
|
||||
onClick={() =>
|
||||
canEditUser(row.original) ? setSelectedUser(row.original) : null
|
||||
}
|
||||
>
|
||||
{getValue()}
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("type", {
|
||||
header: "Type",
|
||||
cell: (info) => USER_TYPE_LABELS[info.getValue()],
|
||||
}),
|
||||
columnHelper.accessor("studentID", {
|
||||
header: "Student ID",
|
||||
cell: (info) => info.getValue() || "N/A",
|
||||
}),
|
||||
columnHelper.accessor("entities", {
|
||||
header: "Entities",
|
||||
cell: ({ getValue }) => mapBy(getValue(), "label").join(", "),
|
||||
}),
|
||||
columnHelper.accessor("subscriptionExpirationDate", {
|
||||
header: "Expiration",
|
||||
cell: (info) => (
|
||||
<span
|
||||
className={clsx(
|
||||
info.getValue()
|
||||
? expirationDateColor(moment(info.getValue()).toDate())
|
||||
: ""
|
||||
)}
|
||||
>
|
||||
{!info.getValue()
|
||||
? "No expiry date"
|
||||
: moment(info.getValue()).format("DD/MM/YYYY")}
|
||||
</span>
|
||||
),
|
||||
}),
|
||||
columnHelper.accessor("isVerified", {
|
||||
header: "Verified",
|
||||
cell: (info) => (
|
||||
<div className="flex gap-3 items-center text-mti-gray-dim text-sm self-center">
|
||||
<div
|
||||
className={clsx(
|
||||
"w-6 h-6 rounded-md flex items-center justify-center border border-mti-purple-light bg-white",
|
||||
"transition duration-300 ease-in-out",
|
||||
info.getValue() && "!bg-mti-purple-light "
|
||||
)}
|
||||
>
|
||||
<BsCheck color="white" className="w-full h-full" />
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
}),
|
||||
{
|
||||
header: (
|
||||
<span
|
||||
className="cursor-pointer"
|
||||
onClick={() => setShowDemographicInformation((prev) => !prev)}
|
||||
>
|
||||
Switch
|
||||
</span>
|
||||
),
|
||||
id: "actions",
|
||||
cell: actionColumn,
|
||||
sortable: false,
|
||||
},
|
||||
];
|
||||
|
||||
const downloadExcel = (rows: WithLabeledEntities<User>[]) => {
|
||||
if (entitiesDownloadUsers.length === 0) return toast.error("You are not allowed to download the user list.")
|
||||
const downloadExcel = (rows: WithLabeledEntities<User>[]) => {
|
||||
if (entitiesDownloadUsers.length === 0)
|
||||
return toast.error("You are not allowed to download the user list.");
|
||||
|
||||
const allowedRows = rows.filter(r => mapBy(r.entities, 'id').some(e => mapBy(entitiesDownloadUsers, 'id').includes(e)))
|
||||
const csv = exportListToExcel(allowedRows);
|
||||
const allowedRows = rows.filter((r) =>
|
||||
mapBy(r.entities, "id").some((e) =>
|
||||
mapBy(entitiesDownloadUsers, "id").includes(e)
|
||||
)
|
||||
);
|
||||
const csv = exportListToExcel(allowedRows);
|
||||
|
||||
const element = document.createElement("a");
|
||||
const file = new Blob([csv], { type: "text/csv" });
|
||||
element.href = URL.createObjectURL(file);
|
||||
element.download = "users.csv";
|
||||
document.body.appendChild(element);
|
||||
element.click();
|
||||
document.body.removeChild(element);
|
||||
};
|
||||
const element = document.createElement("a");
|
||||
const file = new Blob([csv], { type: "text/csv" });
|
||||
element.href = URL.createObjectURL(file);
|
||||
element.download = "users.csv";
|
||||
document.body.appendChild(element);
|
||||
element.click();
|
||||
document.body.removeChild(element);
|
||||
};
|
||||
|
||||
const viewStudentFilter = (x: User) => x.type === "student";
|
||||
const viewTeacherFilter = (x: User) => x.type === "teacher";
|
||||
const belongsToAdminFilter = (x: User) => x.entities.some(({ id }) => mapBy(selectedUser?.entities || [], 'id').includes(id));
|
||||
const viewStudentFilter = (x: User) => x.type === "student";
|
||||
const viewTeacherFilter = (x: User) => x.type === "teacher";
|
||||
const belongsToAdminFilter = (x: User) =>
|
||||
x.entities.some(({ id }) =>
|
||||
mapBy(selectedUser?.entities || [], "id").includes(id)
|
||||
);
|
||||
|
||||
const viewStudentFilterBelongsToAdmin = (x: User) => viewStudentFilter(x) && belongsToAdminFilter(x);
|
||||
const viewTeacherFilterBelongsToAdmin = (x: User) => viewTeacherFilter(x) && belongsToAdminFilter(x);
|
||||
const viewStudentFilterBelongsToAdmin = (x: User) =>
|
||||
viewStudentFilter(x) && belongsToAdminFilter(x);
|
||||
const viewTeacherFilterBelongsToAdmin = (x: User) =>
|
||||
viewTeacherFilter(x) && belongsToAdminFilter(x);
|
||||
|
||||
const renderUserCard = (selectedUser: User) => {
|
||||
const studentsFromAdmin = users.filter(viewStudentFilterBelongsToAdmin);
|
||||
const teachersFromAdmin = users.filter(viewTeacherFilterBelongsToAdmin);
|
||||
return (
|
||||
<div className="w-full flex flex-col gap-8">
|
||||
<UserCard
|
||||
maxUserAmount={0}
|
||||
loggedInUser={user}
|
||||
onViewStudents={
|
||||
(selectedUser.type === "corporate" || selectedUser.type === "teacher") && studentsFromAdmin.length > 0
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-students",
|
||||
filter: viewStudentFilter,
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: belongsToAdminFilter,
|
||||
});
|
||||
const renderUserCard = (selectedUser: User) => {
|
||||
const studentsFromAdmin = users.filter(viewStudentFilterBelongsToAdmin);
|
||||
const teachersFromAdmin = users.filter(viewTeacherFilterBelongsToAdmin);
|
||||
return (
|
||||
<div className="w-full flex flex-col gap-8">
|
||||
<UserCard
|
||||
maxUserAmount={0}
|
||||
loggedInUser={user}
|
||||
onViewStudents={
|
||||
(selectedUser.type === "corporate" ||
|
||||
selectedUser.type === "teacher") &&
|
||||
studentsFromAdmin.length > 0
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-students",
|
||||
filter: viewStudentFilter,
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: belongsToAdminFilter,
|
||||
});
|
||||
|
||||
router.push("/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onViewTeachers={
|
||||
(selectedUser.type === "corporate" || selectedUser.type === "student") && teachersFromAdmin.length > 0
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-teachers",
|
||||
filter: viewTeacherFilter,
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: belongsToAdminFilter,
|
||||
});
|
||||
router.push("/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onViewTeachers={
|
||||
(selectedUser.type === "corporate" ||
|
||||
selectedUser.type === "student") &&
|
||||
teachersFromAdmin.length > 0
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-teachers",
|
||||
filter: viewTeacherFilter,
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: belongsToAdminFilter,
|
||||
});
|
||||
|
||||
router.push("/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onViewCorporate={
|
||||
selectedUser.type === "teacher" || selectedUser.type === "student"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-corporate",
|
||||
filter: (x: User) => x.type === "corporate",
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: belongsToAdminFilter
|
||||
});
|
||||
router.push("/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onViewCorporate={
|
||||
selectedUser.type === "teacher" || selectedUser.type === "student"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-corporate",
|
||||
filter: (x: User) => x.type === "corporate",
|
||||
});
|
||||
appendUserFilters({
|
||||
id: "belongs-to-admin",
|
||||
filter: belongsToAdminFilter,
|
||||
});
|
||||
|
||||
router.push("/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onClose={(shouldReload) => {
|
||||
setSelectedUser(undefined);
|
||||
if (shouldReload) reload();
|
||||
}}
|
||||
user={selectedUser}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
router.push("/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onClose={(shouldReload) => {
|
||||
setSelectedUser(undefined);
|
||||
if (shouldReload) reload();
|
||||
}}
|
||||
user={selectedUser}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{renderHeader && renderHeader(displayUsers.length)}
|
||||
<div className="w-full">
|
||||
<Modal isOpen={!!selectedUser} onClose={() => setSelectedUser(undefined)}>
|
||||
{selectedUser && renderUserCard(selectedUser)}
|
||||
</Modal>
|
||||
<Table<WithLabeledEntities<User>>
|
||||
data={displayUsers}
|
||||
columns={(!showDemographicInformation ? defaultColumns : demographicColumns) as any}
|
||||
searchFields={searchFields}
|
||||
onDownload={entitiesDownloadUsers.length > 0 ? downloadExcel : undefined}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
{renderHeader && renderHeader(displayUsers.length)}
|
||||
<div className="w-full">
|
||||
<Modal
|
||||
isOpen={!!selectedUser}
|
||||
onClose={() => setSelectedUser(undefined)}
|
||||
>
|
||||
{selectedUser && renderUserCard(selectedUser)}
|
||||
</Modal>
|
||||
<Table<WithLabeledEntities<User>>
|
||||
data={displayUsers}
|
||||
columns={
|
||||
(!showDemographicInformation
|
||||
? defaultColumns
|
||||
: demographicColumns) as any
|
||||
}
|
||||
searchFields={searchFields}
|
||||
onDownload={
|
||||
entitiesDownloadUsers.length > 0 ? downloadExcel : undefined
|
||||
}
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user