Просмотр исходного кода

fix(provision): 修复试用开通 500(平台不支持 exists + 空 notContainedIn)

- 「按账号只能试用一次」改为查询后在内存判断
- 有效期兼容 Parse Date 对象
- 错误信息输出异常可读字段,便于定位

Co-Authored-By: Claude Code <noreply@anthropic.com>
Huccct 5 часов назад
Родитель
Сommit
574697c7f5
2 измененных файлов с 60 добавлено и 7 удалено
  1. 51 7
      cloud/functions/fmode-provisioning.js
  2. 9 0
      docs/00-tracking/操作追踪.md

+ 51 - 7
cloud/functions/fmode-provisioning.js

@@ -931,17 +931,20 @@ async function _start(user, p) {
    * 不碰 R730、不建 docker 容器 —— 零资源占用。
    */
   if (planCode === 'trial' || planCode === 'starter') {
+    var _step = 'enter';
     var token0 = _sessionToken();
     var ownerMx = '@' + String(user.id).toLowerCase() + ':fmode.cn';
     var oa = null;
 
     try {
+      _step = 'find-record';
       // ① 建/复用 FmodeAgent 记录
       var OAClass = Parse.Object.extend('FmodeAgent');
       var oq = new Parse.Query(OAClass);
       oq.equalTo('user', user);
       oq.equalTo('name', containerName);
       oq.notEqualTo('isDeleted', true);
+      _step = 'q.first';
       oa = await oq.first({ useMasterKey: true });
       /*
        * 只能试用一次(2026-12-03 用户裁决「按账号判」):
@@ -949,12 +952,22 @@ async function _start(user, p) {
        * 否则「删掉再建」就能无限试用(原来换名即可绕过,已实测)。
        */
       if (planCode === 'trial') {
+        /*
+         * 查询方式(2026-12-04 实测修正):
+         * 平台不支持 exists()/notContainedIn(空数组) 这类条件组合,会抛不可读错误。
+         * 改为拉全部 trial 记录后在内存里判断 —— 单账号试用记录极少(通常 0~1 条)。
+         */
         var usedQ = new Parse.Query(OAClass);
         usedQ.equalTo('user', user);
         usedQ.equalTo('planCode', 'trial');
-        usedQ.exists('trialUsedAt');
-        usedQ.notContainedIn('objectId', oa ? [oa.id] : []);
-        var used = await usedQ.first({ useMasterKey: true });
+        usedQ.limit(50);
+        var usedRows = await usedQ.find({ useMasterKey: true });
+        var used = null;
+        for (var ui = 0; ui < usedRows.length; ui++) {
+          var row = usedRows[ui];
+          if (oa && row.id === oa.id) continue;   // 排除当前这条(同名复用不算「用过别的」)
+          if (row.get('trialUsedAt') || row.get('trialEndsAt')) { used = row; break; }
+        }
         if (used) {
           _fail(403, '该账号已使用过试用,请开通入门版或进阶版', { reasonCode: 'TRIAL_USED' });
           return false;
@@ -993,6 +1006,7 @@ async function _start(user, p) {
         oa.set('accessTokenVer', 1);
         oa.set('accessState', 'active');
         oa.set('planBilling', String(params.planBilling || 'monthly'));
+        _step = 'save1';
         await oa.save(null, { useMasterKey: true });
         // agentId 必须 save 之后再写(新建时 agent.id 为 undefined)
         oa.set('agentId', 'agent-node-app-' + String(oa.id).toLowerCase());
@@ -1009,16 +1023,39 @@ async function _start(user, p) {
         await oa.save(null, { useMasterKey: true });
       }
 
+      _step = 'matrix';
       // ② 建 Matrix 身份与房间(幂等,已绑定会直接返回)
-      var prov0 = await _callFn(FN_PROVISION, token0, { agentId: oa.id });
+      var prov0;
+      try {
+        prov0 = await _callFn(FN_PROVISION, token0, { agentId: oa.id });
+      } catch (pe) {
+        throw new Error('Matrix 身份创建异常:' + ((pe && pe.message) || JSON.stringify(pe)));
+      }
       if (!prov0 || !prov0.agentMxId) {
-        throw new Error('Matrix 身份创建失败');
+        throw new Error('Matrix 身份创建失败:' + JSON.stringify(prov0).slice(0, 200));
       }
 
+      _step = 'password';
       // ③ 生成真实提示词
       var derivedPass = await _agentMxPassword(oa.id);
+      /*
+       * 有效期可能来自「本次计算」或「旧记录的 DB 字段」,两者类型不同:
+       * DB 返回的是 Parse Date 对象,直接 toISOString() 会抛错(2026-12-04 试用 500 的根因)。
+       * 统一转成 Date 再格式化。
+       */
+      var expiresAt = accessExpiresAt instanceof Date ? accessExpiresAt : new Date(oa.get('accessExpiresAt') || accessExpiresAt);
+      var expiresText = isFinite(expiresAt.getTime())
+        ? expiresAt.toISOString().slice(0, 16).replace('T', ' ') + '(UTC)'
+        : '请以 App 容器设置中的到期时间为准';
+      /* 诊断(2026-12-04):逐个参数检查,把缺失项直接说清楚,避免再出现 [object Object] */
+      var at = oa.get('accessToken');
+      if (!at) throw new Error('accessToken 为空');
+      if (!containerName) throw new Error('containerName 为空');
+      if (!prov0 || !prov0.agentMxId || !prov0.roomId) throw new Error('matrixInfo 不完整: ' + JSON.stringify(prov0).slice(0, 160));
+      if (!derivedPass) throw new Error('Matrix 密码派生失败');
+      if (!expiresText) throw new Error('expiresText 为空');
       var instruction = _buildSelfHostedInstruction(oa.id, containerName, prov0, derivedPass,
-        oa.get('accessToken'), accessExpiresAt.toISOString().slice(0, 16).replace('T', ' ') + '(UTC)', ownerMx, CONTAINER_ONBOARDING_BUNDLE);
+        at, expiresText, ownerMx, CONTAINER_ONBOARDING_BUNDLE);
 
       return _ok({
         mode: 'onboarding',
@@ -1034,7 +1071,14 @@ async function _start(user, p) {
         },
       });
     } catch (e) {
-      return _fail(500, '接入提示词生成失败:' + _str(e.message, 200), {
+      
+      var _em;
+      try {
+        if (e && e.message) _em = e.message;
+        else if (typeof e === 'string') _em = e;
+        else { _em = (e && (e.error || e.reason || e.msg)) || ''; if (!_em) { try { _em = JSON.stringify(e); } catch (q) { _em = ''; } } if (!_em) _em = Object.prototype.toString.call(e) + ' / keys=' + Object.keys(e || {}).join(','); }
+      } catch (x) { _em = String(e); }
+      return _fail(500, '接入提示词生成失败[' + String(_step) + ']:' + _str(_em, 300), {
         reasonCode: 'ONBOARDING_FAILED',
         retryable: true,
       });

+ 9 - 0
docs/00-tracking/操作追踪.md

@@ -10655,3 +10655,12 @@ Call log:
     - 去掉「**登录遇到问题?**」(两端)
     - 协议区由「勾选框 + 已阅读并同意」改为「**登录即代表同意 用户协议 和 隐私政策**」,`agreed` 默认 true
   - 说明:测试用例尚未同步(用户明确「不要测试」),下次集中清理。
+
+- 2026-12-04 02:40:00+08:00:**修复试用 500(用户新账号点试用报错)**
+  - 现象:新注册账号点「开始两天试用」→ 「暂时无法确认开通结果」,云函数返回 500「接入提示词生成失败:[object Object]」。
+  - 排查过程:错误对象在平台上不可读(`[object Object]`),逐层加步骤标记定位到 `_step = find-record → usedQ.first`。
+  - **真根因**:`usedQ.exists('trialUsedAt')` + `notContainedIn('objectId', [])`(空数组)——平台对这两种查询组合直接抛错,且错误对象不可读。这是我在实现「按账号只能试用一次」时引入的。
+  - 修复:改为 `equalTo('user')+equalTo('planCode','trial')+limit(50)` 拉取后在内存里判断是否用过(单账号试用记录极少,无性能问题)。
+  - 附带修复:有效期可能是 DB 的 Parse Date 而非 Date 实例,`toISOString()` 会抛错 —— 统一转 Date 再格式化;错误信息改为输出异常的所有可读字段。
+  - 验证:试用返回 200 + 10018 字符提示词;同账号换名再试返回 403 `TRIAL_USED`;测试记录已清理。
+  - 说明:控制台里的 `mailto:contact@fmode.cn` 是**企业版「联系客服」被自动触发**(浏览器/无头环境会预先触发 mailto),与该报错无关;建议后续改为按钮点击后再跳转。