Files
rmser/internal/infrastructure/repository/operations/postgres.go
2025-11-29 08:40:24 +03:00

40 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package operations
import (
"time"
"rmser/internal/domain/operations"
"gorm.io/gorm"
)
type pgRepository struct {
db *gorm.DB
}
func NewRepository(db *gorm.DB) operations.Repository {
return &pgRepository{db: db}
}
func (r *pgRepository) SaveOperations(ops []operations.StoreOperation, opType operations.OperationType, dateFrom, dateTo time.Time) error {
return r.db.Transaction(func(tx *gorm.DB) error {
// 1. Удаляем старые записи этого типа, которые пересекаются с периодом.
// Так как отчет агрегированный, мы привязываемся к периоду "с" и "по".
// Упрощение: удаляем всё, где PeriodFrom совпадает с текущей выгрузкой,
// предполагая, что мы всегда грузим одними и теми же квантами (например, месяц или неделя).
// Для надежности удалим всё, что попадает в диапазон.
if err := tx.Where("op_type = ? AND period_from >= ? AND period_to <= ?", opType, dateFrom, dateTo).
Delete(&operations.StoreOperation{}).Error; err != nil {
return err
}
// 2. Вставляем новые
if len(ops) > 0 {
if err := tx.CreateInBatches(ops, 500).Error; err != nil {
return err
}
}
return nil
})
}