补齐固定旧版的浏览器逐笔写入对照并记录账务差异
This commit is contained in:
1 parent
e77588b337
commit
7d2007955f
39 files changed
+3653
-41
No files matched your search
@@ -0,0 +1,37 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { write } from './ui.mjs';
|
||||
export default async function create(ctx) {
|
||||
const page = await ctx.pageFor('assistant'),
|
||||
old = ctx.version === 'old';
|
||||
const btn = (name, scope = page) => scope.getByRole('button', { name, exact: true });
|
||||
await page
|
||||
.locator(old ? '#order-template-panel summary' : '.ant-collapse-header')
|
||||
.filter({ hasText: '开单模板' })
|
||||
.click();
|
||||
await btn('保存为新模板').click();
|
||||
const nameField = () =>
|
||||
old ? page.locator('[name=template_name]') : page.getByRole('textbox', { name: '模板名称' });
|
||||
await nameField().fill('逐笔开单模板');
|
||||
const result = await write(ctx, page, '保存开单模板', '/api/order-templates', () => btn('保存模板').click());
|
||||
assert.ok(result.id);
|
||||
// 从列表重新套用刚才写入的模板。
|
||||
if (old) {
|
||||
const got = page.waitForResponse(r => new URL(r.url()).pathname === '/api/order-templates/' + result.id);
|
||||
await page.locator('#order-template-select').selectOption(result.id);
|
||||
await got;
|
||||
await page.locator('#order-template-panel:not([open]) summary').click();
|
||||
} else {
|
||||
await page.getByTestId('template-select').locator('.ant-select-selector').click();
|
||||
await page.locator('.ant-select-item-option').filter({ hasText: '逐笔开单模板' }).click();
|
||||
}
|
||||
await btn('更新所选模板').click();
|
||||
await nameField().fill('逐笔模板修改');
|
||||
await write(ctx, page, '更新开单模板', '/api/order-templates/' + result.id + '/update', () =>
|
||||
btn('保存更新').click(),
|
||||
);
|
||||
const remove = async () => {
|
||||
await btn('删除模板').click();
|
||||
if (!old) await btn(/^删\s*除$/, page.getByRole('dialog')).click();
|
||||
};
|
||||
await write(ctx, page, '删除开单模板', '/api/order-templates/' + result.id + '/delete', remove);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { action, navigate, write } from './ui.mjs';
|
||||
import { logout } from './setup.mjs';
|
||||
export default async function demo(ctx) {
|
||||
const page = await ctx.pageFor('guest');
|
||||
await write(ctx, page, '店主演示登录', '/api/demo-login', () =>
|
||||
page
|
||||
.getByRole('button', { name: /以.*身份进入演示/ })
|
||||
.first()
|
||||
.click(),
|
||||
);
|
||||
for (const member of ['assistant', 'assistant2']) {
|
||||
await navigate(page, ctx.version, 'settings');
|
||||
await write(ctx, page, '设置内切换为' + member, '/api/demo-login', () => action(page, 'demo-' + member).click());
|
||||
await logout(ctx, page, '演示店员退出' + member);
|
||||
await write(ctx, page, '返回店主演示' + member, '/api/demo-login', () =>
|
||||
page
|
||||
.getByRole('button', { name: /以.*身份进入演示/ })
|
||||
.first()
|
||||
.click(),
|
||||
);
|
||||
}
|
||||
await logout(ctx, page, '演示退出');
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { action, fill, navigate, submit, write } from './ui.mjs';
|
||||
import { logout } from './setup.mjs';
|
||||
import { dumpDatabase } from '../lib/db-dump.js';
|
||||
|
||||
export default async function employeeRetry(ctx) {
|
||||
const { session, pageFor, step, dbPath } = ctx;
|
||||
const owner = await pageFor('owner');
|
||||
const ownerId = (await session.get('owner', '/api/state')).user.id;
|
||||
const label = '断线恢复员工';
|
||||
const password = 'fixture-employee-F2-retry';
|
||||
const endpoint = '/api/employees';
|
||||
const submitted = [];
|
||||
const fingerprints = new Set();
|
||||
await navigate(owner, ctx.version, 'settings');
|
||||
await action(owner, 'employee-reload').click();
|
||||
await owner.waitForLoadState('networkidle');
|
||||
await action(owner, 'employee-add').click();
|
||||
const form = owner.locator('#employee-form');
|
||||
await fill(form, { label, operatorName: '恢复操作员', loginName: '13900000027', password });
|
||||
|
||||
function observe(request) {
|
||||
assert.equal(request.headers()['x-ledger-user'], ownerId, '员工变更缺少店主身份');
|
||||
assert.equal(request.postDataJSON().password === password, true, '恢复操作未携带原密码');
|
||||
assert.ok(request.headers()['idempotency-key'], '员工变更缺少幂等键');
|
||||
submitted.push(request.headers()['idempotency-key']);
|
||||
fingerprints.add(createHash('sha256').update(request.postDataBuffer()).digest('hex'));
|
||||
}
|
||||
async function checkPrivateMemoryOnly() {
|
||||
const leaked = await owner.evaluate(
|
||||
({ password, key }) =>
|
||||
[localStorage, sessionStorage].some(store =>
|
||||
Object.entries(store).some(([name, value]) =>
|
||||
[password, key].some(needle => name.includes(needle) || value.includes(needle)),
|
||||
),
|
||||
),
|
||||
{ password, key: submitted[0] },
|
||||
);
|
||||
assert.equal(leaked, false, '员工操作凭证或恢复号被写入浏览器持久存储');
|
||||
assert.equal((await owner.locator('body').innerText()).includes(password), false, '错误信息显示了密码');
|
||||
assert.equal(JSON.stringify(dumpDatabase(dbPath).tables).includes(password), false, '账本留存了明文密码');
|
||||
}
|
||||
function databaseCounts() {
|
||||
const db = new DatabaseSync(dbPath, { readOnly: true });
|
||||
try {
|
||||
return {
|
||||
employees: db.prepare('SELECT COUNT(*) AS n FROM users').get().n,
|
||||
operations: db.prepare('SELECT COUNT(*) AS n FROM operations').get().n,
|
||||
};
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
const before = databaseCounts();
|
||||
const drop = async route => {
|
||||
observe(route.request());
|
||||
const response = await route.fetch();
|
||||
assert.equal(response.status(), 200, '员工变更须在服务端成功后才模拟断开');
|
||||
await response.dispose();
|
||||
await route.abort('connectionreset');
|
||||
};
|
||||
const retry = action(owner, 'employee-retry');
|
||||
await owner.route(ctx.base + endpoint, drop);
|
||||
try {
|
||||
await step('店主新增员工已入账但连续收不到回执', async () => {
|
||||
await submit(form);
|
||||
await retry.waitFor();
|
||||
assert.equal(submitted.length, 3);
|
||||
assert.equal(new Set(submitted).size, 1);
|
||||
assert.equal(fingerprints.size, 1);
|
||||
await checkPrivateMemoryOnly();
|
||||
assert.deepEqual(databaseCounts(), { employees: before.employees + 1, operations: before.operations + 1 });
|
||||
});
|
||||
} finally {
|
||||
await owner.unroute(ctx.base + endpoint, drop);
|
||||
}
|
||||
await step('店主从原页面用内存中的凭证恢复员工操作', async () => {
|
||||
const [response] = await Promise.all([
|
||||
owner.waitForResponse(r => r.request().method() === 'POST' && new URL(r.url()).pathname === endpoint),
|
||||
retry.click(),
|
||||
]);
|
||||
assert.equal(response.status(), 200);
|
||||
observe(response.request());
|
||||
assert.equal(submitted.length, 4);
|
||||
assert.equal(new Set(submitted).size, 1);
|
||||
assert.equal(fingerprints.size, 1);
|
||||
await form.waitFor({ state: 'hidden' });
|
||||
await checkPrivateMemoryOnly();
|
||||
assert.deepEqual(databaseCounts(), { employees: before.employees + 1, operations: before.operations + 1 });
|
||||
});
|
||||
const row = owner.locator('[data-employee]').filter({ hasText: label });
|
||||
await row.waitFor();
|
||||
assert.equal(await row.count(), 1);
|
||||
const member = await row.getAttribute('data-employee');
|
||||
const employee = await pageFor('guest');
|
||||
async function selectEmployee() {
|
||||
if (ctx.version === 'old') await employee.locator('#login-form [name=member]').selectOption(member);
|
||||
else {
|
||||
await employee.getByTestId('login-member').locator('.ant-select-selector').click();
|
||||
await employee.locator('.ant-select-item-option').filter({ hasText: label }).click();
|
||||
}
|
||||
await employee.locator('[name=password]:visible').fill(password);
|
||||
}
|
||||
async function signIn(title, status = 200) {
|
||||
const payload = await write(
|
||||
ctx,
|
||||
employee,
|
||||
title,
|
||||
'/api/login',
|
||||
() => employee.getByRole('button', { name: /^登\s*录$/ }).click(),
|
||||
status,
|
||||
);
|
||||
if (status === 200) {
|
||||
assert.equal(payload.user.member, member);
|
||||
const identity = employee.locator(ctx.version === 'old' ? '#identity' : '[data-testid=identity]');
|
||||
await identity.getByText(label, { exact: false }).waitFor();
|
||||
} else assert.equal(payload.error, '账号或密码不正确');
|
||||
}
|
||||
async function setStatus(verb, title) {
|
||||
await action(row, 'employee-' + verb).click();
|
||||
const f = owner.locator('#employee-status-form');
|
||||
await f.locator('[name=verified]').check();
|
||||
await write(ctx, owner, title, '/api/employees/' + member + '/' + verb, () => submit(f));
|
||||
await f.waitFor({ state: 'hidden' });
|
||||
}
|
||||
await selectEmployee();
|
||||
await signIn('新建的员工使用恢复操作提交的密码登录');
|
||||
await logout(ctx, employee, '新建的员工退出账号');
|
||||
await selectEmployee();
|
||||
// 页面已显示并选中账号后,店主停用;再次登录应由服务端拒绝。
|
||||
await setStatus('deactivate', '停用恢复登记的员工');
|
||||
await signIn('停用后使用原登录页面提交正确密码', 401);
|
||||
await setStatus('reactivate', '重新启用恢复登记的员工');
|
||||
await employee.reload();
|
||||
await selectEmployee();
|
||||
await signIn('恢复启用后用同一密码登录');
|
||||
await logout(ctx, employee, '恢复启用的员工退出账号');
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { ui } from './funds-ui.mjs';
|
||||
|
||||
export async function afterSales(context, { owner, assistant, yesterday }) {
|
||||
const { step, pageFor } = context;
|
||||
const { action, field, dialog, fill, navigate, write, submit } = ui(context);
|
||||
const update = /\/api\/after-sales\/[^/]+\/update$/;
|
||||
const reviewEndpoint = choice => new RegExp('/api/after-sales/changes/[^/]+/' + choice + '$');
|
||||
async function edit(page, customer) {
|
||||
await action(page.locator('#order-list tr').filter({ hasText: customer }), 'after-sale-edit').click();
|
||||
const form = page.locator('#after-sale-edit-form');
|
||||
await form.waitFor();
|
||||
return form;
|
||||
}
|
||||
async function list(page, name) {
|
||||
if (!(await action(page, 'after-sale-changes-open').isVisible()))
|
||||
await page.locator('.order-review-menu > summary').click();
|
||||
await action(page, 'after-sale-changes-open').click();
|
||||
await action(dialog(page).locator('tr').filter({ hasText: name }), 'after-sale-change-open').click();
|
||||
await dialog(page).locator('.after-sale-comparison').waitFor();
|
||||
}
|
||||
async function committedWithoutReceipt(page, name, url, form, checkSaved) {
|
||||
const sent = [];
|
||||
const loseReceipt = async route => {
|
||||
const request = route.request();
|
||||
sent.push({ key: request.headers()['idempotency-key'], body: request.postData() });
|
||||
// 第一次请求已经落库。后续自动确认也拿不到回执,直到用户恢复原操作。
|
||||
if (sent.length === 1) assert.equal((await route.fetch()).status(), 200);
|
||||
await route.abort('connectionreset');
|
||||
};
|
||||
await step(name + '已保存但回执中断', async () => {
|
||||
await page.route(url, loseReceipt);
|
||||
try {
|
||||
await submit(form);
|
||||
await action(dialog(page), 'retry').waitFor({ timeout: 20000 });
|
||||
assert.equal(sent.length, 3, '首次提交及两次自动确认');
|
||||
assert.ok(sent[0].key);
|
||||
assert.deepEqual(sent, [sent[0], sent[0], sent[0]]);
|
||||
} finally {
|
||||
await page.unroute(url, loseReceipt);
|
||||
}
|
||||
});
|
||||
const result = await write('同一操作号恢复' + name, page, url, () => action(dialog(page), 'retry').click(), {
|
||||
after: checkSaved,
|
||||
});
|
||||
assert.equal(result.request().headers()['idempotency-key'], sent[0].key);
|
||||
assert.equal(result.request().postData(), sent[0].body);
|
||||
}
|
||||
const otherAssistant = await pageFor('assistant', { fresh: true });
|
||||
const otherOwner = await pageFor('owner', { fresh: true });
|
||||
const names = ['独立售后已核对', '独立售后需驳回'];
|
||||
for (const [i, customer] of names.entries()) {
|
||||
await navigate(assistant, 'orders');
|
||||
await action(assistant, 'new-after-sale').click();
|
||||
const fresh = assistant.locator('#after-sale-form');
|
||||
await fill(fresh, { project: '维修费用', customer, amount: '8.50' });
|
||||
await field(fresh, 'payer').selectOption('assistant');
|
||||
await write('店员新增' + customer, assistant, '/api/after-sales', () => submit(fresh));
|
||||
let form = await edit(assistant, customer);
|
||||
if (i === 0) {
|
||||
await navigate(otherAssistant, 'orders');
|
||||
const second = await edit(otherAssistant, customer);
|
||||
await field(second, 'amount').fill('9.25');
|
||||
await write('另一窗口直接更正同日独立售后', otherAssistant, update, () => submit(second));
|
||||
await field(form, 'amount').fill('9.80');
|
||||
await write('店员冲突版本不能覆盖已修改金额', assistant, update, () => submit(form), { status: 409 });
|
||||
assert.equal(await field(form, 'amount').isDisabled(), true);
|
||||
assert.equal(await action(form, 'close-after-sale').isEnabled(), true);
|
||||
await action(dialog(assistant), 'after-sale-edit').click();
|
||||
form = assistant.locator('#after-sale-edit-form');
|
||||
await field(form, 'amount').waitFor();
|
||||
assert.equal(await field(form, 'amount').inputValue(), '9.25');
|
||||
}
|
||||
await fill(form, { date: yesterday, amount: '12.80', reason: '核对维修收据' });
|
||||
await form.getByRole('button', { name: '提交修改申请' }).waitFor();
|
||||
const pending = () => dialog(assistant).locator('.after-sale-pending').waitFor();
|
||||
if (i === 0) await committedWithoutReceipt(assistant, '店员跨日独立售后申请', update, form, pending);
|
||||
else await write('店员提交第二份跨日独立售后申请', assistant, update, () => submit(form), { after: pending });
|
||||
assert.equal(await dialog(assistant).locator('[data-action=after-sale-change-open]').count(), 0);
|
||||
await action(dialog(assistant), 'close-after-sale').click();
|
||||
}
|
||||
await list(assistant, names[0]);
|
||||
assert.equal(await dialog(assistant).locator('[data-action=after-sale-review-decision]').count(), 0);
|
||||
await action(dialog(assistant), 'after-sale-changes-close').click();
|
||||
await navigate(owner, 'orders');
|
||||
// 从原记录打开复核会先关闭编辑窗。关闭复核后回订单,返回列表则保留状态筛选。
|
||||
await action(owner.locator('#order-list tr').filter({ hasText: names[0] }), 'after-sale-edit').click();
|
||||
await action(dialog(owner), 'after-sale-change-open').click();
|
||||
await dialog(owner).locator('.after-sale-comparison').waitFor();
|
||||
await action(dialog(owner), 'after-sale-changes-close').click();
|
||||
assert.equal(await owner.locator('dialog[open]').count(), 0);
|
||||
for (const [i, customer] of names.entries()) {
|
||||
await list(owner, customer);
|
||||
await action(dialog(owner), 'after-sale-changes-reload').click();
|
||||
await action(dialog(owner).locator('tr').filter({ hasText: customer }), 'after-sale-change-open').click();
|
||||
const approval = dialog(owner).locator('[data-action=after-sale-review-decision][data-kind=approve]');
|
||||
await approval.click();
|
||||
await action(dialog(owner), 'after-sale-review-cancel').click();
|
||||
await approval.click();
|
||||
const form = owner.locator('#after-sale-review-form');
|
||||
assert.equal(await form.evaluate(f => f.checkValidity()), false);
|
||||
await fill(form, { note: '已核对维修收据' });
|
||||
await field(form, 'verified').check();
|
||||
if (i === 0) {
|
||||
await committedWithoutReceipt(owner, '店主同意独立售后修改', reviewEndpoint('approve'), form, () =>
|
||||
dialog(owner).getByRole('heading', { name: '售后修改记录' }).waitFor(),
|
||||
);
|
||||
} else {
|
||||
await navigate(otherOwner, 'orders');
|
||||
await list(otherOwner, customer);
|
||||
await dialog(otherOwner).locator('[data-kind=reject]').click();
|
||||
const reject = otherOwner.locator('#after-sale-review-form');
|
||||
assert.equal(await reject.evaluate(f => f.checkValidity()), false);
|
||||
await field(reject, 'note').fill(' ');
|
||||
await submit(reject);
|
||||
await dialog(otherOwner).getByText('请填写驳回意见。', { exact: false }).waitFor();
|
||||
await field(reject, 'note').fill('原始费用属实');
|
||||
await write('另一店主窗口驳回独立售后修改', otherOwner, reviewEndpoint('reject'), () => submit(reject));
|
||||
await write('旧窗口不能重复批准已驳回的独立售后', owner, reviewEndpoint('approve'), () => submit(form), {
|
||||
status: 409,
|
||||
});
|
||||
assert.equal(await field(form, 'verified').isChecked(), false);
|
||||
assert.equal(await field(form, 'verified').isDisabled(), true);
|
||||
await action(dialog(owner), 'after-sale-change-open').click();
|
||||
await dialog(owner).getByRole('heading', { name: '售后修改记录' }).waitFor();
|
||||
await dialog(owner).getByText('驳回意见:原始费用属实').waitFor();
|
||||
}
|
||||
await action(dialog(owner), 'after-sale-changes-close').click();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import legacyPools from './funds-legacy-pools.mjs';
|
||||
import assert from 'node:assert/strict';
|
||||
import { material } from './funds-material.mjs';
|
||||
import { locks } from './funds-locks.mjs';
|
||||
import { afterSales } from './funds-after-sales.mjs';
|
||||
export async function seedFunds({ day, session }) {
|
||||
const yesterday = new Date(Date.parse(day + 'T12:00:00Z') - 86400000).toISOString().slice(0, 10);
|
||||
await session.post('owner', '/api/stock', {
|
||||
date: yesterday,
|
||||
kind: 'opening',
|
||||
pocket: '现货',
|
||||
grams: '100',
|
||||
note: '锁价交付期初库存',
|
||||
});
|
||||
await session.post('assistant', '/api/orders/issue', {
|
||||
date: day,
|
||||
customer: '店主代收经营款的夹具',
|
||||
customer_type: 'new',
|
||||
salesperson: '娜娜',
|
||||
internal_note: '代收款凭据',
|
||||
member: 'assistant',
|
||||
payment_account: '麦麦微信',
|
||||
rounding_mode: 'cent',
|
||||
lines: [
|
||||
{
|
||||
name: '足金999',
|
||||
unit: 'g',
|
||||
quantity: '1',
|
||||
pocket: '现货',
|
||||
payer: 'assistant',
|
||||
sale: '1000',
|
||||
costParts: { material: '800', labor: '50', accessories: '0', other: '0' },
|
||||
costPayers: { material: 'assistant', labor: 'assistant' },
|
||||
},
|
||||
],
|
||||
fee_items: [],
|
||||
});
|
||||
assert.deepEqual(session.problems, []);
|
||||
return yesterday;
|
||||
}
|
||||
|
||||
export default async function fundsCore(context) {
|
||||
const { pageFor } = context;
|
||||
const yesterday = await seedFunds(context);
|
||||
const participants = { owner: await pageFor('owner'), assistant: await pageFor('assistant'), yesterday };
|
||||
await legacyPools(context);
|
||||
const preview = await material(context, participants);
|
||||
const quotes = await locks(context, participants);
|
||||
await afterSales(context, participants);
|
||||
return { ...preview, ...quotes };
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createRequire } from 'node:module';
|
||||
import path from 'node:path';
|
||||
import { ui } from './funds-ui.mjs';
|
||||
|
||||
function seedLegacyPurchases(appPath, dbPath, dates) {
|
||||
// 使用与旧购料账本测试相同的双人 Ledger 入口,真实生成结算、耗料和分摊记录。
|
||||
const { Ledger } = createRequire(import.meta.url)(path.join(appPath, 'core/ledger.js'));
|
||||
const ledger = new Ledger(dbPath);
|
||||
const actor = { id: 'legacy-assistant-funds', role: 'assistant', name: '库存交接员' };
|
||||
try {
|
||||
for (const [index, date] of dates.entries()) {
|
||||
const run = (kind, input, save) => ledger.transact('funds-legacy-' + date + '-' + kind, actor, input, save);
|
||||
const buy = { date, grams: '10', total: '9000', payer: 'assistant', note: '双人旧账采购凭据' };
|
||||
run('buy', buy, () => ledger.createMaterialPurchase(buy, actor));
|
||||
if (index === 0) continue;
|
||||
const pay = {
|
||||
date,
|
||||
amount: '9000',
|
||||
direction: 'toAssistant',
|
||||
verified: true,
|
||||
note: '双人账先结清整批',
|
||||
revision: ledger.materialPoolDetail(date).revision,
|
||||
};
|
||||
run('settle', pay, () => ledger.settleMaterialPool(date, pay, actor));
|
||||
const sale = {
|
||||
date,
|
||||
customer: '双人旧账后续耗料',
|
||||
internal_note: '原单凭据',
|
||||
salesperson: '库存交接员',
|
||||
discount: '0',
|
||||
payment_account: '助理微信',
|
||||
fee_items: [],
|
||||
lines: [
|
||||
{
|
||||
name: '足金999',
|
||||
unit: 'g',
|
||||
quantity: '3',
|
||||
pocket: '',
|
||||
payer: 'owner',
|
||||
pricingMode: 'manual',
|
||||
sale: '3000',
|
||||
costParts: { material: '0', labor: '0', accessories: '0', other: '0' },
|
||||
costMaterial: { mode: 'pool', poolId: date },
|
||||
},
|
||||
],
|
||||
};
|
||||
run('sale', sale, () => ledger.issueOrder(sale, actor));
|
||||
}
|
||||
} finally {
|
||||
ledger.close();
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] === fileURLToPath(import.meta.url) && process.argv[2] === '--seed-legacy-pools') {
|
||||
seedLegacyPurchases(process.argv[3], process.argv[4], process.argv.slice(5));
|
||||
}
|
||||
|
||||
export default async function legacyPools(context) {
|
||||
const { session, day, dbPath, appPath } = context;
|
||||
const dates = [4, 3].map(offset =>
|
||||
new Date(Date.parse(day + 'T02:00:00Z') - offset * 86400000).toISOString().slice(0, 10),
|
||||
);
|
||||
assert.ok(dbPath, '需要当前对照组的临时 SQLite 路径以准备双人时代的购料记录');
|
||||
execFileSync(
|
||||
process.execPath,
|
||||
[
|
||||
'--disable-warning=ExperimentalWarning',
|
||||
'--require',
|
||||
path.join(appPath, 'e2e/fake-clock.cjs'),
|
||||
fileURLToPath(import.meta.url),
|
||||
'--seed-legacy-pools',
|
||||
appPath,
|
||||
dbPath,
|
||||
...dates,
|
||||
],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
TZ: 'Asia/Shanghai',
|
||||
FAKE_CLOCK_START: day + 'T02:00:00Z',
|
||||
FAKE_RANDOM_SEED: 'old-two-person-pool-fixture',
|
||||
FAKE_CLOCK_TICK_MS: '0',
|
||||
},
|
||||
},
|
||||
);
|
||||
const owner = await context.pageFor('owner');
|
||||
const { navigate, write } = ui(context);
|
||||
const user = (await session.get('owner', '/api/state')).user.id;
|
||||
for (const [index, date] of dates.entries()) {
|
||||
const url = '/api/material-pools/' + date;
|
||||
const detail = await session.get('owner', url);
|
||||
const due = index === 0 ? -900000 : 270000;
|
||||
assert.equal(detail.settlement.settlementDue, due);
|
||||
const direction = due < 0 ? 'toAssistant' : 'toOwner';
|
||||
const job = {
|
||||
url: url + '/settlement',
|
||||
userId: user,
|
||||
key: 'funds-legacy-pool-settle-' + date,
|
||||
data: {
|
||||
date: day,
|
||||
amount: (Math.abs(due) / 100).toFixed(2),
|
||||
direction,
|
||||
note: '旧批次结算原操作',
|
||||
verified: true,
|
||||
revision: detail.revision,
|
||||
},
|
||||
};
|
||||
await owner.evaluate(job => localStorage.setItem('mm-pending-' + job.userId, JSON.stringify(job)), job);
|
||||
await owner.reload();
|
||||
await navigate(owner, 'material-pools');
|
||||
const response = await write(
|
||||
'恢复双人旧购料' + (index === 0 ? '返还店员垫付款' : '耗料后向店主交款'),
|
||||
owner,
|
||||
job.url,
|
||||
() => owner.getByRole('button', { name: '恢复原操作', exact: true }).click(),
|
||||
);
|
||||
assert.equal(response.request().headers()['idempotency-key'], job.key);
|
||||
assert.deepEqual(response.request().postDataJSON(), job.data);
|
||||
const after = await session.get('owner', url);
|
||||
assert.equal(after.settlement.settlementDue, 0);
|
||||
assert.equal(after.settlements.length, detail.settlements.length + 1);
|
||||
assert.equal(after.settlements.at(-1).amount, due);
|
||||
assert.equal(await owner.evaluate(key => localStorage.getItem(key), 'mm-pending-' + user), null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { ui } from './funds-ui.mjs';
|
||||
|
||||
export async function locks(context, { owner, assistant, yesterday }) {
|
||||
const { action, field, fill, navigate, write, submit } = ui(context);
|
||||
const quotes = {};
|
||||
async function selectPool(page, control, label, match) {
|
||||
await context.step('锁价' + label, async () => {
|
||||
const [response] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
r => r.url().endsWith('/api/material-pools/quote') && match(r.request().postDataJSON().entries),
|
||||
),
|
||||
control.selectOption('pool'),
|
||||
]);
|
||||
assert.equal(response.status(), 200);
|
||||
const input = response.request().postDataJSON(),
|
||||
result = await response.json();
|
||||
assert.equal(result.entries.length, input.entries.length);
|
||||
quotes[label] = { input, result };
|
||||
});
|
||||
}
|
||||
const endpoint = tail => new RegExp('/price-locks/[^/]+/' + tail + '$');
|
||||
const lockAction = async (page, customer, name) => {
|
||||
await navigate(page, 'price-locks');
|
||||
await action(page.locator('.price-lock-list tr').filter({ hasText: customer }), name).click();
|
||||
};
|
||||
async function sale(page, name, date, multiple, pool) {
|
||||
await navigate(page, 'price-locks');
|
||||
await action(page, 'new-price-lock').click();
|
||||
const form = page.locator('#price-lock-create-form');
|
||||
await fill(form, { customer: name, date });
|
||||
if (multiple) await action(page, 'add-lock-line').click();
|
||||
const rows = multiple ? await form.locator('[data-price-lock-sale]').all() : [form];
|
||||
for (const [index, row] of rows.entries()) {
|
||||
await fill(row, {
|
||||
name: index ? '足金手链' : '足金999',
|
||||
quantity: index ? '3' : '2',
|
||||
goldPrice: '900',
|
||||
laborRate: '10',
|
||||
});
|
||||
if (pool && index === 1) {
|
||||
await selectPool(
|
||||
page,
|
||||
field(row, 'material_source'),
|
||||
'多行预留试算',
|
||||
entries => entries.length === 2 && entries[0].mg === 2000 && entries[1].mg === 3000,
|
||||
);
|
||||
} else if (pool)
|
||||
await selectPool(
|
||||
page,
|
||||
field(row, 'material_source'),
|
||||
'第一件个人料与公共料预留试算',
|
||||
entries => entries.length === 1 && entries[0].mg === 2000,
|
||||
);
|
||||
else {
|
||||
await field(row, 'material_rate').fill('850');
|
||||
await field(row, 'material_verified').check();
|
||||
}
|
||||
}
|
||||
await field(form, 'received_amount').fill(multiple ? '2500' : '500');
|
||||
await field(form, 'payment_verified').check();
|
||||
await page.waitForLoadState('networkidle');
|
||||
await write('创建' + name, page, '/api/price-locks', () => submit(form));
|
||||
await action(page, 'close-price-lock').click();
|
||||
}
|
||||
async function deliver(name, page, form) {
|
||||
const original = await form.getAttribute('data-id');
|
||||
const details = page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'GET' && /^\/api\/orders\/[^/]+$/.test(new URL(response.url()).pathname),
|
||||
);
|
||||
const [saved, read] = await Promise.all([
|
||||
write(name, page, endpoint('deliver'), () => submit(form), {
|
||||
after: () => page.locator('#order-dialog[open]').waitFor(),
|
||||
}),
|
||||
details,
|
||||
]);
|
||||
const result = await saved.json(),
|
||||
order = await read.json();
|
||||
assert.equal(order.id, result.id);
|
||||
assert.equal(order.price_lock_id, original, '交付后打开的销售单必须关联本次原锁价单');
|
||||
}
|
||||
for (const pool of [false, true]) {
|
||||
if (pool) {
|
||||
// 加入真实个人回收料,触发锁价时按归属查询个人料优先、公料补足的业务报价。
|
||||
await context.session.post('owner', '/api/recoveries', {
|
||||
date: context.day,
|
||||
mode: 'direct',
|
||||
customer: '锁价自有回收料',
|
||||
member: 'owner',
|
||||
salesperson: '麦麦',
|
||||
old_lines: [{ name: '旧料', incoming_weight: '0.400', melted_weight: '0.400', purity: '100' }],
|
||||
buy_rate: '800',
|
||||
payer: 'owner',
|
||||
payment_account: '麦麦微信',
|
||||
verified: true,
|
||||
});
|
||||
assert.deepEqual(context.session.problems, []);
|
||||
await navigate(owner, 'material-pools');
|
||||
await owner.reload();
|
||||
}
|
||||
const name = pool ? '料池多件锁价' : '手工多件锁价';
|
||||
await sale(owner, name, context.day, true, pool);
|
||||
let customer = name;
|
||||
if (!pool) {
|
||||
await lockAction(owner, name, 'edit-price-lock');
|
||||
const form = owner.locator('#price-lock-create-form');
|
||||
customer = name + '已修改';
|
||||
await fill(form, { customer, pending_edit_reason: '修订客户称呼' });
|
||||
await field(form, 'pending_edit_verified').check();
|
||||
await write('直接更正整笔多件锁价', owner, endpoint('edit'), () => submit(form));
|
||||
}
|
||||
await lockAction(owner, customer, 'deliver-price-lock');
|
||||
const form = owner.locator('#price-lock-delivery-form');
|
||||
await form.locator('[name=customer_type][value=new]').check();
|
||||
const rows = await form.locator('[data-price-lock-delivery-item]').all();
|
||||
assert.equal(rows.length, 2);
|
||||
for (const [index, row] of rows.entries()) {
|
||||
await fill(row, { quantity: index ? '3.300' : '1.900', 'cost-labor': '25.50' });
|
||||
await field(row, 'pocket').selectOption('现货');
|
||||
if (!pool) await field(row, 'original_stock').selectOption('stocked');
|
||||
if (!index) continue;
|
||||
if (pool) {
|
||||
await selectPool(
|
||||
owner,
|
||||
field(row, 'extra_source'),
|
||||
'交付补重试算',
|
||||
entries => entries.length === 1 && entries[0].lineIndex === 1 && entries[0].mg === 300,
|
||||
);
|
||||
await row.locator('[data-lock-part="extra-material"] .note:visible').filter({ hasText: '¥' }).waitFor();
|
||||
} else {
|
||||
await field(row, 'extra_rate').fill('860');
|
||||
await field(row, 'extra_payer').selectOption('owner');
|
||||
await field(row, 'extra_stock').selectOption('receive');
|
||||
await field(row, 'extra_verified').check();
|
||||
}
|
||||
}
|
||||
await field(form, 'settlement_verified').check();
|
||||
await field(form, 'delivery_verified').check();
|
||||
await deliver(name + '交付,一件退料一件补料', owner, form);
|
||||
}
|
||||
await sale(assistant, '单件足重锁价', context.day, false, false);
|
||||
await lockAction(assistant, '单件足重锁价', 'deliver-price-lock');
|
||||
const single = assistant.locator('#price-lock-delivery-form');
|
||||
await single.locator('[name=customer_type][value=new]').check();
|
||||
await fill(single, { quantity: '2.000', 'cost-labor': '12.30' });
|
||||
await field(single, 'pocket').selectOption('现货');
|
||||
await field(single, 'original_stock').selectOption('receive');
|
||||
await field(single, 'settlement_verified').check();
|
||||
await field(single, 'delivery_verified').check();
|
||||
await deliver('足重单行锁价按原料成本交付入库并打开销售单', assistant, single);
|
||||
await sale(owner, '当天作废锁价', context.day, false, false);
|
||||
await lockAction(owner, '当天作废锁价', 'cancel-price-lock');
|
||||
const cancel = owner.locator('#price-lock-cancel-form');
|
||||
await fill(cancel, { reason: '当天录错' });
|
||||
await field(cancel, 'verified').check();
|
||||
await write('直接作废当天锁价', owner, endpoint('cancel'), () => submit(cancel));
|
||||
for (const [kind, result] of [
|
||||
['edit', 'approve'],
|
||||
['cancel', 'reject'],
|
||||
['cancel', 'approve'],
|
||||
]) {
|
||||
const verb = kind === 'edit' ? '修改' : '作废';
|
||||
const decision = result === 'approve' ? '同意' : '驳回';
|
||||
const name = '历史锁价' + verb + decision;
|
||||
await sale(assistant, name, yesterday, false, false);
|
||||
await lockAction(assistant, name, kind + '-price-lock');
|
||||
const form = assistant.locator(kind === 'edit' ? '#price-lock-create-form' : '#price-lock-cancel-form');
|
||||
if (kind === 'edit') await fill(form, { customer: name + '改名', pending_edit_reason: '纸单客户名更正' });
|
||||
else await fill(form, { reason: '原始凭据核对' });
|
||||
await field(form, kind === 'edit' ? 'pending_edit_verified' : 'verified').check();
|
||||
await write('店员申请' + verb + '历史锁价,待' + decision, assistant, endpoint('change-requests'), () =>
|
||||
submit(form),
|
||||
);
|
||||
await owner.reload();
|
||||
await navigate(owner, 'price-locks');
|
||||
await action(owner, 'price-lock-changes-open').click();
|
||||
await action(
|
||||
owner.locator('.price-lock-change-list tr').filter({ hasText: name }),
|
||||
'price-lock-change-open',
|
||||
).click();
|
||||
const review = owner.locator('#price-lock-review-form');
|
||||
if (result === 'approve') await field(review, 'verified').check();
|
||||
await fill(review, { review_note: result === 'approve' ? '凭据相符' : '原单保持' });
|
||||
await write(
|
||||
'店主' + decision + '历史锁价' + verb,
|
||||
owner,
|
||||
new RegExp('/price-lock-changes/[^/]+/' + result + '$'),
|
||||
() => review.locator('button[value="' + result + '"]').click(),
|
||||
);
|
||||
}
|
||||
return { 料池报价: quotes };
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { ui } from './funds-ui.mjs';
|
||||
|
||||
export async function material(context, { owner, assistant, yesterday }) {
|
||||
const { day } = context;
|
||||
const { action, field, fill, navigate, write, submit } = ui(context);
|
||||
async function buy(page, label, date, grams, total, note) {
|
||||
await navigate(page, 'material-pools');
|
||||
const form = page.locator('#material-purchase-form');
|
||||
await fill(form, { date, grams, total, note });
|
||||
await write(label, page, '/api/material-purchases', () => submit(form));
|
||||
await page.locator('.material-purchase-table').getByText(note, { exact: true }).waitFor();
|
||||
}
|
||||
async function openPurchase(page, date, note, actionName) {
|
||||
const toggle = page.locator('[data-action="toggle-material-pool"][data-id="' + date + '"]');
|
||||
if ((await toggle.getAttribute('aria-expanded')) !== 'true') await toggle.click();
|
||||
const row = page.locator('.material-purchase-table tr').filter({ hasText: note });
|
||||
await action(row, actionName).click();
|
||||
}
|
||||
await buy(assistant, '店员登记前日购料', yesterday, '8.125', '6906.25', '前日原始凭据');
|
||||
await buy(owner, '店主登记当日购料', day, '10', '8500.00', '本日采购');
|
||||
await buy(owner, '店主登记待更正购料', day, '1', '800', '待更正采购');
|
||||
await openPurchase(owner, day, '待更正采购', 'edit-material-purchase');
|
||||
const edit = owner.locator('#material-purchase-edit-form');
|
||||
await fill(edit, { grams: '1.250', total: '1023.40', note: '当天凭据更正' });
|
||||
await write('当天直接更正购料', owner, /\/material-purchases\/[^/]+\/edit$/, () => submit(edit));
|
||||
await openPurchase(owner, day, '当天凭据更正', 'delete-material-purchase');
|
||||
await write('当天直接删除购料', owner, /\/material-purchases\/[^/]+\/delete$/, () =>
|
||||
submit(owner.locator('#material-purchase-delete-form')),
|
||||
);
|
||||
const rolling = owner.locator('#material-rolling-enable-form');
|
||||
const preview = await context.step('店主只读预览材料结转与关联订单影响', async () => {
|
||||
const [response] = await Promise.all([
|
||||
owner.waitForResponse(
|
||||
r => r.request().method() === 'GET' && r.url().endsWith('/api/material-pools/rolling-preview'),
|
||||
),
|
||||
action(owner, 'material-rolling-enable-preview').click(),
|
||||
]);
|
||||
assert.equal(response.status(), 200);
|
||||
const data = await response.json();
|
||||
assert.equal(data.canEnable, true);
|
||||
assert.ok(Array.isArray(data.relatedOrders));
|
||||
await rolling.waitFor();
|
||||
return data;
|
||||
});
|
||||
await field(rolling, 'verified').check();
|
||||
await write('店主核对并启用跨日材料结转', owner, '/api/material-pools/rolling-enable', () => submit(rolling));
|
||||
for (const [operation, reviewKind] of [
|
||||
['edit', 'approve'],
|
||||
['delete', 'reject'],
|
||||
]) {
|
||||
await assistant.reload();
|
||||
await navigate(assistant, 'material-pools');
|
||||
await openPurchase(assistant, yesterday, '前日原始凭据', operation + '-material-purchase');
|
||||
const form = assistant.locator('#material-purchase-' + operation + '-form');
|
||||
if (operation === 'edit') await field(form, 'total').fill('6950.50');
|
||||
await fill(form, { change_reason: '按原始付款凭据核对' });
|
||||
await field(form, 'change_verified').check();
|
||||
const verb = operation === 'edit' ? '更正' : '删除';
|
||||
await write('店员申请' + verb + '历史购料', assistant, /\/material-purchases\/[^/]+\/change$/, () => submit(form));
|
||||
await owner.reload();
|
||||
await navigate(owner, 'material-pools');
|
||||
await action(owner, 'material-change-open').click();
|
||||
const review = owner.locator('#material-change-review-form');
|
||||
await fill(review, { note: reviewKind === 'approve' ? '付款凭据相符' : '原料确已购入' });
|
||||
if (reviewKind === 'approve') await field(review, 'verified').check();
|
||||
await write(
|
||||
'店主' + (reviewKind === 'approve' ? '批准' : '驳回') + verb + '购料申请',
|
||||
owner,
|
||||
new RegExp('/material-purchase-changes/[^/]+/' + reviewKind + '$'),
|
||||
() => (reviewKind === 'approve' ? submit(review) : action(review, 'material-change-reject').click()),
|
||||
);
|
||||
}
|
||||
await navigate(owner, 'material-pools');
|
||||
const toggle = owner.locator('[data-action="toggle-material-pool"][data-id="' + day + '"]');
|
||||
if ((await toggle.getAttribute('aria-expanded')) !== 'true') await toggle.click();
|
||||
// 三成员账本的网页仅显示旧式料款结算历史,不能新登记两人料款结算。
|
||||
assert.equal(await owner.getByRole('button', { name: '登记实际交款/返款' }).count(), 0);
|
||||
return { 材料结转预览: preview };
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { seedFunds } from './funds-core.mjs';
|
||||
import { ui } from './funds-ui.mjs';
|
||||
|
||||
async function recoverTeamTransfer(context, owner, path) {
|
||||
const plural = path === 'transfers',
|
||||
variant = plural ? '复数地址' : '单数旧地址';
|
||||
const { session, day } = context;
|
||||
const { navigate, write } = ui(context);
|
||||
await navigate(owner, 'team-funds');
|
||||
assert.equal(await owner.getByRole('button', { name: '登记实际转账' }).count(), 0);
|
||||
// 该页现只显示团队月度利润。模拟老用户留在 localStorage 里的原操作。
|
||||
const report = await session.get('owner', '/api/team-funds?date=' + day);
|
||||
const pair = report.pairs.find(row => row.due > 0);
|
||||
assert.ok(pair, '历史转账恢复需要真实待转金额');
|
||||
const state = await session.get('owner', '/api/state');
|
||||
const user = state.user.id;
|
||||
const job = {
|
||||
url: '/api/team-funds/' + path,
|
||||
key: 'funds-legacy-replay-' + path,
|
||||
userId: user,
|
||||
data: {
|
||||
date: day,
|
||||
fromMember: pair.fromMember,
|
||||
toMember: pair.toMember,
|
||||
amount: (Math.min(100, pair.due) / 100).toFixed(2),
|
||||
revision: report.revision,
|
||||
verified: true,
|
||||
note: '旧操作转账凭据',
|
||||
},
|
||||
};
|
||||
await owner.evaluate(({ job, user }) => localStorage.setItem('mm-pending-' + user, JSON.stringify(job)), {
|
||||
job,
|
||||
user,
|
||||
});
|
||||
await owner.reload();
|
||||
await navigate(owner, 'orders');
|
||||
const retry = owner.getByRole('button', { name: '恢复原操作', exact: true });
|
||||
await context.step(variant + '历史转账已记账但未收到回执', async () => {
|
||||
let attempts = 0;
|
||||
const disconnected = Promise.withResolvers();
|
||||
const drop = async route => {
|
||||
const request = route.request();
|
||||
assert.equal(request.headers()['idempotency-key'], job.key);
|
||||
assert.deepEqual(request.postDataJSON(), job.data);
|
||||
if (++attempts === 1) {
|
||||
const committed = await route.fetch();
|
||||
assert.equal(committed.status(), 200);
|
||||
await committed.dispose();
|
||||
}
|
||||
await route.abort('connectionreset');
|
||||
if (attempts === 3) disconnected.resolve();
|
||||
};
|
||||
await owner.route('**' + job.url, drop);
|
||||
try {
|
||||
await retry.click();
|
||||
await Promise.race([
|
||||
disconnected.promise,
|
||||
owner.waitForTimeout(20000).then(() => {
|
||||
throw new Error('未观察到历史转账的三次原操作确认');
|
||||
}),
|
||||
]);
|
||||
await owner.waitForLoadState('networkidle');
|
||||
assert.deepEqual(await owner.evaluate(user => JSON.parse(localStorage.getItem('mm-pending-' + user)), user), job);
|
||||
} finally {
|
||||
await owner.unroute('**' + job.url, drop);
|
||||
}
|
||||
});
|
||||
const saved = await session.get('owner', '/api/team-funds?date=' + day);
|
||||
assert.equal(saved.transfers.length, report.transfers.length + 1);
|
||||
const reads = [];
|
||||
const observe = response => {
|
||||
if (response.request().method() === 'GET')
|
||||
reads.push({ path: new URL(response.url()).pathname, status: response.status() });
|
||||
};
|
||||
owner.on('response', observe);
|
||||
const response = await write('从订单页恢复' + variant + '历史团队实际转账', owner, job.url, () =>
|
||||
owner.getByRole('button', { name: '恢复原操作', exact: true }).click(),
|
||||
);
|
||||
assert.equal(response.request().headers()['idempotency-key'], job.key);
|
||||
assert.deepEqual(response.request().postDataJSON(), job.data);
|
||||
assert.equal(await owner.evaluate(user => localStorage.getItem('mm-pending-' + user), user), null);
|
||||
// 等待恢复回调完成。复数地址会再刷新账目,旧单数地址还会尝试读取订单。
|
||||
const toast = owner
|
||||
.locator('#toast:visible,.ant-message-notice-content:visible')
|
||||
.filter({
|
||||
hasText: /^(订单不存在|实际转账已保存,待转金额已重新核对|原操作已确认)$/,
|
||||
})
|
||||
.last();
|
||||
await toast.waitFor();
|
||||
const finalToast = await toast.innerText();
|
||||
owner.off('response', observe);
|
||||
const { id } = await response.json();
|
||||
const transferAsOrder = '/api/orders/' + id;
|
||||
const orderReads = reads
|
||||
.filter(row => row.path === transferAsOrder || row.path.startsWith(transferAsOrder + '/'))
|
||||
.map(row => [row.path.slice(transferAsOrder.length) || '/', row.status])
|
||||
.sort();
|
||||
const feedback = {
|
||||
heading: await owner.locator('h1:visible').last().innerText(),
|
||||
toast: finalToast,
|
||||
orderReads,
|
||||
};
|
||||
const recovered = await session.get('owner', '/api/team-funds?date=' + day);
|
||||
assert.deepEqual(recovered.transfers, saved.transfers, '同一操作号不得重复入账');
|
||||
return feedback;
|
||||
}
|
||||
|
||||
export async function teamTransfers(context, owner) {
|
||||
const feedback = {};
|
||||
for (const path of ['transfer', 'transfers']) feedback[path] = await recoverTeamTransfer(context, owner, path);
|
||||
if (context.version === 'old')
|
||||
assert.deepEqual(
|
||||
feedback,
|
||||
{
|
||||
transfer: {
|
||||
heading: '订单',
|
||||
toast: '订单不存在',
|
||||
orderReads: [
|
||||
['/', 404],
|
||||
['/cancellation', 404],
|
||||
['/change', 404],
|
||||
['/ownership', 404],
|
||||
],
|
||||
},
|
||||
transfers: { heading: '团队账目', toast: '实际转账已保存,待转金额已重新核对', orderReads: [] },
|
||||
},
|
||||
'历史团队转账两个兼容地址的恢复反馈',
|
||||
);
|
||||
return { 历史团队转账反馈: feedback };
|
||||
}
|
||||
|
||||
export default async function transferOnly(context) {
|
||||
await seedFunds(context);
|
||||
return teamTransfers(context, await context.pageFor('owner'));
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
export function ui({ version, step }) {
|
||||
const action = (scope, name) => scope.locator('[data-action="' + name + '"]:visible').first();
|
||||
const field = (scope, name) => scope.locator('[name="' + name + '"]');
|
||||
const dialog = page => page.locator('dialog[open]').last();
|
||||
async function fill(scope, values) {
|
||||
for (const [key, value] of Object.entries(values)) await field(scope, key).fill(value);
|
||||
}
|
||||
async function navigate(page, section) {
|
||||
while (await page.locator('dialog[open]').count()) await page.keyboard.press('Escape');
|
||||
const link = version === 'old' ? '[data-tab="' + section + '"]' : 'a[href="/next/' + section + '"]';
|
||||
await page.locator('nav:visible').locator(link).first().click();
|
||||
await page.waitForLoadState('networkidle');
|
||||
}
|
||||
async function write(name, page, endpoint, click, { status = 200, after } = {}) {
|
||||
let response;
|
||||
await step(name, async () => {
|
||||
const waiting = page.waitForResponse(r => {
|
||||
const url = new URL(r.url()).pathname;
|
||||
return (
|
||||
r.request().method() === 'POST' && (typeof endpoint === 'string' ? url === endpoint : endpoint.test(url))
|
||||
);
|
||||
});
|
||||
[response] = await Promise.all([waiting, click()]);
|
||||
assert.equal(response.status(), status, name + ' ' + (await response.text()));
|
||||
assert.ok(response.request().headers()['idempotency-key'], name + ' 缺少原操作号');
|
||||
if (after) await after();
|
||||
await page.waitForLoadState('networkidle');
|
||||
});
|
||||
return response;
|
||||
}
|
||||
const submit = form => form.locator('button[type="submit"]').click();
|
||||
return { action, field, dialog, fill, navigate, write, submit };
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import fundsCore from './funds-core.mjs';
|
||||
import { teamTransfers } from './funds-transfer.mjs';
|
||||
|
||||
export default async function funds(context) {
|
||||
const core = await fundsCore(context);
|
||||
const transfers = await teamTransfers(context, await context.pageFor('owner'));
|
||||
return { ...core, ...transfers };
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { write } from './ui.mjs';
|
||||
export default async function history(ctx) {
|
||||
const { session, day } = ctx,
|
||||
owner = await ctx.pageFor('owner');
|
||||
const { user } = await session.get('owner', '/api/state');
|
||||
const daily = await session.get('owner', '/api/daily-funds?date=' + day);
|
||||
const cases = [
|
||||
['旧人数登记', '/api/people-count', { date: day, count: 12, assistant1Count: 5, assistant2Count: 3, revision: 0 }],
|
||||
[
|
||||
'历史服务端销售草稿',
|
||||
'/api/orders',
|
||||
{
|
||||
date: day,
|
||||
customer: '历史草稿',
|
||||
internal_note: '临时账本',
|
||||
salesperson: '麦麦',
|
||||
payment_account: '麦麦现金',
|
||||
lines: [
|
||||
{ name: '足金手镯', unit: 'g', quantity: '1', pocket: '现货', payer: 'owner', sale: '980', cost: '900' },
|
||||
],
|
||||
fee_items: [],
|
||||
},
|
||||
],
|
||||
[
|
||||
'旧完整对外支出确认',
|
||||
'/api/daily-funds/confirm',
|
||||
{
|
||||
date: day,
|
||||
amount: '27.30',
|
||||
revision: daily.confirmation?.revision ?? 0,
|
||||
sourceRevision: daily.sources.revision,
|
||||
verified: true,
|
||||
},
|
||||
],
|
||||
];
|
||||
for (const [i, [label, url, data]] of cases.entries()) {
|
||||
const job = { url, data, userId: user.id, key: 'legacy-browser-parity-' + i };
|
||||
await owner.evaluate(job => localStorage.setItem('mm-pending-' + job.userId, JSON.stringify(job)), job);
|
||||
await owner.goto(ctx.base + (ctx.version === 'old' ? '/' : '/next/orders'));
|
||||
const button = owner.getByRole('button', { name: '恢复原操作', exact: true }).first();
|
||||
const result = await write(
|
||||
ctx,
|
||||
owner,
|
||||
'历史待确认操作 ' + label,
|
||||
url,
|
||||
() => button.click(),
|
||||
url === '/api/daily-funds/confirm' ? 409 : 200,
|
||||
);
|
||||
if (url === '/api/daily-funds/confirm') {
|
||||
assert.match(result.error, /三人经营款按成员往来核对/);
|
||||
continue;
|
||||
}
|
||||
assert.ok(result);
|
||||
assert.equal(await owner.evaluate(id => localStorage.getItem('mm-pending-' + id), user.id), null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { exerciseIssuePoolDate as default } from './issue.mjs';
|
||||
@@ -0,0 +1 @@
|
||||
export { exerciseIssueReopen as default } from './issue.mjs';
|
||||
@@ -0,0 +1,349 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { newUi, oldUi } from '../parity-create-order.mjs';
|
||||
|
||||
async function seedReturnedLot(session, day) {
|
||||
const post = async (path, params) => {
|
||||
const result = await session.postRaw('owner', path, params);
|
||||
assert.equal(result.status, 200, path + ' ' + JSON.stringify(result.body));
|
||||
return result.body;
|
||||
};
|
||||
await post('/api/stock', { date: day, kind: 'opening', pocket: '现货', grams: '60', note: '真实开单对照库存' });
|
||||
|
||||
// 真实售后生成完好现货批次,取消选择应恢复普通开单输入,实际再售应继承原工费与付款人。
|
||||
const sale = await post('/api/orders/issue', {
|
||||
date: day,
|
||||
customer: '供退回现货的原单',
|
||||
member: 'owner',
|
||||
customer_type: 'new',
|
||||
salesperson: '麦麦',
|
||||
internal_note: '退回现货对照',
|
||||
payment_account: '麦麦微信',
|
||||
rounding_mode: 'cent',
|
||||
fee_items: [],
|
||||
lines: [
|
||||
{
|
||||
name: '足金999',
|
||||
code: 'A031',
|
||||
unit: 'g',
|
||||
quantity: '2',
|
||||
pocket: '现货',
|
||||
payer: 'owner',
|
||||
sale: '1420',
|
||||
costParts: { material: '1200', labor: '50', accessories: '0', other: '0' },
|
||||
costPayers: { material: 'owner', labor: 'assistant' },
|
||||
},
|
||||
],
|
||||
});
|
||||
const original = await session.get('owner', '/api/orders/' + sale.id);
|
||||
await post('/api/orders/' + sale.id + '/return', {
|
||||
date: day,
|
||||
revision: original.revision,
|
||||
reason: '按实物退回整件',
|
||||
verified: true,
|
||||
afterSale: {
|
||||
lines: [{ lineIndex: 0, quantity: '2', pocket: '现货', disposition: 'stock' }],
|
||||
refund: { account: '麦麦微信', payer: 'owner', amount: '1420', reference: '' },
|
||||
deductionReason: '',
|
||||
expenses: [],
|
||||
},
|
||||
});
|
||||
const lots = () => session.get('owner', '/api/returned-stock-lots?member=owner&date=' + day);
|
||||
const lot = (await lots()).lots[0];
|
||||
assert.ok(lot?.id);
|
||||
assert.equal(lot.laborCost, 5000);
|
||||
return { lot, lots };
|
||||
}
|
||||
|
||||
export default async function issue({ version, base, day, pageFor, session, step }) {
|
||||
const ui = version === 'old' ? oldUi : newUi;
|
||||
const page = await pageFor('owner');
|
||||
const line = () => ui.line(page, 0);
|
||||
const control = name =>
|
||||
line()
|
||||
.locator(version === 'old' ? '[name="' + name + '"]' : '[data-field="' + name + '"] input')
|
||||
.first();
|
||||
const selectLot = () => line().locator('[name=returnedStockId]');
|
||||
const clickSubmit = () =>
|
||||
page.locator(version === 'old' ? '#order-form button[type=submit]' : 'button[data-action=issue]').click();
|
||||
const isIssue = r => r.method() === 'POST' && new URL(r.url()).pathname === '/api/orders/issue';
|
||||
async function steps(items) {
|
||||
for (const item of items) await ui.step(page, item);
|
||||
}
|
||||
let issued = false;
|
||||
async function start(customer) {
|
||||
if (issued) {
|
||||
if (version === 'new') {
|
||||
await page.locator('[data-action=new-order]').click();
|
||||
} else {
|
||||
await page.locator('#order-dialog[open] [data-action=close-dialog]').click();
|
||||
await page.locator('nav [data-tab=create]').click();
|
||||
}
|
||||
await page.locator('#order-form').waitFor();
|
||||
} else await ui.open(page, base);
|
||||
await page.locator('#order-form').waitFor();
|
||||
await steps([
|
||||
['customer', customer],
|
||||
['customerType', 'new'],
|
||||
]);
|
||||
}
|
||||
async function issueSale(label) {
|
||||
let result;
|
||||
await step(label, async () => {
|
||||
const [response, shown] = await Promise.all([page.waitForResponse(r => isIssue(r.request())), ui.submit(page)]);
|
||||
assert.equal(response.status(), 200, await response.text());
|
||||
assert.ok(shown.paper);
|
||||
const saved = await response.json();
|
||||
result = {
|
||||
payload: response.request().postDataJSON(),
|
||||
order: await session.get('owner', '/api/orders/' + saved.id),
|
||||
};
|
||||
assert.equal(result.order.paper_number, shown.paper);
|
||||
});
|
||||
issued = true;
|
||||
return result;
|
||||
}
|
||||
async function rejected(label) {
|
||||
const issues = [];
|
||||
const watch = r => {
|
||||
if (isIssue(r)) issues.push(r.postDataJSON());
|
||||
};
|
||||
page.on('request', watch);
|
||||
try {
|
||||
await step(label, async () => {
|
||||
await clickSubmit();
|
||||
await page.waitForLoadState('networkidle');
|
||||
assert.deepEqual(issues, [], '本应被表单拦截的开单已发送请求');
|
||||
assert.ok(await page.locator('#order-form').isVisible());
|
||||
});
|
||||
} finally {
|
||||
page.off('request', watch);
|
||||
}
|
||||
}
|
||||
const { lot, lots } = await seedReturnedLot(session, day);
|
||||
|
||||
await start('公式两件开单');
|
||||
await steps([
|
||||
['formula', '0.79×822+120=769\n0.58×(822+45)+55=558\n769+558=1327'],
|
||||
['line', 0, 'cost-materialRate', '800'],
|
||||
['line', 0, 'cost-labor', '10'],
|
||||
['line', 1, 'cost-materialRate', '800'],
|
||||
['line', 1, 'cost-labor', '10'],
|
||||
['fee', '附加费', 'amount', '0'],
|
||||
['internalNote', '按公式核对两件商品'],
|
||||
]);
|
||||
const formula = await issueSale('多件公式识别后实际开单');
|
||||
assert.equal(formula.order.lines.length, 2);
|
||||
assert.equal(formula.order.total, 132700);
|
||||
|
||||
await start('金额和克重精度');
|
||||
await steps([
|
||||
['line', 0, 'quantity', '0.0001'],
|
||||
['line', 0, 'goldPrice', '999.50'],
|
||||
['line', 0, 'laborRate', '0.00'],
|
||||
['line', 0, 'cost-materialRate', '860.20'],
|
||||
['line', 0, 'cost-labor', '0.00'],
|
||||
['internalNote', '精度边界'],
|
||||
]);
|
||||
await rejected('拒绝四位小数克重且保留表单');
|
||||
await steps([
|
||||
['line', 0, 'quantity', '0.001'],
|
||||
['line', 0, 'goldPrice', '999.501'],
|
||||
]);
|
||||
await rejected('拒绝三位小数金额且保留表单');
|
||||
await steps([['line', 0, 'goldPrice', '1e3']]);
|
||||
await rejected('拒绝科学计数法金额且保留表单');
|
||||
await steps([
|
||||
['line', 0, 'goldPrice', '999.50'],
|
||||
['line', 0, 'quantity', '0'],
|
||||
]);
|
||||
await rejected('拒绝零克重且保留表单');
|
||||
await steps([['line', 0, 'quantity', '0.001']]);
|
||||
await steps([
|
||||
['line', 0, 'goldPrice', '00999.50'],
|
||||
['line', 0, 'cost-materialRate', '00860.20'],
|
||||
]);
|
||||
const precision = await issueSale('毫克克重与含前导零的分位金额实际开单');
|
||||
assert.equal(precision.order.lines[0].quantity, 1);
|
||||
assert.equal(precision.order.total, 100);
|
||||
assert.equal(typeof precision.payload.lines[0].quantity, 'string');
|
||||
|
||||
const ordinary = [
|
||||
['line', 0, 'quantity', '1.250'],
|
||||
['line', 0, 'goldPrice', '971.25'],
|
||||
['line', 0, 'laborRate', '8.50'],
|
||||
['line', 0, 'cost-materialRate', '832.25'],
|
||||
['line', 0, 'cost-labor', '3.25'],
|
||||
];
|
||||
await start('取消选用退回现货');
|
||||
await steps([...ordinary, ['internalNote', '改回普通开单']]);
|
||||
const originalQuantity = await control('quantity').inputValue();
|
||||
await selectLot().selectOption(lot.id);
|
||||
assert.equal(await control('quantity').inputValue(), '2.000');
|
||||
assert.equal(await control('cost-labor').inputValue(), '50.00');
|
||||
await selectLot().selectOption('');
|
||||
assert.equal(await control('quantity').inputValue(), originalQuantity);
|
||||
assert.equal(await control('cost-labor').inputValue(), '3.25');
|
||||
const ordinarySale = await issueSale('取消退回现货选择后按原输入开单');
|
||||
assert.ok(!ordinarySale.order.lines[0].returnedStockId);
|
||||
assert.equal(ordinarySale.order.lines[0].costParts.labor, 325);
|
||||
assert.equal((await lots()).lots[0].id, lot.id);
|
||||
await start('完好退回现货再次销售');
|
||||
await selectLot().selectOption(lot.id);
|
||||
await steps([
|
||||
['line', 0, 'goldPrice', '988.75'],
|
||||
['line', 0, 'laborRate', '3.50'],
|
||||
['internalNote', '整批原工费再售'],
|
||||
]);
|
||||
const resale = await issueSale('整批退回现货沿用原工费再次销售');
|
||||
assert.equal(resale.payload.lines[0].returnedStockId, lot.id);
|
||||
assert.equal(resale.order.lines[0].quantity, 2000);
|
||||
assert.equal(resale.order.lines[0].costParts.labor, 5000);
|
||||
assert.equal(resale.order.lines[0].costPayers.labor, 'assistant');
|
||||
assert.ok(!(await lots()).lots.some(item => item.id === lot.id));
|
||||
}
|
||||
|
||||
// 使用同一个账号的两个真实标签页,验证首单成交后重新进入首页的草稿和下一张订单。
|
||||
export async function exerciseIssueReopen({ version, base, day, session, pageFor, step }) {
|
||||
const ui = version === 'old' ? oldUi : newUi;
|
||||
const first = await pageFor('owner');
|
||||
await session.post('owner', '/api/stock', {
|
||||
date: day,
|
||||
kind: 'opening',
|
||||
pocket: '现货',
|
||||
grams: '20',
|
||||
note: '两笔独立销售',
|
||||
});
|
||||
const fill = async (page, items) => {
|
||||
for (const item of items) await ui.step(page, item);
|
||||
};
|
||||
const line = (idx, quantity, price) => [
|
||||
['line', idx, 'quantity', quantity],
|
||||
['line', idx, 'goldPrice', price],
|
||||
['line', idx, 'laborRate', '0'],
|
||||
['line', idx, 'cost-materialRate', '850'],
|
||||
['line', idx, 'cost-labor', '0'],
|
||||
];
|
||||
const issue = async page => {
|
||||
const [response, shown] = await Promise.all([
|
||||
page.waitForResponse(r => r.request().method() === 'POST' && new URL(r.url()).pathname === '/api/orders/issue'),
|
||||
ui.submit(page),
|
||||
]);
|
||||
assert.equal(response.status(), 200);
|
||||
const { id } = await response.json(),
|
||||
saved = await session.get('owner', '/api/orders/' + id);
|
||||
assert.equal(saved.paper_number, shown.paper);
|
||||
await page.waitForLoadState('networkidle');
|
||||
return saved;
|
||||
};
|
||||
await ui.open(first, base);
|
||||
await fill(first, [
|
||||
['customer', '上一笔两件商品'],
|
||||
['customerType', 'new'],
|
||||
...line(0, '1', '899'),
|
||||
['addLine'],
|
||||
...line(1, '2', '900'),
|
||||
['internalNote', '上一笔普通开单'],
|
||||
]);
|
||||
await step('首笔普通两件商品完成销售', async () => {
|
||||
const saved = await issue(first);
|
||||
assert.equal(saved.lines.length, 2);
|
||||
assert.equal(saved.total, 269900);
|
||||
});
|
||||
const { user } = await session.get('owner', '/api/session');
|
||||
const draftKey = (version === 'old' ? 'mm-draft-' : 'mm-next-draft-') + user.id;
|
||||
const persisted = await first.evaluate(key => {
|
||||
const raw = localStorage.getItem(key);
|
||||
if (!raw) return null;
|
||||
const d = JSON.parse(raw);
|
||||
return { customer: d.customer, lines: d.lines.map(row => ({ quantity: row.quantity, sale: row.sale })) };
|
||||
}, draftKey);
|
||||
const next = await pageFor('owner', { fresh: true });
|
||||
await next.locator('#order-form').waitFor();
|
||||
const initialRows = await next
|
||||
.locator(version === 'old' ? '#order-form .line-item' : '#order-form [data-line]')
|
||||
.count();
|
||||
await fill(next, [
|
||||
['customer', '新标签页第二笔'],
|
||||
['customerType', 'new'],
|
||||
...line(0, '0.001', '999.50'),
|
||||
['internalNote', '第二笔应只收一元'],
|
||||
]);
|
||||
await step('新标签页从首页录入第二笔销售', async () => {
|
||||
const saved = await issue(next);
|
||||
const evidence = JSON.stringify({
|
||||
persisted,
|
||||
initialRows,
|
||||
total: saved.total,
|
||||
lines: saved.lines.map(l => ({ quantity: l.quantity, sale: l.sale })),
|
||||
});
|
||||
assert.equal(saved.total, 100, '第二单沿用了已成交订单的商品:' + evidence);
|
||||
assert.equal(saved.lines.length, 1, evidence);
|
||||
assert.equal(initialRows, 1, evidence);
|
||||
assert.ok(!persisted || (!persisted.customer && persisted.lines.every(l => !l.quantity)), evidence);
|
||||
});
|
||||
}
|
||||
|
||||
// 非滚动料池同时存在两天料价时,业务日期往返会实际改变所选批次的成本和利润。
|
||||
export async function exerciseIssuePoolDate({ version, base, day, session, pageFor, step }) {
|
||||
const yesterday = '2026-11-19',
|
||||
ui = version === 'old' ? oldUi : newUi;
|
||||
const { lot } = await seedReturnedLot(session, day);
|
||||
await session.post('owner', '/api/material-purchases', {
|
||||
date: yesterday,
|
||||
grams: '8',
|
||||
total: '4000',
|
||||
payer: 'owner',
|
||||
note: '昨日购料',
|
||||
});
|
||||
await session.post('owner', '/api/material-purchases', {
|
||||
date: day,
|
||||
grams: '5',
|
||||
total: '4500',
|
||||
payer: 'owner',
|
||||
note: '当日购料',
|
||||
});
|
||||
const page = await pageFor('owner');
|
||||
await ui.open(page, base);
|
||||
for (const input of [
|
||||
['customer', '退回现货切换日期'],
|
||||
['customerType', 'new'],
|
||||
['internalNote', '核实重新选用料池'],
|
||||
['line', 0, 'quantity', '1.250'],
|
||||
['line', 0, 'goldPrice', '971.25'],
|
||||
['line', 0, 'laborRate', '8.50'],
|
||||
['line', 0, 'cost-materialRate', '832.25'],
|
||||
['line', 0, 'cost-labor', '3.25'],
|
||||
])
|
||||
await ui.step(page, input);
|
||||
const select = ui.line(page, 0).locator('[name=returnedStockId]');
|
||||
await select.selectOption(lot.id);
|
||||
await select.selectOption('');
|
||||
await ui.step(page, ['line', 0, 'materialSource', 'pool']);
|
||||
const date = page
|
||||
.locator(version === 'old' ? '#order-form [name=date]' : '#order-form [data-field=date] input')
|
||||
.first();
|
||||
for (const d of [yesterday, day]) {
|
||||
await date.fill(d);
|
||||
await date.blur();
|
||||
await page.waitForLoadState('networkidle');
|
||||
}
|
||||
await step('撤销退回现货选择并切换日期后按料池实际开单', async () => {
|
||||
const [response, shown] = await Promise.all([
|
||||
page.waitForResponse(r => r.request().method() === 'POST' && new URL(r.url()).pathname === '/api/orders/issue'),
|
||||
ui.submit(page),
|
||||
]);
|
||||
assert.equal(response.status(), 200);
|
||||
const { id } = await response.json(),
|
||||
order = await session.get('owner', '/api/orders/' + id);
|
||||
assert.equal(order.paper_number, shown.paper);
|
||||
const evidence = JSON.stringify({
|
||||
sale: order.total,
|
||||
pool: response.request().postDataJSON().lines[0].costMaterial,
|
||||
material: order.lines[0].costParts.material,
|
||||
profit: order.profit,
|
||||
});
|
||||
assert.equal(order.lines[0].costMaterial.poolId, yesterday, '原选料池随业务日期切换:' + evidence);
|
||||
assert.equal(order.lines[0].costParts.material, 62500, evidence);
|
||||
assert.equal(order.profit, 59675, evidence);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { action, section, postFrom } from './operations-helpers.mjs';
|
||||
|
||||
export default async function operationsAccess(ctx) {
|
||||
const { session, day } = ctx;
|
||||
for (const [role, label] of [
|
||||
['owner', '店主'],
|
||||
['assistant', '第一名店员'],
|
||||
['assistant2', '第二名店员'],
|
||||
]) {
|
||||
const page = await ctx.pageFor(role);
|
||||
const manager = role === 'owner';
|
||||
await section(page, ctx, 'stock');
|
||||
await page.locator('#stock-form').waitFor();
|
||||
const inventory = await session.get(role, '/api/inventory');
|
||||
assert.equal(inventory.canReview, manager);
|
||||
const review = action(page, 'inventory-review');
|
||||
assert.equal(await review.count(), manager ? 1 : 0);
|
||||
await ctx.step(label + '的库存复核权限', async () => {
|
||||
if (manager) {
|
||||
await postFrom(page, '/api/inventory/review', () => review.click());
|
||||
await page.locator('.stock-review-status').getByText('店主复核', { exact: true }).waitFor();
|
||||
} else {
|
||||
// 页面不给店员提供该按钮。用同样的有效日期、revision 验证 API 自身的权限。
|
||||
const denied = await session.request(role, 'POST', '/api/inventory/review', {
|
||||
body: { date: day, verified: true, revision: inventory.revision },
|
||||
expect: 403,
|
||||
});
|
||||
assert.equal(denied.status, 403);
|
||||
}
|
||||
});
|
||||
const nav = page.locator('nav [data-tab=team-funds]:visible');
|
||||
assert.equal(await nav.count(), manager ? 1 : 0);
|
||||
const expectedStatus = manager ? 200 : 403;
|
||||
for (const url of ['/api/team-funds?date=' + day, '/api/team-profits?month=' + day.slice(0, 7)]) {
|
||||
const r = await session.request(role, 'GET', url, { expect: expectedStatus });
|
||||
assert.equal(r.status, expectedStatus);
|
||||
}
|
||||
if (manager) {
|
||||
await nav.click();
|
||||
const filter = page.locator('#team-funds-filter');
|
||||
await filter.locator('[name=month]').fill('2026-10');
|
||||
const [read] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
r =>
|
||||
new URL(r.url()).pathname === '/api/team-profits' &&
|
||||
new URL(r.url()).searchParams.get('month') === '2026-10',
|
||||
),
|
||||
filter.locator('[type=submit]').click(),
|
||||
]);
|
||||
assert.equal(read.status(), 200);
|
||||
await page.locator('#team-funds-content').getByText('助理月度利润').waitFor();
|
||||
assert.equal(
|
||||
await page.locator('#team-transfer-form:visible, [data-action=inventory-review]:visible').count(),
|
||||
0,
|
||||
);
|
||||
assert.equal(await page.getByRole('button', { name: '登记实际转账' }).count(), 0);
|
||||
} else if (ctx.version === 'new') {
|
||||
await page.goto(ctx.base + '/next/team-funds');
|
||||
await page.locator('nav [data-tab=report][aria-current=page]:visible').waitFor();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
export async function section(page, ctx, key) {
|
||||
if (ctx.version === 'new') await page.goto(ctx.base + '/next/' + key);
|
||||
else {
|
||||
await page.goto(ctx.base + '/');
|
||||
await page
|
||||
.locator('nav button[data-tab="' + key + '"]:visible')
|
||||
.first()
|
||||
.click();
|
||||
}
|
||||
}
|
||||
|
||||
export function action(scope, name) {
|
||||
return scope.locator('[data-action="' + name + '"]:visible').first();
|
||||
}
|
||||
|
||||
export async function postFrom(page, url, click, expectedStatus = 200) {
|
||||
const [response] = await Promise.all([
|
||||
page.waitForResponse(r => new URL(r.url()).pathname === url && r.request().method() === 'POST'),
|
||||
click(),
|
||||
]);
|
||||
const result = await response.json();
|
||||
assert.equal(response.status(), expectedStatus, url + ' ' + JSON.stringify(result));
|
||||
await page.waitForLoadState('networkidle');
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { action, postFrom, section } from './operations-helpers.mjs';
|
||||
|
||||
export async function inventoryWrites(ctx, owner, staff) {
|
||||
const { step, day } = ctx;
|
||||
const manager = owner.locator('#pocket-manager');
|
||||
const editor = owner.locator('#pocket-editor-dialog[open]');
|
||||
await section(owner, ctx, 'stock');
|
||||
await action(owner, 'pocket-manager-toggle').click();
|
||||
const initial = '对照原料盘';
|
||||
const renamed = '对照成对货盘';
|
||||
await action(manager, 'pocket-manager-add').click();
|
||||
await step('库存新增普通货盘', async () => {
|
||||
await editor.locator('[name=name]').fill(initial);
|
||||
await postFrom(owner, '/api/pockets', () => editor.locator('[type=submit]').click());
|
||||
await editor.waitFor({ state: 'hidden' });
|
||||
});
|
||||
const pocketRow = name => manager.locator('tr').filter({ hasText: name });
|
||||
const edit = pocketRow(initial).locator('[data-action=pocket-manager-edit]');
|
||||
const key = await edit.getAttribute('data-pocket-key');
|
||||
const update = '/api/pockets/' + encodeURIComponent(key) + '/update';
|
||||
const form = p => p.locator('#stock-form');
|
||||
const movement = (p, note) => p.locator('tr[data-movement-id]').filter({ hasText: note }).first();
|
||||
async function add(p, name, { kind = 'increase', pocket = key, grams, stockCount, to, date = day }) {
|
||||
const f = form(p);
|
||||
await f.locator('[name=kind]').selectOption(kind);
|
||||
await f.locator('[name=pocket]').selectOption(pocket);
|
||||
if (to) await f.locator('[name=to]').selectOption(to);
|
||||
if (grams) await f.locator('[name=grams]').fill(grams);
|
||||
if (stockCount) await f.locator('[name=stockCount]').fill(stockCount);
|
||||
await f.locator('[name=date]').fill(date);
|
||||
await f.locator('[name=note]').fill(name);
|
||||
const [request, result] = await Promise.all([
|
||||
p.waitForRequest(r => r.method() === 'POST' && new URL(r.url()).pathname === '/api/stock'),
|
||||
postFrom(p, '/api/stock', () => f.locator('button').click()),
|
||||
]);
|
||||
assert.deepEqual(request.postDataJSON(), {
|
||||
kind,
|
||||
date,
|
||||
pocket,
|
||||
grams: grams || '0',
|
||||
note: name,
|
||||
...(to && { to }),
|
||||
...(stockCount && { stockCount: Number(stockCount) }),
|
||||
});
|
||||
if (date === day) await movement(p, name).waitFor();
|
||||
await p.waitForFunction(() => document.querySelector('#stock-form [name=note]')?.value === '');
|
||||
return result;
|
||||
}
|
||||
await step('库存普通货盘登记启用对数前的流水', () => add(owner, '盘点前的克重', { grams: '3.500' }));
|
||||
await section(owner, ctx, 'stock');
|
||||
await action(owner, 'pocket-manager-toggle').click();
|
||||
await edit.click();
|
||||
await step('库存货盘重命名并盘点启用对数', async () => {
|
||||
await editor.locator('[name=name]').fill(renamed);
|
||||
await editor.locator('[name=enableCounts]').check();
|
||||
await editor.locator('[name=initialCount]').fill('4');
|
||||
await editor.locator('[name=countVerified]').check();
|
||||
await postFrom(owner, update, () => editor.locator('[type=submit]').click());
|
||||
await pocketRow(renamed).waitFor();
|
||||
});
|
||||
for (const [state, label] of [
|
||||
[false, '停用'],
|
||||
[true, '启用'],
|
||||
]) {
|
||||
await step('库存' + label + '已有货盘', async () => {
|
||||
await postFrom(owner, update, () =>
|
||||
pocketRow(renamed)
|
||||
.locator('[data-action=pocket-manager-status][data-active=' + state + ']')
|
||||
.click(),
|
||||
);
|
||||
await pocketRow(renamed)
|
||||
.getByText(state ? '已启用' : '已停用', { exact: true })
|
||||
.waitFor();
|
||||
});
|
||||
}
|
||||
await action(manager, 'pocket-manager-add').click();
|
||||
const target = await step('库存新增零基准对数货盘', async () => {
|
||||
await editor.locator('[name=name]').fill('对照第二对数盘');
|
||||
await editor.locator('[name=enableCounts]').check();
|
||||
await editor.locator('[name=initialCount]').fill('0');
|
||||
await editor.locator('[name=countVerified]').check();
|
||||
await postFrom(owner, '/api/pockets', () => editor.locator('[type=submit]').click());
|
||||
return pocketRow('对照第二对数盘').locator('[data-action=pocket-manager-edit]').getAttribute('data-pocket-key');
|
||||
});
|
||||
await step('库存增加克重及对数', () => add(owner, '增加对数', { grams: '12.345', stockCount: '2' }));
|
||||
await step('库存减少克重及对数', () => add(owner, '减少对数', { kind: 'decrease', grams: '1.001', stockCount: '1' }));
|
||||
await step('库存从对数盘平移到普通货盘', () =>
|
||||
add(owner, '平移的组', { kind: 'transfer', grams: '2.250', stockCount: '1', to: '现货' }),
|
||||
);
|
||||
await step('库存只调整对数', () => add(owner, '实物重新清点', { kind: 'adjustment', stockCount: '-1' }));
|
||||
await step('库存两个对数盘间平移克重及对数', () =>
|
||||
add(owner, '两个对数盘间平移', { kind: 'transfer', grams: '0.750', stockCount: '1', to: target }),
|
||||
);
|
||||
const changes = (p, note, kind) => movement(p, note).locator('[data-action=inventory-change-' + kind + ']');
|
||||
async function modify(p, note, kind, reason, newNote) {
|
||||
await changes(p, note, kind).click();
|
||||
const f = p.locator('#inventory-change-form');
|
||||
const id = await f.getAttribute('data-id');
|
||||
if (newNote) await f.locator('[name=note]').fill(newNote);
|
||||
await f.locator('[name=reason]').fill(reason);
|
||||
const confirmation = f.locator('[name=legacyCountVerified]:visible');
|
||||
if (await confirmation.count()) await confirmation.check();
|
||||
const result = await postFrom(
|
||||
p,
|
||||
'/api/inventory/movements/' + encodeURIComponent(id) + '/' + kind.replace('edit', 'update'),
|
||||
() => f.locator('[type=submit]').click(),
|
||||
);
|
||||
await f.waitFor({ state: 'hidden' });
|
||||
return result;
|
||||
}
|
||||
await step('库存盘点后更正只有克重的历史流水', async () => {
|
||||
await changes(owner, '盘点前的克重', 'edit').click();
|
||||
const f = owner.locator('#inventory-change-form');
|
||||
const id = await f.getAttribute('data-id');
|
||||
await f.locator('[name=legacyCountVerified]').check();
|
||||
await f.locator('[name=grams]').fill('3.250');
|
||||
await f.locator('[name=reason]').fill('更正盘点前的重量');
|
||||
await postFrom(owner, '/api/inventory/movements/' + encodeURIComponent(id) + '/update', () =>
|
||||
f.locator('[type=submit]').click(),
|
||||
);
|
||||
await f.waitFor({ state: 'hidden' });
|
||||
});
|
||||
await step('库存店主更正已有平移组', () => modify(owner, '平移的组', 'edit', '更正平移备注', '已更正平移'));
|
||||
await step('库存店主删除完整平移组', () => modify(owner, '已更正平移', 'delete', '撤回整组平移'));
|
||||
await step('库存保存当日复核快照', async () => {
|
||||
await postFrom(owner, '/api/inventory/review', () => action(owner, 'inventory-review').click());
|
||||
await owner.locator('.stock-review-status').getByText('店主复核', { exact: true }).waitFor();
|
||||
});
|
||||
// 店员自己登记的历史记录可发起更正,删除即使当天也要复核。
|
||||
const yesterday = new Date(Date.parse(day + 'T12:00Z') - 86400000).toISOString().slice(0, 10);
|
||||
await section(staff, ctx, 'stock');
|
||||
await step('库存店员登记当日库存变动', () => add(staff, '店员当日记录', { grams: '0.750', pocket: '现货' }));
|
||||
await step('库存店员直接更正自己当日流水', async () => {
|
||||
const changed = await modify(staff, '店员当日记录', 'edit', '复核当天备注', '店员当日记录已复核');
|
||||
assert.equal(changed.pending, false);
|
||||
});
|
||||
await step('库存店员登记历史库存变动', () =>
|
||||
add(staff, '店员历史记录', { date: yesterday, pocket: '现货', grams: '3.250' }),
|
||||
);
|
||||
await staff.locator('#inventory-movements-from').fill(yesterday);
|
||||
await staff.locator('#inventory-movements-from').press('Tab');
|
||||
let request;
|
||||
await step('库存店员申请修改旧流水', async () => {
|
||||
request = await modify(staff, '店员历史记录', 'edit', '请复核修改', '申请更正库存');
|
||||
});
|
||||
async function decide(op, reason) {
|
||||
await action(owner, 'inventory-change-refresh').click();
|
||||
await action(owner, 'inventory-change-open-request').click();
|
||||
const review = owner.locator('#inventory-change-review-form');
|
||||
const id = await review.getAttribute('data-id');
|
||||
if (request.requestId) assert.equal(id, request.requestId);
|
||||
await review.locator('[name=note]').fill(reason);
|
||||
const button = op === 'approve' ? review.locator('[type=submit]') : action(review, 'inventory-change-reject');
|
||||
const result = await postFrom(owner, '/api/inventory/changes/' + encodeURIComponent(id) + '/' + op, () =>
|
||||
button.click(),
|
||||
);
|
||||
await review.waitFor({ state: 'hidden' });
|
||||
return result;
|
||||
}
|
||||
await step('库存店主驳回流水更正申请', () => decide('reject', '维持原记录'));
|
||||
async function reloadHistory() {
|
||||
await section(staff, ctx, 'stock');
|
||||
await staff.locator('#inventory-movements-from').fill(yesterday);
|
||||
await staff.locator('#inventory-movements-from').press('Tab');
|
||||
}
|
||||
await reloadHistory();
|
||||
await step('库存店员重新提交流水更正', async () => {
|
||||
request = await modify(staff, '店员历史记录', 'edit', '复核后重新申请', '核实后更正');
|
||||
});
|
||||
await step('库存店主批准流水更正', () => decide('approve', '已复核修改'));
|
||||
await reloadHistory();
|
||||
await step('库存店员申请删除已更正的旧流水', async () => {
|
||||
request = await modify(staff, '核实后更正', 'delete', '实际需要撤回');
|
||||
});
|
||||
await step('库存店主批准删除申请', () => decide('approve', '核对后撤回'));
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { action, postFrom, section } from './operations-helpers.mjs';
|
||||
|
||||
const api = '/api/recoveries';
|
||||
const field = (form, name) => form.locator('[name="' + name + '"]');
|
||||
const submit = form => form.locator('button[type=submit]');
|
||||
const detail = page => page.locator('#recovery-dialog[open]');
|
||||
|
||||
async function openRecord(ctx, page, id, date) {
|
||||
await section(page, ctx, 'recoveries');
|
||||
const f = page.locator('#recovery-filter-form');
|
||||
await field(f, 'from').fill(date);
|
||||
await submit(f).click();
|
||||
await page
|
||||
.locator('[data-action=recovery-open][data-id="' + id + '"]')
|
||||
.first()
|
||||
.click();
|
||||
await detail(page).locator('[data-action=recovery-print]').waitFor();
|
||||
}
|
||||
|
||||
async function quoteAndSave(page, path) {
|
||||
const f = page.locator('#recovery-form');
|
||||
await field(f, 'verified').check();
|
||||
await page
|
||||
.locator('#recovery-quote-status')
|
||||
.getByText(/结算已核对/)
|
||||
.waitFor();
|
||||
return postFrom(page, path, () => submit(f).click());
|
||||
}
|
||||
|
||||
async function printRecovery(page, id, dialog = detail(page)) {
|
||||
const [popup] = await Promise.all([page.waitForEvent('popup'), action(dialog, 'recovery-print').click()]);
|
||||
assert.equal(new URL(popup.url()).pathname, '/print/recoveries/' + id);
|
||||
try {
|
||||
await popup.evaluate(() => {
|
||||
window.print = () => {};
|
||||
});
|
||||
await postFrom(popup, '/api/print-status/recovery/' + id, () => popup.locator('#print').click());
|
||||
await dialog
|
||||
.locator('[data-print-kind=recovery][data-print-id="' + id + '"]')
|
||||
.getByText('✓ 已打印')
|
||||
.waitFor();
|
||||
} finally {
|
||||
await popup.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function createCustomerDeposit(ctx, page) {
|
||||
await action(page, 'customer-material-new').click();
|
||||
const f = page.locator('#customer-material-form');
|
||||
return ctx.step('客料登记寄存克重与备忘', async () => {
|
||||
await field(f, 'grams').fill('9.125');
|
||||
await field(f, 'memo').fill('寄存对照袋');
|
||||
await field(f, 'verified').check();
|
||||
const r = await postFrom(page, '/api/customer-materials', () => submit(f).click());
|
||||
await page.locator('#customer-material-list').getByText('寄存对照袋', { exact: true }).waitFor();
|
||||
return r;
|
||||
});
|
||||
}
|
||||
|
||||
async function cancelRecord(page, id, reason) {
|
||||
await action(detail(page), 'recovery-edit-cancel').click();
|
||||
const f = page.locator('#recovery-cancel-form');
|
||||
await field(f, 'reason').fill(reason);
|
||||
await field(f, 'verified').check();
|
||||
const legacy = field(f, 'legacyCountVerified');
|
||||
if (await legacy.count()) await legacy.check();
|
||||
return postFrom(page, api + '/' + id + '/cancel', () => submit(f).click());
|
||||
}
|
||||
|
||||
async function review(page, id, decision) {
|
||||
await action(page, 'recovery-changes-open').click();
|
||||
await action(page.locator('#recovery-change-list'), 'recovery-change-open').click();
|
||||
await page.locator('[data-action=recovery-change-decision][data-kind="' + decision + '"]').click();
|
||||
const f = page.locator('#recovery-change-review-form');
|
||||
await field(f, 'note').fill(decision === 'reject' ? '退回重新核对' : '已对照原凭证');
|
||||
if (decision === 'approve') await field(f, 'verified').check();
|
||||
return postFrom(page, '/api/recovery-changes/' + id + '/' + decision, () => submit(f).click());
|
||||
}
|
||||
|
||||
function historicalInput(day) {
|
||||
const product = (oldGrams, quantity, extra) => ({
|
||||
date: day,
|
||||
mode: 'exchange',
|
||||
customer: '历史逐件对照',
|
||||
customer_type: 'new',
|
||||
salesperson: '麦麦',
|
||||
old_lines: [{ name: '旧料', incoming_weight: oldGrams, melted_weight: oldGrams, purity: '100' }],
|
||||
buy_rate: '850',
|
||||
payer: 'owner',
|
||||
payment_account: '麦麦微信',
|
||||
verified: true,
|
||||
exchange: {
|
||||
name: '足金合成新货',
|
||||
quantity,
|
||||
pocket: '现货',
|
||||
gold_price: '1000',
|
||||
labor_rate: '20',
|
||||
labor_mode: 'gram',
|
||||
depreciation_rate: '10',
|
||||
cost_material: { mode: 'gram', rate: '900' },
|
||||
cost_labor: { mode: 'gram', rate: '5' },
|
||||
cost_payer: 'owner',
|
||||
discount: '0',
|
||||
rounding_mode: 'cent',
|
||||
...extra,
|
||||
},
|
||||
});
|
||||
const a = product('10', '15', {}),
|
||||
b = product('20', '12', {
|
||||
pocket: '',
|
||||
gold_price: '1100',
|
||||
labor_rate: '30',
|
||||
depreciation_rate: '5',
|
||||
cost_labor: { mode: 'total', amount: '60' },
|
||||
cost_labor_payer: 'assistant2',
|
||||
});
|
||||
return {
|
||||
...a,
|
||||
member: 'owner',
|
||||
exchange: { items: [a, b], charges: [], fee_items: [], discount: '0', rounding_mode: 'cent' },
|
||||
};
|
||||
}
|
||||
|
||||
export async function recoveryWrites(ctx, owner, staff) {
|
||||
const { step, day, session } = ctx;
|
||||
const yesterday = new Date(Date.parse(day + 'T12:00Z') - 86400000).toISOString().slice(0, 10);
|
||||
await session.post('owner', '/api/stock', {
|
||||
kind: 'increase',
|
||||
date: day,
|
||||
pocket: '现货',
|
||||
grams: '100',
|
||||
note: '置换对照库存',
|
||||
});
|
||||
const historical = await session.post('owner', api, historicalInput(day));
|
||||
const previous = await session.post('assistant', api, {
|
||||
date: yesterday,
|
||||
mode: 'direct',
|
||||
customer: '跨日回收对照',
|
||||
member: 'assistant',
|
||||
salesperson: '娜娜',
|
||||
old_lines: [{ name: '旧料', incoming_weight: '2', melted_weight: '2', purity: '100' }],
|
||||
buy_rate: '850',
|
||||
payer: 'assistant',
|
||||
payment_account: '助理微信',
|
||||
verified: true,
|
||||
});
|
||||
assert.deepEqual(session.problems, []);
|
||||
await section(owner, ctx, 'recoveries');
|
||||
const deposit = await createCustomerDeposit(ctx, owner);
|
||||
await action(owner, 'customer-material-back').click();
|
||||
const f = owner.locator('#recovery-form');
|
||||
const direct = await step('直接回收登记称重纯度与结算', async () => {
|
||||
await field(f, 'customer').fill('直接回收对照');
|
||||
await field(f, 'incoming_weight').fill('3.100');
|
||||
await field(f, 'purity').fill('99');
|
||||
await field(f, 'buy_rate').fill('733.22');
|
||||
await field(f, 'buy_total').fill('2253.44');
|
||||
return quoteAndSave(owner, api);
|
||||
});
|
||||
await step('直接回收单客户打印回写', () => printRecovery(owner, direct.id));
|
||||
await action(detail(owner), 'recovery-edit-open').click();
|
||||
await step('店主修改回收价格及结算', async () => {
|
||||
await field(f, 'change_reason').fill('对照原始价格');
|
||||
await field(f, 'buy_rate').fill('734.22');
|
||||
await action(f, 'recovery-reset-buy').click();
|
||||
await quoteAndSave(owner, api + '/' + direct.id + '/update');
|
||||
});
|
||||
await step('店主取消回收记录并冲回购料', () => cancelRecord(owner, direct.id, '核对后撤回'));
|
||||
await section(owner, ctx, 'recoveries');
|
||||
await owner.locator('[data-action=recovery-mode][data-mode=exchange]').click();
|
||||
const exchange = await step('置换使用部分客料并记录工费收款', async () => {
|
||||
await field(f, 'customer').fill('寄存置换对照');
|
||||
await f.locator('[name=customer_type][value=new]').check();
|
||||
await field(f, 'old_source').selectOption('deposit');
|
||||
await field(f, 'deposit_id').selectOption(deposit.id);
|
||||
await field(f, 'deposit_weight').fill('2');
|
||||
await field(f, 'new_quantity').fill('2');
|
||||
await field(f, 'labor_rate').fill('35');
|
||||
await field(f, 'cost_labor_value').fill('10');
|
||||
return quoteAndSave(owner, api);
|
||||
});
|
||||
const linked = (await session.get('owner', api + '/' + exchange.id + '/edit')).record.order_id;
|
||||
await section(owner, ctx, 'orders');
|
||||
await owner
|
||||
.locator('[data-action=open-order][data-id="' + linked + '"]')
|
||||
.first()
|
||||
.click();
|
||||
await step('置换关联销售单客户打印回写', () =>
|
||||
printRecovery(owner, exchange.id, owner.locator('#order-dialog[open]')),
|
||||
);
|
||||
await openRecord(ctx, owner, exchange.id, day);
|
||||
await step('取消客料置换并恢复寄存余额', () => cancelRecord(owner, exchange.id, '退还原客户寄存'));
|
||||
await section(owner, ctx, 'recoveries');
|
||||
await owner.locator('[data-action=recovery-mode][data-mode=exchange]').click();
|
||||
await step('多件置换共用来料并将余料登记为客料', async () => {
|
||||
await field(f, 'customer').fill('余料寄存对照');
|
||||
await f.locator('[name=customer_type][value=returning]').check();
|
||||
await field(f, 'incoming_weight').fill('5');
|
||||
await field(f, 'new_quantity').fill('2');
|
||||
await field(f, 'labor_rate').fill('20');
|
||||
await field(f, 'cost_labor_value').fill('2');
|
||||
await action(f, 'recovery-add-product').click();
|
||||
await field(f, 'extra_new_quantity').fill('1');
|
||||
await field(f, 'extra_labor_rate').fill('25');
|
||||
await field(f, 'extra_cost_labor_value').fill('3');
|
||||
await field(f, 'surplus_mode').selectOption('deposit');
|
||||
await field(f, 'surplus_memo').fill('新袋余料');
|
||||
await field(f, 'payment_method').selectOption('信用卡');
|
||||
return quoteAndSave(owner, api);
|
||||
});
|
||||
await session.post('owner', '/api/material-purchases', {
|
||||
date: day,
|
||||
grams: '8',
|
||||
total: '6800',
|
||||
payer: 'owner',
|
||||
note: '置换公共料池对照',
|
||||
});
|
||||
assert.deepEqual(session.problems, []);
|
||||
await section(owner, ctx, 'recoveries');
|
||||
await owner.locator('[data-action=recovery-mode][data-mode=exchange]').click();
|
||||
await step('置换补金按所选料池核算并确认收款', async () => {
|
||||
await field(f, 'customer').fill('补金料池对照');
|
||||
await f.locator('[name=customer_type][value=new]').check();
|
||||
await field(f, 'incoming_weight').fill('2');
|
||||
await field(f, 'new_quantity').fill('3');
|
||||
await field(f, 'gold_price').fill('920');
|
||||
await field(f, 'cost_labor_value').fill('15');
|
||||
await field(f, 'labor_rate').fill('20');
|
||||
await field(f, 'material_source').selectOption('pool');
|
||||
await field(f, 'material_pool_id').selectOption(day);
|
||||
return quoteAndSave(owner, api);
|
||||
});
|
||||
await openRecord(ctx, owner, historical.id, day);
|
||||
await action(detail(owner), 'recovery-edit-open').click();
|
||||
await step('历史逐件置换仅修改第二件工费', async () => {
|
||||
await f.locator('[data-recovery-item]').nth(1).waitFor();
|
||||
assert.equal(await f.locator('[data-recovery-item]').count(), 2);
|
||||
await f.locator('[data-recovery-item]').nth(1).locator('[name=extra_labor_rate]').fill('31.5');
|
||||
await field(f, 'change_reason').fill('更正第二件工费');
|
||||
await quoteAndSave(owner, api + '/' + historical.id + '/update');
|
||||
});
|
||||
await openRecord(ctx, staff, previous.id, yesterday);
|
||||
await action(detail(staff), 'recovery-edit-open').click();
|
||||
const sf = staff.locator('#recovery-form');
|
||||
const proposal = await step('店员跨日提交回收更正申请', async () => {
|
||||
// 两个页面都先显示详情模态框,等具备修改理由的编辑表单到位再输入。
|
||||
await field(sf, 'change_reason').fill('请核对历史手续费');
|
||||
await field(sf, 'buy_rate').fill('858');
|
||||
const proposal = await quoteAndSave(staff, api + '/' + previous.id + '/update');
|
||||
assert.equal(proposal.request.after.buy_rate, '858.00');
|
||||
return proposal;
|
||||
});
|
||||
await section(owner, ctx, 'recoveries');
|
||||
await step('店主批准历史回收更正', () => review(owner, proposal.requestId || proposal.request?.id, 'approve'));
|
||||
await openRecord(ctx, staff, previous.id, yesterday);
|
||||
const cancellation = await step('店员跨日提交回收取消申请', () => cancelRecord(staff, previous.id, '核对历史取消'));
|
||||
await section(owner, ctx, 'recoveries');
|
||||
await step('店主驳回历史回收取消申请', () =>
|
||||
review(owner, cancellation.requestId || cancellation.request?.id, 'reject'),
|
||||
);
|
||||
await openRecord(ctx, staff, previous.id, yesterday);
|
||||
const again = await step('店员重新提交已驳回的回收取消申请', () =>
|
||||
cancelRecord(staff, previous.id, '重查后仍需作废'),
|
||||
);
|
||||
await section(owner, ctx, 'recoveries');
|
||||
await step('店主批准回收取消及关联冲回', () => review(owner, again.requestId || again.request?.id, 'approve'));
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { action, postFrom, section } from './operations-helpers.mjs';
|
||||
import { inventoryWrites } from './operations-inventory.mjs';
|
||||
import { recoveryWrites } from './operations-recoveries.mjs';
|
||||
|
||||
async function peopleWrites(ctx, owner, staff) {
|
||||
const url = '/api/private-operations/people';
|
||||
await section(owner, ctx, 'private-operations');
|
||||
await action(owner, 'private-people-open').click();
|
||||
const ownerDialog = owner.locator('#private-people-dialog[open]');
|
||||
await ctx.step('私域店主代员工登记总人数', async () => {
|
||||
const form = ownerDialog.locator('form');
|
||||
await form.locator('[name=member]').selectOption('assistant');
|
||||
await form.locator('[name=total_count]').fill('10');
|
||||
await postFrom(owner, url, () => form.locator('[type=submit]').click());
|
||||
await ownerDialog.waitFor({ state: 'hidden' });
|
||||
});
|
||||
await section(staff, ctx, 'people-entry');
|
||||
const staffDialog = staff.locator('#private-people-dialog[open]');
|
||||
await action(staff, 'private-people-open').click();
|
||||
await staff.waitForFunction(
|
||||
() => document.querySelector('#private-people-dialog [name=total_count]')?.value === '10',
|
||||
);
|
||||
await owner.getByRole('button', { name: '修改娜娜 ' + ctx.day + '人数' }).click();
|
||||
await ctx.step('私域店主更正同一日人数为零', async () => {
|
||||
await ownerDialog.locator('[name=total_count]').fill('0');
|
||||
await postFrom(owner, url, () => ownerDialog.locator('[type=submit]').click());
|
||||
await ownerDialog.waitFor({ state: 'hidden' });
|
||||
});
|
||||
await ctx.step('私域店员持旧版本修改人数并收到冲突', async () => {
|
||||
await staffDialog.locator('[name=total_count]').fill('8');
|
||||
await postFrom(staff, url, () => staffDialog.locator('[type=submit]').click(), 409);
|
||||
await staffDialog.getByRole('button', { name: '重新读取后核对' }).click();
|
||||
await staff.waitForFunction(
|
||||
() => document.querySelector('#private-people-dialog [name=total_count]')?.value === '0',
|
||||
);
|
||||
});
|
||||
await ctx.step('私域店员核对最新人数后保存', async () => {
|
||||
await staffDialog.locator('[name=total_count]').fill('15');
|
||||
await postFrom(staff, url, () => staffDialog.locator('[type=submit]').click());
|
||||
await staffDialog.waitFor({ state: 'hidden' });
|
||||
await staff.locator('#people-entry-history').getByText('15', { exact: true }).first().waitFor();
|
||||
});
|
||||
}
|
||||
|
||||
export default async function operations(ctx) {
|
||||
const owner = await ctx.pageFor('owner');
|
||||
const staff = await ctx.pageFor('assistant');
|
||||
await inventoryWrites(ctx, owner, staff);
|
||||
await recoveryWrites(ctx, owner, staff);
|
||||
await peopleWrites(ctx, owner, staff);
|
||||
const staff2 = await ctx.pageFor('assistant2');
|
||||
await section(staff2, ctx, 'people-entry');
|
||||
await action(staff2, 'private-people-open').click();
|
||||
const dialog = staff2.locator('#private-people-dialog[open]');
|
||||
await ctx.step('私域第二名店员首次登记并核对历史', async () => {
|
||||
await dialog.locator('[name=total_count]').fill('6');
|
||||
await postFrom(staff2, '/api/private-operations/people', () => dialog.locator('[type=submit]').click());
|
||||
await dialog.waitFor({ state: 'hidden' });
|
||||
await staff2.locator('#people-entry-history').getByText('6', { exact: true }).first().waitFor();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
export async function exerciseOrderConflicts({
|
||||
base,
|
||||
day,
|
||||
passwords,
|
||||
session,
|
||||
post,
|
||||
open,
|
||||
field,
|
||||
legacyForm,
|
||||
step,
|
||||
submit,
|
||||
route,
|
||||
issue,
|
||||
}) {
|
||||
for (const conflict of ['revision', 'date']) {
|
||||
const id = await issue(conflict === 'revision' ? '并发入账' : '填单跨过营业日');
|
||||
const page = await open('assistant', id);
|
||||
const form = await legacyForm(page, 'expense');
|
||||
await field(form, 'amount').fill('5.76');
|
||||
await field(form, 'note').fill('新增支出');
|
||||
await field(form, 'change_reason').fill('核实后补登');
|
||||
await field(form, 'verified').check();
|
||||
if (conflict === 'revision') {
|
||||
await post('owner', route(id) + '/expense', { date: day, amount: '1', note: '同时另记支出', payer: 'owner' });
|
||||
} else {
|
||||
await session.day('2026-11-21');
|
||||
await post('assistant', '/api/login', { member: 'assistant', password: passwords.assistant });
|
||||
await page
|
||||
.context()
|
||||
.addCookies([{ name: 'mm_session', value: session.cookies.assistant.slice('mm_session='.length), url: base }]);
|
||||
}
|
||||
await step(conflict === 'revision' ? '并发改账后拒绝过期的直接登记' : '跨过营业日后拒绝原直接登记', async () => {
|
||||
const [response] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
r => new URL(r.url()).pathname === route(id) + '/expense' && r.request().method() === 'POST',
|
||||
),
|
||||
form.locator('button.primary').click(),
|
||||
]);
|
||||
assert.equal(response.status(), conflict === 'revision' ? 409 : 403, await response.text());
|
||||
await form.locator('#order-action-change-error .error').waitFor();
|
||||
assert.equal(await field(form, 'amount').inputValue(), '5.76');
|
||||
assert.equal(await field(form, 'verified').isChecked(), false);
|
||||
if (conflict === 'revision') assert.equal(await form.locator('button.primary').isDisabled(), true);
|
||||
else assert.equal(await form.getAttribute('data-order-direct'), 'false');
|
||||
});
|
||||
if (conflict === 'date') {
|
||||
await field(form, 'verified').check();
|
||||
await submit('跨过营业日保留原输入转为审批', page, form, route(id) + '/change');
|
||||
}
|
||||
}
|
||||
|
||||
// 提交已经落库、响应丢失时,复用详情内的恢复按钮及原操作号。
|
||||
await session.day(day);
|
||||
const id = await issue('订单记账回执中断');
|
||||
const page = await open('assistant', id);
|
||||
const form = await legacyForm(page, 'expense');
|
||||
await field(form, 'amount').fill('2.50');
|
||||
await field(form, 'note').fill('账务回执测试');
|
||||
await field(form, 'change_reason').fill('核准凭据');
|
||||
await field(form, 'verified').check();
|
||||
const endpoint = base + route(id) + '/expense';
|
||||
const attempts = [];
|
||||
await page.route(endpoint, async intercepted => {
|
||||
const req = intercepted.request();
|
||||
attempts.push({ key: req.headers()['idempotency-key'], data: req.postDataJSON() });
|
||||
const response = await intercepted.fetch();
|
||||
assert.equal(response.status(), 200, await response.text());
|
||||
await intercepted.abort('failed');
|
||||
});
|
||||
try {
|
||||
await step('订单记账后连续收不到回执', async () => {
|
||||
await form.locator('button.primary').click();
|
||||
await page
|
||||
.locator('#order-dialog')
|
||||
.getByText(/连接中断,提交结果待确认/)
|
||||
.first()
|
||||
.waitFor();
|
||||
assert.equal(attempts.length, 3);
|
||||
assert.ok(attempts[0].key);
|
||||
assert.deepEqual(attempts[1], attempts[0]);
|
||||
assert.deepEqual(attempts[2], attempts[0]);
|
||||
assert.equal(await field(form, 'amount').inputValue(), '2.50');
|
||||
assert.equal(await form.locator('button.primary').isDisabled(), true, '结果待确认时仍可再次保存');
|
||||
});
|
||||
} finally {
|
||||
await page.unroute(endpoint);
|
||||
}
|
||||
await step('从订单详情原样恢复同笔记账', async () => {
|
||||
const retry = page.locator('#order-dialog[open]').getByRole('button', { name: '恢复原操作', exact: true });
|
||||
const [response] = await Promise.all([
|
||||
page.waitForResponse(r => r.url() === endpoint && r.request().method() === 'POST'),
|
||||
retry.click(),
|
||||
]);
|
||||
assert.equal(response.status(), 200);
|
||||
assert.equal(response.request().headers()['idempotency-key'], attempts[0].key);
|
||||
assert.deepEqual(response.request().postDataJSON(), attempts[0].data);
|
||||
await form.waitFor({ state: 'hidden' });
|
||||
assert.equal(await page.locator('#order-dialog[open]').count(), 1);
|
||||
assert.equal(
|
||||
(await session.get('assistant', route(id))).expenses.filter(row => row.note === '账务回执测试').length,
|
||||
1,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
// 以 f1a4e69 中 server/routes/orders.routes.js:141 的通用路由和
|
||||
// core/ledger.js:1949 的业务分支为底册。具体的 /edit、/canceltoday 等由独立路由先匹配。
|
||||
export const orderActionCoverage = {
|
||||
receipt: { step: '旧单信用卡收款并计入手续费' },
|
||||
refund: { step: '助理同日直接登记全额退款' },
|
||||
expense: { step: '助理同日直接登记额外费用' },
|
||||
fees: { step: '旧单补记实际费用及付款人' },
|
||||
cost: { step: '旧单补齐多行料费和工费' },
|
||||
complete: { step: '补齐旧单账务并扣库存' },
|
||||
return: { step: '助理同日整单退回按对货盘', afterSaleStep: '原单售后登记退款和退货' },
|
||||
correct: { step: '店主更正旧单收款流水' },
|
||||
review: { step: '店主复核旧单' },
|
||||
print: { step: '打开订单客户打印预览并登记审计' },
|
||||
confirm: {
|
||||
reason:
|
||||
'旧草稿点「继续填写并开单」后通过 /api/orders/issue 提交,开单事务内执行 confirm。详情没有独立确认草稿按钮。',
|
||||
sources: ['public/app.js:4091', 'public/app.js:7290', 'core/ledger.js:1485'],
|
||||
},
|
||||
deliver: {
|
||||
reason: '已确认旧单点「补齐旧单账务」提交 complete,由该事务内部执行 deliver。详情没有单独的 deliver 按钮。',
|
||||
sources: ['public/app.js:4099', 'core/ledger.js:2162'],
|
||||
},
|
||||
cancel: {
|
||||
reason: '旧 cancel 操作直接返回 409。当前入口依据业务日期提交 canceltoday 或 cancellation。',
|
||||
sources: ['core/ledger.js:1961', 'public/order-cancellations-ui.js:182', 'public/order-cancellations-ui.js:331'],
|
||||
},
|
||||
material: {
|
||||
reason: '服务端保留订单料费重新分配操作。旧详情料费待补的入口打开「每日购料」,详情动作列表没有提交该接口的控件。',
|
||||
sources: ['core/ledger.js:2276', 'public/app.js:4065', 'public/material-pools-ui.js:1649'],
|
||||
},
|
||||
settlement: {
|
||||
reason:
|
||||
'历史双人模式有单笔交款控件,仅在 !teamMode() 显示。正式和演示服务启动时均启用团队模式,个人余额和转账在团队账目、每日对账登记。',
|
||||
sources: ['public/app.js:583', 'public/app.js:4124', 'server/app.js:31', 'core/ledger.js:1959'],
|
||||
},
|
||||
};
|
||||
|
||||
// 普通改单和锁价改单均省略 action,后端按 edit 处理。
|
||||
// 旧版整单退货与原单售后均提交 action=return,由 afterSale 的存在区分。
|
||||
// 对照 public/order-edit-ui.js:1071、public/order-changes-ui.js:529、
|
||||
// public/order-after-sales-ui.js:371 和 domains/orders/order-changes.js:670。
|
||||
export const orderChangeCoverage = {
|
||||
edit: { steps: ['助理申请修改普通订单待批准', '助理申请修改普通订单待驳回', '助理申请修改跨日已交付料池锁价单'] },
|
||||
expense: { steps: ['助理申请跨日额外费用', '跨过营业日保留原输入转为审批'] },
|
||||
fees: { steps: ['助理申请跨日补记旧单费用'] },
|
||||
refund: { steps: ['助理申请跨日实际退款'] },
|
||||
return: { steps: ['助理申请跨日整单退货'], afterSaleSteps: ['助理提交跨日原单售后申请'] },
|
||||
cost: { steps: ['助理申请补录旧单货品成本'] },
|
||||
};
|
||||
|
||||
export function assertOrderChangeBody(step, body) {
|
||||
const [action, record] =
|
||||
Object.entries(orderChangeCoverage).find(([, entry]) =>
|
||||
[...entry.steps, ...(entry.afterSaleSteps || [])].includes(step),
|
||||
) || [];
|
||||
assert.ok(action, '订单变更申请缺少场景映射 ' + step);
|
||||
assert.ok(Number.isSafeInteger(body.revision));
|
||||
assert.ok(body.reason.trim());
|
||||
assert.equal(body.verified, true);
|
||||
assert.match(body.date, /^\d{4}-\d{2}-\d{2}$/);
|
||||
if (action === 'edit') {
|
||||
assert.equal(Object.hasOwn(body, 'action'), false);
|
||||
assert.ok(body.lines.length > 0);
|
||||
if (step === '助理申请修改跨日已交付料池锁价单') assert.ok(body.price_lock_material);
|
||||
return;
|
||||
}
|
||||
assert.equal(body.action, action);
|
||||
if (action === 'return') {
|
||||
if (record.afterSaleSteps.includes(step)) {
|
||||
assert.ok(body.afterSale.lines.length > 0);
|
||||
assert.ok(body.afterSale.refund.account);
|
||||
assert.ok(Object.hasOwn(body.afterSale.refund, 'amount'));
|
||||
assert.ok(Array.isArray(body.afterSale.expenses));
|
||||
} else {
|
||||
assert.equal(Object.hasOwn(body, 'afterSale'), false);
|
||||
assert.ok(body.returnPockets.length > 0);
|
||||
assert.equal(body.returnCounts.length, body.returnPockets.length);
|
||||
}
|
||||
return;
|
||||
}
|
||||
assert.equal(body.reason, body.change_reason.trim());
|
||||
if (action === 'fees') {
|
||||
assert.ok(body.fee_items.length > 0);
|
||||
assert.ok(body.fee_items.every(f => f.payer && Object.hasOwn(f, 'amount')));
|
||||
} else if (action === 'cost') {
|
||||
assert.ok(body.costs.length > 0);
|
||||
assert.ok(body.costs.every(c => c.parts && c.costMaterial && c.costLabor && c.costPayers && c.payer));
|
||||
} else {
|
||||
assert.ok(body.amount);
|
||||
if (action === 'refund') assert.ok(body.account && body.payment_method);
|
||||
if (action === 'expense') assert.ok(body.note && body.payer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
export async function exerciseDeliveredLocks({ day, yesterday, session, post, open, field, action, submit, route }) {
|
||||
// 一张昨日按料池锁价、今日交付的单行单,及一张当日手填进价的多行单。
|
||||
for (const multi of [false, true]) {
|
||||
const date = multi ? day : yesterday;
|
||||
await session.day(date);
|
||||
let pool;
|
||||
if (!multi) {
|
||||
await post('owner', '/api/material-purchases', {
|
||||
date,
|
||||
grams: '4',
|
||||
total: '3600',
|
||||
payer: 'owner',
|
||||
allocations: [{ member: 'owner', amount: '3600' }],
|
||||
note: '锁价单料池',
|
||||
});
|
||||
const preview = await session.get('owner', '/api/material-pools/rolling-preview');
|
||||
await post('owner', '/api/material-pools/rolling-enable', { date, revision: preview.revision, verified: true });
|
||||
pool = await session.get('owner', '/api/material-pools/' + date);
|
||||
}
|
||||
const line = i => ({
|
||||
name: '锁价商品' + i,
|
||||
unit: 'g',
|
||||
quantity: '1',
|
||||
goldPrice: '1000',
|
||||
laborMode: 'gram',
|
||||
laborRate: '0',
|
||||
material: pool
|
||||
? { source: 'pool', poolId: date, revision: pool.revision }
|
||||
: { source: 'manual', rate: '850', payer: 'owner', verified: true },
|
||||
});
|
||||
const { id } = await post('assistant', '/api/price-locks', {
|
||||
date,
|
||||
member: 'assistant',
|
||||
customer: '锁价编辑' + (multi ? '多行' : '单行'),
|
||||
salesperson: '娜娜',
|
||||
customer_type: 'new',
|
||||
internal_note: '#锁价',
|
||||
lines: multi ? [line(1), line(2)] : [line(1)],
|
||||
payment: { amount: multi ? '2000' : '1000', account: '助理微信', verified: true },
|
||||
});
|
||||
await session.day(day);
|
||||
const lock = await session.get('assistant', '/api/price-locks/' + id);
|
||||
const lines = lock.lines.map(row => ({
|
||||
lineId: row.id,
|
||||
quantity: (row.locked_mg / 1000).toFixed(3),
|
||||
laborRate: '0',
|
||||
laborMode: 'gram',
|
||||
payer: 'assistant',
|
||||
costPayers: { material: row.buy_payer, labor: 'assistant' },
|
||||
costParts: { labor: '20', accessories: '2', other: '1' },
|
||||
inventory: { pocket: '现货', original: row.material_source === 'pool' ? 'stocked' : 'receive', extra: 'receive' },
|
||||
extraMaterial: { rate: '900', payer: 'assistant', verified: true },
|
||||
}));
|
||||
const delivered = await post('assistant', '/api/price-locks/' + id + '/deliver', {
|
||||
date: day,
|
||||
revision: lock.revision,
|
||||
verified: true,
|
||||
lines,
|
||||
fee_items: [{ key: 'shipping', amount: '6', payer: 'assistant', note: '快递费' }],
|
||||
});
|
||||
const page = await open(multi ? 'owner' : 'assistant', delivered.id);
|
||||
await action(page, 'edit-order').click();
|
||||
const form = page.locator('#order-edit-meta-form');
|
||||
await form.waitFor();
|
||||
if (!multi) {
|
||||
await field(form, 'lock_material_source').selectOption('manual');
|
||||
await field(form, 'lock_material_rate').fill('880');
|
||||
await field(form, 'lock_material_payer').selectOption('owner');
|
||||
await field(form, 'lock_material_verified').check();
|
||||
}
|
||||
const modes = form.locator('[name=lock_cost_labor_mode]');
|
||||
assert.equal(await modes.count(), multi ? 2 : 1);
|
||||
await modes.last().selectOption('gram');
|
||||
await form.locator('[name=lock_cost_labor_rate]').last().fill('12.50');
|
||||
await field(form, 'internal_note').fill('改正锁价进货资料');
|
||||
await field(form, 'edit_reason').fill('更正锁价工费');
|
||||
await field(form, 'cost_box').check();
|
||||
await field(form, 'edit_verified').check();
|
||||
await submit(
|
||||
multi ? '店主直接修改多行已交付锁价单' : '助理申请修改跨日已交付料池锁价单',
|
||||
page,
|
||||
form,
|
||||
route(delivered.id) + '/' + (multi ? 'edit' : 'change'),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
export async function exerciseOrderReviews({
|
||||
day,
|
||||
yesterday,
|
||||
session,
|
||||
open,
|
||||
field,
|
||||
action,
|
||||
legacyForm,
|
||||
submit,
|
||||
write,
|
||||
route,
|
||||
issue,
|
||||
order,
|
||||
post,
|
||||
}) {
|
||||
const past = [];
|
||||
await session.day(yesterday);
|
||||
for (const name of ['普通改单批准', '普通改单驳回', '申请取消批准', '申请取消驳回', '跨日原单售后'])
|
||||
past.push(await issue(name, yesterday));
|
||||
const oldSale = await issue('历史分步售退', yesterday);
|
||||
const pendingFees = [{ key: 'shipping', note: '寄件费', amount: '4.50', payer: 'assistant', status: 'estimated' }];
|
||||
const oldUnfinished = (
|
||||
await post('assistant', '/api/orders', order('历史费用申请', yesterday, { fee_items: pendingFees }))
|
||||
).id;
|
||||
await post('assistant', route(oldUnfinished) + '/confirm', { date: yesterday });
|
||||
await session.day(day);
|
||||
|
||||
async function edit(actor, id, period, label, reason, endpoint) {
|
||||
const page = await open(actor, id, period);
|
||||
await action(page, 'edit-order').click();
|
||||
const form = page.locator('#order-form[data-order-edit=true]');
|
||||
await field(form, 'customer').fill(label);
|
||||
await field(form, 'edit_reason').fill(reason);
|
||||
await field(form, 'edit_verified').check();
|
||||
await submit(label, page, form, route(id) + '/' + endpoint);
|
||||
}
|
||||
async function decide(id, period, type, decision, label) {
|
||||
const page = await open('owner', id, period);
|
||||
const name = type === 'ownership' ? 'order-ownership-' + decision : decision + '-order-' + type;
|
||||
await action(page, name).click();
|
||||
const form = page.locator('#order-' + type + '-form');
|
||||
await field(form, 'note').fill(decision === 'approve' ? '凭据与原单已核对' : '请补足原凭据');
|
||||
if (decision === 'approve') await field(form, 'verified').check();
|
||||
const endpoints = {
|
||||
ownership: 'order-ownership-changes',
|
||||
change: 'order-changes',
|
||||
cancellation: 'order-cancellations',
|
||||
};
|
||||
await submit(label, page, form, new RegExp('^/api/' + endpoints[type] + '/[^/]+/' + decision + '$'));
|
||||
}
|
||||
const direct = await issue('普通订单直接改');
|
||||
await edit('assistant', direct, 'today', '助理同日直接修改普通订单', '复核客户称呼', 'edit');
|
||||
for (const [i, decision] of ['approve', 'reject'].entries()) {
|
||||
const result = decision === 'approve' ? '批准' : '驳回';
|
||||
await edit('assistant', past[i], 'yesterday', '助理申请修改普通订单待' + result, '补正昨日客户称呼', 'change');
|
||||
await decide(past[i], 'yesterday', 'change', decision, '店主' + result + '普通改单');
|
||||
}
|
||||
for (const [i, decision] of ['approve', 'reject'].entries()) {
|
||||
const result = decision === 'approve' ? '批准' : '驳回';
|
||||
const id = past[i + 2];
|
||||
const page = await open('assistant', id, 'yesterday');
|
||||
await action(page, 'request-order-cancellation').click();
|
||||
const form = page.locator('#order-cancellation-form');
|
||||
await field(form, 'reason').fill('重复录入的昨日订单');
|
||||
await submit('助理提交取消申请待' + result, page, form, route(id) + '/cancellation');
|
||||
await decide(id, 'yesterday', 'cancellation', decision, '店主' + result + '取消订单');
|
||||
}
|
||||
const cancelId = await issue('同日直接作废');
|
||||
let page = await open('assistant', cancelId);
|
||||
await action(page, 'request-order-cancellation').click();
|
||||
let form = page.locator('#order-cancellation-form');
|
||||
assert.equal(await form.getAttribute('data-kind'), 'direct');
|
||||
await field(form, 'reason').fill('同一交易重复登记');
|
||||
await field(form, 'verified').check();
|
||||
await submit('助理同日直接作废订单', page, form, route(cancelId) + '/canceltoday');
|
||||
|
||||
for (const [actor, decision] of [
|
||||
['owner', 'direct'],
|
||||
['assistant', 'approve'],
|
||||
['assistant', 'reject'],
|
||||
]) {
|
||||
const label = { direct: '店主直接更正订单归属', approve: '助理申请改归属待批准', reject: '助理申请改归属待驳回' }[
|
||||
decision
|
||||
];
|
||||
const id = await issue(label);
|
||||
page = await open(actor, id);
|
||||
await action(page, 'order-ownership-request').click();
|
||||
form = page.locator('#order-ownership-form');
|
||||
await field(form, 'member').selectOption('assistant2');
|
||||
await field(form, 'reason').fill('核正接单员工');
|
||||
await field(form, 'verified').check();
|
||||
await submit(label, page, form, route(id) + '/ownership');
|
||||
if (decision !== 'direct')
|
||||
await decide(
|
||||
id,
|
||||
'today',
|
||||
'ownership',
|
||||
decision,
|
||||
'店主' + (decision === 'approve' ? '批准' : '驳回') + '归属变更',
|
||||
);
|
||||
}
|
||||
// 原单售后的跨日操作经订单变更复核,批准时才冲回库存与实际收入。
|
||||
const id = past[4];
|
||||
page = await open('assistant', id, 'yesterday');
|
||||
await action(page, 'order-after-sale-open').click();
|
||||
form = page.locator('#order-after-sale-form');
|
||||
await field(form, 'reason').fill('跨日退货并核实货款');
|
||||
await write(
|
||||
'助理跨日原单售后试算',
|
||||
page,
|
||||
route(id) + '/after-sale-preview',
|
||||
() => action(page, 'order-after-sale-preview').click(),
|
||||
() => form.getByText('预览已更新,请核对后勾选确认。').waitFor(),
|
||||
);
|
||||
await field(form, 'verified').check();
|
||||
await submit('助理提交跨日原单售后申请', page, form, route(id) + '/change');
|
||||
await decide(id, 'yesterday', 'change', 'approve', '店主批准跨日原单售后');
|
||||
|
||||
// 旧版分步办理的费用、退货和退款各有不同的申请字段及落账时间。
|
||||
for (const [kind, title, target] of [
|
||||
['fees', '补记旧单费用', oldUnfinished],
|
||||
['expense', '额外费用', oldSale],
|
||||
['return', '整单退货', oldSale],
|
||||
['refund', '实际退款', oldSale],
|
||||
]) {
|
||||
page = await open('assistant', target, 'yesterday');
|
||||
form = await legacyForm(page, kind);
|
||||
if (kind === 'fees') await field(form, 'verifiedAmount').fill('5.60');
|
||||
if (kind === 'expense') {
|
||||
await field(form, 'amount').fill('3.75');
|
||||
await field(form, 'note').fill('补登实际支出');
|
||||
}
|
||||
await field(form, kind === 'return' ? 'reason' : 'change_reason').fill('核实跨日' + title);
|
||||
await field(form, 'verified').check();
|
||||
await submit('助理申请跨日' + title, page, form, route(target) + '/change');
|
||||
await decide(target, 'yesterday', 'change', 'approve', '店主批准跨日' + title);
|
||||
}
|
||||
// 历史已确认订单中的货品成本由助理提请复核,尚未发生成交也可补齐。
|
||||
const confirmed = (await post('assistant', '/api/orders', order('历史成本申请'))).id;
|
||||
await post('assistant', route(confirmed) + '/confirm', { date: day });
|
||||
page = await open('assistant', confirmed);
|
||||
await action(page, 'show-cost').click();
|
||||
form = page.locator('#action-form[data-kind=cost]');
|
||||
await field(form, 'cost-0-labor').fill('61.50');
|
||||
await field(form, 'change_reason').fill('补录历史进货工费');
|
||||
await field(form, 'verified').check();
|
||||
await submit('助理申请补录旧单货品成本', page, form, route(confirmed) + '/change');
|
||||
await decide(confirmed, 'today', 'change', 'approve', '店主批准补录旧单成本');
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { assertOrderChangeBody } from './orders-coverage.mjs';
|
||||
import { exerciseOrderConflicts } from './orders-conflicts.mjs';
|
||||
import { exerciseOrderReviews } from './orders-reviews.mjs';
|
||||
import { exerciseDeliveredLocks } from './orders-locks.mjs';
|
||||
|
||||
export default async function orders({ version, base, day, session, pageFor, step, passwords }) {
|
||||
const yesterday = '2026-11-19';
|
||||
const entry = base + (version === 'old' ? '/' : '/next/');
|
||||
const pages = {};
|
||||
const route = id => '/api/orders/' + id;
|
||||
const field = (form, name) => form.locator('[name="' + name + '"]').first();
|
||||
const action = (page, name) => page.locator('[data-action="' + name + '"]:visible').first();
|
||||
const detail = page => page.locator('#order-dialog[open]');
|
||||
const post = async (actor, path, data) => {
|
||||
const response = await session.postRaw(actor, path, data);
|
||||
assert.equal(response.status, 200, path + ' ' + JSON.stringify(response.body));
|
||||
return response.body;
|
||||
};
|
||||
const order = (customer, date = day, extra = {}) => ({
|
||||
date,
|
||||
customer,
|
||||
customer_type: 'new',
|
||||
member: 'assistant',
|
||||
internal_note: '订单写入对照',
|
||||
salesperson: '娜娜',
|
||||
payment_account: '助理支付宝',
|
||||
rounding_mode: 'cent',
|
||||
lines: [
|
||||
{
|
||||
name: '足金项链',
|
||||
unit: 'g',
|
||||
quantity: '1.5',
|
||||
pocket: '现货',
|
||||
payer: 'assistant',
|
||||
sale: '1000',
|
||||
costParts: { material: '720', labor: '58', accessories: '2', other: '4' },
|
||||
costPayers: { material: 'assistant2', labor: 'assistant' },
|
||||
},
|
||||
],
|
||||
fee_items: [],
|
||||
...extra,
|
||||
});
|
||||
const issue = async (name, date = day) => (await post('assistant', '/api/orders/issue', order(name, date))).id;
|
||||
async function open(actor, id, period = 'today') {
|
||||
const page = (pages[actor] ||= await pageFor(actor));
|
||||
await page.goto(entry);
|
||||
await page
|
||||
.locator('nav:visible')
|
||||
.locator(version === 'old' ? '[data-tab="orders"]' : 'a[href="/next/orders"]')
|
||||
.first()
|
||||
.click();
|
||||
await action(page, 'order-period').waitFor();
|
||||
await page
|
||||
.locator('[data-action="order-period"][data-period="' + period + '"]:visible')
|
||||
.first()
|
||||
.click();
|
||||
await page
|
||||
.locator('[data-action="open-order"][data-id="' + id + '"]:visible')
|
||||
.first()
|
||||
.click();
|
||||
await detail(page).locator('.order-detail-identifiers').waitFor();
|
||||
return page;
|
||||
}
|
||||
async function write(label, page, endpoint, click, after) {
|
||||
await step(label, async () => {
|
||||
const [result] = await Promise.all([
|
||||
page.waitForResponse(
|
||||
r =>
|
||||
r.request().method() === 'POST' &&
|
||||
(typeof endpoint === 'string'
|
||||
? new URL(r.url()).pathname === endpoint
|
||||
: endpoint.test(new URL(r.url()).pathname)),
|
||||
),
|
||||
click(),
|
||||
]);
|
||||
assert.equal(result.status(), 200, label + ' ' + (await result.text()).slice(0, 500));
|
||||
if (/^\/api\/orders\/[^/]+\/change$/.test(new URL(result.url()).pathname))
|
||||
assertOrderChangeBody(label, result.request().postDataJSON());
|
||||
if (after) await after();
|
||||
await page.waitForLoadState('networkidle');
|
||||
});
|
||||
}
|
||||
async function submit(label, page, form, endpoint) {
|
||||
await write(
|
||||
label,
|
||||
page,
|
||||
endpoint,
|
||||
() => form.locator('button[type="submit"], button.primary:not([type])').first().click(),
|
||||
() => form.waitFor({ state: 'hidden' }),
|
||||
);
|
||||
}
|
||||
async function legacyForm(page, kind) {
|
||||
if (kind === 'return') {
|
||||
const details = detail(page).locator('details.order-legacy-actions:not([open]) > summary');
|
||||
if (await details.count()) await details.click();
|
||||
}
|
||||
await action(page, 'show-' + kind).click();
|
||||
const form = page.locator('#action-form[data-kind="' + kind + '"]');
|
||||
await form.waitFor();
|
||||
return form;
|
||||
}
|
||||
const helpers = {
|
||||
day,
|
||||
yesterday,
|
||||
session,
|
||||
post,
|
||||
open,
|
||||
field,
|
||||
action,
|
||||
write,
|
||||
submit,
|
||||
legacyForm,
|
||||
route,
|
||||
issue,
|
||||
order,
|
||||
step,
|
||||
base,
|
||||
passwords,
|
||||
};
|
||||
|
||||
await post('owner', '/api/stock', {
|
||||
date: yesterday,
|
||||
kind: 'opening',
|
||||
pocket: '现货',
|
||||
grams: '100',
|
||||
note: '订单对照库存期初',
|
||||
});
|
||||
await post('owner', '/api/pockets', { name: '订单对数盘', countUnit: 'pair', initialCount: 0, countVerified: true });
|
||||
const historical = order('旧单补账');
|
||||
historical.lines.push({
|
||||
name: '银饰',
|
||||
unit: '件',
|
||||
quantity: '1',
|
||||
pocket: '',
|
||||
payer: 'owner',
|
||||
sale: '100',
|
||||
costParts: { material: '30', labor: '5', accessories: '0', other: '0' },
|
||||
costPayers: { material: 'owner', labor: 'assistant' },
|
||||
});
|
||||
historical.fee_items = [{ key: 'shipping', note: '快递费', payer: 'assistant', amount: '5', status: 'estimated' }];
|
||||
const id = (await post('assistant', '/api/orders', historical)).id;
|
||||
await post('assistant', route(id) + '/confirm', { date: day });
|
||||
const owner = await open('owner', id);
|
||||
let form = await legacyForm(owner, 'cost');
|
||||
await field(form, 'cost-0-materialMode').selectOption('gram');
|
||||
await field(form, 'cost-0-materialRate').fill('480.85');
|
||||
await field(form, 'cost-0-laborMode').selectOption('gram');
|
||||
await field(form, 'cost-0-laborRate').fill('10.10');
|
||||
await field(form, 'cost-1-accessories').fill('2.50');
|
||||
assert.equal(await field(form, 'cost-0-material').inputValue(), '721.28');
|
||||
await field(form, 'cost-0-materialMode').selectOption('total');
|
||||
assert.equal(await field(form, 'cost-0-material').inputValue(), '720.00');
|
||||
await submit('旧单补齐多行料费和工费', owner, form, route(id) + '/cost');
|
||||
form = await legacyForm(owner, 'fees');
|
||||
await field(form, 'verifiedAmount').fill('6.50');
|
||||
await field(form, 'verifiedPayer').selectOption('owner');
|
||||
await field(form, 'verified').check();
|
||||
await submit('旧单补记实际费用及付款人', owner, form, route(id) + '/fees');
|
||||
form = await legacyForm(owner, 'receipt');
|
||||
await field(form, 'payment_recipient').selectOption('助理2');
|
||||
await field(form, 'payment_method').selectOption('信用卡');
|
||||
assert.equal(await field(form, 'payment_recipient').isDisabled(), true);
|
||||
await field(form, 'payment_method').selectOption('微信');
|
||||
assert.equal(await field(form, 'payment_recipient').inputValue(), '助理2');
|
||||
await field(form, 'payment_method').selectOption('信用卡');
|
||||
await field(form, 'credit_card_fee_payer').selectOption('assistant2');
|
||||
await field(form, 'verified').check();
|
||||
await submit('旧单信用卡收款并计入手续费', owner, form, route(id) + '/receipt');
|
||||
form = await legacyForm(owner, 'correct');
|
||||
await field(form, 'account').selectOption('麦麦信用卡');
|
||||
await field(form, 'amount').fill('1100');
|
||||
await field(form, 'credit_card_fee_payer').selectOption('owner');
|
||||
await field(form, 'reason').fill('核正手续费付款人');
|
||||
await field(form, 'verified').check();
|
||||
await submit('店主更正旧单收款流水', owner, form, route(id) + '/correct');
|
||||
form = await legacyForm(owner, 'complete');
|
||||
await field(form, 'verified').check();
|
||||
await submit('补齐旧单账务并扣库存', owner, form, route(id) + '/complete');
|
||||
form = await legacyForm(owner, 'review');
|
||||
await submit('店主复核旧单', owner, form, route(id) + '/review');
|
||||
let preview;
|
||||
await write('打开订单客户打印预览并登记审计', owner, route(id) + '/print', async () => {
|
||||
[preview] = await Promise.all([owner.context().waitForEvent('page'), action(owner, 'print').click()]);
|
||||
});
|
||||
await write(
|
||||
'订单客户点击打印并更新打印状态',
|
||||
preview,
|
||||
'/api/print-status/order/' + id,
|
||||
() => preview.locator('#print').click(),
|
||||
() => preview.getByText('✓ 已打印', { exact: true }).waitFor(),
|
||||
);
|
||||
await preview.close();
|
||||
const assistant = await open('assistant', id);
|
||||
form = await legacyForm(assistant, 'expense');
|
||||
await field(form, 'amount').fill('3.12');
|
||||
await field(form, 'note').fill('补记费用');
|
||||
await field(form, 'change_reason').fill('已核实旧单');
|
||||
await field(form, 'verified').check();
|
||||
await field(form, 'date').fill(yesterday);
|
||||
assert.equal(await field(form, 'verified').isChecked(), false);
|
||||
assert.equal(await form.getAttribute('data-order-direct'), 'false');
|
||||
await field(form, 'date').fill(day);
|
||||
await field(form, 'verified').check();
|
||||
await submit('助理同日直接登记额外费用', assistant, form, route(id) + '/expense');
|
||||
form = await legacyForm(assistant, 'return');
|
||||
const pair = await field(form, 'return-0').locator('option').filter({ hasText: '订单对数盘' }).getAttribute('value');
|
||||
await field(form, 'return-0').selectOption(pair);
|
||||
await field(form, 'returnCount-0').fill('2');
|
||||
await field(form, 'return-0').selectOption('现货');
|
||||
assert.equal(await field(form, 'returnCount-0').isDisabled(), true);
|
||||
await field(form, 'return-0').selectOption(pair);
|
||||
await field(form, 'reason').fill('核实实物和对数');
|
||||
await field(form, 'verified').check();
|
||||
await submit('助理同日整单退回按对货盘', assistant, form, route(id) + '/return');
|
||||
form = await legacyForm(assistant, 'refund');
|
||||
await field(form, 'change_reason').fill('已核实退款');
|
||||
await field(form, 'verified').check();
|
||||
await submit('助理同日直接登记全额退款', assistant, form, route(id) + '/refund');
|
||||
|
||||
const sale = await issue('原单售后扣款');
|
||||
await open('owner', sale);
|
||||
await action(owner, 'order-after-sale-open').click();
|
||||
const after = owner.locator('#order-after-sale-form');
|
||||
await field(after, 'reason').fill('实物已退回');
|
||||
await field(after, 'refund_amount').fill('990');
|
||||
await field(after, 'deduction_reason').fill('约定扣回邮费');
|
||||
await action(owner, 'order-after-sale-add-expense').click();
|
||||
await field(after, 'expense_note').fill('退件运费');
|
||||
await field(after, 'expense_amount').fill('6.50');
|
||||
await write(
|
||||
'原单售后试算扣款与费用',
|
||||
owner,
|
||||
route(sale) + '/after-sale-preview',
|
||||
() => action(owner, 'order-after-sale-preview').click(),
|
||||
() => after.getByText('预览已更新,请核对后勾选确认。').waitFor(),
|
||||
);
|
||||
await field(after, 'verified').check();
|
||||
await submit('原单售后登记退款和退货', owner, after, route(sale) + '/return');
|
||||
await exerciseOrderReviews(helpers);
|
||||
await exerciseDeliveredLocks(helpers);
|
||||
await exerciseOrderConflicts(helpers);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { compare } from '../lib/diff.js';
|
||||
import { dumpDatabase } from '../lib/db-dump.js';
|
||||
|
||||
export function readOnlyPost(endpoint) {
|
||||
if (endpoint === '/api/material-pools/quote') return '料池报价';
|
||||
if (endpoint === '/api/recoveries/quote') return '回收报价';
|
||||
if (/^\/api\/recoveries\/[^/]+\/quote$/.test(endpoint)) return '更正回收报价';
|
||||
if (/^\/api\/orders\/[^/]+\/after-sale-preview$/.test(endpoint)) return '订单售后预览';
|
||||
return '';
|
||||
}
|
||||
|
||||
// 浏览器可能在报价同时保存另一笔单。取当时的 SQLite 一致性副本,在独占副本上
|
||||
// 重放已经由 UI 实际发出的报价,核对全部表。业务用例在同一输入条件下另行比对两版报价。副本与请求头只保存在本次临时环境。
|
||||
export class ReadOnlyChecks {
|
||||
constructor(dir) {
|
||||
this.dir = dir;
|
||||
this.samples = new Map();
|
||||
}
|
||||
begin(kind, req) {
|
||||
if (!kind || this.samples.has(kind)) return;
|
||||
const dir = fs.mkdtempSync(path.join(this.dir, 'quote-'));
|
||||
const db = new DatabaseSync(path.join(this.dir, 'ledger.sqlite'), { readOnly: true });
|
||||
try {
|
||||
db.prepare('VACUUM INTO ?').run(path.join(dir, 'ledger.sqlite'));
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
return { dir, kind, path: new URL(req.url()).pathname, data: req.postData(), headers: req.allHeaders() };
|
||||
}
|
||||
finish(sample, res) {
|
||||
if (sample && res.status() === 200 && !this.samples.has(sample.kind)) {
|
||||
this.samples.set(sample.kind, sample);
|
||||
}
|
||||
}
|
||||
async verify(launch, clockStart) {
|
||||
for (const sample of this.samples.values()) {
|
||||
const server = launch({ dataDir: sample.dir, clockStart });
|
||||
try {
|
||||
const { base } = await server.ready();
|
||||
const filename = path.join(sample.dir, 'ledger.sqlite');
|
||||
const before = dumpDatabase(filename);
|
||||
const headers = await sample.headers;
|
||||
const res = await fetch(base + sample.path, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
origin: base,
|
||||
'content-type': 'application/json',
|
||||
'x-requested-with': headers['x-requested-with'],
|
||||
cookie: headers.cookie,
|
||||
...(headers['x-ledger-user'] ? { 'x-ledger-user': headers['x-ledger-user'] } : {}),
|
||||
},
|
||||
body: sample.data,
|
||||
});
|
||||
assert.equal(res.status, 200, sample.kind + ' 重放失败');
|
||||
await res.arrayBuffer();
|
||||
const difference = compare(before, dumpDatabase(filename)).diffs[0];
|
||||
assert.ok(!difference, sample.kind + ' 改写数据库 ' + difference?.path);
|
||||
} finally {
|
||||
await server.stop();
|
||||
}
|
||||
}
|
||||
return Array.from(this.samples.keys());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { section } from './operations-helpers.mjs';
|
||||
|
||||
export default async function recoveryQuote(ctx) {
|
||||
const { day, session } = ctx;
|
||||
await session.post('owner', '/api/recoveries', {
|
||||
date: day,
|
||||
mode: 'direct',
|
||||
customer: '个人回收料来源',
|
||||
member: 'owner',
|
||||
salesperson: '麦麦',
|
||||
old_lines: [{ name: '旧料', incoming_weight: '0.400', melted_weight: '0.400', purity: '100' }],
|
||||
buy_rate: '800',
|
||||
payer: 'owner',
|
||||
payment_account: '麦麦微信',
|
||||
verified: true,
|
||||
});
|
||||
await session.post('owner', '/api/material-purchases', {
|
||||
date: day,
|
||||
grams: '8',
|
||||
total: '7200',
|
||||
payer: 'owner',
|
||||
note: '公共料来源',
|
||||
});
|
||||
assert.deepEqual(session.problems, []);
|
||||
const owner = await ctx.pageFor('owner');
|
||||
await section(owner, ctx, 'recoveries');
|
||||
await owner.locator('[data-action=recovery-mode][data-mode=exchange]').click();
|
||||
const form = owner.locator('#recovery-form');
|
||||
const field = name => form.locator('[name="' + name + '"]');
|
||||
await ctx.step('置换试算列出个人和公共料各自的用量、成本与前后余额', async () => {
|
||||
await field('customer').fill('核对两种扣料来源');
|
||||
await form.locator('[name=customer_type][value=new]').check();
|
||||
await field('incoming_weight').fill('2');
|
||||
await field('new_quantity').fill('3');
|
||||
await field('gold_price').fill('920');
|
||||
await field('cost_labor_value').fill('15');
|
||||
await field('labor_rate').fill('20');
|
||||
await field('material_source').selectOption('pool');
|
||||
await field('material_pool_id').selectOption(day);
|
||||
await owner
|
||||
.locator('#recovery-quote-status')
|
||||
.getByText(/结算已核对/)
|
||||
.waitFor();
|
||||
const shown = await owner.locator('#recovery-material-note').innerText();
|
||||
const expected = [
|
||||
'麦麦个人回收料 0.400g · ¥320.00(加权约 ¥800.00/克)',
|
||||
'公共料 0.600g · ¥540.00(加权约 ¥900.00/克)',
|
||||
'本次前可用:个人 0.400g,公共 8.000g',
|
||||
'本次后余:个人回收料 0.000g,公共料 7.400g',
|
||||
];
|
||||
assert.deepEqual(
|
||||
expected.filter(part => !shown.includes(part)),
|
||||
[],
|
||||
'实际置换料池试算:' + shown,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { action, navigate, write, fill, submit } from './ui.mjs';
|
||||
export default async function report(ctx) {
|
||||
const owner = await ctx.pageFor('owner');
|
||||
const staff = await ctx.pageFor('assistant');
|
||||
async function formSubmit(page, form, label, suffix) {
|
||||
return ctx.step(label, async () => {
|
||||
const [res] = await Promise.all([
|
||||
page.waitForResponse(r => r.request().method() === 'POST' && new URL(r.url()).pathname.endsWith(suffix)),
|
||||
submit(form),
|
||||
]);
|
||||
assert.equal(res.status(), 200, label + ' ' + (await res.text()));
|
||||
await page.waitForLoadState('networkidle');
|
||||
});
|
||||
}
|
||||
for (const [page, role] of [
|
||||
[staff, '店员'],
|
||||
[owner, '店主'],
|
||||
]) {
|
||||
await navigate(page, ctx.version, 'report');
|
||||
await action(page, 'reimbursement-new').click();
|
||||
const form = page.locator('#reimbursement-form');
|
||||
await fill(form, { itemName: role + '运费', itemAmount: '12.30' });
|
||||
await write(ctx, page, role + '新增报销', '/api/reimbursements', () => submit(form));
|
||||
await action(page, 'reimbursement-edit').click();
|
||||
await fill(form, { itemAmount: '12.35' });
|
||||
await formSubmit(page, form, role + '修改报销', '/update');
|
||||
}
|
||||
for (const [verb, title] of [
|
||||
['reject', '驳回'],
|
||||
['approve', '同意'],
|
||||
]) {
|
||||
await action(owner, 'reimbursement-' + verb).click();
|
||||
const form = owner.locator('#reimbursement-review-form');
|
||||
if (verb === 'reject') await fill(form, { note: '缺少原票' });
|
||||
else await form.locator('[name=verified]').check();
|
||||
await formSubmit(owner, form, title + '报销', '/' + verb);
|
||||
}
|
||||
// 服务端启动即迁移为团队账本。完整对外支出只在旧双人账务模式渲染。
|
||||
assert.equal(await owner.locator('#daily-outlay-form').count(), 0);
|
||||
await write(ctx, owner, '保存当日对账', '/api/close', () => action(owner, 'close-day').click());
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
{
|
||||
"setup": [
|
||||
"/api/setup",
|
||||
"/api/login",
|
||||
"/api/demo-login",
|
||||
"/api/logout"
|
||||
],
|
||||
"settings": [
|
||||
"/api/password",
|
||||
"/api/shop-settings",
|
||||
"/api/printing",
|
||||
"/api/employees",
|
||||
"/api/employees/:member(member)/:action(update|deactivate|reactivate|delete)",
|
||||
"/api/team-members/:member(member)/password",
|
||||
"/api/backup",
|
||||
"/api/sync"
|
||||
],
|
||||
"operations": [
|
||||
"/api/pockets",
|
||||
"/api/pockets/:key/update",
|
||||
"/api/inventory/movements/:id(uuid)/update",
|
||||
"/api/inventory/movements/:id(uuid)/delete",
|
||||
"/api/inventory/changes/:id(uuid)/:decision(approve|reject)",
|
||||
"/api/inventory/review",
|
||||
"/api/stock",
|
||||
"/api/customer-materials",
|
||||
"/api/recoveries",
|
||||
"/api/recoveries/quote",
|
||||
"/api/recoveries/:id(uuid)/update",
|
||||
"/api/recoveries/:id(uuid)/cancel",
|
||||
"/api/recoveries/:id(uuid)/quote",
|
||||
"/api/recovery-changes/:id(uuid)/:decision(approve|reject)",
|
||||
"/api/private-operations",
|
||||
"/api/private-operations/people",
|
||||
"/api/people-count-history"
|
||||
],
|
||||
"create": [
|
||||
"/api/order-templates",
|
||||
"/api/order-templates/:id(uuid)/update",
|
||||
"/api/order-templates/:id(uuid)/delete"
|
||||
],
|
||||
"orders": [
|
||||
"/api/orders/:id(hexid)/after-sale-preview",
|
||||
"/api/orders",
|
||||
"/api/orders/:id(hexid)/ownership",
|
||||
"/api/orders/:id(hexid)/change",
|
||||
"/api/orders/:id(hexid)/cancellation",
|
||||
"/api/orders/:id(hexid)/canceltoday",
|
||||
"/api/orders/:id(hexid)/edit",
|
||||
"/api/orders/:id(hexid)/:action(word)",
|
||||
"/api/order-changes/:id(uuid)/:decision(approve|reject)",
|
||||
"/api/order-ownership-changes/:id(uuid)/:decision(approve|reject)",
|
||||
"/api/order-cancellations/:id(uuid)/:decision(approve|reject)",
|
||||
"/api/print-status/:kind(order|recovery)/:id(uuid)"
|
||||
],
|
||||
"issue": [
|
||||
"/api/orders/issue"
|
||||
],
|
||||
"funds": [
|
||||
"/api/after-sales/changes/:id(uuid)/:decision(approve|reject)",
|
||||
"/api/after-sales",
|
||||
"/api/after-sales/:id(uuid)/update",
|
||||
"/api/price-locks",
|
||||
"/api/price-locks/:id(hexid)/deliver",
|
||||
"/api/price-locks/:id(hexid)/edit",
|
||||
"/api/price-locks/:id(hexid)/cancel",
|
||||
"/api/price-locks/:id(hexid)/change-requests",
|
||||
"/api/price-lock-changes/:id(uuid)/:decision(approve|reject)",
|
||||
"/api/material-pools/rolling-enable",
|
||||
"/api/material-pools/quote",
|
||||
"/api/material-pools/:date(day)/settlement",
|
||||
"/api/material-purchase-changes/:id(uuid)/:decision(approve|reject)",
|
||||
"/api/material-purchases",
|
||||
"/api/material-purchases/:id(hexid)/edit",
|
||||
"/api/material-purchases/:id(hexid)/delete",
|
||||
"/api/material-purchases/:id(uuid)/change",
|
||||
"/api/team-funds/transfers",
|
||||
"/api/team-funds/transfer"
|
||||
],
|
||||
"report": [
|
||||
"/api/close",
|
||||
"/api/reimbursements",
|
||||
"/api/reimbursements/:id(uuid)/:action(update|approve|reject)"
|
||||
],
|
||||
"history": [
|
||||
"/api/people-count",
|
||||
"/api/daily-funds/confirm"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
import { action, navigate, write, fill, submit } from './ui.mjs';
|
||||
|
||||
export default async function settings(ctx) {
|
||||
const owner = await ctx.pageFor('owner');
|
||||
await navigate(owner, ctx.version, 'settings');
|
||||
const cost = owner.locator('#shop-cost-form');
|
||||
await action(owner, 'shop-cost-add').click();
|
||||
await fill(cost, { name: '对照测试成本', amount: ctx.prove && ctx.version === 'new' ? '3.22' : '3.21' });
|
||||
await write(ctx, owner, '新增成本配置', '/api/shop-settings', () => submit(cost));
|
||||
const costRow = owner.locator('[data-cost-row]').filter({ hasText: '对照测试成本' });
|
||||
await action(costRow, 'shop-cost-edit').click();
|
||||
await fill(cost, { amount: '3.23' });
|
||||
await write(ctx, owner, '修改成本配置', '/api/shop-settings', () => submit(cost));
|
||||
await action(costRow, 'shop-cost-delete').click();
|
||||
await write(ctx, owner, '删除成本配置', '/api/shop-settings', () => submit(cost));
|
||||
|
||||
await action(owner, 'employee-reload').click();
|
||||
await owner.waitForLoadState('networkidle');
|
||||
await action(owner, 'employee-add').click();
|
||||
const employee = owner.locator('#employee-form');
|
||||
const password = 'ledger-fixture-employee-password';
|
||||
await fill(employee, { label: '测试员工', operatorName: '测试开单人', loginName: '13900000019', password });
|
||||
await write(ctx, owner, '新增员工', '/api/employees', () => submit(employee));
|
||||
const row = owner.locator('[data-employee]').filter({ hasText: '测试员工' });
|
||||
const member = await row.getAttribute('data-employee');
|
||||
const checkPasswordStorage = async () =>
|
||||
assert.equal(
|
||||
await owner.evaluate(
|
||||
p => [localStorage, sessionStorage].some(s => Object.values(s).some(value => value.includes(p))),
|
||||
password,
|
||||
),
|
||||
false,
|
||||
);
|
||||
await checkPasswordStorage();
|
||||
await action(row, 'employee-edit').click();
|
||||
await fill(employee, { operatorName: '新开单人' });
|
||||
const endpoint = '/api/employees/' + member + '/';
|
||||
await write(ctx, owner, '修改员工', endpoint + 'update', () => submit(employee));
|
||||
for (const [verb, title] of [
|
||||
['deactivate', '停用'],
|
||||
['reactivate', '恢复'],
|
||||
['delete', '删除'],
|
||||
]) {
|
||||
await action(row, 'employee-' + verb).click();
|
||||
const form = owner.locator('#employee-status-form');
|
||||
await form.locator('[name=verified]').check();
|
||||
await write(ctx, owner, title + '员工', endpoint + verb, () => submit(form));
|
||||
}
|
||||
const shop = owner.locator('#shop-settings-form'),
|
||||
print = owner.locator('#print-settings');
|
||||
await fill(shop, { storeName: '迁移对照店铺' });
|
||||
await fill(print, { rows: '8' });
|
||||
await write(ctx, owner, '保存店铺名称', '/api/shop-settings', () => submit(shop));
|
||||
assert.equal(await print.locator('[name=rows]').inputValue(), '8');
|
||||
await write(ctx, owner, '保存打印设置', '/api/printing', () => owner.locator('button[form=print-settings]').click());
|
||||
await ctx.step('备份并下载完整账本', async () => {
|
||||
const [file] = await Promise.all([owner.waitForEvent('download'), action(owner, 'backup').click()]);
|
||||
assert.match(file.suggestedFilename(), /\.sqlite$/);
|
||||
const filePath = await file.path();
|
||||
assert.ok(fs.statSync(filePath).size);
|
||||
const db = new DatabaseSync(filePath, { readOnly: true });
|
||||
try {
|
||||
assert.equal(db.prepare('PRAGMA integrity_check').get().integrity_check, 'ok');
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
await owner.waitForLoadState('networkidle');
|
||||
});
|
||||
const sync = action(owner, 'sync');
|
||||
const result = await write(ctx, owner, '手动同步', '/api/sync', () => sync.click());
|
||||
assert.match(result.error, /逐笔对照模拟同步失败/);
|
||||
await owner
|
||||
.getByText(/逐笔对照模拟同步失败/)
|
||||
.first()
|
||||
.waitFor();
|
||||
|
||||
const staff = await ctx.pageFor('assistant');
|
||||
await navigate(staff, ctx.version, 'settings');
|
||||
const form = staff.locator('#password-form');
|
||||
await fill(form, { current: ctx.passwords.assistant, password: 'changed-parity-password' });
|
||||
await write(ctx, staff, '店员修改密码', '/api/password', () => submit(form));
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { fill, write } from './ui.mjs';
|
||||
export async function logout(ctx, page, label) {
|
||||
await write(ctx, page, label, '/api/logout', () =>
|
||||
page.locator(ctx.version === 'old' ? '[data-action=logout]' : '.logout-button').click(),
|
||||
);
|
||||
}
|
||||
export async function login(ctx, page, role, label, password) {
|
||||
if (ctx.version === 'old') await page.locator('#login-form [name=member]').selectOption(role);
|
||||
else {
|
||||
await page.getByTestId('login-member').locator('.ant-select-selector').click();
|
||||
await page.locator('.ant-select-item-option').filter({ hasText: label }).first().click();
|
||||
}
|
||||
await page.locator('[name=password]:visible').fill(password);
|
||||
await write(ctx, page, role + '从登录页进入', '/api/login', () =>
|
||||
page.getByRole('button', { name: /^登\s*录$/ }).click(),
|
||||
);
|
||||
await page.locator(ctx.version === 'old' ? '[data-action=logout]' : '.logout-button').waitFor();
|
||||
}
|
||||
export default async function setup(ctx) {
|
||||
const page = await ctx.pageFor('guest');
|
||||
await fill(page, {
|
||||
storeName: '试用对照店铺',
|
||||
ownerLabel: '店主甲',
|
||||
ownerLoginName: 'owner',
|
||||
ownerPassword: ctx.passwords.owner,
|
||||
});
|
||||
await write(ctx, page, '空库初始化', '/api/setup', () => page.getByRole('button', { name: '建立试用账号' }).click());
|
||||
await logout(ctx, page, '新店主退出');
|
||||
await login(ctx, page, 'owner', '店主甲', ctx.passwords.owner);
|
||||
assert.equal((await page.context().cookies()).filter(c => c.name === 'mm_session').length, 1);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// 只用于这一个启用同步的临时账套。令飞书验证返回可控错误,核对页面反馈。
|
||||
const assert = require('node:assert/strict');
|
||||
global.fetch = async function (url) {
|
||||
assert.equal(String(url), 'https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal');
|
||||
return Response.json({ code: 12345, msg: '逐笔对照模拟同步失败' });
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import assert from 'node:assert/strict';
|
||||
export function action(page, key) {
|
||||
return page.locator('[data-action="' + key + '"]:visible').first();
|
||||
}
|
||||
export async function navigate(page, version, key) {
|
||||
const selector = version === 'old' ? '[data-tab="' + key + '"]' : 'a[href="/next/' + key + '"]';
|
||||
await page.locator('nav:visible').locator(selector).first().click();
|
||||
await page.waitForLoadState('networkidle');
|
||||
}
|
||||
export async function fill(form, fields) {
|
||||
for (const [name, value] of Object.entries(fields)) await form.locator('[name="' + name + '"]').fill(value);
|
||||
}
|
||||
export function submit(form) {
|
||||
return form.locator('button[type=submit], button:not([type])').filter({ visible: true }).last().click();
|
||||
}
|
||||
export function write(ctx, page, label, endpoint, trigger, status = 200) {
|
||||
return ctx.step(label, async () => {
|
||||
const [response] = await Promise.all([
|
||||
page.waitForResponse(r => r.request().method() === 'POST' && new URL(r.url()).pathname === endpoint),
|
||||
trigger(),
|
||||
]);
|
||||
assert.equal(response.status(), status, label);
|
||||
await page.waitForLoadState('networkidle');
|
||||
return response.json();
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user