test_market_protocol_api.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  1. from datetime import datetime, timedelta
  2. from unittest.mock import patch
  3. import pytest
  4. from fastapi import HTTPException
  5. from pydantic import ValidationError
  6. from sqlalchemy import create_engine, event
  7. from sqlalchemy.orm import sessionmaker
  8. from app.models.base import Base
  9. from app.models.models import (
  10. BizAttachment,
  11. BizCellSampleType,
  12. BizCollectionHospital,
  13. BizCollectionProtocol,
  14. BizCollectionRegion,
  15. BizCollectionRegionStaff,
  16. BizCustomer,
  17. BizItemUnit,
  18. BizProtocolCollectionInfo,
  19. BizProtocolPartyCustomer,
  20. BizProtocolPayment,
  21. BizProtocolPaymentDetail,
  22. BizProtocolPaymentSchedule,
  23. BizProtocolPaymentTransfer,
  24. BizProtocolSample,
  25. BizProtocolSampleTransport,
  26. BizSampleCode,
  27. BizSampleReception,
  28. SysPost,
  29. SysPostRole,
  30. SysRole,
  31. SysRoleDataScopeDetail,
  32. SysUser,
  33. SysUserPost,
  34. SysUserRole,
  35. )
  36. from app.models.research_donation import (
  37. BizProtocolDonationConvert,
  38. BizResearchDonation,
  39. BizResearchDonationCollection,
  40. BizResearchDonationParty,
  41. BizResearchDonationSample,
  42. BizResearchDonationSampleTransport,
  43. )
  44. def _session():
  45. engine = create_engine('sqlite:///:memory:')
  46. Base.metadata.create_all(
  47. engine,
  48. tables=[
  49. BizCollectionProtocol.__table__,
  50. BizProtocolPartyCustomer.__table__,
  51. BizProtocolCollectionInfo.__table__,
  52. BizProtocolSample.__table__,
  53. BizProtocolSampleTransport.__table__,
  54. BizProtocolPayment.__table__,
  55. BizProtocolPaymentDetail.__table__,
  56. BizProtocolPaymentSchedule.__table__,
  57. BizProtocolPaymentTransfer.__table__,
  58. BizSampleCode.__table__,
  59. BizSampleReception.__table__,
  60. BizResearchDonation.__table__,
  61. BizResearchDonationParty.__table__,
  62. BizResearchDonationCollection.__table__,
  63. BizResearchDonationSample.__table__,
  64. BizResearchDonationSampleTransport.__table__,
  65. BizProtocolDonationConvert.__table__,
  66. BizCollectionRegionStaff.__table__,
  67. BizCollectionRegion.__table__,
  68. BizCollectionHospital.__table__,
  69. BizCellSampleType.__table__,
  70. BizItemUnit.__table__,
  71. BizCustomer.__table__,
  72. BizAttachment.__table__,
  73. SysUser.__table__,
  74. SysRole.__table__,
  75. SysRoleDataScopeDetail.__table__,
  76. SysUserRole.__table__,
  77. SysPost.__table__,
  78. SysPostRole.__table__,
  79. SysUserPost.__table__,
  80. ],
  81. )
  82. return sessionmaker(bind=engine)()
  83. def _ctx(scope_kind, user_id='u1'):
  84. from app.services.market_field_scope import MarketFieldContext
  85. return MarketFieldContext('tenant-a', user_id, scope_kind)
  86. def _user(user_id='u1'):
  87. return {
  88. 'user_id': user_id,
  89. 'tenant_no': 'tenant-a',
  90. 'role': 'super_admin',
  91. 'region_id': 'dept-from-auth',
  92. }
  93. def _cell(db, row_id, *, sales='u1', manager='manager-a', region='region-a', created=None):
  94. row = BizCollectionProtocol(
  95. id=row_id,
  96. protocol_no=f'CELL-{row_id}',
  97. protocol_status='dsx',
  98. tenant_no='tenant-a',
  99. create_dept_id='dept-a',
  100. create_time=created or datetime.now(),
  101. del_flag=0,
  102. )
  103. collection = BizProtocolCollectionInfo(
  104. id=f'ci-{row_id}',
  105. collection_protocol_id=row_id,
  106. region_id=region,
  107. sales_user_id=sales,
  108. region_manager_user_id=manager,
  109. tenant_no='tenant-a',
  110. create_dept_id='dept-a',
  111. del_flag=0,
  112. )
  113. db.add_all([row, collection])
  114. return row
  115. def _donation(db, row_id, *, sales='u1', manager='manager-a', region='region-a', created=None):
  116. row = BizResearchDonation(
  117. id=row_id,
  118. donation_no=f'DON-{row_id}',
  119. donation_status='dsx',
  120. tenant_no='tenant-a',
  121. create_dept_id='dept-a',
  122. create_time=created or datetime.now(),
  123. del_flag=0,
  124. )
  125. collection = BizResearchDonationCollection(
  126. id=f'dci-{row_id}',
  127. research_donation_id=row_id,
  128. region_id=region,
  129. sales_user_id=sales,
  130. region_manager_user_id=manager,
  131. tenant_no='tenant-a',
  132. create_dept_id='dept-a',
  133. del_flag=0,
  134. )
  135. db.add_all([row, collection])
  136. return row
  137. def _masters(db):
  138. db.add_all(
  139. [
  140. BizCollectionRegion(
  141. id='region-a', region_name='A区', tenant_no='tenant-a', create_dept_id='', del_flag=0
  142. ),
  143. BizCollectionRegion(
  144. id='region-b', region_name='B区', tenant_no='tenant-a', create_dept_id='', del_flag=0
  145. ),
  146. BizCollectionHospital(
  147. id='hospital-a', region_id='region-a', hospital_name='A院', tenant_no='tenant-a', create_dept_id='', del_flag=0
  148. ),
  149. BizCellSampleType(
  150. id='type-a', type_code='A', type_name='样本A', tenant_no='tenant-a', create_dept_id='', del_flag=0
  151. ),
  152. BizSampleCode(
  153. id='code-a', sample_code='S-001', tenant_no='tenant-a', create_dept_id='', del_flag=0
  154. ),
  155. BizSampleCode(
  156. id='code-cross', sample_code='S-CROSS', tenant_no='tenant-b', create_dept_id='', del_flag=0
  157. ),
  158. BizSampleCode(
  159. id='code-deleted', sample_code='S-DELETED', tenant_no='tenant-a', create_dept_id='', del_flag=1
  160. ),
  161. BizItemUnit(
  162. id='unit-a', unit_code='ml', unit_name='毫升', tenant_no='tenant-a', create_dept_id='', del_flag=0
  163. ),
  164. SysUser(
  165. id='u1', user_no='u1', nick_name='当前用户', status='1', tenant_no='tenant-a', create_dept_id='', del_flag=0
  166. ),
  167. SysUser(
  168. id='manager-a', user_no='manager-a', nick_name='经理', status='1', tenant_no='tenant-a', create_dept_id='', del_flag=0
  169. ),
  170. SysUser(
  171. id='u2', user_no='u2', nick_name='其他专员', status='1', tenant_no='tenant-a', create_dept_id='', del_flag=0
  172. ),
  173. BizAttachment(
  174. id='att-protocol-a',
  175. business_type='market:specialist:protocol:staging',
  176. original_name='a.pdf',
  177. file_ext='pdf',
  178. file_url='protocol/a.pdf',
  179. file_size=10,
  180. file_type='application/pdf',
  181. tenant_no='tenant-a',
  182. create_by='u1',
  183. create_dept_id='',
  184. del_flag=0,
  185. ),
  186. ]
  187. )
  188. db.commit()
  189. def _body(source='cell_storage', **overrides):
  190. from app.schemas.market_mobile import MarketProtocolBody
  191. payload = {
  192. 'source': source,
  193. 'protocolNo': 'P-001',
  194. 'registerDate': '20261010',
  195. 'attachments': {'protocolAttachments': 'protocol/a.pdf'},
  196. 'customer': {'motherName': '张三', 'motherPhone': '13800000000'},
  197. 'collection': {
  198. 'regionId': 'region-a',
  199. 'hospitalId': 'hospital-a',
  200. 'salesUserId': 'someone-else',
  201. 'regionManagerUserId': 'manager-a',
  202. },
  203. 'samples': [
  204. {
  205. 'sampleTypeId': 'type-a',
  206. 'sampleCodeId': 'code-a',
  207. 'sampleCode': 'S-001',
  208. 'unitId': 'unit-a',
  209. 'collectAmount': 10,
  210. }
  211. ],
  212. 'remark': '移动端登记',
  213. }
  214. payload.update(overrides)
  215. return MarketProtocolBody.model_validate(payload)
  216. def test_protocol_create_rejects_unknown_attachment_reference():
  217. from app.services.market_protocol import create_protocol
  218. db = _session()
  219. _masters(db)
  220. body = _body(
  221. attachments={'protocolAttachments': 'https://evil.test/a.pdf'}
  222. )
  223. with pytest.raises(ValueError, match='附件'):
  224. create_protocol(
  225. db,
  226. body=body,
  227. ctx=_ctx('specialist'),
  228. user_info=_user(),
  229. )
  230. def test_terminal_protocol_rejects_hidden_update_action():
  231. from app.services.market_protocol import update_protocol
  232. db = _session()
  233. _masters(db)
  234. row = _cell(db, 'terminal')
  235. row.protocol_status = 'yzf'
  236. db.commit()
  237. with pytest.raises(ValueError, match='不可修改'):
  238. update_protocol(
  239. db,
  240. source='cell_storage',
  241. protocol_id=row.id,
  242. body=_body(protocolNo='CELL-terminal'),
  243. ctx=_ctx('specialist'),
  244. user_info=_user(),
  245. )
  246. def test_protocol_list_combines_cell_and_donation_without_scope_leak():
  247. from app.services.market_protocol import list_protocols
  248. db = _session()
  249. now = datetime.now()
  250. _cell(db, 'cell-own', created=now - timedelta(minutes=2))
  251. _cell(db, 'cell-other', sales='u2', created=now)
  252. _donation(db, 'don-own', created=now - timedelta(minutes=1))
  253. _donation(db, 'don-other', sales='u2', created=now + timedelta(minutes=1))
  254. db.commit()
  255. items, total = list_protocols(db, ctx=_ctx('specialist'), user_info=_user())
  256. assert total == 2
  257. assert [(item['source'], item['id']) for item in items] == [
  258. ('research_donation', 'don-own'),
  259. ('cell_storage', 'cell-own'),
  260. ]
  261. def test_protocol_list_large_page_uses_bounded_source_queries_and_global_order():
  262. from app.services.market_protocol import list_protocols
  263. db = _session()
  264. base = datetime(2026, 10, 10, 12, 0, 0)
  265. expected = []
  266. for index in range(24):
  267. created = base + timedelta(seconds=index)
  268. cell_id = f'cell-{index:02d}'
  269. donation_id = f'don-{index:02d}'
  270. _cell(db, cell_id, created=created)
  271. _donation(db, donation_id, created=created + timedelta(microseconds=1))
  272. expected.extend([(created, cell_id), (created + timedelta(microseconds=1), donation_id)])
  273. db.commit()
  274. statements = []
  275. def capture(_conn, _cursor, statement, _parameters, _context, _many):
  276. if 'FROM biz_collection_protocol ' in statement or 'FROM biz_research_donation ' in statement:
  277. statements.append(statement)
  278. event.listen(db.get_bind(), 'before_cursor_execute', capture)
  279. try:
  280. items, total = list_protocols(
  281. db,
  282. ctx=_ctx('specialist'),
  283. user_info=_user(),
  284. page=4,
  285. page_size=7,
  286. )
  287. finally:
  288. event.remove(db.get_bind(), 'before_cursor_execute', capture)
  289. ordered_ids = [item[1] for item in sorted(expected, key=lambda item: (item[0], item[1]), reverse=True)]
  290. assert total == 48
  291. assert [item['id'] for item in items] == ordered_ids[21:28]
  292. page_selects = [sql for sql in statements if 'count(' not in sql.lower()]
  293. assert len(page_selects) == 2
  294. assert all(' LIMIT ' in sql.upper() for sql in page_selects)
  295. def test_protocol_list_stable_tie_breaker_prevents_page_overlap():
  296. from app.services.market_protocol import list_protocols
  297. db = _session()
  298. same_time = datetime(2026, 10, 10, 12, 0, 0)
  299. for row_id in ('a1', 'a3', 'a5', 'a7'):
  300. _cell(db, row_id, created=same_time)
  301. for row_id in ('a2', 'a4', 'a6', 'a8'):
  302. _donation(db, row_id, created=same_time)
  303. db.commit()
  304. page_one, total = list_protocols(
  305. db, ctx=_ctx('specialist'), user_info=_user(), page=1, page_size=3
  306. )
  307. page_two, _ = list_protocols(
  308. db, ctx=_ctx('specialist'), user_info=_user(), page=2, page_size=3
  309. )
  310. assert total == 8
  311. assert [item['id'] for item in page_one] == ['a8', 'a7', 'a6']
  312. assert [item['id'] for item in page_two] == ['a5', 'a4', 'a3']
  313. assert {item['id'] for item in page_one}.isdisjoint(
  314. {item['id'] for item in page_two}
  315. )
  316. def test_protocol_detail_rechecks_source_specific_idor():
  317. from app.services.market_protocol import get_protocol
  318. db = _session()
  319. _cell(db, 'cell-other', sales='u2')
  320. _donation(db, 'don-other', sales='u2')
  321. db.commit()
  322. with pytest.raises(HTTPException) as cell_error:
  323. get_protocol(
  324. db,
  325. source='cell_storage',
  326. protocol_id='cell-other',
  327. ctx=_ctx('specialist'),
  328. user_info=_user(),
  329. )
  330. with pytest.raises(HTTPException) as donation_error:
  331. get_protocol(
  332. db,
  333. source='research_donation',
  334. protocol_id='don-other',
  335. ctx=_ctx('specialist'),
  336. user_info=_user(),
  337. )
  338. assert cell_error.value.status_code == 404
  339. assert donation_error.value.status_code == 404
  340. def test_protocol_detail_can_resolve_source_from_scoped_record():
  341. from app.services.market_protocol import get_protocol
  342. db = _session()
  343. _donation(db, 'don-own')
  344. db.commit()
  345. result = get_protocol(
  346. db,
  347. source=None,
  348. protocol_id='don-own',
  349. ctx=_ctx('specialist'),
  350. user_info=_user(),
  351. )
  352. assert result['source'] == 'research_donation'
  353. assert result['basic']['id'] == 'don-own'
  354. def test_protocol_detail_resolves_web_display_names_for_mobile_fields():
  355. from app.services.market_protocol import get_protocol
  356. db = _session()
  357. _masters(db)
  358. row = _cell(db, 'named')
  359. row.collector_user_id = 'u1'
  360. collection = db.query(BizProtocolCollectionInfo).filter_by(
  361. collection_protocol_id=row.id
  362. ).one()
  363. collection.hospital_id = 'hospital-a'
  364. db.add(
  365. BizProtocolSample(
  366. id='sample-named',
  367. collection_protocol_id=row.id,
  368. sample_type_id='type-a',
  369. sample_code='S-NAMED',
  370. unit_id='unit-a',
  371. tenant_no='tenant-a',
  372. create_dept_id='',
  373. del_flag=0,
  374. )
  375. )
  376. db.commit()
  377. result = get_protocol(
  378. db,
  379. source='cell_storage',
  380. protocol_id=row.id,
  381. ctx=_ctx('specialist'),
  382. user_info=_user(),
  383. )
  384. assert result['basic']['collectorUserName'] == '当前用户'
  385. assert result['collection']['regionName'] == 'A区'
  386. assert result['collection']['hospitalName'] == 'A院'
  387. assert result['collection']['salesUserName'] == '当前用户'
  388. assert result['collection']['regionManagerUserName'] == '经理'
  389. assert result['samples'][0]['sampleTypeName'] == '样本A'
  390. assert result['samples'][0]['unitName'] == '毫升'
  391. def test_protocol_detail_resolves_soft_deleted_master_names_with_tenant_scope():
  392. from app.services.market_protocol import get_protocol
  393. db = _session()
  394. _masters(db)
  395. row = _cell(db, 'historical-master')
  396. collection = db.query(BizProtocolCollectionInfo).filter_by(
  397. collection_protocol_id=row.id
  398. ).one()
  399. collection.hospital_id = 'hospital-a'
  400. db.get(BizCollectionRegion, 'region-a').del_flag = 1
  401. db.get(BizCollectionHospital, 'hospital-a').del_flag = 1
  402. db.get(BizCellSampleType, 'type-a').del_flag = 1
  403. db.get(BizItemUnit, 'unit-a').del_flag = 1
  404. db.add_all(
  405. [
  406. BizCellSampleType(id='type-global-history', type_code='GLOBAL', type_name='历史全局样本', tenant_no='', create_dept_id='', del_flag=1),
  407. BizCellSampleType(id='type-cross-history', type_code='CROSS', type_name='跨租户样本名称', tenant_no='tenant-b', create_dept_id='', del_flag=1),
  408. BizItemUnit(id='unit-cross-history', unit_code='cross', unit_name='跨租户单位名称', tenant_no='tenant-b', create_dept_id='', del_flag=1),
  409. BizProtocolSample(id='sample-history-local', collection_protocol_id=row.id, sample_type_id='type-a', sample_code='S-HISTORY-LOCAL', unit_id='unit-a', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  410. BizProtocolSample(id='sample-history-global', collection_protocol_id=row.id, sample_type_id='type-global-history', sample_code='S-HISTORY-GLOBAL', unit_id='', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  411. BizProtocolSample(id='sample-history-cross', collection_protocol_id=row.id, sample_type_id='type-cross-history', sample_code='S-HISTORY-CROSS', unit_id='unit-cross-history', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  412. ]
  413. )
  414. db.commit()
  415. result = get_protocol(
  416. db,
  417. source='cell_storage',
  418. protocol_id=row.id,
  419. ctx=_ctx('specialist'),
  420. user_info=_user(),
  421. )
  422. samples = {item['sampleCode']: item for item in result['samples']}
  423. assert result['collection']['regionName'] == 'A区'
  424. assert result['collection']['hospitalName'] == 'A院'
  425. assert samples['S-HISTORY-LOCAL']['sampleTypeName'] == '样本A'
  426. assert samples['S-HISTORY-LOCAL']['unitName'] == '毫升'
  427. assert samples['S-HISTORY-GLOBAL']['sampleTypeName'] == '历史全局样本'
  428. assert samples['S-HISTORY-CROSS']['sampleTypeName'] == ''
  429. assert samples['S-HISTORY-CROSS']['unitName'] == ''
  430. def test_protocol_names_use_exact_historical_nicknames_without_raw_fallbacks():
  431. from app.services.market_protocol import get_protocol, list_protocols
  432. db = _session()
  433. _masters(db)
  434. row = _cell(db, 'historical-names')
  435. row.collector_user_id = 'blank-name-user'
  436. collection = db.query(BizProtocolCollectionInfo).filter_by(
  437. collection_protocol_id=row.id
  438. ).one()
  439. collection.region_manager_user_id = 'manager-a'
  440. current_user = db.get(SysUser, 'u1')
  441. current_user.nick_name = '历史删除专员'
  442. current_user.del_flag = 1
  443. manager = db.get(SysUser, 'manager-a')
  444. manager.nick_name = '历史停用经理'
  445. manager.status = '0'
  446. db.add(
  447. SysUser(
  448. id='blank-name-user',
  449. user_no='raw-collector-no',
  450. nick_name='',
  451. status='0',
  452. tenant_no='tenant-a',
  453. create_dept_id='',
  454. del_flag=1,
  455. )
  456. )
  457. sample_type = db.get(BizCellSampleType, 'type-a')
  458. sample_type.type_name = ''
  459. unit = db.get(BizItemUnit, 'unit-a')
  460. unit.unit_name = ''
  461. db.add(
  462. BizProtocolSample(
  463. id='sample-historical-names',
  464. collection_protocol_id=row.id,
  465. sample_type_id='type-a',
  466. sample_code='S-HISTORY',
  467. unit_id='unit-a',
  468. tenant_no='tenant-a',
  469. create_dept_id='',
  470. del_flag=0,
  471. )
  472. )
  473. db.commit()
  474. items, total = list_protocols(
  475. db, ctx=_ctx('specialist'), user_info=_user()
  476. )
  477. detail = get_protocol(
  478. db,
  479. source='cell_storage',
  480. protocol_id=row.id,
  481. ctx=_ctx('specialist'),
  482. user_info=_user(),
  483. )
  484. assert total == 1
  485. assert items[0]['salesUserName'] == '历史删除专员'
  486. assert items[0]['collectorUserName'] == ''
  487. assert items[0]['managerName'] == '历史停用经理'
  488. assert items[0]['sampleTypeName'] == ''
  489. assert detail['basic']['collectorUserName'] == ''
  490. assert detail['collection']['salesUserName'] == '历史删除专员'
  491. assert detail['collection']['regionManagerUserName'] == '历史停用经理'
  492. assert detail['samples'][0]['sampleTypeName'] == ''
  493. assert detail['samples'][0]['unitName'] == ''
  494. def test_specialist_cell_create_forces_current_collection_and_collector_users():
  495. from app.services.market_protocol import create_protocol
  496. db = _session()
  497. _masters(db)
  498. result = create_protocol(
  499. db, body=_body(), ctx=_ctx('specialist'), user_info=_user()
  500. )
  501. main = db.get(BizCollectionProtocol, result['basic']['id'])
  502. collection = db.query(BizProtocolCollectionInfo).filter_by(collection_protocol_id=main.id, del_flag=0).one()
  503. party = db.query(BizProtocolPartyCustomer).filter_by(collection_protocol_id=main.id, del_flag=0).one()
  504. sample = db.query(BizProtocolSample).filter_by(collection_protocol_id=main.id, del_flag=0).one()
  505. assert main.collector_user_id == 'u1'
  506. assert main.create_dept_id == 'dept-from-auth'
  507. assert collection.sales_user_id == 'u1'
  508. assert collection.create_dept_id == 'dept-from-auth'
  509. assert party.collector_user_id == 'u1'
  510. assert party.customer_id is None
  511. assert db.query(BizCustomer).count() == 0
  512. assert sample.sample_code == 'S-001'
  513. def test_specialist_donation_create_forces_current_users_and_has_no_payment_section():
  514. from app.services.market_protocol import create_protocol
  515. db = _session()
  516. _masters(db)
  517. result = create_protocol(
  518. db,
  519. body=_body('research_donation', donationNo='D-001', protocolNo=None),
  520. ctx=_ctx('specialist'),
  521. user_info=_user(),
  522. )
  523. donation = db.get(BizResearchDonation, result['basic']['id'])
  524. collection = db.query(BizResearchDonationCollection).filter_by(research_donation_id=donation.id, del_flag=0).one()
  525. party = db.query(BizResearchDonationParty).filter_by(research_donation_id=donation.id, del_flag=0).one()
  526. sample = db.query(BizResearchDonationSample).filter_by(research_donation_id=donation.id, del_flag=0).one()
  527. assert donation.collector_user_id == 'u1'
  528. assert donation.create_dept_id == 'dept-from-auth'
  529. assert collection.sales_user_id == 'u1'
  530. assert collection.create_dept_id == 'dept-from-auth'
  531. assert party.collector_user_id == 'u1'
  532. assert party.create_dept_id == 'dept-from-auth'
  533. assert sample.create_dept_id == 'dept-from-auth'
  534. assert party.customer_id is None
  535. assert db.query(BizCustomer).count() == 0
  536. assert 'payment' not in result
  537. def test_manager_update_cannot_move_document_out_of_scope_and_rolls_back():
  538. from app.services.market_protocol import update_protocol
  539. db = _session()
  540. _masters(db)
  541. _cell(db, 'cell-manager', manager='u1')
  542. db.commit()
  543. with pytest.raises(ValueError, match='范围'):
  544. update_protocol(
  545. db,
  546. source='cell_storage',
  547. protocol_id='cell-manager',
  548. body=_body(collection={'regionId': 'region-b', 'regionManagerUserId': 'manager-a'}),
  549. ctx=_ctx('manager'),
  550. user_info=_user(),
  551. )
  552. db.expire_all()
  553. collection = db.query(BizProtocolCollectionInfo).filter_by(collection_protocol_id='cell-manager', del_flag=0).one()
  554. assert collection.region_id == 'region-a'
  555. assert collection.region_manager_user_id == 'u1'
  556. def test_partial_collection_update_validates_against_resulting_region():
  557. from app.schemas.market_mobile import MarketProtocolBody
  558. from app.services.market_protocol import update_protocol
  559. db = _session()
  560. _masters(db)
  561. _cell(db, 'cell-partial', sales='u1')
  562. db.commit()
  563. update_protocol(
  564. db,
  565. source='cell_storage',
  566. protocol_id='cell-partial',
  567. body=MarketProtocolBody.model_validate(
  568. {
  569. 'source': 'cell_storage',
  570. 'collection': {'hospitalId': 'hospital-a'},
  571. }
  572. ),
  573. ctx=_ctx('specialist'),
  574. user_info=_user(),
  575. )
  576. collection = db.query(BizProtocolCollectionInfo).filter_by(
  577. collection_protocol_id='cell-partial', del_flag=0
  578. ).one()
  579. assert collection.region_id == 'region-a'
  580. assert collection.hospital_id == 'hospital-a'
  581. def test_cell_partial_customer_update_preserves_ids_and_unspecified_fields():
  582. from app.schemas.market_mobile import MarketProtocolBody
  583. from app.services.market_protocol import update_protocol
  584. db = _session()
  585. _masters(db)
  586. _cell(db, 'cell-party')
  587. db.add_all(
  588. [
  589. BizCustomer(id='mother-c', customer_name='母客户', sex='1', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  590. BizCustomer(id='father-c', customer_name='父客户', sex='0', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  591. BizCustomer(id='newborn-c', customer_name='子客户', sex='2', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  592. BizProtocolPartyCustomer(
  593. id='party-cell', collection_protocol_id='cell-party',
  594. customer_id='mother-c', father_customer_id='father-c', newborn_customer_id='newborn-c',
  595. mother_name='母亲', mother_phone='旧电话', mother_id_card='ID-M',
  596. father_name='父亲', father_phone='父电话', newborn_name='宝宝',
  597. tenant_no='tenant-a', create_dept_id='', del_flag=0,
  598. ),
  599. ]
  600. )
  601. db.commit()
  602. update_protocol(
  603. db,
  604. source='cell_storage',
  605. protocol_id='cell-party',
  606. body=MarketProtocolBody.model_validate(
  607. {
  608. 'source': 'cell_storage',
  609. 'customer': {'motherPhone': '新电话', 'remark': '只改电话'},
  610. }
  611. ),
  612. ctx=_ctx('specialist'),
  613. user_info=_user(),
  614. )
  615. party = db.get(BizProtocolPartyCustomer, 'party-cell')
  616. assert (party.customer_id, party.father_customer_id, party.newborn_customer_id) == (
  617. 'mother-c', 'father-c', 'newborn-c'
  618. )
  619. assert party.mother_name == '母亲'
  620. assert party.mother_id_card == 'ID-M'
  621. assert party.father_name == '父亲'
  622. assert party.father_phone == '父电话'
  623. assert party.newborn_name == '宝宝'
  624. assert party.mother_phone == '新电话'
  625. assert party.remark == '只改电话'
  626. @pytest.mark.parametrize('source', ['cell_storage', 'research_donation'])
  627. def test_protocol_update_rejects_same_tenant_unlinked_customer_id(source):
  628. from app.schemas.market_mobile import MarketProtocolBody
  629. from app.services.market_protocol import update_protocol
  630. db = _session()
  631. _masters(db)
  632. db.add_all(
  633. [
  634. BizCustomer(id='linked-c', customer_name='已关联', sex='1', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  635. BizCustomer(id='unrelated-c', customer_name='无关客户', sex='1', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  636. ]
  637. )
  638. if source == 'cell_storage':
  639. _cell(db, 'customer-idor')
  640. db.add(BizProtocolPartyCustomer(id='linked-party', collection_protocol_id='customer-idor', customer_id='linked-c', mother_name='原姓名', tenant_no='tenant-a', create_dept_id='', del_flag=0))
  641. else:
  642. _donation(db, 'customer-idor')
  643. db.add(BizResearchDonationParty(id='linked-party', research_donation_id='customer-idor', customer_id='linked-c', mother_name='原姓名', tenant_no='tenant-a', create_dept_id='', del_flag=0))
  644. db.commit()
  645. with pytest.raises(ValueError, match='客户'):
  646. update_protocol(
  647. db,
  648. source=source,
  649. protocol_id='customer-idor',
  650. body=MarketProtocolBody.model_validate(
  651. {
  652. 'source': source,
  653. 'customer': {'customerId': 'unrelated-c', 'motherName': '被篡改'},
  654. }
  655. ),
  656. ctx=_ctx('specialist'),
  657. user_info=_user(),
  658. )
  659. db.expire_all()
  660. assert db.get(BizCustomer, 'unrelated-c').customer_name == '无关客户'
  661. assert db.get(BizCustomer, 'linked-c').customer_name == '已关联'
  662. @pytest.mark.parametrize('source', ['cell_storage', 'research_donation'])
  663. def test_protocol_update_does_not_mutate_unrelated_customer_by_id_card(source):
  664. from app.schemas.market_mobile import MarketProtocolBody
  665. from app.services.market_protocol import update_protocol
  666. db = _session()
  667. _masters(db)
  668. db.add(BizCustomer(id='unrelated-card', customer_name='身份证客户', sex='1', id_card_no='CARD-1', tenant_no='tenant-a', create_dept_id='', del_flag=0))
  669. if source == 'cell_storage':
  670. _cell(db, 'card-idor')
  671. db.add(BizProtocolPartyCustomer(id='card-party', collection_protocol_id='card-idor', mother_name='原姓名', tenant_no='tenant-a', create_dept_id='', del_flag=0))
  672. else:
  673. _donation(db, 'card-idor')
  674. db.add(BizResearchDonationParty(id='card-party', research_donation_id='card-idor', mother_name='原姓名', tenant_no='tenant-a', create_dept_id='', del_flag=0))
  675. db.commit()
  676. update_protocol(
  677. db,
  678. source=source,
  679. protocol_id='card-idor',
  680. body=MarketProtocolBody.model_validate(
  681. {
  682. 'source': source,
  683. 'customer': {'motherName': '协议姓名', 'motherIdCard': 'CARD-1'},
  684. }
  685. ),
  686. ctx=_ctx('specialist'),
  687. user_info=_user(),
  688. )
  689. db.expire_all()
  690. assert db.get(BizCustomer, 'unrelated-card').customer_name == '身份证客户'
  691. @pytest.mark.parametrize('source', ['cell_storage', 'research_donation'])
  692. def test_protocol_create_forbids_existing_customer_ids(source):
  693. from app.services.market_protocol import create_protocol
  694. db = _session()
  695. _masters(db)
  696. db.add(BizCustomer(id='existing-c', customer_name='已有客户', sex='1', tenant_no='tenant-a', create_dept_id='', del_flag=0))
  697. db.commit()
  698. with pytest.raises(ValueError, match='客户'):
  699. create_protocol(
  700. db,
  701. body=_body(
  702. source,
  703. **({'donationNo': 'D-CUSTOMER', 'protocolNo': None} if source == 'research_donation' else {}),
  704. customer={'customerId': 'existing-c', 'motherName': '已有客户'},
  705. ),
  706. ctx=_ctx('specialist'),
  707. user_info=_user(),
  708. )
  709. def test_market_protocol_body_accepts_sample_payments():
  710. from app.schemas.market_mobile import MarketProtocolBody
  711. body = MarketProtocolBody.model_validate(
  712. {
  713. 'source': 'cell_storage',
  714. 'protocolNo': 'P-PAY-1',
  715. 'customer': {'motherName': '李四'},
  716. 'samplePayments': [
  717. {
  718. 'sampleCode': 'S-001',
  719. 'payMode': 'dj',
  720. 'contractAmount': 20000,
  721. 'lumpSumDeadline': '20261231',
  722. 'schedules': [
  723. {
  724. 'scheduleNo': 1,
  725. 'dueAmount': 20000,
  726. 'dueDate': '20261231',
  727. }
  728. ],
  729. }
  730. ],
  731. }
  732. )
  733. assert body.sample_payments is not None
  734. assert len(body.sample_payments) == 1
  735. assert body.sample_payments[0].sample_code == 'S-001'
  736. assert body.sample_payments[0].pay_mode == 'dj'
  737. def test_protocol_body_rejects_status_finance_and_conversion_fields():
  738. from app.schemas.market_mobile import MarketProtocolBody
  739. forbidden = [
  740. {'auditStatus': 'shtg'},
  741. {'protocolStatus': 'yzf'},
  742. {'delFlag': 1},
  743. {'refundAmount': 100},
  744. {'financeRemark': '通过'},
  745. {'toResearchTime': '2026-10-10'},
  746. ]
  747. for field in forbidden:
  748. with pytest.raises(ValidationError):
  749. MarketProtocolBody.model_validate({'source': 'cell_storage', **field})
  750. def test_cross_tenant_or_disabled_referenced_user_is_rejected():
  751. from app.services.market_protocol import create_protocol
  752. db = _session()
  753. _masters(db)
  754. db.add(
  755. SysUser(
  756. id='disabled', user_no='disabled', nick_name='停用', status='0', tenant_no='tenant-a', create_dept_id='', del_flag=0
  757. )
  758. )
  759. db.commit()
  760. with pytest.raises(ValueError, match='用户'):
  761. create_protocol(
  762. db,
  763. body=_body(collection={'regionId': 'region-a', 'hospitalId': 'hospital-a', 'regionManagerUserId': 'disabled'}),
  764. ctx=_ctx('specialist'),
  765. user_info=_user(),
  766. )
  767. @pytest.mark.parametrize('source', ['cell_storage', 'research_donation'])
  768. @pytest.mark.parametrize(
  769. ('sample_code_id', 'sample_code'),
  770. [
  771. ('code-cross', 'S-CROSS'),
  772. ('code-deleted', 'S-DELETED'),
  773. ('code-a', 'S-WRONG'),
  774. ],
  775. )
  776. def test_protocol_rejects_invalid_or_inconsistent_sample_code_reference(
  777. source, sample_code_id, sample_code
  778. ):
  779. from app.services.market_protocol import create_protocol
  780. db = _session()
  781. _masters(db)
  782. payload = {
  783. 'samples': [
  784. {
  785. 'sampleTypeId': 'type-a',
  786. 'sampleCodeId': sample_code_id,
  787. 'sampleCode': sample_code,
  788. 'unitId': 'unit-a',
  789. }
  790. ]
  791. }
  792. if source == 'research_donation':
  793. payload.update({'donationNo': 'D-CODE', 'protocolNo': None})
  794. with pytest.raises(ValueError, match='样本编码'):
  795. create_protocol(
  796. db,
  797. body=_body(source, **payload),
  798. ctx=_ctx('specialist'),
  799. user_info=_user(),
  800. )
  801. def test_cell_update_rolls_back_main_and_existing_children_after_late_failure():
  802. from app.schemas.market_mobile import MarketProtocolBody
  803. from app.services.market_protocol import update_protocol
  804. db = _session()
  805. _masters(db)
  806. _cell(db, 'cell-update')
  807. db.add_all(
  808. [
  809. BizProtocolPartyCustomer(
  810. id='party-old', collection_protocol_id='cell-update', mother_name='旧姓名', tenant_no='tenant-a', create_dept_id='', del_flag=0
  811. ),
  812. BizProtocolSample(
  813. id='sample-old', collection_protocol_id='cell-update', sample_code='OLD-CODE', tenant_no='tenant-a', create_dept_id='', del_flag=0
  814. ),
  815. ]
  816. )
  817. db.commit()
  818. body = MarketProtocolBody.model_validate(
  819. {
  820. 'source': 'cell_storage',
  821. 'remark': '新备注',
  822. 'customer': {'motherName': '新姓名'},
  823. 'collection': {'medicalStaff': '新医护'},
  824. 'samples': [{'sampleTypeId': 'type-a', 'sampleCodeId': 'code-a', 'sampleCode': 'S-001'}],
  825. }
  826. )
  827. with patch(
  828. 'app.services.market_protocol.cell_crud.save_samples',
  829. side_effect=RuntimeError('late failure'),
  830. ):
  831. with pytest.raises(RuntimeError, match='late'):
  832. update_protocol(
  833. db,
  834. source='cell_storage',
  835. protocol_id='cell-update',
  836. body=body,
  837. ctx=_ctx('specialist'),
  838. user_info=_user(),
  839. )
  840. db.expire_all()
  841. assert db.get(BizCollectionProtocol, 'cell-update').remark is None
  842. assert db.get(BizProtocolPartyCustomer, 'party-old').mother_name == '旧姓名'
  843. assert db.get(BizProtocolPartyCustomer, 'party-old').del_flag == 0
  844. assert db.get(BizProtocolSample, 'sample-old').sample_code == 'OLD-CODE'
  845. assert db.get(BizProtocolCollectionInfo, 'ci-cell-update').medical_staff is None
  846. def test_donation_update_rolls_back_main_and_old_children_after_soft_delete():
  847. from app.schemas.market_mobile import MarketProtocolBody
  848. from app.services.market_protocol import update_protocol
  849. db = _session()
  850. _masters(db)
  851. _donation(db, 'don-update')
  852. db.add_all(
  853. [
  854. BizResearchDonationParty(
  855. id='dparty-old', research_donation_id='don-update', mother_name='旧姓名', tenant_no='tenant-a', create_dept_id='', del_flag=0
  856. ),
  857. BizResearchDonationSample(
  858. id='dsample-old', research_donation_id='don-update', sample_code='OLD-CODE', tenant_no='tenant-a', create_dept_id='', del_flag=0
  859. ),
  860. ]
  861. )
  862. db.commit()
  863. body = MarketProtocolBody.model_validate(
  864. {
  865. 'source': 'research_donation',
  866. 'donationNo': 'DON-don-update',
  867. 'remark': '新备注',
  868. 'customer': {'motherName': '新姓名'},
  869. 'collection': {'medicalStaff': '新医护'},
  870. 'samples': [{'sampleTypeId': 'type-a', 'sampleCodeId': 'code-a', 'sampleCode': 'S-001'}],
  871. }
  872. )
  873. with patch(
  874. 'app.crud.research_donation._create_samples',
  875. side_effect=RuntimeError('late failure'),
  876. ):
  877. with pytest.raises(RuntimeError, match='late'):
  878. update_protocol(
  879. db,
  880. source='research_donation',
  881. protocol_id='don-update',
  882. body=body,
  883. ctx=_ctx('specialist'),
  884. user_info=_user(),
  885. )
  886. db.expire_all()
  887. assert db.get(BizResearchDonation, 'don-update').remark is None
  888. assert db.get(BizResearchDonationParty, 'dparty-old').mother_name == '旧姓名'
  889. assert db.get(BizResearchDonationParty, 'dparty-old').del_flag == 0
  890. assert db.get(BizResearchDonationSample, 'dsample-old').del_flag == 0
  891. assert db.get(BizResearchDonationCollection, 'dci-don-update').medical_staff is None
  892. def test_manager_can_update_donation_in_scope_but_cannot_move_it_out():
  893. from app.schemas.market_mobile import MarketProtocolBody
  894. from app.services.market_protocol import update_protocol
  895. db = _session()
  896. _masters(db)
  897. _donation(db, 'don-manager', sales='u2', manager='u1')
  898. db.add(
  899. BizResearchDonationParty(
  900. id='dparty-manager', research_donation_id='don-manager', mother_name='旧姓名', tenant_no='tenant-a', create_dept_id='', del_flag=0
  901. )
  902. )
  903. db.commit()
  904. result = update_protocol(
  905. db,
  906. source='research_donation',
  907. protocol_id='don-manager',
  908. body=MarketProtocolBody.model_validate(
  909. {
  910. 'source': 'research_donation',
  911. 'donationNo': 'DON-don-manager',
  912. 'remark': '经理已修改',
  913. 'customer': {'motherName': '新姓名'},
  914. 'collection': {'medicalStaff': '新医护'},
  915. }
  916. ),
  917. ctx=_ctx('manager'),
  918. user_info=_user(),
  919. )
  920. assert result['basic']['remark'] == '经理已修改'
  921. assert result['customer']['motherName'] == '新姓名'
  922. assert result['collection']['medicalStaff'] == '新医护'
  923. with pytest.raises(ValueError, match='范围'):
  924. update_protocol(
  925. db,
  926. source='research_donation',
  927. protocol_id='don-manager',
  928. body=MarketProtocolBody.model_validate(
  929. {
  930. 'source': 'research_donation',
  931. 'collection': {
  932. 'regionId': 'region-b',
  933. 'regionManagerUserId': 'manager-a',
  934. },
  935. }
  936. ),
  937. ctx=_ctx('manager'),
  938. user_info=_user(),
  939. )
  940. db.expire_all()
  941. collection = db.query(BizResearchDonationCollection).filter_by(
  942. research_donation_id='don-manager', del_flag=0
  943. ).one()
  944. assert collection.region_id == 'region-a'
  945. assert collection.region_manager_user_id == 'u1'
  946. def test_protocol_routes_expose_scoped_audit_and_delete_but_not_other_admin_mutations():
  947. from app.api.market_mobile import router
  948. for scope in ('specialist', 'manager'):
  949. prefix = f'/mini/market/{scope}/protocols/{{protocol_id}}'
  950. routes = {
  951. route.path: route.methods
  952. for route in router.routes
  953. if route.path.startswith(f'/mini/market/{scope}/protocols')
  954. }
  955. assert routes[f'{prefix}/audit'] == {'POST'}
  956. assert 'DELETE' in routes[prefix]
  957. assert all(not any(word in path for word in ('void', 'refund', 'convert', 'to-research', 'to-storage')) for path in routes)
  958. def test_protocol_audit_and_delete_recheck_scoped_access_before_crud(monkeypatch):
  959. from app.services.market_protocol import audit_protocol, delete_protocol
  960. db = _session()
  961. _masters(db)
  962. own = _cell(db, 'own', sales='u1')
  963. other = _cell(db, 'other', sales='u2')
  964. db.commit()
  965. audit_calls = []
  966. delete_calls = []
  967. monkeypatch.setattr(
  968. 'app.services.market_protocol.cell_crud.create_audit',
  969. lambda *args, **kwargs: audit_calls.append(kwargs),
  970. )
  971. monkeypatch.setattr(
  972. 'app.services.market_protocol.cell_crud.soft_delete_collection_protocol',
  973. lambda *args, **kwargs: delete_calls.append((args, kwargs)),
  974. )
  975. audit_protocol(
  976. db,
  977. source='cell_storage',
  978. protocol_id=own.id,
  979. audit_status='shtg',
  980. audit_remark='通过',
  981. ctx=_ctx('specialist'),
  982. user_info=_user(),
  983. )
  984. delete_protocol(
  985. db,
  986. source='cell_storage',
  987. protocol_id=own.id,
  988. ctx=_ctx('specialist'),
  989. user_info=_user(),
  990. )
  991. assert audit_calls[0]['collection_protocol_id'] == own.id
  992. assert delete_calls[0][0][1] == own.id
  993. with pytest.raises(HTTPException, match='无权'):
  994. audit_protocol(
  995. db,
  996. source='cell_storage',
  997. protocol_id=other.id,
  998. audit_status='shtg',
  999. audit_remark='',
  1000. ctx=_ctx('specialist'),
  1001. user_info=_user(),
  1002. )
  1003. def test_protocol_list_contains_mobile_card_fields():
  1004. from app.services.market_protocol import list_protocols
  1005. db = _session()
  1006. _masters(db)
  1007. row = _cell(db, 'card')
  1008. row.protocol_total_amount = 20000
  1009. db.add_all([
  1010. BizProtocolPartyCustomer(
  1011. id='party-card', collection_protocol_id=row.id, mother_name='李安然',
  1012. mother_phone='13800138000', mother_id_card='340100', father_name='王先生',
  1013. newborn_sex='1', delivery_mode='sc', newborn_weight_gram=3200,
  1014. tenant_no='tenant-a', create_dept_id='', del_flag=0,
  1015. ),
  1016. BizProtocolSample(
  1017. id='sample-card', collection_protocol_id=row.id, sample_type_id='type-a',
  1018. sample_code='S-CARD', tenant_no='tenant-a', create_dept_id='', del_flag=0,
  1019. ),
  1020. ])
  1021. db.commit()
  1022. items, total = list_protocols(db, ctx=_ctx('specialist'), user_info=_user())
  1023. assert total == 1
  1024. assert items[0]['motherName'] == '李安然'
  1025. assert items[0]['sampleCode'] == 'S-CARD'
  1026. assert items[0]['sampleTypeName'] == '样本A'
  1027. assert items[0]['regionName'] == 'A区'
  1028. assert items[0]['motherPhone'] == '13800138000'
  1029. assert items[0]['motherIdCard'] == '340100'
  1030. assert items[0]['fatherName'] == '王先生'
  1031. assert items[0]['newbornSex'] == '1'
  1032. assert items[0]['deliveryMode'] == 'sc'
  1033. assert items[0]['newbornWeightGram'] == 3200
  1034. assert items[0]['salesUserName'] == '当前用户'
  1035. by_customer, customer_total = list_protocols(
  1036. db, ctx=_ctx('specialist'), user_info=_user(), keyword='李安然'
  1037. )
  1038. by_sample, sample_total = list_protocols(
  1039. db, ctx=_ctx('specialist'), user_info=_user(), keyword='S-CARD'
  1040. )
  1041. assert customer_total == sample_total == 1
  1042. assert by_customer[0]['id'] == by_sample[0]['id'] == row.id
  1043. def test_cell_create_rolls_back_main_customer_and_children_on_child_failure():
  1044. from app.services.market_protocol import create_protocol
  1045. db = _session()
  1046. _masters(db)
  1047. with patch(
  1048. 'app.services.market_protocol.cell_crud.upsert_collection_info',
  1049. side_effect=RuntimeError('injected child failure'),
  1050. ):
  1051. with pytest.raises(RuntimeError, match='injected'):
  1052. create_protocol(
  1053. db, body=_body(), ctx=_ctx('specialist'), user_info=_user()
  1054. )
  1055. assert db.query(BizCollectionProtocol).count() == 0
  1056. assert db.query(BizProtocolPartyCustomer).count() == 0
  1057. assert db.query(BizCustomer).count() == 0
  1058. def test_donation_create_rolls_back_customer_and_children_on_child_failure():
  1059. from app.services.market_protocol import create_protocol
  1060. db = _session()
  1061. _masters(db)
  1062. with patch(
  1063. 'app.crud.research_donation._create_collection',
  1064. side_effect=RuntimeError('injected child failure'),
  1065. ):
  1066. with pytest.raises(RuntimeError, match='injected'):
  1067. create_protocol(
  1068. db,
  1069. body=_body(
  1070. 'research_donation', donationNo='D-ROLLBACK', protocolNo=None
  1071. ),
  1072. ctx=_ctx('specialist'),
  1073. user_info=_user(),
  1074. )
  1075. assert db.query(BizResearchDonation).count() == 0
  1076. assert db.query(BizResearchDonationParty).count() == 0
  1077. assert db.query(BizCustomer).count() == 0