phungtuan commited on
Commit
516fd29
·
1 Parent(s): d0160cb

rating, shop overview

Browse files
app/(main)/shop/[vendorId]/page.tsx CHANGED
@@ -8,6 +8,8 @@ import ChatButton from "@/components/shop/ChatButton";
8
  import FavoriteShopButton from "@/components/shop/FavoriteShopButton";
9
  import ShopProductModalManager from "@/components/shop/ShopProductModalManager";
10
  import VendorCartProvider from "@/components/shop/VendorCartProvider";
 
 
11
 
12
  interface ShopPageProps {
13
  params: Promise<{
@@ -58,6 +60,11 @@ export default async function ShopPage(props: ShopPageProps) {
58
  return (
59
  <VendorCartProvider vendorId={vendorId} vendorName={vendorName}>
60
  <div className="min-h-screen">
 
 
 
 
 
61
  {components.map((component) => (
62
  <ShopComponentWrapper
63
  key={component.id}
@@ -77,12 +84,17 @@ export default async function ShopPage(props: ShopPageProps) {
77
  Shop Coming Soon
78
  </h2>
79
  <p className="text-default-400">
80
- Shop đang được dựng, quay lại sau nhé!
81
  </p>
82
  </div>
83
  </div>
84
  )}
85
 
 
 
 
 
 
86
  <ShopProductModalManager
87
  products={products}
88
  vendorId={vendorId}
 
8
  import FavoriteShopButton from "@/components/shop/FavoriteShopButton";
9
  import ShopProductModalManager from "@/components/shop/ShopProductModalManager";
10
  import VendorCartProvider from "@/components/shop/VendorCartProvider";
11
+ import ShopOverview from "@/components/shop/ShopOverview";
12
+ import ShopReviewsSection from "@/components/shop/ShopReviewsSection";
13
 
14
  interface ShopPageProps {
15
  params: Promise<{
 
60
  return (
61
  <VendorCartProvider vendorId={vendorId} vendorName={vendorName}>
62
  <div className="min-h-screen">
63
+ {/* Shop Overview Stats */}
64
+ <div className="container mx-auto px-4 pt-4">
65
+ <ShopOverview vendorId={vendorId} />
66
+ </div>
67
+
68
  {components.map((component) => (
69
  <ShopComponentWrapper
70
  key={component.id}
 
84
  Shop Coming Soon
85
  </h2>
86
  <p className="text-default-400">
87
+ Shop đang được dựng, quay lại sau nhé!
88
  </p>
89
  </div>
90
  </div>
91
  )}
92
 
93
+ {/* Customer Reviews Section */}
94
+ <div className="container mx-auto px-4 py-8">
95
+ <ShopReviewsSection vendorId={vendorId} />
96
+ </div>
97
+
98
  <ShopProductModalManager
99
  products={products}
100
  vendorId={vendorId}
app/api/orders/[orderId]/receipt/route.ts CHANGED
@@ -37,7 +37,7 @@ export async function POST(
37
  sendOrderReceiptEmail({
38
  orderId: order.id,
39
  email: order.user.email,
40
- fullName: order.fullName,
41
  items: order.items.map((item) => ({
42
  name: item.product.name,
43
  quantity: item.quantity,
 
37
  sendOrderReceiptEmail({
38
  orderId: order.id,
39
  email: order.user.email,
40
+ fullName: order.fullName || "",
41
  items: order.items.map((item) => ({
42
  name: item.product.name,
43
  quantity: item.quantity,
app/api/reviews/route.ts ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest } from "next/server";
2
+ import { z } from "zod";
3
+
4
+ import { prisma } from "@/lib/prisma";
5
+ import { errorResponse, successResponse } from "@/lib/api/responses";
6
+ import { getAuthenticatedUser } from "@/lib/api/auth-helpers";
7
+ import { isErrorResult } from "@/lib/api/responses";
8
+ import { updateProductRating } from "@/lib/db/ecommerce-queries";
9
+
10
+ // Validation schema for creating a review
11
+ const createReviewSchema = z.object({
12
+ orderItemId: z.string().min(1, "Order item ID is required"),
13
+ rating: z.number().int().min(1).max(5, "Product rating must be 1-5"),
14
+ shippingRating: z.number().int().min(1).max(5, "Shipping rating must be 1-5"),
15
+ comment: z.string().max(2000).optional(),
16
+ });
17
+
18
+ /**
19
+ * POST /api/reviews - Create a review for an order item
20
+ */
21
+ export async function POST(req: NextRequest) {
22
+ try {
23
+ // Authenticate user
24
+ const authResult = await getAuthenticatedUser();
25
+ if (isErrorResult(authResult)) {
26
+ return errorResponse(authResult.error, authResult.status);
27
+ }
28
+ const { user } = authResult;
29
+
30
+ // Parse and validate body
31
+ const body = await req.json();
32
+ const validation = createReviewSchema.safeParse(body);
33
+ if (!validation.success) {
34
+ return errorResponse(validation.error.issues[0].message, 400);
35
+ }
36
+ const { orderItemId, rating, shippingRating, comment } = validation.data;
37
+
38
+ // Get order item with order details
39
+ const orderItem = await prisma.orderItem.findUnique({
40
+ where: { id: orderItemId },
41
+ include: {
42
+ order: true,
43
+ product: true,
44
+ review: true,
45
+ },
46
+ });
47
+
48
+ if (!orderItem) {
49
+ return errorResponse("Order item not found", 404);
50
+ }
51
+
52
+ // Verify order belongs to user
53
+ if (orderItem.order.userId !== user.id) {
54
+ return errorResponse("You cannot review this order", 403);
55
+ }
56
+
57
+ // Verify order is delivered
58
+ if (orderItem.order.status !== "DELIVERED") {
59
+ return errorResponse("You can only review delivered orders", 400);
60
+ }
61
+
62
+ // Check if already reviewed
63
+ if (orderItem.review) {
64
+ return errorResponse("You have already reviewed this item", 400);
65
+ }
66
+
67
+ // Create the review
68
+ const review = await prisma.review.create({
69
+ data: {
70
+ productId: orderItem.productId,
71
+ userId: user.id,
72
+ orderId: orderItem.orderId,
73
+ orderItemId: orderItem.id,
74
+ rating,
75
+ shippingRating,
76
+ comment: comment || null,
77
+ isVerified: true, // Order-based reviews are automatically verified
78
+ },
79
+ include: {
80
+ product: {
81
+ select: { id: true, name: true },
82
+ },
83
+ },
84
+ });
85
+
86
+ // Update product average rating
87
+ await updateProductRating(orderItem.productId);
88
+
89
+ return successResponse(review, 201);
90
+ } catch (error) {
91
+ return errorResponse("Failed to create review", 500, error);
92
+ }
93
+ }
app/api/shop/[vendorId]/reviews/route.ts ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest } from "next/server";
2
+
3
+ import { prisma } from "@/lib/prisma";
4
+ import { errorResponse, successResponse } from "@/lib/api/responses";
5
+
6
+ interface RouteParams {
7
+ params: Promise<{
8
+ vendorId: string;
9
+ }>;
10
+ }
11
+
12
+ /**
13
+ * Anonymize user name for display (e.g., "customer" -> "cus*****")
14
+ */
15
+ function anonymizeUserName(name: string | null): string {
16
+ if (!name || name.length < 3) {
17
+ return "cus*****";
18
+ }
19
+ const prefix = name.slice(0, 3).toLowerCase();
20
+ return `${prefix}*****`;
21
+ }
22
+
23
+ /**
24
+ * GET /api/shop/[vendorId]/reviews - Get shop reviews with pagination
25
+ */
26
+ export async function GET(req: NextRequest, { params }: RouteParams) {
27
+ try {
28
+ const { vendorId } = await params;
29
+ const { searchParams } = new URL(req.url);
30
+ const page = parseInt(searchParams.get("page") || "1");
31
+ const limit = parseInt(searchParams.get("limit") || "10");
32
+ const skip = (page - 1) * limit;
33
+
34
+ // Verify vendor exists
35
+ const vendor = await prisma.vendorProfile.findUnique({
36
+ where: { id: vendorId },
37
+ });
38
+
39
+ if (!vendor) {
40
+ return errorResponse("Shop not found", 404);
41
+ }
42
+
43
+ // Get all products for this vendor
44
+ const vendorProducts = await prisma.product.findMany({
45
+ where: { vendorId, deletedAt: null },
46
+ select: { id: true },
47
+ });
48
+ const productIds = vendorProducts.map((p) => p.id);
49
+
50
+ // Get reviews for all vendor products with pagination
51
+ const [reviews, total] = await Promise.all([
52
+ prisma.review.findMany({
53
+ where: {
54
+ productId: { in: productIds },
55
+ orderId: { not: null }, // Only order-based reviews
56
+ },
57
+ include: {
58
+ user: {
59
+ select: { name: true },
60
+ },
61
+ product: {
62
+ select: { id: true, name: true, images: true },
63
+ },
64
+ orderItem: {
65
+ select: { selectedVariant: true },
66
+ },
67
+ },
68
+ orderBy: { createdAt: "desc" },
69
+ skip,
70
+ take: limit,
71
+ }),
72
+ prisma.review.count({
73
+ where: {
74
+ productId: { in: productIds },
75
+ orderId: { not: null },
76
+ },
77
+ }),
78
+ ]);
79
+
80
+ // Transform reviews with anonymized names
81
+ const transformedReviews = reviews.map((review) => ({
82
+ id: review.id,
83
+ rating: review.rating,
84
+ shippingRating: review.shippingRating,
85
+ comment: review.comment,
86
+ createdAt: review.createdAt,
87
+ isVerified: review.isVerified,
88
+ customerName: anonymizeUserName(review.user.name),
89
+ product: {
90
+ id: review.product.id,
91
+ name: review.product.name,
92
+ image: review.product.images[0] || null,
93
+ },
94
+ variant: review.orderItem?.selectedVariant || null,
95
+ }));
96
+
97
+ return successResponse({
98
+ reviews: transformedReviews,
99
+ pagination: {
100
+ page,
101
+ limit,
102
+ total,
103
+ totalPages: Math.ceil(total / limit),
104
+ },
105
+ });
106
+ } catch (error) {
107
+ return errorResponse("Failed to fetch reviews", 500, error);
108
+ }
109
+ }
app/api/shop/[vendorId]/stats/route.ts ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextRequest } from "next/server";
2
+
3
+ import { prisma } from "@/lib/prisma";
4
+ import { errorResponse, successResponse } from "@/lib/api/responses";
5
+
6
+ interface RouteParams {
7
+ params: Promise<{
8
+ vendorId: string;
9
+ }>;
10
+ }
11
+
12
+ /**
13
+ * GET /api/shop/[vendorId]/stats - Get shop overview statistics
14
+ */
15
+ export async function GET(req: NextRequest, { params }: RouteParams) {
16
+ try {
17
+ const { vendorId } = await params;
18
+
19
+ // Get vendor profile with creation date
20
+ const vendor = await prisma.vendorProfile.findUnique({
21
+ where: { id: vendorId },
22
+ select: {
23
+ id: true,
24
+ storeName: true,
25
+ createdAt: true,
26
+ },
27
+ });
28
+
29
+ if (!vendor) {
30
+ return errorResponse("Shop not found", 404);
31
+ }
32
+
33
+ // Get all products for this vendor
34
+ const products = await prisma.product.findMany({
35
+ where: { vendorId, deletedAt: null },
36
+ select: { id: true },
37
+ });
38
+ const productIds = products.map((p) => p.id);
39
+
40
+ // Get review statistics - only order-based reviews (with shippingRating)
41
+ const reviews = await prisma.review.findMany({
42
+ where: {
43
+ productId: { in: productIds },
44
+ orderId: { not: null },
45
+ },
46
+ select: {
47
+ rating: true,
48
+ shippingRating: true,
49
+ },
50
+ });
51
+
52
+ // Calculate averages
53
+ const totalReviews = reviews.length;
54
+ let avgProductRating = 0;
55
+ let avgShippingRating = 0;
56
+
57
+ if (totalReviews > 0) {
58
+ const productSum = reviews.reduce((acc, r) => acc + r.rating, 0);
59
+ const shippingSum = reviews.reduce((acc, r) => acc + (r.shippingRating || 0), 0);
60
+
61
+ avgProductRating = Number((productSum / totalReviews).toFixed(1));
62
+ avgShippingRating = Number((shippingSum / totalReviews).toFixed(1));
63
+ }
64
+
65
+ // Calculate shop age
66
+ const shopCreatedAt = vendor.createdAt;
67
+ const now = new Date();
68
+ const ageInDays = Math.floor(
69
+ (now.getTime() - shopCreatedAt.getTime()) / (1000 * 60 * 60 * 24)
70
+ );
71
+
72
+ return successResponse({
73
+ storeName: vendor.storeName,
74
+ productCount: products.length,
75
+ totalReviews,
76
+ avgProductRating,
77
+ avgShippingRating,
78
+ shopCreatedAt: shopCreatedAt.toISOString(),
79
+ shopAgeInDays: ageInDays,
80
+ });
81
+ } catch (error) {
82
+ return errorResponse("Failed to fetch shop stats", 500, error);
83
+ }
84
+ }
app/api/user/personal/route.ts CHANGED
@@ -41,6 +41,9 @@ export async function GET() {
41
  price: true,
42
  },
43
  },
 
 
 
44
  },
45
  },
46
  address: true,
@@ -89,7 +92,17 @@ export async function GET() {
89
  totalOrders: stats._count.id || 0,
90
  totalSpent: Number(stats._sum.total) || 0,
91
  },
92
- orders,
 
 
 
 
 
 
 
 
 
 
93
  favoriteShops: favoriteShops.map((fs) => ({
94
  id: fs.id,
95
  addedAt: fs.addedAt,
 
41
  price: true,
42
  },
43
  },
44
+ review: {
45
+ select: { id: true },
46
+ },
47
  },
48
  },
49
  address: true,
 
92
  totalOrders: stats._count.id || 0,
93
  totalSpent: Number(stats._sum.total) || 0,
94
  },
95
+ orders: orders.map((order) => ({
96
+ ...order,
97
+ items: order.items.map((item) => ({
98
+ id: item.id,
99
+ quantity: item.quantity,
100
+ price: item.price,
101
+ selectedVariant: item.selectedVariant,
102
+ hasReview: !!item.review,
103
+ product: item.product,
104
+ })),
105
+ })),
106
  favoriteShops: favoriteShops.map((fs) => ({
107
  id: fs.id,
108
  addedAt: fs.addedAt,
bun.lock CHANGED
@@ -80,6 +80,7 @@
80
  "recharts": "^3.7.0",
81
  "resend": "^6.9.1",
82
  "sanitize-html": "^2.17.0",
 
83
  "tailwind-merge": "^3.4.0",
84
  "zod": "^4.1.13",
85
  "zustand": "^5.0.8",
@@ -2020,6 +2021,8 @@
2020
 
2021
  "svix": ["svix@1.84.1", "", { "dependencies": { "standardwebhooks": "1.0.0", "uuid": "^10.0.0" } }, "sha512-K8DPPSZaW/XqXiz1kEyzSHYgmGLnhB43nQCMeKjWGCUpLIpAMMM8kx3rVVOSm6Bo6EHyK1RQLPT4R06skM/MlQ=="],
2022
 
 
 
2023
  "symbol-tree": ["symbol-tree@3.2.4", "", {}, "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw=="],
2024
 
2025
  "synckit": ["synckit@0.9.3", "", { "dependencies": { "@pkgr/core": "^0.1.0", "tslib": "^2.6.2" } }, "sha512-JJoOEKTfL1urb1mDoEblhD9NhEbWmq9jHEMEnxoC4ujUaZ4itA8vKgwkFAyNClgxplLi9tsUKX+EduK0p/l7sg=="],
 
80
  "recharts": "^3.7.0",
81
  "resend": "^6.9.1",
82
  "sanitize-html": "^2.17.0",
83
+ "swr": "^2.4.0",
84
  "tailwind-merge": "^3.4.0",
85
  "zod": "^4.1.13",
86
  "zustand": "^5.0.8",
 
2021
 
2022
  "svix": ["svix@1.84.1", "", { "dependencies": { "standardwebhooks": "1.0.0", "uuid": "^10.0.0" } }, "sha512-K8DPPSZaW/XqXiz1kEyzSHYgmGLnhB43nQCMeKjWGCUpLIpAMMM8kx3rVVOSm6Bo6EHyK1RQLPT4R06skM/MlQ=="],
2023
 
2024
+ "swr": ["swr@2.4.0", "", { "dependencies": { "dequal": "^2.0.3", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-sUlC20T8EOt1pHmDiqueUWMmRRX03W7w5YxovWX7VR2KHEPCTMly85x05vpkP5i6Bu4h44ePSMD9Tc+G2MItFw=="],
2025
+
2026
  "symbol-tree": ["symbol-tree@3.2.4", "", {}, "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw=="],
2027
 
2028
  "synckit": ["synckit@0.9.3", "", { "dependencies": { "@pkgr/core": "^0.1.0", "tslib": "^2.6.2" } }, "sha512-JJoOEKTfL1urb1mDoEblhD9NhEbWmq9jHEMEnxoC4ujUaZ4itA8vKgwkFAyNClgxplLi9tsUKX+EduK0p/l7sg=="],
components/orders/OrderStatusBadge.tsx CHANGED
@@ -21,11 +21,11 @@ const statusConfig: Record<
21
  color: "warning" | "primary" | "secondary" | "success" | "danger";
22
  }
23
  > = {
24
- PENDING: { label: "Pending", color: "warning" },
25
- PROCESSING: { label: "Processing", color: "primary" },
26
- SHIPPED: { label: "Shipped", color: "secondary" },
27
- DELIVERED: { label: "Delivered", color: "success" },
28
- CANCELLED: { label: "Cancelled", color: "danger" },
29
  };
30
 
31
  export default function OrderStatusBadge({
 
21
  color: "warning" | "primary" | "secondary" | "success" | "danger";
22
  }
23
  > = {
24
+ PENDING: { label: "Đang chờ", color: "warning" },
25
+ PROCESSING: { label: "Đang xử lý", color: "primary" },
26
+ SHIPPED: { label: "Đang giao hàng", color: "secondary" },
27
+ DELIVERED: { label: "Đã giao hàng", color: "success" },
28
+ CANCELLED: { label: "Đã hủy", color: "danger" },
29
  };
30
 
31
  export default function OrderStatusBadge({
components/personal/CancelOrderModal.tsx CHANGED
@@ -32,26 +32,26 @@ export default function CancelOrderModal({
32
  <ModalContent>
33
  <ModalHeader className="flex items-center gap-2">
34
  <AlertTriangle className="text-warning" size={24} />
35
- Cancel Order
36
  </ModalHeader>
37
  <ModalBody>
38
  <p>
39
- Are you sure you want to cancel order{" "}
40
  <span className="font-mono font-semibold">
41
  #{order?.id.slice(-8).toUpperCase()}
42
  </span>
43
  ?
44
  </p>
45
  <p className="text-default-500 text-sm mt-2">
46
- This action cannot be undone. The items will be returned to stock.
47
  </p>
48
  </ModalBody>
49
  <ModalFooter>
50
  <Button variant="light" onPress={onClose}>
51
- Keep Order
52
  </Button>
53
  <Button color="danger" isLoading={isLoading} onPress={onConfirm}>
54
- Cancel Order
55
  </Button>
56
  </ModalFooter>
57
  </ModalContent>
 
32
  <ModalContent>
33
  <ModalHeader className="flex items-center gap-2">
34
  <AlertTriangle className="text-warning" size={24} />
35
+ Hủy đơn
36
  </ModalHeader>
37
  <ModalBody>
38
  <p>
39
+ Bạn có chắc chắn muốn hủy đơn hàng{" "}
40
  <span className="font-mono font-semibold">
41
  #{order?.id.slice(-8).toUpperCase()}
42
  </span>
43
  ?
44
  </p>
45
  <p className="text-default-500 text-sm mt-2">
46
+ Hành động này không thể hoàn tác. Các mặt hàng sẽ được trả lại kho.
47
  </p>
48
  </ModalBody>
49
  <ModalFooter>
50
  <Button variant="light" onPress={onClose}>
51
+ Giữ đơn
52
  </Button>
53
  <Button color="danger" isLoading={isLoading} onPress={onConfirm}>
54
+ Hủy đơn
55
  </Button>
56
  </ModalFooter>
57
  </ModalContent>
components/personal/FavoriteShopsSection.tsx CHANGED
@@ -23,7 +23,7 @@ export default function FavoriteShopsSection({
23
  <section>
24
  <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
25
  <Heart className="text-danger" size={20} />
26
- Favorite Shops
27
  </h2>
28
  {shops.length > 0 ? (
29
  <div className="space-y-3">
@@ -47,10 +47,10 @@ export default function FavoriteShopsSection({
47
  {shop.vendor.storeName}
48
  </h3>
49
  <p className="text-sm text-default-500 line-clamp-1">
50
- {shop.vendor.description || "No description"}
51
  </p>
52
  <p className="text-xs text-default-400 mt-1">
53
- {shop.vendor.productCount} products
54
  </p>
55
  </div>
56
  </div>
@@ -65,7 +65,7 @@ export default function FavoriteShopsSection({
65
  startContent={<ExternalLink size={14} />}
66
  variant="flat"
67
  >
68
- Visit Shop
69
  </Button>
70
  <Button
71
  isIconOnly
 
23
  <section>
24
  <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
25
  <Heart className="text-danger" size={20} />
26
+ Shop yêu thích
27
  </h2>
28
  {shops.length > 0 ? (
29
  <div className="space-y-3">
 
47
  {shop.vendor.storeName}
48
  </h3>
49
  <p className="text-sm text-default-500 line-clamp-1">
50
+ {shop.vendor.description || "Không mô tả"}
51
  </p>
52
  <p className="text-xs text-default-400 mt-1">
53
+ {shop.vendor.productCount} sản phẩm
54
  </p>
55
  </div>
56
  </div>
 
65
  startContent={<ExternalLink size={14} />}
66
  variant="flat"
67
  >
68
+ Ghé tới shop
69
  </Button>
70
  <Button
71
  isIconOnly
components/personal/OrdersSection.tsx CHANGED
@@ -1,31 +1,55 @@
1
  "use client";
2
 
 
3
  import { Card, CardBody, CardHeader } from "@heroui/card";
4
  import { Button } from "@heroui/button";
5
  import { Accordion, AccordionItem } from "@heroui/accordion";
6
  import { Image } from "@heroui/image";
7
- import { Package, ShoppingBag, X, ChevronRight } from "lucide-react";
8
 
9
- import { Order, formatDate, canCancelOrder } from "./types";
10
 
11
  import OrderStatusBadge from "@/components/orders/OrderStatusBadge";
 
12
 
13
  interface OrdersSectionProps {
14
  orders: Order[];
15
  cancellingOrderId: string | null;
16
  onCancelClick: (order: Order) => void;
 
 
 
 
 
 
 
 
17
  }
18
 
19
  export default function OrdersSection({
20
  orders,
21
  cancellingOrderId,
22
  onCancelClick,
 
23
  }: OrdersSectionProps) {
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  return (
25
  <section>
26
  <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
27
  <Package size={20} />
28
- My Orders
29
  </h2>
30
  {orders.length > 0 ? (
31
  <div className="space-y-3 max-h-[600px] overflow-y-auto pr-2">
@@ -45,7 +69,7 @@ export default function OrdersSection({
45
  </p>
46
  </div>
47
  <p className="font-semibold">
48
- ${Number(order.total).toFixed(2)}
49
  </p>
50
  </div>
51
  <div className="flex items-center gap-2">
@@ -75,7 +99,7 @@ export default function OrdersSection({
75
  title={
76
  <span className="text-sm font-medium">
77
  {order.items.length}{" "}
78
- {order.items.length === 1 ? "item" : "items"}
79
  </span>
80
  }
81
  >
@@ -104,11 +128,35 @@ export default function OrdersSection({
104
  </p>
105
  <p className="text-xs text-default-500">
106
  {item.quantity} × ${Number(item.price).toFixed(2)}
 
 
 
 
 
107
  </p>
108
  </div>
109
- <p className="font-semibold text-sm">
110
- ${(Number(item.price) * item.quantity).toFixed(2)}
111
- </p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
  </div>
113
  ))}
114
  </div>
@@ -122,16 +170,26 @@ export default function OrdersSection({
122
  <Card className="border-none shadow-sm h-full">
123
  <CardBody className="text-center py-8 flex flex-col items-center justify-center">
124
  <ShoppingBag className="mx-auto mb-3 text-default-300" size={40} />
125
- <h3 className="font-semibold mb-1">No orders yet</h3>
126
  <p className="text-default-500 text-sm mb-4">
127
- When you place orders, they will appear here.
128
  </p>
129
  <Button as="a" color="primary" href="/" size="sm">
130
- Start Shopping
131
  </Button>
132
  </CardBody>
133
  </Card>
134
  )}
 
 
 
 
 
 
 
 
 
 
135
  </section>
136
  );
137
  }
 
1
  "use client";
2
 
3
+ import { useState } from "react";
4
  import { Card, CardBody, CardHeader } from "@heroui/card";
5
  import { Button } from "@heroui/button";
6
  import { Accordion, AccordionItem } from "@heroui/accordion";
7
  import { Image } from "@heroui/image";
8
+ import { Package, ShoppingBag, X, ChevronRight, Star, CheckCircle } from "lucide-react";
9
 
10
+ import { Order, OrderItem, formatDate, canCancelOrder } from "./types";
11
 
12
  import OrderStatusBadge from "@/components/orders/OrderStatusBadge";
13
+ import ReviewModal from "@/components/shop/ReviewModal";
14
 
15
  interface OrdersSectionProps {
16
  orders: Order[];
17
  cancellingOrderId: string | null;
18
  onCancelClick: (order: Order) => void;
19
+ onReviewSuccess?: () => void;
20
+ }
21
+
22
+ interface ReviewableItem {
23
+ id: string;
24
+ productName: string;
25
+ productImage: string | null;
26
+ selectedVariant: string | null;
27
  }
28
 
29
  export default function OrdersSection({
30
  orders,
31
  cancellingOrderId,
32
  onCancelClick,
33
+ onReviewSuccess,
34
  }: OrdersSectionProps) {
35
+ const [reviewItem, setReviewItem] = useState<ReviewableItem | null>(null);
36
+
37
+ const handleReviewClick = (item: OrderItem) => {
38
+ setReviewItem({
39
+ id: item.id,
40
+ productName: item.product.name,
41
+ productImage: item.product.images?.[0] || null,
42
+ selectedVariant: item.selectedVariant,
43
+ });
44
+ };
45
+
46
+ const canReviewOrder = (order: Order) => order.status === "DELIVERED";
47
+
48
  return (
49
  <section>
50
  <h2 className="text-xl font-semibold mb-4 flex items-center gap-2">
51
  <Package size={20} />
52
+ Đơn hàng
53
  </h2>
54
  {orders.length > 0 ? (
55
  <div className="space-y-3 max-h-[600px] overflow-y-auto pr-2">
 
69
  </p>
70
  </div>
71
  <p className="font-semibold">
72
+ {Number(order.total).toFixed(2)}₫
73
  </p>
74
  </div>
75
  <div className="flex items-center gap-2">
 
99
  title={
100
  <span className="text-sm font-medium">
101
  {order.items.length}{" "}
102
+ {order.items.length === 1 ? "sản phẩm" : "sản phẩm"}
103
  </span>
104
  }
105
  >
 
128
  </p>
129
  <p className="text-xs text-default-500">
130
  {item.quantity} × ${Number(item.price).toFixed(2)}
131
+ {item.selectedVariant && (
132
+ <span className="ml-1 text-default-400">
133
+ ({item.selectedVariant})
134
+ </span>
135
+ )}
136
  </p>
137
  </div>
138
+ <div className="flex items-center gap-2">
139
+ <p className="font-semibold text-sm">
140
+ {(Number(item.price) * item.quantity).toFixed(2)}₫
141
+ </p>
142
+ {canReviewOrder(order) && (
143
+ item.hasReview ? (
144
+ <span className="flex items-center gap-1 text-xs text-success-600 bg-success-50 px-2 py-1 rounded-full">
145
+ <CheckCircle size={12} />
146
+ Đã đánh giá
147
+ </span>
148
+ ) : (
149
+ <Button
150
+ size="sm"
151
+ startContent={<Star size={12} />}
152
+ variant="flat"
153
+ onPress={() => handleReviewClick(item)}
154
+ >
155
+ Đánh giá
156
+ </Button>
157
+ )
158
+ )}
159
+ </div>
160
  </div>
161
  ))}
162
  </div>
 
170
  <Card className="border-none shadow-sm h-full">
171
  <CardBody className="text-center py-8 flex flex-col items-center justify-center">
172
  <ShoppingBag className="mx-auto mb-3 text-default-300" size={40} />
173
+ <h3 className="font-semibold mb-1">Chưa có đơn nào</h3>
174
  <p className="text-default-500 text-sm mb-4">
175
+ Khi bạn đặt hàng thành công thì đơn hàng sẽ hiện ở đây.
176
  </p>
177
  <Button as="a" color="primary" href="/" size="sm">
178
+ Bắt đầu mua sắm
179
  </Button>
180
  </CardBody>
181
  </Card>
182
  )}
183
+
184
+ {/* Review Modal */}
185
+ {reviewItem && (
186
+ <ReviewModal
187
+ isOpen={!!reviewItem}
188
+ orderItem={reviewItem}
189
+ onClose={() => setReviewItem(null)}
190
+ onSuccess={onReviewSuccess}
191
+ />
192
+ )}
193
  </section>
194
  );
195
  }
components/personal/StatsCards.tsx CHANGED
@@ -24,7 +24,7 @@ export default function StatsCards({
24
  <ShoppingBag className="text-primary" size={24} />
25
  </div>
26
  <div>
27
- <p className="text-sm text-default-500">Total Orders</p>
28
  <p className="text-2xl font-bold">{totalOrders}</p>
29
  </div>
30
  </CardBody>
@@ -36,8 +36,8 @@ export default function StatsCards({
36
  <DollarSign className="text-success" size={24} />
37
  </div>
38
  <div>
39
- <p className="text-sm text-default-500">Total Spent</p>
40
- <p className="text-2xl font-bold">${totalSpent.toFixed(2)}</p>
41
  </div>
42
  </CardBody>
43
  </Card>
@@ -48,7 +48,7 @@ export default function StatsCards({
48
  <Calendar className="text-secondary" size={24} />
49
  </div>
50
  <div>
51
- <p className="text-sm text-default-500">Member Since</p>
52
  <p className="text-lg font-semibold">{formatDate(memberSince)}</p>
53
  </div>
54
  </CardBody>
 
24
  <ShoppingBag className="text-primary" size={24} />
25
  </div>
26
  <div>
27
+ <p className="text-sm text-default-500">Tổng đơn</p>
28
  <p className="text-2xl font-bold">{totalOrders}</p>
29
  </div>
30
  </CardBody>
 
36
  <DollarSign className="text-success" size={24} />
37
  </div>
38
  <div>
39
+ <p className="text-sm text-default-500">Tổng chi tiêu</p>
40
+ <p className="text-2xl font-bold">{totalSpent.toFixed(2)}₫</p>
41
  </div>
42
  </CardBody>
43
  </Card>
 
48
  <Calendar className="text-secondary" size={24} />
49
  </div>
50
  <div>
51
+ <p className="text-sm text-default-500">Đăng ký từ</p>
52
  <p className="text-lg font-semibold">{formatDate(memberSince)}</p>
53
  </div>
54
  </CardBody>
components/personal/types.ts CHANGED
@@ -4,6 +4,8 @@ export interface OrderItem {
4
  id: string;
5
  quantity: number;
6
  price: number;
 
 
7
  product: {
8
  id: string;
9
  name: string;
 
4
  id: string;
5
  quantity: number;
6
  price: number;
7
+ selectedVariant: string | null;
8
+ hasReview: boolean;
9
  product: {
10
  id: string;
11
  name: string;
components/shop/ReviewCard.tsx ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Card, CardBody } from "@heroui/card";
2
+ import { Image } from "@heroui/image";
3
+ import { Package, CheckCircle } from "lucide-react";
4
+
5
+ import StarRating from "@/components/shop/StarRating";
6
+
7
+ interface ReviewCardProps {
8
+ customerName: string;
9
+ productName: string;
10
+ productImage: string | null;
11
+ variant: string | null;
12
+ rating: number;
13
+ shippingRating: number | null;
14
+ comment: string | null;
15
+ createdAt: string;
16
+ isVerified: boolean;
17
+ }
18
+
19
+ function formatDate(dateString: string): string {
20
+ return new Date(dateString).toLocaleDateString("en-US", {
21
+ year: "numeric",
22
+ month: "short",
23
+ day: "numeric",
24
+ });
25
+ }
26
+
27
+ export default function ReviewCard({
28
+ customerName,
29
+ productName,
30
+ productImage,
31
+ variant,
32
+ rating,
33
+ shippingRating,
34
+ comment,
35
+ createdAt,
36
+ isVerified,
37
+ }: ReviewCardProps) {
38
+ return (
39
+ <Card className="border-none shadow-sm">
40
+ <CardBody className="p-4 gap-3">
41
+ {/* Customer & Date */}
42
+ <div className="flex items-center justify-between">
43
+ <div className="flex items-center gap-2">
44
+ <span className="font-medium text-default-700">{customerName}</span>
45
+ {isVerified && (
46
+ <span className="flex items-center gap-1 text-xs text-success-600 bg-success-50 px-2 py-0.5 rounded-full">
47
+ <CheckCircle size={12} />
48
+ Đã xác minh
49
+ </span>
50
+ )}
51
+ </div>
52
+ <span className="text-xs text-default-400">{formatDate(createdAt)}</span>
53
+ </div>
54
+
55
+ {/* Product info */}
56
+ <div className="flex items-center gap-3 p-2 bg-default-50 rounded-lg">
57
+ <div className="w-10 h-10 bg-default-100 rounded overflow-hidden flex-shrink-0">
58
+ {productImage ? (
59
+ <Image
60
+ alt={productName}
61
+ className="w-full h-full object-cover"
62
+ src={productImage}
63
+ />
64
+ ) : (
65
+ <div className="w-full h-full flex items-center justify-center">
66
+ <Package className="text-default-300" size={16} />
67
+ </div>
68
+ )}
69
+ </div>
70
+ <div className="min-w-0">
71
+ <p className="text-sm font-medium truncate">{productName}</p>
72
+ {variant && (
73
+ <p className="text-xs text-default-500 truncate">{variant}</p>
74
+ )}
75
+ </div>
76
+ </div>
77
+
78
+ {/* Ratings */}
79
+ <div className="flex flex-wrap items-center gap-4">
80
+ <div className="flex items-center gap-2">
81
+ <span className="text-xs text-default-500">Sản phẩm:</span>
82
+ <StarRating rating={rating} size="sm" />
83
+ </div>
84
+ {shippingRating && (
85
+ <div className="flex items-center gap-2">
86
+ <span className="text-xs text-default-500">Vận chuyển:</span>
87
+ <StarRating rating={shippingRating} size="sm" />
88
+ </div>
89
+ )}
90
+ </div>
91
+
92
+ {/* Comment */}
93
+ {comment && (
94
+ <p className="text-sm text-default-600 whitespace-pre-wrap">
95
+ {comment}
96
+ </p>
97
+ )}
98
+ </CardBody>
99
+ </Card>
100
+ );
101
+ }
components/shop/ReviewModal.tsx ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useState } from "react";
4
+ import {
5
+ Modal,
6
+ ModalContent,
7
+ ModalHeader,
8
+ ModalBody,
9
+ ModalFooter,
10
+ } from "@heroui/modal";
11
+ import { Button } from "@heroui/button";
12
+ import { Textarea } from "@heroui/input";
13
+ import { Image } from "@heroui/image";
14
+ import { Package } from "lucide-react";
15
+
16
+ import StarRating from "@/components/shop/StarRating";
17
+
18
+ interface ReviewModalProps {
19
+ isOpen: boolean;
20
+ onClose: () => void;
21
+ orderItem: {
22
+ id: string;
23
+ productName: string;
24
+ productImage: string | null;
25
+ selectedVariant: string | null;
26
+ };
27
+ onSuccess?: () => void;
28
+ }
29
+
30
+ export default function ReviewModal({
31
+ isOpen,
32
+ onClose,
33
+ orderItem,
34
+ onSuccess,
35
+ }: ReviewModalProps) {
36
+ const [productRating, setProductRating] = useState(0);
37
+ const [shippingRating, setShippingRating] = useState(0);
38
+ const [comment, setComment] = useState("");
39
+ const [isSubmitting, setIsSubmitting] = useState(false);
40
+ const [error, setError] = useState<string | null>(null);
41
+
42
+ const handleSubmit = async () => {
43
+ if (productRating === 0) {
44
+ setError("Please rate the product");
45
+ return;
46
+ }
47
+ if (shippingRating === 0) {
48
+ setError("Please rate the shipping");
49
+ return;
50
+ }
51
+
52
+ setIsSubmitting(true);
53
+ setError(null);
54
+
55
+ try {
56
+ const response = await fetch("/api/reviews", {
57
+ method: "POST",
58
+ headers: { "Content-Type": "application/json" },
59
+ body: JSON.stringify({
60
+ orderItemId: orderItem.id,
61
+ rating: productRating,
62
+ shippingRating,
63
+ comment: comment.trim() || undefined,
64
+ }),
65
+ });
66
+
67
+ if (!response.ok) {
68
+ const data = await response.json();
69
+ throw new Error(data.error || "Failed to submit review");
70
+ }
71
+
72
+ onSuccess?.();
73
+ handleClose();
74
+ } catch (err) {
75
+ setError(err instanceof Error ? err.message : "Failed to submit review");
76
+ } finally {
77
+ setIsSubmitting(false);
78
+ }
79
+ };
80
+
81
+ const handleClose = () => {
82
+ setProductRating(0);
83
+ setShippingRating(0);
84
+ setComment("");
85
+ setError(null);
86
+ onClose();
87
+ };
88
+
89
+ return (
90
+ <Modal isOpen={isOpen} size="lg" onClose={handleClose}>
91
+ <ModalContent>
92
+ <ModalHeader className="flex flex-col gap-1">
93
+ <h3 className="text-lg font-semibold">Viết đánh giá</h3>
94
+ <p className="text-sm text-default-500">
95
+ Chia sẻ trải nghiệm của bạn với sản phẩm
96
+ </p>
97
+ </ModalHeader>
98
+
99
+ <ModalBody className="gap-6">
100
+ {/* Product info */}
101
+ <div className="flex items-center gap-4 p-3 bg-default-50 rounded-lg">
102
+ <div className="w-16 h-16 bg-default-100 rounded-lg overflow-hidden flex-shrink-0">
103
+ {orderItem.productImage ? (
104
+ <Image
105
+ alt={orderItem.productName}
106
+ className="w-full h-full object-cover"
107
+ src={orderItem.productImage}
108
+ />
109
+ ) : (
110
+ <div className="w-full h-full flex items-center justify-center">
111
+ <Package className="text-default-300" size={24} />
112
+ </div>
113
+ )}
114
+ </div>
115
+ <div>
116
+ <p className="font-medium">{orderItem.productName}</p>
117
+ {orderItem.selectedVariant && (
118
+ <p className="text-sm text-default-500">
119
+ {orderItem.selectedVariant}
120
+ </p>
121
+ )}
122
+ </div>
123
+ </div>
124
+
125
+ {/* Product rating */}
126
+ <div className="space-y-2">
127
+ <label className="text-sm font-medium">
128
+ Đánh giá sản phẩm <span className="text-danger">*</span>
129
+ </label>
130
+ <div className="flex items-center gap-3">
131
+ <StarRating
132
+ interactive
133
+ rating={productRating}
134
+ size="lg"
135
+ onRatingChange={setProductRating}
136
+ />
137
+ <span className="text-sm text-default-500">
138
+ {productRating > 0 ? `${productRating} star${productRating !== 1 ? "s" : ""}` : "Select rating"}
139
+ </span>
140
+ </div>
141
+ </div>
142
+
143
+ {/* Shipping rating */}
144
+ <div className="space-y-2">
145
+ <label className="text-sm font-medium">
146
+ Đánh giá vận chuyển <span className="text-danger">*</span>
147
+ </label>
148
+ <div className="flex items-center gap-3">
149
+ <StarRating
150
+ interactive
151
+ rating={shippingRating}
152
+ size="lg"
153
+ onRatingChange={setShippingRating}
154
+ />
155
+ <span className="text-sm text-default-500">
156
+ {shippingRating > 0 ? `${shippingRating} star${shippingRating !== 1 ? "s" : ""}` : "Select rating"}
157
+ </span>
158
+ </div>
159
+ </div>
160
+
161
+ {/* Comment */}
162
+ <div className="space-y-2">
163
+ <label className="text-sm font-medium">
164
+ Bình luận <span className="text-default-400">(Không bắt buộc)</span>
165
+ </label>
166
+ <Textarea
167
+ maxLength={2000}
168
+ placeholder="Chia sẻ cảm nghĩ của bạn về sản phẩm..."
169
+ value={comment}
170
+ onValueChange={setComment}
171
+ />
172
+ <p className="text-xs text-default-400 text-right">
173
+ {comment.length}/2000
174
+ </p>
175
+ </div>
176
+
177
+ {/* Error display */}
178
+ {error && (
179
+ <div className="p-3 bg-danger-50 text-danger-600 rounded-lg text-sm">
180
+ {error}
181
+ </div>
182
+ )}
183
+ </ModalBody>
184
+
185
+ <ModalFooter>
186
+ <Button variant="flat" onPress={handleClose}>
187
+ Hủy
188
+ </Button>
189
+ <Button
190
+ color="primary"
191
+ isLoading={isSubmitting}
192
+ onPress={handleSubmit}
193
+ >
194
+ Đăng bình luận
195
+ </Button>
196
+ </ModalFooter>
197
+ </ModalContent>
198
+ </Modal>
199
+ );
200
+ }
components/shop/ShopOverview.tsx ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { Card, CardBody } from "@heroui/card";
4
+ import { Skeleton } from "@heroui/skeleton";
5
+ import { Package, Star, Truck, Calendar } from "lucide-react";
6
+ import useSWR from "swr";
7
+
8
+ import StarRating from "@/components/shop/StarRating";
9
+
10
+ interface ShopStats {
11
+ storeName: string;
12
+ productCount: number;
13
+ totalReviews: number;
14
+ avgProductRating: number;
15
+ avgShippingRating: number;
16
+ shopCreatedAt: string;
17
+ shopAgeInDays: number;
18
+ }
19
+
20
+ interface ShopOverviewProps {
21
+ vendorId: string;
22
+ }
23
+
24
+ const fetcher = (url: string) => fetch(url).then((res) => res.json());
25
+
26
+ function formatShopAge(days: number): string {
27
+ if (days < 30) {
28
+ return `${days} ngày trước`;
29
+ }
30
+ if (days < 365) {
31
+ const months = Math.floor(days / 30);
32
+ return `${months} tháng trước`;
33
+ }
34
+ const years = Math.floor(days / 365);
35
+ const remainingMonths = Math.floor((days % 365) / 30);
36
+ if (remainingMonths === 0) {
37
+ return `${years} năm trước`;
38
+ }
39
+ return `${years} năm, ${remainingMonths} tháng trước`;
40
+ }
41
+
42
+ export default function ShopOverview({ vendorId }: ShopOverviewProps) {
43
+ const { data, isLoading, error } = useSWR<ShopStats>(
44
+ `/api/shop/${vendorId}/stats`,
45
+ fetcher
46
+ );
47
+
48
+ if (error) {
49
+ return null;
50
+ }
51
+
52
+ if (isLoading) {
53
+ return (
54
+ <Card className="mb-6 border-none shadow-md">
55
+ <CardBody className="p-6">
56
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
57
+ {[...Array(4)].map((_, i) => (
58
+ <div key={i} className="space-y-2">
59
+ <Skeleton className="h-4 w-20 rounded" />
60
+ <Skeleton className="h-6 w-16 rounded" />
61
+ </div>
62
+ ))}
63
+ </div>
64
+ </CardBody>
65
+ </Card>
66
+ );
67
+ }
68
+
69
+ if (!data) return null;
70
+
71
+ const stats = [
72
+ {
73
+ icon: Package,
74
+ label: "Products",
75
+ value: data.productCount.toString(),
76
+ color: "text-primary",
77
+ },
78
+ {
79
+ icon: Star,
80
+ label: "Đánh giá sản phẩm",
81
+ value: data.avgProductRating > 0 ? data.avgProductRating.toFixed(1) : "N/A",
82
+ showStars: data.avgProductRating > 0,
83
+ rating: data.avgProductRating,
84
+ color: "text-warning",
85
+ },
86
+ {
87
+ icon: Truck,
88
+ label: "Đánh giá vận chuyển",
89
+ value: data.avgShippingRating > 0 ? data.avgShippingRating.toFixed(1) : "N/A",
90
+ showStars: data.avgShippingRating > 0,
91
+ rating: data.avgShippingRating,
92
+ color: "text-success",
93
+ },
94
+ {
95
+ icon: Calendar,
96
+ label: "Tuổi shop",
97
+ value: formatShopAge(data.shopAgeInDays),
98
+ subtext: `${data.totalReviews} đánh giá`,
99
+ color: "text-secondary",
100
+ },
101
+ ];
102
+
103
+ return (
104
+ <Card className="mb-6 border-none shadow-md bg-gradient-to-r from-default-50 to-default-100">
105
+ <CardBody className="p-6">
106
+ <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
107
+ {stats.map((stat, index) => (
108
+ <div key={index} className="flex items-start gap-3">
109
+ <div className={`p-2 rounded-lg bg-default-100 ${stat.color}`}>
110
+ <stat.icon size={30} />
111
+ </div>
112
+ <div>
113
+ <p className="text-xs text-default-500 uppercase tracking-wide">
114
+ {stat.label}
115
+ </p>
116
+ <div className="flex items-center gap-2">
117
+ {stat.showStars ? (
118
+ <StarRating rating={stat.rating!} showValue size="sm" />
119
+ ) : (
120
+ <p className="font-semibold text-lg">{stat.value}</p>
121
+ )}
122
+ </div>
123
+ {stat.subtext && (
124
+ <p className="text-xs text-default-400">{stat.subtext}</p>
125
+ )}
126
+ </div>
127
+ </div>
128
+ ))}
129
+ </div>
130
+ </CardBody>
131
+ </Card>
132
+ );
133
+ }
components/shop/ShopReviewsSection.tsx ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use client";
2
+
3
+ import { useState } from "react";
4
+ import { Card, CardBody, CardHeader } from "@heroui/card";
5
+ import { Button } from "@heroui/button";
6
+ import { Skeleton } from "@heroui/skeleton";
7
+ import { MessageSquare, ChevronDown } from "lucide-react";
8
+ import useSWR from "swr";
9
+
10
+ import ReviewCard from "@/components/shop/ReviewCard";
11
+
12
+ interface Review {
13
+ id: string;
14
+ rating: number;
15
+ shippingRating: number | null;
16
+ comment: string | null;
17
+ createdAt: string;
18
+ isVerified: boolean;
19
+ customerName: string;
20
+ product: {
21
+ id: string;
22
+ name: string;
23
+ image: string | null;
24
+ };
25
+ variant: string | null;
26
+ }
27
+
28
+ interface ReviewsResponse {
29
+ reviews: Review[];
30
+ pagination: {
31
+ page: number;
32
+ limit: number;
33
+ total: number;
34
+ totalPages: number;
35
+ };
36
+ }
37
+
38
+ interface ShopReviewsSectionProps {
39
+ vendorId: string;
40
+ }
41
+
42
+ const fetcher = (url: string) => fetch(url).then((res) => res.json());
43
+
44
+ export default function ShopReviewsSection({ vendorId }: ShopReviewsSectionProps) {
45
+ const [page, setPage] = useState(1);
46
+ const limit = 5;
47
+
48
+ const { data, isLoading, error } = useSWR<ReviewsResponse>(
49
+ `/api/shop/${vendorId}/reviews?page=${page}&limit=${limit}`,
50
+ fetcher
51
+ );
52
+
53
+ if (error) {
54
+ return null;
55
+ }
56
+
57
+ if (!isLoading && (!data?.reviews || data.reviews.length === 0)) {
58
+ return null;
59
+ }
60
+
61
+ return (
62
+ <Card className="border-none shadow-lg bg-default-50/50 backdrop-blur-sm">
63
+ <CardHeader className="flex items-center gap-2 px-6 py-4 border-b border-default-200">
64
+ <MessageSquare className="text-primary" size={20} />
65
+ <h2 className="text-lg font-semibold">Đánh giá</h2>
66
+ {data && (
67
+ <span className="text-sm text-default-500 ml-2">
68
+ ({data.pagination.total} đánh giá)
69
+ </span>
70
+ )}
71
+ </CardHeader>
72
+
73
+ <CardBody className="p-6">
74
+ {isLoading ? (
75
+ <div className="space-y-4">
76
+ {[...Array(3)].map((_, i) => (
77
+ <div key={i} className="space-y-3 p-4 bg-default-100 rounded-lg">
78
+ <div className="flex items-center gap-3">
79
+ <Skeleton className="h-4 w-24 rounded" />
80
+ <Skeleton className="h-4 w-16 rounded" />
81
+ </div>
82
+ <Skeleton className="h-12 w-full rounded" />
83
+ <Skeleton className="h-4 w-3/4 rounded" />
84
+ </div>
85
+ ))}
86
+ </div>
87
+ ) : (
88
+ <>
89
+ <div className="space-y-4">
90
+ {data?.reviews.map((review) => (
91
+ <ReviewCard
92
+ key={review.id}
93
+ comment={review.comment}
94
+ createdAt={review.createdAt}
95
+ customerName={review.customerName}
96
+ isVerified={review.isVerified}
97
+ productImage={review.product.image}
98
+ productName={review.product.name}
99
+ rating={review.rating}
100
+ shippingRating={review.shippingRating}
101
+ variant={review.variant}
102
+ />
103
+ ))}
104
+ </div>
105
+
106
+ {/* Pagination */}
107
+ {data && data.pagination.totalPages > 1 && (
108
+ <div className="flex justify-center gap-2 mt-6">
109
+ <Button
110
+ isDisabled={page === 1}
111
+ size="sm"
112
+ variant="flat"
113
+ onPress={() => setPage((p) => Math.max(1, p - 1))}
114
+ >
115
+ Trước
116
+ </Button>
117
+ <span className="flex items-center px-4 text-sm text-default-500">
118
+ Trang {page} của {data.pagination.totalPages}
119
+ </span>
120
+ <Button
121
+ isDisabled={page >= data.pagination.totalPages}
122
+ size="sm"
123
+ variant="flat"
124
+ onPress={() => setPage((p) => p + 1)}
125
+ >
126
+ Tiếp theo
127
+ </Button>
128
+ </div>
129
+ )}
130
+
131
+ {/* Load more button for better UX */}
132
+ {data && page === 1 && data.pagination.totalPages > 1 && (
133
+ <div className="flex justify-center mt-4">
134
+ <Button
135
+ className="gap-2"
136
+ endContent={<ChevronDown size={16} />}
137
+ variant="light"
138
+ onPress={() => setPage((p) => p + 1)}
139
+ >
140
+ Hiện thêm đánh giá
141
+ </Button>
142
+ </div>
143
+ )}
144
+ </>
145
+ )}
146
+ </CardBody>
147
+ </Card>
148
+ );
149
+ }
package.json CHANGED
@@ -96,6 +96,7 @@
96
  "recharts": "^3.7.0",
97
  "resend": "^6.9.1",
98
  "sanitize-html": "^2.17.0",
 
99
  "tailwind-merge": "^3.4.0",
100
  "zod": "^4.1.13",
101
  "zustand": "^5.0.8"
 
96
  "recharts": "^3.7.0",
97
  "resend": "^6.9.1",
98
  "sanitize-html": "^2.17.0",
99
+ "swr": "^2.4.0",
100
  "tailwind-merge": "^3.4.0",
101
  "zod": "^4.1.13",
102
  "zustand": "^5.0.8"
prisma/schema.prisma CHANGED
@@ -292,6 +292,7 @@ model Order {
292
  address Address @relation(fields: [addressId], references: [id])
293
  coupon Coupon? @relation(fields: [couponId], references: [id], onDelete: SetNull)
294
  items OrderItem[]
 
295
 
296
  @@index([status])
297
  @@index([userId])
@@ -309,6 +310,7 @@ model OrderItem {
309
 
310
  order Order @relation(fields: [orderId], references: [id], onDelete: Cascade)
311
  product Product @relation(fields: [productId], references: [id])
 
312
 
313
  @@map("order_items")
314
  }
@@ -331,22 +333,28 @@ model Address {
331
 
332
  // Review system
333
  model Review {
334
- id String @id @default(cuid())
335
- productId String
336
- userId String
337
- rating Int // 1-5
338
- title String?
339
- comment String? @db.Text
340
- isVerified Boolean @default(false) // Did user purchase product?
341
- createdAt DateTime @default(now())
342
- updatedAt DateTime @updatedAt
 
 
 
343
 
344
- product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
345
- user User @relation(fields: [userId], references: [id], onDelete: Cascade)
 
 
346
 
347
  @@unique([productId, userId])
348
  @@index([productId])
349
  @@index([userId])
 
350
  @@map("reviews")
351
  }
352
 
 
292
  address Address @relation(fields: [addressId], references: [id])
293
  coupon Coupon? @relation(fields: [couponId], references: [id], onDelete: SetNull)
294
  items OrderItem[]
295
+ reviews Review[]
296
 
297
  @@index([status])
298
  @@index([userId])
 
310
 
311
  order Order @relation(fields: [orderId], references: [id], onDelete: Cascade)
312
  product Product @relation(fields: [productId], references: [id])
313
+ review Review? // One review per order item
314
 
315
  @@map("order_items")
316
  }
 
333
 
334
  // Review system
335
  model Review {
336
+ id String @id @default(cuid())
337
+ productId String
338
+ userId String
339
+ orderId String? // Link to order (for order-based reviews)
340
+ orderItemId String? @unique // Link to specific order item (one review per item)
341
+ rating Int // 1-5 (product rating)
342
+ shippingRating Int? // 1-5 (shipping rating, required for order reviews)
343
+ title String?
344
+ comment String? @db.Text
345
+ isVerified Boolean @default(false) // Did user purchase product?
346
+ createdAt DateTime @default(now())
347
+ updatedAt DateTime @updatedAt
348
 
349
+ product Product @relation(fields: [productId], references: [id], onDelete: Cascade)
350
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
351
+ order Order? @relation(fields: [orderId], references: [id], onDelete: SetNull)
352
+ orderItem OrderItem? @relation(fields: [orderItemId], references: [id], onDelete: SetNull)
353
 
354
  @@unique([productId, userId])
355
  @@index([productId])
356
  @@index([userId])
357
+ @@index([orderId])
358
  @@map("reviews")
359
  }
360