81 lines
2.4 KiB
Go
81 lines
2.4 KiB
Go
package repository
|
|
|
|
import (
|
|
"context"
|
|
|
|
"github.com/Caknoooo/go-gin-clean-starter/database/entities"
|
|
"github.com/Caknoooo/go-gin-clean-starter/modules/zona/query"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type ZonaRepository interface {
|
|
Create(ctx context.Context, tx *gorm.DB, zona entities.MZonaEntity) (entities.MZonaEntity, error)
|
|
GetById(ctx context.Context, tx *gorm.DB, zonaId string) (entities.MZonaEntity, error)
|
|
GetAll(ctx context.Context, filter query.ZonaFilter) ([]entities.MZonaEntity, int64, error)
|
|
Update(ctx context.Context, tx *gorm.DB, zona entities.MZonaEntity) (entities.MZonaEntity, error)
|
|
Delete(ctx context.Context, tx *gorm.DB, zonaId string) error
|
|
}
|
|
|
|
type zonaRepository struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func NewZonaRepository(db *gorm.DB) ZonaRepository {
|
|
return &zonaRepository{db: db}
|
|
}
|
|
|
|
func (r *zonaRepository) Create(ctx context.Context, tx *gorm.DB, zona entities.MZonaEntity) (entities.MZonaEntity, error) {
|
|
if tx == nil {
|
|
tx = r.db
|
|
}
|
|
if err := tx.WithContext(ctx).Create(&zona).Error; err != nil {
|
|
return zona, err
|
|
}
|
|
return zona, nil
|
|
}
|
|
|
|
func (r *zonaRepository) GetById(ctx context.Context, tx *gorm.DB, zonaId string) (entities.MZonaEntity, error) {
|
|
if tx == nil {
|
|
tx = r.db
|
|
}
|
|
var zona entities.MZonaEntity
|
|
if err := tx.WithContext(ctx).Preload("Client").Preload("Warehouse").First(&zona, "id = ?", zonaId).Error; err != nil {
|
|
return zona, err
|
|
}
|
|
return zona, nil
|
|
}
|
|
|
|
func (r *zonaRepository) GetAll(ctx context.Context, filter query.ZonaFilter) ([]entities.MZonaEntity, int64, error) {
|
|
var zonas []entities.MZonaEntity
|
|
var total int64
|
|
db := query.ApplyZonaFilters(r.db, filter)
|
|
db.Model(&entities.MZonaEntity{}).Count(&total)
|
|
if filter.PerPage > 0 && filter.Page > 0 {
|
|
db = db.Offset((filter.Page - 1) * filter.PerPage).Limit(filter.PerPage)
|
|
}
|
|
if err := db.Find(&zonas).Error; err != nil {
|
|
return zonas, total, err
|
|
}
|
|
return zonas, total, nil
|
|
}
|
|
|
|
func (r *zonaRepository) Update(ctx context.Context, tx *gorm.DB, zona entities.MZonaEntity) (entities.MZonaEntity, error) {
|
|
if tx == nil {
|
|
tx = r.db
|
|
}
|
|
if err := tx.WithContext(ctx).Model(&entities.MZonaEntity{}).Where("id = ?", zona.ID).Updates(&zona).Error; err != nil {
|
|
return zona, err
|
|
}
|
|
return zona, nil
|
|
}
|
|
|
|
func (r *zonaRepository) Delete(ctx context.Context, tx *gorm.DB, zonaId string) error {
|
|
if tx == nil {
|
|
tx = r.db
|
|
}
|
|
if err := tx.WithContext(ctx).Delete(&entities.MZonaEntity{}, "id = ?", zonaId).Error; err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|