手机号注册后刷新存放当前用户可用数量的map

This commit is contained in:
2025-12-18 13:37:02 +08:00
parent fd8d44e4ce
commit 278743fab3
3 changed files with 115 additions and 72 deletions

View File

@@ -1609,7 +1609,6 @@
const weixinloading = document.querySelector(".weixin-loading")
let controller = null;
let sessIdList = [];
let openId = '';
let isStopped = false;//是否停止输出
let isUpload = {};
let hasImage = false;
@@ -1621,6 +1620,8 @@
console.log(params.get("userId"), 644, params.get("nickname"), params.get("headingimg"));
const encodedUserId = params.get("userId");
let openId= params.get("openid")?params.get("openid"):'';
const from = params.get("from");
let token = params.get("token");//app的token
let localtoken = params.get("localtoken");//公众号的localtoken
@@ -1748,6 +1749,7 @@
// setCookie('token', res.token);
unshowpop();
// getSessionList();
refreshAiChatNum()
}
// } else {
@@ -2044,6 +2046,7 @@
if (!sessIdList || sessIdList.length == 0) {
activeChatId = null;
chatMessages.innerHTML = "";
weixinloading.classList.add("none");
return;
}
// if (isNew == "new") {
@@ -2724,6 +2727,17 @@
}
}
async function refreshAiChatNum() {
const data = {
userId: userId
}
const res = await fetch("https://serviceai.satabot.com/refreshAiChatNum", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data) // ✅ 加上 signal
});
}
function showpop() {
let html = `<div class='popbox'>
@@ -2928,6 +2942,9 @@
// credentials: 'include', // 发送 cookie
// body: JSON.stringify(sendParam),
}).then(res => res.json()).then(data => {
if (!weixinloading.classList.contains("none")) {
weixinloading.classList.add("none");
}
// chats = data.messages;
// renderChatList();
if (controller) return;
@@ -3070,7 +3087,6 @@
// 请求成功,渲染页面
console.log('获取会话列表成功');
sessIdList = data.sessions;
weixinloading.classList.add("none");
renderChatList();
})
@@ -3219,19 +3235,19 @@
}
});
window.addEventListener('beforeunload', function (event) {
const data = {
userId: userId
}
const res = fetch('https://serviceai.satabot.com/updateAiChatNum', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
// window.addEventListener('beforeunload', function (event) {
// const data = {
// userId: userId
// }
// const res = fetch('https://serviceai.satabot.com/updateAiChatNum', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify(data)
// });
// localStorage.setItem('remainChatNum', JSON.stringify(data));
console.log(res, 98888);
debugger;
})
// })
</script>
</body>

View File

@@ -8,7 +8,7 @@
<meta property=" og:title" content="飒沓光伏智能体">
<meta property="og:description" content="SataBot Agent 是一款由人工智能驱动的光伏场景AI应用程序。">
<meta property="og:image" content="http://1.95.137.212:19000/mbzn/16%3A33%3A49123.png">
<!-- <script src=" https://unpkg.com/vconsole@latest/dist/vconsole.min.js"> -->
<script src=" https://unpkg.com/vconsole@latest/dist/vconsole.min.js">
</script>
<link rel="prefetch" href="index.html">
@@ -654,7 +654,7 @@
</div>
<script>
// 开启 vConsole 调试面板
// var vConsole = new VConsole();
var vConsole = new VConsole();
// wx364b8ebf17fe45fe wx0eeb7556d60121db
// console.log("✅ vConsole 已经启动");
const params = new URLSearchParams(window.location.search);
@@ -724,6 +724,7 @@
loginPlatForm: 2
}
console.log(id);
retryFetch("https://serviceri.satabot.com/login", {
method: "POST",
headers: {
@@ -744,13 +745,13 @@
// window.location.replace(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${_token}&t=${t}`)
} else if (res.code == 200) {
setCookie('token', res.token);
const encodedUserId = btoa(unescape(encodeURIComponent(res.userId)));
localStorage.setItem('userId', encodedUserId);
const t = Date.now();
document.body.classList.add('fadeout');
// setCookie('token', res.token);
// const encodedUserId = btoa(unescape(encodeURIComponent(res.userId)));
// localStorage.setItem('userId', encodedUserId);
// const t = Date.now();
// document.body.classList.add('fadeout');
window.location.replace(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${res.token}&t=${t}`)
// window.location.replace(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${res.token}&t=${t}`)
}
})
.catch(err => {
@@ -801,7 +802,7 @@
const t = Date.now();
document.body.classList.add('fadeout');
window.location.replace(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${res.token}&t=${t}`)
window.location.replace(`https://ai.satabot.com?userId=${encodedUserId}&headingimg=${userInfo.headimgurl}&nickname=${userInfo.nickname}&localtoken=${res.token}&t=${t}&openid=${id}`)
}
})
.catch(err => {

View File

@@ -896,7 +896,6 @@ async function setQuota(userId,num) {
async function hasQuota(userId) {
const m = getMutex(userId);
return await m.runExclusive(async () => {
console.log("更新用户对话次数:", userId, num);
return aiChatNum.has(userId);
});
}
@@ -904,7 +903,8 @@ async function hasQuota(userId) {
async function getQuota(userId) {
const m = getMutex(userId);
return await m.runExclusive(async () => {
console.log("更新用户对话次数:", userId, num);
console.log("获取用户对话次数1:", userId, aiChatNum);
console.log("获取用户对话次数:", userId, aiChatNum.get(userId));
return aiChatNum.get(userId);
});
}
@@ -918,43 +918,54 @@ async function removeQuota(userId) {
}
// ====================== API ======================
app.post("/updateAiChatNum", async (req, res) => {
app.post("/refreshAiChatNum", async (req, res) => {
const { userId } = req.body;
console.log(userId,98888888888);
if(!hasQuota(userId)){
return res.status(400).json({ error: "用户不存在" });
}else{
// 删除当前内存map存放的可用数量
removeQuota(userId);
await pool.query(
"update sys_user set ai_chat_num = ? where user_id= ?",
[aiChatNum.get(userId),userId]
console.log(userId,"刷新对话次数");
try {
const [userRemainChatNum] = await pool.query(
"SELECT ai_chat_num from sys_user where user_id= ?",
[userId]
);
res.json({ code: 0, message: "更新成功" });
}
if (userRemainChatNum.length > 0) {
const quota = userRemainChatNum[0].ai_chat_num;
console.log(userId,"刷新对话次数",quota);
await setQuota(userId,quota);
}
} catch (error) {
console.error("更新失败:", error);
}
})
app.post("/analyze", upload.single("file"), async (req, res) => {
try
const { userId } = req.body;
try
{
const { userId } = req.body;
if(!hasQuota(userId)){
const exists = await hasQuota(userId);
console.log(exists,"exists");
if (!exists) {
const [userRemainChatNum] = await pool.query(
"SELECT ai_chat_num from sys_user where user_id= ?",
"SELECT ai_chat_num from sys_user where user_id= ?",
[userId]
);
if (userRemainChatNum.length>0) {
setQuota(userId,userRemainChatNum[0].ai_chat_num);
console.log(userRemainChatNum,"userRemainChatNum");
if (userRemainChatNum.length > 0) {
const quota = userRemainChatNum[0].ai_chat_num;
console.log(quota,"quota");
console.log(quota <= 0 && quota !== -1,"quota2");
if (quota <= 0 && quota !== -1) {
return res.status(400).json({ error: "对话次数已用完,请完成账号注册" });
}
await setQuota(userId,quota);
}
}else{
if(getQuota(userId)<=0 && getQuota(userId)!==-1){
} else {
const quota = await getQuota(userId);
if (quota <= 0 && quota !== -1) {
return res.status(400).json({ error: "对话次数已用完,请完成账号注册" });
}
}
}
const { requestId } = req.body;
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.setHeader("Transfer-Encoding", "chunked");
@@ -983,21 +994,20 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
}
const { userPrompt, imageBase64, sessionId } = req.body;
const [rows] = await pool.query(
`
SELECT EXISTS(
SELECT 1
FROM ai_chat_messages
WHERE session_id = ?
AND user_id = ?
AND title IS NOT NULL
AND title != ''
) AS hasTitle
`,
[sessionId, userId]
);
const existingTitle = rows[0].hasTitle === 1; // true / false
console.log(existingTitle, rows?.[0], 9999, rows)
`
SELECT EXISTS(
SELECT 1
FROM ai_chat_messages
WHERE session_id = ?
AND user_id = ?
AND title IS NOT NULL
AND title != ''
) AS hasTitle
`,
[sessionId, userId]
);
const existingTitle = rows[0].hasTitle === 1; // true / false
console.log(existingTitle, rows?.[0], 9999, rows)
// 如果前端没有传 sessionId,生成一个
const sessId = sessionId || Date.now().toString();
@@ -1246,20 +1256,36 @@ const existingTitle = rows[0].hasTitle === 1; // true / false
console.log("====== 分析完成 ======");
console.timeEnd("analyze");
// 更新用户剩余对话次数
let userChatNum = aiChatNum.get(userId);
if(userChatNum!==-1){
userChatNum = Math.max(0, userChatNum - 1); // 防止变成负数
setQuota(userId,userChatNum);
console.log(`用户剩余AI 对话次数: ${userChatNum}`);
}
// // 更新用户剩余对话次数
// let userChatNum = await getQuota(userId);
// if(userChatNum!==-1){
// userChatNum = Math.max(0, userChatNum - 1); // 防止变成负数
// await setQuota(userId,userChatNum);
// console.log(`用户剩余AI 对话次数: ${userChatNum}`);
// }
}
catch (err)
{
console.error("❌ 调用失败:", err.response?.data || err.message);
res.status(500).json({ code: 1, error: err.response?.data || err.message });
}
}
finally {
let userChatNum = await getQuota(userId);
console.log(userChatNum,"userChatNum2");
if (userChatNum !== -1 && userChatNum !== undefined) {
userChatNum = Math.max(0, userChatNum - 1); // 防止变成负数
console.log(userChatNum,"userChatNum最终");
await setQuota(userId, userChatNum);
console.log(`用户剩余AI 对话次数: ${userChatNum}`);
// 更新数据库
await pool.query(
"update sys_user set ai_chat_num = ? where user_id= ?",
[userChatNum, userId]
);
console.log("更新用户对话次数:", userId, userChatNum);
}
}
});
app.post("/stop", express.json(), (req, res) => {