market_payment.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. """市场专员/地区经理移动端的催缴与按样本缴费服务。"""
  2. from __future__ import annotations
  3. from datetime import date, datetime, timedelta
  4. from decimal import Decimal
  5. from typing import Any, Dict, List, Optional, Tuple
  6. from fastapi import HTTPException
  7. from sqlalchemy import Integer, and_, case, cast, exists, func, or_, select
  8. from sqlalchemy.orm import Session, aliased
  9. from app.core.utils import parse_datetime
  10. from app.crud import protocol_sample_payment as payment_crud
  11. from app.models.models import (
  12. BizCellSampleType,
  13. BizCollectionProtocol,
  14. BizProtocolCollectionInfo,
  15. BizProtocolPartyCustomer,
  16. BizProtocolPaymentSchedule,
  17. BizProtocolPaymentTransfer,
  18. BizProtocolSample,
  19. BizProtocolSamplePayment,
  20. SysUser,
  21. )
  22. from app.services.market_field_scope import (
  23. MarketFieldContext,
  24. apply_cell_protocol_scope,
  25. )
  26. from app.services.payment_chase import (
  27. chase_period_money,
  28. is_chase_candidate,
  29. parse_due_date_ymd,
  30. )
  31. from app.services.sample_payment_progress import (
  32. compute_sample_payment_progress,
  33. is_schedule_effectively_cleared,
  34. )
  35. from app.services.market_support import (
  36. validate_attachment_refs,
  37. )
  38. def _current_dept_id(user_info: dict) -> str:
  39. return str(
  40. user_info.get('dept_id')
  41. or user_info.get('deptId')
  42. or user_info.get('region_id')
  43. or ''
  44. ).strip()
  45. def _fmt_time(value: Any) -> str:
  46. return value.strftime('%Y-%m-%d %H:%M:%S') if value else ''
  47. def _money(value: Any) -> Optional[str]:
  48. """以固定两位小数字符串输出,避免 JSON float 破坏 DECIMAL(18,2)。"""
  49. if value is None or value == '':
  50. return None
  51. return format(Decimal(str(value)).quantize(Decimal('0.01')), 'f')
  52. def _display_ymd(value: Any) -> str:
  53. text = str(value or '').strip()
  54. if len(text) == 8 and text.isdigit():
  55. return f'{text[:4]}-{text[4:6]}-{text[6:8]}'
  56. return text
  57. def _load_sample_meta(
  58. db: Session,
  59. payments: List[BizProtocolSamplePayment],
  60. tenant_no: str,
  61. ) -> Dict[str, Dict[str, Any]]:
  62. sample_codes = list({str(row.sample_code or '').strip() for row in payments if row.sample_code})
  63. if not sample_codes:
  64. return {}
  65. rows = (
  66. db.query(BizProtocolSample, BizCellSampleType)
  67. .outerjoin(
  68. BizCellSampleType,
  69. and_(
  70. BizCellSampleType.id == BizProtocolSample.sample_type_id,
  71. BizCellSampleType.tenant_no == tenant_no,
  72. BizCellSampleType.del_flag == 0,
  73. ),
  74. )
  75. .filter(
  76. BizProtocolSample.sample_code.in_(sample_codes),
  77. BizProtocolSample.tenant_no == tenant_no,
  78. BizProtocolSample.del_flag == 0,
  79. )
  80. .order_by(
  81. BizProtocolSample.update_time.desc(),
  82. BizProtocolSample.create_time.desc(),
  83. BizProtocolSample.id.desc(),
  84. )
  85. .all()
  86. )
  87. result: Dict[str, Dict[str, Any]] = {}
  88. for sample, sample_type in rows:
  89. original = sample.original_price
  90. current = sample.price
  91. discount = None
  92. if original is not None and current is not None and original > current:
  93. discount = original - current
  94. result.setdefault(
  95. sample.sample_code or '',
  96. {
  97. 'storageYears': sample.storage_years,
  98. 'sampleTypeName': sample_type.type_name if sample_type else '',
  99. 'discountAmount': _money(discount),
  100. },
  101. )
  102. return result
  103. def _transfer_dict(row: BizProtocolPaymentTransfer) -> Dict[str, Any]:
  104. return {
  105. 'id': row.id,
  106. 'scheduleId': row.schedule_id,
  107. 'samplePaymentId': row.sample_payment_id,
  108. 'collectionProtocolId': row.collection_protocol_id,
  109. 'sampleCode': row.sample_code or '',
  110. 'transferAmount': _money(row.transfer_amount),
  111. 'transferTime': _fmt_time(row.transfer_time),
  112. 'transferType': row.transfer_type or '',
  113. 'transferAttachments': row.transfer_attachments or '',
  114. 'payStatus': row.pay_status or '',
  115. 'remark': row.remark or '',
  116. 'financeRemark': row.finance_remark or '',
  117. 'createTime': _fmt_time(row.create_time),
  118. 'updateTime': _fmt_time(row.update_time),
  119. }
  120. def _period_dict(
  121. row: BizProtocolPaymentSchedule,
  122. transfers: List[BizProtocolPaymentTransfer],
  123. ) -> Dict[str, Any]:
  124. paid, arrears = chase_period_money(
  125. due_amount=row.due_amount,
  126. transfers=[
  127. {'transferAmount': item.transfer_amount, 'payStatus': item.pay_status}
  128. for item in transfers
  129. ],
  130. )
  131. schedule_status = row.schedule_status or ''
  132. if schedule_status != 'void' and is_schedule_effectively_cleared(
  133. {'scheduleStatus': schedule_status, 'dueAmount': row.due_amount},
  134. confirmed_paid=Decimal(str(paid or 0)),
  135. ):
  136. schedule_status = 'cleared'
  137. return {
  138. 'id': row.id,
  139. 'scheduleNo': row.schedule_no,
  140. 'dueAmount': _money(row.due_amount),
  141. 'dueDate': row.due_date or '',
  142. 'scheduleStatus': schedule_status,
  143. 'paidAmount': _money(paid),
  144. 'arrearsAmount': _money(arrears),
  145. 'transfers': [_transfer_dict(item) for item in transfers],
  146. }
  147. def _payment_dict(
  148. payment: BizProtocolSamplePayment,
  149. protocol: BizCollectionProtocol,
  150. party: Optional[BizProtocolPartyCustomer],
  151. schedules: List[BizProtocolPaymentSchedule],
  152. transfers_by_schedule: Dict[str, List[BizProtocolPaymentTransfer]],
  153. sample_meta: Optional[Dict[str, Any]] = None,
  154. ) -> Dict[str, Any]:
  155. meta = sample_meta or {}
  156. schedule_rows = [
  157. _period_dict(row, transfers_by_schedule.get(row.id, []))
  158. for row in schedules
  159. ]
  160. active_schedule_rows = [
  161. schedule_row
  162. for schedule_row, schedule in zip(schedule_rows, schedules)
  163. if (schedule.schedule_status or '') != 'void'
  164. ]
  165. transfers = [
  166. transfer
  167. for schedule in schedules
  168. for transfer in transfers_by_schedule.get(schedule.id, [])
  169. ]
  170. periods = payment_crud._build_periods_array(schedules, transfers)
  171. period_by_schedule: Dict[str, Dict[str, Any]] = {}
  172. for period in periods:
  173. if not period:
  174. continue
  175. schedule_id = str(period.get('scheduleId') or '')
  176. period['transfers'] = [
  177. _transfer_dict(row)
  178. for row in transfers_by_schedule.get(schedule_id, [])
  179. ]
  180. period_by_schedule[schedule_id] = period
  181. for schedule in schedule_rows:
  182. period = period_by_schedule.get(str(schedule.get('id') or ''), {})
  183. schedule['displayPaidAmount'] = _money(period.get('displayPaidAmount'))
  184. schedule['payDate'] = period.get('payDate') or ''
  185. progress_summary = compute_sample_payment_progress(
  186. schedules=[
  187. {
  188. 'id': row.id,
  189. 'scheduleStatus': row.schedule_status or '',
  190. 'dueAmount': row.due_amount,
  191. }
  192. for row in schedules
  193. ],
  194. transfers=[
  195. {
  196. 'scheduleId': row.schedule_id,
  197. 'payStatus': row.pay_status or '',
  198. 'transferAmount': row.transfer_amount,
  199. }
  200. for row in transfers
  201. ],
  202. )
  203. paid_total = progress_summary['paidAmount']
  204. remain_total = progress_summary['dueRemainAmount']
  205. receivable_total = sum(
  206. (
  207. Decimal(str(row.due_amount or '0'))
  208. for row in schedules
  209. if (row.schedule_status or '') != 'void'
  210. ),
  211. Decimal('0'),
  212. )
  213. progress_code = progress_summary['progressStatus']
  214. progress = {
  215. 'yjq': '已缴清',
  216. 'bfyj': '部分已缴',
  217. 'dfj': '待缴费',
  218. }[progress_code]
  219. return {
  220. 'id': payment.id,
  221. 'collectionProtocolId': protocol.id,
  222. 'protocolNo': protocol.protocol_no or '',
  223. 'protocolStatus': protocol.protocol_status or '',
  224. 'paymentModelVersion': int(getattr(protocol, 'payment_model_version', None) or 1),
  225. 'motherName': (party.mother_name if party else '') or '',
  226. 'motherPhone': (party.mother_phone if party else '') or '',
  227. 'sampleCode': payment.sample_code or '',
  228. 'payMode': payment.pay_mode or '',
  229. 'contractAmount': _money(payment.contract_amount),
  230. 'signDate': _display_ymd(getattr(protocol, 'register_date', None)),
  231. 'storageYears': meta.get('storageYears'),
  232. 'sampleTypeName': meta.get('sampleTypeName') or '',
  233. 'discountAmount': meta.get('discountAmount'),
  234. 'receivableAmount': _money(receivable_total),
  235. 'remark': payment.remark or '',
  236. 'paidAmount': _money(paid_total),
  237. 'remainAmount': _money(remain_total),
  238. 'dueRemainAmount': _money(remain_total),
  239. 'clearedScheduleCount': progress_summary['clearedScheduleCount'],
  240. 'activeScheduleCount': progress_summary['activeScheduleCount'],
  241. 'paymentProgress': progress,
  242. 'progressStatus': progress_code,
  243. 'periods': periods,
  244. 'schedules': schedule_rows,
  245. }
  246. def _scoped_payment_query(
  247. db: Session,
  248. *,
  249. ctx: MarketFieldContext,
  250. user_info: dict,
  251. v2_only: bool = False,
  252. ):
  253. protocol_conditions = [
  254. BizCollectionProtocol.id
  255. == BizProtocolSamplePayment.collection_protocol_id,
  256. BizCollectionProtocol.tenant_no == ctx.tenant_no,
  257. BizCollectionProtocol.del_flag == 0,
  258. ]
  259. if v2_only:
  260. protocol_conditions.append(BizCollectionProtocol.payment_model_version == 2)
  261. query = (
  262. db.query(
  263. BizProtocolSamplePayment,
  264. BizCollectionProtocol,
  265. BizProtocolPartyCustomer,
  266. )
  267. .join(
  268. BizCollectionProtocol,
  269. and_(*protocol_conditions),
  270. )
  271. .outerjoin(
  272. BizProtocolPartyCustomer,
  273. and_(
  274. BizProtocolPartyCustomer.collection_protocol_id
  275. == BizCollectionProtocol.id,
  276. BizProtocolPartyCustomer.tenant_no == ctx.tenant_no,
  277. BizProtocolPartyCustomer.del_flag == 0,
  278. ),
  279. )
  280. .filter(
  281. BizProtocolSamplePayment.tenant_no == ctx.tenant_no,
  282. BizProtocolSamplePayment.del_flag == 0,
  283. )
  284. )
  285. return apply_cell_protocol_scope(query, db, ctx, user_info=user_info)
  286. def _load_children(
  287. db: Session,
  288. payment_ids: List[str],
  289. tenant_no: str,
  290. ) -> Tuple[
  291. Dict[str, List[BizProtocolPaymentSchedule]],
  292. Dict[str, List[BizProtocolPaymentTransfer]],
  293. ]:
  294. if not payment_ids:
  295. return {}, {}
  296. schedules = (
  297. db.query(BizProtocolPaymentSchedule)
  298. .filter(
  299. BizProtocolPaymentSchedule.sample_payment_id.in_(payment_ids),
  300. BizProtocolPaymentSchedule.tenant_no == tenant_no,
  301. BizProtocolPaymentSchedule.del_flag == 0,
  302. )
  303. .order_by(
  304. BizProtocolPaymentSchedule.order_num.asc(),
  305. BizProtocolPaymentSchedule.schedule_no.asc(),
  306. )
  307. .all()
  308. )
  309. schedule_ids = [row.id for row in schedules]
  310. transfers = []
  311. if schedule_ids:
  312. transfers = (
  313. db.query(BizProtocolPaymentTransfer)
  314. .filter(
  315. BizProtocolPaymentTransfer.schedule_id.in_(schedule_ids),
  316. BizProtocolPaymentTransfer.tenant_no == tenant_no,
  317. BizProtocolPaymentTransfer.del_flag == 0,
  318. )
  319. .order_by(BizProtocolPaymentTransfer.create_time.asc())
  320. .all()
  321. )
  322. schedules_by_payment: Dict[str, List[BizProtocolPaymentSchedule]] = {}
  323. transfers_by_schedule: Dict[str, List[BizProtocolPaymentTransfer]] = {}
  324. for row in schedules:
  325. schedules_by_payment.setdefault(row.sample_payment_id, []).append(row)
  326. for row in transfers:
  327. transfers_by_schedule.setdefault(row.schedule_id, []).append(row)
  328. return schedules_by_payment, transfers_by_schedule
  329. def list_payments(
  330. db: Session,
  331. *,
  332. ctx: MarketFieldContext,
  333. user_info: dict,
  334. page: int = 1,
  335. page_size: int = 10,
  336. keyword: Optional[str] = None,
  337. pay_mode: Optional[str] = None,
  338. progress_status: Optional[str] = None,
  339. installment_due_date_start: Optional[str] = None,
  340. installment_due_date_end: Optional[str] = None,
  341. ) -> Tuple[List[Dict[str, Any]], int]:
  342. query = _scoped_payment_query(db, ctx=ctx, user_info=user_info)
  343. keyword_value = (keyword or '').strip()
  344. if keyword_value:
  345. like = f'%{keyword_value}%'
  346. query = query.filter(
  347. or_(
  348. BizCollectionProtocol.protocol_no.like(like),
  349. BizProtocolSamplePayment.sample_code.like(like),
  350. BizProtocolPartyCustomer.mother_name.like(like),
  351. BizProtocolPartyCustomer.mother_phone.like(like),
  352. )
  353. )
  354. mode = (pay_mode or '').strip()
  355. if mode:
  356. query = query.filter(BizProtocolSamplePayment.pay_mode == mode)
  357. def due_date_value(raw: Optional[str]) -> str:
  358. text = str(raw or '').strip().replace('-', '')
  359. if not text:
  360. return ''
  361. try:
  362. datetime.strptime(text, '%Y%m%d')
  363. except ValueError as exc:
  364. raise ValueError('应缴费时间格式无效,应为 YYYY-MM-DD') from exc
  365. return text
  366. due_start = due_date_value(installment_due_date_start)
  367. due_end = due_date_value(installment_due_date_end)
  368. if due_start or due_end:
  369. due_conditions = [
  370. BizProtocolPaymentSchedule.sample_payment_id
  371. == BizProtocolSamplePayment.id,
  372. BizProtocolPaymentSchedule.tenant_no == ctx.tenant_no,
  373. BizProtocolPaymentSchedule.del_flag == 0,
  374. BizProtocolPaymentSchedule.schedule_status != 'void',
  375. ]
  376. normalized_due = func.replace(BizProtocolPaymentSchedule.due_date, '-', '')
  377. if due_start:
  378. due_conditions.append(normalized_due >= due_start)
  379. if due_end:
  380. due_conditions.append(normalized_due <= due_end)
  381. query = query.filter(exists().where(and_(*due_conditions)))
  382. progress_code = str(progress_status or '').strip()
  383. if progress_code and progress_code not in {'dfj', 'bfyj', 'yjq'}:
  384. raise ValueError('缴费进度无效')
  385. if progress_code:
  386. schedule_count = (
  387. select(func.count(BizProtocolPaymentSchedule.id))
  388. .where(
  389. BizProtocolPaymentSchedule.sample_payment_id
  390. == BizProtocolSamplePayment.id,
  391. BizProtocolPaymentSchedule.tenant_no == ctx.tenant_no,
  392. BizProtocolPaymentSchedule.del_flag == 0,
  393. BizProtocolPaymentSchedule.schedule_status != 'void',
  394. )
  395. .correlate(BizProtocolSamplePayment)
  396. .scalar_subquery()
  397. )
  398. schedule_confirmed_paid = (
  399. select(
  400. func.coalesce(
  401. func.sum(BizProtocolPaymentTransfer.transfer_amount),
  402. 0,
  403. )
  404. )
  405. .where(
  406. BizProtocolPaymentTransfer.schedule_id
  407. == BizProtocolPaymentSchedule.id,
  408. BizProtocolPaymentTransfer.tenant_no == ctx.tenant_no,
  409. BizProtocolPaymentTransfer.del_flag == 0,
  410. BizProtocolPaymentTransfer.pay_status == 'yjf',
  411. )
  412. .correlate(BizProtocolPaymentSchedule)
  413. .scalar_subquery()
  414. )
  415. # 未清期:非 void,且非显式 cleared,且 yjf 合计仍小于应缴
  416. unsettled_exists = (
  417. exists()
  418. .where(
  419. BizProtocolPaymentSchedule.sample_payment_id
  420. == BizProtocolSamplePayment.id,
  421. BizProtocolPaymentSchedule.tenant_no == ctx.tenant_no,
  422. BizProtocolPaymentSchedule.del_flag == 0,
  423. BizProtocolPaymentSchedule.schedule_status != 'void',
  424. BizProtocolPaymentSchedule.schedule_status != 'cleared',
  425. schedule_confirmed_paid
  426. < func.coalesce(BizProtocolPaymentSchedule.due_amount, 0),
  427. )
  428. .correlate(BizProtocolSamplePayment)
  429. )
  430. confirmed_paid = (
  431. select(func.coalesce(func.sum(BizProtocolPaymentTransfer.transfer_amount), 0))
  432. .select_from(BizProtocolPaymentTransfer)
  433. .join(
  434. BizProtocolPaymentSchedule,
  435. and_(
  436. BizProtocolPaymentSchedule.id
  437. == BizProtocolPaymentTransfer.schedule_id,
  438. BizProtocolPaymentSchedule.tenant_no == ctx.tenant_no,
  439. BizProtocolPaymentSchedule.del_flag == 0,
  440. ),
  441. )
  442. .where(
  443. BizProtocolPaymentSchedule.sample_payment_id
  444. == BizProtocolSamplePayment.id,
  445. BizProtocolPaymentTransfer.tenant_no == ctx.tenant_no,
  446. BizProtocolPaymentTransfer.del_flag == 0,
  447. BizProtocolPaymentTransfer.pay_status == 'yjf',
  448. )
  449. .correlate(BizProtocolSamplePayment)
  450. .scalar_subquery()
  451. )
  452. is_cleared = and_(
  453. schedule_count > 0,
  454. ~unsettled_exists,
  455. )
  456. if progress_code == 'yjq':
  457. query = query.filter(is_cleared)
  458. elif progress_code == 'bfyj':
  459. query = query.filter(confirmed_paid > 0, ~is_cleared)
  460. else:
  461. query = query.filter(confirmed_paid <= 0, ~is_cleared)
  462. total = (
  463. query.order_by(None)
  464. .with_entities(func.count(BizProtocolSamplePayment.id))
  465. .scalar()
  466. or 0
  467. )
  468. page = max(1, page)
  469. page_size = min(max(1, page_size), 100)
  470. rows = (
  471. query.order_by(
  472. BizProtocolSamplePayment.create_time.desc(),
  473. BizProtocolSamplePayment.id.desc(),
  474. )
  475. .offset((page - 1) * page_size)
  476. .limit(page_size)
  477. .all()
  478. )
  479. schedules, transfers = _load_children(
  480. db, [row[0].id for row in rows], ctx.tenant_no
  481. )
  482. sample_meta = _load_sample_meta(db, [row[0] for row in rows], ctx.tenant_no)
  483. return [
  484. _payment_dict(
  485. payment,
  486. protocol,
  487. party,
  488. schedules.get(payment.id, []),
  489. transfers,
  490. sample_meta.get(payment.sample_code or ''),
  491. )
  492. for payment, protocol, party in rows
  493. ], int(total)
  494. def get_payment_detail(
  495. db: Session,
  496. *,
  497. payment_id: str,
  498. ctx: MarketFieldContext,
  499. user_info: dict,
  500. ) -> Dict[str, Any]:
  501. row = _scoped_payment_query(
  502. db, ctx=ctx, user_info=user_info, v2_only=False
  503. ).filter(
  504. BizProtocolSamplePayment.id == payment_id
  505. ).first()
  506. if not row:
  507. raise HTTPException(status_code=404, detail='缴费方案不存在或无权访问')
  508. payment, protocol, party = row
  509. schedules, transfers = _load_children(db, [payment.id], ctx.tenant_no)
  510. sample_meta = _load_sample_meta(db, [payment], ctx.tenant_no)
  511. return _payment_dict(
  512. payment,
  513. protocol,
  514. party,
  515. schedules.get(payment.id, []),
  516. transfers,
  517. sample_meta.get(payment.sample_code or ''),
  518. )
  519. def list_payment_chase(
  520. db: Session,
  521. *,
  522. ctx: MarketFieldContext,
  523. user_info: dict,
  524. page: int = 1,
  525. page_size: int = 10,
  526. keyword: Optional[str] = None,
  527. chase_type: Optional[str] = None,
  528. pay_mode: Optional[str] = None,
  529. sales_user_id: Optional[str] = None,
  530. today: Optional[date] = None,
  531. ) -> Tuple[List[Dict[str, Any]], int]:
  532. today_value = today or date.today()
  533. today_key = today_value.strftime('%Y%m%d')
  534. end_key = (today_value + timedelta(days=30)).strftime('%Y%m%d')
  535. normalized_due = func.replace(BizProtocolPaymentSchedule.due_date, '-', '')
  536. dialect_name = db.get_bind().dialect.name
  537. if dialect_name == 'mysql':
  538. parsed_due = func.str_to_date(normalized_due, '%Y%m%d')
  539. month_start = func.str_to_date(
  540. func.concat(func.substr(normalized_due, 1, 6), '01'),
  541. '%Y%m%d',
  542. )
  543. month_number = cast(func.substr(normalized_due, 5, 2), Integer)
  544. day_number = cast(func.substr(normalized_due, 7, 2), Integer)
  545. valid_due = and_(
  546. func.length(normalized_due) == 8,
  547. normalized_due.op('REGEXP')('^[0-9]{8}$'),
  548. month_number.between(1, 12),
  549. day_number.between(1, func.day(func.last_day(month_start))),
  550. func.date_format(parsed_due, '%Y%m%d') == normalized_due,
  551. )
  552. else:
  553. parsed_due = func.date(
  554. func.printf(
  555. '%s-%s-%s',
  556. func.substr(normalized_due, 1, 4),
  557. func.substr(normalized_due, 5, 2),
  558. func.substr(normalized_due, 7, 2),
  559. )
  560. )
  561. valid_due = and_(
  562. func.length(normalized_due) == 8,
  563. func.strftime('%Y%m%d', parsed_due) == normalized_due,
  564. )
  565. paid_subquery = (
  566. db.query(
  567. BizProtocolPaymentTransfer.schedule_id.label('schedule_id'),
  568. func.sum(
  569. case(
  570. (
  571. BizProtocolPaymentTransfer.pay_status == 'yjf',
  572. BizProtocolPaymentTransfer.transfer_amount,
  573. ),
  574. else_=Decimal('0'),
  575. )
  576. ).label('paid_amount'),
  577. )
  578. .filter(
  579. BizProtocolPaymentTransfer.tenant_no == ctx.tenant_no,
  580. BizProtocolPaymentTransfer.del_flag == 0,
  581. )
  582. .group_by(BizProtocolPaymentTransfer.schedule_id)
  583. .subquery()
  584. )
  585. paid_amount = func.coalesce(paid_subquery.c.paid_amount, Decimal('0'))
  586. arrears_amount = (
  587. func.coalesce(BizProtocolPaymentSchedule.due_amount, Decimal('0'))
  588. - paid_amount
  589. )
  590. collection_row = aliased(BizProtocolCollectionInfo)
  591. query = (
  592. db.query(
  593. BizProtocolPaymentSchedule,
  594. BizProtocolSamplePayment,
  595. BizCollectionProtocol,
  596. BizProtocolPartyCustomer,
  597. collection_row,
  598. paid_amount.label('paid_amount'),
  599. )
  600. .join(
  601. BizProtocolSamplePayment,
  602. and_(
  603. BizProtocolSamplePayment.id
  604. == BizProtocolPaymentSchedule.sample_payment_id,
  605. BizProtocolSamplePayment.collection_protocol_id
  606. == BizProtocolPaymentSchedule.collection_protocol_id,
  607. BizProtocolSamplePayment.tenant_no == ctx.tenant_no,
  608. BizProtocolSamplePayment.del_flag == 0,
  609. ),
  610. )
  611. .join(
  612. BizCollectionProtocol,
  613. and_(
  614. BizCollectionProtocol.id
  615. == BizProtocolPaymentSchedule.collection_protocol_id,
  616. BizCollectionProtocol.tenant_no == ctx.tenant_no,
  617. BizCollectionProtocol.del_flag == 0,
  618. ),
  619. )
  620. .join(
  621. collection_row,
  622. and_(
  623. collection_row.collection_protocol_id
  624. == BizCollectionProtocol.id,
  625. collection_row.tenant_no == ctx.tenant_no,
  626. collection_row.del_flag == 0,
  627. ),
  628. )
  629. .outerjoin(
  630. BizProtocolPartyCustomer,
  631. and_(
  632. BizProtocolPartyCustomer.collection_protocol_id
  633. == BizCollectionProtocol.id,
  634. BizProtocolPartyCustomer.tenant_no == ctx.tenant_no,
  635. BizProtocolPartyCustomer.del_flag == 0,
  636. ),
  637. )
  638. .outerjoin(
  639. paid_subquery,
  640. paid_subquery.c.schedule_id == BizProtocolPaymentSchedule.id,
  641. )
  642. .filter(
  643. BizProtocolPaymentSchedule.tenant_no == ctx.tenant_no,
  644. BizProtocolPaymentSchedule.del_flag == 0,
  645. BizProtocolPaymentSchedule.schedule_status != 'void',
  646. valid_due,
  647. normalized_due <= end_key,
  648. arrears_amount > 0,
  649. )
  650. )
  651. query = apply_cell_protocol_scope(query, db, ctx, user_info=user_info)
  652. keyword_value = (keyword or '').strip()
  653. if keyword_value:
  654. like = f'%{keyword_value}%'
  655. query = query.filter(
  656. or_(
  657. BizCollectionProtocol.protocol_no.like(like),
  658. BizProtocolSamplePayment.sample_code.like(like),
  659. BizProtocolPartyCustomer.mother_name.like(like),
  660. BizProtocolPartyCustomer.mother_phone.like(like),
  661. )
  662. )
  663. mode = (pay_mode or '').strip()
  664. if mode:
  665. query = query.filter(BizProtocolSamplePayment.pay_mode == mode)
  666. sales = (sales_user_id or '').strip()
  667. if sales:
  668. query = query.filter(collection_row.sales_user_id == sales)
  669. kind = (chase_type or '').strip()
  670. if kind == 'overdue':
  671. query = query.filter(normalized_due < today_key)
  672. elif kind == 'upcoming':
  673. query = query.filter(normalized_due >= today_key)
  674. total = (
  675. query.order_by(None)
  676. .with_entities(func.count(BizProtocolPaymentSchedule.id))
  677. .scalar()
  678. or 0
  679. )
  680. page = max(1, page)
  681. page_size = min(max(1, page_size), 100)
  682. candidates = (
  683. query.order_by(
  684. normalized_due.asc(),
  685. BizCollectionProtocol.protocol_no.asc(),
  686. BizProtocolPaymentSchedule.id.asc(),
  687. )
  688. .offset((page - 1) * page_size)
  689. .limit(page_size)
  690. .all()
  691. )
  692. sales_user_ids = {
  693. collection.sales_user_id
  694. for _, _, _, _, collection, _ in candidates
  695. if collection.sales_user_id
  696. }
  697. sales_user_names = {
  698. row.id: row.nick_name or ''
  699. for row in db.query(SysUser).filter(
  700. SysUser.id.in_(sales_user_ids or ['']),
  701. SysUser.tenant_no == ctx.tenant_no,
  702. )
  703. }
  704. rows: List[Dict[str, Any]] = []
  705. for schedule, payment, protocol, party, collection, paid in candidates:
  706. due_date = parse_due_date_ymd(schedule.due_date)
  707. if due_date is None:
  708. continue
  709. paid_value = Decimal(str(paid or 0))
  710. due_value = Decimal(str(schedule.due_amount or 0))
  711. arrears = max(due_value - paid_value, Decimal('0'))
  712. is_overdue = due_date < today_value
  713. rows.append(
  714. {
  715. 'scheduleId': schedule.id,
  716. 'samplePaymentId': payment.id,
  717. 'protocolId': protocol.id,
  718. 'protocolNo': protocol.protocol_no or '',
  719. 'protocolStatus': protocol.protocol_status or '',
  720. 'motherName': (party.mother_name if party else '') or '',
  721. 'motherPhone': (party.mother_phone if party else '') or '',
  722. 'sampleCode': payment.sample_code or schedule.sample_code or '',
  723. 'salesUserId': collection.sales_user_id or '',
  724. 'salesUserName': sales_user_names.get(
  725. collection.sales_user_id or '', ''
  726. ),
  727. 'payMode': payment.pay_mode or '',
  728. 'scheduleNo': schedule.schedule_no,
  729. 'dueDate': due_date.strftime('%Y-%m-%d'),
  730. 'dueAmount': _money(schedule.due_amount),
  731. 'paidAmount': _money(paid_value),
  732. 'arrearsAmount': _money(arrears),
  733. 'chaseStatus': 'overdue' if is_overdue else 'upcoming',
  734. 'daysOverdue': (today_value - due_date).days if is_overdue else 0,
  735. 'daysUntilDue': (due_date - today_value).days
  736. if not is_overdue
  737. else 0,
  738. 'paymentModelVersion': int(protocol.payment_model_version or 1),
  739. }
  740. )
  741. return rows, int(total)
  742. def _scoped_chase_schedule(
  743. db: Session,
  744. *,
  745. schedule_id: str,
  746. ctx: MarketFieldContext,
  747. user_info: dict,
  748. today: Optional[date] = None,
  749. ):
  750. row = (
  751. apply_cell_protocol_scope(
  752. db.query(
  753. BizProtocolPaymentSchedule,
  754. BizProtocolSamplePayment,
  755. BizCollectionProtocol,
  756. )
  757. .join(
  758. BizProtocolSamplePayment,
  759. and_(
  760. BizProtocolSamplePayment.id
  761. == BizProtocolPaymentSchedule.sample_payment_id,
  762. BizProtocolSamplePayment.collection_protocol_id
  763. == BizProtocolPaymentSchedule.collection_protocol_id,
  764. BizProtocolSamplePayment.tenant_no == ctx.tenant_no,
  765. BizProtocolSamplePayment.del_flag == 0,
  766. ),
  767. )
  768. .join(
  769. BizCollectionProtocol,
  770. and_(
  771. BizCollectionProtocol.id
  772. == BizProtocolPaymentSchedule.collection_protocol_id,
  773. BizCollectionProtocol.tenant_no == ctx.tenant_no,
  774. BizCollectionProtocol.del_flag == 0,
  775. ),
  776. )
  777. .filter(
  778. BizProtocolPaymentSchedule.id == schedule_id,
  779. BizProtocolPaymentSchedule.tenant_no == ctx.tenant_no,
  780. BizProtocolPaymentSchedule.del_flag == 0,
  781. BizProtocolPaymentSchedule.schedule_status != 'void',
  782. ),
  783. db,
  784. ctx,
  785. user_info=user_info,
  786. )
  787. .first()
  788. )
  789. if not row:
  790. raise HTTPException(status_code=404, detail='催缴期次不存在或无权访问')
  791. schedule, payment, protocol = row
  792. due_date = parse_due_date_ymd(schedule.due_date)
  793. confirmed_paid = (
  794. db.query(func.coalesce(func.sum(BizProtocolPaymentTransfer.transfer_amount), 0))
  795. .filter(
  796. BizProtocolPaymentTransfer.schedule_id == schedule.id,
  797. BizProtocolPaymentTransfer.tenant_no == ctx.tenant_no,
  798. BizProtocolPaymentTransfer.del_flag == 0,
  799. BizProtocolPaymentTransfer.pay_status == 'yjf',
  800. )
  801. .scalar()
  802. or Decimal('0')
  803. )
  804. arrears = max(
  805. Decimal(str(schedule.due_amount or 0)) - Decimal(str(confirmed_paid or 0)),
  806. Decimal('0'),
  807. )
  808. if due_date is None or not is_chase_candidate(
  809. due_date=due_date,
  810. today=today or date.today(),
  811. arrears=arrears,
  812. ):
  813. raise HTTPException(status_code=404, detail='催缴期次不存在或无权访问')
  814. return schedule, payment, protocol
  815. def get_payment_chase_detail(
  816. db: Session,
  817. *,
  818. schedule_id: str,
  819. view: str,
  820. ctx: MarketFieldContext,
  821. user_info: dict,
  822. today: Optional[date] = None,
  823. ) -> Dict[str, Any]:
  824. schedule, payment, protocol = _scoped_chase_schedule(
  825. db,
  826. schedule_id=schedule_id,
  827. ctx=ctx,
  828. user_info=user_info,
  829. today=today,
  830. )
  831. target_view = str(view or '').strip()
  832. if target_view == 'payment':
  833. detail = get_payment_detail(
  834. db,
  835. payment_id=payment.id,
  836. ctx=ctx,
  837. user_info=user_info,
  838. )
  839. target_transfers = (
  840. db.query(BizProtocolPaymentTransfer)
  841. .filter(
  842. BizProtocolPaymentTransfer.schedule_id == schedule.id,
  843. BizProtocolPaymentTransfer.tenant_no == ctx.tenant_no,
  844. BizProtocolPaymentTransfer.del_flag == 0,
  845. )
  846. .order_by(BizProtocolPaymentTransfer.create_time.asc())
  847. .all()
  848. )
  849. target_detail = _payment_dict(
  850. payment,
  851. protocol,
  852. None,
  853. [schedule],
  854. {schedule.id: target_transfers},
  855. )
  856. for key in (
  857. 'receivableAmount',
  858. 'paidAmount',
  859. 'remainAmount',
  860. 'dueRemainAmount',
  861. 'clearedScheduleCount',
  862. 'activeScheduleCount',
  863. 'paymentProgress',
  864. 'progressStatus',
  865. 'periods',
  866. 'schedules',
  867. ):
  868. detail[key] = target_detail[key]
  869. elif target_view == 'protocol':
  870. from app.services import market_protocol
  871. detail = market_protocol.get_protocol(
  872. db,
  873. source=market_protocol.SOURCE_CELL,
  874. protocol_id=protocol.id,
  875. ctx=ctx,
  876. user_info=user_info,
  877. )
  878. else:
  879. raise ValueError('催缴详情类型无效')
  880. detail['chaseView'] = target_view
  881. detail['targetScheduleId'] = schedule.id
  882. detail['allowedActions'] = []
  883. return detail
  884. def _scoped_schedule(
  885. db: Session,
  886. *,
  887. schedule_id: str,
  888. ctx: MarketFieldContext,
  889. user_info: dict,
  890. ):
  891. query = (
  892. db.query(BizProtocolPaymentSchedule)
  893. .join(
  894. BizProtocolSamplePayment,
  895. and_(
  896. BizProtocolSamplePayment.id
  897. == BizProtocolPaymentSchedule.sample_payment_id,
  898. BizProtocolSamplePayment.collection_protocol_id
  899. == BizProtocolPaymentSchedule.collection_protocol_id,
  900. BizProtocolSamplePayment.tenant_no == ctx.tenant_no,
  901. BizProtocolSamplePayment.del_flag == 0,
  902. ),
  903. )
  904. .join(
  905. BizCollectionProtocol,
  906. and_(
  907. BizCollectionProtocol.id
  908. == BizProtocolPaymentSchedule.collection_protocol_id,
  909. BizCollectionProtocol.tenant_no == ctx.tenant_no,
  910. BizCollectionProtocol.del_flag == 0,
  911. ),
  912. )
  913. .filter(
  914. BizProtocolPaymentSchedule.id == schedule_id,
  915. BizProtocolPaymentSchedule.tenant_no == ctx.tenant_no,
  916. BizProtocolPaymentSchedule.del_flag == 0,
  917. BizProtocolPaymentSchedule.schedule_status != 'void',
  918. )
  919. )
  920. query = apply_cell_protocol_scope(query, db, ctx, user_info=user_info)
  921. row = query.populate_existing().with_for_update().first()
  922. if not row:
  923. raise HTTPException(status_code=404, detail='应缴批次不存在或无权访问')
  924. return row
  925. def _scoped_transfer(
  926. db: Session,
  927. *,
  928. transfer_id: str,
  929. ctx: MarketFieldContext,
  930. user_info: dict,
  931. ):
  932. parent = (
  933. db.query(
  934. BizProtocolPaymentTransfer.schedule_id,
  935. BizProtocolPaymentTransfer.sample_payment_id,
  936. BizProtocolPaymentTransfer.collection_protocol_id,
  937. )
  938. .filter(
  939. BizProtocolPaymentTransfer.id == transfer_id,
  940. BizProtocolPaymentTransfer.tenant_no == ctx.tenant_no,
  941. BizProtocolPaymentTransfer.del_flag == 0,
  942. )
  943. .first()
  944. )
  945. if not parent:
  946. raise HTTPException(status_code=404, detail='转账记录不存在或无权访问')
  947. schedule_query = (
  948. db.query(BizProtocolPaymentSchedule)
  949. .join(
  950. BizProtocolSamplePayment,
  951. and_(
  952. BizProtocolSamplePayment.id == parent.sample_payment_id,
  953. BizProtocolSamplePayment.id
  954. == BizProtocolPaymentSchedule.sample_payment_id,
  955. BizProtocolSamplePayment.collection_protocol_id
  956. == parent.collection_protocol_id,
  957. BizProtocolSamplePayment.tenant_no == ctx.tenant_no,
  958. BizProtocolSamplePayment.del_flag == 0,
  959. ),
  960. )
  961. .join(
  962. BizCollectionProtocol,
  963. and_(
  964. BizCollectionProtocol.id == parent.collection_protocol_id,
  965. BizCollectionProtocol.id
  966. == BizProtocolPaymentSchedule.collection_protocol_id,
  967. BizCollectionProtocol.tenant_no == ctx.tenant_no,
  968. BizCollectionProtocol.del_flag == 0,
  969. ),
  970. )
  971. .filter(
  972. BizProtocolPaymentSchedule.id == parent.schedule_id,
  973. BizProtocolPaymentSchedule.sample_payment_id
  974. == parent.sample_payment_id,
  975. BizProtocolPaymentSchedule.collection_protocol_id
  976. == parent.collection_protocol_id,
  977. BizProtocolPaymentSchedule.tenant_no == ctx.tenant_no,
  978. BizProtocolPaymentSchedule.del_flag == 0,
  979. )
  980. )
  981. schedule_query = apply_cell_protocol_scope(
  982. schedule_query, db, ctx, user_info=user_info
  983. )
  984. schedule = schedule_query.populate_existing().with_for_update().first()
  985. if not schedule:
  986. raise HTTPException(status_code=404, detail='转账记录不存在或无权访问')
  987. row = (
  988. db.query(BizProtocolPaymentTransfer)
  989. .filter(
  990. BizProtocolPaymentTransfer.id == transfer_id,
  991. BizProtocolPaymentTransfer.schedule_id == schedule.id,
  992. BizProtocolPaymentTransfer.sample_payment_id
  993. == parent.sample_payment_id,
  994. BizProtocolPaymentTransfer.collection_protocol_id
  995. == parent.collection_protocol_id,
  996. BizProtocolPaymentTransfer.tenant_no == ctx.tenant_no,
  997. BizProtocolPaymentTransfer.del_flag == 0,
  998. )
  999. .populate_existing()
  1000. .with_for_update()
  1001. .first()
  1002. )
  1003. if not row:
  1004. raise HTTPException(status_code=404, detail='转账记录不存在或无权访问')
  1005. return row
  1006. def _editable_fields(fields: Dict[str, Any]) -> Dict[str, Any]:
  1007. aliases = {
  1008. 'transfer_amount': 'transferAmount',
  1009. 'transfer_time': 'transferTime',
  1010. 'transfer_type': 'transferType',
  1011. 'transfer_attachments': 'transferAttachments',
  1012. 'remark': 'remark',
  1013. }
  1014. result: Dict[str, Any] = {}
  1015. for python_name, alias in aliases.items():
  1016. if python_name in fields:
  1017. result[alias] = fields[python_name]
  1018. elif alias in fields:
  1019. result[alias] = fields[alias]
  1020. amount = result.get('transferAmount')
  1021. if amount is not None and Decimal(str(amount)) <= 0:
  1022. raise ValueError('转账金额必须大于 0')
  1023. if 'transferTime' in result and result['transferTime'] not in (None, ''):
  1024. value = result['transferTime']
  1025. result['transferTime'] = value if isinstance(value, datetime) else parse_datetime(str(value))
  1026. if 'transferType' in result:
  1027. result['transferType'] = str(result['transferType'] or '').strip() or None
  1028. if 'transferAttachments' in result:
  1029. result['transferAttachments'] = str(
  1030. result['transferAttachments'] or ''
  1031. ).strip() or None
  1032. if 'remark' in result:
  1033. result['remark'] = str(result['remark'] or '').strip() or None
  1034. return result
  1035. def create_transfer(
  1036. db: Session,
  1037. *,
  1038. schedule_id: str,
  1039. fields: Dict[str, Any],
  1040. ctx: MarketFieldContext,
  1041. user_info: dict,
  1042. ) -> Dict[str, Any]:
  1043. try:
  1044. schedule = _scoped_schedule(
  1045. db,
  1046. schedule_id=schedule_id,
  1047. ctx=ctx,
  1048. user_info=user_info,
  1049. )
  1050. confirmed_paid = (
  1051. db.query(
  1052. func.coalesce(func.sum(BizProtocolPaymentTransfer.transfer_amount), 0)
  1053. )
  1054. .filter(
  1055. BizProtocolPaymentTransfer.schedule_id == schedule.id,
  1056. BizProtocolPaymentTransfer.tenant_no == ctx.tenant_no,
  1057. BizProtocolPaymentTransfer.del_flag == 0,
  1058. BizProtocolPaymentTransfer.pay_status == 'yjf',
  1059. )
  1060. .scalar()
  1061. or Decimal('0')
  1062. )
  1063. arrears = max(
  1064. Decimal(str(schedule.due_amount or 0))
  1065. - Decimal(str(confirmed_paid or 0)),
  1066. Decimal('0'),
  1067. )
  1068. if arrears <= 0:
  1069. raise ValueError('当前应缴批次无欠缴金额')
  1070. values = _editable_fields(fields)
  1071. row = payment_crud.add_transfer(
  1072. db,
  1073. schedule_id=schedule_id,
  1074. tenant_no=ctx.tenant_no,
  1075. user_id=ctx.user_id,
  1076. transfer_amount=values.get('transferAmount'),
  1077. transfer_time=values.get('transferTime'),
  1078. transfer_type=values.get('transferType'),
  1079. transfer_attachments=values.get('transferAttachments'),
  1080. remark=values.get('remark'),
  1081. create_dept_id=_current_dept_id(user_info),
  1082. commit=False,
  1083. )
  1084. if 'transferAttachments' in values:
  1085. row.transfer_attachments = validate_attachment_refs(
  1086. db,
  1087. values['transferAttachments'],
  1088. module='payment',
  1089. ctx=ctx,
  1090. creating=True,
  1091. business_id=row.id,
  1092. )
  1093. db.add(row)
  1094. db.flush()
  1095. result = _transfer_dict(row)
  1096. db.commit()
  1097. return result
  1098. except Exception:
  1099. db.rollback()
  1100. raise
  1101. def update_transfer(
  1102. db: Session,
  1103. *,
  1104. transfer_id: str,
  1105. fields: Dict[str, Any],
  1106. ctx: MarketFieldContext,
  1107. user_info: dict,
  1108. ) -> Dict[str, Any]:
  1109. try:
  1110. row = _scoped_transfer(
  1111. db, transfer_id=transfer_id, ctx=ctx, user_info=user_info
  1112. )
  1113. if (row.pay_status or '') != 'dfj':
  1114. raise ValueError('仅已付款状态可编辑')
  1115. values = _editable_fields(fields)
  1116. if 'transferAttachments' in values:
  1117. values['transferAttachments'] = validate_attachment_refs(
  1118. db,
  1119. values['transferAttachments'],
  1120. module='payment',
  1121. ctx=ctx,
  1122. creating=False,
  1123. existing_refs=row.transfer_attachments,
  1124. business_id=row.id,
  1125. )
  1126. if 'transferAmount' in values:
  1127. row.transfer_amount = Decimal(str(values['transferAmount'])) if values['transferAmount'] is not None else None
  1128. if 'transferTime' in values:
  1129. row.transfer_time = values['transferTime']
  1130. if 'transferType' in values:
  1131. row.transfer_type = values['transferType']
  1132. if 'transferAttachments' in values:
  1133. row.transfer_attachments = values['transferAttachments']
  1134. if 'remark' in values:
  1135. row.remark = values['remark']
  1136. row.update_by = ctx.user_id
  1137. row.update_time = datetime.now()
  1138. db.add(row)
  1139. db.commit()
  1140. db.refresh(row)
  1141. return _transfer_dict(row)
  1142. except Exception:
  1143. db.rollback()
  1144. raise
  1145. def submit_transfer(
  1146. db: Session,
  1147. *,
  1148. transfer_id: str,
  1149. ctx: MarketFieldContext,
  1150. user_info: dict,
  1151. ) -> Dict[str, Any]:
  1152. try:
  1153. row = _scoped_transfer(
  1154. db, transfer_id=transfer_id, ctx=ctx, user_info=user_info
  1155. )
  1156. if (row.pay_status or '') != 'dfj':
  1157. raise ValueError('当前状态不可提交财务确认')
  1158. if row.transfer_amount is None or Decimal(str(row.transfer_amount)) <= 0:
  1159. raise ValueError('请填写转账金额')
  1160. if not (row.transfer_type or '').strip():
  1161. raise ValueError('请选择转账方式')
  1162. now = datetime.now()
  1163. changed = (
  1164. db.query(BizProtocolPaymentTransfer)
  1165. .filter(
  1166. BizProtocolPaymentTransfer.id == transfer_id,
  1167. BizProtocolPaymentTransfer.tenant_no == ctx.tenant_no,
  1168. BizProtocolPaymentTransfer.del_flag == 0,
  1169. BizProtocolPaymentTransfer.pay_status == 'dfj',
  1170. )
  1171. .update(
  1172. {
  1173. BizProtocolPaymentTransfer.pay_status: 'jfqrz',
  1174. BizProtocolPaymentTransfer.update_by: ctx.user_id,
  1175. BizProtocolPaymentTransfer.update_time: now,
  1176. },
  1177. synchronize_session=False,
  1178. )
  1179. )
  1180. if changed != 1:
  1181. raise ValueError('转账状态已变化,请刷新后重试')
  1182. db.commit()
  1183. db.expire(row)
  1184. return _transfer_dict(row)
  1185. except Exception:
  1186. db.rollback()
  1187. raise
  1188. def delete_transfer(
  1189. db: Session,
  1190. *,
  1191. transfer_id: str,
  1192. ctx: MarketFieldContext,
  1193. user_info: dict,
  1194. ) -> Dict[str, str]:
  1195. try:
  1196. row = _scoped_transfer(
  1197. db, transfer_id=transfer_id, ctx=ctx, user_info=user_info
  1198. )
  1199. if (row.pay_status or '') != 'dfj':
  1200. raise ValueError('当前状态不可删除转账记录')
  1201. changed = (
  1202. db.query(BizProtocolPaymentTransfer)
  1203. .filter(
  1204. BizProtocolPaymentTransfer.id == transfer_id,
  1205. BizProtocolPaymentTransfer.tenant_no == ctx.tenant_no,
  1206. BizProtocolPaymentTransfer.del_flag == 0,
  1207. BizProtocolPaymentTransfer.pay_status == 'dfj',
  1208. )
  1209. .update(
  1210. {
  1211. BizProtocolPaymentTransfer.del_flag: 1,
  1212. BizProtocolPaymentTransfer.update_by: ctx.user_id,
  1213. BizProtocolPaymentTransfer.update_time: datetime.now(),
  1214. },
  1215. synchronize_session=False,
  1216. )
  1217. )
  1218. if changed != 1:
  1219. raise ValueError('转账状态已变化,请刷新后重试')
  1220. db.commit()
  1221. return {'id': transfer_id}
  1222. except Exception:
  1223. db.rollback()
  1224. raise
  1225. def withdraw_transfer(
  1226. db: Session,
  1227. *,
  1228. transfer_id: str,
  1229. ctx: MarketFieldContext,
  1230. user_info: dict,
  1231. ) -> Dict[str, Any]:
  1232. try:
  1233. row = _scoped_transfer(
  1234. db, transfer_id=transfer_id, ctx=ctx, user_info=user_info
  1235. )
  1236. if (row.pay_status or '') != 'jfqrz':
  1237. raise ValueError('仅付款确认中可撤回')
  1238. now = datetime.now()
  1239. changed = (
  1240. db.query(BizProtocolPaymentTransfer)
  1241. .filter(
  1242. BizProtocolPaymentTransfer.id == transfer_id,
  1243. BizProtocolPaymentTransfer.tenant_no == ctx.tenant_no,
  1244. BizProtocolPaymentTransfer.del_flag == 0,
  1245. BizProtocolPaymentTransfer.pay_status == 'jfqrz',
  1246. )
  1247. .update(
  1248. {
  1249. BizProtocolPaymentTransfer.pay_status: 'dfj',
  1250. BizProtocolPaymentTransfer.update_by: ctx.user_id,
  1251. BizProtocolPaymentTransfer.update_time: now,
  1252. },
  1253. synchronize_session=False,
  1254. )
  1255. )
  1256. if changed != 1:
  1257. raise ValueError('转账状态已变化,请刷新后重试')
  1258. db.commit()
  1259. db.expire(row)
  1260. return _transfer_dict(row)
  1261. except Exception:
  1262. db.rollback()
  1263. raise