Domain Events Catalog — ERP/MES Commands · Events · Queries · Sagas
Hoàn thành

Domain Events Catalog
Commands · Events · Queries

Danh mục đầy đủ tất cả Commands, Domain Events, và Queries cho từng Bounded Context trong hệ thống ERP/MES — kèm payload schema và Kafka topic mapping.

Cập nhật: 22/07/2026
Modules: 22 Bounded Contexts
Kafka Topics: 15 topics
01 — Conventions

Naming Conventions & Chuẩn Event

LoạiPatternVí dụTense
CommandVerbNounStartProductionOrderHiện tại (imperative)
Domain EventNounVerbedProductionOrderStartedQuá khứ (past tense)
QueryGetNoun / ListNounGetProductionOrderByIdHiện tại
SagaNounSagaProductionOrderSagaNoun

Kafka Topic Mapping

TopicPartition keyRetentionModules publish
production.eventsaggregate_id (order_id)Vĩnh viễnProduction
quality.eventsaggregate_id (inspection_id)Vĩnh viễnQuality
maintenance.eventsaggregate_id (wo_id)Vĩnh viễnMaintenance
inventory.eventsaggregate_id (material_id)Vĩnh viễnInventory
finance.eventsaggregate_id (ledger_id)Vĩnh viễnFinance
Event Envelope — cấu trúc wrapper chuẩn

Mọi Domain Event đều được wrap trong envelope trước khi publish lên Kafka. Payload bên trong là event-specific.

Event Envelope — JSON Schema
{
  "eventId":       "uuid",
  "eventType":     "ProductionOrderStarted",
  "aggregateType": "ProductionOrder",
  "aggregateId":   "uuid",
  "version":       1,
  "occurredAt":    "2026-06-29T09:15:00Z",
  "correlationId": "uuid",
  "causationId":   "uuid",
  "tenantId":      "tenant_abc",
  "payload":       { /* event-specific data */ }
}
02 — Event Flow

Event Flow tổng thể giữa các Modules

Sơ đồ 1 — Cross-module Event Flow
flowchart TD subgraph Prod["Production Module"] P1["ProductionOrderCreated"] P2["ProductionStarted"] P3["ProductionCompleted"] P4["ProductionCancelled"] end subgraph Qual["Quality Module"] Q1["QualityInspectionCreated"] Q2["InspectionPassed"] Q3["InspectionFailed"] Q4["NonConformanceRaised"] end subgraph Maint["Maintenance Module"] M1["WorkOrderCreated"] M2["WorkOrderCompleted"] M3["AssetBreakdownReported"] end subgraph Inv["Inventory Module"] I1["MaterialReserved"] I2["StockDeducted"] I3["StockReplenished"] end subgraph Fin["Finance Module"] F1["CostEntryPosted"] F2["ProductionCostCalculated"] end P1 -->|"trigger"| I1 P3 -->|"trigger"| I2 P3 -->|"trigger"| Q1 P3 -->|"trigger"| F2 Q3 -->|"trigger"| Q4 Q3 -->|"trigger (rework)"| P1 M3 -->|"trigger"| M1 M2 -->|"trigger"| I3 I2 -->|"trigger"| F1 style Prod fill:#1E1B4B,stroke:#6366F1,color:#E2E8F0 style Qual fill:#052E16,stroke:#10B981,color:#E2E8F0 style Maint fill:#1A1200,stroke:#F59E0B,color:#E2E8F0 style Inv fill:#0C2340,stroke:#06B6D4,color:#E2E8F0 style Fin fill:#1A0A2E,stroke:#8B5CF6,color:#E2E8F0
🖱️ Kéo để di chuyển · Cuộn chuột để zoom
03 — Production

Production Module

Production Bounded Context
Quản lý vòng đời lệnh sản xuất từ tạo → chạy → hoàn thành / hủy
LoạiTênTrigger / Mô tảTopic
CommandCreateProductionOrderTạo lệnh sản xuất mới từ kế hoạch
CommandStartProductionOrderOperator bắt đầu sản xuất trên máy
CommandRecordProductionOutputGhi nhận số lượng hoàn thành theo ca
CommandCompleteProductionOrderĐánh dấu lệnh hoàn thành
CommandPauseProductionOrderTạm dừng (máy hỏng, thiếu NVL)
CommandCancelProductionOrderHủy lệnh sản xuất kèm lý do
EventProductionOrderCreatedLệnh được tạo thành côngproduction.events
EventProductionStartedSản xuất bắt đầu; lock NVL ở Inventoryproduction.events
EventProductionOutputRecordedCập nhật số lượng thực tếproduction.events
EventProductionOrderCompletedHoàn thành; trigger Quality + Financeproduction.events
EventProductionOrderPausedTạm dừng kèm reason_codeproduction.events
EventProductionOrderCancelledHủy; release NVL đã reserveproduction.events
QueryGetProductionOrderByIdChi tiết 1 lệnh
QueryListProductionOrdersDanh sách theo filter (status, date, machine)
QueryGetProductionDashboardDashboard tổng hợp theo ngày/ca
QueryGetMachineUtilizationOEE + utilization theo máy / thời gian

Payload — ProductionOrderCreated

JSON Payload
{
  "orderId":      "uuid",
  "orderNumber":  "PO-2026-001234",
  "productId":    "uuid",
  "productCode":  "FG-001",
  "plannedQty":   500,
  "unit":         "PCS",
  "machineId":    "uuid",
  "machineCode":  "MC-01",
  "shift":        "MORNING",
  "plannedStart": "2026-06-30T06:00:00Z",
  "plannedEnd":   "2026-06-30T14:00:00Z",
  "bomVersion":   "v2.3",
  "materials": [
    { "materialId": "uuid", "code": "RM-001", "qty": 1000, "unit": "KG" }
  ]
}
04 — Quality

Quality Module

Quality Bounded Context
Kiểm tra chất lượng, NCR management, traceability theo ISO 9001 / IATF 16949
LoạiTênTrigger / Mô tảTopic
CommandCreateQualityInspectionTạo phiếu kiểm tra cho lô hàng
CommandRecordInspectionResultNhập kết quả đo từng thông số
CommandSubmitInspectionVerdictKết luận PASS / FAIL cho phiếu
CommandRaiseNonConformanceTạo phiếu NCR cho sản phẩm không đạt
CommandDispositionNonConformanceQuyết định xử lý: rework / scrap / accept
CommandCloseNonConformanceĐóng NCR sau khi verify corrective action
EventQualityInspectionCreatedPhiếu kiểm tra được tạoquality.events
EventInspectionResultRecordedKết quả từng thông số được ghi nhậnquality.events
EventInspectionPassedLô hàng đạt — trigger nhập khoquality.events
EventInspectionFailedLô hàng không đạt — trigger NCRquality.events
EventNonConformanceRaisedNCR được tạo kèm defect detailsquality.events
EventNonConformanceDispositionedQuyết định xử lý được đưa raquality.events
EventNonConformanceClosedNCR đã đóng — audit trail completequality.events
QueryGetInspectionByIdChi tiết phiếu kiểm tra
QueryGetQualityDashboardPass rate, NCR count, top defects
QueryGetTraceabilityReportFull traceability theo product lot
05 — Maintenance

Maintenance Module

Maintenance Bounded Context
Preventive (PM), Corrective (CM), Predictive (PdM) maintenance — quản lý tài sản và lịch bảo trì
LoạiTênTrigger / Mô tảTopic
CommandRegisterAssetĐăng ký thiết bị / máy mới vào hệ thống
CommandSchedulePreventiveMaintenanceLên lịch PM định kỳ
CommandReportAssetBreakdownOperator báo cáo máy hỏng
CommandCreateWorkOrderTạo lệnh công việc bảo trì
CommandStartWorkOrderTechnician bắt đầu bảo trì
CommandCompleteWorkOrderHoàn thành bảo trì + ghi findings
EventAssetRegisteredTài sản mới được đăng kýmaintenance.events
EventAssetBreakdownReportedSự cố được báo cáo — trigger CM work ordermaintenance.events
EventMaintenanceScheduledPM được lên lịchmaintenance.events
EventWorkOrderCreatedLệnh công việc được tạomaintenance.events
EventWorkOrderStartedBảo trì bắt đầumaintenance.events
EventWorkOrderCompletedBảo trì xong — trigger inventory (phụ tùng) + asset updatemaintenance.events
EventPredictiveAlertRaisedAI phát hiện dị thường — gợi ý PM sớmmaintenance.events
QueryGetAssetHistoryLịch sử bảo trì đầy đủ của 1 tài sản
QueryGetMaintenanceDashboardMTBF, MTTR, pending work orders
QueryGetUpcomingMaintenanceScheduleLịch PM trong 30 ngày tới
06 — Inventory

Inventory Module

Inventory Bounded Context
Quản lý tồn kho nguyên vật liệu và thành phẩm — reserve, deduct, replenish
LoạiTênTrigger / Mô tảTopic
CommandReserveMaterialReserve số lượng NVL cho Production Order
CommandReleaseMaterialReservationHủy reserve khi lệnh bị cancel
CommandDeductStockTrừ tồn kho khi sản xuất hoàn thành
CommandReceiveStockNhập kho (từ mua hàng hoặc sản xuất)
CommandTransferStockChuyển kho giữa các location
CommandAdjustStockĐiều chỉnh tồn kho sau kiểm kê
EventMaterialReservedNVL đã được reserve thành cônginventory.events
EventMaterialReservationFailedKhông đủ tồn kho để reserveinventory.events
EventMaterialReservationReleasedReserve được hủyinventory.events
EventStockDeductedTồn kho được trừ — trigger Financeinventory.events
EventStockReceivedNhập kho thành cônginventory.events
EventStockTransferredChuyển kho hoàn thànhinventory.events
EventLowStockAlertRaisedTồn kho xuống dưới reorder pointinventory.events
QueryGetStockLevelTồn kho hiện tại theo material + location
QueryGetStockMovementHistoryLịch sử xuất nhập tồn
QueryGetReorderAlertsDanh sách NVL cần đặt hàng lại
07 — Finance

Finance Module

Finance Bounded Context
Hạch toán chi phí sản xuất, tính giá thành, báo cáo tài chính
LoạiTênTrigger / Mô tảTopic
CommandPostCostEntryHạch toán chi phí vào sổ cái
CommandCalculateProductionCostTính giá thành sau khi lệnh hoàn thành
EventCostEntryPostedBút toán đã được ghi nhậnfinance.events
EventProductionCostCalculatedGiá thành đã tính xongfinance.events
QueryGetProductionCostReportBáo cáo giá thành theo lệnh / sản phẩm
QueryGetCostCenterSummaryTổng hợp chi phí theo cost center
08 — Auth / IAM

Auth / IAM Module

Auth Bounded Context
Quản lý người dùng, JWT access/refresh token, phân quyền theo role và tenant
LoạiTênMô tảTopic
CommandRegisterUserĐăng ký tài khoản mới trong tenant
CommandLoginXác thực → trả access token (30 phút) + refresh token (14 ngày)
CommandRefreshTokenRotate refresh token; dùng lại token đã revoke → revoke ALL của user
CommandLogoutRevoke refresh token hiện tại
CommandAssignRolesGán role cho user (Admin, Production, Quality…)
CommandChangePasswordĐổi mật khẩu → revoke all refresh tokens
CommandActivate / DeactivateKích hoạt hoặc khoá tài khoản
QueryGetUser / ListUsersTra cứu thông tin user trong tenant
State store — không Event Sourcing

Auth dùng bảng users + refresh_tokens (SHA-256 hash). Password hash dùng PBKDF2 600k iterations. JWT claims: sub, tenant_id, role.

09 — BOM

Bill of Materials Module

BOM Bounded Context
Multi-level BOM với versioning — Draft → Active → Obsolete; explode đa cấp có cycle guard
LoạiTênMô tảTopic
CommandCreateBomTạo BOM mới — Draft; version tự tăng theo product
CommandAddComponentThêm vật liệu / sub-assembly vào BOM
CommandRemoveComponentXoá component khỏi BOM Draft
CommandActivateBomKích hoạt → auto obsolete BOM Active cũ cùng product
CommandObsoleteBomĐánh dấu BOM không còn hiệu lực
EventBomCreatedBOM mới được tạobom.events
EventComponentAdded / RemovedDanh sách vật liệu thay đổibom.events
EventBomActivatedBOM có hiệu lực — Planning/MRP sử dụngbom.events
EventBomObsoletedBOM hết hiệu lựcbom.events
QueryGetActiveByProductLấy BOM đang Active của sản phẩm
QueryExplodeBomExplode multi-level + cycle guard → danh sách NVL lá
10 — Planning / MRP

Production Planning / MRP Module

Planning Bounded Context
Kế hoạch sản xuất + MRP-lite: explode BOM × qty → shortage; dispatch list theo due date
LoạiTênMô tảTopic
CommandCreateProductionPlanTạo kế hoạch sản xuất theo kỳ (Draft)
CommandAddPlanLineThêm dòng: sản phẩm + qty + máy + due date
CommandRunMrpExplode Active BOM × qty → so sánh Inventory → Shortage list
CommandReleasePlanRelease kế hoạch (bắt buộc đã RunMRP); sửa line → invalidate MRP
CommandClosePlan / CancelPlanĐóng hoặc huỷ kế hoạch
EventProductionPlanCreatedKế hoạch mới được tạoplanning.events
EventMrpCompletedMRP chạy xong — có shortage listplanning.events
EventPlanReleasedKế hoạch Released → tạo Production Ordersplanning.events
QueryGetDispatchListDanh sách lệnh theo due date / machine — điều phối shop floor
11 — Approval Workflow

Approval Workflow Module

Approval Bounded Context
Ma trận phê duyệt động — Sequential / Parallel / AnyOf; SLA escalation; delegation
LoạiTênMô tảTopic
CommandSubmitApprovalRequestGửi yêu cầu phê duyệt (auto-submit sau Release / NCR Disposition)
CommandDecideApprover Approve / Reject; Sequential → next step; Parallel → chờ đủ
CommandEscalateOverdueSLA quá hạn → escalate lên cấp trên
CommandDelegateUỷ quyền cho người khác (không re-delegate)
CommandCancelRequestHuỷ yêu cầu phê duyệt
EventApprovalRequestSubmittedYêu cầu đã được gửiapproval.events
EventStepApproved / StepRejectedTừng bước được phê duyệt hoặc từ chốiapproval.events
EventApprovalCompleted / RejectedToàn bộ luồng hoàn tấtapproval.events
EventStepEscalatedBước bị escalate do quá SLAapproval.events
EventStepDelegatedBước được uỷ quyềnapproval.events
12 — Notification

Notification Module

Notification Bounded Context
In-app inbox + SignalR real-time + Email/Push stubs — Unread → Read → Dismissed
LoạiTênMô tảTopic
CommandPublishNotificationPublish thông báo → push SignalR + lưu inbox
CommandMarkRead / MarkAllReadĐánh dấu đã đọc
CommandDismissẨn thông báo khỏi inbox
EventNotificationPublishedThông báo được tạo và đẩynotification.events
EventNotificationRead / DismissedTrạng thái đọc thay đổinotification.events
QueryGetUnreadNotificationsInbox chưa đọc của user
13 — Traceability

Traceability Module

Traceability Bounded Context
Lot genealogy — Open → Issued → Closed; TraceForward / TraceBackward đa cấp
LoạiTênMô tảTopic
CommandCreateLotTạo lot nguyên liệu / thành phẩm
CommandIssueToOrderXuất lot cho Production Order
CommandLinkParentLiên kết lot con với lot cha (genealogy)
CommandCloseLotĐóng lot khi sử dụng xong
EventLotCreatedLot mới được tạotraceability.events
EventLotIssuedToOrderLot được xuất cho lệnh sản xuấttraceability.events
EventLotLinkedQuan hệ cha-con được thiết lậptraceability.events
EventLotClosedLot đóng lạitraceability.events
QueryTraceBackwardTìm nguyên liệu đầu vào của một sản phẩm
QueryTraceForwardTìm mọi sản phẩm có dùng nguyên liệu đó
14 — CAPA

CAPA Module

CAPA Bounded Context
Corrective & Preventive Action — Open → Investigating → ActionDefined → InProgress → PendingVerification → Closed
LoạiTênMô tảTopic
CommandOpenCapaCaseMở vấn đề CAPA mới
CommandInvestigateBắt đầu điều tra nguyên nhân gốc rễ
CommandDefineActionPlanXác định kế hoạch hành động khắc phục
CommandStartImplementationBắt đầu thực hiện hành động
CommandSubmitVerificationGửi bằng chứng xác nhận hiệu quả
CommandVerify / CancelXác nhận CAPA hiệu quả hoặc huỷ
EventCapaCaseOpenedVấn đề CAPA được mởcapa.events
EventActionPlanDefinedKế hoạch hành động được xác địnhcapa.events
EventCapaVerified / ClosedCAPA được xác nhận hiệu quả và đóngcapa.events
15 — Shift Management

Shift Management Module

Shift Bounded Context
Quản lý ca sản xuất — Planned → Active → Handover → Closed; bàn giao ca có ghi chú
LoạiTênMô tảTopic
CommandScheduleShiftLên lịch ca — cần supervisor, line, target output
CommandStartShiftBắt đầu ca (cần supervisor)
CommandRecordHandoverGhi nhận bàn giao ca (chỉ khi Active)
CommandCloseShiftĐóng ca (chỉ sau khi đã handover)
EventShiftScheduledCa được lên lịchshift.events
EventShiftStartedCa bắt đầushift.events
EventShiftHandoverRecordedBàn giao ca được ghi nhậnshift.events
EventShiftClosedCa kết thúc — dùng cho OEE tính Availabilityshift.events
16 — Procurement

Procurement Module

Procurement Bounded Context
Purchase Order ES — Draft → PendingApproval → Approved → PartiallyReceived → Received → Closed
LoạiTênMô tảTopic
CommandCreatePurchaseOrderTạo PO mới — Draft; PO number PO-{year}-{seq}
CommandAddLine / RemoveLineThêm/xoá dòng vật liệu (chỉ Draft)
CommandSubmitForApprovalGửi duyệt (cần ≥1 line)
CommandApprove / RejectPhê duyệt hoặc từ chối PO
CommandReceiveGoodsNhận hàng từng dòng — auto ReceiveStock Inventory; auto Received khi đủ
CommandClosePO / CancelPOĐóng hoặc huỷ PO
EventPurchaseOrderCreatedPO được tạoprocurement.events
EventPurchaseOrderApprovedPO được phê duyệtprocurement.events
EventGoodsReceivedNhận hàng → hook ReceiveStock Inventoryprocurement.events
EventPurchaseOrderReceived / ClosedPO hoàn tấtprocurement.events
Inventory hooks 2 chiều

GoodsReceivedIGoodsReceiptInventoryHook → ReceiveStock tự động.
LowStockAlertRaisedILowStockPurchaseHook → tạo draft PO supplier TBD, dedup PO mở.

17 — ECO

Engineering Change Order Module

ECO Bounded Context
Quản lý thay đổi kỹ thuật — Draft → Submitted → Approved (→ Implemented auto) | Rejected | Cancelled
LoạiTênMô tảTopic
CommandCreateEcoRequestTạo ECO Draft — ECO number ECO-{year}-{seq}
CommandAddChangeLineThêm dòng thay đổi (AddComponent / RemoveComponent / ModifySpec)
CommandSubmitEcoGửi ECO để phê duyệt
CommandApproveEcoPhê duyệt → auto implement: tạo BOM revision mới + Activate
CommandRejectEco / CancelEcoTừ chối hoặc huỷ ECO
EventEcoRequestCreatedECO được tạoeco.events
EventEcoRequestSubmittedECO gửi để duyệteco.events
EventEcoRequestApprovedECO được duyệteco.events
EventEcoRequestImplementedBOM mới đã được tạo và kích hoạt — auto sau Approvedeco.events
EventEcoRequestRejected / CancelledECO bị từ chối hoặc huỷeco.events
18 — Calibration

Calibration Management Module

Calibration Bounded Context
Lịch hiệu chuẩn thiết bị đo — Scheduled → InProgress → Passed | Failed | Cancelled
LoạiTênMô tảTopic
CommandScheduleCalibrationLên lịch hiệu chuẩn — CAL number CAL-{year}-{seq}; scheduledDate ≥ hôm nay
CommandStartCalibrationBắt đầu thực hiện hiệu chuẩn
CommandRecordPassGhi nhận đạt — cần nextDueDate > scheduledDate
CommandRecordFailGhi nhận không đạt — thiết bị cần đưa ra ngoài
CommandCancelCalibrationHuỷ lịch hiệu chuẩn
EventCalibrationScheduledLịch hiệu chuẩn được tạocalibration.events
EventCalibrationStartedHiệu chuẩn bắt đầucalibration.events
EventCalibrationPassedĐạt — ghi nhận kết quả và ngày hiệu chuẩn tiếp theocalibration.events
EventCalibrationFailedKhông đạt — thiết bị đo cần xử lýcalibration.events
QueryGetOverdueCalibrationsDanh sách thiết bị quá hạn hiệu chuẩn
19 — Sensor OEE

Sensor OEE Module

Sensor OEE (query-side — không ES)
Ingest telemetry từ PLC/edge → tính OEE tuyệt đối A×P×Q từ dữ liệu máy thực tế
LoạiTênMô tảTopic
CommandIngestSensorReadingsNhận batch readings + uptime events từ PLC/edge — anonymous, key-auth tuỳ chọn
CommandRecalculateOeeSnapshotTính lại OEE A×P×Q cho 1 máy / ca / ngày và upsert vào snapshot
QueryGetMachineOeeOEE snapshot 1 máy theo ngày + ca
QueryGetPlantSensorOeeToàn nhà máy — tất cả máy trong ngày
OEE Formula (OeeFormulas.cs — pure static, fully tested)

A = uptime / planned × 100  ·  P = min(100, cycles × idealCycleSec / uptimeSec × 100)  ·  Q = goodCount / cycles × 100  ·  OEE = A × P × Q / 10 000

Dữ liệu lưu trong sensor_readings + machine_uptime_events (Postgres range-partitioned monthly) + oee_daily_snapshots.

20 — Sagas

Saga Flows — Cross-module Workflows

Sagas điều phối các luồng nghiệp vụ phức tạp span nhiều Bounded Context. Mỗi Saga lắng nghe Events và phát Commands đến module khác.

Sơ đồ 2 — Production Completion Saga
sequenceDiagram participant Prod as Production participant Saga as ProductionCompletionSaga participant Inv as Inventory participant Qual as Quality participant Fin as Finance Prod->>Saga: ProductionOrderCompleted activate Saga Saga->>Inv: DeductStock (actual materials used) Inv-->>Saga: StockDeducted Saga->>Qual: CreateQualityInspection Qual-->>Saga: QualityInspectionCreated alt Inspection Passed Qual-->>Saga: InspectionPassed Saga->>Inv: ReceiveStock (finished goods) Saga->>Fin: CalculateProductionCost Fin-->>Saga: ProductionCostCalculated Saga->>Prod: MarkOrderFullyProcessed else Inspection Failed Qual-->>Saga: InspectionFailed Saga->>Qual: RaiseNonConformance Note over Saga: Chờ NCR disposition Qual-->>Saga: NonConformanceDispositioned alt Rework Saga->>Prod: CreateProductionOrder (rework) else Scrap Saga->>Inv: DeductStock (scrap write-off) Saga->>Fin: PostCostEntry (scrap cost) end end deactivate Saga
🖱️ Kéo để di chuyển · Cuộn chuột để zoom

Các Saga chính trong hệ thống

SagaTriggerModules tham giaCompensating action
ProductionCompletionSaga ProductionOrderCompleted Production → Inventory → Quality → Finance Release stock reservation nếu Quality fail
MaterialReservationSaga ProductionOrderCreated Production → Inventory Cancel order nếu không đủ NVL
BreakdownResponseSaga AssetBreakdownReported Maintenance → Production → Inventory Reschedule production order
PredictiveMaintenanceSaga PredictiveAlertRaised Maintenance → Production (schedule window) Dismiss alert nếu không xác nhận

Tài liệu tiếp theo

DevOps & Infrastructure — K8s · CI/CD · Monitoring

Xem tài liệu → ← Về trang chủ