test_market_support_api.py 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119
  1. import asyncio
  2. from decimal import Decimal
  3. from io import BytesIO
  4. from types import SimpleNamespace
  5. from zipfile import ZipFile
  6. import pytest
  7. from sqlalchemy import create_engine
  8. from sqlalchemy.orm import sessionmaker
  9. from app.models.base import Base
  10. from app.models.models import (
  11. BizAttachment,
  12. BizCellSampleType,
  13. BizCollectionHospital,
  14. BizCollectionProtocol,
  15. BizCollectionRegion,
  16. BizCollectionRegionStaff,
  17. BizItemUnit,
  18. BizProtocolCollectionInfo,
  19. BizProtocolFullmoonTodo,
  20. BizProtocolPayment,
  21. BizProtocolPaymentDetail,
  22. BizProtocolSample,
  23. BizProtocolStorageCert,
  24. BizSampleCode,
  25. SysPost,
  26. SysPostRole,
  27. SysRole,
  28. SysRoleDataScopeDetail,
  29. SysDictData,
  30. SysEthnic,
  31. SysUser,
  32. SysUserPost,
  33. SysUserRole,
  34. )
  35. from app.models.research_donation import (
  36. BizResearchDonation,
  37. BizResearchDonationCollection,
  38. BizResearchDonationSample,
  39. )
  40. from app.services import market_support
  41. from app.services.market_field_scope import MarketFieldContext
  42. def _session():
  43. engine = create_engine('sqlite:///:memory:')
  44. Base.metadata.create_all(
  45. engine,
  46. tables=[
  47. BizAttachment.__table__,
  48. BizCellSampleType.__table__,
  49. BizCollectionHospital.__table__,
  50. BizCollectionProtocol.__table__,
  51. BizCollectionRegion.__table__,
  52. BizCollectionRegionStaff.__table__,
  53. BizItemUnit.__table__,
  54. BizProtocolSample.__table__,
  55. BizResearchDonationSample.__table__,
  56. BizSampleCode.__table__,
  57. SysDictData.__table__,
  58. SysEthnic.__table__,
  59. SysUser.__table__,
  60. ],
  61. )
  62. return sessionmaker(bind=engine)()
  63. def _ctx(scope='specialist', user_id='user-a'):
  64. return MarketFieldContext('tenant-a', user_id, scope)
  65. def _user(user_id='user-a'):
  66. return {
  67. 'user_id': user_id,
  68. 'tenant_no': 'tenant-a',
  69. 'region_id': 'dept-a',
  70. }
  71. def _seed_options(db):
  72. db.add_all(
  73. [
  74. BizCollectionRegion(id='ra', region_name='A区', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  75. BizCollectionRegion(id='rb', region_name='B区', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  76. BizCollectionRegion(id='rx', region_name='跨租户秘密区', tenant_no='tenant-b', create_dept_id='', del_flag=0),
  77. BizCollectionHospital(id='ha', region_id='ra', hospital_name='A院', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  78. BizCollectionHospital(id='hb', region_id='rb', hospital_name='B院', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  79. BizCollectionHospital(id='hx', region_id='rx', hospital_name='跨租户秘密院', tenant_no='tenant-b', create_dept_id='', del_flag=0),
  80. BizCollectionRegionStaff(id='rsa', region_id='ra', user_id='user-a', is_leader=0, tenant_no='tenant-a', create_dept_id='', del_flag=0),
  81. BizCollectionRegionStaff(id='rsb', region_id='rb', user_id='user-b', is_leader=1, tenant_no='tenant-a', create_dept_id='', del_flag=0),
  82. BizCollectionRegionStaff(id='rsa2', region_id='ra', user_id='staff-a', is_leader=0, tenant_no='tenant-a', create_dept_id='', del_flag=0),
  83. BizCollectionRegionStaff(id='rsa3', region_id='ra', user_id='leader-a', is_leader=1, tenant_no='tenant-a', create_dept_id='', del_flag=0),
  84. BizCollectionRegionStaff(id='rsx', region_id='rx', user_id='cross-user', is_leader=0, tenant_no='tenant-b', create_dept_id='', del_flag=0),
  85. SysUser(id='user-a', user_no='ua', nick_name='本人', status='1', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  86. SysUser(id='user-b', user_no='ub', nick_name='B经理', status='1', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  87. SysUser(id='staff-a', user_no='sa', nick_name='A员工', status='1', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  88. SysUser(id='leader-a', user_no='la', nick_name='A负责人', status='1', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  89. SysUser(id='disabled', user_no='off', nick_name='停用秘密', status='0', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  90. SysUser(id='cross-user', user_no='xx', nick_name='跨租户秘密用户', status='1', tenant_no='tenant-b', create_dept_id='', del_flag=0),
  91. BizCellSampleType(
  92. id='type-a',
  93. type_code='A',
  94. type_name='样本A',
  95. storage_price=Decimal('25880.00'),
  96. storage_years=20,
  97. tenant_no='tenant-a',
  98. create_dept_id='',
  99. del_flag=0,
  100. ),
  101. BizCellSampleType(
  102. id='type-x',
  103. type_code='X',
  104. type_name='跨租户秘密样本',
  105. storage_price=Decimal('9999999999999999.99'),
  106. storage_years=99,
  107. tenant_no='tenant-b',
  108. create_dept_id='',
  109. del_flag=0,
  110. ),
  111. BizItemUnit(id='unit-a', unit_code='ml', unit_name='毫升', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  112. BizSampleCode(id='sample-code-a', sample_code='S-001', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  113. SysEthnic(id='ethnic-han', ethnic_name='汉族', ethnic_code='01', tenant_no='', create_dept_id='', del_flag=0),
  114. SysDictData(id='dict-pay', dict_label='微信', dict_value='wx', dict_type='zzfs', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  115. SysDictData(id='dict-freight', dict_label='专线车', dict_value='zxc', dict_type='sample_transport_mode', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  116. SysDictData(id='dict-secret', dict_label='不应泄漏', dict_value='secret', dict_type='unrelated', tenant_no='tenant-a', create_dept_id='', del_flag=0),
  117. ]
  118. )
  119. db.commit()
  120. def test_specialist_form_options_list_all_tenant_regions_like_web(monkeypatch):
  121. """市场专员采集地区选项应与 Web 一致:本租户全部地区,不依赖人员绑定。"""
  122. from app.services.market_support import get_form_options
  123. db = _session()
  124. _seed_options(db)
  125. # 未绑定任何采集地区的专员仍应能选到租户内地区(对齐 Web 预签表单)
  126. unbound = get_form_options(
  127. db,
  128. module='presign',
  129. ctx=_ctx('specialist', 'staff-unbound'),
  130. user_info=_user('staff-unbound'),
  131. )
  132. assert unbound['regions'] == [
  133. {'value': 'ra', 'label': 'A区'},
  134. {'value': 'rb', 'label': 'B区'},
  135. ]
  136. assert '跨租户' not in str(unbound)
  137. out = get_form_options(db, module='presign', ctx=_ctx(), user_info=_user())
  138. assert out['regions'] == [
  139. {'value': 'ra', 'label': 'A区'},
  140. {'value': 'rb', 'label': 'B区'},
  141. ]
  142. assert out['hospitals'] == [
  143. {'value': 'ha', 'label': 'A院'},
  144. {'value': 'hb', 'label': 'B院'},
  145. ]
  146. assert {row['value'] for row in out['staff']} >= {
  147. 'leader-a',
  148. 'staff-a',
  149. 'user-a',
  150. 'user-b',
  151. }
  152. assert out['sampleTypes'] == [{'value': 'type-a', 'label': '样本A'}]
  153. assert out['units'] == [{'value': 'unit-a', 'label': '毫升'}]
  154. assert out['payModes'] == [
  155. {'label': '趸交', 'value': 'dj'},
  156. {'label': '分期', 'value': 'fq'},
  157. ]
  158. assert out['orderStatuses'] == [
  159. {'label': '草稿', 'value': 'draft'},
  160. {'label': '进行中', 'value': 'active'},
  161. {'label': '已转正式', 'value': 'converted'},
  162. {'label': '已作废', 'value': 'void'},
  163. ]
  164. assert out['transferTypes'] == [{'value': 'wx', 'label': '微信'}]
  165. assert out['currentUser'] == {'value': 'user-a', 'label': '本人'}
  166. assert '跨租户' not in str(out)
  167. scoped = get_form_options(
  168. db,
  169. module='presign',
  170. ctx=_ctx(),
  171. user_info=_user(),
  172. region_id='ra',
  173. )
  174. assert scoped['regions'] == [
  175. {'value': 'ra', 'label': 'A区'},
  176. {'value': 'rb', 'label': 'B区'},
  177. ]
  178. assert scoped['hospitals'] == [{'value': 'ha', 'label': 'A院'}]
  179. assert scoped['staff'] == [
  180. {'value': 'leader-a', 'label': 'A负责人', 'isLeader': True},
  181. {'value': 'staff-a', 'label': 'A员工', 'isLeader': False},
  182. {'value': 'user-a', 'label': '本人', 'isLeader': False},
  183. ]
  184. monkeypatch.setattr(
  185. 'app.services.market_support._business_region_id',
  186. lambda *args, **kwargs: 'rb',
  187. )
  188. supplemented = get_form_options(
  189. db,
  190. module='presign',
  191. ctx=_ctx(),
  192. user_info=_user(),
  193. business_id='own-document',
  194. )
  195. assert supplemented['regions'] == [
  196. {'value': 'ra', 'label': 'A区'},
  197. {'value': 'rb', 'label': 'B区'},
  198. ]
  199. def test_manager_form_options_list_all_tenant_regions_like_web():
  200. from app.services.market_support import get_form_options
  201. db = _session()
  202. _seed_options(db)
  203. out = get_form_options(
  204. db,
  205. module='protocol',
  206. ctx=_ctx('manager', 'user-b'),
  207. user_info=_user('user-b'),
  208. region_id='rb',
  209. )
  210. assert out['regions'] == [
  211. {'value': 'ra', 'label': 'A区'},
  212. {'value': 'rb', 'label': 'B区'},
  213. ]
  214. assert out['hospitals'] == [{'value': 'hb', 'label': 'B院'}]
  215. assert out['ethnicities'] == [{'value': '汉族', 'label': '汉族'}]
  216. assert out['sampleCodes'] == [
  217. {'value': 'sample-code-a', 'label': 'S-001', 'sampleCode': 'S-001'}
  218. ]
  219. # 级联医院可按任意本租户地区加载;跨租户地区仍拒绝
  220. other = get_form_options(
  221. db,
  222. module='protocol',
  223. ctx=_ctx('manager', 'user-b'),
  224. user_info=_user('user-b'),
  225. region_id='ra',
  226. )
  227. assert other['hospitals'] == [{'value': 'ha', 'label': 'A院'}]
  228. with pytest.raises(PermissionError, match='地区'):
  229. get_form_options(
  230. db,
  231. module='protocol',
  232. ctx=_ctx('manager', 'user-b'),
  233. user_info=_user('user-b'),
  234. region_id='rx',
  235. )
  236. def test_protocol_sample_type_options_keep_exact_defaults_and_tenant_scope():
  237. from app.services.market_support import get_form_options
  238. db = _session()
  239. _seed_options(db)
  240. max_type = BizCellSampleType(
  241. id='type-max',
  242. type_code='MAX',
  243. type_name='最大金额样本',
  244. storage_price=Decimal('9999999999999999.99'),
  245. storage_years=30,
  246. tenant_no='tenant-a',
  247. create_dept_id='',
  248. del_flag=0,
  249. )
  250. null_type = BizCellSampleType(
  251. id='type-null',
  252. type_code='NULL',
  253. type_name='未配置样本',
  254. storage_price=None,
  255. storage_years=None,
  256. tenant_no='tenant-a',
  257. create_dept_id='',
  258. del_flag=0,
  259. )
  260. db.add_all([max_type, null_type])
  261. # SQLite 会把超出双精度安全范围的 NUMERIC 值以 REAL 回读;保持本次
  262. # flush 后的 Decimal 实例在 identity map 中,测试生产 MySQL 返回 Decimal
  263. # 时的实际 API 序列化路径,而不是 SQLite 方言自身的精度损失。
  264. db.flush()
  265. out = get_form_options(
  266. db,
  267. module='protocol',
  268. ctx=_ctx('manager', 'user-b'),
  269. user_info=_user('user-b'),
  270. region_id='rb',
  271. )
  272. sample_types = {item['value']: item for item in out['sampleTypes']}
  273. assert sample_types == {
  274. 'type-a': {
  275. 'value': 'type-a',
  276. 'label': '样本A',
  277. 'storagePrice': '25880.00',
  278. 'storageYears': 20,
  279. },
  280. 'type-max': {
  281. 'value': 'type-max',
  282. 'label': '最大金额样本',
  283. 'storagePrice': '9999999999999999.99',
  284. 'storageYears': 30,
  285. },
  286. 'type-null': {
  287. 'value': 'type-null',
  288. 'label': '未配置样本',
  289. 'storagePrice': None,
  290. 'storageYears': None,
  291. },
  292. }
  293. assert 'type-x' not in sample_types
  294. def test_protocol_form_options_hide_occupied_sample_codes():
  295. from app.services.market_support import get_form_options
  296. db = _session()
  297. _seed_options(db)
  298. db.add(BizSampleCode(id='sample-code-b', sample_code='S-002', tenant_no='tenant-a', create_dept_id='', del_flag=0))
  299. db.add(
  300. BizCollectionProtocol(
  301. id='proto-used',
  302. protocol_no='CP-USED',
  303. tenant_no='tenant-a',
  304. create_dept_id='',
  305. del_flag=0,
  306. )
  307. )
  308. db.add(
  309. BizProtocolSample(
  310. id='ps-used',
  311. collection_protocol_id='proto-used',
  312. sample_code='S-001',
  313. tenant_no='tenant-a',
  314. create_dept_id='',
  315. del_flag=0,
  316. )
  317. )
  318. db.commit()
  319. out = get_form_options(
  320. db,
  321. module='protocol',
  322. ctx=_ctx('manager', 'user-b'),
  323. user_info=_user('user-b'),
  324. region_id='rb',
  325. )
  326. assert out['sampleCodes'] == [
  327. {'value': 'sample-code-b', 'label': 'S-002', 'sampleCode': 'S-002'}
  328. ]
  329. assert out['transferTypes'] == [{'value': 'wx', 'label': '微信'}]
  330. assert out['transportModes'] == [{'value': 'zxc', 'label': '专线车'}]
  331. def test_presign_form_options_search_active_tenant_users_without_pii():
  332. from app.services.market_support import get_form_options
  333. db = _session()
  334. _seed_options(db)
  335. out = get_form_options(
  336. db,
  337. module='presign',
  338. ctx=_ctx(),
  339. user_info=_user(),
  340. user_keyword='员工',
  341. )
  342. assert out['users'] == [{'value': 'staff-a', 'label': 'A员工'}]
  343. assert '跨租户' not in str(out['users'])
  344. assert '停用' not in str(out['users'])
  345. assert 'userNo' not in str(out['users'])
  346. def test_payment_and_freight_options_use_fixed_dictionary_allowlist():
  347. from app.services.market_support import get_form_options
  348. db = _session()
  349. _seed_options(db)
  350. payment = get_form_options(db, module='payment', ctx=_ctx(), user_info=_user())
  351. freight = get_form_options(db, module='freight', ctx=_ctx(), user_info=_user())
  352. assert payment == {'transferTypes': [{'value': 'wx', 'label': '微信'}]}
  353. assert freight == {'transportModes': [{'value': 'zxc', 'label': '专线车'}]}
  354. assert '不应泄漏' not in str(payment) + str(freight)
  355. class _Storage:
  356. def __init__(self):
  357. self.uploaded = []
  358. self.deleted = []
  359. def upload_file(self, content, filename, folder):
  360. self.uploaded.append((content, filename, folder))
  361. return f'https://files.test/{folder}/generated.pdf'
  362. def delete_file(self, path):
  363. self.deleted.append(path)
  364. return True
  365. def test_upload_uses_fixed_folder_and_records_current_tenant_and_uploader():
  366. from app.services.market_support import save_market_attachment
  367. db = _session()
  368. backend = _Storage()
  369. result = save_market_attachment(
  370. db,
  371. content=b'%PDF-1.7 safe',
  372. filename='proof.pdf',
  373. content_type='application/pdf',
  374. module='payment',
  375. ctx=_ctx(),
  376. user_info=_user(),
  377. storage_backend=backend,
  378. )
  379. assert backend.uploaded[0][2] == 'market/specialist/payment'
  380. row = db.query(BizAttachment).one()
  381. assert (row.tenant_no, row.create_by, row.create_dept_id) == ('tenant-a', 'user-a', 'dept-a')
  382. assert row.business_type == 'market:specialist:payment:staging'
  383. assert result['id'] == row.id
  384. assert result['fileUrl'] == row.file_url
  385. def test_presign_and_protocol_upload_allow_20_mib_while_payment_remains_at_10_mib():
  386. from app.services.market_support import save_market_attachment
  387. content = b'%PDF-' + b'a' * (10 * 1024 * 1024)
  388. backend = _Storage()
  389. result = save_market_attachment(
  390. _session(),
  391. content=content,
  392. filename='presign-proof.pdf',
  393. content_type='application/pdf',
  394. module='presign',
  395. ctx=_ctx(),
  396. user_info=_user(),
  397. storage_backend=backend,
  398. )
  399. assert result['fileSize'] == len(content)
  400. protocol_result = save_market_attachment(
  401. _session(),
  402. content=content,
  403. filename='protocol-proof.pdf',
  404. content_type='application/pdf',
  405. module='protocol',
  406. ctx=_ctx(),
  407. user_info=_user(),
  408. storage_backend=_Storage(),
  409. )
  410. assert protocol_result['fileSize'] == len(content)
  411. with pytest.raises(ValueError, match='10MiB'):
  412. save_market_attachment(
  413. _session(),
  414. content=content,
  415. filename='payment-proof.pdf',
  416. content_type='application/pdf',
  417. module='payment',
  418. ctx=_ctx(),
  419. user_info=_user(),
  420. storage_backend=_Storage(),
  421. )
  422. def _zip_payload(path):
  423. output = BytesIO()
  424. with ZipFile(output, 'w') as archive:
  425. archive.writestr('[Content_Types].xml', '<Types/>')
  426. archive.writestr(path, 'payload')
  427. return output.getvalue()
  428. @pytest.mark.parametrize(
  429. ('content', 'filename', 'content_type'),
  430. [
  431. (_zip_payload('ppt/presentation.xml'), 'slides.pptx', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'),
  432. (b'plain text', 'notes.txt', 'text/plain'),
  433. (_zip_payload('folder/readme.txt'), 'archive.zip', 'application/zip'),
  434. (b'Rar!\x1a\x07\x01\x00' + b'a' * 8, 'archive.rar', 'application/vnd.rar'),
  435. (b'\x00\x00\x00\x18ftypmp42' + b'a' * 12, 'video.mp4', 'video/mp4'),
  436. ],
  437. )
  438. def test_protocol_upload_accepts_web_protocol_attachment_formats(content, filename, content_type):
  439. from app.services.market_support import save_market_attachment
  440. result = save_market_attachment(
  441. _session(),
  442. content=content,
  443. filename=filename,
  444. content_type=content_type,
  445. module='protocol',
  446. ctx=_ctx(),
  447. user_info=_user(),
  448. storage_backend=_Storage(),
  449. )
  450. assert result['fileName'] == filename
  451. def test_protocol_detail_payment_capabilities_require_payment_permission():
  452. from app.services.market_support import decorate_allowed_actions
  453. detail = {
  454. 'source': 'cell_storage',
  455. 'basic': {'protocolStatus': 'sxz', 'paymentModelVersion': 2},
  456. 'samplePayments': [{
  457. 'id': 'pay-1',
  458. 'schedules': [{
  459. 'id': 'schedule-1',
  460. 'scheduleStatus': 'open',
  461. 'arrearsAmount': 100,
  462. 'transfers': [
  463. {'id': 'draft', 'payStatus': 'dfj'},
  464. {'id': 'submitted', 'payStatus': 'jfqrz'},
  465. {'id': 'confirmed', 'payStatus': 'yjf'},
  466. ],
  467. }],
  468. }],
  469. }
  470. readonly = decorate_allowed_actions(
  471. 'protocol', detail, scope_kind='specialist', has_payment_permission=False
  472. )
  473. assert readonly['samplePayments'][0]['schedules'][0]['allowedActions'] == []
  474. assert [row['allowedActions'] for row in readonly['samplePayments'][0]['schedules'][0]['transfers']] == [[], [], []]
  475. writable = decorate_allowed_actions(
  476. 'protocol', detail, scope_kind='specialist', has_payment_permission=True
  477. )
  478. schedule = writable['samplePayments'][0]['schedules'][0]
  479. assert schedule['allowedActions'] == ['register-transfer']
  480. assert [row['allowedActions'] for row in schedule['transfers']] == [
  481. ['edit-transfer', 'delete-payment-transfer', 'submit-finance'],
  482. ['withdraw-transfer'],
  483. [],
  484. ]
  485. @pytest.mark.parametrize(
  486. ('content', 'filename', 'content_type'),
  487. [
  488. (b'', 'empty.pdf', 'application/pdf'),
  489. (b'<svg/>', 'bad.svg', 'image/svg+xml'),
  490. (b'MZ', 'bad.exe', 'application/octet-stream'),
  491. (b'not an image', 'fake.jpg', 'image/jpeg'),
  492. (b'%PDF-1.7', 'fake.jpg', 'image/jpeg'),
  493. (b'\x00\x00\x00\x18junk-ftyp-heic-data', 'fake.heic', 'image/heic'),
  494. (b'\x00\x00\x00\x18ftypzzzz\x00\x00\x00\x00zzzz', 'fake.heic', 'image/heic'),
  495. (b'\x00\x00\x00\xffftypheic\x00\x00\x00\x00', 'fake.heic', 'image/heic'),
  496. (b'\x00\x00\x00\x0cftypheic', 'short.heic', 'image/heic'),
  497. (b'\x00\x00\x00\x0fftypheicabc', 'short.heic', 'image/heic'),
  498. (b'\x00\x00\x00\x15ftypheic\x00\x00\x00\x00mif1x', 'misaligned.heic', 'image/heic'),
  499. (b'\x00\x00\x00\x10ftypmif1\x00\x00\x00\x00', 'generic-only.heic', 'image/heic'),
  500. (b'PK\x03\x04not-a-docx', 'fake.docx', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'),
  501. (b'a' * (10 * 1024 * 1024 + 1), 'huge.pdf', 'application/pdf'),
  502. ],
  503. )
  504. def test_upload_rejects_empty_oversized_or_unsafe_files(content, filename, content_type):
  505. from app.services.market_support import save_market_attachment
  506. db = _session()
  507. backend = _Storage()
  508. with pytest.raises(ValueError):
  509. save_market_attachment(
  510. db,
  511. content=content,
  512. filename=filename,
  513. content_type=content_type,
  514. module='payment',
  515. ctx=_ctx(),
  516. user_info=_user(),
  517. storage_backend=backend,
  518. )
  519. assert backend.uploaded == []
  520. def test_upload_deletes_storage_object_when_database_commit_fails(monkeypatch):
  521. from app.services.market_support import save_market_attachment
  522. db = _session()
  523. backend = _Storage()
  524. monkeypatch.setattr(db, 'commit', lambda: (_ for _ in ()).throw(RuntimeError('db down')))
  525. with pytest.raises(RuntimeError, match='db down'):
  526. save_market_attachment(
  527. db,
  528. content=b'%PDF-1.7 safe',
  529. filename='proof.pdf',
  530. content_type='application/pdf',
  531. module='protocol',
  532. ctx=_ctx(),
  533. user_info=_user(),
  534. storage_backend=backend,
  535. )
  536. assert backend.deleted == ['https://files.test/market/specialist/protocol/generated.pdf']
  537. def test_upload_never_refreshes_after_commit_or_deletes_committed_object(monkeypatch):
  538. from app.services.market_support import save_market_attachment
  539. db = _session()
  540. backend = _Storage()
  541. committed = False
  542. original_commit = db.commit
  543. original_refresh = db.refresh
  544. def tracked_commit():
  545. nonlocal committed
  546. original_commit()
  547. committed = True
  548. def refresh_only_before_commit(row):
  549. if committed:
  550. raise RuntimeError('refresh after commit is unsafe')
  551. return original_refresh(row)
  552. monkeypatch.setattr(db, 'commit', tracked_commit)
  553. monkeypatch.setattr(db, 'refresh', refresh_only_before_commit)
  554. result = save_market_attachment(
  555. db,
  556. content=b'%PDF-1.7 safe',
  557. filename='proof.pdf',
  558. content_type='application/pdf',
  559. module='protocol',
  560. ctx=_ctx(),
  561. user_info=_user(),
  562. storage_backend=backend,
  563. )
  564. assert result['id']
  565. assert backend.deleted == []
  566. def test_upload_accepts_well_formed_heif_ftyp_box_with_allowed_brand():
  567. from app.services.market_support import save_market_attachment
  568. db = _session()
  569. backend = _Storage()
  570. content = b'\x00\x00\x00\x14ftypheic\x00\x00\x00\x00mif1'
  571. result = save_market_attachment(
  572. db,
  573. content=content,
  574. filename='photo.heic',
  575. content_type='image/heic',
  576. module='sample',
  577. ctx=_ctx(),
  578. user_info=_user(),
  579. storage_backend=backend,
  580. )
  581. assert result['fileType'] == 'image/heic'
  582. assert backend.uploaded[0][0] == content
  583. def test_heif_extension_accepts_generic_heif_brand():
  584. from app.services.market_support import save_market_attachment
  585. db = _session()
  586. backend = _Storage()
  587. content = b'\x00\x00\x00\x10ftypmif1\x00\x00\x00\x00'
  588. result = save_market_attachment(
  589. db,
  590. content=content,
  591. filename='photo.heif',
  592. content_type='image/heif',
  593. module='sample',
  594. ctx=_ctx(),
  595. user_info=_user(),
  596. storage_backend=backend,
  597. )
  598. assert result['fileType'] == 'image/heif'
  599. def _attachment(**overrides):
  600. values = dict(
  601. id='att-a',
  602. business_type='market:specialist:payment:staging',
  603. business_id=None,
  604. original_name='proof.pdf',
  605. file_ext='pdf',
  606. file_url='market/specialist/payment/a.pdf',
  607. file_size=12,
  608. file_type='application/pdf',
  609. tenant_no='tenant-a',
  610. create_by='user-a',
  611. create_dept_id='',
  612. del_flag=0,
  613. )
  614. values.update(overrides)
  615. return BizAttachment(**values)
  616. class _DownloadStorage:
  617. def __init__(self):
  618. self.requests = []
  619. def presigned_download_url(self, file_url, file_name):
  620. self.requests.append((file_url, file_name))
  621. return 'https://files.test/signed-download'
  622. def _protocol_attachment_session():
  623. engine = create_engine('sqlite:///:memory:')
  624. Base.metadata.create_all(
  625. engine,
  626. tables=[
  627. BizAttachment.__table__,
  628. BizCollectionProtocol.__table__,
  629. BizCollectionRegionStaff.__table__,
  630. BizProtocolCollectionInfo.__table__,
  631. BizProtocolFullmoonTodo.__table__,
  632. BizProtocolPayment.__table__,
  633. BizProtocolPaymentDetail.__table__,
  634. BizProtocolStorageCert.__table__,
  635. BizResearchDonation.__table__,
  636. BizResearchDonationCollection.__table__,
  637. SysPost.__table__,
  638. SysPostRole.__table__,
  639. SysRole.__table__,
  640. SysRoleDataScopeDetail.__table__,
  641. SysUserPost.__table__,
  642. SysUserRole.__table__,
  643. ],
  644. )
  645. db = sessionmaker(bind=engine)()
  646. db.add(
  647. SysRole(
  648. id='market-role',
  649. role_name='市场移动端',
  650. data_scope='1',
  651. status='1',
  652. tenant_no='tenant-a',
  653. create_dept_id='',
  654. del_flag=0,
  655. )
  656. )
  657. for user_id in ('sales-a', 'sales-b', 'manager-a'):
  658. db.add(
  659. SysUserRole(
  660. id=f'user-role-{user_id}',
  661. user_id=user_id,
  662. role_id='market-role',
  663. tenant_no='tenant-a',
  664. create_dept_id='',
  665. del_flag=0,
  666. )
  667. )
  668. db.add(
  669. BizCollectionRegionStaff(
  670. id='manager-a-region-a',
  671. region_id='region-a',
  672. user_id='manager-a',
  673. is_leader=1,
  674. tenant_no='tenant-a',
  675. create_dept_id='',
  676. del_flag=0,
  677. )
  678. )
  679. db.commit()
  680. return db
  681. def _market_user(user_id):
  682. return {
  683. 'user_id': user_id,
  684. 'tenant_no': 'tenant-a',
  685. 'role': 'market_user',
  686. 'dept_id': 'dept-a',
  687. }
  688. def _add_protocol_attachment_reference(
  689. db,
  690. protocol_id,
  691. *,
  692. field,
  693. value,
  694. sales_user_id='sales-a',
  695. region_id='region-a',
  696. manager_user_id='manager-b',
  697. parent_tenant_no='tenant-a',
  698. parent_del_flag=0,
  699. collection_tenant_no=None,
  700. collection_del_flag=0,
  701. child_tenant_no='tenant-a',
  702. child_del_flag=0,
  703. ):
  704. db.add_all(
  705. [
  706. BizCollectionProtocol(
  707. id=protocol_id,
  708. protocol_no=f'P-{protocol_id}',
  709. tenant_no=parent_tenant_no,
  710. create_by=sales_user_id,
  711. create_dept_id='dept-a',
  712. del_flag=parent_del_flag,
  713. ),
  714. BizProtocolCollectionInfo(
  715. id=f'collection-{protocol_id}',
  716. collection_protocol_id=protocol_id,
  717. region_id=region_id,
  718. sales_user_id=sales_user_id,
  719. region_manager_user_id=manager_user_id,
  720. tenant_no=(
  721. collection_tenant_no
  722. if collection_tenant_no is not None
  723. else parent_tenant_no
  724. ),
  725. create_dept_id='dept-a',
  726. del_flag=collection_del_flag,
  727. ),
  728. ]
  729. )
  730. model = (
  731. BizProtocolStorageCert
  732. if field == 'cert_image_urls'
  733. else BizProtocolFullmoonTodo
  734. )
  735. db.add(
  736. model(
  737. id=f'child-{protocol_id}',
  738. collection_protocol_id=protocol_id,
  739. tenant_no=child_tenant_no,
  740. create_dept_id='dept-a',
  741. del_flag=child_del_flag,
  742. **{field: value},
  743. )
  744. )
  745. db.commit()
  746. def _protocol_download_ctx(scope_kind, user_id):
  747. return MarketFieldContext('tenant-a', user_id, scope_kind)
  748. def test_protocol_cert_and_insurance_references_use_real_scope_and_exact_urls():
  749. db = _protocol_attachment_session()
  750. _add_protocol_attachment_reference(
  751. db,
  752. 'own-cert',
  753. field='cert_image_urls',
  754. value=' files/cert.pdf.evil , files/cert-exact.pdf ',
  755. )
  756. _add_protocol_attachment_reference(
  757. db,
  758. 'own-insurance',
  759. field='insurance_attachments',
  760. value='files/insurance.pdf',
  761. )
  762. assert market_support._has_accessible_market_attachment_reference(
  763. db,
  764. module='protocol',
  765. candidates=['files/cert-exact.pdf'],
  766. ctx=_protocol_download_ctx('specialist', 'sales-a'),
  767. user_info=_market_user('sales-a'),
  768. )
  769. assert market_support._has_accessible_market_attachment_reference(
  770. db,
  771. module='protocol',
  772. candidates=['files/insurance.pdf'],
  773. ctx=_protocol_download_ctx('manager', 'manager-a'),
  774. user_info=_market_user('manager-a'),
  775. )
  776. assert not market_support._has_accessible_market_attachment_reference(
  777. db,
  778. module='protocol',
  779. candidates=['files/cert.pdf'],
  780. ctx=_protocol_download_ctx('specialist', 'sales-a'),
  781. user_info=_market_user('sales-a'),
  782. )
  783. assert not market_support._has_accessible_market_attachment_reference(
  784. db,
  785. module='protocol',
  786. candidates=['files/cert-exact.pdf.evil'],
  787. ctx=_protocol_download_ctx('specialist', 'sales-a'),
  788. user_info=_market_user('sales-a'),
  789. )
  790. assert not market_support._has_accessible_market_attachment_reference(
  791. db,
  792. module='protocol',
  793. candidates=['files/cert-exact.pdf'],
  794. ctx=_protocol_download_ctx('specialist', 'sales-b'),
  795. user_info=_market_user('sales-b'),
  796. )
  797. db.add_all(
  798. [
  799. _attachment(
  800. id='short-url',
  801. file_url='files/cert.pdf',
  802. business_type='market:specialist:protocol:bound',
  803. ),
  804. _attachment(
  805. id='long-url',
  806. file_url='files/cert-exact.pdf.evil',
  807. business_type='market:specialist:protocol:bound',
  808. ),
  809. _attachment(
  810. id='other-specialist-scope',
  811. file_url='files/cert-exact.pdf',
  812. business_type='market:specialist:protocol:bound',
  813. ),
  814. ]
  815. )
  816. db.commit()
  817. for file_url in ('files/cert.pdf', 'files/cert-exact.pdf.evil'):
  818. with pytest.raises(PermissionError, match='附件'):
  819. market_support.get_market_attachment_download_url(
  820. db,
  821. file_url=file_url,
  822. file_name=None,
  823. module='protocol',
  824. ctx=_protocol_download_ctx('specialist', 'sales-a'),
  825. user_info=_market_user('sales-a'),
  826. storage_backend=_DownloadStorage(),
  827. )
  828. with pytest.raises(PermissionError, match='附件'):
  829. market_support.get_market_attachment_download_url(
  830. db,
  831. file_url='files/cert-exact.pdf',
  832. file_name=None,
  833. module='protocol',
  834. ctx=_protocol_download_ctx('specialist', 'sales-b'),
  835. user_info=_market_user('sales-b'),
  836. storage_backend=_DownloadStorage(),
  837. )
  838. @pytest.mark.parametrize(
  839. ('attachment_id', 'file_url', 'business_type', 'field', 'scope_kind', 'user_id'),
  840. [
  841. ('legacy-cert', 'files/legacy-cert.pdf', '', 'cert_image_urls', 'specialist', 'sales-a'),
  842. (
  843. 'protocol-cert',
  844. 'files/protocol-cert.pdf',
  845. 'market:specialist:protocol:bound',
  846. 'cert_image_urls',
  847. 'specialist',
  848. 'sales-a',
  849. ),
  850. (
  851. 'protocol-insurance',
  852. 'files/protocol-insurance.pdf',
  853. 'market:manager:protocol:bound',
  854. 'insurance_attachments',
  855. 'manager',
  856. 'manager-a',
  857. ),
  858. (
  859. 'sample-cert',
  860. 'files/sample-cert.pdf',
  861. 'market:specialist:sample:bound',
  862. 'cert_image_urls',
  863. 'specialist',
  864. 'sales-a',
  865. ),
  866. (
  867. 'sample-insurance',
  868. 'files/sample-insurance.pdf',
  869. 'market:manager:sample:bound',
  870. 'insurance_attachments',
  871. 'manager',
  872. 'manager-a',
  873. ),
  874. ],
  875. )
  876. def test_protocol_download_allows_accessible_cert_and_insurance_attachment_history(
  877. attachment_id,
  878. file_url,
  879. business_type,
  880. field,
  881. scope_kind,
  882. user_id,
  883. ):
  884. db = _protocol_attachment_session()
  885. _add_protocol_attachment_reference(
  886. db,
  887. f'protocol-{attachment_id}',
  888. field=field,
  889. value=file_url,
  890. )
  891. db.add(
  892. _attachment(
  893. id=attachment_id,
  894. file_url=file_url,
  895. business_type=business_type,
  896. business_id=f'protocol-{attachment_id}',
  897. create_by='historical-uploader',
  898. )
  899. )
  900. db.commit()
  901. result = market_support.get_market_attachment_download_url(
  902. db,
  903. file_url=file_url,
  904. file_name=None,
  905. module='protocol',
  906. ctx=_protocol_download_ctx(scope_kind, user_id),
  907. user_info=_market_user(user_id),
  908. storage_backend=_DownloadStorage(),
  909. )
  910. assert result == {'downloadUrl': 'https://files.test/signed-download'}
  911. def test_protocol_download_does_not_use_plain_protocol_reference_for_sample_bound():
  912. db = _protocol_attachment_session()
  913. _add_protocol_attachment_reference(
  914. db,
  915. 'plain-protocol-reference',
  916. field='cert_image_urls',
  917. value='files/different-cert.pdf',
  918. )
  919. protocol = db.get(BizCollectionProtocol, 'plain-protocol-reference')
  920. protocol.protocol_attachments = 'files/plain-protocol.pdf'
  921. db.add(
  922. _attachment(
  923. id='plain-protocol-sample-bound',
  924. file_url='files/plain-protocol.pdf',
  925. business_type='market:specialist:sample:bound',
  926. business_id='plain-protocol-reference',
  927. )
  928. )
  929. db.commit()
  930. with pytest.raises(PermissionError, match='附件'):
  931. market_support.get_market_attachment_download_url(
  932. db,
  933. file_url='files/plain-protocol.pdf',
  934. file_name=None,
  935. module='protocol',
  936. ctx=_protocol_download_ctx('specialist', 'sales-a'),
  937. user_info=_market_user('sales-a'),
  938. storage_backend=_DownloadStorage(),
  939. )
  940. @pytest.mark.parametrize(
  941. (
  942. 'case',
  943. 'parent_tenant_no',
  944. 'parent_del_flag',
  945. 'collection_tenant_no',
  946. 'collection_del_flag',
  947. 'child_tenant_no',
  948. 'child_del_flag',
  949. ),
  950. [
  951. ('cross-parent-tenant', 'tenant-b', 0, 'tenant-b', 0, 'tenant-a', 0),
  952. ('deleted-parent', 'tenant-a', 1, 'tenant-a', 0, 'tenant-a', 0),
  953. ('cross-collection-tenant', 'tenant-a', 0, 'tenant-b', 0, 'tenant-a', 0),
  954. ('deleted-collection', 'tenant-a', 0, 'tenant-a', 1, 'tenant-a', 0),
  955. ('cross-child-tenant', 'tenant-a', 0, 'tenant-a', 0, 'tenant-b', 0),
  956. ('deleted-child', 'tenant-a', 0, 'tenant-a', 0, 'tenant-a', 1),
  957. ],
  958. )
  959. def test_protocol_cert_reference_rejects_tenant_scope_and_soft_delete_boundaries(
  960. case,
  961. parent_tenant_no,
  962. parent_del_flag,
  963. collection_tenant_no,
  964. collection_del_flag,
  965. child_tenant_no,
  966. child_del_flag,
  967. ):
  968. db = _protocol_attachment_session()
  969. file_url = f'files/{case}.pdf'
  970. _add_protocol_attachment_reference(
  971. db,
  972. case,
  973. field='cert_image_urls',
  974. value=file_url,
  975. parent_tenant_no=parent_tenant_no,
  976. parent_del_flag=parent_del_flag,
  977. collection_tenant_no=collection_tenant_no,
  978. collection_del_flag=collection_del_flag,
  979. child_tenant_no=child_tenant_no,
  980. child_del_flag=child_del_flag,
  981. )
  982. assert not market_support._has_accessible_market_attachment_reference(
  983. db,
  984. module='protocol',
  985. candidates=[file_url],
  986. ctx=_protocol_download_ctx('specialist', 'sales-a'),
  987. user_info=_market_user('sales-a'),
  988. )
  989. db.add(
  990. _attachment(
  991. id=f'attachment-{case}',
  992. file_url=file_url,
  993. business_type='market:specialist:protocol:bound',
  994. )
  995. )
  996. db.commit()
  997. with pytest.raises(PermissionError, match='附件'):
  998. market_support.get_market_attachment_download_url(
  999. db,
  1000. file_url=file_url,
  1001. file_name=None,
  1002. module='protocol',
  1003. ctx=_protocol_download_ctx('specialist', 'sales-a'),
  1004. user_info=_market_user('sales-a'),
  1005. storage_backend=_DownloadStorage(),
  1006. )
  1007. @pytest.mark.parametrize(
  1008. ('attachment_id', 'file_url', 'business_type', 'attachment_tenant', 'attachment_del_flag'),
  1009. [
  1010. ('sample-staging', 'files/sample-staging.pdf', 'market:specialist:sample:staging', 'tenant-a', 0),
  1011. ('other-staging', 'files/other-staging.pdf', 'market:manager:protocol:staging', 'tenant-a', 0),
  1012. ('cross-tenant', 'files/cross-tenant.pdf', '', 'tenant-b', 0),
  1013. ('deleted-attachment', 'files/deleted-attachment.pdf', '', 'tenant-a', 1),
  1014. ('unreferenced', 'files/unreferenced.pdf', '', 'tenant-a', 0),
  1015. ],
  1016. )
  1017. def test_protocol_download_rejects_staging_cross_tenant_deleted_and_unreferenced_rows(
  1018. attachment_id,
  1019. file_url,
  1020. business_type,
  1021. attachment_tenant,
  1022. attachment_del_flag,
  1023. ):
  1024. db = _protocol_attachment_session()
  1025. referenced_url = file_url if attachment_id != 'unreferenced' else 'files/other.pdf'
  1026. _add_protocol_attachment_reference(
  1027. db,
  1028. f'protocol-{attachment_id}',
  1029. field='cert_image_urls',
  1030. value=referenced_url,
  1031. )
  1032. db.add(
  1033. _attachment(
  1034. id=attachment_id,
  1035. file_url=file_url,
  1036. business_type=business_type,
  1037. tenant_no=attachment_tenant,
  1038. del_flag=attachment_del_flag,
  1039. )
  1040. )
  1041. db.commit()
  1042. with pytest.raises(PermissionError, match='附件'):
  1043. market_support.get_market_attachment_download_url(
  1044. db,
  1045. file_url=file_url,
  1046. file_name=None,
  1047. module='protocol',
  1048. ctx=_protocol_download_ctx('specialist', 'sales-a'),
  1049. user_info=_market_user('sales-a'),
  1050. storage_backend=_DownloadStorage(),
  1051. )
  1052. def test_market_attachment_download_uses_registered_original_name():
  1053. from app.services.market_support import get_market_attachment_download_url
  1054. db = _session()
  1055. db.add(_attachment())
  1056. db.commit()
  1057. backend = _DownloadStorage()
  1058. result = get_market_attachment_download_url(
  1059. db,
  1060. file_url='market/specialist/payment/a.pdf',
  1061. file_name='spoofed.exe',
  1062. module='payment',
  1063. ctx=_ctx(),
  1064. user_info=_user(),
  1065. storage_backend=backend,
  1066. )
  1067. assert result == {'downloadUrl': 'https://files.test/signed-download'}
  1068. assert backend.requests == [
  1069. ('market/specialist/payment/a.pdf', 'proof.pdf')
  1070. ]
  1071. def test_market_attachment_download_rejects_cross_tenant_module_and_other_users_staging():
  1072. from app.services.market_support import get_market_attachment_download_url
  1073. db = _session()
  1074. db.add_all(
  1075. [
  1076. _attachment(id='cross', file_url='cross.pdf', tenant_no='tenant-b'),
  1077. _attachment(
  1078. id='wrong-module',
  1079. file_url='wrong-module.pdf',
  1080. business_type='market:specialist:sample:bound',
  1081. business_id='sample-a',
  1082. ),
  1083. _attachment(
  1084. id='other-staging',
  1085. file_url='other-staging.pdf',
  1086. create_by='user-b',
  1087. ),
  1088. ]
  1089. )
  1090. db.commit()
  1091. for file_url in ('cross.pdf', 'wrong-module.pdf', 'other-staging.pdf'):
  1092. with pytest.raises(PermissionError, match='附件'):
  1093. get_market_attachment_download_url(
  1094. db,
  1095. file_url=file_url,
  1096. file_name=None,
  1097. module='payment',
  1098. ctx=_ctx(),
  1099. user_info=_user(),
  1100. storage_backend=_DownloadStorage(),
  1101. )
  1102. def test_market_attachment_download_rejects_unreferenced_bound_and_legacy_rows(
  1103. monkeypatch,
  1104. ):
  1105. from app.services import market_support
  1106. db = _session()
  1107. db.add_all(
  1108. [
  1109. _attachment(
  1110. id='manager-bound',
  1111. file_url='manager-bound.pdf',
  1112. business_type='market:manager:payment:bound',
  1113. business_id='transfer-a',
  1114. ),
  1115. _attachment(
  1116. id='legacy',
  1117. file_url='legacy.pdf',
  1118. business_type=None,
  1119. create_by='admin',
  1120. ),
  1121. ]
  1122. )
  1123. db.commit()
  1124. monkeypatch.setattr(
  1125. market_support,
  1126. '_has_accessible_market_attachment_reference',
  1127. lambda *args, **kwargs: False,
  1128. )
  1129. for file_url in ('manager-bound.pdf', 'legacy.pdf'):
  1130. with pytest.raises(PermissionError, match='附件'):
  1131. market_support.get_market_attachment_download_url(
  1132. db,
  1133. file_url=file_url,
  1134. file_name=None,
  1135. module='payment',
  1136. ctx=_ctx(),
  1137. user_info=_user(),
  1138. storage_backend=_DownloadStorage(),
  1139. )
  1140. def test_market_attachment_download_allows_accessible_referenced_legacy_row(monkeypatch):
  1141. from app.services import market_support
  1142. db = _session()
  1143. db.add(
  1144. _attachment(
  1145. id='legacy',
  1146. file_url='legacy.pdf',
  1147. business_type=None,
  1148. create_by='admin',
  1149. )
  1150. )
  1151. db.commit()
  1152. checked = []
  1153. def allow_reference(_db, *, module, candidates, ctx, user_info):
  1154. checked.append((module, candidates, ctx.user_id, user_info['user_id']))
  1155. return True
  1156. monkeypatch.setattr(
  1157. market_support,
  1158. '_has_accessible_market_attachment_reference',
  1159. allow_reference,
  1160. )
  1161. result = market_support.get_market_attachment_download_url(
  1162. db,
  1163. file_url='legacy.pdf',
  1164. file_name=None,
  1165. module='payment',
  1166. ctx=_ctx(),
  1167. user_info=_user(),
  1168. storage_backend=_DownloadStorage(),
  1169. )
  1170. assert result['downloadUrl'] == 'https://files.test/signed-download'
  1171. assert checked == [('payment', ['legacy.pdf'], 'user-a', 'user-a')]
  1172. def test_protocol_attachment_reference_respects_specialist_donation_scope():
  1173. from app.models.models import (
  1174. BizCollectionProtocol,
  1175. BizProtocolCollectionInfo,
  1176. BizProtocolPayment,
  1177. BizProtocolPaymentDetail,
  1178. )
  1179. from app.models.research_donation import (
  1180. BizResearchDonation,
  1181. BizResearchDonationCollection,
  1182. )
  1183. from app.services import market_support
  1184. engine = create_engine('sqlite:///:memory:')
  1185. Base.metadata.create_all(
  1186. engine,
  1187. tables=[
  1188. BizCollectionProtocol.__table__,
  1189. BizProtocolCollectionInfo.__table__,
  1190. BizProtocolStorageCert.__table__,
  1191. BizProtocolFullmoonTodo.__table__,
  1192. BizProtocolPayment.__table__,
  1193. BizProtocolPaymentDetail.__table__,
  1194. BizResearchDonation.__table__,
  1195. BizResearchDonationCollection.__table__,
  1196. ],
  1197. )
  1198. db = sessionmaker(bind=engine)()
  1199. db.add_all(
  1200. [
  1201. BizResearchDonation(
  1202. id='donation-a',
  1203. donation_no='D-1',
  1204. donation_status='sxz',
  1205. source_type='direct',
  1206. attachment_urls='legacy.pdf',
  1207. tenant_no='tenant-a',
  1208. create_dept_id='',
  1209. del_flag=0,
  1210. ),
  1211. BizResearchDonationCollection(
  1212. id='collection-a',
  1213. research_donation_id='donation-a',
  1214. sales_user_id='user-a',
  1215. tenant_no='tenant-a',
  1216. create_dept_id='',
  1217. del_flag=0,
  1218. ),
  1219. ]
  1220. )
  1221. db.commit()
  1222. super_admin_a = {**_user('user-a'), 'role': 'super_admin'}
  1223. super_admin_b = {**_user('user-b'), 'role': 'super_admin'}
  1224. assert market_support._has_accessible_market_attachment_reference(
  1225. db,
  1226. module='protocol',
  1227. candidates=['legacy.pdf'],
  1228. ctx=_ctx(user_id='user-a'),
  1229. user_info=super_admin_a,
  1230. )
  1231. assert not market_support._has_accessible_market_attachment_reference(
  1232. db,
  1233. module='protocol',
  1234. candidates=['legacy.pdf'],
  1235. ctx=_ctx(user_id='user-b'),
  1236. user_info=super_admin_b,
  1237. )
  1238. def test_create_attachment_refs_require_current_uploader_staging_exact_match():
  1239. from app.services.market_support import validate_attachment_refs
  1240. db = _session()
  1241. db.add_all(
  1242. [
  1243. _attachment(),
  1244. _attachment(id='att-other', file_url='market/specialist/payment/other.pdf', create_by='other'),
  1245. _attachment(id='att-cross', file_url='market/specialist/payment/cross.pdf', tenant_no='tenant-b'),
  1246. ]
  1247. )
  1248. db.commit()
  1249. assert validate_attachment_refs(
  1250. db,
  1251. 'att-a,market/specialist/payment/a.pdf',
  1252. module='payment',
  1253. ctx=_ctx(),
  1254. creating=True,
  1255. ) == 'market/specialist/payment/a.pdf'
  1256. for invalid in ('att-other', 'att-cross', 'https://evil.test/a.pdf', 'a.pdf'):
  1257. with pytest.raises(ValueError, match='附件'):
  1258. validate_attachment_refs(db, invalid, module='payment', ctx=_ctx(), creating=True)
  1259. def test_staging_attachment_must_match_current_scope_role_exactly():
  1260. from app.services.market_support import validate_attachment_refs
  1261. db = _session()
  1262. db.add(
  1263. _attachment(
  1264. id='manager-staging',
  1265. business_type='market:manager:payment:staging',
  1266. file_url='market/manager/payment/proof.pdf',
  1267. )
  1268. )
  1269. db.commit()
  1270. with pytest.raises(ValueError, match='附件'):
  1271. validate_attachment_refs(
  1272. db,
  1273. 'manager-staging',
  1274. module='payment',
  1275. ctx=_ctx('specialist'),
  1276. creating=True,
  1277. business_id='pay-a',
  1278. )
  1279. def test_attachment_refs_bind_once_to_exact_scope_module_and_business():
  1280. from app.services.market_support import validate_attachment_refs
  1281. db = _session()
  1282. row = _attachment()
  1283. db.add(row)
  1284. db.commit()
  1285. result = validate_attachment_refs(
  1286. db,
  1287. 'att-a,market/specialist/payment/a.pdf',
  1288. module='payment',
  1289. ctx=_ctx(),
  1290. creating=True,
  1291. business_id='transfer-a',
  1292. )
  1293. assert result == 'market/specialist/payment/a.pdf'
  1294. assert (row.business_type, row.business_id) == (
  1295. 'market:specialist:payment:bound',
  1296. 'transfer-a',
  1297. )
  1298. assert validate_attachment_refs(
  1299. db,
  1300. 'att-a',
  1301. module='payment',
  1302. ctx=_ctx(),
  1303. creating=False,
  1304. business_id='transfer-a',
  1305. ) == 'market/specialist/payment/a.pdf'
  1306. with pytest.raises(ValueError, match='附件'):
  1307. validate_attachment_refs(
  1308. db,
  1309. 'att-a',
  1310. module='payment',
  1311. ctx=_ctx(),
  1312. creating=False,
  1313. business_id='transfer-b',
  1314. )
  1315. with pytest.raises(ValueError, match='附件'):
  1316. validate_attachment_refs(
  1317. db,
  1318. 'att-a',
  1319. module='payment',
  1320. ctx=_ctx('manager'),
  1321. creating=False,
  1322. business_id='transfer-a',
  1323. )
  1324. def test_attachment_ref_resolution_uses_one_batched_query_and_deduplicates_aliases():
  1325. from sqlalchemy import event
  1326. from app.services.market_support import validate_attachment_refs
  1327. db = _session()
  1328. db.add_all(
  1329. [
  1330. _attachment(id='att-1', file_url='market/specialist/payment/1.pdf'),
  1331. _attachment(id='att-2', file_url='market/specialist/payment/2.pdf'),
  1332. ]
  1333. )
  1334. db.commit()
  1335. statements = []
  1336. def capture(_conn, _cursor, statement, _parameters, _context, _many):
  1337. if 'biz_attachment' in statement.lower() and statement.lstrip().lower().startswith('select'):
  1338. statements.append(statement)
  1339. event.listen(db.get_bind(), 'before_cursor_execute', capture)
  1340. try:
  1341. result = validate_attachment_refs(
  1342. db,
  1343. 'att-1,market/specialist/payment/1.pdf,att-2',
  1344. module='payment',
  1345. ctx=_ctx(),
  1346. creating=True,
  1347. business_id='transfer-batch',
  1348. )
  1349. finally:
  1350. event.remove(db.get_bind(), 'before_cursor_execute', capture)
  1351. assert result == 'market/specialist/payment/1.pdf,market/specialist/payment/2.pdf'
  1352. assert len(statements) == 1
  1353. @pytest.mark.parametrize(
  1354. 'refs',
  1355. [','.join(f'att-{index}' for index in range(21)), 'x' * 4001],
  1356. )
  1357. def test_attachment_refs_reject_excessive_count_or_total_length(refs):
  1358. from app.services.market_support import validate_attachment_refs
  1359. with pytest.raises(ValueError, match='附件'):
  1360. validate_attachment_refs(
  1361. _session(),
  1362. refs,
  1363. module='payment',
  1364. ctx=_ctx(),
  1365. creating=True,
  1366. business_id='transfer-limit',
  1367. )
  1368. def test_all_mobile_attachment_schemas_cap_total_reference_length():
  1369. from pydantic import ValidationError
  1370. from app.schemas.market_mobile import (
  1371. MarketPaymentTransferBody,
  1372. MarketPresignTransferBody,
  1373. MarketProtocolAttachmentsBody,
  1374. MarketSampleStorageCertBody,
  1375. )
  1376. too_long = 'x' * 4001
  1377. payloads = (
  1378. (MarketPresignTransferBody, {'transferAttachments': too_long}),
  1379. (MarketProtocolAttachmentsBody, {'protocolAttachments': too_long}),
  1380. (MarketPaymentTransferBody, {'transferAttachments': too_long}),
  1381. (MarketSampleStorageCertBody, {'attachments': too_long}),
  1382. )
  1383. for schema, payload in payloads:
  1384. with pytest.raises(ValidationError):
  1385. schema.model_validate(payload)
  1386. def test_update_attachment_refs_allow_exact_existing_refs_and_current_user_new_only():
  1387. from app.services.market_support import validate_attachment_refs
  1388. db = _session()
  1389. db.add_all(
  1390. [
  1391. _attachment(
  1392. id='existing',
  1393. file_url='market/specialist/payment/existing.pdf',
  1394. create_by='legacy',
  1395. business_type='market:specialist:payment:bound',
  1396. business_id='transfer-existing',
  1397. ),
  1398. _attachment(id='new', file_url='market/specialist/payment/new.pdf'),
  1399. ]
  1400. )
  1401. db.commit()
  1402. out = validate_attachment_refs(
  1403. db,
  1404. 'existing,new',
  1405. module='payment',
  1406. ctx=_ctx(),
  1407. creating=False,
  1408. existing_refs='market/specialist/payment/existing.pdf',
  1409. business_id='transfer-existing',
  1410. )
  1411. assert out == 'market/specialist/payment/existing.pdf,market/specialist/payment/new.pdf'
  1412. @pytest.mark.parametrize('metadata_kind', ['missing', 'legacy-unbound', 'other-role-bound'])
  1413. def test_update_may_retain_exact_server_supplied_existing_url_without_current_metadata(
  1414. metadata_kind,
  1415. ):
  1416. from app.services.market_support import validate_attachment_refs
  1417. db = _session()
  1418. existing_url = 'legacy/payment/existing.pdf'
  1419. if metadata_kind == 'legacy-unbound':
  1420. db.add(
  1421. _attachment(
  1422. id='legacy-unbound',
  1423. file_url=existing_url,
  1424. business_type='protocol',
  1425. create_by='legacy-user',
  1426. )
  1427. )
  1428. elif metadata_kind == 'other-role-bound':
  1429. db.add(
  1430. _attachment(
  1431. id='specialist-bound',
  1432. file_url=existing_url,
  1433. business_type='market:specialist:payment:bound',
  1434. business_id='transfer-existing',
  1435. create_by='specialist-user',
  1436. )
  1437. )
  1438. db.commit()
  1439. assert validate_attachment_refs(
  1440. db,
  1441. existing_url,
  1442. module='payment',
  1443. ctx=_ctx('manager'),
  1444. creating=False,
  1445. existing_refs=existing_url,
  1446. business_id='transfer-existing',
  1447. ) == existing_url
  1448. def test_existing_ref_exception_allows_removal_but_not_arbitrary_url_smuggling():
  1449. from app.services.market_support import validate_attachment_refs
  1450. db = _session()
  1451. assert validate_attachment_refs(
  1452. db,
  1453. '',
  1454. module='payment',
  1455. ctx=_ctx(),
  1456. creating=False,
  1457. existing_refs='legacy/payment/existing.pdf',
  1458. business_id='transfer-existing',
  1459. ) == ''
  1460. with pytest.raises(ValueError, match='附件'):
  1461. validate_attachment_refs(
  1462. db,
  1463. 'https://evil.test/smuggled.pdf',
  1464. module='payment',
  1465. ctx=_ctx(),
  1466. creating=False,
  1467. existing_refs='legacy/payment/existing.pdf',
  1468. business_id='transfer-existing',
  1469. )
  1470. def test_allowed_actions_are_state_scope_and_permission_aware():
  1471. from app.services.market_support import allowed_actions
  1472. assert allowed_actions('presign', status='active') == ['edit', 'convert', 'delete']
  1473. assert allowed_actions('presign', status='void') == ['edit', 'delete']
  1474. assert allowed_actions('presign', status='converted') == ['edit']
  1475. assert allowed_actions('presign-transfer', status='dfj') == ['edit', 'delete', 'submit']
  1476. assert allowed_actions('presign-transfer', status='jfqrz') == ['withdraw']
  1477. assert allowed_actions('presign-transfer', status='yjf') == []
  1478. assert allowed_actions('protocol', status='dsx') == ['edit', 'delete']
  1479. assert allowed_actions('protocol', status='yzz') == ['edit', 'delete']
  1480. assert allowed_actions('protocol', status='yzf') == ['edit', 'delete']
  1481. assert allowed_actions('payment-transfer', status='dfj') == [
  1482. 'edit-transfer',
  1483. 'delete-payment-transfer',
  1484. 'submit-finance',
  1485. ]
  1486. assert allowed_actions('payment-transfer', status='jfqrz') == ['withdraw-transfer']
  1487. assert allowed_actions('payment-chase', status='', has_payment_permission=False) == []
  1488. assert allowed_actions('payment-chase', status='', has_payment_permission=True) == []
  1489. assert allowed_actions('sample', status='', source='research_donation', has_sample_code=True) == []
  1490. assert allowed_actions('sample', status='', source='cell_storage', has_sample_code=True) == []
  1491. assert allowed_actions('freight', status='', scope_kind='specialist') == []
  1492. assert allowed_actions('freight', status='', scope_kind='manager') == ['edit']
  1493. assert allowed_actions('presign-list', status='') == ['create']
  1494. assert allowed_actions('protocol-list', status='') == ['create']
  1495. assert allowed_actions('freight-list', status='', scope_kind='specialist') == ['create']
  1496. def test_legacy_v1_protocol_detail_keeps_status_scoped_edit_and_delete():
  1497. from app.services.market_support import decorate_allowed_actions
  1498. result = decorate_allowed_actions(
  1499. 'protocol',
  1500. {
  1501. 'source': 'cell_storage',
  1502. 'basic': {
  1503. 'protocolStatus': 'sxz',
  1504. 'paymentModelVersion': 1,
  1505. },
  1506. },
  1507. scope_kind='specialist',
  1508. detail=True,
  1509. )
  1510. assert result['allowedActions'] == ['edit', 'delete']
  1511. def test_presign_actions_include_delete_and_nested_transfer_actions():
  1512. from app.services.market_support import decorate_allowed_actions
  1513. active = decorate_allowed_actions(
  1514. 'presign',
  1515. {
  1516. 'orderStatus': 'active',
  1517. 'transfers': [
  1518. {'id': 't1', 'payStatus': 'dfj'},
  1519. {'id': 't2', 'payStatus': 'jfqrz'},
  1520. {'id': 't3', 'payStatus': 'yjf'},
  1521. ],
  1522. },
  1523. scope_kind='specialist',
  1524. detail=True,
  1525. )
  1526. assert active['allowedActions'] == ['edit', 'convert', 'delete']
  1527. assert [row['allowedActions'] for row in active['transfers']] == [
  1528. ['edit', 'delete', 'submit'],
  1529. ['withdraw'],
  1530. [],
  1531. ]
  1532. for parent_status, parent_actions in (
  1533. ('converted', ['edit']),
  1534. ('void', ['edit', 'delete']),
  1535. ):
  1536. locked = decorate_allowed_actions(
  1537. 'presign',
  1538. {
  1539. 'orderStatus': parent_status,
  1540. 'transfers': [
  1541. {'id': 't1', 'payStatus': 'dfj'},
  1542. {'id': 't2', 'payStatus': 'jfqrz'},
  1543. ],
  1544. },
  1545. scope_kind='specialist',
  1546. detail=True,
  1547. )
  1548. assert locked['allowedActions'] == parent_actions
  1549. assert [row['allowedActions'] for row in locked['transfers']] == [[], []]
  1550. unknown = decorate_allowed_actions(
  1551. 'presign',
  1552. {
  1553. 'orderStatus': 'legacy-locked',
  1554. 'transfers': [{'id': 't1', 'payStatus': 'dfj'}],
  1555. },
  1556. scope_kind='specialist',
  1557. detail=True,
  1558. )
  1559. assert unknown['transfers'][0]['allowedActions'] == []
  1560. def test_form_options_do_not_leak_children_of_soft_deleted_regions():
  1561. from app.services.market_support import get_form_options
  1562. db = _session()
  1563. _seed_options(db)
  1564. db.add_all(
  1565. [
  1566. BizCollectionRegion(
  1567. id='deleted-region',
  1568. region_name='已删除地区',
  1569. tenant_no='tenant-a',
  1570. create_dept_id='',
  1571. del_flag=1,
  1572. ),
  1573. BizCollectionHospital(
  1574. id='deleted-region-hospital',
  1575. region_id='deleted-region',
  1576. hospital_name='不应泄漏医院',
  1577. tenant_no='tenant-a',
  1578. create_dept_id='',
  1579. del_flag=0,
  1580. ),
  1581. BizCollectionRegionStaff(
  1582. id='deleted-region-staff',
  1583. region_id='deleted-region',
  1584. user_id='user-a',
  1585. is_leader=0,
  1586. tenant_no='tenant-a',
  1587. create_dept_id='',
  1588. del_flag=0,
  1589. ),
  1590. ]
  1591. )
  1592. db.commit()
  1593. out = get_form_options(db, module='presign', ctx=_ctx(), user_info=_user())
  1594. assert '已删除地区' not in str(out)
  1595. assert '不应泄漏医院' not in str(out)
  1596. with pytest.raises(PermissionError, match='地区'):
  1597. get_form_options(
  1598. db,
  1599. module='presign',
  1600. ctx=_ctx(),
  1601. user_info=_user(),
  1602. region_id='deleted-region',
  1603. )
  1604. def test_decorate_allowed_actions_covers_nested_payment_transfers():
  1605. from app.services.market_support import decorate_allowed_actions
  1606. detail = {
  1607. 'id': 'pay-a',
  1608. 'schedules': [
  1609. {
  1610. 'id': 'schedule-a',
  1611. 'scheduleStatus': 'open',
  1612. 'arrearsAmount': '80.00',
  1613. 'transfers': [
  1614. {'id': 'draft', 'payStatus': 'dfj'},
  1615. {'id': 'submitted', 'payStatus': 'jfqrz'},
  1616. {'id': 'done', 'payStatus': 'yjf'},
  1617. ],
  1618. }
  1619. ],
  1620. }
  1621. out = decorate_allowed_actions('payment', detail, scope_kind='specialist')
  1622. assert out['allowedActions'] == ['register-transfer']
  1623. assert out['schedules'][0]['allowedActions'] == ['register-transfer']
  1624. assert [row['allowedActions'] for row in out['schedules'][0]['transfers']] == [
  1625. ['edit-transfer', 'delete-payment-transfer', 'submit-finance'],
  1626. ['withdraw-transfer'],
  1627. [],
  1628. ]
  1629. @pytest.mark.parametrize('protocol_status', ['yzf', 'sdfq', 'zky'])
  1630. def test_payment_terminal_protocol_keeps_transfer_actions_when_arrears_exist(protocol_status):
  1631. from app.services.market_support import decorate_allowed_actions
  1632. detail = {
  1633. 'id': 'pay-terminal',
  1634. 'protocolStatus': protocol_status,
  1635. 'schedules': [
  1636. {
  1637. 'id': 'schedule-open',
  1638. 'scheduleStatus': 'open',
  1639. 'arrearsAmount': '80.00',
  1640. 'transfers': [
  1641. {'id': 'draft', 'payStatus': 'dfj'},
  1642. {'id': 'submitted', 'payStatus': 'jfqrz'},
  1643. ],
  1644. }
  1645. ],
  1646. }
  1647. out = decorate_allowed_actions('payment', detail, scope_kind='specialist')
  1648. assert out['allowedActions'] == ['register-transfer']
  1649. assert out['schedules'][0]['allowedActions'] == ['register-transfer']
  1650. assert [row['allowedActions'] for row in out['schedules'][0]['transfers']] == [
  1651. ['edit-transfer', 'delete-payment-transfer', 'submit-finance'],
  1652. ['withdraw-transfer'],
  1653. ]
  1654. @pytest.mark.parametrize(
  1655. ('schedule_status', 'arrears_amount', 'expected_schedule_actions'),
  1656. [('cleared', '80.00', ['register-transfer']), ('open', '0.00', []), ('void', '80.00', [])],
  1657. )
  1658. def test_payment_schedule_actions_require_non_void_status_and_positive_arrears(
  1659. schedule_status, arrears_amount, expected_schedule_actions
  1660. ):
  1661. from app.services.market_support import decorate_allowed_actions
  1662. detail = {
  1663. 'id': 'pay-closed',
  1664. 'protocolStatus': 'sxz',
  1665. 'schedules': [
  1666. {
  1667. 'id': 'schedule-closed',
  1668. 'scheduleStatus': schedule_status,
  1669. 'arrearsAmount': arrears_amount,
  1670. 'transfers': [{'id': 'draft', 'payStatus': 'dfj'}],
  1671. }
  1672. ],
  1673. }
  1674. out = decorate_allowed_actions('payment', detail, scope_kind='specialist')
  1675. assert out['allowedActions'] == expected_schedule_actions
  1676. assert out['schedules'][0]['allowedActions'] == expected_schedule_actions
  1677. assert out['schedules'][0]['transfers'][0]['allowedActions'] == [
  1678. 'edit-transfer',
  1679. 'delete-payment-transfer',
  1680. 'submit-finance',
  1681. ]
  1682. def test_freight_detail_exposes_only_scope_safe_link_actions():
  1683. from app.services.market_support import decorate_allowed_actions
  1684. specialist = decorate_allowed_actions(
  1685. 'freight',
  1686. {'id': 'f1', 'allowedActions': ['edit', 'link', 'unlink']},
  1687. scope_kind='specialist',
  1688. detail=True,
  1689. )
  1690. manager = decorate_allowed_actions(
  1691. 'freight',
  1692. {'id': 'f1', 'allowedActions': ['link', 'unlink']},
  1693. scope_kind='manager',
  1694. detail=True,
  1695. )
  1696. assert specialist['allowedActions'] == ['edit', 'link', 'unlink']
  1697. assert manager['allowedActions'] == ['link', 'unlink']
  1698. def test_protocol_detail_action_reads_nested_basic_status():
  1699. from app.services.market_support import decorate_allowed_actions
  1700. active = decorate_allowed_actions(
  1701. 'protocol', {'basic': {'protocolStatus': 'dsx'}}, scope_kind='specialist'
  1702. )
  1703. terminal = decorate_allowed_actions(
  1704. 'protocol', {'basic': {'protocolStatus': 'yzf'}}, scope_kind='specialist'
  1705. )
  1706. assert active['allowedActions'] == ['edit', 'delete']
  1707. assert terminal['allowedActions'] == ['edit', 'delete']
  1708. def test_market_support_routes_are_fixed_and_registered_before_dynamic_details():
  1709. from app.api.market_mobile import router
  1710. paths = [route.path for route in router.routes]
  1711. for scope in ('specialist', 'manager'):
  1712. for path in (
  1713. f'/mini/market/{scope}/presign-orders/form-options',
  1714. f'/mini/market/{scope}/protocols/form-options',
  1715. f'/mini/market/{scope}/payments/form-options',
  1716. f'/mini/market/{scope}/freights/form-options',
  1717. ):
  1718. assert path in paths
  1719. for module in ('presign', 'protocol', 'payment'):
  1720. upload_path = f'/mini/market/{scope}/{module}/attachments'
  1721. download_path = f'{upload_path}/download-url'
  1722. assert upload_path in paths
  1723. assert download_path in paths
  1724. upload_route = next(route for route in router.routes if route.path == upload_path)
  1725. download_route = next(route for route in router.routes if route.path == download_path)
  1726. assert [param.name for param in upload_route.dependant.query_params] == []
  1727. assert download_route.methods == {'POST'}
  1728. assert f'/mini/market/{scope}/sample/attachments' not in paths
  1729. assert paths.index(f'/mini/market/{scope}/presign-orders/form-options') < paths.index(
  1730. f'/mini/market/{scope}/presign-orders/{{order_id}}'
  1731. )
  1732. assert paths.index(f'/mini/market/{scope}/protocols/form-options') < paths.index(
  1733. f'/mini/market/{scope}/protocols/{{protocol_id}}'
  1734. )
  1735. assert f'/mini/market/{scope}/samples/form-options' not in paths
  1736. def test_presign_write_routes_use_fixed_paths_and_methods():
  1737. from app.api.market_mobile import router
  1738. for scope in ('specialist', 'manager'):
  1739. expected = {
  1740. f'/mini/market/{scope}/presign-orders/{{order_id}}': {'GET', 'PUT', 'DELETE'},
  1741. f'/mini/market/{scope}/presign-orders/{{order_id}}/transfers': {'POST'},
  1742. f'/mini/market/{scope}/presign-transfers/{{transfer_id}}': {'PUT', 'DELETE'},
  1743. f'/mini/market/{scope}/presign-transfers/{{transfer_id}}/submit': {'POST'},
  1744. f'/mini/market/{scope}/presign-transfers/{{transfer_id}}/withdraw': {'POST'},
  1745. }
  1746. for path, methods in expected.items():
  1747. registered = {
  1748. method
  1749. for route in router.routes
  1750. if route.path == path
  1751. for method in route.methods
  1752. }
  1753. assert registered == methods
  1754. def test_presign_write_routes_map_permission_and_validation_errors(monkeypatch):
  1755. from app.api import market_mobile
  1756. from app.schemas.market_mobile import MarketPresignTransferBody
  1757. delete_route = next(
  1758. route
  1759. for route in market_mobile.router.routes
  1760. if route.path == '/mini/market/specialist/presign-orders/{order_id}'
  1761. and route.methods == {'DELETE'}
  1762. )
  1763. create_transfer_route = next(
  1764. route
  1765. for route in market_mobile.router.routes
  1766. if route.path
  1767. == '/mini/market/specialist/presign-orders/{order_id}/transfers'
  1768. )
  1769. monkeypatch.setattr(
  1770. market_mobile.market_presign,
  1771. 'delete_presign_order',
  1772. lambda *args, **kwargs: (_ for _ in ()).throw(PermissionError('forbidden')),
  1773. )
  1774. permission_result = asyncio.run(
  1775. delete_route.endpoint(order_id='o1', user=_user(), db=SimpleNamespace())
  1776. )
  1777. assert permission_result['code'] == 403
  1778. monkeypatch.setattr(
  1779. market_mobile.market_presign,
  1780. 'create_presign_transfer',
  1781. lambda *args, **kwargs: (_ for _ in ()).throw(ValueError('invalid')),
  1782. )
  1783. validation_result = asyncio.run(
  1784. create_transfer_route.endpoint(
  1785. order_id='o1',
  1786. body=MarketPresignTransferBody(transferAmount=100),
  1787. user=_user(),
  1788. db=SimpleNamespace(),
  1789. )
  1790. )
  1791. assert validation_result['code'] == 400
  1792. def test_market_list_routes_map_invalid_filters_to_validation_response(monkeypatch):
  1793. from app.api import market_mobile
  1794. route_paths = {
  1795. '/mini/market/specialist/protocols': market_mobile.market_protocol,
  1796. '/mini/market/specialist/payments': market_mobile.market_payment,
  1797. '/mini/market/specialist/freights': market_mobile.market_freight,
  1798. }
  1799. routes = {
  1800. route.path: route
  1801. for route in market_mobile.router.routes
  1802. if route.path in route_paths and route.methods == {'GET'}
  1803. }
  1804. for path, service in route_paths.items():
  1805. method_name = {
  1806. '/mini/market/specialist/protocols': 'list_protocols',
  1807. '/mini/market/specialist/payments': 'list_payments',
  1808. '/mini/market/specialist/freights': 'list_freights',
  1809. }[path]
  1810. monkeypatch.setattr(
  1811. service,
  1812. method_name,
  1813. lambda *args, **kwargs: (_ for _ in ()).throw(ValueError('invalid filter')),
  1814. )
  1815. result = asyncio.run(
  1816. routes[path].endpoint(user=_user(), db=SimpleNamespace())
  1817. )
  1818. assert result['code'] == 400
  1819. assert result['message'] == 'invalid filter'
  1820. def test_attachment_routes_read_only_their_module_upload_limit(monkeypatch):
  1821. from app.api import market_mobile
  1822. class TrackingUpload:
  1823. filename = 'proof.pdf'
  1824. content_type = 'application/pdf'
  1825. def __init__(self):
  1826. self.read_size = None
  1827. async def read(self, size):
  1828. self.read_size = size
  1829. return b'%PDF-safe'
  1830. async def close(self):
  1831. return None
  1832. monkeypatch.setattr(
  1833. market_mobile.market_support,
  1834. 'save_market_attachment',
  1835. lambda *args, **kwargs: {'id': 'attachment'},
  1836. )
  1837. routes = {
  1838. route.path: route
  1839. for route in market_mobile.router.routes
  1840. if route.path in {
  1841. '/mini/market/specialist/presign/attachments',
  1842. '/mini/market/specialist/payment/attachments',
  1843. }
  1844. }
  1845. presign_file = TrackingUpload()
  1846. payment_file = TrackingUpload()
  1847. asyncio.run(
  1848. routes['/mini/market/specialist/presign/attachments'].endpoint(
  1849. file=presign_file, user=_user(), db=SimpleNamespace()
  1850. )
  1851. )
  1852. asyncio.run(
  1853. routes['/mini/market/specialist/payment/attachments'].endpoint(
  1854. file=payment_file, user=_user(), db=SimpleNamespace()
  1855. )
  1856. )
  1857. assert presign_file.read_size == 20 * 1024 * 1024 + 1
  1858. assert payment_file.read_size == 10 * 1024 * 1024 + 1
  1859. def test_payment_transfer_response_carries_server_authorized_capabilities():
  1860. draft = market_support.decorate_allowed_actions(
  1861. 'payment-transfer',
  1862. {'id': 't1', 'payStatus': 'dfj'},
  1863. scope_kind='specialist',
  1864. )
  1865. pending = market_support.decorate_allowed_actions(
  1866. 'payment-transfer',
  1867. {'id': 't2', 'payStatus': 'jfqrz'},
  1868. scope_kind='specialist',
  1869. )
  1870. assert draft['allowedActions'] == [
  1871. 'edit-transfer',
  1872. 'delete-payment-transfer',
  1873. 'submit-finance',
  1874. ]
  1875. assert pending['allowedActions'] == ['withdraw-transfer']