来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
383 lines
12 KiB
JavaScript
383 lines
12 KiB
JavaScript
/**
|
||
* 项目功能完整性集成测试
|
||
* 用法: node server/scripts/test-functionality.js
|
||
*/
|
||
|
||
const { currentCycleCode } = require('./test-helpers.js');
|
||
|
||
const BASE = process.env.API_BASE || 'http://127.0.0.1:3001/api';
|
||
const isLocalApi = BASE.includes('127.0.0.1') || BASE.includes('localhost');
|
||
const OPERATING_BRANCH = process.env.E2E_TEST_BRANCH || process.env.OPERATING_BRANCH || 'BR002';
|
||
|
||
function apiHeaders(token, extra = {}) {
|
||
return {
|
||
'Content-Type': 'application/json',
|
||
'X-Operating-Branch': OPERATING_BRANCH,
|
||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||
...extra,
|
||
};
|
||
}
|
||
|
||
/** 与 README / seed-dev-passwords、seed-e2e-role-passwords 对齐,本地优先 123456 */
|
||
const PASSWORD_CANDIDATES = [
|
||
...new Set(
|
||
[
|
||
process.env.TEST_PASSWORD,
|
||
isLocalApi ? process.env.DEV_SIMPLE_PASSWORD || '123456' : null,
|
||
process.env.E2E_TEST_PASSWORD || 'E2eTest@123',
|
||
'Superadmin@123',
|
||
'SuperAdmin@123',
|
||
'Admin@123',
|
||
'Operator@123',
|
||
'123456',
|
||
].filter(Boolean)
|
||
),
|
||
];
|
||
|
||
function accountCandidates(username, email) {
|
||
const list = [];
|
||
for (const password of PASSWORD_CANDIDATES) {
|
||
list.push({ username, password });
|
||
if (email) list.push({ email, password });
|
||
}
|
||
return list;
|
||
}
|
||
|
||
const results = [];
|
||
|
||
function pass(name, detail = '') {
|
||
results.push({ name, ok: true, detail });
|
||
console.log(` ✓ ${name}${detail ? ` — ${detail}` : ''}`);
|
||
}
|
||
|
||
function fail(name, detail = '') {
|
||
results.push({ name, ok: false, detail });
|
||
console.log(` ✗ ${name}${detail ? ` — ${detail}` : ''}`);
|
||
}
|
||
|
||
function skip(name, detail = '') {
|
||
results.push({ name, ok: true, skipped: true, detail });
|
||
console.log(` ○ ${name}${detail ? ` — ${detail}` : ''} (跳过)`);
|
||
}
|
||
|
||
async function jsonFetch(path, options = {}) {
|
||
const { headers: extraHeaders, token, ...rest } = options;
|
||
const res = await fetch(`${BASE}${path}`, {
|
||
...rest,
|
||
headers: apiHeaders(token, extraHeaders),
|
||
});
|
||
const body = await res.json().catch(() => ({}));
|
||
return { res, body };
|
||
}
|
||
|
||
async function loginWithCandidates(candidates) {
|
||
for (const cred of candidates) {
|
||
const { res, body } = await jsonFetch('/auth/token', {
|
||
method: 'POST',
|
||
body: JSON.stringify(cred),
|
||
});
|
||
if (res.ok && body.access_token) return body.access_token;
|
||
}
|
||
throw new Error('login failed');
|
||
}
|
||
|
||
async function login(email, password) {
|
||
return loginWithCandidates([{ email, password }, { username: email.split('@')[0], password }]);
|
||
}
|
||
|
||
async function query(token, spec) {
|
||
const { res, body } = await jsonFetch('/data/query', {
|
||
method: 'POST',
|
||
token,
|
||
body: JSON.stringify(spec),
|
||
});
|
||
return { ok: res.ok && !body.error, res, body };
|
||
}
|
||
|
||
async function invokeFunction(name, payload, token) {
|
||
const { res, body } = await jsonFetch(`/functions/${name}`, {
|
||
method: 'POST',
|
||
token,
|
||
body: JSON.stringify(payload),
|
||
});
|
||
return { ok: res.ok && !body.error, res, body };
|
||
}
|
||
|
||
async function main() {
|
||
console.log('\n=== AI生鲜配送系统 功能完整性测试 ===\n');
|
||
console.log(`API: ${BASE}\n`);
|
||
|
||
// 1. 基础设施
|
||
console.log('[1] 基础设施');
|
||
try {
|
||
const { res, body } = await jsonFetch('/health');
|
||
if (res.ok && body.status === 'ok') pass('后端健康检查');
|
||
else fail('后端健康检查', `status=${res.status}`);
|
||
} catch (e) {
|
||
fail('后端健康检查', e.message);
|
||
console.log('\n后端未启动,请先运行 npm run dev:all\n');
|
||
process.exit(1);
|
||
}
|
||
|
||
const isRemote = !BASE.includes('127.0.0.1') && !BASE.includes('localhost');
|
||
if (!isRemote) {
|
||
try {
|
||
const frontend = await fetch('http://127.0.0.1:3015/', { method: 'GET' });
|
||
if (frontend.ok) pass('前端 dev server (3015)');
|
||
else fail('前端 dev server (3015)', `status=${frontend.status}`);
|
||
} catch {
|
||
fail('前端 dev server (3015)', '未启动');
|
||
}
|
||
} else {
|
||
pass('前端 dev server (3015)', '远程 API 测试跳过');
|
||
}
|
||
|
||
// 2. 认证
|
||
console.log('\n[2] 认证与权限');
|
||
let token;
|
||
const superadminCandidates = accountCandidates('superadmin', 'superadmin@meoo.local');
|
||
const optionalAccounts = [
|
||
{ label: 'admin', username: 'admin', email: 'admin@meoo.local' },
|
||
{ label: 'operator', username: 'operator', email: 'operator@meoo.local' },
|
||
];
|
||
|
||
try {
|
||
token = await loginWithCandidates(superadminCandidates);
|
||
pass('登录: superadmin');
|
||
pass('获取 superadmin token');
|
||
} catch (e) {
|
||
fail('登录: superadmin', e.message);
|
||
fail('获取 superadmin token', e.message);
|
||
console.log('\n无法继续 API 测试\n');
|
||
printSummary();
|
||
process.exit(1);
|
||
}
|
||
|
||
const existingUsers = await query(token, {
|
||
table: 'profiles',
|
||
action: 'select',
|
||
select: 'username',
|
||
filters: [
|
||
{
|
||
op: 'in',
|
||
column: 'username',
|
||
value: optionalAccounts.map((a) => a.username),
|
||
},
|
||
],
|
||
});
|
||
const seededUsernames = new Set(
|
||
(existingUsers.body.data || []).map((row) => row.username)
|
||
);
|
||
|
||
for (const account of optionalAccounts) {
|
||
if (!seededUsernames.has(account.username)) {
|
||
skip(`登录: ${account.label}`, '账号未种子化,可运行 npm run migrate');
|
||
continue;
|
||
}
|
||
try {
|
||
await loginWithCandidates(accountCandidates(account.username, account.email));
|
||
pass(`登录: ${account.label}`);
|
||
} catch (e) {
|
||
fail(`登录: ${account.label}`, e.message);
|
||
}
|
||
}
|
||
|
||
const { res: userRes, body: userBody } = await jsonFetch('/auth/user', { token });
|
||
if (userRes.ok && userBody.id) pass('获取当前用户 /auth/user');
|
||
else fail('获取当前用户 /auth/user');
|
||
|
||
const profileQ = await query(token, {
|
||
table: 'profiles',
|
||
action: 'select',
|
||
select: 'id, username, status',
|
||
filters: [{ op: 'eq', column: 'id', value: userBody.id }],
|
||
single: true,
|
||
});
|
||
if (profileQ.ok && profileQ.body.data?.username) {
|
||
pass('用户资料 profiles', profileQ.body.data.username);
|
||
} else fail('用户资料 profiles', profileQ.body.error?.message);
|
||
|
||
const permQ = await query(token, {
|
||
table: 'role_permissions',
|
||
action: 'select',
|
||
select: 'role',
|
||
filters: [{ op: 'eq', column: 'role', value: 'super_admin' }],
|
||
});
|
||
if (permQ.ok && (permQ.body.data?.length || 0) > 0) {
|
||
pass('权限种子 role_permissions', `${permQ.body.data.length} 条`);
|
||
} else fail('权限种子 role_permissions');
|
||
|
||
// 3. 核心业务数据
|
||
console.log('\n[3] 核心业务数据 API');
|
||
const tables = [
|
||
'categories',
|
||
'skus',
|
||
'customers',
|
||
'suppliers',
|
||
'customer_skus',
|
||
'orders',
|
||
'permissions',
|
||
];
|
||
|
||
for (const table of tables) {
|
||
const q = await query(token, { table, action: 'select', select: '*', limit: 5 });
|
||
if (q.ok) {
|
||
const count = Array.isArray(q.body.data) ? q.body.data.length : q.body.data ? 1 : 0;
|
||
pass(`查询 ${table}`, `${count} 条样本`);
|
||
} else {
|
||
const msg = q.body.error?.message || '';
|
||
if (table === 'categories' && msg.includes('branch_code')) {
|
||
skip(`查询 ${table}`, '需执行 migrate(categories.branch_code)');
|
||
} else {
|
||
fail(`查询 ${table}`, msg);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 4. Edge Functions
|
||
console.log('\n[4] 业务函数 (functions)');
|
||
const textParse = await invokeFunction(
|
||
'parse-order-three-layer',
|
||
{ customerCode: 'CUST001', text: '苹果5斤,鸡蛋20个' },
|
||
token
|
||
);
|
||
if (textParse.ok && textParse.body.data?.items?.length) {
|
||
pass('文本订单解析', `${textParse.body.data.items.length} 条商品`);
|
||
} else {
|
||
fail('文本订单解析', textParse.body.error?.message || '无结果');
|
||
}
|
||
|
||
const tinyImage = Buffer.from(
|
||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
|
||
'base64'
|
||
).toString('base64');
|
||
|
||
const imageParse = await invokeFunction(
|
||
'parse-order-three-layer',
|
||
{ customerCode: 'CUST001', imageBase64: tinyImage },
|
||
token
|
||
);
|
||
if (imageParse.ok && imageParse.body.data?.items?.length) {
|
||
pass('图片订单解析', `${imageParse.body.data.items.length} 条${imageParse.body.data.demoMode ? ' (演示/AI)' : ''}`);
|
||
} else {
|
||
fail('图片订单解析', imageParse.body.error?.message || '无结果');
|
||
}
|
||
|
||
const imageOrder = await invokeFunction(
|
||
'parse-image-order',
|
||
{ customerCode: 'CUST001', imageBase64: tinyImage },
|
||
token
|
||
);
|
||
if (imageOrder.ok && imageOrder.body.data?.items?.length) {
|
||
pass('parse-image-order', `${imageOrder.body.data.items.length} 条`);
|
||
} else {
|
||
fail('parse-image-order', imageOrder.body.error?.message || '无结果');
|
||
}
|
||
|
||
const voiceParse = await invokeFunction(
|
||
'parse-voice-order',
|
||
{ customerCode: 'CUST001', text: '土豆3斤,白菜2斤' },
|
||
token
|
||
);
|
||
if (voiceParse.ok && voiceParse.body.data?.items?.length) {
|
||
pass('语音/文本 parse-voice-order', `${voiceParse.body.data.items.length} 条`);
|
||
} else {
|
||
fail('语音/文本 parse-voice-order', voiceParse.body.error?.message || '无结果');
|
||
}
|
||
|
||
const learnAlias = await invokeFunction(
|
||
'learn-alias',
|
||
{
|
||
customerCode: 'CUST001',
|
||
items: [{ originalName: '测试别名', skuCode: 'SKU001', skuName: '红富士苹果' }],
|
||
},
|
||
token
|
||
);
|
||
if (learnAlias.ok) pass('learn-alias', `learned=${learnAlias.body.data?.learned ?? 0}`);
|
||
else fail('learn-alias', learnAlias.body.error?.message);
|
||
|
||
for (const fn of ['ai-quality-analysis']) {
|
||
const r = await invokeFunction(fn, {}, token);
|
||
if (r.ok && r.body.data) pass(`桩函数 ${fn}`);
|
||
else fail(`桩函数 ${fn}`, r.body.error?.message);
|
||
}
|
||
|
||
const invoiceOcr = await invokeFunction('invoice-ocr', { imageBase64: tinyImage }, token);
|
||
const ocrCode = invoiceOcr.body.error?.code || '';
|
||
const ocrMsg = invoiceOcr.body.error?.message || '';
|
||
if (invoiceOcr.res?.status === 501 || ocrCode === 'not_in_scope' || /不对接税务|未启用/.test(ocrMsg)) {
|
||
skip('桩函数 invoice-ocr', '产品边界:财务不对接税务系统');
|
||
} else if (invoiceOcr.ok && invoiceOcr.body.data) {
|
||
pass('桩函数 invoice-ocr');
|
||
} else {
|
||
fail('桩函数 invoice-ocr', ocrMsg || `status=${invoiceOcr.res?.status}`);
|
||
}
|
||
|
||
// 5. 写操作抽样
|
||
console.log('\n[5] 写操作抽样');
|
||
const orderCode = `ORD${Date.now()}`;
|
||
const insertOrder = await query(token, {
|
||
table: 'orders',
|
||
action: 'insert',
|
||
insertData: {
|
||
order_code: orderCode,
|
||
bid_code: `BID${Date.now()}`,
|
||
cycle_code: currentCycleCode(),
|
||
customer_code: 'CUST001',
|
||
order_status: 0,
|
||
total_amount: 0,
|
||
branch_code: OPERATING_BRANCH,
|
||
},
|
||
});
|
||
if (insertOrder.ok) pass('创建订单 insert orders', orderCode);
|
||
else fail('创建订单 insert orders', insertOrder.body.error?.message);
|
||
|
||
if (insertOrder.ok) {
|
||
const insertItem = await query(token, {
|
||
table: 'order_items',
|
||
action: 'insert',
|
||
insertData: {
|
||
order_code: orderCode,
|
||
sku_code: 'SKU001',
|
||
quantity: 1,
|
||
unit: '斤',
|
||
price: 0,
|
||
amount: 0,
|
||
},
|
||
});
|
||
if (insertItem.ok) pass('创建订单明细 insert order_items');
|
||
else fail('创建订单明细 insert order_items', insertItem.body.error?.message);
|
||
|
||
const delOrder = await query(token, {
|
||
table: 'orders',
|
||
action: 'delete',
|
||
filters: [{ op: 'eq', column: 'order_code', value: orderCode }],
|
||
});
|
||
if (delOrder.ok) pass('清理测试订单 delete orders');
|
||
else fail('清理测试订单 delete orders', delOrder.body.error?.message);
|
||
}
|
||
|
||
printSummary();
|
||
process.exit(results.some((r) => !r.ok) ? 1 : 0);
|
||
}
|
||
|
||
function printSummary() {
|
||
const passed = results.filter((r) => r.ok).length;
|
||
const failed = results.filter((r) => !r.ok);
|
||
const skipped = results.filter((r) => r.skipped).length;
|
||
console.log('\n=== 测试汇总 ===');
|
||
console.log(`通过: ${passed}/${results.length}${skipped ? ` (${skipped} 跳过)` : ''}`);
|
||
if (failed.length) {
|
||
console.log('\n失败项:');
|
||
failed.forEach((r) => console.log(` - ${r.name}: ${r.detail}`));
|
||
} else {
|
||
console.log('全部通过 ✓');
|
||
}
|
||
console.log('');
|
||
}
|
||
|
||
main().catch((error) => {
|
||
console.error(error);
|
||
process.exit(1);
|
||
});
|