@@ -556,7 +650,7 @@ $env:Database__Provider="SqlServer"; $env:Database__ConnectionString="Server=db;
| SQL Server で証明書のエラーになる | 社内の自己署名証明書のサーバーなら接続文字列に `TrustServerCertificate=True` を付けるか、信頼された証明書をサーバーに設定してください |
| 権限エラー(テーブルを作成できない)で止まる | 接続ログインに、対象データベースでのテーブル作成・変更の権限を与えてください |
-## バックアップ
+## バックアップ {#backup}
### SQLite
@@ -570,7 +664,7 @@ SQLiteはWALモードで動作するため、コピーしたファイルが壊
1. サーバーを停止してから `mesapp.db` をコピーする
2. 稼働中なら SQLite の `VACUUM INTO` でバックアップファイルを作る
-Docker の場合は、コンテナを止めてからボリュームごと退避します(署名鍵も一緒に残ります)。
+Docker の場合は、コンテナを止めてからボリュームごと退避します(署名鍵と、Webhook の秘密の値を暗号化する鍵も一緒に残ります)。
ボリューム名は `docker volume ls` で確認してください(compose では `<フォルダ名>_mesapp-data`)。
```bash
@@ -591,6 +685,11 @@ docker compose start
初期状態に戻すには、データベースを削除して空のデータベースを作り直し、再起動します。
+### データ保存先の鍵
+
+データベースとは別に、データ保存先の `jwt-signing.key`(ログインの署名鍵)と `dataprotection-keys` フォルダ([Webhook](#webhooks) の秘密の値を暗号化する鍵)も退避してください。
+`dataprotection-keys` を失うと、戻したデータベースにある Webhook の秘密の値を復号できず、送信先ごとに秘密の値を再発行することになります。
+
## 制限事項
| 項目 | 状況 |
diff --git a/samples/equipment-gateway/README.md b/samples/equipment-gateway/README.md
index bf3291b..1ef3ff3 100644
--- a/samples/equipment-gateway/README.md
+++ b/samples/equipment-gateway/README.md
@@ -7,6 +7,10 @@ PLC との通信は MES に持たせず、このゲートウェイ側で行う
|---|---|
| `flows.json` | Node-RED のフロー。①模擬設備(数秒ごとに状態を変えて MQTT に出す)②MQTT を受けて送信待ちにためる ③5秒ごとにまとめて送る(送れなかった分は次の回に送り直す) |
| `mosquitto.conf` | MQTT ブローカー(Eclipse Mosquitto)の最小構成。**認証も暗号化もしない**ので試すときだけ使う |
+| `settings.js` | Node-RED の設定。Webhook の署名を確かめるため、`/mes-webhook` への本文を JSON に読み替える前のまま残す |
+
+`flows.json` には、MES の Webhook を受けてチャット(Slack・Teams)へ転送する「Webhook の受け側」のタブもあります。
+MES の送信先に `http://node-red:1880/mes-webhook` を登録し、秘密の値を `.env` の `MES_WEBHOOK_SECRET` に入れます(運用ガイドの「Webhook」)。
## 動かし方
diff --git a/samples/equipment-gateway/flows.json b/samples/equipment-gateway/flows.json
index 576e785..75fd8fa 100644
--- a/samples/equipment-gateway/flows.json
+++ b/samples/equipment-gateway/flows.json
@@ -278,5 +278,222 @@
"wires": [
[]
]
+ },
+ {
+ "id": "tab-webhook",
+ "type": "tab",
+ "label": "Webhook の受け側",
+ "info": "Parallel Factory MES の Webhook を受け、署名を確かめてチャット(Slack・Teams)へ転送する見本。\n環境変数 MES_WEBHOOK_SECRET(送信先を登録したときの秘密の値 whsec_...)・CHAT_KIND(slack か teams)・CHAT_WEBHOOK_URL(省くと模擬に送る)。\nMES の送信先の URL は http://node-red:1880/mes-webhook(同じ compose の中から)。"
+ },
+ {
+ "id": "c-wh-recv",
+ "type": "comment",
+ "name": "① MES から受けて署名を確かめる(重複は捨てる)",
+ "info": "",
+ "x": 250,
+ "y": 40,
+ "wires": [],
+ "z": "tab-webhook"
+ },
+ {
+ "id": "wh-in",
+ "type": "http in",
+ "name": "POST /mes-webhook",
+ "url": "/mes-webhook",
+ "method": "post",
+ "upload": false,
+ "swaggerDoc": "",
+ "x": 150,
+ "y": 80,
+ "wires": [
+ [
+ "wh-verify"
+ ]
+ ],
+ "z": "tab-webhook"
+ },
+ {
+ "id": "wh-verify",
+ "type": "function",
+ "name": "署名を確かめる",
+ "func": "// MES の Webhook の署名を確かめる(Spec.md 3.8 Webhook)。\n// 署名は「X-Mes-Timestamp.本文」の HMAC-SHA256。本文は JSON に読み替える前のバイト列そのもの\n// (settings.js の httpNodeMiddleware が msg.payload に残している)。読み替えた後の JSON から作り直すと、\n// 数値の書き方(10.0000 と 10 など)が変わって署名が合わない。\nconst secret = env.get('MES_WEBHOOK_SECRET') || '';\nconst timestamp = msg.req.headers['x-mes-timestamp'] || '';\nconst signature = msg.req.headers['x-mes-signature'] || '';\nconst body = typeof msg.payload === 'string' ? msg.payload : null;\n\nfunction reject(reason) {\n node.warn('受け付けませんでした:' + reason);\n msg.statusCode = 401;\n msg.payload = { error: reason };\n return [msg, null];\n}\nif (!secret) return reject('MES_WEBHOOK_SECRET が設定されていません');\nif (body === null) return reject('本文を生のまま受け取れていません(settings.js を確かめてください)');\n// 古い要求の送り直し(再生攻撃)を弾く。MES とこの PC の時計は NTP で揃える\nif (!/^\\d+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return reject('時刻が5分以上ずれています');\nconst expected = 'sha256=' + crypto.createHmac('sha256', secret).update(timestamp + '.' + body, 'utf8').digest('hex');\nif (expected.length !== signature.length\n || !crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature))) return reject('署名が合いません');\n\nconst event = JSON.parse(body);\n// 少なくとも1回届くので、同じ id は2回目以降を捨てる(覚えるのは直近の1000件)\nconst seen = flow.get('seenIds') || [];\nconst duplicate = seen.includes(event.id);\nif (!duplicate) {\n seen.push(event.id);\n flow.set('seenIds', seen.slice(-1000));\n}\n// 先に 2xx を返す(MES は応答を待っている。転送に時間がかかっても再送されないように)\nconst reply = { req: msg.req, res: msg.res, statusCode: 200, payload: { received: event.id } };\nif (duplicate) {\n node.log('重複を捨てました:' + event.id);\n return [reply, null];\n}\nreturn [reply, { payload: event }];\n",
+ "outputs": 2,
+ "timeout": 0,
+ "noerr": 0,
+ "initialize": "",
+ "finalize": "",
+ "libs": [
+ {
+ "var": "crypto",
+ "module": "crypto"
+ }
+ ],
+ "x": 360,
+ "y": 80,
+ "wires": [
+ [
+ "wh-reply"
+ ],
+ [
+ "wh-to-chat",
+ "wh-received"
+ ]
+ ],
+ "z": "tab-webhook"
+ },
+ {
+ "id": "wh-reply",
+ "type": "http response",
+ "name": "応答",
+ "statusCode": "",
+ "headers": {},
+ "x": 560,
+ "y": 60,
+ "wires": [],
+ "z": "tab-webhook"
+ },
+ {
+ "id": "wh-received",
+ "type": "debug",
+ "name": "受けた通知",
+ "active": true,
+ "tosidebar": true,
+ "console": true,
+ "tostatus": false,
+ "complete": "payload",
+ "targetType": "msg",
+ "statusVal": "",
+ "statusType": "auto",
+ "x": 580,
+ "y": 120,
+ "wires": [],
+ "z": "tab-webhook"
+ },
+ {
+ "id": "c-wh-chat",
+ "type": "comment",
+ "name": "② チャットの形にして転送する",
+ "info": "",
+ "x": 200,
+ "y": 180,
+ "wires": [],
+ "z": "tab-webhook"
+ },
+ {
+ "id": "wh-to-chat",
+ "type": "function",
+ "name": "チャットの形にする",
+ "func": "// 通知をチャットの形にする。CHAT_KIND=slack(既定)か teams。\n// 送り先は CHAT_WEBHOOK_URL(Slack の Incoming Webhook、Teams のワークフローの「Webhook 要求を受信したとき」の URL)。\n// 既定はこのフローの中の模擬(/chat-mock)で、実際のチャットには送らない\nconst event = msg.payload;\nconst url = env.get('CHAT_WEBHOOK_URL') || 'http://localhost:1880/chat-mock';\nconst text = '[' + event.type + '] ' + event.summary;\nmsg.url = url;\nmsg.method = 'POST';\nmsg.headers = { 'Content-Type': 'application/json' };\nif ((env.get('CHAT_KIND') || 'slack') === 'teams') {\n // Teams のワークフローは Adaptive Card を受ける\n msg.payload = {\n type: 'message',\n attachments: [{\n contentType: 'application/vnd.microsoft.card.adaptive',\n content: {\n $schema: 'http://adaptivecards.io/schemas/adaptive-card.json',\n type: 'AdaptiveCard',\n version: '1.4',\n body: [{ type: 'TextBlock', text: text, wrap: true }],\n },\n }],\n };\n} else {\n msg.payload = { text: text };\n}\nreturn msg;\n",
+ "outputs": 1,
+ "timeout": 0,
+ "noerr": 0,
+ "initialize": "",
+ "finalize": "",
+ "libs": [],
+ "x": 180,
+ "y": 220,
+ "wires": [
+ [
+ "wh-chat"
+ ]
+ ],
+ "z": "tab-webhook"
+ },
+ {
+ "id": "wh-chat",
+ "type": "http request",
+ "name": "チャットへ送る",
+ "method": "use",
+ "ret": "txt",
+ "paytoqs": "ignore",
+ "url": "",
+ "tls": "",
+ "persist": false,
+ "proxy": "",
+ "insecureHTTPParser": false,
+ "authType": "",
+ "senderr": false,
+ "headers": [],
+ "x": 400,
+ "y": 220,
+ "wires": [
+ [
+ "wh-chat-result"
+ ]
+ ],
+ "z": "tab-webhook"
+ },
+ {
+ "id": "wh-chat-result",
+ "type": "debug",
+ "name": "転送の結果",
+ "active": true,
+ "tosidebar": true,
+ "console": true,
+ "tostatus": false,
+ "complete": "statusCode",
+ "targetType": "msg",
+ "statusVal": "",
+ "statusType": "auto",
+ "x": 600,
+ "y": 220,
+ "wires": [],
+ "z": "tab-webhook"
+ },
+ {
+ "id": "c-wh-mock",
+ "type": "comment",
+ "name": "③ チャットの模擬(CHAT_WEBHOOK_URL を省いたときの送り先)",
+ "info": "",
+ "x": 270,
+ "y": 280,
+ "wires": [],
+ "z": "tab-webhook"
+ },
+ {
+ "id": "mock-in",
+ "type": "http in",
+ "name": "POST /chat-mock",
+ "url": "/chat-mock",
+ "method": "post",
+ "upload": false,
+ "swaggerDoc": "",
+ "x": 140,
+ "y": 320,
+ "wires": [
+ [
+ "mock-show",
+ "mock-reply"
+ ]
+ ],
+ "z": "tab-webhook"
+ },
+ {
+ "id": "mock-show",
+ "type": "debug",
+ "name": "チャットに届いた形",
+ "active": true,
+ "tosidebar": true,
+ "console": true,
+ "tostatus": false,
+ "complete": "payload",
+ "targetType": "msg",
+ "statusVal": "",
+ "statusType": "auto",
+ "x": 380,
+ "y": 300,
+ "wires": [],
+ "z": "tab-webhook"
+ },
+ {
+ "id": "mock-reply",
+ "type": "http response",
+ "name": "200",
+ "statusCode": "200",
+ "headers": {},
+ "x": 340,
+ "y": 340,
+ "wires": [],
+ "z": "tab-webhook"
}
]
diff --git a/samples/equipment-gateway/settings.js b/samples/equipment-gateway/settings.js
new file mode 100644
index 0000000..292d92f
--- /dev/null
+++ b/samples/equipment-gateway/settings.js
@@ -0,0 +1,31 @@
+// Node-RED の設定(サンプル)。compose.yaml の node-red が `--settings /gateway/settings.js` で読む。
+// 書いていない項目は Node-RED の既定のまま(画面は http://localhost:1880、送信待ちなどのコンテキストはメモリ)。
+
+// Webhook の受け側(flows.json の「Webhook の受け側」タブ)のために、本文を JSON に読み替える前のまま残す。
+// MES の署名は送ったバイト列そのものに付くので、読み替えた後の JSON から作り直すと合わない
+// (数値の書き方などが変わるため)。/mes-webhook への POST だけを対象にし、他の口は今までどおり。
+function keepRawWebhookBody(req, res, next) {
+ // 読み終えた本文はもう流れてこないので、2回目に呼ばれたら(下の2か所の両方に掛けている)何もしない
+ if (req._body || req.method !== 'POST' || req.path !== '/mes-webhook') {
+ return next();
+ }
+ const chunks = [];
+ req.on('data', (chunk) => chunks.push(chunk));
+ req.on('end', () => {
+ // 読み終えた印を付けると、以降の JSON の読み替えは飛ばされ、HTTP 受信ノードの msg.payload に文字列のまま入る
+ req.body = Buffer.concat(chunks).toString('utf8');
+ req._body = true;
+ next();
+ });
+ req.on('error', next);
+}
+
+module.exports = {
+ // 画面(エディタ)は既定で / に置かれ、すべての要求の JSON を先に読み替えてしまう。
+ // その手前で本文を残すため、画面の側の口にも掛ける(画面を別の場所に移したときは、下の HTTP 受信ノードの側で効く)
+ httpAdminMiddleware: keepRawWebhookBody,
+ httpNodeMiddleware: keepRawWebhookBody,
+
+ // 送信待ちを Node-RED の再起動をまたいで残したいときは、次を有効にする(/data/context にファイルで残る)
+ // contextStorage: { default: { module: 'localfilesystem' } },
+};
diff --git a/samples/webhook/README.md b/samples/webhook/README.md
new file mode 100644
index 0000000..041fcc7
--- /dev/null
+++ b/samples/webhook/README.md
@@ -0,0 +1,34 @@
+# Webhook の受け側(サンプル)
+
+Parallel Factory MES が送る Webhook(業務の出来事の通知)を受ける最小の見本です。
+どれも、**署名を確かめる → 時刻のずれを弾く → 2xx を返す → 同じ `id` の2回目以降を捨てる** の順で受け、通知の要約を表示します。
+
+| ファイル | 内容 |
+|---|---|
+| `receive_mes_webhook.py` | Python 3.9 以降(標準ライブラリだけ)。`0.0.0.0` で待つので、別の PC や Docker の MES からも受けられる |
+| `Receive-MesWebhook.ps1` | PowerShell 7。MES と同じ PC で動かす(`http://localhost` だけで待つので管理者の権限は要らない) |
+
+チャット(Slack・Teams)へ転送する見本は、Node-RED のフロー(`samples/equipment-gateway/flows.json` の「Webhook の受け側」タブ)にあります。
+
+## 動かし方
+
+1. MES の「管理」→「Webhook」で送信先を登録し、表示された秘密の値(`whsec_...`)を写す。URL は次のとおり
+ - Python:`http://<この PC>:9000/mes-webhook`(Docker の MES からなら `http://host.docker.internal:9000/mes-webhook`)
+ - PowerShell:`http://localhost:9000/mes-webhook`
+2. 受け側を起動する
+
+ ```powershell
+ python receive_mes_webhook.py --secret whsec_...
+ ./Receive-MesWebhook.ps1 -Secret whsec_...
+ ```
+
+3. 送信先の一覧の **テスト送信** を押す。受け側に `[webhook.ping] Webhook のテスト送信です(…)。` と出れば届いている
+
+## 自分の処理に書き換えるとき
+
+- 処理は `handle()`(Python)・`Invoke-MesEvent`(PowerShell)に書きます。**重い処理は 2xx を返した後に**回してください。MES は応答を既定10秒まで待ち、待ち切れなければ送り直します
+- 署名は、**受け取ったバイト列そのもの**で確かめます。JSON に読み替えてから文字列に戻すと、数値の書き方などが変わって合いません
+- 通知は「読みに行くきっかけ」です。届かなかった・順が入れ替わったときに備え、正しい今の値は連携API(生産実績のフィードなど)で取りに行ってください
+- 覚えておく `id` はメモリにあるので、受け側を再起動すると忘れます。二重に処理すると困るときは、`id` をファイルや DB に残してください
+
+詳しくは利用者ガイドの運用ガイド「Webhook」を見てください。
diff --git a/samples/webhook/Receive-MesWebhook.ps1 b/samples/webhook/Receive-MesWebhook.ps1
new file mode 100644
index 0000000..93aae3b
--- /dev/null
+++ b/samples/webhook/Receive-MesWebhook.ps1
@@ -0,0 +1,96 @@
+<#
+.SYNOPSIS
+ Parallel Factory MES の Webhook を受ける最小の見本(PowerShell 7)
+
+.DESCRIPTION
+ 署名(X-Mes-Signature)を確かめ、時刻のずれと重複を弾いて、通知の要約を表示する。
+ 自分の処理(在庫の取り込み、表示盤への出力など)は Invoke-MesEvent に書く。
+
+ MES と同じ PC で動かす見本(http://localhost だけで待つので管理者の権限は要らない)。
+ MES の送信先には http://localhost:9000/mes-webhook を登録する。
+ 別の PC や Docker の MES から受けるときは、Python の見本(receive_mes_webhook.py)か Node-RED の見本を使う。
+
+.EXAMPLE
+ ./Receive-MesWebhook.ps1 -Secret whsec_...
+#>
+[CmdletBinding()]
+param(
+ # 送信先を登録したときの秘密の値(whsec_...)。省くと環境変数 MES_WEBHOOK_SECRET を読む
+ [string]$Secret = $env:MES_WEBHOOK_SECRET,
+ [int]$Port = 9000
+)
+
+$ErrorActionPreference = 'Stop'
+if (-not $Secret) { throw '-Secret か環境変数 MES_WEBHOOK_SECRET に秘密の値を指定してください' }
+
+# これより古い・先の時刻の要求は、送り直し(再生攻撃)とみなして弾く
+$toleranceSeconds = 300
+# 重複を見分けるために覚えておく通知の数
+$seenLimit = 1000
+$seen = [System.Collections.Generic.Queue[string]]::new()
+$utf8 = [System.Text.UTF8Encoding]::new($false)
+
+function Test-MesSignature([string]$timestamp, [string]$signature, [byte[]]$body) {
+ # 署名は「X-Mes-Timestamp.本文」の HMAC-SHA256 を小文字の16進にし、sha256= を付けたもの。
+ # 本文は受け取ったバイト列そのものを使う(JSON に読み替えてから作り直すと、数値の書き方などが変わって合わない)
+ if ($timestamp -notmatch '^\d+$') { return $false }
+ $now = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()
+ if ([Math]::Abs($now - [long]$timestamp) -gt $toleranceSeconds) { return $false }
+ $message = $utf8.GetBytes("$timestamp.") + $body
+ $hash = [System.Security.Cryptography.HMACSHA256]::HashData($utf8.GetBytes($Secret), $message)
+ $expected = 'sha256=' + [Convert]::ToHexStringLower($hash)
+ return [System.Security.Cryptography.CryptographicOperations]::FixedTimeEquals(
+ $utf8.GetBytes($expected), $utf8.GetBytes($signature))
+}
+
+function Invoke-MesEvent($mesEvent) {
+ # 届いた通知を処理する。ここを自分の処理に書き換える。
+ # 通知は「読みに行くきっかけ」。正しい今の値は連携API(生産実績のフィードなど)で取りに行く
+ Write-Host "[$($mesEvent.type)] $($mesEvent.summary) (sequence $($mesEvent.sequence))"
+}
+
+$listener = [System.Net.HttpListener]::new()
+$listener.Prefixes.Add("http://localhost:$Port/")
+$listener.Start()
+Write-Host "http://localhost:$Port/mes-webhook で待っています(Ctrl+C で止める)"
+try {
+ while ($listener.IsListening) {
+ $context = $listener.GetContext()
+ $request = $context.Request
+ $response = $context.Response
+ try {
+ if ($request.HttpMethod -ne 'POST' -or $request.Url.AbsolutePath -ne '/mes-webhook') {
+ $response.StatusCode = 404
+ continue
+ }
+ $buffer = [System.IO.MemoryStream]::new()
+ $request.InputStream.CopyTo($buffer)
+ $body = $buffer.ToArray()
+ if (-not (Test-MesSignature $request.Headers['X-Mes-Timestamp'] $request.Headers['X-Mes-Signature'] $body)) {
+ Write-Host '署名か時刻が合わないので受け付けませんでした'
+ $response.StatusCode = 401
+ continue
+ }
+ $mesEvent = $utf8.GetString($body) | ConvertFrom-Json
+ # 先に 2xx を返す(MES は応答を待っている。重い処理は応答の後に回す)
+ $response.StatusCode = 200
+ $response.Close()
+
+ # 少なくとも1回届くので、同じ id は2回目以降を捨てる
+ if ($seen.Contains($mesEvent.id)) {
+ Write-Host "重複を捨てました:$($mesEvent.id)"
+ continue
+ }
+ $seen.Enqueue($mesEvent.id)
+ while ($seen.Count -gt $seenLimit) { [void]$seen.Dequeue() }
+ Invoke-MesEvent $mesEvent
+ }
+ finally {
+ # 応答を返していなければ閉じる(閉じ済みなら何もしない)
+ try { $response.Close() } catch [ObjectDisposedException] { }
+ }
+ }
+}
+finally {
+ $listener.Stop()
+}
diff --git a/samples/webhook/receive_mes_webhook.py b/samples/webhook/receive_mes_webhook.py
new file mode 100644
index 0000000..3d95d03
--- /dev/null
+++ b/samples/webhook/receive_mes_webhook.py
@@ -0,0 +1,91 @@
+"""Parallel Factory MES の Webhook を受ける最小の見本(Python 3.9 以降。標準ライブラリだけで動く)。
+
+署名(X-Mes-Signature)を確かめ、時刻のずれと重複を弾いて、通知の要約を表示する。
+自分の処理(在庫の取り込み、表示盤への出力など)は handle() に書く。
+
+ python receive_mes_webhook.py --secret whsec_... --port 9000
+
+MES の送信先には http://<この PC>:9000/mes-webhook を登録する(Docker の MES からなら http://host.docker.internal:9000/mes-webhook)。
+秘密の値は環境変数 MES_WEBHOOK_SECRET でも渡せる。
+"""
+
+import argparse
+import collections
+import hashlib
+import hmac
+import json
+import os
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+
+TOLERANCE_SECONDS = 300 # これより古い・先の時刻の要求は、送り直し(再生攻撃)とみなして弾く
+SEEN_LIMIT = 1000 # 重複を見分けるために覚えておく通知の数
+
+
+def verify(secret: str, timestamp: str, signature: str, body: bytes) -> bool:
+ """署名は「X-Mes-Timestamp.本文」の HMAC-SHA256 を小文字の16進にし、sha256= を付けたもの。
+ 本文は受け取ったバイト列そのものを使う(JSON に読み替えてから作り直すと、数値の書き方などが変わって合わない)。"""
+ if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
+ return False
+ expected = "sha256=" + hmac.new(
+ secret.encode("utf-8"), timestamp.encode("ascii") + b"." + body, hashlib.sha256
+ ).hexdigest()
+ return hmac.compare_digest(expected, signature)
+
+
+def handle(event: dict) -> None:
+ """届いた通知を処理する。ここを自分の処理に書き換える。
+ 通知は「読みに行くきっかけ」。正しい今の値は連携API(生産実績のフィードなど)で取りに行く。"""
+ print(f"[{event['type']}] {event['summary']} (sequence {event['sequence']})", flush=True)
+
+
+class Handler(BaseHTTPRequestHandler):
+ secret = ""
+ seen: "collections.OrderedDict[str, None]" = collections.OrderedDict()
+
+ def do_POST(self) -> None:
+ if self.path != "/mes-webhook":
+ self.send_response(404)
+ self.end_headers()
+ return
+ body = self.rfile.read(int(self.headers.get("Content-Length", "0")))
+ if not verify(self.secret, self.headers.get("X-Mes-Timestamp", ""),
+ self.headers.get("X-Mes-Signature", ""), body):
+ print("署名か時刻が合わないので受け付けませんでした", flush=True)
+ self.send_response(401)
+ self.end_headers()
+ return
+
+ event = json.loads(body)
+ # 先に 2xx を返す(MES は応答を待っている。重い処理は応答の後に回すか、別の仕組みにためる)
+ self.send_response(200)
+ self.end_headers()
+
+ # 少なくとも1回届くので、同じ id は2回目以降を捨てる
+ if event["id"] in self.seen:
+ print(f"重複を捨てました:{event['id']}", flush=True)
+ return
+ self.seen[event["id"]] = None
+ while len(self.seen) > SEEN_LIMIT:
+ self.seen.popitem(last=False)
+ handle(event)
+
+ def log_message(self, format: str, *args) -> None: # 要求ごとの既定のログは出さない
+ pass
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description="Parallel Factory MES の Webhook を受ける見本")
+ parser.add_argument("--secret", default=os.environ.get("MES_WEBHOOK_SECRET", ""),
+ help="送信先を登録したときの秘密の値(whsec_...)")
+ parser.add_argument("--port", type=int, default=9000)
+ args = parser.parse_args()
+ if not args.secret:
+ parser.error("--secret か環境変数 MES_WEBHOOK_SECRET に秘密の値を指定してください")
+ Handler.secret = args.secret
+ print(f"http://0.0.0.0:{args.port}/mes-webhook で待っています(Ctrl+C で止める)", flush=True)
+ ThreadingHTTPServer(("0.0.0.0", args.port), Handler).serve_forever()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/MesApp.Api/Controllers/ProductionRecordsController.cs b/src/MesApp.Api/Controllers/ProductionRecordsController.cs
index c8cc7b5..69ddc66 100644
--- a/src/MesApp.Api/Controllers/ProductionRecordsController.cs
+++ b/src/MesApp.Api/Controllers/ProductionRecordsController.cs
@@ -1,6 +1,9 @@
using MesApp.Api.Localization;
using System.Security.Claims;
using MesApp.Api.Services;
+using MesApp.Api.Services.Webhooks;
+using MesApp.Core.Constants;
+using MesApp.Core.Contracts.Integration;
using MesApp.Core.Abstractions;
using MesApp.Core.Contracts.Execution;
using MesApp.Core.Entities;
@@ -21,6 +24,7 @@ namespace MesApp.Api.Controllers;
public class ProductionRecordsController(
MesAppDbContext db,
InventoryService inventory,
+ WebhookPublisher webhooks,
IAuditLogger auditLogger) : ControllerBase
{
[HttpPut("{id:int}")]
@@ -97,6 +101,19 @@ await inventory.RemoveAsync(record.OutputLot, record.OutputLocationId.Value, -go
CorrectedByUserId = User.FindFirstValue(ClaimTypes.NameIdentifier),
});
+ // 訂正の経路はここだけ(Spec.md 3.8 Webhook)。変更前の値は上の before を、変更後は request を送る
+ await webhooks.EnqueueAsync(WebhookEventTypes.ProductionResultCorrected, async c =>
+ {
+ var orderNo = await db.ManufacturingOrders.AsNoTracking()
+ .Where(o => o.Id == record.WorkOrder!.ManufacturingOrderId).Select(o => o.OrderNo).FirstAsync(c);
+ // 送る文は保存される値なので訳さない
+ return ($"作業指示 {record.WorkOrder!.WorkOrderNo} の実績を訂正しました(良品 {record.GoodQuantity} → {request.GoodQuantity})。",
+ new ProductionResultCorrectedData(record.Id, orderNo, record.WorkOrder.WorkOrderNo, record.WorkOrder.RoutingSequence,
+ record.GoodQuantity, record.DefectQuantity, record.ScrapQuantity, record.ReworkQuantity,
+ request.GoodQuantity, request.DefectQuantity, request.ScrapQuantity, request.ReworkQuantity,
+ request.Reason));
+ }, ct);
+
record.GoodQuantity = request.GoodQuantity;
record.DefectQuantity = request.DefectQuantity;
record.ScrapQuantity = request.ScrapQuantity;
diff --git a/src/MesApp.Api/Controllers/ReceivingController.cs b/src/MesApp.Api/Controllers/ReceivingController.cs
index d6c9e97..89e362a 100644
--- a/src/MesApp.Api/Controllers/ReceivingController.cs
+++ b/src/MesApp.Api/Controllers/ReceivingController.cs
@@ -81,8 +81,8 @@ await inventory.RemoveAsync(lot, receipt.ToLocationId!.Value, receipt.Quantity,
return this.ConflictProblem(ex.Message);
}
lot.InitialQuantity = 0;
- lotStatus.ChangeStatus(lot, LotStockStatus.ToBeDiscarded, LotStatusChangeSource.Receiving,
- "受入取消", User.FindFirstValue(ClaimTypes.NameIdentifier));
+ await lotStatus.ChangeStatusAsync(lot, LotStockStatus.ToBeDiscarded, LotStatusChangeSource.Receiving,
+ "受入取消", User.FindFirstValue(ClaimTypes.NameIdentifier), ct: ct);
await db.SaveChangesAsync(ct);
await auditLogger.LogAsync("Inventory", "ReceiveCancel", nameof(Lot), lotId.ToString(),
detail: $"lot={lot.LotNumber}", ct: ct);
diff --git a/src/MesApp.Api/Controllers/WebhookDeliveriesController.cs b/src/MesApp.Api/Controllers/WebhookDeliveriesController.cs
new file mode 100644
index 0000000..720b68b
--- /dev/null
+++ b/src/MesApp.Api/Controllers/WebhookDeliveriesController.cs
@@ -0,0 +1,92 @@
+using System.Globalization;
+using MesApp.Api.Localization;
+using MesApp.Core.Abstractions;
+using MesApp.Core.Constants;
+using MesApp.Core.Contracts.Integration;
+using MesApp.Core.Entities;
+using MesApp.Core.Localization;
+using MesApp.Infrastructure;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+namespace MesApp.Api.Controllers;
+
+///
+/// Webhook の送信の記録と手での再送(Spec.md 3.8 Webhook。docs-dev/WebhookTasks.md WHK-02)。
+/// 記録には送った通知の要約が含まれるので、送信先と同じくシステム管理者だけにする
+///
+[ApiController]
+[Route("api/webhook-deliveries")]
+[Authorize]
+public class WebhookDeliveriesController(MesAppDbContext db, IAuditLogger auditLogger) : ControllerBase
+{
+ private const int DefaultLimit = 100;
+ private const int MaxLimit = 500;
+
+ ///
送信の記録(新しい順)。送信先・状態で絞れる
+ [HttpGet]
+ [Authorize(Roles = MesRoleGroups.UserAdmin)]
+ public async Task
>> List(
+ int? subscriptionId, WebhookDeliveryState? state, int? limit, CancellationToken ct)
+ {
+ var query = db.WebhookDeliveries.AsNoTracking();
+ if (subscriptionId is { } sid)
+ {
+ query = query.Where(d => d.SubscriptionId == sid);
+ }
+ if (state is { } st)
+ {
+ query = query.Where(d => d.State == st);
+ }
+ var rows = await query
+ .Include(d => d.Outbox)
+ .Include(d => d.Subscription)
+ .OrderByDescending(d => d.Id)
+ .Take(Math.Clamp(limit ?? DefaultLimit, 1, MaxLimit))
+ .ToListAsync(ct);
+ return rows.Select(ToResponse).ToList();
+ }
+
+ ///
+ /// 止まった送信(失敗)を送信待ちに戻す。回数は数え直し、次の間隔で常駐処理が送る。
+ /// 通知の id・sequence は変わらない(受け側は届いていれば重複として捨てられる)
+ ///
+ [HttpPost("{id:long}/resend")]
+ [Authorize(Roles = MesRoleGroups.UserAdmin)]
+ public async Task> Resend(long id, CancellationToken ct)
+ {
+ var delivery = await db.WebhookDeliveries
+ .Include(d => d.Outbox)
+ .Include(d => d.Subscription)
+ .FirstOrDefaultAsync(d => d.Id == id, ct);
+ if (delivery is null)
+ {
+ return this.NotFoundProblem(ApiText.T("Webhook の送信が見つかりません。"));
+ }
+ if (delivery.State != WebhookDeliveryState.Failed)
+ {
+ return this.ConflictProblem(ApiText.T("再送できるのは、送信が止まったもの({0})だけです。", EnumLabels.Of(WebhookDeliveryState.Failed)));
+ }
+ var before = new { delivery.State, delivery.Attempts, delivery.LastStatusCode, delivery.LastError };
+ delivery.State = WebhookDeliveryState.Pending;
+ delivery.Attempts = 0;
+ delivery.NextAttemptAtUnixSeconds = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
+ delivery.LockedAtUnixSeconds = null;
+ await db.SaveChangesAsync(ct);
+ await auditLogger.LogAsync("Webhook", "Resend", "WebhookDelivery", delivery.Id.ToString(CultureInfo.InvariantCulture),
+ detail: new
+ {
+ before,
+ after = new { delivery.State, delivery.Attempts },
+ subscription = delivery.Subscription!.Name,
+ delivery.Outbox!.EventType,
+ }, ct: ct);
+ return ToResponse(delivery);
+ }
+
+ internal static WebhookDeliveryResponse ToResponse(WebhookDelivery d) => new(
+ d.Id, d.SubscriptionId, d.Subscription!.Name, d.OutboxId, d.Outbox!.EventId, d.Outbox.EventType, d.Outbox.Summary,
+ d.Outbox.OccurredAt, d.State, d.Attempts, DateTimeOffset.FromUnixTimeSeconds(d.NextAttemptAtUnixSeconds),
+ d.LastAttemptAt, d.LastStatusCode, d.LastError, d.DeliveredAt);
+}
diff --git a/src/MesApp.Api/Controllers/WebhookSubscriptionsController.cs b/src/MesApp.Api/Controllers/WebhookSubscriptionsController.cs
new file mode 100644
index 0000000..27d7d2c
--- /dev/null
+++ b/src/MesApp.Api/Controllers/WebhookSubscriptionsController.cs
@@ -0,0 +1,225 @@
+using System.Globalization;
+using System.Security.Claims;
+using MesApp.Api.Localization;
+using MesApp.Api.Services.Webhooks;
+using MesApp.Core.Abstractions;
+using MesApp.Core.Constants;
+using MesApp.Core.Contracts.Integration;
+using MesApp.Core.Entities;
+using MesApp.Infrastructure;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.EntityFrameworkCore;
+
+namespace MesApp.Api.Controllers;
+
+///
+/// Webhook の送信先の登録・変更・削除と秘密の再発行(Spec.md 3.8 Webhook。docs-dev/WebhookTasks.md WHK-01)。
+/// 送信先は業務データの持ち出し口になるので、一覧の参照もシステム管理者だけにする(APIキーと同じ)
+///
+[ApiController]
+[Route("api/webhook-subscriptions")]
+[Authorize]
+public class WebhookSubscriptionsController(
+ MesAppDbContext db, WebhookSecrets secrets, WebhookDispatcher dispatcher, IAuditLogger auditLogger) : ControllerBase
+{
+ private const int NameMaxLength = 100;
+ private const int UrlMaxLength = 2000;
+
+ /// 登録済みの送信先(登録順)。送れていない送信の件数を添える(失敗が続いている送信先を見つけるため)
+ [HttpGet]
+ [Authorize(Roles = MesRoleGroups.UserAdmin)]
+ public async Task>> List(CancellationToken ct)
+ {
+ var rows = await db.WebhookSubscriptions.AsNoTracking().OrderBy(s => s.Id).ToListAsync(ct);
+ var counts = await db.WebhookDeliveries.AsNoTracking()
+ // テスト送信の失敗は数えない(結果はその場で返している。数えるとダッシュボードの「失敗中」が消えなくなる)
+ .Where(d => d.State != WebhookDeliveryState.Delivered && d.Outbox!.EventType != WebhookDispatcher.PingEventType)
+ .GroupBy(d => new { d.SubscriptionId, d.State })
+ .Select(g => new { g.Key.SubscriptionId, g.Key.State, Count = g.Count(), Retrying = g.Count(d => d.Attempts > 0) })
+ .ToListAsync(ct);
+ return rows.Select(s =>
+ {
+ var pending = counts.FirstOrDefault(c => c.SubscriptionId == s.Id && c.State == WebhookDeliveryState.Pending);
+ var failed = counts.FirstOrDefault(c => c.SubscriptionId == s.Id && c.State == WebhookDeliveryState.Failed);
+ return ToResponse(s) with
+ {
+ PendingCount = (pending?.Count ?? 0) - (pending?.Retrying ?? 0),
+ RetryingCount = pending?.Retrying ?? 0,
+ FailedCount = failed?.Count ?? 0,
+ };
+ }).ToList();
+ }
+
+ /// 送信先を登録する。秘密の値の平文はこの応答でしか返さない
+ [HttpPost]
+ [Authorize(Roles = MesRoleGroups.UserAdmin)]
+ public async Task> Create(SaveWebhookSubscriptionRequest request, CancellationToken ct)
+ {
+ if (Validate(request) is { } invalid)
+ {
+ return invalid;
+ }
+ var (plain, protectedSecret, prefix) = secrets.Generate();
+ var subscription = new WebhookSubscription
+ {
+ Name = request.Name.Trim(),
+ Url = request.Url.Trim(),
+ EventTypes = Join(request.EventTypes),
+ SecretProtected = protectedSecret,
+ SecretPrefix = prefix,
+ IsActive = request.IsActive,
+ CreatedByUserId = User.FindFirstValue(ClaimTypes.NameIdentifier),
+ };
+ db.WebhookSubscriptions.Add(subscription);
+ await db.SaveChangesAsync(ct);
+ // 平文も暗号文も残さない(監査ログを読める人が署名を作れてはいけない)
+ await auditLogger.LogAsync("Webhook", "Create", "WebhookSubscription", Key(subscription),
+ detail: Snapshot(subscription), ct: ct);
+ return new CreatedWebhookSecretResponse(ToResponse(subscription), plain);
+ }
+
+ /// 送信先を変更する(秘密の値は変えない)
+ [HttpPut("{id:int}")]
+ [Authorize(Roles = MesRoleGroups.UserAdmin)]
+ public async Task> Update(int id, SaveWebhookSubscriptionRequest request, CancellationToken ct)
+ {
+ var subscription = await db.WebhookSubscriptions.FirstOrDefaultAsync(s => s.Id == id, ct);
+ if (subscription is null)
+ {
+ return this.NotFoundProblem(ApiText.T("Webhook の送信先が見つかりません。"));
+ }
+ if (Validate(request) is { } invalid)
+ {
+ return invalid;
+ }
+ var before = Snapshot(subscription);
+ subscription.Name = request.Name.Trim();
+ subscription.Url = request.Url.Trim();
+ subscription.EventTypes = Join(request.EventTypes);
+ subscription.IsActive = request.IsActive;
+ subscription.UpdatedAt = DateTimeOffset.UtcNow;
+ await db.SaveChangesAsync(ct);
+ await auditLogger.LogAsync("Webhook", "Update", "WebhookSubscription", Key(subscription),
+ detail: new { before, after = Snapshot(subscription) }, ct: ct);
+ return ToResponse(subscription);
+ }
+
+ /// 秘密の値を再発行する。古い値はすぐに使えなくなる(以後の送信は新しい値で署名する)
+ [HttpPost("{id:int}/rotate-secret")]
+ [Authorize(Roles = MesRoleGroups.UserAdmin)]
+ public async Task> RotateSecret(int id, CancellationToken ct)
+ {
+ var subscription = await db.WebhookSubscriptions.FirstOrDefaultAsync(s => s.Id == id, ct);
+ if (subscription is null)
+ {
+ return this.NotFoundProblem(ApiText.T("Webhook の送信先が見つかりません。"));
+ }
+ var beforePrefix = subscription.SecretPrefix;
+ var (plain, protectedSecret, prefix) = secrets.Generate();
+ subscription.SecretProtected = protectedSecret;
+ subscription.SecretPrefix = prefix;
+ subscription.SecretRotatedAt = DateTimeOffset.UtcNow;
+ await db.SaveChangesAsync(ct);
+ await auditLogger.LogAsync("Webhook", "RotateSecret", "WebhookSubscription", Key(subscription),
+ detail: new { subscription.Name, before = beforePrefix, after = prefix }, ct: ct);
+ return new CreatedWebhookSecretResponse(ToResponse(subscription), plain);
+ }
+
+ ///
+ /// テスト送信(種類 webhook.ping)。いま1回だけ送って結果を返す(失敗しても再送しない)。
+ /// 無効の送信先にも送れる(有効にする前に受け側を確かめるため)。送信の記録にも残る
+ ///
+ [HttpPost("{id:int}/test")]
+ [Authorize(Roles = MesRoleGroups.UserAdmin)]
+ public async Task> Test(int id, CancellationToken ct)
+ {
+ var subscription = await db.WebhookSubscriptions.AsNoTracking().FirstOrDefaultAsync(s => s.Id == id, ct);
+ if (subscription is null)
+ {
+ return this.NotFoundProblem(ApiText.T("Webhook の送信先が見つかりません。"));
+ }
+ var delivery = new WebhookDelivery { SubscriptionId = id };
+ db.WebhookOutbox.Add(new WebhookOutbox
+ {
+ EventType = WebhookDispatcher.PingEventType,
+ // 受け側へ送る文(保存される値なので訳さない。WHK-03 の summary と同じ扱い)
+ Summary = $"Webhook のテスト送信です({subscription.Name})。",
+ Payload = System.Text.Json.JsonSerializer.Serialize(
+ new { subscriptionId = subscription.Id, name = subscription.Name }, WebhookPublisher.PayloadJson),
+ Deliveries = [delivery],
+ });
+ await db.SaveChangesAsync(ct);
+ await dispatcher.SendNowAsync(db, delivery.Id, ct);
+
+ var sent = await db.WebhookDeliveries.AsNoTracking()
+ .Include(d => d.Outbox).Include(d => d.Subscription)
+ .SingleAsync(d => d.Id == delivery.Id, ct);
+ return WebhookDeliveriesController.ToResponse(sent);
+ }
+
+ /// 送信先を削除する。まだ送っていない送信待ちと送信の記録も消える(止めるだけなら無効にする)
+ [HttpDelete("{id:int}")]
+ [Authorize(Roles = MesRoleGroups.UserAdmin)]
+ public async Task Delete(int id, CancellationToken ct)
+ {
+ var subscription = await db.WebhookSubscriptions.FirstOrDefaultAsync(s => s.Id == id, ct);
+ if (subscription is null)
+ {
+ return this.NotFoundProblem(ApiText.T("Webhook の送信先が見つかりません。"));
+ }
+ db.WebhookSubscriptions.Remove(subscription);
+ await db.SaveChangesAsync(ct);
+ await auditLogger.LogAsync("Webhook", "Delete", "WebhookSubscription", Key(subscription),
+ detail: Snapshot(subscription), ct: ct);
+ return NoContent();
+ }
+
+ private ActionResult? Validate(SaveWebhookSubscriptionRequest request)
+ {
+ var name = request.Name?.Trim() ?? string.Empty;
+ if (name.Length == 0)
+ {
+ return this.BadRequestProblem(ApiText.T("用途(名前)を入力してください。"));
+ }
+ if (name.Length > NameMaxLength)
+ {
+ return this.BadRequestProblem(ApiText.T("用途(名前)は{0}文字以内で入力してください。", NameMaxLength));
+ }
+ var url = request.Url?.Trim() ?? string.Empty;
+ if (url.Length > UrlMaxLength
+ || !Uri.TryCreate(url, UriKind.Absolute, out var uri)
+ || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
+ {
+ return this.BadRequestProblem(ApiText.T("送信先の URL は http:// か https:// で始まる{0}文字以内の URL を入力してください。", UrlMaxLength));
+ }
+ if (uri.UserInfo.Length > 0)
+ {
+ // 一覧・監査ログに URL がそのまま出るので、パスワードを書かせない
+ return this.BadRequestProblem(ApiText.T("送信先の URL に利用者名・パスワードを含めないでください。受け側は署名で送り手を確かめます。"));
+ }
+ var types = request.EventTypes ?? [];
+ if (types.Count == 0)
+ {
+ return this.BadRequestProblem(ApiText.T("通知するイベントの種類を1つ以上選んでください。"));
+ }
+ if (types.FirstOrDefault(t => !WebhookEventTypes.All.Contains(t)) is { } unknown)
+ {
+ return this.BadRequestProblem(ApiText.T("イベントの種類 '{0}' はありません。", unknown));
+ }
+ return null;
+ }
+
+ // 画面の一覧の順(WebhookEventTypes.All の順)に揃え、重複を除いて保存する
+ private static string Join(List types) =>
+ string.Join(',', WebhookEventTypes.All.Where(types.Contains));
+
+ private static string Key(WebhookSubscription s) => s.Id.ToString(CultureInfo.InvariantCulture);
+
+ private static object Snapshot(WebhookSubscription s) =>
+ new { s.Name, s.Url, s.EventTypes, s.IsActive, s.SecretPrefix };
+
+ private static WebhookSubscriptionResponse ToResponse(WebhookSubscription s) => new(
+ s.Id, s.Name, s.Url, WebhookEventTypes.Split(s.EventTypes), s.SecretPrefix, s.IsActive,
+ s.CreatedAt, s.UpdatedAt, s.SecretRotatedAt);
+}
diff --git a/src/MesApp.Api/IntegrationOpenApi.cs b/src/MesApp.Api/IntegrationOpenApi.cs
index 5ea0da1..304a6c9 100644
--- a/src/MesApp.Api/IntegrationOpenApi.cs
+++ b/src/MesApp.Api/IntegrationOpenApi.cs
@@ -1,3 +1,5 @@
+using System.Text.Json.Nodes;
+using MesApp.Api.Services.Webhooks;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi;
@@ -48,7 +50,89 @@ public static IServiceCollection AddIntegrationOpenApi(this IServiceCollection s
[new OpenApiSecuritySchemeReference(ApiKeyAuthentication.Scheme, document)] = [],
},
];
+ AddWebhooks(document);
return Task.CompletedTask;
});
});
+
+ ///
+ /// MES から外へ送る通知(Spec.md 3.8 Webhook。WHK-03)を OpenAPI 3.1 の webhooks 節に載せる。
+ /// 形は (送るときの書き方そのもの)から作る。画面の JSON の設定(列挙は数値)から
+ /// 作らないのは、Webhook の本文は列挙を名前で送るため
+ ///
+ private static void AddWebhooks(OpenApiDocument document)
+ {
+ document.Webhooks ??= new Dictionary();
+ var envelope = WebhookContract.Envelope;
+ foreach (var (eventType, fields) in WebhookContract.Describe())
+ {
+ var properties = envelope.ToDictionary(f => f.Name, f => (IOpenApiSchema)SchemaOf(f));
+ properties["type"] = new OpenApiSchema { Type = JsonSchemaType.String, Enum = [JsonValue.Create(eventType)!] };
+ properties["data"] = new OpenApiSchema
+ {
+ Type = JsonSchemaType.Object,
+ Properties = fields.ToDictionary(f => f.Name, f => (IOpenApiSchema)SchemaOf(f)),
+ // null になり得る項目も、項目自体は必ず送る
+ Required = fields.Select(f => f.Name).ToHashSet(),
+ };
+ document.Webhooks[eventType] = new OpenApiPathItem
+ {
+ Operations = new Dictionary
+ {
+ [HttpMethod.Post] = new OpenApiOperation
+ {
+ Summary = eventType,
+ Description =
+ "送信先として登録した URL へ POST する(管理 → Webhook)。ヘッダ X-Mes-Event(種類)・X-Mes-Delivery(送信の ID。再送でも同じ)・" +
+ "X-Mes-Timestamp(Unix 秒)・X-Mes-Signature(sha256= に続けて、秘密の値を鍵にした「X-Mes-Timestamp.本文」の HMAC-SHA256 の小文字16進)を付ける。" +
+ "少なくとも1回届け、順序は保証しないので、id で重複を捨てる。2xx を返せば送信済み。正しい今の値は連携API のフィードで取りに行く。",
+ RequestBody = new OpenApiRequestBody
+ {
+ Required = true,
+ Content = new Dictionary
+ {
+ ["application/json"] = new OpenApiMediaType
+ {
+ Schema = new OpenApiSchema
+ {
+ Type = JsonSchemaType.Object,
+ Properties = properties,
+ Required = properties.Keys.ToHashSet(),
+ },
+ },
+ },
+ },
+ Responses = new OpenApiResponses
+ {
+ ["2XX"] = new OpenApiResponse { Description = "受け取った(以後は送らない)" },
+ },
+ },
+ },
+ };
+ }
+ }
+
+ private static OpenApiSchema SchemaOf(WebhookContract.Field field)
+ {
+ var schema = field.Kind switch
+ {
+ "integer" => new OpenApiSchema { Type = JsonSchemaType.Integer, Format = "int64" },
+ "number" => new OpenApiSchema { Type = JsonSchemaType.Number },
+ "boolean" => new OpenApiSchema { Type = JsonSchemaType.Boolean },
+ "date-time" => new OpenApiSchema { Type = JsonSchemaType.String, Format = "date-time" },
+ "uuid" => new OpenApiSchema { Type = JsonSchemaType.String, Format = "uuid" },
+ "enum" => new OpenApiSchema
+ {
+ Type = JsonSchemaType.String,
+ Enum = [.. field.Values!.Select(v => (JsonNode)JsonValue.Create(v)!)],
+ },
+ _ => new OpenApiSchema { Type = JsonSchemaType.String },
+ };
+ if (field.Nullable)
+ {
+ schema.Type |= JsonSchemaType.Null;
+ schema.Enum?.Add(null!);
+ }
+ return schema;
+ }
}
diff --git a/src/MesApp.Api/Localization/ApiText.en.resx b/src/MesApp.Api/Localization/ApiText.en.resx
index 28828a1..88bef17 100644
--- a/src/MesApp.Api/Localization/ApiText.en.resx
+++ b/src/MesApp.Api/Localization/ApiText.en.resx
@@ -2763,4 +2763,25 @@
Text entered into stop and failure intervals from equipment events
+
+ The webhook destination was not found.
+
+
+ Enter a destination URL that starts with http:// or https:// and is at most {0} characters long.
+
+
+ Do not include a user name or password in the destination URL. The receiver verifies the sender by the signature.
+
+
+ Select at least one event type to notify.
+
+
+ There is no event type '{0}'.
+
+
+ The webhook delivery was not found.
+
+
+ Only stopped deliveries ({0}) can be resent.
+
diff --git a/src/MesApp.Api/MesAppHost.cs b/src/MesApp.Api/MesAppHost.cs
index 297a7d9..4b96725 100644
--- a/src/MesApp.Api/MesAppHost.cs
+++ b/src/MesApp.Api/MesAppHost.cs
@@ -1,12 +1,14 @@
using System.Globalization;
using MesApp.Api.Services;
using MesApp.Api.Services.FolderLink;
+using MesApp.Api.Services.Webhooks;
using MesApp.Api.Localization;
using MesApp.Core.Abstractions;
using MesApp.Core.Entities;
using MesApp.Infrastructure;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
+using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
@@ -124,6 +126,27 @@ public static WebApplication Build(string[] args)
builder.Services.Configure(builder.Configuration.GetSection(FolderLinkOptions.SectionName));
builder.Services.AddSingleton();
builder.Services.AddHostedService();
+ // Webhook(Spec.md 3.8)。秘密の値の暗号化に Data Protection を使うので、鍵をデータディレクトリに残す
+ // (既定の置き場所は Docker では再起動で消え、復号できなくなる。Spec.md 7.7 の退避の対象)
+ builder.Services.AddDataProtection()
+ .SetApplicationName("ParallelFactoryMES")
+ .PersistKeysToFileSystem(new DirectoryInfo(MesAppDataDirectory.Resolve(
+ builder.Configuration["DataProtection:KeysDirectory"] is { Length: > 0 } keysDirectory
+ ? keysDirectory
+ : "dataprotection-keys")));
+ builder.Services.AddSingleton();
+ builder.Services.AddScoped();
+ builder.Services.Configure(builder.Configuration.GetSection(WebhookOptions.SectionName));
+ // リダイレクトは追わない(送信先が知らない場所へ本文と署名を転送させないため。3xx は失敗として止める)
+ builder.Services.AddHttpClient(WebhookDispatcher.HttpClientName, client =>
+ {
+ // 待ち時間は送信ごとに WebhookOptions.TimeoutSeconds で切る
+ client.Timeout = Timeout.InfiniteTimeSpan;
+ client.DefaultRequestHeaders.UserAgent.ParseAdd("ParallelFactoryMES-Webhook/1");
+ })
+ .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler { AllowAutoRedirect = false });
+ builder.Services.AddSingleton();
+ builder.Services.AddHostedService();
// 既定は JWT(画面用 API)。APIキーは連携API の Controller が明示したときだけ使う(ApiKeyAuthentication.IntegrationSchemes)
builder.Services
diff --git a/src/MesApp.Api/Services/EquipmentEventService.cs b/src/MesApp.Api/Services/EquipmentEventService.cs
index 1621fdd..3b1cb58 100644
--- a/src/MesApp.Api/Services/EquipmentEventService.cs
+++ b/src/MesApp.Api/Services/EquipmentEventService.cs
@@ -44,7 +44,7 @@ public sealed class EquipmentEventOptions
///
///
public sealed class EquipmentEventService(
- MesAppDbContext db, IAuditLogger auditLogger, IOptions options)
+ MesAppDbContext db, Webhooks.WebhookPublisher webhooks, IAuditLogger auditLogger, IOptions options)
{
/// 区間を閉じるだけの状態(電源断・通信断)。稼働履歴のステータスには無い
public const string OffState = "Off";
@@ -249,6 +249,8 @@ private async Task ApplyAsync(
openLog.WorkOrderId = workOrderId;
openLog.Note = row.Note;
row.EquipmentLogId = openLog.Id;
+ // 同じ時刻の変化で区間の状態を置き換えた:停止・故障になったなら知らせる(Spec.md 3.8 Webhook)
+ await ShopFloorReportService.EnqueueStoppedAsync(webhooks, db, openLog, row.AlarmCode, ct);
}
}
else
@@ -275,6 +277,7 @@ private async Task ApplyAsync(
Source = EquipmentLogSource.Event,
};
db.EquipmentLogs.Add(openLog);
+ await ShopFloorReportService.EnqueueStoppedAsync(webhooks, db, openLog, row.AlarmCode, ct);
await db.SaveChangesAsync(ct);
row.EquipmentLogId = openLog.Id;
}
diff --git a/src/MesApp.Api/Services/InspectionService.cs b/src/MesApp.Api/Services/InspectionService.cs
index c7cef26..4134188 100644
--- a/src/MesApp.Api/Services/InspectionService.cs
+++ b/src/MesApp.Api/Services/InspectionService.cs
@@ -20,6 +20,7 @@ public sealed class InspectionService(
NumberingService numbering,
LotStatusService lotStatus,
IBusinessDateService businessDate,
+ Webhooks.WebhookPublisher webhooks,
IAuditLogger auditLogger)
{
///
@@ -174,8 +175,8 @@ public async Task> CreateAsync(
// 履歴に検査指示IDを残すため、採番済みになってから変更する
if (lot is not null && request.Type != InspectionOrderType.Sample)
{
- lotStatus.ChangeStatus(lot, LotStockStatus.AwaitingInspection, LotStatusChangeSource.Inspection,
- $"検査指示 {order.OrderNo} の発行", userId, inspectionOrderId: order.Id);
+ await lotStatus.ChangeStatusAsync(lot, LotStockStatus.AwaitingInspection, LotStatusChangeSource.Inspection,
+ $"検査指示 {order.OrderNo} の発行", userId, inspectionOrderId: order.Id, ct: ct);
await db.SaveChangesAsync(ct);
}
await auditLogger.LogAsync("Quality", "InspectionCreate", nameof(InspectionOrder), order.Id.ToString(),
@@ -314,10 +315,10 @@ public async Task> JudgeAsync(
// 判定結果のロット反映(Spec.md 5.7:検査待ち→正常/不良)
if (order.TargetLot is not null && order.Type != InspectionOrderType.Sample)
{
- lotStatus.ChangeStatus(order.TargetLot, pass ? LotStockStatus.Normal : LotStockStatus.Defective,
+ await lotStatus.ChangeStatusAsync(order.TargetLot, pass ? LotStockStatus.Normal : LotStockStatus.Defective,
LotStatusChangeSource.Inspection,
$"検査指示 {order.OrderNo} の総合判定:{order.OverallJudgment}",
- userId, inspectionOrderId: order.Id);
+ userId, inspectionOrderId: order.Id, ct: ct);
if (!string.IsNullOrWhiteSpace(grade))
{
order.TargetLot.Grade = grade; // グレード管理(C-60-10-01)
@@ -327,7 +328,7 @@ public async Task> JudgeAsync(
// 不合格時は不適合レポートを自動起票(不適合の連鎖:C-30)
if (!pass)
{
- db.NonconformanceReports.Add(new NonconformanceReport
+ var report = new NonconformanceReport
{
ReportNo = await numbering.NextNonconformanceNoAsync(ct),
Source = NonconformanceSource.Inspection,
@@ -336,7 +337,10 @@ public async Task> JudgeAsync(
InspectionOrderId = order.Id,
Content = $"検査 {order.OrderNo} で不合格判定",
ReportedByUserId = userId,
- });
+ };
+ db.NonconformanceReports.Add(report);
+ await webhooks.EnqueueAsync(MesApp.Core.Constants.WebhookEventTypes.NonconformanceCreated,
+ NonconformanceService.CreatedNotice(db, report), ct);
}
await db.SaveChangesAsync(ct);
@@ -413,9 +417,9 @@ public async Task> CorrectResultAsync(
order.JudgedByUserId = null;
if (order.TargetLot is not null && order.Type != InspectionOrderType.Sample)
{
- lotStatus.ChangeStatus(order.TargetLot, LotStockStatus.AwaitingInspection,
+ await lotStatus.ChangeStatusAsync(order.TargetLot, LotStockStatus.AwaitingInspection,
LotStatusChangeSource.Inspection, $"検査実績の訂正による再判定待ち({request.Reason})",
- userId, inspectionOrderId: order.Id);
+ userId, inspectionOrderId: order.Id, ct: ct);
}
}
await db.SaveChangesAsync(ct);
@@ -485,8 +489,8 @@ public async Task> CancelAsync(int orderId, string? use
// 履歴が無いのは発行前から検査待ちだった場合。そのままにする
if (before is not null)
{
- lotStatus.ChangeStatus(lot, before.Value, LotStatusChangeSource.Inspection,
- $"検査指示 {order.OrderNo} の取消による拘束解除", userId, inspectionOrderId: order.Id);
+ await lotStatus.ChangeStatusAsync(lot, before.Value, LotStatusChangeSource.Inspection,
+ $"検査指示 {order.OrderNo} の取消による拘束解除", userId, inspectionOrderId: order.Id, ct: ct);
}
}
await db.SaveChangesAsync(ct);
diff --git a/src/MesApp.Api/Services/LotOperationService.cs b/src/MesApp.Api/Services/LotOperationService.cs
index 85f1448..0b988c2 100644
--- a/src/MesApp.Api/Services/LotOperationService.cs
+++ b/src/MesApp.Api/Services/LotOperationService.cs
@@ -115,7 +115,7 @@ public async Task> ChangeStatusAsync(
return Outcome.Invalid(ApiText.T("存在しないロットIDです。"));
}
var before = lot.StockStatus;
- lotStatus.ChangeStatus(lot, status, LotStatusChangeSource.Manual, reason, userId);
+ await lotStatus.ChangeStatusAsync(lot, status, LotStatusChangeSource.Manual, reason, userId, ct: ct);
await db.SaveChangesAsync(ct);
await auditLogger.LogAsync("Inventory", "StatusChange", nameof(Lot), lot.Id.ToString(),
detail: new
diff --git a/src/MesApp.Api/Services/LotStatusService.cs b/src/MesApp.Api/Services/LotStatusService.cs
index 388f0dd..a81d339 100644
--- a/src/MesApp.Api/Services/LotStatusService.cs
+++ b/src/MesApp.Api/Services/LotStatusService.cs
@@ -1,5 +1,10 @@
+using MesApp.Api.Services.Webhooks;
+using MesApp.Core.Constants;
+using MesApp.Core.Contracts.Integration;
using MesApp.Core.Entities;
+using MesApp.Core.Localization;
using MesApp.Infrastructure;
+using Microsoft.EntityFrameworkCore;
namespace MesApp.Api.Services;
@@ -11,8 +16,9 @@ namespace MesApp.Api.Services;
/// 遷移を として残す。
///
/// SaveChangesは呼び出し側が行う(InventoryServiceと同じ規約。1操作=1トランザクション)。
+/// 変更のたびに Webhook lot.status-changed を同じトランザクションで積む(Spec.md 3.8 Webhook)。
///
-public class LotStatusService(MesAppDbContext db)
+public class LotStatusService(MesAppDbContext db, WebhookPublisher webhooks)
{
///
/// ステータスを変更し、遷移を履歴に残す。現在値と同じ場合は何もしない(無意味な履歴を作らない)。
@@ -24,14 +30,16 @@ public class LotStatusService(MesAppDbContext db)
/// 操作ユーザー
/// 契機となった検査指示
/// 契機となった不適合
- public void ChangeStatus(
+ /// 取消の合図
+ public async Task ChangeStatusAsync(
Lot lot, LotStockStatus to, LotStatusChangeSource source, string? reason, string? userId,
- int? inspectionOrderId = null, int? nonconformanceReportId = null)
+ int? inspectionOrderId = null, int? nonconformanceReportId = null, CancellationToken ct = default)
{
if (lot.StockStatus == to)
{
return;
}
+ var from = lot.StockStatus;
db.LotStatusHistories.Add(new LotStatusHistory
{
LotId = lot.Id,
@@ -44,5 +52,14 @@ public void ChangeStatus(
ChangedByUserId = userId,
});
lot.StockStatus = to;
+
+ await webhooks.EnqueueAsync(WebhookEventTypes.LotStatusChanged, async c =>
+ {
+ var productCode = lot.Product?.Code
+ ?? await db.Products.Where(p => p.Id == lot.ProductId).Select(p => p.Code).FirstAsync(c);
+ // 送る文は保存される値なので訳さない(区分は原文の表示名)
+ return ($"ロット {lot.LotNumber} の在庫ステータスが「{EnumLabels.OriginalOf(from)}」から「{EnumLabels.OriginalOf(to)}」になりました。",
+ new LotStatusChangedData(lot.LotNumber, productCode, from, to, source, reason));
+ }, ct);
}
}
diff --git a/src/MesApp.Api/Services/ManufacturingOrderService.cs b/src/MesApp.Api/Services/ManufacturingOrderService.cs
index aa9d7c3..ae7d12b 100644
--- a/src/MesApp.Api/Services/ManufacturingOrderService.cs
+++ b/src/MesApp.Api/Services/ManufacturingOrderService.cs
@@ -1,6 +1,9 @@
using MesApp.Core.Localization;
using MesApp.Api.Localization;
+using MesApp.Api.Services.Webhooks;
using MesApp.Core.Abstractions;
+using MesApp.Core.Constants;
+using MesApp.Core.Contracts.Integration;
using MesApp.Core.Contracts.Production;
using MesApp.Core.Entities;
using MesApp.Infrastructure;
@@ -27,6 +30,7 @@ public sealed class ManufacturingOrderService(
NumberingService numbering,
IBusinessDateService businessDate,
WorkOrderStatusService workOrderStatus,
+ WebhookPublisher webhooks,
IAuditLogger auditLogger)
{
///
@@ -152,14 +156,16 @@ public async Task CancelAsync(ManufacturingOrder order, string? us
return OrderOutcome.Conflict(ApiText.T("状態 '{0}' の指図は取消できません。", EnumLabels.Of(order.Status)));
}
+ var from = order.Status;
order.Status = ManufacturingOrderStatus.Canceled;
order.UpdatedAt = DateTimeOffset.UtcNow;
+ await EnqueueFinishedAsync(order, from, ct);
foreach (var workOrder in order.WorkOrders.Where(w =>
w.Status is not (WorkOrderStatus.Completed or WorkOrderStatus.Approved)))
{
- workOrderStatus.ChangeStatus(workOrder, WorkOrderStatus.Canceled,
+ await workOrderStatus.ChangeStatusAsync(workOrder, WorkOrderStatus.Canceled,
WorkOrderStatusChangeSource.OrderCancel, userId,
- $"指図 {order.OrderNo} の取消に連動");
+ $"指図 {order.OrderNo} の取消に連動", ct: ct);
}
await db.SaveChangesAsync(ct);
await auditLogger.LogAsync("Production", "Cancel", nameof(ManufacturingOrder), order.Id.ToString(),
@@ -181,12 +187,28 @@ public async Task CompleteIfAllWorkOrdersDoneAsync(
&& w.Status != WorkOrderStatus.Approved && w.Status != WorkOrderStatus.Canceled, ct);
if (allDone)
{
+ var from = order.Status;
order.Status = ManufacturingOrderStatus.Completed;
order.UpdatedAt = now;
+ await EnqueueFinishedAsync(order, from, ct);
}
return allDone;
}
+ ///
+ /// 指図の完了・取消を Webhook manufacturing-order.status-changed で知らせる(Spec.md 3.8 Webhook)。
+ /// 承認・発行などの途中の変化は v1 では送らない(購読する側が欲しいのは「終わった」ことのため)
+ ///
+ private Task EnqueueFinishedAsync(ManufacturingOrder order, ManufacturingOrderStatus from, CancellationToken ct) =>
+ webhooks.EnqueueAsync(WebhookEventTypes.ManufacturingOrderStatusChanged, async c =>
+ {
+ var productCode = order.Product?.Code
+ ?? await db.Products.Where(p => p.Id == order.ProductId).Select(p => p.Code).FirstAsync(c);
+ // 送る文は保存される値なので訳さない(区分は原文の表示名)
+ return ($"製造指図 {order.OrderNo} が「{EnumLabels.OriginalOf(order.Status)}」になりました。",
+ new ManufacturingOrderStatusChangedData(order.OrderNo, order.OrderType, productCode, order.Quantity, from, order.Status));
+ }, ct);
+
///
/// 工程展開(B-10-10-01:工順に基づき工程単位の作業指示に展開)+産出ロット採番(B-10-10-05:
/// 自動=品目コード-日付-連番、または手入力)。承認済みの指図のみ展開できる。
diff --git a/src/MesApp.Api/Services/NonconformanceService.cs b/src/MesApp.Api/Services/NonconformanceService.cs
index 866f3b3..f0cd46b 100644
--- a/src/MesApp.Api/Services/NonconformanceService.cs
+++ b/src/MesApp.Api/Services/NonconformanceService.cs
@@ -1,5 +1,8 @@
using MesApp.Api.Localization;
+using MesApp.Api.Services.Webhooks;
using MesApp.Core.Abstractions;
+using MesApp.Core.Constants;
+using MesApp.Core.Contracts.Integration;
using MesApp.Core.Contracts.Quality;
using MesApp.Core.Entities;
using MesApp.Infrastructure;
@@ -17,6 +20,7 @@ public sealed class NonconformanceService(
MesAppDbContext db,
NumberingService numbering,
LotStatusService lotStatus,
+ WebhookPublisher webhooks,
IAuditLogger auditLogger)
{
///
@@ -68,12 +72,36 @@ public async Task> CreateAsync(
ReportedByUserId = userId,
};
db.NonconformanceReports.Add(report);
+ await webhooks.EnqueueAsync(WebhookEventTypes.NonconformanceCreated, CreatedNotice(db, report), ct);
await db.SaveChangesAsync(ct);
await auditLogger.LogAsync("Quality", "NonconformanceCreate", nameof(NonconformanceReport),
report.Id.ToString(), detail: $"reportNo={report.ReportNo}, source={report.Source}", ct: ct);
return Outcome.Ok(report);
}
+ ///
+ /// Webhook nonconformance.created の本文(Spec.md 3.8 Webhook)。画面・実績CSV からの起票と、
+ /// 検査の不合格からの自動起票()で同じものを使う。
+ /// 対象のロット・作業指示は ID で持っているので、番号とコードを引く
+ ///
+ public static Func> CreatedNotice(
+ MesAppDbContext db, NonconformanceReport report) => async ct =>
+ {
+ var lot = report.LotId is { } lotId
+ ? await db.Lots.AsNoTracking().Where(l => l.Id == lotId)
+ .Select(l => new { l.LotNumber, ProductCode = l.Product!.Code }).FirstOrDefaultAsync(ct)
+ : null;
+ var workOrder = report.WorkOrderId is { } workOrderId
+ ? await db.WorkOrders.AsNoTracking().Where(w => w.Id == workOrderId)
+ .Select(w => new { w.WorkOrderNo, ProductCode = w.Product!.Code }).FirstOrDefaultAsync(ct)
+ : null;
+ // 送る文は保存される値なので訳さない
+ var target = lot is not null ? $"ロット {lot.LotNumber}" : workOrder is not null ? $"作業指示 {workOrder.WorkOrderNo}" : null;
+ return ($"不適合 {report.ReportNo} を起票しました{(target is null ? "" : $"({target})")}。",
+ new NonconformanceCreatedData(report.ReportNo, report.Source, lot?.LotNumber,
+ lot?.ProductCode ?? workOrder?.ProductCode, workOrder?.WorkOrderNo));
+ };
+
///
/// 対応指示(C-30-20-01)。保留→ロット保留、廃棄→ロット廃棄予定、
/// リワーク→リワーク指図の自動起票(対象ロットの由来指図が特定できる場合)、特採→承認待ち。
@@ -103,16 +131,16 @@ public async Task> InstructAsync(
switch (request.Action)
{
case NonconformanceAction.Hold when report.Lot is not null:
- lotStatus.ChangeStatus(report.Lot, LotStockStatus.OnHold,
+ await lotStatus.ChangeStatusAsync(report.Lot, LotStockStatus.OnHold,
LotStatusChangeSource.Nonconformance,
$"不適合 {report.ReportNo} の保留指示({request.Instruction})",
- userId, nonconformanceReportId: report.Id);
+ userId, nonconformanceReportId: report.Id, ct: ct);
break;
case NonconformanceAction.Discard when report.Lot is not null:
- lotStatus.ChangeStatus(report.Lot, LotStockStatus.ToBeDiscarded,
+ await lotStatus.ChangeStatusAsync(report.Lot, LotStockStatus.ToBeDiscarded,
LotStatusChangeSource.Nonconformance,
$"不適合 {report.ReportNo} の廃棄指示({request.Instruction})",
- userId, nonconformanceReportId: report.Id);
+ userId, nonconformanceReportId: report.Id, ct: ct);
break;
case NonconformanceAction.Rework when report.Lot is not null:
await AddReworkOrderAsync(report, userId, ct);
@@ -177,10 +205,10 @@ public async Task> ApproveAsync(
// 特採:承認記録付きで次工程進行(Spec.md 5.7)
if (report.Action == NonconformanceAction.SpecialAcceptance && report.Lot is not null)
{
- lotStatus.ChangeStatus(report.Lot, LotStockStatus.Normal,
+ await lotStatus.ChangeStatusAsync(report.Lot, LotStockStatus.Normal,
LotStatusChangeSource.Nonconformance,
$"不適合 {report.ReportNo} の特採承認による解放",
- userId, nonconformanceReportId: report.Id);
+ userId, nonconformanceReportId: report.Id, ct: ct);
}
await db.SaveChangesAsync(ct);
await auditLogger.LogAsync("Quality", "NonconformanceApprove", nameof(NonconformanceReport),
diff --git a/src/MesApp.Api/Services/ShopFloorReportService.cs b/src/MesApp.Api/Services/ShopFloorReportService.cs
index 263621d..9897cbf 100644
--- a/src/MesApp.Api/Services/ShopFloorReportService.cs
+++ b/src/MesApp.Api/Services/ShopFloorReportService.cs
@@ -1,5 +1,9 @@
using MesApp.Api.Localization;
+using MesApp.Api.Services.Webhooks;
using MesApp.Core.Abstractions;
+using MesApp.Core.Constants;
+using MesApp.Core.Contracts.Integration;
+using MesApp.Core.Localization;
using MesApp.Core.Contracts.Execution;
using MesApp.Core.Contracts.Maintenance;
using MesApp.Core.Entities;
@@ -17,8 +21,35 @@ namespace MesApp.Api.Services;
/// 実績CSV取込の両方から呼ぶ。
/// 保存と監査ログまで行う。トランザクションは呼び出し側が張る。
///
-public sealed class ShopFloorReportService(MesAppDbContext db, IAuditLogger auditLogger)
+public sealed class ShopFloorReportService(MesAppDbContext db, WebhookPublisher webhooks, IAuditLogger auditLogger)
{
+ ///
+ /// Webhook equipment.stopped(Spec.md 3.8 Webhook)を、停止・故障の区間なら積む。
+ /// 手入力・実績CSV(このサービス)と設備イベント()で同じものを使う。
+ /// 区間は保存前でも、設備・作業指示は ID で持っているので番号を引ける
+ ///
+ public static async Task EnqueueStoppedAsync(
+ WebhookPublisher webhooks, MesAppDbContext db, EquipmentLog log, string? alarmCode, CancellationToken ct)
+ {
+ if (log.Status is not (EquipmentLogStatus.Stopped or EquipmentLogStatus.Failure))
+ {
+ return;
+ }
+ await webhooks.EnqueueAsync(WebhookEventTypes.EquipmentStopped, async c =>
+ {
+ var assetNo = await db.Equipments.AsNoTracking()
+ .Where(x => x.Id == log.EquipmentId).Select(x => x.AssetNo).FirstAsync(c);
+ var workOrderNo = log.WorkOrderId is { } workOrderId
+ ? await db.WorkOrders.AsNoTracking().Where(w => w.Id == workOrderId).Select(w => w.WorkOrderNo).FirstOrDefaultAsync(c)
+ : null;
+ // 送る文は保存される値なので訳さない(区分は原文の表示名)
+ var cause = string.IsNullOrWhiteSpace(log.StopCause) ? "原因未入力" : log.StopCause;
+ return ($"設備 {assetNo} が「{EnumLabels.OriginalOf(log.Status)}」になりました({cause})。",
+ new EquipmentStoppedData(assetNo, log.Status, log.StartedAt, log.EndedAt,
+ string.IsNullOrWhiteSpace(log.StopCause) ? null : log.StopCause, alarmCode, log.Source, workOrderNo));
+ }, ct);
+ }
+
/// 作業時間の記録(直接作業は作業指示が必須)
public async Task> AddWorkTimeAsync(
WorkTimeRequest request, string userId, CancellationToken ct)
@@ -129,6 +160,7 @@ public async Task> AddEquipmentLogAsync(
Source = source,
};
db.EquipmentLogs.Add(log);
+ await EnqueueStoppedAsync(webhooks, db, log, alarmCode: null, ct);
await db.SaveChangesAsync(ct);
await auditLogger.LogAsync("Equipment", "Log", nameof(EquipmentLog), log.Id.ToString(),
detail: new
diff --git a/src/MesApp.Api/Services/Webhooks/WebhookContract.cs b/src/MesApp.Api/Services/Webhooks/WebhookContract.cs
new file mode 100644
index 0000000..4eb03e4
--- /dev/null
+++ b/src/MesApp.Api/Services/Webhooks/WebhookContract.cs
@@ -0,0 +1,65 @@
+using System.Reflection;
+using System.Text.Json;
+using MesApp.Core.Contracts.Integration;
+
+namespace MesApp.Api.Services.Webhooks;
+
+///
+/// Webhook の本文の形(Spec.md 3.8 Webhook。WHK-03)を、送るときの書き方(:
+/// camelCase・列挙は名前)のとおりに書き出す。OpenAPI 文書の webhooks 節と、
+/// 約束の基準ファイル(tests/MesApp.Api.Tests/WebhookContract.v1.json)の両方がこれを使う
+/// (別々に書くと、文書と実際に送る形がずれる)
+///
+public static class WebhookContract
+{
+ /// 項目の形。 は string・integer・number・boolean・date-time・uuid・enum
+ /// 列挙の値の名前(enum のときだけ)
+ public sealed record Field(string Name, string Kind, bool Nullable, List? Values);
+
+ /// 種類ごとの本文の data の形(種類の名前の順)
+ public static IReadOnlyList<(string EventType, List Fields)> Describe() =>
+ WebhookPayloads.DataTypes
+ .OrderBy(p => p.Key, StringComparer.Ordinal)
+ .Select(p => (p.Key, Describe(p.Value)))
+ .ToList();
+
+ /// 本文の共通の包み(data 以外)。受け側との約束なので、これも基準ファイルに固定する
+ public static List Envelope { get; } =
+ [
+ new("id", "uuid", false, null),
+ new("sequence", "integer", false, null),
+ new("type", "string", false, null),
+ new("version", "integer", false, null),
+ new("occurredAt", "date-time", false, null),
+ new("summary", "string", false, null),
+ ];
+
+ private static List Describe(Type type)
+ {
+ var nullability = new NullabilityInfoContext();
+ return type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
+ .Where(p => p.GetMethod is not null && p.Name != "EqualityContract")
+ .Select(p =>
+ {
+ var underlying = Nullable.GetUnderlyingType(p.PropertyType);
+ var valueType = underlying ?? p.PropertyType;
+ var nullable = underlying is not null
+ || (!p.PropertyType.IsValueType && nullability.Create(p).ReadState == NullabilityState.Nullable);
+ var name = JsonNamingPolicy.CamelCase.ConvertName(p.Name);
+ return valueType.IsEnum
+ ? new Field(name, "enum", nullable, [.. Enum.GetNames(valueType)])
+ : new Field(name, KindOf(valueType), nullable, null);
+ })
+ .ToList();
+ }
+
+ private static string KindOf(Type type) =>
+ type == typeof(string) ? "string"
+ : type == typeof(int) || type == typeof(long) ? "integer"
+ : type == typeof(decimal) || type == typeof(double) ? "number"
+ : type == typeof(bool) ? "boolean"
+ : type == typeof(DateTimeOffset) || type == typeof(DateTime) ? "date-time"
+ : type == typeof(Guid) ? "uuid"
+ // 約束に入れられる型を増やすときは、ここと OpenAPI の書き出し(IntegrationOpenApi)を揃える
+ : throw new NotSupportedException($"Webhook の本文に使えない型です: {type.Name}");
+}
diff --git a/src/MesApp.Api/Services/Webhooks/WebhookDispatchWorker.cs b/src/MesApp.Api/Services/Webhooks/WebhookDispatchWorker.cs
new file mode 100644
index 0000000..5e02b76
--- /dev/null
+++ b/src/MesApp.Api/Services/Webhooks/WebhookDispatchWorker.cs
@@ -0,0 +1,42 @@
+using Microsoft.Extensions.Options;
+
+namespace MesApp.Api.Services.Webhooks;
+
+///
+/// Webhook の送信の常駐処理(Spec.md 3.8 Webhook。WHK-02)。決めた間隔で送信待ちを見に行き、
+/// 1回分を送り切ったらまだ残っている分を続けて送る。1回の失敗で止めず、次の間隔で続ける( と同じ形)
+///
+public sealed class WebhookDispatchWorker(
+ WebhookDispatcher dispatcher, IOptions options, ILogger logger) : BackgroundService
+{
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ var opt = options.Value;
+ if (!opt.WorkerEnabled)
+ {
+ return;
+ }
+
+ using var timer = new PeriodicTimer(TimeSpan.FromSeconds(Math.Max(1, opt.PollIntervalSeconds)));
+ do
+ {
+ try
+ {
+ // 1回分(BatchSize)を送り切ったら、まだ残っているかもしれないので続ける
+ while (await dispatcher.DispatchDueAsync(stoppingToken) >= Math.Max(1, opt.BatchSize)
+ && !stoppingToken.IsCancellationRequested)
+ {
+ }
+ }
+ catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
+ {
+ return;
+ }
+ catch (Exception ex)
+ {
+ logger.LogError(ex, "Webhook の送信処理に失敗しました。次の間隔で続けます。");
+ }
+ }
+ while (await timer.WaitForNextTickAsync(stoppingToken));
+ }
+}
diff --git a/src/MesApp.Api/Services/Webhooks/WebhookDispatcher.cs b/src/MesApp.Api/Services/Webhooks/WebhookDispatcher.cs
new file mode 100644
index 0000000..cb62e15
--- /dev/null
+++ b/src/MesApp.Api/Services/Webhooks/WebhookDispatcher.cs
@@ -0,0 +1,246 @@
+using System.Globalization;
+using System.Net;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Encodings.Web;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using MesApp.Core.Entities;
+using MesApp.Infrastructure;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Options;
+
+namespace MesApp.Api.Services.Webhooks;
+
+///
+/// Webhook の送信(Spec.md 3.8 Webhook。docs-dev/WebhookTasks.md WHK-02)。
+///
+/// 送信待ちを取り出し、署名を付けて送り、結果を残す。失敗は間隔を空けて再送し、尽きたら失敗で止める。
+/// 取り出しは「送信待ちで、取り出されていない(または取り出しが古い)行」を条件付きの更新で取り、
+/// 更新できた1件だけを送る(複数台で動かしても同じ行を二重に送らない)。
+///
+///
+public sealed class WebhookDispatcher(
+ IServiceScopeFactory scopeFactory,
+ IHttpClientFactory httpClientFactory,
+ WebhookSecrets secrets,
+ IOptions options,
+ ILogger logger)
+{
+ /// 送信に使う名前付きの HttpClient(テストは受け側をこの名前で差し替える)
+ public const string HttpClientName = "webhooks";
+
+ /// 送信の確認だけに使う種類(購読の対象ではない。WebhookEventTypes には入れない)
+ public const string PingEventType = "webhook.ping";
+
+ ///
+ /// 失敗の後に次を送るまでの間隔(n 回目の失敗の後は n 番目。尽きたら最後の値)。
+ /// 既定の8回で、最初の失敗から約2日弱は送り直し続ける(相手の保守で一時的に落ちることが多いため)
+ ///
+ private static readonly TimeSpan[] RetryDelays =
+ [
+ TimeSpan.FromMinutes(1),
+ TimeSpan.FromMinutes(5),
+ TimeSpan.FromMinutes(30),
+ TimeSpan.FromHours(2),
+ TimeSpan.FromHours(6),
+ TimeSpan.FromHours(12),
+ TimeSpan.FromHours(24),
+ ];
+
+ // 本文は人が読めるように日本語をそのまま書く(署名は送ったバイト列そのものに付くので、どちらでもよい)
+ private static readonly JsonSerializerOptions BodyJson = new()
+ {
+ Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
+ };
+
+ private readonly WebhookOptions _options = options.Value;
+
+ /// 送ってよい時刻を過ぎた送信待ちを、1回分()送る
+ /// 取り出して送った件数(成否を問わない)
+ public async Task DispatchDueAsync(CancellationToken ct)
+ {
+ using var scope = scopeFactory.CreateScope();
+ var db = scope.ServiceProvider.GetRequiredService();
+ var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
+ var staleLock = now - _options.LockTimeoutSeconds;
+
+ var candidates = await db.WebhookDeliveries.AsNoTracking()
+ .Where(d => d.State == WebhookDeliveryState.Pending
+ && d.NextAttemptAtUnixSeconds <= now
+ && (d.LockedAtUnixSeconds == null || d.LockedAtUnixSeconds < staleLock))
+ .OrderBy(d => d.Id)
+ .Select(d => d.Id)
+ .Take(Math.Max(1, _options.BatchSize))
+ .ToListAsync(ct);
+
+ var sent = 0;
+ foreach (var id in candidates)
+ {
+ if (await SendIfClaimedAsync(db, id, ct))
+ {
+ sent++;
+ }
+ }
+ return sent;
+ }
+
+ ///
+ /// 1件をいま送る(テスト送信。送ってよい時刻を待たない)。取り出せなかったら false
+ /// (別の処理がちょうど送っている)
+ ///
+ public Task SendNowAsync(MesAppDbContext db, long deliveryId, CancellationToken ct) =>
+ SendIfClaimedAsync(db, deliveryId, ct, ignoreSchedule: true);
+
+ private async Task SendIfClaimedAsync(MesAppDbContext db, long id, CancellationToken ct, bool ignoreSchedule = false)
+ {
+ var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
+ var staleLock = now - _options.LockTimeoutSeconds;
+ // 条件付きの更新で取り出す。同時に取りに来たもう一方は0行になり、送らない
+ var claimed = await db.WebhookDeliveries
+ .Where(d => d.Id == id
+ && d.State == WebhookDeliveryState.Pending
+ && (ignoreSchedule || d.NextAttemptAtUnixSeconds <= now)
+ && (d.LockedAtUnixSeconds == null || d.LockedAtUnixSeconds < staleLock))
+ .ExecuteUpdateAsync(s => s.SetProperty(d => d.LockedAtUnixSeconds, now), ct);
+ if (claimed != 1)
+ {
+ return false;
+ }
+
+ var delivery = await db.WebhookDeliveries
+ .Include(d => d.Outbox)
+ .Include(d => d.Subscription)
+ .SingleAsync(d => d.Id == id, ct);
+ await SendAsync(delivery, ct);
+ delivery.LockedAtUnixSeconds = null;
+ // 送った結果は、止める合図(ct)が来ていても残す(残さないと同じ通知をもう一度送る)
+ await db.SaveChangesAsync(CancellationToken.None);
+ return true;
+ }
+
+ private async Task SendAsync(WebhookDelivery delivery, CancellationToken ct)
+ {
+ var outbox = delivery.Outbox!;
+ var subscription = delivery.Subscription!;
+ var attemptAt = DateTimeOffset.UtcNow;
+ delivery.Attempts++;
+ delivery.LastAttemptAt = attemptAt;
+
+ string secret;
+ try
+ {
+ secret = secrets.Unprotect(subscription.SecretProtected);
+ }
+ catch (CryptographicException)
+ {
+ // DB だけを戻して Data Protection の鍵を失ったとき(Spec.md 7.7)。送り直しても直らない
+ // 保存される値なので訳さない(サーバーのログと同じ扱い)
+ Fail(delivery, null, "秘密の値を復号できません(Data Protection の鍵が無い)。送信先の秘密の値を再発行してから再送してください。", retry: false);
+ logger.LogWarning("Webhook の秘密の値を復号できません:送信先 {SubscriptionId}", subscription.Id);
+ return;
+ }
+
+ var body = BuildBody(outbox);
+ var timestamp = attemptAt.ToUnixTimeSeconds();
+ using var request = new HttpRequestMessage(HttpMethod.Post, subscription.Url)
+ {
+ Content = new StringContent(body, Encoding.UTF8, "application/json"),
+ };
+ request.Headers.Add(WebhookSignature.EventHeader, outbox.EventType);
+ request.Headers.Add(WebhookSignature.DeliveryHeader, delivery.Id.ToString(CultureInfo.InvariantCulture));
+ request.Headers.Add(WebhookSignature.TimestampHeader, timestamp.ToString(CultureInfo.InvariantCulture));
+ request.Headers.Add(WebhookSignature.SignatureHeader, WebhookSignature.Compute(secret, timestamp, body));
+
+ using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
+ timeout.CancelAfter(TimeSpan.FromSeconds(Math.Max(1, _options.TimeoutSeconds)));
+ try
+ {
+ var client = httpClientFactory.CreateClient(HttpClientName);
+ using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
+ var status = (int)response.StatusCode;
+ if (response.IsSuccessStatusCode)
+ {
+ delivery.State = WebhookDeliveryState.Delivered;
+ delivery.DeliveredAt = DateTimeOffset.UtcNow;
+ delivery.LastStatusCode = status;
+ delivery.LastError = null;
+ return;
+ }
+ var text = await ReadHeadAsync(response, timeout.Token);
+ Fail(delivery, status, $"HTTP {status} {response.ReasonPhrase} {text}".Trim(), ShouldRetry(response.StatusCode));
+ }
+ catch (OperationCanceledException) when (!ct.IsCancellationRequested)
+ {
+ Fail(delivery, null, $"応答がありませんでした({_options.TimeoutSeconds}秒)。", retry: true);
+ }
+ catch (HttpRequestException ex)
+ {
+ Fail(delivery, null, ex.Message, retry: true);
+ }
+ catch (Exception ex) when (ex is InvalidOperationException or UriFormatException)
+ {
+ // URL として送れない(登録時に検査しているので、通常は起きない)
+ Fail(delivery, null, ex.Message, retry: false);
+ }
+ }
+
+ ///
+ /// 本文。共通の包みはここで付ける(sequence=送信待ちの ID は保存するまで決まらないため)。
+ /// 項目の名前と意味は受け側との約束(WHK-03 で基準ファイルに固定する)
+ ///
+ internal static string BuildBody(WebhookOutbox outbox)
+ {
+ var envelope = new JsonObject
+ {
+ ["id"] = outbox.EventId,
+ ["sequence"] = outbox.Id,
+ ["type"] = outbox.EventType,
+ ["version"] = outbox.Version,
+ ["occurredAt"] = outbox.OccurredAt,
+ ["summary"] = outbox.Summary,
+ ["data"] = JsonNode.Parse(outbox.Payload),
+ };
+ return envelope.ToJsonString(BodyJson);
+ }
+
+ ///
+ /// 再送するか。接続できない・5xx・408(待ち切れ)・429(混雑)は相手が戻れば通るので再送する。
+ /// それ以外の 4xx と 3xx(リダイレクトは追わない)は送り直しても同じなので止める
+ /// (受け側の不具合で同じ要求を送り続けない)
+ ///
+ internal static bool ShouldRetry(HttpStatusCode status) =>
+ (int)status >= 500 || status is HttpStatusCode.RequestTimeout or HttpStatusCode.TooManyRequests;
+
+ private void Fail(WebhookDelivery delivery, int? status, string error, bool retry)
+ {
+ delivery.LastStatusCode = status;
+ delivery.LastError = error.Length > 1000 ? error[..1000] : error;
+ // テスト送信は再送しない(結果はその場で画面に返している。受け側を直したらもう一度押す)
+ if (retry && delivery.Attempts < _options.MaxAttempts && delivery.Outbox?.EventType != PingEventType)
+ {
+ var delay = RetryDelays[Math.Min(delivery.Attempts, RetryDelays.Length) - 1];
+ delivery.NextAttemptAtUnixSeconds = DateTimeOffset.UtcNow.Add(delay).ToUnixTimeSeconds();
+ logger.LogInformation("Webhook の送信に失敗しました。{Delay} 後に再送します:送信 {DeliveryId}({Error})",
+ delay, delivery.Id, delivery.LastError);
+ return;
+ }
+ delivery.State = WebhookDeliveryState.Failed;
+ logger.LogWarning("Webhook の送信を止めました:送信 {DeliveryId}・{Attempts} 回目({Error})",
+ delivery.Id, delivery.Attempts, delivery.LastError);
+ }
+
+ // 失敗の手がかりに、応答の本文の先頭だけを残す(大きな HTML のエラー画面を丸ごと残さない)
+ private static async Task ReadHeadAsync(HttpResponseMessage response, CancellationToken ct)
+ {
+ try
+ {
+ var text = await response.Content.ReadAsStringAsync(ct);
+ return text.Length > 300 ? text[..300] : text;
+ }
+ catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException)
+ {
+ return string.Empty;
+ }
+ }
+}
diff --git a/src/MesApp.Api/Services/Webhooks/WebhookOptions.cs b/src/MesApp.Api/Services/Webhooks/WebhookOptions.cs
new file mode 100644
index 0000000..b401fc5
--- /dev/null
+++ b/src/MesApp.Api/Services/Webhooks/WebhookOptions.cs
@@ -0,0 +1,28 @@
+namespace MesApp.Api.Services.Webhooks;
+
+/// Webhook の送信の設定(appsettings の Webhooks。Spec.md 3.8 Webhook)
+public sealed class WebhookOptions
+{
+ public const string SectionName = "Webhooks";
+
+ /// 常駐処理で送るか(テストでは止めて、送信を直接呼ぶ)
+ public bool WorkerEnabled { get; set; } = true;
+
+ /// 送信待ちを見に行く間隔(秒)
+ public int PollIntervalSeconds { get; set; } = 5;
+
+ /// 1回の送信の待ち時間(秒)。過ぎたら失敗として再送に回す
+ public int TimeoutSeconds { get; set; } = 10;
+
+ /// 試行の上限(初回を含む)。尽きたら失敗で止め、画面から手で再送する
+ public int MaxAttempts { get; set; } = 8;
+
+ /// 1回に取り出す件数
+ public int BatchSize { get; set; } = 20;
+
+ ///
+ /// 取り出したまま戻らない行(送信中に落ちた等)を取り出し直すまでの秒数。
+ /// 送信の待ち時間より十分長くする(短いと送信中の行をもう一方が取り出して二重に送る)
+ ///
+ public int LockTimeoutSeconds { get; set; } = 300;
+}
diff --git a/src/MesApp.Api/Services/Webhooks/WebhookPublisher.cs b/src/MesApp.Api/Services/Webhooks/WebhookPublisher.cs
new file mode 100644
index 0000000..2acf153
--- /dev/null
+++ b/src/MesApp.Api/Services/Webhooks/WebhookPublisher.cs
@@ -0,0 +1,87 @@
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using MesApp.Core.Constants;
+using MesApp.Core.Contracts.Integration;
+using MesApp.Core.Entities;
+using MesApp.Infrastructure;
+using Microsoft.EntityFrameworkCore;
+
+namespace MesApp.Api.Services.Webhooks;
+
+///
+/// Webhook の出来事を送信待ち(Outbox)に積む(Spec.md 3.8 Webhook。docs-dev/WebhookTasks.md WHK-01)。
+///
+/// 行を に足すだけで、保存(SaveChanges)は呼び出し側。
+/// 業務の変更と同じトランザクションで保存されるので、業務が巻き戻れば送信待ちも残らない。
+/// 状態を変える唯一の経路(各サービス)から呼ぶ。EF の変更の傍受からは作らない
+/// (スキーマの変更がそのまま外部の約束を変えてしまうため)。
+///
+///
+public sealed class WebhookPublisher(MesAppDbContext db)
+{
+ ///
+ /// 本文の data の書き方。項目名は camelCase、区分・状態は列挙の名前(英語)で送る
+ /// (表示言語や画面の表示名で変わらないように。連携API の応答と同じ)
+ ///
+ public static readonly JsonSerializerOptions PayloadJson = new(JsonSerializerDefaults.Web)
+ {
+ Converters = { new JsonStringEnumConverter() },
+ };
+
+ // 1つの要求の中で何度も積むことがあるので、購読は要求(スコープ)ごとに1回だけ読む
+ private List<(int Id, HashSet Types)>? _subscriptions;
+
+ ///
+ /// 出来事を積む。その種類を購読している有効な送信先が無ければ何もしない
+ /// (sequence は連番にならないが、増えることだけを約束する)
+ ///
+ /// の名前
+ /// 人が読める1文(保存して送る値なので訳さない。サーバーの既定の言語=日本語で書く)
+ /// 本文の data( の型)
+ /// 積んだ行(積まなかったら null)
+ public Task EnqueueAsync(string eventType, string summary, object data, CancellationToken ct) =>
+ EnqueueAsync(eventType, _ => Task.FromResult<(string, object)?>((summary, data)), ct);
+
+ ///
+ /// 出来事を積む(本文は購読している送信先があるときだけ作る)。本文にコード・番号を引く問い合わせが要るとき、
+ /// Webhook を使っていない工場で業務の処理を重くしないためにこちらを使う。 が null を返したら積まない
+ ///
+ public async Task EnqueueAsync(
+ string eventType, Func> build, CancellationToken ct)
+ {
+ if (!WebhookPayloads.DataTypes.TryGetValue(eventType, out var dataType))
+ {
+ // 呼び出し側の書き間違い。黙って捨てると通知が出ないことに気付けない
+ throw new ArgumentException($"未定義の Webhook イベントの種類です: {eventType}", nameof(eventType));
+ }
+
+ _subscriptions ??= (await db.WebhookSubscriptions.AsNoTracking()
+ .Where(s => s.IsActive)
+ .Select(s => new { s.Id, s.EventTypes })
+ .ToListAsync(ct))
+ .Select(s => (s.Id, WebhookEventTypes.Split(s.EventTypes).ToHashSet(StringComparer.Ordinal)))
+ .ToList();
+
+ var targets = _subscriptions.Where(s => s.Types.Contains(eventType)).Select(s => s.Id).ToList();
+ if (targets.Count == 0 || await build(ct) is not { } built)
+ {
+ return null;
+ }
+ var (summary, data) = built;
+ if (data.GetType() != dataType)
+ {
+ // 約束の型(基準ファイルで固定している形)以外を送らない
+ throw new ArgumentException($"Webhook {eventType} の data は {dataType.Name} で渡してください: {data.GetType().Name}", nameof(build));
+ }
+
+ var outbox = new WebhookOutbox
+ {
+ EventType = eventType,
+ Summary = summary.Length > 500 ? summary[..500] : summary,
+ Payload = JsonSerializer.Serialize(data, data.GetType(), PayloadJson),
+ Deliveries = targets.Select(id => new WebhookDelivery { SubscriptionId = id }).ToList(),
+ };
+ db.WebhookOutbox.Add(outbox);
+ return outbox;
+ }
+}
diff --git a/src/MesApp.Api/Services/Webhooks/WebhookSecrets.cs b/src/MesApp.Api/Services/Webhooks/WebhookSecrets.cs
new file mode 100644
index 0000000..b982d7b
--- /dev/null
+++ b/src/MesApp.Api/Services/Webhooks/WebhookSecrets.cs
@@ -0,0 +1,36 @@
+using System.Security.Cryptography;
+using Microsoft.AspNetCore.DataProtection;
+
+namespace MesApp.Api.Services.Webhooks;
+
+///
+/// Webhook の秘密の値の発行と暗号化(Spec.md 3.8 Webhook)。
+///
+/// 署名(HMAC)に平文が要るので、APIキーのようにハッシュでは持てない。Data Protection で暗号化して DB に置き、
+/// 鍵はデータディレクトリに置く(DataProtection:KeysDirectory。Spec.md 7.7:DB と一緒に退避しないと、
+/// 戻した DB の秘密は復号できず再発行が要る)。
+///
+///
+public sealed class WebhookSecrets(IDataProtectionProvider provider)
+{
+ /// 平文の先頭に付ける印(受け側の設定で APIキーと取り違えないように)
+ public const string Prefix = "whsec_";
+
+ private const int PrefixLength = 12;
+
+ // 目的の文字列を変えると、既存の秘密をすべて復号できなくなる
+ private readonly IDataProtector _protector = provider.CreateProtector("MesApp.Webhooks.Secret.v1");
+
+ /// 新しい秘密の値を作る。平文は応答で一度だけ返し、保存は暗号文と先頭だけ
+ public (string Plain, string Protected, string DisplayPrefix) Generate()
+ {
+ var plain = Prefix + Base64Url(RandomNumberGenerator.GetBytes(32));
+ return (plain, _protector.Protect(plain), plain[..PrefixLength]);
+ }
+
+ /// 署名のために平文へ戻す。鍵を失った(DB だけ戻した等)ときは
+ public string Unprotect(string protectedSecret) => _protector.Unprotect(protectedSecret);
+
+ private static string Base64Url(byte[] bytes) =>
+ Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
+}
diff --git a/src/MesApp.Api/Services/Webhooks/WebhookSignature.cs b/src/MesApp.Api/Services/Webhooks/WebhookSignature.cs
new file mode 100644
index 0000000..8f8aa93
--- /dev/null
+++ b/src/MesApp.Api/Services/Webhooks/WebhookSignature.cs
@@ -0,0 +1,32 @@
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+
+namespace MesApp.Api.Services.Webhooks;
+
+///
+/// Webhook の署名(Spec.md 3.8 Webhook)。X-Mes-Signature: sha256=<hex> は、
+/// 秘密の値を鍵にした "<X-Mes-Timestamp>.<本文>" の HMAC-SHA256(小文字の16進)。
+///
+/// 時刻を署名に含めるので、受け側は時刻のずれ(例:5分)で古い要求の送り直し(再生攻撃)を弾ける。
+/// 形は Stripe・GitHub と同じなので、受け側の実装例が多い。受け側との約束なので変えない
+///
+///
+public static class WebhookSignature
+{
+ public const string EventHeader = "X-Mes-Event";
+ public const string DeliveryHeader = "X-Mes-Delivery";
+ public const string TimestampHeader = "X-Mes-Timestamp";
+ public const string SignatureHeader = "X-Mes-Signature";
+
+ /// 署名の値(sha256= を含む)
+ /// 秘密の値の平文(whsec_ を含めた全体を鍵にする)
+ /// Unix 秒
+ /// 送る本文(UTF-8 のバイト列と同じ文字列)
+ public static string Compute(string secret, long timestamp, string body)
+ {
+ var message = timestamp.ToString(CultureInfo.InvariantCulture) + "." + body;
+ var hash = HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), Encoding.UTF8.GetBytes(message));
+ return "sha256=" + Convert.ToHexStringLower(hash);
+ }
+}
diff --git a/src/MesApp.Api/Services/WorkOrderDispatchService.cs b/src/MesApp.Api/Services/WorkOrderDispatchService.cs
index 513f12d..0c58c96 100644
--- a/src/MesApp.Api/Services/WorkOrderDispatchService.cs
+++ b/src/MesApp.Api/Services/WorkOrderDispatchService.cs
@@ -90,8 +90,8 @@ public async Task> DispatchAsync(
workOrder.AssignedUserId = request.AssignedUserId;
workOrder.AssignedEquipmentId = request.AssignedEquipmentId;
workOrder.DispatchOrder = request.DispatchOrder;
- workOrderStatus.ChangeStatus(workOrder, WorkOrderStatus.Dispatched,
- WorkOrderStatusChangeSource.Dispatch, userId);
+ await workOrderStatus.ChangeStatusAsync(workOrder, WorkOrderStatus.Dispatched,
+ WorkOrderStatusChangeSource.Dispatch, userId, ct: ct);
await db.SaveChangesAsync(ct);
await auditLogger.LogAsync("Production", "Dispatch", nameof(WorkOrder), workOrder.Id.ToString(),
detail: $"workOrderNo={workOrder.WorkOrderNo}, user={request.AssignedUserId}, " +
diff --git a/src/MesApp.Api/Services/WorkOrderExecutionService.cs b/src/MesApp.Api/Services/WorkOrderExecutionService.cs
index 389c029..095e0d6 100644
--- a/src/MesApp.Api/Services/WorkOrderExecutionService.cs
+++ b/src/MesApp.Api/Services/WorkOrderExecutionService.cs
@@ -1,6 +1,9 @@
using MesApp.Core.Localization;
using MesApp.Api.Localization;
using MesApp.Api.Policies;
+using MesApp.Api.Services.Webhooks;
+using MesApp.Core.Constants;
+using MesApp.Core.Contracts.Integration;
using MesApp.Core.Abstractions;
using MesApp.Core.Contracts.Execution;
using MesApp.Core.Entities;
@@ -48,6 +51,7 @@ public sealed class WorkOrderExecutionService(
InventoryService inventory,
ManufacturingOrderService orders,
IBusinessDateService businessDate,
+ WebhookPublisher webhooks,
IAuditLogger auditLogger)
{
///
@@ -84,8 +88,8 @@ public async Task> StartAsync(int workOrderId, string? userId
}
}
- workOrderStatus.ChangeStatus(workOrder, WorkOrderStatus.Started,
- WorkOrderStatusChangeSource.Start, userId);
+ await workOrderStatus.ChangeStatusAsync(workOrder, WorkOrderStatus.Started,
+ WorkOrderStatusChangeSource.Start, userId, ct: ct);
await db.SaveChangesAsync(ct);
await auditLogger.LogAsync("Execution", "Start", nameof(WorkOrder), workOrderId.ToString(),
detail: $"workOrderNo={workOrder.WorkOrderNo}", ct: ct);
@@ -106,8 +110,8 @@ public async Task> ApproveAsync(int workOrderId, string? user
return Outcome.Conflict(ApiText.T("状態 '{0}' の作業指示は承認できません(完了済みのみ)。", EnumLabels.Of(workOrder.Status)));
}
- workOrderStatus.ChangeStatus(workOrder, WorkOrderStatus.Approved,
- WorkOrderStatusChangeSource.Approval, userId);
+ await workOrderStatus.ChangeStatusAsync(workOrder, WorkOrderStatus.Approved,
+ WorkOrderStatusChangeSource.Approval, userId, ct: ct);
var now = DateTimeOffset.UtcNow;
await db.ProductionRecords
.Where(r => r.WorkOrderId == workOrderId && r.ApprovedAt == null)
@@ -447,8 +451,22 @@ await inventory.AddAsync(outputLot, request.OutputLocationId!.Value, request.Goo
OutputLocationId = outputLot is not null ? request.OutputLocationId : null,
};
db.ProductionRecords.Add(record);
- workOrderStatus.ChangeStatus(workOrder, WorkOrderStatus.Completed,
- WorkOrderStatusChangeSource.ProductionRecord, userId);
+ await workOrderStatus.ChangeStatusAsync(workOrder, WorkOrderStatus.Completed,
+ WorkOrderStatusChangeSource.ProductionRecord, userId, ct: ct);
+ // 画面・実績CSV・連携API のどれもここを通る(Spec.md 3.8 Webhook)。実績の ID は保存するまで決まらないので送らない
+ await webhooks.EnqueueAsync(WebhookEventTypes.ProductionResultCreated, async c =>
+ {
+ var codes = await db.WorkOrders.AsNoTracking()
+ .Where(w => w.Id == workOrderId)
+ .Select(w => new { ProductCode = w.Product!.Code, ProcessCode = w.Process!.Code })
+ .FirstAsync(c);
+ // 送る文は保存される値なので訳さない
+ return ($"作業指示 {workOrder.WorkOrderNo} の実績を記録しました(良品 {record.GoodQuantity}・不良 {record.DefectQuantity})。",
+ new ProductionResultCreatedData(workOrder.ManufacturingOrder!.OrderNo, workOrder.WorkOrderNo,
+ workOrder.RoutingSequence, codes.ProductCode, codes.ProcessCode, record.GoodQuantity,
+ record.DefectQuantity, record.ScrapQuantity, record.ReworkQuantity, record.StartedAt, record.EndedAt,
+ outputLot?.LotNumber));
+ }, ct);
await db.SaveChangesAsync(ct);
await auditLogger.LogAsync("Execution", "ProductionRecord", nameof(WorkOrder), workOrderId.ToString(),
detail: new
diff --git a/src/MesApp.Api/Services/WorkOrderStatusService.cs b/src/MesApp.Api/Services/WorkOrderStatusService.cs
index 47dc07b..a63c9ea 100644
--- a/src/MesApp.Api/Services/WorkOrderStatusService.cs
+++ b/src/MesApp.Api/Services/WorkOrderStatusService.cs
@@ -1,5 +1,10 @@
+using MesApp.Api.Services.Webhooks;
+using MesApp.Core.Constants;
+using MesApp.Core.Contracts.Integration;
using MesApp.Core.Entities;
+using MesApp.Core.Localization;
using MesApp.Infrastructure;
+using Microsoft.EntityFrameworkCore;
namespace MesApp.Api.Services;
@@ -10,20 +15,22 @@ namespace MesApp.Api.Services;
/// 変更は必ず本サービス経由で行い、遷移を として残す。
///
/// SaveChangesは呼び出し側が行う(LotStatusServiceと同じ規約)。
+/// 変更のたびに Webhook work-order.status-changed を同じトランザクションで積む(Spec.md 3.8 Webhook)。
///
-public class WorkOrderStatusService(MesAppDbContext db)
+public class WorkOrderStatusService(MesAppDbContext db, WebhookPublisher webhooks)
{
///
/// 状態を変更し、遷移を履歴に残す。現在値と同じ場合は何もしない
///
- public void ChangeStatus(
+ public async Task ChangeStatusAsync(
WorkOrder workOrder, WorkOrderStatus to, WorkOrderStatusChangeSource source,
- string? userId, string? note = null)
+ string? userId, string? note = null, CancellationToken ct = default)
{
if (workOrder.Status == to)
{
return;
}
+ var from = workOrder.Status;
db.WorkOrderStatusHistories.Add(new WorkOrderStatusHistory
{
WorkOrderId = workOrder.Id,
@@ -34,5 +41,17 @@ public void ChangeStatus(
ChangedByUserId = userId,
});
workOrder.Status = to;
+
+ await webhooks.EnqueueAsync(WebhookEventTypes.WorkOrderStatusChanged, async c =>
+ {
+ var codes = await db.WorkOrders.AsNoTracking()
+ .Where(w => w.Id == workOrder.Id)
+ .Select(w => new { w.ManufacturingOrder!.OrderNo, ProductCode = w.Product!.Code, ProcessCode = w.Process!.Code })
+ .FirstAsync(c);
+ // 送る文は保存される値なので訳さない(区分は原文の表示名)
+ return ($"作業指示 {workOrder.WorkOrderNo} の状態が「{EnumLabels.OriginalOf(from)}」から「{EnumLabels.OriginalOf(to)}」になりました。",
+ new WorkOrderStatusChangedData(codes.OrderNo, workOrder.WorkOrderNo, workOrder.RoutingSequence,
+ codes.ProductCode, codes.ProcessCode, from, to));
+ }, ct);
}
}
diff --git a/src/MesApp.Api/appsettings.json b/src/MesApp.Api/appsettings.json
index 6e5aa49..e27ee98 100644
--- a/src/MesApp.Api/appsettings.json
+++ b/src/MesApp.Api/appsettings.json
@@ -10,6 +10,17 @@
"RefreshTokenLifetimeHours": 12,
"SigningKeyFile": "jwt-signing.key"
},
+ "DataProtection": {
+ "KeysDirectory": "dataprotection-keys"
+ },
+ "Webhooks": {
+ "WorkerEnabled": true,
+ "PollIntervalSeconds": 5,
+ "TimeoutSeconds": 10,
+ "MaxAttempts": 8,
+ "BatchSize": 20,
+ "LockTimeoutSeconds": 300
+ },
"Audit": {
"RetentionYears": 5
},
diff --git a/src/MesApp.Client.Web/Layout/NavMenu.razor b/src/MesApp.Client.Web/Layout/NavMenu.razor
index 277121f..3474a13 100644
--- a/src/MesApp.Client.Web/Layout/NavMenu.razor
+++ b/src/MesApp.Client.Web/Layout/NavMenu.razor
@@ -38,6 +38,7 @@
@L["監査ログ"]
@L["フォルダ連携"]
@L["APIキー"]
+ @L["Webhook"]
@L["このアプリについて"]
diff --git a/src/MesApp.Client.Web/Pages/Home.razor b/src/MesApp.Client.Web/Pages/Home.razor
index fccc5e9..0829998 100644
--- a/src/MesApp.Client.Web/Pages/Home.razor
+++ b/src/MesApp.Client.Web/Pages/Home.razor
@@ -7,6 +7,10 @@
@L["ダッシュボード"]
+
+
+
+
diff --git a/src/MesApp.Client.Web/Pages/Webhooks/DeliveriesTab.razor b/src/MesApp.Client.Web/Pages/Webhooks/DeliveriesTab.razor
new file mode 100644
index 0000000..e147a7e
--- /dev/null
+++ b/src/MesApp.Client.Web/Pages/Webhooks/DeliveriesTab.razor
@@ -0,0 +1,159 @@
+@using MesApp.Core.Contracts.Integration
+@inject HttpClient Http
+
+@* Webhook の送信の記録(Spec.md 3.8 Webhook。docs-dev/WebhookTasks.md WHK-02)。
+ 試行の結果を見て、止まった送信を手で再送する *@
+
+
+
+
+
+
+
+
+
+ @L["失敗した送信は間隔を空けて自動で再送し、回数が尽きると止まります。止まった送信は、受け側を直してから再送してください。"]
+ @L["新しい順に最大{0}件を表示します。", Limit]
+
+
+
+
+ @if (_deliveries is null)
+ {
+
@L["読み込み中..."]
+ }
+ else if (_deliveries.Count == 0)
+ {
+
@L["送信の記録はありません。"]
+ }
+ else
+ {
+ @* 列が多いので、狭い画面では表だけを横にスクロールさせる *@
+
+
+
+ | sequence | @L["発生日時"] | @L["送信先の用途"] | @L["イベント"] | @L["状態"] | @L["試行回数"] | @L["最後の試行"] | @L["結果"] | |
+
+
+ @foreach (var d in _deliveries)
+ {
+
+ | @d.Sequence |
+ @Format(d.OccurredAt) |
+ @d.SubscriptionName |
+ @d.EventType @d.Summary |
+
+ @EnumLabels.Of(d.State)
+ @if (d.State == WebhookDeliveryState.Pending && d.Attempts > 0)
+ {
+ @L["次の再送:{0}", Format(d.NextAttemptAt)]
+ }
+ |
+ @d.Attempts |
+ @Format(d.LastAttemptAt) |
+ @* エラーの文は送ったときのまま残している(訳さない)。状態コードは文の先頭に入っているので重ねない *@
+ @(d.LastError ?? (d.LastStatusCode is { } code ? $"HTTP {code}" : string.Empty)) |
+
+ @if (d.State == WebhookDeliveryState.Failed)
+ {
+
+ }
+ |
+
+ }
+
+
+
+ }
+
+
+@code {
+ private const int Limit = 200;
+
+ private List
_subscriptions = [];
+ private List? _deliveries;
+ private int? _subscriptionId;
+ private WebhookDeliveryState? _state;
+ private string? _error;
+ private string? _message;
+ private bool _busy;
+
+ protected override async Task OnInitializedAsync()
+ {
+ try
+ {
+ _subscriptions = await Http.GetFromJsonAsync>("api/webhook-subscriptions") ?? [];
+ }
+ catch (HttpRequestException)
+ {
+ _error = L["Webhook の送信先の一覧を取得できませんでした。"];
+ }
+ await LoadAsync();
+ }
+
+ private async Task LoadAsync()
+ {
+ var query = $"api/webhook-deliveries?limit={Limit}";
+ if (_subscriptionId is { } sid)
+ {
+ query += $"&subscriptionId={sid}";
+ }
+ if (_state is { } state)
+ {
+ query += $"&state={(int)state}";
+ }
+ try
+ {
+ _deliveries = await Http.GetFromJsonAsync>(query) ?? [];
+ }
+ catch (HttpRequestException)
+ {
+ _error = L["Webhook の送信の記録を取得できませんでした。"];
+ }
+ }
+
+ private async Task ResendAsync(WebhookDeliveryResponse d)
+ {
+ _error = null;
+ _message = null;
+ _busy = true;
+ try
+ {
+ var response = await Http.PostAsync($"api/webhook-deliveries/{d.Id}/resend", null);
+ if (await response.ReadErrorAsync(L["再送に失敗しました。"]) is { } error)
+ {
+ _error = error;
+ return;
+ }
+ _message = L["sequence {0} を送信待ちに戻しました。まもなく送ります。", d.Sequence];
+ await LoadAsync();
+ }
+ finally
+ {
+ _busy = false;
+ }
+ }
+
+ private static string Format(DateTimeOffset? at) => at?.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss") ?? "-";
+}
diff --git a/src/MesApp.Client.Web/Pages/Webhooks/SubscriptionsTab.razor b/src/MesApp.Client.Web/Pages/Webhooks/SubscriptionsTab.razor
new file mode 100644
index 0000000..c3a30e5
--- /dev/null
+++ b/src/MesApp.Client.Web/Pages/Webhooks/SubscriptionsTab.razor
@@ -0,0 +1,320 @@
+@using MesApp.Core.Contracts.Integration
+@inject HttpClient Http
+
+@* Webhook の送信先(Spec.md 3.8 Webhook。docs-dev/WebhookTasks.md WHK-01)。
+ 秘密の値は登録・再発行の直後にしか表示できない(APIキーと同じ) *@
+
+
+
+@if (_secret is not null)
+{
+
+
@L["署名の秘密の値"]
+
@L["この値は今しか表示できません。受け側の設定に、今すぐ写してください。"]
+ @* 値は長く区切りが無いので、どこででも折り返す *@
+
@_secret.PlainSecret
+
@L["受け側はこの値で本文の署名(HMAC-SHA256)を確かめ、MES から送られたことを確認します。"]
+
+
+
+
+}
+
+
+
@(_editingId is null ? L["送信先を登録する"] : L["送信先を変更する"])
+
+ @if (_url.Trim().StartsWith("http://", StringComparison.OrdinalIgnoreCase))
+ {
+
@L["http の送信先には、本文が暗号化されずに流れます。工場の中のネットワークだけで使う送信先にしてください。"]
+ }
+
+
+ @foreach (var type in WebhookEventTypes.All)
+ {
+
+ }
+
+
+
+ @if (_editingId is not null)
+ {
+
+ }
+
+
+
+
+
@L["登録済みの送信先"]
+ @if (_subscriptions is null)
+ {
+
@L["読み込み中..."]
+ }
+ else if (_subscriptions.Count == 0)
+ {
+
@L["登録した送信先はありません。"]
+ }
+ else
+ {
+ @* 列が多いので、狭い画面では表だけを横にスクロールさせる *@
+
+
+
+ | @L["用途"] | @L["送信先の URL"] | @L["通知するイベント"] | @L["秘密の値の先頭"] | @L["状態"] | @L["送れていない送信"] | @L["登録日時"] | |
+
+
+ @foreach (var s in _subscriptions)
+ {
+
+ | @s.Name |
+ @s.Url |
+ @string.Join(L["、"].Value, s.EventTypes.Select(LabelOf)) |
+ @s.SecretPrefix… |
+ @(s.IsActive ? L["有効"] : L["無効"]) |
+
+ @if (s.FailedCount > 0 || s.RetryingCount > 0)
+ {
+ @L["失敗中"]
+ }
+ @L["送信待ち {0}・再送待ち {1}・停止 {2}", s.PendingCount, s.RetryingCount, s.FailedCount]
+ |
+ @Format(s.CreatedAt) |
+
+ @* 再発行と削除は戻せないので、押してから確かめる二段階にする *@
+ @if (_confirm == (s.Id, "rotate"))
+ {
+
+
+ }
+ else if (_confirm == (s.Id, "delete"))
+ {
+
+
+ }
+ else
+ {
+
+
+
+
+ }
+ |
+
+ }
+
+
+
+ }
+
+
+@code {
+ private List? _subscriptions;
+ private CreatedWebhookSecretResponse? _secret;
+ private int? _editingId;
+ private string _name = string.Empty;
+ private string _url = string.Empty;
+ private bool _isActive = true;
+ private HashSet _eventTypes = [];
+ private (int Id, string Action)? _confirm;
+ private string? _error;
+ private string? _message;
+ private bool _busy;
+
+ protected override Task OnInitializedAsync() => LoadAsync();
+
+ private async Task LoadAsync()
+ {
+ try
+ {
+ _subscriptions = await Http.GetFromJsonAsync>("api/webhook-subscriptions") ?? [];
+ }
+ catch (HttpRequestException)
+ {
+ _error = L["Webhook の送信先の一覧を取得できませんでした。"];
+ }
+ }
+
+ private void Toggle(string type, bool on)
+ {
+ if (on)
+ {
+ _eventTypes.Add(type);
+ }
+ else
+ {
+ _eventTypes.Remove(type);
+ }
+ }
+
+ private void Edit(WebhookSubscriptionResponse s)
+ {
+ _editingId = s.Id;
+ _name = s.Name;
+ _url = s.Url;
+ _isActive = s.IsActive;
+ _eventTypes = s.EventTypes.ToHashSet();
+ _error = null;
+ _message = null;
+ }
+
+ private void ResetForm()
+ {
+ _editingId = null;
+ _name = string.Empty;
+ _url = string.Empty;
+ _isActive = true;
+ _eventTypes = [];
+ }
+
+ private async Task SaveAsync()
+ {
+ _error = null;
+ _message = null;
+ _busy = true;
+ try
+ {
+ // 画面の一覧の順で送る(API 側でも並べ直す)
+ var request = new SaveWebhookSubscriptionRequest(
+ _name, _url, WebhookEventTypes.All.Where(_eventTypes.Contains).ToList(), _isActive);
+ if (_editingId is { } id)
+ {
+ var response = await Http.PutAsJsonAsync($"api/webhook-subscriptions/{id}", request);
+ if (await response.ReadErrorAsync(L["Webhook の送信先の変更に失敗しました。"]) is { } error)
+ {
+ _error = error;
+ return;
+ }
+ _message = L["「{0}」を変更しました。", request.Name.Trim()];
+ }
+ else
+ {
+ var response = await Http.PostAsJsonAsync("api/webhook-subscriptions", request);
+ if (await response.ReadErrorAsync(L["Webhook の送信先の登録に失敗しました。"]) is { } error)
+ {
+ _error = error;
+ return;
+ }
+ _secret = await response.Content.ReadFromJsonAsync();
+ }
+ ResetForm();
+ await LoadAsync();
+ }
+ finally
+ {
+ _busy = false;
+ }
+ }
+
+ private async Task RotateAsync(WebhookSubscriptionResponse s)
+ {
+ _error = null;
+ _message = null;
+ _busy = true;
+ try
+ {
+ var response = await Http.PostAsync($"api/webhook-subscriptions/{s.Id}/rotate-secret", null);
+ if (await response.ReadErrorAsync(L["秘密の値の再発行に失敗しました。"]) is { } error)
+ {
+ _error = error;
+ return;
+ }
+ _confirm = null;
+ _secret = await response.Content.ReadFromJsonAsync();
+ await LoadAsync();
+ }
+ finally
+ {
+ _busy = false;
+ }
+ }
+
+ private async Task DeleteAsync(WebhookSubscriptionResponse s)
+ {
+ _error = null;
+ _message = null;
+ _busy = true;
+ try
+ {
+ var response = await Http.DeleteAsync($"api/webhook-subscriptions/{s.Id}");
+ if (await response.ReadErrorAsync(L["Webhook の送信先の削除に失敗しました。"]) is { } error)
+ {
+ _error = error;
+ return;
+ }
+ _confirm = null;
+ if (_editingId == s.Id)
+ {
+ ResetForm();
+ }
+ _message = L["「{0}」を削除しました。", s.Name];
+ await LoadAsync();
+ }
+ finally
+ {
+ _busy = false;
+ }
+ }
+
+ private async Task TestAsync(WebhookSubscriptionResponse s)
+ {
+ _error = null;
+ _message = null;
+ _busy = true;
+ try
+ {
+ var response = await Http.PostAsync($"api/webhook-subscriptions/{s.Id}/test", null);
+ if (await response.ReadErrorAsync(L["テスト送信に失敗しました。"]) is { } error)
+ {
+ _error = error;
+ return;
+ }
+ var result = await response.Content.ReadFromJsonAsync();
+ if (result?.State == WebhookDeliveryState.Delivered)
+ {
+ _message = L["「{0}」へのテスト送信が届きました(HTTP {1})。", s.Name, result.LastStatusCode ?? 0];
+ }
+ else
+ {
+ // エラーの文は送ったときのまま(訳さない)。状態コードは文の先頭に入っている
+ _error = L["「{0}」へのテスト送信が届きませんでした:{1}", s.Name, result?.LastError ?? string.Empty];
+ }
+ await LoadAsync();
+ }
+ finally
+ {
+ _busy = false;
+ }
+ }
+
+ private string LabelOf(string type) => type switch
+ {
+ WebhookEventTypes.ProductionResultCreated => L["生産実績の記録"],
+ WebhookEventTypes.ProductionResultCorrected => L["生産実績の訂正"],
+ WebhookEventTypes.WorkOrderStatusChanged => L["作業指示の状態の変化"],
+ WebhookEventTypes.ManufacturingOrderStatusChanged => L["製造指図の完了・取消"],
+ WebhookEventTypes.LotStatusChanged => L["ロットの状態の変化"],
+ WebhookEventTypes.NonconformanceCreated => L["不適合の起票"],
+ WebhookEventTypes.EquipmentStopped => L["設備の停止・故障"],
+ _ => type, // 訳さない(版を戻したときに残った、今の版が知らない種類)
+ };
+
+ private static string Format(DateTimeOffset? at) => at?.ToLocalTime().ToString("yyyy-MM-dd HH:mm") ?? "-";
+}
diff --git a/src/MesApp.Client.Web/Pages/Webhooks/WebhookFailureNotice.razor b/src/MesApp.Client.Web/Pages/Webhooks/WebhookFailureNotice.razor
new file mode 100644
index 0000000..ec238f3
--- /dev/null
+++ b/src/MesApp.Client.Web/Pages/Webhooks/WebhookFailureNotice.razor
@@ -0,0 +1,33 @@
+@using MesApp.Core.Contracts.Integration
+@inject HttpClient Http
+
+@* Webhook の失敗中の送信先の知らせ(Spec.md 3.8 Webhook。WHK-02)。
+ 失敗が続いても送信先を自動で止めない代わりに、ダッシュボードで気付けるようにする。
+ システム管理者のダッシュボードにだけ置く(一覧の API がシステム管理者専用のため)。
+ 取れなくてもダッシュボードは開けたままにする(何も出さない) *@
+
+@if (_failing.Count > 0)
+{
+
+ @L["Webhook の送信に失敗している送信先があります:{0}", string.Join(L["、"].Value, _failing.Select(s => s.Name))]
+ @* 送信先のタブ(失敗中と送れていない件数が出る)が開く *@
+
@L["送信先を見る"]
+
+}
+
+@code {
+ private List _failing = [];
+
+ protected override async Task OnInitializedAsync()
+ {
+ try
+ {
+ var all = await Http.GetFromJsonAsync>("api/webhook-subscriptions") ?? [];
+ _failing = all.Where(s => s.FailedCount > 0 || s.RetryingCount > 0).ToList();
+ }
+ catch (HttpRequestException)
+ {
+ // ダッシュボードの本体を優先する(知らせが出ないだけ)
+ }
+ }
+}
diff --git a/src/MesApp.Client.Web/Pages/WebhooksPage.razor b/src/MesApp.Client.Web/Pages/WebhooksPage.razor
new file mode 100644
index 0000000..93cb188
--- /dev/null
+++ b/src/MesApp.Client.Web/Pages/WebhooksPage.razor
@@ -0,0 +1,34 @@
+@page "/webhooks"
+@attribute [Authorize(Roles = MesRoles.SystemAdmin)]
+
+@* Webhook(Spec.md 3.8 Webhook。docs-dev/WebhookTasks.md)。
+ 送信先は業務データの持ち出し口になるので、システム管理者専用(一覧の参照も) *@
+
+@L["Webhook - Parallel Factory MES"]
+
+@L["Webhook"]
+
+ @L["実績の記録・状態の変化・不適合・設備の停止などの出来事を、登録した URL へ知らせます。"]
+ @L["通知は読みに行くきっかけです。正しい今の値は連携API で取りに行ってください。"]
+
+
+
+
+
+
+
+@switch (_tab)
+{
+ case "subscriptions":
+
+ break;
+ case "deliveries":
+
+ break;
+}
+
+@code {
+ private string _tab = "subscriptions";
+
+ private string TabClass(string tab) => _tab == tab ? "active" : string.Empty;
+}
diff --git a/src/MesApp.Client.Web/Shared/UiText.en.resx b/src/MesApp.Client.Web/Shared/UiText.en.resx
index ce82e7c..02e41c2 100644
--- a/src/MesApp.Client.Web/Shared/UiText.en.resx
+++ b/src/MesApp.Client.Web/Shared/UiText.en.resx
@@ -4575,4 +4575,184 @@
This list does not refresh automatically. Press "Update" to load the latest status. For equipment that collects status from equipment events, a notice appears when no events have been received for a while (10 minutes by default).
+
+ Webhooks
+
+
+ Signing secret
+
+
+ This value is shown only now. Copy it into the receiver's settings right away.
+
+
+ The receiver uses this value to verify the body's signature (HMAC-SHA256) and confirm that it was sent by the MES.
+
+
+ Register a destination
+
+
+ Edit the destination
+
+
+ e.g. Nonconformance alerts to the team leaders' chat
+
+
+ Destination URL
+
+
+ Active (when inactive, new events are not sent)
+
+
+ Bodies sent to an http destination are not encrypted. Use it only for destinations on the factory's internal network.
+
+
+ Events to notify
+
+
+ Registered destinations
+
+
+ No destinations are registered.
+
+
+ Secret prefix
+
+
+ Registered at
+
+
+ Reissue (the old value stops working)
+
+
+ Delete (pending and past deliveries are deleted too)
+
+
+ Edit
+
+
+ Reissue secret
+
+
+ Could not load the webhook destinations.
+
+
+ Failed to update the webhook destination.
+
+
+ Updated "{0}".
+
+
+ Failed to register the webhook destination.
+
+
+ Failed to reissue the secret.
+
+
+ Failed to delete the webhook destination.
+
+
+ Deleted "{0}".
+
+
+ Production result recorded
+
+
+ Production result corrected
+
+
+ Work order status changed
+
+
+ Manufacturing order completed or canceled
+
+
+ Lot status changed
+
+
+ Nonconformance raised
+
+
+ Equipment stopped or failed
+
+
+ Webhooks - Parallel Factory MES
+
+
+ Sends events such as recorded results, status changes, nonconformances and equipment stops to the URLs you register.
+
+
+ A notification is a cue to fetch data. Get the correct current values from the integration API.
+
+
+ Destinations
+
+
+ Reload
+
+
+ Failed deliveries are retried automatically at increasing intervals and stop when the attempts run out. Fix the receiver, then resend stopped deliveries.
+
+
+ Shows up to {0} entries, newest first.
+
+
+ There are no deliveries.
+
+
+ Event
+
+
+ Attempts
+
+
+ Last attempt
+
+
+ Next retry: {0}
+
+
+ Resend
+
+
+ Could not load the webhook deliveries.
+
+
+ Failed to resend.
+
+
+ Moved sequence {0} back to pending. It will be sent shortly.
+
+
+ Undelivered
+
+
+ Failing
+
+
+ Pending {0} / Retrying {1} / Stopped {2}
+
+
+ Send test
+
+
+ Failed to send the test.
+
+
+ The test to "{0}" was delivered (HTTP {1}).
+
+
+ The test to "{0}" was not delivered: {1}
+
+
+ Some webhook destinations are failing: {0}
+
+
+ View destinations
+
+
+ Deliveries
+
+
+ Destination
+
diff --git a/src/MesApp.Client.Web/_Imports.razor b/src/MesApp.Client.Web/_Imports.razor
index 5d64afd..724b508 100644
--- a/src/MesApp.Client.Web/_Imports.razor
+++ b/src/MesApp.Client.Web/_Imports.razor
@@ -15,6 +15,7 @@
@using MesApp.Client.Web.Pages.Masters
@using MesApp.Client.Web.Pages.Masters.Products
@using MesApp.Client.Web.Pages.Maintenance
+@using MesApp.Client.Web.Pages.Webhooks
@using MesApp.Client.Web.Pages.Dashboard
@using MesApp.Client.Web.Pages.ProductionRecord
@using MesApp.Client.Web.Pages.ProductionPlan
diff --git a/src/MesApp.Core/Constants/WebhookEventTypes.cs b/src/MesApp.Core/Constants/WebhookEventTypes.cs
new file mode 100644
index 0000000..9520a74
--- /dev/null
+++ b/src/MesApp.Core/Constants/WebhookEventTypes.cs
@@ -0,0 +1,48 @@
+namespace MesApp.Core.Constants;
+
+///
+/// Webhook のイベントの種類(Spec.md 3.8 Webhook。docs-dev/WebhookTasks.md の「v1 のイベント」)。
+///
+/// 名前は「対象.出来事」。外部との約束なので、名前は消さない・変えない(CSV の列の約束と同じ)。
+/// 送信先の購読(API)と画面の選択肢で同じ一覧を使う。
+///
+///
+public static class WebhookEventTypes
+{
+ /// 生産実績を記録した(B-40-10)
+ public const string ProductionResultCreated = "production-result.created";
+
+ /// 生産実績を訂正した(B-70-30-01)
+ public const string ProductionResultCorrected = "production-result.corrected";
+
+ /// 作業指示の状態が変わった
+ public const string WorkOrderStatusChanged = "work-order.status-changed";
+
+ /// 製造指図が完了・取消になった
+ public const string ManufacturingOrderStatusChanged = "manufacturing-order.status-changed";
+
+ /// ロットの状態が変わった(保留・解除・廃棄など)
+ public const string LotStatusChanged = "lot.status-changed";
+
+ /// 不適合を起票した
+ public const string NonconformanceCreated = "nonconformance.created";
+
+ /// 設備が停止・故障の区間に入った
+ public const string EquipmentStopped = "equipment.stopped";
+
+ /// 購読できる種類の一覧(画面に出す順)
+ public static IReadOnlyList All { get; } =
+ [
+ ProductionResultCreated,
+ ProductionResultCorrected,
+ WorkOrderStatusChanged,
+ ManufacturingOrderStatusChanged,
+ LotStatusChanged,
+ NonconformanceCreated,
+ EquipmentStopped,
+ ];
+
+ /// 購読の保存形式(カンマ区切り)を一覧に戻す。知らない名前は捨てない(版を戻したときに購読を失わないため)
+ public static List Split(string stored) =>
+ stored.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
+}
diff --git a/src/MesApp.Core/Contracts/Integration/WebhookDtos.cs b/src/MesApp.Core/Contracts/Integration/WebhookDtos.cs
new file mode 100644
index 0000000..592780b
--- /dev/null
+++ b/src/MesApp.Core/Contracts/Integration/WebhookDtos.cs
@@ -0,0 +1,54 @@
+namespace MesApp.Core.Contracts.Integration;
+
+/// Webhook の送信先の一覧の1行(Spec.md 3.8 Webhook)。秘密の値は含めない
+/// 購読するイベントの種類(WebhookEventTypes の名前)
+/// 秘密の値の先頭(例 whsec_AbCdEf)。受け側に設定した値と見分けるためだけに使う
+/// まだ一度も送っていない送信待ち
+/// 失敗して再送を待っている送信
+/// 再送が尽きて止まった送信(手で再送するまで送らない)
+public record WebhookSubscriptionResponse(
+ int Id,
+ string Name,
+ string Url,
+ List EventTypes,
+ string SecretPrefix,
+ bool IsActive,
+ DateTimeOffset CreatedAt,
+ DateTimeOffset? UpdatedAt,
+ DateTimeOffset? SecretRotatedAt,
+ int PendingCount = 0,
+ int RetryingCount = 0,
+ int FailedCount = 0);
+
+/// Webhook の送信先の登録・変更(秘密の値は変えない。変えるときは再発行)
+/// 用途(例:班長チャットへの不適合通知)
+/// 送信先の URL(http・https)
+/// 購読するイベントの種類(1つ以上)
+/// 無効にすると新しい出来事を送らない
+public record SaveWebhookSubscriptionRequest(string Name, string Url, List EventTypes, bool IsActive);
+
+/// 登録・秘密の再発行の結果。 はこの応答でしか返さない(再表示できない)
+public record CreatedWebhookSecretResponse(WebhookSubscriptionResponse Subscription, string PlainSecret);
+
+/// 送信の記録の1行(Spec.md 3.8 Webhook。WHK-02)
+/// 通知の sequence(送信待ちの ID)
+/// 通知の id(受け側が重複を捨てるのに使う)
+/// Pending・Delivered・Failed
+/// 次に送ってよい日時(送信待ちのときだけ意味がある)
+/// 最後の試行のエラーの先頭(送ったときの値のまま。訳さない)
+public record WebhookDeliveryResponse(
+ long Id,
+ int SubscriptionId,
+ string SubscriptionName,
+ long Sequence,
+ Guid EventId,
+ string EventType,
+ string Summary,
+ DateTimeOffset OccurredAt,
+ MesApp.Core.Entities.WebhookDeliveryState State,
+ int Attempts,
+ DateTimeOffset NextAttemptAt,
+ DateTimeOffset? LastAttemptAt,
+ int? LastStatusCode,
+ string? LastError,
+ DateTimeOffset? DeliveredAt);
diff --git a/src/MesApp.Core/Contracts/Integration/WebhookPayloads.cs b/src/MesApp.Core/Contracts/Integration/WebhookPayloads.cs
new file mode 100644
index 0000000..a2d6c28
--- /dev/null
+++ b/src/MesApp.Core/Contracts/Integration/WebhookPayloads.cs
@@ -0,0 +1,123 @@
+using MesApp.Core.Constants;
+using MesApp.Core.Entities;
+
+namespace MesApp.Core.Contracts.Integration;
+
+///
+/// Webhook の本文の data の形(Spec.md 3.8 Webhook。docs-dev/WebhookTasks.md WHK-03)。
+///
+/// 受け側との約束。項目は消さない・名前と型を変えない・null になり得るようにしない・列挙の値を消さない。
+/// 足すのはよい(受け側は知らない項目を読み飛ばす)。形は tests/MesApp.Api.Tests/WebhookContract.v1.json に固定してある。
+/// 項目名は camelCase、区分・状態は列挙の名前(英語)で送る。コード・番号で指し、内部 ID は送らない
+/// (例外は、連携API のフィードの位置と同じ値の )。
+/// 通知は薄く保つ。正しい今の値は連携API のフィードで取りに行ってもらう(通知は「読みに行くきっかけ」)
+///
+///
+public static class WebhookPayloads
+{
+ /// 種類ごとの data の型。発行(WebhookPublisher)がこれと違う型を渡すと例外にする
+ public static IReadOnlyDictionary DataTypes { get; } = new Dictionary
+ {
+ [WebhookEventTypes.ProductionResultCreated] = typeof(ProductionResultCreatedData),
+ [WebhookEventTypes.ProductionResultCorrected] = typeof(ProductionResultCorrectedData),
+ [WebhookEventTypes.WorkOrderStatusChanged] = typeof(WorkOrderStatusChangedData),
+ [WebhookEventTypes.ManufacturingOrderStatusChanged] = typeof(ManufacturingOrderStatusChangedData),
+ [WebhookEventTypes.LotStatusChanged] = typeof(LotStatusChangedData),
+ [WebhookEventTypes.NonconformanceCreated] = typeof(NonconformanceCreatedData),
+ [WebhookEventTypes.EquipmentStopped] = typeof(EquipmentStoppedData),
+ };
+}
+
+///
+/// 生産実績を記録した(production-result.created。B-40-10)。画面・実績CSV・連携API のどれから記録しても出る。
+/// 実績の内部 ID は保存するまで決まらないので含めない(業務と同じトランザクションで積むため)。
+/// 実績の全項目は連携API の生産実績の取得(production-results)で読む
+///
+/// 製造指図番号
+/// 工程順序
+/// 産出ロット(最終工程の実績だけ)
+public record ProductionResultCreatedData(
+ string OrderNo,
+ string WorkOrderNo,
+ int Sequence,
+ string ProductCode,
+ string ProcessCode,
+ decimal GoodQuantity,
+ decimal DefectQuantity,
+ decimal ScrapQuantity,
+ decimal ReworkQuantity,
+ DateTimeOffset StartedAt,
+ DateTimeOffset? EndedAt,
+ string? OutputLotNumber);
+
+/// 生産実績を訂正した(production-result.corrected。B-70-30-01)。訂正の一覧は production-result-corrections で読む
+/// 訂正した実績(連携API の生産実績の id と同じ値)
+public record ProductionResultCorrectedData(
+ long ProductionResultId,
+ string OrderNo,
+ string WorkOrderNo,
+ int Sequence,
+ decimal BeforeGoodQuantity,
+ decimal BeforeDefectQuantity,
+ decimal BeforeScrapQuantity,
+ decimal BeforeReworkQuantity,
+ decimal AfterGoodQuantity,
+ decimal AfterDefectQuantity,
+ decimal AfterScrapQuantity,
+ decimal AfterReworkQuantity,
+ string Reason);
+
+/// 作業指示の状態が変わった(work-order.status-changed)。差立・着手・完了・承認・取消のすべて
+public record WorkOrderStatusChangedData(
+ string OrderNo,
+ string WorkOrderNo,
+ int Sequence,
+ string ProductCode,
+ string ProcessCode,
+ WorkOrderStatus FromStatus,
+ WorkOrderStatus ToStatus);
+
+/// 製造指図が完了・取消になった(manufacturing-order.status-changed)。承認・発行などの途中の変化は v1 では送らない
+public record ManufacturingOrderStatusChangedData(
+ string OrderNo,
+ ManufacturingOrderType OrderType,
+ string ProductCode,
+ decimal Quantity,
+ ManufacturingOrderStatus FromStatus,
+ ManufacturingOrderStatus ToStatus);
+
+/// ロットの在庫ステータスが変わった(lot.status-changed。保留・解除・検査待ち・不良・廃棄予定など)
+/// 変更の契機(手動操作/検査/不適合/受入取消)
+/// 理由(入力されたもの)
+public record LotStatusChangedData(
+ string LotNumber,
+ string ProductCode,
+ LotStockStatus FromStatus,
+ LotStockStatus ToStatus,
+ LotStatusChangeSource Source,
+ string? Reason);
+
+/// 不適合を起票した(nonconformance.created。C-30-10)。検査の不合格からの自動起票でも出る
+/// 発生源(工程内・受入・検査など)
+public record NonconformanceCreatedData(
+ string ReportNo,
+ NonconformanceSource Source,
+ string? LotNumber,
+ string? ProductCode,
+ string? WorkOrderNo);
+
+///
+/// 設備が停止・故障の区間に入った(equipment.stopped。E-20-10-03)。手入力・実績CSV・設備イベントのどれでも出る。
+/// 手入力・CSV は終わった区間を後から登録することが多いので、 が入っていることがある
+///
+/// 停止原因(設備イベントで対応表から引けなければ null。後から追記される)
+/// 設備イベントのアラーム番号(設備イベントのときだけ)
+public record EquipmentStoppedData(
+ string EquipmentAssetNo,
+ EquipmentLogStatus Status,
+ DateTimeOffset StartedAt,
+ DateTimeOffset? EndedAt,
+ string? StopCause,
+ string? AlarmCode,
+ EquipmentLogSource Source,
+ string? WorkOrderNo);
diff --git a/src/MesApp.Core/Entities/Enums.cs b/src/MesApp.Core/Entities/Enums.cs
index 439be3f..933610f 100644
--- a/src/MesApp.Core/Entities/Enums.cs
+++ b/src/MesApp.Core/Entities/Enums.cs
@@ -548,6 +548,17 @@ public enum EquipmentEventResult
Rejected,
}
+/// Webhook の送信の状態(Spec.md 3.8 Webhook。WebhookDelivery)
+public enum WebhookDeliveryState
+{
+ /// 送信待ち(再送待ちを含む)
+ Pending,
+ /// 送信済み(送信先が 2xx を返した)
+ Delivered,
+ /// 失敗(再送の回数が尽きた・再送しない応答だった)
+ Failed,
+}
+
///
/// 保全部品の管理区分(Spec.md 5.1 EquipmentPart。E-10-10-01)。
/// 資産管理部品(金型など設備の一部として資産計上するもの)と、
diff --git a/src/MesApp.Core/Entities/Webhook.cs b/src/MesApp.Core/Entities/Webhook.cs
new file mode 100644
index 0000000..c7a8f8f
--- /dev/null
+++ b/src/MesApp.Core/Entities/Webhook.cs
@@ -0,0 +1,116 @@
+namespace MesApp.Core.Entities;
+
+///
+/// Webhook の送信先(Spec.md 3.8 Webhook。docs-dev/WebhookTasks.md WHK-01)。
+///
+/// 購読するイベントの種類を選び、その出来事が起きたら へ通知する。
+/// 秘密の値は署名(HMAC)に使うため、ハッシュではなく復号できる形(Data Protection で暗号化)で持つ。
+/// 平文は作成・再発行の応答でだけ返す。
+///
+///
+public class WebhookSubscription
+{
+ public int Id { get; set; }
+
+ /// 用途(例:班長チャットへの不適合通知)。一覧で見分けるための名前
+ public string Name { get; set; } = string.Empty;
+
+ /// 送信先の URL(http・https。工場 LAN 内の私設アドレスも許す)
+ public string Url { get; set; } = string.Empty;
+
+ /// 購読するイベントの種類(WebhookEventTypes の名前をカンマ区切り)
+ public string EventTypes { get; set; } = string.Empty;
+
+ /// 署名に使う秘密の値(Data Protection で暗号化したもの)
+ public string SecretProtected { get; set; } = string.Empty;
+
+ /// 秘密の値の先頭(例 whsec_AbCdEf)。受け側に設定した値と見分けるために残す。これだけでは署名できない
+ public string SecretPrefix { get; set; } = string.Empty;
+
+ /// 無効にすると、新しい出来事の送信待ちを作らない(作成済みの送信待ちはそのまま)
+ public bool IsActive { get; set; } = true;
+
+ public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
+
+ /// 作成した利用者(システム管理者)
+ public string? CreatedByUserId { get; set; }
+
+ public DateTimeOffset? UpdatedAt { get; set; }
+
+ /// 秘密の値を最後に再発行した日時
+ public DateTimeOffset? SecretRotatedAt { get; set; }
+
+ public List Deliveries { get; set; } = [];
+}
+
+///
+/// 送信待ちの出来事(Outbox。Spec.md 3.8 Webhook)。
+///
+/// 業務の変更と同じトランザクションで積み、常駐処理が後から送る(業務の処理の中で HTTP を呼ばない)。
+/// 業務が巻き戻れば、この行も残らない。 は通知の sequence(種類をまたいで増える。連番とは限らない)。
+/// 購読している送信先が無い出来事は積まない。7.6節の運用ログ(C 層)。
+///
+///
+public class WebhookOutbox
+{
+ public long Id { get; set; }
+
+ /// 通知の一意の ID(受け側が重複を捨てるのに使う。再送しても変わらない)
+ public Guid EventId { get; set; } = Guid.NewGuid();
+
+ /// イベントの種類(例 production-result.created)
+ public string EventType { get; set; } = string.Empty;
+
+ /// 本文の形の版(v1 は 1)
+ public int Version { get; set; } = 1;
+
+ /// 出来事が起きた日時
+ public DateTimeOffset OccurredAt { get; set; } = DateTimeOffset.UtcNow;
+
+ /// 人が読める1文(チャットへの転送などにそのまま使える)
+ public string Summary { get; set; } = string.Empty;
+
+ /// 本文の data(JSON)。共通の包み(id・sequence・type 等)は送るときに付ける
+ public string Payload { get; set; } = "{}";
+
+ public List Deliveries { get; set; } = [];
+}
+
+///
+/// 送信先ごとの送信(Spec.md 3.8 Webhook)。出来事を積むときに、購読している送信先の数だけ作る。
+/// 試行の結果(状態コード・エラー)を残し、再送の時刻を持つ。7.6節の運用ログ(C 層)
+///
+public class WebhookDelivery
+{
+ public long Id { get; set; }
+
+ public long OutboxId { get; set; }
+ public WebhookOutbox? Outbox { get; set; }
+
+ public int SubscriptionId { get; set; }
+ public WebhookSubscription? Subscription { get; set; }
+
+ public WebhookDeliveryState State { get; set; } = WebhookDeliveryState.Pending;
+
+ /// 試行した回数
+ public int Attempts { get; set; }
+
+ ///
+ /// 次に送ってよい日時(Unix 秒。再送の間隔を空けるため)。
+ /// SQLite は DateTimeOffset を SQL で比べられないので、取り出しの条件に使う時刻は数値で持つ( と同じ)
+ ///
+ public long NextAttemptAtUnixSeconds { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
+
+ /// 常駐処理が取り出した日時(Unix 秒。複数台で同じ行を二重に送らないため。古ければ取り出し直してよい)
+ public long? LockedAtUnixSeconds { get; set; }
+
+ public DateTimeOffset? LastAttemptAt { get; set; }
+
+ /// 最後の試行の HTTP 状態コード(接続できなかったときは null)
+ public int? LastStatusCode { get; set; }
+
+ /// 最後の試行のエラーの先頭(サーバーのログと同じく利用者向けに訳さない)
+ public string? LastError { get; set; }
+
+ public DateTimeOffset? DeliveredAt { get; set; }
+}
diff --git a/src/MesApp.Core/Localization/CoreText.en.resx b/src/MesApp.Core/Localization/CoreText.en.resx
index 82c49c2..d9a1e16 100644
--- a/src/MesApp.Core/Localization/CoreText.en.resx
+++ b/src/MesApp.Core/Localization/CoreText.en.resx
@@ -432,4 +432,13 @@
Rejected
+
+ Pending
+
+
+ Delivered
+
+
+ Failed
+
diff --git a/src/MesApp.Core/Localization/EnumLabels.cs b/src/MesApp.Core/Localization/EnumLabels.cs
index 5795dfa..01721ca 100644
--- a/src/MesApp.Core/Localization/EnumLabels.cs
+++ b/src/MesApp.Core/Localization/EnumLabels.cs
@@ -184,6 +184,9 @@ public static class EnumLabels
[EquipmentEventResult.Accepted] = "採用",
[EquipmentEventResult.Duplicate] = "重複",
[EquipmentEventResult.Rejected] = "拒否",
+ [WebhookDeliveryState.Pending] = "送信待ち",
+ [WebhookDeliveryState.Delivered] = "送信済み",
+ [WebhookDeliveryState.Failed] = "送信失敗",
[MaintenancePartCategory.Asset] = "資産管理部品",
[MaintenancePartCategory.Consumable] = "消耗品",
[MaintenanceCategory.Periodic] = "定期",
diff --git a/src/MesApp.Infrastructure/Configurations/SystemConfigurations.cs b/src/MesApp.Infrastructure/Configurations/SystemConfigurations.cs
index b840d7e..27d824a 100644
--- a/src/MesApp.Infrastructure/Configurations/SystemConfigurations.cs
+++ b/src/MesApp.Infrastructure/Configurations/SystemConfigurations.cs
@@ -60,6 +60,47 @@ public void Configure(EntityTypeBuilder e)
}
}
+internal sealed class WebhookSubscriptionConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder e)
+ {
+ e.Property(x => x.Name).HasMaxLength(100);
+ e.Property(x => x.Url).HasMaxLength(2000);
+ e.Property(x => x.EventTypes).HasMaxLength(1000);
+ e.Property(x => x.SecretProtected).HasMaxLength(1000);
+ e.Property(x => x.SecretPrefix).HasMaxLength(20);
+ // 送信先を消したら送信の記録も消す(運用ログ。消したことは監査ログに残る)
+ e.HasMany(x => x.Deliveries)
+ .WithOne(x => x.Subscription)
+ .HasForeignKey(x => x.SubscriptionId)
+ .OnDelete(DeleteBehavior.Cascade);
+ }
+}
+
+internal sealed class WebhookOutboxConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder e)
+ {
+ e.HasIndex(x => x.EventId).IsUnique();
+ e.Property(x => x.EventType).HasMaxLength(100);
+ e.Property(x => x.Summary).HasMaxLength(500);
+ e.HasMany(x => x.Deliveries)
+ .WithOne(x => x.Outbox)
+ .HasForeignKey(x => x.OutboxId)
+ .OnDelete(DeleteBehavior.Cascade);
+ }
+}
+
+internal sealed class WebhookDeliveryConfiguration : IEntityTypeConfiguration
+{
+ public void Configure(EntityTypeBuilder e)
+ {
+ // 常駐処理が「送信待ちで、送ってよい時刻を過ぎたもの」を引く
+ e.HasIndex(x => new { x.State, x.NextAttemptAtUnixSeconds });
+ e.Property(x => x.LastError).HasMaxLength(1000);
+ }
+}
+
internal sealed class AuditLogConfiguration : IEntityTypeConfiguration
{
public void Configure(EntityTypeBuilder e)
diff --git a/src/MesApp.Infrastructure/MesAppDbContext.cs b/src/MesApp.Infrastructure/MesAppDbContext.cs
index d3e9994..a09a149 100644
--- a/src/MesApp.Infrastructure/MesAppDbContext.cs
+++ b/src/MesApp.Infrastructure/MesAppDbContext.cs
@@ -13,6 +13,9 @@ public class MesAppDbContext(DbContextOptions options)
public DbSet RefreshTokens => Set();
public DbSet ApiKeys => Set();
public DbSet IntegrationRequests => Set();
+ public DbSet WebhookSubscriptions => Set();
+ public DbSet WebhookOutbox => Set();
+ public DbSet WebhookDeliveries => Set();
public DbSet AuditLogs => Set();
// マスタ系(Spec.md 5.1)
@@ -118,6 +121,7 @@ protected override void ConfigureConventions(ModelConfigurationBuilder builder)
builder.Properties().HaveConversion().HaveMaxLength(30);
builder.Properties().HaveConversion().HaveMaxLength(30);
builder.Properties().HaveConversion().HaveMaxLength(30);
+ builder.Properties().HaveConversion().HaveMaxLength(30);
builder.Properties().HaveConversion().HaveMaxLength(30);
builder.Properties().HaveConversion().HaveMaxLength(30);
builder.Properties().HaveConversion().HaveMaxLength(30);
diff --git a/src/MesApp.Infrastructure/Migrations/20261123100858_AddWebhooks.Designer.cs b/src/MesApp.Infrastructure/Migrations/20261123100858_AddWebhooks.Designer.cs
new file mode 100644
index 0000000..164bcc5
--- /dev/null
+++ b/src/MesApp.Infrastructure/Migrations/20261123100858_AddWebhooks.Designer.cs
@@ -0,0 +1,5212 @@
+//
+using System;
+using MesApp.Infrastructure;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+
+#nullable disable
+
+namespace MesApp.Infrastructure.Migrations
+{
+ [DbContext(typeof(MesAppDbContext))]
+ [Migration("20261123100858_AddWebhooks")]
+ partial class AddWebhooks
+ {
+ ///
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
+
+ modelBuilder.Entity("MesApp.Core.Entities.ApiKey", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("CreatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property("CreatedByUserId")
+ .HasColumnType("TEXT");
+
+ b.Property("ExpiresAt")
+ .HasColumnType("TEXT");
+
+ b.Property("KeyHash")
+ .IsRequired()
+ .HasMaxLength(64)
+ .HasColumnType("TEXT");
+
+ b.Property("LastUsedAt")
+ .HasColumnType("TEXT");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("TEXT");
+
+ b.Property("Prefix")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("TEXT");
+
+ b.Property("RevokedAt")
+ .HasColumnType("TEXT");
+
+ b.Property("UserId")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("KeyHash")
+ .IsUnique();
+
+ b.HasIndex("UserId");
+
+ b.ToTable("ApiKeys");
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.AppUser", b =>
+ {
+ b.Property("Id")
+ .HasColumnType("TEXT");
+
+ b.Property("AccessFailedCount")
+ .HasColumnType("INTEGER");
+
+ b.Property("ConcurrencyStamp")
+ .IsConcurrencyToken()
+ .HasColumnType("TEXT");
+
+ b.Property("CreatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property("Department")
+ .HasMaxLength(100)
+ .HasColumnType("TEXT");
+
+ b.Property("DisplayName")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property("Email")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property("EmailConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property("IsActive")
+ .HasColumnType("INTEGER");
+
+ b.Property("LockoutEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property("LockoutEnd")
+ .HasColumnType("TEXT");
+
+ b.Property("MustChangePassword")
+ .HasColumnType("INTEGER");
+
+ b.Property("NormalizedEmail")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property("NormalizedUserName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property("PasswordHash")
+ .HasColumnType("TEXT");
+
+ b.Property("PhoneNumber")
+ .HasColumnType("TEXT");
+
+ b.Property("PhoneNumberConfirmed")
+ .HasColumnType("INTEGER");
+
+ b.Property("SecurityStamp")
+ .HasColumnType("TEXT");
+
+ b.Property("ShiftId")
+ .HasColumnType("INTEGER");
+
+ b.Property("TwoFactorEnabled")
+ .HasColumnType("INTEGER");
+
+ b.Property("UserName")
+ .HasMaxLength(256)
+ .HasColumnType("TEXT");
+
+ b.Property("WorkCenterId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("NormalizedEmail")
+ .HasDatabaseName("EmailIndex");
+
+ b.HasIndex("NormalizedUserName")
+ .IsUnique()
+ .HasDatabaseName("UserNameIndex");
+
+ b.HasIndex("ShiftId");
+
+ b.HasIndex("WorkCenterId");
+
+ b.ToTable("AspNetUsers", (string)null);
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.AuditLog", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("Action")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("Category")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("Detail")
+ .HasColumnType("TEXT");
+
+ b.Property("IpAddress")
+ .HasColumnType("TEXT");
+
+ b.Property("RecordedOn")
+ .HasColumnType("TEXT");
+
+ b.Property("TargetId")
+ .HasMaxLength(100)
+ .HasColumnType("TEXT");
+
+ b.Property("TargetType")
+ .HasMaxLength(100)
+ .HasColumnType("TEXT");
+
+ b.Property("Timestamp")
+ .HasColumnType("TEXT");
+
+ b.Property("UserId")
+ .HasColumnType("TEXT");
+
+ b.Property("UserName")
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("RecordedOn");
+
+ b.HasIndex("Timestamp");
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("Category", "Action");
+
+ b.HasIndex("TargetType", "TargetId");
+
+ b.ToTable("AuditLogs");
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.BomItem", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("AlternativeGroup")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("ChildProductId")
+ .HasColumnType("INTEGER");
+
+ b.Property("IsAlternative")
+ .HasColumnType("INTEGER");
+
+ b.Property("MakeOrBuy")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("TEXT");
+
+ b.Property("ParentProductId")
+ .HasColumnType("INTEGER");
+
+ b.Property("QuantityPer")
+ .HasColumnType("TEXT");
+
+ b.Property("RoutingSequence")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ChildProductId");
+
+ b.HasIndex("ParentProductId", "ChildProductId")
+ .IsUnique();
+
+ b.ToTable("BomItems");
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.Checklist", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("Category")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("TEXT");
+
+ b.Property("Code")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("IsActive")
+ .HasColumnType("INTEGER");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Code")
+ .IsUnique();
+
+ b.ToTable("Checklists");
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.ChecklistItem", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("ChecklistId")
+ .HasColumnType("INTEGER");
+
+ b.Property("IsRequired")
+ .HasColumnType("INTEGER");
+
+ b.Property("Sequence")
+ .HasColumnType("INTEGER");
+
+ b.Property("Text")
+ .IsRequired()
+ .HasMaxLength(500)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ChecklistId");
+
+ b.ToTable("ChecklistItem");
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.ChecklistRecord", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("ChecklistId")
+ .HasColumnType("INTEGER");
+
+ b.Property("EquipmentId")
+ .HasColumnType("INTEGER");
+
+ b.Property("PerformedAt")
+ .HasColumnType("TEXT");
+
+ b.Property("PerformedByUserId")
+ .IsRequired()
+ .HasColumnType("TEXT");
+
+ b.Property("WorkOrderId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ChecklistId");
+
+ b.HasIndex("EquipmentId");
+
+ b.HasIndex("PerformedByUserId");
+
+ b.HasIndex("WorkOrderId");
+
+ b.ToTable("ChecklistRecords");
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.ChecklistResultItem", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("ChecklistItemId")
+ .HasColumnType("INTEGER");
+
+ b.Property("ChecklistRecordId")
+ .HasColumnType("INTEGER");
+
+ b.Property("IsChecked")
+ .HasColumnType("INTEGER");
+
+ b.Property("Note")
+ .HasMaxLength(500)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ChecklistItemId");
+
+ b.HasIndex("ChecklistRecordId");
+
+ b.ToTable("ChecklistResultItem");
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.ControlItem", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("Code")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("IsActive")
+ .HasColumnType("INTEGER");
+
+ b.Property("LowerLimit")
+ .HasColumnType("TEXT");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("TEXT");
+
+ b.Property("TargetValue")
+ .HasColumnType("TEXT");
+
+ b.Property("Unit")
+ .HasMaxLength(30)
+ .HasColumnType("TEXT");
+
+ b.Property("UpperLimit")
+ .HasColumnType("TEXT");
+
+ b.Property("Version")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Code")
+ .IsUnique();
+
+ b.ToTable("ControlItems");
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.DefectReason", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("Category")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("TEXT");
+
+ b.Property("Code")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("IsActive")
+ .HasColumnType("INTEGER");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("Code")
+ .IsUnique();
+
+ b.ToTable("DefectReasons");
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.Equipment", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("AssetNo")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("CollectsEvents")
+ .HasColumnType("INTEGER");
+
+ b.Property("IsActive")
+ .HasColumnType("INTEGER");
+
+ b.Property("MaintenanceParts")
+ .HasMaxLength(1000)
+ .HasColumnType("TEXT");
+
+ b.Property("MaintenanceThreshold")
+ .HasColumnType("TEXT");
+
+ b.Property("MaintenanceType")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("TEXT");
+
+ b.Property("Name")
+ .IsRequired()
+ .HasMaxLength(200)
+ .HasColumnType("TEXT");
+
+ b.Property("Site")
+ .HasMaxLength(200)
+ .HasColumnType("TEXT");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("TEXT");
+
+ b.Property("WorkCenterId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AssetNo")
+ .IsUnique();
+
+ b.HasIndex("WorkCenterId");
+
+ b.ToTable("Equipments");
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.EquipmentAlarmCode", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("AlarmCode")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("EquipmentId")
+ .HasColumnType("INTEGER");
+
+ b.Property("IsActive")
+ .HasColumnType("INTEGER");
+
+ b.Property("StopCause")
+ .IsRequired()
+ .HasMaxLength(500)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("EquipmentId", "AlarmCode")
+ .IsUnique();
+
+ b.ToTable("EquipmentAlarmCodes");
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.EquipmentEvent", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("AlarmCode")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.Property("EquipmentId")
+ .HasColumnType("INTEGER");
+
+ b.Property("EquipmentLogId")
+ .HasColumnType("INTEGER");
+
+ b.Property("EventId")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("TEXT");
+
+ b.Property("Note")
+ .HasMaxLength(500)
+ .HasColumnType("TEXT");
+
+ b.Property("OccurredAt")
+ .HasColumnType("TEXT");
+
+ b.Property("OperationSeq")
+ .HasColumnType("INTEGER");
+
+ b.Property("ReceivedAt")
+ .HasColumnType("TEXT");
+
+ b.Property("ReceivedByUserId")
+ .HasMaxLength(450)
+ .HasColumnType("TEXT");
+
+ b.Property("RejectReason")
+ .HasMaxLength(500)
+ .HasColumnType("TEXT");
+
+ b.Property("Result")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("TEXT");
+
+ b.Property("State")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("TEXT");
+
+ b.Property("WorkOrderNo")
+ .HasMaxLength(50)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("EquipmentLogId");
+
+ b.HasIndex("EquipmentId", "EventId")
+ .IsUnique();
+
+ b.HasIndex("EquipmentId", "OccurredAt");
+
+ b.ToTable("EquipmentEvents");
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.EquipmentLog", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("CreatedAt")
+ .HasColumnType("TEXT");
+
+ b.Property("EndedAt")
+ .HasColumnType("TEXT");
+
+ b.Property("EquipmentId")
+ .HasColumnType("INTEGER");
+
+ b.Property("Note")
+ .HasMaxLength(500)
+ .HasColumnType("TEXT");
+
+ b.Property("RecordedByUserId")
+ .HasColumnType("TEXT");
+
+ b.Property("Source")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasMaxLength(30)
+ .HasColumnType("TEXT")
+ .HasDefaultValue("Manual");
+
+ b.Property("StartedAt")
+ .HasColumnType("TEXT");
+
+ b.Property("Status")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("TEXT");
+
+ b.Property("StopCause")
+ .HasMaxLength(500)
+ .HasColumnType("TEXT");
+
+ b.Property("WorkOrderId")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("EquipmentId");
+
+ b.HasIndex("WorkOrderId");
+
+ b.ToTable("EquipmentLogs");
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.EquipmentPart", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("Category")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("TEXT");
+
+ b.Property("EquipmentId")
+ .HasColumnType("INTEGER");
+
+ b.Property("Note")
+ .HasMaxLength(500)
+ .HasColumnType("TEXT");
+
+ b.Property("ProductId")
+ .HasColumnType("INTEGER");
+
+ b.Property("QuantityPer")
+ .HasPrecision(18, 4)
+ .HasColumnType("TEXT");
+
+ b.HasKey("Id");
+
+ b.HasIndex("ProductId");
+
+ b.HasIndex("EquipmentId", "ProductId")
+ .IsUnique();
+
+ b.ToTable("EquipmentParts");
+ });
+
+ modelBuilder.Entity("MesApp.Core.Entities.InspectionDevice", b =>
+ {
+ b.Property("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("INTEGER");
+
+ b.Property("CalibratedOn")
+ .HasColumnType("TEXT");
+
+ b.Property("CalibrationCycleDays")
+ .HasColumnType("INTEGER");
+
+ b.Property("CalibrationDueOn")
+ .HasColumnType("TEXT");
+
+ b.Property("Code")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("TEXT");
+
+ b.Property