Compare commits

..

2 Commits

Author SHA1 Message Date
mac
f9fe32beed feat: 费用状态字段 + 表格排序 + 首页回款提醒 + 回款率着色
- 平台费用新增状态字段(计入费用/暂不计入),默认计入费用
- 费用表格月份列置首,所有表头点击正/倒序排序
- 首页新增回款提醒条(金色渐变,含确收/回款/未回款/回款率)
- 业务表格回款率着色:<30%红,30-80%黄,>=100%绿
- 版本号v1.0.0.5
2026-07-07 18:34:47 +08:00
mac
a6acfb2012 fix: 季度视图跳过逻辑 + 筛选区字号 + 首页去筛选
- 季度视图与月度视图统一:无当期数据项目跳过不渲染
- 首页去除时间段筛选下拉框
- 业务/平台费用/首页筛选区文字加大一号(text-xs→text-sm)
- 业务视图不记忆上次选择,默认总视图
- seed数据重构,5工作台各>1亿
- 版本号v1.0.0.4
2026-07-07 18:01:04 +08:00
8 changed files with 344 additions and 131 deletions

View File

@@ -105,6 +105,8 @@ def migrate_add_columns():
"ALTER TABLE expense_records ADD COLUMN expense_month VARCHAR(20) NOT NULL DEFAULT ''") "ALTER TABLE expense_records ADD COLUMN expense_month VARCHAR(20) NOT NULL DEFAULT ''")
_add_column_if_missing(conn, "expense_records", "incurred_amount", _add_column_if_missing(conn, "expense_records", "incurred_amount",
"ALTER TABLE expense_records ADD COLUMN incurred_amount DOUBLE NOT NULL DEFAULT 0") "ALTER TABLE expense_records ADD COLUMN incurred_amount DOUBLE NOT NULL DEFAULT 0")
_add_column_if_missing(conn, "expense_records", "status",
"ALTER TABLE expense_records ADD COLUMN status VARCHAR(50) NOT NULL DEFAULT '计入费用'")
# project_finances 费用明细 JSON 数据 # project_finances 费用明细 JSON 数据
_add_column_if_missing(conn, "project_finances", "expense_data", _add_column_if_missing(conn, "project_finances", "expense_data",

View File

@@ -1,127 +1,285 @@
# seed_data.py — 初始示例数据填充(仅在空库时执行一次) # seed_data.py — 丰富示例数据填充(仅在空库时执行一次)
# 从 flask_app.py 搬迁,被 migrations/seed.py 调用 # 为每个工作台生成 > 1 亿的总规模,覆盖万/十万/百万/千万量级
import json
import random
random.seed(42)
from datetime import date from datetime import date
from pathlib import Path from db import db, _exec, one
from db import db, _exec, one, WEIXIN_BASE
from helpers import add_file_index TENANTS = ["科普·无界", "科研·无界", "医患·无界", "MCN·无界", "学会·无界"]
# 每个工作台的差异化客户和项目模板
TENANT_CUSTOMERS = {
"科普·无界": [
("信达生物", ["肿瘤免疫科普年度框架", "信迪利单抗医生教育", "CSCO卫星会项目", "患者随访管理系统"]),
("百利天恒", ["BL-B01D1上市前教育", "双抗药物科普专区", "数字人患教视频"]),
("齐鲁制药", ["多产品线医生教育", "安可达学术推广", "基层医疗科普巡讲"]),
("天广实生物", ["血液肿瘤科普项目", "CD20单抗学术推广"]),
("复星医药", ["复宏汉霖学术年会", "CAR-T患者教育"]),
],
"科研·无界": [
("北京协和医院", ["临床研究数据采集系统", "罕见病队列研究", "AI辅助诊断验证"]),
("中国人民解放军总医院", ["战场创伤数据平台", "远程会诊系统"]),
("复旦大学附属华山医院", ["脑卒中AI预警系统", "神经内科临床研究"]),
("中山大学肿瘤防治中心", ["鼻咽癌早筛项目", "真实世界研究平台"]),
("四川大学华西医院", ["精准医学大数据平台", "基层科研能力提升"]),
],
"医患·无界": [
("平安好医生", ["在线问诊科普内容", "慢病管理专区", "随访SOP标准化"]),
("微医集团", ["互联网医院患教系统", "云药房科普推送"]),
("丁香园", ["医生社区运营升级", "用药助手科普专区"]),
("圆心科技", ["药房患者教育", "DTP药房随访管理", "罕见病用药指导"]),
("国药控股", ["国药患者管理平台", "肿瘤药房随访系统"]),
],
"MCN·无界": [
("抖音健康", ["医学IP孵化矩阵", "短视频科普内容制作", "健康直播运营"]),
("快手健康", ["医生个人IP打造", "快手健康科普专区"]),
("小红书医美", ["皮肤健康科普矩阵", "医美科普合规审核"]),
("B站知识区", ["深度科普纪录片", "医学动画制作"]),
("微信视频号", ["医生科普直播运营", "企业微信科普推送"]),
],
"学会·无界": [
("中华医学会", ["学术年会数字化平台", "继续教育学分系统", "基层医生培训"]),
("中国医师协会", ["医师定考管理系统", "专科医师培训平台"]),
("中国抗癌协会", ["肿瘤科普万里行", "CACA指南推广"]),
("中国药学会", ["合理用药科普平台", "药师继续教育"]),
("中华护理学会", ["护理科研能力提升", "专科护士培训系统"]),
],
}
# 签约金额模板:每个工作台的千万/百万/十万/万级别项目的签约金额
def generate_sign_amounts():
amounts = []
# 千万级2个4000-7000万
amounts.append(random.randint(4500, 7000) * 10000)
amounts.append(random.randint(4000, 6500) * 10000)
# 百万级4个400-980万
for _ in range(4):
amounts.append(random.randint(400, 980) * 10000)
# 十万级4个30-98万
for _ in range(4):
amounts.append(random.randint(30, 98) * 10000)
# 万级3个3-10万
for _ in range(3):
amounts.append(random.randint(3, 10) * 10000)
return sorted(amounts, reverse=True)
# 生成 budget_data JSON每月确收/毛利/回款)
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))
gross_rate = random.uniform(0.25, 0.55)
payment_rate = random.uniform(0.7, 0.95)
for i in range(12):
m = (start_m + i - 1) % 12 + 1
yr = 2026 + (start_m + i - 1) // 12
month_key = f"{yr}-{m:02d}"
# 越往后确收越多
progress = min(1.0, (i + 1) / max(1, random.randint(3, 8)))
rev = round(rev_total * progress * random.uniform(0.85, 1.15))
gross = round(rev * gross_rate * random.uniform(0.9, 1.1))
payment = round(rev * payment_rate * random.uniform(0.85, 1.15))
cost = round(rev * random.uniform(0.3, 0.5))
paid = round(cost * random.uniform(0.8, 1.0))
months.append({
"month": month_key,
"rev": rev,
"gross": gross,
"payment": payment,
"cost": cost,
"paid": paid,
})
return json.dumps(months)
# 生成 expense_data平台费用
def make_expense_data():
"""生成若干条费用记录"""
items = []
expense_types = ["平台采购", "人力成本", "研发费用", "通用费用", "奖金"]
for q in range(1, 7):
for et in random.sample(expense_types, random.randint(2, 4)):
month_str = f"2026-{q:02d}"
amount = random.randint(5000, 150000)
incurred = int(amount * random.uniform(0.6, 1.0))
items.append({"month": month_str, "expense_type": et, "amount": amount, "incurred": incurred})
return json.dumps(items)
def seed_db(): def seed_db():
"""填充初始示例数据(仅在空库时执行一次)""" """填充丰富示例数据"""
conn = db() conn = db()
try: try:
if one(conn, "SELECT id FROM sales_leads LIMIT 1"): if one(conn, "SELECT id FROM sales_leads LIMIT 1"):
return # 已有数据,跳过 return
sales = [ today = date.today().isoformat()
("齐鲁制药", "P0", "跟进中", "多产品线科普年度框架,需推进高层沟通。"), pf_ids = {} # tenant -> [project_finance_ids]
("百利天恒", "P0", "方案中", "BL-B01D1 上市前医生教育机会,准备方案。"),
("信达生物", "P0", "已签约", "现有科普项目升级/续约,重点保障执行。"), for tenant in TENANTS:
("三生制药", "P1", "待跟进", "多科室医生教育+患者科普机会。"), customers = TENANT_CUSTOMERS[tenant]
("天广实生物", "P1", "待跟进", "血液肿瘤医生教育机会。"), amounts = generate_sign_amounts()
cust_idx = 0
for i, sign_amount in enumerate(amounts):
cust_name, projects = customers[cust_idx % len(customers)]
proj_name = projects[i % len(projects)] if i < len(projects) else f"{cust_name} 项目{i+1}"
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 ""
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
budget_data = make_budget_data(sign_amount, sign_month, status)
expense_data = make_expense_data() if status == "已签约" else "[]"
task_data = json.dumps([
{"task": f"{proj_name} 项目启动", "due": f"2026-{min(12, 1+i//2):02d}-01", "status": "已完成" if i < 8 else "进行中"},
{"task": f"方案评审与确认", "due": f"2026-{min(12, 2+i//2):02d}-15", "status": "已完成" if i < 6 else "进行中"},
{"task": f"内容生产阶段", "due": f"2026-{min(12, 3+i//2):02d}-30", "status": "进行中"},
])
cur = _exec(conn, """
INSERT INTO project_finances
(tenant, project_id, business_type, customer_name, sign_amount, sign_month, status,
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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
""", (
tenant, f"PF-{tenant[:2]}-{i+1:04d}", business_type, cust_name,
sign_amount, sign_month, status,
f"销售{random.choice(['A','B','C','D'])}", total_rev, total_gross,
total_payment, total_cost, total_paid,
budget_data, expense_data, task_data,
project_code, f"2026-{random.randint(1,3):02d}-01", f"2026-{random.randint(9,12):02d}-30",
random.choice(["内容生产", "视频制作", "专家访谈", "学术会议", "患者教育"]),
random.randint(10, 100), random.choice([800, 1000, 1200, 1500, 2000]),
f"经理{random.choice(['A','B','C'])}", f"联系人{random.randint(1,20)}",
f"1380000{random.randint(1000,9999)}", f"备注信息 {i+1}",
today, today,
))
# Store for later use
pf_ids.setdefault(tenant, []).append((cur.lastrowid, proj_name, cust_name, status))
# operation_projects: 每个工作台 3-5 个
op_count = random.randint(3, 5)
for j in range(op_count):
pf_row = random.choice(pf_ids[tenant])
cur2 = _exec(conn, """
INSERT INTO operation_projects
(tenant, project_name, project_version, project_type, project_status,
current_stage, owner, start_date, end_date, target_customer, customer_need,
expected_contract_amount, expected_sign_date, sign_probability, next_action,
sop_stage, execution_progress, current_deliverable, notes)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
""", (
tenant, f"{pf_row[1]} 运营方案", "v1.0",
"execution" if random.random() < 0.6 else "opportunity",
"SOP 执行中" if random.random() < 0.6 else "方案已提交",
random.choice(["商务推进", "内容生产", "渠道分发"]),
f"OPC{random.randint(1,5)}", "2026-06-01", "2026-12-31",
pf_row[2], "科普内容项目执行与管理",
pf_row[0] if pf_row[3] == "已签约" else random.randint(50, 300) * 10000,
"2026-06", 70 + random.randint(0, 30),
"补齐版本要求文件并更新下一节点",
"SOP 执行", random.randint(30, 80), "当前交付物 v1.0",
"运营备注",
))
_exec(conn, """
INSERT INTO follow_up_records
(target_type, target_id, followed_at, content, next_action, follower)
VALUES (?,?,?,?,?,?)
""", (
"operation", cur2.lastrowid, today,
f"运营项目跟进:{pf_row[1]},当前进度正常", "继续推进下一里程碑",
f"销售{random.choice(['A','B'])}",
))
# expense_records: 每个工作台 15-20 条
expense_count = random.randint(15, 20)
expense_types = ["通用费用", "平台采购", "人力成本", "研发费用", "奖金", "其他"]
for j in range(expense_count):
et = random.choice(expense_types)
month_str = f"2026-{random.randint(1, 6):02d}"
amount = random.randint(5000, 500000)
incurred = int(amount * random.uniform(0.5, 1.0))
_exec(conn, """
INSERT INTO expense_records
(tenant, expense_type, expense_month, amount, incurred_amount, notes, status)
VALUES (?,?,?,?,?,?,?)
""", (
tenant, et, month_str, amount, incurred,
f"{et} - {random.choice(['季度预算', '紧急支出', '常规费用', '项目费用'])}",
"计入费用",
))
print(f"[seed] {tenant}: {len(amounts)} 项目, {op_count} 运营项目, {expense_count} 费用记录")
conn.commit() # 提交所有工作台的核心数据
# 全域数据sales_leads 对所有 tenant 可见
global_sales = [
("齐鲁制药", "P0", "跟进中", "多产品线科普年度框架"),
("百利天恒", "P0", "方案中", "BL-B01D1 上市前医生教育"),
("信达生物", "P0", "已签约", "现有科普项目升级/续约"),
("三生制药", "P1", "待跟进", "多科室医生教育+患者科普"),
("天广实生物", "P1", "待跟进", "血液肿瘤医生教育机会"),
] ]
for customer, priority, status, note in sales: for customer, priority, status, note in global_sales:
cur = _exec(conn, cur = _exec(conn,
"INSERT INTO sales_leads (target_customer, priority, status) VALUES (?,?,?)", "INSERT INTO sales_leads (target_customer, priority, status, created_at) VALUES (?,?,?,?)",
(customer, priority, status), (customer, priority, status, today),
) )
_exec(conn, _exec(conn,
"INSERT INTO follow_up_records (target_type,target_id,followed_at,content,next_action) VALUES (?,?,?,?,?)", "INSERT INTO follow_up_records (target_type,target_id,followed_at,content,next_action,follower) VALUES (?,?,?,?,?,?)",
("sales", cur.lastrowid, date.today().isoformat(), note, "明确下一次沟通人和时间"), ("sales", cur.lastrowid, today, note, "明确下一次沟通", "销售A"),
) )
# 全域 business_proposals
cur = _exec(conn, cur = _exec(conn,
"INSERT INTO business_proposals (customer_or_project_name,version,description,status,created_date) VALUES (?,?,?,?,?)", "INSERT INTO business_proposals (customer_or_project_name,version,description,status,created_date, tenant) VALUES (?,?,?,?,?,?)",
("信达生物", "v1.5", "信达科普项目续约与报价方案", "已提交客户", "2026-05-28"), ("信达生物", "v1.5", "信达科普项目续约与报价方案", "已提交客户", "2026-05-28", "科普·无界"),
) )
proposal_id = cur.lastrowid proposal_id = cur.lastrowid
proposal_dir = WEIXIN_BASE / "2、业务方案/信达/v1.5"
for category, names in {
"方案": ["整体方案.pptx", "整体方案.pdf"],
"成本": ["业务报价-2亿方案.xlsx", "业务报价-5250万方案.xlsx", "5、最新报价.xlsx"],
"SOP": ["SOP.docx"],
"财务流程": ["财务流程.docx"],
}.items():
for name in names:
add_file_index(conn, "proposal", proposal_id, "v1.5", category, proposal_dir / name, external=True)
projects = [
("圆心科技 科普文章项目", "v2026-文章", "execution", "SOP 执行中", "内容生产", 55, "文章内容生产与审核执行中"),
("圆心科技 科普视频项目", "v2026-视频", "execution", "SOP 执行中", "内容生产", 45, "视频脚本、拍摄与审核推进"),
("圆心科技 科普专访项目", "v2026-专访", "opportunity", "方案已提交", "商务推进", 0, "专访项目推动签约"),
]
op_dir = WEIXIN_BASE / "3、运营方案"
for name, version, kind, status, stage, progress, note in projects:
cur = _exec(conn,
"""INSERT INTO operation_projects
(project_name,project_version,project_type,project_status,current_stage,target_customer,customer_need,
expected_contract_amount,expected_sign_date,sign_probability,next_action,sop_stage,execution_progress,current_deliverable)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(name, version, kind, status, stage, "圆心科技", "科普内容项目执行与管理", 0 if kind == "execution" else 200, "2026-06", 100 if kind == "execution" else 70, "补齐版本要求文件并更新下一节点", stage, progress, note),
)
_exec(conn,
"INSERT INTO follow_up_records (target_type,target_id,followed_at,content,next_action) VALUES (?,?,?,?,?)",
("operation", cur.lastrowid, date.today().isoformat(), note, "补齐版本要求文件并更新下一节点"),
)
file_map = [
(1, "v2026-文章", "项目方案", "圆心科技--科普文章项目(1).pptx"),
(2, "v2026-视频", "项目方案", "圆心科技-科普视频项目(1).pptx"),
(3, "v2026-专访", "项目方案", "圆心科技-科普专访项目-2026年(1).pdf"),
(1, "v2026-文章", "项目管理手册", "圆心科技《项目管理手册》-2026年.pdf"),
(2, "v2026-视频", "审核标准", "科普项目-审核标准(文章-视频-音频).pdf"),
]
for project_id, version, category, filename in file_map:
add_file_index(conn, "operation", project_id, version, category, op_dir / filename, external=True)
# 全域 product_versions
products = [ products = [
("妙手医生服务小程序", "v1.1", "视频任务增强 + 积分商城", "草稿箱、批量上传、积分商城、消息通知", "2026-Q3", "规划中", "科普平台"), ("妙手医生服务小程序", "v1.1", "视频任务增强 + 积分商城", "2026-Q3", "规划中", "P1"),
("数字化营销后台管理系统", "v1.2", "运营数据看板 + 智能审核", "医生活跃、任务完成率、AI 预审、渠道数据上报", "2026-Q3", "设计中", "真研平台"), ("数字化营销后台管理系统", "v1.2", "运营数据看板 + 智能审核", "2026-Q3", "设计中", "P0"),
("妙手患者服务", "v0.5", "科普浏览 + 医生主页 MVP", "科普文章/视频浏览、医生主页、搜索", "2026-Q3", "规划中", "科普平台"), ("妙手患者服务", "v0.5", "科普浏览 + 医生主页 MVP", "2026-Q3", "规划中", "P2"),
("数字人内容平台", "v0.1", "基础数字人视频生成 MVP", "预设形象、AI 配音、脚本驱动、简单模板", "2026-Q3", "规划中", "科普平台"), ("数字人内容平台", "v0.1", "基础数字人视频生成 MVP", "2026-Q3", "规划中", "P2"),
("渠道分发引擎", "v1.0", "六渠道统一分发", "分发 API、内容适配、分发排期、效果追踪", "2027-Q1", "规划中", "科普平台"), ("渠道分发引擎", "v1.0", "六渠道统一分发", "2027-Q1", "规划中", "P1"),
] ]
for product in products: for p in products:
cur = _exec(conn, cur = _exec(conn,
"INSERT INTO product_versions (product_name,version,version_goal,feature_list,launch_date,status,platform) VALUES (?,?,?,?,?,?,?)", "INSERT INTO product_versions (product_name,version,version_goal,launch_date,status,priority,tenant) VALUES (?,?,?,?,?,?,?)",
product, (*p, "科普·无界"),
) )
_exec(conn, _exec(conn,
"INSERT INTO follow_up_records (target_type,target_id,followed_at,content,next_action) VALUES (?,?,?,?,?)", "INSERT INTO follow_up_records (target_type,target_id,followed_at,content,next_action,follower) VALUES (?,?,?,?,?,?)",
("product", cur.lastrowid, date.today().isoformat(), f"{product[0]} {product[1]}{product[2]}", "按路线图推进"), ("product", cur.lastrowid, today, f"{p[0]} {p[1]}{p[2]}", "按路线图推进", "产品经理"),
)
for month, record_type, category, amount, notes in [
("2026-05", "revenue", "信达生物续约确认收入", 120, "信达项目阶段确收"),
("2026-06", "revenue", "信达生物续约确认收入", 80, "信达项目尾款预估"),
("2026-05", "cost_expense", "内容生产", 32, "医生劳务与内容制作"),
("2026-05", "cost_expense", "运营管理", 16, "项目管理与渠道协同"),
("2026-06", "cost_expense", "渠道分发", 24, "投放与分发费用"),
]:
_exec(conn,
"INSERT INTO finance_records (month,record_type,category,amount,occurred_date,notes) VALUES (?,?,?,?,?,?)",
(month, record_type, category, amount, f"{month}-01", notes),
)
tasks_seed = [
("阶段1渠道与商务确认", "商务对接", "合同签订", "Anna", "2026-06-30", "法务审核中", "合同签订后开始执行"),
("阶段1渠道与商务确认", "官媒渠道确认", "沟通官媒确定", "段丽华", "2026-06-30", "官媒尽力推,以先达成合作为准", "集团支持"),
("阶段1渠道与商务确认", "官媒渠道确认", "官媒合作签约", "段丽华", "2026-06-18", "", "官媒确认细节"),
("阶段2系统与标准搭建", "系统开发上线", "音频专访系统开发上线", "戴敏/梁军营", "2026-06-18", "客户比较着急执行,需要技术的资源", ""),
("阶段2系统与标准搭建", "系统开发上线", "精品视频系统开发上线", "戴敏/梁军营", "2026-06-25", "", ""),
("阶段2系统与标准搭建", "标准与培训", "业务执行手册SOP", "胡龙飞", "2026-06-12", "", "系统开发上线"),
("阶段3人员与审核入驻", "团队组建", "医学审核人员到位", "胡龙飞", "2026-06-15", "", "审核人员招聘"),
("阶段3人员与审核入驻", "团队组建", "视频制作人员到位", "胡龙飞", "2026-06-18", "", "项目经理招聘"),
("阶段4供应链与制作", "供应商准入", "准入拍摄/剪辑/主持人", "胡龙飞/侯亚凤", "2026-06-18", "", ""),
("阶段2系统与标准搭建", "脚本生产及审核", "生产脚本", "军营", "2026-06-12", "脚本目前生产比较机械,需要提前准备", "细分标签领域完成"),
]
for phase, milestone, task, owner, due_date, blockers, notes in tasks_seed:
_exec(conn,
"INSERT INTO project_tasks (project_id,phase,milestone,task,owner,due_date,blockers,notes) VALUES (?,?,?,?,?,?,?,?)",
(1, phase, milestone, task, owner, due_date, blockers, notes),
) )
conn.commit() conn.commit()
print("[seed] 丰富示例数据已填充")
finally: finally:
conn.close() conn.close()

View File

@@ -24,7 +24,7 @@ TABLES = {
"finance": ("finance_records", ["month", "project_name", "record_type", "category", "amount", "occurred_date", "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"]), "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", "sign_amount", "sign_month", "status", "sales_person", "owner", "total_rev", "total_gross", "total_payment", "total_cost", "total_paid", "budget_data", "expense_data", "start_date", "end_date", "task_type", "task_count", "service_fee_standard", "project_manager", "task_data", "project_code", "contact_name", "contact_phone", "other_info"]),
"expense": ("expense_records", ["expense_type", "expense_month", "amount", "incurred_amount", "notes", "tenant"]), "expense": ("expense_records", ["expense_type", "expense_month", "amount", "incurred_amount", "notes", "status", "tenant"]),
} }
# ---------- 鉴权装饰器 ---------- # ---------- 鉴权装饰器 ----------

View File

@@ -5,6 +5,12 @@ function renderExpense() {
var money = function(v) { return '¥ ' + (Number(v || 0)).toLocaleString('zh-CN', { minimumFractionDigits: 0, maximumFractionDigits: 2 }); }; var money = function(v) { return '¥ ' + (Number(v || 0)).toLocaleString('zh-CN', { minimumFractionDigits: 0, maximumFractionDigits: 2 }); };
var esc = function(s) { return (s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }; var esc = function(s) { return (s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); };
var EXPENSE_TYPES = ['通用费用','平台采购','人力成本','研发费用','奖金','其他']; var EXPENSE_TYPES = ['通用费用','平台采购','人力成本','研发费用','奖金','其他'];
var STATUS_OPTIONS = ['计入费用','暂不计入'];
// 排序状态
if (!state.expenseSort) state.expenseSort = { key: 'expense_month', asc: true };
var sortKey = state.expenseSort.key;
var sortAsc = state.expenseSort.asc ? 1 : -1;
// 筛选状态 // 筛选状态
var view = state.expenseView || 'total'; var view = state.expenseView || 'total';
@@ -35,71 +41,105 @@ function renderExpense() {
}); });
} }
// 排序
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 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 totalIncurred = filtered.reduce(function(s, r) { return s + (r.incurred_amount || 0); }, 0);
// 月份下拉选项(去年/今年/明年) // 月份下拉选项(去年/今年/明年)
var monthOpts = '<option value="">请选择</option>'; var monthOpts = '';
for (var yr = thisYear - 1; yr <= thisYear + 1; yr++) for (var yr = thisYear - 1; yr <= thisYear + 1; yr++)
for (var m = 1; m <= 12; m++) { for (var m = 1; m <= 12; m++) {
var mv = yr + '-' + String(m).padStart(2, '0'); var mv = yr + '-' + String(m).padStart(2, '0');
monthOpts += '<option value="' + mv + '"' + (mv === state.expenseMonth ? ' selected' : '') + '>' + mv + '</option>'; monthOpts += '<option value="' + mv + '">' + mv + '</option>';
} }
// 季度下拉 // 季度下拉
var qLabels = ['Q1 (1-3月)','Q2 (4-6月)','Q3 (7-9月)','Q4 (10-12月)']; var qLabels = ['Q1 (1-3月)','Q2 (4-6月)','Q3 (7-9月)','Q4 (10-12月)'];
var quarterOpts = ''; var quarterOpts = '';
for (var qi = 0; qi < 4; qi++) { for (var qi = 0; qi < 4; qi++) {
quarterOpts += '<option value="' + qi + '"' + (String(qi) === state.expenseQuarter ? ' selected' : '') + '>' + qLabels[qi] + '</option>'; quarterOpts += '<option value="' + qi + '">' + qLabels[qi] + '</option>';
} }
// 月份/季度日期选择器 // 月份/季度日期选择器
var dateSelect = ''; var dateSelect = '';
if (view === 'monthly') { if (view === 'monthly') {
dateSelect = '<span class="text-xs text-slate-500 ml-2">月份:</span><select onchange="setExpenseMonth(this.value)" class="text-xs font-medium py-1 px-2.5 cursor-pointer" style="appearance:none;-webkit-appearance:none;background-color:transparent;border:0;outline:none;background:url(&apos;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&apos;) no-repeat right 4px center;padding-right:22px;min-height:30px">' + monthOpts + '</select>'; dateSelect = '<span class="text-sm text-slate-500 ml-2">月份:</span><select onchange="setExpenseMonth(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(&apos;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&apos;) no-repeat right 4px center;padding-right:22px;min-height:30px"><option value=""' + (!state.expenseMonth?' selected':'') + '>请选择</option>' + monthOpts.replace('value="' + state.expenseMonth + '"', 'value="' + state.expenseMonth + '" selected') + '</select>';
} else if (view === 'quarterly') { } else if (view === 'quarterly') {
dateSelect = '<span class="text-xs text-slate-500 ml-2">季度:</span><select onchange="setExpenseQuarter(this.value)" class="text-xs font-medium py-1 px-2.5 cursor-pointer" style="appearance:none;-webkit-appearance:none;background-color:transparent;border:0;outline:none;background:url(&apos;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&apos;) no-repeat right 4px center;padding-right:22px;min-height:30px">' + quarterOpts + '</select>'; dateSelect = '<span class="text-sm text-slate-500 ml-2">季度:</span><select onchange="setExpenseQuarter(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(&apos;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&apos;) no-repeat right 4px center;padding-right:22px;min-height:30px">' + quarterOpts.replace('value="' + state.expenseQuarter + '"', 'value="' + state.expenseQuarter + '" selected') + '</select>';
} }
// Toolbar // Toolbar
var toolbar = '<span class="text-xs text-slate-500">视图:</span><select onchange="setExpenseView(this.value)" class="text-xs font-medium py-1 px-2.5 cursor-pointer" style="appearance:none;-webkit-appearance:none;background-color:transparent;border:0;outline:none;background:url(&apos;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&apos;) no-repeat right 4px center;padding-right:22px;min-height:30px"><option value="total"' + (view==='total'?' selected':'') + '>总视图</option><option value="quarterly"' + (view==='quarterly'?' selected':'') + '>季度视图</option><option value="monthly"' + (view==='monthly'?' selected':'') + '>月度视图</option></select><span class="text-xs text-slate-500 ml-3">类型:</span><select onchange="setExpenseFilter(this.value)" class="text-xs font-medium py-1 px-2.5 cursor-pointer" style="appearance:none;-webkit-appearance:none;background-color:transparent;border:0;outline:none;background:url(&apos;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&apos;) no-repeat right 4px center;padding-right:22px;min-height:30px"><option value="全部"' + (typeFilter==='全部'?' selected':'') + '>全部 (' + records.length + ')</option>'; var toolbar = '<span class="text-sm text-slate-500">视图:</span><select onchange="setExpenseView(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(&apos;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&apos;) 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="setExpenseFilter(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(&apos;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&apos;) no-repeat right 4px center;padding-right:22px;min-height:30px"><option value="全部"' + (typeFilter==='全部'?' selected':'') + '>全部 (' + records.length + ')</option>';
EXPENSE_TYPES.forEach(function(t) { 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 += '<option value="' + t + '"' + (typeFilter===t?' selected':'') + '>' + t + ' (' + records.filter(function(r){return r.expense_type===t}).length + ')</option>';
}); });
toolbar += '</select>' + dateSelect; toolbar += '</select>' + dateSelect;
// 排序箭头
var sortArrow = function(key) {
var arrow = key === sortKey ? (sortAsc === 1 ? ' ↑' : ' ↓') : '';
return '<span class="text-slate-400 text-xs cursor-pointer" onclick="toggleExpenseSort(\'' + key + '\')">' + arrow + '</span>';
};
// 表格行 // 表格行
var tableRows = ''; var tableRows = '';
if (filtered.length) { if (filtered.length) {
filtered.forEach(function(r) { filtered.forEach(function(r) {
tableRows += '<tr class="border-b border-slate-100 hover:bg-slate-50 cursor-pointer" onclick="openExpenseEdit(' + r.id + ')"><td class="p-2 font-medium text-center align-middle" style="width:200px">' + esc(r.expense_type) + '</td><td class="p-2 text-center align-middle" style="width:200px">' + (r.expense_month || '—') + '</td><td class="p-2 text-center align-middle font-medium" style="width:200px">' + money(r.amount) + '</td><td class="p-2 text-center align-middle font-medium" style="width:200px">' + money(r.incurred_amount) + '</td><td class="p-2 text-center align-middle text-slate-500" style="width:200px">' + (esc(r.notes) || '—') + '</td></tr>'; 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="openExpenseEdit(' + 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 { } else {
var emptyMsg = view === 'monthly' ? '该月份暂无费用记录' : view === 'quarterly' ? '该季度暂无费用记录' : '暂无费用记录'; var emptyMsg = view === 'monthly' ? '该月份暂无费用记录' : view === 'quarterly' ? '该季度暂无费用记录' : '暂无费用记录';
tableRows = '<tr><td colspan="5" class="p-6 text-center text-slate-400">' + emptyMsg + '</td></tr>'; tableRows = '<tr><td colspan="6" class="p-6 text-center text-slate-400">' + emptyMsg + '</td></tr>';
} }
// 模态框 // 模态框 monthOpts for form (with current value preselected)
var modal = '<div id="expenseModal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/40" onclick="closeExpenseModal()"><div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg mx-4" onclick="event.stopPropagation()"><div class="sticky top-0 z-10 bg-white/95 backdrop-blur border-b border-slate-100 px-6 py-4 flex items-center justify-between"><h3 class="text-lg font-bold text-slate-800" id="expenseModalTitle">新增费用</h3><div class="flex items-center gap-2"><button class="btn btn-ghost btn-sm text-red-600 hidden" id="expenseDeleteBtn" onclick="deleteExpenseItem()">删除</button><button class="btn btn-ghost btn-sm rounded-full w-8 h-8 p-0" onclick="closeExpenseModal()"><i data-lucide="x"></i></button></div></div><form onsubmit="saveExpense(event)" class="p-6 grid gap-4" novalidate><input type="hidden" name="expense_id" value=""><div class="grid grid-cols-2 gap-3"><label class="block"><span class="text-xs text-slate-500 mb-1 block">费用类型 <span class="text-red-500">*</span></span><select name="expense_type" required class="form-ctrl bg-white"><option value="">请选择</option>'; 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="expenseModal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-black/40" onclick="closeExpenseModal()"><div class="bg-white rounded-2xl shadow-2xl w-full max-w-lg mx-4" onclick="event.stopPropagation()"><div class="sticky top-0 z-10 bg-white/95 backdrop-blur border-b border-slate-100 px-6 py-4 flex items-center justify-between"><h3 class="text-lg font-bold text-slate-800" id="expenseModalTitle">新增费用</h3><div class="flex items-center gap-2"><button class="btn btn-ghost btn-sm text-red-600 hidden" id="expenseDeleteBtn" onclick="deleteExpenseItem()">删除</button><button class="btn btn-ghost btn-sm rounded-full w-8 h-8 p-0" onclick="closeExpenseModal()"><i data-lucide="x"></i></button></div></div><form onsubmit="saveExpense(event)" class="p-6 grid gap-4" novalidate><input type="hidden" name="expense_id" value=""><div class="grid grid-cols-2 gap-3"><label class="block"><span class="text-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>'; }); EXPENSE_TYPES.forEach(function(t) { modal += '<option>' + t + '</option>'; });
modal += '</select></label><label class="block"><span class="text-xs text-slate-500 mb-1 block">月份 <span class="text-red-500">*</span></span><select name="expense_month" required class="form-ctrl bg-white">' + monthOpts + '</select></label></div><div class="grid grid-cols-2 gap-3"><label class="block"><span class="text-xs text-slate-500 mb-1 block">金额(元)</span><input name="amount" type="number" step="0.01" class="form-ctrl" placeholder="0.00"></label><label class="block"><span class="text-xs text-slate-500 mb-1 block">已发生金额(元)</span><input name="incurred_amount" type="number" step="0.01" class="form-ctrl" placeholder="0.00"></label></div><label class="block"><span class="text-xs text-slate-500 mb-1 block">费用说明</span><textarea name="notes" class="form-ctrl" rows="3" placeholder="备注信息"></textarea></label><div class="flex justify-end gap-3 pt-2"><button type="button" class="btn btn-ghost btn-sm px-6" onclick="closeExpenseModal()">取消</button><button type="submit" class="btn btn-primary btn-sm px-8">保存</button></div></form></div></div>'; 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="closeExpenseModal()">取消</button><button type="submit" class="btn btn-primary btn-sm px-8">保存</button></div></form></div></div>';
var target = document.querySelector("#financeExpense") || document.querySelector("#financeTabExpense") || document.querySelector("#expense"); var target = document.querySelector("#financeExpense") || document.querySelector("#financeTabExpense") || document.querySelector("#expense");
if (!target) return; if (!target) return;
target.innerHTML = '<div class="grid gap-4">' + 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="openExpenseModal()">新增费用</button></div></div>' + '<div class="card p-3"><div class="flex justify-between items-center"><div class="flex items-center gap-2">' + toolbar + '</div><button class="btn btn-primary btn-sm" onclick="openExpenseModal()">新增费用</button></div></div>' +
'<div class="grid grid-cols-3 gap-3">' + '<div class="grid grid-cols-3 gap-3">' +
'<div class="metric-card p-3"><span class="flex items-center gap-2 text-xs text-slate-500">费用记录</span><strong class="mt-2 block text-xl">' + filtered.length + '</strong></div>' + '<div class="metric-card p-3"><span class="flex items-center gap-2 text-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-xs text-slate-500">总费用</span><strong class="mt-2 block text-xl">' + money(totalAmount) + '</strong></div>' + '<div class="metric-card p-3"><span class="flex items-center gap-2 text-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-xs text-slate-500">已发生金额</span><strong class="mt-2 block text-xl">' + money(totalIncurred) + '</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>' + '</div>' +
modal + modal +
'<div class="card p-4"><div class="overflow-x-auto"><table class="w-full text-sm"><thead><tr class="bg-slate-50 border-b border-slate-200"><th class="p-2 text-center font-semibold" style="width:200px">费用类型</th><th class="p-2 text-center font-semibold" style="width:200px">月份</th><th class="p-2 text-center font-semibold" style="width:200px">金额</th><th class="p-2 text-center font-semibold" style="width:200px">已发生金额</th><th class="p-2 text-center font-semibold" style="width:200px">费用说明</th></tr></thead><tbody>' + tableRows + '</tbody></table></div></div>' + '<div 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="toggleExpenseSort(\'expense_month\')">月份' + sortArrow('expense_month') + '</th><th class="p-2 text-center font-semibold cursor-pointer select-none" onclick="toggleExpenseSort(\'expense_type\')">费用类型' + sortArrow('expense_type') + '</th><th class="p-2 text-center font-semibold cursor-pointer select-none" onclick="toggleExpenseSort(\'status\')">状态' + sortArrow('status') + '</th><th class="p-2 text-center font-semibold cursor-pointer select-none" onclick="toggleExpenseSort(\'amount\')">金额' + sortArrow('amount') + '</th><th class="p-2 text-center font-semibold cursor-pointer select-none" onclick="toggleExpenseSort(\'incurred_amount\')">已发生金额' + sortArrow('incurred_amount') + '</th><th class="p-2 text-center font-semibold">费用说明</th></tr></thead><tbody>' + tableRows + '</tbody></table></div></div>' +
'</div>'; '</div>';
if (window.lucide) window.lucide.createIcons(); if (window.lucide) window.lucide.createIcons();
} }
window.toggleExpenseSort = function(key) {
var cur = state.expenseSort || {};
if (cur.key === key) { cur.asc = !cur.asc; }
else { cur.key = key; cur.asc = true; }
state.expenseSort = cur;
renderExpense();
};
window.setExpenseView = function(v) { state.expenseView = v; renderExpense(); }; window.setExpenseView = function(v) { state.expenseView = v; renderExpense(); };
window.setExpenseFilter = function(v) { state.expenseFilter = v; renderExpense(); }; window.setExpenseFilter = function(v) { state.expenseFilter = v; renderExpense(); };
window.setExpenseMonth = function(v) { state.expenseMonth = v; renderExpense(); }; window.setExpenseMonth = function(v) { state.expenseMonth = v; renderExpense(); };
@@ -109,6 +149,7 @@ window.openExpenseModal = function() {
var form = document.querySelector("#expenseModal form"); var form = document.querySelector("#expenseModal form");
form.reset(); form.reset();
form.querySelector('[name="expense_id"]').value = ""; form.querySelector('[name="expense_id"]').value = "";
form.querySelector('[name="status"]').value = "计入费用";
document.querySelector("#expenseModalTitle").textContent = "新增费用"; document.querySelector("#expenseModalTitle").textContent = "新增费用";
document.querySelector("#expenseDeleteBtn").classList.add("hidden"); document.querySelector("#expenseDeleteBtn").classList.add("hidden");
document.querySelector("#expenseModal").classList.remove("hidden"); document.querySelector("#expenseModal").classList.remove("hidden");
@@ -130,6 +171,7 @@ window.openExpenseEdit = function(id) {
setVal("amount", r.amount); setVal("amount", r.amount);
setVal("incurred_amount", r.incurred_amount); setVal("incurred_amount", r.incurred_amount);
setVal("notes", r.notes); setVal("notes", r.notes);
setVal("status", r.status || "计入费用");
document.querySelector("#expenseModalTitle").textContent = "编辑费用"; document.querySelector("#expenseModalTitle").textContent = "编辑费用";
document.querySelector("#expenseDeleteBtn").classList.remove("hidden"); document.querySelector("#expenseDeleteBtn").classList.remove("hidden");
document.querySelector("#expenseModal").classList.remove("hidden"); document.querySelector("#expenseModal").classList.remove("hidden");
@@ -139,9 +181,9 @@ window.saveExpense = async function(event) {
event.preventDefault(); event.preventDefault();
var form = event.target; var form = event.target;
var data = Object.fromEntries(new FormData(form).entries()); var data = Object.fromEntries(new FormData(form).entries());
// 数字字段空值转 0避免线上 MySQL 严格模式报错
if (data.amount === '' || data.amount === undefined) data.amount = 0; if (data.amount === '' || data.amount === undefined) data.amount = 0;
if (data.incurred_amount === '' || data.incurred_amount === undefined) data.incurred_amount = 0; if (data.incurred_amount === '' || data.incurred_amount === undefined) data.incurred_amount = 0;
if (!data.status) data.status = '计入费用';
var isEdit = !!data.expense_id; var isEdit = !!data.expense_id;
delete data.expense_id; delete data.expense_id;

View File

@@ -111,9 +111,9 @@ function renderFinance() {
const qLabels2 = ["Q1 (1-3月)","Q2 (4-6月)","Q3 (7-9月)","Q4 (10-12月)"]; 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 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 toolQuarterSelect = qLabels2.map((l,i) => '<option value="'+i+'" '+(i===state.finQuarter?'selected':'')+'>'+l+'</option>').join("");
const toolDateSelect = state.finView==='monthly'?'<span class="text-xs text-slate-500 ml-2">月份:</span><select onchange="state.finMonth=this.value;renderFinance()" class="text-xs font-medium py-1 px-2.5 cursor-pointer" style="appearance:none;-webkit-appearance:none;background-color:transparent;border:0;outline:none;background:url(&apos;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&apos;) no-repeat right 4px center;padding-right:22px;min-height:30px">'+toolMonthSelect+'</select>':state.finView==='quarterly'?'<span class="text-xs text-slate-500 ml-2">季度:</span><select onchange="state.finQuarter=parseInt(this.value);localStorage.setItem(\'opc-fin-quarter\',this.value);renderFinance()" class="text-xs font-medium py-1 px-2.5 cursor-pointer" style="appearance:none;-webkit-appearance:none;background-color:transparent;border:0;outline:none;background:url(&apos;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&apos;) no-repeat right 4px center;padding-right:22px;min-height:30px">'+toolQuarterSelect+'</select>':''; 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(&apos;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&apos;) 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(&apos;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&apos;) no-repeat right 4px center;padding-right:22px;min-height:30px">'+toolQuarterSelect+'</select>':'';
const finHeaderBase = `<span class="text-xs text-slate-500">视图:</span><select onchange="setFinView(this.value)" class="text-xs font-medium py-1 px-2.5 cursor-pointer" style="appearance:none;-webkit-appearance:none;background-color:transparent;border:0;outline:none;background:url(&apos;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&apos;) 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 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(&apos;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&apos;) 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 finAddBtn = `<button class="btn btn-primary btn-sm" onclick="openFinanceModal()">新增财务项目</button>`; 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('已签约')" 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>`;
@@ -296,7 +296,7 @@ function renderFinance() {
const subtitle = isUnsigned const subtitle = isUnsigned
? '合同 → 毛利 → 成本 → 项目利润' ? '合同 → 毛利 → 成本 → 项目利润'
: '合同 → 确收 → 毛利 → 成本 → 项目利润 → 回款 → 已付 → 现金流 → 执行率 → 毛利率 → 回款率 → 付款率'; : '合同 → 确收 → 毛利 → 成本 → 项目利润 → 回款 → 已付 → 现金流 → 执行率 → 毛利率 → 回款率 → 付款率';
return card(`<div class="grid ${cardGrid} gap-3 mb-3">${cards.map(([l, v, c]) => '<div class="metric-card p-3"><span class="flex items-center gap-2 text-xs text-slate-500">' + l + '</span><strong class="mt-2 block text-xl ' + c + '">' + v + '</strong></div>').join("")}</div>`, "p-4") + return card(`<div class="grid ${cardGrid} gap-3 mb-3">${cards.map(([l, v, c]) => '<div class="metric-card p-3"><span class="flex items-center gap-2 text-sm text-slate-500">' + l + '</span><strong class="mt-2 block text-xl ' + c + '">' + v + '</strong></div>').join("")}</div>`, "p-4") +
card(`<h3 class="text-sm font-bold text-slate-700">项目财务明细</h3><p class="text-xs text-slate-400 mb-3">${subtitle}</p><div class="overflow-x-auto"><table class="w-full text-sm">${thead}${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">${subtitle}</p><div class="overflow-x-auto"><table class="w-full text-sm">${thead}${tbody}</table></div>`, "p-4");
}; };
@@ -304,7 +304,9 @@ function renderFinance() {
const tdRow = (pf, rev, payment, cost, paid, gross) => { const tdRow = (pf, rev, payment, cost, paid, gross) => {
const cashflow = payment - paid; const cashflow = payment - paid;
const exe = rev && pf.sign_amount ? Math.round(rev / pf.sign_amount * 100) + '%' : '<span class="text-slate-300">—</span>'; const exe = rev && pf.sign_amount ? Math.round(rev / pf.sign_amount * 100) + '%' : '<span class="text-slate-300">—</span>';
const payR = rev && payment ? Math.round(payment / rev * 100) + '%' : '<span class="text-slate-300">—</span>'; const payRVal = rev && payment ? Math.round(payment / rev * 100) : null;
const payRCls = payRVal === null ? '' : payRVal < 30 ? 'text-red-600' : payRVal < 80 ? 'text-amber-600' : 'text-green-600';
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 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 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 st = pf.status === '已签约' ? '<span class="text-green-600">已签约</span>' : '<span class="text-amber-600">待签约</span>';
@@ -379,6 +381,7 @@ function renderFinance() {
const gross = sumBudget(pf, "gross"); const gross = sumBudget(pf, "gross");
const cost = sumExpense(pf, "cost"); const cost = sumExpense(pf, "cost");
const paid = sumExpense(pf, "paid"); const paid = sumExpense(pf, "paid");
if (!rev && !payment && !cost && !paid && !gross) return;
sumRev += rev; sumPay += payment; sumCost += cost; sumPaid += paid; sumGross += gross; sumRev += rev; sumPay += payment; sumCost += cost; sumPaid += paid; sumGross += gross;
rows.push(isUnsigned ? tdRowUnsigned(pf, cost, gross) : tdRow(pf, rev, payment, cost, paid, gross)); rows.push(isUnsigned ? tdRowUnsigned(pf, cost, gross) : tdRow(pf, rev, payment, cost, paid, gross));
}); });

View File

@@ -4,6 +4,15 @@ function renderHome() {
const { summary, financeMonthly } = state.data; const { summary, financeMonthly } = state.data;
const m = summary.metrics; const m = summary.metrics;
const moneyInt = (v) => `${Math.round(Number(v || 0)).toLocaleString("zh-CN")}`; const moneyInt = (v) => `${Math.round(Number(v || 0)).toLocaleString("zh-CN")}`;
// 回款提醒
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 payRateCls = yrPayRate < 30 ? 'text-red-600' : yrPayRate < 80 ? 'text-amber-600' : 'text-green-600';
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>' +
'</div>' : '';
const rows1 = [ const rows1 = [
["年度累计", moneyInt(m.signed_annual || m.signed_amount)], ["年度累计", moneyInt(m.signed_annual || m.signed_amount)],
["本季度累计", moneyInt(m.signed_q2 || 0)], ["本季度累计", moneyInt(m.signed_q2 || 0)],
@@ -105,15 +114,15 @@ function renderHome() {
} }
document.querySelector("#home").innerHTML = ` document.querySelector("#home").innerHTML = `
<div class="grid gap-5"> <div class="grid gap-5">
<div class="flex items-center gap-2"> ${state.tenant === "总工作台" ? "" : `<div class="grid grid-cols-4 gap-3">
<span class="text-xs text-slate-500">筛选:</span> ${[
<select id="homeFilter" class="text-xs font-medium py-1.5 px-3 rounded border border-slate-200 bg-white cursor-pointer" onchange="renderHomeCards()" style="appearance:none;-webkit-appearance:none;padding-right:28px;background:url(&apos;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&apos;) no-repeat right 8px center"> ["项目管理", m.total_projects, "finance"],
<option value="all">全部时间</option> ["重点工作与台账", m.total_proposals, "projects"],
<option value="year">本年度</option> ["业务方案", m.total_products, "proposals"],
<option value="quarter">本季度</option> ["产品迭代", m.upcoming_products, "products"],
<option value="month">本月</option> ].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("")}
</select> </div>`}
</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> ${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 = [ var d = [

View File

@@ -9,7 +9,7 @@ const state = {
selectedProject: null, selectedProject: null,
taskQuery: "", taskQuery: "",
taskView: localStorage.getItem("opc-task-view") || "detail", taskView: localStorage.getItem("opc-task-view") || "detail",
finView: localStorage.getItem("opc-fin-view") || "overview", finView: "overview",
proposalTab: "standard", proposalTab: "standard",
chart: null, chart: null,
chart2: null, chart2: null,
@@ -196,7 +196,6 @@ window.switchTab = switchTab;
window.setFinView = (view) => { window.setFinView = (view) => {
state.finView = view; state.finView = view;
localStorage.setItem("opc-fin-view", view);
renderFinance(); renderFinance();
}; };
window.switchFinFilter = (filter) => { window.switchFinFilter = (filter) => {

View File

@@ -76,7 +76,7 @@
<header class="topbar border-b border-slate-200 bg-white px-8 py-5"> <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 items-center gap-3 w-full">
<div class="flex-1"> <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.3</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.5</span></p>
<div class="flex items-center gap-4 mt-1"> <div class="flex items-center gap-4 mt-1">
<h1 class="text-2xl font-semibold" id="workspaceTitle">科普 OPC 工作台</h1> <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"> <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">