o
    Ah.                     @   sh  d dl mZmZmZmZ d dlmZmZmZ d dl	m
Z
 d dlmZ d dlmZ d dlmZmZmZ d dlmZmZmZ d dlmZ d d	lmZmZ e Zejd
dgdeefddZdedeeee  f fddZ!de dee" fddZ#dedee" fddZ$ejddgdeej%eefdej&fddZ'ej(ddgdeej%eefdej&fd d!Z)d"S )#    )	APIRouterDependsHTTPExceptionstatus)OptionalDictList)jsonable_encoder)ObjectId)database)Role
RoleCreate
RoleUpdate)create_role_serviceupdate_role_serviceget_role_service)get_current_userdetails)features_listdefault_rolesz	/featuresFeatures)tagsc                    s8   |  d}|dkrtS |dkrdtd iS tddd)z
    Returns the list of features.
      - If current user has role 1 (Superadmin), return both SaaS and Platform features.
      - If current user has role 100 (Account admin), return only Platform features.
    roles   d   platform  Insufficient permissionsstatus_codedetail)getr   r   )current_user	user_role r#   4/var/www/html/moveengine/app/v1/routers/saas/rbac.pyget_features   s   
r%   role_idreturnc                 C   s  i }| dkrt d }| dkr!g d}|D ]
}| ||d < q|S | dkrBh d}g d}|D ]}|d |v r?| ||d < q/|S | d	krch d
}g d}|D ]}|d |v r`| ||d < qP|S | dkrh d
}g d}|D ]}|d |v r| ||d < qq|S | dkrdh}g d}|D ]}|d |v r| ||d < q|S | dkrmt d }| dkrg d}ddh}|D ]}|d |vr| ||d < q|S | dkrg d}ddh}|D ]}|d |vr| ||d < q|S | dkr|D ]}|d dv rg d||d < qdg||d < q|S | dkr2ddh}|D ]}|d |v r.g d||d < q|S | dkrRh d}|D ]}|d |v rNg d||d < q=|S | dkrk|D ]}|d dkridg||d < qY|S t  D ]}|D ]
}dg||d < quqq|S )u  
    Generate a permissions mapping for a given system role based on its name, using module IDs as keys.
    
    SaaS roles:
      - Superadmin: Full access (IDs 1-13, all actions).
      - Sales/Accounts: Access to modules [1,2,3,4,5,6,10,11,12] with actions: create, read, update.
      - Partner (and Tech Team): Limited access (only IDs [1,2,3,4,5,10,11,12]) with actions: create, read, update.
    
    Platform roles:
      - Admin: Full access to all modules (IDs 21–35).
      - Manager: All modules with actions: create, read, update, delete.
      - Finance: For Transactions (ID 32) and Invoices (ID 33), full access; read-only for other modules.
      - Customer: Only access to modules [22, 23] with actions: create, read, update.
      - Vendor: Limited access to modules [21, 24, 25, 26, 27] with actions: create, read, update.
      - Workforce: Only access to the Workforce module (ID 27, read-only).
    c   saasr   )createreadupdatedeleteid   >	   r   r/               
         )r*   r+   r,   r0   >   r   r/   r0   r1   r2   r4   r5   r6   r1   r2   r5   r   r         e   f   >       !   r+   h   i   >                  g   rC   )r   copyvalues)r&   permissionsmodulesactionsfeatureallowed_idsdisabled_idscategoryr#   r#   r$   generate_role_permissions   s   E?92+
!



rN   namec                       | d }| |ddS )zD
    Check if a system default role with the given name exists.
    r   T)rO   is_system_defaultfind_one)dbrO   roles_collectionr#   r#   r$   get_role_by_name~      rV   r.   c                    rP   )zG
    Check if a system default role with the given role_id exists.
    r   T)r&   rQ   rR   )rT   r.   rU   r#   r#   r$   get_role_by_id   rW   rX   z/accessRBACrT   c                    s|   | d}|dkrt}n|dkrdtd i}ntddd| d}|s)d	|iS t|| I d
H }|s9tddd||dS )zn
    Returns the list of features (tailored to the user's role) and the role rights from the roles table.
    r   r   r   r   r   r   r   r&   rH   Ni  zRole not found)rH   role)r    r   r   r   )rT   r!   r"   rH   r&   rZ   r#   r#   r$   
get_access   s   


r[   z/defaultRolesc                    s  | ddkrtddd| d }t D ]-\}}|D ]&}d|vr+|d  d	|d< | }||d
< |j|d |dd|idd qqtdd tD }| d }|jddidd|iidd g }	tD ]b}
t| |
d I dH }t	|
d }|r|
d |
d ||
d |
d |
 ddd}t
d!i |}t|d || }|	| qct|
d |
d |
d |d|
d |
d |
 ddd}t|| }|	| qctd|	ittid S )"a  
    Create or update default system roles and insert the features list into the features collection.
    
    This endpoint performs the following:
      1. Inserts/updates the features list (with descriptions) into a dedicated "features" collection.
      2. Updates the features counter (using _id: "features_id") so new features have an appropriate ID.
      3. Creates or updates default system roles with mapped permissions.
    
    Default system roles:
      - SaaS Roles (role_id 1-4): 
          1: Superadmin (full access, is_global_access=True, is_saas_only=True)
          2: Sales/Accounts (access only to allowed modules, is_global_access=True, is_saas_only=True)
          3: Partner (limited access, is_global_access=False, is_saas_only=True)
          4: Tech Team (limited access, is_global_access=False, is_saas_only=True)
      - Platform Roles (role_id 100+):
          100: Admin (full access, is_global_access=True)
          101: Manager (read & update, is_global_access=True)
          102: Finance (full on Transactions/Invoices, read-only otherwise, is_global_access=True)
          103: Workforce (minimal; only Workforce module, is_global_access=False)
          104: Customer (access only to Dashboard and Booking, read-only, is_global_access=True)
          105: Vendor (limited access, is_global_access=False)
    
    These roles are marked with is_system_default=True so they are not modifiable.
    System roles do not use an account_id.
    r   r   r   z.Not authorized to create default system roles.r   featuresdescriptionrO   z featurerM   r.   )features_idrM   z$setT)upsertc                 s   s&    | ]}t | D ]}|d  V  qqdS )r.   N)r   ).0rM   rJ   r#   r#   r$   	<genexpr>   s    z.create_default_system_roles.<locals>.<genexpr>counters_idr_   sequence_valuer&   NrQ   is_global_accessis_saas_onlyF)rO   r^   rG   rQ   rf   rg    )r&   rO   r^   rG   
account_idrQ   rf   rg   created_roles)custom_encoderr#   )r    r   r   itemsrE   
update_onemaxr   rX   rN   r   r   appendr   r   r	   r
   str)rT   r!   features_collectionrM   r]   rJ   feature_docmax_feature_idcounters_collectionrj   role_defexistingrG   update_datarole_update_modelupdated_rolerole_createnew_roler#   r#   r$   create_default_system_roles   sj   




r|   N)*fastapir   r   r   r   typingr   r   r   fastapi.encodersr	   bsonr
   app.dbr   app.v1.models.saas.rolemodelr   r   r   app.v1.services.saas.rolesr   r   r   app.v1.dependencies.authr   app.v1.models.defaultr   r   routerr    r%   intrp   rN   dictrV   rX   get_mongo_dbMongoDBr[   postr|   r#   r#   r#   r$   <module>   s6    `