skailan-core
Version:
Servicio de autenticación y multitenancy para Skailan.
64 lines • 2.47 kB
JavaScript
import { ValidationError, PermissionError, } from "../../../shared/errors/CustomErrors";
export class MembershipService {
repo;
constructor(repo) {
this.repo = repo;
}
/**
* Agrega un nuevo miembro a la organización.
*/
async addMember(membership) {
// Validar que no exista ya la membresía
const existing = await this.repo.findByUserAndOrg(membership.userId, membership.organizationId);
if (existing)
throw new ValidationError("El usuario ya es miembro de la organización.");
await this.repo.save(membership);
}
/**
* Cambia el rol de un miembro, validando reglas de negocio.
*/
async changeRole(membershipId, newRole) {
const membership = await this.repo.findById(membershipId);
if (!membership)
throw new ValidationError("Membresía no encontrada.");
// No permitir eliminar el último OWNER
if (membership.role === "OWNER" && newRole !== "OWNER") {
const owners = await this.repo.findByOrgAndRole(membership.organizationId, "OWNER");
if (owners.length === 1)
throw new PermissionError("No se puede eliminar el último OWNER.");
}
membership.role = newRole;
await this.repo.save(membership);
}
/**
* Elimina un miembro, validando que no sea el último OWNER.
*/
async removeMember(membershipId) {
const membership = await this.repo.findById(membershipId);
if (!membership)
throw new ValidationError("Membresía no encontrada.");
if (membership.role === "OWNER") {
const owners = await this.repo.findByOrgAndRole(membership.organizationId, "OWNER");
if (owners.length === 1)
throw new PermissionError("No se puede eliminar el último OWNER.");
}
await this.repo.delete(membershipId);
}
/**
* Lista los miembros de una organización.
*/
async listMembers(organizationId) {
return this.repo.findByOrg(organizationId);
}
/**
* Suspende o reactiva un miembro.
*/
async setStatus(membershipId, status) {
const membership = await this.repo.findById(membershipId);
if (!membership)
throw new ValidationError("Membresía no encontrada.");
membership.status = status;
await this.repo.save(membership);
}
}
//# sourceMappingURL=MembershipService.js.map