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
112/.env/.envgo-boilerplate.exe12345678910111213141516171819package 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" }123445669 unmodified lines76777880798081package controllers
import ( "fmt" "net/http" "strconv"
69 unmodified lines return }
fmt.Println("Account ID in ListAcademies:", accountId) res, err := c.academyService.ListAcademies(ctx.Request.Context(), accountId) ResponseJSON(ctx, gin.H{}, res, err)}17 unmodified lines1819202121222324252624252627218 unmodified lines24624724825124917 unmodified lines)
type UploadController struct { uploadService *services.UploadService uploadService services.UploadService}
func NewUploadController(s *services.UploadService) *UploadController { return &UploadController{uploadService: s}}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 lines return "material" } return ""}}3 unmodified lines45677893 unmodified lines StatusNotStarted = "NOT_STARTED" StatusInProgress = "IN_PROGRESS" StatusCompleted = "COMPLETED"))
const MB = 1024 * 1024266 unmodified lines26726826927027027127227326 unmodified lines3003013023033043053033043053063073083 unmodified lines3123133143153163173183153163173183193203213 unmodified lines325326327328329330331332328329330331332333334335266 unmodified lines ImageUrl 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"` AcademyProgress AcademyProgress `gorm:"foreignKey:AcademyId;references:Id" json:"academy_progresses,omitempty"`}
func (Academy) TableName() string { return "academy" }26 unmodified lines// Progress
type 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"` 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;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"` 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;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"` 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 lines56789101119 unmodified lines313233333435363637383939404142424344454683 unmodified lines1301311321321334 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 lines configProvider := NewConfigProvider() repositoriesProvider := NewRepositoriesProvider(configProvider) supabaseCfg := configProvider.ProvideSupabaseConfig() if supabaseCfg.URL == "" || supabaseCfg.ServiceKey == "" || supabaseCfg.BucketName == "" { if supabaseCfg.GetURL() == "" || supabaseCfg.GetServiceKey() == "" || supabaseCfg.GetBucketName() == "" { log.Fatalf("Supabase configuration is invalid: URL, ServiceKey, or BucketName is empty") } if !strings.HasPrefix(supabaseCfg.URL, "https://") || !strings.Contains(supabaseCfg.URL, ".supabase.co") { if !strings.HasPrefix(supabaseCfg.GetURL(), "https://") || !strings.Contains(supabaseCfg.GetURL(), ".supabase.co") { log.Fatalf("Supabase URL is invalid") } if strings.Count(supabaseCfg.ServiceKey, ".") != 2 { if strings.Count(supabaseCfg.GetServiceKey(), ".") != 2 { log.Fatalf("Supabase service key is not a valid compact JWS") } storageDriver := NewSupabaseStorage(supabaseCfg.URL, supabaseCfg.ServiceKey, supabaseCfg.BucketName) storageDriver := services.NewSupabaseStorageService(supabaseCfg.GetURL(), supabaseCfg.GetServiceKey(), supabaseCfg.GetBucketName()) servicesProvider := NewServicesProvider(repositoriesProvider, configProvider, storageDriver) controllerProvider := NewControllerProvider(servicesProvider) middlewareProvider := NewMiddlewareProvider(servicesProvider)83 unmodified lines
func (a *appProvider) ProvideMiddlewares() MiddlewareProvider { return a.middlewareProvider}}1234456788 unmodified lines17181919202122239 unmodified lines3334353536373839404142424344454620 unmodified lines6768697071727347 unmodified lines121122123122124125126127126128package provider
import ( "abdanhafidz.com/go-boilerplate/services" "abdanhafidz.com/go-boilerplate/config" "abdanhafidz.com/go-boilerplate/services")
type ServicesProvider interface {8 unmodified lines ProvideForgotPasswordService() services.ForgotPasswordService ProvideEmailVerificationService() services.EmailVerificationService ProvideExternalAuthService() services.ExternalAuthService ProvideUploadService() *services.UploadService ProvideUploadService() services.UploadService ProvideAcademyExamService() services.AcademyExamService}
9 unmodified lines forgotPasswordService services.ForgotPasswordService emailVerificationService services.EmailVerificationService externalAuthService services.ExternalAuthService uploadService *services.UploadService uploadService services.UploadService academyExamService services.AcademyExamService}
func NewServicesProvider( repoProvider RepositoriesProvider, configProvider ConfigProvider, storageProvider services.StorageProvider, storageProvider StorageProvider, ) ServicesProvider {
eventService := services.NewEventService(repoProvider.ProvideEventsRepository(), repoProvider.ProvideEventAssignRepository())20 unmodified lines uploadService := services.NewUploadService( storageProvider, repoProvider.ProvideFileRepository(), config.NewUploadConfig(), )
return &servicesProvider{47 unmodified lines return s.externalAuthService}
func (s *servicesProvider) ProvideUploadService() *services.UploadService {func (s *servicesProvider) ProvideUploadService() services.UploadService { return s.uploadService}
func (s *servicesProvider) ProvideAcademyExamService() services.AcademyExamService { return s.academyExamService }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 lines58596061626361626340 unmodified lines10410510611010710810911038 unmodified lines149150151155152153157154155156157128 unmodified lines28628728829228929029129215 unmodified lines30830931031431131231331416 unmodified lines33133233333733433533633755 unmodified lines39339439539940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748839639739857 unmodified lines DecrementContentOrdersGreaterThan(ctx context.Context, materialId uuid.UUID, order uint) error GetAccumulatedMaterialProgress(ctx context.Context, accountId uuid.UUID, academyId uuid.UUID) (float64, error)
BatchRecalculateMaterialProgress(ctx context.Context, materialId uuid.UUID) error BatchRecalculateAcademyProgress(ctx context.Context, academyId uuid.UUID) 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 lines if err != nil { return a, err } a.AcademyProgresss = ap a.AcademyProgress = ap return a, nil}
38 unmodified lines
for i := range list { if p, exists := progressMap[list[i].Id]; exists { list[i].AcademyProgresss = p list[i].AcademyProgress = p } else { list[i].AcademyProgresss = entity.AcademyProgress{ list[i].AcademyProgress = entity.AcademyProgress{ AccountId: accountId, AcademyId: list[i].Id, Status: entity.StatusNotStarted,128 unmodified lines
func (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"}}, Columns: []clause.Column{{Name: "account_id"}, {Name: "academy_id"}}, UpdateAll: true, }).Save(&p).Error}15 unmodified lines
func (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"}}, Columns: []clause.Column{{Name: "account_id"}, {Name: "material_id"}}, UpdateAll: true, }).Save(&p).Error}16 unmodified lines
func (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"}}, Columns: []clause.Column{{Name: "account_id"}, {Name: "content_id"}}, UpdateAll: true, }).Save(&p).Error}55 unmodified lines return 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 amp SET total_completed_contents = ( SELECT COUNT(id) FROM academy_content_progresses acp WHERE 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 acp WHERE acp.material_id = amp.material_id AND acp.account_id = amp.account_id AND acp.status = 'COMPLETED' )::float / ? * 100, status = CASE WHEN ( SELECT COUNT(id) FROM academy_content_progresses acp WHERE 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 = CASE WHEN ( SELECT COUNT(id) FROM academy_content_progresses acp WHERE acp.material_id = amp.material_id AND acp.account_id = amp.account_id AND acp.status = 'COMPLETED' ) >= ? THEN NOW() ELSE NULL END WHERE 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 ap SET progress = ( SELECT COALESCE(SUM(amp.progress), 0) FROM academy_material_progresses amp WHERE amp.academy_id = ap.academy_id AND amp.account_id = ap.account_id )::float / ?, total_completed_materials = ( SELECT COUNT(id) FROM academy_material_progresses amp WHERE amp.academy_id = ap.academy_id AND amp.account_id = ap.account_id AND amp.status = 'COMPLETED' ), status = CASE WHEN ( SELECT COUNT(id) FROM academy_material_progresses amp WHERE 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 = CASE WHEN ( SELECT COUNT(id) FROM academy_material_progresses amp WHERE amp.academy_id = ap.academy_id AND amp.account_id = ap.account_id AND amp.status = 'COMPLETED' ) >= ? THEN NOW() ELSE NULL END WHERE 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.AcademyMaterialProgress result := r.db.WithContext(ctx).Where("account_id = ? AND academy_id = ? AND material_id IN ?", accountId, academyId, materialIds).Find(&progresses)171 unmodified lines17217317417517617717517617717842 unmodified lines22122222322622722822422522622736 unmodified lines26426526627127227327427527626726826927035 unmodified lines30630730831831932032132232332432530931031131231331433131531631731848 unmodified lines36736836938637037137237321 unmodified lines39539639741439839940040149 unmodified lines45145245347045445545645745845946046115 unmodified lines477478479492480481482483484485486487488489490491492171 unmodified lines return err }
if err := txRepo.BatchRecalculateAcademyProgress(ctx, req.AcademyId); err != nil { return err } // progress recalculation handled on get
return nil })42 unmodified lines return err }
if err := txRepo.BatchRecalculateAcademyProgress(ctx, m.AcademyId); err != nil { return err } // progress recalculation handled on get
return nil })36 unmodified lines return err }
if err := txRepo.BatchRecalculateMaterialProgress(ctx, req.MaterialId); err != nil { return err } if err := txRepo.BatchRecalculateAcademyProgress(ctx, m.AcademyId); err != nil { return err } // progress recalculation handled on get
return nil })35 unmodified lines if _, err := txRepo.UpdateMaterial(ctx, material); err != nil { return err } if err := txRepo.BatchRecalculateMaterialProgress(ctx, c.MaterialId); err != nil { return err }
// Update Academy juga if err := txRepo.BatchRecalculateAcademyProgress(ctx, material.AcademyId); err != nil { return err } // progress recalculation handled on get
return nil })}
// ================= UPDATE PROGRESS ================= // ================= 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 lines if totalContentsCompleted >= m.ContentsCount { matStatus = entity.StatusCompleted matCompletedAt = utils.Ptr(time.Now()) progressPct = 100 progressPct = 100 } } else { matStatus = entity.StatusCompleted21 unmodified lines }
accumulatedProgress, _ := txRepo.GetAccumulatedMaterialProgress(ctx, accountId, academy.Id) a, _ := txRepo.GetAcademyByID(ctx, academy.Id) a, _ := txRepo.GetAcademyByID(ctx, academy.Id)
acadStatus := entity.StatusNotStarted var acadCompletedAt *time.Time49 unmodified lines if err != nil { return nil, http_error.ACADEMY_NOT_FOUND } academyProgress, _ := s.academyRepo.GetAcademyProgress(ctx, accountId, academy.Id) 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 lines if err != nil { return nil, http_error.MATERIAL_NOT_FOUND } materialProgress, _ := s.academyRepo.GetMaterialProgress(ctx, accountId, academy.Id, material.Id) 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 lines39404142434445464243444546474849505152535 unmodified lines59606158596263646566676862 unmodified lines13113213312812913013113213313413513413513613713813914014114214314414014114214314414514614714514614714814915015115215315438 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) 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 errors return entity.AcademyContentProgress{}, err }
acp := entity.AcademyContentProgress{ Id: s.getOrCreateID(existing.Id),5 unmodified lines CompletedAt: utils.Ptr(time.Now()), }
txRepo.UpsertContentProgress(ctx, acp) return acp 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, _ := txRepo.GetAcademyByID(ctx, academyId) academy.MaterialsCount = count _, err = txRepo.UpdateAcademy(ctx, academy) return err 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, _ := txRepo.GetMaterialByID(ctx, materialId) material.ContentsCount = count _, err = txRepo.UpdateMaterial(ctx, material) return err 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 lines345678928 unmodified lines3839404041424324 unmodified lines686970717172737475762 unmodified linesimport ( "context" "errors" "fmt" "regexp" "strings"
28 unmodified lines jwtService: jwtService, accountRepo: accountRepo, accountDetailRepo: accountDetailRepo, }}
24 unmodified lines return entity.Account{}, err }
_, _ = s.CreateEmptyDetail(ctx, created.Id) 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}123456789101112131415161745678910111213141516171819202021222324252627282930212223242526333435272829303132383940333435364344454647373839405051414243444526 unmodified lines72737484757677789 unmodified lines8889901009192939433 unmodified lines12812913014013113213313411 unmodified lines1461471481581491501511523 unmodified lines1561571581681591601611625 unmodified lines168169170180181182183184185186187171172173174175176177178179180181182183184185186187188189190189190191192193194195196192193197198199200201202203204205206207208209196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226210211212228213230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274214215package services
import ( "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" "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")
const MB = 1024 * 1024
type uploadConfig struct { MaxBytes int64 AllowedExts map[string]bool PathPrefix string MaxCount int}
type StorageProvider interface { UploadFile(ctx context.Context, file io.Reader, destinationPath string, contentType string) (string, error)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 FileRepository interface { Create(ctx context.Context, file *entity.File) error FindByID(ctx context.Context, id uuid.UUID) (*entity.File, error)type uploadService struct { storageProvider storageUploader fileRepo repositories.FileRepository cfg config.UploadConfig}
type UploadService struct { storageProvider StorageProvider fileRepo FileRepositoryfunc NewUploadService(storage storageUploader, repo repositories.FileRepository, cfg config.UploadConfig) UploadService { return &uploadService{storageProvider: storage, fileRepo: repo, cfg: cfg}}
func NewUploadService(storage StorageProvider, repo FileRepository) *UploadService { return &UploadService{ storageProvider: storage, fileRepo: repo, }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.getUploadConfig(uploadContext)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 lines return uploadedFiles, nil}
func (s *UploadService) GetFileByID(ctx context.Context, fileID uuid.UUID, accountID uuid.UUID) (*entity.File, error) {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 lines return file, nil}
func (s *UploadService) processSingleFile(ctx context.Context, fileHeader *multipart.FileHeader, config uploadConfig, uploadContext string, accountID uuid.UUID) (*entity.File, error) {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 lines return fileEntity, nil}
func (s *UploadService) validateFile(file *multipart.FileHeader, config uploadConfig) error {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 lines return nil}
func (s *UploadService) generateStoredFilename(originalName string, ext string) string {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 lines return fmt.Sprintf("%s-%d-%s%s", uniqueID.String(), timestamp, sanitizedRawName, ext)}
func (s *UploadService) generateStoragePath(prefix, contextType, filename string, accountID uuid.UUID) string {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] = vfunc (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" } } for k, v := range imgExts { allExts[k] = v
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 } for k, v := range docExts { allExts[k] = v
fileEntity := &entity.File{ Id: uuid.New(), OriginalName: originalName, StoredName: storedFilename, MimeType: contentType, Size: 0, Path: publicURL, Context: uploadContext, AccountId: accountID, CreatedAt: time.Now(), }
switch contextType { case "image": return uploadConfig{ MaxBytes: 10 * MB, AllowedExts: imgExts, PathPrefix: "images", MaxCount: 5, }, nil case "material": return uploadConfig{ MaxBytes: 10 * MB, AllowedExts: docExts, PathPrefix: "materials", MaxCount: 1, }, nil case "submission": return uploadConfig{ MaxBytes: 1 * MB, AllowedExts: codeExts, PathPrefix: "submissions", MaxCount: 1, }, nil case "general": return uploadConfig{ MaxBytes: 5 * MB, AllowedExts: allExts, PathPrefix: "temp", MaxCount: 5, }, nil default: return uploadConfig{}, http_error.INVALID_DATA_PAYLOAD if err := s.fileRepo.Create(ctx, fileEntity); err != nil { return nil, err }}
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} return fileEntity, nil}112/.env/.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