diff --git a/Readme.md b/Readme.md index 91d307d..978a434 100644 --- a/Readme.md +++ b/Readme.md @@ -102,7 +102,7 @@ ZIPにしたものを Releases に添付しています([マスタ](https://gi ## 配布・本番相当の実行 -ビルド済みのものを使う場合(手順の詳細は [管理者向け運用](docs/operations.md)): +ビルド済みのものを使う場合(手順の詳細は [サーバーの配置と設定](docs/operations.md)): - **Microsoft Store 版(1台で試す)**: [Microsoft Store](https://apps.microsoft.com/detail/9p9fqjzh23hc?hl=ja-JP&gl=JP) からインストールします。サーバー不要で、ほかの端末からは接続できません - **ZIP(自己完結版・.NET不要)**: [Releases](https://github.com/msmsrep/ParallelFactoryMES/releases/latest) から @@ -157,7 +157,7 @@ $env:MesAdmin__UserName="admin"; $env:MesAdmin__Password="Passw0rd123"; dotnet p - **HTTPS**: アプリ自身はHTTPSを強制しません。LAN運用ではリバースプロキシ(IIS / nginx)で HTTPSを終端し、プロキシのIPを `ReverseProxy__KnownProxies__0` に設定してください(設定しないと リフレッシュCookieに `Secure` が付かず、監査ログの接続元IPがプロキシのものになります)。 - 手順は [管理者向け運用](docs/operations.md) の「HTTPSで運用する」。なお**カメラによるバーコード読み取りは、ブラウザの制約により + 手順は [セキュリティと監査ログ](docs/security.md#https) の「HTTPSで運用する」。なお**カメラによるバーコード読み取りは、ブラウザの制約により `localhost` 以外ではHTTPSが必須**です(USB HIDリーダーと手入力はHTTPでも動作します)。 - **バックアップ**: SQLiteはWALモードで動作するため、**稼働中のDBファイルの単純コピーは行わないでください**。 停止中にコピーするか、`VACUUM INTO` を使用します。 @@ -166,7 +166,7 @@ $env:MesAdmin__UserName="admin"; $env:MesAdmin__Password="Passw0rd123"; dotnet p 起動時にそのDBへスキーマを作成します(DB自体とログインは事前に作成しておく)。 `DateTimeOffset` はPostgreSQLではUTCで保存され、SQL Serverの既定照合順序ではコードの大文字・小文字を 区別しません(Spec.md 4章)。**既存のSQLiteデータを移す機能はありません**。手順・バックアップ・起動しないときの確認点は - [管理者向け運用](docs/operations.md#database)を参照してください。 + [データベースとバックアップ](docs/database.md#database)を参照してください。 ```powershell $env:Database__Provider="PostgreSql"; $env:Database__ConnectionString="Host=db;Database=mesapp;Username=mesapp;Password=..." diff --git a/build/Capture-GuideScreens.js b/build/Capture-GuideScreens.js index 66766e7..918c33b 100644 --- a/build/Capture-GuideScreens.js +++ b/build/Capture-GuideScreens.js @@ -4,7 +4,9 @@ // [--base http://localhost:5212] [--user admin] [--out ] // // --page walkthrough(既定):「サンプルで見る 製造から出荷まで」(walkthrough.md)の8枚。幅1280・DPR2でページ全体 -// --page intro:紹介ページ(intro.html)の11枚。幅1440・DPR1で、画面の決まった範囲を切り出す +// --page intro:紹介ページ(intro.html)の13枚。幅1440・DPR1で、画面の決まった範囲を切り出す +// 稼働監視・Webhook の2枚のため、APIキーを発行して EQ-06 の設備イベントを送り、 +// このスクリプトの中に立てた受け側(127.0.0.1:--hook-port)を Webhook の送信先に登録する // // 前提:空のDBで起動したアプリ(--base)。初期管理者が無ければ --user / --password で作る。 // 1. samples/master-csv と samples/actual-csv の 01〜15 をZIPにして一括取込する(品目が既にあれば飛ばす) @@ -20,6 +22,7 @@ const fs = require('fs'); const os = require('os'); const path = require('path'); const { spawn, execFileSync } = require('child_process'); +const http = require('http'); const arg = (name, fallback) => { const i = process.argv.indexOf('--' + name); @@ -33,6 +36,7 @@ const LANG = arg('lang', 'en'); const PAGE = arg('page', 'walkthrough'); const EDGE = arg('edge', 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'); const PORT = Number(arg('port', '9224')); +const HOOK_PORT = Number(arg('hook-port', '5299')); const ROOT = path.join(__dirname, '..'); const OUT = arg('out', path.join(__dirname, 'guide-shots', PAGE, LANG)); const ACTUALS_UPTO = 15; // 在庫照会の写真は実績 01〜15 を取り込んだ時点の状態(ガイドの説明と合わせる) @@ -117,6 +121,7 @@ async function prepare() { console.warn('注意: SMP-FG-002 が承認済みのままではありません(walkthrough の撮影で展開済み?)。' + '紹介ページの写真は取込直後の状態を前提にしています。'); } + await prepareIntegration(); } else { // 完了承認(完了していない作業指示は失敗するので無視する) for (const no of ['SMP-SF-001', 'SMP-FG-001']) { @@ -148,6 +153,44 @@ async function prepare() { }; } +// ---- 稼働監視・Webhook の写真の下ごしらえ(intro) ---- +// 受け側はこのスクリプトの中に立て、届いた通知に 204 を返すだけにする(撮り終えたら閉じる) +let hookServer = null; +async function prepareIntegration() { + hookServer = http.createServer((req, res) => { req.resume(); req.on('end', () => { res.writeHead(204); res.end(); }); }); + await new Promise(r => hookServer.listen(HOOK_PORT, '127.0.0.1', r)); + const subs = items(await api('GET', '/api/webhook-subscriptions')); + if (subs.length === 0) { + const created = await api('POST', '/api/webhook-subscriptions', { + name: LANG === 'ja' ? '班長チャットへの通知' : 'Shift leader chat', + url: `http://127.0.0.1:${HOOK_PORT}/mes-webhook`, + eventTypes: ['equipment.stopped', 'nonconformance.created'], isActive: true, + }); + await api('POST', `/api/webhook-subscriptions/${created.data.subscription.id}/test`); + } + // ゲートウェイの代わりに EQ-06(設備イベントで収集する設備)の状態の変化を送る。 + // 最後に反映した時刻より前は「遅着」で拒否されるので、時刻は今から遡った近い過去にする + const admin = (await api('GET', '/api/users')).data.find(u => u.userName === USER); + const key = await api('POST', '/api/api-keys', { name: LANG === 'ja' ? '設備ゲートウェイ' : 'Equipment gateway', userId: admin.id, expiresAt: null }); + const now = Date.now(), at = min => new Date(now - min * 60000).toISOString(); + const events = [ + { min: 58, state: 'Running' }, { min: 41, state: 'Stopped', alarmCode: 'A-101' }, { min: 36, state: 'Running' }, + { min: 17, state: 'Setup' }, { min: 11, state: 'Running' }, { min: 3, state: 'Stopped', alarmCode: 'A-102' }, + ].map((e, i) => ({ equipmentCode: 'EQ-06', eventId: `guide-${now}-${i}`, occurredAt: at(e.min), state: e.state, alarmCode: e.alarmCode })); + const res = await fetch(BASE + '/api/integration/v1/equipment-events', { + method: 'POST', headers: { 'X-Api-Key': key.data.plainKey, 'Content-Type': 'application/json' }, + body: JSON.stringify({ events }), + }); + if (!res.ok) throw new Error('設備イベントを送れませんでした: ' + res.status + ' ' + (await res.text()).slice(0, 300)); + // 送信は常駐処理が数秒おきに拾う。テスト送信と停止2件の3件が送信済みになるまで待つ + for (let i = 0; i < 40; i++) { + const list = items(await api('GET', '/api/webhook-deliveries')); + if (list.length >= 3 && list.every(d => ['Delivered', 1].includes(d.state))) break; + await sleep(1000); + } + console.log('設備イベントを送り、Webhook の送信先を登録しました。'); +} + // ---- CDP ---- let seq = 0; function send(ws, method, params) { @@ -347,6 +390,14 @@ async function shootClip(ws, name, { from, pad = 0, height = HEIGHT, until, shee { name: 'quality', href: 'quality-analysis', clip: { from: card(1), pad: 16, height: 580 } }, { name: 'audit', href: 'audit-logs', clip: { from: h1, pad: 20, height: 860 } }, { name: 'masters', href: 'masters', clip: { from: h1, pad: 20, height: 580 } }, + // 保全管理は稼働監視タブが既定。「設備の今の状態」のカードまで + { name: 'equipment', href: 'maintenance', clip: { from: h1, pad: 20, until: card(0) } }, + { + name: 'webhooks', href: 'webhooks', clip: { from: h1, pad: 20, until: card(1) }, after: async () => { + await evalJs(ws, `(document.querySelectorAll('main.content .tabs button')[1].click(), true)`); + await sleep(2500); + }, + }, ]; for (const shot of shots) { await go(ws, shot.href); @@ -364,6 +415,7 @@ async function shootClip(ws, name, { from, pad = 0, height = HEIGHT, until, shee } else { edge.kill(); } + if (hookServer) hookServer.close(); await sleep(1500); try { fs.rmSync(profile, { recursive: true, force: true }); } catch { /* 一時プロファイルの残骸 */ } } diff --git a/compose.postgres.yaml b/compose.postgres.yaml index 9fed841..e8bb719 100644 --- a/compose.postgres.yaml +++ b/compose.postgres.yaml @@ -1,7 +1,7 @@ # Parallel Factory MES を PostgreSQL で動かす構成 # docker compose -f compose.postgres.yaml up -d → http://localhost:8080 # パスワードは .env ファイル(POSTGRES_PASSWORD=...)で与える。未設定だと起動しない -# 既存の SQLite のデータを PostgreSQL へ移す機能はない(docs/operations.md) +# 既存の SQLite のデータを PostgreSQL へ移す機能はない(docs/database.md) services: db: image: postgres:17 diff --git a/docs-dev/CodeMap.md b/docs-dev/CodeMap.md index 09ee8b5..d0bf2c9 100644 --- a/docs-dev/CodeMap.md +++ b/docs-dev/CodeMap.md @@ -28,7 +28,7 @@ | フォルダ連携(CSVの自動取込。取込のみ) | Spec.md 3.8 / A-20-10-01 ほか | `FolderLinkController.cs` `api/folder-link`(`status`・`scan`。どちらもシステム管理者だけ)
`Api/Services/FolderLink/FolderLinkService.cs`(走査・取込・`processed`/`error` への移動と結果ファイル。**取込は `MasterCsvService`・`ActualCsvService` をそのまま呼ぶ**。権限は `MasterCsvKinds.WriteRolesOf` と種別の `WriteRoles` で画面と同じ判定)/`FolderLinkWorker.cs`(常駐。`FolderLink:Root` が空なら何もしない)/`FolderLinkOptions.cs`(設定。再起動で反映)
**監査ログは利用者を `IHttpContextAccessor` から読むので、走査は文脈を引き継がずに(`ExecutionContext.SuppressFlow`)走らせ、1ファイルごとに連携用の利用者を立てる**(「今すぐ取り込む」のリクエストの文脈を壊さないため)
`Core/Contracts/Integration/FolderLinkDtos.cs` | (各マスタ・実績) | `/folder-link` `Web/Pages/FolderLink.razor`(状態と今すぐ取り込む。設定は画面から変えない) | `Tests/MasterCsvTests.cs`(`フォルダ連携〜`) | | 連携APIのCSV(APIキーで取込・出力。再送への備えつき) | Spec.md 3.8 / A-20-10-01 ほか | `Api/Controllers/Integration/IntegrationCsvController.cs` `api/integration/v1`(`csv-kinds`・`masters/{kind}`・`actuals/{kind}`・`masters/bundle`・`actuals/bundle`。失敗は422)
**種別の解決・ZIPの振り分け・取込権限は `Api/Services/CsvIntake.cs`**(画面の `MasterCsvController`・`ActualCsvController`・フォルダ連携と共通。入口を足すときもここを通す)
`Idempotency-Key` は `Api/Services/IdempotencyService.cs`(`Core/Entities/IntegrationRequest.cs`。取り込む前に処理中の行を入れ、一意索引で同時の重複を止める。期限は Unix 秒)
**CSVの列の約束**:`tests/MesApp.Api.Tests/CsvContract.v1.json`(全種別の列定義)と `CsvColumnInfo.Aliases`(以前の列名。`CsvTable.ApplyAliases` が `CsvImport.Prepare` で解決)。列を足したら `MESAPP_UPDATE_CSV_CONTRACT=1` で基準ファイルを更新 | (各マスタ・実績) | (画面なし) | `Tests/MasterCsvTests.cs`(`連携API〜`・`CSVの列の約束〜`・`CSVの以前の列名〜`) | | 連携APIの生産実績の取得(ERPが取りに来る) | Spec.md 3.8 / B-40-10 / B-70-30-01 | `Api/Controllers/Integration/ProductionResultsController.cs` `api/integration/v1/production-results`・`production-result-corrections`(`afterId` の続きから ID 昇順。`limit` 既定500・上限5,000。応答は `IntegrationFeed`(`nextAfterId`・`hasMore`))
`Core/Contracts/Integration/ProductionResultDtos.cs`(コード・番号で返し、区分・状態は列挙の名前。**内部IDは位置の `id` だけ**)
**値は訂正後の今の値で、訂正は訂正の口で知らせる。取り消した作業指示の実績も返す**(現物のロットが残るため) | Execution.cs: ProductionRecord / ProductionRecordCorrection | (画面なし) | `Tests/ProductionTests.cs`(`連携APIで生産実績〜`) | -| Webhook(MES から外への通知。送信先・送信待ち・送信・イベントの発行) | Spec.md 3.8 / 発行するイベントは B-40-10-01・B-70-30-01・D-10-30-08・C-30-10-01・B-40-20-02・E-20-10-03 ほか | `Api/Controllers/WebhookSubscriptionsController.cs` `api/webhook-subscriptions`(一覧=送れていない件数つき・登録・変更・削除・`{id}/rotate-secret`・`{id}/test`。すべてシステム管理者だけ)
`Api/Controllers/WebhookDeliveriesController.cs` `api/webhook-deliveries`(送信の記録・`{id}/resend`)
**送信は `Api/Services/Webhooks/WebhookDispatcher.cs`**(条件付きの更新で取り出し・本文の包み・再送の判定と間隔)+常駐処理 `WebhookDispatchWorker.cs`・署名 `WebhookSignature.cs`・設定 `WebhookOptions.cs`(`Webhooks:*`)。HttpClient は名前付き `webhooks`(リダイレクトを追わない)
`Api/Services/Webhooks/WebhookPublisher.cs`(`EnqueueAsync`:送信待ちを `DbContext` に足すだけ。保存は呼び出し側=業務と同じトランザクション)
`Api/Services/Webhooks/WebhookSecrets.cs`(秘密の発行と Data Protection での暗号化。鍵は `DataProtection:KeysDirectory`)
種類の一覧 `Core/Constants/WebhookEventTypes.cs`・DTO `Core/Contracts/Integration/WebhookDtos.cs`
**本文の data の型は `Core/Contracts/Integration/WebhookPayloads.cs`**(`DataTypes` が種類→型。約束の書き出しは `Api/Services/Webhooks/WebhookContract.cs`、OpenAPI の `webhooks` 節は `Api/IntegrationOpenApi.cs`)
**発行の場所**:`LotStatusService`・`WorkOrderStatusService`(状態変更のたび)、`WorkOrderExecutionService.AddProductionRecordAsync`(実績)、`ProductionRecordsController.Correct`(訂正)、`ManufacturingOrderService`(完了・取消)、`NonconformanceService.CreateAsync`+`InspectionService`(不合格の自動起票。`NonconformanceService.CreatedNotice` を共用)、`ShopFloorReportService.EnqueueStoppedAsync`(手入力・CSV と `EquipmentEventService` で共用) | `Core/Entities/Webhook.cs`: WebhookSubscription / WebhookOutbox / WebhookDelivery(再送の時刻は Unix 秒)
設定 `Infra/Configurations/SystemConfigurations.cs` | `/webhooks` `Web/Pages/WebhooksPage.razor`(タブ)+ `Web/Pages/Webhooks/SubscriptionsTab.razor`・`DeliveriesTab.razor`
ダッシュボードの知らせ `Web/Pages/Webhooks/WebhookFailureNotice.razor`(`Home.razor` に置く)
受け側の見本:Node-RED の「Webhook の受け側」タブ(`samples/equipment-gateway/flows.json`・本文を生のまま残す `settings.js`・`compose.yaml` の `equipment` プロファイル)、`samples/webhook`(Python・PowerShell)。ガイドは `docs/operations.md`(英語版も)の「Webhook」 | `Tests/AuthTests.cs`(`Webhook〜`・`同じWebhook〜`・`Webhookの本文の約束〜`(基準 `WebhookContract.v1.json`。足したら `MESAPP_UPDATE_WEBHOOK_CONTRACT=1`)。発行は `ExecutionTests`・`QualityTests`・`MaintenanceTests` の `〜Webhookの送信待ちに積まれ〜`(補助は `TestAuth.SubscribeWebhooksAsync`・`QueuedWebhooksAsync`)。受け側は `WebhookReceiver` でテストの中に立て、`WithWebHostBuilder` で名前付き HttpClient を差し替える。常駐処理は `ApiFactory` で止めてある) | +| Webhook(MES から外への通知。送信先・送信待ち・送信・イベントの発行) | Spec.md 3.8 / 発行するイベントは B-40-10-01・B-70-30-01・D-10-30-08・C-30-10-01・B-40-20-02・E-20-10-03 ほか | `Api/Controllers/WebhookSubscriptionsController.cs` `api/webhook-subscriptions`(一覧=送れていない件数つき・登録・変更・削除・`{id}/rotate-secret`・`{id}/test`。すべてシステム管理者だけ)
`Api/Controllers/WebhookDeliveriesController.cs` `api/webhook-deliveries`(送信の記録・`{id}/resend`)
**送信は `Api/Services/Webhooks/WebhookDispatcher.cs`**(条件付きの更新で取り出し・本文の包み・再送の判定と間隔)+常駐処理 `WebhookDispatchWorker.cs`・署名 `WebhookSignature.cs`・設定 `WebhookOptions.cs`(`Webhooks:*`)。HttpClient は名前付き `webhooks`(リダイレクトを追わない)
`Api/Services/Webhooks/WebhookPublisher.cs`(`EnqueueAsync`:送信待ちを `DbContext` に足すだけ。保存は呼び出し側=業務と同じトランザクション)
`Api/Services/Webhooks/WebhookSecrets.cs`(秘密の発行と Data Protection での暗号化。鍵は `DataProtection:KeysDirectory`)
種類の一覧 `Core/Constants/WebhookEventTypes.cs`・DTO `Core/Contracts/Integration/WebhookDtos.cs`
**本文の data の型は `Core/Contracts/Integration/WebhookPayloads.cs`**(`DataTypes` が種類→型。約束の書き出しは `Api/Services/Webhooks/WebhookContract.cs`、OpenAPI の `webhooks` 節は `Api/IntegrationOpenApi.cs`)
**発行の場所**:`LotStatusService`・`WorkOrderStatusService`(状態変更のたび)、`WorkOrderExecutionService.AddProductionRecordAsync`(実績)、`ProductionRecordsController.Correct`(訂正)、`ManufacturingOrderService`(完了・取消)、`NonconformanceService.CreateAsync`+`InspectionService`(不合格の自動起票。`NonconformanceService.CreatedNotice` を共用)、`ShopFloorReportService.EnqueueStoppedAsync`(手入力・CSV と `EquipmentEventService` で共用) | `Core/Entities/Webhook.cs`: WebhookSubscription / WebhookOutbox / WebhookDelivery(再送の時刻は Unix 秒)
設定 `Infra/Configurations/SystemConfigurations.cs` | `/webhooks` `Web/Pages/WebhooksPage.razor`(タブ)+ `Web/Pages/Webhooks/SubscriptionsTab.razor`・`DeliveriesTab.razor`
ダッシュボードの知らせ `Web/Pages/Webhooks/WebhookFailureNotice.razor`(`Home.razor` に置く)
受け側の見本:Node-RED の「Webhook の受け側」タブ(`samples/equipment-gateway/flows.json`・本文を生のまま残す `settings.js`・`compose.yaml` の `equipment` プロファイル)、`samples/webhook`(Python・PowerShell)。ガイドは `docs/integration.md`(英語版も)の「Webhook」 | `Tests/AuthTests.cs`(`Webhook〜`・`同じWebhook〜`・`Webhookの本文の約束〜`(基準 `WebhookContract.v1.json`。足したら `MESAPP_UPDATE_WEBHOOK_CONTRACT=1`)。発行は `ExecutionTests`・`QualityTests`・`MaintenanceTests` の `〜Webhookの送信待ちに積まれ〜`(補助は `TestAuth.SubscribeWebhooksAsync`・`QueuedWebhooksAsync`)。受け側は `WebhookReceiver` でテストの中に立て、`WithWebHostBuilder` で名前付き HttpClient を差し替える。常駐処理は `ApiFactory` で止めてある) | | 連携APIの設備イベントの受信(ゲートウェイが送る) | Spec.md 3.8 / B-40-20-01〜02 / E-20-10-01 | `Api/Controllers/Integration/EquipmentEventsController.cs` `api/integration/v1/equipment-events`(1件ごとに採否。全件拒否でも200)
**区間の組み立ては `Api/Services/EquipmentEventService.cs`**(設定 `EquipmentEventOptions`。設備ごとに発生時刻の順に並べ、開いた区間を閉じて次を開く。遅着は拒否。**同時の要求は設備の行の更新でロックを取って直列**。`AddEquipmentLogAsync` は通さない=停止原因は空のまま開く)
作業指示は指定(指図番号+工程順序)を優先、無ければ割当+着手中が1件のときだけ
`Core/Contracts/Integration/EquipmentEventDtos.cs`
ゲートウェイの見本は `samples/equipment-gateway`(Node-RED の `flows.json` と `mosquitto.conf`)+ `compose.yaml` のプロファイル `equipment`。利用者向けは運用ガイドの「設備イベントの受信」 | Maintenance.cs: EquipmentEvent / EquipmentLog(`Source`=Event)
Masters.cs: Equipment(`CollectsEvents`) | (画面なし。稼働記録タブに記録元が出る) | `Tests/MaintenanceTests.cs`(`設備イベント〜`・`同じ設備への設備イベント〜`) | ## B. 製造実行 diff --git a/docs-dev/StoreListing.en.md b/docs-dev/StoreListing.en.md index fdd9643..6e3b7a4 100644 --- a/docs-dev/StoreListing.en.md +++ b/docs-dev/StoreListing.en.md @@ -43,20 +43,22 @@ Parallel Factory MES is a manufacturing execution system (MES) that records manu [Maintenance] Equipment operation records, maintenance plans, orders and results, work procedures, tool life management [Reports] Print work orders and lot tags or save them as PDF (with barcodes). Works with USB barcode readers [Master Data & Integration] Bulk import and export of master data such as products, processes, routings and equipment via CSV (UTF-8 / Shift_JIS) +[Notifications] Webhooks that immediately notify a URL you register (such as your team chat) when a nonconformance is raised, equipment stops, a lot is put on hold and so on [Administration] Users and roles (permissions), audit log of operations ■ Records you can trace later Status changes of manufacturing orders, work orders and lots are kept as history, and the audit log shows who changed what and when. When a record is corrected, its original content and the reason for the correction are kept as well. ■ Your data stays on this PC -All data you enter is stored on this PC and is never sent to anyone, including the developer. There is no usage tracking and no advertising. The app's screens run only inside this PC and cannot be reached from other devices on the network. +All data you enter is stored on this PC and is never sent to anyone, including the developer (if you register a webhook, notifications are sent only to that destination). There is no usage tracking and no advertising. The app's screens run only inside this PC and cannot be reached from other devices on the network. ■ Getting started -On first launch, a system administrator account is created automatically, and its user name and password are shown at the top of the window. Sign in, change the password, then register processes, products and routings under Master Data. The user guide (website) explains each operation with screenshots. +On first launch, the initial setup screen appears, where you choose the user name and password for the system administrator account. Sign in, then register processes, products and routings under Master Data. The user guide (website) explains each operation with screenshots. ■ Notes ・This app is designed for use on a single PC. If you need to share the same data across multiple PCs, consider deploying it on a server (the source code is public). -・Uninstalling the app deletes all saved data. To keep your data, close the app and copy the data folder beforehand (see "Administration" in the user guide). +・Uninstalling the app deletes all saved data. To keep your data, close the app and copy the data folder beforehand (see "Databases and backups" in the user guide). +・Even in a narrow window, the app stays usable with a collapsible menu and horizontally scrolling tables. ・The app uses the Microsoft Edge WebView2 Runtime to display its screens (included with Windows 11). ・The app's screens are available in Japanese and English. @@ -81,7 +83,8 @@ Equipment maintenance plans, orders and results, plus tool life management Print work orders and lot tags or save them as PDF (with barcodes) Bulk CSV import and export of master data (UTF-8 / Shift_JIS detected automatically) Role-based permissions and an audit log that keeps values before and after each change -Data is stored only on this PC. No server, no internet connection, no usage tracking +Webhooks that immediately notify a registered URL of nonconformances, equipment stops and more +Data is stored only on this PC. No server needed, no usage tracking (the only thing sent out is to webhook destinations you register) ``` ## スクリーンショット diff --git a/docs-dev/StoreListing.md b/docs-dev/StoreListing.md index 64b88bc..9ff7301 100644 --- a/docs-dev/StoreListing.md +++ b/docs-dev/StoreListing.md @@ -8,6 +8,7 @@ Partner Center の「Store 掲載情報 → 日本語」に貼り付ける原稿 - **Store 版でできないことを書かない**。Store 版は1台のPC内で完結し、LAN上の他端末からは接続できない(Spec.md 7.8)。 「全端末から」「タブレットから」などサーバー配置を前提とした言い回しは紹介ページから流用しない - 参照している業務一覧(ENAA)の名前は出さない(第三者の名称・著作物。Readme の注記はリポジトリ向け) +- フォルダ連携・連携API(APIキー)・設備イベントの受信は、他の機器やソフトから接続するサーバー配置向けの機能で、Store 版では使えないので書かない(Webhook は外へ送るだけなので Store 版でも使える) - 画面と説明が食い違うと差し戻されるので、機能名は画面のメニュー名に合わせる。アプリ内に無い機能(バックアップ等。現状は手作業のファイルコピー)を機能として挙げない --- @@ -43,20 +44,22 @@ Parallel Factory MES は、製造指図・作業実績・在庫・品質・設 【設備保全】稼働記録、保全計画・指示・実績、作業手順書、治工具の寿命管理 【帳票】作業指示書・現品票の印刷とPDF出力(バーコード入り)。USBバーコードリーダーでの読み取りに対応 【マスタ・データ連携】品目・工程・工順・設備などのマスタをCSVで一括登録・出力(UTF-8/Shift_JIS) +【通知】不適合の起票・設備の停止・ロットの保留などが起きたとき、登録した URL(社内のチャットなど)へすぐに知らせる Webhook 【管理】ユーザーとロール(権限)、操作の監査ログ ■ 記録を後から追える 製造指図・作業指示・ロットの状態変化は履歴として残り、誰が・いつ・何を変えたかは監査ログで確認できます。訂正した記録も、訂正前の内容と理由が残ります。 ■ データはこのPCの中だけに -入力したデータはすべてこのPC内に保存され、開発者を含む第三者には送信されません。利用状況の収集や広告もありません。アプリの画面はPC内部でのみ動作し、ネットワーク上の他の機器からは接続できません。 +入力したデータはすべてこのPC内に保存され、開発者を含む第三者には送信されません(Webhook で送信先を登録した場合は、その送信先にだけ通知を送ります)。利用状況の収集や広告もありません。アプリの画面はPC内部でのみ動作し、ネットワーク上の他の機器からは接続できません。 ■ はじめかた -初回起動時にシステム管理者のアカウントが自動で作られ、ユーザー名とパスワードがウィンドウ上端に表示されます。ログインしてパスワードを変更したら、マスタ管理から工程・品目・工順を登録してください。操作手順はユーザーガイド(Webサイト)で画面写真付きで説明しています。 +初回起動時に表示される初期セットアップ画面で、システム管理者のユーザー名とパスワードを決めて作成します。ログインしたら、マスタ管理から工程・品目・工順を登録してください。操作手順はユーザーガイド(Webサイト)で画面写真付きで説明しています。 ■ ご注意 ・1台のPCで使うためのアプリです。複数のPCから同じデータを共有したい場合は、サーバーに配置する形態(ソースコードを公開しています)をご検討ください。 -・アンインストールすると、保存したデータもすべて削除されます。必要なデータは、アプリを閉じた状態でデータフォルダーをコピーして事前に保存してください(手順はユーザーガイドの「管理者向け運用」にあります)。 +・アンインストールすると、保存したデータもすべて削除されます。必要なデータは、アプリを閉じた状態でデータフォルダーをコピーして事前に保存してください(手順はユーザーガイドの「データベースとバックアップ」にあります)。 +・ウィンドウの幅を狭くしても、メニューの開閉と表の横スクロールで使えます。 ・画面表示に Microsoft Edge WebView2 ランタイムを使用します(Windows 11 には標準で搭載されています)。 本アプリはオープンソースソフトウェア(GNU Affero General Public License v3.0)です。 @@ -80,7 +83,8 @@ Parallel Factory MES は、製造指図・作業実績・在庫・品質・設 作業指示書・現品票の印刷とPDF出力(バーコード入り) マスタのCSV一括登録・出力(UTF-8/Shift_JIS 自動判別) ロール(権限)ごとの操作制限と、変更前後を残す監査ログ -データはPC内にのみ保存。サーバー・ネット接続・利用状況の収集なし +不適合・設備の停止などを、登録したURLへすぐに知らせる Webhook +データはPC内にのみ保存。サーバー不要・利用状況の収集なし(外へ送るのは自分で登録した Webhook の送信先だけ) ``` ## スクリーンショット diff --git a/docs-dev/note-article-1.1.0.md b/docs-dev/note-article-1.1.0.md new file mode 100644 index 0000000..6a3b151 --- /dev/null +++ b/docs-dev/note-article-1.1.0.md @@ -0,0 +1,195 @@ +貼る前のメモ(このブロックは貼らない):【見出し画像】【画像】の行は、noteで画像をアップロードしたら消す。見出し画像は docs/assets/intro/、それ以外の画像は docs-dev/note-images/1.1.0/ にある。Microsoft Store 版の 1.1.0 が公開されたかを確かめてから貼る。 + +# 紙とExcelの次は「ほかのシステムとつなぐ」― Parallel Factory MES 1.1.0 で増えたこと + +【見出し画像:dashboard.webp】 + +前回の記事では、無償のMES「Parallel Factory MES」(1.0.4)を小さな工場に導入して、日々運用するまでの流れを紹介しました。 + +紙とExcelの記録をMESに載せると、次にこんな声が出てきます。 + +「販売管理から出した製造指図を、毎朝手で取り込むのが面倒」 +「設備が止まった時刻を、作業者があとから思い出して書いている」 +「不良が出たら、班長のスマホにすぐ知らせたい」 + +MESは単独で使うより、**ほかのシステムや設備とつながったときに、はじめて本領を発揮します**。バージョン 1.1.0 では、この「つなぐ」部分を一気に足しました。 + +この記事では、1.0.4 から 1.1.0 で増えた機能と、小さな工場でどう使えるかを紹介します。 + +ユーザーガイド:https://msmsrep.github.io/ParallelFactoryMES/index.html + +## 1.1.0 で増えたこと(まとめ) + +- **フォルダ連携**:決めたフォルダにCSVを置くだけで、自動で取り込む +- **連携API(APIキー)**:販売管理・生産管理(ERP)や社内のスクリプトから、ログインせずにデータをやり取りする +- **設備イベントの受信**:設備の稼働・停止を、PLCからゲートウェイ経由で自動で記録する +- **Webhook**:不適合や設備の停止が起きたとき、MESからチャットなどへすぐに知らせる +- **スマホの画面幅に対応** +- **デスクトップ版(Microsoft Store)の初期管理者を、Web版と同じ初期セットアップ画面で作るように変更** + +難しさの順に並べると、**フォルダ連携 → 連携API → Webhook → 設備イベント** です。プログラムを書かずに始められるのはフォルダ連携だけなので、まずはそこから紹介します。 + +## フォルダ連携:CSVを置くだけで取り込む + +販売管理や生産管理のソフトには、たいてい「CSVで出力」の機能があります。けれど、そのCSVを毎朝MESの画面から手で取り込むのは、地味に手間がかかります。忘れることもあります。 + +**フォルダ連携**を使うと、決めたフォルダ(`inbox`)にCSVが置かれただけで、MESが自動で取り込みます。プログラムを書く必要はありません。 + +たとえば、こんな使い方ができます。 + +- 販売管理ソフトが毎朝出力する製造指図のCSVを、共有フォルダに保存させる +- 受入の記録を、倉庫のPCから共有フォルダに置く + +取り込めたファイルは `processed`、取り込めなかったファイルは `error` フォルダへ移り、横に結果のファイルが付きます。画面から取り込むときと同じチェックを通り、**1行でもエラーがあれば、そのファイルは何も反映しません**。半端に取り込まれて困ることはありません。 + +> 💡 取込は、専用に作った利用者(例:`folder-link`)として行われます。この利用者には、**取り込みたい種類に必要なロールだけ**を付けてください。製造指図なら生産管理担当者、受入なら物流・倉庫担当者です。だれが取り込んだかは、監査ログにもこの利用者で残ります。 + +設定は、サーバーの起動時に連携フォルダと利用者を指定するだけです。システム管理者は「管理 → フォルダ連携」の画面で、設定の誤りや最近処理したファイルを確かめられます。 + +【画像:folder-link.webp(フォルダ連携の画面。取り込めたファイルと、エラーになったファイル)】 + +## 連携API:ほかのシステムからデータをやり取りする + +社内に販売管理・生産管理のシステムがあって、少しプログラムを書ける人(または頼める業者)がいるなら、**連携API**が使えます。 + +### APIキーを発行する + +システム管理者が「管理 → APIキー」でキーを発行し、連携するシステムに設定します。キーで何ができるかは、キーに紐づけた利用者のロールで決まります。フォルダ連携と同じく、**用途ごとに専用の利用者を作り、必要なロールだけを付ける**のがおすすめです。 + +キーは発行したときにしか表示されません。パスワードと同じように扱ってください。 + +### できること + +- **CSVの取込**:マスタも実績も、画面と同じCSVをそのまま送れます。`?dryRun=true` を付ければ、検証だけして反映しません +- **マスタのCSV出力** +- **生産実績を「前回の続きから」読む**:ERPに完成数を渡すときなど、前回読んだところから先だけを取り出せます。あとから訂正された実績も、同じように続きから読めます + +【画像:api-keys.webp(APIキーの画面)】 + +仕様書(OpenAPI)も公開しているので、Postman などに読み込めば、使える口や応答の形がすぐ分かります。 + +### 送り直しても二重にならない + +通信が切れて、同じ実績CSVを送り直したら二重に登録された ― 連携でいちばん起きやすい事故です。 + +連携APIでは、要求に `Idempotency-Key`(送る内容ごとに決めた値)を付けておくと、**同じ内容を送り直しても取り込み直さず、前回の結果を返します**。連携する側は「失敗したら送り直す」だけで済みます。 + +### 版を上げても動き続ける + +連携でもうひとつ怖いのが、「MESを新しい版にしたら、つないでいた仕組みが動かなくなった」ということです。 + +連携API(v1)とCSVの列には、**項目や列を足すことはあっても、消したり名前を変えたりはしない**という約束を決めました。CSVの列とWebhookの本文の形は基準ファイルに固定して、テストで機械的に確かめています。 + +## 設備イベント:設備の稼働・停止を自動で記録する + +前回の記事の「できないこと」に「設備からの自動データ収集」を挙げていました。1.1.0 で、そのうち**設備の稼働状態(稼働・停止・段取り・故障など)**を自動で記録できるようになりました。 + +### 仕組み + +MESは、PLCと直接は通信しません。間に**ゲートウェイ**(Node-RED など)を置きます。 + +``` +設備・PLC ──▶ ゲートウェイ(Node-RED など)──▶ MES + OPC UA・MCプロトコル・Modbus など 連携API(APIキー) +``` + +ゲートウェイがPLCの状態を読み、状態が変わったときにMESへ送ります。MESは届いた変化を時刻の順に並べて、「9:00〜9:10 稼働」「9:10〜9:25 停止」のような稼働履歴に組み立てます。 + +PLCのメーカーや通信方式は工場ごとにばらばらです。MESをそれぞれに合わせる代わりに、その差をゲートウェイで吸収する形にしました。 + +### 小さな工場で助かるところ + +- **停止の時刻を手で書かなくてよくなる**:作業者があとから思い出して書くと、時刻はどうしてもあいまいになります +- **停止原因を自動で引き当てる**:設備のアラーム番号と停止原因の対応表を作っておけば、「A-101 → 材料切れ」のように原因が入ります。引けなかった停止は、あとから保全の画面で原因を書き足せます +- **通信が止まったことに気づける**:受信が一定時間(既定10分)途絶えると、稼働監視の画面に「受信が途絶えています」と出ます + +通信が切れたときに送り直しても、同じイベントは二重に記録されません。 + +### すべての設備を一度につなぐ必要はない + +設備ごとに「設備イベントで収集する」かどうかを選べます。**つないだ設備だけ自動、ほかの設備は今までどおり手入力**、という混在ができるので、主力の1台から始められます。手入力と自動で同じ時間を二重に数えないよう、つないだ設備は手入力できなくなります。 + +> 💡 Docker が使えるなら、リポジトリの `compose.yaml` で、MQTTブローカーと Node-RED のゲートウェイを一緒に起動できます(`docker compose --profile equipment up -d`)。数秒ごとに状態を変える**模擬設備**が入っているので、実機が無くても、稼働履歴が自動で増えていく様子を試せます。 + +【画像:equipment-current.webp(稼働監視の「設備の今の状態」)】 + +【画像:equipment-logs.webp(設備イベントで記録された稼働履歴。原因を引けなかった停止は、あとから書き足せる)】 + +## Webhook:起きたことをすぐに知らせる + +連携APIは「相手が取りに来る」仕組みです。ERPが1日1回完成数を取りに来るなら、それで足ります。 + +けれど、**不良が出た、設備が止まった、ロットが保留になった**、というような出来事は、すぐに知りたいものです。そこで、MESのほうから登録したURLへ知らせる **Webhook** を足しました。 + +通知する出来事は、たとえば次のとおりです。 + +- 生産実績の記録・訂正 +- 作業指示・製造指図の状態の変化 +- ロットの在庫ステータスの変化(保留・解除など) +- 不適合の起票(検査の不合格からの自動起票も含む) +- 設備の停止・故障 + +通知には「設備 EQ-01 が『停止』になりました(材料切れ)。」のような1文の要約が付くので、そのままチャットに流すだけでも役に立ちます。 + +設定は、システム管理者が「管理 → Webhook」で送信先のURLと通知する出来事を選ぶだけです。**テスト送信**のボタンで、届くかどうかをその場で確かめられます。 + +受け取る側の見本として、Node-RED のフロー(署名を確かめて Slack や Teams に転送する)と、Python・PowerShell の短いスクリプトを用意しました。 + +届かなかった通知は、間隔を空けて自動で送り直します。それでも届かなかったものは画面に出るので、受け側を直してから再送できます。 + +【画像:webhook-deliveries.webp(Webhook の送信の記録)】 + +## スマホの画面幅でも使えるように + +1.0.4 では、スマホで開くとサイドバーが画面を埋めてしまい、表も見切れていました。1.1.0 では、スマホの画面幅ではサイドバーを開け閉めでき、幅の広い表は横にスクロールできるようになりました。 + +現場の作業はタブレットで行いたい、班長がスマホで進捗だけ見たい、という使い方がしやすくなります。 + +## デスクトップ版の初期管理者のつくり方が変わりました + +前回の記事で「Microsoft Store 版は初期管理者が自動で作られる」と書きましたが、1.1.0 からは変わります。 + +Store 版も ZIP版・Docker版と同じく、初めて開いたときに「初期セットアップが必要です」と表示されるので、**初期管理者のユーザー名とパスワードを自分で決めて作成**します。自動で生成したパスワードを控えておく手間がなくなり、どの版でも同じ手順で始められるようになりました。 + +## アップデートのしかた + +データベースの更新は、起動時に自動で行われます。**更新の前に、必ずバックアップを取ってください。** + +- **ZIP版**:サーバーを止め、データを残したまま新しいZIPを展開して起動します(データの保存先はアプリのフォルダとは別です) +- **Docker版**:新しいイメージを取得して、同じボリュームでコンテナを作り直します + +``` +docker pull ghcr.io/msmsrep/parallelfactorymes:1.1.0 +``` + +- **Microsoft Store 版**:ストアから更新されます + +> 💡 Webhook を使う場合、データの保存先にある `dataprotection-keys` フォルダ(Webhook の秘密の値を暗号化する鍵)もバックアップに含めてください。失うと、送信先ごとに秘密の値を作り直すことになります。 + +## できないこと(1.1.0 の時点) + +前回挙げたものから、設備の稼働状態の自動記録はできるようになりました。今も対応していないのは次のとおりです。 + +- 秤量機・測定器などからの測定値の自動収集(設備イベントで取れるのは稼働状態だけ) +- EDI / ASN 連携 +- シリアル番号(1台ずつの個体)単位の追跡(ロット単位のみ) +- 多段階の承認ワークフロー(承認は1段階) +- MESから外へのCSVの自動書き出し(実績は連携APIで読み出すか、Webhookで知らせます) + +## おわりに + +1.1.0 のテーマは「MESを工場の中で孤立させない」ことでした。 + +小さな工場なら、つなぐ順番は次のようにすると無理がありません。 + +1. **フォルダ連携**で、今手で取り込んでいるCSVを自動にする(プログラム不要) +2. **Webhook**で、不適合や設備の停止をチャットに流す +3. 主力の設備1台を、**設備イベント**で自動記録にする +4. ERPとの連携が必要になったら、**連携API**でつなぐ + +どれも無償で、ライセンスキーも要りません。まずはサンプルや模擬設備で試してみてください。 + +- ユーザーガイド:https://msmsrep.github.io/ParallelFactoryMES/index.html +- 入手(GitHub):https://github.com/msmsrep/ParallelFactoryMES + +#MES #製造業 #DX #工場 #中小企業 #生産管理 #IoT #NodeRED diff --git a/docs-dev/note-images/1.1.0/api-keys.webp b/docs-dev/note-images/1.1.0/api-keys.webp new file mode 100644 index 0000000..c4042e4 Binary files /dev/null and b/docs-dev/note-images/1.1.0/api-keys.webp differ diff --git a/docs-dev/note-images/1.1.0/equipment-current.webp b/docs-dev/note-images/1.1.0/equipment-current.webp new file mode 100644 index 0000000..9eb8bf8 Binary files /dev/null and b/docs-dev/note-images/1.1.0/equipment-current.webp differ diff --git a/docs-dev/note-images/1.1.0/equipment-logs.webp b/docs-dev/note-images/1.1.0/equipment-logs.webp new file mode 100644 index 0000000..a24e24f Binary files /dev/null and b/docs-dev/note-images/1.1.0/equipment-logs.webp differ diff --git a/docs-dev/note-images/1.1.0/folder-link.webp b/docs-dev/note-images/1.1.0/folder-link.webp new file mode 100644 index 0000000..2677922 Binary files /dev/null and b/docs-dev/note-images/1.1.0/folder-link.webp differ diff --git a/docs-dev/note-images/1.1.0/webhook-deliveries.webp b/docs-dev/note-images/1.1.0/webhook-deliveries.webp new file mode 100644 index 0000000..fe692ac Binary files /dev/null and b/docs-dev/note-images/1.1.0/webhook-deliveries.webp differ diff --git a/docs/_data/nav.yml b/docs/_data/nav.yml index ecd3bc8..c09d6cd 100644 --- a/docs/_data/nav.yml +++ b/docs/_data/nav.yml @@ -39,14 +39,22 @@ ja: url: reports.html - title: ロールと権限 url: roles.html + - section: 管理者向け + items: + - title: サーバーの配置と設定 + url: operations.html + - title: 外部連携 + url: integration.html + - title: セキュリティと監査ログ + url: security.html + - title: データベースとバックアップ + url: database.html - section: 資料 items: - title: リファレンス url: reference.html - title: 困ったときは url: troubleshooting.html - - title: 管理者向け運用 - url: operations.html - title: プライバシーポリシー url: privacy.html @@ -89,13 +97,21 @@ en: url: reports.html - title: Roles and permissions url: roles.html + - section: Administration + items: + - title: Server deployment and settings + url: operations.html + - title: Integrations + url: integration.html + - title: Security and audit log + url: security.html + - title: Databases and backups + url: database.html - section: Reference items: - title: Reference url: reference.html - title: Troubleshooting url: troubleshooting.html - - title: Administration - url: operations.html - title: Privacy policy url: privacy.html diff --git a/docs/_data/ui.yml b/docs/_data/ui.yml index 77cf992..ce1ec66 100644 --- a/docs/_data/ui.yml +++ b/docs/_data/ui.yml @@ -6,6 +6,9 @@ ja: menu: メニュー brand_sub: ユーザーガイド intro_link: 紹介ページ + search_placeholder: ガイドを検索(/) + search_label: ガイドを検索 + search_none: 見つかりませんでした。別の言葉で試してください。 nav_label: ガイド目次 pager_label: ページ送り foot_version: Parallel Factory MES ユーザーガイド / 対象バージョン:Phase 1〜7 @@ -26,6 +29,9 @@ en: menu: Menu brand_sub: User Guide intro_link: Overview + search_placeholder: Search the guide (/) + search_label: Search the guide + search_none: No results. Try different words. nav_label: Guide contents pager_label: Page navigation foot_version: Parallel Factory MES User Guide / Covers Phase 1–7 diff --git a/docs/_includes/search-index.json b/docs/_includes/search-index.json new file mode 100644 index 0000000..6c5f1c1 --- /dev/null +++ b/docs/_includes/search-index.json @@ -0,0 +1,34 @@ +{%- comment -%} + ガイド内検索の索引(assets/search.js が読む)。言語ごとに search.json / en/search.json から呼ぶ。 + ページを h2〜h4 の見出しで節に区切り、節ごとに「ページ名・見出し・リンク先・本文」を持たせる。 + 見出しの id は kramdown が付けるものをそのまま使うため、本文を markdownify してから区切る(GitHub Pages の標準ビルドで動くよう Liquid だけで作る)。 + h3・h4 の節は、属する h2 の見出しを s に持たせる(「バックアップ › SQLite」のように出し、両方の語で探せるようにする) +{%- endcomment -%} +{%- assign dir = include.dir -%} +{%- assign docs = site.pages | where: "dir", dir | where: "layout", "default" | where_exp: "p", "p.nav_url" | where_exp: "p", "p.nav_url != '404.html'" -%} +[ +{%- assign first = true -%} +{%- for p in docs -%} + {%- assign html = p.content | markdownify | replace: "", "" | replace: "", "" -%} + {%- assign parent = "" -%} + {%- assign chunks = html | split: "" -%} + {%- assign head = parts | first -%} + {%- assign id = head | split: 'id="' | last | split: '"' | first -%} + {%- assign heading = head | split: ">" | shift | join: ">" | strip_html | strip -%} + {%- assign body = parts | shift | join: " " -%} + {%- assign level = head | slice: 0, 3 -%} + {%- if level == " x3" or level == " x4" -%}{%- assign sect = parent -%}{%- else -%}{%- assign sect = "" -%}{%- assign parent = heading -%}{%- endif -%} + {%- endif -%} + {%- if forloop.first -%}{%- assign lead = p.lead | append: " " -%}{%- else -%}{%- assign lead = "" -%}{%- endif -%} + {%- assign text = body | strip_html | prepend: lead | split: " " | join: " " -%} + {%- if heading == "" and text == "" -%}{%- continue -%}{%- endif -%} + {%- unless first -%},{%- endunless -%}{%- assign first = false %} +{"p":{{ p.title | jsonify }},"u":{{ p.nav_url | jsonify }},"a":{{ id | jsonify }},"s":{{ sect | jsonify }},"h":{{ heading | jsonify }},"t":{{ text | jsonify }}} + {%- endfor -%} +{%- endfor %} +] diff --git a/docs/_layouts/default.html b/docs/_layouts/default.html index 05a5de2..e63a08f 100644 --- a/docs/_layouts/default.html +++ b/docs/_layouts/default.html @@ -37,8 +37,30 @@
- Parallel Factory MES + + + Parallel Factory MES {{ ui.brand_sub }} + + {{ ui.intro_link }} {%- if switch_url %} {{ ui.lang_switch }} @@ -79,6 +101,7 @@ + {%- endcapture -%} diff --git a/docs/assets/en/intro/equipment.webp b/docs/assets/en/intro/equipment.webp new file mode 100644 index 0000000..453a296 Binary files /dev/null and b/docs/assets/en/intro/equipment.webp differ diff --git a/docs/assets/en/intro/webhooks.webp b/docs/assets/en/intro/webhooks.webp new file mode 100644 index 0000000..e3a4d76 Binary files /dev/null and b/docs/assets/en/intro/webhooks.webp differ diff --git a/docs/assets/intro.css b/docs/assets/intro.css index 69adafb..76dde60 100644 --- a/docs/assets/intro.css +++ b/docs/assets/intro.css @@ -151,6 +151,9 @@ p{margin:0} .start-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:clamp(28px,5vw,64px);margin-top:clamp(48px,7vw,72px)} .start h2{font-size:clamp(22px,2.6vw,28px)} .start-lead{margin-top:10px;color:var(--muted);font-size:15px} +/* 特徴の後の「そのほかにも」。入手する の .gets/.get を使い回す */ +.more>h3{font-size:clamp(20px,2.2vw,24px)} +.more .get b{font-size:16px} .gets{margin-top:24px;display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px} .get{border:1px solid var(--line);border-radius:8px;background:var(--ground);padding:20px 22px;display:flex;flex-direction:column;align-items:flex-start;gap:10px} .get h3{font-size:19px} diff --git a/docs/assets/intro/equipment.webp b/docs/assets/intro/equipment.webp new file mode 100644 index 0000000..4974e1c Binary files /dev/null and b/docs/assets/intro/equipment.webp differ diff --git a/docs/assets/intro/webhooks.webp b/docs/assets/intro/webhooks.webp new file mode 100644 index 0000000..3282a8b Binary files /dev/null and b/docs/assets/intro/webhooks.webp differ diff --git a/docs/assets/search.js b/docs/assets/search.js new file mode 100644 index 0000000..97d0cd7 --- /dev/null +++ b/docs/assets/search.js @@ -0,0 +1,148 @@ +/* ガイド内検索。ヘッダーの検索欄に打つと、言語ごとの索引(search.json / en/search.json)を探して結果を出す。 + 索引は _includes/search-index.json がビルド時に作る(ページを見出しごとの節に区切ったもの)。 + 日本語は語を空白で区切らないので、形態素解析はせず文字列をそのまま探す。空白で区切った語は「かつ」で扱う */ +(function () { + var box = document.querySelector('.search'); + if (!box) return; + var input = box.querySelector('input'); + var panel = box.querySelector('.search-results'); + var src = box.getAttribute('data-index'); + var noneText = box.getAttribute('data-none'); + var index = null, loading = null, active = -1; + + // 全角・半角や大文字・小文字の違いで取りこぼさないようにそろえる + function norm(s) { return (s || '').normalize('NFKC').toLowerCase(); } + function esc(s) { + return s.replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); + } + + function load() { + if (!loading) { + loading = fetch(src).then(function (r) { return r.json(); }).then(function (d) { + index = d.map(function (r) { return { r: r, p: norm(r.p), h: norm(r.s + ' ' + r.h), t: norm(r.t) }; }); + }); + } + return loading; + } + + function count(hay, term) { + var n = 0, i = hay.indexOf(term); + while (i >= 0 && n < 20) { n++; i = hay.indexOf(term, i + term.length); } + return n; + } + + // text の start〜end を切り出し、当たった語を で囲む。 + // 正規化で長さが変わる文字(合字など)を含むときは位置がずれるので、囲まずにそのまま出す + function mark(text, terms, start, end) { + var part = text.slice(start, end); + var low = norm(text); + if (low.length !== text.length) return esc(part); + var lowPart = low.slice(start, end), out = '', i = 0; + while (i < part.length) { + var hit = 0; + for (var j = 0; j < terms.length; j++) { + if (terms[j].length > hit && lowPart.startsWith(terms[j], i)) hit = terms[j].length; + } + if (hit) { out += '' + esc(part.substr(i, hit)) + ''; i += hit; } + else { out += esc(part[i]); i++; } + } + return out; + } + + // 本文から、最初に当たった語の前後を抜き出す + function snippet(text, terms) { + var low = norm(text), at = -1; + for (var k = 0; k < terms.length && at < 0; k++) at = low.indexOf(terms[k]); + if (at < 0 || low.length !== text.length) at = 0; + var start = Math.max(0, at - 30), end = Math.min(text.length, at + 90); + return (start > 0 ? '…' : '') + mark(text, terms, start, end) + (end < text.length ? '…' : ''); + } + + function search(q) { + var terms = norm(q).split(/\s+/).filter(Boolean); + if (!terms.length) return []; + var res = []; + index.forEach(function (e) { + var score = 0; + for (var k = 0; k < terms.length; k++) { + // h には属する h2 の見出し(s)も含めてある + var t = terms[k], inH = e.h.indexOf(t) >= 0, inP = e.p.indexOf(t) >= 0, n = count(e.t, t); + if (!inH && !inP && !n) return; + // 見出しに当たった節を上に、次にページ名、あとは本文に出てくる回数で並べる + score += (inH ? 20 : 0) + (inP ? 8 : 0) + n; + } + res.push({ r: e.r, s: score }); + }); + res.sort(function (a, b) { return b.s - a.s; }); + return res.slice(0, 30).map(function (x) { return { r: x.r, terms: terms }; }); + } + + function render() { + var q = input.value.trim(); + if (!q) { close(); return; } + load().then(function () { + if (input.value.trim() !== q) return; + var found = search(q); + active = -1; + if (!found.length) { + panel.innerHTML = '

' + esc(noneText) + '

'; + } else { + panel.innerHTML = found.map(function (f, i) { + var r = f.r; + var href = r.u + (r.a ? '#' + encodeURIComponent(r.a) : ''); + var sep = ' '; + var title = mark(r.p, f.terms, 0, r.p.length) + + (r.s ? sep + mark(r.s, f.terms, 0, r.s.length) : '') + + (r.h ? sep + mark(r.h, f.terms, 0, r.h.length) : ''); + return '' + title + '' + + '' + snippet(r.t, f.terms) + ''; + }).join(''); + } + panel.hidden = false; + input.setAttribute('aria-expanded', 'true'); + }); + } + + function close() { + panel.hidden = true; + panel.innerHTML = ''; + active = -1; + input.setAttribute('aria-expanded', 'false'); + input.removeAttribute('aria-activedescendant'); + } + + function move(d) { + var links = panel.querySelectorAll('a'); + if (!links.length) return; + if (active >= 0) links[active].classList.remove('active'); + active = (active + d + links.length) % links.length; + links[active].classList.add('active'); + links[active].scrollIntoView({ block: 'nearest' }); + input.setAttribute('aria-activedescendant', links[active].id); + } + + var timer; + input.addEventListener('input', function () { clearTimeout(timer); timer = setTimeout(render, 120); }); + input.addEventListener('focus', function () { load(); if (input.value.trim()) render(); }); + input.addEventListener('keydown', function (ev) { + if (ev.key === 'ArrowDown') { ev.preventDefault(); move(1); } + else if (ev.key === 'ArrowUp') { ev.preventDefault(); move(-1); } + else if (ev.key === 'Enter') { + var links = panel.querySelectorAll('a'); + if (links.length) { ev.preventDefault(); links[Math.max(active, 0)].click(); } + } else if (ev.key === 'Escape') { close(); input.blur(); } + }); + // 同じページ内の節へ飛んだときも結果とスマホのメニューを閉じる + panel.addEventListener('click', function (ev) { + if (ev.target.closest('a')) { close(); document.body.classList.remove('nav-open'); } + }); + document.addEventListener('click', function (ev) { if (!box.contains(ev.target)) close(); }); + // 「/」で検索欄へ(入力欄で打っているときは除く) + document.addEventListener('keydown', function (ev) { + if (ev.key !== '/' || ev.ctrlKey || ev.metaKey || ev.altKey) return; + var t = ev.target.tagName; + if (t === 'INPUT' || t === 'TEXTAREA' || t === 'SELECT' || ev.target.isContentEditable) return; + ev.preventDefault(); + input.focus(); + }); +})(); diff --git a/docs/assets/style.css b/docs/assets/style.css index 4144cfa..2888ef6 100644 --- a/docs/assets/style.css +++ b/docs/assets/style.css @@ -1,42 +1,56 @@ :root { + /* 配色はアイコン(build/icon.svg)と紹介ページ(intro.css)にそろえる:濃紺の線とミントの3段 */ --bg: #ffffff; - --bg-alt: #f6f8fa; - --bg-side: #f9fafb; - --text: #1f2328; - --text-muted: #59636e; - --border: #d8dee4; - --accent: #1f6feb; - --accent-soft: #ddf0ff; + --bg-alt: #f4f8f6; + --bg-side: #f7faf9; + --text: #18193f; + --text-muted: #565a78; + --border: #d8e2dd; + --accent: #17785f; + --accent-soft: #e3f3ec; + --info: #2e3787; + --g1: #cdebdf; + --g2: #8fd2be; + --g3: #5cc8a8; + --logo-ink: #18193f; --danger: #b42318; --warn: #8a5a00; --warn-bg: #fff6e0; - --ok: #1a7f37; - --ok-bg: #e6f6ec; - --code-bg: #f2f4f7; + --ok: #17785f; + --ok-bg: #e3f3ec; + --code-bg: #eef3f1; --sidebar-w: 268px; } @media (prefers-color-scheme: dark) { :root { - --bg: #0f1216; - --bg-alt: #161b22; - --bg-side: #12161c; - --text: #e6edf3; - --text-muted: #9aa4b0; - --border: #2b323b; - --accent: #6cb0ff; - --accent-soft: #16283f; + --bg: #0f1024; + --bg-alt: #171933; + --bg-side: #131529; + --text: #e8ebf5; + --text-muted: #a0a5c2; + --border: #2a2d4f; + --accent: #5cc8a8; + --accent-soft: #16302d; + --info: #aeb6f0; + --g1: #1f4a40; + --g2: #2f7a66; + --g3: #5cc8a8; + --logo-ink: #e8ebf5; --danger: #ff8a80; --warn: #e3b341; --warn-bg: #2a2213; - --ok: #56d364; - --ok-bg: #12261a; - --code-bg: #1a2029; + --ok: #5cc8a8; + --ok-bg: #16302d; + --code-bg: #1c1f3b; } } * { box-sizing: border-box; } +/* 見出しへのリンク(検索の結果・目次)で飛んだとき、見出しが固定ヘッダーの下に隠れないようにする */ +html { scroll-padding-top: 68px; } + body { margin: 0; background: var(--bg); @@ -56,7 +70,7 @@ body { top: 8px; z-index: 100; background: var(--accent); - color: #fff; + color: var(--bg); padding: 8px 12px; border-radius: 6px; } @@ -71,16 +85,30 @@ body { gap: 10px; height: 52px; padding: 0 16px; - background: var(--bg-alt); + background: var(--bg); border-bottom: 1px solid var(--border); } +/* ヘッダー下端にアイコンの3段の色を帯で引く */ +.topbar::after { + content: ""; + position: absolute; + left: 0; right: 0; bottom: -1px; + height: 3px; + background: linear-gradient(90deg, var(--g1) 0 33.3%, var(--g2) 33.3% 66.6%, var(--g3) 66.6%); +} .brand { + display: inline-flex; + align-items: center; + gap: 8px; color: var(--text); text-decoration: none; font-size: 15px; letter-spacing: .01em; } .brand strong { color: var(--accent); } +.brand-mark { width: 26px; height: 26px; flex: none; } +#logo .l1 { fill: var(--g1); } #logo .l2 { fill: var(--g2); } #logo .l3 { fill: var(--g3); } +#logo .ln { fill: none; stroke: var(--logo-ink); stroke-width: 8; stroke-linecap: round; stroke-linejoin: round; } .brand-sub { color: var(--text-muted); font-size: 13px; @@ -100,7 +128,6 @@ body { /* 紹介ページ(intro.html)への導線 */ .intro-link { - margin-left: auto; white-space: nowrap; font-size: 13px; font-weight: 600; @@ -131,10 +158,69 @@ body { margin-left: 4px; vertical-align: 1px; } -/* 狭い画面では導線を優先し、「ユーザーガイド」の副題を隠す */ -@media (max-width: 480px) { +/* ガイド内検索(assets/search.js)。結果は検索欄の下に重ねて出す */ +.search { + position: relative; + margin-left: auto; + flex: 0 1 260px; + min-width: 0; +} +.search input { + width: 100%; + font: inherit; + font-size: 13.5px; + line-height: 1.4; + color: var(--text); + background: var(--bg-alt); + border: 1px solid var(--border); + border-radius: 999px; + padding: 5px 14px; +} +.search input:focus { outline: 2px solid var(--accent); outline-offset: -1px; background: var(--bg); } +.search-results { + position: absolute; + top: calc(100% + 8px); + right: 0; + width: min(520px, calc(100vw - 32px)); + max-height: min(70vh, 560px); + overflow-y: auto; + background: var(--bg); + border: 1px solid var(--border); + border-radius: 10px; + box-shadow: 0 10px 30px rgba(24, 25, 63, .18); + padding: 6px; + z-index: 40; +} +.search-results a { + display: block; + padding: 8px 10px; + border-radius: 8px; + color: var(--text); + text-decoration: none; + line-height: 1.55; +} +.search-results a:hover, .search-results a.active { background: var(--accent-soft); } +.search-results b { display: block; font-size: 14px; font-weight: 600; } +.search-results b span { color: var(--text-muted); font-weight: 400; } +.search-results a > span { display: block; font-size: 12.5px; color: var(--text-muted); } +.search-results mark { background: var(--g1); color: inherit; border-radius: 2px; padding: 0 1px; } +.search-none { margin: 8px 10px; font-size: 13px; color: var(--text-muted); } + +.brand, .brand-sub { white-space: nowrap; } +/* 狭い画面では検索欄と導線を優先し、「ユーザーガイド」の副題を隠す */ +@media (max-width: 900px) { .brand-sub { display: none; } } +/* スマホの幅では、検索欄の場所を空けるためにロゴの文字を隠し、結果を画面の幅いっぱいに出す。 + 紹介ページへの導線は、さらに狭いときはメニュー(_data/nav.yml の先頭)に任せて隠す */ +@media (max-width: 640px) { + .brand > span { display: none; } + .search { flex: 1 1 auto; } + .search-results { position: fixed; top: 60px; left: 8px; right: 8px; width: auto; } +} +@media (max-width: 480px) { + .intro-link { display: none; } +} /* ---------- layout ---------- */ .shell { @@ -179,6 +265,7 @@ body { background: var(--accent-soft); color: var(--accent); font-weight: 600; + box-shadow: inset 3px 0 0 var(--g3); } .content { @@ -199,6 +286,8 @@ h2 { margin: 44px 0 12px; padding-bottom: 8px; border-bottom: 1px solid var(--border); + /* 下線の左端にアクセントを短く重ねる */ + background: linear-gradient(var(--g3), var(--g3)) left bottom / 48px 2px no-repeat; } h3 { font-size: 17px; margin: 30px 0 8px; } h4 { font-size: 15px; margin: 22px 0 6px; color: var(--text-muted); } @@ -270,7 +359,7 @@ tbody tr:nth-child(even) td { background: var(--bg-alt); } background: var(--bg-alt); font-size: 14.5px; } -.note { border-left: 4px solid var(--accent); } +.note { border-left: 4px solid var(--info); } .warn { border-left: 4px solid var(--warn); background: var(--warn-bg); } .tip { border-left: 4px solid var(--ok); background: var(--ok-bg); } .note p:first-child, .warn p:first-child, .tip p:first-child { margin-top: 0; } @@ -293,7 +382,7 @@ ol.steps > li::before { height: 25px; border-radius: 50%; background: var(--accent); - color: #fff; + color: var(--bg); font-size: 13px; font-weight: 700; display: flex; @@ -386,16 +475,16 @@ ol.steps > li::before { /* ---------- 図解(walkthrough.md) ---------- */ /* 担当ロールの色。図の枠と凡例で同じ色を使う */ :root { - --r-pm: #1f6feb; --r-pm-bg: #ddf0ff; /* 生産管理 */ - --r-op: #1a7f37; --r-op-bg: #e6f6ec; /* 現場作業者 */ + --r-pm: #2e3787; --r-pm-bg: #dce0f5; /* 生産管理 */ + --r-op: #17785f; --r-op-bg: #e3f3ec; /* 現場作業者 */ --r-lg: #9a6700; --r-lg-bg: #fff6e0; /* 物流・倉庫 */ --r-qc: #8250df; --r-qc-bg: #f3ecff; /* 品質管理・品質保証 */ --r-ng: #b42318; --r-ng-bg: #ffebe9; /* 不良・逸脱 */ } @media (prefers-color-scheme: dark) { :root { - --r-pm: #6cb0ff; --r-pm-bg: #16283f; - --r-op: #56d364; --r-op-bg: #12261a; + --r-pm: #aeb6f0; --r-pm-bg: #232a55; + --r-op: #8fd2be; --r-op-bg: #16302d; --r-lg: #e3b341; --r-lg-bg: #2a2213; --r-qc: #c297ff; --r-qc-bg: #231a38; --r-ng: #ff8a80; --r-ng-bg: #3a1618; diff --git a/docs/basics.md b/docs/basics.md index 17a9528..3c22a41 100644 --- a/docs/basics.md +++ b/docs/basics.md @@ -103,4 +103,4 @@ next_title: サンプルで見る 製造から出荷まで つまり、5月2日の午前3時に登録した実績は「5月1日」の製造日として集計されます。 夜勤の日跨ぎ実績を同じ製造日にまとめるための仕組みです。境界時刻は設定で変更できます -([管理者向け運用](operations.html))。 +([サーバーの配置と設定](operations.html))。 diff --git a/docs/database.md b/docs/database.md new file mode 100644 index 0000000..2158b1c --- /dev/null +++ b/docs/database.md @@ -0,0 +1,93 @@ +--- +layout: default +title: データベースとバックアップ +nav_url: database.html +lead: "PostgreSQL / SQL Server への切替と、データのバックアップ・復元です。" +prev_url: security.html +prev_title: セキュリティと監査ログ +next_url: reference.html +next_title: リファレンス +--- + +## PostgreSQL / SQL Server を使う {#database} + +既定の SQLite は追加インストールが要らず、数十端末規模までならそのまま運用できます。 +同時に書き込む端末が多い、データ量が大きい、既存のDBサーバーでまとめて管理したい、といった場合は +PostgreSQL または SQL Server に切り替えます。 + +1. DBサーバーに**空のデータベース**と接続用のログインを作ります。 + ログインには、そのデータベースでテーブルを作成・変更できる権限を与えます(起動時にスキーマを作成・更新するため)。 +2. `Database__Provider` と `Database__ConnectionString` を設定して起動します。 + +```powershell +# PostgreSQL +$env:Database__Provider="PostgreSql"; $env:Database__ConnectionString="Host=db;Database=mesapp;Username=mesapp;Password=..." +# SQL Server +$env:Database__Provider="SqlServer"; $env:Database__ConnectionString="Server=db;Database=mesapp;User Id=mesapp;Password=...;TrustServerCertificate=True" +``` + +3. 起動時にテーブルが作られます。ブラウザで開くと、SQLiteのときと同じく初期セットアップの案内が表示されます。 + 以降のバージョンアップでも、起動時に差分が自動適用されます。 + +
+

既存のSQLiteのデータは移りません。 切り替えると空のデータベースから始まります。 +運用を始める前にどのデータベースを使うかを決めてください。設定をSQLiteに戻すと、元の mesapp.db がそのまま使われます(両者のデータは別々です)。

+
+ +### SQLite との違い + +| 項目 | 違い | +|---|---| +| コードの大文字・小文字 | SQL Server の既定の照合順序では区別しません(`ABC` と `abc` は同じコードとして重複扱いになり、検索も区別しません)。SQLite・PostgreSQL は区別します | +| 日時 | PostgreSQL ではUTCで保存されます。同じ時点を指すため、画面表示・集計・CSVの結果は変わりません | +| 小数 | 小数点以下6桁まで保存します(SQLite と同じ値の見え方になるよう末尾のゼロは落とします) | +| デスクトップ版 | SQLite で使う前提です(1台のPCで完結させる構成のため) | + +### 起動しないとき + +| 症状 | 対処 | +|---|---| +| 「不明なDBプロバイダー」で止まる | `Database__Provider` は `Sqlite` / `PostgreSql` / `SqlServer` のいずれかを、大文字・小文字も含めてそのとおりに書いてください | +| 接続のタイムアウト・認証エラーで止まる | 接続文字列のホスト名・ポート・ユーザー名・パスワード、DBサーバー側のファイアウォール、SQL Server では TCP/IP 接続が有効かを確認してください | +| SQL Server で証明書のエラーになる | 社内の自己署名証明書のサーバーなら接続文字列に `TrustServerCertificate=True` を付けるか、信頼された証明書をサーバーに設定してください | +| 権限エラー(テーブルを作成できない)で止まる | 接続ログインに、対象データベースでのテーブル作成・変更の権限を与えてください | + +## バックアップ {#backup} + +### SQLite + +
+

稼働中のDBファイルを単純コピーしないでください。 +SQLiteはWALモードで動作するため、コピーしたファイルが壊れる可能性があります。

+
+ +安全な方法は次の2つです。 + +1. サーバーを停止してから `mesapp.db` をコピーする +2. 稼働中なら SQLite の `VACUUM INTO` でバックアップファイルを作る + +Docker の場合は、コンテナを止めてからボリュームごと退避します(署名鍵と、Webhook の秘密の値を暗号化する鍵も一緒に残ります)。 +ボリューム名は `docker volume ls` で確認してください(compose では `<フォルダ名>_mesapp-data`)。 + +```bash +docker compose stop +docker run --rm -v <ボリューム名>:/data -v "$PWD":/backup alpine tar czf /backup/mesapp-data.tgz -C /data . +docker compose start +``` + +`mesapp.db*`(`-wal` / `-shm` を含む)をすべて削除して再起動すると、初期状態に戻ります。 +検証環境をリセットしたいときに使えます。 + +### PostgreSQL / SQL Server + +各データベースの標準の手段でバックアップします(稼働中でも取得できます)。 + +- PostgreSQL: `pg_dump -Fc -d mesapp -f mesapp.dump`(復元は `pg_restore`) +- SQL Server: `BACKUP DATABASE mesapp TO DISK = N'...\mesapp.bak'`(または SQL Server Management Studio のバックアップ) + +初期状態に戻すには、データベースを削除して空のデータベースを作り直し、再起動します。 + +### データ保存先の鍵 + +データベースとは別に、データ保存先の `jwt-signing.key`(ログインの署名鍵)と `dataprotection-keys` フォルダ([Webhook](integration.html#webhooks) の秘密の値を暗号化する鍵)も退避してください。 +`dataprotection-keys` を失うと、戻したデータベースにある Webhook の秘密の値を復号できず、送信先ごとに秘密の値を再発行することになります。 diff --git a/docs/en/basics.md b/docs/en/basics.md index b8c4937..4be3f64 100644 --- a/docs/en/basics.md +++ b/docs/en/basics.md @@ -103,4 +103,4 @@ By default the date changes at **6:00 a.m.** This means that actuals registered at 3:00 a.m. on May 2 are counted under the production date "May 1". This keeps night-shift actuals that cross midnight together under the same production date. The boundary time can be changed in the settings -([Administration](operations.html)). +([Server deployment and settings](operations.html#settings)). diff --git a/docs/en/database.md b/docs/en/database.md new file mode 100644 index 0000000..f214063 --- /dev/null +++ b/docs/en/database.md @@ -0,0 +1,93 @@ +--- +layout: default +title: Databases and backups +nav_url: database.html +lead: "Switching to PostgreSQL / SQL Server, and backing up and restoring data." +prev_url: security.html +prev_title: Security and audit log +next_url: reference.html +next_title: Reference +--- + +## Using PostgreSQL / SQL Server {#database} + +The default SQLite needs no extra installation and can be used as is for up to a few dozen devices. +When many devices write at the same time, the data volume is large, or you want to manage it together on an existing DB server, +switch to PostgreSQL or SQL Server. + +1. Create an **empty database** and a login for connecting on the DB server. + Give the login permission to create and change tables in that database (the schema is created and updated at startup). +2. Set `Database__Provider` and `Database__ConnectionString` and start it. + +```powershell +# PostgreSQL +$env:Database__Provider="PostgreSql"; $env:Database__ConnectionString="Host=db;Database=mesapp;Username=mesapp;Password=..." +# SQL Server +$env:Database__Provider="SqlServer"; $env:Database__ConnectionString="Server=db;Database=mesapp;User Id=mesapp;Password=...;TrustServerCertificate=True" +``` + +3. The tables are created at startup. When you open it in a browser, the initial setup guidance is shown, just as with SQLite. + In later upgrades, the differences are also applied automatically at startup. + +
+

Existing SQLite data is not carried over. After switching, you start from an empty database. +Decide which database to use before you start operating. If you switch the setting back to SQLite, the original mesapp.db is used as is (the two sets of data are separate).

+
+ +### Differences from SQLite + +| Item | Difference | +|---|---| +| Upper and lower case in codes | With SQL Server's default collation they are not distinguished (`ABC` and `abc` are treated as the same, duplicate code, and searches do not distinguish them either). SQLite and PostgreSQL distinguish them | +| Date and time | PostgreSQL stores them in UTC. They refer to the same moment, so screen display, totals and CSV results do not change | +| Decimals | Up to 6 decimal places are stored (trailing zeros are dropped so that values look the same as in SQLite) | +| Desktop edition | Intended for use with SQLite (because it is designed to run entirely on one PC) | + +### When it does not start + +| Symptom | What to do | +|---|---| +| It stops with an "unknown DB provider" error (the message is in Japanese: 不明なDBプロバイダー) | Write `Database__Provider` as exactly one of `Sqlite` / `PostgreSql` / `SqlServer`, including upper and lower case | +| It stops with a connection timeout or authentication error | Check the host name, port, user name and password in the connection string, the firewall on the DB server, and, for SQL Server, whether TCP/IP connections are enabled | +| SQL Server gives a certificate error | For a server with an internal self-signed certificate, add `TrustServerCertificate=True` to the connection string, or configure a trusted certificate on the server | +| It stops with a permission error (cannot create tables) | Give the connecting login permission to create and change tables in the target database | + +## Backups {#backup} + +### SQLite + +
+

Do not simply copy the DB file while it is running. +SQLite runs in WAL mode, so the copied file may be corrupted.

+
+ +There are two safe methods. + +1. Stop the server, then copy `mesapp.db` +2. While it is running, create a backup file with SQLite's `VACUUM INTO` + +With Docker, stop the container and save the whole volume (the signing key and the keys that encrypt the webhook secrets are kept along with it). +Check the volume name with `docker volume ls` (with compose it is `_mesapp-data`). + +```bash +docker compose stop +docker run --rm -v :/data -v "$PWD":/backup alpine tar czf /backup/mesapp-data.tgz -C /data . +docker compose start +``` + +Deleting all of `mesapp.db*` (including `-wal` / `-shm`) and restarting returns it to the initial state. +You can use this to reset a test environment. + +### PostgreSQL / SQL Server + +Back up with each database's standard tools (backups can be taken while it is running). + +- PostgreSQL: `pg_dump -Fc -d mesapp -f mesapp.dump` (restore with `pg_restore`) +- SQL Server: `BACKUP DATABASE mesapp TO DISK = N'...\mesapp.bak'` (or a backup from SQL Server Management Studio) + +To return to the initial state, drop the database, create an empty one again and restart. + +### Keys in the data folder + +Besides the database, also save `jwt-signing.key` (the sign-in signing key) and the `dataprotection-keys` folder (the keys that encrypt the [webhook](integration.html#webhooks) secrets) in the data folder. +If `dataprotection-keys` is lost, the webhook secrets in a restored database cannot be decrypted, and you will need to reissue the secret for each destination. diff --git a/docs/en/getting-started.md b/docs/en/getting-started.md index 50956e9..66b58ab 100644 --- a/docs/en/getting-started.md +++ b/docs/en/getting-started.md @@ -25,7 +25,7 @@ Every method is free, with no activation or license key. Except when running fro | Item | Details | |---|---| | Server | One Windows / Linux (x64) PC, or an environment that runs Docker (amd64 / arm64). The Store edition needs Windows 10 (2004 or later) / 11 | -| Database | Not required. By default an SQLite file (`mesapp.db`) is created automatically. PostgreSQL / SQL Server can also be used ([Administration](operations.html#database)) | +| Database | Not required. By default an SQLite file (`mesapp.db`) is created automatically. PostgreSQL / SQL Server can also be used ([Databases and backups](database.html#database)) | | Client devices | A modern browser (Chrome, Edge and so on). No dedicated app needs to be installed | | Network | Client devices must be able to reach the server's URL | @@ -55,7 +55,7 @@ docker run -d -p 8080:8080 -v mesapp-data:/data ghcr.io/msmsrep/parallelfactorym ``` Open `http://localhost:8080` in a browser. Without `-v mesapp-data:/data`, your data is lost when the container is recreated. -To run it together with PostgreSQL, see [Administration](operations.html#docker). +To run it together with PostgreSQL, see [Server deployment and settings](operations.html#docker). ### Running from source (for development) @@ -65,7 +65,7 @@ Install the .NET 10 SDK and run the following in the repository root. By default dotnet run --project src/MesApp.Api ``` -For the settings needed to use it from other PCs on the same LAN (port, firewall, HTTPS), see [Administration](operations.html). +For the settings needed to use it from other PCs on the same LAN (port, firewall, HTTPS), see [Server deployment and settings](operations.html).

The database file and signing key are created automatically in the data folder. You do not need to create a database. diff --git a/docs/en/index.md b/docs/en/index.md index f3b6329..7d1da7c 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -14,7 +14,7 @@ so you can use it directly from shop-floor PCs and tablets. - **It manages the whole flow from manufacturing order to shipment.** Manufacturing order → work orders for each process → actuals → inventory → inspection → shipment judgment → shipment. - **It traces everything by lot.** You can follow in both directions which material lots went into which product lots. -- **Every record keeps "who and when".** Corrections to actuals and inspections, master data changes, inventory operations and cancellations are recorded in the audit log, which you can view on the [Audit Log screen](operations.html#audit-log) (system administrators only). +- **Every record keeps "who and when".** Corrections to actuals and inspections, master data changes, inventory operations and cancellations are recorded in the audit log, which you can view on the [Audit Log screen](security.html#audit-log) (system administrators only). diff --git a/docs/en/integration.md b/docs/en/integration.md new file mode 100644 index 0000000..7585e86 --- /dev/null +++ b/docs/en/integration.md @@ -0,0 +1,331 @@ +--- +layout: default +title: Integrations +nav_url: integration.html +lead: "How to connect the MES with other systems and equipment: folder integration for CSV, API keys and the integration API, receiving equipment events, and Webhook notifications." +prev_url: operations.html +prev_title: Server deployment and settings +next_url: security.html +next_title: Security and audit log +--- + +## Folder integration {#folder-link} + +CSV files placed in a chosen folder are imported automatically. CSV files exported by sales or production management software +can be imported without writing a program (for example, have the manufacturing order CSV exported every morning placed in a shared folder). + +### Setting it up + +1. Create the user who performs the imports (for example `folder-link`). Give it **only the roles needed for the types you want to import** + (Production management for manufacturing orders, Logistics / warehouse for receiving; see [Roles and permissions](roles.html) for what each role can do). + Whether an import is allowed, who is recorded on actuals, and the audit log are all decided and recorded as this user. +2. Set the integration folder and the user, then restart. + +```powershell +$env:FolderLink__Root="D:\mes-link"; $env:FolderLink__UserName="folder-link"; ./start.cmd +``` + +With Docker, mount the integration folder from a folder on the host (example for `compose.yaml`). + +```yaml + volumes: + - mesapp-data:/data + - ./mes-link:/link + environment: + FolderLink__Root: /link + FolderLink__UserName: folder-link +``` + +Changing the settings requires a restart. On startup, `inbox`, `processed` and `error` are created under the integration folder. + +### Where to put files + +| Location | How the type is determined | Example | +|---|---|---| +| Directly in `inbox` | File name (the part after the first "_") | `inbox/manufacturing-orders.csv`, `inbox/20261122_manufacturing-orders.csv` | +| `inbox//` | Folder name (any file name) | `inbox/manufacturing-orders/orders.csv` | +| A ZIP directly in `inbox` | File names inside (same as ZIP bulk import) | `inbox/masters.zip` | + +- The type names and CSV columns are the same as the templates on the Master Data and Actuals CSV Import screens. For software that cannot change the name of the file it exports, have it export into the type's folder. +- Files other than CSV and ZIP are ignored. Files being written are imported after writing finishes. +- Files are imported one at a time in the order they were placed (oldest modification time first). When a later file refers to an earlier one (receiving after manufacturing orders, for example), place them in order or put them in one ZIP. + +### Checking the results + +- **Imported files are moved to `processed` and files that could not be imported to `error`**, under `date/time/`, with a result file (`.result.txt`) beside them. The line numbers and reasons for errors are written there. +- Imports go through the same checks as importing from the screens, and **if even one row has an error, nothing in that file is applied**. Put the corrected file back in the same place in `inbox` to import it again. +- System administrators can check settings errors and recently processed files under "Administration" → "Folder integration" in the menu. "Import now" imports without waiting for the next interval. +- If the user does not exist, is inactive or is locked out, nothing is imported and the files stay in `inbox` (the reason is shown on the screen). + +There is no integration that writes data out of the MES yet (automatic export of actuals). + +## API keys {#api-keys} + +Keys that systems such as sales or production management software, or in-house scripts, use to call the MES **integration API** (`/api/integration/v1/...`) without signing in. + +### Issuing a key + +1. Create the user the key will act as (for example `erp-link`). **What the key can do is determined by this user's roles.** Create a dedicated user for each purpose and give it only the roles it needs ([Roles and permissions](roles.html)). +2. A system administrator opens "Administration" → "API keys" in the menu, specifies the purpose, the user and an optional expiry, and clicks **Issue key**. +3. Copy the key shown (a string starting with `pfm_`) into the settings of the connecting system. **The key is shown only at this time.** If it is lost, revoke it and issue a new one. + +### Trying it + +Send the key in the `X-Api-Key` request header. The following endpoint shows who you are treated as (the user and roles). + +```powershell +Invoke-RestMethod http://localhost:5000/api/integration/v1/whoami -Headers @{ "X-Api-Key" = "pfm_..." } +``` + +```bash +curl -H "X-Api-Key: pfm_..." http://localhost:5000/api/integration/v1/whoami +``` + +### Notes + +- Keys work only with the integration API. The APIs used by the screens (such as `/api/products`) cannot be called with a key (401). +- Operations performed with a key are recorded in the audit log as the linked user. +- **A revoked key cannot be restored.** A key also stops working immediately when its user is deactivated or its expiry passes. When the user's roles change, the next call is checked with the new roles. +- Treat keys like passwords. Do not paste them into email or chat; keep them only in the settings of the connecting system. + +## Integration API {#integration-api} + +An API for exchanging data with the MES from sales or production management software (ERP) or in-house scripts. Calls use an [API key](#api-keys). + +### Specification (OpenAPI) + +The integration API specification is published at `/openapi/integration-v1.json` (for example `http://localhost:5000/openapi/integration-v1.json`). +Load it into Postman, Visual Studio or similar tools to see the endpoints, parameters and response shapes. No key is needed to get the specification. + +### Endpoints + +| Endpoint | Purpose | +|---|---| +| `GET /api/integration/v1/whoami` | Check that the key works and who you are treated as, with which roles | +| `GET /api/integration/v1/csv-kinds` | The CSV types and columns that can be imported (the same as the Master Data and Actuals CSV Import screens) | +| `POST /api/integration/v1/masters/{type}` | Import a master data CSV (overwritten by code) | +| `POST /api/integration/v1/actuals/{type}` | Import an actuals CSV (always registered as new) | +| `POST /api/integration/v1/masters/bundle`, `actuals/bundle` | Import a ZIP of CSV files | +| `GET /api/integration/v1/masters/{type}` | Export master data as CSV | +| `GET /api/integration/v1/production-results` | Read production results from where you left off | +| `GET /api/integration/v1/production-result-corrections` | Read corrections to production results from where you left off | +| `POST /api/integration/v1/equipment-events` | Send equipment status changes ([Receiving equipment events](#equipment-events)) | + +### Importing CSV + +Send the CSV as the request body (UTF-8 or Shift_JIS). Add `?dryRun=true` to only validate without applying anything. +The PowerShell examples on this page are for PowerShell 7 (`pwsh`). + +```powershell +$headers = @{ "X-Api-Key" = "pfm_..."; "Idempotency-Key" = "orders-20261123" } +Invoke-RestMethod -Method Post -Headers $headers -ContentType "text/csv; charset=utf-8" -InFile .\manufacturing-orders.csv -Uri http://localhost:5000/api/integration/v1/actuals/manufacturing-orders +``` + +```bash +curl -H "X-Api-Key: pfm_..." -H "Idempotency-Key: orders-20261123" -H "Content-Type: text/csv" --data-binary @manufacturing-orders.csv http://localhost:5000/api/integration/v1/actuals/manufacturing-orders +``` + +- **200** when imported, and **422** if even one row has an error, in which case nothing is applied. In both cases the response body contains the counts and errors with line numbers (in PowerShell 7, add `-SkipHttpErrorCheck` to also receive the body of a 422). +- Import permission is checked with the roles of the user linked to the key, the same as on the screens (403 without permission). + +### Sending again without registering twice (Idempotency-Key) + +Actuals CSV files are **always registered as new**, so sending the same CSV again after a dropped connection can register it twice. +To prevent this, put a value chosen for each content you send (for example the order export time and a sequence number, or a UUID) in the `Idempotency-Key` header. + +- If you send the same key with the same content again, **the previous response is returned without importing again** (the response has the header `Idempotent-Replayed: true`). +- A request with the same key but different content gets 409. Use a new key for new content. +- Keys are remembered for 24 hours, separately for each API key. + +### Reading production results (from where you left off) + +Pass the previous `nextAfterId` as `afterId` to get only the results recorded after it. Keep reading while `hasMore` is true. +Save the last `nextAfterId` so that the next run starts where this one ended. + +```powershell +$headers = @{ "X-Api-Key" = "pfm_..." } +$after = if (Test-Path .\last-id.txt) { Get-Content .\last-id.txt } else { 0 } +do { + $page = Invoke-RestMethod -Headers $headers -Uri "http://localhost:5000/api/integration/v1/production-results?afterId=$after" + $page.items | Export-Csv .\production-results.csv -Append -Encoding utf8 + $after = $page.nextAfterId +} while ($page.hasMore) +Set-Content .\last-id.txt $after +``` + +- Quantities are the current values after any correction. To learn that a result you already read was corrected later, read `production-result-corrections` from where you left off in the same way. +- Results not yet approved are also returned (`approvedAt` is empty). Results of canceled orders are also returned because the physical lots remain (see `workOrderStatus`). + +### Promises that keep integrations working after upgrades + +- Within v1 (`/api/integration/v1`), **fields and endpoints are only added**, never removed, renamed or given a new meaning. Such changes go into a v2. +- The same applies to CSV columns. Columns are not removed and no required columns are added (if you leave out a new column, things work as before). When a column is renamed, its former name can still be read. +- Build your integrations to skip fields they do not know, in case new fields are added to responses. + +## Receiving equipment events {#equipment-events} + +A mechanism that records equipment operation status (running, stopped, setup, failure, idle) automatically from the equipment. +**The MES does not communicate with PLCs directly.** A gateway (such as Node-RED) reads the PLC status and sends it to the MES integration API when the status changes. +The MES sorts the received status changes by time for each piece of equipment and builds them into **intervals in the operation history** (start to end). + +``` +Equipment / PLC ──(OPC UA, MC protocol, Modbus, etc.)──▶ Gateway ──(HTTP, API key)──▶ MES + (Node-RED, etc.) POST /api/integration/v1/equipment-events +``` + +### Preparation + +1. In the equipment master (the **Equipment (BOE)** tab in master management), turn on **Collect operation status from equipment events** for the target equipment. + Operation cannot then be registered for that equipment by manual entry or actuals CSV (so the same time is not counted twice by hand and automatically). Stop causes can still be added. +2. Create a user for the gateway and issue an [API key](#api-keys). Receiving does not depend on roles. +3. If needed, register a **Stop cause mapping** (master management) that replaces alarm codes with stop causes. + +### What to send + +Create one event each time the status changes, collect them, and send them together (up to 1,000 at a time). + +```json +{ + "events": [ + { "equipmentCode": "EQ-06", "eventId": "EQ-06-1732323600000-1", "occurredAt": "2026-11-23T09:00:00+09:00", "state": "Running" }, + { "equipmentCode": "EQ-06", "eventId": "EQ-06-1732324200000-2", "occurredAt": "2026-11-23T09:10:00+09:00", "state": "Stopped", "alarmCode": "A-101" } + ] +} +``` + +| Item | Description | +|---|---| +| `equipmentCode` | The equipment asset No. | +| `eventId` | A unique ID assigned by the gateway (unique per equipment, up to 100 characters). Keep **the same value when resending** | +| `occurredAt` | The time the status changed on the equipment (with an offset such as `+09:00`) | +| `state` | `Running` / `Stopped` / `Setup` / `Failure` / `Idle` / `Off` (power off or connection lost) | +| `alarmCode` | Optional. The alarm code for a stop or failure (the cause is looked up in the stop cause mapping) | +| `workOrderNo` + `operationSeq` | Optional. The work order being processed (a pair of order number and operation sequence) | +| `note` | Optional. A note | + +```powershell +$headers = @{ "X-Api-Key" = "pfm_..." } +$body = @{ events = @(@{ equipmentCode = "EQ-06"; eventId = "test-1"; occurredAt = (Get-Date).ToString("o"); state = "Running" }) } | ConvertTo-Json -Depth 4 +Invoke-RestMethod -Method Post -Headers $headers -ContentType "application/json" -Body $body -Uri http://localhost:5000/api/integration/v1/equipment-events +``` + +### What happens after an event arrives + +- When a new status arrives, the open interval is closed and the next interval is opened. Repeated events with the same status do not change the interval. `Off` only closes the interval. +- Events sent together may be out of time order; they are re-sorted by time before being applied. +- **Resending the same `eventId` results in "Duplicate" and is not recorded twice.** When the connection drops, resend the collected events as they are. +- **Events earlier than the last applied time are rejected as late arrivals.** Past intervals are not rebuilt. Synchronize the clocks of the equipment and gateway with NTP. Times too far ahead of the server time (more than 300 seconds by default) are also rejected. +- The response is 200 and contains a result for each event (`Accepted`, `Duplicate`, or `Rejected` with the reason). It is 200 even if all are rejected. A rejected `eventId` is judged again when it is corrected and resent. +- For stop and failure intervals, the stop cause is looked up from the alarm code in the stop cause mapping. If it is not found, the interval is recorded **without a stop cause**, which can be entered later on the operation monitoring tab in maintenance. +- The work order is linked if specified. If not specified, it is linked **only when exactly one started work order is assigned to that equipment**. + +You can see what is being received under **Current equipment status** on the operation monitoring tab in maintenance. When no events have been received for a while (10 minutes by default), "(no events received)" appears for that equipment, so you can notice that the gateway has stopped. + +### Trying the sample (Docker) + +`compose.yaml` has an `equipment` profile that also starts an MQTT broker (Eclipse Mosquitto) and a Node-RED gateway. +Node-RED contains a **simulated piece of equipment** that changes status every few seconds and a flow that receives MQTT messages and sends them to the MES together (`samples/equipment-gateway`). + +1. Run `docker compose --profile equipment up -d` in the repository root. +2. Import the sample master data into the MES (http://localhost:8080). `EQ-06` is set to collect status from equipment events. +3. Issue an API key, write `MES_API_KEY=pfm_...` in `.env` in the repository root, and run `docker compose --profile equipment up -d` again. +4. On the operation monitoring tab, check that the current status and operation history of `EQ-06` grow. In Node-RED (http://localhost:1880), the status of the node that checks the result (the last function node in step ③ of the flow) shows the numbers accepted, duplicate and rejected. + +To adapt it to your own equipment, replace the simulated equipment (the function node in step ① of the flow) with a node that reads the status from the PLC (OPC UA, MC protocol, Modbus, etc.). +The sample MQTT broker is a minimal setup without authentication or encryption. Configure passwords and TLS for production. + +## Webhooks (notifications from the MES) {#webhooks} + +When an event you want to know about **right away** happens, such as a nonconformance being raised, equipment stopping or a lot being put on hold, the MES notifies the URLs you register over HTTP. +Use it for alerts to the team leaders' chat or to start the next process when production is completed. +Systems that only need data periodically (such as inventory and costing in the ERP) can read production results with the [integration API](#integration-api) instead. + +Notifications are kept **thin**. Only the type, the time, the numbers of what changed and a one-sentence summary are sent. +A notification is a cue to fetch data. Get the correct current values from the integration API (this also lets you catch up when a notification did not arrive or arrived out of order). + +``` +MES ──(POST, signed)──▶ Receiver (Node-RED, in-house script, etc.) ──▶ Chat, display board, ERP +``` + +### Registering a destination + +1. A system administrator opens "Administration" → "Webhooks" in the menu, and on the **Destinations** tab chooses the purpose, the destination URL and the events to notify, then clicks **Register**. +2. Copy the **Signing secret** shown (a string starting with `whsec_`) into the receiver's settings. **The value is shown only at this time.** If it is lost, click **Reissue secret** (the old value stops working immediately, so update the receiver's settings too). +3. Click **Send test** to check that the receiver gets it. The result is shown on the spot (a test that fails is not retried). + +- The URL can also be `http://` (for the factory's internal network). Bodies sent to an `http://` destination are not encrypted, so use `https://` when sending outside the company. +- A URL containing a user name or password cannot be registered (the URL is shown as it is in the list and the audit log). The receiver verifies the sender by the signature. +- To stop sending without deleting, clear **Active**. Deleting a destination also deletes its pending notifications and its delivery records. + +### Events to notify + +| Type | When | Main fields | +|---|---|---| +| `production-result.created` | A production result was recorded (from the screens, actual CSV or the integration API) | Order number, work order number, sequence, item code, good/defect quantities, output lot | +| `production-result.corrected` | A production result was corrected | `productionResultId` of the corrected result, quantities before and after, reason | +| `work-order.status-changed` | A work order's status changed (dispatch, start, completion, approval, cancellation) | Work order number, status before and after | +| `manufacturing-order.status-changed` | A manufacturing order was completed or canceled | Order number, order type, status before and after | +| `lot.status-changed` | A lot's stock status changed (hold, release, awaiting inspection, etc.) | Lot number, item code, before and after, trigger, reason | +| `nonconformance.created` | A nonconformance was raised (including those raised automatically when an inspection fails) | Nonconformance number, source, lot number, item code | +| `equipment.stopped` | Equipment entered a stopped or failure interval (from manual entry, actual CSV or [equipment events](#equipment-events)) | Asset number, status, stop cause, alarm code | + +Types and statuses are sent as English names (such as `OnHold`) so that they do not change with the display language. Internal IDs are not sent; records are identified by numbers and codes. +The summary (`summary`) is in Japanese. + +### What is sent + +```json +{ + "id": "c548bec2-5e89-4210-ba22-2110c0325f09", + "sequence": 7, + "type": "equipment.stopped", + "version": 1, + "occurredAt": "2026-11-23T11:02:01+00:00", + "summary": "…", + "data": { "equipmentAssetNo": "EQ-01", "status": "Stopped", "startedAt": "2026-11-23T10:32:00+00:00", "endedAt": null, + "stopCause": "Material shortage", "alarmCode": null, "source": "Manual", "workOrderNo": null } +} +``` + +The `summary` is a Japanese sentence such as `設備 EQ-01 が「停止」になりました(Material shortage)。` (equipment EQ-01 has stopped). + +| Field or header | Description | +|---|---| +| `id` | The notification's unique ID. **The same value when resent** (the receiver uses it to discard duplicates) | +| `sequence` | A number that increases across types (not necessarily consecutive) | +| `data` | The content for each type (the table above). The list of fields is in the `webhooks` section of the [specification (OpenAPI)](#integration-api) | +| `X-Mes-Event` | The type (the same as `type` in the body) | +| `X-Mes-Delivery` | The delivery ID (the same when resent) | +| `X-Mes-Timestamp` | The time it was sent (Unix seconds) | +| `X-Mes-Signature` | The signature: `sha256=` followed by the lowercase hexadecimal HMAC-SHA256 of "the `X-Mes-Timestamp` value, `.`, the body", keyed with the secret | + +### What the receiver should check + +1. **Verify the signature** using the exact bytes of the body you received. If you parse the JSON and turn it back into a string, the way numbers are written and other details change and the signature no longer matches. +2. **Check the time.** Reject the request if `X-Mes-Timestamp` is off by more than 5 minutes (to block old requests being replayed). Synchronize the clocks of the MES and the receiver with NTP. +3. **Return 2xx right away.** The MES waits up to 10 seconds by default and resends if no response arrives. Do heavy work after responding. +4. **Discard the second and later copies of the same `id`.** Notifications are delivered at least once, so the same notification can arrive twice. The order is not guaranteed either. + +### When delivery fails + +- If the destination cannot be reached, does not respond in time, or returns `5xx`, `408` or `429`, the MES resends at increasing intervals (1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours, 24 hours; up to 8 attempts by default). +- Other `4xx` and `3xx` responses stop after one attempt, because resending would give the same result (redirects are not followed). +- For a stopped notification, fix the receiver, then click **Resend** on the **Deliveries** tab. The notification's `id` does not change, so a receiver that already got it discards it as a duplicate. +- Destinations with notifications waiting to be resent or stopped appear under "Undelivered" on the **Destinations** tab and at the top of the system administrator's **Dashboard**. Destinations are never stopped automatically. +- Delivery records are kept for 30 days by default. +- If the `dataprotection-keys` folder (the keys that encrypt the secrets) in the data folder is lost, the secrets cannot be decrypted and notifications to those destinations stop. Reissue the secret, update the receiver's settings, then resend (save the folder together in [Backups](database.html#backup)). + +### Trying the samples + +- **Node-RED (Docker)**: the Node-RED in the `equipment` profile ([equipment event sample](#equipment-events)) has a tab that receives notifications, verifies the signature and forwards them to a chat (Slack or Teams) in the chat's format. + 1. Start it with `docker compose --profile equipment up -d` and register `http://node-red:1880/mes-webhook` as a destination. + 2. Write the secret as `MES_WEBHOOK_SECRET=whsec_...` in `.env` in the repository root and run `docker compose --profile equipment up -d` again. + 3. Click **Send test**. The received notification and the form that reached the chat appear in the debug pane of Node-RED (http://localhost:1880). + By default the notifications are forwarded to a mock inside the flow, not to a real chat. To send them, write `CHAT_WEBHOOK_URL` (a Slack incoming webhook, or the URL of a Teams workflow triggered when a webhook request is received) in `.env`, plus `CHAT_KIND=teams` for Teams. +- **Scripts**: `samples/webhook` has minimal receivers in Python (`receive_mes_webhook.py`) and PowerShell (`Receive-MesWebhook.ps1`). See the README for where to add your own processing. + +### Promises that keep receivers working across upgrades + +- Fields in the body are not removed, and their names and types do not change. A field that always had a value does not become one that may have none. +- Fields, types and values may be added. Make the receiver skip fields it does not know. +- When the shape must change, it is added as a separate type (v2). diff --git a/docs/en/intro.html b/docs/en/intro.html index b136cdf..060f4a1 100644 --- a/docs/en/intro.html +++ b/docs/en/intro.html @@ -242,6 +242,49 @@

Get started by loading CSV in bulk

+
+
+
Integration APIWebhooks
+

Connect other systems
with CSV, an API and notifications

+

CSV files exported by sales or production planning software are imported just by placing them in a chosen folder. Programs can import and export through the integration API with an API key. Events in the MES are sent to the URLs you register as Webhooks.

+
    +
  • Comes with an OpenAPI specification. Sending again does not register twice
  • +
  • Production results can be read from where you left off
  • +
  • Notifies results, status changes, nonconformances and equipment stops, and retries automatically when delivery fails
  • +
+
+
+
WebhooksDeliveries
+ Deliveries tab of the Webhooks screen, listing an equipment stop notification and a test notification delivered to the destination +
+
+ +
+
+
E-20-10-03Equipment events
+

See the current status
of your equipment

+

A gateway (such as Node-RED) reads the PLC status and sends each change to the MES. The MES assembles the changes into running, stopped and setup periods, and looks up the stop cause from the alarm code.

+
    +
  • A notice appears when no events arrive from a piece of equipment
  • +
  • Stops whose cause could not be looked up can be filled in later
  • +
  • Manually recorded and automatically collected equipment on the same screen
  • +
+
+
+
MaintenanceOperation monitoring
+ Operation monitoring tab of the Maintenance screen. In the current equipment status list, EQ-06, which collects status from equipment events, is stopped while waiting for work from the previous process +
+
+ +
+

And more

+
+
Production plans vs. actuals

Register planned quantities per production date, product and process, and compare them with the good quantity of production results as an achievement rate.

+
Japanese and English

Switch the display language at the top right of the screen. The user guide is also available in both languages.

+
Works on phone widths

On narrow screens the menu opens and closes, and tables scroll sideways, so it can be used from tablets and phones on the shop floor.

+
+
+
@@ -279,7 +322,7 @@

Docker

Try it out

  1. Start it

    Start one of the editions above and open http://localhost:5000 in a browser (8080 for Docker). The Store edition opens the app window directly. The database (SQLite) is created automatically.

  2. -
  3. Create an administrator

    The first time, the initial setup guides you through creating an administrator. The Store edition creates one automatically and shows the user name and initial password at the top of the screen.

  4. +
  5. Create an administrator

    The first time, the initial setup screen appears; choose the user name and password and create the administrator. The Store edition works the same way.

  6. Load the samples

    Import the master data and actual records sample ZIPs in that order, and you are ready to try everything from manufacturing orders to shipping. The sample values, such as product names, are in Japanese.

diff --git a/docs/en/maintenance.md b/docs/en/maintenance.md index 06f3c40..9eccea1 100644 --- a/docs/en/maintenance.md +++ b/docs/en/maintenance.md @@ -26,7 +26,7 @@ For each active piece of equipment, the current status (running, stopped, etc.; The list does not refresh automatically. Press **Update** to load the latest status. For equipment that collects status from equipment events, the **Last received** time is shown. When no events have been received for a while (10 minutes by default), "(no events received)" appears. -Check whether the gateway or the network has stopped ([Receiving equipment events](operations.html#equipment-events)). +Check whether the gateway or the network has stopped ([Receiving equipment events](integration.html#equipment-events)). #### Recording operation diff --git a/docs/en/masters.md b/docs/en/masters.md index 7413030..e84e750 100644 --- a/docs/en/masters.md +++ b/docs/en/masters.md @@ -150,7 +150,7 @@ Places where inventory is kept. Register at least one "Material warehouse" and o | Maintenance type | None / Calendar / Run time / Usage count | | Maintenance threshold | The interval, hours or count, depending on the maintenance type | | Maintenance parts | Notes on replacement parts | -| Collect operation status from equipment events | When on, operation is recorded from equipment events (received from a gateway). Manual entry and actuals CSV can no longer be used ([Receiving equipment events](operations.html#equipment-events)) | +| Collect operation status from equipment events | When on, operation is recorded from equipment events (received from a gateway). Manual entry and actuals CSV can no longer be used ([Receiving equipment events](integration.html#equipment-events)) | ### Stop cause mapping {#alarm-codes} @@ -346,7 +346,7 @@ Open **Administration → Actuals CSV Import** in the menu and import from the p - The permission needed to import each kind is the same as when registering it on the screen (logistics for receiving, shipping orders and shipments; production management for manufacturing orders; quality control for inspections; quality assurance for shipment judgments; and so on. Anyone can import maintenance spot requests and results and tool usage; only maintenance staff can import maintenance plans and planned maintenance orders; production management for tool allocation; quality control for inspection device calibration). - "If even one row has an error, all rows are rolled back" and "Validate only" work the same as for master data CSVs. - With **Bulk import via ZIP** at the top of the screen, you can import several CSVs at once (in file name order; if even one file has an error, all files in the ZIP are rolled back). -- To import CSV files exported regularly by sales or production management software, use **[Folder integration](operations.html#folder-link)**: files placed in a chosen folder are imported automatically (a system administrator sets it up). To import from a program, use the **[integration API](operations.html#integration-api)**. +- To import CSV files exported regularly by sales or production management software, use **[Folder integration](integration.html#folder-link)**: files placed in a chosen folder are imported automatically (a system administrator sets it up). To import from a program, use the **[integration API](integration.html#integration-api)**. A **sample** with a complete set from receiving to shipment is available at **[samples-actual-csv.zip](https://github.com/msmsrep/ParallelFactoryMES/releases/latest/download/samples-actual-csv.zip)** diff --git a/docs/en/operations.md b/docs/en/operations.md index fb31ccb..73f3742 100644 --- a/docs/en/operations.md +++ b/docs/en/operations.md @@ -1,14 +1,29 @@ --- layout: default -title: Administration +title: Server deployment and settings nav_url: operations.html -lead: Information for system administrators, such as deploying the server, settings and backups. -prev_url: troubleshooting.html -prev_title: Troubleshooting -next_url: privacy.html -next_title: Privacy policy +lead: "The server architecture, how to start each distribution, and the settings an administrator needs first." +prev_url: roles.html +prev_title: Roles and permissions +next_url: integration.html +next_title: Integrations --- + + + +Other information for administrators: + +- [Integrations](integration.html) +- [Security and audit log](security.html) +- [Databases and backups](database.html) + ## Architecture The web client (Blazor WebAssembly) is served from the same origin by the API server (ASP.NET Core). @@ -18,7 +33,7 @@ Nothing needs to be installed on users' devices. |---|---| | MesApp.Api | Business logic and database. Also serves the web client | | MesApp.Client.Web | The client that runs in the browser | -| Database | One of SQLite (the default; a single file), PostgreSQL or SQL Server. Migrations are applied automatically at startup ([Using PostgreSQL / SQL Server](#database)) | +| Database | One of SQLite (the default; a single file), PostgreSQL or SQL Server. Migrations are applied automatically at startup ([Using PostgreSQL / SQL Server](database.html#database)) | ## Distribution and startup @@ -52,7 +67,7 @@ Open `http://:8080` in a browser. - The database and signing key are kept in a volume (`/data` inside the container). They are not lost when the container is recreated - The default time zone is `TZ=Asia/Tokyo`. The business date boundary is judged in this time zone - The container does not handle HTTPS. Terminate it at a reverse proxy in front, and specify the network the proxy is on - with `ReverseProxy__KnownNetworks__0` (for example `172.16.0.0/12`) ([Running with HTTPS](#https)) + with `ReverseProxy__KnownNetworks__0` (for example `172.16.0.0/12`) ([Running with HTTPS](security.html#https)) - To upgrade, run `docker compose pull` → `docker compose up -d` ### Publishing from source and starting @@ -114,588 +129,13 @@ $env:MesAdmin__UserName="admin"; $env:MesAdmin__Password="Passw0rd123"; dotnet p If `MesAdmin__Password` is not specified, no initial administrator is created (so that no account is left whose password nobody knows). In that case, create it on the [initial setup screen](getting-started.html). -## Folder integration {#folder-link} - -CSV files placed in a chosen folder are imported automatically. CSV files exported by sales or production management software -can be imported without writing a program (for example, have the manufacturing order CSV exported every morning placed in a shared folder). - -### Setting it up - -1. Create the user who performs the imports (for example `folder-link`). Give it **only the roles needed for the types you want to import** - (Production management for manufacturing orders, Logistics / warehouse for receiving; see [Roles and permissions](roles.html) for what each role can do). - Whether an import is allowed, who is recorded on actuals, and the audit log are all decided and recorded as this user. -2. Set the integration folder and the user, then restart. - -```powershell -$env:FolderLink__Root="D:\mes-link"; $env:FolderLink__UserName="folder-link"; ./start.cmd -``` - -With Docker, mount the integration folder from a folder on the host (example for `compose.yaml`). - -```yaml - volumes: - - mesapp-data:/data - - ./mes-link:/link - environment: - FolderLink__Root: /link - FolderLink__UserName: folder-link -``` - -Changing the settings requires a restart. On startup, `inbox`, `processed` and `error` are created under the integration folder. - -### Where to put files - -| Location | How the type is determined | Example | -|---|---|---| -| Directly in `inbox` | File name (the part after the first "_") | `inbox/manufacturing-orders.csv`, `inbox/20261122_manufacturing-orders.csv` | -| `inbox//` | Folder name (any file name) | `inbox/manufacturing-orders/orders.csv` | -| A ZIP directly in `inbox` | File names inside (same as ZIP bulk import) | `inbox/masters.zip` | - -- The type names and CSV columns are the same as the templates on the Master Data and Actuals CSV Import screens. For software that cannot change the name of the file it exports, have it export into the type's folder. -- Files other than CSV and ZIP are ignored. Files being written are imported after writing finishes. -- Files are imported one at a time in the order they were placed (oldest modification time first). When a later file refers to an earlier one (receiving after manufacturing orders, for example), place them in order or put them in one ZIP. - -### Checking the results - -- **Imported files are moved to `processed` and files that could not be imported to `error`**, under `date/time/`, with a result file (`.result.txt`) beside them. The line numbers and reasons for errors are written there. -- Imports go through the same checks as importing from the screens, and **if even one row has an error, nothing in that file is applied**. Put the corrected file back in the same place in `inbox` to import it again. -- System administrators can check settings errors and recently processed files under "Administration" → "Folder integration" in the menu. "Import now" imports without waiting for the next interval. -- If the user does not exist, is inactive or is locked out, nothing is imported and the files stay in `inbox` (the reason is shown on the screen). - -There is no integration that writes data out of the MES yet (automatic export of actuals). - -## API keys {#api-keys} - -Keys that systems such as sales or production management software, or in-house scripts, use to call the MES **integration API** (`/api/integration/v1/...`) without signing in. - -### Issuing a key - -1. Create the user the key will act as (for example `erp-link`). **What the key can do is determined by this user's roles.** Create a dedicated user for each purpose and give it only the roles it needs ([Roles and permissions](roles.html)). -2. A system administrator opens "Administration" → "API keys" in the menu, specifies the purpose, the user and an optional expiry, and clicks **Issue key**. -3. Copy the key shown (a string starting with `pfm_`) into the settings of the connecting system. **The key is shown only at this time.** If it is lost, revoke it and issue a new one. - -### Trying it - -Send the key in the `X-Api-Key` request header. The following endpoint shows who you are treated as (the user and roles). - -```powershell -Invoke-RestMethod http://localhost:5000/api/integration/v1/whoami -Headers @{ "X-Api-Key" = "pfm_..." } -``` - -```bash -curl -H "X-Api-Key: pfm_..." http://localhost:5000/api/integration/v1/whoami -``` - -### Notes - -- Keys work only with the integration API. The APIs used by the screens (such as `/api/products`) cannot be called with a key (401). -- Operations performed with a key are recorded in the audit log as the linked user. -- **A revoked key cannot be restored.** A key also stops working immediately when its user is deactivated or its expiry passes. When the user's roles change, the next call is checked with the new roles. -- Treat keys like passwords. Do not paste them into email or chat; keep them only in the settings of the connecting system. - -## Integration API {#integration-api} - -An API for exchanging data with the MES from sales or production management software (ERP) or in-house scripts. Calls use an [API key](#api-keys). - -### Specification (OpenAPI) - -The integration API specification is published at `/openapi/integration-v1.json` (for example `http://localhost:5000/openapi/integration-v1.json`). -Load it into Postman, Visual Studio or similar tools to see the endpoints, parameters and response shapes. No key is needed to get the specification. - -### Endpoints - -| Endpoint | Purpose | -|---|---| -| `GET /api/integration/v1/whoami` | Check that the key works and who you are treated as, with which roles | -| `GET /api/integration/v1/csv-kinds` | The CSV types and columns that can be imported (the same as the Master Data and Actuals CSV Import screens) | -| `POST /api/integration/v1/masters/{type}` | Import a master data CSV (overwritten by code) | -| `POST /api/integration/v1/actuals/{type}` | Import an actuals CSV (always registered as new) | -| `POST /api/integration/v1/masters/bundle`, `actuals/bundle` | Import a ZIP of CSV files | -| `GET /api/integration/v1/masters/{type}` | Export master data as CSV | -| `GET /api/integration/v1/production-results` | Read production results from where you left off | -| `GET /api/integration/v1/production-result-corrections` | Read corrections to production results from where you left off | -| `POST /api/integration/v1/equipment-events` | Send equipment status changes ([Receiving equipment events](#equipment-events)) | - -### Importing CSV - -Send the CSV as the request body (UTF-8 or Shift_JIS). Add `?dryRun=true` to only validate without applying anything. -The PowerShell examples on this page are for PowerShell 7 (`pwsh`). - -```powershell -$headers = @{ "X-Api-Key" = "pfm_..."; "Idempotency-Key" = "orders-20261123" } -Invoke-RestMethod -Method Post -Headers $headers -ContentType "text/csv; charset=utf-8" -InFile .\manufacturing-orders.csv -Uri http://localhost:5000/api/integration/v1/actuals/manufacturing-orders -``` - -```bash -curl -H "X-Api-Key: pfm_..." -H "Idempotency-Key: orders-20261123" -H "Content-Type: text/csv" --data-binary @manufacturing-orders.csv http://localhost:5000/api/integration/v1/actuals/manufacturing-orders -``` - -- **200** when imported, and **422** if even one row has an error, in which case nothing is applied. In both cases the response body contains the counts and errors with line numbers (in PowerShell 7, add `-SkipHttpErrorCheck` to also receive the body of a 422). -- Import permission is checked with the roles of the user linked to the key, the same as on the screens (403 without permission). - -### Sending again without registering twice (Idempotency-Key) - -Actuals CSV files are **always registered as new**, so sending the same CSV again after a dropped connection can register it twice. -To prevent this, put a value chosen for each content you send (for example the order export time and a sequence number, or a UUID) in the `Idempotency-Key` header. - -- If you send the same key with the same content again, **the previous response is returned without importing again** (the response has the header `Idempotent-Replayed: true`). -- A request with the same key but different content gets 409. Use a new key for new content. -- Keys are remembered for 24 hours, separately for each API key. - -### Reading production results (from where you left off) - -Pass the previous `nextAfterId` as `afterId` to get only the results recorded after it. Keep reading while `hasMore` is true. -Save the last `nextAfterId` so that the next run starts where this one ended. - -```powershell -$headers = @{ "X-Api-Key" = "pfm_..." } -$after = if (Test-Path .\last-id.txt) { Get-Content .\last-id.txt } else { 0 } -do { - $page = Invoke-RestMethod -Headers $headers -Uri "http://localhost:5000/api/integration/v1/production-results?afterId=$after" - $page.items | Export-Csv .\production-results.csv -Append -Encoding utf8 - $after = $page.nextAfterId -} while ($page.hasMore) -Set-Content .\last-id.txt $after -``` - -- Quantities are the current values after any correction. To learn that a result you already read was corrected later, read `production-result-corrections` from where you left off in the same way. -- Results not yet approved are also returned (`approvedAt` is empty). Results of canceled orders are also returned because the physical lots remain (see `workOrderStatus`). - -### Promises that keep integrations working after upgrades - -- Within v1 (`/api/integration/v1`), **fields and endpoints are only added**, never removed, renamed or given a new meaning. Such changes go into a v2. -- The same applies to CSV columns. Columns are not removed and no required columns are added (if you leave out a new column, things work as before). When a column is renamed, its former name can still be read. -- Build your integrations to skip fields they do not know, in case new fields are added to responses. - -## Receiving equipment events {#equipment-events} - -A mechanism that records equipment operation status (running, stopped, setup, failure, idle) automatically from the equipment. -**The MES does not communicate with PLCs directly.** A gateway (such as Node-RED) reads the PLC status and sends it to the MES integration API when the status changes. -The MES sorts the received status changes by time for each piece of equipment and builds them into **intervals in the operation history** (start to end). - -``` -Equipment / PLC ──(OPC UA, MC protocol, Modbus, etc.)──▶ Gateway ──(HTTP, API key)──▶ MES - (Node-RED, etc.) POST /api/integration/v1/equipment-events -``` - -### Preparation - -1. In the equipment master (the **Equipment (BOE)** tab in master management), turn on **Collect operation status from equipment events** for the target equipment. - Operation cannot then be registered for that equipment by manual entry or actuals CSV (so the same time is not counted twice by hand and automatically). Stop causes can still be added. -2. Create a user for the gateway and issue an [API key](#api-keys). Receiving does not depend on roles. -3. If needed, register a **Stop cause mapping** (master management) that replaces alarm codes with stop causes. - -### What to send - -Create one event each time the status changes, collect them, and send them together (up to 1,000 at a time). - -```json -{ - "events": [ - { "equipmentCode": "EQ-06", "eventId": "EQ-06-1732323600000-1", "occurredAt": "2026-11-23T09:00:00+09:00", "state": "Running" }, - { "equipmentCode": "EQ-06", "eventId": "EQ-06-1732324200000-2", "occurredAt": "2026-11-23T09:10:00+09:00", "state": "Stopped", "alarmCode": "A-101" } - ] -} -``` - -| Item | Description | -|---|---| -| `equipmentCode` | The equipment asset No. | -| `eventId` | A unique ID assigned by the gateway (unique per equipment, up to 100 characters). Keep **the same value when resending** | -| `occurredAt` | The time the status changed on the equipment (with an offset such as `+09:00`) | -| `state` | `Running` / `Stopped` / `Setup` / `Failure` / `Idle` / `Off` (power off or connection lost) | -| `alarmCode` | Optional. The alarm code for a stop or failure (the cause is looked up in the stop cause mapping) | -| `workOrderNo` + `operationSeq` | Optional. The work order being processed (a pair of order number and operation sequence) | -| `note` | Optional. A note | - -```powershell -$headers = @{ "X-Api-Key" = "pfm_..." } -$body = @{ events = @(@{ equipmentCode = "EQ-06"; eventId = "test-1"; occurredAt = (Get-Date).ToString("o"); state = "Running" }) } | ConvertTo-Json -Depth 4 -Invoke-RestMethod -Method Post -Headers $headers -ContentType "application/json" -Body $body -Uri http://localhost:5000/api/integration/v1/equipment-events -``` - -### What happens after an event arrives - -- When a new status arrives, the open interval is closed and the next interval is opened. Repeated events with the same status do not change the interval. `Off` only closes the interval. -- Events sent together may be out of time order; they are re-sorted by time before being applied. -- **Resending the same `eventId` results in "Duplicate" and is not recorded twice.** When the connection drops, resend the collected events as they are. -- **Events earlier than the last applied time are rejected as late arrivals.** Past intervals are not rebuilt. Synchronize the clocks of the equipment and gateway with NTP. Times too far ahead of the server time (more than 300 seconds by default) are also rejected. -- The response is 200 and contains a result for each event (`Accepted`, `Duplicate`, or `Rejected` with the reason). It is 200 even if all are rejected. A rejected `eventId` is judged again when it is corrected and resent. -- For stop and failure intervals, the stop cause is looked up from the alarm code in the stop cause mapping. If it is not found, the interval is recorded **without a stop cause**, which can be entered later on the operation monitoring tab in maintenance. -- The work order is linked if specified. If not specified, it is linked **only when exactly one started work order is assigned to that equipment**. - -You can see what is being received under **Current equipment status** on the operation monitoring tab in maintenance. When no events have been received for a while (10 minutes by default), "(no events received)" appears for that equipment, so you can notice that the gateway has stopped. - -### Trying the sample (Docker) - -`compose.yaml` has an `equipment` profile that also starts an MQTT broker (Eclipse Mosquitto) and a Node-RED gateway. -Node-RED contains a **simulated piece of equipment** that changes status every few seconds and a flow that receives MQTT messages and sends them to the MES together (`samples/equipment-gateway`). - -1. Run `docker compose --profile equipment up -d` in the repository root. -2. Import the sample master data into the MES (http://localhost:8080). `EQ-06` is set to collect status from equipment events. -3. Issue an API key, write `MES_API_KEY=pfm_...` in `.env` in the repository root, and run `docker compose --profile equipment up -d` again. -4. On the operation monitoring tab, check that the current status and operation history of `EQ-06` grow. In Node-RED (http://localhost:1880), the status of the node that checks the result (the last function node in step ③ of the flow) shows the numbers accepted, duplicate and rejected. - -To adapt it to your own equipment, replace the simulated equipment (the function node in step ① of the flow) with a node that reads the status from the PLC (OPC UA, MC protocol, Modbus, etc.). -The sample MQTT broker is a minimal setup without authentication or encryption. Configure passwords and TLS for production. - -## Webhooks (notifications from the MES) {#webhooks} - -When an event you want to know about **right away** happens, such as a nonconformance being raised, equipment stopping or a lot being put on hold, the MES notifies the URLs you register over HTTP. -Use it for alerts to the team leaders' chat or to start the next process when production is completed. -Systems that only need data periodically (such as inventory and costing in the ERP) can read production results with the [integration API](#integration-api) instead. - -Notifications are kept **thin**. Only the type, the time, the numbers of what changed and a one-sentence summary are sent. -A notification is a cue to fetch data. Get the correct current values from the integration API (this also lets you catch up when a notification did not arrive or arrived out of order). - -``` -MES ──(POST, signed)──▶ Receiver (Node-RED, in-house script, etc.) ──▶ Chat, display board, ERP -``` - -### Registering a destination - -1. A system administrator opens "Administration" → "Webhooks" in the menu, and on the **Destinations** tab chooses the purpose, the destination URL and the events to notify, then clicks **Register**. -2. Copy the **Signing secret** shown (a string starting with `whsec_`) into the receiver's settings. **The value is shown only at this time.** If it is lost, click **Reissue secret** (the old value stops working immediately, so update the receiver's settings too). -3. Click **Send test** to check that the receiver gets it. The result is shown on the spot (a test that fails is not retried). - -- The URL can also be `http://` (for the factory's internal network). Bodies sent to an `http://` destination are not encrypted, so use `https://` when sending outside the company. -- A URL containing a user name or password cannot be registered (the URL is shown as it is in the list and the audit log). The receiver verifies the sender by the signature. -- To stop sending without deleting, clear **Active**. Deleting a destination also deletes its pending notifications and its delivery records. - -### Events to notify - -| Type | When | Main fields | -|---|---|---| -| `production-result.created` | A production result was recorded (from the screens, actual CSV or the integration API) | Order number, work order number, sequence, item code, good/defect quantities, output lot | -| `production-result.corrected` | A production result was corrected | `productionResultId` of the corrected result, quantities before and after, reason | -| `work-order.status-changed` | A work order's status changed (dispatch, start, completion, approval, cancellation) | Work order number, status before and after | -| `manufacturing-order.status-changed` | A manufacturing order was completed or canceled | Order number, order type, status before and after | -| `lot.status-changed` | A lot's stock status changed (hold, release, awaiting inspection, etc.) | Lot number, item code, before and after, trigger, reason | -| `nonconformance.created` | A nonconformance was raised (including those raised automatically when an inspection fails) | Nonconformance number, source, lot number, item code | -| `equipment.stopped` | Equipment entered a stopped or failure interval (from manual entry, actual CSV or [equipment events](#equipment-events)) | Asset number, status, stop cause, alarm code | - -Types and statuses are sent as English names (such as `OnHold`) so that they do not change with the display language. Internal IDs are not sent; records are identified by numbers and codes. -The summary (`summary`) is in Japanese. - -### What is sent - -```json -{ - "id": "c548bec2-5e89-4210-ba22-2110c0325f09", - "sequence": 7, - "type": "equipment.stopped", - "version": 1, - "occurredAt": "2026-11-23T11:02:01+00:00", - "summary": "…", - "data": { "equipmentAssetNo": "EQ-01", "status": "Stopped", "startedAt": "2026-11-23T10:32:00+00:00", "endedAt": null, - "stopCause": "Material shortage", "alarmCode": null, "source": "Manual", "workOrderNo": null } -} -``` - -The `summary` is a Japanese sentence such as `設備 EQ-01 が「停止」になりました(Material shortage)。` (equipment EQ-01 has stopped). - -| Field or header | Description | -|---|---| -| `id` | The notification's unique ID. **The same value when resent** (the receiver uses it to discard duplicates) | -| `sequence` | A number that increases across types (not necessarily consecutive) | -| `data` | The content for each type (the table above). The list of fields is in the `webhooks` section of the [specification (OpenAPI)](#integration-api) | -| `X-Mes-Event` | The type (the same as `type` in the body) | -| `X-Mes-Delivery` | The delivery ID (the same when resent) | -| `X-Mes-Timestamp` | The time it was sent (Unix seconds) | -| `X-Mes-Signature` | The signature: `sha256=` followed by the lowercase hexadecimal HMAC-SHA256 of "the `X-Mes-Timestamp` value, `.`, the body", keyed with the secret | - -### What the receiver should check - -1. **Verify the signature** using the exact bytes of the body you received. If you parse the JSON and turn it back into a string, the way numbers are written and other details change and the signature no longer matches. -2. **Check the time.** Reject the request if `X-Mes-Timestamp` is off by more than 5 minutes (to block old requests being replayed). Synchronize the clocks of the MES and the receiver with NTP. -3. **Return 2xx right away.** The MES waits up to 10 seconds by default and resends if no response arrives. Do heavy work after responding. -4. **Discard the second and later copies of the same `id`.** Notifications are delivered at least once, so the same notification can arrive twice. The order is not guaranteed either. - -### When delivery fails - -- If the destination cannot be reached, does not respond in time, or returns `5xx`, `408` or `429`, the MES resends at increasing intervals (1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours, 24 hours; up to 8 attempts by default). -- Other `4xx` and `3xx` responses stop after one attempt, because resending would give the same result (redirects are not followed). -- For a stopped notification, fix the receiver, then click **Resend** on the **Deliveries** tab. The notification's `id` does not change, so a receiver that already got it discards it as a duplicate. -- Destinations with notifications waiting to be resent or stopped appear under "Undelivered" on the **Destinations** tab and at the top of the system administrator's **Dashboard**. Destinations are never stopped automatically. -- Delivery records are kept for 30 days by default. -- If the `dataprotection-keys` folder (the keys that encrypt the secrets) in the data folder is lost, the secrets cannot be decrypted and notifications to those destinations stop. Reissue the secret, update the receiver's settings, then resend (save the folder together in [Backups](#backup)). - -### Trying the samples - -- **Node-RED (Docker)**: the Node-RED in the `equipment` profile ([equipment event sample](#equipment-events)) has a tab that receives notifications, verifies the signature and forwards them to a chat (Slack or Teams) in the chat's format. - 1. Start it with `docker compose --profile equipment up -d` and register `http://node-red:1880/mes-webhook` as a destination. - 2. Write the secret as `MES_WEBHOOK_SECRET=whsec_...` in `.env` in the repository root and run `docker compose --profile equipment up -d` again. - 3. Click **Send test**. The received notification and the form that reached the chat appear in the debug pane of Node-RED (http://localhost:1880). - By default the notifications are forwarded to a mock inside the flow, not to a real chat. To send them, write `CHAT_WEBHOOK_URL` (a Slack incoming webhook, or the URL of a Teams workflow triggered when a webhook request is received) in `.env`, plus `CHAT_KIND=teams` for Teams. -- **Scripts**: `samples/webhook` has minimal receivers in Python (`receive_mes_webhook.py`) and PowerShell (`Receive-MesWebhook.ps1`). See the README for where to add your own processing. - -### Promises that keep receivers working across upgrades - -- Fields in the body are not removed, and their names and types do not change. A field that always had a value does not become one that may have none. -- Fields, types and values may be added. Make the receiver skip fields it does not know. -- When the shape must change, it is added as a separate type (v2). - -## Security - -
-

The app itself does not enforce HTTPS. For LAN operation, terminate HTTPS at a reverse proxy -(IIS / nginx) (Running with HTTPS).

-

Also, barcode scanning with the camera requires HTTPS anywhere other than localhost. -The camera cannot be used over plain HTTP (USB readers and typing work over HTTP too).

-
- -- Authentication uses ASP.NET Core Identity + JWT. -- Corrections to actuals and inspections, master data changes, inventory adjustments and so on are recorded in the audit log (see below). -- Passwords must be at least 8 characters long and contain a lowercase letter and a digit. - -### Running with HTTPS {#https} - -A reverse proxy (IIS / nginx) receives HTTPS from browsers and relays it to the app over HTTP. -Only the proxy holds the certificate. - -``` -Device browser ──HTTPS──▶ IIS / nginx (certificate) ──HTTP──▶ MesApp (127.0.0.1:5000) -``` - -**1. Prepare a certificate.** On a company LAN you cannot get a public certificate, so issue one with an internal CA or -[mkcert](https://github.com/FiloSottile/mkcert). With mkcert, run the following on the server. - -```bash -mkcert -install -mkcert mes.example.local 192.168.10.5 -``` - -List every name (host name and IP) that devices will use. Configure the resulting `mes.example.local+1.pem` (certificate) and -`mes.example.local+1-key.pem` (private key) in the proxy. - -**2. Distribute the CA certificate to devices.** Rename `rootCA.pem` in the folder shown by `mkcert -CAROOT` -to `rootCA.crt`, distribute it to each device and add it to "Trusted Root Certification Authorities" -(run `certutil -addstore -f Root rootCA.crt` on the device, or distribute it by Group Policy if there are many devices). -**Do not distribute** `rootCA-key.pem` in the same folder (anyone holding it can issue any certificate). - -**3. Start the app so that it can be reached only from the proxy.** So that nobody can connect to it directly over HTTP, -listen only on the loopback address (the app does not redirect HTTP to HTTPS). - -```bash -dotnet publish/MesApp.Api.dll --urls http://127.0.0.1:5000 -``` - -**4. Configure the proxy.** Pass the client IP and scheme with `X-Forwarded-For` / `X-Forwarded-Proto`. - -An nginx example: - -```nginx -server { - listen 443 ssl; - server_name mes.example.local; - ssl_certificate mes.example.local+1.pem; - ssl_certificate_key mes.example.local+1-key.pem; - client_max_body_size 50m; # for bulk CSV and ZIP imports - - location / { - proxy_pass http://127.0.0.1:5000; - proxy_set_header Host $host; - proxy_set_header X-Forwarded-For $remote_addr; - proxy_set_header X-Forwarded-Proto $scheme; - } -} -``` - -For IIS, install URL Rewrite and Application Request Routing (ARR), and enable the ARR proxy. -ARR adds `X-Forwarded-For`. Add `X-Forwarded-Proto` with a rewrite rule, after adding the server variable `HTTP_X_FORWARDED_PROTO` -to "Allowed Server Variables" (a `web.config` example). - -```xml - - - - - - - - - - - -``` - -**5. Configure the app to trust the proxy.** The app reads forwarded headers only from the sources specified here. -If the proxy is on the same PC, use the following (if it is on another PC, use its IP). - -```powershell -$env:ReverseProxy__KnownProxies__0="127.0.0.1" -``` - -
-

Without this setting, forwarded headers are not read. Even over HTTPS, -the refresh token cookie does not get Secure, and every client IP in the audit log becomes the proxy's IP. -They are not read when this is not set so that a device connecting directly over HTTP cannot forge the headers to fake its source.

-
- -**Check:** Sign in over HTTPS from a device. If the client IP of the "sign-in" entry in the audit log is the device's IP, you are done. -If it is still `127.0.0.1`, the setting in step 5 is not taking effect. - -## Audit log {#audit-log} - -A record of "who changed what, and when". You can view it from **"Audit Log" in the menu** -(system administrators only; other roles do not even see the menu item). - -### Operations recorded - -| Category | Main operations | -|---|---| -| Setup | Creating the initial administrator | -| Auth | Sign-in, failed sign-in, account lockout, sign-out, password change | -| User | Creating and changing users, password resets, granting skills and qualifications | -| Master | Registering, changing and deactivating master data, CSV imports | -| Production | Registering, approving, canceling and releasing manufacturing orders, dispatching | -| Execution | Starting work, registering results, **correcting results**, work time, process condition data, completion approval | -| Inventory | Receiving, moves, **quantity adjustments**, status changes, split / merge / reassign, scrapping, picking, shipping, stocktaking, **cancellations** | -| Quality | Registering, **correcting**, judging and approving inspection results; raising, instructing and approving nonconformances; shipment judgments | -| Maintenance | Maintenance plans, maintenance orders, maintenance records, managing maintenance procedures | -| Equipment | Recording equipment operation, tool usage | - -For **operations whose before and after you want to follow**, such as quantity adjustments, status changes, corrections and cancellations, the "Details" column contains **the value before, the value after and the reason**. -Other operations contain a summary. - -### Filtering - -You can filter by period, category / operation and target (type and ID). -For example, entering `Lot` in "Target type" and the internal ID of a lot in "Target ID" -lists only the operations performed on that lot. - -
-

The period filters by the recorded date (the server's date). -The date and time in the list are shown in the browser's time, so where the server and browser are in different time zones, -entries around midnight may appear on a different day.

-
- -### Deletion and tampering - -- Individual records **cannot be changed or deleted, either from the screens or from the API**. Records are only ever added. -- **The retention period is 5 years** (it can be changed with `Audit__RetentionYears`). **Nothing is deleted automatically** (whether records may be deleted is a business decision). -- Only when storage becomes a problem can you **delete records older than the retention period in bulk** (see below). - -### Purging old records - -This operation clears out records that are past the retention period. It is **at the very bottom of the Audit Log screen**. -Take a backup first (see below). - -
-
    -
  1. Enter a date in "Delete up to this date (inclusive)" and the reason for deleting in "Reason (required)" (records on or before the date are targeted).
  2. -
  3. Press Check count to delete. Nothing is deleted yet at this point. The number of targeted records is shown.
  4. -
  5. Check the count and press "Delete N records" to delete them.
  6. -
-
- -Changing the date or the reason resets the count check, and you must check again -(so that what you checked and what is actually deleted do not differ). - -To run it from the API, use the following. While `dryRun=true`, it only returns the count and does not touch the database. - -``` -POST /api/audit-logs/purge?dryRun=true -{ "to": "2020-12-31", "reason": "To reduce storage" } -``` - -
-

Records within the retention period cannot be deleted. A date newer than the retention period is rejected -(if the records of recent operations could be deleted to hide them, the audit log would not stand as evidence).

-

A reason is required, and the purge itself (period, count, reason and user) is recorded in the audit log. -This record is written after the deletion, so it is not removed by the same operation.

-
- -## Using PostgreSQL / SQL Server {#database} - -The default SQLite needs no extra installation and can be used as is for up to a few dozen devices. -When many devices write at the same time, the data volume is large, or you want to manage it together on an existing DB server, -switch to PostgreSQL or SQL Server. - -1. Create an **empty database** and a login for connecting on the DB server. - Give the login permission to create and change tables in that database (the schema is created and updated at startup). -2. Set `Database__Provider` and `Database__ConnectionString` and start it. - -```powershell -# PostgreSQL -$env:Database__Provider="PostgreSql"; $env:Database__ConnectionString="Host=db;Database=mesapp;Username=mesapp;Password=..." -# SQL Server -$env:Database__Provider="SqlServer"; $env:Database__ConnectionString="Server=db;Database=mesapp;User Id=mesapp;Password=...;TrustServerCertificate=True" -``` - -3. The tables are created at startup. When you open it in a browser, the initial setup guidance is shown, just as with SQLite. - In later upgrades, the differences are also applied automatically at startup. - -
-

Existing SQLite data is not carried over. After switching, you start from an empty database. -Decide which database to use before you start operating. If you switch the setting back to SQLite, the original mesapp.db is used as is (the two sets of data are separate).

-
- -### Differences from SQLite - -| Item | Difference | -|---|---| -| Upper and lower case in codes | With SQL Server's default collation they are not distinguished (`ABC` and `abc` are treated as the same, duplicate code, and searches do not distinguish them either). SQLite and PostgreSQL distinguish them | -| Date and time | PostgreSQL stores them in UTC. They refer to the same moment, so screen display, totals and CSV results do not change | -| Decimals | Up to 6 decimal places are stored (trailing zeros are dropped so that values look the same as in SQLite) | -| Desktop edition | Intended for use with SQLite (because it is designed to run entirely on one PC) | - -### When it does not start - -| Symptom | What to do | -|---|---| -| It stops with an "unknown DB provider" error (the message is in Japanese: 不明なDBプロバイダー) | Write `Database__Provider` as exactly one of `Sqlite` / `PostgreSql` / `SqlServer`, including upper and lower case | -| It stops with a connection timeout or authentication error | Check the host name, port, user name and password in the connection string, the firewall on the DB server, and, for SQL Server, whether TCP/IP connections are enabled | -| SQL Server gives a certificate error | For a server with an internal self-signed certificate, add `TrustServerCertificate=True` to the connection string, or configure a trusted certificate on the server | -| It stops with a permission error (cannot create tables) | Give the connecting login permission to create and change tables in the target database | - -## Backups {#backup} - -### SQLite - -
-

Do not simply copy the DB file while it is running. -SQLite runs in WAL mode, so the copied file may be corrupted.

-
- -There are two safe methods. - -1. Stop the server, then copy `mesapp.db` -2. While it is running, create a backup file with SQLite's `VACUUM INTO` - -With Docker, stop the container and save the whole volume (the signing key and the keys that encrypt the webhook secrets are kept along with it). -Check the volume name with `docker volume ls` (with compose it is `_mesapp-data`). - -```bash -docker compose stop -docker run --rm -v :/data -v "$PWD":/backup alpine tar czf /backup/mesapp-data.tgz -C /data . -docker compose start -``` - -Deleting all of `mesapp.db*` (including `-wal` / `-shm`) and restarting returns it to the initial state. -You can use this to reset a test environment. - -### PostgreSQL / SQL Server - -Back up with each database's standard tools (backups can be taken while it is running). - -- PostgreSQL: `pg_dump -Fc -d mesapp -f mesapp.dump` (restore with `pg_restore`) -- SQL Server: `BACKUP DATABASE mesapp TO DISK = N'...\mesapp.bak'` (or a backup from SQL Server Management Studio) - -To return to the initial state, drop the database, create an empty one again and restart. - -### Keys in the data folder - -Besides the database, also save `jwt-signing.key` (the sign-in signing key) and the `dataprotection-keys` folder (the keys that encrypt the [webhook](#webhooks) secrets) in the data folder. -If `dataprotection-keys` is lost, the webhook secrets in a restored database cannot be decrypted, and you will need to reissue the secret for each destination. - ## Limitations | Item | Status | |---|---| -| PostgreSQL / SQL Server | Supported ([Using PostgreSQL / SQL Server](#database)). There is no function for moving existing SQLite data | +| PostgreSQL / SQL Server | Supported ([Using PostgreSQL / SQL Server](database.html#database)). There is no function for moving existing SQLite data | | Docker and ZIP distribution | Supported ([Distribution and startup](#distribution-and-startup)) | -| HTTPS | Not enforced by the app (terminate at a reverse proxy; [Running with HTTPS](#https)) | +| HTTPS | Not enforced by the app (terminate at a reverse proxy; [Running with HTTPS](security.html#https)) | | Automatic data collection from equipment and scales | Not supported (entered by hand) | | EDI / ASN integration | Not supported | | Tracking by serial number (individual unit) | Not supported (by lot only) | diff --git a/docs/en/privacy.md b/docs/en/privacy.md index c39c8ba..3d48f05 100644 --- a/docs/en/privacy.md +++ b/docs/en/privacy.md @@ -4,8 +4,8 @@ title: Privacy policy nav_url: privacy.html description: The data Parallel Factory MES handles, where it is stored and whether it is sent anywhere. lead: This page describes the data handled by Parallel Factory MES ("the app"). It mainly covers the Microsoft Store edition (a desktop app that runs entirely on a single PC), and also describes how data is handled when the app is deployed on a server. -prev_url: operations.html -prev_title: Administration +prev_url: troubleshooting.html +prev_title: Troubleshooting --- Last updated: September 21, 2026 @@ -45,7 +45,7 @@ The database, the signing key used for authentication, the startup log and the W The app runs its application server **only inside your PC (on the loopback address `127.0.0.1`)**. This traffic never leaves your PC, and other devices on the same network cannot connect to it. -**Uninstalling the app deletes this folder together with all its data.** If there is data you want to keep, take a backup before uninstalling (see [Administration](operations.html)). +**Uninstalling the app deletes this folder together with all its data.** If there is data you want to keep, take a backup before uninstalling (see [Databases and backups](database.html#backup)). ### When deployed on a server diff --git a/docs/en/reference.md b/docs/en/reference.md index ed06a2d..d486511 100644 --- a/docs/en/reference.md +++ b/docs/en/reference.md @@ -3,8 +3,8 @@ layout: default title: Reference nav_url: reference.html lead: Lists of statuses, numbering rules, the business date and a glossary. For reference when you are unsure during operation. -prev_url: roles.html -prev_title: Roles and permissions +prev_url: database.html +prev_title: Databases and backups next_url: troubleshooting.html next_title: Troubleshooting --- @@ -102,7 +102,7 @@ Daily totals and numbering use the **business date**, not the calendar date. - Example: actuals at 3:00 a.m. on May 2 → the production date is "May 1" This keeps night-shift actuals that cross midnight together under one production date. -The boundary time can be changed in the settings ([Administration](operations.html#settings)). +The boundary time can be changed in the settings ([Server deployment and settings](operations.html#settings)). The business date is used for numbering and for the period in quality analysis. @@ -121,7 +121,7 @@ The business date is used for numbering and for the period in quality analysis. | Shipping needs a shipment judgment | A shipment cannot be carried out without an approved "Approved" or "Special acceptance" judgment | | Approval is single-step | Each approval is finalized with one approval operation (there is no multi-step workflow) | | Corrections need a reason | Quantity adjustments and inspection result corrections require a reason, which is recorded in the audit log | -| Records cannot be erased | The audit log is only ever added to; individual records cannot be changed or deleted. Only entries older than the retention period (5 years by default) can be deleted in bulk by an administrator, with a reason ([Audit log](operations.html#audit-log)) | +| Records cannot be erased | The audit log is only ever added to; individual records cannot be changed or deleted. Only entries older than the retention period (5 years by default) can be deleted in bulk by an administrator, with a reason ([Audit log](security.html#audit-log)) | --- diff --git a/docs/en/reports.md b/docs/en/reports.md index 455841d..485f3e6 100644 --- a/docs/en/reports.md +++ b/docs/en/reports.md @@ -59,7 +59,7 @@ If you print lot tags when receiving and when production is completed and attach This is a browser security restriction and cannot be worked around by the system.

If you run on a LAN over HTTP, we recommend using a USB barcode reader. To use the camera, put the system behind a reverse proxy (IIS / nginx) with HTTPS -(Running with HTTPS).

+(Running with HTTPS).

Where the camera cannot be used, the following message is shown. diff --git a/docs/en/roles.md b/docs/en/roles.md index aec8ad5..3a8ddfa 100644 --- a/docs/en/roles.md +++ b/docs/en/roles.md @@ -5,8 +5,8 @@ nav_url: roles.html lead: The seven roles and a table of the operations each can perform. A user can be given more than one role. prev_url: reports.html prev_title: Reports, labels and scanning -next_url: reference.html -next_title: Reference +next_url: operations.html +next_title: Server deployment and settings --- ## Roles diff --git a/docs/en/search.json b/docs/en/search.json new file mode 100644 index 0000000..5c9fcf5 --- /dev/null +++ b/docs/en/search.json @@ -0,0 +1,5 @@ +--- +# ガイド内検索の索引(英語版)。中身は _includes/search-index.json +layout: null +--- +{% include search-index.json dir="/en/" %} diff --git a/docs/en/security.md b/docs/en/security.md new file mode 100644 index 0000000..ffb949e --- /dev/null +++ b/docs/en/security.md @@ -0,0 +1,181 @@ +--- +layout: default +title: Security and audit log +nav_url: security.html +lead: "Authentication, running with HTTPS, and how to read the audit log and purge old records." +prev_url: integration.html +prev_title: Integrations +next_url: database.html +next_title: Databases and backups +--- + +## Security + +
+

The app itself does not enforce HTTPS. For LAN operation, terminate HTTPS at a reverse proxy +(IIS / nginx) (Running with HTTPS).

+

Also, barcode scanning with the camera requires HTTPS anywhere other than localhost. +The camera cannot be used over plain HTTP (USB readers and typing work over HTTP too).

+
+ +- Authentication uses ASP.NET Core Identity + JWT. +- Corrections to actuals and inspections, master data changes, inventory adjustments and so on are recorded in the audit log (see below). +- Passwords must be at least 8 characters long and contain a lowercase letter and a digit. + +### Running with HTTPS {#https} + +A reverse proxy (IIS / nginx) receives HTTPS from browsers and relays it to the app over HTTP. +Only the proxy holds the certificate. + +``` +Device browser ──HTTPS──▶ IIS / nginx (certificate) ──HTTP──▶ MesApp (127.0.0.1:5000) +``` + +**1. Prepare a certificate.** On a company LAN you cannot get a public certificate, so issue one with an internal CA or +[mkcert](https://github.com/FiloSottile/mkcert). With mkcert, run the following on the server. + +```bash +mkcert -install +mkcert mes.example.local 192.168.10.5 +``` + +List every name (host name and IP) that devices will use. Configure the resulting `mes.example.local+1.pem` (certificate) and +`mes.example.local+1-key.pem` (private key) in the proxy. + +**2. Distribute the CA certificate to devices.** Rename `rootCA.pem` in the folder shown by `mkcert -CAROOT` +to `rootCA.crt`, distribute it to each device and add it to "Trusted Root Certification Authorities" +(run `certutil -addstore -f Root rootCA.crt` on the device, or distribute it by Group Policy if there are many devices). +**Do not distribute** `rootCA-key.pem` in the same folder (anyone holding it can issue any certificate). + +**3. Start the app so that it can be reached only from the proxy.** So that nobody can connect to it directly over HTTP, +listen only on the loopback address (the app does not redirect HTTP to HTTPS). + +```bash +dotnet publish/MesApp.Api.dll --urls http://127.0.0.1:5000 +``` + +**4. Configure the proxy.** Pass the client IP and scheme with `X-Forwarded-For` / `X-Forwarded-Proto`. + +An nginx example: + +```nginx +server { + listen 443 ssl; + server_name mes.example.local; + ssl_certificate mes.example.local+1.pem; + ssl_certificate_key mes.example.local+1-key.pem; + client_max_body_size 50m; # for bulk CSV and ZIP imports + + location / { + proxy_pass http://127.0.0.1:5000; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $remote_addr; + proxy_set_header X-Forwarded-Proto $scheme; + } +} +``` + +For IIS, install URL Rewrite and Application Request Routing (ARR), and enable the ARR proxy. +ARR adds `X-Forwarded-For`. Add `X-Forwarded-Proto` with a rewrite rule, after adding the server variable `HTTP_X_FORWARDED_PROTO` +to "Allowed Server Variables" (a `web.config` example). + +```xml + + + + + + + + + + + +``` + +**5. Configure the app to trust the proxy.** The app reads forwarded headers only from the sources specified here. +If the proxy is on the same PC, use the following (if it is on another PC, use its IP). + +```powershell +$env:ReverseProxy__KnownProxies__0="127.0.0.1" +``` + +
+

Without this setting, forwarded headers are not read. Even over HTTPS, +the refresh token cookie does not get Secure, and every client IP in the audit log becomes the proxy's IP. +They are not read when this is not set so that a device connecting directly over HTTP cannot forge the headers to fake its source.

+
+ +**Check:** Sign in over HTTPS from a device. If the client IP of the "sign-in" entry in the audit log is the device's IP, you are done. +If it is still `127.0.0.1`, the setting in step 5 is not taking effect. + +## Audit log {#audit-log} + +A record of "who changed what, and when". You can view it from **"Audit Log" in the menu** +(system administrators only; other roles do not even see the menu item). + +### Operations recorded + +| Category | Main operations | +|---|---| +| Setup | Creating the initial administrator | +| Auth | Sign-in, failed sign-in, account lockout, sign-out, password change | +| User | Creating and changing users, password resets, granting skills and qualifications | +| Master | Registering, changing and deactivating master data, CSV imports | +| Production | Registering, approving, canceling and releasing manufacturing orders, dispatching | +| Execution | Starting work, registering results, **correcting results**, work time, process condition data, completion approval | +| Inventory | Receiving, moves, **quantity adjustments**, status changes, split / merge / reassign, scrapping, picking, shipping, stocktaking, **cancellations** | +| Quality | Registering, **correcting**, judging and approving inspection results; raising, instructing and approving nonconformances; shipment judgments | +| Maintenance | Maintenance plans, maintenance orders, maintenance records, managing maintenance procedures | +| Equipment | Recording equipment operation, tool usage | + +For **operations whose before and after you want to follow**, such as quantity adjustments, status changes, corrections and cancellations, the "Details" column contains **the value before, the value after and the reason**. +Other operations contain a summary. + +### Filtering + +You can filter by period, category / operation and target (type and ID). +For example, entering `Lot` in "Target type" and the internal ID of a lot in "Target ID" +lists only the operations performed on that lot. + +
+

The period filters by the recorded date (the server's date). +The date and time in the list are shown in the browser's time, so where the server and browser are in different time zones, +entries around midnight may appear on a different day.

+
+ +### Deletion and tampering + +- Individual records **cannot be changed or deleted, either from the screens or from the API**. Records are only ever added. +- **The retention period is 5 years** (it can be changed with `Audit__RetentionYears`). **Nothing is deleted automatically** (whether records may be deleted is a business decision). +- Only when storage becomes a problem can you **delete records older than the retention period in bulk** (see below). + +### Purging old records + +This operation clears out records that are past the retention period. It is **at the very bottom of the Audit Log screen**. +Take a backup first (see below). + +
+
    +
  1. Enter a date in "Delete up to this date (inclusive)" and the reason for deleting in "Reason (required)" (records on or before the date are targeted).
  2. +
  3. Press Check count to delete. Nothing is deleted yet at this point. The number of targeted records is shown.
  4. +
  5. Check the count and press "Delete N records" to delete them.
  6. +
+
+ +Changing the date or the reason resets the count check, and you must check again +(so that what you checked and what is actually deleted do not differ). + +To run it from the API, use the following. While `dryRun=true`, it only returns the count and does not touch the database. + +``` +POST /api/audit-logs/purge?dryRun=true +{ "to": "2020-12-31", "reason": "To reduce storage" } +``` + +
+

Records within the retention period cannot be deleted. A date newer than the retention period is rejected +(if the records of recent operations could be deleted to hide them, the audit log would not stand as evidence).

+

A reason is required, and the purge itself (period, count, reason and user) is recorded in the audit log. +This record is written after the deletion, so it is not removed by the same operation.

+
diff --git a/docs/en/troubleshooting.md b/docs/en/troubleshooting.md index 30c28b3..7e843ba 100644 --- a/docs/en/troubleshooting.md +++ b/docs/en/troubleshooting.md @@ -5,8 +5,8 @@ nav_url: troubleshooting.html lead: Common error messages and what to do about them. Look for the text shown in the red bar. prev_url: reference.html prev_title: Reference -next_url: operations.html -next_title: Administration +next_url: privacy.html +next_title: Privacy policy --- Messages are shown here as they appear when the screen language is English. With the screen in Japanese, they appear in Japanese; see the [Japanese version](../troubleshooting.html) of this page. @@ -117,14 +117,14 @@ Messages are shown here as they appear when the screen language is English. With | Starting the ZIP edition shows "Windows protected your PC" | This warning is attached to files obtained from the internet. You can start it with **More info → Run anyway**. To stop it appearing every time, check **Unblock** in the properties of the ZIP file before extracting, and extract it again | | On Linux, `./start.sh` fails with "Permission denied" | ZIP files do not keep execute permissions. Start it with `sh start.sh` (it gives the program execute permission when it starts) | | The ZIP edition closes immediately after starting / says the port is in use | Another application is using port 5000. Change the port with `MESAPP_URLS` before starting (for example `set MESAPP_URLS=http://0.0.0.0:5100`) | -| Data disappeared after recreating the Docker container | `/data` is not a volume. Start it with `-v mesapp-data:/data` ([Administration](operations.html#docker)) | +| Data disappeared after recreating the Docker container | `/data` is not a volume. Start it with `-v mesapp-data:/data` ([Server deployment and settings](operations.html#docker)) | ## Display and connection | Symptom | What to do | |---|---| | The screen stays at "Loading..." | The server has stopped or the network is disconnected. Check with your administrator | | You are suddenly returned to the sign-in screen while working | The access token has expired. Sign in again. The expiry time can be changed in the settings | -| You cannot connect from another PC | The server's firewall must allow incoming connections on the port ([Administration](operations.html)) | +| You cannot connect from another PC | The server's firewall must allow incoming connections on the port ([Server deployment and settings](operations.html)) | --- diff --git a/docs/getting-started.md b/docs/getting-started.md index c979a0c..9e25965 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -25,7 +25,7 @@ next_title: 画面構成と共通操作 | 項目 | 内容 | |---|---| | サーバー | Windows / Linux(x64)のPC 1台、または Docker が動く環境(amd64 / arm64)。Store 版は Windows 10(2004 以降)/ 11 | -| データベース | 不要。既定ではSQLiteのファイル(`mesapp.db`)が自動生成されます。PostgreSQL / SQL Server も使えます([管理者向け運用](operations.html#database)) | +| データベース | 不要。既定ではSQLiteのファイル(`mesapp.db`)が自動生成されます。PostgreSQL / SQL Server も使えます([データベースとバックアップ](database.html#database)) | | 利用端末 | モダンブラウザ(Chrome / Edge など)。専用アプリのインストールは不要です | | ネットワーク | 端末からサーバーのURLにアクセスできること | @@ -55,7 +55,7 @@ docker run -d -p 8080:8080 -v mesapp-data:/data ghcr.io/msmsrep/parallelfactorym ``` ブラウザで `http://localhost:8080` を開きます。`-v mesapp-data:/data` を付けないと、コンテナを作り直したときにデータが消えます。 -PostgreSQL と一緒に動かす場合は[管理者向け運用](operations.html#docker)を参照してください。 +PostgreSQL と一緒に動かす場合は[サーバーの配置と設定](operations.html#docker)を参照してください。 ### ソースから動かす(開発用) @@ -65,7 +65,7 @@ PostgreSQL と一緒に動かす場合は[管理者向け運用](operations.html dotnet run --project src/MesApp.Api ``` -同じLAN内の他のPCから使う場合の設定(ポート・ファイアウォール・HTTPS)は[管理者向け運用](operations.html)を参照してください。 +同じLAN内の他のPCから使う場合の設定(ポート・ファイアウォール・HTTPS)は[サーバーの配置と設定](operations.html)を参照してください。

データベースファイルと署名鍵はデータ保存先に自動生成されます。データベースの作成作業は不要です。 diff --git a/docs/index.md b/docs/index.md index 766d7dc..13a6242 100644 --- a/docs/index.md +++ b/docs/index.md @@ -14,7 +14,7 @@ next_title: 導入と初期設定 - **製造指図から出荷までを一本の流れで管理**します。製造指図 → 工程ごとの作業指示 → 実績 → 在庫 → 検査 → 出荷判定 → 出荷。 - **ロット単位で追跡**します。どの部材ロットからどの製品ロットができたかを、双方向にたどれます。 -- **記録には必ず「誰が・いつ」が残ります**。実績訂正・検査訂正・マスタ変更・在庫操作・取消は監査ログに記録され、[監査ログ画面](operations.html#audit-log)(システム管理者専用)で確認できます。 +- **記録には必ず「誰が・いつ」が残ります**。実績訂正・検査訂正・マスタ変更・在庫操作・取消は監査ログに記録され、[監査ログ画面](security.html#audit-log)(システム管理者専用)で確認できます。 diff --git a/docs/integration.md b/docs/integration.md new file mode 100644 index 0000000..da1878e --- /dev/null +++ b/docs/integration.md @@ -0,0 +1,329 @@ +--- +layout: default +title: 外部連携 +nav_url: integration.html +lead: "CSVのフォルダ連携、APIキーと連携API、設備イベントの受信、Webhook による通知など、ほかのシステムや設備とつなぐ方法です。" +prev_url: operations.html +prev_title: サーバーの配置と設定 +next_url: security.html +next_title: セキュリティと監査ログ +--- + +## フォルダ連携 {#folder-link} + +決めたフォルダに置かれたCSVを自動で取り込みます。販売管理・生産管理などのソフトが出力したCSVを、 +プログラムを書かずに取り込めます(たとえば、毎朝出力される製造指図のCSVを共有フォルダに置かせる)。 + +### 設定する + +1. 取込を行う利用者を作ります(例 `folder-link`)。**取り込みたい種別に必要なロールだけ**を与えます + (製造指図なら生産管理担当者、受入なら物流・倉庫担当者。ロールごとの権限は[ロールと権限](roles.html))。 + 取込の可否・実績の記録者・監査ログは、この利用者で判定・記録されます。 +2. 連携フォルダと利用者を設定して、再起動します。 + +```powershell +$env:FolderLink__Root="D:\mes-link"; $env:FolderLink__UserName="folder-link"; ./start.cmd +``` + +Docker では、連携フォルダをホストのフォルダにマウントします(`compose.yaml` の例)。 + +```yaml + volumes: + - mesapp-data:/data + - ./mes-link:/link + environment: + FolderLink__Root: /link + FolderLink__UserName: folder-link +``` + +設定を変えたときは再起動が要ります。起動すると、連携フォルダの下に `inbox`・`processed`・`error` が作られます。 + +### ファイルの置き方 + +| 置く場所 | 種別の決まり方 | 例 | +|---|---|---| +| `inbox` の直下 | ファイル名(最初の「_」より後ろ) | `inbox/manufacturing-orders.csv`、`inbox/20261122_manufacturing-orders.csv` | +| `inbox/<種別>/` | フォルダ名(ファイル名は問わない) | `inbox/manufacturing-orders/製造指図.csv` | +| `inbox` の直下のZIP | 中のファイル名(ZIPの一括取込と同じ) | `inbox/masters.zip` | + +- 種別の名前とCSVの列は、マスタ管理・実績CSV取込の画面のテンプレートと同じです。出力するファイル名を変えられないソフトは、種別のフォルダに出力させます。 +- CSV・ZIP 以外のファイルは無視します。書き込み中のファイルは、書き終わってから取り込みます。 +- 置かれた順(更新日時の古い順)に1ファイルずつ取り込みます。後のファイルが前のファイルを参照するとき(製造指図のあとに受入など)は、順に置くか1つのZIPにまとめます。 + +### 結果を確かめる + +- **取り込めたファイルは `processed`、取り込めなかったファイルは `error`** の `日付/時刻/` の下へ移り、横に結果ファイル(`.result.txt`)が付きます。エラーの行番号と理由はここに書かれます。 +- 取込は画面から取り込むときと同じチェックを通り、**1行でもエラーがあればそのファイルは何も反映しません**。直したファイルを `inbox` の同じ場所へ戻せば、取り込み直せます。 +- システム管理者は、メニューの「管理」→「フォルダ連携」で、設定の誤りと最近処理したファイルを確かめられます。「今すぐ取り込む」で、次の間隔を待たずに取り込めます。 +- 利用者がいない・無効・ロック中のときは、何も取り込まずファイルを `inbox` に残します(画面に理由が出ます)。 + +MESから外へ書き出す連携(実績の自動出力)は、まだありません。 + +## APIキー {#api-keys} + +販売管理・生産管理などのシステムや社内のスクリプトが、ログインせずに MES の**連携API**(`/api/integration/v1/...`)を呼ぶためのキーです。 + +### 発行する + +1. キーで操作させる利用者を作ります(例 `erp-link`)。**キーで行える操作は、この利用者のロールで決まります**。用途ごとに専用の利用者を作り、必要なロールだけを与えてください([ロールと権限](roles.html))。 +2. システム管理者が、メニューの「管理」→「APIキー」で、用途・利用者・有効期限(任意)を指定して **キーを発行** を押します。 +3. 表示されたキー(`pfm_` で始まる文字列)を、連携するシステムの設定に写します。**キーはこのときしか表示されません**。なくしたときは、失効させて発行し直します。 + +### 呼んでみる + +要求のヘッダ `X-Api-Key` にキーを付けます。次の口で、誰として扱われるか(利用者とロール)を確かめられます。 + +```powershell +Invoke-RestMethod http://localhost:5000/api/integration/v1/whoami -Headers @{ "X-Api-Key" = "pfm_..." } +``` + +```bash +curl -H "X-Api-Key: pfm_..." http://localhost:5000/api/integration/v1/whoami +``` + +### 注意 + +- キーで呼べるのは連携API だけです。画面で使っている API(`/api/products` など)はキーでは呼べません(401)。 +- キーで行った操作は、紐づけた利用者が行ったものとして監査ログに残ります。 +- **失効させたキーは元に戻せません**。利用者を無効にしたとき、キーの有効期限が過ぎたときも、すぐに使えなくなります。ロールを変えると、次の呼び出しから新しいロールで判定されます。 +- キーはパスワードと同じように扱ってください。メールやチャットに貼らず、連携するシステムの設定の中だけに置きます。 + +## 連携API {#integration-api} + +販売管理・生産管理(ERP)や社内のスクリプトから、MES とデータをやり取りするための API です。呼び出しには [APIキー](#api-keys) を使います。 + +### 仕様書(OpenAPI) + +連携API の仕様書を `/openapi/integration-v1.json` で公開しています(例 `http://localhost:5000/openapi/integration-v1.json`)。 +Postman や Visual Studio などに読み込むと、口の一覧・引数・応答の形が分かります。仕様書の取得にはキーは要りません。 + +### 使える口 + +| 口 | 内容 | +|---|---| +| `GET /api/integration/v1/whoami` | キーが通るか、誰として・どのロールで扱われるかを確かめる | +| `GET /api/integration/v1/csv-kinds` | 取り込める CSV の種別と列(マスタ管理・実績CSV取込の画面と同じ) | +| `POST /api/integration/v1/masters/{種別}` | マスタCSVの取込(コードで上書き) | +| `POST /api/integration/v1/actuals/{種別}` | 実績CSVの取込(常に新規登録) | +| `POST /api/integration/v1/masters/bundle`・`actuals/bundle` | CSV をまとめた ZIP の取込 | +| `GET /api/integration/v1/masters/{種別}` | マスタのCSV出力 | +| `GET /api/integration/v1/production-results` | 生産実績を前回の続きから読む | +| `GET /api/integration/v1/production-result-corrections` | 生産実績の訂正を前回の続きから読む | +| `POST /api/integration/v1/equipment-events` | 設備の状態の変化を送る([設備イベントの受信](#equipment-events)) | + +### CSV を取り込む + +本文に CSV をそのまま送ります(文字コードは UTF-8 か Shift_JIS)。`?dryRun=true` を付けると、検証だけして反映しません。 +このページの PowerShell の例は PowerShell 7(`pwsh`)向けです。 + +```powershell +$headers = @{ "X-Api-Key" = "pfm_..."; "Idempotency-Key" = "orders-20261123" } +Invoke-RestMethod -Method Post -Headers $headers -ContentType "text/csv; charset=utf-8" -InFile .\manufacturing-orders.csv -Uri http://localhost:5000/api/integration/v1/actuals/manufacturing-orders +``` + +```bash +curl -H "X-Api-Key: pfm_..." -H "Idempotency-Key: orders-20261123" -H "Content-Type: text/csv" --data-binary @manufacturing-orders.csv http://localhost:5000/api/integration/v1/actuals/manufacturing-orders +``` + +- 取り込めたら **200**、1行でもエラーがあれば **422** で、何も反映しません。どちらも応答の本文に、件数と行番号付きのエラーが入ります(PowerShell 7 では `-SkipHttpErrorCheck` を付けると 422 の本文も受け取れます)。 +- 取込の権限は、キーに紐づく利用者のロールで画面と同じように判定します(権限が無ければ 403)。 + +### 送り直しても二重に登録しない(Idempotency-Key) + +実績CSVは**常に新規登録**なので、通信が切れたあとに同じ CSV を送り直すと、二重に登録されることがあります。 +これを防ぐには、送る内容ごとに決めた値(例:指図の出力日時と連番、UUID)を `Idempotency-Key` ヘッダに付けます。 + +- 同じキー・同じ内容で送り直すと、**取り込み直さずに前回の応答を返します**(応答のヘッダに `Idempotent-Replayed: true` が付きます)。 +- 同じキーで内容が違う要求は 409 になります。新しい内容には新しいキーを付けてください。 +- キーは24時間覚えています。キーは APIキーごとに別に扱います。 + +### 生産実績を読む(前回の続きから) + +`afterId` に前回の `nextAfterId` を渡すと、その後に記録された実績だけが返ります。`hasMore` が true の間は続けて読みます。 +最後の `nextAfterId` を保存しておけば、次の実行は続きから始まります。 + +```powershell +$headers = @{ "X-Api-Key" = "pfm_..." } +$after = if (Test-Path .\last-id.txt) { Get-Content .\last-id.txt } else { 0 } +do { + $page = Invoke-RestMethod -Headers $headers -Uri "http://localhost:5000/api/integration/v1/production-results?afterId=$after" + $page.items | Export-Csv .\production-results.csv -Append -Encoding utf8 + $after = $page.nextAfterId +} while ($page.hasMore) +Set-Content .\last-id.txt $after +``` + +- 実績の数量は、訂正された後の今の値です。既に読んだ実績が後から訂正されたことは、`production-result-corrections` を同じように続きから読むと分かります。 +- 承認前の実績も返します(`approvedAt` が空)。取り消した指図の実績も、現物のロットが残るので返します(`workOrderStatus` で分かります)。 + +### 版を上げても連携が動き続けるための約束 + +- v1(`/api/integration/v1`)の中では、**項目や口を足すだけ**で、消したり名前や意味を変えたりしません。変えるときは v2 を作ります。 +- CSV の列も同じです。列は消さず、必須の列も増やしません(新しい列は、省けば今までどおりに動きます)。列の名前を変えるときは、以前の名前でも読めるようにします。 +- 応答に知らない項目が増えても、読み飛ばすように連携を作ってください。 + +## 設備イベントの受信 {#equipment-events} + +設備の稼働状態(稼働・停止・段取り・故障・アイドル)を、設備から自動で記録する仕組みです。 +**MES は PLC と直接は通信しません。** PLC の状態はゲートウェイ(Node-RED など)が読み、状態が変わったときに MES の連携API へ送ります。 +MES は届いた状態の変化を、設備ごとに時刻の順に並べて**稼働履歴の区間**(開始〜終了)に組み立てます。 + +``` +設備・PLC ──(OPC UA・MC プロトコル・Modbus など)──▶ ゲートウェイ ──(HTTP・APIキー)──▶ MES + (Node-RED など) POST /api/integration/v1/equipment-events +``` + +### 準備する + +1. 設備マスタ(マスタ管理の **設備(BOE)** タブ)で、対象の設備に **設備イベントで稼働状態を収集する** を付けます。 + 付けた設備には、稼働実績を手入力や実績CSVで登録できなくなります(手と自動で同じ時間を二重に数えないため)。停止原因の追記はできます。 +2. ゲートウェイ用の利用者を作り、[APIキー](#api-keys) を発行します。受信はロールを問いません。 +3. 必要なら、アラーム番号を停止原因に置き換える **停止原因の対応表**(マスタ管理)を登録します。 + +### 送る形 + +状態が変わるたびに1件を作り、ためておいてまとめて送ります(1回に1,000件まで)。 + +```json +{ + "events": [ + { "equipmentCode": "EQ-06", "eventId": "EQ-06-1732323600000-1", "occurredAt": "2026-11-23T09:00:00+09:00", "state": "Running" }, + { "equipmentCode": "EQ-06", "eventId": "EQ-06-1732324200000-2", "occurredAt": "2026-11-23T09:10:00+09:00", "state": "Stopped", "alarmCode": "A-101" } + ] +} +``` + +| 項目 | 内容 | +|---|---| +| `equipmentCode` | 設備の資産番号 | +| `eventId` | ゲートウェイが振る一意のID(設備ごとに一意。100文字まで)。**送り直しても同じ値**にする | +| `occurredAt` | 設備で状態が変わった時刻(`+09:00` などのオフセット付き) | +| `state` | `Running`(稼働)/`Stopped`(停止)/`Setup`(段取り)/`Failure`(故障)/`Idle`(アイドル)/`Off`(電源断・通信断) | +| `alarmCode` | 任意。停止・故障のときのアラーム番号(停止原因の対応表で原因を引く) | +| `workOrderNo` + `operationSeq` | 任意。処理中の作業指示(指図番号と工程順序の組) | +| `note` | 任意。備考 | + +```powershell +$headers = @{ "X-Api-Key" = "pfm_..." } +$body = @{ events = @(@{ equipmentCode = "EQ-06"; eventId = "test-1"; occurredAt = (Get-Date).ToString("o"); state = "Running" }) } | ConvertTo-Json -Depth 4 +Invoke-RestMethod -Method Post -Headers $headers -ContentType "application/json" -Body $body -Uri http://localhost:5000/api/integration/v1/equipment-events +``` + +### 届いた後の扱い + +- 新しい状態が届くと、開いている区間を閉じて次の区間を開きます。同じ状態が続けて届いても区間は変わりません。`Off` は区間を閉じるだけです。 +- 1回に送った中で時刻が前後していても、時刻の順に並べ直して反映します。 +- **同じ `eventId` を送り直すと「重複」になり、二重に記録されません。** 通信が切れたら、ためた分をそのまま送り直してください。 +- **最後に反映した時刻より前のイベントは「遅着」として拒否します。** 過去の区間は組み直しません。設備とゲートウェイの時計は NTP で揃えてください。サーバーの時刻より先すぎる時刻(既定300秒を超える)も拒否します。 +- 応答は 200 で、1件ごとの結果(`Accepted` 採用/`Duplicate` 重複/`Rejected` 拒否と理由)が入ります。全部が拒否でも 200 です。拒否した `eventId` は、直して送り直すと判定し直します。 +- 停止・故障の区間は、アラーム番号から停止原因の対応表で原因を引きます。引けなければ**原因未入力**のまま記録され、保全管理の稼働監視タブで後から入れられます。 +- 作業指示は、指定があればそれに紐づけます。指定が無ければ、**その設備を割り当てた着手中の作業指示がちょうど1件のときだけ**紐づけます。 + +受信の様子は、保全管理の稼働監視タブの **設備の今の状態** で見られます。受信が一定時間(既定10分)途絶えると、その設備に「受信が途絶えています」と出ます(ゲートウェイが止まったことに気づけます)。 + +### サンプルで試す(Docker) + +`compose.yaml` には、MQTT ブローカー(Eclipse Mosquitto)と Node-RED のゲートウェイを一緒に起動する `equipment` プロファイルがあります。 +Node-RED には、数秒ごとに状態を変える**模擬設備**と、MQTT を受けて MES へまとめて送るフローが入っています(`samples/equipment-gateway`)。 + +1. リポジトリの直下で `docker compose --profile equipment up -d` を実行します。 +2. MES(http://localhost:8080)にサンプルのマスタを取り込みます。`EQ-06` が設備イベントで収集する設備になっています。 +3. APIキーを発行し、リポジトリの直下の `.env` に `MES_API_KEY=pfm_...` と書いて、もう一度 `docker compose --profile equipment up -d` を実行します。 +4. 稼働監視タブで、`EQ-06` の今の状態と稼働履歴が増えていくのを確かめます。Node-RED(http://localhost:1880)の「結果を見る」ノードに、採用・重複・拒否の件数が出ます。 + +自分の設備に合わせるときは、Node-RED の「状態を変える」ノードを、PLC から状態を読むノード(OPC UA・MC プロトコル・Modbus など)に置き換えます。 +サンプルの MQTT ブローカーは認証も暗号化もしない最小構成です。本番ではパスワードと TLS を設定してください。 + +## Webhook(MES からの通知) {#webhooks} + +不適合の起票・設備の停止・ロットの保留のように**すぐ知りたい出来事**が起きたとき、MES から登録した URL へ HTTP で知らせる仕組みです。 +班長のチャットへの通知や、完成をきっかけにした次の処理に使えます。 +定期に取りに来れば足りる相手(ERP の在庫・原価など)は、[連携API](#integration-api) の生産実績の読み出しで足ります。 + +通知は**薄く**作っています。種類・発生日時・対象の番号と、人が読める1文の要約だけを送ります。 +通知は「読みに行くきっかけ」です。正しい今の値は連携API で取りに行ってください(通知が届かなかった・順が入れ替わったときも、それで追いつけます)。 + +``` +MES ──(POST・署名付き)──▶ 受け側(Node-RED・社内のスクリプトなど)──▶ チャット・表示盤・ERP +``` + +### 送信先を登録する + +1. システム管理者が、メニューの「管理」→「Webhook」の **送信先** タブで、用途・送信先の URL・通知するイベントを選んで **登録** を押します。 +2. 表示された **署名の秘密の値**(`whsec_` で始まる文字列)を、受け側の設定に写します。**この値は今しか表示できません。** 失くしたら **秘密の値を再発行** を押します(古い値はすぐに使えなくなるので、受け側の設定も直します)。 +3. **テスト送信** を押して、受け側に届くか確かめます。結果はその場で出ます(テスト送信は失敗しても送り直しません)。 + +- URL は `http://` も使えます(工場の中のネットワーク向け)。`http://` の送信先には本文が暗号化されずに流れるので、社外へ送るときは `https://` にしてください。 +- 利用者名・パスワードを含む URL は登録できません(一覧と監査ログに URL がそのまま出るため)。受け側は署名で送り手を確かめます。 +- 送るのを止めるだけなら、**有効** を外します。削除すると、まだ送っていない通知と送信の記録も消えます。 + +### 通知するイベント + +| 種類 | いつ | 主な項目 | +|---|---|---| +| `production-result.created` | 生産実績を記録した(画面・実績CSV・連携API のどれでも) | 指図番号・作業指示番号・工程順序・品目コード・良品/不良数・産出ロット | +| `production-result.corrected` | 生産実績を訂正した | 訂正した実績の `productionResultId`・訂正前後の数・理由 | +| `work-order.status-changed` | 作業指示の状態が変わった(差立・着手・完了・承認・取消) | 作業指示番号・変更前/後の状態 | +| `manufacturing-order.status-changed` | 製造指図が完了・取消になった | 指図番号・指図区分・変更前/後の状態 | +| `lot.status-changed` | ロットの在庫ステータスが変わった(保留・解除・検査待ちなど) | ロット番号・品目コード・変更前/後・契機・理由 | +| `nonconformance.created` | 不適合を起票した(検査の不合格からの自動起票を含む) | 不適合番号・発生源・ロット番号・品目コード | +| `equipment.stopped` | 設備が停止・故障の区間に入った(手入力・実績CSV・[設備イベント](#equipment-events) のどれでも) | 資産番号・状態・停止原因・アラーム番号 | + +区分・状態は英語の名前(`OnHold` など)で送ります(表示言語で変わらないように)。内部のIDは送らず、番号・コードで指します。 +要約(`summary`)は日本語です。 + +### 送る形 + +```json +{ + "id": "c548bec2-5e89-4210-ba22-2110c0325f09", + "sequence": 7, + "type": "equipment.stopped", + "version": 1, + "occurredAt": "2026-11-23T11:02:01+00:00", + "summary": "設備 EQ-01 が「停止」になりました(材料切れ)。", + "data": { "equipmentAssetNo": "EQ-01", "status": "Stopped", "startedAt": "2026-11-23T10:32:00+00:00", "endedAt": null, + "stopCause": "材料切れ", "alarmCode": null, "source": "Manual", "workOrderNo": null } +} +``` + +| 項目・ヘッダ | 内容 | +|---|---| +| `id` | 通知の一意のID。**送り直しても同じ値**(受け側はこれで重複を捨てる) | +| `sequence` | 種類をまたいで増える番号(連番とは限らない) | +| `data` | 種類ごとの中身(上の表)。項目の一覧は [仕様書(OpenAPI)](#integration-api) の `webhooks` 節にある | +| `X-Mes-Event` | 種類(本文の `type` と同じ) | +| `X-Mes-Delivery` | 送信のID(送り直しても同じ) | +| `X-Mes-Timestamp` | 送った時刻(Unix 秒) | +| `X-Mes-Signature` | 署名。`sha256=` に続けて、秘密の値を鍵にした「`X-Mes-Timestamp` の値 `.` 本文」の HMAC-SHA256 を小文字の16進で書いたもの | + +### 受け側で確かめること + +1. **署名を確かめます。** 受け取った本文のバイト列そのもので計算します。JSON に読み替えてから文字列に戻すと、数値の書き方などが変わって合いません。 +2. **時刻のずれを確かめます。** `X-Mes-Timestamp` が5分以上ずれていたら受け付けません(古い要求の送り直しを弾くため)。MES と受け側の時計は NTP で揃えてください。 +3. **すぐに 2xx を返します。** MES は応答を既定10秒まで待ち、待ち切れなければ送り直します。重い処理は応答の後に回してください。 +4. **同じ `id` の2回目以降は捨てます。** 通知は少なくとも1回届きますが、同じ通知が2回届くことがあります。順序も保証しません。 + +### 届かなかったとき + +- 送信先に繋がらない・待ち切れない・`5xx`・`408`・`429` のときは、間隔を空けて送り直します(1分・5分・30分・2時間・6時間・12時間・24時間。既定で8回まで)。 +- それ以外の `4xx` と `3xx` は、送り直しても同じなので1回で止めます(リダイレクトは追いません)。 +- 止まった通知は、**送信の記録** タブで受け側を直してから **再送** を押します。通知の `id` は変わらないので、届いていた受け側は重複として捨てられます。 +- 送り直しを待っている・止まった通知がある送信先は、**送信先** タブの「送れていない送信」と、システム管理者の **ダッシュボード** の上部に出ます。送信先は自動では止めません。 +- 送信の記録は既定30日残します。 +- データ保存先の `dataprotection-keys`(秘密の値を暗号化する鍵)を失うと、秘密の値を復号できず、その送信先の通知は止まります。秘密の値を再発行し、受け側の設定を直してから再送してください([バックアップ](database.html#backup) で一緒に退避します)。 + +### サンプルで試す + +- **Node-RED(Docker)**:`equipment` プロファイルの Node-RED([設備イベントのサンプル](#equipment-events))に、通知を受けて署名を確かめ、チャット(Slack・Teams)の形にして転送する「Webhook の受け側」タブがあります。 + 1. `docker compose --profile equipment up -d` で起動し、送信先に `http://node-red:1880/mes-webhook` を登録します。 + 2. 秘密の値をリポジトリの直下の `.env` に `MES_WEBHOOK_SECRET=whsec_...` と書き、もう一度 `docker compose --profile equipment up -d` を実行します。 + 3. **テスト送信** を押すと、Node-RED(http://localhost:1880)のデバッグ欄に「受けた通知」と「チャットに届いた形」が出ます。 + 転送先の既定はフローの中の模擬で、実際のチャットには送りません。送るときは `.env` に `CHAT_WEBHOOK_URL`(Slack の Incoming Webhook、または Teams のワークフローの「Webhook 要求を受信したとき」の URL)と、Teams なら `CHAT_KIND=teams` を書きます。 +- **スクリプト**:`samples/webhook` に Python(`receive_mes_webhook.py`)と PowerShell(`Receive-MesWebhook.ps1`)の最小の受け側があります。処理を書き足す場所は README を見てください。 + +### 版を上げても受け側が動き続けるための約束 + +- 本文の項目は消しません。名前と型も変えません。値が必ずあった項目を、値の無いことがある項目にはしません。 +- 項目・種類・区分の値は増えることがあります。受け側は知らない項目を読み飛ばすようにしてください。 +- 形を変える必要があるときは、別の種類(v2)として足します。 diff --git a/docs/intro.html b/docs/intro.html index a44f764..92f172e 100644 --- a/docs/intro.html +++ b/docs/intro.html @@ -245,6 +245,49 @@

立ち上げは、CSVをまとめて

+
+
+
連携APIWebhook
+

ほかのシステムとは、
CSV・API・通知でつなぐ

+

販売管理や生産計画のソフトが出すCSVは、決めたフォルダに置くだけで取り込めます。プログラムからは、APIキーで連携APIを呼んで取込・出力ができます。MESの側で起きたことは、Webhook で登録したURLへ知らせます。

+
    +
  • 連携APIの仕様書(OpenAPI)つき。送り直しても二重に登録しない
  • +
  • 生産実績は「前回の続きから」読み出せる
  • +
  • 通知は実績・状態の変化・不適合・設備の停止。届かなければ自動で再送
  • +
+
+
+
Webhook送信の記録
+ Webhook画面の送信の記録タブ。設備の停止とテスト送信の通知が、送信先へ送信済みになった一覧 +
+
+ +
+
+
E-20-10-03設備イベント
+

設備の今の状態が、
その場で分かる

+

PLCの状態をゲートウェイ(Node-REDなど)が読み、変わるたびにMESへ送ります。MESはそれを稼働・停止・段取りの区間に組み立て、アラーム番号から停止原因を引き当てます。

+
    +
  • 受信が途絶えたら、その設備に知らせが出る
  • +
  • 引き当てられなかった停止は、後から原因を入れられる
  • +
  • 手入力の設備と、自動で集める設備を同じ画面で
  • +
+
+
+
設備保全稼働監視
+ 設備保全画面の稼働監視タブ。設備の今の状態の一覧で、設備イベントで収集するEQ-06が停止中、停止原因は前工程からのワーク待ち +
+
+ +
+

そのほかにも

+
+
生産計画と予実

製造日×品目×工程ごとに計画数量を登録し、生産実績の良品数と並べて達成率を見られます。

+
日本語と英語

画面の右上で表示言語を切り替えられます。ユーザーガイドも日英の2言語です。

+
スマホの幅でも

狭い画面ではメニューを開閉でき、表は横にスクロールします。現場のタブレットやスマホから使えます。

+
+
+
@@ -282,7 +325,7 @@

Docker

動かしてみる

  1. 起動する

    上のどれかで起動し、ブラウザで http://localhost:5000(Docker は 8080)を開きます。ストア版はアプリの画面がそのまま開きます。データベース(SQLite)は自動で作られます。

  2. -
  3. 管理者を作る

    最初は初期セットアップの案内が出るので、管理者を作ります。ストア版は管理者が自動で作られ、ユーザー名と初期パスワードが画面の上に表示されます。

  4. +
  5. 管理者を作る

    最初は初期セットアップの画面が出るので、管理者のユーザー名とパスワードを決めて作ります。ストア版も同じです。

  6. サンプルを入れる

    マスタ・実績のサンプルZIPをこの順に取り込むと、製造指図から出荷まで試せる状態になります。

diff --git a/docs/maintenance.md b/docs/maintenance.md index 5e1c7bf..20a08c0 100644 --- a/docs/maintenance.md +++ b/docs/maintenance.md @@ -26,7 +26,7 @@ next_title: 帳票・ラベル・スキャン 自動では更新しません。最新にするときは **更新** を押します。 設備イベントで収集する設備には **最後の受信** の時刻が出ます。受信が一定時間(既定10分)途絶えると「(受信が途絶えています)」と出ます。 -ゲートウェイや通信が止まっていないかを確かめてください([設備イベントの受信](operations.html#equipment-events))。 +ゲートウェイや通信が止まっていないかを確かめてください([設備イベントの受信](integration.html#equipment-events))。 #### 稼働実績を記録する diff --git a/docs/masters.md b/docs/masters.md index bc4a6c9..ee28093 100644 --- a/docs/masters.md +++ b/docs/masters.md @@ -150,7 +150,7 @@ MBOMは、実績入力の**バックフラッシュ**(部材の自動消費) | 保全タイプ | 保全対象外/カレンダベース/稼働時間ベース/使用回数ベース | | 保全閾値 | 保全タイプに応じた周期・時間・回数 | | 保全部品 | 交換部品のメモ | -| 設備イベントで稼働状態を収集する | 付けると、稼働実績を設備イベント(ゲートウェイからの受信)で記録します。手入力・実績CSVでは登録できなくなります([設備イベントの受信](operations.html#equipment-events)) | +| 設備イベントで稼働状態を収集する | 付けると、稼働実績を設備イベント(ゲートウェイからの受信)で記録します。手入力・実績CSVでは登録できなくなります([設備イベントの受信](integration.html#equipment-events)) | ### 停止原因の対応表 {#alarm-codes} @@ -345,7 +345,7 @@ CSVに登場しなかった親品目のMBOM・工順は変更されません。 - 取り込める権限は、種別ごとに画面から登録するときと同じです(受入・出荷指示・出荷実行は物流、製造指図は生産管理、検査は品質管理、出荷判定は品質保証 など。保全の突発依頼と実績・治工具の利用実績は誰でも、保全計画と計画保全の指示は保全担当者だけ、治工具の引当は生産管理、検査機の校正は品質管理)。 - 「1行でもエラーがあると全件取り消し」「検証のみ」はマスタのCSVと同じです。 - 画面の上の **ZIPで一括取込** で、複数のCSVを1回で取り込めます(ファイル名の順。1ファイルでもエラーがあればZIPの全ファイルを取り消し)。 -- 販売管理・生産管理などのソフトが出力するCSVを毎回取り込むときは、**[フォルダ連携](operations.html#folder-link)** を使うと、決めたフォルダに置くだけで自動で取り込めます(設定はシステム管理者が行います)。プログラムから取り込むときは **[連携API](operations.html#integration-api)** を使います。 +- 販売管理・生産管理などのソフトが出力するCSVを毎回取り込むときは、**[フォルダ連携](integration.html#folder-link)** を使うと、決めたフォルダに置くだけで自動で取り込めます(設定はシステム管理者が行います)。プログラムから取り込むときは **[連携API](integration.html#integration-api)** を使います。 受入から出荷まで一通りそろった**サンプル**が **[samples-actual-csv.zip](https://github.com/msmsrep/ParallelFactoryMES/releases/latest/download/samples-actual-csv.zip)** にあります diff --git a/docs/operations.md b/docs/operations.md index ffc0b8b..39abb21 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -1,14 +1,29 @@ --- layout: default -title: 管理者向け運用 +title: サーバーの配置と設定 nav_url: operations.html -lead: サーバーの配置、設定項目、バックアップなど、システム管理者向けの情報です。 -prev_url: troubleshooting.html -prev_title: 困ったときは -next_url: privacy.html -next_title: プライバシーポリシー +lead: "サーバーの構成、配布物ごとの起動方法、設定項目など、管理者が最初に押さえる情報です。" +prev_url: roles.html +prev_title: ロールと権限 +next_url: integration.html +next_title: 外部連携 --- + + + +このほかの管理者向けの情報: + +- [外部連携](integration.html) +- [セキュリティと監査ログ](security.html) +- [データベースとバックアップ](database.html) + ## 構成 Webクライアント(Blazor WebAssembly)は、APIサーバー(ASP.NET Core)が同一オリジンで配信します。 @@ -18,7 +33,7 @@ Webクライアント(Blazor WebAssembly)は、APIサーバー(ASP.NET Cor |---|---| | MesApp.Api | 業務ロジックとデータベース。Webクライアントも配信します | | MesApp.Client.Web | ブラウザで動作するクライアント | -| データベース | SQLite(既定。ファイル1つ)、PostgreSQL、SQL Server のいずれか。起動時にマイグレーションが自動適用されます([PostgreSQL / SQL Server を使う](#database)) | +| データベース | SQLite(既定。ファイル1つ)、PostgreSQL、SQL Server のいずれか。起動時にマイグレーションが自動適用されます([PostgreSQL / SQL Server を使う](database.html#database)) | ## 配布と起動 @@ -52,7 +67,7 @@ docker compose up -d - データベースと署名鍵はボリューム(コンテナ内の `/data`)に置かれます。コンテナを作り直しても消えません - タイムゾーンの既定は `TZ=Asia/Tokyo` です。業務日付の境界時刻はこの時刻で判定されます - HTTPS はコンテナでは扱いません。前段のリバースプロキシで終端し、プロキシのいるネットワークを - `ReverseProxy__KnownNetworks__0`(例 `172.16.0.0/12`)で指定します([HTTPSで運用する](#https)) + `ReverseProxy__KnownNetworks__0`(例 `172.16.0.0/12`)で指定します([HTTPSで運用する](security.html#https)) - バージョンアップは `docker compose pull` → `docker compose up -d` です ### ソースから発行して起動する @@ -114,586 +129,13 @@ $env:MesAdmin__UserName="admin"; $env:MesAdmin__Password="Passw0rd123"; dotnet p `MesAdmin__Password` を指定しない場合、初期管理者は作成されません(値を誰も知らない アカウントを残さないため)。その場合は[初期セットアップ画面](getting-started.html)で作成します。 -## フォルダ連携 {#folder-link} - -決めたフォルダに置かれたCSVを自動で取り込みます。販売管理・生産管理などのソフトが出力したCSVを、 -プログラムを書かずに取り込めます(たとえば、毎朝出力される製造指図のCSVを共有フォルダに置かせる)。 - -### 設定する - -1. 取込を行う利用者を作ります(例 `folder-link`)。**取り込みたい種別に必要なロールだけ**を与えます - (製造指図なら生産管理担当者、受入なら物流・倉庫担当者。ロールごとの権限は[ロールと権限](roles.html))。 - 取込の可否・実績の記録者・監査ログは、この利用者で判定・記録されます。 -2. 連携フォルダと利用者を設定して、再起動します。 - -```powershell -$env:FolderLink__Root="D:\mes-link"; $env:FolderLink__UserName="folder-link"; ./start.cmd -``` - -Docker では、連携フォルダをホストのフォルダにマウントします(`compose.yaml` の例)。 - -```yaml - volumes: - - mesapp-data:/data - - ./mes-link:/link - environment: - FolderLink__Root: /link - FolderLink__UserName: folder-link -``` - -設定を変えたときは再起動が要ります。起動すると、連携フォルダの下に `inbox`・`processed`・`error` が作られます。 - -### ファイルの置き方 - -| 置く場所 | 種別の決まり方 | 例 | -|---|---|---| -| `inbox` の直下 | ファイル名(最初の「_」より後ろ) | `inbox/manufacturing-orders.csv`、`inbox/20261122_manufacturing-orders.csv` | -| `inbox/<種別>/` | フォルダ名(ファイル名は問わない) | `inbox/manufacturing-orders/製造指図.csv` | -| `inbox` の直下のZIP | 中のファイル名(ZIPの一括取込と同じ) | `inbox/masters.zip` | - -- 種別の名前とCSVの列は、マスタ管理・実績CSV取込の画面のテンプレートと同じです。出力するファイル名を変えられないソフトは、種別のフォルダに出力させます。 -- CSV・ZIP 以外のファイルは無視します。書き込み中のファイルは、書き終わってから取り込みます。 -- 置かれた順(更新日時の古い順)に1ファイルずつ取り込みます。後のファイルが前のファイルを参照するとき(製造指図のあとに受入など)は、順に置くか1つのZIPにまとめます。 - -### 結果を確かめる - -- **取り込めたファイルは `processed`、取り込めなかったファイルは `error`** の `日付/時刻/` の下へ移り、横に結果ファイル(`.result.txt`)が付きます。エラーの行番号と理由はここに書かれます。 -- 取込は画面から取り込むときと同じチェックを通り、**1行でもエラーがあればそのファイルは何も反映しません**。直したファイルを `inbox` の同じ場所へ戻せば、取り込み直せます。 -- システム管理者は、メニューの「管理」→「フォルダ連携」で、設定の誤りと最近処理したファイルを確かめられます。「今すぐ取り込む」で、次の間隔を待たずに取り込めます。 -- 利用者がいない・無効・ロック中のときは、何も取り込まずファイルを `inbox` に残します(画面に理由が出ます)。 - -MESから外へ書き出す連携(実績の自動出力)は、まだありません。 - -## APIキー {#api-keys} - -販売管理・生産管理などのシステムや社内のスクリプトが、ログインせずに MES の**連携API**(`/api/integration/v1/...`)を呼ぶためのキーです。 - -### 発行する - -1. キーで操作させる利用者を作ります(例 `erp-link`)。**キーで行える操作は、この利用者のロールで決まります**。用途ごとに専用の利用者を作り、必要なロールだけを与えてください([ロールと権限](roles.html))。 -2. システム管理者が、メニューの「管理」→「APIキー」で、用途・利用者・有効期限(任意)を指定して **キーを発行** を押します。 -3. 表示されたキー(`pfm_` で始まる文字列)を、連携するシステムの設定に写します。**キーはこのときしか表示されません**。なくしたときは、失効させて発行し直します。 - -### 呼んでみる - -要求のヘッダ `X-Api-Key` にキーを付けます。次の口で、誰として扱われるか(利用者とロール)を確かめられます。 - -```powershell -Invoke-RestMethod http://localhost:5000/api/integration/v1/whoami -Headers @{ "X-Api-Key" = "pfm_..." } -``` - -```bash -curl -H "X-Api-Key: pfm_..." http://localhost:5000/api/integration/v1/whoami -``` - -### 注意 - -- キーで呼べるのは連携API だけです。画面で使っている API(`/api/products` など)はキーでは呼べません(401)。 -- キーで行った操作は、紐づけた利用者が行ったものとして監査ログに残ります。 -- **失効させたキーは元に戻せません**。利用者を無効にしたとき、キーの有効期限が過ぎたときも、すぐに使えなくなります。ロールを変えると、次の呼び出しから新しいロールで判定されます。 -- キーはパスワードと同じように扱ってください。メールやチャットに貼らず、連携するシステムの設定の中だけに置きます。 - -## 連携API {#integration-api} - -販売管理・生産管理(ERP)や社内のスクリプトから、MES とデータをやり取りするための API です。呼び出しには [APIキー](#api-keys) を使います。 - -### 仕様書(OpenAPI) - -連携API の仕様書を `/openapi/integration-v1.json` で公開しています(例 `http://localhost:5000/openapi/integration-v1.json`)。 -Postman や Visual Studio などに読み込むと、口の一覧・引数・応答の形が分かります。仕様書の取得にはキーは要りません。 - -### 使える口 - -| 口 | 内容 | -|---|---| -| `GET /api/integration/v1/whoami` | キーが通るか、誰として・どのロールで扱われるかを確かめる | -| `GET /api/integration/v1/csv-kinds` | 取り込める CSV の種別と列(マスタ管理・実績CSV取込の画面と同じ) | -| `POST /api/integration/v1/masters/{種別}` | マスタCSVの取込(コードで上書き) | -| `POST /api/integration/v1/actuals/{種別}` | 実績CSVの取込(常に新規登録) | -| `POST /api/integration/v1/masters/bundle`・`actuals/bundle` | CSV をまとめた ZIP の取込 | -| `GET /api/integration/v1/masters/{種別}` | マスタのCSV出力 | -| `GET /api/integration/v1/production-results` | 生産実績を前回の続きから読む | -| `GET /api/integration/v1/production-result-corrections` | 生産実績の訂正を前回の続きから読む | -| `POST /api/integration/v1/equipment-events` | 設備の状態の変化を送る([設備イベントの受信](#equipment-events)) | - -### CSV を取り込む - -本文に CSV をそのまま送ります(文字コードは UTF-8 か Shift_JIS)。`?dryRun=true` を付けると、検証だけして反映しません。 -このページの PowerShell の例は PowerShell 7(`pwsh`)向けです。 - -```powershell -$headers = @{ "X-Api-Key" = "pfm_..."; "Idempotency-Key" = "orders-20261123" } -Invoke-RestMethod -Method Post -Headers $headers -ContentType "text/csv; charset=utf-8" -InFile .\manufacturing-orders.csv -Uri http://localhost:5000/api/integration/v1/actuals/manufacturing-orders -``` - -```bash -curl -H "X-Api-Key: pfm_..." -H "Idempotency-Key: orders-20261123" -H "Content-Type: text/csv" --data-binary @manufacturing-orders.csv http://localhost:5000/api/integration/v1/actuals/manufacturing-orders -``` - -- 取り込めたら **200**、1行でもエラーがあれば **422** で、何も反映しません。どちらも応答の本文に、件数と行番号付きのエラーが入ります(PowerShell 7 では `-SkipHttpErrorCheck` を付けると 422 の本文も受け取れます)。 -- 取込の権限は、キーに紐づく利用者のロールで画面と同じように判定します(権限が無ければ 403)。 - -### 送り直しても二重に登録しない(Idempotency-Key) - -実績CSVは**常に新規登録**なので、通信が切れたあとに同じ CSV を送り直すと、二重に登録されることがあります。 -これを防ぐには、送る内容ごとに決めた値(例:指図の出力日時と連番、UUID)を `Idempotency-Key` ヘッダに付けます。 - -- 同じキー・同じ内容で送り直すと、**取り込み直さずに前回の応答を返します**(応答のヘッダに `Idempotent-Replayed: true` が付きます)。 -- 同じキーで内容が違う要求は 409 になります。新しい内容には新しいキーを付けてください。 -- キーは24時間覚えています。キーは APIキーごとに別に扱います。 - -### 生産実績を読む(前回の続きから) - -`afterId` に前回の `nextAfterId` を渡すと、その後に記録された実績だけが返ります。`hasMore` が true の間は続けて読みます。 -最後の `nextAfterId` を保存しておけば、次の実行は続きから始まります。 - -```powershell -$headers = @{ "X-Api-Key" = "pfm_..." } -$after = if (Test-Path .\last-id.txt) { Get-Content .\last-id.txt } else { 0 } -do { - $page = Invoke-RestMethod -Headers $headers -Uri "http://localhost:5000/api/integration/v1/production-results?afterId=$after" - $page.items | Export-Csv .\production-results.csv -Append -Encoding utf8 - $after = $page.nextAfterId -} while ($page.hasMore) -Set-Content .\last-id.txt $after -``` - -- 実績の数量は、訂正された後の今の値です。既に読んだ実績が後から訂正されたことは、`production-result-corrections` を同じように続きから読むと分かります。 -- 承認前の実績も返します(`approvedAt` が空)。取り消した指図の実績も、現物のロットが残るので返します(`workOrderStatus` で分かります)。 - -### 版を上げても連携が動き続けるための約束 - -- v1(`/api/integration/v1`)の中では、**項目や口を足すだけ**で、消したり名前や意味を変えたりしません。変えるときは v2 を作ります。 -- CSV の列も同じです。列は消さず、必須の列も増やしません(新しい列は、省けば今までどおりに動きます)。列の名前を変えるときは、以前の名前でも読めるようにします。 -- 応答に知らない項目が増えても、読み飛ばすように連携を作ってください。 - -## 設備イベントの受信 {#equipment-events} - -設備の稼働状態(稼働・停止・段取り・故障・アイドル)を、設備から自動で記録する仕組みです。 -**MES は PLC と直接は通信しません。** PLC の状態はゲートウェイ(Node-RED など)が読み、状態が変わったときに MES の連携API へ送ります。 -MES は届いた状態の変化を、設備ごとに時刻の順に並べて**稼働履歴の区間**(開始〜終了)に組み立てます。 - -``` -設備・PLC ──(OPC UA・MC プロトコル・Modbus など)──▶ ゲートウェイ ──(HTTP・APIキー)──▶ MES - (Node-RED など) POST /api/integration/v1/equipment-events -``` - -### 準備する - -1. 設備マスタ(マスタ管理の **設備(BOE)** タブ)で、対象の設備に **設備イベントで稼働状態を収集する** を付けます。 - 付けた設備には、稼働実績を手入力や実績CSVで登録できなくなります(手と自動で同じ時間を二重に数えないため)。停止原因の追記はできます。 -2. ゲートウェイ用の利用者を作り、[APIキー](#api-keys) を発行します。受信はロールを問いません。 -3. 必要なら、アラーム番号を停止原因に置き換える **停止原因の対応表**(マスタ管理)を登録します。 - -### 送る形 - -状態が変わるたびに1件を作り、ためておいてまとめて送ります(1回に1,000件まで)。 - -```json -{ - "events": [ - { "equipmentCode": "EQ-06", "eventId": "EQ-06-1732323600000-1", "occurredAt": "2026-11-23T09:00:00+09:00", "state": "Running" }, - { "equipmentCode": "EQ-06", "eventId": "EQ-06-1732324200000-2", "occurredAt": "2026-11-23T09:10:00+09:00", "state": "Stopped", "alarmCode": "A-101" } - ] -} -``` - -| 項目 | 内容 | -|---|---| -| `equipmentCode` | 設備の資産番号 | -| `eventId` | ゲートウェイが振る一意のID(設備ごとに一意。100文字まで)。**送り直しても同じ値**にする | -| `occurredAt` | 設備で状態が変わった時刻(`+09:00` などのオフセット付き) | -| `state` | `Running`(稼働)/`Stopped`(停止)/`Setup`(段取り)/`Failure`(故障)/`Idle`(アイドル)/`Off`(電源断・通信断) | -| `alarmCode` | 任意。停止・故障のときのアラーム番号(停止原因の対応表で原因を引く) | -| `workOrderNo` + `operationSeq` | 任意。処理中の作業指示(指図番号と工程順序の組) | -| `note` | 任意。備考 | - -```powershell -$headers = @{ "X-Api-Key" = "pfm_..." } -$body = @{ events = @(@{ equipmentCode = "EQ-06"; eventId = "test-1"; occurredAt = (Get-Date).ToString("o"); state = "Running" }) } | ConvertTo-Json -Depth 4 -Invoke-RestMethod -Method Post -Headers $headers -ContentType "application/json" -Body $body -Uri http://localhost:5000/api/integration/v1/equipment-events -``` - -### 届いた後の扱い - -- 新しい状態が届くと、開いている区間を閉じて次の区間を開きます。同じ状態が続けて届いても区間は変わりません。`Off` は区間を閉じるだけです。 -- 1回に送った中で時刻が前後していても、時刻の順に並べ直して反映します。 -- **同じ `eventId` を送り直すと「重複」になり、二重に記録されません。** 通信が切れたら、ためた分をそのまま送り直してください。 -- **最後に反映した時刻より前のイベントは「遅着」として拒否します。** 過去の区間は組み直しません。設備とゲートウェイの時計は NTP で揃えてください。サーバーの時刻より先すぎる時刻(既定300秒を超える)も拒否します。 -- 応答は 200 で、1件ごとの結果(`Accepted` 採用/`Duplicate` 重複/`Rejected` 拒否と理由)が入ります。全部が拒否でも 200 です。拒否した `eventId` は、直して送り直すと判定し直します。 -- 停止・故障の区間は、アラーム番号から停止原因の対応表で原因を引きます。引けなければ**原因未入力**のまま記録され、保全管理の稼働監視タブで後から入れられます。 -- 作業指示は、指定があればそれに紐づけます。指定が無ければ、**その設備を割り当てた着手中の作業指示がちょうど1件のときだけ**紐づけます。 - -受信の様子は、保全管理の稼働監視タブの **設備の今の状態** で見られます。受信が一定時間(既定10分)途絶えると、その設備に「受信が途絶えています」と出ます(ゲートウェイが止まったことに気づけます)。 - -### サンプルで試す(Docker) - -`compose.yaml` には、MQTT ブローカー(Eclipse Mosquitto)と Node-RED のゲートウェイを一緒に起動する `equipment` プロファイルがあります。 -Node-RED には、数秒ごとに状態を変える**模擬設備**と、MQTT を受けて MES へまとめて送るフローが入っています(`samples/equipment-gateway`)。 - -1. リポジトリの直下で `docker compose --profile equipment up -d` を実行します。 -2. MES(http://localhost:8080)にサンプルのマスタを取り込みます。`EQ-06` が設備イベントで収集する設備になっています。 -3. APIキーを発行し、リポジトリの直下の `.env` に `MES_API_KEY=pfm_...` と書いて、もう一度 `docker compose --profile equipment up -d` を実行します。 -4. 稼働監視タブで、`EQ-06` の今の状態と稼働履歴が増えていくのを確かめます。Node-RED(http://localhost:1880)の「結果を見る」ノードに、採用・重複・拒否の件数が出ます。 - -自分の設備に合わせるときは、Node-RED の「状態を変える」ノードを、PLC から状態を読むノード(OPC UA・MC プロトコル・Modbus など)に置き換えます。 -サンプルの MQTT ブローカーは認証も暗号化もしない最小構成です。本番ではパスワードと TLS を設定してください。 - -## Webhook(MES からの通知) {#webhooks} - -不適合の起票・設備の停止・ロットの保留のように**すぐ知りたい出来事**が起きたとき、MES から登録した URL へ HTTP で知らせる仕組みです。 -班長のチャットへの通知や、完成をきっかけにした次の処理に使えます。 -定期に取りに来れば足りる相手(ERP の在庫・原価など)は、[連携API](#integration-api) の生産実績の読み出しで足ります。 - -通知は**薄く**作っています。種類・発生日時・対象の番号と、人が読める1文の要約だけを送ります。 -通知は「読みに行くきっかけ」です。正しい今の値は連携API で取りに行ってください(通知が届かなかった・順が入れ替わったときも、それで追いつけます)。 - -``` -MES ──(POST・署名付き)──▶ 受け側(Node-RED・社内のスクリプトなど)──▶ チャット・表示盤・ERP -``` - -### 送信先を登録する - -1. システム管理者が、メニューの「管理」→「Webhook」の **送信先** タブで、用途・送信先の URL・通知するイベントを選んで **登録** を押します。 -2. 表示された **署名の秘密の値**(`whsec_` で始まる文字列)を、受け側の設定に写します。**この値は今しか表示できません。** 失くしたら **秘密の値を再発行** を押します(古い値はすぐに使えなくなるので、受け側の設定も直します)。 -3. **テスト送信** を押して、受け側に届くか確かめます。結果はその場で出ます(テスト送信は失敗しても送り直しません)。 - -- URL は `http://` も使えます(工場の中のネットワーク向け)。`http://` の送信先には本文が暗号化されずに流れるので、社外へ送るときは `https://` にしてください。 -- 利用者名・パスワードを含む URL は登録できません(一覧と監査ログに URL がそのまま出るため)。受け側は署名で送り手を確かめます。 -- 送るのを止めるだけなら、**有効** を外します。削除すると、まだ送っていない通知と送信の記録も消えます。 - -### 通知するイベント - -| 種類 | いつ | 主な項目 | -|---|---|---| -| `production-result.created` | 生産実績を記録した(画面・実績CSV・連携API のどれでも) | 指図番号・作業指示番号・工程順序・品目コード・良品/不良数・産出ロット | -| `production-result.corrected` | 生産実績を訂正した | 訂正した実績の `productionResultId`・訂正前後の数・理由 | -| `work-order.status-changed` | 作業指示の状態が変わった(差立・着手・完了・承認・取消) | 作業指示番号・変更前/後の状態 | -| `manufacturing-order.status-changed` | 製造指図が完了・取消になった | 指図番号・指図区分・変更前/後の状態 | -| `lot.status-changed` | ロットの在庫ステータスが変わった(保留・解除・検査待ちなど) | ロット番号・品目コード・変更前/後・契機・理由 | -| `nonconformance.created` | 不適合を起票した(検査の不合格からの自動起票を含む) | 不適合番号・発生源・ロット番号・品目コード | -| `equipment.stopped` | 設備が停止・故障の区間に入った(手入力・実績CSV・[設備イベント](#equipment-events) のどれでも) | 資産番号・状態・停止原因・アラーム番号 | - -区分・状態は英語の名前(`OnHold` など)で送ります(表示言語で変わらないように)。内部のIDは送らず、番号・コードで指します。 -要約(`summary`)は日本語です。 - -### 送る形 - -```json -{ - "id": "c548bec2-5e89-4210-ba22-2110c0325f09", - "sequence": 7, - "type": "equipment.stopped", - "version": 1, - "occurredAt": "2026-11-23T11:02:01+00:00", - "summary": "設備 EQ-01 が「停止」になりました(材料切れ)。", - "data": { "equipmentAssetNo": "EQ-01", "status": "Stopped", "startedAt": "2026-11-23T10:32:00+00:00", "endedAt": null, - "stopCause": "材料切れ", "alarmCode": null, "source": "Manual", "workOrderNo": null } -} -``` - -| 項目・ヘッダ | 内容 | -|---|---| -| `id` | 通知の一意のID。**送り直しても同じ値**(受け側はこれで重複を捨てる) | -| `sequence` | 種類をまたいで増える番号(連番とは限らない) | -| `data` | 種類ごとの中身(上の表)。項目の一覧は [仕様書(OpenAPI)](#integration-api) の `webhooks` 節にある | -| `X-Mes-Event` | 種類(本文の `type` と同じ) | -| `X-Mes-Delivery` | 送信のID(送り直しても同じ) | -| `X-Mes-Timestamp` | 送った時刻(Unix 秒) | -| `X-Mes-Signature` | 署名。`sha256=` に続けて、秘密の値を鍵にした「`X-Mes-Timestamp` の値 `.` 本文」の HMAC-SHA256 を小文字の16進で書いたもの | - -### 受け側で確かめること - -1. **署名を確かめます。** 受け取った本文のバイト列そのもので計算します。JSON に読み替えてから文字列に戻すと、数値の書き方などが変わって合いません。 -2. **時刻のずれを確かめます。** `X-Mes-Timestamp` が5分以上ずれていたら受け付けません(古い要求の送り直しを弾くため)。MES と受け側の時計は NTP で揃えてください。 -3. **すぐに 2xx を返します。** MES は応答を既定10秒まで待ち、待ち切れなければ送り直します。重い処理は応答の後に回してください。 -4. **同じ `id` の2回目以降は捨てます。** 通知は少なくとも1回届きますが、同じ通知が2回届くことがあります。順序も保証しません。 - -### 届かなかったとき - -- 送信先に繋がらない・待ち切れない・`5xx`・`408`・`429` のときは、間隔を空けて送り直します(1分・5分・30分・2時間・6時間・12時間・24時間。既定で8回まで)。 -- それ以外の `4xx` と `3xx` は、送り直しても同じなので1回で止めます(リダイレクトは追いません)。 -- 止まった通知は、**送信の記録** タブで受け側を直してから **再送** を押します。通知の `id` は変わらないので、届いていた受け側は重複として捨てられます。 -- 送り直しを待っている・止まった通知がある送信先は、**送信先** タブの「送れていない送信」と、システム管理者の **ダッシュボード** の上部に出ます。送信先は自動では止めません。 -- 送信の記録は既定30日残します。 -- データ保存先の `dataprotection-keys`(秘密の値を暗号化する鍵)を失うと、秘密の値を復号できず、その送信先の通知は止まります。秘密の値を再発行し、受け側の設定を直してから再送してください([バックアップ](#backup) で一緒に退避します)。 - -### サンプルで試す - -- **Node-RED(Docker)**:`equipment` プロファイルの Node-RED([設備イベントのサンプル](#equipment-events))に、通知を受けて署名を確かめ、チャット(Slack・Teams)の形にして転送する「Webhook の受け側」タブがあります。 - 1. `docker compose --profile equipment up -d` で起動し、送信先に `http://node-red:1880/mes-webhook` を登録します。 - 2. 秘密の値をリポジトリの直下の `.env` に `MES_WEBHOOK_SECRET=whsec_...` と書き、もう一度 `docker compose --profile equipment up -d` を実行します。 - 3. **テスト送信** を押すと、Node-RED(http://localhost:1880)のデバッグ欄に「受けた通知」と「チャットに届いた形」が出ます。 - 転送先の既定はフローの中の模擬で、実際のチャットには送りません。送るときは `.env` に `CHAT_WEBHOOK_URL`(Slack の Incoming Webhook、または Teams のワークフローの「Webhook 要求を受信したとき」の URL)と、Teams なら `CHAT_KIND=teams` を書きます。 -- **スクリプト**:`samples/webhook` に Python(`receive_mes_webhook.py`)と PowerShell(`Receive-MesWebhook.ps1`)の最小の受け側があります。処理を書き足す場所は README を見てください。 - -### 版を上げても受け側が動き続けるための約束 - -- 本文の項目は消しません。名前と型も変えません。値が必ずあった項目を、値の無いことがある項目にはしません。 -- 項目・種類・区分の値は増えることがあります。受け側は知らない項目を読み飛ばすようにしてください。 -- 形を変える必要があるときは、別の種類(v2)として足します。 - -## セキュリティ - -
-

アプリ自身はHTTPSを強制しません。 LAN運用では、リバースプロキシ -(IIS / nginx)でHTTPSを終端してください(HTTPSで運用する)。

-

あわせて、カメラによるバーコード読み取りは localhost 以外ではHTTPSが必須です。 -HTTPのままではカメラが使えません(USBリーダーと手入力はHTTPでも動作します)。

-
- -- 認証は ASP.NET Core Identity + JWT です。 -- 実績訂正・検査訂正・マスタ変更・在庫調整などは監査ログに記録されます(下記)。 -- パスワード要件は8文字以上、英小文字と数字を含むことです。 - -### HTTPSで運用する {#https} - -ブラウザからのHTTPSはリバースプロキシ(IIS / nginx)が受け、アプリへはHTTPで中継します。 -証明書を持つのはプロキシだけです。 - -``` -端末のブラウザ ──HTTPS──▶ IIS / nginx(証明書)──HTTP──▶ MesApp(127.0.0.1:5000) -``` - -**1. 証明書を用意する。** 社内LANでは公的な証明書を取れないので、社内CAか -[mkcert](https://github.com/FiloSottile/mkcert) で発行します。mkcert の場合、サーバーで次を実行します。 - -```bash -mkcert -install -mkcert mes.example.local 192.168.10.5 -``` - -端末から使う名前(ホスト名・IP)をすべて並べます。できた `mes.example.local+1.pem`(証明書)と -`mes.example.local+1-key.pem`(秘密鍵)をプロキシに設定します。 - -**2. CA証明書を端末に配る。** `mkcert -CAROOT` で表示されるフォルダの `rootCA.pem` を -`rootCA.crt` に名前を変えて各端末へ配り、「信頼されたルート証明機関」に入れます -(端末で `certutil -addstore -f Root rootCA.crt`、台数が多ければグループポリシーで配布)。 -同じフォルダの `rootCA-key.pem` は**配らないでください**(持っている人は任意の証明書を発行できます)。 - -**3. アプリをプロキシからだけ届くように起動する。** HTTPで直接つながれないよう、 -ループバックでだけ待ち受けます(アプリはHTTPからHTTPSへのリダイレクトをしません)。 - -```bash -dotnet publish/MesApp.Api.dll --urls http://127.0.0.1:5000 -``` - -**4. プロキシを設定する。** 接続元IPとスキームを `X-Forwarded-For` / `X-Forwarded-Proto` で渡します。 - -nginx の例: - -```nginx -server { - listen 443 ssl; - server_name mes.example.local; - ssl_certificate mes.example.local+1.pem; - ssl_certificate_key mes.example.local+1-key.pem; - client_max_body_size 50m; # CSV・ZIPの一括取込のため - - location / { - proxy_pass http://127.0.0.1:5000; - proxy_set_header Host $host; - proxy_set_header X-Forwarded-For $remote_addr; - proxy_set_header X-Forwarded-Proto $scheme; - } -} -``` - -IIS の場合は URL Rewrite と Application Request Routing(ARR)を入れ、ARRのプロキシを有効にします。 -`X-Forwarded-For` はARRが付けます。`X-Forwarded-Proto` はサーバー変数 `HTTP_X_FORWARDED_PROTO` を -「許可されたサーバー変数」に追加したうえで、書き換え規則で付けます(`web.config` の例)。 - -```xml - - - - - - - - - - - -``` - -**5. プロキシを信頼する設定を入れる。** アプリは、ここで指定した接続元から来た転送ヘッダだけを読みます。 -プロキシが同じPCなら次のとおりです(別のPCならそのIP)。 - -```powershell -$env:ReverseProxy__KnownProxies__0="127.0.0.1" -``` - -
-

この設定が無いと、転送ヘッダは読まれません。 HTTPSでつながっていても、 -リフレッシュトークンのCookieに Secure が付かず、監査ログの接続元IPがすべてプロキシのIPになります。 -未設定のときに読まないのは、HTTPで直接つないだ端末がヘッダを偽装して接続元を詐称できないようにするためです。

-
- -**確認:** 端末からHTTPSでログインし、監査ログの「ログイン」の接続元IPが端末のIPになっていれば完了です。 -`127.0.0.1` のままなら手順5の設定が効いていません。 - -## 監査ログ {#audit-log} - -「誰が・いつ・何を変更したか」の記録です。**メニューの「監査ログ」**から確認できます -(システム管理者専用。他のロールにはメニュー自体が表示されません)。 - -### 記録される操作 - -| 分類 | 主な操作 | -|---|---| -| Setup | 初期管理者の作成 | -| Auth | ログイン、ログイン失敗、アカウントロック、ログアウト、パスワード変更 | -| User | ユーザーの作成・変更、パスワードリセット、スキル資格の付与 | -| Master | マスタの登録・変更・無効化、CSV取込 | -| Production | 製造指図の登録・承認・取消・工程展開、差立 | -| Execution | 着手、実績登録、**実績訂正**、作業時間、製造条件データ、完了承認 | -| Inventory | 受入、移動、**数量調整**、ステータス変更、分割・統合・振替、廃棄、ピッキング、出荷、棚卸、**取消** | -| Quality | 検査実績の登録・**訂正**・判定・承認、不適合の起票・対応指示・承認、出荷判定 | -| Maintenance | 保全計画・保全指示・保全実績、保全手順書の管理 | -| Equipment | 設備稼働の記録、治工具の使用実績 | - -数量調整・ステータス変更・訂正・取消など、**変更前後をたどりたい操作は「詳細」列に変更前・変更後・理由**が -入ります。それ以外は要約が入ります。 - -### 絞り込み - -期間・分類/操作・対象(種別とID)で絞り込めます。 -たとえば「対象の種別」に `Lot`、「対象のID」にロットの内部IDを入れると、 -そのロットに対して行われた操作だけを並べられます。 - -
-

期間は記録日(サーバーの日付)で絞り込みます。 -一覧の日時はブラウザの時刻で表示されるため、サーバーとブラウザのタイムゾーンが異なる環境では -日をまたぐ時間帯でずれて見えることがあります。

-
- -### 削除・改ざんについて - -- 個々の記録は**画面からもAPIからも変更・削除できません**。記録が増えるだけです。 -- **保持期間は5年**です(`Audit__RetentionYears` で変更できます)。**自動削除は行いません**(消してよいかは業務判断のため)。 -- 容量が問題になったときだけ、**保持期間を過ぎた分をまとめて削除**できます(下記)。 - -### 古い記録の一括削除 - -保持期間を過ぎた記録を整理する操作です。**監査ログ画面の一番下**にあります。 -先に下記のバックアップを取得してください。 - -
-
    -
  1. 「この日まで削除」に日付を、「理由」に削除する理由を入力します(指定日を含めてそれ以前が対象です)。
  2. -
  3. 削除件数を確認を押します。この時点ではまだ何も消えません。対象件数が表示されます。
  4. -
  5. 件数を確かめて 「N 件を削除する」 を押すと削除されます。
  6. -
-
- -日付か理由を変更すると件数の確認はリセットされ、もう一度確認し直しになります -(確認した内容と実際に消す内容がずれないようにするためです)。 - -APIから実行する場合は次のとおりです。`dryRun=true` のあいだは件数を返すだけでDBには触りません。 - -``` -POST /api/audit-logs/purge?dryRun=true -{ "to": "2020-12-31", "reason": "容量削減のため" } -``` - -
-

保持期間の内側は削除できません。 保持期間より新しい日付を指定すると拒否されます -(直前の操作の記録を消して隠せてしまうと、監査ログが証跡として成り立たないためです)。

-

理由の入力は必須で、削除したこと自体(期間・件数・理由・実行者)が監査ログに残ります。 -この記録は削除の後に書かれるため、同じ操作では消えません。

-
- -## PostgreSQL / SQL Server を使う {#database} - -既定の SQLite は追加インストールが要らず、数十端末規模までならそのまま運用できます。 -同時に書き込む端末が多い、データ量が大きい、既存のDBサーバーでまとめて管理したい、といった場合は -PostgreSQL または SQL Server に切り替えます。 - -1. DBサーバーに**空のデータベース**と接続用のログインを作ります。 - ログインには、そのデータベースでテーブルを作成・変更できる権限を与えます(起動時にスキーマを作成・更新するため)。 -2. `Database__Provider` と `Database__ConnectionString` を設定して起動します。 - -```powershell -# PostgreSQL -$env:Database__Provider="PostgreSql"; $env:Database__ConnectionString="Host=db;Database=mesapp;Username=mesapp;Password=..." -# SQL Server -$env:Database__Provider="SqlServer"; $env:Database__ConnectionString="Server=db;Database=mesapp;User Id=mesapp;Password=...;TrustServerCertificate=True" -``` - -3. 起動時にテーブルが作られます。ブラウザで開くと、SQLiteのときと同じく初期セットアップの案内が表示されます。 - 以降のバージョンアップでも、起動時に差分が自動適用されます。 - -
-

既存のSQLiteのデータは移りません。 切り替えると空のデータベースから始まります。 -運用を始める前にどのデータベースを使うかを決めてください。設定をSQLiteに戻すと、元の mesapp.db がそのまま使われます(両者のデータは別々です)。

-
- -### SQLite との違い - -| 項目 | 違い | -|---|---| -| コードの大文字・小文字 | SQL Server の既定の照合順序では区別しません(`ABC` と `abc` は同じコードとして重複扱いになり、検索も区別しません)。SQLite・PostgreSQL は区別します | -| 日時 | PostgreSQL ではUTCで保存されます。同じ時点を指すため、画面表示・集計・CSVの結果は変わりません | -| 小数 | 小数点以下6桁まで保存します(SQLite と同じ値の見え方になるよう末尾のゼロは落とします) | -| デスクトップ版 | SQLite で使う前提です(1台のPCで完結させる構成のため) | - -### 起動しないとき - -| 症状 | 対処 | -|---|---| -| 「不明なDBプロバイダー」で止まる | `Database__Provider` は `Sqlite` / `PostgreSql` / `SqlServer` のいずれかを、大文字・小文字も含めてそのとおりに書いてください | -| 接続のタイムアウト・認証エラーで止まる | 接続文字列のホスト名・ポート・ユーザー名・パスワード、DBサーバー側のファイアウォール、SQL Server では TCP/IP 接続が有効かを確認してください | -| SQL Server で証明書のエラーになる | 社内の自己署名証明書のサーバーなら接続文字列に `TrustServerCertificate=True` を付けるか、信頼された証明書をサーバーに設定してください | -| 権限エラー(テーブルを作成できない)で止まる | 接続ログインに、対象データベースでのテーブル作成・変更の権限を与えてください | - -## バックアップ {#backup} - -### SQLite - -
-

稼働中のDBファイルを単純コピーしないでください。 -SQLiteはWALモードで動作するため、コピーしたファイルが壊れる可能性があります。

-
- -安全な方法は次の2つです。 - -1. サーバーを停止してから `mesapp.db` をコピーする -2. 稼働中なら SQLite の `VACUUM INTO` でバックアップファイルを作る - -Docker の場合は、コンテナを止めてからボリュームごと退避します(署名鍵と、Webhook の秘密の値を暗号化する鍵も一緒に残ります)。 -ボリューム名は `docker volume ls` で確認してください(compose では `<フォルダ名>_mesapp-data`)。 - -```bash -docker compose stop -docker run --rm -v <ボリューム名>:/data -v "$PWD":/backup alpine tar czf /backup/mesapp-data.tgz -C /data . -docker compose start -``` - -`mesapp.db*`(`-wal` / `-shm` を含む)をすべて削除して再起動すると、初期状態に戻ります。 -検証環境をリセットしたいときに使えます。 - -### PostgreSQL / SQL Server - -各データベースの標準の手段でバックアップします(稼働中でも取得できます)。 - -- PostgreSQL: `pg_dump -Fc -d mesapp -f mesapp.dump`(復元は `pg_restore`) -- SQL Server: `BACKUP DATABASE mesapp TO DISK = N'...\mesapp.bak'`(または SQL Server Management Studio のバックアップ) - -初期状態に戻すには、データベースを削除して空のデータベースを作り直し、再起動します。 - -### データ保存先の鍵 - -データベースとは別に、データ保存先の `jwt-signing.key`(ログインの署名鍵)と `dataprotection-keys` フォルダ([Webhook](#webhooks) の秘密の値を暗号化する鍵)も退避してください。 -`dataprotection-keys` を失うと、戻したデータベースにある Webhook の秘密の値を復号できず、送信先ごとに秘密の値を再発行することになります。 - ## 制限事項 | 項目 | 状況 | |---|---| -| PostgreSQL / SQL Server | 対応([PostgreSQL / SQL Server を使う](#database))。既存のSQLiteデータを移す機能は無し | +| PostgreSQL / SQL Server | 対応([PostgreSQL / SQL Server を使う](database.html#database))。既存のSQLiteデータを移す機能は無し | | Docker化・Zip配布 | 対応([配布と起動](#配布と起動)) | -| HTTPS | アプリ側では強制しない(リバースプロキシで終端。[HTTPSで運用する](#https)) | +| HTTPS | アプリ側では強制しない(リバースプロキシで終端。[HTTPSで運用する](security.html#https)) | | 設備・秤量機からの自動データ収集 | 未対応(手入力) | | EDI / ASN連携 | 未対応 | | シリアル番号(個体)単位の追跡 | 未対応(ロット単位のみ) | diff --git a/docs/privacy.md b/docs/privacy.md index 6a3a948..06ac1bf 100644 --- a/docs/privacy.md +++ b/docs/privacy.md @@ -4,8 +4,8 @@ title: プライバシーポリシー nav_url: privacy.html description: Parallel Factory MES が扱うデータと、その保存先・送信の有無についての説明です。 lead: Parallel Factory MES(以下「本アプリ」)が扱うデータについての説明です。Microsoft Store 版(単独PC完結のデスクトップアプリ)を主な対象とし、サーバーに配置して使う場合の扱いも併せて記載します。 -prev_url: operations.html -prev_title: 管理者向け運用 +prev_url: troubleshooting.html +prev_title: 困ったときは --- 最終更新日:2026年9月21日 @@ -43,7 +43,7 @@ prev_title: 管理者向け運用 本アプリはアプリケーションサーバーを**PC内部(ループバックアドレス `127.0.0.1`)でのみ**起動します。この通信はPCの外に出ず、同じネットワーク上の他の機器からも接続できません。 -**アプリをアンインストールすると、上記フォルダーごとデータは削除されます。** 残したいデータがある場合は、アンインストール前にバックアップ([管理者向け運用](operations.html)を参照)を取得してください。 +**アプリをアンインストールすると、上記フォルダーごとデータは削除されます。** 残したいデータがある場合は、アンインストール前にバックアップ([データベースとバックアップ](database.html#backup)を参照)を取得してください。 ### サーバーに配置して使う場合 diff --git a/docs/reference.md b/docs/reference.md index 16766e5..204711e 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -3,8 +3,8 @@ layout: default title: リファレンス nav_url: reference.html lead: ステータスの一覧、番号の採番規則、業務日付、用語集です。運用中に迷ったときの参照用です。 -prev_url: roles.html -prev_title: ロールと権限 +prev_url: database.html +prev_title: データベースとバックアップ next_url: troubleshooting.html next_title: 困ったときは --- @@ -102,7 +102,7 @@ next_title: 困ったときは - 例:5月2日 午前3時の実績 → 製造日は「5月1日」 夜勤の日跨ぎ実績を1つの製造日にまとめるための仕組みです。 -境界時刻は設定で変更できます([管理者向け運用](operations.html#settings))。 +境界時刻は設定で変更できます([サーバーの配置と設定](operations.html#settings))。 業務日付が使われるのは、各種番号の採番と、品質分析の期間指定です。 @@ -121,7 +121,7 @@ next_title: 困ったときは | 出荷には出荷判定が必要 | 承認済みの「可」または「特採」判定がないと出荷実行できません | | 承認は単段階 | 各種承認は1回の承認操作で確定します(多段階ワークフローはありません) | | 訂正には理由が必要 | 数量調整・検査実績訂正には理由の入力が必須で、監査ログに記録されます | -| 記録は消せない | 監査ログは追加されるだけで、個々の記録は変更・削除できません。保持期間(既定5年)を過ぎた分だけ、管理者が理由付きで一括削除できます([監査ログ](operations.html#audit-log)) | +| 記録は消せない | 監査ログは追加されるだけで、個々の記録は変更・削除できません。保持期間(既定5年)を過ぎた分だけ、管理者が理由付きで一括削除できます([監査ログ](security.html#audit-log)) | --- diff --git a/docs/reports.md b/docs/reports.md index 6d42e4e..849a8d6 100644 --- a/docs/reports.md +++ b/docs/reports.md @@ -59,7 +59,7 @@ next_title: ロールと権限 ブラウザのセキュリティ制約によるもので、システム側では回避できません。

HTTPでLAN運用している場合は、USBバーコードリーダーの利用を推奨します。 カメラを使いたい場合は、リバースプロキシ(IIS / nginx)でHTTPS化してください -(HTTPSで運用する)。

+(HTTPSで運用する)。

カメラが使えない環境では、次のメッセージが表示されます。 diff --git a/docs/roles.md b/docs/roles.md index 1533dd8..36a03bc 100644 --- a/docs/roles.md +++ b/docs/roles.md @@ -5,8 +5,8 @@ nav_url: roles.html lead: 7つのロールと、それぞれができる操作の対応表です。ユーザーには複数のロールを付与できます。 prev_url: reports.html prev_title: 帳票・ラベル・スキャン -next_url: reference.html -next_title: リファレンス +next_url: operations.html +next_title: サーバーの配置と設定 --- ## ロールの一覧 diff --git a/docs/search.json b/docs/search.json new file mode 100644 index 0000000..51ca333 --- /dev/null +++ b/docs/search.json @@ -0,0 +1,5 @@ +--- +# ガイド内検索の索引(日本語版)。中身は _includes/search-index.json +layout: null +--- +{% include search-index.json dir="/" %} diff --git a/docs/security.md b/docs/security.md new file mode 100644 index 0000000..e62b81d --- /dev/null +++ b/docs/security.md @@ -0,0 +1,181 @@ +--- +layout: default +title: セキュリティと監査ログ +nav_url: security.html +lead: "認証とHTTPSでの運用、監査ログの見方と古い記録の削除です。" +prev_url: integration.html +prev_title: 外部連携 +next_url: database.html +next_title: データベースとバックアップ +--- + +## セキュリティ + +
+

アプリ自身はHTTPSを強制しません。 LAN運用では、リバースプロキシ +(IIS / nginx)でHTTPSを終端してください(HTTPSで運用する)。

+

あわせて、カメラによるバーコード読み取りは localhost 以外ではHTTPSが必須です。 +HTTPのままではカメラが使えません(USBリーダーと手入力はHTTPでも動作します)。

+
+ +- 認証は ASP.NET Core Identity + JWT です。 +- 実績訂正・検査訂正・マスタ変更・在庫調整などは監査ログに記録されます(下記)。 +- パスワード要件は8文字以上、英小文字と数字を含むことです。 + +### HTTPSで運用する {#https} + +ブラウザからのHTTPSはリバースプロキシ(IIS / nginx)が受け、アプリへはHTTPで中継します。 +証明書を持つのはプロキシだけです。 + +``` +端末のブラウザ ──HTTPS──▶ IIS / nginx(証明書)──HTTP──▶ MesApp(127.0.0.1:5000) +``` + +**1. 証明書を用意する。** 社内LANでは公的な証明書を取れないので、社内CAか +[mkcert](https://github.com/FiloSottile/mkcert) で発行します。mkcert の場合、サーバーで次を実行します。 + +```bash +mkcert -install +mkcert mes.example.local 192.168.10.5 +``` + +端末から使う名前(ホスト名・IP)をすべて並べます。できた `mes.example.local+1.pem`(証明書)と +`mes.example.local+1-key.pem`(秘密鍵)をプロキシに設定します。 + +**2. CA証明書を端末に配る。** `mkcert -CAROOT` で表示されるフォルダの `rootCA.pem` を +`rootCA.crt` に名前を変えて各端末へ配り、「信頼されたルート証明機関」に入れます +(端末で `certutil -addstore -f Root rootCA.crt`、台数が多ければグループポリシーで配布)。 +同じフォルダの `rootCA-key.pem` は**配らないでください**(持っている人は任意の証明書を発行できます)。 + +**3. アプリをプロキシからだけ届くように起動する。** HTTPで直接つながれないよう、 +ループバックでだけ待ち受けます(アプリはHTTPからHTTPSへのリダイレクトをしません)。 + +```bash +dotnet publish/MesApp.Api.dll --urls http://127.0.0.1:5000 +``` + +**4. プロキシを設定する。** 接続元IPとスキームを `X-Forwarded-For` / `X-Forwarded-Proto` で渡します。 + +nginx の例: + +```nginx +server { + listen 443 ssl; + server_name mes.example.local; + ssl_certificate mes.example.local+1.pem; + ssl_certificate_key mes.example.local+1-key.pem; + client_max_body_size 50m; # CSV・ZIPの一括取込のため + + location / { + proxy_pass http://127.0.0.1:5000; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $remote_addr; + proxy_set_header X-Forwarded-Proto $scheme; + } +} +``` + +IIS の場合は URL Rewrite と Application Request Routing(ARR)を入れ、ARRのプロキシを有効にします。 +`X-Forwarded-For` はARRが付けます。`X-Forwarded-Proto` はサーバー変数 `HTTP_X_FORWARDED_PROTO` を +「許可されたサーバー変数」に追加したうえで、書き換え規則で付けます(`web.config` の例)。 + +```xml + + + + + + + + + + + +``` + +**5. プロキシを信頼する設定を入れる。** アプリは、ここで指定した接続元から来た転送ヘッダだけを読みます。 +プロキシが同じPCなら次のとおりです(別のPCならそのIP)。 + +```powershell +$env:ReverseProxy__KnownProxies__0="127.0.0.1" +``` + +
+

この設定が無いと、転送ヘッダは読まれません。 HTTPSでつながっていても、 +リフレッシュトークンのCookieに Secure が付かず、監査ログの接続元IPがすべてプロキシのIPになります。 +未設定のときに読まないのは、HTTPで直接つないだ端末がヘッダを偽装して接続元を詐称できないようにするためです。

+
+ +**確認:** 端末からHTTPSでログインし、監査ログの「ログイン」の接続元IPが端末のIPになっていれば完了です。 +`127.0.0.1` のままなら手順5の設定が効いていません。 + +## 監査ログ {#audit-log} + +「誰が・いつ・何を変更したか」の記録です。**メニューの「監査ログ」**から確認できます +(システム管理者専用。他のロールにはメニュー自体が表示されません)。 + +### 記録される操作 + +| 分類 | 主な操作 | +|---|---| +| Setup | 初期管理者の作成 | +| Auth | ログイン、ログイン失敗、アカウントロック、ログアウト、パスワード変更 | +| User | ユーザーの作成・変更、パスワードリセット、スキル資格の付与 | +| Master | マスタの登録・変更・無効化、CSV取込 | +| Production | 製造指図の登録・承認・取消・工程展開、差立 | +| Execution | 着手、実績登録、**実績訂正**、作業時間、製造条件データ、完了承認 | +| Inventory | 受入、移動、**数量調整**、ステータス変更、分割・統合・振替、廃棄、ピッキング、出荷、棚卸、**取消** | +| Quality | 検査実績の登録・**訂正**・判定・承認、不適合の起票・対応指示・承認、出荷判定 | +| Maintenance | 保全計画・保全指示・保全実績、保全手順書の管理 | +| Equipment | 設備稼働の記録、治工具の使用実績 | + +数量調整・ステータス変更・訂正・取消など、**変更前後をたどりたい操作は「詳細」列に変更前・変更後・理由**が +入ります。それ以外は要約が入ります。 + +### 絞り込み + +期間・分類/操作・対象(種別とID)で絞り込めます。 +たとえば「対象の種別」に `Lot`、「対象のID」にロットの内部IDを入れると、 +そのロットに対して行われた操作だけを並べられます。 + +
+

期間は記録日(サーバーの日付)で絞り込みます。 +一覧の日時はブラウザの時刻で表示されるため、サーバーとブラウザのタイムゾーンが異なる環境では +日をまたぐ時間帯でずれて見えることがあります。

+
+ +### 削除・改ざんについて + +- 個々の記録は**画面からもAPIからも変更・削除できません**。記録が増えるだけです。 +- **保持期間は5年**です(`Audit__RetentionYears` で変更できます)。**自動削除は行いません**(消してよいかは業務判断のため)。 +- 容量が問題になったときだけ、**保持期間を過ぎた分をまとめて削除**できます(下記)。 + +### 古い記録の一括削除 + +保持期間を過ぎた記録を整理する操作です。**監査ログ画面の一番下**にあります。 +先に下記のバックアップを取得してください。 + +
+
    +
  1. 「この日まで削除」に日付を、「理由」に削除する理由を入力します(指定日を含めてそれ以前が対象です)。
  2. +
  3. 削除件数を確認を押します。この時点ではまだ何も消えません。対象件数が表示されます。
  4. +
  5. 件数を確かめて 「N 件を削除する」 を押すと削除されます。
  6. +
+
+ +日付か理由を変更すると件数の確認はリセットされ、もう一度確認し直しになります +(確認した内容と実際に消す内容がずれないようにするためです)。 + +APIから実行する場合は次のとおりです。`dryRun=true` のあいだは件数を返すだけでDBには触りません。 + +``` +POST /api/audit-logs/purge?dryRun=true +{ "to": "2020-12-31", "reason": "容量削減のため" } +``` + +
+

保持期間の内側は削除できません。 保持期間より新しい日付を指定すると拒否されます +(直前の操作の記録を消して隠せてしまうと、監査ログが証跡として成り立たないためです)。

+

理由の入力は必須で、削除したこと自体(期間・件数・理由・実行者)が監査ログに残ります。 +この記録は削除の後に書かれるため、同じ操作では消えません。

+
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 01d0649..788f8f1 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -5,8 +5,8 @@ nav_url: troubleshooting.html lead: よくあるエラーメッセージと対処方法です。赤い帯で表示された文言から探してください。 prev_url: reference.html prev_title: リファレンス -next_url: operations.html -next_title: 管理者向け運用 +next_url: privacy.html +next_title: プライバシーポリシー --- ## ログイン・アカウント @@ -115,14 +115,14 @@ next_title: 管理者向け運用 | ZIP版の起動で「WindowsによってPCが保護されました」と出る | インターネットから入手したファイルに付く警告です。**詳細情報 → 実行** で起動できます。毎回出さないようにするには、展開する前にZIPファイルのプロパティで **許可する** にチェックを入れ、展開し直してください | | Linux で `./start.sh` が「許可がありません(Permission denied)」になる | ZIPは実行権限を保持しません。`sh start.sh` で起動してください(起動時に本体へ実行権限を付けます) | | ZIP版を起動するとすぐ閉じる/ポートが使用中と出る | 別のアプリがポート 5000 を使っています。`MESAPP_URLS` でポートを変えてから起動してください(例:`set MESAPP_URLS=http://0.0.0.0:5100`) | -| Docker でコンテナを作り直したらデータが消えた | `/data` をボリュームにしていません。`-v mesapp-data:/data` を付けて起動してください([管理者向け運用](operations.html#docker)) | +| Docker でコンテナを作り直したらデータが消えた | `/data` をボリュームにしていません。`-v mesapp-data:/data` を付けて起動してください([サーバーの配置と設定](operations.html#docker)) | ## 表示・接続 | 症状 | 対処 | |---|---| | 画面が「読み込み中...」のまま | サーバーが停止しているか、ネットワークが切断されています。管理者に確認してください | | 操作していると突然ログイン画面に戻る | アクセストークンの有効期限切れです。再ログインしてください。有効期限は設定で変更できます | -| 他のPCから接続できない | サーバー側のファイアウォールでポートの受信許可が必要です([管理者向け運用](operations.html)) | +| 他のPCから接続できない | サーバー側のファイアウォールでポートの受信許可が必要です([サーバーの配置と設定](operations.html)) | --- diff --git a/src/MesApp.Client.Web/Layout/MainLayout.razor b/src/MesApp.Client.Web/Layout/MainLayout.razor index b323ce0..498d529 100644 --- a/src/MesApp.Client.Web/Layout/MainLayout.razor +++ b/src/MesApp.Client.Web/Layout/MainLayout.razor @@ -7,7 +7,23 @@ @* スマホ幅ではサイドバーを上部に置き、メニューをボタンで開閉する(app.css の @media) *@