Files
b2b/app/repos/currencyRepo/currencyRepo.go
2026-04-17 15:15:28 +02:00

65 lines
1.6 KiB
Go

package currencyRepo
import (
"git.ma-al.com/goc_daniel/b2b/app/db"
"git.ma-al.com/goc_daniel/b2b/app/model"
"git.ma-al.com/goc_daniel/b2b/app/utils/query/filters"
"git.ma-al.com/goc_daniel/b2b/app/utils/query/find"
"gorm.io/gorm"
)
type UICurrencyRepo interface {
CreateConversionRate(currencyRate *model.CurrencyRate) error
Get(id uint) (*model.Currency, error)
Find(langId uint, p find.Paging, filt *filters.FiltersList) (*find.Found[model.Currency], error)
}
type CurrencyRepo struct{}
func New() UICurrencyRepo {
return &CurrencyRepo{}
}
func (repo *CurrencyRepo) CreateConversionRate(currencyRate *model.CurrencyRate) error {
return db.DB.Create(currencyRate).Error
}
func (repo *CurrencyRepo) Get(id uint) (*model.Currency, error) {
var currency model.Currency
err := db.DB.
Model(&model.Currency{}).
Scopes(WithLatestRate()).
Select("b2b_currencies.*, r.conversion_rate").
Where("b2b_currencies.id = ?", id).
First(&currency).Error
return &currency, err
}
func (repo *CurrencyRepo) Find(langId uint, p find.Paging, filt *filters.FiltersList) (*find.Found[model.Currency], error) {
found, err := find.Paginate[model.Currency](langId, p, db.DB.
Model(&model.Currency{}).
Scopes(WithLatestRate()).
Select("b2b_currencies.*, r.conversion_rate").
Scopes(filt.All()...),
)
return &found, err
}
func WithLatestRate() func(db *gorm.DB) *gorm.DB {
return func(db *gorm.DB) *gorm.DB {
return db.Joins(`
LEFT JOIN b2b_currency_rates r
ON r.b2b_id_currency = b2b_currencies.id
AND r.created_at = (
SELECT MAX(created_at)
FROM b2b_currency_rates
WHERE b2b_id_currency = b2b_currencies.id
)
`)
}
}