Files
Ubuntu deb3e72750
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
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库: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 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

640 lines
21 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 全链路 E2E:创建测试订单 + 多角色账号验证 + 10→90 推进
* 用法: API_BASE=https://www.xdjchuanhui.com/api node server/scripts/e2e-full-workflow.mjs
*/
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const { currentCycleCode } = require('./test-helpers.js');
const BASE = process.env.API_BASE || 'http://127.0.0.1:3001/api';
const OPERATING_BRANCH = process.env.OPERATING_BRANCH || 'BR002';
const PASSWORDS = ['Superadmin@123', 'SuperAdmin@123', 'E2eTest@123', 'Purchaser@123', 'Demo123456', '123456'];
const results = [];
const created = { orderCode: null, purchaseCode: null, pickCode: null };
function pass(step, detail = '') {
results.push({ step, ok: true, detail });
console.log(` ✓ ${step}${detail ? ` — ${detail}` : ''}`);
}
function fail(step, detail = '') {
results.push({ step, ok: false, detail });
console.log(` ✗ ${step}${detail ? ` — ${detail}` : ''}`);
}
async function jsonFetch(path, options = {}) {
const res = await fetch(`${BASE}${path}`, {
...options,
headers: {
'Content-Type': 'application/json',
'X-Operating-Branch': OPERATING_BRANCH,
...(options.headers || {}),
},
});
const body = await res.json().catch(() => ({}));
return { res, body };
}
async function loginAs(credential) {
const { res, body } = await jsonFetch('/auth/token', {
method: 'POST',
body: JSON.stringify(credential),
});
if (!res.ok || !body.access_token) {
throw new Error(body.error_description || body.error || `HTTP ${res.status}`);
}
return body.access_token;
}
async function tryLogin() {
const attempts = PASSWORDS.flatMap((password) => [
{ username: 'superadmin', password },
{ email: 'superadmin@meoo.local', password },
]);
for (const cred of attempts) {
try {
const token = await loginAs(cred);
pass('超级管理员登录', Object.keys(cred).join('='));
return token;
} catch {
// try next
}
}
throw new Error('所有密码尝试失败');
}
async function query(token, spec) {
const { res, body } = await jsonFetch('/data/query', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: JSON.stringify(spec),
});
return { ok: res.ok && !body.error, res, body };
}
async function advance(token, orderCode, targetStatus) {
const { res, body } = await jsonFetch('/workflow/orders/advance', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: JSON.stringify({ order_code: orderCode, target_status: targetStatus }),
});
return { ok: res.ok, status: res.status, body };
}
async function getOrder(token, orderCode) {
const q = await query(token, {
table: 'orders',
action: 'select',
select: 'order_code, order_status, customer_code',
filters: [{ op: 'eq', column: 'order_code', value: orderCode }],
single: true,
});
return q.body?.data;
}
async function ensureDemoData(token) {
const cust = await query(token, {
table: 'customers',
action: 'select',
select: 'customer_code, company_name, branch_code',
limit: 1,
});
if (!cust.ok || !cust.body.data?.length) {
fail('基础数据-客户', '无可用客户');
return null;
}
pass('基础数据-客户', cust.body.data[0].customer_code);
const sku = await query(token, {
table: 'skus',
action: 'select',
select: 'sku_code, sku_name, unit',
filters: [{ op: 'eq', column: 'status', value: 1 }],
limit: 5,
});
if (!sku.ok || !sku.body.data?.length) {
fail('基础数据-SKU', '无可用商品');
return null;
}
pass('基础数据-SKU', `${sku.body.data.length} 个`);
const wh = await query(token, {
table: 'warehouses',
action: 'select',
select: 'warehouse_code',
limit: 1,
});
if (!wh.ok || !wh.body.data?.length) {
fail('基础数据-仓库', '无仓库,分拣出库将失败');
} else {
pass('基础数据-仓库', wh.body.data[0].warehouse_code);
}
return {
customer: cust.body.data[0].customer_code,
branchCode: cust.body.data[0].branch_code || 'BR002',
sku: sku.body.data[0],
warehouse: wh.body.data?.[0]?.warehouse_code,
skuSuppliers: await query(token, {
table: 'sku_suppliers',
action: 'select',
select: 'sku_code, supplier_code, supply_price',
filters: [{ op: 'eq', column: 'status', value: 1 }],
limit: 20,
}),
};
}
async function testRoleAccounts() {
console.log('\n[0] 多角色账号登录');
const roles = [
{ username: 'admin', label: '管理员' },
{ username: 'operator', label: '运营' },
{ username: 'warehouse', label: '仓管' },
{ username: 'finance', label: '财务' },
{ username: 'delivery', label: '配送' },
{ username: 'purchaser1', label: '采购员' },
{ username: 'supplier1', label: '供应商' },
{ username: 'delivery1', label: '配送员(移动)' },
];
for (const role of roles) {
try {
await loginAs({ username: role.username, password: 'E2eTest@123' });
pass(`${role.label}登录`, role.username);
} catch {
fail(`${role.label}登录`, `${role.username} / E2eTest@123 失败`);
}
}
}
async function createTestOrder(token, demo) {
console.log('\n[1] 创建测试订单 (status=20)');
const orderCode = `E2E${Date.now()}`;
const sku = demo.sku;
const rel =
demo.skuSuppliers.body?.data?.find((r) => r.sku_code === sku.sku_code) ||
demo.skuSuppliers.body?.data?.[0];
const price = Number(rel?.supply_price || 5.5);
const qty = 2;
const createOrder = await query(token, {
table: 'orders',
action: 'insert',
insertData: {
order_code: orderCode,
bid_code: `BID${Date.now()}`,
cycle_code: currentCycleCode(),
customer_code: demo.customer,
branch_code: demo.branchCode,
order_status: 20,
total_amount: price * qty,
total_weight: qty,
delivery_date: new Date().toISOString().slice(0, 10),
delivery_time_slot: 'morning',
},
});
if (!createOrder.ok) {
fail('创建订单', createOrder.body.error?.message);
return null;
}
pass('创建订单', orderCode);
created.orderCode = orderCode;
const createItems = await query(token, {
table: 'order_items',
action: 'insert',
insertData: [
{
order_code: orderCode,
sku_code: sku.sku_code,
quantity: qty,
unit: sku.unit || '斤',
price,
amount: price * qty,
item_status: 10,
sort_order: 1,
supplier_code: rel?.supplier_code || null,
branch_code: demo.branchCode,
},
],
});
if (!createItems.ok) {
fail('创建订单明细', createItems.body.error?.message);
return orderCode;
}
pass('创建订单明细', sku.sku_code);
return { orderCode, sku, rel, qty, price, branchCode: demo.branchCode };
}
async function setupAllocation(token, ctx) {
console.log('\n[2] 分配与备货 (模拟 20→30)');
const { orderCode, sku, rel, qty, price, branchCode } = ctx;
if (!rel?.supplier_code) {
fail('供应商分配', 'SKU 无 sku_suppliers 关系,无法走供应商备货路径');
return false;
}
const itemQ = await query(token, {
table: 'order_items',
action: 'select',
select: 'id',
filters: [{ op: 'eq', column: 'order_code', value: orderCode }],
single: true,
});
const itemId = itemQ.body?.data?.id;
if (itemId) {
await query(token, {
table: 'order_items',
action: 'update',
updateData: { supplier_code: rel.supplier_code, price, amount: price * qty },
filters: [{ op: 'eq', column: 'id', value: itemId }],
});
}
const prep = await query(token, {
table: 'supplier_preparations',
action: 'insert',
insertData: {
order_code: orderCode,
supplier_code: rel.supplier_code,
sku_code: sku.sku_code,
prepare_qty: qty,
purchase_price: price,
prepare_status: 10,
branch_code: branchCode,
},
});
if (!prep.ok) {
fail('创建备货单', prep.body.error?.message);
return false;
}
pass('创建备货单');
const adv30 = await advance(token, orderCode, 30);
if (adv30.ok) {
pass('推进 20→30', adv30.body.data?.message || '');
} else {
fail('推进 20→30', adv30.body.error_description || JSON.stringify(adv30.body));
throw new Error('工作流推进失败,测试禁止绕过服务端状态机');
}
return true;
}
async function mobileLogin(username, password, roleType) {
const candidates = [...new Set([password, ...PASSWORDS])];
let lastError = '移动端登录失败';
for (const candidate of candidates) {
const payload = { username, password: candidate };
if (roleType) payload.role_type = roleType;
const { res, body } = await jsonFetch('/mobile/login', {
method: 'POST',
body: JSON.stringify(payload),
});
if (res.ok) return body;
lastError = body.error_description || lastError;
}
throw new Error(lastError);
}
async function completeSupplierPreparations(token, orderCode) {
const preps = await query(token, {
table: 'supplier_preparations',
action: 'select',
select: 'id, prepare_status, prepare_qty, purchase_price',
filters: [{ op: 'eq', column: 'order_code', value: orderCode }],
});
const pending = (preps.body?.data || []).filter((r) => Number(r.prepare_status) < 30);
if (!pending.length) {
pass('供应商备货', '已全部完成');
return;
}
const supplierSession = await mobileLogin('supplier1', 'E2eTest@123', 'supplier');
pass('供应商登录', 'supplier1');
for (const prep of pending) {
const statusRes = await jsonFetch('/mobile/supplier/preparations/status', {
method: 'POST',
headers: { Authorization: `Bearer ${supplierSession.access_token}` },
body: JSON.stringify({
id: prep.id,
status: 30,
prepare_qty: Number(prep.prepare_qty) || 10,
purchase_price: Number(prep.purchase_price) || 3,
}),
});
if (statusRes.res.ok) pass('供应商备货完成', prep.id.slice(0, 8));
else fail('供应商备货完成', statusRes.body.error_description || statusRes.res.status);
}
}
async function simulateDeliveryStart(token, orderCode) {
const taskQ = await query(token, {
table: 'delivery_tasks',
action: 'select',
select: 'task_code, person_code',
filters: [{ op: 'eq', column: 'order_code', value: orderCode }],
limit: 1,
});
const taskCode = taskQ.body?.data?.[0]?.task_code;
if (!taskCode) {
fail('配送任务', '分拣出库后未生成配送任务');
return;
}
const deliveryLogin = await mobileLogin('delivery1', 'E2eTest@123', 'delivery');
const personRes = await jsonFetch('/mobile/delivery/tasks', {
headers: { Authorization: `Bearer ${deliveryLogin.access_token}` },
});
const personCode = personRes.body?.person_code;
if (personCode) {
await query(token, {
table: 'delivery_tasks',
action: 'update',
updateData: { person_code: personCode },
filters: [{ op: 'eq', column: 'task_code', value: taskCode }],
});
}
const start = await jsonFetch('/mobile/delivery/start', {
method: 'POST',
headers: { Authorization: `Bearer ${deliveryLogin.access_token}` },
body: JSON.stringify({ task_code: taskCode, order_code: orderCode }),
});
if (start.res.ok) pass('配送员开始配送', taskCode);
else fail('配送员开始配送', start.body.error_description || start.res.status);
}
async function simulateCustomerSign(token, orderCode) {
const taskQ = await query(token, {
table: 'delivery_tasks',
action: 'select',
select: 'task_code',
filters: [{ op: 'eq', column: 'order_code', value: orderCode }],
limit: 1,
});
const taskCode = taskQ.body?.data?.[0]?.task_code;
if (!taskCode) {
fail('客户签收', '无配送任务');
return;
}
const sign = await jsonFetch('/workflow/delivery/signature', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: JSON.stringify({
task_code: taskCode,
order_code: orderCode,
sign_type: 'customer',
signature_data: 'E2E-test-signature',
signer_name: 'E2E客户',
}),
});
if (sign.res.ok) pass('客户电子签收', taskCode);
else fail('客户电子签收', sign.body.error_description || sign.res.status);
}
async function runWorkflowChain(token, orderCode, demo) {
console.log('\n[3] 服务端工作流推进 30→90');
const steps = [
{ from: 30, to: 40, label: '备货完成→待验收' },
{ from: 40, to: 45, label: '验收完成→待分拣' },
{ from: 45, to: 50, label: '分拣→待配送' },
{ from: 50, to: 60, label: '配送中' },
{ from: 60, to: 90, label: '已完成' },
];
for (const step of steps) {
const order = await getOrder(token, orderCode);
const current = Number(order?.order_status || 0);
if (current >= step.to) {
pass(`跳过 ${step.label}`, `已在 status ${current}`);
continue;
}
if (current < step.from) {
fail(`推进 ${step.label}`, `当前 status=${current},期望 >=${step.from}`);
continue;
}
if (step.from === 30 && step.to === 40) {
await completeSupplierPreparations(token, orderCode);
}
if (step.from === 40 && step.to === 45) {
const insps = await query(token, {
table: 'inspections',
action: 'select',
select: 'id, prepare_qty, actual_qty, quality_rating',
filters: [{ op: 'eq', column: 'order_code', value: orderCode }],
});
const pending = (insps.body?.data || []).filter((r) => !r.actual_qty && !r.quality_rating);
for (const row of pending) {
const submit = await jsonFetch('/workflow/inspection/submit', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: JSON.stringify({
id: row.id,
actual_qty: Number(row.prepare_qty) || 0,
quality_rating: 'B',
loss_qty: 0,
}),
});
if (submit.res.ok) {
pass('合规验收入库', `${row.id.slice(0, 8)}… batch=${submit.body.data?.batchNo || 'ok'}`);
} else {
fail('合规验收入库', submit.body.error_description || submit.body.error);
}
}
const inv = await query(token, {
table: 'inventory',
action: 'select',
select: 'batch_no, available_qty, branch_code',
filters: [{ op: 'eq', column: 'sku_code', value: (await query(token, {
table: 'order_items',
action: 'select',
select: 'sku_code',
filters: [{ op: 'eq', column: 'order_code', value: orderCode }],
single: true,
})).body?.data?.sku_code }],
limit: 3,
});
if (inv.body?.data?.length) {
pass('验收入库库存', inv.body.data.map((r) => `${r.batch_no}@${r.branch_code || 'null'}`).join(', '));
} else if (pending.length) {
fail('验收入库库存', '合规验收后未写入库存');
}
const proc = await query(token, {
table: 'processing_tasks',
action: 'select',
select: 'id, process_status',
filters: [{ op: 'eq', column: 'order_code', value: orderCode }],
});
const pendingProc = (proc.body?.data || []).filter(
(t) => Number(t.process_status) !== 40 && Number(t.process_status) !== 50
);
if (pendingProc.length) {
fail('加工任务未完成', `${pendingProc.length} 个任务阻塞 40→45`);
}
}
if (step.from === 50 && step.to === 60) {
await simulateDeliveryStart(token, orderCode);
}
if (step.from === 60 && step.to === 90) {
await simulateCustomerSign(token, orderCode);
}
const adv = await advance(token, orderCode, step.to);
if (adv.ok) {
pass(step.label, adv.body.data?.message || `→ ${step.to}`);
} else {
const after = await getOrder(token, orderCode);
const afterStatus = Number(after?.order_status || 0);
if (afterStatus >= step.to) {
pass(step.label, `订单已在 status ${afterStatus}(合规验收后自动推进)`);
} else {
fail(step.label, adv.body.error_description || adv.body.error || `HTTP ${adv.status}`);
if (step.from === 45) {
const wh = demo.warehouse || 'WH001';
const pick = await jsonFetch('/workflow/picking/create', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: JSON.stringify({ order_code: orderCode, warehouse_code: wh }),
});
if (pick.res.ok) {
created.pickCode = pick.body.data?.pickCode;
pass('手动创建分拣单', created.pickCode);
const out = await jsonFetch('/workflow/picking/outbound', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
body: JSON.stringify({ pick_code: created.pickCode }),
});
if (out.res.ok) pass('分拣出库');
else fail('分拣出库', out.body.error_description);
const retry = await advance(token, orderCode, step.to);
if (retry.ok) pass(`重试 ${step.label}`);
} else {
fail('手动创建分拣单', pick.body.error_description);
}
}
}
}
}
const final = await getOrder(token, orderCode);
if (Number(final?.order_status) === 90) pass('订单终态', 'status=90 已完成');
else fail('订单终态', `status=${final?.order_status},未走完 90`);
}
async function testWorkflowApis(token) {
console.log('\n[4] 工作流 API 探针');
const probes = [
{ name: '加工任务列表', path: '/workflow/processing/tasks?tab=work', method: 'GET' },
{ name: '分拣任务列表', path: '/workflow/picking/tasks', method: 'GET' },
{ name: '待审采购单', path: '/workflow/purchase/pending-audits', method: 'GET' },
];
for (const p of probes) {
const { res, body } = await jsonFetch(p.path, {
method: p.method,
headers: { Authorization: `Bearer ${token}` },
});
if (res.ok) pass(p.name, Array.isArray(body.data) ? `${body.data.length} 条` : 'OK');
else fail(p.name, body.error_description || `HTTP ${res.status}`);
}
}
async function testMobileRoles() {
console.log('\n[5] 移动端 API (unified-login)');
const mobileRoles = [
{ username: 'warehouse', label: '仓管' },
{ username: 'purchaser1', label: '采购员' },
{ username: 'supplier1', label: '供应商' },
{ username: 'delivery1', label: '配送员' },
];
for (const role of mobileRoles) {
const login = await jsonFetch('/auth/unified-login', {
method: 'POST',
body: JSON.stringify({ username: role.username, password: 'E2eTest@123' }),
});
const mobileToken = login.body.mobile_session?.access_token;
if (!mobileToken) {
fail(`${role.label} unified-login`, login.body.error_description || '无 mobile token');
continue;
}
pass(`${role.label} unified-login`);
const path =
role.username === 'warehouse'
? '/mobile/inspection/tasks'
: role.username === 'purchaser1'
? '/mobile/purchase/orders'
: role.username === 'supplier1'
? '/mobile/supplier/preparations'
: '/mobile/delivery/tasks';
const { res, body } = await jsonFetch(path, {
headers: { Authorization: `Bearer ${mobileToken}` },
});
if (res.ok) pass(`移动端 ${path}`, 'OK');
else fail(`移动端 ${path}`, body.error_description || `HTTP ${res.status}`);
}
}
async function main() {
console.log(`\n=== 全链路 E2E 测试 ===\nAPI: ${BASE}\n`);
const health = await jsonFetch('/health');
if (!health.res.ok) {
console.error('API 不可达');
process.exit(1);
}
pass('健康检查');
let token;
try {
token = await tryLogin();
} catch (e) {
fail('登录', e.message);
process.exit(1);
}
await testRoleAccounts();
const demo = await ensureDemoData(token);
if (!demo) process.exit(1);
const ctx = await createTestOrder(token, demo);
if (!ctx) process.exit(1);
await setupAllocation(token, ctx);
await runWorkflowChain(token, ctx.orderCode, demo);
await testWorkflowApis(token);
await testMobileRoles();
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}`));
}
if (created.orderCode) {
if (process.env.KEEP_ORDER === '1') {
console.log(`\n测试订单: ${created.orderCode}(KEEP_ORDER=1,保留)`);
} else if (process.env.DATABASE_URL) {
console.log(`\n[6] 清理本单测试数据: ${created.orderCode}`);
const { cleanupTestOrders } = await import('./cleanup-e2e-test-data.mjs');
await cleanupTestOrders([created.orderCode], { execute: true });
pass('清理测试订单', created.orderCode);
} else {
console.log(`\n测试订单: ${created.orderCode}(无 DATABASE_URL,未自动清理)`);
}
}
process.exit(failed.length ? 1 : 0);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});