2026-10-17 19:50:24 +08:00
'use strict' ;
// 飞书是单向查看副本。默认未启用;只连接显式配置的新账专用表。
const { now } = require ( './ledger' );
const TABLE_NAME = '新账_系统镜像' ;
const FIELDS = [[ '系统键' , 1 ],[ '类型' , 1 ],[ '单号' , 1 ],[ '状态' , 1 ],[ '日期' , 1 ],[ '销售金额' , 2 ],[ '订单利润' , 2 ],[ '已收净额' , 2 ],[ '待结算' , 2 ],[ '数据版本' , 2 ],[ '明细' , 1 ]];
class FeishuSync {
constructor ( ledger , config , fetcher = fetch ){ this . ledger = ledger ; this . config = config ; this . fetcher = fetcher ; this . busy = false ; this . checked = false ; this . token = null ; this . expires = 0 ;}
get enabled (){ return !! ( this . config ? . enabled && this . config . appId && this . config . appSecret && this . config . baseToken && this . config . tableId );}
async request ( method , route , body ){
const r = await this . fetcher ( 'https://open.feishu.cn/open-apis/' + route ,{ method , headers : { 'Content-Type' : 'application/json' ,...( this . token ? { Authorization : 'Bearer ' + this . token } : {})},...( body ? { body : JSON . stringify ( body )} : {}), signal : AbortSignal . timeout ( 20000 )});
const data = await r . json (); if ( ! r . ok || data . code !== 0 ) throw new Error ( `飞书请求失败( ${ data . code ?? r . status } ): ${ String ( data . msg || '请检查网络和应用权限' ). slice ( 0 , 180 ) } ` ); return data ;
}
async auth (){ if ( this . token && Date . now () < this . expires ) return ; const d = await this . request ( 'POST' , 'auth/v3/tenant_access_token/internal' ,{ app_id : this . config . appId , app_secret : this . config . appSecret }); this . token = d . tenant_access_token ; this . expires = Date . now () + Math . max ( 60 ,( d . expire || 7200 ) - 120 ) * 1000 ;}
get route (){ return `bitable/v1/apps/ ${ encodeURIComponent ( this . config . baseToken ) } /tables/ ${ encodeURIComponent ( this . config . tableId ) } ` ;}
async validate (){
if ( this . checked ) return ; await this . auth ();
// 防止把旧账表当作同步目标。表名和字段都核实后才允许写。
let found = false , token = '' ; do { const d = await this . request ( 'GET' , `bitable/v1/apps/ ${ encodeURIComponent ( this . config . baseToken ) } /tables?page_size=100 ${ token ? '&page_token=' + encodeURIComponent ( token ) : '' } ` ); found ||= d . data . items . some ( t => t . table_id === this . config . tableId && t . name === TABLE_NAME ); token = d . data . has_more ? d . data . page_token : '' ; if ( d . data . has_more &&! token ) throw new Error ( '飞书表分页缺失' );} while ( token );
if ( ! found ) throw new Error ( `只允许同步到专用表「 ${ TABLE_NAME } 」,请先建立新表,不使用旧销售表` );
const d = await this . request ( 'GET' , this . route + '/fields?page_size=100' ); if ( d . data . has_more ) throw new Error ( '同步表字段超过预期,请检查专用表' );
for ( const [ name , type ] of FIELDS ) if ( ! d . data . items . some ( f => f . field_name === name && f . type === type )) throw new Error ( `同步表缺少正确类型字段: ${ name } ` );
this . checked = true ;
}
async find ( entity ){
const d = await this . request ( 'POST' , this . route + '/records/search?page_size=100' ,{ filter : { conjunction : 'and' , conditions : [{ field_name : '系统键' , operator : 'is' , value : [ entity ]}]}});
if ( d . data . has_more || d . data . items . length > 1 ) throw new Error ( '同步键存在重复记录,已停止覆盖,请维护者核对' ); return d . data . items [ 0 ] || null ;
}
fields ( entity , revision ){
if ( entity === 'inventory' ) return { '系统键' : entity , '类型' : '库存快照' , '单号' : '' , '状态' : '从主账流水重算' , '日期' : now (). slice ( 0 , 10 ), '销售金额' : 0 , '订单利润' : 0 , '已收净额' : 0 , '待结算' : 0 , '数据版本' : revision , '明细' : JSON . stringify ( this . ledger . inventory ())};
const o = this . ledger . detail ( entity . slice ( 6 )); const { audit , sync ,... details } = o ;
2026-10-26 14:44:07 +08:00
return { '系统键' : entity , '类型' : o . recovery_id ? '置换订单' : '订单' , '单号' : o . number , '状态' : o . status , '日期' : o . date , '销售金额' : o . cancellationApproved ? 0 : o . total / 100 , '订单利润' : o . profit / 100 , '已收净额' : o . netReceived / 100 , '待结算' : o . settlementDue / 100 , '数据版本' : revision , '明细' : JSON . stringify ( details )};
2026-10-17 19:50:24 +08:00
}
async tick (){
if ( ! this . enabled || this . busy ) return ; this . busy = true ;
try {
await this . validate ();
for ( const job of this . ledger . rows ( 'SELECT * FROM sync WHERE revision<>done_revision ORDER BY updated LIMIT 10' )){
try {
await this . auth (); const fields = this . fields ( job . entity , job . revision ); if ( JSON . stringify ( fields ). length > 90000 ) throw new Error ( '订单明细超过同步大小,请在主系统查看,需维护者拆分镜像' );
// 每次重试先查询稳定键。写请求超时后不盲目再创建;一个服务只跑一个同步工人。
const existing = await this . find ( job . entity ); let recordId = existing ? . record_id ;
if ( recordId ) await this . request ( 'PUT' , this . route + '/records/' + encodeURIComponent ( recordId ),{ fields });
else recordId = ( await this . request ( 'POST' , this . route + '/records' ,{ fields })). data . record . record_id ;
const check = ( await this . request ( 'GET' , this . route + '/records/' + encodeURIComponent ( recordId ))). data . record ;
if ( check . fields [ '数据版本' ] !== job . revision || check . fields [ '明细' ] !== fields [ '明细' ]) throw new Error ( '写后回读不一致,保留待同步状态' );
this . ledger . run ( 'UPDATE sync SET done_revision=?,record_id=?,error=NULL,attempts=0 WHERE entity=?' , job . revision , recordId , job . entity );
} catch ( e ){ this . ledger . run ( 'UPDATE sync SET error=?,attempts=attempts+1 WHERE entity=?' , String ( e . message ). slice ( 0 , 300 ), job . entity );}
}
this . lastError = null ;
} catch ( e ){ this . lastError = String ( e . message ). slice ( 0 , 300 );} finally { this . busy = false ;}
}
status (){ return { enabled : this . enabled , busy : this . busy , error : this . lastError || null , pending : this . ledger . one ( 'SELECT COUNT(*) AS n FROM sync WHERE revision<>done_revision' ). n , failed : this . ledger . one ( 'SELECT COUNT(*) AS n FROM sync WHERE error IS NOT NULL' ). n };}
}
module . exports = { FeishuSync , FIELDS , TABLE_NAME };