tariffs/internal/controller/tariff_grpc/controller.go
pasha1coil d952c19708
Some checks failed
Lint / Lint (push) Failing after 1m22s
Deploy / CreateImage (push) Successful in 1m45s
Deploy / DeployService (push) Successful in 27s
added grpc server to tariffs, client for this srv
2025-07-24 09:56:19 +03:00

103 lines
2.6 KiB
Go

package tariff_grpc
import (
"context"
"errors"
our_errors "gitea.pena/PenaSide/tariffs/internal/errors"
"gitea.pena/PenaSide/tariffs/internal/models"
pb "gitea.pena/PenaSide/tariffs/internal/proto/tariffs"
tariffRepo "gitea.pena/PenaSide/tariffs/internal/repository/tariff"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
)
type Deps struct {
Repo *tariffRepo.Tariff
Logger *zap.Logger
}
type TariffGrpc struct {
repo *tariffRepo.Tariff
logger *zap.Logger
pb.UnimplementedTariffServiceServer
}
func NewTariffGrpc(deps Deps) *TariffGrpc {
return &TariffGrpc{
repo: deps.Repo,
logger: deps.Logger,
}
}
func (t *TariffGrpc) GetTariff(ctx context.Context, req *pb.GetTariffRequest) (*pb.GetTariffResponse, error) {
if req.GetId() == "" {
return nil, status.Error(codes.InvalidArgument, "id is required")
}
objID, err := primitive.ObjectIDFromHex(req.GetId())
if err != nil {
return nil, status.Error(codes.InvalidArgument, "invalid object id")
}
tariff, err := t.repo.GetByID(ctx, objID)
if err != nil {
switch {
case errors.Is(err, our_errors.ErrNotFound):
return nil, status.Error(codes.NotFound, "tariff not found")
default:
t.logger.Error("failed to get tariff", zap.Error(err))
return nil, status.Error(codes.Internal, err.Error())
}
}
return &pb.GetTariffResponse{
Tariff: modelToProtoTariff(&tariff),
}, nil
}
func modelToProtoTariff(t *models.Tariff) *pb.Tariff {
privs := make([]*pb.Privilege, 0, len(t.Privileges))
for _, p := range t.Privileges {
privs = append(privs, modelToProtoPrivilege(&p))
}
return &pb.Tariff{
Id: t.ID.Hex(),
Name: t.Name,
UserId: t.UserID,
Description: t.Description,
Price: int32(t.Price),
Order: int32(t.Order),
IsCustom: t.IsCustom,
Privileges: privs,
IsDeleted: t.IsDeleted,
CreatedAt: timestamppb.New(t.CreatedAt),
UpdatedAt: timestamppb.New(t.UpdatedAt),
DeletedAt: timestamppb.New(t.DeletedAt),
}
}
func modelToProtoPrivilege(p *models.Privilege) *pb.Privilege {
var deletedAt *timestamppb.Timestamp
if p.DeletedAt != nil {
deletedAt = timestamppb.New(*p.DeletedAt)
}
return &pb.Privilege{
Id: p.ID.Hex(),
Name: p.Name,
PrivilegeId: p.PrivilegeID,
ServiceKey: p.ServiceKey,
Description: p.Description,
Type: p.Type,
Value: p.Value,
Price: p.Price,
Amount: p.Amount,
CreatedAt: timestamppb.New(p.CreatedAt),
UpdatedAt: timestamppb.New(p.UpdatedAt),
IsDeleted: p.IsDeleted,
DeletedAt: deletedAt,
}
}