Parcourir la source

扣除积分 更新记录

charles_c il y a 5 mois
Parent
commit
57620668e2

+ 50 - 5
src/app/api/exchange-history/route.js

@@ -1,6 +1,8 @@
 import dbConnect from "../../lib/dbConnect";
 import ExchangeHistory from "../../models/ExchangeHistory";
 import ExchangeItem from "../../models/ExchangeItem";
+import User from "../../models/User";
+import PointHistory from "../../models/PointHistory";
 import { NextResponse } from "next/server";
 import { setCORSHeaders, handleError } from "../../lib/apiUtils";
 
@@ -128,6 +130,24 @@ export async function PUT(request) {
   try {
     const { id, ...updateData } = await request.json();
     console.log(id, updateData);
+
+    // 获取原始的兑换历史记录
+    const originalExchangeHistory = await ExchangeHistory.findById(id).populate(
+      "item"
+    );
+    if (!originalExchangeHistory) {
+      return NextResponse.json(
+        { success: false, error: "未找到兑换历史" },
+        { status: 404 }
+      );
+    }
+
+    // 保存原始状态
+    const originalStatus = originalExchangeHistory.status;
+
+    console.log("originalExchangeHistory", originalExchangeHistory);
+
+    // 更新兑换历史
     const updatedExchangeHistory = await ExchangeHistory.findByIdAndUpdate(
       id,
       updateData,
@@ -135,12 +155,37 @@ export async function PUT(request) {
         new: true,
         runValidators: true,
       }
-    );
-    if (!updatedExchangeHistory) {
-      return NextResponse.json(
-        { success: false, error: "未找到兑换历史" },
-        { status: 404 }
+    ).populate("item");
+
+    // 检查状态是否变更为"已兑换"
+    if (updateData.status === "已兑换" && originalStatus !== "已兑换") {
+      const pointsToDeduct = updatedExchangeHistory.item.points;
+
+      // 更新用户积分
+      const updatedUser = await User.findByIdAndUpdate(
+        updatedExchangeHistory.userId,
+        { $inc: { points: -pointsToDeduct } }, // 减少用户积分
+        { new: true, runValidators: true }
       );
+
+      if (!updatedUser) {
+        throw new Error("更新用户积分失败");
+      }
+
+      console.log(
+        `用户 ${updatedUser.username} 的积分已扣除 ${pointsToDeduct} 点`
+      );
+
+      // 创建积分历史记录
+      const reason = `兑换: ${updatedExchangeHistory.item.title
+        .replace(/<[^>]*>/g, "")
+        .trim()}`;
+      const pointHistory = new PointHistory({
+        user: updatedUser._id,
+        points: -pointsToDeduct,
+        reason: reason,
+      });
+      await pointHistory.save();
     }
     const response = NextResponse.json(
       { success: true, data: updatedExchangeHistory },

+ 0 - 2
src/app/api/updateForMatch/route.js

@@ -85,8 +85,6 @@ export async function POST(request) {
             points: pointsEarned,
             reason: reason,
             match: match._id,
-            oldPoints: oldPoints,
-            newPoints: newPoints,
           });
           await pointHistory.save();
         }

+ 1 - 7
src/app/exchange-points/ExchangeForm.jsx

@@ -3,15 +3,9 @@
 import { useState, useEffect } from "react";
 import { X } from "lucide-react";
 
-export default function ExchangeForm({ item, onClose, setAlert }) {
+export default function ExchangeForm({ currentUser, item, onClose, setAlert }) {
   const [formData, setFormData] = useState({});
   const [isSubmitting, setIsSubmitting] = useState(false);
-  const [currentUser, setCurrentUser] = useState(null);
-
-  useEffect(() => {
-    const user = JSON.parse(localStorage.getItem("currentUser") || "null");
-    setCurrentUser(user);
-  }, []);
 
   const handleInputChange = (e) => {
     setFormData({ ...formData, [e.target.name]: e.target.value });

+ 3 - 3
src/app/exchange-points/page.js

@@ -3,7 +3,6 @@
 import Alert from "../ui/components/Alert";
 import ExchangeForm from "./ExchangeForm";
 import { ChevronLeft } from "lucide-react";
-import Image from "next/image";
 import { useRouter } from "next/navigation";
 import { useState, useEffect } from "react";
 import InfiniteScroll from "react-infinite-scroll-component";
@@ -91,9 +90,9 @@ export default function ExchangePage() {
             >
               <div className="flex items-center justify-between">
                 <div className="flex items-center flex-grow">
-                  <Image
+                  <img
                     src={item.logo}
-                    alt={item.title}
+                    // alt={item.title}
                     width={50}
                     height={50}
                     className="rounded-full mr-4 flex-shrink-0"
@@ -181,6 +180,7 @@ export default function ExchangePage() {
 
         {selectedItem && (
           <ExchangeForm
+            currentUser={currentUser}
             item={selectedItem}
             setAlert={setAlert}
             onClose={() => setSelectedItem(null)}