service.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. import io
  2. from typing import Any
  3. import pandas as pd
  4. from fastapi import UploadFile
  5. from app.api.v1.module_system.auth.schema import AuthSchema, SmsCodeSchema
  6. from app.api.v1.module_system.dept.crud import DeptCRUD
  7. from app.api.v1.module_system.menu.crud import MenuCRUD
  8. from app.api.v1.module_system.menu.schema import MenuOutSchema
  9. from app.api.v1.module_system.position.crud import PositionCRUD
  10. from app.api.v1.module_system.role.crud import RoleCRUD
  11. from app.core.base_schema import BatchSetAvailable, UploadResponseSchema
  12. from app.core.exceptions import CustomException
  13. from app.core.logger import log
  14. from app.utils.common_util import traversal_to_tree
  15. from app.utils.excel_util import ExcelUtil
  16. from app.utils.hash_bcrpy_util import PwdUtil
  17. from app.utils.upload_util import UploadUtil
  18. from redis.asyncio.client import Redis
  19. from .crud import UserCRUD
  20. from .schema import (
  21. CurrentUserUpdateSchema,
  22. ResetPasswordSchema,
  23. UserChangePasswordSchema,
  24. UserCreateSchema,
  25. UserForgetPasswordSchema,
  26. UserOutSchema,
  27. UserQueryParam,
  28. UserRegisterSchema,
  29. UserUpdateSchema,
  30. )
  31. from ..auth.service import SmsCodeService
  32. from ..tenant.schema import TenantCreateSchema
  33. from ..tenant.service import TenantService
  34. class UserService:
  35. """用户模块服务层"""
  36. @classmethod
  37. async def get_detail_by_id_service(cls, auth: AuthSchema, id: int) -> dict:
  38. """
  39. 根据ID获取用户详情
  40. 参数:
  41. - auth (AuthSchema): 认证信息模型
  42. - id (int): 用户ID
  43. 返回:
  44. - dict: 用户详情字典
  45. """
  46. user = await UserCRUD(auth).get_by_id_crud(id=id)
  47. if not user:
  48. raise CustomException(msg="用户不存在")
  49. # 如果用户绑定了部门,则获取部门名称
  50. if user.dept_id:
  51. dept = await DeptCRUD(auth).get_by_id_crud(id=user.dept_id)
  52. UserOutSchema.dept_name = dept.name if dept else None
  53. else:
  54. UserOutSchema.dept_name = None
  55. return UserOutSchema.model_validate(user).model_dump()
  56. @classmethod
  57. async def get_user_list_service(
  58. cls,
  59. auth: AuthSchema,
  60. search: UserQueryParam | None = None,
  61. order_by: list[dict[str, str]] | None = None,
  62. ) -> list[dict]:
  63. """
  64. 获取用户列表
  65. 参数:
  66. - auth (AuthSchema): 认证信息模型
  67. - search (UserQueryParam | None): 查询参数对象。
  68. - order_by (list[dict[str, str]] | None): 排序参数列表。
  69. 返回:
  70. - list[dict]: 用户详情字典列表
  71. """
  72. user_list = await UserCRUD(auth).get_list_crud(search=search.__dict__, order_by=order_by)
  73. user_dict_list = []
  74. for user in user_list:
  75. user_dict = UserOutSchema.model_validate(user).model_dump()
  76. user_dict_list.append(user_dict)
  77. return user_dict_list
  78. @classmethod
  79. async def get_user_page_service(
  80. cls,
  81. auth: AuthSchema,
  82. page_no: int,
  83. page_size: int,
  84. search: UserQueryParam | None = None,
  85. order_by: list[dict[str, str]] | None = None,
  86. ) -> dict:
  87. """
  88. 分页查询用户(数据库 OFFSET/LIMIT)。
  89. 参数:
  90. - auth (AuthSchema): 认证信息模型
  91. - page_no (int): 页码(从 1 开始)
  92. - page_size (int): 每页条数
  93. - search (UserQueryParam | None): 查询条件
  94. - order_by (list[dict[str, str]] | None): 排序字段列表
  95. 返回:
  96. - dict: 分页结果(结构由 `CRUD.page` 返回约定)
  97. """
  98. offset = (page_no - 1) * page_size
  99. return await UserCRUD(auth).page(
  100. offset=offset,
  101. limit=page_size,
  102. order_by=order_by or [{"id": "asc"}],
  103. search=search.__dict__ if search else {},
  104. out_schema=UserOutSchema,
  105. )
  106. @classmethod
  107. async def create_user_service(cls, data: UserCreateSchema, auth: AuthSchema) -> dict:
  108. """
  109. 创建用户
  110. 参数:
  111. - data (UserCreateSchema): 用户创建信息
  112. - auth (AuthSchema): 认证信息模型
  113. 返回:
  114. - dict: 创建后的用户详情字典
  115. """
  116. if not data.username:
  117. raise CustomException(msg="用户名不能为空")
  118. # 检查是否试图创建超级管理员
  119. if data.is_superuser:
  120. raise CustomException(msg="不允许创建超级管理员")
  121. # 检查用户名是否存在
  122. user = await UserCRUD(auth).get_by_username_crud(username=data.username)
  123. if user:
  124. raise CustomException(msg="已存在相同用户名称的账号")
  125. # 检查部门是否存在
  126. if data.dept_id:
  127. dept = await DeptCRUD(auth).get_by_id_crud(id=data.dept_id)
  128. if not dept:
  129. raise CustomException(msg="部门不存在")
  130. # 创建用户
  131. if data.password:
  132. data.password = PwdUtil.set_password_hash(password=data.password)
  133. user_dict = data.model_dump(exclude_unset=True, exclude={"role_ids", "position_ids"})
  134. # 创建用户
  135. new_user = await UserCRUD(auth).create(data=user_dict)
  136. # 设置角色
  137. if data.role_ids and len(data.role_ids) > 0:
  138. await UserCRUD(auth).set_user_roles_crud(user_ids=[new_user.id], role_ids=data.role_ids)
  139. # 设置岗位
  140. if data.position_ids and len(data.position_ids) > 0:
  141. await UserCRUD(auth).set_user_positions_crud(
  142. user_ids=[new_user.id], position_ids=data.position_ids
  143. )
  144. new_user_dict = UserOutSchema.model_validate(new_user).model_dump()
  145. return new_user_dict
  146. @classmethod
  147. async def update_user_service(cls, id: int, data: UserUpdateSchema, auth: AuthSchema) -> dict:
  148. """
  149. 更新用户
  150. 参数:
  151. - id (int): 用户ID
  152. - data (UserUpdateSchema): 用户更新信息
  153. - auth (AuthSchema): 认证信息模型
  154. 返回:
  155. - Dict: 更新后的用户详情字典
  156. """
  157. if not data.username:
  158. raise CustomException(msg="账号不能为空")
  159. # 检查用户是否存在
  160. user = await UserCRUD(auth).get_by_id_crud(id=id)
  161. if not user:
  162. raise CustomException(msg="用户不存在")
  163. # 检查是否尝试修改超级管理员
  164. if user.is_superuser:
  165. raise CustomException(msg="超级管理员不允许修改")
  166. # 检查用户名是否重复
  167. exist_user = await UserCRUD(auth).get_by_username_crud(username=data.username)
  168. if exist_user and exist_user.id != id:
  169. raise CustomException(msg="已存在相同的账号")
  170. # 新增:检查手机号是否重复
  171. if data.mobile:
  172. exist_mobile_user = await UserCRUD(auth).get_by_mobile_crud(mobile=data.mobile)
  173. if exist_mobile_user and exist_mobile_user.id != id:
  174. raise CustomException(msg="更新失败,手机号已存在")
  175. # 新增:检查邮箱是否重复
  176. if data.email:
  177. exist_email_user = await UserCRUD(auth).get(email=data.email)
  178. if exist_email_user and exist_email_user.id != id:
  179. raise CustomException(msg="更新失败,邮箱已存在")
  180. # 检查部门是否存在且可用
  181. if data.dept_id:
  182. dept = await DeptCRUD(auth).get_by_id_crud(id=data.dept_id)
  183. if not dept:
  184. raise CustomException(msg="部门不存在")
  185. if dept.status == "1":
  186. raise CustomException(msg="部门已被禁用")
  187. # 更新用户 - 排除不应被修改的字段, 更新不更新密码
  188. user_dict = data.model_dump(
  189. exclude_unset=True,
  190. exclude={"role_ids", "position_ids", "last_login", "password"},
  191. )
  192. new_user = await UserCRUD(auth).update(id=id, data=user_dict)
  193. # 更新角色和岗位
  194. if data.role_ids and len(data.role_ids) > 0:
  195. # 检查角色是否都存在且可用
  196. roles = await RoleCRUD(auth).get_list_crud(search={"id": ("in", data.role_ids)})
  197. if len(roles) != len(data.role_ids):
  198. raise CustomException(msg="部分角色不存在")
  199. if not all(role.status for role in roles):
  200. raise CustomException(msg="部分角色已被禁用")
  201. await UserCRUD(auth).set_user_roles_crud(user_ids=[id], role_ids=data.role_ids)
  202. if data.position_ids and len(data.position_ids) > 0:
  203. # 检查岗位是否都存在且可用
  204. positions = await PositionCRUD(auth).get_list_crud(
  205. search={"id": ("in", data.position_ids)}
  206. )
  207. if len(positions) != len(data.position_ids):
  208. raise CustomException(msg="部分岗位不存在")
  209. if not all(position.status for position in positions):
  210. raise CustomException(msg="部分岗位已被禁用")
  211. await UserCRUD(auth).set_user_positions_crud(
  212. user_ids=[id], position_ids=data.position_ids
  213. )
  214. user_dict = UserOutSchema.model_validate(new_user).model_dump()
  215. return user_dict
  216. @classmethod
  217. async def delete_user_service(cls, auth: AuthSchema, ids: list[int]) -> None:
  218. """
  219. 删除用户
  220. 参数:
  221. - auth (AuthSchema): 认证信息模型
  222. - ids (list[int]): 用户ID列表
  223. 返回:
  224. - None
  225. """
  226. if len(ids) < 1:
  227. raise CustomException(msg="删除失败,删除对象不能为空")
  228. for id in ids:
  229. user = await UserCRUD(auth).get_by_id_crud(id=id)
  230. if not user:
  231. raise CustomException(msg="用户不存在")
  232. if user.is_superuser:
  233. raise CustomException(msg="超级管理员不能删除")
  234. if user.status == "0":
  235. raise CustomException(msg="用户已启用,不能删除")
  236. if auth.user and auth.user.id == id:
  237. raise CustomException(msg="不能删除当前登陆用户")
  238. # 删除用户角色关联数据
  239. await UserCRUD(auth).set_user_roles_crud(user_ids=ids, role_ids=[])
  240. # 删除用户岗位关联数据
  241. await UserCRUD(auth).set_user_positions_crud(user_ids=ids, position_ids=[])
  242. # 删除用户
  243. await UserCRUD(auth).delete(ids=ids)
  244. @classmethod
  245. async def get_current_user_info_service(cls, auth: AuthSchema) -> dict:
  246. """
  247. 获取当前用户信息
  248. 参数:
  249. - auth (AuthSchema): 认证信息模型
  250. 返回:
  251. - Dict: 当前用户详情字典
  252. """
  253. # 获取用户基本信息
  254. if not auth.user or not auth.user.id:
  255. raise CustomException(msg="用户不存在")
  256. user = await UserCRUD(auth).get_by_id_crud(id=auth.user.id)
  257. # 获取部门名称
  258. if user and user.dept:
  259. UserOutSchema.dept_name = user.dept.name
  260. user_dict = UserOutSchema.model_validate(user).model_dump()
  261. # 获取菜单权限
  262. if auth.user and auth.user.is_superuser:
  263. # 使用树形结构查询,预加载children关系
  264. menu_all = await MenuCRUD(auth).get_tree_list_crud(
  265. search={"type": ("in", [1, 2, 4]), "status": "0"},
  266. order_by=[{"order": "asc"}],
  267. )
  268. menus = [MenuOutSchema.model_validate(menu).model_dump() for menu in menu_all]
  269. else:
  270. # 收集用户所有角色的菜单ID,使用列表推导式优化代码
  271. menu_ids = {
  272. menu.id
  273. for role in auth.user.roles or []
  274. for menu in role.menus
  275. if menu.status == "0" and menu.type in [1, 2, 4]
  276. }
  277. # 使用树形结构查询,预加载children关系
  278. menus = (
  279. [
  280. MenuOutSchema.model_validate(menu).model_dump()
  281. for menu in await MenuCRUD(auth).get_tree_list_crud(
  282. search={"id": ("in", list(menu_ids))},
  283. order_by=[{"order": "asc"}],
  284. )
  285. ]
  286. if menu_ids
  287. else []
  288. )
  289. user_dict["menus"] = traversal_to_tree(menus)
  290. return user_dict
  291. @classmethod
  292. async def update_current_user_info_service(
  293. cls, auth: AuthSchema, data: CurrentUserUpdateSchema
  294. ) -> dict:
  295. """
  296. 更新当前用户信息
  297. 参数:
  298. - auth (AuthSchema): 认证信息模型
  299. - data (CurrentUserUpdateSchema): 当前用户更新信息
  300. 返回:
  301. - Dict: 更新后的当前用户详情字典
  302. """
  303. if not auth.user or not auth.user.id:
  304. raise CustomException(msg="用户不存在")
  305. user = await UserCRUD(auth).get_by_id_crud(id=auth.user.id)
  306. if not user:
  307. raise CustomException(msg="用户不存在")
  308. if user.is_superuser:
  309. raise CustomException(msg="超级管理员不能修改个人信息")
  310. # 新增:检查手机号是否重复
  311. if data.mobile:
  312. exist_mobile_user = await UserCRUD(auth).get_by_mobile_crud(mobile=data.mobile)
  313. if exist_mobile_user and exist_mobile_user.id != auth.user.id:
  314. raise CustomException(msg="更新失败,手机号已存在")
  315. # 新增:检查邮箱是否重复
  316. if data.email:
  317. exist_email_user = await UserCRUD(auth).get(email=data.email)
  318. if exist_email_user and exist_email_user.id != auth.user.id:
  319. raise CustomException(msg="更新失败,邮箱已存在")
  320. user_update_data = UserUpdateSchema(**data.model_dump())
  321. new_user = await UserCRUD(auth).update(id=auth.user.id, data=user_update_data)
  322. return UserOutSchema.model_validate(new_user).model_dump()
  323. @classmethod
  324. async def set_user_available_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
  325. """
  326. 设置用户状态
  327. 参数:
  328. - auth (AuthSchema): 认证信息模型
  329. - data (BatchSetAvailable): 批量设置用户状态数据
  330. 返回:
  331. - None
  332. """
  333. for id in data.ids:
  334. user = await UserCRUD(auth).get_by_id_crud(id=id)
  335. if not user:
  336. raise CustomException(msg=f"用户ID {id} 不存在")
  337. if user.is_superuser:
  338. raise CustomException(msg="超级管理员状态不能修改")
  339. await UserCRUD(auth).set_available_crud(ids=data.ids, status=data.status)
  340. @classmethod
  341. async def upload_avatar_service(cls, base_url: str, file: UploadFile) -> dict:
  342. """
  343. 上传用户头像
  344. 参数:
  345. - base_url (str): 基础URL
  346. - file (UploadFile): 上传的文件
  347. 返回:
  348. - Dict: 上传头像响应字典
  349. """
  350. filename, filepath, file_url = await UploadUtil.upload_file(file=file, base_url=base_url)
  351. return UploadResponseSchema(
  352. file_path=f"{filepath}",
  353. file_name=filename,
  354. origin_name=file.filename,
  355. file_url=f"{file_url}",
  356. ).model_dump()
  357. @classmethod
  358. async def change_user_password_service(
  359. cls, auth: AuthSchema, data: UserChangePasswordSchema
  360. ) -> dict:
  361. """
  362. 修改用户密码
  363. 参数:
  364. - auth (AuthSchema): 认证信息模型
  365. - data (UserChangePasswordSchema): 用户密码修改数据
  366. 返回:
  367. - Dict: 更新后的当前用户详情字典
  368. """
  369. if not auth.user or not auth.user.id:
  370. raise CustomException(msg="用户不存在")
  371. if not data.old_password or not data.new_password:
  372. raise CustomException(msg="密码不能为空")
  373. # 验证原密码
  374. user = await UserCRUD(auth).get_by_id_crud(id=auth.user.id)
  375. if not user:
  376. raise CustomException(msg="用户不存在")
  377. if not PwdUtil.verify_password(
  378. plain_password=data.old_password, password_hash=user.password
  379. ):
  380. raise CustomException(msg="原密码输入错误")
  381. # 更新密码
  382. new_password_hash = PwdUtil.set_password_hash(password=data.new_password)
  383. new_user = await UserCRUD(auth).change_password_crud(
  384. id=user.id, password_hash=new_password_hash
  385. )
  386. return UserOutSchema.model_validate(new_user).model_dump()
  387. @classmethod
  388. async def reset_user_password_service(cls, auth: AuthSchema, data: ResetPasswordSchema) -> dict:
  389. """
  390. 重置用户密码
  391. 参数:
  392. - auth (AuthSchema): 认证信息模型
  393. - data (ResetPasswordSchema): 用户密码重置数据
  394. 返回:
  395. - Dict: 更新后的当前用户详情字典
  396. """
  397. if not data.password:
  398. raise CustomException(msg="密码不能为空")
  399. # 验证用户
  400. user = await UserCRUD(auth).get_by_id_crud(id=data.id)
  401. if not user:
  402. raise CustomException(msg="用户不存在")
  403. # 检查是否是超级管理员
  404. if user.is_superuser:
  405. raise CustomException(msg="超级管理员密码不能重置")
  406. # 更新密码
  407. new_password_hash = PwdUtil.set_password_hash(password=data.password)
  408. new_user = await UserCRUD(auth).change_password_crud(
  409. id=data.id, password_hash=new_password_hash
  410. )
  411. return UserOutSchema.model_validate(new_user).model_dump()
  412. @classmethod
  413. async def register_user_service(cls, auth: AuthSchema, redis: Redis, data: UserRegisterSchema) -> dict:
  414. """
  415. 用户注册
  416. 参数:
  417. - auth (AuthSchema): 认证信息模型
  418. - data (UserRegisterSchema): 用户注册数据
  419. 返回:
  420. - Dict: 注册后的用户详情字典
  421. """
  422. # if not data.invite_code or data.invite_code != "8888":
  423. # raise CustomException("无效邀请码")
  424. # 检查用户名是否存在
  425. data.username = data.mobile
  426. username_ok = await UserCRUD(auth).get_by_mobile_crud(mobile=data.mobile)
  427. if username_ok:
  428. raise CustomException(msg="账号已存在")
  429. verify_result = await SmsCodeService.verify_sms_code_service(
  430. sms_code=SmsCodeSchema(
  431. mobile=data.mobile,
  432. template_name=data.template_name or "verify",
  433. code=data.sms_code,
  434. ),
  435. redis=redis
  436. )
  437. if not verify_result:
  438. raise CustomException("验证码过期或错误")
  439. tenant_data = TenantCreateSchema(
  440. name=data.mobile,
  441. code=data.mobile,
  442. )
  443. return await TenantService.create_service(auth=auth, data=tenant_data, password=data.password,)
  444. # data.password = PwdUtil.set_password_hash(password=data.password)
  445. # data.name = data.username
  446. # create_dict = data.model_dump(exclude_unset=True, exclude={"role_ids", "position_ids"})
  447. #
  448. # # 设置创建人ID
  449. # if auth.user and auth.user.id:
  450. # create_dict["created_id"] = auth.user.id
  451. #
  452. # result = await UserCRUD(auth).create(data=create_dict)
  453. # if data.role_ids:
  454. # await UserCRUD(auth).set_user_roles_crud(user_ids=[result.id], role_ids=data.role_ids)
  455. # return UserOutSchema.model_validate(result).model_dump()
  456. @classmethod
  457. async def forget_password_service(
  458. cls, auth: AuthSchema, data: UserForgetPasswordSchema
  459. ) -> dict:
  460. """
  461. 用户忘记密码
  462. 参数:
  463. - auth (AuthSchema): 认证信息模型
  464. - data (UserForgetPasswordSchema): 用户忘记密码数据
  465. 返回:
  466. - Dict: 更新后的当前用户详情字典
  467. """
  468. user = await UserCRUD(auth).get_by_username_crud(username=data.username)
  469. if not user:
  470. raise CustomException(msg="用户不存在")
  471. if user.status == "1":
  472. raise CustomException(msg="用户已停用")
  473. # 检查是否是超级管理员
  474. if user.is_superuser:
  475. raise CustomException(msg="超级管理员密码不能重置")
  476. new_password_hash = PwdUtil.set_password_hash(password=data.new_password)
  477. new_user = await UserCRUD(auth).forget_password_crud(
  478. id=user.id, password_hash=new_password_hash
  479. )
  480. return UserOutSchema.model_validate(new_user).model_dump()
  481. @classmethod
  482. async def batch_import_user_service(
  483. cls, auth: AuthSchema, file: UploadFile, update_support: bool = False
  484. ) -> str:
  485. """
  486. 批量导入用户
  487. 参数:
  488. - auth (AuthSchema): 认证信息模型
  489. - file (UploadFile): 上传的Excel文件
  490. - update_support (bool, optional): 是否支持更新已存在用户. 默认值为False.
  491. 返回:
  492. - str: 导入结果消息
  493. """
  494. header_dict = {
  495. "部门编号": "dept_id",
  496. "账号": "username",
  497. "昵称": "name",
  498. "邮箱": "email",
  499. "手机号": "mobile",
  500. "性别": "gender",
  501. "状态": "status",
  502. }
  503. try:
  504. # 读取Excel文件
  505. contents = await file.read()
  506. df = pd.read_excel(io.BytesIO(contents))
  507. await file.close()
  508. if df.empty:
  509. raise CustomException(msg="导入文件为空")
  510. # 检查表头是否完整
  511. missing_headers = [header for header in header_dict.keys() if header not in df.columns]
  512. if missing_headers:
  513. raise CustomException(msg=f"导入文件缺少必要的列: {', '.join(missing_headers)}")
  514. # 重命名列名
  515. df.rename(columns=header_dict, inplace=True)
  516. # 验证必填字段
  517. required_fields = ["username", "name", "dept_id"]
  518. errors = []
  519. for field in required_fields:
  520. missing_rows = df[df[field].isnull()].index.tolist()
  521. if missing_rows:
  522. field_name = next(k for k, v in header_dict.items() if v == field)
  523. rows_str = "、".join([str(i + 1) for i in missing_rows])
  524. errors.append(f"{field_name}不能为空,第{rows_str}行")
  525. if errors:
  526. raise CustomException(msg=";".join(errors))
  527. error_msgs = []
  528. success_count = 0
  529. count = 0
  530. # 处理每一行数据
  531. for _index, row in df.iterrows():
  532. try:
  533. count = count + 1
  534. # 数据转换
  535. gender = "1" if row["gender"] == "男" else ("2" if row["gender"] == "女" else "1")
  536. status = "0" if row["status"] == "正常" else "1"
  537. # 构建用户数据
  538. user_data = {
  539. "username": str(row["username"]).strip(),
  540. "name": str(row["name"]).strip(),
  541. "email": str(row["email"]).strip(),
  542. "mobile": str(row["mobile"]).strip(),
  543. "gender": gender,
  544. "status": status,
  545. "dept_id": int(row["dept_id"]),
  546. "password": PwdUtil.set_password_hash(password="123456"), # 设置默认密码
  547. }
  548. # 处理用户导入
  549. exists_user = await UserCRUD(auth).get_by_username_crud(
  550. username=user_data["username"]
  551. )
  552. if exists_user:
  553. # 检查是否是超级管理员
  554. if exists_user.is_superuser:
  555. error_msgs.append(f"第{count}行: 超级管理员不允许修改")
  556. continue
  557. if update_support:
  558. user_update_data = UserUpdateSchema(**user_data)
  559. await UserCRUD(auth).update(id=exists_user.id, data=user_update_data)
  560. success_count += 1
  561. else:
  562. error_msgs.append(f"第{count}行: 用户 {user_data['username']} 已存在")
  563. else:
  564. user_create_schema = UserCreateSchema(**user_data)
  565. user_create_data = user_create_schema.model_dump(
  566. exclude_unset=True, exclude={"role_ids", "position_ids"}
  567. )
  568. new_user = await UserCRUD(auth).create(data=user_create_data)
  569. if user_create_schema.role_ids and len(user_create_schema.role_ids) > 0:
  570. await UserCRUD(auth).set_user_roles_crud(
  571. user_ids=[new_user.id], role_ids=user_create_schema.role_ids
  572. )
  573. if user_create_schema.position_ids and len(user_create_schema.position_ids) > 0:
  574. await UserCRUD(auth).set_user_positions_crud(
  575. user_ids=[new_user.id], position_ids=user_create_schema.position_ids
  576. )
  577. success_count += 1
  578. except Exception as e:
  579. error_msgs.append(f"第{count}行: 异常{e!s}")
  580. continue
  581. # 返回详细的导入结果
  582. result = f"成功导入 {success_count} 条数据"
  583. if error_msgs:
  584. result += "\n错误信息:\n" + "\n".join(error_msgs)
  585. return result
  586. except Exception as e:
  587. log.error(f"批量导入用户失败: {e!s}")
  588. raise CustomException(msg=f"导入失败: {e!s}")
  589. @classmethod
  590. async def get_import_template_user_service(cls) -> bytes:
  591. """
  592. 获取用户导入模板
  593. 返回:
  594. - bytes: Excel文件字节流
  595. """
  596. header_list = [
  597. "部门编号",
  598. "账号",
  599. "昵称",
  600. "邮箱",
  601. "手机号",
  602. "性别",
  603. "状态",
  604. ]
  605. selector_header_list = ["性别", "状态"]
  606. option_list = [
  607. {"性别": ["男", "女", "未知"]},
  608. {"状态": ["正常", "停用"]},
  609. ]
  610. return ExcelUtil.get_excel_template(
  611. header_list=header_list,
  612. selector_header_list=selector_header_list,
  613. option_list=option_list,
  614. )
  615. @classmethod
  616. async def export_user_list_service(cls, user_list: list[dict[str, Any]]) -> bytes:
  617. """
  618. 导出用户列表为Excel文件
  619. 参数:
  620. - user_list (list[dict[str, Any]]): 用户列表
  621. 返回:
  622. - bytes: Excel文件字节流
  623. """
  624. if not user_list:
  625. raise CustomException(msg="没有数据可导出")
  626. # 定义字段映射
  627. mapping_dict = {
  628. "id": "用户编号",
  629. "avatar": "头像",
  630. "username": "用户名称",
  631. "name": "用户昵称",
  632. "dept_name": "部门",
  633. "email": "邮箱",
  634. "mobile": "手机号",
  635. "gender": "性别",
  636. "status": "状态",
  637. "is_superuser": "是否超级管理员",
  638. "last_login": "最后登录时间",
  639. "description": "备注",
  640. "created_time": "创建时间",
  641. "updated_time": "更新时间",
  642. "updated_id": "更新者ID",
  643. }
  644. # 复制数据并转换
  645. # creator = {'id': 1, 'name': '管理员', 'username': 'admin'}
  646. data = user_list.copy()
  647. for item in data:
  648. item["status"] = "启用" if item.get("status") == "0" else "停用"
  649. gender = item.get("gender")
  650. item["gender"] = "男" if gender == "1" else ("女" if gender == "2" else "未知")
  651. item["is_superuser"] = "是" if item.get("is_superuser") else "否"
  652. item["creator"] = (
  653. item.get("creator", {}).get("name", "未知")
  654. if isinstance(item.get("creator"), dict)
  655. else "未知"
  656. )
  657. return ExcelUtil.export_list2excel(list_data=data, mapping_dict=mapping_dict)