File size: 11,993 Bytes
551658a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from sqlalchemy import func
from typing import List, Optional
import json

from database import get_db
from models.template import Template
from models.company import Company
from models.user import User
from schemas.template import TemplateResponse, TemplateCreate, TemplateUpdate, TemplateStatusUpdate
from routers.auth import get_current_user, get_current_superadmin
from routers.operation_log import create_operation_log

router = APIRouter()

# 获取模板列表
@router.get("/", response_model=List[TemplateResponse])
async def get_templates(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    # 普通用户只能看到可用的模板,超级管理员可以看到所有模板
    if current_user.is_superadmin:
        templates = db.query(Template).all()
    else:
        templates = db.query(Template).filter(Template.status == 1).all()
    
    # 转换features和regions字段从JSON字符串到列表
    result = []
    for template in templates:
        template_dict = {
            'id': template.id,
            'key': template.key,
            'name': template.name,
            'description': template.description,
            'color': template.color,
            'features': [],
            'applicable_scene': template.applicable_scene,
            'regions': [],
            'select_count': template.select_count or 0,
            'use_count': template.use_count or 0,
            'status': template.status or 0,
            'created_at': template.created_at,
            'updated_at': template.updated_at
        }
        
        if template.features:
            try:
                template_dict['features'] = json.loads(template.features)
            except:
                template_dict['features'] = []
        
        if template.regions:
            try:
                template_dict['regions'] = json.loads(template.regions)
            except:
                template_dict['regions'] = []
        
        result.append(template_dict)
    
    return result

# 通过模板key获取模板信息
@router.get("/{template_key}", response_model=TemplateResponse)
async def get_template_by_key(
    template_key: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    template = db.query(Template).filter(Template.key == template_key).first()
    if template is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Template with key '{template_key}' not found"
        )
    
    # 构造响应数据
    template_dict = {
        'id': template.id,
        'key': template.key,
        'name': template.name,
        'description': template.description,
        'color': template.color,
        'features': [],
        'applicable_scene': template.applicable_scene,
        'regions': [],
        'select_count': template.select_count or 0,
        'use_count': template.use_count or 0,
        'status': template.status or 1,
        'created_at': template.created_at,
        'updated_at': template.updated_at
    }
    
    # 转换features和regions字段从JSON字符串到列表
    if template.features:
        try:
            template_dict['features'] = json.loads(template.features)
        except:
            template_dict['features'] = []
    
    if template.regions:
        try:
            template_dict['regions'] = json.loads(template.regions)
        except:
            template_dict['regions'] = []
    
    return template_dict

# 创建模板(仅超级管理员可操作)
@router.post("/", response_model=TemplateResponse)
async def create_template(
    template: TemplateCreate,
    current_user: User = Depends(get_current_superadmin),
    db: Session = Depends(get_db)
):
    # 检查模板key是否已存在
    existing_template = db.query(Template).filter(Template.key == template.key).first()
    if existing_template:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Template with key '{template.key}' already exists"
        )
    
    # 转换features和regions列表为JSON字符串
    template_data = template.model_dump()
    if template_data.get('features'):
        template_data['features'] = json.dumps(template_data['features'], ensure_ascii=False)
    if template_data.get('regions'):
        template_data['regions'] = json.dumps(template_data['regions'], ensure_ascii=False)
    
    db_template = Template(**template_data)
    db.add(db_template)
    db.commit()
    db.refresh(db_template)
    
    # 记录操作日志
    create_operation_log(
        db=db,
        user=current_user,
        module="template",
        operation_type="add",
        operation_detail=f"新增模板:{db_template.name}(key:{db_template.key})",
        company_code=current_user.company_code
    )
    
    # 转换features和regions字段从JSON字符串到列表
    if db_template.features:
        try:
            db_template.features = json.loads(db_template.features)
        except:
            db_template.features = []
    if db_template.regions:
        try:
            db_template.regions = json.loads(db_template.regions)
        except:
            db_template.regions = []
    
    return db_template

# 更新模板(仅超级管理员可操作)
@router.put("/{template_key}", response_model=TemplateResponse)
async def update_template(
    template_key: str,
    template_update: TemplateUpdate,
    current_user: User = Depends(get_current_superadmin),
    db: Session = Depends(get_db)
):
    template = db.query(Template).filter(Template.key == template_key).first()
    if template is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Template with key '{template_key}' not found"
        )
    
    # 记录修改前的数据
    before_data_dict = {
        "name": template.name,
        "description": template.description,
        "color": template.color,
        "features": template.features,
        "applicable_scene": template.applicable_scene,
        "regions": template.regions
    }
    
    # 更新模板信息
    update_data = template_update.model_dump(exclude_unset=True)
    if 'features' in update_data:
        update_data['features'] = json.dumps(update_data['features'], ensure_ascii=False)
    if 'regions' in update_data:
        update_data['regions'] = json.dumps(update_data['regions'], ensure_ascii=False)
    
    for field, value in update_data.items():
        setattr(template, field, value)
    
    db.commit()
    db.refresh(template)
    
    # 记录修改后的数据
    after_data_dict = {
        "name": template.name,
        "description": template.description,
        "color": template.color,
        "features": template.features,
        "applicable_scene": template.applicable_scene,
        "regions": template.regions
    }
    
    # 只记录有修改的字段,使用中文解析
    modified_fields = []
    field_names = {
        "name": "模板名称",
        "description": "模板描述",
        "color": "模板主色调",
        "features": "模板特性",
        "applicable_scene": "适用场景",
        "regions": "适用区域"
    }
    
    for field, chinese_name in field_names.items():
        if before_data_dict[field] != after_data_dict[field]:
            modified_fields.append(f"{chinese_name}{before_data_dict[field]}{after_data_dict[field]}")
    
    # 生成中文描述的修改内容
    if modified_fields:
        modification_detail = ";".join(modified_fields)
    else:
        modification_detail = "无字段修改"
    
    # 记录操作日志
    create_operation_log(
        db=db,
        user=current_user,
        module="template",
        operation_type="edit",
        operation_detail=f"编辑模板:{template.name}(key:{template.key})",
        before_data=modification_detail,
        after_data=None,
        company_code=current_user.company_code
    )
    
    # 转换features和regions字段从JSON字符串到列表
    if template.features:
        try:
            template.features = json.loads(template.features)
        except:
            template.features = []
    if template.regions:
        try:
            template.regions = json.loads(template.regions)
        except:
            template.regions = []
    
    return template

# 删除模板(仅超级管理员可操作)
@router.delete("/{template_key}")
async def delete_template(
    template_key: str,
    current_user: User = Depends(get_current_superadmin),
    db: Session = Depends(get_db)
):
    template = db.query(Template).filter(Template.key == template_key).first()
    if template is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Template with key '{template_key}' not found"
        )
    
    # 记录模板名称和key,用于日志
    template_name = template.name
    template_key = template.key
    
    db.delete(template)
    db.commit()
    
    # 记录操作日志
    create_operation_log(
        db=db,
        user=current_user,
        module="template",
        operation_type="delete",
        operation_detail=f"删除模板:{template_name}(key:{template_key})",
        company_code=current_user.company_code
    )
    
    return {"message": f"Template with key '{template_key}' deleted successfully"}


# 设置模板状态(仅超级管理员可操作)
@router.put("/{template_key}/status", response_model=TemplateResponse)
async def update_template_status(
    template_key: str,
    status_update: TemplateStatusUpdate,
    current_user: User = Depends(get_current_superadmin),
    db: Session = Depends(get_db)
):
    template = db.query(Template).filter(Template.key == template_key).first()
    if template is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Template with key '{template_key}' not found"
        )
    
    # 验证状态值
    if status_update.status not in [0, 1]:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Status must be 0 (unavailable) or 1 (available)"
        )
    
    # 记录修改前的状态
    old_status = template.status
    
    # 更新状态
    template.status = status_update.status
    db.commit()
    db.refresh(template)
    
    # 记录操作日志
    status_text = {0: "不可用", 1: "可用"}
    create_operation_log(
        db=db,
        user=current_user,
        module="template",
        operation_type="edit",
        operation_detail=f"设置模板状态:{template.name}(key:{template.key}),状态:{status_text.get(old_status, '未知')}{status_text.get(status_update.status, '未知')}",
        company_code=current_user.company_code
    )
    
    # 构造响应数据
    template_dict = {
        'id': template.id,
        'key': template.key,
        'name': template.name,
        'description': template.description,
        'color': template.color,
        'features': [],
        'applicable_scene': template.applicable_scene,
        'regions': [],
        'select_count': template.select_count or 0,
        'use_count': template.use_count or 0,
        'status': template.status or 1,
        'created_at': template.created_at,
        'updated_at': template.updated_at
    }
    
    # 转换features和regions字段从JSON字符串到列表
    if template.features:
        try:
            template_dict['features'] = json.loads(template.features)
        except:
            template_dict['features'] = []
    
    if template.regions:
        try:
            template_dict['regions'] = json.loads(template.regions)
        except:
            template_dict['regions'] = []
    
    return template_dict