Setting User Role using Server Scripts

I have 4 different main user roles created

  • Loan Manager
  • Loan Officer
  • Loan Officer Assistant
  • Loan Processor

and 1 user role for initial entry “Initial User”
i have set this initial user role as my default role in portal settings so that this user can only see the webform. As new users signup, this role is assigned and after they login they will see this form, this form contains other data along with “role” as select field where they select any 1 role from above regarding loan.

once they fill up this form and submit, i want to change the role to the selected role by the user. Now i tried creating server scripts, its changing but not updating on database. “Initial details is the doctype of form”

try:
    
    initial_role = "Initial User"
    doc = frappe.get_doc("Initial Details", {"email": "tommy112@yopmail.com"})
    user_doc = frappe.get_doc("User", {"email": "tommy112@yopmail.com"})
    
    # Check if the user has a specific role
    if initial_role in [role.role for role in user_doc.roles]:
        
        # Remove the old role
        user_doc.remove_roles(initial_role)
    
    # Add a new role
    user_doc.add_roles(doc.personal_details_role)
    user_doc.save()
    frappe.msgprint(f"Role udpated : {user_doc.email}")

except Exception as err:
    frappe.throw(f"{err=}")

and the above code is attached to “Initial Details doctype” with “After Insert” event

when i open incognito window and try with user,
the event is triggered but role not changed

when i change event type to After Save
and make change “from my AdminUser
and then save, the event is triggered
and role is also changed

Please help

NO update on this ?

When i’m adding System Manager as role to my existing custom role,
then its changing the role

how do i find out which permissions from the System manager Role is required for changing the Role for Users?