test_market_freight_scope.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. """市场移动端运费批次:作用域、脱敏与原子写规则。"""
  2. from datetime import datetime, timedelta
  3. from decimal import Decimal
  4. from pathlib import Path
  5. import pytest
  6. from fastapi import HTTPException
  7. from pydantic import ValidationError
  8. from sqlalchemy import create_engine
  9. from sqlalchemy.dialects import mysql
  10. from sqlalchemy.orm import sessionmaker
  11. from app.models.base import Base
  12. from app.models.models import (
  13. BizCellSampleType, BizCollectionProtocol, BizCollectionRegionStaff, BizProtocolCollectionInfo,
  14. BizProtocolPartyCustomer, BizProtocolSample, BizSampleFreight,
  15. BizSampleFreightItem, SysDictData, SysDictType, SysPost, SysPostRole,
  16. SysDept, SysRole, SysRoleDataScopeDetail, SysUser, SysUserPost, SysUserRole,
  17. )
  18. from app.models.research_donation import (
  19. BizResearchDonation, BizResearchDonationCollection,
  20. BizResearchDonationParty, BizResearchDonationSample,
  21. )
  22. from app.services.market_field_scope import MarketFieldContext
  23. TABLES = [
  24. BizCollectionProtocol.__table__, BizProtocolCollectionInfo.__table__,
  25. BizProtocolPartyCustomer.__table__, BizProtocolSample.__table__,
  26. BizResearchDonation.__table__, BizResearchDonationCollection.__table__,
  27. BizResearchDonationParty.__table__, BizResearchDonationSample.__table__,
  28. BizSampleFreight.__table__, BizSampleFreightItem.__table__,
  29. BizCellSampleType.__table__,
  30. BizCollectionRegionStaff.__table__, SysDictType.__table__,
  31. SysDictData.__table__, SysUser.__table__, SysRole.__table__,
  32. SysRoleDataScopeDetail.__table__, SysUserRole.__table__, SysPost.__table__,
  33. SysPostRole.__table__, SysUserPost.__table__, SysDept.__table__,
  34. ]
  35. def _session():
  36. engine = create_engine('sqlite:///:memory:')
  37. Base.metadata.create_all(engine, tables=TABLES)
  38. db = sessionmaker(bind=engine)()
  39. now = datetime(2026, 10, 11, 8, 0)
  40. db.add_all([
  41. SysDictType(id='dt', dict_name='运输方式', dict_type='sample_transport_mode', tenant_no='tenant-a', create_dept_id='', create_time=now, update_time=now, del_flag=0),
  42. SysDictData(id='dd', dict_label='顺丰', dict_value='sf', dict_type='sample_transport_mode', tenant_no='tenant-a', create_dept_id='', create_time=now, update_time=now, del_flag=0),
  43. SysUser(id='u1', dept_id='', user_no='u1', nick_name='专员', password='', tenant_no='tenant-a', create_dept_id='', create_time=now, update_time=now, del_flag=0),
  44. SysUser(id='m1', dept_id='', user_no='m1', nick_name='经理', password='', tenant_no='tenant-a', create_dept_id='', create_time=now, update_time=now, del_flag=0),
  45. SysRole(id='fixture-super-role', role_name='超级管理员', data_scope='1', status='1', tenant_no='tenant-a', create_dept_id='', create_time=now, update_time=now, del_flag=0),
  46. SysUserRole(id='fixture-super-u1', user_id='u1', role_id='fixture-super-role', tenant_no='tenant-a', create_dept_id='', create_time=now, update_time=now, del_flag=0),
  47. SysUserRole(id='fixture-super-m1', user_id='m1', role_id='fixture-super-role', tenant_no='tenant-a', create_dept_id='', create_time=now, update_time=now, del_flag=0),
  48. ])
  49. db.commit()
  50. return db
  51. def _ctx(kind='specialist', user_id='u1'):
  52. return MarketFieldContext('tenant-a', user_id, kind)
  53. def _user(user_id='u1'):
  54. return {'user_id': user_id, 'tenant_no': 'tenant-a', 'role': 'super_admin'}
  55. def _sample(db, key, *, source='cell_storage', sales='u1', manager='m1', region='r1', tenant='tenant-a', deleted=0, created=None):
  56. created = created or datetime(2026, 10, 10, 8, 0)
  57. if source == 'cell_storage':
  58. parent = BizCollectionProtocol(id=f'cp-{key}', protocol_no=f'CP-{key}', tenant_no=tenant, create_dept_id='', create_time=created, del_flag=deleted)
  59. collection = BizProtocolCollectionInfo(id=f'cc-{key}', collection_protocol_id=parent.id, region_id=region, sales_user_id=sales, region_manager_user_id=manager, tenant_no=tenant, create_dept_id='', create_time=created, del_flag=deleted)
  60. party = BizProtocolPartyCustomer(id=f'pc-{key}', collection_protocol_id=parent.id, mother_name=f'客户-{key}', tenant_no=tenant, create_dept_id='', create_time=created, del_flag=deleted)
  61. sample = BizProtocolSample(id=f'cs-{key}', collection_protocol_id=parent.id, sample_code=f'C-{key}', tenant_no=tenant, create_dept_id='', create_time=created, del_flag=deleted)
  62. else:
  63. parent = BizResearchDonation(id=f'rd-{key}', donation_no=f'RD-{key}', tenant_no=tenant, create_dept_id='', create_time=created, del_flag=deleted)
  64. collection = BizResearchDonationCollection(id=f'rc-{key}', research_donation_id=parent.id, region_id=region, sales_user_id=sales, region_manager_user_id=manager, tenant_no=tenant, create_dept_id='', create_time=created, del_flag=deleted)
  65. party = BizResearchDonationParty(id=f'rp-{key}', research_donation_id=parent.id, mother_name=f'客户-{key}', tenant_no=tenant, create_dept_id='', create_time=created, del_flag=deleted)
  66. sample = BizResearchDonationSample(id=f'rs-{key}', research_donation_id=parent.id, sample_code=f'R-{key}', tenant_no=tenant, create_dept_id='', create_time=created, del_flag=deleted)
  67. db.add_all([parent, collection, party, sample])
  68. db.commit()
  69. return sample, parent
  70. def _freight(db, key, samples, *, tenant='tenant-a', amount='12.30', deleted=0, create_by='u1'):
  71. now = datetime(2026, 10, 11, 8, 0)
  72. freight = BizSampleFreight(id=f'f-{key}', freight_no=f'YF-{key}', transport_mode='sf', freight_amount=Decimal(amount), tenant_no=tenant, create_by=create_by, create_dept_id='', create_time=now, update_time=now, del_flag=deleted)
  73. db.add(freight)
  74. for pos, (source, sample, parent) in enumerate(samples):
  75. db.add(BizSampleFreightItem(id=f'fi-{key}-{pos}', freight_id=freight.id, sample_source=source, sample_id=sample.id, sample_code=sample.sample_code, protocol_id=parent.id, tenant_no=tenant, create_dept_id='', create_time=now, update_time=now, del_flag=0))
  76. db.commit()
  77. return freight
  78. def _items(*pairs):
  79. return [{'sampleSource': source, 'sampleId': sample.id} for source, sample in pairs]
  80. def test_specialist_sees_shared_batch_but_only_own_items_and_count():
  81. from app.services.market_freight import get_freight_detail, list_freights
  82. db = _session()
  83. own, own_parent = _sample(db, 'own')
  84. other, other_parent = _sample(db, 'other', sales='u2')
  85. freight = _freight(db, 'mixed', [('cell_storage', own, own_parent), ('cell_storage', other, other_parent)])
  86. rows, total = list_freights(db, ctx=_ctx(), user_info=_user(), include_items=True)
  87. detail = get_freight_detail(db, freight.id, ctx=_ctx(), user_info=_user())
  88. assert total == 1 and rows[0]['visibleItemCount'] == 1
  89. assert [item['sampleCode'] for item in rows[0]['items']] == ['C-own']
  90. assert [item['sampleCode'] for item in detail['items']] == ['C-own']
  91. assert rows[0]['createBy'] == detail['createBy'] == 'u1'
  92. assert rows[0]['createByName'] == detail['createByName'] == '专员'
  93. assert 'linkedSampleCount' not in rows[0] and 'linkedSampleCount' not in detail
  94. assert 'hasHiddenItems' not in detail
  95. def test_freight_creator_name_uses_historical_nickname_without_id_fallback():
  96. from app.services.market_freight import get_freight_detail, list_freights
  97. db = _session()
  98. now = datetime(2026, 10, 11, 8, 0)
  99. db.add_all(
  100. [
  101. SysUser(id='deleted-creator', dept_id='', user_no='deleted-no', nick_name='历史创建人', password='', tenant_no='tenant-a', create_dept_id='', create_time=now, update_time=now, del_flag=1),
  102. SysUser(id='blank-creator', dept_id='', user_no='raw-creator-no', nick_name='', password='', tenant_no='tenant-a', create_dept_id='', create_time=now, update_time=now, del_flag=1),
  103. ]
  104. )
  105. first_sample, first_parent = _sample(db, 'creator-history')
  106. second_sample, second_parent = _sample(db, 'creator-blank')
  107. historical = _freight(
  108. db,
  109. 'creator-history',
  110. [('cell_storage', first_sample, first_parent)],
  111. create_by='deleted-creator',
  112. )
  113. blank = _freight(
  114. db,
  115. 'creator-blank',
  116. [('cell_storage', second_sample, second_parent)],
  117. create_by='blank-creator',
  118. )
  119. items, total = list_freights(db, ctx=_ctx(), user_info=_user())
  120. by_id = {item['id']: item for item in items}
  121. historical_detail = get_freight_detail(
  122. db, historical.id, ctx=_ctx(), user_info=_user()
  123. )
  124. blank_detail = get_freight_detail(
  125. db, blank.id, ctx=_ctx(), user_info=_user()
  126. )
  127. assert total == 2
  128. assert by_id[historical.id]['createByName'] == '历史创建人'
  129. assert historical_detail['createByName'] == '历史创建人'
  130. assert by_id[blank.id]['createByName'] == ''
  131. assert blank_detail['createByName'] == ''
  132. def test_batch_without_visible_item_is_not_listed_or_addressable():
  133. from app.services.market_freight import get_freight_detail, list_freights
  134. db = _session()
  135. other, parent = _sample(db, 'other', sales='u2')
  136. freight = _freight(db, 'hidden', [('cell_storage', other, parent)])
  137. assert list_freights(db, ctx=_ctx(), user_info=_user())[1] == 0
  138. with pytest.raises(HTTPException) as exc:
  139. get_freight_detail(db, freight.id, ctx=_ctx(), user_info=_user())
  140. assert exc.value.status_code == 404
  141. def test_keyword_and_source_filters_use_only_visible_items():
  142. from app.services.market_freight import list_freights
  143. db = _session()
  144. own, op = _sample(db, 'own')
  145. secret, sp = _sample(db, 'SECRET', source='research_donation', sales='u2')
  146. _freight(db, 'mixed', [('cell_storage', own, op), ('research_donation', secret, sp)])
  147. assert list_freights(db, ctx=_ctx(), user_info=_user(), keyword='SECRET')[1] == 0
  148. assert list_freights(db, ctx=_ctx(), user_info=_user(), sample_source='research_donation')[1] == 0
  149. assert list_freights(db, ctx=_ctx(), user_info=_user(), sample_source='cell_storage')[1] == 1
  150. def test_freight_list_filters_create_time_range():
  151. from app.services.market_freight import list_freights
  152. db = _session()
  153. first, first_parent = _sample(db, 'created-in-range')
  154. second, second_parent = _sample(db, 'created-outside')
  155. in_range = _freight(
  156. db,
  157. 'created-in-range',
  158. [('cell_storage', first, first_parent)],
  159. )
  160. outside = _freight(
  161. db,
  162. 'created-outside',
  163. [('cell_storage', second, second_parent)],
  164. )
  165. in_range.create_time = datetime(2026, 10, 11, 8, 0)
  166. outside.create_time = datetime(2026, 9, 1, 8, 0)
  167. db.commit()
  168. items, total = list_freights(
  169. db,
  170. ctx=_ctx(),
  171. user_info=_user(),
  172. create_time_start='2026-10-01',
  173. create_time_end='2026-10-13',
  174. )
  175. assert total == 1
  176. assert [item['id'] for item in items] == [in_range.id]
  177. def test_manager_scope_is_region_union_document_manager_for_both_sources():
  178. from app.services.market_freight import get_freight_detail
  179. db = _session()
  180. db.add(BizCollectionRegionStaff(id='staff', region_id='managed', user_id='m1', is_leader=1, tenant_no='tenant-a', create_dept_id='', del_flag=0))
  181. db.commit()
  182. region_sample, rp = _sample(db, 'region', sales='u9', manager='x', region='managed')
  183. assigned, ap = _sample(db, 'assigned', source='research_donation', sales='u9', manager='m1', region='other')
  184. hidden, hp = _sample(db, 'hidden', sales='m1', manager='x', region='other')
  185. freight = _freight(db, 'manager', [('cell_storage', region_sample, rp), ('research_donation', assigned, ap), ('cell_storage', hidden, hp)])
  186. detail = get_freight_detail(db, freight.id, ctx=_ctx('manager', 'm1'), user_info=_user('m1'))
  187. assert {item['sampleCode'] for item in detail['items']} == {'C-region', 'R-assigned'}
  188. assert detail['visibleItemCount'] == 2
  189. assert all('sampleTypeName' in item and 'motherName' in item and 'newbornName' in item for item in detail['items'])
  190. def test_dual_role_uses_fixed_route_context_not_union_between_pages():
  191. from app.services.market_freight import list_freights
  192. db = _session()
  193. specialist, sp = _sample(db, 'specialist', sales='m1', manager='x', region='other')
  194. manager, mp = _sample(db, 'manager', sales='u9', manager='m1', region='other')
  195. _freight(db, 'specialist', [('cell_storage', specialist, sp)])
  196. _freight(db, 'manager', [('cell_storage', manager, mp)])
  197. specialist_rows, _ = list_freights(db, ctx=_ctx('specialist', 'm1'), user_info=_user('m1'))
  198. manager_rows, _ = list_freights(db, ctx=_ctx('manager', 'm1'), user_info=_user('m1'))
  199. assert [row['freightNo'] for row in specialist_rows] == ['YF-specialist']
  200. assert [row['freightNo'] for row in manager_rows] == ['YF-manager']
  201. def test_cross_tenant_deleted_parent_and_deleted_sample_are_invisible():
  202. from app.services.market_freight import list_freights
  203. db = _session()
  204. cross, cp = _sample(db, 'cross', tenant='tenant-b')
  205. deleted, dp = _sample(db, 'deleted', deleted=1)
  206. _freight(db, 'cross', [('cell_storage', cross, cp)], tenant='tenant-b')
  207. _freight(db, 'deleted', [('cell_storage', deleted, dp)])
  208. assert list_freights(db, ctx=_ctx(), user_info=_user())[1] == 0
  209. def test_sample_options_are_scoped_sql_paginated_stable_and_derive_link_state():
  210. from app.services.market_freight import list_sample_options
  211. db = _session()
  212. base = datetime(2026, 10, 10, 8, 0)
  213. first, fp = _sample(db, 'first', created=base)
  214. _sample(db, 'second', source='research_donation', created=base + timedelta(hours=1))
  215. _sample(db, 'third', created=base + timedelta(hours=2))
  216. _sample(db, 'hidden', sales='u2', created=base + timedelta(hours=3))
  217. _freight(db, 'linked', [('cell_storage', first, fp)])
  218. page1, total = list_sample_options(db, ctx=_ctx(), user_info=_user(), page=1, page_size=2)
  219. page2, total2 = list_sample_options(db, ctx=_ctx(), user_info=_user(), page=2, page_size=2)
  220. assert total == total2 == 3
  221. assert [x['sampleCode'] for x in page1] == ['C-third', 'R-second']
  222. assert [x['sampleCode'] for x in page2] == ['C-first']
  223. assert page2[0]['freightId'] == 'f-linked'
  224. assert page2[0]['freightNo'] == 'YF-linked'
  225. assert set(('protocolNo', 'customerName', 'newbornName', 'sampleTypeName')).issubset(page2[0])
  226. def test_create_derives_snapshots_and_decimal_string_and_requires_visible_item():
  227. from app.services.market_freight import create_freight
  228. db = _session()
  229. own, parent = _sample(db, 'own')
  230. result = create_freight(db, ctx=_ctx(), user_info=_user(), transport_mode='sf', freight_amount=Decimal('12.30'), items=_items(('cell_storage', own)))
  231. item = db.query(BizSampleFreightItem).filter_by(freight_id=result['id']).one()
  232. assert result['freightAmount'] == '12.30'
  233. assert item.sample_code == 'C-own' and item.protocol_id == parent.id
  234. with pytest.raises(ValueError, match='至少'):
  235. create_freight(db, ctx=_ctx(), user_info=_user(), transport_mode='sf', freight_amount='1.00', items=[])
  236. def test_create_prevalidates_every_item_and_rolls_back_without_partial_batch():
  237. from app.services.market_freight import create_freight
  238. db = _session()
  239. own, _ = _sample(db, 'own')
  240. other, _ = _sample(db, 'other', sales='u2')
  241. before = db.query(BizSampleFreight).count()
  242. with pytest.raises(HTTPException):
  243. create_freight(db, ctx=_ctx(), user_info=_user(), transport_mode='sf', freight_amount='1.00', items=_items(('cell_storage', own), ('cell_storage', other)))
  244. assert db.query(BizSampleFreight).count() == before
  245. def test_link_rejects_hidden_and_existing_other_batch_without_silent_move():
  246. from app.services.market_freight import link_samples
  247. db = _session()
  248. own, op = _sample(db, 'own')
  249. other, _ = _sample(db, 'other', sales='u2')
  250. linked, lp = _sample(db, 'linked')
  251. target = _freight(db, 'target', [('cell_storage', own, op)])
  252. source = _freight(db, 'source', [('cell_storage', linked, lp)])
  253. for sample in (other, linked):
  254. with pytest.raises((HTTPException, ValueError)):
  255. link_samples(db, target.id, ctx=_ctx(), user_info=_user(), items=_items(('cell_storage', sample)))
  256. assert db.query(BizSampleFreightItem).filter_by(sample_id=linked.id, del_flag=0).one().freight_id == source.id
  257. def test_unlink_prevalidates_all_items_and_rejects_hidden_or_nonexistent():
  258. from app.services.market_freight import unlink_samples
  259. db = _session()
  260. own, op = _sample(db, 'own')
  261. other, hp = _sample(db, 'hidden', sales='u2')
  262. freight = _freight(db, 'mixed', [('cell_storage', own, op), ('cell_storage', other, hp)])
  263. missing, _ = _sample(db, 'missing')
  264. for sample in (other, missing):
  265. with pytest.raises((HTTPException, ValueError)):
  266. unlink_samples(db, freight.id, ctx=_ctx(), user_info=_user(), items=_items(('cell_storage', sample)))
  267. assert db.query(BizSampleFreightItem).filter_by(freight_id=freight.id, del_flag=0).count() == 2
  268. def test_unlink_last_visible_item_disappears_without_revealing_hidden_remaining():
  269. from app.services.market_freight import list_freights, unlink_samples
  270. db = _session()
  271. own, op = _sample(db, 'own')
  272. other, hp = _sample(db, 'hidden', sales='u2')
  273. freight = _freight(db, 'mixed', [('cell_storage', own, op), ('cell_storage', other, hp)])
  274. result = unlink_samples(db, freight.id, ctx=_ctx(), user_info=_user(), items=_items(('cell_storage', own)))
  275. assert result == {'id': freight.id, 'visibleItemCount': 0, 'disappeared': True}
  276. assert list_freights(db, ctx=_ctx(), user_info=_user())[1] == 0
  277. assert db.query(BizSampleFreight).filter_by(id=freight.id).one().del_flag == 0
  278. @pytest.mark.parametrize('kind,user_id', [('specialist', 'u1'), ('manager', 'm1')])
  279. def test_shared_outside_scope_header_is_immutable_for_both_roles(kind, user_id):
  280. from app.services.market_freight import update_freight
  281. db = _session()
  282. visible, vp = _sample(db, 'visible', sales=user_id if kind == 'specialist' else 'u9', manager=user_id if kind == 'manager' else 'x')
  283. hidden, hp = _sample(db, 'hidden', sales='other', manager='other')
  284. freight = _freight(db, 'mixed', [('cell_storage', visible, vp), ('cell_storage', hidden, hp)])
  285. with pytest.raises(PermissionError, match='全部'):
  286. update_freight(db, freight.id, ctx=_ctx(kind, user_id), user_info=_user(user_id), freight_amount='99.00')
  287. assert db.query(BizSampleFreight).filter_by(id=freight.id).one().freight_amount == Decimal('12.30')
  288. def test_header_update_allowed_when_all_active_items_are_visible():
  289. from app.services.market_freight import update_freight
  290. db = _session()
  291. own, op = _sample(db, 'own')
  292. freight = _freight(db, 'own', [('cell_storage', own, op)])
  293. result = update_freight(db, freight.id, ctx=_ctx(), user_info=_user(), freight_amount='99.10')
  294. assert result['freightAmount'] == '99.10'
  295. @pytest.mark.parametrize('kind,user_id', [('specialist', 'u1'), ('manager', 'm1')])
  296. @pytest.mark.parametrize('mixed', [False, True])
  297. def test_detail_edit_action_requires_every_active_item_visible_without_leaking_totals(
  298. kind, user_id, mixed
  299. ):
  300. from app.services.market_freight import get_freight_detail
  301. from app.services.market_support import decorate_allowed_actions
  302. db = _session()
  303. visible, visible_parent = _sample(
  304. db,
  305. f'action-visible-{kind}-{mixed}',
  306. sales=user_id if kind == 'specialist' else 'other-sales',
  307. manager=user_id if kind == 'manager' else 'other-manager',
  308. )
  309. rows = [('cell_storage', visible, visible_parent)]
  310. if mixed:
  311. hidden, hidden_parent = _sample(
  312. db,
  313. f'action-hidden-{kind}',
  314. sales='hidden-sales',
  315. manager='hidden-manager',
  316. )
  317. rows.append(('cell_storage', hidden, hidden_parent))
  318. freight = _freight(db, f'action-{kind}-{mixed}', rows)
  319. detail = get_freight_detail(
  320. db,
  321. freight.id,
  322. ctx=_ctx(kind, user_id),
  323. user_info=_user(user_id),
  324. )
  325. rendered = decorate_allowed_actions(
  326. 'freight', detail, scope_kind=kind, detail=True
  327. )
  328. expected = ['link', 'unlink'] if mixed else ['edit', 'delete', 'link', 'unlink']
  329. assert detail['allowedActions'] == expected
  330. assert rendered['allowedActions'] == expected
  331. for hidden_key in (
  332. 'allItemsVisible',
  333. 'hiddenItemCount',
  334. 'totalItemCount',
  335. 'activeItemCount',
  336. ):
  337. assert hidden_key not in detail
  338. def test_dto_forbids_scope_snapshots_status_and_non_decimal_amounts():
  339. from app.schemas.market_mobile import MarketFreightCreateBody, MarketFreightItemsBody
  340. with pytest.raises(ValidationError):
  341. MarketFreightItemsBody.model_validate({'items': [{'sampleSource': 'cell_storage', 'sampleId': 's1', 'sampleCode': 'forged'}]})
  342. for extra in ('tenantNo', 'scope', 'status'):
  343. with pytest.raises(ValidationError):
  344. MarketFreightCreateBody.model_validate({'transportMode': 'sf', 'freightAmount': '1.00', 'items': [{'sampleSource': 'cell_storage', 'sampleId': 's1'}], extra: 'x'})
  345. with pytest.raises(ValidationError):
  346. MarketFreightCreateBody.model_validate({'transportMode': 'sf', 'freightAmount': 'NaN', 'items': [{'sampleSource': 'cell_storage', 'sampleId': 's1'}]})
  347. def test_fixed_routes_and_precise_permissions_are_registered():
  348. from app.api.market_mobile import router
  349. paths = [(route.path, route.methods) for route in router.routes]
  350. for kind in ('specialist', 'manager'):
  351. prefix = f'/mini/market/{kind}/freights'
  352. assert any(path == prefix and 'GET' in methods for path, methods in paths)
  353. assert any(path == prefix and 'POST' in methods for path, methods in paths)
  354. assert any(path == f'{prefix}/sample-options' and 'GET' in methods for path, methods in paths)
  355. source = (Path(__file__).parents[1] / 'app/api/market_mobile.py').read_text()
  356. assert "f'mini:market:{scope_kind}:freight'" in source
  357. def test_migration_has_mysql57_indexes_unique_active_link_and_duplicate_preflight():
  358. sql = (Path(__file__).parents[2] / 'docs/sql/migrations/2026-10-11-market-freight-indexes.sql').read_text()
  359. lowered = sql.lower()
  360. assert 'information_schema.statistics' in lowered
  361. assert 'generated always as' in lowered
  362. assert 'unique' in lowered and 'active' in lowered
  363. assert 'group by tenant_no, sample_source, sample_id' in lowered
  364. assert 'having count(*) > 1' in lowered
  365. assert 'create procedure' in lowered and 'signal sqlstate' in lowered
  366. assert 'character_maximum_length' in lowered
  367. assert 'data_type' in lowered and 'is_nullable' in lowered
  368. assert 'normalized_generation_expression' in lowered
  369. assert "uk_sample_freight_tenant_no" in lowered
  370. assert 'exact_freight_unique_indexes' in lowered
  371. def test_write_service_contains_locking_postlock_validation_and_integrity_retry():
  372. source = (Path(__file__).parents[1] / 'app/services/market_freight.py').read_text()
  373. assert source.count('with_for_update') >= 3
  374. assert 'IntegrityError' in source
  375. assert '_lock_batch_header' in source
  376. assert '_lock_sample_graph' in source
  377. assert '_lock_active_items' in source
  378. def test_multiple_party_rows_do_not_duplicate_visible_item_or_count():
  379. from app.services.market_freight import get_freight_detail
  380. db = _session()
  381. sample, parent = _sample(db, 'one')
  382. db.add(BizProtocolPartyCustomer(id='pc-one-duplicate', collection_protocol_id=parent.id, mother_name='重复客户行', tenant_no='tenant-a', create_dept_id='', del_flag=0))
  383. db.commit()
  384. freight = _freight(db, 'one', [('cell_storage', sample, parent)])
  385. detail = get_freight_detail(db, freight.id, ctx=_ctx(), user_info=_user())
  386. assert detail['visibleItemCount'] == 1
  387. assert len(detail['items']) == 1
  388. def test_deleted_batch_is_invisible_even_with_visible_active_item():
  389. from app.services.market_freight import list_freights
  390. db = _session()
  391. sample, parent = _sample(db, 'one')
  392. _freight(db, 'deleted-batch', [('cell_storage', sample, parent)], deleted=1)
  393. assert list_freights(db, ctx=_ctx(), user_info=_user())[1] == 0
  394. def test_context_user_mismatch_fails_closed():
  395. from app.services.market_freight import list_sample_options
  396. db = _session()
  397. _sample(db, 'one')
  398. with pytest.raises(PermissionError):
  399. list_sample_options(db, ctx=_ctx(), user_info=_user('u2'))
  400. def test_manager_can_link_sample_in_managed_region():
  401. from app.services.market_freight import link_samples
  402. db = _session()
  403. db.add(BizCollectionRegionStaff(id='staff-link', region_id='managed', user_id='m1', is_leader=1, tenant_no='tenant-a', create_dept_id='', del_flag=0))
  404. db.commit()
  405. existing, ep = _sample(db, 'existing', sales='u9', manager='m1')
  406. new_sample, _ = _sample(db, 'new', sales='u9', manager='x', region='managed')
  407. freight = _freight(db, 'manager-link', [('cell_storage', existing, ep)])
  408. detail = link_samples(db, freight.id, ctx=_ctx('manager', 'm1'), user_info=_user('m1'), items=_items(('cell_storage', new_sample)))
  409. assert {item['sampleCode'] for item in detail['items']} == {'C-existing', 'C-new'}
  410. def test_batch_paging_is_stable_and_total_counts_only_visible_batches():
  411. from app.services.market_freight import list_freights
  412. db = _session()
  413. first, fp = _sample(db, 'first')
  414. second, sp = _sample(db, 'second')
  415. hidden, hp = _sample(db, 'hidden-page', sales='u2')
  416. f1 = _freight(db, 'first', [('cell_storage', first, fp)])
  417. f2 = _freight(db, 'second', [('cell_storage', second, sp)])
  418. _freight(db, 'hidden-page', [('cell_storage', hidden, hp)])
  419. f1.create_time = f2.create_time
  420. db.commit()
  421. page1, total1 = list_freights(db, ctx=_ctx(), user_info=_user(), page=1, page_size=1)
  422. page2, total2 = list_freights(db, ctx=_ctx(), user_info=_user(), page=2, page_size=1)
  423. assert total1 == total2 == 2
  424. assert [page1[0]['id'], page2[0]['id']] == ['f-second', 'f-first']
  425. @pytest.mark.parametrize('source', ['cell_storage', 'research_donation'])
  426. def test_sample_options_choose_latest_party_once_before_count_and_paging(source):
  427. from app.services.market_freight import list_sample_options
  428. db = _session()
  429. base = datetime(2026, 10, 10, 8, 0)
  430. target, parent = _sample(db, f'duplicate-{source}', source=source, created=base)
  431. _sample(db, f'other-{source}', source=source, created=base + timedelta(hours=1))
  432. if source == 'cell_storage':
  433. db.add(BizProtocolPartyCustomer(
  434. id='zz-latest-cell-party', collection_protocol_id=parent.id,
  435. mother_name='最新细胞客户', tenant_no='tenant-a', create_dept_id='',
  436. create_time=base + timedelta(hours=2), del_flag=0,
  437. ))
  438. latest_name = '最新细胞客户'
  439. else:
  440. db.add(BizResearchDonationParty(
  441. id='zz-latest-donation-party', research_donation_id=parent.id,
  442. mother_name='最新科研客户', tenant_no='tenant-a', create_dept_id='',
  443. create_time=base + timedelta(hours=2), del_flag=0,
  444. ))
  445. latest_name = '最新科研客户'
  446. db.commit()
  447. page1, total1 = list_sample_options(
  448. db, ctx=_ctx(), user_info=_user(), page=1, page_size=1,
  449. sample_source=source,
  450. )
  451. page2, total2 = list_sample_options(
  452. db, ctx=_ctx(), user_info=_user(), page=2, page_size=1,
  453. sample_source=source,
  454. )
  455. rows = page1 + page2
  456. assert total1 == total2 == 2
  457. assert sum(row['sampleId'] == target.id for row in rows) == 1
  458. target_row = next(row for row in rows if row['sampleId'] == target.id)
  459. assert target_row['customerName'] == latest_name
  460. def test_mysql_lock_queries_are_current_reads_with_stable_global_order():
  461. from app.services.market_freight import (
  462. _active_item_lock_query,
  463. _collection_lock_query,
  464. _leader_lock_query,
  465. _sample_parent_lock_query,
  466. )
  467. db = _session()
  468. ctx = _ctx()
  469. sample_sql = str(
  470. _sample_parent_lock_query(
  471. db, 'cell_storage', ['z', 'a'], ctx
  472. ).statement.compile(dialect=mysql.dialect())
  473. ).lower()
  474. collection_sql = str(
  475. _collection_lock_query(
  476. db, 'cell_storage', ['p-z', 'p-a'], ctx
  477. ).statement.compile(dialect=mysql.dialect())
  478. ).lower()
  479. item_sql = str(
  480. _active_item_lock_query(
  481. db, ctx, freight_id='f1', keys=[('cell_storage', 'z')]
  482. ).statement.compile(dialect=mysql.dialect())
  483. ).lower()
  484. leader_sql = str(
  485. _leader_lock_query(db, _ctx('manager', 'm1')).statement.compile(
  486. dialect=mysql.dialect()
  487. )
  488. ).lower()
  489. for sql in (sample_sql, collection_sql, item_sql, leader_sql):
  490. assert ' for update' in sql
  491. assert ' order by ' in sql
  492. assert 'tenant_no' in sql and 'del_flag' in sql
  493. assert 'sales_user_id' in collection_sql
  494. assert 'biz_protocol_collection_info' in collection_sql
  495. assert 'biz_collection_region_staff' in leader_sql
  496. def test_all_write_paths_use_batch_graph_item_lock_order():
  497. source = (Path(__file__).parents[1] / 'app/services/market_freight.py').read_text()
  498. for start_name, end_name in (
  499. ('def update_freight', 'def link_samples'),
  500. ('def link_samples', 'def unlink_samples'),
  501. ('def unlink_samples', 'def delete_freight'),
  502. ('def delete_freight', None),
  503. ):
  504. block = source[source.index(start_name):]
  505. if end_name:
  506. block = block[:block.index(end_name)]
  507. assert block.index('_lock_batch_header') < block.index('_lock_sample_graph')
  508. assert block.index('_lock_sample_graph') < block.index('_lock_active_items')
  509. create_block = source[source.index('def create_freight'):source.index('def update_freight')]
  510. assert create_block.index('_lock_sample_graph') < create_block.index('_lock_active_items')
  511. def test_delete_freight_cascades_when_all_items_visible():
  512. from app.services.market_freight import delete_freight, list_freights, list_sample_options
  513. db = _session()
  514. own, op = _sample(db, 'del-own')
  515. freight = _freight(db, 'del-own', [('cell_storage', own, op)])
  516. result = delete_freight(db, freight.id, ctx=_ctx(), user_info=_user())
  517. assert result == {'id': freight.id, 'visibleItemCount': 0, 'disappeared': True}
  518. assert db.query(BizSampleFreight).filter_by(id=freight.id).one().del_flag == 1
  519. assert db.query(BizSampleFreightItem).filter_by(freight_id=freight.id, del_flag=0).count() == 0
  520. assert list_freights(db, ctx=_ctx(), user_info=_user())[1] == 0
  521. options, total = list_sample_options(db, ctx=_ctx(), user_info=_user(), page=1, page_size=20)
  522. assert total >= 1
  523. assert any(row['sampleId'] == own.id and not row.get('freightId') for row in options)
  524. def test_delete_freight_rejects_when_outside_scope_items_exist():
  525. from app.services.market_freight import delete_freight
  526. db = _session()
  527. own, op = _sample(db, 'del-vis')
  528. other, hp = _sample(db, 'del-hid', sales='u2')
  529. freight = _freight(db, 'del-mixed', [('cell_storage', own, op), ('cell_storage', other, hp)])
  530. with pytest.raises(PermissionError, match='全部'):
  531. delete_freight(db, freight.id, ctx=_ctx(), user_info=_user())
  532. assert db.query(BizSampleFreight).filter_by(id=freight.id).one().del_flag == 0
  533. assert db.query(BizSampleFreightItem).filter_by(freight_id=freight.id, del_flag=0).count() == 2
  534. def test_web_admin_delete_freight_cascades_items_and_allows_relink():
  535. from app.crud import sample_freight as freight_crud
  536. db = _session()
  537. own, op = _sample(db, 'web-del')
  538. freight = _freight(db, 'web-del', [('cell_storage', own, op)])
  539. empty = _freight(db, 'web-empty', [])
  540. result = freight_crud.delete_freight(
  541. db, freight.id, tenant_no='tenant-a', user_id='u1'
  542. )
  543. assert result == {'id': freight.id, 'deleted': True, 'linkedSampleCount': 0}
  544. assert db.query(BizSampleFreight).filter_by(id=freight.id).one().del_flag == 1
  545. assert db.query(BizSampleFreightItem).filter_by(freight_id=freight.id, del_flag=0).count() == 0
  546. empty_result = freight_crud.delete_freight(
  547. db, empty.id, tenant_no='tenant-a', user_id='u1'
  548. )
  549. assert empty_result['deleted'] is True
  550. assert db.query(BizSampleFreight).filter_by(id=empty.id).one().del_flag == 1
  551. created = freight_crud.create_freight(
  552. db,
  553. tenant_no='tenant-a',
  554. user_id='u1',
  555. transport_mode_raw='sf',
  556. freight_amount='8.00',
  557. items=[{'sampleSource': 'cell_storage', 'sampleId': own.id, 'protocolId': op.id}],
  558. )
  559. assert created['id']
  560. assert any(
  561. item.get('sampleId') == own.id for item in (created.get('items') or [])
  562. )
  563. def test_header_update_rejects_assignment_changed_after_prior_visible_read():
  564. from app.services.market_freight import get_freight_detail, update_freight
  565. db = _session()
  566. sample, parent = _sample(db, 'scope-race')
  567. freight = _freight(db, 'scope-race', [('cell_storage', sample, parent)])
  568. assert get_freight_detail(db, freight.id, ctx=_ctx(), user_info=_user())['visibleItemCount'] == 1
  569. collection = db.query(BizProtocolCollectionInfo).filter_by(
  570. collection_protocol_id=parent.id
  571. ).one()
  572. db.query(BizProtocolCollectionInfo).filter_by(id=collection.id).update(
  573. {'sales_user_id': 'u2'}, synchronize_session=False
  574. )
  575. assert collection.sales_user_id == 'u1'
  576. with pytest.raises(HTTPException) as exc:
  577. update_freight(
  578. db, freight.id, ctx=_ctx(), user_info=_user(), freight_amount='55.00'
  579. )
  580. assert exc.value.status_code == 404
  581. assert db.query(BizSampleFreight).filter_by(id=freight.id).one().freight_amount == Decimal('12.30')
  582. def test_final_item_lock_rejects_participant_snapshot_change():
  583. from app.services.market_freight import _lock_active_items
  584. db = _session()
  585. first, fp = _sample(db, 'snapshot-first')
  586. second, sp = _sample(db, 'snapshot-second')
  587. freight = _freight(db, 'snapshot', [('cell_storage', first, fp)])
  588. expected = [('cell_storage', first.id)]
  589. db.add(BizSampleFreightItem(
  590. id='fi-snapshot-race', freight_id=freight.id,
  591. sample_source='cell_storage', sample_id=second.id,
  592. sample_code=second.sample_code, protocol_id=sp.id,
  593. tenant_no='tenant-a', create_dept_id='', del_flag=0,
  594. ))
  595. db.commit()
  596. with pytest.raises(PermissionError, match='发生变化'):
  597. _lock_active_items(
  598. db, _ctx(), freight_id=freight.id,
  599. expected_batch_keys=expected,
  600. )
  601. def test_lock_graph_does_not_rely_on_exists_scope_for_current_field_values():
  602. source = (Path(__file__).parents[1] / 'app/services/market_freight.py').read_text()
  603. block = source[source.index('def _lock_sample_graph'):source.index('def _lock_active_items')]
  604. assert 'apply_cell_protocol_scope' not in block
  605. assert 'apply_donation_scope' not in block
  606. assert '_current_field_visible_parent_ids' in block
  607. assert '_current_data_scope_parent_ids' in block
  608. def test_manager_header_update_rejects_current_leader_revocation():
  609. from app.services.market_freight import get_freight_detail, update_freight
  610. db = _session()
  611. leader = BizCollectionRegionStaff(
  612. id='leader-race', region_id='managed-race', user_id='m1', is_leader=1,
  613. tenant_no='tenant-a', create_dept_id='', del_flag=0,
  614. )
  615. db.add(leader)
  616. db.commit()
  617. sample, parent = _sample(
  618. db, 'leader-race', sales='u9', manager='other', region='managed-race'
  619. )
  620. freight = _freight(db, 'leader-race', [('cell_storage', sample, parent)])
  621. ctx = _ctx('manager', 'm1')
  622. assert get_freight_detail(db, freight.id, ctx=ctx, user_info=_user('m1'))['visibleItemCount'] == 1
  623. db.query(BizCollectionRegionStaff).filter_by(id=leader.id).update(
  624. {'is_leader': 0}, synchronize_session=False
  625. )
  626. assert leader.is_leader == 1
  627. with pytest.raises(HTTPException) as exc:
  628. update_freight(
  629. db, freight.id, ctx=ctx, user_info=_user('m1'), freight_amount='88.00'
  630. )
  631. assert exc.value.status_code == 404
  632. def test_header_update_uses_current_role_data_scope_not_prior_snapshot():
  633. from app.services.market_freight import get_freight_detail, update_freight
  634. db = _session()
  635. now = datetime(2026, 10, 11, 8, 0)
  636. db.add_all([
  637. SysUser(
  638. id='scope-user', dept_id='dept-current', user_no='scope-user',
  639. nick_name='范围用户', password='', tenant_no='tenant-a',
  640. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  641. ),
  642. SysRole(
  643. id='scope-role', role_name='范围角色', data_scope='1', status='1',
  644. tenant_no='tenant-a', create_dept_id='', create_time=now,
  645. update_time=now, del_flag=0,
  646. ),
  647. SysUserRole(
  648. id='scope-user-role', user_id='scope-user', role_id='scope-role',
  649. tenant_no='tenant-a', create_dept_id='', create_time=now,
  650. update_time=now, del_flag=0,
  651. ),
  652. ])
  653. db.commit()
  654. sample, parent = _sample(db, 'data-scope', sales='scope-user')
  655. parent.create_by = 'another-user'
  656. parent.create_dept_id = 'another-dept'
  657. db.commit()
  658. freight = _freight(db, 'data-scope', [('cell_storage', sample, parent)])
  659. ctx = _ctx('specialist', 'scope-user')
  660. user = {'user_id': 'scope-user', 'tenant_no': 'tenant-a', 'role': 'admin'}
  661. assert get_freight_detail(db, freight.id, ctx=ctx, user_info=user)['visibleItemCount'] == 1
  662. cached_role = db.query(SysRole).filter_by(id='scope-role').one()
  663. db.query(SysRole).filter_by(id='scope-role').update(
  664. {'data_scope': '4'}, synchronize_session=False
  665. )
  666. assert cached_role.data_scope == '1'
  667. with pytest.raises(HTTPException) as exc:
  668. update_freight(
  669. db, freight.id, ctx=ctx, user_info=user, freight_amount='77.00'
  670. )
  671. assert exc.value.status_code == 404
  672. def test_current_data_scope_preserves_post_roles_custom_scope_and_union():
  673. from app.services.market_freight import _current_data_scope_parent_ids
  674. db = _session()
  675. now = datetime(2026, 10, 11, 8, 0)
  676. db.add_all([
  677. SysUser(
  678. id='union-user', dept_id='union-home', user_no='union-user',
  679. nick_name='并集用户', password='', tenant_no='tenant-a',
  680. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  681. ),
  682. SysRole(
  683. id='custom-role', role_name='自定义范围', data_scope='5', status='1',
  684. tenant_no='tenant-a', create_dept_id='', create_time=now,
  685. update_time=now, del_flag=0,
  686. ),
  687. SysRole(
  688. id='self-role', role_name='本人范围', data_scope='4', status='1',
  689. tenant_no='tenant-a', create_dept_id='', create_time=now,
  690. update_time=now, del_flag=0,
  691. ),
  692. SysUserRole(
  693. id='union-direct', user_id='union-user', role_id='custom-role',
  694. tenant_no='tenant-a', create_dept_id='', create_time=now,
  695. update_time=now, del_flag=0,
  696. ),
  697. SysRoleDataScopeDetail(
  698. id='union-custom-detail', role_id='custom-role', scope_type='dept',
  699. scope_value='custom-dept', tenant_no='tenant-a', create_dept_id='',
  700. create_time=now, update_time=now, del_flag=0,
  701. ),
  702. SysPost(
  703. id='union-post', post_name='继承职位', post_code='union-post',
  704. status='1', tenant_no='tenant-a', create_dept_id='',
  705. create_time=now, update_time=now, del_flag=0,
  706. ),
  707. SysUserPost(
  708. id='union-user-post', user_id='union-user', post_id='union-post',
  709. tenant_no='tenant-a', create_dept_id='', create_time=now,
  710. update_time=now, del_flag=0,
  711. ),
  712. SysPostRole(
  713. id='union-post-role', post_id='union-post', role_id='self-role',
  714. tenant_no='tenant-a', create_dept_id='', create_time=now,
  715. update_time=now, del_flag=0,
  716. ),
  717. ])
  718. db.commit()
  719. _, custom_parent = _sample(db, 'union-custom')
  720. _, self_parent = _sample(db, 'union-self')
  721. _, denied_parent = _sample(db, 'union-denied')
  722. custom_parent.create_dept_id = 'custom-dept'
  723. self_parent.create_by = 'union-user'
  724. denied_parent.create_dept_id = 'other-dept'
  725. denied_parent.create_by = 'other-user'
  726. db.commit()
  727. visible = _current_data_scope_parent_ids(
  728. db,
  729. [custom_parent, self_parent, denied_parent],
  730. _ctx('specialist', 'union-user'),
  731. {'user_id': 'union-user', 'tenant_no': 'tenant-a', 'role': 'admin'},
  732. )
  733. assert visible == {custom_parent.id, self_parent.id}
  734. def test_current_data_scope_preserves_department_descendant_scope():
  735. from app.services.market_freight import _current_data_scope_parent_ids
  736. db = _session()
  737. now = datetime(2026, 10, 11, 8, 0)
  738. db.add_all([
  739. SysUser(
  740. id='dept-user', dept_id='dept-root', user_no='dept-user',
  741. nick_name='部门用户', password='', tenant_no='tenant-a',
  742. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  743. ),
  744. SysRole(
  745. id='dept-role', role_name='部门以下', data_scope='3', status='1',
  746. tenant_no='tenant-a', create_dept_id='', create_time=now,
  747. update_time=now, del_flag=0,
  748. ),
  749. SysUserRole(
  750. id='dept-user-role', user_id='dept-user', role_id='dept-role',
  751. tenant_no='tenant-a', create_dept_id='', create_time=now,
  752. update_time=now, del_flag=0,
  753. ),
  754. SysDept(
  755. id='dept-root', parent_id='0', dept_name='根部门', status='1',
  756. tenant_no='tenant-a', create_dept_id='', create_time=now,
  757. update_time=now, del_flag=0,
  758. ),
  759. SysDept(
  760. id='dept-child', parent_id='dept-root', dept_name='子部门', status='1',
  761. tenant_no='tenant-a', create_dept_id='', create_time=now,
  762. update_time=now, del_flag=0,
  763. ),
  764. ])
  765. db.commit()
  766. _, child_parent = _sample(db, 'dept-child')
  767. _, denied_parent = _sample(db, 'dept-denied')
  768. child_parent.create_dept_id = 'dept-child'
  769. denied_parent.create_dept_id = 'other-dept'
  770. db.commit()
  771. visible = _current_data_scope_parent_ids(
  772. db,
  773. [child_parent, denied_parent],
  774. _ctx('specialist', 'dept-user'),
  775. {'user_id': 'dept-user', 'tenant_no': 'tenant-a', 'role': 'admin'},
  776. )
  777. assert visible == {child_parent.id}
  778. def test_locked_data_scope_ignores_payload_superadmin_across_tenants():
  779. from app.services.market_freight import (
  780. _current_data_scope_parent_ids,
  781. get_freight_detail,
  782. )
  783. db = _session()
  784. now = datetime(2026, 10, 11, 8, 0)
  785. db.add_all([
  786. SysUser(
  787. id='cross-user', dept_id='cross-dept', user_no='cross-user',
  788. nick_name='跨租户用户', password='', tenant_no='tenant-a',
  789. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  790. ),
  791. SysRole(
  792. id='default-super-role', role_name='超级管理员', data_scope='1',
  793. status='1', tenant_no='zkxw', create_dept_id='', create_time=now,
  794. update_time=now, del_flag=0,
  795. ),
  796. SysUserRole(
  797. id='default-super-link', user_id='cross-user',
  798. role_id='default-super-role', tenant_no='zkxw', create_dept_id='',
  799. create_time=now, update_time=now, del_flag=0,
  800. ),
  801. SysRole(
  802. id='business-self-role', role_name='业务专员', data_scope='4',
  803. status='1', tenant_no='tenant-a', create_dept_id='', create_time=now,
  804. update_time=now, del_flag=0,
  805. ),
  806. SysUserRole(
  807. id='business-self-link', user_id='cross-user',
  808. role_id='business-self-role', tenant_no='tenant-a',
  809. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  810. ),
  811. ])
  812. db.commit()
  813. sample, parent = _sample(
  814. db, 'cross-tenant-scope', sales='cross-user'
  815. )
  816. parent.create_by = 'another-user'
  817. parent.create_dept_id = 'another-dept'
  818. db.commit()
  819. ctx = _ctx('specialist', 'cross-user')
  820. forged_default_tenant_payload = {
  821. 'user_id': 'cross-user', 'tenant_no': 'tenant-a', 'role': 'super_admin'
  822. }
  823. freight = _freight(
  824. db, 'cross-tenant-scope', [('cell_storage', sample, parent)]
  825. )
  826. assert _current_data_scope_parent_ids(
  827. db, [parent], ctx, forged_default_tenant_payload
  828. ) == set()
  829. with pytest.raises(HTTPException) as exc:
  830. get_freight_detail(
  831. db, freight.id, ctx=ctx, user_info=forged_default_tenant_payload
  832. )
  833. assert exc.value.status_code == 404
  834. db.add_all([
  835. SysRole(
  836. id='business-super-role', role_name='超级管理员', data_scope='4',
  837. status='1', tenant_no='tenant-a', create_dept_id='', create_time=now,
  838. update_time=now, del_flag=0,
  839. ),
  840. SysPost(
  841. id='business-super-post', post_name='业务租户超级管理职位',
  842. post_code='business-super-post', status='1', tenant_no='tenant-a',
  843. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  844. ),
  845. SysUserPost(
  846. id='business-super-user-post', user_id='cross-user',
  847. post_id='business-super-post', tenant_no='tenant-a',
  848. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  849. ),
  850. SysPostRole(
  851. id='business-super-post-role', post_id='business-super-post',
  852. role_id='business-super-role', tenant_no='tenant-a',
  853. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  854. ),
  855. ])
  856. db.commit()
  857. assert _current_data_scope_parent_ids(
  858. db, [parent], ctx, forged_default_tenant_payload
  859. ) == {parent.id}
  860. assert get_freight_detail(
  861. db, freight.id, ctx=ctx, user_info=forged_default_tenant_payload
  862. )['visibleItemCount'] == 1