Skip to content

Commit

Permalink
⚡ implement init activity db logic
Browse files Browse the repository at this point in the history
  • Loading branch information
pbc1017 committed Dec 30, 2023
1 parent 2aaff40 commit 48bb09e
Show file tree
Hide file tree
Showing 6 changed files with 222 additions and 33 deletions.
1 change: 1 addition & 0 deletions back/config/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const config = {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
dialect: "mysql",
logging: false,
define: {
timestamps: false,
},
Expand Down
43 changes: 43 additions & 0 deletions back/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions back/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"multer": "^1.4.5-lts.1",
"multer-s3": "^2.10.0",
"mysql2": "^3.6.2",
"node-schedule": "^2.1.1",
"redis": "^4.6.10",
"sequelize": "^6.33.0",
"sequelize-auto": "^0.8.8",
Expand Down
77 changes: 49 additions & 28 deletions back/routes/activity.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ const {
ActivityEvidence,
ActivityMember,
ActivitySign,
ActivityEvidence_init,
Activity_init,
ActivityMember_init,
} = require("../models");
const checkPermission = require("../utils/permission");
const checkReportDuration = require("../utils/duration");
Expand Down Expand Up @@ -108,7 +111,7 @@ router.get("/advisor_sign", async (req, res) => {
order: [["sign_time", "DESC"]],
});

const latestEdit = await Activity.findOne({
const latestEdit = await Activity_init.findOne({
where: {
club_id,
recent_edit: {
Expand Down Expand Up @@ -136,15 +139,12 @@ router.post("/deleteActivity/:activityId", async (req, res) => {
}

const { activityId } = req.params;
console.log(activityId);

const transaction = await sequelize.transaction();

try {
const activity = await Activity.findByPk(activityId);
const authorized = await checkPermission(req, res, [
{ club_rep: 4, club_id: activity.club_id },
{ advisor: activity.club_id },
]);
if (!authorized) {
return;
Expand All @@ -169,7 +169,6 @@ router.post("/deleteActivity/:activityId", async (req, res) => {
});

await transaction.commit();
console.log("terminated");
res
.status(200)
.send({ message: "Activity and related data deleted successfully" });
Expand Down Expand Up @@ -204,7 +203,6 @@ router.post("/addActivity", async (req, res) => {

const authorized = await checkPermission(req, res, [
{ club_rep: 4, club_id: clubId },
{ advisor: clubId },
]);
if (!authorized) {
return;
Expand Down Expand Up @@ -307,8 +305,6 @@ router.post("/editActivity", async (req, res) => {
activity = await Activity.findByPk(activityId);
const authorized = await checkPermission(req, res, [
{ club_rep: 4, club_id: activity.club_id },
{ advisor: activity.club_id },
// { executive: 4 },
]);
if (!authorized) {
return;
Expand Down Expand Up @@ -397,16 +393,24 @@ router.post("/editActivity", async (req, res) => {
});

router.get("/getActivity/:activityId", async (req, res) => {
const durationCheck = await checkReportDuration();
// if (!durationCheck.found || durationCheck.reportStatus !== 1) {
// return res.status(400).send({ message: "활동 추가 기한이 지났습니다." });
// }
const { activityId } = req.params;

try {
let activity;
let evidence;
let participants;

// Fetch activity details
const activity = await Activity.findByPk(activityId);
activity = await Activity.findByPk(activityId);
if (!activity) {
return res.status(404).send("Activity not found");
}

const authorized = await checkPermission(req, res, [
let authorized = await checkPermission(req, res, [
{ club_rep: 4, club_id: activity.club_id },
{ advisor: activity.club_id },
{ executive: 4 },
Expand All @@ -415,10 +419,41 @@ router.get("/getActivity/:activityId", async (req, res) => {
return;
}

// Fetch evidence associated with the activity
let evidence = await ActivityEvidence.findAll({
where: { activity_id: activityId },
});
authorized = await checkPermission(req, res, [
{ advisor: activity.club_id },
]);

if (durationCheck.reportStatus === 2 && authorized) {
activity = await Activity_init.findByPk(activityId);
evidence = await ActivityEvidence_init.findAll({
where: { activity_id: activityId },
});
participants = await ActivityMember_init.findAll({
where: { activity_id: activityId },
include: [
{
model: Member,
attributes: ["name"],
as: "member_student",
},
],
});
} else {
activity = await Activity.findByPk(activityId);
evidence = await ActivityEvidence.findAll({
where: { activity_id: activityId },
});
participants = await ActivityMember.findAll({
where: { activity_id: activityId },
include: [
{
model: Member,
attributes: ["name"],
as: "member_student",
},
],
});
}

// Function to extract the timestamp from the S3 URL
const extractTimestamp = (url) => {
Expand All @@ -435,23 +470,11 @@ router.get("/getActivity/:activityId", async (req, res) => {
return timestampA - timestampB;
});

// Fetch participants associated with the activity
const participants = await ActivityMember.findAll({
where: { activity_id: activityId },
include: [
{
model: Member, // Assuming Member model is imported and associated
attributes: ["name"],
as: "member_student",
},
],
});
// Format the response
const response = {
clubId: activity.club_id,
name: activity.title,
type: activity.activity_type_id,
category: "", // Adjust based on how you store 'category'
startDate: activity.start_date,
endDate: activity.end_date,
location: activity.location,
Expand Down Expand Up @@ -697,8 +720,6 @@ router.get("/search_members", async (req, res) => {
semesterConditions = { semester_id: currentSemester.id };
}

console.log(semesterConditions);

// 해당 동아리에 속한 회원들 조회
const members = await MemberClub.findAll({
where: {
Expand Down
121 changes: 121 additions & 0 deletions back/routes/feedback.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
const express = require("express");
const router = express.Router();
const { Op } = require("sequelize");
const {
Semester,
Duration,
Activity,
ActivityEvidence,
ActivityMember,
Activity_init,
ActivityEvidence_init,
ActivityMember_init,
} = require("../models");
const schedule = require("node-schedule");

const BATCH_SIZE = 100; // 한 번에 처리할 데이터의 양

router.get("/migrate", async (req, res) => {
await migrateDataInBatches();
res.send("finish");
});

const migrateDataInBatches = async () => {
try {
await Activity_init.destroy({ where: {} });
await ActivityMember_init.destroy({ where: {} });
await ActivityEvidence_init.destroy({ where: {} });

// Activity 데이터 이동
const totalActivities = await Activity.count();
const activityIterations = Math.ceil(totalActivities / BATCH_SIZE);

for (let i = 0; i < activityIterations; i++) {
const activities = await Activity.findAll({
limit: BATCH_SIZE,
offset: i * BATCH_SIZE,
});

const activityData = activities.map((a) => a.get({ plain: true }));
await Activity_init.bulkCreate(activityData, { ignoreDuplicates: true });
}

// ActivityMember 데이터 이동
const totalMembers = await ActivityMember.count();
const memberIterations = Math.ceil(totalMembers / BATCH_SIZE);

for (let i = 0; i < memberIterations; i++) {
const members = await ActivityMember.findAll({
limit: BATCH_SIZE,
offset: i * BATCH_SIZE,
});

const memberData = members.map((m) => m.get({ plain: true }));
await ActivityMember_init.bulkCreate(memberData, {
ignoreDuplicates: true,
});
}

// ActivityEvidence 데이터 이동
const totalEvidence = await ActivityEvidence.count();
const evidenceIterations = Math.ceil(totalEvidence / BATCH_SIZE);

for (let i = 0; i < evidenceIterations; i++) {
const evidence = await ActivityEvidence.findAll({
limit: BATCH_SIZE,
offset: i * BATCH_SIZE,
});

const evidenceData = evidence.map((e) => e.get({ plain: true }));
await ActivityEvidence_init.bulkCreate(evidenceData, {
ignoreDuplicates: true,
});
}

console.log("Data migration completed successfully");
} catch (error) {
console.error("Error during batch data migration:", error);
}
};

const scheduleReportModifyStart = async () => {
const currentDate = new Date();
currentDate.setHours(currentDate.getHours() + 9);

const currentSemester = await Semester.findOne({
where: {
start_date: { [Op.lte]: currentDate },
end_date: { [Op.gte]: currentDate },
},
});

if (!currentSemester) {
console.log("현재 학기를 찾을 수 없습니다.");
return;
}

const durations = await Duration.findAll({
where: {
semester_id: currentSemester.id,
duration_name: "ReportModify",
},
attributes: ["start_date"],
});

if (durations.length > 0) {
const reportModifyStartDate = new Date(durations[0].start_date);
// reportModifyStartDate.setHours(-30, -7, 0, 0); // 시작일의 자정에 설정
reportModifyStartDate.setHours(0, 0, 0, 0); // 시작일의 자정에 설정

schedule.scheduleJob(reportModifyStartDate, async function () {
// 여기에 실행할 함수를 넣습니다.
console.log("ReportModify 시작!");
await migrateDataInBatches();
// 실행할 함수 또는 로직
});
}
};

scheduleReportModifyStart();

module.exports = router;
Loading

0 comments on commit 48bb09e

Please sign in to comment.