86 lines
2.1 KiB
Go
86 lines
2.1 KiB
Go
package repository
|
|
|
|
import (
|
|
"BE-MiniERP/modules/inventory/models"
|
|
|
|
"fmt"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type ProductRepository struct {
|
|
DB *gorm.DB
|
|
}
|
|
|
|
func NewProductRepository(db *gorm.DB) *ProductRepository {
|
|
return &ProductRepository{DB: db}
|
|
}
|
|
|
|
func (r *ProductRepository) FindAll(page, limit, offset int, search string, categoryID, collectionID, colourID, sizeID uint) ([]models.Product, error) {
|
|
var products []models.Product
|
|
|
|
query := r.DB.Model(&models.Product{}).
|
|
Preload("Category").
|
|
Preload("Collection").
|
|
Preload("Colour").
|
|
Preload("Size")
|
|
|
|
if search != "" {
|
|
query = query.Where("name ILIKE ? OR sku ILIKE ?", "%"+search+"%", "%"+search+"%")
|
|
}
|
|
|
|
if categoryID != 0 {
|
|
query = query.Where("category_id = ?", categoryID)
|
|
}
|
|
if collectionID != 0 {
|
|
query = query.Where("collection_id = ?", collectionID)
|
|
}
|
|
if colourID != 0 {
|
|
query = query.Where("colour_id = ?", colourID)
|
|
}
|
|
if sizeID != 0 {
|
|
query = query.Where("size_id = ?", sizeID)
|
|
}
|
|
|
|
err := query.
|
|
Order("created_at DESC").
|
|
Limit(limit).
|
|
Offset(offset).
|
|
Find(&products).Error
|
|
|
|
return products, err
|
|
}
|
|
|
|
func (r *ProductRepository) Create(product *models.Product) error {
|
|
return r.DB.Create(product).Error
|
|
}
|
|
|
|
func (r *ProductRepository) Update(id uint, product *models.Product) error {
|
|
return r.DB.Model(&models.Product{}).Where("id = ?", id).Updates(product).Error
|
|
}
|
|
|
|
func (r *ProductRepository) Delete(id uint) error {
|
|
return r.DB.Delete(&models.Product{}, id).Error
|
|
}
|
|
|
|
func (r *ProductRepository) PreloadRelations(product *models.Product) error {
|
|
// Collection
|
|
if err := r.DB.First(&product.Collection, product.CollectionID).Error; err != nil {
|
|
return fmt.Errorf("collection not found: %w", err)
|
|
}
|
|
// Category
|
|
if err := r.DB.First(&product.Category, product.CategoryID).Error; err != nil {
|
|
return fmt.Errorf("category not found: %w", err)
|
|
}
|
|
// Colour
|
|
if err := r.DB.First(&product.Colour, product.ColourID).Error; err != nil {
|
|
return fmt.Errorf("colour not found: %w", err)
|
|
}
|
|
// Size
|
|
if err := r.DB.First(&product.Size, product.SizeID).Error; err != nil {
|
|
return fmt.Errorf("size not found: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|