rentease/internal/booking/service.go
2024-02-16 18:08:24 +01:00

77 lines
1.8 KiB
Go

package booking
import (
"time"
"gorm.io/gorm"
)
type Service struct {
db *gorm.DB
}
func NewService(db *gorm.DB) *Service {
return &Service{db: db}
}
func (bs Service) All() []*Booking {
bookings := make([]*Booking, 0)
_ = bs.db.Order("id desc").Find(&bookings)
return bookings
}
func (bs Service) Create(From time.Time, To time.Time, Name string, PhoneNumber string, Email string, Platform string,
CustomerNumber int, PlatformFees float64,
) *Booking {
b := &Booking{
Name: Name,
PhoneNumber: PhoneNumber,
CustomerNumber: CustomerNumber,
Email: Email,
From: From,
To: To,
Platform: Platform,
PlatformFees: PlatformFees,
}
_ = bs.db.Create(b)
return b
}
type Line struct {
From time.Time
To time.Time
Id string
CustomerName string
Platform string
Total float64
PlatformFees float64
}
func (bs Service) BuildReport(period string, month, year int) []*Line {
res := make([]*Line, 0)
var startDate time.Time
var endDate time.Time
if period == "month" {
startDate = time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.UTC)
endDate = time.Date(year, time.Month(month), 31, 0, 0, 0, 0, time.UTC)
} else {
startDate = time.Date(year, time.January, 1, 0, 0, 0, 0, time.UTC)
endDate = time.Date(year, time.December, 31, 0, 0, 0, 0, time.UTC)
}
bs.db.
Raw(`
select id, customer_name, "from", "to", platform, total, platform_fees
from (select sum(price) as total, booking_id
from bookings
join items on bookings.id = items.booking_id
where "from" between ? and ?
group by booking_id) as sbi,
(select * from bookings) as b
where sbi.booking_id = b.id;
`,
startDate.Format("2006-01-02"), endDate.Format("2006-01-02")).
Scan(&res)
return res
}