Browse Source

问题修复

jax 4 months ago
parent
commit
b1520a4626

+ 17 - 0
.vscode/launch.json

@@ -0,0 +1,17 @@
+{
+    // 使用 IntelliSense 了解相关属性。 
+    // 悬停以查看现有属性的描述。
+    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
+    "version": "0.2.0",
+    "configurations": [
+        {
+            "type": "node",
+            "request": "launch",
+            "name": "启动程序",
+            "skipFiles": [
+                "<node_internals>/**"
+            ],
+            "program": "${file}"
+        }
+    ]
+}

BIN
public/images/login_1919.webp


BIN
public/images/login_logo.jpg


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

@@ -10,8 +10,6 @@ export async function GET(request) {
   try {
     const isFromFrontend = request.headers.get("x-from-frontend") === "true";
 
-    console.log("isFromFrontend", isFromFrontend);
-
     let activities;
     let message;
 

+ 43 - 10
src/app/api/exchange-history/route.js

@@ -9,7 +9,7 @@ import { withAuth } from "../../middleware/authMiddleware";
 
 export const GET = withAuth(async (request) => {
   await dbConnect();
-  console.log("GET请求已接收");
+
   try {
     const { searchParams } = new URL(request.url);
     let query = {};
@@ -52,9 +52,6 @@ export const GET = withAuth(async (request) => {
       }
     }
 
-    console.log("Query:", query);
-    console.log("Item Query:", itemQuery);
-
     // 首先查找符合条件的 ExchangeItem
     const matchedItems = await ExchangeItem.find(itemQuery).select("_id");
     const itemIds = matchedItems.map((item) => item._id);
@@ -67,7 +64,7 @@ export const GET = withAuth(async (request) => {
     const exchangeHistories = await ExchangeHistory.find(query).populate(
       "item",
       "title type points"
-    );
+    ).sort({ createdAt: -1 });
 
     const message =
       exchangeHistories.length > 0
@@ -137,6 +134,7 @@ export const POST = withAuth(async (request) => {
       username,
       item,
       status,
+      pointsToDeduct,
       exchangeInfo,
       exchangeTime,
       exchangeCount,
@@ -186,7 +184,44 @@ export const PUT = withAuth(async (request) => {
   await dbConnect();
   try {
     const { id, ...updateData } = await request.json();
-    console.log(id, updateData);
+
+    const response = NextResponse.json(
+      { success: true, data: null },
+      { status: 200 }
+    );
+
+    //如果是拒绝
+    if (updateData?.status == '拒绝') {
+      const exchangeHistory = await ExchangeHistory.findById(id);
+      if (!exchangeHistory) {
+        return NextResponse.json(
+          { success: false, error: "未找到兑换历史" },
+          { status: 404 }
+        );
+      }
+      console.log('exchangeHistory=' + exchangeHistory)
+      console.log('exchangeHistorypoints=' + exchangeHistory.points)
+      // 更新用户积分
+      const updatedUser = await User.findByIdAndUpdate(
+        exchangeHistory.userId,
+        { $inc: { points: +exchangeHistory.points } },
+        { new: true, runValidators: true }
+      );
+
+      if (!updatedUser) {
+        throw new Error("更新用户积分失败");
+      }
+      const exchangeItem = await ExchangeItem.findById(exchangeHistory.item);
+      // 创建积分加减历史记录
+      const reason = `返还: ${exchangeItem.title.replace(/<[^>]*>/g, "").trim()} 积分`;
+      const pointHistory = new PointHistory({
+        user: updatedUser._id,
+        points: +exchangeHistory.points,
+        reason: reason,
+      });
+      await pointHistory.save();
+
+    }
     const updatedExchangeHistory = await ExchangeHistory.findByIdAndUpdate(
       id,
       updateData,
@@ -200,11 +235,9 @@ export const PUT = withAuth(async (request) => {
         { success: false, error: "未找到兑换历史" },
         { status: 404 }
       );
+
     }
-    const response = NextResponse.json(
-      { success: true, data: updatedExchangeHistory },
-      { status: 200 }
-    );
+
     return setCORSHeaders(response);
   } catch (error) {
     return handleError(error);

+ 2 - 4
src/app/api/match/route.js

@@ -86,7 +86,7 @@ export async function GET(request) {
           }
         }
 
-        console.log("Search Query:", searchQuery);
+        // console.log("Search Query:", searchQuery);
 
         // await Promise.all([
         //   // 更新所有开始超过2小时的比赛为已结束
@@ -130,7 +130,7 @@ export async function GET(request) {
         const skip = (current - 1) * pageSize;
         const totalMatches = await Match.countDocuments(searchQuery);
         const matchesData = await Match.find(searchQuery)
-          .sort({ date: 1, time: 1 })
+          .sort({ date: -1, time: -1 })
           .skip(skip)
           .limit(pageSize);
 
@@ -304,8 +304,6 @@ export const DELETE = withAuth(async (request) => {
     const id = url.searchParams.get("id");
     const ids = url.searchParams.get("ids");
 
-    console.log("Received delete request for id:", id, "or ids:", ids);
-
     if (!id && !ids) {
       return NextResponse.json(
         { success: false, error: "缺少比赛ID" },

+ 0 - 2
src/app/api/new-activities/route.js

@@ -10,8 +10,6 @@ export async function GET(request) {
   try {
     const isFromFrontend = request.headers.get("x-from-frontend") === "true";
 
-    console.log("isFromFrontend", isFromFrontend);
-
     let activities;
     let message;
 

+ 45 - 54
src/app/api/prediction/route.js

@@ -11,7 +11,8 @@ export const GET = withAuth(async (request) => {
     const { searchParams } = new URL(request.url);
     const current = parseInt(searchParams.get("current") || "1");
     const pageSize = parseInt(searchParams.get("pageSize") || "10");
-    const matchInfo = searchParams.get("matchInfo");
+    const homeTeam = searchParams.get("homeTeam");
+    const awayTeam = searchParams.get("awayTeam");
     const username = searchParams.get("username");
     const type = searchParams.get("type"); // 新增type参数来筛选运动类型
 
@@ -29,7 +30,7 @@ export const GET = withAuth(async (request) => {
     // 处理其他搜索参数
     for (const [key, value] of searchParams.entries()) {
       if (
-        ["current", "pageSize", "matchInfo", "username", "type"].includes(key)
+        ["current", "pageSize", "homeTeam", "awayTeam", "username", "type"].includes(key)
       )
         continue;
 
@@ -112,27 +113,22 @@ export const GET = withAuth(async (request) => {
       { $sort: { createdAt: -1 } },
     ];
 
-    if (matchInfo) {
+    if (homeTeam) {
       pipeline.push({
         $match: {
-          $or: [
-            {
-              "matchDetails.homeTeam.name": {
-                $regex: matchInfo,
-                $options: "i",
-              },
-            },
-            {
-              "matchDetails.awayTeam.name": {
-                $regex: matchInfo,
-                $options: "i",
-              },
-            },
-          ],
+          "matchDetails.homeTeam.name": homeTeam,
+        },
+      });
+    }
+    if (awayTeam) {
+      pipeline.push({
+        $match: {
+          "matchDetails.awayTeam.name": awayTeam,
         },
       });
     }
 
+
     const countPipeline = [...pipeline, { $count: "total" }];
     const totalResult = await Prediction.aggregate(countPipeline);
     const totalCount = totalResult.length > 0 ? totalResult[0].total : 0;
@@ -152,7 +148,8 @@ export const GET = withAuth(async (request) => {
           ...prediction,
           match: undefined,
           matchDetails: undefined,
-          matchInfo: `${prediction.matchDetails.homeTeam.name}:${prediction.matchDetails.awayTeam.name}`,
+          homeTeam: prediction.matchDetails.homeTeam.name,
+          awayTeam: prediction.matchDetails.awayTeam.name
         };
 
         // 根据运动类型添加特定信息
@@ -194,8 +191,6 @@ export const POST = withAuth(async (request) => {
     const body = await request.json();
     const { userId, predictions } = body;
 
-    console.log(111, userId, predictions);
-
     if (!userId) {
       return NextResponse.json(
         { success: false, error: "请先登录" },
@@ -224,9 +219,6 @@ export const POST = withAuth(async (request) => {
         match: matchId,
       });
 
-      console.log(111, pred, matchId);
-      console.log("existingPrediction", existingPrediction);
-
       if (existingPrediction) {
         // 更新预测
         if (type === "football" && football) {
@@ -247,7 +239,6 @@ export const POST = withAuth(async (request) => {
               football.totalGoals.prediction;
           }
         } else if (type === "basketball" && basketball) {
-          console.log(222);
 
           if (basketball.whoWillWin) {
             existingPrediction.basketball.whoWillWin.prediction =
@@ -273,24 +264,24 @@ export const POST = withAuth(async (request) => {
           type,
           ...(type === "football" &&
             football && {
-              football: {
-                whoWillWin: { prediction: football.whoWillWin.prediction },
-                firstTeamToScore: {
-                  prediction: football.firstTeamToScore.prediction,
-                  firstTeamToScoreLogo:
-                    football.firstTeamToScore.firstTeamToScoreLogo,
-                },
-                totalGoals: { prediction: football.totalGoals.prediction },
+            football: {
+              whoWillWin: { prediction: football.whoWillWin.prediction },
+              firstTeamToScore: {
+                prediction: football.firstTeamToScore.prediction,
+                firstTeamToScoreLogo:
+                  football.firstTeamToScore.firstTeamToScoreLogo,
               },
-            }),
+              totalGoals: { prediction: football.totalGoals.prediction },
+            },
+          }),
           ...(type === "basketball" &&
             basketball && {
-              basketball: {
-                whoWillWin: { prediction: basketball.whoWillWin.prediction },
-                spread: { prediction: basketball.spread.prediction },
-                totalPoints: { prediction: basketball.totalPoints.prediction },
-              },
-            }),
+            basketball: {
+              whoWillWin: { prediction: basketball.whoWillWin.prediction },
+              spread: { prediction: basketball.spread.prediction },
+              totalPoints: { prediction: basketball.totalPoints.prediction },
+            },
+          }),
         });
 
         const savedPrediction = await newPrediction.save();
@@ -323,24 +314,24 @@ export const PUT = withAuth(async (request) => {
       type,
       ...(type === "football" &&
         football && {
-          football: {
-            whoWillWin: { prediction: football.whoWillWin.prediction },
-            firstTeamToScore: {
-              prediction: football.firstTeamToScore.prediction,
-              firstTeamToScoreLogo:
-                football.firstTeamToScore.firstTeamToScoreLogo,
-            },
-            totalGoals: { prediction: football.totalGoals.prediction },
+        football: {
+          whoWillWin: { prediction: football.whoWillWin.prediction },
+          firstTeamToScore: {
+            prediction: football.firstTeamToScore.prediction,
+            firstTeamToScoreLogo:
+              football.firstTeamToScore.firstTeamToScoreLogo,
           },
-        }),
+          totalGoals: { prediction: football.totalGoals.prediction },
+        },
+      }),
       ...(type === "basketball" &&
         basketball && {
-          basketball: {
-            whoWillWin: { prediction: basketball.whoWillWin.prediction },
-            spread: { prediction: basketball.spread.prediction },
-            totalPoints: { prediction: basketball.totalPoints.prediction },
-          },
-        }),
+        basketball: {
+          whoWillWin: { prediction: basketball.whoWillWin.prediction },
+          spread: { prediction: basketball.spread.prediction },
+          totalPoints: { prediction: basketball.totalPoints.prediction },
+        },
+      }),
     };
 
     const updatedPrediction = await Prediction.findByIdAndUpdate(

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

@@ -47,7 +47,7 @@ export default function ExchangeForm({
         // exchangeCount: formData.exchangeCount || 1,
       };
 
-      console.log("params", params);
+      // console.log("params", params);
 
       const res = await fetchApi("/api/exchange-history", {
         method: "POST",
@@ -67,6 +67,8 @@ export default function ExchangeForm({
         };
         localStorage.setItem("currentUser", JSON.stringify(updatedUser));
         setCurrentUser(updatedUser);
+
+
       } else {
         setAlert({ type: "error", message: res.error });
       }

+ 6 - 7
src/app/exchange-points/page.js

@@ -269,15 +269,14 @@ export default function ExchangePage() {
                         }}
                       ></p>
                       <p
-                        className={`text-sm font-medium ${
-                          exchange.status === "待兑换已审核"
+                        className={`text-sm font-medium ${exchange.status === "待兑换已审核"
                             ? "text-blue-600"
                             : exchange.status === "待兑换未审核"
-                            ? "text-gray-600"
-                            : exchange.status === "已兑换"
-                            ? "text-green-600"
-                            : "text-gray-600"
-                        }`}
+                              ? "text-gray-600"
+                              : exchange.status === "已兑换"
+                                ? "text-green-600"
+                                : "text-gray-600"
+                          }`}
                       >
                         {exchange.status}
                       </p>

+ 1 - 1
src/app/login/page.js

@@ -50,7 +50,7 @@ export default function LoginPage() {
       {/* 背景图片 */}
       <div className="absolute inset-0 flex">
         <img
-          src="https://007xagm5vezzk-fluid-aliyun.erzjzd.com/assets/bd7-bg_mobile@3x-0648c73a.png"
+          src="./images/login_logo.jpg"
           alt="背景图片"
           className="object-cover"
         />

+ 2 - 1
src/app/models/ExchangeHistory.js

@@ -18,9 +18,10 @@ const ExchangeHistorySchema = new mongoose.Schema(
     },
     status: {
       type: String,
-      enum: ["待兑换未审核", "待兑换已审核", "已兑换"],
+      enum: ["待兑换未审核", "待兑换已审核", "已兑换", "拒绝"],
       default: "待兑换未审核",
     },
+    points: { type: Number },
     exchangeInfo: {
       account: { type: String },
       name: { type: String },

+ 4 - 0
src/app/models/Match.js

@@ -83,4 +83,8 @@ const MatchSchema = new mongoose.Schema(
   { timestamps: true }
 );
 
+MatchSchema.index({ "homeTeam.name": 1 }); // homeTeam.name 索引
+MatchSchema.index({ "awayTeam.name": 1 }); // awayTeam.name 索引
+MatchSchema.index({ date: 1 }); // 按照比赛日期索引
+
 export default mongoose.models.Match || mongoose.model("Match", MatchSchema);

+ 0 - 4
src/app/ui/BasketballMatch.jsx

@@ -13,10 +13,6 @@ const BasketballMatch = ({ selectedDayMatches, currentUser }) => {
   const [alert, setAlert] = useState(null);
   const [predictions, setPredictions] = useState([]);
 
-  console.log("selectedDayMatches", selectedDayMatches);
-
-  console.log("predictions", predictions);
-
   // 获取用户预测
   useEffect(() => {
     const fetchPredictions = async () => {

+ 0 - 20
src/app/ui/FootballMatch.jsx

@@ -32,33 +32,14 @@ const FootballMatch = ({ selectedDayMatches, currentUser }) => {
 
   const [selectedFirstTeamToScore, setSelectedFirstTeamToScore] = useState(""); // ["home", "away", "no_goal"]
 
-  // console.log("selectedDayMatches", selectedDayMatches);
-  // console.log("selectedFirstTeamToScore", selectedFirstTeamToScore);
-
-  // console.log(
-  //   "selectedFirstTeamToScoreOfMatch",
-  //   selectedFirstTeamToScoreOfMatch
-  // );
-  // console.log("selectedMatchId", selectedMatchId);
-  // console.log("selectedMatch", selectedMatch);
-
-  // console.log("selectedWinTeams", selectedWinTeams);
-  // console.log("totalGoalCountOfMatch", totalGoalCountOfMatch);
-
   const selectedWinTeam = selectedWinTeams[selectedMatchId] || "";
 
-  // console.log("selectedWinTeam", selectedWinTeam);
-
-  // console.log("predictions", predictions);
-
   const predictionMap = predictions.reduce((map, prediction) => {
     map[prediction.matchId] = prediction;
     return map;
   }, {});
-  // console.log("predictionMap", predictionMap);
 
   useEffect(() => {
-    // console.log("currentUser", currentUser);
     const fetchPredictions = async () => {
       try {
         const res = await fetchApi(
@@ -79,7 +60,6 @@ const FootballMatch = ({ selectedDayMatches, currentUser }) => {
   }, [currentUser]);
 
   useEffect(() => {
-    console.log("selectedMatchId", selectedMatchId);
     if (selectedMatchId !== null) {
       handleSubmitPredictions();
     }

+ 0 - 1
src/app/ui/MatchPrediction.jsx

@@ -42,7 +42,6 @@ const MatchPrediction = ({ currentUser }) => {
   const [footballMatches, setFootballMatches] = useState([]);
   const [basketballMatches, setBasketballMatches] = useState([]);
 
-  console.log("activeTab", activeTab);
   const handleMatchSelect = (matches) => {
     if (activeTab === "football") {
       setFootballMatches(matches);