Commit 86ad4e4b by 周立明

阿维塔模板下载

1 parent b0af501f
# 2026-11-16
- 排查零跑专项 task65(2026-10)「业务库(dj_smartcarlife)连接失败」:账号 `read_dj_smartcarlife` 当前可用(TCP/登录/15 次重复连接/完整 collect_data 均成功,门店 5 家、9 个评灯节点);`.env*` 未覆盖 `BIZ_SQL_DATABASE_URL`,生效值仍是 config.py 默认 `192.168.5.23:3306/dj_smartcarlife`。判定为当时瞬时连接故障,非账号失效。
- 修复 `leapmotor_processor.py`:连接失败异常改为 `f"业务库(dj_smartcarlife)连接失败:{biz_sql_last_error()}"`,并在 import 中补 `biz_sql_last_error`,与广爱专项一致;下次失败可在任务 error_msg 看到原始异常。改动需重启后端生效。
# 2026-11-19
- 阿维塔专项新增「下载模板」链接:按用户选择做**静态空白模板**,不预填门店名。
- 新增 `data-process/import_templates/阿维塔专项-主机厂数据表模板.xlsx`:基于历史附件结构(双层表头 + 12 列 + 末尾 4 个汇总标签),保留合并表头 A1:A2/B1:B2/C1:C2/D1:D2/E1:E2/F1:J1/K1:L1;表头月份改为通用「主机厂数据 / 广联数据」;明细区 20 空行;汇总标签为「阿维塔品牌汇总/售后门店数/售后场景开通率/售后订单数」,数值清空。
- `config.py` 的 `DATA_TABLE_TYPES['avita_special']` 增加 `templates: {'主机厂数据表': '阿维塔专项-主机厂数据表模板.xlsx'}`。前端 `list.js` 已有通用逻辑,无需改 JS/后端接口;链接文案自动为「⬇ 下载主机厂数据表模板」。
- 验证:模板存在;按 `avita_special_processor._parse` 同口径模拟解析 → 0 明细行、品牌汇总命中、三项汇总值为空。改 config 后须重启后端生效。
## 下午追加:改为预填门店名称(用户要求)
- 门店来源经用户确认选 **D+ 阿维塔项目组**:`pg_group_info.group_name='阿维塔'` + `pg_group_store_rel`(deleted_flag='N',按 pgr.id desc),当前 7 家;与历史附件 8 家不一致,未采用历史名单。
- `avita_special_processor.py` 新增 `AVITA_ATTACH_TEMPLATE_PATH`(指向上一步静态 xlsx,作底稿)与 `build_attachment_template()`:D+ 不可达时退化为空门店模板;A3 起连续写门店名,至少保留 20 行数据区,汇总段顺延,其余列/汇总数值清空。
- `app.py` 新增 `GET /api/avita/template`;`static/js/list.js` 对 `avita_special` 走该接口,文案「⬇ 下载模板(门店名称已预填,请勿修改门店名称列)」。config 中 `templates` 保留作底稿,前端不再直接走通用接口。
- 验证:py_compile 通过;实际生成预填 7 家门店,汇总段位于 24~27 行;按 `_parse` 同口径模拟 → 7 明细行、品牌命中、汇总值为空。预览文件 `outputs/avita_special_attachment_template_preview.xlsx`。
- ⚠ 改动涉及 config/processor/app,**须重启后端**才生效。
- 追加修正:`build_attachment_template()` 汇总段不再固定/保留 20 行数据区,改为 `data_end = 2 + n`、`srow = data_end + 2`(最后一行门店后空 1 行);间隔行清空样式。实测 7 家 → 明细 3~9 行、空行 10、汇总 11~14 行,解析仍为 7 明细 + 汇总标签。
...@@ -673,6 +673,23 @@ def baic_template(): ...@@ -673,6 +673,23 @@ def baic_template():
return _xlsx_attachment_response(BytesIO(data), '北汽专项-门店数据模板.xlsx') return _xlsx_attachment_response(BytesIO(data), '北汽专项-门店数据模板.xlsx')
@app.get('/api/avita/template')
@login_required
def avita_template():
"""阿维塔专项:下载主机厂数据表模板(门店名称系统预填)"""
from avita_special_processor import AvitaSpecialProcessor
from io import BytesIO
import shutil
proc = AvitaSpecialProcessor(app=app)
path, tmp_dir = proc.build_attachment_template()
try:
with open(path, 'rb') as f:
data = f.read()
finally:
shutil.rmtree(tmp_dir, ignore_errors=True)
return _xlsx_attachment_response(BytesIO(data), '阿维塔专项-主机厂数据表模板.xlsx')
@app.get('/api/tasks/<int:task_id>/download') @app.get('/api/tasks/<int:task_id>/download')
@login_required @login_required
def task_download(task_id): def task_download(task_id):
......
...@@ -29,6 +29,7 @@ import logging ...@@ -29,6 +29,7 @@ import logging
import os import os
import tempfile import tempfile
from calendar import monthrange from calendar import monthrange
from copy import copy
from datetime import datetime, date from datetime import datetime, date
from decimal import Decimal, InvalidOperation from decimal import Decimal, InvalidOperation
...@@ -38,7 +39,7 @@ from openpyxl.styles import Font, PatternFill, Alignment, Border, Side ...@@ -38,7 +39,7 @@ from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from sqlalchemy import create_engine, text from sqlalchemy import create_engine, text
from config import Config from config import Config
from report_utils import ( from report_utils import (
mark_task_failed, cleanup_tmp_dir, download_all_files, mark_task_failed, cleanup_tmp_dir, download_all_files, _get_biz_sql_conn,
) )
from oss_utils import upload_file from oss_utils import upload_file
from models import ( from models import (
...@@ -51,6 +52,11 @@ AVITA_TEMPLATE_PATH = os.path.join( ...@@ -51,6 +52,11 @@ AVITA_TEMPLATE_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)), os.path.dirname(os.path.abspath(__file__)),
'exporttemplete', 'avita_special_report_template.xlsx') 'exporttemplete', 'avita_special_report_template.xlsx')
# 附件导入模板底稿(静态空白版);下载接口会据此动态预填 D+ 阿维塔项目组门店名称
AVITA_ATTACH_TEMPLATE_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'import_templates', '阿维塔专项-主机厂数据表模板.xlsx')
logger = logging.getLogger('AvitaSpecialProcessor') logger = logging.getLogger('AvitaSpecialProcessor')
AVITA_TYPE = 'avita_special' AVITA_TYPE = 'avita_special'
...@@ -433,6 +439,99 @@ class AvitaSpecialProcessor: ...@@ -433,6 +439,99 @@ class AvitaSpecialProcessor:
def __init__(self, app=None): def __init__(self, app=None):
self.app = app self.app = app
def build_attachment_template(self):
"""基于静态空白底稿预填门店名称,返回临时文件路径与临时目录。
门店来源:D+ `pg_group_info.group_name='阿维塔'` + `pg_group_store_rel`,
按 pgr.id 倒序、按门店名去重;D+ 不可达/查询失败时退化为空门店模板。
布局:A3 起连续写门店名;汇总段不固定,紧跟最后一行门店并空一行,
其余列及汇总数值保持空白。
"""
store_names = []
conn = _get_biz_sql_conn()
if conn is None:
logger.warning('[阿维塔] 附件模板预填:D+ 连接失败,生成空门店模板')
else:
try:
rows = conn.execute(text(
"select pgr.merchant_name "
"from pg_group_info pg "
"inner join pg_group_store_rel pgr on pg.id = pgr.group_id "
" and pgr.deleted_flag = 'N' "
"where pg.deleted_flag = 'N' and pg.group_name = :gname "
"order by pgr.id desc"
), {'gname': '阿维塔'}).fetchall()
seen = set()
for r in rows:
name = r[0]
if name and name not in seen:
seen.add(name)
store_names.append(name)
except Exception as e:
logger.warning(f'[阿维塔] 附件模板预填:门店查询失败,生成空门店模板: {e}')
finally:
conn.close()
logger.info(f'[阿维塔] 附件模板预填门店 {len(store_names)} 家')
wb = openpyxl.load_workbook(AVITA_ATTACH_TEMPLATE_PATH)
ws = wb[wb.sheetnames[0]]
max_col = ws.max_column
summary_labels = [BRAND_SUMMARY_LABEL] + list(SUMMARY_LABELS.keys())
# 捕获底稿数据行样式与汇总段样式(汇总段位置随门店数变化)
name_style = [copy(ws.cell(3, c)._style) for c in range(1, max_col + 1)]
summary_styles = {}
for r in range(3, ws.max_row + 1):
v = ws.cell(r, 1).value
if v in summary_labels:
summary_styles[v] = (
[copy(ws.cell(r, c)._style) for c in range(1, max_col + 1)],
ws.row_dimensions[r].height,
)
# 清空第 3 行起的旧值(含底稿汇总段),再按实际门店数重写
for r in range(3, ws.max_row + 1):
for c in range(1, max_col + 1):
ws.cell(r, c).value = None
n = len(store_names)
for i, name in enumerate(store_names):
r = 3 + i
for c in range(1, max_col + 1):
ws.cell(r, c)._style = copy(name_style[c - 1])
ws.cell(r, 1).value = name
data_end = 2 + n
srow = data_end + 2 # 与最后一行门店之间留一行空行
# 间隔行清空样式,避免残留底稿边框被误认为可填门店行
for c in range(1, max_col + 1):
cell = ws.cell(srow - 1, c)
cell.value = None
cell.font = Font()
cell.fill = PatternFill()
cell.border = Border()
cell.alignment = Alignment()
cell.number_format = 'General'
for i, label in enumerate(summary_labels):
r = srow + i
style, height = summary_styles[label]
for c in range(1, max_col + 1):
ws.cell(r, c)._style = copy(style[c - 1])
ws.cell(r, c).value = None
ws.cell(r, 1).value = label
if height:
ws.row_dimensions[r].height = height
last_row = srow + len(summary_labels) - 1
if ws.max_row > last_row:
ws.delete_rows(last_row + 1, ws.max_row - last_row)
tmp_dir = tempfile.mkdtemp(prefix='avita_tpl_')
path = os.path.join(tmp_dir, '阿维塔专项-主机厂数据表模板.xlsx')
wb.save(path)
return path, tmp_dir
def process(self, task): def process(self, task):
"""处理单个阿维塔专项任务:解析源文件 → 落明细/汇总表 → 置 COMPLETED""" """处理单个阿维塔专项任务:解析源文件 → 落明细/汇总表 → 置 COMPLETED"""
task_id = task.id task_id = task.id
......
...@@ -204,6 +204,12 @@ class Config: ...@@ -204,6 +204,12 @@ class Config:
'forms': [ 'forms': [
'主机厂数据表', '主机厂数据表',
], ],
# 导入模板文件名(存放于 import_templates/ 目录)。
# 注:前端对 avita_special 走 /api/avita/template 动态预填 D+ 门店名称;
# 此静态文件仅作为动态生成底稿(通用接口仍可直接下载空表)。
'templates': {
'主机厂数据表': '阿维塔专项-主机厂数据表模板.xlsx',
},
}, },
# 北汽专项:当前仅需上传源数据表(表名暂定,后续若改名只改下方 forms)。 # 北汽专项:当前仅需上传源数据表(表名暂定,后续若改名只改下方 forms)。
# 注意:源文件「北汽专项源数据表」仅含线上运营手工上传类字段 # 注意:源文件「北汽专项源数据表」仅含线上运营手工上传类字段
......
...@@ -37,7 +37,7 @@ from sqlalchemy import text, bindparam ...@@ -37,7 +37,7 @@ from sqlalchemy import text, bindparam
from config import Config # noqa: F401 (保持与岚图一致的配置加载副作用) from config import Config # noqa: F401 (保持与岚图一致的配置加载副作用)
from indicator_client import IndicatorClient from indicator_client import IndicatorClient
from oss_utils import upload_file from oss_utils import upload_file
from report_utils import mark_task_failed, cleanup_tmp_dir, _get_biz_sql_conn from report_utils import mark_task_failed, cleanup_tmp_dir, _get_biz_sql_conn, biz_sql_last_error
from models import DataProcessTask, db from models import DataProcessTask, db
from voyah_processor import shorten_province from voyah_processor import shorten_province
...@@ -258,7 +258,7 @@ class LeapmotorProcessor: ...@@ -258,7 +258,7 @@ class LeapmotorProcessor:
# ---------- Step1: 业务库 SQL ---------- # ---------- Step1: 业务库 SQL ----------
conn = _get_biz_sql_conn() conn = _get_biz_sql_conn()
if conn is None: if conn is None:
raise Exception("业务库(dj_smartcarlife)连接失败") raise Exception(f"业务库(dj_smartcarlife)连接失败:{biz_sql_last_error()}")
try: try:
# 门店清单(按 pgr.id 倒序) # 门店清单(按 pgr.id 倒序)
......
...@@ -331,14 +331,17 @@ ...@@ -331,14 +331,17 @@
mFiles.appendChild(row); mFiles.appendChild(row);
// 该表单类型配置了导入模板时,显示「下载模板」链接(独立一行,避免与说明文字挤在同一 flex 行重叠) // 该表单类型配置了导入模板时,显示「下载模板」链接(独立一行,避免与说明文字挤在同一 flex 行重叠)
// 广爱专项的模板由后端动态生成(预填门店名称),不走 templates 配置,需单独放行 // 广爱专项的模板由后端动态生成(预填门店名称),不走 templates 配置,需单独放行
if (templates[formType] || mType.value === 'guangai_special') { if (templates[formType] || mType.value === 'guangai_special' || mType.value === 'avita_special') {
var tplRow = document.createElement('div'); var tplRow = document.createElement('div');
tplRow.style.cssText = 'margin:-6px 0 12px 142px;'; tplRow.style.cssText = 'margin:-6px 0 12px 142px;';
var tpl = document.createElement('a'); var tpl = document.createElement('a');
// 广爱专项保留原独立接口(门店名称系统预填),其余类型走通用模板下载接口 // 广爱/阿维塔专项走独立接口(门店名称系统预填),其余类型走通用模板下载接口
if (mType.value === 'guangai_special') { if (mType.value === 'guangai_special') {
tpl.href = '/api/guangai/template'; tpl.href = '/api/guangai/template';
tpl.textContent = '⬇ 下载模板(门店名称已预填,请勿修改门店名称列)'; tpl.textContent = '⬇ 下载模板(门店名称已预填,请勿修改门店名称列)';
} else if (mType.value === 'avita_special') {
tpl.href = '/api/avita/template';
tpl.textContent = '⬇ 下载模板(门店名称已预填,请勿修改门店名称列)';
} else { } else {
tpl.href = '/api/template/download?type=' + encodeURIComponent(mType.value) + tpl.href = '/api/template/download?type=' + encodeURIComponent(mType.value) +
'&form_type=' + encodeURIComponent(formType); '&form_type=' + encodeURIComponent(formType);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!