package infrastructure import ( "context" "mengstack/internal/modules/rbac/domain" "gorm.io/gorm" ) type roleRepo struct { db *gorm.DB } func NewRoleRepository(db *gorm.DB) domain.RoleRepository { return &roleRepo{db: db} } func (r *roleRepo) Create(ctx context.Context, role *domain.Role) error { return r.db.WithContext(ctx).Create(role).Error } func (r *roleRepo) FindByID(ctx context.Context, tenantID string, id uint) (*domain.Role, error) { var role domain.Role err := r.db.WithContext(ctx).Where("id = ? AND tenant_id = ?", id, tenantID).First(&role).Error return &role, err } func (r *roleRepo) FindByIDWithPermissions(ctx context.Context, tenantID string, id uint) (*domain.Role, error) { var role domain.Role err := r.db.WithContext(ctx). Preload("Permissions"). Where("roles.id = ? AND roles.tenant_id = ?", id, tenantID). First(&role).Error return &role, err } func (r *roleRepo) FindByTenant(ctx context.Context, tenantID string) ([]domain.Role, error) { var roles []domain.Role err := r.db.WithContext(ctx). Preload("Permissions"). Where("tenant_id = ?", tenantID). Order("name"). Find(&roles).Error return roles, err } func (r *roleRepo) Update(ctx context.Context, role *domain.Role) error { return r.db.WithContext(ctx).Save(role).Error } func (r *roleRepo) Delete(ctx context.Context, tenantID string, id uint) error { return r.db.WithContext(ctx). Where("id = ? AND tenant_id = ?", id, tenantID). Delete(&domain.Role{}).Error } func (r *roleRepo) SetPermissions(ctx context.Context, roleID uint, permIDs []uint) error { role := &domain.Role{ID: roleID} perms := make([]domain.Permission, len(permIDs)) for i, id := range permIDs { perms[i] = domain.Permission{ID: id} } return r.db.WithContext(ctx).Model(role).Association("Permissions").Replace(perms) }