|
|
@@ -244,11 +244,11 @@ const BLOCKED = {
|
|
|
product_del: '尚未建立门店管理员授权关系', product_stock_change: '尚未建立门店管理员授权关系', product_sale_change: '尚未建立门店管理员授权关系',
|
|
|
unit_record_update: '旧源码在调用前无条件 return;目标库也未迁移 Model 57 单元聚合副表',
|
|
|
e_get_21list_tj: '迁移数据未包含复习收入金额字段或可验证的计价规则',
|
|
|
- pub_add: '需确认 Pub 业务类型与审核规则', pub_list: '需确认 Pub 业务类型与可见范围', user_dept: '目标 Schema 无可证明的用户部门关系',
|
|
|
+ pub_add: '旧前端依赖 Pub 7-13,但目标库只迁入 Pub 2-6,且缺少注销、供应商、商户邀请、退换货与结算副表', pub_list: '旧前端依赖 Pub 7-13,但目标库只迁入 Pub 2-6,无法恢复对应历史记录与审核范围',
|
|
|
user_rnauth_add: '实名认证需新的合规审核与敏感数据存储', user_rnauth_get: '实名认证需新的合规审核与敏感数据存储', user_rnauth_upd: '实名认证需新的合规审核与敏感数据存储',
|
|
|
product_add: '需建立门店管理员授权与商品附加表事务', product_upd: '需建立门店管理员授权与商品附加表事务'
|
|
|
};
|
|
|
-const SENSITIVE = /(?:password|secret|sessiontoken|masterkey|privatekey|legacyPasswordHash|adminPassword|payPassword)/i;
|
|
|
+const SENSITIVE = /(?:password|pwd|secret|sessiontoken|masterkey|privatekey|legacyPasswordHash|adminPassword|payPassword)/i;
|
|
|
function inputOf(request) { const body = request.body || {}; return body.params && typeof body.params === 'object' ? body.params : body; }
|
|
|
function envelope(result, addon, page) { const value = { retcode: 0, retmsg: '', result }; if (addon !== undefined) value.addon = addon; if (page) value.page = page; return value; }
|
|
|
function reject(message) { return { retcode: -1, retmsg: message, result: null }; }
|
|
|
@@ -268,7 +268,21 @@ function legacyAliases(value, className) {
|
|
|
}; const map = maps[className] || {}; for (const [legacy,source] of Object.entries(map)) if (row[legacy] === undefined && row[source] !== undefined) row[legacy] = row[source]; return row;
|
|
|
}
|
|
|
async function currentUser(request, required = true) { const current = request.user || (typeof user !== 'undefined' ? user : null); if (!current) { if (required) fail(401, '登录状态已失效'); return null; } await current.fetch({ useMasterKey: true }); const company = current.get('company'); if (company && company.id !== DEFAULT_COMPANY_ID) fail(403, '用户不属于小树英语帐套'); return current; }
|
|
|
-function legacyUser(current, withToken = false) { const json = safe(current); const value = { ...json, userId: number(current.get('legacyUserId') || current.get('userid') || current.get('num')), userName: String(current.get('username') || ''), honeyName: String(current.get('nickname') || current.get('nickName') || current.get('realName') || current.get('username') || ''), userFace: String(current.get('avatar') || ''), mobile: String(current.get('mobile') || current.get('phone') || ''), groupId: number(current.get('legacyGroupId')), groupName: String(current.get('roleName') || '') }; if (withToken) value.sessionToken = current.getSessionToken(); return value; }
|
|
|
+function objectValue(source, key) { return source && typeof source.get === 'function' ? source.get(key) : source && source[key]; }
|
|
|
+function legacyData(source) { const value = objectValue(source, 'legacyUserData'); return value && typeof value === 'object' && !Array.isArray(value) ? value : {}; }
|
|
|
+function firstValue(...values) { return values.find((value) => value !== undefined && value !== null && value !== ''); }
|
|
|
+function legacyUser(current, withToken = false) {
|
|
|
+ const data = legacyData(current); const username = String(firstValue(objectValue(current,'username'),data.UserName,'') || ''); const userId = number(firstValue(objectValue(current,'legacyUserId'),objectValue(current,'userid'),objectValue(current,'num'),data.UserID)); const groupId = number(firstValue(objectValue(current,'legacyGroupId'),data.GroupID)); const honeyName = String(firstValue(objectValue(current,'nickname'),objectValue(current,'nickName'),objectValue(current,'realName'),data.HoneyName,username) || ''); const avatar = String(firstValue(objectValue(current,'avatar'),data.salt,'') || ''); const mobile = String(firstValue(objectValue(current,'mobile'),objectValue(current,'phone'),'') || ''); const parentId = number(firstValue(data.ParentUserID,objectValue(current,'puid'))); const vip = number(firstValue(data.VIP,objectValue(current,'vip')));
|
|
|
+ const value = { objectId:String(objectValue(current,'objectId') || current.id || ''), userId, userName:username, honeyName, userFace:avatar, mobile, groupId, groupName:String(objectValue(current,'roleName') || ''), email:String(firstValue(objectValue(current,'email'),data.Email,'') || ''), puid:parentId, vip, regTime:firstValue(data.RegTime,objectValue(current,'createdAt')), birthday:firstValue(objectValue(current,'birthday'),data.birthday,''), wechat:firstValue(objectValue(current,'wechat'),data.wechat,''), seturl:String(firstValue(data.seturl,objectValue(current,'seturl'),'') || '') };
|
|
|
+ if (withToken) value.sessionToken = current.getSessionToken(); return value;
|
|
|
+}
|
|
|
+function legacyUserAddon(current) {
|
|
|
+ const data = legacyData(current); const state = objectValue(current,'isDisabled') === true ? 0 : number(firstValue(data.State,1),1); const result = { vip:number(data.VIP), state, State:state, regTime:firstValue(data.RegTime,objectValue(current,'createdAt')), purse:number(data.Purse), silverCoin:number(data.SilverCoin), userExp:number(data.UserExp), userPoint:number(data.UserPoint), boffExp:number(data.boffExp) }; result.VIP = result.vip; result.Purse = result.purse; result.SilverCoin = result.silverCoin; result.UserExp = result.userExp; result.UserPoint = result.userPoint; return result;
|
|
|
+}
|
|
|
+function legacyUserRow(source) {
|
|
|
+ const data = legacyData(source); const userId = number(firstValue(source.legacyUserId,source.userid,source.num,data.UserID)); const username = String(firstValue(source.username,data.UserName,'') || ''); const honeyName = String(firstValue(source.nickname,source.nickName,source.realName,data.HoneyName,username) || ''); const groupId = number(firstValue(source.legacyGroupId,data.GroupID)); const parentId = number(firstValue(data.ParentUserID,source.puid)); const avatar = String(firstValue(source.avatar,data.salt,'') || ''); const teamSize = number(firstValue(source.__teamSize,source.TeamSize)); const vip = number(firstValue(data.VIP,source.vip)); const regTime = firstValue(data.RegTime,source.createdAt); const row = { objectId:String(source.objectId || ''), userId, userName:username, honeyName, userFace:avatar, mobile:String(firstValue(source.mobile,source.phone,'') || ''), groupId, puid:parentId, vip, regTime, teamSize, email:String(firstValue(source.email,data.Email,'') || ''), realName:String(firstValue(source.realName,data.TrueName,'') || '') };
|
|
|
+ return { ...row, UserID:userId, UserName:username, HoneyName:honeyName, UserFace:avatar, GroupID:groupId, ParentUserID:parentId, VIP:vip, RegTime:regTime, TeamSize:teamSize, Email:row.email, TrueName:row.realName, UserExp:number(data.UserExp), boffExp:number(data.boffExp), salt:avatar };
|
|
|
+}
|
|
|
async function findByLegacyId(className, fields, legacyId, aliases) { const field = aliases.find((name) => fields[name]); if (!field) return null; const companyClause = fields.company ? ' AND "company" = $2' : ''; const values = fields.company ? [String(legacyId),DEFAULT_COMPANY_ID] : [String(legacyId)]; const rows = await Psql.query('SELECT "objectId" FROM "' + className + '" WHERE CAST("' + field + '" AS text) = $1' + companyClause + ' LIMIT 1', values); return rows[0] ? new Parse.Query(className).get(rows[0].objectId,{useMasterKey:true}) : null; }
|
|
|
async function paged(className, input, configure) { const fields = await fieldsOf(className); const paging = pageInput(input); const query = new Parse.Query(className); tenant(query, fields); if (configure) configure(query, fields); const total = await query.count({ useMasterKey: true }); query.skip((paging.index - 1) * paging.size); query.limit(paging.size); query.descending(fields.updatedAt ? 'updatedAt' : 'createdAt'); const rows = (await query.find({ useMasterKey: true })).filter(isVisible); return { rows: rows.map(safe), page: { itemCount: total, pageCount: Math.ceil(total / paging.size), pageIndex: paging.index, pageSize: paging.size } }; }
|
|
|
const CONTENT_ADDONS = {
|
|
|
@@ -337,6 +351,31 @@ async function sqlPage(className, input, filters = []) {
|
|
|
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'))); }
|
|
|
+async function legacyUserObject(legacyId) { const fields = await fieldsOf('_User'); return findByLegacyId('_User', fields, legacyId, ['legacyUserId','userid','num']); }
|
|
|
+async function chainContains(startId, expectedAncestorId) {
|
|
|
+ let cursor = number(startId); const expected = number(expectedAncestorId); const visited = new Set();
|
|
|
+ for (let depth = 0; cursor && depth < 64 && !visited.has(cursor); depth += 1) { if (cursor === expected) return true; visited.add(cursor); const item = await legacyUserObject(cursor); if (!item) return false; cursor = number(legacyData(item).ParentUserID); }
|
|
|
+ return false;
|
|
|
+}
|
|
|
+async function authorizeTeamUser(current, requestedId) {
|
|
|
+ const ownId = ownLegacyId(current); const targetId = number(requestedId || ownId); if (!targetId) fail(400, '缺少用户 ID'); if (isAdminUser(current) || targetId === ownId) return targetId;
|
|
|
+ if (await chainContains(targetId, ownId)) return targetId; if (await chainContains(ownId, targetId)) return targetId; fail(403, '无权查看该团队成员');
|
|
|
+}
|
|
|
+function userSelect(alias = 'u') { return alias + '."objectId",' + alias + '."username",' + alias + '."email",' + alias + '."mobile",' + alias + '."phone",' + alias + '."avatar",' + alias + '."nickname",' + alias + '."nickName",' + alias + '."realName",' + alias + '."legacyUserId",' + alias + '."legacyGroupId",' + alias + '."legacyUserData",' + alias + '."createdAt"'; }
|
|
|
+async function teamUserPage(input, current) {
|
|
|
+ const paging = pageInput(input); const parentId = number(input.puid || ownLegacyId(current)); if (!parentId && !isAdminUser(current)) fail(400, '团队列表必须指定上级用户'); if (parentId) await authorizeTeamUser(current,parentId);
|
|
|
+ const values = [DEFAULT_COMPANY_ID]; const clauses = ['u."company" = $1','(u."isDeleted" IS NULL OR u."isDeleted" = FALSE)']; if (parentId) { values.push(String(parentId)); clauses.push('COALESCE(u."legacyUserData"->>\'ParentUserID\',\'0\') = $' + values.length); }
|
|
|
+ const groups = String(input.gids || '').split(',').map(number).filter((value) => value > 0); if (groups.length) { values.push(groups.map(String)); clauses.push('COALESCE(CAST(u."legacyGroupId" AS text),u."legacyUserData"->>\'GroupID\',\'0\') = ANY($' + values.length + '::text[])'); }
|
|
|
+ const where = clauses.join(' AND '); const countRow = await Psql.one('SELECT COUNT(*)::int AS total FROM "_User" u WHERE ' + where, values); const rowValues = values.concat([paging.size,(paging.index - 1) * paging.size]); const order = groups.length ? 'CASE WHEN COALESCE(u."legacyUserData"->>\'UserExp\',\'0\') ~ \'^-?[0-9]+(?:\\.[0-9]+)?$\' THEN (u."legacyUserData"->>\'UserExp\')::numeric ELSE 0 END DESC,' : '';
|
|
|
+ const rows = await Psql.query('SELECT ' + userSelect('u') + ',(SELECT COUNT(*)::int FROM "_User" child WHERE child."company" = $1 AND COALESCE(child."legacyUserData"->>\'ParentUserID\',\'0\') = COALESCE(CAST(u."legacyUserId" AS text),u."legacyUserData"->>\'UserID\',\'0\')) AS "__teamSize" FROM "_User" u WHERE ' + where + ' ORDER BY ' + order + ' CASE WHEN COALESCE(CAST(u."legacyUserId" AS text),u."legacyUserData"->>\'UserID\',\'0\') ~ \'^[0-9]+$\' THEN COALESCE(CAST(u."legacyUserId" AS text),u."legacyUserData"->>\'UserID\',\'0\')::numeric ELSE 0 END DESC LIMIT $' + (values.length + 1) + ' OFFSET $' + (values.length + 2), rowValues); const total = number(countRow.total);
|
|
|
+ return { rows:rows.map(legacyUserRow), page:{ itemCount:total, pageCount:Math.ceil(total / paging.size), pageIndex:paging.index, pageSize:paging.size } };
|
|
|
+}
|
|
|
+async function teamStats(input,current) {
|
|
|
+ const parentId = await authorizeTeamUser(current,input.uid); const rows = await Psql.query('SELECT COALESCE("legacyUserData"->>\'VIP\',\'0\') AS vip,COUNT(*)::int AS total FROM "_User" WHERE "company"=$1 AND ("isDeleted" IS NULL OR "isDeleted"=FALSE) AND COALESCE("legacyUserData"->>\'ParentUserID\',\'0\')=$2 GROUP BY COALESCE("legacyUserData"->>\'VIP\',\'0\')', [DEFAULT_COMPANY_ID,String(parentId)]); const result = { childs:0,v0:0,v1:0,v2:0,v3:0,v4:0,v5:0 }; for (const row of rows) { const total = number(row.total); result.childs += total; const key = 'v' + Math.max(0,Math.min(5,number(row.vip))); result[key] += total; } return result;
|
|
|
+}
|
|
|
+async function coachStudentPage(input,current) {
|
|
|
+ const coachId = ownLegacyId(current); if (!coachId) fail(400,'陪练账号缺少旧系统用户 ID'); const paging = pageInput(input); const baseValues = [DEFAULT_COMPANY_ID,String(coachId)]; const base = 'FROM "CommonModel" c JOIN "CourseAppointment" a ON a."company"=$1 AND CAST(a."id" AS text)=CAST(c."itemId" AS text) WHERE c."company"=$1 AND CAST(c."modelId" AS text)=\'54\' AND CAST(c."status" AS text)=\'99\' AND CAST(a."pl" AS text)=$2 AND COALESCE(CAST(a."szyh" AS text),\'\')<>\'\''; const countRow = await Psql.one('SELECT COUNT(DISTINCT CAST(a."szyh" AS text))::int AS total ' + base,baseValues); const rows = await Psql.query('WITH students AS (SELECT CAST(a."szyh" AS text) AS uid,MAX(CAST(a."id" AS text)) AS appointment_id ' + base + ' GROUP BY CAST(a."szyh" AS text) ORDER BY MAX(c."updatedAt") DESC LIMIT $3 OFFSET $4) SELECT ' + userSelect('u') + ',students.uid AS "__studentId",students.appointment_id AS "__appointmentId" FROM students LEFT JOIN "_User" u ON u."company"=$1 AND CAST(u."legacyUserId" AS text)=students.uid',baseValues.concat([paging.size,(paging.index - 1) * paging.size])); const normalized = rows.map((row) => { const value = legacyUserRow(row); const studentId = number(row.__studentId || value.UserID); return { ...value, userId:studentId, UserID:studentId, szyh:studentId, ID:number(row.__appointmentId), honeyname:value.HoneyName, honeyName:value.HoneyName }; }); const total = number(countRow.total); return { rows:normalized,page:{ itemCount:total,pageCount:Math.ceil(total / paging.size),pageIndex:paging.index,pageSize:paging.size } };
|
|
|
+}
|
|
|
async function authorizeRequestedUser(current, requestedId) {
|
|
|
const targetId = number(requestedId || ownLegacyId(current)); if (!targetId) fail(400, '缺少用户 ID'); if (isAdminUser(current) || targetId === ownLegacyId(current)) return targetId;
|
|
|
const fields = await fieldsOf('_User'); const target = await findByLegacyId('_User', fields, targetId, ['legacyUserId','userid','num']); const agent = target && target.get('agent'); if (!target || !agent || agent.id !== current.id) fail(403, '无权查看该学员的业务记录'); return targetId;
|
|
|
@@ -453,7 +492,7 @@ async function resolveContent(input, requireOne = false) { const fields = await
|
|
|
async function handler(request, response) {
|
|
|
try {
|
|
|
const input = inputOf(request); const action = String(input.action || ''); if (!action) return response.status(400).json(reject('缺少 action'));
|
|
|
- if (action === 'migration_status') return response.json(envelope({ implemented: ['app_update','user_login_passwd','user_register','user_info_name','user_get','user_list','e_user_list','user_update','user_update_pwd','user_update_pwdall','content_list','content_list_llk','content_get','content_uphis','content_add','content_add_zt','content_update','node_list','node_get','product_list','product_get','product_stock_list','e_add_words','e_ck_list','e_get_21list','e_order_detail','e_order_tongji','e_order_update_v2','e_record_detail','e_words_list','stu_record_update_v2','user_point_list','guestbook_add'], blocked: BLOCKED }));
|
|
|
+ if (action === 'migration_status') return response.json(envelope({ implemented: ['app_update','user_login_passwd','user_register','user_info_name','user_get','user_list','user_dept','e_user_list','user_update','user_update_pwd','user_update_pwdall','content_list','content_list_llk','content_get','content_uphis','content_add','content_add_zt','content_update','node_list','node_get','product_list','product_get','product_stock_list','e_add_words','e_ck_list','e_get_21list','e_order_detail','e_order_tongji','e_order_update_v2','e_record_detail','e_words_list','stu_record_update_v2','user_point_list','guestbook_add'], blocked: BLOCKED }));
|
|
|
if (BLOCKED[action]) return response.status(501).json(reject('migration_blocked: ' + BLOCKED[action]));
|
|
|
if (action === 'user_login_passwd') {
|
|
|
const username = String(input.name || input.username || '').trim(); const password = String(input.passwd || input.password || ''); if (!username || !password) return response.status(400).json(reject('请输入账号和密码'));
|
|
|
@@ -465,8 +504,10 @@ async function handler(request, response) {
|
|
|
}
|
|
|
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);
|
|
|
- if (action === 'user_get') { const requestedId = number(input.uid || current.id); let target = current; const ownId = number(current.get('legacyUserId') || current.get('userid') || current.get('num')); if (requestedId && requestedId !== ownId) { const fields = await fieldsOf('_User'); const found = await findByLegacyId('_User', fields, requestedId, ['legacyUserId','userid','num']); if (!found) return response.status(404).json(reject('用户不存在')); const isAdmin = current.get('isAdmin') === true; const isAgentChild = found.get('agent') && found.get('agent').id === current.id; if (!isAdmin && !isAgentChild) return response.status(403).json(reject('无权查看该用户')); target = found; } return response.json(envelope(legacyUser(target), { State: target.get('isDisabled') === true ? 0 : 1 })); }
|
|
|
- if (action === 'user_list' || action === 'e_user_list') { if (action === 'user_list' && current.get('isAdmin') !== true) return response.status(403).json(reject('仅管理员可查询全量用户')); const result = await paged('_User', input, (query, fields) => { const uid = number(current.get('legacyUserId') || current.get('userid')); if (action === 'e_user_list' && fields.agent) query.equalTo('agent', current); else if (fields.legacyUserId && uid) query.notEqualTo('legacyUserId', uid); }); return response.json(envelope(result.rows.map((row) => ({ ...row, userId: number(row.legacyUserId || row.userid || row.num), userName: row.username, honeyName: row.nickname || row.realName || row.username })), undefined, result.page)); }
|
|
|
+ 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' || action === 'user_update_pwd' || action === 'user_update_pwdall') { if (action !== 'user_update') { const password = String(input.passwd || input.password || input.pwd || ''); if (password.length < 8) return response.status(400).json(reject('新密码至少 8 位')); current.setPassword(password); current.set('passwordResetRequired', false); } else { const allowed = { honeyName:'nickname', nickname:'nickname', mobile:'mobile', userFace:'avatar', avatar:'avatar', realName:'realName', gender:'gender', school:'school' }; for (const [source,target] of Object.entries(allowed)) if (input[source] !== undefined) current.set(target, input[source]); } await current.save(null, { useMasterKey: true }); return response.json(envelope(legacyUser(current, action !== 'user_update'))); }
|
|
|
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 === 'content_list' || action === 'content_list_llk') { const result = await contentPage(input, !current); return response.json(envelope(result.rows, undefined, result.page)); }
|