package invoices import ( "time" "rmser/internal/domain/invoices" "github.com/google/uuid" "gorm.io/gorm" "gorm.io/gorm/clause" ) type pgRepository struct { db *gorm.DB } func NewRepository(db *gorm.DB) invoices.Repository { return &pgRepository{db: db} } func (r *pgRepository) GetByID(id uuid.UUID) (*invoices.Invoice, error) { var inv invoices.Invoice err := r.db. Preload("Items"). Preload("Items.Product"). Where("id = ?", id). First(&inv).Error if err != nil { return nil, err } return &inv, nil } func (r *pgRepository) GetLastInvoiceDate(serverID uuid.UUID) (*time.Time, error) { var inv invoices.Invoice // Ищем последнюю накладную только для этого сервера err := r.db.Where("rms_server_id = ?", serverID).Order("date_incoming DESC").First(&inv).Error if err != nil { if err == gorm.ErrRecordNotFound { return nil, nil } return nil, err } return &inv.DateIncoming, nil } func (r *pgRepository) GetByPeriod(serverID uuid.UUID, from, to time.Time) ([]invoices.Invoice, error) { var list []invoices.Invoice err := r.db. Preload("Items"). Preload("Items.Product"). Where("rms_server_id = ? AND date_incoming BETWEEN ? AND ? AND status != ?", serverID, from, to, "DELETED"). Order("date_incoming DESC"). Find(&list).Error return list, err } func (r *pgRepository) SaveInvoices(list []invoices.Invoice) error { return r.db.Transaction(func(tx *gorm.DB) error { for _, inv := range list { if err := tx.Omit("Items").Clauses(clause.OnConflict{ Columns: []clause.Column{{Name: "id"}}, UpdateAll: true, }).Create(&inv).Error; err != nil { return err } // Удаляем старые Items для этой накладной if err := tx.Where("invoice_id = ?", inv.ID).Delete(&invoices.InvoiceItem{}).Error; err != nil { return err } if len(inv.Items) > 0 { if err := tx.Create(&inv.Items).Error; err != nil { return err } } } return nil }) } func (r *pgRepository) CountRecent(serverID uuid.UUID, days int) (int64, error) { var count int64 dateFrom := time.Now().AddDate(0, 0, -days) err := r.db.Model(&invoices.Invoice{}). Where("rms_server_id = ? AND date_incoming >= ?", serverID, dateFrom). Count(&count).Error return count, err } func (r *pgRepository) GetStats(serverID uuid.UUID) (total int64, lastMonth int64, last24h int64, err error) { query := ` SELECT COUNT(*) FILTER (WHERE status != 'DELETED') as total, COUNT(*) FILTER (WHERE status != 'DELETED' AND created_at >= NOW() - INTERVAL '1 month') as last_month, COUNT(*) FILTER (WHERE status != 'DELETED' AND created_at >= NOW() - INTERVAL '24 hours') as last_24h FROM invoices WHERE rms_server_id = $1 ` err = r.db.Raw(query, serverID).Row().Scan(&total, &lastMonth, &last24h) return total, lastMonth, last24h, err }