Compare commits
54 Commits
v2.0.5
...
c70293b447
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c70293b447 | ||
|
|
ff7eb19d5d | ||
|
|
adeff08827 | ||
|
|
493150cb27 | ||
|
|
8bd40de41d | ||
|
|
caebf90438 | ||
|
|
ac6eacea82 | ||
|
|
34786ba9e5 | ||
|
|
83c2a5ca94 | ||
|
|
fbff2e5f24 | ||
|
|
fbd2290d29 | ||
|
|
0eb9d69f1e | ||
|
|
97fcf88c61 | ||
|
|
003b6f3bdb | ||
|
|
a01afef599 | ||
|
|
9226233de5 | ||
|
|
28fa244fe5 | ||
|
|
96948a37de | ||
|
|
ad3885e0be | ||
|
|
d47fde60a4 | ||
|
|
0fb7ee2992 | ||
|
|
2bb99feda4 | ||
|
|
f6792cad39 | ||
|
|
33f47acc55 | ||
|
|
bed6e9192a | ||
|
|
2c7e6b7d29 | ||
|
|
aaa213a765 | ||
|
|
636b3fc82b | ||
|
|
207629a9bb | ||
|
|
361359ee32 | ||
|
|
25da1453be | ||
|
|
39f2b679a1 | ||
|
|
5f9a92b24d | ||
|
|
b6dd913275 | ||
|
|
9b6257ff19 | ||
|
|
5b1dc4555f | ||
|
|
353f11663c | ||
|
|
f3cf6902dd | ||
|
|
25f3b9fe0d | ||
|
|
cf08b2d241 | ||
|
|
4911f24d40 | ||
|
|
8c24abd53e | ||
|
|
0a7f70757d | ||
|
|
29dc7e040e | ||
|
|
c8387011cc | ||
|
|
5061de70f8 | ||
|
|
ea3ba25da5 | ||
|
|
bd7125fab8 | ||
|
|
94dd1fe677 | ||
|
|
fa6c9b1711 | ||
|
|
f4eacfafe2 | ||
|
|
f8c816dc38 | ||
|
|
e2d9049e45 | ||
|
|
1b0049e342 |
91
.gitea/workflows/deploy.yml
Normal file
91
.gitea/workflows/deploy.yml
Normal file
@@ -0,0 +1,91 @@
|
||||
name: Deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: prod-deploy
|
||||
env:
|
||||
DEPLOY_BASE: /opt/opc-manager
|
||||
REPO_URL: https://qiukai:${{ secrets.DEPLOY_TOKEN }}@git.qiukai.me/qiukai/opc-manager.git
|
||||
SERVICE_NAME: opc-manager
|
||||
steps:
|
||||
- name: Clone and deploy
|
||||
run: |
|
||||
set -e
|
||||
RELEASE_ID="${{ github.sha }}"
|
||||
RELEASE_DIR="${DEPLOY_BASE}/releases/${RELEASE_ID}"
|
||||
CLONE_DIR="/tmp/opc-deploy-${RELEASE_ID}"
|
||||
|
||||
echo "=== 1. Clone repository ==="
|
||||
rm -rf "${CLONE_DIR}"
|
||||
git clone --depth 1 --branch main "${REPO_URL}" "${CLONE_DIR}"
|
||||
|
||||
echo "=== 2. Prepare release directory ==="
|
||||
rm -rf "${RELEASE_DIR}"
|
||||
mkdir -p "${RELEASE_DIR}"
|
||||
|
||||
# Copy repo content to release dir (exclude .git, .env, venv, data)
|
||||
rsync -a --exclude='.git' \
|
||||
--exclude='.env' \
|
||||
--exclude='.env.local' \
|
||||
--exclude='.venv' \
|
||||
--exclude='data/uploads' \
|
||||
--exclude='data/opc.sqlite' \
|
||||
--exclude='__pycache__' \
|
||||
--exclude='.gitea' \
|
||||
"${CLONE_DIR}/" "${RELEASE_DIR}/"
|
||||
|
||||
echo "=== 3. Link shared resources ==="
|
||||
mkdir -p "${RELEASE_DIR}/data"
|
||||
# .env from shared dir (not in git)
|
||||
ln -sfn "${DEPLOY_BASE}/shared/.env" "${RELEASE_DIR}/.env"
|
||||
# uploads directory from shared (persist across releases)
|
||||
mkdir -p "${DEPLOY_BASE}/shared/uploads"
|
||||
ln -sfn "${DEPLOY_BASE}/shared/uploads" "${RELEASE_DIR}/data/uploads"
|
||||
|
||||
echo "=== 4. Setup Python venv ==="
|
||||
cd "${RELEASE_DIR}"
|
||||
python3 -m venv .venv
|
||||
. .venv/bin/activate
|
||||
pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
echo "=== 5. Restart service ==="
|
||||
# Update WorkingDirectory in service via symlink approach
|
||||
# The systemd service points to /opt/opc-manager/current
|
||||
ln -sfn "${RELEASE_DIR}" "${DEPLOY_BASE}/current"
|
||||
systemctl restart "${SERVICE_NAME}"
|
||||
sleep 3
|
||||
|
||||
echo "=== 6. Health check ==="
|
||||
for i in 1 2 3 4 5; do
|
||||
if curl -fsS http://127.0.0.1:5177/api/health >/dev/null 2>&1; then
|
||||
echo "Health check passed"
|
||||
break
|
||||
fi
|
||||
echo "Attempt $i: waiting for service..."
|
||||
sleep 2
|
||||
done
|
||||
|
||||
# Final verify
|
||||
if ! curl -fsS http://127.0.0.1:5177/api/health >/dev/null 2>&1; then
|
||||
echo "ERROR: Health check failed after 5 attempts"
|
||||
echo "Rolling back to previous release..."
|
||||
PREV=$(ls -t "${DEPLOY_BASE}/releases" | sed -n '2p')
|
||||
if [ -n "${PREV}" ]; then
|
||||
ln -sfn "${DEPLOY_BASE}/releases/${PREV}" "${DEPLOY_BASE}/current"
|
||||
systemctl restart "${SERVICE_NAME}"
|
||||
echo "Rolled back to ${PREV}"
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "=== 7. Cleanup old releases ==="
|
||||
ls -dt "${DEPLOY_BASE}"/releases/*/ | tail -n +6 | xargs -r rm -rf
|
||||
|
||||
echo "=== 8. Cleanup temp ==="
|
||||
rm -rf "${CLONE_DIR}"
|
||||
|
||||
echo "=== Deploy complete: ${RELEASE_ID} ==="
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -6,3 +6,4 @@ data/uploads/
|
||||
__pycache__/
|
||||
.DS_Store
|
||||
data/opc.sqlite
|
||||
.env
|
||||
|
||||
@@ -53,3 +53,4 @@ curl http://127.0.0.1:5177/api/health
|
||||
- 产品:慰心斋产品路线图中的 5 个产品版本
|
||||
- 财务:首版财务样例和原财务 manager 合并方向
|
||||
|
||||
# test trigger
|
||||
|
||||
@@ -1,5 +1,43 @@
|
||||
# OPC Manager Version Log
|
||||
|
||||
## v1.1.0-beta — 2026-06-23
|
||||
- **安全**:.env 环境变量管理(SECRET_KEY/DB)、debug=False、except 改 mysql.connector.Error + logging
|
||||
- **性能**:attach_common 批量 IN 查询消除 N+1、monthly_finance 预解析 budget_data
|
||||
- **XSS**:批量添加 esc() 转义 21 处用户可控字段
|
||||
- **架构**:app.js 拆分为 7 个模块(utils/home/projects/proposals/products/finance/drawer)+ admin.js
|
||||
- **表单统一**:.form-ctrl 统一所有输入控件(替代 drawer-value/fin-input/inline-form 等)
|
||||
- **首页**:移除风险提醒卡片;财务趋势拆为 3 图(签约趋势/确收毛利/回款费用)
|
||||
- **业务方案**:标准资料库 + 其他资料双 Tab;标准 7 项自动初始化;标准资料支持评论
|
||||
- **经营管理**:
|
||||
- 字段改名:客户名称→项目名称、销售人员→商务负责人
|
||||
- 必填约束:项目名称/商务负责人/经营负责人/签约月份/签约金额>0
|
||||
- 新增经营负责人字段;移除转移功能,新增删除项目
|
||||
- 视图切换:确收/毛利 ↔ 回款/费用
|
||||
- **重点工作与台账**:
|
||||
- 统计卡片样式与经营管理统一(无图标)
|
||||
- 视图切换 + 新增任务按钮移到卡片外右对齐
|
||||
- 任务状态简化为 3 态(未开始/进行中/已结束)
|
||||
- 优先级点击切换、项目右键菜单(重命名/创建副本)
|
||||
- 新建任务绑定当前选中项目(修复新建到错误项目的 bug)
|
||||
- 任务详情抽屉改为创建到 document.body(避免 innerHTML 清除)
|
||||
- **用户体系**:
|
||||
- 新增工作台:MCN·无界、无界·无界
|
||||
- 新增账号:mcn/mcn123、wuji/wuji123
|
||||
- 账号管理后台(admin 限定):增删改查账号 + 工作台权限分配
|
||||
- sidebar 顶部用户头像(首字母)+ 显示名,点击弹菜单(账号管理/退出)
|
||||
- sidebar sticky 定位,滚动时不消失
|
||||
- **登录页**:参考 UOC 业务管理平台样式优化(图标 logo、密码显隐、loading 态、回车提交)
|
||||
- **初始化**:启动自动修正任务状态空值/done→进行中等非法值
|
||||
|
||||
## v1.0.1-beta — 2026-06-22
|
||||
- 数据库迁移:SQLite → MySQL 9.6,适配占位符/类型/游标
|
||||
- 用户体系:管理员 + OPC负责人角色,工作台权限隔离,登录鉴权
|
||||
- 经营管理:状态改为已签约/流程中/待签约三类,签约月份列可编辑,财务指标卡片(确收/毛利/回款/费用/现金流)
|
||||
- 重点工作与台账:阶段排序固定化+折叠分组,任务拖拽手柄与状态互换位置,关闭抽屉自动刷新,首次进入自动选第一个项目
|
||||
- 产品迭代:统一表格(去平台tab),状态点击循环切换,日期改为 date 选择器,新增版本改用右侧抽屉
|
||||
- 左侧工作台/顶部 tab 记忆恢复,跨工作台转移功能
|
||||
- 近期动态修复 tenant 归属
|
||||
|
||||
## v1.2.0 — 2026-06-15
|
||||
- 业务机会 + 运营管理合并为「重点项目」Tab,统一表格展示
|
||||
- 新增项目任务追踪:按阶段分组展示里程碑/执行项/负责人/截止日/卡点
|
||||
|
||||
76
backend/db.py
Normal file
76
backend/db.py
Normal file
@@ -0,0 +1,76 @@
|
||||
# db.py — 基础层:配置常量 + 数据库连接 + SQL 工具 + logger
|
||||
# 被 helpers.py, routes.py, migrations/*, flask_app.py 共同依赖
|
||||
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
import mysql.connector
|
||||
|
||||
# 确保 backend 目录在 sys.path 中(兼容 gunicorn --preload 模式)
|
||||
_backend_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
if _backend_dir not in sys.path:
|
||||
sys.path.insert(0, _backend_dir)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
||||
|
||||
# ---------- 路径常量 ----------
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DATA_DIR = ROOT / "data"
|
||||
UPLOAD_DIR = DATA_DIR / "uploads"
|
||||
DB_PATH = DATA_DIR / "opc.sqlite"
|
||||
|
||||
# ---------- 环境变量 ----------
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv(ROOT / ".env")
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
WEIXIN_BASE = Path(os.environ.get("WEIXIN_BASE", "/Users/mac/天机阁/地阁/慰心斋"))
|
||||
|
||||
# 建目录
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
# ---------- 数据库连接 ----------
|
||||
def db():
|
||||
return mysql.connector.connect(
|
||||
host=os.environ.get("DB_HOST", "127.0.0.1"),
|
||||
port=int(os.environ.get("DB_PORT", "3306")),
|
||||
user=os.environ.get("DB_USER", "opc"),
|
||||
password=os.environ.get("DB_PASSWORD", "opc123456"),
|
||||
database=os.environ.get("DB_NAME", "opc"),
|
||||
charset="utf8mb4",
|
||||
collation="utf8mb4_unicode_ci",
|
||||
)
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.utcnow().isoformat()
|
||||
|
||||
|
||||
def _exec(conn, sql, args=()):
|
||||
"""执行 SQL,自动将 ? 转为 MySQL 的 %s"""
|
||||
cur = conn.cursor(dictionary=True)
|
||||
cur.execute(sql.replace("?", "%s"), args)
|
||||
return cur
|
||||
|
||||
|
||||
def rows(conn, sql, args=()):
|
||||
cur = _exec(conn, sql, args)
|
||||
rows = cur.fetchall()
|
||||
cur.close()
|
||||
return rows
|
||||
|
||||
|
||||
def one(conn, sql, args=()):
|
||||
cur = _exec(conn, sql, args)
|
||||
row = cur.fetchone()
|
||||
cur.close()
|
||||
return row
|
||||
@@ -1,589 +1,33 @@
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
# flask_app.py — 入口:app 创建 + 蓝图注册 + 迁移 + 启动
|
||||
# 拆分后仅 ~35 行,所有路由在 routes.py,业务辅助在 helpers.py,基础设施在 db.py
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import sqlite3
|
||||
import sys
|
||||
|
||||
from flask import Flask, jsonify, render_template, request, send_file
|
||||
# 确保 backend 目录在 sys.path 中(兼容 gunicorn --preload 模式)
|
||||
_backend_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
if _backend_dir not in sys.path:
|
||||
sys.path.insert(0, _backend_dir)
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DATA_DIR = ROOT / "data"
|
||||
UPLOAD_DIR = DATA_DIR / "uploads"
|
||||
DB_PATH = DATA_DIR / "opc.sqlite"
|
||||
WEIXIN_BASE = Path("/Users/mac/天机阁/地阁/慰心斋")
|
||||
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
|
||||
from flask import Flask
|
||||
from db import ROOT # 触发 load_dotenv + 建目录
|
||||
from routes import bp
|
||||
from migrations import run_migrations
|
||||
|
||||
app = Flask(
|
||||
__name__,
|
||||
template_folder=str(ROOT / "templates"),
|
||||
static_folder=str(ROOT / "static"),
|
||||
)
|
||||
app.secret_key = os.environ.get("SECRET_KEY", "opc-dev-secret-2026")
|
||||
app.register_blueprint(bp)
|
||||
|
||||
|
||||
def db():
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.utcnow().isoformat()
|
||||
|
||||
|
||||
def rows(conn, sql, args=()):
|
||||
return [dict(row) for row in conn.execute(sql, args).fetchall()]
|
||||
|
||||
|
||||
def one(conn, sql, args=()):
|
||||
row = conn.execute(sql, args).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def init_db():
|
||||
conn = db()
|
||||
conn.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS sales_leads (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
target_customer TEXT NOT NULL,
|
||||
priority TEXT NOT NULL DEFAULT 'P1',
|
||||
status TEXT NOT NULL DEFAULT '待跟进',
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS follow_up_records (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
target_type TEXT NOT NULL,
|
||||
target_id INTEGER NOT NULL,
|
||||
followed_at TEXT NOT NULL DEFAULT '',
|
||||
follower TEXT NOT NULL DEFAULT '慰心',
|
||||
follow_up_method TEXT NOT NULL DEFAULT '记录',
|
||||
content TEXT NOT NULL DEFAULT '',
|
||||
next_action TEXT NOT NULL DEFAULT '',
|
||||
next_follow_up_at TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS business_proposals (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
customer_or_project_name TEXT NOT NULL,
|
||||
version TEXT NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT '草稿',
|
||||
created_date TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS operation_projects (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_name TEXT NOT NULL,
|
||||
project_version TEXT NOT NULL DEFAULT 'v1.0',
|
||||
project_type TEXT NOT NULL DEFAULT 'opportunity',
|
||||
project_status TEXT NOT NULL DEFAULT '',
|
||||
current_stage TEXT NOT NULL DEFAULT '',
|
||||
owner TEXT NOT NULL DEFAULT '慰心',
|
||||
start_date TEXT NOT NULL DEFAULT '',
|
||||
end_date TEXT NOT NULL DEFAULT '',
|
||||
target_customer TEXT NOT NULL DEFAULT '',
|
||||
customer_need TEXT NOT NULL DEFAULT '',
|
||||
expected_contract_amount REAL NOT NULL DEFAULT 0,
|
||||
expected_sign_date TEXT NOT NULL DEFAULT '',
|
||||
sign_probability REAL NOT NULL DEFAULT 0,
|
||||
next_action TEXT NOT NULL DEFAULT '',
|
||||
related_business_proposal_id INTEGER,
|
||||
sop_file_id INTEGER,
|
||||
sop_stage TEXT NOT NULL DEFAULT '',
|
||||
execution_progress REAL NOT NULL DEFAULT 0,
|
||||
current_deliverable TEXT NOT NULL DEFAULT '',
|
||||
risks TEXT NOT NULL DEFAULT '',
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS product_versions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
product_name TEXT NOT NULL,
|
||||
version TEXT NOT NULL,
|
||||
version_goal TEXT NOT NULL DEFAULT '',
|
||||
feature_list TEXT NOT NULL DEFAULT '',
|
||||
launch_date TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT '规划中',
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS finance_records (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
month TEXT NOT NULL,
|
||||
project_name TEXT NOT NULL DEFAULT '科普(慰心斋)',
|
||||
record_type TEXT NOT NULL,
|
||||
category TEXT NOT NULL DEFAULT '',
|
||||
amount REAL NOT NULL DEFAULT 0,
|
||||
occurred_date TEXT NOT NULL DEFAULT '',
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS file_assets (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
module TEXT NOT NULL,
|
||||
owner_id INTEGER NOT NULL,
|
||||
owner_version TEXT NOT NULL DEFAULT '',
|
||||
file_category TEXT NOT NULL DEFAULT '',
|
||||
file_name TEXT NOT NULL,
|
||||
file_type TEXT NOT NULL DEFAULT '',
|
||||
file_size INTEGER NOT NULL DEFAULT 0,
|
||||
file_path TEXT NOT NULL,
|
||||
is_external INTEGER NOT NULL DEFAULT 0,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS project_tasks (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_id INTEGER NOT NULL,
|
||||
phase TEXT NOT NULL DEFAULT '',
|
||||
milestone TEXT NOT NULL DEFAULT '',
|
||||
task TEXT NOT NULL DEFAULT '',
|
||||
owner TEXT NOT NULL DEFAULT '',
|
||||
due_date TEXT NOT NULL DEFAULT '',
|
||||
blockers TEXT NOT NULL DEFAULT '',
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
"""
|
||||
)
|
||||
# Schema migrations
|
||||
try: conn.execute("ALTER TABLE product_versions ADD COLUMN platform TEXT NOT NULL DEFAULT ''")
|
||||
except: pass
|
||||
|
||||
if one(conn, "SELECT id FROM sales_leads LIMIT 1"):
|
||||
conn.close()
|
||||
return
|
||||
|
||||
sales = [
|
||||
("齐鲁制药", "P0", "跟进中", "多产品线科普年度框架,需推进高层沟通。"),
|
||||
("百利天恒", "P0", "方案中", "BL-B01D1 上市前医生教育机会,准备方案。"),
|
||||
("信达生物", "P0", "已签约", "现有科普项目升级/续约,重点保障执行。"),
|
||||
("三生制药", "P1", "待跟进", "多科室医生教育+患者科普机会。"),
|
||||
("天广实生物", "P1", "待跟进", "血液肿瘤医生教育机会。"),
|
||||
]
|
||||
for customer, priority, status, note in sales:
|
||||
cur = conn.execute(
|
||||
"INSERT INTO sales_leads (target_customer, priority, status) VALUES (?,?,?)",
|
||||
(customer, priority, status),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO follow_up_records (target_type,target_id,followed_at,content,next_action) VALUES (?,?,?,?,?)",
|
||||
("sales", cur.lastrowid, date.today().isoformat(), note, "明确下一次沟通人和时间"),
|
||||
)
|
||||
|
||||
cur = conn.execute(
|
||||
"INSERT INTO business_proposals (customer_or_project_name,version,description,status,created_date) VALUES (?,?,?,?,?)",
|
||||
("信达生物", "v1.5", "信达科普项目续约与报价方案", "已提交客户", "2026-05-28"),
|
||||
)
|
||||
proposal_id = cur.lastrowid
|
||||
proposal_dir = WEIXIN_BASE / "2、业务方案/信达/v1.5"
|
||||
for category, names in {
|
||||
"方案": ["整体方案.pptx", "整体方案.pdf"],
|
||||
"成本": ["业务报价-2亿方案.xlsx", "业务报价-5250万方案.xlsx", "5、最新报价.xlsx"],
|
||||
"SOP": ["SOP.docx"],
|
||||
"财务流程": ["财务流程.docx"],
|
||||
}.items():
|
||||
for name in names:
|
||||
add_file_index(conn, "proposal", proposal_id, "v1.5", category, proposal_dir / name, external=True)
|
||||
|
||||
projects = [
|
||||
("圆心科技 科普文章项目", "v2026-文章", "execution", "SOP 执行中", "内容生产", 55, "文章内容生产与审核执行中"),
|
||||
("圆心科技 科普视频项目", "v2026-视频", "execution", "SOP 执行中", "内容生产", 45, "视频脚本、拍摄与审核推进"),
|
||||
("圆心科技 科普专访项目", "v2026-专访", "opportunity", "方案已提交", "商务推进", 0, "专访项目推动签约"),
|
||||
]
|
||||
op_dir = WEIXIN_BASE / "3、运营方案"
|
||||
for name, version, kind, status, stage, progress, note in projects:
|
||||
cur = conn.execute(
|
||||
"""INSERT INTO operation_projects
|
||||
(project_name,project_version,project_type,project_status,current_stage,target_customer,customer_need,
|
||||
expected_contract_amount,expected_sign_date,sign_probability,next_action,sop_stage,execution_progress,current_deliverable)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(name, version, kind, status, stage, "圆心科技", "科普内容项目执行与管理", 0 if kind == "execution" else 200, "2026-06", 100 if kind == "execution" else 70, "补齐版本要求文件并更新下一节点", stage, progress, note),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO follow_up_records (target_type,target_id,followed_at,content,next_action) VALUES (?,?,?,?,?)",
|
||||
("operation", cur.lastrowid, date.today().isoformat(), note, "补齐版本要求文件并更新下一节点"),
|
||||
)
|
||||
|
||||
file_map = [
|
||||
(1, "v2026-文章", "项目方案", "圆心科技--科普文章项目(1).pptx"),
|
||||
(2, "v2026-视频", "项目方案", "圆心科技-科普视频项目(1).pptx"),
|
||||
(3, "v2026-专访", "项目方案", "圆心科技-科普专访项目-2026年(1).pdf"),
|
||||
(1, "v2026-文章", "项目管理手册", "圆心科技《项目管理手册》-2026年.pdf"),
|
||||
(2, "v2026-视频", "审核标准", "科普项目-审核标准(文章-视频-音频).pdf"),
|
||||
]
|
||||
for project_id, version, category, filename in file_map:
|
||||
add_file_index(conn, "operation", project_id, version, category, op_dir / filename, external=True)
|
||||
|
||||
products = [
|
||||
("妙手医生服务小程序", "v1.1", "视频任务增强 + 积分商城", "草稿箱、批量上传、积分商城、消息通知", "2026-Q3", "规划中", "科普平台"),
|
||||
("数字化营销后台管理系统", "v1.2", "运营数据看板 + 智能审核", "医生活跃、任务完成率、AI 预审、渠道数据上报", "2026-Q3", "设计中", "真研平台"),
|
||||
("妙手患者服务", "v0.5", "科普浏览 + 医生主页 MVP", "科普文章/视频浏览、医生主页、搜索", "2026-Q3", "规划中", "科普平台"),
|
||||
("数字人内容平台", "v0.1", "基础数字人视频生成 MVP", "预设形象、AI 配音、脚本驱动、简单模板", "2026-Q3", "规划中", "科普平台"),
|
||||
("渠道分发引擎", "v1.0", "六渠道统一分发", "分发 API、内容适配、分发排期、效果追踪", "2027-Q1", "规划中", "科普平台"),
|
||||
]
|
||||
for product in products:
|
||||
cur = conn.execute(
|
||||
"INSERT INTO product_versions (product_name,version,version_goal,feature_list,launch_date,status,platform) VALUES (?,?,?,?,?,?,?)",
|
||||
product,
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO follow_up_records (target_type,target_id,followed_at,content,next_action) VALUES (?,?,?,?,?)",
|
||||
("product", cur.lastrowid, date.today().isoformat(), f"{product[0]} {product[1]}:{product[2]}", "按路线图推进"),
|
||||
)
|
||||
|
||||
for month, record_type, category, amount, notes in [
|
||||
("2026-05", "revenue", "信达生物续约确认收入", 120, "信达项目阶段确收"),
|
||||
("2026-06", "revenue", "信达生物续约确认收入", 80, "信达项目尾款预估"),
|
||||
("2026-05", "cost_expense", "内容生产", 32, "医生劳务与内容制作"),
|
||||
("2026-05", "cost_expense", "运营管理", 16, "项目管理与渠道协同"),
|
||||
("2026-06", "cost_expense", "渠道分发", 24, "投放与分发费用"),
|
||||
]:
|
||||
conn.execute(
|
||||
"INSERT INTO finance_records (month,record_type,category,amount,occurred_date,notes) VALUES (?,?,?,?,?,?)",
|
||||
(month, record_type, category, amount, f"{month}-01", notes),
|
||||
)
|
||||
|
||||
# Seed project tasks for 信达科普文章项目 (project_id=1)
|
||||
tasks_seed = [
|
||||
("阶段1:渠道与商务确认", "商务对接", "合同签订", "Anna", "2026-06-30", "法务审核中", "合同签订后开始执行"),
|
||||
("阶段1:渠道与商务确认", "官媒渠道确认", "沟通官媒确定", "段丽华", "2026-06-30", "官媒尽力推,以先达成合作为准", "集团支持"),
|
||||
("阶段1:渠道与商务确认", "官媒渠道确认", "官媒合作签约", "段丽华", "2026-06-18", "", "官媒确认细节"),
|
||||
("阶段2:系统与标准搭建", "系统开发上线", "音频专访系统开发上线", "戴敏/梁军营", "2026-06-18", "客户比较着急执行,需要技术的资源", ""),
|
||||
("阶段2:系统与标准搭建", "系统开发上线", "精品视频系统开发上线", "戴敏/梁军营", "2026-06-25", "", ""),
|
||||
("阶段2:系统与标准搭建", "标准与培训", "业务执行手册SOP", "胡龙飞", "2026-06-12", "", "系统开发上线"),
|
||||
("阶段3:人员与审核入驻", "团队组建", "医学审核人员到位", "胡龙飞", "2026-06-15", "", "审核人员招聘"),
|
||||
("阶段3:人员与审核入驻", "团队组建", "视频制作人员到位", "胡龙飞", "2026-06-18", "", "项目经理招聘"),
|
||||
("阶段4:供应链与制作", "供应商准入", "准入拍摄/剪辑/主持人", "胡龙飞/侯亚凤", "2026-06-18", "", ""),
|
||||
("阶段2:系统与标准搭建", "脚本生产及审核", "生产脚本", "军营", "2026-06-12", "脚本目前生产比较机械,需要提前准备", "细分标签领域完成"),
|
||||
]
|
||||
for phase, milestone, task, owner, due_date, blockers, notes in tasks_seed:
|
||||
conn.execute(
|
||||
"INSERT INTO project_tasks (project_id,phase,milestone,task,owner,due_date,blockers,notes) VALUES (?,?,?,?,?,?,?,?)",
|
||||
(1, phase, milestone, task, owner, due_date, blockers, notes),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def add_file_index(conn, module, owner_id, owner_version, category, path, external=True):
|
||||
path = Path(path)
|
||||
if not path.exists():
|
||||
return
|
||||
conn.execute(
|
||||
"""INSERT INTO file_assets
|
||||
(module,owner_id,owner_version,file_category,file_name,file_type,file_size,file_path,is_external)
|
||||
VALUES (?,?,?,?,?,?,?,?,?)""",
|
||||
(module, owner_id, owner_version, category, path.name, path.suffix.lower().lstrip("."), path.stat().st_size, str(path), 1 if external else 0),
|
||||
)
|
||||
|
||||
|
||||
def latest_followup(conn, target_type, target_id):
|
||||
row = one(
|
||||
conn,
|
||||
"SELECT content FROM follow_up_records WHERE target_type=? AND target_id=? ORDER BY followed_at DESC, id DESC LIMIT 1",
|
||||
(target_type, target_id),
|
||||
)
|
||||
return row["content"] if row else ""
|
||||
|
||||
|
||||
def attach_common(conn, resource, items):
|
||||
target_map = {"sales": "sales", "proposals": "proposal", "operations": "operation", "products": "product"}
|
||||
for item in items:
|
||||
if resource in target_map:
|
||||
item["followups"] = rows(
|
||||
conn,
|
||||
"SELECT * FROM follow_up_records WHERE target_type=? AND target_id=? ORDER BY followed_at DESC, id DESC",
|
||||
(target_map[resource], item["id"]),
|
||||
)
|
||||
item["latest_follow_up_record"] = item["followups"][0]["content"] if item["followups"] else ""
|
||||
if resource == "proposals":
|
||||
item["files"] = rows(conn, "SELECT * FROM file_assets WHERE module='proposal' AND owner_id=? ORDER BY id DESC", (item["id"],))
|
||||
if resource == "operations":
|
||||
item["files"] = rows(conn, "SELECT * FROM file_assets WHERE module='operation' AND owner_id=? ORDER BY id DESC", (item["id"],))
|
||||
return items
|
||||
|
||||
|
||||
def monthly_finance(conn, tenant="科普·无界"):
|
||||
data = []
|
||||
for item in rows(conn, "SELECT DISTINCT month FROM finance_records WHERE tenant=? ORDER BY month", (tenant,)):
|
||||
month = item["month"]
|
||||
def s(cat):
|
||||
return one(conn, "SELECT COALESCE(SUM(amount),0) AS v FROM finance_records WHERE month=? AND category=? AND tenant=?", (month, cat, tenant))["v"]
|
||||
revenue = s("确认收入") + s("签单")
|
||||
labor = s("人力成本")
|
||||
expense = s("费用")
|
||||
purchase = s("外部采购")
|
||||
sign = s("签单")
|
||||
net = revenue - labor - expense - purchase
|
||||
data.append({
|
||||
"month": month, "revenue": revenue, "sign": sign,
|
||||
"labor": labor, "expense": expense, "purchase": purchase,
|
||||
"net_profit": net,
|
||||
})
|
||||
return data
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
return render_template("index.html")
|
||||
|
||||
|
||||
@app.route("/api/bootstrap")
|
||||
def bootstrap():
|
||||
tenant = request.args.get("tenant", "科普·无界")
|
||||
conn = db()
|
||||
try:
|
||||
def q(sql, *args):
|
||||
return rows(conn, sql, args)
|
||||
sales = attach_common(conn, "sales", q("SELECT * FROM sales_leads WHERE tenant=? ORDER BY id DESC", tenant))
|
||||
proposals = attach_common(conn, "proposals", q("SELECT * FROM business_proposals WHERE tenant=? ORDER BY id DESC", tenant))
|
||||
operations = attach_common(conn, "operations", q("SELECT * FROM operation_projects WHERE tenant=? ORDER BY id DESC", tenant))
|
||||
products = attach_common(conn, "products", q("SELECT * FROM product_versions WHERE tenant=? ORDER BY id DESC", tenant))
|
||||
finance = q("SELECT * FROM finance_records WHERE tenant=? ORDER BY month DESC, id DESC", tenant)
|
||||
tasks = q("SELECT * FROM project_tasks WHERE tenant=? ORDER BY phase, sort_order, id", tenant)
|
||||
current_month = "2026-06"
|
||||
# Finance aggregates
|
||||
def sum_cat(months, cat):
|
||||
return sum(x["amount"] for x in finance if x["month"] in months and x.get("category") == cat)
|
||||
months_2026 = [f"2026-{m:02d}" for m in range(1,7)]
|
||||
months_q2 = ["2026-04","2026-05","2026-06"]
|
||||
rev_annual = sum_cat(months_2026, "确认收入") + sum_cat(months_2026, "签单")
|
||||
labor_annual = sum_cat(months_2026, "人力成本")
|
||||
expense_annual = sum_cat(months_2026, "费用")
|
||||
purchase_annual = sum_cat(months_2026, "外部采购")
|
||||
rev_q2 = sum_cat(months_q2, "确认收入") + sum_cat(months_q2, "签单")
|
||||
labor_q2 = sum_cat(months_q2, "人力成本")
|
||||
expense_q2 = sum_cat(months_q2, "费用")
|
||||
purchase_q2 = sum_cat(months_q2, "外部采购")
|
||||
rev_month = sum_cat([current_month], "确认收入") + sum_cat([current_month], "签单")
|
||||
labor_month = sum_cat([current_month], "人力成本")
|
||||
expense_month = sum_cat([current_month], "费用")
|
||||
purchase_month = sum_cat([current_month], "外部采购")
|
||||
cost_month = sum_finance([current_month], "cost_expense")
|
||||
# Contract aggregates — time-based
|
||||
signed_amount = sum(x["expected_contract_amount"] or 0 for x in operations if x["project_status"] == "已签约")
|
||||
from datetime import date
|
||||
today = date.today()
|
||||
def contract_in_period(op, start, end):
|
||||
if op["project_status"] != "已签约": return False
|
||||
try:
|
||||
d = date.fromisoformat(op["created_at"][:10])
|
||||
return start <= d <= end
|
||||
except: return False
|
||||
signed_annual = sum(x["expected_contract_amount"] or 0 for x in operations if contract_in_period(x, date(2026,1,1), date(2026,12,31)))
|
||||
signed_q2 = sum(x["expected_contract_amount"] or 0 for x in operations if contract_in_period(x, date(2026,4,1), date(2026,6,30)))
|
||||
signed_month = sum(x["expected_contract_amount"] or 0 for x in operations if contract_in_period(x, date(2026,6,1), date(2026,6,30)))
|
||||
pipeline_amount = sum(x["expected_contract_amount"] or 0 for x in operations if x["project_status"] not in ["已签约","已丢单","已归档","已完成"])
|
||||
signed_not_executed = sum(x["expected_contract_amount"] or 0 for x in operations if x["project_type"] == "execution" and x["execution_progress"] < 100)
|
||||
summary = {
|
||||
"project_name": "科普(慰心斋)",
|
||||
"metrics": {
|
||||
"p0_customers": len([x for x in sales if x["priority"] == "P0"]),
|
||||
"active_sales": len([x for x in sales if x["status"] in ["待跟进", "跟进中", "方案中", "商务谈判"]]),
|
||||
"execution_projects": len([x for x in operations if x["project_type"] == "execution"]),
|
||||
"risk_projects": len([x for x in operations if x["project_status"] == "有风险" or x["risks"]]),
|
||||
"monthly_revenue": rev_month,
|
||||
"monthly_net_profit": rev_month - labor_month - expense_month - purchase_month,
|
||||
"monthly_gross": rev_month - labor_month - expense_month - purchase_month,
|
||||
"upcoming_products": len([x for x in products if x["status"] in ["规划中", "设计中", "开发中", "测试中"]]),
|
||||
"total_projects": len(operations),
|
||||
"total_proposals": len(proposals),
|
||||
"total_products": len(products),
|
||||
# Extended finance metrics
|
||||
"signed_amount": signed_amount,
|
||||
"signed_annual": signed_annual,
|
||||
"signed_q2": signed_q2,
|
||||
"signed_month": signed_month,
|
||||
"pipeline_amount": pipeline_amount,
|
||||
"revenue_annual": rev_annual,
|
||||
"revenue_q2": rev_q2,
|
||||
"gross_annual": rev_annual - labor_annual - expense_annual - purchase_annual,
|
||||
"gross_q2": rev_q2 - labor_q2 - expense_q2 - purchase_q2,
|
||||
"signed_not_executed": signed_not_executed,
|
||||
},
|
||||
"recent": q("SELECT * FROM follow_up_records WHERE tenant=? ORDER BY id DESC LIMIT 8", tenant),
|
||||
"risks": [{"title": "执行提醒", "content": x["next_action"]} for x in operations if x["next_action"]][:5],
|
||||
}
|
||||
return jsonify({"summary": summary, "sales": sales, "proposals": proposals, "operations": operations, "products": products, "finance": finance, "financeMonthly": monthly_finance(conn, tenant), "tasks": tasks, "tenant": tenant, "tenants": ["科普·无界","科研·无界","医患·无界"]})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
TABLES = {
|
||||
"sales": ("sales_leads", ["target_customer", "priority", "status", "tenant"]),
|
||||
"proposals": ("business_proposals", ["customer_or_project_name", "version", "description", "status", "created_date", "tenant"]),
|
||||
"operations": ("operation_projects", ["project_name", "project_version", "project_type", "project_status", "current_stage", "owner", "target_customer", "customer_need", "expected_contract_amount", "expected_sign_date", "sign_probability", "next_action", "sop_stage", "execution_progress", "current_deliverable", "risks", "notes", "tenant"]),
|
||||
"products": ("product_versions", ["product_name", "version", "version_goal", "feature_list", "launch_date", "status", "platform", "notes", "tenant"]),
|
||||
"finance": ("finance_records", ["month", "project_name", "record_type", "category", "amount", "occurred_date", "notes", "tenant"]),
|
||||
"tasks": ("project_tasks", ["project_id", "phase", "milestone", "task", "owner", "due_date", "blockers", "notes", "status", "sort_order", "tenant"]),
|
||||
}
|
||||
|
||||
|
||||
@app.route("/api/<resource>", methods=["POST"])
|
||||
def create_resource(resource):
|
||||
if resource not in TABLES:
|
||||
return jsonify({"error": "unknown resource"}), 404
|
||||
table, cols = TABLES[resource]
|
||||
payload = request.get_json(force=True).get("data", {})
|
||||
values = [payload.get(col, "") for col in cols]
|
||||
conn = db()
|
||||
try:
|
||||
cur = conn.execute(f"INSERT INTO {table} ({','.join(cols)}) VALUES ({','.join(['?'] * len(cols))})", values)
|
||||
conn.commit()
|
||||
return jsonify({"id": cur.lastrowid})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@app.route("/api/<resource>/<int:item_id>", methods=["PUT", "DELETE"])
|
||||
def update_resource(resource, item_id):
|
||||
if resource not in TABLES:
|
||||
return jsonify({"error": "unknown resource"}), 404
|
||||
table, cols = TABLES[resource]
|
||||
conn = db()
|
||||
try:
|
||||
if request.method == "DELETE":
|
||||
conn.execute(f"DELETE FROM {table} WHERE id=?", (item_id,))
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
payload = request.get_json(force=True).get("data", {})
|
||||
update_cols = [col for col in cols if col in payload]
|
||||
if update_cols:
|
||||
conn.execute(
|
||||
f"UPDATE {table} SET {','.join([col + '=?' for col in update_cols])}, updated_at=? WHERE id=?",
|
||||
[payload[col] for col in update_cols] + [now(), item_id],
|
||||
)
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@app.route("/api/followups/<target_type>/<int:target_id>", methods=["POST"])
|
||||
def add_followup(target_type, target_id):
|
||||
payload = request.get_json(force=True).get("data", {})
|
||||
conn = db()
|
||||
try:
|
||||
conn.execute(
|
||||
"""INSERT INTO follow_up_records
|
||||
(target_type,target_id,followed_at,follower,follow_up_method,content,next_action,next_follow_up_at)
|
||||
VALUES (?,?,?,?,?,?,?,?)""",
|
||||
(
|
||||
target_type,
|
||||
target_id,
|
||||
payload.get("followed_at") or date.today().isoformat(),
|
||||
payload.get("follower") or "慰心",
|
||||
payload.get("follow_up_method") or "记录",
|
||||
payload.get("content") or "",
|
||||
payload.get("next_action") or "",
|
||||
payload.get("next_follow_up_at") or "",
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@app.route("/api/followups/<int:followup_id>", methods=["DELETE"])
|
||||
def delete_followup(followup_id):
|
||||
conn = db()
|
||||
try:
|
||||
cur = conn.execute("DELETE FROM follow_up_records WHERE id=?", (followup_id,))
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@app.route("/api/tasks/batch-sort", methods=["POST"])
|
||||
def batch_sort_tasks():
|
||||
conn = db()
|
||||
try:
|
||||
items = request.get_json(force=True).get("items", [])
|
||||
for item in items:
|
||||
conn.execute("UPDATE project_tasks SET sort_order=? WHERE id=?", (item["sort_order"], item["id"]))
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@app.route("/api/files/upload", methods=["POST"])
|
||||
def upload_file():
|
||||
file = request.files["file"]
|
||||
module = request.form["module"]
|
||||
owner_id = int(request.form["owner_id"])
|
||||
owner_version = request.form.get("owner_version", "")
|
||||
category = request.form.get("file_category", "")
|
||||
folder = UPLOAD_DIR / module / str(owner_id)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
target = folder / file.filename
|
||||
file.save(target)
|
||||
conn = db()
|
||||
try:
|
||||
add_file_index(conn, module, owner_id, owner_version, category, target, external=False)
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@app.route("/api/files/<int:file_id>/content")
|
||||
def file_content(file_id):
|
||||
conn = db()
|
||||
try:
|
||||
asset = one(conn, "SELECT * FROM file_assets WHERE id=?", (file_id,))
|
||||
if not asset:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
path = Path(asset["file_path"])
|
||||
if not path.exists():
|
||||
return jsonify({"error": "missing"}), 404
|
||||
return send_file(path, as_attachment=request.args.get("inline") == "false", download_name=asset["file_name"])
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@app.route("/api/files/<int:file_id>", methods=["DELETE"])
|
||||
def delete_file(file_id):
|
||||
conn = db()
|
||||
try:
|
||||
asset = one(conn, "SELECT * FROM file_assets WHERE id=?", (file_id,))
|
||||
if not asset:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
# Remove physical file from uploads/ if it was uploaded to our dir
|
||||
path = Path(asset["file_path"])
|
||||
if path.exists() and str(UPLOAD_DIR) in str(path.resolve()):
|
||||
path.unlink(missing_ok=True)
|
||||
conn.execute("DELETE FROM file_assets WHERE id=?", (file_id,))
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@app.route("/api/health")
|
||||
def health():
|
||||
return jsonify({"ok": True, "db": str(DB_PATH)})
|
||||
|
||||
|
||||
init_db()
|
||||
|
||||
# 模块级执行迁移(保留 gunicorn --preload 行为:导入即触发)
|
||||
run_migrations()
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run(host="127.0.0.1", port=5177, debug=True)
|
||||
app.run(
|
||||
host="127.0.0.1",
|
||||
port=5177,
|
||||
debug=os.environ.get("FLASK_DEBUG", "false").lower() in ("true", "1", "yes"),
|
||||
)
|
||||
|
||||
105
backend/helpers.py
Normal file
105
backend/helpers.py
Normal file
@@ -0,0 +1,105 @@
|
||||
# helpers.py — 业务查询辅助函数
|
||||
# 依赖:db.py;被 routes.py 和 migrations/seed_data.py 调用
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from db import _exec, rows, one
|
||||
|
||||
|
||||
def add_file_index(conn, module, owner_id, owner_version, category, path, external=True):
|
||||
path = Path(path)
|
||||
if not path.exists():
|
||||
return
|
||||
_exec(conn,
|
||||
"""INSERT INTO file_assets
|
||||
(module,owner_id,owner_version,file_category,file_name,file_type,file_size,file_path,is_external)
|
||||
VALUES (?,?,?,?,?,?,?,?,?)""",
|
||||
(module, owner_id, owner_version, category, path.name, path.suffix.lower().lstrip("."), path.stat().st_size, str(path), 1 if external else 0),
|
||||
)
|
||||
|
||||
|
||||
def attach_common(conn, resource, items):
|
||||
"""批量加载 followups 和 files,避免 N+1 查询"""
|
||||
if not items:
|
||||
return items
|
||||
target_map = {"sales": "sales", "proposals": "proposal", "operations": "operation", "products": "product"}
|
||||
target_type = target_map.get(resource)
|
||||
ids = [item["id"] for item in items]
|
||||
|
||||
# 批量查 followups(一次性 IN 查询)
|
||||
if target_type:
|
||||
placeholders = ",".join(["?"] * len(ids))
|
||||
all_followups = rows(
|
||||
conn,
|
||||
f"SELECT * FROM follow_up_records WHERE target_type=? AND target_id IN ({placeholders}) ORDER BY followed_at DESC, id DESC",
|
||||
[target_type] + ids,
|
||||
)
|
||||
followups_by_id = {}
|
||||
for fu in all_followups:
|
||||
followups_by_id.setdefault(fu["target_id"], []).append(fu)
|
||||
for item in items:
|
||||
item["followups"] = followups_by_id.get(item["id"], [])
|
||||
item["latest_follow_up_record"] = item["followups"][0]["content"] if item["followups"] else ""
|
||||
|
||||
# 批量查 files(proposals + operations)
|
||||
file_modules = {"proposals": "proposal", "operations": "operation"}
|
||||
if resource in file_modules:
|
||||
module = file_modules[resource]
|
||||
placeholders = ",".join(["?"] * len(ids))
|
||||
all_files = rows(
|
||||
conn,
|
||||
f"SELECT * FROM file_assets WHERE module=? AND owner_id IN ({placeholders}) ORDER BY id DESC",
|
||||
[module] + ids,
|
||||
)
|
||||
files_by_id = {}
|
||||
for f in all_files:
|
||||
files_by_id.setdefault(f["owner_id"], []).append(f)
|
||||
for item in items:
|
||||
item["files"] = files_by_id.get(item["id"], [])
|
||||
|
||||
return items
|
||||
|
||||
|
||||
def monthly_finance(conn, tenant="科普·无界"):
|
||||
months = [f"2026-{m:02d}" for m in range(1, 13)]
|
||||
pfs = rows(conn,
|
||||
"SELECT sign_amount, sign_month, status, budget_data FROM project_finances WHERE tenant=? AND status='已签约'",
|
||||
[tenant])
|
||||
|
||||
parsed_budgets = []
|
||||
for pf in pfs:
|
||||
try:
|
||||
budget = json.loads(pf.get("budget_data") or "[]")
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
budget = []
|
||||
budget_map = {}
|
||||
for b in budget:
|
||||
key = (b.get("month") or "").replace("-", "_")
|
||||
budget_map[key] = {
|
||||
"rev": float(b.get("rev") or 0),
|
||||
"gross": float(b.get("gross") or 0),
|
||||
"payment": float(b.get("payment") or 0),
|
||||
"cost": float(b.get("cost") or 0),
|
||||
}
|
||||
parsed_budgets.append((pf, budget_map))
|
||||
|
||||
data = []
|
||||
for month in months:
|
||||
key = month.replace("-", "_")
|
||||
revenue = gross = payment = cost = sign = 0
|
||||
for pf, budget_map in parsed_budgets:
|
||||
if pf["status"] == "已签约" and (pf.get("sign_month") or "") == month:
|
||||
sign += float(pf["sign_amount"] or 0)
|
||||
b = budget_map.get(key)
|
||||
if b:
|
||||
revenue += b["rev"]
|
||||
gross += b["gross"]
|
||||
payment += b["payment"]
|
||||
cost += b["cost"]
|
||||
data.append({
|
||||
"month": month, "revenue": revenue,
|
||||
"labor": 0, "expense": 0, "purchase": 0,
|
||||
"gross": gross,
|
||||
"sign": sign, "payment": payment, "cost": cost,
|
||||
})
|
||||
return data
|
||||
30
backend/migrations/__init__.py
Normal file
30
backend/migrations/__init__.py
Normal file
@@ -0,0 +1,30 @@
|
||||
"""migrations/__init__.py — 数据库自愈机制入口
|
||||
|
||||
应用启动时调用 run_migrations(),自动:
|
||||
1. 建表(CREATE TABLE IF NOT EXISTS)
|
||||
2. 加列(SHOW COLUMNS 检查后 ALTER TABLE ADD COLUMN)
|
||||
3. 数据修正(UPDATE 修复脏数据/变更枚举值)
|
||||
4. 初始化默认用户和示例数据(仅空库时)
|
||||
|
||||
参考 SalesManager 的 migrations/ 模式,所有迁移函数幂等可重复执行。
|
||||
"""
|
||||
|
||||
|
||||
def run_migrations():
|
||||
"""执行所有迁移(顺序执行,幂等)
|
||||
|
||||
延迟 import 避免 circular import(migrations 各子模块依赖 flask_app 的 db/_exec 等)。
|
||||
"""
|
||||
from migrations.tables import migrate_create_tables
|
||||
from migrations.columns import migrate_add_columns
|
||||
from migrations.data_fixes import migrate_fix_task_status, migrate_rename_tenant, migrate_drop_product_fields, migrate_fix_service_fee_standard
|
||||
from migrations.seed import migrate_seed_users, migrate_seed_demo_data
|
||||
|
||||
migrate_create_tables()
|
||||
migrate_add_columns()
|
||||
migrate_fix_task_status()
|
||||
migrate_rename_tenant()
|
||||
migrate_drop_product_fields()
|
||||
migrate_fix_service_fee_standard()
|
||||
migrate_seed_users()
|
||||
migrate_seed_demo_data()
|
||||
105
backend/migrations/columns.py
Normal file
105
backend/migrations/columns.py
Normal file
@@ -0,0 +1,105 @@
|
||||
"""migrations/columns.py — 加列迁移(老表补字段,幂等)"""
|
||||
|
||||
|
||||
def _add_column_if_missing(conn, table, column, ddl):
|
||||
"""检查列是否存在,不存在才加(幂等)"""
|
||||
from db import _exec, mysql, logger
|
||||
|
||||
cur = conn.cursor(dictionary=True)
|
||||
cur.execute(f"SHOW COLUMNS FROM {table} LIKE %s", (column,))
|
||||
exists = cur.fetchone()
|
||||
cur.close()
|
||||
if not exists:
|
||||
try:
|
||||
_exec(conn, ddl)
|
||||
print(f"[migrate] {table}.{column} 列已添加")
|
||||
except mysql.connector.Error as e:
|
||||
logger.debug(f"add column {table}.{column} skipped: {e}")
|
||||
|
||||
|
||||
def migrate_add_columns():
|
||||
"""为老表补齐后续新增的字段"""
|
||||
from db import db
|
||||
|
||||
conn = db()
|
||||
try:
|
||||
# tenant 字段(多工作台支持)
|
||||
for table in ["sales_leads", "follow_up_records", "business_proposals",
|
||||
"operation_projects", "product_versions", "finance_records",
|
||||
"project_tasks"]:
|
||||
_add_column_if_missing(conn, table, "tenant",
|
||||
f"ALTER TABLE {table} ADD COLUMN tenant VARCHAR(100) NOT NULL DEFAULT '科普·无界'")
|
||||
|
||||
# business_proposals 扩展字段
|
||||
_add_column_if_missing(conn, "business_proposals", "proposal_type",
|
||||
"ALTER TABLE business_proposals ADD COLUMN proposal_type VARCHAR(100) NOT NULL DEFAULT '业务方案'")
|
||||
_add_column_if_missing(conn, "business_proposals", "notes",
|
||||
"ALTER TABLE business_proposals ADD COLUMN notes VARCHAR(2000) NOT NULL DEFAULT ''")
|
||||
|
||||
# product_versions 扩展字段
|
||||
_add_column_if_missing(conn, "product_versions", "priority",
|
||||
"ALTER TABLE product_versions ADD COLUMN priority VARCHAR(10) NOT NULL DEFAULT 'P2'")
|
||||
_add_column_if_missing(conn, "product_versions", "start_date",
|
||||
"ALTER TABLE product_versions ADD COLUMN start_date VARCHAR(30) NOT NULL DEFAULT ''")
|
||||
_add_column_if_missing(conn, "product_versions", "plan_date",
|
||||
"ALTER TABLE product_versions ADD COLUMN plan_date VARCHAR(30) NOT NULL DEFAULT ''")
|
||||
_add_column_if_missing(conn, "product_versions", "dev_done_date",
|
||||
"ALTER TABLE product_versions ADD COLUMN dev_done_date VARCHAR(30) NOT NULL DEFAULT ''")
|
||||
_add_column_if_missing(conn, "product_versions", "test_date",
|
||||
"ALTER TABLE product_versions ADD COLUMN test_date VARCHAR(30) NOT NULL DEFAULT ''")
|
||||
_add_column_if_missing(conn, "product_versions", "devs",
|
||||
"ALTER TABLE product_versions ADD COLUMN devs VARCHAR(500) NOT NULL DEFAULT ''")
|
||||
_add_column_if_missing(conn, "product_versions", "testers",
|
||||
"ALTER TABLE product_versions ADD COLUMN testers VARCHAR(500) NOT NULL DEFAULT ''")
|
||||
|
||||
# project_tasks 扩展字段
|
||||
_add_column_if_missing(conn, "project_tasks", "status",
|
||||
"ALTER TABLE project_tasks ADD COLUMN status VARCHAR(50) NOT NULL DEFAULT '未开始'")
|
||||
_add_column_if_missing(conn, "project_tasks", "sort_order",
|
||||
"ALTER TABLE project_tasks ADD COLUMN sort_order INT NOT NULL DEFAULT 0")
|
||||
_add_column_if_missing(conn, "project_tasks", "priority",
|
||||
"ALTER TABLE project_tasks ADD COLUMN priority VARCHAR(10) NOT NULL DEFAULT 'P2'")
|
||||
|
||||
# project_finances 12 个月度预算字段(确收/毛利/回款/费用)
|
||||
for m in ["01","02","03","04","05","06","07","08","09","10","11","12"]:
|
||||
for field in ["rev", "gross", "payment", "cost"]:
|
||||
col = f"{field}_2026_{m}"
|
||||
_add_column_if_missing(conn, "project_finances", col,
|
||||
f"ALTER TABLE project_finances ADD COLUMN {col} DOUBLE NOT NULL DEFAULT 0")
|
||||
|
||||
# project_finances 总视图字段:已回款 / 应付 / 已付
|
||||
_add_column_if_missing(conn, "project_finances", "total_payment",
|
||||
"ALTER TABLE project_finances ADD COLUMN total_payment DOUBLE NOT NULL DEFAULT 0")
|
||||
_add_column_if_missing(conn, "project_finances", "total_cost",
|
||||
"ALTER TABLE project_finances ADD COLUMN total_cost DOUBLE NOT NULL DEFAULT 0")
|
||||
_add_column_if_missing(conn, "project_finances", "total_paid",
|
||||
"ALTER TABLE project_finances ADD COLUMN total_paid DOUBLE NOT NULL DEFAULT 0")
|
||||
|
||||
# project_finances 项目基本信息扩展字段
|
||||
_add_column_if_missing(conn, "project_finances", "project_code",
|
||||
"ALTER TABLE project_finances ADD COLUMN project_code VARCHAR(50) NOT NULL DEFAULT ''")
|
||||
_add_column_if_missing(conn, "project_finances", "start_date",
|
||||
"ALTER TABLE project_finances ADD COLUMN start_date VARCHAR(30) NOT NULL DEFAULT ''")
|
||||
_add_column_if_missing(conn, "project_finances", "end_date",
|
||||
"ALTER TABLE project_finances ADD COLUMN end_date VARCHAR(30) NOT NULL DEFAULT ''")
|
||||
_add_column_if_missing(conn, "project_finances", "task_type",
|
||||
"ALTER TABLE project_finances ADD COLUMN task_type VARCHAR(100) NOT NULL DEFAULT ''")
|
||||
_add_column_if_missing(conn, "project_finances", "task_count",
|
||||
"ALTER TABLE project_finances ADD COLUMN task_count DOUBLE NOT NULL DEFAULT 0")
|
||||
_add_column_if_missing(conn, "project_finances", "service_fee_standard",
|
||||
"ALTER TABLE project_finances ADD COLUMN service_fee_standard DOUBLE NOT NULL DEFAULT 0")
|
||||
_add_column_if_missing(conn, "project_finances", "project_manager",
|
||||
"ALTER TABLE project_finances ADD COLUMN project_manager VARCHAR(100) NOT NULL DEFAULT ''")
|
||||
_add_column_if_missing(conn, "project_finances", "task_data",
|
||||
"ALTER TABLE project_finances ADD COLUMN task_data TEXT")
|
||||
_add_column_if_missing(conn, "project_finances", "contact_name",
|
||||
"ALTER TABLE project_finances ADD COLUMN contact_name VARCHAR(100) NOT NULL DEFAULT ''")
|
||||
_add_column_if_missing(conn, "project_finances", "contact_phone",
|
||||
"ALTER TABLE project_finances ADD COLUMN contact_phone VARCHAR(50) NOT NULL DEFAULT ''")
|
||||
_add_column_if_missing(conn, "project_finances", "other_info",
|
||||
"ALTER TABLE project_finances ADD COLUMN other_info VARCHAR(500) NOT NULL DEFAULT ''")
|
||||
|
||||
conn.commit()
|
||||
print("[migrate] 加列迁移完成")
|
||||
finally:
|
||||
conn.close()
|
||||
94
backend/migrations/data_fixes.py
Normal file
94
backend/migrations/data_fixes.py
Normal file
@@ -0,0 +1,94 @@
|
||||
"""migrations/data_fixes.py — 数据修正迁移(修复脏数据、变更枚举值)"""
|
||||
|
||||
|
||||
def migrate_fix_task_status():
|
||||
"""修正 project_tasks 中非法的 status 值"""
|
||||
from db import db, _exec, mysql, logger
|
||||
|
||||
conn = db()
|
||||
try:
|
||||
fixes = [
|
||||
"UPDATE project_tasks SET status='未开始' WHERE status='' OR status IS NULL",
|
||||
"UPDATE project_tasks SET status='已结束' WHERE status='done'",
|
||||
"UPDATE project_tasks SET status='进行中' WHERE status='验收中'",
|
||||
]
|
||||
for sql in fixes:
|
||||
try:
|
||||
cur = _exec(conn, sql)
|
||||
affected = cur.rowcount
|
||||
cur.close()
|
||||
if affected:
|
||||
print(f"[migrate] 修正 {affected} 条任务状态")
|
||||
except mysql.connector.Error as e:
|
||||
logger.warning(f"task status fix skipped: {e}")
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def migrate_rename_tenant():
|
||||
"""工作台重命名:无界·无界 → 学会·无界"""
|
||||
from db import db, _exec, mysql
|
||||
|
||||
conn = db()
|
||||
try:
|
||||
tables = ["user_tenants", "sales_leads", "follow_up_records", "business_proposals",
|
||||
"operation_projects", "product_versions", "finance_records", "project_tasks",
|
||||
"project_finances"]
|
||||
for table in tables:
|
||||
try:
|
||||
cur = _exec(conn, f"UPDATE {table} SET tenant='学会·无界' WHERE tenant='无界·无界'")
|
||||
affected = cur.rowcount
|
||||
cur.close()
|
||||
if affected:
|
||||
print(f"[migrate] {table}: {affected} 条记录 tenant 改为 '学会·无界'")
|
||||
except mysql.connector.Error:
|
||||
pass
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def migrate_drop_product_fields():
|
||||
"""删除 product_versions 表的 owner / platform / feature_list 字段"""
|
||||
from db import db, mysql
|
||||
|
||||
conn = db()
|
||||
try:
|
||||
for col in ["owner", "platform", "feature_list"]:
|
||||
cur = conn.cursor(dictionary=True)
|
||||
cur.execute("SHOW COLUMNS FROM product_versions LIKE %s", (col,))
|
||||
exists = cur.fetchone()
|
||||
cur.close()
|
||||
if exists:
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(f"ALTER TABLE product_versions DROP COLUMN {col}")
|
||||
cur.close()
|
||||
conn.commit()
|
||||
print(f"[migrate] product_versions.{col} 列已删除")
|
||||
except mysql.connector.Error as e:
|
||||
print(f"[migrate] 删除 {col} 失败: {e}")
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def migrate_fix_service_fee_standard():
|
||||
"""修正 project_finances.service_fee_standard 旧数据为默认值 5(5%)"""
|
||||
from db import db
|
||||
|
||||
conn = db()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"UPDATE project_finances SET service_fee_standard = 5 "
|
||||
"WHERE service_fee_standard = 0 OR service_fee_standard IS NULL "
|
||||
"OR service_fee_standard NOT IN (5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25)"
|
||||
)
|
||||
affected = cur.rowcount
|
||||
cur.close()
|
||||
if affected:
|
||||
conn.commit()
|
||||
print(f"[migrate] project_finances: {affected} 条记录 service_fee_standard 修正为 5")
|
||||
finally:
|
||||
conn.close()
|
||||
57
backend/migrations/seed.py
Normal file
57
backend/migrations/seed.py
Normal file
@@ -0,0 +1,57 @@
|
||||
"""migrations/seed.py — 初始化默认用户和示例数据(仅在空库时执行)"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
|
||||
def migrate_seed_users():
|
||||
"""初始化默认用户和工作台权限(仅空库时执行)"""
|
||||
from db import db, _exec, one
|
||||
from werkzeug.security import generate_password_hash
|
||||
|
||||
conn = db()
|
||||
try:
|
||||
if one(conn, "SELECT id FROM users LIMIT 1"):
|
||||
return # 已有用户,跳过
|
||||
|
||||
default_users = [
|
||||
("qiukai", "yxcowork2026", "qiukai", "admin"),
|
||||
("kepu", "kepu123", "科普负责人", "opc_owner"),
|
||||
("keyan", "keyan123", "科研负责人", "opc_owner"),
|
||||
("yihuan", "yihuan123", "医患负责人", "opc_owner"),
|
||||
("mcn", "mcn123", "MCN负责人", "opc_owner"),
|
||||
("wuji", "wuji123", "无界负责人", "opc_owner"),
|
||||
]
|
||||
for username, pwd, display, role in default_users:
|
||||
_exec(conn, "INSERT INTO users (username, password_hash, display_name, role, created_at) VALUES (?,?,?,?,?)",
|
||||
(username, generate_password_hash(pwd, "pbkdf2:sha256"), display, role, date.today().isoformat()))
|
||||
|
||||
# 绑定工作台
|
||||
tenant_map = [
|
||||
("kepu", "科普·无界"), ("keyan", "科研·无界"), ("yihuan", "医患·无界"),
|
||||
("mcn", "MCN·无界"), ("wuji", "学会·无界"),
|
||||
]
|
||||
for uname, tenant in tenant_map:
|
||||
u = one(conn, "SELECT id FROM users WHERE username=?", (uname,))
|
||||
if u:
|
||||
_exec(conn, "INSERT INTO user_tenants (user_id, tenant) VALUES (?,?)", (u["id"], tenant))
|
||||
|
||||
conn.commit()
|
||||
print("[migrate] 默认用户已初始化")
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def migrate_seed_demo_data():
|
||||
"""填充初始示例数据(仅在空库时执行)"""
|
||||
from db import db, one
|
||||
from migrations.seed_data import seed_db
|
||||
|
||||
conn = db()
|
||||
try:
|
||||
if one(conn, "SELECT id FROM sales_leads LIMIT 1"):
|
||||
return # 已有数据,跳过
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
seed_db()
|
||||
print("[migrate] 示例数据已填充")
|
||||
127
backend/migrations/seed_data.py
Normal file
127
backend/migrations/seed_data.py
Normal file
@@ -0,0 +1,127 @@
|
||||
# seed_data.py — 初始示例数据填充(仅在空库时执行一次)
|
||||
# 从 flask_app.py 搬迁,被 migrations/seed.py 调用
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from db import db, _exec, one, WEIXIN_BASE
|
||||
from helpers import add_file_index
|
||||
|
||||
|
||||
def seed_db():
|
||||
"""填充初始示例数据(仅在空库时执行一次)"""
|
||||
conn = db()
|
||||
try:
|
||||
if one(conn, "SELECT id FROM sales_leads LIMIT 1"):
|
||||
return # 已有数据,跳过
|
||||
|
||||
sales = [
|
||||
("齐鲁制药", "P0", "跟进中", "多产品线科普年度框架,需推进高层沟通。"),
|
||||
("百利天恒", "P0", "方案中", "BL-B01D1 上市前医生教育机会,准备方案。"),
|
||||
("信达生物", "P0", "已签约", "现有科普项目升级/续约,重点保障执行。"),
|
||||
("三生制药", "P1", "待跟进", "多科室医生教育+患者科普机会。"),
|
||||
("天广实生物", "P1", "待跟进", "血液肿瘤医生教育机会。"),
|
||||
]
|
||||
for customer, priority, status, note in sales:
|
||||
cur = _exec(conn,
|
||||
"INSERT INTO sales_leads (target_customer, priority, status) VALUES (?,?,?)",
|
||||
(customer, priority, status),
|
||||
)
|
||||
_exec(conn,
|
||||
"INSERT INTO follow_up_records (target_type,target_id,followed_at,content,next_action) VALUES (?,?,?,?,?)",
|
||||
("sales", cur.lastrowid, date.today().isoformat(), note, "明确下一次沟通人和时间"),
|
||||
)
|
||||
|
||||
cur = _exec(conn,
|
||||
"INSERT INTO business_proposals (customer_or_project_name,version,description,status,created_date) VALUES (?,?,?,?,?)",
|
||||
("信达生物", "v1.5", "信达科普项目续约与报价方案", "已提交客户", "2026-05-28"),
|
||||
)
|
||||
proposal_id = cur.lastrowid
|
||||
proposal_dir = WEIXIN_BASE / "2、业务方案/信达/v1.5"
|
||||
for category, names in {
|
||||
"方案": ["整体方案.pptx", "整体方案.pdf"],
|
||||
"成本": ["业务报价-2亿方案.xlsx", "业务报价-5250万方案.xlsx", "5、最新报价.xlsx"],
|
||||
"SOP": ["SOP.docx"],
|
||||
"财务流程": ["财务流程.docx"],
|
||||
}.items():
|
||||
for name in names:
|
||||
add_file_index(conn, "proposal", proposal_id, "v1.5", category, proposal_dir / name, external=True)
|
||||
|
||||
projects = [
|
||||
("圆心科技 科普文章项目", "v2026-文章", "execution", "SOP 执行中", "内容生产", 55, "文章内容生产与审核执行中"),
|
||||
("圆心科技 科普视频项目", "v2026-视频", "execution", "SOP 执行中", "内容生产", 45, "视频脚本、拍摄与审核推进"),
|
||||
("圆心科技 科普专访项目", "v2026-专访", "opportunity", "方案已提交", "商务推进", 0, "专访项目推动签约"),
|
||||
]
|
||||
op_dir = WEIXIN_BASE / "3、运营方案"
|
||||
for name, version, kind, status, stage, progress, note in projects:
|
||||
cur = _exec(conn,
|
||||
"""INSERT INTO operation_projects
|
||||
(project_name,project_version,project_type,project_status,current_stage,target_customer,customer_need,
|
||||
expected_contract_amount,expected_sign_date,sign_probability,next_action,sop_stage,execution_progress,current_deliverable)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
|
||||
(name, version, kind, status, stage, "圆心科技", "科普内容项目执行与管理", 0 if kind == "execution" else 200, "2026-06", 100 if kind == "execution" else 70, "补齐版本要求文件并更新下一节点", stage, progress, note),
|
||||
)
|
||||
_exec(conn,
|
||||
"INSERT INTO follow_up_records (target_type,target_id,followed_at,content,next_action) VALUES (?,?,?,?,?)",
|
||||
("operation", cur.lastrowid, date.today().isoformat(), note, "补齐版本要求文件并更新下一节点"),
|
||||
)
|
||||
|
||||
file_map = [
|
||||
(1, "v2026-文章", "项目方案", "圆心科技--科普文章项目(1).pptx"),
|
||||
(2, "v2026-视频", "项目方案", "圆心科技-科普视频项目(1).pptx"),
|
||||
(3, "v2026-专访", "项目方案", "圆心科技-科普专访项目-2026年(1).pdf"),
|
||||
(1, "v2026-文章", "项目管理手册", "圆心科技《项目管理手册》-2026年.pdf"),
|
||||
(2, "v2026-视频", "审核标准", "科普项目-审核标准(文章-视频-音频).pdf"),
|
||||
]
|
||||
for project_id, version, category, filename in file_map:
|
||||
add_file_index(conn, "operation", project_id, version, category, op_dir / filename, external=True)
|
||||
|
||||
products = [
|
||||
("妙手医生服务小程序", "v1.1", "视频任务增强 + 积分商城", "草稿箱、批量上传、积分商城、消息通知", "2026-Q3", "规划中", "科普平台"),
|
||||
("数字化营销后台管理系统", "v1.2", "运营数据看板 + 智能审核", "医生活跃、任务完成率、AI 预审、渠道数据上报", "2026-Q3", "设计中", "真研平台"),
|
||||
("妙手患者服务", "v0.5", "科普浏览 + 医生主页 MVP", "科普文章/视频浏览、医生主页、搜索", "2026-Q3", "规划中", "科普平台"),
|
||||
("数字人内容平台", "v0.1", "基础数字人视频生成 MVP", "预设形象、AI 配音、脚本驱动、简单模板", "2026-Q3", "规划中", "科普平台"),
|
||||
("渠道分发引擎", "v1.0", "六渠道统一分发", "分发 API、内容适配、分发排期、效果追踪", "2027-Q1", "规划中", "科普平台"),
|
||||
]
|
||||
for product in products:
|
||||
cur = _exec(conn,
|
||||
"INSERT INTO product_versions (product_name,version,version_goal,feature_list,launch_date,status,platform) VALUES (?,?,?,?,?,?,?)",
|
||||
product,
|
||||
)
|
||||
_exec(conn,
|
||||
"INSERT INTO follow_up_records (target_type,target_id,followed_at,content,next_action) VALUES (?,?,?,?,?)",
|
||||
("product", cur.lastrowid, date.today().isoformat(), f"{product[0]} {product[1]}:{product[2]}", "按路线图推进"),
|
||||
)
|
||||
|
||||
for month, record_type, category, amount, notes in [
|
||||
("2026-05", "revenue", "信达生物续约确认收入", 120, "信达项目阶段确收"),
|
||||
("2026-06", "revenue", "信达生物续约确认收入", 80, "信达项目尾款预估"),
|
||||
("2026-05", "cost_expense", "内容生产", 32, "医生劳务与内容制作"),
|
||||
("2026-05", "cost_expense", "运营管理", 16, "项目管理与渠道协同"),
|
||||
("2026-06", "cost_expense", "渠道分发", 24, "投放与分发费用"),
|
||||
]:
|
||||
_exec(conn,
|
||||
"INSERT INTO finance_records (month,record_type,category,amount,occurred_date,notes) VALUES (?,?,?,?,?,?)",
|
||||
(month, record_type, category, amount, f"{month}-01", notes),
|
||||
)
|
||||
|
||||
tasks_seed = [
|
||||
("阶段1:渠道与商务确认", "商务对接", "合同签订", "Anna", "2026-06-30", "法务审核中", "合同签订后开始执行"),
|
||||
("阶段1:渠道与商务确认", "官媒渠道确认", "沟通官媒确定", "段丽华", "2026-06-30", "官媒尽力推,以先达成合作为准", "集团支持"),
|
||||
("阶段1:渠道与商务确认", "官媒渠道确认", "官媒合作签约", "段丽华", "2026-06-18", "", "官媒确认细节"),
|
||||
("阶段2:系统与标准搭建", "系统开发上线", "音频专访系统开发上线", "戴敏/梁军营", "2026-06-18", "客户比较着急执行,需要技术的资源", ""),
|
||||
("阶段2:系统与标准搭建", "系统开发上线", "精品视频系统开发上线", "戴敏/梁军营", "2026-06-25", "", ""),
|
||||
("阶段2:系统与标准搭建", "标准与培训", "业务执行手册SOP", "胡龙飞", "2026-06-12", "", "系统开发上线"),
|
||||
("阶段3:人员与审核入驻", "团队组建", "医学审核人员到位", "胡龙飞", "2026-06-15", "", "审核人员招聘"),
|
||||
("阶段3:人员与审核入驻", "团队组建", "视频制作人员到位", "胡龙飞", "2026-06-18", "", "项目经理招聘"),
|
||||
("阶段4:供应链与制作", "供应商准入", "准入拍摄/剪辑/主持人", "胡龙飞/侯亚凤", "2026-06-18", "", ""),
|
||||
("阶段2:系统与标准搭建", "脚本生产及审核", "生产脚本", "军营", "2026-06-12", "脚本目前生产比较机械,需要提前准备", "细分标签领域完成"),
|
||||
]
|
||||
for phase, milestone, task, owner, due_date, blockers, notes in tasks_seed:
|
||||
_exec(conn,
|
||||
"INSERT INTO project_tasks (project_id,phase,milestone,task,owner,due_date,blockers,notes) VALUES (?,?,?,?,?,?,?,?)",
|
||||
(1, phase, milestone, task, owner, due_date, blockers, notes),
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
162
backend/migrations/tables.py
Normal file
162
backend/migrations/tables.py
Normal file
@@ -0,0 +1,162 @@
|
||||
"""migrations/tables.py — 建表迁移(所有表的 CREATE TABLE IF NOT EXISTS)"""
|
||||
|
||||
|
||||
def migrate_create_tables():
|
||||
"""确保所有业务表存在(幂等)"""
|
||||
from db import db, _exec, mysql, logger
|
||||
|
||||
conn = db()
|
||||
try:
|
||||
tables = [
|
||||
"""CREATE TABLE IF NOT EXISTS sales_leads (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
target_customer VARCHAR(1000) NOT NULL,
|
||||
priority VARCHAR(1000) NOT NULL DEFAULT 'P1',
|
||||
status VARCHAR(1000) NOT NULL DEFAULT '待跟进',
|
||||
created_at VARCHAR(30) NOT NULL DEFAULT '',
|
||||
updated_at VARCHAR(30) NOT NULL DEFAULT ''
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS follow_up_records (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
target_type VARCHAR(1000) NOT NULL,
|
||||
target_id INT NOT NULL,
|
||||
followed_at VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
follower VARCHAR(1000) NOT NULL DEFAULT '慰心',
|
||||
follow_up_method VARCHAR(1000) NOT NULL DEFAULT '记录',
|
||||
content VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
next_action VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
next_follow_up_at VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
created_at VARCHAR(30) NOT NULL DEFAULT '',
|
||||
updated_at VARCHAR(30) NOT NULL DEFAULT ''
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS business_proposals (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
customer_or_project_name VARCHAR(1000) NOT NULL,
|
||||
version VARCHAR(1000) NOT NULL,
|
||||
description VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
status VARCHAR(1000) NOT NULL DEFAULT '草稿',
|
||||
created_date VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
created_at VARCHAR(30) NOT NULL DEFAULT '',
|
||||
updated_at VARCHAR(30) NOT NULL DEFAULT ''
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS operation_projects (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
project_name VARCHAR(1000) NOT NULL,
|
||||
project_version VARCHAR(1000) NOT NULL DEFAULT 'v1.0',
|
||||
project_type VARCHAR(1000) NOT NULL DEFAULT 'opportunity',
|
||||
project_status VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
current_stage VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
owner VARCHAR(1000) NOT NULL DEFAULT '慰心',
|
||||
start_date VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
end_date VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
target_customer VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
customer_need VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
expected_contract_amount DOUBLE NOT NULL DEFAULT 0,
|
||||
expected_sign_date VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
sign_probability DOUBLE NOT NULL DEFAULT 0,
|
||||
next_action VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
related_business_proposal_id INTEGER,
|
||||
sop_file_id INTEGER,
|
||||
sop_stage VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
execution_progress DOUBLE NOT NULL DEFAULT 0,
|
||||
current_deliverable VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
risks VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
notes VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
created_at VARCHAR(30) NOT NULL DEFAULT '',
|
||||
updated_at VARCHAR(30) NOT NULL DEFAULT ''
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS product_versions (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
product_name VARCHAR(1000) NOT NULL,
|
||||
version VARCHAR(1000) NOT NULL,
|
||||
version_goal VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
feature_list VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
launch_date VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
status VARCHAR(1000) NOT NULL DEFAULT '规划中',
|
||||
notes VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
created_at VARCHAR(30) NOT NULL DEFAULT '',
|
||||
updated_at VARCHAR(30) NOT NULL DEFAULT ''
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS finance_records (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
month VARCHAR(1000) NOT NULL,
|
||||
project_name VARCHAR(1000) NOT NULL DEFAULT '科普(慰心斋)',
|
||||
record_type VARCHAR(1000) NOT NULL,
|
||||
category VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
amount DOUBLE NOT NULL DEFAULT 0,
|
||||
occurred_date VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
notes VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
created_at VARCHAR(30) NOT NULL DEFAULT '',
|
||||
updated_at VARCHAR(30) NOT NULL DEFAULT ''
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS file_assets (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
module VARCHAR(1000) NOT NULL,
|
||||
owner_id INT NOT NULL,
|
||||
owner_version VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
file_category VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
file_name VARCHAR(1000) NOT NULL,
|
||||
file_type VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
file_size INTEGER NOT NULL DEFAULT 0,
|
||||
file_path VARCHAR(1000) NOT NULL,
|
||||
is_external INTEGER NOT NULL DEFAULT 0,
|
||||
notes VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
created_at VARCHAR(30) NOT NULL DEFAULT '',
|
||||
updated_at VARCHAR(30) NOT NULL DEFAULT ''
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS project_tasks (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
project_id INTEGER NOT NULL,
|
||||
phase VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
milestone VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
task VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
owner VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
due_date VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
blockers VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
notes VARCHAR(1000) NOT NULL DEFAULT '',
|
||||
created_at VARCHAR(30) NOT NULL DEFAULT '',
|
||||
updated_at VARCHAR(30) NOT NULL DEFAULT ''
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS users (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
username VARCHAR(100) NOT NULL UNIQUE,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
display_name VARCHAR(100) NOT NULL,
|
||||
role VARCHAR(50) NOT NULL DEFAULT 'opc_owner',
|
||||
created_at VARCHAR(30) NOT NULL DEFAULT ''
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS user_tenants (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id INT NOT NULL,
|
||||
tenant VARCHAR(100) NOT NULL,
|
||||
UNIQUE KEY (user_id, tenant)
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS project_finances (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
tenant VARCHAR(100) NOT NULL DEFAULT '科普·无界',
|
||||
project_id VARCHAR(100) NOT NULL DEFAULT '',
|
||||
business_type VARCHAR(100) NOT NULL DEFAULT '',
|
||||
customer_name VARCHAR(200) NOT NULL DEFAULT '',
|
||||
sign_amount DOUBLE NOT NULL DEFAULT 0,
|
||||
sign_month VARCHAR(20) NOT NULL DEFAULT '',
|
||||
status VARCHAR(50) NOT NULL DEFAULT '待签约',
|
||||
sales_person VARCHAR(100) NOT NULL DEFAULT '',
|
||||
total_rev DOUBLE NOT NULL DEFAULT 0,
|
||||
total_gross DOUBLE NOT NULL DEFAULT 0,
|
||||
budget_data TEXT,
|
||||
created_at VARCHAR(30) NOT NULL DEFAULT '',
|
||||
updated_at VARCHAR(30) NOT NULL DEFAULT ''
|
||||
)""",
|
||||
]
|
||||
|
||||
for ddl in tables:
|
||||
try:
|
||||
_exec(conn, ddl)
|
||||
conn.commit()
|
||||
except mysql.connector.Error as e:
|
||||
logger.debug(f"create table skipped: {e}")
|
||||
conn.commit()
|
||||
|
||||
print("[migrate] 所有业务表已就绪")
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -1 +1,2 @@
|
||||
Flask==3.0.3
|
||||
python-dateutil==2.9.0
|
||||
|
||||
661
backend/routes.py
Normal file
661
backend/routes.py
Normal file
@@ -0,0 +1,661 @@
|
||||
# routes.py — 全部 HTTP 路由(Blueprint)
|
||||
# 依赖:flask, db.py, helpers.py, werkzeug
|
||||
|
||||
import os
|
||||
import json
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from flask import Blueprint, jsonify, render_template, request, send_file, session, redirect
|
||||
from werkzeug.security import generate_password_hash, check_password_hash
|
||||
|
||||
from db import db, now, _exec, rows, one, UPLOAD_DIR
|
||||
from helpers import add_file_index, attach_common, monthly_finance
|
||||
|
||||
bp = Blueprint("api", __name__)
|
||||
|
||||
ALL_TENANTS = ["总工作台", "科普·无界", "科研·无界", "医患·无界", "MCN·无界", "学会·无界"]
|
||||
|
||||
TABLES = {
|
||||
"sales": ("sales_leads", ["target_customer", "priority", "status", "tenant"]),
|
||||
"proposals": ("business_proposals", ["customer_or_project_name", "version", "description", "status", "created_date", "proposal_type", "notes", "tenant"]),
|
||||
"operations": ("operation_projects", ["project_name", "project_version", "project_type", "project_status", "current_stage", "owner", "target_customer", "customer_need", "expected_contract_amount", "expected_sign_date", "sign_probability", "next_action", "sop_stage", "execution_progress", "current_deliverable", "risks", "notes", "tenant"]),
|
||||
"products": ("product_versions", ["product_name", "version", "version_goal", "priority", "start_date", "plan_date", "dev_done_date", "test_date", "launch_date", "status", "notes", "tenant"]),
|
||||
"finance": ("finance_records", ["month", "project_name", "record_type", "category", "amount", "occurred_date", "notes", "tenant"]),
|
||||
"tasks": ("project_tasks", ["project_id", "phase", "milestone", "task", "owner", "due_date", "blockers", "notes", "status", "sort_order", "priority", "tenant"]),
|
||||
"projectFinances": ("project_finances", ["project_id", "tenant", "business_type", "customer_name", "sign_amount", "sign_month", "status", "sales_person", "owner", "total_rev", "total_gross", "total_payment", "total_cost", "total_paid", "budget_data", "start_date", "end_date", "task_type", "task_count", "service_fee_standard", "project_manager", "task_data", "project_code", "contact_name", "contact_phone", "other_info"]),
|
||||
}
|
||||
|
||||
# ---------- 鉴权装饰器 ----------
|
||||
|
||||
def login_required(f):
|
||||
from functools import wraps
|
||||
@wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
if "user_id" not in session:
|
||||
return jsonify({"error": "未登录"}), 401
|
||||
return f(*args, **kwargs)
|
||||
return decorated
|
||||
|
||||
|
||||
def admin_required(f):
|
||||
from functools import wraps
|
||||
@wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
if "user_id" not in session:
|
||||
return jsonify({"error": "未登录"}), 401
|
||||
if session.get("role") != "admin":
|
||||
return jsonify({"error": "无权限"}), 403
|
||||
return f(*args, **kwargs)
|
||||
return decorated
|
||||
|
||||
|
||||
# ---------- 认证路由 ----------
|
||||
|
||||
@bp.route("/login")
|
||||
def login_page():
|
||||
return render_template("login.html")
|
||||
|
||||
|
||||
@bp.route("/api/auth/login", methods=["POST"])
|
||||
def auth_login():
|
||||
data = request.get_json(force=True) or {}
|
||||
username = data.get("username", "").strip()
|
||||
password = data.get("password", "")
|
||||
conn = db()
|
||||
try:
|
||||
user = one(conn, "SELECT * FROM users WHERE username=?", (username,))
|
||||
if not user or not check_password_hash(user["password_hash"], password):
|
||||
return jsonify({"error": "用户名或密码错误"}), 401
|
||||
session["user_id"] = user["id"]
|
||||
session["username"] = user["username"]
|
||||
session["display_name"] = user["display_name"]
|
||||
session["role"] = user["role"]
|
||||
if user["role"] == "admin":
|
||||
session["tenants"] = ["总工作台", "科普·无界", "科研·无界", "医患·无界", "MCN·无界", "学会·无界"]
|
||||
else:
|
||||
ut = rows(conn, "SELECT tenant FROM user_tenants WHERE user_id=?", (user["id"],))
|
||||
session["tenants"] = [x["tenant"] for x in ut]
|
||||
return jsonify({
|
||||
"ok": True,
|
||||
"user": {"id": user["id"], "username": user["username"], "display_name": user["display_name"], "role": user["role"]},
|
||||
"tenants": session["tenants"],
|
||||
})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@bp.route("/api/auth/logout", methods=["POST"])
|
||||
def auth_logout():
|
||||
session.clear()
|
||||
return jsonify({"ok": True})
|
||||
|
||||
|
||||
@bp.route("/api/auth/me")
|
||||
def auth_me():
|
||||
if "user_id" not in session:
|
||||
return jsonify({"logged_in": False})
|
||||
tenants = session.get("tenants", [])
|
||||
if "总工作台" not in tenants:
|
||||
tenants = ["总工作台"] + tenants
|
||||
return jsonify({
|
||||
"logged_in": True,
|
||||
"user": {"id": session["user_id"], "username": session["username"], "display_name": session["display_name"], "role": session["role"]},
|
||||
"tenants": tenants,
|
||||
})
|
||||
|
||||
|
||||
# ---------- 账号管理 ----------
|
||||
|
||||
@bp.route("/api/users")
|
||||
@admin_required
|
||||
def list_users():
|
||||
conn = db()
|
||||
try:
|
||||
users = rows(conn, "SELECT id, username, display_name, role, created_at FROM users ORDER BY id")
|
||||
ut_rows = rows(conn, "SELECT user_id, tenant FROM user_tenants")
|
||||
tenant_map = {}
|
||||
for r in ut_rows:
|
||||
tenant_map.setdefault(r["user_id"], []).append(r["tenant"])
|
||||
for u in users:
|
||||
u["tenants"] = tenant_map.get(u["id"], [])
|
||||
return jsonify(users)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@bp.route("/api/users", methods=["POST"])
|
||||
@admin_required
|
||||
def create_user():
|
||||
data = request.get_json(force=True)
|
||||
username = (data.get("username") or "").strip()
|
||||
display_name = (data.get("display_name") or "").strip()
|
||||
password = data.get("password") or ""
|
||||
role = data.get("role") or "opc_owner"
|
||||
tenants = data.get("tenants") or []
|
||||
if not username or not password or not display_name:
|
||||
return jsonify({"error": "用户名/密码/显示名不能为空"}), 400
|
||||
if role not in ("admin", "opc_owner"):
|
||||
return jsonify({"error": "角色非法"}), 400
|
||||
conn = db()
|
||||
try:
|
||||
if one(conn, "SELECT id FROM users WHERE username=?", (username,)):
|
||||
return jsonify({"error": "用户名已存在"}), 400
|
||||
_exec(conn, "INSERT INTO users (username, password_hash, display_name, role, created_at) VALUES (?,?,?,?,?)",
|
||||
(username, generate_password_hash(password, "pbkdf2:sha256"), display_name, role, date.today().isoformat()))
|
||||
u = one(conn, "SELECT id FROM users WHERE username=?", (username,))
|
||||
for t in tenants:
|
||||
if t in ALL_TENANTS:
|
||||
_exec(conn, "INSERT IGNORE INTO user_tenants (user_id, tenant) VALUES (?,?)", (u["id"], t))
|
||||
conn.commit()
|
||||
return jsonify({"ok": True, "id": u["id"]})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@bp.route("/api/users/<int:uid>", methods=["PUT"])
|
||||
@admin_required
|
||||
def update_user(uid):
|
||||
data = request.get_json(force=True)
|
||||
conn = db()
|
||||
try:
|
||||
u = one(conn, "SELECT * FROM users WHERE id=?", (uid,))
|
||||
if not u:
|
||||
return jsonify({"error": "用户不存在"}), 404
|
||||
display_name = (data.get("display_name") or "").strip() or u["display_name"]
|
||||
role = data.get("role") or u["role"]
|
||||
if role not in ("admin", "opc_owner"):
|
||||
return jsonify({"error": "角色非法"}), 400
|
||||
password = data.get("password") or ""
|
||||
if password:
|
||||
_exec(conn, "UPDATE users SET display_name=?, role=?, password_hash=? WHERE id=?",
|
||||
(display_name, role, generate_password_hash(password, "pbkdf2:sha256"), uid))
|
||||
else:
|
||||
_exec(conn, "UPDATE users SET display_name=?, role=? WHERE id=?", (display_name, role, uid))
|
||||
if "tenants" in data:
|
||||
_exec(conn, "DELETE FROM user_tenants WHERE user_id=?", (uid,))
|
||||
for t in data["tenants"]:
|
||||
if t in ALL_TENANTS:
|
||||
_exec(conn, "INSERT IGNORE INTO user_tenants (user_id, tenant) VALUES (?,?)", (uid, t))
|
||||
if role != "admin":
|
||||
admin_count = one(conn, "SELECT COUNT(*) AS c FROM users WHERE role='admin'")["c"]
|
||||
if admin_count == 0:
|
||||
return jsonify({"error": "至少保留一个管理员"}), 400
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@bp.route("/api/users/<int:uid>", methods=["DELETE"])
|
||||
@admin_required
|
||||
def delete_user(uid):
|
||||
if uid == session.get("user_id"):
|
||||
return jsonify({"error": "不能删除当前登录账号"}), 400
|
||||
conn = db()
|
||||
try:
|
||||
u = one(conn, "SELECT * FROM users WHERE id=?", (uid,))
|
||||
if not u:
|
||||
return jsonify({"error": "用户不存在"}), 404
|
||||
if u["role"] == "admin":
|
||||
admin_count = one(conn, "SELECT COUNT(*) AS c FROM users WHERE role='admin'")["c"]
|
||||
if admin_count <= 1:
|
||||
return jsonify({"error": "至少保留一个管理员"}), 400
|
||||
_exec(conn, "DELETE FROM user_tenants WHERE user_id=?", (uid,))
|
||||
_exec(conn, "DELETE FROM users WHERE id=?", (uid,))
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@bp.route("/api/tenants")
|
||||
def list_tenants():
|
||||
return jsonify(ALL_TENANTS)
|
||||
|
||||
|
||||
# ---------- 首页 + bootstrap ----------
|
||||
|
||||
@bp.route("/")
|
||||
def index():
|
||||
if "user_id" not in session:
|
||||
return redirect("/login")
|
||||
return render_template("index.html")
|
||||
|
||||
|
||||
@bp.route("/api/bootstrap")
|
||||
def bootstrap():
|
||||
if "user_id" not in session:
|
||||
return jsonify({"error": "未登录"}), 401
|
||||
tenant = request.args.get("tenant", session.get("tenants", ["科普·无界"])[0])
|
||||
allowed = session.get("tenants", [])
|
||||
if "总工作台" not in allowed:
|
||||
allowed = ["总工作台"] + allowed
|
||||
if tenant not in allowed:
|
||||
tenant = allowed[0]
|
||||
conn = db()
|
||||
try:
|
||||
# 总工作台:聚合所有工作台的首页数据
|
||||
if tenant == "总工作台":
|
||||
real_tenants = [t for t in allowed if t != "总工作台"]
|
||||
all_metrics = []
|
||||
all_monthly = []
|
||||
all_recent = []
|
||||
for t in real_tenants:
|
||||
t_pfs = rows(conn, "SELECT * FROM project_finances WHERE tenant=? ORDER BY id DESC", [t])
|
||||
t_ops = attach_common(conn, "operations", rows(conn, "SELECT * FROM operation_projects WHERE tenant=? ORDER BY id ASC", [t]))
|
||||
t_sales = attach_common(conn, "sales", rows(conn, "SELECT * FROM sales_leads WHERE tenant=? ORDER BY id DESC", [t]))
|
||||
t_products = attach_common(conn, "products", rows(conn, "SELECT * FROM product_versions WHERE tenant=? ORDER BY id DESC", [t]))
|
||||
t_proposals = attach_common(conn, "proposals", rows(conn, "SELECT * FROM business_proposals WHERE tenant=? ORDER BY id DESC", [t]))
|
||||
t_signed_pfs = [x for x in t_pfs if x["status"] == "已签约"]
|
||||
def t_parse_budget(pf):
|
||||
try:
|
||||
budget = json.loads(pf.get("budget_data") or "[]")
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
budget = []
|
||||
return {(b.get("month") or "").replace("-", "_"): b for b in budget}
|
||||
t_bm = {pf["id"]: t_parse_budget(pf) for pf in t_pfs}
|
||||
def t_sum_budget(field, months_range):
|
||||
total = 0
|
||||
for pf in t_pfs:
|
||||
bm = t_bm.get(pf["id"], {})
|
||||
for m in months_range:
|
||||
b = bm.get(f"2026_{m:02d}")
|
||||
if b:
|
||||
total += float(b.get(field) or 0)
|
||||
return total
|
||||
_now_month = date.today().month
|
||||
_q_start = ((_now_month - 1) // 3) * 3 + 1
|
||||
_q_range = range(_q_start, _q_start + 3)
|
||||
_q_months = [f"2026-{m:02d}" for m in _q_range]
|
||||
_prev_q_start = ((_now_month - 4) // 3) * 3 + 1
|
||||
_prev_q_range = range(max(_prev_q_start, 1), _prev_q_start + 3)
|
||||
_prev_q_months = [f"2026-{m:02d}" for m in _prev_q_range]
|
||||
_prev_month = _now_month - 1 if _now_month > 1 else None
|
||||
all_metrics.append({
|
||||
"total_projects": len(t_signed_pfs),
|
||||
"total_proposals": len(t_ops),
|
||||
"total_products": len(t_proposals),
|
||||
"upcoming_products": len(t_products),
|
||||
"signed_amount": sum(x["sign_amount"] or 0 for x in t_pfs if x["status"] == "已签约"),
|
||||
"signed_annual": sum(x["sign_amount"] or 0 for x in t_pfs if x["status"] == "已签约"),
|
||||
"signed_q2": sum(x["sign_amount"] or 0 for x in t_pfs if x["status"] == "已签约" and (x.get("sign_month") or "")[:7] in _q_months),
|
||||
"signed_month": sum(x["sign_amount"] or 0 for x in t_pfs if x["status"] == "已签约" and (x.get("sign_month") or "")[:7] == f"2026-{_now_month:02d}"),
|
||||
"signed_prev_q": sum(x["sign_amount"] or 0 for x in t_pfs if x["status"] == "已签约" and (x.get("sign_month") or "")[:7] in _prev_q_months),
|
||||
"signed_prev_month": sum(x["sign_amount"] or 0 for x in t_pfs if x["status"] == "已签约" and (x.get("sign_month") or "")[:7] == f"2026-{_prev_month:02d}") if _prev_month else 0,
|
||||
"revenue_annual": t_sum_budget("rev", range(1, 13)),
|
||||
"revenue_q2": t_sum_budget("rev", _q_range),
|
||||
"monthly_revenue": t_sum_budget("rev", [_now_month]),
|
||||
"revenue_prev_q": t_sum_budget("rev", _prev_q_range),
|
||||
"revenue_prev_month": t_sum_budget("rev", [_prev_month]) if _prev_month else 0,
|
||||
"gross_annual": t_sum_budget("gross", range(1, 13)),
|
||||
"gross_q2": t_sum_budget("gross", _q_range),
|
||||
"monthly_net_profit": t_sum_budget("gross", [_now_month]),
|
||||
"gross_prev_q": t_sum_budget("gross", _prev_q_range),
|
||||
"gross_prev_month": t_sum_budget("gross", [_prev_month]) if _prev_month else 0,
|
||||
"payment_annual": t_sum_budget("payment", range(1, 13)),
|
||||
"payment_q2": t_sum_budget("payment", _q_range),
|
||||
"payment_month": t_sum_budget("payment", [_now_month]),
|
||||
"payment_prev_q": t_sum_budget("payment", _prev_q_range),
|
||||
"payment_prev_month": t_sum_budget("payment", [_prev_month]) if _prev_month else 0,
|
||||
"cost_annual": t_sum_budget("cost", range(1, 13)),
|
||||
"cost_q2": t_sum_budget("cost", _q_range),
|
||||
"cost_month": t_sum_budget("cost", [_now_month]),
|
||||
"cost_prev_q": t_sum_budget("cost", _prev_q_range),
|
||||
"cost_prev_month": t_sum_budget("cost", [_prev_month]) if _prev_month else 0,
|
||||
})
|
||||
all_monthly.append(monthly_finance(conn, t))
|
||||
all_recent.extend(rows(conn, "SELECT * FROM follow_up_records WHERE tenant=? ORDER BY id DESC LIMIT 4", [t]))
|
||||
agg = {}
|
||||
for key in ["total_projects","total_proposals","total_products","upcoming_products","signed_amount","signed_annual","signed_q2","signed_month","signed_prev_q","signed_prev_month","revenue_annual","revenue_q2","monthly_revenue","revenue_prev_q","revenue_prev_month","gross_annual","gross_q2","monthly_net_profit","gross_prev_q","gross_prev_month","payment_annual","payment_q2","payment_month","payment_prev_q","payment_prev_month","cost_annual","cost_q2","cost_month","cost_prev_q","cost_prev_month"]:
|
||||
agg[key] = sum(m.get(key, 0) for m in all_metrics)
|
||||
merged_monthly = []
|
||||
for i in range(12):
|
||||
m = {"month": all_monthly[0][i]["month"] if all_monthly and len(all_monthly[0]) > i else f"2026-{i+1:02d}"}
|
||||
for field in ["revenue","gross","payment","cost","sign"]:
|
||||
m[field] = sum(tl[i][field] if i < len(tl) else 0 for tl in all_monthly)
|
||||
merged_monthly.append(m)
|
||||
summary = {
|
||||
"project_name": "总工作台",
|
||||
"metrics": agg,
|
||||
"recent": sorted(all_recent, key=lambda x: x.get("id", 0), reverse=True)[:8],
|
||||
"risks": [],
|
||||
}
|
||||
return jsonify({"summary": summary, "sales": [], "proposals": [], "operations": [], "products": [], "finance": [], "projectFinances": [], "financeMonthly": merged_monthly, "tasks": [], "tenant": tenant, "tenants": allowed})
|
||||
|
||||
def q(sql, *args):
|
||||
return rows(conn, sql, args)
|
||||
sales = attach_common(conn, "sales", q("SELECT * FROM sales_leads WHERE tenant=? ORDER BY id DESC", tenant))
|
||||
proposals = attach_common(conn, "proposals", q("SELECT * FROM business_proposals WHERE tenant=? ORDER BY id DESC", tenant))
|
||||
operations = attach_common(conn, "operations", q("SELECT * FROM operation_projects WHERE tenant=? ORDER BY id ASC", tenant))
|
||||
products = attach_common(conn, "products", q("SELECT * FROM product_versions WHERE tenant=? ORDER BY id DESC", tenant))
|
||||
finance = q("SELECT * FROM finance_records WHERE tenant=? ORDER BY month DESC, id DESC", tenant)
|
||||
tasks = q("SELECT * FROM project_tasks WHERE tenant=? ORDER BY phase, sort_order, id", tenant)
|
||||
pfs = q("SELECT * FROM project_finances WHERE tenant=? ORDER BY id DESC", tenant)
|
||||
signed_pfs = [x for x in pfs if x["status"] == "已签约"]
|
||||
|
||||
def parse_budget(pf):
|
||||
try:
|
||||
budget = json.loads(pf.get("budget_data") or "[]")
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
budget = []
|
||||
return {(b.get("month") or "").replace("-", "_"): b for b in budget}
|
||||
|
||||
budget_maps = [(pf, parse_budget(pf)) for pf in signed_pfs]
|
||||
|
||||
def sum_budget(field, months_range):
|
||||
total = 0
|
||||
for pf, bm in budget_maps:
|
||||
for m in months_range:
|
||||
b = bm.get(f"2026_{m:02d}")
|
||||
if b:
|
||||
total += float(b.get(field) or 0)
|
||||
return total
|
||||
|
||||
_now_month = date.today().month
|
||||
_q_start = ((_now_month - 1) // 3) * 3 + 1
|
||||
_q_range = range(_q_start, _q_start + 3)
|
||||
_prev_q_start = ((_now_month - 4) // 3) * 3 + 1
|
||||
_prev_q_range = range(max(_prev_q_start, 1), _prev_q_start + 3)
|
||||
_prev_month = _now_month - 1 if _now_month > 1 else None
|
||||
rev_annual = sum_budget("rev", range(1, 13))
|
||||
gross_annual = sum_budget("gross", range(1, 13))
|
||||
rev_q2 = sum_budget("rev", _q_range)
|
||||
gross_q2 = sum_budget("gross", _q_range)
|
||||
rev_month = sum_budget("rev", [_now_month])
|
||||
gross_month = sum_budget("gross", [_now_month])
|
||||
rev_prev_q = sum_budget("rev", _prev_q_range)
|
||||
gross_prev_q = sum_budget("gross", _prev_q_range)
|
||||
rev_prev_month = sum_budget("rev", [_prev_month]) if _prev_month else 0
|
||||
gross_prev_month = sum_budget("gross", [_prev_month]) if _prev_month else 0
|
||||
payment_annual = sum_budget("payment", range(1, 13))
|
||||
cost_annual = sum_budget("cost", range(1, 13))
|
||||
payment_q2 = sum_budget("payment", _q_range)
|
||||
cost_q2 = sum_budget("cost", _q_range)
|
||||
payment_month = sum_budget("payment", [_now_month])
|
||||
cost_month = sum_budget("cost", [_now_month])
|
||||
payment_prev_q = sum_budget("payment", _prev_q_range)
|
||||
cost_prev_q = sum_budget("cost", _prev_q_range)
|
||||
payment_prev_month = sum_budget("payment", [_prev_month]) if _prev_month else 0
|
||||
cost_prev_month = sum_budget("cost", [_prev_month]) if _prev_month else 0
|
||||
def pf_status_sum(status):
|
||||
return sum(x["sign_amount"] or 0 for x in pfs if x["status"] == status)
|
||||
signed_amount = pf_status_sum("已签约")
|
||||
signed_annual = sum(x["sign_amount"] or 0 for x in pfs if x["status"] == "已签约")
|
||||
_q_months = [f"2026-{m:02d}" for m in _q_range]
|
||||
signed_q2 = sum(x["sign_amount"] or 0 for x in pfs if x["status"] == "已签约" and (x.get("sign_month") or "")[:7] in _q_months)
|
||||
signed_month = sum(x["sign_amount"] or 0 for x in pfs if x["status"] == "已签约" and (x.get("sign_month") or "")[:7] == f"2026-{_now_month:02d}")
|
||||
_prev_q_months = [f"2026-{m:02d}" for m in _prev_q_range]
|
||||
signed_prev_q = sum(x["sign_amount"] or 0 for x in pfs if x["status"] == "已签约" and (x.get("sign_month") or "")[:7] in _prev_q_months)
|
||||
signed_prev_month = sum(x["sign_amount"] or 0 for x in pfs if x["status"] == "已签约" and (x.get("sign_month") or "")[:7] == f"2026-{_prev_month:02d}") if _prev_month else 0
|
||||
pipeline_amount = sum(x["expected_contract_amount"] or 0 for x in operations if x["project_status"] not in ["已签约","已丢单","已归档","已完成"])
|
||||
signed_not_executed = sum(x["expected_contract_amount"] or 0 for x in operations if x["project_type"] == "execution" and x["execution_progress"] < 100)
|
||||
summary = {
|
||||
"project_name": "科普(慰心斋)",
|
||||
"metrics": {
|
||||
"p0_customers": len([x for x in sales if x["priority"] == "P0"]),
|
||||
"active_sales": len([x for x in sales if x["status"] in ["待跟进", "跟进中", "方案中", "商务谈判"]]),
|
||||
"execution_projects": len([x for x in operations if x["project_type"] == "execution"]),
|
||||
"risk_projects": len([x for x in operations if x["project_status"] == "有风险" or x["risks"]]),
|
||||
"monthly_revenue": rev_month,
|
||||
"monthly_net_profit": gross_month,
|
||||
"monthly_gross": gross_month,
|
||||
"upcoming_products": len(products),
|
||||
"total_projects": len(signed_pfs),
|
||||
"total_proposals": len(operations),
|
||||
"total_products": len(proposals),
|
||||
"signed_amount": signed_amount,
|
||||
"signed_annual": signed_annual,
|
||||
"signed_q2": signed_q2,
|
||||
"signed_month": signed_month,
|
||||
"signed_prev_q": signed_prev_q,
|
||||
"signed_prev_month": signed_prev_month,
|
||||
"pipeline_amount": pipeline_amount,
|
||||
"revenue_annual": rev_annual,
|
||||
"revenue_q2": rev_q2,
|
||||
"revenue_prev_q": rev_prev_q,
|
||||
"revenue_prev_month": rev_prev_month,
|
||||
"gross_annual": gross_annual,
|
||||
"gross_q2": gross_q2,
|
||||
"gross_prev_q": gross_prev_q,
|
||||
"gross_prev_month": gross_prev_month,
|
||||
"payment_annual": payment_annual,
|
||||
"payment_q2": payment_q2,
|
||||
"payment_month": payment_month,
|
||||
"payment_prev_q": payment_prev_q,
|
||||
"payment_prev_month": payment_prev_month,
|
||||
"cost_annual": cost_annual,
|
||||
"cost_q2": cost_q2,
|
||||
"cost_month": cost_month,
|
||||
"cost_prev_q": cost_prev_q,
|
||||
"cost_prev_month": cost_prev_month,
|
||||
"signed_not_executed": signed_not_executed,
|
||||
},
|
||||
"recent": q("SELECT * FROM follow_up_records WHERE tenant=? ORDER BY id DESC LIMIT 8", tenant),
|
||||
"risks": [{"title": "执行提醒", "content": x["next_action"]} for x in operations if x["next_action"]][:5],
|
||||
}
|
||||
return jsonify({"summary": summary, "sales": sales, "proposals": proposals, "operations": operations, "products": products, "finance": finance, "projectFinances": pfs, "financeMonthly": monthly_finance(conn, tenant), "tasks": tasks, "tenant": tenant, "tenants": allowed})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# ---------- 通用 CRUD ----------
|
||||
|
||||
@bp.route("/api/<resource>", methods=["POST"])
|
||||
@login_required
|
||||
def create_resource(resource):
|
||||
if resource not in TABLES:
|
||||
return jsonify({"error": "unknown resource"}), 404
|
||||
table, cols = TABLES[resource]
|
||||
payload = request.get_json(force=True).get("data", {})
|
||||
if resource == "tasks":
|
||||
valid_statuses = ["未开始", "进行中", "已结束"]
|
||||
if not payload.get("status") or payload["status"] not in valid_statuses:
|
||||
payload["status"] = "未开始"
|
||||
conn = db()
|
||||
try:
|
||||
type_cur = conn.cursor()
|
||||
type_cur.execute(f"DESCRIBE {table}")
|
||||
col_types = {r[0]: r[1].upper() for r in type_cur.fetchall()}
|
||||
type_cur.close()
|
||||
values = []
|
||||
for col in cols:
|
||||
val = payload.get(col, "")
|
||||
if val == "" and ("DOUBLE" in col_types.get(col, "") or "INT" in col_types.get(col, "")):
|
||||
val = 0
|
||||
values.append(val)
|
||||
cur = _exec(conn, f"INSERT INTO {table} ({','.join(cols)}) VALUES ({','.join(['?'] * len(cols))})", values)
|
||||
conn.commit()
|
||||
return jsonify({"id": cur.lastrowid})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@bp.route("/api/<resource>/<int:item_id>", methods=["PUT", "DELETE"])
|
||||
@login_required
|
||||
def update_resource(resource, item_id):
|
||||
if resource not in TABLES:
|
||||
return jsonify({"error": "unknown resource"}), 404
|
||||
table, cols = TABLES[resource]
|
||||
conn = db()
|
||||
try:
|
||||
if request.method == "DELETE":
|
||||
_exec(conn, f"DELETE FROM {table} WHERE id=?", (item_id,))
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
payload = request.get_json(force=True).get("data", {})
|
||||
if resource == "tasks" and "status" in payload:
|
||||
valid_statuses = ["未开始", "进行中", "已结束"]
|
||||
if not payload["status"] or payload["status"] not in valid_statuses:
|
||||
payload["status"] = "未开始"
|
||||
if resource == "products":
|
||||
cur = _exec(conn, f"SELECT start_date FROM {table} WHERE id=?", (item_id,))
|
||||
row = cur.fetchone()
|
||||
cur.close()
|
||||
current_start = (row or {}).get("start_date", "") or ""
|
||||
new_start = payload.get("start_date", current_start)
|
||||
if "start_date" in payload and not new_start:
|
||||
return jsonify({"error": "启动时间为必填项"}), 400
|
||||
date_fields = ["plan_date", "dev_done_date", "test_date", "launch_date"]
|
||||
for f in date_fields:
|
||||
if f in payload and payload[f] and new_start and payload[f] < new_start:
|
||||
labels = {"plan_date": "产品方案", "dev_done_date": "研发完成", "test_date": "测试完成", "launch_date": "上线时间"}
|
||||
return jsonify({"error": f"{labels[f]}不能早于启动时间({new_start})"}), 400
|
||||
update_cols = [col for col in cols if col in payload]
|
||||
if update_cols:
|
||||
_exec(conn,
|
||||
f"UPDATE {table} SET {','.join([col + '=?' for col in update_cols])}, updated_at=? WHERE id=?",
|
||||
[payload[col] for col in update_cols] + [now(), item_id],
|
||||
)
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# ---------- followups ----------
|
||||
|
||||
@bp.route("/api/followups/<target_type>/<int:target_id>")
|
||||
def list_followups(target_type, target_id):
|
||||
conn = db()
|
||||
try:
|
||||
fups = rows(conn,
|
||||
"SELECT * FROM follow_up_records WHERE target_type=? AND target_id=? ORDER BY followed_at DESC, id DESC",
|
||||
(target_type, target_id))
|
||||
return jsonify(fups)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@bp.route("/api/followups/<target_type>/<int:target_id>", methods=["POST"])
|
||||
@login_required
|
||||
def add_followup(target_type, target_id):
|
||||
payload = request.get_json(force=True).get("data", {})
|
||||
conn = db()
|
||||
try:
|
||||
_exec(conn,
|
||||
"""INSERT INTO follow_up_records
|
||||
(target_type,target_id,followed_at,follower,follow_up_method,content,next_action,next_follow_up_at,tenant)
|
||||
VALUES (?,?,?,?,?,?,?,?,?)""",
|
||||
(
|
||||
target_type,
|
||||
target_id,
|
||||
payload.get("followed_at") or date.today().isoformat(),
|
||||
payload.get("follower") or "慰心",
|
||||
payload.get("follow_up_method") or "记录",
|
||||
payload.get("content") or "",
|
||||
payload.get("next_action") or "",
|
||||
payload.get("next_follow_up_at") or "",
|
||||
payload.get("tenant") or "科普·无界",
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@bp.route("/api/followups/<int:followup_id>", methods=["DELETE"])
|
||||
@login_required
|
||||
def delete_followup(followup_id):
|
||||
conn = db()
|
||||
try:
|
||||
cur = _exec(conn, "DELETE FROM follow_up_records WHERE id=?", (followup_id,))
|
||||
conn.commit()
|
||||
if cur.rowcount == 0:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# ---------- batch sort ----------
|
||||
|
||||
@bp.route("/api/tasks/batch-sort", methods=["POST"])
|
||||
@login_required
|
||||
def batch_sort_tasks():
|
||||
conn = db()
|
||||
try:
|
||||
items = request.get_json(force=True).get("items", [])
|
||||
for item in items:
|
||||
_exec(conn, "UPDATE project_tasks SET sort_order=? WHERE id=?", (item["sort_order"], item["id"]))
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@bp.route("/api/operations/batch-sort", methods=["POST"])
|
||||
@login_required
|
||||
def batch_sort_operations():
|
||||
conn = db()
|
||||
try:
|
||||
items = request.get_json(force=True).get("items", [])
|
||||
for item in items:
|
||||
_exec(conn, "UPDATE operation_projects SET sort_order=? WHERE id=?", (item["sort_order"], item["id"]))
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# ---------- files ----------
|
||||
|
||||
@bp.route("/api/files/upload", methods=["POST"])
|
||||
@login_required
|
||||
def upload_file():
|
||||
file = request.files["file"]
|
||||
module = request.form["module"]
|
||||
owner_id = int(request.form["owner_id"])
|
||||
owner_version = request.form.get("owner_version", "")
|
||||
category = request.form.get("file_category", "")
|
||||
folder = UPLOAD_DIR / module / str(owner_id)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
target = folder / file.filename
|
||||
file.save(target)
|
||||
conn = db()
|
||||
try:
|
||||
add_file_index(conn, module, owner_id, owner_version, category, target, external=False)
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@bp.route("/api/files/<int:file_id>/content")
|
||||
def file_content(file_id):
|
||||
conn = db()
|
||||
try:
|
||||
asset = one(conn, "SELECT * FROM file_assets WHERE id=?", (file_id,))
|
||||
if not asset:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
path = Path(asset["file_path"])
|
||||
if not path.exists():
|
||||
return jsonify({"error": "missing"}), 404
|
||||
return send_file(path, as_attachment=request.args.get("inline") == "false", download_name=asset["file_name"])
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@bp.route("/api/files/<int:file_id>", methods=["DELETE"])
|
||||
@login_required
|
||||
def delete_file(file_id):
|
||||
conn = db()
|
||||
try:
|
||||
asset = one(conn, "SELECT * FROM file_assets WHERE id=?", (file_id,))
|
||||
if not asset:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
path = Path(asset["file_path"])
|
||||
if path.exists() and str(UPLOAD_DIR) in str(path.resolve()):
|
||||
path.unlink(missing_ok=True)
|
||||
_exec(conn, "DELETE FROM file_assets WHERE id=?", (file_id,))
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# ---------- health ----------
|
||||
|
||||
@bp.route("/api/health")
|
||||
def health():
|
||||
return jsonify({"ok": True, "service": "opc-manager"})
|
||||
193
deploy/README.md
Normal file
193
deploy/README.md
Normal file
@@ -0,0 +1,193 @@
|
||||
# OPC-Manager 自动化部署指南
|
||||
|
||||
## 架构
|
||||
|
||||
```
|
||||
开发者 push main → Gitea 仓库 (git.qiukai.me)
|
||||
↓
|
||||
Gitea Actions 触发
|
||||
↓
|
||||
Runner(跑在业务服务器 82.157.208.197 上)
|
||||
↓
|
||||
git clone → rsync 到 release 目录
|
||||
↓
|
||||
创建 venv → pip install → systemctl restart
|
||||
↓
|
||||
健康检查 → 切换 current 软链 → 清理旧版本
|
||||
```
|
||||
|
||||
## 服务器目录结构
|
||||
|
||||
```
|
||||
/opt/opc-manager/
|
||||
├── releases/
|
||||
│ ├── abc1234/ ← 本次发布(commit sha)
|
||||
│ ├── def5678/ ← 上次发布
|
||||
│ └── ... ← 保留最近 5 个
|
||||
├── shared/
|
||||
│ ├── .env ← 环境变量(不进 git,持久化)
|
||||
│ └── uploads/ ← 上传的文件(持久化,跨版本共享)
|
||||
└── current → releases/abc1234 ← 软链,指向当前生效版本
|
||||
```
|
||||
|
||||
## 一次性准备(在业务服务器上执行)
|
||||
|
||||
### 1. 安装 Gitea Actions Runner
|
||||
|
||||
```bash
|
||||
# 下载 act_runner
|
||||
cd /opt
|
||||
wget https://gitea.com/gitea/act_runner/releases/download/v0.2.11/act_runner-0.2.11-linux-amd64 -O act_runner
|
||||
chmod +x act_runner
|
||||
mv act_runner /usr/local/bin/
|
||||
|
||||
# 注册 runner(到 git.qiukai.me)
|
||||
# 先在 Gitea 网页:仓库设置 → Actions → Runners → New runner,获取 token
|
||||
act_runner register \
|
||||
--instance https://git.qiukai.me \
|
||||
--token <YOUR_RUNNER_TOKEN> \
|
||||
--name prod-deploy \
|
||||
--labels prod-deploy \
|
||||
--no-interactive
|
||||
|
||||
# 安装为系统服务
|
||||
act_runner daemon --config /etc/act_runner/config.yaml &
|
||||
# 或用 systemd:
|
||||
cat > /etc/systemd/system/act-runner.service <<'EOF'
|
||||
[Unit]
|
||||
Description=Gitea Actions Runner
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/local/bin/act_runner daemon
|
||||
Restart=on-failure
|
||||
Environment=HOME=/root
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now act-runner
|
||||
```
|
||||
|
||||
### 2. 创建部署目录结构
|
||||
|
||||
```bash
|
||||
mkdir -p /opt/opc-manager/{releases,shared/uploads}
|
||||
```
|
||||
|
||||
### 3. 创建 .env 文件
|
||||
|
||||
```bash
|
||||
cat > /opt/opc-manager/shared/.env <<'EOF'
|
||||
SECRET_KEY=改成一串随机字符串_至少32位
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_USER=opc
|
||||
DB_PASSWORD=opc123456
|
||||
DB_NAME=opc
|
||||
FLASK_DEBUG=false
|
||||
EOF
|
||||
|
||||
chmod 600 /opt/opc-manager/shared/.env
|
||||
```
|
||||
|
||||
### 4. 安装 systemd service
|
||||
|
||||
```bash
|
||||
# 从仓库的 deploy/opc-manager.service 复制
|
||||
cat > /etc/systemd/system/opc-manager.service <<'EOF'
|
||||
[Unit]
|
||||
Description=OPC Manager (Flask)
|
||||
After=network.target mysql.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=/opt/opc-manager/current
|
||||
ExecStart=/opt/opc-manager/current/.venv/bin/gunicorn --preload -w 4 -b 0.0.0.0:5177 backend.flask_app:app
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
EnvironmentFile=/opt/opc-manager/current/.env
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable opc-manager
|
||||
```
|
||||
|
||||
### 5. 配置 Gitea Secret
|
||||
|
||||
在 Gitea 网页操作:
|
||||
1. 进入仓库 `qiukai/opc-manager`
|
||||
2. 设置 → Actions → Secrets → New Secret
|
||||
3. Name: `DEPLOY_TOKEN`
|
||||
4. Value: 你的 Gitea Personal Access Token(需要有 repo 读权限)
|
||||
- 生成路径:头像 → 设置 → 应用 → 生成令牌
|
||||
|
||||
### 6. 首次手动部署
|
||||
|
||||
push 代码前,先手动跑一次确保目录结构正确:
|
||||
|
||||
```bash
|
||||
cd /opt/opc-manager
|
||||
git clone --depth 1 --branch main https://git.qiukai.me/qiukai/opc-manager.git /tmp/opc-init
|
||||
RELEASE_DIR=/opt/opc-manager/releases/initial
|
||||
mkdir -p "${RELEASE_DIR}"
|
||||
rsync -a --exclude='.git' --exclude='.env' --exclude='.venv' /tmp/opc-init/ "${RELEASE_DIR}/"
|
||||
ln -sfn /opt/opc-manager/shared/.env "${RELEASE_DIR}/.env"
|
||||
ln -sfn /opt/opc-manager/shared/uploads "${RELEASE_DIR}/data/uploads"
|
||||
cd "${RELEASE_DIR}"
|
||||
python3 -m venv .venv
|
||||
. .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
ln -sfn "${RELEASE_DIR}" /opt/opc-manager/current
|
||||
systemctl start opc-manager
|
||||
curl http://127.0.0.1:5177/api/health
|
||||
rm -rf /tmp/opc-init
|
||||
```
|
||||
|
||||
## 日常使用
|
||||
|
||||
### 发布新版本
|
||||
```bash
|
||||
# 本地
|
||||
git push origin main
|
||||
# 自动触发 Gitea Actions → 服务器自动部署
|
||||
```
|
||||
|
||||
### 查看部署状态
|
||||
```bash
|
||||
# 在 Gitea 网页:仓库 → Actions 查看部署日志
|
||||
# 或在服务器:
|
||||
systemctl status opc-manager
|
||||
ls -la /opt/opc-manager/current
|
||||
```
|
||||
|
||||
### 回滚
|
||||
```bash
|
||||
# 列出历史版本
|
||||
ls -t /opt/opc-manager/releases
|
||||
# 切换到上一个版本
|
||||
PREV=$(ls -t /opt/opc-manager/releases | sed -n '2p')
|
||||
ln -sfn "/opt/opc-manager/releases/${PREV}" /opt/opc-manager/current
|
||||
systemctl restart opc-manager
|
||||
```
|
||||
|
||||
## Nginx 反代(可选)
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name opc.yxcowork.vip;
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:5177;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
}
|
||||
}
|
||||
```
|
||||
14
deploy/opc-manager.service
Normal file
14
deploy/opc-manager.service
Normal file
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=OPC Manager (Flask)
|
||||
After=network.target mysql.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=/opt/opc-manager/current
|
||||
ExecStart=/opt/opc-manager/current/.venv/bin/gunicorn --preload -w 4 -b 0.0.0.0:5177 backend.flask_app:app
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
EnvironmentFile=/opt/opc-manager/current/.env
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
82
deploy/服务器配置任务提示词.md
Normal file
82
deploy/服务器配置任务提示词.md
Normal file
@@ -0,0 +1,82 @@
|
||||
# OPC-Manager 自动化部署配置任务
|
||||
|
||||
## 背景
|
||||
OPC-Manager 项目(Flask + MySQL,端口 5177)需要配置 Gitea Actions 自动化部署。参考 SalesManager 的模式:push 到 main 分支后自动部署到业务服务器。部署工作流文件已写好(`.gitea/workflows/deploy.yml`),需要在服务器上完成一次性准备。
|
||||
|
||||
## 服务器信息
|
||||
- 业务服务器:82.157.208.197(SSH 别名 `ssh business`)
|
||||
- Gitea 地址:https://git.qiukai.me
|
||||
- 仓库:qiukai/opc-manager
|
||||
- 服务端口:5177
|
||||
- MySQL:已安装(8.0.45,系统服务),数据库 `opc`,用户 `opc/opc123456`
|
||||
|
||||
## 需要完成的 5 个步骤
|
||||
|
||||
### 1. 安装 Gitea Actions Runner
|
||||
在业务服务器上安装 `act_runner` 并注册到 Gitea:
|
||||
- 下载地址:https://gitea.com/gitea/act_runner/releases/download/v0.2.11/act_runner-0.2.11-linux-amd64
|
||||
- 放到 `/usr/local/bin/act_runner`
|
||||
- 注册时 name=`prod-deploy`,labels=`prod-deploy`
|
||||
- 注册 token 需要到 Gitea 网页获取:仓库 qiukai/opc-manager → 设置 → Actions → Runners → New runner
|
||||
- 安装为 systemd 服务(`/etc/systemd/system/act-runner.service`),开机自启
|
||||
|
||||
### 2. 创建部署目录结构
|
||||
```bash
|
||||
mkdir -p /opt/opc-manager/{releases,shared/uploads}
|
||||
```
|
||||
|
||||
### 3. 创建 .env 文件
|
||||
在 `/opt/opc-manager/shared/.env` 创建环境变量文件:
|
||||
```
|
||||
SECRET_KEY=随机生成32位以上字符串
|
||||
DB_HOST=127.0.0.1
|
||||
DB_PORT=3306
|
||||
DB_USER=opc
|
||||
DB_PASSWORD=opc123456
|
||||
DB_NAME=opc
|
||||
FLASK_DEBUG=false
|
||||
```
|
||||
权限设为 600。
|
||||
|
||||
### 4. 安装 systemd service
|
||||
创建 `/etc/systemd/system/opc-manager.service`:
|
||||
```ini
|
||||
[Unit]
|
||||
Description=OPC Manager (Flask)
|
||||
After=network.target mysql.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
WorkingDirectory=/opt/opc-manager/current
|
||||
ExecStart=/opt/opc-manager/current/.venv/bin/gunicorn --preload -w 4 -b 0.0.0.0:5177 backend.flask_app:app
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
EnvironmentFile=/opt/opc-manager/current/.env
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
执行 `systemctl daemon-reload && systemctl enable opc-manager`(先不 start,等首次部署后自动启动)。
|
||||
|
||||
### 5. 配置 Gitea Secret
|
||||
在 Gitea 网页操作(需要用户在浏览器完成):
|
||||
- 进入仓库 qiukai/opc-manager → 设置 → Actions → Secrets → New Secret
|
||||
- Name: `DEPLOY_TOKEN`
|
||||
- Value: 用户的 Gitea Personal Access Token(需 repo 读权限)
|
||||
- 生成路径:头像 → 设置 → 应用 → 生成令牌
|
||||
|
||||
## 首次部署验证
|
||||
准备完成后,在本地执行一次 `git push origin main`,观察:
|
||||
1. Gitea 网页 Actions 页面是否有部署任务在运行
|
||||
2. 部署日志是否正常
|
||||
3. 部署完成后 `curl http://127.0.0.1:5177/api/health` 是否返回 `{"ok":true,"service":"opc-manager"}`
|
||||
4. `systemctl status opc-manager` 是否 active
|
||||
|
||||
## 参考文件
|
||||
项目的部署工作流在仓库的 `.gitea/workflows/deploy.yml`,systemd 模板在 `deploy/opc-manager.service`,完整说明在 `deploy/README.md`。
|
||||
|
||||
## 注意事项
|
||||
- Gitea Runner 的 token 需要用户在浏览器获取后告诉你,你无法自动获取
|
||||
- Gitea Secret (DEPLOY_TOKEN) 也需要用户在浏览器配置
|
||||
- 如果服务器没有 python3.11+,需要先安装(OPC-Manager 要求 Python 3.9+)
|
||||
- 确保服务器已安装 git、rsync、curl(一般都有)
|
||||
5
requirements.txt
Normal file
5
requirements.txt
Normal file
@@ -0,0 +1,5 @@
|
||||
flask==3.1.3
|
||||
mysql-connector-python==9.4.0
|
||||
python-dotenv==1.2.1
|
||||
werkzeug==3.1.8
|
||||
gunicorn==23.0.0
|
||||
763
static/app.js
763
static/app.js
@@ -1,748 +1,25 @@
|
||||
const state = {
|
||||
active: "home",
|
||||
data: null,
|
||||
tenant: "科普·无界",
|
||||
opFilter: "all",
|
||||
projectView: null,
|
||||
chart: null,
|
||||
chart2: null,
|
||||
productPlatform: "all",
|
||||
};
|
||||
// app.js — 入口文件(加载模块 + 初始化)
|
||||
|
||||
const money = (value) => `${Number(value || 0).toLocaleString("zh-CN")} 万`;
|
||||
const text = (value) => value === undefined || value === null || value === "" ? "—" : value;
|
||||
|
||||
async function api(path, options = {}) {
|
||||
const response = await fetch(path, {
|
||||
headers: options.body instanceof FormData ? undefined : { "Content-Type": "application/json" },
|
||||
...options,
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || "请求失败");
|
||||
return data;
|
||||
// 恢复上次的工作台和标签页
|
||||
const savedTenant = localStorage.getItem("opc-active-tenant");
|
||||
if (savedTenant) {
|
||||
state.tenant = savedTenant;
|
||||
const label = savedTenant.replace("·无界", "");
|
||||
document.querySelector("#workspaceTitle").textContent = label + " OPC 工作台";
|
||||
const tLabel = document.querySelector("#currentTenantLabel");
|
||||
if (tLabel) { tLabel.textContent = label || "工作台"; tLabel.title = savedTenant; }
|
||||
}
|
||||
const savedTab = localStorage.getItem("opc-active-tab");
|
||||
|
||||
function badge(value) {
|
||||
const val = String(value || "—");
|
||||
let cls = "badge-slate";
|
||||
if (["P0", "有风险", "已丢单", "已延期"].includes(val)) cls = "badge-red";
|
||||
if (["P1", "方案中", "方案已提交", "商务谈判", "待客户确认"].includes(val)) cls = "badge-amber";
|
||||
if (["已签约", "已上线", "已完成", "已归档"].includes(val)) cls = "badge-green";
|
||||
if (["execution", "已签约执行项目"].includes(val)) cls = "badge-blue";
|
||||
return `<span class="badge ${cls}">${val === "execution" ? "已签约执行项目" : val === "opportunity" ? "业务机会项目" : val}</span>`;
|
||||
}
|
||||
|
||||
function card(content, cls = "") {
|
||||
return `<section class="card ${cls}">${content}</section>`;
|
||||
}
|
||||
|
||||
function renderTable(headers, rows, rowClicks) {
|
||||
const trAttrs = (rowClicks || []).map((rc) => rc ? `onclick="openDrawer('${rc.resource}', ${rc.id})" class="clickable-row"` : "");
|
||||
return card(`
|
||||
<div class="overflow-x-auto">
|
||||
<table>
|
||||
<thead><tr>${headers.map((h) => `<th>${h}</th>`).join("")}</tr></thead>
|
||||
<tbody>${rows.map((row, i) => `<tr ${trAttrs[i] || ""}>${row.map((c) => `<td>${c}</td>`).join("")}</tr>`).join("")}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
async function load() {
|
||||
state.data = await api(`/api/bootstrap?tenant=${encodeURIComponent(state.tenant)}`);
|
||||
render();
|
||||
}
|
||||
|
||||
function switchTab(tab) {
|
||||
state.active = tab;
|
||||
document.querySelectorAll("#tabs button").forEach((btn) => btn.classList.toggle("active", btn.dataset.tab === tab));
|
||||
document.querySelectorAll(".panel").forEach((panel) => panel.classList.toggle("active", panel.id === tab));
|
||||
render();
|
||||
}
|
||||
|
||||
function render() {
|
||||
if (!state.data) return;
|
||||
renderHome();
|
||||
renderProjects();
|
||||
renderProposals();
|
||||
renderProducts();
|
||||
renderFinance();
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
// Decode and render rich HTML content in followup records
|
||||
drawer.querySelectorAll(".rich-content").forEach((el) => {
|
||||
const html = el.dataset.html;
|
||||
if (html) el.innerHTML = decodeURIComponent(html);
|
||||
});
|
||||
// Initialize Squire editor
|
||||
const squireDiv = drawer.querySelector(".squire-editor");
|
||||
if (squireDiv && window.Squire) {
|
||||
const id = squireDiv.id;
|
||||
if (window.squireInstances[id]) window.squireInstances[id].destroy();
|
||||
const sq = new Squire(squireDiv, { blockTag: "P" });
|
||||
sq.addEventListener("input", () => {
|
||||
const form = squireDiv.closest("form");
|
||||
const btn = form.querySelector(".comment-submit");
|
||||
});
|
||||
window.squireInstances[id] = sq;
|
||||
// Handle placeholder
|
||||
squireDiv.addEventListener("focus", () => squireDiv.classList.add("focused"));
|
||||
squireDiv.addEventListener("blur", () => {
|
||||
if (!squireDiv.textContent.trim()) squireDiv.classList.remove("focused");
|
||||
});
|
||||
// 初始化
|
||||
applyUserTenants();
|
||||
updateSidebarTabs();
|
||||
load().then(() => {
|
||||
if (state.tenant === "总工作台") {
|
||||
switchTab("home");
|
||||
} else if (savedTab && savedTab !== "home") {
|
||||
switchTab(savedTab);
|
||||
}
|
||||
}
|
||||
|
||||
function renderHome() {
|
||||
const { summary, financeMonthly } = state.data;
|
||||
const m = summary.metrics;
|
||||
const rows1 = [
|
||||
["年度累计签约", money(m.signed_annual || m.signed_amount)],
|
||||
["Q2 累计签约", money(m.signed_q2 || 0)],
|
||||
["本月新增签约", money(m.signed_month || 0)],
|
||||
["合同流程中", money(m.pipeline_amount)],
|
||||
];
|
||||
const rows2 = [
|
||||
["年度累计确收", money(m.revenue_annual)],
|
||||
["Q2 累计确收", money(m.revenue_q2)],
|
||||
["本月新增确收", money(m.monthly_revenue)],
|
||||
["已签约未执行", money(m.signed_not_executed)],
|
||||
];
|
||||
const rows3 = [
|
||||
["年度累计毛利", money(m.gross_annual)],
|
||||
["Q2 累计毛利", money(m.gross_q2)],
|
||||
["本月新增毛利", money(m.monthly_net_profit)],
|
||||
["合同毛利率", m.revenue_annual ? Math.round(m.gross_annual / m.revenue_annual * 100) + "%" : "—"],
|
||||
];
|
||||
const tblCard = (title, rows) => card(`<h3 class="text-sm font-bold text-slate-700 mb-3">${title}</h3><table class="w-full text-sm"><tbody>${rows.map(([label, value]) => `<tr class="border-b border-slate-100 last:border-0"><td class="py-2 pr-4 text-slate-500">${label}</td><td class="py-2 text-right font-semibold text-slate-800">${value}</td></tr>`).join("")}</tbody></table>`, "p-4");
|
||||
document.querySelector("#home").innerHTML = `
|
||||
<div class="grid gap-5">
|
||||
<div class="grid grid-cols-6 gap-3">
|
||||
${[
|
||||
["重点项目", m.total_projects, "projects"],
|
||||
["业务方案", m.total_proposals, "proposals"],
|
||||
["产品版本", m.total_products, "products"],
|
||||
["本月确收", money(m.monthly_revenue), "finance"],
|
||||
["本月毛利", money(m.monthly_gross || m.monthly_net_profit), "finance"],
|
||||
["本月净利", money(m.monthly_net_profit), "finance"],
|
||||
].map(([label, value, tab]) => `<button class="metric-card" onclick="switchTab('${tab}')"><span class="flex items-center gap-2 text-xs text-slate-500"><i data-lucide="gauge"></i>${label}</span><strong class="mt-2 block text-2xl">${value}</strong></button>`).join("")}
|
||||
</div>
|
||||
<div class="grid grid-cols-3 gap-5">${tblCard("合同金额", rows1)}${tblCard("确收金额", rows2)}${tblCard("确收毛利", rows3)}</div>
|
||||
<div class="grid grid-cols-2 gap-5">
|
||||
${card(`<div class="mb-3 flex items-center justify-between"><h2 class="text-sm font-bold text-slate-600">财务趋势</h2>${badge("YYYY-MM")}</div><div style="position:relative;height:140px"><canvas id="financeChart"></canvas></div>`, "p-4")}
|
||||
${card(`<h2 class="text-lg font-bold">风险提醒</h2><div class="mt-3 grid gap-2">${(summary.risks.length ? summary.risks : [{ title: "暂无高风险", content: "当前无明确阻塞,按周更新即可。" }]).map((r) => `<div class="rounded-md border border-amber-200 bg-amber-50 p-3"><p class="font-bold text-amber-900">${r.title}</p><p class="mt-1 text-sm text-amber-800 break-words">${r.content}</p></div>`).join("")}</div>`, "p-5")}
|
||||
</div>
|
||||
${card(`<h2 class="text-lg font-bold">近期动态</h2><div class="mt-4 grid gap-2">${summary.recent.map((r) => `<div class="flex justify-between rounded-md bg-slate-50 px-3 py-2 text-sm"><span class="break-words">${r.content}</span><span class="text-slate-500">${r.followed_at}</span></div>`).join("")}</div>`, "p-5")}
|
||||
</div>
|
||||
`;
|
||||
renderChart(financeMonthly);
|
||||
}
|
||||
|
||||
function renderChart(data) {
|
||||
const canvas = document.querySelector("#financeChart");
|
||||
if (!canvas || !window.Chart) return;
|
||||
if (state.chart) state.chart.destroy();
|
||||
state.chart = new Chart(canvas, {
|
||||
type: "line",
|
||||
data: {
|
||||
labels: data.map((x) => x.month),
|
||||
datasets: [
|
||||
{ label: "收入", data: data.map((x) => x.revenue), borderColor: "#2563eb", tension: 0.3 },
|
||||
{ label: "毛利", data: data.map((x) => x.gross_profit), borderColor: "#059669", tension: 0.3 },
|
||||
{ label: "成本/费用", data: data.map((x) => x.cost_expense), borderColor: "#d97706", tension: 0.3 },
|
||||
{ label: "净利", data: data.map((x) => x.net_profit), borderColor: "#7c3aed", tension: 0.3 },
|
||||
],
|
||||
},
|
||||
options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: "bottom", labels: { boxWidth: 12, font: { size: 11 } } } }, scales: { x: { ticks: { font: { size: 11 } }, grid: { display: false } }, y: { ticks: { font: { size: 11 } } } } },
|
||||
});
|
||||
}
|
||||
|
||||
function formHtml(fields, button) {
|
||||
return `<form class="inline-form flex flex-wrap items-end gap-3" onsubmit="${button.handler}(event)">
|
||||
${fields.map((f) => `<label class="grid gap-1 text-sm"><span class="font-bold text-slate-600">${f.label}</span>${f.input}</label>`).join("")}
|
||||
<button class="btn btn-primary" type="submit">${button.text}</button>
|
||||
</form>`;
|
||||
}
|
||||
|
||||
async function createResource(event, resource) {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const data = Object.fromEntries(new FormData(form).entries());
|
||||
try {
|
||||
await api(`/api/${resource}`, { method: "POST", body: JSON.stringify({ data }) });
|
||||
form.reset();
|
||||
await load();
|
||||
} catch (error) {
|
||||
alert("创建失败:" + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
window.createSales = (event) => createResource(event, "sales");
|
||||
window.createProposal = (event) => createResource(event, "proposals");
|
||||
window.createOperation = (event) => createResource(event, "operations");
|
||||
window.createProduct = (event) => createResource(event, "products");
|
||||
|
||||
window.openTaskForm = (projectId, taskId) => {
|
||||
const drawer = document.querySelector(`#task-drawer-${projectId}`);
|
||||
const titleEl = drawer.querySelector(".task-drawer-title");
|
||||
if (taskId === null) {
|
||||
document.querySelector(`#task-id-${projectId}`).value = "";
|
||||
document.querySelector(`#task-name-${projectId}`).value = "";
|
||||
document.querySelector(`#task-phase-${projectId}`).value = "商务洽谈";
|
||||
document.querySelector(`#task-owner-${projectId}`).value = "";
|
||||
document.querySelector(`#task-due-${projectId}`).value = "";
|
||||
document.querySelector(`#task-notes-${projectId}`).value = "";
|
||||
document.querySelector(`#task-blockers-${projectId}`).value = "";
|
||||
document.querySelector(`#task-submit-btn-${projectId}`).textContent = "确认新增";
|
||||
if (titleEl) titleEl.textContent = "新增任务";
|
||||
} else {
|
||||
const task = (state.data.tasks || []).find((t) => t.id === taskId);
|
||||
if (!task) return;
|
||||
document.querySelector(`#task-id-${projectId}`).value = task.id;
|
||||
document.querySelector(`#task-name-${projectId}`).value = task.task || "";
|
||||
document.querySelector(`#task-phase-${projectId}`).value = task.phase || "商务洽谈";
|
||||
document.querySelector(`#task-owner-${projectId}`).value = task.owner || "";
|
||||
document.querySelector(`#task-due-${projectId}`).value = task.due_date || "";
|
||||
document.querySelector(`#task-notes-${projectId}`).value = task.notes || "";
|
||||
document.querySelector(`#task-blockers-${projectId}`).value = task.blockers || "";
|
||||
document.querySelector(`#task-submit-btn-${projectId}`).textContent = "保存修改";
|
||||
if (titleEl) titleEl.textContent = "编辑任务";
|
||||
}
|
||||
drawer.classList.add("open");
|
||||
};
|
||||
window.closeTaskDrawer = (projectId) => {
|
||||
document.querySelector(`#task-drawer-${projectId}`).classList.remove("open");
|
||||
};
|
||||
|
||||
window.submitTaskForm = async (event, projectId) => {
|
||||
event.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(event.currentTarget).entries());
|
||||
data.project_id = Number(projectId);
|
||||
const taskId = data.task_id;
|
||||
delete data.task_id;
|
||||
try {
|
||||
if (taskId) {
|
||||
await api(`/api/tasks/${taskId}`, { method: "PUT", body: JSON.stringify({ data }) });
|
||||
} else {
|
||||
await api("/api/tasks", { method: "POST", body: JSON.stringify({ data }) });
|
||||
}
|
||||
await load();
|
||||
} catch (error) {
|
||||
alert("保存失败:" + error.message);
|
||||
}
|
||||
};
|
||||
window.createFinance = async (event) => {
|
||||
event.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(event.currentTarget).entries());
|
||||
// Map form: month(date)→month(YYYY-MM), category→category, amount, tenant
|
||||
data.month = data.month.substring(0, 7);
|
||||
data.project_name = state.tenant;
|
||||
data.tenant = state.tenant;
|
||||
data.record_type = "revenue"; // default, will be adjusted by category
|
||||
try {
|
||||
await api("/api/finance", { method: "POST", body: JSON.stringify({ data }) });
|
||||
await load();
|
||||
} catch (error) {
|
||||
alert("新增失败:" + error.message);
|
||||
}
|
||||
};
|
||||
window.switchTab = switchTab;
|
||||
window.switchTenant = (tenant) => {
|
||||
state.tenant = tenant;
|
||||
state.projectView = null;
|
||||
load();
|
||||
};
|
||||
|
||||
function renderProjects() {
|
||||
// 二级页面:项目任务详情
|
||||
if (state.projectView) {
|
||||
return renderProjectTasks(state.projectView);
|
||||
}
|
||||
const items = state.data.operations;
|
||||
const rows = items.map((x) => [
|
||||
`<strong>${x.project_name}</strong>`,
|
||||
text(x.customer_need || x.notes),
|
||||
badge(x.current_stage || x.project_status),
|
||||
x.expected_contract_amount ? money(x.expected_contract_amount) : "—",
|
||||
text(x.owner || "—"),
|
||||
`<button class="btn btn-ghost btn-sm text-blue-600" onclick="event.stopPropagation(); state.projectView=${x.id}; renderProjects()"><i data-lucide="eye"></i>查看</button>`
|
||||
]);
|
||||
document.querySelector("#projects").innerHTML = `<div class="grid gap-4">
|
||||
<div id="project-form">
|
||||
${card(formHtml([
|
||||
{ label: "项目名称", input: `<input name="project_name" required>` },
|
||||
{ label: "当前阶段", input: `<select name="current_stage"><option>商务洽谈</option><option>系统上线</option><option>团队分工</option><option>项目交付</option><option>上线推广</option><option>结项验收</option></select>` },
|
||||
{ label: "项目金额", input: `<input name="expected_contract_amount" type="number" step="0.01" placeholder="万元">` },
|
||||
{ label: "负责人", input: `<input name="owner">` },
|
||||
], { handler: "createOperation", text: "新增项目" }), "p-4")}
|
||||
</div>
|
||||
${renderTable(["项目", "项目说明", "当前阶段", "项目金额", "负责人", "进展"], rows, items.map((x) => ({ resource: "operations", id: x.id })))}
|
||||
</div>`;
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
|
||||
function renderProjectTasks(projectId) {
|
||||
const project = state.data.operations.find((x) => x.id === projectId);
|
||||
if (!project) { state.projectView = null; renderProjects(); return; }
|
||||
const tasks = (state.data.tasks || []).filter((t) => t.project_id === projectId);
|
||||
const phases = ["商务洽谈", "系统上线", "团队分工", "项目交付", "上线推广", "结项验收"];
|
||||
document.querySelector("#projects").innerHTML = `<div class="grid gap-4">
|
||||
<div class="flex items-center justify-between px-5">
|
||||
<button class="btn btn-ghost btn-sm" onclick="state.projectView=null;renderProjects()"><i data-lucide="arrow-left"></i>返回项目列表</button>
|
||||
<div class="flex items-center gap-3">
|
||||
<span class="text-sm font-semibold text-slate-700">${project.project_name}</span>
|
||||
<button class="btn btn-primary btn-sm" onclick="openTaskForm(${projectId}, null)"><i data-lucide="plus"></i>新增任务</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="task-page-wrap">
|
||||
<div class="task-body">
|
||||
${phases.map((phase) => {
|
||||
const pt = tasks.filter((t) => t.phase === phase);
|
||||
if (!pt.length) return "";
|
||||
return `<div class="task-group"><div class="task-group-hd"><span class="task-group-icon"><i data-lucide="layers"></i></span><span class="task-group-label">${phase}</span><span class="task-group-n">${pt.length}</span></div><div class="task-group-list" data-phase="${phase}" ondrop="handleTaskDrop(event, ${projectId}, '${phase}')" ondragover="event.preventDefault(); event.currentTarget.classList.add('drag-over')" ondragleave="event.currentTarget.classList.remove('drag-over')">${pt.map((t) => `<div class="task-row ${t.status === 'done' ? 'task-done' : ''}" data-id="${t.id}" draggable="true" ondragstart="handleTaskDragStart(event, ${t.id})" ondragend="event.currentTarget.classList.remove('dragging')"><span class="task-dot" onclick="event.stopPropagation(); toggleTaskDone(${t.id}, ${projectId})"><i data-lucide="${t.status === 'done' ? 'check-circle' : 'circle'}"></i></span><div class="task-main" onclick="openTaskForm(${projectId}, ${t.id})"><span class="task-name">${t.task}</span>${t.notes ? `<span class="task-desc">${t.notes}</span>` : ""}${t.blockers ? `<span class="task-blocker">⚠ ${t.blockers}</span>` : ""}</div><span class="task-col">${t.owner || ""}</span><span class="task-col-badge">${t.due_date || ""}</span></div>`).join("")}</div></div>`;
|
||||
}).join("")}
|
||||
</div>
|
||||
<div id="task-drawer-${projectId}" class="task-drawer">
|
||||
<div class="task-drawer-hd"><span class="task-drawer-title">编辑任务</span><div class="flex items-center gap-2"><button type="button" class="btn btn-ghost btn-sm text-red-600 hover:bg-red-50" onclick="deleteTask(${projectId})"><i data-lucide="trash-2"></i>删除</button><button class="task-close" onclick="closeTaskDrawer(${projectId})"><i data-lucide="x"></i></button></div></div>
|
||||
<form class="task-drawer-form" onsubmit="submitTaskForm(event, ${projectId})">
|
||||
<input type="hidden" name="task_id" id="task-id-${projectId}" value="">
|
||||
<label class="task-field"><span>任务名称</span><input name="task" required id="task-name-${projectId}"></label>
|
||||
<label class="task-field"><span>任务阶段</span><select name="phase" id="task-phase-${projectId}">${phases.map((p) => `<option>${p}</option>`).join("")}</select></label>
|
||||
<label class="task-field"><span>负责人</span><input name="owner" id="task-owner-${projectId}"></label>
|
||||
<label class="task-field"><span>截止时间</span><input name="due_date" type="date" id="task-due-${projectId}"></label>
|
||||
<label class="task-field"><span>任务说明</span><textarea name="notes" rows="3" id="task-notes-${projectId}"></textarea></label>
|
||||
<label class="task-field"><span>卡点&备注</span><textarea name="blockers" rows="2" id="task-blockers-${projectId}" placeholder="风险卡点、依赖项等"></textarea></label>
|
||||
<div class="flex justify-end gap-2 mt-4 pt-3 border-t border-slate-100">
|
||||
<button type="button" class="btn btn-ghost btn-sm" onclick="closeTaskDrawer(${projectId})">取消</button>
|
||||
<button type="submit" class="btn btn-primary btn-sm" id="task-submit-btn-${projectId}">确认新增</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
|
||||
function showTaskModal(projectId) {
|
||||
const project = state.data.operations.find((x) => x.id === projectId);
|
||||
const tasks = (state.data.tasks || []).filter((t) => t.project_id === projectId);
|
||||
const phases = ["商务洽谈", "系统上线", "团队分工", "项目交付", "上线推广", "结项验收"];
|
||||
document.querySelector("#taskModal").innerHTML = `<div class="task-overlay" onclick="closeTaskModal()"><div class="task-panel" onclick="event.stopPropagation()"><div class="task-header"><h2 class="task-title">${project.project_name} · 任务清单</h2><div class="flex items-center gap-3"><button class="btn btn-primary btn-sm" onclick="event.stopPropagation(); openTaskForm(${projectId}, null)"><i data-lucide="plus"></i>新增任务</button><button class="task-close" onclick="closeTaskModal()"><i data-lucide="x"></i></button></div></div><div class="task-body-wrap">
|
||||
<div class="task-body">
|
||||
${phases.map((phase) => {
|
||||
const pt = tasks.filter((t) => t.phase === phase);
|
||||
if (!pt.length) return "";
|
||||
return `<div class="task-group"><div class="task-group-hd"><span class="task-group-icon"><i data-lucide="layers"></i></span><span class="task-group-label">${phase}</span><span class="task-group-n">${pt.length}</span></div><div class="task-group-list">${pt.map((t) => `<div class="task-row" data-id="${t.id}" onclick="event.stopPropagation(); openTaskForm(${projectId}, ${t.id})"><span class="task-dot"><i data-lucide="${t.status === 'done' ? 'check-circle' : 'circle'}"></i></span><div class="task-main"><span class="task-name">${t.task}</span>${t.notes ? `<span class="task-desc">${t.notes}</span>` : ""}${t.blockers ? `<span class="task-blocker">⚠ ${t.blockers}</span>` : ""}</div><span class="task-col">${t.owner || ""}</span><span class="task-col-badge">${t.due_date || ""}</span></div>`).join("")}</div></div>`;
|
||||
}).join("")}
|
||||
</div>
|
||||
<div id="task-drawer-${projectId}" class="task-drawer">
|
||||
<div class="task-drawer-hd"><span class="task-drawer-title">编辑任务</span><button class="task-close" onclick="closeTaskDrawer(${projectId})"><i data-lucide="x"></i></button></div>
|
||||
<form class="task-drawer-form" onsubmit="submitTaskForm(event, ${projectId})">
|
||||
<input type="hidden" name="task_id" id="task-id-${projectId}" value="">
|
||||
<label class="task-field"><span>任务名称</span><input name="task" required id="task-name-${projectId}"></label>
|
||||
<label class="task-field"><span>任务阶段</span><select name="phase" id="task-phase-${projectId}">${phases.map((p) => `<option>${p}</option>`).join("")}</select></label>
|
||||
<label class="task-field"><span>负责人</span><input name="owner" id="task-owner-${projectId}"></label>
|
||||
<label class="task-field"><span>截止时间</span><input name="due_date" type="date" id="task-due-${projectId}"></label>
|
||||
<label class="task-field"><span>任务说明</span><textarea name="notes" rows="3" id="task-notes-${projectId}"></textarea></label>
|
||||
<label class="task-field"><span>卡点&备注</span><textarea name="blockers" rows="2" id="task-blockers-${projectId}" placeholder="风险卡点、依赖项等"></textarea></label>
|
||||
<div class="flex justify-end gap-2 mt-4 pt-3 border-t border-slate-100">
|
||||
<button type="button" class="btn btn-ghost btn-sm" onclick="closeTaskDrawer(${projectId})">取消</button>
|
||||
<button type="submit" class="btn btn-primary btn-sm" id="task-submit-btn-${projectId}">确认新增</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div></div></div>`;
|
||||
document.querySelector("#taskModal").classList.add("active");
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
window.closeTaskModal = () => {
|
||||
document.querySelector("#taskModal").classList.remove("active");
|
||||
document.querySelector("#taskModal").innerHTML = "";
|
||||
};
|
||||
|
||||
function renderProposals() {
|
||||
const proposalRows = state.data.proposals.map((p) => [p.customer_or_project_name, p.version, badge(p.status), p.files.length + " 个"]);
|
||||
const proposalClicks = state.data.proposals.map((p) => ({ resource: "proposals", id: p.id }));
|
||||
document.querySelector("#proposals").innerHTML = `<div class="grid gap-4">
|
||||
${card(formHtml([
|
||||
{ label: "客户/项目", input: `<input name="customer_or_project_name" required placeholder="如:信达生物">` },
|
||||
{ label: "版本号", input: `<input name="version" required placeholder="v1.0">` },
|
||||
{ label: "状态", input: `<select name="status"><option>草稿</option><option>内部评审</option><option selected>已提交客户</option><option>客户反馈中</option><option>已确认</option><option>已归档</option></select>` },
|
||||
], { handler: "createProposal", text: "新增版本" }), "p-4")}
|
||||
${renderTable(["客户/项目", "版本号", "状态", "文件数"], proposalRows, proposalClicks)}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function fileGroup(module, ownerId, version, category, files) {
|
||||
return `<div class="rounded-md border border-slate-200 px-3 py-2">
|
||||
<div class="flex items-center justify-between gap-3"><p class="text-[13px] font-semibold text-slate-800">${category}</p><label class="inline-flex cursor-pointer items-center gap-1 rounded-md border border-slate-200 px-2 py-1 text-[12px] font-medium text-slate-600 hover:bg-slate-50"><i data-lucide="upload"></i>上传<input class="hidden" type="file" onchange="uploadFile(event,'${module}',${ownerId},'${version}','${category}')"></label></div>
|
||||
<div class="mt-2 grid gap-1.5">${files.length ? files.map(fileItem).join("") : `<p class="text-[12px] text-slate-400">暂无文件</p>`}</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function fileItem(file) {
|
||||
return `<div class="flex items-center justify-between gap-2 rounded-md bg-slate-50 px-2 py-1.5 text-[13px]"><div class="min-w-0 flex-1"><p class="truncate font-medium text-slate-800">${file.file_name}</p><div class="mt-0.5 flex gap-3"><a class="file-link inline-flex items-center gap-1" target="_blank" href="/api/files/${file.id}/content?inline=true"><i data-lucide="eye"></i>预览</a><a class="file-link inline-flex items-center gap-1 text-slate-600" href="/api/files/${file.id}/content?inline=false"><i data-lucide="download"></i>下载</a></div></div><button class="btn btn-ghost btn-sm text-red-600" onclick="deleteFile(${file.id})" title="删除"><i data-lucide="trash-2"></i></button></div>`;
|
||||
}
|
||||
|
||||
window.deleteFile = async (fileId) => {
|
||||
if (!confirm("确认删除此文件?")) return;
|
||||
await api(`/api/files/${fileId}`, { method: "DELETE" });
|
||||
await load();
|
||||
closeDrawer();
|
||||
};
|
||||
|
||||
window.uploadFile = async (event, module, ownerId, version, category) => {
|
||||
const file = event.target.files[0];
|
||||
if (!file) return;
|
||||
const form = new FormData();
|
||||
form.append("module", module);
|
||||
form.append("owner_id", ownerId);
|
||||
form.append("owner_version", version);
|
||||
form.append("file_category", category);
|
||||
form.append("file", file);
|
||||
await api("/api/files/upload", { method: "POST", body: form });
|
||||
await load();
|
||||
};
|
||||
|
||||
function renderProducts() {
|
||||
const items = state.productPlatform === "all" ? state.data.products : state.data.products.filter((x) => (x.platform || "") === state.productPlatform);
|
||||
document.querySelector("#products").innerHTML = `<div class="grid gap-4">
|
||||
${card(formHtml([
|
||||
{ label: "产品名称", input: `<input name="product_name" required>` },
|
||||
{ label: "版本号", input: `<input name="version" required>` },
|
||||
{ label: "平台", input: `<select name="platform"><option value="">—</option><option>真研平台</option><option>科普平台</option><option>关爱平台</option></select>` },
|
||||
{ label: "上线日期", input: `<input name="launch_date" placeholder="2026-Q3">` },
|
||||
{ label: "状态", input: `<select name="status"><option>规划中</option><option>设计中</option><option>开发中</option><option>测试中</option><option>已上线</option><option>已延期</option><option>已取消</option></select>` },
|
||||
], { handler: "createProduct", text: "新增版本" }), "p-4")}
|
||||
<div class="flex gap-2">${[["all","全部"],["真研平台","真研"],["科普平台","科普"],["关爱平台","关爱"]].map(([k,v]) => `<button class="btn ${state.productPlatform === k ? "btn-primary" : "btn-ghost"}" onclick="state.productPlatform='${k}'; renderProducts()">${v}</button>`).join("")}</div>
|
||||
${renderTable(["产品名称", "版本号", "版本目标", "核心功能", "平台", "上线日期", "状态"], items.map((p) => [p.product_name, p.version, text(p.version_goal), text(p.feature_list), text(p.platform), text(p.launch_date), badge(p.status)]), items.map((p) => ({ resource: "products", id: p.id })))}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function renderFinance() {
|
||||
const rows = state.data.finance.map((x) => [x.month, x.category, money(x.amount), text(x.notes)]);
|
||||
document.querySelector("#finance").innerHTML = `<div class="grid gap-4">
|
||||
${card(`<div class="flex items-center justify-between cursor-pointer" onclick="toggleFinanceChart()"><h2 class="text-lg font-bold text-slate-700">收入、毛利、成本/费用、净利月度曲线</h2><i data-lucide="chevron-down" class="transition-transform rotate-90" id="financeChartIcon"></i></div><div id="financeChartWrap" class="hidden mt-4"><div style="position:relative;height:300px"><canvas id="financeChart2"></canvas></div></div>`, "p-5")}
|
||||
${card(formHtml([
|
||||
{ label: "日期", input: `<input name="month" type="date" required>` },
|
||||
{ label: "类型", input: `<select name="category"><option>签单</option><option>确认收入</option><option>人力成本</option><option>费用</option><option>外部采购</option></select>` },
|
||||
{ label: "金额/万", input: `<input name="amount" type="number" step="0.01" required>` },
|
||||
{ label: "费用说明", input: `<input name="notes" placeholder="摘要说明">` },
|
||||
], { handler: "createFinance", text: "新增明细" }), "p-4")}
|
||||
${card(`<h3 class="font-bold text-slate-700 mb-3">明细列表 <span class="text-slate-400 font-normal">(${state.data.finance.length})</span></h3>${renderTable(["日期", "类型", "金额", "备注"], rows)}`, "p-4")}
|
||||
</div>`;
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
window.toggleFinanceChart = () => {
|
||||
const wrap = document.querySelector("#financeChartWrap");
|
||||
const icon = document.querySelector("#financeChartIcon");
|
||||
if (!wrap) return;
|
||||
wrap.classList.toggle("hidden");
|
||||
icon.classList.toggle("rotate-90");
|
||||
if (!wrap.classList.contains("hidden") && !state.chart2) renderFinanceChart();
|
||||
};
|
||||
function renderFinanceChart() {
|
||||
const { financeMonthly } = state.data;
|
||||
const canvas = document.querySelector("#financeChart2");
|
||||
if (!canvas || !window.Chart) return;
|
||||
if (state.chart2) state.chart2.destroy();
|
||||
state.chart2 = new Chart(canvas, {
|
||||
type: "line",
|
||||
data: {
|
||||
labels: financeMonthly.map((x) => x.month),
|
||||
datasets: [
|
||||
{ label: "确认收入", data: financeMonthly.map((x) => x.revenue), borderColor: "#2563eb", tension: 0.3 },
|
||||
{ label: "人力成本", data: financeMonthly.map((x) => x.labor), borderColor: "#ef4444", tension: 0.3 },
|
||||
{ label: "费用", data: financeMonthly.map((x) => x.expense), borderColor: "#d97706", tension: 0.3 },
|
||||
{ label: "外部采购", data: financeMonthly.map((x) => x.purchase), borderColor: "#8b5cf6", tension: 0.3 },
|
||||
{ label: "月度净利", data: financeMonthly.map((x) => x.net_profit), borderColor: "#059669", tension: 0.3, borderDash: [5,3] },
|
||||
],
|
||||
},
|
||||
options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: "bottom", labels: { boxWidth: 12, font: { size: 11 } } } }, scales: { x: { ticks: { font: { size: 11 } }, grid: { display: false } }, y: { ticks: { font: { size: 11 } } } } },
|
||||
});
|
||||
}
|
||||
|
||||
function renderChartOn(id, data) {
|
||||
const canvas = document.querySelector(`#${id}`);
|
||||
if (!canvas || !window.Chart) return;
|
||||
if (state.chart2) state.chart2.destroy();
|
||||
state.chart2 = new Chart(canvas, {
|
||||
type: "line",
|
||||
data: {
|
||||
labels: data.map((x) => x.month),
|
||||
datasets: [
|
||||
{ label: "收入", data: data.map((x) => x.revenue), borderColor: "#2563eb", tension: 0.3 },
|
||||
{ label: "毛利", data: data.map((x) => x.gross_profit), borderColor: "#059669", tension: 0.3 },
|
||||
{ label: "成本/费用", data: data.map((x) => x.cost_expense), borderColor: "#d97706", tension: 0.3 },
|
||||
{ label: "净利", data: data.map((x) => x.net_profit), borderColor: "#7c3aed", tension: 0.3 },
|
||||
],
|
||||
},
|
||||
options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: "bottom", labels: { boxWidth: 12, font: { size: 11 } } } }, scales: { x: { ticks: { font: { size: 11 } }, grid: { display: false } }, y: { ticks: { font: { size: 11 } } } } },
|
||||
});
|
||||
}
|
||||
|
||||
function drawerField(icon, label, name, value, multiline = false, customControl = null) {
|
||||
const initialValue = text(value);
|
||||
const control = customControl
|
||||
? customControl
|
||||
: multiline
|
||||
? `<textarea name="${name}" rows="2" class="drawer-value drawer-textarea" data-original="${initialValue}">${initialValue}</textarea>`
|
||||
: `<input name="${name}" value="${initialValue}" class="drawer-value" data-original="${initialValue}">`;
|
||||
return `<div class="drawer-field">
|
||||
<div class="drawer-field-label"><i data-lucide="${icon}"></i><span>${label}</span></div>
|
||||
<div class="drawer-field-control">${control}</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function openDrawer(resource, id) {
|
||||
const list = resource === "sales" ? state.data.sales : resource === "operations" ? state.data.operations : resource === "proposals" ? state.data.proposals : state.data.products;
|
||||
const item = list.find((x) => x.id === id);
|
||||
const drawer = document.querySelector("#drawer");
|
||||
const fields = resource === "sales"
|
||||
? [["target_customer","业务机会"],["priority","优先级"],["status","状态"]]
|
||||
: resource === "operations"
|
||||
? [["project_name","项目名称"],["owner","负责人"],["expected_sign_date","截止时间"],["expected_contract_amount","金额"],["notes","项目说明"]]
|
||||
: resource === "proposals"
|
||||
? [["customer_or_project_name","客户/项目"],["version","版本号"],["description","版本说明"],["created_date","创建日期"],["status","状态"]]
|
||||
: [["product_name","产品名称"],["version","版本号"],["version_goal","版本目标"],["feature_list","核心功能清单"],["platform","平台"],["launch_date","上线日期"],["status","当前状态"],["notes","备注"]];
|
||||
const fieldIcons = {
|
||||
target_customer: "user", priority: "flag", status: "circle-dot",
|
||||
project_name: "briefcase-business", project_version: "git-branch", project_status: "circle-dot", current_stage: "map-pin",
|
||||
owner: "user", customer_need: "file-text", expected_contract_amount: "banknote", expected_sign_date: "calendar",
|
||||
sign_probability: "percent", sop_stage: "list-checks", execution_progress: "activity",
|
||||
current_deliverable: "package", risks: "alert-triangle", next_action: "arrow-right",
|
||||
product_name: "box", version: "tag", version_goal: "target", feature_list: "list", platform: "layers",
|
||||
launch_date: "calendar", notes: "sticky-note"
|
||||
};
|
||||
const multilineFields = ["customer_need", "current_deliverable", "risks", "next_action", "version_goal", "feature_list", "notes"];
|
||||
const followupTarget = resource === "sales" ? "sales" : resource === "proposals" ? "proposal" : resource === "operations" ? "operation" : resource === "products" ? "product" : "";
|
||||
const title = item.target_customer || item.project_name || item.customer_or_project_name || item.product_name;
|
||||
drawer.innerHTML = `<div class="drawer-panel"><div class="sticky top-0 z-10 flex items-center justify-between border-b border-slate-200 bg-white/95 px-5 py-3 backdrop-blur"><div><p class="text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-400">Detail Drawer</p><div class="flex items-center gap-2"><h2 class="drawer-title text-[17px] font-semibold leading-6 text-slate-900">${title}</h2><span id="drawerSaveStatus" class="save-status"></span></div></div><div class="flex items-center gap-2"><button class="btn btn-ghost btn-sm text-red-600 hover:bg-red-50" onclick="deleteOperation(${id})"><i data-lucide="trash-2"></i>删除</button><button class="btn btn-ghost btn-sm" onclick="closeDrawer()">关闭</button></div></div><div class="grid gap-5 p-5">
|
||||
<section>
|
||||
<h3 class="drawer-section-title">属性</h3>
|
||||
<form id="drawerForm" class="drawer-fields">
|
||||
${drawerField("map-pin", "当前阶段", "current_stage", "", false, `<select name="current_stage" class="drawer-value" onchange="saveDrawerField(this,'${resource}',${id})">${["商务洽谈","系统上线","团队分工","项目交付","上线推广","结项验收"].map((s) => `<option ${s === item.current_stage ? "selected" : ""}>${s}</option>`).join("")}</select>`)}
|
||||
${fields.map(([key,label]) => drawerField(fieldIcons[key] || "circle", label, key, item[key], multilineFields.includes(key))).join("")}
|
||||
</form>
|
||||
</section>
|
||||
${resource === "proposals" ? `<section><h3 class="drawer-section-title">方案文件</h3><div class="grid gap-2">${["方案","成本","SOP","财务流程"].map((cat) => fileGroup("proposal", item.id, item.version, cat, item.files.filter((f) => f.file_category === cat))).join("")}</div></section>` : ""}
|
||||
${followupTarget ? `<section>
|
||||
<h3 class="drawer-section-title">活动 / 跟进</h3>
|
||||
<div class="grid gap-2">${(item.followups || []).map((f) => `<div class="activity-item"><div class="activity-icon"><i data-lucide="message-square"></i></div><div class="min-w-0 flex-1"><div class="flex justify-between gap-3 text-[12px] text-slate-500"><span>${f.follower} · ${f.follow_up_method}</span><span>${f.followed_at}</span></div><div class="mt-1 leading-5 text-slate-800 rich-content" data-html="${encodeURIComponent(f.content || '')}"></div>${f.next_action ? `<p class="mt-1 leading-5 text-blue-700">下一步:${text(f.next_action)}</p>` : ""}</div><button class="activity-delete" onclick="deleteFollowup(event, ${f.id}, '${resource}', ${item.id})" title="删除评论"><i data-lucide="trash-2"></i></button></div>`).join("")}</div>
|
||||
<form class="comment-box mt-3" onsubmit="submitComment(event,'${followupTarget}',${item.id},'${resource}')">
|
||||
<div class="squire-toolbar">
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('bold')" title="加粗"><i data-lucide="bold"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('italic')" title="斜体"><i data-lucide="italic"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('underline')" title="下划线"><i data-lucide="underline"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('strikethrough')" title="删除线"><i data-lucide="strikethrough"></i></button>
|
||||
<span class="squire-sep"></span>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('makeUnorderedList')" title="无序列表"><i data-lucide="list"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('makeOrderedList')" title="有序列表"><i data-lucide="list-ordered"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('blockquote')" title="引用"><i data-lucide="quote"></i></button>
|
||||
<span class="squire-sep"></span>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('undo')" title="撤销"><i data-lucide="undo"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('redo')" title="重做"><i data-lucide="redo"></i></button>
|
||||
</div>
|
||||
<div class="squire-editor" id="squire_${resource}_${item.id}" placeholder="添加评论"></div>
|
||||
<div class="comment-toolbar">
|
||||
<span class="comment-hint">支持富文本编辑</span>
|
||||
<button class="btn btn-primary btn-sm comment-submit" type="submit">评论</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>` : ""}
|
||||
</div></div>`;
|
||||
drawer.classList.add("open");
|
||||
bindDrawerAutosave(resource, item.id, item);
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
// Decode and render rich HTML content in followup records
|
||||
drawer.querySelectorAll(".rich-content").forEach((el) => {
|
||||
const html = el.dataset.html;
|
||||
if (html) el.innerHTML = decodeURIComponent(html);
|
||||
});
|
||||
// Initialize Squire editor
|
||||
const squireDiv = drawer.querySelector(".squire-editor");
|
||||
if (squireDiv && window.Squire) {
|
||||
const id = squireDiv.id;
|
||||
if (window.squireInstances[id]) window.squireInstances[id].destroy();
|
||||
const sq = new Squire(squireDiv, { blockTag: "P" });
|
||||
sq.addEventListener("input", () => {
|
||||
const form = squireDiv.closest("form");
|
||||
const btn = form.querySelector(".comment-submit");
|
||||
});
|
||||
window.squireInstances[id] = sq;
|
||||
// Handle placeholder
|
||||
squireDiv.addEventListener("focus", () => squireDiv.classList.add("focused"));
|
||||
squireDiv.addEventListener("blur", () => {
|
||||
if (!squireDiv.textContent.trim()) squireDiv.classList.remove("focused");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function setDrawerSaveStatus(message, tone = "muted") {
|
||||
const el = document.querySelector("#drawerSaveStatus");
|
||||
if (!el) return;
|
||||
el.textContent = message;
|
||||
el.dataset.tone = tone;
|
||||
}
|
||||
|
||||
function bindDrawerAutosave(resource, id, item) {
|
||||
document.querySelectorAll("#drawerForm .drawer-value").forEach((field) => {
|
||||
field.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Enter" && field.tagName !== "TEXTAREA") field.blur();
|
||||
});
|
||||
const doSave = async () => {
|
||||
const value = field.value;
|
||||
if (value === field.dataset.original) return;
|
||||
const previous = field.dataset.original;
|
||||
field.dataset.original = value;
|
||||
setDrawerSaveStatus("保存中…");
|
||||
try {
|
||||
await api(`/api/${resource}/${id}`, { method: "PUT", body: JSON.stringify({ data: { [field.name]: value } }) });
|
||||
item[field.name] = value;
|
||||
const titleValue = item.target_customer || item.project_name || item.customer_or_project_name || item.product_name;
|
||||
const titleEl = document.querySelector(".drawer-title");
|
||||
if (titleEl) titleEl.textContent = titleValue;
|
||||
render();
|
||||
setDrawerSaveStatus("已保存", "success");
|
||||
setTimeout(() => setDrawerSaveStatus(""), 1200);
|
||||
} catch (error) {
|
||||
field.dataset.original = previous;
|
||||
setDrawerSaveStatus("保存失败", "danger");
|
||||
alert(`自动保存失败:${error.message}`);
|
||||
}
|
||||
};
|
||||
field.addEventListener("blur", doSave);
|
||||
if (field.tagName === "SELECT") field.addEventListener("change", doSave);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
window.openDrawer = openDrawer;
|
||||
window.deleteOperation = async (id) => {
|
||||
if (!confirm("确认删除该项目?此操作不可撤销。")) return;
|
||||
try {
|
||||
await api(`/api/operations/${id}`, { method: "DELETE" });
|
||||
closeDrawer();
|
||||
await load();
|
||||
} catch (error) {
|
||||
alert("删除失败:" + error.message);
|
||||
}
|
||||
};
|
||||
window.toggleTaskDone = async (taskId, projectId) => {
|
||||
const task = (state.data.tasks || []).find((t) => t.id === taskId);
|
||||
if (!task) return;
|
||||
const newStatus = task.status === "done" ? "" : "done";
|
||||
try {
|
||||
await api(`/api/tasks/${taskId}`, { method: "PUT", body: JSON.stringify({ data: { status: newStatus } }) });
|
||||
await load();
|
||||
} catch (error) {
|
||||
alert("更新失败:" + error.message);
|
||||
}
|
||||
};
|
||||
window.deleteTask = async (projectId) => {
|
||||
const taskId = document.querySelector(`#task-id-${projectId}`).value;
|
||||
if (!taskId) return;
|
||||
if (!confirm("确认删除该任务?此操作不可撤销。")) return;
|
||||
try {
|
||||
await api(`/api/tasks/${taskId}`, { method: "DELETE" });
|
||||
closeTaskDrawer(projectId);
|
||||
await load();
|
||||
} catch (error) {
|
||||
alert("删除失败:" + error.message);
|
||||
}
|
||||
};
|
||||
let dragTaskId = null;
|
||||
window.handleTaskDragStart = (event, taskId) => {
|
||||
dragTaskId = taskId;
|
||||
event.currentTarget.classList.add("dragging");
|
||||
event.dataTransfer.effectAllowed = "move";
|
||||
};
|
||||
window.handleTaskDrop = async (event, projectId, phase) => {
|
||||
event.preventDefault();
|
||||
event.currentTarget.classList.remove("drag-over");
|
||||
const target = event.currentTarget;
|
||||
if (!dragTaskId) return;
|
||||
// Find the dragged element and insert after the nearest task
|
||||
const dragged = document.querySelector(`.task-row[data-id="${dragTaskId}"]`);
|
||||
if (!dragged) return;
|
||||
const afterElement = getDragAfterElement(target, event.clientY);
|
||||
if (afterElement) {
|
||||
target.insertBefore(dragged, afterElement);
|
||||
} else {
|
||||
target.appendChild(dragged);
|
||||
}
|
||||
dragged.classList.remove("dragging");
|
||||
// Update sort_order in DB
|
||||
const rows = [...target.querySelectorAll(".task-row")];
|
||||
const updates = rows.map((row, i) => ({ id: parseInt(row.dataset.id), sort_order: i }));
|
||||
try {
|
||||
await api(`/api/tasks/batch-sort`, { method: "POST", body: JSON.stringify({ items: updates }) });
|
||||
} catch (e) { /* non-critical */ }
|
||||
dragTaskId = null;
|
||||
};
|
||||
function getDragAfterElement(container, y) {
|
||||
const elements = [...container.querySelectorAll(".task-row:not(.dragging)")];
|
||||
return elements.reduce((closest, child) => {
|
||||
const box = child.getBoundingClientRect();
|
||||
const offset = y - box.top - box.height / 2;
|
||||
if (offset < 0 && offset > closest.offset) {
|
||||
return { offset, element: child };
|
||||
}
|
||||
return closest;
|
||||
}, { offset: Number.NEGATIVE_INFINITY }).element;
|
||||
}
|
||||
window.closeDrawer = () => document.querySelector("#drawer").classList.remove("open");
|
||||
window.squireInstances = {};
|
||||
window.squireCmd = (cmd) => {
|
||||
const currentEditor = document.querySelector(".squire-editor");
|
||||
if (!currentEditor) return;
|
||||
const id = currentEditor.id;
|
||||
const sq = window.squireInstances[id];
|
||||
if (!sq) return;
|
||||
sq.focus();
|
||||
setTimeout(() => {
|
||||
if (cmd === "bold") {
|
||||
sq.hasFormat("b") || sq.hasFormat("strong") ? sq.removeBold() : sq.bold();
|
||||
} else if (cmd === "italic") {
|
||||
sq.hasFormat("i") || sq.hasFormat("em") ? sq.removeItalic() : sq.italic();
|
||||
} else if (cmd === "underline") {
|
||||
sq.hasFormat("u") ? sq.changeFormat(null, { tag: "u" }, null) : sq.changeFormat({ tag: "u" }, null, null);
|
||||
} else if (cmd === "strikethrough") {
|
||||
sq.hasFormat("s") || sq.hasFormat("del") || sq.hasFormat("strike") ? sq.changeFormat(null, { tag: "s" }, null) : sq.changeFormat({ tag: "s" }, null, null);
|
||||
} else {
|
||||
sq[cmd]();
|
||||
}
|
||||
}, 10);
|
||||
};
|
||||
|
||||
window.submitComment = async (event, targetType, targetId, resource) => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const editorDiv = form.querySelector(".squire-editor");
|
||||
const sq = window.squireInstances[editorDiv.id];
|
||||
const content = sq ? sq.getHTML().trim() : "";
|
||||
if (!content || content === "<div><br></div>" || content === "<p><br></p>") return;
|
||||
const button = form.querySelector(".comment-submit");
|
||||
button.disabled = true;
|
||||
button.textContent = "发送中…";
|
||||
await api(`/api/followups/${targetType}/${targetId}`, { method: "POST", body: JSON.stringify({ data: { content } }) });
|
||||
await load();
|
||||
openDrawer(resource, targetId);
|
||||
};
|
||||
|
||||
window.deleteFollowup = async (event, followupId, resource, targetId) => {
|
||||
event.stopPropagation();
|
||||
if (!confirm("确认删除这条评论?")) return;
|
||||
await api(`/api/followups/${followupId}`, { method: "DELETE" });
|
||||
await load();
|
||||
openDrawer(resource, targetId);
|
||||
};
|
||||
|
||||
document.querySelector("#tabs").addEventListener("click", (event) => {
|
||||
const button = event.target.closest("button[data-tab]");
|
||||
if (button) switchTab(button.dataset.tab);
|
||||
});
|
||||
document.querySelector("#refreshBtn").addEventListener("click", load);
|
||||
load().catch((error) => {
|
||||
document.querySelector("main").innerHTML = `<section class="card p-6 text-red-700">加载失败:${error.message}</section>`;
|
||||
}).catch((error) => {
|
||||
document.querySelector("main").innerHTML = `<section class="card p-6 text-red-700">加载失败:${esc(error.message)}</section>`;
|
||||
});
|
||||
|
||||
168
static/modules/admin.js
Normal file
168
static/modules/admin.js
Normal file
@@ -0,0 +1,168 @@
|
||||
// admin.js — 账号管理(仅 admin 可见)
|
||||
|
||||
window.openAdminUsers = async () => {
|
||||
const overlay = document.createElement("div");
|
||||
overlay.id = "adminOverlay";
|
||||
overlay.className = "fixed inset-0 bg-black/40 z-[9998] flex items-center justify-center p-4";
|
||||
overlay.innerHTML = `
|
||||
<div class="bg-white rounded-xl shadow-2xl w-full max-w-3xl max-h-[85vh] flex flex-col">
|
||||
<div class="flex items-center justify-between px-6 py-4 border-b border-slate-200">
|
||||
<h2 class="text-lg font-semibold text-slate-800">账号管理</h2>
|
||||
<div class="flex items-center gap-2">
|
||||
<button class="btn btn-primary btn-sm" onclick="openUserForm()"><i data-lucide="plus" style="width:14px;height:14px"></i>新增账号</button>
|
||||
<button class="text-slate-400 hover:text-slate-700" onclick="closeAdminUsers()"><i data-lucide="x"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="overflow-y-auto p-6" id="adminUserList"></div>
|
||||
</div>`;
|
||||
overlay.addEventListener("click", (e) => { if (e.target === overlay) closeAdminUsers(); });
|
||||
document.body.appendChild(overlay);
|
||||
if (window.lucide) lucide.createIcons();
|
||||
await loadUserList();
|
||||
};
|
||||
|
||||
window.closeAdminUsers = () => {
|
||||
const el = document.getElementById("adminOverlay");
|
||||
if (el) el.remove();
|
||||
};
|
||||
|
||||
async function loadUserList() {
|
||||
const list = document.getElementById("adminUserList");
|
||||
if (!list) return;
|
||||
list.innerHTML = `<div class="text-center text-slate-400 py-8">加载中...</div>`;
|
||||
try {
|
||||
const users = await api("/api/users");
|
||||
const tenants = await api("/api/tenants");
|
||||
list.innerHTML = `
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-slate-200 text-slate-500 text-xs">
|
||||
<th class="text-left py-2 px-2">用户名</th>
|
||||
<th class="text-left py-2 px-2">显示名</th>
|
||||
<th class="text-left py-2 px-2">角色</th>
|
||||
<th class="text-left py-2 px-2">工作台</th>
|
||||
<th class="text-right py-2 px-2">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
${users.map(u => `
|
||||
<tr class="border-b border-slate-100 hover:bg-slate-50">
|
||||
<td class="py-3 px-2 font-medium text-slate-800">${esc(u.username)}</td>
|
||||
<td class="py-3 px-2 text-slate-700">${esc(u.display_name)}</td>
|
||||
<td class="py-3 px-2">
|
||||
<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium ${u.role === 'admin' ? 'bg-blue-100 text-blue-700' : 'bg-slate-100 text-slate-600'}">${u.role === 'admin' ? '管理员' : 'OPC负责人'}</span>
|
||||
</td>
|
||||
<td class="py-3 px-2 text-slate-600 text-xs">${(u.tenants || []).map(t => `<span class="inline-block bg-slate-100 rounded px-1.5 py-0.5 mr-1 mb-1">${esc(t)}</span>`).join('') || '<span class="text-slate-400">—</span>'}</td>
|
||||
<td class="py-3 px-2 text-right">
|
||||
<button class="btn btn-ghost btn-sm" onclick="openUserForm(${u.id})"><i data-lucide="edit-2" style="width:14px;height:14px"></i>编辑</button>
|
||||
<button class="btn btn-ghost btn-sm text-red-600 hover:bg-red-50" onclick="deleteUser(${u.id}, '${esc(u.username)}')"><i data-lucide="trash-2" style="width:14px;height:14px"></i>删除</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('')}
|
||||
</tbody>
|
||||
</table>`;
|
||||
if (window.lucide) lucide.createIcons();
|
||||
} catch (e) {
|
||||
list.innerHTML = `<div class="text-center text-red-600 py-8">加载失败:${esc(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
window.openUserForm = async (uid) => {
|
||||
let user = null;
|
||||
let userTenants = [];
|
||||
if (uid) {
|
||||
try {
|
||||
const users = await api("/api/users");
|
||||
user = users.find(u => u.id === uid);
|
||||
userTenants = user?.tenants || [];
|
||||
} catch (e) { toast("加载用户失败", "error"); return; }
|
||||
}
|
||||
const tenants = await api("/api/tenants");
|
||||
|
||||
const modal = document.createElement("div");
|
||||
modal.id = "userFormModal";
|
||||
modal.className = "fixed inset-0 bg-black/40 z-[9999] flex items-center justify-center p-4";
|
||||
modal.innerHTML = `
|
||||
<div class="bg-white rounded-xl shadow-2xl w-full max-w-md">
|
||||
<div class="flex items-center justify-between px-6 py-4 border-b border-slate-200">
|
||||
<h3 class="text-base font-semibold text-slate-800">${user ? '编辑账号' : '新增账号'}</h3>
|
||||
<button class="text-slate-400 hover:text-slate-700" onclick="document.getElementById('userFormModal').remove()"><i data-lucide="x"></i></button>
|
||||
</div>
|
||||
<form class="p-6 space-y-4" onsubmit="submitUserForm(event, ${uid || 0})">
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-slate-600 mb-1">用户名 ${user ? '<span class="text-slate-400">(不可修改)</span>' : '<span class="text-red-500">*</span>'}</label>
|
||||
<input name="username" class="form-ctrl w-full" value="${user ? esc(user.username) : ''}" ${user ? 'disabled' : 'required'} placeholder="登录用户名">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-slate-600 mb-1">显示名 <span class="text-red-500">*</span></label>
|
||||
<input name="display_name" class="form-ctrl w-full" value="${user ? esc(user.display_name) : ''}" required placeholder="如:科普负责人">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-slate-600 mb-1">密码 ${user ? '<span class="text-slate-400">(留空不修改)</span>' : '<span class="text-red-500">*</span>'}</label>
|
||||
<input name="password" type="password" class="form-ctrl w-full" ${user ? '' : 'required'} placeholder="${user ? '留空保持原密码' : '登录密码'}">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-slate-600 mb-1">角色</label>
|
||||
<select name="role" class="form-ctrl w-full">
|
||||
<option value="opc_owner" ${user?.role === 'opc_owner' ? 'selected' : ''}>OPC负责人(仅看分配工作台)</option>
|
||||
<option value="admin" ${user?.role === 'admin' ? 'selected' : ''}>管理员(看所有工作台)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-slate-600 mb-1">工作台权限 <span class="text-slate-400">(OPC负责人生效)</span></label>
|
||||
<div class="space-y-1.5">
|
||||
${tenants.map(t => `
|
||||
<label class="flex items-center gap-2 cursor-pointer">
|
||||
<input type="checkbox" name="tenants" value="${esc(t)}" ${userTenants.includes(t) ? 'checked' : ''} class="rounded">
|
||||
<span class="text-sm text-slate-700">${esc(t)}</span>
|
||||
</label>
|
||||
`).join('')}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end gap-2 pt-2">
|
||||
<button type="button" class="btn btn-ghost btn-sm" onclick="document.getElementById('userFormModal').remove()">取消</button>
|
||||
<button type="submit" class="btn btn-primary btn-sm">保存</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>`;
|
||||
modal.addEventListener("click", (e) => { if (e.target === modal) modal.remove(); });
|
||||
document.body.appendChild(modal);
|
||||
if (window.lucide) lucide.createIcons();
|
||||
};
|
||||
|
||||
window.submitUserForm = async (event, uid) => {
|
||||
event.preventDefault();
|
||||
const form = event.target;
|
||||
const fd = new FormData(form);
|
||||
const payload = {
|
||||
username: fd.get("username"),
|
||||
display_name: fd.get("display_name"),
|
||||
password: fd.get("password"),
|
||||
role: fd.get("role"),
|
||||
tenants: fd.getAll("tenants"),
|
||||
};
|
||||
try {
|
||||
if (uid) {
|
||||
await api(`/api/users/${uid}`, { method: "PUT", body: JSON.stringify(payload) });
|
||||
toast("已更新", "success");
|
||||
} else {
|
||||
await api("/api/users", { method: "POST", body: JSON.stringify(payload) });
|
||||
toast("已新增", "success");
|
||||
}
|
||||
document.getElementById("userFormModal").remove();
|
||||
await loadUserList();
|
||||
} catch (e) {
|
||||
toast("保存失败:" + e.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
window.deleteUser = async (uid, username) => {
|
||||
if (!confirm(`确认删除账号「${username}」?此操作不可撤销。`)) return;
|
||||
try {
|
||||
await api(`/api/users/${uid}`, { method: "DELETE" });
|
||||
toast("已删除", "success");
|
||||
await loadUserList();
|
||||
} catch (e) {
|
||||
toast("删除失败:" + e.message, "error");
|
||||
}
|
||||
};
|
||||
271
static/modules/drawer.js
Normal file
271
static/modules/drawer.js
Normal file
@@ -0,0 +1,271 @@
|
||||
// drawer.js — 详情抽屉 + 评论 + 删除
|
||||
|
||||
function drawerField(icon, label, name, value, multiline = false, customControl = null) {
|
||||
const safeValue = esc(value || "");
|
||||
const control = customControl
|
||||
? customControl
|
||||
: multiline
|
||||
? `<textarea name="${name}" rows="2" class="form-ctrl" data-original="${safeValue}">${safeValue}</textarea>`
|
||||
: `<input name="${name}" value="${safeValue}" class="form-ctrl" data-original="${safeValue}">`;
|
||||
return `<div class="drawer-field">
|
||||
<div class="drawer-field-label"><i data-lucide="${icon}"></i><span>${label}</span></div>
|
||||
<div class="drawer-field-control">${control}</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function openDrawer(resource, id) {
|
||||
const list = resource === "sales" ? state.data.sales : resource === "operations" ? state.data.operations : resource === "proposals" ? state.data.proposals : state.data.products;
|
||||
const item = list.find((x) => x.id === id);
|
||||
const drawer = document.querySelector("#drawer");
|
||||
const fields = resource === "sales"
|
||||
? [["target_customer","业务机会"],["priority","优先级"],["status","状态"]]
|
||||
: resource === "operations"
|
||||
? [["project_name","项目名称"],["owner","负责人"],["expected_sign_date","截止时间"],["expected_contract_amount","金额"],["notes","项目说明"]]
|
||||
: resource === "proposals"
|
||||
? [["customer_or_project_name","客户/项目"],["proposal_type","方案类型"],["notes","备注"]]
|
||||
: [["product_name","版本名称"],["version","版本号"],["priority","优先级"],["version_goal","版本目标"],["start_date","启动时间"],["plan_date","产品方案"],["dev_done_date","研发完成"],["test_date","测试完成"],["launch_date","上线时间"],["notes","进展备注"]];
|
||||
const fieldIcons = {
|
||||
target_customer: "user", priority: "flag", status: "circle-dot",
|
||||
project_name: "briefcase-business", project_version: "git-branch", project_status: "circle-dot", current_stage: "map-pin",
|
||||
owner: "user", customer_need: "file-text", expected_contract_amount: "banknote", expected_sign_date: "calendar",
|
||||
sign_probability: "percent", sop_stage: "list-checks", execution_progress: "activity",
|
||||
current_deliverable: "package", risks: "alert-triangle", next_action: "arrow-right",
|
||||
product_name: "box", version: "tag", version_goal: "target", feature_list: "list", platform: "layers",
|
||||
launch_date: "calendar", notes: "sticky-note", proposal_type: "tag", customer_or_project_name: "building",
|
||||
priority: "flag", owner: "user", start_date: "play", plan_date: "file-text", dev_done_date: "check-square",
|
||||
test_date: "bug", devs: "users", testers: "shield-check"
|
||||
};
|
||||
const multilineFields = ["customer_need", "current_deliverable", "risks", "next_action", "version_goal", "feature_list", "notes"];
|
||||
const followupTarget = resource === "sales" ? "sales" : resource === "proposals" ? "proposal" : resource === "operations" ? "operation" : resource === "products" ? "product" : "";
|
||||
const title = esc(item.target_customer || item.project_name || (item.customer_or_project_name ? `${item.customer_or_project_name} · ${item.proposal_type || ''}` : "") || item.product_name);
|
||||
const titleForAttr = esc(item.target_customer || item.project_name || (item.customer_or_project_name ? `${item.customer_or_project_name} · ${item.proposal_type || ''}` : "") || item.product_name);
|
||||
drawer.innerHTML = `<div class="drawer-panel"><div class="sticky top-0 z-10 flex items-center justify-between border-b border-slate-200 bg-white/95 px-5 py-3 backdrop-blur"><div><p class="text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-400">Detail Drawer</p><div class="flex items-center gap-2"><h2 class="drawer-title text-[17px] font-semibold leading-6 text-slate-900">${title}</h2><span id="drawerSaveStatus" class="save-status"></span></div></div><div class="flex items-center gap-2"><button class="btn btn-ghost btn-sm text-red-600 hover:bg-red-50" onclick="deleteDrawerItem('${resource}', ${id})"><i data-lucide="trash-2"></i>删除</button><button class="btn btn-ghost btn-sm" onclick="closeDrawer()">关闭</button></div></div><div class="grid gap-5 p-5">
|
||||
${resource === "products" ? (() => {
|
||||
const dDays = (s, e) => { if (!s || !e) return '-'; const d = Math.round((new Date(e) - new Date(s)) / 86400000); return d >= 0 ? d + ' 天' : '-'; };
|
||||
return `<section>
|
||||
<h3 class="drawer-section-title">耗时统计</h3>
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="bg-slate-50 rounded-lg p-3"><p class="text-xs text-slate-500">总耗时(上线−启动)</p><p class="text-lg font-semibold text-slate-800 mt-1">${dDays(item.start_date, item.launch_date)}</p></div>
|
||||
<div class="bg-slate-50 rounded-lg p-3"><p class="text-xs text-slate-500">产品耗时(方案−启动)</p><p class="text-lg font-semibold text-slate-800 mt-1">${dDays(item.start_date, item.plan_date)}</p></div>
|
||||
<div class="bg-slate-50 rounded-lg p-3"><p class="text-xs text-slate-500">研发耗时(研发完成−方案)</p><p class="text-lg font-semibold text-slate-800 mt-1">${dDays(item.plan_date, item.dev_done_date)}</p></div>
|
||||
<div class="bg-slate-50 rounded-lg p-3"><p class="text-xs text-slate-500">测试耗时(测试完成−研发完成)</p><p class="text-lg font-semibold text-slate-800 mt-1">${dDays(item.dev_done_date, item.test_date)}</p></div>
|
||||
</div>
|
||||
</section>`;
|
||||
})() : ""}
|
||||
<section>
|
||||
<h3 class="drawer-section-title">属性</h3>
|
||||
<form id="drawerForm" class="drawer-fields">
|
||||
${resource === "operations" ? drawerField("map-pin", "当前阶段", "current_stage", "", false, `<select name="current_stage" class="form-ctrl" onchange="saveDrawerField(this,'${resource}',${id})">${["商务洽谈","系统上线","团队分工","项目交付","上线推广","结项验收"].map((s) => `<option ${s === item.current_stage ? "selected" : ""}>${s}</option>`).join("")}</select>`) : ""}
|
||||
${fields.map(([key,label]) => {
|
||||
if (resource === "products" && key === "priority") {
|
||||
return `<div class="drawer-field"><div class="drawer-field-label"><i data-lucide="flag"></i><span>优先级 / 状态</span></div><div class="drawer-field-control grid grid-cols-2 gap-3"><select name="priority" class="form-ctrl" onchange="saveDrawerField(this,'${resource}',${id})">${["P0","P1","P2","P3"].map((s) => `<option ${s === (item.priority||'P2') ? "selected" : ""}>${s}</option>`).join("")}</select><select name="status" class="form-ctrl" onchange="saveDrawerField(this,'${resource}',${id})">${["未开始","规划中","开发中","测试中","已上线","已取消"].map((s) => `<option ${s === (item.status||'规划中') ? "selected" : ""}>${s}</option>`).join("")}</select></div></div>`;
|
||||
}
|
||||
if (resource === "products" && (key === "start_date" || key === "plan_date" || key === "dev_done_date" || key === "test_date" || key === "launch_date")) {
|
||||
return drawerField("calendar", label, key, item[key], false, `<input type="date" name="${key}" value="${item[key]||''}" class="form-ctrl" data-original="${item[key]||''}" onchange="saveDrawerField(this,'${resource}',${id})">`);
|
||||
}
|
||||
return drawerField(fieldIcons[key] || "circle", label, key, item[key], multilineFields.includes(key));
|
||||
}).join("")}
|
||||
</form>
|
||||
</section>
|
||||
${resource === "proposals" ? `<section><h3 class="drawer-section-title">附件</h3>${fileGroup("proposal", item.id, "", "附件", item.files || [])}</section>` : ""}
|
||||
${followupTarget ? `<section>
|
||||
<h3 class="drawer-section-title">活动 / 跟进</h3>
|
||||
<div class="grid gap-2">${(item.followups || []).map((f) => `<div class="activity-item"><div class="activity-icon"><i data-lucide="message-square"></i></div><div class="min-w-0 flex-1"><div class="flex justify-between gap-3 text-[12px] text-slate-500"><span>${esc(f.follower)} · ${esc(f.follow_up_method)}</span><span>${esc(f.followed_at)}</span></div><div class="mt-1 leading-5 text-slate-800 rich-content" data-html="${encodeURIComponent(f.content || '')}"></div>${f.next_action ? `<p class="mt-1 leading-5 text-blue-700">下一步:${text(f.next_action)}</p>` : ""}</div><button class="activity-delete" onclick="deleteFollowup(event, ${f.id}, '${resource}', ${item.id})" title="删除评论"><i data-lucide="trash-2"></i></button></div>`).join("")}</div>
|
||||
<form class="comment-box mt-3" onsubmit="submitComment(event,'${followupTarget}',${item.id},'${resource}')">
|
||||
<div class="squire-toolbar">
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('bold')" title="加粗"><i data-lucide="bold"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('italic')" title="斜体"><i data-lucide="italic"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('underline')" title="下划线"><i data-lucide="underline"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('strikethrough')" title="删除线"><i data-lucide="strikethrough"></i></button>
|
||||
<span class="squire-sep"></span>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('makeUnorderedList')" title="无序列表"><i data-lucide="list"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('makeOrderedList')" title="有序列表"><i data-lucide="list-ordered"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('blockquote')" title="引用"><i data-lucide="quote"></i></button>
|
||||
<span class="squire-sep"></span>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('undo')" title="撤销"><i data-lucide="undo"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('redo')" title="重做"><i data-lucide="redo"></i></button>
|
||||
</div>
|
||||
<div class="squire-editor" id="squire_${resource}_${item.id}" placeholder="添加评论"></div>
|
||||
<div class="comment-toolbar">
|
||||
<span class="comment-hint">支持富文本编辑</span>
|
||||
<button class="btn btn-primary btn-sm comment-submit" type="submit">评论</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>` : ""}
|
||||
<div id="uploadTaskList"></div>
|
||||
</div></div>`;
|
||||
drawer.classList.add("open");
|
||||
bindDrawerAutosave(resource, item.id, item);
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
renderUploadTasks();
|
||||
drawer.querySelectorAll(".rich-content").forEach((el) => {
|
||||
const html = el.dataset.html;
|
||||
if (html) el.innerHTML = decodeURIComponent(html);
|
||||
});
|
||||
const squireDiv = drawer.querySelector(".squire-editor");
|
||||
if (squireDiv && window.Squire) {
|
||||
const id = squireDiv.id;
|
||||
if (window.squireInstances[id]) window.squireInstances[id].destroy();
|
||||
const sq = new Squire(squireDiv, { blockTag: "P" });
|
||||
sq.addEventListener("input", () => {
|
||||
const form = squireDiv.closest("form");
|
||||
const btn = form.querySelector(".comment-submit");
|
||||
});
|
||||
window.squireInstances[id] = sq;
|
||||
squireDiv.addEventListener("focus", () => squireDiv.classList.add("focused"));
|
||||
squireDiv.addEventListener("blur", () => {
|
||||
if (!squireDiv.textContent.trim()) squireDiv.classList.remove("focused");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function setDrawerSaveStatus(message, tone = "muted") {
|
||||
const el = document.querySelector("#drawerSaveStatus");
|
||||
if (!el) return;
|
||||
el.textContent = message;
|
||||
el.dataset.tone = tone;
|
||||
}
|
||||
|
||||
function bindDrawerAutosave(resource, id, item) {
|
||||
document.querySelectorAll("#drawerForm .form-ctrl").forEach((field) => {
|
||||
field.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Enter" && field.tagName !== "TEXTAREA") field.blur();
|
||||
});
|
||||
const doSave = async () => {
|
||||
const value = field.value;
|
||||
if (value === field.dataset.original) return;
|
||||
const previous = field.dataset.original;
|
||||
field.dataset.original = value;
|
||||
setDrawerSaveStatus("保存中…");
|
||||
try {
|
||||
await api(`/api/${resource}/${id}`, { method: "PUT", body: JSON.stringify({ data: { [field.name]: value } }) });
|
||||
item[field.name] = value;
|
||||
const titleValue = item.target_customer || item.project_name || item.customer_or_project_name || item.product_name;
|
||||
const titleEl = document.querySelector(".drawer-title");
|
||||
if (titleEl) titleEl.textContent = titleValue;
|
||||
renderActive();
|
||||
setDrawerSaveStatus("已保存", "success");
|
||||
setTimeout(() => setDrawerSaveStatus(""), 1200);
|
||||
} catch (error) {
|
||||
field.dataset.original = previous;
|
||||
setDrawerSaveStatus("保存失败", "danger");
|
||||
toast(`自动保存失败:${error.message}`, "error");
|
||||
}
|
||||
};
|
||||
field.addEventListener("blur", doSave);
|
||||
if (field.tagName === "SELECT") field.addEventListener("change", doSave);
|
||||
});
|
||||
}
|
||||
|
||||
window.openDrawer = openDrawer;
|
||||
window.closeDrawer = () => document.querySelector("#drawer").classList.remove("open");
|
||||
|
||||
window.deleteDrawerItem = async (resource, id) => {
|
||||
if (!confirm("确认删除?此操作不可撤销。")) return;
|
||||
try {
|
||||
const listKey = { sales: "sales", proposals: "proposals", operations: "operations", products: "products" }[resource];
|
||||
let name = "";
|
||||
if (listKey && state.data[listKey]) {
|
||||
const item = state.data[listKey].find(x => x.id === id);
|
||||
name = item ? (item.target_customer || item.project_name || item.customer_or_project_name || item.product_name || "") : "";
|
||||
}
|
||||
await api(`/api/${resource}/${id}`, { method: "DELETE" });
|
||||
if (name) {
|
||||
const resType = { sales: "sales", proposals: "proposal", operations: "operation", products: "product" }[resource] || resource;
|
||||
logActivity(resType, id, "删除了「" + name + "」");
|
||||
}
|
||||
closeDrawer();
|
||||
await load();
|
||||
} catch (error) {
|
||||
toast("删除失败:" + error.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
// Squire 富文本编辑器
|
||||
window.squireInstances = {};
|
||||
window.squireCmd = (cmd) => {
|
||||
const currentEditor = document.querySelector(".squire-editor");
|
||||
if (!currentEditor) return;
|
||||
const id = currentEditor.id;
|
||||
const sq = window.squireInstances[id];
|
||||
if (!sq) return;
|
||||
sq.focus();
|
||||
setTimeout(() => {
|
||||
if (cmd === "bold") {
|
||||
sq.hasFormat("b") || sq.hasFormat("strong") ? sq.removeBold() : sq.bold();
|
||||
} else if (cmd === "italic") {
|
||||
sq.hasFormat("i") || sq.hasFormat("em") ? sq.removeItalic() : sq.italic();
|
||||
} else if (cmd === "underline") {
|
||||
sq.hasFormat("u") ? sq.changeFormat(null, { tag: "u" }, null) : sq.changeFormat({ tag: "u" }, null, null);
|
||||
} else if (cmd === "strikethrough") {
|
||||
sq.hasFormat("s") || sq.hasFormat("del") || sq.hasFormat("strike") ? sq.changeFormat(null, { tag: "s" }, null) : sq.changeFormat({ tag: "s" }, null, null);
|
||||
} else {
|
||||
sq[cmd]();
|
||||
}
|
||||
}, 10);
|
||||
};
|
||||
|
||||
window.submitComment = async (event, targetType, targetId, resource) => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const editorDiv = form.querySelector(".squire-editor");
|
||||
const sq = window.squireInstances[editorDiv.id];
|
||||
const content = sq ? sq.getHTML().trim() : "";
|
||||
if (!content || content === "<div><br></div>" || content === "<p><br></p>") return;
|
||||
const button = form.querySelector(".comment-submit");
|
||||
button.disabled = true;
|
||||
button.textContent = "发送中…";
|
||||
await api(`/api/followups/${targetType}/${targetId}`, { method: "POST", body: JSON.stringify({ data: { content } }) });
|
||||
await load();
|
||||
openDrawer(resource, targetId);
|
||||
};
|
||||
|
||||
window.deleteActivity = async (id) => {
|
||||
if (!confirm("确认删除这条动态?")) return;
|
||||
await api(`/api/followups/${id}`, { method: "DELETE" });
|
||||
await load();
|
||||
};
|
||||
|
||||
window.deleteFollowup = async (event, followupId, resource, targetId) => {
|
||||
event.stopPropagation();
|
||||
if (!confirm("确认删除这条评论?")) return;
|
||||
await api(`/api/followups/${followupId}`, { method: "DELETE" });
|
||||
await load();
|
||||
openDrawer(resource, targetId);
|
||||
};
|
||||
|
||||
window.saveDrawerField = async (el, resource, id) => {
|
||||
const name = el.name;
|
||||
const value = el.value;
|
||||
// 产品日期约束
|
||||
if (resource === "products") {
|
||||
const listKey = "products";
|
||||
const product = (state.data[listKey] || []).find(x => x.id === id);
|
||||
if (product) {
|
||||
// 启动时间必填
|
||||
if (name === "start_date" && !value) {
|
||||
toast("启动时间为必填项", "error");
|
||||
el.value = product.start_date || '';
|
||||
el.focus();
|
||||
return;
|
||||
}
|
||||
// 其他 4 个时间不能早于启动时间
|
||||
if (["plan_date","dev_done_date","test_date","launch_date"].includes(name) && value && product.start_date && value < product.start_date) {
|
||||
toast("该时间不能早于启动时间(" + product.start_date + ")", "error");
|
||||
el.value = product[name] || '';
|
||||
el.focus();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
await api(`/api/${resource}/${id}`, { method: "PUT", body: JSON.stringify({ data: { [name]: value } }) });
|
||||
const listKey = { sales: "sales", proposals: "proposals", operations: "operations", products: "products" }[resource];
|
||||
if (listKey && state.data[listKey]) {
|
||||
const item = state.data[listKey].find(x => x.id === id);
|
||||
if (item) item[name] = value;
|
||||
}
|
||||
} catch (error) {
|
||||
toast("保存失败:" + error.message, "error");
|
||||
}
|
||||
};
|
||||
715
static/modules/finance.js
Normal file
715
static/modules/finance.js
Normal file
@@ -0,0 +1,715 @@
|
||||
// finance.js — 经营管理(财务)模块
|
||||
|
||||
const moneyInt = (v) => `${Math.round(Number(v || 0)).toLocaleString("zh-CN")} 元`;
|
||||
const moneyWan = (v) => `${(Number(v || 0) / 10000).toFixed(1)} 万`;
|
||||
|
||||
function renderFinance() {
|
||||
const pfs = state.data.projectFinances || [];
|
||||
const ops = state.data.operations || [];
|
||||
const fmTypesByTenant = {
|
||||
"科普·无界": ["科普音频","科普视频","科普文章","科普专访","患教会","全品类科普","调研问卷"],
|
||||
"科研·无界": ["真实世界研究","调研问卷","病例征集","患者招募"],
|
||||
"医患·无界": ["医患运营","患者管理","患教会","创新支付","电商","其他"],
|
||||
};
|
||||
const fmTypes = fmTypesByTenant[state.tenant] || fmTypesByTenant["科普·无界"];
|
||||
const tenantOps = (state.data.operations || []).filter(o => (o.project_name || "").includes(state.tenant.replace("·无界","")) || o.tenant === state.tenant);
|
||||
const now = new Date();
|
||||
const thisMonth = now.getMonth() + 1;
|
||||
const displayMonths = [];
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const m = thisMonth + i;
|
||||
const mm = m > 12 ? m - 12 : m;
|
||||
displayMonths.push({ key: "2026_" + String(mm).padStart(2, "0"), label: mm + "月" });
|
||||
}
|
||||
const months = displayMonths.map(d => d.key);
|
||||
const monthLabels = displayMonths.map(d => d.label);
|
||||
|
||||
const signed = pfs.filter(x => x.status === "已签约");
|
||||
const inContract = pfs.filter(x => x.status === "流程中");
|
||||
const pending = pfs.filter(x => x.status === "待签约");
|
||||
const sumSign = Math.round(signed.reduce((s,x) => s + (x.sign_amount||0), 0));
|
||||
const sumPending = Math.round(pending.reduce((s,x) => s + (x.sign_amount||0), 0));
|
||||
const sumContract = Math.round(inContract.reduce((s,x) => s + (x.sign_amount||0), 0));
|
||||
|
||||
const monthRev = months.map(m => {
|
||||
return signed.reduce((s, pf) => {
|
||||
let budget = [];
|
||||
try { budget = JSON.parse(pf.budget_data || "[]"); } catch (e) {}
|
||||
const row = budget.find(b => (b.month || "").replace("-", "_") === m);
|
||||
return s + (row ? (parseFloat(row.rev) || 0) : 0);
|
||||
}, 0);
|
||||
});
|
||||
const monthGross = months.map(m => {
|
||||
return signed.reduce((s, pf) => {
|
||||
let budget = [];
|
||||
try { budget = JSON.parse(pf.budget_data || "[]"); } catch (e) {}
|
||||
const row = budget.find(b => (b.month || "").replace("-", "_") === m);
|
||||
return s + (row ? (parseFloat(row.gross) || 0) : 0);
|
||||
}, 0);
|
||||
});
|
||||
|
||||
const thisMonthKey = displayMonths[0].key;
|
||||
const thisMonthRev = monthRev[0];
|
||||
const thisMonthGross = monthGross[0];
|
||||
let monthPayment = 0, monthCost = 0;
|
||||
for (const pf of pfs) {
|
||||
let budget = [];
|
||||
try { budget = JSON.parse(pf.budget_data || "[]"); } catch (e) {}
|
||||
for (const b of budget) {
|
||||
const bKey = (b.month || "").replace("-", "_");
|
||||
if (bKey === thisMonthKey) {
|
||||
monthPayment += parseFloat(b.payment || 0);
|
||||
monthCost += parseFloat(b.cost || 0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
monthPayment = Math.round(monthPayment);
|
||||
monthCost = Math.round(monthCost);
|
||||
const monthCashflow = monthPayment - monthCost;
|
||||
|
||||
const renderPfRow = (pf) => {
|
||||
let budgetMap = {};
|
||||
try {
|
||||
const budget = JSON.parse(pf.budget_data || "[]");
|
||||
budget.forEach(b => { budgetMap[(b.month || "").replace("-", "_")] = b; });
|
||||
} catch (e) {}
|
||||
const isRevView = state.finView !== "cashflow" && state.finView !== "overview" && state.finView !== "monthly" && state.finView !== "quarterly";
|
||||
const mCols = months.map(m => {
|
||||
const b = budgetMap[m] || {};
|
||||
if (isRevView) {
|
||||
const rev = b.rev || 0;
|
||||
const gross = b.gross || 0;
|
||||
return `<td class="p-2 text-center whitespace-nowrap align-middle"><span class="${rev ? 'text-blue-700 font-medium' : 'text-slate-300'}">${rev ? money(rev) : '—'}</span><br><span class="text-xs ${gross ? 'text-green-600' : 'text-slate-300'}">${gross ? money(gross) : '—'}</span></td>`;
|
||||
} else {
|
||||
const payment = b.payment || 0;
|
||||
const cost = b.cost || 0;
|
||||
return `<td class="p-2 text-center whitespace-nowrap align-middle"><span class="${payment ? 'text-amber-700 font-medium' : 'text-slate-300'}">${payment ? money(payment) : '—'}</span><br><span class="text-xs ${cost ? 'text-rose-600' : 'text-slate-300'}">${cost ? money(cost) : '—'}</span></td>`;
|
||||
}
|
||||
}).join("");
|
||||
const totalCol = (() => {
|
||||
if (isRevView) {
|
||||
const totalRev = pf.total_rev || 0;
|
||||
const totalGross = pf.total_gross || 0;
|
||||
return `<td class="p-2 text-center whitespace-nowrap align-middle font-semibold"><span class="${totalRev ? 'text-blue-700' : 'text-slate-300'}">${totalRev ? money(totalRev) : '—'}</span><br><span class="text-xs ${totalGross ? 'text-green-600' : 'text-slate-300'}">${totalGross ? money(totalGross) : '—'}</span></td>`;
|
||||
} else {
|
||||
let totalPayment = 0, totalCost = 0;
|
||||
try { JSON.parse(pf.budget_data || "[]").forEach(b => { totalPayment += parseFloat(b.payment||0)||0; totalCost += parseFloat(b.cost||0)||0; }); } catch (e) {}
|
||||
return `<td class="p-2 text-center whitespace-nowrap align-middle font-semibold"><span class="${totalPayment ? 'text-amber-700' : 'text-slate-300'}">${totalPayment ? money(totalPayment) : '—'}</span><br><span class="text-xs ${totalCost ? 'text-rose-600' : 'text-slate-300'}">${totalCost ? money(totalCost) : '—'}</span></td>`;
|
||||
}
|
||||
})();
|
||||
const sm = pf.sign_month || "";
|
||||
const signMonthCell = `<td class="p-2 text-center text-sm"><span class="pf-sm-text cursor-pointer hover:text-blue-600" id="pf-sm-${pf.id}" onclick="event.stopPropagation(); editPfSignMonth(event, ${pf.id})">${sm || '—'}</span></td>`;
|
||||
return `<tr class="border-b border-slate-100 hover:bg-slate-50 cursor-pointer" onclick="openPfEditModal(${pf.id})"><td class="p-2 text-sm font-medium text-center">${esc(pf.customer_name)}</td>${signMonthCell}<td class="p-2 text-center text-sm">${money(pf.sign_amount)}</td>${mCols}${totalCol}</tr>`;
|
||||
};
|
||||
|
||||
const finHeaderBase = `<button class="btn btn-sm ${state.finView === 'overview' ? 'btn-primary' : 'btn-ghost'} px-2 py-1.5" data-view="overview" onclick="setFinView('overview')">总视图</button><button class="btn btn-sm ${state.finView === 'monthly' ? 'btn-primary' : 'btn-ghost'} px-2 py-1.5" data-view="monthly" onclick="setFinView('monthly')">月度</button><button class="btn btn-sm ${state.finView === 'quarterly' ? 'btn-primary' : 'btn-ghost'} px-2 py-1.5" data-view="quarterly" onclick="setFinView('quarterly')">季度</button><span class="text-slate-300 mx-0.5">|</span><span class="text-xs text-slate-400">筛选:</span><span class="text-xs text-slate-500">状态:</span><select onchange="state.finFilter=this.value;renderFinance()" class="text-xs font-medium py-1 px-2.5 cursor-pointer" style="appearance:none;-webkit-appearance:none;background-color:transparent;border:0;outline:none;background:url('data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2212%22 height=%2212%22 viewBox=%220 0 24 24%22 fill=%22none%22 stroke=%22%236b7280%22 stroke-width=%222%22 stroke-linecap=%22round%22 stroke-linejoin=%22round%22%3E%3Cpolyline points=%226 9 12 15 18 9%22%3E%3C/polyline%3E%3C/svg%3E') no-repeat right 4px center;padding-right:22px;min-height:30px"><option value="已签约" ${state.finFilter==='已签约'?'selected':''}>已签约 (${pfs.filter(x=>x.status==='已签约').length})</option><option value="流程中" ${state.finFilter==='流程中'?'selected':''}>流程中 (${pfs.filter(x=>x.status==='流程中').length})</option><option value="待签约" ${state.finFilter==='待签约'?'selected':''}>待签约 (${pfs.filter(x=>x.status==='待签约').length})</option></select>`;
|
||||
const finAddBtn = `<button class="btn btn-primary btn-sm" onclick="openFinanceModal()">新增财务项目</button>`;
|
||||
|
||||
document.querySelector("#finance").innerHTML = `<div class="grid gap-4">
|
||||
<div class="grid grid-cols-4 gap-3">
|
||||
${[["已签项目","" + signed.length,"file-check-2"],["签约金额",moneyWan(sumSign),"coins"],["待签项目","" + pending.length,"file-question"],["待签金额",moneyWan(sumPending),"hourglass"]].map(([l,v,icon]) => `<div class="metric-card"><span class="flex items-center gap-2 text-xs text-slate-500"><i data-lucide="${icon}" style="width:14px;height:14px"></i>${l}</span><strong class="mt-2 block text-2xl">${v}</strong></div>`).join("")}
|
||||
</div>
|
||||
<div class="grid grid-cols-5 gap-3">
|
||||
${[["本月确收",moneyInt(thisMonthRev),"trending-up"],["本月毛利",moneyInt(thisMonthGross),"percent"],["本月回款",moneyInt(monthPayment),"wallet"],["本月应付",moneyInt(monthCost),"receipt"],["本月现金流",moneyInt(monthCashflow),"repeat"]].map(([l,v,icon]) => `<div class="metric-card"><span class="flex items-center gap-2 text-xs text-slate-500"><i data-lucide="${icon}" style="width:14px;height:14px"></i>${l}</span><strong class="mt-2 block text-2xl">${v}</strong></div>`).join("")}
|
||||
</div>
|
||||
<div id="financeModal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/40" onclick="closeFinanceModal()"><div class="bg-white rounded-2xl shadow-2xl w-full max-w-6xl mx-4 max-h-[92vh] overflow-y-auto" onclick="event.stopPropagation()"><div class="sticky top-0 z-10 bg-white/95 backdrop-blur border-b border-slate-100 px-8 py-5 flex items-center justify-between"><div><h3 class="text-xl font-bold text-slate-800" id="financeModalTitle">新增项目财务</h3><p class="text-xs text-slate-400 mt-0.5">填写项目财务信息与月度预算</p></div><div class="flex items-center gap-2"><button class="btn btn-ghost btn-sm text-red-600 hidden" id="financeDeleteBtn" onclick="deleteFinanceItem()"><i data-lucide="trash-2"></i>删除</button><button class="btn btn-ghost btn-sm rounded-full w-8 h-8 p-0" onclick="closeFinanceModal()"><i data-lucide="x"></i></button></div></div>
|
||||
<div class="finance-tabs">
|
||||
<button class="finance-tab active" data-tab="info" onclick="switchFinanceTab('info')"><i data-lucide="info" style="width:14px;height:14px;display:inline-block;vertical-align:-2px;margin-right:4px"></i>基本信息</button>
|
||||
<button class="finance-tab" data-tab="budget" onclick="switchFinanceTab('budget')"><i data-lucide="calendar" style="width:14px;height:14px;display:inline-block;vertical-align:-2px;margin-right:4px"></i>项目流水</button>
|
||||
<button class="finance-tab" data-tab="exec" onclick="switchFinanceTab('exec')"><i data-lucide="play-circle" style="width:14px;height:14px;display:inline-block;vertical-align:-2px;margin-right:4px"></i>执行信息</button>
|
||||
<button class="finance-tab" data-tab="tasks" onclick="switchFinanceTab('tasks')"><i data-lucide="list-checks" style="width:14px;height:14px;display:inline-block;vertical-align:-2px;margin-right:4px"></i>任务管理</button>
|
||||
<button class="finance-tab" data-tab="activity" onclick="switchFinanceTab('activity')"><i data-lucide="message-square" style="width:14px;height:14px;display:inline-block;vertical-align:-2px;margin-right:4px"></i>活动与跟进</button>
|
||||
</div>
|
||||
<form onsubmit="createFinance(event)" class="finance-form" novalidate><input type="hidden" name="pf_id" id="pf-id-input" value="">
|
||||
<div class="finance-tab-body">
|
||||
<div id="financeTabInfo">
|
||||
<div class="grid gap-4">
|
||||
<div class="grid grid-cols-3 gap-3">
|
||||
<label class="block"><span class="fin-label">部门</span><input type="hidden" name="project_id" value="${state.tenant}"><input class="form-ctrl bg-slate-50 cursor-not-allowed" value="${state.tenant}" disabled></label>
|
||||
<label class="block"><span class="fin-label">项目编号</span><input name="project_code" class="form-ctrl" placeholder="如:KP-2026-001"></label>
|
||||
<label class="block"><span class="fin-label">项目名称 <span class="text-red-500">*</span></span><input name="customer_name" required class="form-ctrl" placeholder="请输入项目名称"></label>
|
||||
</div>
|
||||
<div class="grid grid-cols-3 gap-3">
|
||||
<label class="block"><span class="fin-label">签约金额(元) <span class="text-red-500">*</span></span><input name="sign_amount" class="form-ctrl" placeholder="必须大于 0"></label>
|
||||
<label class="block"><span class="fin-label">签约月份 <span class="text-red-500">*</span></span><select name="sign_month" required class="form-ctrl bg-white"><option value="">选择</option>${monthOptions('')}</select></label>
|
||||
<label class="block"><span class="fin-label">项目状态</span><select name="status" class="form-ctrl bg-white"><option>已签约</option><option>流程中</option><option>待签约</option></select></label>
|
||||
</div>
|
||||
<div class="grid grid-cols-3 gap-3">
|
||||
<label class="block"><span class="fin-label">商务负责人 <span class="text-red-500">*</span></span><input name="sales_person" required class="form-ctrl" placeholder="请输入商务负责人"></label>
|
||||
<label class="block"><span class="fin-label">经营负责人 <span class="text-red-500">*</span></span><input name="owner" required class="form-ctrl" placeholder="请输入经营负责人"></label>
|
||||
<label class="block"><span class="fin-label">业务联系人</span><input name="contact_name" class="form-ctrl" placeholder="请输入业务联系人"></label>
|
||||
</div>
|
||||
<div class="grid grid-cols-3 gap-3">
|
||||
<label class="block"><span class="fin-label">联系电话</span><input name="contact_phone" class="form-ctrl" placeholder="请输入联系电话"></label>
|
||||
<label class="block"><span class="fin-label">其他</span><input name="other_info" class="form-ctrl" placeholder="备注信息"></label>
|
||||
</div>
|
||||
<div class="block"><span class="fin-label">业务类型</span><div class="flex flex-wrap gap-2 mt-1" id="businessTypeChecks">${fmTypes.map(t => `<label class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full border border-slate-200 cursor-pointer hover:border-blue-300 text-sm bt-chip" onclick="toggleBtChip(this)"><input type="checkbox" name="business_type[]" value="${t}" class="hidden"><span>${t}</span></label>`).join("")}</div></div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="financeTabExec" class="hidden">
|
||||
<div class="fin-field-group">
|
||||
<p class="fin-section-label">执行信息</p>
|
||||
<div class="grid grid-cols-3 gap-4">
|
||||
<label class="block"><span class="fin-label">开始时间</span><input name="start_date" type="date" class="form-ctrl"></label>
|
||||
<label class="block"><span class="fin-label">结束时间</span><input name="end_date" type="date" class="form-ctrl"></label>
|
||||
<label class="block"><span class="fin-label">项目经理</span><input name="project_manager" class="form-ctrl" placeholder="请输入项目经理"></label>
|
||||
<label class="block"><span class="fin-label">合同服务费标准</span><select name="service_fee_standard" class="form-ctrl bg-white">${Array.from({length:21},(_,i)=>{const v=i+5;return `<option value="${v}" ${v===5?'selected':''}>${v}%</option>`}).join("")}</select></label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="financeTabBudget" class="hidden">
|
||||
<div class="grid grid-cols-5 gap-3 mb-4" id="budgetSummary">
|
||||
<div class="bg-blue-50 rounded-lg p-3 text-center border border-blue-100">
|
||||
<p class="text-xs text-blue-600 font-medium">总确收</p>
|
||||
<p class="text-lg font-bold text-blue-700" id="budgetTotalRev">¥0</p>
|
||||
</div>
|
||||
<div class="bg-green-50 rounded-lg p-3 text-center border border-green-100">
|
||||
<p class="text-xs text-green-600 font-medium">总毛利</p>
|
||||
<p class="text-lg font-bold text-green-700" id="budgetTotalGross">¥0</p>
|
||||
</div>
|
||||
<div class="bg-amber-50 rounded-lg p-3 text-center border border-amber-100" id="budgetTotalPaymentCard">
|
||||
<p class="text-xs text-amber-600 font-medium">总回款</p>
|
||||
<p class="text-lg font-bold text-amber-700" id="budgetTotalPayment">¥0</p>
|
||||
</div>
|
||||
<div class="bg-rose-50 rounded-lg p-3 text-center border border-rose-100" id="budgetTotalCostCard">
|
||||
<p class="text-xs text-rose-600 font-medium">总应付</p>
|
||||
<p class="text-lg font-bold text-rose-700" id="budgetTotalCost">¥0</p>
|
||||
</div>
|
||||
<div class="bg-purple-50 rounded-lg p-3 text-center border border-purple-100">
|
||||
<p class="text-xs text-purple-600 font-medium">总已付</p>
|
||||
<p class="text-lg font-bold text-purple-700" id="budgetTotalPaid">¥0</p>
|
||||
</div>
|
||||
</div>
|
||||
<table class="w-full text-sm border border-slate-200 rounded-lg overflow-hidden" id="budgetTable">
|
||||
<thead><tr class="bg-slate-50 border-b border-slate-200"><th class="p-2.5 text-left font-medium text-slate-500" style="min-width:140px">月份</th><th class="p-2.5 text-right font-medium text-slate-500">确收</th><th class="p-2.5 text-right font-medium text-slate-500">毛利</th><th class="p-2.5 text-right font-medium text-slate-500">回款</th><th class="p-2.5 text-right font-medium text-slate-500">应付</th><th class="p-2.5 text-right font-medium text-slate-500">已付</th><th class="p-2.5 w-8"></th></tr></thead>
|
||||
<tbody id="budgetTbody"></tbody>
|
||||
</table>
|
||||
<button type="button" class="btn btn-ghost btn-sm mt-3" onclick="addBudgetRow()"><i data-lucide="plus"></i>添加月份</button>
|
||||
</div>
|
||||
<div id="financeTabTasks" class="hidden">
|
||||
<table class="w-full text-sm border border-slate-200 rounded-lg overflow-hidden" id="taskTable">
|
||||
<thead><tr class="bg-slate-50 border-b border-slate-200"><th class="p-2.5 text-left font-medium text-slate-500" style="min-width:120px">月份</th><th class="p-2.5 text-left font-medium text-slate-500" style="min-width:120px">任务类型</th><th class="p-2.5 text-right font-medium text-slate-500">任务数量</th><th class="p-2.5 text-right font-medium text-slate-500">已执行</th><th class="p-2.5 text-right font-medium text-slate-500">差额</th><th class="p-2.5 text-right font-medium text-slate-500">单价</th><th class="p-2.5 text-right font-medium text-slate-500">执行金额</th><th class="p-2.5 text-right font-medium text-slate-500">未执行金额</th><th class="p-2.5 w-8"></th></tr></thead>
|
||||
<tbody id="taskTbody"></tbody>
|
||||
</table>
|
||||
<button type="button" class="btn btn-ghost btn-sm mt-3" onclick="addTaskRow()"><i data-lucide="plus"></i>添加任务</button>
|
||||
</div>
|
||||
<div id="financeTabActivity" class="hidden">
|
||||
<div class="grid gap-2" id="finActivityList"></div>
|
||||
<div class="comment-box mt-3">
|
||||
<div class="squire-toolbar">
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('bold')" title="加粗"><i data-lucide="bold"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('italic')" title="斜体"><i data-lucide="italic"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('underline')" title="下划线"><i data-lucide="underline"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('strikethrough')" title="删除线"><i data-lucide="strikethrough"></i></button>
|
||||
<span class="squire-sep"></span>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('makeUnorderedList')" title="无序列表"><i data-lucide="list"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('makeOrderedList')" title="有序列表"><i data-lucide="list-ordered"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('blockquote')" title="引用"><i data-lucide="quote"></i></button>
|
||||
<span class="squire-sep"></span>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('undo')" title="撤销"><i data-lucide="undo"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('redo')" title="重做"><i data-lucide="redo"></i></button>
|
||||
</div>
|
||||
<div class="squire-editor" id="squire_finance" placeholder="添加评论"></div>
|
||||
<div class="comment-toolbar">
|
||||
<span class="comment-hint">支持富文本编辑</span>
|
||||
<button class="btn btn-primary btn-sm comment-submit" type="button" onclick="submitFinComment()">评论</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div><div class="flex justify-end gap-3 pt-2 finance-form-actions"><button type="button" class="btn btn-ghost btn-sm px-6" onclick="closeFinanceModal()">取消</button><button type="submit" class="btn btn-primary btn-sm px-8">保存</button></div></form></div></div>
|
||||
${state.finView === 'monthly' ? (() => {
|
||||
const allPfs = pfs.filter(x => x.status === state.finFilter);
|
||||
const now = new Date();
|
||||
const defaultMonth = now.getFullYear() + "-" + String(now.getMonth()+1).padStart(2,"0");
|
||||
if (!state.finMonth) state.finMonth = defaultMonth;
|
||||
const selMonth = state.finMonth;
|
||||
// 收集所有有数据的月份 + 当前月
|
||||
const monthSet = new Set([defaultMonth]);
|
||||
allPfs.forEach(pf => { let bd = []; try { bd = JSON.parse(pf.budget_data || "[]"); } catch(e) {} bd.forEach(b => { if (b.month) monthSet.add(b.month); }); });
|
||||
const sortedMonths = [...monthSet].sort().reverse();
|
||||
const monthOpts = sortedMonths.map(m => `<option value="${m}" ${m === selMonth ? 'selected' : ''}>${m}</option>`).join("");
|
||||
const fmt = (v) => v ? `<span class="font-medium">${money(v)}</span>` : '<span class="text-slate-300">—</span>';
|
||||
const fmtDiff = (v) => { if (!v) return '<span class="text-slate-300">—</span>'; return `<span class="${v > 0 ? 'text-amber-600 font-medium' : 'text-green-600 font-medium'}">${money(Math.abs(v))}</span>`; };
|
||||
const rows = [];
|
||||
let sumRev=0, sumPay=0, sumCost=0, sumPaid=0;
|
||||
allPfs.forEach(pf => {
|
||||
let bd = []; try { bd = JSON.parse(pf.budget_data || "[]"); } catch(e) {}
|
||||
const b = bd.find(x => (x.month||"") === selMonth) || {};
|
||||
const rev = Math.round(parseFloat(b.rev||0)||0);
|
||||
const payment = Math.round(parseFloat(b.payment||0)||0);
|
||||
const cost = Math.round(parseFloat(b.cost||0)||0);
|
||||
const paid = Math.round(parseFloat(b.paid||0)||0);
|
||||
if (!rev && !payment && !cost && !paid) return;
|
||||
const payDiff = rev - payment;
|
||||
const costDiff = cost - paid;
|
||||
const cashflow = payment - paid;
|
||||
sumRev+=rev; sumPay+=payment; sumCost+=cost; sumPaid+=paid;
|
||||
rows.push(`<tr class="border-b border-slate-100 hover:bg-slate-50 cursor-pointer" onclick="openPfEditModal(${pf.id})"><td class="p-2 text-sm font-medium text-center">${esc(pf.customer_name)}</td><td class="p-2 text-center text-sm">${pf.status==='已签约'?'<span class="text-green-600">已签约</span>':pf.status==='流程中'?'<span class="text-blue-600">流程中</span>':'<span class="text-amber-600">待签约</span>'}</td><td class="p-2 text-center text-blue-700 align-middle">${fmt(rev)}</td><td class="p-2 text-center text-amber-700 align-middle">${fmt(payment)}</td><td class="p-2 text-center align-middle">${fmtDiff(payDiff)}</td><td class="p-2 text-center text-rose-700 align-middle">${fmt(cost)}</td><td class="p-2 text-center text-purple-700 align-middle">${fmt(paid)}</td><td class="p-2 text-center align-middle">${fmtDiff(costDiff)}</td><td class="p-2 text-center font-semibold align-middle ${cashflow >= 0 ? 'text-green-600' : 'text-red-600'}">${cashflow ? money(cashflow) : '<span class="text-slate-300">—</span>'}</td></tr>`);
|
||||
});
|
||||
return card(`<div class="flex justify-between items-center mb-3"><div class="flex items-center gap-2">${finHeaderBase}<span class="text-xs text-slate-500">月份:</span><select onchange="state.finMonth=this.value;renderFinance()" class="text-xs font-medium py-1 px-2.5 cursor-pointer" style="appearance:none;-webkit-appearance:none;background-color:transparent;border:0;outline:none;background:url('data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2212%22 height=%2212%22 viewBox=%220 0 24 24%22 fill=%22none%22 stroke=%22%236b7280%22 stroke-width=%222%22 stroke-linecap=%22round%22 stroke-linejoin=%22round%22%3E%3Cpolyline points=%226 9 12 15 18 9%22%3E%3C/polyline%3E%3C/svg%3E') no-repeat right 4px center;padding-right:22px;min-height:30px">${monthOpts}</select></div>${finAddBtn}</div><div class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="bg-slate-50 border-b border-slate-200"><th class="p-2 text-center font-semibold align-middle">项目名称</th><th class="p-2 text-center font-semibold align-middle">状态</th><th class="p-2 text-center font-semibold align-middle text-blue-600">已确收</th><th class="p-2 text-center font-semibold align-middle text-amber-600">已回款</th><th class="p-2 text-center font-semibold align-middle">回款差额</th><th class="p-2 text-center font-semibold align-middle text-rose-600">应付</th><th class="p-2 text-center font-semibold align-middle text-purple-600">已付</th><th class="p-2 text-center font-semibold align-middle">应付差额</th><th class="p-2 text-center font-semibold align-middle text-slate-700">现金流</th></tr></thead><tbody>${rows.length ? rows.join("") : '<tr><td colspan="9" class="p-6 text-center text-slate-400">该月份暂无数据</td></tr>'}<tr class="border-t-2 border-slate-200 bg-slate-50 font-bold"><td class="p-2 text-center" colspan="2">合计</td><td class="p-2 text-center text-blue-700 align-middle">${money(sumRev)}</td><td class="p-2 text-center text-amber-700 align-middle">${money(sumPay)}</td><td class="p-2 text-center align-middle">${fmtDiff(sumRev - sumPay)}</td><td class="p-2 text-center text-rose-700 align-middle">${money(sumCost)}</td><td class="p-2 text-center text-purple-700 align-middle">${money(sumPaid)}</td><td class="p-2 text-center align-middle">${fmtDiff(sumCost - sumPaid)}</td><td class="p-2 text-center font-semibold align-middle ${sumPay - sumPaid >= 0 ? 'text-green-600' : 'text-red-600'}">${money(sumPay - sumPaid)}</td></tr></tbody></table></div>`, "p-4");
|
||||
})() : state.finView === 'quarterly' ? (() => {
|
||||
const allPfs = pfs.filter(x => x.status === state.finFilter);
|
||||
const qRanges = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]];
|
||||
const qLabels = ["Q1 (1-3月)", "Q2 (4-6月)", "Q3 (7-9月)", "Q4 (10-12月)"];
|
||||
const now = new Date();
|
||||
if (state.finQuarter === undefined) {
|
||||
const saved = localStorage.getItem("opc-fin-quarter");
|
||||
state.finQuarter = saved !== null ? parseInt(saved) : Math.floor(now.getMonth() / 3);
|
||||
}
|
||||
const selQ = state.finQuarter;
|
||||
const qRange = qRanges[selQ];
|
||||
const quarterOpts = qLabels.map((l, i) => `<option value="${i}" ${i === selQ ? 'selected' : ''}>${l}</option>`).join("");
|
||||
const sumBudget = (pf, field) => {
|
||||
let total = 0;
|
||||
try { JSON.parse(pf.budget_data || "[]").forEach(b => {
|
||||
const m = parseInt((b.month || "").substring(5)) || 0;
|
||||
if (qRange.includes(m)) total += parseFloat(b[field] || 0);
|
||||
}); } catch (e) {}
|
||||
return total;
|
||||
};
|
||||
const fmt = (v) => v ? `<span class="font-medium">${money(v)}</span>` : '<span class="text-slate-300">—</span>';
|
||||
const fmtDiff = (v) => { if (!v) return '<span class="text-slate-300">—</span>'; return `<span class="${v > 0 ? 'text-amber-600 font-medium' : 'text-green-600 font-medium'}">${money(Math.abs(v))}</span>`; };
|
||||
let sumRev = 0, sumPay = 0, sumCost = 0, sumPaid = 0;
|
||||
const rows = [];
|
||||
allPfs.forEach(pf => {
|
||||
const rev = sumBudget(pf, "rev");
|
||||
const payment = sumBudget(pf, "payment");
|
||||
const cost = sumBudget(pf, "cost");
|
||||
const paid = sumBudget(pf, "paid");
|
||||
const payDiff = rev - payment;
|
||||
const costDiff = cost - paid;
|
||||
const cashflow = payment - paid;
|
||||
sumRev += rev; sumPay += payment; sumCost += cost; sumPaid += paid;
|
||||
rows.push(`<tr class="border-b border-slate-100 hover:bg-slate-50 cursor-pointer" onclick="openPfEditModal(${pf.id})"><td class="p-2 text-sm font-medium text-center">${esc(pf.customer_name)}</td><td class="p-2 text-center text-sm">${pf.status==='已签约'?'<span class="text-green-600">已签约</span>':pf.status==='流程中'?'<span class="text-blue-600">流程中</span>':'<span class="text-amber-600">待签约</span>'}</td><td class="p-2 text-center text-blue-700 align-middle">${fmt(rev)}</td><td class="p-2 text-center text-amber-700 align-middle">${fmt(payment)}</td><td class="p-2 text-center align-middle">${fmtDiff(payDiff)}</td><td class="p-2 text-center text-rose-700 align-middle">${fmt(cost)}</td><td class="p-2 text-center text-purple-700 align-middle">${fmt(paid)}</td><td class="p-2 text-center align-middle">${fmtDiff(costDiff)}</td><td class="p-2 text-center font-semibold align-middle ${cashflow >= 0 ? 'text-green-600' : 'text-red-600'}">${cashflow ? money(cashflow) : '<span class="text-slate-300">—</span>'}</td></tr>`);
|
||||
});
|
||||
return card(`<div class="flex justify-between items-center mb-3"><div class="flex items-center gap-2">${finHeaderBase}<span class="text-xs text-slate-500">季度:</span><select onchange="state.finQuarter=parseInt(this.value);localStorage.setItem('opc-fin-quarter',this.value);renderFinance()" class="text-xs font-medium py-1 px-2.5 cursor-pointer" style="appearance:none;-webkit-appearance:none;background-color:transparent;border:0;outline:none;background:url('data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%2212%22 height=%2212%22 viewBox=%220 0 24 24%22 fill=%22none%22 stroke=%22%236b7280%22 stroke-width=%222%22 stroke-linecap=%22round%22 stroke-linejoin=%22round%22%3E%3Cpolyline points=%226 9 12 15 18 9%22%3E%3C/polyline%3E%3C/svg%3E') no-repeat right 4px center;padding-right:22px;min-height:30px">${quarterOpts}</select></div>${finAddBtn}</div><div class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="bg-slate-50 border-b border-slate-200"><th class="p-2 text-center font-semibold align-middle">项目名称</th><th class="p-2 text-center font-semibold align-middle">状态</th><th class="p-2 text-center font-semibold align-middle text-blue-600">已确收</th><th class="p-2 text-center font-semibold align-middle text-amber-600">已回款</th><th class="p-2 text-center font-semibold align-middle">回款差额</th><th class="p-2 text-center font-semibold align-middle text-rose-600">应付</th><th class="p-2 text-center font-semibold align-middle text-purple-600">已付</th><th class="p-2 text-center font-semibold align-middle">应付差额</th><th class="p-2 text-center font-semibold align-middle text-slate-700">现金流</th></tr></thead><tbody>${rows.length ? rows.join("") : '<tr><td colspan="9" class="p-6 text-center text-slate-400">该季度暂无数据</td></tr>'}<tr class="border-t-2 border-slate-200 bg-slate-50 font-bold"><td class="p-2 text-center" colspan="2">合计</td><td class="p-2 text-center text-blue-700 align-middle">${money(sumRev)}</td><td class="p-2 text-center text-amber-700 align-middle">${money(sumPay)}</td><td class="p-2 text-center align-middle">${fmtDiff(sumRev - sumPay)}</td><td class="p-2 text-center text-rose-700 align-middle">${money(sumCost)}</td><td class="p-2 text-center text-purple-700 align-middle">${money(sumPaid)}</td><td class="p-2 text-center align-middle">${fmtDiff(sumCost - sumPaid)}</td> <td class="p-2 text-center font-semibold align-middle ${sumPay - sumPaid >= 0 ? 'text-green-600' : 'text-red-600'}">${money(sumPay - sumPaid)}</td></tr></tbody></table></div>`, "p-4");
|
||||
})() : (() => {
|
||||
const calcTotals = (pf) => {
|
||||
let budget = []; try { budget = JSON.parse(pf.budget_data || "[]"); } catch (e) {}
|
||||
let rev = 0, payment = 0, cost = 0;
|
||||
budget.forEach(b => { rev += parseFloat(b.rev||0)||0; payment += parseFloat(b.payment||0)||0; cost += parseFloat(b.cost||0)||0; });
|
||||
const paid = parseFloat(pf.total_paid) || 0;
|
||||
return { rev: Math.round(rev), payment: Math.round(payment), cost: Math.round(cost), paid: Math.round(paid) };
|
||||
};
|
||||
const allPfs = pfs.filter(x => x.status === state.finFilter);
|
||||
let sumRev=0, sumPay=0, sumCost=0, sumPaid=0;
|
||||
allPfs.forEach(pf => { const t = calcTotals(pf); sumRev+=t.rev; sumPay+=t.payment; sumCost+=t.cost; sumPaid+=t.paid; });
|
||||
const fmt = (v) => v ? `<span class="font-medium">${money(v)}</span>` : '<span class="text-slate-300">—</span>';
|
||||
const fmtDiff = (v) => { if (!v) return '<span class="text-slate-300">—</span>'; return `<span class="${v > 0 ? 'text-amber-600 font-medium' : 'text-green-600 font-medium'}">${money(Math.abs(v))}</span>`; };
|
||||
return card(`<div class="flex justify-between items-center mb-3"><div class="flex items-center gap-2">${finHeaderBase}</div>${finAddBtn}</div><div class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="bg-slate-50 border-b border-slate-200"><th class="p-2 text-center font-semibold align-middle">项目名称</th><th class="p-2 text-center font-semibold align-middle">状态</th><th class="p-2 text-center font-semibold align-middle text-blue-600">已确收</th><th class="p-2 text-center font-semibold align-middle text-amber-600">已回款</th><th class="p-2 text-center font-semibold align-middle">回款差额</th><th class="p-2 text-center font-semibold align-middle text-rose-600">应付</th><th class="p-2 text-center font-semibold align-middle text-purple-600">已付</th><th class="p-2 text-center font-semibold align-middle">应付差额</th><th class="p-2 text-center font-semibold align-middle text-slate-700">现金流</th></tr></thead><tbody>${allPfs.map(pf => { const t = calcTotals(pf); const payDiff = t.rev - t.payment; const costDiff = t.cost - t.paid; const cashflow = t.payment - t.paid; return `<tr class="border-b border-slate-100 hover:bg-slate-50 cursor-pointer" onclick="openPfEditModal(${pf.id})"><td class="p-2 text-sm font-medium text-center">${esc(pf.customer_name)}</td><td class="p-2 text-center text-sm">${pf.status==='已签约'?'<span class="text-green-600">已签约</span>':pf.status==='流程中'?'<span class="text-blue-600">流程中</span>':'<span class="text-amber-600">待签约</span>'}</td><td class="p-2 text-center text-blue-700 align-middle">${fmt(t.rev)}</td><td class="p-2 text-center text-amber-700 align-middle">${fmt(t.payment)}</td><td class="p-2 text-center align-middle">${fmtDiff(payDiff)}</td><td class="p-2 text-center text-rose-700 align-middle">${fmt(t.cost)}</td><td class="p-2 text-center text-purple-700 align-middle">${fmt(t.paid)}</td><td class="p-2 text-center align-middle">${fmtDiff(costDiff)}</td><td class="p-2 text-center font-semibold align-middle ${cashflow >= 0 ? 'text-green-600' : 'text-red-600'}">${cashflow ? money(cashflow) : '<span class="text-slate-300">—</span>'}</td></tr>`; }).join("")}<tr class="border-t-2 border-slate-200 bg-slate-50 font-bold"><td class="p-2 text-center" colspan="2">合计</td><td class="p-2 text-center text-blue-700 align-middle">${money(sumRev)}</td><td class="p-2 text-center text-amber-700 align-middle">${money(sumPay)}</td><td class="p-2 text-center align-middle">${fmtDiff(sumRev - sumPay)}</td><td class="p-2 text-center text-rose-700 align-middle">${money(sumCost)}</td><td class="p-2 text-center text-purple-700 align-middle">${money(sumPaid)}</td><td class="p-2 text-center align-middle">${fmtDiff(sumCost - sumPaid)}</td><td class="p-2 text-center font-semibold align-middle ${sumPay - sumPaid >= 0 ? 'text-green-600' : 'text-red-600'}">${money(sumPay - sumPaid)}</td></tr></tbody></table></div>`, "p-4");
|
||||
})()}
|
||||
</div>`;
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
|
||||
window.openFinanceModal = () => {
|
||||
const modal = document.querySelector("#financeModal");
|
||||
const form = modal.querySelector("form");
|
||||
form.querySelector('[name="project_id"]').value = state.tenant;
|
||||
const dept = form.querySelector('input[disabled]');
|
||||
if (dept) dept.value = state.tenant;
|
||||
const pfIdInput = form.querySelector('[name="pf_id"]');
|
||||
if (!pfIdInput || !pfIdInput.value) {
|
||||
initBudgetTable(null);
|
||||
initTaskTable(null);
|
||||
document.querySelector("#financeDeleteBtn").classList.add("hidden");
|
||||
}
|
||||
modal.classList.remove("hidden");
|
||||
};
|
||||
|
||||
window.addBudgetRow = (month = '', rev = '', gross = '', payment = '', cost = '', paid = '') => {
|
||||
const tbody = document.querySelector("#budgetTbody");
|
||||
if (!tbody) return;
|
||||
const row = document.createElement("tr");
|
||||
row.innerHTML = `<td><select name="budget_month[]" class="form-ctrl form-ctrl-sm w-full" style="min-width:140px" onchange="updateBudgetSummary()">${monthOptions(month)}</select></td>
|
||||
<td><input name="budget_rev[]" type="number" step="0.01" class="form-ctrl form-ctrl-sm w-full text-right" placeholder="0" value="${rev}" oninput="updateBudgetSummary()"></td>
|
||||
<td><input name="budget_gross[]" type="number" step="0.01" class="form-ctrl form-ctrl-sm w-full text-right" placeholder="0" value="${gross}" oninput="updateBudgetSummary()"></td>
|
||||
<td><input name="budget_payment[]" type="number" step="0.01" class="form-ctrl form-ctrl-sm w-full text-right" placeholder="0" value="${payment}" oninput="updateBudgetSummary()"></td>
|
||||
<td><input name="budget_cost[]" type="number" step="0.01" class="form-ctrl form-ctrl-sm w-full text-right" placeholder="0" value="${cost}" oninput="updateBudgetSummary()"></td>
|
||||
<td><input name="budget_paid[]" type="number" step="0.01" class="form-ctrl form-ctrl-sm w-full text-right" placeholder="0" value="${paid}" oninput="updateBudgetSummary()"></td>
|
||||
<td><button type="button" class="btn btn-ghost btn-sm text-red-500 p-0 w-6 h-6" onclick="this.closest('tr').remove();updateBudgetSummary()"><i data-lucide="trash-2" style="width:14px;height:14px"></i></button></td>`;
|
||||
tbody.appendChild(row);
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
};
|
||||
|
||||
window.updateBudgetSummary = () => {
|
||||
const revEl = document.querySelector("#budgetTotalRev");
|
||||
const grossEl = document.querySelector("#budgetTotalGross");
|
||||
const paymentEl = document.querySelector("#budgetTotalPayment");
|
||||
const costEl = document.querySelector("#budgetTotalCost");
|
||||
const paidEl = document.querySelector("#budgetTotalPaid");
|
||||
if (!revEl || !grossEl) return;
|
||||
const revInputs = document.querySelectorAll('[name="budget_rev[]"]');
|
||||
const grossInputs = document.querySelectorAll('[name="budget_gross[]"]');
|
||||
const paymentInputs = document.querySelectorAll('[name="budget_payment[]"]');
|
||||
const costInputs = document.querySelectorAll('[name="budget_cost[]"]');
|
||||
const paidInputs = document.querySelectorAll('[name="budget_paid[]"]');
|
||||
let totalRev = 0, totalGross = 0, totalPayment = 0, totalCost = 0, totalPaid = 0;
|
||||
revInputs.forEach(el => { totalRev += parseFloat(el.value) || 0; });
|
||||
grossInputs.forEach(el => { totalGross += parseFloat(el.value) || 0; });
|
||||
paymentInputs.forEach(el => { totalPayment += parseFloat(el.value) || 0; });
|
||||
costInputs.forEach(el => { totalCost += parseFloat(el.value) || 0; });
|
||||
paidInputs.forEach(el => { totalPaid += parseFloat(el.value) || 0; });
|
||||
revEl.textContent = money(totalRev);
|
||||
grossEl.textContent = money(totalGross);
|
||||
if (paymentEl) paymentEl.textContent = money(totalPayment);
|
||||
if (costEl) costEl.textContent = money(totalCost);
|
||||
if (paidEl) paidEl.textContent = money(totalPaid);
|
||||
};
|
||||
|
||||
window.initBudgetTable = (budgetData) => {
|
||||
const tbody = document.querySelector("#budgetTbody");
|
||||
if (!tbody) return;
|
||||
tbody.innerHTML = "";
|
||||
const rows = budgetData || [];
|
||||
rows.forEach(r => addBudgetRow(r.month || '', r.rev || '', r.gross || '', r.payment || '', r.cost || '', r.paid || ''));
|
||||
setTimeout(() => updateBudgetSummary(), 50);
|
||||
};
|
||||
|
||||
// ---------- 任务管理 tab ----------
|
||||
const TASK_TYPES = ["科普视频", "科普专访", "科普文章", "问卷调研", "病例征集"];
|
||||
|
||||
function taskMonthOptions(selected) {
|
||||
const now = new Date();
|
||||
const opts = [];
|
||||
for (let i = -2; i <= 12; i++) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth() + i, 1);
|
||||
const v = d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0");
|
||||
opts.push(`<option value="${v}" ${v === selected ? 'selected' : ''}>${v}</option>`);
|
||||
}
|
||||
return opts.join("");
|
||||
}
|
||||
|
||||
window.addTaskRow = (taskMonth = '', taskType = '', taskCount = '', executedCount = '', unitPrice = '') => {
|
||||
const tbody = document.querySelector("#taskTbody");
|
||||
if (!tbody) return;
|
||||
const row = document.createElement("tr");
|
||||
const defaultMonth = (() => { const n = new Date(); return n.getFullYear() + "-" + String(n.getMonth()+1).padStart(2,"0"); })();
|
||||
const isPreset = TASK_TYPES.includes(taskType);
|
||||
const typeCell = isPreset || !taskType
|
||||
? `<select name="task_type[]" class="form-ctrl form-ctrl-sm w-full" onchange="onTaskTypeChange(this)"><option value="">选择</option>${TASK_TYPES.map(t => `<option ${t === taskType ? 'selected' : ''}>${t}</option>`).join("")}<option value="__custom__" ${!isPreset && taskType ? 'selected' : ''}>自定义...</option></select>`
|
||||
: `<input name="task_type[]" class="form-ctrl form-ctrl-sm w-full" value="${esc(taskType)}" placeholder="输入自定义类型"><button type="button" class="btn btn-ghost btn-sm text-slate-400 p-0 w-5 h-5 ml-1" onclick="revertTaskType(this)" title="返回选择"><i data-lucide="rotate-ccw" style="width:12px;height:12px"></i></button>`;
|
||||
row.innerHTML = `<td><select name="task_month[]" class="form-ctrl form-ctrl-sm w-full">${taskMonthOptions(taskMonth || defaultMonth)}</select></td>
|
||||
<td class="flex items-center">${typeCell}</td>
|
||||
<td><input name="task_count[]" type="number" step="1" min="0" class="form-ctrl form-ctrl-sm text-right" style="width:100px" placeholder="0" value="${taskCount}" oninput="updateTaskDiff(this)"></td>
|
||||
<td><input name="task_executed[]" type="number" step="1" min="0" class="form-ctrl form-ctrl-sm text-right" style="width:100px" placeholder="0" value="${executedCount}" oninput="updateTaskDiff(this)"></td>
|
||||
<td><input name="task_diff[]" type="number" class="form-ctrl form-ctrl-sm text-right" style="width:80px" placeholder="—" disabled></td>
|
||||
<td><input name="task_unit_price[]" type="number" step="0.01" min="0" class="form-ctrl form-ctrl-sm text-right" style="width:90px" placeholder="0" value="${unitPrice}" oninput="updateTaskDiff(this)"></td>
|
||||
<td><input name="task_exec_amount[]" type="number" class="form-ctrl form-ctrl-sm text-right" style="width:140px" placeholder="—" disabled></td>
|
||||
<td><input name="task_unexec_amount[]" type="number" class="form-ctrl form-ctrl-sm text-right" style="width:140px" placeholder="—" disabled></td>
|
||||
<td><button type="button" class="btn btn-ghost btn-sm text-red-500 p-0 w-6 h-6" onclick="this.closest('tr').remove()"><i data-lucide="trash-2" style="width:14px;height:14px"></i></button></td>`;
|
||||
tbody.appendChild(row);
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
updateRowCalc(row);
|
||||
};
|
||||
|
||||
window.updateTaskDiff = (el) => {
|
||||
const row = el.closest('tr');
|
||||
if (!row) return;
|
||||
updateRowCalc(row);
|
||||
};
|
||||
|
||||
function updateRowCalc(row) {
|
||||
const countInput = row.querySelector('[name="task_count[]"]');
|
||||
const execInput = row.querySelector('[name="task_executed[]"]');
|
||||
const priceInput = row.querySelector('[name="task_unit_price[]"]');
|
||||
const diffInput = row.querySelector('[name="task_diff[]"]');
|
||||
const execAmtInput = row.querySelector('[name="task_exec_amount[]"]');
|
||||
const unexecAmtInput = row.querySelector('[name="task_unexec_amount[]"]');
|
||||
const c = parseFloat(countInput.value) || 0;
|
||||
const e = parseFloat(execInput.value) || 0;
|
||||
const p = parseFloat(priceInput.value) || 0;
|
||||
const diff = c - e;
|
||||
// 差额
|
||||
diffInput.value = (!c && !e) ? '' : diff;
|
||||
// 执行金额 = 单价 * 已执行
|
||||
const execAmt = p * e;
|
||||
execAmtInput.value = execAmt ? execAmt.toFixed(2) : '';
|
||||
// 未执行金额 = 单价 * 差额
|
||||
const unexecAmt = p * diff;
|
||||
unexecAmtInput.value = unexecAmt ? unexecAmt.toFixed(2) : '';
|
||||
}
|
||||
|
||||
window.toggleBtChip = (chip) => {
|
||||
const cb = chip.querySelector('input');
|
||||
cb.checked = !cb.checked;
|
||||
chip.classList.toggle('bg-blue-50', cb.checked);
|
||||
chip.classList.toggle('border-blue-400', cb.checked);
|
||||
chip.classList.toggle('text-blue-600', cb.checked);
|
||||
};
|
||||
|
||||
window.initTaskTable = (taskData) => {
|
||||
const tbody = document.querySelector("#taskTbody");
|
||||
if (!tbody) return;
|
||||
tbody.innerHTML = "";
|
||||
const rows = taskData || [];
|
||||
rows.forEach(r => addTaskRow(r.task_month || '', r.task_type || '', r.task_count || '', r.task_executed || '', r.unit_price || ''));
|
||||
};
|
||||
|
||||
window.onTaskTypeChange = (sel) => {
|
||||
if (sel.value !== '__custom__') return;
|
||||
const td = sel.parentElement;
|
||||
const oldVal = sel.value;
|
||||
td.innerHTML = `<input name="task_type[]" class="form-ctrl form-ctrl-sm w-full" placeholder="输入自定义类型" autofocus><button type="button" class="btn btn-ghost btn-sm text-slate-400 p-0 w-5 h-5 ml-1" onclick="revertTaskType(this)" title="返回选择"><i data-lucide="rotate-ccw" style="width:12px;height:12px"></i></button>`;
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
td.querySelector('input').focus();
|
||||
};
|
||||
|
||||
window.revertTaskType = (btn) => {
|
||||
const td = btn.parentElement;
|
||||
td.innerHTML = `<select name="task_type[]" class="form-ctrl form-ctrl-sm w-full" onchange="onTaskTypeChange(this)"><option value="">选择</option>${TASK_TYPES.map(t => `<option>${t}</option>`).join("")}<option value="__custom__">自定义...</option></select>`;
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
};
|
||||
|
||||
window.closeFinanceModal = () => {
|
||||
const modal = document.querySelector("#financeModal");
|
||||
modal.classList.add("hidden");
|
||||
};
|
||||
|
||||
window.editPfSignMonth = (event, pfId) => {
|
||||
event.stopPropagation();
|
||||
const pf = (state.data.projectFinances || []).find(x => x.id === pfId);
|
||||
if (!pf) return;
|
||||
const span = event.currentTarget;
|
||||
const td = span.parentElement;
|
||||
const currentValue = pf.sign_month || "";
|
||||
const select = document.createElement("select");
|
||||
select.innerHTML = monthOptions(currentValue);
|
||||
select.className = "form-ctrl form-ctrl-sm w-full";
|
||||
select.value = currentValue;
|
||||
select.addEventListener("change", async () => {
|
||||
const newValue = select.value;
|
||||
try {
|
||||
await api(`/api/projectFinances/${pfId}`, { method: "PUT", body: JSON.stringify({ data: { sign_month: newValue } }) });
|
||||
pf.sign_month = newValue;
|
||||
td.innerHTML = `<span class="pf-sm-text cursor-pointer hover:text-blue-600" onclick="editPfSignMonth(event, ${pfId})">${newValue || '—'}</span>`;
|
||||
} catch (e) { toast("修改失败:" + e.message, "error"); }
|
||||
});
|
||||
select.addEventListener("blur", () => {
|
||||
td.innerHTML = `<span class="pf-sm-text cursor-pointer hover:text-blue-600" onclick="editPfSignMonth(event, ${pfId})">${currentValue || '—'}</span>`;
|
||||
});
|
||||
td.innerHTML = "";
|
||||
td.appendChild(select);
|
||||
select.focus();
|
||||
};
|
||||
|
||||
window.switchFinanceTab = (tab) => {
|
||||
document.querySelectorAll(".finance-tab").forEach(b => b.classList.toggle("active", b.dataset.tab === tab));
|
||||
document.querySelector("#financeTabInfo").classList.toggle("hidden", tab !== "info");
|
||||
document.querySelector("#financeTabBudget").classList.toggle("hidden", tab !== "budget");
|
||||
document.querySelector("#financeTabExec").classList.toggle("hidden", tab !== "exec");
|
||||
document.querySelector("#financeTabTasks").classList.toggle("hidden", tab !== "tasks");
|
||||
document.querySelector("#financeTabActivity").classList.toggle("hidden", tab !== "activity");
|
||||
document.querySelector(".finance-form-actions").classList.toggle("hidden", tab === "activity");
|
||||
if (tab === "activity") initFinSquire();
|
||||
};
|
||||
|
||||
// ---------- 活动与跟进 ----------
|
||||
|
||||
async function loadFinFollowups(pfId) {
|
||||
const list = document.querySelector("#finActivityList");
|
||||
if (!list || !pfId) return;
|
||||
try {
|
||||
const fups = await api(`/api/followups/project_finance/${pfId}`);
|
||||
list.innerHTML = fups.length
|
||||
? fups.map(f => `<div class="activity-item"><div class="activity-icon"><i data-lucide="message-square"></i></div><div class="min-w-0 flex-1"><div class="flex justify-between gap-3 text-[12px] text-slate-500"><span>${esc(f.follower)} · ${esc(f.follow_up_method)}</span><span>${esc(f.followed_at)}</span></div><div class="mt-1 leading-5 text-slate-800 rich-content" data-html="${encodeURIComponent(f.content || '')}"></div>${f.next_action ? `<p class="mt-1 leading-5 text-blue-700">下一步:${text(f.next_action)}</p>` : ""}</div><button class="activity-delete" type="button" onclick="deleteFinFollowup(event, ${f.id})" title="删除评论"><i data-lucide="trash-2"></i></button></div>`).join("")
|
||||
: '<p class="text-sm text-slate-400 py-4 text-center">暂无跟进记录</p>';
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
list.querySelectorAll(".rich-content").forEach(el => {
|
||||
const html = el.dataset.html;
|
||||
if (html) el.innerHTML = decodeURIComponent(html);
|
||||
});
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
function initFinSquire() {
|
||||
const ed = document.querySelector("#squire_finance");
|
||||
if (!ed || !window.Squire) return;
|
||||
if (window.squireInstances["squire_finance"]) { window.squireInstances["squire_finance"].destroy(); }
|
||||
const sq = new Squire(ed, { blockTag: "P" });
|
||||
window.squireInstances["squire_finance"] = sq;
|
||||
ed.addEventListener("focus", () => ed.classList.add("focused"));
|
||||
ed.addEventListener("blur", () => { if (!ed.textContent.trim()) ed.classList.remove("focused"); });
|
||||
}
|
||||
|
||||
window.submitFinComment = async () => {
|
||||
const pfId = document.querySelector("#pf-id-input").value;
|
||||
if (!pfId) return;
|
||||
const sq = window.squireInstances["squire_finance"];
|
||||
const content = sq ? sq.getHTML().trim() : "";
|
||||
if (!content || content === "<div><br></div>" || content === "<p><br></p>") return;
|
||||
const btn = document.querySelector("#financeTabActivity .comment-submit");
|
||||
btn.disabled = true;
|
||||
btn.textContent = "发送中…";
|
||||
await api(`/api/followups/project_finance/${pfId}`, { method: "POST", body: JSON.stringify({ data: { content } }) });
|
||||
sq.setHTML("");
|
||||
btn.disabled = false;
|
||||
btn.textContent = "评论";
|
||||
await loadFinFollowups(pfId);
|
||||
};
|
||||
|
||||
window.deleteFinFollowup = async (event, followupId) => {
|
||||
event.stopPropagation();
|
||||
if (!confirm("确认删除这条评论?")) return;
|
||||
await api(`/api/followups/${followupId}`, { method: "DELETE" });
|
||||
const pfId = document.querySelector("#pf-id-input").value;
|
||||
if (pfId) await loadFinFollowups(pfId);
|
||||
};
|
||||
|
||||
window.openPfEditModal = (pfId) => {
|
||||
const pf = (state.data.projectFinances || []).find(x => x.id === pfId);
|
||||
if (!pf) return;
|
||||
document.querySelector("#pf-id-input").value = pf.id;
|
||||
document.querySelector("#financeModalTitle").textContent = "编辑项目财务";
|
||||
document.querySelector("#financeDeleteBtn").classList.remove("hidden");
|
||||
const form = document.querySelector("#financeModal form");
|
||||
form.querySelector('[name="project_id"]').value = pf.project_id || "";
|
||||
const deptDisplay = form.querySelector('.bg-slate-50 [disabled]');
|
||||
if (deptDisplay) deptDisplay.value = pf.project_id || "";
|
||||
// 回填业务类型多选
|
||||
const btValues = (pf.business_type || "").split(/[,,]/).map(s => s.trim()).filter(Boolean);
|
||||
form.querySelectorAll('[name="business_type[]"]').forEach(cb => {
|
||||
cb.checked = btValues.includes(cb.value);
|
||||
const chip = cb.closest('.bt-chip');
|
||||
if (chip) {
|
||||
chip.classList.toggle('bg-blue-50', cb.checked);
|
||||
chip.classList.toggle('border-blue-400', cb.checked);
|
||||
chip.classList.toggle('text-blue-600', cb.checked);
|
||||
}
|
||||
});
|
||||
form.querySelector('[name="customer_name"]').value = pf.customer_name || "";
|
||||
const setVal = (name, val) => { const el = form.querySelector(`[name="${name}"]`); if (el) el.value = val || ""; };
|
||||
setVal("project_code", pf.project_code);
|
||||
form.querySelector('[name="sign_amount"]').value = pf.sign_amount || "";
|
||||
const signMonthValue = pf.sign_month || "";
|
||||
const signMonthEl = form.querySelector('[name="sign_month"]');
|
||||
if (signMonthEl && signMonthValue) {
|
||||
signMonthEl.innerHTML = monthOptions(signMonthValue);
|
||||
signMonthEl.value = signMonthValue;
|
||||
}
|
||||
form.querySelector('[name="status"]').value = pf.status || "待签约";
|
||||
form.querySelector('[name="sales_person"]').value = pf.sales_person || "";
|
||||
form.querySelector('[name="owner"]').value = pf.owner || "";
|
||||
setVal("start_date", pf.start_date);
|
||||
setVal("end_date", pf.end_date);
|
||||
setVal("task_type", pf.task_type);
|
||||
setVal("task_count", pf.task_count);
|
||||
setVal("service_fee_standard", pf.service_fee_standard || 5);
|
||||
setVal("project_manager", pf.project_manager);
|
||||
setVal("contact_name", pf.contact_name);
|
||||
setVal("contact_phone", pf.contact_phone);
|
||||
setVal("other_info", pf.other_info);
|
||||
let budgetData = [];
|
||||
try { budgetData = JSON.parse(pf.budget_data || "[]"); } catch (e) { budgetData = []; }
|
||||
initBudgetTable(budgetData.length ? budgetData : null);
|
||||
let taskData = [];
|
||||
try { taskData = JSON.parse(pf.task_data || "[]"); } catch (e) { taskData = []; }
|
||||
initTaskTable(taskData.length ? taskData : null);
|
||||
setTimeout(() => updateBudgetSummary(), 100);
|
||||
loadFinFollowups(pf.id);
|
||||
openFinanceModal();
|
||||
};
|
||||
|
||||
window.createFinance = async (event) => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const data = Object.fromEntries(new FormData(form).entries());
|
||||
// 业务类型多选:合并为逗号分隔
|
||||
const btChecked = form.querySelectorAll('[name="business_type[]"]:checked');
|
||||
data.business_type = Array.from(btChecked).map(cb => cb.value).join(",");
|
||||
data.tenant = state.tenant;
|
||||
// 必填校验
|
||||
if (!data.customer_name || !data.customer_name.trim()) { toast("项目名称必填", "error"); return; }
|
||||
if (!data.sales_person || !data.sales_person.trim()) { toast("商务负责人必填", "error"); return; }
|
||||
if (!data.owner || !data.owner.trim()) { toast("经营负责人必填", "error"); return; }
|
||||
if (!data.sign_month) { toast("签约月份必填", "error"); return; }
|
||||
data.sign_amount = parseFloat(data.sign_amount) || 0;
|
||||
if (!(data.sign_amount > 0)) { toast("签约金额必须大于 0", "error"); return; }
|
||||
const months = form.querySelectorAll('[name="budget_month[]"]');
|
||||
const revs = form.querySelectorAll('[name="budget_rev[]"]');
|
||||
const grosses = form.querySelectorAll('[name="budget_gross[]"]');
|
||||
const payments = form.querySelectorAll('[name="budget_payment[]"]');
|
||||
const costs = form.querySelectorAll('[name="budget_cost[]"]');
|
||||
const paids = form.querySelectorAll('[name="budget_paid[]"]');
|
||||
const budgetRows = [];
|
||||
let totalRev = 0, totalGross = 0, totalPaidFromBudget = 0;
|
||||
for (let i = 0; i < months.length; i++) {
|
||||
const m = months[i].value.trim();
|
||||
if (!m) continue;
|
||||
const rev = parseFloat(revs[i].value) || 0;
|
||||
const gross = parseFloat(grosses[i].value) || 0;
|
||||
const payment = parseFloat(payments[i].value) || 0;
|
||||
const cost = parseFloat(costs[i].value) || 0;
|
||||
const paid = parseFloat(paids[i].value) || 0;
|
||||
budgetRows.push({ month: m, rev, gross, payment, cost, paid });
|
||||
totalRev += rev;
|
||||
totalGross += gross;
|
||||
totalPaidFromBudget += paid;
|
||||
}
|
||||
data.budget_data = JSON.stringify(budgetRows);
|
||||
data.total_rev = totalRev;
|
||||
data.total_gross = totalGross;
|
||||
data.total_paid = totalPaidFromBudget;
|
||||
let totalPayment = 0, totalCost = 0;
|
||||
for (const r of budgetRows) { totalPayment += r.payment; totalCost += r.cost; }
|
||||
data.total_payment = totalPayment;
|
||||
data.total_cost = totalCost;
|
||||
// 收集任务管理数据
|
||||
const taskTypeInputs = form.querySelectorAll('[name="task_type[]"]');
|
||||
const taskCountInputs = form.querySelectorAll('[name="task_count[]"]');
|
||||
const taskExecInputs = form.querySelectorAll('[name="task_executed[]"]');
|
||||
const taskRows = [];
|
||||
for (let i = 0; i < taskTypeInputs.length; i++) {
|
||||
const tt = taskTypeInputs[i].value.trim();
|
||||
if (!tt) continue;
|
||||
taskRows.push({
|
||||
task_month: form.querySelectorAll('[name="task_month[]"]')[i].value || '',
|
||||
task_type: tt,
|
||||
task_count: parseFloat(taskCountInputs[i].value) || 0,
|
||||
task_executed: parseFloat(taskExecInputs[i].value) || 0,
|
||||
unit_price: parseFloat(form.querySelectorAll('[name="task_unit_price[]"]')[i].value) || 0,
|
||||
});
|
||||
}
|
||||
data.task_data = JSON.stringify(taskRows);
|
||||
// 清除数组命名的字段(FormData 会收集 task_type[] 等),避免后端写入不存在的列
|
||||
delete data.task_type;
|
||||
delete data.task_count;
|
||||
for (const key of Object.keys(data)) {
|
||||
if (key.endsWith('[]')) delete data[key];
|
||||
}
|
||||
const pfId = data.pf_id;
|
||||
delete data.pf_id;
|
||||
try {
|
||||
if (pfId) {
|
||||
await api("/api/projectFinances/" + pfId, { method: "PUT", body: JSON.stringify({ data }) });
|
||||
if (data.customer_name) logActivity("finance", pfId, "更新了「" + data.customer_name + "」的财务信息");
|
||||
} else {
|
||||
const result = await api("/api/projectFinances", { method: "POST", body: JSON.stringify({ data }) });
|
||||
if (result.id && data.customer_name) logActivity("finance", result.id, "创建了「" + data.customer_name + "」的财务项目");
|
||||
}
|
||||
form.reset();
|
||||
document.querySelector("#pf-id-input").value = "";
|
||||
document.querySelector("#financeModalTitle").textContent = "新增项目财务";
|
||||
closeFinanceModal();
|
||||
await load();
|
||||
} catch (error) {
|
||||
toast("保存失败:" + error.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
window.deleteFinanceItem = async () => {
|
||||
const pfId = document.querySelector("#pf-id-input").value;
|
||||
if (!pfId) return;
|
||||
const pf = (state.data.projectFinances || []).find(x => x.id === parseInt(pfId));
|
||||
const name = pf ? (pf.customer_name || "此项目") : "此项目";
|
||||
if (!confirm(`确认删除「${name}」?此操作不可撤销。`)) return;
|
||||
try {
|
||||
await api(`/api/projectFinances/${pfId}`, { method: "DELETE" });
|
||||
closeFinanceModal();
|
||||
await load();
|
||||
toast("已删除", "success");
|
||||
} catch (error) {
|
||||
toast("删除失败:" + error.message, "error");
|
||||
}
|
||||
};
|
||||
141
static/modules/home.js
Normal file
141
static/modules/home.js
Normal file
@@ -0,0 +1,141 @@
|
||||
// home.js — 首页渲染 + 财务趋势图
|
||||
|
||||
function renderHome() {
|
||||
const { summary, financeMonthly } = state.data;
|
||||
const m = summary.metrics;
|
||||
const moneyInt = (v) => `${Math.round(Number(v || 0)).toLocaleString("zh-CN")} 元`;
|
||||
const rows1 = [
|
||||
["年度累计", moneyInt(m.signed_annual || m.signed_amount)],
|
||||
["季度累计", moneyInt(m.signed_q2 || 0)],
|
||||
["本月新增", moneyInt(m.signed_month || 0)],
|
||||
["上季度累计", moneyInt(m.signed_prev_q || 0)],
|
||||
["上月累计", moneyInt(m.signed_prev_month || 0)],
|
||||
];
|
||||
const rows2 = [
|
||||
["年度累计", moneyInt(m.revenue_annual)],
|
||||
["季度累计", moneyInt(m.revenue_q2)],
|
||||
["本月新增", moneyInt(m.monthly_revenue)],
|
||||
["上季度累计", moneyInt(m.revenue_prev_q || 0)],
|
||||
["上月累计", moneyInt(m.revenue_prev_month || 0)],
|
||||
];
|
||||
const rows3 = [
|
||||
["年度累计", moneyInt(m.gross_annual)],
|
||||
["季度累计", moneyInt(m.gross_q2)],
|
||||
["本月新增", moneyInt(m.monthly_net_profit)],
|
||||
["上季度累计", moneyInt(m.gross_prev_q || 0)],
|
||||
["上月累计", moneyInt(m.gross_prev_month || 0)],
|
||||
];
|
||||
const rows4 = [
|
||||
["年度累计", moneyInt(m.payment_annual || 0)],
|
||||
["季度累计", moneyInt(m.payment_q2 || 0)],
|
||||
["本月新增", moneyInt(m.payment_month || 0)],
|
||||
["上季度累计", moneyInt(m.payment_prev_q || 0)],
|
||||
["上月累计", moneyInt(m.payment_prev_month || 0)],
|
||||
];
|
||||
const rows5 = [
|
||||
["年度累计", moneyInt(m.cost_annual || 0)],
|
||||
["季度累计", moneyInt(m.cost_q2 || 0)],
|
||||
["本月新增", moneyInt(m.cost_month || 0)],
|
||||
["上季度累计", moneyInt(m.cost_prev_q || 0)],
|
||||
["上月累计", moneyInt(m.cost_prev_month || 0)],
|
||||
];
|
||||
let _cardId = 0;
|
||||
const tblCard = (title, rows) => {
|
||||
const id = 'finCard' + (++_cardId);
|
||||
const visible = rows.slice(0, 3);
|
||||
const extra = rows.slice(3);
|
||||
const rowHtml = (r) => r.map(([label, value]) => `<tr class="border-b border-slate-100 last:border-0"><td class="py-2 pr-4 text-slate-500">${label}</td><td class="py-2 text-right font-semibold text-slate-800">${value}</td></tr>`).join("");
|
||||
return card(`<h3 class="text-sm font-bold text-slate-700 mb-3">${title}</h3><table class="w-full text-sm"><tbody>${rowHtml(visible)}</tbody></table><table class="w-full text-sm hidden" id="${id}"><tbody>${rowHtml(extra)}</tbody></table><button class="w-full text-center py-1 text-xs text-slate-400 hover:text-slate-600" onclick="toggleFinCard('${id}')" id="${id}_btn"><i data-lucide="chevron-down" style="width:14px;height:14px;display:inline"></i></button>`, "p-4");
|
||||
};
|
||||
window.toggleFinCard = (id) => {
|
||||
const t = document.getElementById(id);
|
||||
if (!t) return;
|
||||
t.classList.toggle("hidden");
|
||||
const btn = document.getElementById(id + "_btn");
|
||||
btn.innerHTML = t.classList.contains("hidden")
|
||||
? '<i data-lucide="chevron-down" style="width:14px;height:14px;display:inline"></i>'
|
||||
: '<i data-lucide="chevron-up" style="width:14px;height:14px;display:inline"></i>';
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
};
|
||||
document.querySelector("#home").innerHTML = `
|
||||
<div class="grid gap-5">
|
||||
${state.tenant === "总工作台" ? "" : `<div class="grid grid-cols-4 gap-3">
|
||||
${[
|
||||
["经营管理", m.total_projects, "finance"],
|
||||
["重点工作与台账", m.total_proposals, "projects"],
|
||||
["业务方案", m.total_products, "proposals"],
|
||||
["产品迭代", m.upcoming_products, "products"],
|
||||
].map(([label, value, tab]) => `<button class="metric-card" onclick="switchTab('${tab}')"><span class="flex items-center gap-2 text-xs text-slate-500"><i data-lucide="gauge"></i>${label}</span><strong class="mt-2 block text-2xl">${value}</strong></button>`).join("")}
|
||||
</div>`}
|
||||
<div class="grid grid-cols-5 gap-5">${tblCard("合同金额", rows1)}${tblCard("确收金额", rows2)}${tblCard("确收毛利", rows3)}${tblCard("回款金额", rows4)}${tblCard("费用金额", rows5)}</div>
|
||||
<div class="grid grid-cols-3 gap-5">
|
||||
${card(`<div class="mb-3 flex items-center justify-between"><h2 class="text-sm font-bold text-slate-600">月度签约趋势</h2><span class="text-xs text-slate-400">2026</span></div><div style="position:relative;height:200px"><canvas id="chartSign"></canvas></div>`, "p-4")}
|
||||
${card(`<div class="mb-3 flex items-center justify-between"><h2 class="text-sm font-bold text-slate-600">月度确收与毛利</h2><span class="text-xs text-slate-400">2026</span></div><div style="position:relative;height:200px"><canvas id="chartRev"></canvas></div>`, "p-4")}
|
||||
${card(`<div class="mb-3 flex items-center justify-between"><h2 class="text-sm font-bold text-slate-600">月度回款与费用</h2><span class="text-xs text-slate-400">2026</span></div><div style="position:relative;height:200px"><canvas id="chartCash"></canvas></div>`, "p-4")}
|
||||
</div>
|
||||
${card(`<h2 class="text-lg font-bold">近期动态</h2><div class="mt-4 grid gap-2">${summary.recent.map((r) => `<div class="flex items-start justify-between rounded-md bg-slate-50 px-3 py-2 text-sm group"><span class="break-words">${r.content}</span><div class="flex items-center gap-2 flex-shrink-0 ml-2"><span class="text-xs text-slate-400">${r.followed_at}</span><button class="btn btn-ghost btn-sm text-red-400 opacity-0 group-hover:opacity-100 p-0 w-5 h-5" onclick="event.preventDefault();deleteActivity(${r.id})" title="删除动态"><i data-lucide="trash-2" style="width:14px;height:14px"></i></button></div></div>`).join("")}</div>`, "p-5")}
|
||||
</div>
|
||||
`;
|
||||
renderCharts(financeMonthly);
|
||||
}
|
||||
|
||||
function chartOptions(yCallback) {
|
||||
return {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: { legend: { position: "bottom", labels: { boxWidth: 12, font: { size: 11 } } } },
|
||||
scales: {
|
||||
x: { ticks: { font: { size: 10 } }, grid: { display: false } },
|
||||
y: { ticks: { font: { size: 11 }, callback: yCallback } },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const moneyTick = (v) => v >= 10000 ? (v / 10000).toFixed(0) + "万" : v;
|
||||
const monthLabels = (data) => data.map((x) => parseInt(x.month.split("-")[1]) + "月");
|
||||
|
||||
function renderCharts(data) {
|
||||
const labels = monthLabels(data);
|
||||
const baseOpts = chartOptions(moneyTick);
|
||||
|
||||
// 图1:月度签约
|
||||
const c1 = document.querySelector("#chartSign");
|
||||
if (c1 && window.Chart) {
|
||||
if (state.chart) state.chart.destroy();
|
||||
state.chart = new Chart(c1, {
|
||||
type: "line",
|
||||
data: { labels, datasets: [
|
||||
{ label: "签约金额", data: data.map((x) => x.sign || 0), borderColor: "#6366f1", backgroundColor: "rgba(99,102,241,0.06)", fill: true, tension: 0.3 },
|
||||
]},
|
||||
options: baseOpts,
|
||||
});
|
||||
}
|
||||
|
||||
// 图2:月度确收与毛利
|
||||
const c2 = document.querySelector("#chartRev");
|
||||
if (c2 && window.Chart) {
|
||||
if (state.chart2) state.chart2.destroy();
|
||||
state.chart2 = new Chart(c2, {
|
||||
type: "line",
|
||||
data: { labels, datasets: [
|
||||
{ label: "确收", data: data.map((x) => x.revenue || 0), borderColor: "#2563eb", backgroundColor: "rgba(37,99,235,0.06)", fill: true, tension: 0.3 },
|
||||
{ label: "毛利", data: data.map((x) => x.gross || 0), borderColor: "#059669", backgroundColor: "rgba(5,150,105,0.06)", fill: true, tension: 0.3 },
|
||||
]},
|
||||
options: baseOpts,
|
||||
});
|
||||
}
|
||||
|
||||
// 图3:月度回款与费用
|
||||
const c3 = document.querySelector("#chartCash");
|
||||
if (c3 && window.Chart) {
|
||||
if (state.chart3) state.chart3.destroy();
|
||||
state.chart3 = new Chart(c3, {
|
||||
type: "bar",
|
||||
data: { labels, datasets: [
|
||||
{ label: "回款", data: data.map((x) => x.payment || 0), backgroundColor: "#d97706", borderRadius: 4 },
|
||||
{ label: "费用", data: data.map((x) => x.cost || 0), backgroundColor: "#ef4444", borderRadius: 4 },
|
||||
]},
|
||||
options: baseOpts,
|
||||
});
|
||||
}
|
||||
}
|
||||
344
static/modules/products.js
Normal file
344
static/modules/products.js
Normal file
@@ -0,0 +1,344 @@
|
||||
// products.js — 产品迭代模块
|
||||
|
||||
function formHtml(fields, button) {
|
||||
return `<form class="inline-form flex flex-wrap items-end gap-3" onsubmit="${button.handler}(event)">
|
||||
${fields.map((f) => `<label class="grid gap-1 text-sm"><span class="font-bold text-slate-600">${f.label}</span>${f.input}</label>`).join("")}
|
||||
<button class="btn btn-primary" type="submit">${button.text}</button>
|
||||
</form>`;
|
||||
}
|
||||
|
||||
async function createResource(event, resource) {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const data = Object.fromEntries(new FormData(form).entries());
|
||||
data.tenant = state.tenant;
|
||||
try {
|
||||
const result = await api(`/api/${resource}`, { method: "POST", body: JSON.stringify({ data }) });
|
||||
const targetMap = { sales: "sales", proposals: "proposal", operations: "operation", products: "product" };
|
||||
const resType = targetMap[resource] || resource;
|
||||
const name = data.project_name || data.target_customer || data.customer_or_project_name || data.product_name || "";
|
||||
if (result.id && name) logActivity(resType, result.id, "创建了" + name);
|
||||
form.reset();
|
||||
await load();
|
||||
} catch (error) {
|
||||
toast("创建失败:" + error.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
window.createSales = (event) => createResource(event, "sales");
|
||||
window.createProposal = (event) => createResource(event, "proposals");
|
||||
window.createOperation = async (event) => {
|
||||
await createResource(event, "operations");
|
||||
if (typeof closeNewProjectModal === "function") closeNewProjectModal();
|
||||
};
|
||||
|
||||
window.openProductDrawer = () => {
|
||||
const drawer = document.querySelector("#productDrawer");
|
||||
drawer.innerHTML = `<div class="task-drawer-hd">
|
||||
<span class="task-drawer-title">新增产品版本</span>
|
||||
<button class="task-close" onclick="closeProductDrawer()"><i data-lucide="x"></i></button>
|
||||
</div>
|
||||
<form class="task-drawer-form" onsubmit="submitProductDrawer(event)">
|
||||
<label class="task-field"><span>版本名称</span><input name="product_name" required class="form-ctrl"></label>
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<label class="task-field"><span>版本号</span><input name="version" required class="form-ctrl"></label>
|
||||
<label class="task-field"><span>优先级</span><select name="priority" class="form-ctrl"><option>P0</option><option selected>P1</option><option>P2</option><option>P3</option></select></label>
|
||||
</div>
|
||||
<label class="task-field"><span>版本目标</span><textarea name="version_goal" rows="3" class="form-ctrl"></textarea></label>
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<label class="task-field"><span>启动时间 <span class="text-red-500">*</span></span><input name="start_date" type="date" required class="form-ctrl"></label>
|
||||
<label class="task-field"><span>产品方案</span><input name="plan_date" type="date" class="form-ctrl"></label>
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<label class="task-field"><span>研发完成</span><input name="dev_done_date" type="date" class="form-ctrl"></label>
|
||||
<label class="task-field"><span>测试</span><input name="test_date" type="date" class="form-ctrl"></label>
|
||||
</div>
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<label class="task-field"><span>上线时间</span><input name="launch_date" type="date" class="form-ctrl"></label>
|
||||
<label class="task-field"><span>状态</span><select name="status" class="form-ctrl"><option>未开始</option><option>规划中</option><option>开发中</option><option>测试中</option><option>已上线</option><option>已取消</option></select></label>
|
||||
</div>
|
||||
<label class="task-field"><span>进展备注</span><textarea name="notes" rows="3" class="form-ctrl"></textarea></label>
|
||||
<div class="flex justify-end gap-2 mt-4 pt-3 border-t border-slate-100">
|
||||
<button type="button" class="btn btn-ghost btn-sm" onclick="closeProductDrawer()">取消</button>
|
||||
<button type="submit" class="btn btn-primary btn-sm">确认新增</button>
|
||||
</div>
|
||||
</form>`;
|
||||
drawer.classList.add("open");
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
};
|
||||
|
||||
window.closeProductDrawer = () => {
|
||||
document.querySelector("#productDrawer").classList.remove("open");
|
||||
};
|
||||
|
||||
window.cycleProductStatus = async (id) => {
|
||||
const products = state.data.products || [];
|
||||
const product = products.find(x => x.id === id);
|
||||
if (!product) return;
|
||||
const statuses = ["未开始", "规划中", "开发中", "测试中", "已上线", "已取消"];
|
||||
const current = statuses.indexOf(product.status) >= 0 ? product.status : "规划中";
|
||||
const newStatus = statuses[(statuses.indexOf(current) + 1) % statuses.length];
|
||||
try {
|
||||
await api(`/api/products/${id}`, { method: "PUT", body: JSON.stringify({ data: { status: newStatus } }) });
|
||||
product.status = newStatus;
|
||||
renderProducts();
|
||||
} catch (error) {
|
||||
toast("更新失败:" + error.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
window.editProductDate = (event, id) => {
|
||||
event.stopPropagation();
|
||||
const products = state.data.products || [];
|
||||
const product = products.find(x => x.id === id);
|
||||
if (!product) return;
|
||||
const span = event.currentTarget;
|
||||
const td = span.parentElement;
|
||||
const currentValue = product.launch_date || "";
|
||||
const input = document.createElement("input");
|
||||
input.type = "date";
|
||||
input.className = "form-ctrl form-ctrl-sm w-full";
|
||||
input.value = currentValue;
|
||||
input.addEventListener("change", async () => {
|
||||
const newValue = input.value;
|
||||
try {
|
||||
await api(`/api/products/${id}`, { method: "PUT", body: JSON.stringify({ data: { launch_date: newValue } }) });
|
||||
product.launch_date = newValue;
|
||||
td.innerHTML = `<span class="cursor-pointer hover:text-blue-600" onclick="editProductDate(event, ${id})">${newValue || '—'}</span>`;
|
||||
} catch (e) { toast("修改失败:" + e.message, "error"); }
|
||||
});
|
||||
input.addEventListener("blur", () => {
|
||||
td.innerHTML = `<span class="cursor-pointer hover:text-blue-600" onclick="editProductDate(event, ${id})">${currentValue || '—'}</span>`;
|
||||
});
|
||||
td.innerHTML = "";
|
||||
td.appendChild(input);
|
||||
input.focus();
|
||||
};
|
||||
|
||||
window.addNewFeature = () => {};
|
||||
window.removeNewFeature = () => {};
|
||||
window.addFeature = () => {};
|
||||
window.removeFeature = () => {};
|
||||
window.saveFeatureList = () => {};
|
||||
|
||||
window.submitProductDrawer = async (event) => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const data = Object.fromEntries(new FormData(form).entries());
|
||||
// 约束:4 个时间不能早于启动时间
|
||||
const startDate = data.start_date;
|
||||
if (startDate) {
|
||||
for (const f of ['plan_date', 'dev_done_date', 'test_date', 'launch_date']) {
|
||||
if (data[f] && data[f] < startDate) {
|
||||
toast("「" + ({plan_date:'产品方案',dev_done_date:'研发完成',test_date:'测试完成',launch_date:'上线时间'}[f]) + "」不能早于启动时间", "error");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
data.tenant = state.tenant;
|
||||
try {
|
||||
const result = await api("/api/products", { method: "POST", body: JSON.stringify({ data }) });
|
||||
form.reset();
|
||||
closeProductDrawer();
|
||||
if (result.id) logActivity("product", result.id, "创建了产品版本「" + data.product_name + " " + data.version + "」");
|
||||
await load();
|
||||
} catch (error) {
|
||||
toast("创建失败:" + error.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
window.addFeature = () => {};
|
||||
window.removeFeature = () => {};
|
||||
window.saveFeatureList = () => {};
|
||||
|
||||
// 排序状态
|
||||
let productSort = { field: null, dir: 1 };
|
||||
|
||||
window.sortProducts = (field) => {
|
||||
if (productSort.field === field) {
|
||||
productSort.dir = -productSort.dir;
|
||||
} else {
|
||||
productSort.field = field;
|
||||
productSort.dir = 1;
|
||||
}
|
||||
renderProducts();
|
||||
};
|
||||
|
||||
function sortItems(items) {
|
||||
if (!productSort.field) return items;
|
||||
const f = productSort.field;
|
||||
const d = productSort.dir;
|
||||
const priorityOrder = { P0: 0, P1: 1, P2: 2, P3: 3 };
|
||||
return [...items].sort((a, b) => {
|
||||
let va = a[f] || '', vb = b[f] || '';
|
||||
if (f === 'priority') { va = priorityOrder[va] ?? 9; vb = priorityOrder[vb] ?? 9; }
|
||||
if (va < vb) return -1 * d;
|
||||
if (va > vb) return 1 * d;
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
function renderProducts() {
|
||||
const rawItems = state.data.products || [];
|
||||
const items = sortItems(rawItems);
|
||||
const priorityColor = { P0: "bg-red-100 text-red-700", P1: "bg-orange-100 text-orange-700", P2: "bg-blue-100 text-blue-700", P3: "bg-slate-100 text-slate-600" };
|
||||
const sortIcon = (f) => {
|
||||
if (productSort.field !== f) return '<i data-lucide="chevrons-up-down" style="width:12px;height:12px;opacity:0.3"></i>';
|
||||
return productSort.dir > 0 ? '<i data-lucide="chevron-up" style="width:12px;height:12px"></i>' : '<i data-lucide="chevron-down" style="width:12px;height:12px"></i>';
|
||||
};
|
||||
const sortTh = (f, label, extra='') => `<th class="px-3 py-2.5 font-semibold align-middle whitespace-nowrap cursor-pointer hover:text-blue-600 select-none" onclick="sortProducts('${f}')"><span class="inline-flex items-center gap-1">${label}${sortIcon(f)}</span>${extra}</th>`;
|
||||
document.querySelector("#products").innerHTML = `
|
||||
<div class="grid gap-4">
|
||||
<div class="flex justify-end">
|
||||
<button class="btn btn-primary btn-sm" onclick="openProductDrawer()"><i data-lucide="plus"></i>新增产品版本</button>
|
||||
</div>
|
||||
<div class="card overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead class="bg-slate-50 border-b border-slate-200">
|
||||
<tr class="text-left text-xs text-slate-500 uppercase tracking-wider">
|
||||
${sortTh('version','版本号')}
|
||||
${sortTh('priority','优先级')}
|
||||
${sortTh('product_name','版本名称')}
|
||||
${sortTh('status','状态')}
|
||||
${sortTh('start_date','启动时间')}
|
||||
${sortTh('plan_date','产品方案')}
|
||||
${sortTh('dev_done_date','研发完成')}
|
||||
${sortTh('test_date','测试完成')}
|
||||
${sortTh('launch_date','上线时间')}
|
||||
<th class="px-3 py-2.5 font-semibold align-middle whitespace-nowrap">总耗时</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-slate-100">
|
||||
${items.length === 0 ? `<tr><td colspan="10" class="px-3 py-8 text-center text-slate-400">暂无产品版本,点击右上角新增</td></tr>` : items.map((p) => {
|
||||
const days = (s, e) => { if (!s || !e) return '-'; const d = Math.round((new Date(e) - new Date(s)) / 86400000); return d >= 0 ? d + '天' : '-'; };
|
||||
return `
|
||||
<tr class="hover:bg-slate-50 cursor-pointer transition-colors" onclick="openDrawer('products', ${p.id})">
|
||||
<td class="px-3 py-2.5 whitespace-nowrap text-slate-600 align-middle">${esc(p.version) || '—'}</td>
|
||||
<td class="px-3 py-2.5 whitespace-nowrap align-middle"><span class="inline-block px-2 py-0.5 rounded text-xs font-medium ${priorityColor[p.priority] || priorityColor.P2}" onclick="event.stopPropagation();cyclePriority(${p.id})">${esc(p.priority) || 'P2'}</span></td>
|
||||
<td class="px-3 py-2.5 font-medium text-slate-800 max-w-[180px] truncate align-middle" title="${esc(p.product_name)}">${esc(p.product_name) || '—'}</td>
|
||||
<td class="px-3 py-2.5 whitespace-nowrap align-middle"><span class="status-badge status-${esc(p.status)}" onclick="event.stopPropagation();cycleProductStatus(${p.id})">${esc(p.status) || '规划中'}</span></td>
|
||||
<td class="px-3 py-2.5 whitespace-nowrap text-slate-500 text-xs align-middle" onclick="event.stopPropagation()"><input type="date" value="${esc(p.start_date) || ''}" data-id="${p.id}" data-field="start_date" class="prod-date-input" onchange="saveProductDate(this)"></td>
|
||||
<td class="px-3 py-2.5 whitespace-nowrap text-slate-500 text-xs align-middle" onclick="event.stopPropagation()"><input type="date" value="${esc(p.plan_date) || ''}" data-id="${p.id}" data-field="plan_date" class="prod-date-input" onchange="saveProductDate(this)"></td>
|
||||
<td class="px-3 py-2.5 whitespace-nowrap text-slate-500 text-xs align-middle" onclick="event.stopPropagation()"><input type="date" value="${esc(p.dev_done_date) || ''}" data-id="${p.id}" data-field="dev_done_date" class="prod-date-input" onchange="saveProductDate(this)"></td>
|
||||
<td class="px-3 py-2.5 whitespace-nowrap text-slate-500 text-xs align-middle" onclick="event.stopPropagation()"><input type="date" value="${esc(p.test_date) || ''}" data-id="${p.id}" data-field="test_date" class="prod-date-input" onchange="saveProductDate(this)"></td>
|
||||
<td class="px-3 py-2.5 whitespace-nowrap text-slate-600 text-xs align-middle" onclick="event.stopPropagation()"><input type="date" value="${esc(p.launch_date) || ''}" data-id="${p.id}" data-field="launch_date" class="prod-date-input" onchange="saveProductDate(this)"></td>
|
||||
<td class="px-3 py-2.5 whitespace-nowrap text-slate-500 text-xs align-middle">${days(p.start_date, p.launch_date)}</td>
|
||||
</tr>`;
|
||||
}).join("")}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<aside id="productDrawer" class="task-drawer"></aside>
|
||||
`;
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
|
||||
window.saveProductDate = async (input) => {
|
||||
const id = Number(input.dataset.id);
|
||||
const field = input.dataset.field;
|
||||
const value = input.value;
|
||||
// 直接从同一行 DOM 读取启动时间(不依赖 state 缓存)
|
||||
const row = input.closest('tr');
|
||||
const startDateInput = row && row.querySelector('[data-field="start_date"]');
|
||||
const startDate = startDateInput ? startDateInput.value : '';
|
||||
const product = (state.data.products || []).find(x => x.id === id);
|
||||
if (!product) return;
|
||||
|
||||
// 启动时间必填
|
||||
if (field === 'start_date' && !value) {
|
||||
toast("启动时间为必填项", "error");
|
||||
input.value = product.start_date || '';
|
||||
input.focus();
|
||||
return;
|
||||
}
|
||||
// 约束:除启动时间外的 4 个时间不能早于启动时间
|
||||
if (field !== 'start_date' && value && startDate && value < startDate) {
|
||||
toast("该时间不能早于启动时间(" + startDate + ")", "error");
|
||||
input.value = product[field] || '';
|
||||
input.focus();
|
||||
return;
|
||||
}
|
||||
// 启动时间变更后,如果其他时间早于新启动时间,清空
|
||||
if (field === 'start_date' && value) {
|
||||
const fields = ['plan_date', 'dev_done_date', 'test_date', 'launch_date'];
|
||||
const toClear = {};
|
||||
for (const f of fields) {
|
||||
if (product[f] && product[f] < value) {
|
||||
toClear[f] = '';
|
||||
}
|
||||
}
|
||||
if (Object.keys(toClear).length > 0) {
|
||||
try {
|
||||
await api(`/api/products/${id}`, { method: "PUT", body: JSON.stringify({ data: { ...toClear, start_date: value } }) });
|
||||
Object.assign(product, toClear, { start_date: value });
|
||||
toast("启动时间已更新," + Object.keys(toClear).length + " 个早于启动时间的日期已清空", "info");
|
||||
renderProducts();
|
||||
return;
|
||||
} catch (e) {
|
||||
toast("修改失败:" + e.message, "error");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
try {
|
||||
await api(`/api/products/${id}`, { method: "PUT", body: JSON.stringify({ data: { [field]: value } }) });
|
||||
product[field] = value;
|
||||
if (field === 'start_date' || field === 'launch_date') {
|
||||
renderProducts();
|
||||
}
|
||||
} catch (e) {
|
||||
toast("修改失败:" + e.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
window.editProductDateInline = (event, id, field) => {
|
||||
event.stopPropagation();
|
||||
const products = state.data.products || [];
|
||||
const product = products.find(x => x.id === id);
|
||||
if (!product) return;
|
||||
const td = event.currentTarget;
|
||||
const currentValue = product[field] || "";
|
||||
const input = document.createElement("input");
|
||||
input.type = "date";
|
||||
input.className = "form-ctrl form-ctrl-sm w-full text-xs";
|
||||
input.value = currentValue;
|
||||
let saved = false;
|
||||
const save = async () => {
|
||||
if (saved) return;
|
||||
saved = true;
|
||||
const newValue = input.value;
|
||||
try {
|
||||
await api(`/api/products/${id}`, { method: "PUT", body: JSON.stringify({ data: { [field]: newValue } }) });
|
||||
product[field] = newValue;
|
||||
td.innerHTML = newValue || '—';
|
||||
} catch (e) {
|
||||
toast("修改失败:" + e.message, "error");
|
||||
td.innerHTML = currentValue || '—';
|
||||
}
|
||||
};
|
||||
input.addEventListener("change", save);
|
||||
input.addEventListener("blur", () => {
|
||||
if (!saved) td.innerHTML = currentValue || '—';
|
||||
});
|
||||
td.innerHTML = "";
|
||||
td.appendChild(input);
|
||||
input.focus();
|
||||
if (input.showPicker) {
|
||||
try { input.showPicker(); } catch (e) {}
|
||||
}
|
||||
};
|
||||
|
||||
window.cyclePriority = async (id) => {
|
||||
const products = state.data.products || [];
|
||||
const product = products.find(x => x.id === id);
|
||||
if (!product) return;
|
||||
const levels = ["P0", "P1", "P2", "P3"];
|
||||
const cur = levels.indexOf(product.priority) >= 0 ? product.priority : "P2";
|
||||
const next = levels[(levels.indexOf(cur) + 1) % levels.length];
|
||||
try {
|
||||
await api(`/api/products/${id}`, { method: "PUT", body: JSON.stringify({ data: { priority: next } }) });
|
||||
product.priority = next;
|
||||
renderProducts();
|
||||
} catch (e) { toast("更新失败:" + e.message, "error"); }
|
||||
};
|
||||
563
static/modules/projects.js
Normal file
563
static/modules/projects.js
Normal file
@@ -0,0 +1,563 @@
|
||||
// projects.js — 重点工作与台账(项目管理 + 任务管理)
|
||||
|
||||
function applyUserTenants() {
|
||||
fetch("/api/auth/me").then(r => r.json()).then(data => {
|
||||
if (!data.logged_in) { window.location.href = "/login"; return; }
|
||||
const user = data.user;
|
||||
const avatar = document.querySelector("#userAvatar");
|
||||
avatar.textContent = user.display_name.charAt(0);
|
||||
avatar.title = user.display_name;
|
||||
const nameEl = document.querySelector("#userDisplayName");
|
||||
if (nameEl) { nameEl.textContent = user.display_name; nameEl.title = user.display_name; }
|
||||
avatar.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
toggleUserMenu(user);
|
||||
});
|
||||
// 缓存可用工作台列表,供下拉菜单使用
|
||||
state.allowedTenants = data.tenants || [];
|
||||
updateTenantLabel();
|
||||
});
|
||||
}
|
||||
|
||||
window.toggleTenantMenu = (event) => {
|
||||
event.stopPropagation();
|
||||
let menu = document.getElementById("tenantMenu");
|
||||
if (menu) { menu.remove(); return; }
|
||||
const btn = event.currentTarget;
|
||||
const rect = btn.getBoundingClientRect();
|
||||
const tenants = state.allowedTenants || [];
|
||||
menu = document.createElement("div");
|
||||
menu.id = "tenantMenu";
|
||||
menu.className = "fixed bg-white rounded-lg shadow-xl border border-slate-200 py-1 min-w-[160px] z-[9999]";
|
||||
menu.style.left = Math.min(rect.left - 8, window.innerWidth - 180) + "px";
|
||||
menu.style.top = rect.bottom + 6 + "px";
|
||||
menu.innerHTML = `
|
||||
<div class="px-4 py-2 border-b border-slate-100">
|
||||
<p class="text-xs font-semibold text-slate-500 uppercase tracking-wider">切换工作台</p>
|
||||
</div>
|
||||
${tenants.map(t => `
|
||||
<button class="w-full text-left px-4 py-2 text-sm hover:bg-slate-50 transition-colors flex items-center justify-between gap-2 ${t === state.tenant ? 'text-blue-600 font-medium' : 'text-slate-700'}" onclick="switchTenantFromMenu('${t.replace(/'/g, "\\'")}')">
|
||||
<span>${esc(t)}</span>
|
||||
${t === state.tenant ? '<i data-lucide="check" style="width:14px;height:14px"></i>' : ''}
|
||||
</button>
|
||||
`).join('')}`;
|
||||
document.body.appendChild(menu);
|
||||
if (window.lucide) lucide.createIcons();
|
||||
setTimeout(() => {
|
||||
document.addEventListener("click", function closeMenu() {
|
||||
menu.remove();
|
||||
document.removeEventListener("click", closeMenu);
|
||||
}, { once: true });
|
||||
}, 10);
|
||||
};
|
||||
|
||||
window.switchTenantFromMenu = (tenant) => {
|
||||
document.getElementById("tenantMenu")?.remove();
|
||||
switchTenant(tenant);
|
||||
};
|
||||
|
||||
function updateTenantLabel() {
|
||||
const label = document.querySelector("#currentTenantLabel");
|
||||
if (label) {
|
||||
label.textContent = state.tenant.replace("·无界", "") || "工作台";
|
||||
label.title = state.tenant;
|
||||
}
|
||||
}
|
||||
|
||||
window.toggleUserMenu = (user) => {
|
||||
let menu = document.getElementById("userMenu");
|
||||
if (menu) { menu.remove(); return; }
|
||||
const avatar = document.querySelector("#userAvatar");
|
||||
const rect = avatar.getBoundingClientRect();
|
||||
menu = document.createElement("div");
|
||||
menu.id = "userMenu";
|
||||
menu.className = "fixed bg-white rounded-lg shadow-xl border border-slate-200 py-1 min-w-[160px] z-[9999]";
|
||||
menu.style.left = Math.min(rect.left - 8, window.innerWidth - 180) + "px";
|
||||
menu.style.top = rect.bottom + 6 + "px";
|
||||
menu.innerHTML = `
|
||||
<div class="px-4 py-3 border-b border-slate-100">
|
||||
<p class="text-sm font-semibold text-slate-800">${esc(user.display_name)}</p>
|
||||
<p class="text-xs text-slate-500 mt-0.5">${esc(user.username || "")}</p>
|
||||
</div>
|
||||
${user.role === 'admin' ? `<button class="w-full text-left px-4 py-2 text-sm text-slate-700 hover:bg-slate-50 transition-colors flex items-center gap-2" onclick="closeUserMenu();openAdminUsers()">
|
||||
<i data-lucide="users" style="width:14px;height:14px"></i>账号管理
|
||||
</button>` : ''}
|
||||
<button class="w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors flex items-center gap-2" onclick="doLogout()">
|
||||
<i data-lucide="log-out" style="width:14px;height:14px"></i>退出登录
|
||||
</button>`;
|
||||
document.body.appendChild(menu);
|
||||
if (window.lucide) lucide.createIcons();
|
||||
setTimeout(() => {
|
||||
document.addEventListener("click", function closeMenu() {
|
||||
menu.remove();
|
||||
document.removeEventListener("click", closeMenu);
|
||||
}, { once: true });
|
||||
}, 10);
|
||||
};
|
||||
|
||||
window.closeUserMenu = () => {
|
||||
const m = document.getElementById("userMenu");
|
||||
if (m) m.remove();
|
||||
};
|
||||
|
||||
window.selectProject = (id) => {
|
||||
state.selectedProject = id;
|
||||
document.querySelectorAll(".project-tree-node").forEach((el) => el.classList.toggle("active", parseInt(el.dataset.id) === id));
|
||||
renderProjectTasks(id);
|
||||
};
|
||||
|
||||
window.togglePhase = (phaseId) => {
|
||||
const wrap = document.querySelector(`#${phaseId}`);
|
||||
if (!wrap) return;
|
||||
wrap.classList.toggle("collapsed");
|
||||
const toggle = document.querySelector(`#${phaseId}-toggle`);
|
||||
if (toggle) toggle.style.transform = wrap.classList.contains("collapsed") ? "rotate(-90deg)" : "";
|
||||
};
|
||||
|
||||
window.showProjectContext = (event, id) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const menu = document.querySelector("#projectContextMenu");
|
||||
if (!menu) return;
|
||||
menu.dataset.projectId = id;
|
||||
menu.style.left = event.clientX + "px";
|
||||
menu.style.top = event.clientY + "px";
|
||||
menu.classList.remove("hidden");
|
||||
};
|
||||
|
||||
window.openProjectDrawer = () => {
|
||||
const menu = document.querySelector("#projectContextMenu");
|
||||
if (menu) {
|
||||
const id = parseInt(menu.dataset.projectId);
|
||||
if (id) openDrawer("operations", id);
|
||||
}
|
||||
};
|
||||
|
||||
window.renameProject = async () => {
|
||||
const menu = document.querySelector("#projectContextMenu");
|
||||
if (!menu) return;
|
||||
const id = parseInt(menu.dataset.projectId);
|
||||
if (!id) return;
|
||||
const project = (state.data.operations || []).find(x => x.id === id);
|
||||
if (!project) return;
|
||||
const newName = prompt("请输入新的项目名称:", project.project_name);
|
||||
if (!newName || newName.trim() === project.project_name) return;
|
||||
try {
|
||||
await api(`/api/operations/${id}`, { method: "PUT", body: JSON.stringify({ data: { project_name: newName.trim() } }) });
|
||||
project.project_name = newName.trim();
|
||||
renderProjects();
|
||||
toast("已重命名", "success");
|
||||
} catch (error) {
|
||||
toast("重命名失败:" + error.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
window.duplicateProject = async () => {
|
||||
const menu = document.querySelector("#projectContextMenu");
|
||||
if (!menu) return;
|
||||
const id = parseInt(menu.dataset.projectId);
|
||||
if (!id) return;
|
||||
const project = (state.data.operations || []).find(x => x.id === id);
|
||||
if (!project) return;
|
||||
const newName = prompt("请输入副本项目名称:", project.project_name + " - 副本");
|
||||
if (!newName) return;
|
||||
try {
|
||||
const result = await api("/api/operations", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ data: {
|
||||
project_name: newName.trim(),
|
||||
project_version: project.project_version || "v1.0",
|
||||
project_type: project.project_type || "opportunity",
|
||||
project_status: project.project_status || "",
|
||||
current_stage: project.current_stage || "",
|
||||
owner: project.owner || "慰心",
|
||||
target_customer: project.target_customer || "",
|
||||
customer_need: project.customer_need || "",
|
||||
expected_contract_amount: project.expected_contract_amount || 0,
|
||||
expected_sign_date: project.expected_sign_date || "",
|
||||
sign_probability: project.sign_probability || 0,
|
||||
next_action: project.next_action || "",
|
||||
sop_stage: project.sop_stage || "",
|
||||
execution_progress: project.execution_progress || 0,
|
||||
current_deliverable: project.current_deliverable || "",
|
||||
risks: project.risks || "",
|
||||
notes: project.notes || "",
|
||||
tenant: state.tenant,
|
||||
}}),
|
||||
});
|
||||
// 复制任务
|
||||
const tasks = (state.data.tasks || []).filter(t => t.project_id === id);
|
||||
for (const t of tasks) {
|
||||
await api("/api/tasks", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ data: {
|
||||
project_id: result.id,
|
||||
phase: t.phase || "",
|
||||
milestone: t.milestone || "",
|
||||
task: t.task || "",
|
||||
owner: t.owner || "",
|
||||
due_date: t.due_date || "",
|
||||
blockers: t.blockers || "",
|
||||
notes: t.notes || "",
|
||||
status: "未开始",
|
||||
priority: t.priority || "P2",
|
||||
sort_order: t.sort_order || 0,
|
||||
tenant: state.tenant,
|
||||
}}),
|
||||
});
|
||||
}
|
||||
toast("已创建副本", "success");
|
||||
await load();
|
||||
} catch (error) {
|
||||
toast("创建副本失败:" + error.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
window.hideProjectContext = () => {
|
||||
const menu = document.querySelector("#projectContextMenu");
|
||||
if (menu) menu.classList.add("hidden");
|
||||
};
|
||||
|
||||
window.openNewProjectModal = () => {
|
||||
document.querySelector("#newProjectModal").classList.remove("hidden");
|
||||
};
|
||||
|
||||
window.closeNewProjectModal = () => {
|
||||
document.querySelector("#newProjectModal").classList.add("hidden");
|
||||
};
|
||||
|
||||
function renderProjects() {
|
||||
const items = state.data.operations;
|
||||
if (!state.selectedProject && items.length > 0) {
|
||||
state.selectedProject = items[0].id;
|
||||
}
|
||||
const tasks = state.data.tasks || [];
|
||||
const taskStats = {
|
||||
total: tasks.length,
|
||||
ongoing: tasks.filter(t => t.status === '进行中').length,
|
||||
done: tasks.filter(t => t.status === '已结束').length,
|
||||
pending: tasks.filter(t => t.status === '未开始').length,
|
||||
};
|
||||
document.querySelector("#projects").innerHTML = /*html*/`
|
||||
<div class="grid grid-cols-5 gap-3 mb-4">
|
||||
${[
|
||||
["项目总数", items.length, "folder"],
|
||||
["任务总数", taskStats.total, "list-checks"],
|
||||
["进行中", taskStats.ongoing, "play-circle"],
|
||||
["已结束", taskStats.done, "check-circle"],
|
||||
["未开始", taskStats.pending, "circle"],
|
||||
].map(([label, value, icon]) => `
|
||||
<div class="metric-card"><span class="flex items-center gap-2 text-xs text-slate-500"><i data-lucide="${icon}" style="width:14px;height:14px"></i>${label}</span><strong class="mt-2 block text-2xl">${value}</strong></div>
|
||||
`).join("")}
|
||||
</div>
|
||||
<div class="flex justify-between items-center mb-3">
|
||||
<div class="flex items-center gap-1" id="taskViewToggle">
|
||||
<button class="btn btn-sm ${state.taskView === 'compact' ? 'btn-primary' : 'btn-ghost'} p-1.5" onclick="setTaskView('compact')" title="标题视图"><i data-lucide="list" style="width:16px;height:16px"></i></button>
|
||||
<button class="btn btn-sm ${state.taskView !== 'compact' ? 'btn-primary' : 'btn-ghost'} p-1.5" onclick="setTaskView('detail')" title="详细视图"><i data-lucide="align-left" style="width:16px;height:16px"></i></button>
|
||||
</div>
|
||||
<button class="btn btn-primary btn-sm" onclick="openTaskFormForSelected()">
|
||||
<i data-lucide="plus"></i>新增任务
|
||||
</button>
|
||||
</div>
|
||||
<div class="project-board">
|
||||
<div class="project-board-body">
|
||||
<div class="project-tree">
|
||||
<div class="project-tree-hd">
|
||||
<span>项目</span>
|
||||
<button class="btn btn-ghost btn-sm rounded-full w-7 h-7 p-0" onclick="openNewProjectModal()" title="新增项目">
|
||||
<i data-lucide="plus" style="width:16px;height:16px"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="project-tree-list" id="projectTreeList">
|
||||
${items.map((x) => `
|
||||
<div class="project-tree-node ${state.selectedProject === x.id ? 'active' : ''}"
|
||||
data-id="${x.id}"
|
||||
onclick="selectProject(${x.id})"
|
||||
oncontextmenu="showProjectContext(event, ${x.id})">
|
||||
<span class="project-tree-icon"><i data-lucide="folder"></i></span>
|
||||
<span class="project-tree-name">${esc(x.project_name)}</span>
|
||||
</div>
|
||||
`).join("")}
|
||||
${items.length === 0 ? '<div class="project-tree-empty">暂无项目</div>' : ''}
|
||||
</div>
|
||||
</div>
|
||||
<div class="task-feed">
|
||||
${state.selectedProject ? '<div class="task-feed-body">' + renderTaskListHTML(state.selectedProject) + '</div>' : `
|
||||
<div class="project-empty">
|
||||
<div class="text-center">
|
||||
<i data-lucide="arrow-left" style="width:32px;height:32px;margin:0 auto 12px;color:#cbd5e1"></i>
|
||||
<p>请从左侧选择项目查看台账</p>
|
||||
</div>
|
||||
</div>`}
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
document.querySelector("#projectContextMenu")?.remove();
|
||||
const menu = document.createElement("div");
|
||||
menu.id = "projectContextMenu";
|
||||
menu.className = "project-context-menu hidden";
|
||||
menu.innerHTML = `<div class="project-context-item" onclick="openProjectDrawer()"><i data-lucide="info"></i>查看项目详情</div><div class="project-context-item" onclick="renameProject()"><i data-lucide="edit-3"></i>重命名项目</div><div class="project-context-item" onclick="duplicateProject()"><i data-lucide="copy"></i>创建副本</div>`;
|
||||
document.body.appendChild(menu);
|
||||
document.removeEventListener("click", hideProjectContext);
|
||||
document.addEventListener("click", hideProjectContext);
|
||||
|
||||
if (state.selectedProject) renderProjectTasks(state.selectedProject);
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
|
||||
function filterPhaseTasks(tasks, phase) {
|
||||
return tasks.filter((t) => t.phase === phase);
|
||||
}
|
||||
|
||||
function renderTaskListHTML(projectId) {
|
||||
const project = state.data.operations.find((x) => x.id === projectId);
|
||||
if (!project) return "";
|
||||
const tasks = (state.data.tasks || []).filter((t) => t.project_id === projectId);
|
||||
const filtered = tasks;
|
||||
const defaultPhases = ["商务洽谈", "系统上线", "团队分工", "项目交付", "上线推广", "结项验收"];
|
||||
const customPhases = [...new Set(filtered.map(t => t.phase).filter(Boolean))];
|
||||
const phaseOrder = [...defaultPhases];
|
||||
customPhases.forEach(p => { if (!phaseOrder.includes(p)) phaseOrder.push(p); });
|
||||
const phases = phaseOrder.filter(p => filterPhaseTasks(filtered, p).length > 0);
|
||||
const phaseTasks = phases.map(p => ({ phase: p, tasks: filterPhaseTasks(filtered, p) }));
|
||||
|
||||
return `
|
||||
${phaseTasks.map(({ phase, tasks: pt }) => {
|
||||
if (!pt.length) return "";
|
||||
const phaseId = "phase-" + projectId + "-" + phase.replace(/\s/g, "");
|
||||
return `<div class="task-section">
|
||||
<div class="task-section-hd" onclick="togglePhase('${phaseId}')">
|
||||
<span class="task-section-toggle" id="${phaseId}-toggle"><i data-lucide="chevron-down"></i></span>
|
||||
<span class="task-section-icon"><i data-lucide="layers"></i></span>
|
||||
<span class="task-section-label">${phase}</span>
|
||||
<span class="task-section-n">${pt.length}</span>
|
||||
</div>
|
||||
<div class="task-section-list-wrap" id="${phaseId}">
|
||||
<div class="task-section-list" data-phase="${phase}" ondrop="handleTaskDrop(event, ${projectId}, '${phase}')" ondragover="event.preventDefault(); event.currentTarget.classList.add('drag-over')" ondragleave="event.currentTarget.classList.remove('drag-over')">
|
||||
${pt.map((t) => `<div class="task-item ${t.status === '已结束' ? 'task-done' : ''} ${t.priority === 'P0' ? 'task-p0' : t.priority === 'P1' ? 'task-p1' : ''} ${state.taskView === 'detail' ? 'task-detail' : ''}" data-id="${t.id}" draggable="true" ondragstart="handleTaskDragStart(event, ${t.id})" ondragend="event.currentTarget.classList.remove('dragging')">
|
||||
<span class="task-grip"><i data-lucide="grip-vertical"></i></span>
|
||||
<span class="task-status-badge status-${esc(t.status) || '未开始'}" onclick="event.stopPropagation(); cycleTaskStatus(${t.id}, ${projectId})" title="点击切换状态">${esc(t.status) || '未开始'}</span>
|
||||
<span class="task-priority-badge priority-${(t.priority || 'P2').toLowerCase()}" onclick="event.stopPropagation(); cycleTaskPriority(${t.id}, ${projectId})" title="点击切换优先级">${esc(t.priority) || 'P2'}</span>
|
||||
<div class="task-content" onclick="openTaskForm(${projectId}, ${t.id})">
|
||||
<span class="task-title">${esc(t.task)}</span>
|
||||
${state.taskView === 'detail' && t.notes ? '<span class="task-desc">' + esc(t.notes) + '</span>' : ""}
|
||||
${state.taskView === 'detail' && t.blockers ? '<span class="task-blocker">\u26a0 ' + esc(t.blockers) + '</span>' : ""}
|
||||
</div>
|
||||
<span class="task-meta">${esc(t.owner) || ''}</span>
|
||||
<span class="task-meta text-slate-400">${esc(t.due_date) || ''}</span>
|
||||
</div>`).join("")}
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}).join("")}
|
||||
${filtered.length === 0 ? '<div class="task-empty">暂无任务,点击上方按钮创建</div>' : ''}
|
||||
`;
|
||||
}
|
||||
|
||||
function renderProjectTasks(projectId) {
|
||||
const project = state.data.operations.find((x) => x.id === projectId);
|
||||
if (!project) { state.selectedProject = null; renderProjects(); return; }
|
||||
const tasks = (state.data.tasks || []).filter((t) => t.project_id === projectId);
|
||||
const defaultPhases = ["商务洽谈", "系统上线", "团队分工", "项目交付", "上线推广", "结项验收"];
|
||||
const customPhases = [...new Set(tasks.map(t => t.phase).filter(Boolean))];
|
||||
const phases = [...new Set([...defaultPhases, ...customPhases])];
|
||||
|
||||
const body = document.querySelector(".task-feed-body");
|
||||
if (body) body.innerHTML = renderTaskListHTML(projectId);
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
window.openTaskFormForSelected = () => {
|
||||
openTaskForm(state.selectedProject, null);
|
||||
};
|
||||
|
||||
window.openTaskForm = (projectId, taskId) => {
|
||||
if (!projectId) return;
|
||||
// 确保 drawer 存在
|
||||
let drawer = document.querySelector(`#task-drawer-${projectId}`);
|
||||
if (!drawer) {
|
||||
drawer = document.createElement("div");
|
||||
drawer.id = `task-drawer-${projectId}`;
|
||||
drawer.className = "task-drawer";
|
||||
document.body.appendChild(drawer);
|
||||
}
|
||||
const tasks = (state.data.tasks || []).filter((t) => t.project_id === projectId);
|
||||
const defaultPhases = ["商务洽谈", "系统上线", "团队分工", "项目交付", "上线推广", "结项验收"];
|
||||
const customPhases = [...new Set(tasks.map(t => t.phase).filter(Boolean))];
|
||||
const phases = [...new Set([...defaultPhases, ...customPhases])];
|
||||
const task = taskId ? (state.data.tasks || []).find((t) => t.id === taskId) : null;
|
||||
drawer.innerHTML = `<div class="task-drawer-hd"><span class="task-drawer-title">${task ? "编辑任务" : "新增任务"}</span><div class="flex items-center gap-2">${task ? `<button type="button" class="btn btn-ghost btn-sm text-red-600 hover:bg-red-50" onclick="deleteTask(${projectId})"><i data-lucide="trash-2"></i>删除</button>` : ""}<button class="task-close" onclick="closeTaskDrawer(${projectId})"><i data-lucide="x"></i></button></div></div>
|
||||
<form class="task-drawer-form" onsubmit="submitTaskForm(event, ${projectId})">
|
||||
<input type="hidden" name="task_id" id="task-id-${projectId}" value="${task ? task.id : ''}">
|
||||
<div class="task-field-row">
|
||||
<label class="task-field"><span>任务名称</span><input name="task" required id="task-name-${projectId}" class="form-ctrl" value="${task ? esc(task.task) : ''}"></label>
|
||||
<label class="task-field"><span>任务分组</span><select name="phase" id="task-phase-${projectId}" class="form-ctrl">${phases.map((p) => `<option ${task && task.phase === p ? "selected" : ""}>${p}</option>`).join("")}</select></label>
|
||||
</div>
|
||||
<div class="task-field-row">
|
||||
<label class="task-field"><span>优先级</span><select name="priority" id="task-priority-${projectId}" class="form-ctrl"><option ${task && task.priority === 'P0' ? 'selected' : ''}>P0</option><option ${task && task.priority === 'P1' ? 'selected' : ''}>P1</option><option ${(!task || task.priority === 'P2') ? 'selected' : ''}>P2</option><option ${task && task.priority === 'P3' ? 'selected' : ''}>P3</option></select></label>
|
||||
<label class="task-field"><span>状态</span><select name="status" id="task-status-${projectId}" class="form-ctrl"><option ${(!task || task.status === '未开始') ? 'selected' : ''}>未开始</option><option ${task && task.status === '进行中' ? 'selected' : ''}>进行中</option><option ${task && task.status === '已结束' ? 'selected' : ''}>已结束</option></select></label>
|
||||
</div>
|
||||
<div class="task-field-row">
|
||||
<label class="task-field"><span>负责人</span><input name="owner" id="task-owner-${projectId}" class="form-ctrl" value="${task ? esc(task.owner) : ''}"></label>
|
||||
<label class="task-field"><span>截止时间</span><input name="due_date" type="date" id="task-due-${projectId}" class="form-ctrl" value="${task ? esc(task.due_date) : ''}"></label>
|
||||
</div>
|
||||
<label class="task-field"><span>任务说明</span><textarea name="notes" rows="3" id="task-notes-${projectId}" class="form-ctrl">${task ? esc(task.notes) : ''}</textarea></label>
|
||||
<label class="task-field"><span>卡点&备注</span><textarea name="blockers" rows="2" id="task-blockers-${projectId}" class="form-ctrl" placeholder="风险卡点、依赖项等">${task ? esc(task.blockers) : ''}</textarea></label>
|
||||
<div class="flex justify-end gap-2 mt-4 pt-3 border-t border-slate-100">
|
||||
<button type="button" class="btn btn-ghost btn-sm" onclick="closeTaskDrawer(${projectId})">取消</button>
|
||||
<button type="submit" class="btn btn-primary btn-sm" id="task-submit-btn-${projectId}">${task ? "保存" : "确认新增"}</button>
|
||||
</div>
|
||||
</form>`;
|
||||
drawer.classList.add("open");
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
};
|
||||
|
||||
window.closeTaskDrawer = (projectId) => {
|
||||
const drawer = document.querySelector(`#task-drawer-${projectId}`);
|
||||
if (drawer) drawer.classList.remove("open");
|
||||
refreshTaskList(projectId);
|
||||
};
|
||||
|
||||
window.refreshTaskList = (projectId) => {
|
||||
const body = document.querySelector(".task-feed-body");
|
||||
if (body && state.selectedProject === projectId) {
|
||||
body.innerHTML = renderTaskListHTML(projectId);
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
};
|
||||
|
||||
window.submitTaskForm = async (event, projectId) => {
|
||||
event.preventDefault();
|
||||
const data = Object.fromEntries(new FormData(event.currentTarget).entries());
|
||||
data.project_id = Number(projectId);
|
||||
data.tenant = state.tenant;
|
||||
const taskId = data.task_id;
|
||||
delete data.task_id;
|
||||
try {
|
||||
if (taskId) {
|
||||
await api(`/api/tasks/${taskId}`, { method: "PUT", body: JSON.stringify({ data }) });
|
||||
const task = (state.data.tasks || []).find(t => t.id === parseInt(taskId));
|
||||
if (task) Object.assign(task, data);
|
||||
if (data.task) logActivity("task", taskId, "更新了任务「" + data.task + "」");
|
||||
closeTaskDrawer(projectId);
|
||||
} else {
|
||||
const result = await api("/api/tasks", { method: "POST", body: JSON.stringify({ data }) });
|
||||
if (result.id && data.task) logActivity("task", result.id, "创建了任务「" + data.task + "」");
|
||||
closeTaskDrawer(projectId);
|
||||
await load();
|
||||
}
|
||||
} catch (error) {
|
||||
toast("保存失败:" + error.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
window.cycleTaskStatus = async (taskId, projectId) => {
|
||||
const tasks = state.data.tasks || [];
|
||||
const task = tasks.find((t) => t.id === taskId);
|
||||
if (!task) return;
|
||||
const statuses = ["未开始", "进行中", "已结束"];
|
||||
const current = statuses.indexOf(task.status) >= 0 ? task.status : "未开始";
|
||||
const newStatus = statuses[(statuses.indexOf(current) + 1) % statuses.length];
|
||||
try {
|
||||
await api(`/api/tasks/${taskId}`, { method: "PUT", body: JSON.stringify({ data: { status: newStatus } }) });
|
||||
task.status = newStatus;
|
||||
const row = document.querySelector(`.task-item[data-id="${taskId}"]`);
|
||||
if (row) {
|
||||
row.classList.toggle("task-done", newStatus === "已结束");
|
||||
const badge = row.querySelector(".task-status-badge");
|
||||
if (badge) {
|
||||
badge.textContent = newStatus;
|
||||
badge.className = "task-status-badge status-" + newStatus;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
toast("更新失败:" + error.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
window.cycleTaskPriority = async (taskId, projectId) => {
|
||||
const tasks = state.data.tasks || [];
|
||||
const task = tasks.find((t) => t.id === taskId);
|
||||
if (!task) return;
|
||||
const priorities = ["P0", "P1", "P2", "P3"];
|
||||
const current = priorities.indexOf(task.priority) >= 0 ? task.priority : "P2";
|
||||
const newPriority = priorities[(priorities.indexOf(current) + 1) % priorities.length];
|
||||
try {
|
||||
await api(`/api/tasks/${taskId}`, { method: "PUT", body: JSON.stringify({ data: { priority: newPriority } }) });
|
||||
task.priority = newPriority;
|
||||
const row = document.querySelector(`.task-item[data-id="${taskId}"]`);
|
||||
if (row) {
|
||||
row.classList.remove("task-p0", "task-p1");
|
||||
if (newPriority === "P0") row.classList.add("task-p0");
|
||||
else if (newPriority === "P1") row.classList.add("task-p1");
|
||||
const badge = row.querySelector(".task-priority-badge");
|
||||
if (badge) {
|
||||
badge.textContent = newPriority;
|
||||
badge.className = "task-priority-badge priority-" + newPriority.toLowerCase();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
toast("更新失败:" + error.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
window.deleteTask = async (projectId) => {
|
||||
const taskId = document.querySelector(`#task-id-${projectId}`).value;
|
||||
if (!taskId) return;
|
||||
if (!confirm("确认删除该任务?此操作不可撤销。")) return;
|
||||
try {
|
||||
const task = (state.data.tasks || []).find(t => t.id === parseInt(taskId));
|
||||
const taskName = task ? task.task : "";
|
||||
await api(`/api/tasks/${taskId}`, { method: "DELETE" });
|
||||
if (taskName) logActivity("task", taskId, "删除了任务「" + taskName + "」");
|
||||
closeTaskDrawer(projectId);
|
||||
state.data.tasks = (state.data.tasks || []).filter(t => t.id !== parseInt(taskId));
|
||||
const row = document.querySelector(`.task-item[data-id="${taskId}"]`);
|
||||
if (row) row.remove();
|
||||
} catch (error) {
|
||||
toast("删除失败:" + error.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
// 拖拽排序
|
||||
let dragTaskId = null;
|
||||
window.handleTaskDragStart = (event, taskId) => {
|
||||
dragTaskId = taskId;
|
||||
event.currentTarget.classList.add("dragging");
|
||||
event.dataTransfer.effectAllowed = "move";
|
||||
};
|
||||
|
||||
window.handleTaskDrop = async (event, projectId, phase) => {
|
||||
event.preventDefault();
|
||||
event.currentTarget.classList.remove("drag-over");
|
||||
const target = event.currentTarget;
|
||||
if (!dragTaskId) return;
|
||||
const dragged = document.querySelector(`.task-item[data-id="${dragTaskId}"]`);
|
||||
if (!dragged) return;
|
||||
const afterElement = getDragAfterElement(target, event.clientY);
|
||||
if (afterElement) {
|
||||
target.insertBefore(dragged, afterElement);
|
||||
} else {
|
||||
target.appendChild(dragged);
|
||||
}
|
||||
dragged.classList.remove("dragging");
|
||||
const rows = [...target.querySelectorAll(".task-item")];
|
||||
const updates = rows.map((row, i) => ({ id: parseInt(row.dataset.id), sort_order: i }));
|
||||
try {
|
||||
await api(`/api/tasks/batch-sort`, { method: "POST", body: JSON.stringify({ items: updates }) });
|
||||
} catch (e) { /* non-critical */ }
|
||||
dragTaskId = null;
|
||||
};
|
||||
|
||||
function getDragAfterElement(container, y) {
|
||||
const elements = [...container.querySelectorAll(".task-item:not(.dragging)")];
|
||||
return elements.reduce((closest, child) => {
|
||||
const box = child.getBoundingClientRect();
|
||||
const offset = y - box.top - box.height / 2;
|
||||
if (offset < 0 && offset > closest.offset) {
|
||||
return { offset: offset, element: child };
|
||||
} else {
|
||||
return closest;
|
||||
}
|
||||
}, { offset: Number.NEGATIVE_INFINITY }).element;
|
||||
}
|
||||
335
static/modules/proposals.js
Normal file
335
static/modules/proposals.js
Normal file
@@ -0,0 +1,335 @@
|
||||
// proposals.js — 业务方案 + 文件管理
|
||||
|
||||
// 标准资料库固定 7 项
|
||||
const STANDARD_PROPOSALS = [
|
||||
"业务方案-医生版",
|
||||
"业务方案-药企版",
|
||||
"服务清单与报价单",
|
||||
"患者服务清单",
|
||||
"医生项目清单与劳务报价",
|
||||
"项目执行 SOP",
|
||||
"财务结算流程",
|
||||
];
|
||||
|
||||
// 确保标准资料库已初始化(首次进入时创建)
|
||||
async function ensureStandardProposals() {
|
||||
const existing = (state.data.proposals || []).filter(p => p.proposal_type === "标准资料");
|
||||
const missing = STANDARD_PROPOSALS.filter(name => !existing.find(p => p.customer_or_project_name === name));
|
||||
if (missing.length === 0) return;
|
||||
for (const name of missing) {
|
||||
try {
|
||||
await api("/api/proposals", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ data: {
|
||||
customer_or_project_name: name,
|
||||
proposal_type: "标准资料",
|
||||
notes: "",
|
||||
version: "v1.0",
|
||||
status: "已归档",
|
||||
created_date: new Date().toISOString().slice(0, 10),
|
||||
tenant: state.tenant,
|
||||
}}),
|
||||
});
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
await load();
|
||||
}
|
||||
|
||||
window.switchProposalTab = (tab) => {
|
||||
state.proposalTab = tab;
|
||||
renderProposals();
|
||||
};
|
||||
|
||||
function renderProposals() {
|
||||
const items = state.data.proposals || [];
|
||||
const standardItems = items.filter(p => p.proposal_type === "标准资料");
|
||||
const otherItems = items.filter(p => p.proposal_type !== "标准资料");
|
||||
const isStandard = state.proposalTab === "standard";
|
||||
|
||||
document.querySelector("#proposals").innerHTML = `<div class="grid gap-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex gap-1" id="proposalTabToggle">
|
||||
<button class="btn btn-sm ${isStandard ? 'btn-primary' : 'btn-ghost'}" onclick="switchProposalTab('standard')">标准资料库</button>
|
||||
<button class="btn btn-sm ${!isStandard ? 'btn-primary' : 'btn-ghost'}" onclick="switchProposalTab('other')">其他资料</button>
|
||||
</div>
|
||||
${!isStandard ? `<button class="btn btn-primary btn-sm" onclick="openProposalModal()"><i data-lucide="plus"></i>新增方案</button>` : ''}
|
||||
</div>
|
||||
${isStandard ? `<div class="flex items-start gap-2 rounded-lg bg-blue-50 border border-blue-100 px-4 py-3 text-sm text-blue-700"><i data-lucide="info" style="width:16px;height:16px;flex-shrink:0;margin-top:1px"></i><span>这是每一条 OPC 线,必须要梳理清楚的 7 份资料,项目不可以删除,只可以更新附件,请大家将最新的材料上传</span></div>` : `<div class="flex items-start gap-2 rounded-lg bg-emerald-50 border border-emerald-100 px-4 py-3 text-sm text-emerald-700"><i data-lucide="lightbulb" style="width:16px;height:16px;flex-shrink:0;margin-top:1px"></i><span>在这里新建,并且上传您希望与团队其他成员共享的资料</span></div>`}
|
||||
${isStandard ? renderStandardTable(standardItems) : renderOtherTable(otherItems)}
|
||||
</div>
|
||||
<div id="proposalModal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/40" onclick="closeProposalModal()">
|
||||
<div class="bg-white rounded-2xl shadow-2xl w-full max-w-md mx-4" onclick="event.stopPropagation()">
|
||||
<div class="flex items-center justify-between px-6 py-4 border-b border-slate-100">
|
||||
<h3 class="text-lg font-semibold text-slate-800">新增方案</h3>
|
||||
<button class="btn btn-ghost btn-sm rounded-full w-8 h-8 p-0" onclick="closeProposalModal()"><i data-lucide="x"></i></button>
|
||||
</div>
|
||||
<form onsubmit="submitProposal(event)" class="p-6 grid gap-4">
|
||||
<label class="block"><span class="text-xs font-medium text-slate-500">方案名称</span><input name="customer_or_project_name" required class="form-ctrl mt-1"></label>
|
||||
<label class="block"><span class="text-xs font-medium text-slate-500">方案类型</span><select name="proposal_type" class="form-ctrl mt-1">${["业务方案","报价与成本","SOP","PRD","设计稿","财务流程","其他"].map(t => `<option>${t}</option>`).join("")}</select></label>
|
||||
<label class="block"><span class="text-xs font-medium text-slate-500">方案说明</span><textarea name="notes" rows="3" class="form-ctrl mt-1"></textarea></label>
|
||||
<div class="flex justify-end gap-3 pt-3 border-t border-slate-100">
|
||||
<button type="button" class="btn btn-ghost btn-sm" onclick="closeProposalModal()">取消</button>
|
||||
<button type="submit" class="btn btn-primary btn-sm">创建</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>`;
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
|
||||
// 标准资料库:按固定顺序排序,点击行打开附件抽屉(不含删除按钮)
|
||||
function renderStandardTable(items) {
|
||||
const sorted = STANDARD_PROPOSALS.map(name => items.find(p => p.customer_or_project_name === name)).filter(Boolean);
|
||||
const rows = sorted.map((p) => {
|
||||
const fileCount = (p.files || []).length;
|
||||
return `<tr class="border-b border-slate-100 hover:bg-slate-50 cursor-pointer" onclick="openStandardProposalDrawer(${p.id})">
|
||||
<td class="p-3 text-sm font-medium text-slate-800">${esc(p.customer_or_project_name)}</td>
|
||||
<td class="p-3 text-sm text-slate-500 text-center">${fileCount} 个文件</td>
|
||||
<td class="p-3 text-sm text-slate-500 text-center">${(p.created_at || "").slice(0,10) || "—"}</td>
|
||||
</tr>`;
|
||||
}).join("");
|
||||
return `<div class="bg-white rounded-lg border border-slate-200 overflow-hidden">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead><tr class="bg-slate-50 border-b border-slate-200">
|
||||
<th class="p-3 text-left font-semibold text-slate-600">资料名称</th>
|
||||
<th class="p-3 text-center font-semibold text-slate-600">附件</th>
|
||||
<th class="p-3 text-center font-semibold text-slate-600">创建日期</th>
|
||||
</tr></thead>
|
||||
<tbody>${rows}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
// 其他资料:原有表格 + 行点击打开抽屉
|
||||
function renderOtherTable(items) {
|
||||
const rows = items.map((p) => [
|
||||
`<strong>${esc(p.customer_or_project_name)}</strong>`,
|
||||
p.proposal_type || "业务方案",
|
||||
text(p.notes || ""),
|
||||
(p.created_at || "").slice(0, 10) || "\u2014",
|
||||
]);
|
||||
return renderTable(["方案名称", "方案类型", "方案说明", "日期"], rows, items.map((p) => ({ resource: "proposals", id: p.id })));
|
||||
}
|
||||
|
||||
// 标准资料专用抽屉(附件管理 + 评论,不能编辑字段、不能删除项目)
|
||||
window.openStandardProposalDrawer = (id) => {
|
||||
const item = (state.data.proposals || []).find(p => p.id === id);
|
||||
if (!item) return;
|
||||
const drawer = document.querySelector("#drawer");
|
||||
const title = esc(item.customer_or_project_name);
|
||||
const followupTarget = "proposal";
|
||||
drawer.innerHTML = `<div class="drawer-panel"><div class="sticky top-0 z-10 flex items-center justify-between border-b border-slate-200 bg-white/95 px-5 py-3 backdrop-blur"><div><p class="text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-400">标准资料</p><div class="flex items-center gap-2"><h2 class="drawer-title text-[17px] font-semibold leading-6 text-slate-900">${title}</h2><span id="drawerSaveStatus" class="save-status"></span></div></div><button class="btn btn-ghost btn-sm" onclick="closeDrawer()">关闭</button></div><div class="grid gap-5 p-5">
|
||||
<section>
|
||||
<h3 class="drawer-section-title">附件管理</h3>
|
||||
${fileGroup("proposal", item.id, "", "附件", item.files || [])}
|
||||
</section>
|
||||
${followupTarget ? `<section>
|
||||
<h3 class="drawer-section-title">活动 / 跟进</h3>
|
||||
<div class="grid gap-2">${(item.followups || []).map((f) => `<div class="activity-item"><div class="activity-icon"><i data-lucide="message-square"></i></div><div class="min-w-0 flex-1"><div class="flex justify-between gap-3 text-[12px] text-slate-500"><span>${esc(f.follower)} · ${esc(f.follow_up_method)}</span><span>${esc(f.followed_at)}</span></div><div class="mt-1 leading-5 text-slate-800 rich-content" data-html="${encodeURIComponent(f.content || '')}"></div>${f.next_action ? `<p class="mt-1 leading-5 text-blue-700">下一步:${text(f.next_action)}</p>` : ""}</div><button class="activity-delete" onclick="deleteFollowup(event, ${f.id}, 'proposals', ${item.id})" title="删除评论"><i data-lucide="trash-2"></i></button></div>`).join("")}</div>
|
||||
<form class="comment-box mt-3" onsubmit="submitStandardComment(event, ${item.id})">
|
||||
<div class="squire-toolbar">
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('bold')" title="加粗"><i data-lucide="bold"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('italic')" title="斜体"><i data-lucide="italic"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('underline')" title="下划线"><i data-lucide="underline"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('strikethrough')" title="删除线"><i data-lucide="strikethrough"></i></button>
|
||||
<span class="squire-sep"></span>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('makeUnorderedList')" title="无序列表"><i data-lucide="list"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('makeOrderedList')" title="有序列表"><i data-lucide="list-ordered"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('blockquote')" title="引用"><i data-lucide="quote"></i></button>
|
||||
<span class="squire-sep"></span>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('undo')" title="撤销"><i data-lucide="undo"></i></button>
|
||||
<button type="button" class="squire-btn" onmousedown="event.preventDefault();squireCmd('redo')" title="重做"><i data-lucide="redo"></i></button>
|
||||
</div>
|
||||
<div class="squire-editor" id="squire_standard_${item.id}" placeholder="添加评论"></div>
|
||||
<div class="comment-toolbar">
|
||||
<span class="comment-hint">支持富文本编辑</span>
|
||||
<button class="btn btn-primary btn-sm comment-submit" type="submit">评论</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>` : ""}
|
||||
<div id="uploadTaskList"></div>
|
||||
</div></div>`;
|
||||
drawer.classList.add("open");
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
renderUploadTasks();
|
||||
// 渲染富文本评论内容
|
||||
drawer.querySelectorAll(".rich-content").forEach((el) => {
|
||||
const html = el.dataset.html;
|
||||
if (html) el.innerHTML = decodeURIComponent(html);
|
||||
});
|
||||
// 初始化 Squire 编辑器
|
||||
const squireDiv = drawer.querySelector(".squire-editor");
|
||||
if (squireDiv && window.Squire) {
|
||||
const sid = squireDiv.id;
|
||||
if (window.squireInstances[sid]) window.squireInstances[sid].destroy();
|
||||
const sq = new Squire(squireDiv, { blockTag: "P" });
|
||||
window.squireInstances[sid] = sq;
|
||||
squireDiv.addEventListener("focus", () => squireDiv.classList.add("focused"));
|
||||
squireDiv.addEventListener("blur", () => {
|
||||
if (!squireDiv.textContent.trim()) squireDiv.classList.remove("focused");
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// 标准资料评论提交(提交后重新打开标准资料抽屉)
|
||||
window.submitStandardComment = async (event, targetId) => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const editorDiv = form.querySelector(".squire-editor");
|
||||
const sq = window.squireInstances[editorDiv.id];
|
||||
const content = sq ? sq.getHTML().trim() : "";
|
||||
if (!content || content === "<div><br></div>" || content === "<p><br></p>") return;
|
||||
const button = form.querySelector(".comment-submit");
|
||||
button.disabled = true;
|
||||
button.textContent = "发送中…";
|
||||
await api(`/api/followups/proposal/${targetId}`, { method: "POST", body: JSON.stringify({ data: { content } }) });
|
||||
await load();
|
||||
openStandardProposalDrawer(targetId);
|
||||
};
|
||||
|
||||
window.openProposalModal = () => {
|
||||
document.querySelector("#proposalModal").classList.remove("hidden");
|
||||
};
|
||||
window.closeProposalModal = () => {
|
||||
document.querySelector("#proposalModal").classList.add("hidden");
|
||||
};
|
||||
window.submitProposal = async (event) => {
|
||||
event.preventDefault();
|
||||
const form = event.currentTarget;
|
||||
const data = Object.fromEntries(new FormData(form).entries());
|
||||
data.tenant = state.tenant;
|
||||
if (!data.version) data.version = "v1.0";
|
||||
if (!data.description) data.description = "";
|
||||
if (!data.status) data.status = "草稿";
|
||||
if (!data.created_date) data.created_date = new Date().toISOString().slice(0, 10);
|
||||
try {
|
||||
const result = await api("/api/proposals", { method: "POST", body: JSON.stringify({ data }) });
|
||||
if (result.id && data.customer_or_project_name) logActivity("proposal", result.id, "创建了方案「" + data.customer_or_project_name + "」");
|
||||
form.reset();
|
||||
closeProposalModal();
|
||||
await load();
|
||||
} catch (error) {
|
||||
toast("保存失败:" + error.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
// 文件管理
|
||||
function fileGroup(module, ownerId, version, category, files) {
|
||||
return `<div class="rounded-md border border-slate-200 px-3 py-2">
|
||||
<div class="flex items-center justify-between gap-3"><p class="text-[13px] font-semibold text-slate-800">${category}</p><label class="inline-flex cursor-pointer items-center gap-1 rounded-md border border-slate-200 px-2 py-1 text-[12px] font-medium text-slate-600 hover:bg-slate-50"><i data-lucide="upload"></i>上传<input class="hidden" type="file" onchange="uploadFile(event,'${module}',${ownerId},'${version}','${category}')"></label></div>
|
||||
<div class="mt-2 grid gap-1.5">${files.length ? files.map(fileItem).join("") : `<p class="text-[12px] text-slate-400">暂无文件</p>`}</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function fileItem(file) {
|
||||
return `<div class="flex items-center justify-between gap-2 rounded-md bg-slate-50 px-2 py-1.5 text-[13px]"><div class="min-w-0 flex-1"><p class="truncate font-medium text-slate-800">${esc(file.file_name)}</p><div class="mt-0.5 flex gap-3"><a class="file-link inline-flex items-center gap-1 text-slate-600" href="/api/files/${file.id}/content?inline=false"><i data-lucide="download"></i>下载</a></div></div><button class="btn btn-ghost btn-sm text-red-600" onclick="deleteFile(${file.id})" title="删除"><i data-lucide="trash-2"></i></button></div>`;
|
||||
}
|
||||
|
||||
window.deleteFile = async (fileId) => {
|
||||
if (!confirm("确认删除此文件?")) return;
|
||||
await api(`/api/files/${fileId}`, { method: "DELETE" });
|
||||
// 优先在当前打开的抽屉中查找并刷新
|
||||
const drawer = document.querySelector("#drawer.open");
|
||||
if (drawer) {
|
||||
const uploadList = drawer.querySelector("#uploadTaskList");
|
||||
// 通过 file.id 反查所属 item
|
||||
for (const listKey of ["proposals", "operations", "sales", "products"]) {
|
||||
if (!state.data[listKey]) continue;
|
||||
for (const item of state.data[listKey]) {
|
||||
if (!item.files) continue;
|
||||
const idx = item.files.findIndex(f => f.id === fileId);
|
||||
if (idx !== -1) {
|
||||
item.files.splice(idx, 1);
|
||||
// 判断是标准资料还是普通抽屉
|
||||
if (item.proposal_type === "标准资料") {
|
||||
openStandardProposalDrawer(item.id);
|
||||
} else {
|
||||
openDrawer(listKey, item.id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.uploadFile = (event, module, ownerId, version, category) => {
|
||||
const file = event.target.files[0];
|
||||
if (!file) return;
|
||||
const taskId = Date.now();
|
||||
const task = { id: taskId, name: file.name, progress: 0, xhr: null };
|
||||
state.uploadTasks.push(task);
|
||||
renderUploadTasks();
|
||||
|
||||
const form = new FormData();
|
||||
form.append("module", module);
|
||||
form.append("owner_id", ownerId);
|
||||
form.append("owner_version", version);
|
||||
form.append("file_category", category);
|
||||
form.append("file", file);
|
||||
|
||||
const xhr = new XMLHttpRequest();
|
||||
task.xhr = xhr;
|
||||
xhr.upload.addEventListener("progress", (e) => {
|
||||
if (e.lengthComputable) {
|
||||
task.progress = Math.round((e.loaded / e.total) * 100);
|
||||
renderUploadTasks();
|
||||
}
|
||||
});
|
||||
xhr.addEventListener("load", () => {
|
||||
if (xhr.status === 200) {
|
||||
task.progress = 100;
|
||||
renderUploadTasks();
|
||||
const result = JSON.parse(xhr.responseText);
|
||||
const resourceMap = { proposal: "proposals", operation: "operations", sales: "sales", product: "products" };
|
||||
const listKey = resourceMap[module];
|
||||
if (listKey && state.data[listKey]) {
|
||||
const item = state.data[listKey].find(x => x.id === ownerId);
|
||||
if (item) {
|
||||
if (!item.files) item.files = [];
|
||||
item.files.push({ id: result.id, file_name: file.name, file_category: category });
|
||||
// 刷新当前抽屉
|
||||
if (item.proposal_type === "标准资料") {
|
||||
openStandardProposalDrawer(item.id);
|
||||
} else if (document.querySelector("#drawer.open")) {
|
||||
openDrawer(listKey, item.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
setTimeout(() => {
|
||||
state.uploadTasks = state.uploadTasks.filter(t => t.id !== taskId);
|
||||
renderUploadTasks();
|
||||
}, 1500);
|
||||
}
|
||||
});
|
||||
xhr.addEventListener("error", () => {
|
||||
toast("上传失败:" + file.name, "error");
|
||||
state.uploadTasks = state.uploadTasks.filter(t => t.id !== taskId);
|
||||
renderUploadTasks();
|
||||
});
|
||||
xhr.open("POST", "/api/files/upload");
|
||||
xhr.send(form);
|
||||
};
|
||||
|
||||
window.cancelUpload = (taskId) => {
|
||||
const task = state.uploadTasks.find(t => t.id === taskId);
|
||||
if (task && task.xhr) task.xhr.abort();
|
||||
state.uploadTasks = state.uploadTasks.filter(t => t.id !== taskId);
|
||||
renderUploadTasks();
|
||||
};
|
||||
|
||||
window.renderUploadTasks = () => {
|
||||
const el = document.querySelector("#uploadTaskList");
|
||||
if (!el) return;
|
||||
el.innerHTML = state.uploadTasks.map(t => `
|
||||
<div class="upload-task">
|
||||
<span class="upload-task-name">${esc(t.name)}</span>
|
||||
<div class="upload-task-bar"><div class="upload-task-fill" style="width:${t.progress}%"></div></div>
|
||||
<span class="upload-task-pct">${t.progress}%</span>
|
||||
<button class="upload-task-cancel" onclick="cancelUpload(${t.id})"><i data-lucide="x"></i></button>
|
||||
</div>
|
||||
`).join("");
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
};
|
||||
203
static/modules/utils.js
Normal file
203
static/modules/utils.js
Normal file
@@ -0,0 +1,203 @@
|
||||
// utils.js — 全局工具函数与共享状态
|
||||
|
||||
const state = {
|
||||
active: "home",
|
||||
data: null,
|
||||
tenant: "科普·无界",
|
||||
opFilter: "all",
|
||||
finFilter: "已签约",
|
||||
selectedProject: null,
|
||||
taskQuery: "",
|
||||
taskView: localStorage.getItem("opc-task-view") || "detail",
|
||||
finView: localStorage.getItem("opc-fin-view") || "overview",
|
||||
proposalTab: "standard",
|
||||
chart: null,
|
||||
chart2: null,
|
||||
chart3: null,
|
||||
productPlatform: "all",
|
||||
uploadTasks: [],
|
||||
};
|
||||
|
||||
const money = (value) => `${Number(value || 0).toLocaleString("zh-CN")} 元`;
|
||||
const text = (value) => value === undefined || value === null || value === "" ? "—" : esc(value);
|
||||
|
||||
function escapeHtml(str) { return String(str || "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """); }
|
||||
const html = escapeHtml;
|
||||
const esc = escapeHtml;
|
||||
|
||||
// Toast 通知
|
||||
function toast(message, type = "info", duration = 3000) {
|
||||
let container = document.querySelector(".toast-container");
|
||||
if (!container) {
|
||||
container = document.createElement("div");
|
||||
container.className = "toast-container";
|
||||
document.body.appendChild(container);
|
||||
}
|
||||
const el = document.createElement("div");
|
||||
el.className = `toast toast-${type}`;
|
||||
const icon = type === "success" ? "check-circle" : type === "error" ? "alert-circle" : "info";
|
||||
el.innerHTML = `<i data-lucide="${icon}" style="width:16px;height:16px;flex-shrink:0"></i><span>${esc(message)}</span>`;
|
||||
container.appendChild(el);
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
setTimeout(() => {
|
||||
el.classList.add("fade-out");
|
||||
setTimeout(() => el.remove(), 250);
|
||||
}, duration);
|
||||
}
|
||||
window.toast = toast;
|
||||
|
||||
function monthOptions(selected = '') {
|
||||
const now = new Date();
|
||||
const startYear = now.getFullYear() - 1;
|
||||
const endYear = now.getFullYear() + 1;
|
||||
let options = selected ? '' : '<option value="">选择月份</option>';
|
||||
for (let y = startYear; y <= endYear; y++) {
|
||||
for (const m of ["01","02","03","04","05","06","07","08","09","10","11","12"]) {
|
||||
const val = y + "-" + m;
|
||||
const sel = val === selected ? " selected" : "";
|
||||
options += `<option value="${val}"${sel}>${val}</option>`;
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
async function api(path, options = {}) {
|
||||
const response = await fetch(path, {
|
||||
headers: options.body instanceof FormData ? undefined : { "Content-Type": "application/json" },
|
||||
...options,
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || "请求失败");
|
||||
return data;
|
||||
}
|
||||
|
||||
async function logActivity(targetType, targetId, content) {
|
||||
try {
|
||||
await api(`/api/followups/${targetType}/${targetId}`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ data: { content, tenant: state.tenant } }),
|
||||
});
|
||||
} catch (e) { /* non-critical */ }
|
||||
}
|
||||
|
||||
function badge(value) {
|
||||
const val = String(value || "—");
|
||||
let cls = "badge-slate";
|
||||
if (["P0", "有风险", "已丢单", "已延期"].includes(val)) cls = "badge-red";
|
||||
if (["P1", "方案中", "方案已提交", "商务谈判", "待客户确认"].includes(val)) cls = "badge-amber";
|
||||
if (["已签约", "已上线", "已完成", "已归档"].includes(val)) cls = "badge-green";
|
||||
if (["execution", "已签约执行项目"].includes(val)) cls = "badge-blue";
|
||||
return `<span class="badge ${cls}">${val === "execution" ? "已签约执行项目" : val === "opportunity" ? "业务机会项目" : val}</span>`;
|
||||
}
|
||||
|
||||
function card(content, cls = "") {
|
||||
return `<section class="card ${cls}">${content}</section>`;
|
||||
}
|
||||
|
||||
function renderTable(headers, rows, rowClicks) {
|
||||
const trAttrs = (rowClicks || []).map((rc) => rc ? `onclick="openDrawer('${rc.resource}', ${rc.id})" class="clickable-row"` : "");
|
||||
return card(`
|
||||
<div class="overflow-x-auto">
|
||||
<table>
|
||||
<thead><tr>${headers.map((h) => `<th>${h}</th>`).join("")}</tr></thead>
|
||||
<tbody>${rows.map((row, i) => `<tr ${trAttrs[i] || ""}>${row.map((c) => `<td>${c}</td>`).join("")}</tr>`).join("")}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`);
|
||||
}
|
||||
|
||||
async function load() {
|
||||
state.data = await api(`/api/bootstrap?tenant=${encodeURIComponent(state.tenant)}`);
|
||||
// 首次加载时确保标准资料库 7 项已初始化
|
||||
if (typeof ensureStandardProposals === "function") {
|
||||
const existing = (state.data.proposals || []).filter(p => p.proposal_type === "标准资料");
|
||||
const missingCount = 7 - existing.length;
|
||||
if (missingCount > 0) {
|
||||
await ensureStandardProposals();
|
||||
return; // ensureStandardProposals 内部会再次 render
|
||||
}
|
||||
}
|
||||
render();
|
||||
}
|
||||
|
||||
function switchTab(tab) {
|
||||
state.active = tab;
|
||||
localStorage.setItem("opc-active-tab", tab);
|
||||
document.querySelectorAll(".sidebar-tab").forEach((btn) => btn.classList.toggle("active", btn.dataset.tab === tab));
|
||||
document.querySelectorAll(".panel").forEach((panel) => panel.classList.toggle("active", panel.id === tab));
|
||||
render();
|
||||
}
|
||||
|
||||
function updateSidebarTabs() {
|
||||
const isOverview = state.tenant === "总工作台";
|
||||
document.querySelectorAll(".sidebar-tab").forEach((btn) => {
|
||||
const tab = btn.dataset.tab;
|
||||
if (isOverview && tab !== "home") {
|
||||
btn.style.display = "none";
|
||||
} else {
|
||||
btn.style.display = "";
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function render() {
|
||||
if (!state.data) return;
|
||||
renderHome();
|
||||
renderProjects();
|
||||
renderProposals();
|
||||
renderProducts();
|
||||
renderFinance();
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
|
||||
function renderActive() {
|
||||
if (!state.data) return;
|
||||
const tab = state.active;
|
||||
if (tab === "home") renderHome();
|
||||
else if (tab === "projects") renderProjects();
|
||||
else if (tab === "proposals") renderProposals();
|
||||
else if (tab === "products") renderProducts();
|
||||
else if (tab === "finance") renderFinance();
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
|
||||
window.setTaskView = (view) => {
|
||||
state.taskView = view;
|
||||
localStorage.setItem("opc-task-view", view);
|
||||
// 更新按钮选中状态
|
||||
const toggle = document.querySelector("#taskViewToggle");
|
||||
if (toggle) {
|
||||
toggle.querySelectorAll("button").forEach((btn, i) => {
|
||||
const isCompact = i === 0;
|
||||
btn.className = `btn btn-sm ${(isCompact ? view === 'compact' : view !== 'compact') ? 'btn-primary' : 'btn-ghost'} p-1.5`;
|
||||
});
|
||||
}
|
||||
if (state.selectedProject) {
|
||||
const body = document.querySelector(".task-feed-body");
|
||||
if (body) body.innerHTML = renderTaskListHTML(state.selectedProject);
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
};
|
||||
|
||||
window.switchTab = switchTab;
|
||||
|
||||
window.setFinView = (view) => {
|
||||
state.finView = view;
|
||||
localStorage.setItem("opc-fin-view", view);
|
||||
renderFinance();
|
||||
};
|
||||
window.switchTenant = (tenant) => {
|
||||
state.tenant = tenant;
|
||||
state.selectedProject = null;
|
||||
localStorage.setItem("opc-active-tenant", tenant);
|
||||
document.querySelector("#workspaceTitle").textContent = tenant.replace("·无界", "") + " OPC 工作台";
|
||||
const label = document.querySelector("#currentTenantLabel");
|
||||
if (label) { label.textContent = tenant.replace("·无界", "") || "工作台"; label.title = tenant; }
|
||||
updateSidebarTabs();
|
||||
if (tenant === "总工作台") switchTab("home");
|
||||
load();
|
||||
};
|
||||
window.doLogout = async () => {
|
||||
await api("/api/auth/logout", { method: "POST" });
|
||||
location.href = "/login";
|
||||
};
|
||||
@@ -9,25 +9,53 @@ body {
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.tabs {
|
||||
/* 工作台侧边栏 */
|
||||
.workspace-nav-item {
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.tabs button {
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
border-bottom: 2px solid transparent;
|
||||
color: #64748b;
|
||||
display: inline-flex;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
gap: 8px;
|
||||
padding: 14px 16px;
|
||||
justify-content: center;
|
||||
border-radius: 14px;
|
||||
color: #94a3b8;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s;
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
.workspace-nav-item:hover {
|
||||
color: #e2e8f0;
|
||||
background: rgba(255,255,255,0.08);
|
||||
}
|
||||
.workspace-nav-item.active {
|
||||
color: #60a5fa;
|
||||
background: rgba(96,165,250,0.15);
|
||||
}
|
||||
|
||||
.tabs button.active {
|
||||
border-bottom-color: #1d4ed8;
|
||||
color: #1d4ed8;
|
||||
.sidebar-tab {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
padding: 8px 4px;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
color: #94a3b8;
|
||||
transition: all 0.15s ease;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.sidebar-tab:hover {
|
||||
background: #1e293b;
|
||||
color: #cbd5e1;
|
||||
}
|
||||
|
||||
.sidebar-tab.active {
|
||||
background: #1e293b;
|
||||
color: #60a5fa;
|
||||
}
|
||||
|
||||
.sidebar-tab.active i {
|
||||
color: #60a5fa;
|
||||
}
|
||||
|
||||
.panel {
|
||||
@@ -38,6 +66,527 @@ body {
|
||||
display: block;
|
||||
}
|
||||
|
||||
/* 财务模态框 Tab */
|
||||
.finance-tabs {
|
||||
display: flex;
|
||||
gap: 0;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
padding: 0 32px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.finance-tab {
|
||||
padding: 10px 20px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: #64748b;
|
||||
background: none;
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
|
||||
.finance-tab:hover { color: #1e293b; }
|
||||
|
||||
.finance-tab.active {
|
||||
color: #1d4ed8;
|
||||
border-bottom-color: #1d4ed8;
|
||||
}
|
||||
|
||||
/* 详情弹窗固定高度,tab 切换不抖动 */
|
||||
#financeModal > div {
|
||||
height: 650px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
#financeModal .finance-tabs { flex-shrink: 0; }
|
||||
#financeModal form {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
#financeModal .finance-tab-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 32px;
|
||||
}
|
||||
#financeModal .finance-form-actions {
|
||||
flex-shrink: 0;
|
||||
background: #fff;
|
||||
padding: 12px 32px 8px;
|
||||
border-top: 1px solid #f1f5f9;
|
||||
}
|
||||
|
||||
/* 项目统一卡片布局 */
|
||||
.project-board {
|
||||
background: #fff;
|
||||
border: 1px solid #e5e7eb;
|
||||
border-radius: 12px;
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: calc(100vh - 190px);
|
||||
}
|
||||
|
||||
/* 项目树头部 */
|
||||
.project-tree-hd {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 8px 12px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: #374151;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.project-search {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
background: #fff;
|
||||
border: 1px solid #d1d5db;
|
||||
border-radius: 8px;
|
||||
padding: 5px 10px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.project-search i {
|
||||
color: #9ca3af;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.project-search input {
|
||||
border: none;
|
||||
outline: none;
|
||||
font-size: 13px;
|
||||
color: #374151;
|
||||
width: 160px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.project-search input::placeholder { color: #9ca3af; }
|
||||
|
||||
.project-board-body {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* 项目树 */
|
||||
.project-tree {
|
||||
width: 200px;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.project-tree-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.project-tree-node {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 16px;
|
||||
font-size: 13px;
|
||||
color: #334155;
|
||||
cursor: pointer;
|
||||
transition: background 0.1s;
|
||||
border-left: 3px solid transparent;
|
||||
}
|
||||
|
||||
.project-tree-node:hover {
|
||||
background: #f1f5f9;
|
||||
}
|
||||
|
||||
.project-tree-node.active {
|
||||
background: #eff6ff;
|
||||
border-left-color: #3b82f6;
|
||||
color: #1d4ed8;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.project-tree-icon {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
color: #94a3b8;
|
||||
}
|
||||
|
||||
.project-tree-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.project-tree-empty {
|
||||
padding: 20px 16px;
|
||||
font-size: 13px;
|
||||
color: #94a3b8;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* 右键菜单 */
|
||||
.project-context-menu {
|
||||
position: fixed;
|
||||
z-index: 100;
|
||||
background: #fff;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
|
||||
padding: 4px 0;
|
||||
min-width: 140px;
|
||||
}
|
||||
|
||||
.project-context-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 7px 12px;
|
||||
font-size: 12px;
|
||||
color: #334155;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.project-context-item:hover {
|
||||
background: #f1f5f9;
|
||||
}
|
||||
|
||||
.project-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
color: #94a3b8;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
/* 台账任务流(Plane 风格) */
|
||||
.task-feed {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow-y: auto;
|
||||
min-width: 0;
|
||||
border-left: 1px solid #edf2f7;
|
||||
}
|
||||
|
||||
.task-feed-hd {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 8px 16px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.task-feed-body {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.task-section {
|
||||
border-bottom: 1px solid #edf2f7;
|
||||
border-top: 1px solid #edf2f7;
|
||||
}
|
||||
.task-section:first-child { border-top: none; }
|
||||
|
||||
.task-section-hd {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 20px;
|
||||
background: #fafbfc;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.task-section-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
color: #9ca3af;
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
|
||||
.task-section-list-wrap.collapsed {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.task-section-icon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
.task-section-label {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: #111827;
|
||||
}
|
||||
|
||||
.task-section-n {
|
||||
background: #e5e7eb;
|
||||
color: #6b7280;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
padding: 2px 8px;
|
||||
border-radius: 10px;
|
||||
min-width: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.task-section-list {
|
||||
/* flat list, no card */
|
||||
}
|
||||
|
||||
.task-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
height: 60px;
|
||||
padding: 9px 20px;
|
||||
cursor: pointer;
|
||||
transition: background 0.1s;
|
||||
border-bottom: 1px solid #f1f5f9;
|
||||
}
|
||||
.task-item:last-child { border-bottom: none; }
|
||||
|
||||
.task-item:hover {
|
||||
background: #f9fafb;
|
||||
}
|
||||
|
||||
.task-item.task-done .task-title {
|
||||
text-decoration: line-through;
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
/* 状态徽章 */
|
||||
.task-status-badge {
|
||||
flex-shrink: 0;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
padding: 2px 8px;
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.status-未开始 { background: #f1f5f9; color: #64748b; }
|
||||
.status-进行中 { background: #dbeafe; color: #1d4ed8; }
|
||||
.status-验收中 { background: #fef3c7; color: #92400e; }
|
||||
.status-已结束 { background: #dcfce7; color: #166534; }
|
||||
/* 产品版本状态 */
|
||||
.status-规划中 { background: #f1f5f9; color: #64748b; }
|
||||
.status-开发中 { background: #dbeafe; color: #1d4ed8; }
|
||||
.status-测试中 { background: #fef3c7; color: #92400e; }
|
||||
.status-已上线 { background: #dcfce7; color: #166534; }
|
||||
.status-已取消 { background: #f1f5f9; color: #94a3b8; }
|
||||
.status-badge {
|
||||
flex-shrink: 0; display: inline-flex; align-items: center;
|
||||
font-size: 12px; font-weight: 500; padding: 2px 10px;
|
||||
border-radius: 10px; cursor: pointer; white-space: nowrap;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
/* 优先级底色 */
|
||||
.task-p0 { background: #fef2f2; }
|
||||
.task-p0:hover { background: #fee2e2; }
|
||||
.task-p1 { background: #fffbeb; }
|
||||
.task-p1:hover { background: #fef3c7; }
|
||||
|
||||
.task-priority-badge {
|
||||
flex-shrink: 0;
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
padding: 1px 6px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.priority-p0 { background: #fecaca; color: #991b1b; }
|
||||
.priority-p1 { background: #fde68a; color: #92400e; }
|
||||
.priority-p2 { background: #e2e8f0; color: #475569; }
|
||||
.priority-p3 { background: #f1f5f9; color: #94a3b8; }
|
||||
|
||||
.task-check {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
color: #9ca3af;
|
||||
cursor: pointer;
|
||||
}
|
||||
.task-check:hover {
|
||||
color: #3b82f6;
|
||||
}
|
||||
|
||||
.task-grip {
|
||||
flex-shrink: 0;
|
||||
color: #d1d5db;
|
||||
cursor: grab;
|
||||
padding: 2px 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.task-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
}
|
||||
.task-item.task-detail .task-content { flex-direction: row; align-items: center; gap: 8px; }
|
||||
|
||||
.task-feed .task-title {
|
||||
font-weight: 400;
|
||||
color: #1f2937;
|
||||
font-size: 12px;
|
||||
}
|
||||
.task-item.task-detail .task-title { font-weight: 500; white-space: nowrap; flex-shrink: 0; }
|
||||
|
||||
.task-desc {
|
||||
font-size: 12px;
|
||||
color: #9ca3af;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: 360px;
|
||||
}
|
||||
|
||||
.task-meta {
|
||||
flex-shrink: 0;
|
||||
font-size: 12px;
|
||||
color: #6b7280;
|
||||
min-width: 56px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.task-blocker {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
color: #ef4444;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.task-item.task-detail .task-blocker {
|
||||
display: inline;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 240px;
|
||||
margin-top: 0;
|
||||
flex-shrink: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.task-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 60px 20px;
|
||||
color: #9ca3af;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
/* 业务方案列表项 */
|
||||
.proposal-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 20px;
|
||||
border-bottom: 1px solid #f3f4f6;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
|
||||
/* 上传任务列表 */
|
||||
#uploadTaskList {
|
||||
display: none;
|
||||
padding: 12px 20px;
|
||||
border-top: 1px solid #e2e8f0;
|
||||
}
|
||||
.upload-task {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
.upload-task-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
color: #334155;
|
||||
}
|
||||
.upload-task-bar {
|
||||
width: 80px;
|
||||
height: 4px;
|
||||
background: #e5e7eb;
|
||||
border-radius: 2px;
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.upload-task-fill {
|
||||
height: 100%;
|
||||
background: #3b82f6;
|
||||
border-radius: 2px;
|
||||
transition: width 0.2s;
|
||||
}
|
||||
.upload-task-pct {
|
||||
width: 32px;
|
||||
text-align: right;
|
||||
color: #6b7280;
|
||||
font-size: 11px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.upload-task-cancel {
|
||||
flex-shrink: 0;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: none;
|
||||
background: none;
|
||||
color: #9ca3af;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.upload-task-cancel:hover { color: #ef4444; background: #fef2f2; }
|
||||
.proposal-item:hover { background: #f9fafb; }
|
||||
|
||||
.proposal-customer {
|
||||
flex: 0 0 140px;
|
||||
font-weight: 500;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
.proposal-notes {
|
||||
flex: 1;
|
||||
color: #6b7280;
|
||||
font-size: 12px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.proposal-files {
|
||||
flex-shrink: 0;
|
||||
font-size: 12px;
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: white;
|
||||
border: 1px solid #e2e8f0;
|
||||
@@ -95,17 +644,90 @@ body {
|
||||
.btn-ghost { background: white; border: 1px solid #e2e8f0; color: #334155; }
|
||||
.btn-ghost:hover { background: #f8fafc; }
|
||||
|
||||
/* ===== 表单控件统一标准 ===== */
|
||||
input,
|
||||
select,
|
||||
textarea {
|
||||
border: 1px solid #cbd5e1;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 6px;
|
||||
min-height: 38px;
|
||||
padding: 8px 10px;
|
||||
padding: 8px 12px;
|
||||
font-size: 13px;
|
||||
color: #1e293b;
|
||||
background: #fff;
|
||||
outline: none;
|
||||
transition: border-color 0.15s, box-shadow 0.15s;
|
||||
height: 38px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
select {
|
||||
appearance: none;
|
||||
-webkit-appearance: none;
|
||||
background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat;
|
||||
background-position: right 10px center;
|
||||
padding-right: 32px;
|
||||
}
|
||||
input:focus,
|
||||
select:focus,
|
||||
textarea:focus {
|
||||
border-color: #2563eb;
|
||||
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.08);
|
||||
}
|
||||
input::placeholder,
|
||||
textarea::placeholder { color: #cbd5e1; }
|
||||
input:disabled,
|
||||
select:disabled,
|
||||
textarea:disabled { background: #f8fafc; cursor: not-allowed; }
|
||||
|
||||
textarea { min-height: 80px; height: auto; resize: vertical; }
|
||||
|
||||
/* 标准控件类 */
|
||||
.form-ctrl {
|
||||
display: block;
|
||||
height: 38px;
|
||||
width: 100%;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 6px;
|
||||
padding: 8px 12px;
|
||||
font-size: 13px;
|
||||
color: #1e293b;
|
||||
background: #fff;
|
||||
outline: none;
|
||||
transition: border-color 0.15s, box-shadow 0.15s;
|
||||
}
|
||||
.form-ctrl:focus {
|
||||
border-color: #2563eb;
|
||||
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.08);
|
||||
}
|
||||
.form-ctrl::placeholder { color: #cbd5e1; }
|
||||
.form-ctrl:disabled { background: #f8fafc; cursor: not-allowed; }
|
||||
|
||||
/* 紧凑变体 */
|
||||
.form-ctrl-sm {
|
||||
padding: 5px 10px;
|
||||
font-size: 12px;
|
||||
height: 32px;
|
||||
}
|
||||
|
||||
textarea {
|
||||
min-height: 96px;
|
||||
/* 产品表格内联日期选择器 */
|
||||
.prod-date-input {
|
||||
border: 1px solid transparent;
|
||||
background: transparent;
|
||||
font-size: 12px;
|
||||
padding: 2px 4px;
|
||||
border-radius: 4px;
|
||||
width: 110px;
|
||||
cursor: pointer;
|
||||
color: #64748b;
|
||||
}
|
||||
.prod-date-input:hover {
|
||||
border-color: #cbd5e1;
|
||||
background: #f8fafc;
|
||||
}
|
||||
.prod-date-input:focus {
|
||||
border-color: #3b82f6;
|
||||
background: white;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
table {
|
||||
@@ -207,35 +829,6 @@ td {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.drawer-value {
|
||||
background: transparent;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 5px;
|
||||
color: #0f172a;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
min-height: 30px;
|
||||
padding: 4px 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.drawer-value:hover {
|
||||
background: #f8fafc;
|
||||
border-color: #e2e8f0;
|
||||
}
|
||||
|
||||
.drawer-value:focus {
|
||||
background: white;
|
||||
border-color: #60a5fa;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.drawer-textarea {
|
||||
line-height: 1.45;
|
||||
min-height: 54px;
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.activity-item {
|
||||
background: #f8fafc;
|
||||
border: 1px solid #e2e8f0;
|
||||
@@ -263,23 +856,6 @@ td {
|
||||
width: 13px;
|
||||
}
|
||||
|
||||
.inline-form input,
|
||||
.inline-form select {
|
||||
height: 40px;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 6px;
|
||||
padding: 8px 10px;
|
||||
font-size: 14px;
|
||||
background: white;
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
.inline-form input:focus,
|
||||
.inline-form select:focus {
|
||||
border-color: #3b82f6;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.clickable-row {
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
@@ -507,7 +1083,7 @@ td {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
padding: 16px 20px; border-bottom: 1px solid #e2e8f0;
|
||||
}
|
||||
.task-title { color: #1e293b; font-size: 15px; font-weight: 600; }
|
||||
.task-drawer .task-title { color: #1e293b; font-size: 15px; font-weight: 600; }
|
||||
.task-close {
|
||||
color: #94a3b8; background: none; border: none; cursor: pointer;
|
||||
padding: 4px; border-radius: 6px; display: flex;
|
||||
@@ -554,6 +1130,9 @@ td {
|
||||
.task-row:hover { background: #f8fafc; }
|
||||
.task-dot { display: flex; color: #cbd5e1; flex-shrink: 0; cursor: pointer; }
|
||||
.task-dot:hover { color: #6366f1; }
|
||||
.task-grip { display: flex; color: #cbd5e1; flex-shrink: 0; cursor: grab; }
|
||||
.task-grip:hover { color: #94a3b8; }
|
||||
.task-grip:active { cursor: grabbing; }
|
||||
.task-main { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; }
|
||||
.task-name { color: #1e293b; font-size: 13px; }
|
||||
.task-desc { color: #94a3b8; font-size: 12px; word-wrap: break-word; overflow-wrap: break-word; }
|
||||
@@ -565,13 +1144,9 @@ td {
|
||||
background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px;
|
||||
padding: 14px; margin-bottom: 16px;
|
||||
}
|
||||
.task-field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 4px; }
|
||||
.task-field { display: flex; flex-direction: column; gap: 4px; }
|
||||
.task-field span { color: #64748b; font-size: 12px; }
|
||||
.task-field input, .task-field select, .task-field textarea {
|
||||
background: #fff; border: 1px solid #e2e8f0; border-radius: 6px;
|
||||
color: #1e293b; font-size: 13px; padding: 6px 10px; outline: none;
|
||||
}
|
||||
.task-field input:focus, .task-field select:focus, .task-field textarea:focus { border-color: #2563eb; }
|
||||
.task-field span { color: #64748b; font-size: 12px; font-weight: 500; }
|
||||
.col-span-2 { grid-column: span 2; }
|
||||
.task-group-add {
|
||||
display: block; width: 100%; padding: 10px; text-align: center;
|
||||
@@ -579,3 +1154,65 @@ td {
|
||||
border-top: 1px solid #24272d; cursor: pointer;
|
||||
}
|
||||
.task-group-add:hover { color: #e4e5e7; background: #24272d; }
|
||||
|
||||
/* Feature list(产品版本核心功能编号列表) */
|
||||
.feature-item {
|
||||
display: flex; align-items: center; gap: 8px; margin-bottom: 6px;
|
||||
}
|
||||
.feature-num {
|
||||
color: #94a3b8; font-size: 13px; font-weight: 500; min-width: 22px; flex-shrink: 0;
|
||||
}
|
||||
.feature-item .form-ctrl { flex: 1; padding: 5px 10px; }
|
||||
.feature-del {
|
||||
flex-shrink: 0; display: flex; align-items: center; justify-content: center;
|
||||
width: 22px; height: 22px; border-radius: 4px; border: none; background: none;
|
||||
color: #94a3b8; cursor: pointer; transition: color 0.15s;
|
||||
}
|
||||
.feature-del:hover { color: #ef4444; background: #fef2f2; }
|
||||
|
||||
/* Toast 通知 */
|
||||
.toast-container {
|
||||
position: fixed; top: 16px; right: 16px; z-index: 9999;
|
||||
display: flex; flex-direction: column; gap: 8px; pointer-events: none;
|
||||
}
|
||||
.toast {
|
||||
pointer-events: auto;
|
||||
display: flex; align-items: center; gap: 10px;
|
||||
padding: 10px 16px; border-radius: 8px;
|
||||
font-size: 13px; font-weight: 500;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.12);
|
||||
animation: toastIn 0.2s ease-out; max-width: 380px;
|
||||
}
|
||||
.toast.toast-success { background: #f0fdf4; color: #166534; border: 1px solid #bbf7d0; }
|
||||
.toast.toast-error { background: #fef2f2; color: #991b1b; border: 1px solid #fecaca; }
|
||||
.toast.toast-info { background: #eff6ff; color: #1e40af; border: 1px solid #bfdbfe; }
|
||||
.toast.fade-out { animation: toastOut 0.25s ease-in forwards; }
|
||||
@keyframes toastIn { from { opacity: 0; transform: translateX(20px); } to { opacity: 1; transform: translateX(0); } }
|
||||
@keyframes toastOut { to { opacity: 0; transform: translateX(20px); } }
|
||||
|
||||
/* 财务弹窗优化 */
|
||||
.fin-field-group {
|
||||
background: #f8fafc;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 10px;
|
||||
padding: 18px;
|
||||
}
|
||||
.fin-section-label {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: #334155;
|
||||
margin-bottom: 14px;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 1px solid #e2e8f0;
|
||||
}
|
||||
.fin-label {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: #64748b;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
/* 项目树拖拽 */
|
||||
.project-tree-node.dragging { opacity: 0.4; }
|
||||
.project-tree-node.drag-over { border-top: 2px solid #2563eb; }
|
||||
|
||||
@@ -26,31 +26,60 @@
|
||||
<script src="{{ url_for('static', filename='vendor/lucide.js') }}" defer></script>
|
||||
</head>
|
||||
<body class="min-h-screen bg-slate-50 text-slate-950">
|
||||
<div class="flex min-h-screen">
|
||||
<!-- 左侧工作台切换栏 -->
|
||||
<aside class="w-[72px] bg-slate-900 flex flex-col items-center py-6 gap-1 shrink-0 sticky top-0 h-screen overflow-y-auto" id="workspaceSidebar">
|
||||
<div class="flex flex-col items-center mb-2 cursor-pointer" onclick="document.getElementById('userAvatar').click()">
|
||||
<div class="w-10 h-10 rounded-full bg-slate-700 flex items-center justify-center text-white font-bold text-sm hover:ring-2 hover:ring-blue-400 transition-all" id="userAvatar" title=""></div>
|
||||
<span class="text-[10px] text-slate-400 mt-1.5 max-w-[64px] truncate text-center" id="userDisplayName" title=""></span>
|
||||
</div>
|
||||
<!-- 分隔线 -->
|
||||
<div class="w-8 h-px bg-slate-700 my-2"></div>
|
||||
<!-- 工作台切换按钮 -->
|
||||
<div class="flex flex-col items-center cursor-pointer hover:bg-slate-800 rounded-lg py-2 px-1 w-14 transition-colors" onclick="toggleTenantMenu(event)">
|
||||
<i data-lucide="layout-grid" style="width:18px;height:18px;color:#94a3b8"></i>
|
||||
<span class="text-[10px] text-slate-400 mt-1 max-w-[56px] truncate text-center" id="currentTenantLabel">工作台</span>
|
||||
<i data-lucide="chevron-down" style="width:12px;height:12px;color:#64748b;margin-top:2px"></i>
|
||||
</div>
|
||||
<!-- 分隔线 -->
|
||||
<div class="w-8 h-px bg-slate-700 my-2"></div>
|
||||
<!-- 导航 Tab 图标 -->
|
||||
<div class="flex flex-col items-center gap-1 w-14" id="sidebarTabs">
|
||||
<div class="sidebar-tab active" data-tab="home" onclick="switchTab('home')" title="首页">
|
||||
<i data-lucide="home" style="width:20px;height:20px"></i>
|
||||
<span class="text-[10px] mt-1">首页</span>
|
||||
</div>
|
||||
<div class="sidebar-tab" data-tab="finance" onclick="switchTab('finance')" title="经营管理">
|
||||
<i data-lucide="briefcase-business" style="width:20px;height:20px"></i>
|
||||
<span class="text-[10px] mt-1">财务</span>
|
||||
</div>
|
||||
<div class="sidebar-tab" data-tab="projects" onclick="switchTab('projects')" title="重点工作与台账">
|
||||
<i data-lucide="file-text" style="width:20px;height:20px"></i>
|
||||
<span class="text-[10px] mt-1">台账</span>
|
||||
</div>
|
||||
<div class="sidebar-tab" data-tab="proposals" onclick="switchTab('proposals')" title="业务方案">
|
||||
<i data-lucide="package" style="width:20px;height:20px"></i>
|
||||
<span class="text-[10px] mt-1">方案</span>
|
||||
</div>
|
||||
<div class="sidebar-tab" data-tab="products" onclick="switchTab('products')" title="产品迭代">
|
||||
<i data-lucide="wallet-cards" style="width:20px;height:20px"></i>
|
||||
<span class="text-[10px] mt-1">产品</span>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
<!-- 主内容区 -->
|
||||
<div class="flex-1 min-w-0">
|
||||
<header class="topbar border-b border-slate-200 bg-white px-8 py-5">
|
||||
<div class="flex items-center gap-3">
|
||||
<div>
|
||||
<p class="eyebrow text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">OPC Manager</p>
|
||||
<div class="flex items-center gap-3 mt-1">
|
||||
<h1 class="text-2xl font-semibold">无界 OPC 工作台</h1>
|
||||
<select id="tenantSelect" class="rounded-md border border-slate-200 bg-white px-3 py-1.5 text-sm font-medium text-slate-700 outline-none focus:border-blue-500" onchange="switchTenant(this.value)">
|
||||
<option value="科普·无界">科普·无界</option>
|
||||
<option value="科研·无界">科研·无界</option>
|
||||
<option value="医患·无界">医患·无界</option>
|
||||
</select>
|
||||
<h1 class="text-2xl font-semibold" id="workspaceTitle">科普 OPC 工作台</h1>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button id="refreshBtn" class="rounded-md border border-slate-200 bg-white px-3 py-2 text-sm font-medium hover:bg-slate-50" type="button"><i data-lucide="refresh-cw"></i>刷新</button>
|
||||
</header>
|
||||
|
||||
<nav class="tabs border-b border-slate-200 bg-white px-8" id="tabs">
|
||||
<button class="active" data-tab="home"><i data-lucide="home"></i>首页</button>
|
||||
<button data-tab="projects"><i data-lucide="briefcase-business"></i>重点项目</button>
|
||||
<button data-tab="proposals"><i data-lucide="file-text"></i>业务方案</button>
|
||||
<button data-tab="products"><i data-lucide="package"></i>产品研发</button>
|
||||
<button data-tab="finance"><i data-lucide="wallet-cards"></i>财务管理</button>
|
||||
</nav>
|
||||
|
||||
<main class="px-8 py-6">
|
||||
<section id="home" class="panel active"></section>
|
||||
<section id="projects" class="panel"></section>
|
||||
@@ -58,9 +87,35 @@
|
||||
<section id="products" class="panel"></section>
|
||||
<section id="finance" class="panel"></section>
|
||||
</main>
|
||||
|
||||
</div><!-- 关闭主内容区 -->
|
||||
</div><!-- 关闭 flex 容器 -->
|
||||
<aside id="drawer" class="drawer" aria-hidden="true"></aside>
|
||||
<div id="taskModal" class="task-modal"></div>
|
||||
<!-- 新增项目模态框 -->
|
||||
<div id="newProjectModal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/40" onclick="closeNewProjectModal()">
|
||||
<div class="bg-white rounded-2xl shadow-2xl w-full max-w-md mx-4" onclick="event.stopPropagation()">
|
||||
<div class="flex items-center justify-between px-6 py-4 border-b border-slate-100">
|
||||
<h3 class="text-lg font-semibold text-slate-800">新增项目</h3>
|
||||
<button class="btn btn-ghost btn-sm rounded-full w-8 h-8 p-0" onclick="closeNewProjectModal()"><i data-lucide="x"></i></button>
|
||||
</div>
|
||||
<form onsubmit="createOperation(event)" class="p-6 grid gap-4">
|
||||
<label class="block"><span class="text-xs font-medium text-slate-500">项目名称</span><input name="project_name" required class="form-ctrl mt-1"></label>
|
||||
<label class="block"><span class="text-xs font-medium text-slate-500">项目备注</span><textarea name="notes" rows="3" class="form-ctrl mt-1" placeholder="可选"></textarea></label>
|
||||
<div class="flex justify-end gap-3 pt-3 border-t border-slate-100">
|
||||
<button type="button" class="btn btn-ghost btn-sm" onclick="closeNewProjectModal()">取消</button>
|
||||
<button type="submit" class="btn btn-primary btn-sm">创建</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<script src="{{ url_for('static', filename='modules/utils.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='modules/home.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='modules/projects.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='modules/proposals.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='modules/products.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='modules/finance.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='modules/drawer.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='modules/admin.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='app.js') }}"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
102
templates/login.html
Normal file
102
templates/login.html
Normal file
@@ -0,0 +1,102 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>OPC 工作台 · 登录</title>
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/lucide.js') }}" onerror="this.remove()">
|
||||
<script src="{{ url_for('static', filename='vendor/lucide.js') }}"></script>
|
||||
<style>
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
body{font-family:PingFang SC,Microsoft YaHei,-apple-system,sans-serif;background:#f8fafc;min-height:100vh;display:flex;align-items:center;justify-content:center}
|
||||
.card{background:#fff;border-radius:16px;padding:40px 44px;width:400px;max-width:94vw;box-shadow:0 16px 48px rgba(15,23,42,.12)}
|
||||
.logo{text-align:center;margin-bottom:32px}
|
||||
.logo .icon{width:56px;height:56px;margin:0 auto 10px;display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,#1e293b,#0f172a);border-radius:14px;color:#fff}
|
||||
.logo h1{font-size:20px;font-weight:700;color:#1e293b}
|
||||
.logo p{font-size:13px;color:#94a3b8;margin-top:4px}
|
||||
.form-group{margin-bottom:18px}
|
||||
label{display:block;font-size:13px;font-weight:500;color:#475569;margin-bottom:6px}
|
||||
.input-wrap{position:relative}
|
||||
input[type=text],input[type=password]{width:100%;height:42px;padding:0 14px;border:1px solid #cbd5e1;border-radius:8px;font-size:14px;outline:none;transition:.2s;font-family:inherit;color:#1e293b;background:#fff}
|
||||
.input-wrap input{padding:0 40px 0 14px}
|
||||
input[type=text]:focus,input[type=password]:focus,.input-wrap input:focus{border-color:#334155;box-shadow:0 0 0 3px rgba(51,65,85,.12)}
|
||||
input::placeholder{color:#94a3b8}
|
||||
.toggle-pwd{position:absolute;right:10px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:#94a3b8;padding:4px;display:flex;align-items:center;justify-content:center;transition:.2s}
|
||||
.toggle-pwd:hover{color:#334155}
|
||||
.btn{width:100%;height:44px;background:#1e293b;color:#fff;border:none;border-radius:8px;font-size:15px;font-weight:600;cursor:pointer;transition:.2s;margin-top:8px}
|
||||
.btn:hover{background:#0f172a}
|
||||
.btn:active{transform:scale(.98)}
|
||||
.err{background:#fef2f2;border:1px solid #fecaca;color:#dc2626;border-radius:8px;padding:10px 14px;font-size:13px;margin-bottom:16px;display:none}
|
||||
.err.show{display:block}
|
||||
.footer{text-align:center;margin-top:24px;font-size:11px;color:#94a3b8}
|
||||
.footer strong{color:#334155}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<div class="logo">
|
||||
<div class="icon"><i data-lucide="layout-dashboard" style="width:28px;height:28px;stroke-width:2"></i></div>
|
||||
<h1>OPC 工作台</h1>
|
||||
<p>请登录后继续</p>
|
||||
</div>
|
||||
<div class="err" id="errMsg"></div>
|
||||
<div class="form-group">
|
||||
<label>用户名</label>
|
||||
<input type="text" id="username" placeholder="请输入用户名" autocomplete="username" autofocus>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label>密码</label>
|
||||
<div class="input-wrap">
|
||||
<input type="password" id="password" placeholder="请输入密码" autocomplete="current-password">
|
||||
<button type="button" class="toggle-pwd" onclick="togglePwd('password', this)" title="显示/隐藏密码"><i data-lucide="eye" style="width:18px;height:18px"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
<button class="btn" id="loginBtn" onclick="doLogin()">登 录</button>
|
||||
<div class="footer">Powered by <strong>yxcowork.vip</strong></div>
|
||||
</div>
|
||||
<script>
|
||||
if (window.lucide) lucide.createIcons();
|
||||
|
||||
function togglePwd(id, btn) {
|
||||
const input = document.getElementById(id);
|
||||
const isPwd = input.type === 'password';
|
||||
input.type = isPwd ? 'text' : 'password';
|
||||
btn.innerHTML = isPwd
|
||||
? '<i data-lucide="eye-off" style="width:18px;height:18px"></i>'
|
||||
: '<i data-lucide="eye" style="width:18px;height:18px"></i>';
|
||||
if (window.lucide) lucide.createIcons();
|
||||
}
|
||||
|
||||
const errEl = document.getElementById('errMsg');
|
||||
function showErr(msg) { errEl.textContent = msg; errEl.classList.add('show'); }
|
||||
function clearErr() { errEl.classList.remove('show'); }
|
||||
|
||||
document.getElementById('username').addEventListener('input', clearErr);
|
||||
document.getElementById('password').addEventListener('input', clearErr);
|
||||
|
||||
// 回车提交
|
||||
document.getElementById('password').addEventListener('keydown', (e) => { if (e.key === 'Enter') doLogin(); });
|
||||
document.getElementById('username').addEventListener('keydown', (e) => { if (e.key === 'Enter') document.getElementById('password').focus(); });
|
||||
|
||||
async function doLogin() {
|
||||
clearErr();
|
||||
const username = document.getElementById('username').value.trim();
|
||||
const password = document.getElementById('password').value;
|
||||
if (!username || !password) { showErr('请输入用户名和密码'); return; }
|
||||
const btn = document.getElementById('loginBtn');
|
||||
btn.disabled = true; btn.style.opacity = .7; btn.textContent = '登录中...';
|
||||
try {
|
||||
const res = await (await fetch('/api/auth/login', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
})).json();
|
||||
if (res.error) { showErr(res.error); btn.disabled = false; btn.style.opacity = 1; btn.textContent = '登 录'; return; }
|
||||
window.location.href = '/';
|
||||
} catch (err) {
|
||||
showErr('网络错误,请重试');
|
||||
btn.disabled = false; btn.style.opacity = 1; btn.textContent = '登 录';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user