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

Domain Events Catalog
Commands · Events · Queries

Danh mục Commands, Domain Events và Queries đã ghi trên trang này phủ tới AP. Hệ thống hiện có 41 bounded context · 30 Kafka topic — catalog dưới đây mới phủ 22/41 — chưa viết Analytics · CatalogImport · Customs · Documents · EInvoice · Files · FixedAssets · Fx · MasterData · Payroll · Prepaid · Pricing · Reporting · Returns · Sensors · Sites · Subcontracting · Tooling · Warehouse. Nguồn sự thật là CLAUDE.md.

Cập nhật: 18/08/2026
Hệ thống: 41 Bounded Contexts
Kafka Topics: 30 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:#1C222E,stroke:#E1AC36,color:#E2E8F0 style Qual fill:#052E16,stroke:#10B981,color:#E2E8F0 style Maint fill:#1A1200,stroke:#F59E0B,color:#E2E8F0 style Inv fill:#0C2530,stroke:#06B6D4,color:#E2E8F0 style Fin fill:#1A1030,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 — Sales

Sales Module (Order-to-Cash)

Sales Bounded Context — đối xứng Procurement bên bán
SalesOrder: Draft → Confirmed → PartiallyShipped → Shipped → Invoiced → Closed | Cancelled
LoạiTênMô tảTopic
CommandCreateSalesOrderTạo đơn bán — SO number SO-{year}-{seq:D6}
CommandAddSoLine / RemoveSoLineSửa dòng chỉ khi Draft; sản phẩm trùng trong SO → DUPLICATE_LINE
CommandConfirmSalesOrderXác nhận — cần ≥1 dòng (EMPTY_ORDER)
CommandShipGoodsGiao hàng từng phần theo dòng; không vượt outstanding (OVER_SHIPMENT)
CommandInvoiceSalesOrderChỉ từ trạng thái Shipped
EventSalesOrderConfirmedĐơn bán được xác nhậnsales.events
EventSalesOrderGoodsShippedGiao hàng — hook trừ kho theo mã sản phẩm, reference SO {số SO}sales.events
EventSalesOrderInvoicedĐơn bán đã xuất hoá đơnsales.events
21 — Routing

Routing Module (quy trình công nghệ)

Routing Bounded Context — cặp song sinh với BOM
BOM = cần vật tư gì, Routing = đi qua công đoạn nào. Draft → Active → Obsolete, versioning theo sản phẩm
LoạiTênMô tảTopic
CommandCreateRoutingTạo quy trình cho sản phẩm — revision tự tăng
CommandAddRoutingStepThêm bước: sequence · operationCode · workCenterCode · setupMinutes (một lần/lô) · minutesPerUnit (nhân theo SL)
CommandActivateRoutingKích hoạt — bản Active cũ tự Obsolete; partial unique index bảo đảm 1 Active/sản phẩm
EventRoutingCreated / RoutingStepAddedDựng quy trìnhrouting.events
EventRoutingActivated / RoutingObsoletedĐổi bản hiệu lựcrouting.events
EventProductionOperationsPlannedSau khi Release lệnh SX: chụp Routing Active thành công đoạn của lệnh — chụp lại, không tham chiếu sống, đổi quy trình chuẩn không làm thay đổi lệnh đang chạyproduction.events
EventProductionOperationStarted / OutputRecorded / CompletedChạy tuần tự (PREVIOUS_OPERATION_OPEN); bán thành phẩm chảy sang bước sau; ActualQty lấy ở bước CUỐIproduction.events
EventProductionLaborBookedChấm công theo công đoạn — đơn giá giờ chốt vào bản ghi, không tham chiếu sang nhân sựproduction.events
22 — Sổ cái

Ledger Module — Sổ cái kế toán kép

Ledger Bounded Context — nền của toàn bộ phần kế toán
JournalEntry (ES) + ChartOfAccount và AccountingPeriod (state store)
LoạiTênMô tảTopic
CommandCreateJournalEntryDựng bút toán; PostImmediately để dựng và ghi sổ một lần — đường dùng cho bút toán tự động
CommandPostJournalEntryGhi sổ — tổng Nợ phải bằng tổng Có (UNBALANCED_ENTRY), kiểm lúc ghi sổ chứ không lúc thêm dòng
CommandReverseJournalEntryĐảo bút toán — bút toán gốc và bút toán đảo ghi trong cùng một transaction
CommandClosePeriod / ReopenPeriodKhoá lần lượt (EARLIER_PERIOD_OPEN); còn nháp thì không khoá (PERIOD_HAS_DRAFTS)
EventJournalEntryDrafted / LineAdded / LineRemovedDựng chứng từ; số dòng tăng đơn điệu, không lấy lại số đã xoáledger.events
EventJournalEntryPostedGhi sổ — dòng chảy vào bảng chỉ-thêm gl_postingsledger.events
EventJournalEntryReversedBút toán gốc vẫn nằm trên sổ, chỉ đánh dấu đã đảoledger.events
QueryGetTrialBalanceBảng cân đối phát sinh — isBalanced kiểm cả ba cặp cột
QueryGetAccountLedgerSổ cái tài khoản có số dư luỹ kế
23 — Phải thu

Accounts Receivable Module

AR Bounded Context — công nợ phải thu
ArInvoice + ArReceipt (ES). Doanh thu ghi nhận khi XUẤT HOÁ ĐƠN, không phải khi giao hàng
LoạiTênMô tảTopic
CommandCreateArInvoice / IssueArInvoiceHoá đơn bán — thuế tính trên từng dòng rồi cộng, các mặt hàng có thuế suất khác nhau
CommandPostArReceiptPhiếu thu — gán vượt số thực thu bị chặn; thu nhiều hơn tổng đã gán thì được (tiền trả trước)
CommandCancelArReceiptHuỷ phiếu thu — hoàn lại số đã trừ trên từng hoá đơn, sinh bút toán ngược
EventArInvoiceIssuedSự kiện mang đủ dữ liệu (số hoá đơn, tên khách, tenant) để bên nghe không phải tra read model do consumer group khác dựngar.events
EventArInvoicePaymentApplied / ReversedTrừ nợ và hoàn lại — thu vượt số còn nợ bị chặn (OVER_PAYMENT)ar.events
EventArReceiptPosted / CancelledPhiếu thu và mọi hoá đơn nó trừ nợ ghi trong cùng một transactionar.events
QueryGetArAgingBảng tuổi nợ — chưa đến hạn · 1-30 · 31-60 · 61-90 · >90
QueryGetArStatementĐối chiếu công nợ theo khách hàng, có số dư luỹ kế
24 — Phải trả

Accounts Payable Module — đối chiếu 3 chiều

AP Bounded Context — công nợ phải trả
ApInvoice + ApPayment (ES). Nhập kho ghi Nợ 152 / Có 3388, hoá đơn về mới Nợ 3388 + Nợ 133 / Có 331
LoạiTênMô tảTopic
CommandCreateApInvoiceHoá đơn NCC — nhận trùng số hoá đơn bị chặn (DUPLICATE_SUPPLIER_INVOICE), trả tiền hai lần cho một lần mua
CommandMatchApInvoiceĐối chiếu 3 chiều: đơn mua ↔ phiếu nhập ↔ hoá đơn. Đối chiếu số lượng theo số ĐÃ NHẬN, không theo số đã đặt
CommandApproveApInvoiceĐối chiếu không đạt vẫn duyệt được nhưng bắt buộc nêu lý do, lý do nằm lại vĩnh viễn trên sổ
CommandPostApPaymentPhiếu chi — phải gán HẾT vào hoá đơn (ALLOCATION_MISMATCH)
EventApInvoiceMatchedKết quả đối chiếu: Matched · NotOnOrder · OverInvoiced · PriceVarianceap.events
EventApInvoiceApprovedSinh hai bút toán: Nợ 3388 / Có 331 và Nợ 133 / Có 331ap.events
EventApPaymentPosted / CancelledChi tiền và huỷ chi — bút toán ngược, không sửa bút toán cũap.events
QueryGetApAgingBảng tuổi nợ phải trả
QueryGetGrniHàng đã nhận chưa có hoá đơn — giải trình số dư tài khoản 3388
25 — 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ủ