recruitment_processor.py 28.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
"""招聘管理报表处理器

数据来源:嘀加 dj_smartcarlife.dj_car_life_recruitment_demand(无需附件上传,直接查源库)。

==================== I~AF 列取值逻辑(用户 2026-10-19 提供)====================
SELECT business_type, brand,
       IFNULL(d.recruitment_quantity, 0) - (
           SELECT COUNT(0) FROM dj_car_life_recruitment_onboarding_plan p
           WHERE p.deleted_flag = 'N' AND p.demand_id = d.id
       ) AS pending_count,
       DATEDIFF(:cutoff_date, d.created_date) AS cycle_days
FROM dj_car_life_recruitment_demand d
WHERE d.deleted_flag = 'N'
  AND d.`status` = 1                       -- 招聘中
  AND d.business_type IN :biz_ids          -- 按业务类型取值替换

返回字段:
  - business_type : 业务类型编码(需映射:延保(1)/权益(2)/权益+延保(5)/轻改销售(3)/技师(4,8,6,7)/二手车(9))
  - brand         : 品牌(多品牌门店按优先级取唯一品牌,每条需求只纳入一个品牌统计)
                    优先级:问界 > 鸿蒙智行 > 广爱 > 北汽 > 阿维塔 > 零跑 > 岚图 > 其他品牌
  - pending_count : 待招人数 = 招聘数量 - 已入职计划数
  - cycle_days    : 账龄天数 = cutoff_date - created_date;周期档:优秀≤7 / 良好8-14 / 正常15-30 / 异常>30

结果表「统计」sheet 布局(已读模板确认):
  行 4-12  = 8 品牌 + 合计(I~AF 第一块「待招聘需求 业务×周期档」)
    B(2)=待招聘需求合计  C~H(3-8)=各业务合计   I~AF(9-32)=6业务×4档
    周期档顺序(每业务 4 列):优秀(≤7天)/良好(7-14天)/正常(14-30天)/异常(>30天)
  行 14-25 = 第二块「待招聘需求汇总(品牌×4档)」:模板为空,待后续逻辑(本版未填)。
  AG~AL(33-38) = 新增招聘需求(当月提的全部需求,按业务)— 见 fetch_new_rows
  AM~AR(39-44) = 月待招需求(当月提的待招需求,status=1,按业务)— 见 fetch_month_pending_rows
  AS(45)=入职人数(当月 dj_car_life_recruitment_onboarding_plan 入职计划总数,单值不区分品牌/业务,仅填合计行)— 见 fetch_entry_count
  AT(46)=离职人数(本系统无源数据,固定留 0,由使用人下载后手动填写)
  日期基准(AV 列):AU1=当前工作日(cutoff_date) / AU2=月初(当月1号) / AU3=月末(当月最后一天)

AG~AL / AM~AR 取值逻辑(用户 2026-10-19 提供,2026-10-19 修正口径):
  SELECT business_type, brand,
         IFNULL(recruitment_quantity,0)                                AS recruit_qty,   -- 招聘数量
         IFNULL(recruitment_quantity,0)-(
             SELECT COUNT(0) FROM dj_car_life_recruitment_onboarding_plan p
             WHERE p.deleted_flag='N' AND p.demand_id=d.id
         )                                                  AS pending_count  -- 待招人数
  FROM dj_car_life_recruitment_demand d
  WHERE deleted_flag='N'
    AND business_type IN :biz_ids                 -- 按业务类型取值替换
    AND created_date >= :month_start AND created_date < :month_end   -- 当月限制
  -- AM~AR 额外加:AND d.`status` = 1
  口径:AG~AL(新增招聘需求) 取 recruit_qty(招聘数量);AM~AR(待招聘需求) 取 pending_count(待招人数)。

⚠ 本环境 D+ 库(192.168.5.23)不可达,fetch 返回 [] 仅告警;逻辑用 self_test() 离线校验。
"""
import io
import logging
import os
import re
import tempfile
from datetime import date, datetime, timedelta

import openpyxl
from openpyxl.utils import get_column_letter
from sqlalchemy import create_engine, text, bindparam

from config import Config
from report_utils import mark_task_failed
from oss_utils import upload_file
from models import DataProcessTask, db, RecruitmentMonthData

logger = logging.getLogger('RecruitmentProcessor')

RECRUIT_TYPE = 'recruitment'

TEMPLATE_PATH = os.path.join(
    os.path.dirname(os.path.abspath(__file__)),
    'exporttemplete', 'recruitment_report_template.xlsx')

# ---------- 业务类型映射(源表 business_type 编码 -> 结果表业务键) ----------
# 顺序即 B~H / I~AF 列顺序:延保/权益/权益+延保/轻改销售/技师/二手车
RECRUIT_BIZ = {
    'ext_warranty': [1],
    'rights': [2],
    'rights_ext': [5],
    'light_sales': [3],
    'technician': [4, 8, 6, 7],
    'used_car': [9],
}
BIZ_ORDER = ['ext_warranty', 'rights', 'rights_ext', 'light_sales', 'technician', 'used_car']
# 源编码 -> 业务键
BIZ_GROUP_OF = {}
for _g, _ids in RECRUIT_BIZ.items():
    for _i in _ids:
        BIZ_GROUP_OF[_i] = _g
ALL_BIZ_IDS = sorted({i for _ids in RECRUIT_BIZ.values() for i in _ids})

# ---------- 品牌:解析优先级 vs 展示顺序 ----------
# 解析优先级(多品牌取最高):问界 > 鸿蒙智行 > 广爱 > 北汽 > 阿维塔 > 零跑 > 岚图 > 其他品牌
BRAND_PRIORITY = ['问界', '鸿蒙智行', '广爱', '北汽', '阿维塔', '零跑', '岚图', '其他品牌']
# 结果表行展示顺序(读模板确认):问界/鸿蒙智行/广爱/北汽/阿维塔/岚图/零跑/其他品牌
BRAND_DISPLAY_ORDER = ['问界', '鸿蒙智行', '广爱', '北汽', '阿维塔', '岚图', '零跑', '其他品牌']
BRAND_ROW = {b: 4 + i for i, b in enumerate(BRAND_DISPLAY_ORDER)}  # 问界=4 ... 其他品牌=11

# 源表 brand 可能用异名(如「广汽埃安/广汽传祺」对应 广爱);未命中 8 主标签时按子串别名回退。
# ⚠ 如需补充别名,在此追加(key 为源串子串,value 为 8 品牌之一)。
BRAND_ALIASES = {
    '广汽': '广爱',       # 广汽埃安 / 广汽传祺 等
    '鸿蒙': '鸿蒙智行',   # 源库可能写「鸿蒙」
}

# I~AF 列:每业务起始列(优秀/良好/正常/异常 四列连续)
GROUP_START_COL = {
    'ext_warranty': 9,    # I
    'rights': 13,         # M
    'rights_ext': 17,     # Q
    'light_sales': 21,    # U
    'technician': 25,     # Y
    'used_car': 29,       # AC
}
STAGE_ORDER = ['excellent', 'good', 'normal', 'abnormal']
STAGE_OFFSET = {'excellent': 0, 'good': 1, 'normal': 2, 'abnormal': 3}
STAGE_LABEL = {'excellent': '优秀', 'good': '良好', 'normal': '正常', 'abnormal': '异常'}

# AG~AL / AM~AR 块起始列(每业务 6 列,顺序同 BIZ_ORDER)
NEW_BLOCK_START_COL = 33          # AG(新增招聘需求,当月提的全部需求)
MONTH_PENDING_BLOCK_START_COL = 39  # AM(月待招需求,当月提且招聘中)


# ---------- D+ 业务库引擎(嘀加 dj_smartcarlife) ----------
_BIZ_ENGINE = None


def _get_biz_engine():
    """业务系统 SQL 引擎(嘀加 dj_smartcarlife),懒加载单例。

    ⚠ 加 connect_timeout:D+ 不可达时快速失败(返回 []),避免 worker 线程
    卡在 TCP 连接上导致任务永久停留在 PROCESSING。
    """
    global _BIZ_ENGINE
    if _BIZ_ENGINE is None:
        _BIZ_ENGINE = create_engine(
            Config.BIZ_SQL_DATABASE_URL, echo=False, pool_pre_ping=True,
            connect_args={'connect_timeout': 15, 'read_timeout': 30, 'write_timeout': 30},
        )
    return _BIZ_ENGINE


RECRUIT_PENDING_SQL = """
SELECT d.business_type                              AS business_type,
       d.brand                                      AS brand,
       IFNULL(d.recruitment_quantity, 0) - (
           SELECT COUNT(0)
           FROM dj_car_life_recruitment_onboarding_plan p
           WHERE p.deleted_flag = 'N' AND p.demand_id = d.id
       )                                            AS pending_count,
       DATEDIFF(:cutoff_date, d.created_date)        AS cycle_days
FROM dj_car_life_recruitment_demand d
WHERE d.deleted_flag = 'N'
  AND d.`status` = 1
  AND d.business_type IN :biz_ids
"""


def fetch_recruitment_pending_rows(cutoff_date):
    """查询 I~AF 源数据。返回 [{business_type, brand, pending_count, cycle_days}, ...]。

    cutoff_date 替换 SQL 中的 NOW()(支持历史月份重跑:传对应月份基准日)。
    查询失败/不可达返回 [](不致命,调用方仅告警)。
    """
    engine = _get_biz_engine()
    try:
        with engine.connect() as conn:
            stmt = text(RECRUIT_PENDING_SQL).bindparams(
                bindparam('biz_ids', expanding=True))
            rows = conn.execute(
                stmt, {'cutoff_date': cutoff_date.isoformat(), 'biz_ids': ALL_BIZ_IDS}
            ).fetchall()
    except Exception as e:
        logger.warning(f"[招聘] D+ 招聘需求查询失败(cutoff={cutoff_date}): {e}")
        return []

    out = []
    for r in rows:
        # ⚠ business_type 在源库是 varchar,SQL 返回字符串('1'/'9'...);
        # 聚合键 BIZ_GROUP_OF 是整数,必须转 int 否则映射全部 miss -> 全 0
        bt_raw = r[0]
        try:
            bt = int(bt_raw) if bt_raw is not None else None
        except (TypeError, ValueError):
            bt = None
        out.append({
            'business_type': bt,
            'brand': r[1],
            'pending_count': int(r[2] or 0),
            'cycle_days': r[3],
        })
    logger.info(f"[招聘] D+ 招聘需求查询到 {len(out)} 条(status=1, cutoff={cutoff_date})")
    return out


# ---------- AG~AL / AM~AR 源查询(当月提需求,按业务聚合) ----------
# AG~AL:当月提的全部需求(不看状态),取 recruit_qty(招聘数量);
# AM~AR:在上面的基础上加 status=1(招聘中),取 pending_count(待招人数)。
# 两列同一条 SQL,仅取值字段不同:AG~AL 用 recruitment_quantity,AM~AR 用 pendingCount。
RECRUIT_NEW_SQL = """
SELECT d.business_type                              AS business_type,
       d.brand                                      AS brand,
       IFNULL(d.recruitment_quantity, 0)            AS recruit_qty,
       IFNULL(d.recruitment_quantity, 0) - (
           SELECT COUNT(0)
           FROM dj_car_life_recruitment_onboarding_plan p
           WHERE p.deleted_flag = 'N' AND p.demand_id = d.id
       )                                            AS pending_count
FROM dj_car_life_recruitment_demand d
WHERE d.deleted_flag = 'N'
  AND d.business_type IN :biz_ids
  AND d.created_date >= :month_start AND d.created_date < :month_end
"""

RECRUIT_MONTH_PENDING_SQL = RECRUIT_NEW_SQL + "  AND d.`status` = 1\n"


def _fetch_recruit_biz_rows(month_start, month_end, status_filter):
    """AG~AL / AM~AR 通用源查询。

    status_filter=True  -> 仅招聘中(status=1)(AM~AR)
    status_filter=False -> 全部状态(AG~AL)
    返回 [{business_type, brand, recruit_qty, pending_count}, ...]。business_type 转 int。
    """
    engine = _get_biz_engine()
    sql = RECRUIT_MONTH_PENDING_SQL if status_filter else RECRUIT_NEW_SQL
    try:
        with engine.connect() as conn:
            stmt = text(sql).bindparams(bindparam('biz_ids', expanding=True))
            rows = conn.execute(
                stmt,
                {'month_start': month_start.isoformat(),
                 'month_end': month_end.isoformat(),
                 'biz_ids': ALL_BIZ_IDS},
            ).fetchall()
    except Exception as e:
        logger.warning(f"[招聘] D+ 当月招聘查询失败({month_start}~{month_end}, status={status_filter}): {e}")
        return []

    out = []
    for r in rows:
        bt_raw = r[0]
        try:
            bt = int(bt_raw) if bt_raw is not None else None
        except (TypeError, ValueError):
            bt = None
        out.append({
            'business_type': bt,
            'brand': r[1],
            'recruit_qty': int(r[2] or 0),
            'pending_count': int(r[3] or 0),
        })
    logger.info(f"[招聘] D+ 当月招聘查询到 {len(out)} 条(status_filter={status_filter}, {month_start}~{month_end})")
    return out


def fetch_new_rows(month_start, month_end):
    """AG~AL 源:当月提需求(全部状态)的 招聘数量(recruit_qty)。"""
    return _fetch_recruit_biz_rows(month_start, month_end, status_filter=False)


def fetch_month_pending_rows(month_start, month_end):
    """AM~AR 源:当月提需求 且 招聘中(status=1) 的 待招人数(pending_count)。"""
    return _fetch_recruit_biz_rows(month_start, month_end, status_filter=True)


# ---------- AS(入职人数) 源查询(当月入职计划总数,不区分品牌/业务) ----------
RECRUIT_ENTRY_SQL = """
SELECT COUNT(0)
FROM dj_car_life_recruitment_onboarding_plan
WHERE deleted_flag = 'N'
  AND created_date >= :month_start AND created_date < :month_end
"""


def fetch_entry_count(month_start, month_end):
    """AS(入职人数):当月入职计划数(dj_car_life_recruitment_onboarding_plan,单总数)。

    不区分品牌/业务(用户 SQL 即 COUNT(0) 总数);返回单个整数,失败返回 0。
    """
    engine = _get_biz_engine()
    try:
        with engine.connect() as conn:
            rows = conn.execute(
                text(RECRUIT_ENTRY_SQL),
                {'month_start': month_start.isoformat(),
                 'month_end': month_end.isoformat()},
            ).fetchall()
        cnt = int(rows[0][0]) if rows else 0
        logger.info(f"[招聘] 当月入职人数={cnt}({month_start}~{month_end})")
        return cnt
    except Exception as e:
        logger.warning(f"[招聘] D+ 入职人数查询失败({month_start}~{month_end}): {e}")
        return 0


def aggregate_by_biz(rows, value_key='recruit_qty'):
    """按 品牌 × 业务 聚合指定值(无周期档,用于 AG~AL/AM~AR)。

    value_key='recruit_qty'   -> 新增招聘需求(AG~AL) 取 招聘数量
    value_key='pending_count' -> 月待招需求(AM~AR) 取 待招人数
    """
    grid = {b: {g: 0 for g in BIZ_ORDER} for b in BRAND_DISPLAY_ORDER}
    for r in rows:
        g = BIZ_GROUP_OF.get(r['business_type'])
        if g is None:
            continue
        b = resolve_brand(r['brand'])
        if b not in grid:
            b = '其他品牌'
        grid[b][g] += r.get(value_key, 0)
    return grid


def resolve_brand(brand_str):
    """多品牌门店按优先级取唯一品牌;未命中前 7 者 -> 其他品牌。"""
    if not brand_str:
        return '其他品牌'
    s = str(brand_str).strip()
    parts = re.split(r'[,,、/;\s]+', s)
    best = None  # 命中的最高优先级下标
    for part in parts:
        part = part.strip()
        if not part:
            continue
        for idx, pb in enumerate(BRAND_PRIORITY):
            if pb == '其他品牌':
                continue
            if pb in part or part in pb:
                if best is None or idx < best:
                    best = idx
                break
        if best is not None:
            continue
        # 主标签未命中 -> 别名回退(子串)
        for alias, target in BRAND_ALIASES.items():
            if alias in part:
                # 取目标在优先级中的位置
                ti = BRAND_PRIORITY.index(target)
                if best is None or ti < best:
                    best = ti
                break
    return BRAND_PRIORITY[best] if best is not None else '其他品牌'


def cycle_stage(cycle_days):
    """账龄 -> 周期档。优秀≤7 / 良好8-14 / 正常15-30 / 异常>30。"""
    try:
        cd = int(cycle_days)
    except (TypeError, ValueError):
        cd = 0
    if cd <= 7:
        return 'excellent'
    if cd <= 14:
        return 'good'
    if cd <= 30:
        return 'normal'
    return 'abnormal'


def aggregate(rows):
    """按 品牌 × 业务 × 周期档 聚合 pending_count。

    返回 grid[brand][group][stage] = sum;同时便于派生 B~H 与合计行。
    仅 8 个展示品牌参与(解析后落入 其他品牌 的也计入)。
    """
    grid = {b: {g: {st: 0 for st in STAGE_ORDER} for g in BIZ_ORDER}
            for b in BRAND_DISPLAY_ORDER}
    for r in rows:
        g = BIZ_GROUP_OF.get(r['business_type'])
        if g is None:
            continue
        b = resolve_brand(r['brand'])
        if b not in grid:
            b = '其他品牌'
        st = cycle_stage(r['cycle_days'])
        grid[b][g][st] += r['pending_count']
    return grid


def store_grid(task_id, stat_month, cutoff_date, grid, new_grid, pend_month_grid, entry_cnt):
    """软删旧行 + 插 8 品牌行(I~AF + AG~AL + AM~AR + 入职/离职 全部落库)。

    entry_cnt = 当月入职总数(单值,不区分品牌/业务);为便于按任务查询,8 行均存同一总数。
    leave_cnt 本系统无源,固定 0(由使用人下载后手动填写)。
    """
    # 软删同 (task_id, stat_month) 旧行
    old = RecruitmentMonthData.query.filter_by(
        task_id=task_id, stat_month=stat_month, is_deleted=0).all()
    for o in old:
        o.is_deleted = 1
    db.session.flush()

    objs = []
    for order, b in enumerate(BRAND_DISPLAY_ORDER):
        d = {g: grid[b][g] for g in BIZ_ORDER}
        biz_tot = {g: sum(d[g].values()) for g in BIZ_ORDER}
        total = sum(biz_tot.values())
        rec = RecruitmentMonthData(
            task_id=task_id,
            stat_month=stat_month,
            cutoff_date=cutoff_date,
            brand=b,
            brand_order=order,
            pending_total=total,
            pending_ext_warranty=biz_tot['ext_warranty'],
            pending_rights=biz_tot['rights'],
            pending_rights_ext=biz_tot['rights_ext'],
            pending_light_sales=biz_tot['light_sales'],
            pending_technician=biz_tot['technician'],
            pending_used_car=biz_tot['used_car'],
        )
        for g in BIZ_ORDER:
            for st in STAGE_ORDER:
                setattr(rec, f'pending_{g}_{st}', d[g][st])
        # AG~AL:新增(当月提的全部需求)
        rec.new_ext_warranty = new_grid[b]['ext_warranty']
        rec.new_rights = new_grid[b]['rights']
        rec.new_rights_ext = new_grid[b]['rights_ext']
        rec.new_light_sales = new_grid[b]['light_sales']
        rec.new_technician = new_grid[b]['technician']
        rec.new_used_car = new_grid[b]['used_car']
        # AM~AR:月待招(当月提且招聘中)
        rec.pend_month_ext_warranty = pend_month_grid[b]['ext_warranty']
        rec.pend_month_rights = pend_month_grid[b]['rights']
        rec.pend_month_rights_ext = pend_month_grid[b]['rights_ext']
        rec.pend_month_light_sales = pend_month_grid[b]['light_sales']
        rec.pend_month_technician = pend_month_grid[b]['technician']
        rec.pend_month_used_car = pend_month_grid[b]['used_car']
        # 入职/离职(AS/AT):入职为月总数(8 行存同一值便于查询);离职无源留 0
        rec.entry_cnt = entry_cnt
        rec.leave_cnt = 0
        objs.append(rec)
    db.session.bulk_save_objects(objs)
    db.session.commit()
    logger.info(f"[招聘] 已落库 {len(objs)} 行(task {task_id}, {stat_month})")


def generate_result_excel(task, grid, cutoff_date, new_grid, pend_month_grid, entry_cnt):
    """渲染结果表「统计」sheet:B~H + I~AF + AG~AL + AM~AR + AS/AT + 合计。返回 OSS url。"""
    if not os.path.exists(TEMPLATE_PATH):
        raise FileNotFoundError(f"招聘结果表模板缺失: {TEMPLATE_PATH}")
    wb = openpyxl.load_workbook(TEMPLATE_PATH)
    ws = wb['统计']

    month_num = int(task.month.split('-')[1]) if task.month and '-' in task.month else 0

    # 各品牌行(B~H + I~AF + AG~AL + AM~AR)
    for b in BRAND_DISPLAY_ORDER:
        r = BRAND_ROW[b]
        biz_tot = {g: sum(grid[b][g].values()) for g in BIZ_ORDER}
        total = sum(biz_tot.values())
        ws.cell(row=r, column=2, value=total)                 # B 合计
        for gi, g in enumerate(BIZ_ORDER):
            ws.cell(row=r, column=3 + gi, value=biz_tot[g])    # C~H
        for g in BIZ_ORDER:
            start = GROUP_START_COL[g]
            for st in STAGE_ORDER:
                ws.cell(row=r, column=start + STAGE_OFFSET[st], value=grid[b][g][st])
        # AG~AL:新增(当月提的全部需求,按业务)
        for gi, g in enumerate(BIZ_ORDER):
            ws.cell(row=r, column=NEW_BLOCK_START_COL + gi, value=new_grid[b][g])
        # AM~AR:月待招(当月提且招聘中,按业务)
        for gi, g in enumerate(BIZ_ORDER):
            ws.cell(row=r, column=MONTH_PENDING_BLOCK_START_COL + gi, value=pend_month_grid[b][g])

    # 合计行(row 12)
    r = 12
    grand_biz = {g: 0 for g in BIZ_ORDER}
    grand = 0
    for b in BRAND_DISPLAY_ORDER:
        for g in BIZ_ORDER:
            grand_biz[g] += sum(grid[b][g].values())
    grand = sum(grand_biz.values())
    ws.cell(row=r, column=2, value=grand)
    for gi, g in enumerate(BIZ_ORDER):
        ws.cell(row=r, column=3 + gi, value=grand_biz[g])
    for g in BIZ_ORDER:
        start = GROUP_START_COL[g]
        for st in STAGE_ORDER:
            ws.cell(row=r, column=start + STAGE_OFFSET[st],
                    value=sum(grid[b][g][st] for b in BRAND_DISPLAY_ORDER))
    # 合计行 AG~AL / AM~AR
    for gi, g in enumerate(BIZ_ORDER):
        ws.cell(row=r, column=NEW_BLOCK_START_COL + gi,
                value=sum(new_grid[b][g] for b in BRAND_DISPLAY_ORDER))
        ws.cell(row=r, column=MONTH_PENDING_BLOCK_START_COL + gi,
                value=sum(pend_month_grid[b][g] for b in BRAND_DISPLAY_ORDER))
    # AS/AT(入职/离职):模板 AS4:AS12、AT4:AT12 纵向合并,仅锚点(问界行=row4)可写;
    # 月总数写入锚点后随合并区域贯穿至合计行展示。
    ws.cell(row=4, column=45, value=entry_cnt)   # AS 入职(月总数,写入合并锚点)
    ws.cell(row=4, column=46, value=0)           # AT 离职(无源,留 0 由使用人手动填)

    # 月份标签(AG~AT 等含「7月」-> 目标月)与基准日
    for c in range(1, ws.max_column + 1):
        v = ws.cell(row=1, column=c).value
        if isinstance(v, str) and '7月' in v and month_num:
            ws.cell(row=1, column=c, value=v.replace('7月', f'{month_num}月'))
    # 日期基准(AV 列):AU1=当前工作日 / AU2=月初(当月1号) / AU3=月末(当月最后一天)
    y, m = (int(x) for x in task.month.split('-'))
    month_start = date(y, m, 1)
    if m == 12:
        month_end = date(y + 1, 1, 1)
    else:
        month_end = date(y, m + 1, 1)
    month_last = month_end - timedelta(days=1)
    ws.cell(row=1, column=48, value=cutoff_date)   # AU1=当前工作日
    ws.cell(row=2, column=48, value=month_start)   # AU2=月初=当月1号
    ws.cell(row=3, column=48, value=month_last)    # AU3=月末=当月最后一天

    # 写出临时文件 -> OSS
    tmp = tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx',
                                      prefix=f'recruitment_{task.month}_')
    wb.save(tmp.name)
    tmp.close()

    url = ''
    try:
        _now = datetime.now()
        _ts = _now.strftime('%Y%m%d%H%M%S%f')
        object_key = f"data-process/{_now.strftime('%Y%m%d')}/招聘管理_{task.month}_{task.id}_{_ts}.xlsx"
        url = upload_file(tmp.name, object_key)
        logger.info(f"[招聘] 结果表已上传 OSS:task {task.id} -> {url}")
    except Exception as ue:
        logger.warning(f"[招聘] OSS 上传失败(本地副本保留):{ue}")
    finally:
        try:
            os.remove(tmp.name)
        except Exception:
            pass
    return url


class RecruitmentProcessor:
    def __init__(self, app=None):
        self.app = app

    def process(self, task):
        """处理单个招聘管理任务:查 D+ -> 聚合 I~AF -> 落库 -> 渲染结果表 -> 置 COMPLETED。

        cutoff_date 默认取「当前工作日」(运行日);重跑历史月份时由调用方传入覆盖。
        """
        task_id = task.id
        try:
            stat_month = task.month
            cutoff_date = date.today()   # ⚠ 假设:当前工作日=运行日;历史重跑需外部覆盖

            # I~AF:当前招聘中(status=1) 待招需求 × 周期档
            rows = fetch_recruitment_pending_rows(cutoff_date)
            grid = aggregate(rows)

            # AG~AL / AM~AR:当月提需求(created_date∈月)的待招人数,按业务
            y, m = (int(x) for x in stat_month.split('-'))
            if m == 12:
                month_start = date(y, 12, 1)
                month_end = date(y + 1, 1, 1)
            else:
                month_start = date(y, m, 1)
                month_end = date(y, m + 1, 1)
            new_rows = fetch_new_rows(month_start, month_end)              # AG~AL
            pend_month_rows = fetch_month_pending_rows(month_start, month_end)  # AM~AR
            # AG~AL(新增招聘需求) 取 招聘数量(recruit_qty);AM~AR(待招聘需求) 取 待招人数(pending_count)
            new_grid = aggregate_by_biz(new_rows, value_key='recruit_qty')
            pend_month_grid = aggregate_by_biz(pend_month_rows, value_key='pending_count')
            entry_cnt = fetch_entry_count(month_start, month_end)          # AS 入职人数

            store_grid(task_id, stat_month, cutoff_date, grid, new_grid, pend_month_grid, entry_cnt)

            task = DataProcessTask.query.filter_by(id=task_id).first()
            url = ''
            try:
                url = generate_result_excel(task, grid, cutoff_date, new_grid, pend_month_grid, entry_cnt)
            except Exception as ge:
                logger.warning(f"[招聘] 结果表生成失败(task {task_id}): {ge}")

            task.status = 'COMPLETED'
            task.result_file_url = url or ''
            task.error_msg = ''
            db.session.commit()
            logger.info(f"[招聘] 任务 {task_id} 处理完成({stat_month},需求行 {len(rows)})")
        except Exception as e:
            db.session.rollback()
            mark_task_failed(task_id, str(e))

    def scan_recruitment(self):
        """扫描 recruitment 类型的 PROCESSING 任务并逐个处理(供 RecruitmentScheduler 调用)。"""
        logger.info("[招聘] 开始扫描 recruitment 待处理任务")
        tasks = DataProcessTask.query.filter_by(
            data_table_type='recruitment',
            status='PROCESSING',
            is_deleted=0,
        ).order_by(DataProcessTask.id.asc()).all()
        logger.info(f"[招聘] 扫描到 {len(tasks)} 个待处理任务")

        success_count = 0
        fail_count = 0
        for task in tasks:
            try:
                self.process(task)
                success_count += 1
                logger.info(f"[招聘] 任务 {task.id} 处理成功")
            except Exception as e:
                import traceback as _tb
                fail_count += 1
                logger.error(f"[招聘] 任务 {task.id} 处理失败: {str(e)}")
                logger.error(_tb.format_exc())
                try:
                    mark_task_failed(task.id, str(e))
                except Exception as mark_err:
                    logger.error(f"[招聘] 标记任务失败时出错: {mark_err}")

        logger.info(f"[招聘] 扫描完成,成功 {success_count},失败 {fail_count}")
        return {'success': success_count, 'failed': fail_count}


def self_test():
    """离线校验 品牌优先级 + 周期档 分桶逻辑(不依赖 D+)。"""
    synth = [
        # 多品牌门店:同时含 问界 与 鸿蒙智行 -> 应归入 问界(最高优先级)
        {'business_type': 1, 'brand': '问界/鸿蒙智行', 'pending_count': 3, 'cycle_days': 3},
        # 广爱(别名验证)
        {'business_type': 1, 'brand': '广汽埃安', 'pending_count': 5, 'cycle_days': 10},
        # 技师多编码
        {'business_type': 6, 'brand': '北汽', 'pending_count': 2, 'cycle_days': 20},
        {'business_type': 8, 'brand': '北汽', 'pending_count': 1, 'cycle_days': 35},
        # 权益+延保
        {'business_type': 5, 'brand': '阿维塔', 'pending_count': 4, 'cycle_days': 7},
        # 未知品牌 -> 其他品牌
        {'business_type': 3, 'brand': 'XX新势力', 'pending_count': 9, 'cycle_days': 15},
        # 轻改销售 边界
        {'business_type': 3, 'brand': '岚图', 'pending_count': 6, 'cycle_days': 14},
    ]
    grid = aggregate(synth)
    print("=== 品牌优先级 / 周期档 分桶自检 ===")
    for b in BRAND_DISPLAY_ORDER:
        line = []
        for g in BIZ_ORDER:
            line.append(f"{g}=" + "/".join(str(grid[b][g][st]) for st in STAGE_ORDER))
        print(f"  {b:6s}: total={sum(sum(grid[b][g].values()) for g in BIZ_ORDER)} | " + "  ".join(line))
    # 断言关键用例
    assert grid['问界']['ext_warranty']['excellent'] == 3, "多品牌应归问界"
    assert grid['广爱']['ext_warranty']['good'] == 5, "广汽埃安应归广爱-良好"
    assert grid['北汽']['technician']['normal'] == 2 and grid['北汽']['technician']['abnormal'] == 1
    assert grid['其他品牌']['light_sales']['normal'] == 9
    assert grid['岚图']['light_sales']['good'] == 6
    print("[OK] 自检通过:品牌优先级与周期档分桶正确")


if __name__ == '__main__':
    self_test()