账号添加备注

This commit is contained in:
zhinianboke 2025-08-05 14:04:16 +08:00
parent cf4f41b391
commit a87f1904c0
4 changed files with 222 additions and 7 deletions

View File

@ -113,6 +113,7 @@ class DBManager:
value TEXT NOT NULL,
user_id INTEGER NOT NULL,
auto_confirm INTEGER DEFAULT 1,
remark TEXT DEFAULT '',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
@ -372,6 +373,15 @@ class DBManager:
# 检查并更新CHECK约束重建表以支持image类型
self._update_cards_table_constraints(cursor)
# 检查cookies表是否存在remark列
cursor.execute("PRAGMA table_info(cookies)")
cookie_columns = [column[1] for column in cursor.fetchall()]
if 'remark' not in cookie_columns:
logger.info("添加cookies表的remark列...")
cursor.execute("ALTER TABLE cookies ADD COLUMN remark TEXT DEFAULT ''")
logger.info("数据库迁移完成添加remark列")
except Exception as e:
logger.error(f"数据库迁移失败: {e}")
# 迁移失败不应该阻止程序启动
@ -1077,11 +1087,11 @@ class DBManager:
return None
def get_cookie_details(self, cookie_id: str) -> Optional[Dict[str, any]]:
"""获取Cookie的详细信息包括user_id和auto_confirm"""
"""获取Cookie的详细信息包括user_id、auto_confirm和remark"""
with self.lock:
try:
cursor = self.conn.cursor()
self._execute_sql(cursor, "SELECT id, value, user_id, auto_confirm, created_at FROM cookies WHERE id = ?", (cookie_id,))
self._execute_sql(cursor, "SELECT id, value, user_id, auto_confirm, remark, created_at FROM cookies WHERE id = ?", (cookie_id,))
result = cursor.fetchone()
if result:
return {
@ -1089,7 +1099,8 @@ class DBManager:
'value': result[1],
'user_id': result[2],
'auto_confirm': bool(result[3]),
'created_at': result[4]
'remark': result[4] or '',
'created_at': result[5]
}
return None
except Exception as e:
@ -1109,6 +1120,19 @@ class DBManager:
logger.error(f"更新自动确认发货设置失败: {e}")
return False
def update_cookie_remark(self, cookie_id: str, remark: str) -> bool:
"""更新Cookie的备注"""
with self.lock:
try:
cursor = self.conn.cursor()
self._execute_sql(cursor, "UPDATE cookies SET remark = ? WHERE id = ?", (remark, cookie_id))
self.conn.commit()
logger.info(f"更新账号 {cookie_id} 备注: {remark}")
return True
except Exception as e:
logger.error(f"更新账号备注失败: {e}")
return False
def get_auto_confirm(self, cookie_id: str) -> bool:
"""获取Cookie的自动确认发货设置"""
with self.lock:

View File

@ -908,11 +908,16 @@ def get_cookies_details(current_user: Dict[str, Any] = Depends(get_current_user)
for cookie_id, cookie_value in user_cookies.items():
cookie_enabled = cookie_manager.manager.get_cookie_status(cookie_id)
auto_confirm = db_manager.get_auto_confirm(cookie_id)
# 获取备注信息
cookie_details = db_manager.get_cookie_details(cookie_id)
remark = cookie_details.get('remark', '') if cookie_details else ''
result.append({
'id': cookie_id,
'value': cookie_value,
'enabled': cookie_enabled,
'auto_confirm': auto_confirm
'auto_confirm': auto_confirm,
'remark': remark
})
return result
@ -1443,6 +1448,10 @@ class AutoConfirmUpdate(BaseModel):
auto_confirm: bool
class RemarkUpdate(BaseModel):
remark: str
@app.put("/cookies/{cid}/auto-confirm")
def update_auto_confirm(cid: str, update_data: AutoConfirmUpdate, current_user: Dict[str, Any] = Depends(get_current_user)):
"""更新账号的自动确认发货设置"""
@ -1503,6 +1512,65 @@ def get_auto_confirm(cid: str, current_user: Dict[str, Any] = Depends(get_curren
raise HTTPException(status_code=500, detail=str(e))
@app.put("/cookies/{cid}/remark")
def update_cookie_remark(cid: str, update_data: RemarkUpdate, current_user: Dict[str, Any] = Depends(get_current_user)):
"""更新账号备注"""
if cookie_manager.manager is None:
raise HTTPException(status_code=500, detail="CookieManager 未就绪")
try:
# 检查cookie是否属于当前用户
user_id = current_user['user_id']
from db_manager import db_manager
user_cookies = db_manager.get_all_cookies(user_id)
if cid not in user_cookies:
raise HTTPException(status_code=403, detail="无权限操作该Cookie")
# 更新备注
success = db_manager.update_cookie_remark(cid, update_data.remark)
if success:
log_with_user('info', f"更新账号备注: {cid} -> {update_data.remark}", current_user)
return {
"message": "备注更新成功",
"remark": update_data.remark
}
else:
raise HTTPException(status_code=500, detail="备注更新失败")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/cookies/{cid}/remark")
def get_cookie_remark(cid: str, current_user: Dict[str, Any] = Depends(get_current_user)):
"""获取账号备注"""
if cookie_manager.manager is None:
raise HTTPException(status_code=500, detail="CookieManager 未就绪")
try:
# 检查cookie是否属于当前用户
user_id = current_user['user_id']
from db_manager import db_manager
user_cookies = db_manager.get_all_cookies(user_id)
if cid not in user_cookies:
raise HTTPException(status_code=403, detail="无权限操作该Cookie")
# 获取Cookie详细信息包含备注
cookie_details = db_manager.get_cookie_details(cid)
if cookie_details:
return {
"remark": cookie_details.get('remark', ''),
"message": "获取备注成功"
}
else:
raise HTTPException(status_code=404, detail="账号不存在")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))

View File

@ -278,13 +278,14 @@
<thead>
<tr>
<th style="width: 10%">账号ID</th>
<th style="width: 18%">Cookie值</th>
<th style="width: 16%">Cookie值</th>
<th style="width: 8%">关键词</th>
<th style="width: 8%">状态</th>
<th style="width: 9%">默认回复</th>
<th style="width: 9%">AI回复</th>
<th style="width: 10%">自动确认发货</th>
<th style="width: 28%">操作</th>
<th style="width: 12%">备注</th>
<th style="width: 18%">操作</th>
</tr>
</thead>
<tbody></tbody>

View File

@ -1072,7 +1072,7 @@ async function loadCookies() {
if (cookieDetails.length === 0) {
tbody.innerHTML = `
<tr>
<td colspan="7" class="text-center py-4 text-muted empty-state">
<td colspan="9" class="text-center py-4 text-muted empty-state">
<i class="bi bi-inbox fs-1 d-block mb-3"></i>
<h5>暂无账号</h5>
<p class="mb-0">请添加新的闲鱼账号开始使用</p>
@ -1199,6 +1199,13 @@ async function loadCookies() {
</span>
</div>
</td>
<td class="align-middle">
<div class="remark-cell" data-cookie-id="${cookie.id}">
<span class="remark-display" onclick="editRemark('${cookie.id}', '${(cookie.remark || '').replace(/'/g, '&#39;')}')" title="点击编辑备注" style="cursor: pointer; color: #6c757d; font-size: 0.875rem;">
${cookie.remark || '<i class="bi bi-plus-circle text-muted"></i> 添加备注'}
</span>
</div>
</td>
<td class="align-middle">
<div class="btn-group" role="group">
<button class="btn btn-sm btn-outline-primary" onclick="editCookieInline('${cookie.id}', '${cookie.value}')" title="修改Cookie" ${!isEnabled ? 'disabled' : ''}>
@ -6351,3 +6358,118 @@ async function exportKeywords() {
toggleLoading(false);
}
}
// ==================== 备注管理功能 ====================
// 编辑备注
function editRemark(cookieId, currentRemark) {
console.log('editRemark called:', cookieId, currentRemark); // 调试信息
const remarkCell = document.querySelector(`[data-cookie-id="${cookieId}"] .remark-display`);
if (!remarkCell) {
console.log('remarkCell not found'); // 调试信息
return;
}
// 创建输入框
const input = document.createElement('input');
input.type = 'text';
input.className = 'form-control form-control-sm';
input.value = currentRemark || '';
input.placeholder = '请输入备注...';
input.style.fontSize = '0.875rem';
input.maxLength = 100; // 限制备注长度
// 保存原始内容和原始值
const originalContent = remarkCell.innerHTML;
const originalValue = currentRemark || '';
// 标记是否已经进行了编辑
let hasChanged = false;
let isProcessing = false; // 防止重复处理
// 替换为输入框
remarkCell.innerHTML = '';
remarkCell.appendChild(input);
// 监听输入变化
input.addEventListener('input', () => {
hasChanged = input.value.trim() !== originalValue;
});
// 保存函数
const saveRemark = async () => {
console.log('saveRemark called, isProcessing:', isProcessing, 'hasChanged:', hasChanged); // 调试信息
if (isProcessing) return; // 防止重复调用
const newRemark = input.value.trim();
console.log('newRemark:', newRemark, 'originalValue:', originalValue); // 调试信息
// 如果没有变化,直接恢复显示
if (!hasChanged || newRemark === originalValue) {
console.log('No changes detected, restoring original content'); // 调试信息
remarkCell.innerHTML = originalContent;
return;
}
isProcessing = true;
try {
const response = await fetch(`${apiBase}/cookies/${cookieId}/remark`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`
},
body: JSON.stringify({ remark: newRemark })
});
if (response.ok) {
// 更新显示
remarkCell.innerHTML = `
<span class="remark-display" onclick="editRemark('${cookieId}', '${newRemark.replace(/'/g, '&#39;')}')" title="点击编辑备注" style="cursor: pointer; color: #6c757d; font-size: 0.875rem;">
${newRemark || '<i class="bi bi-plus-circle text-muted"></i> 添加备注'}
</span>
`;
showToast('备注更新成功', 'success');
} else {
const errorData = await response.json();
showToast(`备注更新失败: ${errorData.detail || '未知错误'}`, 'danger');
// 恢复原始内容
remarkCell.innerHTML = originalContent;
}
} catch (error) {
console.error('更新备注失败:', error);
showToast('备注更新失败', 'danger');
// 恢复原始内容
remarkCell.innerHTML = originalContent;
} finally {
isProcessing = false;
}
};
// 取消函数
const cancelEdit = () => {
if (isProcessing) return;
remarkCell.innerHTML = originalContent;
};
// 延迟绑定blur事件避免立即触发
setTimeout(() => {
input.addEventListener('blur', saveRemark);
}, 100);
// 绑定键盘事件
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
saveRemark();
} else if (e.key === 'Escape') {
e.preventDefault();
cancelEdit();
}
});
// 聚焦并选中文本
input.focus();
input.select();
}