ENCOA-277, ENCOA-276, ENCOA-282, ENCOA-283

This commit is contained in:
Carlos-Mesquita
2024-12-21 19:23:53 +00:00
parent f6d387ce2d
commit 98a1636d0c
31 changed files with 2513 additions and 194 deletions

View File

@@ -21,6 +21,11 @@ import { PermissionType } from "@/interfaces/permissions";
import usePermissions from "@/hooks/usePermissions";
import { EntityWithRoles } from "@/interfaces/entity";
import Select from "@/components/Low/Select";
import CodeGenImportSummary, { ExcelCodegenDuplicatesMap } from "@/components/ImportSummaries/Codegen";
import { FaFileDownload } from "react-icons/fa";
import { IoInformationCircleOutline } from "react-icons/io5";
import { HiOutlineDocumentText } from "react-icons/hi";
import CodegenTable from "@/components/Tables/CodeGenTable";
const EMAIL_REGEX = new RegExp(/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/);
@@ -74,7 +79,9 @@ export default function BatchCodeGenerator({ user, users, entities = [], permiss
const [isExpiryDateEnabled, setIsExpiryDateEnabled] = useState(true);
const [type, setType] = useState<Type>("student");
const [showHelp, setShowHelp] = useState(false);
const [entity, setEntity] = useState((entities || [])[0]?.id || undefined)
const [entity, setEntity] = useState((entities || [])[0]?.id || undefined);
const [parsedExcel, setParsedExcel] = useState<{ rows?: any[]; errors?: any[] }>({ rows: undefined, errors: undefined });
const [duplicatedRows, setDuplicatedRows] = useState<{ duplicates: ExcelCodegenDuplicatesMap, count: number }>();
const { openFilePicker, filesContent, clear } = useFilePicker({
accept: ".xlsx",
@@ -86,46 +93,123 @@ export default function BatchCodeGenerator({ user, users, entities = [], permiss
if (!isExpiryDateEnabled) setExpiryDate(null);
}, [isExpiryDateEnabled]);
const schema = {
'First Name': {
prop: 'firstName',
type: String,
required: true,
validate: (value: string) => {
if (!value || value.trim() === '') {
throw new Error('First Name cannot be empty')
}
return true
}
},
'Last Name': {
prop: 'lastName',
type: String,
required: true,
validate: (value: string) => {
if (!value || value.trim() === '') {
throw new Error('Last Name cannot be empty')
}
return true
}
},
'Passport/National ID': {
prop: 'passport_id',
type: String,
required: true,
validate: (value: string) => {
if (!value || value.trim() === '') {
throw new Error('Passport/National ID cannot be empty')
}
return true
}
},
'E-mail': {
prop: 'email',
required: true,
type: (value: any) => {
if (!value || value.trim() === '') {
throw new Error('Email cannot be empty')
}
if (!EMAIL_REGEX.test(value.trim())) {
throw new Error('Invalid Email')
}
return value
}
}
}
useEffect(() => {
if (filesContent.length > 0) {
const file = filesContent[0];
readXlsxFile(file.content).then((rows) => {
try {
const information = uniqBy(
rows
.map((row) => {
const [firstName, lastName, country, passport_id, email, phone] = row as string[];
return EMAIL_REGEX.test(email.toString().trim())
? {
email: email.toString().trim().toLowerCase(),
name: `${firstName ?? ""} ${lastName ?? ""}`.trim(),
passport_id: passport_id?.toString().trim() || undefined,
}
: undefined;
})
.filter((x) => !!x) as typeof infos,
(x) => x.email,
);
if (information.length === 0) {
toast.error(
"Please upload an Excel file containing user information, one per line! All already registered e-mails have also been ignored!",
);
return clear();
}
setInfos(information);
} catch {
toast.error(
"Please upload an Excel file containing user information, one per line! All already registered e-mails have also been ignored!",
);
return clear();
}
});
readXlsxFile(
file.content, { schema, ignoreEmptyRows: false })
.then((data) => {
setParsedExcel(data)
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [filesContent]);
useEffect(() => {
if (parsedExcel.rows) {
const duplicates: ExcelCodegenDuplicatesMap = {
email: new Map(),
passport_id: new Map(),
};
const duplicateValues = new Set<string>();
const duplicateRowIndices = new Set<number>();
const errorRowIndices = new Set(
parsedExcel.errors?.map(error => error.row) || []
);
parsedExcel.rows.forEach((row, index) => {
if (!errorRowIndices.has(index + 2)) {
(Object.keys(duplicates) as Array<keyof ExcelCodegenDuplicatesMap>).forEach(field => {
if (row !== null) {
const value = row[field];
if (value) {
if (!duplicates[field].has(value)) {
duplicates[field].set(value, [index + 2]);
} else {
const existingRows = duplicates[field].get(value);
if (existingRows) {
existingRows.push(index + 2);
duplicateValues.add(value);
existingRows.forEach(rowNum => duplicateRowIndices.add(rowNum));
}
}
}
}
});
}
});
const info = parsedExcel.rows
.map((row, index) => {
if (errorRowIndices.has(index + 2) || duplicateRowIndices.has(index + 2) || row === null) {
return undefined;
}
const { firstName, lastName, studentID, passport_id, email, phone, group, country } = row;
if (!email || !EMAIL_REGEX.test(email.toString().trim())) {
return undefined;
}
return {
email: email.toString().trim().toLowerCase(),
name: `${firstName ?? ""} ${lastName ?? ""}`.trim(),
passport_id: passport_id?.toString().trim() || undefined,
};
}).filter((x) => !!x) as typeof infos;
setInfos(info);
}
}, [entity, parsedExcel, type]);
const generateAndInvite = async () => {
const newUsers = infos.filter((x) => !users.map((u) => u.email).includes(x.email));
const existingUsers = infos
@@ -199,40 +283,106 @@ export default function BatchCodeGenerator({ user, users, entities = [], permiss
});
};
const handleTemplateDownload = () => {
const fileName = "BatchCodeTemplate.xlsx";
const url = `https://firebasestorage.googleapis.com/v0/b/encoach-staging.appspot.com/o/import_templates%2F${fileName}?alt=media&token=b771a535-bf95-4060-889c-a086df65d480`;
const link = document.createElement('a');
link.href = url;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
return (
<>
<Modal isOpen={showHelp} onClose={() => setShowHelp(false)} title="Excel File Format">
<div className="mt-4 flex flex-col gap-2">
<span>Please upload an Excel file with the following format:</span>
<table className="w-full">
<thead>
<tr>
<th className="border border-neutral-200 px-2 py-1">First Name</th>
<th className="border border-neutral-200 px-2 py-1">Last Name</th>
<th className="border border-neutral-200 px-2 py-1">Country</th>
<th className="border border-neutral-200 px-2 py-1">Passport/National ID</th>
<th className="border border-neutral-200 px-2 py-1">E-mail</th>
<th className="border border-neutral-200 px-2 py-1">Phone Number</th>
</tr>
</thead>
</table>
<span className="mt-4">
<b>Notes:</b>
<ul>
<li>- All incorrect e-mails will be ignored;</li>
<li>- All already registered e-mails will be ignored;</li>
<li>- You may have a header row with the format above, however, it is not necessary;</li>
<li>- All of the e-mails in the file will receive an e-mail to join EnCoach with the role selected below.</li>
</ul>
</span>
</div>
<Modal isOpen={showHelp} onClose={() => setShowHelp(false)}>
<>
<div className="flex font-bold text-xl justify-center text-gray-700"><span>Excel File Format</span></div>
<div className="mt-4 flex flex-col gap-4">
<div className="flex flex-col gap-3 bg-gray-100 rounded-lg p-4">
<div className="flex items-center gap-2">
<HiOutlineDocumentText className={`w-5 h-5 text-mti-purple-light`} />
<h2 className="text-lg font-semibold">
The uploaded document must:
</h2>
</div>
<ul className="flex flex-col pl-10 gap-2">
<li className="text-gray-700 list-disc">
be an Excel .xlsx document.
</li>
<li className="text-gray-700 list-disc">
only have a single spreadsheet with the following <b>exact same name</b> columns:
<div className="py-4 pr-4">
<table className="w-full bg-white">
<thead>
<tr>
<th className="border border-neutral-200 px-2 py-1">First Name</th>
<th className="border border-neutral-200 px-2 py-1">Last Name</th>
<th className="border border-neutral-200 px-2 py-1">Passport/National ID</th>
<th className="border border-neutral-200 px-2 py-1">E-mail</th>
</tr>
</thead>
</table>
</div>
</li>
</ul>
</div>
<div className="flex flex-col gap-3 bg-gray-100 rounded-lg p-4">
<div className="flex items-center gap-2">
<IoInformationCircleOutline className={`w-5 h-5 text-mti-purple-light`} />
<h2 className="text-lg font-semibold">
Note that:
</h2>
</div>
<ul className="flex flex-col pl-10 gap-2">
<li className="text-gray-700 list-disc">
all incorrect e-mails will be ignored.
</li>
<li className="text-gray-700 list-disc">
all already registered e-mails will be ignored.
</li>
<li className="text-gray-700 list-disc">
all rows which contain duplicate values in the columns: &quot;Passport/National ID&quot;, &quot;E-mail&quot;, will be ignored.
</li>
<li className="text-gray-700 list-disc">
all of the e-mails in the file will receive an e-mail to join EnCoach with the role selected below.
</li>
</ul>
</div>
<div className="bg-gray-100 rounded-lg p-4">
<p className="text-gray-600">
{`The downloadable template is an example of a file that can be imported. Your document doesn't need to be a carbon copy of the template - it can have different styling but it must adhere to the previous requirements.`}
</p>
</div>
<div className="w-full flex justify-between mt-6 gap-8">
<Button color="purple" onClick={() => setShowHelp(false)} variant="outline" className="self-end w-full bg-white">
Close
</Button>
<Button color="purple" onClick={handleTemplateDownload} variant="solid" className="self-end w-full">
<div className="flex items-center gap-2">
<FaFileDownload size={24} />
Download Template
</div>
</Button>
</div>
</div>
</>
</Modal>
<div className="border-mti-gray-platinum flex flex-col gap-4 rounded-xl border p-4">
<div className="flex items-end justify-between">
<label className="text-mti-gray-dim text-base font-normal">Choose an Excel file</label>
<div className="tooltip cursor-pointer" data-tip="Excel File Format" onClick={() => setShowHelp(true)}>
<BsQuestionCircleFill />
</div>
<button
onClick={() => setShowHelp(true)}
className="tooltip cursor-pointer p-1.5 hover:bg-gray-200 rounded-full transition-colors duration-200"
data-tip="Excel File Format"
>
<IoInformationCircleOutline size={24} />
</button>
</div>
<Button onClick={openFilePicker} isLoading={isLoading} disabled={isLoading}>
{filesContent.length > 0 ? filesContent[0].name : "Choose a file"}
@@ -290,6 +440,13 @@ export default function BatchCodeGenerator({ user, users, entities = [], permiss
))}
</select>
)}
{infos.length > 0 && <CodeGenImportSummary infos={infos} parsedExcel={parsedExcel} duplicateRows={duplicatedRows}/>}
{infos.length !== 0 && (
<div className="flex w-full flex-col gap-4">
<span className="text-mti-gray-dim text-base font-normal">Codes will be sent to:</span>
<CodegenTable infos={infos} />
</div>
)}
{checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"], permissions, "createCodes") && (
<Button onClick={generateAndInvite} disabled={infos.length === 0 || (isExpiryDateEnabled ? !expiryDate : false)}>
Generate & Send

View File

@@ -12,16 +12,16 @@ import { checkAccess, getTypesOfUser } from "@/utils/permissions";
import Checkbox from "@/components/Low/Checkbox";
import ReactDatePicker from "react-datepicker";
import clsx from "clsx";
import countryCodes, { CountryData } from "country-codes-list";
import countryCodes from "country-codes-list";
import { User, Type as UserType } from "@/interfaces/user";
import { Type, UserImport } from "../../../interfaces/IUserImport";
import UserTable from "../../../components/UserTable";
import UserTable from "../../../components/Tables/UserTable";
import { EntityWithRoles } from "@/interfaces/entity";
import Select from "@/components/Low/Select";
import { IoInformationCircleOutline } from "react-icons/io5";
import { FaFileDownload } from "react-icons/fa";
import { HiOutlineDocumentText } from "react-icons/hi";
import UserImportSummary, { DuplicatesMap } from "@/components/UserImportSummary";
import UserImportSummary, { ExcelUserDuplicatesMap } from "@/components/ImportSummaries/User";
const EMAIL_REGEX = new RegExp(/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/);
@@ -78,7 +78,7 @@ export default function BatchCreateUser({ user, entities = [], permissions, onFi
const [duplicatedUsers, setDuplicatedUsers] = useState<UserImport[]>([]);
const [newUsers, setNewUsers] = useState<UserImport[]>([]);
const [duplicatedRows, setDuplicatedRows] = useState<{ duplicates: DuplicatesMap, count: number }>();
const [duplicatedRows, setDuplicatedRows] = useState<{ duplicates: ExcelUserDuplicatesMap, count: number }>();
const [isLoading, setIsLoading] = useState(false);
const [expiryDate, setExpiryDate] = useState<Date | null>(
@@ -210,7 +210,7 @@ export default function BatchCreateUser({ user, entities = [], permissions, onFi
useEffect(() => {
if (parsedExcel.rows) {
const duplicates: DuplicatesMap = {
const duplicates: ExcelUserDuplicatesMap = {
studentID: new Map(),
email: new Map(),
passport_id: new Map(),
@@ -225,7 +225,7 @@ export default function BatchCreateUser({ user, entities = [], permissions, onFi
parsedExcel.rows.forEach((row, index) => {
if (!errorRowIndices.has(index + 2)) {
(Object.keys(duplicates) as Array<keyof DuplicatesMap>).forEach(field => {
(Object.keys(duplicates) as Array<keyof ExcelUserDuplicatesMap>).forEach(field => {
if (row !== null) {
const value = row[field];
if (value) {