Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found
Select Git revision
  • deploy
  • develop
  • master
3 results

Target

Select target project
  • websystem1/webback
1 result
Select Git revision
  • deploy
  • develop
  • master
3 results
Show changes
// dtos/MeetingResponseDTO.js
class MeetingDetailResponseDTO {
constructor(meeting) {
constructor(meeting, isScheduleConflict) {
this.id = meeting.id;
this.title = meeting.title;
this.description = meeting.description;
......@@ -10,6 +10,7 @@ class MeetingDetailResponseDTO {
this.time_idx_deadline = meeting.time_idx_deadline;
this.type = meeting.type;
this.creatorName = meeting.creator ? meeting.creator.name : 'Unknown';
this.isScheduleConflict = isScheduleConflict;
this.participants = meeting.participants.map(participant => ({
userId: participant.user_id,
name: participant.participantUser ? participant.participantUser.name : 'Unknown',
......
......@@ -253,7 +253,7 @@ class MeetingService {
{
userId: userId,
title: `번개 모임: ${meeting.title}`,
is_fixed: true,
is_fixed: false,
events: events,
},
transaction
......@@ -299,21 +299,34 @@ class MeetingService {
{
model: MeetingParticipant,
as: 'participants',
where: { user_id: userId }, // userId와 매핑된 미팅만 가져옴
required: false,
attributes: [],
},
{
model: User,
as: 'creator',
attributes: ['name'], // 미팅 생성자의 이름만 필요
},
],
attributes: ['name'],
}
]
});
return meetings.map((meeting) => {
const creatorName = meeting.creator ? meeting.creator.name : 'Unknown';
return new MeetingResponseDTO(meeting, true, false, creatorName);
return Promise.all(meetings.map(async (meeting) => {
const isParticipant = await MeetingParticipant.findOne({
where: {
meeting_id: meeting.id,
user_id: userId
}
});
const hasConflict = await ScheduleService.checkScheduleOverlapByTime(
userId,
meeting.time_idx_start,
meeting.time_idx_end
);
const creatorName = meeting.creator ? meeting.creator.name : 'Unknown';
return new MeetingResponseDTO(meeting, !!isParticipant, hasConflict, creatorName);
}));
}
......@@ -330,128 +343,7 @@ class MeetingService {
return meeting;
}
async joinMeeting(meetingId, userId) {
const meeting = await Meeting.findByPk(meetingId);
console.log(`참여하려는 모임: ${JSON.stringify(meeting)}`);
if (!meeting) {
throw new Error('모임을 찾을 수 없습니다.');
}
if (meeting.type === 'CLOSE') {
throw new Error('이미 마감된 모임입니다.');
}
if (meeting.time_idx_deadline !== undefined) {
const currentTimeIdx = this.getCurrentTimeIdx(); // 현재 시간 인덱스
if (currentTimeIdx >= meeting.time_idx_deadline) {
throw new Error('참가 신청이 마감되었습니다.');
}
}
const existingParticipant = await MeetingParticipant.findOne({
where: { meeting_id: meetingId, user_id: userId },
});
if (existingParticipant) {
throw new Error('이미 참가한 사용자입니다.');
}
// 트랜잭션을 사용하여 참가자 추가 및 스케줄 업데이트를 원자적으로 처리
await sequelize.transaction(async (transaction) => {
// 스케줄 충돌 확인
// 현재 인원 수 확인
if (meeting.cur_num >= meeting.max_num) {
throw new Error("모임 인원이 모두 찼습니다.");
}
const hasConflict = await ScheduleService.checkScheduleOverlapByTime(
userId,
meeting.time_idx_start,
meeting.time_idx_end,
transaction
);
console.log(`스케줄 충돌 결과: ${hasConflict}`);
if (hasConflict) {
throw new Error("스케줄이 겹칩니다. 다른 모임에 참가하세요.");
}
// 참가자 추가
await MeetingParticipant.create(
{ meeting_id: meetingId, user_id: userId },
{ transaction }
);
// 스케줄 생성 (모임 시간 범위 내 모든 time_idx에 대해 생성)
const events = [];
for (
let idx = meeting.time_idx_start;
idx <= meeting.time_idx_end;
idx++
) {
events.push({ time_idx: idx });
}
await ScheduleService.createSchedules(
{
userId: userId,
title: `번개 모임: ${meeting.title}`,
is_fixed: true,
events: events,
},
transaction
);
// 채팅방 참가 (MongoDB)
const user = await User.findOne({
where: { id: userId },
transaction,
});
const chatRoom = await ChatRooms.findOne({
chatRoomId: meeting.chatRoomId,
});
if (chatRoom && !chatRoom.participants.includes(user.name)) {
chatRoom.participants.push(user.name);
chatRoom.isOnline.set(user.name, true);
chatRoom.lastReadAt.set(user.name, new Date());
chatRoom.lastReadLogId.set(user.name, null);
await chatRoom.save();
}
// 현재 인원 수 증가
await meeting.increment("cur_num", { by: 1, transaction });
await Meeting.sequelize.transaction(async (transaction) => {
const hasConflict = await ScheduleService.checkScheduleOverlap(
userId,
new Date(meeting.start_time),
new Date(meeting.end_time)
);
if (hasConflict) {
throw new Error('스케줄이 겹칩니다. 다른 모임에 참가하세요.');
}
await MeetingParticipant.create({ meeting_id: meetingId, user_id: userId }, { transaction });
await ScheduleService.createSchedule({
userId,
title: `번개 모임: ${meeting.title}`,
start_time: new Date(meeting.start_time),
end_time: new Date(meeting.end_time),
is_fixed: true,
});
// 사용자와 FCM 토큰 조회
const user = await this._findUserWithFcmTokens(userId);
const userFcmTokens = user.fcmTokenList.map((fcmToken) => fcmToken.token);
const chatRoom = await ChatRoom.findOne({ chatRoomId: meeting.chatRoomId });
if (chatRoom) {
console.log("채팅방 찾음");
this._addParticipantToChatRoom(chatRoom, user, userFcmTokens);
}
});
});
}
async getMeetingDetail(meetingId) {
async getMeetingDetail(meetingId, userId) {
const meeting = await Meeting.findByPk(meetingId, {
include: [
{
......@@ -465,19 +357,25 @@ class MeetingService {
include: [
{
model: User,
as: "user", // 'participantUser'에서 'user'로 수정
as: "user",
attributes: ["name", "email"],
},
],
},
],
}
]
}
]
});
if (!meeting) {
throw new Error("모임을 찾을 수 없습니다.");
}
return new MeetingDetailResponseDTO(meeting);
const hasConflict = await ScheduleService.checkScheduleOverlapByTime(
userId,
meeting.time_idx_start,
meeting.time_idx_end
);
return new MeetingDetailResponseDTO(meeting, hasConflict);
}
/**
......
......@@ -52,151 +52,146 @@ afterAll(async () => {
await sequelize.close();
});
describe('MeetingService - getMeetings', () => {
describe('MeetingService - 전체 미팅 조회 테스트', () => {
beforeEach(async () => {
await MeetingParticipant.destroy({ where: {} });
await Meeting.destroy({ where: {} });
await Schedule.destroy({ where: {} });
await User.destroy({ where: {} });
// Create dummy users
// 더미 사용자 생성
await User.bulkCreate([
{ id: 1, name: 'Alice', email: 'alice@example.com' },
{ id: 2, name: 'Bob', email: 'bob@example.com' },
{ id: 3, name: 'Charlie', email: 'charlie@example.com' },
{ id: 3, name: 'Charlie', email: 'charlie@example.com' }
]);
});
test('should retrieve meetings where the user is a participant', async () => {
const meetingData = {
title: 'Meeting with Alice',
description: 'Discuss project.',
time_idx_start: 10,
time_idx_end: 20,
location: 'Room A',
time_idx_deadline: 8,
type: 'OPEN',
created_by: 1,
};
const createdMeeting = await MeetingService.createMeeting(meetingData);
await MeetingParticipant.create({
meeting_id: createdMeeting.meeting_id,
user_id: 2,
// 스케줄 충돌 체크 Mock 설정
jest.spyOn(ScheduleService, 'checkScheduleOverlapByTime')
.mockImplementation(async (userId, start, end) => {
// 36-38 시간대 충돌
if (start <= 38 && end >= 36) return true;
// 51 시간대 충돌 (Bob의 개인 일정)
if (userId === 2 && start <= 51 && end >= 51) return true;
return false;
});
});
const meetings = await MeetingService.getMeetings(2); // Bob's user ID
test('모든 미팅 목록 조회 및 스케줄 충돌 확인', async () => {
// 1. Alice의 스케줄 등록
await ScheduleService.createSchedules({
userId: 1,
title: '기존 일정',
is_fixed: true,
events: [
{ time_idx: 36 },
{ time_idx: 37 },
{ time_idx: 38 }
]
});
expect(meetings).toBeDefined();
expect(Array.isArray(meetings)).toBe(true);
expect(meetings.length).toBe(1);
// 2. getCurrentTimeIdx Mock 설정
jest.spyOn(MeetingService, 'getCurrentTimeIdx')
.mockReturnValue(30);
const [meeting] = meetings;
expect(meeting.title).toBe('Meeting with Alice');
expect(meeting.creatorName).toBe('Alice');
expect(meeting.isParticipant).toBe(true);
});
const meetingData1 = {
title: '아침 미팅',
time_idx_start: 36,
time_idx_end: 38,
created_by: 2,
type: 'OPEN',
time_idx_deadline: 35,
location: 'Room A'
};
test('should retrieve meetings where the user is the creator', async () => {
const meetingData = {
title: 'Alice-created Meeting',
description: 'Team discussion.',
time_idx_start: 15,
time_idx_end: 25,
location: 'Room B',
time_idx_deadline: 12,
const meetingData2 = {
title: '점심 미팅',
time_idx_start: 44,
time_idx_end: 46,
created_by: 3,
type: 'OPEN',
created_by: 1,
time_idx_deadline: 43,
location: 'Room B'
};
await MeetingService.createMeeting(meetingData);
await MeetingService.createMeeting(meetingData1);
await MeetingService.createMeeting(meetingData2);
const meetings = await MeetingService.getMeetings(1);
const meetings = await MeetingService.getMeetings(1); // Alice's user ID
expect(meetings.length).toBe(2);
expect(meetings).toBeDefined();
expect(Array.isArray(meetings)).toBe(true);
expect(meetings.length).toBe(1);
const morningMeeting = meetings.find(m => m.title === '아침 미팅');
expect(morningMeeting.isScheduleConflict).toBe(true);
expect(morningMeeting.creatorName).toBe('Bob');
expect(morningMeeting.isParticipant).toBe(false);
const [meeting] = meetings;
expect(meeting.title).toBe('Alice-created Meeting');
expect(meeting.creatorName).toBe('Alice');
expect(meeting.isParticipant).toBe(true);
const lunchMeeting = meetings.find(m => m.title === '점심 미팅');
expect(lunchMeeting.isScheduleConflict).toBe(false);
expect(lunchMeeting.creatorName).toBe('Charlie');
expect(lunchMeeting.isParticipant).toBe(false);
});
test('should not include meetings where the user is neither a participant nor the creator', async () => {
const meetingData = {
title: 'Meeting with Bob',
description: 'General discussion.',
time_idx_start: 30,
time_idx_end: 40,
location: 'Room C',
time_idx_deadline: 28,
type: 'OPEN',
test('미팅 상세 정보 조회 및 충돌 확인', async () => {
jest.spyOn(MeetingService, 'getCurrentTimeIdx')
.mockReturnValue(35);
jest.spyOn(ScheduleService, 'checkScheduleOverlapByTime')
.mockImplementation(async (userId, start, end) => {
return start === 40 && end === 42 && userId === 1;
});
const meeting = await MeetingService.createMeeting({
title: '팀 미팅',
time_idx_start: 40,
time_idx_end: 42,
created_by: 2,
};
type: 'OPEN',
time_idx_deadline: 39,
location: 'Room A'
});
await MeetingService.createMeeting(meetingData);
await MeetingService.joinMeeting(meeting.meeting_id, 3);
const meetings = await MeetingService.getMeetings(1); // Alice's user ID
const meetingDetail = await MeetingService.getMeetingDetail(meeting.meeting_id, 1);
expect(meetings).toBeDefined();
expect(Array.isArray(meetings)).toBe(true);
expect(meetings.length).toBe(0); // Alice is not a participant or the creator
expect(meetingDetail.title).toBe('팀 미팅');
expect(meetingDetail.isScheduleConflict).toBe(true);
expect(meetingDetail.creatorName).toBe('Bob');
});
test('should retrieve multiple meetings correctly', async () => {
const meetingData1 = {
title: 'Meeting 1',
description: 'First meeting.',
test('여러 사용자 관점에서의 미팅 조회', async () => {
const meeting = await MeetingService.createMeeting({
title: '공통 미팅',
time_idx_start: 50,
time_idx_end: 60,
location: 'Room D',
time_idx_deadline: 48,
type: 'OPEN',
time_idx_end: 52,
created_by: 1,
};
const meetingData2 = {
title: 'Meeting 2',
description: 'Second meeting.',
time_idx_start: 70,
time_idx_end: 80,
location: 'Room E',
time_idx_deadline: 68,
type: 'OPEN',
created_by: 2,
};
await MeetingService.createMeeting(meetingData1);
const meeting2 = await MeetingService.createMeeting(meetingData2);
await MeetingParticipant.create({
meeting_id: meeting2.meeting_id,
user_id: 1,
location: 'Room A',
time_idx_deadline: 49
});
const meetings = await MeetingService.getMeetings(1); // Alice's user ID
await ScheduleService.createSchedules({
userId: 2,
title: '개인 일정',
is_fixed: true,
events: [{ time_idx: 51 }]
});
expect(meetings).toBeDefined();
expect(Array.isArray(meetings)).toBe(true);
expect(meetings.length).toBe(2); // Alice is either the creator or a participant in two meetings
const aliceMeetings = await MeetingService.getMeetings(1);
const bobMeetings = await MeetingService.getMeetings(2);
const charlieMeetings = await MeetingService.getMeetings(3);
const meetingTitles = meetings.map((m) => m.title);
expect(meetingTitles).toContain('Meeting 1');
expect(meetingTitles).toContain('Meeting 2');
});
expect(aliceMeetings[0].isScheduleConflict).toBe(false);
expect(bobMeetings[0].isScheduleConflict).toBe(true);
expect(charlieMeetings[0].isScheduleConflict).toBe(false);
test('should return an empty array if the user has no meetings', async () => {
const meetings = await MeetingService.getMeetings(3);
expect(meetings).toBeDefined();
expect(Array.isArray(meetings)).toBe(true);
expect(meetings.length).toBe(0);
expect(aliceMeetings[0].isParticipant).toBe(true);
expect(bobMeetings[0].isParticipant).toBe(false);
expect(charlieMeetings[0].isParticipant).toBe(false);
});
});
describe('MeetingService - Integration: createMeeting, joinMeeting, getMeetings', () => {
beforeEach(async () => {
await MeetingParticipant.destroy({ where: {} });
......@@ -436,62 +431,51 @@ describe('MeetingService2', () => {
// 1단계: 겹치지 않는 시간대의 모임 생성
const meetingData1 = {
title: 'Morning Meeting',
description: 'Morning planning meeting.',
time_idx_start: 10,
time_idx_end: 20,
location: 'Room A',
time_idx_deadline: 8,
type: 'OPEN',
created_by: 1, // Alice가 모임 생성
created_by: 1
};
const meetingData2 = {
title: 'Lunch Meeting',
description: 'Lunch and discussion.',
time_idx_start: 30,
time_idx_end: 40,
location: 'Room B',
time_idx_deadline: 28,
type: 'OPEN',
created_by: 2, // Bob이 모임 생성
created_by: 2
};
const meeting1 = await MeetingService.createMeeting(meetingData1);
const meeting2 = await MeetingService.createMeeting(meetingData2);
// 2단계: Charlie가 두 모임에 참여
jest.spyOn(MeetingService, 'getCurrentTimeIdx').mockReturnValue(5); // 마감 시간을 초과하지 않도록 설정
await MeetingService.joinMeeting(meeting1.meeting_id, 3); // Charlie가 Morning Meeting 참여
await MeetingService.joinMeeting(meeting2.meeting_id, 3); // Charlie가 Lunch Meeting 참여
jest.spyOn(MeetingService, 'getCurrentTimeIdx').mockReturnValue(5);
await MeetingService.joinMeeting(meeting1.meeting_id, 3);
await MeetingService.joinMeeting(meeting2.meeting_id, 3);
// 3단계: Alice의 모임 조회
const aliceMeetings = await MeetingService.getMeetings(1); // Alice의 사용자 ID
expect(aliceMeetings.length).toBe(1); // Alice는 하나의 모임 생성
expect(aliceMeetings[0].title).toBe('Morning Meeting');
expect(aliceMeetings[0].isParticipant).toBe(true);
// 4단계: Bob의 모임 조회
const bobMeetings = await MeetingService.getMeetings(2); // Bob의 사용자 ID
expect(bobMeetings.length).toBe(1); // Bob은 하나의 모임 생성
expect(bobMeetings[0].title).toBe('Lunch Meeting');
expect(bobMeetings[0].isParticipant).toBe(true);
// 3단계: 각 사용자의 모임 조회
const aliceMeetings = await MeetingService.getMeetings(1);
const bobMeetings = await MeetingService.getMeetings(2);
const charlieMeetings = await MeetingService.getMeetings(3);
// 5단계: Charlie의 모임 조회
const charlieMeetings = await MeetingService.getMeetings(3); // Charlie의 사용자 ID
expect(charlieMeetings.length).toBe(2); // Charlie는 두 모임에 참여
const meetingTitles = charlieMeetings.map(meeting => meeting.title);
expect(meetingTitles).toContain('Morning Meeting');
expect(meetingTitles).toContain('Lunch Meeting');
// 모든 미팅이 조회되어야 함
expect(aliceMeetings.length).toBe(2);
expect(bobMeetings.length).toBe(2);
expect(charlieMeetings.length).toBe(2);
// 검증: 각 사용자의 스케줄을 확인하여 충돌이 없는지 확인
const aliceSchedules = await Schedule.findAll({ where: { user_id: 1 } });
expect(aliceSchedules.length).toBe(11); // Morning Meeting: 10-20
// 여부 확인
const aliceMorningMeeting = aliceMeetings.find(m => m.title === 'Morning Meeting');
expect(aliceMorningMeeting.isParticipant).toBe(true);
const bobSchedules = await Schedule.findAll({ where: { user_id: 2 } });
expect(bobSchedules.length).toBe(11); // Lunch Meeting: 30-40
const bobLunchMeeting = bobMeetings.find(m => m.title === 'Lunch Meeting');
expect(bobLunchMeeting.isParticipant).toBe(true);
const charlieSchedules = await Schedule.findAll({ where: { user_id: 3 } });
expect(charlieSchedules.length).toBe(22); // 두 모임, 각 모임마다 11개의 스케줄 (10~20, 30~40)
// Charlie는 두 미팅 모두 참가
expect(charlieMeetings.every(m => m.isParticipant)).toBe(true);
});
});