market_support.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  1. """移动市场表单选项、附件暂存与动作白名单。
  2. 该模块是移动市场写接口的安全边界:客户端不能选择任意字典、目录或附件 URL。
  3. """
  4. from __future__ import annotations
  5. import os
  6. import re
  7. import uuid
  8. import zipfile
  9. from decimal import Decimal
  10. from io import BytesIO
  11. from typing import Any, Dict, Iterable, List, Optional
  12. from fastapi import HTTPException
  13. from sqlalchemy import or_
  14. from sqlalchemy.orm import Session
  15. from app.core.config import settings
  16. from app.core.storage import storage
  17. from app.models.models import (
  18. BizAttachment,
  19. BizCellSampleType,
  20. BizCollectionProtocol,
  21. BizCollectionHospital,
  22. BizCustomer,
  23. BizProtocolCollectionInfo,
  24. BizCollectionRegion,
  25. BizCollectionRegionStaff,
  26. BizItemUnit,
  27. BizPresignOrder,
  28. BizPresignTransfer,
  29. BizProtocolFullmoonTodo,
  30. BizProtocolPayment,
  31. BizProtocolPaymentDetail,
  32. BizProtocolPaymentTransfer,
  33. BizProtocolStorageCert,
  34. BizSampleCode,
  35. SysDictData,
  36. SysEthnic,
  37. SysUser,
  38. )
  39. from app.crud import collection_region as collection_region_crud
  40. from app.crud import customer as customer_crud
  41. from app.core.data_scope import apply_data_scope
  42. from app.models.research_donation import (
  43. BizResearchDonation,
  44. BizResearchDonationCollection,
  45. )
  46. from app.services.market_field_scope import (
  47. MarketFieldContext,
  48. apply_cell_protocol_scope,
  49. apply_donation_scope,
  50. apply_presign_scope,
  51. assert_cell_protocol_access,
  52. assert_donation_access,
  53. assert_presign_access,
  54. )
  55. FORM_MODULES = frozenset({'presign', 'protocol', 'payment', 'freight'})
  56. UPLOAD_MODULES = frozenset({'presign', 'protocol', 'payment', 'sample'})
  57. DICT_BY_MODULE = {
  58. 'payment': ('zzfs', 'transferTypes'),
  59. 'freight': ('sample_transport_mode', 'transportModes'),
  60. }
  61. MAX_UPLOAD_BYTES = 10 * 1024 * 1024
  62. PRESIGN_MAX_UPLOAD_BYTES = 20 * 1024 * 1024
  63. PROTOCOL_MAX_UPLOAD_BYTES = 20 * 1024 * 1024
  64. MAX_ATTACHMENT_REFS = 20
  65. MAX_ATTACHMENT_REFS_LENGTH = 4000
  66. MAX_ATTACHMENT_REF_LENGTH = 1000
  67. PAYMENT_TERMINAL_PROTOCOL_STATUSES = frozenset({'yzf', 'sdfq', 'zky'})
  68. PAYMENT_WRITABLE_SCHEDULE_STATUS = 'open'
  69. HEIC_BRANDS = frozenset(
  70. {b'heic', b'heix', b'hevc', b'hevx', b'heim', b'heis'}
  71. )
  72. HEIF_BRANDS = HEIC_BRANDS | frozenset({b'mif1', b'msf1'})
  73. ALLOWED_MIME_BY_EXT = {
  74. 'jpg': {'image/jpeg'},
  75. 'jpeg': {'image/jpeg'},
  76. 'png': {'image/png'},
  77. 'webp': {'image/webp'},
  78. 'heic': {'image/heic', 'image/heif', 'application/octet-stream'},
  79. 'heif': {'image/heic', 'image/heif', 'application/octet-stream'},
  80. 'pdf': {'application/pdf'},
  81. 'doc': {'application/msword', 'application/octet-stream'},
  82. 'docx': {
  83. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  84. 'application/zip',
  85. 'application/octet-stream',
  86. },
  87. 'xls': {'application/vnd.ms-excel', 'application/octet-stream'},
  88. 'xlsx': {
  89. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  90. 'application/zip',
  91. 'application/octet-stream',
  92. },
  93. }
  94. PROTOCOL_ALLOWED_MIME_BY_EXT = {
  95. **ALLOWED_MIME_BY_EXT,
  96. 'gif': {'image/gif'},
  97. 'bmp': {'image/bmp', 'image/x-ms-bmp'},
  98. 'ppt': {'application/vnd.ms-powerpoint', 'application/octet-stream'},
  99. 'pptx': {
  100. 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  101. 'application/zip',
  102. 'application/octet-stream',
  103. },
  104. 'txt': {'text/plain', 'application/octet-stream'},
  105. 'mp4': {'video/mp4', 'application/octet-stream'},
  106. 'webm': {'video/webm', 'application/octet-stream'},
  107. 'ogg': {'video/ogg', 'application/ogg', 'application/octet-stream'},
  108. 'mov': {'video/quicktime', 'application/octet-stream'},
  109. 'avi': {'video/x-msvideo', 'application/octet-stream'},
  110. 'zip': {'application/zip', 'application/x-zip-compressed', 'application/octet-stream'},
  111. 'rar': {'application/vnd.rar', 'application/x-rar-compressed', 'application/octet-stream'},
  112. }
  113. def _option(value: Any, label: Any) -> Dict[str, str]:
  114. return {'value': str(value or ''), 'label': str(label or '')}
  115. def _protocol_sample_type_option(row: BizCellSampleType) -> Dict[str, Any]:
  116. storage_price = (
  117. format(Decimal(str(row.storage_price)).quantize(Decimal('0.01')), 'f')
  118. if row.storage_price is not None
  119. else None
  120. )
  121. return {
  122. **_option(row.id, row.type_name),
  123. 'storagePrice': storage_price,
  124. 'storageYears': (
  125. int(row.storage_years) if row.storage_years is not None else None
  126. ),
  127. 'sampleCodeFilter': (row.sample_code_filter or '').strip(),
  128. }
  129. def _verify_identity(ctx: MarketFieldContext, user_info: dict) -> None:
  130. if not isinstance(user_info, dict):
  131. raise PermissionError('用户身份与现场范围上下文不一致')
  132. if (
  133. str(user_info.get('user_id') or '').strip() != ctx.user_id
  134. or str(user_info.get('tenant_no') or '').strip() != ctx.tenant_no
  135. ):
  136. raise PermissionError('用户身份与现场范围上下文不一致')
  137. def authorized_region_ids(db: Session, ctx: MarketFieldContext) -> List[str]:
  138. query = db.query(BizCollectionRegionStaff.region_id).filter(
  139. BizCollectionRegionStaff.tenant_no == ctx.tenant_no,
  140. BizCollectionRegionStaff.del_flag == 0,
  141. BizCollectionRegionStaff.user_id == ctx.user_id,
  142. )
  143. if ctx.scope_kind == 'manager':
  144. query = query.filter(BizCollectionRegionStaff.is_leader == 1)
  145. return [str(row[0]) for row in query.distinct().all() if row and row[0]]
  146. def _tenant_region_ids(db: Session, tenant_no: str) -> List[str]:
  147. rows = (
  148. db.query(BizCollectionRegion.id)
  149. .filter(
  150. BizCollectionRegion.tenant_no == tenant_no,
  151. BizCollectionRegion.del_flag == 0,
  152. )
  153. .all()
  154. )
  155. return [str(row[0]) for row in rows if row and row[0]]
  156. def form_option_region_ids(
  157. db: Session,
  158. *,
  159. module: str,
  160. ctx: MarketFieldContext,
  161. user_info: dict,
  162. business_id: Optional[str] = None,
  163. ) -> List[str]:
  164. """表单采集地区候选:与 Web 一致,返回本租户全部采集地区。
  165. 不依赖 ``biz_collection_region_staff`` 绑定;现场写入范围仍由各模块
  166. create/update(如地区经理归属校验)与列表 scope 约束。
  167. """
  168. _ = (module, user_info, business_id)
  169. return _tenant_region_ids(db, ctx.tenant_no)
  170. def _dict_options(db: Session, tenant_no: str, dict_type: str) -> List[dict]:
  171. rows = (
  172. db.query(SysDictData)
  173. .filter(
  174. SysDictData.tenant_no == tenant_no,
  175. SysDictData.del_flag == 0,
  176. SysDictData.dict_type == dict_type,
  177. )
  178. .order_by(SysDictData.order_num.asc(), SysDictData.dict_label.asc())
  179. .all()
  180. )
  181. return [_option(row.dict_value, row.dict_label) for row in rows]
  182. def _business_region_id(
  183. db: Session,
  184. *,
  185. module: str,
  186. business_id: str,
  187. ctx: MarketFieldContext,
  188. user_info: dict,
  189. ) -> Optional[str]:
  190. """仅从当前已在 scope 内的单据补充地区,不把 businessId 当越权入口。"""
  191. record_id = str(business_id or '').strip()
  192. if not record_id:
  193. return None
  194. if module == 'presign':
  195. return str(
  196. assert_presign_access(
  197. db, record_id, ctx, user_info=user_info
  198. ).region_id
  199. or ''
  200. ).strip() or None
  201. if module != 'protocol':
  202. return None
  203. try:
  204. assert_cell_protocol_access(db, record_id, ctx, user_info=user_info)
  205. collection = (
  206. db.query(BizProtocolCollectionInfo)
  207. .filter(
  208. BizProtocolCollectionInfo.collection_protocol_id == record_id,
  209. BizProtocolCollectionInfo.tenant_no == ctx.tenant_no,
  210. BizProtocolCollectionInfo.del_flag == 0,
  211. )
  212. .order_by(
  213. BizProtocolCollectionInfo.create_time.desc(),
  214. BizProtocolCollectionInfo.id.desc(),
  215. )
  216. .first()
  217. )
  218. except HTTPException:
  219. assert_donation_access(db, record_id, ctx, user_info=user_info)
  220. collection = (
  221. db.query(BizResearchDonationCollection)
  222. .filter(
  223. BizResearchDonationCollection.research_donation_id == record_id,
  224. BizResearchDonationCollection.tenant_no == ctx.tenant_no,
  225. BizResearchDonationCollection.del_flag == 0,
  226. )
  227. .order_by(
  228. BizResearchDonationCollection.create_time.desc(),
  229. BizResearchDonationCollection.id.desc(),
  230. )
  231. .first()
  232. )
  233. return str(collection.region_id or '').strip() if collection else None
  234. def search_customers_for_protocol(
  235. db: Session,
  236. *,
  237. ctx: MarketFieldContext,
  238. user_info: dict,
  239. keyword: Optional[str] = None,
  240. page: int = 1,
  241. page_size: int = 20,
  242. ) -> Dict[str, Any]:
  243. """协议单姓名联想:只读检索客户档案(含回填所需联系方式/证件)。"""
  244. _verify_identity(ctx, user_info)
  245. kw = str(keyword or '').strip()
  246. page = max(1, int(page or 1))
  247. page_size = min(max(1, int(page_size or 20)), 100)
  248. query = db.query(BizCustomer).filter(
  249. BizCustomer.del_flag == 0,
  250. BizCustomer.tenant_no == ctx.tenant_no,
  251. )
  252. if kw:
  253. like = f'%{kw}%'
  254. query = query.filter(
  255. or_(
  256. BizCustomer.customer_name.like(like),
  257. BizCustomer.phone_no.like(like),
  258. BizCustomer.id_card_no.like(like),
  259. BizCustomer.customer_tags.like(like),
  260. ),
  261. )
  262. query = apply_data_scope(query, BizCustomer, user_info, db, ctx.tenant_no)
  263. total = query.count()
  264. rows = (
  265. query.order_by(BizCustomer.create_time.desc())
  266. .offset((page - 1) * page_size)
  267. .limit(page_size)
  268. .all()
  269. )
  270. return {
  271. 'list': [customer_crud._row_to_dict(row) for row in rows],
  272. 'total': int(total),
  273. 'page': page,
  274. 'pageSize': page_size,
  275. }
  276. def get_form_options(
  277. db: Session,
  278. *,
  279. module: str,
  280. ctx: MarketFieldContext,
  281. user_info: dict,
  282. region_id: Optional[str] = None,
  283. business_id: Optional[str] = None,
  284. user_keyword: Optional[str] = None,
  285. code_filter: Optional[str] = None,
  286. ) -> Dict[str, Any]:
  287. """返回移动表单最小选项集;不会返回联系方式或证件等 PII。"""
  288. _verify_identity(ctx, user_info)
  289. normalized_module = str(module or '').strip()
  290. if normalized_module not in FORM_MODULES:
  291. raise ValueError('不支持的表单选项模块')
  292. if normalized_module in DICT_BY_MODULE:
  293. dict_type, key = DICT_BY_MODULE[normalized_module]
  294. return {key: _dict_options(db, ctx.tenant_no, dict_type)}
  295. region_ids = form_option_region_ids(
  296. db,
  297. module=normalized_module,
  298. ctx=ctx,
  299. user_info=user_info,
  300. business_id=business_id,
  301. )
  302. selected_region = str(region_id or '').strip()
  303. if selected_region and selected_region not in region_ids:
  304. raise PermissionError('所选地区不在当前用户权限范围内')
  305. regions = []
  306. if region_ids:
  307. regions = (
  308. db.query(BizCollectionRegion)
  309. .filter(
  310. BizCollectionRegion.id.in_(region_ids),
  311. BizCollectionRegion.tenant_no == ctx.tenant_no,
  312. BizCollectionRegion.del_flag == 0,
  313. )
  314. .order_by(BizCollectionRegion.order_num.asc(), BizCollectionRegion.region_name.asc())
  315. .all()
  316. )
  317. active_region_ids = [str(row.id) for row in regions]
  318. if selected_region and selected_region not in active_region_ids:
  319. raise PermissionError('所选地区不存在或已停用')
  320. hospital_regions = (
  321. [selected_region] if selected_region else active_region_ids
  322. )
  323. hospitals = []
  324. staff_rows = []
  325. if hospital_regions:
  326. hospitals = (
  327. db.query(BizCollectionHospital)
  328. .filter(
  329. BizCollectionHospital.region_id.in_(hospital_regions),
  330. BizCollectionHospital.tenant_no == ctx.tenant_no,
  331. BizCollectionHospital.del_flag == 0,
  332. )
  333. .order_by(BizCollectionHospital.order_num.asc(), BizCollectionHospital.hospital_name.asc())
  334. .all()
  335. )
  336. staff_rows = (
  337. db.query(SysUser, BizCollectionRegionStaff)
  338. .join(
  339. BizCollectionRegionStaff,
  340. BizCollectionRegionStaff.user_id == SysUser.id,
  341. )
  342. .filter(
  343. BizCollectionRegionStaff.region_id.in_(hospital_regions),
  344. BizCollectionRegionStaff.tenant_no == ctx.tenant_no,
  345. BizCollectionRegionStaff.del_flag == 0,
  346. SysUser.tenant_no == ctx.tenant_no,
  347. SysUser.del_flag == 0,
  348. SysUser.status == '1',
  349. )
  350. .order_by(
  351. BizCollectionRegionStaff.is_leader.desc(),
  352. SysUser.nick_name.asc(),
  353. SysUser.id.asc(),
  354. )
  355. .all()
  356. )
  357. sample_types = (
  358. db.query(BizCellSampleType)
  359. .filter(
  360. BizCellSampleType.tenant_no == ctx.tenant_no,
  361. BizCellSampleType.del_flag == 0,
  362. )
  363. .order_by(BizCellSampleType.order_num.asc(), BizCellSampleType.type_name.asc())
  364. .all()
  365. )
  366. units = (
  367. db.query(BizItemUnit)
  368. .filter(BizItemUnit.tenant_no == ctx.tenant_no, BizItemUnit.del_flag == 0)
  369. .order_by(BizItemUnit.order_num.asc(), BizItemUnit.unit_name.asc())
  370. .all()
  371. )
  372. staff = []
  373. seen_staff_ids = set()
  374. for user, binding in staff_rows:
  375. if user.id in seen_staff_ids:
  376. continue
  377. seen_staff_ids.add(user.id)
  378. staff.append(
  379. {
  380. **_option(user.id, user.nick_name),
  381. 'isLeader': bool(binding.is_leader),
  382. }
  383. )
  384. current_user = (
  385. db.query(SysUser)
  386. .filter(
  387. SysUser.id == ctx.user_id,
  388. SysUser.tenant_no == ctx.tenant_no,
  389. SysUser.del_flag == 0,
  390. SysUser.status == '1',
  391. )
  392. .first()
  393. )
  394. searched_users = []
  395. if normalized_module == 'presign' and user_keyword is not None:
  396. keyword = str(user_keyword or '').strip()
  397. user_query = db.query(SysUser).filter(
  398. SysUser.tenant_no == ctx.tenant_no,
  399. SysUser.del_flag == 0,
  400. SysUser.status == '1',
  401. )
  402. if keyword:
  403. like = f'%{keyword}%'
  404. user_query = user_query.filter(
  405. or_(SysUser.nick_name.like(like), SysUser.user_no.like(like))
  406. )
  407. searched_users = (
  408. user_query.order_by(SysUser.nick_name.asc(), SysUser.id.asc())
  409. .limit(50)
  410. .all()
  411. )
  412. current_user_regions = []
  413. if current_user:
  414. current_user_regions = [
  415. _option(item.get('id'), item.get('regionName'))
  416. for item in collection_region_crud.list_regions_by_staff_user(
  417. db,
  418. user_id=str(current_user.id),
  419. tenant_no=ctx.tenant_no,
  420. )
  421. if item.get('id')
  422. ]
  423. result = {
  424. 'regions': [_option(row.id, row.region_name) for row in regions],
  425. 'hospitals': [_option(row.id, row.hospital_name) for row in hospitals],
  426. 'staff': staff,
  427. 'sampleTypes': [
  428. (
  429. _protocol_sample_type_option(row)
  430. if normalized_module == 'protocol'
  431. else _option(row.id, row.type_name)
  432. )
  433. for row in sample_types
  434. ],
  435. 'units': [_option(row.id, row.unit_name) for row in units],
  436. 'currentUser': (
  437. _option(current_user.id, current_user.nick_name)
  438. if current_user
  439. else None
  440. ),
  441. # 当前登录人在 biz_collection_region_staff 的关联地区(顺序即默认取第一个)
  442. 'currentUserRegions': current_user_regions,
  443. }
  444. if normalized_module == 'protocol':
  445. ethnicities = (
  446. db.query(SysEthnic)
  447. .filter(
  448. SysEthnic.del_flag == 0,
  449. or_(SysEthnic.tenant_no == '', SysEthnic.tenant_no == ctx.tenant_no),
  450. )
  451. .order_by(SysEthnic.order_num.asc(), SysEthnic.ethnic_code.asc())
  452. .all()
  453. )
  454. # 多取候选再过滤已占用,尽量凑满可选列表
  455. sample_code_query = db.query(BizSampleCode).filter(
  456. BizSampleCode.tenant_no == ctx.tenant_no,
  457. BizSampleCode.del_flag == 0,
  458. )
  459. cf = (code_filter or '').strip()
  460. if cf:
  461. sample_code_query = sample_code_query.filter(
  462. BizSampleCode.sample_code.like(f'%{cf}%')
  463. )
  464. sample_codes = (
  465. sample_code_query.order_by(
  466. BizSampleCode.create_time.desc(), BizSampleCode.sample_code.desc()
  467. )
  468. .limit(200)
  469. .all()
  470. )
  471. from app.crud import collection_protocol as cell_crud
  472. used_codes = cell_crud.get_sample_codes_used_in_protocol_samples(
  473. db,
  474. tenant_no=ctx.tenant_no,
  475. sample_codes=[(row.sample_code or '').strip() for row in sample_codes],
  476. )
  477. available_codes = [
  478. row
  479. for row in sample_codes
  480. if (row.sample_code or '').strip()
  481. and (row.sample_code or '').strip() not in used_codes
  482. ][:100]
  483. result.update(
  484. {
  485. 'ethnicities': [
  486. _option(row.ethnic_name, row.ethnic_name)
  487. for row in ethnicities
  488. ],
  489. 'sampleCodes': [
  490. {
  491. **_option(row.id, row.sample_code),
  492. 'sampleCode': row.sample_code or '',
  493. }
  494. for row in available_codes
  495. ],
  496. # 协议单内嵌转账与缴费模块共用转账方式字典
  497. 'transferTypes': _dict_options(db, ctx.tenant_no, 'zzfs'),
  498. # 协议单内嵌运费与运费模块共用运输方式字典
  499. 'transportModes': _dict_options(
  500. db, ctx.tenant_no, 'sample_transport_mode'
  501. ),
  502. }
  503. )
  504. if normalized_module == 'presign':
  505. result.update(
  506. {
  507. 'payModes': [
  508. {'label': '趸交', 'value': 'dj'},
  509. {'label': '分期', 'value': 'fq'},
  510. ],
  511. 'orderStatuses': [
  512. {'label': '草稿', 'value': 'draft'},
  513. {'label': '进行中', 'value': 'active'},
  514. {'label': '已转正式', 'value': 'converted'},
  515. {'label': '已作废', 'value': 'void'},
  516. ],
  517. 'transferTypes': _dict_options(db, ctx.tenant_no, 'zzfs'),
  518. 'users': [_option(row.id, row.nick_name) for row in searched_users],
  519. }
  520. )
  521. return result
  522. def _validate_upload(
  523. content: bytes,
  524. filename: str,
  525. content_type: str,
  526. *,
  527. max_bytes: int = MAX_UPLOAD_BYTES,
  528. allowed_mime_by_ext: Optional[Dict[str, set]] = None,
  529. ) -> tuple[str, str]:
  530. name = str(filename or '').strip()
  531. if not name or len(name) > 200 or re.search(r'[\x00-\x1f\x7f]', name):
  532. raise ValueError('文件名无效')
  533. if '/' in name or '\\' in name:
  534. raise ValueError('文件名无效')
  535. if not content:
  536. raise ValueError('上传文件不能为空')
  537. if len(content) > max_bytes:
  538. raise ValueError(f'上传文件不能超过 {max_bytes // (1024 * 1024)}MiB')
  539. ext = os.path.splitext(name)[1].lower().lstrip('.')
  540. mime = str(content_type or '').lower().split(';', 1)[0].strip()
  541. allowed_types = allowed_mime_by_ext or ALLOWED_MIME_BY_EXT
  542. if ext not in allowed_types or mime not in allowed_types[ext]:
  543. raise ValueError('不支持的文件类型')
  544. signatures = {
  545. 'jpg': (b'\xff\xd8\xff',),
  546. 'jpeg': (b'\xff\xd8\xff',),
  547. 'png': (b'\x89PNG\r\n\x1a\n',),
  548. 'webp': (b'RIFF',),
  549. 'pdf': (b'%PDF-',),
  550. 'doc': (b'\xd0\xcf\x11\xe0',),
  551. 'xls': (b'\xd0\xcf\x11\xe0',),
  552. 'docx': (b'PK\x03\x04',),
  553. 'xlsx': (b'PK\x03\x04',),
  554. 'gif': (b'GIF87a', b'GIF89a'),
  555. 'bmp': (b'BM',),
  556. 'ppt': (b'\xd0\xcf\x11\xe0',),
  557. 'pptx': (b'PK\x03\x04',),
  558. 'mp4': (b'\x00\x00\x00',),
  559. 'webm': (b'\x1a\x45\xdf\xa3',),
  560. 'ogg': (b'OggS',),
  561. 'mov': (b'\x00\x00\x00',),
  562. 'avi': (b'RIFF',),
  563. 'zip': (b'PK\x03\x04',),
  564. 'rar': (b'Rar!\x1a\x07',),
  565. }
  566. if ext not in {'heic', 'heif', 'txt'} and not any(
  567. content.startswith(prefix) for prefix in signatures.get(ext, ())
  568. ):
  569. raise ValueError('文件内容与扩展名不匹配')
  570. if ext == 'webp' and (len(content) < 12 or content[8:12] != b'WEBP'):
  571. raise ValueError('文件内容与扩展名不匹配')
  572. if ext in {'heic', 'heif'}:
  573. if len(content) < 16 or content[4:8] != b'ftyp':
  574. raise ValueError('文件内容与扩展名不匹配')
  575. box_size = int.from_bytes(content[:4], byteorder='big', signed=False)
  576. if (
  577. box_size < 16
  578. or box_size > len(content)
  579. or (box_size - 16) % 4 != 0
  580. ):
  581. raise ValueError('文件内容与扩展名不匹配')
  582. brands = {content[8:12]}
  583. brands.update(
  584. content[offset : offset + 4]
  585. for offset in range(16, box_size, 4)
  586. )
  587. allowed_brands = HEIC_BRANDS if ext == 'heic' else HEIF_BRANDS
  588. if not brands.intersection(allowed_brands):
  589. raise ValueError('文件内容与扩展名不匹配')
  590. if ext in {'docx', 'xlsx', 'pptx', 'zip'}:
  591. try:
  592. with zipfile.ZipFile(BytesIO(content)) as archive:
  593. names = set(archive.namelist())
  594. except (OSError, zipfile.BadZipFile):
  595. raise ValueError('文件内容与扩展名不匹配')
  596. if ext != 'zip':
  597. required_prefix = {
  598. 'docx': 'word/',
  599. 'xlsx': 'xl/',
  600. 'pptx': 'ppt/',
  601. }[ext]
  602. if '[Content_Types].xml' not in names or not any(
  603. name.startswith(required_prefix) for name in names
  604. ):
  605. raise ValueError('文件内容与扩展名不匹配')
  606. if ext in {'mp4', 'mov'} and (len(content) < 12 or content[4:8] != b'ftyp'):
  607. raise ValueError('文件内容与扩展名不匹配')
  608. if ext == 'avi' and (len(content) < 12 or content[8:12] != b'AVI '):
  609. raise ValueError('文件内容与扩展名不匹配')
  610. if ext == 'txt':
  611. try:
  612. content.decode('utf-8-sig')
  613. except UnicodeDecodeError:
  614. raise ValueError('文件内容与扩展名不匹配')
  615. return ext, mime
  616. def _relative_file_url(full_url: str) -> str:
  617. base_url = (settings.MINIO_BASE_URL or '').rstrip('/')
  618. if base_url and full_url.startswith(base_url + '/'):
  619. return full_url[len(base_url) + 1 :]
  620. return full_url
  621. def _file_size_display(size: int) -> str:
  622. if size < 1024:
  623. return f'{size} B'
  624. if size < 1024 * 1024:
  625. return f'{size / 1024:.1f} KB'
  626. return f'{size / (1024 * 1024):.1f} MB'
  627. def save_market_attachment(
  628. db: Session,
  629. *,
  630. content: bytes,
  631. filename: str,
  632. content_type: str,
  633. module: str,
  634. ctx: MarketFieldContext,
  635. user_info: dict,
  636. storage_backend=storage,
  637. ) -> Dict[str, Any]:
  638. _verify_identity(ctx, user_info)
  639. normalized_module = str(module or '').strip()
  640. if normalized_module not in UPLOAD_MODULES:
  641. raise ValueError('不支持的附件模块')
  642. ext, mime = _validate_upload(
  643. content,
  644. filename,
  645. content_type,
  646. max_bytes=(
  647. PRESIGN_MAX_UPLOAD_BYTES
  648. if normalized_module == 'presign'
  649. else PROTOCOL_MAX_UPLOAD_BYTES
  650. if normalized_module == 'protocol'
  651. else MAX_UPLOAD_BYTES
  652. ),
  653. allowed_mime_by_ext=(
  654. PROTOCOL_ALLOWED_MIME_BY_EXT
  655. if normalized_module == 'protocol'
  656. else ALLOWED_MIME_BY_EXT
  657. ),
  658. )
  659. folder = f'market/{ctx.scope_kind}/{normalized_module}'
  660. full_url = storage_backend.upload_file(content, filename, folder)
  661. file_url = _relative_file_url(full_url)
  662. row = BizAttachment(
  663. id=uuid.uuid4().hex,
  664. business_type=f'market:{ctx.scope_kind}:{normalized_module}:staging',
  665. business_id=None,
  666. original_name=filename,
  667. file_ext=ext,
  668. file_url=file_url,
  669. file_size=len(content),
  670. file_type=mime,
  671. tenant_no=ctx.tenant_no,
  672. create_by=ctx.user_id,
  673. create_dept_id=str(
  674. user_info.get('dept_id')
  675. or user_info.get('deptId')
  676. or user_info.get('region_id')
  677. or ''
  678. ).strip(),
  679. del_flag=0,
  680. )
  681. committed = False
  682. try:
  683. db.add(row)
  684. db.flush()
  685. db.refresh(row)
  686. result = {
  687. 'id': row.id,
  688. 'fileName': row.original_name,
  689. 'fileUrl': row.file_url,
  690. 'fileSize': row.file_size,
  691. 'fileSizeDisplay': _file_size_display(row.file_size or 0),
  692. 'fileType': row.file_type,
  693. }
  694. db.commit()
  695. committed = True
  696. except Exception:
  697. if not committed:
  698. db.rollback()
  699. try:
  700. storage_backend.delete_file(full_url)
  701. except Exception:
  702. pass
  703. raise
  704. return result
  705. def _split_refs(refs: Any) -> List[str]:
  706. if refs is None:
  707. return []
  708. if isinstance(refs, str):
  709. if len(refs) > MAX_ATTACHMENT_REFS_LENGTH:
  710. raise ValueError('附件引用总长度超出限制')
  711. raw: Iterable[Any] = refs.split(',')
  712. elif isinstance(refs, (list, tuple, set)):
  713. raw = refs
  714. else:
  715. raise ValueError('附件引用格式无效')
  716. raw = list(raw)
  717. if len(raw) > MAX_ATTACHMENT_REFS:
  718. raise ValueError('附件数量不能超过 20 个')
  719. values = []
  720. total_length = 0
  721. for item in raw:
  722. if isinstance(item, dict):
  723. item = item.get('id') or item.get('fileUrl') or item.get('url')
  724. value = str(item or '').strip()
  725. if len(value) > MAX_ATTACHMENT_REF_LENGTH:
  726. raise ValueError('附件引用长度无效')
  727. total_length += len(value)
  728. if total_length + max(0, len(raw) - 1) > MAX_ATTACHMENT_REFS_LENGTH:
  729. raise ValueError('附件引用总长度超出限制')
  730. if value and value not in values:
  731. values.append(value)
  732. return values
  733. def _attachment_candidates(value: str) -> List[str]:
  734. candidates = [value]
  735. base = (settings.MINIO_BASE_URL or '').rstrip('/')
  736. if base and value.startswith(base + '/'):
  737. candidates.append(value[len(base) + 1 :])
  738. return list(dict.fromkeys(candidates))
  739. def _attachment_value_matches(value: Any, candidates: Iterable[str]) -> bool:
  740. expected = set(candidates)
  741. for item in str(value or '').split(','):
  742. normalized = str(item or '').strip()
  743. if normalized and expected.intersection(_attachment_candidates(normalized)):
  744. return True
  745. return False
  746. def _attachment_columns_filter(columns, candidates: Iterable[str]):
  747. return or_(
  748. *(
  749. column.contains(candidate)
  750. for column in columns
  751. for candidate in candidates
  752. )
  753. )
  754. def _rows_reference_attachment(rows, field_names, candidates) -> bool:
  755. return any(
  756. _attachment_value_matches(getattr(row, field_name, None), candidates)
  757. for row in rows
  758. for field_name in field_names
  759. )
  760. def _has_accessible_protocol_cert_or_insurance_reference(
  761. db: Session,
  762. *,
  763. candidates: List[str],
  764. ctx: MarketFieldContext,
  765. user_info: dict,
  766. ) -> bool:
  767. reference_models = (
  768. (BizProtocolStorageCert, 'cert_image_urls'),
  769. (BizProtocolFullmoonTodo, 'insurance_attachments'),
  770. )
  771. for model, field_name in reference_models:
  772. rows = (
  773. apply_cell_protocol_scope(
  774. db.query(model).join(
  775. BizCollectionProtocol,
  776. BizCollectionProtocol.id == model.collection_protocol_id,
  777. ),
  778. db,
  779. ctx,
  780. user_info=user_info,
  781. )
  782. .filter(
  783. model.tenant_no == ctx.tenant_no,
  784. model.del_flag == 0,
  785. _attachment_columns_filter(
  786. (getattr(model, field_name),), candidates
  787. ),
  788. )
  789. .all()
  790. )
  791. if _rows_reference_attachment(rows, (field_name,), candidates):
  792. return True
  793. return False
  794. def _has_accessible_protocol_deposit_attachment_reference(
  795. db: Session,
  796. *,
  797. candidates: List[str],
  798. ctx: MarketFieldContext,
  799. user_info: dict,
  800. ) -> bool:
  801. """正式协议意向金凭证挂在预签转账上,经 source_presign_order_id 关联授权。"""
  802. transfer_rows = (
  803. db.query(BizPresignTransfer)
  804. .filter(
  805. BizPresignTransfer.tenant_no == ctx.tenant_no,
  806. BizPresignTransfer.del_flag == 0,
  807. _attachment_columns_filter(
  808. (BizPresignTransfer.transfer_attachments,), candidates
  809. ),
  810. )
  811. .all()
  812. )
  813. if not _rows_reference_attachment(
  814. transfer_rows, ('transfer_attachments',), candidates
  815. ):
  816. return False
  817. presign_ids = {
  818. str(row.presign_order_id or '').strip()
  819. for row in transfer_rows
  820. if str(row.presign_order_id or '').strip()
  821. }
  822. if not presign_ids:
  823. return False
  824. protocol_rows = (
  825. apply_cell_protocol_scope(
  826. db.query(BizCollectionProtocol),
  827. db,
  828. ctx,
  829. user_info=user_info,
  830. )
  831. .filter(
  832. BizCollectionProtocol.tenant_no == ctx.tenant_no,
  833. BizCollectionProtocol.del_flag == 0,
  834. BizCollectionProtocol.source_presign_order_id.in_(presign_ids),
  835. )
  836. .limit(1)
  837. .all()
  838. )
  839. return bool(protocol_rows)
  840. def _has_accessible_market_attachment_reference(
  841. db: Session,
  842. *,
  843. module: str,
  844. candidates: List[str],
  845. ctx: MarketFieldContext,
  846. user_info: dict,
  847. ) -> bool:
  848. """附件必须被当前模块中调用人可访问的业务记录引用。"""
  849. if module == 'protocol':
  850. cell_fields = (
  851. 'protocol_attachments',
  852. 'consent_form_urls',
  853. 'health_survey_form_urls',
  854. )
  855. cell_columns = tuple(
  856. getattr(BizCollectionProtocol, field) for field in cell_fields
  857. )
  858. cell_rows = (
  859. apply_cell_protocol_scope(
  860. db.query(BizCollectionProtocol),
  861. db,
  862. ctx,
  863. user_info=user_info,
  864. )
  865. .filter(_attachment_columns_filter(cell_columns, candidates))
  866. .all()
  867. )
  868. if _rows_reference_attachment(cell_rows, cell_fields, candidates):
  869. return True
  870. payment_detail_rows = (
  871. apply_cell_protocol_scope(
  872. db.query(BizProtocolPaymentDetail)
  873. .join(
  874. BizProtocolPayment,
  875. BizProtocolPayment.id == BizProtocolPaymentDetail.payment_id,
  876. )
  877. .join(
  878. BizCollectionProtocol,
  879. BizCollectionProtocol.id
  880. == BizProtocolPayment.collection_protocol_id,
  881. ),
  882. db,
  883. ctx,
  884. user_info=user_info,
  885. )
  886. .filter(
  887. BizProtocolPaymentDetail.tenant_no == ctx.tenant_no,
  888. BizProtocolPaymentDetail.del_flag == 0,
  889. BizProtocolPayment.tenant_no == ctx.tenant_no,
  890. BizProtocolPayment.del_flag == 0,
  891. _attachment_columns_filter(
  892. (BizProtocolPaymentDetail.transfer_attachments,), candidates
  893. ),
  894. )
  895. .all()
  896. )
  897. if _rows_reference_attachment(
  898. payment_detail_rows, ('transfer_attachments',), candidates
  899. ):
  900. return True
  901. if _has_accessible_protocol_cert_or_insurance_reference(
  902. db,
  903. candidates=candidates,
  904. ctx=ctx,
  905. user_info=user_info,
  906. ):
  907. return True
  908. if _has_accessible_protocol_deposit_attachment_reference(
  909. db,
  910. candidates=candidates,
  911. ctx=ctx,
  912. user_info=user_info,
  913. ):
  914. return True
  915. donation_fields = (
  916. 'consent_form_urls',
  917. 'attachment_urls',
  918. 'infectious_disease_report_urls',
  919. )
  920. donation_columns = tuple(
  921. getattr(BizResearchDonation, field) for field in donation_fields
  922. )
  923. donation_rows = (
  924. apply_donation_scope(
  925. db.query(BizResearchDonation),
  926. db,
  927. ctx,
  928. user_info=user_info,
  929. )
  930. .filter(_attachment_columns_filter(donation_columns, candidates))
  931. .all()
  932. )
  933. return _rows_reference_attachment(
  934. donation_rows, donation_fields, candidates
  935. )
  936. if module == 'presign':
  937. rows = (
  938. apply_presign_scope(
  939. db.query(BizPresignTransfer).join(
  940. BizPresignOrder,
  941. BizPresignOrder.id == BizPresignTransfer.presign_order_id,
  942. ),
  943. db,
  944. ctx,
  945. user_info=user_info,
  946. )
  947. .filter(
  948. BizPresignTransfer.tenant_no == ctx.tenant_no,
  949. BizPresignTransfer.del_flag == 0,
  950. _attachment_columns_filter(
  951. (BizPresignTransfer.transfer_attachments,), candidates
  952. ),
  953. )
  954. .all()
  955. )
  956. return _rows_reference_attachment(
  957. rows, ('transfer_attachments',), candidates
  958. )
  959. if module == 'payment':
  960. rows = (
  961. apply_cell_protocol_scope(
  962. db.query(BizProtocolPaymentTransfer).join(
  963. BizCollectionProtocol,
  964. BizCollectionProtocol.id
  965. == BizProtocolPaymentTransfer.collection_protocol_id,
  966. ),
  967. db,
  968. ctx,
  969. user_info=user_info,
  970. )
  971. .filter(
  972. BizProtocolPaymentTransfer.tenant_no == ctx.tenant_no,
  973. BizProtocolPaymentTransfer.del_flag == 0,
  974. _attachment_columns_filter(
  975. (BizProtocolPaymentTransfer.transfer_attachments,), candidates
  976. ),
  977. )
  978. .all()
  979. )
  980. return _rows_reference_attachment(
  981. rows, ('transfer_attachments',), candidates
  982. )
  983. if module == 'sample':
  984. return _has_accessible_protocol_cert_or_insurance_reference(
  985. db,
  986. candidates=candidates,
  987. ctx=ctx,
  988. user_info=user_info,
  989. )
  990. return False
  991. def get_market_attachment_download_url(
  992. db: Session,
  993. *,
  994. file_url: str,
  995. file_name: Optional[str],
  996. module: str,
  997. ctx: MarketFieldContext,
  998. user_info: dict,
  999. storage_backend=storage,
  1000. ) -> Dict[str, str]:
  1001. """为市场移动端返回附件下载地址。
  1002. 新附件按市场模块隔离;历史 Web 附件没有 business_type,
  1003. 但仍必须是当前租户已登记的 BizAttachment 记录。
  1004. """
  1005. _verify_identity(ctx, user_info)
  1006. normalized_module = str(module or '').strip()
  1007. if normalized_module not in UPLOAD_MODULES:
  1008. raise ValueError('不支持的附件模块')
  1009. normalized_url = str(file_url or '').strip()
  1010. if not normalized_url or len(normalized_url) > MAX_ATTACHMENT_REF_LENGTH:
  1011. raise ValueError('文件地址无效')
  1012. candidates = _attachment_candidates(normalized_url)
  1013. rows = (
  1014. db.query(BizAttachment)
  1015. .filter(
  1016. BizAttachment.tenant_no == ctx.tenant_no,
  1017. BizAttachment.del_flag == 0,
  1018. BizAttachment.file_url.in_(candidates),
  1019. )
  1020. .all()
  1021. )
  1022. expected_staging = f'market:{ctx.scope_kind}:{normalized_module}:staging'
  1023. allowed_bound = {
  1024. f'market:specialist:{normalized_module}:bound',
  1025. f'market:manager:{normalized_module}:bound',
  1026. }
  1027. legacy_sample_bound = {
  1028. 'market:specialist:sample:bound',
  1029. 'market:manager:sample:bound',
  1030. }
  1031. legacy_presign_bound = {
  1032. 'market:specialist:presign:bound',
  1033. 'market:manager:presign:bound',
  1034. }
  1035. row = next(
  1036. (
  1037. item
  1038. for item in rows
  1039. if (
  1040. str(item.business_type or '').strip() == expected_staging
  1041. and str(item.create_by or '') == ctx.user_id
  1042. and not item.business_id
  1043. )
  1044. ),
  1045. None,
  1046. )
  1047. if row is None:
  1048. referenced_rows = [
  1049. item
  1050. for item in rows
  1051. if str(item.business_type or '').strip() in ({''} | allowed_bound)
  1052. ]
  1053. if referenced_rows and _has_accessible_market_attachment_reference(
  1054. db,
  1055. module=normalized_module,
  1056. candidates=candidates,
  1057. ctx=ctx,
  1058. user_info=user_info,
  1059. ):
  1060. row = referenced_rows[0]
  1061. if row is None and normalized_module == 'protocol':
  1062. sample_bound_rows = [
  1063. item
  1064. for item in rows
  1065. if str(item.business_type or '').strip() in legacy_sample_bound
  1066. ]
  1067. if (
  1068. sample_bound_rows
  1069. and _has_accessible_protocol_cert_or_insurance_reference(
  1070. db,
  1071. candidates=candidates,
  1072. ctx=ctx,
  1073. user_info=user_info,
  1074. )
  1075. ):
  1076. row = sample_bound_rows[0]
  1077. if row is None and normalized_module == 'protocol':
  1078. deposit_bound_rows = [
  1079. item
  1080. for item in rows
  1081. if str(item.business_type or '').strip() in legacy_presign_bound
  1082. ]
  1083. if (
  1084. deposit_bound_rows
  1085. and _has_accessible_protocol_deposit_attachment_reference(
  1086. db,
  1087. candidates=candidates,
  1088. ctx=ctx,
  1089. user_info=user_info,
  1090. )
  1091. ):
  1092. row = deposit_bound_rows[0]
  1093. if row is None:
  1094. raise PermissionError('附件不存在或无权下载')
  1095. download_name = str(row.original_name or '').strip()
  1096. if not download_name:
  1097. download_name = str(file_name or '').strip()
  1098. if not download_name:
  1099. download_name = str(row.file_url or '').rsplit('/', 1)[-1] or 'download'
  1100. return {
  1101. 'downloadUrl': storage_backend.presigned_download_url(
  1102. str(row.file_url), download_name
  1103. )
  1104. }
  1105. def validate_attachment_refs(
  1106. db: Session,
  1107. refs: Any,
  1108. *,
  1109. module: str,
  1110. ctx: MarketFieldContext,
  1111. creating: bool,
  1112. existing_refs: Any = None,
  1113. business_id: Optional[str] = None,
  1114. ) -> str:
  1115. """批量锁定并解析附件;有 business_id 时原子消费当前角色暂存记录。"""
  1116. normalized_module = str(module or '').strip()
  1117. if normalized_module not in UPLOAD_MODULES:
  1118. raise ValueError('不支持的附件模块')
  1119. values = _split_refs(refs)
  1120. if not values:
  1121. return ''
  1122. existing = set(_split_refs(existing_refs)) if not creating else set()
  1123. new_values = [value for value in values if value not in existing]
  1124. if not new_values:
  1125. return ','.join(values)
  1126. normalized_business_id = str(business_id or '').strip()
  1127. candidates_by_value = {
  1128. value: _attachment_candidates(value) for value in new_values
  1129. }
  1130. all_candidates = {
  1131. candidate
  1132. for candidates in candidates_by_value.values()
  1133. for candidate in candidates
  1134. }
  1135. rows = (
  1136. db.query(BizAttachment)
  1137. .filter(
  1138. BizAttachment.tenant_no == ctx.tenant_no,
  1139. BizAttachment.del_flag == 0,
  1140. or_(
  1141. BizAttachment.id.in_(new_values),
  1142. BizAttachment.file_url.in_(all_candidates),
  1143. ),
  1144. )
  1145. .with_for_update()
  1146. .all()
  1147. )
  1148. by_id = {str(row.id): row for row in rows}
  1149. by_url = {str(row.file_url): row for row in rows}
  1150. expected_staging = f'market:{ctx.scope_kind}:{normalized_module}:staging'
  1151. expected_bound = f'market:{ctx.scope_kind}:{normalized_module}:bound'
  1152. resolved = []
  1153. seen_row_ids = set()
  1154. for value in values:
  1155. if value in existing:
  1156. if value not in resolved:
  1157. resolved.append(value)
  1158. continue
  1159. row = by_id.get(value)
  1160. if row is None:
  1161. row = next(
  1162. (
  1163. by_url.get(candidate)
  1164. for candidate in candidates_by_value[value]
  1165. if by_url.get(candidate)
  1166. ),
  1167. None,
  1168. )
  1169. if row is None:
  1170. raise ValueError('附件不存在或无权引用')
  1171. if row.id in seen_row_ids:
  1172. continue
  1173. seen_row_ids.add(row.id)
  1174. is_current_staging = (
  1175. row.business_type == expected_staging
  1176. and row.create_by == ctx.user_id
  1177. and not row.business_id
  1178. )
  1179. is_same_binding = (
  1180. bool(normalized_business_id)
  1181. and row.business_type == expected_bound
  1182. and str(row.business_id or '') == normalized_business_id
  1183. )
  1184. if not (is_current_staging or is_same_binding):
  1185. raise ValueError('附件不存在、已被绑定或无权引用')
  1186. if normalized_business_id and is_current_staging:
  1187. row.business_type = expected_bound
  1188. row.business_id = normalized_business_id
  1189. db.add(row)
  1190. resolved.append(str(row.file_url))
  1191. if normalized_business_id:
  1192. db.flush()
  1193. return ','.join(resolved)
  1194. def allowed_actions(
  1195. module: str,
  1196. *,
  1197. status: str,
  1198. scope_kind: str = 'specialist',
  1199. source: str = '',
  1200. has_sample_code: bool = False,
  1201. has_payment_permission: bool = False,
  1202. ) -> List[str]:
  1203. """纯函数动作白名单;路由仍必须执行对应权限与状态校验。"""
  1204. module, state = str(module or '').strip(), str(status or '').strip().lower()
  1205. if module in {'presign-list', 'protocol-list', 'freight-list'}:
  1206. return ['create']
  1207. if module == 'presign':
  1208. if state == 'converted':
  1209. return ['edit']
  1210. if state == 'void':
  1211. return ['edit', 'delete']
  1212. return ['edit', 'convert', 'delete']
  1213. if module == 'presign-transfer':
  1214. if state == 'dfj':
  1215. return ['edit', 'delete', 'submit']
  1216. if state == 'jfqrz':
  1217. return ['withdraw']
  1218. return []
  1219. if module == 'protocol':
  1220. return ['edit', 'delete']
  1221. if module == 'payment':
  1222. return ['register-transfer']
  1223. if module == 'payment-transfer':
  1224. if state == 'dfj':
  1225. return ['edit-transfer', 'delete-payment-transfer', 'submit-finance']
  1226. if state == 'jfqrz':
  1227. return ['withdraw-transfer']
  1228. return []
  1229. if module == 'payment-chase':
  1230. return []
  1231. if module == 'sample':
  1232. return []
  1233. if module == 'freight':
  1234. return ['edit'] if scope_kind == 'manager' else []
  1235. return []
  1236. def decorate_allowed_actions(
  1237. module: str,
  1238. item: Dict[str, Any],
  1239. *,
  1240. scope_kind: str,
  1241. has_payment_permission: bool = False,
  1242. detail: bool = False,
  1243. ) -> Dict[str, Any]:
  1244. """为移动列表/详情 DTO 增加动作白名单,不把动作判断交给客户端。"""
  1245. data = dict(item)
  1246. basic = data.get('basic') if isinstance(data.get('basic'), dict) else {}
  1247. status = str(
  1248. data.get('orderStatus')
  1249. or data.get('protocolStatus')
  1250. or data.get('donationStatus')
  1251. or data.get('payStatus')
  1252. or data.get('status')
  1253. or basic.get('protocolStatus')
  1254. or basic.get('donationStatus')
  1255. or basic.get('status')
  1256. or ''
  1257. )
  1258. if module == 'sample':
  1259. card = data.get('card') if isinstance(data.get('card'), dict) else data
  1260. source = str(card.get('source') or data.get('source') or '')
  1261. sample_code = str(card.get('sampleCode') or data.get('sampleCode') or '')
  1262. candidates = allowed_actions(
  1263. module,
  1264. status=status,
  1265. scope_kind=scope_kind,
  1266. source=source,
  1267. has_sample_code=bool(sample_code.strip()),
  1268. )
  1269. progress = data.get('progress') if isinstance(data.get('progress'), dict) else card.get('progress') or {}
  1270. storage_ready = str((progress.get('storage') or {}).get('code') or '') == 'yrk'
  1271. handles = next(
  1272. (
  1273. section
  1274. for section in data.get('sections') or []
  1275. if section.get('key') == 'market-handles'
  1276. ),
  1277. {},
  1278. )
  1279. storage_cert = card.get('storageCert') or handles.get('storageCert') or {}
  1280. insurance = card.get('insurance') or handles.get('insurance') or {}
  1281. data['allowedActions'] = [
  1282. action
  1283. for action in candidates
  1284. if storage_ready
  1285. and (
  1286. (action == 'storage-cert' and storage_cert.get('code') != 'handled')
  1287. or (action == 'insurance' and insurance.get('code') != 'handled')
  1288. )
  1289. ]
  1290. return data
  1291. if module == 'payment':
  1292. schedules = []
  1293. has_writable_schedule = False
  1294. for schedule in data.get('schedules') or []:
  1295. schedule_data = dict(schedule)
  1296. try:
  1297. arrears = Decimal(str(schedule_data.get('arrearsAmount') or 0))
  1298. except (ArithmeticError, ValueError):
  1299. arrears = Decimal('0')
  1300. schedule_writable = (
  1301. str(schedule_data.get('scheduleStatus') or '').lower() != 'void'
  1302. and arrears > 0
  1303. )
  1304. schedule_data['allowedActions'] = (
  1305. ['register-transfer'] if schedule_writable else []
  1306. )
  1307. has_writable_schedule = has_writable_schedule or schedule_writable
  1308. transfers = []
  1309. for transfer in schedule_data.get('transfers') or []:
  1310. transfer_data = dict(transfer)
  1311. transfer_data['allowedActions'] = (
  1312. allowed_actions(
  1313. 'payment-transfer',
  1314. status=str(transfer_data.get('payStatus') or ''),
  1315. )
  1316. )
  1317. transfers.append(transfer_data)
  1318. schedule_data['transfers'] = transfers
  1319. schedules.append(schedule_data)
  1320. data['schedules'] = schedules
  1321. data['allowedActions'] = (
  1322. ['register-transfer'] if has_writable_schedule else []
  1323. )
  1324. return data
  1325. if module == 'presign' and detail:
  1326. parent_writable = status.lower() in {'', 'draft', 'active'}
  1327. data['transferAllowedActions'] = (
  1328. ['create-transfer'] if parent_writable else []
  1329. )
  1330. transfers = []
  1331. for transfer in data.get('transfers') or []:
  1332. transfer_data = dict(transfer)
  1333. transfer_data['allowedActions'] = (
  1334. allowed_actions(
  1335. 'presign-transfer',
  1336. status=str(transfer_data.get('payStatus') or ''),
  1337. )
  1338. if parent_writable
  1339. else []
  1340. )
  1341. transfers.append(transfer_data)
  1342. data['transfers'] = transfers
  1343. if module == 'freight' and (detail or isinstance(data.get('allowedActions'), list)):
  1344. provided = data.get('allowedActions')
  1345. safe_actions = {'edit', 'delete', 'link', 'unlink'}
  1346. data['allowedActions'] = (
  1347. [action for action in provided if action in safe_actions]
  1348. if isinstance(provided, list)
  1349. else ['link', 'unlink']
  1350. )
  1351. return data
  1352. if module == 'protocol':
  1353. sample_payments = []
  1354. for payment in data.get('samplePayments') or []:
  1355. payment_data = dict(payment)
  1356. schedules = []
  1357. for schedule in payment_data.get('schedules') or []:
  1358. schedule_data = dict(schedule)
  1359. try:
  1360. arrears = Decimal(str(schedule_data.get('arrearsAmount') or 0))
  1361. except (ArithmeticError, ValueError):
  1362. arrears = Decimal('0')
  1363. schedule_writable = (
  1364. has_payment_permission
  1365. and str(schedule_data.get('scheduleStatus') or '').lower() != 'void'
  1366. and arrears > 0
  1367. )
  1368. schedule_data['allowedActions'] = (
  1369. ['register-transfer'] if schedule_writable else []
  1370. )
  1371. transfers = []
  1372. for transfer in schedule_data.get('transfers') or []:
  1373. transfer_data = dict(transfer)
  1374. transfer_data['allowedActions'] = (
  1375. allowed_actions(
  1376. 'payment-transfer',
  1377. status=str(transfer_data.get('payStatus') or ''),
  1378. )
  1379. if has_payment_permission
  1380. else []
  1381. )
  1382. transfers.append(transfer_data)
  1383. schedule_data['transfers'] = transfers
  1384. schedules.append(schedule_data)
  1385. payment_data['schedules'] = schedules
  1386. sample_payments.append(payment_data)
  1387. data['samplePayments'] = sample_payments
  1388. actions = allowed_actions(
  1389. module,
  1390. status=status,
  1391. scope_kind=scope_kind,
  1392. has_payment_permission=has_payment_permission,
  1393. )
  1394. data['allowedActions'] = actions
  1395. return data