diff --git a/Design/DslDefinition/DslDefinition_v2.xsd b/Design/DslDefinition/DslDefinition_v2.xsd index a16f95e..10bd2b6 100644 --- a/Design/DslDefinition/DslDefinition_v2.xsd +++ b/Design/DslDefinition/DslDefinition_v2.xsd @@ -295,6 +295,7 @@ + @@ -313,6 +314,7 @@ + @@ -330,6 +332,13 @@ + + + + + + + diff --git a/Design/ExcelTemplate/ExcelTemplate_DetailDesign.md b/Design/ExcelTemplate/ExcelTemplate_DetailDesign.md new file mode 100644 index 0000000..5ad8ab0 --- /dev/null +++ b/Design/ExcelTemplate/ExcelTemplate_DetailDesign.md @@ -0,0 +1,768 @@ +# Excelテンプレート対応 詳細設計(Issue #58 / 実装方針レビュー版) + +- 作成日: 2026-04-07 +- ステータス: **実装方針レビュー中** +- 対象Issue: https://github.com/ssaattww/ExcelReport/issues/58 +- 設計対象: Excel形式テンプレートを DSL へ変換する機能(`Excel -> XML Template -> DSL`) + +## 1. Excelテンプレート対応で合意したいこと(要約) +Issue本文(2026-04-07作成)から、以下を設計対象とする。 + +1. Excelテンプレートを入力にして、最終的に現行DSL/生成パイプラインへ接続したい +2. デバッグ用途として「Excel -> XML Template -> DSL -> Excel」の中間可視化を持ちたい +3. 本番では中間XMLを省略し「Excel -> DSL(直接変換)」も可能にしたい +4. コンポーネント定義方式は次の2案を比較検討する + - A案: シート単位定義(特殊シート名) + - B案: 名前付き範囲定義(シート内で定義) + +## 2. 方針 +### 2.1 段階導入(破壊的変更なし) +- **Phase A (Debug Path)**: Excel -> XmlTemplate を実装し、変換内容を可視化 +- **Phase B (Production Path)**: Excel -> DSL 直接変換を追加 +- 既存の `DSL -> ReportGenerator` パイプラインは再利用し、既存API互換を維持する + +### 2.2 コンポーネント定義方式の採用(再検討) +ユーザー提案の A/B 案を前提にしつつ、追加で C 案を含めて比較した。 + +- **A案: シート単位定義(特殊シート名)** + - 利点: 実装コストが低く、抽出境界が明確、デバッグしやすい + - 欠点: シート数増加時に運用が冗長になる +- **B案: 名前付き範囲定義(シート内)** + - 利点: 既存Excel運用に近く、シートを増やさず定義可能 + - 欠点: 同名管理・ネスト・範囲衝突で実装複雑度が上がる +- **C案: セルコメント/メタ情報ベース定義(追加検討)** + - 利点: レイアウト自由度が高い + - 欠点: Excel編集で壊れやすく、規約逸脱検知が難しい + +**採用結論(初期リリース): A案** +- 採用理由: 「最小コストで安定導入」「変換ロジックの可観測性」「TDDで仕様固定しやすい」の3点で優位。 +- B/Cは将来拡張として残し、A案運用データを得てから再評価する。 + +## 3. 対象範囲 +### In Scope +- ExcelTemplate 入力モデルの追加 +- Excel -> XmlTemplate 変換器(デバッグ用途) +- Excel -> DSL 直接変換器(本番用途) +- シート単位コンポーネント抽出ルール +- 変換ログ(どのセル/範囲をどのDSL要素へ写像したか) +- 主要テスト(unit + e2e) + +### Out of Scope(今回) +- 名前付き範囲ベースのコンポーネント定義(B案本実装) +- セルコメント/メタ情報ベース定義(C案本実装) +- GUI/CLIツールの本格追加 +- 既存DSL構文の大幅拡張 +- **グラフ作成機能(chart生成/設定DSL拡張)は今回の対象外** + +## 4. アーキテクチャ設計 + +```text +[Excel Workbook] + | (Phase A) + v +[ExcelTemplateExtractor] -> [XmlTemplateSerializer] + | (Phase B bypass possible) + v +[DslEmitter] + v +[Existing DslParser/Layout/Renderer] + v +[Excel Output] +``` + +### 4.1 新規コンポーネント(案) +- `ExcelTemplate/ExcelTemplateExtractor` + - Excelブックを読み取り、シート/セル/スタイル/名前情報を中間モデル化 +- `ExcelTemplate/XmlTemplateSerializer` + - 中間モデルをXML templateとして出力(デバッグ向け) +- `ExcelTemplate/DslEmitter` + - 中間モデル(またはExcel直接)からDSL文字列へ変換 + +### 4.2 既存コンポーネントとの責務境界 +- 既存 `DSL` パーサ以降には変更を極力入れない +- 変換層(ExcelTemplate系)で解決できる仕様はそこで閉じる + +## 5. DSLマッピングルール(初版) +- シート名 `__component_` をコンポーネント定義シートとして扱う +- 通常シートは `` に変換 +- 値セルは `cell@value` へ変換 +- 数式セルは原則 `cell@formula` へ変換する +- C# 側で Excel 関数の計算を再実装することは本仕様の対象外とし、数式は計算済み値へ潰さず保持する +- 最小限のスタイル属性(font/fill/numberFormat)から段階対応 + +### 5.1 コンポーネント定義範囲(Range)の決定ルール +初版では、コンポーネント定義シート `__component_` ごとに、次の優先順位で定義範囲を決定する。 + +1. 明示範囲指定(最優先) + - Workbook DefinedName: `__component_range_` + - 例: `__component_range_GroupBlock` -> `__component_GroupBlock!$A$1:$C$3` +2. 自動判定(DefinedName未指定時) + - 候補セル: 値/数式/挿入トリガ/書式指定/結合セルに関与するセル + - 候補セルの最小外接矩形を定義範囲とする + - trailing側(右端/下端)の完全空行・完全空列はトリミングする + +補足: +- 定義範囲は必ず単一矩形とする(離散領域は不可)。 +- 明示範囲がシート名と不整合、または空矩形の場合は Error とする。 +- 自動判定で候補セルが0件の場合は Error(`EmptyComponentRange`)とする。 + +## 6. 失敗時ポリシー +- 未対応Excel要素を検出した場合: + - 変換を継続可能なら Warning として `ReportGeneratorResult.Issues` へ集約 + - 継続不能なら Error で停止 +- どのセルが未対応だったかを座標付きでログ出力 +- 追加ポリシー(範囲/挿入): + - 定義範囲が不正(空矩形/複数領域/シート不一致)の場合: Error(`InvalidComponentRange`) + - 挿入元展開で挿入先想定範囲を超過した場合: Warning(`TemplateRangeOverflow`, `deltaRows`/`deltaCols` を記録) + - 結合セルが挿入境界をまたいで破壊される場合: Error(`MergedCellBoundaryViolation`) + +## 7. テスト戦略(TDD) +1. Unit + - シート分類(通常/コンポーネント) + - セル値/数式/最小スタイルの抽出 + - DslEmitterの要素生成 +2. Integration + - Excel -> DSL 変換結果のスナップショット比較 +3. E2E + - Excel -> DSL -> ReportGenerator で最終Excel生成まで確認 + +## 8. 互換性 +- 既存公開APIは非変更 +- 既存DSL実行機能に影響なし +- 破壊的変更は現時点では想定しない + +## 9. 実装前の承認結果 +- [x] 比較検討結果(A/B/C)を踏まえ、初期実装は A案で進める +- [x] デバッグ経路(Excel -> XML Template)を同時に入れる +- [x] 初版マッピング対象は 値/数式/最小スタイル とする +- [x] グラフ作成機能は今回スコープ外とする +- [x] コンポーネント定義範囲は「DefinedName明示指定 + 自動判定フォールバック」の二段構成とする +- [x] サイズ不一致時は「クリップせず展開 + overflow Warning」とする +- [x] 挿入先書式は任意(mustではない)とし、3x3外枠+中央useのフレームは展開サイズへ追従拡張する +- [x] 挿入先書式のoverflow補完は `styleOverflow`(`none`/`edge`)で選択可能、既定 `none` とする +- [x] merged cell は初版では「矩形内完結のみ」とする +- [x] 条件付き書式は初版対象外とする +- [x] 数式セルは `cell@formula` へ正規化し、C# 側で Excel 関数計算を行わない +- [x] 大規模テンプレートの性能閾値は当面不問とし、必要時に別途基準化する + +--- + +## 10. 具体表現設計(入れ子コンポーネント / シート定義 / 挿入) + +### 10.1 コンポーネント定義シートの表し方 +- シート名規約: `__component_` +- 例: + - `__component_Header` + - `__component_ItemRow` + - `__component_GroupBlock` + +このシートのセル配置を、そのまま component のレイアウト定義へ変換する。 + +### 10.2 通常シート定義の表し方 +- コンポーネント定義シート以外は通常 `` として扱う。 +- 例: `Invoice` シートは DSL の `` へ変換。 + +### 10.3 コンポーネント挿入の表し方(use) +Excel側で次の記法を挿入トリガとして扱う(初版案): +- セル値: `{{use:Header}}` -> `` +- セル値: `{{use:Header, styleOverflow:edge}}` -> `` +- セル値: `{{use:ItemRow, from:@items, var:item, styleOverflow:edge}}` -> `` + +> 注: 文字列トリガ構文は初版の暫定仕様。将来は名前付き範囲等への置換余地あり。 +> 注: Excel側の shorthand expression(例: `@items`, `@group.Items`, `@item.Name`)は converter が emitted DSL 上で `@(root.Items)`, `@(group.Items)`, `@(item.Name)` へ正規化する。 + +### 10.4 入れ子コンポーネント定義の例 + +#### Excelテンプレート(概念) +- `__component_Header`: タイトル行 +- `__component_ItemRow`: 明細1行(品名/数量/単価) +- `__component_GroupBlock`: 見出し + `{{use:ItemRow, from:@group.Items, var:item}}` を含む +- `Invoice`: `{{use:Header}}` の下に `{{use:GroupBlock, from:@groups, var:group}}` + +#### 変換後 DSL 例(設計イメージ) +```xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +``` + +### 10.5 挿入時の座標ルール(初版) +- `use` は「トリガセル位置」を挿入起点にする。 +- component の高さ/幅ぶん展開し、後続行は下方へシフト(既存 LayoutEngine 規約に追従)。 +- `repeat + use` は反復ごとに順次展開する。 + +### 10.6 検証観点(例ベース) +- 入れ子 repeat/use で scope (`group` / `item`) が衝突しないこと +- `sheet` 直下と component 内で同名 var を使っても期待通りに解決されること +- 展開後のセル位置が連続し、欠落・重複がないこと + + +### 10.7 セル値の具体例(Markdownテーブル) + +#### 10.7.1 セル値トリガ -> DSL 変換例 +| Excelセル値(例) | 意味 | 変換後DSL(例) | 備考 | +|---|---|---|---| +| `請求書` | 固定文字列 | `` | そのまま値セル | +| `@item.Name` | 式評価値 | `` | converter が DSL runtime 互換形へ正規化 | +| `{{use:Header}}` | コンポーネント挿入 | `` | 挿入トリガ | +| `{{use:ItemRow, from:@items, var:item, styleOverflow:edge}}` | 反復+挿入 | `` | repeat展開 + styleOverflow | +| `=SUM(B2:B10)` | Excel数式 | `` | `cell@formula` で保持 | + +#### 10.7.2 入れ子構成のセル配置イメージ(Excel側) +| シート | セル | 入力値 | 役割 | +|---|---|---|---| +| `__component_Header` | `A1` | `請求書` | ヘッダー定義 | +| `__component_GroupBlock` | `A1` | `@group.Name` | グループ見出し | +| `__component_GroupBlock` | `A2` | `{{use:ItemRow, from:@group.Items, var:item}}` | 子component反復挿入 | +| `Invoice` | `A1` | `{{use:Header}}` | 先頭ヘッダー挿入 | +| `Invoice` | `A3` | `{{use:GroupBlock, from:@groups, var:group}}` | グループ単位で入れ子展開 | + +#### 10.7.3 罫線の競合が起こるセル例 +| 位置 | 親component指定 | 子component指定 | 解決結果 | +|---|---|---|---| +| `Invoice!A10` の bottom | `thin` | `dashed` | 子優先で `dashed`(Warning記録) | +| `Invoice!B10` の right | `medium` | 未指定 | 親の `medium` を継承 | +| `Invoice!C10` の top | 未指定 | `thin` | 子の `thin` を採用 | +| `Invoice!D10` の left | `thin` | `thin` | 同値のためWarningなし | + + +### 10.8 Excelセル座標と一致する表現(セルマトリクス) + +#### 10.8.1 挿入先シート(入力テンプレート) +| Row\Col | A | B | C | +|---|---|---|---| +| 1 | `{{use:Header}}` | | | +| 2 | | | | +| 3 | | | | +| 4 | | `{{use:GroupBlock, from:@groups, var:group}}` | | +| 5 | | | | + +#### 10.8.2 挿入元 `__component_GroupBlock` シート(3x3、入力テンプレート) +| Row\Col | A | B | C | +|---|---|---|---| +| 1 | `@group.Name` | | | +| 2 | `{{use:ItemRow, from:@group.Items, var:item}}` | | | +| 3 | | | | + +#### 10.8.3 挿入先セル値のSVG(表示値ベース) +![Insert target cell values](assets/insert-target-cell-values.svg) + +注記: +- `use` セル周辺に描かれている罫線は「テンプレートで定義されている場合の例」であり、必須要件ではない。 +- 挿入先書式が未定義でも `use` 展開は有効で、最終書式は 10.9/11章のルールで決定する。 + +#### 10.8.4 挿入元セル値のSVG(表示値ベース) +![Insert source cell values](assets/insert-source-cell-values.svg) + +注: +- 10.8.3/10.8.4 のSVGは、実運用のExcelTemplate見た目に合わせるため、説明用の背景色強調は行わない。 +- 挿入アンカーや有効範囲の意味づけは本文・表で説明し、セル塗り分けには反映しない。 +- ただしテンプレートで事前定義する罫線(実線/破線)は、入力側SVGにも反映する。 +- 本節の `GroupBlock` 定義範囲は `A1:C3` を採用する。周辺グリッドはシート表示であり、component 有効幅には含めない。 + +#### 10.8.5 書式説明(Markdownテーブル) +| 範囲/セル | 意味 | 備考 | +|---|---|---| +| 挿入先 `A3:C5` | 3x3 の親フレーム | 中央 `B4` が `use` アンカー | +| 挿入先 `A1` | `{{use:Header}}` | ヘッダー挿入トリガ | +| 挿入先 `A1:C1` | 例: 挿入先上辺の書式シード | 必須ではない(未設定でも展開可) | +| 挿入元 `A1:C3` | `GroupBlock` の定義範囲 | 行3列3。`repeat` 展開後の高さは item 件数で増加 | +| 挿入元 `A1` | `@group.Name` | グループ見出し | +| 挿入元 `A2` | `{{use:ItemRow, from:@group.Items, var:item}}` | 子コンポーネント挿入 | + +使用データ(C# class 定義): +`repeat + use` で挿入されるデータモデルは、初版の設計例として以下を基準にする。 + +```csharp +public sealed class InvoiceData +{ + public string Title { get; init; } = string.Empty; + public IReadOnlyList Groups { get; init; } = Array.Empty(); +} + +public sealed class GroupData +{ + public string Name { get; init; } = string.Empty; + public IReadOnlyList Items { get; init; } = Array.Empty(); +} + +public sealed class ItemData +{ + public string Name { get; init; } = string.Empty; + public int Qty { get; init; } + public decimal Price { get; init; } +} +``` + +サンプル入力(C#): +```csharp +var data = new InvoiceData +{ + Title = "請求書", + Groups = + [ + new GroupData + { + Name = "機械部品", + Items = + [ + new ItemData { Name = "Bolt", Qty = 12, Price = 35m }, + new ItemData { Name = "Nut", Qty = 12, Price = 18m }, + new ItemData { Name = "Washer", Qty = 12, Price = 9m } + ] + }, + new GroupData + { + Name = "電材", + Items = [ new ItemData { Name = "Cable", Qty = 3, Price = 980m } ] + } + ] +}; +``` + +#### 10.8.8 C#データ展開後の挿入元(`GroupBlock` インスタンス)SVG +以下は本節のサンプルデータを `GroupBlock` 単位へ展開したときの、挿入元インスタンスの表示値イメージである。 + +![Expanded insert source from C# data](assets/expanded-insert-source-from-csharp.svg) + +#### 10.8.9 C#データ展開後セル値のSVG(`Invoice` 出力イメージ) +以下は本節のサンプルデータを `Invoice` シートへ挿入した出力イメージである。`Header` は `A1:F1` へ拡張し、`A3:C5` の 3x3 親フレームは `@groups` の連続展開結果をまとめて囲むため、最終的に `A3:E10` へ拡張される。`GroupBlock` 実体は 1件目が `B4:D7`、2件目が `B8:D9` に配置される。 + +![Expanded cell values from C# data](assets/expanded-cell-values-from-csharp.svg) + +#### 10.8.10 Header拡張と3x3中央useの状態整理 +| 項目 | 入力(テンプレート) | 出力(展開後) | +|---|---|---| +| Header | `A1:C1` に `{{use:Header}}`、`styleOverflow=edge` | `A1:F1` まで外枠を拡張 | +| GroupBlock repeat | `A3:C5` 外枠、中央 `B4` に `{{use:GroupBlock,...}}` | 親外枠は連続展開全体をまとめて `A3:E10` へ拡張する | +| 1件目 GroupBlock | `repeat` の1件目 | `B4:D7` が挿入元実体。外周のみ罫線を持ち、`B7:D7` のみ下破線 | +| 2件目 GroupBlock | `repeat` の2件目 | `B8:D9` が挿入元実体。上辺は 1件目の `B7:D7` を共有境界として使い、自身は `B9:D9` の下破線を持つ | +| 子データ列 | 値が2列でも可 | 有効幅 `W=3`(値2列+書式1列)なら外枠幅は `W+2=5` 列(`A:E`) | + +注: +- もし子の有効幅が本当に `W=2` なら、展開後外枠は `A3:D10`(4列)になる。 +- 「2列の値」と「コンポーネント有効幅」は同義ではない。幅判定は 10.10 の定義範囲で決まる。 + +### 10.9 サイズ不一致時の挿入ルール(挿入元 > 挿入先想定範囲) +「挿入元 component が複数行/複数列」「挿入先 component / sheet 側の想定定義範囲が小さい」のようなサイズ不一致を、行・列の両方向で明示的に扱う。 + +1. 挿入先の事前定義範囲は **クリップ境界ではなくアンカー情報** とみなす。 +2. 挿入先の書式指定は **任意**(mustではない)。 + - 書式未指定でも `use` 展開は有効。 + - 書式指定がある場合のみ、11章の合成ルールで最終書式を決定する。 +3. `use` は挿入元 component の実サイズ(高さ/幅)まで必ず展開し、途中で切り詰めない。 +4. 挿入先の事前定義範囲を超えたセル(overflow行/overflow列)は、挿入元 component 側の書式決定ルール(11章)をそのまま適用する。 +5. overflow により既存セルが押し下げ/押し広げされる場合、既存セル値・既存書式・結合状態は相対位置を保ってシフトする。 +6. 挿入先想定範囲より大きい展開が発生した場合、`Warning`(種別: `TemplateRangeOverflow`)を記録し、座標/シート名/挿入元component名/`deltaRows`/`deltaCols` を出力する。 +7. 結合セルが挿入境界をまたいで壊れる場合は `Error` とし、当該挿入を停止する(自動補正しない)。 + +#### 10.9.1 挿入先外枠の追従拡張ルール(3x3 + 中央useケース) +挿入先側で `use` を囲む外枠(例: 3x3範囲の外枠 + 中央セルが `use`)を定義している場合、展開後は次で外枠を再計算する。 + +- 前提: + - 初期外枠矩形を `R0` + - `use` アンカーセルを `A` + - `R0` 内でのアンカー余白を `topMargin/bottomMargin/leftMargin/rightMargin` + - 挿入元展開サイズを `H x W` + - `repeat` を含む場合の `H/W` は、`use` 起点で fully expand された結果全体の外接矩形サイズとする +- 展開後外枠: + - `rowStart = A.row - topMargin` + - `rowEnd = A.row + (H - 1) + bottomMargin` + - `colStart = A.col - leftMargin` + - `colEnd = A.col + (W - 1) + rightMargin` +- 結果: + - 3x3で中央use(四辺余白=1)の場合、子component展開範囲を四辺1セルぶん拡張した外枠になる。 + - 行方向だけでなく列方向にも同じルールを適用する。 + - `repeat` が縦方向に 2 件連続展開される場合、`H` は各インスタンス高の合計、`W` はインスタンス幅の最大値とする。 + - 本節の `GroupBlock` 例では `H=6`、`W=3` なので、`A3:C5` の親フレームは `A3:E10` へ拡張される。 + - 現行の `use` 展開はアンカー起点で右方向 / 下方向へ成長するモデルとし、left/up 側の負方向 overflow は発生させない。 + +#### 10.9.2 挿入先書式の overflow 拡張ポリシー(`styleOverflow`) +「挿入先で定義した書式を、子展開で増えた領域にも伸ばすか」を `use` 単位で選択可能にする。 + +- 追加属性(`use`): + - `styleOverflow="none|edge"` + - 既定値は `none`(後方互換優先) +- 例: + +```xml + + + + + + +``` + +- モード定義: + - `none`: 挿入先書式は拡張しない。増分領域は挿入元コンポーネント側書式のみで決定する。 + - `edge`: 増分領域に対し、現行レイアウトモデルで実際に増える trailing edge(右辺 / 下辺)を基準に書式をコピーする。 + +- `edge` の決定ルール: + 1. 右方向に `deltaCols > 0` の場合、右辺基準列 `baseCol = originalColEnd` を取る。 + 2. 下方向に `deltaRows > 0` の場合、下辺基準行 `baseRow = originalRowEnd` を取る。 + 3. 右辺 / 下辺の辺拡張では、基準辺セルに書式がある場合のみ、増分領域へ同一書式をコピーする。 + 4. 右下角領域が同時に増える場合、元範囲の右下角セルを書式基準にする。 + 5. 基準辺または基準角が未設定なら、その行 / 列 / 角にはコピーしない。 + 6. コピー後も競合は 11章ルール(辺単位優先順位)で解決する。 + 7. left / up 側の負方向 overflow は現行 `use` レイアウトモデルでは発生しないため、本版の対象外とする。 + +- 3x3 + 中央`use` + 4列子component overflow ケースの具体化: + - `A1:C1` が書式設定され、`styleOverflow=edge` の場合: `D1` へ拡張される。 + - `A1:C1` が書式設定され、`styleOverflow=none` の場合: `D1` へは拡張されない。 + - `A1:B1` のみ書式設定され、`styleOverflow=edge` の場合: 右辺基準 `C1` が未設定のため `D1` は拡張されない。 + - 同じ考え方で、`A3:A5` が書式設定され、下方向に `deltaRows > 0` の場合は `A6` 以降へ下辺基準で拡張する。 + +#### 10.9.3 書式 overflow のSVG比較(3x3 -> 4列子component) +![Style overflow modes](assets/style-overflow-modes-3x3.svg) + +#### 10.9.4 書式 overflow の期待結果(Markdownテーブル) +| ケース | 入力書式シード | 設定 | 増分方向 | 期待結果 | +|---|---|---|---|---| +| Case 1 | `A1:C1` | `styleOverflow=none` | 右 | `D1` へは拡張しない(未設定) | +| Case 2 | `A1:C1` | `styleOverflow=edge` | 右 | `C1` を基準に `D1` へ拡張する | +| Case 3 | `A1:B1` | `styleOverflow=edge` | 右 | `C1` が未設定なので `D1` へは拡張しない | +| Case 4 | `A3:A5` | `styleOverflow=edge` | 下 | `A5` を基準に `A6` 以降へ拡張する | +| Case 5 | `B2:D4` | `styleOverflow=edge` | 右下角 | 元範囲の右下角 `D4` を基準に角領域へ拡張する | + +補足: +- `A1` は `Header` component 由来の固定値(`請求書`)。 +- left / up 側の負方向 overflow は、現行 `use` 展開モデルでは対象外である。 +- 10.8.9 のSVGでは、`@groups` の2件を連続展開した結果を示す。 +- SVGの線種は 11章ルールに対応する。 + - 実線: 親component外枠、または挿入元実体の top/left/right + - 破線: 挿入元実体の bottom + +### 10.10 コンポーネント定義範囲の具体例 +#### 10.10.1 明示範囲指定 +- 定義名: `__component_range_GroupBlock` +- 参照先: `__component_GroupBlock!$A$1:$C$3` +- 挙動: この矩形外のセルはコンポーネント抽出対象外とする。 + +#### 10.10.2 自動判定時 +- 候補セルが `A1`(`@group.Name`)と `A2`(`{{use:ItemRow,...}}`)のみの場合: + - 初期矩形: `A1:A2` + - 書式指定が `C3` に存在する場合: + - 拡張矩形: `A1:C3` +- この最終矩形を component 展開サイズ(高さ/幅)の基準とする。 + +#### 10.10.3 バリデーション +| チェック項目 | 判定 | 失敗時 | +|---|---|---| +| DefinedName の参照先が対象シートか | 必須 | `InvalidComponentRange` Error | +| 範囲が単一矩形か | 必須 | `InvalidComponentRange` Error | +| 範囲内に有効セルが1つ以上あるか | 必須 | `EmptyComponentRange` Error | +| 自動判定で overflow が発生したか | 任意記録 | `TemplateRangeOverflow` Warning | + + +## 11. セル書式方針(特に罫線) + +### 11.1 基本方針 +- 値/数式だけでなく、セル書式(font/fill/numberFormat/border)も抽出対象にする。 +- ただし初期段階では「既存StyleResolver/Rendererの表現可能範囲」に正規化して取り込む。 + +### 11.2 罫線の取り扱い原則 +入れ子 component 展開時の見た目崩れを防ぐため、次の優先順位で罫線を決定する。 + +1. **セル直指定罫線(最優先)** +2. **component 内ローカル既定罫線** +3. **sheet 側既定罫線(最下位)** + +補足: +- 罫線は辺単位(top/right/bottom/left)で合成し、未指定辺のみ下位ルールから補完する。 +- 競合時(同じ辺に異なる指定)は上位優先とし、Warning を記録する。 + +### 11.3 入れ子時の罫線ルール +- 親componentと子componentの境界で、同一辺が二重定義された場合は「子component優先」。 +- `repeat + use` で連続展開される行境界は、各行の bottom/top を辺単位で解決する。 +- 列方向の境界(left/right)も同様に辺単位で解決する。 +- 同一 `repeat` から生成された sibling instance 同士が連続配置される場合、共有境界は1本だけ描画する。 +- 縦方向 repeat の共有境界では、先行 instance の `bottom` を採用し、後続 instance の `top` は重ね描きしない。 +- 横方向 repeat の共有境界では、先行 instance の `right` を採用し、後続 instance の `left` は重ね描きしない。 +- 共有境界で同優先度・異値の罫線が衝突した場合は「先行 instance の trailing edge 優先」とし、Warning を記録する。 +- 外枠を親で管理し、内側明細線を子で管理する設計を推奨。 +- 挿入先に外枠(フレーム)を定義する場合は 10.9.1 の追従拡張ルールで再配置する。 + +### 11.4 具体例(罫線) + +#### 設計推奨パターン +- `GroupBlock`(親): 外枠(top/left/right/bottom) +- `ItemRow`(子): 明細行の下罫線(bottom) + +このとき: +- 最終行以外: `ItemRow.bottom` が有効 +- グループ末尾: 親 `GroupBlock.bottom` と子 `ItemRow.bottom` が競合しうるため、子優先で解決し Warning を記録 +- `GroupBlock` が repeat で縦連結される場合: 先行 block の `bottom` を共有境界へ採用し、後続 block の `top` は描画しない + +### 11.5 検証ケース(実装前にテスト化予定) +1. 親外枠 + 子内罫線の組み合わせが期待どおり描画される +2. 入れ子 + repeat 展開で行境界の二重線/線欠けが発生しない +3. 競合辺がある場合に Warning が `ReportGeneratorResult.Issues` に記録される +4. 既存 border mode(outer/all)との互換が維持される +5. 挿入元高さ > 挿入先想定行数(例: 3行 component を 1行定義領域へ挿入)でも、overflow行の書式が欠落しない +6. 挿入元幅 > 挿入先想定列数でも、overflow列の書式が欠落しない +7. 3x3外枠 + 中央use のテンプレートで、展開後に外枠が「子範囲+余白」で追従拡張される +8. overflow 発生時に `TemplateRangeOverflow` Warning が座標 + `deltaRows` + `deltaCols` 付きで記録される +9. `styleOverflow=none` で `A1:C1` 書式が `D1` へ拡張されない +10. `styleOverflow=edge` で `A1:C1` 書式が `D1` へ拡張される +11. `styleOverflow=edge` かつ `A1:B1` のみ書式時、`C1` 未設定のため `D1` へ拡張されない +12. `styleOverflow=edge` で下方向に `deltaRows > 0` が発生した場合、下辺基準で overflow 行へ書式が拡張される +13. `styleOverflow=edge` で右下角領域が増える場合、元範囲の右下角セルを基準に corner copy される +14. 同一 `repeat` の連続 instance 境界で、先行 instance の trailing edge が共有境界として1本だけ描画される + +### 11.6 リスクと緩和策 +- リスク: Excel側の自由入力で罫線指定が過剰に衝突する + - 緩和: 競合Warningを必須化し、座標/辺情報付きでログ化 +- リスク: 入れ子深度が増えると見た目把握が難しい + - 緩和: デバッグ経路(Excel -> XmlTemplate)で罫線解決結果を可視化する + +### 11.7 非罫線書式(font/fill/numberFormat)の合成方針 +- 挿入元 component のセルが明示指定する属性は、そのまま採用する(最優先)。 +- 明示指定がない属性は `component ローカル既定 -> sheet 既定` の順で補完する。 +- `styleOverflow=none` の場合、挿入先の事前定義範囲にのみ存在する書式を overflow 行/列へ暗黙コピーしない。 +- `styleOverflow=edge` の場合、10.9.2 の辺基準ルールに従い overflow 行/列へコピーする。 +- ただし既存行を押し下げる際は、押し下げ対象セルの既存書式を保持する(破壊しない)。 + + +## 12. 実装前に詰めるべき懸念点(事前合意チェックリスト) + +以下は、実装前に合意しないと後戻りコストが高い項目。 + +### 12.1 変換契約の厳密化 +| 懸念点 | 未合意時のリスク | 事前合意内容 | +|---|---|---| +| 数式セルの正規化方式(`cell@formula` vs `cell@value`) | 実装途中でDSL互換崩れ | 初版は `cell@formula` で統一する。C# 側で Excel 関数計算は行わず、計算済み値へ潰さない | +| 空セル/空白セルの扱い | 余計なセル生成、座標ずれ | 値/数式/書式/結合/useトリガのいずれもない空セルは非出力とする。空白文字列は値セルとして出力し、`styleOverflow` の種になる書式-onlyセルは保持する | +| 日付/数値の型解釈 | Excel表示とDSL評価の乖離 | まずは生値+numberFormatで保持し、型推論は段階導入 | + +### 12.2 レイアウト展開の境界条件 +| 懸念点 | 未合意時のリスク | 事前合意内容 | +|---|---|---| +| `use` 展開時の行/列シフト | component重なり/欠落 | 「トリガセル起点 + 高さ/幅ぶんシフト」を固定ルール化 | +| 入れ子 `repeat + use` の展開順 | varスコープ衝突 | 親repeat1回ごとに子を完全展開する深さ優先 | +| 挿入元サイズ > 挿入先想定範囲(行/列) | 書式欠落/罫線崩れ/既存セル上書き | 挿入先範囲はクリップしない。overflow行/列まで展開し、後続セルを相対シフト。`TemplateRangeOverflow` Warning必須 | +| 挿入先フレーム(外枠)の追従 | 外枠が狭いまま/拡張過剰 | 10.9.1 の余白保持ルール(子範囲+余白)で外枠を再計算 | +| merged cell 含有component | 結合領域崩れ | 初版は制限付き対応(矩形内完結のみ)で進める | + +### 12.3 書式・罫線の実装リスク +| 懸念点 | 未合意時のリスク | 事前合意内容 | +|---|---|---| +| 挿入先書式の有無 | 「書式なしuseが無効」と誤解 | 挿入先書式は任意。未指定でも展開可、指定時のみ合成 | +| 罫線競合時の採用規則 | 見た目不一致 | 既定ルール(子優先/辺単位/Warning)を固定 | +| 非罫線書式のoverflow補完 | 色/フォント/表示形式の不整合 | `styleOverflow` を `none`/`edge` で明示選択し、既定は `none`。`edge` 時のみ辺基準で補完する | +| Style重複生成 | ファイル肥大/性能低下 | StyleKeyで重複排除し、同一スタイル再利用 | +| 条件付き書式との干渉 | 想定外の上書き | 初版は条件付き書式を非対象として進める | + +### 12.4 運用・性能 +| 懸念点 | 未合意時のリスク | 事前合意内容 | +|---|---|---| +| 大規模テンプレート(数万セル) | 変換時間増大 | 当面は性能閾値を設けず不問とする。Phase A では計測ログのみ必須とし、必要になった時点で別途基準化する | +| 失敗時の原因追跡 | 調査コスト増 | セル座標 + シート名 + 変換段階を必ず記録 | +| 仕様逸脱テンプレート入力 | 実行時クラッシュ | Validateフェーズを設け、Error/Warningを事前集約 | + +### 12.5 今回の事前合意ゴール +- 実装開始条件として、上記表の「事前合意内容」を受け入れ条件に組み込む。 +- 合意できない項目は実装スコープから除外し、設計書へ明示する。 + +### 12.6 実装前レビューで確認する質問 +- 現時点で未解決の確認質問はない。追加の懸念が出た場合は本節へ追記する。 + +## 13. 実装方針 + +### 13.1 基本方針 +- 既存の `ReportGenerator -> DslParser -> LayoutEngine -> WorksheetStateBuilder -> XlsxRenderer` は後段の安定基盤として再利用する。 +- `ExcelTemplate` 対応は前段に追加し、Excelブックを DSL へ変換した上で既存パイプラインへ流す。 +- 初版は additive change を優先し、既存の DSL 実行 API は壊さない。 +- 実装は「DSL契約の不足補完」と「ExcelTemplate変換層の追加」を分離して進める。 + +### 13.2 既存実装との差分整理 +現行コードを前提にすると、設計を実現するには次の差分がある。 + +1. `ExcelTemplate` 変換層がまだ存在しない + - `ExcelTemplateExtractor` / `XmlTemplateSerializer` / `DslEmitter` / facade API は未実装 +2. `cell@formula` 契約が DSL/XSD/AST に未反映 + - 現行実装は `cell@value=\"=...\"` を数式扱いしているため、`cell@formula` を受ける拡張が必要 +3. `use@styleOverflow` 契約が DSL/XSD/AST/LayoutEngine に未反映 + - 右/下 trailing edge 拡張ルールを runtime へ追加する必要がある +4. ExcelTemplate 固有の validation / issue 種別が未実装 + - `InvalidComponentRange` / `EmptyComponentRange` / `TemplateRangeOverflow` / `MergedCellBoundaryViolation` など +5. `repeat` は `direction` 必須のため、converter 側で明示出力する必要がある + - 初版の ExcelTemplate 由来 repeat は `direction="down"` を必ず出力する + +### 13.3 実装単位 +初版は次の単位で実装する。 + +1. DSL契約拡張 + - `Design/DslDefinition/DslDefinition_v2.xsd` + - `ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd` + - `DslContract` の埋め込み schema 読み込み経路 + - `CellAst` に `formula` 対応を追加 + - `UseAst` に `styleOverflow` 対応を追加 + - `DslParser.ValidateDsl` に no-schema mode 用の追加検証を実装 + - `LayoutEngine` に `cell@formula` と `styleOverflow=edge` の runtime ルールを追加 + - `IssueKind` に ExcelTemplate 関連種別を追加 +2. レイアウト runtime 補完 + - `styleOverflow=edge` は `ExpandUse` / `ExpandRepeat` の後段で、アンカー矩形と展開後矩形の差分に対して style-onlyセルを合成する + - 挿入先 seed 書式は「値なしでも style を持つ `LayoutCell`」として layout plan に残す + - trailing edge copy は row/col/corner ごとに `LayoutCell` を生成し、競合は 11章ルールで解決する +3. ExcelTemplate 中間モデル + - `ExcelTemplateWorkbook` + - `ExcelTemplateSheet` + - `ExcelTemplateCell` + - `ExcelTemplateStyle` + - `ExcelTemplateComponentRange` + - `ExcelTemplateIssue` +4. ExcelTemplate 抽出・検証 + - OpenXML から workbook/sheet/cell/style/defined name/merged cell を読む extractor + - シート分類、component 範囲決定、unsupported feature 検出、trigger 解析 +5. 変換出力 + - XML debug 出力用 serializer + - DSL text 出力用 emitter +6. 統合ファサード + - `ConvertToDsl` + - `ConvertToXmlTemplate` + - `GenerateFromExcelTemplate` + +### 13.4 推奨ファイル構成 +```text +ExcelReportLib/ + ExcelTemplate/ + ExcelTemplateConverter.cs + ExcelTemplateReportGenerator.cs + ExcelTemplateConvertOptions.cs + ExcelTemplateExtractor.cs + ExcelTemplateValidator.cs + ComponentRangeResolver.cs + UseTriggerParser.cs + DslEmitter.cs + XmlTemplateSerializer.cs + Model/ + ExcelTemplateWorkbook.cs + ExcelTemplateSheet.cs + ExcelTemplateCell.cs + ExcelTemplateStyle.cs + ExcelTemplateComponentRange.cs +``` + +補足: +- `ExcelTemplateExtractor` は OpenXML 読み取りに専念する。 +- シート分類・範囲解決・unsupported validation は extractor に埋め込まず、小さな協調クラスへ分ける。 +- `ExcelTemplateReportGenerator` は `ExcelTemplateConverter + ReportGenerator` の薄い合成層に留める。 + +### 13.5 実装順序 +1. DSL契約の不足補完 + - `cell@formula` と `use@styleOverflow` を先に通す + - runtime schema は `Design/DslDefinition/DslDefinition_v2.xsd` と test fixture の両方を更新する + - `ValidateDsl` で schema validation 無効時の補完検証も追加する + - ここを先に済ませないと、ExcelTemplate 変換器が正しい DSL を吐けない +2. レイアウト runtime 補完 + - `styleOverflow=edge` は `LayoutEngine` 内の post-expand 処理として追加する + - style-only seed cell を layout plan に保持できることを先に固定する +3. ExcelTemplate 中間モデルと extractor + - 値/数式/最小スタイル/defined name/merged cell を読む + - 初版対象外機能は validation で Warning/Error 化する +4. component 範囲解決と trigger 解析 + - `__component_` 判定 + - `__component_range_` 解決 + - `{{use:...}}` / `repeat + use` の解析 + - repeat は必ず `direction="down"` を明示出力する +5. DslEmitter / XmlTemplateSerializer + - 中間モデルから debug XML と DSL text を生成する +6. facade API と E2E 接続 + - ExcelTemplate 入力から最終 Excel 生成までを 1 API で呼べるようにする + +### 13.6 API 方針 +- 既存 `ReportGenerator` は DSL 専用のまま維持する。 +- ExcelTemplate 入口は新規 API として追加する。 + +想定シグネチャ例: +```csharp +public sealed class ExcelTemplateConversionResult +{ + public string Text { get; } + public IReadOnlyList Issues { get; } +} + +public sealed class ExcelTemplateConverter +{ + public ExcelTemplateConversionResult ConvertToDsl(string xlsxPath, ExcelTemplateConvertOptions? options = null); + public ExcelTemplateConversionResult ConvertToXmlTemplate(string xlsxPath, ExcelTemplateConvertOptions? options = null); +} + +public sealed class ExcelTemplateReportGenerator +{ + public ReportGeneratorResult GenerateFromExcelTemplate( + string xlsxPath, + object? data, + ExcelTemplateGenerateOptions? options = null, + CancellationToken cancellationToken = default); +} +``` + +方針: +- 最初は `string xlsxPath` を主入口にする。stream overload は必要になった時点で追加する。 +- debug 用に「生成 DSL / XML を返す API」を分離し、最終生成 API に詰め込みすぎない。 +- conversion-only API でも `Issues` を返し、座標付き Warning/Error を失わない。 + +### 13.7 テスト戦略 +1. Unit + - `cell@formula` / `styleOverflow` の parser/runtime + - `UseTriggerParser` + - `ComponentRangeResolver` + - `repeat@direction="down"` 明示出力 + - extractor の値/数式/スタイル/defined name/merged cell 抽出 + - 既存後方互換: `cell@value="=..."` が従来どおり数式として動くこと +2. Integration + - xlsx -> xml template snapshot + - xlsx -> dsl snapshot +3. E2E + - xlsx template -> dsl -> final xlsx + - `GroupBlock` / `ItemRow` の repeat/use 展開 + - `styleOverflow=edge` + - `cell@formula` + - merged cell 制約 violation + +### 13.8 実装時のガードレール +- 初版対象外の条件付き書式は extractor/validator で明示的に検出し、silent ignore しない。 +- merged cell は component 定義範囲内で完結している場合だけ許可し、境界跨ぎは Error にする。 +- 数式は値に潰さず保持し、C# 側で Excel 関数計算はしない。 +- `styleOverflow=edge` は現行レイアウトモデルに合わせ、right/down/right-down corner のみ対応する。 +- schema validation を無効化しても契約逸脱を見逃さないよう、`ValidateDsl` で `formula/value` 競合と `styleOverflow` 値を検証する。 +- 既存 `ReportGenerator` の公開挙動を変える変更は避け、必要なら新規 API で閉じる。 + +### 13.9 完了条件 +- ExcelTemplate から DSL 変換が unit/integration で固定されている +- ExcelTemplate から最終 Excel 生成まで E2E で通る +- Issue / logger に座標付き原因が残る +- 初版対象外機能は validation で検知できる +- 設計書と実装の契約差分が解消されている diff --git a/Design/ExcelTemplate/assets/cell-style-state-example.svg b/Design/ExcelTemplate/assets/cell-style-state-example.svg new file mode 100644 index 0000000..30b8af2 --- /dev/null +++ b/Design/ExcelTemplate/assets/cell-style-state-example.svg @@ -0,0 +1,76 @@ + + + + Issue #58: Nested Component Border Resolution (Excel Cell Aligned) + + + + + A + B + C + D + + 1 + 2 + 3 + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + A1 Header + value: 請求書 + + A2 @group.Name + use: ItemRow + + A4 conflict + parent: thin + child: dashed + + B4 right=medium + C4 top=thin + D4 left=thin + + + + Legend + + Parent outer border + + Child/default border + + Conflict (child wins + warning) + + diff --git a/Design/ExcelTemplate/assets/expanded-cell-values-from-csharp.svg b/Design/ExcelTemplate/assets/expanded-cell-values-from-csharp.svg new file mode 100644 index 0000000..5c68755 --- /dev/null +++ b/Design/ExcelTemplate/assets/expanded-cell-values-from-csharp.svg @@ -0,0 +1,75 @@ + + + + Invoice シート(出力Excelイメージ) + Header は A1:F1 へ拡張。GroupBlock repeat は B4:D9 に連続展開され、親フレームは A3:E10 へ拡張される。 + + + + + + + + + + + Row + A + B + C + D + E + F + + + + + + + + + + + + + + + 12345678910 + + 請求書 + + 機械部品 + Bolt1235 + Nut1218 + Washer129 + + 電材 + Cable3980 + + + + + + + + + + + + + + + + + + + diff --git a/Design/ExcelTemplate/assets/expanded-insert-source-from-csharp.svg b/Design/ExcelTemplate/assets/expanded-insert-source-from-csharp.svg new file mode 100644 index 0000000..795b236 --- /dev/null +++ b/Design/ExcelTemplate/assets/expanded-insert-source-from-csharp.svg @@ -0,0 +1,73 @@ + + + + GroupBlock 挿入元インスタンス(C#データ展開後) + 本節サンプルデータから生成された GroupBlock 実体。左: 機械部品 / 右: 電材。 + + + instance #1 (@group.Name = 機械部品) + + + + + + + Row + A + B + C + + + + + + + 1234 + + 機械部品 + Bolt1235 + Nut1218 + Washer129 + + + + + + + + + instance #2 (@group.Name = 電材) + + + + + + + Row + A + B + C + + + + + 12 + + 電材 + Cable3980 + + + + + + + diff --git a/Design/ExcelTemplate/assets/insert-source-cell-values.svg b/Design/ExcelTemplate/assets/insert-source-cell-values.svg new file mode 100644 index 0000000..e6c77cb --- /dev/null +++ b/Design/ExcelTemplate/assets/insert-source-cell-values.svg @@ -0,0 +1,52 @@ + + + + 挿入元コンポーネント(__component_GroupBlock / 3x3) + ExcelTemplate入力例。GroupBlock の定義範囲は A1:C3。 + + + + + + + + Row + A + B + C + + + + + + + + + + + + + + + + + 1 + 2 + 3 + + @group.Name + {{use:ItemRow, from:@group.Items, var:item}} + + + + + diff --git a/Design/ExcelTemplate/assets/insert-target-cell-values.svg b/Design/ExcelTemplate/assets/insert-target-cell-values.svg new file mode 100644 index 0000000..43a44bc --- /dev/null +++ b/Design/ExcelTemplate/assets/insert-target-cell-values.svg @@ -0,0 +1,67 @@ + + + + 挿入先シート(Header + 3x3中央use) + 入力テンプレート。A1:C1 に Header、A3:C5 外枠の中央 B4 に GroupBlock を配置。 + + + + + + + + Row + A + B + C + + + + + + + + + + + + + + + + + + + + + + + + + + + 1 + 2 + 3 + 4 + 5 + + {{use:Header}} + {{use:GroupBlock, from:@groups, var:group}} + + + + + + + + diff --git a/Design/ExcelTemplate/assets/style-overflow-modes-3x3.svg b/Design/ExcelTemplate/assets/style-overflow-modes-3x3.svg new file mode 100644 index 0000000..c203c5d --- /dev/null +++ b/Design/ExcelTemplate/assets/style-overflow-modes-3x3.svg @@ -0,0 +1,79 @@ + + + + 3x3挿入先 + 4列子component: 挿入先書式 overflow 挙動 + overflow 比較専用ケース。子展開により親範囲が右方向へ1列拡張される想定(A..C → A..D)。 + + + Case 1: styleOverflow=none / seed=A1:C1 + + + + RowABCDE + + + + + + + 1234 + @child.Header{{use:ChildRow, from:@child.Rows, var:row}} + + + + 拡張列 D1 へはコピーしない + + + + + Case 2: styleOverflow=edge / seed=A1:C1 + + + + RowABCDE + + + + + + + 1234 + @child.Header{{use:ChildRow, from:@child.Rows, var:row}} + + + + 拡張列 D1 へ edge 方式でコピー + + + + + Case 3: styleOverflow=edge / seed=A1:B1 + + + + RowABCDE + + + + + + + 1234 + @child.Header{{use:ChildRow, from:@child.Rows, var:row}} + + + + C1が未設定のため D1へはコピーしない + + + diff --git a/ExcelReport/ExcelReportLib.Tests/DslEmitterTests.cs b/ExcelReport/ExcelReportLib.Tests/DslEmitterTests.cs new file mode 100644 index 0000000..94782ba --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/DslEmitterTests.cs @@ -0,0 +1,77 @@ +using ExcelReportLib.DSL; +using ExcelReportLib.ExcelTemplate; + +namespace ExcelReportLib.Tests; + +/// +/// Provides tests for . +/// +public sealed class DslEmitterTests +{ + /// + /// Verifies that emitter writes DSL text with workbook, component, and sheet structure. + /// + [Fact] + public void Emit_WritesDslTextForWorkbookComponentsAndSheets() + { + var builder = new ExcelTemplateOutputContractBuilder(); + var contract = builder.Build(ExcelTemplateOutputContractFixture.CreateStandardWorkbook()); + var emitter = new DslEmitter(); + + var text = emitter.Emit(contract); + + Assert.StartsWith("", text, StringComparison.Ordinal); + Assert.Contains("", text, StringComparison.Ordinal); + Assert.Contains("", text, StringComparison.Ordinal); + Assert.Contains("", text, StringComparison.Ordinal); + + var parseResult = DslParser.ParseFromText( + text, + new DslParserOptions { EnableSchemaValidation = true }); + Assert.NotNull(parseResult.Root); + Assert.DoesNotContain(parseResult.Issues, issue => issue.Severity == IssueSeverity.Fatal); + } + + /// + /// Verifies that emitter preserves formula, explicit styleOverflow, and repeat direction in DSL text. + /// + [Fact] + public void Emit_PreservesFormulaStyleOverflowAndDirection() + { + var contract = new ExcelReportLib.ExcelTemplate.Model.ExcelTemplateOutputContract( + components: + [ + new ExcelReportLib.ExcelTemplate.Model.ExcelTemplateOutputComponent( + "Header", + "__component_Header", + "A1:B2", + isRangeResolved: true, + items: + [ + new ExcelReportLib.ExcelTemplate.Model.ExcelTemplateOutputCell("A1", 1, 1, null, null, "SUM(C1:C3)"), + new ExcelReportLib.ExcelTemplate.Model.ExcelTemplateOutputRepeatUse("A2", 2, 1, null, "ItemRow", "@items", "item", "down", "edge"), + ]), + ], + sheets: + [ + new ExcelReportLib.ExcelTemplate.Model.ExcelTemplateOutputSheet( + "Invoice", + [ + new ExcelReportLib.ExcelTemplate.Model.ExcelTemplateOutputUse("A1", 1, 1, null, "Header", "edge"), + ]), + ]); + var emitter = new DslEmitter(); + + var text = emitter.Emit(contract); + + Assert.Contains("formula=\"SUM(C1:C3)\"", text, StringComparison.Ordinal); + Assert.Contains("styleOverflow=\"edge\"", text, StringComparison.Ordinal); + Assert.Contains("direction=\"down\"", text, StringComparison.Ordinal); + + var parseResult = DslParser.ParseFromText( + text, + new DslParserOptions { EnableSchemaValidation = true }); + Assert.NotNull(parseResult.Root); + Assert.DoesNotContain(parseResult.Issues, issue => issue.Severity == IssueSeverity.Fatal); + } +} diff --git a/ExcelReport/ExcelReportLib.Tests/DslParserTests.cs b/ExcelReport/ExcelReportLib.Tests/DslParserTests.cs index d4a9dff..1a21f2b 100644 --- a/ExcelReport/ExcelReportLib.Tests/DslParserTests.cs +++ b/ExcelReport/ExcelReportLib.Tests/DslParserTests.cs @@ -254,6 +254,44 @@ public void ParseFromText_CellValueElement_WithSchemaValidation_Succeeds() issue => issue.Kind == IssueKind.SchemaViolation && issue.Severity == IssueSeverity.Fatal); } + /// + /// Verifies that parse cell formula and use style overflow with schema validation succeeds. + /// + [Fact] + public void ParseFromText_CellFormulaAndUseStyleOverflow_WithSchemaValidation_Succeeds() + { + var result = DslParser.ParseFromText( + """ + + + + + + + + + + + + """, + new DslParserOptions + { + EnableSchemaValidation = true, + }); + + Assert.False(result.HasFatal); + var root = Assert.IsType(result.Root); + var sheet = Assert.Single(root.Sheets); + var cell = Assert.IsType(sheet.Children.Values.First()); + var use = Assert.IsType(sheet.Children.Values.Last()); + + Assert.Equal("SUM(B2:B10)", cell.FormulaRaw); + Assert.Equal("edge", use.StyleOverflow); + Assert.DoesNotContain( + result.Issues, + issue => issue.Kind == IssueKind.SchemaViolation && issue.Severity == IssueSeverity.Fatal); + } + /// /// Verifies that static chart bounds validation checks Excel limits even when sheet rows and cols are omitted. /// diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateComponentRangeResolverTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateComponentRangeResolverTests.cs new file mode 100644 index 0000000..c7efdb5 --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateComponentRangeResolverTests.cs @@ -0,0 +1,152 @@ +using ExcelReportLib.DSL; +using ExcelReportLib.ExcelTemplate; +using ExcelReportLib.ExcelTemplate.Model; + +namespace ExcelReportLib.Tests; + +/// +/// Provides tests for . +/// +public sealed class ExcelTemplateComponentRangeResolverTests +{ + /// + /// Verifies that explicit defined name range takes precedence. + /// + [Fact] + public void Resolve_DefinedName_UsesExplicitRange() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet( + "__component_Header", + [ + new ExcelTemplateCell("A1", 1, 1, "Title", null, null), + ]), + ], + definedNames: new Dictionary(StringComparer.Ordinal) + { + ["__component_range_Header"] = "'__component_Header'!$A$1:$C$3", + }); + + var resolver = new ExcelTemplateComponentRangeResolver(); + + var result = resolver.Resolve(workbook); + + var range = Assert.Single(result.Ranges); + Assert.Equal("Header", range.ComponentName); + Assert.Equal("__component_Header", range.SheetName); + Assert.Equal("A1:C3", range.Reference); + Assert.Empty(result.Issues); + } + + /// + /// Verifies that auto detection uses cells and merged ranges. + /// + [Fact] + public void Resolve_WithoutDefinedName_UsesAutoDetectedBoundingBox() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet( + "__component_GroupBlock", + [ + new ExcelTemplateCell("A1", 1, 1, "Header", null, null), + new ExcelTemplateCell("C2", 2, 3, null, "SUM(A1:A1)", null), + ], + mergedRanges: ["A4:B4"]), + ]); + + var resolver = new ExcelTemplateComponentRangeResolver(); + + var result = resolver.Resolve(workbook); + + var range = Assert.Single(result.Ranges); + Assert.Equal("GroupBlock", range.ComponentName); + Assert.Equal("A1:C4", range.Reference); + Assert.Empty(result.Issues); + } + + /// + /// Verifies that empty component candidates return error. + /// + [Fact] + public void Resolve_EmptyComponentCandidates_ReturnsError() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet("__component_Empty"), + ]); + + var resolver = new ExcelTemplateComponentRangeResolver(); + + var result = resolver.Resolve(workbook); + + Assert.Empty(result.Ranges); + Assert.Contains( + result.Issues, + issue => issue.Severity == IssueSeverity.Error + && issue.Kind == IssueKind.EmptyComponentRange); + } + + /// + /// Verifies that defined name pointing to another sheet returns invalid component range error. + /// + [Fact] + public void Resolve_DefinedNamePointingOtherSheet_ReturnsError() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet( + "__component_Header", + [ + new ExcelTemplateCell("A1", 1, 1, "Title", null, null), + ]), + new ExcelTemplateSheet("Summary"), + ], + definedNames: new Dictionary(StringComparer.Ordinal) + { + ["__component_range_Header"] = "'Summary'!$A$1:$B$2", + }); + + var resolver = new ExcelTemplateComponentRangeResolver(); + + var result = resolver.Resolve(workbook); + + Assert.Empty(result.Ranges); + Assert.Contains( + result.Issues, + issue => issue.Severity == IssueSeverity.Error + && issue.Kind == IssueKind.InvalidComponentRange); + } + + /// + /// Verifies that explicit range without candidates returns empty component range error. + /// + [Fact] + public void Resolve_DefinedNameWithoutCandidates_ReturnsEmptyComponentRange() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet("__component_Header"), + ], + definedNames: new Dictionary(StringComparer.Ordinal) + { + ["__component_range_Header"] = "'__component_Header'!$A$1:$B$2", + }); + + var resolver = new ExcelTemplateComponentRangeResolver(); + + var result = resolver.Resolve(workbook); + + Assert.Empty(result.Ranges); + Assert.Contains( + result.Issues, + issue => issue.Severity == IssueSeverity.Error + && issue.Kind == IssueKind.EmptyComponentRange); + } +} diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateConverterTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateConverterTests.cs new file mode 100644 index 0000000..5395758 --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateConverterTests.cs @@ -0,0 +1,117 @@ +using ExcelReportLib.DSL; +using ExcelReportLib.ExcelTemplate; + +namespace ExcelReportLib.Tests; + +/// +/// Provides integration tests for . +/// +public sealed class ExcelTemplateConverterTests +{ + /// + /// Verifies that converter returns DSL text and no issues for a valid workbook. + /// + [Fact] + public void ConvertToDsl_ValidWorkbook_ReturnsDslText() + { + var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateStandardWorkbookFile(); + + try + { + var converter = new ExcelTemplateConverter(); + + var result = converter.ConvertToDsl(xlsxPath); + + Assert.Contains("", result.Text, StringComparison.Ordinal); + Assert.Empty(result.Issues); + + var parseResult = DslParser.ParseFromText( + result.Text, + new DslParserOptions { EnableSchemaValidation = true }); + Assert.NotNull(parseResult.Root); + Assert.DoesNotContain(parseResult.Issues, issue => issue.Severity == IssueSeverity.Fatal); + } + finally + { + File.Delete(xlsxPath); + } + } + + /// + /// Verifies that converter aggregates validation issues while still returning DSL-compatible XML text. + /// + [Fact] + public void ConvertToXmlTemplate_InvalidWorkbook_ReturnsTextAndAggregatedIssues() + { + var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateIssueWorkbookFile(); + + try + { + var converter = new ExcelTemplateConverter(); + + var result = converter.ConvertToXmlTemplate(xlsxPath); + + Assert.Contains("", result.Text, StringComparison.Ordinal); + Assert.Contains(result.Issues, issue => issue.Kind == IssueKind.EmptyComponentRange); + Assert.Contains(result.Issues, issue => issue.Kind == IssueKind.UnsupportedExcelTemplateFeature); + Assert.Contains(result.Issues, issue => issue.Kind == IssueKind.InvalidAttributeValue); + } + finally + { + File.Delete(xlsxPath); + } + } + + /// + /// Verifies that a corrupt workbook is reported as a fatal load issue instead of escaping as an exception. + /// + [Fact] + public void ConvertToDsl_CorruptWorkbook_ReturnsFatalLoadIssue() + { + var xlsxPath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.xlsx"); + File.WriteAllText(xlsxPath, "not-an-xlsx"); + + try + { + var converter = new ExcelTemplateConverter(); + + var result = converter.ConvertToDsl(xlsxPath); + + Assert.Equal(string.Empty, result.Text); + var issue = Assert.Single(result.Issues); + Assert.Equal(IssueSeverity.Fatal, issue.Severity); + Assert.Equal(IssueKind.LoadFile, issue.Kind); + } + finally + { + File.Delete(xlsxPath); + } + } + + /// + /// Verifies that disabling schema validation still keeps non-schema DSL contract validation. + /// + [Fact] + public void ConvertToDsl_WhenSchemaValidationDisabled_StillValidatesDslContracts() + { + var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateUndefinedComponentWorkbookFile(); + + try + { + var converter = new ExcelTemplateConverter(); + + var result = converter.ConvertToDsl( + xlsxPath, + new ExcelTemplateConvertOptions { EnableSchemaValidation = false }); + + Assert.Contains("", result.Text, StringComparison.Ordinal); + Assert.True( + result.Issues.Count(issue => issue.Kind == IssueKind.UndefinedComponent) >= 2, + "UndefinedComponent issues should include validator + parser results."); + } + finally + { + File.Delete(xlsxPath); + } + } +} diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateEndToEndTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateEndToEndTests.cs new file mode 100644 index 0000000..62e341c --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateEndToEndTests.cs @@ -0,0 +1,178 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using ExcelReportLib.DSL; +using ExcelReportLib.ExcelTemplate; +using ExcelReportLib.Renderer; + +namespace ExcelReportLib.Tests; + +/// +/// Provides end-to-end tests for ExcelTemplate conversion and rendering. +/// +public sealed class ExcelTemplateEndToEndTests +{ + /// + /// Verifies that nested GroupBlock and ItemRow templates are converted into DSL-compatible text. + /// + [Fact] + public void ConvertToDsl_NestedWorkbook_PreservesDslCompatibilityTokens() + { + var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateNestedReportWorkbookFile(); + + try + { + var converter = new ExcelTemplateConverter(); + + var result = converter.ConvertToDsl(xlsxPath); + + Assert.DoesNotContain(result.Issues, issue => issue.Severity == IssueSeverity.Fatal); + Assert.Contains("styleOverflow=\"edge\"", result.Text, StringComparison.Ordinal); + Assert.Contains("from=\"@(root.Groups)\"", result.Text, StringComparison.Ordinal); + Assert.Contains("from=\"@(group.Items)\"", result.Text, StringComparison.Ordinal); + Assert.Contains("value=\"@(item.Name)\"", result.Text, StringComparison.Ordinal); + Assert.Contains("formula=\"SUM(B4:B8)\"", result.Text, StringComparison.Ordinal); + } + finally + { + File.Delete(xlsxPath); + } + } + + /// + /// Verifies that nested GroupBlock and ItemRow templates render expected workbook content through the facade. + /// + [Fact] + public void GenerateFromExcelTemplate_NestedWorkbook_ProducesExpectedWorkbook() + { + var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateNestedReportWorkbookFile(); + + try + { + var generator = new ExcelTemplateReportGenerator(); + + var result = generator.GenerateFromExcelTemplate( + xlsxPath, + new + { + Groups = new[] + { + new + { + Name = "Hardware", + Items = new[] + { + new { Name = "Mouse", Qty = 2, Price = 1200 }, + }, + }, + new + { + Name = "Wiring", + Items = new[] + { + new { Name = "Cable", Qty = 3, Price = 980 }, + }, + }, + }, + }, + CreateOptions()); + + Assert.True( + result.Output is not null, + string.Join(Environment.NewLine, result.Issues.Select(issue => $"{issue.Severity}:{issue.Kind}:{issue.Message}"))); + Assert.DoesNotContain(result.Issues, issue => issue.Severity == IssueSeverity.Fatal); + + using var document = OpenWorkbook(result); + Assert.Equal("Invoice", ReadCellValue(document, GetCell(document, "Invoice", "A1"))); + Assert.Equal("Hardware", ReadCellValue(document, GetCell(document, "Invoice", "A3"))); + Assert.Equal("Mouse", ReadCellValue(document, GetCell(document, "Invoice", "A4"))); + Assert.Equal("2", ReadCellValue(document, GetCell(document, "Invoice", "B4"))); + Assert.Equal("1200", ReadCellValue(document, GetCell(document, "Invoice", "C4"))); + Assert.Equal("Wiring", ReadCellValue(document, GetCell(document, "Invoice", "A5"))); + Assert.Equal("Cable", ReadCellValue(document, GetCell(document, "Invoice", "A6"))); + Assert.Equal("SUM(B4:B8)", GetCell(document, "Invoice", "B1").CellFormula?.Text); + } + finally + { + File.Delete(xlsxPath); + } + } + + /// + /// Verifies that negative validation cases are surfaced on the final result. + /// + [Fact] + public void GenerateFromExcelTemplate_WorkbookWithValidationIssues_ReturnsIssues() + { + var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateValidationIssueWorkbookFile(); + + try + { + var generator = new ExcelTemplateReportGenerator(); + + var result = generator.GenerateFromExcelTemplate(xlsxPath, data: null, CreateOptions()); + + Assert.NotNull(result.Output); + Assert.Contains(result.Issues, issue => issue.Kind == IssueKind.MergedCellBoundaryViolation); + Assert.Contains(result.Issues, issue => issue.Kind == IssueKind.UnsupportedExcelTemplateFeature); + + using var document = OpenWorkbook(result); + Assert.Equal("Ready", ReadCellValue(document, GetCell(document, "Summary", "A1"))); + } + finally + { + File.Delete(xlsxPath); + } + } + + private static ExcelTemplateGenerateOptions CreateOptions() => + new() + { + ReportGeneratorOptions = new ReportGeneratorOptions + { + EnableSchemaValidation = false, + RenderOptions = new RenderOptions + { + TemplateName = "Task11", + DataSource = "Tests", + GeneratedAt = new DateTimeOffset(2026, 4, 14, 0, 0, 0, TimeSpan.Zero), + }, + }, + }; + + private static SpreadsheetDocument OpenWorkbook(ReportGeneratorResult result) + { + var output = Assert.IsType(result.Output); + output.Position = 0; + return SpreadsheetDocument.Open(output, false); + } + + private static WorksheetPart GetWorksheetPart(SpreadsheetDocument document, string sheetName) => + (WorksheetPart)document.WorkbookPart!.GetPartById( + document.WorkbookPart.Workbook.Sheets!.Elements() + .Single(sheet => sheet.Name!.Value == sheetName) + .Id!); + + private static Cell GetCell(SpreadsheetDocument document, string sheetName, string reference) => + GetWorksheetPart(document, sheetName) + .Worksheet + .Descendants() + .Single(cell => cell.CellReference!.Value == reference); + + private static string ReadCellValue(SpreadsheetDocument document, Cell cell) + { + if (cell.DataType?.Value == CellValues.InlineString) + { + return cell.InlineString!.InnerText; + } + + if (cell.DataType?.Value == CellValues.SharedString) + { + return document.WorkbookPart!.SharedStringTablePart!.SharedStringTable + .Elements() + .ElementAt(int.Parse(cell.CellValue!.Text, System.Globalization.CultureInfo.InvariantCulture)) + .InnerText; + } + + return cell.CellValue?.Text ?? string.Empty; + } +} diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateExtractorTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateExtractorTests.cs new file mode 100644 index 0000000..83cf601 --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateExtractorTests.cs @@ -0,0 +1,189 @@ +using System.Globalization; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using ExcelReportLib.ExcelTemplate; + +namespace ExcelReportLib.Tests; + +/// +/// Provides tests for . +/// +public sealed class ExcelTemplateExtractorTests +{ + /// + /// Verifies that extract reads workbook sheets, cells, defined names, and merged ranges. + /// + [Fact] + public void Extract_ReadsWorkbookSheetsCellsDefinedNamesAndMergedRanges() + { + var xlsxPath = CreateWorkbookFile(); + + try + { + var extractor = new ExcelTemplateExtractor(); + + var workbook = extractor.Extract(xlsxPath); + + Assert.Equal(2, workbook.Sheets.Count); + Assert.Equal("'__component_Header'!$A$1:$B$2", workbook.DefinedNames["__component_range_Header"]); + + var componentSheet = workbook.Sheets.Single(sheet => sheet.Name == "__component_Header"); + var summarySheet = workbook.Sheets.Single(sheet => sheet.Name == "Summary"); + + var titleCell = componentSheet.Cells.Single(cell => cell.Reference == "A1"); + var formulaCell = componentSheet.Cells.Single(cell => cell.Reference == "B2"); + var numericCell = summarySheet.Cells.Single(cell => cell.Reference == "C3"); + + Assert.Equal("Title", titleCell.Value); + Assert.Null(titleCell.Formula); + Assert.Equal("SUM(C1:C3)", formulaCell.Formula); + Assert.Null(formulaCell.Value); + Assert.Equal("42", numericCell.Value); + Assert.Contains("A1:B1", componentSheet.MergedRanges); + Assert.False(componentSheet.HasConditionalFormatting); + Assert.True(summarySheet.HasConditionalFormatting); + } + finally + { + File.Delete(xlsxPath); + } + } + + /// + /// Verifies that extract missing file throws file not found. + /// + [Fact] + public void Extract_MissingFile_ThrowsFileNotFoundException() + { + var extractor = new ExcelTemplateExtractor(); + var missingPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture), "missing.xlsx"); + + Assert.Throws(() => extractor.Extract(missingPath)); + } + + private static string CreateWorkbookFile() + { + var path = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.xlsx"); + + using var document = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook); + var workbookPart = document.AddWorkbookPart(); + workbookPart.Workbook = new Workbook(); + + var sheets = workbookPart.Workbook.AppendChild(new Sheets()); + var componentSheetPart = CreateWorksheetPart( + workbookPart, + "__component_Header", + sheetId: 1U, + cells: + [ + CreateInlineStringCell("A1", "Title"), + CreateFormulaCell("B2", "SUM(C1:C3)"), + ], + mergedRange: "A1:B1"); + var summarySheetPart = CreateWorksheetPart( + workbookPart, + "Summary", + sheetId: 2U, + cells: + [ + CreateNumberCell("C3", "42"), + ], + hasConditionalFormatting: true); + + sheets.Append( + CreateSheet(componentSheetPart, workbookPart, "__component_Header", 1U), + CreateSheet(summarySheetPart, workbookPart, "Summary", 2U)); + + workbookPart.Workbook.DefinedNames = new DefinedNames( + new DefinedName + { + Name = "__component_range_Header", + Text = "'__component_Header'!$A$1:$B$2", + }); + workbookPart.Workbook.Save(); + + return path; + } + + private static WorksheetPart CreateWorksheetPart( + WorkbookPart workbookPart, + string sheetName, + uint sheetId, + IReadOnlyList cells, + string? mergedRange = null, + bool hasConditionalFormatting = false) + { + var worksheetPart = workbookPart.AddNewPart($"rId{sheetId}"); + var worksheet = new Worksheet(); + var sheetData = worksheet.AppendChild(new SheetData()); + var rows = cells + .GroupBy(cell => GetRowIndex(cell.CellReference?.Value ?? string.Empty)) + .OrderBy(group => group.Key); + + foreach (var rowGroup in rows) + { + var row = new Row { RowIndex = rowGroup.Key }; + foreach (var cell in rowGroup.OrderBy(cell => cell.CellReference!.Value, StringComparer.Ordinal)) + { + row.Append(cell); + } + + sheetData.Append(row); + } + + if (!string.IsNullOrWhiteSpace(mergedRange)) + { + worksheet.Append(new MergeCells(new MergeCell { Reference = mergedRange })); + } + + if (hasConditionalFormatting) + { + worksheet.Append( + new ConditionalFormatting + { + SequenceOfReferences = new ListValue { InnerText = "C3" }, + }); + } + + worksheetPart.Worksheet = worksheet; + worksheetPart.Worksheet.Save(); + return worksheetPart; + } + + private static Sheet CreateSheet(WorksheetPart worksheetPart, WorkbookPart workbookPart, string name, uint sheetId) => + new() + { + Id = workbookPart.GetIdOfPart(worksheetPart), + Name = name, + SheetId = sheetId, + }; + + private static Cell CreateInlineStringCell(string reference, string value) => + new() + { + CellReference = reference, + DataType = CellValues.InlineString, + InlineString = new InlineString(new Text(value)), + }; + + private static Cell CreateFormulaCell(string reference, string formula) => + new() + { + CellReference = reference, + CellFormula = new CellFormula(formula), + }; + + private static Cell CreateNumberCell(string reference, string value) => + new() + { + CellReference = reference, + CellValue = new CellValue(value), + }; + + private static uint GetRowIndex(string cellReference) + { + var digits = new string(cellReference.Where(char.IsDigit).ToArray()); + return uint.Parse(digits, CultureInfo.InvariantCulture); + } +} diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractBuilderTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractBuilderTests.cs new file mode 100644 index 0000000..537bc90 --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractBuilderTests.cs @@ -0,0 +1,277 @@ +using ExcelReportLib.DSL; +using ExcelReportLib.ExcelTemplate; +using ExcelReportLib.ExcelTemplate.Model; + +namespace ExcelReportLib.Tests; + +/// +/// Provides tests for . +/// +public sealed class ExcelTemplateOutputContractBuilderTests +{ + /// + /// Verifies that the builder classifies component and sheet scopes and normalizes cells, use, and repeat-use entries. + /// + [Fact] + public void Build_ClassifiesScopesAndNormalizesOutputEntries() + { + var workbook = ExcelTemplateOutputContractFixture.CreateStandardWorkbook(); + var builder = new ExcelTemplateOutputContractBuilder(); + + var contract = builder.Build(workbook); + + Assert.Empty(contract.Issues); + Assert.Equal(2, contract.Components.Count); + Assert.Single(contract.Sheets); + + var header = contract.Components.Single(component => component.Name == "Header"); + Assert.Equal("__component_Header", header.SourceSheetName); + Assert.True(header.IsRangeResolved); + Assert.Equal("A1:B2", header.RangeReference); + Assert.Equal(3, header.Items.Count); + + var titleCell = Assert.IsType(header.Items[0]); + Assert.Equal("A1", titleCell.Reference); + Assert.Equal("請求書", titleCell.Value); + Assert.Null(titleCell.Formula); + + var repeatUse = Assert.IsType(header.Items[1]); + Assert.Equal("A2", repeatUse.Reference); + Assert.Equal("ItemRow", repeatUse.ComponentName); + Assert.Equal("@(root.Items)", repeatUse.FromExpression); + Assert.Equal("item", repeatUse.VariableName); + Assert.Equal("down", repeatUse.Direction); + Assert.Null(repeatUse.StyleOverflow); + + var formulaCell = Assert.IsType(header.Items[2]); + Assert.Equal("B2", formulaCell.Reference); + Assert.Null(formulaCell.Value); + Assert.Equal("SUM(C1:C3)", formulaCell.Formula); + Assert.Equal((uint)7, formulaCell.StyleIndex); + + Assert.DoesNotContain(header.Items, item => item.Reference == "C3"); + + var invoice = Assert.Single(contract.Sheets); + Assert.Equal("Invoice", invoice.Name); + Assert.Equal(2, invoice.Items.Count); + + var headerUse = Assert.IsType(invoice.Items[0]); + Assert.Equal("A1", headerUse.Reference); + Assert.Equal("Header", headerUse.ComponentName); + Assert.Null(headerUse.StyleOverflow); + + var invoiceFormula = Assert.IsType(invoice.Items[1]); + Assert.Equal("B3", invoiceFormula.Reference); + Assert.Equal("SUM(B4:B8)", invoiceFormula.Formula); + + var itemRow = contract.Components.Single(component => component.Name == "ItemRow"); + var itemNameCell = Assert.IsType(Assert.Single(itemRow.Items)); + Assert.Equal("@(item.Name)", itemNameCell.Value); + } + + /// + /// Verifies that range resolution and validation issues are aggregated into the contract result. + /// + [Fact] + public void Build_AggregatesRangeResolutionAndValidationIssues() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet("__component_Empty"), + new ExcelTemplateSheet( + "Summary", + [ + new ExcelTemplateCell("A1", 1, 1, "{{use:Missing", null, null), + ], + hasConditionalFormatting: true), + ]); + var builder = new ExcelTemplateOutputContractBuilder(); + + var contract = builder.Build(workbook); + + var emptyComponent = Assert.Single(contract.Components); + Assert.Equal("Empty", emptyComponent.Name); + Assert.False(emptyComponent.IsRangeResolved); + Assert.Null(emptyComponent.RangeReference); + Assert.Empty(emptyComponent.Items); + + Assert.Single(contract.Sheets); + var summary = Assert.Single(contract.Sheets); + var malformedTriggerCell = Assert.IsType(Assert.Single(summary.Items)); + Assert.Equal("A1", malformedTriggerCell.Reference); + Assert.Equal("{{use:Missing", malformedTriggerCell.Value); + + Assert.Contains(contract.Issues, issue => issue.Kind == IssueKind.EmptyComponentRange); + Assert.Contains(contract.Issues, issue => issue.Kind == IssueKind.UnsupportedExcelTemplateFeature); + Assert.Contains( + contract.Issues, + issue => issue.Kind == IssueKind.InvalidAttributeValue + && issue.Message.Contains("A1", StringComparison.Ordinal)); + } + + /// + /// Verifies that style-only cells inside a resolved component range remain in the normalized output. + /// + [Fact] + public void Build_ComponentRangeWithStyleOnlyCell_KeepsStyledEmptyCell() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet( + "__component_Header", + [ + new ExcelTemplateCell("A1", 1, 1, "Title", null, null), + new ExcelTemplateCell("B1", 1, 2, null, null, new ExcelTemplateStyle(11)), + ]), + ], + definedNames: new Dictionary(StringComparer.Ordinal) + { + ["__component_range_Header"] = "'__component_Header'!$A$1:$B$1", + }); + var builder = new ExcelTemplateOutputContractBuilder(); + + var contract = builder.Build(workbook); + + var header = Assert.Single(contract.Components); + Assert.Equal(2, header.Items.Count); + + var styledCell = Assert.IsType(header.Items[1]); + Assert.Equal("B1", styledCell.Reference); + Assert.Null(styledCell.Value); + Assert.Null(styledCell.Formula); + Assert.Equal((uint)11, styledCell.StyleIndex); + } + + /// + /// Verifies that styleOverflow from Excel use triggers is preserved in the output contract. + /// + [Fact] + public void Build_UseTriggerWithStyleOverflow_PreservesExplicitOverflow() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet( + "Invoice", + [ + new ExcelTemplateCell("A1", 1, 1, "{{use:Header, styleOverflow:edge}}", null, null), + new ExcelTemplateCell("A2", 2, 1, "{{use:ItemRow, from:@items, var:item, styleOverflow:edge}}", null, null), + ]), + ]); + var builder = new ExcelTemplateOutputContractBuilder(); + + var contract = builder.Build(workbook); + + var invoice = Assert.Single(contract.Sheets); + var simpleUse = Assert.IsType(invoice.Items[0]); + Assert.Equal("edge", simpleUse.StyleOverflow); + + var repeatUse = Assert.IsType(invoice.Items[1]); + Assert.Equal("edge", repeatUse.StyleOverflow); + Assert.Equal("@(root.Items)", repeatUse.FromExpression); + } + + /// + /// Verifies that simple shorthand local variables are not rewritten to root scope. + /// + [Fact] + public void Build_SimpleIdentifierValue_UsesLocalRepeatScopeWhenVariableExists() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet( + "__component_ItemRow", + [ + new ExcelTemplateCell("A1", 1, 1, "@item", null, null), + ]), + new ExcelTemplateSheet( + "Invoice", + [ + new ExcelTemplateCell("A1", 1, 1, "{{use:ItemRow, from:@items, var:item}}", null, null), + ]), + ]); + var builder = new ExcelTemplateOutputContractBuilder(); + + var contract = builder.Build(workbook); + + var itemRow = Assert.Single(contract.Components); + var itemCell = Assert.IsType(Assert.Single(itemRow.Items)); + Assert.Equal("@(item)", itemCell.Value); + + var invoice = Assert.Single(contract.Sheets); + var repeatUse = Assert.IsType(Assert.Single(invoice.Items)); + Assert.Equal("@(root.Items)", repeatUse.FromExpression); + } + + /// + /// Verifies that repeat variable names do not leak to unrelated components. + /// + [Fact] + public void Build_SimpleIdentifierValue_DoesNotLeakVariableScopeAcrossComponents() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet( + "__component_Target", + [ + new ExcelTemplateCell("A1", 1, 1, "@item", null, null), + ]), + new ExcelTemplateSheet( + "__component_Other", + [ + new ExcelTemplateCell("A1", 1, 1, "X", null, null), + ]), + new ExcelTemplateSheet( + "Invoice", + [ + new ExcelTemplateCell("A1", 1, 1, "{{use:Other, from:@items, var:item}}", null, null), + ]), + ]); + var builder = new ExcelTemplateOutputContractBuilder(); + + var contract = builder.Build(workbook); + + var target = contract.Components.Single(component => component.Name == "Target"); + var targetCell = Assert.IsType(Assert.Single(target.Items)); + Assert.Equal("@(root.Item)", targetCell.Value); + } + + /// + /// Verifies that reusing one component with multiple variable names is reported as an ambiguous normalization error. + /// + [Fact] + public void Build_ComponentReferencedByMultipleVariables_ReportsAmbiguousNormalization() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet( + "__component_ItemRow", + [ + new ExcelTemplateCell("A1", 1, 1, "@item", null, null), + ]), + new ExcelTemplateSheet( + "Invoice", + [ + new ExcelTemplateCell("A1", 1, 1, "{{use:ItemRow, from:@items, var:item}}", null, null), + new ExcelTemplateCell("A2", 2, 1, "{{use:ItemRow, from:@rows, var:row}}", null, null), + ]), + ]); + var builder = new ExcelTemplateOutputContractBuilder(); + + var contract = builder.Build(workbook); + + var itemRow = Assert.Single(contract.Components); + var itemCell = Assert.IsType(Assert.Single(itemRow.Items)); + Assert.Equal("@(root.Item)", itemCell.Value); + Assert.Contains( + contract.Issues, + issue => issue.Kind == IssueKind.InvalidAttributeValue && + issue.Message.Contains("multiple repeat variables", StringComparison.Ordinal)); + } + +} diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractFixture.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractFixture.cs new file mode 100644 index 0000000..302f1e3 --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractFixture.cs @@ -0,0 +1,59 @@ +using ExcelReportLib.ExcelTemplate.Model; + +namespace ExcelReportLib.Tests; + +/// +/// Provides reusable ExcelTemplate workbook fixtures for conversion output tests. +/// +internal static class ExcelTemplateOutputContractFixture +{ + /// + /// Creates a workbook fixture covering component, sheet, formula, and use-trigger cases. + /// + /// The workbook fixture. + public static ExcelTemplateWorkbook CreateStandardWorkbook() => + new( + sheets: + [ + new ExcelTemplateSheet( + "__component_Header", + [ + new ExcelTemplateCell("A1", 1, 1, "請求書", null, new ExcelTemplateStyle(3)), + new ExcelTemplateCell("A2", 2, 1, "{{use:ItemRow, from:@items, var:item}}", null, null), + new ExcelTemplateCell("B2", 2, 2, null, "SUM(C1:C3)", new ExcelTemplateStyle(7)), + new ExcelTemplateCell("C3", 3, 3, "ignored", null, null), + ]), + new ExcelTemplateSheet( + "__component_ItemRow", + [ + new ExcelTemplateCell("A1", 1, 1, "@item.Name", null, null), + ]), + new ExcelTemplateSheet( + "Invoice", + [ + new ExcelTemplateCell("A1", 1, 1, "{{use:Header}}", null, null), + new ExcelTemplateCell("B3", 3, 2, null, "SUM(B4:B8)", null), + ]), + ], + definedNames: new Dictionary(StringComparer.Ordinal) + { + ["__component_range_Header"] = "'__component_Header'!$A$1:$B$2", + }); + + /// + /// Creates a workbook fixture containing unresolved component and validation issues. + /// + /// The workbook fixture. + public static ExcelTemplateWorkbook CreateWorkbookWithIssues() => + new( + sheets: + [ + new ExcelTemplateSheet("__component_Empty"), + new ExcelTemplateSheet( + "Summary", + [ + new ExcelTemplateCell("A1", 1, 1, "{{use:Missing", null, null), + ], + hasConditionalFormatting: true), + ]); +} diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateReportGeneratorTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateReportGeneratorTests.cs new file mode 100644 index 0000000..1bda673 --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateReportGeneratorTests.cs @@ -0,0 +1,148 @@ +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using ExcelReportLib.DSL; +using ExcelReportLib.ExcelTemplate; +using ExcelReportLib.Renderer; + +namespace ExcelReportLib.Tests; + +/// +/// Provides integration tests for . +/// +public sealed class ExcelTemplateReportGeneratorTests +{ + /// + /// Verifies that the ExcelTemplate facade converts and renders a workbook through the existing report pipeline. + /// + [Fact] + public void GenerateFromExcelTemplate_ValidWorkbook_ProducesXlsx() + { + var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateReportWorkbookFile(); + + try + { + var generator = new ExcelTemplateReportGenerator(); + + var result = generator.GenerateFromExcelTemplate( + xlsxPath, + new { Title = "Sales" }, + CreateOptions()); + + Assert.NotNull(result.Output); + Assert.True(result.Succeeded); + Assert.DoesNotContain(result.Issues, issue => issue.Severity is IssueSeverity.Error or IssueSeverity.Fatal); + + using var document = OpenWorkbook(result); + Assert.Equal("Sales", ReadCellValue(document, GetCell(document, "Summary", "A1"))); + } + finally + { + File.Delete(xlsxPath); + } + } + + /// + /// Verifies that fatal conversion failures abort before the DSL report pipeline runs. + /// + [Fact] + public void GenerateFromExcelTemplate_CorruptWorkbook_ReturnsFatalLoadIssue() + { + var xlsxPath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.xlsx"); + File.WriteAllText(xlsxPath, "not-an-xlsx"); + + try + { + var generator = new ExcelTemplateReportGenerator(); + + var result = generator.GenerateFromExcelTemplate(xlsxPath, data: null, CreateOptions()); + + Assert.Null(result.Output); + Assert.True(result.AbortedByFatal); + var issue = Assert.Single(result.Issues); + Assert.Equal(IssueSeverity.Fatal, issue.Severity); + Assert.Equal(IssueKind.LoadFile, issue.Kind); + } + finally + { + File.Delete(xlsxPath); + } + } + + /// + /// Verifies that non-fatal conversion issues are preserved on the final report result. + /// + [Fact] + public void GenerateFromExcelTemplate_WithNonFatalConversionIssue_ReturnsOutputAndIssues() + { + var xlsxPath = ExcelTemplateTestWorkbookFactory.CreateReportWorkbookWithConversionIssueFile(); + + try + { + var generator = new ExcelTemplateReportGenerator(); + + var result = generator.GenerateFromExcelTemplate(xlsxPath, data: null, CreateOptions()); + + Assert.NotNull(result.Output); + Assert.Contains(result.Issues, issue => issue.Kind == IssueKind.EmptyComponentRange); + + using var document = OpenWorkbook(result); + Assert.Equal("Ready", ReadCellValue(document, GetCell(document, "Summary", "A1"))); + } + finally + { + File.Delete(xlsxPath); + } + } + + private static ExcelTemplateGenerateOptions CreateOptions() => + new() + { + ReportGeneratorOptions = new ReportGeneratorOptions + { + EnableSchemaValidation = false, + RenderOptions = new RenderOptions + { + TemplateName = "Task11", + DataSource = "Tests", + GeneratedAt = new DateTimeOffset(2026, 4, 14, 0, 0, 0, TimeSpan.Zero), + }, + }, + }; + + private static SpreadsheetDocument OpenWorkbook(ReportGeneratorResult result) + { + var output = Assert.IsType(result.Output); + output.Position = 0; + return SpreadsheetDocument.Open(output, false); + } + + private static WorksheetPart GetWorksheetPart(SpreadsheetDocument document, string sheetName) => + (WorksheetPart)document.WorkbookPart!.GetPartById( + document.WorkbookPart.Workbook.Sheets!.Elements() + .Single(sheet => sheet.Name!.Value == sheetName) + .Id!); + + private static Cell GetCell(SpreadsheetDocument document, string sheetName, string reference) => + GetWorksheetPart(document, sheetName) + .Worksheet + .Descendants() + .Single(cell => cell.CellReference!.Value == reference); + + private static string ReadCellValue(SpreadsheetDocument document, Cell cell) + { + if (cell.DataType?.Value == CellValues.InlineString) + { + return cell.InlineString!.InnerText; + } + + if (cell.DataType?.Value == CellValues.SharedString) + { + return document.WorkbookPart!.SharedStringTablePart!.SharedStringTable + .Elements() + .ElementAt(int.Parse(cell.CellValue!.Text, System.Globalization.CultureInfo.InvariantCulture)) + .InnerText; + } + + return cell.CellValue?.Text ?? string.Empty; + } +} diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateSnapshotTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateSnapshotTests.cs new file mode 100644 index 0000000..10bc83b --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateSnapshotTests.cs @@ -0,0 +1,47 @@ +using ExcelReportLib.ExcelTemplate; + +namespace ExcelReportLib.Tests; + +/// +/// Provides snapshot tests for ExcelTemplate conversion outputs. +/// +public sealed class ExcelTemplateSnapshotTests +{ + private const string XmlSnapshotFile = "Issue58_StandardTemplate_Debug.xml"; + private const string DslSnapshotFile = "Issue58_StandardTemplate_Dsl.xml"; + + /// + /// Verifies that serializer output matches the checked-in debug XML snapshot. + /// + [Fact] + public void Serialize_StandardWorkbook_MatchesXmlSnapshot() + { + var builder = new ExcelTemplateOutputContractBuilder(); + var contract = builder.Build(ExcelTemplateOutputContractFixture.CreateStandardWorkbook()); + var serializer = new XmlTemplateSerializer(); + + var actual = NormalizeLineEndings(serializer.Serialize(contract).ToString()); + var expected = NormalizeLineEndings(DslTestFixtures.ReadText(XmlSnapshotFile)); + + Assert.Equal(expected, actual); + } + + /// + /// Verifies that DSL emitter output matches the checked-in DSL snapshot. + /// + [Fact] + public void Emit_StandardWorkbook_MatchesDslSnapshot() + { + var builder = new ExcelTemplateOutputContractBuilder(); + var contract = builder.Build(ExcelTemplateOutputContractFixture.CreateStandardWorkbook()); + var emitter = new DslEmitter(); + + var actual = NormalizeLineEndings(emitter.Emit(contract)); + var expected = NormalizeLineEndings(DslTestFixtures.ReadText(DslSnapshotFile)); + + Assert.Equal(expected, actual); + } + + private static string NormalizeLineEndings(string value) => + value.Replace("\r\n", "\n", StringComparison.Ordinal).Trim(); +} diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateTestWorkbookFactory.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateTestWorkbookFactory.cs new file mode 100644 index 0000000..a3e781c --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateTestWorkbookFactory.cs @@ -0,0 +1,423 @@ +using System.Globalization; +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; + +namespace ExcelReportLib.Tests; + +/// +/// Creates temporary xlsx fixtures for ExcelTemplate conversion tests. +/// +internal static class ExcelTemplateTestWorkbookFactory +{ + /// + /// Creates a valid workbook fixture. + /// + /// The temporary workbook path. + public static string CreateStandardWorkbookFile() + { + var path = CreateEmptyWorkbookFile(); + + using var document = SpreadsheetDocument.Open(path, true); + var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created."); + var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets()); + + var componentSheetPart = CreateWorksheetPart( + workbookPart, + sheetId: 1U, + cells: + [ + CreateInlineStringCell("A1", "請求書"), + CreateInlineStringCell("A2", "{{use:ItemRow, from:@items, var:item}}"), + CreateFormulaCell("B2", "SUM(C1:C3)"), + ]); + var itemRowSheetPart = CreateWorksheetPart( + workbookPart, + sheetId: 2U, + cells: + [ + CreateInlineStringCell("A1", "@item.Name"), + ]); + var invoiceSheetPart = CreateWorksheetPart( + workbookPart, + sheetId: 3U, + cells: + [ + CreateInlineStringCell("A1", "{{use:Header}}"), + CreateFormulaCell("B3", "SUM(B4:B8)"), + ]); + + sheets.Append( + CreateSheet(componentSheetPart, workbookPart, "__component_Header", 1U), + CreateSheet(itemRowSheetPart, workbookPart, "__component_ItemRow", 2U), + CreateSheet(invoiceSheetPart, workbookPart, "Invoice", 3U)); + + workbookPart.Workbook.DefinedNames = new DefinedNames( + new DefinedName + { + Name = "__component_range_Header", + Text = "'__component_Header'!$A$1:$B$2", + }); + workbookPart.Workbook.Save(); + + return path; + } + + /// + /// Creates an invalid workbook fixture that still allows conversion output. + /// + /// The temporary workbook path. + public static string CreateIssueWorkbookFile() + { + var path = CreateEmptyWorkbookFile(); + + using var document = SpreadsheetDocument.Open(path, true); + var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created."); + var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets()); + + var emptyComponentSheetPart = CreateWorksheetPart(workbookPart, sheetId: 1U, cells: []); + var summarySheetPart = CreateWorksheetPart( + workbookPart, + sheetId: 2U, + cells: + [ + CreateInlineStringCell("A1", "{{use:Missing"), + ], + hasConditionalFormatting: true); + + sheets.Append( + CreateSheet(emptyComponentSheetPart, workbookPart, "__component_Empty", 1U), + CreateSheet(summarySheetPart, workbookPart, "Summary", 2U)); + workbookPart.Workbook.Save(); + + return path; + } + + /// + /// Creates a workbook fixture that emits a DSL cell with both value and formula attributes. + /// + /// The temporary workbook path. + public static string CreateFormulaValueConflictWorkbookFile() + { + var path = CreateEmptyWorkbookFile(); + + using var document = SpreadsheetDocument.Open(path, true); + var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created."); + var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets()); + + var worksheetPart = CreateWorksheetPart( + workbookPart, + sheetId: 1U, + cells: + [ + CreateFormulaInlineStringCell("A1", "TemplateValue", "SUM(B1:B2)"), + ]); + + sheets.Append(CreateSheet(worksheetPart, workbookPart, "Invoice", 1U)); + workbookPart.Workbook.Save(); + + return path; + } + + /// + /// Creates a workbook fixture with a well-formed use trigger that references an undefined component. + /// + /// The temporary workbook path. + public static string CreateUndefinedComponentWorkbookFile() + { + var path = CreateEmptyWorkbookFile(); + + using var document = SpreadsheetDocument.Open(path, true); + var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created."); + var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets()); + + var worksheetPart = CreateWorksheetPart( + workbookPart, + sheetId: 1U, + cells: + [ + CreateInlineStringCell("A1", "{{use:Missing}}"), + ]); + + sheets.Append(CreateSheet(worksheetPart, workbookPart, "Invoice", 1U)); + workbookPart.Workbook.Save(); + + return path; + } + + /// + /// Creates a workbook fixture for end-to-end report generation through the ExcelTemplate facade. + /// + /// The temporary workbook path. + public static string CreateReportWorkbookFile() + { + var path = CreateEmptyWorkbookFile(); + + using var document = SpreadsheetDocument.Open(path, true); + var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created."); + var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets()); + + var summarySheetPart = CreateWorksheetPart( + workbookPart, + sheetId: 1U, + cells: + [ + CreateInlineStringCell("A1", "@(root.Title)"), + ]); + + sheets.Append(CreateSheet(summarySheetPart, workbookPart, "Summary", 1U)); + workbookPart.Workbook.Save(); + + return path; + } + + /// + /// Creates a report workbook fixture that carries a non-fatal conversion issue. + /// + /// The temporary workbook path. + public static string CreateReportWorkbookWithConversionIssueFile() + { + var path = CreateEmptyWorkbookFile(); + + using var document = SpreadsheetDocument.Open(path, true); + var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created."); + var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets()); + + var emptyComponentSheetPart = CreateWorksheetPart(workbookPart, sheetId: 1U, cells: []); + var summarySheetPart = CreateWorksheetPart( + workbookPart, + sheetId: 2U, + cells: + [ + CreateInlineStringCell("A1", "Ready"), + ]); + + sheets.Append( + CreateSheet(emptyComponentSheetPart, workbookPart, "__component_Empty", 1U), + CreateSheet(summarySheetPart, workbookPart, "Summary", 2U)); + workbookPart.Workbook.Save(); + + return path; + } + + /// + /// Creates a nested workbook fixture that exercises GroupBlock, ItemRow, styleOverflow, and formula preservation. + /// + /// The temporary workbook path. + public static string CreateNestedReportWorkbookFile() + { + var path = CreateEmptyWorkbookFile(); + + using var document = SpreadsheetDocument.Open(path, true); + var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created."); + var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets()); + + var headerSheetPart = CreateWorksheetPart( + workbookPart, + sheetId: 1U, + cells: + [ + CreateInlineStringCell("A1", "Invoice"), + CreateFormulaCell("B1", "SUM(B4:B8)"), + ]); + var itemRowSheetPart = CreateWorksheetPart( + workbookPart, + sheetId: 2U, + cells: + [ + CreateInlineStringCell("A1", "@item.Name"), + CreateInlineStringCell("B1", "@item.Qty"), + CreateInlineStringCell("C1", "@item.Price"), + ]); + var groupBlockSheetPart = CreateWorksheetPart( + workbookPart, + sheetId: 3U, + cells: + [ + CreateInlineStringCell("A1", "@group.Name"), + CreateInlineStringCell("A2", "{{use:ItemRow, from:@group.Items, var:item, styleOverflow:edge}}"), + ]); + var invoiceSheetPart = CreateWorksheetPart( + workbookPart, + sheetId: 4U, + cells: + [ + CreateInlineStringCell("A1", "{{use:Header, styleOverflow:edge}}"), + CreateInlineStringCell("A3", "{{use:GroupBlock, from:@groups, var:group, styleOverflow:edge}}"), + ]); + + sheets.Append( + CreateSheet(headerSheetPart, workbookPart, "__component_Header", 1U), + CreateSheet(itemRowSheetPart, workbookPart, "__component_ItemRow", 2U), + CreateSheet(groupBlockSheetPart, workbookPart, "__component_GroupBlock", 3U), + CreateSheet(invoiceSheetPart, workbookPart, "Invoice", 4U)); + + workbookPart.Workbook.DefinedNames = new DefinedNames( + new DefinedName + { + Name = "__component_range_Header", + Text = "'__component_Header'!$A$1:$B$1", + }, + new DefinedName + { + Name = "__component_range_ItemRow", + Text = "'__component_ItemRow'!$A$1:$C$1", + }, + new DefinedName + { + Name = "__component_range_GroupBlock", + Text = "'__component_GroupBlock'!$A$1:$C$2", + }); + workbookPart.Workbook.Save(); + + return path; + } + + /// + /// Creates a workbook fixture that emits merged-boundary and unsupported-feature issues. + /// + /// The temporary workbook path. + public static string CreateValidationIssueWorkbookFile() + { + var path = CreateEmptyWorkbookFile(); + + using var document = SpreadsheetDocument.Open(path, true); + var workbookPart = document.WorkbookPart ?? throw new InvalidOperationException("WorkbookPart was not created."); + var sheets = workbookPart.Workbook.GetFirstChild() ?? workbookPart.Workbook.AppendChild(new Sheets()); + + var badComponentSheetPart = CreateWorksheetPart( + workbookPart, + sheetId: 1U, + cells: + [ + CreateInlineStringCell("A1", "Broken"), + ], + mergedRanges: + [ + "A1:C1", + ]); + var summarySheetPart = CreateWorksheetPart( + workbookPart, + sheetId: 2U, + cells: + [ + CreateInlineStringCell("A1", "Ready"), + ], + hasConditionalFormatting: true); + + sheets.Append( + CreateSheet(badComponentSheetPart, workbookPart, "__component_Bad", 1U), + CreateSheet(summarySheetPart, workbookPart, "Summary", 2U)); + + workbookPart.Workbook.DefinedNames = new DefinedNames( + new DefinedName + { + Name = "__component_range_Bad", + Text = "'__component_Bad'!$A$1:$B$1", + }); + workbookPart.Workbook.Save(); + + return path; + } + + private static string CreateEmptyWorkbookFile() + { + var path = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid():N}.xlsx"); + + using var document = SpreadsheetDocument.Create(path, SpreadsheetDocumentType.Workbook); + var workbookPart = document.AddWorkbookPart(); + workbookPart.Workbook = new Workbook(); + workbookPart.Workbook.AppendChild(new Sheets()); + workbookPart.Workbook.Save(); + + return path; + } + + private static WorksheetPart CreateWorksheetPart( + WorkbookPart workbookPart, + uint sheetId, + IReadOnlyList cells, + bool hasConditionalFormatting = false, + IReadOnlyList? mergedRanges = null) + { + var worksheetPart = workbookPart.AddNewPart($"rId{sheetId}"); + var worksheet = new Worksheet(); + var sheetData = worksheet.AppendChild(new SheetData()); + var rows = cells + .GroupBy(cell => GetRowIndex(cell.CellReference?.Value ?? string.Empty)) + .OrderBy(group => group.Key); + + foreach (var rowGroup in rows) + { + var row = new Row { RowIndex = rowGroup.Key }; + foreach (var cell in rowGroup.OrderBy(cell => cell.CellReference!.Value, StringComparer.Ordinal)) + { + row.Append(cell); + } + + sheetData.Append(row); + } + + if (hasConditionalFormatting) + { + worksheet.Append( + new ConditionalFormatting + { + SequenceOfReferences = new ListValue { InnerText = "A1" }, + }); + } + + if (mergedRanges is { Count: > 0 }) + { + var mergeCells = new MergeCells(); + foreach (var mergedRange in mergedRanges) + { + mergeCells.Append(new MergeCell { Reference = mergedRange }); + } + + worksheet.Append(mergeCells); + } + + worksheetPart.Worksheet = worksheet; + worksheetPart.Worksheet.Save(); + return worksheetPart; + } + + private static Sheet CreateSheet(WorksheetPart worksheetPart, WorkbookPart workbookPart, string name, uint sheetId) => + new() + { + Id = workbookPart.GetIdOfPart(worksheetPart), + Name = name, + SheetId = sheetId, + }; + + private static Cell CreateInlineStringCell(string reference, string value) => + new() + { + CellReference = reference, + DataType = CellValues.InlineString, + InlineString = new InlineString(new Text(value)), + }; + + private static Cell CreateFormulaCell(string reference, string formula) => + new() + { + CellReference = reference, + CellFormula = new CellFormula(formula), + }; + + private static Cell CreateFormulaInlineStringCell(string reference, string value, string formula) => + new() + { + CellReference = reference, + DataType = CellValues.InlineString, + InlineString = new InlineString(new Text(value)), + CellFormula = new CellFormula(formula), + }; + + private static uint GetRowIndex(string cellReference) + { + var digits = new string(cellReference.Where(char.IsDigit).ToArray()); + return uint.Parse(digits, CultureInfo.InvariantCulture); + } +} diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateUseTriggerParserTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateUseTriggerParserTests.cs new file mode 100644 index 0000000..d2ca3d8 --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateUseTriggerParserTests.cs @@ -0,0 +1,138 @@ +using ExcelReportLib.DSL; +using ExcelReportLib.ExcelTemplate; + +namespace ExcelReportLib.Tests; + +/// +/// Provides tests for . +/// +public sealed class ExcelTemplateUseTriggerParserTests +{ + /// + /// Verifies that non-trigger text is ignored without issues. + /// + [Fact] + public void Parse_PlainText_ReturnsNotTrigger() + { + var parser = new UseTriggerParser(); + + var result = parser.Parse("請求書"); + + Assert.False(result.IsTrigger); + Assert.Null(result.Trigger); + Assert.Empty(result.Issues); + } + + /// + /// Verifies that simple use trigger parses component only. + /// + [Fact] + public void Parse_SimpleUse_ReturnsComponentTrigger() + { + var parser = new UseTriggerParser(); + + var result = parser.Parse("{{use:Header}}"); + + Assert.True(result.IsTrigger); + var trigger = Assert.IsType(result.Trigger); + Assert.Equal("Header", trigger.ComponentName); + Assert.Null(trigger.FromExpression); + Assert.Null(trigger.VariableName); + Assert.Null(trigger.RepeatDirection); + Assert.Empty(result.Issues); + } + + /// + /// Verifies that repeat use trigger parses from and var and normalizes direction down. + /// + [Fact] + public void Parse_RepeatUse_ReturnsRepeatTrigger() + { + var parser = new UseTriggerParser(); + + var result = parser.Parse("{{use:ItemRow, from:@items, var:item}}"); + + Assert.True(result.IsTrigger); + var trigger = Assert.IsType(result.Trigger); + Assert.Equal("ItemRow", trigger.ComponentName); + Assert.Equal("@items", trigger.FromExpression); + Assert.Equal("item", trigger.VariableName); + Assert.Equal("down", trigger.RepeatDirection); + Assert.Empty(result.Issues); + } + + /// + /// Verifies that styleOverflow token is parsed for both use and repeat-use triggers. + /// + [Fact] + public void Parse_UseWithStyleOverflow_ReturnsOverflowMode() + { + var parser = new UseTriggerParser(); + + var simpleResult = parser.Parse("{{use:Header, styleOverflow:edge}}"); + var repeatResult = parser.Parse("{{use:ItemRow, from:@items, var:item, styleOverflow:edge}}"); + + Assert.True(simpleResult.IsTrigger); + Assert.Equal("edge", Assert.IsType(simpleResult.Trigger).StyleOverflow); + + Assert.True(repeatResult.IsTrigger); + Assert.Equal("edge", Assert.IsType(repeatResult.Trigger).StyleOverflow); + } + + /// + /// Verifies that commas inside from expression do not break trigger tokenization. + /// + [Fact] + public void Parse_RepeatUse_WithCommaInFromExpression_ReturnsRepeatTrigger() + { + var parser = new UseTriggerParser(); + + var result = parser.Parse("{{use:ItemRow, from:@(root.Items.Select((x, i) => new { x, i })), var:item}}"); + + Assert.True(result.IsTrigger); + var trigger = Assert.IsType(result.Trigger); + Assert.Equal("ItemRow", trigger.ComponentName); + Assert.Equal("@(root.Items.Select((x, i) => new { x, i }))", trigger.FromExpression); + Assert.Equal("item", trigger.VariableName); + Assert.Equal("down", trigger.RepeatDirection); + Assert.Empty(result.Issues); + } + + /// + /// Verifies that from without var returns error. + /// + [Fact] + public void Parse_FromWithoutVar_ReturnsError() + { + var parser = new UseTriggerParser(); + + var result = parser.Parse("{{use:ItemRow, from:@items}}"); + + Assert.True(result.IsTrigger); + Assert.Null(result.Trigger); + Assert.Contains( + result.Issues, + issue => issue.Severity == IssueSeverity.Error + && issue.Kind == IssueKind.InvalidAttributeValue + && issue.Message.Contains("var", StringComparison.Ordinal)); + } + + /// + /// Verifies that var without from returns error. + /// + [Fact] + public void Parse_VarWithoutFrom_ReturnsError() + { + var parser = new UseTriggerParser(); + + var result = parser.Parse("{{use:ItemRow, var:item}}"); + + Assert.True(result.IsTrigger); + Assert.Null(result.Trigger); + Assert.Contains( + result.Issues, + issue => issue.Severity == IssueSeverity.Error + && issue.Kind == IssueKind.InvalidAttributeValue + && issue.Message.Contains("from", StringComparison.Ordinal)); + } +} diff --git a/ExcelReport/ExcelReportLib.Tests/ExcelTemplateValidatorTests.cs b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateValidatorTests.cs new file mode 100644 index 0000000..31fc62a --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/ExcelTemplateValidatorTests.cs @@ -0,0 +1,124 @@ +using ExcelReportLib.DSL; +using ExcelReportLib.ExcelTemplate; +using ExcelReportLib.ExcelTemplate.Model; + +namespace ExcelReportLib.Tests; + +/// +/// Provides tests for . +/// +public sealed class ExcelTemplateValidatorTests +{ + /// + /// Verifies that merged range crossing component boundary returns error. + /// + [Fact] + public void Validate_MergedRangeCrossingComponentBoundary_ReturnsError() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet( + "__component_Header", + cells: + [ + new ExcelTemplateCell("A1", 1, 1, "Title", null, null), + ], + mergedRanges: ["A1:C1"]), + ], + definedNames: new Dictionary(StringComparer.Ordinal) + { + ["__component_range_Header"] = "'__component_Header'!$A$1:$B$1", + }); + var resolver = new ExcelTemplateComponentRangeResolver(); + var ranges = resolver.Resolve(workbook); + var validator = new ExcelTemplateValidator(); + + var result = validator.Validate(workbook, ranges.Ranges); + + Assert.Contains( + result.Issues, + issue => issue.Severity == IssueSeverity.Error && + issue.Kind == IssueKind.MergedCellBoundaryViolation && + issue.Message.Contains("__component_Header", StringComparison.Ordinal)); + } + + /// + /// Verifies that malformed use trigger returns cell-scoped error. + /// + [Fact] + public void Validate_InvalidUseTrigger_ReturnsError() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet( + "Summary", + cells: + [ + new ExcelTemplateCell("B3", 3, 2, "{{use:ItemRow, from:@items}}", null, null), + ]), + ]); + var validator = new ExcelTemplateValidator(); + + var result = validator.Validate(workbook, []); + + Assert.Contains( + result.Issues, + issue => issue.Severity == IssueSeverity.Error && + issue.Kind == IssueKind.InvalidAttributeValue && + issue.Message.Contains("Summary", StringComparison.Ordinal) && + issue.Message.Contains("B3", StringComparison.Ordinal)); + } + + /// + /// Verifies that conditional formatting is reported as unsupported for the initial release. + /// + [Fact] + public void Validate_SheetWithConditionalFormatting_ReturnsUnsupportedFeature() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet( + "Summary", + hasConditionalFormatting: true), + ]); + var validator = new ExcelTemplateValidator(); + + var result = validator.Validate(workbook, []); + + Assert.Contains( + result.Issues, + issue => issue.Severity == IssueSeverity.Error && + issue.Kind == IssueKind.UnsupportedExcelTemplateFeature && + issue.Message.Contains("conditional formatting", StringComparison.OrdinalIgnoreCase)); + } + + /// + /// Verifies that use trigger referencing unknown component returns undefined component error. + /// + [Fact] + public void Validate_UseTriggerReferencingUnknownComponent_ReturnsError() + { + var workbook = new ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplateSheet( + "Summary", + cells: + [ + new ExcelTemplateCell("A1", 1, 1, "{{use:Missing}}", null, null), + ]), + ]); + var validator = new ExcelTemplateValidator(); + + var result = validator.Validate(workbook, []); + + Assert.Contains( + result.Issues, + issue => issue.Severity == IssueSeverity.Error && + issue.Kind == IssueKind.UndefinedComponent && + issue.Message.Contains("Missing", StringComparison.Ordinal)); + } +} diff --git a/ExcelReport/ExcelReportLib.Tests/LayoutEngineTests.cs b/ExcelReport/ExcelReportLib.Tests/LayoutEngineTests.cs index ace5b39..a37ddd7 100644 --- a/ExcelReport/ExcelReportLib.Tests/LayoutEngineTests.cs +++ b/ExcelReport/ExcelReportLib.Tests/LayoutEngineTests.cs @@ -979,6 +979,30 @@ public void Expand_FormulaRefAndFormulaPlaceholder_PreservedForStateBuild() Assert.Equal("=SUM(#{Detail.Value:Detail.ValueEnd})", totalsCell.Formula); } + /// + /// Verifies that explicit cell formula is preserved for state build. + /// + [Fact] + public void Expand_CellFormula_PreservedForStateBuild() + { + var plan = Expand( + """ + + + + + + """); + + var cell = Assert.Single(Assert.Single(plan.Sheets).Cells); + + Assert.Equal(2, cell.Row); + Assert.Equal(3, cell.Col); + Assert.Null(cell.Value); + Assert.Equal("=SUM(B2:B10)", cell.Formula); + Assert.Empty(plan.Issues); + } + /// /// Verifies that expression value returning '=...' is treated as Excel formula. /// @@ -1071,6 +1095,156 @@ public void Expand_GridAutoSize_AccountsForChildOffsetsInRepeatDirections() Assert.Equal(15, cellsByValue["R2"].Col); } + /// + /// Verifies that use style overflow none does not extend seed styles into overflow area. + /// + [Fact] + public void Expand_UseStyleOverflowNone_DoesNotCopySeedStyles() + { + var plan = Expand( + """ + + + + + + + + + + + + + + + + """); + + var sheet = Assert.Single(plan.Sheets); + var overflowCell = sheet.Cells.Single(cell => cell.Row == 1 && cell.Col == 4); + + Assert.Null(overflowCell.StylePlan.FillColor); + Assert.DoesNotContain( + plan.Issues, + issue => issue.Kind == IssueKind.TemplateRangeOverflow && issue.Severity is IssueSeverity.Error or IssueSeverity.Fatal); + } + + /// + /// Verifies that use style overflow edge copies seed styles into overflow area. + /// + [Fact] + public void Expand_UseStyleOverflowEdge_CopiesSeedStyles() + { + var plan = Expand( + """ + + + + + + + + + + + + + + + + """); + + var sheet = Assert.Single(plan.Sheets); + var overflowCell = sheet.Cells.Single(cell => cell.Row == 1 && cell.Col == 4); + var anchorCell = sheet.Cells.Single(cell => cell.Row == 1 && cell.Col == 3); + + Assert.Equal("#FFDD99", anchorCell.StylePlan.FillColor); + Assert.Equal("#FFDD99", overflowCell.StylePlan.FillColor); + Assert.Contains( + plan.Issues, + issue => issue.Kind == IssueKind.TemplateRangeOverflow && issue.Severity == IssueSeverity.Warning); + } + + /// + /// Verifies that use style overflow edge copies seed styles downward into overflow rows. + /// + [Fact] + public void Expand_UseStyleOverflowEdge_CopiesSeedStylesDownward() + { + var plan = Expand( + """ + + + + + + + + + + + + + + + + """); + + var sheet = Assert.Single(plan.Sheets); + var anchorCell = sheet.Cells.Single(cell => cell.Row == 3 && cell.Col == 1); + var overflowCell = sheet.Cells.Single(cell => cell.Row == 4 && cell.Col == 1); + + Assert.Equal("#99DDFF", anchorCell.StylePlan.FillColor); + Assert.Equal("#99DDFF", overflowCell.StylePlan.FillColor); + Assert.Contains( + plan.Issues, + issue => issue.Kind == IssueKind.TemplateRangeOverflow && issue.Severity == IssueSeverity.Warning); + } + + /// + /// Verifies that use style overflow edge copies corner seed styles into overflow corner cells. + /// + [Fact] + public void Expand_UseStyleOverflowEdge_CopiesSeedStylesIntoOverflowCorner() + { + var plan = Expand( + """ + + + + + + + + + + + + + + + + """); + + var sheet = Assert.Single(plan.Sheets); + var anchorCornerCell = sheet.Cells.Single(cell => cell.Row == 3 && cell.Col == 4); + var overflowCornerCell = sheet.Cells.Single(cell => cell.Row == 4 && cell.Col == 5); + + Assert.Equal("#DDBBFF", anchorCornerCell.StylePlan.FillColor); + Assert.Equal("#DDBBFF", overflowCornerCell.StylePlan.FillColor); + Assert.Contains( + plan.Issues, + issue => issue.Kind == IssueKind.TemplateRangeOverflow && issue.Severity == IssueSeverity.Warning); + } + /// /// Verifies that expand sheet from expression expands multiple sheets. /// diff --git a/ExcelReport/ExcelReportLib.Tests/LayoutNodeTests.cs b/ExcelReport/ExcelReportLib.Tests/LayoutNodeTests.cs index 1e595e2..aded668 100644 --- a/ExcelReport/ExcelReportLib.Tests/LayoutNodeTests.cs +++ b/ExcelReport/ExcelReportLib.Tests/LayoutNodeTests.cs @@ -90,6 +90,24 @@ public void Parse_Cell_FormulaRefScope_ReadsAttribute() Assert.DoesNotContain(issues, issue => issue.Severity is IssueSeverity.Error or IssueSeverity.Fatal); } + /// + /// Verifies that parse cell formula attribute reads formula raw. + /// + [Fact] + public void Parse_Cell_Formula_ReadsAttribute() + { + var issues = new List(); + var cellElement = XElement.Parse( + """ + + """); + + var cell = Assert.IsType(LayoutNodeAst.LayoutNodeAstFactory(cellElement, issues)); + + Assert.Equal("SUM(B2:B10)", cell.FormulaRaw); + Assert.DoesNotContain(issues, issue => issue.Severity is IssueSeverity.Error or IssueSeverity.Fatal); + } + /// /// Verifies that parse cell invalid formula ref scope falls back to global with warning. /// @@ -191,6 +209,24 @@ public void Parse_Use_HasAreaAttribute() Assert.Equal("Title", use.ComponentName); } + /// + /// Verifies that parse use reads style overflow attribute. + /// + [Fact] + public void Parse_Use_StyleOverflow_ReadsAttribute() + { + var issues = new List(); + var useElement = XElement.Parse( + """ + + """); + + var use = Assert.IsType(LayoutNodeAst.LayoutNodeAstFactory(useElement, issues)); + + Assert.Equal("edge", use.StyleOverflow); + Assert.DoesNotContain(issues, issue => issue.Severity is IssueSeverity.Error or IssueSeverity.Fatal); + } + /// /// Verifies that parse grid child nodes. /// @@ -231,4 +267,3 @@ public void Parse_Grid_HasAreaAttribute() Assert.Equal("GridArea", grid.AreaName); } } - diff --git a/ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd b/ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd index a16f95e..10bd2b6 100644 --- a/ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd +++ b/ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd @@ -295,6 +295,7 @@ + @@ -313,6 +314,7 @@ + @@ -330,6 +332,13 @@ + + + + + + + diff --git a/ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Debug.xml b/ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Debug.xml new file mode 100644 index 0000000..02f0dac --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Debug.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Dsl.xml b/ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Dsl.xml new file mode 100644 index 0000000..d7d7cdf --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Dsl.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ExcelReport/ExcelReportLib.Tests/ValidateDslTests.cs b/ExcelReport/ExcelReportLib.Tests/ValidateDslTests.cs index 816c7e8..c77d9c4 100644 --- a/ExcelReport/ExcelReportLib.Tests/ValidateDslTests.cs +++ b/ExcelReport/ExcelReportLib.Tests/ValidateDslTests.cs @@ -292,6 +292,56 @@ public void ValidateDsl_SheetVarElementWithoutFrom_ReturnsError() && issue.Message.Contains("from")); } + /// + /// Verifies that validate DSL formula and value conflict returns error. + /// + [Fact] + public void ValidateDsl_CellFormulaAndValueConflict_ReturnsError() + { + var result = ParseDsl( + """ + + + + + + """); + + Assert.Contains( + result.Issues, + issue => issue.Severity == IssueSeverity.Error + && issue.Kind == IssueKind.InvalidAttributeValue + && issue.Message.Contains("formula", StringComparison.Ordinal) + && issue.Message.Contains("value", StringComparison.Ordinal)); + } + + /// + /// Verifies that validate DSL invalid style overflow returns error. + /// + [Fact] + public void ValidateDsl_InvalidStyleOverflow_ReturnsError() + { + var result = ParseDsl( + """ + + + + + + + + + + + """); + + Assert.Contains( + result.Issues, + issue => issue.Severity == IssueSeverity.Error + && issue.Kind == IssueKind.InvalidAttributeValue + && issue.Message.Contains("styleOverflow", StringComparison.Ordinal)); + } + private static DslParseResult ParseDsl(string xml) => DslParser.ParseFromText( xml, @@ -301,4 +351,3 @@ private static DslParseResult ParseDsl(string xml) => }); } - diff --git a/ExcelReport/ExcelReportLib.Tests/XmlTemplateSerializerTests.cs b/ExcelReport/ExcelReportLib.Tests/XmlTemplateSerializerTests.cs new file mode 100644 index 0000000..bca2e61 --- /dev/null +++ b/ExcelReport/ExcelReportLib.Tests/XmlTemplateSerializerTests.cs @@ -0,0 +1,175 @@ +using System.Xml.Linq; +using ExcelReportLib.DSL; +using ExcelReportLib.ExcelTemplate; + +namespace ExcelReportLib.Tests; + +/// +/// Provides tests for . +/// +public sealed class XmlTemplateSerializerTests +{ + /// + /// Verifies that serializer writes DSL-compatible workbook, component, sheet, cell, use, and repeat structures. + /// + [Fact] + public void Serialize_WritesDslCompatibleWorkbookComponentsSheetsAndItems() + { + var builder = new ExcelTemplateOutputContractBuilder(); + var contract = builder.Build(ExcelTemplateOutputContractFixture.CreateStandardWorkbook()); + var serializer = new XmlTemplateSerializer(); + + var document = serializer.Serialize(contract); + var root = Assert.IsType(document.Root); + + Assert.Equal("workbook", root.Name.LocalName); + Assert.Equal("urn:excelreport:v2", root.Name.NamespaceName); + + var header = root.Elements(root.Name.Namespace + "component").Single(element => (string?)element.Attribute("name") == "Header"); + var grid = Assert.Single(header.Elements(root.Name.Namespace + "grid")); + Assert.Equal("2", (string?)grid.Attribute("rows")); + Assert.Equal("2", (string?)grid.Attribute("cols")); + + var headerItems = grid.Elements().ToArray(); + Assert.Equal("cell", headerItems[0].Name.LocalName); + Assert.Equal("1", (string?)headerItems[0].Attribute("r")); + Assert.Equal("1", (string?)headerItems[0].Attribute("c")); + Assert.Equal("請求書", (string?)headerItems[0].Attribute("value")); + Assert.Equal("repeat", headerItems[1].Name.LocalName); + Assert.Equal("2", (string?)headerItems[1].Attribute("r")); + Assert.Equal("1", (string?)headerItems[1].Attribute("c")); + Assert.Equal("@(root.Items)", (string?)headerItems[1].Attribute("from")); + Assert.Equal("item", (string?)headerItems[1].Attribute("var")); + Assert.Equal("down", (string?)headerItems[1].Attribute("direction")); + Assert.Equal("use", headerItems[1].Elements().Single().Name.LocalName); + Assert.Equal("ItemRow", (string?)headerItems[1].Elements().Single().Attribute("component")); + Assert.Equal("cell", headerItems[2].Name.LocalName); + Assert.Equal("SUM(C1:C3)", (string?)headerItems[2].Attribute("formula")); + + var invoice = Assert.Single(root.Elements(root.Name.Namespace + "sheet")); + Assert.Equal("Invoice", (string?)invoice.Attribute("name")); + Assert.Equal("use", invoice.Elements().First().Name.LocalName); + Assert.Equal("Header", (string?)invoice.Elements().First().Attribute("component")); + var itemRow = root.Elements(root.Name.Namespace + "component").Single(element => (string?)element.Attribute("name") == "ItemRow"); + var itemNameCell = Assert.Single(itemRow.Descendants(root.Name.Namespace + "cell")); + Assert.Equal("@(item.Name)", (string?)itemNameCell.Attribute("value")); + + var parseResult = DslParser.ParseFromText( + document.ToString(), + new DslParserOptions { EnableSchemaValidation = true }); + Assert.NotNull(parseResult.Root); + Assert.DoesNotContain(parseResult.Issues, issue => issue.Severity == IssueSeverity.Fatal); + } + + /// + /// Verifies that serializer keeps DSL compatibility while preserving unresolved context and issues in comments. + /// + [Fact] + public void Serialize_UnresolvedComponentAndIssues_ArePreservedInComments() + { + var builder = new ExcelTemplateOutputContractBuilder(); + var contract = builder.Build(ExcelTemplateOutputContractFixture.CreateWorkbookWithIssues()); + var serializer = new XmlTemplateSerializer(); + + var document = serializer.Serialize(contract); + var root = Assert.IsType(document.Root); + + Assert.Empty(root.Elements(root.Name.Namespace + "component")); + var comments = root.Nodes().OfType().Select(comment => comment.Value).ToArray(); + Assert.Contains(comments, comment => comment.Contains("unresolved-component", StringComparison.Ordinal)); + Assert.Contains(comments, comment => comment.Contains("EmptyComponentRange", StringComparison.Ordinal)); + Assert.Contains(comments, comment => comment.Contains("UnsupportedExcelTemplateFeature", StringComparison.Ordinal)); + + var summary = Assert.Single(root.Elements(root.Name.Namespace + "sheet")); + var malformedCell = Assert.Single(summary.Elements(root.Name.Namespace + "cell")); + Assert.Equal("{{use:Missing", (string?)malformedCell.Attribute("value")); + + var parseResult = DslParser.ParseFromText( + document.ToString(), + new DslParserOptions { EnableSchemaValidation = true }); + Assert.NotNull(parseResult.Root); + Assert.DoesNotContain(parseResult.Issues, issue => issue.Severity == IssueSeverity.Fatal); + } + + /// + /// Verifies that style-only cells are serialized as empty DSL cells without breaking schema compatibility. + /// + [Fact] + public void Serialize_StyleOnlyCell_RemainsDslCompatible() + { + var workbook = new ExcelTemplate.Model.ExcelTemplateWorkbook( + sheets: + [ + new ExcelTemplate.Model.ExcelTemplateSheet( + "__component_Header", + [ + new ExcelTemplate.Model.ExcelTemplateCell("A1", 1, 1, "Title", null, null), + new ExcelTemplate.Model.ExcelTemplateCell("B1", 1, 2, null, null, new ExcelTemplate.Model.ExcelTemplateStyle(11)), + ]), + new ExcelTemplate.Model.ExcelTemplateSheet("Invoice"), + ], + definedNames: new Dictionary(StringComparer.Ordinal) + { + ["__component_range_Header"] = "'__component_Header'!$A$1:$B$1", + }); + + var builder = new ExcelTemplateOutputContractBuilder(); + var contract = builder.Build(workbook); + var serializer = new XmlTemplateSerializer(); + + var document = serializer.Serialize(contract); + var root = Assert.IsType(document.Root); + var header = Assert.Single(root.Elements(root.Name.Namespace + "component")); + var cells = header.Descendants(root.Name.Namespace + "cell").ToArray(); + Assert.Equal(2, cells.Length); + Assert.Null(cells[1].Attribute("value")); + Assert.Null(cells[1].Attribute("formula")); + + var parseResult = DslParser.ParseFromText( + document.ToString(), + new DslParserOptions { EnableSchemaValidation = true }); + Assert.NotNull(parseResult.Root); + Assert.DoesNotContain(parseResult.Issues, issue => issue.Severity == IssueSeverity.Fatal); + } + + /// + /// Verifies that explicit styleOverflow values are emitted on use and repeat-use nodes. + /// + [Fact] + public void Serialize_ExplicitStyleOverflow_EmitsDslAttributes() + { + var contract = new ExcelTemplate.Model.ExcelTemplateOutputContract( + components: + [ + new ExcelTemplate.Model.ExcelTemplateOutputComponent( + "Header", + "__component_Header", + "A1:A2", + isRangeResolved: true, + items: + [ + new ExcelTemplate.Model.ExcelTemplateOutputUse("A1", 1, 1, null, "ItemRow", "edge"), + new ExcelTemplate.Model.ExcelTemplateOutputRepeatUse("A2", 2, 1, null, "ItemRow", "@items", "item", "down", "edge"), + ]), + ], + sheets: + [ + new ExcelTemplate.Model.ExcelTemplateOutputSheet("Invoice"), + ]); + var serializer = new XmlTemplateSerializer(); + + var document = serializer.Serialize(contract); + var root = Assert.IsType(document.Root); + var use = root.Descendants(root.Name.Namespace + "use").First(); + var repeatUse = root.Descendants(root.Name.Namespace + "repeat").Single().Elements(root.Name.Namespace + "use").Single(); + + Assert.Equal("edge", (string?)use.Attribute("styleOverflow")); + Assert.Equal("edge", (string?)repeatUse.Attribute("styleOverflow")); + + var parseResult = DslParser.ParseFromText( + document.ToString(), + new DslParserOptions { EnableSchemaValidation = true }); + Assert.NotNull(parseResult.Root); + Assert.DoesNotContain(parseResult.Issues, issue => issue.Severity == IssueSeverity.Fatal); + } +} diff --git a/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/CellAst.cs b/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/CellAst.cs index 1147bc9..042ad96 100644 --- a/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/CellAst.cs +++ b/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/CellAst.cs @@ -19,6 +19,10 @@ public sealed class CellAst : LayoutNodeAst, IAst /// public string? ValueRaw { get; init; } /// + /// Gets or sets the formula raw. + /// + public string? FormulaRaw { get; init; } + /// /// Gets or sets the style ref shortcut. /// public string? StyleRefShortcut { get; init; } @@ -39,6 +43,7 @@ public sealed class CellAst : LayoutNodeAst, IAst public CellAst(XElement elem, List issues) { var valueAttr = elem.Attribute("value"); + var formulaAttr = elem.Attribute("formula"); var styleRefAttr = elem.Attribute("styleRef"); var formulaRefAttr = elem.Attribute("formulaRef"); var formulaRefScopeAttr = elem.Attribute("formulaRefScope"); @@ -49,10 +54,10 @@ public CellAst(XElement elem, List issues) elem.GetFirstOrDefaultChildElement("value"), "value", issues); + FormulaRaw = formulaAttr?.Value; StyleRefShortcut = styleRefAttr?.Value; FormulaRef = formulaRefAttr?.Value; FormulaRefScope = NormalizeFormulaRefScope(formulaRefScopeAttr?.Value, elem, issues); - // Todo: ValueRaw から式のパース } private static string? NormalizeFormulaRefScope(string? rawScope, XElement owner, List issues) diff --git a/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/UseAst.cs b/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/UseAst.cs index 5f724e1..8f9a18d 100644 --- a/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/UseAst.cs +++ b/ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/UseAst.cs @@ -26,6 +26,14 @@ public sealed class UseAst : LayoutNodeAst, INamedAreaTarget /// Gets or sets the with expr raw. /// public string? WithExprRaw { get; init; } + /// + /// Gets the style overflow mode. + /// + public string StyleOverflow { get; init; } = "none"; + /// + /// Gets a value indicating whether style overflow was explicitly specified. + /// + public bool HasStyleOverflowAttribute { get; init; } /// /// コンポーネント参照先(解析フェーズで設定される)s @@ -65,10 +73,33 @@ public UseAst(XElement elem, List issues) var areaAttr = elem.Attribute("area"); var withAttr = elem.Attribute("with"); + var styleOverflowAttr = elem.Attribute("styleOverflow"); ComponentName = nameAttr.Value; AreaName = string.IsNullOrWhiteSpace(areaAttr?.Value) ? null : areaAttr.Value.Trim(); WithExprRaw = withAttr?.Value; + StyleOverflow = NormalizeStyleOverflow(styleOverflowAttr?.Value); + HasStyleOverflowAttribute = styleOverflowAttr is not null; + } + + private static string NormalizeStyleOverflow(string? raw) + { + if (string.IsNullOrWhiteSpace(raw)) + { + return "none"; + } + + if (string.Equals(raw, "none", StringComparison.OrdinalIgnoreCase)) + { + return "none"; + } + + if (string.Equals(raw, "edge", StringComparison.OrdinalIgnoreCase)) + { + return "edge"; + } + + return raw.Trim(); } } } diff --git a/ExcelReport/ExcelReportLib/DSL/DslParser.cs b/ExcelReport/ExcelReportLib/DSL/DslParser.cs index d1a6b04..9c5b15d 100644 --- a/ExcelReport/ExcelReportLib/DSL/DslParser.cs +++ b/ExcelReport/ExcelReportLib/DSL/DslParser.cs @@ -248,6 +248,8 @@ private static void ValidateDsl(WorkbookAst root, List issues, DslParserO ValidateDuplicateSheetNames(root, issues); ValidateStyleReferences(root, styleIndex, issues); ValidateComponentReferences(root, componentIndex, issues); + ValidateCellContracts(root, issues); + ValidateUseContracts(root, issues); ValidateRepeatConstraints(root, issues); ValidateSheetConstraints(root, issues); ValidateSheetOptions(root, issues); @@ -569,6 +571,43 @@ private static void ValidateComponentReferences( } } + private static void ValidateCellContracts(WorkbookAst root, List issues) + { + foreach (var cell in EnumerateLayoutNodes(root).OfType()) + { + if (!string.IsNullOrWhiteSpace(cell.ValueRaw) && !string.IsNullOrWhiteSpace(cell.FormulaRaw)) + { + issues.Add(new Issue + { + Severity = IssueSeverity.Error, + Kind = IssueKind.InvalidAttributeValue, + Message = " 要素で value 属性と formula 属性は同時に指定できません。", + Span = cell.Span, + }); + } + } + } + + private static void ValidateUseContracts(WorkbookAst root, List issues) + { + foreach (var use in EnumerateLayoutNodes(root).OfType()) + { + if (string.Equals(use.StyleOverflow, "none", StringComparison.Ordinal) || + string.Equals(use.StyleOverflow, "edge", StringComparison.Ordinal)) + { + continue; + } + + issues.Add(new Issue + { + Severity = IssueSeverity.Error, + Kind = IssueKind.InvalidAttributeValue, + Message = $" 要素の styleOverflow には 'none' または 'edge' を指定してください。'{use.StyleOverflow}' は無効です。", + Span = use.Span, + }); + } + } + private static void ValidateRepeatConstraints(WorkbookAst root, List issues) { @@ -1039,6 +1078,26 @@ public enum IssueKind /// CoordinateOutOfRange, /// + /// A template expansion exceeded the anchor range and emitted an overflow warning. + /// + TemplateRangeOverflow, + /// + /// An ExcelTemplate component range definition was malformed or pointed to the wrong sheet. + /// + InvalidComponentRange, + /// + /// An ExcelTemplate component range could not be inferred because it had no candidate cells. + /// + EmptyComponentRange, + /// + /// An ExcelTemplate merged cell crossed the resolved component boundary. + /// + MergedCellBoundaryViolation, + /// + /// The ExcelTemplate workbook used a feature that is intentionally unsupported in the initial release. + /// + UnsupportedExcelTemplateFeature, + /// /// A formula reference series must be a single continuous one-dimensional range. /// FormulaRefSeriesNot1DContinuous, diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/DslEmitter.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/DslEmitter.cs new file mode 100644 index 0000000..f63885c --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/DslEmitter.cs @@ -0,0 +1,46 @@ +using System.Text; +using System.Xml; +using ExcelReportLib.ExcelTemplate.Model; + +namespace ExcelReportLib.ExcelTemplate; + +/// +/// Emits DSL text from the normalized ExcelTemplate output contract. +/// +public sealed class DslEmitter +{ + private readonly XmlTemplateSerializer xmlTemplateSerializer = new(); + + /// + /// Emits DSL-compatible XML text from the output contract. + /// + /// The normalized output contract. + /// The DSL text. + public string Emit(ExcelTemplateOutputContract contract) + { + ArgumentNullException.ThrowIfNull(contract); + + var document = xmlTemplateSerializer.Serialize(contract); + var settings = new XmlWriterSettings + { + Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), + Indent = true, + OmitXmlDeclaration = false, + NewLineChars = Environment.NewLine, + NewLineHandling = NewLineHandling.Replace, + }; + + using var stringWriter = new Utf8StringWriter(); + using (var xmlWriter = XmlWriter.Create(stringWriter, settings)) + { + document.Save(xmlWriter); + } + + return stringWriter.ToString(); + } + + private sealed class Utf8StringWriter : StringWriter + { + public override Encoding Encoding => new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + } +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateComponentRangeResolver.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateComponentRangeResolver.cs new file mode 100644 index 0000000..98be39a --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateComponentRangeResolver.cs @@ -0,0 +1,392 @@ +using System.Text; +using ExcelReportLib.DSL; +using ExcelReportLib.ExcelTemplate.Model; + +namespace ExcelReportLib.ExcelTemplate; + +/// +/// Resolves component ranges from extracted Excel template workbooks. +/// +public sealed class ExcelTemplateComponentRangeResolver +{ + private const string ComponentSheetPrefix = "__component_"; + private const string ComponentRangeNamePrefix = "__component_range_"; + + /// + /// Resolves component ranges for all component sheets in the workbook. + /// + /// The extracted workbook. + /// The resolved ranges and issues. + public ExcelTemplateComponentRangeResolutionResult Resolve(ExcelTemplateWorkbook workbook) + { + ArgumentNullException.ThrowIfNull(workbook); + + var ranges = new List(); + var issues = new List(); + + foreach (var sheet in workbook.Sheets.Where(IsComponentSheet)) + { + var componentName = sheet.Name[ComponentSheetPrefix.Length..]; + var definedName = ComponentRangeNamePrefix + componentName; + + if (workbook.DefinedNames.TryGetValue(definedName, out var explicitReference)) + { + if (TryResolveExplicitRange( + sheet, + componentName, + explicitReference, + out var rangeReference, + out var explicitIssueKind, + out var explicitMessage)) + { + ranges.Add(new ExcelTemplateComponentRange(componentName, sheet.Name, rangeReference)); + } + else + { + issues.Add(new Issue + { + Severity = IssueSeverity.Error, + Kind = explicitIssueKind, + Message = explicitMessage, + }); + } + + continue; + } + + if (TryResolveAutoRange(sheet, out var autoReference)) + { + ranges.Add(new ExcelTemplateComponentRange(componentName, sheet.Name, autoReference)); + continue; + } + + issues.Add(new Issue + { + Severity = IssueSeverity.Error, + Kind = IssueKind.EmptyComponentRange, + Message = $"component '{componentName}' does not contain any candidate cells for range detection.", + }); + } + + return new ExcelTemplateComponentRangeResolutionResult(ranges, issues); + } + + private static bool IsComponentSheet(ExcelTemplateSheet sheet) => + sheet.Name.StartsWith(ComponentSheetPrefix, StringComparison.Ordinal) && + sheet.Name.Length > ComponentSheetPrefix.Length; + + private static bool TryResolveExplicitRange( + ExcelTemplateSheet sheet, + string componentName, + string explicitReference, + out string normalizedReference, + out IssueKind issueKind, + out string message) + { + normalizedReference = string.Empty; + issueKind = IssueKind.InvalidComponentRange; + message = string.Empty; + + if (!TryParseSheetQualifiedRange( + explicitReference, + out var actualSheetName, + out var topRow, + out var leftColumn, + out var bottomRow, + out var rightColumn)) + { + message = $"component '{componentName}' has invalid explicit range: {explicitReference}"; + return false; + } + + if (!string.Equals(sheet.Name, actualSheetName, StringComparison.Ordinal)) + { + message = $"component '{componentName}' explicit range points to '{actualSheetName}' instead of '{sheet.Name}'."; + return false; + } + + if (topRow <= 0 || leftColumn <= 0 || bottomRow < topRow || rightColumn < leftColumn) + { + message = $"component '{componentName}' has invalid explicit range: {explicitReference}"; + return false; + } + + if (!HasCandidateInRange(sheet, topRow, leftColumn, bottomRow, rightColumn)) + { + issueKind = IssueKind.EmptyComponentRange; + message = $"component '{componentName}' explicit range does not contain any candidate cells."; + return false; + } + + normalizedReference = ToRangeReference(topRow, leftColumn, bottomRow, rightColumn); + return true; + } + + private static bool TryResolveAutoRange( + ExcelTemplateSheet sheet, + out string reference) + { + reference = string.Empty; + + var minRow = int.MaxValue; + var minColumn = int.MaxValue; + var maxRow = 0; + var maxColumn = 0; + + foreach (var cell in sheet.Cells.Where(IsCandidateCell)) + { + minRow = Math.Min(minRow, cell.Row); + minColumn = Math.Min(minColumn, cell.Column); + maxRow = Math.Max(maxRow, cell.Row); + maxColumn = Math.Max(maxColumn, cell.Column); + } + + foreach (var mergedRange in sheet.MergedRanges) + { + if (!TryParseLocalRange(mergedRange, out var topRow, out var leftColumn, out var bottomRow, out var rightColumn)) + { + continue; + } + + minRow = Math.Min(minRow, topRow); + minColumn = Math.Min(minColumn, leftColumn); + maxRow = Math.Max(maxRow, bottomRow); + maxColumn = Math.Max(maxColumn, rightColumn); + } + + if (maxRow == 0 || maxColumn == 0) + { + return false; + } + + reference = ToRangeReference(minRow, minColumn, maxRow, maxColumn); + return true; + } + + private static bool IsCandidateCell(ExcelTemplateCell cell) => + !string.IsNullOrWhiteSpace(cell.Value) || + !string.IsNullOrWhiteSpace(cell.Formula) || + cell.Style is not null; + + private static bool HasCandidateInRange( + ExcelTemplateSheet sheet, + int topRow, + int leftColumn, + int bottomRow, + int rightColumn) + { + if (sheet.Cells.Any(cell => + IsCandidateCell(cell) && + cell.Row >= topRow && + cell.Row <= bottomRow && + cell.Column >= leftColumn && + cell.Column <= rightColumn)) + { + return true; + } + + foreach (var mergedRange in sheet.MergedRanges) + { + if (!TryParseLocalRange(mergedRange, out var mergedTopRow, out var mergedLeftColumn, out var mergedBottomRow, out var mergedRightColumn)) + { + continue; + } + + var intersects = + mergedBottomRow >= topRow && + mergedTopRow <= bottomRow && + mergedRightColumn >= leftColumn && + mergedLeftColumn <= rightColumn; + if (intersects) + { + return true; + } + } + + return false; + } + + private static bool TryParseSheetQualifiedRange( + string reference, + out string sheetName, + out int topRow, + out int leftColumn, + out int bottomRow, + out int rightColumn) + { + sheetName = string.Empty; + topRow = 0; + leftColumn = 0; + bottomRow = 0; + rightColumn = 0; + + var separatorIndex = reference.LastIndexOf('!'); + if (separatorIndex <= 0 || separatorIndex == reference.Length - 1) + { + return false; + } + + sheetName = NormalizeSheetName(reference[..separatorIndex]); + if (string.IsNullOrWhiteSpace(sheetName)) + { + return false; + } + + return TryParseLocalRange(reference[(separatorIndex + 1)..], out topRow, out leftColumn, out bottomRow, out rightColumn); + } + + private static string NormalizeSheetName(string token) + { + var trimmed = token.Trim(); + if (trimmed.Length >= 2 && trimmed[0] == '\'' && trimmed[^1] == '\'') + { + return trimmed[1..^1].Replace("''", "'", StringComparison.Ordinal); + } + + return trimmed; + } + + private static bool TryParseLocalRange( + string reference, + out int topRow, + out int leftColumn, + out int bottomRow, + out int rightColumn) + { + topRow = 0; + leftColumn = 0; + bottomRow = 0; + rightColumn = 0; + + if (string.IsNullOrWhiteSpace(reference) || reference.Contains(',', StringComparison.Ordinal)) + { + return false; + } + + var parts = reference.Split(':', StringSplitOptions.TrimEntries); + if (parts.Length is < 1 or > 2) + { + return false; + } + + if (!TryParseCellReference(parts[0], out topRow, out leftColumn)) + { + return false; + } + + if (parts.Length == 1) + { + bottomRow = topRow; + rightColumn = leftColumn; + return true; + } + + if (!TryParseCellReference(parts[1], out bottomRow, out rightColumn)) + { + return false; + } + + return bottomRow >= topRow && rightColumn >= leftColumn; + } + + private static bool TryParseCellReference(string token, out int row, out int column) + { + row = 0; + column = 0; + + if (string.IsNullOrWhiteSpace(token)) + { + return false; + } + + var trimmed = token.Trim().Replace("$", string.Empty, StringComparison.Ordinal); + var letters = new StringBuilder(); + var digits = new StringBuilder(); + + foreach (var character in trimmed) + { + if (char.IsLetter(character)) + { + if (digits.Length > 0) + { + return false; + } + + letters.Append(char.ToUpperInvariant(character)); + continue; + } + + if (!char.IsDigit(character)) + { + return false; + } + + digits.Append(character); + } + + if (letters.Length == 0 || + digits.Length == 0 || + !int.TryParse(digits.ToString(), out row)) + { + return false; + } + + column = 0; + foreach (var character in letters.ToString()) + { + column = checked((column * 26) + (character - 'A' + 1)); + } + + return column > 0; + } + + private static string ToRangeReference(int topRow, int leftColumn, int bottomRow, int rightColumn) + { + var start = ToCellReference(topRow, leftColumn); + var end = ToCellReference(bottomRow, rightColumn); + return start == end ? start : $"{start}:{end}"; + } + + private static string ToCellReference(int row, int column) + { + var current = column; + var builder = new StringBuilder(); + while (current > 0) + { + current--; + builder.Insert(0, (char)('A' + (current % 26))); + current /= 26; + } + + return builder.Append(row).ToString(); + } +} + +/// +/// Represents component range resolution output. +/// +public sealed class ExcelTemplateComponentRangeResolutionResult +{ + /// + /// Initializes a new instance of the resolution result. + /// + /// The resolved component ranges. + /// The collected issues. + public ExcelTemplateComponentRangeResolutionResult( + IReadOnlyList? ranges = null, + IReadOnlyList? issues = null) + { + Ranges = ranges?.ToArray() ?? []; + Issues = issues?.ToArray() ?? []; + } + + /// + /// Gets the resolved ranges. + /// + public IReadOnlyList Ranges { get; } + + /// + /// Gets the collected issues. + /// + public IReadOnlyList Issues { get; } +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConversionResult.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConversionResult.cs new file mode 100644 index 0000000..a9e6671 --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConversionResult.cs @@ -0,0 +1,30 @@ +using ExcelReportLib.DSL; + +namespace ExcelReportLib.ExcelTemplate; + +/// +/// Represents the result of converting an ExcelTemplate workbook to text. +/// +public sealed class ExcelTemplateConversionResult +{ + /// + /// Initializes a new instance of the conversion result. + /// + /// The emitted text. + /// The aggregated issues. + public ExcelTemplateConversionResult(string text, IReadOnlyList? issues = null) + { + Text = text ?? string.Empty; + Issues = issues?.ToArray() ?? []; + } + + /// + /// Gets the emitted text. + /// + public string Text { get; } + + /// + /// Gets the aggregated issues. + /// + public IReadOnlyList Issues { get; } +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConvertOptions.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConvertOptions.cs new file mode 100644 index 0000000..9e7493c --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConvertOptions.cs @@ -0,0 +1,12 @@ +namespace ExcelReportLib.ExcelTemplate; + +/// +/// Represents options for ExcelTemplate conversion-only APIs. +/// +public sealed class ExcelTemplateConvertOptions +{ + /// + /// Gets or sets a value indicating whether emitted text should be validated against the DSL schema. + /// + public bool EnableSchemaValidation { get; init; } = true; +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConverter.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConverter.cs new file mode 100644 index 0000000..88435a0 --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConverter.cs @@ -0,0 +1,107 @@ +using ExcelReportLib.DSL; + +namespace ExcelReportLib.ExcelTemplate; + +/// +/// Converts ExcelTemplate xlsx workbooks into DSL-compatible XML text outputs. +/// +public sealed class ExcelTemplateConverter +{ + private readonly ExcelTemplateExtractor extractor = new(); + private readonly ExcelTemplateOutputContractBuilder contractBuilder = new(); + private readonly XmlTemplateSerializer xmlTemplateSerializer = new(); + private readonly DslEmitter dslEmitter = new(); + + /// + /// Converts an xlsx workbook to DSL text. + /// + /// The source xlsx file path. + /// Optional conversion settings. + /// The conversion result. + public ExcelTemplateConversionResult ConvertToDsl(string xlsxPath, ExcelTemplateConvertOptions? options = null) + { + return ConvertInternal( + xlsxPath, + contract => dslEmitter.Emit(contract), + options); + } + + /// + /// Converts an xlsx workbook to DSL-compatible XML debug text. + /// + /// The source xlsx file path. + /// Optional conversion settings. + /// The conversion result. + public ExcelTemplateConversionResult ConvertToXmlTemplate(string xlsxPath, ExcelTemplateConvertOptions? options = null) + { + return ConvertInternal( + xlsxPath, + contract => xmlTemplateSerializer.Serialize(contract).ToString(), + options); + } + + private ExcelTemplateConversionResult ConvertInternal( + string xlsxPath, + Func emitter, + ExcelTemplateConvertOptions? options) + { + var effectiveOptions = options ?? new ExcelTemplateConvertOptions(); + var issues = new List(); + + if (string.IsNullOrWhiteSpace(xlsxPath)) + { + issues.Add(CreateLoadIssue("ExcelTemplate xlsx path is required.")); + return new ExcelTemplateConversionResult(string.Empty, issues); + } + + if (!File.Exists(xlsxPath)) + { + issues.Add(CreateLoadIssue($"ExcelTemplate file not found: {xlsxPath}")); + return new ExcelTemplateConversionResult(string.Empty, issues); + } + + try + { + var workbook = extractor.Extract(xlsxPath); + var contract = contractBuilder.Build(workbook); + issues.AddRange(contract.Issues); + + var text = emitter(contract); + + var parseResult = DslParser.ParseFromText( + text, + new DslParserOptions { EnableSchemaValidation = effectiveOptions.EnableSchemaValidation }); + issues.AddRange(parseResult.Issues); + + return new ExcelTemplateConversionResult(text, issues); + } + catch (IOException ex) + { + issues.Add(CreateLoadIssue(ex.Message)); + return new ExcelTemplateConversionResult(string.Empty, issues); + } + catch (InvalidDataException ex) + { + issues.Add(CreateLoadIssue(ex.Message)); + return new ExcelTemplateConversionResult(string.Empty, issues); + } + catch (FileFormatException ex) + { + issues.Add(CreateLoadIssue(ex.Message)); + return new ExcelTemplateConversionResult(string.Empty, issues); + } + catch (UnauthorizedAccessException ex) + { + issues.Add(CreateLoadIssue(ex.Message)); + return new ExcelTemplateConversionResult(string.Empty, issues); + } + } + + private static Issue CreateLoadIssue(string message) => + new() + { + Severity = IssueSeverity.Fatal, + Kind = IssueKind.LoadFile, + Message = message, + }; +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateExpressionNormalizer.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateExpressionNormalizer.cs new file mode 100644 index 0000000..18456c6 --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateExpressionNormalizer.cs @@ -0,0 +1,48 @@ +namespace ExcelReportLib.ExcelTemplate; + +/// +/// Normalizes ExcelTemplate expression shorthand into DSL runtime-compatible expression text. +/// +internal static class ExcelTemplateExpressionNormalizer +{ + /// + /// Normalizes an ExcelTemplate expression when it uses the shorthand @foo form. + /// + /// The raw ExcelTemplate expression text. + /// Known local repeat variable names. + /// The normalized expression text. + public static string? Normalize(string? expression, IReadOnlySet? localVariableNames = null) + { + if (string.IsNullOrWhiteSpace(expression)) + { + return expression; + } + + var trimmed = expression.Trim(); + if (!trimmed.StartsWith('@') || trimmed.StartsWith("@(", StringComparison.Ordinal)) + { + return expression; + } + + var body = trimmed[1..].Trim(); + if (string.IsNullOrWhiteSpace(body)) + { + return expression; + } + + if (IsSimpleIdentifier(body)) + { + if (localVariableNames?.Contains(body) == true) + { + return "@(" + body + ")"; + } + + return "@(root." + char.ToUpperInvariant(body[0]) + body[1..] + ")"; + } + + return "@(" + body + ")"; + } + + private static bool IsSimpleIdentifier(string value) => + value.Length > 0 && value.All(character => char.IsLetterOrDigit(character) || character == '_'); +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateExtractor.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateExtractor.cs new file mode 100644 index 0000000..fe49807 --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateExtractor.cs @@ -0,0 +1,187 @@ +using System.Text; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Spreadsheet; +using ExcelReportLib.ExcelTemplate.Model; + +namespace ExcelReportLib.ExcelTemplate; + +/// +/// Reads an Excel workbook into the ExcelTemplate intermediate model. +/// +public sealed class ExcelTemplateExtractor +{ + /// + /// Extracts workbook metadata, sheets, cells, defined names, and merged ranges from an xlsx file. + /// + /// The source xlsx file path. + /// The extracted workbook model. + public ExcelTemplateWorkbook Extract(string xlsxPath) + { + if (string.IsNullOrWhiteSpace(xlsxPath)) + { + throw new ArgumentException("xlsxPath is required.", nameof(xlsxPath)); + } + + if (!File.Exists(xlsxPath)) + { + throw new FileNotFoundException($"Excel template file not found: {xlsxPath}", xlsxPath); + } + + using var document = SpreadsheetDocument.Open(xlsxPath, false); + var workbookPart = document.WorkbookPart + ?? throw new InvalidDataException("WorkbookPart was not found."); + var workbook = workbookPart.Workbook + ?? throw new InvalidDataException("Workbook root was not found."); + + var sheets = workbook.Sheets?.Elements() + .Select(sheet => ExtractSheet(workbookPart, sheet)) + .ToArray() ?? []; + var definedNames = ExtractDefinedNames(workbook); + + return new ExcelTemplateWorkbook(sheets, definedNames); + } + + private static ExcelTemplateSheet ExtractSheet(WorkbookPart workbookPart, Sheet sheet) + { + var worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id!); + var worksheet = worksheetPart.Worksheet; + + var cells = worksheet.Descendants() + .Select(cell => ExtractCell(workbookPart, cell)) + .OrderBy(cell => cell.Row) + .ThenBy(cell => cell.Column) + .ToArray(); + var mergedRanges = worksheet.Elements() + .SelectMany(mergeCells => mergeCells.Elements()) + .Select(mergeCell => mergeCell.Reference?.Value) + .Where(reference => !string.IsNullOrWhiteSpace(reference)) + .Cast() + .ToArray(); + var hasConditionalFormatting = worksheet.Elements().Any(); + + return new ExcelTemplateSheet(sheet.Name?.Value ?? string.Empty, cells, mergedRanges, hasConditionalFormatting); + } + + private static ExcelTemplateCell ExtractCell(WorkbookPart workbookPart, Cell cell) + { + var reference = cell.CellReference?.Value ?? string.Empty; + if (!TryParseCellReference(reference, out var row, out var column)) + { + throw new InvalidDataException($"Unsupported cell reference: {reference}"); + } + + var formula = cell.CellFormula?.Text; + var value = formula is null ? ReadCellValue(workbookPart, cell) : null; + var style = cell.StyleIndex is not null + ? new ExcelTemplateStyle(cell.StyleIndex.Value) + : null; + + return new ExcelTemplateCell(reference, (int)row, (int)column, value, formula, style); + } + + private static IReadOnlyDictionary ExtractDefinedNames(Workbook workbook) + { + var definedNames = new Dictionary(StringComparer.Ordinal); + foreach (var definedName in workbook.DefinedNames?.Elements() ?? []) + { + var name = definedName.Name?.Value; + if (string.IsNullOrWhiteSpace(name)) + { + continue; + } + + definedNames[name] = definedName.Text ?? string.Empty; + } + + return definedNames; + } + + private static string? ReadCellValue(WorkbookPart workbookPart, Cell cell) + { + if (cell.DataType?.Value == CellValues.InlineString) + { + return cell.InlineString?.InnerText ?? string.Empty; + } + + if (cell.DataType?.Value == CellValues.SharedString) + { + var sharedStringIndex = cell.CellValue?.Text; + if (sharedStringIndex is null || + !int.TryParse(sharedStringIndex, out var index) || + workbookPart.SharedStringTablePart?.SharedStringTable is null) + { + return string.Empty; + } + + return workbookPart.SharedStringTablePart.SharedStringTable.Elements() + .ElementAt(index) + .InnerText; + } + + return cell.CellValue?.Text; + } + + private static bool TryParseCellReference(string reference, out uint row, out uint column) + { + if (string.IsNullOrWhiteSpace(reference)) + { + row = 0; + column = 0; + return false; + } + + var trimmed = reference.Trim().TrimStart('$'); + var letters = new StringBuilder(); + var digits = new StringBuilder(); + + foreach (var character in trimmed) + { + if (char.IsLetter(character)) + { + if (digits.Length > 0) + { + row = 0; + column = 0; + return false; + } + + letters.Append(char.ToUpperInvariant(character)); + continue; + } + + if (char.IsDigit(character)) + { + digits.Append(character); + continue; + } + + if (character != '$') + { + row = 0; + column = 0; + return false; + } + } + + if (letters.Length == 0 || digits.Length == 0 || !uint.TryParse(digits.ToString(), out row)) + { + row = 0; + column = 0; + return false; + } + + column = ColumnNameToIndex(letters.ToString()); + return column > 0; + } + + private static uint ColumnNameToIndex(string columnName) + { + uint value = 0; + foreach (var character in columnName) + { + value = checked((value * 26) + (uint)(character - 'A' + 1)); + } + + return value; + } +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateGenerateOptions.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateGenerateOptions.cs new file mode 100644 index 0000000..31cda5d --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateGenerateOptions.cs @@ -0,0 +1,19 @@ +using ExcelReportLib.Logger; + +namespace ExcelReportLib.ExcelTemplate; + +/// +/// Represents options for end-to-end ExcelTemplate report generation. +/// +public sealed class ExcelTemplateGenerateOptions +{ + /// + /// Gets or sets conversion options for the ExcelTemplate-to-DSL step. + /// + public ExcelTemplateConvertOptions? ConvertOptions { get; init; } + + /// + /// Gets or sets report generation options for the DSL-to-XLSX step. + /// + public ReportGeneratorOptions? ReportGeneratorOptions { get; init; } +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateOutputContractBuilder.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateOutputContractBuilder.cs new file mode 100644 index 0000000..949b4c9 --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateOutputContractBuilder.cs @@ -0,0 +1,329 @@ +using System.Text; +using ExcelReportLib.DSL; +using ExcelReportLib.ExcelTemplate.Model; + +namespace ExcelReportLib.ExcelTemplate; + +/// +/// Builds the normalized conversion output contract used by ExcelTemplate serializers and emitters. +/// +public sealed class ExcelTemplateOutputContractBuilder +{ + private const string ComponentSheetPrefix = "__component_"; + private static readonly IReadOnlySet EmptyVariableNames = new HashSet(StringComparer.Ordinal); + private readonly ExcelTemplateComponentRangeResolver componentRangeResolver = new(); + private readonly ExcelTemplateValidator validator = new(); + private readonly UseTriggerParser useTriggerParser = new(); + + /// + /// Builds the conversion output contract from an extracted workbook. + /// + /// The extracted workbook. + /// The normalized contract. + public ExcelTemplateOutputContract Build(ExcelTemplateWorkbook workbook) + { + ArgumentNullException.ThrowIfNull(workbook); + + var rangeResolution = componentRangeResolver.Resolve(workbook); + var validation = validator.Validate(workbook, rangeResolution.Ranges); + var variableScope = ResolveComponentVariableScopes(workbook); + var aggregatedIssues = rangeResolution.Issues + .Concat(validation.Issues) + .Concat(variableScope.Issues) + .ToArray(); + var rangesBySheet = rangeResolution.Ranges.ToDictionary(range => range.SheetName, StringComparer.Ordinal); + + var components = workbook.Sheets + .Where(IsComponentSheet) + .Select(sheet => + { + var hasRange = rangesBySheet.TryGetValue(sheet.Name, out var range); + var componentName = sheet.Name[ComponentSheetPrefix.Length..]; + var valueVariableNames = variableScope.ComponentVariableNames.TryGetValue(componentName, out var variables) + ? variables + : EmptyVariableNames; + return new ExcelTemplateOutputComponent( + componentName, + sheet.Name, + hasRange ? range!.Reference : null, + hasRange, + BuildItems(sheet, hasRange ? range!.Reference : null, valueVariableNames)); + }) + .ToArray(); + + var sheets = workbook.Sheets + .Where(sheet => !IsComponentSheet(sheet)) + .Select(sheet => new ExcelTemplateOutputSheet(sheet.Name, BuildItems(sheet, rangeReference: null, EmptyVariableNames))) + .ToArray(); + + return new ExcelTemplateOutputContract(components, sheets, aggregatedIssues); + } + + private IReadOnlyList BuildItems( + ExcelTemplateSheet sheet, + string? rangeReference, + IReadOnlySet localVariableNames) + { + var filter = TryParseRange(rangeReference, out var topRow, out var leftColumn, out var bottomRow, out var rightColumn); + var items = new List(); + + foreach (var cell in sheet.Cells + .OrderBy(candidate => candidate.Row) + .ThenBy(candidate => candidate.Column)) + { + if (filter && !IsWithinRange(cell, topRow, leftColumn, bottomRow, rightColumn)) + { + continue; + } + + items.Add(NormalizeItem(cell, localVariableNames)); + } + + return items; + } + + private ExcelTemplateOutputItem NormalizeItem(ExcelTemplateCell cell, IReadOnlySet localVariableNames) + { + var styleIndex = cell.Style?.Index; + var triggerResult = useTriggerParser.Parse(cell.Value); + + if (!triggerResult.IsTrigger || triggerResult.Trigger is null) + { + return new ExcelTemplateOutputCell( + cell.Reference, + cell.Row, + cell.Column, + styleIndex, + ExcelTemplateExpressionNormalizer.Normalize(cell.Value, localVariableNames), + cell.Formula); + } + + if (string.IsNullOrWhiteSpace(triggerResult.Trigger.FromExpression)) + { + return new ExcelTemplateOutputUse( + cell.Reference, + cell.Row, + cell.Column, + styleIndex, + triggerResult.Trigger.ComponentName, + triggerResult.Trigger.StyleOverflow); + } + + return new ExcelTemplateOutputRepeatUse( + cell.Reference, + cell.Row, + cell.Column, + styleIndex, + triggerResult.Trigger.ComponentName, + ExcelTemplateExpressionNormalizer.Normalize(triggerResult.Trigger.FromExpression)!, + triggerResult.Trigger.VariableName!, + triggerResult.Trigger.RepeatDirection ?? "down", + triggerResult.Trigger.StyleOverflow); + } + + private ComponentVariableScopeResolution ResolveComponentVariableScopes(ExcelTemplateWorkbook workbook) + { + var discoveredVariables = new Dictionary>(StringComparer.Ordinal); + var componentsWithSimpleShorthand = CollectComponentsWithSimpleShorthand(workbook); + var issues = new List(); + var componentVariableNames = new Dictionary>(StringComparer.Ordinal); + + foreach (var cell in workbook.Sheets.SelectMany(sheet => sheet.Cells)) + { + var triggerResult = useTriggerParser.Parse(cell.Value); + if (!triggerResult.IsTrigger || + triggerResult.Trigger is null || + string.IsNullOrWhiteSpace(triggerResult.Trigger.ComponentName) || + string.IsNullOrWhiteSpace(triggerResult.Trigger.VariableName)) + { + continue; + } + + if (!discoveredVariables.TryGetValue(triggerResult.Trigger.ComponentName, out var variableNames)) + { + variableNames = new HashSet(StringComparer.Ordinal); + discoveredVariables[triggerResult.Trigger.ComponentName] = variableNames; + } + + variableNames.Add(triggerResult.Trigger.VariableName); + } + + foreach (var discovered in discoveredVariables) + { + if (discovered.Value.Count == 1) + { + componentVariableNames[discovered.Key] = discovered.Value; + continue; + } + + componentVariableNames[discovered.Key] = EmptyVariableNames; + if (componentsWithSimpleShorthand.Contains(discovered.Key)) + { + issues.Add( + new Issue + { + Severity = IssueSeverity.Error, + Kind = IssueKind.InvalidAttributeValue, + Message = $"component '{discovered.Key}' is referenced by multiple repeat variables ({string.Join(", ", discovered.Value.OrderBy(value => value, StringComparer.Ordinal))}); simple shorthand local variable normalization is ambiguous.", + }); + } + } + + return new ComponentVariableScopeResolution(componentVariableNames, issues); + } + + private HashSet CollectComponentsWithSimpleShorthand(ExcelTemplateWorkbook workbook) + { + var components = new HashSet(StringComparer.Ordinal); + + foreach (var sheet in workbook.Sheets.Where(IsComponentSheet)) + { + var componentName = sheet.Name[ComponentSheetPrefix.Length..]; + var hasSimpleShorthand = sheet.Cells.Any( + cell => + { + var triggerResult = useTriggerParser.Parse(cell.Value); + return (!triggerResult.IsTrigger || triggerResult.Trigger is null) && IsSimpleShorthandExpression(cell.Value); + }); + if (hasSimpleShorthand) + { + components.Add(componentName); + } + } + + return components; + } + + private static bool IsSimpleShorthandExpression(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + { + return false; + } + + var trimmed = value.Trim(); + if (!trimmed.StartsWith('@') || trimmed.StartsWith("@(", StringComparison.Ordinal)) + { + return false; + } + + var body = trimmed[1..].Trim(); + return body.Length > 0 && body.All(character => char.IsLetterOrDigit(character) || character == '_'); + } + + private sealed class ComponentVariableScopeResolution + { + public ComponentVariableScopeResolution( + IReadOnlyDictionary> componentVariableNames, + IReadOnlyList issues) + { + ComponentVariableNames = componentVariableNames; + Issues = issues; + } + + public IReadOnlyDictionary> ComponentVariableNames { get; } + + public IReadOnlyList Issues { get; } + } + + private static bool IsComponentSheet(ExcelTemplateSheet sheet) => + sheet.Name.StartsWith(ComponentSheetPrefix, StringComparison.Ordinal) && + sheet.Name.Length > ComponentSheetPrefix.Length; + + private static bool IsWithinRange( + ExcelTemplateCell cell, + int topRow, + int leftColumn, + int bottomRow, + int rightColumn) => + cell.Row >= topRow && + cell.Row <= bottomRow && + cell.Column >= leftColumn && + cell.Column <= rightColumn; + + private static bool TryParseRange( + string? reference, + out int topRow, + out int leftColumn, + out int bottomRow, + out int rightColumn) + { + topRow = 0; + leftColumn = 0; + bottomRow = 0; + rightColumn = 0; + + if (string.IsNullOrWhiteSpace(reference)) + { + return false; + } + + var tokens = reference.Split(':', StringSplitOptions.TrimEntries); + if (tokens.Length is < 1 or > 2 || !TryParseCellReference(tokens[0], out topRow, out leftColumn)) + { + return false; + } + + if (tokens.Length == 1) + { + bottomRow = topRow; + rightColumn = leftColumn; + return true; + } + + if (!TryParseCellReference(tokens[1], out bottomRow, out rightColumn)) + { + return false; + } + + return bottomRow >= topRow && rightColumn >= leftColumn; + } + + private static bool TryParseCellReference(string token, out int row, out int column) + { + row = 0; + column = 0; + + if (string.IsNullOrWhiteSpace(token)) + { + return false; + } + + var trimmed = token.Trim().Replace("$", string.Empty, StringComparison.Ordinal); + var letters = new StringBuilder(); + var digits = new StringBuilder(); + + foreach (var character in trimmed) + { + if (char.IsLetter(character)) + { + if (digits.Length > 0) + { + return false; + } + + letters.Append(char.ToUpperInvariant(character)); + continue; + } + + if (!char.IsDigit(character)) + { + return false; + } + + digits.Append(character); + } + + if (letters.Length == 0 || digits.Length == 0 || !int.TryParse(digits.ToString(), out row)) + { + return false; + } + + foreach (var character in letters.ToString()) + { + column = checked((column * 26) + (character - 'A' + 1)); + } + + return column > 0; + } +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateReportGenerator.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateReportGenerator.cs new file mode 100644 index 0000000..cda52e6 --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateReportGenerator.cs @@ -0,0 +1,98 @@ +using ExcelReportLib.DSL; +using ExcelReportLib.Logger; + +namespace ExcelReportLib.ExcelTemplate; + +/// +/// Generates final XLSX output directly from an ExcelTemplate workbook. +/// +public sealed class ExcelTemplateReportGenerator +{ + private readonly ExcelTemplateConverter converter; + private readonly ReportGenerator reportGenerator; + + /// + /// Initializes a new instance of the report generator facade. + /// + /// The ExcelTemplate converter. + /// The downstream DSL report generator. + public ExcelTemplateReportGenerator( + ExcelTemplateConverter? converter = null, + ReportGenerator? reportGenerator = null) + { + this.converter = converter ?? new ExcelTemplateConverter(); + this.reportGenerator = reportGenerator ?? new ReportGenerator(); + } + + /// + /// Converts an ExcelTemplate workbook to DSL and renders the final XLSX through the existing report pipeline. + /// + /// The source xlsx path. + /// The data object used by the DSL runtime. + /// Optional generation settings. + /// The cancellation token. + /// The aggregated report generation result. + public ReportGeneratorResult GenerateFromExcelTemplate( + string xlsxPath, + object? data, + ExcelTemplateGenerateOptions? options = null, + CancellationToken cancellationToken = default) + { + var effectiveOptions = options ?? new ExcelTemplateGenerateOptions(); + var reportOptions = effectiveOptions.ReportGeneratorOptions ?? new ReportGeneratorOptions(); + var logger = reportOptions.Logger ?? new ReportLogger(); + var reportOptionsWithLogger = EnsureLogger(reportOptions, logger); + + var conversionResult = converter.ConvertToDsl(xlsxPath, effectiveOptions.ConvertOptions); + LogIssues(logger, conversionResult.Issues); + + if (HasFatal(conversionResult.Issues) || string.IsNullOrWhiteSpace(conversionResult.Text)) + { + return new ReportGeneratorResult( + renderResult: null, + issues: conversionResult.Issues, + logEntries: logger.GetEntries(), + abortedByFatal: true); + } + + var reportResult = reportGenerator.Generate( + conversionResult.Text, + data, + reportOptionsWithLogger, + cancellationToken); + + return new ReportGeneratorResult( + reportResult.RenderResult, + conversionResult.Issues.Concat(reportResult.Issues).ToArray(), + reportResult.LogEntries, + reportResult.AbortedByFatal, + reportResult.UnhandledException); + } + + private static ReportGeneratorOptions EnsureLogger(ReportGeneratorOptions options, IReportLogger logger) + { + if (ReferenceEquals(options.Logger, logger)) + { + return options; + } + + return new ReportGeneratorOptions + { + EnableSchemaValidation = options.EnableSchemaValidation, + TreatExpressionSyntaxErrorAsFatal = options.TreatExpressionSyntaxErrorAsFatal, + Logger = logger, + RenderOptions = options.RenderOptions, + }; + } + + private static bool HasFatal(IEnumerable issues) => + issues.Any(issue => issue.Severity == IssueSeverity.Fatal); + + private static void LogIssues(IReportLogger logger, IEnumerable issues) + { + foreach (var issue in issues) + { + logger.LogIssue(issue, ReportPhase.Parsing); + } + } +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateValidator.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateValidator.cs new file mode 100644 index 0000000..4b4b3b3 --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateValidator.cs @@ -0,0 +1,245 @@ +using System.Text; +using ExcelReportLib.DSL; +using ExcelReportLib.ExcelTemplate.Model; + +namespace ExcelReportLib.ExcelTemplate; + +/// +/// Validates extracted ExcelTemplate workbooks against initial-release constraints. +/// +public sealed class ExcelTemplateValidator +{ + private readonly UseTriggerParser useTriggerParser = new(); + + /// + /// Validates the workbook and resolved component ranges. + /// + /// The extracted workbook. + /// The resolved component ranges. + /// The validation result. + public ExcelTemplateValidationResult Validate( + ExcelTemplateWorkbook workbook, + IReadOnlyList componentRanges) + { + ArgumentNullException.ThrowIfNull(workbook); + ArgumentNullException.ThrowIfNull(componentRanges); + + var issues = new List(); + var rangesBySheet = componentRanges.ToDictionary(range => range.SheetName, StringComparer.Ordinal); + var componentNames = new HashSet(componentRanges.Select(range => range.ComponentName), StringComparer.Ordinal); + + foreach (var sheet in workbook.Sheets) + { + ValidateUnsupportedFeatures(sheet, issues); + ValidateUseTriggers(sheet, componentNames, issues); + + if (rangesBySheet.TryGetValue(sheet.Name, out var componentRange)) + { + ValidateMergedRanges(sheet, componentRange, issues); + } + } + + return new ExcelTemplateValidationResult(issues); + } + + private void ValidateUnsupportedFeatures(ExcelTemplateSheet sheet, IList issues) + { + if (!sheet.HasConditionalFormatting) + { + return; + } + + issues.Add(new Issue + { + Severity = IssueSeverity.Error, + Kind = IssueKind.UnsupportedExcelTemplateFeature, + Message = $"sheet '{sheet.Name}' uses conditional formatting, which is unsupported in the initial ExcelTemplate release.", + }); + } + + private void ValidateUseTriggers( + ExcelTemplateSheet sheet, + ISet componentNames, + IList issues) + { + foreach (var cell in sheet.Cells) + { + var result = useTriggerParser.Parse(cell.Value); + if (!result.IsTrigger) + { + continue; + } + + if (result.Issues.Count > 0) + { + foreach (var issue in result.Issues) + { + issues.Add(new Issue + { + Severity = issue.Severity, + Kind = issue.Kind, + Message = $"sheet '{sheet.Name}' cell {cell.Reference}: {issue.Message}", + }); + } + + continue; + } + + if (result.Trigger is not null && !componentNames.Contains(result.Trigger.ComponentName)) + { + issues.Add(new Issue + { + Severity = IssueSeverity.Error, + Kind = IssueKind.UndefinedComponent, + Message = $"sheet '{sheet.Name}' cell {cell.Reference} references undefined component '{result.Trigger.ComponentName}'.", + }); + } + } + } + + private static void ValidateMergedRanges( + ExcelTemplateSheet sheet, + ExcelTemplateComponentRange componentRange, + IList issues) + { + if (!TryParseRangeReference(componentRange.Reference, out var topRow, out var leftColumn, out var bottomRow, out var rightColumn)) + { + return; + } + + foreach (var mergedRange in sheet.MergedRanges) + { + if (!TryParseRangeReference(mergedRange, out var mergedTop, out var mergedLeft, out var mergedBottom, out var mergedRight)) + { + continue; + } + + var intersects = + mergedBottom >= topRow && + mergedTop <= bottomRow && + mergedRight >= leftColumn && + mergedLeft <= rightColumn; + var contained = + mergedTop >= topRow && + mergedBottom <= bottomRow && + mergedLeft >= leftColumn && + mergedRight <= rightColumn; + + if (intersects && !contained) + { + issues.Add(new Issue + { + Severity = IssueSeverity.Error, + Kind = IssueKind.MergedCellBoundaryViolation, + Message = $"component sheet '{sheet.Name}' has merged range '{mergedRange}' crossing resolved component range '{componentRange.Reference}'.", + }); + } + } + } + + private static bool TryParseRangeReference( + string reference, + out int topRow, + out int leftColumn, + out int bottomRow, + out int rightColumn) + { + topRow = 0; + leftColumn = 0; + bottomRow = 0; + rightColumn = 0; + + if (string.IsNullOrWhiteSpace(reference) || reference.Contains(',', StringComparison.Ordinal)) + { + return false; + } + + var parts = reference.Split(':', StringSplitOptions.TrimEntries); + if (parts.Length is < 1 or > 2 || !TryParseCellReference(parts[0], out topRow, out leftColumn)) + { + return false; + } + + if (parts.Length == 1) + { + bottomRow = topRow; + rightColumn = leftColumn; + return true; + } + + if (!TryParseCellReference(parts[1], out bottomRow, out rightColumn)) + { + return false; + } + + return bottomRow >= topRow && rightColumn >= leftColumn; + } + + private static bool TryParseCellReference(string token, out int row, out int column) + { + row = 0; + column = 0; + + if (string.IsNullOrWhiteSpace(token)) + { + return false; + } + + var trimmed = token.Trim().Replace("$", string.Empty, StringComparison.Ordinal); + var letters = new StringBuilder(); + var digits = new StringBuilder(); + + foreach (var character in trimmed) + { + if (char.IsLetter(character)) + { + if (digits.Length > 0) + { + return false; + } + + letters.Append(char.ToUpperInvariant(character)); + continue; + } + + if (!char.IsDigit(character)) + { + return false; + } + + digits.Append(character); + } + + if (letters.Length == 0 || digits.Length == 0 || !int.TryParse(digits.ToString(), out row)) + { + return false; + } + + foreach (var character in letters.ToString()) + { + column = checked((column * 26) + (character - 'A' + 1)); + } + + return column > 0; + } +} + +/// +/// Represents ExcelTemplate validation output. +/// +public sealed class ExcelTemplateValidationResult +{ + /// + /// Initializes a new instance of the validation result. + /// + /// The collected issues. + public ExcelTemplateValidationResult(IReadOnlyList? issues = null) + { + Issues = issues?.ToArray() ?? []; + } + + /// + /// Gets the collected issues. + /// + public IReadOnlyList Issues { get; } +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateCell.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateCell.cs new file mode 100644 index 0000000..35447bf --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateCell.cs @@ -0,0 +1,62 @@ +namespace ExcelReportLib.ExcelTemplate.Model; + +/// +/// Represents an extracted Excel template cell. +/// +public sealed class ExcelTemplateCell +{ + /// + /// Initializes a new instance of the cell model. + /// + /// The A1 reference. + /// The 1-based row index. + /// The 1-based column index. + /// The cell value. + /// The cell formula text without leading equals. + /// The cell style metadata. + public ExcelTemplateCell( + string reference, + int row, + int column, + string? value, + string? formula, + ExcelTemplateStyle? style) + { + Reference = reference; + Row = row; + Column = column; + Value = value; + Formula = formula; + Style = style; + } + + /// + /// Gets the A1 reference. + /// + public string Reference { get; } + + /// + /// Gets the 1-based row index. + /// + public int Row { get; } + + /// + /// Gets the 1-based column index. + /// + public int Column { get; } + + /// + /// Gets the cell value. + /// + public string? Value { get; } + + /// + /// Gets the formula text. + /// + public string? Formula { get; } + + /// + /// Gets the extracted style metadata. + /// + public ExcelTemplateStyle? Style { get; } +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateComponentRange.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateComponentRange.cs new file mode 100644 index 0000000..2466124 --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateComponentRange.cs @@ -0,0 +1,35 @@ +namespace ExcelReportLib.ExcelTemplate.Model; + +/// +/// Represents a resolved component range in an Excel template workbook. +/// +public sealed class ExcelTemplateComponentRange +{ + /// + /// Initializes a new instance of the component range model. + /// + /// The logical component name. + /// The source sheet name. + /// The A1 range reference. + public ExcelTemplateComponentRange(string componentName, string sheetName, string reference) + { + ComponentName = componentName; + SheetName = sheetName; + Reference = reference; + } + + /// + /// Gets the logical component name. + /// + public string ComponentName { get; } + + /// + /// Gets the source sheet name. + /// + public string SheetName { get; } + + /// + /// Gets the A1 range reference. + /// + public string Reference { get; } +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateOutputContract.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateOutputContract.cs new file mode 100644 index 0000000..9512bbe --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateOutputContract.cs @@ -0,0 +1,301 @@ +using ExcelReportLib.DSL; + +namespace ExcelReportLib.ExcelTemplate.Model; + +/// +/// Represents the normalized conversion output contract used by ExcelTemplate emitters. +/// +public sealed class ExcelTemplateOutputContract +{ + /// + /// Initializes a new instance of the output contract. + /// + /// The normalized component scopes. + /// The normalized sheet scopes. + /// The aggregated conversion issues. + public ExcelTemplateOutputContract( + IReadOnlyList? components = null, + IReadOnlyList? sheets = null, + IReadOnlyList? issues = null) + { + Components = components?.ToArray() ?? []; + Sheets = sheets?.ToArray() ?? []; + Issues = issues?.ToArray() ?? []; + } + + /// + /// Gets the normalized component scopes. + /// + public IReadOnlyList Components { get; } + + /// + /// Gets the normalized sheet scopes. + /// + public IReadOnlyList Sheets { get; } + + /// + /// Gets the aggregated conversion issues. + /// + public IReadOnlyList Issues { get; } +} + +/// +/// Represents a normalized component scope for conversion output. +/// +public sealed class ExcelTemplateOutputComponent +{ + /// + /// Initializes a new instance of the component scope. + /// + /// The logical component name. + /// The source component sheet name. + /// The resolved source range when available. + /// Whether the component range was successfully resolved. + /// The normalized output items. + public ExcelTemplateOutputComponent( + string name, + string sourceSheetName, + string? rangeReference, + bool isRangeResolved, + IReadOnlyList? items = null) + { + Name = name; + SourceSheetName = sourceSheetName; + RangeReference = rangeReference; + IsRangeResolved = isRangeResolved; + Items = items?.ToArray() ?? []; + } + + /// + /// Gets the logical component name. + /// + public string Name { get; } + + /// + /// Gets the source component sheet name. + /// + public string SourceSheetName { get; } + + /// + /// Gets the resolved source range when available. + /// + public string? RangeReference { get; } + + /// + /// Gets a value indicating whether the component range was successfully resolved. + /// + public bool IsRangeResolved { get; } + + /// + /// Gets the normalized output items. + /// + public IReadOnlyList Items { get; } +} + +/// +/// Represents a normalized sheet scope for conversion output. +/// +public sealed class ExcelTemplateOutputSheet +{ + /// + /// Initializes a new instance of the sheet scope. + /// + /// The sheet name. + /// The normalized output items. + public ExcelTemplateOutputSheet( + string name, + IReadOnlyList? items = null) + { + Name = name; + Items = items?.ToArray() ?? []; + } + + /// + /// Gets the sheet name. + /// + public string Name { get; } + + /// + /// Gets the normalized output items. + /// + public IReadOnlyList Items { get; } +} + +/// +/// Represents a normalized output item within a component or sheet scope. +/// +public abstract class ExcelTemplateOutputItem +{ + /// + /// Initializes a new instance of the output item. + /// + /// The A1 reference. + /// The 1-based row index. + /// The 1-based column index. + /// The workbook style index when present. + protected ExcelTemplateOutputItem(string reference, int row, int column, uint? styleIndex) + { + Reference = reference; + Row = row; + Column = column; + StyleIndex = styleIndex; + } + + /// + /// Gets the A1 reference. + /// + public string Reference { get; } + + /// + /// Gets the 1-based row index. + /// + public int Row { get; } + + /// + /// Gets the 1-based column index. + /// + public int Column { get; } + + /// + /// Gets the workbook style index when present. + /// + public uint? StyleIndex { get; } +} + +/// +/// Represents a normalized value or formula cell. +/// +public sealed class ExcelTemplateOutputCell : ExcelTemplateOutputItem +{ + /// + /// Initializes a new instance of the cell output item. + /// + /// The A1 reference. + /// The 1-based row index. + /// The 1-based column index. + /// The workbook style index when present. + /// The raw cell value. + /// The raw cell formula. + public ExcelTemplateOutputCell( + string reference, + int row, + int column, + uint? styleIndex, + string? value, + string? formula) + : base(reference, row, column, styleIndex) + { + Value = value; + Formula = formula; + } + + /// + /// Gets the raw cell value. + /// + public string? Value { get; } + + /// + /// Gets the raw cell formula. + /// + public string? Formula { get; } +} + +/// +/// Represents a normalized use trigger. +/// +public sealed class ExcelTemplateOutputUse : ExcelTemplateOutputItem +{ + /// + /// Initializes a new instance of the use output item. + /// + /// The A1 reference. + /// The 1-based row index. + /// The 1-based column index. + /// The workbook style index when present. + /// The referenced component name. + /// The normalized style overflow mode when explicitly known. + public ExcelTemplateOutputUse( + string reference, + int row, + int column, + uint? styleIndex, + string componentName, + string? styleOverflow) + : base(reference, row, column, styleIndex) + { + ComponentName = componentName; + StyleOverflow = styleOverflow; + } + + /// + /// Gets the referenced component name. + /// + public string ComponentName { get; } + + /// + /// Gets the normalized style overflow mode when explicitly known. + /// + public string? StyleOverflow { get; } +} + +/// +/// Represents a normalized repeat-use trigger. +/// +public sealed class ExcelTemplateOutputRepeatUse : ExcelTemplateOutputItem +{ + /// + /// Initializes a new instance of the repeat-use output item. + /// + /// The A1 reference. + /// The 1-based row index. + /// The 1-based column index. + /// The workbook style index when present. + /// The referenced component name. + /// The repeat source expression. + /// The repeat variable name. + /// The normalized repeat direction. + /// The normalized style overflow mode when explicitly known. + public ExcelTemplateOutputRepeatUse( + string reference, + int row, + int column, + uint? styleIndex, + string componentName, + string fromExpression, + string variableName, + string direction, + string? styleOverflow) + : base(reference, row, column, styleIndex) + { + ComponentName = componentName; + FromExpression = fromExpression; + VariableName = variableName; + Direction = direction; + StyleOverflow = styleOverflow; + } + + /// + /// Gets the referenced component name. + /// + public string ComponentName { get; } + + /// + /// Gets the repeat source expression. + /// + public string FromExpression { get; } + + /// + /// Gets the repeat variable name. + /// + public string VariableName { get; } + + /// + /// Gets the normalized repeat direction. + /// + public string Direction { get; } + + /// + /// Gets the normalized style overflow mode when explicitly known. + /// + public string? StyleOverflow { get; } +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateSheet.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateSheet.cs new file mode 100644 index 0000000..4c91303 --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateSheet.cs @@ -0,0 +1,46 @@ +namespace ExcelReportLib.ExcelTemplate.Model; + +/// +/// Represents an extracted Excel template sheet. +/// +public sealed class ExcelTemplateSheet +{ + /// + /// Initializes a new instance of the sheet model. + /// + /// The sheet name. + /// The extracted cells. + /// The extracted merged ranges. + /// Whether the sheet contains conditional formatting. + public ExcelTemplateSheet( + string name, + IReadOnlyList? cells = null, + IReadOnlyList? mergedRanges = null, + bool hasConditionalFormatting = false) + { + Name = name; + Cells = cells?.ToArray() ?? []; + MergedRanges = mergedRanges?.ToArray() ?? []; + HasConditionalFormatting = hasConditionalFormatting; + } + + /// + /// Gets the sheet name. + /// + public string Name { get; } + + /// + /// Gets the extracted cells. + /// + public IReadOnlyList Cells { get; } + + /// + /// Gets the merged range references. + /// + public IReadOnlyList MergedRanges { get; } + + /// + /// Gets a value indicating whether the sheet contains conditional formatting. + /// + public bool HasConditionalFormatting { get; } +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateStyle.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateStyle.cs new file mode 100644 index 0000000..d640507 --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateStyle.cs @@ -0,0 +1,21 @@ +namespace ExcelReportLib.ExcelTemplate.Model; + +/// +/// Represents extracted style metadata for a cell. +/// +public sealed class ExcelTemplateStyle +{ + /// + /// Initializes a new instance of the style model. + /// + /// The workbook style index. + public ExcelTemplateStyle(uint index) + { + Index = index; + } + + /// + /// Gets the workbook style index. + /// + public uint Index { get; } +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateWorkbook.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateWorkbook.cs new file mode 100644 index 0000000..bd63ef9 --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateWorkbook.cs @@ -0,0 +1,32 @@ +namespace ExcelReportLib.ExcelTemplate.Model; + +/// +/// Represents an extracted Excel template workbook. +/// +public sealed class ExcelTemplateWorkbook +{ + /// + /// Initializes a new instance of the workbook model. + /// + /// The extracted sheets. + /// The extracted defined names. + public ExcelTemplateWorkbook( + IReadOnlyList? sheets = null, + IReadOnlyDictionary? definedNames = null) + { + Sheets = sheets?.ToArray() ?? []; + DefinedNames = definedNames is null + ? new Dictionary(StringComparer.Ordinal) + : new Dictionary(definedNames, StringComparer.Ordinal); + } + + /// + /// Gets the extracted sheets. + /// + public IReadOnlyList Sheets { get; } + + /// + /// Gets the extracted workbook defined names. + /// + public IReadOnlyDictionary DefinedNames { get; } +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/UseTriggerParser.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/UseTriggerParser.cs new file mode 100644 index 0000000..e91d9fd --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/UseTriggerParser.cs @@ -0,0 +1,289 @@ +using ExcelReportLib.DSL; +using System.Text; + +namespace ExcelReportLib.ExcelTemplate; + +/// +/// Parses ExcelTemplate use trigger strings into structured trigger metadata. +/// +public sealed class UseTriggerParser +{ + /// + /// Parses a cell text value as a use trigger when applicable. + /// + /// The raw cell text. + /// The parse result. + public ExcelTemplateUseTriggerParseResult Parse(string? cellValue) + { + if (string.IsNullOrWhiteSpace(cellValue)) + { + return ExcelTemplateUseTriggerParseResult.NotTrigger(); + } + + var trimmed = cellValue.Trim(); + if (!trimmed.StartsWith("{{use:", StringComparison.Ordinal)) + { + return ExcelTemplateUseTriggerParseResult.NotTrigger(); + } + + if (!trimmed.EndsWith("}}", StringComparison.Ordinal)) + { + return ExcelTemplateUseTriggerParseResult.Invalid(" trigger must end with '}}'."); + } + + var body = trimmed["{{use:".Length..^2].Trim(); + if (string.IsNullOrWhiteSpace(body)) + { + return ExcelTemplateUseTriggerParseResult.Invalid(" trigger must specify a component name."); + } + + var tokens = SplitTopLevelTokens(body); + if (tokens.Length == 0) + { + return ExcelTemplateUseTriggerParseResult.Invalid(" trigger must specify a component name."); + } + + var componentName = tokens[0].Trim(); + if (string.IsNullOrWhiteSpace(componentName)) + { + return ExcelTemplateUseTriggerParseResult.Invalid(" trigger must specify a component name."); + } + + string? fromExpression = null; + string? variableName = null; + string? styleOverflow = null; + + for (var index = 1; index < tokens.Length; index++) + { + var parts = tokens[index].Split(':', 2, StringSplitOptions.TrimEntries); + if (parts.Length != 2 || string.IsNullOrWhiteSpace(parts[0]) || string.IsNullOrWhiteSpace(parts[1])) + { + return ExcelTemplateUseTriggerParseResult.Invalid($" trigger token '{tokens[index]}' is invalid."); + } + + switch (parts[0]) + { + case "from": + fromExpression = parts[1]; + break; + case "var": + variableName = parts[1]; + break; + case "styleOverflow": + styleOverflow = parts[1]; + break; + default: + return ExcelTemplateUseTriggerParseResult.Invalid( + $" trigger token '{parts[0]}' is unsupported. Supported keys are from, var, and styleOverflow."); + } + } + + if (string.IsNullOrWhiteSpace(fromExpression) != string.IsNullOrWhiteSpace(variableName)) + { + var message = string.IsNullOrWhiteSpace(fromExpression) + ? " repeat trigger requires from when var is specified." + : " repeat trigger requires var when from is specified."; + return ExcelTemplateUseTriggerParseResult.Invalid(message); + } + + var trigger = new ExcelTemplateUseTrigger( + componentName, + fromExpression, + variableName, + string.IsNullOrWhiteSpace(fromExpression) ? null : "down", + styleOverflow); + return ExcelTemplateUseTriggerParseResult.Success(trigger); + } + + private static string[] SplitTopLevelTokens(string body) + { + var tokens = new List(); + var current = new StringBuilder(); + var parenthesesDepth = 0; + var bracketDepth = 0; + var braceDepth = 0; + var inSingleQuote = false; + var inDoubleQuote = false; + + for (var index = 0; index < body.Length; index++) + { + var character = body[index]; + var previous = index > 0 ? body[index - 1] : '\0'; + + if (character == '"' && !inSingleQuote && previous != '\\') + { + inDoubleQuote = !inDoubleQuote; + current.Append(character); + continue; + } + + if (character == '\'' && !inDoubleQuote && previous != '\\') + { + inSingleQuote = !inSingleQuote; + current.Append(character); + continue; + } + + if (!inSingleQuote && !inDoubleQuote) + { + switch (character) + { + case '(': + parenthesesDepth++; + break; + case ')': + parenthesesDepth = Math.Max(0, parenthesesDepth - 1); + break; + case '[': + bracketDepth++; + break; + case ']': + bracketDepth = Math.Max(0, bracketDepth - 1); + break; + case '{': + braceDepth++; + break; + case '}': + braceDepth = Math.Max(0, braceDepth - 1); + break; + case ',' when parenthesesDepth == 0 && bracketDepth == 0 && braceDepth == 0: + var token = current.ToString().Trim(); + if (!string.IsNullOrWhiteSpace(token)) + { + tokens.Add(token); + } + + current.Clear(); + continue; + } + } + + current.Append(character); + } + + var lastToken = current.ToString().Trim(); + if (!string.IsNullOrWhiteSpace(lastToken)) + { + tokens.Add(lastToken); + } + + return [.. tokens]; + } +} + +/// +/// Represents a parsed ExcelTemplate use trigger. +/// +public sealed class ExcelTemplateUseTrigger +{ + /// + /// Initializes a new instance of the use trigger model. + /// + /// The referenced component name. + /// The repeat source expression. + /// The repeat variable name. + /// The normalized repeat direction. + /// The requested style overflow mode. + public ExcelTemplateUseTrigger( + string componentName, + string? fromExpression, + string? variableName, + string? repeatDirection, + string? styleOverflow) + { + ComponentName = componentName; + FromExpression = fromExpression; + VariableName = variableName; + RepeatDirection = repeatDirection; + StyleOverflow = styleOverflow; + } + + /// + /// Gets the referenced component name. + /// + public string ComponentName { get; } + + /// + /// Gets the repeat source expression. + /// + public string? FromExpression { get; } + + /// + /// Gets the repeat variable name. + /// + public string? VariableName { get; } + + /// + /// Gets the normalized repeat direction. + /// + public string? RepeatDirection { get; } + + /// + /// Gets the requested style overflow mode. + /// + public string? StyleOverflow { get; } +} + +/// +/// Represents a use trigger parse result. +/// +public sealed class ExcelTemplateUseTriggerParseResult +{ + private ExcelTemplateUseTriggerParseResult( + bool isTrigger, + ExcelTemplateUseTrigger? trigger, + IReadOnlyList? issues) + { + IsTrigger = isTrigger; + Trigger = trigger; + Issues = issues?.ToArray() ?? []; + } + + /// + /// Gets a value indicating whether the input matched use-trigger syntax. + /// + public bool IsTrigger { get; } + + /// + /// Gets the parsed trigger when parsing succeeded. + /// + public ExcelTemplateUseTrigger? Trigger { get; } + + /// + /// Gets the parse issues. + /// + public IReadOnlyList Issues { get; } + + /// + /// Creates a non-trigger result. + /// + /// The result. + public static ExcelTemplateUseTriggerParseResult NotTrigger() => + new(false, null, null); + + /// + /// Creates a successful trigger result. + /// + /// The parsed trigger. + /// The result. + public static ExcelTemplateUseTriggerParseResult Success(ExcelTemplateUseTrigger trigger) => + new(true, trigger, null); + + /// + /// Creates an invalid trigger result. + /// + /// The validation message. + /// The result. + public static ExcelTemplateUseTriggerParseResult Invalid(string message) => + new( + true, + null, + [ + new Issue + { + Severity = IssueSeverity.Error, + Kind = IssueKind.InvalidAttributeValue, + Message = message, + }, + ]); +} diff --git a/ExcelReport/ExcelReportLib/ExcelTemplate/XmlTemplateSerializer.cs b/ExcelReport/ExcelReportLib/ExcelTemplate/XmlTemplateSerializer.cs new file mode 100644 index 0000000..7c43096 --- /dev/null +++ b/ExcelReport/ExcelReportLib/ExcelTemplate/XmlTemplateSerializer.cs @@ -0,0 +1,294 @@ +using System.Text; +using System.Xml.Linq; +using ExcelReportLib.DSL; +using ExcelReportLib.ExcelTemplate.Model; + +namespace ExcelReportLib.ExcelTemplate; + +/// +/// Serializes the normalized ExcelTemplate output contract into DSL-compatible XML. +/// +public sealed class XmlTemplateSerializer +{ + private static readonly XNamespace DslNamespace = DslContract.NamespaceUri; + + /// + /// Serializes the output contract to a DSL-compatible XML document. + /// + /// The normalized output contract. + /// The serialized XML document. + public XDocument Serialize(ExcelTemplateOutputContract contract) + { + ArgumentNullException.ThrowIfNull(contract); + + var workbook = new XElement(DslNamespace + "workbook"); + + foreach (var issue in contract.Issues) + { + workbook.Add(new XComment(SanitizeComment($"issue severity={issue.Severity} kind={issue.Kind} message={issue.Message}"))); + } + + foreach (var component in contract.Components) + { + workbook.Add(new XComment(SanitizeComment(BuildComponentDebugComment(component)))); + if (!component.IsRangeResolved) + { + continue; + } + + workbook.Add(CreateComponentElement(component)); + } + + foreach (var sheet in contract.Sheets) + { + workbook.Add(CreateSheetElement(sheet)); + } + + return new XDocument(new XDeclaration("1.0", "utf-8", null), workbook); + } + + private static XElement CreateComponentElement(ExcelTemplateOutputComponent component) + { + var element = new XElement( + DslNamespace + "component", + new XAttribute("name", component.Name)); + + element.Add(CreateGridElement(component)); + return element; + } + + private static XElement CreateGridElement(ExcelTemplateOutputComponent component) + { + var grid = new XElement(DslNamespace + "grid"); + if (component.IsRangeResolved && + TryParseDimensions(component.RangeReference, out var rows, out var cols)) + { + grid.SetAttributeValue("rows", rows); + grid.SetAttributeValue("cols", cols); + } + + foreach (var item in component.Items) + { + grid.Add(CreateLayoutElement(item, includePlacement: true)); + } + + return grid; + } + + private static XElement CreateSheetElement(ExcelTemplateOutputSheet sheet) + { + var element = new XElement( + DslNamespace + "sheet", + new XAttribute("name", sheet.Name)); + + foreach (var item in sheet.Items) + { + element.Add(CreateLayoutElement(item, includePlacement: true)); + } + + return element; + } + + private static XElement CreateLayoutElement(ExcelTemplateOutputItem item, bool includePlacement) + { + return item switch + { + ExcelTemplateOutputCell cell => CreateCellElement(cell, includePlacement), + ExcelTemplateOutputUse use => CreateUseElement(use, includePlacement), + ExcelTemplateOutputRepeatUse repeatUse => CreateRepeatElement(repeatUse, includePlacement), + _ => throw new InvalidOperationException($"Unsupported output item type: {item.GetType().FullName}"), + }; + } + + private static XElement CreateCellElement(ExcelTemplateOutputCell cell, bool includePlacement) + { + var element = new XElement(DslNamespace + "cell"); + AddPlacementAttributes(element, cell, includePlacement); + + if (cell.Formula is not null) + { + element.SetAttributeValue("formula", cell.Formula); + } + else if (cell.Value is not null) + { + element.SetAttributeValue("value", cell.Value); + } + + return element; + } + + private static XElement CreateUseElement(ExcelTemplateOutputUse use, bool includePlacement) + { + var element = new XElement( + DslNamespace + "use", + new XAttribute("component", use.ComponentName)); + AddPlacementAttributes(element, use, includePlacement); + + if (!string.IsNullOrWhiteSpace(use.StyleOverflow)) + { + element.SetAttributeValue("styleOverflow", use.StyleOverflow); + } + + return element; + } + + private static XElement CreateRepeatElement(ExcelTemplateOutputRepeatUse repeatUse, bool includePlacement) + { + var element = new XElement( + DslNamespace + "repeat", + new XAttribute("from", repeatUse.FromExpression), + new XAttribute("var", repeatUse.VariableName), + new XAttribute("direction", repeatUse.Direction)); + AddPlacementAttributes(element, repeatUse, includePlacement); + element.Add(CreateUseElement( + new ExcelTemplateOutputUse( + repeatUse.Reference, + repeatUse.Row, + repeatUse.Column, + repeatUse.StyleIndex, + repeatUse.ComponentName, + repeatUse.StyleOverflow), + includePlacement: false)); + return element; + } + + private static void AddPlacementAttributes(XElement element, ExcelTemplateOutputItem item, bool includePlacement) + { + if (!includePlacement) + { + return; + } + + element.SetAttributeValue("r", item.Row); + element.SetAttributeValue("c", item.Column); + } + + private static string BuildComponentDebugComment(ExcelTemplateOutputComponent component) + { + var builder = new StringBuilder(); + builder.Append("component"); + builder.Append(" name=").Append(component.Name); + builder.Append(" sourceSheet=").Append(component.SourceSheetName); + builder.Append(" rangeResolved=").Append(component.IsRangeResolved ? "true" : "false"); + + if (!string.IsNullOrWhiteSpace(component.RangeReference)) + { + builder.Append(" range=").Append(component.RangeReference); + } + + if (!component.IsRangeResolved) + { + builder.Append(" unresolved-component"); + } + + return builder.ToString(); + } + + private static bool TryParseDimensions(string? rangeReference, out int rows, out int cols) + { + rows = 0; + cols = 0; + + if (string.IsNullOrWhiteSpace(rangeReference) || + !TryParseRange(rangeReference, out var topRow, out var leftColumn, out var bottomRow, out var rightColumn)) + { + return false; + } + + rows = bottomRow - topRow + 1; + cols = rightColumn - leftColumn + 1; + return rows > 0 && cols > 0; + } + + private static bool TryParseRange( + string reference, + out int topRow, + out int leftColumn, + out int bottomRow, + out int rightColumn) + { + topRow = 0; + leftColumn = 0; + bottomRow = 0; + rightColumn = 0; + + var parts = reference.Split(':', StringSplitOptions.TrimEntries); + if (parts.Length is < 1 or > 2 || !TryParseCellReference(parts[0], out topRow, out leftColumn)) + { + return false; + } + + if (parts.Length == 1) + { + bottomRow = topRow; + rightColumn = leftColumn; + return true; + } + + if (!TryParseCellReference(parts[1], out bottomRow, out rightColumn)) + { + return false; + } + + return bottomRow >= topRow && rightColumn >= leftColumn; + } + + private static bool TryParseCellReference(string token, out int row, out int column) + { + row = 0; + column = 0; + + if (string.IsNullOrWhiteSpace(token)) + { + return false; + } + + var trimmed = token.Trim().Replace("$", string.Empty, StringComparison.Ordinal); + var letters = new StringBuilder(); + var digits = new StringBuilder(); + + foreach (var character in trimmed) + { + if (char.IsLetter(character)) + { + if (digits.Length > 0) + { + return false; + } + + letters.Append(char.ToUpperInvariant(character)); + continue; + } + + if (!char.IsDigit(character)) + { + return false; + } + + digits.Append(character); + } + + if (letters.Length == 0 || digits.Length == 0 || !int.TryParse(digits.ToString(), out row)) + { + return false; + } + + foreach (var character in letters.ToString()) + { + column = checked((column * 26) + (character - 'A' + 1)); + } + + return column > 0; + } + + private static string SanitizeComment(string value) + { + var sanitized = value.Replace("--", "- -", StringComparison.Ordinal); + if (sanitized.EndsWith("-", StringComparison.Ordinal)) + { + sanitized += " "; + } + + return sanitized; + } +} diff --git a/ExcelReport/ExcelReportLib/LayoutEngine/LayoutEngine.cs b/ExcelReport/ExcelReportLib/LayoutEngine/LayoutEngine.cs index 238f94e..a5cccec 100644 --- a/ExcelReport/ExcelReportLib/LayoutEngine/LayoutEngine.cs +++ b/ExcelReport/ExcelReportLib/LayoutEngine/LayoutEngine.cs @@ -317,7 +317,7 @@ private ExpandResult ExpandCell( styleScope = styleScope.Append([CreateStyleRef(cell.StyleRefShortcut, issues)], null); } - var rendered = EvaluateCellValue(cell.ValueRaw, rootData, dataContext, vars, issues); + var rendered = EvaluateCellValue(cell.ValueRaw, cell.FormulaRaw, rootData, dataContext, vars, issues); var stylePlan = styleResolver.BuildPlan( styleScope.StyleRefs, styleScope.InlineStyles, @@ -561,9 +561,7 @@ private ExpandResult ExpandUse( var componentBaseRow = baseRow + ResolveOffset(component.Placement.Row); var componentBaseCol = baseCol + ResolveOffset(component.Placement.Col); - var styleScope = inheritedStyles - .Append(component.StyleRefs, component.Style) - .Append(use.StyleRefs, use.Style); + var componentStyleScope = inheritedStyles.Append(component.StyleRefs, component.Style); var result = ExpandNode( component.Body, @@ -573,10 +571,14 @@ private ExpandResult ExpandUse( boundData, vars, $"{scopePath}/use", - styleScope, + componentStyleScope, componentIndex, styleResolver, issues); + var useSeedScope = StyleScope.From(use.StyleRefs, use.Style); + var seedResult = CreateUseSeedResult(use, baseRow, baseCol, $"{scopePath}/use-seed", useSeedScope, styleResolver, issues); + result = MergeSeedCells(result, seedResult.Cells); + result = ApplyUseStyleOverflow(result, seedResult.Cells, use, baseRow, baseCol, $"{scopePath}/use-overflow", issues); var conditionalFormattings = new List(result.ConditionalFormattings); conditionalFormattings.AddRange( CreateScopedConditionalFormattings( @@ -638,11 +640,19 @@ private ExpandResult ExpandUse( private RenderedValue EvaluateCellValue( string? valueRaw, + string? formulaRaw, object? rootData, object? dataContext, IReadOnlyDictionary vars, IList issues) { + if (!string.IsNullOrWhiteSpace(formulaRaw)) + { + return new RenderedValue( + Value: null, + Formula: EvaluateFormulaText(formulaRaw, rootData, dataContext, vars, issues)); + } + if (string.IsNullOrWhiteSpace(valueRaw)) { return RenderedValue.Empty; @@ -670,6 +680,35 @@ private RenderedValue EvaluateCellValue( return new RenderedValue(valueRaw, Formula: null); } + private string? EvaluateFormulaText( + string formulaRaw, + object? rootData, + object? dataContext, + IReadOnlyDictionary vars, + IList issues) + { + if (LooksLikeExpression(formulaRaw)) + { + var evaluated = EvaluateExpressionValue(formulaRaw, rootData, dataContext, vars, issues); + return NormalizeFormulaText(evaluated?.ToString()); + } + + return NormalizeFormulaText(formulaRaw); + } + + private static string? NormalizeFormulaText(string? formula) + { + var normalized = formula?.Trim(); + if (string.IsNullOrWhiteSpace(normalized)) + { + return null; + } + + return normalized.StartsWith("=", StringComparison.Ordinal) + ? normalized + : "=" + normalized; + } + private bool ShouldRender( string? whenExprRaw, object? rootData, @@ -1191,6 +1230,261 @@ private static void AppendIssues(IList target, IEnumerable? source } } + private static ExpandResult CreateUseSeedResult( + UseAst use, + int baseRow, + int baseCol, + string scopePath, + StyleScope useSeedScope, + IStyleResolver styleResolver, + IList issues) + { + if (!HasUseSeedStyles(useSeedScope)) + { + return ExpandResult.Empty; + } + + var stylePlan = styleResolver.BuildPlan( + useSeedScope.StyleRefs, + useSeedScope.InlineStyles, + sheetDefault: null, + workbookDefault: null, + StyleTarget.Cell, + issues); + var seedCells = new List(use.Placement.RowSpan * use.Placement.ColSpan); + var anchorBottom = baseRow + use.Placement.RowSpan - 1; + var anchorRight = baseCol + use.Placement.ColSpan - 1; + + for (var row = baseRow; row <= anchorBottom; row++) + { + for (var col = baseCol; col <= anchorRight; col++) + { + seedCells.Add( + new LayoutCell( + row, + col, + rowSpan: 1, + colSpan: 1, + value: null, + formula: null, + formulaRef: null, + formulaRefScope: null, + scopePath, + stylePlan)); + } + } + + var seedResult = new ExpandResult( + seedCells, + use.Placement.RowSpan, + use.Placement.ColSpan, + Array.Empty(), + Array.Empty()); + + return ApplyGridBorders(seedResult, useSeedScope, styleResolver); + } + + private static bool HasUseSeedStyles(StyleScope useSeedScope) => + useSeedScope.StyleRefs.Count > 0 || useSeedScope.InlineStyles.Count > 0; + + private static ExpandResult MergeSeedCells(ExpandResult result, IReadOnlyList seedCells) + { + if (seedCells.Count == 0) + { + return result; + } + + var mergedCells = result.Cells.ToList(); + var updatedHeads = new HashSet<(int Row, int Col)>(); + + foreach (var seedCell in seedCells) + { + if (!HasStyleContent(seedCell.StylePlan)) + { + continue; + } + + if (TryFindCoveringCellIndex(mergedCells, seedCell.Row, seedCell.Col, out var existingIndex)) + { + var existingCell = mergedCells[existingIndex]; + var existingHead = (existingCell.Row, existingCell.Col); + if (updatedHeads.Add(existingHead)) + { + mergedCells[existingIndex] = AppendStyleToCell(existingCell, seedCell.StylePlan); + } + + continue; + } + + mergedCells.Add(seedCell); + } + + return result with + { + Cells = mergedCells, + }; + } + + private static ExpandResult ApplyUseStyleOverflow( + ExpandResult result, + IReadOnlyList seedCells, + UseAst use, + int baseRow, + int baseCol, + string scopePath, + IList issues) + { + var anchorBottom = baseRow + use.Placement.RowSpan - 1; + var anchorRight = baseCol + use.Placement.ColSpan - 1; + var expandedBottom = baseRow + result.Height - 1; + var expandedRight = baseCol + result.Width - 1; + var deltaRows = Math.Max(0, expandedBottom - anchorBottom); + var deltaCols = Math.Max(0, expandedRight - anchorRight); + + if (deltaRows == 0 && deltaCols == 0) + { + return result; + } + + var shouldTrackOverflow = + use.HasStyleOverflowAttribute || + use.Placement.RowSpan > 1 || + use.Placement.ColSpan > 1 || + seedCells.Count > 0; + if (!shouldTrackOverflow) + { + return result; + } + + issues.Add(new Issue + { + Severity = IssueSeverity.Warning, + Kind = IssueKind.TemplateRangeOverflow, + Message = + $"component '{use.ComponentName}' expanded beyond anchor range at r={baseRow}, c={baseCol} (deltaRows={deltaRows}, deltaCols={deltaCols}).", + Span = use.Span, + }); + + if (!string.Equals(use.StyleOverflow, "edge", StringComparison.Ordinal) || seedCells.Count == 0) + { + return result; + } + + var mergedCells = result.Cells.ToList(); + var seedCellLookup = seedCells.ToDictionary(cell => (cell.Row, cell.Col)); + + if (deltaCols > 0) + { + for (var row = baseRow; row <= anchorBottom; row++) + { + if (!seedCellLookup.TryGetValue((row, anchorRight), out var seedCell) || !HasStyleContent(seedCell.StylePlan)) + { + continue; + } + + for (var col = anchorRight + 1; col <= expandedRight; col++) + { + AddOrMergeStyleCell(mergedCells, row, col, seedCell.StylePlan, scopePath); + } + } + } + + if (deltaRows > 0) + { + for (var col = baseCol; col <= anchorRight; col++) + { + if (!seedCellLookup.TryGetValue((anchorBottom, col), out var seedCell) || !HasStyleContent(seedCell.StylePlan)) + { + continue; + } + + for (var row = anchorBottom + 1; row <= expandedBottom; row++) + { + AddOrMergeStyleCell(mergedCells, row, col, seedCell.StylePlan, scopePath); + } + } + } + + if (deltaRows > 0 && + deltaCols > 0 && + seedCellLookup.TryGetValue((anchorBottom, anchorRight), out var cornerSeedCell) && + HasStyleContent(cornerSeedCell.StylePlan)) + { + for (var row = anchorBottom + 1; row <= expandedBottom; row++) + { + for (var col = anchorRight + 1; col <= expandedRight; col++) + { + AddOrMergeStyleCell(mergedCells, row, col, cornerSeedCell.StylePlan, scopePath); + } + } + } + + return result with + { + Cells = mergedCells, + }; + } + + private static void AddOrMergeStyleCell( + IList cells, + int row, + int col, + StylePlan stylePlan, + string scopePath) + { + if (!HasStyleContent(stylePlan)) + { + return; + } + + if (TryFindCoveringCellIndex(cells, row, col, out var existingIndex)) + { + cells[existingIndex] = AppendStyleToCell(cells[existingIndex], stylePlan); + return; + } + + cells.Add( + new LayoutCell( + row, + col, + rowSpan: 1, + colSpan: 1, + value: null, + formula: null, + formulaRef: null, + formulaRefScope: null, + scopePath, + stylePlan)); + } + + private static bool TryFindCoveringCellIndex( + IList cells, + int row, + int col, + out int index) + { + for (var i = 0; i < cells.Count; i++) + { + var cell = cells[i]; + if (row < cell.Row || col < cell.Col) + { + continue; + } + + if (row <= cell.Row + cell.RowSpan - 1 && col <= cell.Col + cell.ColSpan - 1) + { + index = i; + return true; + } + } + + index = -1; + return false; + } + + private static bool HasStyleContent(StylePlan stylePlan) => + stylePlan.EffectiveStyle.HasContent; + /// /// グリッド解決後のセル集合へ、mode=outer/all の border を mode=cell として展開する。 /// @@ -1396,6 +1690,22 @@ private static LayoutCell AppendBordersToCell(LayoutCell cell, IReadOnlyList /// 既存 StylePlan に border を追記した新しい StylePlan を生成する。 /// @@ -1447,6 +1757,49 @@ private static StylePlan CreateStylePlanWithAdditionalBorders( stylePlan.BorderTraces); } + private static StylePlan MergeStylePlans( + StylePlan baseStylePlan, + StylePlan overlayStylePlan) + { + if (!HasStyleContent(overlayStylePlan)) + { + return baseStylePlan; + } + + var mergedBorders = baseStylePlan.Borders + .Concat(overlayStylePlan.Borders) + .Select(CloneBorder) + .ToArray(); + var mergedEffectiveStyle = new ResolvedStyle( + "effective", + StyleSourceKind.Computed, + DSL.AST.StyleScope.Both, + overlayStylePlan.FontName ?? baseStylePlan.FontName, + overlayStylePlan.FontSize ?? baseStylePlan.FontSize, + overlayStylePlan.FontBold ?? baseStylePlan.FontBold, + overlayStylePlan.FontItalic ?? baseStylePlan.FontItalic, + overlayStylePlan.FontUnderline ?? baseStylePlan.FontUnderline, + overlayStylePlan.FillColor ?? baseStylePlan.FillColor, + overlayStylePlan.NumberFormatCode ?? baseStylePlan.NumberFormatCode, + mergedBorders); + + return new StylePlan( + mergedEffectiveStyle, + baseStylePlan.AppliedStyles.Concat(overlayStylePlan.AppliedStyles).ToArray(), + baseStylePlan.WorkbookDefault, + baseStylePlan.SheetDefault, + baseStylePlan.ReferenceStyles.Concat(overlayStylePlan.ReferenceStyles).ToArray(), + baseStylePlan.InlineStyles.Concat(overlayStylePlan.InlineStyles).ToArray(), + overlayStylePlan.FontNameTrace ?? baseStylePlan.FontNameTrace, + overlayStylePlan.FontSizeTrace ?? baseStylePlan.FontSizeTrace, + overlayStylePlan.FontBoldTrace ?? baseStylePlan.FontBoldTrace, + overlayStylePlan.FontItalicTrace ?? baseStylePlan.FontItalicTrace, + overlayStylePlan.FontUnderlineTrace ?? baseStylePlan.FontUnderlineTrace, + overlayStylePlan.FillColorTrace ?? baseStylePlan.FillColorTrace, + overlayStylePlan.NumberFormatCodeTrace ?? baseStylePlan.NumberFormatCodeTrace, + baseStylePlan.BorderTraces.Concat(overlayStylePlan.BorderTraces).ToArray()); + } + /// /// border mode が grid 展開対象かを判定する。 /// diff --git a/reports/chat-handover-for-new-thread-20260412_153728.md b/reports/chat-handover-for-new-thread-20260412_153728.md new file mode 100644 index 0000000..f94248b --- /dev/null +++ b/reports/chat-handover-for-new-thread-20260412_153728.md @@ -0,0 +1,234 @@ +# 【1. このチャットの目的】 + +このチャットの目的は、issue #58 の ExcelTemplate 対応について、設計の具体化、レビュー反映、実装前合意の固定、実装方針の策定、sub-agent レビュー、コミットと push までを完了させることだった。 + +最終状態として、設計書 `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` は実装前合意と実装方針まで反映済みであり、実装着手前に必要な主要論点は整理済みである。最新コミットは `4b81b7d`、ブランチは `codex/create-design-document-for-approval`、push 済みである。 + +# 【2. 新しいチャットに切り替える理由】 + +ここまでで設計・レビュー・方針整理の文脈が長くなっており、次のチャットでは実装を開始する可能性が高い。実装開始時に必要なのは、過去の会話要約ではなく、どの設計が確定し、どのレビュー指摘がどう反映され、次に何から手を付けるべきかが単体で再現できる引き継ぎである。そのため、新しいチャットで追加確認なしに再開できるように、この文書を残す。 + +# 【3. 背景・前提条件】 + +プロジェクトは `/home/ibis/dotnet_ws/ExcelReport` にある。現在ブランチは `codex/create-design-document-for-approval` で、`origin/codex/create-design-document-for-approval` に push 済み。`git status --short --branch` の結果はクリーンで、未コミット差分はない。 + +現行ライブラリの実行経路は次のとおり。 + +```text +ReportGenerator + -> DslParser + -> LayoutEngine + -> WorksheetStateBuilder + -> XlsxRenderer +``` + +主要実装ファイル: +- `ExcelReport/ExcelReportLib/ReportGenerator.cs` +- `ExcelReport/ExcelReportLib/DSL/DslParser.cs` +- `ExcelReport/ExcelReportLib/LayoutEngine/LayoutEngine.cs` +- `ExcelReport/ExcelReportLib/WorksheetState/WorksheetStateBuilder.cs` +- `ExcelReport/ExcelReportLib/Renderer/XlsxRenderer.cs` + +issue #58 の設計対象は「Excel形式テンプレートを DSL へ変換し、既存の DSL 実行パイプラインへ接続する機能」である。設計書は次のファイルに集約されている。 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + +このチャットの最後に確定している基本前提は次のとおり。 +- 初期実装は A案(`__component_` のシート単位コンポーネント定義)で進める +- デバッグ経路として `Excel -> XML Template` を同時に持つ +- グラフ作成機能は今回スコープ外 +- 数式セルは `cell@formula` へ正規化し、C# 側で Excel 関数計算はしない +- merged cell は初版では「矩形内完結のみ」 +- 条件付き書式は初版対象外 +- 性能閾値は当面不問 +- `styleOverflow=edge` は現行レイアウトモデルに合わせて right/down/right-down corner のみ + +# 【4. ここまでの経緯】 + +issue #58 について、まず設計書名と章構成を整理し、`Issue58` という識別的でない名前を `ExcelTemplate` に改めた。続いて、入れ子コンポーネント、`use` / `repeat`、サイズ不一致時の overflow、書式合成、SVG・Markdown 表、C# サンプルデータを設計書へ追加し、ユーザー指摘に合わせて 10.8 / 10.9 / 10.10 節の図・説明・順序を繰り返し修正した。 + +その後、sub-agent による設計レビューを複数回実施した。 + +1. `gpt-5.3-codex` / `high` +- `repeat` 時の `H` 定義未確定 +- `GroupBlock` の有効幅不一致 +- `styleOverflow=edge` の行方向未定義 +- 連続 instance 境界の罫線優先未定義 +- 10.8.8 図注記ズレ + +これらを設計へ反映し、再レビューした結果、High/Critical は解消。残留 Low として `styleOverflow=edge` の4方向検証不足と 10.9.4 テーブル表現不足が指摘され、それも反映した。 + +2. `gpt-5.4` / `high` +- 現行 `use` 展開モデルでは `styleOverflow=edge` を left/up まで広げるのは不整合 +- overflow 比較 SVG の文脈が GroupBlock 専用に見える + +これに対応して、`styleOverflow=edge` は right/down/right-down corner のみへ限定し、比較 SVG を generic 文脈へ修正した。 + +次に、実装前レビューとしてユーザーから次を確定した。 +- merged cell 制約: 良い +- 条件付き書式対象外: 良い +- 数式正規化 `cell@formula`: 良い +- 性能閾値: 不問、解決済み + +この合意を 12 章へ反映し、さらに「実装方針策定し、レビューをしてもらってください」という依頼を受けたため、既存コードの統合ポイントを調査した。調査の結果、後段の `ReportGenerator -> DslParser -> LayoutEngine -> WorksheetStateBuilder -> XlsxRenderer` は再利用し、前段に ExcelTemplate 変換層を追加するのが最小リスクと判断した。 + +この内容を次のレポートへ整理した。 +- `reports/issue58-implementation-approach-2026-04-12.md` + +その後、実装方針を `gpt-5.4` / `high` の sub-agent にレビューさせ、以下の指摘を受けた。 +- runtime schema 更新対象が不足している +- `repeat@direction` 必須との契約不一致 +- `styleOverflow=edge` の実装位置が未固定 +- conversion-only API が診断情報を返していない +- legacy `cell@value="=..."` の回帰テストが未明記 +- schema validation 無効時の `ValidateDsl` 補完検証が未明記 + +これらを設計書 13 章と実装方針レポートへ反映し、レビュー結果を次へ保存した。 +- `reports/issue58-implementation-approach-review-2026-04-12.md` + +最後に、これらの更新をコミットし、push した。 + +直近コミット: +- `4b81b7d` `docs: add issue58 implementation approach review` +- `ae6c8b9` `docs: finalize issue58 pre-implementation agreements` +- `4c6d5ba` `docs: align style overflow rules with layout model` +- `f64deb4` `docs: refine issue58 design after review` +- `be0df01` `docs: record issue58 subagent design review` + +# 【5. 決定事項】 + +決定事項は次のとおり。ここは未解決事項と混ぜないこと。 + +1. コンポーネント定義方式 +- 初版は A案採用 +- シート名規約は `__component_` +- 名前付き範囲ベース定義は今回 out of scope + +2. デバッグ経路 +- `Excel -> XML Template -> DSL -> Excel` を持つ +- 本番では `Excel -> DSL` 直接変換も可能にする設計 + +3. DSL / 実行契約 +- 数式セルは `cell@formula` で保持する +- C# 側で Excel 関数計算はしない +- 現行後方互換として `cell@value="=..."` は残し、回帰テストで固定する +- `repeat` は emitted DSL で必ず `direction="down"` を明示出力する +- `styleOverflow=edge` は right/down/right-down corner の trailing edge copy のみ対応 +- schema validation を無効化しても `ValidateDsl` で契約逸脱を検知する + +4. レイアウト / 書式ルール +- サイズ不一致時はクリップせず、overflow 行/列まで展開する +- `TemplateRangeOverflow` Warning を出す +- 挿入先書式は任意であり must ではない +- `styleOverflow=none|edge` を `use` 単位で選択可能、既定は `none` +- `styleOverflow=edge` は `LayoutEngine` の post-expand 処理として実装する +- style-only seed cell は `LayoutCell` として保持する +- merged cell は初版では定義範囲内で矩形完結のみ許可 + +5. API 方針 +- 既存 `ReportGenerator` は DSL 専用のまま維持 +- ExcelTemplate 入口は新規 API を追加 +- conversion-only API でも `Issues` を返す result object にする + +6. 実装順序 +- 1: DSL 契約拡張 +- 2: `styleOverflow=edge` の runtime 補完 +- 3: ExcelTemplate 中間モデル / extractor / validator +- 4: component 範囲解決 / trigger 解析 +- 5: DslEmitter / XmlTemplateSerializer +- 6: facade API / E2E + +7. 追跡ファイル +- `tasks/tasks-status.md` 更新済み +- `tasks/phases-status.md` 更新済み +- `tasks/feedback-points.md` 更新済み + +# 【6. 未解決事項・保留事項】 + +現時点で残っているのは実装そのもの。設計上の主要論点はこのチャットで固定済みだが、以下は未着手であり、次チャットで開始する必要がある。 + +1. 実装未着手 +- `cell@formula` の XSD / AST / parser / runtime 実装 +- `use@styleOverflow` の XSD / AST / runtime 実装 +- runtime schema 更新 (`Design/DslDefinition/DslDefinition_v2.xsd` と test fixture 両方) +- `ValidateDsl` の no-schema mode 用追加検証 +- ExcelTemplate 抽出層 (`Extractor`, `Validator`, `ComponentRangeResolver`, `UseTriggerParser`, `DslEmitter`, `XmlTemplateSerializer`, facade) + +2. テスト未着手 +- `cell@formula` parser/runtime テスト +- legacy `cell@value="=..."` 回帰テスト +- `styleOverflow=edge` の runtime テスト +- xlsx -> xml snapshot +- xlsx -> dsl snapshot +- xlsx -> dsl -> final xlsx E2E + +3. 外部依存やブロッカー +- 現時点でユーザー回答待ちの設計論点はない +- CI 状態確認や secret は今回作業では不要だった +- ブランチは clean / push 済みで、未反映差分はない + +# 【7. 次のチャットで最初に依頼すべき内容】 + +次のチャットでは、以下をそのまま貼れば再開できる。 + +```text +issue #58 の実装を開始してください。 + +前提: +- ブランチは `codex/create-design-document-for-approval` +- 最新 push 済みコミットは `4b81b7d` +- 引き継ぎは `reports/chat-handover-for-new-thread-20260412_153728.md` +- 設計書は `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` +- 実装方針レポートは `reports/issue58-implementation-approach-2026-04-12.md` +- 実装方針レビューは `reports/issue58-implementation-approach-review-2026-04-12.md` + +最初にやること: +1. `git status --short --branch` で作業木確認 +2. `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` の 13章を確認 +3. `reports/issue58-implementation-approach-review-2026-04-12.md` の指摘反映事項を確認 +4. 実装順序どおりに、まず `cell@formula` / `use@styleOverflow` の DSL 契約拡張から着手 + +実装順序: +1. runtime schema 更新 (`Design/DslDefinition/DslDefinition_v2.xsd` と `ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd`) +2. `CellAst` / `UseAst` / `DslParser.ValidateDsl` / `LayoutEngine` の契約拡張 +3. `styleOverflow=edge` の post-expand runtime 実装と unit test +4. ExcelTemplate extractor/model/validator 実装 +5. emitter/snapshot +6. facade/E2E + +作業後は必ず: +- `reports/` に調査・レビュー記録を残す +- `tasks/tasks-status.md` +- `tasks/phases-status.md` +- `tasks/feedback-points.md` +を更新する +``` + +# 【8. 引き継ぎ本文】 + +新しいチャットでは、issue #58 の「ExcelTemplate を DSL に変換して既存パイプラインへ接続する機能」の実装を開始する。設計作業はほぼ完了しており、主要な設計判断は `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` に反映済みである。特に重要なのは 12 章の事前合意と 13 章の実装方針であり、13 章がそのまま実装順序の基準になる。 + +現在の HEAD は `4b81b7d` (`docs: add issue58 implementation approach review`) で、ブランチは `codex/create-design-document-for-approval`。`origin/codex/create-design-document-for-approval` へ push 済みで、作業木はクリーン。次チャット開始時に `git status --short --branch` を実行すれば、同じ状態で開始できるはずである。 + +今回の実装で守るべきコア判断は次のとおり。ExcelTemplate 対応は既存 `ReportGenerator` 後段を壊さず、前段に変換層を追加する additive change とする。数式セルは `cell@formula` に正規化し、C# 側で Excel 関数計算はしない。`repeat` は converter が必ず `direction="down"` を emitted DSL に明示出力する。`styleOverflow=edge` は現行レイアウトモデルに合わせて right/down/right-down corner のみ対応し、`LayoutEngine` の post-expand 処理として実装する。conversion-only API も `Issues` を返す result object にし、座標付き Warning/Error を失わない。schema validation を無効化しても、`ValidateDsl` で契約逸脱を止める。 + +実装の最初の着手点は ExcelTemplate 抽出器ではない。最初にやるべきなのは DSL 契約拡張である。理由は、`cell@formula` と `use@styleOverflow` を runtime が理解できないままでは、変換器が正しい DSL を出力しても後段で処理できないからである。したがって、まず `Design/DslDefinition/DslDefinition_v2.xsd` と `ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd` を更新し、続いて `CellAst`, `UseAst`, `DslParser.ValidateDsl`, `LayoutEngine` の対応を行う必要がある。 + +この順序を補強するレビュー結果は `reports/issue58-implementation-approach-review-2026-04-12.md` にある。ここで特に重い指摘だったのは、runtime schema 対象不足、`repeat@direction` 契約不一致、`styleOverflow=edge` の実装位置未固定である。これらはすでに設計に反映済みなので、次チャットでは再議論せず、その前提で実装に入ってよい。 + +関連ファイルは次を起点に読むこと。 +- 設計書: `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` +- 実装方針: `reports/issue58-implementation-approach-2026-04-12.md` +- 実装方針レビュー: `reports/issue58-implementation-approach-review-2026-04-12.md` +- 追跡: `tasks/tasks-status.md`, `tasks/phases-status.md`, `tasks/feedback-points.md` + +また、issue #58 の設計関連レポートは 2026-04-12 付で `reports/` に多数残っている。図修正や設計レビューの経緯が必要なら参照できるが、実装開始時に必須なのは上記 3 ファイルで十分である。 + +次チャットでは、最初の実作業として以下の順で進めること。 + +```bash +git status --short --branch +rg -n "## 13\\.|cell@formula|styleOverflow|direction=\"down\"" Design/ExcelTemplate/ExcelTemplate_DetailDesign.md +sed -n '1,220p' reports/issue58-implementation-approach-review-2026-04-12.md +``` + +その後、DSL 契約拡張の作業計画を立て、必要な unit test から先に入る。作業中は今回と同じく、調査やレビュー結果を `reports/` に残し、`tasks/tasks-status.md`, `tasks/phases-status.md`, `tasks/feedback-points.md` を必ず同期更新すること。 diff --git a/reports/issue58-component-range-resolver-2026-04-13.md b/reports/issue58-component-range-resolver-2026-04-13.md new file mode 100644 index 0000000..725f960 --- /dev/null +++ b/reports/issue58-component-range-resolver-2026-04-13.md @@ -0,0 +1,54 @@ +# issue #58 ComponentRangeResolver 実装記録 + +- 作成日: 2026-04-13 +- 対象: issue #58 ExcelTemplate 対応の実装第3段 +- ブランチ: `codex/create-design-document-for-approval` + +## 1. 実施内容 + +ExcelTemplate 変換層の次段として、`__component_` シートの定義範囲を解決する `ExcelTemplateComponentRangeResolver` を追加した。 + +今回反映した内容: + +- `ExcelTemplateComponentRangeResolver` を追加 +- component シート判定 + - シート名 `__component_` を対象化 +- 明示範囲解決 + - workbook defined name `__component_range_` を最優先で採用 + - `'__component_Header'!$A$1:$C$3` のような sheet-qualified range を正規化 + - 別シート参照や不正 range は `InvalidComponentRange` Error +- 自動判定 + - 値 / 数式 / style を持つセル + - merged range + を candidate とし、最小外接矩形を component range として解決 +- 空範囲検出 + - 明示範囲・自動判定の両方で candidate 0 件は `EmptyComponentRange` Error +- `IssueKind.InvalidComponentRange` / `IssueKind.EmptyComponentRange` を追加 + +## 2. テスト + +TDD: + +1. 先に `ExcelTemplateComponentRangeResolverTests` を追加して Red を確認 +2. 最小実装で Green 化 +3. 明示範囲が空でも通ってしまう穴を追加テストで再現 +4. candidate 0 件時の `EmptyComponentRange` 判定を補完して再度 Green 化 + +実施: + +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter "FullyQualifiedName~ExcelTemplateComponentRangeResolverTests"` +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj` + +結果: + +- resolver 対象テスト: 5 passed +- 全体テスト: 223 passed, 0 failed + +## 3. 次の実装候補 + +次は設計 13.5 順序どおり、以下のどちらかへ進む。 + +1. `UseTriggerParser` + - `{{use:...}}` / `repeat + use` を解析し、DSL へ落とす入力契約を固定する +2. `ExcelTemplateValidator` + - merged cell 境界 / 初版対象外機能 / invalid component range を Error/Warning 化する diff --git a/reports/issue58-component-range-resolver-review-2026-04-13.md b/reports/issue58-component-range-resolver-review-2026-04-13.md new file mode 100644 index 0000000..451191c --- /dev/null +++ b/reports/issue58-component-range-resolver-review-2026-04-13.md @@ -0,0 +1,30 @@ +# issue #58 ComponentRangeResolver review 記録 + +- 作成日: 2026-04-13 +- 対象: `ExcelTemplateComponentRangeResolver` 実装差分 +- 要求レビュー条件: sub-agent `gpt-5.4` / `high` + +## 1. review 実施状況 + +1. `gpt-5.4` / `high` review を `codex review --uncommitted` で試行 + - 実行コマンド: + - `codex review --uncommitted -c model="gpt-5.4" -c reasoning_effort="high" -c approval_policy="never" -c sandbox_mode="workspace-write"` +2. 結果 + - このセッションの network 制限により websocket / responses API 接続が `Operation not permitted` で失敗 + - review stream は `Review was interrupted. Please re-run /review and wait for it to complete.` で終了 + +## 2. 代替確認 + +- 実装前提の自己点検を実施 + - 明示範囲優先 + - 明示範囲の別シート参照拒否 + - 自動判定の bbox + - 明示範囲でも candidate 0 件なら `EmptyComponentRange` +- 上記を unit test 5件で固定 +- 全体回帰 `223 passed` を確認 + +## 3. 結論 + +- 本セッションでは `gpt-5.4` / `high` の外部 review は完走不可 +- 手元で追加修正が必要な不整合は検出していない +- 残留リスクは、後続 `ExcelTemplateValidator` 実装時に merged range 境界違反と malformed defined name の Error 粒度を最終確定する点 diff --git a/reports/issue58-conversion-api-2026-04-14.md b/reports/issue58-conversion-api-2026-04-14.md new file mode 100644 index 0000000..6ec7600 --- /dev/null +++ b/reports/issue58-conversion-api-2026-04-14.md @@ -0,0 +1,48 @@ +# issue #58 Conversion API Implementation Record + +- Date: 2026-04-14 +- Scope: Phase 12 / R58-07, R58-08 +- Reference: `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + +## Summary + +- Added `ExcelTemplateConverter` as the conversion-only entry point for `xlsx -> DSL text` and `xlsx -> XML template text`. +- Added `ExcelTemplateConversionResult` and `ExcelTemplateConvertOptions`. +- Aggregated conversion issues from extractor/contract/parser into `result.Issues`. +- Hardened the public API so corrupt `xlsx` input is returned as a fatal `IssueKind.LoadFile` instead of leaking `FileFormatException`. +- Rechecked remaining work against the detail design before implementation. No missing phase/task was found beyond `Phase 13-14 / R58-09..R58-12`. + +## Implemented Behavior + +- `ConvertToDsl(string xlsxPath, ExcelTemplateConvertOptions? options = null)` + - extracts workbook + - builds normalized output contract + - emits DSL text + - optionally parses emitted text with schema validation and appends parser issues +- `ConvertToXmlTemplate(string xlsxPath, ExcelTemplateConvertOptions? options = null)` + - shares the same pipeline + - emits DSL-compatible debug XML text +- Input validation + - blank path -> fatal `LoadFile` + - file not found -> fatal `LoadFile` + - corrupt/invalid workbook container -> fatal `LoadFile` + +## TDD + +- Added `ExcelTemplateConverterTests` + - valid workbook -> DSL text, no issues + - issue workbook -> XML text, aggregated issues + - corrupt workbook -> fatal load issue + - schema validation opt-out -> conversion issues only +- Added `ExcelTemplateTestWorkbookFactory` + - valid workbook fixture + - issue workbook fixture + +## Verification + +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter ExcelTemplateConverterTests` + - Passed 4 +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter "ExcelTemplate|XmlTemplateSerializerTests|DslEmitterTests|ExcelTemplateSnapshotTests|ExcelTemplateConverterTests"` + - Passed 32 +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj` + - Passed 248 diff --git a/reports/issue58-conversion-api-review-2026-04-14.md b/reports/issue58-conversion-api-review-2026-04-14.md new file mode 100644 index 0000000..848fe79 --- /dev/null +++ b/reports/issue58-conversion-api-review-2026-04-14.md @@ -0,0 +1,25 @@ +# issue #58 Conversion API Review Record + +- Date: 2026-04-14 +- Scope: Phase 12 / R58-07, R58-08 + +## gpt-5.4 High Review Attempt + +- Attempted `gpt-5.4` / `high` review via local `codex exec review --uncommitted -m gpt-5.4 -c model_reasoning_effort="high"`. +- The review could not complete in this sandbox because outbound access to Codex backend endpoints was blocked. +- Observed errors included: + - `dns error` + - websocket connect failure to `chatgpt.com` + - `Operation not permitted` + +## Findings + +- External sub-agent findings: unavailable due network restriction in the current sandbox. +- Local review finding addressed during this cycle: + - `ExcelTemplateConverter` leaked `FileFormatException` for corrupt workbook input instead of returning a fatal conversion issue. + - Fixed by catching `InvalidDataException` and `FileFormatException`, then covering the behavior with `ConvertToDsl_CorruptWorkbook_ReturnsFatalLoadIssue`. + +## Current Assessment + +- No remaining findings were identified by the in-process review after the fix. +- Sub-agent review should be retried in an environment where Codex backend access is permitted. diff --git a/reports/issue58-converter-review-2026-04-14-round2.md b/reports/issue58-converter-review-2026-04-14-round2.md new file mode 100644 index 0000000..61c401b --- /dev/null +++ b/reports/issue58-converter-review-2026-04-14-round2.md @@ -0,0 +1,23 @@ +# Issue #58 Converter Review Round 2 + +- Date: 2026-04-14 +- Reviewer: `gpt-5.4` / `high` workflow follow-up +- Scope: + - `ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConverter.cs` + - `ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConversionResult.cs` + - `ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateConvertOptions.cs` + - `ExcelReport/ExcelReportLib.Tests/ExcelTemplateConverterTests.cs` + - `ExcelReport/ExcelReportLib.Tests/ExcelTemplateTestWorkbookFactory.cs` + +## Findings + +findingsなし + +## Notes + +- Prior round finding about skipping `DslParser.ParseFromText(...)` when `EnableSchemaValidation=false` was rechecked and is now resolved by always running parser validation while toggling schema validation only. +- Targeted verification executed after the fix: + - `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~ExcelTemplateConverterTests"` + - `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~ExcelTemplate|FullyQualifiedName~XmlTemplateSerializerTests|FullyQualifiedName~DslEmitterTests|FullyQualifiedName~ExcelTemplateSnapshotTests|FullyQualifiedName~ExcelTemplateOutputContractBuilderTests|FullyQualifiedName~ExcelTemplateValidatorTests|FullyQualifiedName~ExcelTemplateComponentRangeResolverTests|FullyQualifiedName~ExcelTemplateUseTriggerParserTests|FullyQualifiedName~ExcelTemplateExtractorTests"` +- Residual risk outside this review scope: + - broader facade/E2E files currently have separate in-flight changes and should be reviewed independently from this converter-focused round. diff --git a/reports/issue58-design-fixes-after-subagent-review-2026-04-12.md b/reports/issue58-design-fixes-after-subagent-review-2026-04-12.md new file mode 100644 index 0000000..ef1224e --- /dev/null +++ b/reports/issue58-design-fixes-after-subagent-review-2026-04-12.md @@ -0,0 +1,25 @@ +# issue #58 sub-agent 指摘対応による設計修正メモ + +## 背景 +- `gpt-5.3-codex` / `high` の sub-agent レビューで、`repeat` 時の高さ定義、`GroupBlock` 幅定義、`styleOverflow=edge` の行方向、連続 instance 境界罫線に未定義があると判明した。 + +## 対応 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + - `GroupBlock` の定義範囲を `A1:C3` に統一 + - 10.9.1 に `repeat` 時の `H/W` を「fully expand 後の外接矩形サイズ」として定義 + - 本節例では `H=6`、`W=3` なので親フレームは `A3:E10` と明記 + - 10.9.2 に `styleOverflow=edge` の上下左右・角領域ルールを追加 + - 11.3/11.4/11.5 に、連続 instance 境界は先行 instance の trailing edge を採用する規則を追加 +- `Design/ExcelTemplate/assets/insert-source-cell-values.svg` + - `GroupBlock / 3x3` 表記へ更新 +- `Design/ExcelTemplate/assets/expanded-insert-source-from-csharp.svg` + - 列数を 3 列へ統一 + - 注記を「本節サンプルデータ」へ変更 +- `Design/ExcelTemplate/assets/style-overflow-modes-3x3.svg` + - 本節の `GroupBlock` と分離するため「4列子component overflow ケース」表記へ変更 + +## 結果 +- 10.8 の `GroupBlock` 幅と 10.10 の定義範囲が一致した。 +- 10.8.9 / 10.8.10 の `A3:E10` 前提を、10.9.1 の数式で説明可能になった。 +- `styleOverflow=edge` は列方向だけでなく行方向も定義された。 +- 連続展開時の共有境界が、図と本文で同じ規則になった。 diff --git a/reports/issue58-destination-style-optional-and-column-overflow-2026-04-12.md b/reports/issue58-destination-style-optional-and-column-overflow-2026-04-12.md new file mode 100644 index 0000000..c7cb527 --- /dev/null +++ b/reports/issue58-destination-style-optional-and-column-overflow-2026-04-12.md @@ -0,0 +1,30 @@ +# issue #58 追補: 挿入先書式の任意化 / 外枠追従 / 列overflow対応 (2026-04-12) + +## ユーザー確認事項 +1. 挿入先の書式はmustではないのではないか。 +2. 3x3外枠 + 中央use で子展開したとき、外枠が子サイズに追従して一回り大きくなるべき。 +3. 行数超過だけでなく列数超過も同様に考慮すべき。 + +## 設計更新 +- 対象: `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + +### 1) 挿入先書式は任意(mustではない) +- 10.9 に明記: + - 書式未指定でも `use` 展開は有効。 + - 書式指定がある場合のみ 11章ルールで合成。 + +### 2) 外枠追従拡張(3x3 + 中央use) +- 10.9.1 を新設: + - 初期外枠 `R0` とアンカー `A` の相対余白(top/bottom/left/right)を保持。 + - 展開サイズ `H x W` を使い、`子範囲 + 余白` で外枠を再計算。 + - 3x3中央useの例では、子範囲を四辺1セル拡張した外枠になる。 + +### 3) 列overflow対応 +- 10.9 を行/列の両方向へ拡張。 +- 6章の失敗時ポリシーで `TemplateRangeOverflow` に `deltaRows/deltaCols` 記録を追加。 +- 11.5 / 12.2 / 12.3 の検証・リスク表も列方向前提へ更新。 + +## 期待効果 +- 挿入先無書式テンプレートと有書式テンプレートの両方を自然に運用可能。 +- 外枠フレームを持つテンプレートでも展開後の見た目を保ちやすい。 +- 横方向のサイズ超過による書式欠落を事前に防止できる。 diff --git a/reports/issue58-dsl-compatibility-e2e-2026-04-14.md b/reports/issue58-dsl-compatibility-e2e-2026-04-14.md new file mode 100644 index 0000000..68ae309 --- /dev/null +++ b/reports/issue58-dsl-compatibility-e2e-2026-04-14.md @@ -0,0 +1,37 @@ +# issue #58 DSL Compatibility Hardening And E2E Record + +- Date: 2026-04-14 +- Scope: Phase 14 / R58-11, R58-12, R58-13, R58-14 +- Reference: `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + +## Summary + +- Added `styleOverflow` support to ExcelTemplate use-trigger parsing. +- Added Excel expression normalization so emitted DSL is runtime-compatible. + - `@items` -> `@(root.Items)` + - `@group.Items` -> `@(group.Items)` + - `@item.Name` -> `@(item.Name)` +- Updated conversion snapshots to the normalized DSL-compatible shape. +- Added end-to-end tests for nested `GroupBlock` / `ItemRow`, `styleOverflow=edge`, and `cell@formula`. +- Added negative E2E coverage for `MergedCellBoundaryViolation` and `UnsupportedExcelTemplateFeature`. + +## Implemented Behavior + +- `UseTriggerParser` + - now accepts `styleOverflow` +- `ExcelTemplateOutputContractBuilder` + - propagates parsed `styleOverflow` + - normalizes Excel shorthand expressions before DSL emission +- E2E coverage + - nested component conversion preserves `styleOverflow="edge"` and normalized expressions in emitted DSL + - facade rendering produces final workbook content for nested `GroupBlock` / `ItemRow` + - validation issues from merged-boundary and unsupported conditional formatting are surfaced on final results + +## Verification + +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter ExcelTemplateEndToEndTests` + - Passed 3 +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter "ExcelTemplate|ReportGeneratorTests|ExcelTemplateEndToEndTests|ExcelTemplateReportGeneratorTests|ExcelTemplateConverterTests|XmlTemplateSerializerTests|DslEmitterTests|ExcelTemplateSnapshotTests"` + - Passed 86 +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj` + - Passed 256 diff --git a/reports/issue58-dsl-compatibility-e2e-review-2026-04-14.md b/reports/issue58-dsl-compatibility-e2e-review-2026-04-14.md new file mode 100644 index 0000000..5e1e45b --- /dev/null +++ b/reports/issue58-dsl-compatibility-e2e-review-2026-04-14.md @@ -0,0 +1,23 @@ +# issue #58 DSL Compatibility Hardening And E2E Review Record + +- Date: 2026-04-14 +- Scope: Phase 14 / R58-11, R58-12, R58-13, R58-14 + +## gpt-5.4 High Review Attempt + +- Attempted `gpt-5.4` / `high` review via `timeout 15s codex exec review --uncommitted -m gpt-5.4 -c model_reasoning_effort="high"`. +- The review timed out because the current sandbox blocks outbound Codex backend access. +- Captured error symptoms: + - `dns error` + - websocket connect failure to `chatgpt.com` + - `Operation not permitted` + +## Findings + +- External sub-agent findings: unavailable due network restriction in the current sandbox. +- Local review findings after implementation: none. + +## Final Status + +- issue #58 implementation tasks are complete in the current workspace. +- Independent `gpt-5.4/high` review still needs a network-enabled environment if strict external review evidence is required beyond the recorded attempts. diff --git a/reports/issue58-dsl-contract-extension-2026-04-12.md b/reports/issue58-dsl-contract-extension-2026-04-12.md new file mode 100644 index 0000000..bb4e5a4 --- /dev/null +++ b/reports/issue58-dsl-contract-extension-2026-04-12.md @@ -0,0 +1,60 @@ +# issue #58 DSL契約拡張 実装記録 + +- 作成日: 2026-04-12 +- 追記日: 2026-04-13 +- 対象: issue #58 ExcelTemplate 対応の実装第1段 +- ブランチ: `codex/create-design-document-for-approval` + +## 1. 実施内容 + +issue #58 の実装着手として、ExcelTemplate 変換器より先に必要な DSL 契約拡張を実装した。 + +今回反映した内容: + +- `cell@formula` を runtime schema / test fixture schema / AST / LayoutEngine に追加 +- `use@styleOverflow="none|edge"` を runtime schema / test fixture schema / AST / LayoutEngine に追加 +- `DslParser.ValidateDsl` に no-schema mode 用の補完検証を追加 + - `` の `value` と `formula` の同時指定を Error 化 + - `` の `styleOverflow` 不正値を Error 化 +- `IssueKind.TemplateRangeOverflow` を追加 +- `LayoutEngine` で `styleOverflow=edge` の post-expand 補完を追加 + - `use` の seed 書式を anchor 矩形の style-only `LayoutCell` として保持 + - right / down / corner の trailing edge copy を実装 + - legacy DSL への Warning ノイズを避けるため、overflow 追跡は ExcelTemplate 向けアンカー情報がある `use` に限定 +- `cell@formula` は `SUM(A1:A3)` のような `=` なし入力も受け付け、runtime では `=SUM(A1:A3)` に正規化 +- 既存互換として `cell@value="=..."` は従来どおり数式扱いを維持 + +2026-04-13 追記: + +- `styleOverflow=edge` の runtime テストを right に加えて down / right-down corner まで拡張した +- review 前に 3方向の補完挙動を unit test で固定した + +## 2. 変更ファイル + +- `Design/DslDefinition/DslDefinition_v2.xsd` +- `ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd` +- `ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/CellAst.cs` +- `ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/UseAst.cs` +- `ExcelReport/ExcelReportLib/DSL/DslParser.cs` +- `ExcelReport/ExcelReportLib/LayoutEngine/LayoutEngine.cs` +- `ExcelReport/ExcelReportLib.Tests/LayoutNodeTests.cs` +- `ExcelReport/ExcelReportLib.Tests/ValidateDslTests.cs` +- `ExcelReport/ExcelReportLib.Tests/DslParserTests.cs` +- `ExcelReport/ExcelReportLib.Tests/LayoutEngineTests.cs` + +## 3. テスト + +実施: + +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter "FullyQualifiedName~LayoutNodeTests|FullyQualifiedName~ValidateDslTests|FullyQualifiedName~DslParserTests|FullyQualifiedName~LayoutEngineTests"` +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj` + +結果: + +- 対象テスト: 72 passed +- 全体テスト: 216 passed, 0 failed + +## 4. 次の実装候補 + +次は handover と設計 13 章どおり、ExcelTemplate 側の中間モデル / extractor / validator / emitter へ進める。 +ただしその前に、今回追加した `styleOverflow=edge` の right/down/corner 実装を基準として、ExcelTemplate converter が `use` の anchor range と seed style をどう DSL へ落とすかを具体化してから進むのが安全。 diff --git a/reports/issue58-dsl-contract-extension-review-2026-04-13.md b/reports/issue58-dsl-contract-extension-review-2026-04-13.md new file mode 100644 index 0000000..00601a1 --- /dev/null +++ b/reports/issue58-dsl-contract-extension-review-2026-04-13.md @@ -0,0 +1,33 @@ +# issue #58 DSL契約拡張 review 記録 + +- 作成日: 2026-04-13 +- 対象: `cell@formula` / `use@styleOverflow` / `TemplateRangeOverflow` 実装差分 +- 要求レビュー条件: sub-agent `gpt-5.4` / `high` + +## 1. review 実施状況 + +1. 組み込み sub-agent 呼び出しを実施 + - `gpt-5.4` / `high` を指定して review を依頼 +2. ローカル Codex CLI でも `gpt-5.4` / `high` review を試行 + - 実行コマンド: `codex review --uncommitted -c model="gpt-5.4" -c reasoning_effort="high" -c approval_policy="never" -c sandbox_mode="workspace-write"` + - 結果: このセッションの network 制限により websocket 接続が `Operation not permitted` で失敗し、CLI 経由の review 結果は取得不能 + +## 2. 対応 + +- sub-agent review の結果取得が不安定だったため、review 前提で不足しやすいケースを先に補強した + - `styleOverflow=edge` の down 方向コピー + - `styleOverflow=edge` の right-down corner コピー +- 差分の自己点検を実施し、追加の実装修正が必要な不整合は検出しなかった + +## 3. テスト + +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter "FullyQualifiedName~LayoutNodeTests|FullyQualifiedName~ValidateDslTests|FullyQualifiedName~DslParserTests|FullyQualifiedName~LayoutEngineTests"` + - 72 passed +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj` + - 216 passed, 0 failed + +## 4. 結論 + +- 現セッションでは `gpt-5.4` / `high` の CLI review は network 制限で完走できなかった +- 実装差分自体は追加テスト補強後も全件通過しており、手元確認では追加指摘なし +- 残留リスクは、ExcelTemplate converter 実装着手時に `use` anchor range と seed style の DSL 出力契約を E2E で再確認する点 diff --git a/reports/issue58-dsl-emitter-2026-04-13.md b/reports/issue58-dsl-emitter-2026-04-13.md new file mode 100644 index 0000000..942fdbb --- /dev/null +++ b/reports/issue58-dsl-emitter-2026-04-13.md @@ -0,0 +1,37 @@ +# issue #58 DslEmitter + +Date: 2026-04-13 + +## Summary +- 対象 task: `R58-03 DslEmitter の基本出力を実装する` +- あわせて `R58-04 DslEmitter で cell@formula / styleOverflow / direction="down" を反映する` まで同時に完了 +- 方針: `DslEmitter` は `XmlTemplateSerializer` の DSL 互換 XML を再利用し、UTF-8 declaration 付き text 出力の責務に絞る + +## TDD +1. Red + - `DslEmitterTests` を追加し、`DslEmitter` 未定義の compile error を確認 +2. Green + - `DslEmitter` を追加 + - `XmlTemplateSerializer` の `XDocument` を UTF-8 declaration 付き XML text へ整形出力 +3. Verify + - `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter DslEmitterTests` + - Passed 2 + - `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter "ExcelTemplate|XmlTemplateSerializerTests|DslEmitterTests"` + - Passed 26 + - `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj` + - Passed 242 + +## Fixed Behavior +- XML declaration: `` +- DSL root/body: `workbook/component/grid/sheet/cell/use/repeat` +- `cell@formula` を text 出力へ保持 +- explicit `use@styleOverflow` を text 出力へ保持 +- `repeat@direction="down"` を text 出力へ保持 +- emitted text は `DslParser + XSD validation` で parse 可能 + +## Files +- `ExcelReport/ExcelReportLib/ExcelTemplate/DslEmitter.cs` +- `ExcelReport/ExcelReportLib.Tests/DslEmitterTests.cs` + +## Residual Risk +- `DslEmitter` は serializer の薄い wrapper なので、text 形状の安定化は `R58-06` の snapshot で固定する必要がある diff --git a/reports/issue58-dsl-emitter-review-2026-04-13.md b/reports/issue58-dsl-emitter-review-2026-04-13.md new file mode 100644 index 0000000..a6a7dd2 --- /dev/null +++ b/reports/issue58-dsl-emitter-review-2026-04-13.md @@ -0,0 +1,11 @@ +# issue #58 DslEmitter Review + +Date: 2026-04-13 +Reviewer: sub-agent `gpt-5.4` / `high` + +## Review Result +- Findings: なし + +## Residual Risks +- `DslEmitter` は `XmlTemplateSerializer` の薄い wrapper なので、serializer 側の formatting 変更が DSL text に波及する +- full snapshot で whitespace / comment ordering を固定する作業は `R58-06` で必要 diff --git a/reports/issue58-excel-template-extractor-2026-04-13.md b/reports/issue58-excel-template-extractor-2026-04-13.md new file mode 100644 index 0000000..161fa9c --- /dev/null +++ b/reports/issue58-excel-template-extractor-2026-04-13.md @@ -0,0 +1,58 @@ +# issue #58 ExcelTemplate extractor 実装記録 + +- 作成日: 2026-04-13 +- 対象: issue #58 ExcelTemplate 対応の実装第2段 +- ブランチ: `codex/create-design-document-for-approval` + +## 1. 実施内容 + +ExcelTemplate 変換層の最初の実装として、中間モデルと extractor の最小読取を追加した。 + +今回反映した内容: + +- `ExcelTemplateExtractor` を追加 +- 中間モデルを追加 + - `ExcelTemplateWorkbook` + - `ExcelTemplateSheet` + - `ExcelTemplateCell` + - `ExcelTemplateStyle` + - `ExcelTemplateComponentRange` +- OpenXML から次を抽出可能にした + - workbook の sheet 一覧 + - cell の A1参照 / row / col / 値 / 数式 / style index + - workbook defined names + - sheet merged ranges +- まずは extractor を OpenXML 読み取り専用に留め、sheet 分類 / component 範囲解決 / trigger 解析 / validator は未着手のまま分離した + +## 2. テスト + +実施: + +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter "FullyQualifiedName~ExcelTemplateExtractorTests"` +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj` + +結果: + +- extractor 対象テスト: 2 passed +- 全体テスト: 218 passed, 0 failed + +## 3. review + +要求レビュー条件は sub-agent `gpt-5.4` / `high`。 + +試行: + +- `codex review --uncommitted -c model="gpt-5.4" -c reasoning_effort="high" -c approval_policy="never" -c sandbox_mode="workspace-write"` + +結果: + +- このセッションの network 制限により `https://chatgpt.com/backend-api/codex/responses` への接続が `Operation not permitted` で失敗し、review は完走できなかった +- 実装修正が必要な追加指摘は取得できていないため、今回は差分自己点検 + 全体回帰を代替エビデンスとして記録する + +## 4. 次の実装候補 + +次は設計 13.5 順序どおり、以下のいずれかへ進む。 + +1. `ComponentRangeResolver` と `__component_` / `__component_range_` 解決 +2. `UseTriggerParser` で `{{use:...}}` を正規化 +3. `ExcelTemplateValidator` で merged cell 境界・対象外機能を Error/Warning 化 diff --git a/reports/issue58-excel-template-facade-2026-04-14.md b/reports/issue58-excel-template-facade-2026-04-14.md new file mode 100644 index 0000000..095fd48 --- /dev/null +++ b/reports/issue58-excel-template-facade-2026-04-14.md @@ -0,0 +1,41 @@ +# issue #58 ExcelTemplate Facade Implementation Record + +- Date: 2026-04-14 +- Scope: Phase 13 / R58-09, R58-10 +- Reference: `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + +## Summary + +- Added `ExcelTemplateReportGenerator` as the facade from `xlsx` directly to final `xlsx`. +- Added `ExcelTemplateGenerateOptions` to separate conversion options from downstream `ReportGeneratorOptions`. +- Kept the existing `ReportGenerator` public API unchanged and implemented the ExcelTemplate entry point as a thin composition layer. +- Preserved conversion issues on the final `ReportGeneratorResult`. +- Short-circuited the facade before DSL execution when conversion returns a fatal issue. + +## Implemented Behavior + +- `GenerateFromExcelTemplate(string xlsxPath, object? data, ExcelTemplateGenerateOptions? options = null, CancellationToken cancellationToken = default)` + - converts ExcelTemplate workbook to DSL text + - logs conversion issues into the same logger used by downstream report generation + - aborts early on fatal conversion issues + - otherwise calls the existing `ReportGenerator.Generate` + - returns a final `ReportGeneratorResult` that includes both conversion issues and report-generation issues + +## TDD + +- Added `ExcelTemplateReportGeneratorTests` + - valid workbook -> final xlsx output + - corrupt workbook -> fatal load issue, no output + - non-fatal conversion issue -> output preserved and issue merged +- Extended `ExcelTemplateTestWorkbookFactory` + - report workbook fixture + - report workbook fixture with non-fatal conversion issue + +## Verification + +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter ExcelTemplateReportGeneratorTests` + - Passed 3 +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter "ExcelTemplate|ReportGeneratorTests|ExcelTemplateReportGeneratorTests|ExcelTemplateConverterTests|XmlTemplateSerializerTests|DslEmitterTests|ExcelTemplateSnapshotTests"` + - Passed 81 +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj` + - Passed 251 diff --git a/reports/issue58-excel-template-facade-review-2026-04-14.md b/reports/issue58-excel-template-facade-review-2026-04-14.md new file mode 100644 index 0000000..56c6c7b --- /dev/null +++ b/reports/issue58-excel-template-facade-review-2026-04-14.md @@ -0,0 +1,23 @@ +# issue #58 ExcelTemplate Facade Review Record + +- Date: 2026-04-14 +- Scope: Phase 13 / R58-09, R58-10 + +## gpt-5.4 High Review Attempt + +- Attempted `gpt-5.4` / `high` review via `timeout 15s codex exec review --uncommitted -m gpt-5.4 -c model_reasoning_effort="high"`. +- The review timed out because Codex backend access was blocked by the current sandbox network policy. +- Captured error symptoms: + - model refresh request failure + - `dns error` + - websocket connect failure to `chatgpt.com` + - `Operation not permitted` + +## Findings + +- External sub-agent findings: unavailable due network restriction in the current sandbox. +- Local review findings after implementation: none. + +## Residual Risk + +- External review has not yet completed successfully in this sandbox, so an independent `gpt-5.4/high` pass still needs to be retried in a network-enabled environment. diff --git a/reports/issue58-expanded-cell-values-svg-2026-04-12.md b/reports/issue58-expanded-cell-values-svg-2026-04-12.md new file mode 100644 index 0000000..fd870c9 --- /dev/null +++ b/reports/issue58-expanded-cell-values-svg-2026-04-12.md @@ -0,0 +1,21 @@ +# issue #58 追補: C#データ展開後セル値SVGの追加 (2026-04-12) + +## 目的 +- 設計書上で、C#サンプルデータ適用後に最終的にどのセルへ何が入るかを、座標付きで視覚確認できるようにする。 + +## 対応内容 +1. 設計書追記 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` +- `10.10.1 C#データ展開後セル値のSVG` を追加。 + +2. SVG追加 +- `Design/ExcelTemplate/assets/expanded-cell-values-from-csharp.svg` +- 内容: + - `Invoice` シートの展開後イメージ + - `A1=請求書` + - `A3=機械部品`, `A4:C6=3件の明細` + - `A7=電材`, `A8:C8=1件の明細` + +## 設計上の意図 +- 10.10 の C#サンプル入力と 10.9 のサイズ不一致ルールを、最終セル値で突き合わせてレビュー可能にする。 +- SVGは表示値のみを扱い、書式説明は既存のMarkdown表(10.8.5)に集約する方針を維持する。 diff --git a/reports/issue58-expanded-svg-style-rework-2026-04-12.md b/reports/issue58-expanded-svg-style-rework-2026-04-12.md new file mode 100644 index 0000000..f00751f --- /dev/null +++ b/reports/issue58-expanded-svg-style-rework-2026-04-12.md @@ -0,0 +1,23 @@ +# issue #58 追補: 展開後SVGの書式スタイル再設計 (2026-04-12) + +## 背景 +- ユーザー指摘により、`expanded-cell-values-from-csharp.svg` の書式表現が実際の設計ルール(11章)と一致していない懸念を確認。 + +## 修正内容 +1. SVGスタイルを再設計 +- 対象: `Design/ExcelTemplate/assets/expanded-cell-values-from-csharp.svg` +- 変更: + - 背景色主体の表現を廃止 + - 親component外枠を濃紺実線で表現 + - 子component明細bottomを青破線で表現 + - 親子競合辺(子優先 + Warning)を赤破線で表現 + - 凡例(Legend)を追加 + +2. 設計書へ対応関係を追記 +- 対象: `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` +- 追記箇所: `10.10.1` +- 追記内容: 線種とルールの対応(濃紺実線/青破線/赤破線) + +## 期待効果 +- 展開後セル値と書式ルール(親外枠・子明細・競合解決)の整合を図上で即座にレビュー可能。 +- 仕様レビュー時に「見た目は合っているがルールが異なる」状態を検出しやすくする。 diff --git a/reports/issue58-final-review-2026-04-14-round3.md b/reports/issue58-final-review-2026-04-14-round3.md new file mode 100644 index 0000000..5ac210c --- /dev/null +++ b/reports/issue58-final-review-2026-04-14-round3.md @@ -0,0 +1,55 @@ +# issue #58 Final Review Round 3 + +- Date: 2026-04-14 +- Reviewer: `gpt-5.4` / `high` +- Scope note: + - `git status --short` was clean at review time. + - Because there were no uncommitted changes left, this review covered the effective final issue #58 delta in the latest committed range: + - `545e1c0` `feat: add excel template conversion api` + - `26e86f2` `feat: add excel template report facade` + - `57af77c` `feat: complete excel template e2e flow` + +## Findings + +1. Medium - bare shorthand identifiers are always rewritten to `root.*`, which breaks repeat/local-scope expressions. + - File: `ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateExpressionNormalizer.cs:32-35` + - Why it matters: + - The normalizer unconditionally rewrites any simple shorthand like `@item` to `@(root.Item)`. + - That is correct for root collections such as `@groups`, but it is incorrect for repeat/local variables. Inside repeated content, the DSL runtime already supports scoped expressions like `@(it)`, so the shorthand counterpart `@item` should map to `@(item)`, not `@(root.Item)`. + - As written, a template cell whose intended value is the current repeated object will resolve against the workbook root instead of the local repeat variable. + - Evidence: + - Existing DSL runtime/tests already rely on bare scoped expressions, for example `@(it)` in `ExcelReport/ExcelReportLib.Tests/LayoutEngineTests.cs:958`. + - Recommendation: + - Make normalization context-aware instead of blindly prepending `root.` for every simple identifier. + - Add regression coverage for cell values like `@item` / `@group` inside repeated components. + +2. Medium - the happy-path E2E does not actually verify repeated `GroupBlock` placement, so the most important nested-repeat case remains unguarded. + - File: `ExcelReport/ExcelReportLib.Tests/ExcelTemplateEndToEndTests.cs:55-68` + - Why it matters: + - The final Phase 14 E2E test only passes a single `group`, so it exercises nested `ItemRow` repetition but not repeated top-level `GroupBlock` placement. + - That means row-shift/overlap behavior for the second `GroupBlock` instance is still unverified even though Phase 14 is marked complete. + - Supporting references: + - Claimed complete in `tasks/tasks-status.md:106-109` + - Claimed complete in `tasks/phases-status.md:88` + - The fixture itself is clearly designed for top-level `@groups` repetition in `ExcelReport/ExcelReportLib.Tests/ExcelTemplateTestWorkbookFactory.cs:240-270` + - Recommendation: + - Add a second happy-path E2E with at least two groups and assert the second group’s placement/cell values. + - Keep the current single-group test if useful, but it is not sufficient as the closeout proof for nested repeat/use. + +3. Low - the final status documents still contain contradictory closeout wording, which weakens the “remaining work is always visible” requirement. + - Files: + - `tasks/tasks-status.md:89-92` + - `tasks/phases-status.md:78-81` + - Why it matters: + - Both files say issue #58 is complete with `0 tasks / 0 phases`, but the adjacent shelf-inventory note still says Phase 14 work “was added”. + - In isolation, that wording reads as if new work was discovered but not clearly closed, which is exactly the ambiguity the user asked to avoid. + - Recommendation: + - Rephrase those lines to explicitly say the additional Phase 14 hardening tasks were identified and completed in the same cycle. + +## Summary + +- Findings: 3 +- Highest severity: Medium +- Residual risk: + - The code path for root shorthand normalization is covered, but repeat/local shorthand normalization is not. + - Final E2E coverage is strong for conversion and single-group rendering, but still thin for multi-group nested expansion. diff --git a/reports/issue58-final-review-2026-04-14-round4.md b/reports/issue58-final-review-2026-04-14-round4.md new file mode 100644 index 0000000..98ab8d6 --- /dev/null +++ b/reports/issue58-final-review-2026-04-14-round4.md @@ -0,0 +1,29 @@ +# issue #58 Final Review Round 4 + +- Date: 2026-04-14 +- Scope: issue #58 related uncommitted changes in the current workspace +- Focus: + - local repeat variable vs root shorthand normalization + - multi-`GroupBlock` happy-path E2E + - tasks/phases closeout wording + +## Findings + +1. Medium - local/root shorthand normalization is still resolved with workbook-global variable names instead of lexical scope. + - `ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateOutputContractBuilder.cs:30` + - `ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateOutputContractBuilder.cs:116-133` + - `ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateExpressionNormalizer.cs:35-40` + - Why: + - The fix now avoids rewriting `@item` to `@(root.Item)` when `item` is known as a repeat variable, but that knowledge is collected once for the whole workbook. + - As a result, if any trigger anywhere defines `var:item`, every simple shorthand `@item` in the workbook will be normalized to `@(item)`, even in cells that are outside that repeat scope and should still resolve against `root`. + - Risk: + - A root property whose name collides with any repeat variable becomes impossible to express with shorthand in unrelated sheets/components. + - This is a scope leak, not a true fix of the original context problem. + - Test gap: + - `ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractBuilderTests.cs:180-206` verifies the positive local case only. + - There is still no regression test for the collision case: local `var:item` exists somewhere, but another cell’s `@item` should remain `@(root.Item)`. + +## Notes + +- Point 2 is improved: the happy-path E2E now uses two groups and asserts the second group placement (`ExcelReport/ExcelReportLib.Tests/ExcelTemplateEndToEndTests.cs:57-91`). +- Point 3 is improved: the tasks/phases closeout wording is now internally consistent enough for the requested “completed in the same cycle” interpretation (`tasks/tasks-status.md:88-92`, `tasks/phases-status.md:77-81`). diff --git a/reports/issue58-final-review-2026-04-14-round5.md b/reports/issue58-final-review-2026-04-14-round5.md new file mode 100644 index 0000000..c02231a --- /dev/null +++ b/reports/issue58-final-review-2026-04-14-round5.md @@ -0,0 +1,32 @@ +# issue #58 Final Review Round 5 + +- Date: 2026-04-14 +- Scope: + - `ExcelTemplateExpressionNormalizer` / `ExcelTemplateOutputContractBuilder` scope fix + - `ExcelTemplateOutputContractBuilderTests` additions + - `ExcelTemplateEndToEndTests` multi-`GroupBlock` coverage + - `tasks` / `phases` closeout wording + +## Findings + +1. Medium - local shorthand normalization is still keyed by component name, so the same component cannot be safely reused with different repeat variable aliases. + - `ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateOutputContractBuilder.cs:31` + - `ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateOutputContractBuilder.cs:39-47` + - `ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateOutputContractBuilder.cs:121-148` + - Why: + - The fix now avoids workbook-global leakage by collecting local variable names per component, which is an improvement. + - But the emitted DSL component definition is still normalized once using the union of all variable names observed for that component across all call sites. + - If one workbook uses the same component as `{{use:ItemRow, ..., var:item}}` and elsewhere as `{{use:ItemRow, ..., var:entry}}`, a shorthand cell like `@item` inside `ItemRow` will be normalized as local even for the `entry` call site, and vice versa. + - Test gap: + - The new tests cover the positive local case and cross-component non-leak: + - `ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractBuilderTests.cs:180-206` + - `ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractBuilderTests.cs:213-240` + - There is still no regression for same-component multi-alias reuse. + +## Notes + +- Multi-`GroupBlock` happy-path E2E is improved and now actually asserts the second group’s placement: + - `ExcelReport/ExcelReportLib.Tests/ExcelTemplateEndToEndTests.cs:57-91` +- `tasks` / `phases` closeout wording is now internally consistent with “identified and completed in the same cycle”: + - `tasks/tasks-status.md:88-92` + - `tasks/phases-status.md:77-81` diff --git a/reports/issue58-final-review-2026-04-14-round6.md b/reports/issue58-final-review-2026-04-14-round6.md new file mode 100644 index 0000000..2868717 --- /dev/null +++ b/reports/issue58-final-review-2026-04-14-round6.md @@ -0,0 +1,29 @@ +# issue #58 Final Review Round 6 + +- Date: 2026-04-14 +- Scope: + - `ExcelTemplateOutputContractBuilder` scope resolution and issue emission + - `ExcelTemplateOutputContractBuilderTests` new regression cases + - existing issue #58 changes for new inconsistencies +- Verification: + - `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~ExcelTemplateOutputContractBuilderTests|FullyQualifiedName~ExcelTemplateEndToEndTests"` + - Result: `Passed 10, Failed 0` + +## Findings + +1. Medium - ambiguous-normalization errors are raised for every multi-alias component reuse, even when the component contains no ambiguous shorthand at all. + - `ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateOutputContractBuilder.cs:150-166` + - Why: + - `ResolveComponentVariableScopes` emits `InvalidAttributeValue` as soon as a component is referenced by more than one repeat variable name. + - That is stricter than the stated rule. The rule is to reject ambiguous local shorthand normalization, not to reject all multi-alias reuse of a component. + - A component that only uses explicit expressions like `@item.Name` / `@row.Name` (or no shorthand-local expressions at all) is not ambiguous, but this implementation still marks it as an error solely because two aliases exist. + - Missing regression: + - The added test covers the ambiguous case only: + - `ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractBuilderTests.cs:247-274` + - There is still no coverage for a valid multi-alias component whose cells avoid ambiguous simple shorthand. + +## Notes + +- Multi-`GroupBlock` happy-path E2E remains improved and still looks sound: + - `ExcelReport/ExcelReportLib.Tests/ExcelTemplateEndToEndTests.cs:57-91` +- `tasks` / `phases` wording remains consistent with “identified and completed in the same cycle”. diff --git a/reports/issue58-final-review-2026-04-14-round7.md b/reports/issue58-final-review-2026-04-14-round7.md new file mode 100644 index 0000000..e641f4b --- /dev/null +++ b/reports/issue58-final-review-2026-04-14-round7.md @@ -0,0 +1,25 @@ +# issue #58 Final Review Round 7 + +- Date: 2026-04-14 +- Reviewer: final workspace review + +## Findings + +findingsなし + +## Verification + +- Reviewed current final implementation state for issue #58. +- Confirmed convergence for: + - shorthand / local scope normalization + - multi-`GroupBlock` happy-path E2E + - `tasks` / `phases` closeout consistency with remaining work = 0 +- Test results: + - `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --configuration Release --no-restore --filter "FullyQualifiedName~ExcelTemplateOutputContractBuilderTests|FullyQualifiedName~ExcelTemplateEndToEndTests|FullyQualifiedName~ExcelTemplateConverterTests|FullyQualifiedName~ExcelTemplateReportGeneratorTests"` + - Passed 17, Failed 0 + - `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --configuration Release --no-restore` + - Passed 259, Failed 0 + +## Reviewed Commit Range + +- `57af77c..6de8a27` diff --git a/reports/issue58-formula-normalization-decision-2026-04-12.md b/reports/issue58-formula-normalization-decision-2026-04-12.md new file mode 100644 index 0000000..1a85277 --- /dev/null +++ b/reports/issue58-formula-normalization-decision-2026-04-12.md @@ -0,0 +1,15 @@ +# issue #58 数式正規化方針の確定 + +## 決定 +- 数式セルは原則 `cell@formula` へ変換する。 +- C# 側で Excel 関数の計算を再実装することは想定しない。 +- したがって、数式セルを `cell@value` の計算済み値へ潰す運用は採らない。 + +## 反映 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + - 5章の DSL マッピングルールを `cell@formula` 原則へ修正 + - 12.1 の事前合意内容を確定事項へ修正 + - 12.6 から数式正規化の確認質問を削除 + +## 補足 +- これは「Excel 上で持っている数式を保持する」方針であり、C# 側で Excel 関数の意味論まで再現する仕様ではない。 diff --git a/reports/issue58-gpt54-review-followup-2026-04-12.md b/reports/issue58-gpt54-review-followup-2026-04-12.md new file mode 100644 index 0000000..1475293 --- /dev/null +++ b/reports/issue58-gpt54-review-followup-2026-04-12.md @@ -0,0 +1,20 @@ +# issue #58 gpt-5.4 review 指摘対応メモ + +## レビュー結果 +- reviewer: `gpt-5.4` +- reasoning: `high` +- findings: + - Medium: `styleOverflow=edge` の left / up 要件が、現行の外枠拡張モデルと不整合 + - Low: `style-overflow-modes-3x3.svg` の文脈が `GroupBlock` と誤認されやすい + +## 対応 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + - `use` 展開はアンカー起点で right / down 方向へ成長するモデルと明記 + - `styleOverflow=edge` を trailing edge(右辺 / 下辺 / 右下角)へ限定 + - 10.9.4 と 11.5 の left / up ケースを削除し、right / down / right-down corner に揃えた +- `Design/ExcelTemplate/assets/style-overflow-modes-3x3.svg` + - 図中ラベルを `@child.Header` / `{{use:ChildRow,...}}` へ変更し、overflow 比較専用ケースであることを明確化 + +## 結果 +- `10.9.1` の外枠拡張式と `10.9.2/10.9.4/11.5` の仕様が同じ方向性になった。 +- overflow 比較SVGが `GroupBlock` 本文例と混同されにくくなった。 diff --git a/reports/issue58-implementation-approach-2026-04-12.md b/reports/issue58-implementation-approach-2026-04-12.md new file mode 100644 index 0000000..59d52ab --- /dev/null +++ b/reports/issue58-implementation-approach-2026-04-12.md @@ -0,0 +1,200 @@ +# issue #58 実装方針レポート + +- 作成日: 2026-04-12 +- 対象: `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` +- 目的: ExcelTemplate 対応の実装順序、統合ポイント、既存コードとの差分を固定する + +## 1. 調査結果 + +現行の実行経路は次のとおり。 + +```text +ReportGenerator + -> DslParser + -> LayoutEngine + -> WorksheetStateBuilder + -> XlsxRenderer +``` + +確認した主要ファイル: +- `ExcelReport/ExcelReportLib/ReportGenerator.cs` +- `ExcelReport/ExcelReportLib/DSL/DslParser.cs` +- `ExcelReport/ExcelReportLib/LayoutEngine/LayoutEngine.cs` +- `ExcelReport/ExcelReportLib/WorksheetState/WorksheetStateBuilder.cs` +- `ExcelReport/ExcelReportLib/Renderer/XlsxRenderer.cs` + +判断: +- 後段パイプラインは既に成立しているため、Issue #58 は「前段に ExcelTemplate 変換層を追加する」実装として進めるのが最小リスク。 +- `ReportGenerator` を直接 ExcelTemplate 対応へ書き換えるより、新しい facade を追加して既存 DSL 経路を再利用する方が安全。 + +## 2. 現行コードとの差分 + +設計をそのまま実装するには、次の差分がある。 + +1. ExcelTemplate 変換層が存在しない + - `ExcelTemplateExtractor` + - `XmlTemplateSerializer` + - `DslEmitter` + - `ExcelTemplateReportGenerator` +2. `cell@formula` が DSL 契約に存在しない + - 現行は `cell@value` が `=` で始まると数式扱い + - 設計は `cell@formula` 正規化を要求 +3. `use@styleOverflow` が DSL 契約/runtime に存在しない + - XSD / `UseAst` / `LayoutEngine` の拡張が必要 +4. ExcelTemplate 専用 validation が存在しない + - component 範囲 + - merged cell 境界 + - unsupported feature + - overflow warning +5. `repeat` は `direction` 必須 + - converter は `direction="down"` を明示出力しないと現行 DSL では parse error になる + +## 3. 実装方針 + +### 3.1 方針の軸 +- additive change を優先する +- ExcelTemplate は DSL へ変換してから既存後段へ流す +- runtime 契約の不足は先に埋める +- 初版対象外は validator で明示検出する + +### 3.2 実装順序 +1. DSL 契約拡張 +2. レイアウト runtime 補完 +3. ExcelTemplate 中間モデル +4. OpenXML extractor + validator +5. DslEmitter / XmlTemplateSerializer +6. ExcelTemplate facade API +7. E2E 固定 + +### 3.3 この順序にする理由 +- `cell@formula` と `styleOverflow` が未実装のままでは、変換器が正しい DSL を吐いても downstream が処理できない +- `repeat` に `direction` を明示しないと emitted DSL 自体が現行 parser で失敗する +- Excel 読み取りと DSL 生成を分離すると、debug XML / DSL snapshot / runtime の責務が崩れない +- facade を最後に載せることで、単体検証が済んだ部品を組み合わせる形にできる + +## 4. 具体的な実装単位 + +### 4.1 DSL 契約拡張 +対象: +- `Design/DslDefinition/DslDefinition_v2.xsd` +- `ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd` +- `ExcelReport/ExcelReportLib/DSL/DslContract.cs` +- `ExcelReport/ExcelReportLib/DSL/DslParser.cs` +- `ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/CellAst.cs` +- `ExcelReport/ExcelReportLib/DSL/AST/LayoutNode/UseAst.cs` +- `ExcelReport/ExcelReportLib/LayoutEngine/LayoutEngine.cs` + +作業: +- `cell@formula` を XSD/AST に追加 +- runtime が読む埋め込み schema と test fixture schema の両方を更新 +- `CellAst` は `formula` と `value` を明確に分離 +- `DslParser.ValidateDsl` に no-schema mode 用の契約検証を追加 +- `LayoutEngine` は `formula` を優先して `LayoutCell.Formula` へ流す +- `use@styleOverflow="none|edge"` を XSD/AST に追加 +- `repeat` は converter が `direction="down"` を明示出力する前提で統一 + +### 4.2 レイアウト runtime 補完 +対象: +- `ExcelReport/ExcelReportLib/LayoutEngine/LayoutEngine.cs` +- `ExcelReport/ExcelReportLib/LayoutEngine/LayoutCell.cs` + +作業: +- `styleOverflow=edge` は `ExpandUse` / `ExpandRepeat` の後段処理として実装する +- 挿入先 seed 書式は「値なしでも style を持つ `LayoutCell`」として保持する +- trailing edge copy は row / col / corner ごとに style-onlyセルを合成する +- 競合解決は 11章の border/style ルールへ委譲する + +### 4.3 ExcelTemplate モデルと extractor +新規追加候補: +- `ExcelTemplate/Model/ExcelTemplateWorkbook.cs` +- `ExcelTemplate/Model/ExcelTemplateSheet.cs` +- `ExcelTemplate/Model/ExcelTemplateCell.cs` +- `ExcelTemplate/Model/ExcelTemplateStyle.cs` +- `ExcelTemplate/Model/ExcelTemplateComponentRange.cs` +- `ExcelTemplate/ExcelTemplateExtractor.cs` +- `ExcelTemplate/ExcelTemplateValidator.cs` +- `ExcelTemplate/ComponentRangeResolver.cs` +- `ExcelTemplate/UseTriggerParser.cs` + +役割: +- extractor: OpenXML 読み取り +- validator: 初版対象外/不正入力の集約 +- resolver: component 定義範囲の決定 +- parser: `{{use:...}}` trigger を DSL 相当へ正規化 + +### 4.4 出力器 +新規追加候補: +- `ExcelTemplate/DslEmitter.cs` +- `ExcelTemplate/XmlTemplateSerializer.cs` +- `ExcelTemplate/ExcelTemplateConverter.cs` + +役割: +- XML debug 出力 +- DSL text 出力 +- 変換入口の統一 + +### 4.5 facade +新規追加候補: +- `ExcelTemplate/ExcelTemplateReportGenerator.cs` +- `ExcelTemplate/ExcelTemplateGenerateOptions.cs` + +役割: +- ExcelTemplate -> DSL 変換 +- 既存 `ReportGenerator` 呼び出し +- logger / issues の統合 + +API 方針: +- `ConvertToDsl` / `ConvertToXmlTemplate` は `string` ではなく result object を返す +- result object は `Text` と `Issues` を持ち、conversion-only 呼び出しでも座標付き Warning/Error を失わない + +## 5. テスト方針 + +### 5.1 Unit +- `cell@formula` parser/runtime +- `styleOverflow=edge` +- `UseTriggerParser` +- `ComponentRangeResolver` +- `repeat@direction="down"` 明示出力 +- extractor の値/数式/スタイル/defined name/merged cell +- 後方互換: `cell@value="=..."` が従来どおり数式として動くこと + +### 5.2 Integration +- xlsx -> xml snapshot +- xlsx -> dsl snapshot + +### 5.3 E2E +- xlsx -> dsl -> final xlsx +- `GroupBlock` / `ItemRow` +- `styleOverflow=edge` +- `cell@formula` +- merged cell violation +- unsupported conditional formatting + +## 6. リスクと対策 + +| リスク | 影響 | 対策 | +|---|---|---| +| `cell@formula` と現行 `value=\"=...\"` の二重契約 | 互換崩れ | `formula` 優先、既存 `value=\"=...\"` は後方互換として残し、回帰テストで固定する | +| `styleOverflow` 実装が広がりすぎる | 実装膨張 | 初版は right/down/right-down corner のみ | +| Excel 自由入力の未対応機能 | silent corruption | validator で Warning/Error を強制 | +| merged cell 境界崩れ | 出力破損 | 初版は矩形内完結のみ許可 | +| schema validation 無効時に契約逸脱を見逃す | 実行時不整合 | `ValidateDsl` に追加検証を実装する | + +## 7. 実装開始条件 + +以下を満たしたら実装着手してよい。 + +1. 設計書 13章の方針に reviewer 合意がある +2. `cell@formula` / `styleOverflow` の DSL 契約拡張を先行タスクに置く +3. `styleOverflow=edge` を `LayoutEngine` の post-expand 処理として実装する方針に合意がある +4. 初版対象外を validator で止める方針にブレがない + +## 8. 推奨着手順 + +1. DSL 契約拡張と unit test +2. runtime 補完 (`styleOverflow=edge`) と unit test +3. extractor/model と unit test +4. emitter/snapshot test +5. facade/E2E + +この順で進めると、途中段階でも差分が小さく、レビュー単位を保ちやすい。 diff --git a/reports/issue58-implementation-approach-review-2026-04-12.md b/reports/issue58-implementation-approach-review-2026-04-12.md new file mode 100644 index 0000000..9de30f7 --- /dev/null +++ b/reports/issue58-implementation-approach-review-2026-04-12.md @@ -0,0 +1,44 @@ +# issue #58 実装方針レビュー記録 + +- 作成日: 2026-04-12 +- reviewer: sub-agent `gpt-5.4` / `high` +- 対象: + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + - `reports/issue58-implementation-approach-2026-04-12.md` + +## 指摘事項 + +1. High: runtime schema 更新対象が不足 + - test fixture XSD だけでなく、runtime が読む `Design/DslDefinition/DslDefinition_v2.xsd` と埋め込み schema 経路も対象化する必要がある +2. High: `repeat@direction` 必須との契約不一致 + - design example / emitted DSL に `direction="down"` を明示する必要がある +3. High: `styleOverflow=edge` の実装位置が未固定 + - `LayoutEngine` 内のどの段で seed 書式を増分領域へコピーするかを先に決める必要がある +4. Medium: conversion-only API が診断情報を返せていない + - DSL/XML 文字列だけでなく `Issues` 返却が必要 +5. Medium: `cell@value="=..."` 後方互換の回帰テストが未明記 +6. Medium: schema validation 無効時の `ValidateDsl` 補完検証が未明記 + +## 対応内容 + +1. 実装方針へ runtime schema の更新対象を追加 + - `Design/DslDefinition/DslDefinition_v2.xsd` + - `ExcelReport/ExcelReportLib.Tests/TestDsl/DslDefinition_v2.xsd` + - `DslContract` / `DslParser.ValidateDsl` +2. design example を `direction="down"` 明示へ統一 +3. `styleOverflow=edge` は `LayoutEngine` の post-expand 処理として固定 + - style-only seed cell を `LayoutCell` として保持 + - row / col / corner 単位で trailing edge copy +4. `ConvertToDsl` / `ConvertToXmlTemplate` は result object + `Issues` 返却へ修正 +5. unit test 計画に legacy `cell@value="=..."` 回帰を追加 +6. `ValidateDsl` で no-schema mode 時の契約検証追加を明記 + +## 結論 + +重大指摘は実装方針へ反映済み。 + +実装着手前に固定された重要事項: +- `repeat` は converter が `direction="down"` を明示出力する +- `styleOverflow=edge` は `LayoutEngine` の post-expand で実装する +- conversion-only API でも `Issues` を返す +- schema validation 無効時も `ValidateDsl` で契約逸脱を止める diff --git a/reports/issue58-investigation-2026-04-07.md b/reports/issue58-investigation-2026-04-07.md new file mode 100644 index 0000000..ceec306 --- /dev/null +++ b/reports/issue58-investigation-2026-04-07.md @@ -0,0 +1,46 @@ +# issue #58 調査レポート (2026-04-07) + +## 実施内容 +- ローカルリポジトリ内で `#58` / `issue58` / `issue #58` の記述有無を調査。 +- `gh` 以外の経路として、GitHub Issue URL を直接参照して本文を取得。 + +## 実行コマンド / 手段 +1. `rg -n "issue ?#?58|#58|issue58" -S .` +2. Browserツールで `https://github.com/ssaattww/ExcelReport/issues/58` を開いて本文を確認 + +## 取得できた issue 本文の要点 +- タイトル: **Excel形式のテンプレート対応** +- 想定フロー: `Excelテンプレート -> (xml template) -> DSL -> ... -> Excel book` +- 意図: + - xml template はデバッグ目的で利用 + - 本番では DSL へ直接変換できるのが望ましい +- コンポーネント定義案: + - シート単位定義(特殊シート名) + - 名前付き範囲定義(シート内) +- 進め方: + - dotnet 8 インストール + - 仕様策定後にレポート出力 + - ユーザー承認 + - TDD + +## 判断 +- issue #58 の要件は取得済み。 +- 上記要件を反映して `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` を承認依頼版へ更新した。 + +## 次アクション +- ユーザー承認後、TDDで実装に着手する。 + +- ユーザー追加指示に基づき、設計書へ「入れ子コンポーネント定義」「シート表現」「コンポーネント挿入表現」の具体例(DSLサンプル)を追記した。 + +## 追加検討(ユーザーコメント反映) +- A/B案を鵜呑みにせず、C案(セルコメント/メタ情報ベース)を追加して比較した。 +- 比較結果として、初期リリースは A案(シート単位定義)が最も安定導入しやすいと判断。 +- また、今回の対象範囲外へ **グラフ作成機能** を明示追加した。 + +- ユーザー懸念(入れ子component時の罫線崩れ)に対応し、設計書へ罫線優先順位・辺単位合成・競合Warning・検証ケースを追加した。 + +- ユーザー要望に合わせ、設計書へセル値/挿入トリガ/罫線競合の具体例を Markdown テーブルで追加した。 + +- 実装前リスクを深掘りし、変換契約/展開境界/罫線実装/性能運用の観点で事前合意チェックリストを設計書へ追加した。 + +- 「テーブルの各セルをExcelセルと一致」要望に対応し、A-D列×行番号のセルマトリクス表とSVG図(A1〜D4対応)を設計書へ追加した。 diff --git a/reports/issue58-invoice-use-style-optional-note-2026-04-12.md b/reports/issue58-invoice-use-style-optional-note-2026-04-12.md new file mode 100644 index 0000000..1177564 --- /dev/null +++ b/reports/issue58-invoice-use-style-optional-note-2026-04-12.md @@ -0,0 +1,15 @@ +# issue #58 設計補足メモ(Invoice `use` 書式任意) + +## 背景 +ユーザー指摘: `Invoice` シートの `use` 部分が書式設定されているように見え、挿入先書式が must と誤解される懸念がある。 + +## 対応 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` の 10.8.3(挿入先セル値SVG)に注記を追加。 +- 追加注記: + - `use` 周辺罫線は「テンプレートで定義されている場合の例」であり必須ではない。 + - 挿入先書式が未定義でも `use` 展開は有効で、最終書式は 10.9/11章ルールで決定する。 + +## 既存設計との整合 +- 10.9 で「挿入先書式は任意(mustではない)」を明記済み。 +- 10.9.1 で「3x3外枠 + 中央`use`」の外枠追従拡張(行/列両方向)を定義済み。 +- overflow 記録は `TemplateRangeOverflow` + `deltaRows`/`deltaCols` を採用済み。 diff --git a/reports/issue58-low-findings-followup-2026-04-12.md b/reports/issue58-low-findings-followup-2026-04-12.md new file mode 100644 index 0000000..f233bbc --- /dev/null +++ b/reports/issue58-low-findings-followup-2026-04-12.md @@ -0,0 +1,14 @@ +# issue #58 再レビュー Low 指摘対応メモ + +## 対応対象 +- `styleOverflow=edge` の4方向検証不足 +- 10.9.4 の期待結果テーブルが右方向専用に見える点 + +## 対応 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + - 10.9.4 を 右 / 左 / 下 / 上 / 角 の 5方向が読める表へ拡張 + - 11.5 に left / top / corner copy の検証ケースを追加 + +## 結果 +- `styleOverflow=edge` の仕様定義と期待結果表の対応が明確になった。 +- 検証観点も 4方向 + 角領域までカバーする形になった。 diff --git a/reports/issue58-output-contract-2026-04-13.md b/reports/issue58-output-contract-2026-04-13.md new file mode 100644 index 0000000..afa2b9a --- /dev/null +++ b/reports/issue58-output-contract-2026-04-13.md @@ -0,0 +1,39 @@ +# issue #58 Output Contract Builder + +Date: 2026-04-13 + +## Summary +- 対象 task: `R58-01 変換出力の最小契約を固定する` +- 目的: `XmlTemplateSerializer` / `DslEmitter` の前段で使う共通の出力契約を、component/sheet 分類・cell/use/repeat-use 正規化・issue 集約の形で固定する + +## TDD +1. Red + - `ExcelTemplateOutputContractBuilderTests` を追加し、未実装状態で compile error (`ExcelTemplateOutputContractBuilder` など未定義) を確認した +2. Green + - `ExcelTemplateOutputContractBuilder` と `ExcelTemplateOutputContract` 系モデルを追加 + - resolver / validator / use trigger parser を束ねて contract を組み立てる最小実装を追加 +3. Verify + - `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter ExcelTemplateOutputContractBuilderTests` + - Passed 2 + - `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter "ExcelTemplate"` + - Passed 19 + +## Implemented Contract +- component sheet は `__component_` 接頭辞で判定し、resolved range を持つものだけ contract の `Components` へ入れる +- 通常 sheet は `Sheets` へ入れる +- cell は row/column 順で並べる +- `{{use:...}}` は `ExcelTemplateOutputUse` または `ExcelTemplateOutputRepeatUse` に正規化する +- 数式セルは `ExcelTemplateOutputCell.Formula` へ保持する +- component range resolver と validator の `Issues` を contract へ集約する +- range 解決に失敗した component sheet も contract へ残し、未解決文脈を downstream へ渡す +- テスト fixture は `ExcelTemplateOutputContractFixture` にまとめ、後続 snapshot テストで再利用できる形にした + +## Files +- `ExcelReport/ExcelReportLib/ExcelTemplate/ExcelTemplateOutputContractBuilder.cs` +- `ExcelReport/ExcelReportLib/ExcelTemplate/Model/ExcelTemplateOutputContract.cs` +- `ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractBuilderTests.cs` +- `ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractFixture.cs` + +## Residual Risk +- 現時点では Excel 側から `styleOverflow` を入力する新しい source syntax は未導入のため、contract 上の `use` / `repeat-use` は `StyleOverflow = null` で「未指定」を保持している +- `R58-02` / `R58-03` ではこの contract をそのまま serializer / emitter に接続し、snapshot で出力表現を固定する必要がある diff --git a/reports/issue58-output-contract-review-2026-04-13.md b/reports/issue58-output-contract-review-2026-04-13.md new file mode 100644 index 0000000..6cbc7a6 --- /dev/null +++ b/reports/issue58-output-contract-review-2026-04-13.md @@ -0,0 +1,20 @@ +# issue #58 Output Contract Review + +Date: 2026-04-13 +Reviewer: sub-agent `gpt-5.4` / `high` + +## Review Rounds +1. 初回 review + - Medium: `styleOverflow` を常に `"none"` へ正規化しており、未指定と明示指定を区別できない + - Medium: range 解決失敗 component が contract から脱落し、downstream で文脈を失う + - Low: style-only cell と malformed trigger preserve のテスト不足 +2. 対応 + - `StyleOverflow` を nullable にし、未指定は `null` で保持 + - 未解決 component も `IsRangeResolved = false` / `RangeReference = null` で contract に残す + - style-only cell と malformed trigger preserve のテストを追加 +3. 再 review + - Findings: なし + +## Residual Risks +- unresolved component を `XmlTemplateSerializer` / `DslEmitter` でどう表現するかは次タスクで明示する必要がある +- contract は sparse item ベースなので、snapshot タスクでは空座標再構成と順序を明示固定する必要がある diff --git a/reports/issue58-output-svg-refresh-2026-04-12.md b/reports/issue58-output-svg-refresh-2026-04-12.md new file mode 100644 index 0000000..df530e3 --- /dev/null +++ b/reports/issue58-output-svg-refresh-2026-04-12.md @@ -0,0 +1,15 @@ +# issue #58 10.8.9 出力SVG更新メモ + +## 指摘 +- 10.8.9 の図が古いままで、最新の状態整理(A1:F1 / A3:E8)を反映していない。 + +## 対応 +- `Design/ExcelTemplate/assets/expanded-cell-values-from-csharp.svg` を差し替え。 + - Header外枠: `A1:F1` + - 子枠外枠: `A3:E8` + - 子値配置: `B4:D7`(`@group.Name` + ItemRow) +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` の 10.8.9/10.10 補足を更新。 + - 図は状態整理ケース優先で「先頭GroupBlock抜粋」であることを明記。 + +## 結果 +- 10.8.10 の状態整理テーブルと 10.8.9 図の整合が取れた。 diff --git a/reports/issue58-performance-threshold-closed-2026-04-12.md b/reports/issue58-performance-threshold-closed-2026-04-12.md new file mode 100644 index 0000000..3cbd845 --- /dev/null +++ b/reports/issue58-performance-threshold-closed-2026-04-12.md @@ -0,0 +1,12 @@ +# issue #58 性能閾値確認のクローズ + +## 回答 +- 大規模テンプレートの性能閾値は当面不問。 + +## 反映 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + - 12.4 の性能方針を「当面は性能閾値を設けず不問」として更新 + - 12.6 の未解決質問をクローズし、「現時点で未解決なし」とした + +## 結果 +- 12章の実装前レビュー確認事項はすべて合意済みとなった。 diff --git a/reports/issue58-pre-implementation-answers-2026-04-12.md b/reports/issue58-pre-implementation-answers-2026-04-12.md new file mode 100644 index 0000000..dc13b93 --- /dev/null +++ b/reports/issue58-pre-implementation-answers-2026-04-12.md @@ -0,0 +1,15 @@ +# issue #58 実装前レビュー回答の反映 + +## 回答 +- merged cell の初版制約(矩形内完結のみ): 良い +- 条件付き書式は初版対象外: 良い +- 数式セルは原則 `cell@formula`: 良い +- 大規模テンプレートの性能閾値: とりあえず不問 + +## 反映 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + - merged cell 制約を合意済み方針として固定 + - 条件付き書式を初版対象外で固定 + - 数式正規化は既存の `cell@formula` 原則を維持 + - 性能閾値は当面固定せず、Phase A の実測後に別途定める方針へ更新 + - 12.6 の確認質問は性能閾値の1点のみに整理 diff --git a/reports/issue58-repeat-frame-aggregation-2026-04-12.md b/reports/issue58-repeat-frame-aggregation-2026-04-12.md new file mode 100644 index 0000000..54eee07 --- /dev/null +++ b/reports/issue58-repeat-frame-aggregation-2026-04-12.md @@ -0,0 +1,22 @@ +# issue #58 repeat 展開時の親フレーム再解釈メモ + +## 指摘 +- 10.8.9 の図では、1件目 `GroupBlock` を `B4:D7` に挿入するなら、2件目は `B8:D9` に続けて配置されるはず。 +- 親フレームも分割せず、`A3:E10` でまとめて囲う方が自然。 + +## 判断 +- この指摘は妥当。 +- `A3:C5` の 3x3 親フレームは、中央 `B4` の `use:GroupBlock` が返す repeat 全体に対する外枠として扱う。 +- したがって、親フレームはインスタンスごとに複製せず、repeat 展開結果の総高さに追従して一度だけ拡張する。 + +## 対応 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + - 10.8.9 を `A3:E10` 前提の説明へ修正 + - 10.8.10 を「repeat 全体の親フレーム」と「各インスタンス位置」の表へ修正 +- `Design/ExcelTemplate/assets/expanded-cell-values-from-csharp.svg` + - 1件目: `B4:D7` + - 2件目: `B8:D9` + - 親フレーム: `A3:E10` + +## 結果 +- 10.8.9 の図と 10.8.10 の状態整理が、repeat の連続展開前提で整合した。 diff --git a/reports/issue58-section-layout-and-target-svg-fix-2026-04-12.md b/reports/issue58-section-layout-and-target-svg-fix-2026-04-12.md new file mode 100644 index 0000000..c47c957 --- /dev/null +++ b/reports/issue58-section-layout-and-target-svg-fix-2026-04-12.md @@ -0,0 +1,28 @@ +# issue #58 図配置/10.8.3 修正メモ + +## 背景 +ユーザー指摘: +- 10.8.3/10.8.4 と 10.10.1/10.10.2 が離れており見づらい。 +- 10.8.3 の 1行目と2行目の間に破線が入っており、出力結果との整合が悪い。 +- 10.8.3 にヘッダーがない。 + +## 対応 +1. 章配置の整理 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + - 10.8.8: C#データ展開後の挿入元(GroupBlockインスタンス)図を追加。 + - 10.8.9: C#データ展開後のInvoice出力図を追加。 + - 10.10.1 は「図の参照位置」説明へ変更し、10.8.8/10.8.9 を参照する構成へ変更。 + +2. 10.8.3 図の修正 +- `Design/ExcelTemplate/assets/insert-target-cell-values.svg` + - 破線(1行目と2行目境界として誤認される表現)を削除。 + - `A1` に `{{use:Header}}` を追加。 + - 中央 `{{use:GroupBlock, from:@groups, var:group}}` は維持。 + +3. 表の整合 +- 10.8.1: `A1` に `{{use:Header}}` を追加。 +- 10.8.5: `A1` のヘッダー挿入トリガ説明を追加。 + +## 結果 +- 参照図が 10.8 節に集約され、入力図/展開後図を連続で確認可能。 +- 10.8.3 の不要破線を除去し、ヘッダー挿入トリガを明示。 diff --git a/reports/issue58-size-mismatch-design-review-2026-04-12.md b/reports/issue58-size-mismatch-design-review-2026-04-12.md new file mode 100644 index 0000000..5804339 --- /dev/null +++ b/reports/issue58-size-mismatch-design-review-2026-04-12.md @@ -0,0 +1,44 @@ +# issue #58 設計レビュー: 挿入サイズ不一致と設計書命名修正 (2026-04-12) + +## 背景 +- ユーザー懸念: 挿入元コンポーネント行数が挿入先の想定定義範囲より大きい場合に、書式崩れが起きる可能性がある。 +- 追加要望: `Issue58` だけでは設計書の目的が分かりづらいため、設計書名を明確化する。 + +## 確認結果(修正前) +- 既存設計には `use` 展開時の行シフト方針はあったが、 + - 挿入先想定範囲を超過した行の扱い + - overflow発生時のWarning仕様 + - 境界をまたぐ結合セルの停止条件 + が明示されておらず、サイズ不一致時の書式保全要件として不十分だった。 + +## 実施した修正 +1. 設計書タイトルを明確化 +- `Issue #58 詳細設計(承認依頼版)` +- -> `Excelテンプレート対応 詳細設計(Issue #58 / 承認依頼版)` + +2. 設計対象を明記 +- ドキュメント冒頭に `Excel -> XML Template -> DSL` を対象とする旨を追加。 + +3. サイズ不一致ケースの仕様を追加 +- `10.9 サイズ不一致時の挿入ルール(挿入元 > 挿入先想定範囲)` を新設。 +- 追加内容: + - 挿入先定義範囲はクリップ境界ではなくアンカー扱い + - 挿入元実高さまで展開(切り詰め禁止) + - overflow行は挿入元書式ルールを適用 + - 後続行は既存値/書式/結合状態を保って相対シフト + - `TemplateRangeOverflow` Warning を座標付きで記録 + - 結合セル境界破壊は Error 停止 + +4. テスト観点と合意表の補強 +- 11.5 に overflow時の書式保持/Warning検証ケースを追加。 +- 12.2 に「挿入元高さ > 挿入先想定行数」の合意項目を追加。 + +5. ファイル名と配置先を更新 +- `Design/Issue58/Issue58_DetailDesign.md` +- -> `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + +## 関連更新 +- `tasks/tasks-status.md` を 2026-04-12 更新。 +- `tasks/phases-status.md` を 2026-04-12 更新。 +- `tasks/feedback-points.md` に FP118 を追加(対応済み)。 +- 既存レポート `reports/issue58-investigation-2026-04-07.md` 内の参照パスを新ファイル名へ更新。 diff --git a/reports/issue58-snapshots-2026-04-13.md b/reports/issue58-snapshots-2026-04-13.md new file mode 100644 index 0000000..01b4590 --- /dev/null +++ b/reports/issue58-snapshots-2026-04-13.md @@ -0,0 +1,35 @@ +# issue #58 Snapshot Tests + +Date: 2026-04-13 + +## Summary +- 対象 task: + - `R58-05 xlsx -> xml snapshot テストを追加する` + - `R58-06 xlsx -> dsl snapshot テストを追加する` +- 目的: `XmlTemplateSerializer` / `DslEmitter` の shape を外部 fixture で固定し、後続 API 実装で text/structure が揺れないようにする + +## Implemented +- `ExcelTemplateSnapshotTests` を追加 +- serializer snapshot: + - `ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Debug.xml` + - `XmlTemplateSerializer.Serialize(contract).ToString()` と比較 +- DSL snapshot: + - `ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Dsl.xml` + - `DslEmitter.Emit(contract)` と比較 +- 比較時は line ending を正規化して cross-platform で安定化 + +## Verification +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter ExcelTemplateSnapshotTests` + - Passed 2 +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter "ExcelTemplate|XmlTemplateSerializerTests|DslEmitterTests|ExcelTemplateSnapshotTests"` + - Passed 28 +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj` + - Passed 244 + +## Files +- `ExcelReport/ExcelReportLib.Tests/ExcelTemplateSnapshotTests.cs` +- `ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Debug.xml` +- `ExcelReport/ExcelReportLib.Tests/TestDsl/Issue58_StandardTemplate_Dsl.xml` + +## Residual Risk +- snapshot review が終わるまでは、fixture 粒度や deterministic policy の見落としが残る可能性がある diff --git a/reports/issue58-snapshots-review-2026-04-13.md b/reports/issue58-snapshots-review-2026-04-13.md new file mode 100644 index 0000000..fb2bfef --- /dev/null +++ b/reports/issue58-snapshots-review-2026-04-13.md @@ -0,0 +1,11 @@ +# issue #58 Snapshot Tests Review + +Date: 2026-04-13 +Reviewer: sub-agent `gpt-5.4` / `high` + +## Review Result +- Findings: なし + +## Residual Risks +- external snapshot は happy-path 固定が中心で、unresolved-component / issue-comment の外部 snapshot はまだ未追加 +- serializer / emitter の formatting 変更は fixture 更新を伴うため、今後は意図的変更として扱う必要がある diff --git a/reports/issue58-state-table-only-adjustment-2026-04-12.md b/reports/issue58-state-table-only-adjustment-2026-04-12.md new file mode 100644 index 0000000..02bce41 --- /dev/null +++ b/reports/issue58-state-table-only-adjustment-2026-04-12.md @@ -0,0 +1,11 @@ +# issue #58 状態整理の記載方式調整 + +## 指摘 +- 「理解できたなら状態遷移図は不要」 + +## 対応 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` の 10.8.10 から図参照を削除。 +- 10.8.10 は状態整理テーブルのみで、入力/出力条件と結果を記載する構成へ統一。 + +## 意図 +- 図の追加よりも、セル範囲・拡張結果・条件分岐(`W=3` / `W=2`)を表で明確化することを優先。 diff --git a/reports/issue58-style-overflow-policy-2026-04-12.md b/reports/issue58-style-overflow-policy-2026-04-12.md new file mode 100644 index 0000000..7092154 --- /dev/null +++ b/reports/issue58-style-overflow-policy-2026-04-12.md @@ -0,0 +1,38 @@ +# issue #58 設計更新メモ(3x3 SVG化 + styleOverflow方針) + +## 背景 +ユーザー指摘: +- SVG例を 3x3 挿入先 + 中央 use の具体例にしてほしい。 +- 挿入先書式を拡張したい場合/したくない場合の双方を扱いたい。 +- `A1:C1` と `A1:B1` のように書式シードが異なる場合の拡張挙動を明確化したい。 + +## 対応内容 +1. SVG更新 +- `Design/ExcelTemplate/assets/insert-target-cell-values.svg` + - 3x3 挿入先、中央 `{{use:GroupBlock}}` の例へ変更。 +- `Design/ExcelTemplate/assets/insert-source-cell-values.svg` + - 3x4 GroupBlock(`@group.Name` / `{{use:ItemRow,...}}`)へ変更。 +- `Design/ExcelTemplate/assets/style-overflow-modes-3x3.svg` + - Case1 `styleOverflow=none` + `A1:C1` + - Case2 `styleOverflow=edge` + `A1:C1` + - Case3 `styleOverflow=edge` + `A1:B1` + +2. 設計追記(`Design/ExcelTemplate/ExcelTemplate_DetailDesign.md`) +- 10.8.1 / 10.8.2 を 3x3 / 3x4 例へ更新。 +- 10.8.6 / 10.8.7 を追加し、SVG比較とMarkdown表で期待結果を固定。 +- 10.9.2 を追加し `styleOverflow="none|edge"`(既定 `none`)を定義。 +- `edge` の右方向拡張規則: + - 右辺基準列 `baseCol=originalColEnd` に書式がある行のみコピー。 + - `baseCol` 未設定行はコピーしない。 +- 具体ケース: + - `A1:C1` + `edge` => `D1` 拡張あり + - `A1:C1` + `none` => `D1` 拡張なし + - `A1:B1` + `edge` => `C1` 未設定のため `D1` 拡張なし + +3. 検証観点更新 +- 11.5 に `styleOverflow` の3ケースを追加。 +- 11.7 / 12.3 を `styleOverflow` 前提へ更新。 + +## 補足 +- 既定動作は後方互換のため `styleOverflow=none`。 +- 拡張が必要な箇所のみ `styleOverflow=edge` を指定する運用を想定。 diff --git a/reports/issue58-subagent-design-review-2026-04-12.md b/reports/issue58-subagent-design-review-2026-04-12.md new file mode 100644 index 0000000..b5bca82 --- /dev/null +++ b/reports/issue58-subagent-design-review-2026-04-12.md @@ -0,0 +1,79 @@ +# issue #58 sub-agent 設計レビュー結果 + +## 実施条件 +- reviewer: `gpt-5.3-codex` +- reasoning: `high` +- 対象: `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` の 10.8 / 10.9 / 10.10 と関連SVG +- 観点: + - `repeat + use` の展開規則 + - 親フレーム拡張 / `styleOverflow` / component定義範囲の関係 + - 行方向 / 列方向ケースの詰め + - 図 / 表 / 本文の整合 + +## Findings + +### 1. High: `repeat + use` 時の `H` 定義が未確定 +- 該当: + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:353` + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:390` + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:393` +- 内容: + - 10.8.9 では親フレームを `A3:E10` と明示しているが、10.9.1 の拡張式は単一の `H x W` を前提にしている。 + - `repeat` の場合に `H` を「1インスタンス高」とみなすのか、「repeat 全体の連結総高」とみなすのかが未定義。 + - このままだと `A3:E8` と `A3:E10` の両方が解釈上成立する。 +- 影響: + - 親フレーム拡張の実装が実装者依存になる。 + +### 2. High: `GroupBlock` の有効幅定義が 3列 / 4列で不一致 +- 該当: + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:265` + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:293` + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:364` + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:448` + - `Design/ExcelTemplate/assets/insert-source-cell-values.svg:13` + - `Design/ExcelTemplate/assets/insert-source-cell-values.svg:55` + - `Design/ExcelTemplate/assets/expanded-insert-source-from-csharp.svg:29` + - `Design/ExcelTemplate/assets/expanded-insert-source-from-csharp.svg:43` +- 内容: + - 本文は `3x4` / `A1:D3` / `A1:D4` を使う一方、状態整理では `W=3` を前提に `A:E` 拡張を説明している。 + - SVG も `A:D` を示す入力図と、実質 `A:C` 外周で描かれた展開後図が混在している。 +- 影響: + - 列方向拡張、親フレーム幅、`styleOverflow` 評価基準が不安定になる。 + +### 3. Medium: `styleOverflow=edge` が右方向列拡張しか定義されていない +- 該当: + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:371` + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:398` + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:417` +- 内容: + - 10.9 の宣言は行 / 列の両方向対応だが、具体アルゴリズムは `deltaCols > 0` の右方向だけ。 + - `deltaRows > 0`、上方向、左方向への拡張規則がない。 +- 影響: + - 行方向 overflow や逆方向拡張で実装差異が出る。 + +### 4. Medium: 連続インスタンス境界の罫線競合解決順が未固定 +- 該当: + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:362` + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:363` + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:486` +- 内容: + - `B7:D7` と `B8:D9` のような連続配置では、前インスタンスの `bottom` と次インスタンスの `top` が同一境界で衝突しうる。 + - 11章では辺単位解決までは書かれているが、同優先度同士の決着規則がない。 +- 影響: + - 連続展開時の境界線が renderer 実装に依存する。 + +### 5. Low: 10.8.8 SVG の注記が現行章構成とずれている +- 該当: + - `Design/ExcelTemplate/assets/expanded-insert-source-from-csharp.svg:14` +- 内容: + - 図内説明が「10.10 サンプルデータから生成」となっているが、現在のサンプル提示位置は 10.8 内。 +- 影響: + - 読み手が参照位置を誤認しやすい。 + +## 総評 +- 現時点で、実装に入る前に固定すべき論点が残っている。 +- 優先度は次の順序が妥当: + 1. `repeat` に対する `H` / `W` の定義を固定 + 2. `GroupBlock` の有効幅を 3列か4列かで統一 + 3. `styleOverflow=edge` の行方向 / 左右上下方向ルールを補完 + 4. 連続インスタンス境界の罫線競合順を固定 diff --git a/reports/issue58-subagent-rereview-2026-04-12.md b/reports/issue58-subagent-rereview-2026-04-12.md new file mode 100644 index 0000000..d3eb5fb --- /dev/null +++ b/reports/issue58-subagent-rereview-2026-04-12.md @@ -0,0 +1,44 @@ +# issue #58 sub-agent 再レビュー結果 + +## 実施条件 +- reviewer: `gpt-5.3-codex` +- reasoning: `high` +- 対象: + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + - `insert-source-cell-values.svg` + - `expanded-insert-source-from-csharp.svg` + - `expanded-cell-values-from-csharp.svg` + - `style-overflow-modes-3x3.svg` + +## 結論 +- High / Critical の指摘はなし。 +- 前回の主要5指摘は解消済み。 +- 残留は Low 2件。 + +## Low Findings + +### 1. `styleOverflow=edge` の4方向検証が不足 +- 該当: + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:421` + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:515` +- 内容: + - 4方向と角領域のルール自体は定義済み。 + - ただし検証ケースは右方向 / 下方向寄りで、左方向 / 上方向 / 角コピーを明示的に確認していない。 +- 残留リスク: + - 実装時に left / top / corner の扱いで差異が出る可能性がある。 + +### 2. 期待結果テーブルが右方向専用に見える +- 該当: + - `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md:440` +- 内容: + - 10.9.4 の表は `D1` への拡張結果のみを示している。 + - 本文で4方向ルールを定義したのに対し、表現が右方向ケースに偏っている。 +- 残留リスク: + - 読み手が「4方向対応」と「表の例」が結び付けにくい。 + +## 前回5指摘の解消確認 +1. `repeat + use` 時の `H/W` 定義: 解消 +2. `GroupBlock` 有効幅不一致: 解消 +3. `styleOverflow=edge` の行方向未定義: 解消 +4. 連続 instance 境界の罫線競合未定義: 解消 +5. 10.8.8 図注記ズレ: 解消 diff --git a/reports/issue58-svg-and-range-design-update-2026-04-12.md b/reports/issue58-svg-and-range-design-update-2026-04-12.md new file mode 100644 index 0000000..4d274aa --- /dev/null +++ b/reports/issue58-svg-and-range-design-update-2026-04-12.md @@ -0,0 +1,34 @@ +# issue #58 設計更新レポート: SVG分離 / C#データ定義 / 範囲定義 (2026-04-12) + +## 要求 +- セル表示値をSVG表で示す。 +- SVGは「挿入元」「挿入先」を分ける。 +- 書式説明はSVGではなくMarkdownテーブルで管理する。 +- 挿入対象となるC# classデータを別途定義する。 +- コンポーネント定義範囲の定義方法を設計へ追加する。 + +## 実施内容 +1. 設計書更新 +- 対象: `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` +- 追加/更新: + - 5.1 コンポーネント定義範囲(DefinedName明示 + 自動判定) + - 6 失敗時ポリシーへ範囲/挿入エラー種別を追加 + - 9 承認ポイントを6項目へ拡張 + - 10.8 SVGを挿入先/挿入元の2枚へ分離 + - 10.8.5 で書式説明をMarkdownテーブル化 + - 10.10 挿入データ用C# class定義とサンプル入力を追加 + - 10.11 範囲定義の具体例とバリデーション表を追加 + +2. SVG追加 +- `Design/ExcelTemplate/assets/insert-target-cell-values.svg` +- `Design/ExcelTemplate/assets/insert-source-cell-values.svg` + +3. 追跡ファイル更新 +- `tasks/tasks-status.md` +- `tasks/phases-status.md` +- `tasks/feedback-points.md`(FP119追加) + +## 設計判断 +- コンポーネント範囲は、運用で明示指定したいケースと簡易運用の両立のため二段構成(DefinedName優先 + 自動判定)を採用。 +- SVGは表示値の確認に限定し、書式競合ルールはMarkdownへ集約してテキスト差分レビューしやすくした。 +- C# classサンプルは `repeat + use` の入力像を固定し、仕様レビュー時の認識差分を減らすことを狙う。 diff --git a/reports/issue58-svg-format-restoration-2026-04-12.md b/reports/issue58-svg-format-restoration-2026-04-12.md new file mode 100644 index 0000000..f59f853 --- /dev/null +++ b/reports/issue58-svg-format-restoration-2026-04-12.md @@ -0,0 +1,30 @@ +# issue #58 SVGフォーマット復元メモ(10.10.1 挿入元復活) + +## 背景 +ユーザー指摘: +- 10.10.1 の挿入元が消えている。 +- 新規SVGが例示文言(ヘッダー/なにかの値)に寄りすぎており、以前の正式フォーマットから外れている。 + +## 対応 +1. 10.10.1 の復元 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` + - 10.10.1 を「C#データ展開後の挿入元(GroupBlockインスタンス)SVG」として追加。 + - 既存の出力図を 10.10.2 へ再配置。 + +2. 新規SVGの正式フォーマット化 +- `Design/ExcelTemplate/assets/insert-target-cell-values.svg` + - 3x3 中央 `{{use:GroupBlock, from:@groups, var:group}}` へ修正。 +- `Design/ExcelTemplate/assets/insert-source-cell-values.svg` + - `__component_GroupBlock`(`@group.Name` / `{{use:ItemRow,...}}`)へ修正。 +- `Design/ExcelTemplate/assets/style-overflow-modes-3x3.svg` + - セル値を `@group.Name` / `{{use:ItemRow,...}}` へ修正。 +- `Design/ExcelTemplate/assets/expanded-insert-source-from-csharp.svg` + - C#展開後の GroupBlock 挿入元インスタンス図を新規追加。 + +3. 設計表の整合 +- 10.8.1/10.8.2/10.8.5 を `GroupBlock/ItemRow` 前提へ差し替え。 +- 10.9.2 の `styleOverflow` サンプル `use` も `GroupBlock` に統一。 + +## 結果 +- 「3x3例」は維持しつつ、文言とコンポーネント構造は正式設計(GroupBlock/ItemRow/Invoice)へ復元。 +- 10.10.1 に挿入元図が復活し、挿入元/挿入先の両方を追える状態になった。 diff --git a/reports/issue58-svg-realistic-appearance-update-2026-04-12.md b/reports/issue58-svg-realistic-appearance-update-2026-04-12.md new file mode 100644 index 0000000..265a336 --- /dev/null +++ b/reports/issue58-svg-realistic-appearance-update-2026-04-12.md @@ -0,0 +1,32 @@ +# issue #58 追補: SVGを実運用見た目へ調整 (2026-04-12) + +## 背景 +- ユーザー指摘: SVGの強調色(アンカー/範囲強調)が、実際のExcelTemplate運用や出力Excelの見た目と乖離している。 + +## 対応方針 +- 説明用のセル背景強調を廃止。 +- SVGは「実際のExcelに近い見た目」を優先し、意味づけは本文/表で説明する。 + +## 実施内容 +1. 入力側SVGの修正 +- `Design/ExcelTemplate/assets/insert-target-cell-values.svg` +- `Design/ExcelTemplate/assets/insert-source-cell-values.svg` +- 変更: + - アンカー/有効範囲の背景色強調を削除 + - Excelライクなヘッダー色 + 通常セル罫線へ統一 + +2. 展開後SVGの修正 +- `Design/ExcelTemplate/assets/expanded-cell-values-from-csharp.svg` +- 変更: + - 凡例・色分け中心の表現を廃止 + - 最終出力寄りの見た目へ統一 + - 罫線は実線/破線のみで結果を表現(競合結果も最終見た目として破線で表現) + +3. 設計書の追記 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` +- 追記箇所: + - 10.8: 「説明用背景色強調を行わない」注記 + - 10.10.1: 線種説明を色ベースから実線/破線ベースへ修正 + +## 効果 +- 図と実運用イメージの差を縮小し、レビュー時の誤解(図示都合の色=本番書式)を防止。 diff --git a/reports/issue58-svg-source-target-border-alignment-2026-04-12.md b/reports/issue58-svg-source-target-border-alignment-2026-04-12.md new file mode 100644 index 0000000..386a7e2 --- /dev/null +++ b/reports/issue58-svg-source-target-border-alignment-2026-04-12.md @@ -0,0 +1,25 @@ +# issue #58 追補: 挿入元/挿入先SVGの罫線整合修正 (2026-04-12) + +## 背景 +- ユーザー指摘: 挿入元/挿入先SVGは書式設定がない見た目だが、展開後SVGでは罫線が設定されており、図同士で不整合に見える。 + +## 対応 +1. 挿入先SVG修正 +- `Design/ExcelTemplate/assets/insert-target-cell-values.svg` +- 追加: + - Header挿入行(A1:D1)の実線外枠 + - GroupBlock挿入領域(A3:C4)の実線/破線境界 + +2. 挿入元SVG修正 +- `Design/ExcelTemplate/assets/insert-source-cell-values.svg` +- 追加: + - GroupBlock定義領域(A1:C2)の実線外枠 + - 明細境界の破線 + +3. 設計書追記 +- `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` +- 10.8 注記に「入力側SVGにもテンプレート定義罫線を反映する」旨を追加。 + +## 効果 +- 入力テンプレート図と出力結果図で、罫線の有無・線種が一貫して読み取れる。 +- 「入力側は無書式、出力側だけ有書式」に見える誤解を解消。 diff --git a/reports/issue58-use-trigger-parser-2026-04-13.md b/reports/issue58-use-trigger-parser-2026-04-13.md new file mode 100644 index 0000000..00d3089 --- /dev/null +++ b/reports/issue58-use-trigger-parser-2026-04-13.md @@ -0,0 +1,53 @@ +# issue #58 UseTriggerParser 実装記録 + +- 作成日: 2026-04-13 +- 対象: issue #58 ExcelTemplate 対応の実装第4段 +- ブランチ: `codex/create-design-document-for-approval` + +## 1. 実施内容 + +ExcelTemplate の `{{use:...}}` セル値トリガを構造化する `UseTriggerParser` を追加した。 + +今回反映した内容: + +- `UseTriggerParser` を追加 +- trigger モデルを追加 + - `ExcelTemplateUseTrigger` + - `ExcelTemplateUseTriggerParseResult` +- 初期対応文法 + - `{{use:Header}}` + - `{{use:ItemRow, from:@items, var:item}}` +- repeat trigger の正規化 + - `from` と `var` が両方ある場合のみ repeat とみなす + - repeat は `direction="down"` を parser 結果で固定 +- 異常系 + - `from` だけ / `var` だけ + - 未対応 key + - 閉じ括弧欠落 + を `InvalidAttributeValue` Error として返す +- 非 trigger 文字列は通常セル値扱いのため `IsTrigger = false` / issue なしで返す + +## 2. テスト + +TDD: + +1. `ExcelTemplateUseTriggerParserTests` を先に追加して Red を確認 +2. 最小文法だけ実装して Green 化 + +実施: + +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter "FullyQualifiedName~ExcelTemplateUseTriggerParserTests"` +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj` + +結果: + +- parser 対象テスト: 5 passed +- 全体テスト: 228 passed, 0 failed + +## 3. 次の実装候補 + +次は `ExcelTemplateValidator` に進み、以下を Error/Warning として固定する。 + +1. merged cell が component range 境界を跨ぐケース +2. malformed defined name / unsupported trigger の診断集約 +3. 初版対象外機能の Warning/Error 化 diff --git a/reports/issue58-use-trigger-parser-review-2026-04-13.md b/reports/issue58-use-trigger-parser-review-2026-04-13.md new file mode 100644 index 0000000..c1583a7 --- /dev/null +++ b/reports/issue58-use-trigger-parser-review-2026-04-13.md @@ -0,0 +1,30 @@ +# issue #58 UseTriggerParser review 記録 + +- 作成日: 2026-04-13 +- 対象: `UseTriggerParser` 実装差分 +- 要求レビュー条件: sub-agent `gpt-5.4` / `high` + +## 1. review 実施状況 + +1. `gpt-5.4` / `high` review を `codex review --uncommitted` で試行 + - 実行コマンド: + - `codex review --uncommitted -c model="gpt-5.4" -c reasoning_effort="high" -c approval_policy="never" -c sandbox_mode="workspace-write"` +2. 結果 + - このセッションの network 制限により websocket / responses API 接続が `Operation not permitted` で失敗 + - review stream は `Review was interrupted. Please re-run /review and wait for it to complete.` で終了 + +## 2. 代替確認 + +- 手元点検で確認した点 + - trigger 非該当文字列を誤って use と解釈しない + - simple use と repeat use の2文法 + - `from`/`var` の対チェック + - repeat direction の `down` 固定 +- unit test 5件で固定 +- 全体回帰 `228 passed` を確認 + +## 3. 結論 + +- 本セッションでは `gpt-5.4` / `high` の外部 review は完走不可 +- 手元確認では追加修正が必要な不整合は検出していない +- 残留リスクは、validator 実装時に malformed trigger の座標付き issue へどう昇格させるかを最終確定する点 diff --git a/reports/issue58-validator-and-trigger-hardening-2026-04-13.md b/reports/issue58-validator-and-trigger-hardening-2026-04-13.md new file mode 100644 index 0000000..4c3d17a --- /dev/null +++ b/reports/issue58-validator-and-trigger-hardening-2026-04-13.md @@ -0,0 +1,56 @@ +# issue #58 Validator / trigger hardening 実装記録 + +- 作成日: 2026-04-13 +- 対象: issue #58 ExcelTemplate 対応の実装第5段 +- ブランチ: `codex/create-design-document-for-approval` + +## 1. 実施内容 + +ExcelTemplate 変換層の前処理として、validator と trigger parser の補強を追加した。 + +今回反映した内容: + +- `ExcelTemplateValidator` を追加 + - component 範囲を跨ぐ merged range を `MergedCellBoundaryViolation` Error として検出 + - 初版対象外の conditional formatting を `UnsupportedExcelTemplateFeature` Error として検出 + - `UseTriggerParser` の構文エラーを sheet/cell 座標付き Error として集約 + - `{{use:...}}` が未定義 component を参照した場合は `UndefinedComponent` Error を返す +- `ExcelTemplateSheet` に `HasConditionalFormatting` を追加 +- `ExcelTemplateExtractor` が sheet 上の conditional formatting 有無を抽出するよう拡張 +- `UseTriggerParser` を補強 + - `from:` 式を単純なカンマ split で壊さないよう、top-level comma tokenizer へ変更 + - `@(root.Items.Select((x, i) => new { x, i }))` のようなカンマを含む式を正しく解析可能化 +- `IssueKind` に次を追加 + - `MergedCellBoundaryViolation` + - `UnsupportedExcelTemplateFeature` + +## 2. テスト + +追加/更新: + +- `ExcelTemplateValidatorTests` + - merged range 境界違反 + - malformed use trigger + - unsupported conditional formatting + - undefined component trigger +- `ExcelTemplateUseTriggerParserTests` + - `from:` 式内カンマを含む repeat trigger +- `ExcelTemplateExtractorTests` + - conditional formatting 検出 + +実施: + +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter "FullyQualifiedName~ExcelTemplateValidatorTests|FullyQualifiedName~ExcelTemplateExtractorTests"` +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter "FullyQualifiedName~ExcelTemplateExtractorTests|FullyQualifiedName~ExcelTemplateComponentRangeResolverTests|FullyQualifiedName~ExcelTemplateUseTriggerParserTests|FullyQualifiedName~ExcelTemplateValidatorTests|FullyQualifiedName~LayoutNodeTests|FullyQualifiedName~ValidateDslTests|FullyQualifiedName~DslParserTests|FullyQualifiedName~LayoutEngineTests"` +- `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj` + +結果: + +- validator + extractor: 6 passed +- 関連テスト: 89 passed +- 全体テスト: 233 passed, 0 failed + +## 3. 次の実装候補 + +次は `DslEmitter` / `XmlTemplateSerializer` に進み、resolver / trigger / validator の結果を debug XML と DSL text へ落とす段階に入る。 +その際は `repeat direction="down"` の emitted DSL 固定と、validator issue を conversion result へどう集約するかを先に決める。 diff --git a/reports/issue58-validator-review-2026-04-13.md b/reports/issue58-validator-review-2026-04-13.md new file mode 100644 index 0000000..49a4afe --- /dev/null +++ b/reports/issue58-validator-review-2026-04-13.md @@ -0,0 +1,27 @@ +# issue #58 Validator / trigger hardening review 記録 + +- 作成日: 2026-04-13 +- 対象: `ExcelTemplateValidator` / `UseTriggerParser` 補強差分 +- 要求レビュー条件: sub-agent `gpt-5.4` / `high` + +## 1. review 実施状況 + +1. sub-agent `gpt-5.4` / `high` へ review を依頼 + - このセッションでは複数回、review 依頼に対して findings ではなく実装完了報告が返り、純粋な review 出力としては採用不能だった +2. `codex review --uncommitted -c model="gpt-5.4" -c reasoning_effort="high" -c approval_policy="never" -c sandbox_mode="workspace-write"` を試行 + - 結果: network 制限により websocket / responses API 接続が `Operation not permitted` で失敗 + +## 2. 代替確認 + +- 差分の自己点検で `UseTriggerParser` の tokenization 欠陥を検出 + - `from:` 式中のカンマで単純 split が壊れ、valid trigger を invalid 扱いする +- 先行テスト `Parse_RepeatUse_WithCommaInFromExpression_ReturnsRepeatTrigger` を追加して Red を確認 +- top-level comma tokenizer へ差し替えて Green 化 +- validator の新規テスト 4件と extractor 追随テスト 1件を追加 +- 全体回帰 `233 passed` を確認 + +## 3. 結論 + +- 本セッションでは `gpt-5.4` / `high` の純粋な外部 review は取得不能 +- ただし local review で検出した実害ある欠陥 1 件は修正済み +- 現時点の残留リスクは、`DslEmitter` 実装時に validator issue と emitted DSL の対応関係を snapshot で固定していない点 diff --git a/reports/issue58-xml-template-serializer-2026-04-13.md b/reports/issue58-xml-template-serializer-2026-04-13.md new file mode 100644 index 0000000..3d465c5 --- /dev/null +++ b/reports/issue58-xml-template-serializer-2026-04-13.md @@ -0,0 +1,44 @@ +# issue #58 XmlTemplateSerializer + +Date: 2026-04-13 + +## Summary +- 対象 task: `R58-02 XmlTemplateSerializer の workbook/component/sheet 出力を実装する` +- 方針: user 指摘に合わせ、debug XML であっても DSL 互換を優先し、`DslParser` で parse 可能な `` を直接出力する + +## TDD +1. Red + - `XmlTemplateSerializerTests` を追加し、`XmlTemplateSerializer` 未実装の compile error を作った + - テストでは構造確認に加えて `DslParser.ParseFromText` まで行い、DSL 互換を先に固定した +2. Green + - `XmlTemplateSerializer` を追加 + - `component` は `` body に正規化し、resolved range がある場合のみ `rows/cols` を付与 + - `sheet` は直下に `cell` / `use` / `repeat` を配置 + - unresolved component や issue は schema を壊さないよう XML comment へ退避し、未解決 component 自体は DSL 本体から除外 +3. Verify + - `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter XmlTemplateSerializerTests` + - Passed 4 + - `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj --filter "ExcelTemplate|XmlTemplateSerializerTests"` + - Passed 24 + - `dotnet test ExcelReport/ExcelReportLib.Tests/ExcelReportLib.Tests.csproj` + - Passed 240 + +## Serialization Rules Fixed In This Step +- root: `` +- component: `...` +- component item placement: `grid` 配下の `cell` / `repeat` / `use` に `r` / `c` を付与 +- repeat-use: `` +- formula cell: `cell@formula` +- simple use: `use@component` +- unresolved component / conversion issues: XML comment として保持 +- schema compatibility: `DslParser` + embedded XSD validation を有効にした parse までテストで固定 +- serializer branch coverage: style-only empty cell と explicit `styleOverflow` 出力を追加テストで固定 + +## Files +- `ExcelReport/ExcelReportLib/ExcelTemplate/XmlTemplateSerializer.cs` +- `ExcelReport/ExcelReportLib.Tests/XmlTemplateSerializerTests.cs` +- `ExcelReport/ExcelReportLib.Tests/ExcelTemplateOutputContractFixture.cs` + +## Residual Risk +- style index はまだ DSL 表現へ落としていないため、debug XML 上では書式 source 情報を comment 以上には出していない +- 次の `R58-03` / `R58-04` では serializer と emitter の責務重複を避けつつ、text 出力の整形規則を固定する必要がある diff --git a/reports/issue58-xml-template-serializer-review-2026-04-13.md b/reports/issue58-xml-template-serializer-review-2026-04-13.md new file mode 100644 index 0000000..96f9c10 --- /dev/null +++ b/reports/issue58-xml-template-serializer-review-2026-04-13.md @@ -0,0 +1,20 @@ +# issue #58 XmlTemplateSerializer Review + +Date: 2026-04-13 +Reviewer: sub-agent `gpt-5.4` / `high` + +## Review Rounds +1. 初回 review + - Medium: DSL 互換確認が parser tolerant 止まりで、XSD validation まで固定できていない + - Medium: unresolved component を DSL 本体へ出すと、不正 range を過小評価しやすい + - Low: style-only empty cell と explicit `styleOverflow` の serializer 分岐テスト不足 +2. 対応 + - `DslParserOptions.EnableSchemaValidation = true` で parse する検証へ強化 + - unresolved component は XML comment のみ残し、DSL 本体から除外 + - style-only empty cell と explicit `styleOverflow` の serializer テストを追加 +3. 再 review + - Findings: なし + +## Residual Risks +- unresolved component の machine-readable な失敗文脈は `Issues` 側を正とする前提になる +- style/source metadata の debug fidelity を XML と DSL emitter のどちらで担保するかは後続 task で詰める必要がある diff --git a/tasks/feedback-points.md b/tasks/feedback-points.md index b94fec6..cbc4e6b 100644 --- a/tasks/feedback-points.md +++ b/tasks/feedback-points.md @@ -2,7 +2,7 @@ プロジェクトマネージャーへの指摘事項を記録 -Last Updated: 2026-04-05 +Last Updated: 2026-04-14 ## アクティブな指摘点 @@ -101,6 +101,43 @@ Last Updated: 2026-04-05 | FP107 | issue #16 follow-up: 設計書に C# `$\"...\"` 補間記法の書き方を明記する | 対応済み | 2026-04-05 | | FP108 | PR #57 Codexレビュー: `xl` ローカル宣言によるラムダ変数名衝突(CS0136)を解消し、回帰テストで担保する | 対応済み | 2026-04-05 | | FP109 | PR #57 SubAgent指摘: `xl` ヘルパーの null/空白入力は Runtime Error とし、設計書の実装方針記述を実装実態に合わせて修正する | 対応済み | 2026-04-05 | +| FP110 | issue #58 は実装前に設計書を作成し、ユーザー承認を得てから進める | 対応中 | 2026-04-07 | +| FP111 | `gh` が使えない場合でも、URL直接参照など代替手段で issue 本文を取得して要件確定する | 対応中 | 2026-04-07 | +| FP112 | issue #58 設計ではA/B案を盲従せず代替案も比較し、結果としてA案採用なら理由を明記する。グラフ作成機能は今回スコープ外へ明記する | 対応中 | 2026-04-07 | +| FP113 | issue #58 設計では入れ子コンポーネント定義/シート定義/挿入表現を具体例で明記し、実装前にレビュー可能な状態にする | 対応中 | 2026-04-07 | +| FP114 | issue #58 設計では入れ子コンポーネント時の罫線(border)解決方針を具体化し、競合時の優先順位とWarning方針を明記する | 対応中 | 2026-04-07 | +| FP115 | issue #58 設計ではセル値の具体例をMarkdownテーブルで示し、挿入トリガや罫線競合の変換結果を明確化する | 対応中 | 2026-04-07 | +| FP116 | issue #58 設計では実装前懸念を深掘りし、後戻りコストが高い項目を事前合意チェックリストで固定する | 対応中 | 2026-04-07 | +| FP117 | issue #58 設計ではテーブルの各セルをExcel座標に一致させ、必要に応じてSVGで書式状態を可視化する | 対応中 | 2026-04-11 | +| FP118 | issue #58 設計では「挿入元 > 挿入先想定範囲」のサイズ不一致時に書式が壊れないルール(overflow展開/Warning/Error)を明記し、設計書名を内容が分かる名称へ修正する | 対応済み | 2026-04-12 | +| FP119 | issue #58 設計ではセル表示値SVGを挿入元/挿入先で分離し、書式説明をMarkdownへ移し、挿入C# classデータとコンポーネント定義範囲を明記する | 対応済み | 2026-04-12 | +| FP120 | issue #58 設計では C#データ展開後のセル値をSVG表で追加し、展開結果の行配置をレビュー可能にする | 対応済み | 2026-04-12 | +| FP121 | issue #58 設計では展開後SVGの書式表現を再検討し、11章ルール(親外枠/子明細bottom/競合辺)と一致させる | 対応済み | 2026-04-12 | +| FP122 | issue #58 のSVGは説明用の背景色強調を使わず、実際のExcelTemplate/出力Excelの見た目に寄せて表現する | 対応済み | 2026-04-12 | +| FP123 | issue #58 のSVGは挿入元/挿入先にもテンプレート定義罫線を反映し、出力結果との書式差分を説明図都合で生まない | 対応済み | 2026-04-12 | +| FP124 | issue #58 設計では「挿入先書式は任意(mustではない)」を明記し、3x3外枠+中央use の外枠追従拡張と列方向overflow対応(`deltaCols`)を追加する | 対応済み | 2026-04-12 | +| FP125 | `Invoice` の `use` 部分の書式が必須に見える懸念に対し、SVG節へ「テンプレートで定義されている場合の例であり必須ではない」注記を追加する | 対応済み | 2026-04-12 | +| FP126 | issue #58 のSVG例を `3x3挿入先 + 中央use` / `3x4子component` に更新し、挿入先書式overflowを `styleOverflow`(`none`/`edge`)で選択可能にして `A1:C1` と `A1:B1` の拡張挙動を決定する | 対応済み | 2026-04-12 | +| FP127 | 10.10.1 で消えた挿入元図を復元し、ユーザー例示の簡略文言(ヘッダー/なにかの値)ではなく `GroupBlock/ItemRow` の正式フォーマットでSVG/設計表を整合させる | 対応済み | 2026-04-12 | +| FP128 | 10.8.3/10.8.4 と 10.10.1/10.10.2 の図参照が離れて見づらい点を改善し、10.8.3 の不要な破線を除去して `use:Header` を追加する | 対応済み | 2026-04-12 | +| FP129 | 状態遷移図は不要とし、10.8.10 は状態整理テーブルのみで記載する | 対応済み | 2026-04-12 | +| FP130 | 10.8.9 の出力図が古い指摘に対し、`A1:F1` Header拡張と `A3:E8` 子枠拡張が確認できる図へ更新し、本文も抜粋図であることを明記する | 対応済み | 2026-04-12 | +| FP131 | 10.8.9 は `GroupBlock` repeat を個別フレームではなく連続展開として扱い、1件目を `B4:D7`、2件目を `B8:D9`、親フレームを `A3:E10` とする図と説明へ修正する | 対応済み | 2026-04-12 | +| FP132 | 設計のぬけもれがないか、sub-agent(`gpt-5.3-codex` / `high`)でレビューし、指摘事項をレポート化する | 対応済み | 2026-04-12 | +| FP133 | sub-agent 指摘を受け、`GroupBlock` 幅定義、`repeat` 時の aggregate `H/W`、`styleOverflow=edge` の行方向、連続 instance 境界の罫線優先順を設計へ反映する | 対応済み | 2026-04-12 | +| FP134 | 更新後設計を再度 sub-agent(`gpt-5.3-codex` / `high`)でレビューし、High/Critical が解消済みであることを確認する | 対応済み | 2026-04-12 | +| FP135 | 再レビューの Low 指摘として、`styleOverflow=edge` の4方向検証不足と 10.9.4 の右方向偏りを設計へ反映する | 対応済み | 2026-04-12 | +| FP136 | `gpt-5.4` / `high` レビュー指摘として、現行 `use` 展開モデルでは `styleOverflow=edge` を right/down/right-down corner に限定し、overflow比較SVGも generic 文脈へ修正する | 対応済み | 2026-04-12 | +| FP137 | 数式セルは原則 `cell@formula` とし、C# 側で Excel 関数計算をしない前提を設計へ明記する | 対応済み | 2026-04-12 | +| FP138 | 実装前レビュー回答として、merged cell 制約は矩形内完結のみ、条件付き書式は初版対象外、性能閾値は当面不問で進める | 対応済み | 2026-04-12 | +| FP139 | issue #58 の実装方針を策定し、sub-agent レビューを通して runtime schema 対象、`repeat@direction`、`styleOverflow=edge` 実装位置、conversion API の診断返却まで設計へ固定する | 対応済み | 2026-04-12 | +| FP140 | 新しいチャットに移っても issue #58 実装を追加確認なしで再開できる handover 文書を作成する | 対応済み | 2026-04-12 | +| FP141 | 外部仕様変更やブロッカーがない限り、確認待ちを増やさず極力自走して進める | 対応中 | 2026-04-13 | +| FP142 | issue #58 の残作業は、phase を task より大きい粒度で全洗い出しし、残件数と完了見込みが追えるように tasks/phases へ明示する | 対応中 | 2026-04-13 | +| FP143 | issue #58 でヌケモレが見つかった場合は、実装前に phase/task へまとめて追加してから着手し、小出しで後追い追加しない。この指摘も必ずメモする | 対応中 | 2026-04-13 | +| FP144 | ユーザーが止めると言うか、当初目標が完了するまで自走し、指示待ちで止まらない | 対応中 | 2026-04-13 | +| FP145 | issue #58 は DSL互換を最優先にし、DSLへ変換できない実装には価値がない前提で進める | 対応中 | 2026-04-14 | +| FP146 | sub-agent レビュー結果は毎回 `reports/` にファイル出力してから共有する | 対応中 | 2026-04-14 | --- ## 対応履歴 diff --git a/tasks/phases-status.md b/tasks/phases-status.md index 4e81054..61a0001 100644 --- a/tasks/phases-status.md +++ b/tasks/phases-status.md @@ -1,9 +1,94 @@ # Phases Status -Last Updated: 2026-04-05 +Last Updated: 2026-04-14 ## Overall Progress +- 2026-04-14: issue #58 の最終reviewとして `gpt-5.4` / `high` round 7 を実施し、findings なしを `reports/issue58-final-review-2026-04-14-round7.md` に記録 +- 2026-04-14: issue #58 の最終検証として関連17件と全体259件の通過を確認 +- 2026-04-14: issue #58 の収束確認として shorthand/local scope 正規化、複数 `GroupBlock` happy-path E2E、tasks/phases の残件0整合を確認 +- 2026-04-14: issue #58 の converter review round 2 として、`EnableSchemaValidation=false` 時も `DslParser` の非schema検証を継続する修正を反映し、`reports/issue58-converter-review-2026-04-14-round2.md` に記録 +- 2026-04-14: issue #58 の Phase 14 として `UseTriggerParser` の `styleOverflow` 対応、Excel shorthand expression の emitted DSL 正規化、nested/negative E2E を完了 +- 2026-04-14: issue #58 の Phase 14 review を `gpt-5.4` / `high` で `timeout 15s codex exec review` により再試行したが、sandbox の network 制限で timeout したため `reports/issue58-dsl-compatibility-e2e-review-2026-04-14.md` に記録 +- 2026-04-14: issue #58 の設計書を emitted DSL の expression 正規化と `styleOverflow` trigger 仕様へ同期 +- 2026-04-14: issue #58 の Phase 14 検証として E2E 3件、関連86件、全体256件通過を確認 +- 2026-04-14: issue #58 の Phase 14 着手前棚卸しで、`styleOverflow` trigger 未対応と Excel shorthand expression の DSL runtime 非互換を確認し、残taskへ追加 +- 2026-04-14: issue #58 の Phase 13 として `ExcelTemplateReportGenerator` / `ExcelTemplateGenerateOptions` を追加し、ExcelTemplate facade から既存 `ReportGenerator` まで接続 +- 2026-04-14: issue #58 の Phase 13 で non-fatal conversion issue の最終結果集約と fatal conversion issue の short-circuit を実装 +- 2026-04-14: issue #58 の Phase 13 review を `gpt-5.4` / `high` で `timeout 15s codex exec review` により再試行したが、sandbox の network 制限で timeout したため `reports/issue58-excel-template-facade-review-2026-04-14.md` に記録 +- 2026-04-14: issue #58 の Phase 13 検証として facade 3件、関連81件、全体251件通過を確認 +- 2026-04-14: issue #58 の残phase/taskを `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` と再突合し、`Phase 12-14 / R58-07..R58-12` でゴールまでの手順が網羅されていることを確認 +- 2026-04-14: issue #58 の Phase 12 として `ExcelTemplateConverter` / conversion result / options を追加し、conversion-only API を `Text + Issues` 契約へ統合 +- 2026-04-14: issue #58 の Phase 12 review対応として、corrupt workbook の `FileFormatException` 漏れを fatal `LoadFile` issue 集約へ修正し、失敗系 integration test を追加 +- 2026-04-14: issue #58 の Phase 12 review を `gpt-5.4` / `high` で `codex exec review` により再試行したが、sandbox の network 制限で中断したため `reports/issue58-conversion-api-review-2026-04-14.md` に記録 +- 2026-04-14: issue #58 の Phase 12 検証として converter 4件、関連32件、全体248件通過を確認 +- 2026-04-13: issue #58 の snapshot task として debug XML / DSL text の external fixture を追加し、serializer/emitter の canonical shape を固定 +- 2026-04-13: issue #58 の snapshot を `gpt-5.4` / `high` sub-agent で review し、findings なしを確認 +- 2026-04-13: issue #58 の snapshot 検証として snapshot 2件、関連28件、全体244件通過を確認 +- 2026-04-13: issue #58 の `DslEmitter` を追加し、DSL 互換 XML を UTF-8 declaration 付き DSL text へ出力可能化 +- 2026-04-13: issue #58 の emitted DSL text で `cell@formula` / explicit `styleOverflow` / `direction="down"` 保持を固定 +- 2026-04-13: issue #58 の `DslEmitter` を `gpt-5.4` / `high` sub-agent で review し、findings なしを確認 +- 2026-04-13: issue #58 の emitter 検証として emitter 2件、関連26件、全体242件通過を確認 +- 2026-04-13: issue #58 の `XmlTemplateSerializer` を追加し、`workbook/component/grid/sheet/cell/use/repeat` の DSL 互換 XML 出力を実装 +- 2026-04-13: issue #58 の serializer review で指摘された XSD validation 検証不足、未解決 component の DSL 化、serializer 分岐テスト不足を修正 +- 2026-04-13: issue #58 の `XmlTemplateSerializer` を `gpt-5.4` / `high` sub-agent で再 review し、findings なしを確認 +- 2026-04-13: issue #58 の serializer 検証として serializer 4件、関連24件、全体240件通過を確認 +- 2026-04-13: issue #58 の出力契約第1段として `ExcelTemplateOutputContractBuilder` と normalized output model を追加し、component/sheet 分類・cell/use/repeat-use 正規化・issue 集約を固定 +- 2026-04-13: issue #58 の output contract review で指摘された `styleOverflow` 未指定区別、未解決 component 文脈保持、style-only cell / malformed trigger テスト不足を修正 +- 2026-04-13: issue #58 の output contract を `gpt-5.4` / `high` sub-agent で再 review し、findings なしを確認 +- 2026-04-13: issue #58 の output contract 検証として output contract 3件、ExcelTemplate 系20件、全体236件通過を確認 +- 2026-04-13: issue #58 の validator を追加し、merged range 境界違反・malformed use trigger・unsupported conditional formatting を Error として検出可能化 +- 2026-04-13: issue #58 の `UseTriggerParser` を top-level comma tokenizer へ補強し、`from:` 式内カンマを含む repeat trigger の回帰を修正 +- 2026-04-13: issue #58 の validator 実装記録と review 記録を `reports/issue58-validator-and-trigger-hardening-2026-04-13.md` / `reports/issue58-validator-review-2026-04-13.md` に保存 +- 2026-04-13: issue #58 の validator/trigger/extractor 関連89件と全体233件通過を確認 +- 2026-04-13: issue #58 の use trigger 解析第1段として `UseTriggerParser` を追加し、simple use / repeat use を構造化、repeat direction を `down` で固定 +- 2026-04-13: issue #58 の use trigger parser を 5件の unit test と全体228件回帰で検証 +- 2026-04-13: issue #58 の use trigger parser review は `gpt-5.4` / `high` で再試行したが、network 制限により中断したため report に記録 +- 2026-04-13: issue #58 の component range 解決第1段として `ExcelTemplateComponentRangeResolver` を追加し、defined name 優先 + candidate bbox 自動判定を実装 +- 2026-04-13: issue #58 の component range resolver を 5件の unit test と全体223件回帰で検証 +- 2026-04-13: issue #58 の component range resolver review は `gpt-5.4` / `high` で再試行したが、network 制限により中断したため report に記録 +- 2026-04-13: issue #58 の ExcelTemplate 中間モデル第1段として `ExcelTemplateExtractor` と workbook/sheet/cell/style/component range モデルを追加 +- 2026-04-13: issue #58 の extractor を xlsx 読取テストで固定し、追加2件 + 全体218件通過を確認 +- 2026-04-13: issue #58 の extractor 実装内容と review 試行結果を `reports/issue58-excel-template-extractor-2026-04-13.md` に記録 +- 2026-04-13: issue #58 の `styleOverflow=edge` runtime 検証を down/corner ケースまで拡張し、関連72件・全体216件通過を確認 +- 2026-04-13: issue #58 の review 試行結果と残留リスクを `reports/issue58-dsl-contract-extension-review-2026-04-13.md` に記録 +- 2026-04-12: issue #58 実装開始として `cell@formula` / `use@styleOverflow` の DSL契約拡張、`ValidateDsl` 補完検証、`LayoutEngine` の `styleOverflow=edge` post-expand 補完、`TemplateRangeOverflow` Warning を実装 +- 2026-04-12: issue #58 の実装第1段を全体回帰で検証し、`ExcelReportLib.Tests` 214件全通過を確認 +- 2026-04-12: issue #58 設計へ「挿入先書式は任意」を明記し、3x3外枠+中央use の外枠追従拡張ルール(子範囲+余白)を追加 +- 2026-04-12: issue #58 のサイズ不一致対応を列方向まで拡張し、`TemplateRangeOverflow` の `deltaRows/deltaCols` 記録を定義 +- 2026-04-12: issue #58 挿入元/挿入先SVGへテンプレート定義罫線を反映し、出力結果SVGとの書式整合を改善 +- 2026-04-12: issue #58 SVG表現を説明用強調から実運用見た目へ修正し、ExcelTemplate/出力Excelと同系統の見た目に統一 +- 2026-04-12: issue #58 展開後SVGの書式スタイルを再検討し、罫線ルール準拠(親外枠/子明細bottom/競合辺)へ修正 +- 2026-04-12: issue #58 設計へ C#サンプルデータ展開後セル値のSVG(`expanded-cell-values-from-csharp.svg`)を追加 +- 2026-04-12: issue #58 設計でセル表示値SVGを挿入先/挿入元に分離し、書式説明はMarkdownテーブルへ移管 +- 2026-04-12: issue #58 設計へ挿入データのC# class定義(`InvoiceData/GroupData/ItemData`)とサンプル入力を追加 +- 2026-04-12: issue #58 設計へコンポーネント定義範囲(DefinedName明示指定 + 自動判定)と検証ルールを追加 +- 2026-04-12: issue #58 設計にサイズ不一致(挿入元 > 挿入先想定範囲)時の展開/書式保持ルールを追加し、`TemplateRangeOverflow` Warning と結合セル境界Error条件を明記 +- 2026-04-12: issue #58 の設計書名を「Excelテンプレート対応」に明確化し、ファイル名を `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` に更新 +- 2026-04-11: issue #58 設計にセル座標一致の表現(A-D列マトリクス)とSVG可視化を追加 +- 2026-04-07: issue #58 実装前リスクを詳細化し、高コストな後戻り項目の事前合意リストを追加 +- 2026-04-07: issue #58 設計にセル値の具体例テーブルを追加し、変換イメージを明確化 +- 2026-04-07: issue #58 設計へセル書式方針(border中心)を追加し、入れ子時の罫線競合解決ルールを明文化 +- 2026-04-07: issue #58 設計へ入れ子component・sheet定義・use挿入の具体例を追加し、実装前レビュー精度を向上 +- 2026-04-07: issue #58 設計を見直し、A/B/C比較の上でA案採用理由を明文化。対象範囲外にグラフ作成機能を追記 +- 2026-04-07: issue #58 の本文を URL 直接参照で取得し、設計を要件反映版へ更新(承認待ち) +- 2026-04-07: issue #58 対応を開始し、要件未取得リスクを `reports/issue58-investigation-2026-04-07.md` に記録 +- 2026-04-07: issue #58 の実装前ステップとして設計ドラフト `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` を作成し、ユーザー承認待ちへ遷移 + +## Issue #58 Remaining Phases + +- 基準日: 2026-04-14 +- 現在位置: issue #58 完了 +- 残見積り: 0 phases / 0 tasks / 0 実装サイクル +- 注記: 下部の `Phase Summary` / `Completed Phases` は既存プロジェクト全体の旧集計であり、issue #58 の残作業はこの節を正として扱う +- 棚卸し結果: phase 追加は不要。Phase 14 で追加した DSL互換 hardening task も同サイクルで完了済み + +| Phase | Status | Scope | Exit Criteria | Estimate | +|---|---|---|---|---| +| Phase 11: Conversion Output Core | Done | `DslEmitter` / `XmlTemplateSerializer` / 変換用fixture整備 | ExcelTemplate から XML debug / DSL text を安定出力でき、snapshot unit が通る | 1-2 cycles | +| Phase 12: Conversion API Integration | Done | `ExcelTemplateConverter` / options / result object / issue集約 | `ConvertToDsl` / `ConvertToXmlTemplate` が `Text + Issues` を返し、conversion-only API を integration test で固定 | 1 cycle | +| Phase 13: Report Generation Facade | Done | `ExcelTemplateReportGenerator` / 既存 `ReportGenerator` 接続 / happy-path統合 | `GenerateFromExcelTemplate` で既存 DSL 経路まで接続し、基本生成ケースが通る | 1 cycle | +| Phase 14: DSL Compatibility Hardening And E2E Closeout | Done | trigger/styleOverflow hardening / expression DSL互換化 / xlsx->dsl->final xlsx E2E / negative E2E / docs同期 / 最終review | DSL互換 hardening 後に happy-path + negative-path を含む E2E と records/tasks/phases 更新が完了 | 1-2 cycles | - 2026-04-05: issue #16 向けに `Design/SheetReference/SheetReference_DetailDesign.md` を追加し、sheet repeat 生成シート間参照の仕様を定義 - 2026-04-05: `cell@value` 式評価結果が `=` 始まり文字列の場合に数式として扱う仕様を `DslDefinition_DetailDesign.md` へ追記 - 2026-04-05: `LayoutEngine.EvaluateCellValue` を拡張し、式評価結果 `=...` を数式として保持する実装を追加 @@ -194,6 +279,24 @@ Last Updated: 2026-04-05 - 2026-04-05: 調査記録 `reports/pr49-codex-review-followup-2026-04-05.md` を追加 - 2026-04-05: 設計書 `DslDefinition_DetailDesign.md` に属性逆引き章を追加(`area` に限定しない属性単位整理) - 2026-04-05: issue #16 follow-up として `sheet repeat` の完全例(データモデル/DSL全文/展開結果)を `Design/SheetReference/SheetReference_DetailDesign.md` に追記 +- 2026-04-12: issue #58 設計補足として `Invoice` の `use` 書式は任意(mustではない)を 10.8.3 注記へ追記 +- 2026-04-12: issue #58 で SVG 例を `3x3挿入先 + 中央use` / `3x4子` へ更新し、書式overflow比較図を追加 +- 2026-04-12: issue #58 で `styleOverflow`(`none`/`edge`)ポリシーと `A1:C1` / `A1:B1` ケースの決定ルールを設計へ反映 +- 2026-04-12: issue #58 で 10.10.1 の挿入元SVGを復元し、簡略例から `GroupBlock/ItemRow` 正式フォーマットへ差し戻し +- 2026-04-12: issue #58 で図の参照を 10.8 節へ集約(10.8.8/10.8.9)し、10.8.3 の破線除去 + `use:Header` 追加を反映 +- 2026-04-12: issue #58 で 10.8.10 は状態遷移図を省略し、状態整理テーブル中心の記載へ調整 +- 2026-04-12: issue #58 で 10.8.9 出力SVGを `A1:F1` / `A3:E8` 状態整理ケースへ更新し、説明文も先頭GroupBlock抜粋へ整合 +- 2026-04-12: issue #58 で repeat 解釈を修正し、`GroupBlock` 2件は `B4:D7` / `B8:D9` に連続展開、親フレームは `A3:E10` として 10.8.9/10.8.10 を更新 +- 2026-04-12: issue #58 で sub-agent(`gpt-5.3-codex` / `high`)レビューを実施し、`repeat` 高さ定義・`GroupBlock` 幅定義・`styleOverflow=edge` 行方向・連続境界罫線の未定義を残課題として記録 +- 2026-04-12: issue #58 で sub-agent 指摘へ対応し、`GroupBlock` を `A1:C3` に統一、`repeat` 時の aggregate `H/W`、`styleOverflow=edge` の上下左右、連続 instance 境界の trailing edge 優先を設計へ反映 +- 2026-04-12: issue #58 で更新後設計を sub-agent(`gpt-5.3-codex` / `high`)で再レビューし、重大指摘なし、残留は `styleOverflow=edge` の4方向検証と 10.9.4 表の表現改善のみと確認 +- 2026-04-12: issue #58 で再レビューの Low 指摘へ対応し、10.9.4 の期待結果表を4方向+角領域へ拡張、11.5 に left/top/corner copy 検証を追加 +- 2026-04-12: issue #58 で `gpt-5.4` / `high` レビューを実施し、現行モデルでは `styleOverflow=edge` を right/down/right-down corner に限定すべきと確認、10.9.4/11.5/SVG を整合 +- 2026-04-12: issue #58 で数式セルの正規化方針を確定し、`cell@formula` 原則・C# 側で Excel 関数計算を行わない前提を設計へ反映 +- 2026-04-12: issue #58 の実装前レビュー回答を反映し、merged cell 制約・条件付き書式対象外を固定、性能閾値は当面未固定で進める方針に更新 +- 2026-04-12: issue #58 の実装方針として、既存 `ReportGenerator` 後段を再利用しつつ、`ExcelTemplate` 前段変換層・DSL契約拡張・テスト順序を 13章と実装方針レポートへ整理 +- 2026-04-12: issue #58 の実装方針を sub-agent(`gpt-5.4` / `high`)でレビューし、runtime schema 更新対象、`repeat@direction=\"down\"` 明示、`styleOverflow=edge` の `LayoutEngine` post-expand 実装、conversion result + `Issues`、`ValidateDsl` 補完検証を反映 +- 2026-04-12: 新しいチャット向け handover 文書を作成し、issue #58 実装再開に必要な背景・決定事項・未解決事項・次アクションを固定 - Completed Phases: 10 / 10 - In Progress Phases: 0 / 10 - Overall Progress: 100% diff --git a/tasks/tasks-status.md b/tasks/tasks-status.md index 735625f..757ac43 100644 --- a/tasks/tasks-status.md +++ b/tasks/tasks-status.md @@ -1,10 +1,115 @@ # Tasks Status -Last Updated: 2026-04-05 -Scope: ExcelReport開発 - issue #16 シート間参照 / issue #43 非同期api対応 / README刷新(Chart・Async) +Last Updated: 2026-04-14 +Scope: ExcelReport開発 - issue #16 シート間参照 / issue #43 非同期api対応 / issue #58 Excelテンプレート対応(実装開始) / README刷新(Chart・Async) ## Progress Summary +- 2026-04-14 issue#58 最終review完了: `gpt-5.4` / `high` round 7 で findings なしを確認し、`reports/issue58-final-review-2026-04-14-round7.md` に記録 +- 2026-04-14 issue#58 最終検証: `ExcelTemplateOutputContractBuilderTests|ExcelTemplateEndToEndTests|ExcelTemplateConverterTests|ExcelTemplateReportGeneratorTests` 17件通過、`ExcelReportLib.Tests` 全体259件通過 +- 2026-04-14 issue#58 収束確認: shorthand/local scope 正規化、複数 `GroupBlock` happy-path E2E、tasks/phases の残件0整合を確認 +- 2026-04-14 issue#58 review対応: `EnableSchemaValidation=false` でも `DslParser` の非schema検証を継続するよう `ExcelTemplateConverter` を修正し、review round 2 記録を `reports/issue58-converter-review-2026-04-14-round2.md` に保存 +- 2026-04-14 issue#58 実装完了: `UseTriggerParser` に `styleOverflow` を追加し、Excel shorthand expression を emitted DSL の runtime 互換 `@(...)` 形へ正規化 +- 2026-04-14 issue#58 E2E追加: nested `GroupBlock` / `ItemRow` / `styleOverflow=edge` / `cell@formula` の happy-path と、`MergedCellBoundaryViolation` / `UnsupportedExcelTemplateFeature` の negative-path を facade 経由で固定 +- 2026-04-14 issue#58 review試行: `gpt-5.4` / `high` review を `timeout 15s codex exec review` で再試行したが、sandbox の network 制限により timeout したため `reports/issue58-dsl-compatibility-e2e-review-2026-04-14.md` に記録 +- 2026-04-14 issue#58 設計同期: emitted DSL の expression 正規化と `styleOverflow` trigger を `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` に反映 +- 2026-04-14 issue#58 検証: `ExcelTemplateEndToEndTests` 3件、関連86件、`ExcelReportLib.Tests` 全体256件通過 +- 2026-04-14 issue#58 記録: DSL互換 hardening/E2E 実装記録と review 記録を `reports/issue58-dsl-compatibility-e2e-2026-04-14.md` / `reports/issue58-dsl-compatibility-e2e-review-2026-04-14.md` に保存 +- 2026-04-14 issue#58 残件補正: Phase 14 着手前の棚卸しで、`styleOverflow` の trigger 未対応と Excel shorthand expression の DSL runtime 非互換を確認し、残taskへ追加 +- 2026-04-14 issue#58 実装継続: `ExcelTemplateReportGenerator` / `ExcelTemplateGenerateOptions` を追加し、`xlsx -> dsl -> final xlsx` の facade API を既存 `ReportGenerator` 経路へ接続 +- 2026-04-14 issue#58 実装補強: non-fatal conversion issue を最終 `ReportGeneratorResult.Issues` に保持しつつ生成を継続し、fatal conversion issue は facade で short-circuit する契約を固定 +- 2026-04-14 issue#58 review試行: `gpt-5.4` / `high` review を `timeout 15s codex exec review` で再試行したが、sandbox の network 制限により timeout したため `reports/issue58-excel-template-facade-review-2026-04-14.md` に記録 +- 2026-04-14 issue#58 検証: `ExcelTemplateReportGeneratorTests` 3件、関連81件、`ExcelReportLib.Tests` 全体251件通過 +- 2026-04-14 issue#58 記録: facade 実装記録と review 記録を `reports/issue58-excel-template-facade-2026-04-14.md` / `reports/issue58-excel-template-facade-review-2026-04-14.md` に保存 +- 2026-04-14 issue#58 残件再棚卸し: `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` と tasks/phases を突合し、残作業は `Phase 12-14 / R58-07..R58-12` で網羅されていることを確認(追加 task/phase なし) +- 2026-04-14 issue#58 実装継続: `ExcelTemplateConverter` / `ExcelTemplateConversionResult` / `ExcelTemplateConvertOptions` を追加し、conversion-only API を `Text + Issues` 返却へ統合 +- 2026-04-14 issue#58 review対応: corrupt workbook 入力で漏れていた `FileFormatException` を fatal `IssueKind.LoadFile` へ集約し、schema validation opt-out を含む integration test を補強 +- 2026-04-14 issue#58 review試行: `gpt-5.4` / `high` review を `codex exec review` で再試行したが、sandbox の network 制限(dns/websocket `Operation not permitted`)で完了できず、結果を `reports/issue58-conversion-api-review-2026-04-14.md` に記録 +- 2026-04-14 issue#58 検証: `ExcelTemplateConverterTests` 4件、関連32件、`ExcelReportLib.Tests` 全体248件通過 +- 2026-04-14 issue#58 記録: conversion API 実装記録と review 記録を `reports/issue58-conversion-api-2026-04-14.md` / `reports/issue58-conversion-api-review-2026-04-14.md` に保存 +- 2026-04-13 issue#58 テスト追加: serializer/emitter の external snapshot として `Issue58_StandardTemplate_Debug.xml` / `Issue58_StandardTemplate_Dsl.xml` を追加 +- 2026-04-13 issue#58 review完了: `gpt-5.4` / `high` sub-agent review で snapshot 差分の findings なしを確認 +- 2026-04-13 issue#58 検証: `ExcelTemplateSnapshotTests` 2件、関連28件、`ExcelReportLib.Tests` 全体244件通過 +- 2026-04-13 issue#58 記録: snapshot 実装記録と review 記録を `reports/issue58-snapshots-2026-04-13.md` / `reports/issue58-snapshots-review-2026-04-13.md` に保存 +- 2026-04-13 issue#58 実装継続: `DslEmitter` を追加し、DSL 互換 `XDocument` を UTF-8 declaration 付き DSL text へ出力可能化 +- 2026-04-13 issue#58 実装完了: `cell@formula` / explicit `styleOverflow` / `direction=\"down\"` を emitted DSL text に保持する経路を固定 +- 2026-04-13 issue#58 review完了: `gpt-5.4` / `high` sub-agent review で `DslEmitter` 差分の findings なしを確認 +- 2026-04-13 issue#58 検証: `DslEmitterTests` 2件、関連26件、`ExcelReportLib.Tests` 全体242件通過 +- 2026-04-13 issue#58 記録: emitter 実装記録と review 記録を `reports/issue58-dsl-emitter-2026-04-13.md` / `reports/issue58-dsl-emitter-review-2026-04-13.md` に保存 +- 2026-04-13 issue#58 実装継続: `XmlTemplateSerializer` を追加し、`workbook/component/grid/sheet/cell/use/repeat` の DSL 互換 XML 出力を実装 +- 2026-04-13 issue#58 review対応: serializer の XSD validation 検証を追加し、未解決 component は DSL 本体から除外して comment に退避、style-only empty cell / explicit `styleOverflow` の分岐テストを補強 +- 2026-04-13 issue#58 review完了: `gpt-5.4` / `high` sub-agent 再 review で findings なしを確認 +- 2026-04-13 issue#58 検証: `XmlTemplateSerializerTests` 4件、関連24件、`ExcelReportLib.Tests` 全体240件通過 +- 2026-04-13 issue#58 記録: serializer 実装記録と review 記録を `reports/issue58-xml-template-serializer-2026-04-13.md` / `reports/issue58-xml-template-serializer-review-2026-04-13.md` に保存 +- 2026-04-13 issue#58 実装継続: `ExcelTemplateOutputContractBuilder` と output contract model を追加し、component/sheet 分類・cell/use/repeat-use 正規化・issue 集約を固定 +- 2026-04-13 issue#58 review対応: `styleOverflow` を未指定と明示 `none` で区別できる contract に修正し、未解決 component 文脈保持と style-only/malformed trigger の契約テストを補強 +- 2026-04-13 issue#58 review完了: `gpt-5.4` / `high` sub-agent 再 review で findings なしを確認 +- 2026-04-13 issue#58 検証: output contract 3件、ExcelTemplate 系20件、`ExcelReportLib.Tests` 全体236件通過 +- 2026-04-13 issue#58 記録: output contract 実装記録と review 記録を `reports/issue58-output-contract-2026-04-13.md` / `reports/issue58-output-contract-review-2026-04-13.md` に保存 +- 2026-04-13 issue#58 実装継続: `ExcelTemplateValidator` を追加し、merged range 境界違反・malformed use trigger・unsupported conditional formatting を Error 化 +- 2026-04-13 issue#58 実装修正: `UseTriggerParser` を top-level comma tokenizer へ補強し、`from:` 式内カンマを含む trigger を正しく解析可能化 +- 2026-04-13 issue#58 検証: validator/extractor 6件、関連89件、`ExcelReportLib.Tests` 全体233件通過 +- 2026-04-13 issue#58 記録: validator 実装記録と review 記録を `reports/issue58-validator-and-trigger-hardening-2026-04-13.md` / `reports/issue58-validator-review-2026-04-13.md` に保存 +- 2026-04-13 issue#58 実装継続: `UseTriggerParser` を追加し、`{{use:...}}` / `repeat + use` の最小文法を構造化して `direction=\"down\"` を固定 +- 2026-04-13 issue#58 検証: `ExcelTemplateUseTriggerParserTests` 5件通過、`ExcelReportLib.Tests` 全体228件通過 +- 2026-04-13 issue#58 review試行: `gpt-5.4` / `high` review は network 制限で中断し、結果を `reports/issue58-use-trigger-parser-review-2026-04-13.md` に記録 +- 2026-04-13 issue#58 記録: use trigger parser 実装内容を `reports/issue58-use-trigger-parser-2026-04-13.md` に記録 +- 2026-04-13 issue#58 実装継続: `ExcelTemplateComponentRangeResolver` を追加し、`__component_` の defined name 優先解決と candidate bbox 自動判定を実装 +- 2026-04-13 issue#58 検証: `ExcelTemplateComponentRangeResolverTests` 5件通過、`ExcelReportLib.Tests` 全体223件通過 +- 2026-04-13 issue#58 review試行: `gpt-5.4` / `high` review は network 制限で中断し、結果を `reports/issue58-component-range-resolver-review-2026-04-13.md` に記録 +- 2026-04-13 issue#58 記録: component range resolver 実装内容を `reports/issue58-component-range-resolver-2026-04-13.md` に記録 +- 2026-04-13 issue#58 実装継続: `ExcelTemplateExtractor` と中間モデル(workbook/sheet/cell/style/component range)を追加し、xlsx から sheet/cell/formula/defined name/merged cell を読取可能化 +- 2026-04-13 issue#58 検証: `ExcelTemplateExtractorTests` 2件通過、`ExcelReportLib.Tests` 全体218件通過 +- 2026-04-13 issue#58 記録: extractor 実装と review 試行結果を `reports/issue58-excel-template-extractor-2026-04-13.md` に記録 +- 2026-04-13 issue#58 テスト補強: `styleOverflow=edge` の down/corner runtime テストを追加し、`LayoutNodeTests|ValidateDslTests|DslParserTests|LayoutEngineTests` 72件通過、`ExcelReportLib.Tests` 全体216件通過 +- 2026-04-13 issue#58 review記録: `gpt-5.4` / `high` review 試行結果と残留リスクを `reports/issue58-dsl-contract-extension-review-2026-04-13.md` に記録 +- 2026-04-12 issue#58 実装開始: `cell@formula` / `use@styleOverflow` の DSL 契約拡張、`ValidateDsl` 補完検証、`LayoutEngine` の `styleOverflow=edge` post-expand 補完、`TemplateRangeOverflow` Warning を実装 +- 2026-04-12 issue#58 検証: `LayoutNodeTests|ValidateDslTests|DslParserTests|LayoutEngineTests` 70件通過、`ExcelReportLib.Tests` 全体214件通過 +- 2026-04-12 issue#58 設計修正: 挿入先書式は任意(mustではない)を明記し、3x3外枠+中央useの外枠追従拡張ルール(子範囲+余白)を追加 +- 2026-04-12 issue#58 設計修正: サイズ不一致を行方向だけでなく列方向も対象化し、`TemplateRangeOverflow` に `deltaRows/deltaCols` 記録を追加 +- 2026-04-12 issue#58 可視化再修正: 挿入元/挿入先SVGにもテンプレート定義罫線(実線/破線)を反映し、出力SVGとの見た目整合を改善 +- 2026-04-12 issue#58 可視化方針修正: SVGを説明用着色から実運用見た目へ変更し、ExcelTemplate/出力Excelに寄せた表記へ統一 +- 2026-04-12 issue#58 可視化修正: 展開後SVGの書式表現を再設計し、親外枠/子明細bottom/競合辺(子優先+Warning)を線種で明示 +- 2026-04-12 issue#58 可視化追加: C#サンプルデータ展開後のセル値SVG(`expanded-cell-values-from-csharp.svg`)を設計書へ追加 +- 2026-04-12 issue#58 可視化更新: セル表示値のSVGを挿入先/挿入元で分離(`insert-target-cell-values.svg` / `insert-source-cell-values.svg`)、書式説明はMarkdown表へ移管 +- 2026-04-12 issue#58 設計補完: 挿入データ用C# class(`InvoiceData/GroupData/ItemData`)とサンプルデータを設計書へ追加 +- 2026-04-12 issue#58 範囲定義設計: コンポーネント定義範囲を「DefinedName明示指定 + 自動判定フォールバック」で定義し、検証/エラー条件を追加 +- 2026-04-12 issue#58 設計補強: 挿入元サイズ > 挿入先想定範囲(例: 3行を1行定義領域へ挿入)の書式保持ルール、`TemplateRangeOverflow` Warning、結合セル境界Errorを追記 +- 2026-04-12 issue#58 命名改善: 設計書タイトルを「Excelテンプレート対応」へ変更し、ファイル名を `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` へ更新 +- 2026-04-11 issue#58 可視化強化: Excelセル座標と一致するセルマトリクス表 + SVG図を設計書へ追加 +- 2026-04-07 issue#58 懸念深掘り: 実装前チェックリスト(変換契約/展開境界/罫線/性能)を設計書へ追加 +- 2026-04-07 issue#58 具体例拡張: セル値/挿入トリガ/罫線競合をMarkdownテーブルで設計書に追記 +- 2026-04-07 issue#58 罫線方針追加: 入れ子component時のborder優先順位・辺単位合成・競合Warning・検証ケースを設計へ追記 +- 2026-04-07 issue#58 設計具体化: 入れ子コンポーネント定義/シート表現/挿入表現をDSL例付きで追記(実装は未着手) +- 2026-04-07 issue#58 方針見直し: A/B案にC案を加えて比較し、初期採用はA案を維持。対象範囲外へグラフ作成機能を明記 +- 2026-04-07 issue#58 要件取得: `gh` 非依存で GitHub issue URL から本文を取得し、設計ドラフトを承認依頼版へ更新 +- 2026-04-07 issue#58 着手: 要件本文未取得のため調査レポート `reports/issue58-investigation-2026-04-07.md` を作成 +- 2026-04-07 issue#58 設計: 承認前ドラフト `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` を作成(要件確定待ち) + +## Issue #58 Remaining Tasks + +- 基準日: 2026-04-14 +- 現在位置: issue #58 完了 +- 残見積り: 0 tasks / 0 実装サイクル +- 注記: 下部の既存 `Task List` は旧来の全体タスク集計であり、issue #58 の残タスクはこの節を正として扱う +- 棚卸し結果: `Design/ExcelTemplate/ExcelTemplate_DetailDesign.md` と突合し、Phase 14 へ追加した `styleOverflow` trigger 対応と expression DSL互換 hardening も同サイクルで完了済み + +| Task ID | Title | Status | Phase | Dependencies | Exit Criteria | Estimate | +|---|---|---|---|---|---|---| +| R58-01 | 変換出力の最小契約を固定する | Done | 11 | 66a09b1, 1103fbb, fb24ba2 | XML/DSL の出力対象、issue 集約方針、fixture 形式をコード上で固定 | 0.5 cycle | +| R58-02 | `XmlTemplateSerializer` の workbook/component/sheet 出力を実装する | Done | 11 | R58-01 | debug XML が component/sheet/cell/use/repeat を表現できる | 1 cycle | +| R58-03 | `DslEmitter` の基本出力を実装する | Done | 11 | R58-01 | workbook/components/sheets/cells が DSL text へ変換される | 1 cycle | +| R58-04 | `DslEmitter` で `cell@formula` / `styleOverflow` / `direction=\"down\"` を反映する | Done | 11 | R58-03 | 設計どおりの契約が emitted DSL に反映される | 0.5 cycle | +| R58-05 | xlsx -> xml snapshot テストを追加する | Done | 11 | R58-02 | debug XML の snapshot が固定される | 0.5 cycle | +| R58-06 | xlsx -> dsl snapshot テストを追加する | Done | 11 | R58-03, R58-04 | DSL text の snapshot が固定される | 0.5 cycle | +| R58-07 | `ExcelTemplateConverter` と result/options を実装する | Done | 12 | R58-02, R58-03, R58-04 | `ConvertToDsl` / `ConvertToXmlTemplate` が `Text + Issues` を返す | 0.5 cycle | +| R58-08 | conversion-only API の issue 集約と integration test を追加する | Done | 12 | R58-07 | validator/resolver/parser の issues が conversion result に保持される | 0.5 cycle | +| R58-09 | `ExcelTemplateReportGenerator` facade を実装する | Done | 13 | R58-07, R58-08 | `GenerateFromExcelTemplate` が既存 `ReportGenerator` 経路を呼べる | 1 cycle | +| R58-10 | facade の happy-path integration test を追加する | Done | 13 | R58-09 | 基本帳票生成ケースが API 経由で通る | 0.5 cycle | +| R58-11 | use trigger で `styleOverflow` を受け取り emitted DSL へ反映する | Done | 14 | R58-09, R58-10 | `{{use:..., styleOverflow:edge}}` が `use@styleOverflow="edge"` として最終 DSL に残る | 0.5 cycle | +| R58-12 | Excel expression を DSL runtime 互換形へ揃える | Done | 14 | R58-09, R58-10 | Excel cell / trigger の expression が E2E で実行可能な DSL 互換形になる | 0.5 cycle | +| R58-13 | xlsx -> dsl -> final xlsx E2E を追加する | Done | 14 | R58-11, R58-12 | `GroupBlock` / `ItemRow` / `styleOverflow=edge` / `cell@formula` を含む E2E が通る | 1 cycle | +| R58-14 | negative E2E と最終記録を追加する | Done | 14 | R58-11, R58-12, R58-13 | merged violation / unsupported conditional formatting の negative case、reports/tasks/phases の最終同期が完了 | 1 cycle | - 2026-04-05 issue#16 設計: `Design/SheetReference/SheetReference_DetailDesign.md` を追加し、sheet repeat での動的シート間参照方式を定義 - 2026-04-05 issue#16 仕様化: `cell@value` の式評価結果が `=` 始まり文字列なら数式扱いとする仕様を DSL 設計書へ反映 - 2026-04-05 issue#16 実装: `LayoutEngine.EvaluateCellValue` を拡張し、式評価結果 `=...` を `Formula` として保持 @@ -228,6 +333,31 @@ Scope: ExcelReport開発 - issue #16 シート間参照 / issue #43 非同期api ## Additional Work +- 2026-04-13 issue #58 実装: `ExcelTemplateValidator` を追加し、`MergedCellBoundaryViolation` / `UnsupportedExcelTemplateFeature` / malformed trigger の診断を集約 +- 2026-04-13 issue #58 実装: `ExcelTemplateSheet.HasConditionalFormatting` と extractor の conditional formatting 検出を追加 +- 2026-04-13 issue #58 実装修正: `UseTriggerParser` の comma tokenization を top-level split へ修正し、`from:` 式内カンマの回帰を防止 +- 2026-04-13 issue #58 テスト: validator 4件 + trigger parser 1件 + extractor 1件を追加し、全体233件通過を確認 +- 2026-04-13 issue #58 記録: `reports/issue58-validator-and-trigger-hardening-2026-04-13.md` と `reports/issue58-validator-review-2026-04-13.md` を追加 +- 2026-04-13 issue #58 実装: `UseTriggerParser` / `ExcelTemplateUseTrigger` / `ExcelTemplateUseTriggerParseResult` を追加 +- 2026-04-13 issue #58 実装: `{{use:Header}}` と `{{use:ItemRow, from:@items, var:item}}` の最小文法を解析し、repeat direction を `down` で正規化 +- 2026-04-13 issue #58 テスト: `ExcelTemplateUseTriggerParserTests` を追加し、通常文字列 / simple use / repeat use / from-var 不整合を固定 +- 2026-04-13 issue #58 review: `gpt-5.4` / `high` review を再試行したが、network 制限で `codex review` が中断したため結果を report に記録 +- 2026-04-13 issue #58 記録: `reports/issue58-use-trigger-parser-2026-04-13.md` / `reports/issue58-use-trigger-parser-review-2026-04-13.md` を追加 +- 2026-04-13 issue #58 実装: `ExcelTemplateComponentRangeResolver` を追加し、`__component_range_` の明示範囲と candidate bbox 自動判定を実装 +- 2026-04-13 issue #58 実装: `IssueKind.InvalidComponentRange` / `IssueKind.EmptyComponentRange` を追加 +- 2026-04-13 issue #58 テスト: `ExcelTemplateComponentRangeResolverTests` を追加し、defined name優先 / bbox自動判定 / 空範囲Error / 別シート参照Error を固定 +- 2026-04-13 issue #58 review: `gpt-5.4` / `high` review を再試行したが、network 制限で `codex review` が中断したため結果を report に記録 +- 2026-04-13 issue #58 記録: `reports/issue58-component-range-resolver-2026-04-13.md` / `reports/issue58-component-range-resolver-review-2026-04-13.md` を追加 +- 2026-04-12 issue #58 実装: `cell@formula` / `use@styleOverflow` を XSD / AST / `ValidateDsl` / `LayoutEngine` へ追加 +- 2026-04-12 issue #58 実装: `styleOverflow=edge` を `LayoutEngine` post-expand で実装し、anchor 矩形 seed 書式の right/down/corner trailing edge copy に対応 +- 2026-04-12 issue #58 実装: `IssueKind.TemplateRangeOverflow` を追加し、ExcelTemplate 向け anchor overflow を Warning として記録 +- 2026-04-12 issue #58 テスト: parser/validation/runtime テストを追加し、`ExcelReportLib.Tests` 全体214件通過を確認 +- 2026-04-13 issue #58 テスト補強: `styleOverflow=edge` の down/corner ケースを `LayoutEngineTests` へ追加し、関連72件・全体216件通過を確認 +- 2026-04-12 issue #58 記録: `reports/issue58-dsl-contract-extension-2026-04-12.md` を作成 +- 2026-04-13 issue #58 review記録: `reports/issue58-dsl-contract-extension-review-2026-04-13.md` を作成 +- 2026-04-13 issue #58 実装継続: `ExcelTemplateExtractor` と `ExcelTemplateWorkbook/Sheet/Cell/Style/ComponentRange` を追加し、xlsx から sheet/cell/formula/defined name/merged cell を抽出可能にした +- 2026-04-13 issue #58 テスト追加: `ExcelTemplateExtractorTests` を追加し、対象2件 + 全体218件通過を確認 +- 2026-04-13 issue #58 記録: `reports/issue58-excel-template-extractor-2026-04-13.md` を作成 - 2026-04-05 issue #16: `sheet repeat` で増えるシート名を式で参照可能にするため、`cell@value` 式評価後の数式自動判定を実装 - 2026-04-05 issue #16: 設計書 `Design/SheetReference/SheetReference_DetailDesign.md` を追加 - 2026-04-05 issue #16 follow-up: `sheet repeat` の完全例(データモデル/DSL全文/展開結果)を設計書へ追記 @@ -295,6 +425,49 @@ Scope: ExcelReport開発 - issue #16 シート間参照 / issue #43 非同期api - 2026-03-19 ドキュメント運用: READMEからNuGet公開手順を削除し、`reports/nuget-publish-process-2026-03-19.md` に移管 +- 2026-04-12 issue #58 設計補足: `Invoice` の `use` セル書式は必須ではない旨を `ExcelTemplate_DetailDesign.md` 10.8.3 注記に明記 +- 2026-04-12 記録: `reports/issue58-invoice-use-style-optional-note-2026-04-12.md` を作成 +- 2026-04-12 issue #58 設計更新: SVG例を `3x3挿入先 + 中央use` / `3x4子component` に差し替え、書式overflow比較SVGを追加 +- 2026-04-12 issue #58 設計更新: `styleOverflow`(`none`/`edge`、既定`none`)を追加し、`A1:C1` / `A1:B1` の拡張挙動を明確化 +- 2026-04-12 記録: `reports/issue58-style-overflow-policy-2026-04-12.md` を作成 +- 2026-04-12 issue #58 修正: 10.10.1 に挿入元(C#展開後 GroupBlock インスタンス)SVGを復元し、既存出力図を 10.10.2 へ再配置 +- 2026-04-12 issue #58 修正: `ChildBlock/ヘッダー/なにかの値` の簡略例を廃止し、`GroupBlock/ItemRow` の正式フォーマットへ差し戻し +- 2026-04-12 記録: `reports/issue58-svg-format-restoration-2026-04-12.md` を作成 +- 2026-04-12 issue #58 視認性改善: 展開後図を 10.8 節へ集約(10.8.8/10.8.9)し、10.10.1 は参照節へ整理 +- 2026-04-12 issue #58 修正: 10.8.3 の破線境界を除去し、挿入先3x3図に `{{use:Header}}` を追加して出力イメージとの差異を縮小 +- 2026-04-12 記録: `reports/issue58-section-layout-and-target-svg-fix-2026-04-12.md` を作成 +- 2026-04-12 issue #58 方針調整: 10.8.10 は状態遷移図を持たず、状態整理テーブルのみで記載する方針へ変更 +- 2026-04-12 記録: `reports/issue58-state-table-only-adjustment-2026-04-12.md` を作成 +- 2026-04-12 issue #58 修正: 10.8.9 の出力SVGを更新し、`A1:F1` Header拡張 + `A3:E8` 子枠拡張が見える状態整理ケースへ差し替え +- 2026-04-12 issue #58 修正: 10.8.9/10.10補足を「先頭GroupBlock抜粋」注記へ更新し、図と説明の整合を修正 +- 2026-04-12 記録: `reports/issue58-output-svg-refresh-2026-04-12.md` を作成 +- 2026-04-12 issue #58 再修正: 10.8.9/10.8.10 の repeat 解釈を見直し、2件の `GroupBlock` を `B4:D7` と `B8:D9` へ連続配置、親フレームを `A3:E10` へ拡張する図と説明へ更新 +- 2026-04-12 記録: `reports/issue58-repeat-frame-aggregation-2026-04-12.md` を作成 +- 2026-04-12 issue #58 review: sub-agent(`gpt-5.3-codex` / `high`)で 10.8/10.9/10.10 を設計レビューし、`repeat` 時の `H` 定義、`GroupBlock` 有効幅、`styleOverflow=edge` の行方向、連続インスタンス境界罫線の未定義を指摘事項として整理 +- 2026-04-12 記録: `reports/issue58-subagent-design-review-2026-04-12.md` を作成 +- 2026-04-12 issue #58 設計修正: sub-agent 指摘を受け、`GroupBlock` 定義範囲を `A1:C3` に統一し、`repeat` 時の `H/W` 定義、`styleOverflow=edge` の上下左右、連続 instance 境界の trailing edge 優先ルールを設計へ追記 +- 2026-04-12 記録: `reports/issue58-design-fixes-after-subagent-review-2026-04-12.md` を作成 +- 2026-04-12 issue #58 re-review: sub-agent(`gpt-5.3-codex` / `high`)で更新後設計を再レビューし、High/Critical なし、残留は `styleOverflow=edge` の4方向検証不足と 10.9.4 テーブルの右方向偏りのみと確認 +- 2026-04-12 記録: `reports/issue58-subagent-rereview-2026-04-12.md` を作成 +- 2026-04-12 issue #58 follow-up: 再レビューの Low 指摘に対応し、10.9.4 を 右/左/下/上/角 の期待結果表へ拡張、11.5 に left/top/corner copy の検証ケースを追加 +- 2026-04-12 記録: `reports/issue58-low-findings-followup-2026-04-12.md` を作成 +- 2026-04-12 issue #58 review: sub-agent(`gpt-5.4` / `high`)で `f64deb4` をレビューし、`styleOverflow=edge` は現行モデル上 right/down trailing edge 限定に揃えるべきこと、overflow比較SVGの文脈分離が必要なことを指摘 +- 2026-04-12 issue #58 修正: `styleOverflow=edge` を right/down/right-down corner へ限定し、10.9.4/11.5 と overflow比較SVGを整合させた +- 2026-04-12 記録: `reports/issue58-gpt54-review-followup-2026-04-12.md` を作成 +- 2026-04-12 issue #58 方針確定: 数式セルは原則 `cell@formula` へ変換し、C# 側で Excel 関数計算をしない方針を設計へ反映 +- 2026-04-12 記録: `reports/issue58-formula-normalization-decision-2026-04-12.md` を作成 +- 2026-04-12 issue #58 合意反映: merged cell は矩形内完結のみ、条件付き書式は初版対象外、性能閾値は当面不問として 12章を更新 +- 2026-04-12 記録: `reports/issue58-pre-implementation-answers-2026-04-12.md` を作成 +- 2026-04-12 issue #58 合意反映: 大規模テンプレートの性能閾値は当面不問とし、12.6 の未解決質問をクローズ +- 2026-04-12 記録: `reports/issue58-performance-threshold-closed-2026-04-12.md` を作成 +- 2026-04-12 issue #58 実装方針策定: 既存 `ReportGenerator` 後段を再利用し、前段に `ExcelTemplate` 変換層を追加する実装順序・API方針・テスト戦略を 13章と実装方針レポートへ反映 +- 2026-04-12 記録: `reports/issue58-implementation-approach-2026-04-12.md` を作成 +- 2026-04-12 issue #58 review: sub-agent(`gpt-5.4` / `high`)で実装方針レビューを実施し、runtime schema 対象不足、`repeat@direction` 契約不一致、`styleOverflow=edge` 実装位置未固定、conversion API の診断不足を指摘として整理 +- 2026-04-12 issue #58 実装方針修正: runtime schema の更新対象、`direction=\"down\"` 明示、`LayoutEngine` post-expand での `styleOverflow=edge` 実装、conversion result + `Issues`、`ValidateDsl` 補完検証、legacy formula 回帰テストを方針へ反映 +- 2026-04-12 記録: `reports/issue58-implementation-approach-review-2026-04-12.md` を作成 +- 2026-04-12 引き継ぎ: 新しいチャットで issue #58 実装を再開できるよう、背景・決定事項・未解決事項・次アクションを整理した handover 文書を作成 +- 2026-04-12 記録: `reports/chat-handover-for-new-thread-20260412_153728.md` を作成 + ## Status Definitions - Done: 完了