render_flowcharts.py 17.5 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
#!/usr/bin/env python3
"""Render local PNG copies of the five Mermaid diagrams for the DOCX.

The Markdown Mermaid blocks remain the editable source. This renderer is fully
offline and draws equivalent labelled flows with Pillow so no internal workflow
content is sent to a third-party renderer.
"""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import Iterable

from PIL import Image, ImageDraw, ImageFont


ROOT = Path(__file__).resolve().parents[1]
ASSET_DIR = ROOT / "assets"
FONT_REGULAR = Path(r"C:\Windows\Fonts\msyh.ttc")
FONT_BOLD = Path(r"C:\Windows\Fonts\msyhbd.ttc")

INK = "#0B2545"
MUTED = "#526274"
BLUE = "#2E74B5"
BLUE_FILL = "#E8EEF5"
LIGHT = "#F4F6F9"
GREEN = "#2C7A5A"
GREEN_FILL = "#E8F5EE"
GOLD = "#8A6500"
GOLD_FILL = "#FFF7DD"
RED = "#9B1C1C"
RED_FILL = "#FDECEC"
WHITE = "#FFFFFF"
BORDER = "#A7B4C2"


@dataclass(frozen=True)
class Box:
    x: int
    y: int
    w: int
    h: int
    text: str
    fill: str = BLUE_FILL
    outline: str = BLUE
    decision: bool = False
    font_size: int = 30

    @property
    def center(self) -> tuple[int, int]:
        return self.x + self.w // 2, self.y + self.h // 2

    @property
    def top(self) -> tuple[int, int]:
        return self.x + self.w // 2, self.y

    @property
    def bottom(self) -> tuple[int, int]:
        return self.x + self.w // 2, self.y + self.h

    @property
    def left(self) -> tuple[int, int]:
        return self.x, self.y + self.h // 2

    @property
    def right(self) -> tuple[int, int]:
        return self.x + self.w, self.y + self.h // 2


def font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont:
    return ImageFont.truetype(str(FONT_BOLD if bold else FONT_REGULAR), size)


def wrap_text(draw: ImageDraw.ImageDraw, text: str, text_font, max_width: int) -> list[str]:
    result: list[str] = []
    for paragraph in text.replace("<br/>", "\n").replace("<br>", "\n").splitlines():
        if not paragraph:
            result.append("")
            continue
        current = ""
        for char in paragraph:
            candidate = current + char
            if current and draw.textlength(candidate, font=text_font) > max_width:
                result.append(current)
                current = char
            else:
                current = candidate
        if current:
            result.append(current)
    return result or [""]


def draw_centered_text(
    draw: ImageDraw.ImageDraw,
    rect: tuple[int, int, int, int],
    text: str,
    size: int,
    color: str = INK,
    bold: bool = False,
) -> None:
    x1, y1, x2, y2 = rect
    text_font = font(size, bold)
    lines = wrap_text(draw, text, text_font, max(20, x2 - x1 - 36))
    line_gap = max(6, size // 5)
    boxes = [draw.textbbox((0, 0), line, font=text_font) for line in lines]
    heights = [box[3] - box[1] for box in boxes]
    total_height = sum(heights) + line_gap * max(0, len(lines) - 1)
    y = y1 + (y2 - y1 - total_height) / 2
    for line, box, height in zip(lines, boxes, heights):
        width = box[2] - box[0]
        draw.text(
            (x1 + (x2 - x1 - width) / 2, y),
            line,
            font=text_font,
            fill=color,
        )
        y += height + line_gap


def draw_box(draw: ImageDraw.ImageDraw, box: Box) -> None:
    if box.decision:
        cx, cy = box.center
        points = [
            (cx, box.y),
            (box.x + box.w, cy),
            (cx, box.y + box.h),
            (box.x, cy),
        ]
        draw.polygon(points, fill=box.fill, outline=box.outline, width=4)
        inset = 30
    else:
        draw.rounded_rectangle(
            (box.x, box.y, box.x + box.w, box.y + box.h),
            radius=22,
            fill=box.fill,
            outline=box.outline,
            width=4,
        )
        inset = 16
    draw_centered_text(
        draw,
        (
            box.x + inset,
            box.y + inset,
            box.x + box.w - inset,
            box.y + box.h - inset,
        ),
        box.text,
        box.font_size,
        bold=False,
    )


def arrow(
    draw: ImageDraw.ImageDraw,
    start: tuple[int, int],
    end: tuple[int, int],
    label: str = "",
    color: str = MUTED,
    bend: tuple[int, int] | None = None,
) -> None:
    points = [start]
    if bend:
        points.append(bend)
    points.append(end)
    draw.line(points, fill=color, width=5, joint="curve")
    px, py = points[-2]
    ex, ey = points[-1]
    dx, dy = ex - px, ey - py
    length = max((dx * dx + dy * dy) ** 0.5, 1)
    ux, uy = dx / length, dy / length
    left = (
        ex - ux * 22 - uy * 11,
        ey - uy * 22 + ux * 11,
    )
    right = (
        ex - ux * 22 + uy * 11,
        ey - uy * 22 - ux * 11,
    )
    draw.polygon([end, left, right], fill=color)
    if label:
        label_font = font(25)
        bbox = draw.textbbox((0, 0), label, font=label_font)
        width, height = bbox[2] - bbox[0], bbox[3] - bbox[1]
        mid_index = max(0, len(points) // 2 - 1)
        a, b = points[mid_index], points[mid_index + 1]
        mx, my = (a[0] + b[0]) / 2, (a[1] + b[1]) / 2
        draw.rounded_rectangle(
            (mx - width / 2 - 10, my - height / 2 - 6, mx + width / 2 + 10, my + height / 2 + 6),
            radius=8,
            fill=WHITE,
        )
        draw.text((mx - width / 2, my - height / 2), label, font=label_font, fill=INK)


def title(draw: ImageDraw.ImageDraw, text: str, width: int) -> None:
    draw_centered_text(draw, (60, 25, width - 60, 100), text, 42, color=INK, bold=True)


def lane(
    draw: ImageDraw.ImageDraw,
    rect: tuple[int, int, int, int],
    label: str,
    fill: str = "#FAFBFC",
) -> None:
    draw.rounded_rectangle(rect, radius=26, fill=fill, outline=BORDER, width=3)
    x1, y1, x2, _ = rect
    draw_centered_text(draw, (x1 + 12, y1 + 8, x2 - 12, y1 + 62), label, 28, color=BLUE, bold=True)


def new_canvas(width: int, height: int, diagram_title: str) -> tuple[Image.Image, ImageDraw.ImageDraw]:
    image = Image.new("RGB", (width, height), WHITE)
    draw = ImageDraw.Draw(image)
    title(draw, diagram_title, width)
    return image, draw


def save(image: Image.Image, filename: str) -> None:
    ASSET_DIR.mkdir(parents=True, exist_ok=True)
    path = ASSET_DIR / filename
    image.save(path, format="PNG", optimize=True, dpi=(220, 220))
    print(f"Rendered {path}")


def render_end_to_end() -> None:
    image, draw = new_canvas(1700, 2260, "订单端到端角色泳道")
    lanes = [
        (100, 130, 1600, 560, "销售 / 驻店员工", "#F9FBFD"),
        (100, 600, 1600, 1160, "订单前端与订单服务", "#F8FAFC"),
        (100, 1200, 1600, 1900, "技师 / 施工", "#F9FBFD"),
        (100, 1940, 1600, 2190, "外部依赖", "#F8FAFC"),
    ]
    for x1, y1, x2, y2, label, fill in lanes:
        lane(draw, (x1, y1, x2, y2), label, fill)

    sales = [
        Box(150, 250, 340, 150, "选择入口\n新建 / 扫码 / 补录 / 编辑", font_size=28),
        Box(700, 250, 300, 150, "填写客户、车辆、场景"),
        Box(1230, 250, 300, 150, "选择商品、支付并提交"),
    ]
    for item in sales:
        draw_box(draw, item)
    arrow(draw, sales[0].right, sales[1].left)
    arrow(draw, sales[1].right, sales[2].left)

    decision = Box(700, 690, 300, 170, "提交类型", fill=GOLD_FILL, outline=GOLD, decision=True)
    results = [
        Box(150, 930, 220, 120, "预录工单", LIGHT, BORDER, font_size=28),
        Box(430, 930, 220, 120, "战败工单", RED_FILL, RED, font_size=28),
        Box(710, 930, 220, 120, "补录 / 纠错", LIGHT, BORDER, font_size=28),
        Box(990, 930, 220, 120, "待支付", GOLD_FILL, GOLD, font_size=28),
        Box(1270, 930, 220, 120, "已支付", GREEN_FILL, GREEN, font_size=28),
    ]
    draw_box(draw, decision)
    for item in results:
        draw_box(draw, item)
        arrow(draw, decision.bottom, item.top)
    arrow(draw, sales[-1].bottom, decision.top)

    construction = [
        Box(1230, 1320, 300, 135, "确认是否施工"),
        Box(700, 1320, 300, 135, "创建施工单并领单"),
        Box(170, 1320, 300, 135, "商品级出库"),
        Box(170, 1640, 300, 135, "上传图片与起止时间"),
        Box(700, 1640, 300, 135, "部分 / 全部完工"),
        Box(1230, 1640, 300, 135, "客户返工\n新建返工施工单"),
    ]
    for item in construction:
        draw_box(draw, item)
    arrow(draw, results[-1].bottom, construction[0].top)
    arrow(draw, construction[0].left, construction[1].right)
    arrow(draw, construction[1].left, construction[2].right)
    arrow(draw, construction[2].bottom, construction[3].top)
    arrow(draw, construction[3].right, construction[4].left)
    arrow(draw, construction[4].right, construction[5].left)

    external = [
        Box(210, 2020, 310, 100, "库存 / 扫码", LIGHT, BORDER, font_size=27),
        Box(695, 2020, 310, 100, "日报 / 产值 / BI", LIGHT, BORDER, font_size=27),
        Box(1180, 2020, 310, 100, "支付 / 退款", LIGHT, BORDER, font_size=27),
    ]
    for item in external:
        draw_box(draw, item)
    save(image, "order-end-to-end.png")


def render_state_machine() -> None:
    image, draw = new_canvas(1700, 1860, "工单状态机与页面路由")
    boxes = {
        "pending": Box(120, 180, 300, 140, "1 待跟进\n进入 createOrder", GOLD_FILL, GOLD),
        "defeat": Box(120, 600, 300, 140, "2 战败", RED_FILL, RED),
        "pay": Box(700, 180, 300, 140, "3 待支付\n进入 confirmOrder", GOLD_FILL, GOLD),
        "approval": Box(1280, 180, 300, 140, "14 审批中", GOLD_FILL, GOLD),
        "paid": Box(700, 600, 300, 140, "4 已支付\n进入订单详情", GREEN_FILL, GREEN),
        "evaluated": Box(1290, 600, 300, 140, "6 已评价", GREEN_FILL, GREEN),
        "revoked": Box(120, 1120, 300, 140, "9 已撤销", LIGHT, BORDER),
        "closed": Box(510, 1120, 300, 140, "10 已关闭", LIGHT, BORDER),
        "error": Box(900, 1120, 300, 140, "11 错误订单", RED_FILL, RED),
        "refunded": Box(1290, 1120, 300, 140, "12 已退款", LIGHT, BORDER),
    }
    arrow(draw, boxes["pending"].right, boxes["pay"].left, "编辑并提交")
    arrow(draw, boxes["pending"].bottom, boxes["defeat"].top, "战败")
    arrow(draw, boxes["pay"].bottom, boxes["paid"].top, "支付成功")
    arrow(draw, boxes["approval"].bottom, boxes["paid"].right, "审批通过")
    arrow(draw, boxes["paid"].right, boxes["evaluated"].left, "客户评价")
    arrow(draw, boxes["pending"].left, boxes["revoked"].top, "撤销", bend=(40, 900))
    arrow(draw, boxes["pay"].left, boxes["revoked"].right, "满足条件撤销", bend=(540, 900))
    arrow(draw, boxes["paid"].bottom, boxes["error"].top, "标记错误 / 纠错")
    arrow(draw, boxes["paid"].bottom, boxes["closed"].top, "关闭")
    arrow(draw, boxes["paid"].right, boxes["refunded"].top, "退款完成")
    arrow(draw, boxes["evaluated"].bottom, boxes["refunded"].top, "退款完成")
    for item in boxes.values():
        draw_box(draw, item)

    note = Box(
        240,
        1500,
        1220,
        190,
        "列表另按所有子订单 constructionStatus 计算 allConstructionFlag:\n全部为 1 或 2 且工单未关闭时,可直接进入施工单详情。",
        LIGHT,
        BORDER,
        font_size=30,
    )
    draw_box(draw, note)
    save(image, "work-order-state-machine.png")


def render_submission() -> None:
    image, draw = new_canvas(1700, 2200, "提交校验与 API 决策")
    checks = [
        Box(590, 150, 520, 105, "submit(i)"),
        Box(590, 310, 520, 105, "日报 / 学习 / 锁单"),
        Box(590, 470, 520, 105, "状态与页面权限"),
        Box(590, 630, 520, 105, "商品、必填、VIN、错单价差、总价"),
    ]
    for item in checks:
        draw_box(draw, item)
    for current, nxt in zip(checks, checks[1:]):
        arrow(draw, current.bottom, nxt.top)

    d1 = Box(650, 820, 400, 180, "是否补录?", GOLD_FILL, GOLD, decision=True)
    d2 = Box(650, 1110, 400, 180, "是否暂存?", GOLD_FILL, GOLD, decision=True)
    d3 = Box(650, 1400, 400, 180, "是否纠错?", GOLD_FILL, GOLD, decision=True)
    for item in (d1, d2, d3):
        draw_box(draw, item)
    arrow(draw, checks[-1].bottom, d1.top)
    arrow(draw, d1.bottom, d2.top, "否")
    arrow(draw, d2.bottom, d3.top, "否")

    supplement = Box(1180, 850, 380, 130, "supplementOrder", GREEN_FILL, GREEN)
    preliminary = Box(1180, 1140, 380, 130, "createPrerecordedOrder", GREEN_FILL, GREEN)
    correction = Box(1180, 1430, 380, 130, "correctionOrder\noldOrderCode", GREEN_FILL, GREEN)
    normal = Box(650, 1720, 400, 140, "createWithPay", GREEN_FILL, GREEN)
    confirm = Box(650, 1960, 400, 120, "confirmOrder", BLUE_FILL, BLUE)
    for item in (supplement, preliminary, correction, normal, confirm):
        draw_box(draw, item)
    arrow(draw, d1.right, supplement.left, "是")
    arrow(draw, d2.right, preliminary.left, "是")
    arrow(draw, d3.right, correction.left, "是")
    arrow(draw, d3.bottom, normal.top, "否")
    arrow(draw, normal.bottom, confirm.top, "正常支付")

    defeat = Box(150, 1720, 380, 140, "selectPayType=0\n战败字段清洗", RED_FILL, RED)
    draw_box(draw, defeat)
    arrow(draw, normal.left, defeat.right, "战败")
    save(image, "submission-decision.png")


def render_cancel_refund() -> None:
    image, draw = new_canvas(1700, 2340, "撤销、退款与标记错误")
    start = Box(620, 140, 460, 120, "工单列表 / 详情操作")
    action = Box(650, 350, 400, 170, "操作类型", GOLD_FILL, GOLD, decision=True)
    draw_box(draw, start)
    draw_box(draw, action)
    arrow(draw, start.bottom, action.top)

    revoke = [
        Box(90, 680, 420, 120, "撤销门控\n日报 / 学习 / 锁单"),
        Box(90, 900, 420, 120, "状态、支付方式、角色条件"),
        Box(90, 1120, 420, 120, "首次 getOrderRefundStep"),
        Box(90, 1340, 420, 120, "二次确认弹窗"),
        Box(90, 1560, 420, 120, "再次 getOrderRefundStep"),
        Box(90, 1780, 420, 120, "revokeOrder"),
        Box(90, 2000, 420, 120, "9 已撤销", LIGHT, BORDER),
    ]
    refund = [
        Box(640, 680, 420, 120, "退款组件 / 申请页"),
        Box(640, 980, 420, 120, "退款后端流程"),
        Box(640, 1280, 420, 120, "12 已退款", LIGHT, BORDER),
    ]
    correction = [
        Box(1190, 680, 420, 120, "日报 / 学习 / 锁单\n+ 退款步骤"),
        Box(1190, 980, 420, 120, "查询施工汇总"),
        Box(1190, 1280, 420, 120, "存在施工时风险提示"),
        Box(1190, 1580, 420, 120, "进入 createOrder 纠错"),
        Box(1190, 1880, 420, 120, "correctionOrder"),
        Box(1190, 2100, 420, 120, "11 错误订单", RED_FILL, RED),
    ]
    for column in (revoke, refund, correction):
        for item in column:
            draw_box(draw, item)
        for current, nxt in zip(column, column[1:]):
            arrow(draw, current.bottom, nxt.top)
    arrow(draw, action.left, revoke[0].top, "撤销", bend=(300, 560))
    arrow(draw, action.bottom, refund[0].top, "退款")
    arrow(draw, action.right, correction[0].top, "标记错误", bend=(1400, 560))

    blocked = Box(535, 1560, 510, 130, "退款已发起:禁止撤销\n联系总部运营", RED_FILL, RED)
    draw_box(draw, blocked)
    arrow(draw, revoke[2].right, blocked.left, "Y")
    arrow(draw, revoke[4].right, blocked.left, "Y")
    save(image, "cancel-refund-correction.png")


def render_construction() -> None:
    image, draw = new_canvas(1700, 2700, "施工单创建与商品级履约")
    boxes = [
        Box(560, 130, 580, 110, "已支付工单 → showFlag=1"),
        Box(560, 310, 580, 120, "逐商品选择施工 / 不施工"),
        Box(560, 500, 580, 160, "存在施工商品?", GOLD_FILL, GOLD, decision=True),
        Box(560, 760, 580, 120, "创建施工单:商品 + 主技师 + 服务项目"),
        Box(560, 950, 580, 120, "待领单 innerStatus=0"),
        Box(560, 1140, 580, 120, "addOrUpdate 确认技师/商品/服务"),
        Box(560, 1330, 580, 120, "商品待出库 subItemStatus=0"),
        Box(560, 1520, 580, 120, "扫码或手工出库 outbound"),
        Box(560, 1710, 580, 120, "商品待完工 subItemStatus=1"),
        Box(560, 1900, 580, 120, "1-9张施工图 + 起止时间"),
        Box(560, 2090, 580, 120, "complete → 商品已施工 status=2"),
        Box(560, 2280, 580, 160, "全部商品完工?", GOLD_FILL, GOLD, decision=True),
    ]
    for item in boxes:
        draw_box(draw, item)
    for current, nxt in zip(boxes, boxes[1:]):
        arrow(draw, current.bottom, nxt.top)

    no_construction = Box(80, 730, 360, 150, "全部不施工\nbatchAdd 登记关系", LIGHT, BORDER)
    partial = Box(80, 2480, 520, 130, "否:部分施工 / 部分完工", GOLD_FILL, GOLD)
    complete = Box(720, 2480, 520, 130, "是:已施工 / 已完工", GREEN_FILL, GREEN)
    rework = Box(1300, 2200, 330, 190, "返工\nrework 创建新单\n原商品标记已返工", RED_FILL, RED, font_size=28)
    for item in (no_construction, partial, complete, rework):
        draw_box(draw, item)
    arrow(draw, boxes[2].left, no_construction.right, "否")
    arrow(draw, boxes[-1].left, partial.top, "否", bend=(340, 2400))
    arrow(draw, boxes[-1].bottom, complete.top, "是")
    arrow(draw, complete.right, rework.bottom, "客户返工", bend=(1470, 2580))
    arrow(draw, rework.top, boxes[4].right, "新返工单重走")
    save(image, "construction-lifecycle.png")


def main() -> int:
    if not FONT_REGULAR.exists() or not FONT_BOLD.exists():
        raise SystemExit("Microsoft YaHei fonts are required")
    render_end_to_end()
    render_state_machine()
    render_submission()
    render_cancel_refund()
    render_construction()
    return 0


if __name__ == "__main__":
    raise SystemExit(main())