generated from PenaSide/GolangTemplate
93 lines
2.4 KiB
Go
93 lines
2.4 KiB
Go
package history
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"math"
|
|
|
|
"go.uber.org/zap"
|
|
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/dto"
|
|
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/errors"
|
|
"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/models"
|
|
)
|
|
|
|
type historyRepository interface {
|
|
CountAll(context.Context) (int64, errors.Error)
|
|
FindMany(context.Context, *dto.GetHistories) ([]models.History, errors.Error)
|
|
Insert(context.Context, *models.History) (*models.History, errors.Error)
|
|
}
|
|
|
|
type Deps struct {
|
|
Logger *zap.Logger
|
|
Repository historyRepository
|
|
}
|
|
|
|
type Service struct {
|
|
logger *zap.Logger
|
|
repository historyRepository
|
|
}
|
|
|
|
func New(deps Deps) *Service {
|
|
if deps.Logger == nil {
|
|
log.Panicln("logger is nil on <New (history service)>")
|
|
}
|
|
|
|
if deps.Repository == nil {
|
|
log.Panicln("repository is nil on <New (history service)>")
|
|
}
|
|
|
|
return &Service{
|
|
logger: deps.Logger,
|
|
repository: deps.Repository,
|
|
}
|
|
}
|
|
|
|
func (receiver *Service) GetHistoryList(ctx context.Context, dto *dto.GetHistories) (*models.PaginationResponse[models.History], errors.Error) {
|
|
if dto == nil {
|
|
return nil, errors.New(
|
|
fmt.Errorf("pagination is nil on <GetHistoryList> of <HistoryService>: %w", errors.ErrInternalError),
|
|
errors.ErrInternalError,
|
|
)
|
|
}
|
|
|
|
count, err := receiver.repository.CountAll(ctx)
|
|
if err != nil {
|
|
receiver.logger.Error("failed to count histories on <GetHistoryList> of <HistoryService>",
|
|
zap.Error(err),
|
|
)
|
|
|
|
return nil, err
|
|
}
|
|
|
|
if count == 0 {
|
|
return &models.PaginationResponse[models.History]{TotalPages: 0, Records: []models.History{}}, nil
|
|
}
|
|
|
|
totalPages := int64(math.Ceil(float64(count) / float64(dto.Pagination.Limit)))
|
|
|
|
histories, err := receiver.repository.FindMany(ctx, dto)
|
|
if err != nil {
|
|
receiver.logger.Error("failed to get historiy list on <GetHistoryList> of <HistoryService>",
|
|
zap.Error(err),
|
|
)
|
|
|
|
return nil, err
|
|
}
|
|
|
|
return &models.PaginationResponse[models.History]{
|
|
TotalPages: totalPages,
|
|
Records: histories,
|
|
}, nil
|
|
}
|
|
|
|
func (receiver *Service) CreateHistory(ctx context.Context, history *models.History) (*models.History, errors.Error) {
|
|
createdHistory, err := receiver.repository.Insert(ctx, history)
|
|
if err != nil {
|
|
receiver.logger.Error("failed to create history on <CreateHistory> of <HistoryService>", zap.Error(err))
|
|
return nil, err
|
|
}
|
|
|
|
return createdHistory, nil
|
|
}
|