Spaces:
Paused

File size: 9,078 Bytes
5eb4857
 
 
 
 
b7980f7
5eb4857
 
 
 
 
b7980f7
5eb4857
 
 
b7980f7
5eb4857
 
 
 
 
 
 
 
b7980f7
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
b7980f7
 
 
 
 
 
5eb4857
 
e58f87e
5eb4857
 
 
e58f87e
5eb4857
 
 
 
 
 
 
 
 
 
 
 
b7980f7
 
 
5eb4857
 
 
 
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
b7980f7
 
 
 
 
 
 
 
 
 
 
5eb4857
b7980f7
5eb4857
b7980f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
e58f87e
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e58f87e
5eb4857
 
 
 
 
 
 
 
 
 
b7980f7
 
5eb4857
 
 
 
 
b7980f7
 
 
 
 
 
 
 
 
5eb4857
 
b7980f7
5eb4857
 
 
 
 
 
 
 
 
b7980f7
 
 
5eb4857
b7980f7
5eb4857
 
 
 
b7980f7
5eb4857
 
b7980f7
 
 
 
 
5eb4857
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
"""
User endpoints: profile and admin management.
"""

from datetime import datetime
from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select

from core.deps import get_db, get_current_user
from core.permissions import require_roles, WORKSPACE_ADMIN_ROLES
from core.security import get_password_hash
from core.logging import get_logger
from models.user import User, UserRole
from models.user_workspace import UserWorkspace
from schemas.user import UserResponse, UserUpdate, UserAdminUpdate, UserCreate

router = APIRouter()
logger = get_logger(__name__)

@router.post("/", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_workspace_user(
    payload: UserCreate,
    current_user: User = Depends(require_roles(WORKSPACE_ADMIN_ROLES)),
    db: AsyncSession = Depends(get_db)
) -> Any:
    """
    Administratively create a new user within the current workspace.
    - CUSTOMER_ADMIN can create CUSTOMER_ADMIN and CUSTOMER_USER.
    - SC_ADMIN can create SC_LEAD and SC_AGENT.
    """
    # 1. Role Validation
    allowed_roles = []
    if current_user.role == UserRole.CUSTOMER_ADMIN:
        allowed_roles = [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]
    elif current_user.role == UserRole.SC_ADMIN:
        allowed_roles = [UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SC_ADMIN]
    
    if payload.role not in allowed_roles:
        raise HTTPException(
            status_code=403, 
            detail=f"You do not have permission to assign the role: {payload.role}"
        )

    # 2. Duplicate Check (excluding soft-deleted users)
    stmt = select(User).where(User.email == payload.email, User.deleted_at.is_(None))
    result = await db.execute(stmt)
    if result.scalar_one_or_none():
        raise HTTPException(status_code=400, detail="User with this email already exists")

    # 3. Creation
    new_user = User(
        email=payload.email,
        hashed_password=get_password_hash(payload.password),
        full_name=payload.full_name,
        is_active=True
    )
    db.add(new_user)
    await db.flush() # Get user id

    # 4. Create Workspace Association
    # Note: Use current_user.workspace_id (the active context)
    new_link = UserWorkspace(
        user_id=new_user.id,
        workspace_id=current_user.workspace_id,
        role=payload.role,
        is_primary=True # For simplicity, first association is primary
    )
    db.add(new_link)
    
    await db.commit()
    await db.refresh(new_user)
    
    # Attach context for response (UserResponse expects role/workspace_id)
    setattr(new_user, "role", payload.role)
    setattr(new_user, "workspace_id", current_user.workspace_id)
    
    logger.info(f"User created: {new_user.email} (Role: {payload.role}) in workspace {current_user.workspace_id}")
    return new_user

@router.get("/me/", response_model=UserResponse)
async def read_user_me(current_user: User = Depends(get_current_user)) -> Any:
    return current_user

@router.patch("/me/", response_model=UserResponse)
async def update_user_me(
    payload: UserUpdate,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    for field, value in payload.model_dump(exclude_unset=True).items():
        setattr(current_user, field, value)
    db.add(current_user)
    await db.commit()
    await db.refresh(current_user)
    return current_user

@router.get("/", response_model=List[UserResponse])
async def list_users(
    workspace_id: Optional[str] = None,
    skip: int = 0, limit: int = 100,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    """
    List users - many-to-many aware.
    - Super Admin: Sees all users by default or via workspace_id='all'.
    - Local Admins: Strictly limited to their active workspace.
    """
    # 1. Check for Global Visibility (Super Admin ONLY)
    is_global = (workspace_id == "all" or (workspace_id is None and current_user.role == UserRole.SC_ADMIN))
    
    stmt = select(User).join(UserWorkspace, User.id == UserWorkspace.user_id)
    
    if is_global and current_user.role == UserRole.SC_ADMIN:
        # Platform-wide view
        pass 
    else:
        # Strict Isolation
        target_ws = workspace_id if (workspace_id and current_user.role == UserRole.SC_ADMIN) else current_user.workspace_id
        stmt = stmt.where(UserWorkspace.workspace_id == target_ws)
        
        # Role hierarchy for local admins
        if current_user.role == UserRole.CUSTOMER_ADMIN:
            allowed_roles = [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]
            stmt = stmt.where(UserWorkspace.role.in_(allowed_roles))
        elif current_user.role == UserRole.SC_LEAD:
            allowed_roles = [UserRole.SC_ADMIN, UserRole.SC_LEAD, UserRole.SC_AGENT]
            stmt = stmt.where(UserWorkspace.role.in_(allowed_roles))

    stmt = stmt.where(User.deleted_at.is_(None)).offset(skip).limit(limit)
    result = await db.execute(stmt)
    users = result.scalars().all()
    
    # 2. Inject context for the response
    for u in users:
        # Determine the workspace context for role discovery
        # If global, we use the user's primary/active context for role lookup
        context_ws = current_user.workspace_id if is_global else target_ws
        
        # Performance: find role for response context (safely fallback to primary if global)
        assoc_stmt = select(UserWorkspace.role).where(
            UserWorkspace.user_id == u.id
        )
        if not is_global:
            assoc_stmt = assoc_stmt.where(UserWorkspace.workspace_id == context_ws)
        
        u_role = (await db.execute(assoc_stmt.limit(1))).scalar() or UserRole.CUSTOMER_USER
        
        setattr(u, "role", u_role)
        setattr(u, "workspace_id", context_ws)
        
    return users

@router.delete("/{user_id}/", status_code=status.HTTP_200_OK, dependencies=[Depends(require_roles(WORKSPACE_ADMIN_ROLES))])
async def deactivate_user_v3(
    user_id: str,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    stmt = select(User).where(
        User.id == user_id, 
        User.workspace_id == current_user.workspace_id,
        User.deleted_at.is_(None)
    )
    result = await db.execute(stmt)
    user = result.scalar_one_or_none()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
        
    user.is_active = False
    user.deleted_at = datetime.utcnow()
    user.deleted_by_id = current_user.id
    db.add(user)
    await db.commit()
    logger.info(f"User deactivated/soft-deleted: {user_id} by admin {current_user.id}")
    return {"status": "deleted"}
@router.patch("/{user_id}/", response_model=UserResponse, dependencies=[Depends(require_roles(WORKSPACE_ADMIN_ROLES))])
async def update_user_admin(
    user_id: str,
    payload: UserAdminUpdate,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
) -> Any:
    """
    Administratively update another user's role or status.
    Uses the same hierarchy logic as creation.
    """
    # 1. Fetch User (Global check)
    stmt = select(User).where(User.id == user_id, User.deleted_at.is_(None))
    result = await db.execute(stmt)
    user = result.scalar_one_or_none()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")

    # 2. Fetch Association for CURRENT workspace
    assoc_stmt = select(UserWorkspace).where(
        UserWorkspace.user_id == user_id,
        UserWorkspace.workspace_id == current_user.workspace_id
    )
    association = (await db.execute(assoc_stmt)).scalar_one_or_none()
    if not association:
        raise HTTPException(status_code=403, detail="User is not in your workspace")

    update_data = payload.model_dump(exclude_unset=True)

    # Role validation
    if "role" in update_data:
        allowed_roles = []
        if current_user.role == UserRole.CUSTOMER_ADMIN:
             allowed_roles = [UserRole.CUSTOMER_ADMIN, UserRole.CUSTOMER_USER]
        elif current_user.role == UserRole.SC_ADMIN:
             allowed_roles = [UserRole.SC_LEAD, UserRole.SC_AGENT, UserRole.SC_ADMIN]
             
        if update_data["role"] not in allowed_roles:
            raise HTTPException(status_code=403, detail=f"Permission denied for role: {update_data['role']}")
        
        # Update association role, not user role
        association.role = update_data.pop("role")

    # Update other User fields (name, avatar, etc)
    for field, value in update_data.items():
        setattr(user, field, value)

    db.add(user)
    db.add(association)
    await db.commit()
    await db.refresh(user)
    
    # Inject context for response
    setattr(user, "role", association.role)
    setattr(user, "workspace_id", current_user.workspace_id)
    
    logger.info(f"User {user_id} updated by admin {current_user.id}: {update_data}")
    return user