upload project source code
This commit is contained in:
@@ -0,0 +1 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
@@ -0,0 +1,144 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from fastapi import APIRouter, Depends, UploadFile, Body, Path, Query, Request
|
||||
from fastapi.responses import StreamingResponse, JSONResponse
|
||||
|
||||
from app.common.response import SuccessResponse, StreamResponse, ErrorResponse
|
||||
from app.core.dependencies import AuthPermission, db_getter, get_current_user
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from app.core.base_params import PaginationQueryParam
|
||||
from app.utils.common_util import bytes2file_response
|
||||
from app.core.logger import log
|
||||
from app.core.base_schema import BatchSetAvailable
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from .service import YifanFeedbackService
|
||||
from .schema import YifanFeedbackCreateSchema, YifanFeedbackUpdateSchema, YifanFeedbackQueryParam, MiniFeedbackSubmitSchema
|
||||
|
||||
YifanFeedbackRouter = APIRouter(prefix='/yifan_feedback', tags=["意见反馈模块"])
|
||||
|
||||
|
||||
@YifanFeedbackRouter.post("/mini/submit", summary="小程序-提交意见反馈", description="小程序用户提交意见反馈")
|
||||
async def submit_feedback_for_mini(
|
||||
data: MiniFeedbackSubmitSchema,
|
||||
auth: AuthSchema = Depends(get_current_user)
|
||||
) -> JSONResponse:
|
||||
"""
|
||||
小程序提交意见反馈接口
|
||||
|
||||
需要登录,自动获取当前用户ID
|
||||
"""
|
||||
user_id = auth.user.id
|
||||
|
||||
result = await YifanFeedbackService.submit_feedback_service(auth=auth, user_id=user_id, data=data)
|
||||
log.info(f"用户 {user_id} 提交意见反馈成功")
|
||||
return SuccessResponse(data=result, msg="提交成功,感谢您的反馈!")
|
||||
|
||||
@YifanFeedbackRouter.get("/detail/{id}", summary="获取意见反馈详情", description="获取意见反馈详情")
|
||||
async def get_yifan_feedback_detail_controller(
|
||||
id: int = Path(..., description="ID"),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_feedback:query"]))
|
||||
) -> JSONResponse:
|
||||
"""获取意见反馈详情接口"""
|
||||
result_dict = await YifanFeedbackService.detail_yifan_feedback_service(auth=auth, id=id)
|
||||
log.info(f"获取意见反馈详情成功 {id}")
|
||||
return SuccessResponse(data=result_dict, msg="获取意见反馈详情成功")
|
||||
|
||||
@YifanFeedbackRouter.get("/list", summary="查询意见反馈列表", description="查询意见反馈列表")
|
||||
async def get_yifan_feedback_list_controller(
|
||||
page: PaginationQueryParam = Depends(),
|
||||
search: YifanFeedbackQueryParam = Depends(),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_feedback:query"]))
|
||||
) -> JSONResponse:
|
||||
"""查询意见反馈列表接口(数据库分页)"""
|
||||
result_dict = await YifanFeedbackService.page_yifan_feedback_service(
|
||||
auth=auth,
|
||||
page_no=page.page_no if page.page_no is not None else 1,
|
||||
page_size=page.page_size if page.page_size is not None else 10,
|
||||
search=search,
|
||||
order_by=page.order_by
|
||||
)
|
||||
log.info("查询意见反馈列表成功")
|
||||
return SuccessResponse(data=result_dict, msg="查询意见反馈列表成功")
|
||||
|
||||
@YifanFeedbackRouter.post("/create", summary="创建意见反馈", description="创建意见反馈")
|
||||
async def create_yifan_feedback_controller(
|
||||
data: YifanFeedbackCreateSchema,
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_feedback:create"]))
|
||||
) -> JSONResponse:
|
||||
"""创建意见反馈接口"""
|
||||
result_dict = await YifanFeedbackService.create_yifan_feedback_service(auth=auth, data=data)
|
||||
log.info("创建意见反馈成功")
|
||||
return SuccessResponse(data=result_dict, msg="创建意见反馈成功")
|
||||
|
||||
@YifanFeedbackRouter.put("/update/{id}", summary="修改意见反馈", description="修改意见反馈")
|
||||
async def update_yifan_feedback_controller(
|
||||
data: YifanFeedbackUpdateSchema,
|
||||
id: int = Path(..., description="ID"),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_feedback:update"]))
|
||||
) -> JSONResponse:
|
||||
"""修改意见反馈接口"""
|
||||
result_dict = await YifanFeedbackService.update_yifan_feedback_service(auth=auth, id=id, data=data)
|
||||
log.info("修改意见反馈成功")
|
||||
return SuccessResponse(data=result_dict, msg="修改意见反馈成功")
|
||||
|
||||
@YifanFeedbackRouter.delete("/delete", summary="删除意见反馈", description="删除意见反馈")
|
||||
async def delete_yifan_feedback_controller(
|
||||
ids: list[int] = Body(..., description="ID列表"),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_feedback:delete"]))
|
||||
) -> JSONResponse:
|
||||
"""删除意见反馈接口"""
|
||||
await YifanFeedbackService.delete_yifan_feedback_service(auth=auth, ids=ids)
|
||||
log.info(f"删除意见反馈成功: {ids}")
|
||||
return SuccessResponse(msg="删除意见反馈成功")
|
||||
|
||||
@YifanFeedbackRouter.patch("/available/setting", summary="批量修改意见反馈状态", description="批量修改意见反馈状态")
|
||||
async def batch_set_available_yifan_feedback_controller(
|
||||
data: BatchSetAvailable,
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_feedback:patch"]))
|
||||
) -> JSONResponse:
|
||||
"""批量修改意见反馈状态接口"""
|
||||
await YifanFeedbackService.set_available_yifan_feedback_service(auth=auth, data=data)
|
||||
log.info(f"批量修改意见反馈状态成功: {data.ids}")
|
||||
return SuccessResponse(msg="批量修改意见反馈状态成功")
|
||||
|
||||
@YifanFeedbackRouter.post('/export', summary="导出意见反馈", description="导出意见反馈")
|
||||
async def export_yifan_feedback_list_controller(
|
||||
search: YifanFeedbackQueryParam = Depends(),
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_feedback:export"]))
|
||||
) -> StreamingResponse:
|
||||
"""导出意见反馈接口"""
|
||||
result_dict_list = await YifanFeedbackService.list_yifan_feedback_service(search=search, auth=auth)
|
||||
export_result = await YifanFeedbackService.batch_export_yifan_feedback_service(obj_list=result_dict_list)
|
||||
log.info('导出意见反馈成功')
|
||||
|
||||
return StreamResponse(
|
||||
data=bytes2file_response(export_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers={
|
||||
'Content-Disposition': 'attachment; filename=yifan_feedback.xlsx'
|
||||
}
|
||||
)
|
||||
|
||||
@YifanFeedbackRouter.post('/import', summary="导入意见反馈", description="导入意见反馈")
|
||||
async def import_yifan_feedback_list_controller(
|
||||
file: UploadFile,
|
||||
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_feedback:import"]))
|
||||
) -> JSONResponse:
|
||||
"""导入意见反馈接口"""
|
||||
batch_import_result = await YifanFeedbackService.batch_import_yifan_feedback_service(file=file, auth=auth, update_support=True)
|
||||
log.info("导入意见反馈成功")
|
||||
|
||||
return SuccessResponse(data=batch_import_result, msg="导入意见反馈成功")
|
||||
|
||||
@YifanFeedbackRouter.post('/download/template', summary="获取意见反馈导入模板", description="获取意见反馈导入模板", dependencies=[Depends(AuthPermission(["module_yifan:yifan_feedback:download"]))])
|
||||
async def export_yifan_feedback_template_controller() -> StreamingResponse:
|
||||
"""获取意见反馈导入模板接口"""
|
||||
import_template_result = await YifanFeedbackService.import_template_download_yifan_feedback_service()
|
||||
log.info('获取意见反馈导入模板成功')
|
||||
|
||||
return StreamResponse(
|
||||
data=bytes2file_response(import_template_result),
|
||||
media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
headers={'Content-Disposition': 'attachment; filename=yifan_feedback_template.xlsx'}
|
||||
)
|
||||
@@ -0,0 +1,123 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from typing import Sequence
|
||||
|
||||
from app.core.base_crud import CRUDBase
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from .model import YifanFeedbackModel
|
||||
from .schema import YifanFeedbackCreateSchema, YifanFeedbackUpdateSchema, YifanFeedbackOutSchema
|
||||
|
||||
|
||||
class YifanFeedbackCRUD(CRUDBase[YifanFeedbackModel, YifanFeedbackCreateSchema, YifanFeedbackUpdateSchema]):
|
||||
"""意见反馈数据层"""
|
||||
|
||||
def __init__(self, auth: AuthSchema) -> None:
|
||||
"""
|
||||
初始化CRUD数据层
|
||||
|
||||
参数:
|
||||
- auth (AuthSchema): 认证信息模型
|
||||
"""
|
||||
super().__init__(model=YifanFeedbackModel, auth=auth)
|
||||
|
||||
async def get_by_id_yifan_feedback_crud(self, id: int, preload: list | None = None) -> YifanFeedbackModel | None:
|
||||
"""
|
||||
详情
|
||||
|
||||
参数:
|
||||
- id (int): 对象ID
|
||||
- preload (list | None): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
返回:
|
||||
- YifanFeedbackModel | None: 模型实例或None
|
||||
"""
|
||||
return await self.get(id=id, preload=preload)
|
||||
|
||||
async def list_yifan_feedback_crud(self, search: dict | None = None, order_by: list[dict] | None = None, preload: list | None = None) -> Sequence[YifanFeedbackModel]:
|
||||
"""
|
||||
列表查询
|
||||
|
||||
参数:
|
||||
- search (dict | None): 查询参数
|
||||
- order_by (list[dict] | None): 排序参数,未提供时使用模型默认项
|
||||
- preload (list | None): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
返回:
|
||||
- Sequence[YifanFeedbackModel]: 模型实例序列
|
||||
"""
|
||||
return await self.list(search=search, order_by=order_by, preload=preload)
|
||||
|
||||
async def create_yifan_feedback_crud(self, data: YifanFeedbackCreateSchema) -> YifanFeedbackModel | None:
|
||||
"""
|
||||
创建
|
||||
|
||||
参数:
|
||||
- data (YifanFeedbackCreateSchema): 创建模型
|
||||
|
||||
返回:
|
||||
- YifanFeedbackModel | None: 模型实例或None
|
||||
"""
|
||||
return await self.create(data=data)
|
||||
|
||||
async def update_yifan_feedback_crud(self, id: int, data: YifanFeedbackUpdateSchema) -> YifanFeedbackModel | None:
|
||||
"""
|
||||
更新
|
||||
|
||||
参数:
|
||||
- id (int): 对象ID
|
||||
- data (YifanFeedbackUpdateSchema): 更新模型
|
||||
|
||||
返回:
|
||||
- YifanFeedbackModel | None: 模型实例或None
|
||||
"""
|
||||
return await self.update(id=id, data=data)
|
||||
|
||||
async def delete_yifan_feedback_crud(self, ids: list[int]) -> None:
|
||||
"""
|
||||
批量删除
|
||||
|
||||
参数:
|
||||
- ids (list[int]): 对象ID列表
|
||||
|
||||
返回:
|
||||
- None
|
||||
"""
|
||||
return await self.delete(ids=ids)
|
||||
|
||||
async def set_available_yifan_feedback_crud(self, ids: list[int], status: str) -> None:
|
||||
"""
|
||||
批量设置可用状态
|
||||
|
||||
参数:
|
||||
- ids (list[int]): 对象ID列表
|
||||
- status (str): 可用状态
|
||||
|
||||
返回:
|
||||
- None
|
||||
"""
|
||||
return await self.set(ids=ids, status=status)
|
||||
|
||||
async def page_yifan_feedback_crud(self, offset: int, limit: int, order_by: list[dict] | None = None, search: dict | None = None, preload: list | None = None) -> dict:
|
||||
"""
|
||||
分页查询
|
||||
|
||||
参数:
|
||||
- offset (int): 偏移量
|
||||
- limit (int): 每页数量
|
||||
- order_by (list[dict] | None): 排序参数,未提供时使用模型默认项
|
||||
- search (dict | None): 查询参数,未提供时查询所有
|
||||
- preload (list | None): 预加载关系,未提供时使用模型默认项
|
||||
|
||||
返回:
|
||||
- Dict: 分页数据
|
||||
"""
|
||||
order_by_list = order_by or [{'id': 'asc'}]
|
||||
search_dict = search or {}
|
||||
return await self.page(
|
||||
offset=offset,
|
||||
limit=limit,
|
||||
order_by=order_by_list,
|
||||
search=search_dict,
|
||||
out_schema=YifanFeedbackOutSchema,
|
||||
preload=preload
|
||||
)
|
||||
@@ -0,0 +1,29 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import datetime
|
||||
from sqlalchemy import Integer, DateTime, SmallInteger, Text, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.base_model import ModelMixin, UserMixin
|
||||
|
||||
|
||||
class YifanFeedbackModel(ModelMixin, UserMixin):
|
||||
"""
|
||||
意见反馈表
|
||||
"""
|
||||
__tablename__: str = 'yifan_feedback'
|
||||
__table_args__: dict[str, str] = {'comment': '意见反馈'}
|
||||
__loader_options__: list[str] = ["created_by", "updated_by"]
|
||||
|
||||
is_deleted: Mapped[int | None] = mapped_column(SmallInteger, nullable=True, comment='是否删除(0否 1是)')
|
||||
user_id: Mapped[int | None] = mapped_column(Integer, nullable=True, comment='用户ID')
|
||||
content: Mapped[str | None] = mapped_column(Text, nullable=True, comment='反馈内容')
|
||||
images: Mapped[str | None] = mapped_column(String(1000), nullable=True, comment='图片URL(多个用逗号分隔)')
|
||||
contact: Mapped[str | None] = mapped_column(String(100), nullable=True, comment='联系方式')
|
||||
feedback_type: Mapped[str | None] = mapped_column(String(32), nullable=True, comment='反馈类型(suggestion:建议 bug:问题 complaint:投诉 other:其他)')
|
||||
handle_status: Mapped[int | None] = mapped_column(SmallInteger, nullable=True, comment='处理状态(0待处理 1处理中 2已处理 3已关闭)')
|
||||
handle_result: Mapped[str | None] = mapped_column(Text, nullable=True, comment='处理结果')
|
||||
handle_time: Mapped[datetime.datetime | None] = mapped_column(DateTime, nullable=True, comment='处理时间')
|
||||
handler_id: Mapped[int | None] = mapped_column(Integer, nullable=True, comment='处理人ID')
|
||||
remark: Mapped[str | None] = mapped_column(String(255), nullable=True, comment='备注')
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import datetime
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from fastapi import Query
|
||||
|
||||
from app.core.validator import DateTimeStr
|
||||
from app.core.base_schema import BaseSchema, UserBySchema
|
||||
|
||||
|
||||
class MiniFeedbackSubmitSchema(BaseModel):
|
||||
"""
|
||||
小程序提交意见反馈模型
|
||||
"""
|
||||
content: str = Field(..., min_length=1, max_length=2000, description='反馈内容')
|
||||
images: str | None = Field(default=None, description='图片URL(多个用逗号分隔)')
|
||||
contact: str | None = Field(default=None, max_length=100, description='联系方式')
|
||||
feedback_type: str = Field(default='other', description='反馈类型(suggestion:建议 bug:问题 complaint:投诉 other:其他)')
|
||||
|
||||
|
||||
class YifanFeedbackCreateSchema(BaseModel):
|
||||
"""
|
||||
意见反馈新增模型
|
||||
"""
|
||||
is_deleted: int = Field(default=0, description='是否删除(0否 1是)')
|
||||
status: int = Field(default=1, description='状态(0禁用 1启用)')
|
||||
user_id: int | None = Field(default=None, description='用户ID')
|
||||
content: str = Field(default=..., description='反馈内容')
|
||||
images: str | None = Field(default=None, description='图片URL(多个用逗号分隔)')
|
||||
contact: str | None = Field(default=None, description='联系方式')
|
||||
feedback_type: str = Field(default='other', description='反馈类型(suggestion:建议 bug:问题 complaint:投诉 other:其他)')
|
||||
handle_status: int = Field(default=0, description='处理状态(0待处理 1处理中 2已处理 3已关闭)')
|
||||
handle_result: str | None = Field(default=None, description='处理结果')
|
||||
handle_time: DateTimeStr | None = Field(default=None, description='处理时间')
|
||||
handler_id: int | None = Field(default=None, description='处理人ID')
|
||||
remark: str | None = Field(default=None, description='备注')
|
||||
|
||||
|
||||
class YifanFeedbackUpdateSchema(YifanFeedbackCreateSchema):
|
||||
"""
|
||||
意见反馈更新模型
|
||||
"""
|
||||
...
|
||||
|
||||
|
||||
class YifanFeedbackOutSchema(YifanFeedbackCreateSchema, BaseSchema, UserBySchema):
|
||||
"""
|
||||
意见反馈响应模型
|
||||
"""
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class YifanFeedbackQueryParam:
|
||||
"""意见反馈查询参数"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
content: str | None = Query(None, description="反馈内容"),
|
||||
images: str | None = Query(None, description="图片URL(多个用逗号分隔)"),
|
||||
contact: str | None = Query(None, description="联系方式"),
|
||||
feedback_type: str | None = Query(None, description="反馈类型(suggestion:建议 bug:问题 complaint:投诉 other:其他)"),
|
||||
handle_result: str | None = Query(None, description="处理结果"),
|
||||
remark: str | None = Query(None, description="备注"),
|
||||
created_id: int | None = Query(None, description="创建人ID"),
|
||||
updated_id: int | None = Query(None, description="更新人ID"),
|
||||
is_deleted: int | None = Query(None, description="是否删除(0否 1是)"),
|
||||
status: int | None = Query(None, description="状态(0禁用 1启用)"),
|
||||
user_id: int | None = Query(None, description="用户ID"),
|
||||
handle_status: int | None = Query(None, description="处理状态(0待处理 1处理中 2已处理 3已关闭)"),
|
||||
handle_time: datetime.datetime | None = Query(None, description="处理时间"),
|
||||
handler_id: int | None = Query(None, description="处理人ID"),
|
||||
created_time: list[DateTimeStr] | None = Query(None, description="创建时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
|
||||
updated_time: list[DateTimeStr] | None = Query(None, description="更新时间范围", examples=["2025-01-01 00:00:00", "2025-12-31 23:59:59"]),
|
||||
|
||||
) -> None:
|
||||
|
||||
# 精确查询字段
|
||||
self.created_id = created_id
|
||||
# 精确查询字段
|
||||
self.updated_id = updated_id
|
||||
# 精确查询字段
|
||||
self.is_deleted = is_deleted
|
||||
# 精确查询字段
|
||||
self.status = status
|
||||
# 精确查询字段
|
||||
self.user_id = user_id
|
||||
# 模糊查询字段
|
||||
self.content = ("like", content)
|
||||
# 模糊查询字段
|
||||
self.images = ("like", images)
|
||||
# 模糊查询字段
|
||||
self.contact = ("like", contact)
|
||||
# 模糊查询字段
|
||||
self.feedback_type = ("like", feedback_type)
|
||||
# 精确查询字段
|
||||
self.handle_status = handle_status
|
||||
# 模糊查询字段
|
||||
self.handle_result = ("like", handle_result)
|
||||
# 精确查询字段
|
||||
self.handle_time = handle_time
|
||||
# 精确查询字段
|
||||
self.handler_id = handler_id
|
||||
# 模糊查询字段
|
||||
self.remark = ("like", remark)
|
||||
# 时间范围查询
|
||||
if created_time and len(created_time) == 2:
|
||||
self.created_time = ("between", (created_time[0], created_time[1]))
|
||||
if updated_time and len(updated_time) == 2:
|
||||
self.updated_time = ("between", (updated_time[0], updated_time[1]))
|
||||
@@ -0,0 +1,267 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import io
|
||||
from fastapi import UploadFile
|
||||
import pandas as pd
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.base_schema import BatchSetAvailable
|
||||
from app.core.exceptions import CustomException
|
||||
from app.utils.excel_util import ExcelUtil
|
||||
from app.core.logger import log
|
||||
from app.api.v1.module_system.auth.schema import AuthSchema
|
||||
from .schema import YifanFeedbackCreateSchema, YifanFeedbackUpdateSchema, YifanFeedbackOutSchema, YifanFeedbackQueryParam, MiniFeedbackSubmitSchema
|
||||
from .crud import YifanFeedbackCRUD
|
||||
from .model import YifanFeedbackModel
|
||||
|
||||
|
||||
class YifanFeedbackService:
|
||||
"""
|
||||
意见反馈服务层
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
async def submit_feedback_service(cls, auth: AuthSchema, user_id: int, data: MiniFeedbackSubmitSchema) -> dict:
|
||||
"""
|
||||
小程序提交意见反馈
|
||||
"""
|
||||
# 构造创建数据
|
||||
create_data = {
|
||||
'user_id': user_id,
|
||||
'content': data.content,
|
||||
'images': data.images,
|
||||
'contact': data.contact,
|
||||
'feedback_type': data.feedback_type,
|
||||
'handle_status': 0, # 待处理
|
||||
'status': 1, # 启用
|
||||
'is_deleted': 0,
|
||||
}
|
||||
|
||||
obj = await YifanFeedbackCRUD(auth).create(data=create_data)
|
||||
|
||||
return {
|
||||
'id': obj.id,
|
||||
'feedback_type': obj.feedback_type,
|
||||
'created_time': str(obj.created_time),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
async def detail_yifan_feedback_service(cls, auth: AuthSchema, id: int) -> dict:
|
||||
"""详情"""
|
||||
obj = await YifanFeedbackCRUD(auth).get_by_id_yifan_feedback_crud(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg="该数据不存在")
|
||||
return YifanFeedbackOutSchema.model_validate(obj).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def list_yifan_feedback_service(cls, auth: AuthSchema, search: YifanFeedbackQueryParam | None = None, order_by: list[dict] | None = None) -> list[dict]:
|
||||
"""列表查询"""
|
||||
search_dict = search.__dict__ if search else None
|
||||
obj_list = await YifanFeedbackCRUD(auth).list_yifan_feedback_crud(search=search_dict, order_by=order_by)
|
||||
return [YifanFeedbackOutSchema.model_validate(obj).model_dump() for obj in obj_list]
|
||||
|
||||
@classmethod
|
||||
async def page_yifan_feedback_service(cls, auth: AuthSchema, page_no: int, page_size: int, search: YifanFeedbackQueryParam | None = None, order_by: list[dict] | None = None) -> dict:
|
||||
"""分页查询(数据库分页)"""
|
||||
search_dict = search.__dict__ if search else {}
|
||||
order_by_list = order_by or [{'id': 'asc'}]
|
||||
offset = (page_no - 1) * page_size
|
||||
result = await YifanFeedbackCRUD(auth).page_yifan_feedback_crud(
|
||||
offset=offset,
|
||||
limit=page_size,
|
||||
order_by=order_by_list,
|
||||
search=search_dict
|
||||
)
|
||||
return result
|
||||
|
||||
@classmethod
|
||||
async def create_yifan_feedback_service(cls, auth: AuthSchema, data: YifanFeedbackCreateSchema) -> dict:
|
||||
"""创建"""
|
||||
# 检查唯一性约束
|
||||
obj = await YifanFeedbackCRUD(auth).create_yifan_feedback_crud(data=data)
|
||||
return YifanFeedbackOutSchema.model_validate(obj).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def update_yifan_feedback_service(cls, auth: AuthSchema, id: int, data: YifanFeedbackUpdateSchema) -> dict:
|
||||
"""更新"""
|
||||
# 检查数据是否存在
|
||||
obj = await YifanFeedbackCRUD(auth).get_by_id_yifan_feedback_crud(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg='更新失败,该数据不存在')
|
||||
|
||||
# 检查唯一性约束
|
||||
|
||||
obj = await YifanFeedbackCRUD(auth).update_yifan_feedback_crud(id=id, data=data)
|
||||
return YifanFeedbackOutSchema.model_validate(obj).model_dump()
|
||||
|
||||
@classmethod
|
||||
async def delete_yifan_feedback_service(cls, auth: AuthSchema, ids: list[int]) -> None:
|
||||
"""删除"""
|
||||
if len(ids) < 1:
|
||||
raise CustomException(msg='删除失败,删除对象不能为空')
|
||||
for id in ids:
|
||||
obj = await YifanFeedbackCRUD(auth).get_by_id_yifan_feedback_crud(id=id)
|
||||
if not obj:
|
||||
raise CustomException(msg=f'删除失败,ID为{id}的数据不存在')
|
||||
await YifanFeedbackCRUD(auth).delete_yifan_feedback_crud(ids=ids)
|
||||
|
||||
@classmethod
|
||||
async def set_available_yifan_feedback_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
|
||||
"""批量设置状态"""
|
||||
await YifanFeedbackCRUD(auth).set_available_yifan_feedback_crud(ids=data.ids, status=data.status)
|
||||
|
||||
@classmethod
|
||||
async def batch_export_yifan_feedback_service(cls, obj_list: list[dict]) -> bytes:
|
||||
"""批量导出"""
|
||||
mapping_dict = {
|
||||
'id': '主键ID',
|
||||
'created_time': '创建时间',
|
||||
'updated_time': '更新时间',
|
||||
'created_id': '创建人ID',
|
||||
'updated_id': '更新人ID',
|
||||
'is_deleted': '是否删除(0否 1是)',
|
||||
'status': '状态(0禁用 1启用)',
|
||||
'user_id': '用户ID',
|
||||
'content': '反馈内容',
|
||||
'images': '图片URL(多个用逗号分隔)',
|
||||
'contact': '联系方式',
|
||||
'feedback_type': '反馈类型(suggestion:建议 bug:问题 complaint:投诉 other:其他)',
|
||||
'handle_status': '处理状态(0待处理 1处理中 2已处理 3已关闭)',
|
||||
'handle_result': '处理结果',
|
||||
'handle_time': '处理时间',
|
||||
'handler_id': '处理人ID',
|
||||
'remark': '备注',
|
||||
'updated_id': '更新者ID',
|
||||
}
|
||||
|
||||
data = obj_list.copy()
|
||||
for item in data:
|
||||
# 状态转换
|
||||
if 'status' in item:
|
||||
item['status'] = '启用' if item.get('status') == '0' else '停用'
|
||||
# 创建者转换
|
||||
creator_info = item.get('creator')
|
||||
if isinstance(creator_info, dict):
|
||||
item['creator'] = creator_info.get('name', '未知')
|
||||
elif creator_info is None:
|
||||
item['creator'] = '未知'
|
||||
|
||||
return ExcelUtil.export_list2excel(list_data=data, mapping_dict=mapping_dict)
|
||||
|
||||
@classmethod
|
||||
async def batch_import_yifan_feedback_service(cls, auth: AuthSchema, file: UploadFile, update_support: bool = False) -> str:
|
||||
"""批量导入"""
|
||||
header_dict = {
|
||||
'主键ID': 'id',
|
||||
'创建时间': 'created_time',
|
||||
'更新时间': 'updated_time',
|
||||
'创建人ID': 'created_id',
|
||||
'更新人ID': 'updated_id',
|
||||
'是否删除(0否 1是)': 'is_deleted',
|
||||
'状态(0禁用 1启用)': 'status',
|
||||
'用户ID': 'user_id',
|
||||
'反馈内容': 'content',
|
||||
'图片URL(多个用逗号分隔)': 'images',
|
||||
'联系方式': 'contact',
|
||||
'反馈类型(suggestion:建议 bug:问题 complaint:投诉 other:其他)': 'feedback_type',
|
||||
'处理状态(0待处理 1处理中 2已处理 3已关闭)': 'handle_status',
|
||||
'处理结果': 'handle_result',
|
||||
'处理时间': 'handle_time',
|
||||
'处理人ID': 'handler_id',
|
||||
'备注': 'remark',
|
||||
}
|
||||
|
||||
try:
|
||||
contents = await file.read()
|
||||
df = pd.read_excel(io.BytesIO(contents))
|
||||
await file.close()
|
||||
|
||||
if df.empty:
|
||||
raise CustomException(msg="导入文件为空")
|
||||
|
||||
missing_headers = [header for header in header_dict.keys() if header not in df.columns]
|
||||
if missing_headers:
|
||||
raise CustomException(msg=f"导入文件缺少必要的列: {', '.join(missing_headers)}")
|
||||
|
||||
df.rename(columns=header_dict, inplace=True)
|
||||
|
||||
# 验证必填字段
|
||||
|
||||
error_msgs = []
|
||||
success_count = 0
|
||||
count = 0
|
||||
|
||||
for index, row in df.iterrows():
|
||||
count += 1
|
||||
try:
|
||||
data = {
|
||||
"id": row['id'],
|
||||
"created_time": row['created_time'],
|
||||
"updated_time": row['updated_time'],
|
||||
"created_id": row['created_id'],
|
||||
"updated_id": row['updated_id'],
|
||||
"is_deleted": row['is_deleted'],
|
||||
"status": row['status'],
|
||||
"user_id": row['user_id'],
|
||||
"content": row['content'],
|
||||
"images": row['images'],
|
||||
"contact": row['contact'],
|
||||
"feedback_type": row['feedback_type'],
|
||||
"handle_status": row['handle_status'],
|
||||
"handle_result": row['handle_result'],
|
||||
"handle_time": row['handle_time'],
|
||||
"handler_id": row['handler_id'],
|
||||
"remark": row['remark'],
|
||||
}
|
||||
# 使用CreateSchema做校验后入库
|
||||
create_schema = YifanFeedbackCreateSchema.model_validate(data)
|
||||
|
||||
# 检查唯一性约束
|
||||
|
||||
await YifanFeedbackCRUD(auth).create_yifan_feedback_crud(data=create_schema)
|
||||
success_count += 1
|
||||
except Exception as e:
|
||||
error_msgs.append(f"第{count}行: {str(e)}")
|
||||
continue
|
||||
|
||||
result = f"成功导入 {success_count} 条数据"
|
||||
if error_msgs:
|
||||
result += "\n错误信息:\n" + "\n".join(error_msgs)
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
log.error(f"批量导入失败: {str(e)}")
|
||||
raise CustomException(msg=f"导入失败: {str(e)}")
|
||||
|
||||
@classmethod
|
||||
async def import_template_download_yifan_feedback_service(cls) -> bytes:
|
||||
"""下载导入模板"""
|
||||
header_list = [
|
||||
'主键ID',
|
||||
'创建时间',
|
||||
'更新时间',
|
||||
'创建人ID',
|
||||
'更新人ID',
|
||||
'是否删除(0否 1是)',
|
||||
'状态(0禁用 1启用)',
|
||||
'用户ID',
|
||||
'反馈内容',
|
||||
'图片URL(多个用逗号分隔)',
|
||||
'联系方式',
|
||||
'反馈类型(suggestion:建议 bug:问题 complaint:投诉 other:其他)',
|
||||
'处理状态(0待处理 1处理中 2已处理 3已关闭)',
|
||||
'处理结果',
|
||||
'处理时间',
|
||||
'处理人ID',
|
||||
'备注',
|
||||
]
|
||||
selector_header_list = []
|
||||
option_list = []
|
||||
|
||||
# 添加下拉选项
|
||||
|
||||
return ExcelUtil.get_excel_template(
|
||||
header_list=header_list,
|
||||
selector_header_list=selector_header_list,
|
||||
option_list=option_list
|
||||
)
|
||||
Reference in New Issue
Block a user