UPDATE: Project Module
All checks were successful
Build and Release / release (push) Successful in 1m15s

This commit is contained in:
2026-04-25 14:05:15 +07:00
parent 44a63f29c6
commit ac90236022
71 changed files with 5110 additions and 257 deletions

View File

@@ -136,7 +136,7 @@ func (a *authService) Signin(ctx context.Context, dto *request.SignInDto) (*resp
return nil, fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
if user.AuthProvider != constants.LocalProvider.String() && user.PasswordHash == "" {
if user.AuthProvider != constants.ProviderTypeLocal.String() && user.PasswordHash == "" {
return nil, fiber.NewError(fiber.StatusUnauthorized, "Please sign in with "+user.AuthProvider)
}
@@ -219,7 +219,7 @@ func (a *authService) RefreshToken(ctx context.Context, id string, refreshToken
roles := models.RolesEntityToRoleConstant(user.Roles)
if slices.Contains(roles, constants.BANNED) {
if slices.Contains(roles, constants.RoleTypeBanned) {
return nil, fiber.NewError(fiber.StatusUnauthorized, "User is banned!")
}
@@ -254,7 +254,7 @@ func (a *authService) Signup(ctx context.Context, dto *request.SignUpDto) (*resp
return nil, fiber.NewError(fiber.StatusBadRequest, err.Error())
}
ok, err := a.tokenRepo.CheckVerified(ctx, dto.Email, constants.TokenEmailVerify, dto.TokenID)
ok, err := a.tokenRepo.CheckVerified(ctx, dto.Email, constants.TokenTypeEmailVerify, dto.TokenID)
if err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
@@ -284,7 +284,7 @@ func (a *authService) Signup(ctx context.Context, dto *request.SignUpDto) (*resp
String: string(hashed),
Valid: len(hashed) != 0,
},
AuthProvider: constants.LocalProvider.String(),
AuthProvider: constants.ProviderTypeLocal.String(),
},
)
if err != nil {
@@ -308,7 +308,7 @@ func (a *authService) Signup(ctx context.Context, dto *request.SignUpDto) (*resp
if err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
role, err := a.roleRepo.GetByname(ctx, constants.USER.String())
role, err := a.roleRepo.GetByname(ctx, constants.RoleTypeUser.String())
if err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
@@ -352,7 +352,7 @@ func (a *authService) Signup(ctx context.Context, dto *request.SignUpDto) (*resp
}
func (a *authService) ForgotPassword(ctx context.Context, dto *request.ForgotPasswordDto) error {
ok, err := a.tokenRepo.CheckVerified(ctx, dto.Email, constants.TokenPasswordReset, dto.TokenID)
ok, err := a.tokenRepo.CheckVerified(ctx, dto.Email, constants.TokenTypePasswordReset, dto.TokenID)
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
@@ -423,7 +423,7 @@ func (a *authService) SigninWithGoogle(ctx context.Context, dto *request.SigninW
ctx,
sqlc.UpsertUserParams{
Email: dto.Email,
AuthProvider: constants.GoogleProvider.String(),
AuthProvider: constants.ProviderTypeGoogle.String(),
GoogleID: pgtype.Text{
String: dto.Sub,
Valid: dto.Sub != "",
@@ -454,7 +454,7 @@ func (a *authService) SigninWithGoogle(ctx context.Context, dto *request.SigninW
if err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
role, err := a.roleRepo.GetByname(ctx, constants.USER.String())
role, err := a.roleRepo.GetByname(ctx, constants.RoleTypeUser.String())
if err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
@@ -521,8 +521,8 @@ func (a *authService) CreateToken(ctx context.Context, dto *request.CreateTokenD
}
shouldSend := true
if (dto.TokenType == constants.TokenEmailVerify && user != nil) ||
(dto.TokenType == constants.TokenPasswordReset && user == nil) {
if (dto.TokenType == constants.TokenTypeEmailVerify && user != nil) ||
(dto.TokenType == constants.TokenTypePasswordReset && user == nil) {
shouldSend = false
}
@@ -575,8 +575,8 @@ func (a *authService) VerifyToken(ctx context.Context, dto *request.VerifyTokenD
return nil, fiber.NewError(fiber.StatusInternalServerError, "Internal Server Error")
}
if (dto.TokenType == constants.TokenEmailVerify && user != nil) ||
(dto.TokenType == constants.TokenPasswordReset && user == nil) {
if (dto.TokenType == constants.TokenTypeEmailVerify && user != nil) ||
(dto.TokenType == constants.TokenTypePasswordReset && user == nil) {
return nil, genericError
}

View File

@@ -71,7 +71,7 @@ func (m *mediaService) DeleteMedia(ctx context.Context, claims *response.JWTClai
}
shoudDelete := false
if slices.Contains(claims.Roles, constants.ADMIN) || slices.Contains(claims.Roles, constants.MOD) || media.UserID == claims.UId {
if slices.Contains(claims.Roles, constants.RoleTypeAdmin) || slices.Contains(claims.Roles, constants.RoleTypeMod) || media.UserID == claims.UId {
shoudDelete = true
}
@@ -95,7 +95,7 @@ func (m *mediaService) BulkDeleteMedia(ctx context.Context, claims *response.JWT
return fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
shoudDelete := false
if slices.Contains(claims.Roles, constants.ADMIN) || slices.Contains(claims.Roles, constants.MOD) {
if slices.Contains(claims.Roles, constants.RoleTypeAdmin) || slices.Contains(claims.Roles, constants.RoleTypeMod) {
shoudDelete = true
}
listMediaIds := make([]pgtype.UUID, len(listMedia))

View File

@@ -0,0 +1,256 @@
package services
import (
"context"
"fmt"
"github.com/gofiber/fiber/v3"
"github.com/jackc/pgx/v5/pgtype"
"golang.org/x/sync/errgroup"
"history-api/internal/dtos/request"
"history-api/internal/dtos/response"
"history-api/internal/gen/sqlc"
"history-api/internal/models"
"history-api/internal/repositories"
"history-api/pkg/constants"
"history-api/pkg/convert"
)
type ProjectService interface {
GetProjectByID(ctx context.Context, id string) (*response.ProjectResponse, error)
GetProjectByUserID(ctx context.Context, userID string, dto *request.GetProjectsByUserDto) ([]*response.ProjectResponse, error)
SearchProject(ctx context.Context, dto *request.SearchProjectDto) (*response.PaginatedResponse, error)
DeleteProject(ctx context.Context, id string) error
CreateProject(ctx context.Context, userID string, dto *request.CreateProjectDto) (*response.ProjectResponse, error)
UpdateProject(ctx context.Context, id string, dto *request.UpdateProjectDto) (*response.ProjectResponse, error)
}
type projectService struct {
projectRepo repositories.ProjectRepository
}
func NewProjectService(projectRepo repositories.ProjectRepository) ProjectService {
return &projectService{
projectRepo: projectRepo,
}
}
func (s *projectService) GetProjectByID(ctx context.Context, id string) (*response.ProjectResponse, error) {
projectUUID, err := convert.StringToUUID(id)
if err != nil {
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid project ID format")
}
project, err := s.projectRepo.GetByID(ctx, projectUUID)
if err != nil {
return nil, fiber.NewError(fiber.StatusNotFound, "Project not found")
}
return project.ToResponse(), nil
}
func (s *projectService) GetProjectByUserID(ctx context.Context, userID string, dto *request.GetProjectsByUserDto) ([]*response.ProjectResponse, error) {
userUUID, err := convert.StringToUUID(userID)
if err != nil {
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid user ID format")
}
limit := int32(20)
if dto.Limit > 0 {
limit = dto.Limit
}
arg := sqlc.GetProjectsByUserIdParams{
UserID: userUUID,
Limit: limit,
}
if dto.CursorID != "" {
if cursorID, err := convert.StringToUUID(dto.CursorID); err == nil {
arg.CursorID = cursorID
}
}
projects, err := s.projectRepo.GetByUserID(ctx, arg)
if err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
return models.ProjectsEntityToResponse(projects), nil
}
func (s *projectService) fillSearchArgs(arg *sqlc.SearchProjectsParams, dto *request.SearchProjectDto) {
if dto.Sort != "" {
arg.Sort = dto.Sort
} else {
arg.Sort = "updated_at"
}
arg.Order = "desc"
if dto.Order == "asc" {
arg.Order = "asc"
}
if len(dto.Statuses) > 0 {
for _, statusStr := range dto.Statuses {
statusType := constants.ParseProjectStatusTypeText(statusStr)
if statusType != constants.ProjectStatusTypeUnknow {
arg.Statuses = append(arg.Statuses, fmt.Sprintf("%d", statusType.Int16()))
}
}
}
if len(dto.UserIDs) > 0 {
for _, id := range dto.UserIDs {
if u, err := convert.StringToUUID(id); err == nil {
arg.UserIds = append(arg.UserIds, u)
}
}
}
if dto.CreatedFrom != nil {
arg.CreatedFrom = pgtype.Timestamptz{Time: *dto.CreatedFrom, Valid: true}
}
if dto.CreatedTo != nil {
arg.CreatedTo = pgtype.Timestamptz{Time: *dto.CreatedTo, Valid: true}
}
if dto.Search != "" {
arg.SearchText = pgtype.Text{String: dto.Search, Valid: true}
}
}
func (s *projectService) SearchProject(ctx context.Context, dto *request.SearchProjectDto) (*response.PaginatedResponse, error) {
if dto.Page < 1 {
dto.Page = 1
}
if dto.Limit == 0 {
dto.Limit = 20
}
offset := (dto.Page - 1) * dto.Limit
arg := sqlc.SearchProjectsParams{
Limit: int32(dto.Limit),
Offset: int32(offset),
}
s.fillSearchArgs(&arg, dto)
var rows []*models.ProjectEntity
var totalRecords int64
g, gCtx := errgroup.WithContext(ctx)
g.Go(func() error {
var err error
rows, err = s.projectRepo.Search(gCtx, arg)
return err
})
g.Go(func() error {
countArg := sqlc.CountProjectsParams{
Statuses: arg.Statuses,
UserIds: arg.UserIds,
SearchText: arg.SearchText,
CreatedFrom: arg.CreatedFrom,
CreatedTo: arg.CreatedTo,
}
var err error
totalRecords, err = s.projectRepo.Count(gCtx, countArg)
return err
})
if err := g.Wait(); err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
projects := models.ProjectsEntityToResponse(rows)
return response.BuildPaginatedResponse(projects, totalRecords, dto.Page, dto.Limit), nil
}
func (s *projectService) CreateProject(ctx context.Context, userID string, dto *request.CreateProjectDto) (*response.ProjectResponse, error) {
userUUID, err := convert.StringToUUID(userID)
if err != nil {
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid user ID format")
}
arg := sqlc.CreateProjectParams{
Title: dto.Title,
Description: convert.PtrToText(dto.Description),
ProjectStatus: constants.ProjectStatusTypePrivate.Int16(),
UserID: userUUID,
}
if dto.Status != nil {
statusType := constants.ParseProjectStatusTypeText(*dto.Status)
if statusType == constants.ProjectStatusTypeUnknow {
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid status type")
}
arg.ProjectStatus = statusType.Int16()
}
project, err := s.projectRepo.Create(ctx, arg)
if err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to create project")
}
return project.ToResponse(), nil
}
func (s *projectService) UpdateProject(ctx context.Context, id string, dto *request.UpdateProjectDto) (*response.ProjectResponse, error) {
projectUUID, err := convert.StringToUUID(id)
if err != nil {
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid project ID format")
}
_, err = s.projectRepo.GetByID(ctx, projectUUID)
if err != nil {
return nil, fiber.NewError(fiber.StatusNotFound, "Project not found")
}
arg := sqlc.UpdateProjectParams{
ID: projectUUID,
}
if dto.Title != nil {
arg.Title = convert.PtrToText(dto.Title)
}
if dto.Description != nil {
arg.Description = convert.PtrToText(dto.Description)
}
if dto.Status != nil {
statusType := constants.ParseProjectStatusTypeText(*dto.Status)
if statusType == constants.ProjectStatusTypeUnknow {
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid status type")
}
arg.Status = pgtype.Int2{Int16: statusType.Int16(), Valid: true}
}
project, err := s.projectRepo.Update(ctx, arg)
if err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, "Failed to update project")
}
return project.ToResponse(), nil
}
func (s *projectService) DeleteProject(ctx context.Context, id string) error {
projectUUID, err := convert.StringToUUID(id)
if err != nil {
return fiber.NewError(fiber.StatusBadRequest, "Invalid project ID format")
}
_, err = s.projectRepo.GetByID(ctx, projectUUID)
if err != nil {
return fiber.NewError(fiber.StatusNotFound, "Project not found")
}
err = s.projectRepo.Delete(ctx, projectUUID)
if err != nil {
return fiber.NewError(fiber.StatusInternalServerError, "Failed to delete project")
}
return nil
}

View File

@@ -117,16 +117,16 @@ func (u *userService) ChangeRoleUser(ctx context.Context, userId string, claims
hasModRole := false
for _, r := range newListRole {
if r.Name == constants.USER.String() {
if r.Name == constants.RoleTypeUser.String() {
hasUserRole = true
}
if r.Name == constants.ADMIN.String() {
if r.Name == constants.RoleTypeAdmin.String() {
hasAdminRole = true
}
if r.Name == constants.BANNED.String() {
if r.Name == constants.RoleTypeBanned.String() {
hasBannedRole = true
}
if r.Name == constants.MOD.String() {
if r.Name == constants.RoleTypeMod.String() {
hasModRole = true
}
}
@@ -135,7 +135,7 @@ func (u *userService) ChangeRoleUser(ctx context.Context, userId string, claims
return nil, fiber.NewError(fiber.StatusNotFound, "User must have the USER role")
}
if slices.Contains(claims.Roles, constants.MOD) && !slices.Contains(claims.Roles, constants.ADMIN) {
if slices.Contains(claims.Roles, constants.RoleTypeMod) && !slices.Contains(claims.Roles, constants.RoleTypeAdmin) {
if hasAdminRole {
return nil, fiber.NewError(fiber.StatusForbidden, "MOD cannot assign ADMIN role to any user")
}
@@ -149,7 +149,7 @@ func (u *userService) ChangeRoleUser(ctx context.Context, userId string, claims
}
isTargetAdminOrMod := false
for _, r := range user.Roles {
if r.Name == constants.ADMIN.String() || r.Name == constants.MOD.String() {
if r.Name == constants.RoleTypeAdmin.String() || r.Name == constants.RoleTypeMod.String() {
isTargetAdminOrMod = true
break
}
@@ -159,7 +159,7 @@ func (u *userService) ChangeRoleUser(ctx context.Context, userId string, claims
}
}
if slices.Contains(claims.Roles, constants.ADMIN) {
if slices.Contains(claims.Roles, constants.RoleTypeAdmin) {
if userId == claims.UId && hasBannedRole {
return nil, fiber.NewError(fiber.StatusForbidden, "You can't assign BANNED role to yourself")
}

View File

@@ -53,7 +53,7 @@ func NewVerificationService(
func (v *verificationService) CreateVerification(ctx context.Context, userId string, dto *request.CreateUserVerificationDto) (*response.UserVerificationResponse, error) {
verifyType := constants.ParseVerifyTypeText(dto.VerifyType)
if verifyType == constants.VerifyUnknown {
if verifyType == constants.VerifyTypeUnknown {
return nil, fiber.NewError(fiber.StatusInternalServerError, "Unknown verify type!")
}
@@ -124,11 +124,11 @@ func (v *verificationService) DeleteVerification(ctx context.Context, claims *re
}
shoudDelete := false
if slices.Contains(claims.Roles, constants.ADMIN) || slices.Contains(claims.Roles, constants.MOD) {
if slices.Contains(claims.Roles, constants.RoleTypeAdmin) || slices.Contains(claims.Roles, constants.RoleTypeMod) {
shoudDelete = true
}
if verification.User.ID == claims.UId && verification.Status == constants.StatusPending {
if verification.User.ID == claims.UId && verification.Status == constants.StatusTypePending {
shoudDelete = true
}
@@ -182,7 +182,7 @@ func (m *verificationService) fillSearchArgs(arg *sqlc.SearchUserVerificationsPa
if len(dto.Statuses) > 0 {
for _, id := range dto.Statuses {
if u := constants.ParseStatusTypeText(id); u != constants.StatusUnknown {
if u := constants.ParseStatusTypeText(id); u != constants.StatusTypeUnknown {
arg.Statuses = append(arg.Statuses, u.Int16())
}
}
@@ -190,7 +190,7 @@ func (m *verificationService) fillSearchArgs(arg *sqlc.SearchUserVerificationsPa
if len(dto.VerifyTypes) > 0 {
for _, id := range dto.VerifyTypes {
if u := constants.ParseVerifyTypeText(id); u != constants.VerifyUnknown {
if u := constants.ParseVerifyTypeText(id); u != constants.VerifyTypeUnknown {
arg.VerifyTypes = append(arg.VerifyTypes, u.Int16())
}
}
@@ -276,7 +276,7 @@ func (v *verificationService) SearchVerification(ctx context.Context, dto *reque
func (v *verificationService) UpdateStatusVerification(ctx context.Context, userId string, verificationId string, dto *request.UpdateVerificationStatusDto) (*response.UserVerificationResponse, error) {
statusType := constants.ParseStatusTypeText(dto.Status)
if statusType == constants.StatusUnknown {
if statusType == constants.StatusTypeUnknown {
return nil, fiber.NewError(fiber.StatusInternalServerError, "Unknown status type!")
}
verificationUUID, err := convert.StringToUUID(verificationId)
@@ -289,7 +289,7 @@ func (v *verificationService) UpdateStatusVerification(ctx context.Context, user
return nil, fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
historianRole, err := v.roleRepo.GetByname(ctx, constants.HISTORIAN.String())
historianRole, err := v.roleRepo.GetByname(ctx, constants.RoleTypeHistorian.String())
if err != nil {
return nil, fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
@@ -304,7 +304,7 @@ func (v *verificationService) UpdateStatusVerification(ctx context.Context, user
return nil, fiber.NewError(fiber.StatusInternalServerError, err.Error())
}
if verification.Status != constants.StatusPending {
if verification.Status != constants.StatusTypePending {
return nil, fiber.NewError(fiber.StatusBadRequest, "Invalid status!")
}
@@ -340,7 +340,7 @@ func (v *verificationService) UpdateStatusVerification(ctx context.Context, user
Status: statusType,
}
if statusType == constants.StatusApproved {
if statusType == constants.StatusTypeApproved {
roleIdList := make([]pgtype.UUID, 0)
userVerification.Roles = append(userVerification.Roles, historianRole.ToRoleSimple())