bill-server-go/internal/bill/service.go

68 lines
1.7 KiB
Go
Raw Normal View History

2023-05-08 15:07:20 +08:00
package bill
import (
"context"
2023-06-10 16:53:44 +08:00
"github.com/samber/lo"
2023-05-08 15:07:20 +08:00
"time"
)
type billService struct {
billRepository BillRepository
}
func NewBillService(r BillRepository) BillService {
return &billService{
billRepository: r,
}
}
2023-05-31 15:31:49 +08:00
// GetBills
2023-05-08 15:07:20 +08:00
// - date is {year, month, day} when return a day bills
// - date is {year, month} when return a month bills
// - date is {year} when return a year bills
// - date is {} when return all bills
2023-06-10 16:53:44 +08:00
func (b *billService) GetBills(ctx context.Context, date BDate) ([]interface{}, error) {
if date.Year == 0 && (date.Month > 0 || date.Day > 0) {
2023-05-08 15:07:20 +08:00
date.Year = time.Now().Year()
2023-06-10 16:53:44 +08:00
} else if date.Month == 0 && date.Day > 0 {
2023-05-08 15:07:20 +08:00
date.Month = int(time.Now().Month())
}
2023-06-10 16:53:44 +08:00
var bills []Bill
var err error
2023-05-08 15:07:20 +08:00
switch {
case date.Year == 0:
2023-06-10 16:53:44 +08:00
bills, err = b.billRepository.GetBills(ctx)
2023-05-08 15:07:20 +08:00
case date.Month == 0:
2023-06-10 16:53:44 +08:00
bills, err = b.billRepository.GetBillByYear(ctx, date.Year)
2023-05-08 15:07:20 +08:00
case date.Day == 0:
2023-06-10 16:53:44 +08:00
bills, err = b.billRepository.GetBillByMonth(ctx, date.Year, date.Month)
2023-05-08 15:07:20 +08:00
default:
2023-06-10 16:53:44 +08:00
bills, err = b.billRepository.GetBillByDay(ctx, date.Year, date.Month, date.Day)
2023-05-08 15:07:20 +08:00
}
2023-06-10 16:53:44 +08:00
return lo.Map(bills, func(b Bill, _ int) interface{} {
return b.Dto()
}), err
2023-05-08 15:07:20 +08:00
}
2023-06-10 16:53:44 +08:00
func (b *billService) GetBillByID(ctx context.Context, id int) (interface{}, error) {
bill, err := b.billRepository.GetBillByID(ctx, id)
if err != nil {
return nil, err
}
billDto := bill.Dto()
return &billDto, nil
2023-05-08 15:07:20 +08:00
}
2023-05-11 21:00:29 +08:00
func (b *billService) CreateBill(ctx context.Context, bill *Bill) error {
2023-05-08 15:07:20 +08:00
return b.billRepository.CreateBill(ctx, bill)
}
2023-05-11 21:00:29 +08:00
func (b *billService) UpdateBill(ctx context.Context, bill *Bill) error {
2023-05-08 15:07:20 +08:00
return b.billRepository.UpdateBill(ctx, bill)
}
2023-05-11 21:00:29 +08:00
func (b *billService) DeleteBill(ctx context.Context, id int) error {
2023-05-08 15:07:20 +08:00
return b.billRepository.DeleteBill(ctx, id)
}