> ## Knowledge Base Index
> Fetch the complete knowledge base index at: https://help.swellsystem.com/sitemap.xml
> Use this file to discover available pages before exploring further.
> Pure-Markdown content can be obtained by appending a '.md' suffix to the content URLs listed in the sitemap (without the trailing slash).

# Complete User Management Guide

# Complete User Management Guide

## How Users Invite Team Members

### Location: Settings → Team

1. **Access Team Management:**
   - Go to **Settings** in the main navigation
   - Click **Team** tab
   - You'll see all current team members

2. **Invite User:**
   - Click **"+ Invite User"** button (top right)
   - Fill in the invitation form:
     - **Email Address** (required): The email of the person to invite
     - **Name** (optional): Their name (can be set during acceptance if not provided)
     - **Role** (required): Choose from:
       - **Member**: Standard access
       - **Admin**: Full access (can manage users)
       - **Guest**: Read-only access
   - Click **"Send Invitation"**

3. **What Happens:**
   - Invitation record is created in database
   - Email is sent to the invited user via `UserInvitationNotification`
   - Invitation link expires in **7 days**
   - User slot is **reserved** but not consumed until acceptance

4. **User Accepts:**
   - Invited user clicks link in email
   - If new user: Creates account, sets password, joins team
   - If existing user: Automatically added to team and logged in
   - Invitation is marked as accepted
   - User slot is **consumed**

### Alternative: Manual User Creation

**Via Artisan Command (for super admins):**
```bash
php artisan user:assign-to-tenant user@example.com --tenant=1 --role=admin
```

## CRUD Implementation Status

### ✅ User CRUD - FULLY IMPLEMENTED

**Create (Invite):**
- ✅ `TeamManagement::inviteUser()` - Creates invitation
- ✅ `InvitationController::accept()` - Creates user account
- ✅ Email notification sent

**Read (View):**
- ✅ `TeamManagement` component displays all team members
- ✅ Search functionality
- ✅ Pagination support
- ✅ Shows roles, join dates, email addresses

**Update:**
- ✅ `TeamManagement::updateUser()` - Updates name and role
- ✅ Modal-based edit form
- ✅ Role can be changed
- ✅ Name can be updated

**Delete (Remove):**
- ✅ `TeamManagement::removeUser()` - Removes user from tenant
- ✅ `TenantService::removeUserFromTenant()` - Detaches user
- ✅ User slot is freed up

### ✅ Invitation CRUD - FULLY IMPLEMENTED

**Create:**
- ✅ `UserInvitation::createInvitation()` - Static factory method
- ✅ `TeamManagement::inviteUser()` - Creates invitation

**Read:**
- ✅ `TeamManagement::pendingInvitations` - Shows pending invitations
- ✅ `InvitationController::showAcceptForm()` - Displays acceptance form

**Update:**
- ✅ `resendInvitation()` - Resends invitation email
- ✅ Invitation can be accepted (updates `accepted_at`)

**Delete:**
- ✅ `cancelInvitation()` - Deletes invitation

### ⚠️ Role/Permission CRUD - PARTIALLY IMPLEMENTED

**Read:**
- ✅ Roles exist in database via `RolePermissionSeeder`
- ✅ Permissions exist in database
- ✅ `RoleManager` component displays roles (basic)
- ✅ `HasTenantRoles` trait provides role/permission checks

**Create/Update/Delete:**
- ⚠️ `RoleManager` component exists but seems basic (needs review)
- ⚠️ No visible UI for creating custom roles
- ⚠️ No visible UI for managing permissions per role
- ✅ Roles can be assigned to users via `assignTenantRole()`
- ✅ Permissions can be assigned via `givePermissionTo()`

**Current Roles:**
- `owner` - Full tenant access
- `admin` - Nearly full access
- `member` - Standard access
- `guest` - Read-only access

**Recommendation:**
Consider enhancing `RoleManager` component to allow:
- Creating custom roles
- Assigning permissions to roles
- Managing permissions per role
- UI for role/permission CRUD

## Where and How Users Are Managed

### Primary Location: Settings → Team

**Features Available:**
- View all team members
- Invite new users
- Edit user roles
- Remove users
- View pending invitations
- Resend/cancel invitations
- Search team members
- See available user slots

### Access Control

**Who Can Manage Users:**
- **Owner**: Full access to manage team
- **Admin**: Can invite and manage users
- **Member**: Cannot manage team (403 error)
- **Guest**: Cannot manage team (403 error)

**Permission Check:**
```php
// In TeamManagement::mount()
$role = $user->getTenantRole($tenant);
if (!in_array($role, ['owner', 'admin'])) {
    abort(403, 'You do not have permission to manage team members.');
}
```

### Super Admin Panel: `/admin`

**Super Admins can:**
- View all users across all tenants
- View all tenants
- Manage resellers
- Set super admin status
- Impersonate tenants for support

**Location**: `https://dashboard.swellsystem.com/admin`

## Role Assignment and Permission System

### How Roles Work

**Role Assignment:**
1. **During Invitation**: Role is selected when inviting user
2. **After Invitation**: Role is stored in `tenant_user` pivot table
3. **Via Code**: Can assign via `$user->assignTenantRole('admin')`

**Role Storage:**
- **Pivot Table**: `tenant_user.role` column stores tenant-specific role
- **Spatie Permission**: Roles can also be stored in `model_has_roles` (tenant-scoped)

**Example Roles:**
- `owner` - Tenant creator, cannot be changed
- `admin` - Full access within tenant
- `member` - Standard user access
- `guest` - Read-only access

### How Permissions Work

**Permission System:**
- Uses **Spatie Laravel Permission** with **tenant scoping**
- Permissions are tenant-scoped (via `team_id`)
- Roles have permissions attached
- Users inherit permissions through roles

**Checking Permissions:**

**In Code:**
```php
// Check permission
if (!$user->hasTenantPermission('crm.create')) {
    abort(403, 'You do not have permission.');
}

// Check role
if (!$user->hasTenantRole('admin')) {
    abort(403, 'You must be an admin.');
}
```

**In Middleware:**
```php
Route::middleware(['auth', 'permission:crm.create'])->group(function () {
    // Protected routes
});
```

**In Views:**
```blade
@can('crm.create')
    <button>Create Contact</button>
@endcan

@role('admin')
    <a href="/settings">Settings</a>
@endrole
```

### Permission Structure

**Format**: `{module}.{action}`

**Examples:**
- `crm.view` - View CRM records
- `crm.create` - Create CRM records
- `crm.edit` - Edit CRM records
- `crm.delete` - Delete CRM records
- `projects.view` - View projects
- `finance.approve` - Approve financial transactions
- `tenant.users.manage` - Manage team members
- `tenant.settings.edit` - Edit tenant settings

### Default Permissions by Role

**Owner:**
- All permissions for all modules
- Tenant management permissions

**Admin:**
- Most permissions (typically excludes billing)
- User management permissions
- Settings management

**Member:**
- View permissions for active modules
- Create/edit permissions for own records
- Limited delete permissions

**Guest:**
- View permissions only
- No create/edit/delete permissions

## Billing Impact

### User Limits

User limits are enforced based on your subscription plan:

| Plan | Included Users | User Limit | Add-On Price |
|------|---------------|------------|--------------|
| Free | 1 | 1 | N/A |
| Starter | 3 | 3 | $8/user/month |
| Professional | 10 | 10 | $6/user/month |
| Business | 25 | 25 | $4/user/month |
| Enterprise | Unlimited | Unlimited | N/A |

**During Trial:**
- Business plan limits apply (25 users)
- No billing until trial ends
- Full access during trial period

### Adding Users

**Before Limit:**
- No additional charge
- User is added immediately
- No billing impact

**At Limit:**
- Cannot invite more users
- Error message: *"Cannot invite user. Plan allows X users."*
- Options:
  1. **Purchase User Add-Ons**: Settings → Billing → Add-Ons → User Add-Ons
  2. **Upgrade Plan**: Upgrade to higher tier

**User Add-Ons:**
- Charged monthly on your billing cycle
- Prorated if purchased mid-cycle
- Add to your base user limit

**Example:**
- Professional plan (10 users)
- Purchase 5 user add-ons ($6/user = $30/month)
- Total capacity: 15 users
- Monthly charge: Base plan + $30

### Removing Users

**User Slot Freed:**
- When user is removed, their slot becomes immediately available
- Can invite new user to fill the slot
- **Note**: User add-on subscriptions are NOT automatically cancelled
  - You must manually cancel add-on if removing users permanently

**Best Practice:**
- Remove users before billing cycle ends
- Cancel user add-on subscription if removing permanently
- Prevents charges for unused add-on slots

### Billing Integration

**Automatic Checks:**
- `Tenant::canAddUser()` checks limits before adding
- Includes add-on count in calculation: `limit + addonCount`
- Throws exception if limit reached

**Add-On Purchase:**
- Go to Settings → Billing
- Click "Add-Ons" → "User Add-Ons"
- Enter quantity
- Complete Stripe checkout
- Add-ons added to `user_addons_count` field
- Limit updated immediately

## Notifications

### When Invitations Are Sent

**Email Notification:**
- `UserInvitationNotification` sent immediately
- Queued (sent in background via Laravel queues)
- Includes:
  - Invitation link (unique token, expires in 7 days)
  - Company name
  - Inviter's name
  - Assigned role
  - Expiration date

**Delivery Channels:**
- Email only (via `via()` method returning `['mail']`)

**Notification Template:**
- Subject: "You've been invited to join {Company} on SWELLEnterprise"
- Greeting: Personalized with inviter's name
- Action button: "Accept Invitation" (links to `/invitations/accept/{token}`)
- Expiration notice

### When Users Join

**Current Implementation:**
- **No automatic notifications** sent when invitation is accepted
- Business owner is NOT notified when user accepts
- Team members are NOT notified when new members join

**Optional Enhancement:**
You could add:
- `UserAddedNotification` when user accepts invitation
- `TeamMemberJoinedNotification` to notify team members
- Implement via observers or in `InvitationController::accept()`

### Notification System

**Laravel Notifications:**
- Uses Laravel's notification system
- Queued for performance
- Respects tenant SMTP settings if configured

**Channels Available:**
- Email (current)
- Database (can be enabled)
- Push notifications (if configured)

## Summary: Business Owner Workflow

### Scenario: Inviting Your Team

**As a business owner, here's the complete workflow:**

1. **Check Your Plan:**
   - Go to Settings → Billing
   - See your current plan and user limit
   - Check current user count

2. **Plan for Growth:**
   - If near limit, purchase add-ons or upgrade
   - User add-ons: $4-8/user/month (depending on plan)
   - Upgrading plan gives you more included users

3. **Invite Team Members:**
   - Go to Settings → Team
   - Click "+ Invite User"
   - Enter email, name (optional), and role
   - Click "Send Invitation"
   - User receives email immediately

4. **Assign Roles:**
   - **Owner**: Yourself (assigned during registration)
   - **Admin**: Managers who need full access
   - **Member**: Regular team members
   - **Guest**: Clients/consultants who need read-only access

5. **Manage Permissions:**
   - Roles control what users can do
   - Permissions are inherited through roles
   - Can customize permissions per role (via code or role manager)

6. **Monitor Team:**
   - View all team members in Settings → Team
   - See pending invitations
   - Edit roles as needed
   - Remove users who leave

7. **Handle Billing:**
   - When at limit, purchase add-ons or upgrade
   - User slots are freed when users are removed
   - Monitor usage vs. plan limits

### Impact on Paid Plan

**Adding Users:**
- No charge if within plan limit
- Additional charge if purchasing add-ons ($4-8/user/month)
- Upgrade plan for higher included user count

**Removing Users:**
- User slot freed immediately
- Can add new user to fill slot
- **Important**: Cancel user add-on subscription if not replacing user

**Trial Period:**
- Business plan limits apply (25 users)
- No billing until trial ends
- Full access during trial

## Access Control Examples

### Example 1: Member Can Only View CRM

**Goal**: Team member should view CRM but not create/edit.

**Setup:**
1. Invite user with "Member" role
2. Customize member role permissions:
   ```php
   $memberRole = Role::findByName('member');
   $memberRole->revokePermissionTo('crm.create');
   $memberRole->revokePermissionTo('crm.edit');
   $memberRole->givePermissionTo('crm.view');
   ```

**Result:**
- User can view contacts/companies/leads
- Cannot create, edit, or delete
- Access controlled via permissions

### Example 2: Guest for Read-Only Projects Access

**Goal**: Client can view projects but not modify.

**Setup:**
1. Invite user with "Guest" role
2. Ensure guest role has `projects.view` permission
3. Revoke all create/edit/delete permissions

**Result:**
- Guest can view projects
- Cannot create tasks or edit projects
- Read-only access enforced

### Example 3: Admin with Limited Modules

**Goal**: Manager should manage users but only access CRM.

**Setup:**
1. Invite user with "Admin" role
2. Customize admin permissions:
   ```php
   $adminRole = Role::findByName('admin');
   // Remove project/finance permissions
   $adminRole->revokePermissionTo(['projects.view', 'finance.view']);
   // Keep CRM and user management
   $adminRole->givePermissionTo(['crm.view', 'crm.create', 'crm.edit', 'tenant.users.manage']);
   ```

**Result:**
- Admin can manage users and CRM
- Cannot access projects or finance modules
- Permissions restrict module access

## CRUD Capabilities Summary

### ✅ Implemented

1. **User Invitations**: Full CRUD
2. **User Management**: Full CRUD (via TeamManagement component)
3. **Role Assignment**: Can assign roles when inviting and when editing users
4. **Permission System**: Spatie Permission with tenant scoping
5. **Billing Integration**: User limits enforced, add-ons supported
6. **Notifications**: Invitation emails sent automatically

### ⚠️ Partially Implemented

1. **Role Management**: Basic RoleManager component exists but may need enhancement
2. **Permission UI**: No visible UI for managing permissions per role (can be done via code)

### Recommended Enhancements

1. **Role Manager UI**: Full CRUD interface for creating/editing roles
2. **Permission Assignment**: UI for assigning permissions to roles
3. **Join Notifications**: Notify owner/admins when users accept invitations
4. **User Activity**: Track when users were added/removed/role changed

## Next Steps

For business owners wanting to invite their team:

1. **Review Your Plan**: Check user limit in Settings → Billing
2. **Invite Team**: Go to Settings → Team → Invite User
3. **Assign Roles**: Choose appropriate roles (Member, Admin, Guest)
4. **Monitor Usage**: Track user count vs. plan limit
5. **Manage as Needed**: Edit roles or remove users as team changes

For developers wanting to enhance the system:

1. **Role Manager**: Enhance `RoleManager` component for full CRUD
2. **Permission UI**: Add UI for managing permissions per role
3. **Notifications**: Add join notifications
4. **Activity Log**: Track user management actions

---

**For more information:**
- [Team Management](https://help.swellsystem.com/en/article/team-management-1x692m2/)
- [Billing & Subscriptions](https://help.swellsystem.com/en/article/billing-subscriptions-1qwalvv/)
- [User Invitations & Roles](https://help.swellsystem.com/en/article/user-invitations-roles-permissions-guide-1k9k848/)
