test_market_freight_scope.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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):
  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_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 'linkedSampleCount' not in rows[0] and 'linkedSampleCount' not in detail
  92. assert 'hasHiddenItems' not in detail
  93. def test_batch_without_visible_item_is_not_listed_or_addressable():
  94. from app.services.market_freight import get_freight_detail, list_freights
  95. db = _session()
  96. other, parent = _sample(db, 'other', sales='u2')
  97. freight = _freight(db, 'hidden', [('cell_storage', other, parent)])
  98. assert list_freights(db, ctx=_ctx(), user_info=_user())[1] == 0
  99. with pytest.raises(HTTPException) as exc:
  100. get_freight_detail(db, freight.id, ctx=_ctx(), user_info=_user())
  101. assert exc.value.status_code == 404
  102. def test_keyword_and_source_filters_use_only_visible_items():
  103. from app.services.market_freight import list_freights
  104. db = _session()
  105. own, op = _sample(db, 'own')
  106. secret, sp = _sample(db, 'SECRET', source='research_donation', sales='u2')
  107. _freight(db, 'mixed', [('cell_storage', own, op), ('research_donation', secret, sp)])
  108. assert list_freights(db, ctx=_ctx(), user_info=_user(), keyword='SECRET')[1] == 0
  109. assert list_freights(db, ctx=_ctx(), user_info=_user(), sample_source='research_donation')[1] == 0
  110. assert list_freights(db, ctx=_ctx(), user_info=_user(), sample_source='cell_storage')[1] == 1
  111. def test_manager_scope_is_region_union_document_manager_for_both_sources():
  112. from app.services.market_freight import get_freight_detail
  113. db = _session()
  114. db.add(BizCollectionRegionStaff(id='staff', region_id='managed', user_id='m1', is_leader=1, tenant_no='tenant-a', create_dept_id='', del_flag=0))
  115. db.commit()
  116. region_sample, rp = _sample(db, 'region', sales='u9', manager='x', region='managed')
  117. assigned, ap = _sample(db, 'assigned', source='research_donation', sales='u9', manager='m1', region='other')
  118. hidden, hp = _sample(db, 'hidden', sales='m1', manager='x', region='other')
  119. freight = _freight(db, 'manager', [('cell_storage', region_sample, rp), ('research_donation', assigned, ap), ('cell_storage', hidden, hp)])
  120. detail = get_freight_detail(db, freight.id, ctx=_ctx('manager', 'm1'), user_info=_user('m1'))
  121. assert {item['sampleCode'] for item in detail['items']} == {'C-region', 'R-assigned'}
  122. assert detail['visibleItemCount'] == 2
  123. assert all('sampleTypeName' in item and 'motherName' in item and 'newbornName' in item for item in detail['items'])
  124. def test_dual_role_uses_fixed_route_context_not_union_between_pages():
  125. from app.services.market_freight import list_freights
  126. db = _session()
  127. specialist, sp = _sample(db, 'specialist', sales='m1', manager='x', region='other')
  128. manager, mp = _sample(db, 'manager', sales='u9', manager='m1', region='other')
  129. _freight(db, 'specialist', [('cell_storage', specialist, sp)])
  130. _freight(db, 'manager', [('cell_storage', manager, mp)])
  131. specialist_rows, _ = list_freights(db, ctx=_ctx('specialist', 'm1'), user_info=_user('m1'))
  132. manager_rows, _ = list_freights(db, ctx=_ctx('manager', 'm1'), user_info=_user('m1'))
  133. assert [row['freightNo'] for row in specialist_rows] == ['YF-specialist']
  134. assert [row['freightNo'] for row in manager_rows] == ['YF-manager']
  135. def test_cross_tenant_deleted_parent_and_deleted_sample_are_invisible():
  136. from app.services.market_freight import list_freights
  137. db = _session()
  138. cross, cp = _sample(db, 'cross', tenant='tenant-b')
  139. deleted, dp = _sample(db, 'deleted', deleted=1)
  140. _freight(db, 'cross', [('cell_storage', cross, cp)], tenant='tenant-b')
  141. _freight(db, 'deleted', [('cell_storage', deleted, dp)])
  142. assert list_freights(db, ctx=_ctx(), user_info=_user())[1] == 0
  143. def test_sample_options_are_scoped_sql_paginated_stable_and_derive_link_state():
  144. from app.services.market_freight import list_sample_options
  145. db = _session()
  146. base = datetime(2026, 10, 10, 8, 0)
  147. first, fp = _sample(db, 'first', created=base)
  148. _sample(db, 'second', source='research_donation', created=base + timedelta(hours=1))
  149. _sample(db, 'third', created=base + timedelta(hours=2))
  150. _sample(db, 'hidden', sales='u2', created=base + timedelta(hours=3))
  151. _freight(db, 'linked', [('cell_storage', first, fp)])
  152. page1, total = list_sample_options(db, ctx=_ctx(), user_info=_user(), page=1, page_size=2)
  153. page2, total2 = list_sample_options(db, ctx=_ctx(), user_info=_user(), page=2, page_size=2)
  154. assert total == total2 == 3
  155. assert [x['sampleCode'] for x in page1] == ['C-third', 'R-second']
  156. assert [x['sampleCode'] for x in page2] == ['C-first']
  157. assert page2[0]['freightId'] == 'f-linked'
  158. def test_create_derives_snapshots_and_decimal_string_and_requires_visible_item():
  159. from app.services.market_freight import create_freight
  160. db = _session()
  161. own, parent = _sample(db, 'own')
  162. result = create_freight(db, ctx=_ctx(), user_info=_user(), transport_mode='sf', freight_amount=Decimal('12.30'), items=_items(('cell_storage', own)))
  163. item = db.query(BizSampleFreightItem).filter_by(freight_id=result['id']).one()
  164. assert result['freightAmount'] == '12.30'
  165. assert item.sample_code == 'C-own' and item.protocol_id == parent.id
  166. with pytest.raises(ValueError, match='至少'):
  167. create_freight(db, ctx=_ctx(), user_info=_user(), transport_mode='sf', freight_amount='1.00', items=[])
  168. def test_create_prevalidates_every_item_and_rolls_back_without_partial_batch():
  169. from app.services.market_freight import create_freight
  170. db = _session()
  171. own, _ = _sample(db, 'own')
  172. other, _ = _sample(db, 'other', sales='u2')
  173. before = db.query(BizSampleFreight).count()
  174. with pytest.raises(HTTPException):
  175. create_freight(db, ctx=_ctx(), user_info=_user(), transport_mode='sf', freight_amount='1.00', items=_items(('cell_storage', own), ('cell_storage', other)))
  176. assert db.query(BizSampleFreight).count() == before
  177. def test_link_rejects_hidden_and_existing_other_batch_without_silent_move():
  178. from app.services.market_freight import link_samples
  179. db = _session()
  180. own, op = _sample(db, 'own')
  181. other, _ = _sample(db, 'other', sales='u2')
  182. linked, lp = _sample(db, 'linked')
  183. target = _freight(db, 'target', [('cell_storage', own, op)])
  184. source = _freight(db, 'source', [('cell_storage', linked, lp)])
  185. for sample in (other, linked):
  186. with pytest.raises((HTTPException, ValueError)):
  187. link_samples(db, target.id, ctx=_ctx(), user_info=_user(), items=_items(('cell_storage', sample)))
  188. assert db.query(BizSampleFreightItem).filter_by(sample_id=linked.id, del_flag=0).one().freight_id == source.id
  189. def test_unlink_prevalidates_all_items_and_rejects_hidden_or_nonexistent():
  190. from app.services.market_freight import unlink_samples
  191. db = _session()
  192. own, op = _sample(db, 'own')
  193. other, hp = _sample(db, 'hidden', sales='u2')
  194. freight = _freight(db, 'mixed', [('cell_storage', own, op), ('cell_storage', other, hp)])
  195. missing, _ = _sample(db, 'missing')
  196. for sample in (other, missing):
  197. with pytest.raises((HTTPException, ValueError)):
  198. unlink_samples(db, freight.id, ctx=_ctx(), user_info=_user(), items=_items(('cell_storage', sample)))
  199. assert db.query(BizSampleFreightItem).filter_by(freight_id=freight.id, del_flag=0).count() == 2
  200. def test_unlink_last_visible_item_disappears_without_revealing_hidden_remaining():
  201. from app.services.market_freight import list_freights, unlink_samples
  202. db = _session()
  203. own, op = _sample(db, 'own')
  204. other, hp = _sample(db, 'hidden', sales='u2')
  205. freight = _freight(db, 'mixed', [('cell_storage', own, op), ('cell_storage', other, hp)])
  206. result = unlink_samples(db, freight.id, ctx=_ctx(), user_info=_user(), items=_items(('cell_storage', own)))
  207. assert result == {'id': freight.id, 'visibleItemCount': 0, 'disappeared': True}
  208. assert list_freights(db, ctx=_ctx(), user_info=_user())[1] == 0
  209. assert db.query(BizSampleFreight).filter_by(id=freight.id).one().del_flag == 0
  210. @pytest.mark.parametrize('kind,user_id', [('specialist', 'u1'), ('manager', 'm1')])
  211. def test_shared_outside_scope_header_is_immutable_for_both_roles(kind, user_id):
  212. from app.services.market_freight import update_freight
  213. db = _session()
  214. visible, vp = _sample(db, 'visible', sales=user_id if kind == 'specialist' else 'u9', manager=user_id if kind == 'manager' else 'x')
  215. hidden, hp = _sample(db, 'hidden', sales='other', manager='other')
  216. freight = _freight(db, 'mixed', [('cell_storage', visible, vp), ('cell_storage', hidden, hp)])
  217. with pytest.raises(PermissionError, match='全部'):
  218. update_freight(db, freight.id, ctx=_ctx(kind, user_id), user_info=_user(user_id), freight_amount='99.00')
  219. assert db.query(BizSampleFreight).filter_by(id=freight.id).one().freight_amount == Decimal('12.30')
  220. def test_header_update_allowed_when_all_active_items_are_visible():
  221. from app.services.market_freight import update_freight
  222. db = _session()
  223. own, op = _sample(db, 'own')
  224. freight = _freight(db, 'own', [('cell_storage', own, op)])
  225. result = update_freight(db, freight.id, ctx=_ctx(), user_info=_user(), freight_amount='99.10')
  226. assert result['freightAmount'] == '99.10'
  227. @pytest.mark.parametrize('kind,user_id', [('specialist', 'u1'), ('manager', 'm1')])
  228. @pytest.mark.parametrize('mixed', [False, True])
  229. def test_detail_edit_action_requires_every_active_item_visible_without_leaking_totals(
  230. kind, user_id, mixed
  231. ):
  232. from app.services.market_freight import get_freight_detail
  233. from app.services.market_support import decorate_allowed_actions
  234. db = _session()
  235. visible, visible_parent = _sample(
  236. db,
  237. f'action-visible-{kind}-{mixed}',
  238. sales=user_id if kind == 'specialist' else 'other-sales',
  239. manager=user_id if kind == 'manager' else 'other-manager',
  240. )
  241. rows = [('cell_storage', visible, visible_parent)]
  242. if mixed:
  243. hidden, hidden_parent = _sample(
  244. db,
  245. f'action-hidden-{kind}',
  246. sales='hidden-sales',
  247. manager='hidden-manager',
  248. )
  249. rows.append(('cell_storage', hidden, hidden_parent))
  250. freight = _freight(db, f'action-{kind}-{mixed}', rows)
  251. detail = get_freight_detail(
  252. db,
  253. freight.id,
  254. ctx=_ctx(kind, user_id),
  255. user_info=_user(user_id),
  256. )
  257. rendered = decorate_allowed_actions(
  258. 'freight', detail, scope_kind=kind, detail=True
  259. )
  260. expected = ['link', 'unlink'] if mixed else ['edit', 'link', 'unlink']
  261. assert detail['allowedActions'] == expected
  262. assert rendered['allowedActions'] == expected
  263. for hidden_key in (
  264. 'allItemsVisible',
  265. 'hiddenItemCount',
  266. 'totalItemCount',
  267. 'activeItemCount',
  268. ):
  269. assert hidden_key not in detail
  270. def test_dto_forbids_scope_snapshots_status_and_non_decimal_amounts():
  271. from app.schemas.market_mobile import MarketFreightCreateBody, MarketFreightItemsBody
  272. with pytest.raises(ValidationError):
  273. MarketFreightItemsBody.model_validate({'items': [{'sampleSource': 'cell_storage', 'sampleId': 's1', 'sampleCode': 'forged'}]})
  274. for extra in ('tenantNo', 'scope', 'status'):
  275. with pytest.raises(ValidationError):
  276. MarketFreightCreateBody.model_validate({'transportMode': 'sf', 'freightAmount': '1.00', 'items': [{'sampleSource': 'cell_storage', 'sampleId': 's1'}], extra: 'x'})
  277. with pytest.raises(ValidationError):
  278. MarketFreightCreateBody.model_validate({'transportMode': 'sf', 'freightAmount': 'NaN', 'items': [{'sampleSource': 'cell_storage', 'sampleId': 's1'}]})
  279. def test_fixed_routes_and_precise_permissions_are_registered():
  280. from app.api.market_mobile import router
  281. paths = [(route.path, route.methods) for route in router.routes]
  282. for kind in ('specialist', 'manager'):
  283. prefix = f'/mini/market/{kind}/freights'
  284. assert any(path == prefix and 'GET' in methods for path, methods in paths)
  285. assert any(path == prefix and 'POST' in methods for path, methods in paths)
  286. assert any(path == f'{prefix}/sample-options' and 'GET' in methods for path, methods in paths)
  287. source = (Path(__file__).parents[1] / 'app/api/market_mobile.py').read_text()
  288. assert "f'mini:market:{scope_kind}:freight'" in source
  289. def test_migration_has_mysql57_indexes_unique_active_link_and_duplicate_preflight():
  290. sql = (Path(__file__).parents[2] / 'docs/sql/migrations/2026-10-11-market-freight-indexes.sql').read_text()
  291. lowered = sql.lower()
  292. assert 'information_schema.statistics' in lowered
  293. assert 'generated always as' in lowered
  294. assert 'unique' in lowered and 'active' in lowered
  295. assert 'group by tenant_no, sample_source, sample_id' in lowered
  296. assert 'having count(*) > 1' in lowered
  297. assert 'create procedure' in lowered and 'signal sqlstate' in lowered
  298. assert 'character_maximum_length' in lowered
  299. assert 'data_type' in lowered and 'is_nullable' in lowered
  300. assert 'normalized_generation_expression' in lowered
  301. assert "uk_sample_freight_tenant_no" in lowered
  302. assert 'exact_freight_unique_indexes' in lowered
  303. def test_write_service_contains_locking_postlock_validation_and_integrity_retry():
  304. source = (Path(__file__).parents[1] / 'app/services/market_freight.py').read_text()
  305. assert source.count('with_for_update') >= 3
  306. assert 'IntegrityError' in source
  307. assert '_lock_batch_header' in source
  308. assert '_lock_sample_graph' in source
  309. assert '_lock_active_items' in source
  310. def test_multiple_party_rows_do_not_duplicate_visible_item_or_count():
  311. from app.services.market_freight import get_freight_detail
  312. db = _session()
  313. sample, parent = _sample(db, 'one')
  314. db.add(BizProtocolPartyCustomer(id='pc-one-duplicate', collection_protocol_id=parent.id, mother_name='重复客户行', tenant_no='tenant-a', create_dept_id='', del_flag=0))
  315. db.commit()
  316. freight = _freight(db, 'one', [('cell_storage', sample, parent)])
  317. detail = get_freight_detail(db, freight.id, ctx=_ctx(), user_info=_user())
  318. assert detail['visibleItemCount'] == 1
  319. assert len(detail['items']) == 1
  320. def test_deleted_batch_is_invisible_even_with_visible_active_item():
  321. from app.services.market_freight import list_freights
  322. db = _session()
  323. sample, parent = _sample(db, 'one')
  324. _freight(db, 'deleted-batch', [('cell_storage', sample, parent)], deleted=1)
  325. assert list_freights(db, ctx=_ctx(), user_info=_user())[1] == 0
  326. def test_context_user_mismatch_fails_closed():
  327. from app.services.market_freight import list_sample_options
  328. db = _session()
  329. _sample(db, 'one')
  330. with pytest.raises(PermissionError):
  331. list_sample_options(db, ctx=_ctx(), user_info=_user('u2'))
  332. def test_manager_can_link_sample_in_managed_region():
  333. from app.services.market_freight import link_samples
  334. db = _session()
  335. 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))
  336. db.commit()
  337. existing, ep = _sample(db, 'existing', sales='u9', manager='m1')
  338. new_sample, _ = _sample(db, 'new', sales='u9', manager='x', region='managed')
  339. freight = _freight(db, 'manager-link', [('cell_storage', existing, ep)])
  340. detail = link_samples(db, freight.id, ctx=_ctx('manager', 'm1'), user_info=_user('m1'), items=_items(('cell_storage', new_sample)))
  341. assert {item['sampleCode'] for item in detail['items']} == {'C-existing', 'C-new'}
  342. def test_batch_paging_is_stable_and_total_counts_only_visible_batches():
  343. from app.services.market_freight import list_freights
  344. db = _session()
  345. first, fp = _sample(db, 'first')
  346. second, sp = _sample(db, 'second')
  347. hidden, hp = _sample(db, 'hidden-page', sales='u2')
  348. f1 = _freight(db, 'first', [('cell_storage', first, fp)])
  349. f2 = _freight(db, 'second', [('cell_storage', second, sp)])
  350. _freight(db, 'hidden-page', [('cell_storage', hidden, hp)])
  351. f1.create_time = f2.create_time
  352. db.commit()
  353. page1, total1 = list_freights(db, ctx=_ctx(), user_info=_user(), page=1, page_size=1)
  354. page2, total2 = list_freights(db, ctx=_ctx(), user_info=_user(), page=2, page_size=1)
  355. assert total1 == total2 == 2
  356. assert [page1[0]['id'], page2[0]['id']] == ['f-second', 'f-first']
  357. @pytest.mark.parametrize('source', ['cell_storage', 'research_donation'])
  358. def test_sample_options_choose_latest_party_once_before_count_and_paging(source):
  359. from app.services.market_freight import list_sample_options
  360. db = _session()
  361. base = datetime(2026, 10, 10, 8, 0)
  362. target, parent = _sample(db, f'duplicate-{source}', source=source, created=base)
  363. _sample(db, f'other-{source}', source=source, created=base + timedelta(hours=1))
  364. if source == 'cell_storage':
  365. db.add(BizProtocolPartyCustomer(
  366. id='zz-latest-cell-party', collection_protocol_id=parent.id,
  367. mother_name='最新细胞客户', tenant_no='tenant-a', create_dept_id='',
  368. create_time=base + timedelta(hours=2), del_flag=0,
  369. ))
  370. latest_name = '最新细胞客户'
  371. else:
  372. db.add(BizResearchDonationParty(
  373. id='zz-latest-donation-party', research_donation_id=parent.id,
  374. mother_name='最新科研客户', tenant_no='tenant-a', create_dept_id='',
  375. create_time=base + timedelta(hours=2), del_flag=0,
  376. ))
  377. latest_name = '最新科研客户'
  378. db.commit()
  379. page1, total1 = list_sample_options(
  380. db, ctx=_ctx(), user_info=_user(), page=1, page_size=1,
  381. sample_source=source,
  382. )
  383. page2, total2 = list_sample_options(
  384. db, ctx=_ctx(), user_info=_user(), page=2, page_size=1,
  385. sample_source=source,
  386. )
  387. rows = page1 + page2
  388. assert total1 == total2 == 2
  389. assert sum(row['sampleId'] == target.id for row in rows) == 1
  390. target_row = next(row for row in rows if row['sampleId'] == target.id)
  391. assert target_row['customerName'] == latest_name
  392. def test_mysql_lock_queries_are_current_reads_with_stable_global_order():
  393. from app.services.market_freight import (
  394. _active_item_lock_query,
  395. _collection_lock_query,
  396. _leader_lock_query,
  397. _sample_parent_lock_query,
  398. )
  399. db = _session()
  400. ctx = _ctx()
  401. sample_sql = str(
  402. _sample_parent_lock_query(
  403. db, 'cell_storage', ['z', 'a'], ctx
  404. ).statement.compile(dialect=mysql.dialect())
  405. ).lower()
  406. collection_sql = str(
  407. _collection_lock_query(
  408. db, 'cell_storage', ['p-z', 'p-a'], ctx
  409. ).statement.compile(dialect=mysql.dialect())
  410. ).lower()
  411. item_sql = str(
  412. _active_item_lock_query(
  413. db, ctx, freight_id='f1', keys=[('cell_storage', 'z')]
  414. ).statement.compile(dialect=mysql.dialect())
  415. ).lower()
  416. leader_sql = str(
  417. _leader_lock_query(db, _ctx('manager', 'm1')).statement.compile(
  418. dialect=mysql.dialect()
  419. )
  420. ).lower()
  421. for sql in (sample_sql, collection_sql, item_sql, leader_sql):
  422. assert ' for update' in sql
  423. assert ' order by ' in sql
  424. assert 'tenant_no' in sql and 'del_flag' in sql
  425. assert 'sales_user_id' in collection_sql
  426. assert 'biz_protocol_collection_info' in collection_sql
  427. assert 'biz_collection_region_staff' in leader_sql
  428. def test_all_write_paths_use_batch_graph_item_lock_order():
  429. source = (Path(__file__).parents[1] / 'app/services/market_freight.py').read_text()
  430. for start_name, end_name in (
  431. ('def update_freight', 'def link_samples'),
  432. ('def link_samples', 'def unlink_samples'),
  433. ('def unlink_samples', None),
  434. ):
  435. block = source[source.index(start_name):]
  436. if end_name:
  437. block = block[:block.index(end_name)]
  438. assert block.index('_lock_batch_header') < block.index('_lock_sample_graph')
  439. assert block.index('_lock_sample_graph') < block.index('_lock_active_items')
  440. create_block = source[source.index('def create_freight'):source.index('def update_freight')]
  441. assert create_block.index('_lock_sample_graph') < create_block.index('_lock_active_items')
  442. def test_header_update_rejects_assignment_changed_after_prior_visible_read():
  443. from app.services.market_freight import get_freight_detail, update_freight
  444. db = _session()
  445. sample, parent = _sample(db, 'scope-race')
  446. freight = _freight(db, 'scope-race', [('cell_storage', sample, parent)])
  447. assert get_freight_detail(db, freight.id, ctx=_ctx(), user_info=_user())['visibleItemCount'] == 1
  448. collection = db.query(BizProtocolCollectionInfo).filter_by(
  449. collection_protocol_id=parent.id
  450. ).one()
  451. db.query(BizProtocolCollectionInfo).filter_by(id=collection.id).update(
  452. {'sales_user_id': 'u2'}, synchronize_session=False
  453. )
  454. assert collection.sales_user_id == 'u1'
  455. with pytest.raises(HTTPException) as exc:
  456. update_freight(
  457. db, freight.id, ctx=_ctx(), user_info=_user(), freight_amount='55.00'
  458. )
  459. assert exc.value.status_code == 404
  460. assert db.query(BizSampleFreight).filter_by(id=freight.id).one().freight_amount == Decimal('12.30')
  461. def test_final_item_lock_rejects_participant_snapshot_change():
  462. from app.services.market_freight import _lock_active_items
  463. db = _session()
  464. first, fp = _sample(db, 'snapshot-first')
  465. second, sp = _sample(db, 'snapshot-second')
  466. freight = _freight(db, 'snapshot', [('cell_storage', first, fp)])
  467. expected = [('cell_storage', first.id)]
  468. db.add(BizSampleFreightItem(
  469. id='fi-snapshot-race', freight_id=freight.id,
  470. sample_source='cell_storage', sample_id=second.id,
  471. sample_code=second.sample_code, protocol_id=sp.id,
  472. tenant_no='tenant-a', create_dept_id='', del_flag=0,
  473. ))
  474. db.commit()
  475. with pytest.raises(PermissionError, match='发生变化'):
  476. _lock_active_items(
  477. db, _ctx(), freight_id=freight.id,
  478. expected_batch_keys=expected,
  479. )
  480. def test_lock_graph_does_not_rely_on_exists_scope_for_current_field_values():
  481. source = (Path(__file__).parents[1] / 'app/services/market_freight.py').read_text()
  482. block = source[source.index('def _lock_sample_graph'):source.index('def _lock_active_items')]
  483. assert 'apply_cell_protocol_scope' not in block
  484. assert 'apply_donation_scope' not in block
  485. assert '_current_field_visible_parent_ids' in block
  486. assert '_current_data_scope_parent_ids' in block
  487. def test_manager_header_update_rejects_current_leader_revocation():
  488. from app.services.market_freight import get_freight_detail, update_freight
  489. db = _session()
  490. leader = BizCollectionRegionStaff(
  491. id='leader-race', region_id='managed-race', user_id='m1', is_leader=1,
  492. tenant_no='tenant-a', create_dept_id='', del_flag=0,
  493. )
  494. db.add(leader)
  495. db.commit()
  496. sample, parent = _sample(
  497. db, 'leader-race', sales='u9', manager='other', region='managed-race'
  498. )
  499. freight = _freight(db, 'leader-race', [('cell_storage', sample, parent)])
  500. ctx = _ctx('manager', 'm1')
  501. assert get_freight_detail(db, freight.id, ctx=ctx, user_info=_user('m1'))['visibleItemCount'] == 1
  502. db.query(BizCollectionRegionStaff).filter_by(id=leader.id).update(
  503. {'is_leader': 0}, synchronize_session=False
  504. )
  505. assert leader.is_leader == 1
  506. with pytest.raises(HTTPException) as exc:
  507. update_freight(
  508. db, freight.id, ctx=ctx, user_info=_user('m1'), freight_amount='88.00'
  509. )
  510. assert exc.value.status_code == 404
  511. def test_header_update_uses_current_role_data_scope_not_prior_snapshot():
  512. from app.services.market_freight import get_freight_detail, update_freight
  513. db = _session()
  514. now = datetime(2026, 10, 11, 8, 0)
  515. db.add_all([
  516. SysUser(
  517. id='scope-user', dept_id='dept-current', user_no='scope-user',
  518. nick_name='范围用户', password='', tenant_no='tenant-a',
  519. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  520. ),
  521. SysRole(
  522. id='scope-role', role_name='范围角色', data_scope='1', status='1',
  523. tenant_no='tenant-a', create_dept_id='', create_time=now,
  524. update_time=now, del_flag=0,
  525. ),
  526. SysUserRole(
  527. id='scope-user-role', user_id='scope-user', role_id='scope-role',
  528. tenant_no='tenant-a', create_dept_id='', create_time=now,
  529. update_time=now, del_flag=0,
  530. ),
  531. ])
  532. db.commit()
  533. sample, parent = _sample(db, 'data-scope', sales='scope-user')
  534. parent.create_by = 'another-user'
  535. parent.create_dept_id = 'another-dept'
  536. db.commit()
  537. freight = _freight(db, 'data-scope', [('cell_storage', sample, parent)])
  538. ctx = _ctx('specialist', 'scope-user')
  539. user = {'user_id': 'scope-user', 'tenant_no': 'tenant-a', 'role': 'admin'}
  540. assert get_freight_detail(db, freight.id, ctx=ctx, user_info=user)['visibleItemCount'] == 1
  541. cached_role = db.query(SysRole).filter_by(id='scope-role').one()
  542. db.query(SysRole).filter_by(id='scope-role').update(
  543. {'data_scope': '4'}, synchronize_session=False
  544. )
  545. assert cached_role.data_scope == '1'
  546. with pytest.raises(HTTPException) as exc:
  547. update_freight(
  548. db, freight.id, ctx=ctx, user_info=user, freight_amount='77.00'
  549. )
  550. assert exc.value.status_code == 404
  551. def test_current_data_scope_preserves_post_roles_custom_scope_and_union():
  552. from app.services.market_freight import _current_data_scope_parent_ids
  553. db = _session()
  554. now = datetime(2026, 10, 11, 8, 0)
  555. db.add_all([
  556. SysUser(
  557. id='union-user', dept_id='union-home', user_no='union-user',
  558. nick_name='并集用户', password='', tenant_no='tenant-a',
  559. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  560. ),
  561. SysRole(
  562. id='custom-role', role_name='自定义范围', data_scope='5', status='1',
  563. tenant_no='tenant-a', create_dept_id='', create_time=now,
  564. update_time=now, del_flag=0,
  565. ),
  566. SysRole(
  567. id='self-role', role_name='本人范围', data_scope='4', status='1',
  568. tenant_no='tenant-a', create_dept_id='', create_time=now,
  569. update_time=now, del_flag=0,
  570. ),
  571. SysUserRole(
  572. id='union-direct', user_id='union-user', role_id='custom-role',
  573. tenant_no='tenant-a', create_dept_id='', create_time=now,
  574. update_time=now, del_flag=0,
  575. ),
  576. SysRoleDataScopeDetail(
  577. id='union-custom-detail', role_id='custom-role', scope_type='dept',
  578. scope_value='custom-dept', tenant_no='tenant-a', create_dept_id='',
  579. create_time=now, update_time=now, del_flag=0,
  580. ),
  581. SysPost(
  582. id='union-post', post_name='继承职位', post_code='union-post',
  583. status='1', tenant_no='tenant-a', create_dept_id='',
  584. create_time=now, update_time=now, del_flag=0,
  585. ),
  586. SysUserPost(
  587. id='union-user-post', user_id='union-user', post_id='union-post',
  588. tenant_no='tenant-a', create_dept_id='', create_time=now,
  589. update_time=now, del_flag=0,
  590. ),
  591. SysPostRole(
  592. id='union-post-role', post_id='union-post', role_id='self-role',
  593. tenant_no='tenant-a', create_dept_id='', create_time=now,
  594. update_time=now, del_flag=0,
  595. ),
  596. ])
  597. db.commit()
  598. _, custom_parent = _sample(db, 'union-custom')
  599. _, self_parent = _sample(db, 'union-self')
  600. _, denied_parent = _sample(db, 'union-denied')
  601. custom_parent.create_dept_id = 'custom-dept'
  602. self_parent.create_by = 'union-user'
  603. denied_parent.create_dept_id = 'other-dept'
  604. denied_parent.create_by = 'other-user'
  605. db.commit()
  606. visible = _current_data_scope_parent_ids(
  607. db,
  608. [custom_parent, self_parent, denied_parent],
  609. _ctx('specialist', 'union-user'),
  610. {'user_id': 'union-user', 'tenant_no': 'tenant-a', 'role': 'admin'},
  611. )
  612. assert visible == {custom_parent.id, self_parent.id}
  613. def test_current_data_scope_preserves_department_descendant_scope():
  614. from app.services.market_freight import _current_data_scope_parent_ids
  615. db = _session()
  616. now = datetime(2026, 10, 11, 8, 0)
  617. db.add_all([
  618. SysUser(
  619. id='dept-user', dept_id='dept-root', user_no='dept-user',
  620. nick_name='部门用户', password='', tenant_no='tenant-a',
  621. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  622. ),
  623. SysRole(
  624. id='dept-role', role_name='部门以下', data_scope='3', status='1',
  625. tenant_no='tenant-a', create_dept_id='', create_time=now,
  626. update_time=now, del_flag=0,
  627. ),
  628. SysUserRole(
  629. id='dept-user-role', user_id='dept-user', role_id='dept-role',
  630. tenant_no='tenant-a', create_dept_id='', create_time=now,
  631. update_time=now, del_flag=0,
  632. ),
  633. SysDept(
  634. id='dept-root', parent_id='0', dept_name='根部门', status='1',
  635. tenant_no='tenant-a', create_dept_id='', create_time=now,
  636. update_time=now, del_flag=0,
  637. ),
  638. SysDept(
  639. id='dept-child', parent_id='dept-root', dept_name='子部门', status='1',
  640. tenant_no='tenant-a', create_dept_id='', create_time=now,
  641. update_time=now, del_flag=0,
  642. ),
  643. ])
  644. db.commit()
  645. _, child_parent = _sample(db, 'dept-child')
  646. _, denied_parent = _sample(db, 'dept-denied')
  647. child_parent.create_dept_id = 'dept-child'
  648. denied_parent.create_dept_id = 'other-dept'
  649. db.commit()
  650. visible = _current_data_scope_parent_ids(
  651. db,
  652. [child_parent, denied_parent],
  653. _ctx('specialist', 'dept-user'),
  654. {'user_id': 'dept-user', 'tenant_no': 'tenant-a', 'role': 'admin'},
  655. )
  656. assert visible == {child_parent.id}
  657. def test_locked_data_scope_ignores_payload_superadmin_across_tenants():
  658. from app.services.market_freight import (
  659. _current_data_scope_parent_ids,
  660. get_freight_detail,
  661. )
  662. db = _session()
  663. now = datetime(2026, 10, 11, 8, 0)
  664. db.add_all([
  665. SysUser(
  666. id='cross-user', dept_id='cross-dept', user_no='cross-user',
  667. nick_name='跨租户用户', password='', tenant_no='tenant-a',
  668. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  669. ),
  670. SysRole(
  671. id='default-super-role', role_name='超级管理员', data_scope='1',
  672. status='1', tenant_no='zkxw', create_dept_id='', create_time=now,
  673. update_time=now, del_flag=0,
  674. ),
  675. SysUserRole(
  676. id='default-super-link', user_id='cross-user',
  677. role_id='default-super-role', tenant_no='zkxw', create_dept_id='',
  678. create_time=now, update_time=now, del_flag=0,
  679. ),
  680. SysRole(
  681. id='business-self-role', role_name='业务专员', data_scope='4',
  682. status='1', tenant_no='tenant-a', create_dept_id='', create_time=now,
  683. update_time=now, del_flag=0,
  684. ),
  685. SysUserRole(
  686. id='business-self-link', user_id='cross-user',
  687. role_id='business-self-role', tenant_no='tenant-a',
  688. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  689. ),
  690. ])
  691. db.commit()
  692. sample, parent = _sample(
  693. db, 'cross-tenant-scope', sales='cross-user'
  694. )
  695. parent.create_by = 'another-user'
  696. parent.create_dept_id = 'another-dept'
  697. db.commit()
  698. ctx = _ctx('specialist', 'cross-user')
  699. forged_default_tenant_payload = {
  700. 'user_id': 'cross-user', 'tenant_no': 'tenant-a', 'role': 'super_admin'
  701. }
  702. freight = _freight(
  703. db, 'cross-tenant-scope', [('cell_storage', sample, parent)]
  704. )
  705. assert _current_data_scope_parent_ids(
  706. db, [parent], ctx, forged_default_tenant_payload
  707. ) == set()
  708. with pytest.raises(HTTPException) as exc:
  709. get_freight_detail(
  710. db, freight.id, ctx=ctx, user_info=forged_default_tenant_payload
  711. )
  712. assert exc.value.status_code == 404
  713. db.add_all([
  714. SysRole(
  715. id='business-super-role', role_name='超级管理员', data_scope='4',
  716. status='1', tenant_no='tenant-a', create_dept_id='', create_time=now,
  717. update_time=now, del_flag=0,
  718. ),
  719. SysPost(
  720. id='business-super-post', post_name='业务租户超级管理职位',
  721. post_code='business-super-post', status='1', tenant_no='tenant-a',
  722. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  723. ),
  724. SysUserPost(
  725. id='business-super-user-post', user_id='cross-user',
  726. post_id='business-super-post', tenant_no='tenant-a',
  727. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  728. ),
  729. SysPostRole(
  730. id='business-super-post-role', post_id='business-super-post',
  731. role_id='business-super-role', tenant_no='tenant-a',
  732. create_dept_id='', create_time=now, update_time=now, del_flag=0,
  733. ),
  734. ])
  735. db.commit()
  736. assert _current_data_scope_parent_ids(
  737. db, [parent], ctx, forged_default_tenant_payload
  738. ) == {parent.id}
  739. assert get_freight_detail(
  740. db, freight.id, ctx=ctx, user_info=forged_default_tenant_payload
  741. )['visibleItemCount'] == 1