移入店铺配置,保留原账号与历史账务口径
This commit is contained in:
1 parent
8d68111479
commit
90bdc75150
22 files changed
+535
-62
No files matched your search
+11
-7
@@ -5,6 +5,7 @@ const path=require('node:path');
|
||||
const crypto=require('node:crypto');
|
||||
const {DatabaseSync,backup}=require('node:sqlite');
|
||||
const TeamMembers=require('./team-members');
|
||||
const ShopSettings=require('./shop-settings');
|
||||
const OrderChanges=require('./order-changes');
|
||||
const {inventoryMovementsFile}=require('./inventory-movements-export');
|
||||
const {Ledger,ACCOUNTS,today,fail,text,owner}=require('./ledger');
|
||||
@@ -101,7 +102,7 @@ function createApp(options={}){
|
||||
const url=new URL(req.url,'http://'+req.headers.host);const route=url.pathname;const isPost=req.method==='POST';
|
||||
if(!['GET','POST'].includes(req.method))fail('不支持的请求方式',405);
|
||||
if(isPost){const expectedOrigin=production?new URL(process.env.PUBLIC_URL).origin:'http://'+req.headers.host;if(req.headers.origin!==expectedOrigin||req.headers['x-requested-with']!=='maimai-ledger'||!req.headers['content-type']?.startsWith('application/json'))fail('请从系统页面提交操作',403);}
|
||||
if(route==='/api/session'&&!isPost)return send(res,200,{user:user(req),setup:!ledger.one('SELECT id FROM users LIMIT 1'),mode,today:today()});
|
||||
if(route==='/api/session'&&!isPost)return send(res,200,{user:user(req),setup:!ledger.one('SELECT id FROM users LIMIT 1'),mode,today:today(),brand:{storeName:ShopSettings.read(ledger).storeName}});
|
||||
if(route==='/api/setup'&&isPost){
|
||||
if(production||mode==='demo'||ledger.one('SELECT id FROM users LIMIT 1'))fail('初始化入口已关闭',403);const b=await read(req);
|
||||
if(String(b.ownerPassword||'').length<12||String(b.assistantPassword||'').length<12)fail('两组密码都至少12个字符');
|
||||
@@ -120,6 +121,8 @@ function createApp(options={}){
|
||||
if(!actor)fail('请先登录',401);
|
||||
// 仅校验本次页面的原账号与cookie一致,实际授权仍由登录和成员权限决定。
|
||||
if(req.headers['x-ledger-user']!==undefined&&req.headers['x-ledger-user']!==actor.id){const error=new Error('登录账号已在其他页面切换,请刷新后继续;原操作已暂停。');error.status=409;error.code='ACCOUNT_CHANGED';throw error;}
|
||||
if(route==='/api/shop-settings'&&!isPost)return send(res,200,ShopSettings.publicSettings(actorLedger,actor));
|
||||
if(isPost&&['/api/shop-settings','/api/printing'].includes(route))owner(actor);
|
||||
if(route==='/api/team-members'&&!isPost)return send(res,200,actorLedger.teamMembers());
|
||||
if(route==='/api/pockets'&&!isPost)return send(res,200,{catalog:actorLedger.pocketCatalog(),pockets:actorLedger.activePocketKeys(),canManage:actor.role==='owner'});
|
||||
const pocketMatch=route.match(/^\/api\/pockets\/([^/]+)\/update$/);
|
||||
@@ -129,7 +132,7 @@ function createApp(options={}){
|
||||
if(['/api/team-funds/transfers','/api/team-funds/transfer'].includes(route))owner(actor);
|
||||
const memberPasswordMatch=route.match(/^\/api\/team-members\/(owner|assistant|assistant2)\/password$/);
|
||||
if(route==='/api/logout'&&isPost){const token=req.headers.cookie?.split(';').map(x=>x.trim()).find(x=>x.startsWith('mm_session='))?.slice(11);if(token)actorLedger.run('DELETE FROM sessions WHERE hash=?',sha(token));res.setHeader('Set-Cookie','mm_session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0');return send(res,200,{ok:true});}
|
||||
if(route==='/api/state'&&!isPost){const orders=actorLedger.visibleRows('order',actorLedger.rows('SELECT id FROM orders ORDER BY created DESC')).map(r=>actorLedger.detail(r.id));return send(res,200,{today:today(),mode,user:actor,members:TeamMembers.MEMBERS,pockets:actorLedger.activePocketKeys(),pocketCatalog:actorLedger.pocketCatalog(),accounts:ACCOUNTS,inventory:actorLedger.inventory(),orders:orders.map(({audit,payments,expenses,settlements,...o})=>o),priceLockCounts:actorLedger.priceLocks({status:'pending'}).counts,materialPoolSummary:actorLedger.materialPools().summary,materialPoolSettlement:actorLedger.materialPoolSettlement(),materialPoolAllocation:actorLedger.materialPoolAllocationStatus(),sync:actor.role==='owner'?sync.status():{enabled:sync.enabled},printing:settings(actorLedger.meta('printing',defaults)),backup:actor.role==='owner'?{last:lastBackup,error:backupError}:null,movements:actorLedger.inventoryMovements({},actor).movements});}
|
||||
if(route==='/api/state'&&!isPost){const orders=actorLedger.visibleRows('order',actorLedger.rows('SELECT id FROM orders ORDER BY created DESC')).map(r=>actorLedger.detail(r.id));return send(res,200,{today:today(),mode,user:actor,members:TeamMembers.MEMBERS,shopSettings:ShopSettings.publicSettings(actorLedger,actor),pockets:actorLedger.activePocketKeys(),pocketCatalog:actorLedger.pocketCatalog(),accounts:ACCOUNTS,inventory:actorLedger.inventory(),orders:orders.map(({audit,payments,expenses,settlements,...o})=>o),priceLockCounts:actorLedger.priceLocks({status:'pending'}).counts,materialPoolSummary:actorLedger.materialPools().summary,materialPoolSettlement:actorLedger.materialPoolSettlement(),materialPoolAllocation:actorLedger.materialPoolAllocationStatus(),sync:actor.role==='owner'?sync.status():{enabled:sync.enabled},printing:ShopSettings.printingSettings(actorLedger),backup:actor.role==='owner'?{last:lastBackup,error:backupError}:null,movements:actorLedger.inventoryMovements({},actor).movements});}
|
||||
if(route==='/api/material-pools'&&!isPost)return send(res,200,actorLedger.materialPools(Object.fromEntries(url.searchParams)));
|
||||
if(route==='/api/material-pools/rolling-preview'&&!isPost){owner(actor);return send(res,200,actorLedger.rollingMaterialPreview(Object.fromEntries(url.searchParams),actor));}
|
||||
if(route==='/api/material-purchase-changes'&&!isPost)return send(res,200,actorLedger.materialPurchaseChanges(Object.fromEntries(url.searchParams),actor));
|
||||
@@ -196,8 +199,8 @@ function createApp(options={}){
|
||||
const match=route.match(/^\/api\/orders\/([a-f0-9-]+)(?:\/([a-z]+))?$/);
|
||||
if(match&&!isPost){if(match[2]==='public')return send(res,200,actorLedger.publicOrder(match[1]));if(match[2]==='edit')return send(res,200,actorLedger.orderEdit(match[1],actor));if(match[2]==='change')return send(res,200,actorLedger.orderChange(match[1],actor));if(match[2]==='ownership')return send(res,200,actorLedger.orderOwnership(match[1],actor));if(match[2]==='cancellation')return send(res,200,actorLedger.orderCancellation(match[1],actor));if(!match[2])return send(res,200,actorLedger.detail(match[1]));fail('地址不存在',404);}
|
||||
const recoveryPrintMatch=route.match(/^\/print\/recoveries\/([a-f0-9-]{36})$/);
|
||||
if(recoveryPrintMatch&&!isPost){const dto=actorLedger.publicRecovery(recoveryPrintMatch[1],actor),print=dto.mode==='exchange'?exchangeCustomerPrintDocument:recoveryCustomerPrintDocument;return send(res,200,print(dto,actorLedger.meta('printing',defaults)),'text/html; charset=utf-8');}
|
||||
if(route.startsWith('/print/')&&!isPost){const id=route.slice(7),order=actorLedger.detail(id);if(order.recovery_id){const dto=actorLedger.publicRecovery(order.recovery_id,actor);return send(res,200,exchangeCustomerPrintDocument(dto,actorLedger.meta('printing',defaults)),'text/html; charset=utf-8');}return send(res,200,receipt(actorLedger.publicOrder(id),actorLedger.meta('printing',defaults),url.searchParams.get('mode')),'text/html; charset=utf-8');}
|
||||
if(recoveryPrintMatch&&!isPost){const dto=actorLedger.publicRecovery(recoveryPrintMatch[1],actor),print=dto.mode==='exchange'?exchangeCustomerPrintDocument:recoveryCustomerPrintDocument;return send(res,200,print(dto,ShopSettings.printingSettings(actorLedger)),'text/html; charset=utf-8');}
|
||||
if(route.startsWith('/print/')&&!isPost){const id=route.slice(7),order=actorLedger.detail(id);if(order.recovery_id){const dto=actorLedger.publicRecovery(order.recovery_id,actor);return send(res,200,exchangeCustomerPrintDocument(dto,ShopSettings.printingSettings(actorLedger)),'text/html; charset=utf-8');}return send(res,200,receipt(actorLedger.publicOrder(id),ShopSettings.printingSettings(actorLedger),url.searchParams.get('mode')),'text/html; charset=utf-8');}
|
||||
if(route==='/api/report'&&!isPost){
|
||||
return send(res,200,actorLedger.reportFor(Object.fromEntries(url.searchParams),actor));
|
||||
}
|
||||
@@ -268,12 +271,13 @@ function createApp(options={}){
|
||||
if(inventoryChangeMatch&&inventoryChangeMatch[2]==='reject')return actorLedger.rejectInventoryChange(inventoryChangeMatch[1],b,actor);
|
||||
if(route==='/api/inventory/review')return actorLedger.reviewInventory(b,actor);
|
||||
if(route==='/api/close')return actorLedger.closeDay(b.date,actor,b.basis);
|
||||
if(route==='/api/printing'){owner(actor);const s=settings({...actorLedger.meta('printing',defaults),...b});actorLedger.setMeta('printing',s);actorLedger.audit('printing','更新打印参数',actor,s);return {ok:true};}
|
||||
if(route==='/api/shop-settings')return ShopSettings.update(actorLedger,b,actor);
|
||||
if(route==='/api/printing')return ShopSettings.updatePrinting(actorLedger,b,actor);
|
||||
if(route==='/api/password'){const u=actorLedger.one('SELECT * FROM users WHERE id=?',actor.id);if(derive(String(b.current||''),u.salt)!==u.hash)fail('原密码不正确');if(String(b.password||'').length<12)fail('新密码至少12个字符');const salt=crypto.randomBytes(24).toString('hex');actorLedger.run('UPDATE users SET salt=?,hash=? WHERE id=?',salt,derive(b.password,salt),actor.id);actorLedger.run('UPDATE team_user_members SET password_set=1 WHERE user_id=?',actor.id);actorLedger.run('DELETE FROM sessions WHERE user_id=?',actor.id);return {ok:true};}
|
||||
fail('地址不存在',404);
|
||||
},{syncTeamFunds:route!=='/api/pockets'&&!pocketMatch});return send(res,200,route==='/api/people-count'?peopleCountResponse(actorLedger,result,actor):result);
|
||||
},{syncTeamFunds:!['/api/pockets','/api/shop-settings','/api/printing'].includes(route)&&!pocketMatch});return send(res,200,route==='/api/people-count'?peopleCountResponse(actorLedger,result,actor):result);
|
||||
}
|
||||
const assets={'/':'index.html','/app.js':'app.js','/order-copy.js':'order-copy.js','/order-templates.js':'order-templates.js','/order-templates-ui.js':'order-templates-ui.js','/order-edit-ui.js':'order-edit-ui.js','/order-cancellations-ui.js':'order-cancellations-ui.js','/order-changes-ui.js':'order-changes-ui.js','/order-after-sales-ui.js':'order-after-sales-ui.js','/order-ownership-ui.js':'order-ownership-ui.js','/daily-funds-ui.js':'daily-funds-ui.js','/team-funds-ui.js':'team-funds-ui.js','/cost-funding-ui.js':'cost-funding-ui.js','/price-locks-ui.js':'price-locks-ui.js','/price-lock-changes-ui.js':'price-lock-changes-ui.js','/material-pools-ui.js':'material-pools-ui.js','/recoveries-ui.js':'recoveries-ui.js','/recovery-changes-ui.js':'recovery-changes-ui.js','/inventory-changes-ui.js':'inventory-changes-ui.js','/pockets-ui.js':'pockets-ui.js','/credit-card-fees.js':'credit-card-fees.js','/calculations.js':'calculations.js','/fee-estimates.js':'fee-estimates.js','/app.css':'app.css','/print.js':'print.js'};const file=assets[route];if(!file||isPost)fail('地址不存在',404);
|
||||
const assets={'/':'index.html','/app.js':'app.js','/order-copy.js':'order-copy.js','/order-templates.js':'order-templates.js','/order-templates-ui.js':'order-templates-ui.js','/order-edit-ui.js':'order-edit-ui.js','/order-cancellations-ui.js':'order-cancellations-ui.js','/order-changes-ui.js':'order-changes-ui.js','/order-after-sales-ui.js':'order-after-sales-ui.js','/order-ownership-ui.js':'order-ownership-ui.js','/daily-funds-ui.js':'daily-funds-ui.js','/team-funds-ui.js':'team-funds-ui.js','/cost-funding-ui.js':'cost-funding-ui.js','/price-locks-ui.js':'price-locks-ui.js','/price-lock-changes-ui.js':'price-lock-changes-ui.js','/material-pools-ui.js':'material-pools-ui.js','/recoveries-ui.js':'recoveries-ui.js','/recovery-changes-ui.js':'recovery-changes-ui.js','/inventory-changes-ui.js':'inventory-changes-ui.js','/pockets-ui.js':'pockets-ui.js','/shop-settings-ui.js':'shop-settings-ui.js','/credit-card-fees.js':'credit-card-fees.js','/calculations.js':'calculations.js','/fee-estimates.js':'fee-estimates.js','/app.css':'app.css','/print.js':'print.js'};const file=assets[route];if(!file||isPost)fail('地址不存在',404);
|
||||
send(res,200,fs.readFileSync(path.join(__dirname,'public',file)),file.endsWith('.js')?'application/javascript; charset=utf-8':file.endsWith('.css')?'text/css; charset=utf-8':'text/html; charset=utf-8');
|
||||
}catch(e){if(!res.headersSent)send(res,e.status||400,{error:e.status||e.message?.startsWith('打印')?e.message:(e.code?.startsWith('SQLITE')?'保存失败,请保留操作内容并联系维护者':e.message||'操作失败'),...(e.code==='ACCOUNT_CHANGED'?{code:e.code}:{}),...(e.code==='RECOVERY_MATERIAL_IN_USE'?{code:e.code,blockedUsages:e.blockedUsages}:{})});else res.end();}
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user