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

View File

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

View File

@@ -896,7 +896,6 @@ async function setQuota(userId,num) {
async function hasQuota(userId) { async function hasQuota(userId) {
const m = getMutex(userId); const m = getMutex(userId);
return await m.runExclusive(async () => { return await m.runExclusive(async () => {
console.log("更新用户对话次数:", userId, num);
return aiChatNum.has(userId); return aiChatNum.has(userId);
}); });
} }
@@ -904,7 +903,8 @@ async function hasQuota(userId) {
async function getQuota(userId) { async function getQuota(userId) {
const m = getMutex(userId); const m = getMutex(userId);
return await m.runExclusive(async () => { return await m.runExclusive(async () => {
console.log("更新用户对话次数:", userId, num); console.log("获取用户对话次数1:", userId, aiChatNum);
console.log("获取用户对话次数:", userId, aiChatNum.get(userId));
return aiChatNum.get(userId); return aiChatNum.get(userId);
}); });
} }
@@ -918,44 +918,55 @@ async function removeQuota(userId) {
} }
// ====================== API ====================== // ====================== API ======================
app.post("/updateAiChatNum", async (req, res) => { app.post("/refreshAiChatNum", async (req, res) => {
const { userId } = req.body; const { userId } = req.body;
console.log(userId,98888888888); console.log(userId,"刷新对话次数");
if(!hasQuota(userId)){ try {
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]
);
res.json({ code: 0, message: "更新成功" });
}
})
app.post("/analyze", upload.single("file"), async (req, res) => {
try
{
const { userId } = req.body;
if(!hasQuota(userId)){
const [userRemainChatNum] = await pool.query( 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] [userId]
); );
if (userRemainChatNum.length>0) { if (userRemainChatNum.length > 0) {
setQuota(userId,userRemainChatNum[0].ai_chat_num); const quota = userRemainChatNum[0].ai_chat_num;
console.log(userId,"刷新对话次数",quota);
await setQuota(userId,quota);
} }
}else{ } catch (error) {
if(getQuota(userId)<=0 && getQuota(userId)!==-1){ console.error("更新失败:", error);
}
})
app.post("/analyze", upload.single("file"), async (req, res) => {
const { userId } = req.body;
try
{
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= ?",
[userId]
);
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 {
const quota = await getQuota(userId);
if (quota <= 0 && quota !== -1) {
return res.status(400).json({ error: "对话次数已用完,请完成账号注册" }); return res.status(400).json({ error: "对话次数已用完,请完成账号注册" });
} }
} }
const { requestId } = req.body; const { requestId } = req.body;
res.setHeader("Content-Type", "text/plain; charset=utf-8"); res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.setHeader("Transfer-Encoding", "chunked"); res.setHeader("Transfer-Encoding", "chunked");
res.setHeader("Cache-Control", "no-cache"); res.setHeader("Cache-Control", "no-cache");
@@ -994,9 +1005,8 @@ app.post("/analyze", upload.single("file"), async (req, res) => {
) AS hasTitle ) AS hasTitle
`, `,
[sessionId, userId] [sessionId, userId]
); );
const existingTitle = rows[0].hasTitle === 1; // true / false
const existingTitle = rows[0].hasTitle === 1; // true / false
console.log(existingTitle, rows?.[0], 9999, rows) console.log(existingTitle, rows?.[0], 9999, rows)
// 如果前端没有传 sessionId,生成一个 // 如果前端没有传 sessionId,生成一个
@@ -1246,20 +1256,36 @@ const existingTitle = rows[0].hasTitle === 1; // true / false
console.log("====== 分析完成 ======"); console.log("====== 分析完成 ======");
console.timeEnd("analyze"); console.timeEnd("analyze");
// 更新用户剩余对话次数 // // 更新用户剩余对话次数
let userChatNum = aiChatNum.get(userId); // let userChatNum = await getQuota(userId);
// if(userChatNum!==-1){
if(userChatNum!==-1){ // userChatNum = Math.max(0, userChatNum - 1); // 防止变成负数
userChatNum = Math.max(0, userChatNum - 1); // 防止变成负数 // await setQuota(userId,userChatNum);
setQuota(userId,userChatNum); // console.log(`用户剩余AI 对话次数: ${userChatNum}`);
console.log(`用户剩余AI 对话次数: ${userChatNum}`); // }
}
} }
catch (err) catch (err)
{ {
console.error("❌ 调用失败:", err.response?.data || err.message); console.error("❌ 调用失败:", err.response?.data || err.message);
res.status(500).json({ code: 1, 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) => { app.post("/stop", express.json(), (req, res) => {