# -*- coding: utf-8 -*- """线下《起调薪薪资标准》解析与匹配。 表结构(2026-10 版,单工作表「起调薪薪资」): 列1 序列 / 列2 品牌 / 列3 岗位(可含 "/" 多别名,"XX"为通配)/ 列4 岗位补贴 列5-13 薪资总额(重庆/成都/长沙/西安/海口/郑州/南宁/深圳/昆明) 列14 星级奖金规则 / 列15 备注(含绩效奖金档位;含「数字人」的行不处理) 合并单元格的序列/品牌向下沿用。 匹配口径: 应发 = 薪资总额(城市) + 岗位补贴(城市) + 奖金(星级) - 管理岗「4200+绩效奖金」:奖金 = 备注中的绩效奖金档位(按星级); - 服务岗:奖金 = 星级奖金(一星100…十星1000;见习/代理/正式=0); - 技师岗不做总额核对(标准表不含技师序列)。 """ from __future__ import annotations import os import re from typing import List, Optional, Tuple import pandas as pd from .. import config SHEET = "起调薪薪资" COL_SEQ, COL_BRAND, COL_POST, COL_ALLOW, COL_NOTE = 1, 2, 3, 4, 15 COL_BONUS = 14 CITY_COLS = [(5 + i, c) for i, c in enumerate(config.CITIES)] def _num(value) -> Optional[float]: """取单元格开头的数字("4200+绩效奖金" → 4200)。""" m = re.match(r"(\d+(?:\.\d+)?)", config.text(value).replace(",", "")) return float(m.group(1)) if m else None def _perf_by_star(note: str) -> dict: result = {} for part in config.text(note).replace(";", "、").split("、"): m = re.search(r"(见习/代理|见习|代理|一星|二星|三星|四星|五星|六星|七星|八星|九星|十星)" r"(\d+)元", part) if m: result[m.group(1)] = float(m.group(2)) return result def _allowance(cell, city: str) -> Optional[float]: text = config.text(cell) if text in ("/", ""): return 0.0 if text == "固定500": return 500.0 if "深圳" in text: others = re.findall(r"其他(\d+)", text) shenzhen = re.findall(r"深圳(\d+)", text) if city == "深圳" and shenzhen: return float(shenzhen[0]) if others: return float(others[0]) return _num(text) def _star_bonus(star: str, note: str = "") -> Optional[float]: """服务岗星级奖金:一星100…十星1000;见习/代理/正式=0。 部分岗位备注为「一星100元,二星至十星逐渐加50元」→ 一星100、二星150、三星200… 高级/资深等未知星级返回 None。 """ level = config.star_level(star) if level: if "逐渐加50元" in config.text(note): return float(100 + (level - 1) * 50) return float(level * 100) if config.norm(star) in ("见习", "代理", "正式"): return 0.0 return None _DATE_RE = re.compile(r"(20\d{6})") def find_latest_file(dir_path: str, log=None) -> str: """在工作目录内按关键词挑最新标准表:文件名日期优先,无日期时按修改时间。""" try: names = os.listdir(dir_path) except OSError: return "" candidates = [] for name in names: if name.startswith("~$") or not name.lower().endswith((".xlsx", ".xls")): continue if not any(keyword in name for keyword in config.STANDARD_FILE_KEYWORDS): continue full = os.path.join(dir_path, name) if not os.path.isfile(full): continue m = _DATE_RE.search(name) candidates.append((m.group(1) if m else "", os.path.getmtime(full), full)) if not candidates: return "" dated = [c for c in candidates if c[0]] best = max(dated or candidates, key=lambda c: (c[0], c[1])) if log: log(f"[INFO] 标准表目录自动选取:{os.path.basename(best[2])}") return best[2] def load(path: str, log=None) -> List[dict]: """读取标准表;path 为目录时按关键词+最新日期取一个文件。 表不存在、工作表被改名、列数不足或文件损坏时返回空列表(按「未载入标准表」处理, 由调用方逐条记为待人工核对),不抛异常中断整批处理。 """ path = config.text(path) if path and os.path.isdir(path): path = find_latest_file(path, log) if not path: if log: log(f"[WARN] 标准表目录内未找到含关键词「{config.STANDARD_FILE_KEYWORDS[0]}」的 xlsx;" f"服务/管理账套固定项总额按待人工核对处理", "WARNING") return [] if not path or not os.path.exists(path): return [] try: frame = pd.read_excel(path, sheet_name=SHEET, header=None, dtype=str).fillna("") except Exception as exc: # noqa: BLE001 - 结构/文件异常统一降级 if log: log(f"[WARN] 线下标准表读取失败({os.path.basename(path)}):{exc};" f"服务/管理账套固定项总额按待人工核对处理", "WARNING") return [] if frame.shape[1] <= COL_NOTE: if log: log(f"[WARN] 线下标准表列数不足({os.path.basename(path)}):" f"至少需 {COL_NOTE + 1} 列,当前 {frame.shape[1]} 列;" f"服务/管理账套固定项总额按待人工核对处理", "WARNING") return [] rows: List[dict] = [] seq = brand = "" for i in range(len(frame)): current = frame.iloc[i] if config.text(current[COL_SEQ]): seq = config.text(current[COL_SEQ]) if config.text(current[COL_BRAND]): brand = config.text(current[COL_BRAND]) post = config.text(current[COL_POST]) if not post or seq not in config.STANDARD_SEQUENCES or brand not in config.BRANDS: continue note = config.text(current[COL_NOTE]) salary = {city: config.text(current[col]) for col, city in CITY_COLS} if any("绩效" in value for value in salary.values()): kind = "perf" elif re.search(r"\d+-\d+", config.text(current[COL_BONUS])): kind = "star" else: kind = "none" rows.append({ "row": i, "sequence": seq, "brand": brand, "post": post, "allowance": config.text(current[COL_ALLOW]), "salary": salary, "bonus_kind": kind, "perf": _perf_by_star(note), "note": note, "skip": "数字人" in note, }) if log: log(f"[INFO] 标准表载入 {len(rows)} 行:{os.path.basename(path)}" f"(数字人跳过 {sum(1 for r in rows if r['skip'])} 行)") return rows def _post_match(alias: str, post: str) -> int: """返回匹配级别:3 完全相等 / 2 XX 通配 / 1 包含 / 0 不匹配。""" a, p = config.norm(alias), config.norm(post) if not a or not p: return 0 if a == p: return 3 if "XX" in a: # 「二级XX厨师」→ 前缀「二级」+ 后缀「厨师」按顺序命中即可 pos = 0 for part in [x for x in a.split("XX") if x]: idx = p.find(part, pos) if idx < 0: return 0 pos = idx + len(part) return 2 return 1 if len(a) >= 2 and a in p else 0 def expected(matched: dict, *, city: str, star: str) -> Tuple[Optional[dict], str]: """命中行 → 标准分项:薪资总额/岗位补贴/奖金(奖金类目见 kind)。""" if not matched: return None, "未匹配到标准行" salary = _num(matched["salary"].get(city, "")) if salary is None: return None, f"标准表「{matched['post']}」无「{city or '未知城市'}」薪资(或为区间)" allowance = _allowance(matched["allowance"], city) if allowance is None: return None, f"标准表「{matched['post']}」岗位补贴无法解析({matched['allowance']})" if matched["bonus_kind"] == "perf": perf = matched["perf"] key = "见习/代理" if config.norm(star) in ("见习", "代理") else config.norm(star) if key not in perf: return None, f"标准表无「{star or '空'}」绩效奖金档位({matched['post']})" bonus, kind = perf[key], "绩效奖金" elif matched["bonus_kind"] == "star": bonus = _star_bonus(star, matched.get("note", "")) if bonus is None: return None, f"星级「{star or '空'}」无星级奖金规则" kind = "星级奖金" else: bonus, kind = 0.0, "" return { "salary": round(salary, 2), "allowance": round(allowance, 2), "bonus": round(bonus, 2), "kind": kind, "total": round(salary + allowance + bonus, 2), }, "" def match(rows: List[dict], *, sequence: str, brand: str, post: str, city: str, star: str) -> Tuple[Optional[float], Optional[dict], str]: """返回 (应发总额, 命中行, 说明)。""" if not rows: return None, None, "未载入标准表" seq = config.SEQUENCE_ALIASES.get(config.norm(sequence), config.norm(sequence)) if seq not in config.STANDARD_SEQUENCES: return None, None, f"标准表不含序列「{sequence}」" best, best_score, best_skip = None, 0, None for row in rows: if row["sequence"] != seq or row["brand"] != brand: continue score = max((_post_match(alias, post) for alias in row["post"].split("/")), default=0) if score > best_score: best, best_score = row, score if score and row["skip"]: best_skip = row if not best: return None, None, f"标准表未匹配到岗位「{post}」({seq}/{brand})" if best_skip is not None and best_skip is best: return None, best, f"标准表备注「数字人不操作」,按规则跳过({best['post']})" parts, reason = expected(best, city=city, star=star) if parts is None: return None, best, reason return parts["total"], best, ""