# Change Status Component - Implementation Guide (Go Service Layer) ## Overview Khi người dùng cập nhật `status` của 1 bản ghi trong bảng `component_items`, hệ thống phải: 1. **Tách/mở rộng record** trong bảng `component_items` (quản lý quantity chính xác theo status) 2. **Tự động ghi log** vào bảng `component_status_history` 3. Tất cả trong **cùng 1 transaction** ### Nguyên tắc: Mỗi record = 1 nhóm linh kiện cùng tình trạng Mỗi record `component_items` đại diện cho **một nhóm linh kiện có cùng component, cùng container, cùng status**. Khi đổi status một phần số lượng → phải tách record. ## Tables liên quan - `component_items` — bản ghi linh kiện tại 1 vị trí (container), mỗi record = 1 nhóm cùng status - `component_status_history` — lịch sử thay đổi tình trạng (audit log) ## Status Enum Values ``` normal | damaged | long_unused | expired | pending_inspection ``` --- ## Business Logic - 3 Trường Hợp ### Request Body ```json { "status": "damaged", "changed_quantity": 5, "note": "Bị cháy khi test mạch", "changed_by": "nguyenvana" } ``` ### Trường hợp 1: `changed_quantity` = NULL hoặc = `quantity` (đổi toàn bộ) Đổi status của **toàn bộ** linh kiện trong record. ``` Trước: component_items (id=1): quantity=20, status="normal" Request: { status: "damaged", changed_quantity: null } hoặc changed_quantity: 20 Sau: component_items (id=1): quantity=20, status="damaged" ``` → Chỉ UPDATE status, không tách record. ### Trường hợp 2: `changed_quantity` < `quantity` (đổi một phần, CHƯA có record cùng status mới) Tách thành 2 record: phần còn tốt + phần đổi status. ``` Trước: component_items (id=1): quantity=20, status="normal" Request: { status: "damaged", changed_quantity: 5 } Kiểm tra: KHÔNG có record nào có (component_id=1.component_id, container_id=1.container_id, status="damaged") Sau: component_items (id=1): quantity=15, status="normal" ← giảm 5 component_items (id=NEW): quantity=5, status="damaged" ← record mới ``` ### Trường hợp 3: `changed_quantity` < `quantity` (đổi một phần, ĐÃ có record cùng status mới) Giảm quantity record cũ, **cộng dồn** vào record đã có cùng status. ``` Trước: component_items (id=1): quantity=20, status="normal" component_items (id=2): quantity=3, status="damaged" ← đã có sẵn Request: { status: "damaged", changed_quantity: 5 } Kiểm tra: ĐÃ CÓ record (id=2) cùng (component_id, container_id, status="damaged") Sau: component_items (id=1): quantity=15, status="normal" ← giảm 5 component_items (id=2): quantity=8, status="damaged" ← 3 + 5 = 8 ``` --- ## Go Service Layer Flow ### 1. API Endpoint ``` PUT /api/v1/component-items/:id/status ``` ### 2. Request Model ```go type UpdateComponentItemStatusRequest struct { Status string `json:"status" binding:"required,oneof=normal damaged long_unused expired pending_inspection"` ChangedQuantity *int `json:"changed_quantity"` Note string `json:"note"` ChangedBy string `json:"changed_by" binding:"required"` } ``` ### 3. Chi tiết Transaction ``` BEGIN TRANSACTION │ ├── Bước 1: SELECT component_items WHERE id = :id │ → Lưu lại old_status, old_quantity, component_id, container_id │ ├── Bước 2: Kiểm tra changed_quantity │ │ │ ├── Nếu changed_quantity IS NULL hoặc changed_quantity == old_quantity: │ │ │ │ │ └── Bước 2a: UPDATE component_items │ │ SET status = :new_status, updated_at = NOW() │ │ WHERE id = :id │ │ │ └── Nếu changed_quantity < old_quantity (đổi một phần): │ │ │ ├── Bước 2b-i: UPDATE component_items (record cũ) │ │ SET quantity = old_quantity - changed_quantity, updated_at = NOW() │ │ WHERE id = :id │ │ │ ├── Bước 2b-ii: SELECT component_items │ │ WHERE component_id = :component_id │ │ AND container_id = :container_id │ │ AND status = :new_status │ │ → Kiểm tra đã có record cùng status chưa │ │ │ ├── Nếu CHƯA có: │ │ └── Bước 2b-iii: INSERT INTO component_items │ │ (component_id, container_id, quantity, status, metadata, created_at) │ │ VALUES (:component_id, :container_id, :changed_quantity, :new_status, :metadata, NOW()) │ │ │ └── Nếu ĐÃ có (existing_id): │ └── Bước 2b-iv: UPDATE component_items │ SET quantity = existing_quantity + changed_quantity, updated_at = NOW() │ WHERE id = existing_id │ ├── Bước 3: INSERT INTO component_status_history │ (component_item_id, old_status, new_status, changed_quantity, note, changed_by, changed_at) │ VALUES (:id, :old_status, :new_status, :changed_quantity, :note, :changed_by, NOW()) │ └── COMMIT (hoặc ROLLBACK nếu có lỗi) ``` ### 4. Service Logic (Pseudocode) ```go func UpdateComponentItemStatus(ctx context.Context, dbPool *pgxpool.Pool, queries *db.Queries, id int64, req UpdateComponentItemStatusRequest) error { // 1. Lấy bản ghi hiện tại existing, err := queries.GetComponentItemByID(ctx, id) if err != nil { return ErrNotFound } // 2. Kiểm tra status không đổi if existing.Status == db.ComponentItemStatusEnum(req.Status) { return ErrStatusUnchanged } // 3. Bắt đầu transaction tx, err := dbPool.Begin(ctx) if err != nil { return err } defer func() { if err != nil { tx.Rollback(ctx) } }() txQueries := queries.WithTx(tx) newStatus := db.ComponentItemStatusEnum(req.Status) // 4. Xác định changed_qty (default = toàn bộ) changedQty := int32(existing.Quantity) if req.ChangedQuantity != nil { changedQty = int32(*req.ChangedQuantity) } // 5. Phân nhánh theo trường hợp if changedQty >= existing.Quantity { // Trường hợp 1: Đổi toàn bộ _, err = txQueries.UpdateComponentItemStatus(ctx, db.UpdateComponentItemStatusParams{ ID: id, Status: newStatus, UpdatedAt: time.Now(), }) } else { // Trường hợp 2 & 3: Đổi một phần // 5a. Giảm quantity record cũ _, err = txQueries.UpdateComponentItemQuantity(ctx, db.UpdateComponentItemQuantityParams{ ID: id, Quantity: existing.Quantity - changedQty, UpdatedAt: time.Now(), }) if err != nil { return err } // 5b. Tìm record cùng (component_id, container_id, new_status) existingNewStatus, findErr := txQueries.GetComponentItemByComponentContainerStatus(ctx, db.GetComponentItemByComponentContainerStatusParams{ ComponentID: existing.ComponentID, ContainerID: existing.ContainerID, Status: newStatus, }, ) if findErr == sql.ErrNoRows { // Trường hợp 2: Chưa có → tạo record mới _, err = txQueries.CreateComponentItem(ctx, db.CreateComponentItemParams{ ComponentID: existing.ComponentID, ContainerID: existing.ContainerID, Quantity: changedQty, Status: newStatus, Metadata: existing.Metadata, CreatedAt: time.Now(), }) } else if findErr == nil { // Trường hợp 3: Đã có → cộng dồn quantity _, err = txQueries.UpdateComponentItemQuantity(ctx, db.UpdateComponentItemQuantityParams{ ID: existingNewStatus.ID, Quantity: existingNewStatus.Quantity + changedQty, UpdatedAt: time.Now(), }) } else { return findErr } } if err != nil { return err } // 6. Ghi log vào component_status_history _, err = txQueries.CreateComponentStatusHistory(ctx, db.CreateComponentStatusHistoryParams{ ComponentItemID: id, OldStatus: db.NullComponentItemStatusEnum{ ComponentItemStatusEnum: existing.Status, Valid: true, }, NewStatus: newStatus, ChangedQuantity: pgtype.Int4{Int32: changedQty, Valid: true}, Note: pgtype.Text{String: req.Note, Valid: req.Note != ""}, ChangedBy: pgtype.Text{String: req.ChangedBy, Valid: true}, ChangedAt: time.Now(), }) if err != nil { return err } // 7. Commit return tx.Commit(ctx) } ``` --- ## SQL Queries cần viết (cho sqlc) ### db/queries/component_item.sql ```sql -- name: GetComponentItemByID :one SELECT * FROM component_items WHERE id = sqlc.arg(id); -- name: UpdateComponentItemStatus :one UPDATE component_items SET status = sqlc.arg(status), updated_at = sqlc.arg(updated_at) WHERE id = sqlc.arg(id) RETURNING *; -- name: UpdateComponentItemQuantity :one UPDATE component_items SET quantity = sqlc.arg(quantity), updated_at = sqlc.arg(updated_at) WHERE id = sqlc.arg(id) RETURNING *; -- name: GetComponentItemByComponentContainerStatus :one SELECT * FROM component_items WHERE component_id = sqlc.arg(component_id) AND container_id = sqlc.arg(container_id) AND status = sqlc.arg(status); -- name: CreateComponentItem :one INSERT INTO component_items (component_id, container_id, quantity, status, metadata, created_at) VALUES ( sqlc.arg(component_id), sqlc.arg(container_id), sqlc.arg(quantity), sqlc.arg(status), sqlc.arg(metadata), sqlc.arg(created_at) ) RETURNING *; ``` ### db/queries/component_status_history.sql ```sql -- name: CreateComponentStatusHistory :one INSERT INTO component_status_history ( component_item_id, old_status, new_status, changed_quantity, note, changed_by, changed_at ) VALUES ( sqlc.arg(component_item_id), sqlc.arg(old_status), sqlc.arg(new_status), sqlc.arg(changed_quantity), sqlc.arg(note), sqlc.arg(changed_by), sqlc.arg(changed_at) ) RETURNING *; ``` --- ## Files cần tạo/sửa | File | Action | Mô tả | |------|--------|-------| | `internal/models/requests/component_item_request.go` | Sửa | Thêm `UpdateComponentItemStatusRequest` | | `internal/models/responses/component_item_response.go` | Sửa | Thêm response struct cho status change | | `internal/repositories/component_item_repository.go` | Sửa | Hàm `UpdateComponentItemStatus` (chứa transaction logic) | | `internal/services/component_item_service.go` | Sửa | Handler `ComponentItemUpdateStatus` | | `internal/routers/router.go` | Sửa | Thêm route `PUT /api/v1/component-items/:id/status` | | `db/queries/component_item.sql` | Sửa | Thêm `UpdateComponentItemQuantity`, `GetComponentItemByComponentContainerStatus` | | `db/queries/component_status_history.sql` | Đã có | `CreateComponentStatusHistory` | | `db/migrations/` | (đã có) | Bảng đã tạo ở migration 000001 | --- ## Edge Cases cần xử lý | Trường hợp | Xử lý | |---|---| | `old_status == new_status` | Không update, không ghi history, trả về `"Status unchanged"` | | `component_item` không tồn tại | Return 404 | | `changed_quantity > quantity` | Return 400 — không thể đổi status nhiều hơn số lượng hiện có | | `changed_quantity == 0` | Return 400 — không hợp lý | | `changed_quantity < 0` | Return 400 — không cho số âm | | `changed_quantity` NULL | Đổi status toàn bộ, tương đương `changed_quantity = quantity` | | Transaction failed | Rollback, return 500 | | `changed_by` | Lấy từ JWT token context hoặc request body, ưu tiên JWT | | Record cũ sau khi trừ quantity = 0 | Xóa record đó (`DELETE WHERE quantity = 0`) hoặc để số 0 (tùy chọn) | ### Lưu ý: Xử lý khi quantity record cũ = 0 sau khi tách ``` Trước: (id=1): quantity=5, status="normal" Request: changed_quantity=5, status="damaged" Sau khi UPDATE: (id=1): quantity=0, status="normal" ``` Nên **xóa** record có quantity = 0 sau khi UPDATE, để tránh record rác: ```sql -- name: DeleteComponentItemZeroQuantity :execrows DELETE FROM component_items WHERE id = sqlc.arg(id) AND quantity = 0; ``` Hoặc thêm logic sau bước UPDATE quantity: ```go if existing.Quantity - changedQty == 0 { txQueries.DeleteComponentItem(ctx, id) } ``` --- ## Ví dụ Response ### Thành công - Đổi toàn bộ (Trường hợp 1): ```json { "code": 200, "message": "Status updated successfully", "data": { "id": 1, "old_status": "normal", "new_status": "damaged", "changed_quantity": 20, "history_id": 42 } } ``` ### Thành công - Đổi một phần, tạo record mới (Trường hợp 2): ```json { "code": 200, "message": "Status updated successfully", "data": { "id": 1, "old_status": "normal", "new_status": "damaged", "changed_quantity": 5, "new_component_item_id": 15, "history_id": 42 } } ``` ### Thành công - Đổi một phần, cộng dồn record cũ (Trường hợp 3): ```json { "code": 200, "message": "Status updated successfully", "data": { "id": 1, "old_status": "normal", "new_status": "damaged", "changed_quantity": 5, "merged_component_item_id": 2, "history_id": 42 } } ``` ### Status không đổi: ```json { "code": 200, "message": "Status unchanged", "data": null } ``` ### Validation lỗi - changed_quantity > quantity: ```json { "code": 400, "message": "changed_quantity (25) exceeds current quantity (20)", "data": null } ``` --- ## Ví dụ Vòng Đời Hoàn Chỉnh ``` Ngày 01/03: Nhập kho 20 tụ điện 100uF vào container A → Invoice type=import, quantity=20 → component_items (id=1): quantity=20, status="normal" ───────────────────────────────────────────────── Ngày 02/04: Kiểm kho phát hiện 5 cái bị ẩm → Request: { status: "damaged", changed_quantity: 5, note: "Bị ẩm mốc" } Transaction: UPDATE (id=1): quantity = 20 - 5 = 15 INSERT (id=2): quantity = 5, status = "damaged" INSERT history: old=normal, new=damaged, qty=5 Sau: component_items (id=1): quantity=15, status="normal" component_items (id=2): quantity=5, status="damaged" ───────────────────────────────────────────────── Ngày 05/04: Phát hiện thêm 3 cái bị ẩm nữa → Request: { status: "damaged", changed_quantity: 3, note: "Tiếp tục bị ẩm" } Transaction: UPDATE (id=1): quantity = 15 - 3 = 12 UPDATE (id=2): quantity = 5 + 3 = 8 ← cộng dồn vào record damaged đã có INSERT history: old=normal, new=damaged, qty=3 Sau: component_items (id=1): quantity=12, status="normal" component_items (id=2): quantity=8, status="damaged" ───────────────────────────────────────────────── Ngày 10/04: Kỹ thuật xác nhận 5 cái damaged không sửa được → Request trên record id=2: { status: "expired", changed_quantity: 5 } Transaction: UPDATE (id=2): quantity = 8 - 5 = 3 INSERT (id=3): quantity = 5, status = "expired" INSERT history: old=damaged, new=expired, qty=5 Sau: component_items (id=1): quantity=12, status="normal" component_items (id=2): quantity=3, status="damaged" component_items (id=3): quantity=5, status="expired" ───────────────────────────────────────────────── Ngày 15/04: Xuất bỏ 5 cái expired ra khỏi kho → Invoice type=export, note="Loại bỏ linh kiện expired" → stock_transactions ghi nhận xuất → component_items (id=3): bị xóa hoặc quantity = 0 ```