Download app/api/organization.py from OpenVar/backend: direct link, hf CLI and curl.
- Browser
- Download file 15.3 kB
-
https://huggingface.co/spaces/OpenVar/backend/resolve/main/app/api/organization.py
- Command line
-
hf download hf://spaces/OpenVar/backend/app/api/organization.py
-
curl -L -o organization.py https://huggingface.co/spaces/OpenVar/backend/resolve/main/app/api/organization.py
15.3 kB
| """Organization, Department, and Membership management API.""" | |
| from datetime import datetime, timezone | |
| from typing import List, Optional | |
| from fastapi import APIRouter, Depends, HTTPException, status | |
| from pydantic import BaseModel | |
| from sqlalchemy.orm import Session | |
| from app.database import get_db | |
| from app.models.db import ( | |
| User, Organization, Department, Membership, | |
| UserType, OrgStatus, MemberRole, | |
| ) | |
| from app.services.auth_service import get_current_user, require_superadmin | |
| router = APIRouter() | |
| # --------------------------------------------------------------------------- | |
| # Schemas | |
| # --------------------------------------------------------------------------- | |
| class CreateOrgRequest(BaseModel): | |
| name: str | |
| display_name: Optional[str] = None | |
| description: Optional[str] = None | |
| website: Optional[str] = None | |
| industry: Optional[str] = None | |
| class OrgResponse(BaseModel): | |
| id: str | |
| name: str | |
| display_name: Optional[str] | |
| description: Optional[str] | |
| status: str | |
| creator_id: str | |
| website: Optional[str] | |
| industry: Optional[str] | |
| max_members: int | |
| rejection_reason: Optional[str] | |
| created_at: str | |
| approved_at: Optional[str] | |
| class Config: | |
| from_attributes = True | |
| class CreateDeptRequest(BaseModel): | |
| name: str | |
| description: Optional[str] = None | |
| parent_id: Optional[str] = None | |
| class DeptResponse(BaseModel): | |
| id: str | |
| organization_id: str | |
| name: str | |
| description: Optional[str] | |
| parent_id: Optional[str] | |
| member_count: int = 0 | |
| class Config: | |
| from_attributes = True | |
| class AddMemberRequest(BaseModel): | |
| email: str | |
| department_id: Optional[str] = None | |
| role: str = "member" | |
| class MemberResponse(BaseModel): | |
| id: str | |
| user_id: str | |
| user_email: str | |
| user_name: str | |
| organization_id: str | |
| department_id: Optional[str] | |
| department_name: Optional[str] | |
| role: str | |
| is_active: bool | |
| joined_at: str | |
| class ApproveOrgRequest(BaseModel): | |
| approved: bool | |
| rejection_reason: Optional[str] = None | |
| # --------------------------------------------------------------------------- | |
| # Helpers | |
| # --------------------------------------------------------------------------- | |
| def _org_response(org: Organization) -> OrgResponse: | |
| return OrgResponse( | |
| id=org.id, | |
| name=org.name, | |
| display_name=org.display_name, | |
| description=org.description, | |
| status=org.status.value, | |
| creator_id=org.creator_id, | |
| website=org.website, | |
| industry=org.industry, | |
| max_members=org.max_members, | |
| rejection_reason=org.rejection_reason, | |
| created_at=org.created_at.isoformat() if org.created_at else "", | |
| approved_at=org.approved_at.isoformat() if org.approved_at else None, | |
| ) | |
| def _require_org_admin(user: User, org: Organization, db: Session): | |
| """Ensure user is org creator or org_admin member.""" | |
| if user.is_superadmin: | |
| return | |
| if org.creator_id == user.id: | |
| return | |
| membership = db.query(Membership).filter( | |
| Membership.user_id == user.id, | |
| Membership.organization_id == org.id, | |
| Membership.role == MemberRole.org_admin, | |
| Membership.is_active == True, | |
| ).first() | |
| if not membership: | |
| raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Organization admin access required") | |
| # --------------------------------------------------------------------------- | |
| # Organization CRUD | |
| # --------------------------------------------------------------------------- | |
| async def create_organization( | |
| request: CreateOrgRequest, | |
| current_user: User = Depends(get_current_user), | |
| db: Session = Depends(get_db), | |
| ): | |
| """Enterprise user applies to create an organization. Status starts as 'pending'.""" | |
| if current_user.user_type != UserType.enterprise: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Only enterprise users can create organizations", | |
| ) | |
| existing = db.query(Organization).filter(Organization.name == request.name).first() | |
| if existing: | |
| raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Organization name already taken") | |
| org = Organization( | |
| name=request.name, | |
| display_name=request.display_name or request.name, | |
| description=request.description, | |
| website=request.website, | |
| industry=request.industry, | |
| creator_id=current_user.id, | |
| status=OrgStatus.pending, | |
| ) | |
| db.add(org) | |
| db.commit() | |
| db.refresh(org) | |
| return _org_response(org) | |
| async def list_my_organizations( | |
| current_user: User = Depends(get_current_user), | |
| db: Session = Depends(get_db), | |
| ): | |
| """List organizations the current user belongs to or created.""" | |
| created = db.query(Organization).filter(Organization.creator_id == current_user.id).all() | |
| member_orgs = ( | |
| db.query(Organization) | |
| .join(Membership, Membership.organization_id == Organization.id) | |
| .filter(Membership.user_id == current_user.id, Membership.is_active == True) | |
| .all() | |
| ) | |
| all_orgs = {org.id: org for org in created + member_orgs} | |
| return [_org_response(org) for org in all_orgs.values()] | |
| async def get_organization( | |
| org_id: str, | |
| current_user: User = Depends(get_current_user), | |
| db: Session = Depends(get_db), | |
| ): | |
| """Get organization details.""" | |
| org = db.query(Organization).filter(Organization.id == org_id).first() | |
| if not org: | |
| raise HTTPException(status_code=404, detail="Organization not found") | |
| return _org_response(org) | |
| # --------------------------------------------------------------------------- | |
| # Department management | |
| # --------------------------------------------------------------------------- | |
| async def create_department( | |
| org_id: str, | |
| request: CreateDeptRequest, | |
| current_user: User = Depends(get_current_user), | |
| db: Session = Depends(get_db), | |
| ): | |
| """Add a department to an organization.""" | |
| org = db.query(Organization).filter(Organization.id == org_id).first() | |
| if not org: | |
| raise HTTPException(status_code=404, detail="Organization not found") | |
| _require_org_admin(current_user, org, db) | |
| existing = db.query(Department).filter( | |
| Department.organization_id == org_id, Department.name == request.name | |
| ).first() | |
| if existing: | |
| raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Department name already exists") | |
| dept = Department( | |
| organization_id=org_id, | |
| name=request.name, | |
| description=request.description, | |
| parent_id=request.parent_id, | |
| ) | |
| db.add(dept) | |
| db.commit() | |
| db.refresh(dept) | |
| return DeptResponse( | |
| id=dept.id, | |
| organization_id=dept.organization_id, | |
| name=dept.name, | |
| description=dept.description, | |
| parent_id=dept.parent_id, | |
| ) | |
| async def list_departments( | |
| org_id: str, | |
| current_user: User = Depends(get_current_user), | |
| db: Session = Depends(get_db), | |
| ): | |
| """List all departments in an organization.""" | |
| departments = db.query(Department).filter(Department.organization_id == org_id).all() | |
| result = [] | |
| for dept in departments: | |
| count = db.query(Membership).filter( | |
| Membership.department_id == dept.id, Membership.is_active == True | |
| ).count() | |
| result.append(DeptResponse( | |
| id=dept.id, | |
| organization_id=dept.organization_id, | |
| name=dept.name, | |
| description=dept.description, | |
| parent_id=dept.parent_id, | |
| member_count=count, | |
| )) | |
| return result | |
| async def delete_department( | |
| org_id: str, | |
| dept_id: str, | |
| current_user: User = Depends(get_current_user), | |
| db: Session = Depends(get_db), | |
| ): | |
| """Delete a department.""" | |
| org = db.query(Organization).filter(Organization.id == org_id).first() | |
| if not org: | |
| raise HTTPException(status_code=404, detail="Organization not found") | |
| _require_org_admin(current_user, org, db) | |
| dept = db.query(Department).filter(Department.id == dept_id, Department.organization_id == org_id).first() | |
| if not dept: | |
| raise HTTPException(status_code=404, detail="Department not found") | |
| db.delete(dept) | |
| db.commit() | |
| return {"message": "Department deleted"} | |
| # --------------------------------------------------------------------------- | |
| # Member management | |
| # --------------------------------------------------------------------------- | |
| async def add_member( | |
| org_id: str, | |
| request: AddMemberRequest, | |
| current_user: User = Depends(get_current_user), | |
| db: Session = Depends(get_db), | |
| ): | |
| """Add a user to an organization by email. Creates an account if the user doesn't exist.""" | |
| org = db.query(Organization).filter(Organization.id == org_id).first() | |
| if not org: | |
| raise HTTPException(status_code=404, detail="Organization not found") | |
| if org.status != OrgStatus.approved: | |
| raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Organization is not approved yet") | |
| _require_org_admin(current_user, org, db) | |
| user = db.query(User).filter(User.email == request.email).first() | |
| if not user: | |
| raise HTTPException(status_code=404, detail=f"User with email {request.email} not found. They must register first.") | |
| existing = db.query(Membership).filter( | |
| Membership.user_id == user.id, | |
| Membership.organization_id == org_id, | |
| Membership.department_id == request.department_id, | |
| ).first() | |
| if existing: | |
| raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="User is already a member") | |
| role = MemberRole(request.role) if request.role in [r.value for r in MemberRole] else MemberRole.member | |
| membership = Membership( | |
| user_id=user.id, | |
| organization_id=org_id, | |
| department_id=request.department_id, | |
| role=role, | |
| ) | |
| db.add(membership) | |
| db.commit() | |
| db.refresh(membership) | |
| dept_name = None | |
| if membership.department_id: | |
| dept = db.query(Department).filter(Department.id == membership.department_id).first() | |
| dept_name = dept.name if dept else None | |
| return MemberResponse( | |
| id=membership.id, | |
| user_id=user.id, | |
| user_email=user.email, | |
| user_name=user.full_name, | |
| organization_id=org_id, | |
| department_id=membership.department_id, | |
| department_name=dept_name, | |
| role=membership.role.value, | |
| is_active=membership.is_active, | |
| joined_at=membership.joined_at.isoformat() if membership.joined_at else "", | |
| ) | |
| async def list_members( | |
| org_id: str, | |
| current_user: User = Depends(get_current_user), | |
| db: Session = Depends(get_db), | |
| ): | |
| """List all members in an organization.""" | |
| memberships = db.query(Membership).filter( | |
| Membership.organization_id == org_id, | |
| Membership.is_active == True, | |
| ).all() | |
| result = [] | |
| for m in memberships: | |
| user = db.query(User).filter(User.id == m.user_id).first() | |
| dept_name = None | |
| if m.department_id: | |
| dept = db.query(Department).filter(Department.id == m.department_id).first() | |
| dept_name = dept.name if dept else None | |
| result.append(MemberResponse( | |
| id=m.id, | |
| user_id=m.user_id, | |
| user_email=user.email if user else "", | |
| user_name=user.full_name if user else "", | |
| organization_id=org_id, | |
| department_id=m.department_id, | |
| department_name=dept_name, | |
| role=m.role.value, | |
| is_active=m.is_active, | |
| joined_at=m.joined_at.isoformat() if m.joined_at else "", | |
| )) | |
| return result | |
| async def remove_member( | |
| org_id: str, | |
| member_id: str, | |
| current_user: User = Depends(get_current_user), | |
| db: Session = Depends(get_db), | |
| ): | |
| """Remove a member from an organization.""" | |
| org = db.query(Organization).filter(Organization.id == org_id).first() | |
| if not org: | |
| raise HTTPException(status_code=404, detail="Organization not found") | |
| _require_org_admin(current_user, org, db) | |
| membership = db.query(Membership).filter(Membership.id == member_id, Membership.organization_id == org_id).first() | |
| if not membership: | |
| raise HTTPException(status_code=404, detail="Membership not found") | |
| membership.is_active = False | |
| db.commit() | |
| return {"message": "Member removed"} | |
| # --------------------------------------------------------------------------- | |
| # Admin endpoints (superadmin) | |
| # --------------------------------------------------------------------------- | |
| async def list_pending_organizations( | |
| _admin: User = Depends(require_superadmin), | |
| db: Session = Depends(get_db), | |
| ): | |
| """List all organizations pending approval (superadmin only).""" | |
| pending = db.query(Organization).filter(Organization.status == OrgStatus.pending).all() | |
| return [_org_response(org) for org in pending] | |
| async def list_all_organizations( | |
| _admin: User = Depends(require_superadmin), | |
| db: Session = Depends(get_db), | |
| ): | |
| """List all organizations (superadmin only).""" | |
| orgs = db.query(Organization).order_by(Organization.created_at.desc()).all() | |
| return [_org_response(org) for org in orgs] | |
| async def review_organization( | |
| org_id: str, | |
| request: ApproveOrgRequest, | |
| _admin: User = Depends(require_superadmin), | |
| db: Session = Depends(get_db), | |
| ): | |
| """Approve or reject a pending organization (superadmin only).""" | |
| org = db.query(Organization).filter(Organization.id == org_id).first() | |
| if not org: | |
| raise HTTPException(status_code=404, detail="Organization not found") | |
| if request.approved: | |
| org.status = OrgStatus.approved | |
| org.approved_at = datetime.now(timezone.utc) | |
| org.rejection_reason = None | |
| # Automatically add creator as org_admin | |
| existing = db.query(Membership).filter( | |
| Membership.user_id == org.creator_id, | |
| Membership.organization_id == org.id, | |
| ).first() | |
| if not existing: | |
| membership = Membership( | |
| user_id=org.creator_id, | |
| organization_id=org.id, | |
| role=MemberRole.org_admin, | |
| ) | |
| db.add(membership) | |
| else: | |
| org.status = OrgStatus.rejected | |
| org.rejection_reason = request.rejection_reason or "Application not approved" | |
| db.commit() | |
| db.refresh(org) | |
| return _org_response(org) | |