Initial commit: gamer project

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
lizhilun
2026-03-12 11:23:10 +08:00
co-authored by Claude Opus 4.6
commit a0d7bfdc3d
26 changed files with 5410 additions and 0 deletions
+309
View File
@@ -0,0 +1,309 @@
const API = '';
let token = localStorage.getItem('token');
let username = localStorage.getItem('username');
let currentType = 'income';
let currentCategory = '接单';
let currentYear = new Date().getFullYear();
let currentMonth = new Date().getMonth() + 1;
let currentNav = 'stats';
function headers() {
return { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token };
}
function formatLocalTime(isoStr) {
if (!isoStr) return '';
const d = new Date(isoStr);
const h = String(d.getHours()).padStart(2, '0');
const m = String(d.getMinutes()).padStart(2, '0');
return h + ':' + m;
}
function formatLocalDate(input) {
if (!input) return '未知日期';
const d = input instanceof Date ? input : new Date(input);
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return y + '-' + m + '-' + day;
}
async function loadTotalStats() {
try {
const res = await fetch(API + '/api/stats/total', { headers: headers() });
if (!res.ok) return;
const s = await res.json();
document.getElementById('totalTakeCount').textContent = s.take_count;
document.getElementById('totalDispatchCount').textContent = s.dispatch_count;
document.getElementById('totalNetIncome').textContent = '' + s.net_income.toFixed(2);
} catch (e) { console.error(e); }
}
function renderHorizontalChart(containerId, rows, clickHandler, fromPage) {
const container = document.getElementById(containerId);
if (rows.length === 0) {
container.innerHTML = '<div class="ranking-empty">暂无数据</div>';
return;
}
const max = Math.max(...rows.map(r => r.count), 1);
container.innerHTML = rows.map((r, i) => {
const pct = Math.max((r.count / max) * 100, 2);
const onclick = clickHandler ? ` onclick="${clickHandler}('${r.name.replace(/'/g, "\\'")}', '${fromPage}')"` : '';
return `<div class="hbar-row"${onclick}>
<div class="hbar-index ${i < 3 ? 'top' : ''}">${i + 1}</div>
<div class="hbar-label" title="${r.name}">${r.name}</div>
<div class="hbar-track"><div class="hbar-fill" style="width:${pct}%"></div></div>
<div class="hbar-value">${r.count}单</div>
</div>`;
}).join('');
}
async function openTakeRanking() {
showPage('takeRankingPage');
try {
const res = await fetch(API + '/api/stats/take-ranking', { headers: headers() });
if (!res.ok) return;
const data = await res.json();
console.log('take-ranking data:', data);
const rows = data.rows || [];
// 显示统计卡片
const summaryContainer = document.getElementById('takeRankingSummary');
summaryContainer.innerHTML = `
<div class="item">
<div class="label">接单总数</div>
<div class="val">${data.total_take_count || 0}</div>
</div>
<div class="item">
<div class="label">接单总收入</div>
<div class="val green">${(data.total_take_income || 0).toFixed(2)}</div>
</div>
<div class="item">
<div class="label">红包收入</div>
<div class="val purple">${(data.total_redEnvelope_income || 0).toFixed(2)}</div>
</div>
`;
renderHorizontalChart('takeRankingChart', rows, 'openBossDetail', 'takeRankingPage');
} catch (e) { console.error(e); }
}
async function openDispatchRanking() {
showPage('dispatchRankingPage');
try {
const res = await fetch(API + '/api/stats/dispatch-ranking', { headers: headers() });
if (!res.ok) return;
const data = await res.json();
const rows = data.rows || [];
// 计算总计
const totalDispatch = data.total_dispatch_count !== undefined ? data.total_dispatch_count : (rows.reduce((sum, r) => sum + (r.dispatch_count || 0), 0));
const totalPartnerIncome = rows.reduce((sum, r) => sum + (r.partner_income || 0), 0);
const totalRebateIncome = rows.reduce((sum, r) => sum + (r.rebate_income || 0), 0);
const totalMilkTeaIncome = data.total_milkTea_income || 0;
// 显示4个卡片
const summaryContainer = document.getElementById('dispatchRankingSummary');
summaryContainer.innerHTML = `
<div class="item">
<div class="label">派单总数</div>
<div class="val">${totalDispatch}</div>
</div>
<div class="item">
<div class="label">陪玩总收入</div>
<div class="val green">${totalPartnerIncome.toFixed(2)}</div>
</div>
<div class="item">
<div class="label">返点总收入</div>
<div class="val orange">${totalRebateIncome.toFixed(2)}</div>
</div>
<div class="item">
<div class="label">奶茶收入</div>
<div class="val purple">${totalMilkTeaIncome.toFixed(2)}</div>
</div>
`;
// 显示排行列表
const max = Math.max(...rows.map(r => r.dispatch_count || 0), 1);
const container = document.getElementById('dispatchRankingChart');
container.innerHTML = rows.map((r, i) => {
const pct = Math.max(((r.dispatch_count || 0) / max) * 100, 2);
return `<div class="hbar-row" onclick="openPartnerDetail('${r.name.replace(/'/g, "\\'")}', 'dispatchRankingPage')">
<div class="hbar-index ${i < 3 ? 'top' : ''}">${i + 1}</div>
<div class="hbar-label" title="${r.name}">${r.name}</div>
<div class="hbar-track"><div class="hbar-fill" style="width:${pct}%"></div></div>
<div class="hbar-value">${r.dispatch_count}单</div>
</div>`;
}).join('');
} catch (e) { console.error(e); }
}
function showToast(msg) {
const t = document.getElementById('toast');
t.textContent = msg;
t.classList.add('show');
setTimeout(() => t.classList.remove('show'), 2000);
}
function showPage(pageId) {
document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
document.getElementById(pageId).classList.add('active');
window.scrollTo(0, 0);
if (pageId === 'homePage') {
updateMonthDisplay();
loadStats();
document.getElementById('profileName').textContent = username;
document.getElementById('avatarText').textContent = username.charAt(0).toUpperCase();
switchNav(currentNav);
}
if (pageId === 'recordPage') {
currentType = 'income';
currentCategory = '接单';
document.querySelectorAll('.type-btn').forEach((b, i) => b.classList.toggle('active', i === 0));
document.getElementById('incomeCats').style.display = 'grid';
document.getElementById('expenseCats').style.display = 'none';
selectCategory(document.querySelector('#incomeCats .category-item'), '接单');
}
if (pageId === 'rankingPage') {
const startDate = `${currentYear}-${String(currentMonth).padStart(2, '0')}-01`;
const now = new Date();
const endDay = (currentYear === now.getFullYear() && currentMonth === now.getMonth() + 1) ? formatLocalDate(now) : `${currentYear}-${String(currentMonth).padStart(2, '0')}-28`;
document.getElementById('rankStartDate').value = startDate;
document.getElementById('rankEndDate').value = endDay;
currentSort = 'total_income';
document.querySelectorAll('.sort-btn').forEach((b, i) => b.classList.toggle('active', i === 0));
loadRankingDetail();
}
if (pageId === 'orderListPage') {
document.getElementById('orderListTitle').textContent = `${currentYear}${currentMonth}月接单列表`;
orderPage = 1; orderHasMore = true;
document.getElementById('orderList').innerHTML = '';
loadOrders();
}
if (pageId === 'otherIncomeListPage') {
document.getElementById('otherIncomeListTitle').textContent = `${currentYear}${currentMonth}月红包及其他收入`;
otherIncomePage = 1; otherIncomeHasMore = true;
document.getElementById('otherIncomeList').innerHTML = '';
loadOtherIncome();
}
if (pageId === 'dispatchListPage') {
document.getElementById('dispatchListTitle').textContent = `${currentYear}${currentMonth}月派单列表`;
dispatchPage = 1; dispatchHasMore = true;
document.getElementById('dispatchList').innerHTML = '';
loadDispatches();
}
if (pageId === 'redEnvelopeListPage') {
redEnvelopePage = 1; redEnvelopeHasMore = true;
document.getElementById('redEnvelopeList').innerHTML = '';
loadRedEnvelope();
}
if (pageId === 'milkTeaListPage') {
milkTeaPage = 1; milkTeaHasMore = true;
document.getElementById('milkTeaList').innerHTML = '';
loadMilkTea();
}
}
function switchNav(nav) {
currentNav = nav;
document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
document.getElementById('navStats').classList.toggle('active', nav === 'stats');
document.getElementById('navMine').classList.toggle('active', nav === 'mine');
if (nav === 'stats') {
document.getElementById('statsPanel').classList.add('active');
} else {
document.getElementById('minePanel').classList.add('active');
loadTotalStats();
}
}
function updateMonthDisplay() {
document.getElementById('monthDisplay').textContent = `${currentYear}${currentMonth}`;
}
// 头像连续点击5次显示隐藏按钮
let avatarTapCount = 0;
let avatarTapTimer = null;
function onAvatarTap() {
avatarTapCount++;
clearTimeout(avatarTapTimer);
avatarTapTimer = setTimeout(() => { avatarTapCount = 0; }, 1500);
if (avatarTapCount >= 5) {
avatarTapCount = 0;
const el = document.getElementById('secretBtns');
const visible = el.style.display !== 'none';
el.style.display = visible ? 'none' : 'block';
showToast(visible ? '已隐藏' : '已解锁');
}
}
// 下拉刷新
(function() {
let startY = 0, pulling = false, triggered = false;
const threshold = 60;
function getPanel() { return document.getElementById('statsPanel'); }
function getIndicator() { return document.getElementById('pullIndicator'); }
document.addEventListener('touchstart', function(e) {
const panel = getPanel();
if (!panel || !panel.classList.contains('active')) return;
if (currentNav !== 'stats') return;
if (window.scrollY > 0) return;
startY = e.touches[0].clientY;
pulling = true;
triggered = false;
}, { passive: true });
document.addEventListener('touchmove', function(e) {
if (!pulling) return;
const panel = getPanel();
if (!panel || !panel.classList.contains('active')) { pulling = false; return; }
if (window.scrollY > 0) { pulling = false; return; }
const dy = e.touches[0].clientY - startY;
if (dy < 0) return;
const indicator = getIndicator();
const arrow = document.getElementById('pullArrow');
const text = document.getElementById('pullText');
if (dy > 10) {
indicator.classList.add('visible');
if (dy >= threshold) {
arrow.classList.add('flipped');
text.textContent = '松手刷新';
triggered = true;
} else {
arrow.classList.remove('flipped');
text.textContent = '下拉刷新';
triggered = false;
}
}
}, { passive: true });
document.addEventListener('touchend', function() {
if (!pulling) return;
pulling = false;
const indicator = getIndicator();
const arrow = document.getElementById('pullArrow');
const text = document.getElementById('pullText');
if (triggered) {
text.textContent = '刷新中...';
arrow.classList.remove('flipped');
indicator.classList.add('refreshing');
loadStats().then(() => {
setTimeout(() => {
indicator.classList.remove('visible', 'refreshing');
showToast('已刷新');
}, 500);
});
} else {
indicator.classList.remove('visible');
}
}, { passive: true });
})();
document.addEventListener('DOMContentLoaded', function() {
if (token && username) {
showPage('homePage');
}
renderForm();
});
+29
View File
@@ -0,0 +1,29 @@
async function doLogin() {
const user = document.getElementById('loginUser').value.trim();
const pass = document.getElementById('loginPass').value.trim();
if (!user || !pass) { document.getElementById('loginError').textContent = '请输入用户名和密码'; return; }
try {
const res = await fetch(API + '/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: user, password: pass })
});
const data = await res.json();
if (!res.ok) { document.getElementById('loginError').textContent = data.error; return; }
token = data.token;
username = data.username;
localStorage.setItem('token', token);
localStorage.setItem('username', username);
showPage('homePage');
} catch (e) {
document.getElementById('loginError').textContent = '网络错误';
}
}
function doLogout() {
token = null;
username = null;
localStorage.removeItem('token');
localStorage.removeItem('username');
showPage('loginPage');
}
+103
View File
@@ -0,0 +1,103 @@
// 联系人自动补全模块
const _acCache = {};
async function acFetchNames(field) {
if (_acCache[field] && Date.now() - _acCache[field].ts < 60000) return _acCache[field].data;
try {
const res = await fetch(API + '/api/contacts?field=' + field, { headers: headers() });
if (!res.ok) return [];
const data = await res.json();
_acCache[field] = { data, ts: Date.now() };
return data;
} catch { return []; }
}
function acInvalidateCache(field) {
if (field) delete _acCache[field];
else Object.keys(_acCache).forEach(k => delete _acCache[k]);
}
function acSetup(inputId, field) {
const input = document.getElementById(inputId);
if (!input || input._acBound) return;
input._acBound = true;
input.setAttribute('autocomplete', 'off');
const wrap = document.createElement('div');
wrap.className = 'ac-wrap';
input.parentNode.insertBefore(wrap, input);
wrap.appendChild(input);
const list = document.createElement('div');
list.className = 'ac-list';
wrap.appendChild(list);
let names = [];
let activeIdx = -1;
async function loadNames() {
names = await acFetchNames(field);
}
function render(query) {
const q = query.trim().toLowerCase();
const filtered = q ? names.filter(n => n.toLowerCase().includes(q)) : names;
if (filtered.length === 0) { list.classList.remove('show'); return; }
activeIdx = -1;
list.innerHTML = filtered.slice(0, 10).map((n, i) => {
let display = n;
if (q) {
const idx = n.toLowerCase().indexOf(q);
if (idx >= 0) {
display = n.slice(0, idx) + '<span class="ac-highlight">' + n.slice(idx, idx + q.length) + '</span>' + n.slice(idx + q.length);
}
}
return `<div class="ac-item" data-idx="${i}" data-value="${n.replace(/"/g, '&quot;')}">${display}</div>`;
}).join('');
list.classList.add('show');
}
function pick(value) {
input.value = value;
list.classList.remove('show');
input.dispatchEvent(new Event('input', { bubbles: true }));
}
input.addEventListener('focus', async () => {
await loadNames();
render(input.value);
});
input.addEventListener('input', () => { render(input.value); });
input.addEventListener('keydown', (e) => {
const items = list.querySelectorAll('.ac-item');
if (!list.classList.contains('show') || items.length === 0) return;
if (e.key === 'ArrowDown') {
e.preventDefault();
activeIdx = Math.min(activeIdx + 1, items.length - 1);
items.forEach((el, i) => el.classList.toggle('active', i === activeIdx));
items[activeIdx].scrollIntoView({ block: 'nearest' });
} else if (e.key === 'ArrowUp') {
e.preventDefault();
activeIdx = Math.max(activeIdx - 1, 0);
items.forEach((el, i) => el.classList.toggle('active', i === activeIdx));
items[activeIdx].scrollIntoView({ block: 'nearest' });
} else if (e.key === 'Enter' && activeIdx >= 0) {
e.preventDefault();
pick(items[activeIdx].dataset.value);
} else if (e.key === 'Escape') {
list.classList.remove('show');
}
});
list.addEventListener('mousedown', (e) => {
e.preventDefault(); // 防止 input 失焦
const item = e.target.closest('.ac-item');
if (item) pick(item.dataset.value);
});
document.addEventListener('click', (e) => {
if (!wrap.contains(e.target)) list.classList.remove('show');
});
}
+164
View File
@@ -0,0 +1,164 @@
function openEditModal(record) {
document.getElementById('editId').value = record.id;
document.getElementById('editCategory').value = record.category || '';
const cat = record.category;
const body = document.getElementById('editFormBody');
let localTime = '';
if (record.created_at) {
const dt = new Date(record.created_at);
localTime = new Date(dt.getTime() - dt.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
}
if (cat === '接单' || cat === '派单') {
document.getElementById('editModalTitle').textContent = cat === '派单' ? '编辑派单记录' : '编辑接单记录';
let fields = `
<div class="form-group"><label>单数</label><input type="number" id="editQuantity" value="${record.quantity || ''}"></div>
<div class="form-group"><label>单价(元)</label><input type="number" step="0.01" id="editPrice" value="${record.unit_price || ''}"></div>
`;
if (cat === '派单') {
const rebateVal = record.rebate || (record.quantity ? (record.amount / record.quantity) : '');
fields += `<div class="form-group"><label>返点(元)</label><input type="number" step="0.01" id="editRebate" value="${rebateVal}"></div>`;
}
fields += `
<div class="form-group"><label>老板</label><input type="text" id="editBoss" value="${record.boss || ''}"></div>
<div class="form-group"><label>${cat === '派单' ? '负责打单的陪玩' : '一起的陪玩'}</label><input type="text" id="editPartner" value="${record.partner || ''}"></div>
<div class="form-group"><label>时间</label><input type="datetime-local" id="editTime" value="${localTime}"></div>
`;
body.innerHTML = fields;
} else if (cat === '红包收入' || cat === '奶茶') {
document.getElementById('editModalTitle').textContent = '编辑' + cat + '记录';
body.innerHTML = `
<div class="form-group"><label>金额(元)</label><input type="number" step="0.01" id="editAmount" value="${record.amount || ''}"></div>
<div class="form-group"><label>来源</label><input type="text" id="editSource" value="${record.source || ''}"></div>
<div class="form-group"><label>时间</label><input type="datetime-local" id="editTime" value="${localTime}"></div>
`;
} else if (cat === '红包支出' || cat === '比心' || cat === '其他支出') {
document.getElementById('editModalTitle').textContent = '编辑' + cat + '记录';
let fields = `
<div class="form-group"><label>金额(元)</label><input type="number" step="0.01" id="editAmount" value="${record.amount || ''}"></div>
`;
if (cat !== '比心') {
fields += `<div class="form-group"><label>目的地</label><input type="text" id="editDest" value="${record.destination || ''}"></div>`;
} else {
fields += `<div class="form-group"><label>用途</label><input type="text" id="editDest" value="${record.destination || ''}"></div>`;
}
if (cat === '其他支出') {
fields += `<div class="form-group"><label>备注</label><input type="text" id="editNote" value="${record.note || ''}"></div>`;
}
fields += `<div class="form-group"><label>时间</label><input type="datetime-local" id="editTime" value="${localTime}"></div>`;
body.innerHTML = fields;
} else {
document.getElementById('editModalTitle').textContent = '编辑记录';
body.innerHTML = `
<div class="form-group"><label>金额(元)</label><input type="number" step="0.01" id="editAmount" value="${record.amount || ''}"></div>
<div class="form-group"><label>时间</label><input type="datetime-local" id="editTime" value="${localTime}"></div>
`;
}
// 绑定自动补全
if (cat === '接单' || cat === '派单') {
acSetup('editBoss', 'boss');
acSetup('editPartner', 'partner');
} else if (cat === '红包收入' || cat === '奶茶') {
acSetup('editSource', 'source');
} else if (cat === '红包支出' || cat === '比心' || cat === '其他支出') {
acSetup('editDest', 'destination');
}
document.getElementById('editModal').classList.add('show');
}
function closeEditModal() {
document.getElementById('editModal').classList.remove('show');
}
function refreshCurrentList() {
const cat = document.getElementById('editCategory').value;
if (cat === '派单') {
dispatchPage = 1; dispatchHasMore = true;
document.getElementById('dispatchList').innerHTML = '';
loadDispatches();
} else if (cat === '接单') {
orderPage = 1; orderHasMore = true;
document.getElementById('orderList').innerHTML = '';
loadOrders();
} else {
otherIncomePage = 1; otherIncomeHasMore = true;
document.getElementById('otherIncomeList').innerHTML = '';
loadOtherIncome();
}
// 如果在日详情页也刷新
if (document.getElementById('dailyDetailPage').classList.contains('active') && currentDailyDate) {
openDailyDetail(currentDailyDate);
}
}
async function saveEditRecord() {
const id = document.getElementById('editId').value;
const cat = document.getElementById('editCategory').value;
const time = document.getElementById('editTime')?.value;
let body = {};
if (cat === '接单' || cat === '派单') {
const quantity = parseInt(document.getElementById('editQuantity').value) || 0;
const unit_price = parseFloat(document.getElementById('editPrice').value) || 0;
const boss = document.getElementById('editBoss').value.trim();
const partner = document.getElementById('editPartner').value.trim();
if (cat === '派单') {
const rebate = parseFloat(document.getElementById('editRebate').value) || 0;
if (!quantity || !unit_price || !rebate || !boss) { showToast('请填写完整信息'); return; }
body = { quantity, unit_price, rebate, amount: quantity * rebate, boss, partner };
} else {
if (!quantity || !unit_price || !boss) { showToast('请填写完整信息'); return; }
body = { quantity, unit_price, amount: quantity * unit_price, boss, partner };
}
} else if (cat === '红包收入' || cat === '奶茶') {
const amount = parseFloat(document.getElementById('editAmount').value);
const source = document.getElementById('editSource').value.trim();
if (!amount || !source) { showToast('请填写完整信息'); return; }
body = { amount, source };
} else if (cat === '红包支出' || cat === '比心' || cat === '其他支出') {
const amount = parseFloat(document.getElementById('editAmount').value);
if (!amount) { showToast('请填写完整信息'); return; }
body = { amount };
if (cat === '比心') {
const dest = document.getElementById('editDest').value.trim();
body.destination = dest || '比心';
} else {
const dest = document.getElementById('editDest').value.trim();
if (!dest) { showToast('请填写完整信息'); return; }
body.destination = dest;
}
body.note = document.getElementById('editNote')?.value.trim() || '';
} else {
const amount = parseFloat(document.getElementById('editAmount').value);
if (!amount) { showToast('请填写完整信息'); return; }
body = { amount };
}
if (time) body.created_at = new Date(time).toISOString();
try {
const res = await fetch(API + '/api/records/' + id, {
method: 'PUT',
headers: headers(),
body: JSON.stringify(body)
});
if (!res.ok) { showToast('保存失败'); return; }
showToast('保存成功');
acInvalidateCache();
closeEditModal();
refreshCurrentList();
} catch (e) { showToast('网络错误'); }
}
async function deleteEditRecord() {
const id = document.getElementById('editId').value;
if (!confirm('确定删除这条记录?')) return;
try {
const res = await fetch(API + '/api/records/' + id, { method: 'DELETE', headers: headers() });
if (!res.ok) { showToast('删除失败'); return; }
showToast('已删除');
closeEditModal();
refreshCurrentList();
} catch (e) { showToast('网络错误'); }
}
+108
View File
@@ -0,0 +1,108 @@
// 导出功能
function showExportDialog() {
document.getElementById('exportModal').classList.add('show');
}
function closeExportModal() {
document.getElementById('exportModal').classList.remove('show');
}
async function doExport(format) {
closeExportModal();
showToast('正在导出...');
try {
const res = await fetch(API + '/api/export?format=' + format, { headers: headers() });
if (!res.ok) {
const err = await res.json();
showToast(err.error || '导出失败');
return;
}
const disposition = res.headers.get('Content-Disposition');
let filename = 'gamer-export.' + format;
if (disposition) {
const match = disposition.match(/filename="?([^"]+)"?/);
if (match) filename = match[1];
}
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showToast('导出成功');
} catch (e) {
showToast('导出失败: 网络错误');
}
}
// 导入功能
let pendingImportContent = null;
function triggerImport() {
document.getElementById('importFileInput').value = '';
document.getElementById('importFileInput').click();
}
function handleImportFile(event) {
const file = event.target.files[0];
if (!file) return;
const ext = file.name.split('.').pop().toLowerCase();
if (ext !== 'json' && ext !== 'csv') {
showToast('请选择 JSON 或 CSV 文件');
return;
}
const reader = new FileReader();
reader.onload = function(e) {
const content = e.target.result;
pendingImportContent = content;
let count = 0;
try {
const trimmed = content.replace(/^\uFEFF/, '').trim();
if (trimmed.startsWith('{')) {
const data = JSON.parse(trimmed);
count = data.recordCount || (data.records ? data.records.length : 0);
} else {
count = Math.max(0, trimmed.split('\n').filter(l => l.trim()).length - 1);
}
} catch (err) {
showToast('文件格式无法识别');
return;
}
document.getElementById('importConfirmMsg').textContent =
'文件: ' + file.name + '\n检测到 ' + count + ' 条记录,确认导入?\n(重复记录将自动跳过)';
document.getElementById('importConfirmModal').classList.add('show');
};
reader.readAsText(file, 'UTF-8');
}
function closeImportConfirm() {
document.getElementById('importConfirmModal').classList.remove('show');
pendingImportContent = null;
}
async function confirmImport() {
document.getElementById('importConfirmModal').classList.remove('show');
if (!pendingImportContent) return;
showToast('正在导入...');
try {
const res = await fetch(API + '/api/import', {
method: 'POST',
headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Authorization': 'Bearer ' + token },
body: pendingImportContent
});
const data = await res.json();
if (!res.ok) {
showToast(data.error || '导入失败');
return;
}
showToast('导入完成: ' + data.imported + '条新增, ' + data.skipped + '条跳过');
pendingImportContent = null;
loadStats();
loadTotalStats();
} catch (e) {
showToast('导入失败: 网络错误');
}
}
+43
View File
@@ -0,0 +1,43 @@
let pickerYear = currentYear;
let pickerMonth = currentMonth;
function openMonthPicker() {
pickerYear = currentYear;
pickerMonth = currentMonth;
renderMonthPicker();
document.getElementById('monthPickerOverlay').classList.add('show');
}
function closeMonthPicker() {
document.getElementById('monthPickerOverlay').classList.remove('show');
}
function changePickerYear(delta) {
pickerYear += delta;
renderMonthPicker();
}
function renderMonthPicker() {
document.getElementById('pickerYearDisplay').textContent = pickerYear;
const grid = document.getElementById('pickerMonthGrid');
grid.innerHTML = '';
for (let m = 1; m <= 12; m++) {
const btn = document.createElement('button');
btn.textContent = m + '月';
if (m === pickerMonth) btn.classList.add('active');
btn.onclick = () => {
pickerMonth = m;
grid.querySelectorAll('button').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
};
grid.appendChild(btn);
}
}
function confirmMonth() {
currentYear = pickerYear;
currentMonth = pickerMonth;
updateMonthDisplay();
closeMonthPicker();
loadStats();
}
+300
View File
@@ -0,0 +1,300 @@
let orderPage = 1;
let orderHasMore = true;
let orderLoading = false;
async function loadOrders(append) {
if (orderLoading || (!append && !orderHasMore)) return;
orderLoading = true;
document.getElementById('orderLoading').style.display = 'block';
try {
const res = await fetch(API + '/api/records/orders?page=' + orderPage + '&limit=20&year=' + currentYear + '&month=' + currentMonth, { headers: headers() });
if (!res.ok) return;
const data = await res.json();
const container = document.getElementById('orderList');
if (!append) container.innerHTML = '';
if (data.records.length === 0) {
if (orderPage === 1) container.innerHTML = '<div class="ranking-empty">暂无接单记录</div>';
orderHasMore = false;
} else {
const grouped = {};
data.records.forEach(r => {
const date = formatLocalDate(r.created_at);
if (!grouped[date]) grouped[date] = [];
grouped[date].push(r);
});
let html = '';
for (const [date, records] of Object.entries(grouped)) {
html += `<div class="order-date-group" data-date="${date}">
<div class="order-date-label">${date}</div>`;
records.forEach(r => {
const time = formatLocalTime(r.created_at);
html += `<div class="order-item" onclick='openEditModal(${JSON.stringify(r).replace(/'/g, "&#39;")})'>
<div class="order-item-top">
<span class="order-item-boss">${r.boss || '-'}</span>
<span class="order-item-amount">${(r.amount || 0).toFixed(2)}</span>
</div>
<div class="order-item-bottom">
<span>${r.quantity || 0}× ${(r.unit_price || 0).toFixed(2)}</span>
<span>${time}${r.partner ? ' · ' + r.partner : ''}</span>
</div>
</div>`;
});
html += '</div>';
}
container.insertAdjacentHTML('beforeend', html);
orderHasMore = data.records.length >= 20;
orderPage++;
if (!append) {
const today = formatLocalDate(new Date());
setTimeout(() => {
const el = container.querySelector(`[data-date="${today}"]`);
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
}, 100);
}
}
} catch (e) { console.error(e); }
orderLoading = false;
document.getElementById('orderLoading').style.display = 'none';
}
// 滚动加载
window.addEventListener('scroll', () => {
if (document.getElementById('orderListPage').classList.contains('active')) {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
if (orderHasMore && !orderLoading) loadOrders(true);
}
}
if (document.getElementById('dispatchListPage').classList.contains('active')) {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
if (dispatchHasMore && !dispatchLoading) loadDispatches(true);
}
}
if (document.getElementById('otherIncomeListPage').classList.contains('active')) {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
if (otherIncomeHasMore && !otherIncomeLoading) loadOtherIncome(true);
}
}
if (document.getElementById('redEnvelopeListPage').classList.contains('active')) {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
if (redEnvelopeHasMore && !redEnvelopeLoading) loadRedEnvelope(true);
}
}
if (document.getElementById('milkTeaListPage').classList.contains('active')) {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
if (milkTeaHasMore && !milkTeaLoading) loadMilkTea(true);
}
}
});
// 红包及其他收入列表
let otherIncomePage = 1;
let otherIncomeHasMore = true;
let otherIncomeLoading = false;
async function loadOtherIncome(append) {
if (otherIncomeLoading || (!append && !otherIncomeHasMore)) return;
otherIncomeLoading = true;
document.getElementById('otherIncomeLoading').style.display = 'block';
try {
const res = await fetch(API + '/api/records/other-income?page=' + otherIncomePage + '&limit=20&year=' + currentYear + '&month=' + currentMonth, { headers: headers() });
if (!res.ok) return;
const data = await res.json();
const container = document.getElementById('otherIncomeList');
if (!append) container.innerHTML = '';
if (data.records.length === 0) {
if (otherIncomePage === 1) container.innerHTML = '<div class="ranking-empty">暂无红包及其他收入记录</div>';
otherIncomeHasMore = false;
} else {
const grouped = {};
data.records.forEach(r => {
const date = formatLocalDate(r.created_at);
if (!grouped[date]) grouped[date] = [];
grouped[date].push(r);
});
let html = '';
for (const [date, records] of Object.entries(grouped)) {
html += `<div class="order-date-group" data-date="${date}">
<div class="order-date-label">${date}</div>`;
records.forEach(r => {
const time = formatLocalTime(r.created_at);
const displayCategory = r.category === '红包收入' ? '红包' : (r.category || '-');
html += `<div class="order-item" onclick='openEditModal(${JSON.stringify(r).replace(/'/g, "&#39;")})'>
<div class="order-item-top">
<span class="order-item-boss">${displayCategory}${r.boss ? ' · ' + r.boss : ''}</span>
<span class="order-item-amount">${(r.amount || 0).toFixed(2)}</span>
</div>
<div class="order-item-bottom">
<span>${r.source || ''}</span>
<span>${time}</span>
</div>
</div>`;
});
html += '</div>';
}
container.insertAdjacentHTML('beforeend', html);
otherIncomeHasMore = data.records.length >= 20;
otherIncomePage++;
}
} catch (e) { console.error(e); }
otherIncomeLoading = false;
document.getElementById('otherIncomeLoading').style.display = 'none';
}
// 派单列表
let dispatchPage = 1;
let dispatchHasMore = true;
let dispatchLoading = false;
async function loadDispatches(append) {
if (dispatchLoading || (!append && !dispatchHasMore)) return;
dispatchLoading = true;
document.getElementById('dispatchLoading').style.display = 'block';
try {
const res = await fetch(API + '/api/records/dispatches?page=' + dispatchPage + '&limit=20&year=' + currentYear + '&month=' + currentMonth, { headers: headers() });
if (!res.ok) return;
const data = await res.json();
const container = document.getElementById('dispatchList');
if (!append) container.innerHTML = '';
if (data.records.length === 0) {
if (dispatchPage === 1) container.innerHTML = '<div class="ranking-empty">暂无派单记录</div>';
dispatchHasMore = false;
} else {
const grouped = {};
data.records.forEach(r => {
const date = formatLocalDate(r.created_at);
if (!grouped[date]) grouped[date] = [];
grouped[date].push(r);
});
let html = '';
for (const [date, records] of Object.entries(grouped)) {
html += `<div class="order-date-group" data-date="${date}">
<div class="order-date-label">${date}</div>`;
records.forEach(r => {
const time = formatLocalTime(r.created_at);
html += `<div class="order-item" onclick='openEditModal(${JSON.stringify(r).replace(/'/g, "&#39;")})'>
<div class="order-item-top">
<span class="order-item-boss">${r.boss || '-'}</span>
<span class="order-item-amount">${(r.amount || 0).toFixed(2)}</span>
</div>
<div class="order-item-bottom">
<span>${r.quantity || 0}× ${(r.rebate || r.amount / r.quantity).toFixed(2)}(单价${(r.unit_price || 0).toFixed(2)}</span>
<span>${time}${r.partner ? ' · ' + r.partner : ''}</span>
</div>
</div>`;
});
html += '</div>';
}
container.insertAdjacentHTML('beforeend', html);
dispatchHasMore = data.records.length >= 20;
dispatchPage++;
}
} catch (e) { console.error(e); }
dispatchLoading = false;
document.getElementById('dispatchLoading').style.display = 'none';
}
// 红包收入列表
let redEnvelopePage = 1;
let redEnvelopeHasMore = true;
let redEnvelopeLoading = false;
async function loadRedEnvelope(append) {
if (redEnvelopeLoading || (!append && !redEnvelopeHasMore)) return;
redEnvelopeLoading = true;
document.getElementById('redEnvelopeLoading').style.display = 'block';
try {
const res = await fetch(API + '/api/records/red-envelope?page=' + redEnvelopePage + '&limit=20&year=' + currentYear + '&month=' + currentMonth, { headers: headers() });
if (!res.ok) return;
const data = await res.json();
const container = document.getElementById('redEnvelopeList');
if (!append) container.innerHTML = '';
if (data.records.length === 0) {
if (redEnvelopePage === 1) container.innerHTML = '<div class="ranking-empty">暂无红包收入记录</div>';
redEnvelopeHasMore = false;
} else {
const grouped = {};
data.records.forEach(r => {
const date = formatLocalDate(r.created_at);
if (!grouped[date]) grouped[date] = [];
grouped[date].push(r);
});
let html = '';
for (const [date, records] of Object.entries(grouped)) {
html += `<div class="order-date-group" data-date="${date}">
<div class="order-date-label">${date}</div>`;
records.forEach(r => {
const time = formatLocalTime(r.created_at);
html += `<div class="order-item" onclick='openEditModal(${JSON.stringify(r).replace(/'/g, "&#39;")})'>
<div class="order-item-top">
<span class="order-item-boss">红包</span>
<span class="order-item-amount">${(r.amount || 0).toFixed(2)}</span>
</div>
<div class="order-item-bottom">
<span>${r.source || ''}</span>
<span>${time}</span>
</div>
</div>`;
});
html += '</div>';
}
container.insertAdjacentHTML('beforeend', html);
redEnvelopeHasMore = data.records.length >= 20;
redEnvelopePage++;
}
} catch (e) { console.error(e); }
redEnvelopeLoading = false;
document.getElementById('redEnvelopeLoading').style.display = 'none';
}
// 奶茶收入列表
let milkTeaPage = 1;
let milkTeaHasMore = true;
let milkTeaLoading = false;
async function loadMilkTea(append) {
if (milkTeaLoading || (!append && !milkTeaHasMore)) return;
milkTeaLoading = true;
document.getElementById('milkTeaLoading').style.display = 'block';
try {
const res = await fetch(API + '/api/records/milk-tea?page=' + milkTeaPage + '&limit=20&year=' + currentYear + '&month=' + currentMonth, { headers: headers() });
if (!res.ok) return;
const data = await res.json();
const container = document.getElementById('milkTeaList');
if (!append) container.innerHTML = '';
if (data.records.length === 0) {
if (milkTeaPage === 1) container.innerHTML = '<div class="ranking-empty">暂无奶茶收入记录</div>';
milkTeaHasMore = false;
} else {
const grouped = {};
data.records.forEach(r => {
const date = formatLocalDate(r.created_at);
if (!grouped[date]) grouped[date] = [];
grouped[date].push(r);
});
let html = '';
for (const [date, records] of Object.entries(grouped)) {
html += `<div class="order-date-group" data-date="${date}">
<div class="order-date-label">${date}</div>`;
records.forEach(r => {
const time = formatLocalTime(r.created_at);
html += `<div class="order-item" onclick='openEditModal(${JSON.stringify(r).replace(/'/g, "&#39;")})'>
<div class="order-item-top">
<span class="order-item-boss">奶茶</span>
<span class="order-item-amount">${(r.amount || 0).toFixed(2)}</span>
</div>
<div class="order-item-bottom">
<span>${r.source || ''}</span>
<span>${time}</span>
</div>
</div>`;
});
html += '</div>';
}
container.insertAdjacentHTML('beforeend', html);
milkTeaHasMore = data.records.length >= 20;
milkTeaPage++;
}
} catch (e) { console.error(e); }
milkTeaLoading = false;
document.getElementById('milkTeaLoading').style.display = 'none';
}
+63
View File
@@ -0,0 +1,63 @@
let currentSort = 'total_income';
function switchSort(el) {
document.querySelectorAll('.sort-btn').forEach(b => b.classList.remove('active'));
el.classList.add('active');
currentSort = el.dataset.sort;
}
async function loadRankingDetail() {
const startDate = document.getElementById('rankStartDate').value;
const endDate = document.getElementById('rankEndDate').value;
let url = API + '/api/stats/boss-ranking?sortBy=' + currentSort;
if (startDate) url += '&startDate=' + startDate;
if (endDate) {
const d = new Date(endDate);
d.setDate(d.getDate() + 1);
url += '&endDate=' + formatLocalDate(d);
}
try {
const res = await fetch(url, { headers: headers() });
if (!res.ok) return;
const rows = await res.json();
const container = document.getElementById('rankingDetailList');
if (rows.length === 0) {
container.innerHTML = '<div class="ranking-empty">暂无数据</div>';
return;
}
if (currentSort === 'dispatch_count') {
const max = Math.max(...rows.map(r => r.dispatch_count), 1);
container.innerHTML = rows.map((r, i) => {
const pct = Math.max((r.dispatch_count / max) * 100, 2);
return `<div class="hbar-row" onclick="openBossDetail('${r.boss.replace(/'/g, "\\'")}', 'rankingPage')">
<div class="hbar-index ${i < 3 ? 'top' : ''}">${i + 1}</div>
<div class="hbar-label" title="${r.boss}">${r.boss}</div>
<div class="hbar-track"><div class="hbar-fill" style="width:${pct}%"></div></div>
<div class="hbar-value">${r.dispatch_count}单</div>
</div>`;
}).join('');
} else if (currentSort === 'take_count') {
const max = Math.max(...rows.map(r => r.take_count), 1);
container.innerHTML = rows.map((r, i) => {
const pct = Math.max((r.take_count / max) * 100, 2);
return `<div class="hbar-row" onclick="openBossDetail('${r.boss.replace(/'/g, "\\'")}', 'rankingPage')">
<div class="hbar-index ${i < 3 ? 'top' : ''}">${i + 1}</div>
<div class="hbar-label" title="${r.boss}">${r.boss}</div>
<div class="hbar-track"><div class="hbar-fill" style="width:${pct}%"></div></div>
<div class="hbar-value">${r.take_count}单</div>
</div>`;
}).join('');
} else {
const max = Math.max(...rows.map(r => r.total_income), 1);
container.innerHTML = rows.map((r, i) => {
const pct = Math.max((r.total_income / max) * 100, 2);
return `<div class="hbar-row" onclick="openBossDetail('${r.boss.replace(/'/g, "\\'")}', 'rankingPage')">
<div class="hbar-index ${i < 3 ? 'top' : ''}">${i + 1}</div>
<div class="hbar-label" title="${r.boss}">${r.boss}</div>
<div class="hbar-track"><div class="hbar-fill" style="width:${pct}%"></div></div>
<div class="hbar-value">${r.total_income.toFixed(2)}</div>
</div>`;
}).join('');
}
} catch (e) { console.error(e); }
}
+174
View File
@@ -0,0 +1,174 @@
function switchRecordType(type) {
currentType = type;
document.querySelectorAll('.type-btn').forEach((b, i) => {
b.classList.toggle('active', (type === 'income' && i === 0) || (type === 'expense' && i === 1));
});
document.getElementById('incomeCats').style.display = type === 'income' ? 'grid' : 'none';
document.getElementById('expenseCats').style.display = type === 'expense' ? 'grid' : 'none';
const firstCat = type === 'income'
? document.querySelector('#incomeCats .category-item')
: document.querySelector('#expenseCats .category-item');
const catName = type === 'income' ? '接单' : '红包支出';
selectCategory(firstCat, catName);
}
function selectCategory(el, cat) {
currentCategory = cat;
el.parentElement.querySelectorAll('.category-item').forEach(c => c.classList.remove('active'));
el.classList.add('active');
renderForm();
}
function renderForm() {
const form = document.getElementById('recordForm');
const now = new Date();
const defaultTime = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
let html = '';
if (currentCategory === '接单') {
html = `
<div class="form-group"><label>单数</label><input type="number" id="fQuantity" placeholder="请输入单数" oninput="calcAmount()"></div>
<div class="form-group"><label>单价(元)</label><input type="number" step="0.01" id="fPrice" placeholder="请输入单价" oninput="calcAmount()"></div>
<div class="form-group"><label>老板</label><input type="text" id="fBoss" placeholder="请输入老板名称"></div>
<div class="form-group"><label>一起的陪玩(可选)</label><input type="text" id="fPartner" placeholder="请输入陪玩名称"></div>
<div class="form-group"><label>时间</label><input type="datetime-local" id="fTime" value="${defaultTime}"></div>
<div class="computed-amount">预计收入<div class="total" id="calcTotal">0.00</div></div>
<button class="submit-btn" onclick="submitRecord()">保存记录</button>
`;
} else if (currentCategory === '派单') {
html = `
<div class="form-group"><label>单数</label><input type="number" id="fQuantity" placeholder="请输入单数" oninput="calcAmount()"></div>
<div class="form-group"><label>单价(元)</label><input type="number" step="0.01" id="fPrice" placeholder="请输入单价"></div>
<div class="form-group"><label>返点(元)</label><input type="number" step="0.01" id="fRebate" placeholder="请输入返点" oninput="calcAmount()"></div>
<div class="form-group"><label>老板</label><input type="text" id="fBoss" placeholder="请输入老板名称"></div>
<div class="form-group"><label>负责打单的陪玩</label><input type="text" id="fPartner" placeholder="请输入陪玩名称"></div>
<div class="form-group"><label>时间</label><input type="datetime-local" id="fTime" value="${defaultTime}"></div>
<div class="computed-amount">预计收入<div class="total" id="calcTotal">0.00</div></div>
<button class="submit-btn" onclick="submitRecord()">保存记录</button>
`;
} else if (currentCategory === '红包收入') {
html = `
<div class="form-group"><label>红包金额(元)</label><input type="number" step="0.01" id="fAmount" placeholder="请输入金额"></div>
<div class="form-group"><label>红包来源</label><input type="text" id="fSource" placeholder="发红包人的名称"></div>
<div class="form-group"><label>时间</label><input type="datetime-local" id="fTime" value="${defaultTime}"></div>
<button class="submit-btn" onclick="submitRecord()">保存记录</button>
`;
} else if (currentCategory === '红包支出') {
html = `
<div class="form-group"><label>红包金额(元)</label><input type="number" step="0.01" id="fAmount" placeholder="请输入金额"></div>
<div class="form-group"><label>红包目的地</label><input type="text" id="fDest" placeholder="收红包人的名称"></div>
<div class="form-group"><label>时间</label><input type="datetime-local" id="fTime" value="${defaultTime}"></div>
<button class="submit-btn" onclick="submitRecord()">保存记录</button>
`;
} else if (currentCategory === '其他支出') {
html = `
<div class="form-group"><label>金额(元)</label><input type="number" step="0.01" id="fAmount" placeholder="请输入金额"></div>
<div class="form-group"><label>支出目的地</label><input type="text" id="fDest" placeholder="收款人名称"></div>
<div class="form-group"><label>备注(可选)</label><input type="text" id="fNote" placeholder="备注信息"></div>
<div class="form-group"><label>时间</label><input type="datetime-local" id="fTime" value="${defaultTime}"></div>
<button class="submit-btn" onclick="submitRecord()">保存记录</button>
`;
} else if (currentCategory === '奶茶') {
html = `
<div class="form-group"><label>金额(元)</label><input type="number" step="0.01" id="fAmount" placeholder="请输入金额"></div>
<div class="form-group"><label>来源</label><input type="text" id="fSource" placeholder="奶茶来源"></div>
<div class="form-group"><label>时间</label><input type="datetime-local" id="fTime" value="${defaultTime}"></div>
<button class="submit-btn" onclick="submitRecord()">保存记录</button>
`;
} else if (currentCategory === '比心') {
html = `
<div class="form-group"><label>金额(元)</label><input type="number" step="0.01" id="fAmount" placeholder="请输入金额"></div>
<div class="form-group"><label>用途</label><input type="text" id="fDest" placeholder="请输入用途"></div>
<div class="form-group"><label>时间</label><input type="datetime-local" id="fTime" value="${defaultTime}"></div>
<button class="submit-btn" onclick="submitRecord()">保存记录</button>
`;
}
form.innerHTML = html;
// 绑定自动补全
if (currentCategory === '接单' || currentCategory === '派单') {
acSetup('fBoss', 'boss');
acSetup('fPartner', 'partner');
} else if (currentCategory === '红包收入' || currentCategory === '奶茶') {
acSetup('fSource', 'source');
} else if (currentCategory === '红包支出' || currentCategory === '其他支出') {
acSetup('fDest', 'destination');
} else if (currentCategory === '比心') {
acSetup('fDest', 'destination');
}
}
function calcAmount() {
const q = parseFloat(document.getElementById('fQuantity')?.value) || 0;
let price;
if (currentCategory === '派单') {
price = parseFloat(document.getElementById('fRebate')?.value) || 0;
} else {
price = parseFloat(document.getElementById('fPrice')?.value) || 0;
}
const el = document.getElementById('calcTotal');
if (el) el.textContent = '' + (q * price).toFixed(2);
}
async function submitRecord() {
let body = { type: currentType, category: currentCategory };
const fTime = document.getElementById('fTime')?.value;
if (fTime) body.created_at = new Date(fTime).toISOString();
if (currentCategory === '接单' || currentCategory === '派单') {
const quantity = parseInt(document.getElementById('fQuantity').value);
const unit_price = parseFloat(document.getElementById('fPrice').value);
const boss = document.getElementById('fBoss').value.trim();
const partner = document.getElementById('fPartner')?.value.trim() || '';
if (currentCategory === '派单') {
const rebate = parseFloat(document.getElementById('fRebate').value);
if (!quantity || !unit_price || !rebate || !boss) { showToast('请填写完整信息'); return; }
body.quantity = quantity;
body.unit_price = unit_price;
body.rebate = rebate;
body.amount = quantity * rebate;
} else {
if (!quantity || !unit_price || !boss) { showToast('请填写完整信息'); return; }
body.quantity = quantity;
body.unit_price = unit_price;
body.amount = quantity * unit_price;
}
body.boss = boss;
body.partner = partner;
} else if (currentCategory === '红包收入' || currentCategory === '奶茶') {
const amount = parseFloat(document.getElementById('fAmount').value);
const source = document.getElementById('fSource').value.trim();
if (!amount || !source) { showToast('请填写完整信息'); return; }
body.amount = amount;
body.source = source;
body.boss = source; // 红包来源就是老板,同步设置 boss 字段
} else if (currentCategory === '红包支出' || currentCategory === '其他支出' || currentCategory === '比心') {
const amount = parseFloat(document.getElementById('fAmount').value);
if (!amount) { showToast('请填写完整信息'); return; }
body.amount = amount;
if (currentCategory === '比心') {
const dest = document.getElementById('fDest').value.trim();
body.destination = dest || '比心';
} else {
const dest = document.getElementById('fDest').value.trim();
if (!dest) { showToast('请填写完整信息'); return; }
body.destination = dest;
}
body.note = document.getElementById('fNote')?.value.trim() || '';
}
try {
const res = await fetch(API + '/api/records', {
method: 'POST',
headers: headers(),
body: JSON.stringify(body)
});
if (!res.ok) { showToast('保存失败'); return; }
showToast('保存成功');
acInvalidateCache();
setTimeout(() => showPage('homePage'), 1000);
} catch (e) {
showToast('网络错误');
}
}
+485
View File
@@ -0,0 +1,485 @@
async function loadStats() {
try {
const res = await fetch(API + '/api/stats/monthly?year=' + currentYear + '&month=' + currentMonth, { headers: headers() });
if (!res.ok) return;
const s = await res.json();
document.getElementById('takeCount').textContent = s.take_order_count;
document.getElementById('dispatchCount').textContent = s.dispatch_order_count;
document.getElementById('takeIncome').textContent = '' + s.take_order_income.toFixed(2);
document.getElementById('dispatchIncome').textContent = '' + s.dispatch_order_income.toFixed(2);
document.getElementById('redEnvelopeCount').textContent = s.redEnvelope_count || 0;
document.getElementById('redEnvelopeIncome').textContent = '' + (s.redEnvelope_income || 0).toFixed(2);
document.getElementById('milkTeaCount').textContent = s.milkTea_count || 0;
document.getElementById('milkTeaIncome').textContent = '' + (s.milkTea_income || 0).toFixed(2);
document.getElementById('totalIncome').textContent = '' + s.total_income.toFixed(2);
document.getElementById('totalExpense').textContent = '' + s.total_expense.toFixed(2);
document.getElementById('netIncome').textContent = '' + (s.total_income - s.total_expense).toFixed(2);
loadBossRankingPreview();
loadPartnerRankingPreview();
loadWeeklyChart();
} catch (e) { console.error(e); }
}
async function loadWeeklyChart() {
try {
const res = await fetch(API + '/api/stats/daily-income', { headers: headers() });
if (!res.ok) return;
const days = await res.json();
const container = document.getElementById('weeklyChartBars');
const max = Math.max(...days.map(d => d.income), 1);
container.innerHTML = days.map(d => {
const pct = Math.max((d.income / max) * 100, 3);
const label = d.date.slice(5).replace('-', '/');
const amount = d.income > 0 ? '' + d.income.toFixed(0) : '0';
return `<div class="weekly-bar-col" onclick="openDailyDetail('${d.date}')">
<span class="weekly-bar-amount">${amount}</span>
<div class="weekly-bar" style="height:${pct}%"></div>
<span class="weekly-bar-date">${label}</span>
</div>`;
}).join('');
} catch (e) { console.error(e); }
}
let currentDailyDate = '';
async function openDailyDetail(date) {
currentDailyDate = date;
document.getElementById('dailyDetailTitle').textContent = date + ' 收入';
document.getElementById('dailyNavDate').textContent = date;
document.getElementById('dailySummary').innerHTML = '<div class="ranking-empty">加载中...</div>';
document.getElementById('dailyDetailList').innerHTML = '';
if (!document.getElementById('dailyDetailPage').classList.contains('active')) {
showPage('dailyDetailPage');
}
try {
const res = await fetch(API + '/api/stats/daily-detail?date=' + date, { headers: headers() });
if (!res.ok) return;
const data = await res.json();
document.getElementById('dailySummary').innerHTML = `
<div class="daily-summary-amount">${data.total_income.toFixed(2)}</div>
<div class="daily-summary-label">当日总收入</div>
`;
const container = document.getElementById('dailyDetailList');
if (data.records.length === 0) {
container.innerHTML = '<div class="ranking-empty">当日暂无收入记录</div>';
return;
}
container.innerHTML = data.records.map(r => {
const time = formatLocalTime(r.created_at);
const displayCategory = r.category === '红包收入' ? '红包' : (r.category || '-');
return `<div class="order-item" onclick='openEditModal(${JSON.stringify(r).replace(/'/g, "&#39;")})'>
<div class="order-item-top">
<span class="order-item-boss">${displayCategory}${r.boss ? ' · ' + r.boss : ''}</span>
<span class="order-item-amount">${(r.amount || 0).toFixed(2)}</span>
</div>
<div class="order-item-bottom">
<span>${r.quantity ? r.quantity + '单 × ' + (r.category === '派单' ? (r.rebate || r.amount / r.quantity).toFixed(2) + '(单价' + (r.unit_price || 0).toFixed(2) + '' : (r.unit_price || 0).toFixed(2)) : (r.source || '')}</span>
<span>${time}${r.partner ? ' · ' + r.partner : ''}</span>
</div>
</div>`;
}).join('');
} catch (e) { console.error(e); }
}
function switchDailyDate(offset) {
const d = new Date(currentDailyDate);
d.setDate(d.getDate() + offset);
openDailyDetail(formatLocalDate(d));
}
let monthlyDetailYear, monthlyDetailMonth;
function openMonthlyDetail(type) {
monthlyDetailYear = currentYear;
monthlyDetailMonth = currentMonth;
loadMonthlyDetail(type);
}
function switchMonthlyDetail(type, offset) {
monthlyDetailMonth += offset;
if (monthlyDetailMonth > 12) { monthlyDetailMonth = 1; monthlyDetailYear++; }
if (monthlyDetailMonth < 1) { monthlyDetailMonth = 12; monthlyDetailYear--; }
loadMonthlyDetail(type);
}
function openYearlyIncome() {
loadYearlyNetIncome();
}
async function loadYearlyNetIncome() {
document.getElementById('yearlyNetIncomeSummary').innerHTML = '<div class="ranking-empty">加载中...</div>';
document.getElementById('yearlyNetIncomeList').innerHTML = '';
if (!document.getElementById('yearlyNetIncomePage').classList.contains('active')) {
showPage('yearlyNetIncomePage');
}
try {
const res = await fetch(API + '/api/stats/yearly-net-income', { headers: headers() });
if (!res.ok) return;
const data = await res.json();
const grandNetIncome = (data.grandTotal.total_income || 0) - (data.grandTotal.total_expense || 0);
const grandColor = grandNetIncome >= 0 ? '#27ae60' : '#e74c3c';
document.getElementById('yearlyNetIncomeSummary').innerHTML = `
<div class="daily-summary-amount" style="color:${grandColor}">${grandNetIncome.toFixed(2)}</div>
<div class="daily-summary-label">累计净收入</div>
`;
const container = document.getElementById('yearlyNetIncomeList');
const monthNames = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'];
if (data.yearlyStats.length === 0) {
container.innerHTML = '<div class="ranking-empty">暂无数据</div>';
return;
}
container.innerHTML = data.yearlyStats.map(y => {
const year = y.year;
const income = y.total_income || 0;
const expense = y.total_expense || 0;
const net = income - expense;
const netColor = net >= 0 ? '#27ae60' : '#e74c3c';
const monthlyData = data.monthlyData[year] || [];
const monthlyHtml = monthlyData.map(m => {
const mIncome = m.total_income || 0;
const mExpense = m.total_expense || 0;
const mNet = mIncome - mExpense;
const mColor = mNet >= 0 ? '#27ae60' : '#e74c3c';
return `<div style="display:flex;justify-content:space-between;padding:12px 16px;border-bottom:1px solid #f0f0f0;font-size:14px;">
<span>${monthNames[parseInt(m.month) - 1]}</span>
<span style="color:${mColor}">${mNet.toFixed(2)}</span>
</div>`;
}).join('');
return `<div class="order-item" style="padding:0;">
<div class="order-item-top" style="padding:12px;">
<span class="order-item-boss">${year}年</span>
<span class="order-item-amount" style="color:${netColor}">${net.toFixed(2)}</span>
</div>
<div class="order-item-bottom" style="padding:0 12px 12px;">
<span>收入: ${income.toFixed(2)} | 支出: ${expense.toFixed(2)}</span>
</div>
<div style="border-top:1px solid #eee;">${monthlyHtml}</div>
</div>`;
}).join('');
} catch (e) { console.error(e); }
}
async function loadMonthlyDetail(type) {
const pageId = type === 'income' ? 'monthlyIncomeDetailPage' : 'monthlyExpenseDetailPage';
const titleId = type === 'income' ? 'monthlyIncomeTitle' : 'monthlyExpenseTitle';
const navId = type === 'income' ? 'monthlyIncomeNav' : 'monthlyExpenseNav';
const summaryId = type === 'income' ? 'monthlyIncomeSummary' : 'monthlyExpenseSummary';
const listId = type === 'income' ? 'monthlyIncomeList' : 'monthlyExpenseList';
const label = type === 'income' ? '收入' : '支出';
document.getElementById(titleId).textContent = `${monthlyDetailYear}${monthlyDetailMonth}${label}`;
document.getElementById(navId).textContent = `${monthlyDetailYear}${monthlyDetailMonth}`;
document.getElementById(summaryId).innerHTML = '<div class="ranking-empty">加载中...</div>';
document.getElementById(listId).innerHTML = '';
if (!document.getElementById(pageId).classList.contains('active')) {
showPage(pageId);
}
try {
const res = await fetch(API + '/api/stats/monthly-records?type=' + type + '&year=' + monthlyDetailYear + '&month=' + monthlyDetailMonth, { headers: headers() });
if (!res.ok) return;
const data = await res.json();
const color = type === 'income' ? '#27ae60' : '#e74c3c';
document.getElementById(summaryId).innerHTML = `
<div class="daily-summary-amount" style="color:${color}">${data.total.toFixed(2)}</div>
<div class="daily-summary-label">当月总${label}</div>
`;
const container = document.getElementById(listId);
if (data.records.length === 0) {
container.innerHTML = '<div class="ranking-empty">当月暂无' + label + '记录</div>';
return;
}
const grouped = {};
data.records.forEach(r => {
const date = formatLocalDate(r.created_at);
if (!grouped[date]) grouped[date] = [];
grouped[date].push(r);
});
let html = '';
for (const [date, records] of Object.entries(grouped)) {
html += `<div class="order-date-group"><div class="order-date-label">${date}</div>`;
records.forEach(r => {
const time = formatLocalTime(r.created_at);
const displayCategory = r.category === '红包收入' ? '红包' : (r.category || '-');
html += `<div class="order-item" onclick='openEditModal(${JSON.stringify(r).replace(/'/g, "&#39;")})'>
<div class="order-item-top">
<span class="order-item-boss">${displayCategory}${r.boss ? ' · ' + r.boss : r.source ? ' · ' + r.source : r.destination ? ' · ' + r.destination : ''}</span>
<span class="order-item-amount">${type === 'expense' ? '-' : ''}${(r.amount || 0).toFixed(2)}</span>
</div>
<div class="order-item-bottom">
<span>${r.quantity ? r.quantity + '单 × ' + (r.category === '派单' ? (r.rebate || r.amount / r.quantity).toFixed(2) + '(单价' + (r.unit_price || 0).toFixed(2) + '' : (r.unit_price || 0).toFixed(2)) : (r.note || '')}</span>
<span>${time}${r.partner ? ' · ' + r.partner : ''}</span>
</div>
</div>`;
});
html += '</div>';
}
container.innerHTML = html;
} catch (e) { console.error(e); }
}
async function loadBossRankingPreview() {
try {
const res = await fetch(API + '/api/stats/boss-ranking/preview?year=' + currentYear + '&month=' + currentMonth, { headers: headers() });
if (!res.ok) return;
const rows = await res.json();
const container = document.getElementById('rankingPreviewList');
if (rows.length === 0) {
container.innerHTML = '<div class="ranking-empty">暂无数据</div>';
return;
}
const max = Math.max(...rows.map(r => r.total_income), 1);
container.innerHTML = rows.map((r, i) => {
const pct = Math.max((r.total_income / max) * 100, 2);
return `<div class="hbar-row" onclick="openBossDetail('${r.boss.replace(/'/g, "\\'")}', 'homePage')">
<div class="hbar-index ${i < 3 ? 'top' : ''}">${i + 1}</div>
<div class="hbar-label" title="${r.boss}">${r.boss}</div>
<div class="hbar-track"><div class="hbar-fill" style="width:${pct}%"></div></div>
<div class="hbar-value">${r.total_income.toFixed(2)}</div>
</div>`;
}).join('');
} catch (e) { console.error(e); }
}
let currentBossName = '';
let bossDetailFrom = 'homePage';
function openBossDetail(boss, from) {
currentBossName = boss;
bossDetailFrom = from || 'homePage';
loadBossDetail();
}
function bossDetailGoBack() {
showPage(bossDetailFrom);
}
async function loadBossDetail() {
document.getElementById('bossDetailTitle').textContent = currentBossName + ' 交易记录';
document.getElementById('bossDetailSummary').innerHTML = '<div class="ranking-empty">加载中...</div>';
document.getElementById('bossDetailList').innerHTML = '';
showPage('bossDetailPage');
try {
const res = await fetch(API + '/api/stats/boss-records?boss=' + encodeURIComponent(currentBossName), { headers: headers() });
if (!res.ok) return;
const data = await res.json();
document.getElementById('bossDetailSummary').innerHTML = `
<div style="display:flex;justify-content:space-around;flex-wrap:wrap;gap:8px">
<div style="text-align:center">
<div class="daily-summary-amount" style="font-size:24px;color:#e74c3c">${data.boss_total_expense.toFixed(2)}</div>
<div class="daily-summary-label">老板总支出</div>
</div>
<div style="text-align:center">
<div class="daily-summary-amount" style="font-size:24px;color:#27ae60">${data.my_income.toFixed(2)}</div>
<div class="daily-summary-label">我的总收入</div>
</div>
</div>
`;
const container = document.getElementById('bossDetailList');
if (data.records.length === 0) {
container.innerHTML = '<div class="ranking-empty">暂无交易记录</div>';
return;
}
const grouped = {};
data.records.forEach(r => {
const d = new Date(r.created_at);
const key = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0');
if (!grouped[key]) grouped[key] = { records: [], total: 0 };
grouped[key].records.push(r);
grouped[key].total += r.amount || 0;
});
let html = '';
for (const [month, group] of Object.entries(grouped)) {
html += `<div class="order-date-group"><div class="order-date-label">${month} 收入 ${group.total.toFixed(2)}</div>`;
group.records.forEach(r => {
const time = formatLocalDate(r.created_at) + ' ' + formatLocalTime(r.created_at);
const displayCategory = r.category === '红包收入' ? '红包' : r.category;
html += `<div class="order-item" onclick='openEditModal(${JSON.stringify(r).replace(/'/g, "&#39;")})'>
<div class="order-item-top">
<span class="order-item-boss">${displayCategory}${r.partner ? ' · ' + r.partner : ''}</span>
<span class="order-item-amount">${(r.amount || 0).toFixed(2)}</span>
</div>
<div class="order-item-bottom">
<span>${r.quantity ? r.quantity + '单 × ' + (r.category === '派单' ? (r.rebate || r.amount / r.quantity).toFixed(2) + '(单价' + (r.unit_price || 0).toFixed(2) + '' : (r.unit_price || 0).toFixed(2)) : (r.note || '')}</span>
<span>${time}</span>
</div>
</div>`;
});
html += '</div>';
}
container.innerHTML = html;
} catch (e) { console.error(e); }
}
async function loadPartnerRankingPreview() {
try {
const res = await fetch(API + '/api/stats/partner-ranking/preview?year=' + currentYear + '&month=' + currentMonth, { headers: headers() });
if (!res.ok) return;
const rows = await res.json();
const container = document.getElementById('partnerRankingPreviewList');
if (rows.length === 0) {
container.innerHTML = '<div class="ranking-empty">暂无数据</div>';
return;
}
const max = Math.max(...rows.map(r => r.dispatch_count), 1);
container.innerHTML = rows.map((r, i) => {
const pct = Math.max((r.dispatch_count / max) * 100, 2);
return `<div class="hbar-row" onclick="openPartnerDetail('${r.partner.replace(/'/g, "\\'")}', 'homePage')">
<div class="hbar-index ${i < 3 ? 'top' : ''}">${i + 1}</div>
<div class="hbar-label" title="${r.partner}">${r.partner}</div>
<div class="hbar-track"><div class="hbar-fill" style="width:${pct}%"></div></div>
<div class="hbar-value">${r.dispatch_count}单</div>
</div>`;
}).join('');
} catch (e) { console.error(e); }
}
function openPartnerRankingPage() {
const now = new Date();
const y = now.getFullYear();
const m = String(now.getMonth() + 1).padStart(2, '0');
document.getElementById('partnerRankStartDate').value = y + '-' + m + '-01';
document.getElementById('partnerRankEndDate').value = y + '-' + m + '-' + String(now.getDate()).padStart(2, '0');
showPage('partnerRankingPage');
loadPartnerRankingDetail();
}
async function loadPartnerRankingDetail() {
const startDate = document.getElementById('partnerRankStartDate').value;
const endDate = document.getElementById('partnerRankEndDate').value;
let url = API + '/api/stats/partner-ranking';
const params = [];
if (startDate) params.push('startDate=' + startDate);
if (endDate) {
const d = new Date(endDate);
d.setDate(d.getDate() + 1);
params.push('endDate=' + formatLocalDate(d));
}
if (params.length) url += '?' + params.join('&');
console.log('partner-ranking url:', url);
try {
const res = await fetch(url, { headers: headers() });
console.log('partner-ranking res.ok:', res.ok);
if (!res.ok) return;
const data = await res.json();
console.log('partner-ranking data:', data);
const rows = data.rows || [];
console.log('rows:', rows);
const summary = data.summary || { total_partner_income: 0, total_rebate_income: 0, total_milkTea_income: 0 };
// 计算派单总数(从列表)
const totalDispatch = rows.reduce((sum, r) => sum + (r.dispatch_count || 0), 0);
console.log('totalDispatch:', totalDispatch);
// 更新统计卡片
document.getElementById('partnerTotalDispatchCount').textContent = totalDispatch;
document.getElementById('totalPartnerIncome').textContent = (summary.total_partner_income || 0).toFixed(2);
document.getElementById('totalRebateIncome').textContent = summary.total_rebate_income.toFixed(2);
document.getElementById('totalMilkTeaIncome').textContent = (summary.total_milkTea_income || 0).toFixed(2);
const container = document.getElementById('partnerRankingDetailList');
if (rows.length === 0) {
container.innerHTML = '<div class="ranking-empty">暂无数据</div>';
return;
}
const max = Math.max(...rows.map(r => r.dispatch_count), 1);
container.innerHTML = rows.map((r, i) => {
const pct = Math.max((r.dispatch_count / max) * 100, 2);
return `<div class="hbar-row" onclick="openPartnerDetail('${r.partner.replace(/'/g, "\\'")}', 'partnerRankingPage')">
<div class="hbar-index ${i < 3 ? 'top' : ''}">${i + 1}</div>
<div class="hbar-label" title="${r.partner}">${r.partner}</div>
<div class="hbar-track"><div class="hbar-fill" style="width:${pct}%"></div></div>
<div class="hbar-value">${r.dispatch_count}单</div>
</div>`;
}).join('');
} catch (e) { console.error(e); }
}
let currentPartnerName = '';
let partnerDetailFrom = 'homePage';
function openPartnerDetail(partner, from) {
currentPartnerName = partner;
partnerDetailFrom = from || 'homePage';
loadPartnerDetail();
}
function partnerDetailGoBack() {
showPage(partnerDetailFrom);
}
async function loadPartnerDetail() {
document.getElementById('partnerDetailTitle').textContent = currentPartnerName + ' 交易记录';
document.getElementById('partnerDetailSummary').innerHTML = '<div class="ranking-empty">加载中...</div>';
document.getElementById('partnerDetailList').innerHTML = '';
showPage('partnerDetailPage');
try {
const res = await fetch(API + '/api/stats/partner-records?partner=' + encodeURIComponent(currentPartnerName), { headers: headers() });
if (!res.ok) return;
const data = await res.json();
document.getElementById('partnerDetailSummary').innerHTML = `
<div style="display:flex;justify-content:space-around;flex-wrap:wrap;gap:8px">
<div style="text-align:center">
<div class="daily-summary-amount" style="font-size:24px">${data.dispatch_count}</div>
<div class="daily-summary-label">总派单数</div>
</div>
<div style="text-align:center">
<div class="daily-summary-amount" style="font-size:24px;color:#e67e22">${data.spread_income.toFixed(2)}</div>
<div class="daily-summary-label">陪玩总收入</div>
</div>
<div style="text-align:center">
<div class="daily-summary-amount" style="font-size:24px;color:#27ae60">${data.rebate_income.toFixed(2)}</div>
<div class="daily-summary-label">总返点收入</div>
</div>
<div style="text-align:center">
<div class="daily-summary-amount" style="font-size:24px;color:#3498db">${data.other_income.toFixed(2)}</div>
<div class="daily-summary-label">红包及其他</div>
</div>
</div>
`;
const container = document.getElementById('partnerDetailList');
if (data.records.length === 0) {
container.innerHTML = '<div class="ranking-empty">暂无交易记录</div>';
return;
}
const grouped = {};
data.records.forEach(r => {
const d = new Date(r.created_at);
const key = d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0');
if (!grouped[key]) grouped[key] = { records: [], total: 0 };
grouped[key].records.push(r);
grouped[key].total += r.amount || 0;
});
let html = '';
for (const [month, group] of Object.entries(grouped)) {
html += `<div class="order-date-group"><div class="order-date-label">${month} 收入 ${group.total.toFixed(2)}</div>`;
group.records.forEach(r => {
const time = formatLocalDate(r.created_at) + ' ' + formatLocalTime(r.created_at);
const displayCategory = r.category === '红包收入' ? '红包' : r.category;
html += `<div class="order-item" onclick='openEditModal(${JSON.stringify(r).replace(/'/g, "&#39;")})'>
<div class="order-item-top">
<span class="order-item-boss">${displayCategory}${r.boss ? ' · ' + r.boss : ''}</span>
<span class="order-item-amount">${(r.amount || 0).toFixed(2)}</span>
</div>
<div class="order-item-bottom">
<span>${r.quantity ? r.quantity + '单 × ' + (r.category === '派单' ? (r.rebate || r.amount / r.quantity).toFixed(2) + '(单价' + (r.unit_price || 0).toFixed(2) + '' : (r.unit_price || 0).toFixed(2)) : (r.source || '')}</span>
<span>${time}</span>
</div>
</div>`;
});
html += '</div>';
}
container.innerHTML = html;
} catch (e) { console.error(e); }
}