Commit 29a70092 by chenxi

广爱报表

1 parent 0e169e63
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
登录:账密登录/退出,账号由开发者预置到用户表,无注册入口。 登录:账密登录/退出,账号由开发者预置到用户表,无注册入口。
""" """
import os import os
import tempfile
# ========= OpenBLAS 内存分配问题修复 ========= # ========= OpenBLAS 内存分配问题修复 =========
# 限制 OpenBLAS 线程数,避免内存分配失败 # 限制 OpenBLAS 线程数,避免内存分配失败
...@@ -40,6 +41,7 @@ from scheduler import ( ...@@ -40,6 +41,7 @@ from scheduler import (
BaicSpecialScheduler, BaicSpecialScheduler,
RecruitmentScheduler, RecruitmentScheduler,
GlsxDailyScheduler, GlsxDailyScheduler,
GuangaiScheduler,
) )
app = Flask(__name__, static_folder='static', static_url_path='') app = Flask(__name__, static_folder='static', static_url_path='')
...@@ -131,9 +133,28 @@ def compute_week_period(month, week_num): ...@@ -131,9 +133,28 @@ def compute_week_period(month, week_num):
return first_day, ends[week_num - 1] return first_day, ends[week_num - 1]
def parse_period(data, tcfg): def _xlsx_attachment_response(file_bytes_or_path, download_name):
"""xlsx 附件下载响应:显式写 RFC 5987 Content-Disposition。
Werkzeug 的 send_file(download_name=中文) 会把非 ASCII 做 NFKD+ASCII-ignore
归一化,中文文件名被剥成 "-.xlsx"(2026-10-19 实测),故此处手工编码文件名。
"""
from urllib.parse import quote as _quote
from flask import send_file
# 必须先传 download_name(BytesIO 无路径时 werkzeug 会直接抛
# "No name provided for attachment");其生成的归一化文件名随后被覆盖。
resp = send_file(file_bytes_or_path, as_attachment=True,
download_name=download_name,
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
resp.headers['Content-Disposition'] = (
"attachment; filename*=UTF-8''" + _quote(download_name))
return resp
def parse_period(data, tcfg, data_table_type=None):
"""解析「所属周期」日期区间(period_start / period_end)。 """解析「所属周期」日期区间(period_start / period_end)。
- period_type='week':根据 month + week_num 反推日期(双重保险,忽略前端传入的 period_start/end); - period_type='week':根据 month + week_num 反推日期(双重保险,忽略前端传入的 period_start/end);
广爱专项(guangai_special)用累计制周区间(WN = 1日~当月第 N 个周日,仅 1~4 周);
- need_period=True 且 period_type='month'(或未传):必须提供两个 YYYY-MM-DD 日期,且结束 >= 开始; - need_period=True 且 period_type='month'(或未传):必须提供两个 YYYY-MM-DD 日期,且结束 >= 开始;
- need_period=False(如预算达成数据):返回 (None, None)。 - need_period=False(如预算达成数据):返回 (None, None)。
返回 (period_type, week_num, start_date, end_date);异常时抛 ValueError。 返回 (period_type, week_num, start_date, end_date);异常时抛 ValueError。
...@@ -147,6 +168,16 @@ def parse_period(data, tcfg): ...@@ -147,6 +168,16 @@ def parse_period(data, tcfg):
if period_type == 'week': if period_type == 'week':
if not tcfg.get('need_period') or not tcfg.get('support_week'): if not tcfg.get('need_period') or not tcfg.get('support_week'):
raise ValueError('该类型仅支持按月粒度,不可选择按周') raise ValueError('该类型仅支持按月粒度,不可选择按周')
if data_table_type == 'guangai_special':
# 广爱专项:累计制周区间,仅 1~4 周
try:
week_num = int(data.get('week_num'))
except (TypeError, ValueError):
raise ValueError('按周时必须提供合法的 week_num(1-4)')
from guangai_processor import compute_guangai_week_period
month = (data.get('month') or '').strip()
start, end = compute_guangai_week_period(month, week_num)
return period_type, week_num, start, end
if period_type == 'week': if period_type == 'week':
# 按周:强校验 week_num,后端计算权威日期区间 # 按周:强校验 week_num,后端计算权威日期区间
...@@ -353,7 +384,7 @@ def task_create(): ...@@ -353,7 +384,7 @@ def task_create():
# period_type='week' → 后端根据 month+week_num 双重保险反推日期区间 # period_type='week' → 后端根据 month+week_num 双重保险反推日期区间
# period_type='month' → need_period=True 的类型必填手动选,False 类型(预算达成)不传 # period_type='month' → need_period=True 的类型必填手动选,False 类型(预算达成)不传
try: try:
period_type, week_num, period_start, period_end = parse_period(data, tcfg) period_type, week_num, period_start, period_end = parse_period(data, tcfg, data_table_type=data_table_type)
except ValueError as e: except ValueError as e:
return fail(str(e)) return fail(str(e))
needs_period = tcfg.get('need_period') or period_type == 'week' needs_period = tcfg.get('need_period') or period_type == 'week'
...@@ -399,6 +430,32 @@ def task_create(): ...@@ -399,6 +430,32 @@ def task_create():
if len(uploaded) < len(tcfg['forms']): if len(uploaded) < len(tcfg['forms']):
return fail(f'请上传全部必填表单文件:{"、".join(tcfg["forms"])}') return fail(f'请上传全部必填表单文件:{"、".join(tcfg["forms"])}')
# 广爱专项:附件校验前置 —— 失败直接返回错误文件(浏览器下载),不生成任务记录
if data_table_type == 'guangai_special':
from guangai_processor import GuangaiProcessor
from oss_utils import download_file as _oss_download
from flask import send_file as _send_file
from io import BytesIO as _BytesIO
import shutil as _shutil
gp = GuangaiProcessor(app=app)
chk_dir = tempfile.mkdtemp(prefix='guangai_chk_')
try:
attach_local = os.path.join(chk_dir, '门店维度数据.xlsx')
_oss_download(uploaded[0]['file_url'], attach_local)
check = gp.validate_attachment_file(
attach_local, month, period_type, week_num,
period_start, period_end)
if not check['ok']:
err_path = os.path.join(chk_dir, '广爱专项-附件校验错误.xlsx')
gp.build_error_file(attach_local, check['errors'], err_path)
with open(err_path, 'rb') as f:
err_bytes = f.read()
return _xlsx_attachment_response(
_BytesIO(err_bytes), '广爱专项-附件校验错误.xlsx')
_guangai_rows = check['rows']
finally:
_shutil.rmtree(chk_dir, ignore_errors=True)
task = DataProcessTask(data_table_type=data_table_type, task = DataProcessTask(data_table_type=data_table_type,
data_table_type_name=tcfg['name'], data_table_type_name=tcfg['name'],
month=month, month=month,
...@@ -417,6 +474,12 @@ def task_create(): ...@@ -417,6 +474,12 @@ def task_create():
from report_utils import create_subtasks_for_task from report_utils import create_subtasks_for_task
create_subtasks_for_task(task.id) create_subtasks_for_task(task.id)
# 广爱专项:附件已在前置校验通过,此处入库(失败可「重新生成」)
if data_table_type == 'guangai_special':
from guangai_processor import GuangaiProcessor
GuangaiProcessor(app=app).store_validated_rows(
_guangai_rows, task.id, creator)
return ok(task.to_dict(), '单据创建成功,进入数据处理') return ok(task.to_dict(), '单据创建成功,进入数据处理')
...@@ -444,7 +507,7 @@ def task_regenerate(task_id): ...@@ -444,7 +507,7 @@ def task_regenerate(task_id):
# 所属周期 / 粒度:重新生成时可调整(包括 period_type 切换),类型与月份锁定 # 所属周期 / 粒度:重新生成时可调整(包括 period_type 切换),类型与月份锁定
try: try:
period_type, week_num, period_start, period_end = parse_period(data, tcfg) period_type, week_num, period_start, period_end = parse_period(data, tcfg, data_table_type=t.data_table_type)
except ValueError as e: except ValueError as e:
return fail(str(e)) return fail(str(e))
needs_period = tcfg.get('need_period') or period_type == 'week' needs_period = tcfg.get('need_period') or period_type == 'week'
...@@ -510,9 +573,52 @@ def task_regenerate(task_id): ...@@ -510,9 +573,52 @@ def task_regenerate(task_id):
from report_utils import create_subtasks_for_task from report_utils import create_subtasks_for_task
create_subtasks_for_task(t.id, reset=True) create_subtasks_for_task(t.id, reset=True)
# 广爱专项:重新生成时若重传了附件 → 先校验;失败直接返回错误文件,不改动任何状态
if t.data_table_type == 'guangai_special' and new_files:
from guangai_processor import GuangaiProcessor
from oss_utils import download_file as _oss_download
from flask import send_file as _send_file
from io import BytesIO as _BytesIO
import shutil as _shutil
gp = GuangaiProcessor(app=app)
chk_dir = tempfile.mkdtemp(prefix='guangai_chk_')
try:
attach_local = os.path.join(chk_dir, '门店维度数据.xlsx')
_oss_download(new_files[0]['file_url'], attach_local)
check = gp.validate_attachment_file(
attach_local, t.month, period_type, week_num,
period_start, period_end)
if not check['ok']:
err_path = os.path.join(chk_dir, '广爱专项-附件校验错误.xlsx')
gp.build_error_file(attach_local, check['errors'], err_path)
with open(err_path, 'rb') as f:
err_bytes = f.read()
return _xlsx_attachment_response(
_BytesIO(err_bytes), '广爱专项-附件校验错误.xlsx')
gp.store_validated_rows(check['rows'], t.id, updater)
finally:
_shutil.rmtree(chk_dir, ignore_errors=True)
return ok(t.to_dict(), '已重新生成数据流程,等待调度器处理') return ok(t.to_dict(), '已重新生成数据流程,等待调度器处理')
@app.get('/api/guangai/template')
@login_required
def guangai_template():
"""广爱专项:下载门店维度数据模板(门店名称系统预填)"""
from guangai_processor import GuangaiProcessor
from io import BytesIO
import shutil
proc = GuangaiProcessor(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):
...@@ -683,6 +789,7 @@ avita_special_scheduler = AvitaSpecialScheduler(app=app) ...@@ -683,6 +789,7 @@ avita_special_scheduler = AvitaSpecialScheduler(app=app)
baic_special_scheduler = BaicSpecialScheduler(app=app) baic_special_scheduler = BaicSpecialScheduler(app=app)
recruitment_scheduler = RecruitmentScheduler(app=app) recruitment_scheduler = RecruitmentScheduler(app=app)
glsx_daily_scheduler = GlsxDailyScheduler(app=app) glsx_daily_scheduler = GlsxDailyScheduler(app=app)
guangai_scheduler = GuangaiScheduler(app=app)
ALL_SCHEDULERS = [ ALL_SCHEDULERS = [
('budget_achievement', scheduler), ('budget_achievement', scheduler),
...@@ -700,6 +807,7 @@ ALL_SCHEDULERS = [ ...@@ -700,6 +807,7 @@ ALL_SCHEDULERS = [
('baic_special', baic_special_scheduler), ('baic_special', baic_special_scheduler),
('recruitment', recruitment_scheduler), ('recruitment', recruitment_scheduler),
('glsx_daily', glsx_daily_scheduler), ('glsx_daily', glsx_daily_scheduler),
('guangai_special', guangai_scheduler),
] ]
......
...@@ -103,6 +103,14 @@ class Config: ...@@ -103,6 +103,14 @@ class Config:
# 区域展示表「说明行」末尾的线上运营咨询人:默认林泽娜、邓锦婷,换人时改环境变量即可 # 区域展示表「说明行」末尾的线上运营咨询人:默认林泽娜、邓锦婷,换人时改环境变量即可
COMMON_EQUITY_ONLINE_OPERATORS = os.getenv('COMMON_EQUITY_ONLINE_OPERATORS', '林泽娜、邓锦婷') COMMON_EQUITY_ONLINE_OPERATORS = os.getenv('COMMON_EQUITY_ONLINE_OPERATORS', '林泽娜、邓锦婷')
# ---------- 广爱专项:D+ 主服务商户 ID(驻店类型"直营"判定基准) ----------
# 源码口径(ServiceMerchantService#dealSingleBusinessTypeData):
# yq_merchant_config.partner_merchant_id == 本 ID → directSalesFlag=1(直营)
# 生产 44217696 / 测试 44212541,按环境通过环境变量配置
GUANGAI_DJ_SERVICE_MERCHANT_ID = int(os.getenv('GUANGAI_DJ_SERVICE_MERCHANT_ID', '44212541'))
# 广爱专项:原厂权益商品类目 ID(goods_sub_order 一/二/三级商品类目任一命中即计入)
GUANGAI_ORIGINAL_EQUITY_GOODS_TYPE = int(os.getenv('GUANGAI_ORIGINAL_EQUITY_GOODS_TYPE', '189'))
# ---------- 业务系统 SQL 数据源(嘀加 dj_smartcarlife 库)---------- # ---------- 业务系统 SQL 数据源(嘀加 dj_smartcarlife 库)----------
BIZ_SQL_ENABLED = os.getenv('BIZ_SQL_ENABLED', 'true').lower() == 'true' BIZ_SQL_ENABLED = os.getenv('BIZ_SQL_ENABLED', 'true').lower() == 'true'
BIZ_SQL_DATABASE_URL = os.getenv( BIZ_SQL_DATABASE_URL = os.getenv(
...@@ -221,6 +229,7 @@ class Config: ...@@ -221,6 +229,7 @@ class Config:
'红黄门店数据', '红黄门店数据',
], ],
}, },
<<<<<<< Updated upstream
# 招聘管理:无需上传数据源表(forms 为空),need_period=False; # 招聘管理:无需上传数据源表(forms 为空),need_period=False;
# 处理引擎已接入:processor.py 路由至 RecruitmentProcessor # 处理引擎已接入:processor.py 路由至 RecruitmentProcessor
# (查 D+ dj_car_life_recruitment_demand → 聚合 I~AF → 落 recruitment_month_data → 渲染结果表 → 上传 OSS)。 # (查 D+ dj_car_life_recruitment_demand → 聚合 I~AF → 落 recruitment_month_data → 渲染结果表 → 上传 OSS)。
...@@ -230,5 +239,15 @@ class Config: ...@@ -230,5 +239,15 @@ class Config:
'need_period': False, 'need_period': False,
'support_week': False, 'support_week': False,
'forms': [], 'forms': [],
=======
# 广爱专项:附件驱动报表,支持按月/按周(累计制 W1~W4,无第 5 周),1 个附件
'guangai_special': {
'name': '广爱专项',
'need_period': True,
'support_week': True,
'forms': [
'门店维度数据',
],
>>>>>>> Stashed changes
}, },
} }
...@@ -1128,3 +1128,41 @@ class CommonEquityMonthSnapshot(db.Model): ...@@ -1128,3 +1128,41 @@ class CommonEquityMonthSnapshot(db.Model):
def to_dict(self): def to_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns} return {c.name: getattr(self, c.name) for c in self.__table__.columns}
class GuangaiStoreReportData(db.Model):
"""广爱专项-门店维度上传数据(附件解析入库,按 月+维度+商户+任务 唯一,重复上传覆盖)"""
__tablename__ = 'guangai_store_report_data'
__table_args__ = (
# ⚠ 唯一键必须含 task_id:周维度 week_num 非空,若仅 (month,period_type,week_num,merchant_id),
# 软删的旧行会永久占用键导致"重复上传=覆盖"必然冲突(2026-10-19 实测);
# month 维度因 week_num 为 NULL 侥幸不冲突。task_id 每次上传不同 → 不冲突,
# 当前有效行由 is_deleted=0 过滤保证。
db.UniqueConstraint('month', 'period_type', 'week_num', 'merchant_id',
'task_id', name='uq_guangai_store_dim'),
{'comment': '广爱专项-门店维度上传数据'},
)
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='主键ID')
month = db.Column(db.String(7), nullable=False, comment='所属月份 YYYY-MM')
period_type = db.Column(db.String(10), nullable=False, default='month',
comment='数据维度:month 整月 / week 周(W1~W4 累计制)')
week_num = db.Column(db.Integer, nullable=True, comment='周序号 1-4,按月时为 NULL')
period_start = db.Column(db.Date, nullable=True, comment='数据区间-开始日期')
period_end = db.Column(db.Date, nullable=True, comment='数据区间-结束日期')
merchant_id = db.Column(db.String(50), nullable=False, comment='商户号')
merchant_name = db.Column(db.String(200), nullable=False, comment='商户名称(唯一匹配键)')
brand = db.Column(db.String(50), nullable=False, comment='品牌:广汽丰田/广汽本田/广汽传祺')
after_sales_enabled = db.Column(db.String(10), nullable=False, comment='是否打通售后:是/否')
group_delivery_cnt = db.Column(db.Integer, nullable=False, default=0, comment='一店一群·交车数(≥0 整数)')
group_refer_cnt = db.Column(db.Integer, nullable=False, default=0, comment='一店一群·触客数(≥0 整数)')
refer_rate = db.Column(db.DECIMAL(10, 4), nullable=True, comment='触客率(可空;空=系统按 触客数÷交车数 计算)')
output_target = db.Column(db.DECIMAL(14, 2), nullable=True, comment='产值目标(元,可空,仅本次导出用)')
unit_target = db.Column(db.Integer, nullable=True, comment='件数目标(台,可空,仅本次导出用)')
task_id = db.Column(db.Integer, nullable=True, comment='关联的上传任务ID(可追溯)')
creator = db.Column(db.String(50), default='', comment='创建人')
updater = db.Column(db.String(50), default='', comment='更新人')
created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='最近更新时间')
is_deleted = db.Column(db.Integer, nullable=False, default=0, comment='是否删除:0正常 / 1已删除')
deleted_at = db.Column(db.DateTime, nullable=True, comment='删除时间')
...@@ -1487,10 +1487,17 @@ class DataProcessor: ...@@ -1487,10 +1487,17 @@ class DataProcessor:
LeapmotorProcessor(app=self.app).process(task) LeapmotorProcessor(app=self.app).process(task)
return return
<<<<<<< Updated upstream
if getattr(task, 'data_table_type', None) == 'recruitment': if getattr(task, 'data_table_type', None) == 'recruitment':
from recruitment_processor import RecruitmentProcessor from recruitment_processor import RecruitmentProcessor
logger.info(f"[处理任务] 路由 recruitment 任务 {task_id} 至 RecruitmentProcessor") logger.info(f"[处理任务] 路由 recruitment 任务 {task_id} 至 RecruitmentProcessor")
RecruitmentProcessor(app=self.app).process(task) RecruitmentProcessor(app=self.app).process(task)
=======
if getattr(task, 'data_table_type', None) == 'guangai_special':
from guangai_processor import GuangaiProcessor
logger.info(f"[处理任务] 路由 guangai_special 任务 {task_id} 至 GuangaiProcessor")
GuangaiProcessor(app=self.app).process(task)
>>>>>>> Stashed changes
return return
# 通用+权益:与 CommonEquityScheduler 共用同一处理逻辑,避免调度与手工处理行为不一致 # 通用+权益:与 CommonEquityScheduler 共用同一处理逻辑,避免调度与手工处理行为不一致
......
...@@ -859,3 +859,36 @@ class GlsxDailyScheduler(NewReportScheduler): ...@@ -859,3 +859,36 @@ class GlsxDailyScheduler(NewReportScheduler):
finally: finally:
self._is_processing = False self._is_processing = False
self._lock.release() self._lock.release()
class GuangaiScheduler(NewReportScheduler):
"""广爱专项报表独立调度器(扫描 guangai_special 类型任务)"""
OUTPUT_CATEGORY = 'guangai_special'
JOB_NAME = 'guangai_special_scan'
def _execute_scan(self):
if not self._lock.acquire(blocking=False):
logger.debug(f"[{self.JOB_NAME}] 上一轮处理尚未完成,跳过本轮扫描")
return
self._is_processing = True
self._last_run_time = datetime.now()
try:
logger.info(f"[{self.JOB_NAME}] 开始扫描 guangai_special 待处理任务")
with self.app.app_context():
from guangai_processor import GuangaiProcessor
processor = GuangaiProcessor(app=self.app)
result = processor.scan_guangai()
self._last_run_result = result
logger.info(f"[{self.JOB_NAME}] 扫描完成:成功 {result.get('success', 0)} 个,"
f"失败 {result.get('failed', 0)} 个")
except Exception as e:
logger.error(f"[{self.JOB_NAME}] 扫描执行异常: {str(e)}")
self._last_run_result = {'error': str(e)}
finally:
self._is_processing = False
self._lock.release()
...@@ -325,6 +325,17 @@ ...@@ -325,6 +325,17 @@
row.appendChild(upload); row.appendChild(upload);
row.appendChild(tip); row.appendChild(tip);
mFiles.appendChild(row); mFiles.appendChild(row);
// 广爱专项:「下载模板」独立一行(避免与说明文字挤在同一 flex 行重叠)
if (mType.value === 'guangai_special') {
var tplRow = document.createElement('div');
tplRow.style.cssText = 'margin:-6px 0 12px 142px;';
var tpl = document.createElement('a');
tpl.href = '/api/guangai/template';
tpl.style.cssText = 'color:#1890ff;font-size:13px;text-decoration:underline;';
tpl.textContent = '⬇ 下载模板(门店名称已预填,请勿修改门店名称列)';
tplRow.appendChild(tpl);
mFiles.appendChild(tplRow);
}
}); });
} }
...@@ -418,6 +429,7 @@ ...@@ -418,6 +429,7 @@
return options; return options;
} }
<<<<<<< Updated upstream
// 组装一个周选项:start 恒为当月 1 号,end 为传入的结束日期字符串 // 组装一个周选项:start 恒为当月 1 号,end 为传入的结束日期字符串
function makeWeekOption(w, monthVal, endStr) { function makeWeekOption(w, monthVal, endStr) {
var startStr = monthVal + '-01'; var startStr = monthVal + '-01';
...@@ -429,6 +441,33 @@ ...@@ -429,6 +441,33 @@
start: startStr, start: startStr,
end: endStr end: endStr
}; };
=======
// 广爱专项:周区间为「累计制」(WN = 当月1日 ~ 当月第 N 个周日,仅 W1~W4,无第 5 周)
function isGuangaiType() {
return mType.value === 'guangai_special';
}
function computeGuangaiWeekOptions(monthVal) {
if (!monthVal) return [];
var parts = monthVal.split('-');
var y = parseInt(parts[0], 10), m = parseInt(parts[1], 10);
var firstDay = new Date(y, m - 1, 1);
var jsDay = firstDay.getDay(); // 0=周日 .. 6=周六
var offset = (7 - jsDay) % 7; // 距第 1 个周日的天数(JS: 周日=0)
var firstSunday = new Date(y, m - 1, 1 + offset);
var monthStr = monthVal;
var options = [];
for (var w = 1; w <= 4; w++) {
var end = new Date(firstSunday);
end.setDate(firstSunday.getDate() + (w - 1) * 7);
options.push({
week: w,
label: 'W' + w + ' (' + (firstDay.getMonth() + 1) + '/1-' + (end.getMonth() + 1) + '/' + end.getDate() + ')',
start: monthStr + '-01',
end: fmtDate(end)
});
}
return options;
>>>>>>> Stashed changes
} }
// Date 对象 → 'YYYY-MM-DD' // Date 对象 → 'YYYY-MM-DD'
...@@ -443,7 +482,8 @@ ...@@ -443,7 +482,8 @@
function renderWeekSelect(monthVal) { function renderWeekSelect(monthVal) {
var sel = document.getElementById('mWeekSelect'); var sel = document.getElementById('mWeekSelect');
sel.innerHTML = ''; sel.innerHTML = '';
var opts = computeWeekOptions(monthVal); var opts = isGuangaiType() ? computeGuangaiWeekOptions(monthVal)
: computeWeekOptions(monthVal);
if (!opts.length) { sel.style.display = 'none'; return; } if (!opts.length) { sel.style.display = 'none'; return; }
opts.forEach(function (o) { opts.forEach(function (o) {
var opt = document.createElement('option'); var opt = document.createElement('option');
...@@ -464,7 +504,8 @@ ...@@ -464,7 +504,8 @@
// 根据周序号自动填入 period start/end // 根据周序号自动填入 period start/end
function applyWeekPeriod(weekNum) { function applyWeekPeriod(weekNum) {
var opts = computeWeekOptions(mMonth.value); var opts = isGuangaiType() ? computeGuangaiWeekOptions(mMonth.value)
: computeWeekOptions(mMonth.value);
var found = null; var found = null;
for (var i = 0; i < opts.length; i++) { for (var i = 0; i < opts.length; i++) {
if (opts[i].week === weekNum) { found = opts[i]; break; } if (opts[i].week === weekNum) { found = opts[i]; break; }
...@@ -682,10 +723,32 @@ ...@@ -682,10 +723,32 @@
var url = modalMode === 'regenerate' var url = modalMode === 'regenerate'
? '/api/tasks/' + editingTaskId + '/regenerate' ? '/api/tasks/' + editingTaskId + '/regenerate'
: '/api/tasks'; : '/api/tasks';
return api(url, { return fetch(url, {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload) body: JSON.stringify(payload)
}).then(function (r) {
if (r.status === 401) { location.href = '/login.html'; throw new Error('未登录'); }
var ct = (r.headers.get('Content-Type') || '');
// 广爱专项:附件校验失败 → 后端直接返回错误文件流,浏览器触发下载(不生成报表记录)
if (ct.indexOf('spreadsheet') !== -1 || ct.indexOf('octet-stream') !== -1) {
return r.blob().then(function (blob) {
var cd = r.headers.get('Content-Disposition') || '';
var m = /filename\*?=(?:UTF-8''|")?([^";]+)/i.exec(cd);
var fname = '广爱专项-附件校验错误.xlsx';
if (m) {
try { fname = decodeURIComponent(m[1].replace(/"/g, '')); } catch (e) {}
}
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = fname;
document.body.appendChild(a);
a.click();
setTimeout(function () { URL.revokeObjectURL(a.href); a.remove(); }, 1000);
throw { handled: true, message: '附件校验失败,已下载错误文件;本次未生成报表记录,请修正后重新提交' };
});
}
return r.json();
}); });
}).then(function (res) { }).then(function (res) {
hideLoading(); hideLoading();
...@@ -695,6 +758,7 @@ ...@@ -695,6 +758,7 @@
loadList(); loadList();
}).catch(function (e) { }).catch(function (e) {
hideLoading(); hideLoading();
if (e && e.handled) { toast(e.message, true); return; } // 已触发错误文件下载
toast(e.message || '提交失败', true); toast(e.message || '提交失败', true);
btn.disabled = false; btn.disabled = false;
}); });
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!