contract.py 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883
  1. """CRM 合同 CRUD — 对照 CrmContractServiceImpl.java(列表/详情 P1)"""
  2. from __future__ import annotations
  3. import json
  4. import math
  5. import re
  6. from collections import defaultdict
  7. from datetime import date, datetime, timedelta
  8. from decimal import Decimal, ROUND_HALF_UP
  9. from typing import Any, Dict, List, Optional, Tuple
  10. from sqlalchemy import and_, func, or_
  11. from sqlalchemy.orm import Query, Session
  12. from app.core.delete_guard import assert_row_deletable_by_creator
  13. from app.core.utils import generate_uuid
  14. from app.crud.crm.data_scope_helpers import apply_crm_owner_scope, ensure_crm_owner_row_in_scope, apply_crm_create_by_scope, ensure_crm_create_by_row_in_scope
  15. from app.crud.crm.contact import get_contact
  16. from app.crud.crm.contract_approval import (
  17. can_user_approve,
  18. create_approval_records,
  19. delete_pending_approvals,
  20. invalidate_all_approvals,
  21. )
  22. from app.crud.crm.contract_product import (
  23. batch_insert_contract_products,
  24. delete_products_by_contract_id,
  25. list_contract_products,
  26. list_products_by_contract_ids,
  27. )
  28. from app.crud.crm.customer import get_customer
  29. from app.crud.crm.invoice_info import list_invoice_info_by_customer
  30. from app.services.crm_settlement_clause import default_settlement_clause
  31. from app.services.crm_supplier_hazard import assert_products_allowed_for_supplier
  32. from app.crud.crm.product import resolve_product_id_for_quote_item
  33. from app.crud.crm.quote import get_quote
  34. from app.crud.crm.quote_product import list_quote_products
  35. from app.crud.crm.supplier_info import get_supplier_info
  36. from app.models.crm_models import (
  37. CrmContract,
  38. CrmContractApproval,
  39. CrmContractChange,
  40. CrmContractProduct,
  41. CrmContractTemplate,
  42. CrmOpportunity,
  43. CrmProduct,
  44. CrmQuote,
  45. )
  46. from app.models.models import SysUser
  47. _FMT = "%Y-%m-%d %H:%M:%S"
  48. def _ensure_contract_in_scope(db: Session, row: CrmContract, user_info, tenant_no: str) -> None:
  49. ensure_crm_owner_row_in_scope(db, row, user_info, tenant_no, message="无权访问该合同")
  50. def _get_contract_row_in_scope(
  51. db: Session,
  52. contract_id: str,
  53. *,
  54. tenant_no: str,
  55. user_info=None,
  56. ) -> CrmContract:
  57. row = get_contract_row(db, contract_id, tenant_no=tenant_no)
  58. if not row:
  59. raise ValueError("合同不存在")
  60. _ensure_contract_in_scope(db, row, user_info, tenant_no)
  61. return row
  62. _DATE_FMT = "%Y-%m-%d"
  63. def total_pages(total: int, page_size: int) -> int:
  64. if page_size <= 0:
  65. return 0
  66. return math.ceil(total / page_size)
  67. def _decimal_value(value: Any, default: Decimal = Decimal("0")) -> Decimal:
  68. if value is None or value == "":
  69. return default
  70. if isinstance(value, Decimal):
  71. return value
  72. return Decimal(str(value))
  73. def _parse_optional_date(value: Any) -> Optional[date]:
  74. if value is None:
  75. return None
  76. if isinstance(value, date) and not isinstance(value, datetime):
  77. return value
  78. if isinstance(value, datetime):
  79. return value.date()
  80. text = str(value).strip()
  81. if not text:
  82. return None
  83. for fmt in (_DATE_FMT, _FMT):
  84. try:
  85. return datetime.strptime(text, fmt).date()
  86. except ValueError:
  87. continue
  88. raise ValueError(f"日期格式无效: {text}")
  89. def _parse_optional_datetime(value: Any) -> Optional[datetime]:
  90. if value is None:
  91. return None
  92. if isinstance(value, datetime):
  93. return value
  94. text = str(value).strip()
  95. if not text:
  96. return None
  97. for fmt in (_FMT, _DATE_FMT):
  98. try:
  99. return datetime.strptime(text, fmt)
  100. except ValueError:
  101. continue
  102. raise ValueError(f"日期时间格式无效: {text}")
  103. def _get_field(data: dict, *keys: str, default=None):
  104. for key in keys:
  105. if key in data and data[key] is not None:
  106. return data[key]
  107. return default
  108. def _resolve_user_display_name(db: Session, user_id: Optional[str]) -> str:
  109. uid = (user_id or "").strip()
  110. if not uid:
  111. return ""
  112. u = db.query(SysUser).filter(SysUser.id == uid, SysUser.del_flag == 0).first()
  113. if not u:
  114. return ""
  115. return (u.nick_name or u.user_no or "").strip()
  116. def _is_blank(value: Any) -> bool:
  117. return value is None or str(value).strip() == ""
  118. def _first_non_blank(*values: Any) -> str:
  119. for value in values:
  120. text = "" if value is None else str(value).strip()
  121. if text:
  122. return text
  123. return ""
  124. def _get_default_invoice_info(db: Session, *, tenant_no: str, customer_id: str) -> Optional[dict]:
  125. rows = list_invoice_info_by_customer(db, tenant_no, customer_id)
  126. if not rows:
  127. return None
  128. for row in rows:
  129. if str(row.get("isDefault") or "").strip() == "1":
  130. return row
  131. return rows[0]
  132. def _build_customer_address(customer: Any) -> str:
  133. if not customer:
  134. return ""
  135. address_parts = [
  136. _first_non_blank(getattr(customer, "province", "")),
  137. _first_non_blank(getattr(customer, "city", "")),
  138. _first_non_blank(getattr(customer, "district", "")),
  139. _first_non_blank(getattr(customer, "address", "")),
  140. ]
  141. return "".join([part for part in address_parts if part])
  142. def _row_to_dict(row: CrmContract) -> Dict[str, Any]:
  143. """ORM → camelCase(单点真相)"""
  144. return {
  145. "id": row.id,
  146. "contractNo": row.contract_no or "",
  147. "contractName": row.contract_name or "",
  148. "customerId": row.customer_id or "",
  149. "customerName": row.customer_name or "",
  150. "opportunityId": row.opportunity_id or "",
  151. "quoteId": row.quote_id or "",
  152. "parentContractId": row.parent_contract_id or "",
  153. "renewalCount": row.renewal_count if row.renewal_count is not None else 0,
  154. "templateId": row.template_id or "",
  155. "contractTemplate": row.contract_template or "",
  156. "contactId": row.contact_id or "",
  157. "contactName": row.contact_name or "",
  158. "contactMobile": row.contact_mobile or "",
  159. "contractType": row.contract_type or "",
  160. "contractNature": row.contract_nature or "",
  161. "amount": float(row.amount) if row.amount is not None else 0.0,
  162. "currency": row.currency or "CNY",
  163. "taxRate": float(row.tax_rate) if row.tax_rate is not None else 0.0,
  164. "amountWithTax": float(row.amount_with_tax) if row.amount_with_tax is not None else 0.0,
  165. "freight": float(row.freight) if getattr(row, "freight", None) is not None else 0.0,
  166. "barrelDeposit": float(getattr(row, "barrel_deposit", None) or 0),
  167. "status": row.status or "draft",
  168. "approvalStatus": row.approval_status or "",
  169. "signDate": row.sign_date.strftime(_DATE_FMT) if row.sign_date else "",
  170. "actualSignDate": row.actual_sign_date.strftime(_DATE_FMT) if row.actual_sign_date else "",
  171. "startDate": row.start_date.strftime(_DATE_FMT) if row.start_date else "",
  172. "endDate": row.end_date.strftime(_DATE_FMT) if row.end_date else "",
  173. "contractPeriod": row.contract_period,
  174. "performanceStatus": row.performance_status or "",
  175. "performanceRate": float(row.performance_rate) if row.performance_rate is not None else 0.0,
  176. "customerSatisfaction": row.customer_satisfaction,
  177. "approvalFlowId": row.approval_flow_id or "",
  178. "contractFile": row.contract_file or "",
  179. "attachmentFiles": row.attachment_files or "",
  180. "ownerUserId": row.owner_user_id or "",
  181. "ownerUserName": row.owner_user_name or "",
  182. "receivedAmount": float(row.received_amount) if row.received_amount is not None else 0.0,
  183. "unreceivedAmount": float(row.unreceived_amount) if row.unreceived_amount is not None else 0.0,
  184. "invoiceAmount": float(row.invoice_amount) if row.invoice_amount is not None else 0.0,
  185. "uninvoiceAmount": float(row.uninvoice_amount) if row.uninvoice_amount is not None else 0.0,
  186. "partyA": row.party_a or "",
  187. "partyAAddress": row.party_a_address or "",
  188. "partyAContact": row.party_a_contact or "",
  189. "partyAMobile": row.party_a_mobile or "",
  190. "partyALegalPerson": row.party_a_legal_person or "",
  191. "partyAAgent": row.party_a_agent or "",
  192. "partyAPhoneFax": row.party_a_phone_fax or "",
  193. "partyABank": row.party_a_bank or "",
  194. "partyAAccount": row.party_a_account or "",
  195. "supplierId": row.supplier_id or "",
  196. "settlementMethod": row.settlement_method or "",
  197. "partyB": row.party_b or "",
  198. "partyBAddress": row.party_b_address or "",
  199. "partyBContact": row.party_b_contact or "",
  200. "partyBMobile": row.party_b_mobile or "",
  201. "partyBLegalPerson": row.party_b_legal_person or "",
  202. "partyBAgent": row.party_b_agent or "",
  203. "partyBPhoneFax": row.party_b_phone_fax or "",
  204. "partyBBank": row.party_b_bank or "",
  205. "partyBAccount": row.party_b_account or "",
  206. "paymentTerms": row.payment_terms or "",
  207. "deliveryTerms": row.delivery_terms or "",
  208. "contractTerms": row.contract_terms or "",
  209. "invalidReason": row.invalid_reason or "",
  210. "invalidTime": row.invalid_time.strftime(_FMT) if row.invalid_time else "",
  211. "templateContent": row.template_content or "",
  212. "settlementClauseDrafts": row.settlement_clause_drafts or "",
  213. "createBy": row.create_by or "",
  214. "createTime": row.create_time.strftime(_FMT) if row.create_time else "",
  215. "updateBy": row.update_by or "",
  216. "updateTime": row.update_time.strftime(_FMT) if row.update_time else "",
  217. "remark": row.remark or "",
  218. }
  219. def contract_row_to_dict(row: CrmContract) -> Dict[str, Any]:
  220. return _row_to_dict(row)
  221. def _build_contract_filters(
  222. db: Session,
  223. q: Query,
  224. filters: dict,
  225. *,
  226. tenant_no: str,
  227. ) -> Query:
  228. """Java: buildQueryWrapper"""
  229. q = q.filter(CrmContract.tenant_no == tenant_no, CrmContract.del_flag == 0)
  230. keyword = (_get_field(filters, "keyword") or "").strip()
  231. if keyword:
  232. like = f"%{keyword}%"
  233. pinyin_like = f"%{keyword.lower()}%"
  234. product_match = (
  235. db.query(CrmContractProduct.id)
  236. .outerjoin(
  237. CrmProduct,
  238. and_(
  239. CrmProduct.id == CrmContractProduct.product_id,
  240. CrmProduct.del_flag == 0,
  241. CrmProduct.tenant_no == tenant_no,
  242. ),
  243. )
  244. .filter(
  245. CrmContractProduct.contract_id == CrmContract.id,
  246. CrmContractProduct.tenant_no == tenant_no,
  247. CrmContractProduct.del_flag == 0,
  248. or_(
  249. CrmContractProduct.product_name.like(like),
  250. func.lower(func.coalesce(CrmProduct.product_name, "")).like(
  251. f"%{keyword.lower()}%"
  252. ),
  253. func.lower(func.coalesce(CrmProduct.name_pinyin_abbr, "")).like(
  254. pinyin_like
  255. ),
  256. ),
  257. )
  258. .exists()
  259. )
  260. q = q.filter(
  261. or_(
  262. CrmContract.contract_no.like(like),
  263. product_match,
  264. )
  265. )
  266. contract_no = (_get_field(filters, "contract_no", "contractNo") or "").strip()
  267. contract_name = (_get_field(filters, "contract_name", "contractName") or "").strip()
  268. customer_name = (_get_field(filters, "customer_name", "customerName") or "").strip()
  269. if (
  270. contract_no
  271. and contract_name
  272. and customer_name
  273. and contract_no == contract_name == customer_name
  274. ):
  275. legacy_keyword = contract_no
  276. q = q.filter(
  277. or_(
  278. CrmContract.contract_no.like(f"%{legacy_keyword}%"),
  279. CrmContract.contract_name.like(f"%{legacy_keyword}%"),
  280. CrmContract.customer_name.like(f"%{legacy_keyword}%"),
  281. )
  282. )
  283. else:
  284. if contract_no:
  285. q = q.filter(CrmContract.contract_no.like(f"%{contract_no}%"))
  286. if contract_name:
  287. q = q.filter(CrmContract.contract_name.like(f"%{contract_name}%"))
  288. if customer_name:
  289. q = q.filter(CrmContract.customer_name.like(f"%{customer_name}%"))
  290. customer_id = (_get_field(filters, "customer_id", "customerId") or "").strip()
  291. if customer_id:
  292. q = q.filter(CrmContract.customer_id == customer_id)
  293. opportunity_id = (_get_field(filters, "opportunity_id", "opportunityId") or "").strip()
  294. if opportunity_id:
  295. q = q.filter(CrmContract.opportunity_id == opportunity_id)
  296. quote_id = (_get_field(filters, "quote_id", "quoteId") or "").strip()
  297. if quote_id:
  298. q = q.filter(CrmContract.quote_id == quote_id)
  299. contract_type = (_get_field(filters, "contract_type", "contractType") or "").strip()
  300. if contract_type:
  301. q = q.filter(CrmContract.contract_type == contract_type)
  302. status = (_get_field(filters, "status") or "").strip()
  303. if status:
  304. q = q.filter(CrmContract.status == status)
  305. exclude_status = (_get_field(filters, "exclude_status", "excludeStatus") or "").strip()
  306. if exclude_status:
  307. q = q.filter(CrmContract.status != exclude_status)
  308. approval_status = (_get_field(filters, "approval_status", "approvalStatus") or "").strip()
  309. if approval_status:
  310. q = q.filter(CrmContract.approval_status == approval_status)
  311. owner_user_id = (_get_field(filters, "owner_user_id", "ownerUserId") or "").strip()
  312. if owner_user_id:
  313. q = q.filter(CrmContract.owner_user_id == owner_user_id)
  314. pending_approval_user_id = (
  315. _get_field(filters, "pending_approval_user_id", "pendingApprovalUserId") or ""
  316. ).strip()
  317. if pending_approval_user_id:
  318. # 仅返回当前处于审批中且审批状态为待审批的合同,避免历史审批记录混入草稿/已审批数据
  319. q = q.filter(
  320. CrmContract.status == "approving",
  321. CrmContract.approval_status == "pending",
  322. )
  323. q = q.filter(
  324. CrmContract.id.in_(
  325. db.query(CrmContractApproval.contract_id)
  326. .filter(
  327. CrmContractApproval.approver_id == pending_approval_user_id,
  328. CrmContractApproval.approval_result == "pending",
  329. CrmContractApproval.is_current == 1,
  330. CrmContractApproval.del_flag == 0,
  331. )
  332. .distinct()
  333. )
  334. )
  335. approved_by_user_id = (
  336. _get_field(filters, "approved_by_user_id", "approvedByUserId") or ""
  337. ).strip()
  338. if approved_by_user_id:
  339. # 已审批列表应只看审批流已结束的合同,排除仍在审批中的记录
  340. q = q.filter(CrmContract.approval_status.in_(("approved", "rejected")))
  341. contract_ids = [
  342. cid
  343. for (cid,) in db.query(CrmContractApproval.contract_id)
  344. .filter(
  345. CrmContractApproval.approver_id == approved_by_user_id,
  346. CrmContractApproval.approval_result.in_(("approved", "rejected")),
  347. CrmContractApproval.del_flag == 0,
  348. )
  349. .distinct()
  350. .all()
  351. if cid
  352. ]
  353. if contract_ids:
  354. q = q.filter(CrmContract.id.in_(contract_ids))
  355. else:
  356. q = q.filter(CrmContract.id == "__none__")
  357. min_amount = _get_field(filters, "min_amount", "minAmount")
  358. if min_amount is not None and min_amount != "":
  359. q = q.filter(CrmContract.amount >= _decimal_value(min_amount))
  360. max_amount = _get_field(filters, "max_amount", "maxAmount")
  361. if max_amount is not None and max_amount != "":
  362. q = q.filter(CrmContract.amount <= _decimal_value(max_amount))
  363. sign_date_begin = _parse_optional_date(_get_field(filters, "sign_date_begin", "signDateBegin"))
  364. if sign_date_begin:
  365. q = q.filter(CrmContract.sign_date >= sign_date_begin)
  366. sign_date_end = _parse_optional_date(_get_field(filters, "sign_date_end", "signDateEnd"))
  367. if sign_date_end:
  368. q = q.filter(CrmContract.sign_date <= sign_date_end)
  369. begin_time = _parse_optional_datetime(_get_field(filters, "begin_time", "beginTime"))
  370. end_time = _parse_optional_datetime(_get_field(filters, "end_time", "endTime"))
  371. if begin_time and end_time:
  372. q = q.filter(CrmContract.create_time >= begin_time, CrmContract.create_time <= end_time)
  373. elif begin_time:
  374. q = q.filter(CrmContract.create_time >= begin_time)
  375. elif end_time:
  376. q = q.filter(CrmContract.create_time <= end_time)
  377. return q.order_by(CrmContract.create_time.desc())
  378. def list_contracts(
  379. db: Session,
  380. tenant_no: str,
  381. *,
  382. page: int = 1,
  383. page_size: int = 10,
  384. filters: dict = None,
  385. current_user_id: str = None,
  386. user_info=None,
  387. include_products: bool = False,
  388. ) -> Tuple[List[Dict[str, Any]], int]:
  389. """Java: queryPageList"""
  390. q = db.query(CrmContract)
  391. q = _build_contract_filters(db, q, filters or {}, tenant_no=tenant_no)
  392. if user_info:
  393. q = apply_crm_owner_scope(q, CrmContract, user_info, db, tenant_no)
  394. total = q.order_by(None).with_entities(func.count(CrmContract.id)).scalar() or 0
  395. page = max(1, page)
  396. page_size = min(max(1, page_size), 500)
  397. rows = q.offset((page - 1) * page_size).limit(page_size).all()
  398. result = [_row_to_dict(r) for r in rows]
  399. for item in result:
  400. if item.get("status") == "approving" and current_user_id:
  401. item["canApprove"] = can_user_approve(db, item["id"], current_user_id)
  402. else:
  403. item["canApprove"] = False
  404. if item.get("ownerUserId") and not item.get("ownerUserName"):
  405. item["ownerUserName"] = _resolve_user_display_name(db, item["ownerUserId"])
  406. if item.get("createBy") and not item.get("createByName"):
  407. item["createByName"] = _resolve_user_display_name(db, item["createBy"])
  408. if include_products and result:
  409. contract_ids = [str(item["id"]) for item in result if item.get("id")]
  410. products_map = list_products_by_contract_ids(db, contract_ids, tenant_no=tenant_no)
  411. for item in result:
  412. item["products"] = products_map.get(str(item.get("id") or ""), [])
  413. return result, int(total)
  414. def get_contract(
  415. db: Session,
  416. contract_id: str,
  417. *,
  418. tenant_no: str,
  419. current_user_id: str = None,
  420. user_info=None,
  421. ) -> Optional[Dict[str, Any]]:
  422. """Java: queryById"""
  423. row = (
  424. db.query(CrmContract)
  425. .filter(
  426. CrmContract.id == contract_id,
  427. CrmContract.tenant_no == tenant_no,
  428. CrmContract.del_flag == 0,
  429. )
  430. .first()
  431. )
  432. if not row:
  433. return None
  434. _ensure_contract_in_scope(db, row, user_info, tenant_no)
  435. detail = _row_to_dict(row)
  436. detail["createByName"] = _resolve_user_display_name(db, detail.get("createBy"))
  437. detail["updateByName"] = _resolve_user_display_name(db, detail.get("updateBy"))
  438. if detail.get("ownerUserId") and not detail.get("ownerUserName"):
  439. detail["ownerUserName"] = _resolve_user_display_name(db, detail["ownerUserId"])
  440. supplier_id = (detail.get("supplierId") or "").strip()
  441. supplier = None
  442. if supplier_id:
  443. supplier = get_supplier_info(db, supplier_id, tenant_no=tenant_no)
  444. if supplier:
  445. detail["supplierName"] = supplier.supplier_name or ""
  446. customer = None
  447. customer_id = (detail.get("customerId") or "").strip()
  448. if customer_id:
  449. customer = get_customer(db, customer_id)
  450. # 查询兜底:历史空数据按基础资料补展示,不改变原始库存量
  451. if supplier:
  452. if _is_blank(detail.get("partyA")):
  453. detail["partyA"] = _first_non_blank(getattr(supplier, "supplier_name", ""))
  454. if _is_blank(detail.get("partyAAddress")):
  455. detail["partyAAddress"] = _first_non_blank(getattr(supplier, "supplier_address", ""))
  456. if _is_blank(detail.get("partyALegalPerson")):
  457. detail["partyALegalPerson"] = _first_non_blank(getattr(supplier, "legal_person", ""))
  458. if _is_blank(detail.get("partyAAgent")):
  459. detail["partyAAgent"] = _first_non_blank(getattr(supplier, "agent", ""))
  460. if _is_blank(detail.get("partyAPhoneFax")):
  461. detail["partyAPhoneFax"] = _first_non_blank(getattr(supplier, "phone_fax", ""))
  462. if _is_blank(detail.get("partyABank")):
  463. detail["partyABank"] = _first_non_blank(getattr(supplier, "bank_name", ""))
  464. if _is_blank(detail.get("partyAAccount")):
  465. detail["partyAAccount"] = _first_non_blank(getattr(supplier, "bank_account", ""))
  466. if customer:
  467. inv = _get_default_invoice_info(db, tenant_no=tenant_no, customer_id=customer_id)
  468. if _is_blank(detail.get("partyB")):
  469. detail["partyB"] = _first_non_blank(
  470. inv.get("companyName") if inv else "",
  471. customer.customer_name,
  472. )
  473. if _is_blank(detail.get("partyBAddress")):
  474. detail["partyBAddress"] = _first_non_blank(
  475. inv.get("companyAddress") if inv else "",
  476. _build_customer_address(customer),
  477. )
  478. if _is_blank(detail.get("partyBContact")):
  479. detail["partyBContact"] = _first_non_blank(detail.get("contactName"))
  480. if _is_blank(detail.get("partyBMobile")):
  481. detail["partyBMobile"] = _first_non_blank(
  482. inv.get("phoneFax") if inv else "",
  483. detail.get("contactMobile"),
  484. customer.mobile,
  485. customer.telephone,
  486. )
  487. if _is_blank(detail.get("partyBLegalPerson")):
  488. detail["partyBLegalPerson"] = _first_non_blank(inv.get("legalRepresentative") if inv else "")
  489. if _is_blank(detail.get("partyBPhoneFax")):
  490. detail["partyBPhoneFax"] = _first_non_blank(
  491. inv.get("phoneFax") if inv else "",
  492. customer.telephone,
  493. )
  494. if _is_blank(detail.get("partyBBank")):
  495. detail["partyBBank"] = _first_non_blank(inv.get("bankName") if inv else "")
  496. if _is_blank(detail.get("partyBAccount")):
  497. detail["partyBAccount"] = _first_non_blank(inv.get("bankAccount") if inv else "")
  498. detail["products"] = list_contract_products(
  499. db,
  500. contract_id,
  501. tenant_no=tenant_no,
  502. include_price_tiers=True,
  503. )
  504. if current_user_id and detail.get("status") == "approving":
  505. detail["canApprove"] = can_user_approve(db, contract_id, current_user_id)
  506. else:
  507. detail["canApprove"] = False
  508. return detail
  509. def get_contract_detail(
  510. db: Session,
  511. contract_id: str,
  512. *,
  513. tenant_no: str,
  514. current_user_id: str = None,
  515. user_info=None,
  516. ) -> Dict[str, Any]:
  517. detail = get_contract(
  518. db,
  519. contract_id,
  520. tenant_no=tenant_no,
  521. current_user_id=current_user_id,
  522. user_info=user_info,
  523. )
  524. if not detail:
  525. raise ValueError("合同不存在")
  526. return detail
  527. def get_contract_row(
  528. db: Session,
  529. contract_id: str,
  530. *,
  531. tenant_no: str,
  532. ) -> Optional[CrmContract]:
  533. return (
  534. db.query(CrmContract)
  535. .filter(
  536. CrmContract.id == contract_id,
  537. CrmContract.tenant_no == tenant_no,
  538. CrmContract.del_flag == 0,
  539. )
  540. .first()
  541. )
  542. def _get_supplier_short_name(db: Session, supplier_id: str, tenant_no: str) -> str:
  543. if not supplier_id:
  544. return "山峡"
  545. supplier = get_supplier_info(db, supplier_id, tenant_no=tenant_no)
  546. if not supplier:
  547. return "山峡"
  548. if (supplier.short_name or "").strip():
  549. return supplier.short_name.strip()
  550. if (supplier.supplier_name or "").strip():
  551. return supplier.supplier_name.strip()
  552. return "山峡"
  553. def _build_contract_name_from_parties(
  554. db: Session,
  555. *,
  556. tenant_no: str,
  557. contract_no: str,
  558. party_a: str = "",
  559. party_b: str = "",
  560. supplier_id: str = "",
  561. customer_id: str = "",
  562. customer_name: str = "",
  563. customer_short_name: str = "",
  564. user_contract_name: str = "",
  565. ) -> str:
  566. """根据供需方面板与主数据生成/校正合同名称。"""
  567. supplier = get_supplier_info(db, supplier_id, tenant_no=tenant_no) if supplier_id else None
  568. supplier_name = (getattr(supplier, "supplier_name", None) or "").strip() if supplier else ""
  569. supplier_short_name = _get_supplier_short_name(db, supplier_id or "", tenant_no)
  570. cust_name = (customer_name or "").strip()
  571. cust_short = (customer_short_name or "").strip()
  572. invoice_name = ""
  573. if customer_id:
  574. # 始终从客户主数据取简称,避免前端未带 shortName 时落成全称
  575. customer = get_customer(db, customer_id)
  576. if customer:
  577. cust_name = cust_name or (customer.customer_name or "").strip()
  578. db_short = (customer.short_name or "").strip()
  579. if db_short:
  580. cust_short = db_short
  581. inv = _get_default_invoice_info(db, tenant_no=tenant_no, customer_id=customer_id)
  582. if inv:
  583. invoice_name = (inv.get("companyName") or "").strip()
  584. return generate_contract_name(
  585. contract_no or "",
  586. party_a=party_a or "",
  587. party_b=party_b or "",
  588. supplier_name=supplier_name,
  589. supplier_short_name=supplier_short_name,
  590. customer_name=cust_name,
  591. customer_short_name=cust_short,
  592. customer_invoice_name=invoice_name,
  593. user_contract_name=user_contract_name or "",
  594. )
  595. def generate_contract_no(
  596. db: Session,
  597. tenant_no: str,
  598. *,
  599. supplier_id: str = None,
  600. sign_date: date = None,
  601. ) -> str:
  602. """Java: generateContractNo — {供方编码}/X-JT{yyyyMMdd}{3位序号}
  603. 流水与撞号检测须含软删:uk_contract_tenant_no 对 (contract_no, tenant_no) 全局唯一。
  604. """
  605. supplier_code = "SX"
  606. if supplier_id:
  607. supplier = get_supplier_info(db, supplier_id, tenant_no=tenant_no)
  608. if supplier and (supplier.supplier_code or "").strip():
  609. supplier_code = supplier.supplier_code.strip()
  610. date_to_use = sign_date or date.today()
  611. date_str = date_to_use.strftime("%Y%m%d")
  612. prefix = f"{supplier_code}/X-JT{date_str}"
  613. # 含软删:已软删编号仍占唯一索引,不能复用
  614. last = (
  615. db.query(CrmContract)
  616. .filter(
  617. CrmContract.tenant_no == tenant_no,
  618. CrmContract.contract_no.like(f"{prefix}%"),
  619. )
  620. .order_by(CrmContract.contract_no.desc())
  621. .first()
  622. )
  623. sequence = 1
  624. if last and last.contract_no and len(last.contract_no) >= len(prefix) + 3:
  625. try:
  626. sequence = int(last.contract_no[len(prefix) :]) + 1
  627. except ValueError:
  628. sequence = 1
  629. for retry in range(50):
  630. candidate = f"{prefix}{sequence + retry:03d}"
  631. if not contract_no_exists(db, tenant_no, candidate):
  632. return candidate
  633. raise ValueError("生成合同编号失败,请稍后重试")
  634. def contract_no_exists(
  635. db: Session,
  636. tenant_no: str,
  637. contract_no: str,
  638. *,
  639. exclude_id: str = None,
  640. ) -> bool:
  641. """租户内合同编号是否已占用(含软删,保证全局唯一)。"""
  642. q = db.query(CrmContract.id).filter(
  643. CrmContract.tenant_no == tenant_no,
  644. CrmContract.contract_no == contract_no,
  645. )
  646. if exclude_id:
  647. q = q.filter(CrmContract.id != exclude_id)
  648. return q.first() is not None
  649. _CONTRACT_NO_STD_RE = re.compile(r"^([A-Z]+)/X-JT(\d{8})(\d{3})$")
  650. def replace_contract_no_date(contract_no: str, sign_date: date) -> Optional[str]:
  651. """标准编号替换日期段,保留序号;非标准返回 None。"""
  652. if not contract_no or not sign_date:
  653. return None
  654. m = _CONTRACT_NO_STD_RE.match(contract_no.strip())
  655. if not m:
  656. return None
  657. supplier_code, _old_date, seq = m.group(1), m.group(2), m.group(3)
  658. date_str = sign_date.strftime("%Y%m%d")
  659. return f"{supplier_code}/X-JT{date_str}{seq}"
  660. def align_contract_no_to_sign_date(
  661. db: Session,
  662. tenant_no: str,
  663. contract_no: str,
  664. sign_date: date,
  665. *,
  666. exclude_id: str = None,
  667. ) -> str:
  668. """将标准合同编号日期段对齐签订日;撞号则序号顺延(含软删查重)。
  669. 非标准编号原样返回。无签订日则原样返回。
  670. """
  671. if not (contract_no or "").strip():
  672. return contract_no or ""
  673. if not sign_date:
  674. return contract_no.strip()
  675. replaced = replace_contract_no_date(contract_no, sign_date)
  676. if replaced is None:
  677. return contract_no.strip()
  678. m = _CONTRACT_NO_STD_RE.match(replaced)
  679. if not m:
  680. return replaced
  681. supplier_code, date_str, seq = m.group(1), m.group(2), m.group(3)
  682. start_seq = int(seq)
  683. for retry in range(50):
  684. candidate = f"{supplier_code}/X-JT{date_str}{start_seq + retry:03d}"
  685. if not contract_no_exists(db, tenant_no, candidate, exclude_id=exclude_id):
  686. return candidate
  687. raise ValueError("生成合同编号失败,请稍后重试")
  688. def resolve_party_short_name(
  689. party_name: str,
  690. *,
  691. supplier_name: str = "",
  692. supplier_short_name: str = "",
  693. customer_name: str = "",
  694. customer_short_name: str = "",
  695. customer_invoice_name: str = "",
  696. ) -> str:
  697. """按面板单位全称精确匹配交易主体/客户主数据,取 shortName;对不上则用全称。"""
  698. party = (party_name or "").strip()
  699. if not party:
  700. return ""
  701. s_name = (supplier_name or "").strip()
  702. s_short = (supplier_short_name or "").strip()
  703. if s_name and party == s_name:
  704. return s_short or s_name
  705. if s_short and party == s_short:
  706. return s_short
  707. c_name = (customer_name or "").strip()
  708. c_short = (customer_short_name or "").strip()
  709. c_inv = (customer_invoice_name or "").strip()
  710. if c_name and party == c_name:
  711. return c_short or c_name
  712. if c_short and party == c_short:
  713. return c_short
  714. if c_inv and party == c_inv:
  715. return c_short or c_inv
  716. return party
  717. def _strip_contract_name_no_suffix(name: str) -> str:
  718. return re.sub(r"([^)]+)$", "", (name or "").strip()).strip()
  719. def _auto_contract_name_body(
  720. party_a: str = "",
  721. party_b: str = "",
  722. *,
  723. supplier_name: str = "",
  724. supplier_short_name: str = "",
  725. customer_name: str = "",
  726. customer_short_name: str = "",
  727. customer_invoice_name: str = "",
  728. ) -> str:
  729. a = resolve_party_short_name(
  730. party_a,
  731. supplier_name=supplier_name,
  732. supplier_short_name=supplier_short_name,
  733. customer_name=customer_name,
  734. customer_short_name=customer_short_name,
  735. customer_invoice_name=customer_invoice_name,
  736. )
  737. b = resolve_party_short_name(
  738. party_b,
  739. supplier_name=supplier_name,
  740. supplier_short_name=supplier_short_name,
  741. customer_name=customer_name,
  742. customer_short_name=customer_short_name,
  743. customer_invoice_name=customer_invoice_name,
  744. )
  745. return "-".join(x for x in (a, b) if x)
  746. def _user_contract_name_uses_party_full_name(
  747. cleaned_user_name: str,
  748. party_a: str = "",
  749. party_b: str = "",
  750. *,
  751. supplier_name: str = "",
  752. customer_name: str = "",
  753. customer_invoice_name: str = "",
  754. ) -> bool:
  755. """前端预览误用单位全称时,名称片段会等于面板/客户/开票全称。"""
  756. parts = [p.strip() for p in (cleaned_user_name or "").split("-") if p.strip()]
  757. if not parts:
  758. return False
  759. full_names = {
  760. (party_a or "").strip(),
  761. (party_b or "").strip(),
  762. (supplier_name or "").strip(),
  763. (customer_name or "").strip(),
  764. (customer_invoice_name or "").strip(),
  765. }
  766. full_names.discard("")
  767. return any(part in full_names for part in parts)
  768. def generate_contract_name(
  769. contract_no: str,
  770. party_a: str = "",
  771. party_b: str = "",
  772. *,
  773. supplier_name: str = "",
  774. supplier_short_name: str = "",
  775. customer_name: str = "",
  776. customer_short_name: str = "",
  777. customer_invoice_name: str = "",
  778. user_contract_name: str = "",
  779. contract_type: str = "", # 保留兼容旧调用,命名不再按类型反序
  780. ) -> str:
  781. """按面板供方(partyA)-需方(partyB)生成:{供方简称}-{需方简称}({合同编号})。
  782. - 名称为空:按主数据简称自动生成
  783. - 名称含单位全称(前端误预览):仍按简称重算
  784. - 续签 / 真正手填自定义名:保留主体,仅校正末尾括号内合同编号
  785. """
  786. auto_body = _auto_contract_name_body(
  787. party_a,
  788. party_b,
  789. supplier_name=supplier_name,
  790. supplier_short_name=supplier_short_name,
  791. customer_name=customer_name,
  792. customer_short_name=customer_short_name,
  793. customer_invoice_name=customer_invoice_name,
  794. )
  795. def _with_no(body: str) -> str:
  796. if not body:
  797. return f"合同({contract_no})" if contract_no else "合同"
  798. return f"{body}({contract_no})" if contract_no else body
  799. user_raw = (user_contract_name or "").strip()
  800. if not user_raw:
  801. return _with_no(auto_body)
  802. # 续签名称:保留整段(含原编号括号),仅必要时追加当前编号
  803. if "-续签" in user_raw:
  804. cleaned = _strip_contract_name_no_suffix(user_raw)
  805. # 若原文已以当前编号结尾则保持;否则在整段后续签名后挂编号
  806. if contract_no and user_raw.endswith(f"({contract_no})"):
  807. return user_raw
  808. if contract_no and f"({contract_no})" not in cleaned:
  809. # 续签名通常为「原名-续签N」,原名里已有旧编号括号,不能 strip 掉
  810. return f"{user_raw}({contract_no})" if not user_raw.endswith(f"({contract_no})") else user_raw
  811. return user_raw
  812. cleaned = _strip_contract_name_no_suffix(user_raw)
  813. if (
  814. cleaned == auto_body
  815. or _user_contract_name_uses_party_full_name(
  816. cleaned,
  817. party_a,
  818. party_b,
  819. supplier_name=supplier_name,
  820. customer_name=customer_name,
  821. customer_invoice_name=customer_invoice_name,
  822. )
  823. ):
  824. return _with_no(auto_body)
  825. if contract_no and f"({contract_no})" not in cleaned:
  826. return f"{cleaned}({contract_no})"
  827. return cleaned
  828. # 框架类合同类型(含历史 framework,兼容未刷完数据)
  829. FRAMEWORK_CONTRACT_TYPES = frozenset({"framework", "framework_sale", "framework_purchase"})
  830. def is_framework_contract_type(contract_type: Optional[str]) -> bool:
  831. return (contract_type or "").strip() in FRAMEWORK_CONTRACT_TYPES
  832. def _validate_contract_type_and_products(data: dict) -> None:
  833. contract_type = (_get_field(data, "contract_type", "contractType") or "").strip()
  834. if contract_type in ("sale", "purchase") or is_framework_contract_type(contract_type):
  835. products = _get_field(data, "products", "productList") or []
  836. if not products:
  837. raise ValueError("销售合同、采购合同或框架合同必须至少添加一个产品")
  838. def _normalize_framework_contract_data(data: dict) -> None:
  839. if not is_framework_contract_type(_get_field(data, "contract_type", "contractType")):
  840. return
  841. data["amount"] = 0
  842. data["amountWithTax"] = 0
  843. products = _get_field(data, "products", "productList") or []
  844. for product in products:
  845. if not isinstance(product, dict):
  846. continue
  847. quantity_mode = (_get_field(product, "quantity_mode", "quantityMode") or "customer_demand").strip()
  848. price_mode = (_get_field(product, "price_mode", "priceMode") or "market").strip()
  849. product["quantityMode"] = quantity_mode
  850. product["priceMode"] = price_mode
  851. if quantity_mode == "customer_demand":
  852. product["quantity"] = 0
  853. if price_mode == "market":
  854. product["price"] = 0
  855. product["subtotal"] = 0
  856. product["taxAmount"] = 0
  857. def _validate_product_prices_by_contract_type(data: dict) -> None:
  858. contract_type = (_get_field(data, "contract_type", "contractType") or "").strip()
  859. if contract_type not in ("sale", "purchase"):
  860. return
  861. products = _get_field(data, "products", "productList") or []
  862. for product in products:
  863. price = _decimal_value(_get_field(product, "price"))
  864. subtotal = _decimal_value(_get_field(product, "subtotal"))
  865. if price < Decimal("0"):
  866. raise ValueError("销售/采购合同产品的含税单价不能为负数")
  867. if subtotal < Decimal("0"):
  868. raise ValueError("销售/采购合同产品的含税总价不能为负数")
  869. def _validate_sale_purchase_contract_amount(data: dict) -> None:
  870. contract_type = (_get_field(data, "contract_type", "contractType") or "").strip()
  871. if contract_type not in ("sale", "purchase"):
  872. return
  873. amount = _decimal_value(_get_field(data, "amount"))
  874. if amount < Decimal("0"):
  875. raise ValueError("销售合同或采购合同的合同金额不能为负数")
  876. def _resolve_contract_product_ids(
  877. db: Session,
  878. *,
  879. tenant_no: str,
  880. products: List[dict],
  881. user_id: str = None,
  882. ) -> None:
  883. for product in products:
  884. pid = resolve_product_id_for_quote_item(
  885. db,
  886. tenant_no=tenant_no,
  887. product_data=product,
  888. user_id=user_id,
  889. )
  890. product["productId"] = pid
  891. product["product_id"] = pid
  892. def _calc_amount_with_tax(amount: Decimal, tax_rate: Decimal) -> Decimal:
  893. if tax_rate is None:
  894. tax_rate = Decimal("0")
  895. return amount * (Decimal("1") + tax_rate / Decimal("100"))
  896. def _apply_contract_entity_fields(
  897. entity: CrmContract,
  898. data: dict,
  899. *,
  900. db: Session,
  901. tenant_no: str,
  902. user_id: str = None,
  903. is_create: bool = True,
  904. ) -> None:
  905. field_map = (
  906. (("contract_name", "contractName"), "contract_name"),
  907. (("customer_id", "customerId"), "customer_id"),
  908. (("customer_name", "customerName"), "customer_name"),
  909. (("opportunity_id", "opportunityId"), "opportunity_id"),
  910. (("quote_id", "quoteId"), "quote_id"),
  911. (("parent_contract_id", "parentContractId"), "parent_contract_id"),
  912. (("template_id", "templateId"), "template_id"),
  913. (("contract_template", "contractTemplate"), "contract_template"),
  914. (("contact_id", "contactId"), "contact_id"),
  915. (("contract_type", "contractType"), "contract_type"),
  916. (("contract_nature", "contractNature"), "contract_nature"),
  917. (("currency",), "currency"),
  918. (("performance_status", "performanceStatus"), "performance_status"),
  919. (("contract_file", "contractFile"), "contract_file"),
  920. (("attachment_files", "attachmentFiles"), "attachment_files"),
  921. (("owner_user_id", "ownerUserId"), "owner_user_id"),
  922. (("party_a", "partyA"), "party_a"),
  923. (("party_a_address", "partyAAddress"), "party_a_address"),
  924. (("party_a_contact", "partyAContact"), "party_a_contact"),
  925. (("party_a_mobile", "partyAMobile"), "party_a_mobile"),
  926. (("party_a_legal_person", "partyALegalPerson"), "party_a_legal_person"),
  927. (("party_a_agent", "partyAAgent"), "party_a_agent"),
  928. (("party_a_phone_fax", "partyAPhoneFax"), "party_a_phone_fax"),
  929. (("party_a_bank", "partyABank"), "party_a_bank"),
  930. (("party_a_account", "partyAAccount"), "party_a_account"),
  931. (("supplier_id", "supplierId"), "supplier_id"),
  932. (("settlement_method", "settlementMethod"), "settlement_method"),
  933. (("party_b", "partyB"), "party_b"),
  934. (("party_b_address", "partyBAddress"), "party_b_address"),
  935. (("party_b_contact", "partyBContact"), "party_b_contact"),
  936. (("party_b_mobile", "partyBMobile"), "party_b_mobile"),
  937. (("party_b_legal_person", "partyBLegalPerson"), "party_b_legal_person"),
  938. (("party_b_agent", "partyBAgent"), "party_b_agent"),
  939. (("party_b_phone_fax", "partyBPhoneFax"), "party_b_phone_fax"),
  940. (("party_b_bank", "partyBBank"), "party_b_bank"),
  941. (("party_b_account", "partyBAccount"), "party_b_account"),
  942. (("payment_terms", "paymentTerms"), "payment_terms"),
  943. (("delivery_terms", "deliveryTerms"), "delivery_terms"),
  944. (("contract_terms", "contractTerms"), "contract_terms"),
  945. (("template_content", "templateContent"), "template_content"),
  946. (("settlement_clause_drafts", "settlementClauseDrafts"), "settlement_clause_drafts"),
  947. (("remark",), "remark"),
  948. (("order_num", "orderNum"), "order_num"),
  949. )
  950. for keys, attr in field_map:
  951. val = _get_field(data, *keys)
  952. if val is not None:
  953. setattr(entity, attr, val)
  954. if _get_field(data, "amount") is not None:
  955. entity.amount = _decimal_value(_get_field(data, "amount"))
  956. if _get_field(data, "tax_rate", "taxRate") is not None:
  957. entity.tax_rate = _decimal_value(_get_field(data, "tax_rate", "taxRate"))
  958. if _get_field(data, "amount_with_tax", "amountWithTax") is not None:
  959. entity.amount_with_tax = _decimal_value(_get_field(data, "amount_with_tax", "amountWithTax"))
  960. elif entity.amount is not None and entity.tax_rate is not None:
  961. entity.amount_with_tax = _calc_amount_with_tax(entity.amount, entity.tax_rate)
  962. if _get_field(data, "freight") is not None:
  963. entity.freight = _decimal_value(_get_field(data, "freight"))
  964. if _get_field(data, "barrel_deposit", "barrelDeposit") is not None:
  965. entity.barrel_deposit = _decimal_value(_get_field(data, "barrel_deposit", "barrelDeposit"))
  966. for date_key, attr in (
  967. (("sign_date", "signDate"), "sign_date"),
  968. (("actual_sign_date", "actualSignDate"), "actual_sign_date"),
  969. (("start_date", "startDate"), "start_date"),
  970. (("end_date", "endDate"), "end_date"),
  971. ):
  972. val = _get_field(data, *date_key)
  973. if val is not None:
  974. setattr(entity, attr, _parse_optional_date(val))
  975. if _get_field(data, "contract_period", "contractPeriod") is not None:
  976. entity.contract_period = int(_get_field(data, "contract_period", "contractPeriod"))
  977. if _get_field(data, "performance_rate", "performanceRate") is not None:
  978. entity.performance_rate = _decimal_value(_get_field(data, "performance_rate", "performanceRate"))
  979. if _get_field(data, "customer_satisfaction", "customerSatisfaction") is not None:
  980. entity.customer_satisfaction = int(_get_field(data, "customer_satisfaction", "customerSatisfaction"))
  981. if _get_field(data, "renewal_count", "renewalCount") is not None:
  982. entity.renewal_count = int(_get_field(data, "renewal_count", "renewalCount"))
  983. if is_create and not entity.status:
  984. entity.status = "draft"
  985. if entity.status == "draft":
  986. entity.approval_status = None
  987. customer_id = (entity.customer_id or "").strip()
  988. customer = None
  989. if customer_id:
  990. customer = get_customer(db, customer_id)
  991. if customer and tenant_no and customer.tenant_no != tenant_no:
  992. raise ValueError("客户不存在")
  993. if customer:
  994. entity.customer_name = customer.customer_name or entity.customer_name or ""
  995. if entity.contact_id:
  996. contact = get_contact(db, entity.contact_id)
  997. if contact:
  998. entity.contact_name = contact.contact_name or entity.contact_name or ""
  999. entity.contact_mobile = contact.mobile or entity.contact_mobile or ""
  1000. owner_id = (entity.owner_user_id or user_id or "").strip()
  1001. if owner_id:
  1002. entity.owner_user_id = owner_id
  1003. entity.owner_user_name = _resolve_user_display_name(db, owner_id)
  1004. supplier = None
  1005. supplier_id = (entity.supplier_id or "").strip()
  1006. if supplier_id:
  1007. supplier = get_supplier_info(db, supplier_id, tenant_no=tenant_no)
  1008. # 后端兜底:当新增/编辑未显式传入供需方信息时,按供应商与客户基础资料补齐,避免写入空数据
  1009. if supplier:
  1010. if _is_blank(entity.party_a):
  1011. entity.party_a = _first_non_blank(getattr(supplier, "supplier_name", ""))
  1012. if _is_blank(entity.party_a_address):
  1013. entity.party_a_address = _first_non_blank(getattr(supplier, "supplier_address", ""))
  1014. if _is_blank(entity.party_a_legal_person):
  1015. entity.party_a_legal_person = _first_non_blank(getattr(supplier, "legal_person", ""))
  1016. if _is_blank(entity.party_a_agent):
  1017. entity.party_a_agent = _first_non_blank(getattr(supplier, "agent", ""))
  1018. if _is_blank(entity.party_a_phone_fax):
  1019. entity.party_a_phone_fax = _first_non_blank(getattr(supplier, "phone_fax", ""))
  1020. if _is_blank(entity.party_a_bank):
  1021. entity.party_a_bank = _first_non_blank(getattr(supplier, "bank_name", ""))
  1022. if _is_blank(entity.party_a_account):
  1023. entity.party_a_account = _first_non_blank(getattr(supplier, "bank_account", ""))
  1024. if customer:
  1025. inv = _get_default_invoice_info(db, tenant_no=tenant_no, customer_id=customer_id)
  1026. if _is_blank(entity.party_b):
  1027. entity.party_b = _first_non_blank(
  1028. inv.get("companyName") if inv else "",
  1029. customer.customer_name,
  1030. )
  1031. if _is_blank(entity.party_b_address):
  1032. entity.party_b_address = _first_non_blank(
  1033. inv.get("companyAddress") if inv else "",
  1034. _build_customer_address(customer),
  1035. )
  1036. if _is_blank(entity.party_b_contact):
  1037. entity.party_b_contact = _first_non_blank(entity.contact_name)
  1038. if _is_blank(entity.party_b_mobile):
  1039. entity.party_b_mobile = _first_non_blank(
  1040. inv.get("phoneFax") if inv else "",
  1041. entity.contact_mobile,
  1042. customer.mobile,
  1043. customer.telephone,
  1044. )
  1045. if _is_blank(entity.party_b_legal_person):
  1046. entity.party_b_legal_person = _first_non_blank(inv.get("legalRepresentative") if inv else "")
  1047. if _is_blank(entity.party_b_phone_fax):
  1048. entity.party_b_phone_fax = _first_non_blank(
  1049. inv.get("phoneFax") if inv else "",
  1050. customer.telephone,
  1051. )
  1052. if _is_blank(entity.party_b_bank):
  1053. entity.party_b_bank = _first_non_blank(inv.get("bankName") if inv else "")
  1054. if _is_blank(entity.party_b_account):
  1055. entity.party_b_account = _first_non_blank(inv.get("bankAccount") if inv else "")
  1056. received = entity.received_amount if entity.received_amount is not None else Decimal("0")
  1057. invoice = entity.invoice_amount if entity.invoice_amount is not None else Decimal("0")
  1058. amount = entity.amount if entity.amount is not None else Decimal("0")
  1059. entity.received_amount = received
  1060. entity.invoice_amount = invoice
  1061. entity.unreceived_amount = amount - received
  1062. entity.uninvoice_amount = amount - invoice
  1063. def create_contract(
  1064. db: Session,
  1065. *,
  1066. tenant_no: str,
  1067. data: dict,
  1068. user_id: str = None,
  1069. dept_id: str = "",
  1070. ) -> Dict[str, Any]:
  1071. """Java: insertByBo"""
  1072. products = _get_field(data, "products", "productList") or []
  1073. if not isinstance(products, list):
  1074. raise ValueError("产品明细格式无效")
  1075. product_rows = [dict(p) for p in products]
  1076. _validate_contract_type_and_products(data)
  1077. _normalize_framework_contract_data(data)
  1078. _validate_product_prices_by_contract_type(data)
  1079. _validate_sale_purchase_contract_amount(data)
  1080. customer_id = (_get_field(data, "customer_id", "customerId") or "").strip()
  1081. if not customer_id:
  1082. raise ValueError("客户ID不能为空")
  1083. supplier_id = (_get_field(data, "supplier_id", "supplierId") or "").strip() or None
  1084. assert_products_allowed_for_supplier(
  1085. db,
  1086. tenant_no=tenant_no,
  1087. supplier_id=str(supplier_id) if supplier_id else None,
  1088. products=product_rows or [],
  1089. )
  1090. contract_type = (_get_field(data, "contract_type", "contractType") or "sale").strip() or "sale"
  1091. sign_date = _parse_optional_date(_get_field(data, "sign_date", "signDate")) or date.today()
  1092. contract_no = (_get_field(data, "contract_no", "contractNo") or "").strip()
  1093. if not contract_no:
  1094. contract_no = generate_contract_no(db, tenant_no, supplier_id=supplier_id, sign_date=sign_date)
  1095. else:
  1096. contract_no = align_contract_no_to_sign_date(db, tenant_no, contract_no, sign_date)
  1097. if contract_no_exists(db, tenant_no, contract_no):
  1098. raise ValueError(f"合同编号已存在:{contract_no}")
  1099. user_contract_name = (_get_field(data, "contract_name", "contractName") or "").strip()
  1100. now = datetime.now()
  1101. entity = CrmContract(
  1102. id=generate_uuid(),
  1103. contract_no=contract_no,
  1104. contract_name="",
  1105. customer_id=customer_id,
  1106. status="draft",
  1107. contract_type=contract_type,
  1108. amount=_decimal_value(_get_field(data, "amount")),
  1109. tax_rate=_decimal_value(_get_field(data, "tax_rate", "taxRate"), Decimal("6.00")),
  1110. freight=_decimal_value(_get_field(data, "freight"), Decimal("0")),
  1111. barrel_deposit=_decimal_value(_get_field(data, "barrel_deposit", "barrelDeposit"), Decimal("0")),
  1112. currency=_get_field(data, "currency") or "CNY",
  1113. sign_date=sign_date,
  1114. tenant_no=tenant_no,
  1115. create_by=user_id,
  1116. create_dept_id=dept_id or "",
  1117. create_time=now,
  1118. update_by=user_id,
  1119. update_time=now,
  1120. del_flag=0,
  1121. received_amount=Decimal("0"),
  1122. invoice_amount=Decimal("0"),
  1123. )
  1124. _apply_contract_entity_fields(
  1125. entity, data, db=db, tenant_no=tenant_no, user_id=user_id, is_create=True
  1126. )
  1127. entity.contract_no = contract_no
  1128. entity.contract_name = _build_contract_name_from_parties(
  1129. db,
  1130. tenant_no=tenant_no,
  1131. contract_no=contract_no,
  1132. party_a=entity.party_a or "",
  1133. party_b=entity.party_b or "",
  1134. supplier_id=entity.supplier_id or supplier_id or "",
  1135. customer_id=entity.customer_id or customer_id,
  1136. customer_name=entity.customer_name or "",
  1137. user_contract_name=user_contract_name,
  1138. )
  1139. _resolve_contract_product_ids(db, tenant_no=tenant_no, products=product_rows, user_id=user_id)
  1140. db.add(entity)
  1141. db.flush()
  1142. if product_rows:
  1143. batch_insert_contract_products(
  1144. db,
  1145. tenant_no=tenant_no,
  1146. contract_id=entity.id,
  1147. products=product_rows,
  1148. contract_type=contract_type,
  1149. user_id=user_id,
  1150. dept_id=dept_id,
  1151. )
  1152. db.commit()
  1153. db.refresh(entity)
  1154. return get_contract_detail(db, entity.id, tenant_no=tenant_no)
  1155. # 允许编辑的合同状态:草稿 / 审批中 / 已审批(未执行);保存后统一回草稿
  1156. CONTRACT_EDITABLE_STATUSES = frozenset({"draft", "approving", "approved"})
  1157. def assert_contract_editable_for_update(status: str) -> None:
  1158. s = (status or "").strip() or "draft"
  1159. if s not in CONTRACT_EDITABLE_STATUSES:
  1160. raise ValueError("仅草稿、审批中或已审批(未执行)的合同才能修改")
  1161. def update_contract(
  1162. db: Session,
  1163. contract_id: str,
  1164. *,
  1165. tenant_no: str,
  1166. data: dict,
  1167. user_id: str = None,
  1168. dept_id: str = "",
  1169. user_info=None,
  1170. ) -> Dict[str, Any]:
  1171. """Java: updateByBo"""
  1172. old = _get_contract_row_in_scope(db, contract_id, tenant_no=tenant_no, user_info=user_info)
  1173. if not old:
  1174. raise ValueError("合同不存在")
  1175. prev_status = (old.status or "").strip() or "draft"
  1176. assert_contract_editable_for_update(prev_status)
  1177. products = _get_field(data, "products", "productList")
  1178. product_rows = [dict(p) for p in products] if products is not None else None
  1179. work_data = dict(data)
  1180. if product_rows is not None:
  1181. work_data["products"] = product_rows
  1182. _validate_contract_type_and_products(work_data)
  1183. _normalize_framework_contract_data(work_data)
  1184. _validate_product_prices_by_contract_type(work_data)
  1185. _validate_sale_purchase_contract_amount(work_data)
  1186. contract_type = (_get_field(data, "contract_type", "contractType") or old.contract_type or "sale").strip()
  1187. old.contract_type = contract_type
  1188. # 再编辑回草稿:作废全部历史审批(含已通过/已拒绝),避免再提审后 canApprove 命中旧记录
  1189. invalidate_all_approvals(db, contract_id)
  1190. _apply_contract_entity_fields(
  1191. old, data, db=db, tenant_no=tenant_no, user_id=user_id, is_create=False
  1192. )
  1193. # 编辑保存后统一回草稿(含审批中 / 已审批未执行)
  1194. old.status = "draft"
  1195. old.approval_status = None
  1196. products_to_check = (
  1197. product_rows
  1198. if product_rows is not None
  1199. else list_contract_products(db, contract_id, tenant_no=tenant_no)
  1200. )
  1201. assert_products_allowed_for_supplier(
  1202. db,
  1203. tenant_no=tenant_no,
  1204. supplier_id=str(old.supplier_id) if old.supplier_id else None,
  1205. products=products_to_check or [],
  1206. )
  1207. if product_rows is not None:
  1208. _resolve_contract_product_ids(db, tenant_no=tenant_no, products=product_rows, user_id=user_id)
  1209. sign_date = old.sign_date or date.today()
  1210. submitted_no = (_get_field(data, "contract_no", "contractNo") or "").strip() or (
  1211. old.contract_no or ""
  1212. ).strip()
  1213. if submitted_no:
  1214. aligned_no = align_contract_no_to_sign_date(
  1215. db,
  1216. tenant_no,
  1217. submitted_no,
  1218. sign_date,
  1219. exclude_id=old.id,
  1220. )
  1221. if aligned_no != (old.contract_no or ""):
  1222. if contract_no_exists(db, tenant_no, aligned_no, exclude_id=old.id):
  1223. raise ValueError(f"合同编号已存在:{aligned_no}")
  1224. old.contract_no = aligned_no
  1225. elif submitted_no != (old.contract_no or ""):
  1226. if contract_no_exists(db, tenant_no, submitted_no, exclude_id=old.id):
  1227. raise ValueError(f"合同编号已存在:{submitted_no}")
  1228. old.contract_no = submitted_no
  1229. user_name = (_get_field(data, "contract_name", "contractName") or old.contract_name or "").strip()
  1230. old.contract_name = _build_contract_name_from_parties(
  1231. db,
  1232. tenant_no=tenant_no,
  1233. contract_no=old.contract_no or "",
  1234. party_a=old.party_a or "",
  1235. party_b=old.party_b or "",
  1236. supplier_id=old.supplier_id or "",
  1237. customer_id=old.customer_id or "",
  1238. customer_name=old.customer_name or "",
  1239. user_contract_name=user_name,
  1240. )
  1241. old.update_by = user_id
  1242. old.update_time = datetime.now()
  1243. db.flush()
  1244. if product_rows is not None:
  1245. delete_products_by_contract_id(db, contract_id)
  1246. if product_rows:
  1247. batch_insert_contract_products(
  1248. db,
  1249. tenant_no=tenant_no,
  1250. contract_id=contract_id,
  1251. products=product_rows,
  1252. contract_type=contract_type,
  1253. user_id=user_id,
  1254. dept_id=dept_id,
  1255. )
  1256. db.commit()
  1257. return get_contract_detail(db, contract_id, tenant_no=tenant_no)
  1258. def soft_delete_contracts(
  1259. db: Session,
  1260. contract_ids: List[str],
  1261. *,
  1262. tenant_no: str,
  1263. validate: bool = True,
  1264. user_info=None,
  1265. ) -> int:
  1266. """Java: deleteWithValidByIds — 软删除"""
  1267. count = 0
  1268. for cid in contract_ids:
  1269. entity = _get_contract_row_in_scope(db, cid, tenant_no=tenant_no, user_info=user_info)
  1270. if not entity:
  1271. continue
  1272. if validate and entity.status != "draft":
  1273. raise ValueError("只能删除草稿状态的合同")
  1274. assert_row_deletable_by_creator(entity, user_info)
  1275. entity.del_flag = 1
  1276. entity.update_time = datetime.now()
  1277. count += 1
  1278. db.commit()
  1279. return count
  1280. def validate_framework_contract_for_submit_approval(
  1281. db: Session,
  1282. contract_id: str,
  1283. *,
  1284. tenant_no: str,
  1285. contract: CrmContract = None,
  1286. ) -> None:
  1287. """框架合同提交审批校验:仅要求有产品明细;调价区间为可选,不强制。"""
  1288. entity = contract or get_contract_row(db, contract_id, tenant_no=tenant_no)
  1289. if not entity:
  1290. raise ValueError("合同不存在")
  1291. if not is_framework_contract_type(entity.contract_type):
  1292. return
  1293. products = list_contract_products(db, contract_id, tenant_no=tenant_no)
  1294. if not products:
  1295. raise ValueError("框架合同必须维护产品明细")
  1296. def submit_contract_approval(
  1297. db: Session,
  1298. contract_id: str,
  1299. *,
  1300. tenant_no: str,
  1301. approver_ids: List[str] = None,
  1302. remark: str = "",
  1303. user_id: str = None,
  1304. dept_id: str = "",
  1305. user_info=None,
  1306. ) -> bool:
  1307. """Java: submitApproval"""
  1308. entity = _get_contract_row_in_scope(db, contract_id, tenant_no=tenant_no, user_info=user_info)
  1309. if not entity:
  1310. raise ValueError("合同不存在")
  1311. if entity.status != "draft":
  1312. raise ValueError("只有草稿状态的合同才能提交审批")
  1313. validate_framework_contract_for_submit_approval(
  1314. db, contract_id, tenant_no=tenant_no, contract=entity
  1315. )
  1316. entity.status = "approving"
  1317. entity.approval_status = "pending"
  1318. if remark:
  1319. entity.remark = remark
  1320. entity.update_time = datetime.now()
  1321. db.flush()
  1322. if approver_ids:
  1323. # 重新提审前清掉残留审批记录,保证仅当前轮有效
  1324. invalidate_all_approvals(db, contract_id)
  1325. create_approval_records(
  1326. db,
  1327. tenant_no=tenant_no,
  1328. contract_id=contract_id,
  1329. approver_ids=approver_ids,
  1330. user_id=user_id,
  1331. dept_id=dept_id,
  1332. )
  1333. db.commit()
  1334. return True
  1335. def batch_submit_contract_approval(
  1336. db: Session,
  1337. contract_ids: List[str],
  1338. *,
  1339. tenant_no: str,
  1340. approver_ids: List[str] = None,
  1341. remark: str = "",
  1342. user_id: str = None,
  1343. dept_id: str = "",
  1344. user_info=None,
  1345. ) -> int:
  1346. """Java: batchSubmitApproval"""
  1347. success = 0
  1348. for cid in contract_ids:
  1349. try:
  1350. submit_contract_approval(
  1351. db,
  1352. cid,
  1353. tenant_no=tenant_no,
  1354. approver_ids=approver_ids,
  1355. remark=remark,
  1356. user_id=user_id,
  1357. dept_id=dept_id,
  1358. )
  1359. success += 1
  1360. except ValueError:
  1361. continue
  1362. return success
  1363. def withdraw_contract_approval(
  1364. db: Session,
  1365. contract_id: str,
  1366. *,
  1367. tenant_no: str,
  1368. remark: str = "",
  1369. user_id: str = None,
  1370. user_info=None,
  1371. ) -> bool:
  1372. """Java: withdrawApproval"""
  1373. entity = _get_contract_row_in_scope(db, contract_id, tenant_no=tenant_no, user_info=user_info)
  1374. if not entity:
  1375. raise ValueError("合同不存在")
  1376. if entity.status != "approving":
  1377. raise ValueError("只有审批中的合同才能撤回")
  1378. entity.status = "draft"
  1379. entity.approval_status = None
  1380. if remark:
  1381. entity.remark = remark
  1382. entity.update_by = user_id
  1383. entity.update_time = datetime.now()
  1384. delete_pending_approvals(db, contract_id)
  1385. db.commit()
  1386. return True
  1387. def start_execute(
  1388. db: Session,
  1389. contract_id: str,
  1390. *,
  1391. tenant_no: str,
  1392. remark: str = "",
  1393. user_id: str = None,
  1394. user_info=None,
  1395. ) -> bool:
  1396. entity = _get_contract_row_in_scope(db, contract_id, tenant_no=tenant_no, user_info=user_info)
  1397. if not entity:
  1398. raise ValueError("合同不存在")
  1399. if entity.status != "approved":
  1400. raise ValueError("只有已审批的合同才能开始执行")
  1401. entity.status = "executing"
  1402. if remark:
  1403. entity.remark = remark
  1404. entity.update_by = user_id
  1405. entity.update_time = datetime.now()
  1406. db.commit()
  1407. return True
  1408. def finish_contract(
  1409. db: Session,
  1410. contract_id: str,
  1411. *,
  1412. tenant_no: str,
  1413. remark: str = "",
  1414. user_id: str = None,
  1415. user_info=None,
  1416. ) -> bool:
  1417. entity = _get_contract_row_in_scope(db, contract_id, tenant_no=tenant_no, user_info=user_info)
  1418. if not entity:
  1419. raise ValueError("合同不存在")
  1420. if entity.status != "executing":
  1421. raise ValueError("只有执行中的合同才能完成")
  1422. entity.status = "finished"
  1423. if remark:
  1424. entity.remark = remark
  1425. entity.update_by = user_id
  1426. entity.update_time = datetime.now()
  1427. db.commit()
  1428. return True
  1429. def invalid_contract(
  1430. db: Session,
  1431. contract_id: str,
  1432. *,
  1433. tenant_no: str,
  1434. invalid_reason: str,
  1435. remark: str = "",
  1436. user_id: str = None,
  1437. user_info=None,
  1438. ) -> bool:
  1439. if not (invalid_reason or "").strip():
  1440. raise ValueError("作废原因不能为空")
  1441. entity = _get_contract_row_in_scope(db, contract_id, tenant_no=tenant_no, user_info=user_info)
  1442. if not entity:
  1443. raise ValueError("合同不存在")
  1444. if entity.status == "finished":
  1445. raise ValueError("已完成的合同不能作废")
  1446. entity.status = "invalid"
  1447. entity.invalid_reason = invalid_reason
  1448. entity.invalid_time = datetime.now()
  1449. if remark:
  1450. entity.remark = remark
  1451. entity.update_by = user_id
  1452. entity.update_time = datetime.now()
  1453. db.commit()
  1454. return True
  1455. def save_template(
  1456. db: Session,
  1457. contract_id: str,
  1458. template_content: str,
  1459. *,
  1460. tenant_no: str,
  1461. settlement_clause_drafts: str = None,
  1462. user_info=None,
  1463. ) -> bool:
  1464. entity = _get_contract_row_in_scope(db, contract_id, tenant_no=tenant_no, user_info=user_info)
  1465. if not entity:
  1466. raise ValueError("合同不存在")
  1467. drafts = settlement_clause_drafts
  1468. if not (drafts or "").strip():
  1469. method = (entity.settlement_method or "").strip() or "arrive_payment"
  1470. drafts = json.dumps(
  1471. {method: default_settlement_clause(method)},
  1472. ensure_ascii=False,
  1473. )
  1474. entity.template_content = template_content or ""
  1475. entity.settlement_clause_drafts = drafts
  1476. entity.update_time = datetime.now()
  1477. db.commit()
  1478. return True
  1479. def get_template(
  1480. db: Session,
  1481. contract_id: str,
  1482. *,
  1483. tenant_no: str,
  1484. user_info=None,
  1485. ) -> str:
  1486. entity = _get_contract_row_in_scope(db, contract_id, tenant_no=tenant_no, user_info=user_info)
  1487. if not entity:
  1488. raise ValueError("合同不存在")
  1489. return entity.template_content or ""
  1490. def upload_file(
  1491. db: Session,
  1492. contract_id: str,
  1493. file_url: str,
  1494. *,
  1495. tenant_no: str,
  1496. user_info=None,
  1497. ) -> bool:
  1498. entity = _get_contract_row_in_scope(db, contract_id, tenant_no=tenant_no, user_info=user_info)
  1499. if not entity:
  1500. raise ValueError("合同不存在")
  1501. entity.contract_file = file_url or ""
  1502. entity.update_time = datetime.now()
  1503. db.commit()
  1504. return True
  1505. def upload_attachments(
  1506. db: Session,
  1507. contract_id: str,
  1508. oss_ids: str,
  1509. *,
  1510. tenant_no: str,
  1511. user_info=None,
  1512. ) -> bool:
  1513. if not (oss_ids or "").strip():
  1514. raise ValueError("附件ossId不能为空")
  1515. entity = _get_contract_row_in_scope(db, contract_id, tenant_no=tenant_no, user_info=user_info)
  1516. if not entity:
  1517. raise ValueError("合同不存在")
  1518. existing = (entity.attachment_files or "").strip()
  1519. new_parts = [x.strip() for x in oss_ids.split(",") if x.strip()]
  1520. merged = set(existing.split(",")) if existing and not existing.startswith("[") else set()
  1521. merged.discard("")
  1522. merged.update(new_parts)
  1523. entity.attachment_files = ",".join(sorted(merged))
  1524. entity.update_time = datetime.now()
  1525. db.commit()
  1526. return True
  1527. def upload_attachments_with_category(
  1528. db: Session,
  1529. contract_id: str,
  1530. attachments: List[dict],
  1531. *,
  1532. tenant_no: str,
  1533. user_info=None,
  1534. ) -> bool:
  1535. """按入参整表覆盖合同扫描件;attachments=[] 表示清空。"""
  1536. entity = _get_contract_row_in_scope(db, contract_id, tenant_no=tenant_no, user_info=user_info)
  1537. if not entity:
  1538. raise ValueError("合同不存在")
  1539. saved: List[dict] = []
  1540. seen = set()
  1541. for att in attachments or []:
  1542. oss_id = str(att.get("ossId") or att.get("oss_id") or "").strip()
  1543. if not oss_id or oss_id in seen:
  1544. continue
  1545. seen.add(oss_id)
  1546. saved.append({
  1547. "ossId": oss_id,
  1548. "category": str(att.get("category") or "other"),
  1549. })
  1550. entity.attachment_files = json.dumps(saved, ensure_ascii=False)
  1551. entity.update_time = datetime.now()
  1552. db.commit()
  1553. return True
  1554. def statistics_overview(
  1555. db: Session,
  1556. tenant_no: str,
  1557. *,
  1558. owner_user_id: str = None,
  1559. begin_time: str = None,
  1560. end_time: str = None,
  1561. user_info=None,
  1562. ) -> Dict[str, Any]:
  1563. q = db.query(CrmContract).filter(CrmContract.tenant_no == tenant_no, CrmContract.del_flag == 0)
  1564. if owner_user_id:
  1565. q = q.filter(CrmContract.owner_user_id == owner_user_id)
  1566. begin_dt = _parse_optional_datetime(begin_time)
  1567. end_dt = _parse_optional_datetime(end_time)
  1568. if begin_dt and end_dt:
  1569. q = q.filter(CrmContract.create_time >= begin_dt, CrmContract.create_time <= end_dt)
  1570. elif begin_dt:
  1571. q = q.filter(CrmContract.create_time >= begin_dt)
  1572. elif end_dt:
  1573. q = q.filter(CrmContract.create_time <= end_dt)
  1574. if user_info:
  1575. q = apply_crm_owner_scope(q, CrmContract, user_info, db, tenant_no)
  1576. contracts = q.all()
  1577. total_count = len(contracts)
  1578. def _count(status: str) -> int:
  1579. return sum(1 for c in contracts if c.status == status)
  1580. total_amount = sum(_decimal_value(c.amount) for c in contracts)
  1581. received_amount = sum(_decimal_value(c.received_amount) for c in contracts)
  1582. unreceived_amount = sum(_decimal_value(c.unreceived_amount) for c in contracts)
  1583. invoice_amount = sum(_decimal_value(c.invoice_amount) for c in contracts)
  1584. uninvoice_amount = sum(_decimal_value(c.uninvoice_amount) for c in contracts)
  1585. received_rate = (
  1586. (received_amount / total_amount * Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
  1587. if total_amount > 0
  1588. else Decimal("0")
  1589. )
  1590. invoice_rate = (
  1591. (invoice_amount / total_amount * Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
  1592. if total_amount > 0
  1593. else Decimal("0")
  1594. )
  1595. return {
  1596. "totalCount": total_count,
  1597. "draftCount": _count("draft"),
  1598. "approvingCount": _count("approving"),
  1599. "executingCount": _count("executing"),
  1600. "finishedCount": _count("finished"),
  1601. "invalidCount": _count("invalid"),
  1602. "totalAmount": float(total_amount),
  1603. "receivedAmount": float(received_amount),
  1604. "unreceivedAmount": float(unreceived_amount),
  1605. "receivedRate": float(received_rate),
  1606. "invoiceAmount": float(invoice_amount),
  1607. "uninvoiceAmount": float(uninvoice_amount),
  1608. "invoiceRate": float(invoice_rate),
  1609. }
  1610. def statistics_by_status(db: Session, tenant_no: str, *, user_info=None) -> List[Dict[str, Any]]:
  1611. q = db.query(CrmContract).filter(CrmContract.tenant_no == tenant_no, CrmContract.del_flag == 0)
  1612. if user_info:
  1613. q = apply_crm_owner_scope(q, CrmContract, user_info, db, tenant_no)
  1614. contracts = q.all()
  1615. total_count = len(contracts)
  1616. total_amount = sum(_decimal_value(c.amount) for c in contracts)
  1617. status_map = (
  1618. ("draft", "草稿"),
  1619. ("approving", "审批中"),
  1620. ("approved", "已审批"),
  1621. ("executing", "执行中"),
  1622. ("finished", "已完成"),
  1623. ("invalid", "已作废"),
  1624. )
  1625. result = []
  1626. for status, status_name in status_map:
  1627. subset = [c for c in contracts if c.status == status]
  1628. count = len(subset)
  1629. amount = sum(_decimal_value(c.amount) for c in subset)
  1630. percent = (count * 100.0 / total_count) if total_count else 0.0
  1631. result.append(
  1632. {
  1633. "status": status,
  1634. "statusName": status_name,
  1635. "count": count,
  1636. "amount": float(amount),
  1637. "percent": f"{percent:.2f}",
  1638. }
  1639. )
  1640. return result
  1641. def statistics_by_type(db: Session, tenant_no: str, *, user_info=None) -> List[Dict[str, Any]]:
  1642. q = db.query(CrmContract).filter(CrmContract.tenant_no == tenant_no, CrmContract.del_flag == 0)
  1643. if user_info:
  1644. q = apply_crm_owner_scope(q, CrmContract, user_info, db, tenant_no)
  1645. contracts = q.all()
  1646. total_count = len(contracts)
  1647. type_map = (
  1648. ("sale", "销售合同"),
  1649. ("service", "服务合同"),
  1650. ("purchase", "采购合同"),
  1651. ("framework_sale", "框架销售合同"),
  1652. ("framework_purchase", "框架采购合同"),
  1653. ("framework", "框架合同"), # 历史兼容
  1654. ("supplement", "补充协议"),
  1655. ("lease", "租赁合同"),
  1656. ("other", "其他"),
  1657. )
  1658. result = []
  1659. for contract_type, type_name in type_map:
  1660. subset = [c for c in contracts if c.contract_type == contract_type]
  1661. count = len(subset)
  1662. if count == 0:
  1663. continue
  1664. amount = sum(_decimal_value(c.amount) for c in subset)
  1665. percent = (count * 100.0 / total_count) if total_count else 0.0
  1666. result.append(
  1667. {
  1668. "contractType": contract_type,
  1669. "typeName": type_name,
  1670. "count": count,
  1671. "amount": float(amount),
  1672. "percent": f"{percent:.2f}",
  1673. }
  1674. )
  1675. return result
  1676. def _contract_period_key(dt: datetime, period_type: str) -> str:
  1677. if period_type == "year":
  1678. return dt.strftime("%Y")
  1679. if period_type == "quarter":
  1680. quarter = (dt.month - 1) // 3 + 1
  1681. return f"{dt.year}-Q{quarter}"
  1682. return dt.strftime("%Y-%m")
  1683. def statistics_trend(
  1684. db: Session,
  1685. tenant_no: str,
  1686. *,
  1687. period_type: str = "month",
  1688. begin_time: str = None,
  1689. end_time: str = None,
  1690. user_info=None,
  1691. ) -> List[Dict[str, Any]]:
  1692. q = db.query(CrmContract).filter(CrmContract.tenant_no == tenant_no, CrmContract.del_flag == 0)
  1693. begin_dt = _parse_optional_datetime(begin_time)
  1694. end_dt = _parse_optional_datetime(end_time)
  1695. if begin_dt and end_dt:
  1696. q = q.filter(CrmContract.create_time >= begin_dt, CrmContract.create_time <= end_dt)
  1697. if user_info:
  1698. q = apply_crm_owner_scope(q, CrmContract, user_info, db, tenant_no)
  1699. contracts = q.all()
  1700. if not contracts:
  1701. return []
  1702. grouped: Dict[str, List[CrmContract]] = defaultdict(list)
  1703. for contract in contracts:
  1704. create_time = contract.create_time or datetime.now()
  1705. grouped[_contract_period_key(create_time, period_type or "month")].append(contract)
  1706. result = []
  1707. for period, subset in sorted(grouped.items()):
  1708. total_amount = sum(_decimal_value(c.amount) for c in subset)
  1709. received_amount = sum(_decimal_value(c.received_amount) for c in subset)
  1710. received_rate = (
  1711. (received_amount / total_amount * Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
  1712. if total_amount > 0
  1713. else Decimal("0")
  1714. )
  1715. result.append(
  1716. {
  1717. "period": period,
  1718. "totalCount": len(subset),
  1719. "totalAmount": float(total_amount),
  1720. "receivedAmount": float(received_amount),
  1721. "receivedRate": float(received_rate),
  1722. }
  1723. )
  1724. return result
  1725. def query_expiring(
  1726. db: Session,
  1727. tenant_no: str,
  1728. *,
  1729. days: int = 30,
  1730. user_info=None,
  1731. ) -> List[Dict[str, Any]]:
  1732. if not days or days <= 0:
  1733. days = 30
  1734. today = date.today()
  1735. end_date = today + timedelta(days=days)
  1736. rows = (
  1737. db.query(CrmContract)
  1738. .filter(
  1739. CrmContract.tenant_no == tenant_no,
  1740. CrmContract.del_flag == 0,
  1741. CrmContract.status == "executing",
  1742. CrmContract.end_date.isnot(None),
  1743. CrmContract.end_date <= end_date,
  1744. CrmContract.end_date >= today,
  1745. )
  1746. .order_by(CrmContract.end_date.asc())
  1747. .all()
  1748. )
  1749. return [_row_to_dict(r) for r in rows]
  1750. def _quote_products_to_contract_products(quote_products: List[dict]) -> List[dict]:
  1751. rows = []
  1752. for item in quote_products:
  1753. rows.append(
  1754. {
  1755. "productId": item.get("productId") or item.get("product_id"),
  1756. "productName": item.get("productName") or item.get("product_name"),
  1757. "brandMode": item.get("brandMode") or item.get("brand_mode"),
  1758. "brandId": item.get("brandId") or item.get("brand_id"),
  1759. "brandName": item.get("brandName") or item.get("brand_name"),
  1760. "productNo": item.get("productNo") or item.get("product_no"),
  1761. "categoryId": item.get("categoryId") or item.get("category_id"),
  1762. "categoryName": item.get("categoryName") or item.get("category_name"),
  1763. "model": item.get("model"),
  1764. "unit": item.get("unit"),
  1765. "quantity": item.get("quantity"),
  1766. "price": item.get("price"),
  1767. "discount": item.get("discount"),
  1768. "taxRate": item.get("taxRate") or item.get("tax_rate"),
  1769. "taxAmount": item.get("taxAmount") or item.get("tax_amount"),
  1770. "subtotal": item.get("subtotal"),
  1771. "packageSpec": item.get("packageSpec") or item.get("package_spec"),
  1772. "deliveryMethod": item.get("deliveryMethod") or item.get("delivery_method"),
  1773. "description": item.get("description"),
  1774. "sort": item.get("sort"),
  1775. "remark": item.get("remark"),
  1776. }
  1777. )
  1778. return rows
  1779. def create_from_quote(
  1780. db: Session,
  1781. quote_id: str,
  1782. *,
  1783. tenant_no: str,
  1784. data: dict,
  1785. user_id: str = None,
  1786. dept_id: str = "",
  1787. user_info=None,
  1788. ) -> str:
  1789. """Java: createFromQuote — 返回合同 id"""
  1790. quote = get_quote(db, quote_id, tenant_no=tenant_no)
  1791. if not quote:
  1792. raise ValueError("报价单不存在")
  1793. payload = dict(data)
  1794. payload.setdefault("quoteId", quote_id)
  1795. payload.setdefault("customerId", quote.customer_id)
  1796. if quote.opportunity_id:
  1797. payload.setdefault("opportunityId", quote.opportunity_id)
  1798. if payload.get("amount") is None:
  1799. payload["amount"] = float(quote.final_amount or quote.total_amount or 0)
  1800. if payload.get("freight") is None:
  1801. payload["freight"] = float(quote.freight or 0)
  1802. if payload.get("barrelDeposit") is None and payload.get("barrel_deposit") is None:
  1803. payload["barrelDeposit"] = float(getattr(quote, "barrel_deposit", None) or 0)
  1804. if not payload.get("ownerUserId"):
  1805. payload["ownerUserId"] = quote.owner_user_id or user_id or ""
  1806. if quote.supplier_id and not payload.get("supplierId"):
  1807. payload["supplierId"] = quote.supplier_id
  1808. products = _get_field(payload, "products", "productList")
  1809. if not products:
  1810. quote_products = list_quote_products(db, quote_id, tenant_no=tenant_no)
  1811. payload["products"] = _quote_products_to_contract_products(quote_products)
  1812. if not payload.get("contractType"):
  1813. qtype = (quote.quote_type or "sales").strip()
  1814. payload["contractType"] = "purchase" if qtype == "purchase" else "sale"
  1815. detail = create_contract(
  1816. db,
  1817. tenant_no=tenant_no,
  1818. data=payload,
  1819. user_id=user_id,
  1820. dept_id=dept_id,
  1821. )
  1822. contract_id = detail["id"]
  1823. quote_row = (
  1824. db.query(CrmQuote)
  1825. .filter(CrmQuote.id == quote_id, CrmQuote.tenant_no == tenant_no, CrmQuote.del_flag == 0)
  1826. .first()
  1827. )
  1828. if quote_row:
  1829. quote_row.status = "converted"
  1830. quote_row.contract_id = contract_id
  1831. quote_row.update_time = datetime.now()
  1832. db.commit()
  1833. return contract_id
  1834. def renew_contract(
  1835. db: Session,
  1836. parent_contract_id: str,
  1837. *,
  1838. tenant_no: str,
  1839. data: dict,
  1840. user_id: str = None,
  1841. dept_id: str = "",
  1842. user_info=None,
  1843. ) -> str:
  1844. """Java: renewContract — 基础续签"""
  1845. parent = get_contract_row(db, parent_contract_id, tenant_no=tenant_no)
  1846. if not parent:
  1847. raise ValueError("原合同不存在")
  1848. renewal_count = (parent.renewal_count or 0) + 1
  1849. payload = dict(data)
  1850. payload.setdefault("customerId", parent.customer_id)
  1851. payload.setdefault("contactId", parent.contact_id)
  1852. payload.setdefault("contractType", parent.contract_type)
  1853. payload.setdefault("ownerUserId", parent.owner_user_id)
  1854. payload.setdefault("supplierId", payload.get("supplierId") or parent.supplier_id)
  1855. payload["parentContractId"] = parent_contract_id
  1856. payload["renewalCount"] = renewal_count
  1857. payload["contractNature"] = "renewal"
  1858. if not payload.get("contractName"):
  1859. payload["contractName"] = f"{parent.contract_name or '合同'}-续签{renewal_count}"
  1860. payload.setdefault("partyA", parent.party_a)
  1861. payload.setdefault("partyAAddress", parent.party_a_address)
  1862. payload.setdefault("partyAContact", parent.party_a_contact)
  1863. payload.setdefault("partyAMobile", parent.party_a_mobile)
  1864. payload.setdefault("partyB", parent.party_b)
  1865. payload.setdefault("partyBAddress", parent.party_b_address)
  1866. payload.setdefault("partyBContact", parent.party_b_contact)
  1867. payload.setdefault("partyBMobile", parent.party_b_mobile)
  1868. payload.setdefault("paymentTerms", payload.get("paymentTerms") or parent.payment_terms)
  1869. payload.setdefault("deliveryTerms", payload.get("deliveryTerms") or parent.delivery_terms)
  1870. payload.setdefault("contractTerms", payload.get("contractTerms") or parent.contract_terms)
  1871. if payload.get("amount") is None:
  1872. payload["amount"] = float(parent.amount or 0)
  1873. if payload.get("taxRate") is None and parent.tax_rate is not None:
  1874. payload["taxRate"] = float(parent.tax_rate)
  1875. products = _get_field(payload, "products", "productList")
  1876. if not products:
  1877. payload["products"] = list_contract_products(db, parent_contract_id, tenant_no=tenant_no)
  1878. detail = create_contract(db, tenant_no=tenant_no, data=payload, user_id=user_id, dept_id=dept_id)
  1879. return detail["id"]
  1880. def export_contracts(
  1881. db: Session,
  1882. tenant_no: str,
  1883. *,
  1884. filters: dict = None,
  1885. user_info=None,
  1886. ) -> List[Dict[str, Any]]:
  1887. """Java: queryList for export"""
  1888. q = db.query(CrmContract)
  1889. q = _build_contract_filters(db, q, filters or {}, tenant_no=tenant_no)
  1890. rows = q.limit(10000).all()
  1891. return [_row_to_dict(r) for r in rows]
  1892. # --- 子模块:变更 / 模板(列表与详情) ---
  1893. def _change_row_to_dict(row: CrmContractChange) -> Dict[str, Any]:
  1894. return {
  1895. "id": row.id,
  1896. "contractId": row.contract_id or "",
  1897. "contractNo": row.contract_no or "",
  1898. "changeType": row.change_type or "",
  1899. "changeReason": row.change_reason or "",
  1900. "changeContent": row.change_content or "",
  1901. "oldValue": row.old_value or "",
  1902. "newValue": row.new_value or "",
  1903. "changeAmount": float(row.change_amount) if row.change_amount is not None else None,
  1904. "approvalStatus": row.approval_status or "",
  1905. "approverId": row.approver_id or "",
  1906. "approverName": row.approver_name or "",
  1907. "approvalTime": row.approval_time.strftime(_FMT) if row.approval_time else "",
  1908. "approvalOpinion": row.approval_opinion or "",
  1909. "attachmentFiles": row.attachment_files or "",
  1910. "remark": row.remark or "",
  1911. "createTime": row.create_time.strftime(_FMT) if row.create_time else "",
  1912. }
  1913. def list_contract_changes(
  1914. db: Session,
  1915. tenant_no: str,
  1916. *,
  1917. page: int = 1,
  1918. page_size: int = 10,
  1919. filters: dict = None,
  1920. user_info=None,
  1921. ) -> Tuple[List[Dict[str, Any]], int]:
  1922. q = db.query(CrmContractChange).filter(
  1923. CrmContractChange.tenant_no == tenant_no,
  1924. CrmContractChange.del_flag == 0,
  1925. )
  1926. if user_info:
  1927. q = apply_crm_create_by_scope(q, CrmContractChange, user_info, db, tenant_no)
  1928. filters = filters or {}
  1929. contract_id = (filters.get("contractId") or filters.get("contract_id") or "").strip()
  1930. if contract_id:
  1931. q = q.filter(CrmContractChange.contract_id == contract_id)
  1932. contract_no = (filters.get("contractNo") or filters.get("contract_no") or "").strip()
  1933. if contract_no:
  1934. q = q.filter(CrmContractChange.contract_no.like(f"%{contract_no}%"))
  1935. total = q.order_by(None).with_entities(func.count(CrmContractChange.id)).scalar() or 0
  1936. page = max(1, page)
  1937. page_size = min(max(1, page_size), 500)
  1938. rows = q.order_by(CrmContractChange.create_time.desc()).offset((page - 1) * page_size).limit(page_size).all()
  1939. return [_change_row_to_dict(r) for r in rows], int(total)
  1940. def get_contract_change_detail(
  1941. db: Session,
  1942. change_id: str,
  1943. *,
  1944. tenant_no: str,
  1945. user_info=None,
  1946. ) -> Dict[str, Any]:
  1947. row = (
  1948. db.query(CrmContractChange)
  1949. .filter(
  1950. CrmContractChange.id == change_id,
  1951. CrmContractChange.tenant_no == tenant_no,
  1952. CrmContractChange.del_flag == 0,
  1953. )
  1954. .first()
  1955. )
  1956. if not row:
  1957. raise ValueError("合同变更记录不存在")
  1958. ensure_crm_create_by_row_in_scope(
  1959. db, row, user_info, tenant_no, message="无权访问该合同变更"
  1960. )
  1961. return _change_row_to_dict(row)
  1962. def _template_row_to_dict(row: CrmContractTemplate) -> Dict[str, Any]:
  1963. return {
  1964. "id": row.id,
  1965. "templateNo": row.template_no or "",
  1966. "templateName": row.template_name or "",
  1967. "contractType": row.contract_type or "",
  1968. "templateContent": row.template_content or "",
  1969. "paymentTerms": row.payment_terms or "",
  1970. "deliveryTerms": row.delivery_terms or "",
  1971. "contractTerms": row.contract_terms or "",
  1972. "partyB": row.party_b or "",
  1973. "partyBAddress": row.party_b_address or "",
  1974. "partyBContact": row.party_b_contact or "",
  1975. "partyBMobile": row.party_b_mobile or "",
  1976. "defaultCurrency": row.default_currency or "CNY",
  1977. "defaultTaxRate": float(row.default_tax_rate) if row.default_tax_rate is not None else 6.0,
  1978. "defaultPeriod": row.default_period,
  1979. "isActive": row.is_active if row.is_active is not None else 1,
  1980. "usageCount": row.usage_count if row.usage_count is not None else 0,
  1981. "sort": row.sort if row.sort is not None else 0,
  1982. "remark": row.remark or "",
  1983. "createTime": row.create_time.strftime(_FMT) if row.create_time else "",
  1984. }
  1985. def list_contract_templates(
  1986. db: Session,
  1987. tenant_no: str,
  1988. *,
  1989. page: int = 1,
  1990. page_size: int = 10,
  1991. filters: dict = None,
  1992. user_info=None,
  1993. ) -> Tuple[List[Dict[str, Any]], int]:
  1994. q = db.query(CrmContractTemplate).filter(
  1995. CrmContractTemplate.tenant_no == tenant_no,
  1996. CrmContractTemplate.del_flag == 0,
  1997. )
  1998. if user_info:
  1999. q = apply_crm_create_by_scope(q, CrmContractTemplate, user_info, db, tenant_no)
  2000. filters = filters or {}
  2001. template_no = (filters.get("templateNo") or filters.get("template_no") or "").strip()
  2002. if template_no:
  2003. q = q.filter(CrmContractTemplate.template_no.like(f"%{template_no}%"))
  2004. template_name = (filters.get("templateName") or filters.get("template_name") or "").strip()
  2005. if template_name:
  2006. q = q.filter(CrmContractTemplate.template_name.like(f"%{template_name}%"))
  2007. if filters.get("isActive") is not None:
  2008. q = q.filter(CrmContractTemplate.is_active == int(filters["isActive"]))
  2009. total = q.order_by(None).with_entities(func.count(CrmContractTemplate.id)).scalar() or 0
  2010. page = max(1, page)
  2011. page_size = min(max(1, page_size), 500)
  2012. rows = q.order_by(CrmContractTemplate.sort.asc(), CrmContractTemplate.create_time.desc()).offset(
  2013. (page - 1) * page_size
  2014. ).limit(page_size).all()
  2015. return [_template_row_to_dict(r) for r in rows], int(total)
  2016. def get_contract_template_detail(
  2017. db: Session,
  2018. template_id: str,
  2019. *,
  2020. tenant_no: str,
  2021. ) -> Dict[str, Any]:
  2022. row = (
  2023. db.query(CrmContractTemplate)
  2024. .filter(
  2025. CrmContractTemplate.id == template_id,
  2026. CrmContractTemplate.tenant_no == tenant_no,
  2027. CrmContractTemplate.del_flag == 0,
  2028. )
  2029. .first()
  2030. )
  2031. if not row:
  2032. raise ValueError("合同模板不存在")
  2033. return _template_row_to_dict(row)
  2034. def _opportunity_products_to_contract_products(items: List[dict]) -> List[dict]:
  2035. rows = []
  2036. for item in items:
  2037. rows.append(
  2038. {
  2039. "productId": item.get("productId") or item.get("product_id"),
  2040. "productName": item.get("productName") or item.get("product_name"),
  2041. "productNo": item.get("productNo") or item.get("product_no") or item.get("productCode"),
  2042. "categoryId": item.get("categoryId") or item.get("category_id"),
  2043. "categoryName": item.get("categoryName") or item.get("category_name"),
  2044. "model": item.get("model"),
  2045. "unit": item.get("unit"),
  2046. "quantity": item.get("quantity"),
  2047. "price": item.get("price"),
  2048. "discount": item.get("discount"),
  2049. "taxRate": item.get("taxRate") or item.get("tax_rate"),
  2050. "subtotal": item.get("subtotal"),
  2051. "description": item.get("description"),
  2052. "sort": item.get("sort") or item.get("sortOrder"),
  2053. "remark": item.get("remark"),
  2054. }
  2055. )
  2056. return rows
  2057. def create_from_opportunity(
  2058. db: Session,
  2059. opportunity_id: str,
  2060. *,
  2061. tenant_no: str,
  2062. data: dict,
  2063. user_id: str = None,
  2064. dept_id: str = "",
  2065. user_info=None,
  2066. ) -> str:
  2067. """Java: createFromOpportunity — 返回合同 id"""
  2068. opp_row = (
  2069. db.query(CrmOpportunity)
  2070. .filter(
  2071. CrmOpportunity.id == opportunity_id,
  2072. CrmOpportunity.tenant_no == tenant_no,
  2073. CrmOpportunity.del_flag == 0,
  2074. )
  2075. .first()
  2076. )
  2077. if not opp_row:
  2078. raise ValueError("商机不存在")
  2079. payload = dict(data)
  2080. payload.setdefault("opportunityId", opportunity_id)
  2081. payload.setdefault("customerId", opp_row.customer_id)
  2082. if payload.get("amount") is None:
  2083. payload["amount"] = float(opp_row.amount or 0)
  2084. if not payload.get("ownerUserId"):
  2085. payload["ownerUserId"] = opp_row.owner_user_id or user_id or ""
  2086. products = _get_field(payload, "products", "productList")
  2087. if not products:
  2088. from app.crud.crm.opportunity_product import list_products_by_opportunity
  2089. opp_products = list_products_by_opportunity(db, opportunity_id, tenant_no=tenant_no)
  2090. payload["products"] = _opportunity_products_to_contract_products(opp_products)
  2091. detail = create_contract(
  2092. db,
  2093. tenant_no=tenant_no,
  2094. data=payload,
  2095. user_id=user_id,
  2096. dept_id=dept_id,
  2097. )
  2098. contract_id = detail["id"]
  2099. opp_row.stage = "won"
  2100. opp_row.update_time = datetime.now()
  2101. db.commit()
  2102. return contract_id
  2103. def sign_contract(
  2104. db: Session,
  2105. contract_id: str,
  2106. *,
  2107. tenant_no: str,
  2108. actual_sign_date: str,
  2109. contract_file: str,
  2110. remark: str = "",
  2111. user_id: str = None,
  2112. user_info=None,
  2113. ) -> bool:
  2114. """Java: signContract"""
  2115. entity = _get_contract_row_in_scope(db, contract_id, tenant_no=tenant_no, user_info=user_info)
  2116. if not entity:
  2117. raise ValueError("合同不存在")
  2118. if entity.status != "approved":
  2119. raise ValueError("只有审批通过的合同才能签订")
  2120. entity.actual_sign_date = _parse_optional_date(actual_sign_date)
  2121. entity.contract_file = (contract_file or "").strip()
  2122. entity.status = "executing"
  2123. entity.performance_status = "normal"
  2124. entity.performance_rate = Decimal("0")
  2125. if remark:
  2126. entity.remark = remark
  2127. entity.update_by = user_id
  2128. entity.update_time = datetime.now()
  2129. db.commit()
  2130. return True
  2131. def batch_assign_owner(
  2132. db: Session,
  2133. contract_ids: List[str],
  2134. *,
  2135. tenant_no: str,
  2136. owner_user_id: str,
  2137. remark: str = "",
  2138. user_id: str = None,
  2139. user_info=None,
  2140. ) -> int:
  2141. """Java: batchAssignOwner"""
  2142. if not contract_ids:
  2143. raise ValueError("合同ID列表不能为空")
  2144. owner_id = (owner_user_id or "").strip()
  2145. if not owner_id:
  2146. raise ValueError("负责人ID不能为空")
  2147. success = 0
  2148. owner_name = _resolve_user_display_name(db, owner_id)
  2149. for cid in contract_ids:
  2150. entity = _get_contract_row_in_scope(db, cid, tenant_no=tenant_no, user_info=user_info)
  2151. if not entity:
  2152. continue
  2153. entity.owner_user_id = owner_id
  2154. entity.owner_user_name = owner_name
  2155. if remark:
  2156. entity.remark = remark
  2157. entity.update_by = user_id
  2158. entity.update_time = datetime.now()
  2159. success += 1
  2160. db.commit()
  2161. return success
  2162. def download_contract_pdf(
  2163. db: Session,
  2164. contract_id: str,
  2165. *,
  2166. tenant_no: str,
  2167. user_info=None,
  2168. ) -> str:
  2169. """Java: downloadContractPdf — 返回合同文件 URL/路径"""
  2170. detail = get_contract_detail(db, contract_id, tenant_no=tenant_no)
  2171. if not detail:
  2172. raise ValueError("合同不存在")
  2173. file_path = (detail.get("contractFile") or "").strip()
  2174. if not file_path:
  2175. raise ValueError("合同PDF文件不存在")
  2176. return file_path
  2177. def generate_template_no(db: Session, tenant_no: str) -> str:
  2178. """Java: generateTemplateNo — TMPL{yyyyMMdd}{4位序号}"""
  2179. date_str = datetime.now().strftime("%Y%m%d")
  2180. prefix = f"TMPL{date_str}"
  2181. last = (
  2182. db.query(CrmContractTemplate)
  2183. .filter(
  2184. CrmContractTemplate.tenant_no == tenant_no,
  2185. CrmContractTemplate.del_flag == 0,
  2186. CrmContractTemplate.template_no.like(f"{prefix}%"),
  2187. )
  2188. .order_by(CrmContractTemplate.template_no.desc())
  2189. .first()
  2190. )
  2191. sequence = 1
  2192. if last and last.template_no and len(last.template_no) >= len(prefix) + 4:
  2193. try:
  2194. sequence = int(last.template_no[len(prefix) :]) + 1
  2195. except ValueError:
  2196. sequence = 1
  2197. for retry in range(10):
  2198. candidate = f"{prefix}{sequence + retry:04d}"
  2199. exists = (
  2200. db.query(CrmContractTemplate.id)
  2201. .filter(CrmContractTemplate.template_no == candidate, CrmContractTemplate.del_flag == 0)
  2202. .first()
  2203. )
  2204. if not exists:
  2205. return candidate
  2206. raise ValueError("生成模板编号失败,请稍后重试")
  2207. def _get_change_row(db: Session, change_id: str, *, tenant_no: str) -> Optional[CrmContractChange]:
  2208. return (
  2209. db.query(CrmContractChange)
  2210. .filter(
  2211. CrmContractChange.id == change_id,
  2212. CrmContractChange.tenant_no == tenant_no,
  2213. CrmContractChange.del_flag == 0,
  2214. )
  2215. .first()
  2216. )
  2217. def _enrich_change_rows(db: Session, rows: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
  2218. contract_ids = {row.get("contractId") for row in rows if row.get("contractId")}
  2219. if not contract_ids:
  2220. return rows
  2221. contracts = (
  2222. db.query(CrmContract.id, CrmContract.contract_name)
  2223. .filter(CrmContract.id.in_(contract_ids), CrmContract.del_flag == 0)
  2224. .all()
  2225. )
  2226. name_map = {item.id: item.contract_name or "" for item in contracts}
  2227. for row in rows:
  2228. row["contractName"] = name_map.get(row.get("contractId"), "")
  2229. return rows
  2230. def create_contract_change(
  2231. db: Session,
  2232. *,
  2233. tenant_no: str,
  2234. data: dict,
  2235. user_id: str = None,
  2236. dept_id: str = "",
  2237. ) -> Dict[str, Any]:
  2238. contract_id = (_get_field(data, "contract_id", "contractId") or "").strip()
  2239. if not contract_id:
  2240. raise ValueError("合同ID不能为空")
  2241. contract = get_contract_row(db, contract_id, tenant_no=tenant_no)
  2242. if not contract:
  2243. raise ValueError("合同不存在")
  2244. change_type = (_get_field(data, "change_type", "changeType") or "").strip()
  2245. change_reason = (_get_field(data, "change_reason", "changeReason") or "").strip()
  2246. if not change_type:
  2247. raise ValueError("变更类型不能为空")
  2248. if not change_reason:
  2249. raise ValueError("变更原因不能为空")
  2250. now = datetime.now()
  2251. entity = CrmContractChange(
  2252. id=generate_uuid(),
  2253. contract_id=contract_id,
  2254. contract_no=(_get_field(data, "contract_no", "contractNo") or contract.contract_no or "").strip(),
  2255. change_type=change_type,
  2256. change_reason=change_reason,
  2257. change_content=_get_field(data, "change_content", "changeContent") or "",
  2258. old_value=_get_field(data, "old_value", "oldValue") or "",
  2259. new_value=_get_field(data, "new_value", "newValue") or "",
  2260. change_amount=_decimal_value(_get_field(data, "change_amount", "changeAmount"))
  2261. if _get_field(data, "change_amount", "changeAmount") is not None
  2262. else None,
  2263. approval_status="pending",
  2264. attachment_files=_get_field(data, "attachment_files", "attachmentFiles") or "",
  2265. remark=_get_field(data, "remark") or "",
  2266. tenant_no=tenant_no,
  2267. create_by=user_id,
  2268. create_dept_id=dept_id or "",
  2269. create_time=now,
  2270. update_by=user_id,
  2271. update_time=now,
  2272. del_flag=0,
  2273. )
  2274. db.add(entity)
  2275. db.commit()
  2276. return get_contract_change_detail(db, entity.id, tenant_no=tenant_no)
  2277. def update_contract_change(
  2278. db: Session,
  2279. change_id: str,
  2280. *,
  2281. tenant_no: str,
  2282. data: dict,
  2283. user_id: str = None,
  2284. user_info=None,
  2285. ) -> Dict[str, Any]:
  2286. entity = _get_change_row(db, change_id, tenant_no=tenant_no)
  2287. if not entity:
  2288. raise ValueError("合同变更记录不存在")
  2289. ensure_crm_create_by_row_in_scope(
  2290. db, entity, user_info, tenant_no, message="无权访问该合同变更"
  2291. )
  2292. if entity.approval_status != "pending":
  2293. raise ValueError("只能修改待审批状态的变更记录")
  2294. for keys, attr in (
  2295. (("change_type", "changeType"), "change_type"),
  2296. (("change_reason", "changeReason"), "change_reason"),
  2297. (("change_content", "changeContent"), "change_content"),
  2298. (("old_value", "oldValue"), "old_value"),
  2299. (("new_value", "newValue"), "new_value"),
  2300. (("attachment_files", "attachmentFiles"), "attachment_files"),
  2301. (("remark",), "remark"),
  2302. ):
  2303. val = _get_field(data, *keys)
  2304. if val is not None:
  2305. setattr(entity, attr, val)
  2306. if _get_field(data, "change_amount", "changeAmount") is not None:
  2307. entity.change_amount = _decimal_value(_get_field(data, "change_amount", "changeAmount"))
  2308. entity.update_by = user_id
  2309. entity.update_time = datetime.now()
  2310. db.commit()
  2311. return get_contract_change_detail(db, change_id, tenant_no=tenant_no)
  2312. def soft_delete_contract_changes(
  2313. db: Session,
  2314. change_ids: List[str],
  2315. *,
  2316. tenant_no: str,
  2317. validate: bool = True,
  2318. user_info=None,
  2319. ) -> int:
  2320. count = 0
  2321. for cid in change_ids:
  2322. entity = _get_change_row(db, cid, tenant_no=tenant_no)
  2323. if not entity:
  2324. continue
  2325. ensure_crm_create_by_row_in_scope(
  2326. db, entity, user_info, tenant_no, message="无权访问该合同变更"
  2327. )
  2328. if validate and entity.approval_status != "pending":
  2329. raise ValueError("只能删除待审批状态的变更记录")
  2330. assert_row_deletable_by_creator(entity, user_info)
  2331. entity.del_flag = 1
  2332. entity.update_time = datetime.now()
  2333. count += 1
  2334. db.commit()
  2335. return count
  2336. def submit_change_approval(
  2337. db: Session,
  2338. change_id: str,
  2339. *,
  2340. tenant_no: str,
  2341. approver_ids: List[str] = None,
  2342. remark: str = "",
  2343. user_id: str = None,
  2344. ) -> bool:
  2345. """Java Controller TODO — 保持 pending,记录备注"""
  2346. entity = _get_change_row(db, change_id, tenant_no=tenant_no)
  2347. if not entity:
  2348. raise ValueError("变更记录不存在")
  2349. if entity.approval_status != "pending":
  2350. raise ValueError("只能提交待审批状态的变更记录")
  2351. if remark:
  2352. entity.remark = remark
  2353. entity.update_by = user_id
  2354. entity.update_time = datetime.now()
  2355. db.commit()
  2356. return True
  2357. def withdraw_change(db: Session, change_id: str, *, tenant_no: str, user_id: str = None) -> bool:
  2358. entity = _get_change_row(db, change_id, tenant_no=tenant_no)
  2359. if not entity:
  2360. raise ValueError("变更记录不存在")
  2361. if entity.approval_status != "pending":
  2362. raise ValueError("只能撤回待审批状态的变更记录")
  2363. entity.del_flag = 1
  2364. entity.update_by = user_id
  2365. entity.update_time = datetime.now()
  2366. db.commit()
  2367. return True
  2368. def execute_change(db: Session, change_id: str, *, tenant_no: str, user_id: str = None) -> bool:
  2369. entity = _get_change_row(db, change_id, tenant_no=tenant_no)
  2370. if not entity:
  2371. raise ValueError("变更记录不存在")
  2372. if entity.approval_status != "approved":
  2373. raise ValueError("只能执行已通过审批的变更")
  2374. entity.update_by = user_id
  2375. entity.update_time = datetime.now()
  2376. db.commit()
  2377. return True
  2378. def export_contract_changes(
  2379. db: Session,
  2380. tenant_no: str,
  2381. *,
  2382. filters: dict = None,
  2383. ) -> List[Dict[str, Any]]:
  2384. rows, _ = list_contract_changes(
  2385. db,
  2386. tenant_no,
  2387. page=1,
  2388. page_size=10000,
  2389. filters=filters or {},
  2390. )
  2391. return _enrich_change_rows(db, rows)
  2392. def create_contract_template(
  2393. db: Session,
  2394. *,
  2395. tenant_no: str,
  2396. data: dict,
  2397. user_id: str = None,
  2398. dept_id: str = "",
  2399. ) -> Dict[str, Any]:
  2400. template_name = (_get_field(data, "template_name", "templateName") or "").strip()
  2401. if not template_name:
  2402. raise ValueError("模板名称不能为空")
  2403. template_no = (_get_field(data, "template_no", "templateNo") or "").strip()
  2404. if not template_no:
  2405. template_no = generate_template_no(db, tenant_no)
  2406. now = datetime.now()
  2407. entity = CrmContractTemplate(
  2408. id=generate_uuid(),
  2409. template_no=template_no,
  2410. template_name=template_name,
  2411. contract_type=_get_field(data, "contract_type", "contractType") or "",
  2412. template_content=_get_field(data, "template_content", "templateContent") or "",
  2413. payment_terms=_get_field(data, "payment_terms", "paymentTerms") or "",
  2414. delivery_terms=_get_field(data, "delivery_terms", "deliveryTerms") or "",
  2415. contract_terms=_get_field(data, "contract_terms", "contractTerms") or "",
  2416. party_b=_get_field(data, "party_b", "partyB") or "",
  2417. party_b_address=_get_field(data, "party_b_address", "partyBAddress") or "",
  2418. party_b_contact=_get_field(data, "party_b_contact", "partyBContact") or "",
  2419. party_b_mobile=_get_field(data, "party_b_mobile", "partyBMobile") or "",
  2420. default_currency=_get_field(data, "default_currency", "defaultCurrency") or "CNY",
  2421. default_tax_rate=_decimal_value(_get_field(data, "default_tax_rate", "defaultTaxRate"), Decimal("6.00")),
  2422. default_period=int(_get_field(data, "default_period", "defaultPeriod") or 12),
  2423. is_active=int(_get_field(data, "is_active", "isActive") if _get_field(data, "is_active", "isActive") is not None else 1),
  2424. usage_count=0,
  2425. sort=int(_get_field(data, "sort") or 0),
  2426. remark=_get_field(data, "remark") or "",
  2427. tenant_no=tenant_no,
  2428. create_by=user_id,
  2429. create_dept_id=dept_id or "",
  2430. create_time=now,
  2431. update_by=user_id,
  2432. update_time=now,
  2433. del_flag=0,
  2434. )
  2435. db.add(entity)
  2436. db.commit()
  2437. return get_contract_template_detail(db, entity.id, tenant_no=tenant_no)
  2438. def update_contract_template(
  2439. db: Session,
  2440. template_id: str,
  2441. *,
  2442. tenant_no: str,
  2443. data: dict,
  2444. user_id: str = None,
  2445. user_info=None,
  2446. ) -> Dict[str, Any]:
  2447. entity = (
  2448. db.query(CrmContractTemplate)
  2449. .filter(
  2450. CrmContractTemplate.id == template_id,
  2451. CrmContractTemplate.tenant_no == tenant_no,
  2452. CrmContractTemplate.del_flag == 0,
  2453. )
  2454. .first()
  2455. )
  2456. if not entity:
  2457. raise ValueError("合同模板不存在")
  2458. ensure_crm_create_by_row_in_scope(
  2459. db, entity, user_info, tenant_no, message="无权访问该合同模板"
  2460. )
  2461. field_map = (
  2462. (("template_no", "templateNo"), "template_no"),
  2463. (("template_name", "templateName"), "template_name"),
  2464. (("contract_type", "contractType"), "contract_type"),
  2465. (("template_content", "templateContent"), "template_content"),
  2466. (("payment_terms", "paymentTerms"), "payment_terms"),
  2467. (("delivery_terms", "deliveryTerms"), "delivery_terms"),
  2468. (("contract_terms", "contractTerms"), "contract_terms"),
  2469. (("party_b", "partyB"), "party_b"),
  2470. (("party_b_address", "partyBAddress"), "party_b_address"),
  2471. (("party_b_contact", "partyBContact"), "party_b_contact"),
  2472. (("party_b_mobile", "partyBMobile"), "party_b_mobile"),
  2473. (("default_currency", "defaultCurrency"), "default_currency"),
  2474. (("remark",), "remark"),
  2475. )
  2476. for keys, attr in field_map:
  2477. val = _get_field(data, *keys)
  2478. if val is not None:
  2479. setattr(entity, attr, val)
  2480. if _get_field(data, "default_tax_rate", "defaultTaxRate") is not None:
  2481. entity.default_tax_rate = _decimal_value(_get_field(data, "default_tax_rate", "defaultTaxRate"))
  2482. if _get_field(data, "default_period", "defaultPeriod") is not None:
  2483. entity.default_period = int(_get_field(data, "default_period", "defaultPeriod"))
  2484. if _get_field(data, "is_active", "isActive") is not None:
  2485. entity.is_active = int(_get_field(data, "is_active", "isActive"))
  2486. if _get_field(data, "sort") is not None:
  2487. entity.sort = int(_get_field(data, "sort"))
  2488. entity.update_by = user_id
  2489. entity.update_time = datetime.now()
  2490. db.commit()
  2491. return get_contract_template_detail(db, template_id, tenant_no=tenant_no)
  2492. def soft_delete_contract_templates(
  2493. db: Session,
  2494. template_ids: List[str],
  2495. *,
  2496. tenant_no: str,
  2497. validate: bool = True,
  2498. user_info=None,
  2499. ) -> int:
  2500. count = 0
  2501. for tid in template_ids:
  2502. entity = (
  2503. db.query(CrmContractTemplate)
  2504. .filter(
  2505. CrmContractTemplate.id == tid,
  2506. CrmContractTemplate.tenant_no == tenant_no,
  2507. CrmContractTemplate.del_flag == 0,
  2508. )
  2509. .first()
  2510. )
  2511. if not entity:
  2512. continue
  2513. ensure_crm_create_by_row_in_scope(
  2514. db, entity, user_info, tenant_no, message="无权访问该合同模板"
  2515. )
  2516. if validate and (entity.usage_count or 0) > 0:
  2517. raise ValueError(f"模板【{entity.template_name}】已被使用,不能删除")
  2518. assert_row_deletable_by_creator(entity, user_info)
  2519. entity.del_flag = 1
  2520. entity.update_time = datetime.now()
  2521. count += 1
  2522. db.commit()
  2523. return count
  2524. def toggle_contract_template_active(
  2525. db: Session,
  2526. template_id: str,
  2527. *,
  2528. tenant_no: str,
  2529. is_active: int,
  2530. user_id: str = None,
  2531. ) -> bool:
  2532. entity = (
  2533. db.query(CrmContractTemplate)
  2534. .filter(
  2535. CrmContractTemplate.id == template_id,
  2536. CrmContractTemplate.tenant_no == tenant_no,
  2537. CrmContractTemplate.del_flag == 0,
  2538. )
  2539. .first()
  2540. )
  2541. if not entity:
  2542. raise ValueError("合同模板不存在")
  2543. entity.is_active = 1 if int(is_active) == 1 else 0
  2544. entity.update_by = user_id
  2545. entity.update_time = datetime.now()
  2546. db.commit()
  2547. return True
  2548. def export_contract_templates(
  2549. db: Session,
  2550. tenant_no: str,
  2551. *,
  2552. filters: dict = None,
  2553. ) -> List[Dict[str, Any]]:
  2554. rows, _ = list_contract_templates(
  2555. db,
  2556. tenant_no,
  2557. page=1,
  2558. page_size=10000,
  2559. filters=filters or {},
  2560. )
  2561. return rows