@k2works/claude-code-booster 3.2.1 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/lib/assets/.claude/skills/analyzing-business/SKILL.md +2 -2
  2. package/lib/assets/.claude/skills/analyzing-inception-deck/SKILL.md +5 -5
  3. package/lib/assets/.claude/skills/analyzing-requirements/SKILL.md +2 -2
  4. package/lib/assets/.claude/skills/generating-slides/SKILL.md +7 -7
  5. package/lib/assets/docs/article/index.md +4 -1
  6. package/lib/assets/docs/article/practical-database-design/index.md +121 -0
  7. package/lib/assets/docs/article/practical-database-design/part1/chapter01.md +288 -0
  8. package/lib/assets/docs/article/practical-database-design/part1/chapter02.md +518 -0
  9. package/lib/assets/docs/article/practical-database-design/part1/chapter03.md +557 -0
  10. package/lib/assets/docs/article/practical-database-design/part2/chapter04.md +924 -0
  11. package/lib/assets/docs/article/practical-database-design/part2/chapter05.md +1627 -0
  12. package/lib/assets/docs/article/practical-database-design/part2/chapter06.md +2716 -0
  13. package/lib/assets/docs/article/practical-database-design/part2/chapter07.md +2082 -0
  14. package/lib/assets/docs/article/practical-database-design/part2/chapter08.md +2105 -0
  15. package/lib/assets/docs/article/practical-database-design/part2/chapter09.md +2031 -0
  16. package/lib/assets/docs/article/practical-database-design/part2/chapter10.md +1387 -0
  17. package/lib/assets/docs/article/practical-database-design/part2/chapter11.md +1677 -0
  18. package/lib/assets/docs/article/practical-database-design/part2/chapter12.md +1417 -0
  19. package/lib/assets/docs/article/practical-database-design/part2/chapter13.md +1434 -0
  20. package/lib/assets/docs/article/practical-database-design/part3/chapter14.md +667 -0
  21. package/lib/assets/docs/article/practical-database-design/part3/chapter15.md +1625 -0
  22. package/lib/assets/docs/article/practical-database-design/part3/chapter16.md +1915 -0
  23. package/lib/assets/docs/article/practical-database-design/part3/chapter17.md +1708 -0
  24. package/lib/assets/docs/article/practical-database-design/part3/chapter18.md +2095 -0
  25. package/lib/assets/docs/article/practical-database-design/part3/chapter19.md +1123 -0
  26. package/lib/assets/docs/article/practical-database-design/part3/chapter20.md +1031 -0
  27. package/lib/assets/docs/article/practical-database-design/part3/chapter21.md +1382 -0
  28. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter14-orm.md +991 -0
  29. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter15-orm.md +1300 -0
  30. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter16-orm.md +1166 -0
  31. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter17-orm.md +1584 -0
  32. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter18-orm.md +1183 -0
  33. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter19-orm.md +1016 -0
  34. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter20-orm.md +1753 -0
  35. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter21-orm.md +1447 -0
  36. package/lib/assets/docs/article/practical-database-design/part3-orm/chapter22-orm.md +1878 -0
  37. package/lib/assets/docs/article/practical-database-design/part4/chapter22.md +965 -0
  38. package/lib/assets/docs/article/practical-database-design/part4/chapter23.md +2069 -0
  39. package/lib/assets/docs/article/practical-database-design/part4/chapter24.md +2439 -0
  40. package/lib/assets/docs/article/practical-database-design/part4/chapter25.md +3661 -0
  41. package/lib/assets/docs/article/practical-database-design/part4/chapter26.md +2916 -0
  42. package/lib/assets/docs/article/practical-database-design/part4/chapter27.md +3105 -0
  43. package/lib/assets/docs/article/practical-database-design/part4/chapter28.md +2697 -0
  44. package/lib/assets/docs/article/practical-database-design/part4/chapter29.md +2544 -0
  45. package/lib/assets/docs/article/practical-database-design/part4/chapter30.md +2180 -0
  46. package/lib/assets/docs/article/practical-database-design/part4/chapter31.md +1192 -0
  47. package/lib/assets/docs/article/practical-database-design/part4/chapter32.md +2101 -0
  48. package/lib/assets/docs/article/practical-database-design/part5/chapter33.md +1032 -0
  49. package/lib/assets/docs/article/practical-database-design/part5/chapter34.md +1609 -0
  50. package/lib/assets/docs/article/practical-database-design/part5/chapter35.md +1453 -0
  51. package/lib/assets/docs/article/practical-database-design/part5/chapter36.md +1292 -0
  52. package/lib/assets/docs/article/practical-database-design/part5/chapter37.md +1470 -0
  53. package/lib/assets/docs/article/practical-database-design/part5/chapter38.md +1698 -0
  54. package/lib/assets/docs/article/practical-database-design/part5/chapter39.md +2334 -0
  55. package/lib/assets/docs/article/practical-database-design/study/study2-1.md +1693 -0
  56. package/lib/assets/docs/article/practical-database-design/study/study2-2.md +1347 -0
  57. package/lib/assets/docs/article/practical-database-design/study/study2-3.md +2044 -0
  58. package/lib/assets/docs/article/practical-database-design/study/study2-4.md +2229 -0
  59. package/lib/assets/docs/article/practical-database-design/study/study2-5.md +2418 -0
  60. package/lib/assets/docs/article/practical-database-design/study/study3-1.md +2205 -0
  61. package/lib/assets/docs/article/practical-database-design/study/study3-2.md +2221 -0
  62. package/lib/assets/docs/article/practical-database-design/study/study3-3.md +2253 -0
  63. package/lib/assets/docs/article/practical-database-design/study/study3-4.md +2106 -0
  64. package/lib/assets/docs/article/practical-database-design/study/study3-5.md +2507 -0
  65. package/lib/assets/docs/article/practical-database-design/study/study4-1.md +2587 -0
  66. package/lib/assets/docs/article/practical-database-design/study/study4-2.md +2075 -0
  67. package/lib/assets/docs/article/practical-database-design/study/study4-3.md +1805 -0
  68. package/lib/assets/docs/article/practical-database-design/study/study4-4.md +1895 -0
  69. package/lib/assets/docs/article/practical-database-design/study/study4-5.md +2878 -0
  70. package/package.json +1 -1
@@ -0,0 +1,2075 @@
1
+ # 実践データベース設計:生産管理システム 研究 2 - JavaFX デスクトップアプリケーションの実装
2
+
3
+ ## はじめに
4
+
5
+ 本研究では、API サーバー構成(第32章)やモノリスサービス(研究 1)とは異なるアプローチとして、**JavaFX** によるデスクトップアプリケーションを実装します。FXML による宣言的 UI 定義と、データバインディングによるリアクティブな画面更新を活用した、業務アプリケーションを構築します。
6
+
7
+ 研究 1 で構築したヘキサゴナルアーキテクチャ(ドメイン層・アプリケーション層)はそのまま共有し、**Input Adapter として JavaFX の Controller/ViewModel 層のみを追加**します。
8
+
9
+ ---
10
+
11
+ ## 第38章:JavaFX デスクトップアプリケーションの基礎
12
+
13
+ ### 38.1 JavaFX とは
14
+
15
+ JavaFX は Java のリッチクライアントプラットフォームです。Swing の後継として位置づけられ、モダンな UI 構築が可能です。
16
+
17
+ ```plantuml
18
+ @startuml javafx_architecture
19
+ !define RECTANGLE class
20
+
21
+ skinparam backgroundColor #FEFEFE
22
+
23
+ package "JavaFX Architecture (生産管理システム)" {
24
+
25
+ package "View Layer" {
26
+ RECTANGLE "FXML Files\n(宣言的 UI 定義)" as fxml {
27
+ - MainView.fxml
28
+ - ItemView.fxml
29
+ - PurchaseOrderView.fxml
30
+ }
31
+
32
+ RECTANGLE "CSS Stylesheets\n(スタイル定義)" as css {
33
+ - application.css
34
+ - theme-light.css
35
+ - theme-dark.css
36
+ }
37
+ }
38
+
39
+ package "Controller/ViewModel Layer" {
40
+ RECTANGLE "Controllers\n(画面制御)" as controller {
41
+ - MainController
42
+ - ItemController
43
+ - PurchaseOrderController
44
+ }
45
+
46
+ RECTANGLE "ViewModels\n(画面状態管理)" as viewmodel {
47
+ - ItemViewModel
48
+ - BomViewModel
49
+ - PurchaseOrderViewModel
50
+ }
51
+ }
52
+
53
+ package "Application Core" {
54
+ RECTANGLE "Use Cases\n(ビジネスロジック)" as usecase {
55
+ - ItemUseCase
56
+ - BomService
57
+ - PurchaseOrderUseCase
58
+ }
59
+ }
60
+ }
61
+
62
+ fxml --> controller : "fx:controller"
63
+ css --> fxml : "stylesheets"
64
+ controller --> viewmodel : "データバインド"
65
+ viewmodel --> usecase : "Input Port"
66
+
67
+ note bottom of fxml
68
+ Scene Builder で
69
+ 視覚的に編集可能
70
+ end note
71
+
72
+ note right of viewmodel
73
+ ObservableList,
74
+ Property による
75
+ 双方向バインディング
76
+ end note
77
+
78
+ @enduml
79
+ ```
80
+
81
+ **Web アプリケーションとの比較:**
82
+
83
+ | 特徴 | Web アプリ(REST API) | JavaFX デスクトップ |
84
+ |------|----------------------|-------------------|
85
+ | 配置 | サーバー + ブラウザ | ローカルインストール |
86
+ | オフライン | 不可 | 可能(ローカル DB) |
87
+ | レスポンス | ネットワーク依存 | 高速 |
88
+ | UI 自由度 | HTML/CSS 制約 | ネイティブ制御 |
89
+ | 印刷機能 | 制限あり | 高機能 |
90
+ | 更新配布 | 自動 | 手動/自動更新 |
91
+
92
+ ---
93
+
94
+ ### 38.2 MVVM パターンの採用
95
+
96
+ JavaFX では、**MVVM(Model-View-ViewModel)** パターンを採用し、UI とビジネスロジックを分離します。
97
+
98
+ ```plantuml
99
+ @startuml mvvm_pattern
100
+ !define RECTANGLE class
101
+
102
+ skinparam backgroundColor #FEFEFE
103
+
104
+ package "MVVM Pattern" {
105
+
106
+ RECTANGLE "View\n(FXML + Controller)" as view {
107
+ + TableView<ItemRow>
108
+ + TextField
109
+ + Button
110
+ --
111
+ initialize()
112
+ onSaveClick()
113
+ }
114
+
115
+ RECTANGLE "ViewModel\n(画面状態)" as vm {
116
+ + ObservableList<ItemRow> items
117
+ + StringProperty searchKeyword
118
+ + BooleanProperty loading
119
+ --
120
+ search()
121
+ save()
122
+ delete()
123
+ }
124
+
125
+ RECTANGLE "Model\n(Domain + UseCase)" as model {
126
+ + Item
127
+ + ItemUseCase
128
+ + ItemRepository
129
+ --
130
+ findByCode()
131
+ save()
132
+ }
133
+ }
134
+
135
+ view --> vm : "Data Binding\n(双方向)"
136
+ vm --> model : "UseCase 呼び出し"
137
+ model --> vm : "結果を Property に反映"
138
+ vm --> view : "自動 UI 更新"
139
+
140
+ note right of view
141
+ FXML で宣言的に定義
142
+ Controller で
143
+ イベントハンドリング
144
+ end note
145
+
146
+ note right of vm
147
+ JavaFX Property で
148
+ リアクティブな
149
+ 状態管理
150
+ end note
151
+
152
+ note right of model
153
+ API版と共有
154
+ 変更不要
155
+ end note
156
+
157
+ @enduml
158
+ ```
159
+
160
+ **各層の責務:**
161
+
162
+ | 層 | 責務 | JavaFX での実装 |
163
+ |----|------|----------------|
164
+ | **View** | UI 表示・ユーザー入力 | FXML + Controller |
165
+ | **ViewModel** | 画面状態管理・変換 | Property, ObservableList |
166
+ | **Model** | ビジネスロジック | UseCase, Repository |
167
+
168
+ ---
169
+
170
+ ### 38.3 ヘキサゴナルアーキテクチャとの統合
171
+
172
+ JavaFX を導入しても、既存のヘキサゴナルアーキテクチャ(ドメイン層・アプリケーション層)はそのまま共有し、**Input Adapter として JavaFX の Controller/ViewModel 層のみを追加**します。
173
+
174
+ ```plantuml
175
+ @startuml hexagonal_javafx
176
+ !define RECTANGLE class
177
+
178
+ package "Hexagonal Architecture (JavaFX版)" {
179
+
180
+ RECTANGLE "Application Core\n(Domain + Use Cases)" as core {
181
+ - Item (品目)
182
+ - Bom (部品構成表)
183
+ - PurchaseOrder (発注)
184
+ - Stock (在庫)
185
+ - ItemUseCase
186
+ - BomService
187
+ - PurchaseOrderUseCase
188
+ }
189
+
190
+ RECTANGLE "Input Adapters\n(Driving Side)" as input {
191
+ - REST Controller(API版)
192
+ - JavaFX Controller(新規追加)
193
+ - ViewModel
194
+ - FXML View
195
+ }
196
+
197
+ RECTANGLE "Output Adapters\n(Driven Side)" as output {
198
+ - MyBatis Repository
199
+ - Database Access
200
+ - Entity Mapping
201
+ }
202
+ }
203
+
204
+ input --> core : "Input Ports\n(Use Cases)"
205
+ core --> output : "Output Ports\n(Repository Interfaces)"
206
+
207
+ note top of core
208
+ 既存のビジネスロジック
209
+ REST API 版と完全に共有
210
+ JavaFX 固有のコードは含まない
211
+ end note
212
+
213
+ note left of input
214
+ JavaFX Controller を
215
+ Input Adapter として追加
216
+ 既存の REST API と共存可能
217
+ end note
218
+
219
+ note right of output
220
+ 既存の Repository を
221
+ そのまま使用
222
+ 変更不要
223
+ end note
224
+
225
+ @enduml
226
+ ```
227
+
228
+ **JavaFX でもヘキサゴナルアーキテクチャを維持する理由:**
229
+
230
+ 1. **再利用性**: 既存の UseCase/Repository をそのまま活用
231
+ 2. **並行運用**: REST API と JavaFX の両方を提供可能
232
+ 3. **テスト容易性**: ドメインロジックは UI フレームワークに依存しない
233
+ 4. **移行容易性**: 段階的に Web からデスクトップへ移行可能
234
+
235
+ ---
236
+
237
+ ### 38.4 ディレクトリ構成
238
+
239
+ 既存の構成に `infrastructure/in/javafx/` を追加します。
240
+
241
+ ```
242
+ src/main/java/com/example/production/
243
+ ├── domain/ # ドメイン層(API版と共通)
244
+ │ ├── model/
245
+ │ │ ├── item/
246
+ │ │ ├── bom/
247
+ │ │ ├── purchase/
248
+ │ │ └── inventory/
249
+ │ └── exception/
250
+
251
+ ├── application/ # アプリケーション層(API版と共通)
252
+ │ ├── port/
253
+ │ │ ├── in/ # Input Port(ユースケース)
254
+ │ │ └── out/ # Output Port(リポジトリ)
255
+ │ └── service/
256
+
257
+ ├── infrastructure/
258
+ │ ├── out/
259
+ │ │ └── persistence/ # Output Adapter(DB実装)- 既存
260
+ │ │ ├── mapper/
261
+ │ │ └── repository/
262
+ │ ├── in/
263
+ │ │ ├── rest/ # Input Adapter(REST実装)- 既存
264
+ │ │ │ ├── controller/
265
+ │ │ │ └── dto/
266
+ │ │ └── javafx/ # Input Adapter(JavaFX実装)- 新規追加
267
+ │ │ ├── controller/ # FXML Controller
268
+ │ │ ├── viewmodel/ # ViewModel
269
+ │ │ ├── view/ # 画面表示用の行モデル
270
+ │ │ ├── dialog/ # ダイアログ
271
+ │ │ ├── util/ # ユーティリティ
272
+ │ │ └── config/ # JavaFX 設定
273
+
274
+ └── Application.java # Spring Boot + JavaFX 起動クラス
275
+
276
+ src/main/resources/
277
+ ├── fxml/ # FXML ファイル
278
+ │ ├── main.fxml
279
+ │ ├── item/
280
+ │ │ ├── item-list.fxml
281
+ │ │ └── item-edit.fxml
282
+ │ ├── bom/
283
+ │ │ ├── bom-tree.fxml
284
+ │ │ └── where-used.fxml
285
+ │ ├── purchase/
286
+ │ │ ├── order-list.fxml
287
+ │ │ └── order-entry.fxml
288
+ │ └── common/
289
+ │ ├── login.fxml
290
+ │ └── error-dialog.fxml
291
+
292
+ ├── css/ # スタイルシート
293
+ │ ├── application.css
294
+ │ └── theme/
295
+
296
+ ├── images/ # 画像リソース
297
+
298
+ └── reports/ # JasperReports テンプレート
299
+ ├── purchase-order.jrxml
300
+ └── mrp-result.jrxml
301
+ ```
302
+
303
+ ---
304
+
305
+ ### 38.5 技術スタックの追加
306
+
307
+ <details>
308
+ <summary>build.gradle.kts(差分)</summary>
309
+
310
+ ```kotlin
311
+ plugins {
312
+ // 既存のプラグイン...
313
+ id("org.openjfx.javafxplugin") version "0.1.0" // 追加
314
+ }
315
+
316
+ // JavaFX 設定
317
+ javafx {
318
+ version = "21"
319
+ modules = listOf(
320
+ "javafx.controls",
321
+ "javafx.fxml",
322
+ "javafx.graphics",
323
+ "javafx.swing" // JasperReports 連携用
324
+ )
325
+ }
326
+
327
+ dependencies {
328
+ // 既存の依存関係(Spring Boot, MyBatis, PostgreSQL等)はそのまま
329
+
330
+ // JavaFX 関連を追加
331
+ implementation("org.controlsfx:controlsfx:11.2.0") // 拡張コントロール
332
+ implementation("com.dlsc.formsfx:formsfx-core:11.6.0") // フォーム生成
333
+ implementation("org.kordamp.ikonli:ikonli-javafx:12.3.1") // アイコン
334
+ implementation("org.kordamp.ikonli:ikonli-fontawesome5-pack:12.3.1")
335
+
336
+ // JasperReports(帳票出力)
337
+ implementation("net.sf.jasperreports:jasperreports:6.20.6")
338
+
339
+ // Excel 出力
340
+ implementation("org.apache.poi:poi-ooxml:5.2.5")
341
+
342
+ // TestFX(UI テスト)
343
+ testImplementation("org.testfx:testfx-core:4.0.18")
344
+ testImplementation("org.testfx:testfx-junit5:4.0.18")
345
+ }
346
+ ```
347
+
348
+ </details>
349
+
350
+ **追加パッケージの説明:**
351
+
352
+ | パッケージ | 用途 |
353
+ |-----------|------|
354
+ | javafx.controls | 標準 UI コントロール |
355
+ | javafx.fxml | FXML パーサー |
356
+ | ControlsFX | 拡張コントロール(SearchableComboBox等) |
357
+ | Ikonli | アイコンフォント |
358
+ | JasperReports | 帳票出力 |
359
+ | Apache POI | Excel 出力 |
360
+ | TestFX | UI 自動テスト |
361
+
362
+ ---
363
+
364
+ ### 46.6 Spring Boot + JavaFX 統合
365
+
366
+ <details>
367
+ <summary>JavaFxApplication.java</summary>
368
+
369
+ ```java
370
+ package com.example.production.infrastructure.in.javafx;
371
+
372
+ import javafx.application.Application;
373
+ import javafx.application.Platform;
374
+ import javafx.stage.Stage;
375
+ import org.springframework.boot.builder.SpringApplicationBuilder;
376
+ import org.springframework.context.ConfigurableApplicationContext;
377
+
378
+ /**
379
+ * JavaFX アプリケーションのエントリーポイント
380
+ * Spring Boot コンテキストと JavaFX を統合
381
+ */
382
+ public class JavaFxApplication extends Application {
383
+
384
+ private ConfigurableApplicationContext springContext;
385
+
386
+ @Override
387
+ public void init() {
388
+ springContext = new SpringApplicationBuilder(ProductionApplication.class).run();
389
+ }
390
+
391
+ @Override
392
+ public void start(Stage primaryStage) {
393
+ StageManager stageManager = springContext.getBean(StageManager.class);
394
+ stageManager.setPrimaryStage(primaryStage);
395
+ stageManager.switchScene(FxmlView.MAIN);
396
+ }
397
+
398
+ @Override
399
+ public void stop() {
400
+ springContext.close();
401
+ Platform.exit();
402
+ }
403
+ }
404
+ ```
405
+
406
+ </details>
407
+
408
+ <details>
409
+ <summary>StageManager.java</summary>
410
+
411
+ ```java
412
+ package com.example.production.infrastructure.in.javafx.config;
413
+
414
+ import javafx.fxml.FXMLLoader;
415
+ import javafx.scene.Parent;
416
+ import javafx.scene.Scene;
417
+ import javafx.stage.Stage;
418
+ import org.springframework.context.ApplicationContext;
419
+ import org.springframework.stereotype.Component;
420
+
421
+ import java.io.IOException;
422
+ import java.util.Objects;
423
+
424
+ /**
425
+ * JavaFX Stage/Scene の管理
426
+ */
427
+ @Component
428
+ public class StageManager {
429
+
430
+ private final ApplicationContext applicationContext;
431
+ private Stage primaryStage;
432
+
433
+ public StageManager(ApplicationContext applicationContext) {
434
+ this.applicationContext = applicationContext;
435
+ }
436
+
437
+ public void setPrimaryStage(Stage primaryStage) {
438
+ this.primaryStage = primaryStage;
439
+ }
440
+
441
+ public void switchScene(FxmlView view) {
442
+ Parent root = loadView(view.getFxmlPath());
443
+ Scene scene = new Scene(root);
444
+
445
+ scene.getStylesheets().add(
446
+ Objects.requireNonNull(
447
+ getClass().getResource("/css/application.css")
448
+ ).toExternalForm()
449
+ );
450
+
451
+ primaryStage.setTitle(view.getTitle());
452
+ primaryStage.setScene(scene);
453
+ primaryStage.centerOnScreen();
454
+
455
+ if (!primaryStage.isShowing()) {
456
+ primaryStage.show();
457
+ }
458
+ }
459
+
460
+ private Parent loadView(String fxmlPath) {
461
+ try {
462
+ FXMLLoader loader = new FXMLLoader(getClass().getResource(fxmlPath));
463
+ loader.setControllerFactory(applicationContext::getBean);
464
+ return loader.load();
465
+ } catch (IOException e) {
466
+ throw new RuntimeException("FXML ロードエラー: " + fxmlPath, e);
467
+ }
468
+ }
469
+
470
+ public ApplicationContext getApplicationContext() {
471
+ return applicationContext;
472
+ }
473
+ }
474
+ ```
475
+
476
+ </details>
477
+
478
+ <details>
479
+ <summary>FxmlView.java(画面定義)</summary>
480
+
481
+ ```java
482
+ package com.example.production.infrastructure.in.javafx.config;
483
+
484
+ public enum FxmlView {
485
+
486
+ MAIN("/fxml/main.fxml", "生産管理システム"),
487
+ ITEM_LIST("/fxml/item/item-list.fxml", "品目マスタ"),
488
+ ITEM_EDIT("/fxml/item/item-edit.fxml", "品目編集"),
489
+ BOM_TREE("/fxml/bom/bom-tree.fxml", "BOM展開"),
490
+ WHERE_USED("/fxml/bom/where-used.fxml", "使用先照会"),
491
+ ORDER_LIST("/fxml/purchase/order-list.fxml", "発注一覧"),
492
+ ORDER_ENTRY("/fxml/purchase/order-entry.fxml", "発注入力"),
493
+ STOCK_LIST("/fxml/inventory/stock-list.fxml", "在庫照会"),
494
+ MRP_EXECUTION("/fxml/mrp/mrp-execution.fxml", "MRP実行");
495
+
496
+ private final String fxmlPath;
497
+ private final String title;
498
+
499
+ FxmlView(String fxmlPath, String title) {
500
+ this.fxmlPath = fxmlPath;
501
+ this.title = title;
502
+ }
503
+
504
+ public String getFxmlPath() { return fxmlPath; }
505
+ public String getTitle() { return title; }
506
+ }
507
+ ```
508
+
509
+ </details>
510
+
511
+ ---
512
+
513
+ ### 46.7 JavaFX Property の活用
514
+
515
+ JavaFX の Property 機能を使って、UI とデータの双方向バインディングを実現します。
516
+
517
+ <details>
518
+ <summary>ItemRow.java(View 用データクラス)</summary>
519
+
520
+ ```java
521
+ package com.example.production.infrastructure.in.javafx.view;
522
+
523
+ import javafx.beans.property.*;
524
+ import java.math.BigDecimal;
525
+
526
+ /**
527
+ * 品目マスタ画面用の行モデル
528
+ */
529
+ public class ItemRow {
530
+
531
+ private final StringProperty itemCode = new SimpleStringProperty();
532
+ private final StringProperty itemName = new SimpleStringProperty();
533
+ private final StringProperty categoryName = new SimpleStringProperty();
534
+ private final IntegerProperty leadTime = new SimpleIntegerProperty();
535
+ private final IntegerProperty safetyStock = new SimpleIntegerProperty();
536
+ private final StringProperty unitCode = new SimpleStringProperty();
537
+
538
+ // Property アクセサ
539
+ public StringProperty itemCodeProperty() { return itemCode; }
540
+ public StringProperty itemNameProperty() { return itemName; }
541
+ public StringProperty categoryNameProperty() { return categoryName; }
542
+ public IntegerProperty leadTimeProperty() { return leadTime; }
543
+ public IntegerProperty safetyStockProperty() { return safetyStock; }
544
+ public StringProperty unitCodeProperty() { return unitCode; }
545
+
546
+ // Getter/Setter
547
+ public String getItemCode() { return itemCode.get(); }
548
+ public void setItemCode(String value) { itemCode.set(value); }
549
+
550
+ public String getItemName() { return itemName.get(); }
551
+ public void setItemName(String value) { itemName.set(value); }
552
+
553
+ public String getCategoryName() { return categoryName.get(); }
554
+ public void setCategoryName(String value) { categoryName.set(value); }
555
+
556
+ public int getLeadTime() { return leadTime.get(); }
557
+ public void setLeadTime(int value) { leadTime.set(value); }
558
+
559
+ public int getSafetyStock() { return safetyStock.get(); }
560
+ public void setSafetyStock(int value) { safetyStock.set(value); }
561
+ }
562
+ ```
563
+
564
+ </details>
565
+
566
+ <details>
567
+ <summary>ItemViewModel.java</summary>
568
+
569
+ ```java
570
+ package com.example.production.infrastructure.in.javafx.viewmodel;
571
+
572
+ import com.example.production.application.port.in.ItemUseCase;
573
+ import com.example.production.domain.model.item.Item;
574
+ import com.example.production.domain.model.item.ItemCategory;
575
+ import com.example.production.infrastructure.in.javafx.view.ItemRow;
576
+ import javafx.beans.property.*;
577
+ import javafx.collections.FXCollections;
578
+ import javafx.collections.ObservableList;
579
+ import org.springframework.stereotype.Component;
580
+
581
+ import java.util.List;
582
+
583
+ @Component
584
+ public class ItemViewModel {
585
+
586
+ private final ItemUseCase itemUseCase;
587
+
588
+ private final ObservableList<ItemRow> items = FXCollections.observableArrayList();
589
+ private final ObjectProperty<ItemRow> selectedItem = new SimpleObjectProperty<>();
590
+ private final StringProperty searchKeyword = new SimpleStringProperty("");
591
+ private final ObjectProperty<ItemCategory> filterCategory = new SimpleObjectProperty<>();
592
+ private final BooleanProperty loading = new SimpleBooleanProperty(false);
593
+ private final StringProperty errorMessage = new SimpleStringProperty();
594
+
595
+ public ItemViewModel(ItemUseCase itemUseCase) {
596
+ this.itemUseCase = itemUseCase;
597
+ }
598
+
599
+ public void search() {
600
+ loading.set(true);
601
+ errorMessage.set(null);
602
+
603
+ try {
604
+ List<Item> result;
605
+ if (filterCategory.get() != null) {
606
+ result = itemUseCase.getItemsByCategory(filterCategory.get());
607
+ } else if (!searchKeyword.get().isBlank()) {
608
+ result = itemUseCase.searchByKeyword(searchKeyword.get());
609
+ } else {
610
+ result = itemUseCase.getAllItems();
611
+ }
612
+
613
+ items.clear();
614
+ result.forEach(item -> items.add(toRow(item)));
615
+ } catch (Exception e) {
616
+ errorMessage.set("検索エラー: " + e.getMessage());
617
+ } finally {
618
+ loading.set(false);
619
+ }
620
+ }
621
+
622
+ public void delete(String itemCode) {
623
+ loading.set(true);
624
+ try {
625
+ itemUseCase.deleteItem(itemCode);
626
+ items.removeIf(row -> row.getItemCode().equals(itemCode));
627
+ } catch (Exception e) {
628
+ errorMessage.set("削除エラー: " + e.getMessage());
629
+ throw e;
630
+ } finally {
631
+ loading.set(false);
632
+ }
633
+ }
634
+
635
+ public ObservableList<ItemRow> getItems() { return items; }
636
+ public ObjectProperty<ItemRow> selectedItemProperty() { return selectedItem; }
637
+ public StringProperty searchKeywordProperty() { return searchKeyword; }
638
+ public ObjectProperty<ItemCategory> filterCategoryProperty() { return filterCategory; }
639
+ public BooleanProperty loadingProperty() { return loading; }
640
+ public StringProperty errorMessageProperty() { return errorMessage; }
641
+
642
+ private ItemRow toRow(Item item) {
643
+ ItemRow row = new ItemRow();
644
+ row.setItemCode(item.getItemCode());
645
+ row.setItemName(item.getItemName());
646
+ row.setCategoryName(item.getCategory() != null ? item.getCategory().name() : "");
647
+ row.setLeadTime(item.getLeadTime() != null ? item.getLeadTime() : 0);
648
+ row.setSafetyStock(item.getSafetyStock() != null ? item.getSafetyStock() : 0);
649
+ return row;
650
+ }
651
+ }
652
+ ```
653
+
654
+ </details>
655
+
656
+ ---
657
+
658
+ ## 第39章:マスタの実装
659
+
660
+ ### 39.1 品目マスタ画面の設計
661
+
662
+ ```plantuml
663
+ @startuml item_master_screen
664
+
665
+ package "品目マスタ画面構成" {
666
+
667
+ class "ItemListController\n(一覧画面)" as list {
668
+ + TableView<ItemRow>
669
+ + TextField (検索)
670
+ + ComboBox (区分フィルタ)
671
+ + Button (新規/編集/削除)
672
+ --
673
+ initialize()
674
+ onSearch()
675
+ onNew()
676
+ onEdit()
677
+ onDelete()
678
+ }
679
+
680
+ class "ItemEditController\n(編集画面)" as edit {
681
+ + TextField (コード/名称)
682
+ + ComboBox (品目区分)
683
+ + TextField (リードタイム/安全在庫)
684
+ --
685
+ initialize()
686
+ onSave()
687
+ onCancel()
688
+ }
689
+
690
+ class "ItemViewModel\n(画面状態)" as vm {
691
+ + ObservableList<ItemRow>
692
+ + selectedItem
693
+ + searchKeyword
694
+ + filterCategory
695
+ --
696
+ search()
697
+ create()
698
+ update()
699
+ delete()
700
+ }
701
+
702
+ class "ItemUseCase\n(ビジネスロジック)" as usecase {
703
+ + findAll()
704
+ + findByCode()
705
+ + create()
706
+ + update()
707
+ + delete()
708
+ }
709
+ }
710
+
711
+ list --> vm : "バインド"
712
+ edit --> vm : "バインド"
713
+ vm --> usecase : "Input Port"
714
+
715
+ @enduml
716
+ ```
717
+
718
+ ### 39.2 品目マスタ一覧画面の TDD 実装
719
+
720
+ #### Red: 失敗するテストを書く
721
+
722
+ <details>
723
+ <summary>ItemListControllerTest.java</summary>
724
+
725
+ ```java
726
+ @ExtendWith({ApplicationExtension.class, MockitoExtension.class})
727
+ @DisplayName("品目マスタ一覧画面")
728
+ class ItemListControllerTest {
729
+
730
+ @Mock
731
+ private ItemUseCase itemUseCase;
732
+
733
+ private ItemViewModel viewModel;
734
+
735
+ @Start
736
+ void start(Stage stage) throws Exception {
737
+ viewModel = new ItemViewModel(itemUseCase);
738
+ var controller = new ItemListController(viewModel);
739
+
740
+ var loader = new FXMLLoader(getClass().getResource("/fxml/item/item-list.fxml"));
741
+ loader.setController(controller);
742
+ stage.setScene(new Scene(loader.load()));
743
+ stage.show();
744
+ }
745
+
746
+ @Test
747
+ @DisplayName("品目一覧がテーブルに表示される")
748
+ void shouldDisplayItemsInTable(FxRobot robot) {
749
+ // Arrange
750
+ when(itemUseCase.getAllItems()).thenReturn(List.of(
751
+ createItem("PROD-001", "製品A", ItemCategory.PRODUCT),
752
+ createItem("PART-001", "部品B", ItemCategory.PART)
753
+ ));
754
+
755
+ // Act
756
+ robot.interact(() -> viewModel.search());
757
+
758
+ // Assert
759
+ TableView<ItemRow> table = robot.lookup("#itemTable").queryTableView();
760
+ assertThat(table.getItems()).hasSize(2);
761
+ assertThat(table.getItems().get(0).getItemCode()).isEqualTo("PROD-001");
762
+ }
763
+
764
+ @Test
765
+ @DisplayName("品目区分でフィルタリングできる")
766
+ void shouldFilterByCategory(FxRobot robot) {
767
+ when(itemUseCase.getItemsByCategory(ItemCategory.PRODUCT)).thenReturn(List.of(
768
+ createItem("PROD-001", "製品A", ItemCategory.PRODUCT)
769
+ ));
770
+
771
+ robot.clickOn("#categoryComboBox").clickOn("製品");
772
+ robot.clickOn("#searchButton");
773
+
774
+ TableView<ItemRow> table = robot.lookup("#itemTable").queryTableView();
775
+ assertThat(table.getItems()).hasSize(1);
776
+ }
777
+
778
+ @Test
779
+ @DisplayName("キーワードで品目を検索できる")
780
+ void shouldSearchItemsByKeyword(FxRobot robot) {
781
+ when(itemUseCase.searchByKeyword("製品")).thenReturn(List.of(
782
+ createItem("PROD-001", "製品A", ItemCategory.PRODUCT)
783
+ ));
784
+
785
+ robot.clickOn("#searchField").write("製品").type(KeyCode.ENTER);
786
+
787
+ TableView<ItemRow> table = robot.lookup("#itemTable").queryTableView();
788
+ assertThat(table.getItems()).hasSize(1);
789
+ }
790
+
791
+ private Item createItem(String code, String name, ItemCategory category) {
792
+ return Item.builder()
793
+ .itemCode(code)
794
+ .itemName(name)
795
+ .category(category)
796
+ .effectiveDate(LocalDate.now())
797
+ .build();
798
+ }
799
+ }
800
+ ```
801
+
802
+ </details>
803
+
804
+ #### Green: Controller の実装
805
+
806
+ <details>
807
+ <summary>ItemListController.java</summary>
808
+
809
+ ```java
810
+ package com.example.production.infrastructure.in.javafx.controller;
811
+
812
+ import com.example.production.domain.model.item.ItemCategory;
813
+ import com.example.production.infrastructure.in.javafx.util.AlertHelper;
814
+ import com.example.production.infrastructure.in.javafx.view.ItemRow;
815
+ import com.example.production.infrastructure.in.javafx.viewmodel.ItemViewModel;
816
+ import javafx.fxml.FXML;
817
+ import javafx.fxml.Initializable;
818
+ import javafx.scene.control.*;
819
+ import javafx.scene.control.cell.PropertyValueFactory;
820
+ import org.springframework.stereotype.Component;
821
+
822
+ import java.net.URL;
823
+ import java.util.ResourceBundle;
824
+
825
+ @Component
826
+ public class ItemListController implements Initializable {
827
+
828
+ private final ItemViewModel viewModel;
829
+
830
+ @FXML private TextField searchField;
831
+ @FXML private ComboBox<ItemCategory> categoryComboBox;
832
+ @FXML private TableView<ItemRow> itemTable;
833
+ @FXML private TableColumn<ItemRow, String> codeColumn;
834
+ @FXML private TableColumn<ItemRow, String> nameColumn;
835
+ @FXML private TableColumn<ItemRow, String> categoryColumn;
836
+ @FXML private TableColumn<ItemRow, Integer> leadTimeColumn;
837
+ @FXML private TableColumn<ItemRow, Integer> safetyStockColumn;
838
+ @FXML private Button editButton;
839
+ @FXML private Button deleteButton;
840
+ @FXML private Label recordCount;
841
+ @FXML private ProgressIndicator loadingIndicator;
842
+
843
+ public ItemListController(ItemViewModel viewModel) {
844
+ this.viewModel = viewModel;
845
+ }
846
+
847
+ @Override
848
+ public void initialize(URL url, ResourceBundle rb) {
849
+ // カテゴリコンボボックスの設定
850
+ categoryComboBox.getItems().add(null); // 全て
851
+ categoryComboBox.getItems().addAll(ItemCategory.values());
852
+ categoryComboBox.valueProperty().bindBidirectional(viewModel.filterCategoryProperty());
853
+
854
+ // テーブルカラムの設定
855
+ codeColumn.setCellValueFactory(new PropertyValueFactory<>("itemCode"));
856
+ nameColumn.setCellValueFactory(new PropertyValueFactory<>("itemName"));
857
+ categoryColumn.setCellValueFactory(new PropertyValueFactory<>("categoryName"));
858
+ leadTimeColumn.setCellValueFactory(new PropertyValueFactory<>("leadTime"));
859
+ safetyStockColumn.setCellValueFactory(new PropertyValueFactory<>("safetyStock"));
860
+
861
+ // テーブルとViewModelのバインド
862
+ itemTable.setItems(viewModel.getItems());
863
+ viewModel.selectedItemProperty().bind(itemTable.getSelectionModel().selectedItemProperty());
864
+
865
+ // ボタンの有効/無効制御
866
+ editButton.disableProperty().bind(
867
+ itemTable.getSelectionModel().selectedItemProperty().isNull()
868
+ );
869
+ deleteButton.disableProperty().bind(
870
+ itemTable.getSelectionModel().selectedItemProperty().isNull()
871
+ );
872
+
873
+ // ローディングインジケーター
874
+ loadingIndicator.visibleProperty().bind(viewModel.loadingProperty());
875
+
876
+ // 検索フィールドのバインド
877
+ searchField.textProperty().bindBidirectional(viewModel.searchKeywordProperty());
878
+
879
+ // 件数表示
880
+ viewModel.getItems().addListener((observable, oldValue, newValue) -> {
881
+ recordCount.setText(viewModel.getItems().size() + " 件");
882
+ });
883
+
884
+ // 初期検索
885
+ viewModel.search();
886
+ }
887
+
888
+ @FXML
889
+ private void onSearch() {
890
+ viewModel.search();
891
+ }
892
+
893
+ @FXML
894
+ private void onNew() {
895
+ // 新規画面への遷移
896
+ }
897
+
898
+ @FXML
899
+ private void onEdit() {
900
+ // 編集画面への遷移
901
+ }
902
+
903
+ @FXML
904
+ private void onDelete() {
905
+ ItemRow selected = viewModel.selectedItemProperty().get();
906
+ if (selected == null) return;
907
+
908
+ if (AlertHelper.showConfirmation(
909
+ "品目「" + selected.getItemName() + "」を削除しますか?")) {
910
+ try {
911
+ viewModel.delete(selected.getItemCode());
912
+ AlertHelper.showInfo("削除しました");
913
+ } catch (Exception e) {
914
+ AlertHelper.showError("削除に失敗しました: " + e.getMessage());
915
+ }
916
+ }
917
+ }
918
+
919
+ @FXML
920
+ private void onExportExcel() {
921
+ // Excel出力処理
922
+ }
923
+ }
924
+ ```
925
+
926
+ </details>
927
+
928
+ <details>
929
+ <summary>item-list.fxml</summary>
930
+
931
+ ```xml
932
+ <?xml version="1.0" encoding="UTF-8"?>
933
+ <?import javafx.scene.control.*?>
934
+ <?import javafx.scene.layout.*?>
935
+ <?import org.kordamp.ikonli.javafx.FontIcon?>
936
+
937
+ <VBox xmlns="http://javafx.com/javafx/21"
938
+ xmlns:fx="http://javafx.com/fxml/1"
939
+ fx:controller="com.example.production.infrastructure.in.javafx.controller.ItemListController"
940
+ spacing="10" padding="10">
941
+
942
+ <!-- ツールバー -->
943
+ <HBox spacing="10" alignment="CENTER_LEFT">
944
+ <ComboBox fx:id="categoryComboBox" promptText="品目区分" prefWidth="120"/>
945
+ <TextField fx:id="searchField" promptText="品目コード・品目名で検索" prefWidth="250"/>
946
+ <Button fx:id="searchButton" onAction="#onSearch">
947
+ <graphic><FontIcon iconLiteral="fas-search"/></graphic>
948
+ </Button>
949
+ <Pane HBox.hgrow="ALWAYS"/>
950
+ <Button fx:id="newButton" text="新規" styleClass="primary" onAction="#onNew">
951
+ <graphic><FontIcon iconLiteral="fas-plus"/></graphic>
952
+ </Button>
953
+ <Button fx:id="editButton" text="編集" onAction="#onEdit" disable="true"/>
954
+ <Button fx:id="deleteButton" text="削除" styleClass="danger" onAction="#onDelete" disable="true"/>
955
+ <Button text="Excel出力" onAction="#onExportExcel">
956
+ <graphic><FontIcon iconLiteral="fas-file-excel"/></graphic>
957
+ </Button>
958
+ </HBox>
959
+
960
+ <!-- 品目テーブル -->
961
+ <TableView fx:id="itemTable" VBox.vgrow="ALWAYS">
962
+ <placeholder><Label text="該当する品目がありません"/></placeholder>
963
+ <columns>
964
+ <TableColumn fx:id="codeColumn" text="品目コード" prefWidth="120"/>
965
+ <TableColumn fx:id="nameColumn" text="品目名" prefWidth="200"/>
966
+ <TableColumn fx:id="categoryColumn" text="品目区分" prefWidth="100"/>
967
+ <TableColumn fx:id="leadTimeColumn" text="リードタイム" prefWidth="100"/>
968
+ <TableColumn fx:id="safetyStockColumn" text="安全在庫" prefWidth="100"/>
969
+ </columns>
970
+ </TableView>
971
+
972
+ <!-- ステータスバー -->
973
+ <HBox spacing="10" styleClass="status-bar">
974
+ <Label fx:id="recordCount" text="0 件"/>
975
+ <Pane HBox.hgrow="ALWAYS"/>
976
+ <ProgressIndicator fx:id="loadingIndicator" visible="false" prefWidth="20" prefHeight="20"/>
977
+ </HBox>
978
+ </VBox>
979
+ ```
980
+
981
+ </details>
982
+
983
+ ### 39.3 BOM 展開画面の実装
984
+
985
+ <details>
986
+ <summary>BomTreeController.java</summary>
987
+
988
+ ```java
989
+ package com.example.production.infrastructure.in.javafx.controller;
990
+
991
+ import com.example.production.application.service.BomNode;
992
+ import com.example.production.application.service.BomService;
993
+ import com.example.production.infrastructure.in.javafx.util.AlertHelper;
994
+ import javafx.fxml.FXML;
995
+ import javafx.fxml.Initializable;
996
+ import javafx.scene.control.*;
997
+ import org.springframework.stereotype.Component;
998
+
999
+ import java.net.URL;
1000
+ import java.util.ResourceBundle;
1001
+
1002
+ @Component
1003
+ public class BomTreeController implements Initializable {
1004
+
1005
+ private final BomService bomService;
1006
+
1007
+ @FXML private TextField itemCodeField;
1008
+ @FXML private TreeView<BomNode> bomTreeView;
1009
+ @FXML private Label itemNameLabel;
1010
+ @FXML private ProgressIndicator loadingIndicator;
1011
+
1012
+ public BomTreeController(BomService bomService) {
1013
+ this.bomService = bomService;
1014
+ }
1015
+
1016
+ @Override
1017
+ public void initialize(URL url, ResourceBundle rb) {
1018
+ // TreeView のセルファクトリ設定
1019
+ bomTreeView.setCellFactory(tv -> new TreeCell<>() {
1020
+ @Override
1021
+ protected void updateItem(BomNode item, boolean empty) {
1022
+ super.updateItem(item, empty);
1023
+ if (empty || item == null) {
1024
+ setText(null);
1025
+ setGraphic(null);
1026
+ } else {
1027
+ String indent = " ".repeat(item.getLevel());
1028
+ setText(String.format("%s%s [%s] x %s",
1029
+ indent,
1030
+ item.getItemCode(),
1031
+ item.getItemName(),
1032
+ item.getRequiredQuantity()));
1033
+ }
1034
+ }
1035
+ });
1036
+ }
1037
+
1038
+ @FXML
1039
+ private void onExpand() {
1040
+ String itemCode = itemCodeField.getText();
1041
+ if (itemCode == null || itemCode.isBlank()) {
1042
+ AlertHelper.showWarning("品目コードを入力してください");
1043
+ return;
1044
+ }
1045
+
1046
+ loadingIndicator.setVisible(true);
1047
+ try {
1048
+ BomNode root = bomService.explodeBom(itemCode);
1049
+ TreeItem<BomNode> rootItem = createTreeItem(root);
1050
+ rootItem.setExpanded(true);
1051
+ bomTreeView.setRoot(rootItem);
1052
+ itemNameLabel.setText(root.getItemName());
1053
+ } catch (Exception e) {
1054
+ AlertHelper.showError("BOM展開エラー: " + e.getMessage());
1055
+ } finally {
1056
+ loadingIndicator.setVisible(false);
1057
+ }
1058
+ }
1059
+
1060
+ private TreeItem<BomNode> createTreeItem(BomNode node) {
1061
+ TreeItem<BomNode> item = new TreeItem<>(node);
1062
+ if (node.getChildren() != null) {
1063
+ for (BomNode child : node.getChildren()) {
1064
+ item.getChildren().add(createTreeItem(child));
1065
+ }
1066
+ }
1067
+ item.setExpanded(true);
1068
+ return item;
1069
+ }
1070
+
1071
+ @FXML
1072
+ private void onExpandAll() {
1073
+ expandAll(bomTreeView.getRoot(), true);
1074
+ }
1075
+
1076
+ @FXML
1077
+ private void onCollapseAll() {
1078
+ expandAll(bomTreeView.getRoot(), false);
1079
+ }
1080
+
1081
+ private void expandAll(TreeItem<?> item, boolean expand) {
1082
+ if (item != null) {
1083
+ item.setExpanded(expand);
1084
+ for (TreeItem<?> child : item.getChildren()) {
1085
+ expandAll(child, expand);
1086
+ }
1087
+ }
1088
+ }
1089
+ }
1090
+ ```
1091
+
1092
+ </details>
1093
+
1094
+ <details>
1095
+ <summary>bom-tree.fxml</summary>
1096
+
1097
+ ```xml
1098
+ <?xml version="1.0" encoding="UTF-8"?>
1099
+ <?import javafx.scene.control.*?>
1100
+ <?import javafx.scene.layout.*?>
1101
+ <?import org.kordamp.ikonli.javafx.FontIcon?>
1102
+
1103
+ <VBox xmlns="http://javafx.com/javafx/21"
1104
+ xmlns:fx="http://javafx.com/fxml/1"
1105
+ fx:controller="com.example.production.infrastructure.in.javafx.controller.BomTreeController"
1106
+ spacing="10" padding="10">
1107
+
1108
+ <!-- 検索エリア -->
1109
+ <HBox spacing="10" alignment="CENTER_LEFT">
1110
+ <Label text="品目コード:"/>
1111
+ <TextField fx:id="itemCodeField" prefWidth="150"/>
1112
+ <Button text="展開" styleClass="primary" onAction="#onExpand">
1113
+ <graphic><FontIcon iconLiteral="fas-sitemap"/></graphic>
1114
+ </Button>
1115
+ <Separator orientation="VERTICAL"/>
1116
+ <Button text="全展開" onAction="#onExpandAll">
1117
+ <graphic><FontIcon iconLiteral="fas-plus-square"/></graphic>
1118
+ </Button>
1119
+ <Button text="全折畳" onAction="#onCollapseAll">
1120
+ <graphic><FontIcon iconLiteral="fas-minus-square"/></graphic>
1121
+ </Button>
1122
+ <Pane HBox.hgrow="ALWAYS"/>
1123
+ <Label fx:id="itemNameLabel" styleClass="item-name-label"/>
1124
+ </HBox>
1125
+
1126
+ <!-- BOM ツリー -->
1127
+ <TreeView fx:id="bomTreeView" VBox.vgrow="ALWAYS" showRoot="true"/>
1128
+
1129
+ <!-- ステータスバー -->
1130
+ <HBox spacing="10" styleClass="status-bar">
1131
+ <ProgressIndicator fx:id="loadingIndicator" visible="false" prefWidth="20" prefHeight="20"/>
1132
+ </HBox>
1133
+ </VBox>
1134
+ ```
1135
+
1136
+ </details>
1137
+
1138
+ ---
1139
+
1140
+ ## 第40章:トランザクションの実装
1141
+
1142
+ ### 40.1 トランザクション画面の特徴
1143
+
1144
+ トランザクション画面は、マスタ画面とは異なる以下の特徴があります。
1145
+
1146
+ ```plantuml
1147
+ @startuml transaction_screen_pattern
1148
+
1149
+ package "トランザクション画面の特徴" {
1150
+
1151
+ class "ヘッダ・明細構造" as header_detail {
1152
+ + 発注ヘッダ(仕入先、発注日)
1153
+ + 発注明細(品目、数量、単価)
1154
+ --
1155
+ 1:N の関係
1156
+ 明細の動的追加・削除
1157
+ }
1158
+
1159
+ class "計算処理" as calculation {
1160
+ + 明細金額 = 数量 × 単価
1161
+ + 合計金額 = Σ 明細金額
1162
+ --
1163
+ リアルタイム再計算
1164
+ }
1165
+
1166
+ class "ステータス管理" as status {
1167
+ + 下書き → 確定 → 完了
1168
+ + ステータスによる編集制限
1169
+ --
1170
+ 業務フロー制御
1171
+ }
1172
+
1173
+ class "帳票出力" as report {
1174
+ + 発注書
1175
+ + MRP結果レポート
1176
+ --
1177
+ JasperReports 連携
1178
+ }
1179
+ }
1180
+
1181
+ header_detail --> calculation : "明細変更時"
1182
+ status --> header_detail : "編集可否"
1183
+ header_detail --> report : "印刷"
1184
+
1185
+ @enduml
1186
+ ```
1187
+
1188
+ ### 40.2 発注入力画面の設計
1189
+
1190
+ ```plantuml
1191
+ @startuml order_entry_screen
1192
+
1193
+ package "発注入力画面" {
1194
+
1195
+ class "PurchaseOrderEntryController" as controller {
1196
+ + supplierComboBox
1197
+ + orderDatePicker
1198
+ + detailTableView
1199
+ + totalAmountLabel
1200
+ --
1201
+ onSupplierChange()
1202
+ onAddDetail()
1203
+ onRemoveDetail()
1204
+ onSave()
1205
+ onConfirm()
1206
+ onPrint()
1207
+ }
1208
+
1209
+ class "PurchaseOrderViewModel" as vm {
1210
+ + selectedSupplier
1211
+ + orderDate
1212
+ + orderDetails (ObservableList)
1213
+ + totalAmount (calculated)
1214
+ + status
1215
+ --
1216
+ addDetail()
1217
+ removeDetail()
1218
+ calculateTotal()
1219
+ save()
1220
+ confirm()
1221
+ }
1222
+
1223
+ class "OrderDetailRow" as detail {
1224
+ + itemCode
1225
+ + itemName
1226
+ + quantity
1227
+ + unitPrice
1228
+ + deliveryDate
1229
+ + amount (calculated)
1230
+ }
1231
+ }
1232
+
1233
+ controller --> vm : "バインド"
1234
+ vm "1" --> "*" detail : "contains"
1235
+
1236
+ note right of detail
1237
+ 明細行の金額は
1238
+ 数量 × 単価 で
1239
+ 自動計算
1240
+ end note
1241
+
1242
+ @enduml
1243
+ ```
1244
+
1245
+ ### 40.3 発注入力画面の TDD 実装
1246
+
1247
+ #### Red: 失敗するテストを書く
1248
+
1249
+ <details>
1250
+ <summary>PurchaseOrderEntryControllerTest.java</summary>
1251
+
1252
+ ```java
1253
+ @ExtendWith({ApplicationExtension.class, MockitoExtension.class})
1254
+ @DisplayName("発注入力画面")
1255
+ class PurchaseOrderEntryControllerTest {
1256
+
1257
+ @Mock
1258
+ private PurchaseOrderUseCase orderUseCase;
1259
+ @Mock
1260
+ private ItemUseCase itemUseCase;
1261
+
1262
+ private PurchaseOrderViewModel viewModel;
1263
+
1264
+ @Nested
1265
+ @DisplayName("明細追加")
1266
+ class AddDetail {
1267
+
1268
+ @Test
1269
+ @DisplayName("品目を選択して明細を追加できる")
1270
+ void shouldAddDetailWhenItemSelected(FxRobot robot) {
1271
+ when(itemUseCase.getItemByCode("PART-001")).thenReturn(
1272
+ createItem("PART-001", "テスト部品", new BigDecimal("500"))
1273
+ );
1274
+
1275
+ robot.clickOn("#itemCodeField").write("PART-001");
1276
+ robot.clickOn("#quantityField").write("100");
1277
+ robot.clickOn("#addDetailButton");
1278
+
1279
+ TableView<OrderDetailRow> table = robot.lookup("#detailTable").queryTableView();
1280
+ assertThat(table.getItems()).hasSize(1);
1281
+ assertThat(table.getItems().get(0).getAmount())
1282
+ .isEqualByComparingTo(new BigDecimal("50000"));
1283
+ }
1284
+ }
1285
+
1286
+ @Nested
1287
+ @DisplayName("合計計算")
1288
+ class TotalCalculation {
1289
+
1290
+ @Test
1291
+ @DisplayName("明細追加時に合計金額が再計算される")
1292
+ void shouldRecalculateTotalWhenDetailAdded(FxRobot robot) {
1293
+ viewModel.addDetail(createDetailRow("PART-001", 100, new BigDecimal("500")));
1294
+ viewModel.addDetail(createDetailRow("MAT-001", 50, new BigDecimal("200")));
1295
+
1296
+ Label totalLabel = robot.lookup("#totalAmountLabel").queryAs(Label.class);
1297
+ // 100 × 500 + 50 × 200 = 60,000
1298
+ assertThat(totalLabel.getText()).contains("60,000");
1299
+ }
1300
+ }
1301
+
1302
+ @Nested
1303
+ @DisplayName("発注確定")
1304
+ class ConfirmOrder {
1305
+
1306
+ @Test
1307
+ @DisplayName("下書き状態の発注を確定できる")
1308
+ void shouldConfirmDraftOrder(FxRobot robot) {
1309
+ // Arrange
1310
+ viewModel.addDetail(createDetailRow("PART-001", 100, new BigDecimal("500")));
1311
+ when(orderUseCase.confirmOrder(anyString())).thenReturn(
1312
+ createOrder("PO-001", OrderStatus.CONFIRMED)
1313
+ );
1314
+
1315
+ // Act
1316
+ robot.clickOn("#confirmButton");
1317
+
1318
+ // Assert
1319
+ verify(orderUseCase).confirmOrder(anyString());
1320
+ }
1321
+ }
1322
+ }
1323
+ ```
1324
+
1325
+ </details>
1326
+
1327
+ #### Green: Controller と FXML の実装
1328
+
1329
+ <details>
1330
+ <summary>PurchaseOrderEntryController.java</summary>
1331
+
1332
+ ```java
1333
+ package com.example.production.infrastructure.in.javafx.controller;
1334
+
1335
+ import com.example.production.application.port.in.*;
1336
+ import com.example.production.domain.model.purchase.OrderStatus;
1337
+ import com.example.production.infrastructure.in.javafx.util.AlertHelper;
1338
+ import com.example.production.infrastructure.in.javafx.view.OrderDetailRow;
1339
+ import com.example.production.infrastructure.in.javafx.viewmodel.PurchaseOrderViewModel;
1340
+ import javafx.fxml.FXML;
1341
+ import javafx.fxml.Initializable;
1342
+ import javafx.scene.control.*;
1343
+ import javafx.scene.control.cell.PropertyValueFactory;
1344
+ import org.springframework.stereotype.Component;
1345
+
1346
+ import java.math.BigDecimal;
1347
+ import java.net.URL;
1348
+ import java.time.LocalDate;
1349
+ import java.util.ResourceBundle;
1350
+
1351
+ @Component
1352
+ public class PurchaseOrderEntryController implements Initializable {
1353
+
1354
+ private final PurchaseOrderViewModel viewModel;
1355
+ private final ItemUseCase itemUseCase;
1356
+
1357
+ @FXML private TextField orderNumberField;
1358
+ @FXML private DatePicker orderDatePicker;
1359
+ @FXML private TextField supplierCodeField;
1360
+ @FXML private TextField supplierNameField;
1361
+ @FXML private Label statusLabel;
1362
+
1363
+ @FXML private TextField itemCodeField;
1364
+ @FXML private TextField itemNameField;
1365
+ @FXML private TextField quantityField;
1366
+ @FXML private TextField unitPriceField;
1367
+ @FXML private DatePicker deliveryDatePicker;
1368
+
1369
+ @FXML private TableView<OrderDetailRow> detailTable;
1370
+ @FXML private TableColumn<OrderDetailRow, Integer> lineNoColumn;
1371
+ @FXML private TableColumn<OrderDetailRow, String> itemCodeColumn;
1372
+ @FXML private TableColumn<OrderDetailRow, String> itemNameColumn;
1373
+ @FXML private TableColumn<OrderDetailRow, BigDecimal> quantityColumn;
1374
+ @FXML private TableColumn<OrderDetailRow, BigDecimal> unitPriceColumn;
1375
+ @FXML private TableColumn<OrderDetailRow, LocalDate> deliveryDateColumn;
1376
+ @FXML private TableColumn<OrderDetailRow, BigDecimal> amountColumn;
1377
+
1378
+ @FXML private Label totalAmountLabel;
1379
+ @FXML private Button saveButton;
1380
+ @FXML private Button confirmButton;
1381
+
1382
+ public PurchaseOrderEntryController(
1383
+ PurchaseOrderViewModel viewModel,
1384
+ ItemUseCase itemUseCase) {
1385
+ this.viewModel = viewModel;
1386
+ this.itemUseCase = itemUseCase;
1387
+ }
1388
+
1389
+ @Override
1390
+ public void initialize(URL url, ResourceBundle rb) {
1391
+ // テーブルカラムの設定
1392
+ lineNoColumn.setCellValueFactory(new PropertyValueFactory<>("lineNumber"));
1393
+ itemCodeColumn.setCellValueFactory(new PropertyValueFactory<>("itemCode"));
1394
+ itemNameColumn.setCellValueFactory(new PropertyValueFactory<>("itemName"));
1395
+ quantityColumn.setCellValueFactory(new PropertyValueFactory<>("quantity"));
1396
+ unitPriceColumn.setCellValueFactory(new PropertyValueFactory<>("unitPrice"));
1397
+ deliveryDateColumn.setCellValueFactory(new PropertyValueFactory<>("deliveryDate"));
1398
+ amountColumn.setCellValueFactory(new PropertyValueFactory<>("amount"));
1399
+
1400
+ // 金額カラムの書式設定
1401
+ amountColumn.setCellFactory(col -> new TableCell<>() {
1402
+ @Override
1403
+ protected void updateItem(BigDecimal item, boolean empty) {
1404
+ super.updateItem(item, empty);
1405
+ if (empty || item == null) {
1406
+ setText(null);
1407
+ } else {
1408
+ setText(String.format("%,d", item.intValue()));
1409
+ }
1410
+ setStyle("-fx-alignment: CENTER-RIGHT;");
1411
+ }
1412
+ });
1413
+
1414
+ // テーブルとViewModelのバインド
1415
+ detailTable.setItems(viewModel.getOrderDetails());
1416
+
1417
+ // 合計金額のバインド
1418
+ viewModel.totalAmountProperty().addListener((obs, oldVal, newVal) -> {
1419
+ totalAmountLabel.setText(String.format("¥%,d", newVal.intValue()));
1420
+ });
1421
+
1422
+ // 初期日付の設定
1423
+ orderDatePicker.setValue(LocalDate.now());
1424
+ deliveryDatePicker.setValue(LocalDate.now().plusDays(7));
1425
+
1426
+ // ボタン制御
1427
+ updateButtonState();
1428
+ }
1429
+
1430
+ @FXML
1431
+ private void onSearchItem() {
1432
+ String itemCode = itemCodeField.getText();
1433
+ if (itemCode == null || itemCode.isBlank()) return;
1434
+
1435
+ try {
1436
+ var item = itemUseCase.getItemByCode(itemCode);
1437
+ itemNameField.setText(item.getItemName());
1438
+ // デフォルト単価があれば設定
1439
+ } catch (Exception e) {
1440
+ AlertHelper.showWarning("品目が見つかりません: " + itemCode);
1441
+ itemNameField.clear();
1442
+ }
1443
+ }
1444
+
1445
+ @FXML
1446
+ private void onAddDetail() {
1447
+ try {
1448
+ String itemCode = itemCodeField.getText();
1449
+ String itemName = itemNameField.getText();
1450
+ BigDecimal quantity = new BigDecimal(quantityField.getText());
1451
+ BigDecimal unitPrice = new BigDecimal(unitPriceField.getText());
1452
+ LocalDate deliveryDate = deliveryDatePicker.getValue();
1453
+
1454
+ viewModel.addDetail(itemCode, itemName, quantity, unitPrice, deliveryDate);
1455
+
1456
+ // 入力フィールドをクリア
1457
+ itemCodeField.clear();
1458
+ itemNameField.clear();
1459
+ quantityField.clear();
1460
+ unitPriceField.clear();
1461
+ itemCodeField.requestFocus();
1462
+ } catch (NumberFormatException e) {
1463
+ AlertHelper.showWarning("数量・単価は数値で入力してください");
1464
+ }
1465
+ }
1466
+
1467
+ @FXML
1468
+ private void onRemoveDetail() {
1469
+ OrderDetailRow selected = detailTable.getSelectionModel().getSelectedItem();
1470
+ if (selected != null) {
1471
+ viewModel.removeDetail(selected);
1472
+ }
1473
+ }
1474
+
1475
+ @FXML
1476
+ private void onSave() {
1477
+ if (viewModel.getOrderDetails().isEmpty()) {
1478
+ AlertHelper.showWarning("明細を1件以上入力してください");
1479
+ return;
1480
+ }
1481
+
1482
+ try {
1483
+ viewModel.setSupplierCode(supplierCodeField.getText());
1484
+ viewModel.setOrderDate(orderDatePicker.getValue());
1485
+ viewModel.save();
1486
+ orderNumberField.setText(viewModel.getOrderNumber());
1487
+ AlertHelper.showInfo("保存しました");
1488
+ updateButtonState();
1489
+ } catch (Exception e) {
1490
+ AlertHelper.showError("保存エラー: " + e.getMessage());
1491
+ }
1492
+ }
1493
+
1494
+ @FXML
1495
+ private void onConfirm() {
1496
+ if (AlertHelper.showConfirmation("発注を確定しますか?\n確定後は編集できません。")) {
1497
+ try {
1498
+ viewModel.confirm();
1499
+ statusLabel.setText("確定");
1500
+ AlertHelper.showInfo("発注を確定しました");
1501
+ updateButtonState();
1502
+ } catch (Exception e) {
1503
+ AlertHelper.showError("確定エラー: " + e.getMessage());
1504
+ }
1505
+ }
1506
+ }
1507
+
1508
+ @FXML
1509
+ private void onPrint() {
1510
+ // JasperReports で発注書を印刷
1511
+ }
1512
+
1513
+ @FXML
1514
+ private void onClear() {
1515
+ viewModel.clear();
1516
+ orderNumberField.clear();
1517
+ supplierCodeField.clear();
1518
+ supplierNameField.clear();
1519
+ orderDatePicker.setValue(LocalDate.now());
1520
+ statusLabel.setText("新規");
1521
+ updateButtonState();
1522
+ }
1523
+
1524
+ private void updateButtonState() {
1525
+ boolean isNew = viewModel.getOrderNumber() == null;
1526
+ boolean isDraft = viewModel.getStatus() == OrderStatus.DRAFT;
1527
+
1528
+ saveButton.setDisable(!isDraft && !isNew);
1529
+ confirmButton.setDisable(isNew || !isDraft);
1530
+ }
1531
+ }
1532
+ ```
1533
+
1534
+ </details>
1535
+
1536
+ <details>
1537
+ <summary>order-entry.fxml</summary>
1538
+
1539
+ ```xml
1540
+ <?xml version="1.0" encoding="UTF-8"?>
1541
+ <?import javafx.scene.control.*?>
1542
+ <?import javafx.scene.layout.*?>
1543
+ <?import org.kordamp.ikonli.javafx.FontIcon?>
1544
+
1545
+ <VBox xmlns="http://javafx.com/javafx/21"
1546
+ xmlns:fx="http://javafx.com/fxml/1"
1547
+ fx:controller="com.example.production.infrastructure.in.javafx.controller.PurchaseOrderEntryController"
1548
+ spacing="10" padding="10">
1549
+
1550
+ <!-- ヘッダ情報 -->
1551
+ <GridPane hgap="10" vgap="10" styleClass="header-form">
1552
+ <Label text="発注番号:" GridPane.columnIndex="0" GridPane.rowIndex="0"/>
1553
+ <TextField fx:id="orderNumberField" editable="false" GridPane.columnIndex="1"/>
1554
+
1555
+ <Label text="発注日:" GridPane.columnIndex="2" GridPane.rowIndex="0"/>
1556
+ <DatePicker fx:id="orderDatePicker" GridPane.columnIndex="3"/>
1557
+
1558
+ <Label text="ステータス:" GridPane.columnIndex="4" GridPane.rowIndex="0"/>
1559
+ <Label fx:id="statusLabel" text="新規" styleClass="status-label" GridPane.columnIndex="5"/>
1560
+
1561
+ <Label text="仕入先:" GridPane.columnIndex="0" GridPane.rowIndex="1"/>
1562
+ <HBox spacing="5" GridPane.columnIndex="1" GridPane.columnSpan="3">
1563
+ <TextField fx:id="supplierCodeField" prefWidth="100"/>
1564
+ <Button onAction="#onSearchSupplier">
1565
+ <graphic><FontIcon iconLiteral="fas-search"/></graphic>
1566
+ </Button>
1567
+ <TextField fx:id="supplierNameField" editable="false" HBox.hgrow="ALWAYS"/>
1568
+ </HBox>
1569
+ </GridPane>
1570
+
1571
+ <Separator/>
1572
+
1573
+ <!-- 明細入力エリア -->
1574
+ <HBox spacing="10" alignment="CENTER_LEFT">
1575
+ <Label text="品目:"/>
1576
+ <TextField fx:id="itemCodeField" prefWidth="100" onAction="#onSearchItem"/>
1577
+ <Button onAction="#onSearchItem">
1578
+ <graphic><FontIcon iconLiteral="fas-search"/></graphic>
1579
+ </Button>
1580
+ <TextField fx:id="itemNameField" prefWidth="150" editable="false"/>
1581
+ <Label text="数量:"/>
1582
+ <TextField fx:id="quantityField" prefWidth="80" alignment="CENTER_RIGHT"/>
1583
+ <Label text="単価:"/>
1584
+ <TextField fx:id="unitPriceField" prefWidth="100" alignment="CENTER_RIGHT"/>
1585
+ <Label text="納期:"/>
1586
+ <DatePicker fx:id="deliveryDatePicker" prefWidth="130"/>
1587
+ <Button fx:id="addDetailButton" text="追加" styleClass="primary" onAction="#onAddDetail">
1588
+ <graphic><FontIcon iconLiteral="fas-plus"/></graphic>
1589
+ </Button>
1590
+ </HBox>
1591
+
1592
+ <!-- 明細テーブル -->
1593
+ <TableView fx:id="detailTable" VBox.vgrow="ALWAYS" editable="true">
1594
+ <columns>
1595
+ <TableColumn fx:id="lineNoColumn" text="No." prefWidth="50"/>
1596
+ <TableColumn fx:id="itemCodeColumn" text="品目コード" prefWidth="100"/>
1597
+ <TableColumn fx:id="itemNameColumn" text="品目名" prefWidth="180"/>
1598
+ <TableColumn fx:id="quantityColumn" text="数量" prefWidth="80" styleClass="quantity-column"/>
1599
+ <TableColumn fx:id="unitPriceColumn" text="単価" prefWidth="100" styleClass="amount-column"/>
1600
+ <TableColumn fx:id="deliveryDateColumn" text="納期" prefWidth="100"/>
1601
+ <TableColumn fx:id="amountColumn" text="金額" prefWidth="120" styleClass="amount-column"/>
1602
+ <TableColumn text="削除" prefWidth="60">
1603
+ <cellFactory>
1604
+ <!-- 削除ボタン -->
1605
+ </cellFactory>
1606
+ </TableColumn>
1607
+ </columns>
1608
+ </TableView>
1609
+
1610
+ <!-- 合計エリア -->
1611
+ <HBox spacing="20" alignment="CENTER_RIGHT" styleClass="total-area">
1612
+ <VBox alignment="CENTER_RIGHT" spacing="5">
1613
+ <HBox spacing="10" alignment="CENTER_RIGHT">
1614
+ <Label text="合計金額:" styleClass="total-label-large"/>
1615
+ <Label fx:id="totalAmountLabel" text="¥0" styleClass="total-value-large"/>
1616
+ </HBox>
1617
+ </VBox>
1618
+ </HBox>
1619
+
1620
+ <!-- ボタンエリア -->
1621
+ <HBox spacing="10" alignment="CENTER_RIGHT">
1622
+ <Button text="クリア" onAction="#onClear"/>
1623
+ <Button text="印刷" onAction="#onPrint">
1624
+ <graphic><FontIcon iconLiteral="fas-print"/></graphic>
1625
+ </Button>
1626
+ <Button fx:id="saveButton" text="保存" styleClass="primary" onAction="#onSave">
1627
+ <graphic><FontIcon iconLiteral="fas-save"/></graphic>
1628
+ </Button>
1629
+ <Button fx:id="confirmButton" text="確定" styleClass="success" onAction="#onConfirm" disable="true">
1630
+ <graphic><FontIcon iconLiteral="fas-check"/></graphic>
1631
+ </Button>
1632
+ </HBox>
1633
+ </VBox>
1634
+ ```
1635
+
1636
+ </details>
1637
+
1638
+ ### 40.4 MRP 実行画面の実装
1639
+
1640
+ <details>
1641
+ <summary>MrpExecutionController.java</summary>
1642
+
1643
+ ```java
1644
+ package com.example.production.infrastructure.in.javafx.controller;
1645
+
1646
+ import com.example.production.application.service.MrpService;
1647
+ import com.example.production.application.service.PlannedOrder;
1648
+ import com.example.production.application.service.ShortageItem;
1649
+ import com.example.production.infrastructure.in.javafx.util.AlertHelper;
1650
+ import javafx.application.Platform;
1651
+ import javafx.concurrent.Task;
1652
+ import javafx.fxml.FXML;
1653
+ import javafx.fxml.Initializable;
1654
+ import javafx.scene.control.*;
1655
+ import javafx.scene.control.cell.PropertyValueFactory;
1656
+ import org.springframework.stereotype.Component;
1657
+
1658
+ import java.math.BigDecimal;
1659
+ import java.net.URL;
1660
+ import java.time.LocalDate;
1661
+ import java.util.ResourceBundle;
1662
+ import java.util.concurrent.ExecutorService;
1663
+ import java.util.concurrent.Executors;
1664
+
1665
+ @Component
1666
+ public class MrpExecutionController implements Initializable {
1667
+
1668
+ private final MrpService mrpService;
1669
+ private final ExecutorService executor = Executors.newSingleThreadExecutor();
1670
+
1671
+ @FXML private DatePicker startDatePicker;
1672
+ @FXML private DatePicker endDatePicker;
1673
+ @FXML private ProgressBar progressBar;
1674
+ @FXML private Label progressLabel;
1675
+
1676
+ @FXML private TableView<PlannedOrder> plannedOrderTable;
1677
+ @FXML private TableColumn<PlannedOrder, String> poItemCodeColumn;
1678
+ @FXML private TableColumn<PlannedOrder, String> poItemNameColumn;
1679
+ @FXML private TableColumn<PlannedOrder, BigDecimal> poQuantityColumn;
1680
+ @FXML private TableColumn<PlannedOrder, LocalDate> poDueDateColumn;
1681
+
1682
+ @FXML private TableView<ShortageItem> shortageTable;
1683
+ @FXML private TableColumn<ShortageItem, String> siItemCodeColumn;
1684
+ @FXML private TableColumn<ShortageItem, String> siItemNameColumn;
1685
+ @FXML private TableColumn<ShortageItem, BigDecimal> siShortageColumn;
1686
+
1687
+ @FXML private Label executionTimeLabel;
1688
+ @FXML private Label totalItemsLabel;
1689
+ @FXML private Label shortageCountLabel;
1690
+
1691
+ public MrpExecutionController(MrpService mrpService) {
1692
+ this.mrpService = mrpService;
1693
+ }
1694
+
1695
+ @Override
1696
+ public void initialize(URL url, ResourceBundle rb) {
1697
+ // 初期日付の設定
1698
+ startDatePicker.setValue(LocalDate.now());
1699
+ endDatePicker.setValue(LocalDate.now().plusMonths(3));
1700
+
1701
+ // 計画オーダテーブルのカラム設定
1702
+ poItemCodeColumn.setCellValueFactory(new PropertyValueFactory<>("itemCode"));
1703
+ poItemNameColumn.setCellValueFactory(new PropertyValueFactory<>("itemName"));
1704
+ poQuantityColumn.setCellValueFactory(new PropertyValueFactory<>("quantity"));
1705
+ poDueDateColumn.setCellValueFactory(new PropertyValueFactory<>("dueDate"));
1706
+
1707
+ // 不足品目テーブルのカラム設定
1708
+ siItemCodeColumn.setCellValueFactory(new PropertyValueFactory<>("itemCode"));
1709
+ siItemNameColumn.setCellValueFactory(new PropertyValueFactory<>("itemName"));
1710
+ siShortageColumn.setCellValueFactory(new PropertyValueFactory<>("shortageQuantity"));
1711
+
1712
+ progressBar.setProgress(0);
1713
+ }
1714
+
1715
+ @FXML
1716
+ private void onExecute() {
1717
+ LocalDate startDate = startDatePicker.getValue();
1718
+ LocalDate endDate = endDatePicker.getValue();
1719
+
1720
+ if (startDate == null || endDate == null) {
1721
+ AlertHelper.showWarning("期間を指定してください");
1722
+ return;
1723
+ }
1724
+
1725
+ if (startDate.isAfter(endDate)) {
1726
+ AlertHelper.showWarning("開始日は終了日より前にしてください");
1727
+ return;
1728
+ }
1729
+
1730
+ // バックグラウンドでMRP実行
1731
+ Task<Void> task = new Task<>() {
1732
+ @Override
1733
+ protected Void call() throws Exception {
1734
+ updateProgress(0.1, 1.0);
1735
+ updateMessage("需要取得中...");
1736
+
1737
+ updateProgress(0.3, 1.0);
1738
+ updateMessage("BOM展開中...");
1739
+
1740
+ updateProgress(0.5, 1.0);
1741
+ updateMessage("正味所要量計算中...");
1742
+
1743
+ updateProgress(0.7, 1.0);
1744
+ updateMessage("計画オーダ生成中...");
1745
+
1746
+ long start = System.currentTimeMillis();
1747
+ var result = mrpService.execute(startDate, endDate);
1748
+ long elapsed = System.currentTimeMillis() - start;
1749
+
1750
+ updateProgress(1.0, 1.0);
1751
+ updateMessage("完了");
1752
+
1753
+ Platform.runLater(() -> {
1754
+ plannedOrderTable.getItems().setAll(result.getPlannedOrders());
1755
+ shortageTable.getItems().setAll(result.getShortageItems());
1756
+
1757
+ executionTimeLabel.setText(String.format("%.2f 秒", elapsed / 1000.0));
1758
+ totalItemsLabel.setText(String.valueOf(result.getPlannedOrders().size()));
1759
+ shortageCountLabel.setText(String.valueOf(result.getShortageItems().size()));
1760
+ });
1761
+
1762
+ return null;
1763
+ }
1764
+ };
1765
+
1766
+ progressBar.progressProperty().bind(task.progressProperty());
1767
+ progressLabel.textProperty().bind(task.messageProperty());
1768
+
1769
+ task.setOnFailed(e -> {
1770
+ AlertHelper.showError("MRP実行エラー: " + task.getException().getMessage());
1771
+ progressBar.progressProperty().unbind();
1772
+ progressLabel.textProperty().unbind();
1773
+ });
1774
+
1775
+ executor.submit(task);
1776
+ }
1777
+
1778
+ @FXML
1779
+ private void onExportExcel() {
1780
+ // Excel出力処理
1781
+ }
1782
+ }
1783
+ ```
1784
+
1785
+ </details>
1786
+
1787
+ ---
1788
+
1789
+ ## 第41章:エラーハンドリングと帳票出力
1790
+
1791
+ ### 41.1 AlertHelper の実装
1792
+
1793
+ アラートダイアログを統一的に扱うためのヘルパークラスを作成します。
1794
+
1795
+ <details>
1796
+ <summary>AlertHelper.java</summary>
1797
+
1798
+ ```java
1799
+ package com.example.production.infrastructure.in.javafx.util;
1800
+
1801
+ import javafx.scene.control.Alert;
1802
+ import javafx.scene.control.ButtonType;
1803
+ import javafx.scene.control.TextArea;
1804
+ import javafx.scene.layout.GridPane;
1805
+ import javafx.scene.layout.Priority;
1806
+
1807
+ import java.io.PrintWriter;
1808
+ import java.io.StringWriter;
1809
+ import java.util.Optional;
1810
+
1811
+ public class AlertHelper {
1812
+
1813
+ private AlertHelper() {}
1814
+
1815
+ public static void showInfo(String message) {
1816
+ Alert alert = new Alert(Alert.AlertType.INFORMATION);
1817
+ alert.setTitle("情報");
1818
+ alert.setHeaderText(null);
1819
+ alert.setContentText(message);
1820
+ alert.showAndWait();
1821
+ }
1822
+
1823
+ public static void showWarning(String message) {
1824
+ Alert alert = new Alert(Alert.AlertType.WARNING);
1825
+ alert.setTitle("警告");
1826
+ alert.setHeaderText(null);
1827
+ alert.setContentText(message);
1828
+ alert.showAndWait();
1829
+ }
1830
+
1831
+ public static void showError(String message) {
1832
+ Alert alert = new Alert(Alert.AlertType.ERROR);
1833
+ alert.setTitle("エラー");
1834
+ alert.setHeaderText(null);
1835
+ alert.setContentText(message);
1836
+ alert.showAndWait();
1837
+ }
1838
+
1839
+ public static void showException(String title, String header, Throwable exception) {
1840
+ Alert alert = new Alert(Alert.AlertType.ERROR);
1841
+ alert.setTitle(title);
1842
+ alert.setHeaderText(header);
1843
+ alert.setContentText(exception.getMessage());
1844
+
1845
+ StringWriter sw = new StringWriter();
1846
+ PrintWriter pw = new PrintWriter(sw);
1847
+ exception.printStackTrace(pw);
1848
+
1849
+ TextArea textArea = new TextArea(sw.toString());
1850
+ textArea.setEditable(false);
1851
+ textArea.setWrapText(true);
1852
+ textArea.setMaxWidth(Double.MAX_VALUE);
1853
+ textArea.setMaxHeight(Double.MAX_VALUE);
1854
+ GridPane.setVgrow(textArea, Priority.ALWAYS);
1855
+ GridPane.setHgrow(textArea, Priority.ALWAYS);
1856
+
1857
+ GridPane expContent = new GridPane();
1858
+ expContent.setMaxWidth(Double.MAX_VALUE);
1859
+ expContent.add(textArea, 0, 0);
1860
+
1861
+ alert.getDialogPane().setExpandableContent(expContent);
1862
+ alert.showAndWait();
1863
+ }
1864
+
1865
+ public static boolean showConfirmation(String message) {
1866
+ Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
1867
+ alert.setTitle("確認");
1868
+ alert.setHeaderText(null);
1869
+ alert.setContentText(message);
1870
+
1871
+ Optional<ButtonType> result = alert.showAndWait();
1872
+ return result.isPresent() && result.get() == ButtonType.OK;
1873
+ }
1874
+ }
1875
+ ```
1876
+
1877
+ </details>
1878
+
1879
+ ### 41.2 グローバル例外ハンドラ
1880
+
1881
+ <details>
1882
+ <summary>グローバル例外ハンドラ</summary>
1883
+
1884
+ ```java
1885
+ public class JavaFxApplication extends Application {
1886
+
1887
+ private static final Logger logger = LoggerFactory.getLogger(JavaFxApplication.class);
1888
+
1889
+ @Override
1890
+ public void init() {
1891
+ Thread.setDefaultUncaughtExceptionHandler(this::handleUncaughtException);
1892
+ // ...
1893
+ }
1894
+
1895
+ private void handleUncaughtException(Thread thread, Throwable throwable) {
1896
+ logger.error("未処理例外が発生しました [Thread: {}]", thread.getName(), throwable);
1897
+
1898
+ if (Platform.isFxApplicationThread()) {
1899
+ showErrorDialog(throwable);
1900
+ } else {
1901
+ Platform.runLater(() -> showErrorDialog(throwable));
1902
+ }
1903
+ }
1904
+
1905
+ private void showErrorDialog(Throwable throwable) {
1906
+ AlertHelper.showException(
1907
+ "予期しないエラー",
1908
+ "アプリケーションで予期しないエラーが発生しました",
1909
+ throwable
1910
+ );
1911
+ }
1912
+ }
1913
+ ```
1914
+
1915
+ </details>
1916
+
1917
+ ### 41.3 JasperReports による帳票出力
1918
+
1919
+ <details>
1920
+ <summary>ReportService.java</summary>
1921
+
1922
+ ```java
1923
+ package com.example.production.infrastructure.in.javafx.util;
1924
+
1925
+ import net.sf.jasperreports.engine.*;
1926
+ import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
1927
+ import org.springframework.core.io.ClassPathResource;
1928
+ import org.springframework.stereotype.Service;
1929
+
1930
+ import java.io.InputStream;
1931
+ import java.util.List;
1932
+ import java.util.Map;
1933
+
1934
+ @Service
1935
+ public class ReportService {
1936
+
1937
+ /**
1938
+ * 発注書を生成して印刷プレビューを表示
1939
+ */
1940
+ public void printPurchaseOrder(String orderNumber, Map<String, Object> parameters, List<?> details) {
1941
+ try {
1942
+ InputStream reportStream = new ClassPathResource("reports/purchase-order.jrxml").getInputStream();
1943
+ JasperReport jasperReport = JasperCompileManager.compileReport(reportStream);
1944
+
1945
+ JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(details);
1946
+ JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
1947
+
1948
+ // プレビュー表示
1949
+ javafx.embed.swing.SwingNode swingNode = new javafx.embed.swing.SwingNode();
1950
+ javax.swing.SwingUtilities.invokeLater(() -> {
1951
+ net.sf.jasperreports.swing.JRViewer viewer = new net.sf.jasperreports.swing.JRViewer(jasperPrint);
1952
+ swingNode.setContent(viewer);
1953
+ });
1954
+
1955
+ // 新しいウィンドウでプレビュー表示
1956
+ javafx.stage.Stage previewStage = new javafx.stage.Stage();
1957
+ previewStage.setTitle("発注書プレビュー - " + orderNumber);
1958
+ javafx.scene.layout.BorderPane pane = new javafx.scene.layout.BorderPane(swingNode);
1959
+ previewStage.setScene(new javafx.scene.Scene(pane, 800, 600));
1960
+ previewStage.show();
1961
+
1962
+ } catch (Exception e) {
1963
+ throw new RuntimeException("帳票生成エラー", e);
1964
+ }
1965
+ }
1966
+
1967
+ /**
1968
+ * MRP結果レポートをExcel出力
1969
+ */
1970
+ public void exportMrpResultToExcel(List<?> plannedOrders, List<?> shortageItems, String filePath) {
1971
+ // Apache POI を使用したExcel出力
1972
+ }
1973
+ }
1974
+ ```
1975
+
1976
+ </details>
1977
+
1978
+ ---
1979
+
1980
+ ## まとめ
1981
+
1982
+ ### 実装した機能一覧
1983
+
1984
+ | 章 | 内容 |
1985
+ |----|------|
1986
+ | **第38章: 基礎** | JavaFX + Spring Boot 統合、MVVM パターン、Property と DataBinding |
1987
+ | **第39章: マスタ画面** | 品目マスタ CRUD、BOM展開画面、TestFX による TDD、Excel エクスポート |
1988
+ | **第40章: トランザクション画面** | 発注入力・確定処理、MRP実行画面、ヘッダ・明細構造、進捗表示 |
1989
+ | **第41章: エラーハンドリング** | 統一的なアラート表示、バリデーション、JasperReports 帳票出力 |
1990
+
1991
+ ### アーキテクチャの特徴
1992
+
1993
+ ```plantuml
1994
+ @startuml javafx_architecture
1995
+
1996
+ skinparam backgroundColor #FEFEFE
1997
+ skinparam packageStyle rectangle
1998
+
1999
+ package "UI Layer" {
2000
+ package "JavaFX UI" as javafx {
2001
+ [FXML/CSS] as fxml
2002
+ }
2003
+ package "REST API UI" as rest {
2004
+ [Controller] as controller
2005
+ }
2006
+
2007
+ [ViewModel] as viewmodel
2008
+ [DTO/Response] as dto
2009
+
2010
+ fxml --> viewmodel
2011
+ controller --> dto
2012
+ }
2013
+
2014
+ package "Application Layer" {
2015
+ [UseCase\n(ItemUseCase, BomService, etc.)] as usecase
2016
+ }
2017
+
2018
+ package "Domain Layer" {
2019
+ [Entity\n(Item, Bom, PurchaseOrder)] as entity
2020
+ [Value Object] as vo
2021
+ [Repository\n(Port)] as repo_port
2022
+ }
2023
+
2024
+ package "Infrastructure Layer" {
2025
+ [MyBatis Mapper\n(Repository Implementation)] as mapper
2026
+ }
2027
+
2028
+ viewmodel --> usecase
2029
+ dto --> usecase
2030
+ usecase --> entity
2031
+ usecase --> vo
2032
+ usecase --> repo_port
2033
+ repo_port <|.. mapper : implements
2034
+
2035
+ @enduml
2036
+ ```
2037
+
2038
+ ### 技術スタック
2039
+
2040
+ | カテゴリ | 技術 |
2041
+ |---------|------|
2042
+ | **言語** | Java 21 |
2043
+ | **フレームワーク** | Spring Boot 3.4, JavaFX 21 |
2044
+ | **ORM** | MyBatis 3.0 |
2045
+ | **データベース** | PostgreSQL 16 |
2046
+ | **帳票** | JasperReports |
2047
+ | **Excel** | Apache POI |
2048
+ | **テスト** | JUnit 5, TestFX |
2049
+
2050
+ ### API サーバー版との比較
2051
+
2052
+ | 観点 | API サーバー版 | デスクトップ版 |
2053
+ |------|--------------|---------------|
2054
+ | **UI** | React/Vue | JavaFX + FXML |
2055
+ | **通信** | HTTP/REST | 直接呼び出し |
2056
+ | **状態管理** | Redux/Vuex | JavaFX Property |
2057
+ | **配置** | サーバー + クライアント | スタンドアロン |
2058
+ | **オフライン** | 不可 | 可能 |
2059
+ | **帳票** | サーバー生成 PDF | クライアント直接印刷 |
2060
+
2061
+ ### デスクトップアプリケーションの選択基準
2062
+
2063
+ | 選択基準 | デスクトップ向き | Web 向き |
2064
+ |---------|----------------|---------|
2065
+ | オフライン要件 | 必須 | 不要 |
2066
+ | 帳票・印刷 | 高度な制御 | 基本的な印刷 |
2067
+ | レスポンス | 即座の応答 | ネットワーク許容 |
2068
+ | 配布・更新 | 限定的 | 全ユーザー同時 |
2069
+ | UI 自由度 | 高い | HTML/CSS 制約 |
2070
+
2071
+ JavaFX デスクトップアプリケーションは、オフライン環境での利用や高度な帳票出力が必要な業務システムに適しています。既存のヘキサゴナルアーキテクチャを活かしながら、Input Adapter として追加することで、REST API と並行運用も可能です。
2072
+
2073
+ ---
2074
+
2075
+ [目次へ戻る](../index.md)