feat: add bulk import endpoint
This commit is contained in:
@@ -518,3 +518,96 @@ export async function searchPermitByAddress(address: string) {
|
||||
.sort({ score: { $meta: "textScore" } })
|
||||
.limit(1);
|
||||
}
|
||||
|
||||
export async function bulkImport(csvData: Object[], user: AuthenticatedUser) {
|
||||
const allowedFields = [
|
||||
"Permit Number",
|
||||
"County",
|
||||
"Client",
|
||||
"Address",
|
||||
"Open Date",
|
||||
"County Status",
|
||||
"Record Type",
|
||||
"Lot",
|
||||
"Block",
|
||||
"Job Number",
|
||||
"Community Name",
|
||||
];
|
||||
|
||||
const failed = [];
|
||||
const created = [];
|
||||
|
||||
for (const [index, record] of csvData.entries()) {
|
||||
try {
|
||||
if (!record["Permit Number"]) {
|
||||
failed.push(index);
|
||||
continue;
|
||||
}
|
||||
|
||||
const permitInDb = await permitModel.findOne({
|
||||
permitNumber: record["Permit Number"],
|
||||
});
|
||||
|
||||
if (!permitInDb) {
|
||||
let clientData = null;
|
||||
let countyData = null;
|
||||
|
||||
if (record["Client"]) {
|
||||
const clientInDb = await orgModel.findOne({ name: record["Client"] });
|
||||
if (clientInDb) {
|
||||
clientData = {
|
||||
id: clientInDb._id,
|
||||
pid: clientInDb.pid,
|
||||
licenseNumber: clientInDb.licenseNumber,
|
||||
name: clientInDb.name,
|
||||
avatar: clientInDb.avatar,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (record["County"]) {
|
||||
const countyInDb = await orgModel.findOne({ name: record["County"] });
|
||||
if (countyInDb) {
|
||||
countyData = {
|
||||
id: countyInDb._id,
|
||||
pid: countyInDb.pid,
|
||||
name: countyInDb.name,
|
||||
avatar: countyInDb.avatar,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const newPermit = await permitModel.create({
|
||||
tenantId: user.tenantId,
|
||||
pid: generateId(),
|
||||
permitNumber: record["Permit Number"],
|
||||
county: countyData,
|
||||
client: clientData?.id,
|
||||
clientData: clientData,
|
||||
cleanStatus: record["County Status"],
|
||||
address: record["Address"],
|
||||
recordType: record["Record Type"],
|
||||
lot: record["Lot"],
|
||||
block: record["Block"],
|
||||
jobNumber: record["Job Number"],
|
||||
communityName: record["Community Name"],
|
||||
createdAt: new Date(),
|
||||
createdBy: user.userId,
|
||||
importFlag: true,
|
||||
});
|
||||
|
||||
const populatedPermit = await newPermit.populate({
|
||||
path: "assignedTo createdBy",
|
||||
select: "pid name avatar",
|
||||
});
|
||||
|
||||
created.push(populatedPermit);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
failed.push(index + 2);
|
||||
}
|
||||
}
|
||||
|
||||
return { created, failed, allowedFields };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user