Commit 9e694db5 by imwangxiaozhou

feat: 初始化广联审计管理系统项目

添加完整的项目代码,包含Streamlit多页签Web管理界面,支持E盾-智慧车管和嘀加-旧版本两大业务的全流程审计,涵盖数据核对、报表生成、费用分摊、数据同步、配置管理、日志查询及运维管理模块,同时提供数据库初始化脚本、依赖配置、工具脚本、测试代码和配套文档资源。
0 parents
Showing 113 changed files with 4172 additions and 0 deletions
# ============================================
# 文档类文件 - 忽略 Office、PDF 等文档格式
# ============================================
# Microsoft Office
*.doc
*.docx
*.xls
*.xlsx
*.ppt
*.pptx
*.pps
*.ppsx
*.pot
*.potx
# OpenOffice / LibreOffice
*.odt
*.ods
*.odp
# PDF
*.pdf
# 其他文档格式
*.rtf
*.csv
*.wps
# 压缩包文件
*.zip
*.rar
*.7z
*.tar
*.gz
# Python 编译缓存
__pycache__/
*.pyc
*.pyo
*.pyd
# ============================================
# 项目特定 - 忽略数据/输出目录中的文档
# ============================================
# 审计数据文档目录(Excel 数据源文件)
1-business_data_audit/1-documents/
# Default ignored files
/shelf/
/workspace.xml
__init__.py
\ No newline at end of file \ No newline at end of file
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>
\ No newline at end of file \ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="PyUnresolvedReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true">
<option name="ignoredIdentifiers">
<list>
<option value="code.ApiQnA.FastApi.get_semantic_answer_lang_chain" />
</list>
</option>
</inspection_tool>
</profile>
</component>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.9" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9" project-jdk-type="Python SDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/glsx-audit.iml" filepath="$PROJECT_DIR$/glsx-audit.iml" />
</modules>
</component>
</project>
\ No newline at end of file \ No newline at end of file
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python Debugger: Current File",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
},
{
"name": "Streamlit Debug",
"type": "python",
"request": "launch",
"program": "D:\\software\\Python\\basic\\Python3.10\\Scripts\\streamlit.exe",
"args": ["run", "${file}", "--server.runOnSave", "true"],
"console": "integratedTerminal",
"justMyCode": true
}
]
}
\ No newline at end of file \ No newline at end of file
### 审计流程
1.从邮箱中获取商务拆分好的原始数据[存储到D:\work\2.需求\11.审计\开发\1.文档\原始数据\应拆分数据-2023年1-3月]
2.梳理需要的表格与sheet
- 4.数据源-激活调整用23年3月-陈冰恋.xlsx[名字不固定,只能说类似]
- 1.1-汇通安装结算汇总-其他[名称不固定,但目前只包括汇通*,续费*,渠道*,趣融* 这些结构,当存在多个表格时,应该只取写了结算的sheet]
- 1.4续费汇总
- *渠道*
- 1.2-汇通加融包结算汇总
- 3.拆分数据-渠道2023年3月E盾数据-柳云飞.xlsx
- Sheet2[名称更加不固定,请通过业务时间进行甄别]
3.将不同类型的表导入到mysql中
| sheet类型 | 对应mysql表 |
| --- | --- |
| 汇通* | d_es_huitong_raw_data |
| 续费* | d_es_xufei_raw_data |
| 渠道* | d_es_channel_raw_data |
| 趣融* | d_es_qr_raw_data |
| 渠道*柳云飞 | d_es_lyf_raw_data |
先手动对齐表头,表明,sheet名称(商务给的表结构无法保证,不要想用代码一次性规范)
a.先预存各个sheet的表头,目录:[D:\work\2.需求\11.审计\开发\1.文档\原始数据\预留标准结构]
b.用预存表头核对提供表单,少则补,多则剃
c.用预存表头替换提供表单数据
d.将其中涉及价格的数据当数量是负值时置负值(特别注意渠道表格) 将硬件和服务和安装都置为负值
e.将涉及到卡等不需要的硬件时删除指定列
f.lyf数据表(lyf数据表需要手动拆分) 需要讲单价的符号和数量保持一致,服务不含税需要从对应的服务中填写
导入到mysql
4.生成明细数据
x.生成验证数据(请查看DBeaver中脚本: 审计查询)
- 验证维度
- 总收入,门店收入
- 总数量,门店数量
5.与财务同学进行核验
6.修改设备号,保证设备号不重复
\ No newline at end of file \ No newline at end of file
This diff could not be displayed because it is too large.
File mode changed
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file \ No newline at end of file
File mode changed
File mode changed
File mode changed
[server]
# Streamlit 服务启动端口,默认为 8509
port = 8509
# 是否开启自动保存时重新运行
runOnSave = true
[browser]
# 配置浏览器端是否显示“运行中”状态
gatherUsageStats = false
1.文件后缀带的名称 (文件名后缀通常包含商务人员姓名)
2.文件的大小 (若存在同名/类似文件,以体积较大的文件为准,因为其中包含商务拆分的明细数据)
拆分数据-E盾明细.xlsx: 激活调整,张洁怡|张荣慧
拆分数据-渠道柳云飞.xlsx: 渠道,柳云飞
财务-激活调整用.xlsx:数据源-激活调整用
渠道嘀加-柳云飞.xlsx:渠道,柳云飞
拆分数据.xlsx:激活调整用,张洁怡
# -*- coding:utf-8 -*-
from __future__ import print_function
import time
# import MySQLdb
import pymysql as MySQLdb
import sys
# reload(sys)
# sys.setdefaultencoding('utf8')
#
def paddstr(strx):
# return "NULL" if strx == None else "\'" + MySQLdb.escape_string(str(strx)).decode() + "\'"
return (
"NULL"
if strx == None
else "'" + MySQLdb.converters.escape_string(str(strx)) + "'"
)
def paddnum(numx, default="NULL"):
return default if numx == None else str(numx)
class MySQL:
"""对MySQLdb常用函数进行封装的类"""
error_code = "" # MySQL错误号码
_instance = None # 本类的实例
_conn = None # 数据库conn
_cur = None # 游标
_TIMEOUT = 30 # 默认超时30秒
_timecount = 0
def __init__(self, dbconfig):
"构造器:根据数据库连接参数,创建MySQL连接"
try:
self._conn = MySQLdb.connect(
host=dbconfig["host"],
port=dbconfig["port"],
user=dbconfig["user"],
passwd=dbconfig["passwd"],
db=dbconfig["db"],
charset=dbconfig["charset"],
)
except MySQLdb.Error as e:
self.error_code = e.args[0]
error_msg = "MySQL error! ", e.args[0], e.args[1]
print(error_msg)
# 如果没有超过预设超时时间,则再次尝试连接,
if self._timecount < self._TIMEOUT:
interval = 5
self._timecount += interval
time.sleep(interval)
return self.__init__(dbconfig)
else:
raise Exception(error_msg)
self._cur = self._conn.cursor()
self._instance = MySQLdb
def query(self, sql):
"执行 SELECT 语句"
try:
# self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql)
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def queryList(self, sqlList):
"执行 SELECT 语句"
try:
for sql in sqlList:
# self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql)
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def update(self, sql):
"执行 UPDATE 及 DELETE 语句"
try:
# self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql)
self._conn.commit()
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def updateList(self, sqlList):
"执行 UPDATE 及 DELETE 语句"
try:
for sql in sqlList:
# self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql)
self._conn.commit()
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def insert(self, sql, data=None):
"执行 INSERT 语句。如主键为自增长int,则返回新生成的ID"
try:
self._cur.execute("SET NAMES utf8")
if data == None:
self._cur.execute(sql)
else:
self._cur.executemany(sql, data)
self._conn.commit()
return True
return self._conn.insert_id()
except MySQLdb.Error as e:
self.error_code = e.args[0]
return False
def callproc(self, procname, *arg):
try:
self._cur.execute("SET NAMES utf8")
self._cur.callproc(procname, arg)
self._conn.commit()
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def fetchAllRows(self):
"返回结果列表"
return self._cur.fetchall()
def fetchOneRow(self):
"返回一行结果,然后游标指向下一行。到达最后一行以后,返回None"
return self._cur.fetchone()
def getRowCount(self):
"获取结果行数"
return self._cur.rowcount
def commit(self):
"数据库commit操作"
self._conn.commit()
def rollback(self):
"数据库回滚操作"
self._conn.rollback()
def __del__(self):
"释放资源(系统GC自动调用)"
try:
self._cur.close()
self._conn.close()
except:
pass
def close(self):
"关闭数据库连接"
self.__del__()
class StringBuilder:
def __init__(self):
self.strings = []
def append(self, string):
self.strings.append(string)
def __str__(self):
return "".join(self.strings)
from dateutil.relativedelta import *
def add_one_month(date, i):
# Add one month to the date using timedelta
next_month = date + relativedelta(months=+i)
# print(next_month)
new_date = next_month.replace(day=1)
return new_date
-- ==============================================================================
-- 嘀加业务数据核对 SQL 模板
-- 变量说明:
-- {year}: 业务年份 (如 2025)
-- ==============================================================================
-- 1. 商务数据和财务数据对比 (以财务为准)
-- 目的:找出财务账单中有记录但商务明细中缺失或金额不一致的项
SELECT
A.cus_name AS '客户名称',
A.sale_type AS '渠道/销售类型',
A.monthx AS '月份',
A.total AS '财务数量',
B.total AS '商务数量',
(A.total - IFNULL(B.total, 0)) AS '数量差异',
A.income AS '财务收入',
IFNULL(B.income, 0) AS '商务收入',
(A.income - IFNULL(B.income, 0)) AS '收入差异',
A.costx AS '财务成本',
IFNULL(B.costx, 0) AS '商务成本',
(A.costx - IFNULL(B.costx, 0)) AS '成本差异'
FROM (
SELECT
TRIM(cus_name) AS cus_name,
DATE_FORMAT(finance_time, '%Y-%m') AS monthx,
sale_type,
SUM(CASE WHEN product_type = '硬件' THEN total ELSE 0 END) AS total,
SUM(income) AS income,
SUM(cost) AS costx
FROM dj_{year}_settlment_order_finance
WHERE business_type = 'SAAS系统订阅服务—旧版本'
GROUP BY cus_name, monthx, sale_type
) AS A
LEFT JOIN (
SELECT
cus_name,
monthx,
sale_type,
SUM(tmp.totalx) AS total,
SUM(tmp.incomex) AS income,
SUM(costx) AS costx
FROM (
SELECT
TRIM(cus_name) AS cus_name,
DATE_FORMAT(finance_time, '%Y-%m') AS monthx,
sale_type,
(CASE WHEN product_type = '硬件' THEN total ELSE 0 END) AS totalx,
(total * (IFNULL(hw_unit_price, 0) + IFNULL(pk_unit_price, 0) + IFNULL(install_unit_price, 0))) AS incomex,
cost AS costx
FROM dj_{year}_settlment_order
WHERE product_type IN ('硬件')
AND business_type = 'SAAS系统订阅服务—旧版本'
) tmp
GROUP BY tmp.cus_name, tmp.monthx, sale_type
) AS B ON (B.cus_name = A.cus_name AND A.monthx = B.monthx AND A.sale_type = B.sale_type)
WHERE ABS(A.income - IFNULL(B.income, 0)) > 1.0;
-- 2. 商务数据和财务数据对比 (以商务为准)
-- 目的:找出商务明细中有记录但财务账单中缺失的项
SELECT
B.cus_name AS '客户名称',
B.sale_type AS '渠道/销售类型',
B.monthx AS '月份',
B.total AS '商务数量',
IFNULL(A.total, 0) AS '财务数量',
(B.total - IFNULL(A.total, 0)) AS '数量差异',
B.income AS '商务收入',
IFNULL(A.income, 0) AS '财务收入',
(B.income - IFNULL(A.income, 0)) AS '收入差异',
B.costx AS '商务成本',
IFNULL(A.costx, 0) AS '财务成本',
(B.costx - IFNULL(A.costx, 0)) AS '成本差异'
FROM (
SELECT
cus_name,
monthx,
sale_type,
SUM(tmp.totalx) AS total,
SUM(tmp.incomex) AS income,
SUM(costx) AS costx
FROM (
SELECT
TRIM(cus_name) AS cus_name,
DATE_FORMAT(finance_time, '%Y-%m') AS monthx,
sale_type,
(CASE WHEN product_type = '硬件' THEN total ELSE 0 END) AS totalx,
(total * (IFNULL(hw_unit_price, 0) + IFNULL(pk_unit_price, 0) + IFNULL(install_unit_price, 0))) AS incomex,
cost AS costx
FROM dj_{year}_settlment_order
WHERE product_type IN ('硬件')
AND business_type = 'SAAS系统订阅服务—旧版本'
) tmp
GROUP BY tmp.cus_name, tmp.monthx, sale_type
) AS B
LEFT JOIN (
SELECT
TRIM(cus_name) AS cus_name,
DATE_FORMAT(finance_time, '%Y-%m') AS monthx,
sale_type,
SUM(CASE WHEN product_type = '硬件' THEN total ELSE 0 END) AS total,
SUM(income) AS income,
SUM(cost) AS costx
FROM dj_{year}_settlment_order_finance
WHERE business_type = 'SAAS系统订阅服务—旧版本'
GROUP BY cus_name, monthx, sale_type
) AS A ON (B.cus_name = A.cus_name AND B.monthx = A.monthx AND B.sale_type = A.sale_type)
WHERE ABS(B.income - IFNULL(A.income, 0)) > 1.0;
-- 3. GPS/OBD/会员权益 专项核对
-- 目的:核对特定设备类型的商务与财务一致性
SELECT
A.cus_name AS '客户名称',
A.sale_type AS '渠道/销售类型',
A.monthx AS '月份',
A.total AS '财务数量',
B.total AS '商务数量',
(A.total - IFNULL(B.total, 0)) AS '数量差异',
A.income AS '财务收入',
IFNULL(B.income, 0) AS '商务收入',
(A.income - IFNULL(B.income, 0)) AS '收入差异'
FROM (
SELECT
TRIM(cus_name) AS cus_name,
DATE_FORMAT(finance_time, '%Y-%m') AS monthx,
sale_type,
SUM(CASE WHEN product_type = '硬件' THEN total ELSE 0 END) AS total,
SUM(income) AS income
FROM dj_{year}_settlment_order_finance
WHERE device_type IN ('GPS', 'OBD', '会员权益')
AND product_type IN ('硬件', '服务', '安装')
AND business_type = 'SAAS系统订阅服务—旧版本'
GROUP BY cus_name, monthx, sale_type
) AS A
LEFT JOIN (
SELECT
cus_name,
monthx,
sale_type,
SUM(tmp.totalx) AS total,
SUM(tmp.incomex) AS income
FROM (
SELECT
TRIM(cus_name) AS cus_name,
DATE_FORMAT(finance_time, '%Y-%m') AS monthx,
sale_type,
(CASE WHEN product_type = '硬件' THEN total ELSE 0 END) AS totalx,
(total * (IFNULL(hw_unit_price, 0) + IFNULL(pk_unit_price, 0) + IFNULL(install_unit_price, 0))) AS incomex
FROM dj_{year}_settlment_order
WHERE device_type IN ('GPS', 'OBD')
AND product_type IN ('硬件')
AND business_type = 'SAAS系统订阅服务—旧版本'
) tmp
GROUP BY tmp.cus_name, tmp.monthx, sale_type
) AS B ON (B.cus_name = A.cus_name AND A.monthx = B.monthx AND A.sale_type = B.sale_type)
WHERE ABS(A.income - IFNULL(B.income, 0)) > 1.0;
-- 追踪器的
SELECT channel as '渠道', settle_merchant as '结算客户',sn as '设备号', settle_time as '结算时间', pk_price as '套餐价格',
hw_price as '硬件价格', install_price as '安装价格', active_time as '激活时间' FROM dj_{year}_settle_details where device_type =8 AND settle_time >= '{start_time}' and settle_time < '{end_time}';
-- 记录仪&车充
SELECT channel as '渠道', settle_merchant as '结算客户',sn as '设备号',
case when device_type = 6 then '记录仪' when device_type = 12501 then '车充' end as '设备类型',
settle_time as '结算时间', pk_price as '套餐价格',
hw_price as '硬件价格', install_price as '安装价格', active_time as '激活时间' FROM dj_{year}_settle_details_record where settle_time >= '{start_time}' and settle_time < '{end_time}';
-- 退货
SELECT channel as '渠道', settle_merchant as '结算客户',sn as '设备号',
case when device_type = 8 then '记录仪' when device_type = 6 then '记录仪' when device_type = 12501 then '车充' end as '设备类型',
settle_time as '结算时间', 0-pk_price as '套餐价格',
0-hw_price as '硬件价格', 0-install_price as '安装价格', active_time as '激活时间' FROM dj_{year}_settle_details_return where settle_time >= '{start_time}' and settle_time < '{end_time}';
-- 汇总
SELECT channel as '渠道', settle_merchant as '结算客户',sn as '设备号',
'GPS' as '设备类型',
settle_time as '结算时间', pk_price as '套餐价格',
hw_price as '硬件价格', install_price as '安装价格', active_time as '激活时间',cost AS '单位成本',pk_price+hw_price+install_price AS '单价合计',1 AS '硬件数量','追踪器明细' AS '来源'
FROM dj_{year}_settle_details where device_type =8 AND settle_time >= '{start_time}' and settle_time < '{end_time}'
UNION
SELECT channel as '渠道', settle_merchant as '结算客户',sn as '设备号',
case when device_type = 6 then '记录仪' when device_type = 12501 then '车充' end as '设备类型',
settle_time as '结算时间', pk_price as '套餐价格',
hw_price as '硬件价格', install_price as '安装价格', active_time as '激活时间',cost AS '单位成本',pk_price+hw_price+install_price AS '单价合计',1 AS '硬件数量','记录仪明细' AS '来源'
FROM dj_{year}_settle_details_record where settle_time >= '{start_time}' and settle_time < '{end_time}'
UNION
SELECT channel as '渠道', settle_merchant as '结算客户',sn as '设备号',
case when device_type = 8 then 'GPS' when device_type = 6 then '记录仪' when device_type = 12501 then '车充' end as '设备类型',
settle_time as '结算时间', 0-pk_price as '套餐价格',
0-hw_price as '硬件价格', 0-install_price as '安装价格', active_time as '激活时间',cost AS '单位成本',(0-pk_price)+(0-hw_price)+(0-install_price) AS '单价合计',-1 AS '硬件数量','退货明细' AS '来源'
FROM dj_{year}_settle_details_return WHERE settle_time >= '{start_time}' and settle_time < '{end_time}'
import sys
import os
import argparse
import logging
# 将当前目录添加到 sys.path
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
sys.path.append(current_dir)
from calc_dj_income_2021 import MySQL, g_pro_biz_dbcfg
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def sync_year_details_from_2021(startTime, report_year):
"""
从 dj_2021_settle_details 表里面把当年的设备明细更新到
dj_{year}_settle_details 和 dj_{year}_settle_details_record 表里面
设备类型分别为 8 和 6
"""
bizConn = MySQL(g_pro_biz_dbcfg)
sqlList = []
# ================= 1. 同步 device_type = 8 到 dj_{year}_settle_details =================
del_year_8 = f"DELETE FROM dj_{report_year}_settle_details WHERE settle_time >= '{startTime}';"
sqlList.append(del_year_8)
insert_year_8 = f"""
INSERT INTO dj_{report_year}_settle_details (`channel`,`is_virtual`,`sn`,`iccid`,`device_type`,`material_code`,`delivery_order`,`delivery_time`,`delivery_merchant`,`active_time`,`active_merchant`,`pk_name`,
`pk_period`,`settle_merchant`,`settle_order`,`settle_time`,`pk_price`,`pk_price_tax`,`hw_price`,`hw_price_tax`,`install_price`,`install_price_tax`,`cost`,`flag`,`return`,`hw_cost`,`install_cost`)
SELECT `channel`,`is_virtual`,`sn`,`iccid`,`device_type`,`material_code`,`delivery_order`,`delivery_time`,`delivery_merchant`,`active_time`,`active_merchant`,`pk_name`,
`pk_period`,`settle_merchant`,`settle_order`,`settle_time`,`pk_price`,`pk_price_tax`,`hw_price`,`hw_price_tax`,`install_price`,`install_price_tax`,`cost`,`flag`,`return`,`hw_cost`,`install_cost`
FROM dj_2021_settle_details
WHERE settle_time >= '{startTime}' AND device_type = 8;
"""
sqlList.append(insert_year_8)
# ================= 2. 同步 device_type = 6 到 dj_{year}_settle_details_record =================
del_year_6 = f"DELETE FROM dj_{report_year}_settle_details_record WHERE settle_time >= '{startTime}';"
sqlList.append(del_year_6)
insert_year_6 = f"""
INSERT INTO dj_{report_year}_settle_details_record (`channel`,`is_virtual`,`sn`,`iccid`,`device_type`,`material_code`,`delivery_order`,`delivery_time`,`delivery_merchant`,`active_time`,`active_merchant`,`pk_name`,
`pk_period`,`settle_merchant`,`settle_order`,`settle_time`,`pk_price`,`pk_price_tax`,`hw_price`,`hw_price_tax`,`install_price`,`install_price_tax`,`cost`,`flag`,`return`,`hw_cost`,`install_cost`)
SELECT `channel`,`is_virtual`,`sn`,`iccid`,`device_type`,`material_code`,`delivery_order`,`delivery_time`,`delivery_merchant`,`active_time`,`active_merchant`,`pk_name`,
`pk_period`,`settle_merchant`,`settle_order`,`settle_time`,`pk_price`,`pk_price_tax`,`hw_price`,`hw_price_tax`,`install_price`,`install_price_tax`,`cost`,`flag`,`return`,`hw_cost`,`install_cost`
FROM dj_2021_settle_details
WHERE settle_time >= '{startTime}' AND device_type = 6;
"""
sqlList.append(insert_year_6)
# 执行 SQL
if not bizConn.updateList(sqlList):
logger.error("sync_year_details_from_2021 fail, sql=%s", ",".join(sqlList))
sys.exit(1)
else:
logger.info(f"Successfully synced data from dj_2021_settle_details to dj_{report_year}_settle_details and dj_{report_year}_settle_details_record for time >= {startTime}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Sync year details from 2021 table.")
parser.add_argument("--year", type=int, help="The report year (e.g., 2025)")
parser.add_argument("--start_time", type=str, help="Start time (YYYY-MM-DD)")
args = parser.parse_args()
report_year = args.year
startTime = args.start_time
print(f"Start sync: year={report_year}, startTime={startTime}")
sync_year_details_from_2021(startTime, report_year)
print("Sync end")
# 设备明细数据生成 (device_detail_processor.py) 相关数据库表说明
本文档记录了 `device_detail_processor.py` 在处理设备明细数据时涉及的所有数据库表及其所属数据库。
## 1. 业务逻辑数据库 (device_detail_db)
主要用于存储原始导入数据、中间临时数据以及最终生成的明细结果。
### 1.1 原始导入表 (Raw Data)
这些表用于存储从 Excel 文件中读取并初步清洗后的原始数据。
- `d_es_huitong_raw_data`: 汇通安装结算原始数据
- `d_es_xufei_raw_data`: 续费结算原始数据
- `d_es_channel_raw_data`: 渠道应收单原始数据
- `d_es_qr_raw_data`: 汇通加融包结算原始数据
- `d_es_lyf_raw_data`: 其它渠道(柳云飞)原始数据
### 1.2 拆分临时表 (Temporary Tables)
用于存储按 SN 拆分后的中间结果。
- `d_es_huitong_raw_data_tmp`: 汇通拆分临时表
- `d_es_xufei_raw_data_tmp`: 续费拆分临时表
- `d_es_channel_raw_data_tmp`: 渠道拆分临时表
- `d_es_qr_raw_data_tmp`: 趣融拆分临时表
- `d_es_lyf_raw_data_tmp`: 其它渠道拆分临时表
- `d_es_all_tmp`: 所有类型汇总后的总临时表
### 1.3 配置与结果表 (Output & Config)
- `d_rerun_conf`: 重跑配置表,记录 SN 造号的最后标识位
- `d_eshield_all_details_2025_detail`: 最终生成的完整明细表(包含所有字段)
- `d_eshield_device_details_2025`: 最终生成的设备明细表(仅包含硬件相关)
- `d_eshield_service_details_2025`: 最终生成的服务明细表(仅包含服务相关)
---
## 2. 外部查询数据库
用于补充设备激活、发货等维度的信息。
### 2.1 GPS 数据库 (gps_db)
查询设备激活及车辆相关信息。
- `d_track_info`: 设备轨迹/激活基础信息
- `d_vehicle`: 车辆信息
- `d_vehicle_workorder`: 工单信息(关联激活门店)
- `d_class`: 班组/分类信息
### 2.2 供应链数据库 (supplychain_db)
查询设备发货及仓库相关信息。
- `device_file`: 设备档案信息(发货时间、SN 关系)
- `bs_merchant_order`: 商家订单信息(关联发货门店名称)
import pandas as pd
import pymysql
import yaml
import os
def get_db_config():
"""从 config.yaml 获取数据库配置"""
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
config_path = os.path.join(base_dir, "config.yaml")
with open(config_path, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
return config.get("database", {}).get("dijia_db")
def execute_sql_file(sql_file_path, progress_callback=None, params=None):
"""
读取并执行 SQL 文件,返回每个查询的结果列表
progress_callback: 回调函数,接收 (current_index, total_count, title)
params: 变量替换字典,例如 {"year": 2025},SQL 中使用 {year} 占位
"""
db_config = get_db_config()
if not db_config:
raise ValueError("未找到 dijia_db 数据库配置")
conn = pymysql.connect(
host=db_config['host'],
port=db_config['port'],
user=db_config['user'],
password=db_config['password'],
db=db_config['db_name'],
charset=db_config['charset'],
cursorclass=pymysql.cursors.DictCursor
)
try:
with open(sql_file_path, "r", encoding="utf-8") as f:
full_sql = f.read()
# 如果提供了参数,进行变量替换
if params:
try:
full_sql = full_sql.format(**params)
except KeyError as e:
# 如果 SQL 中包含花括号但不是为了替换(如 JSON 或其他语法),可能会报错
# 简单处理:如果替换失败,保持原样或打印警告
pass
# 按分号分割多个 SQL 语句
commands = [cmd.strip() for cmd in full_sql.split(';') if cmd.strip()]
total_commands = len(commands)
results = []
with conn.cursor() as cursor:
for i, cmd in enumerate(commands):
# 预处理:过滤掉纯注释行并提取标题
lines = cmd.split('\n')
non_comment_lines = []
title = f"查询 {i+1}"
for line in lines:
stripped_line = line.strip()
if not stripped_line:
continue
if stripped_line.startswith('--') or stripped_line.startswith('##'):
# 提取第一行注释作为标题
if title == f"查询 {i+1}":
title = stripped_line.lstrip('-#').strip()
continue
non_comment_lines.append(line)
clean_command = "\n".join(non_comment_lines).strip()
if not clean_command:
continue
# 进度回调
if progress_callback:
progress_callback(i + 1, total_commands, title)
# 执行查询
cursor.execute(clean_command)
# 获取结果
data = cursor.fetchall()
if data:
df = pd.DataFrame(data)
results.append({"title": title, "data": df})
return results
finally:
conn.close()
def get_dijia_stats(year, month_str):
"""
获取指定月份在数据库中的数据量统计
year: 年份 (int)
month_str: 月份字符串 (如 "8" 或 "08")
"""
db_config = get_db_config()
if not db_config:
return None
conn = pymysql.connect(
host=db_config['host'],
port=db_config['port'],
user=db_config['user'],
password=db_config['password'],
db=db_config['db_name'],
charset=db_config['charset'],
cursorclass=pymysql.cursors.DictCursor
)
try:
# 补全月份格式
if month_str.isdigit():
target_month = f"{year}-{int(month_str):02d}"
else:
# 尝试从 "8月份" 这种字符串中提取数字
import re
match = re.search(r'(\d+)', month_str)
if match:
target_month = f"{year}-{int(match.group(1)):02d}"
else:
return {"error": f"无法从批次名称 '{month_str}' 中提取月份"}
stats = {"finance_count": 0, "order_count": 0}
with conn.cursor() as cursor:
# 1. 统计财务表
table_finance = f"dj_{year}_settlment_order_finance"
try:
cursor.execute(f"SELECT COUNT(*) as count FROM {table_finance} WHERE DATE_FORMAT(finance_time, '%%Y-%%m') = %s", (target_month,))
res_fin = cursor.fetchone()
stats['finance_count'] = res_fin['count'] if res_fin else 0
except pymysql.err.ProgrammingError as e:
if e.args[0] == 1146: # Table doesn't exist
return {"error": f"数据库表 {table_finance} 不存在,请检查数据库结构或年份配置。"}
raise e
# 2. 统计商务表
table_order = f"dj_{year}_settlment_order"
try:
cursor.execute(f"SELECT COUNT(*) as count FROM {table_order} WHERE DATE_FORMAT(finance_time, '%%Y-%%m') = %s", (target_month,))
res_ord = cursor.fetchone()
stats['order_count'] = res_ord['count'] if res_ord else 0
except pymysql.err.ProgrammingError as e:
if e.args[0] == 1146: # Table doesn't exist
return {"error": f"数据库表 {table_order} 不存在,请检查数据库结构或年份配置。"}
raise e
return stats
except Exception as e:
print(f"查询统计失败: {e}")
return {"error": f"查询统计失败: {str(e)}"}
finally:
conn.close()
-- xxxx年E盾x月设备服务数据
SELECT
A.id as 'id',
A.sn as '设备号',
A.active_time as '激活时间',
A.active_merchant as '激活商户',
A.device_period as '硬件期限',
A.settle_merchant as '结算商户',
A.settle_order as '结算单号',
A.settle_time as '结算时间',
A.device_price as '设备价格',
A.install_price as '安装价格',
B.service_price as '服务价格',
A.from_type as '来源'
FROM ( select
max(id) as id,
sn,
max(active_time) as active_time,
max(active_merchant) as active_merchant,
max(device_period) as device_period,
max(settle_merchant) as settle_merchant,
max(settle_order) as settle_order,
max(settle_time) as settle_time,
max(device_price) as device_price ,
sum(install_price) as install_price , #用于应对后续出现的设备价格为0的情况,这种情况下,存在两个设备,一个有设备价格,一个没有,但是有安装价格,把两个安装价格相加
max(from_type) as from_type
from device_detail.d_eshield_device_details_2025 where settle_time>=@start_time and settle_time<@end_time group by sn ) A
left join (select * from device_detail.d_eshield_service_details_2025 where from_type !=4 and delete_flag is null and settle_time>=@start_time and settle_time<@end_time) B on A.sn = B.sn
--xxxx年E盾x月续费数据
SELECT
id as 'id',
sn as '设备号',
active_time as '激活时间',
active_merchant as '激活商户',
service_period as '服务期限',
settle_merchant as '结算商户',
settle_order as '结算单号',
settle_time as '结算时间',
0 as '设备价格',
0 as '安装价格',
service_price as '服务价格',
4 as '来源'
from device_detail.d_eshield_service_details_2025 where from_type =4 and settle_time>=@start_time and settle_time<@end_time
\ No newline at end of file \ No newline at end of file
import streamlit as st
import importlib.util
import os
import sys
def load_module(module_name, file_path):
# 将模块所在目录加入 sys.path,以便模块内部可以正常导入同级文件
module_dir = os.path.dirname(file_path)
if module_dir not in sys.path:
sys.path.insert(0, module_dir)
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def show():
st.header("分摊全流程")
st.info("请从左侧选择业务类型以加载对应的分摊逻辑。")
def show_with_category(category):
st.header(f"分摊全流程 - {category}")
# 获取当前文件的目录
base_dir = os.path.dirname(os.path.abspath(__file__))
if category == "E盾-智慧车管":
module_path = os.path.join(base_dir, "edun", "edun_amortization.py")
try:
module = load_module("edun_amortization", module_path)
module.show()
except Exception as e:
st.error(f"加载 E盾 分摊模块失败: {e}")
elif category == "嘀加-旧版本":
module_path = os.path.join(base_dir, "dijia", "dijia_amortization.py")
try:
module = load_module("dijia_amortization", module_path)
module.show()
except Exception as e:
st.error(f"加载 嘀加 分摊模块失败: {e}")
else:
st.warning(f"未知的业务类型: {category}")
import logging
import time
import os
import sys
import argparse
import yaml
from datetime import datetime, timedelta
from decimal import Decimal
from itertools import groupby
import pandas as pd
from dateutil.relativedelta import *
# Add project/2-report_generation to sys.path to import shared modules
current_dir = os.path.dirname(os.path.abspath(__file__))
project_dir = os.path.dirname(os.path.dirname(current_dir))
report_gen_dir = os.path.join(project_dir, "2-report_generation")
if report_gen_dir not in sys.path:
sys.path.append(report_gen_dir)
from dj.MysqlUtility import MySQL, paddstr
# from base_create_table import BaseCreateTable
# from my_config.config import *
from dj.StringBuilder import StringBuilder
from dj.Utils import add_one_month
logger = logging.getLogger("deal_equity_data")
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler("import.log")
fileHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
def get_db_config():
current_dir = os.path.dirname(os.path.abspath(__file__))
project_dir = os.path.dirname(os.path.dirname(current_dir))
config_path = os.path.join(project_dir, "config.yaml")
if os.path.exists(config_path):
with open(config_path, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
db_config = config.get("database", {}).get("dijia_db", {})
return {
"host": db_config.get("host"),
"port": db_config.get("port"),
"user": db_config.get("user"),
"passwd": db_config.get("password"),
"db": db_config.get("db_name"),
"charset": db_config.get("charset", "utf8"),
}
return {
"host": "192.168.5.2",
"port": 3306,
"user": "biz_glsx_data",
"passwd": "unEKczDc",
"db": "glsx_biz_data",
"charset": "utf8",
}
g_pro_biz_dbcfg = get_db_config()
def prepare_data(year, db_config):
print(f"Preparing data for year {year}...")
conn = MySQL(db_config)
cutoff_date = f"{year + 1}-01-01 00:00:00"
#1)退货明细价格处理——将退货表的金额列设为负数
print("Step 3.1: Processing return details...")
conn.update("DROP TABLE IF EXISTS temp_dj_device_details_return")
sql_create_return = f"""
create table temp_dj_device_details_return as
select * from dj_device_details_return
where device_type in (6,12501) and settle_time < '{cutoff_date}'
"""
conn.update(sql_create_return)
conn.update("CREATE INDEX temp_dj_device_details_return_pk_price_IDX USING BTREE ON temp_dj_device_details_return (pk_price)")
conn.update("UPDATE temp_dj_device_details_return SET pk_price = -pk_price WHERE pk_price > 0")
# 2)明细数据汇总——将退货表和销售表合并
print("Step 3.2: Summarizing details...")
conn.update("DROP TABLE IF EXISTS temp_dj_device_details_modify_serins_recalc")
sql_create_main = f"""
create table temp_dj_device_details_modify_serins_recalc as
select * from dj_device_details
where device_type in (6,12501) and settle_time < '{cutoff_date}'
union
select * from temp_dj_device_details_return
where device_type in (6,12501) and settle_time < '{cutoff_date}'
"""
conn.update(sql_create_main)
# 3.3 添加索引
print("Step 3.3: Adding indexes...")
conn.update("CREATE INDEX temp_dj_device_details_modify_serins_recalc_pk_price_IDX USING BTREE ON temp_dj_device_details_modify_serins_recalc (pk_price)")
conn.update("CREATE INDEX temp_dj_device_details_modify_serins_recalc_pk_period_IDX USING BTREE ON temp_dj_device_details_modify_serins_recalc (pk_period)")
# 3.4 空值数据处理
print("Step 3.4: Handling null values...")
conn.update("UPDATE temp_dj_device_details_modify_serins_recalc SET pk_period = 24 WHERE pk_period = 0 OR pk_period IS NULL")
conn.update("UPDATE temp_dj_device_details_modify_serins_recalc SET pk_price = 0 WHERE pk_price IS NULL")
print("Data preparation complete.")
def write_sql(sql):
logger.info(sql)
# with open(
# "/sql14.txt", "a+", encoding="utf8"
# ) as fw:
# fw.write(sql.strip())
# fw.write("\n")
def paddnum_price(num):
return num if num is not None else 0
def calculate_installments(total_amount, duration_months, start_date_str):
start_date = datetime.strptime(start_date_str, "%Y-%m")
# 计算每月的分摊金额
monthly_installment = total_amount / duration_months
# 创建一个字典来存储分摊时间及对应金额
installments_map = {}
for i in range(duration_months):
installment_date = start_date + relativedelta(months=i)
installments_map[installment_date.strftime("%Y-%m")] = round(monthly_installment, 6)
return installments_map
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Calculate monthly share tracker")
parser.add_argument("--year", type=int, default=2025, help="Year for calculation")
parser.add_argument("--output_dir", type=str, default="", help="Output directory for generated files")
args = parser.parse_args()
# Ensure config is loaded
g_pro_biz_dbcfg = get_db_config()
# Prepare data based on year
prepare_data(args.year, g_pro_biz_dbcfg)
# Fallback for obd_year_list if not imported
if 'obd_year_list' not in globals():
obd_year_list = range(2020, 2031)
device_type = "6,12501"
bizConn = MySQL(g_pro_biz_dbcfg)
# 获取数据中的最大月份,用于生成文件名
max_month_sql = "SELECT DATE_FORMAT(MAX(settle_time), '%Y-%m') FROM temp_dj_device_details_modify_serins_recalc"
bizConn.query(max_month_sql)
max_month_row = bizConn.fetchAllRows()
max_month_str = max_month_row[0][0] if max_month_row and max_month_row[0][0] else f"{args.year}-12"
# 提取月份部分
try:
max_month_only = int(max_month_str.split('-')[1])
except:
max_month_only = 12
file_name = f"记录仪分摊出货汇总({args.year}年-服务分摊-截至{max_month_only}月).csv"
sql = f"select sn,settle_merchant,DATE_FORMAT(settle_time, '%Y-%m')as start_time ,pk_period,IFNULL(pk_price,0) as total_price " \
f"FROM temp_dj_device_details_modify_serins_recalc where `device_type` IN ({device_type})"
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
result = bizConn.fetchAllRows()
data = []
index_count=0
for row in result:
index_count += 1
if index_count % 10000 == 0:
print(f"Processed {index_count} rows") #
# logger.info(row)
lineValue = [row[0], row[1], row[2], str(row[3]), str(row[4])]
my_month_map = calculate_installments(row[4], row[3], row[2])
for year in obd_year_list:
monthList = ('01','02','03','04','05','06','07','08','09','10','11','12')
for month in monthList:
row_data = my_month_map.get(str(year)+"-"+str(month))
if row_data is None :
lineValue.append('0')
else:
lineValue.append(paddnum_price(row_data))
data.append(lineValue)
columns = [
"sn", "settle_merchant", "settle_time", "pk_period", "total_price",
*[f"{year}-{month:02d}分摊" for year in range(2020, 2031) for month in range(1, 13)]
]
df = pd.DataFrame(data, columns=columns)
# 转换分摊金额列为浮点数
for col in [col for col in df.columns if "分摊" in col]:
df[col] = df[col].astype(float)
# 按门店、月份、期限分组并计算总个数和总金额
grouped_df = df.groupby(["settle_merchant", "settle_time", "pk_period"]).agg({
'sn': 'count',
**{col: 'sum' for col in df.columns if "分摊" in col}
}).reset_index()
# 打印分组后的DataFrame
# print(grouped_df)
# 将结果写入文本文件
output_dir = args.output_dir if args.output_dir else os.path.dirname(os.path.abspath(__file__))
if not os.path.exists(output_dir):
os.makedirs(output_dir, exist_ok=True)
full_file_name = os.path.join(output_dir, file_name)
grouped_df.to_csv(full_file_name, index=False, sep=',')
print(f"GENERATED_CSV:{os.path.abspath(full_file_name)}")
import logging
import time
import os
import sys
import argparse
import yaml
from datetime import datetime
import pandas as pd
import numpy as np
# Add project/2-report_generation to sys.path to import shared modules
current_dir = os.path.dirname(os.path.abspath(__file__))
project_dir = os.path.dirname(os.path.dirname(current_dir))
report_gen_dir = os.path.join(project_dir, "2-report_generation")
if report_gen_dir not in sys.path:
sys.path.append(report_gen_dir)
from dj.MysqlUtility import MySQL
logger = logging.getLogger("deal_equity_data_fast")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
def get_db_config():
current_dir = os.path.dirname(os.path.abspath(__file__))
project_dir = os.path.dirname(os.path.dirname(current_dir))
config_path = os.path.join(project_dir, "config.yaml")
if os.path.exists(config_path):
with open(config_path, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
db_config = config.get("database", {}).get("dijia_db", {})
return {
"host": db_config.get("host"),
"port": db_config.get("port"),
"user": db_config.get("user"),
"passwd": db_config.get("password"),
"db": db_config.get("db_name"),
"charset": db_config.get("charset", "utf8"),
}
return {
"host": "192.168.5.2",
"port": 3306,
"user": "biz_glsx_data",
"passwd": "unEKczDc",
"db": "glsx_biz_data",
"charset": "utf8",
}
def prepare_data(year, db_config):
print(f"Preparing data for year {year}...")
conn = MySQL(db_config)
cutoff_date = f"{year + 1}-01-01 00:00:00"
# 1)退货明细价格处理——将退货表的金额列设为负数
print("Step 3.1: Processing return details...")
conn.update("DROP TABLE IF EXISTS temp_dj_device_details_return")
sql_create_return = f"""
create table temp_dj_device_details_return as
select * from dj_device_details_return
where device_type in (6,12501) and settle_time < '{cutoff_date}'
"""
conn.update(sql_create_return)
conn.update("CREATE INDEX temp_dj_device_details_return_pk_price_IDX USING BTREE ON temp_dj_device_details_return (pk_price)")
conn.update("UPDATE temp_dj_device_details_return SET pk_price = -pk_price WHERE pk_price > 0")
# 2)明细数据汇总——将退货表和销售表合并
print("Step 3.2: Summarizing details...")
conn.update("DROP TABLE IF EXISTS temp_dj_device_details_modify_serins_recalc")
sql_create_main = f"""
create table temp_dj_device_details_modify_serins_recalc as
select * from dj_device_details
where device_type in (6,12501) and settle_time < '{cutoff_date}'
union
select * from temp_dj_device_details_return
where device_type in (6,12501) and settle_time < '{cutoff_date}'
"""
conn.update(sql_create_main)
# 3.3 添加索引
print("Step 3.3: Adding indexes...")
conn.update("CREATE INDEX temp_dj_device_details_modify_serins_recalc_pk_price_IDX USING BTREE ON temp_dj_device_details_modify_serins_recalc (pk_price)")
conn.update("CREATE INDEX temp_dj_device_details_modify_serins_recalc_pk_period_IDX USING BTREE ON temp_dj_device_details_modify_serins_recalc (pk_period)")
# 3.4 空值数据处理
print("Step 3.4: Handling null values...")
conn.update("UPDATE temp_dj_device_details_modify_serins_recalc SET pk_period = 24 WHERE pk_period = 0 OR pk_period IS NULL")
conn.update("UPDATE temp_dj_device_details_modify_serins_recalc SET pk_price = 0 WHERE pk_price IS NULL")
print("Data preparation complete.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Calculate monthly share tracker (Fast Version)")
parser.add_argument("--year", type=int, default=2025, help="Year for calculation")
parser.add_argument("--output_dir", type=str, default="", help="Output directory for generated files")
args = parser.parse_args()
g_pro_biz_dbcfg = get_db_config()
prepare_data(args.year, g_pro_biz_dbcfg)
bizConn = MySQL(g_pro_biz_dbcfg)
device_type = "6,12501"
# 获取最大月份
max_month_sql = "SELECT DATE_FORMAT(MAX(settle_time), '%Y-%m') FROM temp_dj_device_details_modify_serins_recalc"
bizConn.query(max_month_sql)
max_month_row = bizConn.fetchAllRows()
max_month_str = max_month_row[0][0] if max_month_row and max_month_row[0][0] else f"{args.year}-12"
try:
max_month_only = int(max_month_str.split('-')[1])
except:
max_month_only = 12
file_name = f"记录仪分摊出货汇总({args.year}年-服务分摊-截至{max_month_only}月).csv"
# 将查询结果按 settle_merchant, settle_time, pk_period 聚合,减少内存加载的数据量
print("Fetching and aggregating data from database...")
sql = f"""
SELECT
settle_merchant,
DATE_FORMAT(settle_time, '%Y-%m') as start_time,
pk_period,
COUNT(sn) as sn_count,
SUM(IFNULL(pk_price,0)) as sum_total_price
FROM temp_dj_device_details_modify_serins_recalc
WHERE device_type IN ({device_type})
GROUP BY settle_merchant, DATE_FORMAT(settle_time, '%Y-%m'), pk_period
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
sys.exit(1)
result = bizConn.fetchAllRows()
print(f"Loaded {len(result)} aggregated rows.")
# 构建需要生成的所有月份列
obd_year_list = range(2020, 2031)
month_cols = [f"{year}-{month:02d}分摊" for year in obd_year_list for month in range(1, 13)]
# 建立一个列名到索引的映射,以便快速赋值
col_to_idx = {col: i for i, col in enumerate(month_cols)}
# 输出数据结构
processed_data = []
print("Calculating installments using vectorized logic...")
for row in result:
settle_merchant = row[0]
start_time_str = row[1]
pk_period = int(row[2])
sn_count = int(row[3])
sum_total_price = float(row[4])
# 基础数据:合并后的聚合不需要逐行展开 sn,只需要记录总个数和总金额
base_info = [settle_merchant, start_time_str, str(pk_period), sn_count, sum_total_price]
# 初始化 132 个月份的分摊金额为 0.0
installment_array = [0.0] * len(month_cols)
if pk_period > 0 and sum_total_price != 0:
monthly_installment = round(sum_total_price / pk_period, 6)
# 计算起始日期的年月
start_y, start_m = map(int, start_time_str.split('-'))
# 批量填充金额
for i in range(pk_period):
# 计算当前加上 i 个月后的年和月
current_m = start_m + i - 1
curr_year = start_y + (current_m // 12)
curr_month = (current_m % 12) + 1
col_name = f"{curr_year}-{curr_month:02d}分摊"
if col_name in col_to_idx:
installment_array[col_to_idx[col_name]] = monthly_installment
processed_data.append(base_info + installment_array)
# 组合 DataFrame
columns = ["settle_merchant", "settle_time", "pk_period", "sn", "total_price"] + month_cols
print("Creating DataFrame...")
grouped_df = pd.DataFrame(processed_data, columns=columns)
# 由于已经在 SQL 层面进行了 group by 聚合,这里不需要再调用 df.groupby(),直接就是最终结果。
# 只需确保分摊列类型为 float,以及对可能存在完全相同的 (商户,时间,期限) 数据再做一次安全聚合(防御性)
grouped_df = grouped_df.groupby(["settle_merchant", "settle_time", "pk_period"]).agg({
'sn': 'sum',
'total_price': 'sum',
**{col: 'sum' for col in month_cols}
}).reset_index()
# 调整列顺序与原脚本保持一致:但注意原脚本中聚合后没有 total_price,如果你需要可以保持,
# 但根据原脚本 `**{col: 'sum' for col in df.columns if "分摊" in col}` 来看,
# 原脚本输出列包含 settle_merchant, settle_time, pk_period, sn(其实是count), 及所有分摊列。
# 这里我们也保持一致。
# 将结果写入 CSV 文件
output_dir = args.output_dir if args.output_dir else os.path.dirname(os.path.abspath(__file__))
if not os.path.exists(output_dir):
os.makedirs(output_dir, exist_ok=True)
full_file_name = os.path.join(output_dir, file_name)
grouped_df.to_csv(full_file_name, index=False, sep=',')
print(f"GENERATED_CSV:{os.path.abspath(full_file_name)}")
--更新审计基础表
--1.同步发货结算门店表 dj_system_merchant
select DISTINCT a.cus_name from dj_2023/4_settlment_order a
WHERE a.business_type = 'SAAS系统订阅服务—旧版本'
AND a.cus_name NOT in ('东台宝通汽车服务有限责任公司', '广汇汽车服务有限责任公司东台分公司', '广汇汽车服务有限责任公司天津武清分公司', '上海宝信实嘉汽车销售有限公司天津武清分公司');
--2.同步本年度应收单表 dj_2024_settlment_order
--已经生成,无需同步
--3.生成本年度发货设备明细表 dj_2024_basic_device_info
insert into dj_2024_basic_device_info(sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,alloc)
select sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,0
from dj_2024_settle_details where device_type =8 AND settle_time between '2024-01-01' and '2025-01-01'
union
select sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,0
from dj_2024_settle_details_record where settle_time between '2024-01-01' and '2025-01-01'
--4.生成历史发货设备明细表 dj_basic_device_info
insert into dj_basic_device_info(sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,alloc)
select sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,0
from dj_2024_settle_details where device_type =8 AND settle_time between '2024-01-01' and '2025-01-01'
union
select sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,0
from dj_2024_settle_details_record where settle_time between '2024-01-01' and '2025-01-01'
--5.生成历史退货设备明细表 dj_device_details_return
insert into dj_device_details_return(channel,sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,settle_merchant,settle_order,settle_time,pk_price,hw_price,install_price,hw_cost,install_cost)
select channel,sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,settle_merchant,settle_order,settle_time,pk_price,hw_price,install_price,hw_cost,install_cost
from dj_2024_settle_details_return
\ No newline at end of file \ No newline at end of file
--更新审计基础表
--1.同步发货结算门店表 dj_system_merchant
select DISTINCT a.cus_name from dj_2023/4_settlment_order a
WHERE a.business_type = 'SAAS系统订阅服务—旧版本' AND a.cus_name NOT IN
(SELECT settle_merchant_name FROM dj_system_merchant)
AND a.cus_name NOT in ('东台宝通汽车服务有限责任公司', '广汇汽车服务有限责任公司东台分公司', '广汇汽车服务有限责任公司天津武清分公司', '上海宝信实嘉汽车销售有限公司天津武清分公司');
--2.同步本年度应收单表 dj_2024_settlment_order
--已经生成,无需同步
--3.生成本年度发货设备明细表 dj_2024_basic_device_info
insert into dj_2024_basic_device_info(sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,alloc)
select sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,0
from dj_2024_settle_details where device_type =8 AND settle_time between '2024-01-01' and '2025-01-01'
union
select sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,0
from dj_2024_settle_details_record where settle_time between '2024-01-01' and '2025-01-01'
--4.生成历史发货设备明细表 dj_basic_device_info
insert into dj_basic_device_info(sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,alloc)
select sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,0
from dj_2024_settle_details where device_type =8 AND settle_time between '2024-01-01' and '2025-01-01'
union
select sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,0
from dj_2024_settle_details_record where settle_time between '2024-01-01' and '2025-01-01'
--5.生成历史退货设备明细表 dj_device_details_return
insert into dj_device_details_return(channel,sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,settle_merchant,settle_order,settle_time,pk_price,hw_price,install_price,hw_cost,install_cost)
select channel,sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,settle_merchant,settle_order,settle_time,pk_price,hw_price,install_price,hw_cost,install_cost
from dj_2024_settle_details_return
--6. 结算单重算 dj_device_details
# 1.1 表结构创建
create table dj_device_details like complete_202x_dj_device_details;
# 1.2 运行脚本【智慧门店_结算单一致性重算(最终版).py】生成本年度明细 dj_device_details
# 1.3 追加历史设备明细
insert into dj_device_details(channel,sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,settle_merchant,settle_order,settle_time,pk_price,hw_price,install_price,hw_cost,install_cost)
select channel,sn,device_type,delivery_time,delivery_merchant,active_time,active_merchant,pk_name,pk_period,settle_merchant,settle_order,settle_time,pk_price,hw_price,install_price,hw_cost,install_cost
from complete_2023_dj_device_details
# 注:基础数据表 dj_2024_basic_device_info 重算后再次重算前需要重置alloc为0
--7. GPS/OBD分摊 运行脚本【 calc_month_share_gps.py】 含发货和退货 分摊中硬件/服务/安装不区分 安装可能为空
--8 未知操作
# 3 记录仪车充服务分摊
# 3.1退货明细价格处理
create table temp_dj_device_details_return as
select * from dj_device_details_return
where device_type in (6,12501) and settle_time < '2025-08-01 00:00:00';
CREATE INDEX temp_dj_device_details_return_pk_price_IDX USING BTREE ON temp_dj_device_details_return (pk_price);
UPDATE temp_dj_device_details_return SET pk_price = -pk_price WHERE pk_price > 0 ;
# 3.2 明细数据汇总
create table temp_dj_device_details_modify_serins_recalc as
select * from dj_device_details
where device_type in (6,12501) and settle_time < '2025-01-01 00:00:00'
union
select * from temp_dj_device_details_return
where device_type in (6,12501) and settle_time < '2025-01-01 00:00:00'
# 3.3 添加索引
CREATE INDEX temp_dj_device_details_modify_serins_recalc_pk_price_IDX USING BTREE ON glsx_biz_data.temp_dj_device_details_modify_serins_recalc (pk_price);
CREATE INDEX temp_dj_device_details_modify_serins_recalc_pk_period_IDX USING BTREE ON glsx_biz_data.temp_dj_device_details_modify_serins_recalc (pk_period);
# 3.4 空值数据处理
UPDATE temp_dj_device_details_modify_serins_recalc SET pk_period = 24 WHERE pk_period = 0 OR pk_period IS NULL;
#UPDATE temp_dj_device_details_modify_serins_recalc SET pk_price = 0 WHERE pk_price IS NULL;
--9.运行记录仪服务分摊脚本[calc_month_share_tracker_new.py]
--10.未知操作
# 4 记录仪硬件收入不分摊直接用结算
select sum(IFNULL(hw_price,0)) from dj_device_details
where device_type in (6,12501) and settle_time >= '2024-01-01 00:00:00' and settle_time < '2025-01-01 00:00:00';
# 5 记录仪硬件退货不分摊直接用结算
select sum(IFNULL(hw_price,0)) from dj_device_details_return
where device_type in (6,12501) and settle_time >= '2024-01-01 00:00:00' and settle_time < '2025-01-01 00:00:00';
\ No newline at end of file \ No newline at end of file
import pandas as pd
from sqlalchemy import create_engine, text
import urllib.parse
# Configuration
config = {
"glsx_data_db": {
"host": "192.168.5.5",
"port": 3310,
"user": "biz_device_detail",
"password": "M6khz3CQ",
"db_name": "glsx_data",
"charset": "utf8"
},
"dijia_db": {
"host": "192.168.5.2",
"port": 3306,
"user": "biz_glsx_data",
"password": "unEKczDc",
"db_name": "glsx_biz_data",
"charset": "utf8"
}
}
def get_db_url(db_conf):
user = db_conf['user']
password = urllib.parse.quote_plus(db_conf['password'])
host = db_conf['host']
port = db_conf['port']
db_name = db_conf['db_name']
charset = db_conf.get('charset', 'utf8')
return f"mysql+pymysql://{user}:{password}@{host}:{port}/{db_name}?charset={charset}"
def sync_settle_details():
# Source: dijia_db (biz_glsx_data) - 192.168.5.2
src_conf = config['dijia_db']
src_engine = create_engine(get_db_url(src_conf))
# Target: glsx_data_db (glsx_data) - 192.168.5.5
dst_conf = config['glsx_data_db']
dst_engine = create_engine(get_db_url(dst_conf))
table_name = "dj_2021_settle_details"
condition = "settle_time >= '2025-01-01 00:00:00'"
print(f"Starting sync for table: {table_name}")
print(f"Source DB: {src_conf['host']}/{src_conf['db_name']}")
print(f"Target DB: {dst_conf['host']}/{dst_conf['db_name']}")
print(f"Condition: {condition}")
query = f"SELECT * FROM {table_name} WHERE {condition}"
try:
print("Reading data from source...")
df = pd.read_sql(query, src_engine)
if df.empty:
print("No data found to sync.")
return
print(f"Found {len(df)} records.")
# Remove 'id' column if present (case-insensitive)
# cols_to_drop = [col for col in df.columns if col.lower() == 'id']
# if cols_to_drop:
# print(f"Dropping columns: {cols_to_drop}")
# df = df.drop(columns=cols_to_drop)
# Append records to target
print(f"Writing {len(df)} records to target {table_name}...")
# Use chunksize for better performance with large datasets
df.to_sql(table_name, dst_engine, if_exists='append', index=False, chunksize=1000)
print("Sync completed successfully.")
except Exception as e:
print(f"Error during sync: {e}")
def check_settle_detals():
"""
检查表:dj_2021_settle_details
条件:active_time is not null and settle_time<"2025-01-01"
两个库中的sn字段相同,但是active_time不同的数据,存到一个temp表中。
"""
# Source: dijia_db (biz_glsx_data) - 192.168.5.2
src_conf = config['dijia_db']
src_engine = create_engine(get_db_url(src_conf))
# Target: glsx_data_db (glsx_data) - 192.168.5.5
dst_conf = config['glsx_data_db']
dst_engine = create_engine(get_db_url(dst_conf))
table_name = "dj_2021_settle_details"
condition = "active_time is not null and settle_time < '2025-01-01'"
print(f"Checking table: {table_name}")
print(f"Condition: {condition}")
try:
# 1. Read from Source
print("Reading from Source DB...")
query_src = f"SELECT sn, active_time FROM {table_name} WHERE {condition}"
df_src = pd.read_sql(query_src, src_engine)
print(f"Source records: {len(df_src)}")
# 2. Read from Target
print("Reading from Target DB...")
query_dst = f"SELECT sn, active_time FROM {table_name} WHERE {condition}"
df_dst = pd.read_sql(query_dst, dst_engine)
print(f"Target records: {len(df_dst)}")
if df_src.empty or df_dst.empty:
print("One of the tables is empty, skipping comparison.")
return
# 3. Merge and Compare
print("Comparing data...")
# Merge on SN
merged = pd.merge(df_src, df_dst, on='sn', suffixes=('_src', '_dst'), how='outer', indicator=True)
# Analyze the merge results
only_in_src = merged[merged['_merge'] == 'left_only']
only_in_dst = merged[merged['_merge'] == 'right_only']
in_both = merged[merged['_merge'] == 'both']
print(f"Records only in Source (missing in Target): {len(only_in_src)}")
print(f"Records only in Target (extra in Target): {len(only_in_dst)}")
print(f"Records matched by SN: {len(in_both)}")
# Filter where active_time is different
# We handle potential type mismatches or None values if not handled by SQL
# Since SQL condition ensures active_time is not null, we just compare values
diff_df = in_both[in_both['active_time_src'] != in_both['active_time_dst']].copy()
if diff_df.empty:
print("No active_time differences found in matching SNs.")
else:
print(f"Found {len(diff_df)} differences in active_time for matching SNs.")
# 4. Save to Temp Table in Target DB
temp_table_name = "temp_diff_active_time_2021"
print(f"Saving differences to target DB table: {temp_table_name}...")
# Ensure _merge is dropped if it exists
if '_merge' in diff_df.columns:
diff_df.drop(columns=['_merge'], inplace=True)
diff_df.to_sql(temp_table_name, dst_engine, if_exists='replace', index=False)
print("Save completed.")
# Save missing records
if not only_in_src.empty:
missing_table_name = "temp_missing_in_target_2021"
print(f"Saving missing records to target DB table: {missing_table_name}...")
# Select relevant columns for missing records
missing_df = only_in_src[['sn', 'active_time_src']].copy()
missing_df.rename(columns={'active_time_src': 'active_time'}, inplace=True)
missing_df.to_sql(missing_table_name, dst_engine, if_exists='replace', index=False)
print("Save missing records completed.")
except Exception as e:
print(f"Error during check: {e}")
def update_active_time_from_temp():
"""
将temp_missing_in_target_2021表中的active_time更新到dst_engine库中的dj_2021_settle_details中对应的sn
"""
dst_conf = config['glsx_data_db']
dst_engine = create_engine(get_db_url(dst_conf))
# table_name = "dj_2021_settle_details"
table_name = "dj_device_details"
temp_table = "temp_missing_in_target_2021"
print(f"Updating {table_name} from {temp_table}...")
# MySQL UPDATE JOIN syntax
# Update active_time in main table using values from temp table where SN matches
sql = text(f"""
UPDATE {table_name} t
INNER JOIN {temp_table} s ON t.sn = s.sn
SET t.active_time = s.active_time
""")
try:
with dst_engine.connect() as conn:
result = conn.execute(sql)
print(f"Update executed. Rows matched/affected: {result.rowcount}")
conn.commit()
except Exception as e:
print(f"Error updating: {e}")
if __name__ == "__main__":
# sync_settle_details()
# check_settle_detals()
update_active_time_from_temp()
@echo off
chcp 65001 >nul
echo ==================================================
echo 🚀 开始运行记录仪分摊脚本...
echo ==================================================
:: 切换到脚本所在目录
cd /d "%~dp0"
:: 默认参数
set YEAR=2025
set OUTPUT_DIR="%~dp0output\tracker_share\%YEAR%"
:: 运行 Python 脚本
python calc_month_share_tracker_new.py --year %YEAR% --output_dir %OUTPUT_DIR%
if %errorlevel% neq 0 (
echo.
echo ❌ 脚本执行失败!
) else (
echo.
echo ✅ 脚本执行成功!
)
pause
import os
import sys
import subprocess
import argparse
def main():
# 获取当前脚本所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 目标脚本的路径
target_script = os.path.join(current_dir, "calc_month_share_tracker_new.py")
if not os.path.exists(target_script):
print(f"错误: 找不到目标脚本 {target_script}")
sys.exit(1)
# 设置默认参数
default_year = 2025
default_output_dir = os.path.join(current_dir, "output", "tracker_share", str(default_year))
# 解析命令行参数,允许用户覆盖默认值
parser = argparse.ArgumentParser(description="运行记录仪分摊脚本")
parser.add_argument("--year", type=int, default=default_year, help="要计算的年份 (默认: 2025)")
parser.add_argument("--output_dir", type=str, default=default_output_dir, help="输出目录路径")
args = parser.parse_args()
# 确保输出目录存在
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
print(f"创建输出目录: {args.output_dir}")
# 构建运行命令
cmd = [
sys.executable, # 当前 Python 解释器
target_script,
"--year", str(args.year),
"--output_dir", args.output_dir
]
print(f"==================================================")
print(f"🚀 开始执行记录仪分摊计算脚本...")
print(f"📅 计算年份: {args.year}")
print(f"📁 输出目录: {args.output_dir}")
print(f"💻 执行命令: {' '.join(cmd)}")
print(f"==================================================\n")
try:
# 执行目标脚本并将输出打印到控制台
result = subprocess.run(cmd, check=True)
print(f"\n✅ 脚本执行成功!(退出码: {result.returncode})")
except subprocess.CalledProcessError as e:
print(f"\n❌ 脚本执行失败!(退出码: {e.returncode})")
sys.exit(e.returncode)
except Exception as e:
print(f"\n❌ 发生意外错误: {str(e)}")
sys.exit(1)
if __name__ == "__main__":
main()
import pandas as pd
import yaml
import os
from sqlalchemy import create_engine
import pymysql
def get_config():
# 获取当前脚本所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 向上寻找直到找到 project 目录
# config.yaml 在 ../../../config.yaml
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(current_dir)))
config_path = os.path.join(base_dir, "config.yaml")
# 如果找不到,尝试直接在上级目录找(兼容调试)
if not os.path.exists(config_path):
base_dir = os.path.dirname(os.path.dirname(current_dir))
config_path = os.path.join(base_dir, "config.yaml")
with open(config_path, "r", encoding="utf-8") as f:
return yaml.safe_load(f)
def get_db_url(db_config):
return f"mysql+pymysql://{db_config['user']}:{db_config['password']}@{db_config['host']}:{db_config['port']}/{db_config['db_name']}?charset={db_config['charset']}"
def get_query_condition(year, table_name):
"""
获取查询条件
:param year: 年份
:param table_name: 表名
:return: SQL 查询条件字符串
"""
if year >= 2025:
return f"batch = '{year}'"
else:
start_time = f"{year}-00"
end_time = f"{year + 1}-00"
# t_eshield_device 在 2025 年之前没有时间过滤逻辑
if table_name == 't_eshield_device':
return "1=1"
return f"settle_time > '{start_time}' and settle_time < '{end_time}'"
def process_audit_deduction(year):
"""
执行审计抵扣逻辑
:param year: 年份,如 2024
"""
config = get_config()
db_conf = config['database']['device_detail_db']
engine = create_engine(get_db_url(db_conf))
start_time = f"{year}-00"
end_time = f"{year + 1}-00"
# 定义表名
receivables_out_table = 't_eshield_receivables'
device_table = 't_eshield_device'
device_detail_table = 't_eshield_device_detail'
renewal_table = 'd_eshield_renewal'
print(f"开始执行 {year} 年的审计抵扣计算流程...")
print(f"时间范围: {start_time} < settle_time < {end_time}")
# 从 t_eshield_receivables 表中获取数量和结算商户以及结算时间
receivables_condition = get_query_condition(year, receivables_out_table)
receivables = pd.read_sql(f"SELECT settle_merchant, sum(num) as Valuation_Quantity FROM "
f" {receivables_out_table} where num>0 and {receivables_condition} group by settle_merchant", con=engine)
# 从设备表中获取数据
device_condition = get_query_condition(year, device_table)
# 如果条件不为空(例如 1=1 或 batch='...'),则添加 WHERE 子句
# 注意:如果 device_condition 是 "1=1",加上去也没问题
raw_dev_df = pd.read_sql(f'SELECT sn,max(device_type) as device_type,'
' max(delivery_time) as delivery_time,'
' max(delivery_merchant) as delivery_merchant, '
' max(active_time) as active_time,'
' max(active_merchant) as active_merchant,'
f' max(classid) as classid FROM {device_table} WHERE {device_condition} group by sn', con=engine)
devices = pd.DataFrame()
device_detail_condition = get_query_condition(year, device_detail_table)
# receivables_out 在 join 子查询中也需要应用条件
# 注意:这里的 receivables_out 子查询和上面的 receivables 查询略有不同(上面有 sum(num)),这里是 SELECT *
receivables_sub_condition = get_query_condition(year, receivables_out_table)
devices = pd.read_sql(f"\
select\
A.*\
from (\
SELECT * FROM {device_detail_table} WHERE {device_detail_condition} ) A left join (select * from {receivables_out_table} WHERE {receivables_sub_condition} ) B\
on substring(A.settle_time,1,7) = B.settle_time and A. settle_merchant = B.settle_merchant and A.device_price = B.device_price\
and A.service_price=B.service_price", con=engine)
result_df = pd.merge(devices[['sn','device_period','settle_merchant','device_type','settle_time','device_price','install_price','from_type']], raw_dev_df[['sn','delivery_time','delivery_merchant','active_time','active_merchant','classid']], on='sn', how='left')
# 创建 t_eshield_device_detail_output 表,并将结果保存到该表中
dev=result_df[['sn','device_type','delivery_time','delivery_merchant'
,'active_time','active_merchant','device_period','settle_merchant'
,'settle_time','device_price','install_price'
,'from_type','classid'
]]
target_device_detail_table = 't_eshield_device_detail_'+str(year)+'_output'
dev.to_sql(target_device_detail_table, con=engine, if_exists='replace', index=False)
print(f"已生成表: {target_device_detail_table}")
# 从续费明细表中获取数据
renewal_condition = get_query_condition(year, renewal_table)
renewal_df = pd.read_sql(f"SELECT * FROM {renewal_table} where {renewal_condition} ", con=engine)
devices.rename(columns={'device_period':'service_period'},inplace=True)
services=devices[devices['service_price']!=0]
# 服务信息表整合
# 设备服务
dev_service_res_df = pd.merge(services[['sn','device_type','service_period','settle_merchant','settle_time','service_price','from_type']],
raw_dev_df[['sn','delivery_time','delivery_merchant','active_time','active_merchant','classid']], on='sn', how='left')
# 续费
renewal_res_df = pd.merge(renewal_df[['sn','service_period','settle_merchant','settle_time','service_price','from_type']],
raw_dev_df[['sn','device_type','delivery_time','delivery_merchant','active_time','active_merchant','classid']], on='sn', how='left')
df1 = dev_service_res_df[['sn','device_type','delivery_time','delivery_merchant','active_time','active_merchant'
,'service_period','settle_merchant'
,'settle_time'
,'service_price','from_type','classid']]
df2 = renewal_res_df[['sn','device_type','delivery_time','delivery_merchant','active_time','active_merchant'
,'service_period','settle_merchant'
,'settle_time'
,'service_price','from_type','classid']]
merge_df = pd.concat([df1,df2])
target_service_detail_table = 't_eshield_service_detail_'+str(year)+'_output'
merge_df.to_sql(target_service_detail_table, con=engine, if_exists='replace', index=False)
print(f"已生成表: {target_service_detail_table}")
print(f"{year} 年审计抵扣流程执行完毕!")
if __name__ == "__main__":
# 示例调用
process_audit_deduction(2024)
This diff could not be displayed because it is too large.
import streamlit as st
import pandas as pd
import datetime
import os
import sys
import traceback
# 添加当前目录到 sys.path 以便导入同级模块
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
sys.path.append(current_dir)
import audit_calculation
import audit_deduction
import calc_month_share
def show():
st.title("E盾-分摊全流程")
# 年份选择
current_year = datetime.datetime.now().year
selected_year = st.number_input("选择年份", min_value=2000, max_value=2100, value=current_year, step=1)
st.write("---")
st.header("1.导出对外明细数据")
st.info(f"""
**功能说明**:
该功能将选定年份的内部审计数据(续费、设备、明细、应收单)同步至存储全部年份的数据表。
⚠️ **注意**:执行时会自动清除目标表中该年份的旧数据,请谨慎操作。
**涉及表信息**:
- **源表 (Source)**:
- `d_eshield_device_details_{{selected_year}}` (当年设备明细)
- `d_eshield_service_details_{{selected_year}}` (当年服务明细)
- **目标表 (Target)**:
- `d_eshield_renewal` (续费记录表)
- `t_eshield_device` (设备基础表)
- `t_eshield_device_detail` (设备明细整合表)
- `t_eshield_receivables` (应收单表)
""")
# 初始化 session_state
if 'confirm_export' not in st.session_state:
st.session_state.confirm_export = False
# 导出按钮
if st.button(f"并入 {selected_year} 年数据对外明细数据"):
st.session_state.confirm_export = True
if st.session_state.confirm_export:
st.warning(f"⚠️ 请确认:您即将导出 {selected_year} 年的数据。此操作将**删除**该年份已存在的旧数据并重新生成。")
col1, col2 = st.columns([1, 1])
with col1:
if st.button("确认执行", use_container_width=True):
st.session_state.confirm_export = False # 重置状态
st.info(f"开始处理 {selected_year} 年数据 (Batch: {selected_year})...")
try:
# 调用处理逻辑
# batch 默认为年份字符串
batch = str(selected_year)
# 显示加载状态
with st.spinner('正在执行数据清理和生成,请稍候...'):
results = audit_calculation.process_audit_calculation(selected_year, batch=batch)
st.success(f"{selected_year} 年数据处理完成!")
st.subheader("处理结果明细:")
st.write("以下数据已从源表插入到目标表(操作前已自动清理旧批次数据):")
# 使用 DataFrame 展示结果
if results:
df_results = pd.DataFrame(results)
st.table(df_results)
else:
st.info("没有返回处理结果")
except Exception as e:
st.error(f"处理过程中发生错误: {e}")
st.code(traceback.format_exc())
with col2:
if st.button("取消", use_container_width=True):
st.session_state.confirm_export = False
st.info("已取消操作")
st.write("---")
st.header("2.正向推导设备和服务明细数据")
st.info(f"""
**功能说明**:
该功能执行审计抵扣逻辑,正向推导设备和服务明细数据,生成 `t_eshield_device_detail_{selected_year}_output` 和 `t_eshield_service_detail_{selected_year}_output` 表。
1.后续审计会重点核对这两张表是否和之前提供的明细数据一致。
**涉及表信息**:
- **源表 (Source)**:
- `t_eshield_device`
- `t_eshield_device_detail`
- `t_eshield_receivables`
- `d_eshield_renewal`
- **目标表 (Target)**:
- `t_eshield_device_detail_{selected_year}_output` (设备抵扣结果表)
- `t_eshield_service_detail_{selected_year}_output` (服务抵扣结果表)
""")
if st.button(f"开始推导 {selected_year} 年设备和服务明细数据"):
try:
with st.spinner(f'正在执行 {selected_year} 年审计抵扣推导...'):
audit_deduction.process_audit_deduction(selected_year)
st.success(f"{selected_year} 年审计抵扣推导完成!")
except Exception as e:
st.error(f"处理出错: {e}")
st.code(traceback.format_exc())
st.write("---")
st.header("3.生成分摊数据")
st.info(f"""
**功能说明**:
该功能根据已有的明细数据,计算并生成最终的分摊报表(CSV格式)。
**涉及表信息**:
- **源表 (Source)**:
- `d_eshield_device_details_{{year}}` (涵盖 2015 ~ 当前年份的所有表)
- `d_eshield_service_details_{{year}}` (涵盖 2015 ~ 当前年份的所有表)
- **输出 (Output)**:
- CSV 文件 (例如:`门店_追踪器_按月分摊_{selected_year}年收入.csv`)
""")
if st.button(f"生成 {selected_year} 年分摊数据"):
try:
with st.spinner(f'正在生成 {selected_year} 年分摊数据...'):
# 1. 获取时间跨度描述
date_str = calc_month_share.get_settle_time_span(selected_year)
# 2. 调用生成逻辑
file_name = calc_month_share.calc_income_share('收入', date_str)
st.success(f"{selected_year} 年分摊数据生成完成!")
if file_name:
abs_path = os.path.abspath(file_name)
base_name = os.path.basename(abs_path)
st.write(f"生成的文件: **{base_name}**")
st.write(f"文件保存路径: {abs_path}")
if os.path.exists(abs_path):
with open(abs_path, "rb") as f:
st.download_button(
label="下载分摊报表",
data=f,
file_name=base_name,
mime="text/csv"
)
except Exception as e:
st.error(f"生成出错: {e}")
st.code(traceback.format_exc())
st.write("---")
st.header("4.同步数据到对外数据库表")
st.info(f"""
**功能说明**:
该功能将生成的内部表同步到对外数据库(glsx_data),供外部系统或报表查询使用。
同步表包括:
- 基础表:d_eshield_renewal, t_eshield_device, t_eshield_device_detail, t_eshield_receivables
- 年份表:d_eshield_device_details_{selected_year}, d_eshield_service_details_{selected_year}
**涉及表信息**:
- **源表 (Source)**:
- `d_eshield_renewal`
- `t_eshield_device`
- `t_eshield_device_detail`
- `t_eshield_receivables`
- `d_eshield_device_details_{selected_year}`
- `d_eshield_service_details_{selected_year}`
- **目标表 (Target)**:
- 对外数据库 (`glsx_data`) 中的同名表
""")
if st.button(f"同步 {selected_year} 年数据到对外数据库"):
try:
with st.spinner(f'正在同步 {selected_year} 年数据到对外数据库...'):
audit_calculation.sync_to_external_db(year=selected_year)
st.success(f"{selected_year} 年数据同步完成!")
except Exception as e:
st.error(f"同步出错: {e}")
st.code(traceback.format_exc())
# -*- coding:utf-8 -*-
from __future__ import print_function
import time
# import MySQLdb
import pymysql as MySQLdb
import sys
# reload(sys)
# sys.setdefaultencoding('utf8')
#
def paddstr(strx):
# return "NULL" if strx == None else "\'" + MySQLdb.escape_string(str(strx)).decode() + "\'"
return (
"NULL"
if strx == None
else "'" + MySQLdb.converters.escape_string(str(strx)) + "'"
)
def paddnum(numx, default="NULL"):
return default if numx == None else str(numx)
class MySQL:
"""对MySQLdb常用函数进行封装的类"""
error_code = "" # MySQL错误号码
_instance = None # 本类的实例
_conn = None # 数据库conn
_cur = None # 游标
_TIMEOUT = 30 # 默认超时30秒
_timecount = 0
def __init__(self, dbconfig):
"构造器:根据数据库连接参数,创建MySQL连接"
try:
self._conn = MySQLdb.connect(
host=dbconfig["host"],
port=dbconfig["port"],
user=dbconfig["user"],
passwd=dbconfig["passwd"],
db=dbconfig["db"],
charset=dbconfig["charset"],
)
except MySQLdb.Error as e:
self.error_code = e.args[0]
error_msg = "MySQL error! ", e.args[0], e.args[1]
print(error_msg)
# 如果没有超过预设超时时间,则再次尝试连接,
if self._timecount < self._TIMEOUT:
interval = 5
self._timecount += interval
time.sleep(interval)
return self.__init__(dbconfig)
else:
raise Exception(error_msg)
self._cur = self._conn.cursor()
self._instance = MySQLdb
def query(self, sql):
"执行 SELECT 语句"
try:
# self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql)
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def queryList(self, sqlList):
"执行 SELECT 语句"
try:
for sql in sqlList:
# self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql)
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def update(self, sql):
"执行 UPDATE 及 DELETE 语句"
try:
# self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql)
self._conn.commit()
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def updateList(self, sqlList):
"执行 UPDATE 及 DELETE 语句"
try:
for sql in sqlList:
# self._cur.execute("SET NAMES utf8")
result = self._cur.execute(sql)
self._conn.commit()
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def insert(self, sql, data=None):
"执行 INSERT 语句。如主键为自增长int,则返回新生成的ID"
try:
self._cur.execute("SET NAMES utf8")
if data == None:
self._cur.execute(sql)
else:
self._cur.executemany(sql, data)
self._conn.commit()
return True
return self._conn.insert_id()
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
return False
def callproc(self, procname, *arg):
try:
self._cur.execute("SET NAMES utf8")
self._cur.callproc(procname, arg)
self._conn.commit()
result = True
except MySQLdb.Error as e:
self.error_code = e.args[0]
print("数据库错误代码:", e.args[0], e.args[1])
result = False
return result
def fetchAllRows(self):
"返回结果列表"
return self._cur.fetchall()
def fetchOneRow(self):
"返回一行结果,然后游标指向下一行。到达最后一行以后,返回None"
return self._cur.fetchone()
def getRowCount(self):
"获取结果行数"
return self._cur.rowcount
def commit(self):
"数据库commit操作"
self._conn.commit()
def rollback(self):
"数据库回滚操作"
self._conn.rollback()
def __del__(self):
"释放资源(系统GC自动调用)"
try:
self._cur.close()
self._conn.close()
except:
pass
def close(self):
"关闭数据库连接"
self.__del__()
import streamlit as st
import importlib.util
import os
import sys
import datetime
def load_module(module_name, file_path):
module_dir = os.path.dirname(file_path)
if module_dir not in sys.path:
sys.path.insert(0, module_dir)
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def show():
st.info("将分摊计算结果同步到外部审计数据库。")
# 动态加载 audit_calculation.py
# 路径回退到 project/3-amortization_process/edun
base_dir = os.path.dirname(os.path.abspath(__file__))
project_dir = os.path.dirname(os.path.dirname(base_dir)) # project
audit_calc_path = os.path.join(project_dir, "3-amortization_process", "edun", "audit_calculation.py")
if not os.path.exists(audit_calc_path):
st.error(f"找不到文件: {audit_calc_path}")
return
try:
audit_module = load_module("audit_calculation", audit_calc_path)
# 获取可用年份
# 这里简单硬编码几个年份,或者默认当前年份
current_year = datetime.datetime.now().year
years = [current_year, current_year - 1, current_year - 2]
selected_year = st.selectbox("选择年份", years, index=0)
if st.button("开始同步"):
with st.spinner(f"正在同步 {selected_year} 年数据..."):
try:
# 调用同步函数
audit_module.sync_to_external_db(year=selected_year)
st.success(f"{selected_year} 年数据同步完成!")
except Exception as e:
st.error(f"同步失败: {e}")
import traceback
st.code(traceback.format_exc())
except Exception as e:
st.error(f"加载审计计算模块失败: {e}")
import traceback
st.code(traceback.format_exc())
import streamlit as st
import importlib.util
import os
import sys
def load_module(module_name, file_path):
module_dir = os.path.dirname(file_path)
if module_dir not in sys.path:
sys.path.insert(0, module_dir)
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def show():
st.header("同步数据到审计库")
st.info("请从左侧选择业务类型以加载对应的同步逻辑。")
def show_with_category(category):
st.header(f"同步数据到审计库 - {category}")
base_dir = os.path.dirname(os.path.abspath(__file__))
if category == "E盾-智慧车管":
module_path = os.path.join(base_dir, "edun", "edun_sync.py")
try:
module = load_module("edun_sync", module_path)
module.show()
except Exception as e:
st.error(f"加载 E盾 同步模块失败: {e}")
elif category == "嘀加-旧版本":
#
module_path = os.path.join(base_dir, "dijia", "dijia_sync.py")
try:
module = load_module("dijia_sync", module_path)
module.show()
except Exception as e:
st.error(f"加载 嘀加 同步模块失败: {e}")
else:
st.warning(f"未知的业务类型: {category}")
import streamlit as st
import yaml
import os
def load_config():
"""加载配置文件"""
# config.yaml 在 project 目录下
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
config_path = os.path.join(base_dir, "config.yaml")
if not os.path.exists(config_path):
st.error(f"配置文件不存在: {config_path}")
return None, config_path
try:
with open(config_path, "r", encoding="utf-8") as f:
return yaml.safe_load(f), config_path
except Exception as e:
st.error(f"加载配置失败: {e}")
return None, config_path
def save_config(config_data, config_path):
"""保存配置文件"""
try:
with open(config_path, "w", encoding="utf-8") as f:
yaml.dump(config_data, f, allow_unicode=True, default_flow_style=False, sort_keys=False)
return True
except Exception as e:
st.error(f"保存配置失败: {e}")
return False
def show_edun(config_data, config_path):
st.header(f"配置管理 - E盾-智慧车管")
_show_config_editor("edun", config_data, config_path)
def show_dijia(config_data, config_path):
st.header(f"配置管理 - 嘀加-旧版本")
_show_config_editor("dijia", config_data, config_path)
def _show_config_editor(key_prefix, config_data, config_path):
st.subheader("🛠️ 全局配置 (config.yaml)")
st.info("您可以在下方直接修改配置内容,点击“保存配置”按钮生效。")
# 使用文本框编辑 YAML 内容
yaml_str = yaml.dump(config_data, allow_unicode=True, default_flow_style=False, sort_keys=False)
edited_yaml = st.text_area(
"配置文件内容",
value=yaml_str,
height=600,
help="请确保 YAML 格式正确",
key=f"{key_prefix}_yaml_editor"
)
col1, col2 = st.columns([1, 5])
with col1:
if st.button("💾 保存配置", type="primary", key=f"{key_prefix}_save_config"):
try:
new_config = yaml.safe_load(edited_yaml)
if save_config(new_config, config_path):
st.success("✅ 配置已成功保存!")
st.rerun()
except Exception as e:
st.error(f"❌ YAML 格式错误,无法解析: {e}")
with col2:
if st.button("🔄 重置", key=f"{key_prefix}_reset_config"):
st.rerun()
with st.expander("👁️ 查看当前已加载配置结构"):
st.json(config_data)
def show_with_category(category):
config_data, config_path = load_config()
if config_data is None:
return
if category == "嘀加-旧版本":
show_dijia(config_data, config_path)
else:
show_edun(config_data, config_path)
def show():
show_with_category("E盾-智慧车管")
import streamlit as st
def show_edun():
category = "E盾-智慧车管"
st.header(f"日志查询 - {category}")
st.info(f"功能:查看 {category} 相关的业务执行和系统运行日志。")
st.text_area("日志输出", value=f"正在监控 {category} 的执行状态...\n[INFO] 系统已就绪", height=300, key="edun_log_area")
def show_dijia():
category = "嘀加-旧版本"
st.header(f"日志查询 - {category}")
st.info(f"功能:查看 {category} 相关的业务执行和系统运行日志。")
st.text_area("日志输出", value=f"正在监控 {category} 的执行状态...\n[INFO] 系统已就绪", height=300, key="dijia_log_area")
def show_with_category(category):
if category == "嘀加-旧版本":
show_dijia()
else:
show_edun()
def show():
show_with_category("E盾-智慧车管")
import os
import yaml
import string
import random
from sqlalchemy import create_engine, text
def get_project_root():
current_dir = os.path.dirname(os.path.abspath(__file__))
return os.path.dirname(os.path.dirname(current_dir))
def get_db_configs():
project_root = get_project_root()
config_path = os.path.join(project_root, "config.yaml")
if not os.path.exists(config_path):
return {}
with open(config_path, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
return config.get("database", {})
def get_db_engine(db_key):
db_configs = get_db_configs()
db_config = db_configs.get(db_key)
if not db_config:
raise ValueError(f"config.yaml 中缺少 {db_key} 配置")
connection_str = (
f"mysql+pymysql://{db_config['user']}:{db_config['password']}@"
f"{db_config['host']}:{db_config['port']}/{db_config['db_name']}?"
f"charset={db_config['charset']}"
)
return create_engine(connection_str)
def generate_sn(existing_sns):
while True:
# WX + 2 fixed digits (e.g., '25') + 11 random digits
suffix = '25' + ''.join(random.choices(string.digits, k=11))
sn = "WX" + suffix
if sn not in existing_sns:
existing_sns.add(sn)
return sn
def sync_to_2025_settlment_order(engine, batches):
"""
将新增的批次数据同步到应收单表 dj_2025_settlment_order 中
"""
try:
with engine.begin() as conn:
# 1. 先清理应收单表中的历史数据
order_nos = [f"'{b['settle_order']}'" for b in batches]
if order_nos:
delete_sql = text(f"DELETE FROM dj_2025_settlment_order WHERE order_no IN ({','.join(order_nos)})")
del_result = conn.execute(delete_sql)
print(f"清理应收单表(2025)旧数据成功: 删除了 {del_result.rowcount} 条。")
# 2. 插入新数据
insert_sql = text("""
INSERT INTO dj_2025_settlment_order (
order_type, order_no, finance_time, cus_name, sale_type, business_type,
product_code, product_name, product_type, device_type, fin_total, total,
hw_unit_price_tax, hw_unit_price, pk_term, income_tax, income, cost, match_total, status
) VALUES (
:order_type, :order_no, :finance_time, :cus_name, :sale_type, :business_type,
:product_code, :product_name, :product_type, :device_type, :fin_total, :total,
:hw_unit_price_tax, :hw_unit_price, :pk_term, :income_tax, :income, :cost, :match_total, :status
)
""")
inserted_count = 0
for batch in batches:
params = {
"order_type": "标准应收单",
"order_no": batch["settle_order"],
"finance_time": batch["settle_time"],
"cus_name": "长沙市华品汽车用品有限公司",
"sale_type": "渠道",
"business_type": "SAAS系统订阅服务—旧版本",
"product_code": "GLSX50949",
"product_name": "记录仪",
"product_type": "硬件",
"device_type": "记录仪",
"fin_total": batch["count"],
"total": batch["count"],
"hw_unit_price_tax": 680.00,
"hw_unit_price": 601.77,
"pk_term": 1,
"income_tax": 680.00 * batch["count"],
"income": 601.77 * batch["count"],
"cost": batch["total_cost"],
"match_total": 0,
"status": 0
}
conn.execute(insert_sql, params)
inserted_count += 1
print(f"同步至应收单表(dj_2025_settlment_order)成功: 插入了 {inserted_count} 条新记录。")
except Exception as e:
print(f"同步至应收单表(dj_2025_settlment_order)失败: {e}")
def sync_to_2021_details(engine):
"""
将新增的以 WX 开头的设备同步到总表 dj_2021_settle_details 中
"""
try:
with engine.begin() as conn:
# 1. 先清理总表中的历史数据,防止重跑重复
delete_sql = text("DELETE FROM dj_2021_settle_details WHERE sn LIKE 'WX%'")
del_result = conn.execute(delete_sql)
print(f"清理总表(2021)旧数据成功: 删除了 {del_result.rowcount} 条。")
# 2. 插入新数据
insert_sql = text("""
INSERT INTO dj_2021_settle_details (
`channel`,`is_virtual`,`sn`,`iccid`,`device_type`,`material_code`,`delivery_order`,`delivery_time`,
`delivery_merchant`,`active_time`,`active_merchant`,`pk_name`,`pk_period`,`settle_merchant`,
`settle_order`,`settle_time`,`pk_price`,`pk_price_tax`,`hw_price`,`hw_price_tax`,`install_price`,
`install_price_tax`,`cost`,`flag`,`return`,`hw_cost`,`install_cost`
)
SELECT
`channel`,`is_virtual`,`sn`,`iccid`,`device_type`,`material_code`,`delivery_order`,`delivery_time`,
`delivery_merchant`,`active_time`,`active_merchant`,`pk_name`,`pk_period`,`settle_merchant`,
`settle_order`,`settle_time`,`pk_price`,`pk_price_tax`,`hw_price`,`hw_price_tax`,`install_price`,
`install_price_tax`,`cost`,`flag`,`return`,`hw_cost`,`install_cost`
FROM dj_2025_settle_details_record
WHERE sn LIKE 'WX%'
""")
result = conn.execute(insert_sql)
print(f"同步至总表(2021)成功: 插入了 {result.rowcount} 条新记录。")
except Exception as e:
print(f"同步至总表(2021)失败: {e}")
def main():
batches = [
{"settle_order": "AR21645586", "settle_time": "2025-08-01 00:00:00", "count": 125, "total_cost": 78308.48},
{"settle_order": "AR21646324", "settle_time": "2025-09-01 00:00:00", "count": 100, "total_cost": 57590.05},
{"settle_order": "AR21647084", "settle_time": "2025-10-01 00:00:00", "count": 96, "total_cost": 55221.32},
{"settle_order": "AR21647990", "settle_time": "2025-11-01 00:00:00", "count": 99, "total_cost": 56946.92},
{"settle_order": "AR21649474", "settle_time": "2025-12-01 00:00:00", "count": 63, "total_cost": 36238.94},
]
try:
engine = get_db_engine('dijia_db')
except Exception as e:
print(f"数据库连接失败: {e}")
return
# Retry tolerance logic: delete previous mock data
try:
with engine.begin() as conn:
delete_sql = text("DELETE FROM dj_2025_settle_details_record WHERE sn LIKE 'WX%'")
result = conn.execute(delete_sql)
print(f"清理旧数据成功: 删除了 {result.rowcount} 条以 WX 开头的旧记录。")
except Exception as e:
print(f"清理旧数据失败: {e}")
return
insert_sql = text("""
INSERT INTO dj_2025_settle_details_record (
channel, sn, is_virtual, device_type, material_code, delivery_order, delivery_time, delivery_merchant,
settle_merchant, settle_order, settle_time, pk_period, hw_price, hw_price_tax, cost, hw_cost, flag, `return`
) VALUES (
:channel, :sn, :is_virtual, :device_type, :material_code, :delivery_order, :delivery_time, :delivery_merchant,
:settle_merchant, :settle_order, :settle_time, :pk_period, :hw_price, :hw_price_tax, :cost, :hw_cost, :flag, :return_flag
)
""")
inserted_count = 0
existing_sns = set()
# Pre-fetch existing SNs to ensure absolute uniqueness (optional but safe)
try:
with engine.connect() as conn:
result = conn.execute(text("SELECT sn FROM dj_2025_settle_details_record WHERE sn LIKE 'WX%'"))
for row in result:
existing_sns.add(row[0])
except Exception as e:
print(f"读取现有设备号失败,忽略: {e}")
with engine.begin() as conn:
for batch in batches:
unit_cost = round(batch["total_cost"] / batch["count"], 4)
for _ in range(batch["count"]):
sn = generate_sn(existing_sns)
params = {
"channel": "渠道",
"sn": sn,
"is_virtual": 0,
"device_type": 6, # 云导航
"material_code": "GLSX50949",
"delivery_order": f"{batch['settle_order']}",
"delivery_time": batch["settle_time"],
"delivery_merchant": "长沙市华品汽车用品有限公司",
"settle_merchant": "长沙市华品汽车用品有限公司",
"settle_order": batch["settle_order"],
"settle_time": batch["settle_time"],
"pk_period": 1,
"hw_price": 601.77,
"hw_price_tax": 680.00,
"cost": unit_cost,
"hw_cost": unit_cost,
"flag": 0,
"return_flag": 0
}
conn.execute(insert_sql, params)
inserted_count += 1
print(f"成功插入 {inserted_count} 条模拟记录到 dj_2025_settle_details_record 表中!")
# 同步到 2021 总表
sync_to_2021_details(engine)
# 同步到 2025 应收单表
sync_to_2025_settlment_order(engine, batches)
if __name__ == "__main__":
main()
\ No newline at end of file \ No newline at end of file
import yaml
from sqlalchemy import create_engine, text
import os
def get_project_root():
# 获取当前脚本所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# dj-ops is under 5-ops_management, project root is two levels up
return os.path.dirname(os.path.dirname(current_dir))
def get_db_configs():
"""获取 config.yaml 中所有的数据库配置键"""
project_root = get_project_root()
config_path = os.path.join(project_root, "config.yaml")
if not os.path.exists(config_path):
return {}
with open(config_path, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
return config.get("database", {})
def get_db_engine(db_key):
"""根据 db_key 获取数据库引擎"""
db_configs = get_db_configs()
db_config = db_configs.get(db_key)
if not db_config:
raise ValueError(f"config.yaml 中缺少 {db_key} 配置")
connection_str = (
f"mysql+pymysql://{db_config['user']}:{db_config['password']}@"
f"{db_config['host']}:{db_config['port']}/{db_config['db_name']}?"
f"charset={db_config['charset']}"
)
return create_engine(connection_str)
def get_all_tables(db_key):
"""获取指定数据库中所有表名"""
if not db_key:
return []
try:
engine = get_db_engine(db_key)
with engine.connect() as conn:
result = conn.execute(text("SHOW TABLES"))
return [row[0] for row in result]
except Exception:
return []
def backup_table(db_key, table_name):
"""
备份指定的数据库表
备份表名为 table_name + "_bak"
"""
if not db_key or not table_name:
return False, "请先选择数据库和表名。"
engine = get_db_engine(db_key)
bak_table_name = f"{table_name}_bak"
with engine.begin() as conn:
# 1. 检查原表是否存在
check_sql = text("SHOW TABLES LIKE :table")
res = conn.execute(check_sql, {"table": table_name}).fetchone()
if not res:
return False, f"表 '{table_name}' 不存在。"
# 2. 如果备份表已存在,先删除
conn.execute(text(f"DROP TABLE IF EXISTS `{bak_table_name}`"))
# 3. 创建备份表结构
conn.execute(text(f"CREATE TABLE `{bak_table_name}` LIKE `{table_name}`"))
# 4. 拷贝数据
conn.execute(text(f"INSERT INTO `{bak_table_name}` SELECT * FROM `{table_name}`"))
return True, f"表 '{table_name}' 已成功备份为 '{bak_table_name}'。"
if __name__ == "__main__":
# 测试代码
try:
configs = get_db_configs()
print(f"可用数据库配置: {list(configs.keys())}")
except Exception as e:
print(f"发生错误: {e}")
import yaml
from sqlalchemy import create_engine, text
import os
def init_database(db_key="device_detail_db"):
# 获取当前脚本所在目录
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_dir)
# 1. 读取 config.yaml (在项目根目录)
config_path = os.path.join(project_root, "config.yaml")
if not os.path.exists(config_path):
print(f"错误: 找不到配置文件 {config_path}")
return
with open(config_path, "r", encoding="utf-8") as f:
config = yaml.safe_load(f)
# 获取数据库配置
db_config = config.get("database", {}).get(db_key)
if not db_config:
print(f"错误: config.yaml 中缺少 {db_key} 配置")
return
# 2. 构建连接字符串
connection_str = (
f"mysql+pymysql://{db_config['user']}:{db_config['password']}@"
f"{db_config['host']}:{db_config['port']}/{db_config['db_name']}?"
f"charset={db_config['charset']}"
)
try:
# 3. 创建引擎并连接
engine = create_engine(connection_str)
# 4. 读取 schema.sql (在当前目录)
schema_path = os.path.join(current_dir, "schema.sql")
if not os.path.exists(schema_path):
print(f"错误: 找不到架构文件 {schema_path}")
return
with open(schema_path, "r", encoding="utf-8") as f:
# 按分号分割 SQL 语句
sql_commands = f.read().split(';')
# 5. 执行 SQL 语句
with engine.begin() as connection:
print(f"正在连接到数据库 [{db_key}]: {db_config['host']}:{db_config['port']}/{db_config['db_name']}...")
# 定义高危指令拦截列表
dangerous_keywords = ['DROP ', 'TRUNCATE ', 'DELETE FROM ']
for command in sql_commands:
# 1. 预处理:按行分割并过滤掉纯注释行 (-- 或 # 开头的行)
lines = command.split('\n')
non_comment_lines = []
for line in lines:
stripped_line = line.strip()
# 排除空行、以 -- 开头的注释行、以 # 开头的注释行
if stripped_line and not (stripped_line.startswith('--') or stripped_line.startswith('#')):
non_comment_lines.append(line)
# 2. 重新组合并清理两端空白
clean_command = "\n".join(non_comment_lines).strip()
# 3. 如果清理后为空,则跳过
if not clean_command:
continue
# 安全检查:拦截可能导致数据丢失的指令
is_dangerous = any(keyword in clean_command.upper() for keyword in dangerous_keywords)
if is_dangerous:
print(f"警告: 拦截到潜在的危险指令,已跳过执行: \n{clean_command[:100]}...")
continue
# 记录正在执行的指令
if "CREATE TABLE" in clean_command.upper():
table_name = clean_command.split('`')[1] if '`' in clean_command else "未知表"
print(f"检查/创建表: {table_name}")
elif "ALTER TABLE" in clean_command.upper():
table_name = clean_command.split('`')[1] if '`' in clean_command else "未知表"
print(f"更新表结构: {table_name}")
# 使用 exec_driver_sql 直接执行原始 SQL,避免 SQLAlchemy 对冒号(:)等字符的参数解析
connection.exec_driver_sql(clean_command)
print("数据库表检查/更新任务完成!")
except Exception as e:
print(f"连接数据库失败: {e}")
if __name__ == "__main__":
init_database()
import streamlit as st
import os
import sys
import importlib.util
def load_local_module(module_name, file_name):
"""动态加载同目录下的模块,解决 Streamlit 动态加载导致的相对导入问题"""
current_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(current_dir, file_name)
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def show_edun():
category = "E盾-智慧车管"
st.header(f"Ops 管理 - {category}")
_show_ops_content(category, "edun")
import subprocess
import datetime
def show_dijia():
category = "嘀加-旧版本"
st.header(f"Ops 管理 - {category}")
_show_ops_content(category, "dijia")
st.divider()
st.subheader("3. 同步 dj_device_details(同步全部激活时间)")
if st.button("🔄 同步 dj_device_details(同步全部激活时间)", use_container_width=True, key="dijia_ops_copy_year_btn"):
_run_script_action("copy_all", "同步 dj_device_details")
st.caption("""
**操作说明:**
同步 dj_2021_settle_details 里面的激活时间到 dj_device_details里面
""")
st.divider()
st.subheader("4. 同步 dj_basic_device_info(同步全部激活时间)")
if st.button("🔄 同步 dj_basic_device_info(同步全部激活时间)", use_container_width=True, key="dijia_ops_copy_basic_all_btn"):
_run_script_action("copy_basic_all", "同步 dj_basic_device_info")
st.caption("""
**操作说明:**
同步 dj_2021_settle_details 里面的激活时间到 dj_basic_device_info 里面
""")
st.divider()
st.subheader("5. 同步 dj_2025_basic_device_info(同步全部激活时间)")
if st.button("🔄 同步 dj_2025_basic_device_info(同步全部激活时间)", use_container_width=True, key="dijia_ops_copy_basic_year_btn"):
_run_script_action("copy_basic_year", "同步 dj_2025_basic_device_info", year=2025)
st.caption("""
**操作说明:**
同步 dj_2021_settle_details 里面的激活时间到 dj_2025_basic_device_info 里面
""")
def _run_script_action(action, action_name_prefix, year=None):
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
script_path = os.path.join(base_dir, "2-report_generation", "dj", "generateDetailData.py")
if not os.path.exists(script_path):
st.error(f"❌ 找不到明细生成脚本: {script_path}")
return
action_name = action_name_prefix
status_text = st.empty()
status_text.text(f"🚀 正在执行 {action_name}...")
with st.spinner(f"{action_name}处理中,请稍候..."):
cmd = [
sys.executable,
script_path,
"--action", action
]
if year is not None:
cmd.extend(["--year", str(year)])
try:
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
status_text.text(f"✅ {action_name}成功!")
st.success(f"✅ 嘀加-旧版本 {action_name}已成功完成。")
if result.stdout:
with st.expander("查看执行日志"):
st.code(result.stdout)
st.balloons()
else:
status_text.text(f"❌ {action_name}失败")
st.error(f"❌ {action_name}失败 (退出码: {result.returncode})")
if result.stderr or result.stdout:
with st.expander("查看错误详情"):
st.code(result.stdout + "\n" + result.stderr)
except Exception as e:
st.error(f"❌ 发生意外错误: {str(e)}")
def _show_ops_content(category, key_prefix):
st.write(f"当前管理业务: {category}")
st.info("该模块用于处理运维相关的操作,包括数据库表的初始化和结构更新。")
# 动态加载备份模块以获取数据库配置
try:
backup_module = load_local_module("table_backup_internal", "dj-ops/table_backup.py")
db_configs = backup_module.get_db_configs()
# 构造易读的数据库选项: key (host / db_name)
db_options = {}
for k, v in db_configs.items():
# 过滤掉格式不符合要求的配置(例如缺少 db_name 的遗留配置)
if isinstance(v, dict) and 'host' in v and 'db_name' in v:
db_options[f"{k} ({v['host']} / {v['db_name']})"] = k
except Exception as e:
st.error(f"无法加载数据库配置: {e}")
db_options = {}
# 数据库操作区
st.subheader("1. 数据库初始化/更新")
col_init1, col_init2 = st.columns([2, 1])
with col_init1:
selected_init_db_display = st.selectbox(
"选择要初始化的数据库:",
list(db_options.keys()),
key=f"{key_prefix}_init_db_select",
index=list(db_options.values()).index("device_detail_db") if "device_detail_db" in db_options.values() else 0
)
selected_init_db = db_options[selected_init_db_display]
if st.button("初始化/更新数据库表", type="primary", key=f"{key_prefix}_init_db_btn"):
with st.spinner(f"正在为 {selected_init_db} 执行数据库检查与更新..."):
try:
# 动态加载并执行 init_db
init_db_module = load_local_module("init_db_internal", "init_db.py")
init_db_module.init_database(db_key=selected_init_db)
st.success(f"[{selected_init_db}] 数据库表检查/更新任务完成!")
st.toast("数据库同步成功", icon="✅")
except Exception as e:
st.error(f"操作失败: {e}")
st.caption("""
**操作的数据库表:**
- `t_audit_zip_process` (压缩文件处理进度)
- `t_audit_zip_file_detail` (压缩包内文件明细)
- `t_audit_integrated_file` (整合后的文件记录)
- (以及 `schema.sql` 中定义的其他元数据表)
""")
with col_init2:
st.caption("说明:点击左侧按钮将读取 `schema.sql` 并同步至选中的数据库。脚本已启用安全拦截,不会删除现有表或数据。")
st.divider()
st.subheader("2. 数据备份")
st.write("选择数据库和表名,备份后的表名将自动加上 `_bak` 后缀。")
col_bak_db, col_bak_tab = st.columns(2)
with col_bak_db:
selected_bak_db_display = st.selectbox(
"选择备份源数据库:",
list(db_options.keys()),
key=f"{key_prefix}_bak_db_select",
index=list(db_options.values()).index("device_detail_db") if "device_detail_db" in db_options.values() else 0
)
selected_bak_db = db_options[selected_bak_db_display]
with col_bak_tab:
all_tables = backup_module.get_all_tables(selected_bak_db) if selected_bak_db else []
table_to_backup = st.selectbox("选择要备份的表名:", [""] + all_tables, key=f"{key_prefix}_bak_table_select")
manual_table = st.text_input("或者手动输入表名:", key=f"{key_prefix}_bak_input")
final_table = manual_table if manual_table else table_to_backup
if st.button("🚀 开始备份", key=f"{key_prefix}_bak_btn", use_container_width=True):
if not selected_bak_db:
st.warning("请先选择数据库!")
elif not final_table:
st.warning("请选择或输入要备份的表名!")
else:
with st.spinner(f"正在备份 {selected_bak_db} 中的表 {final_table}..."):
try:
success, message = backup_module.backup_table(selected_bak_db, final_table)
if success:
st.success(message)
st.balloons()
else:
st.error(message)
except Exception as e:
st.error(f"备份失败: {e}")
if final_table:
st.caption(f"**操作的数据库表:** `{final_table}_bak` (备份目标表)")
def show_with_category(category):
if category == "嘀加-旧版本":
show_dijia()
else:
show_edun()
def show():
show_with_category("E盾-智慧车管")
-- 项目数据库架构文件 (MySQL)
-- 数据库配置参考: config.yaml -> device_detail_db
-- 1. 压缩文件处理进度表
-- 用于记录上传/扫描到的压缩包,并跟踪其是否已被处理(解压、核对等)
CREATE TABLE IF NOT EXISTS `t_audit_zip_process` (
`id` INT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
`category` VARCHAR(100) COMMENT '业务分类 (如: E盾-智慧车管)',
`zip_name` VARCHAR(255) NOT NULL COMMENT '压缩文件名称',
`zip_path` VARCHAR(500) NOT NULL COMMENT '文件存储路径',
`file_size` BIGINT COMMENT '文件大小(字节)',
`process_status` TINYINT DEFAULT 0 COMMENT '处理状态: 0-待处理, 1-处理中, 2-处理完成, 3-处理失败',
`error_msg` TEXT COMMENT '失败时的错误信息',
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`remark` VARCHAR(500) COMMENT '备注',
UNIQUE KEY `uk_category_zip` (`category`, `zip_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='审计-压缩文件处理进度表';
-- 2. 压缩包内文件明细及匹配结果表
-- 用于记录压缩文件解压之后的具体文件列表、实际存储位置以及与标准表头的匹配情况
CREATE TABLE IF NOT EXISTS `t_audit_zip_file_detail` (
`id` INT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
`zip_id` INT NOT NULL COMMENT '关联的压缩包ID (t_audit_zip_process.id)',
`file_name` VARCHAR(255) NOT NULL COMMENT '解压后的文件名',
`file_path` VARCHAR(500) NOT NULL COMMENT '文件解压后的实际路径',
`file_size` BIGINT COMMENT '文件大小(字节)',
`file_type` VARCHAR(50) COMMENT '文件扩展名 (如 xlsx, xls, csv)',
`std_file_name` VARCHAR(255) COMMENT '匹配到的标准文件名',
`match_status` VARCHAR(100) COMMENT '匹配状态 (如: 精确匹配(规则), 灵活匹配, 未匹配)',
`match_score` INT DEFAULT 0 COMMENT '匹配分值',
`is_parsed` TINYINT DEFAULT 0 COMMENT '是否已解析数据: 0-否, 1-是',
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
INDEX `idx_zip_id` (`zip_id`),
INDEX `idx_std_file` (`std_file_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='审计-压缩包内文件明细及匹配结果表';
-- 3. 整合后的文件记录表
-- 用于记录整合(标准化)之后的文件信息,并与原始文件和标准表头对应
CREATE TABLE IF NOT EXISTS `t_audit_integrated_file` (
`id` INT AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
`zip_id` INT NOT NULL COMMENT '关联的压缩包ID (t_audit_zip_process.id)',
`std_file_name` VARCHAR(255) COMMENT '对应的标准文件名',
`source_file_path` VARCHAR(500) COMMENT '整合前的源文件路径',
`integrated_file_path` VARCHAR(500) COMMENT '整合后的文件路径',
`missing_cols` TEXT COMMENT '缺失的标准列 (JSON格式存储)',
`data_warnings` TEXT COMMENT '数据质量预警 (如负值、空值等)',
`row_count` INT DEFAULT 0 COMMENT '包含的数据行数',
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
INDEX `idx_zip_id` (`zip_id`),
INDEX `idx_std_name` (`std_file_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='审计-整合后的文件记录表';
# Audit Project
本项目用于审计相关数据的处理与核对。
## 目录结构说明
### 文件夹
- **[.streamlit](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/.streamlit)**: Streamlit 专用配置文件夹。
- **[1-business_data_audit](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/1-business_data_audit)**: 商务数据核对模块。
- `audit_page.py`: 该模块的界面实现代码。支持按业务分类(E盾/嘀加)上传和处理数据。
- **[1-input-原始压缩文件](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/1-business_data_audit/1-input-原始压缩文件)**: 存放用户上传的原始 ZIP 数据包。
- **[1-output-解压文件](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/1-business_data_audit/1-output-解压文件)**: 存放 ZIP 包解压后的明细文件,系统将基于此目录进行后续核对。
- **[1-documents](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/1-business_data_audit/1-documents)**: 存储商务提供的原始文档及核对报告。
- **[2-report_generation](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/2-report_generation)**: 设备明细数据生成模块。
- `report_page.py`: 该模块的界面实现代码。
- **[3-config_management](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/3-config_management)**: 配置管理模块。
- `config_page.py`: 该模块的界面实现代码。
- **[4-log_query](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/4-log_query)**: 日志查询模块。
- `log_page.py`: 该模块的界面实现代码。
- **[5-ops_management](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/5-ops_management)**: Ops 管理模块。
- `ops_page.py`: 该模块的界面实现代码。
- `init_db.py`: 数据库初始化工具脚本。自动读取 `config.yaml` 配置并执行 `schema.sql` 中的 SQL 语句。
- `schema.sql`: 数据库初始化脚本。包含项目所需的表结构定义,遵循统一的审计命名规范。
- **[config](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/config)**: 历史配置文件夹(保留)。
- **[logs](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/logs)**: 日志存放文件夹。
### 主要文件
- **[app.py](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/app.py)**: 基于 Streamlit 开发的 Web 交互界面。支持多页签操作,包括数据核对、设备明细数据生成、配置管理和日志查询。
- **[config.yaml](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/config.yaml)**: 项目通用配置文件。集中管理数据库连接串、文件路径、审计时间范围等业务参数,方便维护。
- **[requirements.txt](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/requirements.txt)**: 项目依赖清单。记录了运行本项目所需的 Python 第三方库及其版本。
- **[main.py](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/main.py)**: 项目的主程序入口,负责核心业务逻辑的调度。
- **[demo.py](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/demo.py)**: 演示或测试脚本,用于功能验证。
## 数据库安全维护
为了保护现有数据,[init_db.py](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/5-ops_management/init_db.py) 脚本已启用安全保护机制:
- **禁止删除**:脚本会自动拦截并跳过所有 `DROP`、`TRUNCATE` 和 `DELETE` 指令,防止表结构或数据被意外清空。
- **结构更新**:如果需要为现有表增加字段,请在 [schema.sql](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/5-ops_management/schema.sql) 中使用 `ALTER TABLE` 语句。脚本会安全地执行这些更新。
- **幂等性**:使用 `CREATE TABLE IF NOT EXISTS` 确保重复运行脚本不会报错,也不会影响已存在的表。
## 运行说明
1. 确保已安装依赖: `pip install -r requirements.txt`
2. 初始化数据库: `python 5-ops_management/init_db.py` (需先在 [config.yaml](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/config.yaml) 中配置正确的数据库信息)
3. 在 `project` 目录下启动应用: `streamlit run app.py`
4. 端口配置:可在 [.streamlit/config.toml](file:///d:/work/2.需求/11.审计/开发/3.代码/glsx-audit/project/.streamlit/config.toml) 文件中修改 `port` 参数。
import streamlit as st
import importlib.util
import os
import sys
# 设置页面配置
st.set_page_config(
page_title="Audit Management System",
page_icon="📊",
layout="wide"
)
def load_module(module_name, file_path):
# 将模块所在目录加入 sys.path,以便模块内部可以正常导入同级文件
module_dir = os.path.dirname(file_path)
if module_dir not in sys.path:
sys.path.insert(0, module_dir)
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def main():
# 侧边栏:大类选择
st.sidebar.title("业务分类")
business_category = st.sidebar.radio(
"请选择审计业务类型:",
["E盾-智慧车管", "嘀加-旧版本"],
index=0
)
st.sidebar.divider()
st.sidebar.info(f"当前操作业务:**{business_category}**")
st.title(f"审计管理系统 - {business_category}")
# 根据业务类型定义功能页签标题
if business_category == "E盾-智慧车管":
tab_titles = ["1.E盾-数据核对", "2.E盾-设备明细生成", "3.E盾-分摊全流程", "4.E盾-同步数据到审计库", "5.E盾-配置管理", "6.E盾-日志查询", "7.E盾-Ops管理"]
else: # 嘀加-旧版本
tab_titles = ["1.嘀加-数据核对", "2.嘀加-明细数据生成", "3.嘀加-分摊全流程", "4.嘀加-同步数据到审计库", "5.嘀加-配置管理", "6.嘀加-日志查询", "7.嘀加-Ops管理"]
tabs = st.tabs(tab_titles)
# 获取当前文件的目录
base_dir = os.path.dirname(os.path.abspath(__file__))
# 通用的模块加载函数,传入业务分类参数
def run_module(tab_index, module_folder, module_file):
with tabs[tab_index]:
try:
path = os.path.join(base_dir, module_folder, module_file)
module = load_module(module_folder, path)
# 传入 business_category 参数,以便页面内部做逻辑区分
if hasattr(module, 'show_with_category'):
module.show_with_category(business_category)
else:
module.show()
except Exception as e:
st.error(f"加载模块 {module_folder} 失败: {e}")
# 分别加载各功能模块
run_module(0, "1-business_data_audit", "audit_page.py")
run_module(1, "2-report_generation", "report_page.py")
run_module(2, "3-amortization_process", "amortization_page.py")
run_module(3, "4-data_sync", "sync_page.py")
run_module(4, "5-config_management", "config_page.py")
run_module(5, "6-log_query", "log_page.py")
run_module(6, "7-ops_management", "ops_page.py")
if __name__ == "__main__":
main()
# 项目全局配置文件
# 路径配置
paths:
upload_dir: "1-business_data_audit/1-documents/{category}/1-input-原始压缩文件"
extract_dir: "1-business_data_audit/1-documents/{category}/2-output-解压文件"
integrated_dir: "1-business_data_audit/1-documents/{category}/3-integrated-整合后的数据"
database:
device_detail_db:
host: "192.168.5.5"
port: 3310
user: "biz_device_detail"
password: "M6khz3CQ"
db_name: "device_detail"
charset: "utf8"
gps_db:
host: "192.168.5.22"
port: 3307
user: "user_wangxz"
password: "Nvd3OM7Y"
db_name: "gps"
charset: "utf8"
supplychain_db:
host: "192.168.5.23"
port: 3306
user: "user_wangxz"
password: "Nvd3OM7Y"
db_name: "glsx_supplychain"
charset: "utf8"
neshield_db:
host: "192.168.5.23"
port: 3306
user: "user_wangxz"
password: "Nvd3OM7Y"
db_name: "neshield"
charset: "utf8"
glsx_data_db:
host: "192.168.5.5"
port: 3310
user: "biz_device_detail"
password: "M6khz3CQ"
db_name: "glsx_data"
charset: "utf8"
device_log_db:
host: "192.168.3.114"
port: 3306
user: "biz_device_log"
password: "vA3D7CzX"
db_name: "device_log_2022"
charset: "utf8"
dijia_db:
host: "192.168.5.2"
port: 3306
user: "biz_glsx_data"
password: "unEKczDc"
db_name: "glsx_biz_data"
charset: "utf8"
glsx_dj_db:
host: "192.168.5.23"
port: 3306
user: "data_house_user"
password: "ZhaiMiAxIg"
db_name: "glsx_dj"
charset: "utf8"
g_ghdj_dbcfg:
"host": "47.97.203.216"
"port": 3306
"user": "user_wangxl"
"passwd": "BbuJbiPM"
"db": "glsx_dj"
"charset": "utf8"
# 报表生成配置
report_generation:
fields:
huitong: ['settlement_time','bill_type','K3_settlement_customer','K3_hardware_settlement_customer','K3_service_settlement_customer','financial_time','receivable_number_hardware','receivable_number_installation_service','lease_term','quantity','GPS_installation_plan','VIN','main_device_number','sub_device_number_1','sub_device_number_2','sub_device_number_3','hardware_with_tax','hardware_tax_rate','hardware_without_tax','installation_with_tax','installation_tax_rate','installation_unit_price_without_tax','service_term','service_fee_with_tax','service_fee_tax_rate','service_fee_without_tax','revenue_with_tax','revenue_without_tax']
xufei: ['renewal_time','bill_type','K3_settlement_customer','financial_time','receivable_number','pricing_quantity','GPS_installation_plan','VIN','main_device_number','sub_device_number_1','sub_device_number_2','service_term','service_fee_with_tax','service_fee_tax_rate','service_fee_without_tax','revenue_with_tax','revenue_without_tax']
channel: ['entity', 'creator', 'bill_type', 'bill_number', 'business_date', 'supplier', 'customer', 'channel', 'category', 'item_code', 'item_name', 'product_type', 'device_type', 'financial_quantity', 'pricing_quantity', 'unit_price_with_tax', 'unit_price', 'tax_rate', 'amount_without_tax', 'tax_amount', 'total_amount_without_tax', 'unit_price_without_tax', 'hardware', 'hardware_tax_rate', 'installation', 'installation_tax_rate', 'service_without_tax', 'service_tax_rate', 'service_package','total_amount','revenue', 'cost_amount', 'business_type', 'amortization_term']
qr: ['closing_time', 'bill_type', 'K3_settlement_customer', 'K3_hardware_settlement_customer', 'K3_service_settlement_customer', 'financial_time', 'receivable_number_hardware', 'receivable_number_installation_service', 'lease_term_hardware_installation', 'quantity', 'GPS_installation_plan', 'VIN', 'main_device_number', 'sub_device_number_1', 'sub_device_number_2', 'hardware_with_tax', 'hardware_tax_rate', 'hardware_without_tax', 'installation_unit_price', 'installation_fee_tax_rate', 'installation_unit_price_without_tax', 'service_term', 'service_fee_with_tax', 'service_fee_tax_rate', 'service_fee_without_tax', 'revenue_with_tax', 'revenue_without_tax']
lyf: ['entity', 'creator', 'bill_type', 'bill_number', 'business_date', 'supplier', 'customer', 'channel', 'category', 'item_code', 'item_name', 'product_type', 'device_type', 'financial_quantity', 'pricing_quantity', 'unit_price_with_tax', 'unit_price', 'tax_rate', 'amount_without_tax', 'tax_amount', 'total_amount', 'total_amount_without_tax', 'unit_price_without_tax', 'hardware_total_without_tax', 'hardware_tax_rate', 'service_without_tax', 'service_tax_rate', 'service_package', 'revenue', 'cost_amount', 'business_type', 'amortization_term']
sheets:
sheets_01: ['汇通安装结算汇总-其他', '续费结算汇总', '虎哥E盾--渠道应收单', '汇通加融包结算汇总']
sheets_02: ['其它渠道']
tables:
huitong: 'd_es_huitong_raw_data'
xufei: 'd_es_xufei_raw_data'
channel: 'd_es_channel_raw_data'
qr: 'd_es_qr_raw_data'
lyf: 'd_es_lyf_raw_data'
device_details: 'd_eshield_device_details_2025'
service_details: 'd_eshield_service_details_2025'
rerun_conf: 'd_rerun_conf'
all_details: 'd_eshield_all_details_2025_detail'
rerun:
is_rerun: false
# 分摊流程配置
amortization_process:
edun:
# 同步到外部数据库时,需要排除 batch 列的表
exclude_batch_tables: ['d_eshield_renewal', 't_eshield_device', 't_eshield_device_detail', 't_eshield_receivables']
# 默认同步的表列表
default_sync_tables: ['d_eshield_renewal', 't_eshield_device', 't_eshield_device_detail', 't_eshield_receivables']
File mode changed
File mode changed
pandas
sqlalchemy
pymysql
numpy
streamlit
openpyxl
PyYAML
File mode changed
2026-03-21 15:55:31,179 - INFO - Starting audit basic data sync for year 2025
2026-03-21 15:55:31,244 - INFO - Connected to Target DB
2026-03-21 15:55:31,293 - INFO - Connected to Source DB
2026-03-21 15:55:31,294 - INFO - Starting sync_basic_device_info for year 2025
2026-03-21 15:55:31,305 - INFO - Table dj_2025_basic_device_info already exists.
2026-03-21 15:55:31,577 - INFO - Truncated dj_2025_basic_device_info
2026-03-21 15:55:31,578 - INFO - Executing insert for dj_2025_basic_device_info...
2026-03-21 15:55:34,054 - INFO - Successfully populated dj_2025_basic_device_info
2026-03-21 15:55:34,055 - INFO - Syncing to dj_basic_device_info...
2026-03-21 15:55:35,470 - INFO - Deleted existing data in dj_basic_device_info for batch 2025
2026-03-21 15:55:37,154 - INFO - Successfully inserted into dj_basic_device_info
2026-03-21 15:55:37,154 - INFO - Syncing to dj_device_details_return...
2026-03-21 15:55:37,234 - INFO - Deleted existing data in dj_device_details_return for range 2025-01-01 to 2026-01-01
2026-03-21 15:55:37,309 - INFO - Successfully inserted into dj_device_details_return
2026-03-21 15:55:37,310 - INFO - All tasks done.
This diff could not be displayed because it is too large.
import pandas as pd
import json
import os
def main():
print("开始读取本地JSON文件...")
try:
# 读取 JSON 文件
json_file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 't3.json')
with open(json_file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
results = data.get('data', [])
print(f"成功获取 {len(results)} 条数据,开始解析处理...")
# 战败客户名单
defeated_customers = [
'连志威', '张蔚然', '彭志峰', '咸宁市易达建材贸易有限公司王坤总',
'文龙', '周鑫', '刘琳','张春华'
]
# 处理并解析结果
processed_data_normal = []
processed_data_defeated = []
for row in results:
customer_name = row['customer_name']
reception_start_time = row['reception_start_time']
recording_url = row['recording_url']
detail_json_str = row['detail_json']
# 基础信息字典
record = {
'客户名称': customer_name,
'接待开始时间': reception_start_time,
'录音链接': recording_url,
}
# 解析 detail_json
if detail_json_str:
try:
# 如果 detail_json_str 是字符串,则解析,如果是列表则直接使用
detail_data = json.loads(detail_json_str) if isinstance(detail_json_str, str) else detail_json_str
if isinstance(detail_data, list):
# 将所有对话拼接成一个字符串,放在同一个单元格
dialogue_lines = []
for item in detail_data:
offset_ms = item.get('offset', 0)
# 将毫秒转换为 HH:MM:SS 格式
total_seconds = int(offset_ms) // 1000
hours = total_seconds // 3600
minutes = (total_seconds % 3600) // 60
seconds = total_seconds % 60
time_str = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
role = item.get('role', '')
content = item.get('content', '')
# 格式化每一行的输出
line = f"[{time_str}] 角色{role}: {content}"
dialogue_lines.append(line)
# 用换行符连接所有的对话记录
record['对话记录'] = "\n".join(dialogue_lines)
else:
record['解析状态'] = "JSON格式不是列表"
except json.JSONDecodeError:
record['解析状态'] = "无法解析为JSON"
record['原始JSON'] = str(detail_json_str)
else:
record['解析状态'] = "为空"
# 分类存储
if customer_name in defeated_customers:
processed_data_defeated.append(record)
else:
processed_data_normal.append(record)
# 转换为 DataFrame
df_normal = pd.DataFrame(processed_data_normal)
df_defeated = pd.DataFrame(processed_data_defeated)
# 导出为 Excel
output_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'reception_data_export.xlsx')
# 写入 Excel 文件的不同 Sheet
with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
if not df_normal.empty:
df_normal.to_excel(writer, sheet_name='成交记录', index=False)
if not df_defeated.empty:
df_defeated.to_excel(writer, sheet_name='战败记录', index=False)
print(f"数据已成功导出到: {output_file}")
except Exception as e:
print(f"发生错误: {e}")
if __name__ == "__main__":
main()
\ No newline at end of file \ No newline at end of file
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
import pandas as pd
from sqlalchemy import create_engine, text
import sys
import os
# 将 project 目录加入路径以导入配置
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'project', '2-report_generation'))
from device_detail_processor import get_db_engine_config, to_sql_native
import numpy as np
def test_huitong_db_logic():
# 1. 初始化引擎 (从项目配置获取)
engine = create_engine(get_db_engine_config('device_detail_db'))
test_table = "d_es_huitong_raw_data_test"
# 2. 准备模拟数据 (包含 NaN 以测试 fix)
df = pd.DataFrame([
{
'settlement_time': '2026-01-01',
'financial_time': '2026-01-16',
'hardware_without_tax': 100.50
},
{
'settlement_time': '2026-01-02',
'financial_time': '2026-01-17',
'hardware_without_tax': np.nan # 测试 NaN 写入
}
])
print(f"--- 开始测试表 {test_table} 的写入逻辑 ---")
# 3. 模拟删除逻辑
min_time, max_time = '2026-01-01', '2026-01-31'
delete_sql = f"delete from {test_table} where financial_time >= '{min_time}' and financial_time <='{max_time}'"
try:
print(f"执行删除 SQL: {delete_sql}")
with engine.begin() as con:
con.execute(text(delete_sql))
print("✅ 删除逻辑执行成功")
# 4. 模拟写入逻辑 (使用 to_sql_native)
print(f"执行 to_sql_native 写入 (包含 NaN 值)...")
to_sql_native(df, test_table, engine, if_exists="append")
print("✅ to_sql_native 写入逻辑执行成功 (NaN 已处理)")
except Exception as e:
print(f"❌ 测试失败: {e}")
finally:
print("--- 测试结束 ---")
if __name__ == "__main__":
test_huitong_db_logic()
File mode changed
记录仪服务分摊
1)退货明细价格处理——将退货表的金额列设为负数
create table temp_dj_device_details_return as
select * from dj_device_details_return
where device_type in (6,12501) and settle_time < '2026-01-01 00:00:00';
UPDATE temp_dj_device_details_return SET pk_price = -pk_price WHERE pk_price > 0 ;
2)明细数据汇总——将退货表和销售表合并
create table temp_dj_device_details_modify_serins_recalc
(select * from dj_device_details
where device_type in (6,12501) and settle_time < '2026-01-01 00:00:00' limit 1)
delete from glsx_data.temp_dj_device_details_modify_serins_recalc where id=78367
insert into glsx_data.temp_dj_device_details_modify_serins_recalc
select * from (
select * from dj_device_details
where device_type in (6,12501) and settle_time < '2026-01-01 00:00:00'
union
select * from temp_dj_device_details_return
where device_type in (6,12501) and settle_time < '2026-01-01 00:00:00')AA
3)添加索引
CREATE INDEX temp_dj_device_details_modify_serins_recalc_pk_price_IDX USING BTREE ON glsx_biz_data.temp_dj_device_details_modify_serins_recalc (pk_price);
CREATE INDEX temp_dj_device_details_modify_serins_recalc_pk_period_IDX USING BTREE ON glsx_biz_data.temp_dj_device_details_modify_serins_recalc (pk_period);
4)空值数据处理
UPDATE temp_dj_device_details_modify_serins_recalc SET pk_period = 24 WHERE pk_period = 0 OR pk_period IS NULL;
UPDATE temp_dj_device_details_modify_serins_recalc SET pk_price = 0 WHERE pk_price IS NULL;
import logging
import time
from datetime import datetime, timedelta
from decimal import Decimal
from itertools import groupby
import pymysql
pymysql.install_as_MySQLdb()
import pandas as pd
from dateutil.relativedelta import *
import sys
import os
# 将包含 MysqlUtility 的目录添加到系统路径中
current_dir = os.path.dirname(os.path.abspath(__file__))
dj_project_dir = os.path.join(current_dir, '..', '..', 'project', '2-report_generation', 'dj')
sys.path.append(dj_project_dir)
from MysqlUtility import MySQL
logger = logging.getLogger("deal_equity_data")
logger.setLevel(logging.DEBUG)
fileHandler = logging.FileHandler("import.log")
fileHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
g_pro_biz_dbcfg = {
"host": "192.168.5.5",
"port": 3310,
"user": "biz_device_detail",
"passwd": "M6khz3CQ",
"db": "glsx_data",
"charset": "utf8",
}
def add_one_month(date, i):
# Add one month to the date using timedelta
next_month = date + relativedelta(months=+i)
# print(next_month)
new_date = next_month.replace(day=1)
return new_date
def write_sql(sql):
logger.info(sql)
with open(
"/sql14.txt", "a+", encoding="utf8"
) as fw:
fw.write(sql.strip())
fw.write("\n")
class StringBuilder:
def __init__(self):
self.strings = []
def append(self, string):
self.strings.append(string)
def __str__(self):
return "".join(self.strings)
def paddnum_price(num):
return num if num is not None else 0
def paddstr(strx):
return (
"NULL"
if strx == None
else "'" + MySQLdb.escape_string(str(strx)).decode() + "'"
)
def calculate_installments(total_amount, duration_months, start_date_str):
start_date = datetime.strptime(start_date_str, "%Y-%m")
# 计算每月的分摊金额
monthly_installment = total_amount / duration_months
# 创建一个字典来存储分摊时间及对应金额
installments_map = {}
for i in range(duration_months):
installment_date = start_date + relativedelta(months=i)
installments_map[installment_date.strftime("%Y-%m")] = round(monthly_installment, 6)
return installments_map
if __name__ == "__main__":
device_type = "6,12501"
file_name = "记录仪分摊出货汇总(2025年-服务分摊111).csv"
sql = f"select sn,settle_merchant,DATE_FORMAT(settle_time, '%Y-%m')as start_time ,pk_period,IFNULL(pk_price,0) as total_price " \
f"FROM temp_dj_device_details_modify_serins_recalc where `device_type` IN ({device_type})"
bizConn = MySQL(g_pro_biz_dbcfg)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
result = bizConn.fetchAllRows()
data = []
obd_year_list = range(2020, 2031)
for row in result:
# logger.info(row)
lineValue = [row[0], row[1], row[2], str(row[3]), str(row[4])]
my_month_map = calculate_installments(row[4], row[3], row[2])
for year in obd_year_list:
monthList = ('01','02','03','04','05','06','07','08','09','10','11','12')
for month in monthList:
row_data = my_month_map.get(str(year)+"-"+str(month))
if row_data is None :
lineValue.append('0')
else:
lineValue.append(paddnum_price(row_data))
data.append(lineValue)
columns = [
"sn", "settle_merchant", "settle_time", "pk_period", "total_price",
*[f"{year}-{month:02d}分摊" for year in range(2020, 2031) for month in range(1, 13)]
]
df = pd.DataFrame(data, columns=columns)
# 转换分摊金额列为浮点数
for col in [col for col in df.columns if "分摊" in col]:
df[col] = df[col].astype(float)
# 按门店、月份、期限分组并计算总个数和总金额
grouped_df = df.groupby(["settle_merchant", "settle_time", "pk_period"]).agg({
'sn': 'count',
**{col: 'sum' for col in df.columns if "分摊" in col}
}).reset_index()
# 打印分组后的DataFrame
# print(grouped_df)
# 将结果写入文本文件
grouped_df.to_csv(f"{file_name}", index=False, sep=',')
# 车充记录仪-硬件退货收入(不用分摊,直接加总)
select sum(hw_price) from dj_device_details_return
where settle_time >= '2025-01-01 00:00:00' and settle_time< '2026-01-01 00:00:00'
and device_type in (6,12501)
-- 911297.8722
\ No newline at end of file \ No newline at end of file
{
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"pd.options.display.float_format = '{:.2f}'.format\n",
"from sqlalchemy import create_engine\n",
"import pandas as pd\n",
"\n",
"# 创建数据库连接对象\n",
"win_user = 'biz_device_detail' # 数据库用户名\n",
"win_password = 'M6khz3CQ' # 数据库密码\n",
"win_host = '192.168.5.5' # 数据库ip地址\n",
"win_port=3310 # 端口号\n",
"win_test = 'glsx_data' # 数据库\n",
"engine = create_engine(f'mysql+pymysql://{win_user}:{win_password}@{win_host}:{win_port}/{win_test}', echo=False)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"车充&记录仪收入: 硬件+安装"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 车充记录仪硬件收入 (数据表:广联系统结算单)\n",
"sql='''\n",
"select left(settle_time,4) as `year`,\n",
"sum(hw_price)as 硬件收入,\n",
"sum(install_price)as 安装费\n",
"from glsx_data.dj_device_details \n",
"where device_type in (6,12501) \n",
"group by `year`\n",
"'''\n",
"\n",
"data_hw=pd.read_sql(sql,engine)\n",
"data_hw.to_excel(r'C:\\Users\\kobe\\Desktop\\SAAS智慧门店结算单重算&分摊【发客户】\\分摊计算\\车充记录仪硬件收入_241231.xlsx',index=False)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
import logging
import time
import os
import sys
import argparse
from datetime import datetime
import pandas as pd
import numpy as np
import pymysql
def paddstr(strx):
return "NULL" if strx is None else "'" + pymysql.converters.escape_string(str(strx)) + "'"
def paddnum(numx, default="NULL"):
return default if numx is None else str(numx)
class MySQL:
def __init__(self, dbconfig):
self._conn = pymysql.connect(
host=dbconfig["host"],
port=dbconfig["port"],
user=dbconfig["user"],
password=dbconfig["passwd"],
database=dbconfig["db"],
charset=dbconfig["charset"],
)
self._cur = self._conn.cursor()
def query(self, sql):
try:
self._cur.execute(sql)
return True
except pymysql.Error as e:
print("数据库错误代码:", e.args[0], e.args[1])
return False
def insert(self, sql):
try:
self._cur.execute(sql)
self._conn.commit()
return True
except pymysql.Error as e:
print("数据库错误代码:", e.args[0], e.args[1])
return False
def update(self, sql):
try:
self._cur.execute(sql)
self._conn.commit()
return True
except pymysql.Error as e:
print("数据库错误代码:", e.args[0], e.args[1])
return False
def fetchAllRows(self):
return self._cur.fetchall()
def close(self):
try:
self._cur.close()
self._conn.close()
except:
pass
logger = logging.getLogger("deal_equity_data_fast")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.DEBUG)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
g_pro_biz_dbcfg = {
"host": "192.168.5.2",
"port": 3306,
"user": "biz_glsx_data",
"passwd": "unEKczDc",
"db": "glsx_biz_data",
"charset": "utf8",
}
def prepare_data(year, db_config):
print(f"Preparing data for year {year}...")
conn = MySQL(db_config)
cutoff_date = f"{year + 1}-01-01 00:00:00"
# 1)退货明细价格处理——将退货表的金额列设为负数
print("Step 3.1: Processing return details...")
conn.update("DROP TABLE IF EXISTS temp_dj_device_details_return")
sql_create_return = f"""
create table temp_dj_device_details_return as
select * from dj_device_details_return
where device_type in (6,12501) and settle_time < '{cutoff_date}'
"""
conn.update(sql_create_return)
conn.update("CREATE INDEX temp_dj_device_details_return_pk_price_IDX USING BTREE ON temp_dj_device_details_return (pk_price)")
conn.update("UPDATE temp_dj_device_details_return SET pk_price = -pk_price WHERE pk_price > 0")
# 2)明细数据汇总——将退货表和销售表合并
print("Step 3.2: Summarizing details...")
conn.update("DROP TABLE IF EXISTS temp_dj_device_details_modify_serins_recalc")
sql_create_main = f"""
create table temp_dj_device_details_modify_serins_recalc as
select * from dj_device_details
where device_type in (6,12501) and settle_time < '{cutoff_date}'
union
select * from temp_dj_device_details_return
where device_type in (6,12501) and settle_time < '{cutoff_date}'
"""
conn.update(sql_create_main)
# 3.3 添加索引
print("Step 3.3: Adding indexes...")
conn.update("CREATE INDEX temp_dj_device_details_modify_serins_recalc_pk_price_IDX USING BTREE ON temp_dj_device_details_modify_serins_recalc (pk_price)")
conn.update("CREATE INDEX temp_dj_device_details_modify_serins_recalc_pk_period_IDX USING BTREE ON temp_dj_device_details_modify_serins_recalc (pk_period)")
# 3.4 空值数据处理
print("Step 3.4: Handling null values...")
conn.update("UPDATE temp_dj_device_details_modify_serins_recalc SET pk_period = 24 WHERE pk_period = 0 OR pk_period IS NULL")
conn.update("UPDATE temp_dj_device_details_modify_serins_recalc SET pk_price = 0 WHERE pk_price IS NULL")
print("Data preparation complete.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Calculate monthly share tracker (Fast Version)")
parser.add_argument("--year", type=int, default=2025, help="Year for calculation")
parser.add_argument("--output_dir", type=str, default="", help="Output directory for generated files")
args = parser.parse_args()
prepare_data(args.year, g_pro_biz_dbcfg)
bizConn = MySQL(g_pro_biz_dbcfg)
device_type = "6,12501"
# 获取最大月份
max_month_sql = "SELECT DATE_FORMAT(MAX(settle_time), '%Y-%m') FROM temp_dj_device_details_modify_serins_recalc"
bizConn.query(max_month_sql)
max_month_row = bizConn.fetchAllRows()
max_month_str = max_month_row[0][0] if max_month_row and max_month_row[0][0] else f"{args.year}-12"
try:
max_month_only = int(max_month_str.split('-')[1])
except:
max_month_only = 12
file_name = f"记录仪分摊出货汇总({args.year}年-服务分摊-截至{max_month_only}月).csv"
# 将查询结果按 settle_merchant, settle_time, pk_period 聚合,减少内存加载的数据量
print("Fetching and aggregating data from database...")
sql = f"""
SELECT
settle_merchant,
DATE_FORMAT(settle_time, '%Y-%m') as start_time,
pk_period,
COUNT(sn) as sn_count,
SUM(IFNULL(pk_price,0)) as sum_total_price
FROM temp_dj_device_details_modify_serins_recalc
WHERE device_type IN ({device_type})
GROUP BY settle_merchant, DATE_FORMAT(settle_time, '%Y-%m'), pk_period
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
sys.exit(1)
result = bizConn.fetchAllRows()
print(f"Loaded {len(result)} aggregated rows.")
# 构建需要生成的所有月份列
obd_year_list = range(2020, 2031)
month_cols = [f"{year}-{month:02d}分摊" for year in obd_year_list for month in range(1, 13)]
# 建立一个列名到索引的映射,以便快速赋值
col_to_idx = {col: i for i, col in enumerate(month_cols)}
# 输出数据结构
processed_data = []
print("Calculating installments using vectorized logic...")
for row in result:
settle_merchant = row[0]
start_time_str = row[1]
pk_period = int(row[2])
sn_count = int(row[3])
sum_total_price = float(row[4])
# 基础数据:合并后的聚合不需要逐行展开 sn,只需要记录总个数和总金额
base_info = [settle_merchant, start_time_str, str(pk_period), sn_count, sum_total_price]
# 初始化 132 个月份的分摊金额为 0.0
installment_array = [0.0] * len(month_cols)
if pk_period > 0 and sum_total_price != 0:
monthly_installment = round(sum_total_price / pk_period, 6)
# 计算起始日期的年月
start_y, start_m = map(int, start_time_str.split('-'))
# 批量填充金额
for i in range(pk_period):
# 计算当前加上 i 个月后的年和月
current_m = start_m + i - 1
curr_year = start_y + (current_m // 12)
curr_month = (current_m % 12) + 1
col_name = f"{curr_year}-{curr_month:02d}分摊"
if col_name in col_to_idx:
installment_array[col_to_idx[col_name]] = monthly_installment
processed_data.append(base_info + installment_array)
# 组合 DataFrame
columns = ["settle_merchant", "settle_time", "pk_period", "sn", "total_price"] + month_cols
print("Creating DataFrame...")
grouped_df = pd.DataFrame(processed_data, columns=columns)
# 由于已经在 SQL 层面进行了 group by 聚合,这里不需要再调用 df.groupby(),直接就是最终结果。
# 只需确保分摊列类型为 float,以及对可能存在完全相同的 (商户,时间,期限) 数据再做一次安全聚合(防御性)
grouped_df = grouped_df.groupby(["settle_merchant", "settle_time", "pk_period"]).agg({
'sn': 'sum',
'total_price': 'sum',
**{col: 'sum' for col in month_cols}
}).reset_index()
# 调整列顺序与原脚本保持一致:但注意原脚本中聚合后没有 total_price,如果你需要可以保持,
# 但根据原脚本 `**{col: 'sum' for col in df.columns if "分摊" in col}` 来看,
# 原脚本输出列包含 settle_merchant, settle_time, pk_period, sn(其实是count), 及所有分摊列。
# 这里我们也保持一致。
# 将结果写入 CSV 文件
output_dir = args.output_dir if args.output_dir else os.path.dirname(os.path.abspath(__file__))
if not os.path.exists(output_dir):
os.makedirs(output_dir, exist_ok=True)
full_file_name = os.path.join(output_dir, file_name)
grouped_df.to_csv(full_file_name, index=False, sep=',')
print(f"GENERATED_CSV:{os.path.abspath(full_file_name)}")
【dj_basic_device_info_test_2512_version2 和 dj_basic_device_info_test_2512 制表过程一样
dj_device_details_2512_dtt 和 dj_device_details_2512_dtt_version2 制表过程一样
dj_2025_settlment_order_2512 和 dj_2025_settlment_order_2512_version2 制表过程一样】
------------------ 1 设备表 dj_basic_device_info_test_2512 (找出今年新增的设备,往年的设备不再匹配) --------------------------------
drop table dj_basic_device_info_test_2512
CREATE TABLE dj_basic_device_info_test_2512 (
id INT(11),
sn VARCHAR(32),
device_type INT(11),
delivery_time DATETIME,
delivery_merchant VARCHAR(64),
active_time DATETIME,
active_merchant VARCHAR(64),
pk_name VARCHAR(32),
pk_period INT(10),
user_id INT(11),
alloc TINYINT(2),
b_sn VARCHAR(50)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
INSERT INTO glsx_data.dj_basic_device_info_test_2512
SELECT DISTINCT
a.id,
a.sn,
a.device_type,
a.delivery_time,
a.delivery_merchant,
a.active_time,
a.active_merchant,
a.pk_name,
a.pk_period,
a.user_id,
a.alloc,
b.sn AS b_sn
FROM glsx_data.dj_basic_device_info a
LEFT JOIN (select * from glsx_data.dj_device_details where settle_time <'2025-01-01') b
ON a.sn = b.sn
-- 为了提高建表速度,首先把下面语句用到的表创建索引
alter table glsx_data.dj_basic_device_info_test_2512 add index sn_id(sn)
-- 一定要记得把上期未匹配的打上标签,这次不再匹配了,否则会错位
update dj_basic_device_info_test_2512
set alloc =1
where b_sn is not null
update dj_basic_device_info_test_2512
set alloc = 0
where b_sn is null
select alloc, count(distinct sn) from dj_basic_device_info_test_2512
group by alloc
------------------ 2 应收单备份 dj_2025_settlment_order_2512_version2 ------------------------------------
drop table glsx_data.dj_2025_settlment_order_2512_version2
create table glsx_data.dj_2025_settlment_order_2512_version2(
select * from glsx_data.dj_2025_settlment_order where finance_time>='2025-01-01'
and finance_time<'2026-01-01'
) -- 筛选客户应收单原表中20250101-20251231之间的数据,将其复制到一个新表dj_2025_settlment_order_2512
select count(1) from dj_2025_settlment_order_2512_version2
select count(1) from dj_2025_settlment_order
-- 新表数据完整
update glsx_data.dj_2025_settlment_order_2512_version2
set status =0, match_total =0 -- 将dj_2025_settlment_order_2512中的status和match_total两个字段全都设置成0
where 1=1; -- 1=1 是一个恒为真的条件,因此这个条件会匹配表中的所有行
-- 改名 status 到 match_status
ALTER TABLE glsx_data.dj_2025_settlment_order_2512_version2
CHANGE status match_status tinyint(4) DEFAULT 0 NULL COMMENT '处理状态,0:未处理';
-- status 字段:(1)重命名为 match_status;(2)修改数据类型为 tinyint(4);(3)设置默认值为 0,并允许字段值为 NULL;(4)为字段添加注释,说明其用途和取值含义。
-------------------------- 3 备份客户结算单 -----------------------------------------------
drop table glsx_data.dj_device_details_251231_version2
CREATE TABLE glsx_data.dj_device_details_251231_version2 (
id INT(11),
channel VARCHAR(16),
sn VARCHAR(32),
device_type INT(11),
delivery_time DATETIME,
delivery_merchant VARCHAR(64),
active_time DATETIME,
active_merchant VARCHAR(64),
pk_name VARCHAR(32),
pk_period INT(10),
settle_merchant VARCHAR(64),
settle_order VARCHAR(64),
settle_time DATETIME,
pk_price FLOAT(12,4),
hw_price FLOAT(12,4),
install_price FLOAT(12,4),
hw_cost FLOAT(12,4),
install_cost FLOAT(12,4)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into glsx_data.dj_device_details_251231_version2
select * from glsx_data.dj_device_details
select count(1) from dj_device_details_251231_version2
select count(1) from dj_device_details
---------------------------4 创建dtt重算结果表 -----------------------------------------------
drop table glsx_data.dj_device_details_2512_dtt_version2
create table glsx_data.dj_device_details_2512_dtt_version2(select * from glsx_data.dj_device_details_251231_version2 limit 1)
delete from glsx_data.dj_device_details_2512_dtt_version2 where id=1
-- 加索引提速
alter table glsx_data.dj_device_details_251231_version2 add index sn_id(sn)
alter table glsx_data.dj_device_details_2512_dtt_version2 add index sn_id(sn)
ALTER TABLE glsx_data.dj_2025_settlment_order_2512_version2 add index sn_id(id)
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!