|
|
@@ -43,6 +43,17 @@ async function payrollReadUsers(co){
|
|
|
try{return(await Psql.query('SELECT xs_payroll_read_users($1) AS row',[co])).map(item=>item.row);}
|
|
|
catch{return Psql.query('SELECT * FROM "_User" WHERE "company"=$1',[co]);}
|
|
|
}
|
|
|
+const PAYROLL_UNBOUND_STORE={storeId:0,storeName:'未绑定门店'};
|
|
|
+async function payrollStoreDirectory(co){
|
|
|
+ const rows=await Psql.query('SELECT "storeId","storeName" FROM xs_payroll_store_directory($1) ORDER BY "storeId"',[co]);
|
|
|
+ return new Map(rows.map(row=>[number(row.storeId),{storeId:number(row.storeId),storeName:row.storeName}]));
|
|
|
+}
|
|
|
+function payrollStore(stores,storeId){
|
|
|
+ return stores.get(number(storeId))||PAYROLL_UNBOUND_STORE;
|
|
|
+}
|
|
|
+function payrollLessonStore(stores,storeId,coach){
|
|
|
+ return payrollStore(stores,storeId||number(coach&&legacyOf(coach).ParentUserID));
|
|
|
+}
|
|
|
async function payrollCanonicalSnapshot(context,input,options={}) {
|
|
|
const co=payrollTenant(context,input);
|
|
|
// A display-only estimate cannot authorize settlement. Financial reads and all
|
|
|
@@ -51,18 +62,25 @@ async function payrollCanonicalSnapshot(context,input,options={}) {
|
|
|
const fresh=readAcceleration&&options.readMonth?await payrollFreshReadSnapshot(co,options.readMonth,forDashboard,Boolean(context.storeId)):null;
|
|
|
const [snapshot,syncResult]=fresh?[fresh,forDashboard?{state:'not_checked',settlementReady:false,datasets:[],message:'金额已按实时完课记录计算,结算资格仍需完整核验'}:payrollSyncStatusFromCutoff(fresh.cutoff,true)]:await Promise.all([payrollSql('SELECT COALESCE(jsonb_agg(s),\'[]\'::jsonb) AS rows,'+((forDashboard||readAcceleration||options.omitSourceVersion===true)?"''::text":(readAcceleration?'xs_payroll_source_version_fast($1)':'xs_payroll_source_version($1)'))+' AS version FROM '+(readAcceleration?'xs_payroll_sources_cached':'xs_payroll_sources')+'($1) s',[co]),forDashboard?Promise.resolve({state:'not_checked',settlementReady:false,datasets:[],message:'金额已按实时完课记录计算,结算资格仍需完整核验'}):payrollSettlementSyncStatus(context,input,readAcceleration)]);
|
|
|
const {readSourceVersion,...sync}=syncResult;
|
|
|
- const users=readAcceleration?await payrollReadUsers(co):await Psql.query('SELECT * FROM "_User" WHERE "company"=$1',[co]);
|
|
|
+ const [users,stores]=await Promise.all([
|
|
|
+ readAcceleration?payrollReadUsers(co):Psql.query('SELECT * FROM "_User" WHERE "company"=$1',[co]),
|
|
|
+ payrollStoreDirectory(co)
|
|
|
+ ]);
|
|
|
const map=new Map(users.map(u=>[number(u.legacyUserId||legacyOf(u).UserID),u]));
|
|
|
const items=(snapshot.rows||[]).map(row=>{
|
|
|
- const item=payrollSourceProjection(row,'cache'),coach=map.get(item.coachId),student=map.get(item.studentId),storeId=item.storeId||number(coach&&legacyOf(coach).ParentUserID),store=map.get(storeId);
|
|
|
+ const item=payrollSourceProjection(row,'cache'),coach=map.get(item.coachId),student=map.get(item.studentId);
|
|
|
+ const store=payrollLessonStore(stores,item.storeId,coach);
|
|
|
return {...item,objectId:text(row.lessonObjectId||row.objectId),standardLessonKey:row.standardLessonKey,source:row.source,commonStatus:number(row.commonStatus,99),
|
|
|
coachName:coach?displayName(coach):item.coachName,coachObjectId:coach?coach.objectId:'',coachMobile:coach?mobileOf(coach):'',
|
|
|
- studentName:student?displayName(student):item.studentName,storeId,storeName:store?displayName(store):item.storeName||'未绑定门店',
|
|
|
+ studentName:student?displayName(student):item.studentName,...store,
|
|
|
teacherPaySnapshot:row.teacherPaySnapshot==null?null:Number(row.teacherPaySnapshot)};
|
|
|
});
|
|
|
const scopedItems=context.storeId?items.filter(i=>i.storeId===context.storeId):items;
|
|
|
- const total=fresh?(context.storeId?(fresh.scopeRows||[]).filter(row=>{const coach=map.get(number(row[0]||row[1]));return(number(row[2]||row[3])||number(coach&&legacyOf(coach).ParentUserID))===context.storeId;}).length:number(fresh.total)):scopedItems.length;
|
|
|
- return {items:scopedItems,version:fresh&&options.omitSourceVersion===true?'':readAcceleration&&!forDashboard&&options.omitSourceVersion!==true?text(readSourceVersion):snapshot.version,sourceStatus:{available:true,mode:'parse',message:'新数据库有效完课记录(含历史补充)',total,refreshedAt:new Date().toISOString(),complete:sync.settlementReady,stale:!sync.settlementReady,cacheHit:false,sync}};
|
|
|
+ const total=fresh?(context.storeId?(fresh.scopeRows||[]).filter(row=>{
|
|
|
+ const coach=map.get(number(row[0]||row[1]));
|
|
|
+ return payrollLessonStore(stores,number(row[2]||row[3]),coach).storeId===context.storeId;
|
|
|
+ }).length:number(fresh.total)):scopedItems.length;
|
|
|
+ return {items:scopedItems,stores,version:fresh&&options.omitSourceVersion===true?'':readAcceleration&&!forDashboard&&options.omitSourceVersion!==true?text(readSourceVersion):snapshot.version,sourceStatus:{available:true,mode:'parse',message:'新数据库有效完课记录(含历史补充)',total,refreshedAt:new Date().toISOString(),complete:sync.settlementReady,stale:!sync.settlementReady,cacheHit:false,sync}};
|
|
|
}
|
|
|
async function payrollSourceRows(context,input,month,requireLive=false){const data=await payrollCanonicalSnapshot(context,input);return {...data,items:data.items.filter(i=>payrollBusinessDate(i.lessonAt).slice(0,7)===month)};}
|
|
|
function payrollCalculatedLine(item,rates,settlementMonth,rules,mappings){
|
|
|
@@ -73,7 +91,7 @@ function payrollCalculatedLine(item,rates,settlementMonth,rules,mappings){
|
|
|
async function payrollPreviewData(context,input,month,includeUsed=false,requireLive=false,options={}){
|
|
|
// Generation, refresh, review and forced-live callers retain uncached financial checks.
|
|
|
if(!includeUsed||requireLive||input.targetId)return payrollPreviewUncached(context,input,month,includeUsed,requireLive,options);
|
|
|
- const co=payrollTenant(context,input),key='preview-v2:'+JSON.stringify([month,context.storeId||0,number(input.storeId||(input.filters||{}).storeId),text(input.search),options.forDashboard===true,options.omitSourceVersion===true]);
|
|
|
+ const co=payrollTenant(context,input),key='preview-v3:'+JSON.stringify([month,context.storeId||0,number(input.storeId||(input.filters||{}).storeId),text(input.search),options.forDashboard===true,options.omitSourceVersion===true]);
|
|
|
let cached;try{cached=(await Psql.one('SELECT xs_payroll_preview_cache_read($1,$2) AS result',[co,key])).result;}catch{ /* Missing/failed cache always falls back to the authoritative path. */ }
|
|
|
if(cached?.payload){const result=cached.payload,refreshedAt=new Date().toISOString(),sync={...result.sourceStatus.sync};if(sync.lastSuccessAt)sync.lagSeconds=Math.max(0,Math.floor((Date.now()-new Date(sync.lastSuccessAt).getTime())/1000));return {...result,refreshedAt,sourceStatus:{...result.sourceStatus,refreshedAt,cacheHit:true,sync}};}
|
|
|
const result=await payrollPreviewUncached(context,input,month,includeUsed,requireLive,{...options,readAcceleration:Boolean(cached?.stamp)});
|
|
|
@@ -96,18 +114,27 @@ async function payrollPreviewUncached(context,input,month,includeUsed=false,requ
|
|
|
}
|
|
|
const lines=Array.from(grouped.values()).filter(item=>{const m=payrollBusinessDate(item.lessonAt).slice(0,7);return (m===month||!m||allowLate&&m===previous)&& (includeUsed||!other.has(payrollIdentity(item)));}).map(item=>payrollCalculatedLine(item,rates,month,rules,mappingMap));
|
|
|
const rewards=await Psql.query('SELECT r.* FROM "ReviewRewardIncome" r WHERE r."company"=$1 AND r."status"=\'earned\' AND '+(includeUsed?'r."incomeMonth"=$2':'r."incomeMonth"<=$2 AND NOT EXISTS(SELECT 1 FROM "PayrollLine" l WHERE l."company"=r."company" AND l."reviewRewardId"=r."objectId" AND NOT COALESCE(l."excluded",false) AND l."batchId"<>$3)')+' ORDER BY r."objectId"',includeUsed?[co,month]:[co,month,text(input.targetId)]);
|
|
|
- lines.push(...rewards.map(r=>rewardPayrollLine(r,month)));
|
|
|
- if(!includeUsed&&input.targetId){const existing=await Psql.query('SELECT * FROM "PayrollLine" WHERE "company"=$1 AND "batchId"=$2 AND "kind"=\'lesson\' AND NOT COALESCE("excluded",false)',[co,input.targetId]),present=new Set(lines.map(payrollIdentity));for(const row of existing)if(!present.has(row.standardLessonKey))lines.push({...payrollLine(row),standardLessonKey:row.standardLessonKey,exception:'原计薪课次已缺失、跨月或被其他批次占用,请核对',amount:0});}
|
|
|
+ lines.push(...rewards.map(r=>({...rewardPayrollLine(r,month),...payrollStore(source.stores,r.storeId)})));
|
|
|
+ if(!includeUsed&&input.targetId){const existing=await Psql.query('SELECT * FROM "PayrollLine" WHERE "company"=$1 AND "batchId"=$2 AND "kind"=\'lesson\' AND NOT COALESCE("excluded",false)',[co,input.targetId]),present=new Set(lines.map(payrollIdentity));for(const row of existing)if(!present.has(row.standardLessonKey))lines.push({...payrollLine(row),...payrollStore(source.stores,row.storeId),standardLessonKey:row.standardLessonKey,exception:'原计薪课次已缺失、跨月或被其他批次占用,请核对',amount:0});}
|
|
|
return {...payrollResult(month,lines,source.sourceStatus,input),sourceVersion:source.version};
|
|
|
}
|
|
|
async function payrollPage(context,input){return storePayrollPage(context,input);}
|
|
|
-async function payrollDetailData(context,input,targetId){const co=payrollTenant(context,input),batch=await Psql.oneOrNone('SELECT * FROM "PayrollBatch" WHERE "company"=$1 AND "objectId"=$2',[co,targetId]);if(!batch||context.storeId&&number(batch.scopeStoreId)!==context.storeId)fail(404,'工资单不存在或不属于本店');const rows=await Psql.query('SELECT * FROM "PayrollLine" WHERE "company"=$1 AND "batchId"=$2 ORDER BY "lessonAt" NULLS LAST,"objectId"',[co,targetId]),lines=rows.map(row=>({...payrollLine(row),standardLessonKey:row.standardLessonKey,exclusionReason:row.exclusionReason,coachMobile:row.coachMobile}));return{...payrollSummary(batch),version:batch.version,lines,exceptions:lines.filter(r=>r.exception&&!r.excluded),coachItems:payrollCoachItems(lines,{})};}
|
|
|
+async function payrollDetailData(context,input,targetId){
|
|
|
+ const co=payrollTenant(context,input),batch=await Psql.oneOrNone('SELECT * FROM "PayrollBatch" WHERE "company"=$1 AND "objectId"=$2',[co,targetId]);
|
|
|
+ if(!batch||context.storeId&&number(batch.scopeStoreId)!==context.storeId)fail(404,'工资单不存在或不属于本店');
|
|
|
+ const [rows,stores]=await Promise.all([
|
|
|
+ Psql.query('SELECT * FROM "PayrollLine" WHERE "company"=$1 AND "batchId"=$2 ORDER BY "lessonAt" NULLS LAST,"objectId"',[co,targetId]),
|
|
|
+ payrollStoreDirectory(co)
|
|
|
+ ]);
|
|
|
+ const lines=rows.map(row=>({...payrollLine(row),...payrollStore(stores,row.storeId),standardLessonKey:row.standardLessonKey,exclusionReason:row.exclusionReason,coachMobile:row.coachMobile}));
|
|
|
+ return {...payrollSummary(batch),version:batch.version,lines,exceptions:lines.filter(r=>r.exception&&!r.excluded),coachItems:payrollCoachItems(lines,{})};
|
|
|
+}
|
|
|
async function payrollOverviewData(context,input){
|
|
|
if(context.storeId)input={...input,storeId:context.storeId};
|
|
|
const co=payrollTenant(context,input),month=text(input.month)||businessDate().slice(0,7),income=await payrollPreviewData(context,{...input,storeId:0,search:''},month,true,false,{forDashboard:input.displayOnly===true,omitSourceVersion:Boolean(context.storeId)}),batches=(await payrollPage(context,{...input,month,page:1,pageSize:100})).items;
|
|
|
const batch=batches[0],settlement=batch?await payrollDetailData(context,{},batch.objectId):null;
|
|
|
const visible=payrollResult(month,income.lines,income.sourceStatus,input),settlementTotals=settlement?payrollResult(month,settlement.lines,income.sourceStatus,input):null;
|
|
|
- const stores=context.storeId?[{storeId:context.storeId,storeName:storeNameOf((context.store||context.current).toJSON())}]:await Psql.query('SELECT "legacyUserId" AS "storeId",COALESCE(NULLIF("realName",\'\'),NULLIF("nickname",\'\'),"username") AS "storeName" FROM "_User" WHERE "company"=$1 AND ("identityType"=\'store\' OR "legacyGroupId"=2) ORDER BY "legacyUserId"',[co]);
|
|
|
+ const stores=context.storeId?[{storeId:context.storeId,storeName:storeNameOf((context.store||context.current).toJSON())}]:Array.from((await payrollStoreDirectory(co)).values());
|
|
|
const detailLines=input.summaryOnly===true?[]:number(input.lineCoachId)>0?visible.lines.filter(line=>line.coachId===number(input.lineCoachId)):visible.lines;
|
|
|
return {...visible,lines:detailLines,exceptions:detailLines.filter(line=>line.exception&&!line.excluded),batches,stores,incomeAmount:visible.payableAmount,settlementAmount:settlementTotals?.payableAmount??null,settlementAdjustmentAmount:settlementTotals?.adjustmentAmount??0,settlementCarryAmount:settlementTotals?settlementTotals.lines.filter(l=>l.kind!=='adjustment'&&l.originalMonth!==month&&!l.exception).reduce((a,l)=>a+l.amount,0):0};
|
|
|
}
|