upload project source code

This commit is contained in:
2026-04-30 18:49:43 +08:00
commit 9b394ba682
2277 changed files with 660945 additions and 0 deletions

View File

@@ -0,0 +1 @@
# -*- coding: utf-8 -*-

View File

@@ -0,0 +1,153 @@
# -*- coding: utf-8 -*-
from fastapi import APIRouter, Depends, UploadFile, Body, Path, Query
from fastapi.responses import StreamingResponse, JSONResponse
from app.common.response import SuccessResponse, StreamResponse
from app.core.dependencies import AuthPermission, db_getter
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 YifanFaqService
from .schema import YifanFaqCreateSchema, YifanFaqUpdateSchema, YifanFaqQueryParam
YifanFaqRouter = APIRouter(prefix='/yifan_faq', tags=["常见问题模块"])
@YifanFaqRouter.get("/mini/grouped", summary="小程序-按分类获取常见问题", description="按分类分组返回常见问题列表,用于小程序展示")
async def get_faq_grouped_for_mini(
db: AsyncSession = Depends(db_getter)
) -> JSONResponse:
"""
小程序获取常见问题接口(按分类分组)
返回格式:
{
"data": [
{
"category": "general",
"category_name": "通用",
"items": [
{"id": 1, "question": "...", "answer": "..."},
...
]
},
...
]
}
"""
result = await YifanFaqService.get_faq_grouped_service(db=db)
return SuccessResponse(data=result, msg="获取成功")
@YifanFaqRouter.get("/detail/{id}", summary="获取常见问题详情", description="获取常见问题详情")
async def get_yifan_faq_detail_controller(
id: int = Path(..., description="ID"),
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_faq:query"]))
) -> JSONResponse:
"""获取常见问题详情接口"""
result_dict = await YifanFaqService.detail_yifan_faq_service(auth=auth, id=id)
log.info(f"获取常见问题详情成功 {id}")
return SuccessResponse(data=result_dict, msg="获取常见问题详情成功")
@YifanFaqRouter.get("/list", summary="查询常见问题列表", description="查询常见问题列表")
async def get_yifan_faq_list_controller(
page: PaginationQueryParam = Depends(),
search: YifanFaqQueryParam = Depends(),
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_faq:query"]))
) -> JSONResponse:
"""查询常见问题列表接口(数据库分页)"""
result_dict = await YifanFaqService.page_yifan_faq_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="查询常见问题列表成功")
@YifanFaqRouter.post("/create", summary="创建常见问题", description="创建常见问题")
async def create_yifan_faq_controller(
data: YifanFaqCreateSchema,
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_faq:create"]))
) -> JSONResponse:
"""创建常见问题接口"""
result_dict = await YifanFaqService.create_yifan_faq_service(auth=auth, data=data)
log.info("创建常见问题成功")
return SuccessResponse(data=result_dict, msg="创建常见问题成功")
@YifanFaqRouter.put("/update/{id}", summary="修改常见问题", description="修改常见问题")
async def update_yifan_faq_controller(
data: YifanFaqUpdateSchema,
id: int = Path(..., description="ID"),
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_faq:update"]))
) -> JSONResponse:
"""修改常见问题接口"""
result_dict = await YifanFaqService.update_yifan_faq_service(auth=auth, id=id, data=data)
log.info("修改常见问题成功")
return SuccessResponse(data=result_dict, msg="修改常见问题成功")
@YifanFaqRouter.delete("/delete", summary="删除常见问题", description="删除常见问题")
async def delete_yifan_faq_controller(
ids: list[int] = Body(..., description="ID列表"),
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_faq:delete"]))
) -> JSONResponse:
"""删除常见问题接口"""
await YifanFaqService.delete_yifan_faq_service(auth=auth, ids=ids)
log.info(f"删除常见问题成功: {ids}")
return SuccessResponse(msg="删除常见问题成功")
@YifanFaqRouter.patch("/available/setting", summary="批量修改常见问题状态", description="批量修改常见问题状态")
async def batch_set_available_yifan_faq_controller(
data: BatchSetAvailable,
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_faq:patch"]))
) -> JSONResponse:
"""批量修改常见问题状态接口"""
await YifanFaqService.set_available_yifan_faq_service(auth=auth, data=data)
log.info(f"批量修改常见问题状态成功: {data.ids}")
return SuccessResponse(msg="批量修改常见问题状态成功")
@YifanFaqRouter.post('/export', summary="导出常见问题", description="导出常见问题")
async def export_yifan_faq_list_controller(
search: YifanFaqQueryParam = Depends(),
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_faq:export"]))
) -> StreamingResponse:
"""导出常见问题接口"""
result_dict_list = await YifanFaqService.list_yifan_faq_service(search=search, auth=auth)
export_result = await YifanFaqService.batch_export_yifan_faq_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_faq.xlsx'
}
)
@YifanFaqRouter.post('/import', summary="导入常见问题", description="导入常见问题")
async def import_yifan_faq_list_controller(
file: UploadFile,
auth: AuthSchema = Depends(AuthPermission(["module_yifan:yifan_faq:import"]))
) -> JSONResponse:
"""导入常见问题接口"""
batch_import_result = await YifanFaqService.batch_import_yifan_faq_service(file=file, auth=auth, update_support=True)
log.info("导入常见问题成功")
return SuccessResponse(data=batch_import_result, msg="导入常见问题成功")
@YifanFaqRouter.post('/download/template', summary="获取常见问题导入模板", description="获取常见问题导入模板", dependencies=[Depends(AuthPermission(["module_yifan:yifan_faq:download"]))])
async def export_yifan_faq_template_controller() -> StreamingResponse:
"""获取常见问题导入模板接口"""
import_template_result = await YifanFaqService.import_template_download_yifan_faq_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_faq_template.xlsx'}
)

View File

@@ -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 YifanFaqModel
from .schema import YifanFaqCreateSchema, YifanFaqUpdateSchema, YifanFaqOutSchema
class YifanFaqCRUD(CRUDBase[YifanFaqModel, YifanFaqCreateSchema, YifanFaqUpdateSchema]):
"""常见问题数据层"""
def __init__(self, auth: AuthSchema) -> None:
"""
初始化CRUD数据层
参数:
- auth (AuthSchema): 认证信息模型
"""
super().__init__(model=YifanFaqModel, auth=auth)
async def get_by_id_yifan_faq_crud(self, id: int, preload: list | None = None) -> YifanFaqModel | None:
"""
详情
参数:
- id (int): 对象ID
- preload (list | None): 预加载关系,未提供时使用模型默认项
返回:
- YifanFaqModel | None: 模型实例或None
"""
return await self.get(id=id, preload=preload)
async def list_yifan_faq_crud(self, search: dict | None = None, order_by: list[dict] | None = None, preload: list | None = None) -> Sequence[YifanFaqModel]:
"""
列表查询
参数:
- search (dict | None): 查询参数
- order_by (list[dict] | None): 排序参数,未提供时使用模型默认项
- preload (list | None): 预加载关系,未提供时使用模型默认项
返回:
- Sequence[YifanFaqModel]: 模型实例序列
"""
return await self.list(search=search, order_by=order_by, preload=preload)
async def create_yifan_faq_crud(self, data: YifanFaqCreateSchema) -> YifanFaqModel | None:
"""
创建
参数:
- data (YifanFaqCreateSchema): 创建模型
返回:
- YifanFaqModel | None: 模型实例或None
"""
return await self.create(data=data)
async def update_yifan_faq_crud(self, id: int, data: YifanFaqUpdateSchema) -> YifanFaqModel | None:
"""
更新
参数:
- id (int): 对象ID
- data (YifanFaqUpdateSchema): 更新模型
返回:
- YifanFaqModel | None: 模型实例或None
"""
return await self.update(id=id, data=data)
async def delete_yifan_faq_crud(self, ids: list[int]) -> None:
"""
批量删除
参数:
- ids (list[int]): 对象ID列表
返回:
- None
"""
return await self.delete(ids=ids)
async def set_available_yifan_faq_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_faq_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=YifanFaqOutSchema,
preload=preload
)

View File

@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
from sqlalchemy import Integer, DateTime, SmallInteger, Text, String
from sqlalchemy.orm import Mapped, mapped_column
from app.core.base_model import ModelMixin, UserMixin
class YifanFaqModel(ModelMixin, UserMixin):
"""
常见问题表
"""
__tablename__: str = 'yifan_faq'
__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是)')
question: Mapped[str | None] = mapped_column(String(500), nullable=True, comment='问题标题')
answer: Mapped[str | None] = mapped_column(Text, nullable=True, comment='答案内容')
category: Mapped[str | None] = mapped_column(String(32), nullable=True, comment='分类(general:通用 payment:支付 account:账户 service:服务 other:其他)')
sort_order: Mapped[int | None] = mapped_column(Integer, nullable=True, comment='排序(数值越小越靠前)')
view_count: Mapped[int | None] = mapped_column(Integer, nullable=True, comment='浏览次数')
is_hot: Mapped[int | None] = mapped_column(SmallInteger, nullable=True, comment='是否热门(0否 1是)')
remark: Mapped[str | None] = mapped_column(String(255), nullable=True, comment='备注')

View File

@@ -0,0 +1,85 @@
# -*- coding: utf-8 -*-
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 YifanFaqCreateSchema(BaseModel):
"""
常见问题新增模型
"""
is_deleted: int = Field(default=0, description='是否删除(0否 1是)')
status: int = Field(default=1, description='状态(0禁用 1启用)')
question: str = Field(default=..., description='问题标题')
answer: str = Field(default=..., description='答案内容')
category: str = Field(default='general', description='分类(general:通用 payment:支付 account:账户 service:服务 other:其他)')
sort_order: int = Field(default=0, description='排序(数值越小越靠前)')
view_count: int = Field(default=0, description='浏览次数')
is_hot: int = Field(default=0, description='是否热门(0否 1是)')
remark: str | None = Field(default=None, description='备注')
class YifanFaqUpdateSchema(YifanFaqCreateSchema):
"""
常见问题更新模型
"""
...
class YifanFaqOutSchema(YifanFaqCreateSchema, BaseSchema, UserBySchema):
"""
常见问题响应模型
"""
model_config = ConfigDict(from_attributes=True)
class YifanFaqQueryParam:
"""常见问题查询参数"""
def __init__(
self,
question: str | None = Query(None, description="问题标题"),
answer: str | None = Query(None, description="答案内容"),
category: str | None = Query(None, description="分类(general:通用 payment:支付 account:账户 service:服务 other:其他)"),
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启用)"),
sort_order: int | None = Query(None, description="排序(数值越小越靠前)"),
view_count: int | None = Query(None, description="浏览次数"),
is_hot: int | None = Query(None, description="是否热门(0否 1是)"),
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.question = ("like", question)
# 模糊查询字段
self.answer = ("like", answer)
# 模糊查询字段
self.category = ("like", category)
# 精确查询字段
self.sort_order = sort_order
# 精确查询字段
self.view_count = view_count
# 精确查询字段
self.is_hot = is_hot
# 模糊查询字段
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]))

View File

@@ -0,0 +1,292 @@
# -*- coding: utf-8 -*-
import io
from fastapi import UploadFile
import pandas as pd
from sqlalchemy import select
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 YifanFaqCreateSchema, YifanFaqUpdateSchema, YifanFaqOutSchema, YifanFaqQueryParam
from .crud import YifanFaqCRUD
from .model import YifanFaqModel
# 分类映射
CATEGORY_MAP = {
'general': '通用',
'payment': '支付',
'account': '账户',
'service': '服务',
'other': '其他',
}
# 分类排序
CATEGORY_ORDER = ['general', 'payment', 'account', 'service', 'other']
class YifanFaqService:
"""
常见问题服务层
"""
@classmethod
async def get_faq_grouped_service(cls, db: AsyncSession) -> list[dict]:
"""
按分类分组获取常见问题(小程序专用)
"""
# 查询所有启用的FAQ按分类和排序字段排序
stmt = (
select(YifanFaqModel)
.where(YifanFaqModel.status == '1')
.order_by(YifanFaqModel.category, YifanFaqModel.sort_order)
)
result = await db.execute(stmt)
faq_list = result.scalars().all()
# 按分类分组
grouped = {}
for faq in faq_list:
category = faq.category or 'other'
if category not in grouped:
grouped[category] = []
grouped[category].append({
'id': faq.id,
'question': faq.question,
'answer': faq.answer,
'is_hot': faq.is_hot,
})
# 按预定义顺序返回
result_list = []
for cat in CATEGORY_ORDER:
if cat in grouped:
result_list.append({
'category': cat,
'category_name': CATEGORY_MAP.get(cat, cat),
'items': grouped[cat]
})
# 添加未知分类
for cat, items in grouped.items():
if cat not in CATEGORY_ORDER:
result_list.append({
'category': cat,
'category_name': CATEGORY_MAP.get(cat, cat),
'items': items
})
return result_list
@classmethod
async def detail_yifan_faq_service(cls, auth: AuthSchema, id: int) -> dict:
"""详情"""
obj = await YifanFaqCRUD(auth).get_by_id_yifan_faq_crud(id=id)
if not obj:
raise CustomException(msg="该数据不存在")
return YifanFaqOutSchema.model_validate(obj).model_dump()
@classmethod
async def list_yifan_faq_service(cls, auth: AuthSchema, search: YifanFaqQueryParam | None = None, order_by: list[dict] | None = None) -> list[dict]:
"""列表查询"""
search_dict = search.__dict__ if search else None
obj_list = await YifanFaqCRUD(auth).list_yifan_faq_crud(search=search_dict, order_by=order_by)
return [YifanFaqOutSchema.model_validate(obj).model_dump() for obj in obj_list]
@classmethod
async def page_yifan_faq_service(cls, auth: AuthSchema, page_no: int, page_size: int, search: YifanFaqQueryParam | 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 YifanFaqCRUD(auth).page_yifan_faq_crud(
offset=offset,
limit=page_size,
order_by=order_by_list,
search=search_dict
)
return result
@classmethod
async def create_yifan_faq_service(cls, auth: AuthSchema, data: YifanFaqCreateSchema) -> dict:
"""创建"""
# 检查唯一性约束
obj = await YifanFaqCRUD(auth).create_yifan_faq_crud(data=data)
return YifanFaqOutSchema.model_validate(obj).model_dump()
@classmethod
async def update_yifan_faq_service(cls, auth: AuthSchema, id: int, data: YifanFaqUpdateSchema) -> dict:
"""更新"""
# 检查数据是否存在
obj = await YifanFaqCRUD(auth).get_by_id_yifan_faq_crud(id=id)
if not obj:
raise CustomException(msg='更新失败,该数据不存在')
# 检查唯一性约束
obj = await YifanFaqCRUD(auth).update_yifan_faq_crud(id=id, data=data)
return YifanFaqOutSchema.model_validate(obj).model_dump()
@classmethod
async def delete_yifan_faq_service(cls, auth: AuthSchema, ids: list[int]) -> None:
"""删除"""
if len(ids) < 1:
raise CustomException(msg='删除失败,删除对象不能为空')
for id in ids:
obj = await YifanFaqCRUD(auth).get_by_id_yifan_faq_crud(id=id)
if not obj:
raise CustomException(msg=f'删除失败ID为{id}的数据不存在')
await YifanFaqCRUD(auth).delete_yifan_faq_crud(ids=ids)
@classmethod
async def set_available_yifan_faq_service(cls, auth: AuthSchema, data: BatchSetAvailable) -> None:
"""批量设置状态"""
await YifanFaqCRUD(auth).set_available_yifan_faq_crud(ids=data.ids, status=data.status)
@classmethod
async def batch_export_yifan_faq_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启用)',
'question': '问题标题',
'answer': '答案内容',
'category': '分类(general:通用 payment:支付 account:账户 service:服务 other:其他)',
'sort_order': '排序(数值越小越靠前)',
'view_count': '浏览次数',
'is_hot': '是否热门(0否 1是)',
'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_faq_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',
'问题标题': 'question',
'答案内容': 'answer',
'分类(general:通用 payment:支付 account:账户 service:服务 other:其他)': 'category',
'排序(数值越小越靠前)': 'sort_order',
'浏览次数': 'view_count',
'是否热门(0否 1是)': 'is_hot',
'备注': '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'],
"question": row['question'],
"answer": row['answer'],
"category": row['category'],
"sort_order": row['sort_order'],
"view_count": row['view_count'],
"is_hot": row['is_hot'],
"remark": row['remark'],
}
# 使用CreateSchema做校验后入库
create_schema = YifanFaqCreateSchema.model_validate(data)
# 检查唯一性约束
await YifanFaqCRUD(auth).create_yifan_faq_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_faq_service(cls) -> bytes:
"""下载导入模板"""
header_list = [
'主键ID',
'创建时间',
'更新时间',
'创建人ID',
'更新人ID',
'是否删除(0否 1是)',
'状态(0禁用 1启用)',
'问题标题',
'答案内容',
'分类(general:通用 payment:支付 account:账户 service:服务 other:其他)',
'排序(数值越小越靠前)',
'浏览次数',
'是否热门(0否 1是)',
'备注',
]
selector_header_list = []
option_list = []
# 添加下拉选项
return ExcelUtil.get_excel_template(
header_list=header_list,
selector_header_list=selector_header_list,
option_list=option_list
)