Bỏ qua, đến nội dung

Cài đặt và sử dụng

Kích hoạt plugin

Vào Settings → Plugin Manager, bật @digiforce-nc/plugin-snapshot-field. Plugin đăng ký field type snapshot và các collection history phụ trợ.

Thêm field Snapshot

  1. Mở Collection Manager → chọn collection (ví dụ: orders).
  2. Thêm field mới → chọn interface Snapshot.
  3. Cấu hình:
Thuộc tínhMô tảVí dụ
targetFieldField relation (belongsTo/hasOne) để chụp giá trịproduct
appendsCác association cần eager load khi chụp['category', 'images']
  1. Lưu — khi tạo bản ghi mới, snapshot tự động được chụp.
typescript
const productSnapshotField = {
  name: 'productSnapshot',
  type: 'snapshot',
  interface: 'snapshot',
  targetField: 'product',
  appends: ['category', 'images'],
};

Chọn target field

Target field phải là một relation field (belongsTo hoặc hasOne) trong cùng collection. Ví dụ:

  • Collection orders có relation product → chọn product làm targetField.
  • Khi tạo đơn hàng, snapshot sẽ chụp toàn bộ thông tin sản phẩm tại thời điểm đó.

Cấu hình appends

Appends là danh sách association cần kèm theo khi chụp:

Ví dụ appendsDữ liệu kèm theo
['category']Thông tin danh mục sản phẩm
['images']Danh sách ảnh sản phẩm
['category', 'images', 'variants']Danh mục + ảnh + biến thể

Không có appends: chỉ chụp field trực tiếp của target record.

Cách hoạt động

  1. Người dùng tạo bản ghi mới (ví dụ: đơn hàng) và chọn target (ví dụ: sản phẩm).
  2. Sau khi tạo xong, hook afterCreateWithAssociations tự động chạy.
  3. Hook đọc toàn bộ dữ liệu target record + appends.
  4. Serialize thành JSON và lưu vào cột snapshot.
  5. Giá trị snapshot bất biến — dù target record thay đổi sau đó, snapshot giữ nguyên.

Đọc dữ liệu snapshot

typescript
const order = await repository.findOne({
  filterByTk: 1,
  fields: ['productSnapshot'],
});

// order.productSnapshot.name = "iPhone 15"
// order.productSnapshot.price = 25000000
// order.productSnapshot.category.name = "Điện thoại"
// Giá trị tại thời điểm tạo đơn — không thay đổi

Hiển thị trên giao diện

Plugin cung cấp Snapshot Block Initializers để hiển thị dữ liệu snapshot trong detail/form:

  • Snapshot hiển thị giống record gốc nhưng ở chế độ read-only.
  • Schema hiển thị dựa trên collectionsHistory / fieldsHistory để đảm bảo đúng cấu trúc tại thời điểm chụp.

Lưu ý

  • Snapshot chỉ chụp khi tạo mới (create), không chụp lại khi update.
  • Giá trị snapshot là JSON — không thể query chi tiết bên trong (ví dụ: filter theo snapshot.price).
  • Với target record có nhiều association, dung lượng JSON có thể lớn. Chỉ append những gì cần thiết.
  • Xóa target record không ảnh hưởng snapshot đã chụp.