Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 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
2 changes: 2 additions & 0 deletions src/app/my/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import Tab from "@/widgets/mypage/ui/Tab.tsx/Tab";
import { apiFetch } from "@/shared/api/fetcher";
import { useModalStore } from "@/shared/model/modal.store";
import { usePostCreateModal } from "@/features/createPost/lib/usePostCreateModal";
import { PostStatus } from "@/entities/post/model/types/post";

const options = [
{ label: "판매중 상품", value: "selling" },
Expand All @@ -27,6 +28,7 @@ interface PostListItem {
chatCount: number;
viewCount: number;
thumbnail: string;
status: PostStatus;
}

const Mypage = () => {
Expand Down
2 changes: 0 additions & 2 deletions src/entities/chat/lib/useChatPost.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ import { useEffect, useState } from "react";
import { PostDetail } from "@/entities/post/model/types/post";
import { apiFetch } from "@/shared/api/fetcher";
import { useModalStore } from "@/shared/model/modal.store";

export const useChatPost = (postingId: number) => {
const [post, setPost] = useState<PostDetail | null>(null);
const [isLoading, setIsLoading] = useState(false);
const { openModal, closeModal } = useModalStore();

useEffect(() => {
async function fetchPost() {
try {
Expand Down
22 changes: 21 additions & 1 deletion src/entities/chat/lib/useChatSocket.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import { useEffect, useRef } from "react";
import { ChatSocket } from "../model/socket";
import { MessageProps } from "../model/types";
import { DealStatus, MessageProps } from "../model/types";
import { PostStatus } from "@/entities/post/model/types/post";

export const useChatSocket = (
chatId: number | null,
pushMessageToCache: (msg: MessageProps) => void,
scrollToBottom?: () => void,
onDealUpdate?: (update: {
postStatus: PostStatus;
dealStatus: DealStatus;
}) => void,
) => {
const socketRef = useRef<ChatSocket | null>(null);
const isConnectedRef = useRef(false);
Expand All @@ -22,6 +27,21 @@ export const useChatSocket = (
pushMessageToCache(msg);
requestAnimationFrame(() => scrollToBottom?.());
},
onDealUpdate: (update) => {
onDealUpdate?.({
postStatus: update.postStatus,
dealStatus: update.dealStatus,
});
pushMessageToCache({
messageId: Date.now(),
type: "system",
content: update.message,
isMine: false,
sendAt: new Date().toISOString(),
isRead: true,
});
requestAnimationFrame(() => scrollToBottom?.());
},
onSystem: (sys) => console.log("[System]", sys.message),
onClose: (code) => {
console.log("[Socket] Closed:", code);
Expand Down
80 changes: 80 additions & 0 deletions src/entities/chat/lib/useDealStatus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { useState } from "react";
import { useQueryClient, useMutation } from "@tanstack/react-query";
import { apiFetch } from "@/shared/api/fetcher";
import { DealStatus } from "../model/types";
import { PostStatus } from "@/entities/post/model/types/post";
import { useModalStore } from "@/shared/model/modal.store";

interface DealResponse {
chatId: number;
postingId: number;
sellerId: number;
buyerId: number;
dealStatus: DealStatus;
postStatus: PostStatus;
changedBy: number;
changedAt: string;
}

export const useDealStatus = (
chatId: number | null,
initialPostStatus: PostStatus,
initialDealStatus: DealStatus,
) => {
const queryClient = useQueryClient();
const [postStatus, setPostStatus] = useState<PostStatus>(initialPostStatus);
const [dealStatus, setDealStatus] = useState<DealStatus>(initialDealStatus);

const applyUpdate = (update: {
postStatus: PostStatus;
dealStatus: DealStatus;
}) => {
setPostStatus(update.postStatus);
setDealStatus(update.dealStatus);
};

const { openModal, closeModal } = useModalStore();
const { mutate: onDealChange, isPending: isLoading } = useMutation<
DealResponse,
Error,
DealStatus
>({
mutationFn: async (nextStatus: DealStatus) => {
if (!chatId) {
throw new Error("아직 채팅이 시작되지 않았습니다.");
}
return await apiFetch<DealResponse>(`/api/chat/${chatId}/deal`, {
method: "PATCH",
body: JSON.stringify({ status: nextStatus }),
});
},
onSuccess: (res) => {
//optimistic update
setPostStatus(res.postStatus);
setDealStatus(res.dealStatus);
queryClient.invalidateQueries({ queryKey: ["chats"] });
queryClient.invalidateQueries({
queryKey: ["postDetail", res.postingId],
});
//TODO: 소켓을 통한 시스템 메시지 송/수신 및 상대방 postStatus, dealStatus update
openModal("normal", {
message: "거래 상태가 변경되었습니다.",
onClick: closeModal,
});
},
onError: () => {
openModal("normal", {
message: "거래 상태 변경에 실패했습니다.",
onClick: closeModal,
});
},
});

return {
postStatus,
dealStatus,
isLoading,
onDealChange,
applyUpdate,
};
};
17 changes: 16 additions & 1 deletion src/entities/chat/model/socket.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import { error } from "console";
import { MessageProps } from "./types";
import { DealStatus, MessageProps } from "./types";
import { useAuthStore } from "@/features/auth/model/auth.store";
import { refreshAccessToken } from "@/shared/api/refresh";
import { PostStatus } from "@/entities/post/model/types/post";

export interface ChatSocketEvents {
onOpen?: () => void;
onMessage?: (message: MessageProps) => void;
onSystem?: (system: { type: string; message: string }) => void;
onDealUpdate?: (update: {
postStatus: PostStatus;
dealStatus: DealStatus;
message: string;
}) => void;
onClose?: (code: number, reason?: string) => void;
onError?: (event: Event) => void;
}
Expand Down Expand Up @@ -45,6 +51,15 @@ export class ChatSocket {
this.socket.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (data.type === "deal_update") {
this.events.onDealUpdate?.({
dealStatus: data.dealStatus,
postStatus: data.postStatus,
message: data.systemMessage,
});
return;
}

if (["welcome", "system", "read"].includes(data.type)) {
this.events.onSystem?.(data);
return;
Expand Down
4 changes: 3 additions & 1 deletion src/entities/chat/model/types.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
export type DealStatus = "ACTIVE" | "RESERVED" | "COMPLETED";

export interface Chat {
chatId: number;
postingId: number;
postingTitle: string;
role: string;
lastMessage: MessageProps;
createdAt: string;
status: string;
status: DealStatus;
otherId: number;
otherNickname: string;
otherImage: string;
Expand Down
38 changes: 37 additions & 1 deletion src/entities/chat/ui/ChattingRoom/ChattingRoom.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ import { useModalStore } from "@/shared/model/modal.store";
import Button from "@/shared/ui/Button/Button";
import { TextField } from "@/shared/ui/TextField/TextField";
import DeleteIcon from "@/shared/icons/delete.svg";
import PostStatusBadge from "@/entities/post/ui/badge/PostStatusBadge";
import DealActionPanel from "@/features/deal/ui/DealActionPanel/DealActionPanel";

import { apiFetch } from "@/shared/api/fetcher";
import { useChatMessages } from "../../lib/useChatMessages";
import { useChatSocket } from "../../lib/useChatSocket";
import { useDealStatus } from "../../lib/useDealStatus";
import { useInfiniteScroll } from "@/shared/lib/useInfiniteScroll";
import { DealStatus } from "../../model/types";

import { getPostDetail } from "@/entities/post/api/getPostDetail";
import { getUser } from "@/entities/user/api/getUser";
Expand All @@ -20,10 +24,12 @@ export const ChattingRoom = ({
postingId,
otherId,
chatId: initialChatId,
status: dealStatus,
}: {
postingId: number;
otherId: number;
chatId?: number;
status?: DealStatus;
}) => {
const [chatId, setChatId] = useState<number | null>(initialChatId ?? null);
const {
Expand Down Expand Up @@ -55,6 +61,18 @@ export const ChattingRoom = ({
messagesEndRef,
} = useChatMessages(chatId);

const {
postStatus: currentPostStatus,
dealStatus: currentDealStatus,
isLoading: isDealLoading,
onDealChange,
applyUpdate,
} = useDealStatus(
chatId ?? null,
post?.status ?? "SELLING",
dealStatus ?? "ACTIVE",
);

const scrollToBottom = () => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
};
Expand All @@ -72,6 +90,7 @@ export const ChattingRoom = ({
chatId,
pushMessageToCache,
scrollToBottom,
applyUpdate,
);

const { openModal, closeModal } = useModalStore();
Expand Down Expand Up @@ -201,11 +220,28 @@ export const ChattingRoom = ({
/>
{/* 제목과 가격 세로 정렬 */}
<div className="flex flex-col">
<span className="font-bold text-white">{post?.title}</span>
<span className="font-bold text-white">
{post?.title}
{post && (
<PostStatusBadge status={currentPostStatus} className="ml-2" />
)}
</span>
<span className="text-white">
{post?.price.toLocaleString("ko-KR") + " 원"}
</span>
</div>

<div className="absolute top-4 right-4">
{post && (
<DealActionPanel
isOwner={!(otherId === post.sellerId)}
postStatus={currentPostStatus}
dealStatus={currentDealStatus}
onDealChange={onDealChange}
isLoading={isDealLoading}
/>
)}
</div>
</div>

{/* 메시지 리스트 영역 */}
Expand Down
3 changes: 3 additions & 0 deletions src/entities/post/model/types/post.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export type PostStatus = "SELLING" | "RESERVED" | "SOLD";
export interface Post {
postingId: number;
title: string;
Expand All @@ -9,6 +10,7 @@ export interface Post {
chatCount: number;
viewCount: number;
thumbnail: string;
status: PostStatus;
}

export interface PostDetail {
Expand All @@ -26,4 +28,5 @@ export interface PostDetail {
images: string[];
isOwner: boolean;
isFavorite: boolean;
status: PostStatus;
}
39 changes: 39 additions & 0 deletions src/entities/post/ui/badge/PostStatusBadge.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import React from "react";
import cn from "@/shared/lib/cn";
import { PostStatus } from "../../model/types/post";

const postStatusMessageMap: Record<PostStatus, string> = {
SELLING: "판매 중",
RESERVED: "예약 중",
SOLD: "판매 완료",
};

const postStatusColorMap: Record<PostStatus, string> = {
SELLING: "bg-linear-to-r from-[#5097fa] to-[#5363ff] text-[#F1F1F5]",
RESERVED: "bg-white text-[#5097FA]",
SOLD: "bg-black text-[#9FA6B2]",
};

interface PostStatusBadgeProps {
status: PostStatus;
className?: string;
}

const PostStatusBadge = ({ status, className }: PostStatusBadgeProps) => {
const message = postStatusMessageMap[status];
const colorClass = postStatusColorMap[status];

return (
<span
className={cn(
"inline-block rounded-md px-2 py-[2px] text-[14px] font-medium",
colorClass,
className,
)}
>
{message}
</span>
);
};

export default PostStatusBadge;
8 changes: 8 additions & 0 deletions src/entities/post/ui/card/PostCard.stories.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Meta, StoryObj } from "@storybook/nextjs-vite";
import PostCard from "./PostCard";
import { PostStatus } from "../../model/types/post";

const meta: Meta<typeof PostCard> = {
title: "Post/PostCard",
Expand All @@ -16,6 +17,10 @@ const meta: Meta<typeof PostCard> = {
chatCount: { control: "number" },
viewCount: { control: "number" },
thumbnail: { control: "text" },
status: {
control: { type: "radio" },
options: ["SELLING", "RESERVED", "SOLD"],
},
},
};

Expand All @@ -33,6 +38,7 @@ export const Mobile: Story = {
chatCount: 2,
viewCount: 101,
thumbnail: "",
status: "SELLING",
},
globals: {
viewport: { value: "mobile2", isRotated: false },
Expand All @@ -51,6 +57,7 @@ export const Tablet: Story = {
chatCount: 2,
viewCount: 101,
thumbnail: "",
status: "RESERVED",
},
globals: {
viewport: { value: "tablet", isRotated: false },
Expand All @@ -69,6 +76,7 @@ export const Desktop: Story = {
chatCount: 2,
viewCount: 101,
thumbnail: "",
status: "SOLD",
},
globals: {
viewport: { value: "desktop", isRotated: false },
Expand Down
Loading