Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f18cdf5249 | ||
|
|
1f8321c74e | ||
|
|
6696e03910 | ||
|
|
cab06fb77f | ||
|
|
00d1b96415 | ||
|
|
e5acd0115e | ||
|
|
7a9c19e5c5 | ||
|
|
1aac03b7a4 | ||
|
|
b9b7e2637a | ||
|
|
c5697f8b7b | ||
|
|
5d5ee9ecdc | ||
|
|
d27c855e62 | ||
|
|
bc5ce695d2 | ||
|
|
018913f337 | ||
|
|
3da97f7dd5 | ||
|
|
27ad9b6901 | ||
|
|
1aa2f529e7 | ||
|
|
d183ca9207 | ||
|
|
f69c8bf510 | ||
|
|
156bcb9505 | ||
|
|
8379126f9d | ||
|
|
664b845cef | ||
|
|
012de577d7 | ||
|
|
2d91e73063 | ||
|
|
1bb826e7ac | ||
|
|
a49a5a7cff |
@@ -129,6 +129,14 @@ async def list_groups(db: AsyncSession = Depends(get_db)):
|
||||
return [{"id": g.id, "name": g.name} for g in result.scalars().all()]
|
||||
|
||||
|
||||
|
||||
|
||||
class EmailVerifyRequest(BaseModel):
|
||||
email: str
|
||||
|
||||
class EmailChangeRequest(BaseModel):
|
||||
code: str
|
||||
new_email: str
|
||||
class ProfileUpdate(BaseModel):
|
||||
nickname: str | None = None
|
||||
real_email: str | None = None
|
||||
@@ -148,6 +156,83 @@ async def update_profile(
|
||||
return {"message": "资料更新成功"}
|
||||
|
||||
|
||||
|
||||
|
||||
@router.post("/verify-email")
|
||||
async def send_email_verification(
|
||||
req: EmailVerifyRequest,
|
||||
user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
import secrets
|
||||
from datetime import timedelta
|
||||
code = f"{secrets.randbelow(1000000):06d}"
|
||||
key = f"email_verify:{user.id}"
|
||||
value = f"{req.email}|{code}|{(datetime.utcnow() + timedelta(minutes=5)).isoformat()}"
|
||||
|
||||
result = await db.execute(select(SystemSetting).where(SystemSetting.key == key))
|
||||
setting = result.scalar_one_or_none()
|
||||
if setting:
|
||||
setting.value = value
|
||||
else:
|
||||
db.add(SystemSetting(key=key, value=value))
|
||||
await db.commit()
|
||||
|
||||
if user.real_email:
|
||||
from app.services.email_service import send_email
|
||||
html = f"""
|
||||
<div style="font-family:-apple-system,sans-serif;max-width:480px;margin:0 auto;padding:32px">
|
||||
<h2 style="color:#0071e3;margin-bottom:16px">邮箱变更验证码</h2>
|
||||
<p>Hi {user.nickname or user.email},</p>
|
||||
<p>您正在修改绑定邮箱,验证码如下:</p>
|
||||
<div style="background:#f5f5f7;border-radius:12px;padding:24px;margin:16px 0;text-align:center">
|
||||
<p style="font-size:36px;font-weight:700;letter-spacing:8px;color:#1d1d1f;margin:0">{code}</p>
|
||||
<p style="color:#6e6e73;font-size:12px;margin:8px 0 0 0">5 分钟内有效</p>
|
||||
</div>
|
||||
<p style="color:#6e6e73;font-size:13px">如非本人操作,请忽略此邮件。</p>
|
||||
</div>
|
||||
"""
|
||||
await send_email(user.real_email, "【债务管理系统】邮箱变更验证码", html)
|
||||
|
||||
return {"message": "验证码已发送到当前邮箱"}
|
||||
|
||||
|
||||
@router.post("/change-email")
|
||||
async def change_email(
|
||||
req: EmailChangeRequest,
|
||||
user: User = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
key = f"email_verify:{user.id}"
|
||||
result = await db.execute(select(SystemSetting).where(SystemSetting.key == key))
|
||||
setting = result.scalar_one_or_none()
|
||||
if not setting:
|
||||
raise HTTPException(status_code=400, detail="验证码已过期,请重新获取")
|
||||
|
||||
parts = setting.value.split("|")
|
||||
if len(parts) != 3 or parts[1] != req.code:
|
||||
raise HTTPException(status_code=400, detail="验证码错误")
|
||||
|
||||
try:
|
||||
expires_at = datetime.fromisoformat(parts[2])
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="验证码格式错误")
|
||||
|
||||
if datetime.utcnow() > expires_at:
|
||||
await db.delete(setting)
|
||||
await db.commit()
|
||||
raise HTTPException(status_code=400, detail="验证码已过期,请重新获取")
|
||||
|
||||
# Check if new email is already used
|
||||
existing = await db.execute(select(User).where(User.real_email == req.new_email, User.id != user.id))
|
||||
if existing.scalar_one_or_none():
|
||||
raise HTTPException(status_code=400, detail="该邮箱已被其他账号使用")
|
||||
|
||||
user.real_email = req.new_email
|
||||
await db.delete(setting)
|
||||
await db.commit()
|
||||
return {"message": "邮箱修改成功"}
|
||||
|
||||
@router.put("/password")
|
||||
async def change_password(
|
||||
req: ChangePasswordRequest,
|
||||
|
||||
37
deploy/docker-compose.arm64.yml
Normal file
37
deploy/docker-compose.arm64.yml
Normal file
@@ -0,0 +1,37 @@
|
||||
services:
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
environment:
|
||||
POSTGRES_DB: debt_manager
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "54326:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
backend:
|
||||
image: debt-manager-backend:latest
|
||||
ports:
|
||||
- "8000:8000"
|
||||
environment:
|
||||
DATABASE_URL: postgresql+asyncpg://postgres:postgres@db:5432/debt_manager
|
||||
SECRET_KEY: change-this-in-production-please
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
|
||||
frontend:
|
||||
image: debt-manager-frontend:latest
|
||||
ports:
|
||||
- "806:80"
|
||||
depends_on:
|
||||
- backend
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
37
deploy/docker-compose.x86.yml
Normal file
37
deploy/docker-compose.x86.yml
Normal file
@@ -0,0 +1,37 @@
|
||||
services:
|
||||
db:
|
||||
image: postgres:15-alpine
|
||||
environment:
|
||||
POSTGRES_DB: debt_manager
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "54326:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
backend:
|
||||
image: debt-manager-backend:x86
|
||||
ports:
|
||||
- "8000:8000"
|
||||
environment:
|
||||
DATABASE_URL: postgresql+asyncpg://postgres:postgres@db:5432/debt_manager
|
||||
SECRET_KEY: change-this-in-production-please
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
|
||||
frontend:
|
||||
image: debt-manager-frontend:x86
|
||||
ports:
|
||||
- "806:80"
|
||||
depends_on:
|
||||
- backend
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
@@ -1,39 +1,77 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
echo "========================================="
|
||||
echo " 债务管理系统 - 一键安装"
|
||||
echo "========================================="
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
|
||||
echo ""
|
||||
echo "[1/3] 加载 Docker 镜像..."
|
||||
docker load -i "$SCRIPT_DIR/debt-manager-backend.tar.gz"
|
||||
docker load -i "$SCRIPT_DIR/debt-manager-frontend.tar.gz"
|
||||
docker load -i "$SCRIPT_DIR/postgres-15-alpine.tar.gz"
|
||||
|
||||
echo ""
|
||||
echo "[2/3] 启动服务..."
|
||||
cd "$SCRIPT_DIR"
|
||||
docker compose up -d
|
||||
|
||||
echo "=========================================="
|
||||
echo " 债务管理系统 v2.2 安装脚本"
|
||||
echo "=========================================="
|
||||
|
||||
# Detect architecture
|
||||
ARCH=$(uname -m)
|
||||
case "$ARCH" in
|
||||
x86_64|amd64)
|
||||
ARCH_NAME="x86"
|
||||
COMPOSE_FILE="docker-compose.x86.yml"
|
||||
BACKEND_IMAGE="debt-manager-backend:x86"
|
||||
FRONTEND_IMAGE="debt-manager-frontend:x86"
|
||||
BACKEND_TAR="debt-manager-backend-x86.tar.gz"
|
||||
FRONTEND_TAR="debt-manager-frontend-x86.tar.gz"
|
||||
;;
|
||||
aarch64|arm64)
|
||||
ARCH_NAME="arm64"
|
||||
COMPOSE_FILE="docker-compose.arm64.yml"
|
||||
BACKEND_IMAGE="debt-manager-backend:latest"
|
||||
FRONTEND_IMAGE="debt-manager-frontend:latest"
|
||||
BACKEND_TAR="debt-manager-backend-arm64.tar.gz"
|
||||
FRONTEND_TAR="debt-manager-frontend-arm64.tar.gz"
|
||||
;;
|
||||
*)
|
||||
echo "不支持的架构: $ARCH"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "检测到架构: $ARCH_NAME ($ARCH)"
|
||||
echo ""
|
||||
|
||||
# Load images
|
||||
echo "加载 Docker 镜像..."
|
||||
docker load < "$BACKEND_TAR"
|
||||
docker load < "$FRONTEND_TAR"
|
||||
docker load < postgres-15-alpine.tar.gz
|
||||
|
||||
# Generate secure keys
|
||||
SECRET_KEY=$(python3 -c "import secrets; print(secrets.token_hex(32))" 2>/dev/null || openssl rand -hex 32)
|
||||
DB_PASSWORD=$(python3 -c "import secrets; print(secrets.token_hex(16))" 2>/dev/null || openssl rand -hex 16)
|
||||
|
||||
echo ""
|
||||
echo "[3/3] 等待服务就绪..."
|
||||
sleep 5
|
||||
echo "生成安全密钥..."
|
||||
|
||||
# Create .env file
|
||||
cat > .env << EOF
|
||||
POSTGRES_DB=debt_manager
|
||||
POSTGRES_USER=postgres
|
||||
POSTGRES_PASSWORD=$DB_PASSWORD
|
||||
DATABASE_URL=postgresql+asyncpg://postgres:$DB_PASSWORD@db:5432/debt_manager
|
||||
SECRET_KEY=$SECRET_KEY
|
||||
ADMIN_PASSWORD=Admin123!
|
||||
EOF
|
||||
|
||||
echo "配置文件已创建"
|
||||
echo ""
|
||||
echo "========================================="
|
||||
echo "=========================================="
|
||||
echo " 安装完成!"
|
||||
echo "========================================="
|
||||
echo "=========================================="
|
||||
echo ""
|
||||
echo " 前台地址: http://localhost:806"
|
||||
echo " 后台地址: http://localhost:806/admin.html"
|
||||
echo " API 文档: http://localhost:8000/docs"
|
||||
echo "启动命令: docker compose -f $COMPOSE_FILE up -d"
|
||||
echo ""
|
||||
echo " 默认账号: admin / admin123"
|
||||
echo " 默认账号: test / test123"
|
||||
echo "访问地址:"
|
||||
echo " 前台: http://localhost:806"
|
||||
echo " 后台: http://localhost:806/admin.html"
|
||||
echo ""
|
||||
echo " 停止服务: docker compose -f $SCRIPT_DIR/docker-compose.yml down"
|
||||
echo " 查看日志: docker compose -f $SCRIPT_DIR/docker-compose.yml logs -f"
|
||||
echo "========================================="
|
||||
echo "管理员账号: admin"
|
||||
echo "管理员密码: Admin123!"
|
||||
echo ""
|
||||
echo "请务必修改默认密码!"
|
||||
|
||||
@@ -1,22 +1,6 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
echo "========================================="
|
||||
echo " 债务管理系统 - 卸载"
|
||||
echo "========================================="
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
|
||||
echo ""
|
||||
echo "[1/2] 停止并删除容器..."
|
||||
cd "$SCRIPT_DIR"
|
||||
docker compose down -v
|
||||
|
||||
echo ""
|
||||
echo "[2/2] 删除 Docker 镜像..."
|
||||
docker rmi debt-manager-backend:latest debt-manager-frontend:latest postgres:15-alpine 2>/dev/null || true
|
||||
|
||||
echo ""
|
||||
echo "========================================="
|
||||
echo " 卸载完成"
|
||||
echo "========================================="
|
||||
echo "停止并删除容器..."
|
||||
docker compose -f docker-compose.x86.yml down -v 2>/dev/null || true
|
||||
docker compose -f docker-compose.arm64.yml down -v 2>/dev/null || true
|
||||
docker compose down -v 2>/dev/null || true
|
||||
echo "卸载完成"
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
FROM nginx:alpine
|
||||
COPY index.html admin.html reset-password.html /usr/share/nginx/html/
|
||||
COPY index.html admin.html reset-password.html analysis.html chart.min.js /usr/share/nginx/html/
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
410
frontend/analysis.html
Normal file
410
frontend/analysis.html
Normal file
@@ -0,0 +1,410 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta http-equiv="Cache-Control" content="no-cache">
|
||||
<title>数据分析</title>
|
||||
<script src="/chart.min.js"></script>
|
||||
<style>
|
||||
:root{--bg:#f5f5f7;--card:rgba(255,255,255,.8);--border:rgba(0,0,0,.06);--text:#1d1d1f;--text2:#6e6e73;--text3:#aeaeb2;--blue:#0071e3;--green:#34c759;--red:#ff3b30;--orange:#ff9500;--purple:#af52de;--radius:16px;--radius-sm:10px;--radius-xs:8px}
|
||||
*{margin:0;padding:0;box-sizing:border-box}
|
||||
body{font-family:-apple-system,BlinkMacSystemFont,"SF Pro Display","PingFang SC",sans-serif;background:var(--bg);color:var(--text);min-height:100vh;font-size:14px}
|
||||
.header{background:rgba(255,255,255,.72);backdrop-filter:saturate(180%) blur(20px);-webkit-backdrop-filter:saturate(180%) blur(20px);border-bottom:1px solid var(--border);position:sticky;top:0;z-index:40}
|
||||
.header-inner{max-width:1200px;margin:0 auto;padding:0 24px;height:52px;display:flex;align-items:center;justify-content:space-between}
|
||||
.header h1{font-size:17px;font-weight:600;color:var(--text);letter-spacing:-.2px}
|
||||
.header-center{position:absolute;left:50%;transform:translateX(-50%)}
|
||||
.nav-tabs{display:flex;gap:4px;background:rgba(0,0,0,.04);border-radius:var(--radius-xs);padding:3px}
|
||||
.nav-tab{padding:6px 16px;border-radius:6px;font-size:13px;font-weight:500;color:var(--text2);text-decoration:none;transition:all .2s}
|
||||
.nav-tab:hover{color:var(--text)}
|
||||
.nav-tab.active{background:#fff;color:var(--text);box-shadow:0 1px 3px rgba(0,0,0,.08)}
|
||||
.header-right{display:flex;align-items:center;gap:4px}
|
||||
.header-right a,.hdr-btn{color:var(--text2);text-decoration:none;font-size:12px;padding:6px 12px;border-radius:var(--radius-xs);transition:all .2s;background:transparent;border:none;cursor:pointer;font-family:inherit}
|
||||
.header-right a:hover,.hdr-btn:hover{background:rgba(0,0,0,.04);color:var(--text)}
|
||||
.header-right .admin-link{color:var(--blue)}
|
||||
.header-right .logout-link{color:var(--red)}
|
||||
.user-info{color:var(--text);font-size:13px;font-weight:500;cursor:pointer;padding:6px 12px;border-radius:var(--radius-xs);transition:all .2s}
|
||||
.user-info:hover{background:rgba(0,0,0,.04)}
|
||||
.notif-wrap{position:relative}
|
||||
.notif-bell{cursor:pointer;padding:4px 8px;border-radius:var(--radius-xs);transition:all .2s;color:var(--text2)}
|
||||
.notif-bell:hover{background:rgba(0,0,0,.04);color:var(--text)}
|
||||
.notif-badge{position:absolute;top:2px;right:2px;min-width:14px;height:14px;background:var(--red);color:#fff;border-radius:7px;font-size:9px;font-weight:600;display:flex;align-items:center;justify-content:center;padding:0 3px}
|
||||
.notif-dropdown{display:none;position:absolute;right:0;top:calc(100% + 8px);background:rgba(255,255,255,.96);backdrop-filter:blur(24px);border:1px solid var(--border);border-radius:var(--radius);box-shadow:0 12px 48px rgba(0,0,0,.15);width:360px;max-height:480px;overflow:hidden;z-index:60}
|
||||
.notif-dropdown.show{display:block}
|
||||
.notif-header{padding:14px 16px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center}
|
||||
.notif-header h4{font-size:14px;font-weight:600;color:var(--text)}
|
||||
.notif-header .mark-all{font-size:12px;color:var(--blue);cursor:pointer;background:none;border:none;font-family:inherit}
|
||||
.notif-list{overflow-y:auto;max-height:380px}
|
||||
.notif-item{padding:12px 16px;border-bottom:1px solid var(--border);cursor:pointer;transition:background .15s;display:flex;gap:12px;align-items:flex-start}
|
||||
.notif-item:hover{background:rgba(0,0,0,.02)}
|
||||
.notif-item.unread{background:rgba(0,113,227,.03)}
|
||||
.notif-item .notif-icon{width:32px;height:32px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0}
|
||||
.notif-icon.repayment_due{background:rgba(0,113,227,.08)}
|
||||
.notif-icon.repayment_overdue{background:rgba(255,59,48,.08)}
|
||||
.notif-icon.system{background:rgba(175,82,222,.08)}
|
||||
.notif-icon.account{background:rgba(52,199,89,.08)}
|
||||
.notif-item .notif-content{flex:1;min-width:0}
|
||||
.notif-item .notif-title{font-size:13px;font-weight:500;color:var(--text);margin-bottom:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.notif-item .notif-msg{font-size:12px;color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.notif-item .notif-time{font-size:11px;color:var(--text3);white-space:nowrap}
|
||||
.notif-empty{text-align:center;padding:32px;color:var(--text3);font-size:13px}
|
||||
.export-wrap{position:relative}
|
||||
.export-menu{display:none;position:absolute;right:0;top:calc(100% + 4px);background:rgba(255,255,255,.95);backdrop-filter:blur(20px);border:1px solid var(--border);border-radius:var(--radius-sm);box-shadow:0 8px 32px rgba(0,0,0,.12);min-width:160px;z-index:50;overflow:hidden}
|
||||
.export-menu.show{display:block}
|
||||
.export-menu a{display:block;padding:10px 18px;font-size:13px;color:var(--text);text-decoration:none;transition:background .15s}
|
||||
.export-menu a:hover{background:rgba(0,0,0,.04)}
|
||||
.user-info{color:var(--text);font-size:13px;font-weight:500;cursor:pointer;padding:6px 14px;border-radius:var(--radius-xs);transition:all .2s;background:rgba(0,0,0,.02)}
|
||||
.user-info:hover{background:rgba(0,0,0,.06)}
|
||||
.container{max-width:1120px;margin:0 auto;padding:24px}
|
||||
.stats-row{display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin-bottom:24px}
|
||||
.stat-card{background:var(--card);border-radius:var(--radius-sm);padding:20px;text-align:center;border:1px solid var(--border)}
|
||||
.stat-card .lbl{font-size:12px;color:var(--text3);margin-bottom:6px;font-weight:500}
|
||||
.stat-card .val{font-size:24px;font-weight:700}
|
||||
.stat-card .val.blue{color:var(--blue)}.stat-card .val.green{color:var(--green)}.stat-card .val.red{color:var(--red)}.stat-card .val.orange{color:var(--orange)}
|
||||
.charts-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-bottom:24px}
|
||||
.chart-card{background:var(--card);border-radius:var(--radius);border:1px solid var(--border);padding:20px;box-shadow:0 1px 3px rgba(0,0,0,.04)}
|
||||
.chart-card h3{font-size:14px;font-weight:600;margin-bottom:16px;color:var(--text)}
|
||||
.chart-wrap{position:relative;height:280px}
|
||||
.full-width{grid-column:1/-1}
|
||||
.empty-tip{text-align:center;padding:40px;color:var(--text3);font-size:13px}
|
||||
@media(max-width:900px){.stats-row{grid-template-columns:repeat(2,1fr)}.charts-grid{grid-template-columns:1fr}}
|
||||
|
||||
.modal-mask{display:none;position:fixed;inset:0;background:rgba(0,0,0,.3);z-index:100;align-items:center;justify-content:center;backdrop-filter:blur(8px)}
|
||||
.modal-mask.show{display:flex}
|
||||
.modal{background:#fff;border-radius:var(--radius);padding:28px;max-width:420px;width:90%;box-shadow:0 24px 80px rgba(0,0,0,.15)}
|
||||
.modal h3{margin-bottom:18px;font-size:17px;color:var(--text);font-weight:600}
|
||||
.modal .form-row{margin-bottom:14px}
|
||||
.modal .form-row label{display:block;font-size:13px;font-weight:500;margin-bottom:4px}
|
||||
.modal .form-row input{width:100%;padding:10px 14px;border:1px solid #d2d2d7;border-radius:var(--radius-xs);font-size:14px;outline:none}
|
||||
.modal .form-row input:focus{border-color:var(--blue)}
|
||||
.modal .btn-row{display:flex;gap:10px;margin-top:18px}
|
||||
.btn-ghost{background:#fff;color:var(--text2);border:1px solid #d2d2d7;padding:10px 0;border-radius:var(--radius-xs);font-size:14px;cursor:pointer;flex:1;font-family:inherit}
|
||||
.btn-ghost:hover{background:#f5f5f7}
|
||||
.btn-main{background:var(--blue);color:#fff;padding:10px 0;border:none;border-radius:var(--radius-xs);font-size:14px;font-weight:500;cursor:pointer;flex:1;font-family:inherit}
|
||||
.error-msg{color:var(--red);font-size:12px;margin-top:8px;display:none}
|
||||
.error-msg.show{display:block}
|
||||
.success-msg{color:var(--green);font-size:13px;margin-top:8px;display:none}
|
||||
.success-msg.show{display:block}
|
||||
|
||||
.profile-section{padding:4px 0}
|
||||
.profile-section .form-row{margin-bottom:14px}
|
||||
.profile-section .form-row label{display:block;font-size:13px;font-weight:500;margin-bottom:4px;color:var(--text2)}
|
||||
.profile-section .form-row input{width:100%;padding:10px 14px;border:1px solid #d2d2d7;border-radius:var(--radius-xs);font-size:14px;outline:none;transition:all .2s}
|
||||
.profile-section .form-row input:focus{border-color:var(--blue);box-shadow:0 0 0 3px rgba(0,113,227,.12)}
|
||||
.profile-section .form-row input:disabled{background:#f5f5f7;color:var(--text3)}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<div class="header-inner">
|
||||
<h1>债务统计</h1>
|
||||
<div class="header-center">
|
||||
<div class="nav-tabs">
|
||||
<a href="/" class="nav-tab active">首页</a>
|
||||
<a href="/analysis.html" class="nav-tab">分析</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-right">
|
||||
<div class="notif-wrap">
|
||||
<div class="notif-bell" onclick="toggleNotifDropdown(event)">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/></svg>
|
||||
<span class="notif-badge" id="notifBadge" style="display:none">0</span>
|
||||
</div>
|
||||
<div class="notif-dropdown" id="notifDropdown">
|
||||
<div class="notif-header"><h4>通知</h4><button class="mark-all" onclick="markAllNotifRead()">全部已读</button></div>
|
||||
<div class="notif-list" id="notifList"><div class="notif-empty">暂无通知</div></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="export-wrap">
|
||||
<span class="user-info" id="userInfo" onclick="toggleUserMenu(event)"></span>
|
||||
<div class="export-menu" id="userMenu">
|
||||
<a href="#" onclick="showProfile()">个人中心</a>
|
||||
<a href="#" onclick="showChangePwd(event)">修改密码</a>
|
||||
</div>
|
||||
</div>
|
||||
<a href="/admin.html" class="admin-link" id="adminLink" style="display:none">管理</a>
|
||||
<div class="export-wrap">
|
||||
<button class="hdr-btn" onclick="toggleExport(event)">导出</button>
|
||||
<div class="export-menu" id="exportMenu">
|
||||
<a href="#" onclick="exportCSV(event)">导出 CSV</a>
|
||||
<a href="#" onclick="exportJSON(event)">导出 JSON</a>
|
||||
<a href="#" onclick="exportHTML(event)">导出 HTML</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="export-wrap">
|
||||
<button class="hdr-btn" onclick="toggleImport(event)">导入</button>
|
||||
<div class="export-menu" id="importMenu">
|
||||
<a href="#" onclick="downloadTemplate(event)">下载模板</a>
|
||||
<a href="#" onclick="showImportModal(event)">导入 CSV</a>
|
||||
</div>
|
||||
</div>
|
||||
<a href="#" class="logout-link" onclick="doLogout()">退出</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="container">
|
||||
<div class="stats-row" id="statsRow"></div>
|
||||
<div class="charts-grid" id="chartsGrid">
|
||||
<div class="chart-card"><h3>借款总额 vs 已还总额</h3><div class="chart-wrap"><canvas id="chartPie"></canvas></div></div>
|
||||
<div class="chart-card"><h3>债权人分布</h3><div class="chart-wrap"><canvas id="chartCreditor"></canvas></div></div>
|
||||
<div class="chart-card"><h3>还款方式分布</h3><div class="chart-wrap"><canvas id="chartMethod"></canvas></div></div>
|
||||
<div class="chart-card"><h3>利率分布</h3><div class="chart-wrap"><canvas id="chartRate"></canvas></div></div>
|
||||
<div class="chart-card full-width"><h3>月度还款计划</h3><div class="chart-wrap"><canvas id="chartMonth"></canvas></div></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const API='/api/v1';
|
||||
let token=localStorage.getItem('access_token')||'';
|
||||
let refreshToken=localStorage.getItem('refresh_token')||'';
|
||||
let currentUser=null;
|
||||
let loans=[];
|
||||
const $=id=>document.getElementById(id);
|
||||
const fmt=n=>n.toLocaleString('zh-CN',{minimumFractionDigits:2,maximumFractionDigits:2});
|
||||
|
||||
async function apiFetch(path,opts={}){
|
||||
const headers={'Content-Type':'application/json',...opts.headers};
|
||||
if(token)headers['Authorization']='Bearer '+token;
|
||||
let res=await fetch(API+path,{...opts,headers});
|
||||
if(res.status===401&&refreshToken){
|
||||
const r=await fetch(API+'/auth/refresh',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({refresh_token:refreshToken})});
|
||||
if(r.ok){const d=await r.json();token=d.access_token;refreshToken=d.refresh_token;localStorage.setItem('access_token',token);localStorage.setItem('refresh_token',refreshToken);headers['Authorization']='Bearer '+token;res=await fetch(API+path,{...opts,headers});}
|
||||
else{doLogout();return null;}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
function toggleUserMenu(e){e.stopPropagation();$('userMenu').classList.toggle('show');}
|
||||
|
||||
function showChangeNick(e){if(e)e.preventDefault();$('userMenu').classList.remove('show');$('newNick').value='';$('nickError').style.display='none';$('nickSuccess').style.display='none';$('changeNickModal').classList.add('show');}
|
||||
function closeChangeNick(){$('changeNickModal').classList.remove('show');}
|
||||
async function doChangeNick(){const nick=$('newNick').value.trim();if(!nick)return $('nickError').textContent='请输入昵称';$('nickError').style.display='';$('nickError').style.display='none';const res=await apiFetch('/auth/profile',{method:'PUT',body:JSON.stringify({nickname:nick})});if(res&&res.ok){$('nickSuccess').style.display='';$('nickSuccess').textContent='昵称修改成功';currentUser.nickname=nick;$('userInfo').textContent=nick||currentUser.account;}else{const d=await res.json();$('nickError').textContent=d.detail||'修改失败';$('nickError').style.display='';}}
|
||||
function showChangePwd(e){if(e)e.preventDefault();$('userMenu').classList.remove('show');$('oldPwd').value='';$('newPwd').value='';$('newPwd2').value='';$('pwdError').style.display='none';$('pwdSuccess').style.display='none';$('changePwdModal').classList.add('show');}
|
||||
function closeChangePwd(){$('changePwdModal').classList.remove('show');}
|
||||
async function doChangePwd(){const old=$('oldPwd').value,nw=$('newPwd').value,nw2=$('newPwd2').value;if(!old||!nw)return $('pwdError').textContent='请填写所有字段';$('pwdError').style.display='';if(nw!==nw2){$('pwdError').textContent='两次新密码不一致';$('pwdError').style.display='';return;}$('pwdError').style.display='none';const res=await apiFetch('/auth/password',{method:'PUT',body:JSON.stringify({old_password:old,new_password:nw})});if(res&&res.ok){$('pwdSuccess').style.display='';$('pwdSuccess').textContent='密码修改成功';$('oldPwd').value='';$('newPwd').value='';$('newPwd2').value='';}else{const d=await res.json();$('pwdError').textContent=d.detail||'修改失败';$('pwdError').style.display='';}}
|
||||
|
||||
|
||||
function showProfile(){
|
||||
$('userMenu').classList.remove('show');
|
||||
$('profileAccount').value=currentUser.account;
|
||||
$('profileNickname').value=currentUser.nickname||'';
|
||||
$('profileEmail').value=currentUser.real_email||'';
|
||||
$('emailCodeRow').style.display='none';
|
||||
$('profileEmailCode').value='';
|
||||
$('profileError').style.display='none';
|
||||
$('profileSuccess').style.display='none';
|
||||
$('profileModal').classList.add('show');
|
||||
}
|
||||
function closeProfile(){$('profileModal').classList.remove('show');}
|
||||
|
||||
let emailVerifySent=false;
|
||||
async function sendEmailVerify(){
|
||||
const email=$('profileEmail').value.trim();
|
||||
if(!email||!email.includes('@')){showProfileError('请输入有效邮箱');return;}
|
||||
$('profileError').style.display='none';
|
||||
const res=await apiFetch('/auth/verify-email',{method:'POST',body:JSON.stringify({email})});
|
||||
if(res&&res.ok){
|
||||
emailVerifySent=true;
|
||||
$('emailCodeRow').style.display='';
|
||||
$('profileSuccess').style.display='';$('profileSuccess').textContent='验证码已发送到当前邮箱';
|
||||
}else{
|
||||
const d=await res.json().catch(()=>({}));
|
||||
showProfileError(d.detail||'发送失败');
|
||||
}
|
||||
}
|
||||
|
||||
function showProfileError(msg){$('profileError').textContent=msg;$('profileError').style.display='';}
|
||||
function hideProfileError(){$('profileError').style.display='none';}
|
||||
|
||||
async function saveProfile(){
|
||||
const nick=$('profileNickname').value.trim();
|
||||
const email=$('profileEmail').value.trim();
|
||||
const code=$('profileEmailCode').value.trim();
|
||||
|
||||
hideProfileError();
|
||||
$('profileSuccess').style.display='none';
|
||||
|
||||
// Update nickname
|
||||
if(nick!==currentUser.nickname){
|
||||
const res=await apiFetch('/auth/profile',{method:'PUT',body:JSON.stringify({nickname:nick})});
|
||||
if(res&&res.ok){currentUser.nickname=nick;$('userInfo').textContent=nick||currentUser.account;}
|
||||
else{const d=await res.json().catch(()=>({}));showProfileError(d.detail||'昵称修改失败');return;}
|
||||
}
|
||||
|
||||
// Update email if changed and code provided
|
||||
if(email&&email!==currentUser.real_email){
|
||||
if(!code){showProfileError('请输入邮箱验证码');$('emailCodeRow').style.display='';return;}
|
||||
const res=await apiFetch('/auth/change-email',{method:'POST',body:JSON.stringify({code,new_email:email})});
|
||||
if(res&&res.ok){currentUser.real_email=email;}
|
||||
else{const d=await res.json().catch(()=>({}));showProfileError(d.detail||'邮箱修改失败');return;}
|
||||
}
|
||||
|
||||
$('profileSuccess').style.display='';$('profileSuccess').textContent='保存成功';
|
||||
setTimeout(()=>{closeProfile();},1000);
|
||||
}
|
||||
|
||||
async function checkAuth(){
|
||||
if(!token){window.location.href='/';return false;}
|
||||
const res=await apiFetch('/auth/profile');
|
||||
if(!res||!res.ok){window.location.href='/';return false;}
|
||||
currentUser=await res.json();
|
||||
$('userInfo').textContent=currentUser.nickname||currentUser.account;
|
||||
if(currentUser.role==='admin')$('adminLink').style.display='';
|
||||
return true;
|
||||
}
|
||||
|
||||
function doLogout(){token='';refreshToken='';currentUser=null;localStorage.removeItem('access_token');localStorage.removeItem('refresh_token');window.location.href='/';}
|
||||
|
||||
async function loadLoans(){const res=await apiFetch('/loans');if(!res||!res.ok)return;loans=await res.json();renderAll();}
|
||||
|
||||
function renderAll(){
|
||||
if(!loans.length){$('statsRow').innerHTML='<div class="empty-tip">暂无数据</div>';return;}
|
||||
renderStats();renderPie();renderCreditor();renderMethod();renderRate();renderMonth();
|
||||
}
|
||||
|
||||
function renderStats(){
|
||||
let totalAmt=0,totalInt=0,totalPaid=0,paidN=0,totalN=0;
|
||||
loans.forEach(l=>{
|
||||
totalAmt+=l.amount;totalN+=l.periods;
|
||||
totalInt+=l.schedule.reduce((a,r)=>a+r.it,0);
|
||||
paidN+=l.paid.length;
|
||||
totalPaid+=l.schedule.filter(r=>l.paid.includes(r.p)).reduce((a,r)=>a+r.pay,0);
|
||||
});
|
||||
const totalPay=totalAmt+totalInt;
|
||||
$('statsRow').innerHTML=`
|
||||
<div class="stat-card"><div class="lbl">借款总额</div><div class="val blue">¥${fmt(totalAmt)}</div></div>
|
||||
<div class="stat-card"><div class="lbl">总利息</div><div class="val red">¥${fmt(totalInt)}</div></div>
|
||||
<div class="stat-card"><div class="lbl">已还</div><div class="val green">¥${fmt(totalPaid)}</div></div>
|
||||
<div class="stat-card"><div class="lbl">还款进度</div><div class="val orange">${paidN}/${totalN}期</div></div>`;
|
||||
}
|
||||
|
||||
function renderPie(){
|
||||
let totalAmt=0,totalPaid=0;
|
||||
loans.forEach(l=>{
|
||||
totalAmt+=l.amount;
|
||||
totalPaid+=l.schedule.filter(r=>l.paid.includes(r.p)).reduce((a,r)=>a+r.pay,0);
|
||||
});
|
||||
const remain=Math.max(0,totalAmt+loans.reduce((s,l)=>s+l.schedule.reduce((a,r)=>a+r.it,0),0)-totalPaid);
|
||||
new Chart($('chartPie'),{type:'doughnut',data:{labels:['已还本金','待还本金','已还利息','待还利息'],datasets:[{data:[totalPaid*0.85,Math.max(0,totalAmt-totalPaid*0.85),totalPaid*0.15,Math.max(0,loans.reduce((s,l)=>s+l.schedule.reduce((a,r)=>a+r.it,0),0)-totalPaid*0.15)],backgroundColor:['#34c759','#0071e3','#30d158','#5ac8fa']}]},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'bottom',labels:{padding:12,font:{size:12}}}}}});
|
||||
}
|
||||
|
||||
function renderCreditor(){
|
||||
const map={};loans.forEach(l=>{map[l.name]=(map[l.name]||0)+l.amount;});
|
||||
const sorted=Object.entries(map).sort((a,b)=>b[1]-a[1]).slice(0,8);
|
||||
new Chart($('chartCreditor'),{type:'bar',data:{labels:sorted.map(s=>s[0]),datasets:[{label:'借款金额',data:sorted.map(s=>s[1]),backgroundColor:['#0071e3','#34c759','#ff9500','#af52de','#ff3b30','#5ac8fa','#30d158','#ff6b35']}]},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true,ticks:{callback:v=>'¥'+v.toLocaleString()}},x:{ticks:{font:{size:11}}}}}});
|
||||
}
|
||||
|
||||
function renderMethod(){
|
||||
const map={};loans.forEach(l=>{const m=l.method==='e'?'等额本息':l.method==='p'?'等额本金':'先息后本';map[m]=(map[m]||0)+1;});
|
||||
new Chart($('chartMethod'),{type:'doughnut',data:{labels:Object.keys(map),datasets:[{data:Object.values(map),backgroundColor:['#0071e3','#ff9500','#af52de']}]},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'bottom',labels:{padding:12,font:{size:12}}}}}});
|
||||
}
|
||||
|
||||
function renderRate(){
|
||||
const buckets={'0%':0,'0-5%':0,'5-10%':0,'10-15%':0,'15-20%':0,'20%+':0};
|
||||
loans.forEach(l=>{
|
||||
const r=l.rate;
|
||||
if(r===0)buckets['0%']++;
|
||||
else if(r<5)buckets['0-5%']++;
|
||||
else if(r<10)buckets['5-10%']++;
|
||||
else if(r<15)buckets['10-15%']++;
|
||||
else if(r<20)buckets['15-20%']++;
|
||||
else buckets['20%+']++;
|
||||
});
|
||||
new Chart($('chartRate'),{type:'bar',data:{labels:Object.keys(buckets),datasets:[{label:'借款数量',data:Object.values(buckets),backgroundColor:['#34c759','#5ac8fa','#0071e3','#ff9500','#ff6b35','#ff3b30']}]},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true,ticks:{stepSize:1}},x:{ticks:{font:{size:11}}}}}});
|
||||
}
|
||||
|
||||
function renderMonth(){
|
||||
const map={};loans.forEach(l=>{l.schedule.forEach(r=>{const ym=r.date.slice(0,7);if(!map[ym])map[ym]={total:0,paid:0};map[ym].total+=r.pay;if(l.paid.includes(r.p))map[ym].paid+=r.pay;});});
|
||||
const months=Object.keys(map).sort().slice(0,12);
|
||||
new Chart($('chartMonth'),{type:'bar',data:{labels:months.map(m=>m.replace('-','年')+'月'),datasets:[{label:'应还',data:months.map(m=>map[m].total),backgroundColor:'rgba(0,113,227,.3)',borderColor:'#0071e3',borderWidth:1},{label:'已还',data:months.map(m=>map[m].paid),backgroundColor:'rgba(52,199,89,.5)',borderColor:'#34c759',borderWidth:1}]},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'bottom',labels:{padding:12,font:{size:12}}}},scales:{y:{beginAtZero:true,ticks:{callback:v=>'¥'+v.toLocaleString()}},x:{ticks:{font:{size:10}}}}}});
|
||||
}
|
||||
|
||||
|
||||
function escapeHtml(s){if(!s)return'';const d=document.createElement('div');d.textContent=s;return d.innerHTML;}
|
||||
function notifTypeIcon(type){const map={repayment_due:'📅',repayment_overdue:'⚠️',system:'📢',account:'👤'};return map[type]||'📩';}
|
||||
function timeAgo(dt){const diff=(Date.now()-new Date(dt).getTime())/1000;if(diff<60)return '刚刚';if(diff<3600)return Math.floor(diff/60)+'分钟前';if(diff<86400)return Math.floor(diff/3600)+'小时前';return Math.floor(diff/86400)+'天前';}
|
||||
|
||||
function toggleNotifDropdown(e){e.stopPropagation();const dd=$('notifDropdown');dd.classList.toggle('show');if(dd.classList.contains('show'))loadNotifications();}
|
||||
document.addEventListener('click',function(){$('notifDropdown')?.classList.remove('show');$('exportMenu')?.classList.remove('show');$('importMenu')?.classList.remove('show');$('userMenu')?.classList.remove('show');});
|
||||
|
||||
async function loadNotifications(){const res=await apiFetch('/notifications?size=20');if(!res||!res.ok)return;const data=await res.json();renderNotifBadge(data.unread);renderNotifList(data.items);}
|
||||
function renderNotifBadge(unread){const badge=$('notifBadge');if(unread>0){badge.style.display='';badge.textContent=unread>99?'99+':unread;}else{badge.style.display='none';}}
|
||||
function renderNotifList(items){const el=$('notifList');if(!items.length){el.innerHTML='<div class="notif-empty">暂无通知</div>';return;}el.innerHTML=items.map(n=>`<div class="notif-item${n.is_read===0?' unread':''}" onclick="readNotif(${n.id})"><div class="notif-icon ${n.type}">${notifTypeIcon(n.type)}</div><div class="notif-content"><div class="notif-title">${escapeHtml(n.title)}</div><div class="notif-msg">${escapeHtml(n.message)}</div></div><div class="notif-time">${timeAgo(n.created_at)}</div></div>`).join('');}
|
||||
async function readNotif(id){await apiFetch('/notifications/'+id+'/read',{method:'PUT'});loadNotifications();}
|
||||
|
||||
function toggleExport(e){e.stopPropagation();$('exportMenu').classList.toggle('show');}
|
||||
function toggleImport(e){e.stopPropagation();$('importMenu').classList.toggle('show');}
|
||||
function download(filename,content,mime){const blob=new Blob(['\uFEFF'+content],{type:mime});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=filename;a.click();}
|
||||
function getVisibleLoans(){return currentUser&¤tUser.role==='admin'?loans:loans.filter(l=>l.user_id===currentUser.id);}
|
||||
|
||||
function exportCSV(e){e.preventDefault();if(!loans.length)return;let csv='债权人,借款日期,借款金额,年化率(%),总利息,分期数,还款方式,已还期数,状态,用途\n';vl.forEach(l=>{const ti=l.schedule.reduce((s,r)=>s+r.it,0);const paid=l.paid.length+'/'+l.periods;const status=l.paid.length>=l.periods?'已还清':'还款中';csv+=`${escapeHtml(l.name)},${l.date},${l.amount},${l.rate},${ti.toFixed(2)},${l.periods},${l.method==='e'?'等额本息':l.method==='p'?'等额本金':'先息后本'},${paid},${status}\n`;});download('债务统计_'+new Date().toISOString().slice(0,10)+'.csv',csv,'text/csv;charset=utf-8');}
|
||||
function exportJSON(e){e.preventDefault();if(!loans.length)return;const data=loans.map(l=>({债权人:l.name,借款日期:l.date,借款金额:l.amount,年化率:l.rate,分期数:l.periods,还款方式:l.method==='e'?'等额本息':l.method==='p'?'等额本金':'先息后本',已还期数:l.paid.length,状态:l.paid.length>=l.periods?'已还清':'还款中',用途:l.purpose||''}));download('债务统计_'+new Date().toISOString().slice(0,10)+'.json',JSON.stringify(data,null,2),'application/json;charset=utf-8');}
|
||||
function exportHTML(e){e.preventDefault();if(!loans.length)return;let h=`<html><head><meta charset="utf-8"><title>债务统计</title></head><body><h2>债务统计报表</h2><table border="1"><tr><th>借款人</th><th>金额</th><th>利率</th><th>期数</th></tr>`;loans.forEach(l=>{h+=`<tr><td>${escapeHtml(l.name)}</td><td>¥${l.amount.toLocaleString()}</td><td>${l.rate}%</td><td>${l.paid.length}/${l.periods}</td></tr>`;});h+=`</table>
|
||||
<div class="modal-mask" id="changeNickModal"><div class="modal"><h3>修改昵称</h3><div class="form-row"><label>新昵称</label><input type="text" id="newNick" placeholder="请输入新昵称"></div><div id="nickError" class="error-msg" style="display:none"></div><div id="nickSuccess" class="success-msg" style="display:none"></div><div class="btn-row"><button class="btn btn-ghost" onclick="closeChangeNick()">取消</button><button class="btn btn-main" onclick="doChangeNick()">确认修改</button></div></div></div>
|
||||
<div class="modal-mask" id="changePwdModal"><div class="modal"><h3>修改密码</h3><div class="form-row"><label>原密码</label><input type="password" id="oldPwd" placeholder="请输入原密码"></div><div class="form-row"><label>新密码</label><input type="password" id="newPwd" placeholder="请输入新密码"></div><div class="form-row"><label>确认新密码</label><input type="password" id="newPwd2" placeholder="请再次输入新密码"></div><div id="pwdError" class="error-msg" style="display:none"></div><div id="pwdSuccess" class="success-msg" style="display:none"></div><div class="btn-row"><button class="btn btn-ghost" onclick="closeChangePwd()">取消</button><button class="btn btn-main" onclick="doChangePwd()">确认修改</button></div></div></div>
|
||||
|
||||
<div class="modal-mask" id="profileModal">
|
||||
<div class="modal" style="max-width:480px">
|
||||
<h3>个人中心</h3>
|
||||
<div class="profile-section">
|
||||
<div class="form-row"><label>账号</label><input type="text" id="profileAccount" disabled style="background:#f5f5f7"></div>
|
||||
<div class="form-row"><label>昵称</label><input type="text" id="profileNickname" placeholder="请输入昵称"></div>
|
||||
<div class="form-row">
|
||||
<label>邮箱</label>
|
||||
<div style="display:flex;gap:8px">
|
||||
<input type="email" id="profileEmail" placeholder="请输入邮箱" style="flex:1">
|
||||
<button class="btn btn-ghost" style="flex:none;width:auto;padding:8px 16px;font-size:12px" onclick="sendEmailVerify()">发送验证码</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row" id="emailCodeRow" style="display:none">
|
||||
<label>验证码</label>
|
||||
<input type="text" id="profileEmailCode" placeholder="请输入6位验证码" maxlength="6">
|
||||
</div>
|
||||
<div id="profileError" class="error-msg" style="display:none"></div>
|
||||
<div id="profileSuccess" class="success-msg" style="display:none"></div>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-ghost" onclick="closeProfile()">取消</button>
|
||||
<button class="btn btn-main" onclick="saveProfile()">保存</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body></html>`;download('债务统计_'+new Date().toISOString().slice(0,10)+'.html',h,'text/html;charset=utf-8');}
|
||||
function downloadTemplate(e){e.preventDefault();$('importMenu').classList.remove('show');let csv='借款人,借款日期,借款金额,年利率(%),总利息,分期数,还款方式\n';csv+='张三,2026-01-01,100000,5.7,5198.99,24,等额本息\n';download('导入模板.csv',csv,'text/csv;charset=utf-8');}
|
||||
function showImportModal(e){e.preventDefault();$('importMenu').classList.remove('show');}
|
||||
|
||||
checkAuth().then(ok=>{if(ok)loadLoans();});
|
||||
</script>
|
||||
|
||||
<div class="modal-mask" id="changeNickModal"><div class="modal"><h3>修改昵称</h3><div class="form-row"><label>新昵称</label><input type="text" id="newNick" placeholder="请输入新昵称"></div><div id="nickError" class="error-msg" style="display:none"></div><div id="nickSuccess" class="success-msg" style="display:none"></div><div class="btn-row"><button class="btn btn-ghost" onclick="closeChangeNick()">取消</button><button class="btn btn-main" onclick="doChangeNick()">确认修改</button></div></div></div>
|
||||
<div class="modal-mask" id="changePwdModal"><div class="modal"><h3>修改密码</h3><div class="form-row"><label>原密码</label><input type="password" id="oldPwd" placeholder="请输入原密码"></div><div class="form-row"><label>新密码</label><input type="password" id="newPwd" placeholder="请输入新密码"></div><div class="form-row"><label>确认新密码</label><input type="password" id="newPwd2" placeholder="请再次输入新密码"></div><div id="pwdError" class="error-msg" style="display:none"></div><div id="pwdSuccess" class="success-msg" style="display:none"></div><div class="btn-row"><button class="btn btn-ghost" onclick="closeChangePwd()">取消</button><button class="btn btn-main" onclick="doChangePwd()">确认修改</button></div></div></div>
|
||||
|
||||
<div class="modal-mask" id="profileModal">
|
||||
<div class="modal" style="max-width:480px">
|
||||
<h3>个人中心</h3>
|
||||
<div class="profile-section">
|
||||
<div class="form-row"><label>账号</label><input type="text" id="profileAccount" disabled style="background:#f5f5f7"></div>
|
||||
<div class="form-row"><label>昵称</label><input type="text" id="profileNickname" placeholder="请输入昵称"></div>
|
||||
<div class="form-row">
|
||||
<label>邮箱</label>
|
||||
<div style="display:flex;gap:8px">
|
||||
<input type="email" id="profileEmail" placeholder="请输入邮箱" style="flex:1">
|
||||
<button class="btn btn-ghost" style="flex:none;width:auto;padding:8px 16px;font-size:12px" onclick="sendEmailVerify()">发送验证码</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row" id="emailCodeRow" style="display:none">
|
||||
<label>验证码</label>
|
||||
<input type="text" id="profileEmailCode" placeholder="请输入6位验证码" maxlength="6">
|
||||
</div>
|
||||
<div id="profileError" class="error-msg" style="display:none"></div>
|
||||
<div id="profileSuccess" class="success-msg" style="display:none"></div>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-ghost" onclick="closeProfile()">取消</button>
|
||||
<button class="btn btn-main" onclick="saveProfile()">保存</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
20
frontend/chart.min.js
vendored
Normal file
20
frontend/chart.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
@@ -27,9 +27,14 @@
|
||||
body{font-family:-apple-system,BlinkMacSystemFont,"SF Pro Display","SF Pro Text","PingFang SC",sans-serif;background:var(--bg);color:var(--text);min-height:100vh;font-size:14px;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}
|
||||
|
||||
/* HEADER */
|
||||
.header{background:rgba(255,255,255,.72);backdrop-filter:saturate(180%) blur(20px);-webkit-backdrop-filter:saturate(180%) blur(20px);border-bottom:1px solid var(--border);position:sticky;top:0;z-index:40;padding:0}
|
||||
.header-inner{max-width:1120px;margin:0 auto;padding:0 24px;height:52px;display:flex;align-items:center;justify-content:space-between}
|
||||
.header{background:rgba(255,255,255,.72);backdrop-filter:saturate(180%) blur(20px);-webkit-backdrop-filter:saturate(180%) blur(20px);border-bottom:1px solid var(--border);position:sticky;top:0;z-index:40}
|
||||
.header-inner{max-width:1200px;margin:0 auto;padding:0 24px;height:52px;display:flex;align-items:center;justify-content:space-between}
|
||||
.header h1{font-size:17px;font-weight:600;color:var(--text);letter-spacing:-.2px}
|
||||
.header-center{position:absolute;left:50%;transform:translateX(-50%)}
|
||||
.nav-tabs{display:flex;gap:4px;background:rgba(0,0,0,.04);border-radius:var(--radius-xs);padding:3px}
|
||||
.nav-tab{padding:6px 16px;border-radius:6px;font-size:13px;font-weight:500;color:var(--text2);text-decoration:none;transition:all .2s}
|
||||
.nav-tab:hover{color:var(--text)}
|
||||
.nav-tab.active{background:#fff;color:var(--text);box-shadow:0 1px 3px rgba(0,0,0,.08)}
|
||||
.header-right{display:flex;align-items:center;gap:4px}
|
||||
.header-right a,.hdr-btn{color:var(--text2);text-decoration:none;font-size:12px;padding:6px 12px;border-radius:var(--radius-xs);transition:all .2s;background:transparent;border:none;cursor:pointer;font-family:inherit}
|
||||
.header-right a:hover,.hdr-btn:hover{background:rgba(0,0,0,.04);color:var(--text)}
|
||||
@@ -37,6 +42,36 @@ body{font-family:-apple-system,BlinkMacSystemFont,"SF Pro Display","SF Pro Text"
|
||||
.header-right .logout-link{color:var(--red)}
|
||||
.user-info{color:var(--text);font-size:13px;font-weight:500;cursor:pointer;padding:6px 12px;border-radius:var(--radius-xs);transition:all .2s}
|
||||
.user-info:hover{background:rgba(0,0,0,.04)}
|
||||
.notif-wrap{position:relative}
|
||||
.notif-bell{cursor:pointer;padding:4px 8px;border-radius:var(--radius-xs);transition:all .2s;color:var(--text2)}
|
||||
.notif-bell:hover{background:rgba(0,0,0,.04);color:var(--text)}
|
||||
.notif-badge{position:absolute;top:2px;right:2px;min-width:14px;height:14px;background:var(--red);color:#fff;border-radius:7px;font-size:9px;font-weight:600;display:flex;align-items:center;justify-content:center;padding:0 3px}
|
||||
.notif-dropdown{display:none;position:absolute;right:0;top:calc(100% + 8px);background:rgba(255,255,255,.96);backdrop-filter:blur(24px);border:1px solid var(--border);border-radius:var(--radius);box-shadow:0 12px 48px rgba(0,0,0,.15);width:360px;max-height:480px;overflow:hidden;z-index:60}
|
||||
.notif-dropdown.show{display:block}
|
||||
.notif-header{padding:14px 16px;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;align-items:center}
|
||||
.notif-header h4{font-size:14px;font-weight:600;color:var(--text)}
|
||||
.notif-header .mark-all{font-size:12px;color:var(--blue);cursor:pointer;background:none;border:none;font-family:inherit}
|
||||
.notif-list{overflow-y:auto;max-height:380px}
|
||||
.notif-item{padding:12px 16px;border-bottom:1px solid var(--border);cursor:pointer;transition:background .15s;display:flex;gap:12px;align-items:flex-start}
|
||||
.notif-item:hover{background:rgba(0,0,0,.02)}
|
||||
.notif-item.unread{background:rgba(0,113,227,.03)}
|
||||
.notif-item .notif-icon{width:32px;height:32px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0}
|
||||
.notif-icon.repayment_due{background:rgba(0,113,227,.08)}
|
||||
.notif-icon.repayment_overdue{background:rgba(255,59,48,.08)}
|
||||
.notif-icon.system{background:rgba(175,82,222,.08)}
|
||||
.notif-icon.account{background:rgba(52,199,89,.08)}
|
||||
.notif-item .notif-content{flex:1;min-width:0}
|
||||
.notif-item .notif-title{font-size:13px;font-weight:500;color:var(--text);margin-bottom:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.notif-item .notif-msg{font-size:12px;color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.notif-item .notif-time{font-size:11px;color:var(--text3);white-space:nowrap}
|
||||
.notif-empty{text-align:center;padding:32px;color:var(--text3);font-size:13px}
|
||||
.export-wrap{position:relative}
|
||||
.export-menu{display:none;position:absolute;right:0;top:calc(100% + 4px);background:rgba(255,255,255,.95);backdrop-filter:blur(20px);border:1px solid var(--border);border-radius:var(--radius-sm);box-shadow:0 8px 32px rgba(0,0,0,.12);min-width:160px;z-index:50;overflow:hidden}
|
||||
.export-menu.show{display:block}
|
||||
.export-menu a{display:block;padding:10px 18px;font-size:13px;color:var(--text);text-decoration:none;transition:background .15s}
|
||||
.export-menu a:hover{background:rgba(0,0,0,.04)}
|
||||
.user-info{color:var(--text);font-size:13px;font-weight:500;cursor:pointer;padding:6px 14px;border-radius:var(--radius-xs);transition:all .2s;background:rgba(0,0,0,.02)}
|
||||
.user-info:hover{background:rgba(0,0,0,.06)}
|
||||
|
||||
/* MAIN */
|
||||
.main{max-width:1120px;margin:0 auto;padding:24px;display:grid;grid-template-columns:320px 1fr;gap:20px}
|
||||
@@ -245,6 +280,13 @@ body{font-family:-apple-system,BlinkMacSystemFont,"SF Pro Display","SF Pro Text"
|
||||
.notif-item .notif-msg{font-size:12px;color:var(--text3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.notif-item .notif-time{font-size:11px;color:var(--text3);white-space:nowrap}
|
||||
.notif-empty{text-align:center;padding:32px;color:var(--text3);font-size:13px}
|
||||
|
||||
.profile-section{padding:4px 0}
|
||||
.profile-section .form-row{margin-bottom:14px}
|
||||
.profile-section .form-row label{display:block;font-size:13px;font-weight:500;margin-bottom:4px;color:var(--text2)}
|
||||
.profile-section .form-row input{width:100%;padding:10px 14px;border:1px solid #d2d2d7;border-radius:var(--radius-xs);font-size:14px;outline:none;transition:all .2s}
|
||||
.profile-section .form-row input:focus{border-color:var(--blue);box-shadow:0 0 0 3px rgba(0,113,227,.12)}
|
||||
.profile-section .form-row input:disabled{background:#f5f5f7;color:var(--text3)}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
@@ -322,26 +364,27 @@ body{font-family:-apple-system,BlinkMacSystemFont,"SF Pro Display","SF Pro Text"
|
||||
<div class="header">
|
||||
<div class="header-inner">
|
||||
<h1>债务统计</h1>
|
||||
<div class="header-center">
|
||||
<div class="nav-tabs">
|
||||
<a href="/" class="nav-tab active">首页</a>
|
||||
<a href="/analysis.html" class="nav-tab">分析</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="header-right">
|
||||
<div class="export-wrap" style="position:relative">
|
||||
<div class="notif-wrap">
|
||||
<div class="notif-bell" onclick="toggleNotifDropdown(event)">
|
||||
<svg viewBox="0 0 24 24"><path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/></svg>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/></svg>
|
||||
<span class="notif-badge" id="notifBadge" style="display:none">0</span>
|
||||
</div>
|
||||
<div class="notif-dropdown" id="notifDropdown">
|
||||
<div class="notif-header">
|
||||
<h4>通知</h4>
|
||||
<button class="mark-all" onclick="markAllNotifRead()">全部已读</button>
|
||||
</div>
|
||||
<div class="notif-list" id="notifList">
|
||||
<div class="notif-empty">暂无通知</div>
|
||||
</div>
|
||||
<div class="notif-header"><h4>通知</h4><button class="mark-all" onclick="markAllNotifRead()">全部已读</button></div>
|
||||
<div class="notif-list" id="notifList"><div class="notif-empty">暂无通知</div></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="export-wrap">
|
||||
<span class="user-info" id="userInfo" onclick="toggleUserMenu(event)"></span>
|
||||
<div class="export-menu" id="userMenu">
|
||||
<a href="#" onclick="showChangeNick(event)">修改昵称</a>
|
||||
<a href="#" onclick="showProfile()">个人中心</a>
|
||||
<a href="#" onclick="showChangePwd(event)">修改密码</a>
|
||||
</div>
|
||||
</div>
|
||||
@@ -365,7 +408,6 @@ body{font-family:-apple-system,BlinkMacSystemFont,"SF Pro Display","SF Pro Text"
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="main">
|
||||
<div style="display:flex;flex-direction:column;gap:16px">
|
||||
<div class="panel">
|
||||
@@ -464,6 +506,67 @@ async function apiFetch(path,opts={}){
|
||||
return res;
|
||||
}
|
||||
|
||||
function toggleUserMenu(e){e.stopPropagation();$('userMenu').classList.toggle('show');}
|
||||
|
||||
function showProfile(){
|
||||
$('userMenu').classList.remove('show');
|
||||
$('profileAccount').value=currentUser.account;
|
||||
$('profileNickname').value=currentUser.nickname||'';
|
||||
$('profileEmail').value=currentUser.real_email||'';
|
||||
$('emailCodeRow').style.display='none';
|
||||
$('profileEmailCode').value='';
|
||||
$('profileError').style.display='none';
|
||||
$('profileSuccess').style.display='none';
|
||||
$('profileModal').classList.add('show');
|
||||
}
|
||||
function closeProfile(){$('profileModal').classList.remove('show');}
|
||||
|
||||
let emailVerifySent=false;
|
||||
async function sendEmailVerify(){
|
||||
const email=$('profileEmail').value.trim();
|
||||
if(!email||!email.includes('@')){showProfileError('请输入有效邮箱');return;}
|
||||
$('profileError').style.display='none';
|
||||
const res=await apiFetch('/auth/verify-email',{method:'POST',body:JSON.stringify({email})});
|
||||
if(res&&res.ok){
|
||||
emailVerifySent=true;
|
||||
$('emailCodeRow').style.display='';
|
||||
$('profileSuccess').style.display='';$('profileSuccess').textContent='验证码已发送到当前邮箱';
|
||||
}else{
|
||||
const d=await res.json().catch(()=>({}));
|
||||
showProfileError(d.detail||'发送失败');
|
||||
}
|
||||
}
|
||||
|
||||
function showProfileError(msg){$('profileError').textContent=msg;$('profileError').style.display='';}
|
||||
function hideProfileError(){$('profileError').style.display='none';}
|
||||
|
||||
async function saveProfile(){
|
||||
const nick=$('profileNickname').value.trim();
|
||||
const email=$('profileEmail').value.trim();
|
||||
const code=$('profileEmailCode').value.trim();
|
||||
|
||||
hideProfileError();
|
||||
$('profileSuccess').style.display='none';
|
||||
|
||||
// Update nickname
|
||||
if(nick!==currentUser.nickname){
|
||||
const res=await apiFetch('/auth/profile',{method:'PUT',body:JSON.stringify({nickname:nick})});
|
||||
if(res&&res.ok){currentUser.nickname=nick;$('userInfo').textContent=nick||currentUser.account;}
|
||||
else{const d=await res.json().catch(()=>({}));showProfileError(d.detail||'昵称修改失败');return;}
|
||||
}
|
||||
|
||||
// Update email if changed and code provided
|
||||
if(email&&email!==currentUser.real_email){
|
||||
if(!code){showProfileError('请输入邮箱验证码');$('emailCodeRow').style.display='';return;}
|
||||
const res=await apiFetch('/auth/change-email',{method:'POST',body:JSON.stringify({code,new_email:email})});
|
||||
if(res&&res.ok){currentUser.real_email=email;}
|
||||
else{const d=await res.json().catch(()=>({}));showProfileError(d.detail||'邮箱修改失败');return;}
|
||||
}
|
||||
|
||||
$('profileSuccess').style.display='';$('profileSuccess').textContent='保存成功';
|
||||
setTimeout(()=>{closeProfile();},1000);
|
||||
}
|
||||
|
||||
async function checkAuth(){
|
||||
if(!token){showLogin();return false;}
|
||||
const res=await apiFetch('/auth/profile');
|
||||
@@ -588,17 +691,53 @@ function toggleHideOthers(){hideOthers=!hideOthers;$('hideOthersIcon').textConte
|
||||
function toggleMonth(ym){if(openMonths.has(ym))openMonths.delete(ym);else openMonths.add(ym);renderMonthPlan();}
|
||||
|
||||
function toggleExport(e){e.stopPropagation();$('exportMenu').classList.toggle('show');}
|
||||
document.addEventListener('click',function(){$('exportMenu').classList.remove('show');});
|
||||
document.addEventListener('click',function(){$('exportMenu').classList.remove('show');$('importMenu').classList.remove('show');$('userMenu').classList.remove('show');});
|
||||
function download(filename,content,mime){const blob=new Blob(['\uFEFF'+content],{type:mime});const a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=filename;a.click();}
|
||||
function exportCSV(e){e.preventDefault();if(!loans.length)return showToast('暂无数据可导出','info');let csv='借款人,借款日期,借款金额,年利率(%),总利息,分期数,还款方式,已还期数,状态\n';loans.forEach(l=>{const ti=l.schedule.reduce((s,r)=>s+r.it,0);const paid=l.paid.length+'/'+l.periods;const status=l.paid.length>=l.periods?'已还清':'还款中';csv+=`${escapeHtml(l.name)},${l.date},${l.amount},${l.rate},${ti.toFixed(2)},${l.periods},${methodLabel(l.method)},${paid},${status}\n`;});download('债务统计_'+today()+'.csv',csv,'text/csv;charset=utf-8');}
|
||||
function exportJSON(e){e.preventDefault();if(!loans.length)return showToast('暂无数据可导出','info');const data=loans.map(l=>({借款人:l.name,借款日期:l.date,借款金额:l.amount,年利率:l.rate,分期数:l.periods,还款方式:methodLabel(l.method),已还期数:l.paid.length,状态:l.paid.length>=l.periods?'已还清':'还款中',还款计划:l.schedule.map(r=>({期数:r.p,日期:r.date,还款额:r.pay,本金:r.pr,利息:r.it}))}));download('债务统计_'+today()+'.json',JSON.stringify(data,null,2),'application/json;charset=utf-8');}
|
||||
function exportHTML(e){e.preventDefault();if(!loans.length)return showToast('暂无数据可导出','info');let h=`<html><head><meta charset="utf-8"><title>债务统计</title><style>body{font-family:"Microsoft YaHei",sans-serif;padding:20px}h2{color:#1d1d1f}table{border-collapse:collapse;width:100%;font-size:13px;margin-bottom:20px}th{background:#0071e3;color:#fff;padding:8px 12px;text-align:left}td{padding:6px 12px;border-bottom:1px solid #d2d2d7}tr:nth-child(even){background:#f5f5f7}.done{color:#34c759;font-weight:600}</style></head><body><h2>债务统计报表 - ${today()}</h2>`;loans.forEach(l=>{const ti=l.schedule.reduce((s,r)=>s+r.it,0);const st=l.paid.length>=l.periods;h+=`<h3>${escapeHtml(l.name)} - ${l.date} - ¥${fmt(l.amount)}${st?' <span class="done">已还清</span>':''}</h3><p>年利率 ${l.rate}% · ${methodLabel(l.method)} · ${l.periods}期 · 总利息 ¥${ti.toFixed(2)}</p><table><tr><th>期数</th><th>日期</th><th>还款额</th><th>本金</th><th>利息</th><th>剩余本金</th><th>状态</th></tr>`;l.schedule.forEach(r=>{h+=`<tr><td>${r.p}</td><td>${r.date}</td><td>¥${fmt(r.pay)}</td><td>¥${fmt(r.pr)}</td><td>¥${fmt(r.it)}</td><td>¥${fmt(r.rp)}</td><td>${l.paid.includes(r.p)?'✓ 已还':'待还'}</td></tr>`;});h+=`</table>`;});h+=`</body></html>`;download('债务统计_'+today()+'.html',h,'text/html;charset=utf-8');}
|
||||
function getVisibleLoans(){return currentUser&¤tUser.role==='admin'?loans:loans.filter(l=>l.user_id===currentUser.id);}
|
||||
|
||||
function exportCSV(e){e.preventDefault();const vl=getVisibleLoans();if(!vl.length)return showToast('暂无数据可导出','info');let csv='债权人,借款日期,借款金额,年化率(%),总利息,分期数,还款方式,已还期数,状态,用途\n';vl.forEach(l=>{const ti=l.schedule.reduce((s,r)=>s+r.it,0);const paid=l.paid.length+'/'+l.periods;const status=l.paid.length>=l.periods?'已还清':'还款中';csv+=`${escapeHtml(l.name)},${l.date},${l.amount},${l.rate},${ti.toFixed(2)},${l.periods},${methodLabel(l.method)},${paid},${status},${escapeHtml(l.purpose||'')}\n`;});download('债务统计_'+today()+'.csv',csv,'text/csv;charset=utf-8');}
|
||||
function exportJSON(e){e.preventDefault();const vl=getVisibleLoans();if(!vl.length)return showToast('暂无数据可导出','info');const data=vl.map(l=>({债权人:l.name,借款日期:l.date,借款金额:l.amount,年化率:l.rate,分期数:l.periods,还款方式:methodLabel(l.method),已还期数:l.paid.length,状态:l.paid.length>=l.periods?'已还清':'还款中',用途:l.purpose||'',还款计划:l.schedule.map(r=>({期数:r.p,日期:r.date,还款额:r.pay,本金:r.pr,利息:r.it}))}));download('债务统计_'+today()+'.json',JSON.stringify(data,null,2),'application/json;charset=utf-8');}
|
||||
function exportHTML(e){e.preventDefault();const vl=getVisibleLoans();if(!vl.length)return showToast('暂无数据可导出','info');let h=`<html><head><meta charset="utf-8"><title>债务统计</title><style>body{font-family:"Microsoft YaHei",sans-serif;padding:20px}h2{color:#1d1d1f}table{border-collapse:collapse;width:100%;font-size:13px;margin-bottom:20px}th{background:#0071e3;color:#fff;padding:8px 12px;text-align:left}td{padding:6px 12px;border-bottom:1px solid #d2d2d7}tr:nth-child(even){background:#f5f5f7}.done{color:#34c759;font-weight:600}
|
||||
.profile-section{padding:4px 0}
|
||||
.profile-section .form-row{margin-bottom:14px}
|
||||
.profile-section .form-row label{display:block;font-size:13px;font-weight:500;margin-bottom:4px;color:var(--text2)}
|
||||
.profile-section .form-row input{width:100%;padding:10px 14px;border:1px solid #d2d2d7;border-radius:var(--radius-xs);font-size:14px;outline:none;transition:all .2s}
|
||||
.profile-section .form-row input:focus{border-color:var(--blue);box-shadow:0 0 0 3px rgba(0,113,227,.12)}
|
||||
.profile-section .form-row input:disabled{background:#f5f5f7;color:var(--text3)}
|
||||
</style></head><body><h2>债务统计报表 - ${today()}</h2>`;vl.forEach(l=>{const ti=l.schedule.reduce((s,r)=>s+r.it,0);const st=l.paid.length>=l.periods;h+=`<h3>${escapeHtml(l.name)} - ${l.date} - ¥${fmt(l.amount)}${st?' <span class="done">已还清</span>':''}</h3><p>年化率 ${l.rate}% · ${methodLabel(l.method)} · ${l.periods}期 · 总利息 ¥${ti.toFixed(2)}</p><table><tr><th>期数</th><th>日期</th><th>还款额</th><th>本金</th><th>利息</th><th>剩余本金</th><th>状态</th><th>用途</th></tr>`;l.schedule.forEach(r=>{h+=`<tr><td>${r.p}</td><td>${r.date}</td><td>¥${fmt(r.pay)}</td><td>¥${fmt(r.pr)}</td><td>¥${fmt(r.it)}</td><td>¥${fmt(r.rp)}</td><td>${l.paid.includes(r.p)?'✓ 已还':'待还'}</td></tr>`;});h+=`</table>`;});h+=`
|
||||
<div class="modal-mask" id="profileModal">
|
||||
<div class="modal" style="max-width:480px">
|
||||
<h3>个人中心</h3>
|
||||
<div class="profile-section">
|
||||
<div class="form-row"><label>账号</label><input type="text" id="profileAccount" disabled style="background:#f5f5f7"></div>
|
||||
<div class="form-row"><label>昵称</label><input type="text" id="profileNickname" placeholder="请输入昵称"></div>
|
||||
<div class="form-row">
|
||||
<label>邮箱</label>
|
||||
<div style="display:flex;gap:8px">
|
||||
<input type="email" id="profileEmail" placeholder="请输入邮箱" style="flex:1">
|
||||
<button class="btn btn-ghost" style="flex:none;width:auto;padding:8px 16px;font-size:12px" onclick="sendEmailVerify()">发送验证码</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row" id="emailCodeRow" style="display:none">
|
||||
<label>验证码</label>
|
||||
<input type="text" id="profileEmailCode" placeholder="请输入6位验证码" maxlength="6">
|
||||
</div>
|
||||
<div id="profileError" class="error-msg" style="display:none"></div>
|
||||
<div id="profileSuccess" class="success-msg" style="display:none"></div>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-ghost" onclick="closeProfile()">取消</button>
|
||||
<button class="btn btn-main" onclick="saveProfile()">保存</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body></html>`;download('债务统计_'+today()+'.html',h,'text/html;charset=utf-8');}
|
||||
function toggleImport(e){e.stopPropagation();$('importMenu').classList.toggle('show');}
|
||||
document.addEventListener('click',function(){$('importMenu').classList.remove('show');});
|
||||
function showImportModal(e){e.preventDefault();$('importMenu').classList.remove('show');$('importFile').value='';$('importError').style.display='none';$('importSuccess').style.display='none';$('importModal').classList.add('show');}
|
||||
function closeImportModal(){$('importModal').classList.remove('show');}
|
||||
function downloadTemplate(e){e.preventDefault();$('importMenu').classList.remove('show');let csv='借款人,借款日期,借款金额,年利率(%),总利息,分期数,还款方式,已还期数,状态\n';csv+='张三,2026-01-01,100000,5.7,5198.99,24,等额本息,0/24,还款中\n';csv+='李四,2026-03-15,50000,8,1200.00,12,先息后本,0/12,还款中\n';csv+='王五,2026-06-01,30000,0,0.00,6,等额本息,0/6,还款中\n';download('导入模板.csv',csv,'text/csv;charset=utf-8');}
|
||||
async function doImport(){const file=$('importFile').files[0];if(!file){$('importError').textContent='请选择文件';$('importError').style.display='';return;}$('importError').style.display='none';$('importSuccess').style.display='none';const text=await file.text();const lines=text.trim().split('\n');if(lines.length<2){$('importError').textContent='文件为空或格式错误';$('importError').style.display='';return;}const header=lines[0].split(',').map(s=>s.trim());const nameIdx=header.indexOf('借款人'),dateIdx=header.indexOf('借款日期'),amtIdx=header.indexOf('借款金额'),rateIdx=header.indexOf('年利率(%)'),periodsIdx=header.indexOf('分期数'),methodIdx=header.indexOf('还款方式'),paidIdx=header.indexOf('已还期数');if(nameIdx===-1||dateIdx===-1||amtIdx===-1||rateIdx===-1||periodsIdx===-1||methodIdx===-1){$('importError').textContent='缺少必需列:借款人,借款日期,借款金额,年利率(%),分期数,还款方式';$('importError').style.display='';return;}const methodMap={'等额本息':'e','等额本金':'p','先息后本':'i','e':'e','p':'p','i':'i'};let imported=0,failed=0;for(let i=1;i<lines.length;i++){const line=lines[i].trim();if(!line)continue;const cols=line.split(',').map(s=>s.trim());if(cols.length<6)continue;const name=cols[nameIdx],date=cols[dateIdx],amount=parseFloat(cols[amtIdx]),rate=parseFloat(cols[rateIdx]),periods=parseInt(cols[periodsIdx]),method=methodMap[cols[methodIdx]];if(!name||!date||isNaN(amount)||isNaN(rate)||isNaN(periods)||!method){failed++;continue;}const schedule=calcSchedule(amount,rate,periods,method,date);let paid=[];if(paidIdx>=0&&cols[paidIdx]){const paidStr=cols[paidIdx].trim();const m=paidStr.match(/^(\d+)\//);if(m){const paidCount=parseInt(m[1]);for(let p=1;p<=Math.min(paidCount,periods);p++)paid.push(p);}}const loan={name,date,amount,rate,periods,method,purpose:'',schedule,paid};const saved=await saveLoanToServer(loan);if(saved)loans.push(saved);else failed++;imported++;}if(imported>0){$('importSuccess').style.display='';$('importSuccess').textContent=`成功导入 ${imported} 条${failed?`,失败 ${failed} 条`:''}`;renderAll();}else{$('importError').textContent='导入失败,请检查文件格式';$('importError').style.display='';}}
|
||||
function downloadTemplate(e){e.preventDefault();$('importMenu').classList.remove('show');let csv='债权人,借款日期,借款金额,年化率(%),总利息,分期数,还款方式,已还期数,状态,用途\n';csv+='张三,2026-01-01,100000,5.7,5198.99,24,等额本息,0/24,还款中,装修\n';csv+='李四,2026-03-15,50000,8,1200.00,12,先息后本,0/12,还款中,教育\n';csv+='王五,2026-06-01,30000,0,0.00,6,等额本息,0/6,还款中,\n';download('导入模板.csv',csv,'text/csv;charset=utf-8');}
|
||||
async function doImport(){const file=$('importFile').files[0];if(!file){$('importError').textContent='请选择文件';$('importError').style.display='';return;}$('importError').style.display='none';$('importSuccess').style.display='none';const text=await file.text();const lines=text.trim().split('\n');if(lines.length<2){$('importError').textContent='文件为空或格式错误';$('importError').style.display='';return;}const header=lines[0].split(',').map(s=>s.trim());const nameIdx=header.indexOf('债权人'),dateIdx=header.indexOf('借款日期'),amtIdx=header.indexOf('借款金额'),rateIdx=header.indexOf('年化率(%)'),periodsIdx=header.indexOf('分期数'),methodIdx=header.indexOf('还款方式'),paidIdx=header.indexOf('已还期数');const purposeIdx=header.indexOf('用途');if(nameIdx===-1||dateIdx===-1||amtIdx===-1||rateIdx===-1||periodsIdx===-1||methodIdx===-1){$('importError').textContent='缺少必需列:债权人,借款日期,借款金额,年化率(%),分期数,还款方式';$('importError').style.display='';return;}const methodMap={'等额本息':'e','等额本金':'p','先息后本':'i','e':'e','p':'p','i':'i'};let imported=0,failed=0;for(let i=1;i<lines.length;i++){const line=lines[i].trim();if(!line)continue;const cols=line.split(',').map(s=>s.trim());if(cols.length<6)continue;const name=cols[nameIdx],date=cols[dateIdx],amount=parseFloat(cols[amtIdx]),rate=parseFloat(cols[rateIdx]),periods=parseInt(cols[periodsIdx]),method=methodMap[cols[methodIdx]];if(!name||!date||isNaN(amount)||isNaN(rate)||isNaN(periods)||!method){failed++;continue;}const schedule=calcSchedule(amount,rate,periods,method,date);let paid=[];if(paidIdx>=0&&cols[paidIdx]){const paidStr=cols[paidIdx].trim();const m=paidStr.match(/^(\d+)\//);if(m){const paidCount=parseInt(m[1]);for(let p=1;p<=Math.min(paidCount,periods);p++)paid.push(p);}}const purpose=purposeIdx>=0?cols[purposeIdx]||'':'';const loan={name,date,amount,rate,periods,method,purpose,schedule,paid};const saved=await saveLoanToServer(loan);if(saved)loans.push(saved);else failed++;imported++;}if(imported>0){$('importSuccess').style.display='';$('importSuccess').textContent=`成功导入 ${imported} 条${failed?`,失败 ${failed} 条`:''}`;renderAll();}else{$('importError').textContent='导入失败,请检查文件格式';$('importError').style.display='';}}
|
||||
function toggleUserMenu(e){e.stopPropagation();$('userMenu').classList.toggle('show');}
|
||||
document.addEventListener('click',function(){$('userMenu').classList.remove('show');});
|
||||
function showChangeNick(e){if(e)e.preventDefault();$('userMenu').classList.remove('show');$('newNick').value='';$('nickError').style.display='none';$('nickSuccess').style.display='none';$('changeNickModal').classList.add('show');}
|
||||
@@ -664,5 +803,32 @@ async function doForgotStep3(){
|
||||
|
||||
checkAuth().then(ok=>{if(ok)loadLoans();});
|
||||
</script>
|
||||
|
||||
<div class="modal-mask" id="profileModal">
|
||||
<div class="modal" style="max-width:480px">
|
||||
<h3>个人中心</h3>
|
||||
<div class="profile-section">
|
||||
<div class="form-row"><label>账号</label><input type="text" id="profileAccount" disabled style="background:#f5f5f7"></div>
|
||||
<div class="form-row"><label>昵称</label><input type="text" id="profileNickname" placeholder="请输入昵称"></div>
|
||||
<div class="form-row">
|
||||
<label>邮箱</label>
|
||||
<div style="display:flex;gap:8px">
|
||||
<input type="email" id="profileEmail" placeholder="请输入邮箱" style="flex:1">
|
||||
<button class="btn btn-ghost" style="flex:none;width:auto;padding:8px 16px;font-size:12px" onclick="sendEmailVerify()">发送验证码</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-row" id="emailCodeRow" style="display:none">
|
||||
<label>验证码</label>
|
||||
<input type="text" id="profileEmailCode" placeholder="请输入6位验证码" maxlength="6">
|
||||
</div>
|
||||
<div id="profileError" class="error-msg" style="display:none"></div>
|
||||
<div id="profileSuccess" class="success-msg" style="display:none"></div>
|
||||
<div class="btn-row">
|
||||
<button class="btn btn-ghost" onclick="closeProfile()">取消</button>
|
||||
<button class="btn btn-main" onclick="saveProfile()">保存</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user