File size: 12,890 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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional

from database import get_db
from models.company_r2_config import CompanyR2Config
from models.company import Company
from models.user import User
from schemas.product import (
    CompanyR2ConfigResponse, CompanyR2ConfigCreate, CompanyR2ConfigUpdate
)
from routers.auth import get_current_user, is_admin_user
from utils.r2_uploader import set_cached_config, clear_cached_config, R2Config

router = APIRouter()


def verify_superadmin(current_user: User):
    """验证用户是否为超级管理员或admin用户"""
    if not current_user.is_superadmin and not is_admin_user(current_user):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only superadmin can access this endpoint"
        )


@router.get("/all", response_model=List[CompanyR2ConfigResponse])
async def get_all_r2_configs(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取所有公司的 R2 配置(仅超管)"""
    verify_superadmin(current_user)
    configs = db.query(CompanyR2Config).all()
    
    result = []
    for config in configs:
        company = db.query(Company).filter(
            Company.company_code == config.company_code
        ).first()
        config_dict = {
            'id': config.id,
            'company_code': config.company_code,
            'company_name': company.name if company else None,
            'r2_account_id': config.r2_account_id,
            'r2_access_key_id': config.r2_access_key_id,
            'r2_secret_access_key': config.r2_secret_access_key,
            'r2_bucket_name': config.r2_bucket_name,
            'r2_public_url': config.r2_public_url,
            'r2_enabled': config.r2_enabled,
            'created_at': config.created_at,
            'updated_at': config.updated_at
        }
        result.append(config_dict)
    
    return result


@router.get("/config/{company_code}", response_model=Optional[CompanyR2ConfigResponse])
async def get_r2_config_by_company(
    company_code: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取指定公司的 R2 配置(仅超管)"""
    verify_superadmin(current_user)
    config = db.query(CompanyR2Config).filter(
        CompanyR2Config.company_code == company_code
    ).first()
    
    if config:
        r2_config = R2Config({
            'r2_account_id': config.r2_account_id,
            'r2_access_key_id': config.r2_access_key_id,
            'r2_secret_access_key': config.r2_secret_access_key,
            'r2_bucket_name': config.r2_bucket_name,
            'r2_public_url': config.r2_public_url,
            'r2_enabled': config.r2_enabled
        })
        set_cached_config(company_code, r2_config)
        
        company = db.query(Company).filter(
            Company.company_code == config.company_code
        ).first()
        config_dict = {
            'id': config.id,
            'company_code': config.company_code,
            'company_name': company.name if company else None,
            'r2_account_id': config.r2_account_id,
            'r2_access_key_id': config.r2_access_key_id,
            'r2_secret_access_key': config.r2_secret_access_key,
            'r2_bucket_name': config.r2_bucket_name,
            'r2_public_url': config.r2_public_url,
            'r2_enabled': config.r2_enabled,
            'created_at': config.created_at,
            'updated_at': config.updated_at
        }
        return config_dict
    
    return config


@router.post("/config/{company_code}", response_model=CompanyR2ConfigResponse, status_code=status.HTTP_201_CREATED)
async def create_r2_config_for_company(
    company_code: str,
    config_data: CompanyR2ConfigCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """为指定公司创建或更新 R2 配置(仅超管)"""
    verify_superadmin(current_user)
    
    existing_config = db.query(CompanyR2Config).filter(
        CompanyR2Config.company_code == company_code
    ).first()
    
    if existing_config:
        update_data = config_data.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(existing_config, field, value)
        db.commit()
        db.refresh(existing_config)
        config = existing_config
    else:
        config_dict = config_data.model_dump()
        config_dict['company_code'] = company_code
        config = CompanyR2Config(**config_dict)
        db.add(config)
        db.commit()
        db.refresh(config)
    
    clear_cached_config(company_code)
    r2_config = R2Config({
        'r2_account_id': config.r2_account_id,
        'r2_access_key_id': config.r2_access_key_id,
        'r2_secret_access_key': config.r2_secret_access_key,
        'r2_bucket_name': config.r2_bucket_name,
        'r2_public_url': config.r2_public_url,
        'r2_enabled': config.r2_enabled
    })
    set_cached_config(company_code, r2_config)
    
    company = db.query(Company).filter(
        Company.company_code == config.company_code
    ).first()
    config_dict = {
        'id': config.id,
        'company_code': config.company_code,
        'company_name': company.name if company else None,
        'r2_account_id': config.r2_account_id,
        'r2_access_key_id': config.r2_access_key_id,
        'r2_secret_access_key': config.r2_secret_access_key,
        'r2_bucket_name': config.r2_bucket_name,
        'r2_public_url': config.r2_public_url,
        'r2_enabled': config.r2_enabled,
        'created_at': config.created_at,
        'updated_at': config.updated_at
    }
    return config_dict


@router.put("/config/{company_code}", response_model=CompanyR2ConfigResponse)
async def update_r2_config_for_company(
    company_code: str,
    config_update: CompanyR2ConfigUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新指定公司的 R2 配置(仅超管)"""
    verify_superadmin(current_user)
    
    config = db.query(CompanyR2Config).filter(
        CompanyR2Config.company_code == company_code
    ).first()
    
    if config is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="R2 config not found"
        )
    
    update_data = config_update.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(config, field, value)
    
    db.commit()
    db.refresh(config)
    
    clear_cached_config(company_code)
    r2_config = R2Config({
        'r2_account_id': config.r2_account_id,
        'r2_access_key_id': config.r2_access_key_id,
        'r2_secret_access_key': config.r2_secret_access_key,
        'r2_bucket_name': config.r2_bucket_name,
        'r2_public_url': config.r2_public_url,
        'r2_enabled': config.r2_enabled
    })
    set_cached_config(company_code, r2_config)
    
    company = db.query(Company).filter(
        Company.company_code == config.company_code
    ).first()
    config_dict = {
        'id': config.id,
        'company_code': config.company_code,
        'company_name': company.name if company else None,
        'r2_account_id': config.r2_account_id,
        'r2_access_key_id': config.r2_access_key_id,
        'r2_secret_access_key': config.r2_secret_access_key,
        'r2_bucket_name': config.r2_bucket_name,
        'r2_public_url': config.r2_public_url,
        'r2_enabled': config.r2_enabled,
        'created_at': config.created_at,
        'updated_at': config.updated_at
    }
    return config_dict


@router.delete("/config/{company_code}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_r2_config_for_company(
    company_code: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除指定公司的 R2 配置(仅超管)"""
    verify_superadmin(current_user)
    
    config = db.query(CompanyR2Config).filter(
        CompanyR2Config.company_code == company_code
    ).first()
    
    if config is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="R2 config not found"
        )
    
    db.delete(config)
    db.commit()
    
    clear_cached_config(company_code)
    
    return None


@router.get("/config", response_model=Optional[CompanyR2ConfigResponse])
async def get_company_r2_config(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取当前公司的 R2 配置"""
    config = db.query(CompanyR2Config).filter(
        CompanyR2Config.company_code == current_user.company_code
    ).first()
    
    if config:
        r2_config = R2Config({
            'r2_account_id': config.r2_account_id,
            'r2_access_key_id': config.r2_access_key_id,
            'r2_secret_access_key': config.r2_secret_access_key,
            'r2_bucket_name': config.r2_bucket_name,
            'r2_public_url': config.r2_public_url,
            'r2_enabled': config.r2_enabled
        })
        set_cached_config(current_user.company_code, r2_config)
    
    return config


@router.post("/config", response_model=CompanyR2ConfigResponse, status_code=status.HTTP_201_CREATED)
async def create_company_r2_config(
    config_data: CompanyR2ConfigCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建或更新当前公司的 R2 配置"""
    existing_config = db.query(CompanyR2Config).filter(
        CompanyR2Config.company_code == current_user.company_code
    ).first()
    
    if existing_config:
        update_data = config_data.model_dump(exclude_unset=True)
        for field, value in update_data.items():
            setattr(existing_config, field, value)
        db.commit()
        db.refresh(existing_config)
        config = existing_config
    else:
        config_dict = config_data.model_dump()
        config_dict['company_code'] = current_user.company_code
        config = CompanyR2Config(**config_dict)
        db.add(config)
        db.commit()
        db.refresh(config)
    
    clear_cached_config(current_user.company_code)
    r2_config = R2Config({
        'r2_account_id': config.r2_account_id,
        'r2_access_key_id': config.r2_access_key_id,
        'r2_secret_access_key': config.r2_secret_access_key,
        'r2_bucket_name': config.r2_bucket_name,
        'r2_public_url': config.r2_public_url,
        'r2_enabled': config.r2_enabled
    })
    set_cached_config(current_user.company_code, r2_config)
    
    return config


@router.put("/config", response_model=CompanyR2ConfigResponse)
async def update_company_r2_config(
    config_update: CompanyR2ConfigUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新当前公司的 R2 配置"""
    config = db.query(CompanyR2Config).filter(
        CompanyR2Config.company_code == current_user.company_code
    ).first()
    
    if config is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="R2 config not found"
        )
    
    update_data = config_update.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(config, field, value)
    
    db.commit()
    db.refresh(config)
    
    clear_cached_config(current_user.company_code)
    r2_config = R2Config({
        'r2_account_id': config.r2_account_id,
        'r2_access_key_id': config.r2_access_key_id,
        'r2_secret_access_key': config.r2_secret_access_key,
        'r2_bucket_name': config.r2_bucket_name,
        'r2_public_url': config.r2_public_url,
        'r2_enabled': config.r2_enabled
    })
    set_cached_config(current_user.company_code, r2_config)
    
    return config


@router.delete("/config", status_code=status.HTTP_204_NO_CONTENT)
async def delete_company_r2_config(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除当前公司的 R2 配置"""
    config = db.query(CompanyR2Config).filter(
        CompanyR2Config.company_code == current_user.company_code
    ).first()
    
    if config is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="R2 config not found"
        )
    
    db.delete(config)
    db.commit()
    
    clear_cached_config(current_user.company_code)
    
    return None


@router.post("/config/clear-cache", status_code=status.HTTP_200_OK)
async def clear_r2_config_cache(
    current_user: User = Depends(get_current_user)
):
    """清除当前公司的 R2 配置缓存"""
    clear_cached_config(current_user.company_code)
    return {"message": "Cache cleared successfully"}