File size: 12,073 Bytes
dce1329
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
# User Invitation System - Implementation Plan

## Overview
Implement a secure user invitation system that allows platform admins to invite users to organizations (clients/contractors) via WhatsApp (primary) or Email (fallback). Users are created in Supabase Auth ONLY after accepting the invitation.

---

## 1. Database Schema Changes

### Important Note on User Status
The existing `user_status` enum (`invited`, `pending_setup`, `active`, `suspended`) is **KEPT**.
- `user_invitations` table tracks PRE-acceptance state (before user exists)
- `users.status` tracks POST-acceptance state (after user is created)
- Flow: Invitation sent β†’ User accepts β†’ User created with status `active` β†’ User can be `suspended` later

### New Table: `user_invitations`

```sql
CREATE TYPE invitation_status AS ENUM (
    'pending',
    'accepted',
    'expired',
    'cancelled'
);

CREATE TYPE invitation_method AS ENUM (
    'whatsapp',
    'email',
    'both'
);

CREATE TABLE user_invitations (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    
    -- Invitation Details
    email TEXT NOT NULL,
    phone TEXT,
    invited_role app_role NOT NULL,
    
    -- Organization Link (one must be set based on role)
    client_id UUID REFERENCES clients(id) ON DELETE CASCADE,
    contractor_id UUID REFERENCES contractors(id) ON DELETE CASCADE,
    
    -- Invitation Token & Status
    token TEXT NOT NULL UNIQUE,
    status invitation_status DEFAULT 'pending',
    invitation_method invitation_method DEFAULT 'whatsapp',
    
    -- Lifecycle
    invited_by_user_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
    invited_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()),
    expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
    accepted_at TIMESTAMP WITH TIME ZONE,
    
    -- Delivery Tracking
    whatsapp_sent BOOLEAN DEFAULT FALSE,
    whatsapp_sent_at TIMESTAMP WITH TIME ZONE,
    email_sent BOOLEAN DEFAULT FALSE,
    email_sent_at TIMESTAMP WITH TIME ZONE,
    
    -- Metadata
    invitation_metadata JSONB DEFAULT '{}',
    created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()),
    updated_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now()),
    
    -- Constraints
    CONSTRAINT chk_invitation_org_link CHECK (
        (client_id IS NOT NULL AND contractor_id IS NULL) OR
        (client_id IS NULL AND contractor_id IS NOT NULL) OR
        (invited_role = 'platform_admin' AND client_id IS NULL AND contractor_id IS NULL)
    ),
    CONSTRAINT chk_invitation_contact CHECK (
        email IS NOT NULL OR phone IS NOT NULL
    )
);

-- Indexes
CREATE INDEX idx_invitations_token ON user_invitations(token) WHERE status = 'pending';
CREATE INDEX idx_invitations_email ON user_invitations(email, status);
CREATE INDEX idx_invitations_status ON user_invitations(status, expires_at);
CREATE INDEX idx_invitations_client ON user_invitations(client_id) WHERE client_id IS NOT NULL;
CREATE INDEX idx_invitations_contractor ON user_invitations(contractor_id) WHERE contractor_id IS NOT NULL;

-- Prevent duplicate pending invitations
CREATE UNIQUE INDEX idx_invitations_unique_pending ON user_invitations(email, client_id, contractor_id) 
WHERE status = 'pending';

COMMENT ON TABLE user_invitations IS 'Tracks user invitations before Supabase Auth account creation';
```

---

## 2. Environment Variables

Add to `.env`:

```env
# Base URL for invitation links
BASE_URL=https://swiftops.atomio.tech

# Invitation Configuration
INVITATION_TOKEN_EXPIRY_HOURS=72

# Notification Services (already exist)
RESEND_API_KEY=re_xxx
WASENDER_API_KEY=xxx
WASENDER_PHONE_NUMBER=+254xxx
```

---

## 3. Project Structure

```
src/app/
β”œβ”€β”€ services/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ invitation_service.py      # Core invitation logic
β”‚   β”œβ”€β”€ notification_service.py    # WhatsApp/Email delivery
β”‚   └── token_service.py           # Token generation/validation
β”œβ”€β”€ templates/
β”‚   β”œβ”€β”€ emails/
β”‚   β”‚   β”œβ”€β”€ base.html              # Base email template
β”‚   β”‚   β”œβ”€β”€ invitation.html        # User invitation email
β”‚   β”‚   └── invitation_reminder.html
β”‚   └── whatsapp/
β”‚       β”œβ”€β”€ invitation.txt         # WhatsApp invitation message
β”‚       └── invitation_reminder.txt
β”œβ”€β”€ models/
β”‚   └── invitation.py              # Invitation model
β”œβ”€β”€ schemas/
β”‚   └── invitation.py              # Invitation schemas
└── api/v1/
    └── invitations.py             # Invitation endpoints
```

---

## 4. Implementation Steps

### Step 1: Database Migration
- [ ] Create migration file for `user_invitations` table
- [ ] Add `invitation_status` and `invitation_method` enums
- [ ] Run migration

### Step 2: Models & Schemas
- [ ] Create `src/app/models/invitation.py`
- [ ] Create `src/app/schemas/invitation.py` with:
  - `InvitationCreate`
  - `InvitationResponse`
  - `InvitationAccept`
  - `InvitationValidate`

### Step 3: Core Services

#### A. Token Service (`src/app/services/token_service.py`)
- [ ] `generate_invitation_token()` - Secure random token (32 chars)
- [ ] `validate_invitation_token(token)` - Check validity & expiry
- [ ] `invalidate_token(token)` - Mark as used/expired

#### B. Notification Service (`src/app/services/notification_service.py`)
- [ ] `send_whatsapp_invitation(phone, name, invitation_url)` - WaSender integration
- [ ] `send_email_invitation(email, name, invitation_url)` - Resend integration
- [ ] `send_invitation(invitation, method)` - Smart routing (WhatsApp β†’ Email fallback)
- [ ] Template rendering with Jinja2

#### C. Invitation Service (`src/app/services/invitation_service.py`)
- [ ] `create_invitation(email, phone, role, org_id, invited_by, method)`
- [ ] `validate_invitation(token)` - Check token validity
- [ ] `accept_invitation(token, user_data)` - Create Supabase user + local profile
- [ ] `cancel_invitation(invitation_id)` - Cancel pending invitation
- [ ] `resend_invitation(invitation_id)` - Resend notification
- [ ] `cleanup_expired_invitations()` - Background job

### Step 4: Email Templates

#### `src/app/templates/emails/base.html`
- [ ] Create responsive HTML base template
- [ ] Include SwiftOps branding
- [ ] Header, footer, styling

#### `src/app/templates/emails/invitation.html`
- [ ] Personalized greeting
- [ ] Organization name
- [ ] Role information
- [ ] CTA button with invitation URL
- [ ] Expiry notice
- [ ] Support contact

### Step 5: WhatsApp Templates

#### `src/app/templates/whatsapp/invitation.txt`
```
Hi {{name}},

You've been invited to join {{organization_name}} on SwiftOps as a {{role}}.

Click here to accept: {{invitation_url}}

This invitation expires in {{expiry_hours}} hours.

Need help? Contact support@atomio.tech
```

### Step 6: API Endpoints

#### `src/app/api/v1/invitations.py`
- [ ] `POST /invitations` - Create invitation (platform_admin, client_admin, contractor_admin)
- [ ] `GET /invitations` - List invitations (filtered by org)
- [ ] `GET /invitations/{id}` - Get invitation details
- [ ] `POST /invitations/{id}/resend` - Resend invitation
- [ ] `DELETE /invitations/{id}` - Cancel invitation
- [ ] `POST /invitations/validate` - Validate token (public endpoint)
- [ ] `POST /invitations/accept` - Accept invitation & create user (public endpoint)

### Step 7: Update Existing Endpoints

#### `src/app/api/v1/clients.py`
- [ ] Add existence check in `create_client()`
- [ ] Return existing client if found (with flag `already_exists: true`)

#### `src/app/api/v1/contractors.py`
- [ ] Add existence check in `create_contractor()`
- [ ] Return existing contractor if found (with flag `already_exists: true`)

#### `src/app/api/v1/auth.py`
- [ ] Remove self-registration endpoint OR restrict to invitation-only
- [ ] Update `register()` to require invitation token
- [ ] Link new user to invitation record

### Step 8: Authorization Rules

**Who can invite whom:**
- `platform_admin` β†’ Can invite anyone to any organization
- `client_admin` β†’ Can invite users to their client organization only
- `contractor_admin` β†’ Can invite users to their contractor organization only
- Other roles β†’ Cannot invite users

**Validation:**
- Check inviter has permission for target organization
- Validate role is appropriate for organization type
- Prevent duplicate pending invitations

### Step 9: Frontend Integration Points

**Invitation Flow:**
1. User receives WhatsApp/Email with link: `https://swiftops.atomio.tech/accept-invitation?token=xxx`
2. Frontend validates token via `POST /invitations/validate`
3. Shows registration form pre-filled with email/phone
4. User completes profile (name, password)
5. Frontend submits to `POST /invitations/accept`
6. Backend creates Supabase user + local profile
7. Returns auth token
8. User is logged in

---

## 5. Security Considerations

- [ ] Tokens are cryptographically secure (secrets.token_urlsafe)
- [ ] Tokens expire after 72 hours (configurable)
- [ ] Rate limiting on invitation endpoints
- [ ] Validate email/phone format
- [ ] Prevent invitation spam (max 3 pending per email)
- [ ] Log all invitation activities
- [ ] HTTPS only for invitation URLs

---

## 6. Testing Checklist

- [ ] Unit tests for token generation/validation
- [ ] Integration tests for invitation flow
- [ ] Test WhatsApp delivery (WaSender)
- [ ] Test email delivery (Resend)
- [ ] Test fallback mechanism (WhatsApp β†’ Email)
- [ ] Test expiry handling
- [ ] Test duplicate invitation prevention
- [ ] Test authorization rules
- [ ] Test Supabase user creation on acceptance

---

## 7. Background Jobs (Future Enhancement)

- [ ] Cleanup expired invitations (daily cron)
- [ ] Send reminder for pending invitations (24h before expiry)
- [ ] Generate invitation analytics

---

## 8. API Response Examples

### Create Invitation
```json
POST /api/v1/invitations
{
  "email": "john@example.com",
  "phone": "+254712345678",
  "role": "field_agent",
  "contractor_id": "uuid",
  "invitation_method": "whatsapp"
}

Response:
{
  "id": "uuid",
  "email": "john@example.com",
  "status": "pending",
  "invitation_url": "https://swiftops.atomio.tech/accept-invitation?token=xxx",
  "expires_at": "2025-11-19T12:00:00Z",
  "whatsapp_sent": true,
  "email_sent": false
}
```

### Accept Invitation
```json
POST /api/v1/invitations/accept
{
  "token": "xxx",
  "first_name": "John",
  "last_name": "Doe",
  "password": "SecurePass123!"
}

Response:
{
  "access_token": "jwt_token",
  "token_type": "bearer",
  "user": {
    "id": "uuid",
    "email": "john@example.com",
    "full_name": "John Doe",
    "role": "field_agent",
    "contractor_id": "uuid"
  }
}
```

---

## 9. Implementation Order

1. **Phase 1: Foundation** (Day 1)
   - Database migration
   - Models & schemas
   - Token service

2. **Phase 2: Core Logic** (Day 2)
   - Invitation service
   - Notification service
   - Templates (email + WhatsApp)

3. **Phase 3: API** (Day 3)
   - Invitation endpoints
   - Update client/contractor endpoints
   - Authorization logic

4. **Phase 4: Integration** (Day 4)
   - Update auth flow
   - Frontend integration
   - Testing

5. **Phase 5: Polish** (Day 5)
   - Error handling
   - Logging
   - Documentation

---

## 10. Success Criteria

βœ… Platform admin can invite users to any organization
βœ… Org admins can invite users to their organization
βœ… Invitations sent via WhatsApp (primary) or Email (fallback)
βœ… Secure token-based invitation links
βœ… Users created in Supabase ONLY after acceptance
βœ… Duplicate invitation prevention
βœ… Expiry handling
βœ… Audit trail for all invitations
βœ… Client/contractor existence checks before creation

---

## Notes

- **WhatsApp Priority**: Default to WhatsApp to conserve Resend credits
- **Fallback Logic**: If WhatsApp fails, automatically try email
- **Token Security**: Use `secrets.token_urlsafe(32)` for tokens
- **Expiry**: 72 hours default, configurable via env
- **Email Domain**: swiftops@atomio.tech (configured in Resend)
- **Base URL**: https://swiftops.atomio.tech (from env)