Skip to content

Commit

Permalink
Merge pull request #103 from manipalutsav/feature-praciceSlot-endpoin…
Browse files Browse the repository at this point in the history
…ts-update

feature practice slot sort by date
  • Loading branch information
Pawardevelops authored Mar 28, 2024
2 parents fe404d3 + 45aafe0 commit c984e97
Show file tree
Hide file tree
Showing 4 changed files with 212 additions and 37 deletions.
104 changes: 104 additions & 0 deletions scripts/slotting.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
const dotenv = require("dotenv");
const mongoose = require("mongoose");

var ObjectId = require('mongodb').ObjectId;
const Slot2Model = require("../src/models/Slot2");
const EventModel = require("../src/models/Event");
const RoundModel = require("../src/models/Round");
const TeamModel = require("../src/models/Team");

dotenv.config();


const connectToDatabase = async () => {
try {
const ip = process.env.MONGODB_IP || "127.0.0.1";
const port = process.env.MONGODB_PORT;
const host = ip + ":" + port;
const uri = "mongodb://" + host;
console.log(uri)
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: process.env.MONGODB_DATABASE,
};

console.log(`Connecting to ${uri}`);
await mongoose.connect(uri, options);
console.log("Connected to MongoDB!");
} catch (error) {
console.error("Error connecting to MongoDB:", error);
process.exit(1);
}
};

// Function to find or create a slot for a team in a round
const findOrCreateSlot = async (roundId, collegeId, teamIndex) => {
try {
// Find the maximum slot number for the specified college and team index
const slots = await Slot2Model.find({ round: roundId });

const newSlotNumber = slots.reduce((max, slot) => Math.max(max, slot.number), 0)+1;


// Create new slot for the specified college and team index
// const newSlot = new Slot2Model({
// number: newSlotNumber,
// round: roundId,
// college: collegeId,
// teamIndex
// });

// await newSlot.save();
console.log(`Slot added for round ${roundId}, college ${collegeId}, and teamIndex ${teamIndex} and slot number is ${newSlotNumber}.`);
} catch (error) {
console.error("Error creating slot:", error);
}
};

// Function to slot teams for a specific event and college
const slotTeamsForEventAndCollege = async (collegeId, eventId) => {
try {

// Find teams from the specified college in the event
const teams = await TeamModel.find({ college: ObjectId(collegeId), event: ObjectId(eventId) });
// If no teams are found, log a message and return
if (teams.length === 0) {
console.log(`No teams found for college ${collegeId} in event ${eventId}.`);
return;
}

// Get all rounds in the event
const rounds = await RoundModel.find({ event: eventId });

// For each team, check if there is a slot for each round
for (const team of teams) {
for (const round of rounds) {
// Check if a slot exists for the team in the round
const existingSlot = await Slot2Model.findOne({ round: ObjectId(round._id), college: ObjectId(collegeId), teamIndex: team.index });
// If no slot exists, create a new one
if (!existingSlot) {
await findOrCreateSlot(round._id, collegeId, team.index);
}
}
}

console.log(`Slotting completed for all teams from college ${collegeId} in event ${eventId}`);
} catch (error) {
console.error("Error:", error);
}
};

const main = async () => {
await connectToDatabase();
const collegeId = new ObjectId( process.argv[2]);
const eventId = new ObjectId( process.argv[3]);
if (!collegeId || !eventId) {
console.error("Please provide the college ID and event ID as arguments.");
process.exit(1);
}
await slotTeamsForEventAndCollege(collegeId, eventId);
await mongoose.disconnect();
};

main();
1 change: 1 addition & 0 deletions src/controllers/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -1237,6 +1237,7 @@ const getTeam = async (req, res, next) => {
});
};


const getTeams = async (req, res) => {
let teams = await TeamModel.find({ event: req.params.event }).populate("college");

Expand Down
138 changes: 102 additions & 36 deletions src/controllers/practiceSlot.js
Original file line number Diff line number Diff line change
@@ -1,53 +1,119 @@
const PracticeSlotModel = require("../models/PracticeSlot");
const CollegeModel = require("../models/College");

const Team = require("../models/Team")
const Event = require("../models/Event")

const createPracticeSlot = async (req, res) => {
let colleges = await CollegeModel.find();

let count = colleges.length;
let slots = [];
for (let i = 0; i < count; i++) {
let index = Math.floor(Math.random() * 100) % colleges.length;
let college = colleges.splice(index, 1)[0].toObject();
let order = i + 1;
try {
await PracticeSlotModel.create({
number: order,
college: college._id
});
} catch (e) {
throw e;
try {
console.log("Practice slotting:");

// Assuming the date is provided in the request body, ensure it's in the correct format
const date = req.body.date;
console.log(date+" this is date")

// Step 1: Find events occurring at the specified venue and date
const events = await Event.find({
venue: "KMC Greens, Main Stage",
startDate: { $gt: new Date(date) },
endDate: { $lt: new Date(date + "T23:59:59.999Z") }
});
console.log(events.length, "events found");

// Step 2: Fetch teams for all events
const teamsByEvent = [];
for (const event of events) {
const teams = await Team.find({ event: event._id });
teamsByEvent.push(...teams);
}
console.log(teamsByEvent.length, "teams found in total");

// Step 3: Create practice slots by removing duplicate teams based on college
const slots = [];
const addedTeams = new Set(); // Track teams by college to remove duplicates
let order = 0;
for (const team of teamsByEvent) {
const teamIdentifier = `${team.college}-${team.index}`; // Unique identifier for the team
if (!addedTeams.has(teamIdentifier)) {
console.log("Team added:", teamIdentifier);
order += 1;
const college = await CollegeModel.findOne({ _id: team.college });
await PracticeSlotModel.create({
number: order,
college: team.college,
date: date,
index:team.index
});
slots.push({ team: team.index, location: college.location, college: college.name, order: order });
addedTeams.add(teamIdentifier);
} else {
console.log("Team removed:", teamIdentifier);
}
}
slots.push({ number: order, ...college });
console.log(slots.length, "slots created");

return res.json({
status: 200,
message: "Success",
data: slots,
});
} catch (error) {
console.error("Error creating practice slots:", error);
return res.status(500).json({
status: 500,
message: "Internal Server Error",
});
}
return res.json({
status: 200,
message: "Success",
data: slots,
});
};




const getPracticeSlots = async (req, res, next) => {
console.log(2);
let slots = await PracticeSlotModel.find().populate('college');
if (!slots) next();
slots = slots.map(slot => ({
id: slot.id,
number: slot.number,
...slot.college.toObject(),
}));
try {
// Fetch practice slots with populated college details

const slots = await PracticeSlotModel.find({});

return res.json({
status: 200,
message: "Success",
data: slots,
});
// Check if practice slots are found
if (!slots || slots.length === 0) {
return res.status(404).json({ status: 404, message: "Practice slots not found" });
}

// Map the practice slots data to include college name, location, and team details
const populatedSlots = await Promise.all(slots.map(async (slot) => {
const College = await CollegeModel.findById(slot.college);
// Check if college is found
if (!College) {
throw new Error("College not found for practice slot");
}
// Format the data with college name and location
const slotData = {
order: slot.number,
date:slot.date,
college: College.name,
location: College.location,
team: slot.index
};
return slotData;
}));

// Return the populated data with college details
return res.json({
status: 200,
message: "Success",
data: populatedSlots
});
} catch (error) {
console.error("Error fetching practice slots:", error);
return res.status(500).json({ status: 500, message: "Internal Server Error" });
}
};



const deletePracticeSlots = async (req, res) => {
await PracticeSlotModel.deleteMany();
const date = req.body.date;
await PracticeSlotModel.deleteMany({date:new Date(date)});
return res.json({
status: 200,
message: "Success",
Expand Down
6 changes: 5 additions & 1 deletion src/models/PracticeSlot.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ const schema = {
type: mongoose.Schema.Types.ObjectId,
ref: "College",
required: true,
}
},
index: {
type: Number,
},
date:Date
};

const options = {
Expand Down

0 comments on commit c984e97

Please sign in to comment.