contract.py 101 KB

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