Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
-- 기존 FK 삭제
ALTER TABLE `chatrooms` DROP FOREIGN KEY `chatrooms_consumer_id_fkey`;
ALTER TABLE `chatrooms` DROP FOREIGN KEY `chatrooms_request_id_fkey`;

-- request_id → commission_id
ALTER TABLE `chatrooms`
CHANGE COLUMN `request_id` `commission_id` BIGINT NOT NULL;

-- consumer_id → user_id
ALTER TABLE `chatrooms`
CHANGE COLUMN `consumer_id` `user_id` BIGINT NOT NULL;

-- hidden_consumer → hidden_user
ALTER TABLE `chatrooms`
CHANGE COLUMN `hidden_consumer` `hidden_user` BOOLEAN NOT NULL DEFAULT false;

-- FK 재생성 (이름 변경된 컬럼에 맞게)
ALTER TABLE `chatrooms`
ADD CONSTRAINT `chatrooms_user_id_fkey`
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`)
ON DELETE RESTRICT ON UPDATE CASCADE;

ALTER TABLE `chatrooms`
ADD CONSTRAINT `chatrooms_commission_id_fkey`
FOREIGN KEY (`commission_id`) REFERENCES `requests`(`id`)
ON DELETE RESTRICT ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
Warnings:

- You are about to drop the column `commission_id` on the `chatrooms` table. All the data in the column will be lost.
- Added the required column `commission_Id` to the `chatrooms` table without a default value. This is not possible if the table is not empty.

*/
-- DropForeignKey
ALTER TABLE `chatrooms` DROP FOREIGN KEY `chatrooms_commission_id_fkey`;

-- DropIndex
DROP INDEX `chatrooms_commission_id_fkey` ON `chatrooms`;

-- AlterTable
ALTER TABLE `chatrooms` DROP COLUMN `commission_id`,
ADD COLUMN `commission_Id` BIGINT NOT NULL;

-- AddForeignKey
ALTER TABLE `chatrooms` ADD CONSTRAINT `chatrooms_commission_Id_fkey` FOREIGN KEY (`commission_Id`) REFERENCES `commissions`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
14 changes: 7 additions & 7 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ model Commission {
category Category @relation(fields: [categoryId], references: [id])
requests Request[]
bookmarks Bookmark[]
chatrooms Chatroom[]
commissionTags CommissionTag[]

@@map("commissions")
Expand Down Expand Up @@ -145,7 +146,6 @@ model Request {

user User @relation(fields: [userId], references: [id])
commission Commission @relation(fields: [commissionId], references: [id])
chatrooms Chatroom[]
reviews Review[]
PointTransaction PointTransaction[]

Expand Down Expand Up @@ -212,16 +212,16 @@ model PointTransaction {

model Chatroom {
id BigInt @id @default(autoincrement())
requestId BigInt @map("request_id")
consumerId BigInt @map("consumer_id")
commissionId BigInt @map("commission_Id")
userId BigInt @map("user_id")
artistId BigInt @map("artist_id")
hiddenArtist Boolean @default(false) @map("hidden_artist")
hiddenConsumer Boolean @default(false) @map("hidden_consumer")
hiddenUser Boolean @default(false) @map("hidden_user")
createdAt DateTime @default(now()) @map("created_at")

request Request @relation(fields: [requestId], references: [id])
consumer User @relation("ConsumerChatrooms", fields: [consumerId], references: [id])
artist Artist @relation("ArtistChatrooms", fields: [artistId], references: [id])
commission Commission @relation(fields: [commissionId], references: [id])
user User @relation("ConsumerChatrooms", fields: [userId], references: [id])
artist Artist @relation("ArtistChatrooms", fields: [artistId], references: [id])
chatMessages ChatMessage[]

@@map("chatrooms")
Expand Down
32 changes: 32 additions & 0 deletions prisma/seed.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,38 @@ async function main() {
},
});

// Artist 2 생성
const artistAccount2 = await prisma.account.create({
data: {
provider: "kakao",
oauthId: "artist2_oauth_id",
},
});
const artist2 = await prisma.artist.create({
data: {
accountId: artistAccount2.id,
nickname: "artist_two",
description: "두 번째 테스트용 작가입니다.",
profileImage: "https://example.com/artist2.png",
},
});

// Artist 3 생성
const artistAccount3 = await prisma.account.create({
data: {
provider: "kakao",
oauthId: "artist3_oauth_id",
},
});
const artist3 = await prisma.artist.create({
data: {
accountId: artistAccount3.id,
nickname: "artist_three",
description: "세 번째 테스트용 작가입니다.",
profileImage: "https://example.com/artist3.png",
},
});

// Category 생성
const category1 = await prisma.category.create({
data: {
Expand Down
12 changes: 7 additions & 5 deletions src/chat/controller/chatroom.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ import { parseWithBigInt, stringifyWithBigInt } from "../../bigintJson.js";

export const createChatroom = async (req, res, next) => {
try {
const consumerId = BigInt(req.user.userId);
const userId = BigInt(req.user.userId);

const dto = new CreateChatroomDto({
consumerId: consumerId,
userId,
artistId: BigInt(req.body.artistId),
requestId: BigInt(req.body.requestId),
commissionId: BigInt(req.body.commissionId),
});

const chatroom = await ChatroomService.createChatroom(dto);
Expand All @@ -26,8 +26,10 @@ export const createChatroom = async (req, res, next) => {

export const getChatroom = async (req, res, next) => {
try {
const userId = BigInt(req.user.userId);

const dto = new GetChatroomDto({
consumerId: BigInt(req.user.userId),
userId,
accountId: BigInt(req.user.accountId),
});

Expand All @@ -47,7 +49,7 @@ export const deleteChatrooms = async (req, res, next) => {
const dto = new DeleteChatroomDto({
chatroomIds: req.body.chatroomIds,
userType: req.body.userType,
userId: userId,
userId,
});

const chatrooms = await ChatroomService.softDeleteChatroomsByUser(dto);
Expand Down
14 changes: 7 additions & 7 deletions src/chat/dto/chatroom.dto.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
export class CreateChatroomDto {
constructor({ consumerId, artistId, requestId }) {
this.consumerId = consumerId;
constructor({ userId, artistId, commissionId }) {
this.userId = userId;
this.artistId = artistId;
this.requestId = requestId;
this.commissionId = commissionId;
}
}

export class GetChatroomDto {
constructor({ consumerId, accountId }) {
this.consumerId = BigInt(consumerId);
constructor({ userId, accountId }) {
this.userId = BigInt(userId);
this.accountId = BigInt(accountId);
}
}
Expand All @@ -19,8 +19,8 @@ export class ChatroomListResponseDto {
this.artist_id = room.artist.id;
this.artist_nickname = room.artist.nickname;
this.artist_profile_image = room.artist.profileImage;
this.request_id = room.request.id;
this.request_title = room.request.commission.title;
this.commission_id = room.commission.id;
this.commission_title = room.commission.title;
// 이미지가 있으면 이미지 URL, 없으면 텍스트 content
const lastMsg = room.chatMessages[0];
this.last_message = lastMsg?.imageUrl || lastMsg?.content || null;
Expand Down
26 changes: 11 additions & 15 deletions src/chat/repository/chatroom.repository.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,27 @@ export const ChatroomRepository = {
console.log(data)
return await prisma.chatroom.create({
data: {
consumerId: data.consumerId,
userId: data.userId,
artistId: data.artistId,
requestId: data.requestId,
commissionId: data.commissionId,
},
});
},

async findChatroomByUsersAndCommission(consumerId, artistId, requestId) {
async findChatroomByUsersAndCommission(userId, artistId, commissionId) {
return await prisma.chatroom.findFirst({
where: {
consumerId,
userId,
artistId,
requestId,
commissionId,
},
});
},

async findChatroomsByUser(consumerId) {
async findChatroomsByUser(userId) {
// 1. 채팅방 기본 정보 + 마지막 메시지(내용, 생성시간, id) 조회
const chatrooms = await prisma.chatroom.findMany({
where: { consumerId },
where: { userId },
include: {
artist: {
select: {
Expand All @@ -34,14 +34,10 @@ export const ChatroomRepository = {
profileImage: true,
}
},
request: {
commission: {
select: {
id: true,
commission: {
select: {
title: true,
}
}
title: true,
}
},
chatMessages: {
Expand Down Expand Up @@ -91,8 +87,8 @@ export const ChatroomRepository = {
},

async softDeleteChatrooms(chatroomIds, userType, userId) {
const hiddenField = userType === "consumer" ? "hiddenConsumer" : "hiddenArtist";
const userField = userType === "consumer" ? "consumerId" : "artistId";
const hiddenField = userType === "user" ? "hiddenUser" : "hiddenArtist";
const userField = userType === "user" ? "userId" : "artistId";

await prisma.chatroom.updateMany({
where: {
Expand Down
4 changes: 2 additions & 2 deletions src/chat/service/chat.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ export const ChatService = {
throw new ChatroomNotFoundError({ chatroomId: dto.chatroomId });
}

if (dto.userId !== chatroom.consumerId && dto.userId !== chatroom.artistId) {
throw new ForbiddenError({ consumerId: dto.userId });
if (dto.userId !== chatroom.userId && dto.userId !== chatroom.artistId) {
throw new ForbiddenError({ userId: dto.userId });
}

const messages = await ChatRepository.findMessagesWithImages(dto);
Expand Down
30 changes: 15 additions & 15 deletions src/chat/service/chatroom.service.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,35 @@
import { ChatroomRepository } from "../repository/chatroom.repository.js";
import { ChatRepository } from "../repository/chat.repository.js";
import { UserRepository } from "../../user/repository/user.repository.js";
import { RequestRepository } from "../../request/repository/request.repository.js";
import { CommissionRepository } from "../../commission/repository/commission.repository.js";
import { UserNotFoundError } from "../../common/errors/user.errors.js";
import { ArtistNotFoundError } from "../../common/errors/artist.errors.js";
import { RequestNotFoundError } from "../../common/errors/request.errors.js";
import { CommissionNotFoundError } from "../../common/errors/commission.errors.js";
import { ChatroomNotFoundError } from "../../common/errors/chat.errors.js";
import { ChatroomListResponseDto } from "../dto/chatroom.dto.js";

export const ChatroomService = {
async createChatroom(dto) {
const user = await UserRepository.findUserById(dto.consumerId);
const user = await UserRepository.findUserById(dto.userId);
if (!user) {
throw new UserNotFoundError({ consumerId: dto.consumerId });
throw new UserNotFoundError({ userId: dto.userId });
}

const artist = await UserRepository.findArtistById(dto.artistId);
if (!artist) {
throw new ArtistNotFoundError({ artistId: dto.artistId });
}

const request = await RequestRepository.findRequestById(dto.requestId);
if (!request) {
throw new RequestNotFoundError({ requestId: dto.requestId });
const commission = await CommissionRepository.findCommissionById(dto.commissionId);
if (!commission) {
throw new CommissionNotFoundError({ commissionId: dto.commissionId });
}

// 채팅방 중복 확인
const existing = await ChatroomRepository.findChatroomByUsersAndCommission(
dto.consumerId,
dto.userId,
dto.artistId,
dto.requestId
dto.commissionId
);

// 기존 채팅방 반환
Expand All @@ -39,21 +39,21 @@ export const ChatroomService = {

// 채팅방이 없을 시 생성
const chatroom = await ChatroomRepository.createChatroom({
consumerId: dto.consumerId,
userId: dto.userId,
artistId: dto.artistId,
requestId: dto.requestId,
commissionId: dto.commissionId,
});

return chatroom;
},

async getChatroomsByUserId(dto) {
const user = await UserRepository.findUserById(dto.consumerId);
const user = await UserRepository.findUserById(dto.userId);
if (!user) {
throw new UserNotFoundError({ consumerId: dto.consumerId });
throw new UserNotFoundError({ userId: dto.userId });
}

const chatrooms = await ChatroomRepository.findChatroomsByUser(dto.consumerId);
const chatrooms = await ChatroomRepository.findChatroomsByUser(dto.userId);
console.log(dto.accountId)

const result = [];
Expand All @@ -76,7 +76,7 @@ export const ChatroomService = {
const chatrooms = await ChatroomRepository.findChatroomsByIds(dto.chatroomIds);

const chatroomIdsToDelete = chatrooms
.filter(cr => cr.hiddenConsumer && cr.hiddenArtist)
.filter(cr => cr.hiddenUser && cr.hiddenArtist)
.map(cr => cr.id);

if (chatroomIdsToDelete.length > 0) {
Expand Down
Loading