charles_c 5 kuukautta sitten
vanhempi
commit
6e1d8525b1
1 muutettua tiedostoa jossa 99 lisäystä ja 0 poistoa
  1. 99 0
      src/app/api/one-click-clear/route.js

+ 99 - 0
src/app/api/one-click-clear/route.js

@@ -0,0 +1,99 @@
+import dbConnect from "../../lib/dbConnect";
+import PointHistory from "../../models/PointHistory";
+import User from "../../models/User";
+import ExchangeHistory from "../../models/ExchangeHistory";
+import Prediction from "../../models/Prediction";
+import { NextResponse } from "next/server";
+import { setCORSHeaders, handleError } from "../../lib/apiUtils";
+
+export async function POST(request) {
+  await dbConnect();
+
+  try {
+    // 计算一年前的时间
+    const oneYearAgo = new Date();
+    oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
+
+    // 1. 查找一年内未登录的用户
+    const inactiveUsers = await User.find({
+      lastLoginAt: {
+        $exists: true, // lastLoginAt 字段存在
+        $lt: oneYearAgo, // 最后登录时间早于一年前
+      },
+    });
+
+    console.log("找到的不活跃用户数:", inactiveUsers.length);
+
+    if (inactiveUsers.length === 0) {
+      return setCORSHeaders(
+        NextResponse.json({
+          success: false,
+          error: "没有找到需要清理的不活跃用户",
+          data: { inactiveUsersCount: 0 },
+        })
+      );
+    }
+
+    // 获取这些用户的ID
+    const userIds = inactiveUsers.map((user) => user._id);
+
+    let deletedCounts = {
+      points: 0,
+      predictions: 0,
+      exchanges: 0,
+    };
+
+    // 使用 Promise.all 并行执行删除操作
+    const [
+      pointHistoryResult,
+      predictionResult,
+      exchangeHistoryResult,
+      userUpdateResult,
+    ] = await Promise.all([
+      // 1. 清空这些用户的积分历史记录
+      PointHistory.deleteMany({ user: { $in: userIds } }),
+
+      // 2. 清空这些用户的预测记录
+      Prediction.deleteMany({ user: { $in: userIds } }),
+
+      // 3. 清空这些用户的兑换记录
+      ExchangeHistory.deleteMany({ userId: { $in: userIds } }),
+
+      // 4. 重置这些用户积分为0
+      User.updateMany({ _id: { $in: userIds } }, { $set: { points: 0 } }),
+    ]);
+
+    // 统计删除结果
+    deletedCounts.points = pointHistoryResult.deletedCount;
+    deletedCounts.predictions = predictionResult.deletedCount;
+    deletedCounts.exchanges = exchangeHistoryResult.deletedCount;
+
+    const response = NextResponse.json(
+      {
+        success: true,
+        message: `已清空 ${inactiveUsers.length} 个不活跃用户的记录`,
+        data: {
+          inactiveUsersCount: inactiveUsers.length,
+          inactiveUsernames: inactiveUsers.map((user) => user.username), // 可选:返回被清理的用户名列表
+          deletedRecords: {
+            pointHistories: deletedCounts.points,
+            predictions: deletedCounts.predictions,
+            exchangeHistories: deletedCounts.exchanges,
+            userUpdated: userUpdateResult.modifiedCount,
+          },
+        },
+      },
+      { status: 200 }
+    );
+
+    return setCORSHeaders(response);
+  } catch (error) {
+    console.error("清空记录时出错:", error);
+    return handleError(error);
+  }
+}
+
+export async function OPTIONS() {
+  const response = new NextResponse(null, { status: 204 });
+  return setCORSHeaders(response);
+}