test_pl_dispatch_calendar.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. """手工派车日历:独立记录、隔离、选择项及 HTTP 权限回归。"""
  2. from datetime import date, datetime, timedelta
  3. from importlib.util import find_spec
  4. import pytest
  5. from fastapi import HTTPException
  6. from pydantic import ValidationError
  7. from sqlalchemy import create_engine
  8. from sqlalchemy.orm import sessionmaker
  9. from app.core.db_auth import DbUserContext
  10. from app.models.crm_models import CrmProduct
  11. from app.models.pl_models import PlVehicle
  12. def modules():
  13. assert find_spec('app.services.pl_dispatch_calendar_service') is not None, '手工派车日历服务尚未实现'
  14. from app.models.pl_dispatch_calendar import PlDispatchCalendar
  15. from app.schemas.pl.dispatch_calendar import CreateBody, UpdateBody
  16. from app.services import pl_dispatch_calendar_service as svc
  17. return PlDispatchCalendar, CreateBody, UpdateBody, svc
  18. def user(uid='u1', tenant='t1', role='super_admin'):
  19. return DbUserContext(uid, '测试用户', 'd1', role, tenant)
  20. def payload(**kwargs):
  21. return {'dispatchDate': '2026-10-26', 'vehicleId': 'v1', 'productId': 'p1',
  22. 'origin': '宜昌', 'destination': '重庆', 'remark': None, **kwargs}
  23. @pytest.fixture
  24. def db():
  25. model, _, _, _ = modules()
  26. engine = create_engine('sqlite://')
  27. for table in (model, PlVehicle, CrmProduct):
  28. table.__table__.create(engine)
  29. with sessionmaker(bind=engine)() as session:
  30. session.add_all([
  31. PlVehicle(id='v1', license_plate='鄂E12345', vehicle_type='self', tenant_no='t1', create_by='u1'),
  32. PlVehicle(id='v2', license_plate='鄂E67890', vehicle_type='carrier', tenant_no='t1', create_by='u2'),
  33. PlVehicle(id='v3', license_plate='渝A12345', vehicle_type='self', tenant_no='t2', create_by='u1'),
  34. PlVehicle(id='v4', license_plate='鄂E00000', vehicle_type='self', tenant_no='t1', create_by='u1', del_flag=1),
  35. CrmProduct(id='p1', product_no='P001', product_name='液碱', tenant_no='t1', create_by='u1'),
  36. CrmProduct(id='p2', product_no='P002', product_name='盐酸', tenant_no='t1', create_by='u2'),
  37. CrmProduct(id='p3', product_no='P003', product_name='硫酸', tenant_no='t2', create_by='u1'),
  38. CrmProduct(id='p4', product_no='P004', product_name='氯酸钠', tenant_no='t1', create_by='u1', del_flag=1),
  39. ])
  40. session.commit()
  41. yield session
  42. engine.dispose()
  43. def create(db, caller=None, **kwargs):
  44. _, schema, _, svc = modules()
  45. return svc.create_record(db, 't1', caller or user(), schema(**payload(**kwargs)))
  46. def test_crud_duplicate_trips_snapshots_and_soft_delete(db):
  47. model, _, update, svc = modules()
  48. first = create(db)
  49. second = create(db)
  50. assert first.id != second.id
  51. assert first.tenant_no == 't1' and first.create_by == 'u1' and first.create_dept_id == 'd1'
  52. assert first.dispatch_date == date(2026, 10, 26)
  53. db.get(PlVehicle, 'v1').license_plate = '鄂E99999'
  54. db.get(CrmProduct, 'p1').product_name = '烧碱'
  55. db.commit()
  56. assert svc.get_record(db, 't1', user(), first.id).license_plate == '鄂E12345'
  57. updated = svc.update_record(db, 't1', user(), first.id, update(**payload(vehicleId='v2', productId='p2', origin='武汉')))
  58. result = svc._row_to_dict(updated)
  59. assert result['licensePlate'] == '鄂E67890' and result['productName'] == '盐酸'
  60. assert result['origin'] == '武汉'
  61. assert set(result) == {'id', 'dispatchDate', 'vehicleId', 'licensePlate', 'productId', 'productName', 'origin', 'destination', 'remark', 'createTime', 'updateTime'}
  62. assert svc.delete_record(db, 't1', user(), first.id) == 1
  63. assert db.get(model, first.id).del_flag == 1
  64. assert svc.list_records(db, 't1', user(), month='2026-10')['total'] == 1
  65. with pytest.raises(HTTPException):
  66. svc.get_record(db, 't1', user(), first.id)
  67. def test_month_pagination_sort_and_vehicle_filter(db):
  68. _, _, _, svc = modules()
  69. first = create(db, dispatchDate='2026-10-01')
  70. first.create_time = datetime.now() - timedelta(days=2)
  71. second = create(db, dispatchDate='2026-10-31', vehicleId='v2')
  72. create(db, dispatchDate='2026-09-30')
  73. create(db, dispatchDate='2026-11-01')
  74. page1 = svc.list_records(db, 't1', user(), month='2026-10', page=1, page_size=1)
  75. page2 = svc.list_records(db, 't1', user(), month='2026-10', page=2, page_size=1)
  76. assert page1['total'] == 2 and page1['list'][0]['id'] == second.id
  77. assert page2['list'][0]['id'] == first.id
  78. assert svc.list_records(db, 't1', user(), month='2026-10', vehicle_id='v1')['total'] == 1
  79. @pytest.mark.parametrize('month', ['2026-13', '2026-1', 'abc', '1899-12', '2101-01'])
  80. def test_invalid_month_rejected(db, month):
  81. _, _, _, svc = modules()
  82. with pytest.raises(HTTPException) as exc:
  83. svc.list_records(db, 't1', user(), month=month)
  84. assert exc.value.status_code == 422
  85. def test_tenant_and_data_scope_cover_records_and_options(db, monkeypatch):
  86. _, _, update, svc = modules()
  87. first = create(db)
  88. other = create(db, caller=user('u2'))
  89. import app.core.data_scope as scope
  90. monkeypatch.setattr(scope, '_resolve_user_role_scopes', lambda *a: [{'data_scope': '4', 'details': []}])
  91. limited = user(role='admin')
  92. assert [r['id'] for r in svc.list_records(db, 't1', limited, month='2026-10')['list']] == [first.id]
  93. assert svc.list_records(db, 't2', user(tenant='t2'), month='2026-10')['total'] == 0
  94. for tenant, caller, record in [('t1', limited, other), ('t2', user(tenant='t2'), first)]:
  95. for action in [lambda: svc.get_record(db, tenant, caller, record.id),
  96. lambda: svc.update_record(db, tenant, caller, record.id, update(**payload())),
  97. lambda: svc.delete_record(db, tenant, caller, record.id)]:
  98. with pytest.raises(HTTPException) as exc:
  99. action()
  100. assert exc.value.status_code == 404
  101. assert svc.list_vehicles(db, 't1', limited)['list'] == [{'id': 'v1', 'licensePlate': '鄂E12345'}]
  102. assert svc.list_products(db, 't1', limited)['list'] == [{'id': 'p1', 'productName': '液碱'}]
  103. with pytest.raises(HTTPException):
  104. create(db, caller=limited, vehicleId='v2')
  105. with pytest.raises(HTTPException):
  106. create(db, caller=limited, productId='p2')
  107. monkeypatch.setattr(scope, '_resolve_user_role_scopes', lambda *a: [{'data_scope': '4', 'details': []}, {'data_scope': '1', 'details': []}])
  108. assert svc.list_records(db, 't1', limited, month='2026-10')['total'] == 2
  109. assert svc.list_vehicles(db, 't1', limited)['total'] == 2
  110. def test_options_full_library_types_search_pagination(db):
  111. _, _, _, svc = modules()
  112. assert svc.list_vehicles(db, 't1', user())['total'] == 2
  113. assert svc.list_vehicles(db, 't1', user(), q='67890')['list'] == [{'id': 'v2', 'licensePlate': '鄂E67890'}]
  114. assert len(svc.list_vehicles(db, 't1', user(), page_size=1)['list']) == 1
  115. assert svc.list_products(db, 't1', user(), q='盐酸')['list'] == [{'id': 'p2', 'productName': '盐酸'}]
  116. assert svc.list_products(db, 't1', user(), q='%')['total'] == 0
  117. @pytest.mark.parametrize('field,value', [('vehicleId', 'v3'), ('vehicleId', 'v4'), ('vehicleId', 'missing'), ('productId', 'p3'), ('productId', 'p4'), ('productId', 'missing')])
  118. def test_invalid_cross_tenant_and_deleted_relations_rejected(db, field, value):
  119. _, _, _, svc = modules()
  120. with pytest.raises(HTTPException) as exc:
  121. create(db, **{field: value})
  122. assert exc.value.status_code == 422
  123. assert svc.list_records(db, 't1', user(), month='2026-10')['total'] == 0
  124. @pytest.mark.parametrize('bad', [
  125. {'dispatchDate': '2026-02-30'}, {'dispatchDate': '1899-12-31'}, {'dispatchDate': '2101-01-01'},
  126. {'dispatchDate': 1792972800}, {'dispatchDate': '2026-10-26T00:00:00'}, {'origin': ' '}, {'destination': 'x' * 256},
  127. {'vehicleId': ''}, {'productId': ''}, {'remark': 'x' * 501}, {'tenantNo': 't2'},
  128. {'licensePlate': '伪造'}, {'productName': '伪造'}, {'createBy': 'other'},
  129. ])
  130. def test_schema_rejects_bad_fields_and_client_snapshots(bad):
  131. _, schema, _, _ = modules()
  132. with pytest.raises(ValidationError):
  133. schema(**payload(**bad))
  134. def test_http_read_only_manage_permissions_both_clients_and_routes(db, monkeypatch):
  135. from fastapi import FastAPI
  136. from fastapi.testclient import TestClient
  137. from app.core.auth import get_current_user
  138. from app.core.database import get_db
  139. from app.api.pl import dispatch_calendar as calendar_api
  140. from app.api.pl.dispatch_calendar import router
  141. from sqlalchemy.pool import StaticPool
  142. model, _, _, _ = modules()
  143. engine = create_engine('sqlite://', connect_args={'check_same_thread': False}, poolclass=StaticPool)
  144. for table in (model, PlVehicle, CrmProduct):
  145. table.__table__.create(engine)
  146. factory = sessionmaker(bind=engine)
  147. with factory() as session:
  148. session.add(PlVehicle(id='v1', license_plate='鄂E12345', vehicle_type='self', tenant_no='t1'))
  149. session.add(CrmProduct(id='p1', product_no='P1', product_name='液碱', tenant_no='t1'))
  150. session.commit()
  151. def database():
  152. with factory() as session:
  153. yield session
  154. import app.core.data_scope as scope
  155. monkeypatch.setattr(scope, '_resolve_user_role_scopes', lambda *a: [{'data_scope': '1', 'details': []}])
  156. app = FastAPI()
  157. app.include_router(router, prefix='/api')
  158. app.dependency_overrides[get_db] = database
  159. path = '/api/transport/dispatch-calendar'
  160. codes = set()
  161. monkeypatch.setattr(calendar_api, 'iter_user_menu_perm_codes', lambda *a: codes)
  162. with TestClient(app) as client:
  163. assert client.get(path, params={'month': '2026-10'}).status_code == 401
  164. app.dependency_overrides[get_current_user] = lambda: {'role': 'admin', 'user_id': 'u1', 'tenant_no': 't1'}
  165. assert client.get(path, params={'month': '2026-10'}).status_code == 403
  166. for prefix in ('pl', 'mini:pl'):
  167. codes.clear()
  168. codes.add(prefix + ':dispatch-calendar:list')
  169. assert client.get(path, params={'month': '2026-10'}).status_code == 200
  170. assert client.get(path + '/vehicles').json()['total'] == 1
  171. assert client.get(path + '/products').json()['total'] == 1
  172. assert client.post(path, json=payload()).status_code == 403
  173. codes.add(prefix + ':dispatch-calendar:manage')
  174. response = client.post(path, json=payload())
  175. assert response.status_code == 200, response.text
  176. record_id = response.json()['id']
  177. assert client.get(f'{path}/{record_id}').json()['dispatchDate'] == '2026-10-26'
  178. assert client.put(f'{path}/{record_id}', json=payload(origin='武汉')).json()['origin'] == '武汉'
  179. codes.remove(prefix + ':dispatch-calendar:manage')
  180. assert client.put(f'{path}/{record_id}', json=payload()).status_code == 403
  181. assert client.delete(f'{path}/{record_id}').status_code == 403
  182. codes.add(prefix + ':dispatch-calendar:manage')
  183. assert client.delete(f'{path}/{record_id}').json() == {'deleted': 1}
  184. assert client.get(f'{path}/{record_id}').status_code == 404
  185. assert client.post(path, json=payload(tenantNo='t2')).status_code == 422
  186. assert client.get(path, params={'month': '2026-13'}).status_code == 422
  187. engine.dispose()
  188. def test_permissions_use_current_tenant_and_button_grants(db):
  189. from app.api.pl.dispatch_calendar import require_manage
  190. from app.models.models import SysRole, SysUserRole, SysMenu, SysRoleMenu
  191. for model in (SysRole, SysUserRole, SysMenu, SysRoleMenu):
  192. model.__table__.create(db.get_bind())
  193. db.add_all([
  194. SysRole(id='role1', role_name='调度员', tenant_no='t1'),
  195. SysUserRole(id='ur1', user_id='u1', role_id='role1', tenant_no='t1'),
  196. SysMenu(id='calendar', menu_name='派车日历', menu_type='C', parent_id='0',
  197. perms='pl:dispatch-calendar:list', tenant_no='t1'),
  198. SysMenu(id='manage', menu_name='维护派车日历', menu_type='F', parent_id='calendar',
  199. perms='pl:dispatch-calendar:manage', visible='1', tenant_no='t1'),
  200. SysRoleMenu(id='rm1', role_id='role1', menu_id='manage', tenant_no='t1'),
  201. ])
  202. db.commit()
  203. caller = {'role': 'admin', 'user_id': 'u1', 'tenant_no': 't1'}
  204. assert require_manage(caller, db) == caller
  205. with pytest.raises(HTTPException) as exc:
  206. require_manage({**caller, 'tenant_no': 't2'}, db)
  207. assert exc.value.status_code == 403
  208. def test_month_pagination_can_fetch_more_than_500_trips(db):
  209. model, _, _, svc = modules()
  210. db.add_all([model(id=f'bulk-{number:04}', dispatch_date=date(2026, 10, 26),
  211. vehicle_id='v1', license_plate='鄂E12345', product_id='p1', product_name='液碱',
  212. origin='宜昌', destination='重庆', tenant_no='t1', create_by='u1')
  213. for number in range(503)])
  214. db.commit()
  215. first = svc.list_records(db, 't1', user(), month='2026-10', page=1, page_size=500)
  216. second = svc.list_records(db, 't1', user(), month='2026-10', page=2, page_size=500)
  217. assert first['total'] == second['total'] == 503
  218. assert len(first['list']) == 500 and len(second['list']) == 3
  219. assert len({row['id'] for row in first['list'] + second['list']}) == 503
  220. def test_calendar_openapi_schema_can_be_generated():
  221. from fastapi import FastAPI
  222. from app.api.pl.dispatch_calendar import router
  223. app = FastAPI()
  224. app.include_router(router, prefix='/api')
  225. document = app.openapi()
  226. for schema in ('CreateBody', 'UpdateBody'):
  227. field = document['components']['schemas'][schema]['properties']['dispatchDate']
  228. assert field['type'] == 'string' and field['format'] == 'date'