@@ -0,0 +1,769 @@
# -*- coding: utf-8 -*-
""" 金蝶云星空 WebAPI 客户端:登录/会话复用/单据查询/报表取数。
设计要点(2026-11 实测,勿随意改动):
- 登录:AuthService.ValidateUser,参数 [账套ID, 账号, 密码, 2052],
成功返回 LoginResultType=1 并由服务端下发 kdservice-sessionid;
- 会话:同一个 requests.Session 可跨多次调用复用;失效时 session_alive() 返回 False,
调用方可重新 login();
- 单据查询:DynamicFormService.ExecuteBillQuery,参数为对象数组,StartRow/Limit 分页;
- 报表取数:Kingdee.K3.SCM.WebApi.ServicesStub.StockReportQueryService.GetReportData,
参数必须整体序列化为**一个 JSON 字符串**塞进 parameters[0],
FORMID/FSCHEMEID 必填,且方案必须是有元数据的方案;返回 88 个报表字段。
"""
import json
import time
import requests
import urllib3
from urllib3 . exceptions import InsecureRequestWarning
from . sites import SITES
LOGIN_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .AuthService.ValidateUser.common.kdsvc ' )
LOGOUT_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .AuthService.Logout.common.kdsvc ' )
BILL_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.ExecuteBillQuery.common.kdsvc ' )
META_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.QueryBusinessInfo.common.kdsvc ' )
REPORT_SVC = ( ' /Kingdee.K3.SCM.WebApi.ServicesStub '
' .StockReportQueryService.GetReportData,Kingdee.K3.SCM.WebApi.ServicesStub.common.kdsvc ' )
# ---- 认证 ----
LOGIN_ORG_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .AuthService.ValidateUserByOrgNumber.common.kdsvc ' )
LOGIN_SECRET_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .AuthService.LoginByAppSecret.common.kdsvc ' )
SWITCH_ORG_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.SwitchOrg.common.kdsvc ' )
# ---- 单据读写与业务动作 ----
VIEW_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.View.common.kdsvc ' )
SAVE_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.Save.common.kdsvc ' )
BATCH_SAVE_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.BatchSave.common.kdsvc ' )
SUBMIT_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.Submit.common.kdsvc ' )
AUDIT_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.Audit.common.kdsvc ' )
DELETE_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.Delete.common.kdsvc ' )
OPERATION_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.ExcuteOperation.common.kdsvc ' )
WORKFLOW_AUDIT_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.WorkflowAudit.common.kdsvc ' )
PUSH_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.Push.common.kdsvc ' )
ALLOCATE_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.Allocate.common.kdsvc ' )
GROUP_SAVE_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.GroupSave.common.kdsvc ' )
GROUP_DELETE_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.GroupDelete.common.kdsvc ' )
SEND_MSG_SVC = ( ' /Kingdee.BOS.WebApi.ServicesStub '
' .DynamicFormService.SendMsg.common.kdsvc ' )
# ---- 业务专用服务 ----
INVENTORY_SVC = ( ' /Kingdee.K3.SCM.WebApi.ServicesStub '
' .InventoryQueryService.GetInventoryData '
' ,Kingdee.K3.SCM.WebApi.ServicesStub.common.kdsvc ' )
UA = ( ' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
' (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 ' )
SESSION_DEAD = ( ' 会话信息已丢失 ' , ' 请重新登录 ' , ' Unexpectable request ' )
class ErpError ( RuntimeError ) :
""" ERP 调用失败(登录失败 / 接口报错 / 返回结构异常)。 """
class ErpClient :
""" 一个 ERP 站点(新版 criterion / 旧版 erp)的 WebAPI 客户端。 """
def __init__ ( self , erp = ' new ' , host = None , acct = None ,
timeout = 60 , verify_ssl = False , logger = None , retry = 3 ) :
""" erp:站点键(SITES 里的 ' new ' / ' old ' / ' test ' )。
站点属性(host / acct / base_path)都可在构造时覆盖;
base_path 指应用部署路径前缀:生产两套是虚拟目录 `/K3Cloud`,
部分部署(如金蝶测试服 k3cloud.info.shuhe.leus.cc)直接挂在根路径即 ` ' ' `。
"""
if erp not in SITES :
raise ErpError ( f " 未知 ERP 站点: { erp } (可选 { list ( SITES ) } ) " )
site = SITES [ erp ]
self . erp = erp
self . host = host or site [ ' host ' ]
self . acct = acct or site [ ' acct ' ]
self . base_path = str ( site . get ( ' base_path ' , ' /K3Cloud ' ) ) . rstrip ( ' / ' )
self . timeout = timeout
self . verify_ssl = verify_ssl
self . retry = max ( 1 , int ( retry ) )
self . log = logger or ( lambda msg : None )
self . session = requests . Session ( )
# 内网 ERP 用自签/内部证书,verify_ssl=False 属预期行为:
# 关掉 urllib3 的 InsecureRequestWarning,避免它写 stderr 被壳子记成 [ERROR]
if not self . verify_ssl :
urllib3 . disable_warnings ( InsecureRequestWarning )
# ---------- 基础 ----------
@property
def base ( self ) :
return f ' https:// { self . host } { self . base_path } '
def _post ( self , path , body , timeout = None , headers = None ) :
h = { ' User-Agent ' : UA }
if headers :
h . update ( headers )
try :
r = self . session . post ( self . base + path , json = body , headers = h ,
timeout = timeout or self . timeout , verify = self . verify_ssl )
except Exception as e :
raise ErpError ( f ' 请求异常( { path } ): { e } ' )
return r
@staticmethod
def _json ( r , what ) :
try :
return r . json ( )
except Exception :
raise ErpError ( f ' { what } 返回非 JSON( HTTP { r . status_code } ): { ( r . text or " " ) [ : 180 ] } ' )
# ---------- 登录与会话 ----------
def login ( self , username , password ) :
""" 账密登录,成功后本实例可直接调用其它方法。失败抛 ErpError。 """
username = str ( username or ' ' ) . strip ( )
password = str ( password or ' ' )
if not ( username and password ) :
raise ErpError ( ' ERP 登录账号/密码缺失 ' )
last = ' '
for attempt in range ( 1 , self . retry + 1 ) :
self . log ( f ' [erpsdk] 第 { attempt } / { self . retry } 次登录( { self . host } ,账套 { self . acct } ) ' )
r = self . _post ( LOGIN_SVC , { ' parameters ' : [ self . acct , username , password , 2052 ] } )
j = self . _json ( r , ' 登录 ' )
if j . get ( ' LoginResultType ' ) == 1 :
self . username = username
self . log ( f ' [erpsdk] 登录成功,会话 { j . get ( " KDSVCSessionId " ) } ' )
return self
msg = str ( j . get ( ' Message ' ) or j . get ( ' MessageCode ' ) or ' 未知错误 ' )
if ' 密码 ' in msg or ' 用户名 ' in msg :
raise ErpError ( f ' ERP 登录失败: { msg } ' )
last = msg
self . log ( f ' [erpsdk] 登录未通过: { msg } ' )
time . sleep ( 1 )
raise ErpError ( f ' ERP 登录失败(重试耗尽): { last } ' )
def session_alive ( self ) :
""" 探活:探针查询返回 JSON 且不含会话失效关键字即有效(权限报错也算有效)。 """
try :
r = self . _post ( BILL_SVC , { ' parameters ' : [ {
' FormId ' : ' BD_MATERIAL ' , ' FieldKeys ' : ' FNumber ' , ' FilterString ' : ' ' ,
' OrderString ' : ' ' , ' TopRowCount ' : 1 , ' StartRow ' : 0 , ' Limit ' : 0 } ] } ,
timeout = self . timeout )
except ErpError :
return False
t = ( r . text or ' ' ) . strip ( )
if r . status_code != 200 or any ( k in t for k in SESSION_DEAD ) :
return False
return t . startswith ( ( ' [ ' , ' { ' ) )
def logout ( self ) :
try :
self . _post ( LOGOUT_SVC , { ' parameters ' : [ ] } )
except Exception :
pass
# ---------- 单据查询 ----------
def bill_query ( self , form_id , field_keys , filter_string = ' ' , order_string = ' ' ,
limit = None , start_row = 0 , top_row_count = 0 ) :
""" ExecuteBillQuery 分页取数,返回行列表(每行为 list)。
limit=None 表示一次取完(底层 Limit=0 / TopRowCount 由调用方给);
给 limit 则按 StartRow 循环直到取完。
"""
body = { ' FormId ' : form_id , ' FieldKeys ' : field_keys ,
' FilterString ' : filter_string or ' ' , ' OrderString ' : order_string or ' ' ,
' TopRowCount ' : int ( top_row_count or 0 ) , ' StartRow ' : int ( start_row or 0 ) ,
' Limit ' : int ( limit or 0 ) }
r = self . _post ( BILL_SVC , { ' parameters ' : [ body ] } ,
timeout = max ( self . timeout , 120 ) )
text = ( r . text or ' ' ) . strip ( )
if text . startswith ( ' response_error ' ) :
line = [ ln for ln in text . splitlines ( ) if ' 错误信息 ' in ln ]
raise ErpError ( ' 单据查询报错: ' + ( line [ - 1 ] . strip ( ) if line else text [ : 150 ] ) )
data = self . _json ( r , ' 单据查询 ' )
# 业务错误以 [[{"Result":{...}}]] 形式返回
if ( isinstance ( data , list ) and data and isinstance ( data [ 0 ] , list )
and data [ 0 ] and isinstance ( data [ 0 ] [ 0 ] , dict ) and ' Result ' in data [ 0 ] [ 0 ] ) :
rs = data [ 0 ] [ 0 ] [ ' Result ' ] [ ' ResponseStatus ' ]
if not rs . get ( ' IsSuccess ' , True ) :
errs = rs . get ( ' Errors ' ) or [ { } ]
raise ErpError ( ' 单据查询被拒绝: ' + str ( errs [ 0 ] . get ( ' Message ' ) ) [ : 150 ] )
return data
def bill_query_all ( self , form_id , field_keys , filter_string = ' ' , order_string = ' ' ,
page_size = 2000 , max_rows = None ) :
""" 分页取全量(按 StartRow 循环),返回行列表。
max_rows 给定时最多取这么多行(防止误查全表把内存/Excel 写爆)。
"""
rows , start = [ ] , 0
while True :
page = self . bill_query ( form_id , field_keys , filter_string , order_string ,
limit = page_size , start_row = start )
if not page :
break
rows . extend ( page )
self . log ( f ' [erpsdk] 单据 { form_id } 已取 { len ( rows ) } 行 ' )
if max_rows and len ( rows ) > = int ( max_rows ) :
self . log ( f ' [erpsdk] 已达行数上限 { max_rows } ,停止取数(请用 FilterString 收窄条件) ' )
break
if len ( page ) < page_size :
break
start + = page_size
return rows
# ---------- 元数据 ----------
def query_metadata ( self , form_id ) :
""" 表单元数据(字段标识/名称/引用对象),用于生成 FieldKeys。 """
r = self . _post ( META_SVC , { ' parameters ' : [ json . dumps ( { ' FormId ' : form_id } , ensure_ascii = False ) ] } ,
timeout = max ( self . timeout , 120 ) )
j = self . _json ( r , ' 元数据查询 ' )
res = ( j . get ( ' Result ' ) or { } )
if not ( res . get ( ' ResponseStatus ' ) or { } ) . get ( ' IsSuccess ' , False ) :
errs = ( res . get ( ' ResponseStatus ' ) or { } ) . get ( ' Errors ' ) or [ { } ]
raise ErpError ( ' 元数据查询失败: ' + str ( errs [ 0 ] . get ( ' Message ' ) ) [ : 150 ] )
return res . get ( ' NeedReturnData ' ) or { }
# ---------- 报表取数 ----------
def report_query ( self , form_id , scheme_id , begin , end ,
org_id = None , stock_codes = None , limit = 5000 ,
more_conditions = None , progress = None , max_pages = None ) :
""" 分页报表取数(物料收发汇总等分页账表),返回行字典列表。
参数:
form_id 报表 FORMID,如 STK_StockSummaryRpt
scheme_id 过滤方案 ID(必须是有元数据的方案,不能是系统默认方案)
begin/end 日期区间 YYYY-MM-DD → 快捷条件 BeginDate/EndDate
org_id 库存组织内码(快捷条件 StockOrgId,只认内码,不认编码)
stock_codes 仓库编码列表 → 高级条件 FSTOCKNUMBER(多条 OR)
more_conditions 额外高级条件(原样追加)
limit 单页行数(接口上限 10000,默认 5000)
max_pages 最多取几页(None=取全量;自检/抽样传 1 避免整表翻页)
"""
quickly = [ { ' FieldName ' : ' BeginDate ' , ' FieldValue ' : str ( begin ) } ,
{ ' FieldName ' : ' EndDate ' , ' FieldValue ' : str ( end ) } ]
if org_id :
quickly . append ( { ' FieldName ' : ' StockOrgId ' , ' FieldValue ' : str ( org_id ) } )
more = [ ]
codes = [ str ( c ) . strip ( ) for c in ( stock_codes or [ ] ) if str ( c ) . strip ( ) ]
for i , code in enumerate ( codes ) :
more . append ( { ' Left ' : ' ' , ' FieldName ' : ' FSTOCKNUMBER ' , ' Compare ' : ' = ' ,
' FieldValue ' : code , ' Right ' : ' ' ,
' Logic ' : ' OR ' if i < len ( codes ) - 1 else ' AND ' } )
if more_conditions :
more . extend ( more_conditions )
rows , start = [ ] , 0
while True :
payload = { ' FORMID ' : form_id , ' FSCHEMEID ' : scheme_id ,
' QuicklyCondition ' : quickly , ' MoreCondition ' : more ,
' StartRow ' : start , ' Limit ' : int ( limit ) }
t0 = time . time ( )
r = self . _post ( REPORT_SVC , { ' parameters ' : [ json . dumps ( payload , ensure_ascii = False ) ] } ,
timeout = max ( self . timeout , 240 ) ,
headers = { ' Content-Type ' : ' application/json ' } )
text = ( r . text or ' ' ) . strip ( )
if text . startswith ( ' response_error ' ) :
line = [ ln for ln in text . splitlines ( ) if ' 错误信息 ' in ln ]
raise ErpError ( ' 报表接口报错: ' + ( line [ - 1 ] . strip ( ) if line else text [ : 150 ] ) )
j = self . _json ( r , ' 报表取数 ' )
if not j . get ( ' success ' ) :
raise ErpError ( f ' 报表取数失败: { j . get ( " message " ) } ' )
page = j . get ( ' data ' ) or [ ]
total = j . get ( ' TotalCount ' ) or 0
self . log ( f ' [erpsdk] 报表 { form_id } { begin } ~ { end } 第 { start } ~ { start + len ( page ) } 行, '
f ' 共 { total } 行, { int ( ( time . time ( ) - t0 ) * 1000 ) } ms ' )
rows . extend ( page )
if progress :
try :
progress ( len ( rows ) , total )
except Exception :
pass
if len ( page ) < int ( limit ) or len ( rows ) > = total :
break
if max_pages and ( start / / max ( 1 , int ( limit ) ) + 1 ) > = int ( max_pages ) :
break
start + = int ( limit )
return rows
# ================== 写操作与业务动作(按金蝶云星空 WebAPI 契约实现) ==================
# 这些方法挂在 ErpClient 上(见文件末尾的 _attach_write_apis)。
# 统一约定:
# - 失败抛 ErpError(带服务端 Errors[0].Message);
# - 成功返回服务端 Result 节点(含 Id / Number / 单据编号等),便于调用方取单号;
# - 「引用型」字段用 ref(number=…) / ref(id=…) 构造,避免手写 {"FNumber": …} 出错。
def _ref ( number = None , id = None ) :
""" 构造基础资料引用值:ref( ' 37000365 ' ) → { ' FNumber ' : ' 37000365 ' }; ref(id=5718953) → { ' Id ' : 5718953}。
部分字段(如付款申请单的申请人 FBJ_SQR)在服务端只存内码/工号,
这时要用 staff_ref()(工号)或 ref(id=…),按 FNumber 传会命中不到。
"""
if id is not None :
return { ' Id ' : id }
if number is not None :
return { ' FNumber ' : str ( number ) }
raise ErpError ( ' ref() 至少需要 number 或 id ' )
def _staff_ref ( staff_number ) :
""" 员工/经办人类字段的引用值(键为 FSTAFFNUMBER 工号)。
金蝶官方 Save 报文里 `FBJ_SQR`(申请人)、`F_VTUY_Ba`(往来员工)都是这种结构:
staff_ref( ' 37000025 ' ) → { ' FSTAFFNUMBER ' : ' 37000025 ' }
**实测**:按 FNumber 或 Id 传都会被服务端忽略(申请人保持登录人),只有 FSTAFFNUMBER 生效。
"""
if not staff_number :
raise ErpError ( ' staff_ref() 需要工号 ' )
return { ' FSTAFFNUMBER ' : str ( staff_number ) }
def _user_ref ( user_id ) :
""" 用户类字段的引用值(键为 FUSERID),如 F_VTUY_PrinterId_re5(打印人)。 """
if not user_id :
raise ErpError ( ' user_ref() 需要用户内码 ' )
return { ' FUSERID ' : str ( user_id ) }
def _save_options ( need_return_fields = None , sub_system_id = ' ' , is_verify_base_data_field = False ,
is_entry_batch_fill = True , validate_flag = True , number_search = True ,
is_auto_adjust_field = True , interation_flags = ' ' , ignore_interation_flag = True ,
is_control_precision = False , validate_repeat_json = False ) :
""" 构造 Save 的可选参数包,直接作为 `save(..., extra=…)` 传入。
字段含义见金蝶官方 WebAPI 文档(Save 的 data 节点),常用:
need_return_fields 需要返回的字段,如 [ ' FBillNo ' , ' FPAYAPPLYENTRY.FCOSTID ' ]
is_verify_base_data_field 是否验证所有基础资料有效性(严格模式建议 True)
validate_flag 是否校验数据合法性(False 时不校验,仅调试用)
number_search 是否用编码搜索基础资料(默认 True)
"""
return {
' NeedReturnFields ' : list ( need_return_fields or [ ] ) ,
' SubSystemId ' : sub_system_id or ' ' ,
' IsVerifyBaseDataField ' : bool ( is_verify_base_data_field ) ,
' IsEntryBatchFill ' : bool ( is_entry_batch_fill ) ,
' ValidateFlag ' : bool ( validate_flag ) ,
' NumberSearch ' : bool ( number_search ) ,
' IsAutoAdjustField ' : bool ( is_auto_adjust_field ) ,
' InterationFlags ' : interation_flags or ' ' ,
' IgnoreInterationFlag ' : bool ( ignore_interation_flag ) ,
' IsControlPrecision ' : bool ( is_control_precision ) ,
' ValidateRepeatJson ' : bool ( validate_repeat_json ) ,
}
# 金蝶返回的 MsgCode 语义(官方文档「错误代码说明」)
MSG_CODE = {
0 : ' 默认 ' , 1 : ' 上下文丢失 ' , 2 : ' 没有权限 ' , 3 : ' 操作标识为空 ' , 4 : ' 异常 ' ,
5 : ' 单据标识为空 ' , 6 : ' 数据库操作失败 ' , 7 : ' 许可错误 ' , 8 : ' 参数错误 ' ,
9 : ' 指定字段/值不存在 ' , 10 : ' 未找到对应数据 ' , 11 : ' 验证失败 ' , 12 : ' 不可操作 ' ,
13 : ' 网控冲突 ' , 14 : ' 调用限制 ' , 15 : ' 禁止管理员登录 ' ,
}
def _bill_key ( numbers = None , ids = None , create_org_id = None ) :
""" Submit/Audit/Delete 等单据动作的第二个参数(Numbers / Ids 二选一,可都带)。 """
body = { }
if create_org_id is not None :
body [ ' CreateOrgId ' ] = str ( create_org_id )
if numbers :
body [ ' Numbers ' ] = list ( numbers ) if isinstance ( numbers , ( list , tuple ) ) else [ str ( numbers ) ]
body [ ' Ids ' ] = ' , ' . join ( str ( i ) for i in ids ) if isinstance ( ids , ( list , tuple ) ) else ( str ( ids ) if ids else ' ' )
return json . dumps ( body , ensure_ascii = False )
def _impl_login_by_org ( self , username , password , org_number , lcid = 2052 ) :
""" 按组织编号登录(ValidateUserByOrgNumber):登录后会话即锁定该组织上下文。 """
body = { ' parameters ' : [ self . acct , str ( username ) . strip ( ) , str ( password ) , int ( lcid ) , str ( org_number ) ] }
return self . _login_with ( LOGIN_ORG_SVC , body , f ' 按组织 { org_number } 登录 ' )
def _impl_login_by_app_secret ( self , username , app_id , app_secret , lcid = 2052 ) :
""" AppSecret 登录(LoginByAppSecret):适合无人值守的服务账号。 """
body = { ' parameters ' : [ self . acct , str ( username ) . strip ( ) , app_id , app_secret , int ( lcid ) ] }
return self . _login_with ( LOGIN_SECRET_SVC , body , ' AppSecret 登录 ' )
def _impl_login_with ( self , path , body , what ) :
last = ' '
for attempt in range ( 1 , self . retry + 1 ) :
self . log ( f ' [erpsdk] 第 { attempt } / { self . retry } 次 { what } ( { self . host } ,账套 { self . acct } ) ' )
r = self . _post ( path , body )
j = self . _json ( r , what )
if j . get ( ' LoginResultType ' ) == 1 :
self . log ( f ' [erpsdk] { what } 成功,会话 { j . get ( " KDSVCSessionId " ) } ' )
return self
msg = str ( j . get ( ' Message ' ) or j . get ( ' MessageCode ' ) or ' 未知错误 ' )
if ' 密码 ' in msg or ' 用户名 ' in msg :
raise ErpError ( f ' { what } 失败: { msg } ' )
last = msg
time . sleep ( 1 )
raise ErpError ( f ' { what } 失败(重试耗尽): { last } ' )
def _result ( self , r , what ) :
""" 解析 .kdsvc 返回:抽出 Result 节点,IsSuccess=false 时抛 ErpError。 """
text = ( r . text or ' ' ) . strip ( )
if text . startswith ( ' response_error ' ) :
line = [ ln for ln in text . splitlines ( ) if ' 错误信息 ' in ln ]
raise ErpError ( f ' { what } 报错: ' + ( line [ - 1 ] . strip ( ) if line else text [ : 150 ] ) )
j = self . _json ( r , what )
res = j . get ( ' Result ' , j ) if isinstance ( j , dict ) else j
if isinstance ( res , list ) :
# 批量接口返回 [{Result:{...}}]
res = [ ( ( x or { } ) . get ( ' Result ' , x ) ) for x in res if isinstance ( x , dict ) ]
bad = [ x for x in res if isinstance ( x , dict )
and not ( ( x . get ( ' ResponseStatus ' ) or { } ) . get ( ' IsSuccess ' , True ) ) ]
if bad :
errs = ( bad [ 0 ] . get ( ' ResponseStatus ' ) or { } ) . get ( ' Errors ' ) or [ { } ]
raise ErpError ( f ' { what } 失败: ' + str ( errs [ 0 ] . get ( ' Message ' ) ) [ : 200 ] )
return res
status = ( res or { } ) . get ( ' ResponseStatus ' ) or { }
if status and not status . get ( ' IsSuccess ' , True ) :
errs = status . get ( ' Errors ' ) or [ { } ]
raise ErpError ( f ' { what } 失败: ' + str ( errs [ 0 ] . get ( ' Message ' ) ) [ : 200 ] )
return res or { }
def _impl_switch_org ( self , org_number ) :
""" 切换会话的当前组织(DynamicFormService.SwitchOrg)。 """
body = { ' parameters ' : [ json . dumps ( { ' OrgNumber ' : str ( org_number ) } , ensure_ascii = False ) ] }
self . _result ( self . _post ( SWITCH_ORG_SVC , body ) , ' 切换组织 ' )
self . log ( f ' [erpsdk] 已切换组织上下文 → { org_number } ' )
return self
def _impl_view ( self , form_id , number = None , id = None , create_org_id = None ) :
""" 查看单据,返回完整单据 JSON(字段标识为大写形式,如 FBILLNo / FPAYAPPLYENTRY)。 """
key = { }
if number :
key [ ' Number ' ] = str ( number )
if id is not None :
key [ ' Id ' ] = str ( id )
if create_org_id is not None :
key [ ' CreateOrgId ' ] = str ( create_org_id )
if not key :
raise ErpError ( ' view() 需要 number 或 id ' )
body = { ' parameters ' : [ form_id , json . dumps ( key , ensure_ascii = False ) ] }
res = self . _result ( self . _post ( VIEW_SVC , body , timeout = max ( self . timeout , 120 ) ) , ' 查看单据 ' )
return res . get ( ' Result ' ) or res
def _impl_save ( self , form_id , model , need_update_fields = None , is_delete_entry = True ,
extra = None , what = ' 保存 ' ) :
""" 保存单据(DynamicFormService.Save)。
model 直接传字段字典,例如:
erp.save( ' CN_PAYAPPLY ' , {
' FBILLTYPEID ' : erp_ref( ' FKSQ006.0YS ' ),
' FDATE ' : ' 2026-10-30 ' ,
' FPAYAPPLYENTRY ' : [ { ' FCOSTID ' : erp_ref( ' 0111001 ' ), ' FAPPLYAMOUNTFOR ' : 2000}],
})
返回服务端 Result(含 Id / Number 等)。
"""
payload = { ' Creator ' : ' ' , ' NeedUpDateFields ' : list ( need_update_fields or [ ] ) ,
' IsDeleteEntry ' : bool ( is_delete_entry ) }
if extra :
payload . update ( extra )
payload [ ' Model ' ] = model
body = { ' parameters ' : [ form_id , json . dumps ( payload , ensure_ascii = False ) ] }
res = self . _result ( self . _post ( SAVE_SVC , body , timeout = max ( self . timeout , 120 ) ) , what )
num = res . get ( ' Number ' ) or res . get ( ' FBillNo ' )
self . log ( f ' [erpsdk] { what } 成功: { form_id } Id= { res . get ( " Id " ) } 单号= { num } ' )
return res
def _impl_batch_save ( self , form_id , models , need_update_fields = None , is_delete_entry = True ) :
""" 批量保存(DynamicFormService.BatchSave),models 为字段字典列表。 """
payload = { ' Creator ' : ' ' , ' NeedUpDateFields ' : list ( need_update_fields or [ ] ) ,
' IsDeleteEntry ' : bool ( is_delete_entry ) , ' Model ' : list ( models ) }
body = { ' parameters ' : [ form_id , json . dumps ( payload , ensure_ascii = False ) ] }
res = self . _result ( self . _post ( BATCH_SAVE_SVC , body , timeout = max ( self . timeout , 180 ) ) , ' 批量保存 ' )
self . log ( f ' [erpsdk] 批量保存完成: { form_id } 共 { len ( models ) } 条 ' )
return res
def _impl_bill_action ( self , path , form_id , numbers = None , ids = None , create_org_id = None , what = ' 单据操作 ' ) :
""" Submit / Audit / UnAudit 等「按单据编号或内码」的动作。 """
if not numbers and not ids :
raise ErpError ( f ' { what } 需要 numbers 或 ids ' )
body = { ' parameters ' : [ form_id , _bill_key ( numbers , ids , create_org_id ) ] }
res = self . _result ( self . _post ( path , body , timeout = max ( self . timeout , 120 ) ) , what )
self . log ( f ' [erpsdk] { what } 完成: { form_id } { numbers or ids } ' )
return res
def _impl_submit ( self , form_id , numbers = None , ids = None , create_org_id = None ) :
""" 提交单据(状态 A → B)。支持工作流的单据提交后进入审批流。 """
return self . _bill_action ( SUBMIT_SVC , form_id , numbers , ids , create_org_id , ' 提交 ' )
def _impl_audit ( self , form_id , numbers = None , ids = None , create_org_id = None ) :
""" 审核单据(B → C)。走工作流的单据请用 workflow_audit。 """
return self . _bill_action ( AUDIT_SVC , form_id , numbers , ids , create_org_id , ' 审核 ' )
def _impl_unaudit ( self , form_id , numbers = None , ids = None , create_org_id = None ) :
""" 反审核(C → B),走 ExcuteOperation 的 UnAudit 操作。 """
return self . execute_operation ( form_id , ' UnAudit ' , numbers , ids , create_org_id , ' 反审核 ' )
def _impl_delete ( self , form_id , numbers = None , ids = None ) :
""" 删除单据(仅草稿态可删)。 """
if not ids and not numbers :
raise ErpError ( ' 删除需要 ids 或 numbers ' )
body = { ' parameters ' : [ form_id , _bill_key ( numbers , ids ) ] }
res = self . _result ( self . _post ( DELETE_SVC , body , timeout = max ( self . timeout , 120 ) ) , ' 删除 ' )
self . log ( f ' [erpsdk] 删除完成: { form_id } { ids or numbers } ' )
return res
def _impl_execute_operation ( self , form_id , op_number , numbers = None , ids = None ,
create_org_id = None , what = None , extra_key = None , extra_value = None ) :
""" 执行单据操作(DynamicFormService.ExcuteOperation)。
常用 op_number: UnSubmit(撤销提交)、UnAudit(反审核)、Cancel(作废)、
Forbid(禁用)、Enable(启用)、ToStart(执行至开工)等。
"""
if not numbers and not ids :
raise ErpError ( ' ExcuteOperation 需要 numbers 或 ids ' )
key = _bill_key ( numbers , ids , create_org_id )
if extra_key :
d = json . loads ( key )
d [ extra_key ] = extra_value
key = json . dumps ( d , ensure_ascii = False )
body = { ' parameters ' : [ form_id , op_number , key ] }
res = self . _result ( self . _post ( OPERATION_SVC , body , timeout = max ( self . timeout , 120 ) ) ,
what or f ' 操作 { op_number } ' )
self . log ( f ' [erpsdk] 操作 { op_number } 完成: { form_id } { numbers or ids } ' )
return res
def _impl_forbid ( self , form_id , numbers = None , ids = None ) :
""" 禁用基础资料(Forbid)。 """
return self . execute_operation ( form_id , ' Forbid ' , numbers , ids , what = ' 禁用 ' )
def _impl_enable ( self , form_id , numbers = None , ids = None ) :
""" 启用基础资料(Enable)。 """
return self . execute_operation ( form_id , ' Enable ' , numbers , ids , what = ' 启用 ' )
def _impl_cancel ( self , form_id , numbers = None , ids = None ) :
""" 作废单据(Cancel)。 """
return self . execute_operation ( form_id , ' Cancel ' , numbers , ids , what = ' 作废 ' )
def _impl_operations ( self , form_id ) :
""" 列出一个单据类型支持的操作码(OperationNumber + 中文名)。
金蝶各单据类型的**操作码不统一**:多数单据「撤销提交」是 `UnSubmit`,
但付款申请单(CN_PAYAPPLY)把它叫 `CancelAssign`。所以撤单前应先查这里,
不要凭经验写死。结果按 form_id 缓存,避免重复请求元数据。
"""
cache = getattr ( self , ' _ops_cache ' , None )
if cache is None :
cache = self . _ops_cache = { }
if form_id not in cache :
md = self . query_metadata ( form_id )
items = [ ]
for o in ( md . get ( ' Operations ' ) or [ ] ) :
nm = o . get ( ' OperationName ' ) or [ ]
cn = next ( ( x . get ( ' Value ' ) for x in nm if x . get ( ' Key ' ) == 2052 ) , ' ' )
items . append ( { ' number ' : o . get ( ' OperationNumber ' ) or ' ' , ' name ' : cn or ' ' } )
cache [ form_id ] = items
return cache [ form_id ]
def _impl_revoke ( self , form_id , numbers = None , ids = None , create_org_id = None ) :
""" 撤销提交(把已提交单据退回可删除状态)。
自动探测单据类型的撤销操作码:
1) 优先 `UnSubmit`
2) 其次中文名「撤销」的操作(付款申请单是 `CancelAssign`)
"""
ops = self . operations ( form_id )
if not ops :
raise ErpError ( f ' { form_id } 没有可用的操作定义(元数据未返回 Operations) ' )
by_number = { o [ ' number ' ] for o in ops }
target = None
if ' UnSubmit ' in by_number :
target = ' UnSubmit '
else :
for o in ops :
if o [ ' name ' ] == ' 撤销 ' :
target = o [ ' number ' ]
break
if target is None and ' CancelAssign ' in by_number :
target = ' CancelAssign '
if not target :
raise ErpError ( f ' { form_id } 未找到撤销操作,可用操作: '
+ ' 、 ' . join ( f " { o [ ' number ' ] } ( { o [ ' name ' ] } ) " for o in ops ) )
self . log ( f ' [erpsdk] { form_id } 撤销操作码 = { target } ' )
return self . execute_operation ( form_id , target , numbers , ids , create_org_id , what = ' 撤销 ' )
def _impl_unsubmit ( self , form_id , numbers = None , ids = None ) :
""" 撤销提交(同 revoke,自动探测操作码)。 """
return self . revoke ( form_id , numbers , ids )
def _impl_workflow_audit ( self , form_id , numbers = None , ids = None , user_id = 0 , user_name = ' ' ,
approval_type = 1 , action_result_id = ' ' ) :
""" 工作流审批(WorkflowAudit)。approval_type: 1=同意(按环境实测确认)。 """
if not numbers and not ids :
raise ErpError ( ' 工作流审批需要 numbers 或 ids ' )
data = { ' FormId ' : form_id , ' Ids ' : ' , ' . join ( ids ) if isinstance ( ids , ( list , tuple ) ) else ( ids or ' ' ) ,
' Numbers ' : list ( numbers ) if isinstance ( numbers , ( list , tuple ) ) else ( [ str ( numbers ) ] if numbers else [ ] ) ,
' UserId ' : int ( user_id ) , ' UserName ' : str ( user_name ) ,
' ApprovalType ' : int ( approval_type ) , ' ActionResultId ' : action_result_id }
body = { ' parameters ' : [ json . dumps ( data , ensure_ascii = False ) ] }
res = self . _result ( self . _post ( WORKFLOW_AUDIT_SVC , body , timeout = max ( self . timeout , 120 ) ) , ' 工作流审批 ' )
self . log ( f ' [erpsdk] 工作流审批完成: { form_id } { numbers or ids } ' )
return res
def _impl_push ( self , form_id , numbers = None , ids = None , rule_id = None , target_org_id = None ,
target_bill_type_id = None , target_form_id = None , custom_params = None ,
is_enable_default_rule = ' false ' ) :
""" 下推(Push):源单 → 目标单,返回目标单数据。 """
if not numbers and not ids :
raise ErpError ( ' 下推需要 numbers 或 ids ' )
data = { ' Ids ' : ' , ' . join ( ids ) if isinstance ( ids , ( list , tuple ) ) else ( ids or ' ' ) ,
' Numbers ' : list ( numbers ) if isinstance ( numbers , ( list , tuple ) ) else ( [ str ( numbers ) ] if numbers else [ ] ) ,
' RuleId ' : rule_id or ' ' , ' TargetBillTypeId ' : target_bill_type_id or ' ' ,
' TargetOrgId ' : ' ' if target_org_id is None else str ( target_org_id ) ,
' TargetFormId ' : target_form_id or ' ' ,
' IsEnableDefaultRule ' : is_enable_default_rule ,
' CustomParams ' : custom_params or { } }
body = { ' parameters ' : [ form_id , json . dumps ( data , ensure_ascii = False ) ] }
res = self . _result ( self . _post ( PUSH_SVC , body , timeout = max ( self . timeout , 180 ) ) , ' 下推 ' )
self . log ( f ' [erpsdk] 下推完成: { form_id } → { target_form_id or rule_id or " 默认规则 " } ' )
return res
def _impl_allocate ( self , form_id , pk_ids , to_org_ids , is_auto_submit_and_audit = ' false ' ) :
""" 分配(Allocate):把基础资料分配到目标组织。pk_ids / to_org_ids 可为逗号串或列表。 """
def _join ( v ) :
return ' , ' . join ( str ( x ) for x in v ) if isinstance ( v , ( list , tuple ) ) else str ( v )
data = { ' IsAutoSubmitAndAudit ' : is_auto_submit_and_audit ,
' PkIds ' : _join ( pk_ids ) , ' TOrgIds ' : _join ( to_org_ids ) }
body = { ' parameters ' : [ form_id , json . dumps ( data , ensure_ascii = False ) ] }
res = self . _result ( self . _post ( ALLOCATE_SVC , body , timeout = max ( self . timeout , 180 ) ) , ' 分配 ' )
self . log ( f ' [erpsdk] 分配完成: { form_id } → { data [ " TOrgIds " ] } ' )
return res
def _impl_group_save ( self , form_id , model ) :
""" 分组保存(GroupSave):物料分组 / 客户分组等树形基础资料。 """
body = { ' parameters ' : [ form_id , json . dumps ( model , ensure_ascii = False ) ] }
res = self . _result ( self . _post ( GROUP_SAVE_SVC , body , timeout = max ( self . timeout , 120 ) ) , ' 分组保存 ' )
self . log ( f ' [erpsdk] 分组保存完成: { form_id } ' )
return res
def _impl_group_delete ( self , form_id , group_field_key , group_pk_ids ) :
""" 分组删除(GroupDelete)。 """
data = { ' FormId ' : form_id , ' GroupFieldKey ' : group_field_key , ' GroupPkIds ' : str ( group_pk_ids ) }
body = { ' parameters ' : [ json . dumps ( data , ensure_ascii = False ) ] }
res = self . _result ( self . _post ( GROUP_DELETE_SVC , body , timeout = max ( self . timeout , 120 ) ) , ' 分组删除 ' )
self . log ( f ' [erpsdk] 分组删除完成: { form_id } { group_pk_ids } ' )
return res
def _impl_send_msg ( self , models ) :
""" 发送消息(SendMsg)。models: [ { ' FTitle ' , ' FContent ' , ' FReceivers ' , ' FType ' }]。 """
body = { ' parameters ' : [ { ' Model ' : list ( models ) } ] }
res = self . _result ( self . _post ( SEND_MSG_SVC , body , timeout = max ( self . timeout , 120 ) ) , ' 发送消息 ' )
self . log ( f ' [erpsdk] 消息已发送: { len ( models ) } 条 ' )
return res
def _impl_get_inventory ( self , stock_numbers = None , material_numbers = None ,
page_index = 1 , page_rows = 2000 , show_aux_prop = False , show_stock_loc = False ) :
""" 即时库存查询(InventoryQueryService.GetInventoryData)。
stock_numbers / material_numbers 可传逗号串或列表;三者全空会报「不能全为空」。
"""
def _join ( v ) :
if not v :
return ' '
return ' , ' . join ( str ( x ) for x in v ) if isinstance ( v , ( list , tuple ) ) else str ( v )
data = { ' fstocknumbers ' : _join ( stock_numbers ) , ' fmaterialnumbers ' : _join ( material_numbers ) ,
' isshowauxprop ' : bool ( show_aux_prop ) , ' isshowstockloc ' : bool ( show_stock_loc ) ,
' pageindex ' : int ( page_index ) , ' pagerows ' : int ( page_rows ) }
body = { ' parameters ' : [ json . dumps ( data , ensure_ascii = False ) ] }
r = self . _post ( INVENTORY_SVC , body , timeout = max ( self . timeout , 180 ) )
j = self . _json ( r , ' 即时库存 ' )
if not j . get ( ' success ' ) :
raise ErpError ( f ' 即时库存查询失败: { j . get ( " message " ) } ' )
self . log ( f ' [erpsdk] 即时库存 { j . get ( " rowcount " ) } 条 ' )
return j . get ( ' data ' ) or [ ]
def _impl_find ( self , form_id , field_keys , filter_string , order_string = ' ' , limit = 10 ) :
""" 按条件查单据(bill_query 的语义化封装),返回行列表;查重/幂等校验常用。 """
return self . bill_query ( form_id , field_keys , filter_string ,
order_string or ' FID DESC ' , limit = limit )
def _attach_write_apis ( ) :
""" 把写操作挂到 ErpClient(保持主类文件紧凑)。 """
apis = {
' login_by_org ' : _impl_login_by_org ,
' login_by_app_secret ' : _impl_login_by_app_secret ,
' _login_with ' : _impl_login_with ,
' _result ' : _result ,
' switch_org ' : _impl_switch_org ,
' view ' : _impl_view ,
' save ' : _impl_save ,
' batch_save ' : _impl_batch_save ,
' _bill_action ' : _impl_bill_action ,
' submit ' : _impl_submit ,
' audit ' : _impl_audit ,
' unaudit ' : _impl_unaudit ,
' delete ' : _impl_delete ,
' execute_operation ' : _impl_execute_operation ,
' forbid ' : _impl_forbid ,
' enable ' : _impl_enable ,
' cancel_bill ' : _impl_cancel ,
' unsubmit ' : _impl_unsubmit ,
' revoke ' : _impl_revoke ,
' operations ' : _impl_operations ,
' workflow_audit ' : _impl_workflow_audit ,
' push ' : _impl_push ,
' allocate ' : _impl_allocate ,
' group_save ' : _impl_group_save ,
' group_delete ' : _impl_group_delete ,
' send_msg ' : _impl_send_msg ,
' get_inventory ' : _impl_get_inventory ,
' find ' : _impl_find ,
}
for name , fn in apis . items ( ) :
setattr ( ErpClient , name , fn )
def _doc_save_example ( ) :
""" 占位:见 README「Save 选项」一节;函数体为空,仅用于生成 api.json 的可读分组。 """
return None
_attach_write_apis ( )