Spaces:
Runtime error
Runtime error
Commit ·
36c99b0
1
Parent(s): a6ebab6
Deploy files from GitHub repository
Browse filesFiles changed (19)
- .gitignore+2-1
- config/supabase.goDeleted-19
- config/supabase_config.goAdded+25
- config/upload_config.goAdded+49
- controllers/academy_controller.go-2
- controllers/upload_controller.go+3-5
- models/entity/contant.go+3-1
- models/entity/entity.go+13-13
- provider/provider.go+6-5
- provider/services_provider.go+8-6
- provider/storage_provider.goAdded+10
- provider/supabase_storage.goDeleted-47
- repositories/academy_repository.go+6-99
- services/academy_service.go+22-25
- services/academy_service_helpers.go+27-23
- services/account_service.go+4-2
- services/supabase_storage_service.goAdded+27
- services/upload_service.go+73-132
- space/.gitignore+2-1
1/.env12/.envgo-boilerplate.exe
12345678910111213141516171819package config
type Supabase interface{ NewSupabaseConfig(url string, key string, bucket string)}
type SupabaseConfig struct { URL string ServiceKey string BucketName string}
func NewSupabaseConfig(url string, key string, bucket string) SupabaseConfig { return SupabaseConfig{ URL: url, ServiceKey: key, BucketName: bucket, }}12345678910111213141516171819202122232425package config
type SupabaseConfig interface { GetURL() string GetServiceKey() string GetBucketName() string}
type supabaseConfig struct { url string serviceKey string bucketName string}
func NewSupabaseConfig(url string, key string, bucket string) SupabaseConfig { return &supabaseConfig{ url: url, serviceKey: key, bucketName: bucket, }}
func (c *supabaseConfig) GetURL() string { return c.url }func (c *supabaseConfig) GetServiceKey() string { return c.serviceKey }func (c *supabaseConfig) GetBucketName() string { return c.bucketName }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849package config
import models "abdanhafidz.com/go-boilerplate/models/entity"
type UploadRule struct { MaxBytes int64 AllowedExts map[string]bool PathPrefix string MaxCount int}
type UploadConfig interface { Get(contextType string) (UploadRule, error)}
type uploadConfig struct{}
func NewUploadConfig() UploadConfig { return &uploadConfig{} }
func (c *uploadConfig) Get(contextType string) (UploadRule, error) { codeExts := map[string]bool{".cpp": true, ".c": true, ".py": true, ".java": true, ".go": true, ".js": true, ".txt": true} imgExts := map[string]bool{".jpg": true, ".jpeg": true, ".png": true, ".webp": true, ".gif": true} docExts := map[string]bool{".pdf": true, ".doc": true, ".docx": true}
allExts := make(map[string]bool) for k, v := range codeExts { allExts[k] = v } for k, v := range imgExts { allExts[k] = v } for k, v := range docExts { allExts[k] = v }
switch contextType { case "image": return UploadRule{ MaxBytes: 10 * models.MB, AllowedExts: imgExts, PathPrefix: "images", MaxCount: 5 }, nil case "material": return UploadRule{ MaxBytes: 10 * models.MB, AllowedExts: docExts, PathPrefix: "materials", MaxCount: 1 }, nil case "submission": return UploadRule{ MaxBytes: 1 * models.MB, AllowedExts: codeExts, PathPrefix: "submissions", MaxCount: 1 }, nil case "general": return UploadRule{ MaxBytes: 5 * models.MB, AllowedExts: allExts, PathPrefix: "temp", MaxCount: 5 }, nil default: return UploadRule{}, ErrInvalidUploadContext }}
var ErrInvalidUploadContext = errInvalidUploadContext{}
type errInvalidUploadContext struct{}
func (e errInvalidUploadContext) Error() string { return "invalid upload context" }123456769 unmodified lines77787980818283package controllersimport ("fmt""net/http""strconv"69 unmodified linesreturn}fmt.Println("Account ID in ListAcademies:", accountId)res, err := c.academyService.ListAcademies(ctx.Request.Context(), accountId)ResponseJSON(ctx, gin.H{}, res, err)}12345669 unmodified lines767778798081package controllersimport ("net/http""strconv"69 unmodified linesreturn}res, err := c.academyService.ListAcademies(ctx.Request.Context(), accountId)ResponseJSON(ctx, gin.H{}, res, err)}
17 unmodified lines181920212223242526272829218 unmodified lines24824925025117 unmodified lines)type UploadController struct {uploadService *services.UploadService}func NewUploadController(s *services.UploadService) *UploadController {return &UploadController{uploadService: s}}func (c *UploadController) Upload(ctx *gin.Context) {fmt.Println("👉 Content-Type:", ctx.GetHeader("Content-Type"))218 unmodified linesreturn "material"}return ""}17 unmodified lines18192021222324252627218 unmodified lines24624724824917 unmodified lines)type UploadController struct {uploadService services.UploadService}func NewUploadController(s services.UploadService) *UploadController { return &UploadController{ uploadService: s } }func (c *UploadController) Upload(ctx *gin.Context) {fmt.Println("👉 Content-Type:", ctx.GetHeader("Content-Type"))218 unmodified linesreturn "material"}return ""}
3 unmodified lines45673 unmodified linesStatusNotStarted = "NOT_STARTED"StatusInProgress = "IN_PROGRESS"StatusCompleted = "COMPLETED")3 unmodified lines4567893 unmodified linesStatusNotStarted = "NOT_STARTED"StatusInProgress = "IN_PROGRESS"StatusCompleted = "COMPLETED")const MB = 1024 * 1024
266 unmodified lines26726826927027127227326 unmodified lines3003013023033043053063073083 unmodified lines3123133143153163173183193203213 unmodified lines325326327328329330331332333334335266 unmodified linesImageUrl string `json:"image_url,omitempty"`MaterialsCount int64 `json:"materials_count,omitempty"`Materials []AcademyMaterial `gorm:"foreignKey:AcademyId;references:Id" json:"materials,omitempty"`AcademyProgresss AcademyProgress `gorm:"foreignKey:AcademyId;references:Id" json:"academy_progresses,omitempty"`}func (Academy) TableName() string { return "academy" }26 unmodified lines// Progresstype AcademyProgress struct {Id uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`AccountId uuid.UUID `gorm:"type:uuid;index" json:"account_id,omitempty"`AcademyId uuid.UUID `gorm:"type:uuid;index" json:"academy_id,omitempty"`Status string `gorm:"type:varchar(50);default:'not attempted'" json:"status,omitempty"`Progress float64 `gorm:"default:0" json:"progress"`TotalCompletedMaterials uint `gorm:"default:0" json:"total_completed_materials"`3 unmodified linesfunc (AcademyProgress) TableName() string { return "academy_progress" }type AcademyMaterialProgress struct {Id uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`AccountId uuid.UUID `gorm:"type:uuid;index" json:"account_id,omitempty"`AcademyId uuid.UUID `gorm:"type:uuid;index" json:"academy_id,omitempty"`MaterialId uuid.UUID `gorm:"type:uuid;index" json:"material_id,omitempty"`Progress float64 `gorm:"default:0" json:"progress,omitempty"`TotalCompletedContents uint `gorm:"default:0" json:"total_completed_contents,omitempty"`Status string `gorm:"type:varchar(50);default:'not attempted'" json:"status,omitempty"`3 unmodified linesfunc (AcademyMaterialProgress) TableName() string { return "academy_material_progress" }type AcademyContentProgress struct {Id uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`AccountId uuid.UUID `gorm:"type:uuid;index" json:"account_id,omitempty"`AcademyId uuid.UUID `gorm:"type:uuid;index" json:"academy_id,omitempty"`MaterialId uuid.UUID `gorm:"type:uuid;index" json:"material_id,omitempty"`ContentId uuid.UUID `gorm:"type:uuid;index" json:"content_id,omitempty"`Status string `gorm:"type:varchar(50);default:'not attempted'" json:"status,omitempty"`CompletedAt *time.Time `json:"completed_at"`}266 unmodified lines26726826927027127227326 unmodified lines3003013023033043053063073083 unmodified lines3123133143153163173183193203213 unmodified lines325326327328329330331332333334335266 unmodified linesImageUrl string `json:"image_url,omitempty"`MaterialsCount int64 `json:"materials_count,omitempty"`Materials []AcademyMaterial `gorm:"foreignKey:AcademyId;references:Id" json:"materials,omitempty"`AcademyProgress AcademyProgress `gorm:"foreignKey:AcademyId;references:Id" json:"academy_progresses,omitempty"`}func (Academy) TableName() string { return "academy" }26 unmodified lines// Progresstype AcademyProgress struct {Id uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`AccountId uuid.UUID `gorm:"type:uuid;uniqueIndex:idx_account_academy" json:"account_id,omitempty"`AcademyId uuid.UUID `gorm:"type:uuid;uniqueIndex:idx_account_academy" json:"academy_id,omitempty"`Status string `gorm:"type:varchar(50);default:'not attempted'" json:"status,omitempty"`Progress float64 `gorm:"default:0" json:"progress"`TotalCompletedMaterials uint `gorm:"default:0" json:"total_completed_materials"`3 unmodified linesfunc (AcademyProgress) TableName() string { return "academy_progress" }type AcademyMaterialProgress struct {Id uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`AccountId uuid.UUID `gorm:"type:uuid;uniqueIndex:idx_account_material" json:"account_id,omitempty"`AcademyId uuid.UUID `gorm:"type:uuid;index" json:"academy_id,omitempty"`MaterialId uuid.UUID `gorm:"type:uuid;uniqueIndex:idx_account_material" json:"material_id,omitempty"`Progress float64 `gorm:"default:0" json:"progress,omitempty"`TotalCompletedContents uint `gorm:"default:0" json:"total_completed_contents,omitempty"`Status string `gorm:"type:varchar(50);default:'not attempted'" json:"status,omitempty"`3 unmodified linesfunc (AcademyMaterialProgress) TableName() string { return "academy_material_progress" }type AcademyContentProgress struct {Id uuid.UUID `gorm:"type:uuid;primaryKey" json:"id"`AccountId uuid.UUID `gorm:"type:uuid;uniqueIndex:idx_account_content" json:"account_id,omitempty"`AcademyId uuid.UUID `gorm:"type:uuid;index" json:"academy_id,omitempty"`MaterialId uuid.UUID `gorm:"type:uuid;index" json:"material_id,omitempty"`ContentId uuid.UUID `gorm:"type:uuid;uniqueIndex:idx_account_content" json:"content_id,omitempty"`Status string `gorm:"type:varchar(50);default:'not attempted'" json:"status,omitempty"`CompletedAt *time.Time `json:"completed_at"`}
4 unmodified lines567891019 unmodified lines3031323334353637383940414243444583 unmodified lines1291301311324 unmodified lines"strings"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/gin-gonic/gin")type AppProvider interface {19 unmodified linesconfigProvider := NewConfigProvider()repositoriesProvider := NewRepositoriesProvider(configProvider)supabaseCfg := configProvider.ProvideSupabaseConfig()if supabaseCfg.URL == "" || supabaseCfg.ServiceKey == "" || supabaseCfg.BucketName == "" {log.Fatalf("Supabase configuration is invalid: URL, ServiceKey, or BucketName is empty")}if !strings.HasPrefix(supabaseCfg.URL, "https://") || !strings.Contains(supabaseCfg.URL, ".supabase.co") {log.Fatalf("Supabase URL is invalid")}if strings.Count(supabaseCfg.ServiceKey, ".") != 2 {log.Fatalf("Supabase service key is not a valid compact JWS")}storageDriver := NewSupabaseStorage(supabaseCfg.URL, supabaseCfg.ServiceKey, supabaseCfg.BucketName)servicesProvider := NewServicesProvider(repositoriesProvider, configProvider, storageDriver)controllerProvider := NewControllerProvider(servicesProvider)middlewareProvider := NewMiddlewareProvider(servicesProvider)83 unmodified linesfunc (a *appProvider) ProvideMiddlewares() MiddlewareProvider {return a.middlewareProvider}4 unmodified lines56789101119 unmodified lines3132333435363738394041424344454683 unmodified lines1301311321334 unmodified lines"strings"entity "abdanhafidz.com/go-boilerplate/models/entity""github.com/gin-gonic/gin""abdanhafidz.com/go-boilerplate/services")type AppProvider interface {19 unmodified linesconfigProvider := NewConfigProvider()repositoriesProvider := NewRepositoriesProvider(configProvider)supabaseCfg := configProvider.ProvideSupabaseConfig()if supabaseCfg.GetURL() == "" || supabaseCfg.GetServiceKey() == "" || supabaseCfg.GetBucketName() == "" {log.Fatalf("Supabase configuration is invalid: URL, ServiceKey, or BucketName is empty")}if !strings.HasPrefix(supabaseCfg.GetURL(), "https://") || !strings.Contains(supabaseCfg.GetURL(), ".supabase.co") {log.Fatalf("Supabase URL is invalid")}if strings.Count(supabaseCfg.GetServiceKey(), ".") != 2 {log.Fatalf("Supabase service key is not a valid compact JWS")}storageDriver := services.NewSupabaseStorageService(supabaseCfg.GetURL(), supabaseCfg.GetServiceKey(), supabaseCfg.GetBucketName())servicesProvider := NewServicesProvider(repositoriesProvider, configProvider, storageDriver)controllerProvider := NewControllerProvider(servicesProvider)middlewareProvider := NewMiddlewareProvider(servicesProvider)83 unmodified linesfunc (a *appProvider) ProvideMiddlewares() MiddlewareProvider {return a.middlewareProvider}
12345678 unmodified lines161718192021229 unmodified lines323334353637383940414243444520 unmodified lines66676869707147 unmodified lines119120121122123124125126package providerimport ("abdanhafidz.com/go-boilerplate/services")type ServicesProvider interface {8 unmodified linesProvideForgotPasswordService() services.ForgotPasswordServiceProvideEmailVerificationService() services.EmailVerificationServiceProvideExternalAuthService() services.ExternalAuthServiceProvideUploadService() *services.UploadServiceProvideAcademyExamService() services.AcademyExamService}9 unmodified linesforgotPasswordService services.ForgotPasswordServiceemailVerificationService services.EmailVerificationServiceexternalAuthService services.ExternalAuthServiceuploadService *services.UploadServiceacademyExamService services.AcademyExamService}func NewServicesProvider(repoProvider RepositoriesProvider,configProvider ConfigProvider,storageProvider services.StorageProvider,) ServicesProvider {eventService := services.NewEventService(repoProvider.ProvideEventsRepository(), repoProvider.ProvideEventAssignRepository())20 unmodified linesuploadService := services.NewUploadService(storageProvider,repoProvider.ProvideFileRepository(),)return &servicesProvider{47 unmodified linesreturn s.externalAuthService}func (s *servicesProvider) ProvideUploadService() *services.UploadService {return s.uploadService}func (s *servicesProvider) ProvideAcademyExamService() services.AcademyExamService { return s.academyExamService }123456788 unmodified lines171819202122239 unmodified lines333435363738394041424344454620 unmodified lines6768697071727347 unmodified lines121122123124125126127128package providerimport ("abdanhafidz.com/go-boilerplate/config""abdanhafidz.com/go-boilerplate/services")type ServicesProvider interface {8 unmodified linesProvideForgotPasswordService() services.ForgotPasswordServiceProvideEmailVerificationService() services.EmailVerificationServiceProvideExternalAuthService() services.ExternalAuthServiceProvideUploadService() services.UploadServiceProvideAcademyExamService() services.AcademyExamService}9 unmodified linesforgotPasswordService services.ForgotPasswordServiceemailVerificationService services.EmailVerificationServiceexternalAuthService services.ExternalAuthServiceuploadService services.UploadServiceacademyExamService services.AcademyExamService}func NewServicesProvider(repoProvider RepositoriesProvider,configProvider ConfigProvider,storageProvider StorageProvider,) ServicesProvider {eventService := services.NewEventService(repoProvider.ProvideEventsRepository(), repoProvider.ProvideEventAssignRepository())20 unmodified linesuploadService := services.NewUploadService(storageProvider,repoProvider.ProvideFileRepository(),config.NewUploadConfig(),)return &servicesProvider{47 unmodified linesreturn s.externalAuthService}func (s *servicesProvider) ProvideUploadService() services.UploadService {return s.uploadService}func (s *servicesProvider) ProvideAcademyExamService() services.AcademyExamService { return s.academyExamService }
12345678910package provider
import ( "context" "io")
type StorageProvider interface { UploadFile(ctx context.Context, file io.Reader, destinationPath string, contentType string) (string, error)}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647package provider
import ( "context" "fmt" "io" "mime/multipart" storage_go "github.com/supabase-community/storage-go")
type StorageProvider interface { UploadFile(ctx context.Context, file multipart.File, header *multipart.FileHeader) (string, error) GetFileURL(path string) (string, error) DeleteFile(path string) error}
type SupabaseStorage struct { client *storage_go.Client bucketName string url string}
func NewSupabaseStorage(url string, key string, bucketName string) *SupabaseStorage { client := storage_go.NewClient(url+"/storage/v1", key, nil) return &SupabaseStorage{ client: client, bucketName: bucketName, url: url, }}
func (s *SupabaseStorage) UploadFile(ctx context.Context, file io.Reader, destinationPath string, contentType string) (string, error) { _, err := s.client.UploadFile(s.bucketName, destinationPath, file, storage_go.FileOptions{ ContentType: &contentType, Upsert: new(bool), })
if err != nil { return "", err } publicURL := s.client.GetPublicUrl(s.bucketName, destinationPath).SignedURL if publicURL == "" { publicURL = fmt.Sprintf("%s/storage/v1/object/public/%s/%s", s.url, s.bucketName, destinationPath) }
return publicURL, nil}57 unmodified lines58596061626364656640 unmodified lines10710810911011111211338 unmodified lines152153154155156157158159160128 unmodified lines28929029129229329429515 unmodified lines31131231331431531631716 unmodified lines33433533633733833934055 unmodified lines39639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049157 unmodified linesDecrementContentOrdersGreaterThan(ctx context.Context, materialId uuid.UUID, order uint) errorGetAccumulatedMaterialProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (float64, error)BatchRecalculateMaterialProgress(ctx context.Context, materialId uuid.UUID) errorBatchRecalculateAcademyProgress(ctx context.Context, academyId uuid.UUID) errorGetMaterialProgressBatch(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, materialIds []uuid.UUID) (map[uuid.UUID]entity.AcademyMaterialProgress, error)GetContentProgressBatch(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, contentIds []uuid.UUID) (map[uuid.UUID]entity.AcademyContentProgress, error)}40 unmodified linesif err != nil {return a, err}a.AcademyProgresss = apreturn a, nil}38 unmodified linesfor i := range list {if p, exists := progressMap[list[i].Id]; exists {list[i].AcademyProgresss = p} else {list[i].AcademyProgresss = entity.AcademyProgress{AccountId: accountId,AcademyId: list[i].Id,Status: entity.StatusNotStarted,128 unmodified linesfunc (r *academyRepository) UpsertAcademyProgress(ctx context.Context, p entity.AcademyProgress) (entity.AcademyProgress, error) {return p, r.db.WithContext(ctx).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "id"}},UpdateAll: true,}).Save(&p).Error}15 unmodified linesfunc (r *academyRepository) UpsertMaterialProgress(ctx context.Context, p entity.AcademyMaterialProgress) (entity.AcademyMaterialProgress, error) {return p, r.db.WithContext(ctx).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "id"}},UpdateAll: true,}).Save(&p).Error}16 unmodified linesfunc (r *academyRepository) UpsertContentProgress(ctx context.Context, p entity.AcademyContentProgress) (entity.AcademyContentProgress, error) {return p, r.db.WithContext(ctx).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "id"}},UpdateAll: true,}).Save(&p).Error}55 unmodified linesreturn total, err}func (r *academyRepository) BatchRecalculateMaterialProgress(ctx context.Context, materialId uuid.UUID) error {totalContents, err := r.CountContentsByMaterialID(ctx, materialId)if err != nil {return err}if totalContents == 0 {return r.db.WithContext(ctx).Model(&entity.AcademyMaterialProgress{}).Where("material_id = ?", materialId).Updates(map[string]interface{}{"progress": 100,"status": entity.StatusCompleted,"total_completed_contents": 0,}).Error}return r.db.WithContext(ctx).Exec(`UPDATE academy_material_progresses ampSETtotal_completed_contents = (SELECT COUNT(id) FROM academy_content_progresses acpWHERE acp.material_id = amp.material_id AND acp.account_id = amp.account_id AND acp.status = 'COMPLETED'),progress = (SELECT COUNT(id) FROM academy_content_progresses acpWHERE acp.material_id = amp.material_id AND acp.account_id = amp.account_id AND acp.status = 'COMPLETED')::float / ? * 100,status = CASEWHEN (SELECT COUNT(id) FROM academy_content_progresses acpWHERE acp.material_id = amp.material_id AND acp.account_id = amp.account_id AND acp.status = 'COMPLETED') >= ? THEN 'COMPLETED'ELSE 'IN_PROGRESS'END,completed_at = CASEWHEN (SELECT COUNT(id) FROM academy_content_progresses acpWHERE acp.material_id = amp.material_id AND acp.account_id = amp.account_id AND acp.status = 'COMPLETED') >= ? THEN NOW()ELSE NULLENDWHERE amp.material_id = ?`, totalContents, totalContents, totalContents, materialId).Error}func (r *academyRepository) BatchRecalculateAcademyProgress(ctx context.Context, academyId uuid.UUID) error {totalMaterials, err := r.CountMaterialsByAcademyID(ctx, academyId)if err != nil {return err}if totalMaterials == 0 {return r.db.WithContext(ctx).Model(&entity.AcademyProgress{}).Where("academy_id = ?", academyId).Updates(map[string]interface{}{"progress": 100,"status": entity.StatusCompleted,"total_completed_materials": 0,}).Error}return r.db.WithContext(ctx).Exec(`UPDATE academy_progress apSETprogress = (SELECT COALESCE(SUM(amp.progress), 0) FROM academy_material_progresses ampWHERE amp.academy_id = ap.academy_id AND amp.account_id = ap.account_id)::float / ?,total_completed_materials = (SELECT COUNT(id) FROM academy_material_progresses ampWHERE amp.academy_id = ap.academy_id AND amp.account_id = ap.account_id AND amp.status = 'COMPLETED'),status = CASEWHEN (SELECT COUNT(id) FROM academy_material_progresses ampWHERE amp.academy_id = ap.academy_id AND amp.account_id = ap.account_id AND amp.status = 'COMPLETED') >= ? THEN 'COMPLETED'ELSE 'IN_PROGRESS'END,completed_at = CASEWHEN (SELECT COUNT(id) FROM academy_material_progresses ampWHERE amp.academy_id = ap.academy_id AND amp.account_id = ap.account_id AND amp.status = 'COMPLETED') >= ? THEN NOW()ELSE NULLENDWHERE ap.academy_id = ?`, totalMaterials, totalMaterials, totalMaterials, academyId).Error}func (r *academyRepository) GetMaterialProgressBatch(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, materialIds []uuid.UUID) (map[uuid.UUID]entity.AcademyMaterialProgress, error) {var progresses []entity.AcademyMaterialProgressresult := r.db.WithContext(ctx).Where("account_id = ? AND academy_id = ? AND material_id IN ?", accountId, academyId, materialIds).Find(&progresses)57 unmodified lines58596061626340 unmodified lines10410510610710810911038 unmodified lines149150151152153154155156157128 unmodified lines28628728828929029129215 unmodified lines30830931031131231331416 unmodified lines33133233333433533633755 unmodified lines39339439539639739857 unmodified linesDecrementContentOrdersGreaterThan(ctx context.Context, materialId uuid.UUID, order uint) errorGetAccumulatedMaterialProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (float64, error)GetMaterialProgressBatch(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, materialIds []uuid.UUID) (map[uuid.UUID]entity.AcademyMaterialProgress, error)GetContentProgressBatch(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, contentIds []uuid.UUID) (map[uuid.UUID]entity.AcademyContentProgress, error)}40 unmodified linesif err != nil {return a, err}a.AcademyProgress = apreturn a, nil}38 unmodified linesfor i := range list {if p, exists := progressMap[list[i].Id]; exists {list[i].AcademyProgress = p} else {list[i].AcademyProgress = entity.AcademyProgress{AccountId: accountId,AcademyId: list[i].Id,Status: entity.StatusNotStarted,128 unmodified linesfunc (r *academyRepository) UpsertAcademyProgress(ctx context.Context, p entity.AcademyProgress) (entity.AcademyProgress, error) {return p, r.db.WithContext(ctx).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "account_id"}, {Name: "academy_id"}},UpdateAll: true,}).Save(&p).Error}15 unmodified linesfunc (r *academyRepository) UpsertMaterialProgress(ctx context.Context, p entity.AcademyMaterialProgress) (entity.AcademyMaterialProgress, error) {return p, r.db.WithContext(ctx).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "account_id"}, {Name: "material_id"}},UpdateAll: true,}).Save(&p).Error}16 unmodified linesfunc (r *academyRepository) UpsertContentProgress(ctx context.Context, p entity.AcademyContentProgress) (entity.AcademyContentProgress, error) {return p, r.db.WithContext(ctx).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "account_id"}, {Name: "content_id"}},UpdateAll: true,}).Save(&p).Error}55 unmodified linesreturn total, err}func (r *academyRepository) GetMaterialProgressBatch(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID, materialIds []uuid.UUID) (map[uuid.UUID]entity.AcademyMaterialProgress, error) {var progresses []entity.AcademyMaterialProgressresult := r.db.WithContext(ctx).Where("account_id = ? AND academy_id = ? AND material_id IN ?", accountId, academyId, materialIds).Find(&progresses)
171 unmodified lines17217317417517617717817918042 unmodified lines22322422522622722822923023136 unmodified lines26826927027127227327427527627727827935 unmodified lines31531631731831932032132232332432532632732832933033133233333448 unmodified lines38338438538638738838921 unmodified lines41141241341441541641749 unmodified lines46746846947047147247315 unmodified lines489490491492493494495171 unmodified linesreturn err}if err := txRepo.BatchRecalculateAcademyProgress(ctx, req.AcademyId); err != nil {return err}return nil})42 unmodified linesreturn err}if err := txRepo.BatchRecalculateAcademyProgress(ctx, m.AcademyId); err != nil {return err}return nil})36 unmodified linesreturn err}if err := txRepo.BatchRecalculateMaterialProgress(ctx, req.MaterialId); err != nil {return err}if err := txRepo.BatchRecalculateAcademyProgress(ctx, m.AcademyId); err != nil {return err}return nil})35 unmodified linesif _, err := txRepo.UpdateMaterial(ctx, material); err != nil {return err}if err := txRepo.BatchRecalculateMaterialProgress(ctx, c.MaterialId); err != nil {return err}// Update Academy jugaif err := txRepo.BatchRecalculateAcademyProgress(ctx, material.AcademyId); err != nil {return err}return nil})}// ================= UPDATE PROGRESS =================func (s *academyService) UpdateContentProgress(ctx context.Context, accountId uuid.UUID, academySlug string, materialSlug string, order uint) (entity.AcademyContentProgress, entity.AcademyMaterialProgress, entity.AcademyProgress, error) {academy, err := s.academyRepo.GetAcademyBySlug(ctx, academySlug)48 unmodified linesif totalContentsCompleted >= m.ContentsCount {matStatus = entity.StatusCompletedmatCompletedAt = utils.Ptr(time.Now())progressPct = 100}} else {matStatus = entity.StatusCompleted21 unmodified lines}accumulatedProgress, _ := txRepo.GetAccumulatedMaterialProgress(ctx, accountId, academy.Id)a, _ := txRepo.GetAcademyByID(ctx, academy.Id)acadStatus := entity.StatusNotStartedvar acadCompletedAt *time.Time49 unmodified linesif err != nil {return nil, http_error.ACADEMY_NOT_FOUND}academyProgress, _ := s.academyRepo.GetAcademyProgress(ctx, accountId, academy.Id)materials, err := s.academyRepo.GetMaterialsWithContents(ctx, academy.Id)if err != nil {materials = []entity.AcademyMaterial{}15 unmodified linesif err != nil {return nil, http_error.MATERIAL_NOT_FOUND}materialProgress, _ := s.academyRepo.GetMaterialProgress(ctx, accountId, academy.Id, material.Id)_, contents, err := s.academyRepo.GetMaterialWithContents(ctx, material.Id)if err != nil {contents = []entity.AcademyContent{}171 unmodified lines17217317417517617717842 unmodified lines22122222322422522622736 unmodified lines26426526626726826927035 unmodified lines30630730830931031131231331431531631731848 unmodified lines36736836937037137237321 unmodified lines39539639739839940040149 unmodified lines45145245345445545645745845946046115 unmodified lines477478479480481482483484485486487488489490491492171 unmodified linesreturn err}// progress recalculation handled on getreturn nil})42 unmodified linesreturn err}// progress recalculation handled on getreturn nil})36 unmodified linesreturn err}// progress recalculation handled on getreturn nil})35 unmodified linesif _, err := txRepo.UpdateMaterial(ctx, material); err != nil {return err}// progress recalculation handled on getreturn nil})}// ================= UPDATE PROGRESS =================func (s *academyService) UpdateContentProgress(ctx context.Context, accountId uuid.UUID, academySlug string, materialSlug string, order uint) (entity.AcademyContentProgress, entity.AcademyMaterialProgress, entity.AcademyProgress, error) {academy, err := s.academyRepo.GetAcademyBySlug(ctx, academySlug)48 unmodified linesif totalContentsCompleted >= m.ContentsCount {matStatus = entity.StatusCompletedmatCompletedAt = utils.Ptr(time.Now())progressPct = 100}} else {matStatus = entity.StatusCompleted21 unmodified lines}accumulatedProgress, _ := txRepo.GetAccumulatedMaterialProgress(ctx, accountId, academy.Id)a, _ := txRepo.GetAcademyByID(ctx, academy.Id)acadStatus := entity.StatusNotStartedvar acadCompletedAt *time.Time49 unmodified linesif err != nil {return nil, http_error.ACADEMY_NOT_FOUND}accumulatedProgress, _ := s.academyRepo.GetAccumulatedMaterialProgress(ctx, accountId, academy.Id)academyProgress := s.calculateAcademyProgress(ctx, s.academyRepo, accountId, academy.Id, accumulatedProgress, academy.MaterialsCount)if _, err := s.academyRepo.UpsertAcademyProgress(ctx, academyProgress); err != nil {return nil, err}materials, err := s.academyRepo.GetMaterialsWithContents(ctx, academy.Id)if err != nil {materials = []entity.AcademyMaterial{}15 unmodified linesif err != nil {return nil, http_error.MATERIAL_NOT_FOUND}totalCompleted, _ := s.academyRepo.CountCompletedContentsByMaterialAndAccount(ctx, accountId, material.Id)materialProgress := s.calculateMaterialProgress(ctx, s.academyRepo, accountId, academy.Id, material.Id, totalCompleted, material.ContentsCount)if _, err := s.academyRepo.UpsertMaterialProgress(ctx, materialProgress); err != nil {return nil, err}accumulatedProgress, _ := s.academyRepo.GetAccumulatedMaterialProgress(ctx, accountId, academy.Id)academyProgress := s.calculateAcademyProgress(ctx, s.academyRepo, accountId, academy.Id, accumulatedProgress, academy.MaterialsCount)if _, err := s.academyRepo.UpsertAcademyProgress(ctx, academyProgress); err != nil {return nil, err}_, contents, err := s.academyRepo.GetMaterialWithContents(ctx, material.Id)if err != nil {contents = []entity.AcademyContent{}
38 unmodified lines39404142434445464748495 unmodified lines555657585960616262 unmodified lines12512612712812913013113213313413513613713813914014114214314414514614714814915038 unmodified lines}func (s *academyService) upsertContentProgressSimplified(ctx context.Context,txRepo repositories.AcademyRepository,accountId, academyId, materialId, contentId uuid.UUID,) entity.AcademyContentProgress {existing, _ := txRepo.GetContentProgress(ctx, accountId, academyId, materialId, contentId)acp := entity.AcademyContentProgress{Id: s.getOrCreateID(existing.Id),5 unmodified linesCompletedAt: utils.Ptr(time.Now()),}txRepo.UpsertContentProgress(ctx, acp)return acp}func (s *academyService) calculateMaterialProgress(62 unmodified lines}func (s *academyService) updateAcademyMaterialCount(ctx context.Context, txRepo repositories.AcademyRepository, academyId uuid.UUID) error {count, err := txRepo.CountMaterialsByAcademyID(ctx, academyId)if err != nil {return err}academy, _ := txRepo.GetAcademyByID(ctx, academyId)academy.MaterialsCount = count_, err = txRepo.UpdateAcademy(ctx, academy)return err}func (s *academyService) updateMaterialContentCount(ctx context.Context, txRepo repositories.AcademyRepository, materialId uuid.UUID) error {count, err := txRepo.CountContentsByMaterialID(ctx, materialId)if err != nil {return err}material, _ := txRepo.GetMaterialByID(ctx, materialId)material.ContentsCount = count_, err = txRepo.UpdateMaterial(ctx, material)return err}func formatTime(t *time.Time) *string {38 unmodified lines3940414243444546474849505152535 unmodified lines5960616263646566676862 unmodified lines13113213313413513613713813914014114214314414514614714814915015115215315438 unmodified lines}func (s *academyService) upsertContentProgressSimplified(ctx context.Context,txRepo repositories.AcademyRepository,accountId, academyId, materialId, contentId uuid.UUID,) (entity.AcademyContentProgress, error) {existing, err := txRepo.GetContentProgress(ctx, accountId, academyId, materialId, contentId)if err != nil {// propagate non-not-found errorsreturn entity.AcademyContentProgress{}, err}acp := entity.AcademyContentProgress{Id: s.getOrCreateID(existing.Id),5 unmodified linesCompletedAt: utils.Ptr(time.Now()),}if _, err := txRepo.UpsertContentProgress(ctx, acp); err != nil {return entity.AcademyContentProgress{}, err}return acp, nil}func (s *academyService) calculateMaterialProgress(62 unmodified lines}func (s *academyService) updateAcademyMaterialCount(ctx context.Context, txRepo repositories.AcademyRepository, academyId uuid.UUID) error {count, err := txRepo.CountMaterialsByAcademyID(ctx, academyId)if err != nil { return err }academy, err := txRepo.GetAcademyByID(ctx, academyId)if err != nil { return err }academy.MaterialsCount = count_, err = txRepo.UpdateAcademy(ctx, academy)return err}func (s *academyService) updateMaterialContentCount(ctx context.Context, txRepo repositories.AcademyRepository, materialId uuid.UUID) error {count, err := txRepo.CountContentsByMaterialID(ctx, materialId)if err != nil { return err }material, err := txRepo.GetMaterialByID(ctx, materialId)if err != nil { return err }material.ContentsCount = count_, err = txRepo.UpdateMaterial(ctx, material)return err}func formatTime(t *time.Time) *string {
2 unmodified lines34567828 unmodified lines3738394041424324 unmodified lines686970717273742 unmodified linesimport ("context""errors""regexp""strings"28 unmodified linesjwtService: jwtService,accountRepo: accountRepo,accountDetailRepo: accountDetailRepo,}}24 unmodified linesreturn entity.Account{}, err}_, _ = s.CreateEmptyDetail(ctx, created.Id)return created, nil2 unmodified lines345678928 unmodified lines38394041424324 unmodified lines6869707172737475762 unmodified linesimport ("context""errors""fmt""regexp""strings"28 unmodified linesjwtService: jwtService,accountRepo: accountRepo,accountDetailRepo: accountDetailRepo,}}24 unmodified linesreturn entity.Account{}, err}if _, err := s.CreateEmptyDetail(ctx, created.Id); err != nil {return entity.Account{}, fmt.Errorf("create empty detail: %w", err)}return created, nil
123456789101112131415161718192021222324252627package services
import ( "context" "fmt" "io" storage_go "github.com/supabase-community/storage-go")
type SupabaseStorageService struct { client *storage_go.Client bucketName string url string}
func NewSupabaseStorageService(url string, key string, bucketName string) *SupabaseStorageService { client := storage_go.NewClient(url+"/storage/v1", key, nil) return &SupabaseStorageService{ client: client, bucketName: bucketName, url: url }}
func (s *SupabaseStorageService) UploadFile(ctx context.Context, file io.Reader, destinationPath string, contentType string) (string, error) { _, err := s.client.UploadFile(s.bucketName, destinationPath, file, storage_go.FileOptions{ ContentType: &contentType, Upsert: new(bool) }) if err != nil { return "", err } publicURL := s.client.GetPublicUrl(s.bucketName, destinationPath).SignedURL if publicURL == "" { publicURL = fmt.Sprintf("%s/storage/v1/object/public/%s/%s", s.url, s.bucketName, destinationPath) } return publicURL, nil}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535426 unmodified lines818283848586879 unmodified lines97989910010110210333 unmodified lines13713813914014114214311 unmodified lines1551561571581591601613 unmodified lines1651661671681691701715 unmodified lines177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274package servicesimport ("context""errors""fmt""io""mime/multipart""path/filepath""regexp""strings""time""github.com/google/uuid"entity "abdanhafidz.com/go-boilerplate/models/entity"http_error "abdanhafidz.com/go-boilerplate/models/error")const MB = 1024 * 1024type uploadConfig struct {MaxBytes int64AllowedExts map[string]boolPathPrefix stringMaxCount int}type StorageProvider interface {UploadFile(ctx context.Context, file io.Reader, destinationPath string, contentType string) (string, error)}type FileRepository interface {Create(ctx context.Context, file *entity.File) errorFindByID(ctx context.Context, id uuid.UUID) (*entity.File, error)}type UploadService struct {storageProvider StorageProviderfileRepo FileRepository}func NewUploadService(storage StorageProvider, repo FileRepository) *UploadService {return &UploadService{storageProvider: storage,fileRepo: repo,}}func (s *UploadService) UploadFiles(ctx context.Context, files []*multipart.FileHeader, uploadContext string, accountID uuid.UUID) ([]entity.File, error) {config, err := s.getUploadConfig(uploadContext)if err != nil {return nil, err}26 unmodified linesreturn uploadedFiles, nil}func (s *UploadService) GetFileByID(ctx context.Context, fileID uuid.UUID, accountID uuid.UUID) (*entity.File, error) {file, err := s.fileRepo.FindByID(ctx, fileID)if err != nil {if errors.Is(err, http_error.NOT_FOUND_ERROR) {9 unmodified linesreturn file, nil}func (s *UploadService) processSingleFile(ctx context.Context, fileHeader *multipart.FileHeader, config uploadConfig, uploadContext string, accountID uuid.UUID) (*entity.File, error) {if err := s.validateFile(fileHeader, config); err != nil {return nil, err}33 unmodified linesreturn fileEntity, nil}func (s *UploadService) validateFile(file *multipart.FileHeader, config uploadConfig) error {if file.Size == 0 || file.Size > config.MaxBytes {return http_error.FILE_TOO_LARGE}11 unmodified linesreturn nil}func (s *UploadService) generateStoredFilename(originalName string, ext string) string {originalNameWithoutExt := strings.TrimSuffix(originalName, ext)reg := regexp.MustCompile("[^a-zA-Z0-9._-]+")sanitizedRawName := reg.ReplaceAllString(originalNameWithoutExt, "_")3 unmodified linesreturn fmt.Sprintf("%s-%d-%s%s", uniqueID.String(), timestamp, sanitizedRawName, ext)}func (s *UploadService) generateStoragePath(prefix, contextType, filename string, accountID uuid.UUID) string {switch contextType {case "submission":now := time.Now()5 unmodified lines}}func (s *UploadService) getUploadConfig(contextType string) (uploadConfig, error) {codeExts := map[string]bool{".cpp": true, ".c": true, ".py": true, ".java": true, ".go": true, ".js": true, ".txt": true}imgExts := map[string]bool{".jpg": true, ".jpeg": true, ".png": true, ".webp": true, ".gif": true}docExts := map[string]bool{".pdf": true, ".doc": true, ".docx": true}allExts := make(map[string]bool)for k, v := range codeExts {allExts[k] = v}for k, v := range imgExts {allExts[k] = v}for k, v := range docExts {allExts[k] = v}switch contextType {case "image":return uploadConfig{MaxBytes: 10 * MB,AllowedExts: imgExts,PathPrefix: "images",MaxCount: 5,}, nilcase "material":return uploadConfig{MaxBytes: 10 * MB,AllowedExts: docExts,PathPrefix: "materials",MaxCount: 1,}, nilcase "submission":return uploadConfig{MaxBytes: 1 * MB,AllowedExts: codeExts,PathPrefix: "submissions",MaxCount: 1,}, nilcase "general":return uploadConfig{MaxBytes: 5 * MB,AllowedExts: allExts,PathPrefix: "temp",MaxCount: 5,}, nildefault:return uploadConfig{}, http_error.INVALID_DATA_PAYLOAD}}func (s *UploadService) UploadRawFile(ctx context.Context, reader io.Reader, originalName string, contentType string, uploadContext string, accountID uuid.UUID) (*entity.File, error) {config, err := s.getUploadConfig(uploadContext)if err != nil {return nil, http_error.BAD_REQUEST_ERROR}ext := strings.ToLower(strings.TrimSpace(filepath.Ext(originalName)))if ext == "" {if strings.Contains(contentType, "pdf") {ext = ".pdf"} else if strings.Contains(contentType, "png") {ext = ".png"} else if strings.Contains(contentType, "jpeg") || strings.Contains(contentType, "jpg") {ext = ".jpg"} else {ext = ".bin"}}storedFilename := s.generateStoredFilename(originalName, ext)storagePath := s.generateStoragePath(config.PathPrefix, uploadContext, storedFilename, accountID)publicURL, err := s.storageProvider.UploadFile(ctx, reader, storagePath, contentType)if err != nil {return nil, err}fileEntity := &entity.File{Id: uuid.New(),OriginalName: originalName,StoredName: storedFilename,MimeType: contentType,Size: 0,Path: publicURL,Context: uploadContext,AccountId: accountID,CreatedAt: time.Now(),}if err := s.fileRepo.Create(ctx, fileEntity); err != nil {return nil, err}return fileEntity, nil}12345678910111213141516171819202122232425262728293031323334353637383940414243444526 unmodified lines727374757677789 unmodified lines8889909192939433 unmodified lines12812913013113213313411 unmodified lines1461471481491501511523 unmodified lines1561571581591601611625 unmodified lines168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215package servicesimport ("context""errors""fmt""io""mime/multipart""path/filepath""regexp""strings""time""abdanhafidz.com/go-boilerplate/config"entity "abdanhafidz.com/go-boilerplate/models/entity"http_error "abdanhafidz.com/go-boilerplate/models/error""abdanhafidz.com/go-boilerplate/repositories""github.com/google/uuid")type UploadService interface {UploadFiles(ctx context.Context, files []*multipart.FileHeader, uploadContext string, accountID uuid.UUID) ([]entity.File, error)GetFileByID(ctx context.Context, fileID uuid.UUID, accountID uuid.UUID) (*entity.File, error)UploadRawFile(ctx context.Context, reader io.Reader, originalName string, contentType string, uploadContext string, accountID uuid.UUID) (*entity.File, error)}type uploadService struct {storageProvider storageUploaderfileRepo repositories.FileRepositorycfg config.UploadConfig}func NewUploadService(storage storageUploader, repo repositories.FileRepository, cfg config.UploadConfig) UploadService {return &uploadService{storageProvider: storage, fileRepo: repo, cfg: cfg}}type storageUploader interface {UploadFile(ctx context.Context, file io.Reader, destinationPath string, contentType string) (string, error)}func (s *uploadService) UploadFiles(ctx context.Context, files []*multipart.FileHeader, uploadContext string, accountID uuid.UUID) ([]entity.File, error) {config, err := s.cfg.Get(uploadContext)if err != nil {return nil, err}26 unmodified linesreturn uploadedFiles, nil}func (s *uploadService) GetFileByID(ctx context.Context, fileID uuid.UUID, accountID uuid.UUID) (*entity.File, error) {file, err := s.fileRepo.FindByID(ctx, fileID)if err != nil {if errors.Is(err, http_error.NOT_FOUND_ERROR) {9 unmodified linesreturn file, nil}func (s *uploadService) processSingleFile(ctx context.Context, fileHeader *multipart.FileHeader, config config.UploadRule, uploadContext string, accountID uuid.UUID) (*entity.File, error) {if err := s.validateFile(fileHeader, config); err != nil {return nil, err}33 unmodified linesreturn fileEntity, nil}func (s *uploadService) validateFile(file *multipart.FileHeader, config config.UploadRule) error {if file.Size == 0 || file.Size > config.MaxBytes {return http_error.FILE_TOO_LARGE}11 unmodified linesreturn nil}func (s *uploadService) generateStoredFilename(originalName string, ext string) string {originalNameWithoutExt := strings.TrimSuffix(originalName, ext)reg := regexp.MustCompile("[^a-zA-Z0-9._-]+")sanitizedRawName := reg.ReplaceAllString(originalNameWithoutExt, "_")3 unmodified linesreturn fmt.Sprintf("%s-%d-%s%s", uniqueID.String(), timestamp, sanitizedRawName, ext)}func (s *uploadService) generateStoragePath(prefix, contextType, filename string, accountID uuid.UUID) string {switch contextType {case "submission":now := time.Now()5 unmodified lines}}func (s *uploadService) UploadRawFile(ctx context.Context, reader io.Reader, originalName string, contentType string, uploadContext string, accountID uuid.UUID) (*entity.File, error) {rule, err := s.cfg.Get(uploadContext)if err != nil {return nil, http_error.BAD_REQUEST_ERROR}ext := strings.ToLower(strings.TrimSpace(filepath.Ext(originalName)))if ext == "" {if strings.Contains(contentType, "pdf") {ext = ".pdf"} else if strings.Contains(contentType, "png") {ext = ".png"} else if strings.Contains(contentType, "jpeg") || strings.Contains(contentType, "jpg") {ext = ".jpg"} else {ext = ".bin"}}storedFilename := s.generateStoredFilename(originalName, ext)storagePath := s.generateStoragePath(rule.PathPrefix, uploadContext, storedFilename, accountID)publicURL, err := s.storageProvider.UploadFile(ctx, reader, storagePath, contentType)if err != nil {return nil, err}fileEntity := &entity.File{Id: uuid.New(),OriginalName: originalName,StoredName: storedFilename,MimeType: contentType,Size: 0,Path: publicURL,Context: uploadContext,AccountId: accountID,CreatedAt: time.Now(),}if err := s.fileRepo.Create(ctx, fileEntity); err != nil {return nil, err}return fileEntity, nil}
1/.env12/.envgo-boilerplate.exe
.gitignore+2-1
config/supabase.goDeleted-19
config/supabase_config.goAdded+25
config/upload_config.goAdded+49
controllers/academy_controller.go-2
controllers/upload_controller.go+3-5
models/entity/contant.go+3-1
models/entity/entity.go+13-13
provider/provider.go+6-5
provider/services_provider.go+8-6
provider/storage_provider.goAdded+10
provider/supabase_storage.goDeleted-47
repositories/academy_repository.go+6-99
services/academy_service.go+22-25
services/academy_service_helpers.go+27-23
services/account_service.go+4-2
services/supabase_storage_service.goAdded+27
services/upload_service.go+73-132
space/.gitignore+2-1