Spaces:
Configuration error
Configuration error
Commit ·
212dffe
1
Parent(s): 7beb700
Deploy files from GitHub repository
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- models/request_model.go+3-1
- pkg/validation/custom_rules.go+42
- pkg/validation/validation.go+1
- services/cv_service.go+9-3
- space/Makefile+9-1
- space/config/config.go+3
- space/controller/cv/cv_controller.go+20
- space/docker-compose.yml+4-7
- space/go.mod+1-1
- space/main.go+8-4
- space/models/exception_model.go+3-1
- space/models/request_model.go+10
- space/pkg/storage/local.goAdded+67
- space/pkg/storage/storage.goAdded+71
- space/response/api_response_v2.go+1-1
- space/response/validation.go+1-1
- space/router/cv_route.go+1
- space/router/router.go+1
- space/router/storage_route.goAdded+24
- space/services/cv_service.go+468-385
- space/services/email_verification_service.go+78-78
- space/services/forgot_password_service.go+1-1
- space/space/.gitignore+1
- space/space/pkg/validation/custom_rules.goAdded+162
- space/space/pkg/validation/validation.goAdded+164
- space/space/pkg/worker/distributor.goAdded+23
- space/space/pkg/worker/logger.goAdded+37
- space/space/pkg/worker/processor.goAdded+66
- space/space/pkg/worker/redis_distributor.goAdded+16
- space/space/pkg/worker/task_send_forgot_password_email.goAdded+75
- space/space/pkg/worker/task_send_verify_email.goAdded+75
- space/space/space/main.go+5
- space/space/space/models/exception_model.go+18-15
- space/space/space/response/api_response_v2.go+16-1
- space/space/space/response/validation.goAdded+14
- space/space/space/services/cv_service.go+384-343
- space/space/space/space/go.sum+2
- space/space/space/space/models/database_orm_model.go+32-31
- space/space/space/space/models/request_model.go+62-59
- space/space/space/space/space/controller/quiz/list_quiz_controller.goAdded+23
- space/space/space/space/space/go.mod+4-3
- space/space/space/space/space/router/quiz_route.go+1
- space/space/space/space/space/services/academy_quiz_service.go+20-3
- space/space/space/space/space/space/config/database_connection_config.go+3
- space/space/space/space/space/space/controller/cv/cv_controller.go+288
- space/space/space/space/space/space/models/database_orm_model.go+39
- space/space/space/space/space/space/models/request_model.go+23
- space/space/space/space/space/space/repositories/cv_repository.go+117
- space/space/space/space/space/space/router/cv_route.go+18
- space/space/space/space/space/space/services/cv_service.go+167
12345678997 unmodified lines107108109110111112package modelsimport ("github.com/lib/pq""mime/multipart""time")type LoginRequest struct {97 unmodified linesMaritalStatus *string `json:"marital_status" validate:"marital_status"`LastEducation *string `json:"last_education" validate:"last_education"`LastJob *string `json:"last_job"`}WorshipAndReligiousUnderstandingRequest struct {1234567891097 unmodified lines108109110111112113114package modelsimport ("mime/multipart""time""github.com/lib/pq")type LoginRequest struct {97 unmodified linesMaritalStatus *string `json:"marital_status" validate:"marital_status"`LastEducation *string `json:"last_education" validate:"last_education"`LastJob *string `json:"last_job"`PhoneNumber *string `json:"phone_number" validate:"phone_number"`}WorshipAndReligiousUnderstandingRequest struct {
123456143 unmodified lines1501511521531541554 unmodified lines160161162package validationimport ("strings""sync"143 unmodified linesreturn err}return nil}4 unmodified linesstrings.ContainsAny(password, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") &&strings.ContainsAny(password, "0123456789")}1234567143 unmodified lines1511521531541551561571581591601614 unmodified lines166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204package validationimport ("regexp""strings""sync"143 unmodified linesreturn err}err = validate.RegisterValidation("phone_number", v.PhoneNumberRule)if err != nil {return err}return nil}4 unmodified linesstrings.ContainsAny(password, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") &&strings.ContainsAny(password, "0123456789")}func (v *Validator) PhoneNumberRule(fl v10.FieldLevel) bool {phone := SanitizePhoneNumber(fl.Field().String())return strings.HasPrefix(phone, "+62")}func SanitizePhoneNumber(input string) string {// Hilangkan semua spasi dan stripinput = strings.ReplaceAll(input, " ", "")input = strings.ReplaceAll(input, "-", "")input = strings.ReplaceAll(input, "(", "")input = strings.ReplaceAll(input, ")", "")// Hilangkan semua karakter non-digit kecuali +re := regexp.MustCompile(`[^0-9\+]`)input = re.ReplaceAllString(input, "")// Handle nomor diawali 0 (contoh: 0812...) menjadi +62812...if strings.HasPrefix(input, "0") {input = "+62" + input[1:]}// Handle jika diawali dengan 62 tanpa + (contoh: 62812...)if strings.HasPrefix(input, "62") && !strings.HasPrefix(input, "+62") {input = "+" + input}// Handle jika tidak ada awalan +62 sama sekali (contoh: 8123456789)if !strings.HasPrefix(input, "+62") {if strings.HasPrefix(input, "8") {input = "+62" + input}}return input}
78 unmodified lines79808182838478 unmodified linesif err := rules.RegisterAllCustomRules(validate); err != nil {return err}return nil}78 unmodified lines7980818283848578 unmodified linesif err := rules.RegisterAllCustomRules(validate); err != nil {return err}return nil}
12345678910111213141574 unmodified lines909192939495package servicesimport ("api.qobiltu.id/models""api.qobiltu.id/pkg/storage""api.qobiltu.id/pkg/validation""api.qobiltu.id/repositories""api.qobiltu.id/response""context""errors""gorm.io/gorm""strconv")type CVService interface {74 unmodified linesaccountDetails.LastEducation = req.LastEducationaccountDetails.LastJob = req.LastJob// Simpan datares, err := s.cvRepository.SaveAccountDetails(ctx, accountDetails)if err != nil {1234567891011121314151674 unmodified lines919293949596979899100101package servicesimport ("context""errors""strconv""api.qobiltu.id/models""api.qobiltu.id/pkg/storage""api.qobiltu.id/pkg/validation""api.qobiltu.id/repositories""api.qobiltu.id/response""gorm.io/gorm")type CVService interface {74 unmodified linesaccountDetails.LastEducation = req.LastEducationaccountDetails.LastJob = req.LastJobif req.PhoneNumber != nil {sanitizedPhone := validation.SanitizePhoneNumber(*req.PhoneNumber)accountDetails.PhoneNumber = &sanitizedPhone}// Simpan datares, err := s.cvRepository.SaveAccountDetails(ctx, accountDetails)if err != nil {
1234567up-dev:docker compose -f docker-compose.dev.yml up -drun-dev:go run main.go.PHONY : up-dev run-dev123456789101112131415up-dev:docker compose -f docker-compose.dev.yml up -ddown-dev:docker compose -f docker-compose.dev.yml downup:docker compose up -d --builddown:docker compose downrun-dev:go run main.go.PHONY : up-dev run-dev down-dev up down
28 unmodified lines29303132333414 unmodified lines49505152535428 unmodified linesvar REDIS_POOL_SIZE intvar REDIS_POOL_TIMEOUT time.Durationfunc init() {godotenv.Load()ENV = os.Getenv("ENV")14 unmodified linesREDIS_POOL_SIZE = getValue(os.Getenv("REDIS_POOL_SIZE"), 10, func(s string) (int, error) { return strconv.Atoi(s) })REDIS_MIN_IDLE_CONNS = getValue(os.Getenv("REDIS_MIN_IDLE_CONNS"), 10, func(s string) (int, error) { return strconv.Atoi(s) })REDIS_POOL_TIMEOUT = getValue(os.Getenv("REDIS_POOL_TIMEOUT"), time.Second*30, func(s string) (time.Duration, error) { return time.ParseDuration(s) })}func getValue[T any](value string, defaultValue T, convert func(string) (T, error)) T {28 unmodified lines293031323334353614 unmodified lines5152535455565728 unmodified linesvar REDIS_POOL_SIZE intvar REDIS_POOL_TIMEOUT time.Durationvar APP_URL stringfunc init() {godotenv.Load()ENV = os.Getenv("ENV")14 unmodified linesREDIS_POOL_SIZE = getValue(os.Getenv("REDIS_POOL_SIZE"), 10, func(s string) (int, error) { return strconv.Atoi(s) })REDIS_MIN_IDLE_CONNS = getValue(os.Getenv("REDIS_MIN_IDLE_CONNS"), 10, func(s string) (int, error) { return strconv.Atoi(s) })REDIS_POOL_TIMEOUT = getValue(os.Getenv("REDIS_POOL_TIMEOUT"), time.Second*30, func(s string) (time.Duration, error) { return time.ParseDuration(s) })APP_URL = getValue(os.Getenv("APP_URL"), "http://localhost:3000", func(s string) (string, error) { return s, nil })}func getValue[T any](value string, defaultValue T, convert func(string) (T, error)) T {
45 unmodified lines464748495051501 unmodified lines55355455545 unmodified linesListAchievement(ctx *gin.Context)GetAchievement(ctx *gin.Context)DeleteAchievement(ctx *gin.Context)}type cvController struct {501 unmodified linesresponse.HandleSuccess(ctx, http.StatusOK, "Achievement deleted successfully", nil, nil)}45 unmodified lines4647484950515253501 unmodified lines55555655755855956056156256356456556656756856957057157257357457545 unmodified linesListAchievement(ctx *gin.Context)GetAchievement(ctx *gin.Context)DeleteAchievement(ctx *gin.Context)UploadProfileImage(ctx *gin.Context)}type cvController struct {501 unmodified linesresponse.HandleSuccess(ctx, http.StatusOK, "Achievement deleted successfully", nil, nil)}func (c *cvController) UploadProfileImage(ctx *gin.Context) {accountData := middleware.GetAccountData(ctx)avatarFile, _ := ctx.FormFile("avatar")req := models.UploadProfileImageRequest{AccountID: int64(accountData.UserID),File: avatarFile,}res, err := c.cvService.UploadProfileImage(ctx, &req)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Profile image uploaded successfully", res, nil)}
5 unmodified lines67891011121314151617181925 unmodified lines454647484950515253545 unmodified linesbuild: .depends_on:- dbenv_file: .envports:- "8080:8080"networks:- qobiltu-network# volumes:# - ./logs:/app/logs# - /home/qobiltu/api-qobiltu:/apprestart: unless-stoppeddb:25 unmodified lines- qobiltu-networkrestart: alwaysvolumes:db-data:redis-data:networks:qobiltu-network:driver: bridge5 unmodified lines6789101112131415161718192025 unmodified lines4647484950515 unmodified linesbuild: .depends_on:- db- redisenv_file: .envports:- "8080:8080"volumes:- ./logs:/app/logs- ./uploads:/app/uploadsnetworks:- qobiltu-networkrestart: unless-stoppeddb:25 unmodified lines- qobiltu-networkrestart: alwaysnetworks:qobiltu-network:driver: bridge
7 unmodified lines891011121323 unmodified lines373839404142437 unmodified linesgithub.com/go-playground/universal-translator v0.18.1github.com/go-playground/validator/v10 v10.25.0github.com/golang-jwt/jwt/v5 v5.2.1github.com/gosimple/slug v1.15.0github.com/hibiken/asynq v0.25.1github.com/joho/godotenv v1.5.123 unmodified linesgithub.com/go-logr/stdr v1.2.2 // indirectgithub.com/goccy/go-json v0.10.5 // indirectgithub.com/google/s2a-go v0.1.9 // indirectgithub.com/google/uuid v1.6.0 // indirectgithub.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirectgithub.com/googleapis/gax-go/v2 v2.14.1 // indirectgithub.com/gosimple/unidecode v1.0.1 // indirect7 unmodified lines89101112131423 unmodified lines3839404142437 unmodified linesgithub.com/go-playground/universal-translator v0.18.1github.com/go-playground/validator/v10 v10.25.0github.com/golang-jwt/jwt/v5 v5.2.1github.com/google/uuid v1.6.0github.com/gosimple/slug v1.15.0github.com/hibiken/asynq v0.25.1github.com/joho/godotenv v1.5.123 unmodified linesgithub.com/go-logr/stdr v1.2.2 // indirectgithub.com/goccy/go-json v0.10.5 // indirectgithub.com/google/s2a-go v0.1.9 // indirectgithub.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirectgithub.com/googleapis/gax-go/v2 v2.14.1 // indirectgithub.com/gosimple/unidecode v1.0.1 // indirect
1 unmodified line23456789101112131415166 unmodified lines23242526272824 unmodified lines535455565758591 unmodified lineimport ("api.qobiltu.id/config"cv_controller "api.qobiltu.id/controller/cv""api.qobiltu.id/controller/health_check""api.qobiltu.id/mail""api.qobiltu.id/repositories""api.qobiltu.id/router""api.qobiltu.id/services""api.qobiltu.id/utils""api.qobiltu.id/validation""api.qobiltu.id/worker""github.com/hibiken/asynq""log/slog""net"6 unmodified lineserr := validation.New(validation.LocaleID)utils.FatalIfErr("failed to setup validator", err)// setup email senderemailConfig := mail.Config{Host: config.SMTP_HOST,24 unmodified lineshealthCheckController := health_check_controller.NewHealthCheckController(healthCheckService)cvRepository := repositories.NewCVRepository(config.DB)cvService := services.NewCVService(cvRepository)cvController := cv_controller.NewCVController(cvService)// start task processor1 unmodified line2345678910111213141516176 unmodified lines24252627282930313224 unmodified lines575859606162631 unmodified lineimport ("api.qobiltu.id/config""api.qobiltu.id/controller/cv""api.qobiltu.id/controller/health_check""api.qobiltu.id/mail""api.qobiltu.id/pkg/storage""api.qobiltu.id/pkg/validation""api.qobiltu.id/pkg/worker""api.qobiltu.id/repositories""api.qobiltu.id/router""api.qobiltu.id/services""api.qobiltu.id/utils""github.com/hibiken/asynq""log/slog""net"6 unmodified lineserr := validation.New(validation.LocaleID)utils.FatalIfErr("failed to setup validator", err)// setup storagelocalStorage := storage.NewLocalStorage("uploads", config.APP_URL+"/storage/")// setup email senderemailConfig := mail.Config{Host: config.SMTP_HOST,24 unmodified lineshealthCheckController := health_check_controller.NewHealthCheckController(healthCheckService)cvRepository := repositories.NewCVRepository(config.DB)cvService := services.NewCVService(cvRepository, localStorage)cvController := cv_controller.NewCVController(cvService)// start task processor
123456package modelsimport "api.qobiltu.id/validation"type Exception struct {Unauthorized bool `json:"unauthorized,omitempty"`12345678package modelsimport ("api.qobiltu.id/pkg/validation")type Exception struct {Unauthorized bool `json:"unauthorized,omitempty"`
1 unmodified line234567141 unmodified lines1491501511521 unmodified lineimport ("github.com/lib/pq""time")141 unmodified linesAccountID int64 `json:"account_id"`AchievementOrAward *string `json:"achievement_or_award"` // prestasi atau penghargaan})1 unmodified line2345678141 unmodified lines1501511521531541551561571581591601611621 unmodified lineimport ("github.com/lib/pq""mime/multipart""time")141 unmodified linesAccountID int64 `json:"account_id"`AchievementOrAward *string `json:"achievement_or_award"` // prestasi atau penghargaan}UploadProfileImageRequest struct {AccountID int64File *multipart.FileHeader}UploadProfileImageResponse struct {URL string `json:"url"`})
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667package storage
import ( "context" "fmt" "io" "os" "path/filepath" "strings")
type LocalStorage struct { *BaseStorage basePath string baseURL string}
func NewLocalStorage(basePath, baseURL string) *LocalStorage { return &LocalStorage{ BaseStorage: NewBaseStorage(), basePath: basePath, baseURL: baseURL, }}
func (s *LocalStorage) Upload(ctx context.Context, file io.ReadSeeker, path string) error { fullPath := filepath.Join(s.basePath, path)
dir := filepath.Dir(fullPath) if err := os.MkdirAll(dir, 0755); err != nil { return err }
dst, err := os.Create(fullPath) if err != nil { return err } defer dst.Close()
if _, err := io.Copy(dst, file); err != nil { return err } return nil}
func (s *LocalStorage) GetURL(path string) string { return filepath.Join(s.baseURL, path)}
func (s *LocalStorage) Delete(ctx context.Context, path string) error { // Contoh input: "http://localhost:8080/storage/users/5/profile/filename.png"
// Ambil bagian setelah "/storage/" const prefix = "/storage/" idx := strings.Index(path, prefix) if idx == -1 { return os.ErrNotExist }
relativePath := path[idx+len(prefix):]
// Gabungkan dengan basePath fullPath := filepath.Join(s.basePath, relativePath) fmt.Println(fullPath)
return os.Remove(fullPath)}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071package storage
import ( "context" "errors" "github.com/google/uuid" "io" "path/filepath")
type FileType int
const ( ProfileImage FileType = iota)
var ( ErrInvalidFileType = errors.New("invalid file type") ErrFileTooLarge = errors.New("file too large") ErrNoFileUploaded = errors.New("no file uploaded"))
type Storage interface { Upload(ctx context.Context, file io.ReadSeeker, path string) error GetURL(path string) string Delete(ctx context.Context, path string) error
ValidateExtension(fileType FileType, filename string) bool GenerateFilename(originalName string) string GetPath(fileType FileType, identifier string, filename string) string}
var ( _ Storage = (*LocalStorage)(nil))
type BaseStorage struct { allowedExtensions map[FileType][]string}
func NewBaseStorage() *BaseStorage { return &BaseStorage{ allowedExtensions: map[FileType][]string{ ProfileImage: {".jpg", ".jpeg", ".png", ".webp"}, }, }}
func (bs *BaseStorage) ValidateExtension(fileType FileType, filename string) bool { ext := filepath.Ext(filename) for _, allowed := range bs.allowedExtensions[fileType] { if ext == allowed { return true } } return false}
func (bs *BaseStorage) GenerateFilename(originalName string) string { ext := filepath.Ext(originalName) return uuid.New().String() + ext}
func (bs *BaseStorage) GetPath(fileType FileType, identifier string, filename string) string { switch fileType { case ProfileImage: return filepath.Join("users", identifier, "profile", filename) default: return filepath.Join("misc", filename) }}1 unmodified line234567891 unmodified lineimport ("api.qobiltu.id/models""api.qobiltu.id/utils""api.qobiltu.id/validation""errors""net/http"1 unmodified line234567891 unmodified lineimport ("api.qobiltu.id/models""api.qobiltu.id/pkg/validation""api.qobiltu.id/utils""errors""net/http"
1 unmodified line23456781 unmodified lineimport ("api.qobiltu.id/models""api.qobiltu.id/validation")func HandleValidationError(validationErrors []validation.ErrorMessage) error {1 unmodified line23456781 unmodified lineimport ("api.qobiltu.id/models""api.qobiltu.id/pkg/validation")func HandleValidationError(validationErrors []validation.ErrorMessage) error {
6 unmodified lines7891011126 unmodified lines{routerGroup.POST("/account-details", s.cvController.SaveAccountDetails)routerGroup.GET("/account-details", s.cvController.GetAccountDetails)routerGroup.POST("/personality-and-preferences", s.cvController.SavePersonalityAndPreference)routerGroup.GET("/personality-and-preferences", s.cvController.GetPersonalityAndPreference)6 unmodified lines789101112136 unmodified lines{routerGroup.POST("/account-details", s.cvController.SaveAccountDetails)routerGroup.GET("/account-details", s.cvController.GetAccountDetails)routerGroup.POST("/account-details/avatar", s.cvController.UploadProfileImage)routerGroup.POST("/personality-and-preferences", s.cvController.SavePersonalityAndPreference)routerGroup.GET("/personality-and-preferences", s.cvController.GetPersonalityAndPreference)
17 unmodified lines1819202117 unmodified lines// another way to register routess.HealthCheckRoute()s.CVRoute()}17 unmodified lines181920212217 unmodified lines// another way to register routess.HealthCheckRoute()s.CVRoute()s.StorageRoute()}
123456789101112131415161718192021222324package router
import ( "api.qobiltu.id/middleware" "github.com/gin-gonic/gin" "net/http" "strings")
func (s *Server) StorageRoute() { s.router.GET("/storage/*filepath", func(ctx *gin.Context) { filepath := ctx.Param("filepath")
// Prevent directory listing if filepath == "" || strings.HasSuffix(filepath, "/") { ctx.AbortWithStatus(http.StatusForbidden) return }
fs := http.Dir("uploads")
ctx.FileFromFS(filepath, fs) }).Use(middleware.AuthUser)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485package servicesimport ("api.qobiltu.id/models""api.qobiltu.id/repositories""api.qobiltu.id/response""api.qobiltu.id/validation""context""errors""gorm.io/gorm")type CVService interface {SaveAccountDetails(ctx context.Context, req *models.AccountDetailsRequest) (*models.AccountDetails, error)GetAccountDetails(ctx context.Context, id int64) (*models.AccountDetails, error)SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCVRequest) (*models.PersonalityAndPreferenceCV, error)GetPersonalityAndPreference(ctx context.Context, id int64) (*models.PersonalityAndPreferenceCV, error)CreateFamilyMember(ctx context.Context, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error)UpdateFamilyMember(ctx context.Context, id int64, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error)ListFamilyMember(ctx context.Context, accountID int64) ([]models.FamilyMemberCV, error)GetFamilyMember(ctx context.Context, id int64) (*models.FamilyMemberCV, error)DeleteFamilyMember(ctx context.Context, id int64) errorSavePhysicalAndHealth(ctx context.Context, req *models.PhysicalAndHealthRequest) (*models.PhysicalAndHealthCV, error)GetPhysicalAndHealth(ctx context.Context, id int64) (*models.PhysicalAndHealthCV, error)SaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingRequest) (*models.WorshipAndReligiousUnderstandingCV, error)GetWorshipAndReligiousUnderstanding(ctx context.Context, id int64) (*models.WorshipAndReligiousUnderstandingCV, error)CreateEducation(ctx context.Context, req *models.EducationRequest) (*models.EducationCV, error)UpdateEducation(ctx context.Context, id int64, req *models.EducationRequest) (*models.EducationCV, error)ListEducation(ctx context.Context, accountID int64) ([]models.EducationCV, error)GetEducation(ctx context.Context, id int64) (*models.EducationCV, error)DeleteEducation(ctx context.Context, id int64) errorCreateJob(ctx context.Context, req *models.JobRequest) (*models.JobCV, error)UpdateJob(ctx context.Context, id int64, req *models.JobRequest) (*models.JobCV, error)ListJob(ctx context.Context, accountID int64) ([]models.JobCV, error)GetJob(ctx context.Context, id int64) (*models.JobCV, error)DeleteJob(ctx context.Context, id int64) errorCreateAchievement(ctx context.Context, req *models.AchievementRequest) (*models.AchievementCV, error)UpdateAchievement(ctx context.Context, id int64, req *models.AchievementRequest) (*models.AchievementCV, error)ListAchievement(ctx context.Context, accountID int64) ([]models.AchievementCV, error)GetAchievement(ctx context.Context, id int64) (*models.AchievementCV, error)DeleteAchievement(ctx context.Context, id int64) error}type cvService struct {cvRepository repositories.CVRepository}func NewCVService(cvRepository repositories.CVRepository) CVService {return &cvService{cvRepository: cvRepository,}}func (s *cvService) SaveAccountDetails(ctx context.Context, req *models.AccountDetailsRequest) (*models.AccountDetails, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Ambil data lama jika adaaccountDetails, err := s.cvRepository.GetAccountDetailsByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Internal Server Error")}// Apply perubahanif accountDetails == nil {accountDetails = &models.AccountDetails{}}accountDetails.AccountID = uint(req.AccountID)accountDetails.FullName = req.FullNameaccountDetails.Gender = req.GenderaccountDetails.DateOfBirth = req.DateOfBirthaccountDetails.PlaceOfBirth = req.PlaceOfBirthaccountDetails.Domicile = req.DomicileaccountDetails.MaritalStatus = req.MaritalStatusaccountDetails.LastEducation = req.LastEducationaccountDetails.LastJob = req.LastJob// Simpan datares, err := s.cvRepository.SaveAccountDetails(ctx, accountDetails)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) GetAccountDetails(ctx context.Context, id int64) (*models.AccountDetails, error) {res, err := s.cvRepository.GetAccountDetailsByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data diri tidak ditemukan")}return res, nil}func (s *cvService) SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCVRequest) (*models.PersonalityAndPreferenceCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Ambil data lama jika adapersonalityAndPreference, err := s.cvRepository.GetPersonalityAndPreferenceByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Internal Server Error")}// Apply perubahanif personalityAndPreference == nil {personalityAndPreference = &models.PersonalityAndPreferenceCV{}}personalityAndPreference.AccountID = req.AccountIDpersonalityAndPreference.PositiveTraits = req.PositiveTraitspersonalityAndPreference.NegativeTraits = req.NegativeTraitspersonalityAndPreference.Hobbies = req.HobbiespersonalityAndPreference.LifeGoals = req.LifeGoalspersonalityAndPreference.DailyActivities = req.DailyActivitiespersonalityAndPreference.LeisureActivities = req.LeisureActivitiespersonalityAndPreference.Likes = req.LikespersonalityAndPreference.Dislikes = req.DislikespersonalityAndPreference.StressHandling = req.StressHandlingpersonalityAndPreference.AngerTriggers = req.AngerTriggerspersonalityAndPreference.FavoriteFoodAndDrinks = req.FavoriteFoodAndDrinkspersonalityAndPreference.CanCook = req.CanCookpersonalityAndPreference.TypesOfDishesCooked = req.TypesOfDishesCookedpersonalityAndPreference.MonthlyExpenses = req.MonthlyExpensesres, err := s.cvRepository.SavePersonalityAndPreference(ctx, personalityAndPreference)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) GetPersonalityAndPreference(ctx context.Context, id int64) (*models.PersonalityAndPreferenceCV, error) {res, err := s.cvRepository.GetPersonalityAndPreferenceByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) CreateFamilyMember(ctx context.Context, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Mapping request ke modelfamilyMember := &models.FamilyMemberCV{AccountID: req.AccountID,Role: req.Role,Status: req.Status,Religion: req.Religion,Job: req.Job,LastEducation: req.LastEducation,Age: req.Age,}// Simpan ke repositoryres, err := s.cvRepository.SaveFamilyMember(ctx, familyMember)if err != nil {return nil, response.HandleGormError(err, "Gagal menyimpan anggota keluarga")}return res, nil}func (s *cvService) ListFamilyMember(ctx context.Context, accountID int64) ([]models.FamilyMemberCV, error) {list, err := s.cvRepository.ListFamilyMember(ctx, accountID)if err != nil {return nil, response.HandleGormError(err, "Gagal mengambil daftar anggota keluarga")}return list, nil}func (s *cvService) GetFamilyMember(ctx context.Context, id int64) (*models.FamilyMemberCV, error) {res, err := s.cvRepository.GetFamilyMember(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data anggota keluarga tidak ditemukan")}return res, nil}func (s *cvService) DeleteFamilyMember(ctx context.Context, id int64) error {err := s.cvRepository.DeleteFamilyMember(ctx, id)if err != nil {return response.HandleGormError(err, "Gagal menghapus anggota keluarga")}return nil}func (s *cvService) UpdateFamilyMember(ctx context.Context, id int64, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}existing, err := s.cvRepository.GetFamilyMember(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data anggota keluarga tidak ditemukan")}existing.Role = req.Roleexisting.Status = req.Statusexisting.Religion = req.Religionexisting.Job = req.Jobexisting.LastEducation = req.LastEducationexisting.Age = req.Ageupdated, err := s.cvRepository.SaveFamilyMember(ctx, existing)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui anggota keluarga")}return updated, nil}func (s *cvService) SavePhysicalAndHealth(ctx context.Context, req *models.PhysicalAndHealthRequest) (*models.PhysicalAndHealthCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Cek apakah data sudah ada berdasarkan account_idexisting, err := s.cvRepository.GetPhysicalAndHealthByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Terjadi kesalahan saat mengambil data fisik dan kesehatan")}// Jika belum ada, buat objek baruif existing == nil {existing = &models.PhysicalAndHealthCV{}}// Mapping field dari requestexisting.AccountID = req.AccountIDexisting.HeightInCm = req.HeightInCmexisting.WeightInKg = req.WeightInKgexisting.BodyShape = req.BodyShapeexisting.SkinColor = req.SkinColorexisting.HairType = req.HairTypeexisting.MedicalHistory = req.MedicalHistoryexisting.PhysicalDisorder = req.PhysicalDisorderexisting.PhysicalTraits = req.PhysicalTraits// Simpan datares, err := s.cvRepository.SavePhysicalAndHealth(ctx, existing)if err != nil {return nil, response.HandleGormError(err, "Gagal menyimpan data fisik dan kesehatan")}return res, nil}func (s *cvService) GetPhysicalAndHealth(ctx context.Context, id int64) (*models.PhysicalAndHealthCV, error) {res, err := s.cvRepository.GetPhysicalAndHealthByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data fisik dan kesehatan tidak ditemukan")}return res, nil}func (s *cvService) SaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingRequest) (*models.WorshipAndReligiousUnderstandingCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Cek apakah data sudah ada berdasarkan account_idworshipAndReligiousUnderstanding, err := s.cvRepository.GetWorshipAndReligiousUnderstandingByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Terjadi kesalahan saat mengambil data agama dan pemahaman agama")}// Jika belum ada, buat objek baruif worshipAndReligiousUnderstanding == nil {worshipAndReligiousUnderstanding = &models.WorshipAndReligiousUnderstandingCV{}}// Mapping field dari requestworshipAndReligiousUnderstanding.AccountID = req.AccountIDworshipAndReligiousUnderstanding.ObligatoryPrayer = req.ObligatoryPrayerworshipAndReligiousUnderstanding.CongregationalPrayer = req.CongregationalPrayerworshipAndReligiousUnderstanding.TahajjudPrayer = req.TahajjudPrayerworshipAndReligiousUnderstanding.DhuhaPrayer = req.DhuhaPrayerworshipAndReligiousUnderstanding.QuranMemorization = req.QuranMemorizationworshipAndReligiousUnderstanding.QuranReadingAbility = req.QuranReadingAbilityworshipAndReligiousUnderstanding.DaudFasting = req.DaudFastingworshipAndReligiousUnderstanding.AyyamulBidhFasting = req.AyyamulBidhFastingworshipAndReligiousUnderstanding.HajjOrUmrah = req.HajjOrUmrahworshipAndReligiousUnderstanding.ListeningToMusic = req.ListeningToMusicworshipAndReligiousUnderstanding.OpinionOnIkhtilat = req.OpinionOnIkhtilatworshipAndReligiousUnderstanding.OpinionOnTouchingNonMahram = req.OpinionOnTouchingNonMahramworshipAndReligiousUnderstanding.OpinionOnVeil = req.OpinionOnVeilworshipAndReligiousUnderstanding.WeeklyReligiousStudies = req.WeeklyReligiousStudiesworshipAndReligiousUnderstanding.FollowedUstadz = req.FollowedUstadz// Simpan datares, err := s.cvRepository.SaveWorshipAndReligiousUnderstanding(ctx, worshipAndReligiousUnderstanding)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) GetWorshipAndReligiousUnderstanding(ctx context.Context, id int64) (*models.WorshipAndReligiousUnderstandingCV, error) {res, err := s.cvRepository.GetWorshipAndReligiousUnderstandingByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data agama dan pemahaman agama tidak ditemukan")}return res, nil}func (s *cvService) CreateEducation(ctx context.Context, req *models.EducationRequest) (*models.EducationCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}edu := &models.EducationCV{AccountID: req.AccountID,LastEducation: req.LastEducation,EducationInstitute: req.EducationInstitute,EducationMajor: req.EducationMajor,YearStart: req.YearStart,YearGraduate: req.YearGraduate,}res, err := s.cvRepository.SaveEducation(ctx, edu)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data pendidikan")}return res, nil}func (s *cvService) UpdateEducation(ctx context.Context, id int64, req *models.EducationRequest) (*models.EducationCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}edu, err := s.cvRepository.GetEducation(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pendidikan tidak ditemukan")}edu.LastEducation = req.LastEducationedu.EducationInstitute = req.EducationInstituteedu.EducationMajor = req.EducationMajoredu.YearStart = req.YearStartedu.YearGraduate = req.YearGraduateres, err := s.cvRepository.SaveEducation(ctx, edu)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data pendidikan")}return res, nil}func (s *cvService) ListEducation(ctx context.Context, accountID int64) ([]models.EducationCV, error) {return s.cvRepository.ListEducation(ctx, accountID)}func (s *cvService) GetEducation(ctx context.Context, id int64) (*models.EducationCV, error) {edu, err := s.cvRepository.GetEducation(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pendidikan tidak ditemukan")}return edu, nil}func (s *cvService) DeleteEducation(ctx context.Context, id int64) error {return s.cvRepository.DeleteEducation(ctx, id)}func (s *cvService) CreateJob(ctx context.Context, req *models.JobRequest) (*models.JobCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}job := &models.JobCV{AccountID: req.AccountID,InstitutionName: req.InstitutionName,CurrentJob: req.CurrentJob,YearStartedWorking: req.YearStartedWorking,MonthlyIncome: req.MonthlyIncome,IncomeSources: req.IncomeSources,}res, err := s.cvRepository.SaveJob(ctx, job)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data pekerjaan")}return res, nil}func (s *cvService) UpdateJob(ctx context.Context, id int64, req *models.JobRequest) (*models.JobCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}job, err := s.cvRepository.GetJob(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pekerjaan tidak ditemukan")}job.InstitutionName = req.InstitutionNamejob.CurrentJob = req.CurrentJobjob.YearStartedWorking = req.YearStartedWorkingjob.MonthlyIncome = req.MonthlyIncomejob.IncomeSources = req.IncomeSourcesres, err := s.cvRepository.SaveJob(ctx, job)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data pekerjaan")}return res, nil}func (s *cvService) ListJob(ctx context.Context, accountID int64) ([]models.JobCV, error) {return s.cvRepository.ListJob(ctx, accountID)}func (s *cvService) GetJob(ctx context.Context, id int64) (*models.JobCV, error) {job, err := s.cvRepository.GetJob(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pekerjaan tidak ditemukan")}return job, nil}func (s *cvService) DeleteJob(ctx context.Context, id int64) error {return s.cvRepository.DeleteJob(ctx, id)}func (s *cvService) CreateAchievement(ctx context.Context, req *models.AchievementRequest) (*models.AchievementCV, error) {ach := &models.AchievementCV{AccountID: req.AccountID,AchievementOrAward: req.AchievementOrAward,}res, err := s.cvRepository.SaveAchievement(ctx, ach)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data prestasi")}return res, nil}func (s *cvService) UpdateAchievement(ctx context.Context, id int64, req *models.AchievementRequest) (*models.AchievementCV, error) {ach, err := s.cvRepository.GetAchievement(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data prestasi tidak ditemukan")}ach.AchievementOrAward = req.AchievementOrAwardres, err := s.cvRepository.SaveAchievement(ctx, ach)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data prestasi")}return res, nil}func (s *cvService) ListAchievement(ctx context.Context, accountID int64) ([]models.AchievementCV, error) {return s.cvRepository.ListAchievement(ctx, accountID)}func (s *cvService) GetAchievement(ctx context.Context, id int64) (*models.AchievementCV, error) {ach, err := s.cvRepository.GetAchievement(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data prestasi tidak ditemukan")}return ach, nil}func (s *cvService) DeleteAchievement(ctx context.Context, id int64) error {return s.cvRepository.DeleteAchievement(ctx, id)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568package servicesimport ("context""errors""strconv""api.qobiltu.id/models""api.qobiltu.id/pkg/storage""api.qobiltu.id/pkg/validation""api.qobiltu.id/repositories""api.qobiltu.id/response""gorm.io/gorm")type CVService interface {SaveAccountDetails(ctx context.Context, req *models.AccountDetailsRequest) (*models.AccountDetails, error)GetAccountDetails(ctx context.Context, id int64) (*models.AccountDetails, error)SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCVRequest) (*models.PersonalityAndPreferenceCV, error)GetPersonalityAndPreference(ctx context.Context, id int64) (*models.PersonalityAndPreferenceCV, error)CreateFamilyMember(ctx context.Context, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error)UpdateFamilyMember(ctx context.Context, id int64, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error)ListFamilyMember(ctx context.Context, accountID int64) ([]models.FamilyMemberCV, error)GetFamilyMember(ctx context.Context, id int64) (*models.FamilyMemberCV, error)DeleteFamilyMember(ctx context.Context, id int64) errorSavePhysicalAndHealth(ctx context.Context, req *models.PhysicalAndHealthRequest) (*models.PhysicalAndHealthCV, error)GetPhysicalAndHealth(ctx context.Context, id int64) (*models.PhysicalAndHealthCV, error)SaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingRequest) (*models.WorshipAndReligiousUnderstandingCV, error)GetWorshipAndReligiousUnderstanding(ctx context.Context, id int64) (*models.WorshipAndReligiousUnderstandingCV, error)CreateEducation(ctx context.Context, req *models.EducationRequest) (*models.EducationCV, error)UpdateEducation(ctx context.Context, id int64, req *models.EducationRequest) (*models.EducationCV, error)ListEducation(ctx context.Context, accountID int64) ([]models.EducationCV, error)GetEducation(ctx context.Context, id int64) (*models.EducationCV, error)DeleteEducation(ctx context.Context, id int64) errorCreateJob(ctx context.Context, req *models.JobRequest) (*models.JobCV, error)UpdateJob(ctx context.Context, id int64, req *models.JobRequest) (*models.JobCV, error)ListJob(ctx context.Context, accountID int64) ([]models.JobCV, error)GetJob(ctx context.Context, id int64) (*models.JobCV, error)DeleteJob(ctx context.Context, id int64) errorCreateAchievement(ctx context.Context, req *models.AchievementRequest) (*models.AchievementCV, error)UpdateAchievement(ctx context.Context, id int64, req *models.AchievementRequest) (*models.AchievementCV, error)ListAchievement(ctx context.Context, accountID int64) ([]models.AchievementCV, error)GetAchievement(ctx context.Context, id int64) (*models.AchievementCV, error)DeleteAchievement(ctx context.Context, id int64) errorUploadProfileImage(ctx context.Context, req *models.UploadProfileImageRequest) (*models.UploadProfileImageResponse, error)}type cvService struct {cvRepository repositories.CVRepositorystorage storage.Storage}func NewCVService(cvRepository repositories.CVRepository, storage storage.Storage) CVService {return &cvService{cvRepository: cvRepository,storage: storage,}}func (s *cvService) SaveAccountDetails(ctx context.Context, req *models.AccountDetailsRequest) (*models.AccountDetails, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Ambil data lama jika adaaccountDetails, err := s.cvRepository.GetAccountDetailsByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Internal Server Error")}// Apply perubahanif accountDetails == nil {accountDetails = &models.AccountDetails{}}accountDetails.AccountID = uint(req.AccountID)accountDetails.FullName = req.FullNameaccountDetails.Gender = req.GenderaccountDetails.DateOfBirth = req.DateOfBirthaccountDetails.PlaceOfBirth = req.PlaceOfBirthaccountDetails.Domicile = req.DomicileaccountDetails.MaritalStatus = req.MaritalStatusaccountDetails.LastEducation = req.LastEducationaccountDetails.LastJob = req.LastJobif req.PhoneNumber != nil {sanitizedPhone := validation.SanitizePhoneNumber(*req.PhoneNumber)accountDetails.PhoneNumber = &sanitizedPhone}// Simpan datares, err := s.cvRepository.SaveAccountDetails(ctx, accountDetails)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) GetAccountDetails(ctx context.Context, id int64) (*models.AccountDetails, error) {res, err := s.cvRepository.GetAccountDetailsByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data diri tidak ditemukan")}return res, nil}func (s *cvService) SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCVRequest) (*models.PersonalityAndPreferenceCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Ambil data lama jika adapersonalityAndPreference, err := s.cvRepository.GetPersonalityAndPreferenceByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Internal Server Error")}// Apply perubahanif personalityAndPreference == nil {personalityAndPreference = &models.PersonalityAndPreferenceCV{}}personalityAndPreference.AccountID = req.AccountIDpersonalityAndPreference.PositiveTraits = req.PositiveTraitspersonalityAndPreference.NegativeTraits = req.NegativeTraitspersonalityAndPreference.Hobbies = req.HobbiespersonalityAndPreference.LifeGoals = req.LifeGoalspersonalityAndPreference.DailyActivities = req.DailyActivitiespersonalityAndPreference.LeisureActivities = req.LeisureActivitiespersonalityAndPreference.Likes = req.LikespersonalityAndPreference.Dislikes = req.DislikespersonalityAndPreference.StressHandling = req.StressHandlingpersonalityAndPreference.AngerTriggers = req.AngerTriggerspersonalityAndPreference.FavoriteFoodAndDrinks = req.FavoriteFoodAndDrinkspersonalityAndPreference.CanCook = req.CanCookpersonalityAndPreference.TypesOfDishesCooked = req.TypesOfDishesCookedpersonalityAndPreference.MonthlyExpenses = req.MonthlyExpensesres, err := s.cvRepository.SavePersonalityAndPreference(ctx, personalityAndPreference)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) GetPersonalityAndPreference(ctx context.Context, id int64) (*models.PersonalityAndPreferenceCV, error) {res, err := s.cvRepository.GetPersonalityAndPreferenceByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) CreateFamilyMember(ctx context.Context, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Mapping request ke modelfamilyMember := &models.FamilyMemberCV{AccountID: req.AccountID,Role: req.Role,Status: req.Status,Religion: req.Religion,Job: req.Job,LastEducation: req.LastEducation,Age: req.Age,}// Simpan ke repositoryres, err := s.cvRepository.SaveFamilyMember(ctx, familyMember)if err != nil {return nil, response.HandleGormError(err, "Gagal menyimpan anggota keluarga")}return res, nil}func (s *cvService) ListFamilyMember(ctx context.Context, accountID int64) ([]models.FamilyMemberCV, error) {list, err := s.cvRepository.ListFamilyMember(ctx, accountID)if err != nil {return nil, response.HandleGormError(err, "Gagal mengambil daftar anggota keluarga")}return list, nil}func (s *cvService) GetFamilyMember(ctx context.Context, id int64) (*models.FamilyMemberCV, error) {res, err := s.cvRepository.GetFamilyMember(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data anggota keluarga tidak ditemukan")}return res, nil}func (s *cvService) DeleteFamilyMember(ctx context.Context, id int64) error {err := s.cvRepository.DeleteFamilyMember(ctx, id)if err != nil {return response.HandleGormError(err, "Gagal menghapus anggota keluarga")}return nil}func (s *cvService) UpdateFamilyMember(ctx context.Context, id int64, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}existing, err := s.cvRepository.GetFamilyMember(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data anggota keluarga tidak ditemukan")}existing.Role = req.Roleexisting.Status = req.Statusexisting.Religion = req.Religionexisting.Job = req.Jobexisting.LastEducation = req.LastEducationexisting.Age = req.Ageupdated, err := s.cvRepository.SaveFamilyMember(ctx, existing)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui anggota keluarga")}return updated, nil}func (s *cvService) SavePhysicalAndHealth(ctx context.Context, req *models.PhysicalAndHealthRequest) (*models.PhysicalAndHealthCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Cek apakah data sudah ada berdasarkan account_idexisting, err := s.cvRepository.GetPhysicalAndHealthByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Terjadi kesalahan saat mengambil data fisik dan kesehatan")}// Jika belum ada, buat objek baruif existing == nil {existing = &models.PhysicalAndHealthCV{}}// Mapping field dari requestexisting.AccountID = req.AccountIDexisting.HeightInCm = req.HeightInCmexisting.WeightInKg = req.WeightInKgexisting.BodyShape = req.BodyShapeexisting.SkinColor = req.SkinColorexisting.HairType = req.HairTypeexisting.MedicalHistory = req.MedicalHistoryexisting.PhysicalDisorder = req.PhysicalDisorderexisting.PhysicalTraits = req.PhysicalTraits// Simpan datares, err := s.cvRepository.SavePhysicalAndHealth(ctx, existing)if err != nil {return nil, response.HandleGormError(err, "Gagal menyimpan data fisik dan kesehatan")}return res, nil}func (s *cvService) GetPhysicalAndHealth(ctx context.Context, id int64) (*models.PhysicalAndHealthCV, error) {res, err := s.cvRepository.GetPhysicalAndHealthByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data fisik dan kesehatan tidak ditemukan")}return res, nil}func (s *cvService) SaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingRequest) (*models.WorshipAndReligiousUnderstandingCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Cek apakah data sudah ada berdasarkan account_idworshipAndReligiousUnderstanding, err := s.cvRepository.GetWorshipAndReligiousUnderstandingByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Terjadi kesalahan saat mengambil data agama dan pemahaman agama")}// Jika belum ada, buat objek baruif worshipAndReligiousUnderstanding == nil {worshipAndReligiousUnderstanding = &models.WorshipAndReligiousUnderstandingCV{}}// Mapping field dari requestworshipAndReligiousUnderstanding.AccountID = req.AccountIDworshipAndReligiousUnderstanding.ObligatoryPrayer = req.ObligatoryPrayerworshipAndReligiousUnderstanding.CongregationalPrayer = req.CongregationalPrayerworshipAndReligiousUnderstanding.TahajjudPrayer = req.TahajjudPrayerworshipAndReligiousUnderstanding.DhuhaPrayer = req.DhuhaPrayerworshipAndReligiousUnderstanding.QuranMemorization = req.QuranMemorizationworshipAndReligiousUnderstanding.QuranReadingAbility = req.QuranReadingAbilityworshipAndReligiousUnderstanding.DaudFasting = req.DaudFastingworshipAndReligiousUnderstanding.AyyamulBidhFasting = req.AyyamulBidhFastingworshipAndReligiousUnderstanding.HajjOrUmrah = req.HajjOrUmrahworshipAndReligiousUnderstanding.ListeningToMusic = req.ListeningToMusicworshipAndReligiousUnderstanding.OpinionOnIkhtilat = req.OpinionOnIkhtilatworshipAndReligiousUnderstanding.OpinionOnTouchingNonMahram = req.OpinionOnTouchingNonMahramworshipAndReligiousUnderstanding.OpinionOnVeil = req.OpinionOnVeilworshipAndReligiousUnderstanding.WeeklyReligiousStudies = req.WeeklyReligiousStudiesworshipAndReligiousUnderstanding.FollowedUstadz = req.FollowedUstadz// Simpan datares, err := s.cvRepository.SaveWorshipAndReligiousUnderstanding(ctx, worshipAndReligiousUnderstanding)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) GetWorshipAndReligiousUnderstanding(ctx context.Context, id int64) (*models.WorshipAndReligiousUnderstandingCV, error) {res, err := s.cvRepository.GetWorshipAndReligiousUnderstandingByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data agama dan pemahaman agama tidak ditemukan")}return res, nil}func (s *cvService) CreateEducation(ctx context.Context, req *models.EducationRequest) (*models.EducationCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}edu := &models.EducationCV{AccountID: req.AccountID,LastEducation: req.LastEducation,EducationInstitute: req.EducationInstitute,EducationMajor: req.EducationMajor,YearStart: req.YearStart,YearGraduate: req.YearGraduate,}res, err := s.cvRepository.SaveEducation(ctx, edu)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data pendidikan")}return res, nil}func (s *cvService) UpdateEducation(ctx context.Context, id int64, req *models.EducationRequest) (*models.EducationCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}edu, err := s.cvRepository.GetEducation(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pendidikan tidak ditemukan")}edu.LastEducation = req.LastEducationedu.EducationInstitute = req.EducationInstituteedu.EducationMajor = req.EducationMajoredu.YearStart = req.YearStartedu.YearGraduate = req.YearGraduateres, err := s.cvRepository.SaveEducation(ctx, edu)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data pendidikan")}return res, nil}func (s *cvService) ListEducation(ctx context.Context, accountID int64) ([]models.EducationCV, error) {return s.cvRepository.ListEducation(ctx, accountID)}func (s *cvService) GetEducation(ctx context.Context, id int64) (*models.EducationCV, error) {edu, err := s.cvRepository.GetEducation(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pendidikan tidak ditemukan")}return edu, nil}func (s *cvService) DeleteEducation(ctx context.Context, id int64) error {return s.cvRepository.DeleteEducation(ctx, id)}func (s *cvService) CreateJob(ctx context.Context, req *models.JobRequest) (*models.JobCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}job := &models.JobCV{AccountID: req.AccountID,InstitutionName: req.InstitutionName,CurrentJob: req.CurrentJob,YearStartedWorking: req.YearStartedWorking,MonthlyIncome: req.MonthlyIncome,IncomeSources: req.IncomeSources,}res, err := s.cvRepository.SaveJob(ctx, job)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data pekerjaan")}return res, nil}func (s *cvService) UpdateJob(ctx context.Context, id int64, req *models.JobRequest) (*models.JobCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}job, err := s.cvRepository.GetJob(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pekerjaan tidak ditemukan")}job.InstitutionName = req.InstitutionNamejob.CurrentJob = req.CurrentJobjob.YearStartedWorking = req.YearStartedWorkingjob.MonthlyIncome = req.MonthlyIncomejob.IncomeSources = req.IncomeSourcesres, err := s.cvRepository.SaveJob(ctx, job)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data pekerjaan")}return res, nil}func (s *cvService) ListJob(ctx context.Context, accountID int64) ([]models.JobCV, error) {return s.cvRepository.ListJob(ctx, accountID)}func (s *cvService) GetJob(ctx context.Context, id int64) (*models.JobCV, error) {job, err := s.cvRepository.GetJob(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pekerjaan tidak ditemukan")}return job, nil}func (s *cvService) DeleteJob(ctx context.Context, id int64) error {return s.cvRepository.DeleteJob(ctx, id)}func (s *cvService) CreateAchievement(ctx context.Context, req *models.AchievementRequest) (*models.AchievementCV, error) {ach := &models.AchievementCV{AccountID: req.AccountID,AchievementOrAward: req.AchievementOrAward,}res, err := s.cvRepository.SaveAchievement(ctx, ach)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data prestasi")}return res, nil}func (s *cvService) UpdateAchievement(ctx context.Context, id int64, req *models.AchievementRequest) (*models.AchievementCV, error) {ach, err := s.cvRepository.GetAchievement(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data prestasi tidak ditemukan")}ach.AchievementOrAward = req.AchievementOrAwardres, err := s.cvRepository.SaveAchievement(ctx, ach)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data prestasi")}return res, nil}func (s *cvService) ListAchievement(ctx context.Context, accountID int64) ([]models.AchievementCV, error) {return s.cvRepository.ListAchievement(ctx, accountID)}func (s *cvService) GetAchievement(ctx context.Context, id int64) (*models.AchievementCV, error) {ach, err := s.cvRepository.GetAchievement(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data prestasi tidak ditemukan")}return ach, nil}func (s *cvService) DeleteAchievement(ctx context.Context, id int64) error {return s.cvRepository.DeleteAchievement(ctx, id)}func (s *cvService) UploadProfileImage(ctx context.Context, req *models.UploadProfileImageRequest) (*models.UploadProfileImageResponse, error) {if req.File == nil {return nil, models.Exception{BadRequest: true,Message: "No file uploaded",Err: storage.ErrNoFileUploaded,}}var maxFileSize int64 = 5 << 20 // 5MBif req.File.Size > maxFileSize {return nil, models.Exception{BadRequest: true,Message: "File too large, max size is 5MB",Err: storage.ErrFileTooLarge,}}if !s.storage.ValidateExtension(storage.ProfileImage, req.File.Filename) {return nil, models.Exception{BadRequest: true,Message: "Invalid file extension",Err: storage.ErrInvalidFileType,}}accountDetails, err := s.cvRepository.GetAccountDetailsByAccountID(ctx, req.AccountID)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}filename := s.storage.GenerateFilename(req.File.Filename)path := s.storage.GetPath(storage.ProfileImage, strconv.Itoa(int(req.AccountID)), filename)file, err := req.File.Open()if err != nil {return nil, models.Exception{InternalServerError: true,Message: "Internal Server Error",Err: err,}}defer file.Close()if err := s.storage.Upload(ctx, file, path); err != nil {return nil, models.Exception{InternalServerError: true,Message: "Internal Server Error",Err: err,}}// remove old avatarif accountDetails.Avatar != nil {s.storage.Delete(ctx, *accountDetails.Avatar)}url := s.storage.GetURL(path)accountDetails.Avatar = &url_, err = s.cvRepository.SaveAccountDetails(ctx, accountDetails)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return &models.UploadProfileImageResponse{URL: url,}, nil}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101package servicesimport ("api.qobiltu.id/utils""api.qobiltu.id/worker""context""github.com/hibiken/asynq""strconv""time""api.qobiltu.id/config""api.qobiltu.id/models""api.qobiltu.id/repositories"uuid "github.com/satori/go.uuid")type EmailVerificationService struct {Service[models.EmailVerification, models.EmailVerification]}func (s *EmailVerificationService) Create() {accountRepo := repositories.GetAccountById(s.Constructor.AccountID)if accountRepo.NoRecord {s.Error = accountRepo.RowsErrors.Exception.DataNotFound = trues.Exception.Message = "There is no account data with given credentials!"return}token, err := utils.GenerateToken()if err != nil {s.Error = errs.Exception.InternalServerError = trues.Exception.Message = "failed to generate token for email verification"return}remainingTime := time.Duration(config.EMAIL_VERIFICATION_DURATION) * time.HourdueTime := CalculateDueTime(remainingTime)s.Constructor.UUID = uuid.NewV4()repo := repositories.CreateEmailVerification(s.Constructor.UUID, s.Constructor.AccountID, dueTime, uint(token))s.Error = repo.RowsErrors.Result = repo.Resultif s.Error != nil {return}err = worker.AsyncTaskDistributor.DistributeTaskSendVerifyEmail(context.Background(),&worker.PayloadSendVerifyEmail{EmailAddress: accountRepo.Result.Email,VerificationCode: strconv.Itoa(int(token)),ExpirationInMinutes: int(remainingTime.Minutes()),Subject: worker.TaskSendVerifyEmailSubject,},[]asynq.Option{asynq.MaxRetry(worker.TaskSendVerifyEmailMaxRetry),asynq.Queue(worker.Critical),}...)if err != nil {s.Error = errs.Exception.InternalServerError = trues.Exception.Message = "failed to send email verification"return}}func (s *EmailVerificationService) Validate() {repo := repositories.GetEmailVerification(s.Constructor.AccountID, s.Constructor.Token)s.Error = repo.RowsErrorif repo.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "Invalid token!"return}if repo.Result.ExpiredAt.Before(time.Now()) {s.Exception.Unauthorized = trues.Exception.Message = "Token has expired!"repositories.UpdateExpiredEmailVerification(s.Constructor.UUID)s.Delete()return}account := repositories.GetAccountById(repo.Result.AccountID)account.Result.IsEmailVerified = truerepositories.UpdateAccount(account.Result)s.Result = repo.Result}func (s *EmailVerificationService) Delete() {repo := repositories.DeleteEmailVerification(s.Constructor.Token)s.Error = repo.RowsErrorif repo.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "Invalid token!"return}s.Result = repo.Result}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101package servicesimport ("api.qobiltu.id/pkg/worker""api.qobiltu.id/utils""context""github.com/hibiken/asynq""strconv""time""api.qobiltu.id/config""api.qobiltu.id/models""api.qobiltu.id/repositories"uuid "github.com/satori/go.uuid")type EmailVerificationService struct {Service[models.EmailVerification, models.EmailVerification]}func (s *EmailVerificationService) Create() {accountRepo := repositories.GetAccountById(s.Constructor.AccountID)if accountRepo.NoRecord {s.Error = accountRepo.RowsErrors.Exception.DataNotFound = trues.Exception.Message = "There is no account data with given credentials!"return}token, err := utils.GenerateToken()if err != nil {s.Error = errs.Exception.InternalServerError = trues.Exception.Message = "failed to generate token for email verification"return}remainingTime := time.Duration(config.EMAIL_VERIFICATION_DURATION) * time.HourdueTime := CalculateDueTime(remainingTime)s.Constructor.UUID = uuid.NewV4()repo := repositories.CreateEmailVerification(s.Constructor.UUID, s.Constructor.AccountID, dueTime, uint(token))s.Error = repo.RowsErrors.Result = repo.Resultif s.Error != nil {return}err = worker.AsyncTaskDistributor.DistributeTaskSendVerifyEmail(context.Background(),&worker.PayloadSendVerifyEmail{EmailAddress: accountRepo.Result.Email,VerificationCode: strconv.Itoa(int(token)),ExpirationInMinutes: int(remainingTime.Minutes()),Subject: worker.TaskSendVerifyEmailSubject,},[]asynq.Option{asynq.MaxRetry(worker.TaskSendVerifyEmailMaxRetry),asynq.Queue(worker.Critical),}...)if err != nil {s.Error = errs.Exception.InternalServerError = trues.Exception.Message = "failed to send email verification"return}}func (s *EmailVerificationService) Validate() {repo := repositories.GetEmailVerification(s.Constructor.AccountID, s.Constructor.Token)s.Error = repo.RowsErrorif repo.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "Invalid token!"return}if repo.Result.ExpiredAt.Before(time.Now()) {s.Exception.Unauthorized = trues.Exception.Message = "Token has expired!"repositories.UpdateExpiredEmailVerification(s.Constructor.UUID)s.Delete()return}account := repositories.GetAccountById(repo.Result.AccountID)account.Result.IsEmailVerified = truerepositories.UpdateAccount(account.Result)s.Result = repo.Result}func (s *EmailVerificationService) Delete() {repo := repositories.DeleteEmailVerification(s.Constructor.Token)s.Error = repo.RowsErrorif repo.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "Invalid token!"return}s.Result = repo.Result}
12345678package servicesimport ("api.qobiltu.id/utils""api.qobiltu.id/worker""context""github.com/hibiken/asynq""strconv"12345678package servicesimport ("api.qobiltu.id/pkg/worker""api.qobiltu.id/utils""context""github.com/hibiken/asynq""strconv"
6 unmodified lines7896 unmodified lineslogs/.ideamy-notes6 unmodified lines789106 unmodified lineslogs/.ideamy-notesuploads
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162package validation
import ( "strings" "sync"
v10 "github.com/go-playground/validator/v10" "gorm.io/gorm")
type ValidOptionSource interface { GetValidOptions(key string) ([]string, error) GetValidKeys() []string}
// --------------------// InMemoryOptionSource// --------------------
type InMemoryOptionSource struct{}
var inMemoryOptions = map[string][]string{ "last_education": {"SD", "SMP", "SMA", "D1", "D2", "D3", "D4", "D5", "S1", "S2", "S3"}, "marital_status": {"Belum Menikah", "Duda", "Janda"}, "gender": {"Laki-laki", "Perempuan"}, "monthly_expenses": {"< 2 Juta", "2-5 Juta", "5-20 Juta", "> 10 Juta"}, "monthly_income": {"< 3 Juta", "3-5 Juta", "5-10 Juta", "> 10 Juta"}, "religion": {"Islam", "Non-Islam"}, "family_role": {"Ayah", "Ibu", "Kakak", "Adik", "Anak"}, "life_status": {"Hidup", "Wafat"}, "body_shape": {"Ideal", "Kurus", "Berisi", "Gemuk"}, "skin_color": {"Putih", "Kuning Langsat", "Sawo Matang"}, "hair_type": {"Lurus", "Bergelombang", "Keriting"}, "frequently": {"Selalu", "Sering", "Kadang", "Jarang"}, "quran_reading_ability": {"Lancar", "Menengah", "Perlu Bimbingan"},}
func (s *InMemoryOptionSource) GetValidOptions(key string) ([]string, error) { return inMemoryOptions[key], nil}
func (s *InMemoryOptionSource) GetValidKeys() []string { keys := make([]string, 0, len(inMemoryOptions)) for k := range inMemoryOptions { keys = append(keys, k) } return keys}
// --------------------// DBOptionSource// --------------------
type DBOptionSource struct { options map[string][]string mu sync.RWMutex}
type ( OptionCategory struct { ID int64 `gorm:"primaryKey" json:"id"` OptionName string `json:"option_name"` OptionSlug string `json:"option_slug" gorm:"uniqueIndex"` }
OptionValues struct { ID int64 `gorm:"primaryKey" json:"id"` OptionCategoryID int64 `json:"option_category_id"` OptionValue string `json:"option_value"` })
func NewDBOptionSource(db *gorm.DB) (*DBOptionSource, error) { var categories []OptionCategory if err := db.Find(&categories).Error; err != nil { return nil, err }
options := make(map[string][]string) for _, cat := range categories { var values []OptionValues if err := db.Where("option_category_id = ?", cat.ID).Find(&values).Error; err != nil { return nil, err } for _, val := range values { options[cat.OptionSlug] = append(options[cat.OptionSlug], val.OptionValue) } }
return &DBOptionSource{options: options}, nil}
func (s *DBOptionSource) GetValidOptions(key string) ([]string, error) { s.mu.RLock() defer s.mu.RUnlock() return s.options[key], nil}
func (s *DBOptionSource) GetValidKeys() []string { s.mu.RLock() defer s.mu.RUnlock() keys := make([]string, 0, len(s.options)) for k := range s.options { keys = append(keys, k) } return keys}
// --------------------// Validator// --------------------
type Validator struct { source ValidOptionSource}
func NewValidatorRules(source ValidOptionSource) *Validator { return &Validator{source: source}}
func (v *Validator) GenericOptionRule(key string) func(fl v10.FieldLevel) bool { return func(fl v10.FieldLevel) bool { value := fl.Field().String() if value == "" { return true } validOptions, err := v.source.GetValidOptions(key) if err != nil { return false } for _, opt := range validOptions { if opt == value { return true } } return false }}
func (v *Validator) RegisterAllCustomRules(validate *v10.Validate) error { for _, key := range v.source.GetValidKeys() { err := validate.RegisterValidation(key, v.GenericOptionRule(key)) if err != nil { return err } }
err := validate.RegisterValidation("password", v.PasswordRule) if err != nil { return err }
return nil}
func (v *Validator) PasswordRule(fl v10.FieldLevel) bool { password := fl.Field().String() return len(password) >= 8 && strings.ContainsAny(password, "abcdefghijklmnopqrstuvwxyz") && strings.ContainsAny(password, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") && strings.ContainsAny(password, "0123456789")}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164package validation
import ( "errors" "fmt" "strings"
"github.com/go-playground/locales/en" "github.com/go-playground/locales/id" ut "github.com/go-playground/universal-translator" v10 "github.com/go-playground/validator/v10" entranslations "github.com/go-playground/validator/v10/translations/en" idtranslations "github.com/go-playground/validator/v10/translations/id")
// Constants for supported localesconst ( LocaleID = "id" LocaleEN = "en")
// ErrorMessage represents a validation error messagetype ErrorMessage struct { Field string `json:"field"` Message string `json:"-"`}
type validator struct { validate *v10.Validate translator ut.Translator}
// validatorInstance adalah instance global dari validator.var validatorInstance *validator
// New creates a new validation instance with the specified locale// dan menginisialisasi instance global validatorInstance.func New(locale string) error { v := &validator{} parsedLocale := parseLocale(locale)
uni := ut.New(en.New(), id.New(), en.New()) translator, found := uni.GetTranslator(parsedLocale) if !found { return fmt.Errorf("translator not found for locale: %s", parsedLocale) }
validate := v10.New()
if err := setupValidations(validate); err != nil { return fmt.Errorf("failed to setup validations: %w", err) }
if err := setupTranslations(validate, translator, parsedLocale); err != nil { return fmt.Errorf("failed to setup translations for locale %s: %w", parsedLocale, err) }
v.validate = validate v.translator = translator
validatorInstance = v // Inisialisasi instance global return nil}
func parseLocale(locale string) string { switch strings.ToLower(locale) { case "id": return LocaleID case "en": return LocaleEN default: return LocaleID // Default to Indonesian }}
// setupValidations configures custom validation rules.func setupValidations(validate *v10.Validate) error { rules := NewValidatorRules(&InMemoryOptionSource{}) if err := rules.RegisterAllCustomRules(validate); err != nil { return err } return nil}
// setupTranslations configures translations for validation messages.func setupTranslations(validate *v10.Validate, translator ut.Translator, locale string) error { // Register default translations based on locale if err := registerDefaultTranslations(validate, translator, locale); err != nil { return fmt.Errorf("failed to register default translations for locale %s: %w", locale, err) }
// Register custom password validation translation err := validate.RegisterTranslation("password", translator, func(ut ut.Translator) error { return ut.Add("password", "harus mengandung minimal 8 karakter, huruf besar, huruf kecil, dan angka.", true) }, func(ut ut.Translator, fe v10.FieldError) string { translated, err := ut.T(fe.Tag(), fe.Field()) if err != nil { return fe.Field() + " is invalid" } return translated }, ) if err != nil { return fmt.Errorf("failed to register password translation: %w", err) }
return nil}
// registerDefaultTranslations sets up default translations for the specified locale.func registerDefaultTranslations(validate *v10.Validate, translator ut.Translator, locale string) error { switch locale { case LocaleID: return idtranslations.RegisterDefaultTranslations(validate, translator) case LocaleEN: return entranslations.RegisterDefaultTranslations(validate, translator) default: // Fallback to English if the locale is not supported return entranslations.RegisterDefaultTranslations(validate, translator) }}
// Validate validates a struct using the global validator instance// and returns a slice of ErrorMessage.func Validate(s any) []ErrorMessage { if validatorInstance == nil { return []ErrorMessage{{Field: "", Message: "Validator belum diinisialisasi. Panggil validation.New() terlebih dahulu."}} } err := validatorInstance.validate.Struct(s) if err != nil { return TranslateError(err) } return nil}
// TranslateError takes a validation error and translates it using the global translator.func TranslateError(err error) []ErrorMessage { if validatorInstance == nil { return nil }
var validationErrors v10.ValidationErrors if !errors.As(err, &validationErrors) { return nil }
errorMessages := make([]ErrorMessage, 0, len(validationErrors)) for _, e := range validationErrors { fieldLabel := e.Field() msg, err := validatorInstance.translator.T(e.Tag(), fieldLabel) if err != nil { msg = fieldLabel + " is Invalid" }
errorMessages = append(errorMessages, ErrorMessage{ Field: e.Tag(), Message: msg, }) }
return errorMessages}1234567891011121314151617181920212223package worker
import ( "context" "github.com/hibiken/asynq")
type TaskDistributor interface { DistributeTaskSendVerifyEmail( ctx context.Context, payload *PayloadSendVerifyEmail, opts ...asynq.Option, ) error
DistributeTaskSendForgotPasswordEmail( ctx context.Context, payload *PayloadSendForgotPasswordEmail, opts ...asynq.Option, ) error}
// AsyncTaskDistributor is a global variable to hold the task distributorvar AsyncTaskDistributor TaskDistributor12345678910111213141516171819202122232425262728293031323334353637package worker
import ( "context" "fmt" "log/slog")
type Logger struct{}
func NewLogger() *Logger { return &Logger{}}
func (logger *Logger) Printf(ctx context.Context, format string, v ...interface{}) { slog.Info(fmt.Sprintf(format, v...))}
func (logger *Logger) Debug(args ...interface{}) { slog.Debug(fmt.Sprint(args...))}
func (logger *Logger) Info(args ...interface{}) { slog.Info(fmt.Sprint(args...))}
func (logger *Logger) Warn(args ...interface{}) { slog.Warn(fmt.Sprint(args...))}
func (logger *Logger) Error(args ...interface{}) { slog.Error(fmt.Sprint(args...))}
func (logger *Logger) Fatal(args ...interface{}) { slog.Error(fmt.Sprint(args...))}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566package worker
import ( "api.qobiltu.id/mail" "context" "github.com/hibiken/asynq" "github.com/redis/go-redis/v9" "log/slog")
const ( Low = "low" Default = "default" Critical = "critical")
type TaskProcessor interface { Start() error Shutdown() ProcessTaskSendVerifyEmail(ctx context.Context, task *asynq.Task) error ProcessTaskSendForgotPasswordEmail(ctx context.Context, task *asynq.Task) error}
type RedisTaskProcessor struct { server *asynq.Server emailSender mail.Sender}
func NewRedisTaskProcessor(redisOpt asynq.RedisClientOpt, emailSender mail.Sender) TaskProcessor { logger := NewLogger() redis.SetLogger(logger)
server := asynq.NewServer( redisOpt, asynq.Config{ // priority value. Keys are the names of the queues and values are associated priority value. Queues: map[string]int{ Critical: 6, Default: 3, Low: 1, }, ErrorHandler: asynq.ErrorHandlerFunc(func(ctx context.Context, task *asynq.Task, err error) { slog.Error("process task failed", "error", err, "type", task.Type(), "payload", string(task.Payload())) }), // maximum number of concurrent processing of tasks. Concurrency: 50, Logger: logger, }, )
return &RedisTaskProcessor{ server: server, emailSender: emailSender, }}
func (p *RedisTaskProcessor) Start() error { mux := asynq.NewServeMux() mux.HandleFunc(TaskSendVerifyEmail, p.ProcessTaskSendVerifyEmail) mux.HandleFunc(TaskSendForgotPasswordEmail, p.ProcessTaskSendForgotPasswordEmail) return p.server.Start(mux)}
func (p *RedisTaskProcessor) Shutdown() { p.server.Shutdown()}12345678910111213141516package worker
import ( "github.com/hibiken/asynq")
type RedisTaskDistributor struct { client *asynq.Client}
func NewRedisTaskDistributor(redisOpt asynq.RedisClientOpt) TaskDistributor { client := asynq.NewClient(redisOpt) return &RedisTaskDistributor{ client: client, }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475package worker
import ( "api.qobiltu.id/assets" "bytes" "context" "encoding/json" "fmt" "github.com/hibiken/asynq" "html/template" "log/slog")
const ( TaskSendForgotPasswordEmailMaxRetry = 5 TaskSendForgotPasswordEmail = "task:send_forgot_password_email" TaskSendForgotPasswordEmailSubject = "Permintaan Reset Password")
type PayloadSendForgotPasswordEmail struct { EmailAddress string `json:"email_address"` ResetToken string `json:"reset_token"` ExpirationInMinutes int `json:"expiration_in_minutes"` Subject string `json:"subject"` AppName string `json:"app_name"`}
func (d *RedisTaskDistributor) DistributeTaskSendForgotPasswordEmail( ctx context.Context, payload *PayloadSendForgotPasswordEmail, opts ...asynq.Option,) error { jsonPayload, err := json.Marshal(payload) if err != nil { return fmt.Errorf("failed to marshal task payload: %w", err) }
task := asynq.NewTask(TaskSendForgotPasswordEmail, jsonPayload, opts...)
_, err = d.client.EnqueueContext(ctx, task) if err != nil { return fmt.Errorf("failed to enqueue task: %w", err) }
return nil}
func (p *RedisTaskProcessor) ProcessTaskSendForgotPasswordEmail(ctx context.Context, task *asynq.Task) error { var payload PayloadSendForgotPasswordEmail if err := json.Unmarshal(task.Payload(), &payload); err != nil { return fmt.Errorf("failed to unmarshal payload: %w", asynq.SkipRetry) }
var tmpl *template.Template tmpl, err := template.ParseFS(assets.EmbeddedFiles, assets.EmailForgotPasswordTemplatePath) if err != nil { return fmt.Errorf("failed to parse forgot password email template: %w", err) } var body bytes.Buffer if err := tmpl.ExecuteTemplate(&body, "htmlBody", payload); err != nil { return fmt.Errorf("failed to execute forgot password email template: %w", err) } htmlContent := body.String()
slog.Info("Sending forgot password email", slog.String("email", payload.EmailAddress))
err = p.emailSender.Send(payload.EmailAddress, payload.Subject, htmlContent, payload) if err != nil { return fmt.Errorf("failed to send forgot password email: %w", err) }
slog.Info("Forgot password email sent successfully", slog.String("email", payload.EmailAddress))
return nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475package worker
import ( "api.qobiltu.id/assets" "bytes" "context" "encoding/json" "fmt" "github.com/hibiken/asynq" "html/template" "log/slog")
const ( TaskSendVerifyEmailMaxRetry = 3 TaskSendVerifyEmail = "task:send_verify_email" TaskSendVerifyEmailSubject = "Verifikasi Email")
type PayloadSendVerifyEmail struct { EmailAddress string `json:"email_address"` VerificationCode string `json:"verification_code"` ExpirationInMinutes int `json:"expiration_in_minutes"` Subject string `json:"subject"`}
func (d *RedisTaskDistributor) DistributeTaskSendVerifyEmail( ctx context.Context, payload *PayloadSendVerifyEmail, opts ...asynq.Option,) error { jsonPayload, err := json.Marshal(payload) if err != nil { return fmt.Errorf("failed to marshal task payload: %w", err) }
task := asynq.NewTask(TaskSendVerifyEmail, jsonPayload, opts...)
_, err = d.client.EnqueueContext(ctx, task) if err != nil { return fmt.Errorf("failed to enqueue task: %w", err) }
return nil}
func (p *RedisTaskProcessor) ProcessTaskSendVerifyEmail(ctx context.Context, task *asynq.Task) error { var payload PayloadSendVerifyEmail if err := json.Unmarshal(task.Payload(), &payload); err != nil { return fmt.Errorf("failed to unmarshal payload: %w", asynq.SkipRetry) }
var tmpl *template.Template tmpl, err := template.ParseFS(assets.EmbeddedFiles, assets.EmailConfirmationTemplatePath) if err != nil { return fmt.Errorf("failed to parse email template: %w", err) }
var body bytes.Buffer if err := tmpl.ExecuteTemplate(&body, "htmlBody", payload); err != nil { return fmt.Errorf("failed to execute email template: %w", err) } htmlContent := body.String()
slog.Info("Sending verification email", slog.String("email", payload.EmailAddress))
err = p.emailSender.Send(payload.EmailAddress, payload.Subject, htmlContent, payload) if err != nil { return fmt.Errorf("failed to send verify email: %w", err) }
slog.Info("Verification email sent successfully", slog.String("email", payload.EmailAddress))
return nil}8 unmodified lines910111213143 unmodified lines1819202122238 unmodified lines"api.qobiltu.id/router""api.qobiltu.id/services""api.qobiltu.id/utils""api.qobiltu.id/worker""github.com/hibiken/asynq""log/slog"3 unmodified linesfunc main() {// setup email senderemailConfig := mail.Config{Host: config.SMTP_HOST,8 unmodified lines91011121314153 unmodified lines192021222324252627288 unmodified lines"api.qobiltu.id/router""api.qobiltu.id/services""api.qobiltu.id/utils""api.qobiltu.id/validation""api.qobiltu.id/worker""github.com/hibiken/asynq""log/slog"3 unmodified linesfunc main() {// setup validationerr := validation.New(validation.LocaleID)utils.FatalIfErr("failed to setup validator", err)// setup email senderemailConfig := mail.Config{Host: config.SMTP_HOST,
1234567891011121314151617181920212223package modelstype Exception struct {Unauthorized bool `json:"unauthorized,omitempty"`BadRequest bool `json:"bad_request,omitempty"`DataNotFound bool `json:"data_not_found,omitempty"`InternalServerError bool `json:"internal_server_error,omitempty"`DataDuplicate bool `json:"data_duplicate,omitempty"`QueryError bool `json:"query_error,omitempty"`InvalidPasswordLength bool `json:"invalid_password_length,omitempty"`IsPassTheLimit bool `json:"is_pass_the_limit,omitempty"`IsTimeOut bool `json:"is_time_out,omitempty"`AttemptNotFound bool `json:"attempt_not_found,omitempty"`Forbidden bool `json:"forbidden,omitempty"`ValidationError bool `json:"validation_error,omitempty"`Message string `json:"message,omitempty"`Err error `json:"-"`}func (a Exception) Error() string {return a.Err.Error()}1234567891011121314151617181920212223242526package modelsimport "api.qobiltu.id/validation"type Exception struct {Unauthorized bool `json:"unauthorized,omitempty"`BadRequest bool `json:"bad_request,omitempty"`DataNotFound bool `json:"data_not_found,omitempty"`InternalServerError bool `json:"internal_server_error,omitempty"`DataDuplicate bool `json:"data_duplicate,omitempty"`QueryError bool `json:"query_error,omitempty"`InvalidPasswordLength bool `json:"invalid_password_length,omitempty"`IsPassTheLimit bool `json:"is_pass_the_limit,omitempty"`IsTimeOut bool `json:"is_time_out,omitempty"`AttemptNotFound bool `json:"attempt_not_found,omitempty"`Forbidden bool `json:"forbidden,omitempty"`ValidationError bool `json:"validation_error,omitempty"`Message string `json:"message,omitempty"`Err error `json:"-"`ValidationErrorFields []validation.ErrorMessage `json:"validation_error_fields,omitempty"`}func (a Exception) Error() string {return a.Err.Error()}
2 unmodified lines34567830 unmodified lines3940414243444531 unmodified lines7778792 unmodified linesimport ("api.qobiltu.id/models""api.qobiltu.id/utils""errors""net/http"30 unmodified linescase exception.AttemptNotFound:responseError(c, http.StatusNotFound, exception)case exception.ValidationError:responseError(c, http.StatusUnprocessableEntity, exception)default:responseError(c, http.StatusInternalServerError, exception)}31 unmodified linesc.AbortWithStatusJSON(status, res)return}2 unmodified lines345678930 unmodified lines4041424344454631 unmodified lines78798081828384858687888990919293942 unmodified linesimport ("api.qobiltu.id/models""api.qobiltu.id/utils""api.qobiltu.id/validation""errors""net/http"30 unmodified linescase exception.AttemptNotFound:responseError(c, http.StatusNotFound, exception)case exception.ValidationError:responseValidationError(c, http.StatusUnprocessableEntity, exception.ValidationErrorFields) // Gunakan fungsi khusus untuk validasidefault:responseError(c, http.StatusInternalServerError, exception)}31 unmodified linesc.AbortWithStatusJSON(status, res)return}func responseValidationError(c *gin.Context, status int, validationErrors []validation.ErrorMessage) {res := models.ErrorResponse{Status: "error",Message: "Validasi data gagal.",Errors: models.Exception{ValidationError: true,ValidationErrorFields: validationErrors,},}c.AbortWithStatusJSON(status, res)return}
1234567891011121314package response
import ( "api.qobiltu.id/models" "api.qobiltu.id/validation")
func HandleValidationError(validationErrors []validation.ErrorMessage) error { return models.Exception{ ValidationError: true, Message: "Validation failed", ValidationErrorFields: validationErrors, }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444package servicesimport ("api.qobiltu.id/models""api.qobiltu.id/repositories""api.qobiltu.id/response""context""errors""gorm.io/gorm")type CVService interface {SaveAccountDetails(ctx context.Context, req *models.AccountDetailsRequest) (*models.AccountDetails, error)GetAccountDetails(ctx context.Context, id int64) (*models.AccountDetails, error)SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCVRequest) (*models.PersonalityAndPreferenceCV, error)GetPersonalityAndPreference(ctx context.Context, id int64) (*models.PersonalityAndPreferenceCV, error)CreateFamilyMember(ctx context.Context, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error)UpdateFamilyMember(ctx context.Context, id int64, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error)ListFamilyMember(ctx context.Context, accountID int64) ([]models.FamilyMemberCV, error)GetFamilyMember(ctx context.Context, id int64) (*models.FamilyMemberCV, error)DeleteFamilyMember(ctx context.Context, id int64) errorSavePhysicalAndHealth(ctx context.Context, req *models.PhysicalAndHealthRequest) (*models.PhysicalAndHealthCV, error)GetPhysicalAndHealth(ctx context.Context, id int64) (*models.PhysicalAndHealthCV, error)SaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingRequest) (*models.WorshipAndReligiousUnderstandingCV, error)GetWorshipAndReligiousUnderstanding(ctx context.Context, id int64) (*models.WorshipAndReligiousUnderstandingCV, error)CreateEducation(ctx context.Context, req *models.EducationRequest) (*models.EducationCV, error)UpdateEducation(ctx context.Context, id int64, req *models.EducationRequest) (*models.EducationCV, error)ListEducation(ctx context.Context, accountID int64) ([]models.EducationCV, error)GetEducation(ctx context.Context, id int64) (*models.EducationCV, error)DeleteEducation(ctx context.Context, id int64) errorCreateJob(ctx context.Context, req *models.JobRequest) (*models.JobCV, error)UpdateJob(ctx context.Context, id int64, req *models.JobRequest) (*models.JobCV, error)ListJob(ctx context.Context, accountID int64) ([]models.JobCV, error)GetJob(ctx context.Context, id int64) (*models.JobCV, error)DeleteJob(ctx context.Context, id int64) errorCreateAchievement(ctx context.Context, req *models.AchievementRequest) (*models.AchievementCV, error)UpdateAchievement(ctx context.Context, id int64, req *models.AchievementRequest) (*models.AchievementCV, error)ListAchievement(ctx context.Context, accountID int64) ([]models.AchievementCV, error)GetAchievement(ctx context.Context, id int64) (*models.AchievementCV, error)DeleteAchievement(ctx context.Context, id int64) error}type cvService struct {cvRepository repositories.CVRepository}func NewCVService(cvRepository repositories.CVRepository) CVService {return &cvService{cvRepository: cvRepository,}}func (s *cvService) SaveAccountDetails(ctx context.Context, req *models.AccountDetailsRequest) (*models.AccountDetails, error) {// Ambil data lama jika adaaccountDetails, err := s.cvRepository.GetAccountDetailsByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Internal Server Error")}// Apply perubahanif accountDetails == nil {accountDetails = &models.AccountDetails{}}accountDetails.AccountID = uint(req.AccountID)accountDetails.FullName = req.FullNameaccountDetails.Gender = req.GenderaccountDetails.DateOfBirth = req.DateOfBirthaccountDetails.PlaceOfBirth = req.PlaceOfBirthaccountDetails.Domicile = req.DomicileaccountDetails.MaritalStatus = req.MaritalStatusaccountDetails.LastEducation = req.LastEducationaccountDetails.LastJob = req.LastJob// Simpan datares, err := s.cvRepository.SaveAccountDetails(ctx, accountDetails)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) GetAccountDetails(ctx context.Context, id int64) (*models.AccountDetails, error) {res, err := s.cvRepository.GetAccountDetailsByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data diri tidak ditemukan")}return res, nil}func (s *cvService) SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCVRequest) (*models.PersonalityAndPreferenceCV, error) {// Ambil data lama jika adapersonalityAndPreference, err := s.cvRepository.GetPersonalityAndPreferenceByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Internal Server Error")}// Apply perubahanif personalityAndPreference == nil {personalityAndPreference = &models.PersonalityAndPreferenceCV{}}personalityAndPreference.AccountID = req.AccountIDpersonalityAndPreference.PositiveTraits = req.PositiveTraitspersonalityAndPreference.NegativeTraits = req.NegativeTraitspersonalityAndPreference.Hobbies = req.HobbiespersonalityAndPreference.LifeGoals = req.LifeGoalspersonalityAndPreference.DailyActivities = req.DailyActivitiespersonalityAndPreference.LeisureActivities = req.LeisureActivitiespersonalityAndPreference.Likes = req.LikespersonalityAndPreference.Dislikes = req.DislikespersonalityAndPreference.StressHandling = req.StressHandlingpersonalityAndPreference.AngerTriggers = req.AngerTriggerspersonalityAndPreference.FavoriteFoodAndDrinks = req.FavoriteFoodAndDrinkspersonalityAndPreference.CanCook = req.CanCookpersonalityAndPreference.TypesOfDishesCooked = req.TypesOfDishesCookedpersonalityAndPreference.MonthlyExpenses = req.MonthlyExpensesres, err := s.cvRepository.SavePersonalityAndPreference(ctx, personalityAndPreference)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) GetPersonalityAndPreference(ctx context.Context, id int64) (*models.PersonalityAndPreferenceCV, error) {res, err := s.cvRepository.GetPersonalityAndPreferenceByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) CreateFamilyMember(ctx context.Context, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error) {// Mapping request ke modelfamilyMember := &models.FamilyMemberCV{AccountID: req.AccountID,Role: req.Role,Status: req.Status,Religion: req.Religion,Job: req.Job,LastEducation: req.LastEducation,Age: req.Age,}// Simpan ke repositoryres, err := s.cvRepository.SaveFamilyMember(ctx, familyMember)if err != nil {return nil, response.HandleGormError(err, "Gagal menyimpan anggota keluarga")}return res, nil}func (s *cvService) ListFamilyMember(ctx context.Context, accountID int64) ([]models.FamilyMemberCV, error) {list, err := s.cvRepository.ListFamilyMember(ctx, accountID)if err != nil {return nil, response.HandleGormError(err, "Gagal mengambil daftar anggota keluarga")}return list, nil}func (s *cvService) GetFamilyMember(ctx context.Context, id int64) (*models.FamilyMemberCV, error) {res, err := s.cvRepository.GetFamilyMember(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data anggota keluarga tidak ditemukan")}return res, nil}func (s *cvService) DeleteFamilyMember(ctx context.Context, id int64) error {err := s.cvRepository.DeleteFamilyMember(ctx, id)if err != nil {return response.HandleGormError(err, "Gagal menghapus anggota keluarga")}return nil}func (s *cvService) UpdateFamilyMember(ctx context.Context, id int64, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error) {existing, err := s.cvRepository.GetFamilyMember(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data anggota keluarga tidak ditemukan")}existing.Role = req.Roleexisting.Status = req.Statusexisting.Religion = req.Religionexisting.Job = req.Jobexisting.LastEducation = req.LastEducationexisting.Age = req.Ageupdated, err := s.cvRepository.SaveFamilyMember(ctx, existing)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui anggota keluarga")}return updated, nil}func (s *cvService) SavePhysicalAndHealth(ctx context.Context, req *models.PhysicalAndHealthRequest) (*models.PhysicalAndHealthCV, error) {// Cek apakah data sudah ada berdasarkan account_idexisting, err := s.cvRepository.GetPhysicalAndHealthByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Terjadi kesalahan saat mengambil data fisik dan kesehatan")}// Jika belum ada, buat objek baruif existing == nil {existing = &models.PhysicalAndHealthCV{}}// Mapping field dari requestexisting.AccountID = req.AccountIDexisting.HeightInCm = req.HeightInCmexisting.WeightInKg = req.WeightInKgexisting.BodyShape = req.BodyShapeexisting.SkinColor = req.SkinColorexisting.HairType = req.HairTypeexisting.MedicalHistory = req.MedicalHistoryexisting.PhysicalDisorder = req.PhysicalDisorderexisting.PhysicalTraits = req.PhysicalTraits// Simpan datares, err := s.cvRepository.SavePhysicalAndHealth(ctx, existing)if err != nil {return nil, response.HandleGormError(err, "Gagal menyimpan data fisik dan kesehatan")}return res, nil}func (s *cvService) GetPhysicalAndHealth(ctx context.Context, id int64) (*models.PhysicalAndHealthCV, error) {res, err := s.cvRepository.GetPhysicalAndHealthByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data fisik dan kesehatan tidak ditemukan")}return res, nil}func (s *cvService) SaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingRequest) (*models.WorshipAndReligiousUnderstandingCV, error) {// Cek apakah data sudah ada berdasarkan account_idworshipAndReligiousUnderstanding, err := s.cvRepository.GetWorshipAndReligiousUnderstandingByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Terjadi kesalahan saat mengambil data agama dan pemahaman agama")}// Jika belum ada, buat objek baruif worshipAndReligiousUnderstanding == nil {worshipAndReligiousUnderstanding = &models.WorshipAndReligiousUnderstandingCV{}}// Mapping field dari requestworshipAndReligiousUnderstanding.AccountID = req.AccountIDworshipAndReligiousUnderstanding.ObligatoryPrayer = req.ObligatoryPrayerworshipAndReligiousUnderstanding.CongregationalPrayer = req.CongregationalPrayerworshipAndReligiousUnderstanding.TahajjudPrayer = req.TahajjudPrayerworshipAndReligiousUnderstanding.DhuhaPrayer = req.DhuhaPrayerworshipAndReligiousUnderstanding.QuranMemorization = req.QuranMemorizationworshipAndReligiousUnderstanding.QuranReadingAbility = req.QuranReadingAbilityworshipAndReligiousUnderstanding.DaudFasting = req.DaudFastingworshipAndReligiousUnderstanding.AyyamulBidhFasting = req.AyyamulBidhFastingworshipAndReligiousUnderstanding.HajjOrUmrah = req.HajjOrUmrahworshipAndReligiousUnderstanding.ListeningToMusic = req.ListeningToMusicworshipAndReligiousUnderstanding.OpinionOnIkhtilat = req.OpinionOnIkhtilatworshipAndReligiousUnderstanding.OpinionOnTouchingNonMahram = req.OpinionOnTouchingNonMahramworshipAndReligiousUnderstanding.OpinionOnVeil = req.OpinionOnVeilworshipAndReligiousUnderstanding.WeeklyReligiousStudies = req.WeeklyReligiousStudiesworshipAndReligiousUnderstanding.FollowedUstadz = req.FollowedUstadz// Simpan datares, err := s.cvRepository.SaveWorshipAndReligiousUnderstanding(ctx, worshipAndReligiousUnderstanding)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) GetWorshipAndReligiousUnderstanding(ctx context.Context, id int64) (*models.WorshipAndReligiousUnderstandingCV, error) {res, err := s.cvRepository.GetWorshipAndReligiousUnderstandingByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data agama dan pemahaman agama tidak ditemukan")}return res, nil}func (s *cvService) CreateEducation(ctx context.Context, req *models.EducationRequest) (*models.EducationCV, error) {edu := &models.EducationCV{AccountID: req.AccountID,LastEducation: req.LastEducation,EducationInstitute: req.EducationInstitute,EducationMajor: req.EducationMajor,YearStart: req.YearStart,YearGraduate: req.YearGraduate,}res, err := s.cvRepository.SaveEducation(ctx, edu)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data pendidikan")}return res, nil}func (s *cvService) UpdateEducation(ctx context.Context, id int64, req *models.EducationRequest) (*models.EducationCV, error) {edu, err := s.cvRepository.GetEducation(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pendidikan tidak ditemukan")}edu.LastEducation = req.LastEducationedu.EducationInstitute = req.EducationInstituteedu.EducationMajor = req.EducationMajoredu.YearStart = req.YearStartedu.YearGraduate = req.YearGraduateres, err := s.cvRepository.SaveEducation(ctx, edu)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data pendidikan")}return res, nil}func (s *cvService) ListEducation(ctx context.Context, accountID int64) ([]models.EducationCV, error) {return s.cvRepository.ListEducation(ctx, accountID)}func (s *cvService) GetEducation(ctx context.Context, id int64) (*models.EducationCV, error) {edu, err := s.cvRepository.GetEducation(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pendidikan tidak ditemukan")}return edu, nil}func (s *cvService) DeleteEducation(ctx context.Context, id int64) error {return s.cvRepository.DeleteEducation(ctx, id)}func (s *cvService) CreateJob(ctx context.Context, req *models.JobRequest) (*models.JobCV, error) {job := &models.JobCV{AccountID: req.AccountID,InstitutionName: req.InstitutionName,CurrentJob: req.CurrentJob,YearStartedWorking: req.YearStartedWorking,MonthlyIncome: req.MonthlyIncome,IncomeSources: req.IncomeSources,}res, err := s.cvRepository.SaveJob(ctx, job)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data pekerjaan")}return res, nil}func (s *cvService) UpdateJob(ctx context.Context, id int64, req *models.JobRequest) (*models.JobCV, error) {job, err := s.cvRepository.GetJob(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pekerjaan tidak ditemukan")}job.InstitutionName = req.InstitutionNamejob.CurrentJob = req.CurrentJobjob.YearStartedWorking = req.YearStartedWorkingjob.MonthlyIncome = req.MonthlyIncomejob.IncomeSources = req.IncomeSourcesres, err := s.cvRepository.SaveJob(ctx, job)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data pekerjaan")}return res, nil}func (s *cvService) ListJob(ctx context.Context, accountID int64) ([]models.JobCV, error) {return s.cvRepository.ListJob(ctx, accountID)}func (s *cvService) GetJob(ctx context.Context, id int64) (*models.JobCV, error) {job, err := s.cvRepository.GetJob(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pekerjaan tidak ditemukan")}return job, nil}func (s *cvService) DeleteJob(ctx context.Context, id int64) error {return s.cvRepository.DeleteJob(ctx, id)}func (s *cvService) CreateAchievement(ctx context.Context, req *models.AchievementRequest) (*models.AchievementCV, error) {ach := &models.AchievementCV{AccountID: req.AccountID,AchievementOrAward: req.AchievementOrAward,}res, err := s.cvRepository.SaveAchievement(ctx, ach)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data prestasi")}return res, nil}func (s *cvService) UpdateAchievement(ctx context.Context, id int64, req *models.AchievementRequest) (*models.AchievementCV, error) {ach, err := s.cvRepository.GetAchievement(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data prestasi tidak ditemukan")}ach.AchievementOrAward = req.AchievementOrAwardres, err := s.cvRepository.SaveAchievement(ctx, ach)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data prestasi")}return res, nil}func (s *cvService) ListAchievement(ctx context.Context, accountID int64) ([]models.AchievementCV, error) {return s.cvRepository.ListAchievement(ctx, accountID)}func (s *cvService) GetAchievement(ctx context.Context, id int64) (*models.AchievementCV, error) {ach, err := s.cvRepository.GetAchievement(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data prestasi tidak ditemukan")}return ach, nil}func (s *cvService) DeleteAchievement(ctx context.Context, id int64) error {return s.cvRepository.DeleteAchievement(ctx, id)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485package servicesimport ("api.qobiltu.id/models""api.qobiltu.id/repositories""api.qobiltu.id/response""api.qobiltu.id/validation""context""errors""gorm.io/gorm")type CVService interface {SaveAccountDetails(ctx context.Context, req *models.AccountDetailsRequest) (*models.AccountDetails, error)GetAccountDetails(ctx context.Context, id int64) (*models.AccountDetails, error)SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCVRequest) (*models.PersonalityAndPreferenceCV, error)GetPersonalityAndPreference(ctx context.Context, id int64) (*models.PersonalityAndPreferenceCV, error)CreateFamilyMember(ctx context.Context, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error)UpdateFamilyMember(ctx context.Context, id int64, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error)ListFamilyMember(ctx context.Context, accountID int64) ([]models.FamilyMemberCV, error)GetFamilyMember(ctx context.Context, id int64) (*models.FamilyMemberCV, error)DeleteFamilyMember(ctx context.Context, id int64) errorSavePhysicalAndHealth(ctx context.Context, req *models.PhysicalAndHealthRequest) (*models.PhysicalAndHealthCV, error)GetPhysicalAndHealth(ctx context.Context, id int64) (*models.PhysicalAndHealthCV, error)SaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingRequest) (*models.WorshipAndReligiousUnderstandingCV, error)GetWorshipAndReligiousUnderstanding(ctx context.Context, id int64) (*models.WorshipAndReligiousUnderstandingCV, error)CreateEducation(ctx context.Context, req *models.EducationRequest) (*models.EducationCV, error)UpdateEducation(ctx context.Context, id int64, req *models.EducationRequest) (*models.EducationCV, error)ListEducation(ctx context.Context, accountID int64) ([]models.EducationCV, error)GetEducation(ctx context.Context, id int64) (*models.EducationCV, error)DeleteEducation(ctx context.Context, id int64) errorCreateJob(ctx context.Context, req *models.JobRequest) (*models.JobCV, error)UpdateJob(ctx context.Context, id int64, req *models.JobRequest) (*models.JobCV, error)ListJob(ctx context.Context, accountID int64) ([]models.JobCV, error)GetJob(ctx context.Context, id int64) (*models.JobCV, error)DeleteJob(ctx context.Context, id int64) errorCreateAchievement(ctx context.Context, req *models.AchievementRequest) (*models.AchievementCV, error)UpdateAchievement(ctx context.Context, id int64, req *models.AchievementRequest) (*models.AchievementCV, error)ListAchievement(ctx context.Context, accountID int64) ([]models.AchievementCV, error)GetAchievement(ctx context.Context, id int64) (*models.AchievementCV, error)DeleteAchievement(ctx context.Context, id int64) error}type cvService struct {cvRepository repositories.CVRepository}func NewCVService(cvRepository repositories.CVRepository) CVService {return &cvService{cvRepository: cvRepository,}}func (s *cvService) SaveAccountDetails(ctx context.Context, req *models.AccountDetailsRequest) (*models.AccountDetails, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Ambil data lama jika adaaccountDetails, err := s.cvRepository.GetAccountDetailsByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Internal Server Error")}// Apply perubahanif accountDetails == nil {accountDetails = &models.AccountDetails{}}accountDetails.AccountID = uint(req.AccountID)accountDetails.FullName = req.FullNameaccountDetails.Gender = req.GenderaccountDetails.DateOfBirth = req.DateOfBirthaccountDetails.PlaceOfBirth = req.PlaceOfBirthaccountDetails.Domicile = req.DomicileaccountDetails.MaritalStatus = req.MaritalStatusaccountDetails.LastEducation = req.LastEducationaccountDetails.LastJob = req.LastJob// Simpan datares, err := s.cvRepository.SaveAccountDetails(ctx, accountDetails)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) GetAccountDetails(ctx context.Context, id int64) (*models.AccountDetails, error) {res, err := s.cvRepository.GetAccountDetailsByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data diri tidak ditemukan")}return res, nil}func (s *cvService) SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCVRequest) (*models.PersonalityAndPreferenceCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Ambil data lama jika adapersonalityAndPreference, err := s.cvRepository.GetPersonalityAndPreferenceByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Internal Server Error")}// Apply perubahanif personalityAndPreference == nil {personalityAndPreference = &models.PersonalityAndPreferenceCV{}}personalityAndPreference.AccountID = req.AccountIDpersonalityAndPreference.PositiveTraits = req.PositiveTraitspersonalityAndPreference.NegativeTraits = req.NegativeTraitspersonalityAndPreference.Hobbies = req.HobbiespersonalityAndPreference.LifeGoals = req.LifeGoalspersonalityAndPreference.DailyActivities = req.DailyActivitiespersonalityAndPreference.LeisureActivities = req.LeisureActivitiespersonalityAndPreference.Likes = req.LikespersonalityAndPreference.Dislikes = req.DislikespersonalityAndPreference.StressHandling = req.StressHandlingpersonalityAndPreference.AngerTriggers = req.AngerTriggerspersonalityAndPreference.FavoriteFoodAndDrinks = req.FavoriteFoodAndDrinkspersonalityAndPreference.CanCook = req.CanCookpersonalityAndPreference.TypesOfDishesCooked = req.TypesOfDishesCookedpersonalityAndPreference.MonthlyExpenses = req.MonthlyExpensesres, err := s.cvRepository.SavePersonalityAndPreference(ctx, personalityAndPreference)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) GetPersonalityAndPreference(ctx context.Context, id int64) (*models.PersonalityAndPreferenceCV, error) {res, err := s.cvRepository.GetPersonalityAndPreferenceByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) CreateFamilyMember(ctx context.Context, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Mapping request ke modelfamilyMember := &models.FamilyMemberCV{AccountID: req.AccountID,Role: req.Role,Status: req.Status,Religion: req.Religion,Job: req.Job,LastEducation: req.LastEducation,Age: req.Age,}// Simpan ke repositoryres, err := s.cvRepository.SaveFamilyMember(ctx, familyMember)if err != nil {return nil, response.HandleGormError(err, "Gagal menyimpan anggota keluarga")}return res, nil}func (s *cvService) ListFamilyMember(ctx context.Context, accountID int64) ([]models.FamilyMemberCV, error) {list, err := s.cvRepository.ListFamilyMember(ctx, accountID)if err != nil {return nil, response.HandleGormError(err, "Gagal mengambil daftar anggota keluarga")}return list, nil}func (s *cvService) GetFamilyMember(ctx context.Context, id int64) (*models.FamilyMemberCV, error) {res, err := s.cvRepository.GetFamilyMember(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data anggota keluarga tidak ditemukan")}return res, nil}func (s *cvService) DeleteFamilyMember(ctx context.Context, id int64) error {err := s.cvRepository.DeleteFamilyMember(ctx, id)if err != nil {return response.HandleGormError(err, "Gagal menghapus anggota keluarga")}return nil}func (s *cvService) UpdateFamilyMember(ctx context.Context, id int64, req *models.FamilyMemberRequest) (*models.FamilyMemberCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}existing, err := s.cvRepository.GetFamilyMember(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data anggota keluarga tidak ditemukan")}existing.Role = req.Roleexisting.Status = req.Statusexisting.Religion = req.Religionexisting.Job = req.Jobexisting.LastEducation = req.LastEducationexisting.Age = req.Ageupdated, err := s.cvRepository.SaveFamilyMember(ctx, existing)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui anggota keluarga")}return updated, nil}func (s *cvService) SavePhysicalAndHealth(ctx context.Context, req *models.PhysicalAndHealthRequest) (*models.PhysicalAndHealthCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Cek apakah data sudah ada berdasarkan account_idexisting, err := s.cvRepository.GetPhysicalAndHealthByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Terjadi kesalahan saat mengambil data fisik dan kesehatan")}// Jika belum ada, buat objek baruif existing == nil {existing = &models.PhysicalAndHealthCV{}}// Mapping field dari requestexisting.AccountID = req.AccountIDexisting.HeightInCm = req.HeightInCmexisting.WeightInKg = req.WeightInKgexisting.BodyShape = req.BodyShapeexisting.SkinColor = req.SkinColorexisting.HairType = req.HairTypeexisting.MedicalHistory = req.MedicalHistoryexisting.PhysicalDisorder = req.PhysicalDisorderexisting.PhysicalTraits = req.PhysicalTraits// Simpan datares, err := s.cvRepository.SavePhysicalAndHealth(ctx, existing)if err != nil {return nil, response.HandleGormError(err, "Gagal menyimpan data fisik dan kesehatan")}return res, nil}func (s *cvService) GetPhysicalAndHealth(ctx context.Context, id int64) (*models.PhysicalAndHealthCV, error) {res, err := s.cvRepository.GetPhysicalAndHealthByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data fisik dan kesehatan tidak ditemukan")}return res, nil}func (s *cvService) SaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingRequest) (*models.WorshipAndReligiousUnderstandingCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}// Cek apakah data sudah ada berdasarkan account_idworshipAndReligiousUnderstanding, err := s.cvRepository.GetWorshipAndReligiousUnderstandingByAccountID(ctx, req.AccountID)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, response.HandleGormError(err, "Terjadi kesalahan saat mengambil data agama dan pemahaman agama")}// Jika belum ada, buat objek baruif worshipAndReligiousUnderstanding == nil {worshipAndReligiousUnderstanding = &models.WorshipAndReligiousUnderstandingCV{}}// Mapping field dari requestworshipAndReligiousUnderstanding.AccountID = req.AccountIDworshipAndReligiousUnderstanding.ObligatoryPrayer = req.ObligatoryPrayerworshipAndReligiousUnderstanding.CongregationalPrayer = req.CongregationalPrayerworshipAndReligiousUnderstanding.TahajjudPrayer = req.TahajjudPrayerworshipAndReligiousUnderstanding.DhuhaPrayer = req.DhuhaPrayerworshipAndReligiousUnderstanding.QuranMemorization = req.QuranMemorizationworshipAndReligiousUnderstanding.QuranReadingAbility = req.QuranReadingAbilityworshipAndReligiousUnderstanding.DaudFasting = req.DaudFastingworshipAndReligiousUnderstanding.AyyamulBidhFasting = req.AyyamulBidhFastingworshipAndReligiousUnderstanding.HajjOrUmrah = req.HajjOrUmrahworshipAndReligiousUnderstanding.ListeningToMusic = req.ListeningToMusicworshipAndReligiousUnderstanding.OpinionOnIkhtilat = req.OpinionOnIkhtilatworshipAndReligiousUnderstanding.OpinionOnTouchingNonMahram = req.OpinionOnTouchingNonMahramworshipAndReligiousUnderstanding.OpinionOnVeil = req.OpinionOnVeilworshipAndReligiousUnderstanding.WeeklyReligiousStudies = req.WeeklyReligiousStudiesworshipAndReligiousUnderstanding.FollowedUstadz = req.FollowedUstadz// Simpan datares, err := s.cvRepository.SaveWorshipAndReligiousUnderstanding(ctx, worshipAndReligiousUnderstanding)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil}func (s *cvService) GetWorshipAndReligiousUnderstanding(ctx context.Context, id int64) (*models.WorshipAndReligiousUnderstandingCV, error) {res, err := s.cvRepository.GetWorshipAndReligiousUnderstandingByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data agama dan pemahaman agama tidak ditemukan")}return res, nil}func (s *cvService) CreateEducation(ctx context.Context, req *models.EducationRequest) (*models.EducationCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}edu := &models.EducationCV{AccountID: req.AccountID,LastEducation: req.LastEducation,EducationInstitute: req.EducationInstitute,EducationMajor: req.EducationMajor,YearStart: req.YearStart,YearGraduate: req.YearGraduate,}res, err := s.cvRepository.SaveEducation(ctx, edu)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data pendidikan")}return res, nil}func (s *cvService) UpdateEducation(ctx context.Context, id int64, req *models.EducationRequest) (*models.EducationCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}edu, err := s.cvRepository.GetEducation(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pendidikan tidak ditemukan")}edu.LastEducation = req.LastEducationedu.EducationInstitute = req.EducationInstituteedu.EducationMajor = req.EducationMajoredu.YearStart = req.YearStartedu.YearGraduate = req.YearGraduateres, err := s.cvRepository.SaveEducation(ctx, edu)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data pendidikan")}return res, nil}func (s *cvService) ListEducation(ctx context.Context, accountID int64) ([]models.EducationCV, error) {return s.cvRepository.ListEducation(ctx, accountID)}func (s *cvService) GetEducation(ctx context.Context, id int64) (*models.EducationCV, error) {edu, err := s.cvRepository.GetEducation(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pendidikan tidak ditemukan")}return edu, nil}func (s *cvService) DeleteEducation(ctx context.Context, id int64) error {return s.cvRepository.DeleteEducation(ctx, id)}func (s *cvService) CreateJob(ctx context.Context, req *models.JobRequest) (*models.JobCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}job := &models.JobCV{AccountID: req.AccountID,InstitutionName: req.InstitutionName,CurrentJob: req.CurrentJob,YearStartedWorking: req.YearStartedWorking,MonthlyIncome: req.MonthlyIncome,IncomeSources: req.IncomeSources,}res, err := s.cvRepository.SaveJob(ctx, job)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data pekerjaan")}return res, nil}func (s *cvService) UpdateJob(ctx context.Context, id int64, req *models.JobRequest) (*models.JobCV, error) {if err := validation.Validate(req); err != nil {return nil, response.HandleValidationError(err)}job, err := s.cvRepository.GetJob(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pekerjaan tidak ditemukan")}job.InstitutionName = req.InstitutionNamejob.CurrentJob = req.CurrentJobjob.YearStartedWorking = req.YearStartedWorkingjob.MonthlyIncome = req.MonthlyIncomejob.IncomeSources = req.IncomeSourcesres, err := s.cvRepository.SaveJob(ctx, job)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data pekerjaan")}return res, nil}func (s *cvService) ListJob(ctx context.Context, accountID int64) ([]models.JobCV, error) {return s.cvRepository.ListJob(ctx, accountID)}func (s *cvService) GetJob(ctx context.Context, id int64) (*models.JobCV, error) {job, err := s.cvRepository.GetJob(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pekerjaan tidak ditemukan")}return job, nil}func (s *cvService) DeleteJob(ctx context.Context, id int64) error {return s.cvRepository.DeleteJob(ctx, id)}func (s *cvService) CreateAchievement(ctx context.Context, req *models.AchievementRequest) (*models.AchievementCV, error) {ach := &models.AchievementCV{AccountID: req.AccountID,AchievementOrAward: req.AchievementOrAward,}res, err := s.cvRepository.SaveAchievement(ctx, ach)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data prestasi")}return res, nil}func (s *cvService) UpdateAchievement(ctx context.Context, id int64, req *models.AchievementRequest) (*models.AchievementCV, error) {ach, err := s.cvRepository.GetAchievement(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data prestasi tidak ditemukan")}ach.AchievementOrAward = req.AchievementOrAwardres, err := s.cvRepository.SaveAchievement(ctx, ach)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data prestasi")}return res, nil}func (s *cvService) ListAchievement(ctx context.Context, accountID int64) ([]models.AchievementCV, error) {return s.cvRepository.ListAchievement(ctx, accountID)}func (s *cvService) GetAchievement(ctx context.Context, id int64) (*models.AchievementCV, error) {ach, err := s.cvRepository.GetAchievement(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data prestasi tidak ditemukan")}return ach, nil}func (s *cvService) DeleteAchievement(ctx context.Context, id int64) error {return s.cvRepository.DeleteAchievement(ctx, id)}
96 unmodified lines97989910010110296 unmodified linesgithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=96 unmodified lines97989910010110210310496 unmodified linesgithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
2 unmodified lines345678232 unmodified lines2412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722733 unmodified lines2772782792802812822832842852862872882892902912922 unmodified linesimport ("time"uuid "github.com/satori/go.uuid")232 unmodified lines}WorshipAndReligiousUnderstandingCV struct {ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"`AccountID int64 `gorm:"column:account_id;not null;unique" json:"account_id"`Account *Account `gorm:"foreignKey:AccountID;constraint:OnDelete:CASCADE" json:"account,omitempty"`ObligatoryPrayer *string `gorm:"column:obligatory_prayer" json:"obligatory_prayer"` // sholat_wajib_5_waktuCongregationalPrayer *string `gorm:"column:congregational_prayer" json:"congregational_prayer"` // sholat_berjamaah_di_masjidTahajjudPrayer *string `gorm:"column:tahajjud_prayer" json:"tahajjud_prayer"` // sholat_tahajudDhuhaPrayer *string `gorm:"column:dhuha_prayer" json:"dhuha_prayer"` // sholat_dhuhaQuranMemorization *string `gorm:"column:quran_memorization" json:"quran_memorization"` // hafalan_alquranQuranReadingAbility *string `gorm:"column:quran_reading_ability" json:"quran_reading_ability"` // kemampuan_baca_alquranDaudFasting *string `gorm:"column:daud_fasting" json:"daud_fasting"` // puasa_daudAyyamulBidhFasting *string `gorm:"column:ayyamul_bidh_fasting" json:"ayyamul_bidh_fasting"` // puasa_ayyamul_bidhHajjOrUmrah *string `gorm:"column:hajj_or_umrah" json:"hajj_or_umrah"` // ibadah_haji_umrohListeningToMusic *string `gorm:"column:listening_to_music" json:"listening_to_music"` // mendengarkan_musikOpinionOnIkhtilat *string `gorm:"column:opinion_on_ikhtilat" json:"opinion_on_ikhtilat"` // pendapat_ikhtilatOpinionOnTouchingNonMahram *string `gorm:"column:opinion_on_touching_non_mahram" json:"opinion_on_touching_non_mahram"` // pendapat_menyentuh_non_mahramOpinionOnVeil *string `gorm:"column:opinion_on_veil" json:"opinion_on_veil"` // pendapat_tentang_cadarWeeklyReligiousStudies *string `gorm:"column:weekly_religious_studies" json:"weekly_religious_studies"` // kajian_yang_diikuti_dalam_sepekanFollowedUstadz *string `gorm:"column:followed_ustadz" json:"followed_ustadz"` // ustadz_yang_diikutiCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"`UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"`}EducationCV struct {ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"` // idAccountID int64 `gorm:"column:account_id;not null" json:"account_id"` // id akunAccount *Account `gorm:"foreignKey:AccountID;constraint:OnDelete:CASCADE" json:"account,omitempty"` // relasi ke akunLastEducation *string `gorm:"column:last_education" json:"last_education"` // pendidikan terakhirEducationInstitute *string `gorm:"column:education_institute" json:"education_institute"` // institusi pendidikanEducationMajor *string `gorm:"column:education_major" json:"education_major"` // jurusan pendidikanYearStart *int `gorm:"column:year_start" json:"year_start"` // tahun masuk3 unmodified lines}JobCV struct {ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"` // idAccountID int64 `gorm:"column:account_id;not null" json:"account_id"` // id akunAccount *Account `gorm:"foreignKey:AccountID;constraint:OnDelete:CASCADE" json:"account,omitempty"` // relasi ke akunInstitutionName *string `gorm:"column:institution_name" json:"institution_name"` // nama instansiCurrentJob *string `gorm:"column:current_job" json:"current_job"` // pekerjaan saat iniYearStartedWorking *int `gorm:"column:year_started_working" json:"year_started_working"` // tahun mulai bekerjaMonthlyIncome *string `gorm:"column:monthly_income" json:"monthly_income"` // penghasilan per bulanIncomeSources *string `gorm:"column:income_sources" json:"income_sources"` // sumber penghasilanCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"` // tanggal dibuatUpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"` // tanggal diperbarui}AchievementCV struct {2 unmodified lines3456789232 unmodified lines2422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732743 unmodified lines2782792802812822832842852862872882892902912922932 unmodified linesimport ("time""github.com/lib/pq"uuid "github.com/satori/go.uuid")232 unmodified lines}WorshipAndReligiousUnderstandingCV struct {ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"`AccountID int64 `gorm:"column:account_id;not null;unique" json:"account_id"`Account *Account `gorm:"foreignKey:AccountID;constraint:OnDelete:CASCADE" json:"account,omitempty"`ObligatoryPrayer *string `gorm:"column:obligatory_prayer" json:"obligatory_prayer"` // sholat_wajib_5_waktuCongregationalPrayer *string `gorm:"column:congregational_prayer" json:"congregational_prayer"` // sholat_berjamaah_di_masjidTahajjudPrayer *string `gorm:"column:tahajjud_prayer" json:"tahajjud_prayer"` // sholat_tahajudDhuhaPrayer *string `gorm:"column:dhuha_prayer" json:"dhuha_prayer"` // sholat_dhuhaQuranMemorization *string `gorm:"column:quran_memorization" json:"quran_memorization"` // hafalan_alquranQuranReadingAbility *string `gorm:"column:quran_reading_ability" json:"quran_reading_ability"` // kemampuan_baca_alquranDaudFasting *string `gorm:"column:daud_fasting" json:"daud_fasting"` // puasa_daudAyyamulBidhFasting *string `gorm:"column:ayyamul_bidh_fasting" json:"ayyamul_bidh_fasting"` // puasa_ayyamul_bidhHajjOrUmrah pq.StringArray `gorm:"column:hajj_or_umrah;type:varchar(255)[]" json:"hajj_or_umrah"` // ibadah_haji_umrohListeningToMusic *string `gorm:"column:listening_to_music" json:"listening_to_music"` // mendengarkan_musikOpinionOnIkhtilat *string `gorm:"column:opinion_on_ikhtilat" json:"opinion_on_ikhtilat"` // pendapat_ikhtilatOpinionOnTouchingNonMahram *string `gorm:"column:opinion_on_touching_non_mahram" json:"opinion_on_touching_non_mahram"` // pendapat_menyentuh_non_mahramOpinionOnVeil *string `gorm:"column:opinion_on_veil" json:"opinion_on_veil"` // pendapat_tentang_cadarWeeklyReligiousStudies *string `gorm:"column:weekly_religious_studies" json:"weekly_religious_studies"` // kajian_yang_diikuti_dalam_sepekanFollowedUstadz *string `gorm:"column:followed_ustadz" json:"followed_ustadz"` // ustadz_yang_diikutiCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"`UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"`}EducationCV struct {ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"` // idAccountID int64 `gorm:"column:account_id;not null" json:"account_id"` // id akunAccount *Account `gorm:"foreignKey:AccountID;constraint:OnDelete:CASCADE" json:"account,omitempty"` // relasi ke akunLastEducation *string `gorm:"column:last_education" json:"last_education" validate:""` // pendidikan terakhirEducationInstitute *string `gorm:"column:education_institute" json:"education_institute"` // institusi pendidikanEducationMajor *string `gorm:"column:education_major" json:"education_major"` // jurusan pendidikanYearStart *int `gorm:"column:year_start" json:"year_start"` // tahun masuk3 unmodified lines}JobCV struct {ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"` // idAccountID int64 `gorm:"column:account_id;not null" json:"account_id"` // id akunAccount *Account `gorm:"foreignKey:AccountID;constraint:OnDelete:CASCADE" json:"account,omitempty"` // relasi ke akunInstitutionName *string `gorm:"column:institution_name" json:"institution_name"` // nama instansiCurrentJob *string `gorm:"column:current_job" json:"current_job"` // pekerjaan saat iniYearStartedWorking *int `gorm:"column:year_started_working" json:"year_started_working"` // tahun mulai bekerjaMonthlyIncome *string `gorm:"column:monthly_income" json:"monthly_income"` // penghasilan per bulanIncomeSources pq.StringArray `gorm:"column:income_sources;type:varchar(255)[]" json:"income_sources"` // sumber penghasilanCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"` // tanggal dibuatUpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"` // tanggal diperbarui}AchievementCV struct {
12345648 unmodified lines555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145package modelsimport "time"type LoginRequest struct {Email string `json:"email" binding:"required"`48 unmodified linestype (PersonalityAndPreferenceCVRequest struct {AccountID int64 `json:"-"`PositiveTraits *string `json:"positive_traits"` // sifat positifNegativeTraits *string `json:"negative_traits"` // sifat negatifHobbies *string `json:"hobbies"` // hobiLifeGoals *string `json:"life_goals"` // target hidupDailyActivities *string `json:"daily_activities"` // kegiatan sehari-hariLeisureActivities *string `json:"leisure_activities"` // kegiatan waktu luangLikes *string `json:"likes"` // hal yang disukaiDislikes *string `json:"dislikes"` // hal yang tidak disukaiStressHandling *string `json:"stress_handling"` // cara mengatasi stresAngerTriggers *string `json:"anger_triggers"` // pemicu amarahFavoriteFoodAndDrinks *string `json:"favorite_food_and_drinks"` // makanan dan minuman favoritCanCook *bool `json:"can_cook"` // bisa memasakTypesOfDishesCooked *string `json:"types_of_dishes_cooked"` // jenis masakan yang bisa dimasakMonthlyExpenses *string `json:"monthly_expenses"` // pengeluaran per bulan}FamilyMemberRequest struct {AccountID int64 `json:"-"`Role *string `json:"role"` // Peran dalam keluargaStatus *string `json:"status"` // Status (Hidup, Wafat)Religion *string `json:"religion"` // AgamaJob *string `json:"job"` // PekerjaanLastEducation *string `json:"last_education"` // Pendidikan terakhirAge *int `json:"age"` // Usia}PhysicalAndHealthRequest struct {AccountID int64 `json:"-"`HeightInCm *int `json:"height_cm"` // Tinggi badan dalam satuan sentimeterWeightInKg *int `json:"weight_kg"` // Berat badan dalam satuan kilogramBodyShape *string `json:"body_shape"` // Bentuk tubuhSkinColor *string `json:"skin_color"` // Warna kulitHairType *string `json:"hair_type"` // Tipe rambutMedicalHistory *string `json:"medical_history"` // Riwayat penyakitPhysicalDisorder *string `json:"physical_disorder"` // Cacat fisikPhysicalTraits *string `json:"physical_traits"` // Ciri khas fisik}AccountDetailsRequest struct {AccountID int64 `json:"-"`FullName *string `json:"full_name"`Gender *string `json:"gender"`DateOfBirth *time.Time `json:"date_of_birth"`PlaceOfBirth *string `json:"place_of_birth"`Domicile *string `json:"domicile"`MaritalStatus *string `json:"marital_status"`LastEducation *string `json:"last_education"`LastJob *string `json:"last_job"`}WorshipAndReligiousUnderstandingRequest struct {AccountID int64 `json:"-"`ObligatoryPrayer *string `json:"obligatory_prayer"` // sholat_wajib_5_waktuCongregationalPrayer *string `json:"congregational_prayer"` // sholat_berjamaah_di_masjidTahajjudPrayer *string `json:"tahajjud_prayer"` // sholat_tahajudDhuhaPrayer *string `json:"dhuha_prayer"` // sholat_dhuhaQuranMemorization *string `json:"quran_memorization"` // hafalan_alquranQuranReadingAbility *string `json:"quran_reading_ability"` // kemampuan_baca_alquranDaudFasting *string `json:"daud_fasting"` // puasa_daudAyyamulBidhFasting *string `json:"ayyamul_bidh_fasting"` // puasa_ayyamul_bidhHajjOrUmrah *string `json:"hajj_or_umrah"` // ibadah_haji_umrohListeningToMusic *string `json:"listening_to_music"` // mendengarkan_musikOpinionOnIkhtilat *string `json:"opinion_on_ikhtilat"` // pendapat_ikhtilatOpinionOnTouchingNonMahram *string `json:"opinion_on_touching_non_mahram"` // pendapat_menyentuh_non_mahramOpinionOnVeil *string `json:"opinion_on_veil"` // pendapat_tentang_cadarWeeklyReligiousStudies *string `json:"weekly_religious_studies"` // kajian_yang_diikuti_dalam_sepekanFollowedUstadz *string `json:"followed_ustadz"` // ustadz_yang_diikuti}EducationRequest struct {AccountID int64 `json:"account_id"`LastEducation *string `json:"last_education"` // pendidikan terakhirEducationInstitute *string `json:"education_institute"` // institusi pendidikanEducationMajor *string `json:"education_major"` // jurusan pendidikanYearStart *int `json:"year_start"` // tahun masukYearGraduate *int `json:"year_graduate"` // tahun lulus}JobRequest struct {AccountID int64 `json:"account_id"`InstitutionName *string `json:"institution_name"` // nama instansiCurrentJob *string `json:"current_job"` // pekerjaan saat iniYearStartedWorking *int `json:"year_started_working"` // tahun mulai bekerjaMonthlyIncome *string `json:"monthly_income"` // penghasilan per bulanIncomeSources *string `json:"income_sources"` // sumber penghasilan}AchievementRequest struct {12345678948 unmodified lines585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148package modelsimport ("github.com/lib/pq""time")type LoginRequest struct {Email string `json:"email" binding:"required"`48 unmodified linestype (PersonalityAndPreferenceCVRequest struct {AccountID int64 `json:"-"`PositiveTraits *string `json:"positive_traits"` // sifat positifNegativeTraits *string `json:"negative_traits"` // sifat negatifHobbies *string `json:"hobbies"` // hobiLifeGoals *string `json:"life_goals"` // target hidupDailyActivities *string `json:"daily_activities"` // kegiatan sehari-hariLeisureActivities *string `json:"leisure_activities"` // kegiatan waktu luangLikes *string `json:"likes"` // hal yang disukaiDislikes *string `json:"dislikes"` // hal yang tidak disukaiStressHandling *string `json:"stress_handling"` // cara mengatasi stresAngerTriggers *string `json:"anger_triggers"` // pemicu amarahFavoriteFoodAndDrinks *string `json:"favorite_food_and_drinks"` // makanan dan minuman favoritCanCook *bool `json:"can_cook"` // bisa memasakTypesOfDishesCooked *string `json:"types_of_dishes_cooked"` // jenis masakan yang bisa dimasakMonthlyExpenses *string `json:"monthly_expenses" validate:"monthly_expenses"` // pengeluaran per bulan}FamilyMemberRequest struct {AccountID int64 `json:"-"`Role *string `json:"role" validate:"family_role"` // Peran dalam keluargaStatus *string `json:"status" validate:"life_status"` // Status (Hidup, Wafat)Religion *string `json:"religion" validate:"religion"` // AgamaJob *string `json:"job"` // PekerjaanLastEducation *string `json:"last_education" validate:"last_education"` // Pendidikan terakhirAge *int `json:"age"` // Usia}PhysicalAndHealthRequest struct {AccountID int64 `json:"-"`HeightInCm *int `json:"height_cm"` // Tinggi badan dalam satuan sentimeterWeightInKg *int `json:"weight_kg"` // Berat badan dalam satuan kilogramBodyShape *string `json:"body_shape" validate:"body_shape"` // Bentuk tubuhSkinColor *string `json:"skin_color" validate:"skin_color"` // Warna kulitHairType *string `json:"hair_type" validate:"hair_type"` // Tipe rambutMedicalHistory *string `json:"medical_history"` // Riwayat penyakitPhysicalDisorder *string `json:"physical_disorder"` // Cacat fisikPhysicalTraits *string `json:"physical_traits"` // Ciri khas fisik}AccountDetailsRequest struct {AccountID int64 `json:"-"`FullName *string `json:"full_name"`Gender *string `json:"gender" validate:"gender"`DateOfBirth *time.Time `json:"date_of_birth"`PlaceOfBirth *string `json:"place_of_birth"`Domicile *string `json:"domicile"`MaritalStatus *string `json:"marital_status" validate:"marital_status"`LastEducation *string `json:"last_education" validate:"last_education"`LastJob *string `json:"last_job"`}WorshipAndReligiousUnderstandingRequest struct {AccountID int64 `json:"-"`ObligatoryPrayer *string `json:"obligatory_prayer"` // sholat_wajib_5_waktuCongregationalPrayer *string `json:"congregational_prayer"` // sholat_berjamaah_di_masjidTahajjudPrayer *string `json:"tahajjud_prayer"` // sholat_tahajudDhuhaPrayer *string `json:"dhuha_prayer"` // sholat_dhuhaQuranMemorization *string `json:"quran_memorization"` // hafalan_alquranQuranReadingAbility *string `json:"quran_reading_ability" validate:"quran_reading_ability"` // kemampuan_baca_alquranDaudFasting *string `json:"daud_fasting"` // puasa_daudAyyamulBidhFasting *string `json:"ayyamul_bidh_fasting"` // puasa_ayyamul_bidhHajjOrUmrah pq.StringArray `json:"hajj_or_umrah"` // ibadah_haji_umrohListeningToMusic *string `json:"listening_to_music"` // mendengarkan_musikOpinionOnIkhtilat *string `json:"opinion_on_ikhtilat"` // pendapat_ikhtilatOpinionOnTouchingNonMahram *string `json:"opinion_on_touching_non_mahram"` // pendapat_menyentuh_non_mahramOpinionOnVeil *string `json:"opinion_on_veil"` // pendapat_tentang_cadarWeeklyReligiousStudies *string `json:"weekly_religious_studies"` // kajian_yang_diikuti_dalam_sepekanFollowedUstadz *string `json:"followed_ustadz"` // ustadz_yang_diikuti}EducationRequest struct {AccountID int64 `json:"account_id"`LastEducation *string `json:"last_education" validate:"last_education"` // pendidikan terakhirEducationInstitute *string `json:"education_institute"` // institusi pendidikanEducationMajor *string `json:"education_major"` // jurusan pendidikanYearStart *int `json:"year_start"` // tahun masukYearGraduate *int `json:"year_graduate"` // tahun lulus}JobRequest struct {AccountID int64 `json:"account_id"`InstitutionName *string `json:"institution_name"` // nama instansiCurrentJob *string `json:"current_job"` // pekerjaan saat iniYearStartedWorking *int `json:"year_started_working"` // tahun mulai bekerjaMonthlyIncome *string `json:"monthly_income" validate:"monthly_income"` // penghasilan per bulanIncomeSources pq.StringArray `json:"income_sources"` // sumber penghasilan}AchievementRequest struct {
1234567891011121314151617181920212223package controller
import (
"strconv"
"api.qobiltu.id/controller"
"api.qobiltu.id/models"
"api.qobiltu.id/services"
"github.com/gin-gonic/gin"
)
func List(c *gin.Context) {
quizList := services.QuizListService{}
quizListController := controller.Controller[any, models.Academy, []models.Quiz]{
Service: &quizList.Service,
}
quizListController.HeaderParse(c, func() {
academy_id, _ := strconv.Atoi(c.Param("academy_id"))
quizList.Constructor.ID = uint(academy_id)
quizList.Retrieve()
quizListController.Response(c)
})
}3 unmodified lines456789101112131416 unmodified lines3132333435363738393 unmodified linesrequire (github.com/gin-gonic/gin v1.10.0github.com/golang-jwt/jwt/v5 v5.2.1github.com/gosimple/slug v1.15.0github.com/hibiken/asynq v0.25.1github.com/joho/godotenv v1.5.1github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatiblegithub.com/redis/go-redis/v9 v9.7.0github.com/satori/go.uuid v1.2.0golang.org/x/crypto v0.36.016 unmodified linesgithub.com/gin-contrib/sse v1.0.0 // indirectgithub.com/go-logr/logr v1.4.2 // indirectgithub.com/go-logr/stdr v1.2.2 // indirectgithub.com/go-playground/locales v0.14.1 // indirectgithub.com/go-playground/universal-translator v0.18.1 // indirectgithub.com/go-playground/validator/v10 v10.25.0 // indirectgithub.com/goccy/go-json v0.10.5 // indirectgithub.com/google/s2a-go v0.1.9 // indirectgithub.com/google/uuid v1.6.0 // indirect3 unmodified lines45678910111213141516171816 unmodified lines3536373839403 unmodified linesrequire (github.com/gin-gonic/gin v1.10.0github.com/go-playground/locales v0.14.1github.com/go-playground/universal-translator v0.18.1github.com/go-playground/validator/v10 v10.25.0github.com/golang-jwt/jwt/v5 v5.2.1github.com/gosimple/slug v1.15.0github.com/hibiken/asynq v0.25.1github.com/joho/godotenv v1.5.1github.com/jordan-wright/email v4.0.1-0.20210109023952-943e75fe5223+incompatiblegithub.com/lib/pq v1.10.9github.com/redis/go-redis/v9 v9.7.0github.com/satori/go.uuid v1.2.0golang.org/x/crypto v0.36.016 unmodified linesgithub.com/gin-contrib/sse v1.0.0 // indirectgithub.com/go-logr/logr v1.4.2 // indirectgithub.com/go-logr/stdr v1.2.2 // indirectgithub.com/goccy/go-json v0.10.5 // indirectgithub.com/google/s2a-go v0.1.9 // indirectgithub.com/google/uuid v1.6.0 // indirect
8 unmodified lines910111213148 unmodified linesfunc QuizRoute(router *gin.Engine) {routerGroup := router.Group("/api/v1/quiz"){routerGroup.POST("/:academy_id/:quiz_id/attempt", middleware.AuthUser, QuizController.Attempt)routerGroup.GET("/:academy_id/:quiz_id/question", middleware.AuthUser, QuizController.Question)routerGroup.PUT("/:academy_id/:quiz_id/choose-answer", middleware.AuthUser, QuizController.Answer)8 unmodified lines91011121314158 unmodified linesfunc QuizRoute(router *gin.Engine) {routerGroup := router.Group("/api/v1/quiz"){routerGroup.GET("/:academy_id/list", middleware.AuthUser, QuizController.List)routerGroup.POST("/:academy_id/:quiz_id/attempt", middleware.AuthUser, QuizController.Attempt)routerGroup.GET("/:academy_id/:quiz_id/question", middleware.AuthUser, QuizController.Question)routerGroup.PUT("/:academy_id/:quiz_id/choose-answer", middleware.AuthUser, QuizController.Answer)
1 unmodified line23456789101112132 unmodified lines16171819202155 unmodified lines777879808182838440 unmodified lines12512612712812913020 unmodified lines1511521531 unmodified lineimport ("errors""fmt""time""api.qobiltu.id/models""api.qobiltu.id/repositories")type AttemptQuizService struct {Service[models.Quiz, models.QuizAttempt]}2 unmodified linesService[models.QuizAttempt, models.QuizResultResponse]}func AuthorizeQuizwithAcademy(s *AttemptQuizService, next func()) {academyRepo := repositories.GetAcademyByID(s.Constructor.AcademyID)s.Error = academyRepo.RowsError55 unmodified lines}s.Error = errors.Join(allAttemptsRepo.RowsError, quizRepo.RowsError)CheckUserAttemptLimit(s, allAttemptsRepo, quizRepo, userID, func() {fmt.Println("accountID", userID)fmt.Println("quizID", s.Constructor.ID)latestAttemptRepo := repositories.GetUserLastAttempt(userID, s.Constructor.ID)if latestAttemptRepo.NoRecord {s.Exception.DataNotFound = true40 unmodified lines}})}func (s *SubmitQuizService) Create(userID uint) {quizAttemptRepo := repositories.GetAttemptById(s.Constructor.ID)if quizAttemptRepo.NoRecord {20 unmodified linesreturn}1 unmodified line23456789101112132 unmodified lines1617181920212223242555 unmodified lines818283848586878840 unmodified lines12913013113213313413520 unmodified lines1561571581591601611621631641651661671681691701 unmodified lineimport ("errors""time""api.qobiltu.id/models""api.qobiltu.id/repositories")type AttemptQuizService struct {Service[models.Quiz, models.QuizAttempt]}2 unmodified linesService[models.QuizAttempt, models.QuizResultResponse]}type QuizListService struct {Service[models.Academy, []models.Quiz]}func AuthorizeQuizwithAcademy(s *AttemptQuizService, next func()) {academyRepo := repositories.GetAcademyByID(s.Constructor.AcademyID)s.Error = academyRepo.RowsError55 unmodified lines}s.Error = errors.Join(allAttemptsRepo.RowsError, quizRepo.RowsError)CheckUserAttemptLimit(s, allAttemptsRepo, quizRepo, userID, func() {// fmt.Println("accountID", userID)// fmt.Println("quizID", s.Constructor.ID)latestAttemptRepo := repositories.GetUserLastAttempt(userID, s.Constructor.ID)if latestAttemptRepo.NoRecord {s.Exception.DataNotFound = true40 unmodified lines}})}func (s *SubmitQuizService) Create(userID uint) {quizAttemptRepo := repositories.GetAttemptById(s.Constructor.ID)if quizAttemptRepo.NoRecord {20 unmodified linesreturn}func (s *QuizListService) Retrieve() {quizRepo := repositories.GetQuizbyAcademyId(s.Constructor.ID)s.Error = quizRepo.RowsErrorif quizRepo.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "There is no quiz with given academy ID!"return}s.Result = quizRepo.Resultreturn}
73 unmodified lines74757677787973 unmodified lines&models.FamilyMemberCV{},&models.PhysicalAndHealthCV{},&models.WorshipAndReligiousUnderstandingCV{},)if err != nil {73 unmodified lines74757677787980818273 unmodified lines&models.FamilyMemberCV{},&models.PhysicalAndHealthCV{},&models.WorshipAndReligiousUnderstandingCV{},&models.EducationCV{},&models.JobCV{},&models.AchievementCV{},)if err != nil {
27 unmodified lines282930313233231 unmodified lines26526626727 unmodified linesSaveWorshipAndReligiousUnderstanding(ctx *gin.Context)GetWorshipAndReligiousUnderstanding(ctx *gin.Context)}type cvController struct {231 unmodified linesresponse.HandleSuccess(ctx, http.StatusOK, "Get worship and religious understanding success", res, nil)}27 unmodified lines282930313233343536373839404142434445464748495051231 unmodified lines28328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455527 unmodified linesSaveWorshipAndReligiousUnderstanding(ctx *gin.Context)GetWorshipAndReligiousUnderstanding(ctx *gin.Context)CreateEducation(ctx *gin.Context)UpdateEducation(ctx *gin.Context)ListEducation(ctx *gin.Context)GetEducation(ctx *gin.Context)DeleteEducation(ctx *gin.Context)CreateJob(ctx *gin.Context)UpdateJob(ctx *gin.Context)ListJob(ctx *gin.Context)GetJob(ctx *gin.Context)DeleteJob(ctx *gin.Context)CreateAchievement(ctx *gin.Context)UpdateAchievement(ctx *gin.Context)ListAchievement(ctx *gin.Context)GetAchievement(ctx *gin.Context)DeleteAchievement(ctx *gin.Context)}type cvController struct {231 unmodified linesresponse.HandleSuccess(ctx, http.StatusOK, "Get worship and religious understanding success", res, nil)}// --- Education ---func (c *cvController) CreateEducation(ctx *gin.Context) {var req models.EducationRequestif err := ctx.ShouldBindJSON(&req); err != nil {response.HandleError(ctx, err)return}accountData := middleware.GetAccountData(ctx)req.AccountID = int64(accountData.UserID)res, err := c.cvService.CreateEducation(ctx, &req)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Education created successfully", res, nil)}func (c *cvController) UpdateEducation(ctx *gin.Context) {idStr := ctx.Param("id")id, err := strconv.ParseInt(idStr, 10, 64)if err != nil {response.HandleError(ctx, err)return}var req models.EducationRequestif err := ctx.ShouldBindJSON(&req); err != nil {response.HandleError(ctx, err)return}res, err := c.cvService.UpdateEducation(ctx, id, &req)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Education updated successfully", res, nil)}func (c *cvController) ListEducation(ctx *gin.Context) {accountData := middleware.GetAccountData(ctx)accountID := int64(accountData.UserID)res, err := c.cvService.ListEducation(ctx, accountID)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "List of education retrieved successfully", res, nil)}func (c *cvController) GetEducation(ctx *gin.Context) {idStr := ctx.Param("id")id, err := strconv.ParseInt(idStr, 10, 64)if err != nil {response.HandleError(ctx, err)return}res, err := c.cvService.GetEducation(ctx, id)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Get education success", res, nil)}func (c *cvController) DeleteEducation(ctx *gin.Context) {idStr := ctx.Param("id")id, err := strconv.ParseInt(idStr, 10, 64)if err != nil {response.HandleError(ctx, err)return}err = c.cvService.DeleteEducation(ctx, id)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Education deleted successfully", nil, nil)}// --- Job ---func (c *cvController) CreateJob(ctx *gin.Context) {var req models.JobRequestif err := ctx.ShouldBindJSON(&req); err != nil {response.HandleError(ctx, err)return}accountData := middleware.GetAccountData(ctx)req.AccountID = int64(accountData.UserID)res, err := c.cvService.CreateJob(ctx, &req)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Job created successfully", res, nil)}func (c *cvController) UpdateJob(ctx *gin.Context) {idStr := ctx.Param("id")id, err := strconv.ParseInt(idStr, 10, 64)if err != nil {response.HandleError(ctx, err)return}var req models.JobRequestif err := ctx.ShouldBindJSON(&req); err != nil {response.HandleError(ctx, err)return}res, err := c.cvService.UpdateJob(ctx, id, &req)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Job updated successfully", res, nil)}func (c *cvController) ListJob(ctx *gin.Context) {accountData := middleware.GetAccountData(ctx)accountID := int64(accountData.UserID)res, err := c.cvService.ListJob(ctx, accountID)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "List of jobs retrieved successfully", res, nil)}func (c *cvController) GetJob(ctx *gin.Context) {idStr := ctx.Param("id")id, err := strconv.ParseInt(idStr, 10, 64)if err != nil {response.HandleError(ctx, err)return}res, err := c.cvService.GetJob(ctx, id)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Get job success", res, nil)}func (c *cvController) DeleteJob(ctx *gin.Context) {idStr := ctx.Param("id")id, err := strconv.ParseInt(idStr, 10, 64)if err != nil {response.HandleError(ctx, err)return}err = c.cvService.DeleteJob(ctx, id)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Job deleted successfully", nil, nil)}// --- Achievement ---func (c *cvController) CreateAchievement(ctx *gin.Context) {var req models.AchievementRequestif err := ctx.ShouldBindJSON(&req); err != nil {response.HandleError(ctx, err)return}accountData := middleware.GetAccountData(ctx)req.AccountID = int64(accountData.UserID)res, err := c.cvService.CreateAchievement(ctx, &req)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Achievement created successfully", res, nil)}func (c *cvController) UpdateAchievement(ctx *gin.Context) {idStr := ctx.Param("id")id, err := strconv.ParseInt(idStr, 10, 64)if err != nil {response.HandleError(ctx, err)return}var req models.AchievementRequestif err := ctx.ShouldBindJSON(&req); err != nil {response.HandleError(ctx, err)return}res, err := c.cvService.UpdateAchievement(ctx, id, &req)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Achievement updated successfully", res, nil)}func (c *cvController) ListAchievement(ctx *gin.Context) {accountData := middleware.GetAccountData(ctx)accountID := int64(accountData.UserID)res, err := c.cvService.ListAchievement(ctx, accountID)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "List of achievements retrieved successfully", res, nil)}func (c *cvController) GetAchievement(ctx *gin.Context) {idStr := ctx.Param("id")id, err := strconv.ParseInt(idStr, 10, 64)if err != nil {response.HandleError(ctx, err)return}res, err := c.cvService.GetAchievement(ctx, id)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Get achievement success", res, nil)}func (c *cvController) DeleteAchievement(ctx *gin.Context) {idStr := ctx.Param("id")id, err := strconv.ParseInt(idStr, 10, 64)if err != nil {response.HandleError(ctx, err)return}err = c.cvService.DeleteAchievement(ctx, id)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Achievement deleted successfully", nil, nil)}
154 unmodified lines155156157158159160100 unmodified lines26126226326426526623 unmodified lines290291292154 unmodified linestype Quiz struct {ID uint `gorm:"primaryKey" json:"id"`AcademyID uint `json:"academy_id"`Title string `json:"title"`Description string `json:"description"`AttemptLimit int `json:"attempt_limit"`100 unmodified linesCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"`UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"`})// Gorm table name settings23 unmodified linesfunc (WorshipAndReligiousUnderstandingCV) TableName() string {return "worship_and_religious_understanding_cv"}154 unmodified lines155156157158159160161100 unmodified lines26226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130223 unmodified lines326327328329330331154 unmodified linestype Quiz struct {ID uint `gorm:"primaryKey" json:"id"`AcademyID uint `json:"academy_id"`Slug string `json:"slug" gorm:"uniqueIndex" `Title string `json:"title"`Description string `json:"description"`AttemptLimit int `json:"attempt_limit"`100 unmodified linesCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"`UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"`}EducationCV struct {ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"` // idAccountID int64 `gorm:"column:account_id;not null" json:"account_id"` // id akunAccount *Account `gorm:"foreignKey:AccountID;constraint:OnDelete:CASCADE" json:"account,omitempty"` // relasi ke akunLastEducation *string `gorm:"column:last_education" json:"last_education"` // pendidikan terakhirEducationInstitute *string `gorm:"column:education_institute" json:"education_institute"` // institusi pendidikanEducationMajor *string `gorm:"column:education_major" json:"education_major"` // jurusan pendidikanYearStart *int `gorm:"column:year_start" json:"year_start"` // tahun masukYearGraduate *int `gorm:"column:year_graduate" json:"year_graduate"` // tahun lulusCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"` // tanggal dibuatUpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"` // tanggal diperbarui}JobCV struct {ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"` // idAccountID int64 `gorm:"column:account_id;not null" json:"account_id"` // id akunAccount *Account `gorm:"foreignKey:AccountID;constraint:OnDelete:CASCADE" json:"account,omitempty"` // relasi ke akunInstitutionName *string `gorm:"column:institution_name" json:"institution_name"` // nama instansiCurrentJob *string `gorm:"column:current_job" json:"current_job"` // pekerjaan saat iniYearStartedWorking *int `gorm:"column:year_started_working" json:"year_started_working"` // tahun mulai bekerjaMonthlyIncome *string `gorm:"column:monthly_income" json:"monthly_income"` // penghasilan per bulanIncomeSources *string `gorm:"column:income_sources" json:"income_sources"` // sumber penghasilanCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"` // tanggal dibuatUpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"` // tanggal diperbarui}AchievementCV struct {ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"` // idAccountID int64 `gorm:"column:account_id;not null" json:"account_id"` // id akunAccount *Account `gorm:"foreignKey:AccountID;constraint:OnDelete:CASCADE" json:"account,omitempty"` // relasi ke akunAchievementOrAward *string `gorm:"column:achievement_or_award" json:"achievement_or_award"` // prestasi atau penghargaanCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"` // tanggal dibuatUpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"` // tanggal diperbarui})// Gorm table name settings23 unmodified linesfunc (WorshipAndReligiousUnderstandingCV) TableName() string {return "worship_and_religious_understanding_cv"}func (EducationCV) TableName() string { return "education_cv" }func (JobCV) TableName() string { return "job_cv" }func (AchievementCV) TableName() string { return "achievement_cv" }
122 unmodified lines123124125126122 unmodified linesWeeklyReligiousStudies *string `json:"weekly_religious_studies"` // kajian_yang_diikuti_dalam_sepekanFollowedUstadz *string `json:"followed_ustadz"` // ustadz_yang_diikuti})122 unmodified lines123124125126127128129130131132133134135136137138139140141142143144145146147148149122 unmodified linesWeeklyReligiousStudies *string `json:"weekly_religious_studies"` // kajian_yang_diikuti_dalam_sepekanFollowedUstadz *string `json:"followed_ustadz"` // ustadz_yang_diikuti}EducationRequest struct {AccountID int64 `json:"account_id"`LastEducation *string `json:"last_education"` // pendidikan terakhirEducationInstitute *string `json:"education_institute"` // institusi pendidikanEducationMajor *string `json:"education_major"` // jurusan pendidikanYearStart *int `json:"year_start"` // tahun masukYearGraduate *int `json:"year_graduate"` // tahun lulus}JobRequest struct {AccountID int64 `json:"account_id"`InstitutionName *string `json:"institution_name"` // nama instansiCurrentJob *string `json:"current_job"` // pekerjaan saat iniYearStartedWorking *int `json:"year_started_working"` // tahun mulai bekerjaMonthlyIncome *string `json:"monthly_income"` // penghasilan per bulanIncomeSources *string `json:"income_sources"` // sumber penghasilan}AchievementRequest struct {AccountID int64 `json:"account_id"`AchievementOrAward *string `json:"achievement_or_award"` // prestasi atau penghargaan})
22 unmodified lines23242526272895 unmodified lines12412512622 unmodified linesSaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingCV) (*models.WorshipAndReligiousUnderstandingCV, error)GetWorshipAndReligiousUnderstandingByAccountID(ctx context.Context, accountID int64) (*models.WorshipAndReligiousUnderstandingCV, error)}type cvRepository struct {95 unmodified lines}return &worshipAndReligiousUnderstanding, nil}22 unmodified lines23242526272829303132333435363738394041424395 unmodified lines13914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224322 unmodified linesSaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingCV) (*models.WorshipAndReligiousUnderstandingCV, error)GetWorshipAndReligiousUnderstandingByAccountID(ctx context.Context, accountID int64) (*models.WorshipAndReligiousUnderstandingCV, error)SaveEducation(ctx context.Context, req *models.EducationCV) (*models.EducationCV, error)ListEducation(ctx context.Context, accountID int64) ([]models.EducationCV, error)GetEducation(ctx context.Context, id int64) (*models.EducationCV, error)DeleteEducation(ctx context.Context, id int64) errorSaveJob(ctx context.Context, req *models.JobCV) (*models.JobCV, error)ListJob(ctx context.Context, accountID int64) ([]models.JobCV, error)GetJob(ctx context.Context, id int64) (*models.JobCV, error)DeleteJob(ctx context.Context, id int64) errorSaveAchievement(ctx context.Context, req *models.AchievementCV) (*models.AchievementCV, error)ListAchievement(ctx context.Context, accountID int64) ([]models.AchievementCV, error)GetAchievement(ctx context.Context, id int64) (*models.AchievementCV, error)DeleteAchievement(ctx context.Context, id int64) error}type cvRepository struct {95 unmodified lines}return &worshipAndReligiousUnderstanding, nil}// SaveEducation menyimpan atau memperbarui data pendidikan ke databasefunc (r *cvRepository) SaveEducation(ctx context.Context, req *models.EducationCV) (*models.EducationCV, error) {if err := r.db.WithContext(ctx).Save(req).Error; err != nil {return req, err}return req, nil}// ListEducation mengambil daftar data pendidikan berdasarkan account_idfunc (r *cvRepository) ListEducation(ctx context.Context, accountID int64) ([]models.EducationCV, error) {var educations []models.EducationCVif err := r.db.WithContext(ctx).Where("account_id = ?", accountID).Find(&educations).Error; err != nil {return nil, err}return educations, nil}// GetEducation mengambil satu data pendidikan berdasarkan idfunc (r *cvRepository) GetEducation(ctx context.Context, id int64) (*models.EducationCV, error) {var education models.EducationCVif err := r.db.WithContext(ctx).Where("id = ?", id).First(&education).Error; err != nil {return nil, err}return &education, nil}// DeleteEducation menghapus data pendidikan berdasarkan idfunc (r *cvRepository) DeleteEducation(ctx context.Context, id int64) error {if err := r.db.WithContext(ctx).Where("id = ?", id).Delete(&models.EducationCV{}).Error; err != nil {return err}return nil}// SaveJob menyimpan atau memperbarui data pekerjaan ke databasefunc (r *cvRepository) SaveJob(ctx context.Context, req *models.JobCV) (*models.JobCV, error) {if err := r.db.WithContext(ctx).Save(req).Error; err != nil {return req, err}return req, nil}// ListJob mengambil daftar data pekerjaan berdasarkan account_idfunc (r *cvRepository) ListJob(ctx context.Context, accountID int64) ([]models.JobCV, error) {var jobs []models.JobCVif err := r.db.WithContext(ctx).Where("account_id = ?", accountID).Find(&jobs).Error; err != nil {return nil, err}return jobs, nil}// GetJob mengambil satu data pekerjaan berdasarkan idfunc (r *cvRepository) GetJob(ctx context.Context, id int64) (*models.JobCV, error) {var job models.JobCVif err := r.db.WithContext(ctx).Where("id = ?", id).First(&job).Error; err != nil {return nil, err}return &job, nil}// DeleteJob menghapus data pekerjaan berdasarkan idfunc (r *cvRepository) DeleteJob(ctx context.Context, id int64) error {if err := r.db.WithContext(ctx).Where("id = ?", id).Delete(&models.JobCV{}).Error; err != nil {return err}return nil}// SaveAchievement menyimpan atau memperbarui data prestasi ke databasefunc (r *cvRepository) SaveAchievement(ctx context.Context, req *models.AchievementCV) (*models.AchievementCV, error) {if err := r.db.WithContext(ctx).Save(req).Error; err != nil {return req, err}return req, nil}// ListAchievement mengambil daftar data prestasi berdasarkan account_idfunc (r *cvRepository) ListAchievement(ctx context.Context, accountID int64) ([]models.AchievementCV, error) {var achievements []models.AchievementCVif err := r.db.WithContext(ctx).Where("account_id = ?", accountID).Find(&achievements).Error; err != nil {return nil, err}return achievements, nil}// GetAchievement mengambil satu data prestasi berdasarkan idfunc (r *cvRepository) GetAchievement(ctx context.Context, id int64) (*models.AchievementCV, error) {var achievement models.AchievementCVif err := r.db.WithContext(ctx).Where("id = ?", id).First(&achievement).Error; err != nil {return nil, err}return &achievement, nil}// DeleteAchievement menghapus data prestasi berdasarkan idfunc (r *cvRepository) DeleteAchievement(ctx context.Context, id int64) error {if err := r.db.WithContext(ctx).Where("id = ?", id).Delete(&models.AchievementCV{}).Error; err != nil {return err}return nil}
21 unmodified lines222324252621 unmodified linesrouterGroup.POST("/worship-and-religious-understandings", s.cvController.SaveWorshipAndReligiousUnderstanding)routerGroup.GET("/worship-and-religious-understandings", s.cvController.GetWorshipAndReligiousUnderstanding)}}21 unmodified lines222324252627282930313233343536373839404142434421 unmodified linesrouterGroup.POST("/worship-and-religious-understandings", s.cvController.SaveWorshipAndReligiousUnderstanding)routerGroup.GET("/worship-and-religious-understandings", s.cvController.GetWorshipAndReligiousUnderstanding)routerGroup.POST("/educations", s.cvController.CreateEducation)routerGroup.GET("/educations", s.cvController.ListEducation)routerGroup.GET("/educations/:id", s.cvController.GetEducation)routerGroup.PUT("/educations/:id", s.cvController.UpdateEducation)routerGroup.DELETE("/educations/:id", s.cvController.DeleteEducation)routerGroup.POST("/jobs", s.cvController.CreateJob)routerGroup.GET("/jobs", s.cvController.ListJob)routerGroup.GET("/jobs/:id", s.cvController.GetJob)routerGroup.PUT("/jobs/:id", s.cvController.UpdateJob)routerGroup.DELETE("/jobs/:id", s.cvController.DeleteJob)routerGroup.POST("/achievements", s.cvController.CreateAchievement)routerGroup.GET("/achievements", s.cvController.ListAchievement)routerGroup.GET("/achievements/:id", s.cvController.GetAchievement)routerGroup.PUT("/achievements/:id", s.cvController.UpdateAchievement)routerGroup.DELETE("/achievements/:id", s.cvController.DeleteAchievement)}}
26 unmodified lines272829303132242 unmodified lines27527627726 unmodified linesSaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingRequest) (*models.WorshipAndReligiousUnderstandingCV, error)GetWorshipAndReligiousUnderstanding(ctx context.Context, id int64) (*models.WorshipAndReligiousUnderstandingCV, error)}type cvService struct {242 unmodified lines}return res, nil}26 unmodified lines272829303132333435363738394041424344454647484950242 unmodified lines29329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344426 unmodified linesSaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingRequest) (*models.WorshipAndReligiousUnderstandingCV, error)GetWorshipAndReligiousUnderstanding(ctx context.Context, id int64) (*models.WorshipAndReligiousUnderstandingCV, error)CreateEducation(ctx context.Context, req *models.EducationRequest) (*models.EducationCV, error)UpdateEducation(ctx context.Context, id int64, req *models.EducationRequest) (*models.EducationCV, error)ListEducation(ctx context.Context, accountID int64) ([]models.EducationCV, error)GetEducation(ctx context.Context, id int64) (*models.EducationCV, error)DeleteEducation(ctx context.Context, id int64) errorCreateJob(ctx context.Context, req *models.JobRequest) (*models.JobCV, error)UpdateJob(ctx context.Context, id int64, req *models.JobRequest) (*models.JobCV, error)ListJob(ctx context.Context, accountID int64) ([]models.JobCV, error)GetJob(ctx context.Context, id int64) (*models.JobCV, error)DeleteJob(ctx context.Context, id int64) errorCreateAchievement(ctx context.Context, req *models.AchievementRequest) (*models.AchievementCV, error)UpdateAchievement(ctx context.Context, id int64, req *models.AchievementRequest) (*models.AchievementCV, error)ListAchievement(ctx context.Context, accountID int64) ([]models.AchievementCV, error)GetAchievement(ctx context.Context, id int64) (*models.AchievementCV, error)DeleteAchievement(ctx context.Context, id int64) error}type cvService struct {242 unmodified lines}return res, nil}func (s *cvService) CreateEducation(ctx context.Context, req *models.EducationRequest) (*models.EducationCV, error) {edu := &models.EducationCV{AccountID: req.AccountID,LastEducation: req.LastEducation,EducationInstitute: req.EducationInstitute,EducationMajor: req.EducationMajor,YearStart: req.YearStart,YearGraduate: req.YearGraduate,}res, err := s.cvRepository.SaveEducation(ctx, edu)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data pendidikan")}return res, nil}func (s *cvService) UpdateEducation(ctx context.Context, id int64, req *models.EducationRequest) (*models.EducationCV, error) {edu, err := s.cvRepository.GetEducation(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pendidikan tidak ditemukan")}edu.LastEducation = req.LastEducationedu.EducationInstitute = req.EducationInstituteedu.EducationMajor = req.EducationMajoredu.YearStart = req.YearStartedu.YearGraduate = req.YearGraduateres, err := s.cvRepository.SaveEducation(ctx, edu)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data pendidikan")}return res, nil}func (s *cvService) ListEducation(ctx context.Context, accountID int64) ([]models.EducationCV, error) {return s.cvRepository.ListEducation(ctx, accountID)}func (s *cvService) GetEducation(ctx context.Context, id int64) (*models.EducationCV, error) {edu, err := s.cvRepository.GetEducation(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pendidikan tidak ditemukan")}return edu, nil}func (s *cvService) DeleteEducation(ctx context.Context, id int64) error {return s.cvRepository.DeleteEducation(ctx, id)}func (s *cvService) CreateJob(ctx context.Context, req *models.JobRequest) (*models.JobCV, error) {job := &models.JobCV{AccountID: req.AccountID,InstitutionName: req.InstitutionName,CurrentJob: req.CurrentJob,YearStartedWorking: req.YearStartedWorking,MonthlyIncome: req.MonthlyIncome,IncomeSources: req.IncomeSources,}res, err := s.cvRepository.SaveJob(ctx, job)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data pekerjaan")}return res, nil}func (s *cvService) UpdateJob(ctx context.Context, id int64, req *models.JobRequest) (*models.JobCV, error) {job, err := s.cvRepository.GetJob(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pekerjaan tidak ditemukan")}job.InstitutionName = req.InstitutionNamejob.CurrentJob = req.CurrentJobjob.YearStartedWorking = req.YearStartedWorkingjob.MonthlyIncome = req.MonthlyIncomejob.IncomeSources = req.IncomeSourcesres, err := s.cvRepository.SaveJob(ctx, job)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data pekerjaan")}return res, nil}func (s *cvService) ListJob(ctx context.Context, accountID int64) ([]models.JobCV, error) {return s.cvRepository.ListJob(ctx, accountID)}func (s *cvService) GetJob(ctx context.Context, id int64) (*models.JobCV, error) {job, err := s.cvRepository.GetJob(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data pekerjaan tidak ditemukan")}return job, nil}func (s *cvService) DeleteJob(ctx context.Context, id int64) error {return s.cvRepository.DeleteJob(ctx, id)}func (s *cvService) CreateAchievement(ctx context.Context, req *models.AchievementRequest) (*models.AchievementCV, error) {ach := &models.AchievementCV{AccountID: req.AccountID,AchievementOrAward: req.AchievementOrAward,}res, err := s.cvRepository.SaveAchievement(ctx, ach)if err != nil {return nil, response.HandleGormError(err, "Gagal menambahkan data prestasi")}return res, nil}func (s *cvService) UpdateAchievement(ctx context.Context, id int64, req *models.AchievementRequest) (*models.AchievementCV, error) {ach, err := s.cvRepository.GetAchievement(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data prestasi tidak ditemukan")}ach.AchievementOrAward = req.AchievementOrAwardres, err := s.cvRepository.SaveAchievement(ctx, ach)if err != nil {return nil, response.HandleGormError(err, "Gagal memperbarui data prestasi")}return res, nil}func (s *cvService) ListAchievement(ctx context.Context, accountID int64) ([]models.AchievementCV, error) {return s.cvRepository.ListAchievement(ctx, accountID)}func (s *cvService) GetAchievement(ctx context.Context, id int64) (*models.AchievementCV, error) {ach, err := s.cvRepository.GetAchievement(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Data prestasi tidak ditemukan")}return ach, nil}func (s *cvService) DeleteAchievement(ctx context.Context, id int64) error {return s.cvRepository.DeleteAchievement(ctx, id)}
models/request_model.go+3-1
pkg/validation/custom_rules.go+42
pkg/validation/validation.go+1
services/cv_service.go+9-3
space/Makefile+9-1
space/config/config.go+3
space/controller/cv/cv_controller.go+20
space/docker-compose.yml+4-7
space/go.mod+1-1
space/main.go+8-4
space/models/exception_model.go+3-1
space/models/request_model.go+10
space/pkg/storage/local.goAdded+67
space/pkg/storage/storage.goAdded+71
space/response/api_response_v2.go+1-1
space/response/validation.go+1-1
space/router/cv_route.go+1
space/router/router.go+1
space/router/storage_route.goAdded+24
space/services/cv_service.go+468-385
space/services/email_verification_service.go+78-78
space/services/forgot_password_service.go+1-1
space/space/.gitignore+1
space/space/pkg/validation/custom_rules.goAdded+162
space/space/pkg/validation/validation.goAdded+164
space/space/pkg/worker/distributor.goAdded+23
space/space/pkg/worker/logger.goAdded+37
space/space/pkg/worker/processor.goAdded+66
space/space/pkg/worker/redis_distributor.goAdded+16
space/space/pkg/worker/task_send_forgot_password_email.goAdded+75
space/space/pkg/worker/task_send_verify_email.goAdded+75
space/space/space/main.go+5
space/space/space/models/exception_model.go+18-15
space/space/space/response/api_response_v2.go+16-1
space/space/space/response/validation.goAdded+14
space/space/space/services/cv_service.go+384-343
space/space/space/space/go.sum+2
space/space/space/space/models/database_orm_model.go+32-31
space/space/space/space/models/request_model.go+62-59
space/space/space/space/space/controller/quiz/list_quiz_controller.goAdded+23
space/space/space/space/space/go.mod+4-3
space/space/space/space/space/router/quiz_route.go+1
space/space/space/space/space/services/academy_quiz_service.go+20-3
space/space/space/space/space/space/config/database_connection_config.go+3
space/space/space/space/space/space/controller/cv/cv_controller.go+288
space/space/space/space/space/space/models/database_orm_model.go+39
space/space/space/space/space/space/models/request_model.go+23
space/space/space/space/space/space/repositories/cv_repository.go+117
space/space/space/space/space/space/router/cv_route.go+18
space/space/space/space/space/space/services/cv_service.go+167