aditya.siregar 67f1dbc850 init project
2024-05-28 14:14:55 +07:00

90 lines
2.3 KiB
Go

package branch
import (
"context"
"furtuna-be/internal/common/logger"
"furtuna-be/internal/common/mycontext"
"furtuna-be/internal/entity"
"furtuna-be/internal/repository"
"go.uber.org/zap"
)
type BranchService struct {
repo repository.Branch
}
func NewBranchService(repo repository.Branch) *BranchService {
return &BranchService{
repo: repo,
}
}
func (s *BranchService) Create(ctx mycontext.Context, branchReq *entity.Branch) (*entity.Branch, error) {
branchDB := branchReq.ToBranchDB()
branchDB.CreatedBy = ctx.RequestedBy()
branchDB, err := s.repo.CreateBranch(ctx, branchDB)
if err != nil {
logger.ContextLogger(ctx).Error("error when create branch", zap.Error(err))
return nil, err
}
return branchDB.ToBranch(), nil
}
func (s *BranchService) Update(ctx mycontext.Context, id int64, branchReq *entity.Branch) (*entity.Branch, error) {
existingBranch, err := s.repo.GetBranchByID(ctx, id)
if err != nil {
return nil, err
}
existingBranch.ToUpdatedBranch(ctx.RequestedBy(), *branchReq)
updatedBranchDB, err := s.repo.UpdateBranch(ctx, existingBranch.ToBranchDB())
if err != nil {
logger.ContextLogger(ctx).Error("error when update branch", zap.Error(err))
return nil, err
}
return updatedBranchDB.ToBranch(), nil
}
func (s *BranchService) GetByID(ctx context.Context, id int64) (*entity.Branch, error) {
branchDB, err := s.repo.GetBranchByID(ctx, id)
if err != nil {
logger.ContextLogger(ctx).Error("error when get branch by id", zap.Error(err))
return nil, err
}
return branchDB.ToBranch(), nil
}
func (s *BranchService) GetAll(ctx context.Context, search entity.BranchSearch) ([]*entity.Branch, int, error) {
branches, total, err := s.repo.GetAllBranches(ctx, search)
if err != nil {
logger.ContextLogger(ctx).Error("error when get all branches", zap.Error(err))
return nil, 0, err
}
return branches.ToBranchList(), total, nil
}
func (s *BranchService) Delete(ctx mycontext.Context, id int64) error {
branchDB, err := s.repo.GetBranchByID(ctx, id)
if err != nil {
logger.ContextLogger(ctx).Error("error when get branch by id", zap.Error(err))
return err
}
branchDB.SetDeleted(ctx.RequestedBy())
_, err = s.repo.UpdateBranch(ctx, branchDB)
if err != nil {
logger.ContextLogger(ctx).Error("error when update branch", zap.Error(err))
return err
}
return nil
}