File size: 37,037 Bytes
dad7dc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
# User Invitation System - Complete Implementation Guide

**Version:** 2.0  
**Last Updated:** November 18, 2025  
**Backend Status:** βœ… Fully Implemented  
**Frontend Status:** πŸ“ Ready for Implementation  

---

## Table of Contents

1. [Overview](#overview)
2. [Complete Workflow](#complete-workflow)
3. [API Endpoints Reference](#api-endpoints-reference)
4. [Frontend Implementation](#frontend-implementation)
5. [Token Expiry & Resend Logic](#token-expiry--resend-logic)
6. [Error Handling](#error-handling)
7. [Security & Validation](#security--validation)

---

## Overview

### System Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Admin Creates  β”‚
β”‚   Invitation    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
         β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Backend Sends  │─────▢│ WhatsApp/Email   β”‚
β”‚  Notification   β”‚      β”‚ with Invite Link β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                  β”‚
                                  β–Ό
                         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                         β”‚  User Clicks    β”‚
                         β”‚     Link        β”‚
                         β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                  β”‚
                                  β–Ό
                         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                         β”‚  Frontend       β”‚
                         β”‚  Validates      β”‚
                         β”‚  Token          β”‚
                         β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                  β”‚
                                  β–Ό
                         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                         β”‚  User Fills     β”‚
                         β”‚  Registration   β”‚
                         β”‚  Form           β”‚
                         β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                  β”‚
                                  β–Ό
                         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                         β”‚  Account        β”‚
                         β”‚  Created &      β”‚
                         β”‚  Auto Login     β”‚
                         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

### Key Features

βœ… **Smart Token Management** - Expired tokens auto-regenerate on resend  
βœ… **Dual Notification** - WhatsApp primary, Email fallback  
βœ… **One-Time Use** - Tokens can't be reused after acceptance  
βœ… **Auto Login** - Users logged in immediately after signup  
βœ… **Role-Based** - Pre-assigned role and organization  
βœ… **72-Hour Expiry** - Tokens valid for 3 days (regenerate on resend)  

---

## Complete Workflow

### Phase 1: Admin Creates Invitation

**Endpoint:** `POST /api/v1/invitations`

```javascript
const response = await fetch('/api/v1/invitations', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${adminToken}`,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    email: "john.doe@example.com",
    phone: "+254712345678",
    invited_role: "field_agent",
    contractor_id: "uuid-of-contractor",
    invitation_method: "whatsapp" // or "email" or "both"
  })
});

// Response
{
  "id": "uuid",
  "email": "john.doe@example.com",
  "phone": "+254712345678",
  "invited_role": "field_agent",
  "status": "pending",
  "invited_at": "2025-11-18T10:00:00Z",
  "expires_at": "2025-11-21T10:00:00Z",
  "whatsapp_sent": true,
  "email_sent": false,
  "organization_name": "ABC Contractors"
}
```

### Phase 2: User Receives Notification

**WhatsApp/Email contains:**
```
πŸŽ‰ You're invited to join SwiftOps!

ABC Contractors has invited you to join as a Field Agent.

Click here to accept: https://swiftops.atomio.tech/accept-invitation?token=ABC123XYZ

This link expires in 72 hours.
```

### Phase 3: User Clicks Link

**Frontend Route:** `/accept-invitation?token=ABC123XYZ`

```javascript
// Extract token from URL
const searchParams = new URLSearchParams(window.location.search);
const token = searchParams.get('token');

if (!token) {
  // Show error: "Invalid invitation link"
}
```

### Phase 4: Validate Token

**Endpoint:** `POST /api/v1/invitations/validate` (PUBLIC - No Auth)

```javascript
const response = await fetch('/api/v1/invitations/validate', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ token })
});

if (response.ok) {
  const invitation = await response.json();
  // Show registration form with pre-filled data
} else {
  // Show error message
}
```

**Response:**
```json
{
  "id": "uuid",
  "email": "john.doe@example.com",
  "invited_role": "field_agent",
  "status": "pending",
  "expires_at": "2025-11-21T10:00:00Z",
  "organization_name": "ABC Contractors",
  "organization_type": "contractor",
  "is_expired": false,
  "is_valid": true
}
```

### Phase 5: User Completes Registration

**Endpoint:** `POST /api/v1/invitations/accept` (PUBLIC - No Auth)

```javascript
const response = await fetch('/api/v1/invitations/accept', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
    token: "ABC123XYZ",
    first_name: "John",
    last_name: "Doe",
    password: "SecurePass123!",
    phone: "+254712345678" // Optional
  })
});

const data = await response.json();

// Store token and redirect
localStorage.setItem('access_token', data.access_token);
window.location.href = '/dashboard';
```

**Response:**
```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "user": {
    "id": "uuid",
    "email": "john.doe@example.com",
    "first_name": "John",
    "last_name": "Doe",
    "full_name": "John Doe",
    "role": "field_agent",
    "is_active": true
  }
}
```

---

## API Endpoints Reference

### 1. Create Invitation

**POST** `/api/v1/invitations`

**Authorization:** Required (`platform_admin`, `client_admin`, `contractor_admin`)

**Request Body:**
```json
{
  "email": "user@example.com",
  "phone": "+254712345678",
  "invited_role": "field_agent",
  "client_id": "uuid",           // For client roles
  "contractor_id": "uuid",       // For contractor roles
  "invitation_method": "whatsapp" // "whatsapp", "email", "both"
}
```

**Response:** `201 Created`
```json
{
  "id": "uuid",
  "email": "user@example.com",
  "phone": "+254712345678",
  "invited_role": "field_agent",
  "status": "pending",
  "invited_at": "2025-11-18T10:00:00Z",
  "expires_at": "2025-11-21T10:00:00Z",
  "whatsapp_sent": true,
  "email_sent": false,
  "organization_name": "ABC Contractors"
}
```

**Authorization Rules:**
- `platform_admin` - Can invite to any organization
- `client_admin` - Can invite to their client only
- `contractor_admin` - Can invite to their contractor only

---

### 2. List Invitations

**GET** `/api/v1/invitations?page=1&per_page=20&status=pending`

**Authorization:** Required (`invite_users` permission)

**Query Parameters:**
- `page` - Page number (default: 1)
- `per_page` - Items per page (default: 20)
- `status` - Filter by status: `pending`, `accepted`, `expired`, `cancelled`

**Response:** `200 OK`
```json
{
  "items": [
    {
      "id": "uuid",
      "email": "user@example.com",
      "invited_role": "field_agent",
      "status": "pending",
      "invited_at": "2025-11-18T10:00:00Z",
      "expires_at": "2025-11-21T10:00:00Z",
      "organization_name": "ABC Contractors"
    }
  ],
  "total": 50,
  "page": 1,
  "per_page": 20,
  "pages": 3
}
```

---

### 3. Get Invitation Details

**GET** `/api/v1/invitations/{invitation_id}`

**Authorization:** Required (`invite_users` permission)

**Response:** `200 OK`
```json
{
  "id": "uuid",
  "email": "user@example.com",
  "phone": "+254712345678",
  "invited_role": "field_agent",
  "status": "pending",
  "invited_at": "2025-11-18T10:00:00Z",
  "expires_at": "2025-11-21T10:00:00Z",
  "accepted_at": null,
  "whatsapp_sent": true,
  "whatsapp_sent_at": "2025-11-18T10:00:05Z",
  "email_sent": false,
  "organization_name": "ABC Contractors"
}
```

---

### 4. Resend Invitation

**POST** `/api/v1/invitations/{invitation_id}/resend`

**Authorization:** Required (`invite_users` permission)

**Request Body:**
```json
{
  "invitation_method": "email" // Optional: Override delivery method
}
```

**Response:** `200 OK`
```json
{
  "id": "uuid",
  "email": "user@example.com",
  "status": "pending",
  "expires_at": "2025-11-21T16:00:00Z", // Extended if was expired
  "whatsapp_sent": false,
  "email_sent": true
}
```

**Behavior:**
- βœ… If **not expired**: Resends with same token
- βœ… If **expired**: Generates NEW token + extends expiry by 72 hours + resends
- ❌ Cannot resend if status is `accepted` or `cancelled`

---

### 5. Cancel Invitation

**DELETE** `/api/v1/invitations/{invitation_id}`

**Authorization:** Required (`invite_users` permission)

**Response:** `204 No Content`

**Behavior:**
- Sets status to `cancelled`
- User can no longer use the token
- Invitation record remains in database for audit trail

---

### 6. Validate Token (PUBLIC)

**POST** `/api/v1/invitations/validate`

**Authorization:** None (Public endpoint)

**Request Body:**
```json
{
  "token": "ABC123XYZ"
}
```

**Response:** `200 OK`
```json
{
  "id": "uuid",
  "email": "john.doe@example.com",
  "invited_role": "field_agent",
  "status": "pending",
  "expires_at": "2025-11-21T10:00:00Z",
  "organization_name": "ABC Contractors",
  "organization_type": "contractor",
  "is_expired": false,
  "is_valid": true
}
```

**Use Case:**
- Call this when user lands on `/accept-invitation?token=...`
- Pre-fill email in registration form
- Show organization name and role
- Catch invalid/expired tokens early

---

### 7. Accept Invitation (PUBLIC)

**POST** `/api/v1/invitations/accept`

**Authorization:** None (Public endpoint)

**Request Body:**
```json
{
  "token": "ABC123XYZ",
  "first_name": "John",
  "last_name": "Doe",
  "password": "SecurePass123!",
  "phone": "+254712345678"  // Optional
}
```

**Password Requirements:**
- Minimum 8 characters
- At least 1 uppercase letter
- At least 1 digit

**Phone Requirements:**
- Must start with `+` and country code
- Example: `+254712345678`

**Response:** `200 OK`
```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "bearer",
  "user": {
    "id": "uuid",
    "email": "john.doe@example.com",
    "first_name": "John",
    "last_name": "Doe",
    "full_name": "John Doe",
    "role": "field_agent",
    "is_active": true
  }
}
```

**What Happens:**
1. βœ… Validates token (not expired, still pending)
2. βœ… Checks if user already exists (prevents duplicates)
3. βœ… Creates Supabase Auth user
4. βœ… Creates local user profile with role and organization
5. βœ… Marks invitation as `accepted`
6. βœ… Returns authentication token
7. βœ… User is logged in immediately

---

## Frontend Implementation

### Component Structure

```
src/
β”œβ”€β”€ pages/
β”‚   β”œβ”€β”€ AcceptInvitationPage.jsx    # Main invitation acceptance page
β”‚   └── InvitationExpiredPage.jsx   # Show when token expired
β”œβ”€β”€ components/
β”‚   β”œβ”€β”€ InvitationValidation.jsx    # Token validation logic
β”‚   └── RegistrationForm.jsx        # User signup form
└── services/
    └── invitationService.js        # API calls
```

---

### AcceptInvitationPage.jsx

```javascript
import React, { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { validateInvitation, acceptInvitation } from '@/services/invitationService';
import RegistrationForm from '@/components/RegistrationForm';

export default function AcceptInvitationPage() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const token = searchParams.get('token');
  
  const [loading, setLoading] = useState(true);
  const [invitation, setInvitation] = useState(null);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    if (!token) {
      setError('Invalid invitation link');
      setLoading(false);
      return;
    }
    
    validateToken();
  }, [token]);
  
  const validateToken = async () => {
    try {
      const data = await validateInvitation(token);
      
      if (!data.is_valid) {
        setError('This invitation is no longer valid');
        return;
      }
      
      if (data.is_expired) {
        setError('This invitation has expired. Please contact your administrator for a new invitation.');
        return;
      }
      
      setInvitation(data);
    } catch (err) {
      setError(err.message || 'Failed to validate invitation');
    } finally {
      setLoading(false);
    }
  };
  
  const handleSubmit = async (formData) => {
    try {
      const response = await acceptInvitation({
        token,
        ...formData
      });
      
      // Store auth token
      localStorage.setItem('access_token', response.access_token);
      
      // Store user info
      localStorage.setItem('user', JSON.stringify(response.user));
      
      // Redirect to dashboard
      navigate('/dashboard');
      
      // Optional: Show success message
      // toast.success('Account created successfully!');
    } catch (err) {
      throw err; // Let form handle error display
    }
  };
  
  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="spinner" />
          <p className="mt-4">Validating invitation...</p>
        </div>
      </div>
    );
  }
  
  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center max-w-md p-8 bg-red-50 rounded-lg">
          <h2 className="text-2xl font-bold text-red-800 mb-4">
            Invitation Error
          </h2>
          <p className="text-red-600">{error}</p>
          <button 
            onClick={() => navigate('/login')}
            className="mt-6 btn-primary"
          >
            Go to Login
          </button>
        </div>
      </div>
    );
  }
  
  return (
    <div className="min-h-screen bg-gray-50 py-12">
      <div className="max-w-md mx-auto">
        {/* Welcome Header */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold mb-2">Welcome to SwiftOps!</h1>
          <p className="text-gray-600">
            You've been invited to join <strong>{invitation.organization_name}</strong>
          </p>
          <p className="text-sm text-gray-500 mt-2">
            Role: <span className="font-semibold capitalize">
              {invitation.invited_role.replace('_', ' ')}
            </span>
          </p>
        </div>
        
        {/* Registration Form */}
        <RegistrationForm 
          email={invitation.email}
          onSubmit={handleSubmit}
        />
      </div>
    </div>
  );
}
```

---

### RegistrationForm.jsx

```javascript
import React, { useState } from 'react';

export default function RegistrationForm({ email, onSubmit }) {
  const [formData, setFormData] = useState({
    first_name: '',
    last_name: '',
    password: '',
    confirmPassword: '',
    phone: ''
  });
  
  const [errors, setErrors] = useState({});
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  
  const validatePassword = (password) => {
    const errors = [];
    if (password.length < 8) errors.push('At least 8 characters');
    if (!/[A-Z]/.test(password)) errors.push('One uppercase letter');
    if (!/[0-9]/.test(password)) errors.push('One number');
    return errors;
  };
  
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // Clear error for this field
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: null }));
    }
  };
  
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // Validation
    const newErrors = {};
    
    if (!formData.first_name.trim()) {
      newErrors.first_name = 'First name is required';
    }
    
    if (!formData.last_name.trim()) {
      newErrors.last_name = 'Last name is required';
    }
    
    const passwordErrors = validatePassword(formData.password);
    if (passwordErrors.length > 0) {
      newErrors.password = 'Password must contain: ' + passwordErrors.join(', ');
    }
    
    if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = 'Passwords do not match';
    }
    
    if (formData.phone && !formData.phone.startsWith('+')) {
      newErrors.phone = 'Phone must start with + and country code';
    }
    
    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }
    
    setLoading(true);
    
    try {
      await onSubmit({
        first_name: formData.first_name,
        last_name: formData.last_name,
        password: formData.password,
        phone: formData.phone || undefined
      });
    } catch (err) {
      setErrors({ 
        submit: err.response?.data?.detail || 'Failed to create account' 
      });
    } finally {
      setLoading(false);
    }
  };
  
  const passwordStrength = validatePassword(formData.password);
  
  return (
    <form onSubmit={handleSubmit} className="bg-white p-8 rounded-lg shadow-md">
      {/* Email (read-only) */}
      <div className="mb-4">
        <label className="block text-sm font-medium mb-2">Email</label>
        <input
          type="email"
          value={email}
          disabled
          className="w-full px-4 py-2 border rounded-lg bg-gray-100"
        />
      </div>
      
      {/* First Name */}
      <div className="mb-4">
        <label className="block text-sm font-medium mb-2">
          First Name <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          name="first_name"
          value={formData.first_name}
          onChange={handleChange}
          className="w-full px-4 py-2 border rounded-lg"
          required
        />
        {errors.first_name && (
          <p className="text-red-500 text-sm mt-1">{errors.first_name}</p>
        )}
      </div>
      
      {/* Last Name */}
      <div className="mb-4">
        <label className="block text-sm font-medium mb-2">
          Last Name <span className="text-red-500">*</span>
        </label>
        <input
          type="text"
          name="last_name"
          value={formData.last_name}
          onChange={handleChange}
          className="w-full px-4 py-2 border rounded-lg"
          required
        />
        {errors.last_name && (
          <p className="text-red-500 text-sm mt-1">{errors.last_name}</p>
        )}
      </div>
      
      {/* Password */}
      <div className="mb-4">
        <label className="block text-sm font-medium mb-2">
          Password <span className="text-red-500">*</span>
        </label>
        <div className="relative">
          <input
            type={showPassword ? "text" : "password"}
            name="password"
            value={formData.password}
            onChange={handleChange}
            className="w-full px-4 py-2 border rounded-lg"
            required
          />
          <button
            type="button"
            onClick={() => setShowPassword(!showPassword)}
            className="absolute right-3 top-2.5 text-gray-500"
          >
            {showPassword ? 'Hide' : 'Show'}
          </button>
        </div>
        
        {/* Password Requirements */}
        {formData.password && (
          <div className="mt-2 text-sm">
            <p className={passwordStrength.length === 0 ? 'text-green-600' : 'text-gray-600'}>
              Password must contain:
            </p>
            <ul className="list-disc list-inside text-xs mt-1">
              <li className={formData.password.length >= 8 ? 'text-green-600' : 'text-gray-500'}>
                At least 8 characters
              </li>
              <li className={/[A-Z]/.test(formData.password) ? 'text-green-600' : 'text-gray-500'}>
                One uppercase letter
              </li>
              <li className={/[0-9]/.test(formData.password) ? 'text-green-600' : 'text-gray-500'}>
                One number
              </li>
            </ul>
          </div>
        )}
        
        {errors.password && (
          <p className="text-red-500 text-sm mt-1">{errors.password}</p>
        )}
      </div>
      
      {/* Confirm Password */}
      <div className="mb-4">
        <label className="block text-sm font-medium mb-2">
          Confirm Password <span className="text-red-500">*</span>
        </label>
        <input
          type={showPassword ? "text" : "password"}
          name="confirmPassword"
          value={formData.confirmPassword}
          onChange={handleChange}
          className="w-full px-4 py-2 border rounded-lg"
          required
        />
        {errors.confirmPassword && (
          <p className="text-red-500 text-sm mt-1">{errors.confirmPassword}</p>
        )}
      </div>
      
      {/* Phone (Optional) */}
      <div className="mb-6">
        <label className="block text-sm font-medium mb-2">
          Phone Number (Optional)
        </label>
        <input
          type="tel"
          name="phone"
          value={formData.phone}
          onChange={handleChange}
          placeholder="+254712345678"
          className="w-full px-4 py-2 border rounded-lg"
        />
        <p className="text-xs text-gray-500 mt-1">
          Include country code (e.g., +254 for Kenya)
        </p>
        {errors.phone && (
          <p className="text-red-500 text-sm mt-1">{errors.phone}</p>
        )}
      </div>
      
      {/* Submit Error */}
      {errors.submit && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg">
          <p className="text-red-600 text-sm">{errors.submit}</p>
        </div>
      )}
      
      {/* Submit Button */}
      <button
        type="submit"
        disabled={loading}
        className="w-full bg-blue-600 text-white py-3 rounded-lg font-semibold hover:bg-blue-700 disabled:bg-gray-400"
      >
        {loading ? 'Creating Account...' : 'Create Account'}
      </button>
      
      {/* Terms */}
      <p className="text-xs text-gray-500 text-center mt-4">
        By creating an account, you agree to our Terms of Service and Privacy Policy.
      </p>
    </form>
  );
}
```

---

### invitationService.js

```javascript
const API_BASE = process.env.REACT_APP_API_URL || 'http://localhost:8000/api/v1';

export const validateInvitation = async (token) => {
  const response = await fetch(`${API_BASE}/invitations/validate`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ token })
  });
  
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.detail || 'Failed to validate invitation');
  }
  
  return response.json();
};

export const acceptInvitation = async (data) => {
  const response = await fetch(`${API_BASE}/invitations/accept`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data)
  });
  
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.detail || 'Failed to accept invitation');
  }
  
  return response.json();
};

export const createInvitation = async (token, data) => {
  const response = await fetch(`${API_BASE}/invitations`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  });
  
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.detail || 'Failed to create invitation');
  }
  
  return response.json();
};

export const listInvitations = async (token, params = {}) => {
  const queryString = new URLSearchParams(params).toString();
  const response = await fetch(`${API_BASE}/invitations?${queryString}`, {
    headers: { 'Authorization': `Bearer ${token}` }
  });
  
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.detail || 'Failed to fetch invitations');
  }
  
  return response.json();
};

export const resendInvitation = async (token, invitationId, method = null) => {
  const response = await fetch(`${API_BASE}/invitations/${invitationId}/resend`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ invitation_method: method })
  });
  
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.detail || 'Failed to resend invitation');
  }
  
  return response.json();
};

export const cancelInvitation = async (token, invitationId) => {
  const response = await fetch(`${API_BASE}/invitations/${invitationId}`, {
    method: 'DELETE',
    headers: { 'Authorization': `Bearer ${token}` }
  });
  
  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.detail || 'Failed to cancel invitation');
  }
  
  return true;
};
```

---

### Router Configuration

```javascript
// In your main router file (App.jsx or routes.jsx)
import AcceptInvitationPage from '@/pages/AcceptInvitationPage';

<Routes>
  {/* Public Route */}
  <Route path="/accept-invitation" element={<AcceptInvitationPage />} />
  
  {/* Other routes */}
  <Route path="/login" element={<LoginPage />} />
  <Route path="/dashboard" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
  {/* ... */}
</Routes>
```

---

## Token Expiry & Resend Logic

### Token Lifecycle

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Token Created  β”‚
β”‚  Expires: +72h  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
         β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Status: Pending│◄───── User can accept
β”‚  Not Expired    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚
         β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
         β”‚             β”‚
         β–Ό             β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Accepted   β”‚  β”‚  Expired    β”‚
β”‚  (Used)     β”‚  β”‚  (72h past) β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
                        β”‚
                        β–Ό
                 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                 β”‚   Resend    β”‚
                 β”‚   Clicked   β”‚
                 β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
                        β”‚
                        β–Ό
                 β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                 β”‚  New Token      β”‚
                 β”‚  Generated      β”‚
                 β”‚  Expires: +72h  β”‚
                 β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

### Resend Behavior

**Scenario 1: Not Expired**
```javascript
// Day 1: Invitation sent, expires Day 4
// Day 2: Admin clicks "Resend"

β†’ Same token sent again
β†’ Expiry unchanged (still Day 4)
β†’ Notification resent via WhatsApp/Email
```

**Scenario 2: Expired**
```javascript
// Day 1: Invitation sent, expires Day 4
// Day 5: Token expired, Admin clicks "Resend"

β†’ NEW token generated
β†’ Expiry set to Day 8 (72 hours from now)
β†’ Notification sent with new link
β†’ Old token no longer works
```

### Admin Dashboard Implementation

```javascript
// InvitationsList.jsx
function InvitationRow({ invitation, onResend }) {
  const isExpired = new Date(invitation.expires_at) < new Date();
  
  return (
    <tr>
      <td>{invitation.email}</td>
      <td>
        <span className={`badge ${
          invitation.status === 'pending' ? 'badge-warning' :
          invitation.status === 'accepted' ? 'badge-success' :
          'badge-gray'
        }`}>
          {invitation.status}
        </span>
        {isExpired && invitation.status === 'pending' && (
          <span className="badge badge-danger ml-2">Expired</span>
        )}
      </td>
      <td>{invitation.invited_role}</td>
      <td>{new Date(invitation.expires_at).toLocaleDateString()}</td>
      <td>
        {invitation.status === 'pending' && (
          <button 
            onClick={() => onResend(invitation.id)}
            className="btn-sm btn-primary"
          >
            {isExpired ? 'Resend (New Token)' : 'Resend'}
          </button>
        )}
      </td>
    </tr>
  );
}
```

---

## Error Handling

### Common Error Scenarios

#### 1. Invalid Token
```json
// Response: 400 Bad Request
{
  "detail": "Invalid or expired invitation token"
}
```

**Frontend Handling:**
```javascript
if (error.detail.includes('Invalid')) {
  setError('This invitation link is invalid. Please check your link or contact support.');
}
```

---

#### 2. Token Expired
```json
// Response: 400 Bad Request
{
  "detail": "Invalid or expired invitation token"
}
```

**Frontend Handling:**
```javascript
if (invitation.is_expired) {
  setError('This invitation has expired. Please contact your administrator for a new invitation.');
}
```

---

#### 3. User Already Exists
```json
// Response: 400 Bad Request
{
  "detail": "User already exists"
}
```

**Frontend Handling:**
```javascript
if (error.detail.includes('already exists')) {
  setError('An account with this email already exists. Try logging in instead.');
  // Show "Go to Login" button
}
```

---

#### 4. Password Too Weak
```json
// Response: 422 Unprocessable Entity
{
  "detail": [
    {
      "loc": ["body", "password"],
      "msg": "Password must contain at least one uppercase letter",
      "type": "value_error"
    }
  ]
}
```

**Frontend Handling:**
```javascript
// Show inline validation before submit
const passwordErrors = validatePassword(password);
if (passwordErrors.length > 0) {
  setError('Password must contain: ' + passwordErrors.join(', '));
}
```

---

#### 5. Already Accepted
```json
// Response: 404 Not Found
{
  "detail": "Invitation not found or already processed"
}
```

**Frontend Handling:**
```javascript
if (error.detail.includes('already processed')) {
  setError('This invitation has already been used. Try logging in instead.');
}
```

---

#### 6. Network Error
```javascript
try {
  await acceptInvitation(data);
} catch (err) {
  if (err.message.includes('Failed to fetch')) {
    setError('Connection failed. Please check your internet and try again.');
  }
}
```

---

### Error Display Component

```javascript
function ErrorMessage({ error, onRetry, onGoToLogin }) {
  if (!error) return null;
  
  const isUserExists = error.includes('already exists');
  const isExpired = error.includes('expired');
  
  return (
    <div className="p-4 bg-red-50 border border-red-200 rounded-lg">
      <h3 className="text-red-800 font-semibold mb-2">Error</h3>
      <p className="text-red-600 mb-4">{error}</p>
      
      <div className="flex gap-2">
        {isUserExists && (
          <button onClick={onGoToLogin} className="btn-primary">
            Go to Login
          </button>
        )}
        {isExpired && (
          <p className="text-sm text-red-600">
            Contact your administrator for a new invitation.
          </p>
        )}
        {!isUserExists && !isExpired && onRetry && (
          <button onClick={onRetry} className="btn-secondary">
            Try Again
          </button>
        )}
      </div>
    </div>
  );
}
```

---

## Security & Validation

### Backend Validation

βœ… **Token Security**
- 32-byte cryptographically secure random tokens
- Unique constraint in database
- Single-use (marked as accepted after use)
- Time-limited (72-hour expiry)

βœ… **Password Requirements**
- Minimum 8 characters
- At least 1 uppercase letter
- At least 1 digit
- No maximum length (within reason)

βœ… **Email Validation**
- Valid email format
- Must match invitation email
- Cannot be changed by user

βœ… **Phone Validation**
- Optional field
- Must start with `+` and country code
- Example: `+254712345678`

βœ… **Authorization**
- Only admins with `invite_users` permission
- Row-level security on invitations (org-based)
- Cannot invite to other organizations

### Frontend Validation

```javascript
// Validate before submit
const validate = (formData) => {
  const errors = {};
  
  // Required fields
  if (!formData.first_name.trim()) {
    errors.first_name = 'First name is required';
  }
  
  if (!formData.last_name.trim()) {
    errors.last_name = 'Last name is required';
  }
  
  // Password strength
  if (formData.password.length < 8) {
    errors.password = 'Password must be at least 8 characters';
  }
  if (!/[A-Z]/.test(formData.password)) {
    errors.password = 'Password must contain an uppercase letter';
  }
  if (!/[0-9]/.test(formData.password)) {
    errors.password = 'Password must contain a number';
  }
  
  // Password match
  if (formData.password !== formData.confirmPassword) {
    errors.confirmPassword = 'Passwords do not match';
  }
  
  // Phone format
  if (formData.phone && !formData.phone.startsWith('+')) {
    errors.phone = 'Phone must start with + and country code';
  }
  
  return errors;
};
```

### Best Practices

1. **Validate token on page load** - Don't let user fill form if token is invalid
2. **Show clear error messages** - Help user understand what went wrong
3. **Pre-fill email** - User can't change it (comes from invitation)
4. **Show password requirements live** - Help user create strong password
5. **Auto-login after signup** - Store token and redirect immediately
6. **Handle network errors gracefully** - Show retry option
7. **Disable submit during processing** - Prevent duplicate submissions
8. **Show organization name** - User knows what they're joining

---

## Testing Checklist

### Backend Testing

- [ ] Create invitation with WhatsApp method
- [ ] Create invitation with Email method
- [ ] Create invitation with Both methods
- [ ] Validate valid token
- [ ] Validate expired token
- [ ] Validate invalid token
- [ ] Accept valid invitation
- [ ] Try to accept twice (should fail)
- [ ] Try to accept expired token (should fail)
- [ ] Resend non-expired invitation (same token)
- [ ] Resend expired invitation (new token generated)
- [ ] Cancel invitation
- [ ] Try to accept cancelled invitation (should fail)

### Frontend Testing

- [ ] Land on `/accept-invitation` without token (show error)
- [ ] Land on page with invalid token (show error)
- [ ] Land on page with expired token (show error)
- [ ] Land on page with valid token (show form)
- [ ] Submit form with empty fields (show validation errors)
- [ ] Submit form with weak password (show validation errors)
- [ ] Submit form with mismatched passwords (show validation errors)
- [ ] Submit form with invalid phone format (show validation errors)
- [ ] Submit form with valid data (create account & redirect)
- [ ] Try to accept same invitation twice (show error)
- [ ] Handle network errors gracefully

---

## Environment Variables

```env
# Backend (.env)
APP_DOMAIN=swiftops.atomio.tech
APP_PROTOCOL=https
INVITATION_TOKEN_EXPIRY_HOURS=72

# Notification Services
RESEND_API_KEY=re_xxxxxxxxxxxxx
RESEND_FROM_EMAIL=swiftops@atomio.tech
WASENDER_API_KEY=xxxxxxxxxxxxx

# Supabase
SUPABASE_URL=https://xxx.supabase.co
SUPABASE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```

```env
# Frontend (.env)
REACT_APP_API_URL=https://api.swiftops.atomio.tech/api/v1
```

---

## Quick Reference

### Key URLs
- Invitation Link: `https://swiftops.atomio.tech/accept-invitation?token=ABC123XYZ`
- API Base: `https://api.swiftops.atomio.tech/api/v1`

### Key Timings
- Token Expiry: 72 hours (3 days)
- Token Regeneration: On resend if expired
- Auto Login: Immediate after account creation

### Key Status Values
- `pending` - Invitation sent, not yet accepted
- `accepted` - User created account
- `expired` - 72 hours passed (can be resent with new token)
- `cancelled` - Admin cancelled invitation

### Key Roles
- `platform_admin` - System administrator
- `client_admin` - Client organization admin
- `contractor_admin` - Contractor organization admin
- `project_manager` - Project manager
- `dispatcher` - Dispatcher
- `sales_manager` - Sales manager
- `field_agent` - Field worker
- `sales_agent` - Sales representative

---

**Last Updated:** November 18, 2025  
**Questions?** Check the API responses or backend logs for detailed error messages.