Spaces:
Configuration error
Configuration error
Commit ·
9e52285
1
Parent(s): 9adc91d
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)
- config/database_connection_config.go+3
- controller/cv/cv_controller.go+210
- controller/user/user_profile_controller.go+21-21
- controller/user/user_update_profile_controller.go+25-25
- models/database_orm_model.go+116-56
- models/request_model.go+52-20
- repositories/account_repository.go+87-87
- repositories/cv_repository.go+107-18
- router/cv_route.go+20-5
- services/cv_service.go+264-95
- services/external_authentication_service.go+81-81
- services/user_profile_service.go+4-4
- space/config/database_connection_config.go+4
- space/controller/cv/cv_controller.goAdded+267
- space/main.go+9-1
- space/middleware/authentication_middleware.go+7
- space/models/database_orm_model.go+118-33
- space/models/request_model.go+126-51
- space/repositories/cv_repository.goAdded+126
- space/router/cv_route.goAdded+26
- space/router/router.go+11-10
- space/router/server.go+4
- space/services/cv_service.goAdded+108
- space/space/services/health_check_service.go+1-2
- space/space/space/.gitignore+1
- space/space/space/controller/health_check/health_check_controller.go+12-8
- space/space/space/main.go+2-2
- space/space/space/models/database_orm_model.go+207-207
- space/space/space/models/exception_model.go+19-13
- space/space/space/models/health_check_model.go+1-3
- space/space/space/repositories/health_check_repository.go+12-13
- space/space/space/response/api_response_v2.goAdded+79
- space/space/space/response/gorm.goAdded+62
- space/space/space/router/server.go+2-2
- space/space/space/services/health_check_service.goAdded+32
- space/space/space/services/user_profile_service.go+115-115
- space/space/space/space/Dockerfile+6
- space/space/space/space/space/.github/workflows/main.yml+1
- space/space/space/space/space/apperror/apperror.goAdded+168
- space/space/space/space/space/config/database_connection_config.go+80-79
- space/space/space/space/space/config/tx.goAdded+34
- space/space/space/space/space/controller/health_check/health_check_controller.goAdded+31
- space/space/space/space/space/models/exception_model.go+17-15
- space/space/space/space/space/models/health_check_model.goAdded+10
- space/space/space/space/space/repositories/health_check_repository.goAdded+41
- space/space/space/space/space/response/paging.goAdded+58
- space/space/space/space/space/response/response.goAdded+152
- space/space/space/space/space/router/health_check_route.goAdded+5
- space/space/space/space/space/router/router.go+12-19
- space/space/space/space/space/router/server.goAdded+32
70 unmodified lines71727374757670 unmodified lines&models.Answer{},&models.UserAnswer{},&models.PersonalityAndPreferenceCV{},)if err != nil {70 unmodified lines71727374757677787970 unmodified lines&models.Answer{},&models.UserAnswer{},&models.PersonalityAndPreferenceCV{},&models.FamilyMemberCV{},&models.PhysicalAndHealthCV{},&models.WorshipAndReligiousUnderstandingCV{},)if err != nil {
6 unmodified lines78910111213141516176 unmodified lines24252627282925 unmodified lines5556576 unmodified lines"api.qobiltu.id/services""github.com/gin-gonic/gin""net/http")type CVController interface {SavePersonalityAndPreference(ctx *gin.Context)GetPersonalityAndPreference(ctx *gin.Context)}type cvController struct {6 unmodified lines}}func (c *cvController) SavePersonalityAndPreference(ctx *gin.Context) {var req models.PersonalityAndPreferenceCVRequestif err := ctx.ShouldBindJSON(&req); err != nil {25 unmodified linesresponse.HandleSuccess(ctx, http.StatusOK, "Get Personality and Preference success", res, nil)}6 unmodified lines7891011121314151617181920212223242526272829303132336 unmodified lines404142434445464748495051525354555657585960616263646566676869707172737475767778798025 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662676 unmodified lines"api.qobiltu.id/services""github.com/gin-gonic/gin""net/http""strconv")type CVController interface {SaveAccountDetails(ctx *gin.Context)GetAccountDetails(ctx *gin.Context)SavePersonalityAndPreference(ctx *gin.Context)GetPersonalityAndPreference(ctx *gin.Context)CreateFamilyMember(ctx *gin.Context)UpdateFamilyMember(ctx *gin.Context)ListFamilyMember(ctx *gin.Context)GetFamilyMember(ctx *gin.Context)DeleteFamilyMember(ctx *gin.Context)SavePhysicalAndHealth(ctx *gin.Context)GetPhysicalAndHealth(ctx *gin.Context)SaveWorshipAndReligiousUnderstanding(ctx *gin.Context)GetWorshipAndReligiousUnderstanding(ctx *gin.Context)}type cvController struct {6 unmodified lines}}// --- Account Details ---func (c *cvController) SaveAccountDetails(ctx *gin.Context) {var req models.AccountDetailsRequestif err := ctx.ShouldBindJSON(&req); err != nil {response.HandleError(ctx, err)return}accountData := middleware.GetAccountData(ctx)req.AccountID = int64(accountData.UserID)res, err := c.cvService.SaveAccountDetails(ctx, &req)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Account details saved", res, nil)}func (c *cvController) GetAccountDetails(ctx *gin.Context) {accountData := middleware.GetAccountData(ctx)accountID := int64(accountData.UserID)res, err := c.cvService.GetAccountDetails(ctx, accountID)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Get account details success", res, nil)}// --- Personality & Preference ---func (c *cvController) SavePersonalityAndPreference(ctx *gin.Context) {var req models.PersonalityAndPreferenceCVRequestif err := ctx.ShouldBindJSON(&req); err != nil {25 unmodified linesresponse.HandleSuccess(ctx, http.StatusOK, "Get Personality and Preference success", res, nil)}// --- Family Member ---func (c *cvController) CreateFamilyMember(ctx *gin.Context) {var req models.FamilyMemberRequestif err := ctx.ShouldBindJSON(&req); err != nil {response.HandleError(ctx, err)return}accountData := middleware.GetAccountData(ctx)req.AccountID = int64(accountData.UserID)res, err := c.cvService.CreateFamilyMember(ctx, &req)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Family member saved", res, nil)}func (c *cvController) UpdateFamilyMember(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.FamilyMemberRequestif err := ctx.ShouldBindJSON(&req); err != nil {response.HandleError(ctx, err)return}res, err := c.cvService.UpdateFamilyMember(ctx, id, &req)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Family member updated", res, nil)}func (c *cvController) ListFamilyMember(ctx *gin.Context) {accountData := middleware.GetAccountData(ctx)accountID := int64(accountData.UserID)list, err := c.cvService.ListFamilyMember(ctx, accountID)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "List family members", list, nil)}func (c *cvController) GetFamilyMember(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.GetFamilyMember(ctx, id)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Get family member success", res, nil)}func (c *cvController) DeleteFamilyMember(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.DeleteFamilyMember(ctx, id)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Family member deleted", nil, nil)}// --- Physical and Health ---func (c *cvController) SavePhysicalAndHealth(ctx *gin.Context) {var req models.PhysicalAndHealthRequestif err := ctx.ShouldBindJSON(&req); err != nil {response.HandleError(ctx, err)return}accountData := middleware.GetAccountData(ctx)req.AccountID = int64(accountData.UserID)res, err := c.cvService.SavePhysicalAndHealth(ctx, &req)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Physical and health saved", res, nil)}func (c *cvController) GetPhysicalAndHealth(ctx *gin.Context) {accountData := middleware.GetAccountData(ctx)accountID := int64(accountData.UserID)res, err := c.cvService.GetPhysicalAndHealth(ctx, accountID)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Get physical and health success", res, nil)}// --- Worship and Religious Understanding ---func (c *cvController) SaveWorshipAndReligiousUnderstanding(ctx *gin.Context) {var req models.WorshipAndReligiousUnderstandingRequestif err := ctx.ShouldBindJSON(&req); err != nil {response.HandleError(ctx, err)return}accountData := middleware.GetAccountData(ctx)req.AccountID = int64(accountData.UserID)res, err := c.cvService.SaveWorshipAndReligiousUnderstanding(ctx, &req)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Worship and religious understanding saved", res, nil)}func (c *cvController) GetWorshipAndReligiousUnderstanding(ctx *gin.Context) {accountData := middleware.GetAccountData(ctx)accountID := int64(accountData.UserID)res, err := c.cvService.GetWorshipAndReligiousUnderstanding(ctx, accountID)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Get worship and religious understanding success", res, nil)}
123456789101112131415161718192021package userimport ("api.qobiltu.id/controller""api.qobiltu.id/models""api.qobiltu.id/services""github.com/gin-gonic/gin")func Profile(c *gin.Context) {userProfile := services.UserProfileService{}userProfileController := controller.Controller[any, models.AccountDetails, models.UserProfileResponse]{Service: &userProfile.Service,}userProfileController.HeaderParse(c, func() {userProfileController.Service.Constructor.AccountID = uint(userProfileController.AccountData.UserID)userProfile.Retrieve()userProfileController.Response(c)},)}123456789101112131415161718192021package userimport ("api.qobiltu.id/controller""api.qobiltu.id/models""api.qobiltu.id/services""github.com/gin-gonic/gin")func Profile(c *gin.Context) {userProfile := services.UserProfileService{}userProfileController := controller.Controller[any, models.AccountDetails, models.UserProfileResponse]{Service: &userProfile.Service,}userProfileController.HeaderParse(c, func() {userProfileController.Service.Constructor.AccountID = uint(userProfileController.AccountData.UserID)userProfile.Retrieve()userProfileController.Response(c)},)}
12345678910111213141516171819202122232425package userimport ("api.qobiltu.id/controller""api.qobiltu.id/models""api.qobiltu.id/services""github.com/gin-gonic/gin")func UpdateProfile(c *gin.Context) {userProfile := services.UserProfileService{}userUpdateProfileController := controller.Controller[models.AccountDetails, models.AccountDetails, models.UserProfileResponse]{Service: &userProfile.Service,}userUpdateProfileController.RequestJSON(c, func() {userUpdateProfileController.Service.Constructor = userUpdateProfileController.RequestuserUpdateProfileController.HeaderParse(c, func() {userUpdateProfileController.Service.Constructor.AccountID = uint(userUpdateProfileController.AccountData.UserID)})userProfile.Update()},)}12345678910111213141516171819202122232425package userimport ("api.qobiltu.id/controller""api.qobiltu.id/models""api.qobiltu.id/services""github.com/gin-gonic/gin")func UpdateProfile(c *gin.Context) {userProfile := services.UserProfileService{}userUpdateProfileController := controller.Controller[models.AccountDetails, models.AccountDetails, models.UserProfileResponse]{Service: &userProfile.Service,}userUpdateProfileController.RequestJSON(c, func() {userUpdateProfileController.Service.Constructor = userUpdateProfileController.RequestuserUpdateProfileController.HeaderParse(c, func() {userUpdateProfileController.Service.Constructor.AccountID = userUpdateProfileController.AccountData.UserID})userProfile.Update()},)}
17 unmodified lines18192021222324252627282930313233343536147 unmodified lines18418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123217 unmodified lines}type AccountDetails struct {ID uint64 `gorm:"primaryKey" json:"id"`AccountID uint `json:"account_id"`InitialName string `json:"initial_name"`FullName *string `json:"full_name"`DateOfBirth *time.Time `json:"date_of_birth"`PlaceOfBirth *string `json:"place_of_birth"`Domicile *string `json:"domicile"`LastJob *string `json:"last_job"`Gender *string `json:"gender"`LastEducation *string `json:"last_education"`MaritalStatus *string `json:"marital_status"`Avatar *string `json:"avatar"`PhoneNumber *string `json:"phone_number"`}type EmailVerification struct {147 unmodified linesAverageScore float64 `gorm:"column:average_score" json:"average_score"`}type PersonalityAndPreferenceCV 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"`PositiveTraits *string `gorm:"column:positive_traits" json:"positive_traits"` // sifat positifNegativeTraits *string `gorm:"column:negative_traits" json:"negative_traits"` // sifat negatifHobbies *string `gorm:"column:hobbies" json:"hobbies"` // hobiLifeGoals *string `gorm:"column:life_goals" json:"life_goals"` // target hidupDailyActivities *string `gorm:"column:daily_activities" json:"daily_activities"` // kegiatan sehari-hariLeisureActivities *string `gorm:"column:leisure_activities" json:"leisure_activities"` // kegiatan waktu luangLikes *string `gorm:"column:likes" json:"likes"` // hal yang disukaiDislikes *string `gorm:"column:dislikes" json:"dislikes"` // hal yang tidak disukaiStressHandling *string `gorm:"column:stress_handling" json:"stress_handling"` // cara mengatasi stresAngerTriggers *string `gorm:"column:anger_triggers" json:"anger_triggers"` // pemicu amarahFavoriteFoodAndDrinks *string `gorm:"column:favorite_food_and_drinks" json:"favorite_food_and_drinks"` // makanan dan minuman favoritCanCook *bool `gorm:"column:can_cook" json:"can_cook"` // bisa memasakTypesOfDishesCooked *string `gorm:"column:types_of_dishes_cooked" json:"types_of_dishes_cooked"` // jenis masakan yang bisa dimasakMonthlyExpenses *string `gorm:"column:monthly_expenses" json:"monthly_expenses"` // pengeluaran per bulanCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"`UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"`}// Gorm table name settingsfunc (Account) TableName() string { return "account" }func (AccountDetails) TableName() string { return "account_details" }func (EmailVerification) TableName() string { return "email_verifications" }func (ExternalAuth) TableName() string { return "extern_auth" }func (FCM) TableName() string { return "fcm" }func (ForgotPassword) TableName() string { return "forgot_password" }func (Academy) TableName() string { return "academy" }func (AcademyMaterial) TableName() string { return "academy_materials" }func (AcademyContent) TableName() string { return "academy_contents" }func (AcademyMaterialProgress) TableName() string { return "academy_materials_progress" }func (AcademyContentProgress) TableName() string { return "academy_contents_progress" }func (RegionProvince) TableName() string { return "region_provinces" }func (RegionCity) TableName() string { return "region_cities" }func (Answer) TableName() string { return "answers" }func (Question) TableName() string { return "questions" }func (Quiz) TableName() string { return "quizzes" }func (QuizAttempt) TableName() string { return "quiz_attempts" }func (UserAnswer) TableName() string { return "user_answers" }func (OptionCategory) TableName() string { return "option_categories" }func (OptionValues) TableName() string { return "option_values" }func (PersonalityAndPreferenceCV) TableName() string {return "personality_and_preference_cv"}17 unmodified lines181920212223242526272829303132333435363738147 unmodified lines18618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129217 unmodified lines}type AccountDetails struct {ID uint64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"`AccountID uint `gorm:"column:account_id;not null;unique" json:"account_id"`InitialName string `gorm:"column:initial_name;not null" json:"initial_name"`FullName *string `gorm:"column:full_name" json:"full_name"`DateOfBirth *time.Time `gorm:"column:date_of_birth" json:"date_of_birth"`PlaceOfBirth *string `gorm:"column:place_of_birth" json:"place_of_birth"`Domicile *string `gorm:"column:domicile" json:"domicile"`LastJob *string `gorm:"column:last_job" json:"last_job"`Gender *string `gorm:"column:gender" json:"gender"`LastEducation *string `gorm:"column:last_education" json:"last_education"`MaritalStatus *string `gorm:"column:marital_status" json:"marital_status"`Avatar *string `gorm:"column:avatar" json:"avatar"`PhoneNumber *string `gorm:"column:phone_number" json:"phone_number"`CreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"`UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"`}type EmailVerification struct {147 unmodified linesAverageScore float64 `gorm:"column:average_score" json:"average_score"`}type (PersonalityAndPreferenceCV 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"`PositiveTraits *string `gorm:"column:positive_traits" json:"positive_traits"` // sifat positifNegativeTraits *string `gorm:"column:negative_traits" json:"negative_traits"` // sifat negatifHobbies *string `gorm:"column:hobbies" json:"hobbies"` // hobiLifeGoals *string `gorm:"column:life_goals" json:"life_goals"` // target hidupDailyActivities *string `gorm:"column:daily_activities" json:"daily_activities"` // kegiatan sehari-hariLeisureActivities *string `gorm:"column:leisure_activities" json:"leisure_activities"` // kegiatan waktu luangLikes *string `gorm:"column:likes" json:"likes"` // hal yang disukaiDislikes *string `gorm:"column:dislikes" json:"dislikes"` // hal yang tidak disukaiStressHandling *string `gorm:"column:stress_handling" json:"stress_handling"` // cara mengatasi stresAngerTriggers *string `gorm:"column:anger_triggers" json:"anger_triggers"` // pemicu amarahFavoriteFoodAndDrinks *string `gorm:"column:favorite_food_and_drinks" json:"favorite_food_and_drinks"` // makanan dan minuman favoritCanCook *bool `gorm:"column:can_cook" json:"can_cook"` // bisa memasakTypesOfDishesCooked *string `gorm:"column:types_of_dishes_cooked" json:"types_of_dishes_cooked"` // jenis masakan yang bisa dimasakMonthlyExpenses *string `gorm:"column:monthly_expenses" json:"monthly_expenses"` // pengeluaran per bulanCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"`UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"`}FamilyMemberCV struct {ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"`AccountID int64 `gorm:"column:account_id;not null" json:"account_id"`Account *Account `gorm:"foreignKey:AccountID;constraint:OnDelete:CASCADE" json:"account,omitempty"`Role *string `gorm:"column:role" json:"role"` // Peran dalam keluargaStatus *string `gorm:"column:status" json:"status"` // Status (Hidup, Wafat)Religion *string `gorm:"column:religion" json:"religion"` // AgamaJob *string `gorm:"column:job" json:"job"` // PekerjaanLastEducation *string `gorm:"column:last_education" json:"last_education"` // Pendidikan terakhirAge *int `gorm:"column:age" json:"age"` // UsiaCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"`UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"`}PhysicalAndHealthCV 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"`HeightInCm *int `gorm:"column:height_cm" json:"height_cm"` // Tinggi badan dalam satuan sentimeterWeightInKg *int `gorm:"column:weight_kg" json:"weight_kg"` // Berat badan dalam satuan kilogramBodyShape *string `gorm:"column:body_shape" json:"body_shape"` // Bentuk tubuhSkinColor *string `gorm:"column:skin_color" json:"skin_color"` // Warna kulitHairType *string `gorm:"column:hair_type" json:"hair_type"` // Tipe rambutMedicalHistory *string `gorm:"column:medical_history" json:"medical_history"` // Riwayat penyakitPhysicalDisorder *string `gorm:"column:physical_disorder" json:"physical_disorder"` // Cacat fisikPhysicalTraits *string `gorm:"column:physical_traits" json:"physical_traits"` // Ciri khas fisikCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"` // Waktu data dibuatUpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"` // Waktu data terakhir diperbarui}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"`})// Gorm table name settingsfunc (Account) TableName() string { return "account" }func (AccountDetails) TableName() string { return "account_details" }func (EmailVerification) TableName() string { return "email_verifications" }func (ExternalAuth) TableName() string { return "extern_auth" }func (FCM) TableName() string { return "fcm" }func (ForgotPassword) TableName() string { return "forgot_password" }func (Academy) TableName() string { return "academy" }func (AcademyMaterial) TableName() string { return "academy_materials" }func (AcademyContent) TableName() string { return "academy_contents" }func (AcademyMaterialProgress) TableName() string { return "academy_materials_progress" }func (AcademyContentProgress) TableName() string { return "academy_contents_progress" }func (RegionProvince) TableName() string { return "region_provinces" }func (RegionCity) TableName() string { return "region_cities" }func (Answer) TableName() string { return "answers" }func (Question) TableName() string { return "questions" }func (Quiz) TableName() string { return "quizzes" }func (QuizAttempt) TableName() string { return "quiz_attempts" }func (UserAnswer) TableName() string { return "user_answers" }func (OptionCategory) TableName() string { return "option_categories" }func (OptionValues) TableName() string { return "option_values" }func (PersonalityAndPreferenceCV) TableName() string { return "personality_and_preference_cv" }func (FamilyMemberCV) TableName() string { return "family_member_cv" }func (PhysicalAndHealthCV) TableName() string { return "physical_and_health_cv" }func (WorshipAndReligiousUnderstandingCV) TableName() string {return "worship_and_religious_understanding_cv"}
53 unmodified lines5455565758596010 unmodified lines71727374757677787980818283848586878889909192939453 unmodified linestype (PersonalityAndPreferenceCVRequest struct {AccountID int64 `json:"account_id"`PositiveTraits *string `json:"positive_traits"` // sifat positifNegativeTraits *string `json:"negative_traits"` // sifat negatifHobbies *string `json:"hobbies"` // hobi10 unmodified linesMonthlyExpenses *string `json:"monthly_expenses"` // pengeluaran per bulan}PersonalityAndPreferenceCVResponse struct {ID int64 `json:"id"`AccountID int64 `json:"account_id"`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 bulanCreatedAt time.Time `json:"created_at"`UpdatedAt time.Time `json:"updated_at"`})53 unmodified lines5455565758596010 unmodified lines717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512653 unmodified linestype (PersonalityAndPreferenceCVRequest struct {AccountID int64 `json:"-"`PositiveTraits *string `json:"positive_traits"` // sifat positifNegativeTraits *string `json:"negative_traits"` // sifat negatifHobbies *string `json:"hobbies"` // hobi10 unmodified linesMonthlyExpenses *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})
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687package repositoriesimport ("api.qobiltu.id/models")func GetAccountbyEmail(email string) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](models.Account{Email: email},)repo.Transactions(WhereGivenConstructor[models.Account, models.Account],Find[models.Account, models.Account],)return *repo}func GetAllAccount() Repository[models.Account, []models.Account] {repo := Construct[models.Account, []models.Account](models.Account{},)repo.Transactions(Find[models.Account, []models.Account],)return *repo}func GetAccountById(accountId uint) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](models.Account{Id: accountId},)repo.Transactions(WhereGivenConstructor[models.Account, models.Account],Find[models.Account, models.Account],)return *repo}func UpdateAccount(account models.Account) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](account,)repo.Transaction.Save(&repo.Constructor)repo.Result = repo.Constructorreturn *repo}func GetDetailAccountById(accountId uint) Repository[models.AccountDetails, models.AccountDetails] {repo := Construct[models.AccountDetails, models.AccountDetails](models.AccountDetails{AccountID: accountId},)// fmt.Println("Account ID:", repo.Constructor.AccountID)repo.Transactions(WhereGivenConstructor[models.AccountDetails, models.AccountDetails],Find[models.AccountDetails, models.AccountDetails],)return *repo}func CreateAccount(account models.Account) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](account,)Create(repo)return *repo}func CreateAccountDetails(accountDetails models.AccountDetails) Repository[models.AccountDetails, models.AccountDetails] {repo := Construct[models.AccountDetails, models.AccountDetails](accountDetails,)Create(repo)return *repo}func UpdateAccountDetails(accountDetails models.AccountDetails) Repository[models.AccountDetails, models.AccountDetails] {repo := Construct[models.AccountDetails, models.AccountDetails](models.AccountDetails{AccountID: accountDetails.AccountID},)repo.Transaction.Where("account_id = ?", accountDetails.AccountID).First(&repo.Constructor)accountDetails.ID = repo.Constructor.ID// fmt.Println(repo.Constructor)// fmt.Println(accountDetails)repo.Transaction.Updates(accountDetails)repo.Result = accountDetailsreturn *repo}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687package repositoriesimport ("api.qobiltu.id/models")func GetAccountbyEmail(email string) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](models.Account{Email: email},)repo.Transactions(WhereGivenConstructor[models.Account, models.Account],Find[models.Account, models.Account],)return *repo}func GetAllAccount() Repository[models.Account, []models.Account] {repo := Construct[models.Account, []models.Account](models.Account{},)repo.Transactions(Find[models.Account, []models.Account],)return *repo}func GetAccountById(accountId uint) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](models.Account{Id: accountId},)repo.Transactions(WhereGivenConstructor[models.Account, models.Account],Find[models.Account, models.Account],)return *repo}func UpdateAccount(account models.Account) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](account,)repo.Transaction.Save(&repo.Constructor)repo.Result = repo.Constructorreturn *repo}func GetDetailAccountById(accountId uint) Repository[models.AccountDetails, models.AccountDetails] {repo := Construct[models.AccountDetails, models.AccountDetails](models.AccountDetails{AccountID: accountId},)// fmt.Println("Account ID:", repo.Constructor.AccountID)repo.Transactions(WhereGivenConstructor[models.AccountDetails, models.AccountDetails],Find[models.AccountDetails, models.AccountDetails],)return *repo}func CreateAccount(account models.Account) Repository[models.Account, models.Account] {repo := Construct[models.Account, models.Account](account,)Create(repo)return *repo}func CreateAccountDetails(accountDetails models.AccountDetails) Repository[models.AccountDetails, models.AccountDetails] {repo := Construct[models.AccountDetails, models.AccountDetails](accountDetails,)Create(repo)return *repo}func UpdateAccountDetails(accountDetails models.AccountDetails) Repository[models.AccountDetails, models.AccountDetails] {repo := Construct[models.AccountDetails, models.AccountDetails](models.AccountDetails{AccountID: accountDetails.AccountID},)repo.Transaction.Where("account_id = ?", accountDetails.AccountID).First(&repo.Constructor)accountDetails.ID = repo.Constructor.ID// fmt.Println(repo.Constructor)// fmt.Println(accountDetails)repo.Transaction.Updates(accountDetails)repo.Result = accountDetailsreturn *repo}
12345678910111213141516171819202122232425262728293031323334353637package repositoriesimport ("api.qobiltu.id/models""context""gorm.io/gorm")type CVRepository interface {SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCV) (*models.PersonalityAndPreferenceCV, error)GetPersonalityAndPreferenceByAccountID(ctx context.Context, accountID int64) (*models.PersonalityAndPreferenceCV, error)}type cvRepository struct {db *gorm.DB}func NewCVRepository(db *gorm.DB) CVRepository {return &cvRepository{db: db,}}func (r *cvRepository) SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCV) (*models.PersonalityAndPreferenceCV, error) {if err := r.db.WithContext(ctx).Save(req).Error; err != nil {return req, err}return req, nil}func (r *cvRepository) GetPersonalityAndPreferenceByAccountID(ctx context.Context, accountID int64) (*models.PersonalityAndPreferenceCV, error) {var personalityAndPreference models.PersonalityAndPreferenceCVif err := r.db.WithContext(ctx).Where("account_id = ?", accountID).First(&personalityAndPreference).Error; err != nil {return nil, err}return &personalityAndPreference, nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126package repositoriesimport ("api.qobiltu.id/models""context""gorm.io/gorm")type CVRepository interface {SaveAccountDetails(ctx context.Context, req *models.AccountDetails) (*models.AccountDetails, error)GetAccountDetailsByAccountID(ctx context.Context, accountID int64) (*models.AccountDetails, error)SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCV) (*models.PersonalityAndPreferenceCV, error)GetPersonalityAndPreferenceByAccountID(ctx context.Context, accountID int64) (*models.PersonalityAndPreferenceCV, error)SaveFamilyMember(ctx context.Context, req *models.FamilyMemberCV) (*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.PhysicalAndHealthCV) (*models.PhysicalAndHealthCV, error)GetPhysicalAndHealthByAccountID(ctx context.Context, accountID int64) (*models.PhysicalAndHealthCV, error)SaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingCV) (*models.WorshipAndReligiousUnderstandingCV, error)GetWorshipAndReligiousUnderstandingByAccountID(ctx context.Context, accountID int64) (*models.WorshipAndReligiousUnderstandingCV, error)}type cvRepository struct {db *gorm.DB}func NewCVRepository(db *gorm.DB) CVRepository {return &cvRepository{db: db,}}func (r *cvRepository) SaveAccountDetails(ctx context.Context, req *models.AccountDetails) (*models.AccountDetails, error) {if err := r.db.WithContext(ctx).Save(req).Error; err != nil {return req, err}return req, nil}func (r *cvRepository) GetAccountDetailsByAccountID(ctx context.Context, accountID int64) (*models.AccountDetails, error) {var accountDetails models.AccountDetailsif err := r.db.WithContext(ctx).Where("account_id = ?", accountID).First(&accountDetails).Error; err != nil {return nil, err}return &accountDetails, nil}func (r *cvRepository) SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCV) (*models.PersonalityAndPreferenceCV, error) {if err := r.db.WithContext(ctx).Save(req).Error; err != nil {return req, err}return req, nil}func (r *cvRepository) GetPersonalityAndPreferenceByAccountID(ctx context.Context, accountID int64) (*models.PersonalityAndPreferenceCV, error) {var personalityAndPreference models.PersonalityAndPreferenceCVif err := r.db.WithContext(ctx).Where("account_id = ?", accountID).First(&personalityAndPreference).Error; err != nil {return nil, err}return &personalityAndPreference, nil}func (r *cvRepository) SaveFamilyMember(ctx context.Context, req *models.FamilyMemberCV) (*models.FamilyMemberCV, error) {if err := r.db.WithContext(ctx).Save(req).Error; err != nil {return req, err}return req, nil}func (r *cvRepository) GetFamilyMember(ctx context.Context, id int64) (*models.FamilyMemberCV, error) {var familyMember models.FamilyMemberCVif err := r.db.WithContext(ctx).Where("id = ?", id).First(&familyMember).Error; err != nil {return nil, err}return &familyMember, nil}func (r *cvRepository) DeleteFamilyMember(ctx context.Context, id int64) error {if err := r.db.WithContext(ctx).Where("id = ?", id).Delete(&models.FamilyMemberCV{}).Error; err != nil {return err}return nil}func (r *cvRepository) ListFamilyMember(ctx context.Context, accountID int64) ([]models.FamilyMemberCV, error) {familyMembers := make([]models.FamilyMemberCV, 0)if err := r.db.WithContext(ctx).Where("account_id = ?", accountID).Find(&familyMembers).Error; err != nil {return nil, err}return familyMembers, nil}func (r *cvRepository) SavePhysicalAndHealth(ctx context.Context, req *models.PhysicalAndHealthCV) (*models.PhysicalAndHealthCV, error) {if err := r.db.WithContext(ctx).Save(req).Error; err != nil {return req, err}return req, nil}func (r *cvRepository) GetPhysicalAndHealthByAccountID(ctx context.Context, accountID int64) (*models.PhysicalAndHealthCV, error) {var physicalAndHealth models.PhysicalAndHealthCVif err := r.db.WithContext(ctx).Where("account_id = ?", accountID).First(&physicalAndHealth).Error; err != nil {return nil, err}return &physicalAndHealth, nil}func (r *cvRepository) SaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingCV) (*models.WorshipAndReligiousUnderstandingCV, error) {if err := r.db.WithContext(ctx).Save(req).Error; err != nil {return req, err}return req, nil}func (r *cvRepository) GetWorshipAndReligiousUnderstandingByAccountID(ctx context.Context, accountID int64) (*models.WorshipAndReligiousUnderstandingCV, error) {var worshipAndReligiousUnderstanding models.WorshipAndReligiousUnderstandingCVif err := r.db.WithContext(ctx).Where("account_id = ?", accountID).First(&worshipAndReligiousUnderstanding).Error; err != nil {return nil, err}return &worshipAndReligiousUnderstanding, nil}
2 unmodified lines345678910112 unmodified linesimport "api.qobiltu.id/middleware"func (s *Server) CVRoute() {routerGroup := s.router.Group("/api/v1/cv").Use(middleware.AuthUser){routerGroup.POST("/personality-and-preference", s.cvController.SavePersonalityAndPreference)routerGroup.GET("/personality-and-preference", s.cvController.GetPersonalityAndPreference)}}2 unmodified lines345678910111213141516171819202122232425262 unmodified linesimport "api.qobiltu.id/middleware"func (s *Server) CVRoute() {routerGroup := s.router.Group("/api/v1/cv").Use(middleware.AuthUser){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)routerGroup.POST("/family-members", s.cvController.CreateFamilyMember)routerGroup.GET("/family-members", s.cvController.ListFamilyMember)routerGroup.GET("/family-members/:id", s.cvController.GetFamilyMember)routerGroup.PUT("/family-members/:id", s.cvController.UpdateFamilyMember)routerGroup.DELETE("/family-members/:id", s.cvController.DeleteFamilyMember)routerGroup.POST("/physical-and-healths", s.cvController.SavePhysicalAndHealth)routerGroup.GET("/physical-and-healths", s.cvController.GetPhysicalAndHealth)routerGroup.POST("/worship-and-religious-understandings", s.cvController.SaveWorshipAndReligiousUnderstanding)routerGroup.GET("/worship-and-religious-understandings", s.cvController.GetWorshipAndReligiousUnderstanding)}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108package servicesimport ("api.qobiltu.id/models""api.qobiltu.id/repositories""api.qobiltu.id/response""context""errors""gorm.io/gorm")type CVService interface {SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCVRequest) (*models.PersonalityAndPreferenceCVResponse, error)GetPersonalityAndPreference(ctx context.Context, id int64) (*models.PersonalityAndPreferenceCVResponse, error)}type cvService struct {cvRepository repositories.CVRepository}func NewCVService(cvRepository repositories.CVRepository) CVService {return &cvService{cvRepository: cvRepository,}}func (s *cvService) SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCVRequest) (*models.PersonalityAndPreferenceCVResponse, 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 &models.PersonalityAndPreferenceCVResponse{ID: res.ID,AccountID: res.AccountID,PositiveTraits: res.PositiveTraits,NegativeTraits: res.NegativeTraits,Hobbies: res.Hobbies,LifeGoals: res.LifeGoals,DailyActivities: res.DailyActivities,LeisureActivities: res.LeisureActivities,Likes: res.Likes,Dislikes: res.Dislikes,StressHandling: res.StressHandling,AngerTriggers: res.AngerTriggers,FavoriteFoodAndDrinks: res.FavoriteFoodAndDrinks,CanCook: res.CanCook,TypesOfDishesCooked: res.TypesOfDishesCooked,MonthlyExpenses: res.MonthlyExpenses,CreatedAt: res.CreatedAt,UpdatedAt: res.UpdatedAt,}, nil}func (s *cvService) GetPersonalityAndPreference(ctx context.Context, id int64) (*models.PersonalityAndPreferenceCVResponse, error) {res, err := s.cvRepository.GetPersonalityAndPreferenceByAccountID(ctx, id)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return &models.PersonalityAndPreferenceCVResponse{ID: res.ID,AccountID: res.AccountID,PositiveTraits: res.PositiveTraits,NegativeTraits: res.NegativeTraits,Hobbies: res.Hobbies,LifeGoals: res.LifeGoals,DailyActivities: res.DailyActivities,LeisureActivities: res.LeisureActivities,Likes: res.Likes,Dislikes: res.Dislikes,StressHandling: res.StressHandling,AngerTriggers: res.AngerTriggers,FavoriteFoodAndDrinks: res.FavoriteFoodAndDrinks,CanCook: res.CanCook,TypesOfDishesCooked: res.TypesOfDishesCooked,MonthlyExpenses: res.MonthlyExpenses,CreatedAt: res.CreatedAt,UpdatedAt: res.UpdatedAt,}, nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277package 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)}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}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081package servicesimport ("context""errors""api.qobiltu.id/models""api.qobiltu.id/repositories"uuid "github.com/satori/go.uuid""google.golang.org/api/idtoken")type GoogleAuthService struct {Service[models.ExternalAuth, models.AuthenticatedUser]}func (s *GoogleAuthService) Authenticate(isAgree bool) {GoogleAuth := repositories.GetExternalAccountByOauthId(s.Constructor.OauthID)payload, errGoogleAuth := idtoken.Validate(context.Background(), s.Constructor.OauthID, "")s.Error = errGoogleAuthif errGoogleAuth != nil {s.Exception.Unauthorized = trues.Exception.Message = "Oauth Provider Failed Login (Google Authentication)"return}email := payload.Claims["email"]checkRegisteredEmail := repositories.GetAccountbyEmail(email.(string))if !checkRegisteredEmail.NoRecord {token, _ := GenerateToken(&checkRegisteredEmail.Result)checkRegisteredEmail.Result.Password = "SECRET"s.Result = models.AuthenticatedUser{Account: checkRegisteredEmail.Result,Token: token,}return}if GoogleAuth.NoRecord {if !isAgree {s.Exception.BadRequest = trues.Exception.Message = "Please agree to the terms and conditions to create an account"return}s.Constructor.UUID = uuid.NewV4()s.Constructor.OauthProvider = "Google"createAccount := repositories.CreateAccount(models.Account{UUID: uuid.NewV4(),Email: email.(string),IsEmailVerified: true,})s.Constructor.AccountID = createAccount.Result.IdcreateGoogleAuth := repositories.CreateExternalAuth(s.Constructor)GoogleAuth.Result.AccountID = createGoogleAuth.Result.AccountIDuserProfile := UserProfileService{}userProfile.Constructor.AccountID = GoogleAuth.Result.AccountIDuserProfile.Create()if userProfile.Error != nil {s.Error = userProfile.Errorreturn}s.Error = createGoogleAuth.RowsErrors.Error = errors.Join(s.Error, createAccount.RowsError)}accountData := repositories.GetAccountById(GoogleAuth.Result.AccountID)token, err_tok := GenerateToken(&accountData.Result)if err_tok != nil {s.Error = errors.Join(s.Error, err_tok)}accountData.Result.Password = "SECRET"s.Result = models.AuthenticatedUser{Account: accountData.Result,Token: token,}s.Error = accountData.RowsError}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081package servicesimport ("context""errors""api.qobiltu.id/models""api.qobiltu.id/repositories"uuid "github.com/satori/go.uuid""google.golang.org/api/idtoken")type GoogleAuthService struct {Service[models.ExternalAuth, models.AuthenticatedUser]}func (s *GoogleAuthService) Authenticate(isAgree bool) {GoogleAuth := repositories.GetExternalAccountByOauthId(s.Constructor.OauthID)payload, errGoogleAuth := idtoken.Validate(context.Background(), s.Constructor.OauthID, "")s.Error = errGoogleAuthif errGoogleAuth != nil {s.Exception.Unauthorized = trues.Exception.Message = "Oauth Provider Failed Login (Google Authentication)"return}email := payload.Claims["email"]checkRegisteredEmail := repositories.GetAccountbyEmail(email.(string))if !checkRegisteredEmail.NoRecord {token, _ := GenerateToken(&checkRegisteredEmail.Result)checkRegisteredEmail.Result.Password = "SECRET"s.Result = models.AuthenticatedUser{Account: checkRegisteredEmail.Result,Token: token,}return}if GoogleAuth.NoRecord {if !isAgree {s.Exception.BadRequest = trues.Exception.Message = "Please agree to the terms and conditions to create an account"return}s.Constructor.UUID = uuid.NewV4()s.Constructor.OauthProvider = "Google"createAccount := repositories.CreateAccount(models.Account{UUID: uuid.NewV4(),Email: email.(string),IsEmailVerified: true,})s.Constructor.AccountID = createAccount.Result.IdcreateGoogleAuth := repositories.CreateExternalAuth(s.Constructor)GoogleAuth.Result.AccountID = createGoogleAuth.Result.AccountIDuserProfile := UserProfileService{}userProfile.Constructor.AccountID = GoogleAuth.Result.AccountIDuserProfile.Create()if userProfile.Error != nil {s.Error = userProfile.Errorreturn}s.Error = createGoogleAuth.RowsErrors.Error = errors.Join(s.Error, createAccount.RowsError)}accountData := repositories.GetAccountById(GoogleAuth.Result.AccountID)token, err_tok := GenerateToken(&accountData.Result)if err_tok != nil {s.Error = errors.Join(s.Error, err_tok)}accountData.Result.Password = "SECRET"s.Result = models.AuthenticatedUser{Account: accountData.Result,Token: token,}s.Error = accountData.RowsError}
52 unmodified lines5354555657585960616263641 unmodified line6667686970717223 unmodified lines9697989910010110252 unmodified linesreturn}s.Result = models.UserProfileResponse{Account: repositories.GetAccountById(s.Constructor.AccountID).Result,Details: userProfile.Result,}}func (s *UserProfileService) Retrieve() {userProfile := repositories.GetDetailAccountById(s.Constructor.AccountID)s.Error = userProfile.RowsErrorif userProfile.NoRecord {s.Exception.DataNotFound = true1 unmodified linereturn}s.Result = models.UserProfileResponse{Account: repositories.GetAccountById(s.Constructor.AccountID).Result,Details: userProfile.Result,}s.Result.Account.Password = "SECRET"23 unmodified liness.Exception.Message = "There is no account with given credentials!"return}account := repositories.GetAccountById(s.Constructor.AccountID)account.Result.IsDetailCompleted = (userProfile.Result.InitialName != "" &&userProfile.Result.FullName != nil &&userProfile.Result.DateOfBirth != nil &&52 unmodified lines5354555657585960616263641 unmodified line6667686970717223 unmodified lines9697989910010110252 unmodified linesreturn}s.Result = models.UserProfileResponse{Account: repositories.GetAccountById(uint(s.Constructor.AccountID)).Result,Details: userProfile.Result,}}func (s *UserProfileService) Retrieve() {userProfile := repositories.GetDetailAccountById(uint(s.Constructor.AccountID))s.Error = userProfile.RowsErrorif userProfile.NoRecord {s.Exception.DataNotFound = true1 unmodified linereturn}s.Result = models.UserProfileResponse{Account: repositories.GetAccountById(uint(s.Constructor.AccountID)).Result,Details: userProfile.Result,}s.Result.Account.Password = "SECRET"23 unmodified liness.Exception.Message = "There is no account with given credentials!"return}account := repositories.GetAccountById(uint(s.Constructor.AccountID))account.Result.IsDetailCompleted = (userProfile.Result.InitialName != "" &&userProfile.Result.FullName != nil &&userProfile.Result.DateOfBirth != nil &&
69 unmodified lines70717273747569 unmodified lines&models.Question{},&models.Answer{},&models.UserAnswer{},)if err != nil {69 unmodified lines7071727374757677787969 unmodified lines&models.Question{},&models.Answer{},&models.UserAnswer{},&models.PersonalityAndPreferenceCV{},&models.FamilyMemberCV{},&models.PhysicalAndHealthCV{},&models.WorshipAndReligiousUnderstandingCV{},)if err != nil {
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267package cv_controller
import ( "api.qobiltu.id/middleware" "api.qobiltu.id/models" "api.qobiltu.id/response" "api.qobiltu.id/services" "github.com/gin-gonic/gin" "net/http" "strconv")
type CVController interface { SaveAccountDetails(ctx *gin.Context) GetAccountDetails(ctx *gin.Context)
SavePersonalityAndPreference(ctx *gin.Context) GetPersonalityAndPreference(ctx *gin.Context)
CreateFamilyMember(ctx *gin.Context) UpdateFamilyMember(ctx *gin.Context) ListFamilyMember(ctx *gin.Context) GetFamilyMember(ctx *gin.Context) DeleteFamilyMember(ctx *gin.Context)
SavePhysicalAndHealth(ctx *gin.Context) GetPhysicalAndHealth(ctx *gin.Context)
SaveWorshipAndReligiousUnderstanding(ctx *gin.Context) GetWorshipAndReligiousUnderstanding(ctx *gin.Context)}
type cvController struct { cvService services.CVService}
func NewCVController(cvService services.CVService) CVController { return &cvController{ cvService: cvService, }}
// --- Account Details ---func (c *cvController) SaveAccountDetails(ctx *gin.Context) { var req models.AccountDetailsRequest if err := ctx.ShouldBindJSON(&req); err != nil { response.HandleError(ctx, err) return }
accountData := middleware.GetAccountData(ctx) req.AccountID = int64(accountData.UserID)
res, err := c.cvService.SaveAccountDetails(ctx, &req) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, http.StatusOK, "Account details saved", res, nil)}
func (c *cvController) GetAccountDetails(ctx *gin.Context) { accountData := middleware.GetAccountData(ctx) accountID := int64(accountData.UserID)
res, err := c.cvService.GetAccountDetails(ctx, accountID) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, http.StatusOK, "Get account details success", res, nil)}
// --- Personality & Preference ---
func (c *cvController) SavePersonalityAndPreference(ctx *gin.Context) { var req models.PersonalityAndPreferenceCVRequest if err := ctx.ShouldBindJSON(&req); err != nil { response.HandleError(ctx, err) return }
accountData := middleware.GetAccountData(ctx) req.AccountID = int64(accountData.UserID)
res, err := c.cvService.SavePersonalityAndPreference(ctx, &req) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, http.StatusOK, "Personality and Preference saved", res, nil)}
func (c *cvController) GetPersonalityAndPreference(ctx *gin.Context) { accountData := middleware.GetAccountData(ctx) accountID := int64(accountData.UserID)
res, err := c.cvService.GetPersonalityAndPreference(ctx, accountID) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, http.StatusOK, "Get Personality and Preference success", res, nil)}
// --- Family Member ---
func (c *cvController) CreateFamilyMember(ctx *gin.Context) { var req models.FamilyMemberRequest if err := ctx.ShouldBindJSON(&req); err != nil { response.HandleError(ctx, err) return }
accountData := middleware.GetAccountData(ctx) req.AccountID = int64(accountData.UserID)
res, err := c.cvService.CreateFamilyMember(ctx, &req) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, http.StatusOK, "Family member saved", res, nil)}
func (c *cvController) UpdateFamilyMember(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.FamilyMemberRequest if err := ctx.ShouldBindJSON(&req); err != nil { response.HandleError(ctx, err) return }
res, err := c.cvService.UpdateFamilyMember(ctx, id, &req) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, http.StatusOK, "Family member updated", res, nil)}
func (c *cvController) ListFamilyMember(ctx *gin.Context) { accountData := middleware.GetAccountData(ctx) accountID := int64(accountData.UserID)
list, err := c.cvService.ListFamilyMember(ctx, accountID) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, http.StatusOK, "List family members", list, nil)}
func (c *cvController) GetFamilyMember(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.GetFamilyMember(ctx, id) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, http.StatusOK, "Get family member success", res, nil)}
func (c *cvController) DeleteFamilyMember(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.DeleteFamilyMember(ctx, id) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, http.StatusOK, "Family member deleted", nil, nil)}
// --- Physical and Health ---
func (c *cvController) SavePhysicalAndHealth(ctx *gin.Context) { var req models.PhysicalAndHealthRequest if err := ctx.ShouldBindJSON(&req); err != nil { response.HandleError(ctx, err) return }
accountData := middleware.GetAccountData(ctx) req.AccountID = int64(accountData.UserID)
res, err := c.cvService.SavePhysicalAndHealth(ctx, &req) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, http.StatusOK, "Physical and health saved", res, nil)}
func (c *cvController) GetPhysicalAndHealth(ctx *gin.Context) { accountData := middleware.GetAccountData(ctx) accountID := int64(accountData.UserID)
res, err := c.cvService.GetPhysicalAndHealth(ctx, accountID) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, http.StatusOK, "Get physical and health success", res, nil)}
// --- Worship and Religious Understanding ---
func (c *cvController) SaveWorshipAndReligiousUnderstanding(ctx *gin.Context) { var req models.WorshipAndReligiousUnderstandingRequest if err := ctx.ShouldBindJSON(&req); err != nil { response.HandleError(ctx, err) return }
accountData := middleware.GetAccountData(ctx) req.AccountID = int64(accountData.UserID)
res, err := c.cvService.SaveWorshipAndReligiousUnderstanding(ctx, &req) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, http.StatusOK, "Worship and religious understanding saved", res, nil)}
func (c *cvController) GetWorshipAndReligiousUnderstanding(ctx *gin.Context) { accountData := middleware.GetAccountData(ctx) accountID := int64(accountData.UserID)
res, err := c.cvService.GetWorshipAndReligiousUnderstanding(ctx, accountID) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, http.StatusOK, "Get worship and religious understanding success", res, nil)}1 unmodified line23456738 unmodified lines464748495051525354555657581 unmodified lineimport ("api.qobiltu.id/config""api.qobiltu.id/controller/health_check""api.qobiltu.id/mail""api.qobiltu.id/repositories"38 unmodified lineshealthCheckService := services.NewHealthCheckService(healthCheckRepository)healthCheckController := health_check_controller.NewHealthCheckController(healthCheckService)// start task processorerr = taskProcessor.Start()utils.FatalIfErr("failed to start task processor", err)slog.Info("Task processor started")// create servers, err := router.NewServer(healthCheckController)utils.FatalIfErr("failed to create server", err)// run server1 unmodified line234567838 unmodified lines47484950515253545556575859606162636465661 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"38 unmodified lineshealthCheckService := services.NewHealthCheckService(healthCheckRepository)healthCheckController := health_check_controller.NewHealthCheckController(healthCheckService)cvRepository := repositories.NewCVRepository(config.DB)cvService := services.NewCVService(cvRepository)cvController := cv_controller.NewCVController(cvService)// start task processorerr = taskProcessor.Start()utils.FatalIfErr("failed to start task processor", err)slog.Info("Task processor started")// create servers, err := router.NewServer(healthCheckController,cvController,)utils.FatalIfErr("failed to create server", err)// run server
32 unmodified lines333435363732 unmodified linesc.Abort()return}}32 unmodified lines33343536373839404142434432 unmodified linesc.Abort()return}}func GetAccountData(c *gin.Context) models.AccountData {cParam, _ := c.Get("accountData")if cParam != nil {return cParam.(models.AccountData)}return models.AccountData{}}
17 unmodified lines18192021222324252627282930313233343536147 unmodified lines18418518618718818919019119219319419519619719819920020120220320420520620717 unmodified lines}type AccountDetails struct {ID uint64 `gorm:"primaryKey" json:"id"`AccountID uint `json:"account_id"`InitialName string `json:"initial_name"`FullName *string `json:"full_name"`DateOfBirth *time.Time `json:"date_of_birth"`PlaceOfBirth *string `json:"place_of_birth"`Domicile *string `json:"domicile"`LastJob *string `json:"last_job"`Gender *string `json:"gender"`LastEducation *string `json:"last_education"`MaritalStatus *string `json:"marital_status"`Avatar *string `json:"avatar"`PhoneNumber *string `json:"phone_number"`}type EmailVerification struct {147 unmodified linesAverageScore float64 `gorm:"column:average_score" json:"average_score"`}// Gorm table name settingsfunc (Account) TableName() string { return "account" }func (AccountDetails) TableName() string { return "account_details" }func (EmailVerification) TableName() string { return "email_verifications" }func (ExternalAuth) TableName() string { return "extern_auth" }func (FCM) TableName() string { return "fcm" }func (ForgotPassword) TableName() string { return "forgot_password" }func (Academy) TableName() string { return "academy" }func (AcademyMaterial) TableName() string { return "academy_materials" }func (AcademyContent) TableName() string { return "academy_contents" }func (AcademyMaterialProgress) TableName() string { return "academy_materials_progress" }func (AcademyContentProgress) TableName() string { return "academy_contents_progress" }func (RegionProvince) TableName() string { return "region_provinces" }func (RegionCity) TableName() string { return "region_cities" }func (Answer) TableName() string { return "answers" }func (Question) TableName() string { return "questions" }func (Quiz) TableName() string { return "quizzes" }func (QuizAttempt) TableName() string { return "quiz_attempts" }func (UserAnswer) TableName() string { return "user_answers" }func (OptionCategory) TableName() string { return "option_categories" }func (OptionValues) TableName() string { return "option_values" }17 unmodified lines181920212223242526272829303132333435363738147 unmodified lines18618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129217 unmodified lines}type AccountDetails struct {ID uint64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"`AccountID uint `gorm:"column:account_id;not null;unique" json:"account_id"`InitialName string `gorm:"column:initial_name;not null" json:"initial_name"`FullName *string `gorm:"column:full_name" json:"full_name"`DateOfBirth *time.Time `gorm:"column:date_of_birth" json:"date_of_birth"`PlaceOfBirth *string `gorm:"column:place_of_birth" json:"place_of_birth"`Domicile *string `gorm:"column:domicile" json:"domicile"`LastJob *string `gorm:"column:last_job" json:"last_job"`Gender *string `gorm:"column:gender" json:"gender"`LastEducation *string `gorm:"column:last_education" json:"last_education"`MaritalStatus *string `gorm:"column:marital_status" json:"marital_status"`Avatar *string `gorm:"column:avatar" json:"avatar"`PhoneNumber *string `gorm:"column:phone_number" json:"phone_number"`CreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"`UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"`}type EmailVerification struct {147 unmodified linesAverageScore float64 `gorm:"column:average_score" json:"average_score"`}type (PersonalityAndPreferenceCV 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"`PositiveTraits *string `gorm:"column:positive_traits" json:"positive_traits"` // sifat positifNegativeTraits *string `gorm:"column:negative_traits" json:"negative_traits"` // sifat negatifHobbies *string `gorm:"column:hobbies" json:"hobbies"` // hobiLifeGoals *string `gorm:"column:life_goals" json:"life_goals"` // target hidupDailyActivities *string `gorm:"column:daily_activities" json:"daily_activities"` // kegiatan sehari-hariLeisureActivities *string `gorm:"column:leisure_activities" json:"leisure_activities"` // kegiatan waktu luangLikes *string `gorm:"column:likes" json:"likes"` // hal yang disukaiDislikes *string `gorm:"column:dislikes" json:"dislikes"` // hal yang tidak disukaiStressHandling *string `gorm:"column:stress_handling" json:"stress_handling"` // cara mengatasi stresAngerTriggers *string `gorm:"column:anger_triggers" json:"anger_triggers"` // pemicu amarahFavoriteFoodAndDrinks *string `gorm:"column:favorite_food_and_drinks" json:"favorite_food_and_drinks"` // makanan dan minuman favoritCanCook *bool `gorm:"column:can_cook" json:"can_cook"` // bisa memasakTypesOfDishesCooked *string `gorm:"column:types_of_dishes_cooked" json:"types_of_dishes_cooked"` // jenis masakan yang bisa dimasakMonthlyExpenses *string `gorm:"column:monthly_expenses" json:"monthly_expenses"` // pengeluaran per bulanCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"`UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"`}FamilyMemberCV struct {ID int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"`AccountID int64 `gorm:"column:account_id;not null" json:"account_id"`Account *Account `gorm:"foreignKey:AccountID;constraint:OnDelete:CASCADE" json:"account,omitempty"`Role *string `gorm:"column:role" json:"role"` // Peran dalam keluargaStatus *string `gorm:"column:status" json:"status"` // Status (Hidup, Wafat)Religion *string `gorm:"column:religion" json:"religion"` // AgamaJob *string `gorm:"column:job" json:"job"` // PekerjaanLastEducation *string `gorm:"column:last_education" json:"last_education"` // Pendidikan terakhirAge *int `gorm:"column:age" json:"age"` // UsiaCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"`UpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"`}PhysicalAndHealthCV 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"`HeightInCm *int `gorm:"column:height_cm" json:"height_cm"` // Tinggi badan dalam satuan sentimeterWeightInKg *int `gorm:"column:weight_kg" json:"weight_kg"` // Berat badan dalam satuan kilogramBodyShape *string `gorm:"column:body_shape" json:"body_shape"` // Bentuk tubuhSkinColor *string `gorm:"column:skin_color" json:"skin_color"` // Warna kulitHairType *string `gorm:"column:hair_type" json:"hair_type"` // Tipe rambutMedicalHistory *string `gorm:"column:medical_history" json:"medical_history"` // Riwayat penyakitPhysicalDisorder *string `gorm:"column:physical_disorder" json:"physical_disorder"` // Cacat fisikPhysicalTraits *string `gorm:"column:physical_traits" json:"physical_traits"` // Ciri khas fisikCreatedAt time.Time `gorm:"column:created_at;autoCreateTime" json:"created_at"` // Waktu data dibuatUpdatedAt time.Time `gorm:"column:updated_at;autoUpdateTime" json:"updated_at"` // Waktu data terakhir diperbarui}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"`})// Gorm table name settingsfunc (Account) TableName() string { return "account" }func (AccountDetails) TableName() string { return "account_details" }func (EmailVerification) TableName() string { return "email_verifications" }func (ExternalAuth) TableName() string { return "extern_auth" }func (FCM) TableName() string { return "fcm" }func (ForgotPassword) TableName() string { return "forgot_password" }func (Academy) TableName() string { return "academy" }func (AcademyMaterial) TableName() string { return "academy_materials" }func (AcademyContent) TableName() string { return "academy_contents" }func (AcademyMaterialProgress) TableName() string { return "academy_materials_progress" }func (AcademyContentProgress) TableName() string { return "academy_contents_progress" }func (RegionProvince) TableName() string { return "region_provinces" }func (RegionCity) TableName() string { return "region_cities" }func (Answer) TableName() string { return "answers" }func (Question) TableName() string { return "questions" }func (Quiz) TableName() string { return "quizzes" }func (QuizAttempt) TableName() string { return "quiz_attempts" }func (UserAnswer) TableName() string { return "user_answers" }func (OptionCategory) TableName() string { return "option_categories" }func (OptionValues) TableName() string { return "option_values" }func (PersonalityAndPreferenceCV) TableName() string { return "personality_and_preference_cv" }func (FamilyMemberCV) TableName() string { return "family_member_cv" }func (PhysicalAndHealthCV) TableName() string { return "physical_and_health_cv" }func (WorshipAndReligiousUnderstandingCV) TableName() string {return "worship_and_religious_understanding_cv"}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051package modelstype LoginRequest struct {Email string `json:"email" binding:"required"`Password string `json:"password" binding:"required"`}type RegisterRequest struct {Name string `json:"name"`Email string `json:"email" binding:"required,email"`Phone int `json:"phone"`Password string `json:"password" binding:"required"`}type ChangePasswordRequest struct {OldPassword string `json:"old_password" binding:"required" `NewPassword string `json:"new_password" binding:"required" `}type CreateVerifyEmailRequest struct {Token uint `json:"token" binding:"required"`}type OptionsRequest struct {OptionName string `json:"option_name" binding:"required"`OptionValue []string `json:"option_values" binding:"required"`}type ExternalAuthRequest struct {OauthID string `json:"oauth_id" binding:"required"`OauthProvider string `json:"oauth_provider" binding:"required"`IsAgreeTerms bool `json:"is_agree_terms"`IsSexualDisease bool `json:"is_sexual_disease"`}type ForgotPasswordRequest struct {Email string `json:"email" binding:"required,email"`}type ValidateForgotPasswordRequest struct {Token uint `json:"token" binding:"required"`NewPassword string `json:"new_password"`}type QuestionQuizRequest struct {QuestionNo int `json:"question_no" binding:"required"`}type AnswerQuizRequest struct {QuestionNo int `json:"question_no" binding:"required"`Answer int `json:"answer" binding:"required"`}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126package modelsimport "time"type LoginRequest struct {Email string `json:"email" binding:"required"`Password string `json:"password" binding:"required"`}type RegisterRequest struct {Name string `json:"name"`Email string `json:"email" binding:"required,email"`Phone int `json:"phone"`Password string `json:"password" binding:"required"`}type ChangePasswordRequest struct {OldPassword string `json:"old_password" binding:"required" `NewPassword string `json:"new_password" binding:"required" `}type CreateVerifyEmailRequest struct {Token uint `json:"token" binding:"required"`}type OptionsRequest struct {OptionName string `json:"option_name" binding:"required"`OptionValue []string `json:"option_values" binding:"required"`}type ExternalAuthRequest struct {OauthID string `json:"oauth_id" binding:"required"`OauthProvider string `json:"oauth_provider" binding:"required"`IsAgreeTerms bool `json:"is_agree_terms"`IsSexualDisease bool `json:"is_sexual_disease"`}type ForgotPasswordRequest struct {Email string `json:"email" binding:"required,email"`}type ValidateForgotPasswordRequest struct {Token uint `json:"token" binding:"required"`NewPassword string `json:"new_password"`}type QuestionQuizRequest struct {QuestionNo int `json:"question_no" binding:"required"`}type AnswerQuizRequest struct {QuestionNo int `json:"question_no" binding:"required"`Answer int `json:"answer" binding:"required"`}type (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})
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126package repositories
import ( "api.qobiltu.id/models" "context" "gorm.io/gorm")
type CVRepository interface { SaveAccountDetails(ctx context.Context, req *models.AccountDetails) (*models.AccountDetails, error) GetAccountDetailsByAccountID(ctx context.Context, accountID int64) (*models.AccountDetails, error)
SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCV) (*models.PersonalityAndPreferenceCV, error) GetPersonalityAndPreferenceByAccountID(ctx context.Context, accountID int64) (*models.PersonalityAndPreferenceCV, error)
SaveFamilyMember(ctx context.Context, req *models.FamilyMemberCV) (*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) error
SavePhysicalAndHealth(ctx context.Context, req *models.PhysicalAndHealthCV) (*models.PhysicalAndHealthCV, error) GetPhysicalAndHealthByAccountID(ctx context.Context, accountID int64) (*models.PhysicalAndHealthCV, error)
SaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingCV) (*models.WorshipAndReligiousUnderstandingCV, error) GetWorshipAndReligiousUnderstandingByAccountID(ctx context.Context, accountID int64) (*models.WorshipAndReligiousUnderstandingCV, error)}
type cvRepository struct { db *gorm.DB}
func NewCVRepository(db *gorm.DB) CVRepository { return &cvRepository{ db: db, }}
func (r *cvRepository) SaveAccountDetails(ctx context.Context, req *models.AccountDetails) (*models.AccountDetails, error) { if err := r.db.WithContext(ctx).Save(req).Error; err != nil { return req, err } return req, nil}
func (r *cvRepository) GetAccountDetailsByAccountID(ctx context.Context, accountID int64) (*models.AccountDetails, error) { var accountDetails models.AccountDetails if err := r.db.WithContext(ctx).Where("account_id = ?", accountID).First(&accountDetails).Error; err != nil { return nil, err } return &accountDetails, nil}
func (r *cvRepository) SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCV) (*models.PersonalityAndPreferenceCV, error) { if err := r.db.WithContext(ctx).Save(req).Error; err != nil { return req, err } return req, nil}
func (r *cvRepository) GetPersonalityAndPreferenceByAccountID(ctx context.Context, accountID int64) (*models.PersonalityAndPreferenceCV, error) { var personalityAndPreference models.PersonalityAndPreferenceCV if err := r.db.WithContext(ctx).Where("account_id = ?", accountID).First(&personalityAndPreference).Error; err != nil { return nil, err } return &personalityAndPreference, nil}
func (r *cvRepository) SaveFamilyMember(ctx context.Context, req *models.FamilyMemberCV) (*models.FamilyMemberCV, error) { if err := r.db.WithContext(ctx).Save(req).Error; err != nil { return req, err } return req, nil}
func (r *cvRepository) GetFamilyMember(ctx context.Context, id int64) (*models.FamilyMemberCV, error) { var familyMember models.FamilyMemberCV if err := r.db.WithContext(ctx).Where("id = ?", id).First(&familyMember).Error; err != nil { return nil, err } return &familyMember, nil}
func (r *cvRepository) DeleteFamilyMember(ctx context.Context, id int64) error { if err := r.db.WithContext(ctx).Where("id = ?", id).Delete(&models.FamilyMemberCV{}).Error; err != nil { return err } return nil}
func (r *cvRepository) ListFamilyMember(ctx context.Context, accountID int64) ([]models.FamilyMemberCV, error) { familyMembers := make([]models.FamilyMemberCV, 0) if err := r.db.WithContext(ctx).Where("account_id = ?", accountID).Find(&familyMembers).Error; err != nil { return nil, err } return familyMembers, nil}
func (r *cvRepository) SavePhysicalAndHealth(ctx context.Context, req *models.PhysicalAndHealthCV) (*models.PhysicalAndHealthCV, error) { if err := r.db.WithContext(ctx).Save(req).Error; err != nil { return req, err } return req, nil}
func (r *cvRepository) GetPhysicalAndHealthByAccountID(ctx context.Context, accountID int64) (*models.PhysicalAndHealthCV, error) { var physicalAndHealth models.PhysicalAndHealthCV if err := r.db.WithContext(ctx).Where("account_id = ?", accountID).First(&physicalAndHealth).Error; err != nil { return nil, err } return &physicalAndHealth, nil}
func (r *cvRepository) SaveWorshipAndReligiousUnderstanding(ctx context.Context, req *models.WorshipAndReligiousUnderstandingCV) (*models.WorshipAndReligiousUnderstandingCV, error) { if err := r.db.WithContext(ctx).Save(req).Error; err != nil { return req, err } return req, nil}
func (r *cvRepository) GetWorshipAndReligiousUnderstandingByAccountID(ctx context.Context, accountID int64) (*models.WorshipAndReligiousUnderstandingCV, error) { var worshipAndReligiousUnderstanding models.WorshipAndReligiousUnderstandingCV if err := r.db.WithContext(ctx).Where("account_id = ?", accountID).First(&worshipAndReligiousUnderstanding).Error; err != nil { return nil, err } return &worshipAndReligiousUnderstanding, nil}1234567891011121314151617181920212223242526package router
import "api.qobiltu.id/middleware"
func (s *Server) CVRoute() { routerGroup := s.router.Group("/api/v1/cv").Use(middleware.AuthUser) { 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)
routerGroup.POST("/family-members", s.cvController.CreateFamilyMember) routerGroup.GET("/family-members", s.cvController.ListFamilyMember) routerGroup.GET("/family-members/:id", s.cvController.GetFamilyMember) routerGroup.PUT("/family-members/:id", s.cvController.UpdateFamilyMember) routerGroup.DELETE("/family-members/:id", s.cvController.DeleteFamilyMember)
routerGroup.POST("/physical-and-healths", s.cvController.SavePhysicalAndHealth) routerGroup.GET("/physical-and-healths", s.cvController.GetPhysicalAndHealth)
routerGroup.POST("/worship-and-religious-understandings", s.cvController.SaveWorshipAndReligiousUnderstanding) routerGroup.GET("/worship-and-religious-understandings", s.cvController.GetWorshipAndReligiousUnderstanding) }}1234567891011121314151617181920package routerimport ("api.qobiltu.id/controller")func (s *Server) setupRoutes() {s.router.GET("/", controller.HomeController)AuthRoute(s.router)UserRoute(s.router)EmailRoute(s.router)OptionsRoute(s.router)AcademyRoute(s.router)QuizRoute(s.router)// another way to register routess.HealthCheckRoute()}123456789101112131415161718192021package routerimport ("api.qobiltu.id/controller")func (s *Server) setupRoutes() {s.router.GET("/", controller.HomeController)AuthRoute(s.router)UserRoute(s.router)EmailRoute(s.router)OptionsRoute(s.router)AcademyRoute(s.router)QuizRoute(s.router)// another way to register routess.HealthCheckRoute()s.CVRoute()}
1234561 unmodified line8910111213141516171 unmodified line192021222324package routerimport ("api.qobiltu.id/controller/health_check""github.com/gin-gonic/gin")1 unmodified linetype Server struct {router *gin.EnginehealthCheckController health_check_controller.HealthCheckController}func NewServer(healthCheckController health_check_controller.HealthCheckController,) (*Server, error) {router := gin.Default()1 unmodified lineserver := &Server{healthCheckController: healthCheckController,router: router,}12345671 unmodified line910111213141516171819201 unmodified line22232425262728package routerimport (cv_controller "api.qobiltu.id/controller/cv""api.qobiltu.id/controller/health_check""github.com/gin-gonic/gin")1 unmodified linetype Server struct {router *gin.EnginehealthCheckController health_check_controller.HealthCheckControllercvController cv_controller.CVController}func NewServer(healthCheckController health_check_controller.HealthCheckController,cvController cv_controller.CVController,) (*Server, error) {router := gin.Default()1 unmodified lineserver := &Server{healthCheckController: healthCheckController,cvController: cvController,router: router,}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108package services
import ( "api.qobiltu.id/models" "api.qobiltu.id/repositories" "api.qobiltu.id/response" "context" "errors" "gorm.io/gorm")
type CVService interface { SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCVRequest) (*models.PersonalityAndPreferenceCVResponse, error) GetPersonalityAndPreference(ctx context.Context, id int64) (*models.PersonalityAndPreferenceCVResponse, error)}
type cvService struct { cvRepository repositories.CVRepository}
func NewCVService(cvRepository repositories.CVRepository) CVService { return &cvService{ cvRepository: cvRepository, }}
func (s *cvService) SavePersonalityAndPreference(ctx context.Context, req *models.PersonalityAndPreferenceCVRequest) (*models.PersonalityAndPreferenceCVResponse, error) { // Ambil data lama jika ada personalityAndPreference, err := s.cvRepository.GetPersonalityAndPreferenceByAccountID(ctx, req.AccountID) if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { return nil, response.HandleGormError(err, "Internal Server Error") }
// Apply perubahan if personalityAndPreference == nil { personalityAndPreference = &models.PersonalityAndPreferenceCV{} }
personalityAndPreference.AccountID = req.AccountID personalityAndPreference.PositiveTraits = req.PositiveTraits personalityAndPreference.NegativeTraits = req.NegativeTraits personalityAndPreference.Hobbies = req.Hobbies personalityAndPreference.LifeGoals = req.LifeGoals personalityAndPreference.DailyActivities = req.DailyActivities personalityAndPreference.LeisureActivities = req.LeisureActivities personalityAndPreference.Likes = req.Likes personalityAndPreference.Dislikes = req.Dislikes personalityAndPreference.StressHandling = req.StressHandling personalityAndPreference.AngerTriggers = req.AngerTriggers personalityAndPreference.FavoriteFoodAndDrinks = req.FavoriteFoodAndDrinks personalityAndPreference.CanCook = req.CanCook personalityAndPreference.TypesOfDishesCooked = req.TypesOfDishesCooked personalityAndPreference.MonthlyExpenses = req.MonthlyExpenses
res, err := s.cvRepository.SavePersonalityAndPreference(ctx, personalityAndPreference) if err != nil { return nil, response.HandleGormError(err, "Internal Server Error") }
return &models.PersonalityAndPreferenceCVResponse{ ID: res.ID, AccountID: res.AccountID, PositiveTraits: res.PositiveTraits, NegativeTraits: res.NegativeTraits, Hobbies: res.Hobbies, LifeGoals: res.LifeGoals, DailyActivities: res.DailyActivities, LeisureActivities: res.LeisureActivities, Likes: res.Likes, Dislikes: res.Dislikes, StressHandling: res.StressHandling, AngerTriggers: res.AngerTriggers, FavoriteFoodAndDrinks: res.FavoriteFoodAndDrinks, CanCook: res.CanCook, TypesOfDishesCooked: res.TypesOfDishesCooked, MonthlyExpenses: res.MonthlyExpenses, CreatedAt: res.CreatedAt, UpdatedAt: res.UpdatedAt, }, nil}
func (s *cvService) GetPersonalityAndPreference(ctx context.Context, id int64) (*models.PersonalityAndPreferenceCVResponse, error) { res, err := s.cvRepository.GetPersonalityAndPreferenceByAccountID(ctx, id) if err != nil { return nil, response.HandleGormError(err, "Internal Server Error") } return &models.PersonalityAndPreferenceCVResponse{ ID: res.ID, AccountID: res.AccountID, PositiveTraits: res.PositiveTraits, NegativeTraits: res.NegativeTraits, Hobbies: res.Hobbies, LifeGoals: res.LifeGoals, DailyActivities: res.DailyActivities, LeisureActivities: res.LeisureActivities, Likes: res.Likes, Dislikes: res.Dislikes, StressHandling: res.StressHandling, AngerTriggers: res.AngerTriggers, FavoriteFoodAndDrinks: res.FavoriteFoodAndDrinks, CanCook: res.CanCook, TypesOfDishesCooked: res.TypesOfDishesCooked, MonthlyExpenses: res.MonthlyExpenses, CreatedAt: res.CreatedAt, UpdatedAt: res.UpdatedAt, }, nil}4 unmodified lines56789101113 unmodified lines252627282930314 unmodified lines"api.qobiltu.id/repositories""api.qobiltu.id/response""context""gorm.io/gorm")type HealthCheckService interface {13 unmodified linesfunc (s *healthCheckService) Check(ctx context.Context, req *models.HealthCheckRequest) (*models.HealthCheckResponse, error) {res, err := s.healthCheckRepository.Check(ctx, req)if err != nil {return nil, response.HandleGormError(gorm.ErrDuplicatedKey, "Internal Server Error")}return res, nil4 unmodified lines567891013 unmodified lines242526272829304 unmodified lines"api.qobiltu.id/repositories""api.qobiltu.id/response""context")type HealthCheckService interface {13 unmodified linesfunc (s *healthCheckService) Check(ctx context.Context, req *models.HealthCheckRequest) (*models.HealthCheckResponse, error) {res, err := s.healthCheckRepository.Check(ctx, req)if err != nil {return nil, response.HandleGormError(err, "Internal Server Error")}return res, nil
5 unmodified lines6785 unmodified lines.errorlogs/.idea5 unmodified lines67895 unmodified lines.errorlogs/.ideamy-notes
2 unmodified lines3456789101112131415161718192021222324252627282930312 unmodified linesimport ("api.qobiltu.id/models""api.qobiltu.id/response""api.qobiltu.id/services/health_check_service""github.com/gin-gonic/gin""net/http")type HealthCheckController struct {healthCheckService *health_check_service.HealthCheckService}func NewHealthCheckController(healthCheckService *health_check_service.HealthCheckService) *HealthCheckController {return &HealthCheckController{healthCheckService: healthCheckService,}}func (h *HealthCheckController) Check(ctx *gin.Context) {req := models.HealthCheckRequest{}res, err := h.healthCheckService.Check(ctx, &req)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, "Service is running", http.StatusOK, res, nil)}2 unmodified lines345678910111213141516171819202122232425262728293031323334352 unmodified linesimport ("api.qobiltu.id/models""api.qobiltu.id/response""api.qobiltu.id/services""github.com/gin-gonic/gin""net/http")type HealthCheckController interface {Check(ctx *gin.Context)}type healthCheckController struct {healthCheckService services.HealthCheckService}func NewHealthCheckController(healthCheckService services.HealthCheckService) HealthCheckController {return &healthCheckController{healthCheckService: healthCheckService,}}func (c *healthCheckController) Check(ctx *gin.Context) {req := models.HealthCheckRequest{}res, err := c.healthCheckService.Check(ctx, &req)if err != nil {response.HandleError(ctx, err)return}response.HandleSuccess(ctx, http.StatusOK, "Service OK", res, nil)}
5 unmodified lines678910111230 unmodified lines434445464748495 unmodified lines"api.qobiltu.id/mail""api.qobiltu.id/repositories""api.qobiltu.id/router""api.qobiltu.id/services/health_check_service""api.qobiltu.id/utils""api.qobiltu.id/worker""github.com/hibiken/asynq"30 unmodified lines// setup repo, service, and controllerhealthCheckRepository := repositories.NewHealthCheckRepository(config.DB)healthCheckService := health_check_service.NewHealthCheckService(healthCheckRepository)healthCheckController := health_check_controller.NewHealthCheckController(healthCheckService)// start task processor5 unmodified lines678910111230 unmodified lines434445464748495 unmodified lines"api.qobiltu.id/mail""api.qobiltu.id/repositories""api.qobiltu.id/router""api.qobiltu.id/services""api.qobiltu.id/utils""api.qobiltu.id/worker""github.com/hibiken/asynq"30 unmodified lines// setup repo, service, and controllerhealthCheckRepository := repositories.NewHealthCheckRepository(config.DB)healthCheckService := services.NewHealthCheckService(healthCheckRepository)healthCheckController := health_check_controller.NewHealthCheckController(healthCheckService)// start task processor
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207package modelsimport ("time"uuid "github.com/satori/go.uuid")type Account struct {Id uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid" `Email string `gorm:"uniqueIndex" json:"email"`Password string `json:"password"`IsEmailVerified bool `json:"is_email_verified"`IsDetailCompleted bool `json:"is_detail_completed"`CreatedAt time.Time `json:"created_at"`DeletedAt *time.Time `json:"deleted_at" gorm:"default:null"`}type AccountDetails struct {ID uint `gorm:"primaryKey" json:"id"`AccountID uint `json:"account_id"`InitialName string `json:"initial_name"`FullName *string `json:"full_name"`DateOfBirth *time.Time `json:"date_of_birth"`PlaceOfBirth *string `json:"place_of_birth"`Domicile *string `json:"domicile"`LastJob *string `json:"last_job"`Gender *bool `json:"gender"`LastEducation *string `json:"last_education"`MaritalStatus *string `json:"marital_status"`Avatar *string `json:"avatar"`PhoneNumber *string `json:"phone_number"`}type EmailVerification struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid" `Token uint `json:"token"`AccountID uint `json:"account_id"`IsExpired bool `json:"is_expired"`CreatedAt time.Time `json:"created_at"`ExpiredAt time.Time `json:"expired_at"`}type ExternalAuth struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid" `OauthID string `json:"oauth_id"`AccountID uint `json:"account_id"`OauthProvider string `json:"oauth_provider"`}type FCM struct {ID uint `gorm:"primaryKey" json:"id"`AccountID uint `json:"account_id"`FCMToken string `json:"fcm_token"`}type ForgotPassword struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid" `Token uint `json:"token"`AccountID uint `json:"account_id"`IsExpired bool `json:"is_expired"`CreatedAt time.Time `json:"created_at"`ExpiredAt time.Time `json:"expired_at"`}type Academy struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid"`Title string `json:"title"`Slug string `json:"slug" gorm:"uniqueIndex" `TotalMaterial int `json:"total_material"`CompletedMaterial int `json:"completed_material"`IsCompletedRead bool `json:"is_read"`IsPassedExam bool `json:"is_exam"`Description string `json:"description"`}type AcademyMaterial struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid"`AcademyID uint `json:"academy_id"`Title string `json:"title"`Slug string `json:"slug" gorm:"uniqueIndex"`IsCompleted bool `json:"is_completed"`Description string `json:"description"`}type AcademyContent struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `json:"uuid"`Title string `json:"title"`Order uint `json:"order"`AcademyMaterialID uint `json:"academy_material_id"`Description string `json:"description"`}type OptionCategory struct {ID uint `gorm:"primaryKey" json:"id"`OptionName string `json:"option_name"`OptionSlug string `json:"option_slug" gorm:"uniqueIndex"`}type OptionValues struct {ID uint `gorm:"primaryKey" json:"id"`OptionCategoryID uint `json:"option_category_id"`OptionValue string `json:"option_value"`}type AcademyMaterialProgress struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid"`AccountID uint `json:"account_id"`AcademyMaterialID uint `json:"academy_material_id"`Progress uint `json:"progress"`}type AcademyContentProgress struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid"`AccountID uint `json:"account_id"`AcademyID uint `json:"academy_id"`}type RegionProvince struct {ID uint `json:"id"`Name string `json:"name"`Code string `json:"code"`}type RegionCity struct {ID uint `json:"id"`Type string `json:"type"`Name string `json:"name"`Code string `json:"code"`FullCode string `json:"full_code"`ProvinceID uint `json:"province_id"`}type Answer struct {ID uint `gorm:"primaryKey" json:"id"`QuestionID uint `json:"question_id"`Content string `json:"content"`IsCorrect bool `json:"-"`}type Question struct {ID uint `gorm:"primaryKey" json:"id"`QuizID uint `json:"quiz_id"`Content string `json:"content"`Order int `json:"order"`CorrectAnswer uint `json:"-"`}type 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"`TimeLimit int `json:"time_limit"`MinScore int `json:"min_score"`CreatedAt time.Time `json:"created_at"`}type QuizAttempt struct {ID uint `gorm:"primaryKey" json:"id"`AccountID uint `json:"user_id"`QuizID uint `json:"quiz_id"`StartedAt time.Time `json:"started_at"`DueAt time.Time `json:"due_at"`FinishedAt *time.Time `json:"finished_at"`Score float64 `json:"score"`}type UserAnswer struct {ID uint `gorm:"primaryKey" json:"id"`QuizAttemptID uint `json:"quiz_attempt_id"`QuestionID uint `json:"question_id"`SelectedAnswer uint `json:"selected_answer"`IsCorrect bool `json:"is_correct"`}type QuizResult struct {QuizAttemptID uint `gorm:"column:quiz_attempt_id" json:"quiz_attempt_id"`TotalQuestions int `gorm:"column:total_questions" json:"total_questions"`CorrectAnswers int `gorm:"column:correct_answers" json:"correct_answers"`AverageScore float64 `gorm:"column:average_score" json:"average_score"`}// Gorm table name settingsfunc (Account) TableName() string { return "account" }func (AccountDetails) TableName() string { return "account_details" }func (EmailVerification) TableName() string { return "email_verifications" }func (ExternalAuth) TableName() string { return "extern_auth" }func (FCM) TableName() string { return "fcm" }func (ForgotPassword) TableName() string { return "forgot_password" }func (Academy) TableName() string { return "academy" }func (AcademyMaterial) TableName() string { return "academy_materials" }func (AcademyContent) TableName() string { return "academy_contents" }func (AcademyMaterialProgress) TableName() string { return "academy_materials_progress" }func (AcademyContentProgress) TableName() string { return "academy_contents_progress" }func (RegionProvince) TableName() string { return "region_provinces" }func (RegionCity) TableName() string { return "region_cities" }func (Answer) TableName() string { return "answers" }func (Question) TableName() string { return "questions" }func (Quiz) TableName() string { return "quizzes" }func (QuizAttempt) TableName() string { return "quiz_attempts" }func (UserAnswer) TableName() string { return "user_answers" }func (OptionCategory) TableName() string { return "option_categories" }func (OptionValues) TableName() string { return "option_values" }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207package modelsimport ("time"uuid "github.com/satori/go.uuid")type Account struct {Id uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid" `Email string `gorm:"uniqueIndex" json:"email"`Password string `json:"password"`IsEmailVerified bool `json:"is_email_verified"`IsDetailCompleted bool `json:"is_detail_completed"`CreatedAt time.Time `json:"created_at"`DeletedAt *time.Time `json:"deleted_at" gorm:"default:null"`}type AccountDetails struct {ID uint64 `gorm:"primaryKey" json:"id"`AccountID uint `json:"account_id"`InitialName string `json:"initial_name"`FullName *string `json:"full_name"`DateOfBirth *time.Time `json:"date_of_birth"`PlaceOfBirth *string `json:"place_of_birth"`Domicile *string `json:"domicile"`LastJob *string `json:"last_job"`Gender *string `json:"gender"`LastEducation *string `json:"last_education"`MaritalStatus *string `json:"marital_status"`Avatar *string `json:"avatar"`PhoneNumber *string `json:"phone_number"`}type EmailVerification struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid" `Token uint `json:"token"`AccountID uint `json:"account_id"`IsExpired bool `json:"is_expired"`CreatedAt time.Time `json:"created_at"`ExpiredAt time.Time `json:"expired_at"`}type ExternalAuth struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid" `OauthID string `json:"oauth_id"`AccountID uint `json:"account_id"`OauthProvider string `json:"oauth_provider"`}type FCM struct {ID uint `gorm:"primaryKey" json:"id"`AccountID uint `json:"account_id"`FCMToken string `json:"fcm_token"`}type ForgotPassword struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid" `Token uint `json:"token"`AccountID uint `json:"account_id"`IsExpired bool `json:"is_expired"`CreatedAt time.Time `json:"created_at"`ExpiredAt time.Time `json:"expired_at"`}type Academy struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid"`Title string `json:"title"`Slug string `json:"slug" gorm:"uniqueIndex" `TotalMaterial int `json:"total_material"`CompletedMaterial int `json:"completed_material"`IsCompletedRead bool `json:"is_read"`IsPassedExam bool `json:"is_exam"`Description string `json:"description"`}type AcademyMaterial struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid"`AcademyID uint `json:"academy_id"`Title string `json:"title"`Slug string `json:"slug" gorm:"uniqueIndex"`IsCompleted bool `json:"is_completed"`Description string `json:"description"`}type AcademyContent struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `json:"uuid"`Title string `json:"title"`Order uint `json:"order"`AcademyMaterialID uint `json:"academy_material_id"`Description string `json:"description"`}type OptionCategory struct {ID uint `gorm:"primaryKey" json:"id"`OptionName string `json:"option_name"`OptionSlug string `json:"option_slug" gorm:"uniqueIndex"`}type OptionValues struct {ID uint `gorm:"primaryKey" json:"id"`OptionCategoryID uint `json:"option_category_id"`OptionValue string `json:"option_value"`}type AcademyMaterialProgress struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid"`AccountID uint `json:"account_id"`AcademyMaterialID uint `json:"academy_material_id"`Progress uint `json:"progress"`}type AcademyContentProgress struct {ID uint `gorm:"primaryKey" json:"id"`UUID uuid.UUID `gorm:"type:uuid" json:"uuid"`AccountID uint `json:"account_id"`AcademyID uint `json:"academy_id"`}type RegionProvince struct {ID uint `json:"id"`Name string `json:"name"`Code string `json:"code"`}type RegionCity struct {ID uint `json:"id"`Type string `json:"type"`Name string `json:"name"`Code string `json:"code"`FullCode string `json:"full_code"`ProvinceID uint `json:"province_id"`}type Answer struct {ID uint `gorm:"primaryKey" json:"id"`QuestionID uint `json:"question_id"`Content string `json:"content"`IsCorrect bool `json:"-"`}type Question struct {ID uint `gorm:"primaryKey" json:"id"`QuizID uint `json:"quiz_id"`Content string `json:"content"`Order int `json:"order"`CorrectAnswer uint `json:"-"`}type 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"`TimeLimit int `json:"time_limit"`MinScore int `json:"min_score"`CreatedAt time.Time `json:"created_at"`}type QuizAttempt struct {ID uint `gorm:"primaryKey" json:"id"`AccountID uint `json:"user_id"`QuizID uint `json:"quiz_id"`StartedAt time.Time `json:"started_at"`DueAt time.Time `json:"due_at"`FinishedAt *time.Time `json:"finished_at"`Score float64 `json:"score"`}type UserAnswer struct {ID uint `gorm:"primaryKey" json:"id"`QuizAttemptID uint `json:"quiz_attempt_id"`QuestionID uint `json:"question_id"`SelectedAnswer uint `json:"selected_answer"`IsCorrect bool `json:"is_correct"`}type QuizResult struct {QuizAttemptID uint `gorm:"column:quiz_attempt_id" json:"quiz_attempt_id"`TotalQuestions int `gorm:"column:total_questions" json:"total_questions"`CorrectAnswers int `gorm:"column:correct_answers" json:"correct_answers"`AverageScore float64 `gorm:"column:average_score" json:"average_score"`}// Gorm table name settingsfunc (Account) TableName() string { return "account" }func (AccountDetails) TableName() string { return "account_details" }func (EmailVerification) TableName() string { return "email_verifications" }func (ExternalAuth) TableName() string { return "extern_auth" }func (FCM) TableName() string { return "fcm" }func (ForgotPassword) TableName() string { return "forgot_password" }func (Academy) TableName() string { return "academy" }func (AcademyMaterial) TableName() string { return "academy_materials" }func (AcademyContent) TableName() string { return "academy_contents" }func (AcademyMaterialProgress) TableName() string { return "academy_materials_progress" }func (AcademyContentProgress) TableName() string { return "academy_contents_progress" }func (RegionProvince) TableName() string { return "region_provinces" }func (RegionCity) TableName() string { return "region_cities" }func (Answer) TableName() string { return "answers" }func (Question) TableName() string { return "questions" }func (Quiz) TableName() string { return "quizzes" }func (QuizAttempt) TableName() string { return "quiz_attempts" }func (UserAnswer) TableName() string { return "user_answers" }func (OptionCategory) TableName() string { return "option_categories" }func (OptionValues) TableName() string { return "option_values" }
1234567891011121314151617package 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"`}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()}
12345678package modelstype HealthCheckRequest struct {ExampleCallback func() (string, string)}type HealthCheckResponse struct {DatabaseStatus string `json:"database_status"`123456package modelstype HealthCheckRequest struct{}type HealthCheckResponse struct {DatabaseStatus string `json:"database_status"`
6 unmodified lines78910111213141516171819202122232425262728293031323334351 unmodified line37383940416 unmodified lines"gorm.io/gorm")type HealthCheckRepository struct {db *gorm.DB}func NewHealthCheckRepository(db *gorm.DB) *HealthCheckRepository {return &HealthCheckRepository{db: db,}}func (r *HealthCheckRepository) Check(ctx context.Context, req *models.HealthCheckRequest) (*models.HealthCheckResponse, error) {res := &models.HealthCheckResponse{}err := config.RunTx(ctx, r.db, func(tx *gorm.DB) error {if err := tx.Exec("SELECT 1").Error; err != nil {return err}// call logic from service if needed// instead of writing the logic in the repository// and make sure the param consist of the ctx and requestres.DatabaseStatus, res.RedisStatus = req.ExampleCallback()return nil})1 unmodified linereturn nil, err}return res, nil}6 unmodified lines789101112131415161718192021222324252627282930311 unmodified line33343536373839406 unmodified lines"gorm.io/gorm")type HealthCheckRepository interface {Check(ctx context.Context, req *models.HealthCheckRequest) (*models.HealthCheckResponse, error)}type healthCheckRepository struct {db *gorm.DB}func NewHealthCheckRepository(db *gorm.DB) HealthCheckRepository {return &healthCheckRepository{db: db,}}func (r *healthCheckRepository) Check(ctx context.Context, req *models.HealthCheckRequest) (*models.HealthCheckResponse, error) {err := config.RunTx(ctx, r.db, func(tx *gorm.DB) error {if err := tx.Exec("SELECT 1").Error; err != nil {return err}return nil})1 unmodified linereturn nil, err}return &models.HealthCheckResponse{DatabaseStatus: "OK",RedisStatus: "OK",}, nil}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879package response
import ( "api.qobiltu.id/models" "api.qobiltu.id/utils" "errors" "net/http"
"github.com/gin-gonic/gin")
func HandleError(c *gin.Context, err error) { var exception models.Exception
if errors.As(err, &exception) { utils.LogError(exception.Err)
switch { case exception.DataDuplicate: responseError(c, http.StatusConflict, exception) case exception.Unauthorized: responseError(c, http.StatusUnauthorized, exception) case exception.DataNotFound: responseError(c, http.StatusNotFound, exception) case exception.Forbidden: responseError(c, http.StatusForbidden, exception) case exception.BadRequest: responseError(c, http.StatusBadRequest, exception) case exception.InternalServerError: responseError(c, http.StatusInternalServerError, exception) case exception.QueryError: responseError(c, http.StatusInternalServerError, exception) case exception.InvalidPasswordLength: responseError(c, http.StatusBadRequest, exception) case exception.IsPassTheLimit: responseError(c, http.StatusTooManyRequests, exception) case exception.IsTimeOut: responseError(c, http.StatusRequestTimeout, exception) case exception.AttemptNotFound: responseError(c, http.StatusNotFound, exception) case exception.ValidationError: responseError(c, http.StatusUnprocessableEntity, exception) default: responseError(c, http.StatusInternalServerError, exception) } } else { utils.LogError(err) responseError(c, http.StatusInternalServerError, models.Exception{ InternalServerError: true, Message: "Internal Server Error", }) }}
func HandleSuccess(c *gin.Context, status int, msg string, data any, metaData any) { res := models.SuccessResponse{ Status: "success", Message: msg, Data: data, MetaData: metaData, }
c.JSON(status, res) return}
func responseError(c *gin.Context, status int, exception models.Exception) { message := exception.Message exception.Message = ""
res := models.ErrorResponse{ Status: "error", Message: message, Errors: exception, }
c.AbortWithStatusJSON(status, res) return}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162package response
import ( "api.qobiltu.id/models" "errors" "strings"
"gorm.io/gorm")
func HandleGormError(err error, fallbackMessage string) error { if err == nil { return nil }
if errors.Is(err, gorm.ErrRecordNotFound) { return models.Exception{ Message: "Data not found", DataNotFound: true, Err: err, } }
lowerErr := strings.ToLower(err.Error()) if strings.Contains(lowerErr, "duplicated key") || strings.Contains(lowerErr, "unique constraint") || strings.Contains(lowerErr, "duplicate entry") { return models.Exception{ Message: "Data already exists", DataDuplicate: true, Err: err, } }
if strings.Contains(lowerErr, "password") && strings.Contains(lowerErr, "length") { return models.Exception{ Message: "Invalid password length", InvalidPasswordLength: true, Err: err, } }
if strings.Contains(lowerErr, "permission denied") || strings.Contains(lowerErr, "forbidden") { return models.Exception{ Message: "Access forbidden", Forbidden: true, Err: err, } }
if errors.As(err, &gorm.ErrInvalidData) { return models.Exception{ Message: "Invalid data format", BadRequest: true, Err: err, } }
return models.Exception{ Message: fallbackMessage, InternalServerError: true, Err: err, }}6 unmodified lines78910111213141516176 unmodified linestype Server struct {router *gin.EnginehealthCheckController *health_check_controller.HealthCheckController}func NewServer(healthCheckController *health_check_controller.HealthCheckController,) (*Server, error) {router := gin.Default()6 unmodified lines78910111213141516176 unmodified linestype Server struct {router *gin.EnginehealthCheckController health_check_controller.HealthCheckController}func NewServer(healthCheckController health_check_controller.HealthCheckController,) (*Server, error) {router := gin.Default()
1234567891011121314151617181920212223242526272829303132package services
import ( "api.qobiltu.id/models" "api.qobiltu.id/repositories" "api.qobiltu.id/response" "context" "gorm.io/gorm")
type HealthCheckService interface { Check(ctx context.Context, req *models.HealthCheckRequest) (*models.HealthCheckResponse, error)}
type healthCheckService struct { healthCheckRepository repositories.HealthCheckRepository}
func NewHealthCheckService(healthCheckRepository repositories.HealthCheckRepository) HealthCheckService { return &healthCheckService{ healthCheckRepository: healthCheckRepository, }}
func (s *healthCheckService) Check(ctx context.Context, req *models.HealthCheckRequest) (*models.HealthCheckResponse, error) { res, err := s.healthCheckRepository.Check(ctx, req) if err != nil { return nil, response.HandleGormError(gorm.ErrDuplicatedKey, "Internal Server Error") }
return res, nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115package servicesimport ("regexp""strconv""strings""api.qobiltu.id/models""api.qobiltu.id/repositories")type UserProfileService struct {Service[models.AccountDetails, models.UserProfileResponse]}// SanitizePhoneNumber membersihkan dan menormalkan nomor telepon ke format +62func 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}func (s *UserProfileService) Create() {userProfile := repositories.CreateAccountDetails(s.Constructor)s.Error = userProfile.RowsErrorif userProfile.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "There is no account with given credentials!"return}s.Result = models.UserProfileResponse{Account: repositories.GetAccountById(s.Constructor.AccountID).Result,Details: userProfile.Result,}}func (s *UserProfileService) Retrieve() {userProfile := repositories.GetDetailAccountById(s.Constructor.AccountID)s.Error = userProfile.RowsErrorif userProfile.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "There is no account with given credentials!"return}s.Result = models.UserProfileResponse{Account: repositories.GetAccountById(s.Constructor.AccountID).Result,Details: userProfile.Result,}s.Result.Account.Password = "SECRET"}func (s *UserProfileService) Update() {if s.Constructor.PhoneNumber != nil {phoneNumber := *s.Constructor.PhoneNumber*s.Constructor.PhoneNumber = SanitizePhoneNumber(phoneNumber)}usersCount := repositories.GetAllAccount().RowsCountvar initialName stringif s.Constructor.Gender != nil {if *s.Constructor.Gender {initialName = "IKH_"} else {initialName = "AKH_"}}initialName += strconv.Itoa(usersCount)s.Constructor.InitialName = initialNameuserProfile := repositories.UpdateAccountDetails(s.Constructor)s.Error = userProfile.RowsErrorif userProfile.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "There is no account with given credentials!"return}account := repositories.GetAccountById(s.Constructor.AccountID)account.Result.IsDetailCompleted = (userProfile.Result.InitialName != "" &&userProfile.Result.FullName != nil &&userProfile.Result.DateOfBirth != nil &&userProfile.Result.PlaceOfBirth != nil &&userProfile.Result.Domicile != nil &&userProfile.Result.LastJob != nil &&userProfile.Result.Gender != nil &&userProfile.Result.LastEducation != nil &&userProfile.Result.MaritalStatus != nil)repositories.UpdateAccount(account.Result)s.Result = models.UserProfileResponse{Account: account.Result,Details: userProfile.Result,}s.Result.Account.Password = "SECRET"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115package servicesimport ("regexp""strconv""strings""api.qobiltu.id/models""api.qobiltu.id/repositories")type UserProfileService struct {Service[models.AccountDetails, models.UserProfileResponse]}// SanitizePhoneNumber membersihkan dan menormalkan nomor telepon ke format +62func 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}func (s *UserProfileService) Create() {userProfile := repositories.CreateAccountDetails(s.Constructor)s.Error = userProfile.RowsErrorif userProfile.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "There is no account with given credentials!"return}s.Result = models.UserProfileResponse{Account: repositories.GetAccountById(s.Constructor.AccountID).Result,Details: userProfile.Result,}}func (s *UserProfileService) Retrieve() {userProfile := repositories.GetDetailAccountById(s.Constructor.AccountID)s.Error = userProfile.RowsErrorif userProfile.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "There is no account with given credentials!"return}s.Result = models.UserProfileResponse{Account: repositories.GetAccountById(s.Constructor.AccountID).Result,Details: userProfile.Result,}s.Result.Account.Password = "SECRET"}func (s *UserProfileService) Update() {if s.Constructor.PhoneNumber != nil {phoneNumber := *s.Constructor.PhoneNumber*s.Constructor.PhoneNumber = SanitizePhoneNumber(phoneNumber)}usersCount := repositories.GetAllAccount().RowsCountvar initialName stringif s.Constructor.Gender != nil {if strings.ToLower(*s.Constructor.Gender) == "laki-laki" {initialName = "IKH_"} else {initialName = "AKH_"}}initialName += strconv.Itoa(usersCount)s.Constructor.InitialName = initialNameuserProfile := repositories.UpdateAccountDetails(s.Constructor)s.Error = userProfile.RowsErrorif userProfile.NoRecord {s.Exception.DataNotFound = trues.Exception.Message = "There is no account with given credentials!"return}account := repositories.GetAccountById(s.Constructor.AccountID)account.Result.IsDetailCompleted = (userProfile.Result.InitialName != "" &&userProfile.Result.FullName != nil &&userProfile.Result.DateOfBirth != nil &&userProfile.Result.PlaceOfBirth != nil &&userProfile.Result.Domicile != nil &&userProfile.Result.LastJob != nil &&userProfile.Result.Gender != nil &&userProfile.Result.LastEducation != nil &&userProfile.Result.MaritalStatus != nil)repositories.UpdateAccount(account.Result)s.Result = models.UserProfileResponse{Account: account.Result,Details: userProfile.Result,}s.Result.Account.Password = "SECRET"}
24 unmodified lines25262728293024 unmodified lines# Set working directoryWORKDIR /app# Copy hasil build dari builder ke image runtimeCOPY --from=builder /app/main .24 unmodified lines25262728293031323334353624 unmodified lines# Set working directoryWORKDIR /app# Install tzdataRUN apk update && apk add --no-cache tzdata# Set the timezone environment variableENV TZ="Asia/Jakarta"# Copy hasil build dari builder ke image runtimeCOPY --from=builder /app/main .
24 unmodified lines2526272824 unmodified linesgit pull origin maindocker-compose down -vdocker-compose up --build -dEOF24 unmodified lines252627282924 unmodified linesgit pull origin maindocker-compose down -vdocker-compose up --build -ddocker image prune -fEOF
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168package apperror
import ( "api.qobiltu.id/validation" "fmt")
// AppError is a custom error type for the application.type AppError struct { Code string // Optional: Error code for programmatic handling Message string // Human-readable error message Err error // Underlying error, if any Details map[string]any // Optional: Additional details about the error}
func (e AppError) Error() string { if e.Code != "" { return fmt.Sprintf("[%s] %s", e.Code, e.Message) } return e.Message}
// NewAppError creates a new AppError.func NewAppError(code, message string, err error, details map[string]any) error { return &AppError{ Code: code, Message: message, Err: err, Details: details, }}
// ValidationError represents errors related to data validation.type ValidationError struct { Errors []validation.ErrorMessage // Structure to hold field and message of validation errors}
func (e ValidationError) Error() string { return fmt.Sprintf("validation failed: %+v", e.Errors)}
// NewValidationError creates a new ValidationError.func NewValidationError(message string, errors []validation.ErrorMessage) error { return &AppError{ Code: "VALIDATION_ERROR", Message: message, Err: ValidationError{Errors: errors}, }}
// InternalError represents unexpected errors within the application.type InternalError struct { Message string Err error}
func (e InternalError) Error() string { return fmt.Sprintf("internal server error: %v", e.Err)}
// NewInternalError creates a new InternalError wrapped in AppError.func NewInternalError(message string, err error) error { return &AppError{ Code: "INTERNAL_ERROR", Message: message, Err: InternalError{Message: message, Err: err}, }}
// ConflictError represents errors due to a conflict with the current state.type ConflictError struct { Message string Err error}
func (e ConflictError) Error() string { return fmt.Sprintf("conflict: %s", e.Err)}
// NewConflictError creates a new ConflictError wrapped in AppError.func NewConflictError(message string, err error) error { return &AppError{ Code: "CONFLICT_ERROR", Message: message, Err: ConflictError{Message: message, Err: err}, }}
// NotFoundError represents errors when a resource is not found.type NotFoundError struct { Message string Resource string ID any}
func (e NotFoundError) Error() string { return fmt.Sprintf("%s with ID '%v' not found", e.Resource, e.ID)}
// NewNotFoundError creates a new NotFoundError wrapped in AppError.func NewNotFoundError(resource string, id any) error { message := fmt.Sprintf("%s not found", resource) return &AppError{ Code: "NOT_FOUND_ERROR", Message: fmt.Sprintf("%s not found", resource), Err: NotFoundError{Message: message, Resource: resource, ID: id}, Details: map[string]any{ "resource": resource, "id": id, }, }}
// UnauthorizedError represents errors when access is denied due to lack of credentials.type UnauthorizedError struct { Message string Err error}
func (e UnauthorizedError) Error() string { return fmt.Sprintf("unauthorized: %s", e.Err)}
// NewUnauthorizedError creates a new UnauthorizedError wrapped in AppError.func NewUnauthorizedError(message string, err error) error { return &AppError{ Code: "UNAUTHORIZED_ERROR", Message: message, Err: UnauthorizedError{Message: message, Err: err}, }}
// ForbiddenError represents errors when access is denied even with valid credentials.type ForbiddenError struct { Message string Err error}
func (e ForbiddenError) Error() string { return fmt.Sprintf("forbidden: %s", e.Err)}
// NewForbiddenError creates a new ForbiddenError wrapped in AppError.func NewForbiddenError(message string, err error) error { return &AppError{ Code: "FORBIDDEN_ERROR", Message: message, Err: ForbiddenError{Message: message, Err: err}, }}
// BadRequestError represents errors due to an invalid request.type BadRequestError struct { Message string Err error}
func (e BadRequestError) Error() string { return fmt.Sprintf("bad request: %s", e.Err)}
func NewBadRequestError(message string, err error) error { return &AppError{ Code: "BAD_REQUEST_ERROR", Message: message, Err: BadRequestError{Message: message, Err: err}, }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879package configimport ("fmt""log""os""gorm.io/driver/postgres""gorm.io/gorm""gorm.io/gorm/logger""api.qobiltu.id/models""github.com/joho/godotenv")var DB *gorm.DBvar err errorvar Salt stringfunc init() {godotenv.Load()if err != nil {fmt.Println("Gagal membaca file .env")return}os.Setenv("TZ", "Asia/Jakarta")dbHost := os.Getenv("DB_HOST")dbPort := os.Getenv("DB_PORT")dbUser := os.Getenv("DB_USER")dbPassword := os.Getenv("DB_PASSWORD")dbName := os.Getenv("DB_NAME")Salt := os.Getenv("SALT")dsn := "host=" + dbHost + " user=" + dbUser + " password=" + dbPassword + " dbname=" + dbName + " port=" + dbPort + " sslmode=disable TimeZone=Asia/Jakarta"DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{TranslateError: true})if err != nil {panic(err)}if Salt == "" {Salt = "D3f4u|t"}// Call AutoMigrateAll to perform auto-migrationAutoMigrateAll(DB)}func AutoMigrateAll(db *gorm.DB) {// Enable logger to see SQL logsdb.Logger.LogMode(logger.Info)// Auto-migrate all modelserr := db.AutoMigrate(&models.Account{},&models.AccountDetails{},&models.EmailVerification{},&models.ExternalAuth{},&models.FCM{},&models.ForgotPassword{},&models.Academy{},&models.AcademyMaterial{},&models.AcademyContent{},&models.AcademyMaterialProgress{},&models.AcademyContentProgress{},&models.RegionCity{},&models.RegionProvince{},&models.OptionCategory{},&models.OptionValues{},&models.Quiz{},&models.QuizAttempt{},&models.Question{},&models.Answer{},&models.UserAnswer{},)if err != nil {log.Fatal(err)}fmt.Println("Migration completed successfully.")}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980package configimport ("fmt""log""log/slog""os""gorm.io/driver/postgres""gorm.io/gorm""gorm.io/gorm/logger""api.qobiltu.id/models""github.com/joho/godotenv")var DB *gorm.DBvar err errorvar Salt stringfunc init() {godotenv.Load()if err != nil {fmt.Println("Gagal membaca file .env")return}os.Setenv("TZ", "Asia/Jakarta")dbHost := os.Getenv("DB_HOST")dbPort := os.Getenv("DB_PORT")dbUser := os.Getenv("DB_USER")dbPassword := os.Getenv("DB_PASSWORD")dbName := os.Getenv("DB_NAME")Salt := os.Getenv("SALT")dsn := "host=" + dbHost + " user=" + dbUser + " password=" + dbPassword + " dbname=" + dbName + " port=" + dbPort + " sslmode=disable TimeZone=Asia/Jakarta"DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{TranslateError: true})if err != nil {panic(err)}if Salt == "" {Salt = "D3f4u|t"}// Call AutoMigrateAll to perform auto-migrationAutoMigrateAll(DB)}func AutoMigrateAll(db *gorm.DB) {// Enable logger to see SQL logsdb.Logger.LogMode(logger.Info)// Auto-migrate all modelserr := db.AutoMigrate(&models.Account{},&models.AccountDetails{},&models.EmailVerification{},&models.ExternalAuth{},&models.FCM{},&models.ForgotPassword{},&models.Academy{},&models.AcademyMaterial{},&models.AcademyContent{},&models.AcademyMaterialProgress{},&models.AcademyContentProgress{},&models.RegionCity{},&models.RegionProvince{},&models.OptionCategory{},&models.OptionValues{},&models.Quiz{},&models.QuizAttempt{},&models.Question{},&models.Answer{},&models.UserAnswer{},)if err != nil {log.Fatal(err)}slog.Info("Auto-migration completed successfully")}
12345678910111213141516171819202122232425262728293031323334package config
import ( "context" "fmt" "gorm.io/gorm")
func RunTx(ctx context.Context, db *gorm.DB, fn func(tx *gorm.DB) error) error { tx := db.WithContext(ctx).Begin() if tx.Error != nil { return fmt.Errorf("failed to begin transaction: %w", tx.Error) }
defer func() { if p := recover(); p != nil { _ = tx.Rollback() panic(p) // Re-throw panic setelah rollback } }()
if err := fn(tx); err != nil { if rbErr := tx.Rollback().Error; rbErr != nil { return fmt.Errorf("transaction error: %v, rollback error: %w", err, rbErr) } return err }
if err := tx.Commit().Error; err != nil { return fmt.Errorf("failed to commit transaction: %w", err) }
return nil}12345678910111213141516171819202122232425262728293031package health_check_controller
import ( "api.qobiltu.id/models" "api.qobiltu.id/response" "api.qobiltu.id/services/health_check_service" "github.com/gin-gonic/gin" "net/http")
type HealthCheckController struct { healthCheckService *health_check_service.HealthCheckService}
func NewHealthCheckController(healthCheckService *health_check_service.HealthCheckService) *HealthCheckController { return &HealthCheckController{ healthCheckService: healthCheckService, }}
func (h *HealthCheckController) Check(ctx *gin.Context) { req := models.HealthCheckRequest{}
res, err := h.healthCheckService.Check(ctx, &req) if err != nil { response.HandleError(ctx, err) return }
response.HandleSuccess(ctx, "Service is running", http.StatusOK, res, nil)}123456789101112131415package 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"`Message string `json:"message,omitempty"`}1234567891011121314151617package 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"`}
12345678910package models
type HealthCheckRequest struct { ExampleCallback func() (string, string)}
type HealthCheckResponse struct { DatabaseStatus string `json:"database_status"` RedisStatus string `json:"redis_status"`}1234567891011121314151617181920212223242526272829303132333435363738394041package repositories
import ( "api.qobiltu.id/config" "api.qobiltu.id/models" "context" "gorm.io/gorm")
type HealthCheckRepository struct { db *gorm.DB}
func NewHealthCheckRepository(db *gorm.DB) *HealthCheckRepository { return &HealthCheckRepository{ db: db, }}
func (r *HealthCheckRepository) Check(ctx context.Context, req *models.HealthCheckRequest) (*models.HealthCheckResponse, error) { res := &models.HealthCheckResponse{}
err := config.RunTx(ctx, r.db, func(tx *gorm.DB) error { if err := tx.Exec("SELECT 1").Error; err != nil { return err }
// call logic from service if needed // instead of writing the logic in the repository // and make sure the param consist of the ctx and request res.DatabaseStatus, res.RedisStatus = req.ExampleCallback()
return nil })
if err != nil { return nil, err }
return res, nil}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758package response
import ( "errors" "fmt")
type PagingInfo struct { HasPreviousPage bool `json:"has_previous_page"` HasNextPage bool `json:"has_next_page"` CurrentPage int `json:"current_page"` PerPage int `json:"per_page"` TotalData int `json:"total_data"` LastPage int `json:"last_page"` From int `json:"from"` To int `json:"to"` TotalDataInCurrentPage int `json:"total_data_in_current_page"` Label string `json:"label"`}
var ErrPageInfo = errors.New("per_page harus lebih besar dari 0 dan offset tidak boleh negatif")
func NewPagingInfo(currentPage, perPage, offset, totalData int) (*PagingInfo, error) { if perPage <= 0 || offset < 0 { return nil, ErrPageInfo }
lastPage := totalData / perPage if totalData%perPage != 0 { lastPage++ }
to := min(offset+perPage, totalData) from := int(0) if to > offset { from = offset + 1 }
if currentPage > lastPage { currentPage = lastPage }
totalDataInCurrentPage := to - offset label := fmt.Sprintf("Menampilkan %d sampai %d dari %d data", from, to, totalData)
return &PagingInfo{ HasPreviousPage: currentPage > 1, HasNextPage: currentPage < lastPage, CurrentPage: currentPage, PerPage: perPage, TotalData: totalData, LastPage: lastPage, From: from, To: to, TotalDataInCurrentPage: totalDataInCurrentPage, Label: label, }, nil}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152package response
import ( errors "api.qobiltu.id/apperror" "api.qobiltu.id/models" goErrors "errors" "fmt" "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" "net/http")
type ErrorResponse struct { Details string `json:"details"` ValidationErrors []ValidationError `json:"validation_errors,omitempty"` models.Exception}
type API struct { Status string `json:"status"` Message string `json:"message,omitempty"` Data any `json:"data,omitempty"` MetaData any `json:"meta_data"` Error *ErrorResponse `json:"errors,omitempty"`}
type List struct { List any `json:"list"`}
type ValidationError struct { Field string `json:"field"` Message string `json:"message"`}
func HandleError(c *gin.Context, err error) {
apiResponse := API{ Status: "error", Message: "An error occurred, " + err.Error(), Error: &ErrorResponse{ Exception: models.Exception{Message: ""}, }, MetaData: struct{}{}, }
var appErr *errors.AppError
if goErrors.As(err, &appErr) { apiResponse.Error.Details = fmt.Sprintf("%v", appErr.Err)
switch specificErr := appErr.Err.(type) { case errors.ValidationError: validationError := make([]ValidationError, len(specificErr.Errors)) apiResponse.Message = "Validation Error" apiResponse.Error.ValidationErrors = validationError for i, ve := range specificErr.Errors { apiResponse.Error.ValidationErrors[i] = ValidationError{ Field: ve.Field, Message: ve.Message, } } c.JSON(http.StatusBadRequest, apiResponse) return case errors.ConflictError: apiResponse.Message = specificErr.Message apiResponse.Error.Details = specificErr.Error() apiResponse.Error.Exception.DataDuplicate = true c.JSON(http.StatusConflict, apiResponse) return case errors.InternalError: apiResponse.Message = specificErr.Message apiResponse.Error.Details = specificErr.Error() apiResponse.Error.Exception.InternalServerError = true c.JSON(http.StatusInternalServerError, apiResponse) return case errors.NotFoundError: apiResponse.Message = specificErr.Message apiResponse.Error.Details = specificErr.Error() apiResponse.Error.Exception.DataNotFound = true c.JSON(http.StatusNotFound, apiResponse) return case errors.UnauthorizedError: apiResponse.Message = specificErr.Message apiResponse.Error.Details = specificErr.Error() apiResponse.Error.Exception.Unauthorized = true c.JSON(http.StatusUnauthorized, apiResponse) return case errors.ForbiddenError: apiResponse.Message = specificErr.Message apiResponse.Error.Details = specificErr.Error() apiResponse.Error.Exception.Forbidden = true c.JSON(http.StatusForbidden, apiResponse) return case errors.BadRequestError: apiResponse.Message = specificErr.Message apiResponse.Error.Details = specificErr.Error() apiResponse.Error.Exception.BadRequest = true c.JSON(http.StatusBadRequest, apiResponse) return default: apiResponse.Error.Details = "An unexpected error occurred." apiResponse.Error.Exception.InternalServerError = true c.JSON(http.StatusInternalServerError, apiResponse) return } } else if validationErrors, ok := err.(validator.ValidationErrors); ok { apiResponse.Error.Details = "Validation failed for the request." apiResponse.Error.Exception.ValidationError = true apiResponse.Error.ValidationErrors = make([]ValidationError, len(validationErrors)) for i, fe := range validationErrors { apiResponse.Error.ValidationErrors[i] = ValidationError{ Field: fe.Field(), Message: fe.Translate(nil), // adjust if you use translator } } c.JSON(http.StatusBadRequest, apiResponse) return }
c.JSON(http.StatusInternalServerError, apiResponse) apiResponse.Error.Details = err.Error()}
func HandleSuccess(c *gin.Context, message string, statusCode int, data any, metaData any) { apiResponse := API{ Status: "success", Message: message, Data: data, MetaData: metaData, }
if metaData == nil { apiResponse.MetaData = struct{}{} }
c.JSON(statusCode, apiResponse)}
func HandleSuccessWithPaging(c *gin.Context, message string, content any, pagingInfo *PagingInfo) {
apiResponse := API{ Message: message, Status: "success", Data: List{ List: content, }, MetaData: pagingInfo, }
c.JSON(http.StatusOK, apiResponse)}12345package router
func (s *Server) HealthCheckRoute() { s.router.GET("/api/v1/health-check", s.healthCheckController.Check)}123456789101112131415161718192021222324252627package routerimport ("log""api.qobiltu.id/config""api.qobiltu.id/controller""github.com/gin-gonic/gin")func StartService() {router := gin.Default()router.Use(gin.Recovery())router.GET("/", controller.HomeController)AuthRoute(router)UserRoute(router)EmailRoute(router)OptionsRoute(router)AcademyRoute(router)QuizRoute(router)err := router.Run(config.TCP_ADDRESS)if err != nil {log.Fatalf("Failed to run server: %v", err)}}1234567891011121314151617181920package routerimport ("api.qobiltu.id/controller")func (s *Server) setupRoutes() {s.router.GET("/", controller.HomeController)AuthRoute(s.router)UserRoute(s.router)EmailRoute(s.router)OptionsRoute(s.router)AcademyRoute(s.router)QuizRoute(s.router)// another way to register routess.HealthCheckRoute()}
1234567891011121314151617181920212223242526272829303132package router
import ( "api.qobiltu.id/controller/health_check" "github.com/gin-gonic/gin")
type Server struct { router *gin.Engine healthCheckController *health_check_controller.HealthCheckController}
func NewServer( healthCheckController *health_check_controller.HealthCheckController,) (*Server, error) {
router := gin.Default() router.Use(gin.Recovery())
server := &Server{ healthCheckController: healthCheckController, router: router, }
server.setupRoutes()
return server, nil}
func (s *Server) Start(address string) error { return s.router.Run(address)}config/database_connection_config.go+3
controller/cv/cv_controller.go+210
controller/user/user_profile_controller.go+21-21
controller/user/user_update_profile_controller.go+25-25
models/database_orm_model.go+116-56
models/request_model.go+52-20
repositories/account_repository.go+87-87
repositories/cv_repository.go+107-18
router/cv_route.go+20-5
services/cv_service.go+264-95
services/external_authentication_service.go+81-81
services/user_profile_service.go+4-4
space/config/database_connection_config.go+4
space/controller/cv/cv_controller.goAdded+267
space/main.go+9-1
space/middleware/authentication_middleware.go+7
space/models/database_orm_model.go+118-33
space/models/request_model.go+126-51
space/repositories/cv_repository.goAdded+126
space/router/cv_route.goAdded+26
space/router/router.go+11-10
space/router/server.go+4
space/services/cv_service.goAdded+108
space/space/services/health_check_service.go+1-2
space/space/space/.gitignore+1
space/space/space/controller/health_check/health_check_controller.go+12-8
space/space/space/main.go+2-2
space/space/space/models/database_orm_model.go+207-207
space/space/space/models/exception_model.go+19-13
space/space/space/models/health_check_model.go+1-3
space/space/space/repositories/health_check_repository.go+12-13
space/space/space/response/api_response_v2.goAdded+79
space/space/space/response/gorm.goAdded+62
space/space/space/router/server.go+2-2
space/space/space/services/health_check_service.goAdded+32
space/space/space/services/user_profile_service.go+115-115
space/space/space/space/Dockerfile+6
space/space/space/space/space/.github/workflows/main.yml+1
space/space/space/space/space/apperror/apperror.goAdded+168
space/space/space/space/space/config/database_connection_config.go+80-79
space/space/space/space/space/config/tx.goAdded+34
space/space/space/space/space/controller/health_check/health_check_controller.goAdded+31
space/space/space/space/space/models/exception_model.go+17-15
space/space/space/space/space/models/health_check_model.goAdded+10
space/space/space/space/space/repositories/health_check_repository.goAdded+41
space/space/space/space/space/response/paging.goAdded+58
space/space/space/space/space/response/response.goAdded+152
space/space/space/space/space/router/health_check_route.goAdded+5
space/space/space/space/space/router/router.go+12-19
space/space/space/space/space/router/server.goAdded+32