Files
SupplierSystem/server/scripts/test-miniprogram-flow.mjs
Ubuntu 5fa2bbfd55
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
fix(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14)
- T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9)
- T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4)
- T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8)
- T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15)
- T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8)
- T7 前后端测试与 lint 门禁清零
- T8 应付卡片按关联订单日(口径 A)
- T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
2026-10-19 16:16:51 +08:00

256 lines
8.6 KiB
JavaScript

#!/usr/bin/env node
/**
* 小程序全流程 API 探针(**无默认目标**,必须显式指定)
* 用法: API_BASE=http://127.0.0.1:3022/api node server/scripts/test-miniprogram-flow.mjs
* 远程: API_BASE=https://... ALLOW_REMOTE=1(非 TTY 拒绝)
*/
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const { guardTestTarget } = require('./test-target-guard.js');
const explicitApiBase = String(process.env.API_BASE || '').trim();
if (!explicitApiBase) {
console.error('未设置 API_BASE:本机请用 http://127.0.0.1:3022/api;远程需同时设置 ALLOW_REMOTE=1');
process.exit(1);
}
const BASE = guardTestTarget({ base: explicitApiBase, explicit: true, label: 'API_BASE' });
const PASSWORDS = [
process.env.MP_TEST_PASSWORD,
'Superadmin@123',
'E2eTest@123',
'Purchaser@123',
'123456',
].filter(Boolean);
const ACCOUNTS = [
{ username: 'superadmin', label: '超管', expectRoles: ['order_entry', 'warehouse'] },
{ username: 'operator', label: '录单员', expectRoles: ['order_entry'] },
{ username: 'warehouse', label: '仓管', expectRoles: ['warehouse'], denyOrderEntry: true },
{ username: 'purchaser1', label: '采购员', expectRoles: ['purchaser'], denyOrderEntry: true },
{ username: 'supplier1', label: '供应商', expectRoles: ['supplier'], denyOrderEntry: true },
{ username: 'delivery1', label: '配送员', expectRoles: ['delivery'], denyOrderEntry: true },
];
const results = [];
function pass(step, detail = '') {
results.push({ ok: true, step, detail });
console.log(` ✓ ${step}${detail ? `: ${detail}` : ''}`);
}
function fail(step, detail = '') {
results.push({ ok: false, step, detail });
console.log(` ✗ ${step}${detail ? `: ${detail}` : ''}`);
}
async function jsonFetch(path, options = {}) {
const url = `${BASE}${path}`;
const res = await fetch(url, {
...options,
headers: {
'Content-Type': 'application/json',
...(options.headers || {}),
},
});
let body = {};
try {
body = await res.json();
} catch {
body = {};
}
return { res, body };
}
async function mobileLogin(username) {
for (const password of PASSWORDS) {
const { res, body } = await jsonFetch('/mobile/login', {
method: 'POST',
body: JSON.stringify({ username, password }),
});
if (res.ok && body.access_token) {
return { token: body.access_token, body, password };
}
}
return null;
}
async function authedGet(token, path) {
return jsonFetch(path, { headers: { Authorization: `Bearer ${token}` } });
}
async function authedPost(token, path, payload) {
return jsonFetch(path, {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: JSON.stringify(payload),
});
}
async function testAccount(account) {
console.log(`\n--- ${account.label} (${account.username}) ---`);
const login = await mobileLogin(account.username);
if (!login) {
fail(`${account.label} 登录`, '所有候选密码均失败');
return null;
}
pass(`${account.label} 登录`, `role=${login.body.role_type}`);
const token = login.token;
const roleType = login.body.role_type;
const available = (login.body.available_roles || []).map((r) =>
typeof r === 'string' ? r : r.role_type
);
const me = await authedGet(token, '/mobile/me');
if (me.res.ok) pass(`${account.label} /mobile/me`);
else fail(`${account.label} /mobile/me`, me.body.error_description || me.res.status);
const roles = await authedGet(token, '/mobile/roles');
if (roles.res.ok) {
const list = (roles.body.available_roles || []).map((r) => r.role_type || r);
pass(`${account.label} /mobile/roles`, list.join(', ') || '(空)');
} else {
fail(`${account.label} /mobile/roles`, roles.body.error_description);
}
for (const expected of account.expectRoles || []) {
if (available.includes(expected)) pass(`${account.label} 应有角色 ${expected}`);
else fail(`${account.label} 应有角色 ${expected}`, `实际: ${available.join(', ')}`);
}
if (account.denyOrderEntry) {
if (available.includes('order_entry')) {
fail(`${account.label} 不应有录单员角色`, 'available_roles 含 order_entry');
} else {
pass(`${account.label} 无录单员角色`);
}
const oe = await authedGet(token, '/mobile/order-entry/customers');
if (oe.res.status === 403 || oe.res.status === 401) {
pass(`${account.label} 代客录单 API 已拒绝`, String(oe.res.status));
} else if (oe.res.ok) {
fail(`${account.label} 代客录单 API 应拒绝`, '却返回 200');
} else {
pass(`${account.label} 代客录单 API 非 200`, String(oe.res.status));
}
}
const roleApis = {
delivery: '/mobile/delivery/tasks',
purchaser: '/mobile/purchase/orders',
supplier: '/mobile/supplier/preparations',
warehouse: '/mobile/picking/tasks',
order_entry: '/mobile/order-entry/customers',
};
const apiPath = roleApis[roleType];
if (apiPath) {
const probe = await authedGet(token, apiPath);
if (probe.res.ok) pass(`${account.label} 主功能 ${apiPath}`, Array.isArray(probe.body.data) ? `${probe.body.data.length} 条` : 'OK');
else fail(`${account.label} 主功能 ${apiPath}`, probe.body.error_description || probe.res.status);
}
return { token, roleType, available, login };
}
async function testOrderEntryFlow(token) {
console.log('\n--- 代客录单流程 ---');
const sw = await authedPost(token, '/mobile/switch-role', { role_type: 'order_entry' });
let t = token;
if (sw.res.ok && sw.body.access_token) {
t = sw.body.access_token;
pass('切换录单员', sw.body.role_type);
}
const customers = await authedGet(t, '/mobile/order-entry/customers');
if (!customers.res.ok) {
fail('加载客户列表', customers.body.error_description);
return;
}
const list = customers.body.data || [];
pass('加载客户列表', `${list.length} 个客户`);
if (!list.length) {
fail('代客录单', '无客户可测');
return;
}
const customer = list[0];
const parse = await authedPost(t, '/mobile/customer-order/parse', {
text: '测试苹果5斤',
customer_code: customer.customer_code,
});
if (parse.res.ok && (parse.body.data?.items || []).length) {
pass('文字解析', `${parse.body.data.items.length} 项`);
} else {
fail('文字解析', parse.body.error_description || parse.body.data?.message || '无商品');
}
const submit = await authedPost(t, '/mobile/order-entry/orders', {
customer_code: customer.customer_code,
remark: '小程序流程测试',
items: [{ item_name: '流程测试商品', quantity: 1, unit: '斤', price: 10, processing_method: '原材料' }],
});
if (submit.res.ok && submit.body.order_code) {
pass('提交代客录单', submit.body.order_code);
} else {
fail('提交代客录单', submit.body.error_description || JSON.stringify(submit.body).slice(0, 120));
}
}
async function testWarehouseFlow(token) {
console.log('\n--- 仓管流程 ---');
const sw = await authedPost(token, '/mobile/switch-role', { role_type: 'warehouse' });
let t = token;
if (sw.res.ok && sw.body.access_token) t = sw.body.access_token;
for (const [name, path] of [
['分拣', '/mobile/picking/tasks'],
['验收', '/mobile/inspection/tasks'],
['加工', '/mobile/processing/tasks?tab=work'],
]) {
const r = await authedGet(t, path);
if (r.res.ok) pass(name, Array.isArray(r.body.data) ? `${r.body.data.length} 条` : 'OK');
else fail(name, r.body.error_description || r.res.status);
}
}
async function main() {
console.log(`\n=== 小程序全流程 API 测试 ===\nAPI: ${BASE}\n`);
const health = await jsonFetch('/health');
if (!health.res.ok) {
console.error('API 不可达');
process.exit(1);
}
pass('健康检查');
let orderEntryToken = null;
let superToken = null;
for (const account of ACCOUNTS) {
const ctx = await testAccount(account);
if (account.username === 'operator' && ctx) orderEntryToken = ctx.token;
if (account.username === 'superadmin' && ctx) superToken = ctx.token;
}
if (orderEntryToken) await testOrderEntryFlow(orderEntryToken);
else if (superToken) await testOrderEntryFlow(superToken);
if (superToken) await testWarehouseFlow(superToken);
console.log('\n=== 汇总 ===');
const failed = results.filter((r) => !r.ok);
const passed = results.filter((r) => r.ok);
console.log(`通过: ${passed.length} 失败: ${failed.length}`);
if (failed.length) {
console.log('\n失败项:');
failed.forEach((f) => console.log(` - ${f.step}: ${f.detail}`));
}
process.exit(failed.length ? 1 : 0);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});