test_market_support_api.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. import asyncio
  2. from types import SimpleNamespace
  3. import pytest
  4. from sqlalchemy import create_engine
  5. from sqlalchemy.orm import sessionmaker
  6. from app.models.base import Base
  7. from app.models.models import (
  8. BizAttachment,
  9. BizCellSampleType,
  10. BizCollectionHospital,
  11. BizCollectionRegion,
  12. BizCollectionRegionStaff,
  13. BizItemUnit,
  14. SysDictData,
  15. SysUser,
  16. )
  17. from app.services.market_field_scope import MarketFieldContext
  18. def _session():
  19. engine = create_engine('sqlite:///:memory:')
  20. Base.metadata.create_all(
  21. engine,
  22. tables=[
  23. BizAttachment.__table__,
  24. BizCellSampleType.__table__,
  25. BizCollectionHospital.__table__,
  26. BizCollectionRegion.__table__,
  27. BizCollectionRegionStaff.__table__,
  28. BizItemUnit.__table__,
  29. SysDictData.__table__,
  30. SysUser.__table__,
  31. ],
  32. )
  33. return sessionmaker(bind=engine)()
  34. def _ctx(scope='specialist', user_id='user-a'):
  35. return MarketFieldContext('tenant-a', user_id, scope)
  36. def _user(user_id='user-a'):
  37. return {
  38. 'user_id': user_id,
  39. 'tenant_no': 'tenant-a',
  40. 'region_id': 'dept-a',
  41. }
  42. def _seed_options(db):
  43. db.add_all(
  44. [
  45. BizCollectionRegion(id='ra', region_name='A区', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  46. BizCollectionRegion(id='rb', region_name='B区', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  47. BizCollectionRegion(id='rx', region_name='跨租户秘密区', tenant_no='tenant-b', create_dept_id='', del_flag=0),
  48. BizCollectionHospital(id='ha', region_id='ra', hospital_name='A院', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  49. BizCollectionHospital(id='hb', region_id='rb', hospital_name='B院', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  50. BizCollectionHospital(id='hx', region_id='rx', hospital_name='跨租户秘密院', tenant_no='tenant-b', create_dept_id='', del_flag=0),
  51. BizCollectionRegionStaff(id='rsa', region_id='ra', user_id='user-a', is_leader=0, tenant_no='tenant-a', create_dept_id='', del_flag=0),
  52. BizCollectionRegionStaff(id='rsb', region_id='rb', user_id='user-b', is_leader=1, tenant_no='tenant-a', create_dept_id='', del_flag=0),
  53. BizCollectionRegionStaff(id='rsa2', region_id='ra', user_id='staff-a', is_leader=0, tenant_no='tenant-a', create_dept_id='', del_flag=0),
  54. BizCollectionRegionStaff(id='rsa3', region_id='ra', user_id='leader-a', is_leader=1, tenant_no='tenant-a', create_dept_id='', del_flag=0),
  55. BizCollectionRegionStaff(id='rsx', region_id='rx', user_id='cross-user', is_leader=0, tenant_no='tenant-b', create_dept_id='', del_flag=0),
  56. SysUser(id='user-a', user_no='ua', nick_name='本人', status='1', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  57. SysUser(id='user-b', user_no='ub', nick_name='B经理', status='1', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  58. SysUser(id='staff-a', user_no='sa', nick_name='A员工', status='1', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  59. SysUser(id='leader-a', user_no='la', nick_name='A负责人', status='1', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  60. SysUser(id='disabled', user_no='off', nick_name='停用秘密', status='0', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  61. SysUser(id='cross-user', user_no='xx', nick_name='跨租户秘密用户', status='1', tenant_no='tenant-b', create_dept_id='', del_flag=0),
  62. BizCellSampleType(id='type-a', type_code='A', type_name='样本A', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  63. BizCellSampleType(id='type-x', type_code='X', type_name='跨租户秘密样本', tenant_no='tenant-b', create_dept_id='', del_flag=0),
  64. BizItemUnit(id='unit-a', unit_code='ml', unit_name='毫升', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  65. SysDictData(id='dict-pay', dict_label='微信', dict_value='wx', dict_type='zzfs', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  66. SysDictData(id='dict-freight', dict_label='专线车', dict_value='zxc', dict_type='sample_transport_mode', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  67. SysDictData(id='dict-secret', dict_label='不应泄漏', dict_value='secret', dict_type='unrelated', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  68. ]
  69. )
  70. db.commit()
  71. def test_specialist_form_options_are_region_scoped_and_minimal(monkeypatch):
  72. from app.services.market_support import get_form_options
  73. db = _session()
  74. _seed_options(db)
  75. out = get_form_options(db, module='presign', ctx=_ctx(), user_info=_user())
  76. assert out['regions'] == [{'value': 'ra', 'label': 'A区'}]
  77. assert out['hospitals'] == [{'value': 'ha', 'label': 'A院'}]
  78. assert out['staff'] == [
  79. {'value': 'leader-a', 'label': 'A负责人', 'isLeader': True},
  80. {'value': 'staff-a', 'label': 'A员工', 'isLeader': False},
  81. {'value': 'user-a', 'label': '本人', 'isLeader': False},
  82. ]
  83. assert out['sampleTypes'] == [{'value': 'type-a', 'label': '样本A'}]
  84. assert out['units'] == [{'value': 'unit-a', 'label': '毫升'}]
  85. assert out['payModes'] == [
  86. {'label': '趸交', 'value': 'dj'},
  87. {'label': '分期', 'value': 'fq'},
  88. ]
  89. assert out['orderStatuses'] == [
  90. {'label': '草稿', 'value': 'draft'},
  91. {'label': '进行中', 'value': 'active'},
  92. {'label': '已转正式', 'value': 'converted'},
  93. {'label': '已作废', 'value': 'void'},
  94. ]
  95. assert out['transferTypes'] == [{'value': 'wx', 'label': '微信'}]
  96. assert '跨租户' not in str(out)
  97. monkeypatch.setattr(
  98. 'app.services.market_support._business_region_id',
  99. lambda *args, **kwargs: 'rb',
  100. )
  101. supplemented = get_form_options(
  102. db,
  103. module='presign',
  104. ctx=_ctx(),
  105. user_info=_user(),
  106. business_id='own-document',
  107. )
  108. assert supplemented['regions'] == [
  109. {'value': 'ra', 'label': 'A区'},
  110. {'value': 'rb', 'label': 'B区'},
  111. ]
  112. def test_manager_form_options_only_include_led_regions_and_requested_region_must_be_authorized():
  113. from app.services.market_support import get_form_options
  114. db = _session()
  115. _seed_options(db)
  116. out = get_form_options(
  117. db,
  118. module='protocol',
  119. ctx=_ctx('manager', 'user-b'),
  120. user_info=_user('user-b'),
  121. region_id='rb',
  122. )
  123. assert out['regions'] == [{'value': 'rb', 'label': 'B区'}]
  124. assert out['hospitals'] == [{'value': 'hb', 'label': 'B院'}]
  125. with pytest.raises(PermissionError, match='地区'):
  126. get_form_options(
  127. db,
  128. module='protocol',
  129. ctx=_ctx('manager', 'user-b'),
  130. user_info=_user('user-b'),
  131. region_id='ra',
  132. )
  133. def test_payment_and_freight_options_use_fixed_dictionary_allowlist():
  134. from app.services.market_support import get_form_options
  135. db = _session()
  136. _seed_options(db)
  137. payment = get_form_options(db, module='payment', ctx=_ctx(), user_info=_user())
  138. freight = get_form_options(db, module='freight', ctx=_ctx(), user_info=_user())
  139. assert payment == {'transferTypes': [{'value': 'wx', 'label': '微信'}]}
  140. assert freight == {'transportModes': [{'value': 'zxc', 'label': '专线车'}]}
  141. assert '不应泄漏' not in str(payment) + str(freight)
  142. class _Storage:
  143. def __init__(self):
  144. self.uploaded = []
  145. self.deleted = []
  146. def upload_file(self, content, filename, folder):
  147. self.uploaded.append((content, filename, folder))
  148. return f'https://files.test/{folder}/generated.pdf'
  149. def delete_file(self, path):
  150. self.deleted.append(path)
  151. return True
  152. def test_upload_uses_fixed_folder_and_records_current_tenant_and_uploader():
  153. from app.services.market_support import save_market_attachment
  154. db = _session()
  155. backend = _Storage()
  156. result = save_market_attachment(
  157. db,
  158. content=b'%PDF-1.7 safe',
  159. filename='proof.pdf',
  160. content_type='application/pdf',
  161. module='payment',
  162. ctx=_ctx(),
  163. user_info=_user(),
  164. storage_backend=backend,
  165. )
  166. assert backend.uploaded[0][2] == 'market/specialist/payment'
  167. row = db.query(BizAttachment).one()
  168. assert (row.tenant_no, row.create_by, row.create_dept_id) == ('tenant-a', 'user-a', 'dept-a')
  169. assert row.business_type == 'market:specialist:payment:staging'
  170. assert result['id'] == row.id
  171. assert result['fileUrl'] == row.file_url
  172. def test_presign_upload_allows_20_mib_while_other_modules_remain_at_10_mib():
  173. from app.services.market_support import save_market_attachment
  174. content = b'%PDF-' + b'a' * (10 * 1024 * 1024)
  175. backend = _Storage()
  176. result = save_market_attachment(
  177. _session(),
  178. content=content,
  179. filename='presign-proof.pdf',
  180. content_type='application/pdf',
  181. module='presign',
  182. ctx=_ctx(),
  183. user_info=_user(),
  184. storage_backend=backend,
  185. )
  186. assert result['fileSize'] == len(content)
  187. with pytest.raises(ValueError, match='10MiB'):
  188. save_market_attachment(
  189. _session(),
  190. content=content,
  191. filename='payment-proof.pdf',
  192. content_type='application/pdf',
  193. module='payment',
  194. ctx=_ctx(),
  195. user_info=_user(),
  196. storage_backend=_Storage(),
  197. )
  198. @pytest.mark.parametrize(
  199. ('content', 'filename', 'content_type'),
  200. [
  201. (b'', 'empty.pdf', 'application/pdf'),
  202. (b'<svg/>', 'bad.svg', 'image/svg+xml'),
  203. (b'MZ', 'bad.exe', 'application/octet-stream'),
  204. (b'not an image', 'fake.jpg', 'image/jpeg'),
  205. (b'%PDF-1.7', 'fake.jpg', 'image/jpeg'),
  206. (b'\x00\x00\x00\x18junk-ftyp-heic-data', 'fake.heic', 'image/heic'),
  207. (b'\x00\x00\x00\x18ftypzzzz\x00\x00\x00\x00zzzz', 'fake.heic', 'image/heic'),
  208. (b'\x00\x00\x00\xffftypheic\x00\x00\x00\x00', 'fake.heic', 'image/heic'),
  209. (b'\x00\x00\x00\x0cftypheic', 'short.heic', 'image/heic'),
  210. (b'\x00\x00\x00\x0fftypheicabc', 'short.heic', 'image/heic'),
  211. (b'\x00\x00\x00\x15ftypheic\x00\x00\x00\x00mif1x', 'misaligned.heic', 'image/heic'),
  212. (b'\x00\x00\x00\x10ftypmif1\x00\x00\x00\x00', 'generic-only.heic', 'image/heic'),
  213. (b'PK\x03\x04not-a-docx', 'fake.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'),
  214. (b'a' * (10 * 1024 * 1024 + 1), 'huge.pdf', 'application/pdf'),
  215. ],
  216. )
  217. def test_upload_rejects_empty_oversized_or_unsafe_files(content, filename, content_type):
  218. from app.services.market_support import save_market_attachment
  219. db = _session()
  220. backend = _Storage()
  221. with pytest.raises(ValueError):
  222. save_market_attachment(
  223. db,
  224. content=content,
  225. filename=filename,
  226. content_type=content_type,
  227. module='payment',
  228. ctx=_ctx(),
  229. user_info=_user(),
  230. storage_backend=backend,
  231. )
  232. assert backend.uploaded == []
  233. def test_upload_deletes_storage_object_when_database_commit_fails(monkeypatch):
  234. from app.services.market_support import save_market_attachment
  235. db = _session()
  236. backend = _Storage()
  237. monkeypatch.setattr(db, 'commit', lambda: (_ for _ in ()).throw(RuntimeError('db down')))
  238. with pytest.raises(RuntimeError, match='db down'):
  239. save_market_attachment(
  240. db,
  241. content=b'%PDF-1.7 safe',
  242. filename='proof.pdf',
  243. content_type='application/pdf',
  244. module='protocol',
  245. ctx=_ctx(),
  246. user_info=_user(),
  247. storage_backend=backend,
  248. )
  249. assert backend.deleted == ['https://files.test/market/specialist/protocol/generated.pdf']
  250. def test_upload_never_refreshes_after_commit_or_deletes_committed_object(monkeypatch):
  251. from app.services.market_support import save_market_attachment
  252. db = _session()
  253. backend = _Storage()
  254. committed = False
  255. original_commit = db.commit
  256. original_refresh = db.refresh
  257. def tracked_commit():
  258. nonlocal committed
  259. original_commit()
  260. committed = True
  261. def refresh_only_before_commit(row):
  262. if committed:
  263. raise RuntimeError('refresh after commit is unsafe')
  264. return original_refresh(row)
  265. monkeypatch.setattr(db, 'commit', tracked_commit)
  266. monkeypatch.setattr(db, 'refresh', refresh_only_before_commit)
  267. result = save_market_attachment(
  268. db,
  269. content=b'%PDF-1.7 safe',
  270. filename='proof.pdf',
  271. content_type='application/pdf',
  272. module='protocol',
  273. ctx=_ctx(),
  274. user_info=_user(),
  275. storage_backend=backend,
  276. )
  277. assert result['id']
  278. assert backend.deleted == []
  279. def test_upload_accepts_well_formed_heif_ftyp_box_with_allowed_brand():
  280. from app.services.market_support import save_market_attachment
  281. db = _session()
  282. backend = _Storage()
  283. content = b'\x00\x00\x00\x14ftypheic\x00\x00\x00\x00mif1'
  284. result = save_market_attachment(
  285. db,
  286. content=content,
  287. filename='photo.heic',
  288. content_type='image/heic',
  289. module='sample',
  290. ctx=_ctx(),
  291. user_info=_user(),
  292. storage_backend=backend,
  293. )
  294. assert result['fileType'] == 'image/heic'
  295. assert backend.uploaded[0][0] == content
  296. def test_heif_extension_accepts_generic_heif_brand():
  297. from app.services.market_support import save_market_attachment
  298. db = _session()
  299. backend = _Storage()
  300. content = b'\x00\x00\x00\x10ftypmif1\x00\x00\x00\x00'
  301. result = save_market_attachment(
  302. db,
  303. content=content,
  304. filename='photo.heif',
  305. content_type='image/heif',
  306. module='sample',
  307. ctx=_ctx(),
  308. user_info=_user(),
  309. storage_backend=backend,
  310. )
  311. assert result['fileType'] == 'image/heif'
  312. def _attachment(**overrides):
  313. values = dict(
  314. id='att-a',
  315. business_type='market:specialist:payment:staging',
  316. business_id=None,
  317. original_name='proof.pdf',
  318. file_ext='pdf',
  319. file_url='market/specialist/payment/a.pdf',
  320. file_size=12,
  321. file_type='application/pdf',
  322. tenant_no='tenant-a',
  323. create_by='user-a',
  324. create_dept_id='',
  325. del_flag=0,
  326. )
  327. values.update(overrides)
  328. return BizAttachment(**values)
  329. def test_create_attachment_refs_require_current_uploader_staging_exact_match():
  330. from app.services.market_support import validate_attachment_refs
  331. db = _session()
  332. db.add_all(
  333. [
  334. _attachment(),
  335. _attachment(id='att-other', file_url='market/specialist/payment/other.pdf', create_by='other'),
  336. _attachment(id='att-cross', file_url='market/specialist/payment/cross.pdf', tenant_no='tenant-b'),
  337. ]
  338. )
  339. db.commit()
  340. assert validate_attachment_refs(
  341. db,
  342. 'att-a,market/specialist/payment/a.pdf',
  343. module='payment',
  344. ctx=_ctx(),
  345. creating=True,
  346. ) == 'market/specialist/payment/a.pdf'
  347. for invalid in ('att-other', 'att-cross', 'https://evil.test/a.pdf', 'a.pdf'):
  348. with pytest.raises(ValueError, match='附件'):
  349. validate_attachment_refs(db, invalid, module='payment', ctx=_ctx(), creating=True)
  350. def test_staging_attachment_must_match_current_scope_role_exactly():
  351. from app.services.market_support import validate_attachment_refs
  352. db = _session()
  353. db.add(
  354. _attachment(
  355. id='manager-staging',
  356. business_type='market:manager:payment:staging',
  357. file_url='market/manager/payment/proof.pdf',
  358. )
  359. )
  360. db.commit()
  361. with pytest.raises(ValueError, match='附件'):
  362. validate_attachment_refs(
  363. db,
  364. 'manager-staging',
  365. module='payment',
  366. ctx=_ctx('specialist'),
  367. creating=True,
  368. business_id='pay-a',
  369. )
  370. def test_attachment_refs_bind_once_to_exact_scope_module_and_business():
  371. from app.services.market_support import validate_attachment_refs
  372. db = _session()
  373. row = _attachment()
  374. db.add(row)
  375. db.commit()
  376. result = validate_attachment_refs(
  377. db,
  378. 'att-a,market/specialist/payment/a.pdf',
  379. module='payment',
  380. ctx=_ctx(),
  381. creating=True,
  382. business_id='transfer-a',
  383. )
  384. assert result == 'market/specialist/payment/a.pdf'
  385. assert (row.business_type, row.business_id) == (
  386. 'market:specialist:payment:bound',
  387. 'transfer-a',
  388. )
  389. assert validate_attachment_refs(
  390. db,
  391. 'att-a',
  392. module='payment',
  393. ctx=_ctx(),
  394. creating=False,
  395. business_id='transfer-a',
  396. ) == 'market/specialist/payment/a.pdf'
  397. with pytest.raises(ValueError, match='附件'):
  398. validate_attachment_refs(
  399. db,
  400. 'att-a',
  401. module='payment',
  402. ctx=_ctx(),
  403. creating=False,
  404. business_id='transfer-b',
  405. )
  406. with pytest.raises(ValueError, match='附件'):
  407. validate_attachment_refs(
  408. db,
  409. 'att-a',
  410. module='payment',
  411. ctx=_ctx('manager'),
  412. creating=False,
  413. business_id='transfer-a',
  414. )
  415. def test_attachment_ref_resolution_uses_one_batched_query_and_deduplicates_aliases():
  416. from sqlalchemy import event
  417. from app.services.market_support import validate_attachment_refs
  418. db = _session()
  419. db.add_all(
  420. [
  421. _attachment(id='att-1', file_url='market/specialist/payment/1.pdf'),
  422. _attachment(id='att-2', file_url='market/specialist/payment/2.pdf'),
  423. ]
  424. )
  425. db.commit()
  426. statements = []
  427. def capture(_conn, _cursor, statement, _parameters, _context, _many):
  428. if 'biz_attachment' in statement.lower() and statement.lstrip().lower().startswith('select'):
  429. statements.append(statement)
  430. event.listen(db.get_bind(), 'before_cursor_execute', capture)
  431. try:
  432. result = validate_attachment_refs(
  433. db,
  434. 'att-1,market/specialist/payment/1.pdf,att-2',
  435. module='payment',
  436. ctx=_ctx(),
  437. creating=True,
  438. business_id='transfer-batch',
  439. )
  440. finally:
  441. event.remove(db.get_bind(), 'before_cursor_execute', capture)
  442. assert result == 'market/specialist/payment/1.pdf,market/specialist/payment/2.pdf'
  443. assert len(statements) == 1
  444. @pytest.mark.parametrize(
  445. 'refs',
  446. [','.join(f'att-{index}' for index in range(21)), 'x' * 4001],
  447. )
  448. def test_attachment_refs_reject_excessive_count_or_total_length(refs):
  449. from app.services.market_support import validate_attachment_refs
  450. with pytest.raises(ValueError, match='附件'):
  451. validate_attachment_refs(
  452. _session(),
  453. refs,
  454. module='payment',
  455. ctx=_ctx(),
  456. creating=True,
  457. business_id='transfer-limit',
  458. )
  459. def test_all_mobile_attachment_schemas_cap_total_reference_length():
  460. from pydantic import ValidationError
  461. from app.schemas.market_mobile import (
  462. MarketPaymentTransferBody,
  463. MarketPresignTransferBody,
  464. MarketProtocolAttachmentsBody,
  465. MarketSampleStorageCertBody,
  466. )
  467. too_long = 'x' * 4001
  468. payloads = (
  469. (MarketPresignTransferBody, {'transferAttachments': too_long}),
  470. (MarketProtocolAttachmentsBody, {'protocolAttachments': too_long}),
  471. (MarketPaymentTransferBody, {'transferAttachments': too_long}),
  472. (MarketSampleStorageCertBody, {'attachments': too_long}),
  473. )
  474. for schema, payload in payloads:
  475. with pytest.raises(ValidationError):
  476. schema.model_validate(payload)
  477. def test_update_attachment_refs_allow_exact_existing_refs_and_current_user_new_only():
  478. from app.services.market_support import validate_attachment_refs
  479. db = _session()
  480. db.add_all(
  481. [
  482. _attachment(
  483. id='existing',
  484. file_url='market/specialist/payment/existing.pdf',
  485. create_by='legacy',
  486. business_type='market:specialist:payment:bound',
  487. business_id='transfer-existing',
  488. ),
  489. _attachment(id='new', file_url='market/specialist/payment/new.pdf'),
  490. ]
  491. )
  492. db.commit()
  493. out = validate_attachment_refs(
  494. db,
  495. 'existing,new',
  496. module='payment',
  497. ctx=_ctx(),
  498. creating=False,
  499. existing_refs='market/specialist/payment/existing.pdf',
  500. business_id='transfer-existing',
  501. )
  502. assert out == 'market/specialist/payment/existing.pdf,market/specialist/payment/new.pdf'
  503. @pytest.mark.parametrize('metadata_kind', ['missing', 'legacy-unbound', 'other-role-bound'])
  504. def test_update_may_retain_exact_server_supplied_existing_url_without_current_metadata(
  505. metadata_kind,
  506. ):
  507. from app.services.market_support import validate_attachment_refs
  508. db = _session()
  509. existing_url = 'legacy/payment/existing.pdf'
  510. if metadata_kind == 'legacy-unbound':
  511. db.add(
  512. _attachment(
  513. id='legacy-unbound',
  514. file_url=existing_url,
  515. business_type='protocol',
  516. create_by='legacy-user',
  517. )
  518. )
  519. elif metadata_kind == 'other-role-bound':
  520. db.add(
  521. _attachment(
  522. id='specialist-bound',
  523. file_url=existing_url,
  524. business_type='market:specialist:payment:bound',
  525. business_id='transfer-existing',
  526. create_by='specialist-user',
  527. )
  528. )
  529. db.commit()
  530. assert validate_attachment_refs(
  531. db,
  532. existing_url,
  533. module='payment',
  534. ctx=_ctx('manager'),
  535. creating=False,
  536. existing_refs=existing_url,
  537. business_id='transfer-existing',
  538. ) == existing_url
  539. def test_existing_ref_exception_allows_removal_but_not_arbitrary_url_smuggling():
  540. from app.services.market_support import validate_attachment_refs
  541. db = _session()
  542. assert validate_attachment_refs(
  543. db,
  544. '',
  545. module='payment',
  546. ctx=_ctx(),
  547. creating=False,
  548. existing_refs='legacy/payment/existing.pdf',
  549. business_id='transfer-existing',
  550. ) == ''
  551. with pytest.raises(ValueError, match='附件'):
  552. validate_attachment_refs(
  553. db,
  554. 'https://evil.test/smuggled.pdf',
  555. module='payment',
  556. ctx=_ctx(),
  557. creating=False,
  558. existing_refs='legacy/payment/existing.pdf',
  559. business_id='transfer-existing',
  560. )
  561. def test_allowed_actions_are_state_scope_and_permission_aware():
  562. from app.services.market_support import allowed_actions
  563. assert allowed_actions('presign', status='active') == ['edit', 'convert', 'delete']
  564. assert allowed_actions('presign', status='void') == ['edit', 'delete']
  565. assert allowed_actions('presign', status='converted') == ['edit']
  566. assert allowed_actions('presign-transfer', status='dfj') == ['edit', 'delete', 'submit']
  567. assert allowed_actions('presign-transfer', status='jfqrz') == ['withdraw']
  568. assert allowed_actions('presign-transfer', status='yjf') == []
  569. assert allowed_actions('protocol', status='dsx') == ['edit']
  570. assert allowed_actions('protocol', status='yzz') == []
  571. assert allowed_actions('payment-transfer', status='dfj') == ['edit-transfer', 'submit-finance']
  572. assert allowed_actions('payment-transfer', status='jfqrz') == ['withdraw-transfer']
  573. assert allowed_actions('payment-chase', status='', has_payment_permission=False) == []
  574. assert allowed_actions('payment-chase', status='', has_payment_permission=True) == ['register-transfer']
  575. assert allowed_actions('sample', status='', source='research_donation', has_sample_code=True) == []
  576. assert allowed_actions('sample', status='', source='cell_storage', has_sample_code=True) == ['storage-cert', 'insurance']
  577. assert allowed_actions('freight', status='', scope_kind='specialist') == []
  578. assert allowed_actions('freight', status='', scope_kind='manager') == ['edit']
  579. assert allowed_actions('presign-list', status='') == ['create']
  580. assert allowed_actions('protocol-list', status='') == ['create']
  581. assert allowed_actions('freight-list', status='', scope_kind='specialist') == ['create']
  582. def test_presign_actions_include_delete_and_nested_transfer_actions():
  583. from app.services.market_support import decorate_allowed_actions
  584. active = decorate_allowed_actions(
  585. 'presign',
  586. {
  587. 'orderStatus': 'active',
  588. 'transfers': [
  589. {'id': 't1', 'payStatus': 'dfj'},
  590. {'id': 't2', 'payStatus': 'jfqrz'},
  591. {'id': 't3', 'payStatus': 'yjf'},
  592. ],
  593. },
  594. scope_kind='specialist',
  595. detail=True,
  596. )
  597. assert active['allowedActions'] == ['edit', 'convert', 'delete']
  598. assert [row['allowedActions'] for row in active['transfers']] == [
  599. ['edit', 'delete', 'submit'],
  600. ['withdraw'],
  601. [],
  602. ]
  603. for parent_status, parent_actions in (
  604. ('converted', ['edit']),
  605. ('void', ['edit', 'delete']),
  606. ):
  607. locked = decorate_allowed_actions(
  608. 'presign',
  609. {
  610. 'orderStatus': parent_status,
  611. 'transfers': [
  612. {'id': 't1', 'payStatus': 'dfj'},
  613. {'id': 't2', 'payStatus': 'jfqrz'},
  614. ],
  615. },
  616. scope_kind='specialist',
  617. detail=True,
  618. )
  619. assert locked['allowedActions'] == parent_actions
  620. assert [row['allowedActions'] for row in locked['transfers']] == [[], []]
  621. unknown = decorate_allowed_actions(
  622. 'presign',
  623. {
  624. 'orderStatus': 'legacy-locked',
  625. 'transfers': [{'id': 't1', 'payStatus': 'dfj'}],
  626. },
  627. scope_kind='specialist',
  628. detail=True,
  629. )
  630. assert unknown['transfers'][0]['allowedActions'] == []
  631. def test_form_options_do_not_leak_children_of_soft_deleted_regions():
  632. from app.services.market_support import get_form_options
  633. db = _session()
  634. _seed_options(db)
  635. db.add_all(
  636. [
  637. BizCollectionRegion(
  638. id='deleted-region',
  639. region_name='已删除地区',
  640. tenant_no='tenant-a',
  641. create_dept_id='',
  642. del_flag=1,
  643. ),
  644. BizCollectionHospital(
  645. id='deleted-region-hospital',
  646. region_id='deleted-region',
  647. hospital_name='不应泄漏医院',
  648. tenant_no='tenant-a',
  649. create_dept_id='',
  650. del_flag=0,
  651. ),
  652. BizCollectionRegionStaff(
  653. id='deleted-region-staff',
  654. region_id='deleted-region',
  655. user_id='user-a',
  656. is_leader=0,
  657. tenant_no='tenant-a',
  658. create_dept_id='',
  659. del_flag=0,
  660. ),
  661. ]
  662. )
  663. db.commit()
  664. out = get_form_options(db, module='presign', ctx=_ctx(), user_info=_user())
  665. assert '已删除地区' not in str(out)
  666. assert '不应泄漏医院' not in str(out)
  667. with pytest.raises(PermissionError, match='地区'):
  668. get_form_options(
  669. db,
  670. module='presign',
  671. ctx=_ctx(),
  672. user_info=_user(),
  673. region_id='deleted-region',
  674. )
  675. def test_decorate_allowed_actions_covers_nested_payment_transfers():
  676. from app.services.market_support import decorate_allowed_actions
  677. detail = {
  678. 'id': 'pay-a',
  679. 'schedules': [
  680. {
  681. 'id': 'schedule-a',
  682. 'scheduleStatus': 'open',
  683. 'transfers': [
  684. {'id': 'draft', 'payStatus': 'dfj'},
  685. {'id': 'submitted', 'payStatus': 'jfqrz'},
  686. {'id': 'done', 'payStatus': 'yjf'},
  687. ],
  688. }
  689. ],
  690. }
  691. out = decorate_allowed_actions('payment', detail, scope_kind='specialist')
  692. assert out['allowedActions'] == ['register-transfer']
  693. assert out['schedules'][0]['allowedActions'] == ['register-transfer']
  694. assert [row['allowedActions'] for row in out['schedules'][0]['transfers']] == [
  695. ['edit-transfer', 'submit-finance'],
  696. ['withdraw-transfer'],
  697. [],
  698. ]
  699. @pytest.mark.parametrize('protocol_status', ['yzf', 'sdfq', 'zky'])
  700. def test_payment_terminal_protocol_removes_all_nested_write_actions(protocol_status):
  701. from app.services.market_support import decorate_allowed_actions
  702. detail = {
  703. 'id': 'pay-terminal',
  704. 'protocolStatus': protocol_status,
  705. 'schedules': [
  706. {
  707. 'id': 'schedule-open',
  708. 'scheduleStatus': 'open',
  709. 'transfers': [
  710. {'id': 'draft', 'payStatus': 'dfj'},
  711. {'id': 'submitted', 'payStatus': 'jfqrz'},
  712. ],
  713. }
  714. ],
  715. }
  716. out = decorate_allowed_actions('payment', detail, scope_kind='specialist')
  717. assert out['allowedActions'] == []
  718. assert out['schedules'][0]['allowedActions'] == []
  719. assert [row['allowedActions'] for row in out['schedules'][0]['transfers']] == [[], []]
  720. @pytest.mark.parametrize('schedule_status', ['cleared', 'void'])
  721. def test_non_open_payment_schedule_removes_schedule_and_transfer_actions(schedule_status):
  722. from app.services.market_support import decorate_allowed_actions
  723. detail = {
  724. 'id': 'pay-closed',
  725. 'protocolStatus': 'sxz',
  726. 'schedules': [
  727. {
  728. 'id': 'schedule-closed',
  729. 'scheduleStatus': schedule_status,
  730. 'transfers': [{'id': 'draft', 'payStatus': 'dfj'}],
  731. }
  732. ],
  733. }
  734. out = decorate_allowed_actions('payment', detail, scope_kind='specialist')
  735. assert out['allowedActions'] == []
  736. assert out['schedules'][0]['allowedActions'] == []
  737. assert out['schedules'][0]['transfers'][0]['allowedActions'] == []
  738. def test_freight_detail_exposes_only_scope_safe_link_actions():
  739. from app.services.market_support import decorate_allowed_actions
  740. specialist = decorate_allowed_actions(
  741. 'freight',
  742. {'id': 'f1', 'allowedActions': ['edit', 'link', 'unlink']},
  743. scope_kind='specialist',
  744. detail=True,
  745. )
  746. manager = decorate_allowed_actions(
  747. 'freight',
  748. {'id': 'f1', 'allowedActions': ['link', 'unlink']},
  749. scope_kind='manager',
  750. detail=True,
  751. )
  752. assert specialist['allowedActions'] == ['edit', 'link', 'unlink']
  753. assert manager['allowedActions'] == ['link', 'unlink']
  754. def test_protocol_detail_action_reads_nested_basic_status():
  755. from app.services.market_support import decorate_allowed_actions
  756. active = decorate_allowed_actions(
  757. 'protocol', {'basic': {'protocolStatus': 'dsx'}}, scope_kind='specialist'
  758. )
  759. terminal = decorate_allowed_actions(
  760. 'protocol', {'basic': {'protocolStatus': 'yzf'}}, scope_kind='specialist'
  761. )
  762. assert active['allowedActions'] == ['edit']
  763. assert terminal['allowedActions'] == []
  764. def test_market_support_routes_are_fixed_and_registered_before_dynamic_details():
  765. from app.api.market_mobile import router
  766. paths = [route.path for route in router.routes]
  767. for scope in ('specialist', 'manager'):
  768. for path in (
  769. f'/mini/market/{scope}/presign-orders/form-options',
  770. f'/mini/market/{scope}/protocols/form-options',
  771. f'/mini/market/{scope}/payments/form-options',
  772. f'/mini/market/{scope}/samples/form-options',
  773. f'/mini/market/{scope}/freights/form-options',
  774. ):
  775. assert path in paths
  776. for module in ('presign', 'protocol', 'payment', 'sample'):
  777. upload_path = f'/mini/market/{scope}/{module}/attachments'
  778. assert upload_path in paths
  779. upload_route = next(route for route in router.routes if route.path == upload_path)
  780. assert [param.name for param in upload_route.dependant.query_params] == []
  781. assert paths.index(f'/mini/market/{scope}/presign-orders/form-options') < paths.index(
  782. f'/mini/market/{scope}/presign-orders/{{order_id}}'
  783. )
  784. assert paths.index(f'/mini/market/{scope}/protocols/form-options') < paths.index(
  785. f'/mini/market/{scope}/protocols/{{protocol_id}}'
  786. )
  787. assert paths.index(f'/mini/market/{scope}/samples/form-options') < paths.index(
  788. f'/mini/market/{scope}/samples/{{sample_id}}'
  789. )
  790. def test_presign_write_routes_use_fixed_paths_and_methods():
  791. from app.api.market_mobile import router
  792. for scope in ('specialist', 'manager'):
  793. expected = {
  794. f'/mini/market/{scope}/presign-orders/{{order_id}}': {'GET', 'PUT', 'DELETE'},
  795. f'/mini/market/{scope}/presign-orders/{{order_id}}/transfers': {'POST'},
  796. f'/mini/market/{scope}/presign-transfers/{{transfer_id}}': {'PUT', 'DELETE'},
  797. f'/mini/market/{scope}/presign-transfers/{{transfer_id}}/submit': {'POST'},
  798. f'/mini/market/{scope}/presign-transfers/{{transfer_id}}/withdraw': {'POST'},
  799. }
  800. for path, methods in expected.items():
  801. registered = {
  802. method
  803. for route in router.routes
  804. if route.path == path
  805. for method in route.methods
  806. }
  807. assert registered == methods
  808. def test_presign_write_routes_map_permission_and_validation_errors(monkeypatch):
  809. from app.api import market_mobile
  810. from app.schemas.market_mobile import MarketPresignTransferBody
  811. delete_route = next(
  812. route
  813. for route in market_mobile.router.routes
  814. if route.path == '/mini/market/specialist/presign-orders/{order_id}'
  815. and route.methods == {'DELETE'}
  816. )
  817. create_transfer_route = next(
  818. route
  819. for route in market_mobile.router.routes
  820. if route.path
  821. == '/mini/market/specialist/presign-orders/{order_id}/transfers'
  822. )
  823. monkeypatch.setattr(
  824. market_mobile.market_presign,
  825. 'delete_presign_order',
  826. lambda *args, **kwargs: (_ for _ in ()).throw(PermissionError('forbidden')),
  827. )
  828. permission_result = asyncio.run(
  829. delete_route.endpoint(order_id='o1', user=_user(), db=SimpleNamespace())
  830. )
  831. assert permission_result['code'] == 403
  832. monkeypatch.setattr(
  833. market_mobile.market_presign,
  834. 'create_presign_transfer',
  835. lambda *args, **kwargs: (_ for _ in ()).throw(ValueError('invalid')),
  836. )
  837. validation_result = asyncio.run(
  838. create_transfer_route.endpoint(
  839. order_id='o1',
  840. body=MarketPresignTransferBody(transferAmount=100),
  841. user=_user(),
  842. db=SimpleNamespace(),
  843. )
  844. )
  845. assert validation_result['code'] == 400
  846. def test_attachment_routes_read_only_their_module_upload_limit(monkeypatch):
  847. from app.api import market_mobile
  848. class TrackingUpload:
  849. filename = 'proof.pdf'
  850. content_type = 'application/pdf'
  851. def __init__(self):
  852. self.read_size = None
  853. async def read(self, size):
  854. self.read_size = size
  855. return b'%PDF-safe'
  856. async def close(self):
  857. return None
  858. monkeypatch.setattr(
  859. market_mobile.market_support,
  860. 'save_market_attachment',
  861. lambda *args, **kwargs: {'id': 'attachment'},
  862. )
  863. routes = {
  864. route.path: route
  865. for route in market_mobile.router.routes
  866. if route.path in {
  867. '/mini/market/specialist/presign/attachments',
  868. '/mini/market/specialist/payment/attachments',
  869. }
  870. }
  871. presign_file = TrackingUpload()
  872. payment_file = TrackingUpload()
  873. asyncio.run(
  874. routes['/mini/market/specialist/presign/attachments'].endpoint(
  875. file=presign_file, user=_user(), db=SimpleNamespace()
  876. )
  877. )
  878. asyncio.run(
  879. routes['/mini/market/specialist/payment/attachments'].endpoint(
  880. file=payment_file, user=_user(), db=SimpleNamespace()
  881. )
  882. )
  883. assert presign_file.read_size == 20 * 1024 * 1024 + 1
  884. assert payment_file.read_size == 10 * 1024 * 1024 + 1