package application import ( "context" "errors" "mengstack/internal/modules/settings/domain" "gorm.io/gorm" ) type Service struct { repo domain.SettingRepository } func NewService(repo domain.SettingRepository) *Service { return &Service{repo: repo} } func (s *Service) GetGlobalSetting(ctx context.Context, key string) (*domain.SettingDTO, error) { setting, err := s.repo.FindByKey(ctx, "", key) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return nil, nil } return nil, err } dto := domain.ToSettingDTO(setting) return &dto, nil } func (s *Service) UpdateGlobalSetting(ctx context.Context, key string, req *domain.UpdateSettingRequest, userID uint) error { setting := &domain.Setting{ TenantID: "", Key: key, Value: req.Value, Type: req.Type, Scope: "global", UpdatedBy: userID, } if setting.Type == "" { setting.Type = "string" } return s.repo.Upsert(ctx, setting) } func (s *Service) ListGlobalSettings(ctx context.Context) ([]domain.SettingDTO, error) { settings, err := s.repo.FindGlobal(ctx) if err != nil { return nil, err } result := make([]domain.SettingDTO, len(settings)) for i, s := range settings { result[i] = domain.ToSettingDTO(&s) } return result, nil } func (s *Service) GetTenantSetting(ctx context.Context, tenantID, key string) (*domain.SettingDTO, error) { setting, err := s.repo.FindByKey(ctx, tenantID, key) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { return s.GetGlobalSetting(ctx, key) } return nil, err } dto := domain.ToSettingDTO(setting) return &dto, nil } func (s *Service) UpdateTenantSetting(ctx context.Context, tenantID, key string, req *domain.UpdateSettingRequest, userID uint) error { setting := &domain.Setting{ TenantID: tenantID, Key: key, Value: req.Value, Type: req.Type, Scope: "tenant", UpdatedBy: userID, } if setting.Type == "" { setting.Type = "string" } return s.repo.Upsert(ctx, setting) } func (s *Service) ListTenantSettings(ctx context.Context, tenantID string) ([]domain.SettingDTO, error) { settings, err := s.repo.FindByTenant(ctx, tenantID) if err != nil { return nil, err } result := make([]domain.SettingDTO, len(settings)) for i, s := range settings { result[i] = domain.ToSettingDTO(&s) } return result, nil } func (s *Service) DeleteTenantSetting(ctx context.Context, tenantID, key string) error { return s.repo.Delete(ctx, tenantID, key) }