Bladeren bron

fix: restore app and unit node contracts

彭峰 2 maanden geleden
bovenliggende
commit
4ba99d5874

+ 2 - 0
docs/migration/wxapp-cloud-action-matrix.md

@@ -56,6 +56,8 @@
 - `e_user_list`:按旧源码的 Model 54、`status=99`、`CourseAppointment.pl` 分组预约学员,不再依赖目标库中仅有 2 条的通用 `agent` 指针。
 - `user_point_list`:按旧接口 `stype=1..6` 分别查询 `UserExpDomP/UserSIcon/UserExpHis/UserUserPoint/UserDummyPoint/UserCredit`,恢复 `ExpHisID/HisTime/Detail` 别名;迁移资料没有提现费率,余额日志的 `purse_fee` 明确返回 `null` 并标记规则不可用。
 - `guestbook_add`:兼容旧页的 `model` JSON(`UserID/Title/TContent/Cateid`)和 Angular 表单的扁平字段,限制 800 字并阻止普通用户冒用他人 `UserID`。
+- `node_list`:普通栏目按旧 `OrderID/NodeID` 升序;`ifunit=1` 分支使用真实 Parse 会话,按 Model 52 词库和 `PracticeRecord.xxcs` 返回每单元 `total/yx_word/process`。
+- `app_update`:从目标 `App.index/version/changelog/downUrl` 恢复 `ver/nver/intro/path`;迁移资料没有 APK 字节大小,因此 `size=null` 并显式标记 `sizeUnavailable=true`。目标记录中的安装包地址已保留,但其文件域名在 2026-08-18 检查时 TLS 证书已过期,实际下载仍属于外部环境阻塞。
 
 迁移数据没有保存复习收入金额,也没有提供可验证的计价公式,因此 `e_get_21list_tj` 改为显式 501;收入列表仍返回复习事实,但用 `incomeRuleUnavailable=true` 标记金额不可恢复,不伪造收入。
 

+ 10 - 3
scripts/deploy-admin-functions.mjs

@@ -360,6 +360,13 @@ async function sqlPage(className, input, filters = []) {
   const rows = await Psql.query('SELECT * FROM "' + className + '" WHERE ' + where + ' ORDER BY "updatedAt" DESC LIMIT $' + (values.length + 1) + ' OFFSET $' + (values.length + 2), rowValues); const total = number(countRow.total);
   return { rows: rows.filter(isVisible).map((row) => legacyAliases(row, className)), page: { itemCount: total, pageCount: Math.ceil(total / paging.size), pageIndex: paging.index, pageSize: paging.size } };
 }
+async function nodePage(input) {
+  const paging = pageInput(input); const values = [DEFAULT_COMPANY_ID]; const clauses = ['"company"=$1']; if (input.pid !== undefined && input.pid !== '') { values.push(String(number(input.pid))); clauses.push('CAST("parentId" AS text)=$' + values.length); } const where = clauses.join(' AND '); const countRow = await Psql.one('SELECT COUNT(*)::int AS total FROM "Node" WHERE ' + where,values); const rows = await Psql.query('SELECT * FROM "Node" WHERE ' + where + ' ORDER BY CASE WHEN CAST("orderId" AS text) ~ \'^-?[0-9]+$\' THEN CAST("orderId" AS numeric) ELSE 0 END ASC, CASE WHEN CAST("nodeId" AS text) ~ \'^-?[0-9]+$\' THEN CAST("nodeId" AS numeric) ELSE 0 END ASC LIMIT $' + (values.length + 1) + ' OFFSET $' + (values.length + 2),values.concat([paging.size,(paging.index - 1) * paging.size])); const total = number(countRow.total); return { rows:rows.filter(isVisible).map((row) => legacyAliases(row,'Node')),page:{itemCount:total,pageCount:Math.ceil(total / paging.size),pageIndex:paging.index,pageSize:paging.size} };
+}
+async function nodeUnitPage(input,current) {
+  const uid = await authorizeRequestedUser(current,input.userId || input.uid); const paging = pageInput(input); const parentId = number(input.pid); if (!parentId) fail(400,'缺少课程栏目 ID'); const countRow = await Psql.one('SELECT COUNT(*)::int AS total FROM "Node" WHERE "company"=$1 AND CAST("parentId" AS text)=$2',[DEFAULT_COMPANY_ID,String(parentId)]); const rows = await Psql.query('SELECT n.*,COALESCE(w.total,0)::int AS "total",COALESCE(l.learned,0)::int AS "yx_word" FROM "Node" n LEFT JOIN LATERAL (SELECT COUNT(*)::int AS total FROM "CommonModel" c WHERE c."company"=$1 AND CAST(c."modelId" AS text)=\'52\' AND CAST(c."nodeId" AS text)=CAST(n."nodeId" AS text)) w ON TRUE LEFT JOIN LATERAL (SELECT COUNT(DISTINCT CAST(p."scid" AS text))::int AS learned FROM "PracticeRecord" p JOIN "CommonModel" c ON c."company"=$1 AND CAST(c."modelId" AS text)=\'52\' AND CAST(c."generalId" AS text)=CAST(p."scid" AS text) AND CAST(c."nodeId" AS text)=CAST(n."nodeId" AS text) WHERE p."company"=$1 AND CAST(p."yhid" AS text)=$3 AND COALESCE(CAST(p."xxcs" AS numeric),0)>0) l ON TRUE WHERE n."company"=$1 AND CAST(n."parentId" AS text)=$2 ORDER BY CASE WHEN CAST(n."orderId" AS text) ~ \'^-?[0-9]+$\' THEN CAST(n."orderId" AS numeric) ELSE 0 END ASC,CASE WHEN CAST(n."nodeId" AS text) ~ \'^-?[0-9]+$\' THEN CAST(n."nodeId" AS numeric) ELSE 0 END ASC LIMIT $4 OFFSET $5',[DEFAULT_COMPANY_ID,String(parentId),String(uid),paging.size,(paging.index - 1) * paging.size]); const total = number(countRow.total); return { rows:rows.map((source) => { const row = legacyAliases(source,'Node'); row.total = number(source.total); row.yx_word = number(source.yx_word); row.process = row.total ? Math.round(row.yx_word / row.total * 100) : 0; return row; }),page:{itemCount:total,pageCount:Math.ceil(total / paging.size),pageIndex:paging.index,pageSize:paging.size} };
+}
+function legacyAppRow(source) { if (!source) return null; const row = legacyAliases(source,'App'); row.ver = number(firstValue(row.index,String(row.version || '').replace(/\D/g,''))); row.nver = String(row.version || ''); row.intro = String(firstValue(row.changelog,row.desc,'') || ''); row.path = String(firstValue(row.downUrl,row.apkUrl,'') || ''); row.size = null; row.sizeUnavailable = true; return row; }
 function parseArray(value) { if (Array.isArray(value)) return value; if (typeof value !== 'string' || !value.trim()) return []; try { const parsed = JSON.parse(value); return Array.isArray(parsed) ? parsed : []; } catch (_) { return []; } }
 function largePageInput(input) { return { index: Math.max(1, number(input.cpage || input.page, 1)), size: Math.min(500, Math.max(1, number(input.psize || input.pageSize, 20))) }; }
 function ownLegacyId(current) { return number(current && (current.get('legacyUserId') || current.get('userid') || current.get('num'))); }
@@ -520,19 +527,19 @@ async function handler(request, response) {
     }
     if (action === 'user_register') { const registered = await registerUser(input); return response.json(envelope(registered.result,registered.addon)); }
     if (action === 'user_info_name') { const username = String(input.uname || input.name || '').trim(); if (!username) return response.status(400).json(reject('缺少用户名')); const rows = await Psql.query('SELECT "objectId" FROM "_User" WHERE "company" = $1 AND "username" = $2 LIMIT 1', [DEFAULT_COMPANY_ID, username]); const found = rows[0]; return found ? response.json(envelope({ objectId: found.objectId })) : response.status(404).json(reject('用户不存在')); }
-    const publicRead = PUBLIC_READ.has(action) && !contentQueryRequiresAuth(action, input); const current = await currentUser(request, !publicRead); if (contentQueryRequiresAuth(action, input) && current) await authorizeContentAccess(current, input);
+    const privateNodeProgress = action === 'node_list' && number(input.ifunit) === 1; const publicRead = PUBLIC_READ.has(action) && !contentQueryRequiresAuth(action, input) && !privateNodeProgress; const current = await currentUser(request, !publicRead); if (contentQueryRequiresAuth(action, input) && current) await authorizeContentAccess(current, input);
     if (action === 'user_get') { const requestedId = number(input.uid || ownLegacyId(current)); let target = current; if (requestedId && requestedId !== ownLegacyId(current)) { await authorizeTeamUser(current,requestedId); target = await legacyUserObject(requestedId); if (!target) return response.status(404).json(reject('用户不存在')); } return response.json(envelope(legacyUser(target),legacyUserAddon(target))); }
     if (action === 'user_list') { const result = await teamUserPage(input,current); return response.json(envelope(result.rows,undefined,result.page)); }
     if (action === 'user_dept') return response.json(envelope(await teamStats(input,current)));
     if (action === 'e_user_list') { const result = await coachStudentPage(input,current); return response.json(envelope(result.rows,undefined,result.page)); }
     if (action === 'user_update') { const updated = await updateUserProfile(input,current); return response.json(envelope(updated.result,updated.addon)); }
-    if (action === 'app_update') { const filters = input.platform ? [{ field: 'platform', value: input.platform }] : []; const result = await sqlPage('App', { page: 1, pageSize: 1 }, filters); return response.json(envelope(result.rows[0] || null)); }
+    if (action === 'app_update') { const result = await sqlPage('App', { page: 1, pageSize: 1 }); return response.json(envelope(legacyAppRow(result.rows[0]))); }
     if (action === 'content_list' || action === 'content_list_llk') { const result = await contentPage(input, !current); return response.json(envelope(result.rows, undefined, result.page)); }
     if (action === 'content_get') { const id = String(input.id || input.gid || input.generalId || ''); if (!id) return response.status(400).json(reject('缺少内容 ID')); const identity = /^\d+$/.test(id) ? { generalId: id } : { objectId: id }; const base = await contentPage({ page: 1, pageSize: 1, ...identity }); let detail = base.rows[0]; if (!detail) return response.status(404).json(reject('内容不存在')); const detailModel = number(detail.modelId || detail.ModelID); if (CONTENT_ADDONS[detailModel]) detail = (await contentPage({ page: 1, pageSize: 1, modelId: detailModel, ...identity })).rows[0] || detail; if (PRIVATE_CONTENT_MODELS.has(detailModel)) { if (!current) return response.status(401).json(reject('该内容详情需要登录')); await authorizeContentDetail(current, detail); } return response.json(envelope(detail)); }
     if (action === 'content_uphis') { const resolved = await resolveContent(input, true); if (!resolved.object) return response.status(404).json(reject('内容不存在')); resolved.object.increment('hits', Math.max(1, number(input.num, 1))); await resolved.object.save(null, { useMasterKey: true }); return response.json(envelope({ hits: resolved.object.get('hits') })); }
     if (action === 'content_add') return response.json(envelope(await createContentPair(input, current)));
     if (action === 'content_update') return response.json(envelope(await updateContentPair(input, current)));
-    if (action === 'node_list') { const filters = input.pid !== undefined ? [{ field: 'parentId', value: number(input.pid) }] : []; const result = await sqlPage('Node', input, filters); return response.json(envelope(result.rows, undefined, result.page)); }
+    if (action === 'node_list') { const result = privateNodeProgress ? await nodeUnitPage(input,current) : await nodePage(input); return response.json(envelope(result.rows, undefined, result.page)); }
     if (action === 'node_get') { const result = await sqlPage('Node', { page: 1, pageSize: 1 }, [{ field: 'nodeId', value: number(input.id || input.nid) }]); return result.rows[0] ? response.json(envelope(result.rows[0])) : response.status(404).json(reject('栏目不存在')); }
     const legacyId = ownLegacyId(current);
     if (action === 'content_add_zt') return response.json(envelope(await createStudyContent(input, current)));

+ 6 - 0
scripts/smoke-admin-functions.mjs

@@ -196,6 +196,8 @@ try {
   if (contentExact.result?.[0]?.objectId !== content.result[0].objectId || contentExact.page?.itemCount !== 1) throw new Error('内容 objectId 精确查询校验失败');
   const contentDetail = await callLegacyFunction('', { action: 'content_get', id: content.result[0].objectId });
   if (contentDetail.result?.objectId !== content.result[0].objectId) throw new Error('内容详情 ID 校验失败');
+  const appUpdate = await callLegacyFunction('', { action: 'app_update' });
+  if (Number(appUpdate.result?.ver) !== 113 || appUpdate.result?.nver !== '1.1.8' || !String(appUpdate.result?.path).startsWith('https://') || appUpdate.result?.size !== null || appUpdate.result?.sizeUnavailable !== true) throw new Error(`应用版本旧契约别名异常:${JSON.stringify(appUpdate)}`);
 
   const words = await callLegacyFunction('', { action: 'content_list', modelId: 52, page: 1, pageSize: 1 });
   if (Number(words.page?.itemCount) < 89000 || !words.result?.[0]?.GeneralID || words.result?.[0]?.sy === undefined) throw new Error('词库 addon 联表校验失败');
@@ -243,6 +245,10 @@ try {
   if (!Array.isArray(ownCourseWords.result) || ownCourseWords.result[0]?.w_learned !== 0) throw new Error('普通用户本人课程词库权限校验失败');
   const learnedWrite = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_add_words', uid: memberLegacyId, wordsId: '2505', kcid: 16, save: 1 });
   if (learnedWrite.result?.created !== 1 || learnedWrite.result?.learnedIncremented !== 1) throw new Error('首次学习词进度写入校验失败');
+  await callLegacyFunction('', { action: 'node_list', pid: 16, ifunit: 1, userId: memberLegacyId }, 401);
+  const unitNodes = await callLegacyFunction(memberLogin.sessionToken, { action: 'node_list', pid: 16, ifunit: 1, userId: memberLegacyId, pageSize: 100 });
+  const learnedUnit = unitNodes.result?.find((node) => Number(node.NodeID) === 40);
+  if (!learnedUnit || Number(learnedUnit.total) < 1 || Number(learnedUnit.yx_word) !== 1 || Number(learnedUnit.process) !== Math.round(100 / Number(learnedUnit.total))) throw new Error(`单元已学进度异常:${JSON.stringify(learnedUnit)}`);
   const learnedRead = await callLegacyFunction(memberLogin.sessionToken, { action: 'e_ck_list', uid: memberLegacyId, nids: 40, page: 1, pageSize: 1000 });
   if (Number(learnedRead.result?.find((word) => Number(word.GeneralID) === 2505)?.w_learned) !== 1) throw new Error('学习次数写后读校验失败');
   await callLegacyFunction(memberLogin.sessionToken, { action: 'e_add_words', uid: memberLegacyId, wordsId: '2505', kcid: 16, ifnew: 1 });

+ 8 - 0
src/app/core/api.service.spec.ts

@@ -191,6 +191,14 @@ describe('ApiService', () => {
     request.flush({ retcode: 0, result: [] });
   });
 
+  it('requires a Parse session for user-specific unit progress', () => {
+    sessionToken = 'r:session-token';
+    api.get('node_list', { pid: 16, ifunit: 1, userId: 58 }).subscribe();
+    const request = http.expectOne(API_CONFIG.cloudFunctionUrl);
+    expect(request.request.body).toEqual({ token: 'r:session-token', params: { action: 'node_list', pid: 16, ifunit: 1, userId: 58 } });
+    request.flush({ retcode: 0, result: [{ NodeID: 40, total: 20, yx_word: 5, process: 25 }] });
+  });
+
   it('turns retcode -1 responses into ApiError', () => {
     let actual: unknown;
     api.post('user_login_passwd', {}).subscribe({ error: (error) => actual = error });

+ 2 - 0
src/app/core/cloud-action-migration.ts

@@ -47,6 +47,7 @@ const CONTENT_MODEL_FIELDS: Record<number, Set<string>> = {
 const NODE_MODELS: Record<number, number> = { 28: 58, 29: 54, 32: 53, 291: 56, 296: 59, 327: 52, 388: 60, 389: 61 };
 
 export function usesCloudGateway(action: string, params: Record<string, unknown> = {}, hasParseSession = false): boolean {
+  if (action === 'node_list' && Number(params['ifunit']) === 1) return hasParseSession;
   if (H5_CLOUD_ROUTED_ACTIONS.has(action)) return true;
   if (SESSION_CLOUD_ROUTED_ACTIONS.has(action)) return hasParseSession;
   if (action !== 'content_list') return false;
@@ -59,6 +60,7 @@ export function usesCloudGateway(action: string, params: Record<string, unknown>
 
 export function requiresCloudSession(action: string, params: Record<string, unknown> = {}): boolean {
   return SESSION_CLOUD_ROUTED_ACTIONS.has(action)
+    || (action === 'node_list' && Number(params['ifunit']) === 1)
     || (action === 'content_list' && contentModel(params) !== 52 && Boolean(contentModel(params)));
 }