convert-excel-template-to-schema.py 33.7 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 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@file 将门店工作汇报 Excel 填写表单 sheet 转为动态表单 schema。
依据行样式:删除线=剔除;紫色 rgb(242,199,255)=按 Excel 重解析;无标记=沿用 baseline fixture。
用法:
  python packageDynamicForm/scripts/convert-excel-template-to-schema.py --sheet staff --format js
  python packageDynamicForm/scripts/convert-excel-template-to-schema.py --sheet store --format js
  python packageDynamicForm/scripts/convert-excel-template-to-schema.py --sheet staff --env production --format js
"""
from __future__ import annotations

import argparse
import copy
import json
import re
import subprocess
import sys
import zipfile
import xml.etree.ElementTree as ET
from pathlib import Path

PKG_ROOT = Path(__file__).resolve().parent.parent
DEFAULT_XLSX = Path(r'c:/Users/admin/Downloads/门店工作汇报模板-V2.1.1.xlsx')
PURPLE_RGB = (242, 199, 255)
NS = {'m': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'}

BASE_SCENE_CODE = {
    '1.1': 100101,
    '1.2': 100102,
    '1.3': 100103,
    '2.1.1': 110101,
    '2.1.2': 110102,
    '2.3.1': 110201,
    '2.3.2': 110202,
}

BRAND_ENV_MAPS_PATH = PKG_ROOT / 'fixtures/brand-id-env-maps.json'

BRAND_NAME_TO_ID: dict[str, int] = {}
FILTER_BRAND_IDS: list[int] = []
FIVE_REALM_IDS: list[int] = []


def load_brand_env_maps() -> dict:
    """读取 fixtures/brand-id-env-maps.json(与 brand-id-env-maps.mjs 数值一致)。"""
    return json.loads(BRAND_ENV_MAPS_PATH.read_text(encoding='utf-8'))


def apply_brand_env(env: str = 'daily') -> None:
    """按环境切换全局 brandId 映射,供 parse_brand_restriction 使用。"""
    global BRAND_NAME_TO_ID, FILTER_BRAND_IDS, FIVE_REALM_IDS
    maps = load_brand_env_maps()
    if env not in maps:
        raise ValueError(f'unknown brand env: {env}')
    name_to_id = maps[env]
    BRAND_NAME_TO_ID = dict(name_to_id)
    FIVE_REALM_IDS = [
        name_to_id['问界'],
        name_to_id['享界'],
        name_to_id['智界'],
        name_to_id['尚界'],
        name_to_id['尊界'],
    ]
    FILTER_BRAND_IDS = FIVE_REALM_IDS + [name_to_id['岚图']]


def build_file_header_comment(env: str = 'daily') -> str:
    """生成 JS fixture 文件头 brandIdMap 注释块。"""
    name_to_id = load_brand_env_maps()[env]
    lines = [
        '// const baseSceneCode = {',
        "//   '1.1': 100101, //精品升级",
        "//   '1.2': 100102, //次新车升配",
        "//   '1.3': 100103, //售后众筹",
        "//   '2.1.1': 110101, //售前会员权益升级",
        "//   '2.1.2': 110102, //售后会员权益升级",
        "//   '2.3.1': 110201, //售前延保",
        "//   '2.3.2': 110202, //售后延保",
        '// }',
        '// const sceneType = {',
        "//   '延保': 0,",
        "//   '权益': 0,",
        "//   '轻改': 1,",
        '// }',
        '// const brandIdMap = {',
    ]
    for name, brand_id in name_to_id.items():
        lines.append(f"//   '{name}': {brand_id},")
    lines.append('// }')
    return '\n'.join(lines)


apply_brand_env('daily')

SHEET_CONFIG = {
    'staff': {
        'sheet_filter': '驻店日报',
        'baseline': PKG_ROOT / 'fixtures/schema-staff-daily-full.js',
        'output': PKG_ROOT / 'fixtures/schema-staff-daily-v2.1.1.js',
        'form_code': 'staff_daily_report',
        'attendance_key': 'F1-1',
    },
    'store': {
        'sheet_filter': '门店日报',
        'baseline': PKG_ROOT / 'fixtures/schema-store-daily-full.js',
        'output': PKG_ROOT / 'fixtures/schema-store-daily-v2.1.1.js',
        'form_code': 'store_daily_report',
        'attendance_key': None,
    },
}

TYPE_MAP = {
    '单选框': 'radio',
    '数值输入框': 'numberInput',
    '多行文本输入框': 'textarea',
    '分组': 'group',
    '子表单': 'subform',
    '分割线': 'divider',
    '选择器': 'select',
}


def load_baseline_js(path: Path) -> dict[str, dict]:
    """从 indexed JS fixture 扁平化 key → field(含嵌套子字段)。"""
    code = f"""
    const m = require({json.dumps(str(path).replace(chr(92), '/'))});
    const list = Object.keys(m).sort((a,b)=>+a-+b).map(k=>m[k]);
    function walk(field, out) {{
      if (!field || !field.key) return;
      out[field.key] = field;
      if (Array.isArray(field.children)) {{
        for (const ch of field.children) {{
          if (Array.isArray(ch)) {{
            for (const c of ch) walk(c, out);
          }} else {{
            walk(ch, out);
          }}
        }}
      }}
    }}
    const map = {{}};
    for (const f of list) walk(f, map);
    console.log(JSON.stringify(map));
    """
    result = subprocess.run(
        ['node', '-e', code],
        capture_output=True,
        text=True,
        encoding='utf-8',
        cwd=str(PKG_ROOT.parent),
    )
    if result.returncode != 0:
        raise RuntimeError(result.stderr or 'baseline load failed')
    return json.loads(result.stdout)


def col_index(ref: str) -> int:
    col = ''.join(ch for ch in ref if ch.isalpha())
    num = 0
    for ch in col:
        num = num * 26 + ord(ch) - 64
    return num - 1


def parse_styles(z: zipfile.ZipFile):
    styles = ET.fromstring(z.read('xl/styles.xml'))
    fills = []
    for fill in styles.findall('.//m:fills/m:fill', NS):
        pattern = fill.find('m:patternFill', NS)
        if pattern is None:
            fills.append(None)
            continue
        fg = pattern.find('m:fgColor', NS)
        rgb = None
        if fg is not None and fg.get('rgb'):
            h = fg.get('rgb')
            if len(h) == 8:
                h = h[2:]
            rgb = tuple(int(h[i : i + 2], 16) for i in (0, 2, 4))
        fills.append(rgb)

    fonts = [{'strike': f.find('m:strike', NS) is not None} for f in styles.findall('.//m:fonts/m:font', NS)]
    xfs = [
        (int(xf.get('fontId', 0)), int(xf.get('fillId', 0)))
        for xf in styles.findall('.//m:cellXfs/m:xf', NS)
    ]
    return fills, fonts, xfs


def read_shared_strings(z: zipfile.ZipFile) -> list[str]:
    if 'xl/sharedStrings.xml' not in z.namelist():
        return []
    ss = ET.fromstring(z.read('xl/sharedStrings.xml'))
    out = []
    for si in ss.findall('.//m:si', NS):
        texts = [(t.text or '') for t in si.findall('.//m:t', NS)]
        out.append(''.join(texts))
    return out


def cell_text(cell, shared: list[str]) -> str:
    t = cell.get('t')
    v = cell.find('m:v', NS)
    if v is None:
        return ''
    if t == 's':
        return shared[int(v.text)]
    return v.text or ''


def classify_row(row, xfs, fonts, fills, shared: list[str]) -> tuple[str | None, str]:
    key = ''
    classes = set()
    for cell in row.findall('m:c', NS):
        ref = cell.get('r', '')
        if ref.startswith('A'):
            key = cell_text(cell, shared)
        style_id = cell.get('s')
        if style_id is None:
            classes.add('normal')
            continue
        font_id, fill_id = xfs[int(style_id)]
        if fonts[font_id]['strike']:
            classes.add('strike')
        elif fills[fill_id] == PURPLE_RGB:
            classes.add('purple')
        else:
            classes.add('normal')
    if not key.startswith('F'):
        return None, key
    if 'strike' in classes:
        return 'remove', key
    if 'purple' in classes:
        return 'purple', key
    return 'keep', key


def infer_base_scene_from_scene_text(scene_text: str) -> list[int]:
    """显隐列为空时,从业务大类列推断 baseSceneCode。"""
    codes: list[int] = []
    text = scene_text or ''
    if '延保' in text:
        codes.extend([110201, 110202])
    if '权益' in text:
        codes.extend([110101, 110102])
    if '轻改' in text:
        codes.extend([100101, 100102, 100103])
    return sorted(set(codes))


def read_sheet_rows(xlsx: Path, sheet_filter: str) -> tuple[list[str], list[dict]]:
    with zipfile.ZipFile(xlsx) as z:
        fills, fonts, xfs = parse_styles(z)
        shared_strings = read_shared_strings(z)
        wb = ET.fromstring(z.read('xl/workbook.xml'))
        sheets = [
            (
                s.get('name'),
                s.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id'),
            )
            for s in wb.findall('.//m:sheet', NS)
        ]
        rels = ET.fromstring(z.read('xl/_rels/workbook.xml.rels'))
        rid_map = {r.get('Id'): r.get('Target') for r in rels}

        for name, rid in sheets:
            if sheet_filter not in name:
                continue
            target = rid_map[rid]
            if not target.startswith('xl/'):
                target = 'xl/' + target
            sh = ET.fromstring(z.read(target))
            header: list[str] = []
            records: list[dict] = []
            for row in sh.findall('.//m:sheetData/m:row', NS):
                cells: dict[int, str] = {}
                for cell in row.findall('m:c', NS):
                    cells[col_index(cell.get('r', 'A1'))] = cell_text(cell, shared_strings)
                if not cells:
                    continue
                max_col = max(cells)
                values = [cells.get(i, '') for i in range(max_col + 1)]
                if not header:
                    header = values
                    continue
                row_type, key = classify_row(row, xfs, fonts, fills, shared_strings)
                if row_type is None:
                    continue
                record = {header[i]: values[i] if i < len(values) else '' for i in range(len(header))}
                record['_rowType'] = row_type
                record['_key'] = key
                records.append(record)
            return header, records
    raise ValueError(f'sheet not found: {sheet_filter}')


def parse_scene_type(text: str) -> list[int]:
    text = (text or '').strip()
    if not text or text == '不限':
        return []
    parts = [p.strip() for p in re.split(r'[,,]', text) if p.strip()]
    result: list[int] = []
    for p in parts:
        if p in ('延保', '权益'):
            result.append(0)
        elif p == '轻改':
            result.append(1)
    return result


def parse_brand_restriction(text: str) -> tuple[list[int], list[int]]:
    """返回 (brandId, filterBrandId)。

    「岚图,其他品牌」为 OR 语义:brandId 留空,filterBrandId 仅含五界;
    运行时 brandSpec 在经营品牌全部落在五界内时隐藏,岚图或其它品牌任一即可显示。
    """
    text = (text or '').strip()
    if not text or text == '不限':
        return [], []
    parts = [p.strip() for p in re.split(r'[,,]', text) if p.strip()]
    has_other = '其他品牌' in parts
    named = [p for p in parts if p in BRAND_NAME_TO_ID]
    brand_ids = [BRAND_NAME_TO_ID[p] for p in named]

    if has_other and not named:
        return [], list(FILTER_BRAND_IDS)
    if has_other and named:
        # 岚图 or 其他品牌:OR 语义,仅用 filterBrandId 隐藏纯五界门店
        return [], list(FIVE_REALM_IDS)
    return brand_ids, []


def extract_scene_codes(visibility: str) -> list[int]:
    """从显隐文案提取 baseSceneCode;token 按长度降序 + 边界匹配,避免 2.1.1 误命中 1.1。"""
    codes: list[int] = []
    for token in sorted(BASE_SCENE_CODE.keys(), key=len, reverse=True):
        pattern = r'(?<![\d.])' + re.escape(token) + r'(?![\d.])'
        if re.search(pattern, visibility):
            codes.append(BASE_SCENE_CODE[token])
    return sorted(set(codes))


def parse_visibility(visibility: str, attendance_key: str | None) -> tuple[list[int], dict]:
    visibility = (visibility or '').strip()
    rules: dict = {}
    base_scene: list[int] = []

    if not visibility or visibility == '-':
        return base_scene, rules

    if '场景' in visibility:
        base_scene = extract_scene_codes(visibility)

    if attendance_key and ('今日出勤=在岗' in visibility or '今日出勤 = 在岗' in visibility):
        rules['keys'] = [attendance_key]
        rules['result'] = 'val1 == "在岗"'

    return base_scene, rules


def parse_other_rules(text: str, field: dict) -> None:
    text = (text or '').strip()
    if not text or text == '-':
        return
    rules = field.setdefault('rules', {})
    if '大于等于0的整数' in text:
        rules['min'] = 0
        rules['integer'] = True
    elif '大于等于0的数值' in text:
        rules['min'] = 0
        rules['decimal'] = True
    if '不超过100字' in text:
        rules['maxLength'] = 100
    if '后置单位"%"' in text or '后置显示文字"%"' in text or '单位"%"' in text:
        field['unit'] = '%'
    if '后置显示文字"元"' in text or '单位"元"' in text:
        field['unit'] = '元'


def parse_options(options_text: str, field: dict) -> None:
    text = (options_text or '').strip()
    if not text or text == '-':
        return
    if text.startswith('固定值:'):
        raw = text.split(':', 1)[1]
        opts = [o.strip() for o in re.split(r'[,,]', raw) if o.strip()]
        field['options'] = [{'label': o, 'value': o} for o in opts]
    if '当前门店驻店人员' in text:
        field['optionsKey'] = 'storeStaffList'
        field['type'] = 'multipleSelect'
        field['options'] = []
    if '当前门店4S店成员' in text:
        field['optionsKey'] = '4sStaffList'
        field['type'] = 'select'
        field['options'] = []


def parse_required(text: str) -> bool:
    return '☑' in (text or '') or text.strip().upper() == 'Y'


def parse_default_value(text: str, field_type: str):
    text = (text or '').strip()
    if text == '-' or text == '':
        return None
    if field_type == 'numberInput':
        try:
            if '.' in text:
                return float(text)
            return int(text)
        except ValueError:
            return 0
    return text


def is_container_row(key: str, comp_type: str) -> bool:
    return comp_type in ('group', 'subform') and key.count('-') == 1


def parent_key(key: str) -> str | None:
    parts = key.split('-')
    if len(parts) <= 2:
        return None
    return '-'.join(parts[:2])


def row_to_field(record: dict, sheet_kind: str, attendance_key: str | None) -> dict:
    if sheet_kind == 'staff':
        scene_text = record.get('业务大类限制', '')
        brand_text = record.get('门店经营品牌限制', '')
        visibility = record.get('显隐条件', '')
        options_text = record.get('选项数据', '')
        other_rules = record.get('其他规则', '')
    else:
        scene_text = record.get('业务大类限制', '')
        brand_text = record.get('门店经营品牌限制', '')
        visibility = record.get('显隐条件', '')
        options_text = record.get('选项数据', '')
        other_rules = record.get('其他规则', '')

    key = record['_key']
    comp_name = record.get('表单组件名称', '')
    comp_type_raw = record.get('表单组件类型', '')
    field_type = TYPE_MAP.get(comp_type_raw, 'numberInput')

  # 选择器默认 select,options 解析可能改为 multipleSelect
    field: dict = {
        'label': comp_name,
        'sortNum': str(record.get('排序', '')).strip(),
        'key': key,
        'type': field_type,
        'required': parse_required(record.get('必填', '')),
        'sceneType': parse_scene_type(scene_text),
        'brandId': [],
        'baseSceneCode': [],
        'rules': {},
    }

    brand_id, filter_brand = parse_brand_restriction(brand_text)
    field['brandId'] = brand_id
    if filter_brand:
        field['filterBrandId'] = filter_brand

    base_scene, vis_rules = parse_visibility(visibility, attendance_key)
    if not base_scene:
        base_scene = infer_base_scene_from_scene_text(scene_text)
    field['baseSceneCode'] = base_scene
    if vis_rules:
        field['rules'].update(vis_rules)

    parse_options(options_text, field)
    parse_other_rules(other_rules, field)

    default_val = parse_default_value(record.get('默认值', ''), field['type'])
    if default_val is not None:
        field['value'] = default_val
    elif field['type'] == 'numberInput' and 'value' not in field:
        field['value'] = 0
    elif field['type'] == 'textarea':
        field.setdefault('value', '')

    # divider 硬编码(与 V2.0 引擎契约一致)
    if field['type'] == 'divider':
        field['rules'] = {}
        if key == 'F2-94':
            field['sceneType'] = [0, 0]
            field['ybCode'] = [110201, 110202]
            field['qyCode'] = [110101, 110102]
        elif key == 'F2-91':
            field['isYB'] = True
            field['ybCode'] = [110201, 110202]
            field['qyCode'] = [110101, 110102]
        elif key == 'F2-92':
            field['isQY'] = True
            field['ybCode'] = [110201, 110202]
            field['qyCode'] = [110101, 110102]
        elif key == 'F2-93':
            field['qgCode'] = [100101, 100102, 100103]

    # F2-1 / F2-2 若从 Excel 解析需补全(keep 行走 baseline)
    if key == 'F2-1':
        field['completeFun'] = {'key': 'F2-2', 'result': '(list.length)'}
    if key == 'F2-2':
        field['disabledFun'] = {'keys': ['F2-1'], 'result': 'val1 != null'}

    return field


def build_children_rules(children: list[dict]) -> dict:
    rules_map: dict = {}
    for child in children:
        if child.get('type') != 'numberInput':
            continue
        child_rules = {'min': 0}
        if child.get('unit') == '元' or child.get('rules', {}).get('decimal'):
            child_rules['decimal'] = True
        else:
            child_rules['integer'] = True
        rules_map[child['key']] = child_rules
    return rules_map


def assemble_list(records: list[dict], baseline_map: dict[str, dict], sheet_cfg: dict) -> list[dict]:
    attendance_key = sheet_cfg.get('attendance_key')
    sheet_kind = 'staff' if 'staff' in sheet_cfg['form_code'] else 'store'

    flat: dict[str, dict] = {}
    remove_keys: set[str] = set()

    for record in records:
        key = record['_key']
        row_type = record['_rowType']
        if row_type == 'remove':
            remove_keys.add(key)
            continue
        if row_type == 'keep':
            if key not in baseline_map:
                raise KeyError(f'keep row {key} missing in baseline')
            flat[key] = copy.deepcopy(baseline_map[key])
            continue
        flat[key] = row_to_field(record, sheet_kind, attendance_key)

    # 剔除嵌套在 baseline 拷贝里但已删除的子 key
    for key in list(flat.keys()):
        field = flat[key]
        if field.get('type') == 'group' and isinstance(field.get('children'), list):
            field['children'] = [
                ch for ch in field['children']
                if ch.get('key') not in remove_keys
            ]
            field['childrenRules'] = {
                k: v for k, v in (field.get('childrenRules') or {}).items()
                if k not in remove_keys
            }
        if field.get('type') == 'subform' and isinstance(field.get('children'), list):
            new_rows = []
            for row in field['children']:
                if not isinstance(row, list):
                    continue
                new_rows.append([c for c in row if c.get('key') not in remove_keys])
            field['children'] = new_rows
            field['childrenRules'] = {
                k: v for k, v in (field.get('childrenRules') or {}).items()
                if k not in remove_keys
            }

    # 将紫色解析的叶子字段合并进容器
    for key, field in list(flat.items()):
        pk = parent_key(key)
        if pk is None or pk == key:
            continue
        if pk not in flat:
            continue
        parent = flat[pk]
        if parent.get('type') == 'group':
            children = parent.setdefault('children', [])
            replaced = False
            for i, ch in enumerate(children):
                if ch.get('key') == key:
                    children[i] = field
                    replaced = True
                    break
            if not replaced:
                children.append(field)
            del flat[key]
        elif parent.get('type') == 'subform':
            children = parent.setdefault('children', [[]])
            if not children:
                children.append([])
            row = children[0]
            replaced = False
            for i, ch in enumerate(row):
                if ch.get('key') == key:
                    row[i] = field
                    replaced = True
                    break
            if not replaced:
                row.append(field)
            del flat[key]

    # 顶层 list:仅保留无 parent 或 parent 不在 flat 的字段
    top_keys = [k for k in flat if parent_key(k) is None or parent_key(k) not in flat]

    for key in top_keys:
        field = flat[key]
        if field.get('type') == 'group' and field.get('children'):
            field['children'] = sorted(field['children'], key=lambda c: int(c.get('sortNum', 0)))
            field['childrenRules'] = build_children_rules(field['children'])
        if field.get('type') == 'subform' and field.get('children'):
            for row in field['children']:
                if isinstance(row, list):
                    row.sort(key=lambda c: int(c.get('sortNum', 0)))
            field['childrenRules'] = build_children_rules(
                [c for row in field['children'] if isinstance(row, list) for c in row]
            )

    top_fields = [flat[k] for k in top_keys]
    top_fields.sort(key=lambda f: int(f.get('sortNum', 0)))
    return top_fields


def build_visibility_map(records: list[dict]) -> dict[str, str]:
    """Excel 显隐条件列,供新增字段生成行内备注。"""
    out: dict[str, str] = {}
    for record in records:
        if record.get('_rowType') == 'remove':
            continue
        vis = (record.get('显隐条件') or '').strip()
        if vis and vis != '-':
            out[record['_key']] = vis
    return out


def load_comment_sidecar() -> dict:
    path = PKG_ROOT / 'fixtures/template-field-comments.json'
    return json.loads(path.read_text(encoding='utf-8'))


def visibility_to_inline_comment(text: str) -> str:
    text = (text or '').strip()
    if not text or text == '-':
        return ''
    return f'//{text}'


COMMENTS_JSON = PKG_ROOT / 'fixtures/template-field-comments.json'

# 字段属性输出顺序(对齐 V2.0 业务配置粘贴格式)
FIELD_PROP_ORDER = [
    'label', 'sortNum', 'key', 'type', 'required', 'sceneType', 'brandId',
    'baseSceneCode', 'options', 'optionsKey', 'value', 'unit', 'rules',
    'filterBrandId', 'completeFun', 'disabledFun', 'isYB', 'isQY',
    'ybCode', 'qyCode', 'qgCode', 'childrenRules', 'children',
]

DIVIDER_PROP_ORDER = [
    'label', 'sortNum', 'key', 'type', 'required', 'sceneType', 'brandId',
    'baseSceneCode', 'isYB', 'isQY', 'ybCode', 'qyCode', 'qgCode', 'rules',
]


def _js_str(value: str) -> str:
    return "'" + value.replace('\\', '\\\\').replace("'", "\\'") + "'"


def _js_value(value, indent: int, inline_comment: str = '') -> str:
    pad = ' ' * indent
    suffix = f' {inline_comment}' if inline_comment else ''
    if isinstance(value, str):
        if value == '(list.length)':
            return f'"(list.length)"{suffix}'
        return f'{_js_str(value)}{suffix}'
    if isinstance(value, bool):
        return f'{str(value).lower()}{suffix}'
    if isinstance(value, int):
        return f'{value}{suffix}'
    if isinstance(value, float):
        if value == int(value):
            return f'{int(value)}{suffix}'
        return f'{value}{suffix}'
    if value is None:
        return f'null{suffix}'
    if isinstance(value, list):
        if not value:
            return f'[]{suffix}'
        inner = ', '.join(_js_value(v, indent, '') for v in value)
        return f'[{inner}]{suffix}'
    if isinstance(value, dict):
        return _js_object(value, indent, {}, {}) + (f' {inline_comment}' if inline_comment else '')
    return f'{json.dumps(value, ensure_ascii=False)}{suffix}'


def _ordered_field_items(field: dict, omit: set[str]) -> list[tuple[str, object]]:
    prop_order = DIVIDER_PROP_ORDER if field.get('type') == 'divider' else FIELD_PROP_ORDER
    seen = set()
    items: list[tuple[str, object]] = []
    for key in prop_order:
        if key in field and key not in omit:
            items.append((key, field[key]))
            seen.add(key)
    for key, val in field.items():
        if key not in seen and key not in omit:
            items.append((key, val))
    return items


def _emit_comment_line(inner_pad: str, text: str) -> str:
    return f'{inner_pad}{text.rstrip(",")}'


def _js_object(
    obj: dict,
    indent: int,
    field_comments: dict,
    visibility_map: dict[str, str],
    field_key: str | None = None,
) -> str:
    pad = ' ' * indent
    inner_pad = ' ' * (indent + 4)
    omit = set(field_comments.get('omitProps', []))
    prop_before: dict = field_comments.get('propBefore', {})
    prop_inline: dict = field_comments.get('propInline', {})
    prop_before_rules: list = field_comments.get('propBeforeRules', [])

    lines: list[str] = []
    visibility_used = False
    for prop, val in _ordered_field_items(obj, omit):
        for comment_line in prop_before.get(prop, []):
            lines.append(_emit_comment_line(inner_pad, comment_line) + ',')
        if prop == 'rules' and prop_before_rules:
            for comment_line in prop_before_rules:
                lines.append(_emit_comment_line(inner_pad, comment_line) + ',')

        sidecar_inline = prop_inline.get(prop, '')
        inline = sidecar_inline
        if not inline and field_key and not visibility_used:
            vis = visibility_map.get(field_key, '')
            if vis:
                if prop == 'baseSceneCode' and '场景' in vis:
                    inline = visibility_to_inline_comment(vis)
                    visibility_used = True
                elif prop == 'filterBrandId' and '门店经营品牌' in vis:
                    inline = visibility_to_inline_comment(vis)
                    visibility_used = True
                elif prop == 'brandId' and '门店经营品牌' in vis and 'filterBrandId' not in obj:
                    inline = visibility_to_inline_comment(vis)
                    visibility_used = True
                elif prop == 'rules' and ('今日出勤' in vis or 'F2-1' in vis):
                    inline = visibility_to_inline_comment(vis)
                    visibility_used = True

        if prop == 'children':
            lines.append(f'{inner_pad}children: {_js_children(val, indent + 4, visibility_map)},')
            continue
        if prop == 'childrenRules':
            lines.append(f'{inner_pad}childrenRules: {_js_children_rules(val, indent + 4)},')
            continue
        if prop in ('completeFun', 'disabledFun') and isinstance(val, dict):
            lines.append(f'{inner_pad}{prop}: {_js_fun_obj(val, indent + 4)},')
            continue
        if prop == 'rules' and isinstance(val, dict):
            lines.append(f'{inner_pad}rules: {_js_rules(val, indent + 4)},')
            if inline:
                lines.append(f'{inner_pad}{inline}')
            continue
        if prop == 'options' and isinstance(val, list) and val and isinstance(val[0], dict):
            lines.append(f'{inner_pad}options: {_js_options(val, indent + 4)},')
            continue

        core = _js_value(val, indent + 4, '')
        if sidecar_inline:
            lines.append(f'{inner_pad}{prop}: {core}, {sidecar_inline},')
        else:
            lines.append(f'{inner_pad}{prop}: {core},')
            if inline:
                lines.append(f'{inner_pad}{inline}')

    return '{\n' + '\n'.join(lines) + f'\n{pad}}}'


def _js_fun_obj(obj: dict, indent: int) -> str:
    pad = ' ' * indent
    inner = ' ' * (indent + 4)
    parts = []
    for k, v in obj.items():
        if k == 'result':
            if v == '(list.length)':
                parts.append(f'{inner}result: "(list.length)"')
            else:
                parts.append(f'{inner}result: {_js_str(v)}')
        else:
            parts.append(f'{inner}{k}: {_js_value(v, indent + 4)}')
    return '{\n' + ',\n'.join(parts) + f'\n{pad}}}'


def _js_rules(rules: dict, indent: int) -> str:
    pad = ' ' * indent
    inner = ' ' * (indent + 4)
    order = ['min', 'integer', 'decimal', 'maxLength', 'keys', 'result']
    lines = []
    for k in order:
        if k not in rules:
            continue
        val = rules[k]
        if k == 'result':
            lines.append(f'{inner}result: {_js_str(val)},')
        elif k == 'keys':
            lines.append(f'{inner}keys: [{", ".join(_js_str(x) for x in val)}],')
        else:
            lines.append(f'{inner}{k}: {_js_value(val, indent + 4)},')
    for k, val in rules.items():
        if k in order:
            continue
        lines.append(f'{inner}{k}: {_js_value(val, indent + 4)},')
    if lines:
        lines[-1] = lines[-1].rstrip(',')
    if not lines:
        return '{}'
    return '{\n' + '\n'.join(lines) + f'\n{pad}}}'


def _js_options(options: list, indent: int) -> str:
    pad = ' ' * indent
    inner = ' ' * (indent + 4)
    items = []
    for opt in options:
        items.append(
            f'{inner}{{\n{inner}    label: {_js_str(opt["label"])},\n'
            f'{inner}    value: {_js_str(opt["value"])}\n{inner}}}'
        )
    return '[\n' + ',\n'.join(items) + f'\n{pad}]'


def _js_children_rules(rules: dict, indent: int) -> str:
    pad = ' ' * indent
    inner = ' ' * (indent + 4)
    lines = []
    for k in sorted(rules.keys()):
        r = rules[k]
        r_parts = [f'min: {r.get("min", 0)}']
        if r.get('decimal'):
            r_parts.append('decimal: true')
        else:
            r_parts.append('integer: true')
        lines.append(f"{inner}{_js_str(k)}: {{ {', '.join(r_parts)} }}")
    return '{\n' + ',\n'.join(lines) + f'\n{pad}}}'


def _js_children(children, indent: int, visibility_map: dict[str, str]) -> str:
    pad = ' ' * indent
    inner = ' ' * (indent + 4)
    if not children:
        return '[]'
    # group: [child, child]; subform: [[child, ...]]
    if children and isinstance(children[0], list):
        row = children[0]
        row_lines = []
        for ch in row:
            fc = load_comment_sidecar()['fields'].get(ch.get('key', ''), {})
            row_lines.append(
                f'{inner}{_js_field(ch, indent + 4, fc, visibility_map)}'
            )
        return '[\n' + f'{inner}[\n' + ',\n\n'.join(row_lines) + f'\n{inner}]\n{pad}]'
    child_lines = []
    for ch in children:
        fc = load_comment_sidecar()['fields'].get(ch.get('key', ''), {})
        child_lines.append(f'{inner}{_js_field(ch, indent + 4, fc, visibility_map)}')
    return '[\n' + ',\n\n'.join(child_lines) + f'\n{pad}]'


def _js_field(field: dict, indent: int, field_comments: dict, visibility_map: dict[str, str]) -> str:
    pad = ' ' * indent
    key = field.get('key', '')
    vis_inline = ''
    if key and key not in field_comments.get('propInline', {}):
        vis = visibility_map.get(key, '')
        if vis and '场景' in vis and 'baseSceneCode' not in field_comments.get('omitProps', []):
            pass  # baseSceneCode 行内备注在 _js_object 处理
    body = _js_object(field, indent, field_comments, visibility_map, field_key=key)
    return body


def emit_js_array(
    fields: list[dict],
    visibility_map: dict[str, str],
    sidecar: dict,
) -> str:
    header = sidecar.get('fileHeader', '')
    jsdoc = sidecar.get('jsDoc', '')
    field_comment_map = sidecar.get('fields', {})

    parts = [header, jsdoc, '[{']
    field_strs = []
    for i, field in enumerate(fields):
        fc = field_comment_map.get(field.get('key', ''), {})
        field_strs.append(_js_field(field, 4, fc, visibility_map))
    parts[2] = '[\n' + ',\n\n'.join('    ' + s for s in field_strs) + '\n]'
    return '\n'.join(parts) + '\n'


def convert(sheet: str, xlsx: Path) -> tuple[list[dict], dict[str, str]]:
    cfg = SHEET_CONFIG[sheet]
    _header, records = read_sheet_rows(xlsx, cfg['sheet_filter'])
    baseline_map = load_baseline_js(cfg['baseline'])
    field_list = assemble_list(records, baseline_map, cfg)
    visibility_map = build_visibility_map(records)
    return field_list, visibility_map


def main():
    parser = argparse.ArgumentParser(description='Excel 填写表单 → schema JSON/JS')
    parser.add_argument('--sheet', choices=['staff', 'store'], required=True)
    parser.add_argument('--input', type=Path, default=DEFAULT_XLSX)
    parser.add_argument('--output', type=Path, default=None)
    parser.add_argument('--format', choices=['js', 'json'], default='js')
    parser.add_argument(
        '--env',
        choices=['daily', 'production'],
        default='daily',
        help='brandId 环境:daily=测试,production=线上(默认输出 .prod 后缀)',
    )
    args = parser.parse_args()

    apply_brand_env(args.env)

    if not args.input.exists():
        print(f'input not found: {args.input}', file=sys.stderr)
        sys.exit(1)

    field_list, visibility_map = convert(args.sheet, args.input)
    cfg = SHEET_CONFIG[args.sheet]
    out = args.output or cfg['output']
    if args.env == 'production' and args.output is None:
        out = out.with_name(out.stem + '.prod' + out.suffix)
    if args.format == 'json':
        if out.suffix != '.json':
            out = out.with_suffix('.json')
        schema = {
            'version': '2.1.1',
            'formCode': cfg['form_code'],
            'title': f"{'驻店' if args.sheet == 'staff' else '门店'}日报 V2.1.1",
            'list': field_list,
        }
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(json.dumps(schema, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
    else:
        if out.suffix != '.js':
            out = out.with_suffix('.js')
        sidecar = load_comment_sidecar()
        if args.env == 'production':
            sidecar = {**sidecar, 'fileHeader': build_file_header_comment('production')}
        content = emit_js_array(field_list, visibility_map, sidecar)
        out.parent.mkdir(parents=True, exist_ok=True)
        out.write_text(content, encoding='utf-8')

    print(f'written {out} ({len(field_list)} top-level fields, format={args.format}, env={args.env})')


if __name__ == '__main__':
    main()