Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41f4ac1b1b | ||
|
|
4edd0b0473 | ||
|
|
a31d10f23f | ||
|
|
347c8aa818 | ||
|
|
e21d41b218 | ||
|
|
a57cba8043 | ||
|
|
fdb16d053a | ||
|
|
61ba9c4c5d | ||
|
|
eba4945fba | ||
|
|
2445dea4dd | ||
|
|
d2ea5d0d5d | ||
|
|
e233c294b0 | ||
|
|
6d30b8b891 | ||
|
|
666f35931c | ||
|
|
8196eb2802 | ||
|
|
1d79160dc2 | ||
|
|
3cb0abcf41 | ||
|
|
c3e0e9a496 | ||
|
|
b626de53ca | ||
|
|
6853b755b8 | ||
|
|
76da3a2106 | ||
|
|
e7e93c06f8 |
@@ -65,7 +65,7 @@ def monthly_finance(conn, tenant="科普·无界"):
|
||||
_year = date.today().year
|
||||
months = [f"{_year}-{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='已签约'",
|
||||
"SELECT sign_amount, sign_month, budget_data, expense_data FROM project_finances WHERE tenant=?",
|
||||
[tenant])
|
||||
|
||||
parsed_budgets = []
|
||||
@@ -104,7 +104,7 @@ def monthly_finance(conn, tenant="科普·无界"):
|
||||
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:
|
||||
if (pf.get("sign_month") or "") == month:
|
||||
sign += float(pf["sign_amount"] or 0)
|
||||
b = budget_map.get(key)
|
||||
if b:
|
||||
|
||||
@@ -17,7 +17,7 @@ def run_migrations():
|
||||
"""
|
||||
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_fixes import migrate_fix_task_status, migrate_rename_tenant, migrate_drop_product_fields, migrate_fix_service_fee_standard, migrate_fix_expense_status
|
||||
from migrations.data_split import migrate_data_split
|
||||
from migrations.seed import migrate_seed_users, migrate_seed_demo_data
|
||||
|
||||
@@ -27,6 +27,7 @@ def run_migrations():
|
||||
migrate_rename_tenant()
|
||||
migrate_drop_product_fields()
|
||||
migrate_fix_service_fee_standard()
|
||||
migrate_fix_expense_status()
|
||||
migrate_data_split()
|
||||
migrate_seed_users()
|
||||
migrate_seed_demo_data()
|
||||
|
||||
@@ -114,5 +114,30 @@ def migrate_add_columns():
|
||||
|
||||
conn.commit()
|
||||
print("[migrate] 加列迁移完成")
|
||||
|
||||
# plan_finances 新增字段
|
||||
_add_column_if_missing(conn, "plan_finances", "client_name",
|
||||
"ALTER TABLE plan_finances ADD COLUMN client_name VARCHAR(200) NOT NULL DEFAULT ''")
|
||||
_add_column_if_missing(conn, "plan_finances", "project_type",
|
||||
"ALTER TABLE plan_finances ADD COLUMN project_type VARCHAR(50) NOT NULL DEFAULT '待签约'")
|
||||
_add_column_if_missing(conn, "plan_finances", "weight",
|
||||
"ALTER TABLE plan_finances ADD COLUMN weight VARCHAR(10) NOT NULL DEFAULT '20%'")
|
||||
# 删除 plan_finances.status 列(计划模块不再需要状态字段)
|
||||
cur = conn.cursor()
|
||||
cur.execute("SHOW COLUMNS FROM plan_finances LIKE 'status'")
|
||||
if cur.fetchone():
|
||||
cur.execute("ALTER TABLE plan_finances DROP COLUMN status")
|
||||
conn.commit()
|
||||
print("[migrate] plan_finances.status 列已删除")
|
||||
# project_finances 新增客户名称字段
|
||||
_add_column_if_missing(conn, "project_finances", "client_name",
|
||||
"ALTER TABLE project_finances ADD COLUMN client_name VARCHAR(200) NOT NULL DEFAULT ''")
|
||||
# 删除 project_finances.status 列(实际模块不再需要状态字段)
|
||||
cur.execute("SHOW COLUMNS FROM project_finances LIKE 'status'")
|
||||
if cur.fetchone():
|
||||
cur.execute("ALTER TABLE project_finances DROP COLUMN status")
|
||||
conn.commit()
|
||||
print("[migrate] project_finances.status 列已删除")
|
||||
cur.close()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@@ -92,3 +92,25 @@ def migrate_fix_service_fee_standard():
|
||||
print(f"[migrate] project_finances: {affected} 条记录 service_fee_standard 修正为 5")
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def migrate_fix_expense_status():
|
||||
"""修正 expense_records 中空的 status 为默认值「计入费用」"""
|
||||
from db import db
|
||||
|
||||
conn = db()
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"UPDATE expense_records SET status='计入费用' "
|
||||
"WHERE status IS NULL OR status='' OR status='待审批'"
|
||||
)
|
||||
affected = cur.rowcount
|
||||
cur.close()
|
||||
if affected:
|
||||
conn.commit()
|
||||
print(f"[migrate] expense_records: {affected} 条记录 status 修正为 '计入费用'")
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ def make_budget_data(sign_amount, signed_month, status):
|
||||
"""生成12个月的预算数据"""
|
||||
months = []
|
||||
start_m = int(signed_month.split("-")[1]) if signed_month else 1
|
||||
rev_total = sign_amount if status == "已签约" else int(sign_amount * random.uniform(0.3, 0.7))
|
||||
rev_total = sign_amount
|
||||
gross_rate = random.uniform(0.25, 0.55)
|
||||
payment_rate = random.uniform(0.7, 0.95)
|
||||
|
||||
@@ -135,17 +135,17 @@ def seed_db():
|
||||
cust_idx += i % 3
|
||||
|
||||
# 70% 已签约, 30% 待签约
|
||||
status = "已签约" if random.random() < 0.7 else "待签约"
|
||||
sign_month = f"2026-{random.randint(1, 6):02d}" if status == "已签约" else ""
|
||||
status = "已签约"
|
||||
sign_month = f"2026-{random.randint(1, 6):02d}"
|
||||
project_code = f"{tenant[:2]}-2026-{i+1:03d}"
|
||||
business_type = random.choice(["学术推广", "医生教育", "患者管理", "科研合作", "科普内容"])
|
||||
|
||||
# 如果签约,总额 = 签约额;否则为0
|
||||
total_rev = int(sign_amount * random.uniform(0.8, 1.0)) if status == "已签约" else 0
|
||||
total_gross = int(total_rev * random.uniform(0.25, 0.5)) if status == "已签约" else 0
|
||||
total_payment = int(total_rev * random.uniform(0.7, 0.9)) if status == "已签约" else 0
|
||||
total_cost = int(total_rev * random.uniform(0.3, 0.5)) if status == "已签约" else 0
|
||||
total_paid = int(total_cost * random.uniform(0.7, 0.95)) if status == "已签约" else 0
|
||||
total_rev = int(sign_amount * random.uniform(0.8, 1.0))
|
||||
total_gross = int(total_rev * random.uniform(0.25, 0.5))
|
||||
total_payment = int(total_rev * random.uniform(0.7, 0.9))
|
||||
total_cost = int(total_rev * random.uniform(0.3, 0.5))
|
||||
total_paid = int(total_cost * random.uniform(0.7, 0.95))
|
||||
|
||||
budget_data = make_budget_data(sign_amount, sign_month, status)
|
||||
expense_data = make_expense_data() if status == "已签约" else "[]"
|
||||
@@ -157,16 +157,16 @@ def seed_db():
|
||||
|
||||
cur = _exec(conn, """
|
||||
INSERT INTO project_finances
|
||||
(tenant, project_id, business_type, customer_name, sign_amount, sign_month, status,
|
||||
(tenant, project_id, business_type, customer_name, sign_amount, sign_month,
|
||||
sales_person, total_rev, total_gross, total_payment, total_cost, total_paid,
|
||||
budget_data, expense_data, task_data,
|
||||
project_code, start_date, end_date, task_type, task_count,
|
||||
service_fee_standard, project_manager, contact_name, contact_phone, other_info,
|
||||
created_at, updated_at)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
""", (
|
||||
tenant, f"PF-{tenant[:2]}-{i+1:04d}", business_type, cust_name,
|
||||
sign_amount, sign_month, status,
|
||||
sign_amount, sign_month,
|
||||
f"销售{random.choice(['A','B','C','D'])}", total_rev, total_gross,
|
||||
total_payment, total_cost, total_paid,
|
||||
budget_data, expense_data, task_data,
|
||||
@@ -178,7 +178,7 @@ def seed_db():
|
||||
today, today,
|
||||
))
|
||||
# Store for later use
|
||||
pf_ids.setdefault(tenant, []).append((cur.lastrowid, proj_name, cust_name, status))
|
||||
pf_ids.setdefault(tenant, []).append((cur.lastrowid, proj_name, cust_name))
|
||||
|
||||
# operation_projects: 每个工作台 3-5 个
|
||||
op_count = random.randint(3, 5)
|
||||
|
||||
@@ -158,6 +158,8 @@ def migrate_create_tables():
|
||||
created_at VARCHAR(30) NOT NULL DEFAULT '',
|
||||
updated_at VARCHAR(30) NOT NULL DEFAULT ''
|
||||
)""",
|
||||
"""CREATE TABLE IF NOT EXISTS plan_finances LIKE project_finances""",
|
||||
"""CREATE TABLE IF NOT EXISTS plan_expense_records LIKE expense_records""",
|
||||
]
|
||||
|
||||
for ddl in tables:
|
||||
|
||||
@@ -23,8 +23,10 @@ TABLES = {
|
||||
"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"]),
|
||||
"projectFinances": ("project_finances", ["project_id", "tenant", "business_type", "customer_name", "client_name", "sign_amount", "sign_month", "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", "status", "tenant"]),
|
||||
"planFinances": ("plan_finances", ["project_id", "tenant", "business_type", "customer_name", "client_name", "sign_amount", "sign_month", "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", "client_name", "project_type", "weight"]),
|
||||
"planExpense": ("plan_expense_records", ["expense_type", "expense_month", "amount", "incurred_amount", "notes", "status", "tenant"]),
|
||||
}
|
||||
|
||||
# ---------- 鉴权装饰器 ----------
|
||||
@@ -92,6 +94,30 @@ def auth_logout():
|
||||
return jsonify({"ok": True})
|
||||
|
||||
|
||||
@bp.route("/api/auth/change-password", methods=["POST"])
|
||||
@login_required
|
||||
def auth_change_password():
|
||||
data = request.get_json(force=True) or {}
|
||||
old_password = data.get("old_password", "")
|
||||
new_password = data.get("new_password", "")
|
||||
if not old_password or not new_password:
|
||||
return jsonify({"error": "旧密码和新密码不能为空"}), 400
|
||||
if len(new_password) < 6:
|
||||
return jsonify({"error": "新密码至少需要6位"}), 400
|
||||
user_id = session.get("user_id")
|
||||
conn = db()
|
||||
try:
|
||||
user = one(conn, "SELECT * FROM users WHERE id=?", (user_id,))
|
||||
if not user or not check_password_hash(user["password_hash"], old_password):
|
||||
return jsonify({"error": "旧密码错误"}), 401
|
||||
new_hash = generate_password_hash(new_password)
|
||||
_exec(conn, "UPDATE users SET password_hash=? WHERE id=?", (new_hash, user_id))
|
||||
conn.commit()
|
||||
return jsonify({"ok": True})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@bp.route("/api/auth/me")
|
||||
def auth_me():
|
||||
if "user_id" not in session:
|
||||
@@ -250,7 +276,7 @@ def bootstrap():
|
||||
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"] == "已签约"]
|
||||
t_signed_pfs = t_pfs
|
||||
def t_parse_budget(pf):
|
||||
try:
|
||||
budget = json.loads(pf.get("budget_data") or "[]")
|
||||
@@ -300,12 +326,12 @@ def bootstrap():
|
||||
"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"{_year}-{_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"{_year}-{_prev_month:02d}") if _prev_month else 0,
|
||||
"signed_amount": sum(x["sign_amount"] or 0 for x in t_pfs),
|
||||
"signed_annual": sum(x["sign_amount"] or 0 for x in t_pfs),
|
||||
"signed_q2": sum(x["sign_amount"] or 0 for x in t_pfs if (x.get("sign_month") or "")[:7] in _q_months),
|
||||
"signed_month": sum(x["sign_amount"] or 0 for x in t_pfs if (x.get("sign_month") or "")[:7] == f"{_year}-{_now_month:02d}"),
|
||||
"signed_prev_q": sum(x["sign_amount"] or 0 for x in t_pfs if (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.get("sign_month") or "")[:7] == f"{_year}-{_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]),
|
||||
@@ -331,6 +357,7 @@ def bootstrap():
|
||||
def t_expense_sum(m_range):
|
||||
total = 0
|
||||
for r in t_expense:
|
||||
if (r.get("status") or "") == "暂不计入": continue
|
||||
m = (r.get("expense_month") or "").strip()
|
||||
if not m or "-" not in m: continue
|
||||
try:
|
||||
@@ -358,6 +385,27 @@ def bootstrap():
|
||||
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"]
|
||||
def t_expense_paid_sum(m_range):
|
||||
total = 0
|
||||
for r in t_expense:
|
||||
if (r.get("status") or "") == "暂不计入": continue
|
||||
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("incurred_amount") or 0)
|
||||
except: pass
|
||||
return total
|
||||
all_metrics[-1]["expense_paid_annual"] = t_expense_paid_sum(range(1, 13))
|
||||
all_metrics[-1]["expense_paid_q2"] = t_expense_paid_sum(_q_range)
|
||||
all_metrics[-1]["expense_paid_month"] = t_expense_paid_sum([_now_month])
|
||||
all_metrics[-1]["expense_paid_prev_q"] = t_expense_paid_sum(_prev_q_range)
|
||||
all_metrics[-1]["expense_paid_prev_month"] = t_expense_paid_sum([_prev_month]) if _prev_month else 0
|
||||
all_metrics[-1]["dept_cf_annual"] = all_metrics[-1]["cashflow_annual"] - all_metrics[-1]["expense_paid_annual"]
|
||||
all_metrics[-1]["dept_cf_q2"] = all_metrics[-1]["cashflow_q2"] - all_metrics[-1]["expense_paid_q2"]
|
||||
all_metrics[-1]["dept_cf_month"] = all_metrics[-1]["cashflow_month"] - all_metrics[-1]["expense_paid_month"]
|
||||
all_metrics[-1]["dept_cf_prev_q"] = all_metrics[-1]["cashflow_prev_q"] - all_metrics[-1]["expense_paid_prev_q"]
|
||||
all_metrics[-1]["dept_cf_prev_month"] = all_metrics[-1]["cashflow_prev_month"] - all_metrics[-1]["expense_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"]
|
||||
@@ -366,7 +414,7 @@ def bootstrap():
|
||||
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"]:
|
||||
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","expense_paid_annual","expense_paid_q2","expense_paid_month","expense_paid_prev_q","expense_paid_prev_month","dept_cf_annual","dept_cf_q2","dept_cf_month","dept_cf_prev_q","dept_cf_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):
|
||||
@@ -380,7 +428,7 @@ def bootstrap():
|
||||
"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})
|
||||
return jsonify({"summary": summary, "sales": [], "proposals": [], "operations": [], "products": [], "finance": [], "projectFinances": [], "financeMonthly": merged_monthly, "tasks": [], "expense": [], "planFinances": [], "planExpense": [], "tenant": tenant, "tenants": allowed})
|
||||
|
||||
def q(sql, *args):
|
||||
return rows(conn, sql, args)
|
||||
@@ -392,7 +440,9 @@ def bootstrap():
|
||||
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"] == "已签约"]
|
||||
planPfs = q("SELECT * FROM plan_finances WHERE tenant=? ORDER BY id DESC", tenant)
|
||||
planExpense = q("SELECT * FROM plan_expense_records WHERE tenant=? ORDER BY id DESC", tenant)
|
||||
signed_pfs = pfs
|
||||
|
||||
def parse_budget(pf):
|
||||
try:
|
||||
@@ -459,6 +509,7 @@ def bootstrap():
|
||||
def expense_sum(month_range):
|
||||
total = 0
|
||||
for r in expense:
|
||||
if (r.get("status") or "") == "暂不计入": continue
|
||||
m = (r.get("expense_month") or "").strip()
|
||||
if not m or "-" not in m: continue
|
||||
try:
|
||||
@@ -471,6 +522,22 @@ def bootstrap():
|
||||
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
|
||||
def expense_paid_sum(month_range):
|
||||
total = 0
|
||||
for r in expense:
|
||||
if (r.get("status") or "") == "暂不计入": continue
|
||||
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("incurred_amount") or 0)
|
||||
except: pass
|
||||
return total
|
||||
expense_paid_annual = expense_paid_sum(range(1, 13))
|
||||
expense_paid_q2 = expense_paid_sum(_q_range)
|
||||
expense_paid_month = expense_paid_sum([_now_month])
|
||||
expense_paid_prev_q = expense_paid_sum(_prev_q_range)
|
||||
expense_paid_prev_month = expense_paid_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])
|
||||
@@ -486,21 +553,24 @@ def bootstrap():
|
||||
cashflow_month = payment_month - paid_month
|
||||
cashflow_prev_q = payment_prev_q - paid_prev_q
|
||||
cashflow_prev_month = payment_prev_month - paid_prev_month
|
||||
dept_cf_annual = cashflow_annual - expense_paid_annual
|
||||
dept_cf_q2 = cashflow_q2 - expense_paid_q2
|
||||
dept_cf_month = cashflow_month - expense_paid_month
|
||||
dept_cf_prev_q = cashflow_prev_q - expense_paid_prev_q
|
||||
dept_cf_prev_month = cashflow_prev_month - expense_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"] == "已签约")
|
||||
signed_amount = sum(x["sign_amount"] or 0 for x in pfs)
|
||||
signed_annual = sum(x["sign_amount"] or 0 for x in pfs)
|
||||
_q_months = [f"{_year}-{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"{_year}-{_now_month:02d}")
|
||||
signed_q2 = sum(x["sign_amount"] or 0 for x in pfs if (x.get("sign_month") or "")[:7] in _q_months)
|
||||
signed_month = sum(x["sign_amount"] or 0 for x in pfs if (x.get("sign_month") or "")[:7] == f"{_year}-{_now_month:02d}")
|
||||
_prev_q_months = [f"{_year}-{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"{_year}-{_prev_month:02d}") if _prev_month else 0
|
||||
signed_prev_q = sum(x["sign_amount"] or 0 for x in pfs if (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.get("sign_month") or "")[:7] == f"{_year}-{_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 = {
|
||||
@@ -557,6 +627,16 @@ def bootstrap():
|
||||
"cashflow_month": cashflow_month,
|
||||
"cashflow_prev_q": cashflow_prev_q,
|
||||
"cashflow_prev_month": cashflow_prev_month,
|
||||
"expense_paid_annual": expense_paid_annual,
|
||||
"expense_paid_q2": expense_paid_q2,
|
||||
"expense_paid_month": expense_paid_month,
|
||||
"expense_paid_prev_q": expense_paid_prev_q,
|
||||
"expense_paid_prev_month": expense_paid_prev_month,
|
||||
"dept_cf_annual": dept_cf_annual,
|
||||
"dept_cf_q2": dept_cf_q2,
|
||||
"dept_cf_month": dept_cf_month,
|
||||
"dept_cf_prev_q": dept_cf_prev_q,
|
||||
"dept_cf_prev_month": dept_cf_prev_month,
|
||||
"profit_annual": profit_annual,
|
||||
"profit_q2": profit_q2,
|
||||
"profit_month": profit_month,
|
||||
@@ -572,7 +652,7 @@ def bootstrap():
|
||||
"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})
|
||||
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, "planFinances": planPfs, "planExpense": planExpense, "tenant": tenant, "tenants": allowed})
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@@ -166,3 +166,89 @@ window.deleteUser = async (uid, username) => {
|
||||
toast("删除失败:" + e.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
// 修改密码弹窗
|
||||
window.openChangePwdModal = () => {
|
||||
const overlay = document.createElement("div");
|
||||
overlay.id = "changePwdOverlay";
|
||||
overlay.className = "fixed inset-0 bg-black/40 z-[9999] flex items-center justify-center p-4";
|
||||
overlay.innerHTML = `
|
||||
<div class="bg-white rounded-xl shadow-2xl w-full max-w-sm">
|
||||
<div class="flex items-center justify-between px-6 py-4 border-b border-slate-200">
|
||||
<h2 class="text-lg font-semibold text-slate-800">修改密码</h2>
|
||||
<button class="text-slate-400 hover:text-slate-700" onclick="closeChangePwdModal()"><i data-lucide="x"></i></button>
|
||||
</div>
|
||||
<form class="p-6 grid gap-4" onsubmit="doChangePwd(event)" novalidate>
|
||||
<label class="block">
|
||||
<span class="text-sm text-slate-500 mb-1 block">旧密码</span>
|
||||
<div class="relative">
|
||||
<input type="password" name="old_password" required class="form-ctrl pr-10" placeholder="输入旧密码">
|
||||
<button type="button" class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-1" onclick="togglePwdEye(this)"><i data-lucide="eye-off" style="width:16px;height:16px"></i></button>
|
||||
</div>
|
||||
</label>
|
||||
<label class="block">
|
||||
<span class="text-sm text-slate-500 mb-1 block">新密码</span>
|
||||
<div class="relative">
|
||||
<input type="password" name="new_password" required minlength="6" class="form-ctrl pr-10" placeholder="至少6位">
|
||||
<button type="button" class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-1" onclick="togglePwdEye(this)"><i data-lucide="eye-off" style="width:16px;height:16px"></i></button>
|
||||
</div>
|
||||
</label>
|
||||
<label class="block">
|
||||
<span class="text-sm text-slate-500 mb-1 block">确认新密码</span>
|
||||
<div class="relative">
|
||||
<input type="password" name="confirm_password" required minlength="6" class="form-ctrl pr-10" placeholder="再次输入新密码">
|
||||
<button type="button" class="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600 p-1" onclick="togglePwdEye(this)"><i data-lucide="eye-off" style="width:16px;height:16px"></i></button>
|
||||
</div>
|
||||
</label>
|
||||
<div class="flex justify-end gap-3 pt-2">
|
||||
<button type="button" class="btn btn-ghost btn-sm px-6" onclick="closeChangePwdModal()">取消</button>
|
||||
<button type="submit" class="btn btn-primary btn-sm px-8">确认修改</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>`;
|
||||
overlay.addEventListener("click", (e) => { if (e.target === overlay) closeChangePwdModal(); });
|
||||
document.body.appendChild(overlay);
|
||||
if (window.lucide) lucide.createIcons();
|
||||
};
|
||||
|
||||
window.togglePwdEye = (btn) => {
|
||||
const input = btn.parentElement.querySelector("input");
|
||||
const icon = btn.querySelector("i");
|
||||
if (input.type === "password") {
|
||||
input.type = "text";
|
||||
icon.setAttribute("data-lucide", "eye");
|
||||
} else {
|
||||
input.type = "password";
|
||||
icon.setAttribute("data-lucide", "eye-off");
|
||||
}
|
||||
if (window.lucide) lucide.createIcons({ elements: [icon] });
|
||||
};
|
||||
|
||||
window.closeChangePwdModal = () => {
|
||||
const el = document.getElementById("changePwdOverlay");
|
||||
if (el) el.remove();
|
||||
};
|
||||
|
||||
window.doChangePwd = async (e) => {
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
const fd = new FormData(form);
|
||||
const oldPwd = fd.get("old_password");
|
||||
const newPwd = fd.get("new_password");
|
||||
const confirmPwd = fd.get("confirm_password");
|
||||
if (newPwd !== confirmPwd) { toast("两次输入的新密码不一致", "error"); return; }
|
||||
if (newPwd.length < 6) { toast("新密码至少需要6位", "error"); return; }
|
||||
try {
|
||||
const resp = await fetch("/api/auth/change-password", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ old_password: oldPwd, new_password: newPwd }),
|
||||
});
|
||||
const data = await resp.json();
|
||||
if (!resp.ok) { toast(data.error || "修改失败", "error"); return; }
|
||||
closeChangePwdModal();
|
||||
toast("密码修改成功", "success");
|
||||
} catch (err) {
|
||||
toast("请求失败:" + err.message, "error");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -24,8 +24,8 @@ function renderFinance() {
|
||||
const months = displayMonths.map(d => d.key);
|
||||
const monthLabels = displayMonths.map(d => d.label);
|
||||
|
||||
const signed = pfs.filter(x => x.status === "已签约");
|
||||
const pending = pfs.filter(x => x.status === "待签约");
|
||||
const signed = pfs;
|
||||
const pending = pfs;
|
||||
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));
|
||||
|
||||
@@ -98,29 +98,26 @@ function renderFinance() {
|
||||
})();
|
||||
const sm = pf.sign_month || "";
|
||||
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 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>`;
|
||||
return `<tr class="border-b border-slate-100 hover:bg-slate-50 cursor-pointer" onclick="openPfEditModal(${pf.id})"><td class="p-2 text-center align-middle text-sm">${esc(pf.client_name || "")}</td><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-sm text-slate-500 ml-2">月份:</span><select onchange="state.finMonth=this.value;renderFinance()" class="text-sm 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-sm text-slate-500 ml-2">季度:</span><select onchange="state.finQuarter=parseInt(this.value);localStorage.setItem(\'opc-fin-quarter\',this.value);renderFinance()" class="text-sm 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-sm text-slate-500">视图:</span><select onchange="setFinView(this.value)" class="text-sm 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>${toolDateSelect}`;
|
||||
const qLabels = ['Q1','Q2','Q3','Q4'];
|
||||
const qMonths = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]];
|
||||
const nowD = new Date();
|
||||
const activeQ = state.finQuarter !== undefined ? state.finQuarter : Math.floor(nowD.getMonth() / 3);
|
||||
const activeMonths = qMonths[activeQ];
|
||||
const finHeaderBase = `<div class="flex items-center gap-2"><button onclick="setFinView('overview')" class="px-3 py-1 rounded text-sm font-medium ${state.finView==='overview'?'bg-blue-600 text-white':'bg-slate-100 text-slate-600 hover:bg-slate-200'}">总视图</button><span class="text-slate-300 mx-2">|</span><span class="text-sm text-slate-500">按季度:</span>${qLabels.map((q,i) => `<button onclick="setFinQuarter(${i})" class="px-3 py-1 rounded text-sm font-medium ${state.finView==='quarterly'&&activeQ===i?'bg-blue-600 text-white':'bg-slate-100 text-slate-600 hover:bg-slate-200'}">${q}</button>`).join('')}<span class="text-slate-300 mx-2">|</span><span class="text-sm text-slate-500">按月度:</span>${activeMonths.map(m => { const ms = `2026-${String(m).padStart(2,'0')}`; return `<button onclick="setFinMonth('${ms}')" class="px-3 py-1 rounded text-sm font-medium ${state.finView==='monthly'&&state.finMonth===ms?'bg-blue-600 text-white':'bg-slate-100 text-slate-600 hover:bg-slate-200'}">${m}月</button>`; }).join('')}</div>`;
|
||||
const finAddBtn = `<button class="btn btn-primary btn-sm" onclick="openFinanceModal()">新增财务项目</button>`;
|
||||
|
||||
const finFilterTabs = `<div class="finance-tabs" style="padding:0;border-bottom:1px solid #e2e8f0;margin-bottom:0"><button onclick="switchFinFilter('已签约')" class="finance-tab${state.finFilter==='已签约'?' active':''}" style="font-size:14px;font-weight:600">已签约 (${pfs.filter(x=>x.status==='已签约').length})</button><button onclick="switchFinFilter('待签约')" class="finance-tab${state.finFilter==='待签约'?' active':''}" style="font-size:14px;font-weight:600">待签约 (${pfs.filter(x=>x.status==='待签约').length})</button><button onclick="switchFinFilter('expense')" class="finance-tab${state.finFilter==='expense'?' active':''}" style="font-size:14px;font-weight:600">平台费用</button></div>`;
|
||||
const finFilterTabs = `<div class="finance-tabs" style="padding:0;border-bottom:1px solid #e2e8f0;margin-bottom:0"><button onclick="switchFinFilter('overview')" class="finance-tab${state.finFilter==='overview'?' active':''}" style="font-size:14px;font-weight:600">月度总览</button><button onclick="switchFinFilter('quarterlyOverview')" class="finance-tab${state.finFilter==='quarterlyOverview'?' active':''}" style="font-size:14px;font-weight:600">季度总览</button><button onclick="switchFinFilter('projects')" class="finance-tab${state.finFilter==='projects'?' active':''}" style="font-size:14px;font-weight:600">项目 (${pfs.length})</button><button onclick="switchFinFilter('expense')" class="finance-tab${state.finFilter==='expense'?' active':''}" style="font-size:14px;font-weight:600">平台费用</button></div>`;
|
||||
|
||||
document.querySelector("#finance").innerHTML = `<div class="grid gap-4">
|
||||
${finFilterTabs}
|
||||
${state.finFilter !== 'expense' ? card(`<div class="flex justify-between items-center"><div class="flex items-center gap-2">${finHeaderBase}</div>${finAddBtn}</div>`, "p-4") : ''}
|
||||
${state.finFilter !== 'expense' && state.finFilter !== 'overview' && state.finFilter !== 'quarterlyOverview' ? card(`<div class="flex justify-between items-center"><div class="flex items-center gap-2">${finHeaderBase}</div>${finAddBtn}</div>`, "p-4") : ''}
|
||||
<div id="financeModal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/40" onclick="closeFinanceModal()"><div class="bg-white rounded-2xl shadow-2xl w-full max-w-6xl mx-4 max-h-[92vh] overflow-y-auto" onclick="event.stopPropagation()"><div class="sticky top-0 z-10 bg-white/95 backdrop-blur border-b border-slate-100 px-8 py-5 flex items-center justify-between"><div><h3 class="text-xl font-bold text-slate-800" id="financeModalTitle">新增项目财务</h3><p class="text-xs text-slate-400 mt-0.5">填写项目财务信息与月度预算</p></div><div class="flex items-center gap-2"><button class="btn btn-ghost btn-sm text-red-600 hidden" id="financeDeleteBtn" onclick="deleteFinanceItem()"><i data-lucide="trash-2"></i>删除</button><button class="btn btn-ghost btn-sm rounded-full w-8 h-8 p-0" onclick="closeFinanceModal()"><i data-lucide="x"></i></button></div></div>
|
||||
<div class="finance-tabs">
|
||||
<button class="finance-tab active" data-tab="info" onclick="switchFinanceTab('info')"><i data-lucide="info" style="width:14px;height:14px;display:inline-block;vertical-align:-2px;margin-right:4px"></i>基本信息</button>
|
||||
@@ -137,12 +134,12 @@ function renderFinance() {
|
||||
<div class="grid grid-cols-3 gap-3">
|
||||
<label class="block"><span class="fin-label">部门</span><input type="hidden" name="project_id" value="${state.tenant}"><input class="form-ctrl bg-slate-50 cursor-not-allowed" value="${state.tenant}" disabled></label>
|
||||
<label class="block"><span class="fin-label">项目编号</span><input name="project_code" class="form-ctrl" placeholder="如:KP-2026-001"></label>
|
||||
<label class="block"><span class="fin-label">项目名称 <span class="text-red-500">*</span></span><input name="customer_name" required class="form-ctrl" placeholder="请输入项目名称"></label>
|
||||
<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><input name="client_name" class="form-ctrl" placeholder="客户名称"></label>
|
||||
</div>
|
||||
<div class="grid grid-cols-3 gap-3">
|
||||
<label class="block"><span class="fin-label">签约金额(元) <span class="text-red-500">*</span></span><input name="sign_amount" class="form-ctrl" placeholder="必须大于 0"></label>
|
||||
<label class="block"><span class="fin-label">签约月份 <span class="text-red-500">*</span></span><select name="sign_month" required class="form-ctrl bg-white"><option value="">选择</option>${monthOptions('')}</select></label>
|
||||
<label class="block"><span class="fin-label">项目状态</span><select name="status" class="form-ctrl bg-white"><option>已签约</option><option>待签约</option></select></label>
|
||||
|
||||
</div>
|
||||
<div class="grid grid-cols-3 gap-3">
|
||||
<label class="block"><span class="fin-label">商务负责人 <span class="text-red-500">*</span></span><input name="sales_person" required class="form-ctrl" placeholder="请输入商务负责人"></label>
|
||||
@@ -237,11 +234,19 @@ function renderFinance() {
|
||||
</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>
|
||||
${(() => {
|
||||
if (state.finFilter === 'overview') {
|
||||
setTimeout(() => renderFinanceOverview(), 10);
|
||||
return `<div id="financeOverview"></div>`;
|
||||
}
|
||||
if (state.finFilter === 'quarterlyOverview') {
|
||||
setTimeout(() => renderFinanceQuarterlyOverview(), 10);
|
||||
return `<div id="financeQuarterlyOverview"></div>`;
|
||||
}
|
||||
if (state.finFilter === 'expense') {
|
||||
setTimeout(() => renderExpense(), 10);
|
||||
return `<div id="financeExpense"></div>`;
|
||||
}
|
||||
const isUnsigned = state.finFilter === '待签约';
|
||||
const isUnsigned = false;
|
||||
const METRIC_CARDS = [
|
||||
{ label: '签约金额', value: ctx => moneyWan(ctx.signTotal), color: 'text-slate-700' },
|
||||
{ label: '已确收', hideUnsigned: true, value: ctx => moneyWan(ctx.sumRev), color: 'text-blue-700' },
|
||||
@@ -255,7 +260,43 @@ function renderFinance() {
|
||||
{ label: '毛利率', hideUnsigned: true, value: ctx => ctx.sumRev && ctx.sumGross ? Math.round(ctx.sumGross / ctx.sumRev * 100) + '%' : '—', color: 'text-slate-500' },
|
||||
{ label: '回款率', hideUnsigned: true, value: ctx => ctx.sumRev && ctx.sumPay ? Math.round(ctx.sumPay / ctx.sumRev * 100) + '%' : '—', color: 'text-slate-500' },
|
||||
{ label: '付款率', hideUnsigned: true, value: ctx => ctx.sumCost && ctx.sumPaid ? Math.round(ctx.sumPaid / ctx.sumCost * 100) + '%' : '—', color: 'text-slate-500' },
|
||||
].filter(c => state.finFilter !== '待签约' || !c.hideUnsigned);
|
||||
].filter(c => true);
|
||||
|
||||
// 列排序
|
||||
if (!state.finSort) state.finSort = { key: null, asc: true };
|
||||
const sortData = (data, key) => {
|
||||
if (!key || !state.finSort.key) return data;
|
||||
var asc = state.finSort.asc ? 1 : -1;
|
||||
return data.slice().sort(function(a, b) {
|
||||
var va = a[key], vb = b[key];
|
||||
if (typeof va === 'string') va = va || '', vb = vb || '';
|
||||
else { va = parseFloat(va) || 0; vb = parseFloat(vb) || 0; }
|
||||
if (va < vb) return -1 * asc;
|
||||
if (va > vb) return 1 * asc;
|
||||
return 0;
|
||||
});
|
||||
};
|
||||
const buildThead = (cols, sortKey) => {
|
||||
var h = '<thead><tr class="bg-slate-50 border-b border-slate-200">';
|
||||
cols.forEach(function(c) {
|
||||
var arrow = sortKey ? (sortKey === c.key ? (state.finSort.asc ? ' ↑' : ' ↓') : '') : '';
|
||||
h += '<th class="p-2 text-center font-semibold align-middle cursor-pointer select-none" onclick="setFinSort(\'' + sortKey + '|' + c.key + '\')">' + c.label + arrow + '</th>';
|
||||
});
|
||||
h += '</tr></thead>';
|
||||
return h;
|
||||
};
|
||||
const SIGNED_COLS = [
|
||||
{ key: 'customer_name', label: '项目名称' }, { key: 'sign_amount', label: '签约金额' },
|
||||
{ key: 'rev', label: '已确收' }, { key: 'gross', label: '毛利' }, { key: 'cost', label: '成本' },
|
||||
{ key: 'profit', label: '项目利润' }, { key: 'payment', label: '已回款' }, { key: 'paid', label: '已付' },
|
||||
{ key: 'cashflow', label: '现金流' }, { key: 'exe_rate', label: '执行率' }, { key: 'gross_rate', label: '毛利率' },
|
||||
{ key: 'pay_rate', label: '回款率' }, { key: 'paid_rate', label: '付款率' },
|
||||
];
|
||||
const UNSIGNED_COLS = [
|
||||
{ key: 'customer_name', label: '项目名称' }, { key: 'sign_amount', label: '签约金额' },
|
||||
{ key: 'sign_month', label: '签约月份' }, { key: 'gross', label: '毛利' }, { key: 'cost', label: '成本' },
|
||||
{ key: 'profit', label: '项目利润' },
|
||||
];
|
||||
|
||||
const renderView = (rows, sumRev, sumPay, sumCost, sumPaid, sumGross, signTotal, signCnt, emptyText) => {
|
||||
const ctx = { sumRev, sumPay, sumCost, sumPaid, sumGross, signTotal, signCnt };
|
||||
@@ -263,33 +304,8 @@ function renderFinance() {
|
||||
const v = c.value(ctx);
|
||||
return typeof v === 'object' ? [c.label, v.val, v.cls] : [c.label, v, c.color];
|
||||
});
|
||||
const thead = isUnsigned
|
||||
? '<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">签约月份</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>' +
|
||||
'</tr></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 theadCols = isUnsigned ? 7 : 14;
|
||||
const thead = isUnsigned ? buildThead(UNSIGNED_COLS, 'uns') : buildThead(SIGNED_COLS, 'sig');
|
||||
const theadCols = isUnsigned ? 6 : 13;
|
||||
const tbody = rows.length ? `<tbody>${rows.join("")}</tbody>` : `<tr><td colspan="${theadCols}" class="p-6 text-center text-slate-400">${emptyText}</td></tr>`;
|
||||
|
||||
const cardGrid = isUnsigned ? 'grid-cols-4' : 'grid-cols-6';
|
||||
@@ -309,31 +325,28 @@ function renderFinance() {
|
||||
const payR = payRVal !== null ? '<span class="' + payRCls + ' font-semibold">' + payRVal + '%</span>' : '<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 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>`;
|
||||
return `<tr class="border-b border-slate-100 hover:bg-slate-50 cursor-pointer" onclick="openPfEditModal(${pf.id})"><td class="p-2 text-center align-middle text-sm">${esc(pf.client_name || "")}</td><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 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>`;
|
||||
};
|
||||
// 待签约简版行
|
||||
const tdRowUnsigned = (pf, cost, gross) => {
|
||||
const st = pf.status === '待签约' ? '<span class="text-amber-600">待签约</span>' : '<span class="text-green-600">已签约</span>';
|
||||
const profit = gross;
|
||||
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 align-middle text-sm">${pf.sign_month || '—'}</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></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 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 font-medium">${money(pf.sign_amount)}</td><td class="p-2 text-center align-middle text-sm">${pf.sign_month || '—'}</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></tr>`;
|
||||
};
|
||||
|
||||
if (state.finView === 'monthly') {
|
||||
const allPfs = pfs.filter(x => x.status === state.finFilter);
|
||||
const allPfs = pfs;
|
||||
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;
|
||||
var dataItems = [];
|
||||
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) {}
|
||||
@@ -345,16 +358,31 @@ function renderFinance() {
|
||||
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(isUnsigned ? tdRowUnsigned(pf, cost, gross) : tdRow(pf, rev, payment, cost, paid, gross));
|
||||
dataItems.push({
|
||||
pf: pf, customer_name: pf.customer_name || '', sign_amount: pf.sign_amount || 0, sign_month: pf.sign_month || '',
|
||||
rev: rev, gross: gross, cost: cost, profit: gross, payment: payment, paid: paid,
|
||||
cashflow: payment - paid,
|
||||
exe_rate: rev && pf.sign_amount ? Math.round(rev / pf.sign_amount * 100) : 0,
|
||||
gross_rate: rev && gross ? Math.round(gross / rev * 100) : 0,
|
||||
pay_rate: rev && payment ? Math.round(payment / rev * 100) : 0,
|
||||
paid_rate: cost && paid ? Math.round(paid / cost * 100) : 0,
|
||||
});
|
||||
});
|
||||
var sortK = state.finSort && state.finSort.key ? state.finSort.key.split('|')[1] : null;
|
||||
dataItems = sortData(dataItems, sortK);
|
||||
const rows = [];
|
||||
let sumRev = 0, sumPay = 0, sumCost = 0, sumPaid = 0, sumGross = 0;
|
||||
dataItems.forEach(d => {
|
||||
sumRev += d.rev; sumPay += d.payment; sumCost += d.cost; sumPaid += d.paid; sumGross += d.gross;
|
||||
rows.push(isUnsigned ? tdRowUnsigned(d.pf, d.cost, d.gross) : tdRow(d.pf, d.rev, d.payment, d.cost, d.paid, d.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;
|
||||
const signCnt = allPfs.filter(x => (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 allPfs = pfs;
|
||||
const qRanges = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]];
|
||||
const now = new Date();
|
||||
if (state.finQuarter === undefined) {
|
||||
@@ -373,8 +401,7 @@ function renderFinance() {
|
||||
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 = [];
|
||||
var dataItems = [];
|
||||
allPfs.forEach(pf => {
|
||||
const rev = sumBudget(pf, "rev");
|
||||
const payment = sumBudget(pf, "payment");
|
||||
@@ -382,11 +409,26 @@ function renderFinance() {
|
||||
const cost = sumExpense(pf, "cost");
|
||||
const paid = sumExpense(pf, "paid");
|
||||
if (!rev && !payment && !cost && !paid && !gross) return;
|
||||
sumRev += rev; sumPay += payment; sumCost += cost; sumPaid += paid; sumGross += gross;
|
||||
rows.push(isUnsigned ? tdRowUnsigned(pf, cost, gross) : tdRow(pf, rev, payment, cost, paid, gross));
|
||||
dataItems.push({
|
||||
pf: pf, customer_name: pf.customer_name || '', sign_amount: pf.sign_amount || 0, sign_month: pf.sign_month || '',
|
||||
rev: rev, gross: gross, cost: cost, profit: gross, payment: payment, paid: paid,
|
||||
cashflow: payment - paid,
|
||||
exe_rate: rev && pf.sign_amount ? Math.round(rev / pf.sign_amount * 100) : 0,
|
||||
gross_rate: rev && gross ? Math.round(gross / rev * 100) : 0,
|
||||
pay_rate: rev && payment ? Math.round(payment / rev * 100) : 0,
|
||||
paid_rate: cost && paid ? Math.round(paid / cost * 100) : 0,
|
||||
});
|
||||
});
|
||||
var sortK = state.finSort && state.finSort.key ? state.finSort.key.split('|')[1] : null;
|
||||
dataItems = sortData(dataItems, sortK);
|
||||
let sumRev = 0, sumPay = 0, sumCost = 0, sumPaid = 0, sumGross = 0;
|
||||
const rows = [];
|
||||
dataItems.forEach(d => {
|
||||
sumRev += d.rev; sumPay += d.payment; sumCost += d.cost; sumPaid += d.paid; sumGross += d.gross;
|
||||
rows.push(isUnsigned ? tdRowUnsigned(d.pf, d.cost, d.gross) : tdRow(d.pf, d.rev, d.payment, d.cost, d.paid, d.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;
|
||||
const signCnt = allPfs.filter(x => qRange.includes(parseInt((x.sign_month || "0").substring(5)) || 0)).length;
|
||||
return renderView(rows, sumRev, sumPay, sumCost, sumPaid, sumGross, signTotal, signCnt, '该季度暂无数据');
|
||||
}
|
||||
|
||||
@@ -400,16 +442,29 @@ function renderFinance() {
|
||||
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);
|
||||
const allPfs = pfs;
|
||||
var dataItems = allPfs.map(pf => {
|
||||
var t = calcTotals(pf);
|
||||
return {
|
||||
pf: pf, customer_name: pf.customer_name || '', sign_amount: pf.sign_amount || 0, sign_month: pf.sign_month || '',
|
||||
rev: t.rev, gross: t.gross, cost: t.cost, profit: t.gross,
|
||||
payment: t.payment, paid: t.paid, cashflow: t.payment - t.paid,
|
||||
exe_rate: t.rev && pf.sign_amount ? Math.round(t.rev / pf.sign_amount * 100) : 0,
|
||||
gross_rate: t.rev && t.gross ? Math.round(t.gross / t.rev * 100) : 0,
|
||||
pay_rate: t.rev && t.payment ? Math.round(t.payment / t.rev * 100) : 0,
|
||||
paid_rate: t.cost && t.paid ? Math.round(t.paid / t.cost * 100) : 0,
|
||||
};
|
||||
});
|
||||
var sortK = state.finSort && state.finSort.key ? state.finSort.key.split('|')[1] : null;
|
||||
dataItems = sortData(dataItems, sortK);
|
||||
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(isUnsigned ? tdRowUnsigned(pf, t.cost, t.gross) : tdRow(pf, t.rev, t.payment, t.cost, t.paid, t.gross));
|
||||
dataItems.forEach(d => {
|
||||
sumRev += d.rev; sumPay += d.payment; sumCost += d.cost; sumPaid += d.paid; sumGross += d.gross;
|
||||
rows.push(isUnsigned ? tdRowUnsigned(d.pf, d.cost, d.gross) : tdRow(d.pf, d.rev, d.payment, d.cost, d.paid, d.gross));
|
||||
});
|
||||
const signTotal = Math.round(allPfs.reduce((a, p) => a + (p.sign_amount || 0), 0));
|
||||
const signCnt = allPfs.filter(x => x.status === "已签约").length;
|
||||
const signCnt = allPfs.length;
|
||||
return renderView(rows, sumRev, sumPay, sumCost, sumPaid, sumGross, signTotal, signCnt, '暂无数据');
|
||||
})()}
|
||||
</div>`;
|
||||
@@ -721,6 +776,7 @@ window.openPfEditModal = (pfId) => {
|
||||
}
|
||||
});
|
||||
form.querySelector('[name="customer_name"]').value = pf.customer_name || "";
|
||||
const clientInput = form.querySelector('[name="client_name"]'); if (clientInput) clientInput.value = pf.client_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 || "";
|
||||
@@ -730,7 +786,6 @@ window.openPfEditModal = (pfId) => {
|
||||
signMonthEl.innerHTML = monthOptions(signMonthValue);
|
||||
signMonthEl.value = signMonthValue;
|
||||
}
|
||||
form.querySelector('[name="status"]').value = pf.status || "待签约";
|
||||
form.querySelector('[name="sales_person"]').value = pf.sales_person || "";
|
||||
form.querySelector('[name="owner"]').value = pf.owner || "";
|
||||
setVal("start_date", pf.start_date);
|
||||
@@ -876,4 +931,137 @@ window.deleteFinanceItem = async () => {
|
||||
} catch (error) {
|
||||
toast("删除失败:" + error.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
// 月度总览渲染
|
||||
function renderFinanceOverview() {
|
||||
const { summary, financeMonthly } = state.data;
|
||||
if (!summary) return;
|
||||
const m = summary.metrics;
|
||||
const moneyIntL = (v) => Math.round(Number(v || 0)).toLocaleString("zh-CN");
|
||||
const moneyWan = (v) => { const n = Number(v || 0); return n >= 10000 ? (n / 10000).toFixed(0) + "万" : n.toLocaleString("zh-CN"); };
|
||||
const card = (body, cls) => '<div class="card ' + (cls || 'p-4') + '">' + body + '</div>';
|
||||
const fm = financeMonthly || [];
|
||||
const mLbl = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'];
|
||||
const LABELS = ['合同金额','确收金额','确收毛利','成本','项目利润','回款金额','已付','现金流'];
|
||||
const annualVals = [m.signed_annual||m.signed_amount||0, m.revenue_annual||0, m.gross_annual||0, m.cost_annual||0, m.profit_annual||0, m.payment_annual||0, m.paid_annual||0, m.cashflow_annual||0];
|
||||
const fmFields = ['sign','revenue','gross','cost',null,'payment','paid',null];
|
||||
var thead = '<tr class="border-b border-slate-200"><th class="py-2 text-left text-slate-500 whitespace-nowrap">指标</th><th class="py-2 text-right font-semibold text-slate-700 whitespace-nowrap">年度累计</th>';
|
||||
for (var mi = 0; mi < 12; mi++) { thead += '<th class="py-2 text-right font-semibold text-slate-600 whitespace-nowrap">' + mLbl[mi] + '</th>'; }
|
||||
thead += '</tr>';
|
||||
var tbody = '';
|
||||
for (var ri = 0; ri < 8; ri++) {
|
||||
var rowHtml = '<tr class="border-b border-slate-100 last:border-0"><td class="py-2 text-left font-semibold text-slate-700 whitespace-nowrap">' + LABELS[ri] + '</td>';
|
||||
rowHtml += '<td class="py-2 text-right font-semibold text-slate-800 whitespace-nowrap">' + moneyIntL(annualVals[ri]) + '</td>';
|
||||
for (var mi = 0; mi < 12; mi++) {
|
||||
var val = 0;
|
||||
if (fm[mi]) {
|
||||
if (ri === 4) { val = (fm[mi].gross || 0) - (fm[mi].cost || 0); }
|
||||
else if (ri === 7) { val = (fm[mi].payment || 0) - (fm[mi].paid || 0); }
|
||||
else { var fk = fmFields[ri]; if (fk) val = fm[mi][fk] || 0; }
|
||||
}
|
||||
var cls = 'text-slate-700';
|
||||
if (ri === 4) cls = val >= 0 ? 'text-green-600' : 'text-red-600';
|
||||
if (ri === 7) cls = val >= 0 ? 'text-green-600' : 'text-red-600';
|
||||
rowHtml += '<td class="py-2 text-right text-sm whitespace-nowrap ' + cls + '">' + moneyIntL(val) + '</td>';
|
||||
}
|
||||
tbody += rowHtml + '</tr>';
|
||||
}
|
||||
|
||||
document.querySelector("#financeOverview").innerHTML = '<div class="grid gap-5">' +
|
||||
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="finChartSign"></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="finChartRev"></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="finChartCash"></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="finChartProfit"></canvas></div>', 'p-4') +
|
||||
'</div></div>';
|
||||
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
if (financeMonthly && window.Chart) {
|
||||
renderOverviewCharts(financeMonthly);
|
||||
}
|
||||
}
|
||||
|
||||
// 季度总览渲染
|
||||
function renderFinanceQuarterlyOverview() {
|
||||
const { summary, financeMonthly } = state.data;
|
||||
if (!summary) return;
|
||||
const m = summary.metrics;
|
||||
const moneyIntL = (v) => Math.round(Number(v || 0)).toLocaleString("zh-CN");
|
||||
const card = (body, cls) => '<div class="card ' + (cls || 'p-4') + '">' + body + '</div>';
|
||||
const fm = financeMonthly || [];
|
||||
const LABELS = ['合同金额','确收金额','确收毛利','成本','项目利润','回款金额','已付','现金流'];
|
||||
const qLbl = ['Q1','Q2','Q3','Q4'];
|
||||
const qRanges = [[0,1,2],[3,4,5],[6,7,8],[9,10,11]];
|
||||
const annualVals = [m.signed_annual||m.signed_amount||0, m.revenue_annual||0, m.gross_annual||0, m.cost_annual||0, m.profit_annual||0, m.payment_annual||0, m.paid_annual||0, m.cashflow_annual||0];
|
||||
const fmFields = ['sign','revenue','gross','cost',null,'payment','paid',null];
|
||||
var qData = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]];
|
||||
for (var qi = 0; qi < 4; qi++) {
|
||||
for (var ri = 0; ri < 8; ri++) {
|
||||
var sum = 0;
|
||||
for (var mi = 0; mi < 3; mi++) {
|
||||
var idx = qRanges[qi][mi];
|
||||
if (fm[idx]) {
|
||||
if (ri === 4) { sum += (fm[idx].gross||0) - (fm[idx].cost||0); }
|
||||
else if (ri === 7) { sum += (fm[idx].payment||0) - (fm[idx].paid||0); }
|
||||
else { var fk = fmFields[ri]; if (fk) sum += fm[idx][fk] || 0; }
|
||||
}
|
||||
}
|
||||
qData[ri][qi] = sum;
|
||||
}
|
||||
}
|
||||
var thead = '<tr class="border-b border-slate-200"><th class="py-2 text-left text-slate-500 whitespace-nowrap">指标</th><th class="py-2 text-right font-semibold text-slate-700 whitespace-nowrap">年度累计</th>';
|
||||
thead += '<th class="py-2 text-right font-semibold text-slate-600 whitespace-nowrap">Q1</th>';
|
||||
thead += '<th class="py-2 text-right font-semibold text-slate-600 whitespace-nowrap">Q2</th><th class="py-2 text-right font-semibold text-slate-400 whitespace-nowrap">环比</th>';
|
||||
thead += '<th class="py-2 text-right font-semibold text-slate-600 whitespace-nowrap">Q3</th><th class="py-2 text-right font-semibold text-slate-400 whitespace-nowrap">环比</th>';
|
||||
thead += '<th class="py-2 text-right font-semibold text-slate-600 whitespace-nowrap">Q4</th><th class="py-2 text-right font-semibold text-slate-400 whitespace-nowrap">环比</th>';
|
||||
thead += '</tr>';
|
||||
var qoq = function(cur, prev) { if (!prev) return '<span class="text-slate-300">—</span>'; var pct = Math.round((cur - prev) / prev * 100); var cls = pct >= 0 ? 'text-green-600' : 'text-red-600'; var sign = pct >= 0 ? '+' : ''; return '<span class="' + cls + '">' + sign + pct + '%</span>'; };
|
||||
var tbody = '';
|
||||
for (var ri = 0; ri < 8; ri++) {
|
||||
var rowHtml = '<tr class="border-b border-slate-100 last:border-0"><td class="py-2 text-left font-semibold text-slate-700 whitespace-nowrap">' + LABELS[ri] + '</td>';
|
||||
rowHtml += '<td class="py-2 text-right font-semibold text-slate-800 whitespace-nowrap">' + moneyIntL(annualVals[ri]) + '</td>';
|
||||
for (var qi = 0; qi < 4; qi++) {
|
||||
var val = qData[ri][qi];
|
||||
var cls = 'text-slate-700';
|
||||
if (ri === 4) cls = val >= 0 ? 'text-green-600' : 'text-red-600';
|
||||
if (ri === 7) cls = val >= 0 ? 'text-green-600' : 'text-red-600';
|
||||
rowHtml += '<td class="py-2 text-right text-sm whitespace-nowrap ' + cls + '">' + moneyIntL(val) + '</td>';
|
||||
if (qi > 0) { rowHtml += '<td class="py-2 text-right text-sm whitespace-nowrap">' + qoq(val, qData[ri][qi - 1]) + '</td>'; }
|
||||
}
|
||||
tbody += rowHtml + '</tr>';
|
||||
}
|
||||
document.querySelector("#financeQuarterlyOverview").innerHTML = '<div class="grid gap-5">' +
|
||||
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>';
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
|
||||
function renderOverviewCharts(data) {
|
||||
if (typeof monthLabels !== 'function') return;
|
||||
const labels = monthLabels(data);
|
||||
const baseOpts = typeof chartOptions === 'function' ? chartOptions(moneyTick) : { responsive: true, maintainAspectRatio: false };
|
||||
var iconf = { type: "line", options: baseOpts, data: { labels: labels } };
|
||||
|
||||
var c1 = document.querySelector("#finChartSign");
|
||||
if (c1 && window.Chart) {
|
||||
if (state.finChart1) state.finChart1.destroy();
|
||||
state.finChart1 = new Chart(c1, Object.assign({}, iconf, { data: { labels: labels, datasets: [{ label: "签约金额", data: data.map(function(x) { return x.sign || 0; }), borderColor: "#6366f1", backgroundColor: "rgba(99,102,241,0.06)", fill: true, tension: 0.3 }] } }));
|
||||
}
|
||||
var c2 = document.querySelector("#finChartRev");
|
||||
if (c2 && window.Chart) {
|
||||
if (state.finChart2) state.finChart2.destroy();
|
||||
state.finChart2 = new Chart(c2, Object.assign({}, iconf, { data: { labels: labels, datasets: [{ label: "确收", data: data.map(function(x) { return x.revenue || 0; }), borderColor: "#2563eb", backgroundColor: "rgba(37,99,235,0.06)", fill: true, tension: 0.3 }, { label: "毛利", data: data.map(function(x) { return x.gross || 0; }), borderColor: "#059669", backgroundColor: "rgba(5,150,105,0.06)", fill: true, tension: 0.3 }] } }));
|
||||
}
|
||||
var c3 = document.querySelector("#finChartCash");
|
||||
if (c3 && window.Chart) {
|
||||
if (state.finChart3) state.finChart3.destroy();
|
||||
state.finChart3 = new Chart(c3, Object.assign({}, iconf, { data: { labels: labels, datasets: [{ label: "回款", data: data.map(function(x) { return x.payment || 0; }), borderColor: "#d97706", backgroundColor: "rgba(217,119,6,0.06)", fill: true, tension: 0.3 }, { label: "已付", data: data.map(function(x) { return x.cost || 0; }), borderColor: "#7c3aed", backgroundColor: "rgba(124,58,237,0.06)", fill: true, tension: 0.3 }] } }));
|
||||
}
|
||||
var c4 = document.querySelector("#finChartProfit");
|
||||
if (c4 && window.Chart) {
|
||||
if (state.finChart4) state.finChart4.destroy();
|
||||
state.finChart4 = new Chart(c4, Object.assign({}, iconf, { data: { labels: labels, datasets: [{ label: "利润", data: data.map(function(x) { return x.gross || 0; }), borderColor: "#6366f1", backgroundColor: "rgba(99,102,241,0.06)", fill: true, tension: 0.3 }] } }));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -7,11 +7,14 @@ function renderHome() {
|
||||
// 回款提醒
|
||||
const yrRev = m.revenue_annual || 0, yrPay = m.payment_annual || 0, yrUnpaid = yrRev - yrPay;
|
||||
const yrPayRate = yrRev > 0 ? Math.round(yrPay / yrRev * 100) : 0;
|
||||
const yrUnpaidWan = Math.round(yrUnpaid / 10000);
|
||||
const yrUnpaidWan = Math.round(Math.abs(yrUnpaid) / 10000);
|
||||
const payRateCls = yrPayRate < 30 ? 'text-red-600' : yrPayRate < 80 ? 'text-amber-600' : 'text-green-600';
|
||||
const unpaidLabel = yrUnpaid >= 0
|
||||
? '你还有 <strong class=\"text-red-600\">' + yrUnpaidWan + '万</strong> 未回款'
|
||||
: '超额回款 <strong class=\"text-green-600\">' + yrUnpaidWan + '万</strong>';
|
||||
const payReminder = yrRev > 0 ? '<div class=\"flex items-center gap-3 px-4 py-3 rounded-lg border\" style=\"background:linear-gradient(135deg,#fef3c7,#fde68a);border-color:#f59e0b\">' +
|
||||
'<i data-lucide=\"bell-ring\" class=\"text-amber-600 flex-shrink-0\" style=\"width:18px;height:18px\"></i>' +
|
||||
'<span class=\"text-sm text-amber-900\"><strong>回款提醒:</strong>本年度确收 <strong>' + moneyInt(yrRev) + '</strong>,回款 <strong>' + moneyInt(yrPay) + '</strong>,你还有 <strong class=\"text-red-600\">' + yrUnpaidWan + '万</strong> 未回款,当前回款率:<strong class=\"' + payRateCls + '\">' + yrPayRate + '%</strong></span>' +
|
||||
'<span class=\"text-sm text-amber-900\"><strong>回款提醒:</strong>本年度确收 <strong>' + moneyInt(yrRev) + '</strong>,回款 <strong>' + moneyInt(yrPay) + '</strong>,' + unpaidLabel + ',当前回款率:<strong class=\"' + payRateCls + '\">' + yrPayRate + '%</strong></span>' +
|
||||
'</div>' : '';
|
||||
const rows1 = [
|
||||
["年度累计", moneyInt(m.signed_annual || m.signed_amount)],
|
||||
@@ -123,10 +126,9 @@ function renderHome() {
|
||||
].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>`}
|
||||
${payReminder}
|
||||
${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>
|
||||
${(() => {
|
||||
${(() => {
|
||||
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_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]],
|
||||
@@ -137,35 +139,38 @@ function renderHome() {
|
||||
(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)
|
||||
]]
|
||||
]],
|
||||
['项目现金流', [m.cashflow_annual||0, m.cashflow_q2||0, m.cashflow_month||0, m.cashflow_prev_q||0, m.cashflow_prev_month||0],
|
||||
[m.cashflow_q2||0,m.cashflow_prev_q||0], [m.cashflow_month||0,m.cashflow_prev_month||0]],
|
||||
['部门费用流出', [m.expense_paid_annual||0, m.expense_paid_q2||0, m.expense_paid_month||0, m.expense_paid_prev_q||0, m.expense_paid_prev_month||0],
|
||||
[m.expense_paid_q2||0,m.expense_paid_prev_q||0], [m.expense_paid_month||0,m.expense_paid_prev_month||0]],
|
||||
['部门现金流', [m.dept_cf_annual||0, m.dept_cf_q2||0, m.dept_cf_month||0, m.dept_cf_prev_q||0, m.dept_cf_prev_month||0],
|
||||
[m.dept_cf_q2||0,m.dept_cf_prev_q||0], [m.dept_cf_month||0,m.dept_cf_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;
|
||||
var buildDeptTable = function(title, dataRows) {
|
||||
var h = '';
|
||||
for (var di = 0; di < dataRows.length; di++) {
|
||||
var r = dataRows[di];
|
||||
var rawNet = r[1][0];
|
||||
var isNet = r[0] === '部门净利' || r[0] === '部门现金流';
|
||||
var isCF = r[0] === '项目现金流';
|
||||
var cls = isNet ? (rawNet >= 0 ? 'text-green-600' : 'text-red-600') : isCF ? (rawNet >= 0 ? 'text-green-600' : 'text-red-600') : 'text-slate-800';
|
||||
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 ' + cls + '">' + moneyInt(r[1][0]) + '</td>' +
|
||||
'<td class="py-2 text-right font-semibold ' + cls + '">' + moneyInt(r[1][3]) + '</td>' +
|
||||
'<td class="py-2 text-right font-semibold ' + cls + '">' + moneyInt(r[1][4]) + '</td>' +
|
||||
'<td class="py-2 text-right font-semibold ' + cls + '">' + 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 ' + cls + '">' + moneyInt(r[1][2]) + '</td>' +
|
||||
'<td class="py-2 text-right">' + qoq(r[3][0], r[3][1]) + '</td></tr>';
|
||||
}
|
||||
return card('<h3 class="text-sm font-bold text-slate-700 mb-3">' + title + '</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>' + h + '</tbody></table></div>', 'p-4');
|
||||
};
|
||||
return buildDeptTable('部门经营情况', d.slice(0, 3)) + buildDeptTable('部门现金流', d.slice(3, 6));
|
||||
})()}
|
||||
</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="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="chartProfit"></canvas></div>`, "p-4")}
|
||||
</div>
|
||||
${card(`<h2 class="text-lg font-bold">近期动态</h2><div class="mt-4 grid gap-2">${summary.recent.map((r) => `<div class="flex items-start justify-between rounded-md bg-slate-50 px-3 py-2 text-sm group"><span class="break-words">${r.content}</span><div class="flex items-center gap-2 flex-shrink-0 ml-2"><span class="text-xs text-slate-400">${r.followed_at}</span><button class="btn btn-ghost btn-sm text-red-400 opacity-0 group-hover:opacity-100 p-0 w-5 h-5" onclick="event.preventDefault();deleteActivity(${r.id})" title="删除动态"><i data-lucide="trash-2" style="width:14px;height:14px"></i></button></div></div>`).join("")}</div>`, "p-5")}
|
||||
</div>
|
||||
`;
|
||||
renderCharts(financeMonthly);
|
||||
}
|
||||
|
||||
function chartOptions(yCallback) {
|
||||
|
||||
@@ -10,7 +10,7 @@ window.renderPerformance = () => {
|
||||
const qRange = qRanges[q];
|
||||
const storageKey = 'opc-performance-Q' + (q + 1);
|
||||
|
||||
const pfs = (data.projectFinances || []).filter(p => p.status === '已签约');
|
||||
const pfs = (data.projectFinances || []);
|
||||
|
||||
const sumQ = (field) => {
|
||||
let total = 0;
|
||||
|
||||
1142
static/modules/plan.js
Normal file
1142
static/modules/plan.js
Normal file
File diff suppressed because it is too large
Load Diff
219
static/modules/plan_expense.js
Normal file
219
static/modules/plan_expense.js
Normal file
@@ -0,0 +1,219 @@
|
||||
// expense.js — 费用管理模块
|
||||
|
||||
function renderPlanExpense() {
|
||||
var records = state.data.planExpense || [];
|
||||
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 STATUS_OPTIONS = ['计入费用','暂不计入'];
|
||||
|
||||
// 排序状态
|
||||
if (!state.planExpSort) state.planExpSort = { key: 'expense_month', asc: true };
|
||||
var sortKey = state.planExpSort.key;
|
||||
var sortAsc = state.planExpSort.asc ? 1 : -1;
|
||||
|
||||
// 筛选状态
|
||||
var view = state.planExpView || 'total';
|
||||
var typeFilter = state.planExpFilter || '全部';
|
||||
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.planExpMonth) state.planExpMonth = defaultMonth;
|
||||
if (state.planExpQuarter === '') state.planExpQuarter = String(Math.floor(now.getMonth() / 3));
|
||||
|
||||
// 月度筛选
|
||||
if (view === 'monthly') {
|
||||
filtered = filtered.filter(function(r) { return r.expense_month === state.planExpMonth; });
|
||||
}
|
||||
|
||||
// 季度筛选
|
||||
if (view === 'quarterly') {
|
||||
var q = parseInt(state.planExpQuarter) || 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;
|
||||
});
|
||||
}
|
||||
|
||||
// 排序
|
||||
filtered.sort(function(a, b) {
|
||||
var va = a[sortKey] || '', vb = b[sortKey] || '';
|
||||
if (sortKey === 'amount' || sortKey === 'incurred_amount') {
|
||||
va = parseFloat(va) || 0; vb = parseFloat(vb) || 0;
|
||||
}
|
||||
if (va < vb) return -1 * sortAsc;
|
||||
if (va > vb) return 1 * sortAsc;
|
||||
return 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 = '';
|
||||
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 + '</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 + '">' + qLabels[qi] + '</option>';
|
||||
}
|
||||
|
||||
// 月份/季度日期选择器
|
||||
var dateSelect = '';
|
||||
if (view === 'monthly') {
|
||||
dateSelect = '<span class="text-sm text-slate-500 ml-2">月份:</span><select onchange="setPlanExpMonth(this.value)" class="text-sm 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.planExpMonth?' selected':'') + '>请选择</option>' + monthOpts.replace('value="' + state.planExpMonth + '"', 'value="' + state.planExpMonth + '" selected') + '</select>';
|
||||
} else if (view === 'quarterly') {
|
||||
dateSelect = '<span class="text-sm text-slate-500 ml-2">季度:</span><select onchange="setPlanExpQuarter(this.value)" class="text-sm 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.replace('value="' + state.planExpQuarter + '"', 'value="' + state.planExpQuarter + '" selected') + '</select>';
|
||||
}
|
||||
|
||||
// Toolbar
|
||||
var toolbar = '<span class="text-sm text-slate-500">视图:</span><select onchange="setPlanExpView(this.value)" class="text-sm 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-sm text-slate-500 ml-3">类型:</span><select onchange="setPlanExpFilter(this.value)" class="text-sm 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 sortArrow = function(key) {
|
||||
var arrow = key === sortKey ? (sortAsc === 1 ? ' ↑' : ' ↓') : '';
|
||||
return '<span class="text-slate-400 text-xs cursor-pointer" onclick="togglePlanExpSort(\'' + key + '\')">' + arrow + '</span>';
|
||||
};
|
||||
|
||||
// 表格行
|
||||
var tableRows = '';
|
||||
if (filtered.length) {
|
||||
filtered.forEach(function(r) {
|
||||
var statusCls = r.status === '暂不计入' ? 'text-amber-600' : 'text-green-600';
|
||||
tableRows += '<tr class="border-b border-slate-100 hover:bg-slate-50 cursor-pointer" onclick="openPlanExpEdit(' + r.id + ')"><td class="p-2 text-center align-middle font-medium">' + (r.expense_month || '—') + '</td><td class="p-2 font-medium text-center align-middle">' + esc(r.expense_type) + '</td><td class="p-2 text-center align-middle font-semibold ' + statusCls + '">' + esc(r.status || '计入费用') + '</td><td class="p-2 text-center align-middle font-medium">' + money(r.amount) + '</td><td class="p-2 text-center align-middle font-medium">' + money(r.incurred_amount) + '</td><td class="p-2 text-center align-middle text-slate-500">' + (esc(r.notes) || '—') + '</td></tr>';
|
||||
});
|
||||
} else {
|
||||
var emptyMsg = view === 'monthly' ? '该月份暂无费用记录' : view === 'quarterly' ? '该季度暂无费用记录' : '暂无费用记录';
|
||||
tableRows = '<tr><td colspan="6" class="p-6 text-center text-slate-400">' + emptyMsg + '</td></tr>';
|
||||
}
|
||||
|
||||
// 模态框 monthOpts for form (with current value preselected)
|
||||
var modalMonthOpts = '<option value="">请选择</option>';
|
||||
for (var yr2 = thisYear - 1; yr2 <= thisYear + 1; yr2++)
|
||||
for (var m2 = 1; m2 <= 12; m2++) {
|
||||
var mv2 = yr2 + '-' + String(m2).padStart(2, '0');
|
||||
modalMonthOpts += '<option value="' + mv2 + '">' + mv2 + '</option>';
|
||||
}
|
||||
var statusOpts = STATUS_OPTIONS.map(function(s) { return '<option value="' + s + '">' + s + '</option>'; }).join('');
|
||||
|
||||
var modal = '<div id="planExpenseModal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/40" onclick="closePlanExpModal()"><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="planExpenseModalTitle">新增费用</h3><div class="flex items-center gap-2"><button class="btn btn-ghost btn-sm text-red-600 hidden" id="planExpDeleteBtn" onclick="deletePlanExpItem()">删除</button><button class="btn btn-ghost btn-sm rounded-full w-8 h-8 p-0" onclick="closePlanExpModal()"><i data-lucide="x"></i></button></div></div><form onsubmit="savePlanExpense(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-sm 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-sm text-slate-500 mb-1 block">月份 <span class="text-red-500">*</span></span><select name="expense_month" required class="form-ctrl bg-white">' + modalMonthOpts + '</select></label></div><div class="grid grid-cols-2 gap-3"><label class="block"><span class="text-sm 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-sm 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-sm text-slate-500 mb-1 block">状态</span><select name="status" class="form-ctrl bg-white">' + statusOpts + '</select></label><label class="block"><span class="text-sm 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="closePlanExpModal()">取消</button><button type="submit" class="btn btn-primary btn-sm px-8">保存</button></div></form></div></div>';
|
||||
|
||||
var target = document.querySelector("#planExpenseModule") || document.querySelector("#planExpenseModule") || document.querySelector("#planExpenseContent");
|
||||
if (!target) return;
|
||||
target.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="openPlanExpModal()">新增费用</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-sm 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-sm 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-sm 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 cursor-pointer select-none" onclick="togglePlanExpSort(\'expense_month\')">月份' + sortArrow('expense_month') + '</th><th class="p-2 text-center font-semibold cursor-pointer select-none" onclick="togglePlanExpSort(\'expense_type\')">费用类型' + sortArrow('expense_type') + '</th><th class="p-2 text-center font-semibold cursor-pointer select-none" onclick="togglePlanExpSort(\'status\')">状态' + sortArrow('status') + '</th><th class="p-2 text-center font-semibold cursor-pointer select-none" onclick="togglePlanExpSort(\'amount\')">金额' + sortArrow('amount') + '</th><th class="p-2 text-center font-semibold cursor-pointer select-none" onclick="togglePlanExpSort(\'incurred_amount\')">已发生金额' + sortArrow('incurred_amount') + '</th><th class="p-2 text-center font-semibold">费用说明</th></tr></thead><tbody>' + tableRows + '</tbody></table></div></div>' +
|
||||
'</div>';
|
||||
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
|
||||
window.togglePlanExpSort = function(key) {
|
||||
var cur = state.planExpSort || {};
|
||||
if (cur.key === key) { cur.asc = !cur.asc; }
|
||||
else { cur.key = key; cur.asc = true; }
|
||||
state.planExpSort = cur;
|
||||
renderPlanExpense();
|
||||
};
|
||||
|
||||
window.setPlanExpView = function(v) { state.planExpView = v; renderPlanExpense(); };
|
||||
window.setPlanExpFilter = function(v) { state.planExpFilter = v; renderPlanExpense(); };
|
||||
window.setPlanExpMonth = function(v) { state.planExpMonth = v; renderPlanExpense(); };
|
||||
window.setPlanExpQuarter = function(v) { state.planExpQuarter = v; renderPlanExpense(); };
|
||||
|
||||
window.openPlanExpModal = function() {
|
||||
var form = document.querySelector("#planExpenseModal form");
|
||||
form.reset();
|
||||
form.querySelector('[name="expense_id"]').value = "";
|
||||
form.querySelector('[name="status"]').value = "计入费用";
|
||||
document.querySelector("#planExpenseModalTitle").textContent = "新增费用";
|
||||
document.querySelector("#planExpDeleteBtn").classList.add("hidden");
|
||||
document.querySelector("#planExpenseModal").classList.remove("hidden");
|
||||
};
|
||||
|
||||
window.closePlanExpModal = function() {
|
||||
document.querySelector("#planExpenseModal").classList.add("hidden");
|
||||
};
|
||||
|
||||
window.openPlanExpEdit = function(id) {
|
||||
var r = (state.data.planExpense || []).find(function(x) { return x.id === id; });
|
||||
if (!r) return;
|
||||
var form = document.querySelector("#planExpenseModal 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);
|
||||
setVal("status", r.status || "计入费用");
|
||||
document.querySelector("#planExpenseModalTitle").textContent = "编辑费用";
|
||||
document.querySelector("#planExpDeleteBtn").classList.remove("hidden");
|
||||
document.querySelector("#planExpenseModal").classList.remove("hidden");
|
||||
};
|
||||
|
||||
window.savePlanExpense = async function(event) {
|
||||
event.preventDefault();
|
||||
var form = event.target;
|
||||
var data = Object.fromEntries(new FormData(form).entries());
|
||||
if (data.amount === '' || data.amount === undefined) data.amount = 0;
|
||||
if (data.incurred_amount === '' || data.incurred_amount === undefined) data.incurred_amount = 0;
|
||||
if (!data.status) data.status = '计入费用';
|
||||
var isEdit = !!data.expense_id;
|
||||
delete data.expense_id;
|
||||
|
||||
var id = form.querySelector('[name="expense_id"]').value;
|
||||
var url = isEdit ? "/api/planExpense/" + id : "/api/planExpense";
|
||||
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();
|
||||
renderPlanExpense();
|
||||
}
|
||||
closePlanExpModal();
|
||||
};
|
||||
|
||||
window.deletePlanExpItem = async function() {
|
||||
var id = document.querySelector("#planExpenseModal form [name='expense_id']").value;
|
||||
if (!id || !confirm("确定删除?")) return;
|
||||
var resp = await fetch("/api/planExpense/" + 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();
|
||||
renderPlanExpense();
|
||||
}
|
||||
};
|
||||
@@ -82,6 +82,9 @@ window.toggleUserMenu = (user) => {
|
||||
${user.role === 'admin' ? `<button class="w-full text-left px-4 py-2 text-sm text-slate-700 hover:bg-slate-50 transition-colors flex items-center gap-2" onclick="closeUserMenu();openAdminUsers()">
|
||||
<i data-lucide="users" style="width:14px;height:14px"></i>账号管理
|
||||
</button>` : ''}
|
||||
<button class="w-full text-left px-4 py-2 text-sm text-slate-700 hover:bg-slate-50 transition-colors flex items-center gap-2" onclick="closeUserMenu();openChangePwdModal()">
|
||||
<i data-lucide="lock" style="width:14px;height:14px"></i>修改密码
|
||||
</button>
|
||||
<button class="w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition-colors flex items-center gap-2" onclick="doLogout()">
|
||||
<i data-lucide="log-out" style="width:14px;height:14px"></i>退出登录
|
||||
</button>`;
|
||||
|
||||
@@ -5,11 +5,15 @@ const state = {
|
||||
data: null,
|
||||
tenant: "科普·无界",
|
||||
opFilter: "all",
|
||||
finFilter: "已签约",
|
||||
finFilter: "projects",
|
||||
selectedProject: null,
|
||||
taskQuery: "",
|
||||
taskView: localStorage.getItem("opc-task-view") || "detail",
|
||||
finView: "overview",
|
||||
finSort: null, // { key: 'col', asc: true }
|
||||
planFilter: "projects",
|
||||
planView: "overview",
|
||||
planSort: null,
|
||||
proposalTab: "standard",
|
||||
chart: null,
|
||||
chart2: null,
|
||||
@@ -132,7 +136,7 @@ function switchTab(tab) {
|
||||
document.querySelectorAll(".panel").forEach((panel) => panel.classList.toggle("active", panel.id === tab));
|
||||
|
||||
// 更新顶部标题
|
||||
const titles = { home: 'OPC 工作台', finance: '业务管理', projects: '重点工作台账', proposals: '业务方案', products: '版本与运营', performance: '季度绩效考核' };
|
||||
const titles = { home: 'OPC 工作台', finance: '实际管理', plan: '计划管理', projects: '重点工作台账', proposals: '业务方案', products: '版本与运营', performance: '季度绩效考核' };
|
||||
const titleEl = document.querySelector('#workspaceTitle');
|
||||
if (titleEl) titleEl.textContent = titles[tab] || state.tenant + ' OPC 工作台';
|
||||
|
||||
@@ -159,6 +163,7 @@ function render() {
|
||||
renderProducts();
|
||||
renderPerformance();
|
||||
renderFinance();
|
||||
renderPlan();
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
|
||||
@@ -171,6 +176,7 @@ function renderActive() {
|
||||
else if (tab === "products") renderProducts();
|
||||
else if (tab === "performance") renderPerformance();
|
||||
else if (tab === "finance") renderFinance();
|
||||
else if (tab === "plan") renderPlan();
|
||||
if (window.lucide) window.lucide.createIcons();
|
||||
}
|
||||
|
||||
@@ -198,10 +204,37 @@ window.setFinView = (view) => {
|
||||
state.finView = view;
|
||||
renderFinance();
|
||||
};
|
||||
window.setFinQuarter = (q) => { state.finQuarter = q; state.finView = 'quarterly'; renderFinance(); };
|
||||
window.setFinMonth = (month) => { state.finMonth = month; state.finView = 'monthly'; renderFinance(); };
|
||||
window.switchFinFilter = (filter) => {
|
||||
state.finFilter = filter;
|
||||
state.finSort = null;
|
||||
renderFinance();
|
||||
};
|
||||
|
||||
window.setFinSort = (key) => {
|
||||
if (!state.finSort) state.finSort = { key: null, asc: true };
|
||||
if (state.finSort.key === key) { state.finSort.asc = !state.finSort.asc; }
|
||||
else { state.finSort.key = key; state.finSort.asc = true; }
|
||||
renderFinance();
|
||||
};
|
||||
window.setPlanView = (view) => {
|
||||
state.planView = view;
|
||||
renderPlan();
|
||||
};
|
||||
window.setPlanQuarter = (q) => { state.planQuarter = q; state.planView = 'quarterly'; renderPlan(); };
|
||||
window.setPlanMonth = (month) => { state.planMonth = month; state.planView = 'monthly'; renderPlan(); };
|
||||
window.switchPlanFilter = (filter) => {
|
||||
state.planFilter = filter;
|
||||
state.planSort = null;
|
||||
renderPlan();
|
||||
};
|
||||
window.setPlanSort = (key) => {
|
||||
if (!state.planSort) state.planSort = { key: null, asc: true };
|
||||
if (state.planSort.key === key) { state.planSort.asc = !state.planSort.asc; }
|
||||
else { state.planSort.key = key; state.planSort.asc = true; }
|
||||
renderPlan();
|
||||
};
|
||||
window.switchTenant = (tenant) => {
|
||||
state.tenant = tenant;
|
||||
state.selectedProject = null;
|
||||
|
||||
@@ -96,26 +96,26 @@ body {
|
||||
}
|
||||
|
||||
/* 详情弹窗固定高度,tab 切换不抖动 */
|
||||
#financeModal > div {
|
||||
#financeModal > div, #planModal > div {
|
||||
height: 650px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
#financeModal .finance-tabs { flex-shrink: 0; }
|
||||
#financeModal form {
|
||||
#financeModal .finance-tabs, #planModal .finance-tabs { flex-shrink: 0; }
|
||||
#financeModal form, #planModal form {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
#financeModal .finance-tab-body {
|
||||
#financeModal .finance-tab-body, #planModal .finance-tab-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 32px;
|
||||
}
|
||||
#financeModal .finance-form-actions {
|
||||
#financeModal .finance-form-actions, #planModal .finance-form-actions {
|
||||
flex-shrink: 0;
|
||||
background: #fff;
|
||||
padding: 12px 32px 8px;
|
||||
|
||||
@@ -45,13 +45,17 @@
|
||||
<div class="w-8 h-px bg-slate-700 my-2"></div>
|
||||
<!-- 导航 Tab 图标 -->
|
||||
<div class="flex flex-col items-center gap-1 w-14" id="sidebarTabs">
|
||||
<div class="sidebar-tab active" data-tab="home" onclick="switchTab('home')" title="首页">
|
||||
<i data-lucide="home" style="width:20px;height:20px"></i>
|
||||
<span class="text-[10px] mt-1">首页</span>
|
||||
<div class="sidebar-tab active" data-tab="home" onclick="switchTab('home')" title="部门">
|
||||
<i data-lucide="trending-up" style="width:20px;height:20px"></i>
|
||||
<span class="text-[10px] mt-1">部门</span>
|
||||
</div>
|
||||
<div class="sidebar-tab" data-tab="finance" onclick="switchTab('finance')" title="业务">
|
||||
<div class="sidebar-tab" data-tab="plan" onclick="switchTab('plan')" title="计划">
|
||||
<i data-lucide="calendar-range" style="width:20px;height:20px"></i>
|
||||
<span class="text-[10px] mt-1">计划</span>
|
||||
</div>
|
||||
<div class="sidebar-tab" data-tab="finance" onclick="switchTab('finance')" title="实际">
|
||||
<i data-lucide="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 class="sidebar-tab" data-tab="projects" onclick="switchTab('projects')" title="Focus">
|
||||
<i data-lucide="file-text" style="width:20px;height:20px"></i>
|
||||
@@ -76,7 +80,7 @@
|
||||
<header class="topbar border-b border-slate-200 bg-white px-8 py-5">
|
||||
<div class="flex items-center gap-3 w-full">
|
||||
<div class="flex-1">
|
||||
<p class="eyebrow text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">OPC Manager <span class="ml-2 text-xs font-normal text-slate-400 tracking-normal">v1.0.0.5</span></p>
|
||||
<p class="eyebrow text-xs font-semibold uppercase tracking-[0.18em] text-blue-700">OPC Manager <span class="ml-2 text-xs font-normal text-slate-400 tracking-normal">v1.0.0.27</span></p>
|
||||
<div class="flex items-center gap-4 mt-1">
|
||||
<h1 class="text-2xl font-semibold" id="workspaceTitle">科普 OPC 工作台</h1>
|
||||
<div class="hidden sm:flex items-center gap-1.5 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-100 rounded-full px-4 py-1.5">
|
||||
@@ -99,6 +103,7 @@
|
||||
<section id="performance" class="panel"></section>
|
||||
<section id="performance" class="panel"></section>
|
||||
<section id="finance" class="panel"></section>
|
||||
<section id="plan" class="panel"></section>
|
||||
</main>
|
||||
</div><!-- 关闭主内容区 -->
|
||||
</div><!-- 关闭 flex 容器 -->
|
||||
@@ -129,6 +134,8 @@
|
||||
<script src="{{ url_for('static', filename='modules/performance.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/plan.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='modules/plan_expense.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='modules/drawer.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='modules/admin.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='app.js') }}"></script>
|
||||
|
||||
Reference in New Issue
Block a user