initial commit - code moved to separate repo
This commit is contained in:
270
src/helpers/data.js
Normal file
270
src/helpers/data.js
Normal file
@ -0,0 +1,270 @@
|
||||
|
||||
const common = require('./common');
|
||||
|
||||
async function findPublisher(names, email, select, getAll = false) {
|
||||
// Normalize and split the name if provided
|
||||
let nameParts = names ? names.normalize('NFC').trim().split(/\s+/) : [];
|
||||
|
||||
// Construct the select clause
|
||||
let selectClause = select
|
||||
? select.split(",").reduce((acc, curr) => ({ ...acc, [curr]: true }), {})
|
||||
: { id: true, firstName: true, lastName: true };
|
||||
|
||||
|
||||
// Construct the where clause based on the provided data
|
||||
let whereClause = [];
|
||||
if (nameParts.length > 0) {
|
||||
if (nameParts.length === 1) {
|
||||
// If only one name part is provided, check it against both firstName and lastName
|
||||
whereClause.push({ OR: [{ firstName: nameParts[0] }, { lastName: nameParts[0] }] });
|
||||
} else if (nameParts.length === 2) {
|
||||
// If two name parts are provided, check combinations of firstName and lastName
|
||||
whereClause.push({ firstName: nameParts[0], lastName: nameParts[1] });
|
||||
whereClause.push({ firstName: nameParts[1], lastName: nameParts[0] });
|
||||
} else if (nameParts.length === 3) {
|
||||
// If three name parts are provided, consider the middle name part of first or last name
|
||||
whereClause.push({ firstName: `${nameParts[0]} ${nameParts[1]}`, lastName: nameParts[2] });
|
||||
whereClause.push({ firstName: nameParts[0], lastName: `${nameParts[1]} ${nameParts[2]}` });
|
||||
} else if (nameParts.length > 3) {
|
||||
// Join all parts except the last as the first name, and consider the last part as the last name
|
||||
const firstName = nameParts.slice(0, -1).join(' ');
|
||||
const lastName = nameParts.slice(-1).join(' ');
|
||||
whereClause.push({ firstName: firstName, lastName: lastName });
|
||||
|
||||
// Alternative case: First part as first name, and join the rest as the last name
|
||||
const altFirstName = nameParts.slice(0, 1).join(' ');
|
||||
const altLastName = nameParts.slice(1).join(' ');
|
||||
whereClause.push({ firstName: altFirstName, lastName: altLastName });
|
||||
}
|
||||
}
|
||||
|
||||
if (email) {
|
||||
whereClause.push({ email: email });
|
||||
}
|
||||
|
||||
if (whereClause.length === 0) {
|
||||
return null; // No search criteria provided
|
||||
}
|
||||
|
||||
|
||||
const prisma = common.getPrismaClient();
|
||||
// let publisher = await prisma.publisher.findFirst({
|
||||
// select: selectClause,
|
||||
// where: { OR: whereClause }
|
||||
// });
|
||||
// Retrieve all matching records
|
||||
try {
|
||||
let result = await prisma.publisher.findMany({
|
||||
select: selectClause,
|
||||
where: { OR: whereClause }
|
||||
});
|
||||
|
||||
// If getAll is false, take only the first record
|
||||
if (!getAll && result.length > 0) {
|
||||
result = result.length > 0 ? [result[0]] : [];
|
||||
}
|
||||
if (result.length === 0 && names) {
|
||||
console.log("No publisher found, trying fuzzy search for '" + names + "'- email: '" + email + "'");
|
||||
const publishers = await prisma.publisher.findMany();
|
||||
result = await common.fuzzySearch(publishers, names, 0.90);
|
||||
console.log("Fuzzy search result: " + result?.firstName + " " + result?.lastName + " - " + result?.email);
|
||||
}
|
||||
//always return an array
|
||||
result = result || [];
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error("Error finding publisher: ", error);
|
||||
throw error; // Rethrow the error or handle it as needed
|
||||
}
|
||||
}
|
||||
|
||||
async function findPublisherAvailability(publisherId, date) {
|
||||
|
||||
const prisma = common.getPrismaClient();
|
||||
const dayOfWeek = common.getDayOfWeekNameEnEnum(date); // Assuming common.getDayOfWeekNameEnEnum returns the day of week
|
||||
//const weekOfMonth = common.getWeekOfMonth(date); // Assuming common.getWeekOfMonth returns the week of month
|
||||
date = new Date(date); // Convert to date object if not already
|
||||
const hours = date.getHours();
|
||||
const minutes = date.getMinutes();
|
||||
|
||||
const potentialAvailabilities = await prisma.availability.findMany({
|
||||
where: {
|
||||
publisherId: publisherId,
|
||||
OR: [
|
||||
{
|
||||
// Exact date match
|
||||
startTime: {
|
||||
gte: new Date(date.setHours(0, 0, 0, 0)),
|
||||
lt: new Date(date.setHours(23, 59, 59, 999))
|
||||
}
|
||||
},
|
||||
{
|
||||
// Correct day of week and before the date, with endDate consideration
|
||||
dayofweek: dayOfWeek,
|
||||
OR: [
|
||||
{
|
||||
endDate: null
|
||||
},
|
||||
{
|
||||
endDate: {
|
||||
gt: date
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
// Filter the results based on time and other criteria when not exact date match
|
||||
const availability = potentialAvailabilities.find(avail => {
|
||||
const availStartHours = avail.startTime.getHours();
|
||||
const availStartMinutes = avail.startTime.getMinutes();
|
||||
const availEndHours = avail.endTime.getHours();
|
||||
const availEndMinutes = avail.endTime.getMinutes();
|
||||
|
||||
const isAfterStartTime = hours > availStartHours || (hours === availStartHours && minutes >= availStartMinutes);
|
||||
const isBeforeEndTime = hours < availEndHours || (hours === availEndHours && minutes <= availEndMinutes);
|
||||
// check day of week if not null
|
||||
const isCorrectDayOfWeek = avail.repeatWeekly ? avail.startTime.getDay() === date.getDay() : true;
|
||||
const isExactDateMatch = avail.dayOfMonth ? avail.startTime.toDateString() === date.toDateString() : true;
|
||||
const isBeforeEndDate = avail.repeatWeekly ? true : avail.endTime > date;
|
||||
//const isCorrectWeekOfMonth = avail.repeatWeekly ? true : avail.weekOfMonth === weekOfMonth;
|
||||
|
||||
return isAfterStartTime && isBeforeEndTime && isCorrectDayOfWeek && isExactDateMatch && isBeforeEndDate;
|
||||
});
|
||||
|
||||
return availability;
|
||||
}
|
||||
|
||||
|
||||
async function getAvailabilities(userId) {
|
||||
const prismaClient = common.getPrismaClient();
|
||||
const items = await prismaClient.availability.findMany({
|
||||
where: {
|
||||
publisherId: userId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
isactive: true,
|
||||
isFromPreviousAssignment: true,
|
||||
dayofweek: true,
|
||||
dayOfMonth: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
repeatWeekly: true,
|
||||
endDate: true,
|
||||
publisher: {
|
||||
select: {
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
// Convert Date objects to ISO strings
|
||||
const serializableItems = items.map(item => ({
|
||||
...item,
|
||||
startTime: item.startTime.toISOString(),
|
||||
endTime: item.endTime.toISOString(),
|
||||
name: common.getTimeFomatted(item.startTime) + "-" + common.getTimeFomatted(item.endTime),
|
||||
//endDate can be null
|
||||
endDate: item.endDate ? item.endDate.toISOString() : null,
|
||||
type: 'availability',
|
||||
// Convert other Date fields similarly if they exist
|
||||
}));
|
||||
|
||||
/*model Assignment {
|
||||
id Int @id @default(autoincrement())
|
||||
shift Shift @relation(fields: [shiftId], references: [id], onDelete: Cascade)
|
||||
shiftId Int
|
||||
publisher Publisher @relation(fields: [publisherId], references: [id], onDelete: Cascade)
|
||||
publisherId String
|
||||
isactive Boolean @default(true)
|
||||
isConfirmed Boolean @default(false)
|
||||
isWithTransport Boolean @default(false)
|
||||
Report Report[]
|
||||
}*/
|
||||
//get assignments for this user
|
||||
const assignments = await prismaClient.assignment.findMany({
|
||||
where: {
|
||||
publisherId: userId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
isTentative: true,
|
||||
isConfirmed: true,
|
||||
isWithTransport: true,
|
||||
shift: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
startTime: true,
|
||||
endTime: true,
|
||||
//select all assigned publishers names as name - comma separated
|
||||
assignments: {
|
||||
select: {
|
||||
publisher: {
|
||||
select: {
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const serializableAssignments = assignments.map(item => ({
|
||||
...item,
|
||||
startTime: item.shift.startTime.toISOString(),
|
||||
endTime: item.shift.endTime.toISOString(),
|
||||
// name: item.shift.publishers.map(p => p.firstName + " " + p.lastName).join(", "),
|
||||
//name: item.shift.assignments.map(a => a.publisher.firstName[0] + " " + a.publisher.lastName).join(", "),
|
||||
name: common.getTimeFomatted(new Date(item.shift.startTime)) + "-" + common.getTimeFomatted(new Date(item.shift.endTime)),
|
||||
type: 'assignment',
|
||||
//delete shift object
|
||||
shift: null,
|
||||
publisher: { id: userId }
|
||||
}));
|
||||
|
||||
serializableItems.push(...serializableAssignments);
|
||||
|
||||
return serializableItems;
|
||||
|
||||
}
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
async function runSqlFile(filePath) {
|
||||
|
||||
const prisma = common.getPrismaClient();
|
||||
// Seed the database with some sample data
|
||||
try {
|
||||
// Read the SQL file
|
||||
const sql = fs.readFileSync(filePath, { encoding: 'utf-8' });
|
||||
|
||||
// Split the file content by semicolon and filter out empty statements
|
||||
const statements = sql.split(';').map(s => s.trim()).filter(s => s.length);
|
||||
|
||||
// Execute each statement
|
||||
for (const statement of statements) {
|
||||
await prisma.$executeRawUnsafe(statement);
|
||||
}
|
||||
console.log('SQL script executed successfully.');
|
||||
} catch (error) {
|
||||
console.error('Error executing SQL script:', error);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
findPublisher,
|
||||
findPublisherAvailability,
|
||||
runSqlFile,
|
||||
getAvailabilities
|
||||
};
|
Reference in New Issue
Block a user