Files
weiguang-jewelry-ledger/新账系统/test/team-privacy-http.test.js
T

149 lines
20 KiB
JavaScript
Raw Normal View History

'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),{randomUUID}=require('node:crypto');
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {Ledger,today}=require('../ledger'),{createApp,createUser}=require('../server');
const password='synthetic-team-password-2026';
async function fixture(t){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-team-privacy-')),ledger=new Ledger(':memory:');
for(const [member,name,role] of [['owner','麦麦','owner'],['assistant','助理','assistant'],['assistant2','助理2','assistant']])createUser(ledger,name,role,password,member);
const app=createApp({mode:'trial',dataDir:dir,ledger,port:0,feishuConfig:{enabled:false}});
await new Promise(resolve=>app.server.listen(0,'127.0.0.1',resolve));
t.after(async()=>{await new Promise(resolve=>app.server.close(resolve));ledger.close();fs.rmSync(dir,{recursive:true,force:true});});
const base='http://127.0.0.1:'+app.server.address().port,cookies={};
const call=async(member,route,data,key=randomUUID())=>{
const response=await fetch(base+route,{method:data===undefined?'GET':'POST',headers:{...(cookies[member]?{Cookie:cookies[member]}:{}),...(data!==undefined?{'Content-Type':'application/json',Origin:base,'X-Requested-With':'maimai-ledger','Idempotency-Key':key}:{})},...(data===undefined?{}:{body:JSON.stringify(data)})});
const body=(response.headers.get('content-type')||'').includes('json')?await response.json():await response.text();return {status:response.status,body,response};
};
for(const [member,name] of [['owner','麦麦'],['assistant','助理1'],['assistant2','助理2']]){const result=await call(member,'/api/login',{name,password});assert.equal(result.status,200);assert.equal(result.body.user.member,member);cookies[member]=result.response.headers.get('set-cookie').split(';')[0];}
const issue=async(member,extra={})=>{
const account={owner:'麦麦微信',assistant:'助理微信',assistant2:'助理2微信'}[member];
const input={date:today(),customer:'仅'+member+'可见客户',internal_note:'测试内部备注',salesperson:'相同可改显示名',payment_account:account,rounding_mode:'cent',discount:'0',lines:[{name:'测试银饰',unit:'件',quantity:'1',pocket:'',payer:member,cost:'100',sale:'150'}],fee_items:[],...extra};
const result=await call(member,'/api/orders/issue',input);assert.equal(result.status,200,JSON.stringify(result.body));return result.body.id;
};
return {ledger,app,call,issue,cookies};
}
test('团队月度利润与旧资金接口仅老板可读,助理普通对账、本人往来与报销照常使用',async t=>{
const f=await fixture(t),date=today(),month=date.slice(0,7);for(const member of ['owner','assistant','assistant2'])await f.issue(member);
const owner=(await f.call('owner','/api/team-profits?month='+month));assert.equal(owner.status,200);assert.deepEqual(owner.body.rows.map(row=>[row.member,row.profit]),[['assistant',5000],['assistant2',5000]]);assert.equal(owner.body.from,month+'-01');assert.equal(owner.body.date,date);assert.equal((await f.call('owner','/api/team-funds?date='+date)).status,200);
const transfers=f.ledger.one('SELECT COUNT(*) AS count FROM team_fund_transfers').count,operations=f.ledger.one('SELECT COUNT(*) AS count FROM operations').count;
for(const member of ['assistant','assistant2']){
for(const route of ['/api/team-profits','/api/team-profits?month='+month,'/api/team-funds?date='+date])assert.equal((await f.call(member,route)).status,403,member+' '+route);
for(const route of ['/api/team-funds/transfers','/api/team-funds/transfer'])assert.equal((await f.call(member,route,{date,fromMember:member,toMember:'owner',amount:'1',verified:true})).status,403);
const daily=await f.call(member,'/api/daily-funds?date='+date);assert.equal(daily.status,200);assert.ok(daily.body.team.pairs.every(pair=>pair.members.includes(member)));
const report=await f.call(member,'/api/report?date='+date+'&basis=orderDate');assert.equal(report.status,200);assert.equal(report.body.ownershipBusiness[member].profit,5000);assert.deepEqual(Object.keys(report.body.ownershipBusiness),[member]);assert.ok(report.body.dailyFunds.team);
}
assert.equal(f.ledger.one('SELECT COUNT(*) AS count FROM operations').count,operations);assert.equal(f.ledger.one('SELECT COUNT(*) AS count FROM team_fund_transfers').count,transfers);
const claim=await f.call('assistant','/api/reimbursements',{date,items:[{name:'合成独立邮寄',amount:'5',member:'owner',sourceType:'independent'}]});assert.equal(claim.status,200);assert.equal(claim.body.reimbursement.total,500);
assert.equal((await f.call('owner','/api/team-profits?month=2026-13')).status,400);assert.equal((await f.call('none','/api/team-profits')).status,401);
});
test('三个真实登录会话按固定成员隔离订单、客户、业绩利润、打印和所有直接ID入口',async t=>{
const f=await fixture(t),ids={};for(const member of ['owner','assistant','assistant2'])ids[member]=await f.issue(member);
for(const [name,member] of [['娜娜','assistant'],['小昊','assistant2']]){const login=await f.call(member,'/api/login',{name,password});assert.equal(login.status,200);assert.equal(login.body.user.member,member);assert.equal(login.body.user.label,name);}
for(const self of ['assistant','assistant2']){
const other=self==='assistant'?'assistant2':'assistant',foreign=f.ledger.detail(ids[other]),own=f.ledger.detail(ids[self]);
for(const route of ['/api/state','/api/order-book?date='+today(),'/api/report?date='+today(),'/api/report?date='+today()+'&basis=orderDate']){
const result=await f.call(self,route);assert.equal(result.status,200,JSON.stringify(result.body));const source=JSON.stringify(result.body);
assert.ok(source.includes(ids[self]),route);assert.ok(!source.includes(foreign.customer),route);assert.ok(!source.includes(foreign.number),route);assert.ok(!source.includes(ids[other]),route);assert.ok(!source.includes(ids.owner),route);
}
for(const suffix of ['','/public','/edit','/change','/cancellation'])assert.equal((await f.call(self,'/api/orders/'+ids[other]+suffix)).status,404,suffix);
assert.equal((await f.call(self,'/print/'+ids[other])).status,404);
for(const suffix of ['/print','/edit','/change','/cancellation','/canceltoday','/receipt','/expense','/return','/settlement'])assert.equal((await f.call(self,'/api/orders/'+ids[other]+suffix,{date:today(),revision:foreign.revision,reason:'不得访问他人',verified:true})).status,404,suffix);
assert.equal((await f.call(self,'/api/order-book?member='+other)).status,403);
assert.equal((await f.call(self,'/api/report?member='+other)).status,403);
const report=(await f.call(self,'/api/report?basis=orderDate&date='+today())).body;assert.equal(report.sales,15000);assert.equal(report.profit,5000);
assert.equal((await f.call(self,'/api/export/inventory')).status,403);
assert.equal((await f.call(self,'/api/backup',{})).status,403);
}
const all=(await f.call('owner','/api/state')).body;assert.equal(all.orders.length,3);
assert.equal((await f.call('owner','/api/order-book?member=assistant2')).body.rows.length,1);
assert.equal((await f.call('owner','/api/report?basis=orderDate&date='+today()+'&member=assistant2')).body.sales,15000);
assert.equal(f.ledger.actor,null);assert.equal(f.ledger.memberFilter,null);
// 改显示名、冒充另一个开单人,均不改变账号及原订单的归属。
const helper=f.ledger.one("SELECT user_id FROM team_user_members WHERE member='assistant2'");f.ledger.run('UPDATE users SET name=? WHERE id=?','任意新显示名',helper.user_id);
const unchanged=(await f.call('assistant2','/api/session')).body.user;assert.equal(unchanged.member,'assistant2');assert.equal(unchanged.label,'小昊');
assert.equal((await f.call('assistant','/api/orders/issue',{member:'assistant2'})).status,403);
const mine=(await f.call('assistant2','/api/orders/'+ids.assistant2+'/edit')).body;
assert.equal((await f.call('assistant2','/api/orders/'+ids.assistant2+'/edit',{...mine.inputs,member:'assistant',revision:mine.revision,verified:true,reason:'不能换归属'})).status,403);
const delegated=await f.issue('owner',{member:'assistant2',customer:'老板代录助理2'});assert.equal(f.ledger.entityMember('order',delegated),'assistant2');assert.equal((await f.call('assistant2','/api/orders/'+delegated)).status,200);assert.equal((await f.call('assistant','/api/orders/'+delegated)).status,404);
});
test('三人HTTP共享完整盘点流水但不共享结构化成本和业务详情,原手动改删审批与财务权限保留',async t=>{
const f=await fixture(t),d=today(),members=['owner','assistant','assistant2'],stock={},orders={};
for(const member of members){
const result=await f.call(member,'/api/stock',{kind:'purchase',date:d,pocket:'现货',grams:'5',cost:member==='assistant2'?'9327.46':'1234.56',note:member+'原始库存备注'});assert.equal(result.status,200,JSON.stringify(result.body));stock[member]=f.ledger.one('SELECT * FROM movements WHERE group_id=?',result.body.group);
orders[member]=await f.issue(member,{lines:[{name:'仅'+member+'可见产品',unit:'g',quantity:'1',pocket:'现货',payer:member,cost:'100',sale:'150'}]});
}
const original=(await f.call('assistant2','/api/inventory/movements/'+stock.assistant2.id)).body,input={...original.values,revision:original.revision,note:'批准后库存备注',reason:'不能泄露的私有审批原因'};
const submitted=await f.call('assistant2','/api/inventory/movements/'+stock.assistant2.id+'/update',input);assert.equal(submitted.status,200);assert.equal(submitted.body.pending,true);const requestId=submitted.body.requestId;
const all=(await f.call('owner','/api/inventory/movements')).body,ids=all.movements.map(row=>row.id);assert.equal(all.total,6);
const tables=['orders','payments','expenses','journal','movements','inventory_changes','inventory_manual_groups','operations','audit'],snapshot=()=>JSON.stringify(tables.map(table=>[table,f.ledger.rows('SELECT * FROM '+table+' ORDER BY rowid')])),before=snapshot();
for(const member of members){
const shared=(await f.call(member,'/api/inventory/movements')).body,state=(await f.call(member,'/api/state')).body;assert.equal(shared.total,6);assert.deepEqual(shared.movements.map(row=>row.id),ids);assert.deepEqual(state.movements.map(row=>row.id),ids);assert.equal(state.inventory.find(row=>row.pocket==='现货').mg,12000);
for(const other of members){
const row=shared.movements.find(row=>row.id===stock[other].id),sale=shared.movements.find(row=>row.note===f.ledger.detail(orders[other]).number);assert.ok(row);assert.ok(sale);assert.equal(row.note,other+'原始库存备注');assert.equal(row.actor,stock[other].actor);assert.equal(row.mg,5000);
if(member!=='owner'&&member!==other){
assert.equal(row.canEdit,false);assert.equal(row.canDelete,false);assert.equal(row.pendingRequestId,null);assert.ok(!Object.hasOwn(row,'purchase_cost'));assert.ok(!Object.hasOwn(sale,'order_id'));assert.ok(!Object.hasOwn(sale,'purchase_cost'));assert.equal(f.ledger.canAccess('movement',row.id,state.user),false);
assert.equal((await f.call(member,'/api/inventory/movements/'+row.id)).status,404);for(const action of ['update','delete'])assert.equal((await f.call(member,'/api/inventory/movements/'+row.id+'/'+action,{...input,verified:true})).status,404);
assert.equal((await f.call(member,'/api/orders/'+orders[other])).status,404);assert.equal((await f.call(member,'/print/'+orders[other])).status,404);
const privateState=JSON.stringify({...state,movements:[]});assert.ok(!privateState.includes(f.ledger.detail(orders[other]).customer));assert.ok(!privateState.includes(orders[other]));
}
}
if(member==='assistant'){
const foreign=shared.movements.find(row=>row.id===stock.assistant2.id);assert.equal(foreign.pendingApproval,true);assert.ok(!JSON.stringify(shared).includes(requestId));assert.ok(!JSON.stringify(state.movements).includes('不能泄露的私有审批原因'));assert.ok(!JSON.stringify(shared).includes('9327.46'));assert.ok(!JSON.stringify(shared).includes('932746'));
assert.equal((await f.call(member,'/api/inventory/changes')).body.requests.length,0);assert.equal((await f.call(member,'/api/inventory/changes/'+requestId)).status,404);assert.equal((await f.call(member,'/api/inventory/changes/'+requestId+'/approve',{revision:1,verified:true})).status,403);
const report=(await f.call(member,'/api/report?date='+d+'&basis=orderDate')).body;assert.equal(report.sales,15000);assert.equal(report.profit,5000);
}
}
assert.equal(snapshot(),before,'共享读取与越权失败不改变库存、订单、成本利润、审批、审计或幂等结果');
const request=(await f.call('owner','/api/inventory/changes/'+requestId)).body,approved=await f.call('owner','/api/inventory/changes/'+requestId+'/approve',{revision:request.revision,inventoryRevision:request.inventoryRevision,verified:true});assert.equal(approved.status,200);assert.equal(approved.body.applied,true);
const own=approved.body.group.movements[0];assert.equal((await f.call('assistant2','/api/inventory/movements/'+own.id)).body.canEdit,true);assert.equal((await f.call('assistant','/api/inventory/movements/'+own.id)).status,404);assert.equal(f.ledger.inventory().find(row=>row.pocket==='现货').mg,12000);
});
test('锁价、独立售后、私有同名模板、人数和审批列表都只包含本人;老板可全部复核',async t=>{
const f=await fixture(t),d=today(),locks={},templates={},changes={},cancellations={};
for(const self of ['assistant','assistant2']){
const lock=await f.call(self,'/api/price-locks',{date:d,customer:self+'独有锁价客户',internal_note:'测试内部备注',salesperson:'相同显示名',line:{name:'足金999',quantity:'1.000',goldPrice:'900',laborRate:'0',laborMode:'gram',pieces:'1',charges:[]},material:{rate:'850',payer:self,verified:true},payment:{amount:'900',account:self==='assistant'?'助理微信':'助理2微信',verified:true}});assert.equal(lock.status,200,JSON.stringify(lock.body));locks[self]=lock.body.id;
const after=await f.call(self,'/api/after-sales',{date:d,project:self+'独有售后项目',customer:self+'独有售后客户',amount:'5',payer:self});assert.equal(after.status,200,JSON.stringify(after.body));
const template=await f.call(self,'/api/order-templates',{name:'双方独立同名模板',preset:{lines:[{name:'银饰',unit:'件',quantity:'1',pocket:'',payer:self,cost:'2',sale:'3'}],fee_items:[]}});assert.equal(template.status,200,JSON.stringify(template.body));templates[self]=template.body.id;
const id=await f.issue(self,{customer:self+'审批客户'}),edit=(await f.call(self,'/api/orders/'+id+'/edit')).body;
const change=await f.call(self,'/api/orders/'+id+'/change',{...edit.inputs,customer:self+'申请后客户',revision:edit.revision,reason:'合成修改原因',verified:true});assert.equal(change.status,200,JSON.stringify(change.body));changes[self]=change.body.requestId;
const cancelId=await f.issue(self,{customer:self+'取消客户'}),cancel=(await f.call(self,'/api/orders/'+cancelId+'/cancellation')).body;
const cancellation=await f.call(self,'/api/orders/'+cancelId+'/cancellation',{revision:cancel.revision,reason:'合成取消原因',verified:true});assert.equal(cancellation.status,200,JSON.stringify(cancellation.body));cancellations[self]=cancellation.body.requestId;
}
for(const self of ['assistant','assistant2']){
const other=self==='assistant'?'assistant2':'assistant';
assert.equal((await f.call(self,'/api/price-locks')).body.rows.length,1);assert.equal((await f.call(self,'/api/price-locks')).body.counts.pending,1);
assert.equal((await f.call(self,'/api/price-locks/'+locks[other])).status,404);
assert.equal((await f.call(self,'/api/price-locks/'+locks[other]+'/deliver',{})).status,404);
assert.equal((await f.call(self,'/api/order-templates')).body.rows.length,1);assert.equal((await f.call(self,'/api/order-templates/'+templates[other])).status,404);
assert.equal((await f.call(self,'/api/order-templates/'+templates[other]+'/delete',{revision:1})).status,404);
const report=JSON.stringify((await f.call(self,'/api/report?basis=orderDate&date='+d)).body);assert.ok(!report.includes(other+'独有售后客户'));assert.ok(!report.includes(other+'独有锁价客户'));
for(const [resource,requests] of [['order-changes',changes],['order-cancellations',cancellations]]){
const list=(await f.call(self,'/api/'+resource)).body;assert.equal(list.requests.length,1);assert.equal(list.counts.pending,1);assert.equal(list.requests[0].id,requests[self]);
assert.equal((await f.call(self,'/api/'+resource+'/'+requests[other])).status,404);assert.equal((await f.call(self,'/api/'+resource+'/'+requests[self]+'/approve',{verified:true})).status,403);
assert.equal((await f.call('owner','/api/'+resource)).body.requests.length,2);
}
const ownKey=self==='assistant'?'assistant1Count':'assistant2Count',otherKey=self==='assistant'?'assistant2Count':'assistant1Count',people=(await f.call(self,'/api/people-count?date='+d)).body;
assert.ok(!Object.hasOwn(people,otherKey));assert.ok(!Object.hasOwn(people,'count'));
assert.equal((await f.call(self,'/api/people-count',{date:d,revision:people.revision,[ownKey]:'3'})).status,200);
const next=(await f.call(self,'/api/people-count?date='+d)).body;assert.equal(next[ownKey],3);assert.ok(!Object.hasOwn(next,otherKey));assert.equal((await f.call(self,'/api/people-count',{date:d,revision:next.revision,[otherKey]:'999'})).status,403);
assert.ok(!JSON.stringify((await f.call(self,'/api/people-count-history?date='+d+'&from='+d)).body).includes(otherKey));
}
const people=(await f.call('owner','/api/people-count?date='+d)).body;assert.equal(people.assistant1Count,3);assert.equal(people.assistant2Count,3);
});
test('新助理没有默认可登录密码;只有老板可设置并使旧会话失效,旧助理登录别名及ID保持',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-team-credentials-')),ledger=new Ledger(':memory:');
createUser(ledger,'麦麦','owner',password,'owner');createUser(ledger,'助理','assistant',password,'assistant');const old=ledger.one("SELECT * FROM users WHERE role='assistant'");
const app=createApp({mode:'trial',dataDir:dir,ledger,port:0,feishuConfig:{enabled:false}});await new Promise(resolve=>app.server.listen(0,'127.0.0.1',resolve));
t.after(async()=>{await new Promise(resolve=>app.server.close(resolve));ledger.close();fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+app.server.address().port;
const post=(route,body,cookie='')=>fetch(base+route,{method:'POST',headers:{'Content-Type':'application/json',Origin:base,'X-Requested-With':'maimai-ledger','Idempotency-Key':randomUUID(),Cookie:cookie},body:JSON.stringify(body)});
const login=await post('/api/login',{name:'麦麦',password}),ownerCookie=login.headers.get('set-cookie').split(';')[0];
assert.equal((await post('/api/login',{name:'助理2',password:'123456789012'})).status,401);
const helperLogin=await post('/api/login',{name:'助理1',password});assert.equal(helperLogin.status,200);assert.equal((await helperLogin.json()).user.id,old.id);
assert.equal((await post('/api/team-members/assistant2/password',{password,verified:true},helperLogin.headers.get('set-cookie').split(';')[0])).status,403);
assert.equal((await post('/api/team-members/assistant2/password',{password:'short',verified:true},ownerCookie)).status,400);
assert.equal((await post('/api/team-members/assistant2/password',{password,verified:true},ownerCookie)).status,200);
assert.equal((await post('/api/login',{name:'助理2',password})).status,200);assert.equal((await post('/api/login',{name:'助理',password})).status,200);
const kept=ledger.one('SELECT * FROM users WHERE id=?',old.id);assert.equal(kept.hash,old.hash);assert.equal(kept.salt,old.salt);assert.equal(kept.name,old.name);
});