Compare commits

...

9 Commits

Author SHA1 Message Date
70b40cb90b feat: 新增阅读数功能
- 数据库添加 views 字段,兼容旧数据库自动添加
- API 新增 /api/items/<id>/view 接口增加阅读数
- 列表显示阅读数(👁图标)
- 详情页显示阅读数,点击详情时自动增加
2026-04-19 10:44:05 +08:00
22c32a9f3d fix: 编辑保存失败时显示错误提示;修复只修改标签时返回False的问题 2026-04-19 09:25:59 +08:00
c3791ce961 fix: 重点关注图标样式优化,只有五角星变实心,按钮保持outline样式 2026-04-19 09:03:44 +08:00
27e24e2a86 fix: 修复数据库初始化索引创建顺序 2026-04-19 00:13:35 +08:00
0864c99b75 feat: 新增重点关注功能
- 数据库新增 is_starred 字段,兼容旧数据库自动添加
- 所有类别数据支持一键设置/取消重点关注
- 侧边栏新增"重点关注"过滤选项,重点关注数据优先显示
- 新增数据时可直接勾选"设为重点关注"开关
- 编辑时可切换重点关注状态
- 卡片显示重点关注标记(星标图标)和特殊样式
- API新增 /api/items/<id>/star 接口用于切换重点关注状态
- 重点关注数据按创建时间倒序排列并优先显示
2026-04-19 00:11:24 +08:00
0c6057de28 feat: 内容统计信息显示(有效行数/总字数) 2026-04-17 10:51:58 +08:00
6f20e5978d fix: 分页正确显示当前筛选的总数
- API返回 total 字段(筛选后的实际总数)
- 新增 count_items 函数计算筛选条件下的总数
- 分页使用API返回的total而不是全局统计
- 解决筛选后分页显示不正确的问题
2026-04-16 14:08:12 +08:00
56ff1e8163 fix: 搜索输入实时响应修复
- 改用直接 setTimeout 方式,不用 debounce 函数
- 避免函数绑定问题导致搜索不触发
2026-04-16 14:03:05 +08:00
9ec479415a docs: 更新版本历史 v2.4.0 2026-04-16 13:55:07 +08:00
3 changed files with 335 additions and 33 deletions

View File

@@ -141,6 +141,13 @@ xian-favor/
## 版本历史
- **v2.4.0** (2026-04-16): 数据库备份机制
- 自动备份:每天 04:00 执行
- 手动备份:页面一键操作
- 备份清理规则保留30天 + 每月第一天永久保留
- 手动备份最多保留10个
- 支持恢复备份和删除备份
- 备份管理页面入口在侧边栏
- **v2.3.2** (2026-04-16): 搜索功能修复
- 修复 debounce 函数定义顺序问题
- 搜索框输入后可正常过滤列表

View File

@@ -17,15 +17,39 @@ CORS(app)
@app.route('/api/items', methods=['GET'])
def list_items():
"""列出条目"""
starred_param = request.args.get('starred')
starred = None
if starred_param == 'true' or starred_param == '1':
starred = True
elif starred_param == 'false' or starred_param == '0':
starred = False
items = db.list_items(
type=request.args.get('type'),
status=request.args.get('status'),
tag=request.args.get('tag'),
keyword=request.args.get('keyword'),
starred=starred,
sort_by=request.args.get('sort_by'),
sort_order=request.args.get('sort_order'),
limit=int(request.args.get('limit', 50)),
offset=int(request.args.get('offset', 0))
)
return jsonify({'success': True, 'data': items})
# 为每个条目添加内容统计
for item in items:
item['content_stats'] = calculate_content_stats(item)
# 获取符合条件的总数(用于分页)
total = db.count_items(
type=request.args.get('type'),
status=request.args.get('status'),
tag=request.args.get('tag'),
keyword=request.args.get('keyword'),
starred=starred
)
return jsonify({'success': True, 'data': items, 'total': total})
@app.route('/api/items', methods=['POST'])
@@ -51,7 +75,8 @@ def create_item():
priority=data.get('priority', 'medium'),
due_date=data.get('due_date'),
note=data.get('note'),
tags=data.get('tags', [])
tags=data.get('tags', []),
is_starred=data.get('is_starred', False)
)
item = db.get_item(item_id)
return jsonify({'success': True, 'data': item}), 201
@@ -68,9 +93,33 @@ def get_item(item_id):
# 获取邮件发送历史
email_logs = db.get_email_logs(item_id)
item['email_logs'] = email_logs
# 添加内容统计
item['content_stats'] = calculate_content_stats(item)
return jsonify({'success': True, 'data': item})
def calculate_content_stats(item):
"""计算内容统计:有效行数、总字数"""
# 合计所有文本内容
all_text = ''
if item.get('content'):
all_text += item['content'] + '\n'
if item.get('note'):
all_text += item['note'] + '\n'
if not all_text.strip():
return {'lines': 0, 'chars': 0}
# 有效行数(去除空行)
lines = [line for line in all_text.split('\n') if line.strip()]
line_count = len(lines)
# 总字数(去除空格后的字符数)
char_count = len(all_text.replace(' ', '').replace('\n', '').replace('\t', '').strip())
return {'lines': line_count, 'chars': char_count}
@app.route('/api/items/<int:item_id>', methods=['PUT'])
def update_item(item_id):
"""更新条目"""
@@ -97,6 +146,34 @@ def delete_item(item_id):
return jsonify({'success': False, 'error': '条目不存在'}), 404
@app.route('/api/items/<int:item_id>/star', methods=['POST'])
def toggle_star_item(item_id):
"""切换重点关注状态"""
if db.toggle_star(item_id):
item = db.get_item(item_id)
return jsonify({'success': True, 'data': item})
return jsonify({'success': False, 'error': '条目不存在'}), 404
@app.route('/api/items/<int:item_id>/star/<int:status>', methods=['POST'])
def set_star_item(item_id, status):
"""设置重点关注状态 (status: 1=重点关注, 0=取消重点关注)"""
starred = status == 1
if db.set_star(item_id, starred):
item = db.get_item(item_id)
return jsonify({'success': True, 'data': item})
return jsonify({'success': False, 'error': '条目不存在'}), 404
@app.route('/api/items/<int:item_id>/view', methods=['POST'])
def increment_views(item_id):
"""增加阅读数"""
if db.increment_views(item_id):
item = db.get_item(item_id)
return jsonify({'success': True, 'data': item})
return jsonify({'success': False, 'error': '条目不存在'}), 404
@app.route('/api/items/<int:item_id>/done', methods=['POST'])
def complete_item(item_id):
"""完成待办"""
@@ -587,6 +664,9 @@ INDEX_TEMPLATE = '''
.type-link { border-left: 4px solid #28a745; }
.type-column { border-left: 4px solid #6f42c1; }
.type-todo { border-left: 4px solid #ffc107; }
.is-starred { border-left: 4px solid #ffc107; background: #fffbe6; }
.is-starred:hover { background: #fff9e0; }
.star-btn { font-size: 11px; }
.status-pending { color: #ffc107; }
.status-in_progress { color: #17a2b8; }
.status-completed { color: #28a745; text-decoration: line-through; }
@@ -606,6 +686,7 @@ INDEX_TEMPLATE = '''
</div>
<nav>
<a href="#" class="active" data-filter="all"><i class="bi bi-inbox"></i> 全部</a>
<a href="#" data-filter="starred"><i class="bi bi-star-fill" style="color:#ffc107;"></i> 重点关注</a>
<a href="#" data-filter="text"><i class="bi bi-file-text"></i> 文本</a>
<a href="#" data-filter="link"><i class="bi bi-link-45deg"></i> 链接</a>
<a href="#" data-filter="column"><i class="bi bi-newspaper"></i> 专栏</a>
@@ -644,6 +725,15 @@ INDEX_TEMPLATE = '''
<option value="column">专栏</option>
<option value="todo">待办</option>
</select>
<select id="sortBy" class="form-select" style="width: 130px;" onchange="changeSort()">
<option value="">默认排序</option>
<option value="created_at">创建时间</option>
<option value="updated_at">更新时间</option>
</select>
<select id="sortOrder" class="form-select" style="width: 100px;" onchange="changeSort()">
<option value="desc">降序 ↓</option>
<option value="asc">升序 ↑</option>
</select>
</div>
<button class="btn btn-outline-info me-2" onclick="showAIAddModal()" title="AI自动添加">
<i class="bi bi-robot"></i> AI添加
@@ -775,6 +865,14 @@ INDEX_TEMPLATE = '''
<label class="form-label">详情/备注</label>
<textarea id="addNote" class="form-control" rows="5"></textarea>
</div>
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="addStarred">
<label class="form-check-label" for="addStarred">
<i class="bi bi-star-fill" style="color:#ffc107;"></i> 设为重点关注
</label>
</div>
</div>
</form>
</div>
<div class="modal-footer">
@@ -881,6 +979,14 @@ INDEX_TEMPLATE = '''
<label class="form-label">详情/备注</label>
<textarea id="editNote" class="form-control" rows="5"></textarea>
</div>
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="editStarred">
<label class="form-check-label" for="editStarred">
<i class="bi bi-star-fill" style="color:#ffc107;"></i> 重点关注
</label>
</div>
</div>
</form>
</div>
<div class="modal-footer">
@@ -1163,7 +1269,8 @@ INDEX_TEMPLATE = '''
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
const API_BASE = '/api';
let currentFilter = { type: '', status: '' };
let currentFilter = { type: '', status: '', starred: null };
let currentSort = { sort_by: '', sort_order: '' };
let currentPage = 1;
const pageSize = 20;
function debounce(fn, delay) {
@@ -1179,7 +1286,7 @@ document.addEventListener('DOMContentLoaded', async () => {
// 确保初始状态清空
document.getElementById('searchInput').value = '';
document.getElementById('typeFilter').value = '';
currentFilter = { type: '', status: '' };
currentFilter = { type: '', status: '', starred: null };
await loadStats(); // 先加载统计,确保总数可用
loadItems();
@@ -1201,8 +1308,12 @@ document.addEventListener('DOMContentLoaded', async () => {
updateEditFieldsByType(e.target.value);
});
// 搜索
document.getElementById('searchInput').addEventListener('input', debounce(loadItems, 300));
// 搜索 - 直接绑定,不用 debounce
let searchTimer;
document.getElementById('searchInput').addEventListener('input', (e) => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => loadItems(), 300);
});
// 类型过滤
document.getElementById('typeFilter').addEventListener('change', (e) => {
@@ -1218,12 +1329,14 @@ document.addEventListener('DOMContentLoaded', async () => {
a.classList.add('active');
const filter = a.dataset.filter;
if (['text', 'link', 'column', 'todo'].includes(filter)) {
currentFilter = { type: filter, status: '' };
if (filter === 'starred') {
currentFilter = { type: '', status: '', starred: true };
} else if (['text', 'link', 'column', 'todo'].includes(filter)) {
currentFilter = { type: filter, status: '', starred: null };
} else if (['pending', 'in_progress', 'completed'].includes(filter)) {
currentFilter = { type: 'todo', status: filter };
currentFilter = { type: 'todo', status: filter, starred: null };
} else {
currentFilter = { type: '', status: '' };
currentFilter = { type: '', status: '', starred: null };
}
loadItems();
});
@@ -1237,14 +1350,17 @@ async function loadItems(page = 1) {
let url = `${API_BASE}/items?limit=${pageSize}&offset=${(page-1)*pageSize}`;
if (currentFilter.type) url += `&type=${currentFilter.type}`;
if (currentFilter.status) url += `&status=${currentFilter.status}`;
if (currentFilter.starred !== null) url += `&starred=${currentFilter.starred ? 'true' : 'false'}`;
if (keyword) url += `&keyword=${encodeURIComponent(keyword)}`;
if (currentSort.sort_by) url += `&sort_by=${currentSort.sort_by}`;
if (currentSort.sort_order) url += `&sort_order=${currentSort.sort_order}`;
const res = await fetch(url);
const data = await res.json();
if (data.success) {
renderItems(data.data);
renderPagination(data.data.length, page);
renderPagination(data.total, page); // 使用API返回的total
}
}
@@ -1257,16 +1373,19 @@ function renderItems(items) {
}
container.innerHTML = items.map(item => `
<div class="card type-${item.type} item-card" style="cursor: pointer;" onclick="showDetail(${item.id})">
<div class="card type-${item.type} item-card ${item.is_starred ? 'is-starred' : ''}" style="cursor: pointer;" onclick="showDetail(${item.id})">
<div class="card-body">
<div class="d-flex justify-content-between align-items-start">
<div style="flex: 1; min-width: 0;">
<h6 class="card-title text-truncate mb-1 ${item.type === 'todo' && item.status === 'completed' ? 'text-muted' : ''}">
${getTypeIcon(item.type)} ${item.title || truncate(item.content || item.url, 30)}
${item.is_starred ? '<i class="bi bi-star-fill" style="color:#ffc107;"></i>' : ''} ${getTypeIcon(item.type)} ${item.title || truncate(item.content || item.url, 30)}
${item.type === 'todo' && item.status === 'completed' ? '' : ''}
<span style="font-size:10px; opacity:0.5; margin-left:8px;">
${formatShortDate(item.created_at)}${item.updated_at && item.updated_at !== item.created_at ? '' + formatShortDate(item.updated_at) : ''}
</span>
${item.content_stats && (item.content_stats.lines > 0 || item.content_stats.chars > 0) ?
`<span style="font-size:10px; opacity:0.6; margin-left:4px;" title="有效行数/总字数">[${item.content_stats.lines}行/${item.content_stats.chars}字]</span>` : ''}
${item.views > 0 ? `<span style="font-size:10px; opacity:0.5; margin-left:4px;" title="阅读次数">👁${item.views}</span>` : ''}
</h6>
<p class="card-text text-muted small mb-0 text-truncate" style="font-size:12px;">
${item.url ? truncate(item.url, 50) : item.content ? truncate(item.content, 50) : item.note ? truncate(item.note, 50) : ''}
@@ -1275,6 +1394,9 @@ function renderItems(items) {
</div>
<div class="d-flex align-items-center gap-1 flex-wrap ms-2" onclick="event.stopPropagation();">
${item.tags.slice(0, 2).map(t => `<span class="badge bg-secondary" style="font-size:10px;">${t}</span>`).join('')}
<button class="btn btn-sm btn-outline-warning py-0 px-1 star-btn" onclick="toggleStar(${item.id})" title="${item.is_starred ? '取消重点关注' : '设为重点关注'}">
<i class="bi bi-star${item.is_starred ? '-fill' : ''}" style="font-size:11px; ${item.is_starred ? 'color:#ffc107;' : ''}"></i>
</button>
${item.type !== 'todo' ? `<button class="btn btn-sm btn-outline-secondary py-0 px-1" onclick="showConvertModal(${item.id})" title="转为待办"><i class="bi bi-arrow-repeat" style="font-size:11px;"></i></button>` : ''}
<button class="btn btn-sm btn-outline-info py-0 px-1" onclick="showSendEmailModal(${item.id})" title="发送邮件"><i class="bi bi-envelope" style="font-size:11px;"></i></button>
<button class="btn btn-sm btn-outline-primary py-0 px-1" onclick="openEditModal(${item.id})" title="编辑"><i class="bi bi-pencil" style="font-size:11px;"></i></button>
@@ -1289,9 +1411,8 @@ function renderItems(items) {
}
// 渲染分页
function renderPagination(itemCount, page) {
function renderPagination(total, page) {
const container = document.getElementById('pagination');
const total = parseInt(document.getElementById('statTotal').textContent);
const totalPages = Math.ceil(total / pageSize);
if (totalPages <= 1) {
@@ -1353,6 +1474,14 @@ async function refreshData() {
loadItems(currentPage);
}
// 排序切换
function changeSort() {
const sortBy = document.getElementById('sortBy').value;
const sortOrder = document.getElementById('sortOrder').value;
currentSort = { sort_by: sortBy, sort_order: sortOrder };
loadItems(1); // 切换排序时回到第一页
}
// ============ 添加功能 ============
// 快捷添加按钮
@@ -1397,7 +1526,8 @@ async function addItem() {
priority: type === 'todo' ? document.getElementById('addPriority').value : null,
due_date: type === 'todo' ? document.getElementById('addDueDate').value : null,
note: document.getElementById('addNote').value,
tags: document.getElementById('addTags').value.split(',').map(t => t.trim()).filter(t => t)
tags: document.getElementById('addTags').value.split(',').map(t => t.trim()).filter(t => t),
is_starred: document.getElementById('addStarred').checked
};
const res = await fetch(`${API_BASE}/items`, {
@@ -1520,6 +1650,10 @@ let currentDetailId = null;
// 显示详情
async function showDetail(id) {
currentDetailId = id;
// 增加阅读数
await fetch(`${API_BASE}/items/${id}/view`, { method: 'POST' });
const res = await fetch(`${API_BASE}/items/${id}`);
const data = await res.json();
@@ -1535,6 +1669,19 @@ async function showDetail(id) {
let html = `<div class="mb-3"><strong>类型:</strong> ${getTypeLabel(item.type)}</div>`;
// 显示阅读数
html += `<div class="mb-3"><strong>阅读:</strong> <span class="badge bg-secondary">👁 ${item.views || 0} 次</span></div>`;
// 显示重点关注状态
if (item.is_starred) {
html += `<div class="mb-3"><strong>状态:</strong> <span class="badge bg-warning text-dark"><i class="bi bi-star-fill"></i> 重点关注</span></div>`;
}
// 显示内容统计
if (item.content_stats && (item.content_stats.lines > 0 || item.content_stats.chars > 0)) {
html += `<div class="mb-3"><strong>统计:</strong> <span class="badge bg-info">${item.content_stats.lines} 有效行 / ${item.content_stats.chars} 字</span></div>`;
}
if (item.url) {
html += `<div class="mb-3"><strong>URL:</strong> <a href="${item.url}" target="_blank">${item.url}</a></div>`;
}
@@ -1640,6 +1787,9 @@ async function openEditModal(id) {
}
}
// 设置重点关注状态
document.getElementById('editStarred').checked = item.is_starred === 1;
new bootstrap.Modal(document.getElementById('editModal')).show();
}
@@ -1666,17 +1816,34 @@ async function saveEdit() {
priority: type === 'todo' ? document.getElementById('editPriority').value : null,
due_date: type === 'todo' ? document.getElementById('editDueDate').value : null,
note: document.getElementById('editNote').value,
tags: document.getElementById('editTags').value.split(',').map(t => t.trim()).filter(t => t)
tags: document.getElementById('editTags').value.split(',').map(t => t.trim()).filter(t => t),
is_starred: document.getElementById('editStarred').checked ? 1 : 0
};
const res = await fetch(`${API_BASE}/items/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
try {
const res = await fetch(`${API_BASE}/items/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await res.json();
if (res.ok && result.success) {
bootstrap.Modal.getInstance(document.getElementById('editModal')).hide();
refreshData();
} else {
alert('保存失败: ' + (result.error || '未知错误'));
}
} catch (e) {
alert('保存失败: ' + e.message);
}
}
// 切换重点关注状态
async function toggleStar(id) {
const res = await fetch(`${API_BASE}/items/${id}/star`, { method: 'POST' });
if (res.ok) {
bootstrap.Modal.getInstance(document.getElementById('editModal')).hide();
refreshData();
}
}

View File

@@ -59,6 +59,8 @@ class Database:
priority TEXT DEFAULT 'medium',
due_date TEXT,
note TEXT,
is_starred INTEGER DEFAULT 0,
views INTEGER DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)
@@ -114,6 +116,21 @@ class Database:
cursor.execute("CREATE INDEX IF NOT EXISTS idx_item_tags_item ON item_tags(item_id)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_item_tags_tag ON item_tags(tag_id)")
# 检查并添加 is_starred 字段(兼容旧数据库)
try:
cursor.execute("SELECT is_starred FROM items LIMIT 1")
except sqlite3.OperationalError:
cursor.execute("ALTER TABLE items ADD COLUMN is_starred INTEGER DEFAULT 0")
# 创建 is_starred 索引(字段添加后再创建)
cursor.execute("CREATE INDEX IF NOT EXISTS idx_items_starred ON items(is_starred)")
# 检查并添加 views 字段(兼容旧数据库)
try:
cursor.execute("SELECT views FROM items LIMIT 1")
except sqlite3.OperationalError:
cursor.execute("ALTER TABLE items ADD COLUMN views INTEGER DEFAULT 0")
conn.commit()
# ============ Item 操作 ============
@@ -121,7 +138,7 @@ class Database:
def create_item(self, type: str = "text", title: str = None, content: str = None,
url: str = None, source: str = None, status: str = "pending",
priority: str = "medium", due_date: str = None, note: str = None,
tags: List[str] = None) -> int:
tags: List[str] = None, is_starred: bool = False) -> int:
"""创建新条目"""
self._ensure_init()
now = datetime.now().isoformat()
@@ -135,9 +152,9 @@ class Database:
with self.get_conn() as conn:
cursor = conn.cursor()
cursor.execute("""
INSERT INTO items (type, title, content, url, source, status, priority, due_date, note, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (type, title, content, url, source, status, priority, due_date, note, now, now))
INSERT INTO items (type, title, content, url, source, status, priority, due_date, note, is_starred, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (type, title, content, url, source, status, priority, due_date, note, 1 if is_starred else 0, now, now))
item_id = cursor.lastrowid
# 添加标签
@@ -161,8 +178,13 @@ class Database:
return item
def list_items(self, type: str = None, status: str = None, tag: str = None,
keyword: str = None, limit: int = 50, offset: int = 0) -> List[Dict[str, Any]]:
"""列出条目"""
keyword: str = None, starred: bool = None, sort_by: str = None,
sort_order: str = None, limit: int = 50, offset: int = 0) -> List[Dict[str, Any]]:
"""列出条目
sort_by: created_at, updated_at
sort_order: desc, asc
"""
with self.get_conn() as conn:
cursor = conn.cursor()
@@ -184,6 +206,10 @@ class Database:
conditions.append("i.status = ?")
params.append(status)
if starred is not None:
conditions.append("i.is_starred = ?")
params.append(1 if starred else 0)
if keyword:
conditions.append("(i.title LIKE ? OR i.content LIKE ? OR i.note LIKE ?)")
keyword_pattern = f"%{keyword}%"
@@ -192,7 +218,31 @@ class Database:
if conditions:
query += " WHERE " + " AND ".join(conditions)
query += " ORDER BY i.created_at DESC LIMIT ? OFFSET ?"
# 排序逻辑
if sort_by == 'updated_at':
order_field = 'i.updated_at'
elif sort_by == 'created_at':
order_field = 'i.created_at'
else:
# 默认:重点关注优先 + 创建时间降序
order_field = 'i.created_at'
order_dir = 'DESC' if (sort_order == 'asc' or sort_order is None) else 'ASC'
# 这里反转逻辑:用户选择"降序"时用DESC选择"升序"时用ASC
if sort_order == 'asc':
order_dir = 'ASC'
elif sort_order == 'desc':
order_dir = 'DESC'
else:
order_dir = 'DESC' # 默认降序
# 如果有指定排序字段,按该字段排序;否则默认重点关注优先
if sort_by:
query += f" ORDER BY {order_field} {order_dir} LIMIT ? OFFSET ?"
else:
# 默认:重点关注优先,然后创建时间降序
query += f" ORDER BY i.is_starred DESC, i.created_at DESC LIMIT ? OFFSET ?"
params.extend([limit, offset])
cursor.execute(query, params)
@@ -204,11 +254,51 @@ class Database:
return items
def count_items(self, type: str = None, status: str = None, tag: str = None,
keyword: str = None, starred: bool = None) -> int:
"""计算符合条件的条目总数"""
with self.get_conn() as conn:
cursor = conn.cursor()
query = "SELECT COUNT(DISTINCT i.id) as count FROM items i"
params = []
conditions = []
# 标签过滤需要JOIN
if tag:
query += " JOIN item_tags it ON i.id = it.item_id JOIN tags t ON it.tag_id = t.id"
conditions.append("t.name = ?")
params.append(tag)
if type:
conditions.append("i.type = ?")
params.append(type)
if status:
conditions.append("i.status = ?")
params.append(status)
if starred is not None:
conditions.append("i.is_starred = ?")
params.append(1 if starred else 0)
if keyword:
conditions.append("(i.title LIKE ? OR i.content LIKE ? OR i.note LIKE ?)")
keyword_pattern = f"%{keyword}%"
params.extend([keyword_pattern, keyword_pattern, keyword_pattern])
if conditions:
query += " WHERE " + " AND ".join(conditions)
cursor.execute(query, params)
return cursor.fetchone()['count']
def update_item(self, item_id: int, **kwargs) -> bool:
"""更新条目"""
allowed_fields = ['type', 'title', 'content', 'url', 'source', 'status', 'priority', 'due_date', 'note']
allowed_fields = ['type', 'title', 'content', 'url', 'source', 'status', 'priority', 'due_date', 'note', 'is_starred']
update_fields = {k: v for k, v in kwargs.items() if k in allowed_fields}
# 只有 tags 变化也算有效更新
if not update_fields and 'tags' not in kwargs:
return False
@@ -217,6 +307,11 @@ class Database:
with self.get_conn() as conn:
cursor = conn.cursor()
# 检查条目是否存在
cursor.execute("SELECT id FROM items WHERE id = ?", (item_id,))
if not cursor.fetchone():
return False
if update_fields:
set_clause = ", ".join(f"{k} = ?" for k in update_fields.keys())
set_clause += ", updated_at = ?"
@@ -231,7 +326,7 @@ class Database:
self._add_tags_to_item(conn, item_id, kwargs['tags'])
conn.commit()
return cursor.rowcount > 0
return True
def delete_item(self, item_id: int) -> bool:
"""删除条目"""
@@ -241,6 +336,39 @@ class Database:
conn.commit()
return cursor.rowcount > 0
def toggle_star(self, item_id: int) -> bool:
"""切换重点关注状态"""
with self.get_conn() as conn:
cursor = conn.cursor()
# 先获取当前状态
cursor.execute("SELECT is_starred FROM items WHERE id = ?", (item_id,))
row = cursor.fetchone()
if not row:
return False
new_status = 0 if row['is_starred'] else 1
now = datetime.now().isoformat()
cursor.execute("UPDATE items SET is_starred = ?, updated_at = ? WHERE id = ?", (new_status, now, item_id))
conn.commit()
return True
def set_star(self, item_id: int, starred: bool = True) -> bool:
"""设置重点关注状态"""
with self.get_conn() as conn:
cursor = conn.cursor()
now = datetime.now().isoformat()
cursor.execute("UPDATE items SET is_starred = ?, updated_at = ? WHERE id = ?", (1 if starred else 0, now, item_id))
conn.commit()
return cursor.rowcount > 0
def increment_views(self, item_id: int) -> bool:
"""增加阅读数"""
with self.get_conn() as conn:
cursor = conn.cursor()
cursor.execute("UPDATE items SET views = views + 1 WHERE id = ?", (item_id,))
conn.commit()
return cursor.rowcount > 0
# ============ Tag 操作 ============
def create_tag(self, name: str, color: str = "#3498db") -> int: