66 lines
1.8 KiB
Go
Executable File
66 lines
1.8 KiB
Go
Executable File
package repository
|
|
|
|
import (
|
|
"github.com/rovina/zsp-backend/internal/model"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type ContractBatchRepository interface {
|
|
List(folderID *uint) ([]model.ContractBatch, error)
|
|
GetByID(id uint) (*model.ContractBatch, error)
|
|
Create(b *model.ContractBatch, files []model.ContractBatchFile) error
|
|
Delete(id uint) error
|
|
}
|
|
|
|
type contractBatchRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewContractBatchRepository(db *gorm.DB) ContractBatchRepository {
|
|
return &contractBatchRepository{db: db}
|
|
}
|
|
|
|
func (r *contractBatchRepository) List(folderID *uint) ([]model.ContractBatch, error) {
|
|
var list []model.ContractBatch
|
|
query := r.db.Model(&model.ContractBatch{}).Order("create_time DESC")
|
|
if folderID != nil && *folderID > 0 {
|
|
query = query.Where("folder_id = ?", *folderID)
|
|
}
|
|
err := query.Preload("Files").Find(&list).Error
|
|
return list, err
|
|
}
|
|
|
|
func (r *contractBatchRepository) GetByID(id uint) (*model.ContractBatch, error) {
|
|
var b model.ContractBatch
|
|
if err := r.db.Preload("Files").First(&b, id).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
return &b, nil
|
|
}
|
|
|
|
func (r *contractBatchRepository) Create(b *model.ContractBatch, files []model.ContractBatchFile) error {
|
|
return r.db.Transaction(func(tx *gorm.DB) error {
|
|
if err := tx.Create(b).Error; err != nil {
|
|
return err
|
|
}
|
|
for i := range files {
|
|
files[i].BatchID = b.ID
|
|
}
|
|
if len(files) > 0 {
|
|
if err := tx.Create(&files).Error; err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
|
|
func (r *contractBatchRepository) Delete(id uint) error {
|
|
return r.db.Transaction(func(tx *gorm.DB) error {
|
|
if err := tx.Where("batch_id = ?", id).Delete(&model.ContractBatchFile{}).Error; err != nil {
|
|
return err
|
|
}
|
|
return tx.Delete(&model.ContractBatch{}, id).Error
|
|
})
|
|
}
|