ENCOA-281
This commit is contained in:
@@ -6,14 +6,13 @@ import { toast } from "react-toastify";
|
||||
import { useFilePicker } from "use-file-picker";
|
||||
import readXlsxFile from "read-excel-file";
|
||||
import Modal from "@/components/Modal";
|
||||
import { BsQuestionCircleFill } from "react-icons/bs";
|
||||
import { PermissionType } from "@/interfaces/permissions";
|
||||
import moment from "moment";
|
||||
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
|
||||
import Checkbox from "@/components/Low/Checkbox";
|
||||
import ReactDatePicker from "react-datepicker";
|
||||
import clsx from "clsx";
|
||||
import countryCodes from "country-codes-list";
|
||||
import countryCodes, { CountryData } from "country-codes-list";
|
||||
import { User, Type as UserType } from "@/interfaces/user";
|
||||
import { Type, UserImport } from "../../../interfaces/IUserImport";
|
||||
import UserTable from "../../../components/UserTable";
|
||||
@@ -22,6 +21,7 @@ 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";
|
||||
|
||||
const EMAIL_REGEX = new RegExp(/^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$/);
|
||||
|
||||
@@ -71,11 +71,14 @@ interface Props {
|
||||
onFinish: () => void;
|
||||
}
|
||||
|
||||
|
||||
export default function BatchCreateUser({ user, entities = [], permissions, onFinish }: Props) {
|
||||
const [infos, setInfos] = useState<UserImport[]>([]);
|
||||
const [parsedExcel, setParsedExcel] = useState<{ rows?: any[]; errors?: any[] }>({ rows: undefined, errors: undefined });
|
||||
|
||||
const [duplicatedUsers, setDuplicatedUsers] = useState<UserImport[]>([]);
|
||||
const [newUsers, setNewUsers] = useState<UserImport[]>([]);
|
||||
const [duplicatedRows, setDuplicatedRows] = useState<{ duplicates: DuplicatesMap, count: number }>();
|
||||
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [expiryDate, setExpiryDate] = useState<Date | null>(
|
||||
@@ -96,61 +99,187 @@ export default function BatchCreateUser({ user, entities = [], permissions, onFi
|
||||
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
|
||||
}
|
||||
},
|
||||
'Student ID': {
|
||||
prop: 'studentID',
|
||||
type: String,
|
||||
required: true,
|
||||
validate: (value: string) => {
|
||||
if (!value || value.trim() === '') {
|
||||
throw new Error('Student ID 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
|
||||
}
|
||||
},
|
||||
'Phone Number': {
|
||||
prop: 'phone',
|
||||
type: Number,
|
||||
required: true,
|
||||
validate: (value: number) => {
|
||||
if (value === null || value === undefined || String(value).trim() === '') {
|
||||
throw new Error('Phone Number cannot be empty')
|
||||
}
|
||||
return true
|
||||
}
|
||||
},
|
||||
'Classroom Name': {
|
||||
prop: 'group',
|
||||
type: String,
|
||||
required: true,
|
||||
validate: (value: string) => {
|
||||
if (!value || value.trim() === '') {
|
||||
throw new Error('Classroom Name cannot be empty')
|
||||
}
|
||||
return true
|
||||
}
|
||||
},
|
||||
'Country': {
|
||||
prop: 'country',
|
||||
type: (value: any) => {
|
||||
if (!value || value.trim() === '') {
|
||||
throw new Error('Country cannot be empty')
|
||||
}
|
||||
const validCountry = countryCodes.findOne("countryCode" as any, value.toUpperCase()) ||
|
||||
countryCodes.all().find((x) => x.countryNameEn.toLowerCase() === value.toLowerCase());
|
||||
if (!validCountry) {
|
||||
throw new Error('Invalid Country/Country Code')
|
||||
}
|
||||
return validCountry;
|
||||
},
|
||||
required: true
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (filesContent.length > 0) {
|
||||
const file = filesContent[0];
|
||||
readXlsxFile(file.content).then((rows) => {
|
||||
try {
|
||||
const information = uniqBy(
|
||||
rows
|
||||
.map((row) => {
|
||||
const [firstName, lastName, studentID, passport_id, email, phone, group, country] = row as string[];
|
||||
const countryItem =
|
||||
countryCodes.findOne("countryCode" as any, country.toUpperCase()) ||
|
||||
countryCodes.all().find((x) => x.countryNameEn.toLowerCase() === country.toLowerCase());
|
||||
|
||||
return EMAIL_REGEX.test(email.toString().trim())
|
||||
? {
|
||||
email: email.toString().trim().toLowerCase(),
|
||||
name: `${firstName ?? ""} ${lastName ?? ""}`.trim(),
|
||||
type: type,
|
||||
passport_id: passport_id?.toString().trim() || undefined,
|
||||
groupName: group,
|
||||
studentID,
|
||||
entity,
|
||||
demographicInformation: {
|
||||
country: countryItem?.countryCode,
|
||||
passport_id: passport_id?.toString().trim() || undefined,
|
||||
phone: phone.toString(),
|
||||
},
|
||||
}
|
||||
: 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 (e) {
|
||||
console.log(e)
|
||||
|
||||
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: DuplicatesMap = {
|
||||
studentID: new Map(),
|
||||
email: new Map(),
|
||||
passport_id: new Map(),
|
||||
phone: 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 DuplicatesMap>).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 infos = 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(),
|
||||
type: type,
|
||||
passport_id: passport_id?.toString().trim() || undefined,
|
||||
groupName: group,
|
||||
studentID,
|
||||
entity,
|
||||
demographicInformation: {
|
||||
country: country?.countryCode,
|
||||
passport_id: passport_id?.toString().trim() || undefined,
|
||||
phone: phone.toString(),
|
||||
},
|
||||
} as UserImport;
|
||||
})
|
||||
.filter((item): item is UserImport => item !== undefined);
|
||||
|
||||
setDuplicatedRows({ duplicates, count: duplicateRowIndices.size });
|
||||
setInfos(infos);
|
||||
setNewUsers([]);
|
||||
setDuplicatedUsers([]);
|
||||
}
|
||||
}, [entity, parsedExcel, type]);
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
const crossReferenceEmails = async () => {
|
||||
try {
|
||||
@@ -185,12 +314,12 @@ export default function BatchCreateUser({ user, entities = [], permissions, onFi
|
||||
if (!confirm(`You are about to ${[newUsersSentence, existingUsersSentence].filter((x) => !!x).join(" and ")}, are you sure you want to continue?`))
|
||||
return;
|
||||
|
||||
Promise.all(newUsers.map(async (u) => await axios.post(`/api/invites`, {to: u.id, entity, from: user.id})))
|
||||
Promise.all(newUsers.map(async (u) => await axios.post(`/api/invites`, { to: u.id, entity, from: user.id })))
|
||||
.then(() => toast.success(`Successfully invited ${newUsers.length} registered student(s)!`))
|
||||
.finally(() => {
|
||||
if (newUsers.length === 0) setIsLoading(false);
|
||||
});
|
||||
|
||||
|
||||
if (newUsers.length > 0) {
|
||||
setIsLoading(true);
|
||||
|
||||
@@ -246,7 +375,7 @@ export default function BatchCreateUser({ user, entities = [], permissions, onFi
|
||||
be an Excel .xlsx document.
|
||||
</li>
|
||||
<li className="text-gray-700 list-disc">
|
||||
only have a single spreadsheet with only the following 8 columns in the <b>same order</b>:
|
||||
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>
|
||||
@@ -281,7 +410,7 @@ export default function BatchCreateUser({ user, entities = [], permissions, onFi
|
||||
all already registered e-mails will be ignored.
|
||||
</li>
|
||||
<li className="text-gray-700 list-disc">
|
||||
the spreadsheet may have a header row with the format above, however, it is not necessary as long the columns are in the <b>right order</b>.
|
||||
all rows which contain duplicate values in the columns: "Student ID", "Passport/National ID", "E-mail", 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.
|
||||
@@ -380,21 +509,16 @@ export default function BatchCreateUser({ user, entities = [], permissions, onFi
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
{parsedExcel.rows !== undefined && <UserImportSummary parsedExcel={parsedExcel} newUsers={newUsers} enlistedUsers={duplicatedUsers} duplicateRows={duplicatedRows} />}
|
||||
{newUsers.length !== 0 && (
|
||||
<div className="flex w-full flex-col gap-4">
|
||||
<span className="text-mti-gray-dim text-base font-normal">New Users:</span>
|
||||
<UserTable users={newUsers} />
|
||||
</div>
|
||||
)}
|
||||
{duplicatedUsers.length !== 0 && (
|
||||
<div className="flex w-full flex-col gap-4">
|
||||
<span className="text-mti-gray-dim text-base font-normal">Duplicated Users:</span>
|
||||
<UserTable users={duplicatedUsers} />
|
||||
</div>
|
||||
)}
|
||||
{(duplicatedUsers.length !== 0 && newUsers.length === 0) && <span className="text-red-500 font-bold">The imported .csv only contains duplicated users!</span>}
|
||||
<Button className="my-auto mt-4" onClick={makeUsers} disabled={newUsers.length === 0}>
|
||||
Create {newUsers.length !== 0 ? `${newUsers.length} New Users` : ''}
|
||||
Create {newUsers.length !== 0 ? `${newUsers.length} new user${newUsers.length > 1 ? 's' : ''}` : ''}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
|
||||
Reference in New Issue
Block a user