Compare commits
44 Commits
bed6e9192a
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0dc1a56b2 | ||
|
|
39350e2363 | ||
|
|
f45afd954d | ||
|
|
f44f7eab9e | ||
|
|
664da22329 | ||
|
|
dbc98e4693 | ||
|
|
73a6ac126c | ||
|
|
ac312741df | ||
|
|
878e26d4ca | ||
|
|
1b88366ba0 | ||
|
|
e12ed0936b | ||
|
|
56feeb0cfe | ||
|
|
8edb74f173 | ||
|
|
340f8bd88c | ||
|
|
1a42c6e6f3 | ||
|
|
7ab0c71b54 | ||
|
|
d21497bce3 | ||
|
|
8a78c756b7 | ||
|
|
574e3c5700 | ||
|
|
8430c93b97 | ||
|
|
c70293b447 | ||
|
|
ff7eb19d5d | ||
|
|
adeff08827 | ||
|
|
493150cb27 | ||
|
|
8bd40de41d | ||
|
|
caebf90438 | ||
|
|
ac6eacea82 | ||
|
|
34786ba9e5 | ||
|
|
83c2a5ca94 | ||
|
|
fbff2e5f24 | ||
|
|
fbd2290d29 | ||
|
|
0eb9d69f1e | ||
|
|
97fcf88c61 | ||
|
|
003b6f3bdb | ||
|
|
a01afef599 | ||
|
|
9226233de5 | ||
|
|
28fa244fe5 | ||
|
|
96948a37de | ||
|
|
ad3885e0be | ||
|
|
d47fde60a4 | ||
|
|
0fb7ee2992 | ||
|
|
2bb99feda4 | ||
|
|
f6792cad39 | ||
|
|
33f47acc55 |
@@ -83,7 +83,7 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
echo "=== 7. Cleanup old releases ==="
|
echo "=== 7. Cleanup old releases ==="
|
||||||
find "${DEPLOY_BASE}/releases" -mindepth 1 -maxdepth 1 -type d | sort | head -n -5 | xargs -r rm -rf
|
ls -dt "${DEPLOY_BASE}"/releases/*/ | tail -n +6 | xargs -r rm -rf
|
||||||
|
|
||||||
echo "=== 8. Cleanup temp ==="
|
echo "=== 8. Cleanup temp ==="
|
||||||
rm -rf "${CLONE_DIR}"
|
rm -rf "${CLONE_DIR}"
|
||||||
|
|||||||
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
|
||||||
1058
backend/flask_app.py
1058
backend/flask_app.py
File diff suppressed because it is too large
Load Diff
126
backend/helpers.py
Normal file
126
backend/helpers.py
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
# 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, expense_data FROM project_finances WHERE tenant=? AND status='已签约'",
|
||||||
|
[tenant])
|
||||||
|
|
||||||
|
parsed_budgets = []
|
||||||
|
expense_maps = {}
|
||||||
|
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),
|
||||||
|
}
|
||||||
|
parsed_budgets.append((pf, budget_map))
|
||||||
|
|
||||||
|
# Parse expense_data for cost/paid
|
||||||
|
try:
|
||||||
|
ed = json.loads(pf.get("expense_data") or "[]")
|
||||||
|
except (json.JSONDecodeError, TypeError):
|
||||||
|
ed = []
|
||||||
|
em = {}
|
||||||
|
for e in ed:
|
||||||
|
key = (e.get("month") or "").replace("-", "_")
|
||||||
|
em[key] = {
|
||||||
|
"cost": float(e.get("cost") or 0),
|
||||||
|
"paid": float(e.get("paid") or 0),
|
||||||
|
}
|
||||||
|
expense_maps[pf.get("id", id(pf))] = em
|
||||||
|
|
||||||
|
data = []
|
||||||
|
for month in months:
|
||||||
|
key = month.replace("-", "_")
|
||||||
|
revenue = gross = payment = cost = paid = 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"]
|
||||||
|
em = expense_maps.get(pf.get("id", id(pf)), {})
|
||||||
|
e = em.get(key)
|
||||||
|
if e:
|
||||||
|
cost += e["cost"]
|
||||||
|
paid += e["paid"]
|
||||||
|
data.append({
|
||||||
|
"month": month,
|
||||||
|
"revenue": round(revenue, 2),
|
||||||
|
"gross": round(gross, 2),
|
||||||
|
"payment": round(payment, 2),
|
||||||
|
"cost": round(cost, 2),
|
||||||
|
"paid": round(paid, 2),
|
||||||
|
"sign": round(sign, 2),
|
||||||
|
})
|
||||||
|
return data
|
||||||
32
backend/migrations/__init__.py
Normal file
32
backend/migrations/__init__.py
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
"""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.data_split import migrate_data_split
|
||||||
|
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_data_split()
|
||||||
|
migrate_seed_users()
|
||||||
|
migrate_seed_demo_data()
|
||||||
116
backend/migrations/columns.py
Normal file
116
backend/migrations/columns.py
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
"""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 ''")
|
||||||
|
# expense_records 字段迁移(重构为费用类型+月份+金额+已发生金额+费用说明)
|
||||||
|
_add_column_if_missing(conn, "expense_records", "expense_type",
|
||||||
|
"ALTER TABLE expense_records ADD COLUMN expense_type VARCHAR(100) NOT NULL DEFAULT ''")
|
||||||
|
_add_column_if_missing(conn, "expense_records", "expense_month",
|
||||||
|
"ALTER TABLE expense_records ADD COLUMN expense_month VARCHAR(20) NOT NULL DEFAULT ''")
|
||||||
|
_add_column_if_missing(conn, "expense_records", "incurred_amount",
|
||||||
|
"ALTER TABLE expense_records ADD COLUMN incurred_amount DOUBLE NOT NULL DEFAULT 0")
|
||||||
|
|
||||||
|
# project_finances 费用明细 JSON 数据
|
||||||
|
_add_column_if_missing(conn, "project_finances", "expense_data",
|
||||||
|
"ALTER TABLE project_finances ADD COLUMN expense_data TEXT")
|
||||||
|
|
||||||
|
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()
|
||||||
56
backend/migrations/data_split.py
Normal file
56
backend/migrations/data_split.py
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
"""migrations/data_split.py — 预算数据拆分迁移:budget_data → expense_data
|
||||||
|
|
||||||
|
旧结构:budget_data = [{month, rev, gross, payment, cost, paid}]
|
||||||
|
新结构:expense_data = [{month, expense_type, cost, paid, exp_note}]
|
||||||
|
|
||||||
|
部署时自动:检测未拆分的旧数据,将 cost/paid 从 budget_data 迁移到 expense_data。
|
||||||
|
幂等:只处理 expense_data 为空的记录。
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_data_split():
|
||||||
|
"""一次性数据拆分迁移"""
|
||||||
|
from db import db, _exec
|
||||||
|
import json
|
||||||
|
|
||||||
|
conn = db()
|
||||||
|
try:
|
||||||
|
# 查询未迁移的记录
|
||||||
|
cur = conn.cursor(dictionary=True)
|
||||||
|
cur.execute(
|
||||||
|
"SELECT id, budget_data, expense_data FROM project_finances "
|
||||||
|
"WHERE (expense_data IS NULL OR expense_data = '' OR expense_data = '[]') "
|
||||||
|
"AND budget_data IS NOT NULL AND budget_data != '' AND budget_data != '[]'"
|
||||||
|
)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
cur.close()
|
||||||
|
|
||||||
|
migrated = 0
|
||||||
|
for row in rows:
|
||||||
|
try:
|
||||||
|
budget = json.loads(row.get("budget_data") or "[]")
|
||||||
|
except (json.JSONDecodeError, TypeError):
|
||||||
|
continue
|
||||||
|
|
||||||
|
expense_rows = []
|
||||||
|
for b in budget:
|
||||||
|
expense_rows.append({
|
||||||
|
"month": b.get("month", ""),
|
||||||
|
"expense_type": "",
|
||||||
|
"cost": float(b.get("cost") or 0),
|
||||||
|
"paid": float(b.get("paid") or 0),
|
||||||
|
"exp_note": "",
|
||||||
|
})
|
||||||
|
|
||||||
|
if expense_rows:
|
||||||
|
_exec(
|
||||||
|
conn,
|
||||||
|
"UPDATE project_finances SET expense_data = ? WHERE id = ?",
|
||||||
|
(json.dumps(expense_rows, ensure_ascii=False), row["id"]),
|
||||||
|
)
|
||||||
|
migrated += 1
|
||||||
|
|
||||||
|
conn.commit()
|
||||||
|
print(f"[migrate] 数据拆分迁移完成:{migrated} 条记录已从 budget_data 提取 cost/paid 到 expense_data")
|
||||||
|
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()
|
||||||
173
backend/migrations/tables.py
Normal file
173
backend/migrations/tables.py
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
"""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 ''
|
||||||
|
)""",
|
||||||
|
"""CREATE TABLE IF NOT EXISTS expense_records (
|
||||||
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
tenant VARCHAR(100) NOT NULL DEFAULT '科普·无界',
|
||||||
|
expense_type VARCHAR(100) NOT NULL DEFAULT '',
|
||||||
|
expense_month VARCHAR(20) NOT NULL DEFAULT '',
|
||||||
|
amount DOUBLE NOT NULL DEFAULT 0,
|
||||||
|
incurred_amount DOUBLE NOT NULL DEFAULT 0,
|
||||||
|
notes VARCHAR(1000) NOT NULL DEFAULT '',
|
||||||
|
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()
|
||||||
798
backend/routes.py
Normal file
798
backend/routes.py
Normal file
@@ -0,0 +1,798 @@
|
|||||||
|
# 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", "expense_data", "start_date", "end_date", "task_type", "task_count", "service_fee_standard", "project_manager", "task_data", "project_code", "contact_name", "contact_phone", "other_info"]),
|
||||||
|
"expense": ("expense_records", ["expense_type", "expense_month", "amount", "incurred_amount", "notes", "tenant"]),
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---------- 鉴权装饰器 ----------
|
||||||
|
|
||||||
|
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_expense = rows(conn, "SELECT * FROM expense_records WHERE tenant=?", [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
|
||||||
|
|
||||||
|
def t_parse_expense(pf):
|
||||||
|
try:
|
||||||
|
ed = json.loads(pf.get("expense_data") or "[]")
|
||||||
|
except (json.JSONDecodeError, TypeError):
|
||||||
|
ed = []
|
||||||
|
return {(e.get("month") or "").replace("-", "_"): e for e in ed}
|
||||||
|
|
||||||
|
t_em = {pf["id"]: t_parse_expense(pf) for pf in t_pfs}
|
||||||
|
|
||||||
|
def t_sum_expense(field, months_range):
|
||||||
|
total = 0
|
||||||
|
for pf in t_pfs:
|
||||||
|
em = t_em.get(pf["id"], {})
|
||||||
|
for m in months_range:
|
||||||
|
e = em.get(f"2026_{m:02d}")
|
||||||
|
if e:
|
||||||
|
total += float(e.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_expense("cost", range(1, 13)),
|
||||||
|
"cost_q2": t_sum_expense("cost", _q_range),
|
||||||
|
"cost_month": t_sum_expense("cost", [_now_month]),
|
||||||
|
"cost_prev_q": t_sum_expense("cost", _prev_q_range),
|
||||||
|
"cost_prev_month": t_sum_expense("cost", [_prev_month]) if _prev_month else 0,
|
||||||
|
})
|
||||||
|
# 费用汇总(从 expense_records 表计算)
|
||||||
|
def t_expense_sum(m_range):
|
||||||
|
total = 0
|
||||||
|
for r in t_expense:
|
||||||
|
m = (r.get("expense_month") or "").strip()
|
||||||
|
if not m or "-" not in m: continue
|
||||||
|
try:
|
||||||
|
if int(m.split("-")[1]) in m_range:
|
||||||
|
total += float(r.get("amount") or 0)
|
||||||
|
except: pass
|
||||||
|
return total
|
||||||
|
all_metrics[-1]["expense_annual"] = t_expense_sum(range(1, 13))
|
||||||
|
all_metrics[-1]["expense_q2"] = t_expense_sum(_q_range)
|
||||||
|
all_metrics[-1]["expense_month"] = t_expense_sum([_now_month])
|
||||||
|
all_metrics[-1]["expense_prev_q"] = t_expense_sum(_prev_q_range)
|
||||||
|
all_metrics[-1]["expense_prev_month"] = t_expense_sum([_prev_month]) if _prev_month else 0
|
||||||
|
all_metrics[-1]["paid_annual"] = t_sum_expense("paid", range(1, 13))
|
||||||
|
all_metrics[-1]["paid_q2"] = t_sum_expense("paid", _q_range)
|
||||||
|
all_metrics[-1]["paid_month"] = t_sum_expense("paid", [_now_month])
|
||||||
|
all_metrics[-1]["paid_prev_q"] = t_sum_expense("paid", _prev_q_range)
|
||||||
|
all_metrics[-1]["paid_prev_month"] = t_sum_expense("paid", [_prev_month]) if _prev_month else 0
|
||||||
|
all_metrics[-1]["proj_expense_annual"] = t_sum_budget("expense", range(1, 13))
|
||||||
|
all_metrics[-1]["proj_expense_q2"] = t_sum_budget("expense", _q_range)
|
||||||
|
all_metrics[-1]["proj_expense_month"] = t_sum_budget("expense", [_now_month])
|
||||||
|
all_metrics[-1]["proj_expense_prev_q"] = t_sum_budget("expense", _prev_q_range)
|
||||||
|
all_metrics[-1]["proj_expense_prev_month"] = t_sum_budget("expense", [_prev_month]) if _prev_month else 0
|
||||||
|
all_metrics[-1]["cashflow_annual"] = all_metrics[-1]["payment_annual"] - all_metrics[-1]["paid_annual"]
|
||||||
|
all_metrics[-1]["cashflow_q2"] = all_metrics[-1]["payment_q2"] - all_metrics[-1]["paid_q2"]
|
||||||
|
all_metrics[-1]["cashflow_month"] = all_metrics[-1]["payment_month"] - all_metrics[-1]["paid_month"]
|
||||||
|
all_metrics[-1]["cashflow_prev_q"] = all_metrics[-1]["payment_prev_q"] - all_metrics[-1]["paid_prev_q"]
|
||||||
|
all_metrics[-1]["cashflow_prev_month"] = all_metrics[-1]["payment_prev_month"] - all_metrics[-1]["paid_prev_month"]
|
||||||
|
all_metrics[-1]["profit_annual"] = all_metrics[-1]["gross_annual"] - all_metrics[-1]["proj_expense_annual"]
|
||||||
|
all_metrics[-1]["profit_q2"] = all_metrics[-1]["gross_q2"] - all_metrics[-1]["proj_expense_q2"]
|
||||||
|
all_metrics[-1]["profit_month"] = all_metrics[-1]["monthly_net_profit"] - all_metrics[-1]["proj_expense_month"]
|
||||||
|
all_metrics[-1]["profit_prev_q"] = all_metrics[-1]["gross_prev_q"] - all_metrics[-1]["proj_expense_prev_q"]
|
||||||
|
all_metrics[-1]["profit_prev_month"] = all_metrics[-1]["gross_prev_month"] - all_metrics[-1]["proj_expense_prev_month"]
|
||||||
|
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","expense_annual","expense_q2","expense_month","expense_prev_q","expense_prev_month","paid_annual","paid_q2","paid_month","paid_prev_q","paid_prev_month","cashflow_annual","cashflow_q2","cashflow_month","cashflow_prev_q","cashflow_prev_month","profit_annual","profit_q2","profit_month","profit_prev_q","profit_prev_month","proj_expense_annual","proj_expense_q2","proj_expense_month","proj_expense_prev_q","proj_expense_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","paid","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": [], "expense": [], "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)
|
||||||
|
expense = q("SELECT * FROM expense_records 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 parse_expense(pf):
|
||||||
|
try:
|
||||||
|
ed = json.loads(pf.get("expense_data") or "[]")
|
||||||
|
except (json.JSONDecodeError, TypeError):
|
||||||
|
ed = []
|
||||||
|
return {(e.get("month") or "").replace("-", "_"): e for e in ed}
|
||||||
|
|
||||||
|
expense_maps = [(pf, parse_expense(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
|
||||||
|
|
||||||
|
def sum_expense(field, months_range):
|
||||||
|
total = 0
|
||||||
|
for pf, em in expense_maps:
|
||||||
|
for m in months_range:
|
||||||
|
e = em.get(f"2026_{m:02d}")
|
||||||
|
if e:
|
||||||
|
total += float(e.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_expense("cost", range(1, 13))
|
||||||
|
payment_q2 = sum_budget("payment", _q_range)
|
||||||
|
cost_q2 = sum_expense("cost", _q_range)
|
||||||
|
payment_month = sum_budget("payment", [_now_month])
|
||||||
|
cost_month = sum_expense("cost", [_now_month])
|
||||||
|
payment_prev_q = sum_budget("payment", _prev_q_range)
|
||||||
|
cost_prev_q = sum_expense("cost", _prev_q_range)
|
||||||
|
payment_prev_month = sum_budget("payment", [_prev_month]) if _prev_month else 0
|
||||||
|
cost_prev_month = sum_expense("cost", [_prev_month]) if _prev_month else 0
|
||||||
|
def expense_sum(month_range):
|
||||||
|
total = 0
|
||||||
|
for r in expense:
|
||||||
|
m = (r.get("expense_month") or "").strip()
|
||||||
|
if not m or "-" not in m: continue
|
||||||
|
try:
|
||||||
|
if int(m.split("-")[1]) in month_range:
|
||||||
|
total += float(r.get("amount") or 0)
|
||||||
|
except: pass
|
||||||
|
return total
|
||||||
|
expense_annual = expense_sum(range(1, 13))
|
||||||
|
expense_q2 = expense_sum(_q_range)
|
||||||
|
expense_month_val = expense_sum([_now_month])
|
||||||
|
expense_prev_q = expense_sum(_prev_q_range)
|
||||||
|
expense_prev_month = expense_sum([_prev_month]) if _prev_month else 0
|
||||||
|
paid_annual = sum_expense("paid", range(1, 13))
|
||||||
|
paid_q2 = sum_expense("paid", _q_range)
|
||||||
|
paid_month = sum_expense("paid", [_now_month])
|
||||||
|
paid_prev_q = sum_expense("paid", _prev_q_range)
|
||||||
|
paid_prev_month = sum_expense("paid", [_prev_month]) if _prev_month else 0
|
||||||
|
proj_expense_annual = sum_budget("expense", range(1, 13))
|
||||||
|
proj_expense_q2 = sum_budget("expense", _q_range)
|
||||||
|
proj_expense_month = sum_budget("expense", [_now_month])
|
||||||
|
proj_expense_prev_q = sum_budget("expense", _prev_q_range)
|
||||||
|
proj_expense_prev_month = sum_budget("expense", [_prev_month]) if _prev_month else 0
|
||||||
|
cashflow_annual = payment_annual - paid_annual
|
||||||
|
cashflow_q2 = payment_q2 - paid_q2
|
||||||
|
cashflow_month = payment_month - paid_month
|
||||||
|
cashflow_prev_q = payment_prev_q - paid_prev_q
|
||||||
|
cashflow_prev_month = payment_prev_month - paid_prev_month
|
||||||
|
profit_annual = gross_annual - proj_expense_annual
|
||||||
|
profit_q2 = gross_q2 - proj_expense_q2
|
||||||
|
profit_month = gross_month - proj_expense_month
|
||||||
|
profit_prev_q = gross_prev_q - proj_expense_prev_q
|
||||||
|
profit_prev_month = gross_prev_month - proj_expense_prev_month
|
||||||
|
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,
|
||||||
|
"expense_annual": expense_annual,
|
||||||
|
"expense_q2": expense_q2,
|
||||||
|
"expense_month": expense_month_val,
|
||||||
|
"expense_prev_q": expense_prev_q,
|
||||||
|
"expense_prev_month": expense_prev_month,
|
||||||
|
"paid_annual": paid_annual,
|
||||||
|
"paid_q2": paid_q2,
|
||||||
|
"paid_month": paid_month,
|
||||||
|
"paid_prev_q": paid_prev_q,
|
||||||
|
"paid_prev_month": paid_prev_month,
|
||||||
|
"cashflow_annual": cashflow_annual,
|
||||||
|
"cashflow_q2": cashflow_q2,
|
||||||
|
"cashflow_month": cashflow_month,
|
||||||
|
"cashflow_prev_q": cashflow_prev_q,
|
||||||
|
"cashflow_prev_month": cashflow_prev_month,
|
||||||
|
"profit_annual": profit_annual,
|
||||||
|
"profit_q2": profit_q2,
|
||||||
|
"profit_month": profit_month,
|
||||||
|
"profit_prev_q": profit_prev_q,
|
||||||
|
"profit_prev_month": profit_prev_month,
|
||||||
|
"proj_expense_annual": proj_expense_annual,
|
||||||
|
"proj_expense_q2": proj_expense_q2,
|
||||||
|
"proj_expense_month": proj_expense_month,
|
||||||
|
"proj_expense_prev_q": proj_expense_prev_q,
|
||||||
|
"proj_expense_prev_month": proj_expense_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, "expense": expense, "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"})
|
||||||
@@ -1,33 +1,25 @@
|
|||||||
// app.js — 入口文件(加载模块 + 初始化)
|
// app.js — 入口文件(加载模块 + 初始化)
|
||||||
// 所有业务逻辑已拆分到 modules/ 目录:
|
|
||||||
// utils.js — 共享状态、工具函数、API 封装
|
|
||||||
// home.js — 首页 + 财务趋势图
|
|
||||||
// projects.js — 重点工作与台账(项目+任务+拖拽)
|
|
||||||
// proposals.js — 业务方案 + 文件管理
|
|
||||||
// products.js — 产品迭代
|
|
||||||
// finance.js — 经营管理(财务)
|
|
||||||
// drawer.js — 详情抽屉 + 评论 + 转移
|
|
||||||
|
|
||||||
// Tab 点击委托
|
|
||||||
document.querySelector("#tabs").addEventListener("click", (event) => {
|
|
||||||
const button = event.target.closest("button[data-tab]");
|
|
||||||
if (button) switchTab(button.dataset.tab);
|
|
||||||
});
|
|
||||||
|
|
||||||
// 恢复上次的工作台和标签页
|
// 恢复上次的工作台和标签页
|
||||||
const savedTenant = localStorage.getItem("opc-active-tenant");
|
const savedTenant = localStorage.getItem("opc-active-tenant");
|
||||||
if (savedTenant) {
|
if (savedTenant) {
|
||||||
state.tenant = savedTenant;
|
state.tenant = savedTenant;
|
||||||
document.querySelectorAll(".workspace-nav-item").forEach(el => el.classList.toggle("active", el.dataset.tenant === savedTenant));
|
|
||||||
const label = savedTenant.replace("·无界", "");
|
const label = savedTenant.replace("·无界", "");
|
||||||
document.querySelector("#workspaceTitle").textContent = label + " OPC 工作台";
|
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");
|
const savedTab = localStorage.getItem("opc-active-tab");
|
||||||
|
|
||||||
// 初始化
|
// 初始化
|
||||||
applyUserTenants();
|
applyUserTenants();
|
||||||
|
updateSidebarTabs();
|
||||||
load().then(() => {
|
load().then(() => {
|
||||||
if (savedTab && savedTab !== "home") switchTab(savedTab);
|
if (state.tenant === "总工作台") {
|
||||||
|
switchTab("home");
|
||||||
|
} else if (savedTab && savedTab !== "home") {
|
||||||
|
switchTab(savedTab);
|
||||||
|
}
|
||||||
}).catch((error) => {
|
}).catch((error) => {
|
||||||
document.querySelector("main").innerHTML = `<section class="card p-6 text-red-700">加载失败:${esc(error.message)}</section>`;
|
document.querySelector("main").innerHTML = `<section class="card p-6 text-red-700">加载失败:${esc(error.message)}</section>`;
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// drawer.js — 详情抽屉 + 评论 + 转移 + 删除
|
// drawer.js — 详情抽屉 + 评论 + 删除
|
||||||
|
|
||||||
function drawerField(icon, label, name, value, multiline = false, customControl = null) {
|
function drawerField(icon, label, name, value, multiline = false, customControl = null) {
|
||||||
const safeValue = esc(value || "");
|
const safeValue = esc(value || "");
|
||||||
@@ -23,7 +23,7 @@ function openDrawer(resource, id) {
|
|||||||
? [["project_name","项目名称"],["owner","负责人"],["expected_sign_date","截止时间"],["expected_contract_amount","金额"],["notes","项目说明"]]
|
? [["project_name","项目名称"],["owner","负责人"],["expected_sign_date","截止时间"],["expected_contract_amount","金额"],["notes","项目说明"]]
|
||||||
: resource === "proposals"
|
: resource === "proposals"
|
||||||
? [["customer_or_project_name","客户/项目"],["proposal_type","方案类型"],["notes","备注"]]
|
? [["customer_or_project_name","客户/项目"],["proposal_type","方案类型"],["notes","备注"]]
|
||||||
: [["product_name","产品名称"],["version","版本号"],["version_goal","版本目标"],["feature_list","核心功能"],["launch_date","上线日期"],["status","状态"],["notes","备注"]];
|
: [["product_name","版本名称"],["version","版本号"],["priority","优先级"],["version_goal","版本目标"],["start_date","启动时间"],["plan_date","产品方案"],["dev_done_date","研发完成"],["test_date","测试完成"],["launch_date","上线时间"],["notes","进展备注"]];
|
||||||
const fieldIcons = {
|
const fieldIcons = {
|
||||||
target_customer: "user", priority: "flag", status: "circle-dot",
|
target_customer: "user", priority: "flag", status: "circle-dot",
|
||||||
project_name: "briefcase-business", project_version: "git-branch", project_status: "circle-dot", current_stage: "map-pin",
|
project_name: "briefcase-business", project_version: "git-branch", project_status: "circle-dot", current_stage: "map-pin",
|
||||||
@@ -31,29 +31,38 @@ function openDrawer(resource, id) {
|
|||||||
sign_probability: "percent", sop_stage: "list-checks", execution_progress: "activity",
|
sign_probability: "percent", sop_stage: "list-checks", execution_progress: "activity",
|
||||||
current_deliverable: "package", risks: "alert-triangle", next_action: "arrow-right",
|
current_deliverable: "package", risks: "alert-triangle", next_action: "arrow-right",
|
||||||
product_name: "box", version: "tag", version_goal: "target", feature_list: "list", platform: "layers",
|
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"
|
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 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 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 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);
|
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-blue-600 hover:bg-blue-50" onclick="openTransferModal('${resource}', ${id}, '${titleForAttr}')" ${resource === 'operations' ? '' : 'style="display:none"'}><i data-lucide="move-right"></i>转移</button><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">
|
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>
|
<section>
|
||||||
<h3 class="drawer-section-title">属性</h3>
|
<h3 class="drawer-section-title">属性</h3>
|
||||||
<form id="drawerForm" class="drawer-fields">
|
<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>`) : ""}
|
${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]) => {
|
${fields.map(([key,label]) => {
|
||||||
if (resource === "products" && key === "feature_list") {
|
if (resource === "products" && key === "priority") {
|
||||||
const features = (item[key] || "").split("\n").filter(Boolean);
|
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 (features.length === 0) features.push("");
|
|
||||||
return `<div class="drawer-field"><div class="drawer-field-label"><i data-lucide="list"></i><span>${label}</span></div><div class="drawer-field-control" data-field="feature_list" data-id="${id}"><div class="feature-list" id="featureList_${id}">${features.map((f,i) => `<div class="feature-item"><span class="feature-num">${i+1}.</span><input class="form-ctrl" value="${f.replace(/"/g,'"')}" onchange="saveFeatureList(${id})"><button class="feature-del" onclick="event.preventDefault();removeFeature(${id},${i})"><i data-lucide="x" style="width:12px;height:12px"></i></button></div>`).join("")}</div><button class="btn btn-ghost btn-sm text-blue-600 mt-1" onclick="event.preventDefault();addFeature(${id})"><i data-lucide="plus" style="width:14px;height:14px"></i>添加功能</button></div></div>`;
|
|
||||||
}
|
}
|
||||||
if (resource === "products" && key === "launch_date") {
|
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("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})">`);
|
||||||
}
|
}
|
||||||
if (resource === "products" && key === "status") {
|
|
||||||
return drawerField("circle-dot", label, key, "", false, `<select name="status" class="form-ctrl" onchange="saveDrawerField(this,'${resource}',${id})">${["规划中","开发中","测试中","已上线","已取消"].map((s) => `<option ${s === (item.status||'规划中') ? "selected" : ""}>${s}</option>`).join("")}</select>`);
|
|
||||||
}
|
|
||||||
return drawerField(fieldIcons[key] || "circle", label, key, item[key], multilineFields.includes(key));
|
return drawerField(fieldIcons[key] || "circle", label, key, item[key], multilineFields.includes(key));
|
||||||
}).join("")}
|
}).join("")}
|
||||||
</form>
|
</form>
|
||||||
@@ -172,33 +181,6 @@ window.deleteDrawerItem = async (resource, id) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
window.openTransferModal = (resource, id, title) => {
|
|
||||||
document.querySelector("#transfer-resource").value = resource;
|
|
||||||
document.querySelector("#transfer-id").value = id;
|
|
||||||
document.querySelector("#transfer-title-text").textContent = "将「" + title + "」转移到:";
|
|
||||||
document.querySelector("#transferModal").classList.remove("hidden");
|
|
||||||
};
|
|
||||||
|
|
||||||
window.closeTransferModal = () => {
|
|
||||||
document.querySelector("#transferModal").classList.add("hidden");
|
|
||||||
};
|
|
||||||
|
|
||||||
window.submitTransfer = async (event) => {
|
|
||||||
event.preventDefault();
|
|
||||||
const form = event.currentTarget;
|
|
||||||
const resource = form.querySelector('[name="transfer_resource"]').value;
|
|
||||||
const id = form.querySelector('[name="transfer_id"]').value;
|
|
||||||
const newTenant = form.querySelector('[name="transfer_tenant"]').value;
|
|
||||||
try {
|
|
||||||
await api(`/api/${resource}/${id}`, { method: "PUT", body: JSON.stringify({ data: { tenant: newTenant } }) });
|
|
||||||
closeTransferModal();
|
|
||||||
closeDrawer();
|
|
||||||
await load();
|
|
||||||
} catch (error) {
|
|
||||||
toast("转移失败:" + error.message, "error");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Squire 富文本编辑器
|
// Squire 富文本编辑器
|
||||||
window.squireInstances = {};
|
window.squireInstances = {};
|
||||||
window.squireCmd = (cmd) => {
|
window.squireCmd = (cmd) => {
|
||||||
@@ -255,6 +237,27 @@ window.deleteFollowup = async (event, followupId, resource, targetId) => {
|
|||||||
window.saveDrawerField = async (el, resource, id) => {
|
window.saveDrawerField = async (el, resource, id) => {
|
||||||
const name = el.name;
|
const name = el.name;
|
||||||
const value = el.value;
|
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 {
|
try {
|
||||||
await api(`/api/${resource}/${id}`, { method: "PUT", body: JSON.stringify({ data: { [name]: value } }) });
|
await api(`/api/${resource}/${id}`, { method: "PUT", body: JSON.stringify({ data: { [name]: value } }) });
|
||||||
const listKey = { sales: "sales", proposals: "proposals", operations: "operations", products: "products" }[resource];
|
const listKey = { sales: "sales", proposals: "proposals", operations: "operations", products: "products" }[resource];
|
||||||
|
|||||||
175
static/modules/expense.js
Normal file
175
static/modules/expense.js
Normal file
@@ -0,0 +1,175 @@
|
|||||||
|
// expense.js — 费用管理模块
|
||||||
|
|
||||||
|
function renderExpense() {
|
||||||
|
var records = state.data.expense || [];
|
||||||
|
var money = function(v) { return '¥ ' + (Number(v || 0)).toLocaleString('zh-CN', { minimumFractionDigits: 0, maximumFractionDigits: 2 }); };
|
||||||
|
var esc = function(s) { return (s || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); };
|
||||||
|
var EXPENSE_TYPES = ['通用费用','平台采购','人力成本','研发费用','奖金','其他'];
|
||||||
|
|
||||||
|
// 筛选状态
|
||||||
|
var view = state.expenseView || 'total';
|
||||||
|
var typeFilter = state.expenseFilter || '全部';
|
||||||
|
var filtered = typeFilter === '全部' ? records : records.filter(function(r) { return r.expense_type === typeFilter; });
|
||||||
|
|
||||||
|
// 视图数据预处理
|
||||||
|
var now = new Date();
|
||||||
|
var thisYear = now.getFullYear();
|
||||||
|
var defaultMonth = thisYear + '-' + String(now.getMonth() + 1).padStart(2, '0');
|
||||||
|
|
||||||
|
if (!state.expenseMonth) state.expenseMonth = defaultMonth;
|
||||||
|
if (state.expenseQuarter === '') state.expenseQuarter = String(Math.floor(now.getMonth() / 3));
|
||||||
|
|
||||||
|
// 月度筛选
|
||||||
|
if (view === 'monthly') {
|
||||||
|
filtered = filtered.filter(function(r) { return r.expense_month === state.expenseMonth; });
|
||||||
|
}
|
||||||
|
|
||||||
|
// 季度筛选
|
||||||
|
if (view === 'quarterly') {
|
||||||
|
var q = parseInt(state.expenseQuarter) || 0;
|
||||||
|
var qRanges = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]];
|
||||||
|
var qRange = qRanges[q];
|
||||||
|
filtered = filtered.filter(function(r) {
|
||||||
|
var m = parseInt((r.expense_month || '0').substring(5)) || 0;
|
||||||
|
return qRange.indexOf(m) >= 0;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
var totalAmount = filtered.reduce(function(s, r) { return s + (r.amount || 0); }, 0);
|
||||||
|
var totalIncurred = filtered.reduce(function(s, r) { return s + (r.incurred_amount || 0); }, 0);
|
||||||
|
|
||||||
|
// 月份下拉选项(去年/今年/明年)
|
||||||
|
var monthOpts = '<option value="">请选择</option>';
|
||||||
|
for (var yr = thisYear - 1; yr <= thisYear + 1; yr++)
|
||||||
|
for (var m = 1; m <= 12; m++) {
|
||||||
|
var mv = yr + '-' + String(m).padStart(2, '0');
|
||||||
|
monthOpts += '<option value="' + mv + '"' + (mv === state.expenseMonth ? ' selected' : '') + '>' + mv + '</option>';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 季度下拉
|
||||||
|
var qLabels = ['Q1 (1-3月)','Q2 (4-6月)','Q3 (7-9月)','Q4 (10-12月)'];
|
||||||
|
var quarterOpts = '';
|
||||||
|
for (var qi = 0; qi < 4; qi++) {
|
||||||
|
quarterOpts += '<option value="' + qi + '"' + (String(qi) === state.expenseQuarter ? ' selected' : '') + '>' + qLabels[qi] + '</option>';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 月份/季度日期选择器
|
||||||
|
var dateSelect = '';
|
||||||
|
if (view === 'monthly') {
|
||||||
|
dateSelect = '<span class="text-xs text-slate-500 ml-2">月份:</span><select onchange="setExpenseMonth(this.value)" 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>';
|
||||||
|
} else if (view === 'quarterly') {
|
||||||
|
dateSelect = '<span class="text-xs text-slate-500 ml-2">季度:</span><select onchange="setExpenseQuarter(this.value)" 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>';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Toolbar
|
||||||
|
var toolbar = '<span class="text-xs text-slate-500">视图:</span><select onchange="setExpenseView(this.value)" 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="total"' + (view==='total'?' selected':'') + '>总视图</option><option value="quarterly"' + (view==='quarterly'?' selected':'') + '>季度视图</option><option value="monthly"' + (view==='monthly'?' selected':'') + '>月度视图</option></select><span class="text-xs text-slate-500 ml-3">类型:</span><select onchange="setExpenseFilter(this.value)" 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="全部"' + (typeFilter==='全部'?' selected':'') + '>全部 (' + records.length + ')</option>';
|
||||||
|
EXPENSE_TYPES.forEach(function(t) {
|
||||||
|
toolbar += '<option value="' + t + '"' + (typeFilter===t?' selected':'') + '>' + t + ' (' + records.filter(function(r){return r.expense_type===t}).length + ')</option>';
|
||||||
|
});
|
||||||
|
toolbar += '</select>' + dateSelect;
|
||||||
|
|
||||||
|
// 表格行
|
||||||
|
var tableRows = '';
|
||||||
|
if (filtered.length) {
|
||||||
|
filtered.forEach(function(r) {
|
||||||
|
tableRows += '<tr class="border-b border-slate-100 hover:bg-slate-50 cursor-pointer" onclick="openExpenseEdit(' + r.id + ')"><td class="p-2 font-medium text-center align-middle" style="width:200px">' + esc(r.expense_type) + '</td><td class="p-2 text-center align-middle" style="width:200px">' + (r.expense_month || '—') + '</td><td class="p-2 text-center align-middle font-medium" style="width:200px">' + money(r.amount) + '</td><td class="p-2 text-center align-middle font-medium" style="width:200px">' + money(r.incurred_amount) + '</td><td class="p-2 text-center align-middle text-slate-500" style="width:200px">' + (esc(r.notes) || '—') + '</td></tr>';
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
var emptyMsg = view === 'monthly' ? '该月份暂无费用记录' : view === 'quarterly' ? '该季度暂无费用记录' : '暂无费用记录';
|
||||||
|
tableRows = '<tr><td colspan="5" class="p-6 text-center text-slate-400">' + emptyMsg + '</td></tr>';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 模态框
|
||||||
|
var modal = '<div id="expenseModal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/40" onclick="closeExpenseModal()"><div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg mx-4" onclick="event.stopPropagation()"><div class="sticky top-0 z-10 bg-white/95 backdrop-blur border-b border-slate-100 px-6 py-4 flex items-center justify-between"><h3 class="text-lg font-bold text-slate-800" id="expenseModalTitle">新增费用</h3><div class="flex items-center gap-2"><button class="btn btn-ghost btn-sm text-red-600 hidden" id="expenseDeleteBtn" onclick="deleteExpenseItem()">删除</button><button class="btn btn-ghost btn-sm rounded-full w-8 h-8 p-0" onclick="closeExpenseModal()"><i data-lucide="x"></i></button></div></div><form onsubmit="saveExpense(event)" class="p-6 grid gap-4" novalidate><input type="hidden" name="expense_id" value=""><div class="grid grid-cols-2 gap-3"><label class="block"><span class="text-xs text-slate-500 mb-1 block">费用类型 <span class="text-red-500">*</span></span><select name="expense_type" required class="form-ctrl bg-white"><option value="">请选择</option>';
|
||||||
|
EXPENSE_TYPES.forEach(function(t) { modal += '<option>' + t + '</option>'; });
|
||||||
|
modal += '</select></label><label class="block"><span class="text-xs text-slate-500 mb-1 block">月份 <span class="text-red-500">*</span></span><select name="expense_month" required class="form-ctrl bg-white">' + monthOpts + '</select></label></div><div class="grid grid-cols-2 gap-3"><label class="block"><span class="text-xs text-slate-500 mb-1 block">金额(元)</span><input name="amount" type="number" step="0.01" class="form-ctrl" placeholder="0.00"></label><label class="block"><span class="text-xs text-slate-500 mb-1 block">已发生金额(元)</span><input name="incurred_amount" type="number" step="0.01" class="form-ctrl" placeholder="0.00"></label></div><label class="block"><span class="text-xs text-slate-500 mb-1 block">费用说明</span><textarea name="notes" class="form-ctrl" rows="3" placeholder="备注信息"></textarea></label><div class="flex justify-end gap-3 pt-2"><button type="button" class="btn btn-ghost btn-sm px-6" onclick="closeExpenseModal()">取消</button><button type="submit" class="btn btn-primary btn-sm px-8">保存</button></div></form></div></div>';
|
||||||
|
|
||||||
|
document.querySelector("#expense").innerHTML = '<div class="grid gap-4">' +
|
||||||
|
'<div class="card p-3"><div class="flex justify-between items-center"><div class="flex items-center gap-2">' + toolbar + '</div><button class="btn btn-primary btn-sm" onclick="openExpenseModal()">新增费用</button></div></div>' +
|
||||||
|
'<div class="grid grid-cols-3 gap-3">' +
|
||||||
|
'<div class="metric-card p-3"><span class="flex items-center gap-2 text-xs text-slate-500">费用记录</span><strong class="mt-2 block text-xl">' + filtered.length + '</strong></div>' +
|
||||||
|
'<div class="metric-card p-3"><span class="flex items-center gap-2 text-xs text-slate-500">总费用</span><strong class="mt-2 block text-xl">' + money(totalAmount) + '</strong></div>' +
|
||||||
|
'<div class="metric-card p-3"><span class="flex items-center gap-2 text-xs text-slate-500">已发生金额</span><strong class="mt-2 block text-xl">' + money(totalIncurred) + '</strong></div>' +
|
||||||
|
'</div>' +
|
||||||
|
modal +
|
||||||
|
'<div class="card p-4"><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" style="width:200px">费用类型</th><th class="p-2 text-center font-semibold" style="width:200px">月份</th><th class="p-2 text-center font-semibold" style="width:200px">金额</th><th class="p-2 text-center font-semibold" style="width:200px">已发生金额</th><th class="p-2 text-center font-semibold" style="width:200px">费用说明</th></tr></thead><tbody>' + tableRows + '</tbody></table></div></div>' +
|
||||||
|
'</div>';
|
||||||
|
|
||||||
|
if (window.lucide) window.lucide.createIcons();
|
||||||
|
}
|
||||||
|
|
||||||
|
window.setExpenseView = function(v) { state.expenseView = v; renderExpense(); };
|
||||||
|
window.setExpenseFilter = function(v) { state.expenseFilter = v; renderExpense(); };
|
||||||
|
window.setExpenseMonth = function(v) { state.expenseMonth = v; renderExpense(); };
|
||||||
|
window.setExpenseQuarter = function(v) { state.expenseQuarter = v; renderExpense(); };
|
||||||
|
|
||||||
|
window.openExpenseModal = function() {
|
||||||
|
var form = document.querySelector("#expenseModal form");
|
||||||
|
form.reset();
|
||||||
|
form.querySelector('[name="expense_id"]').value = "";
|
||||||
|
document.querySelector("#expenseModalTitle").textContent = "新增费用";
|
||||||
|
document.querySelector("#expenseDeleteBtn").classList.add("hidden");
|
||||||
|
document.querySelector("#expenseModal").classList.remove("hidden");
|
||||||
|
};
|
||||||
|
|
||||||
|
window.closeExpenseModal = function() {
|
||||||
|
document.querySelector("#expenseModal").classList.add("hidden");
|
||||||
|
};
|
||||||
|
|
||||||
|
window.openExpenseEdit = function(id) {
|
||||||
|
var r = (state.data.expense || []).find(function(x) { return x.id === id; });
|
||||||
|
if (!r) return;
|
||||||
|
var form = document.querySelector("#expenseModal form");
|
||||||
|
form.reset();
|
||||||
|
var setVal = function(name, val) { var el = form.querySelector('[name="' + name + '"]'); if (el) el.value = val || ""; };
|
||||||
|
setVal("expense_id", r.id);
|
||||||
|
setVal("expense_type", r.expense_type);
|
||||||
|
setVal("expense_month", r.expense_month);
|
||||||
|
setVal("amount", r.amount);
|
||||||
|
setVal("incurred_amount", r.incurred_amount);
|
||||||
|
setVal("notes", r.notes);
|
||||||
|
document.querySelector("#expenseModalTitle").textContent = "编辑费用";
|
||||||
|
document.querySelector("#expenseDeleteBtn").classList.remove("hidden");
|
||||||
|
document.querySelector("#expenseModal").classList.remove("hidden");
|
||||||
|
};
|
||||||
|
|
||||||
|
window.saveExpense = async function(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
var form = event.target;
|
||||||
|
var data = Object.fromEntries(new FormData(form).entries());
|
||||||
|
// 数字字段空值转 0,避免线上 MySQL 严格模式报错
|
||||||
|
if (data.amount === '' || data.amount === undefined) data.amount = 0;
|
||||||
|
if (data.incurred_amount === '' || data.incurred_amount === undefined) data.incurred_amount = 0;
|
||||||
|
var isEdit = !!data.expense_id;
|
||||||
|
delete data.expense_id;
|
||||||
|
|
||||||
|
var id = form.querySelector('[name="expense_id"]').value;
|
||||||
|
var url = isEdit ? "/api/expense/" + id : "/api/expense";
|
||||||
|
var method = isEdit ? "PUT" : "POST";
|
||||||
|
|
||||||
|
var resp = await fetch(url, { method: method, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ data: Object.assign({}, data, { tenant: state.tenant }) }) });
|
||||||
|
if (!resp.ok) { var err = await resp.text(); alert("保存失败:" + err); return; }
|
||||||
|
|
||||||
|
var bResp = await fetch("/api/bootstrap?tenant=" + encodeURIComponent(state.tenant));
|
||||||
|
if (bResp.ok) {
|
||||||
|
var bd = await bResp.json();
|
||||||
|
state.data = bd;
|
||||||
|
applyUserTenants();
|
||||||
|
renderExpense();
|
||||||
|
}
|
||||||
|
closeExpenseModal();
|
||||||
|
};
|
||||||
|
|
||||||
|
window.deleteExpenseItem = async function() {
|
||||||
|
var id = document.querySelector("#expenseModal form [name='expense_id']").value;
|
||||||
|
if (!id || !confirm("确定删除?")) return;
|
||||||
|
var resp = await fetch("/api/expense/" + id, { method: "DELETE" });
|
||||||
|
if (!resp.ok) { alert("删除失败"); return; }
|
||||||
|
var bResp = await fetch("/api/bootstrap?tenant=" + encodeURIComponent(state.tenant));
|
||||||
|
if (bResp.ok) {
|
||||||
|
var bd = await bResp.json();
|
||||||
|
state.data = bd;
|
||||||
|
applyUserTenants();
|
||||||
|
renderExpense();
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
// finance.js — 经营管理(财务)模块
|
// finance.js — 经营管理(财务)模块
|
||||||
|
|
||||||
const moneyInt = (v) => `${Math.round(Number(v || 0)).toLocaleString("zh-CN")} 元`;
|
const moneyInt = (v) => `${Math.round(Number(v || 0)).toLocaleString("zh-CN")} 元`;
|
||||||
|
const moneyWan = (v) => `${(Number(v || 0) / 10000).toFixed(1)} 万`;
|
||||||
|
|
||||||
function renderFinance() {
|
function renderFinance() {
|
||||||
const pfs = state.data.projectFinances || [];
|
const pfs = state.data.projectFinances || [];
|
||||||
const ops = state.data.operations || [];
|
const ops = state.data.operations || [];
|
||||||
const fmTypesByTenant = {
|
const fmTypesByTenant = {
|
||||||
"科普·无界": ["科普音频","科普视频","科普文章","全品类科普","调研问卷"],
|
"科普·无界": ["科普音频","科普视频","科普文章","科普专访","患教会","全品类科普","调研问卷"],
|
||||||
"科研·无界": ["真实世界研究","调研问卷","病例征集","患者招募"],
|
"科研·无界": ["真实世界研究","调研问卷","病例征集","患者招募"],
|
||||||
"医患·无界": ["医患运营","患者管理","患教会","创新支付","电商","其他"],
|
"医患·无界": ["医患运营","患者管理","患教会","创新支付","电商","其他"],
|
||||||
};
|
};
|
||||||
@@ -24,11 +25,9 @@ function renderFinance() {
|
|||||||
const monthLabels = displayMonths.map(d => d.label);
|
const monthLabels = displayMonths.map(d => d.label);
|
||||||
|
|
||||||
const signed = pfs.filter(x => x.status === "已签约");
|
const signed = pfs.filter(x => x.status === "已签约");
|
||||||
const inContract = pfs.filter(x => x.status === "流程中");
|
|
||||||
const pending = 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 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 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 => {
|
const monthRev = months.map(m => {
|
||||||
return signed.reduce((s, pf) => {
|
return signed.reduce((s, pf) => {
|
||||||
@@ -73,102 +72,312 @@ function renderFinance() {
|
|||||||
const budget = JSON.parse(pf.budget_data || "[]");
|
const budget = JSON.parse(pf.budget_data || "[]");
|
||||||
budget.forEach(b => { budgetMap[(b.month || "").replace("-", "_")] = b; });
|
budget.forEach(b => { budgetMap[(b.month || "").replace("-", "_")] = b; });
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
const isRevView = state.finView !== "cashflow";
|
const isRevView = state.finView !== "cashflow" && state.finView !== "overview" && state.finView !== "monthly" && state.finView !== "quarterly";
|
||||||
const mCols = months.map(m => {
|
const mCols = months.map(m => {
|
||||||
const b = budgetMap[m] || {};
|
const b = budgetMap[m] || {};
|
||||||
if (isRevView) {
|
if (isRevView) {
|
||||||
const rev = b.rev || 0;
|
const rev = b.rev || 0;
|
||||||
const gross = b.gross || 0;
|
const gross = b.gross || 0;
|
||||||
return `<td class="p-2 text-right whitespace-nowrap"><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>`;
|
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 {
|
} else {
|
||||||
const payment = b.payment || 0;
|
const payment = b.payment || 0;
|
||||||
const cost = b.cost || 0;
|
const cost = b.cost || 0;
|
||||||
return `<td class="p-2 text-right whitespace-nowrap"><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>`;
|
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("");
|
}).join("");
|
||||||
const totalCol = (() => {
|
const totalCol = (() => {
|
||||||
if (isRevView) {
|
if (isRevView) {
|
||||||
const totalRev = pf.total_rev || 0;
|
const totalRev = pf.total_rev || 0;
|
||||||
const totalGross = pf.total_gross || 0;
|
const totalGross = pf.total_gross || 0;
|
||||||
return `<td class="p-2 text-right whitespace-nowrap 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>`;
|
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 {
|
} else {
|
||||||
let totalPayment = 0, totalCost = 0;
|
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) {}
|
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-right whitespace-nowrap 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>`;
|
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 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>`;
|
const signMonthCell = `<td class="p-2 text-center align-middle 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><td class="p-2 text-sm text-center">${esc(pf.business_type)}</td><td class="p-2 text-sm text-center">${pf.status === "已签约" ? badge("已签约") : pf.status === "流程中" ? badge("流程中","blue") : badge("待签约","amber")}</td>${signMonthCell}<td class="p-2 text-center text-sm">${money(pf.sign_amount)}</td>${mCols}${totalCol}<td class="p-2 text-sm text-slate-500 text-center">${esc(pf.sales_person) || "—"}</td><td class="p-2 text-sm text-slate-500 text-center">${esc(pf.owner) || "—"}</td></tr>`;
|
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 align-middle">${esc(pf.customer_name)}</td>${signMonthCell}<td class="p-2 text-center align-middle text-sm">${money(pf.sign_amount)}</td>${mCols}${totalCol}</tr>`;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const now2 = new Date();
|
||||||
|
const defaultMonth2 = now2.getFullYear() + "-" + String(now2.getMonth()+1).padStart(2,"0");
|
||||||
|
if (!state.finMonth) state.finMonth = defaultMonth2;
|
||||||
|
if (state.finQuarter === undefined) state.finQuarter = Math.floor(now2.getMonth() / 3);
|
||||||
|
const monthSet2 = new Set([defaultMonth2]);
|
||||||
|
pfs.forEach(pf => { let bd = []; try { bd = JSON.parse(pf.budget_data || "[]"); } catch(e) {} bd.forEach(b => { if (b.month) monthSet2.add(b.month); }); });
|
||||||
|
const allMonths = [...monthSet2].sort().reverse();
|
||||||
|
const qLabels2 = ["Q1 (1-3月)","Q2 (4-6月)","Q3 (7-9月)","Q4 (10-12月)"];
|
||||||
|
const toolMonthSelect = allMonths.map(m => '<option value="'+m+'" '+(m===state.finMonth?'selected':'')+'>'+m+'</option>').join("");
|
||||||
|
const toolQuarterSelect = qLabels2.map((l,i) => '<option value="'+i+'" '+(i===state.finQuarter?'selected':'')+'>'+l+'</option>').join("");
|
||||||
|
const toolDateSelect = state.finView==='monthly'?'<span class="text-xs text-slate-500 ml-2">月份:</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">'+toolMonthSelect+'</select>':state.finView==='quarterly'?'<span class="text-xs text-slate-500 ml-2">季度:</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">'+toolQuarterSelect+'</select>':'';
|
||||||
|
|
||||||
|
const finHeaderBase = `<span class="text-xs text-slate-500">视图:</span><select onchange="setFinView(this.value)" 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="overview" ${state.finView==='overview'?'selected':''}>总视图</option><option value="quarterly" ${state.finView==='quarterly'?'selected':''}>季度视图</option><option value="monthly" ${state.finView==='monthly'?'selected':''}>月度视图</option></select><span class="text-xs text-slate-500 ml-3">状态:</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></select>${toolDateSelect}`;
|
||||||
|
const finAddBtn = `<button class="btn btn-primary btn-sm" onclick="openFinanceModal()">新增财务项目</button>`;
|
||||||
|
|
||||||
document.querySelector("#finance").innerHTML = `<div class="grid gap-4">
|
document.querySelector("#finance").innerHTML = `<div class="grid gap-4">
|
||||||
<div class="grid grid-cols-6 gap-3">
|
${card(`<div class="flex justify-between items-center"><div class="flex items-center gap-2">${finHeaderBase}</div>${finAddBtn}</div>`, "p-3")}
|
||||||
${[["已签项目","" + signed.length,"file-check-2"],["签约金额",moneyInt(sumSign),"coins"],["流程项目","" + inContract.length,"file-clock"],["流程金额",moneyInt(sumContract),"clock"],["待签项目","" + pending.length,"file-question"],["待签金额",moneyInt(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 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>
|
|
||||||
<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 class="flex justify-between items-center"><div class="flex items-center gap-1" id="finViewToggle"><button class="btn btn-sm ${state.finView !== 'cashflow' ? 'btn-primary' : 'btn-ghost'} p-1.5" data-view="rev" onclick="setFinView('rev')" title="确收/毛利视图"><i data-lucide="trending-up" style="width:16px;height:16px"></i></button><button class="btn btn-sm ${state.finView === 'cashflow' ? 'btn-primary' : 'btn-ghost'} p-1.5" data-view="cashflow" onclick="setFinView('cashflow')" title="回款/费用视图"><i data-lucide="wallet" style="width:16px;height:16px"></i></button></div><button class="btn btn-primary btn-sm" onclick="openFinanceModal()"><i data-lucide="plus"></i>新增财务项目</button></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-5xl 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">
|
<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 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="revpay" onclick="switchFinanceTab('revpay')"><i data-lucide="dollar-sign" style="width:14px;height:14px;display:inline-block;vertical-align:-2px;margin-right:4px"></i>确收与回款</button>
|
||||||
|
<button class="finance-tab" data-tab="cost" onclick="switchFinanceTab('cost')"><i data-lucide="receipt" 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>
|
</div>
|
||||||
<form onsubmit="createFinance(event)" class="p-8 grid gap-6"><input type="hidden" name="pf_id" id="pf-id-input" value="">
|
<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 id="financeTabInfo">
|
||||||
<div class="grid grid-cols-2 gap-5">
|
|
||||||
<div class="fin-field-group">
|
|
||||||
<p class="fin-section-label">项目信息</p>
|
|
||||||
<div class="grid gap-4">
|
<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 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><select name="business_type" class="form-ctrl bg-white">${fmTypes.map(t => `<option>${t}</option>`).join("")}</select></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>
|
<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>
|
||||||
</div>
|
<div class="grid grid-cols-3 gap-3">
|
||||||
<div class="fin-field-group">
|
<label class="block"><span class="fin-label">签约金额(元) <span class="text-red-500">*</span></span><input name="sign_amount" class="form-ctrl" placeholder="必须大于 0"></label>
|
||||||
<p class="fin-section-label">合同信息</p>
|
|
||||||
<div class="grid gap-4">
|
|
||||||
<label class="block"><span class="fin-label">签约金额(元) <span class="text-red-500">*</span></span><input name="sign_amount" type="number" step="0.01" min="0.01" required class="form-ctrl" placeholder="必须大于 0"></label>
|
|
||||||
<div class="grid grid-cols-2 gap-3">
|
|
||||||
<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 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>
|
<label class="block"><span class="fin-label">项目状态</span><select name="status" class="form-ctrl bg-white"><option>已签约</option><option>待签约</option></select></label>
|
||||||
</div>
|
</div>
|
||||||
<div class="grid grid-cols-2 gap-3">
|
<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="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 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>
|
||||||
|
<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>
|
||||||
|
<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>
|
||||||
</div>
|
</div>
|
||||||
<div id="financeTabBudget" class="hidden">
|
<div id="financeTabRevpay" class="hidden">
|
||||||
<div class="grid grid-cols-4 gap-3 mb-4" id="budgetSummary">
|
<div class="grid grid-cols-3 gap-3 mb-4" id="revpaySummary">
|
||||||
<div class="bg-blue-50 rounded-lg p-3 text-center border border-blue-100">
|
<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-xs text-blue-600 font-medium">总确收</p>
|
||||||
<p class="text-lg font-bold text-blue-700" id="budgetTotalRev">¥0</p>
|
<p class="text-lg font-bold text-blue-700" id="revpayTotalRev">¥0</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="bg-green-50 rounded-lg p-3 text-center border border-green-100">
|
<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-xs text-green-600 font-medium">总毛利</p>
|
||||||
<p class="text-lg font-bold text-green-700" id="budgetTotalGross">¥0</p>
|
<p class="text-lg font-bold text-green-700" id="revpayTotalGross">¥0</p>
|
||||||
</div>
|
</div>
|
||||||
<div class="bg-amber-50 rounded-lg p-3 text-center border border-amber-100" id="budgetTotalPaymentCard">
|
<div class="bg-amber-50 rounded-lg p-3 text-center border border-amber-100">
|
||||||
<p class="text-xs text-amber-600 font-medium">总回款</p>
|
<p class="text-xs text-amber-600 font-medium">总回款</p>
|
||||||
<p class="text-lg font-bold text-amber-700" id="budgetTotalPayment">¥0</p>
|
<p class="text-lg font-bold text-amber-700" id="revpayTotalPayment">¥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>
|
||||||
</div>
|
</div>
|
||||||
<table class="w-full text-sm border border-slate-200 rounded-lg overflow-hidden" id="budgetTable">
|
<table class="w-full text-sm border border-slate-200 rounded-lg overflow-hidden" id="revpayTable">
|
||||||
<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 w-8"></th></tr></thead>
|
<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-left font-medium text-slate-500">备注</th><th class="p-2.5 w-8"></th></tr></thead>
|
||||||
<tbody id="budgetTbody"></tbody>
|
<tbody id="revpayTbody"></tbody>
|
||||||
</table>
|
</table>
|
||||||
<button type="button" class="btn btn-ghost btn-sm mt-3" onclick="addBudgetRow()"><i data-lucide="plus"></i>添加月份</button>
|
<button type="button" class="btn btn-ghost btn-sm mt-3" onclick="addRevpayRow()"><i data-lucide="plus"></i>添加月份</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex justify-end gap-3 pt-2"><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>
|
<div id="financeTabCost" class="hidden">
|
||||||
${card(`<div class="flex items-center justify-between mb-3"><h3 class="font-bold text-slate-700">项目明细 <span class="text-slate-400 font-normal">(${pfs.length})</span></h3></div><div class="flex gap-2 mb-3">${[["已签约","已签约"],["流程中","流程中"],["待签约","待签约"]].map(([k,v]) => `<button class="btn btn-sm ${state.finFilter === k ? 'btn-primary' : 'btn-ghost'}" onclick="state.finFilter='${k}';renderFinance()">${v} (${pfs.filter(x=>x.status===k).length})</button>`).join("")}</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">项目名称</th><th class="p-2 text-center font-semibold">类型</th><th class="p-2 text-center font-semibold">状态</th><th class="p-2 text-center font-semibold">签约月份</th><th class="p-2 text-center font-semibold">签约金额</th>${monthLabels.map(l => `<th class="p-2 text-center font-semibold">${l}<br><span class="text-xs text-slate-400">${state.finView !== 'cashflow' ? '确收/毛利' : '回款/费用'}</span></th>`).join("")}<th class="p-2 text-center font-semibold">总计<br><span class="text-xs text-slate-400">${state.finView !== 'cashflow' ? '确收/毛利' : '回款/费用'}</span></th><th class="p-2 text-center font-semibold">商务负责人</th><th class="p-2 text-center font-semibold">经营负责人</th></tr></thead><tbody>${pfs.filter(x => x.status === state.finFilter).map(renderPfRow).join("")}</tbody></table></div>`, "p-4")}
|
<div class="grid grid-cols-2 gap-3 mb-4" id="costSummary">
|
||||||
|
<div class="bg-rose-50 rounded-lg p-3 text-center border border-rose-100">
|
||||||
|
<p class="text-xs text-rose-600 font-medium">总成本</p>
|
||||||
|
<p class="text-lg font-bold text-rose-700" id="costTotalCost">¥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="costTotalPaid">¥0</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<table class="w-full text-sm border border-slate-200 rounded-lg overflow-hidden" id="costTable">
|
||||||
|
<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-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-left font-medium text-slate-500">备注</th><th class="p-2.5 w-8"></th></tr></thead>
|
||||||
|
<tbody id="costTbody"></tbody>
|
||||||
|
</table>
|
||||||
|
<button type="button" class="btn btn-ghost btn-sm mt-3" onclick="addCostRow()"><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>
|
||||||
|
${(() => {
|
||||||
|
const METRIC_CARDS = [
|
||||||
|
{ label: '签约金额', value: ctx => moneyWan(ctx.signTotal), color: 'text-slate-700' },
|
||||||
|
{ label: '已确收', value: ctx => moneyWan(ctx.sumRev), color: 'text-blue-700' },
|
||||||
|
{ label: '毛利', value: ctx => money(ctx.sumGross), color: 'text-green-700' },
|
||||||
|
{ label: '成本', value: ctx => moneyWan(ctx.sumCost), color: 'text-rose-700' },
|
||||||
|
{ label: '项目利润', value: ctx => { const v = ctx.sumGross; return { val: moneyWan(v), cls: v >= 0 ? 'text-green-600' : 'text-red-600' }; }, color: null },
|
||||||
|
{ label: '已回款', value: ctx => moneyWan(ctx.sumPay), color: 'text-amber-700' },
|
||||||
|
{ label: '已付', value: ctx => moneyWan(ctx.sumPaid), color: 'text-purple-700' },
|
||||||
|
{ label: '现金流', value: ctx => { const v = ctx.sumPay - ctx.sumPaid; return { val: money(v), cls: v >= 0 ? 'text-green-600' : 'text-red-600' }; }, color: null },
|
||||||
|
{ label: '执行率', value: ctx => ctx.sumRev && ctx.signTotal ? Math.round(ctx.sumRev / ctx.signTotal * 100) + '%' : '—', color: 'text-slate-500' },
|
||||||
|
{ label: '毛利率', value: ctx => ctx.sumRev && ctx.sumGross ? Math.round(ctx.sumGross / ctx.sumRev * 100) + '%' : '—', color: 'text-slate-500' },
|
||||||
|
{ label: '回款率', value: ctx => ctx.sumRev && ctx.sumPay ? Math.round(ctx.sumPay / ctx.sumRev * 100) + '%' : '—', color: 'text-slate-500' },
|
||||||
|
{ label: '付款率', value: ctx => ctx.sumCost && ctx.sumPaid ? Math.round(ctx.sumPaid / ctx.sumCost * 100) + '%' : '—', color: 'text-slate-500' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const renderView = (rows, sumRev, sumPay, sumCost, sumPaid, sumGross, signTotal, signCnt, emptyText) => {
|
||||||
|
const ctx = { sumRev, sumPay, sumCost, sumPaid, sumGross, signTotal, signCnt };
|
||||||
|
const cards = METRIC_CARDS.map(c => {
|
||||||
|
const v = c.value(ctx);
|
||||||
|
return typeof v === 'object' ? [c.label, v.val, v.cls] : [c.label, v, c.color];
|
||||||
|
});
|
||||||
|
const thead = '<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">签约金额</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">毛利</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">项目利润</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 text-purple-600">已付</th>' +
|
||||||
|
'<th class="p-2 text-center font-semibold align-middle text-slate-700">现金流</th>' +
|
||||||
|
'<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">回款率</th>' +
|
||||||
|
'<th class="p-2 text-center font-semibold align-middle">付款率</th>' +
|
||||||
|
'</tr></thead>';
|
||||||
|
const tbody = rows.length ? `<tbody>${rows.join("")}</tbody>` : `<tr><td colspan="15" class="p-6 text-center text-slate-400">${emptyText}</td></tr>`;
|
||||||
|
|
||||||
|
return card(`<div class="grid grid-cols-6 gap-3 mb-3">${cards.map(([l, v, c]) => '<div class="metric-card p-3"><span class="flex items-center gap-2 text-xs text-slate-500">' + l + '</span><strong class="mt-2 block text-xl ' + c + '">' + v + '</strong></div>').join("")}</div>`, "p-4") +
|
||||||
|
card(`<h3 class="text-sm font-bold text-slate-700">项目财务明细</h3><p class="text-xs text-slate-400 mb-3">合同 → 确收 → 毛利 → 成本 → 项目利润 → 回款 → 已付 → 现金流 → 执行率 → 毛利率 → 回款率 → 付款率</p><div class="overflow-x-auto"><table class="w-full text-sm">${thead}${tbody}</table></div>`, "p-4");
|
||||||
|
};
|
||||||
|
|
||||||
|
const fmtNoUnit = (v) => v ? `<span class="font-medium">${Number(v||0).toLocaleString('zh-CN')}</span>` : '<span class="text-slate-300">—</span>';
|
||||||
|
const tdRow = (pf, rev, payment, cost, paid, gross) => {
|
||||||
|
const cashflow = payment - paid;
|
||||||
|
const exe = rev && pf.sign_amount ? Math.round(rev / pf.sign_amount * 100) + '%' : '<span class="text-slate-300">—</span>';
|
||||||
|
const payR = rev && payment ? Math.round(payment / rev * 100) + '%' : '<span class="text-slate-300">—</span>';
|
||||||
|
const paidR = cost && paid ? Math.round(paid / cost * 100) + '%' : '<span class="text-slate-300">—</span>';
|
||||||
|
const grossR = rev && gross ? Math.round(gross / rev * 100) + '%' : '<span class="text-slate-300">—</span>';
|
||||||
|
const st = pf.status === '已签约' ? '<span class="text-green-600">已签约</span>' : '<span class="text-amber-600">待签约</span>';
|
||||||
|
const cf = cashflow ? money(cashflow) : '<span class="text-slate-300">—</span>';
|
||||||
|
const cfCls = cashflow >= 0 ? 'text-green-600' : 'text-red-600';
|
||||||
|
const profit = gross;
|
||||||
|
const pfCls = profit >= 0 ? 'text-green-600' : 'text-red-600';
|
||||||
|
const pfVal = profit ? money(profit) : '<span class="text-slate-300">—</span>';
|
||||||
|
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 align-middle truncate" style="min-width:300px;max-width:300px;width:300px" title="${esc(pf.customer_name)}">${esc(pf.customer_name)}</td><td class="p-2 text-center align-middle text-sm">${st}</td><td class="p-2 text-center align-middle text-sm font-medium">${money(pf.sign_amount)}</td><td class="p-2 text-center text-blue-700 align-middle">${fmtNoUnit(rev)}</td><td class="p-2 text-center align-middle text-sm font-medium">${fmtNoUnit(gross)}</td><td class="p-2 text-center text-rose-700 align-middle">${fmtNoUnit(cost)}</td><td class="p-2 text-center font-semibold align-middle ${pfCls}">${pfVal}</td><td class="p-2 text-center text-amber-700 align-middle">${fmtNoUnit(payment)}</td><td class="p-2 text-center text-purple-700 align-middle">${fmtNoUnit(paid)}</td><td class="p-2 text-center font-semibold align-middle ${cfCls}">${cf}</td><td class="p-2 text-center align-middle text-sm">${exe}</td><td class="p-2 text-center align-middle text-sm">${grossR}</td><td class="p-2 text-center align-middle text-sm">${payR}</td><td class="p-2 text-center align-middle text-sm">${paidR}</td></tr>`;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (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 rows = [];
|
||||||
|
let sumRev = 0, sumPay = 0, sumCost = 0, sumPaid = 0, sumGross = 0;
|
||||||
|
allPfs.forEach(pf => {
|
||||||
|
let bd = []; try { bd = JSON.parse(pf.budget_data || "[]"); } catch (e) {}
|
||||||
|
let ed = []; try { ed = JSON.parse(pf.expense_data || "[]"); } catch (e) {}
|
||||||
|
const b = bd.find(x => (x.month || "") === selMonth) || {};
|
||||||
|
const e = ed.find(x => (x.month || "") === selMonth) || {};
|
||||||
|
const rev = Math.round(parseFloat(b.rev || 0) || 0);
|
||||||
|
const payment = Math.round(parseFloat(b.payment || 0) || 0);
|
||||||
|
const gross = Math.round(parseFloat(b.gross || 0) || 0);
|
||||||
|
const cost = Math.round(parseFloat(e.cost || 0) || 0);
|
||||||
|
const paid = Math.round(parseFloat(e.paid || 0) || 0);
|
||||||
|
if (!rev && !payment && !cost && !paid && !gross) return;
|
||||||
|
sumRev += rev; sumPay += payment; sumCost += cost; sumPaid += paid; sumGross += gross;
|
||||||
|
rows.push(tdRow(pf, rev, payment, cost, paid, gross));
|
||||||
|
});
|
||||||
|
const signTotal = Math.round(allPfs.filter(x => (x.sign_month || "").substring(0, 7) === selMonth).reduce((a, p) => a + (p.sign_amount || 0), 0));
|
||||||
|
const signCnt = allPfs.filter(x => x.status === "已签约" && (x.sign_month || "").substring(0, 7) === selMonth).length;
|
||||||
|
return renderView(rows, sumRev, sumPay, sumCost, sumPaid, sumGross, signTotal, signCnt, '该月份暂无数据');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (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 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 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 sumExpense = (pf, field) => {
|
||||||
|
let total = 0;
|
||||||
|
try { JSON.parse(pf.expense_data || "[]").forEach(e => { const m = parseInt((e.month || "").substring(5)) || 0; if (qRange.includes(m)) total += parseFloat(e[field] || 0); }); } catch (e) {}
|
||||||
|
return total;
|
||||||
|
};
|
||||||
|
let sumRev = 0, sumPay = 0, sumCost = 0, sumPaid = 0, sumGross = 0;
|
||||||
|
const rows = [];
|
||||||
|
allPfs.forEach(pf => {
|
||||||
|
const rev = sumBudget(pf, "rev");
|
||||||
|
const payment = sumBudget(pf, "payment");
|
||||||
|
const gross = sumBudget(pf, "gross");
|
||||||
|
const cost = sumExpense(pf, "cost");
|
||||||
|
const paid = sumExpense(pf, "paid");
|
||||||
|
sumRev += rev; sumPay += payment; sumCost += cost; sumPaid += paid; sumGross += gross;
|
||||||
|
rows.push(tdRow(pf, rev, payment, cost, paid, gross));
|
||||||
|
});
|
||||||
|
const signTotal = Math.round(allPfs.filter(x => { const m = parseInt((x.sign_month || "0").substring(5)) || 0; return qRange.includes(m); }).reduce((a, p) => a + (p.sign_amount || 0), 0));
|
||||||
|
const signCnt = allPfs.filter(x => x.status === "已签约" && qRange.includes(parseInt((x.sign_month || "0").substring(5)) || 0)).length;
|
||||||
|
return renderView(rows, sumRev, sumPay, sumCost, sumPaid, sumGross, signTotal, signCnt, '该季度暂无数据');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 总视图
|
||||||
|
const calcTotals = (pf) => {
|
||||||
|
let budget = []; try { budget = JSON.parse(pf.budget_data || "[]"); } catch (e) {}
|
||||||
|
let expense = []; try { expense = JSON.parse(pf.expense_data || "[]"); } catch (e) {}
|
||||||
|
let rev = 0, payment = 0, gross = 0;
|
||||||
|
budget.forEach(b => { rev += parseFloat(b.rev || 0) || 0; gross += parseFloat(b.gross || 0) || 0; payment += parseFloat(b.payment || 0) || 0; });
|
||||||
|
let cost = 0, paid = 0;
|
||||||
|
expense.forEach(e => { cost += parseFloat(e.cost || 0) || 0; paid += parseFloat(e.paid || 0) || 0; });
|
||||||
|
return { rev: Math.round(rev), payment: Math.round(payment), cost: Math.round(cost), paid: Math.round(paid), gross: Math.round(gross) };
|
||||||
|
};
|
||||||
|
const allPfs = pfs.filter(x => x.status === state.finFilter);
|
||||||
|
let sumRev = 0, sumPay = 0, sumCost = 0, sumPaid = 0, sumGross = 0;
|
||||||
|
const rows = [];
|
||||||
|
allPfs.forEach(pf => {
|
||||||
|
const t = calcTotals(pf);
|
||||||
|
sumRev += t.rev; sumPay += t.payment; sumCost += t.cost; sumPaid += t.paid; sumGross += t.gross;
|
||||||
|
rows.push(tdRow(pf, t.rev, t.payment, t.cost, t.paid, t.gross));
|
||||||
|
});
|
||||||
|
const signTotal = Math.round(allPfs.reduce((a, p) => a + (p.sign_amount || 0), 0));
|
||||||
|
const signCnt = allPfs.filter(x => x.status === "已签约").length;
|
||||||
|
return renderView(rows, sumRev, sumPay, sumCost, sumPaid, sumGross, signTotal, signCnt, '暂无数据');
|
||||||
|
})()}
|
||||||
</div>`;
|
</div>`;
|
||||||
if (window.lucide) window.lucide.createIcons();
|
if (window.lucide) window.lucide.createIcons();
|
||||||
}
|
}
|
||||||
@@ -181,54 +390,183 @@ window.openFinanceModal = () => {
|
|||||||
if (dept) dept.value = state.tenant;
|
if (dept) dept.value = state.tenant;
|
||||||
const pfIdInput = form.querySelector('[name="pf_id"]');
|
const pfIdInput = form.querySelector('[name="pf_id"]');
|
||||||
if (!pfIdInput || !pfIdInput.value) {
|
if (!pfIdInput || !pfIdInput.value) {
|
||||||
initBudgetTable(null);
|
initRevpayTable(null);
|
||||||
|
initCostTable(null);
|
||||||
|
initTaskTable(null);
|
||||||
document.querySelector("#financeDeleteBtn").classList.add("hidden");
|
document.querySelector("#financeDeleteBtn").classList.add("hidden");
|
||||||
}
|
}
|
||||||
modal.classList.remove("hidden");
|
modal.classList.remove("hidden");
|
||||||
};
|
};
|
||||||
|
|
||||||
window.addBudgetRow = (month = '', rev = '', gross = '', payment = '', cost = '') => {
|
window.addRevpayRow = (month = '', rev = '', gross = '', payment = '', rev_note = '') => {
|
||||||
const tbody = document.querySelector("#budgetTbody");
|
const tbody = document.querySelector("#revpayTbody");
|
||||||
if (!tbody) return;
|
if (!tbody) return;
|
||||||
const row = document.createElement("tr");
|
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>
|
row.innerHTML = `<td><select name="budget_month[]" class="form-ctrl form-ctrl-sm w-full" style="min-width:140px" onchange="updateRevpaySummary()">${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_rev[]" type="number" step="0.01" class="form-ctrl form-ctrl-sm w-full text-right" placeholder="0" value="${rev}" oninput="updateRevpaySummary()"></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_gross[]" type="number" step="0.01" class="form-ctrl form-ctrl-sm w-full text-right" placeholder="0" value="${gross}" oninput="updateRevpaySummary()"></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_payment[]" type="number" step="0.01" class="form-ctrl form-ctrl-sm w-full text-right" placeholder="0" value="${payment}" oninput="updateRevpaySummary()"></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_rev_note[]" class="form-ctrl form-ctrl-sm w-full" placeholder="备注" value="${rev_note}"></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>`;
|
<td><button type="button" class="btn btn-ghost btn-sm text-red-500 p-0 w-6 h-6" onclick="this.closest('tr').remove();updateRevpaySummary()"><i data-lucide="trash-2" style="width:14px;height:14px"></i></button></td>`;
|
||||||
tbody.appendChild(row);
|
tbody.appendChild(row);
|
||||||
if (window.lucide) window.lucide.createIcons();
|
if (window.lucide) window.lucide.createIcons();
|
||||||
};
|
};
|
||||||
|
|
||||||
window.updateBudgetSummary = () => {
|
window.addCostRow = (month = '', expense_type = '', cost = '', paid = '', exp_note = '') => {
|
||||||
const revEl = document.querySelector("#budgetTotalRev");
|
const tbody = document.querySelector("#costTbody");
|
||||||
const grossEl = document.querySelector("#budgetTotalGross");
|
if (!tbody) return;
|
||||||
const paymentEl = document.querySelector("#budgetTotalPayment");
|
const row = document.createElement("tr");
|
||||||
const costEl = document.querySelector("#budgetTotalCost");
|
row.innerHTML = `<td><select name="expense_month[]" class="form-ctrl form-ctrl-sm w-full" style="min-width:140px" onchange="updateCostSummary()">${monthOptions(month)}</select></td>
|
||||||
if (!revEl || !grossEl) return;
|
<td><input name="expense_type[]" class="form-ctrl form-ctrl-sm w-full" placeholder="费用类型" value="${expense_type}"></td>
|
||||||
|
<td><input name="expense_cost[]" type="number" step="0.01" class="form-ctrl form-ctrl-sm w-full text-right" placeholder="0" value="${cost}" oninput="updateCostSummary()"></td>
|
||||||
|
<td><input name="expense_paid[]" type="number" step="0.01" class="form-ctrl form-ctrl-sm w-full text-right" placeholder="0" value="${paid}" oninput="updateCostSummary()"></td>
|
||||||
|
<td><input name="expense_note[]" class="form-ctrl form-ctrl-sm w-full" placeholder="备注" value="${exp_note}"></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();updateCostSummary()"><i data-lucide="trash-2" style="width:14px;height:14px"></i></button></td>`;
|
||||||
|
tbody.appendChild(row);
|
||||||
|
if (window.lucide) window.lucide.createIcons();
|
||||||
|
};
|
||||||
|
|
||||||
|
window.updateRevpaySummary = () => {
|
||||||
|
const revEl = document.querySelector("#revpayTotalRev");
|
||||||
|
const grossEl = document.querySelector("#revpayTotalGross");
|
||||||
|
const paymentEl = document.querySelector("#revpayTotalPayment");
|
||||||
|
if (!revEl || !paymentEl) return;
|
||||||
const revInputs = document.querySelectorAll('[name="budget_rev[]"]');
|
const revInputs = document.querySelectorAll('[name="budget_rev[]"]');
|
||||||
const grossInputs = document.querySelectorAll('[name="budget_gross[]"]');
|
const grossInputs = document.querySelectorAll('[name="budget_gross[]"]');
|
||||||
const paymentInputs = document.querySelectorAll('[name="budget_payment[]"]');
|
const paymentInputs = document.querySelectorAll('[name="budget_payment[]"]');
|
||||||
const costInputs = document.querySelectorAll('[name="budget_cost[]"]');
|
let totalRev = 0, totalGross = 0, totalPayment = 0;
|
||||||
let totalRev = 0, totalGross = 0, totalPayment = 0, totalCost = 0;
|
|
||||||
revInputs.forEach(el => { totalRev += parseFloat(el.value) || 0; });
|
revInputs.forEach(el => { totalRev += parseFloat(el.value) || 0; });
|
||||||
grossInputs.forEach(el => { totalGross += parseFloat(el.value) || 0; });
|
grossInputs.forEach(el => { totalGross += parseFloat(el.value) || 0; });
|
||||||
paymentInputs.forEach(el => { totalPayment += parseFloat(el.value) || 0; });
|
paymentInputs.forEach(el => { totalPayment += parseFloat(el.value) || 0; });
|
||||||
costInputs.forEach(el => { totalCost += parseFloat(el.value) || 0; });
|
|
||||||
revEl.textContent = money(totalRev);
|
revEl.textContent = money(totalRev);
|
||||||
grossEl.textContent = money(totalGross);
|
if (grossEl) grossEl.textContent = money(totalGross);
|
||||||
if (paymentEl) paymentEl.textContent = money(totalPayment);
|
paymentEl.textContent = money(totalPayment);
|
||||||
if (costEl) costEl.textContent = money(totalCost);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
window.initBudgetTable = (budgetData) => {
|
window.updateCostSummary = () => {
|
||||||
const tbody = document.querySelector("#budgetTbody");
|
const costEl = document.querySelector("#costTotalCost");
|
||||||
|
const paidEl = document.querySelector("#costTotalPaid");
|
||||||
|
if (!costEl || !paidEl) return;
|
||||||
|
const costInputs = document.querySelectorAll('[name="expense_cost[]"]');
|
||||||
|
const paidInputs = document.querySelectorAll('[name="expense_paid[]"]');
|
||||||
|
let totalCost = 0, totalPaid = 0;
|
||||||
|
costInputs.forEach(el => { totalCost += parseFloat(el.value) || 0; });
|
||||||
|
paidInputs.forEach(el => { totalPaid += parseFloat(el.value) || 0; });
|
||||||
|
costEl.textContent = money(totalCost);
|
||||||
|
paidEl.textContent = money(totalPaid);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.initRevpayTable = (budgetData) => {
|
||||||
|
const tbody = document.querySelector("#revpayTbody");
|
||||||
if (!tbody) return;
|
if (!tbody) return;
|
||||||
tbody.innerHTML = "";
|
tbody.innerHTML = "";
|
||||||
const rows = budgetData || [];
|
const rows = budgetData || [];
|
||||||
rows.forEach(r => addBudgetRow(r.month || '', r.rev || '', r.gross || '', r.payment || '', r.cost || ''));
|
rows.forEach(r => addRevpayRow(r.month || '', r.rev || '', r.gross || '', r.payment || '', r.rev_note || ''));
|
||||||
setTimeout(() => updateBudgetSummary(), 50);
|
setTimeout(() => updateRevpaySummary(), 50);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.initCostTable = (expenseData) => {
|
||||||
|
const tbody = document.querySelector("#costTbody");
|
||||||
|
if (!tbody) return;
|
||||||
|
tbody.innerHTML = "";
|
||||||
|
const rows = expenseData || [];
|
||||||
|
rows.forEach(r => addCostRow(r.month || '', r.expense_type || '', r.cost || '', r.paid || '', r.exp_note || ''));
|
||||||
|
setTimeout(() => updateCostSummary(), 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 = () => {
|
window.closeFinanceModal = () => {
|
||||||
@@ -266,7 +604,65 @@ window.editPfSignMonth = (event, pfId) => {
|
|||||||
window.switchFinanceTab = (tab) => {
|
window.switchFinanceTab = (tab) => {
|
||||||
document.querySelectorAll(".finance-tab").forEach(b => b.classList.toggle("active", b.dataset.tab === 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("#financeTabInfo").classList.toggle("hidden", tab !== "info");
|
||||||
document.querySelector("#financeTabBudget").classList.toggle("hidden", tab !== "budget");
|
document.querySelector("#financeTabRevpay").classList.toggle("hidden", tab !== "revpay");
|
||||||
|
document.querySelector("#financeTabCost").classList.toggle("hidden", tab !== "cost");
|
||||||
|
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) => {
|
window.openPfEditModal = (pfId) => {
|
||||||
@@ -279,8 +675,20 @@ window.openPfEditModal = (pfId) => {
|
|||||||
form.querySelector('[name="project_id"]').value = pf.project_id || "";
|
form.querySelector('[name="project_id"]').value = pf.project_id || "";
|
||||||
const deptDisplay = form.querySelector('.bg-slate-50 [disabled]');
|
const deptDisplay = form.querySelector('.bg-slate-50 [disabled]');
|
||||||
if (deptDisplay) deptDisplay.value = pf.project_id || "";
|
if (deptDisplay) deptDisplay.value = pf.project_id || "";
|
||||||
form.querySelector('[name="business_type"]').value = pf.business_type || "";
|
// 回填业务类型多选
|
||||||
|
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 || "";
|
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 || "";
|
form.querySelector('[name="sign_amount"]').value = pf.sign_amount || "";
|
||||||
const signMonthValue = pf.sign_month || "";
|
const signMonthValue = pf.sign_month || "";
|
||||||
const signMonthEl = form.querySelector('[name="sign_month"]');
|
const signMonthEl = form.querySelector('[name="sign_month"]');
|
||||||
@@ -291,10 +699,26 @@ window.openPfEditModal = (pfId) => {
|
|||||||
form.querySelector('[name="status"]').value = pf.status || "待签约";
|
form.querySelector('[name="status"]').value = pf.status || "待签约";
|
||||||
form.querySelector('[name="sales_person"]').value = pf.sales_person || "";
|
form.querySelector('[name="sales_person"]').value = pf.sales_person || "";
|
||||||
form.querySelector('[name="owner"]').value = pf.owner || "";
|
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 = [];
|
let budgetData = [];
|
||||||
try { budgetData = JSON.parse(pf.budget_data || "[]"); } catch (e) { budgetData = []; }
|
try { budgetData = JSON.parse(pf.budget_data || "[]"); } catch (e) { budgetData = []; }
|
||||||
initBudgetTable(budgetData.length ? budgetData : null);
|
initRevpayTable(budgetData.length ? budgetData : null);
|
||||||
|
let expenseData = [];
|
||||||
|
try { expenseData = JSON.parse(pf.expense_data || "[]"); } catch (e) { expenseData = []; }
|
||||||
|
initCostTable(expenseData.length ? expenseData : null);
|
||||||
|
let taskData = [];
|
||||||
|
try { taskData = JSON.parse(pf.task_data || "[]"); } catch (e) { taskData = []; }
|
||||||
|
initTaskTable(taskData.length ? taskData : null);
|
||||||
setTimeout(() => updateBudgetSummary(), 100);
|
setTimeout(() => updateBudgetSummary(), 100);
|
||||||
|
loadFinFollowups(pf.id);
|
||||||
openFinanceModal();
|
openFinanceModal();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -302,6 +726,9 @@ window.createFinance = async (event) => {
|
|||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const form = event.currentTarget;
|
const form = event.currentTarget;
|
||||||
const data = Object.fromEntries(new FormData(form).entries());
|
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;
|
data.tenant = state.tenant;
|
||||||
// 必填校验
|
// 必填校验
|
||||||
if (!data.customer_name || !data.customer_name.trim()) { toast("项目名称必填", "error"); return; }
|
if (!data.customer_name || !data.customer_name.trim()) { toast("项目名称必填", "error"); return; }
|
||||||
@@ -314,23 +741,73 @@ window.createFinance = async (event) => {
|
|||||||
const revs = form.querySelectorAll('[name="budget_rev[]"]');
|
const revs = form.querySelectorAll('[name="budget_rev[]"]');
|
||||||
const grosses = form.querySelectorAll('[name="budget_gross[]"]');
|
const grosses = form.querySelectorAll('[name="budget_gross[]"]');
|
||||||
const payments = form.querySelectorAll('[name="budget_payment[]"]');
|
const payments = form.querySelectorAll('[name="budget_payment[]"]');
|
||||||
const costs = form.querySelectorAll('[name="budget_cost[]"]');
|
const revNotes = form.querySelectorAll('[name="budget_rev_note[]"]');
|
||||||
const budgetRows = [];
|
const budgetRows = [];
|
||||||
let totalRev = 0, totalGross = 0;
|
let totalRev = 0, totalGross = 0, totalPayment = 0;
|
||||||
for (let i = 0; i < months.length; i++) {
|
for (let i = 0; i < months.length; i++) {
|
||||||
const m = months[i].value.trim();
|
const m = months[i].value.trim();
|
||||||
if (!m) continue;
|
if (!m) continue;
|
||||||
const rev = parseFloat(revs[i].value) || 0;
|
const rev = parseFloat(revs[i].value) || 0;
|
||||||
const gross = parseFloat(grosses[i].value) || 0;
|
const gross = parseFloat(grosses[i].value) || 0;
|
||||||
const payment = parseFloat(payments[i].value) || 0;
|
const payment = parseFloat(payments[i].value) || 0;
|
||||||
const cost = parseFloat(costs[i].value) || 0;
|
const rev_note = (revNotes[i] ? revNotes[i].value : '') || '';
|
||||||
budgetRows.push({ month: m, rev, gross, payment, cost });
|
budgetRows.push({ month: m, rev, gross, payment, rev_note });
|
||||||
totalRev += rev;
|
totalRev += rev;
|
||||||
totalGross += gross;
|
totalGross += gross;
|
||||||
|
totalPayment += payment;
|
||||||
}
|
}
|
||||||
data.budget_data = JSON.stringify(budgetRows);
|
data.budget_data = JSON.stringify(budgetRows);
|
||||||
data.total_rev = totalRev;
|
data.total_rev = totalRev;
|
||||||
data.total_gross = totalGross;
|
data.total_gross = totalGross;
|
||||||
|
data.total_payment = totalPayment;
|
||||||
|
|
||||||
|
// 费用明细数据
|
||||||
|
const expMonths = form.querySelectorAll('[name="expense_month[]"]');
|
||||||
|
const expTypes = form.querySelectorAll('[name="expense_type[]"]');
|
||||||
|
const expCosts = form.querySelectorAll('[name="expense_cost[]"]');
|
||||||
|
const expPaids = form.querySelectorAll('[name="expense_paid[]"]');
|
||||||
|
const expNotes = form.querySelectorAll('[name="expense_note[]"]');
|
||||||
|
const expenseRows = [];
|
||||||
|
let totalCost = 0, totalPaid = 0;
|
||||||
|
for (let i = 0; i < expMonths.length; i++) {
|
||||||
|
const m = expMonths[i].value.trim();
|
||||||
|
if (!m) continue;
|
||||||
|
const expense_type = (expTypes[i] ? expTypes[i].value : '') || '';
|
||||||
|
const cost = parseFloat(expCosts[i].value) || 0;
|
||||||
|
const paid = parseFloat(expPaids[i].value) || 0;
|
||||||
|
const exp_note = (expNotes[i] ? expNotes[i].value : '') || '';
|
||||||
|
expenseRows.push({ month: m, expense_type, cost, paid, exp_note });
|
||||||
|
totalCost += cost;
|
||||||
|
totalPaid += paid;
|
||||||
|
}
|
||||||
|
data.expense_data = JSON.stringify(expenseRows);
|
||||||
|
data.total_paid = totalPaid;
|
||||||
|
data.total_cost = totalCost;
|
||||||
|
for (const r of budgetRows) { totalPayment += r.payment; }
|
||||||
|
data.total_payment = totalPayment;
|
||||||
|
// 收集任务管理数据
|
||||||
|
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;
|
const pfId = data.pf_id;
|
||||||
delete data.pf_id;
|
delete data.pf_id;
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -6,45 +6,151 @@ function renderHome() {
|
|||||||
const moneyInt = (v) => `${Math.round(Number(v || 0)).toLocaleString("zh-CN")} 元`;
|
const moneyInt = (v) => `${Math.round(Number(v || 0)).toLocaleString("zh-CN")} 元`;
|
||||||
const rows1 = [
|
const rows1 = [
|
||||||
["年度累计", moneyInt(m.signed_annual || m.signed_amount)],
|
["年度累计", moneyInt(m.signed_annual || m.signed_amount)],
|
||||||
["季度累计", moneyInt(m.signed_q2 || 0)],
|
["本季度累计", moneyInt(m.signed_q2 || 0)],
|
||||||
["本月新增", moneyInt(m.signed_month || 0)],
|
["本月累计", moneyInt(m.signed_month || 0)],
|
||||||
|
["上本季度累计", moneyInt(m.signed_prev_q || 0)],
|
||||||
|
["上月累计", moneyInt(m.signed_prev_month || 0)],
|
||||||
];
|
];
|
||||||
const rows2 = [
|
const rows2 = [
|
||||||
["年度累计", moneyInt(m.revenue_annual)],
|
["年度累计", moneyInt(m.revenue_annual)],
|
||||||
["季度累计", moneyInt(m.revenue_q2)],
|
["本季度累计", moneyInt(m.revenue_q2)],
|
||||||
["本月新增", moneyInt(m.monthly_revenue)],
|
["本月累计", moneyInt(m.monthly_revenue)],
|
||||||
|
["上本季度累计", moneyInt(m.revenue_prev_q || 0)],
|
||||||
|
["上月累计", moneyInt(m.revenue_prev_month || 0)],
|
||||||
];
|
];
|
||||||
const rows3 = [
|
const rows3 = [
|
||||||
["年度累计", moneyInt(m.gross_annual)],
|
["年度累计", moneyInt(m.gross_annual)],
|
||||||
["季度累计", moneyInt(m.gross_q2)],
|
["本季度累计", moneyInt(m.gross_q2)],
|
||||||
["本月新增", moneyInt(m.monthly_net_profit)],
|
["本月累计", moneyInt(m.monthly_net_profit)],
|
||||||
|
["上本季度累计", moneyInt(m.gross_prev_q || 0)],
|
||||||
|
["上月累计", moneyInt(m.gross_prev_month || 0)],
|
||||||
];
|
];
|
||||||
const rows4 = [
|
const rows4 = [
|
||||||
["年度累计", moneyInt(m.payment_annual || 0)],
|
["年度累计", moneyInt(m.payment_annual || 0)],
|
||||||
["季度累计", moneyInt(m.payment_q2 || 0)],
|
["本季度累计", moneyInt(m.payment_q2 || 0)],
|
||||||
["本月新增", moneyInt(m.payment_month || 0)],
|
["本月累计", moneyInt(m.payment_month || 0)],
|
||||||
|
["上本季度累计", moneyInt(m.payment_prev_q || 0)],
|
||||||
|
["上月累计", moneyInt(m.payment_prev_month || 0)],
|
||||||
];
|
];
|
||||||
const rows5 = [
|
const rows5 = [
|
||||||
["年度累计", moneyInt(m.cost_annual || 0)],
|
["年度累计", moneyInt(m.cost_annual || 0)],
|
||||||
["季度累计", moneyInt(m.cost_q2 || 0)],
|
["本季度累计", moneyInt(m.cost_q2 || 0)],
|
||||||
["本月新增", moneyInt(m.cost_month || 0)],
|
["本月累计", moneyInt(m.cost_month || 0)],
|
||||||
|
["上本季度累计", moneyInt(m.cost_prev_q || 0)],
|
||||||
|
["上月累计", moneyInt(m.cost_prev_month || 0)],
|
||||||
];
|
];
|
||||||
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");
|
const rows7 = [
|
||||||
|
["年度累计", moneyInt(m.paid_annual || 0)],
|
||||||
|
["本季度累计", moneyInt(m.paid_q2 || 0)],
|
||||||
|
["本月累计", moneyInt(m.paid_month || 0)],
|
||||||
|
["上本季度累计", moneyInt(m.paid_prev_q || 0)],
|
||||||
|
["上月累计", moneyInt(m.paid_prev_month || 0)],
|
||||||
|
];
|
||||||
|
const rowsProjExpense = [
|
||||||
|
["年度累计", moneyInt(m.proj_expense_annual || 0)],
|
||||||
|
["本季度累计", moneyInt(m.proj_expense_q2 || 0)],
|
||||||
|
["本月累计", moneyInt(m.proj_expense_month || 0)],
|
||||||
|
["上本季度累计", moneyInt(m.proj_expense_prev_q || 0)],
|
||||||
|
["上月累计", moneyInt(m.proj_expense_prev_month || 0)],
|
||||||
|
];
|
||||||
|
const rows8 = [
|
||||||
|
["年度累计", moneyInt(m.cashflow_annual || 0)],
|
||||||
|
["本季度累计", moneyInt(m.cashflow_q2 || 0)],
|
||||||
|
["本月累计", moneyInt(m.cashflow_month || 0)],
|
||||||
|
["上本季度累计", moneyInt(m.cashflow_prev_q || 0)],
|
||||||
|
["上月累计", moneyInt(m.cashflow_prev_month || 0)],
|
||||||
|
];
|
||||||
|
const rows9 = [
|
||||||
|
["年度累计", moneyInt(m.profit_annual || 0)],
|
||||||
|
["本季度累计", moneyInt(m.profit_q2 || 0)],
|
||||||
|
["本月累计", moneyInt(m.profit_month || 0)],
|
||||||
|
["上本季度累计", moneyInt(m.profit_prev_q || 0)],
|
||||||
|
["上月累计", moneyInt(m.profit_prev_month || 0)],
|
||||||
|
];
|
||||||
|
const qoq = (cur, prev) => {
|
||||||
|
if (!prev) return '<span class="text-slate-300">—</span>';
|
||||||
|
const pct = Math.round((cur - prev) / prev * 100);
|
||||||
|
const cls = pct >= 0 ? 'text-green-600' : 'text-red-600';
|
||||||
|
const sign = pct >= 0 ? '+' : '';
|
||||||
|
return '<span class="' + cls + '">' + sign + pct + '%</span>';
|
||||||
|
};
|
||||||
|
const COLORS = ['text-slate-700','text-blue-600','text-green-600','text-rose-600','text-indigo-600','text-amber-600','text-purple-600','text-cyan-600'];
|
||||||
|
const LABELS = ['合同金额','确收金额','确收毛利','成本','项目利润','回款金额','已付','现金流'];
|
||||||
|
const Q_FIELDS = [m.signed_q2||0, m.revenue_q2, m.gross_q2, m.cost_q2||0, m.profit_q2||0, m.payment_q2||0, m.paid_q2||0, m.cashflow_q2||0];
|
||||||
|
const Q_PREV = [m.signed_prev_q||0, m.revenue_prev_q||0, m.gross_prev_q||0, m.cost_prev_q||0, m.profit_prev_q||0, m.payment_prev_q||0, m.paid_prev_q||0, m.cashflow_prev_q||0];
|
||||||
|
const M_FIELDS = [m.signed_month||0, m.monthly_revenue, m.monthly_net_profit, m.cost_month||0, m.profit_month||0, m.payment_month||0, m.paid_month||0, m.cashflow_month||0];
|
||||||
|
const M_PREV = [m.signed_prev_month||0, m.revenue_prev_month||0, m.gross_prev_month||0, m.cost_prev_month||0, m.profit_prev_month||0, m.payment_prev_month||0, m.paid_prev_month||0, m.cashflow_prev_month||0];
|
||||||
|
const ROWS = [rows1, rows2, rows3, rows5, rows9, rows4, rows7, rows8];
|
||||||
|
// 现金流和项目利润的原始值数组,用于正负着色
|
||||||
|
const CF_RAW = [m.cashflow_annual||0, m.cashflow_q2||0, m.cashflow_month||0, m.cashflow_prev_q||0, m.cashflow_prev_month||0];
|
||||||
|
const PF_RAW = [m.profit_annual||0, m.profit_q2||0, m.profit_month||0, m.profit_prev_q||0, m.profit_prev_month||0];
|
||||||
|
var valCls = function(ri) { return (ri === 4 || ri === 7) ? '' : 'text-slate-800'; };
|
||||||
|
var tdVal = function(ri, col, val) {
|
||||||
|
if (ri === 4) return '<td class="py-2 text-right font-semibold ' + (PF_RAW[col] >= 0 ? 'text-green-600' : 'text-red-600') + '">' + val + '</td>';
|
||||||
|
if (ri === 7) return '<td class="py-2 text-right font-semibold ' + (CF_RAW[col] >= 0 ? 'text-green-600' : 'text-red-600') + '">' + val + '</td>';
|
||||||
|
return '<td class="py-2 text-right font-semibold text-slate-800">' + val + '</td>';
|
||||||
|
};
|
||||||
|
var thead = '<tr class="border-b border-slate-200"><th class="py-2 text-left text-slate-500">指标</th><th class="py-2 text-right font-semibold text-slate-700">年度累计</th><th class="py-2 text-right font-semibold text-slate-700">上季度累计</th><th class="py-2 text-right font-semibold text-slate-700">上月累计</th><th class="py-2 text-right font-semibold text-slate-700">本季度累计</th><th class="py-2 text-right font-semibold text-slate-400">季环比</th><th class="py-2 text-right font-semibold text-slate-700">本月累计</th><th class="py-2 text-right font-semibold text-slate-400">月环比</th></tr>';
|
||||||
|
var tbody = '';
|
||||||
|
for (var ri = 0; ri < 8; ri++) {
|
||||||
|
var vals = ROWS[ri];
|
||||||
|
tbody += '<tr class="border-b border-slate-100 last:border-0"><td class="py-2 text-left font-semibold text-slate-700">' + LABELS[ri] + '</td>' +
|
||||||
|
tdVal(ri, 0, vals[0][1]) +
|
||||||
|
tdVal(ri, 3, vals[3][1]) +
|
||||||
|
tdVal(ri, 4, vals[4][1]) +
|
||||||
|
tdVal(ri, 1, vals[1][1]) +
|
||||||
|
'<td class="py-2 text-right">' + qoq(Q_FIELDS[ri], Q_PREV[ri]) + '</td>' +
|
||||||
|
tdVal(ri, 2, vals[2][1]) +
|
||||||
|
'<td class="py-2 text-right">' + qoq(M_FIELDS[ri], M_PREV[ri]) + '</td></tr>';
|
||||||
|
}
|
||||||
document.querySelector("#home").innerHTML = `
|
document.querySelector("#home").innerHTML = `
|
||||||
<div class="grid gap-5">
|
<div class="grid gap-5">
|
||||||
<div class="grid grid-cols-4 gap-3">
|
${state.tenant === "总工作台" ? "" : `<div class="grid grid-cols-4 gap-3">
|
||||||
${[
|
${[
|
||||||
["经营管理", m.total_projects, "finance"],
|
["项目管理", m.total_projects, "finance"],
|
||||||
["重点工作与台账", m.total_proposals, "projects"],
|
["重点工作与台账", m.total_proposals, "projects"],
|
||||||
["业务方案", m.total_products, "proposals"],
|
["业务方案", m.total_products, "proposals"],
|
||||||
["产品迭代", m.upcoming_products, "products"],
|
["产品迭代", 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("")}
|
].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>`}
|
||||||
<div class="grid grid-cols-5 gap-5">${tblCard("合同金额", rows1)}${tblCard("确收金额", rows2)}${tblCard("确收毛利", rows3)}${tblCard("回款金额", rows4)}${tblCard("费用金额", rows5)}</div>
|
${card(`<h3 class="text-sm font-bold text-slate-700 mb-3">部门经营情况</h3><div class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="border-b border-slate-200"><th class="py-2 text-left text-slate-500">指标</th><th class="py-2 text-right font-semibold text-slate-700">年度累计</th><th class="py-2 text-right font-semibold text-slate-700">上季度累计</th><th class="py-2 text-right font-semibold text-slate-700">上月累计</th><th class="py-2 text-right font-semibold text-slate-700">本季度累计</th><th class="py-2 text-right font-semibold text-slate-400">季环比</th><th class="py-2 text-right font-semibold text-slate-700">本月累计</th><th class="py-2 text-right font-semibold text-slate-400">月环比</th></tr></thead><tbody>
|
||||||
<div class="grid grid-cols-3 gap-5">
|
${(() => {
|
||||||
|
var d = [
|
||||||
|
['部门毛利', [m.profit_annual||0, m.profit_q2||0, m.profit_month||0, m.profit_prev_q||0, m.profit_prev_month||0],
|
||||||
|
[m.profit_q2||0,m.profit_prev_q||0], [m.profit_month||0,m.profit_prev_month||0]],
|
||||||
|
['部门费用', [m.expense_annual||0, m.expense_q2||0, (m.expense_month||0), m.expense_prev_q||0, m.expense_prev_month||0],
|
||||||
|
[m.expense_q2||0,m.expense_prev_q||0], [(m.expense_month||0),m.expense_prev_month||0]],
|
||||||
|
['部门净利', [
|
||||||
|
(m.profit_annual||0)-(m.expense_annual||0), (m.profit_q2||0)-(m.expense_q2||0), (m.profit_month||0)-(m.expense_month||0),
|
||||||
|
(m.profit_prev_q||0)-(m.expense_prev_q||0), (m.profit_prev_month||0)-(m.expense_prev_month||0)
|
||||||
|
], [
|
||||||
|
(m.profit_q2||0)-(m.expense_q2||0), (m.profit_prev_q||0)-(m.expense_prev_q||0)
|
||||||
|
], [
|
||||||
|
(m.profit_month||0)-(m.expense_month||0), (m.profit_prev_month||0)-(m.expense_prev_month||0)
|
||||||
|
]]
|
||||||
|
];
|
||||||
|
var h = '';
|
||||||
|
var netCls = function(di, raw) { return di === 2 ? (raw >= 0 ? 'text-green-600' : 'text-red-600') : 'text-slate-800'; };
|
||||||
|
for (var di = 0; di < 3; di++) {
|
||||||
|
var r = d[di];
|
||||||
|
h += '<tr class="border-b border-slate-100 last:border-0"><td class="py-2 text-left font-semibold text-slate-700">' + r[0] + '</td>' +
|
||||||
|
'<td class="py-2 text-right font-semibold ' + netCls(di, r[1][0]) + '">' + moneyInt(r[1][0]) + '</td>' +
|
||||||
|
'<td class="py-2 text-right font-semibold ' + netCls(di, r[1][3]) + '">' + moneyInt(r[1][3]) + '</td>' +
|
||||||
|
'<td class="py-2 text-right font-semibold ' + netCls(di, r[1][4]) + '">' + moneyInt(r[1][4]) + '</td>' +
|
||||||
|
'<td class="py-2 text-right font-semibold ' + netCls(di, r[1][1]) + '">' + moneyInt(r[1][1]) + '</td>' +
|
||||||
|
'<td class="py-2 text-right">' + qoq(r[2][0], r[2][1]) + '</td>' +
|
||||||
|
'<td class="py-2 text-right font-semibold ' + netCls(di, r[1][2]) + '">' + moneyInt(r[1][2]) + '</td>' +
|
||||||
|
'<td class="py-2 text-right">' + qoq(r[3][0], r[3][1]) + '</td></tr>';
|
||||||
|
}
|
||||||
|
return h;
|
||||||
|
})()}
|
||||||
|
</tbody></table></div>`, "p-4")}
|
||||||
|
${card(`<h3 class="text-sm font-bold text-slate-700">业务(项目)财务概览</h3><p class="text-xs text-slate-400 mb-3">合同 → 确收 → 毛利 → 成本 → 项目利润 → 回款 → 已付 → 现金流</p><div class="overflow-x-auto"><table class="w-full text-sm"><thead>${thead}</thead><tbody>${tbody}</tbody></table></div>`, "p-4")}
|
||||||
|
<div class="grid grid-cols-4 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="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="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")}
|
${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")}
|
||||||
|
${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="chartProfit"></canvas></div>`, "p-4")}
|
||||||
</div>
|
</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")}
|
${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>
|
</div>
|
||||||
@@ -98,15 +204,28 @@ function renderCharts(data) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// 图3:月度回款与费用
|
// 图3:月度回款与已付
|
||||||
const c3 = document.querySelector("#chartCash");
|
const c3 = document.querySelector("#chartCash");
|
||||||
if (c3 && window.Chart) {
|
if (c3 && window.Chart) {
|
||||||
if (state.chart3) state.chart3.destroy();
|
if (state.chart3) state.chart3.destroy();
|
||||||
state.chart3 = new Chart(c3, {
|
state.chart3 = new Chart(c3, {
|
||||||
type: "bar",
|
type: "line",
|
||||||
data: { labels, datasets: [
|
data: { labels, datasets: [
|
||||||
{ label: "回款", data: data.map((x) => x.payment || 0), backgroundColor: "#d97706", borderRadius: 4 },
|
{ label: "回款", data: data.map((x) => x.payment || 0), borderColor: "#d97706", backgroundColor: "rgba(217,119,6,0.06)", fill: true, tension: 0.3 },
|
||||||
{ label: "费用", data: data.map((x) => x.cost || 0), backgroundColor: "#ef4444", borderRadius: 4 },
|
{ label: "已付", data: data.map((x) => x.cost || 0), borderColor: "#7c3aed", backgroundColor: "rgba(124,58,237,0.06)", fill: true, tension: 0.3 },
|
||||||
|
]},
|
||||||
|
options: baseOpts,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 图4:月度项目利润
|
||||||
|
const c4 = document.querySelector("#chartProfit");
|
||||||
|
if (c4 && window.Chart) {
|
||||||
|
if (state.chart4) state.chart4.destroy();
|
||||||
|
state.chart4 = new Chart(c4, {
|
||||||
|
type: "line",
|
||||||
|
data: { labels, datasets: [
|
||||||
|
{ label: "利润", data: data.map((x) => (x.gross || 0)), borderColor: "#6366f1", backgroundColor: "rgba(99,102,241,0.06)", fill: true, tension: 0.3 },
|
||||||
]},
|
]},
|
||||||
options: baseOpts,
|
options: baseOpts,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -39,13 +39,25 @@ window.openProductDrawer = () => {
|
|||||||
<button class="task-close" onclick="closeProductDrawer()"><i data-lucide="x"></i></button>
|
<button class="task-close" onclick="closeProductDrawer()"><i data-lucide="x"></i></button>
|
||||||
</div>
|
</div>
|
||||||
<form class="task-drawer-form" onsubmit="submitProductDrawer(event)">
|
<form class="task-drawer-form" onsubmit="submitProductDrawer(event)">
|
||||||
<label class="task-field"><span>产品名称</span><input name="product_name" required class="form-ctrl"></label>
|
<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><input name="version" required class="form-ctrl"></label>
|
||||||
<label class="task-field"><span>版本目标</span><textarea name="version_goal" rows="2" class="form-ctrl"></textarea></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>
|
||||||
<label class="task-field"><span>核心功能</span><div class="feature-list" id="newFeatureList"><div class="feature-item"><span class="feature-num">1.</span><input class="form-ctrl" value=""><button class="feature-del" onclick="event.preventDefault();removeNewFeature(this)"><i data-lucide="x" style="width:12px;height:12px"></i></button></div></div><button class="btn btn-ghost btn-sm text-blue-600 mt-1" onclick="event.preventDefault();addNewFeature()"><i data-lucide="plus" style="width:14px;height:14px"></i>添加功能</button></label>
|
</div>
|
||||||
<label class="task-field"><span>上线日期</span><input name="launch_date" type="date" class="form-ctrl"></label>
|
<label class="task-field"><span>版本目标</span><textarea name="version_goal" rows="3" class="form-ctrl"></textarea></label>
|
||||||
<label class="task-field"><span>状态</span><select name="status" class="form-ctrl"><option>规划中</option><option>开发中</option><option>测试中</option><option>已上线</option><option>已取消</option></select></label>
|
<div class="grid grid-cols-2 gap-3">
|
||||||
<input type="hidden" name="feature_list" id="newFeatureListHidden">
|
<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">
|
<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="button" class="btn btn-ghost btn-sm" onclick="closeProductDrawer()">取消</button>
|
||||||
<button type="submit" class="btn btn-primary btn-sm">确认新增</button>
|
<button type="submit" class="btn btn-primary btn-sm">确认新增</button>
|
||||||
@@ -63,7 +75,7 @@ window.cycleProductStatus = async (id) => {
|
|||||||
const products = state.data.products || [];
|
const products = state.data.products || [];
|
||||||
const product = products.find(x => x.id === id);
|
const product = products.find(x => x.id === id);
|
||||||
if (!product) return;
|
if (!product) return;
|
||||||
const statuses = ["规划中", "开发中", "测试中", "已上线", "已取消"];
|
const statuses = ["未开始", "规划中", "开发中", "测试中", "已上线", "已取消"];
|
||||||
const current = statuses.indexOf(product.status) >= 0 ? product.status : "规划中";
|
const current = statuses.indexOf(product.status) >= 0 ? product.status : "规划中";
|
||||||
const newStatus = statuses[(statuses.indexOf(current) + 1) % statuses.length];
|
const newStatus = statuses[(statuses.indexOf(current) + 1) % statuses.length];
|
||||||
try {
|
try {
|
||||||
@@ -103,32 +115,26 @@ window.editProductDate = (event, id) => {
|
|||||||
input.focus();
|
input.focus();
|
||||||
};
|
};
|
||||||
|
|
||||||
window.addNewFeature = () => {
|
window.addNewFeature = () => {};
|
||||||
const list = document.querySelector("#newFeatureList");
|
window.removeNewFeature = () => {};
|
||||||
if (!list) return;
|
window.addFeature = () => {};
|
||||||
const idx = list.children.length;
|
window.removeFeature = () => {};
|
||||||
const div = document.createElement("div");
|
window.saveFeatureList = () => {};
|
||||||
div.className = "feature-item";
|
|
||||||
div.innerHTML = `<span class="feature-num">${idx+1}.</span><input class="form-ctrl" value=""><button class="feature-del" onclick="event.preventDefault();removeNewFeature(this)"><i data-lucide="x" style="width:12px;height:12px"></i></button>`;
|
|
||||||
list.appendChild(div);
|
|
||||||
if (window.lucide) window.lucide.createIcons();
|
|
||||||
};
|
|
||||||
|
|
||||||
window.removeNewFeature = (btn) => {
|
|
||||||
const div = btn.closest(".feature-item");
|
|
||||||
if (!div) return;
|
|
||||||
div.remove();
|
|
||||||
const list = document.querySelector("#newFeatureList");
|
|
||||||
if (list) list.querySelectorAll(".feature-num").forEach((el, i) => { el.textContent = (i+1) + "."; });
|
|
||||||
};
|
|
||||||
|
|
||||||
window.submitProductDrawer = async (event) => {
|
window.submitProductDrawer = async (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const form = event.currentTarget;
|
const form = event.currentTarget;
|
||||||
const data = Object.fromEntries(new FormData(form).entries());
|
const data = Object.fromEntries(new FormData(form).entries());
|
||||||
const featureInputs = form.querySelectorAll("#newFeatureList input");
|
// 约束:4 个时间不能早于启动时间
|
||||||
data.feature_list = [...featureInputs].map(el => el.value.trim()).filter(Boolean).join("\n");
|
const startDate = data.start_date;
|
||||||
data.platform = "";
|
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;
|
data.tenant = state.tenant;
|
||||||
try {
|
try {
|
||||||
const result = await api("/api/products", { method: "POST", body: JSON.stringify({ data }) });
|
const result = await api("/api/products", { method: "POST", body: JSON.stringify({ data }) });
|
||||||
@@ -141,64 +147,198 @@ window.submitProductDrawer = async (event) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
window.addFeature = (id) => {
|
window.addFeature = () => {};
|
||||||
const list = document.querySelector(`#featureList_${id}`);
|
window.removeFeature = () => {};
|
||||||
if (!list) return;
|
window.saveFeatureList = () => {};
|
||||||
const idx = list.children.length;
|
|
||||||
const div = document.createElement("div");
|
// 排序状态
|
||||||
div.className = "feature-item";
|
let productSort = { field: null, dir: 1 };
|
||||||
div.innerHTML = `<span class="feature-num">${idx+1}.</span><input class="form-ctrl" value="" onchange="saveFeatureList(${id})"><button class="feature-del" onclick="event.preventDefault();removeFeature(${id},${idx})"><i data-lucide="x" style="width:12px;height:12px"></i></button>`;
|
|
||||||
list.appendChild(div);
|
window.sortProducts = (field) => {
|
||||||
if (window.lucide) window.lucide.createIcons();
|
if (productSort.field === field) {
|
||||||
saveFeatureList(id);
|
productSort.dir = -productSort.dir;
|
||||||
|
} else {
|
||||||
|
productSort.field = field;
|
||||||
|
productSort.dir = 1;
|
||||||
|
}
|
||||||
|
renderProducts();
|
||||||
};
|
};
|
||||||
|
|
||||||
window.removeFeature = (id, idx) => {
|
function sortItems(items) {
|
||||||
const list = document.querySelector(`#featureList_${id}`);
|
if (!productSort.field) return items;
|
||||||
if (!list) return;
|
const f = productSort.field;
|
||||||
const items = list.querySelectorAll(".feature-item");
|
const d = productSort.dir;
|
||||||
if (items[idx]) items[idx].remove();
|
const priorityOrder = { P0: 0, P1: 1, P2: 2, P3: 3 };
|
||||||
list.querySelectorAll(".feature-num").forEach((el, i) => { el.textContent = (i+1) + "."; });
|
return [...items].sort((a, b) => {
|
||||||
saveFeatureList(id);
|
let va = a[f] || '', vb = b[f] || '';
|
||||||
};
|
if (f === 'priority') { va = priorityOrder[va] ?? 9; vb = priorityOrder[vb] ?? 9; }
|
||||||
|
if (va < vb) return -1 * d;
|
||||||
window.saveFeatureList = (id) => {
|
if (va > vb) return 1 * d;
|
||||||
const list = document.querySelector(`#featureList_${id}`);
|
return 0;
|
||||||
if (!list) return;
|
});
|
||||||
const values = [...list.querySelectorAll("input")].map(el => el.value.trim()).filter(Boolean);
|
}
|
||||||
const data = values.join("\n");
|
|
||||||
api(`/api/products/${id}`, { method: "PUT", body: JSON.stringify({ data: { feature_list: data } }) });
|
|
||||||
const product = (state.data.products || []).find(x => x.id === id);
|
|
||||||
if (product) product.feature_list = data;
|
|
||||||
};
|
|
||||||
|
|
||||||
function renderProducts() {
|
function renderProducts() {
|
||||||
const items = state.data.products || [];
|
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 = `
|
document.querySelector("#products").innerHTML = `
|
||||||
<div class="grid gap-4">
|
<div class="grid gap-4">
|
||||||
<div class="flex justify-end">
|
<div class="flex justify-end">
|
||||||
<button class="btn btn-primary btn-sm" onclick="openProductDrawer()"><i data-lucide="plus"></i>新增产品版本</button>
|
<button class="btn btn-primary btn-sm" onclick="openProductDrawer()"><i data-lucide="plus"></i>新增产品版本</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="grid grid-cols-3 gap-4">
|
<div class="card overflow-x-auto">
|
||||||
${items.map((p) => `
|
<table class="w-full text-sm">
|
||||||
<div class="bg-white rounded-xl border border-slate-200 p-4 cursor-pointer hover:shadow-lg hover:border-blue-200 transition-all" onclick="openDrawer('products', ${p.id})">
|
<thead class="bg-slate-50 border-b border-slate-200">
|
||||||
<div class="flex items-start justify-between">
|
<tr class="text-left text-xs text-slate-500 uppercase tracking-wider">
|
||||||
<h4 class="text-base font-semibold text-slate-800 leading-tight">${esc(p.product_name)}</h4>
|
${sortTh('version','版本号')}
|
||||||
<span class="status-badge status-${esc(p.status)}" onclick="event.stopPropagation(); cycleProductStatus(${p.id})" title="点击切换状态">${esc(p.status) || '规划中'}</span>
|
${sortTh('priority','优先级')}
|
||||||
</div>
|
${sortTh('product_name','版本名称')}
|
||||||
<div class="mt-2 flex items-center gap-2 text-xs text-slate-500">
|
${sortTh('status','状态')}
|
||||||
<span class="font-medium">${esc(p.version)}</span>
|
${sortTh('start_date','启动时间')}
|
||||||
<span>·</span>
|
${sortTh('plan_date','产品方案')}
|
||||||
<span class="cursor-pointer hover:text-blue-600 transition-colors" onclick="event.stopPropagation(); editProductDate(event, ${p.id})">${esc(p.launch_date) || '—'}</span>
|
${sortTh('dev_done_date','研发完成')}
|
||||||
</div>
|
${sortTh('test_date','测试完成')}
|
||||||
<div class="mt-3 space-y-1">
|
${sortTh('launch_date','上线时间')}
|
||||||
<p class="text-sm text-slate-700 mt-1.5 leading-relaxed">${esc(p.version_goal) || '—'}</p>
|
<th class="px-3 py-2.5 font-semibold align-middle whitespace-nowrap">总耗时</th>
|
||||||
<div class="text-sm text-slate-600 mt-1.5 leading-relaxed whitespace-pre-line">${esc(p.feature_list) || '—'}</div>
|
</tr>
|
||||||
</div>
|
</thead>
|
||||||
</div>
|
<tbody class="divide-y divide-slate-100">
|
||||||
`).join("")}
|
${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>
|
||||||
</div>
|
</div>
|
||||||
<aside id="productDrawer" class="task-drawer"></aside>
|
<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"); }
|
||||||
|
};
|
||||||
|
|||||||
@@ -13,13 +13,57 @@ function applyUserTenants() {
|
|||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
toggleUserMenu(user);
|
toggleUserMenu(user);
|
||||||
});
|
});
|
||||||
const allowedTenants = data.tenants || [];
|
// 缓存可用工作台列表,供下拉菜单使用
|
||||||
document.querySelectorAll(".workspace-nav-item").forEach(el => {
|
state.allowedTenants = data.tenants || [];
|
||||||
el.style.display = allowedTenants.includes(el.dataset.tenant) ? "" : "none";
|
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) => {
|
window.toggleUserMenu = (user) => {
|
||||||
let menu = document.getElementById("userMenu");
|
let menu = document.getElementById("userMenu");
|
||||||
if (menu) { menu.remove(); return; }
|
if (menu) { menu.remove(); return; }
|
||||||
|
|||||||
@@ -9,13 +9,18 @@ const state = {
|
|||||||
selectedProject: null,
|
selectedProject: null,
|
||||||
taskQuery: "",
|
taskQuery: "",
|
||||||
taskView: localStorage.getItem("opc-task-view") || "detail",
|
taskView: localStorage.getItem("opc-task-view") || "detail",
|
||||||
finView: localStorage.getItem("opc-fin-view") || "rev",
|
finView: localStorage.getItem("opc-fin-view") || "overview",
|
||||||
proposalTab: "standard",
|
proposalTab: "standard",
|
||||||
chart: null,
|
chart: null,
|
||||||
chart2: null,
|
chart2: null,
|
||||||
chart3: null,
|
chart3: null,
|
||||||
|
chart4: null,
|
||||||
productPlatform: "all",
|
productPlatform: "all",
|
||||||
uploadTasks: [],
|
uploadTasks: [],
|
||||||
|
expenseFilter: "全部",
|
||||||
|
expenseView: "total",
|
||||||
|
expenseMonth: "",
|
||||||
|
expenseQuarter: "",
|
||||||
};
|
};
|
||||||
|
|
||||||
const money = (value) => `${Number(value || 0).toLocaleString("zh-CN")} 元`;
|
const money = (value) => `${Number(value || 0).toLocaleString("zh-CN")} 元`;
|
||||||
@@ -123,11 +128,23 @@ async function load() {
|
|||||||
function switchTab(tab) {
|
function switchTab(tab) {
|
||||||
state.active = tab;
|
state.active = tab;
|
||||||
localStorage.setItem("opc-active-tab", tab);
|
localStorage.setItem("opc-active-tab", tab);
|
||||||
document.querySelectorAll("#tabs button").forEach((btn) => btn.classList.toggle("active", btn.dataset.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));
|
document.querySelectorAll(".panel").forEach((panel) => panel.classList.toggle("active", panel.id === tab));
|
||||||
render();
|
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() {
|
function render() {
|
||||||
if (!state.data) return;
|
if (!state.data) return;
|
||||||
renderHome();
|
renderHome();
|
||||||
@@ -135,6 +152,7 @@ function render() {
|
|||||||
renderProposals();
|
renderProposals();
|
||||||
renderProducts();
|
renderProducts();
|
||||||
renderFinance();
|
renderFinance();
|
||||||
|
renderExpense();
|
||||||
if (window.lucide) window.lucide.createIcons();
|
if (window.lucide) window.lucide.createIcons();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,7 +197,10 @@ window.switchTenant = (tenant) => {
|
|||||||
state.selectedProject = null;
|
state.selectedProject = null;
|
||||||
localStorage.setItem("opc-active-tenant", tenant);
|
localStorage.setItem("opc-active-tenant", tenant);
|
||||||
document.querySelector("#workspaceTitle").textContent = tenant.replace("·无界", "") + " OPC 工作台";
|
document.querySelector("#workspaceTitle").textContent = tenant.replace("·无界", "") + " OPC 工作台";
|
||||||
document.querySelectorAll(".workspace-nav-item").forEach((el) => el.classList.toggle("active", el.dataset.tenant === tenant));
|
const label = document.querySelector("#currentTenantLabel");
|
||||||
|
if (label) { label.textContent = tenant.replace("·无界", "") || "工作台"; label.title = tenant; }
|
||||||
|
updateSidebarTabs();
|
||||||
|
if (tenant === "总工作台") switchTab("home");
|
||||||
load();
|
load();
|
||||||
};
|
};
|
||||||
window.doLogout = async () => {
|
window.doLogout = async () => {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
body {
|
body {
|
||||||
min-width: 1180px;
|
min-width: 1400px;
|
||||||
|
overflow-x: auto;
|
||||||
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
|
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,25 +33,30 @@ body {
|
|||||||
background: rgba(96,165,250,0.15);
|
background: rgba(96,165,250,0.15);
|
||||||
}
|
}
|
||||||
|
|
||||||
.tabs {
|
.sidebar-tab {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 4px;
|
flex-direction: column;
|
||||||
}
|
|
||||||
|
|
||||||
.tabs button {
|
|
||||||
align-items: center;
|
align-items: center;
|
||||||
border-bottom: 2px solid transparent;
|
padding: 8px 4px;
|
||||||
color: #64748b;
|
border-radius: 8px;
|
||||||
display: inline-flex;
|
cursor: pointer;
|
||||||
font-size: 14px;
|
color: #94a3b8;
|
||||||
font-weight: 600;
|
transition: all 0.15s ease;
|
||||||
gap: 8px;
|
width: 100%;
|
||||||
padding: 14px 16px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.tabs button.active {
|
.sidebar-tab:hover {
|
||||||
border-bottom-color: #1d4ed8;
|
background: #1e293b;
|
||||||
color: #1d4ed8;
|
color: #cbd5e1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar-tab.active {
|
||||||
|
background: #1e293b;
|
||||||
|
color: #60a5fa;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar-tab.active i {
|
||||||
|
color: #60a5fa;
|
||||||
}
|
}
|
||||||
|
|
||||||
.panel {
|
.panel {
|
||||||
@@ -89,6 +95,33 @@ body {
|
|||||||
border-bottom-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 {
|
.project-board {
|
||||||
background: #fff;
|
background: #fff;
|
||||||
@@ -677,6 +710,27 @@ textarea { min-height: 80px; height: auto; resize: vertical; }
|
|||||||
height: 32px;
|
height: 32px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 产品表格内联日期选择器 */
|
||||||
|
.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 {
|
table {
|
||||||
border-collapse: collapse;
|
border-collapse: collapse;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
|||||||
@@ -29,29 +29,46 @@
|
|||||||
<div class="flex min-h-screen">
|
<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">
|
<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-6 cursor-pointer" onclick="document.getElementById('userAvatar').click()">
|
<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>
|
<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>
|
<span class="text-[10px] text-slate-400 mt-1.5 max-w-[64px] truncate text-center" id="userDisplayName" title=""></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="workspace-nav-item active" data-tenant="科普·无界" onclick="switchTenant('科普·无界')" title="科普·无界">
|
<!-- 分隔线 -->
|
||||||
<svg class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M8 12h8"/><path d="M12 8v8"/></svg>
|
<div class="w-8 h-px bg-slate-700 my-2"></div>
|
||||||
<span class="text-[10px] mt-1">科普</span>
|
<!-- 工作台切换按钮 -->
|
||||||
|
<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>
|
||||||
<div class="workspace-nav-item" data-tenant="科研·无界" onclick="switchTenant('科研·无界')" title="科研·无界">
|
<!-- 分隔线 -->
|
||||||
<svg class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>
|
<div class="w-8 h-px bg-slate-700 my-2"></div>
|
||||||
<span class="text-[10px] mt-1">科研</span>
|
<!-- 导航 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>
|
||||||
<div class="workspace-nav-item" data-tenant="医患·无界" onclick="switchTenant('医患·无界')" title="医患·无界">
|
<div class="sidebar-tab" data-tab="finance" onclick="switchTab('finance')" title="项目管理">
|
||||||
<svg class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>
|
<i data-lucide="folder-open-dot" style="width:20px;height:20px"></i>
|
||||||
<span class="text-[10px] mt-1">医患</span>
|
<span class="text-[10px] mt-1">项目</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="workspace-nav-item" data-tenant="MCN·无界" onclick="switchTenant('MCN·无界')" title="MCN·无界">
|
<div class="sidebar-tab" data-tab="expense" onclick="switchTab('expense')" title="费用管理">
|
||||||
<svg class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="7" width="20" height="15" rx="2"/><path d="M17 2l-5 5-5-5"/></svg>
|
<i data-lucide="receipt" style="width:20px;height:20px"></i>
|
||||||
<span class="text-[10px] mt-1">MCN</span>
|
<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>
|
||||||
<div class="workspace-nav-item" data-tenant="无界·无界" onclick="switchTenant('无界·无界')" title="无界·无界">
|
|
||||||
<svg class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M2 12h20"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
|
|
||||||
<span class="text-[10px] mt-1">无界</span>
|
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
<!-- 主内容区 -->
|
<!-- 主内容区 -->
|
||||||
@@ -67,49 +84,18 @@
|
|||||||
</div>
|
</div>
|
||||||
</header>
|
</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="finance"><i data-lucide="briefcase-business"></i>经营管理</button>
|
|
||||||
<button data-tab="projects"><i data-lucide="file-text"></i>重点工作与台账</button>
|
|
||||||
<button data-tab="proposals"><i data-lucide="package"></i>业务方案</button>
|
|
||||||
<button data-tab="products"><i data-lucide="wallet-cards"></i>产品迭代</button>
|
|
||||||
</nav>
|
|
||||||
|
|
||||||
<main class="px-8 py-6">
|
<main class="px-8 py-6">
|
||||||
<section id="home" class="panel active"></section>
|
<section id="home" class="panel active"></section>
|
||||||
<section id="projects" class="panel"></section>
|
<section id="projects" class="panel"></section>
|
||||||
<section id="proposals" class="panel"></section>
|
<section id="proposals" class="panel"></section>
|
||||||
<section id="products" class="panel"></section>
|
<section id="products" class="panel"></section>
|
||||||
<section id="finance" class="panel"></section>
|
<section id="finance" class="panel"></section>
|
||||||
|
<section id="expense" class="panel"></section>
|
||||||
</main>
|
</main>
|
||||||
</div><!-- 关闭主内容区 -->
|
</div><!-- 关闭主内容区 -->
|
||||||
</div><!-- 关闭 flex 容器 -->
|
</div><!-- 关闭 flex 容器 -->
|
||||||
<aside id="drawer" class="drawer" aria-hidden="true"></aside>
|
<aside id="drawer" class="drawer" aria-hidden="true"></aside>
|
||||||
<div id="taskModal" class="task-modal"></div>
|
<div id="taskModal" class="task-modal"></div>
|
||||||
<div id="transferModal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/40" onclick="closeTransferModal()">
|
|
||||||
<div class="bg-white rounded-2xl shadow-2xl w-full max-w-sm 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="closeTransferModal()"><i data-lucide="x"></i></button>
|
|
||||||
</div>
|
|
||||||
<form onsubmit="submitTransfer(event)" class="p-6 grid gap-4">
|
|
||||||
<input type="hidden" name="transfer_resource" id="transfer-resource" value="">
|
|
||||||
<input type="hidden" name="transfer_id" id="transfer-id" value="">
|
|
||||||
<p id="transfer-title-text" class="text-sm text-slate-600"></p>
|
|
||||||
<label class="block"><span class="text-xs font-medium text-slate-500">目标工作台</span>
|
|
||||||
<select name="transfer_tenant" class="form-ctrl mt-1">
|
|
||||||
<option value="科普·无界">科普·无界</option>
|
|
||||||
<option value="科研·无界">科研·无界</option>
|
|
||||||
<option value="医患·无界">医患·无界</option>
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
<div class="flex justify-end gap-3 pt-3">
|
|
||||||
<button type="button" class="btn btn-ghost btn-sm" onclick="closeTransferModal()">取消</button>
|
|
||||||
<button type="submit" class="btn btn-primary btn-sm">确认转移</button>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<!-- 新增项目模态框 -->
|
<!-- 新增项目模态框 -->
|
||||||
<div id="newProjectModal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/40" onclick="closeNewProjectModal()">
|
<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="bg-white rounded-2xl shadow-2xl w-full max-w-md mx-4" onclick="event.stopPropagation()">
|
||||||
@@ -133,6 +119,7 @@
|
|||||||
<script src="{{ url_for('static', filename='modules/proposals.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/products.js') }}"></script>
|
||||||
<script src="{{ url_for('static', filename='modules/finance.js') }}"></script>
|
<script src="{{ url_for('static', filename='modules/finance.js') }}"></script>
|
||||||
|
<script src="{{ url_for('static', filename='modules/expense.js') }}"></script>
|
||||||
<script src="{{ url_for('static', filename='modules/drawer.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='modules/admin.js') }}"></script>
|
||||||
<script src="{{ url_for('static', filename='app.js') }}"></script>
|
<script src="{{ url_for('static', filename='app.js') }}"></script>
|
||||||
|
|||||||
Reference in New Issue
Block a user