diff --git a/backend/src/controllers/importController.js b/backend/src/controllers/importController.js index 18b9b54..655b856 100644 --- a/backend/src/controllers/importController.js +++ b/backend/src/controllers/importController.js @@ -200,22 +200,59 @@ export const bulkImportExcelData = async (req, res) => { if (appointments) { for (const row of appointments) { if (!row.FullName) continue; - const docId = row.Doctor?.toString(); - const deptId = row["Department Id"]?.toString(); - if (docId && deptId) { - await prisma.appointment - .create({ - data: { - name: row.FullName.toString(), - mobileNumber: row.Number?.toString() || "", - email: row["Email Id"]?.toString() || null, - message: row.Message?.toString() || null, - date: row.Date ? new Date(row.Date) : new Date(), - doctorId: docId, - departmentId: deptId, - }, - }) - .catch(() => {}); + const doctorName = row.Doctor?.toString(); + const departmentName = row["Department Id"]?.toString(); + + const doctor = await prisma.doctor.findFirst({ + where: { name: doctorName }, + }); + + const department = await prisma.department.findFirst({ + where: { name: departmentName }, + }); + const parseDate = (value) => { + if (!value) return new Date(); + + // Excel numeric date + if (typeof value === "number") { + return new Date((value - 25569) * 86400 * 1000); + } + + if (typeof value === "string") { + const v = value.trim(); + + // Handle DD/MM/YYYY + const ddmmyyyy = /^(\d{2})\/(\d{2})\/(\d{4})$/; + const match = v.match(ddmmyyyy); + + if (match) { + const [_, dd, mm, yyyy] = match; + return new Date(`${yyyy}-${mm}-${dd}`); + } + + // Fallback (ISO or other valid formats) + const d = new Date(v); + + if (!isNaN(d.getTime()) && d.getFullYear() < 2100) { + return d; + } + } + + console.warn("⚠️ Invalid date, using current date:", value); + return new Date(); + }; + if (doctor && department) { + await prisma.appointment.create({ + data: { + name: row.FullName.toString(), + mobileNumber: row.Number?.toString() || "", + email: row["Email Id"]?.toString() || null, + message: row.Message?.toString() || null, + date: parseDate(row.Date), + doctorId: doctor.doctorId, + departmentId: department.departmentId, + }, + }); } } }