Files
cowork-local/core/xlsx_write.py
T
anhtnm1andClaude Opus 5 e29a0ccdbd refactor: vá 4 hồi quy, tách 4 file chạm trần LOC, docstring lên 100%
Hồi quy đã vá
-------------
F-12  Kéo–thả hoặc dán tệp vào ô chat ném NameError. R08 tách `_Input` sang
      `chat_input_box.py` nhưng để `_paths_from_mime()` ở lại
      `composer_widget.py`, nên hai hàm sự kiện Qt gọi một cái tên không tồn
      tại. Bốn hàm dùng chung chuyển sang `composer_mime.py` — module thứ ba
      là chỗ duy nhất không lặp lại được lỗi này. Đo lại: cả thả lẫn dán đều
      gắn 1 tệp, khớp bản trước refactor.

F-01  Đổi provider thì bộ chọn model AI-Edit không làm gì. Hook cũ kiểm
      `folder.ai_model_combo`, thuộc tính R08-T12 đã dời sang
      `ai_panel.resolver`. Làm mới vô điều kiện, đúng như tab cũ: lần lấy đầu
      tiên hỏng thì đổi provider chính là lúc phải thử lại.

F-07  Hàng chọn kỳ của Dashboard bị đẩy xuống dưới các thẻ số liệu. Hàng này
      lọc CẢ BA thẻ con chứ không riêng biểu đồ, nên để nó nằm dưới là bắt
      người dùng đọc con số trước khi thấy con số đó tính cho kỳ nào. Kèm
      theo: `TokenUsageCardWidget` bị bỏ sót `setContentsMargins(0,0,0,0)`
      mà hai thẻ con còn lại đã có, đẩy cả hàng thẻ lệch 9px.
      `check_layout_geometry` nay khớp TỪNG BYTE với bản trước refactor.

F-11  Hai lớp khai trùng tên phương thức; Python giữ bản sau nên bản đầu là
      mã chết. `co4e_tab.py::showEvent` bản đầu gọi `_narrow_guard.attach()`
      và không bao giờ chạy.

Tách file (F-09)
----------------
Bốn file chạm trần 400 dòng, mỗi lần cắt ra một trách nhiệm thật:

    graph_renderer.py         -> graph_scene_builder.py + graph_export.py
    co4e_workflow_service.py  -> co4e_run_history.py
    json_config_repository.py -> config_sections.py
    agents_admin_tab.py       -> shared/agent_kind_visuals.py

File cuối còn xoá 3 bản sao của hàm đã có trong `shared/formatters.py`,
giống hệt đến từng dòng — nay định dạng thời gian và avatar không lệch nhau
giữa các bảng Giám sát nữa.

Docstring
---------
41,6% -> 100% (3.478/3.478 định nghĩa production), kể cả module dormant và
phương thức dunder. Toàn bộ phần bổ sung viết bằng tiếng Việt; comment tiếng
Anh có sẵn giữ nguyên — dịch ngược là một đợt riêng.

Seam chưa nối dây (F-05)
------------------------
9 seam mang nhãn `SEAM · dựng <ngày>` kèm hai câu: được nối khi nào, và để
dormant thì hỏng gì. Ngày lấy từ lịch sử git, không phải hạn tự đặt. Gate O
đọc nhãn đó và nhắc khi quá 30 ngày.

859 test xanh · 4/4 cổng CASAN · 19/24 checker khớp từng byte bản cũ.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-30 10:41:45 +09:00

100 lines
3.9 KiB
Python

"""Build a REAL .xlsx from text content so an agent can CREATE Excel by calling
save_file/write_file('report.xlsx', <table text>).
A .xlsx is a binary ZIP package — writing the model's text straight to a .xlsx
corrupts it (the file won't open). This turns the content the model produces
(CSV / TSV / a Markdown table / JSON rows) into a genuine workbook via openpyxl
(already a dependency). Pure logic (no Qt) → unit-testable.
"""
from __future__ import annotations
import csv
import io
import json
from pathlib import Path
from typing import List
def _openpyxl():
"""Import openpyxl, auto-installing it on first use if it isn't present —
same self-healing path the Excel VIEWER and doc_style_extract use
(``deps.ensure_module``). openpyxl is a declared dependency, so this only
matters for a from-source run whose venv is missing it; a normal install /
frozen build already bundles it. Returns the module or None."""
try:
from .deps import ensure_module
return ensure_module("openpyxl", "openpyxl")
except Exception: # noqa: BLE001 - fall back to a plain import
try:
import openpyxl # noqa: F401
return openpyxl
except Exception: # noqa: BLE001
return None
def is_available() -> bool:
"""Máy đã cài ``openpyxl`` chưa — không có thì mọi tính năng Excel tắt."""
return _openpyxl() is not None
def _rows_from_text(content: str) -> List[list]:
"""Parse table content into a list of rows. Accepts JSON (list-of-lists or
list-of-dicts), a Markdown table, or CSV/TSV (delimiter sniffed)."""
content = content or ""
s = content.strip()
# JSON: [[...],[...]] or [{...},{...}] or {"rows"/"data": [...]}
if s[:1] in ("[", "{"):
try:
data = json.loads(s)
if isinstance(data, dict):
data = data.get("rows") or data.get("data") or [data]
rows: List[list] = []
if isinstance(data, list):
if data and isinstance(data[0], dict):
headers = list(dict.fromkeys(k for d in data if isinstance(d, dict) for k in d))
rows.append(headers)
for d in data:
rows.append([d.get(h, "") for h in headers] if isinstance(d, dict) else [d])
else:
for r in data:
rows.append(list(r) if isinstance(r, (list, tuple)) else [r])
if rows:
return rows
except (ValueError, TypeError):
pass
lines = [ln for ln in content.splitlines() if ln.strip()]
# Markdown table: rows delimited by '|', a --- separator row skipped.
if lines and lines[0].lstrip().startswith("|"):
rows = []
for ln in lines:
body = ln.strip()
if set(body) <= set("|-: "): # separator row like |---|---|
continue
rows.append([c.strip() for c in body.strip("|").split("|")])
if rows:
return rows
# CSV / TSV — sniff which delimiter dominates.
delim = "\t" if content.count("\t") > content.count(",") else ","
return list(csv.reader(io.StringIO(content), delimiter=delim))
def build_xlsx_from_text(path, content: str) -> bool:
"""Write a genuine .xlsx at ``path`` from CSV/TSV/Markdown-table/JSON
``content``. Returns True on success, False if openpyxl is unavailable or the
write fails (caller can then fall back). Never raises."""
openpyxl = _openpyxl()
if openpyxl is None:
return False
try:
rows = _rows_from_text(content)
wb = openpyxl.Workbook()
ws = wb.active
for r in rows:
ws.append(["" if v is None else v for v in r])
p = Path(path)
p.parent.mkdir(parents=True, exist_ok=True)
wb.save(str(p))
return True
except Exception: # noqa: BLE001
return False