所有设备按店铺营业时段访问台账
This commit is contained in:
1 parent
67b145c4b8
commit
76db0e0277
10 files changed
+223
-22
No files matched your search
+59
-11
@@ -5,6 +5,7 @@ const path=require('node:path');
|
||||
const crypto=require('node:crypto');
|
||||
const {DatabaseSync,backup}=require('node:sqlite');
|
||||
const {loginPage,scriptHash}=require('./login-page');
|
||||
const {accessWindow}=require('./business-hours');
|
||||
const TeamMembers=require('./team-members');
|
||||
const ShopSettings=require('./shop-settings');
|
||||
const PrintStatus=require('./print-status');
|
||||
@@ -87,6 +88,9 @@ function createApp(options={}){
|
||||
if(!production&&!['127.0.0.1','::1','localhost'].includes(host))throw new Error('试用/演示只能绑定本机,云端请配置production模式与HTTPS');
|
||||
if(production&&(!process.env.PUBLIC_URL?.startsWith('https://')||!process.env.DATA_DIR||!path.isAbsolute(process.env.DATA_DIR)))throw new Error('云端须配置HTTPS PUBLIC_URL和绝对路径持久化DATA_DIR');
|
||||
const shopAccessPolicy = options.shopAccessPolicy ?? (production && process.env.SHOP_ACCESS_POLICY === '1');
|
||||
const hoursPolicy=options.hoursPolicy??(production&&process.env.SHOP_ACCESS_POLICY==='hours');
|
||||
const hoursClock=options.hoursClock??Date.now;
|
||||
const currentWindow=()=>hoursPolicy?accessWindow(ledger.meta(ShopSettings.KEY)?.businessHours,hoursClock()):null;
|
||||
if (shopAccessPolicy && !['127.0.0.1', '::1'].includes(host)) throw new Error('网络访问限制须绑定本机反向代理');
|
||||
const dataDir=options.dataDir||(production?process.env.DATA_DIR:null)||path.join(__dirname,'data',mode);
|
||||
const ledger=options.ledger||new Ledger(path.join(dataDir,'ledger.sqlite'));
|
||||
@@ -103,8 +107,21 @@ function createApp(options={}){
|
||||
ensureTeamAccounts(ledger);
|
||||
const sync=new FeishuSync(ledger,config,options.fetcher);
|
||||
const automaticSnapshots=new InventorySnapshotScheduler(ledger,{clock:options.clock,logger:options.inventorySnapshotLogger,...options.inventorySnapshotTimers});
|
||||
const send=(res,status,data,contentType='application/json; charset=utf-8')=>{res.writeHead(status,{'Content-Type':contentType});res.end(contentType.startsWith('application/json')?JSON.stringify(data):data);};
|
||||
async function read(req){let raw='';for await(const chunk of req){raw+=chunk;if(Buffer.byteLength(raw)>300000)fail('内容过大',413);}try{return JSON.parse(raw||'{}');}catch{fail('请求内容不是有效JSON');}}
|
||||
const send=(res,status,data,contentType='application/json; charset=utf-8')=>{
|
||||
if(status===200&&res.businessWindow?.state==='open'&&contentType.startsWith('text/html')){
|
||||
const remaining=Math.max(0,res.businessWindow.closesAt-hoursClock());
|
||||
data=data.toString().replace('</body>',`<script src="/business-hours-lock.js" data-remaining="${remaining}"></script></body>`);
|
||||
}
|
||||
res.writeHead(status,{'Content-Type':contentType});res.end(contentType.startsWith('application/json')?JSON.stringify(data):data);
|
||||
};
|
||||
async function read(req){let raw='';for await(const chunk of req){raw+=chunk;if(Buffer.byteLength(raw)>300000)fail('内容过大',413);}
|
||||
// 读取慢速提交期间也可能到达关门时间。
|
||||
const period=currentWindow();
|
||||
if(period?.state==='closed'||period?.state==='unset'&&!['/api/login','/api/business-hours/setup','/api/logout'].includes(req.url.split('?')[0])){
|
||||
throw Object.assign(new Error(period.message||'营业时间尚未设置'),{status:403,code:'BUSINESS_HOURS'});
|
||||
}
|
||||
try{return JSON.parse(raw||'{}');}catch{fail('请求内容不是有效JSON');}
|
||||
}
|
||||
function user(req){const cookie=req.headers.cookie?.split(';').map(s=>s.trim()).find(s=>s.startsWith('mm_session='))?.slice(11);if(!cookie)return null;return sessionUser(ledger,ledger.one('SELECT u.id,u.name,u.role FROM sessions s JOIN users u ON u.id=s.user_id JOIN team_user_members t ON t.user_id=u.id JOIN team_members m ON m.member=t.member WHERE s.hash=? AND s.expires>? AND m.enabled=1',sha(cookie),Date.now())||null);}
|
||||
function session(res,u){if(!u)fail('账号不可用',401);const token=crypto.randomBytes(32).toString('hex');ledger.run('DELETE FROM sessions WHERE expires<?',Date.now());ledger.run('INSERT INTO sessions VALUES (?,?,?)',sha(token),u.id,Date.now()+8*60*60*1000);res.setHeader('Set-Cookie',`mm_session=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=28800${production?'; Secure':''}`);return {user:sessionUser(ledger,u)};}
|
||||
let lastBackup=null,backupError=null,backupBusy=false;
|
||||
@@ -122,16 +139,32 @@ function createApp(options={}){
|
||||
const zone = req.headers['x-ledger-access-zone'];
|
||||
if (shopAccessPolicy && !['store', 'owner'].includes(zone)) fail('请通过店铺正式网址访问', 403);
|
||||
const outside = shopAccessPolicy && zone === 'owner';
|
||||
const window=currentWindow();
|
||||
function denyHours(message){
|
||||
throw Object.assign(new Error(message),{code:'BUSINESS_HOURS',status:403});
|
||||
}
|
||||
function standalone(info,status=200){
|
||||
const policy=res.getHeader('Content-Security-Policy');
|
||||
res.setHeader('Content-Security-Policy',policy.replace("script-src 'self'","script-src 'sha256-"+scriptHash+"'"));
|
||||
return send(res,status,loginPage(info),'text/html; charset=utf-8');
|
||||
}
|
||||
if(window?.state==='closed'){
|
||||
if(route==='/'&&!isPost)return standalone({brand:{storeName:ShopSettings.read(ledger).storeName},closedMessage:window.message},403);
|
||||
denyHours(window.message);
|
||||
}
|
||||
if(window?.state==='unset'&&!['/','/api/login','/api/session','/api/business-hours/setup','/api/logout'].includes(route))
|
||||
denyHours('店主尚未设置营业时间,账本暂未开放。');
|
||||
function checkAccount(account) {
|
||||
if(window?.state==='unset'&&account&&account.role!=='owner')denyHours('请等待店主设置营业时间。');
|
||||
if (outside && account && account.role !== 'owner') fail('员工账号请连接店内 Wi-Fi 后使用', 403);
|
||||
return account;
|
||||
}
|
||||
function sessionInfo(account){
|
||||
const setup=!ledger.one('SELECT id FROM users LIMIT 1');
|
||||
const loginOptions=ShopSettings.loginOptions(ledger).filter(row=>!outside||row.member==='owner')
|
||||
const loginOptions=ShopSettings.loginOptions(ledger).filter(row=>(!outside&&window?.state!=='unset')||row.member==='owner')
|
||||
.filter(row=>ledger.one('SELECT user_id FROM team_user_members WHERE member=?',row.member))
|
||||
.map(({member,label})=>({member,label}));
|
||||
return {user:account,setup,mode,today:today(),brand:{storeName:setup?'店铺台账':ShopSettings.read(ledger).storeName},loginOptions};
|
||||
return {user:account,setup,mode,today:today(),...(window&&{accessWindow:window}),brand:{storeName:setup?'店铺台账':ShopSettings.read(ledger).storeName},loginOptions};
|
||||
}
|
||||
if(route==='/api/session'&&!isPost)return send(res,200,sessionInfo(checkAccount(user(req))));
|
||||
if(route==='/api/setup'&&isPost){
|
||||
@@ -148,11 +181,26 @@ function createApp(options={}){
|
||||
return send(res,200,session(res,checkAccount(u)));
|
||||
}
|
||||
if(route==='/api/demo-login'&&isPost&&mode==='demo'){const b=await read(req),member=b.member??(b.role==='assistant2'?'assistant2':b.role==='assistant'?'assistant':'owner');if(!TeamMembers.isActive(ledger,member))fail('演示成员无效');return send(res,200,session(res,ledger.one('SELECT u.id,u.name,u.role FROM users u JOIN team_user_members t ON t.user_id=u.id WHERE t.member=?',member)));}
|
||||
const actor=checkAccount(user(req));const actorLedger=ledger.asActor(actor);
|
||||
if(route==='/'&&!isPost&&!actor){
|
||||
const policy=res.getHeader('Content-Security-Policy');
|
||||
res.setHeader('Content-Security-Policy',policy.replace("script-src 'self'","script-src 'sha256-"+scriptHash+"'"));
|
||||
return send(res,200,loginPage(sessionInfo(null)),'text/html; charset=utf-8');
|
||||
const current=user(req);
|
||||
const actor=route==='/'&&window?.state==='unset'&¤t?.role!=='owner'?null:checkAccount(current);
|
||||
const actorLedger=ledger.asActor(actor);
|
||||
if(actor)res.businessWindow=window;
|
||||
if(route==='/'&&!isPost&&(!actor||window?.state==='unset')){
|
||||
const info=sessionInfo(actor);
|
||||
if(window?.state==='unset'&&actor?.role==='owner')info.hoursRevision=ShopSettings.read(ledger).revision;
|
||||
return standalone(info);
|
||||
}
|
||||
if(route==='/api/business-hours/setup'&&isPost){
|
||||
owner(actor);
|
||||
const body=await read(req);
|
||||
if(currentWindow()?.state!=='unset')fail('营业时间已设置,请重新打开台账。',409);
|
||||
if(!body.businessHours)fail('请填写营业时间。');
|
||||
ShopSettings.update(ledger,{revision:body.revision,businessHours:body.businessHours},actor);
|
||||
return send(res,200,{ok:true});
|
||||
}
|
||||
if(route==='/api/access-window'&&!isPost){
|
||||
if(!actor)fail('请先登录',401);
|
||||
return send(res,200,{window});
|
||||
}
|
||||
if(route.startsWith('/api/')||route.startsWith('/print/')){
|
||||
if(!actor)fail('请先登录',401);
|
||||
@@ -340,9 +388,9 @@ function createApp(options={}){
|
||||
fail('地址不存在',404);
|
||||
},{syncTeamFunds:!['/api/private-operations/people','/api/pockets','/api/shop-settings','/api/printing','/api/employees','/api/password'].includes(route)&&!pocketMatch&&!employeeMatch&&!memberPasswordMatch});return send(res,200,route==='/api/people-count'?peopleCountResponse(actorLedger,result,actor):result);
|
||||
}
|
||||
const assets={'/':'index.html','/login-ui.js':'login-ui.js','/private-operations-ui.js':'private-operations-ui.js','/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','/employees-ui.js':'employees-ui.js','/credit-card-fees.js':'credit-card-fees.js','/calculations.js':'calculations.js','/order-formula.js':'order-formula.js','/fee-estimates.js':'fee-estimates.js','/order-cost-presets-ui.js':'order-cost-presets-ui.js','/app.css':'app.css','/print.js':'print.js'};const file=assets[route];if(!file||isPost)fail('地址不存在',404);
|
||||
const assets={'/':'index.html','/business-hours-lock.js':'business-hours-lock.js','/login-ui.js':'login-ui.js','/private-operations-ui.js':'private-operations-ui.js','/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','/employees-ui.js':'employees-ui.js','/credit-card-fees.js':'credit-card-fees.js','/calculations.js':'calculations.js','/order-formula.js':'order-formula.js','/fee-estimates.js':'fee-estimates.js','/order-cost-presets-ui.js':'order-cost-presets-ui.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==='EMPLOYEE_HAS_BUSINESS'?{code:e.code,businessUsage:e.businessUsage}:{}),...(e.code==='RECOVERY_MATERIAL_IN_USE'?{code:e.code,blockedUsages:e.blockedUsages}:{})});else res.end();}
|
||||
}catch(e){if(!res.headersSent)send(res,e.status||400,{error:e.status||e.message?.startsWith('打印')?e.message:(e.code?.startsWith('SQLITE')?'保存失败,请保留操作内容并联系维护者':e.message||'操作失败'),...(['ACCOUNT_CHANGED','BUSINESS_HOURS'].includes(e.code)?{code:e.code}:{}),...(e.code==='EMPLOYEE_HAS_BUSINESS'?{code:e.code,businessUsage:e.businessUsage}:{}),...(e.code==='RECOVERY_MATERIAL_IN_USE'?{code:e.code,blockedUsages:e.blockedUsages}:{})});else res.end();}
|
||||
});
|
||||
const timers=[];
|
||||
function startTimers(){if(timers.length)return false;timers.push(setInterval(()=>sync.tick(),60000));timers.push(setInterval(()=>doBackup().catch(()=>{}),6*60*60*1000));automaticSnapshots.start();doBackup().catch(()=>{});for(const t of timers)t.unref();return true;}
|
||||
|
||||
Reference in new issue
Block a user