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
+760
View File
@@ -0,0 +1,760 @@
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f5f5f5;
max-width: 480px;
margin: 0 auto;
min-height: 100vh;
position: relative;
}
/* 登录页 */
.page { display: none; }
.page.active { display: flex; flex-direction: column; }
#loginPage {
min-height: 100vh;
justify-content: center;
align-items: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 20px;
}
.login-box {
background: #fff;
border-radius: 16px;
padding: 40px 30px;
width: 100%;
max-width: 360px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}
.login-box h1 {
text-align: center;
color: #333;
margin-bottom: 30px;
font-size: 22px;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
color: #666;
margin-bottom: 6px;
font-size: 14px;
}
.form-group input {
width: 100%;
padding: 12px 16px;
border: 1px solid #ddd;
border-radius: 10px;
font-size: 16px;
outline: none;
transition: border-color 0.2s;
}
.form-group input:focus {
border-color: #667eea;
}
.btn {
width: 100%;
padding: 14px;
border: none;
border-radius: 10px;
font-size: 16px;
cursor: pointer;
transition: opacity 0.2s;
}
.btn:active { opacity: 0.8; }
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
}
.login-error {
color: #e74c3c;
text-align: center;
margin-top: 12px;
font-size: 14px;
min-height: 20px;
}
/* 首页 */
#homePage {
min-height: 100vh;
background: #f5f5f5;
}
.home-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
padding: 16px 20px;
display: flex;
justify-content: center;
align-items: center;
}
.month-selector {
display: flex; align-items: center; gap: 4px;
font-size: 16px; cursor: pointer; font-weight: 600;
}
.month-selector svg { width: 16px; height: 16px; }
.tab-content { padding: 16px 20px 100px; }
.tab-panel { display: none; }
.tab-panel.active { display: block; }
/* 统计卡片 */
.stat-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
margin-top: 8px;
}
.sub-income {
font-size: 15px;
color: #27ae60;
margin-top: 4px;
font-weight: 600;
}
.stat-card {
background: #fff;
border-radius: 12px;
padding: 16px;
box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.stat-card .label {
font-size: 13px;
color: #999;
margin-bottom: 8px;
}
.stat-card .value {
font-size: 22px;
font-weight: 700;
color: #333;
}
.stat-card .value.income { color: #27ae60; }
.stat-card .value.expense { color: #e74c3c; }
.stat-card.full { grid-column: 1 / -1; }
.stat-summary {
display: flex;
justify-content: space-between;
background: #fff;
border-radius: 12px;
padding: 16px;
margin-top: 12px;
box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.stat-summary .item { text-align: center; flex: 1; }
.stat-summary .item .label { font-size: 13px; color: #999; margin-bottom: 4px; }
.stat-summary .item .val { font-size: 20px; font-weight: 700; }
.stat-summary .item .val.green { color: #27ae60; }
.stat-summary .item .val.red { color: #e74c3c; }
.stat-summary .item .val.orange { color: #f39c12; }
.stat-summary .item .val.purple { color: #9b59b6; }
/* 最近7天收入柱状图 */
.weekly-chart {
background: #fff;
border-radius: 12px;
padding: 16px;
margin-top: 12px;
box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.weekly-chart-title {
font-size: 15px;
font-weight: 600;
color: #333;
margin-bottom: 16px;
}
.weekly-chart-bars {
display: flex;
align-items: flex-end;
justify-content: space-between;
height: 150px;
gap: 8px;
}
.weekly-bar-col {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
height: 100%;
justify-content: flex-end;
cursor: pointer;
}
.weekly-bar-col:active { opacity: 0.7; }
.weekly-bar-amount {
font-size: 10px;
color: #667eea;
font-weight: 600;
margin-bottom: 4px;
white-space: nowrap;
}
.weekly-bar {
width: 100%;
max-width: 32px;
border-radius: 6px 6px 0 0;
background: linear-gradient(180deg, #667eea 0%, #764ba2 100%);
min-height: 4px;
transition: height 0.3s ease;
}
.weekly-bar-date {
font-size: 11px;
color: #999;
margin-top: 6px;
}
/* 日收入详情页 */
#dailyDetailPage { min-height: 100vh; background: #f5f5f5; }
.daily-nav {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 20px 0;
}
.daily-nav-btn {
background: none; border: none; color: #667eea;
font-size: 14px; cursor: pointer; padding: 6px 0;
}
.daily-nav-btn:active { opacity: 0.6; }
.daily-nav-date {
font-size: 15px; font-weight: 600; color: #333;
}
.daily-summary {
background: #fff;
border-radius: 12px;
padding: 24px 16px;
margin: 16px 20px;
text-align: center;
box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.daily-summary-amount {
font-size: 32px;
font-weight: 700;
color: #27ae60;
}
.daily-summary-label {
font-size: 13px;
color: #999;
margin-top: 4px;
}
/* 我的页面 */
.profile-card {
background: #fff;
border-radius: 12px;
padding: 24px;
text-align: center;
box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.profile-card .avatar {
width: 64px;
height: 64px;
border-radius: 50%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-size: 28px;
margin: 0 auto 12px;
}
.profile-card .name { font-size: 18px; font-weight: 600; color: #333; }
.refresh-btn {
margin-top: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
color: #fff;
border-radius: 12px;
padding: 12px;
width: 100%;
font-size: 15px;
cursor: pointer;
}
.refresh-btn:active { opacity: 0.8; }
.logout-btn {
margin-top: 20px;
background: #fff;
border: 1px solid #e74c3c;
color: #e74c3c;
border-radius: 12px;
padding: 12px;
width: 100%;
font-size: 15px;
cursor: pointer;
}
.logout-btn:active { background: #ffeaea; }
/* 底部导航 */
.bottom-bar {
position: fixed;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 100%;
max-width: 480px;
background: #fff;
padding: 6px 20px 18px;
box-shadow: 0 -2px 10px rgba(0,0,0,0.05);
display: flex;
justify-content: space-around;
align-items: flex-end;
z-index: 10;
}
.nav-item {
display: flex; flex-direction: column; align-items: center;
cursor: pointer; padding: 4px 12px; color: #999; font-size: 11px; gap: 2px;
transition: color 0.2s;
}
.nav-item svg { width: 24px; height: 24px; }
.nav-item.active { color: #667eea; }
.record-btn {
width: 50px;
height: 50px;
border-radius: 50%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
color: #fff;
font-size: 28px;
cursor: pointer;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
display: flex;
align-items: center;
justify-content: center;
transition: transform 0.2s;
margin-top: -15px;
}
.record-btn:active { transform: scale(0.9); }
/* 记录页 */
#recordPage {
min-height: 100vh;
background: #f5f5f5;
}
.page-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
padding: 16px 20px;
display: flex;
align-items: center;
gap: 12px;
}
.page-header .back {
font-size: 22px;
cursor: pointer;
background: none;
border: none;
color: #fff;
padding: 4px;
}
.page-header h2 { font-size: 18px; font-weight: 600; }
.type-switch {
display: flex;
margin: 16px 20px;
background: #fff;
border-radius: 10px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.type-switch .type-btn {
flex: 1;
padding: 12px;
text-align: center;
font-size: 15px;
cursor: pointer;
border: none;
background: #fff;
color: #999;
transition: all 0.2s;
}
.type-switch .type-btn.active {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
}
.category-list {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
padding: 0 20px;
margin-bottom: 16px;
}
.category-item {
background: #fff;
border: 2px solid transparent;
border-radius: 10px;
padding: 12px 8px;
text-align: center;
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
color: #666;
}
.category-item.active {
border-color: #667eea;
color: #667eea;
background: #f0f2ff;
}
.record-form {
padding: 0 20px 30px;
overflow: hidden;
}
.record-form .form-group { margin-bottom: 14px; }
.record-form .form-group input[type="datetime-local"] {
-webkit-appearance: none;
appearance: none;
}
.record-form .form-group label {
display: block;
font-size: 14px;
color: #666;
margin-bottom: 6px;
}
.record-form .form-group input {
width: 100%;
padding: 12px 14px;
border: 1px solid #e0e0e0;
border-radius: 10px;
font-size: 15px;
outline: none;
background: #fff;
box-sizing: border-box;
max-width: 100%;
}
.record-form .form-group input:focus { border-color: #667eea; }
.computed-amount {
background: #f0f2ff;
border-radius: 10px;
padding: 14px;
text-align: center;
margin-bottom: 16px;
font-size: 14px;
color: #666;
}
.computed-amount .total {
font-size: 28px;
font-weight: 700;
color: #667eea;
margin-top: 4px;
}
.submit-btn {
width: 100%;
padding: 14px;
border: none;
border-radius: 10px;
font-size: 16px;
cursor: pointer;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
}
.submit-btn:active { opacity: 0.8; }
/* Toast */
.toast {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0,0,0,0.75);
color: #fff;
padding: 12px 24px;
border-radius: 8px;
font-size: 14px;
z-index: 999;
display: none;
}
.toast.show { display: block; }
/* 排行预览 */
.ranking-preview {
background: #fff;
border-radius: 12px;
padding: 16px;
margin-top: 12px;
box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.ranking-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}
.ranking-title { font-size: 15px; font-weight: 600; color: #333; }
.ranking-detail-btn { font-size: 13px; color: #667eea; cursor: pointer; }
.ranking-list, .ranking-detail-list { display: flex; flex-direction: column; }
.ranking-item {
display: flex;
align-items: center;
padding: 10px 0;
border-bottom: 1px solid #f0f0f0;
cursor: pointer;
}
.ranking-item:last-child { border-bottom: none; }
.ranking-index {
width: 24px; height: 24px; border-radius: 50%;
background: #eee; color: #999; font-size: 12px; font-weight: 600;
display: flex; align-items: center; justify-content: center;
margin-right: 12px; flex-shrink: 0;
}
.ranking-index.top {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
}
.ranking-boss { flex: 1; font-size: 14px; color: #333; }
.ranking-amount { font-size: 15px; font-weight: 600; color: #27ae60; }
.ranking-empty { text-align: center; color: #999; padding: 20px 0; font-size: 14px; }
/* 排行详情页 */
#rankingPage { min-height: 100vh; background: #f5f5f5; }
.ranking-filters { padding: 16px 20px; }
.filter-row { display: flex; gap: 10px; margin-bottom: 12px; }
.filter-row .form-group { flex: 1; min-width: 0; margin-bottom: 0; text-align: center; }
.filter-row .form-group label { text-align: center; }
.filter-row .form-group input {
width: 100%; padding: 10px 4px; border: 1px solid #e0e0e0;
border-radius: 10px; font-size: 12px; outline: none; background: #fff;
text-align: center; box-sizing: border-box;
-webkit-appearance: none; appearance: none;
}
.filter-row .form-group input:focus { border-color: #667eea; }
.sort-switch {
display: flex; background: #fff; border-radius: 10px;
overflow: hidden; border: 1px solid #e0e0e0; flex: 1;
}
.sort-btn {
flex: 1; padding: 10px 8px; text-align: center; font-size: 13px;
cursor: pointer; border: none; background: #fff; color: #999; transition: all 0.2s;
}
.sort-btn.active {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff;
}
.ranking-detail-list { padding: 0 20px 30px; }
.ranking-detail-item {
background: #fff; border-radius: 12px; padding: 14px 16px;
margin-bottom: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.ranking-detail-top { display: flex; align-items: center; }
.ranking-detail-stats {
display: flex; justify-content: space-between;
margin-top: 8px; padding-left: 36px; font-size: 12px; color: #999;
}
/* 接单列表页 */
#orderListPage { min-height: 100vh; background: #f5f5f5; }
.order-list { padding: 12px 20px 30px; }
.order-date-group { margin-bottom: 16px; }
.order-date-label {
font-size: 13px; color: #999; font-weight: 600;
margin-bottom: 8px; padding-left: 4px;
}
.order-item {
background: #fff; border-radius: 12px; padding: 14px 16px;
margin-bottom: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.04);
cursor: pointer; transition: background 0.15s;
}
.order-item:active { background: #f8f8f8; }
.order-item-top { display: flex; justify-content: space-between; align-items: center; }
.order-item-boss { font-size: 15px; font-weight: 600; color: #333; }
.order-item-amount { font-size: 15px; font-weight: 600; color: #27ae60; }
.order-item-bottom { display: flex; justify-content: space-between; margin-top: 6px; font-size: 12px; color: #999; }
.order-loading { text-align: center; padding: 16px; color: #999; font-size: 14px; }
/* 编辑弹窗 */
.modal-overlay {
position: fixed; top: 0; left: 0; right: 0; bottom: 0;
background: rgba(0,0,0,0.5); z-index: 100;
display: none; justify-content: center; align-items: center;
}
.modal-overlay.show { display: flex; }
.modal-box {
background: #fff; border-radius: 16px; padding: 24px;
width: 90%; max-width: 400px; max-height: 80vh; overflow-y: auto;
}
.modal-box h3 { font-size: 18px; margin-bottom: 16px; color: #333; }
.modal-box .form-group { margin-bottom: 14px; }
.modal-box .form-group label { display: block; font-size: 14px; color: #666; margin-bottom: 6px; }
.modal-box .form-group input {
width: 100%; padding: 10px 12px; border: 1px solid #e0e0e0;
border-radius: 10px; font-size: 14px; outline: none; background: #fff;
box-sizing: border-box;
}
.modal-box .form-group input[type="datetime-local"] {
-webkit-appearance: none;
appearance: none;
}
.modal-box .form-group input:focus { border-color: #667eea; }
.modal-actions { display: flex; gap: 12px; margin-top: 16px; }
.modal-actions button { flex: 1; padding: 12px; border-radius: 10px; font-size: 15px; cursor: pointer; border: none; }
.modal-actions .btn-cancel { background: #f0f0f0; color: #666; }
.modal-actions .btn-save {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #fff;
}
.modal-actions .btn-delete { background: #e74c3c; color: #fff; }
/* 可点击的统计卡片 */
.stat-card.clickable { cursor: pointer; transition: transform 0.15s; }
.stat-card.clickable:active { transform: scale(0.97); }
.stat-summary .item.clickable { cursor: pointer; }
.stat-summary .item.clickable:active { opacity: 0.7; }
.mine-stats {
display: flex;
gap: 12px;
margin: 16px 0;
width: 100%;
}
.mine-stat-item {
flex: 1;
background: #f8f9fa;
border-radius: 10px;
padding: 12px 8px;
text-align: center;
}
.mine-stat-value {
font-size: 18px;
font-weight: 700;
color: #333;
}
.mine-stat-value.green { color: #27ae60; }
.mine-stat-label {
font-size: 12px;
color: #999;
margin-top: 4px;
}
.mine-stat-item { cursor: pointer; }
.mine-stat-item:active { opacity: 0.7; }
.horizontal-chart {
padding: 16px;
}
.hbar-row {
display: flex;
align-items: center;
margin-bottom: 10px;
background: #fff;
border-radius: 12px;
padding: 12px 14px;
box-shadow: 0 1px 4px rgba(0,0,0,0.06);
}
.hbar-index {
width: 24px;
height: 24px;
border-radius: 50%;
background: #e0e0e0;
color: #666;
font-size: 12px;
font-weight: 700;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
margin-right: 10px;
}
.hbar-index.top { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #fff; }
.hbar-label {
width: 60px;
font-size: 14px;
color: #333;
font-weight: 600;
text-align: left;
flex-shrink: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.hbar-track {
flex: 1;
height: 22px;
background: #f0f0f0;
border-radius: 11px;
overflow: hidden;
position: relative;
margin: 0 10px;
}
.hbar-fill {
height: 100%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 11px;
min-width: 4px;
transition: width 0.4s ease;
}
.hbar-value {
font-size: 14px;
font-weight: 700;
color: #667eea;
text-align: right;
flex-shrink: 0;
min-width: 45px;
}
/* 月份选择器弹窗 */
.month-picker-overlay {
position: fixed; top: 0; left: 0; right: 0; bottom: 0;
background: rgba(0,0,0,0.5); z-index: 100;
display: none; justify-content: center; align-items: center;
}
.month-picker-overlay.show { display: flex; }
.month-picker {
background: #fff; border-radius: 16px; padding: 24px;
width: 85%; max-width: 360px;
}
.month-picker-header {
display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;
}
.month-picker-header button {
background: none; border: none; font-size: 20px; cursor: pointer; color: #667eea; padding: 4px 8px;
}
.month-picker-header span { font-size: 18px; font-weight: 600; color: #333; }
.month-picker-grid {
display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px;
}
.month-picker-grid button {
padding: 12px 0; border-radius: 10px; border: 1px solid #e0e0e0;
background: #fff; font-size: 14px; color: #333; cursor: pointer; transition: all 0.15s;
}
.month-picker-grid button.active {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: #fff; border-color: transparent;
}
.month-picker-grid button:active { transform: scale(0.95); }
.month-picker-actions { display: flex; gap: 12px; margin-top: 16px; }
.month-picker-actions button {
flex: 1; padding: 12px; border-radius: 10px; font-size: 15px; cursor: pointer; border: none;
}
.month-picker-actions .btn-cancel { background: #f0f0f0; color: #666; }
.month-picker-actions .btn-confirm {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #fff;
}
/* 自动补全 */
.ac-wrap { position: relative; }
.ac-list {
position: absolute; left: 0; right: 0; top: 100%;
background: #fff; border: 1px solid #e0e0e0; border-top: none;
border-radius: 0 0 10px 10px; max-height: 180px; overflow-y: auto;
z-index: 50; display: none;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}
.ac-list.show { display: block; }
.ac-item {
padding: 10px 14px; font-size: 14px; color: #333;
cursor: pointer; border-bottom: 1px solid #f5f5f5;
}
.ac-item:last-child { border-bottom: none; }
.ac-item:active, .ac-item.active { background: #f0f2ff; color: #667eea; }
.ac-item .ac-highlight { color: #667eea; font-weight: 600; }
/* 下拉刷新 */
.pull-indicator {
display: flex; align-items: center; justify-content: center; gap: 6px;
height: 0; overflow: hidden; color: #999; font-size: 13px;
transition: height 0.2s;
}
.pull-indicator.visible { height: 40px; }
.pull-indicator.refreshing .pull-arrow {
animation: spin 0.8s linear infinite;
}
.pull-arrow {
width: 18px; height: 18px; transition: transform 0.2s;
}
.pull-arrow.flipped { transform: rotate(180deg); }
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
+456
View File
@@ -0,0 +1,456 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>接单系统</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!-- 登录页 -->
<div id="loginPage" class="page active">
<div class="login-box">
<h1>接单系统</h1>
<div class="form-group">
<label>用户名</label>
<input type="text" id="loginUser" placeholder="请输入用户名" autocomplete="username">
</div>
<div class="form-group">
<label>密码</label>
<input type="password" id="loginPass" placeholder="请输入密码" autocomplete="current-password">
</div>
<button class="btn btn-primary" onclick="doLogin()">登 录</button>
<div class="login-error" id="loginError"></div>
</div>
</div>
<!-- 首页 -->
<div id="homePage" class="page">
<div class="home-header">
<div class="month-selector" onclick="openMonthPicker()">
<span id="monthDisplay">2026年2月</span>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 9l6 6 6-6"/></svg>
</div>
</div>
<div class="tab-content">
<!-- 统计 -->
<div id="statsPanel" class="tab-panel active">
<div class="pull-indicator" id="pullIndicator">
<svg class="pull-arrow" id="pullArrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 19V5M5 12l7-7 7 7"/></svg>
<span id="pullText">下拉刷新</span>
</div>
<div class="stat-grid">
<div class="stat-card clickable" onclick="showPage('orderListPage')">
<div class="label">接单数</div>
<div class="value" id="takeCount">0</div>
<div class="sub-income" id="takeIncome">0</div>
</div>
<div class="stat-card clickable" onclick="showPage('dispatchListPage')">
<div class="label">派单数</div>
<div class="value" id="dispatchCount">0</div>
<div class="sub-income" id="dispatchIncome">0</div>
</div>
<div class="stat-card clickable" onclick="showPage('redEnvelopeListPage')">
<div class="label">红包</div>
<div class="value" id="redEnvelopeCount">0</div>
<div class="sub-income" id="redEnvelopeIncome">0</div>
</div>
<div class="stat-card clickable" onclick="showPage('milkTeaListPage')">
<div class="label">奶茶</div>
<div class="value" id="milkTeaCount">0</div>
<div class="sub-income" id="milkTeaIncome">0</div>
</div>
</div>
<div class="stat-summary">
<div class="item clickable" onclick="openMonthlyDetail('income')">
<div class="label">总收入</div>
<div class="val green" id="totalIncome">0</div>
</div>
<div class="item clickable" onclick="openMonthlyDetail('expense')">
<div class="label">总支出</div>
<div class="val red" id="totalExpense">0</div>
</div>
<div class="item">
<div class="label">净收入</div>
<div class="val green" id="netIncome">0</div>
</div>
</div>
<!-- 最近7天收入柱状图 -->
<div class="weekly-chart">
<div class="weekly-chart-title">最近7天收入</div>
<div class="weekly-chart-bars" id="weeklyChartBars"></div>
</div>
<!-- 老板收入排行预览 -->
<div class="ranking-preview">
<div class="ranking-header">
<span class="ranking-title">老板贡献榜(本月)</span>
<span class="ranking-detail-btn" onclick="showPage('rankingPage')">详情 &rarr;</span>
</div>
<div id="rankingPreviewList" class="ranking-list">
<div class="ranking-empty">暂无数据</div>
</div>
</div>
<!-- 陪玩派单榜预览 -->
<div class="ranking-preview">
<div class="ranking-header">
<span class="ranking-title">陪玩派单榜(本月)</span>
<span class="ranking-detail-btn" onclick="openPartnerRankingPage()">详情 &rarr;</span>
</div>
<div id="partnerRankingPreviewList" class="ranking-list">
<div class="ranking-empty">暂无数据</div>
</div>
</div>
</div>
<div id="minePanel" class="tab-panel">
<div class="profile-card">
<div class="avatar" id="avatarText" onclick="onAvatarTap()"></div>
<div class="name" id="profileName">用户</div>
<div class="mine-stats">
<div class="mine-stat-item" onclick="openTakeRanking()">
<div class="mine-stat-value" id="totalTakeCount">0</div>
<div class="mine-stat-label">总接单数</div>
</div>
<div class="mine-stat-item" onclick="openDispatchRanking()">
<div class="mine-stat-value" id="totalDispatchCount">0</div>
<div class="mine-stat-label">总派单数</div>
</div>
<div class="mine-stat-item" onclick="openYearlyIncome()">
<div class="mine-stat-value green" id="totalNetIncome">0</div>
<div class="mine-stat-label">总净收入</div>
</div>
</div>
<button class="refresh-btn" onclick="location.reload()">刷新界面</button>
<div id="secretBtns" style="display:none">
<button class="refresh-btn" style="margin-top:12px" onclick="showExportDialog()">导出数据</button>
<button class="refresh-btn" style="margin-top:12px" onclick="triggerImport()">导入数据</button>
<input type="file" id="importFileInput" accept=".json,.csv" style="display:none" onchange="handleImportFile(event)">
</div>
<button class="logout-btn" onclick="doLogout()">退出登录</button>
</div>
</div>
</div>
<div class="bottom-bar">
<div class="nav-item active" id="navStats" onclick="switchNav('stats')">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 3v18h18"/><path d="M7 16l4-8 4 4 4-6"/></svg>
<span>统计</span>
</div>
<button class="record-btn" onclick="showPage('recordPage')">+</button>
<div class="nav-item" id="navMine" onclick="switchNav('mine')">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 4-7 8-7s8 3 8 7"/></svg>
<span>我的</span>
</div>
</div>
</div>
<!-- 记录页 -->
<div id="recordPage" class="page">
<div class="page-header">
<button class="back" onclick="showPage('homePage')">&larr;</button>
<h2>记一笔</h2>
</div>
<div class="type-switch">
<button class="type-btn active" onclick="switchRecordType('income')">收入</button>
<button class="type-btn" onclick="switchRecordType('expense')">支出</button>
</div>
<div id="incomeCats" class="category-list">
<div class="category-item active" onclick="selectCategory(this, '接单')">接单</div>
<div class="category-item" onclick="selectCategory(this, '派单')">派单</div>
<div class="category-item" onclick="selectCategory(this, '红包收入')">红包</div>
<div class="category-item" onclick="selectCategory(this, '奶茶')">奶茶</div>
</div>
<div id="expenseCats" class="category-list" style="display:none;">
<div class="category-item active" onclick="selectCategory(this, '红包支出')">红包</div>
<div class="category-item" onclick="selectCategory(this, '比心')">比心</div>
<div class="category-item" onclick="selectCategory(this, '其他支出')">其他</div>
</div>
<div class="record-form" id="recordForm">
<!-- 动态表单内容 -->
</div>
</div>
<!-- 排行详情页 -->
<div id="rankingPage" class="page">
<div class="page-header">
<button class="back" onclick="showPage('homePage')">&larr;</button>
<h2>老板贡献榜</h2>
</div>
<div class="ranking-filters">
<div class="filter-row">
<div class="form-group">
<label>开始日期</label>
<input type="date" id="rankStartDate">
</div>
<div class="form-group">
<label>结束日期</label>
<input type="date" id="rankEndDate">
</div>
</div>
<div class="filter-row">
<div class="sort-switch">
<button class="sort-btn active" data-sort="total_income" onclick="switchSort(this)">收入总数</button>
<button class="sort-btn" data-sort="take_count" onclick="switchSort(this)">接单数</button>
<button class="sort-btn" data-sort="dispatch_count" onclick="switchSort(this)">派单数</button>
</div>
</div>
<button class="submit-btn" onclick="loadRankingDetail()">查询</button>
</div>
<div id="rankingDetailList" class="ranking-detail-list"></div>
</div>
<!-- 接单列表页 -->
<div id="orderListPage" class="page">
<div class="page-header">
<button class="back" onclick="showPage('homePage')">&larr;</button>
<h2 id="orderListTitle">接单列表</h2>
</div>
<div id="orderList" class="order-list"></div>
<div id="orderLoading" class="order-loading" style="display:none;">加载中...</div>
</div>
<!-- 派单列表页 -->
<div id="dispatchListPage" class="page">
<div class="page-header">
<button class="back" onclick="showPage('homePage')">&larr;</button>
<h2 id="dispatchListTitle">派单列表</h2>
</div>
<div id="dispatchList" class="order-list"></div>
<div id="dispatchLoading" class="order-loading" style="display:none;">加载中...</div>
</div>
<!-- 陪玩派单榜详情页 -->
<div id="partnerRankingPage" class="page">
<div class="page-header">
<button class="back" onclick="showPage('homePage')">&larr;</button>
<h2>陪玩派单榜</h2>
</div>
<div class="ranking-filters">
<div class="filter-row">
<div class="form-group">
<label>开始日期</label>
<input type="date" id="partnerRankStartDate">
</div>
<div class="form-group">
<label>结束日期</label>
<input type="date" id="partnerRankEndDate">
</div>
</div>
<button class="submit-btn" onclick="loadPartnerRankingDetail()">查询</button>
</div>
<div id="partnerRankingSummary" class="stat-summary" style="margin: 12px 16px;">
<div class="item">
<div class="val" id="partnerTotalDispatchCount">0</div>
<div class="label">派单总数</div>
</div>
<div class="item">
<div class="val green" id="totalPartnerIncome">0.00</div>
<div class="label">陪玩总收入</div>
</div>
<div class="item">
<div class="val orange" id="totalRebateIncome">0.00</div>
<div class="label">返点总收入</div>
</div>
<div class="item">
<div class="val purple" id="totalMilkTeaIncome">0.00</div>
<div class="label">奶茶收入</div>
</div>
</div>
<div id="partnerRankingDetailList" class="ranking-detail-list" style="margin-top: 12px;"></div>
</div>
<!-- 总接单排行页 -->
<div id="takeRankingPage" class="page">
<div class="page-header">
<button class="back" onclick="showPage('homePage');switchNav('mine')">&larr;</button>
<h2>总接单数排行</h2>
</div>
<div id="takeRankingSummary" class="stat-summary"></div>
<div id="takeRankingChart" class="horizontal-chart"></div>
</div>
<!-- 总派单排行页 -->
<div id="dispatchRankingPage" class="page">
<div class="page-header">
<button class="back" onclick="showPage('homePage');switchNav('mine')">&larr;</button>
<h2>总派单数排行</h2>
</div>
<div id="dispatchRankingSummary" class="stat-summary"></div>
<div id="dispatchRankingChart" class="horizontal-chart"></div>
</div>
<!-- 老板交易详情页 -->
<div id="bossDetailPage" class="page">
<div class="page-header">
<button class="back" onclick="bossDetailGoBack()">&larr;</button>
<h2 id="bossDetailTitle">交易记录</h2>
</div>
<div class="daily-summary" id="bossDetailSummary"></div>
<div id="bossDetailList" class="order-list"></div>
</div>
<!-- 陪玩交易详情页 -->
<div id="partnerDetailPage" class="page">
<div class="page-header">
<button class="back" onclick="partnerDetailGoBack()">&larr;</button>
<h2 id="partnerDetailTitle">交易记录</h2>
</div>
<div class="daily-summary" id="partnerDetailSummary"></div>
<div id="partnerDetailList" class="order-list"></div>
</div>
<!-- 红包及其他收入列表页 -->
<div id="monthlyIncomeDetailPage" class="page">
<div class="page-header">
<button class="back" onclick="showPage('homePage')">&larr;</button>
<h2 id="monthlyIncomeTitle">月收入详情</h2>
</div>
<div class="daily-nav">
<button class="daily-nav-btn" onclick="switchMonthlyDetail('income', -1)">&larr; 上一月</button>
<span class="daily-nav-date" id="monthlyIncomeNav"></span>
<button class="daily-nav-btn" onclick="switchMonthlyDetail('income', 1)">下一月 &rarr;</button>
</div>
<div class="daily-summary" id="monthlyIncomeSummary"></div>
<div id="monthlyIncomeList" class="order-list"></div>
</div>
<!-- 月支出详情页 -->
<div id="monthlyExpenseDetailPage" class="page">
<div class="page-header">
<button class="back" onclick="showPage('homePage')">&larr;</button>
<h2 id="monthlyExpenseTitle">月支出详情</h2>
</div>
<div class="daily-nav">
<button class="daily-nav-btn" onclick="switchMonthlyDetail('expense', -1)">&larr; 上一月</button>
<span class="daily-nav-date" id="monthlyExpenseNav"></span>
<button class="daily-nav-btn" onclick="switchMonthlyDetail('expense', 1)">下一月 &rarr;</button>
</div>
<div class="daily-summary" id="monthlyExpenseSummary"></div>
<div id="monthlyExpenseList" class="order-list"></div>
</div>
<!-- 年度净收入页面 -->
<div id="yearlyNetIncomePage" class="page">
<div class="page-header">
<button class="back" onclick="showPage('homePage')">&larr;</button>
<h2>年度净收入</h2>
</div>
<div class="daily-summary" id="yearlyNetIncomeSummary"></div>
<div id="yearlyNetIncomeList" class="order-list"></div>
</div>
<!-- 红包收入列表页 -->
<div id="redEnvelopeListPage" class="page">
<div class="page-header">
<button class="back" onclick="showPage('homePage')">&larr;</button>
<h2>红包收入</h2>
</div>
<div id="redEnvelopeList" class="order-list"></div>
<div id="redEnvelopeLoading" class="order-loading" style="display:none;">加载中...</div>
</div>
<!-- 奶茶收入列表页 -->
<div id="milkTeaListPage" class="page">
<div class="page-header">
<button class="back" onclick="showPage('homePage')">&larr;</button>
<h2>奶茶收入</h2>
</div>
<div id="milkTeaList" class="order-list"></div>
<div id="milkTeaLoading" class="order-loading" style="display:none;">加载中...</div>
</div>
<!-- 红包及其他收入列表页 -->
<div id="otherIncomeListPage" class="page">
<div class="page-header">
<button class="back" onclick="showPage('homePage')">&larr;</button>
<h2 id="otherIncomeListTitle">红包及其他收入</h2>
</div>
<div id="otherIncomeList" class="order-list"></div>
<div id="otherIncomeLoading" class="order-loading" style="display:none;">加载中...</div>
</div>
<!-- 日收入详情页 -->
<div id="dailyDetailPage" class="page">
<div class="page-header">
<button class="back" onclick="showPage('homePage')">&larr;</button>
<h2 id="dailyDetailTitle">当日收入</h2>
</div>
<div class="daily-nav">
<button class="daily-nav-btn" onclick="switchDailyDate(-1)">&larr; 前一天</button>
<span class="daily-nav-date" id="dailyNavDate"></span>
<button class="daily-nav-btn" onclick="switchDailyDate(1)">后一天 &rarr;</button>
</div>
<div class="daily-summary" id="dailySummary"></div>
<div id="dailyDetailList" class="order-list"></div>
</div>
<!-- 编辑弹窗 -->
<div class="modal-overlay" id="editModal">
<div class="modal-box">
<h3 id="editModalTitle">编辑记录</h3>
<input type="hidden" id="editId">
<input type="hidden" id="editCategory">
<div id="editFormBody"></div>
<div class="modal-actions">
<button class="btn-cancel" onclick="closeEditModal()">取消</button>
<button class="btn-delete" onclick="deleteEditRecord()">删除</button>
<button class="btn-save" onclick="saveEditRecord()">保存</button>
</div>
</div>
</div>
<!-- 月份选择器 -->
<div class="month-picker-overlay" id="monthPickerOverlay">
<div class="month-picker">
<div class="month-picker-header">
<button onclick="changePickerYear(-1)">&larr;</button>
<span id="pickerYearDisplay">2026</span>
<button onclick="changePickerYear(1)">&rarr;</button>
</div>
<div class="month-picker-grid" id="pickerMonthGrid"></div>
<div class="month-picker-actions">
<button class="btn-cancel" onclick="closeMonthPicker()">取消</button>
<button class="btn-confirm" onclick="confirmMonth()">确定</button>
</div>
</div>
</div>
<!-- 导出格式选择弹窗 -->
<div class="modal-overlay" id="exportModal">
<div class="modal-box" style="text-align:center">
<h3>选择导出格式</h3>
<p style="color:#999;font-size:14px;margin-bottom:20px">导出所有记录数据</p>
<div style="display:flex;flex-direction:column;gap:12px">
<button class="submit-btn" onclick="doExport('json')">导出 JSON</button>
<button class="submit-btn" onclick="doExport('csv')">导出 CSV</button>
<button class="btn-cancel" style="padding:14px;border-radius:10px;font-size:15px;border:none;cursor:pointer" onclick="closeExportModal()">取消</button>
</div>
</div>
</div>
<!-- 导入确认弹窗 -->
<div class="modal-overlay" id="importConfirmModal">
<div class="modal-box" style="text-align:center">
<h3>确认导入</h3>
<p id="importConfirmMsg" style="color:#666;font-size:14px;margin-bottom:20px;white-space:pre-line"></p>
<div class="modal-actions">
<button class="btn-cancel" onclick="closeImportConfirm()">取消</button>
<button class="btn-save" onclick="confirmImport()">确认导入</button>
</div>
</div>
</div>
<div class="toast" id="toast"></div>
<script src="js/app.js?v=20260224"></script>
<script src="js/auth.js"></script>
<script src="js/autocomplete.js"></script>
<script src="js/month-picker.js"></script>
<script src="js/stats.js?v=2026022401"></script>
<script src="js/ranking.js"></script>
<script src="js/order-list.js"></script>
<script src="js/edit-modal.js"></script>
<script src="js/record-form.js"></script>
<script src="js/import-export.js"></script>
</body>
</html>
+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); }
}