File: test_sync_google2odoo.py

package info (click to toggle)
odoo 18.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 878,716 kB
  • sloc: javascript: 927,937; python: 685,670; xml: 388,524; sh: 1,033; sql: 415; makefile: 26
file content (2422 lines) | stat: -rw-r--r-- 115,461 bytes parent folder | download
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
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

import pytz
from datetime import datetime, date, timedelta

from dateutil.relativedelta import relativedelta
from odoo.tests.common import new_test_user
from odoo.exceptions import ValidationError
from odoo.addons.google_calendar.models.res_users import User
from odoo.addons.google_calendar.tests.test_sync_common import TestSyncGoogle, patch_api
from odoo.addons.google_calendar.utils.google_calendar import GoogleEvent, GoogleCalendarService
from odoo import Command, tools
from unittest.mock import patch


@patch.object(User, '_get_google_calendar_token', lambda user: 'dummy-token')
class TestSyncGoogle2Odoo(TestSyncGoogle):

    def setUp(self):
        super().setUp()
        self.other_company = self.env['res.company'].create({'name': 'Other Company'})
        self.public_partner = self.env['res.partner'].create({
            'name': 'Public Contact',
            'email': 'public_email@example.com',
            'type': 'contact',
        })
        self.env.ref('base.partner_admin').write({
            'name': 'Mitchell Admin',
            'email': 'admin@yourcompany.example.com',
        })
        self.private_partner = self.env['res.partner'].create({
            'name': 'Private Contact',
            'email': 'private_email@example.com',
            'company_id': self.other_company.id,
        })

    def generate_recurring_event(self, mock_dt, **values):
        """ Function Used to return a recurrence created at fake time of 'mock_dt'. """
        rrule = values.pop('rrule', None)
        google_id = values.pop('google_id', None)
        with self.mock_datetime_and_now(mock_dt):
            base_event = self.env['calendar.event'].with_user(self.organizer_user).create({
                'name': 'coucou',
                'need_sync': False,
                **values
            })
            recurrence = self.env['calendar.recurrence'].with_user(self.organizer_user).create({
                'google_id': google_id,
                'rrule': rrule,
                'need_sync': False,
                'base_event_id': base_event.id,
            })
            recurrence._apply_recurrence()
        return recurrence

    def google_respond_to_recurrent_event_with_option_this_event(self, recurrence, event_index, response_status):
        """
        Function returns google api response simulating 'self.attendee_user' responding to the event number 'event_index' (0-indexed)
        in 'recurrence' with response of 'response_status' and option "This event"
        """
        update_time = (recurrence.write_date + timedelta(seconds=30)).strftime("%Y-%m-%dT%H:%M:%SZ")
        recurrence_google_values = recurrence._google_values()
        recurrence_google_values['updated'] = update_time
        updated_event_google_values = recurrence.calendar_event_ids.sorted('start')[event_index]._google_values()
        updated_event_google_values['updated'] = update_time
        updated_event_google_values['attendees'] = [
            {"email": self.organizer_user.partner_id.email, "responseStatus": "accepted"},
            {"email": self.attendee_user.partner_id.email, "responseStatus": response_status},
        ]
        return [
            recurrence_google_values,
            updated_event_google_values,
        ]

    def google_respond_to_recurrent_event_with_option_all_events(self, recurrence, response_status):
        """
        Function returns google api response simulating 'self.attendee_user' responding to 'recurrence'
        with response of 'response_status' and option "All events"
        """
        update_time = (recurrence.write_date + timedelta(seconds=30)).strftime("%Y-%m-%dT%H:%M:%SZ")
        recurrence_google_values = recurrence._google_values()
        recurrence_google_values['updated'] = update_time
        recurrence_google_values['attendees'] = [
            {"email": self.organizer_user.partner_id.email, "responseStatus": "accepted"},
            {"email": self.attendee_user.partner_id.email, "responseStatus": response_status},
        ]
        return [recurrence_google_values]

    def google_respond_to_recurrent_event_with_option_following_events(self, recurrence, event_index, response_status, rrule1, rrule2):
        """
        Function returns google api response simulating 'self.attendee_user' responding to the event number 'event_index' (0-indexed)
        in 'recurrence' with response of 'response_status' and option "This and following events".
        """
        update_time = (recurrence.write_date + timedelta(seconds=30)).strftime("%Y-%m-%dT%H:%M:%SZ")
        recurrence_google_values = recurrence._google_values()
        recurrence_google_values['updated'] = update_time
        updated_event_google_values = recurrence.calendar_event_ids.sorted('start')[event_index]._google_values()
        updated_event_google_values['updated'] = update_time
        updated_event_google_values['attendees'] = [
            {"email": self.organizer_user.partner_id.email, "responseStatus": "accepted"},
            {"email": self.attendee_user.partner_id.email, "responseStatus": response_status},
        ]
        updated_event_id = updated_event_google_values['id']
        updated_event_google_values['id'] = updated_event_id[:updated_event_id.index('_') + 1] + 'R' + updated_event_id[updated_event_id.index('_') + 1:]
        recurrence_google_values["recurrence"] = [rrule1]
        updated_event_google_values["recurrence"] = [rrule2]
        return [
            recurrence_google_values,
            updated_event_google_values,
        ]

    @property
    def now(self):
        return pytz.utc.localize(datetime.now()).isoformat()

    def sync(self, events):
        events.clear_type_ambiguity(self.env)
        google_recurrence = events.filter(GoogleEvent.is_recurrence)
        self.env['calendar.recurrence']._sync_google2odoo(google_recurrence)
        self.env['calendar.event']._sync_google2odoo(events - google_recurrence)

    @patch_api
    def test_new_google_event(self):
        description = '<script>alert("boom")</script><p style="white-space: pre"><h1>HELLO</h1></p><ul><li>item 1</li><li>item 2</li></ul>'
        values = {
            'id': 'oj44nep1ldf8a3ll02uip0c9aa',
            'description': description,
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing new update',
            'visibility': 'public',
            'attendees': [{
                'displayName': 'Mitchell Admin',
                'email': self.public_partner.email,
                'responseStatus': 'needsAction'
            },],
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2020-01-13T16:55:00+01:00',
                'timeZone': 'Europe/Brussels'
            },
            'end': {
                'dateTime': '2020-01-13T19:55:00+01:00',
                'timeZone': 'Europe/Brussels'
            },
        }
        self.env['calendar.event']._sync_google2odoo(GoogleEvent([values]))
        event = self.env['calendar.event'].search([('google_id', '=', values.get('id'))])
        self.assertTrue(event, "It should have created an event")
        self.assertEqual(event.name, values.get('summary'))
        self.assertFalse(event.allday)
        self.assertEqual(event.description, tools.html_sanitize(description))
        self.assertEqual(event.start, datetime(2020, 1, 13, 15, 55))
        self.assertEqual(event.stop, datetime(2020, 1, 13, 18, 55))
        admin_attendee = event.attendee_ids.filtered(lambda e: e.email == self.public_partner.email)
        self.assertEqual(self.public_partner.email, admin_attendee.email)
        self.assertEqual(self.public_partner.name, admin_attendee.partner_id.name)
        self.assertEqual(event.partner_ids, event.attendee_ids.partner_id)
        self.assertEqual('needsAction', admin_attendee.state)
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_invalid_owner_property(self):
        values = {
            'id': 'oj44nep1ldf8a3ll02uip0c9aa',
            'description': 'Small mini desc',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing new update',
            'visibility': 'public',
            'attendees': [],
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2020-01-13T16:55:00+01:00',
                'timeZone': 'Europe/Brussels'
            },
            'extendedProperties': {
                'shared':  {'%s_owner_id' % self.env.cr.dbname: "invalid owner id"}
            },
            'end': {
                'dateTime': '2020-01-13T19:55:00+01:00',
                'timeZone': 'Europe/Brussels'
            },
        }
        self.env['calendar.event']._sync_google2odoo(GoogleEvent([values]))
        event = self.env['calendar.event'].search([('google_id', '=', values.get('id'))])
        self.assertEqual(event.user_id, self.env.user)
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_valid_owner_property(self):
        user = new_test_user(self.env, login='calendar-user')
        values = {
            'id': 'oj44nep1ldf8a3ll02uip0c9aa',
            'description': 'Small mini desc',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing new update',
            'visibility': 'public',
            'attendees': [],
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2020-01-13T16:55:00+01:00',
                'timeZone': 'Europe/Brussels'
            },
            'extendedProperties': {
                'shared':  {'%s_owner_id' % self.env.cr.dbname: str(user.id)}
            },
            'end': {
                'dateTime': '2020-01-13T19:55:00+01:00',
                'timeZone': 'Europe/Brussels'
            },
        }
        self.env['calendar.event']._sync_google2odoo(GoogleEvent([values]))
        event = self.env['calendar.event'].search([('google_id', '=', values.get('id'))])
        self.assertEqual(event.user_id, user)
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_cancelled(self):
        """ Cancel event when the current user is the organizer """
        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        event = self.env['calendar.event'].create({
            'name': 'coucou',
            'start': date(2020, 1, 6),
            'stop': date(2020, 1, 6),
            'google_id': google_id,
            'user_id': self.env.user.id,
            'need_sync': False,
            'partner_ids': [(6, 0, self.env.user.partner_id.ids)]  # current user is attendee
        })
        gevent = GoogleEvent([{
            'id': google_id,
            'status': 'cancelled',
        }])
        self.sync(gevent)
        self.assertFalse(event.exists())
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_attendee_cancelled(self):
        """ Cancel event when the current user is not the organizer """
        user = new_test_user(self.env, login='calendar-user')
        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        event = self.env['calendar.event'].create({
            'name': 'coucou',
            'start': date(2020, 1, 5),
            'stop': date(2020, 1, 6),
            'allday': True,
            'google_id': google_id,
            'need_sync': False,
            'user_id': False,  # Not the current user
            'partner_ids': [Command.set(user.partner_id.ids)],
        })
        gevent = GoogleEvent([{
            'id': google_id,
            'status': 'cancelled',
        }])
        user_attendee = event.attendee_ids
        self.assertEqual(user_attendee.state, 'needsAction')
        # We have to call sync with the attendee user
        gevent.clear_type_ambiguity(self.env)
        self.env['calendar.event'].with_user(user)._sync_google2odoo(gevent)
        self.assertTrue(event.active)
        user_attendee = event.attendee_ids
        self.assertTrue(user_attendee)
        self.assertEqual(user_attendee.state, 'declined')
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_private_extended_properties(self):
        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        event = self.env['calendar.event'].create({
            'name': 'coucou',
            'start': date(2020, 1, 6),
            'stop': date(2020, 1, 6),
            'allday': True,
            'google_id': google_id,
            'need_sync': False,
            'user_id': False,  # Not the current user
            'partner_ids': [(6, 0, self.env.user.partner_id.ids)]  # current user is attendee
        })
        user_attendee = event.attendee_ids
        self.assertTrue(user_attendee)
        self.assertEqual(user_attendee.state, 'accepted')
        user_attendee.do_decline()
        # To avoid 403 errors, we send a limited dictionnary when we don't have write access.
        # guestsCanModify property is not properly handled yet
        self.assertGoogleEventPatched(event.google_id, {
            'id': event.google_id,
            'summary': 'coucou',
            'start': {'date': str(event.start_date), 'dateTime': None},
            'end': {'date': str(event.stop_date + relativedelta(days=1)), 'dateTime': None},
            'attendees': [{'email': 'odoobot@example.com', 'responseStatus': 'declined'}],
            'extendedProperties': {'private': {'%s_odoo_id' % self.env.cr.dbname: event.id}},
            'reminders': {'overrides': [], 'useDefault': False},
        })

    @patch_api
    def test_attendee_removed(self):
        user = new_test_user(self.env, login='calendar-user')
        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        event = self.env['calendar.event'].with_user(user).create({
            'name': 'coucou',
            'start': date(2020, 1, 6),
            'stop': date(2020, 1, 6),
            'google_id': google_id,
            'user_id': False,  # user is not owner
            'need_sync': False,
            'partner_ids': [(6, 0, user.partner_id.ids)],  # but user is attendee
        })
        gevent = GoogleEvent([{
            'id': google_id,
            'description': 'Small mini desc',
            "updated": self.now,
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing new update',
            'visibility': 'public',
            'attendees': [],  # <= attendee removed in Google
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2020-01-13T16:55:00+01:00',
                'timeZone': 'Europe/Brussels'
            },
            'end': {
                'dateTime': '2020-01-13T19:55:00+01:00',
                'timeZone': 'Europe/Brussels'
            },
        }])
        self.assertEqual(event.partner_ids, user.partner_id)
        self.assertEqual(event.attendee_ids.partner_id, user.partner_id)
        self.sync(gevent)
        # User attendee removed but gevent owner might be added after synch.
        self.assertNotEqual(event.attendee_ids.partner_id, user.partner_id)
        self.assertNotEqual(event.partner_ids, user.partner_id)
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_attendee_removed_multiple(self):

        user = new_test_user(self.env, login='calendar-user')
        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        base_event = self.env['calendar.event'].create({
            'name': 'coucou',
            'allday': True,
            'start': datetime(2020, 1, 6),
            'stop': datetime(2020, 1, 6),
            'user_id': False,  # user is not owner
            'need_sync': False,
            'partner_ids': [(6, 0, user.partner_id.ids)],  # but user is attendee
        })
        recurrence = self.env['calendar.recurrence'].create({
            'google_id': google_id,
            'rrule': 'FREQ=WEEKLY;COUNT=2;BYDAY=MO',
            'need_sync': False,
            'base_event_id': base_event.id,
            'calendar_event_ids': [(4, base_event.id)],
        })
        recurrence._apply_recurrence()

        gevent = GoogleEvent([{
            'id': google_id,
            "updated": self.now,
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'coucou',
            'attendees': [],  # <= attendee removed in Google
            'recurrence': ['RRULE:FREQ=WEEKLY;COUNT=2;BYDAY=MO'],
            'reminders': {'useDefault': True},
            'start': {'date': '2020-01-6'},
            'end': {'date': '2020-01-7'},
        }])
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(events.partner_ids, user.partner_id)
        self.assertEqual(events.attendee_ids.partner_id, user.partner_id)
        self.sync(gevent)
        # User attendee removed but gevent owner might be added after synch.
        self.assertNotEqual(events.attendee_ids.partner_id, user.partner_id)
        self.assertNotEqual(events.partner_ids, user.partner_id)
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence(self):
        recurrence_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        values = {
            'id': recurrence_id,
            'description': 'Small mini desc',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing new update',
            'recurrence': ['RRULE:FREQ=WEEKLY;WKST=SU;COUNT=3;BYDAY=MO'],
            'reminders': {'useDefault': True},
            'start': {'date': '2020-01-6'},
            'end': {'date': '2020-01-7'},
            'transparency': 'opaque',
        }
        self.env['calendar.recurrence']._sync_google2odoo(GoogleEvent([values]))
        recurrence = self.env['calendar.recurrence'].search([('google_id', '=', values.get('id'))])
        self.assertTrue(recurrence, "it should have created a recurrence")
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 3, "it should have created a recurrence with 3 events")
        self.assertTrue(all(events.mapped('recurrency')))
        self.assertEqual(events[0].start_date, date(2020, 1, 6))
        self.assertEqual(events[1].start_date, date(2020, 1, 13))
        self.assertEqual(events[2].start_date, date(2020, 1, 20))
        self.assertEqual(events[0].start_date, date(2020, 1, 6))
        self.assertEqual(events[1].start_date, date(2020, 1, 13))
        self.assertEqual(events[2].start_date, date(2020, 1, 20))
        self.assertEqual(events[0].google_id, '%s_20200106' % recurrence_id)
        self.assertEqual(events[1].google_id, '%s_20200113' % recurrence_id)
        self.assertEqual(events[2].google_id, '%s_20200120' % recurrence_id)
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_datetime(self):
        recurrence_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        values = {
            'id': recurrence_id,
            'description': 'Small mini desc',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing new update',
            'visibility': 'public',
            'recurrence': ['RRULE:FREQ=WEEKLY;WKST=SU;COUNT=3;BYDAY=MO'],
            'reminders': {'useDefault': True},
            'start': {'dateTime': '2020-01-06T18:00:00+01:00', 'date': None},
            'end': {'dateTime': '2020-01-06T19:00:00+01:00', 'date': None},
        }
        self.env['calendar.recurrence']._sync_google2odoo(GoogleEvent([values]))
        recurrence = self.env['calendar.recurrence'].search([('google_id', '=', values.get('id'))])
        self.assertTrue(recurrence, "it should have created a recurrence")
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 3, "it should have created a recurrence with 3 events")
        self.assertTrue(all(events.mapped('recurrency')))
        self.assertEqual(events[0].start, datetime(2020, 1, 6, 17, 0))
        self.assertEqual(events[1].start, datetime(2020, 1, 13, 17, 0))
        self.assertEqual(events[2].start, datetime(2020, 1, 20, 17, 0))
        self.assertEqual(events[0].google_id, '%s_20200106T170000Z' % recurrence_id)
        self.assertEqual(events[1].google_id, '%s_20200113T170000Z' % recurrence_id)
        self.assertEqual(events[2].google_id, '%s_20200120T170000Z' % recurrence_id)
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_exdate(self):
        recurrence_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        events = GoogleEvent([{
            'id': recurrence_id,
            'summary': 'Pricing new update',
            'organizer': {'email': self.env.user.email, 'self': True},
            'recurrence': ['RRULE:FREQ=WEEKLY;WKST=SU;COUNT=3;BYDAY=MO'],
            'reminders': {'useDefault': True},
            'start': {'date': '2020-01-6'},
            'end': {'date': '2020-01-7'},
        }, {   # Third event has been deleted
            'id': '%s_20200113' % recurrence_id,
            'originalStartTime': {'dateTime': '2020-01-13'},
            'recurringEventId': 'oj44nep1ldf8a3ll02uip0c9pk',
            'reminders': {'useDefault': True},
            'status': 'cancelled',
        }])
        self.sync(events)
        recurrence = self.env['calendar.recurrence'].search([('google_id', '=', recurrence_id)])
        self.assertTrue(recurrence, "it should have created a recurrence")
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 2, "it should have created a recurrence with 2 events")
        self.assertEqual(events[0].start_date, date(2020, 1, 6))
        self.assertEqual(events[1].start_date, date(2020, 1, 20))
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_first_exdate(self):
        recurrence_id = "4c0de517evkk3ra294lmut57vm"
        events = GoogleEvent([{
            "id": recurrence_id,
            "updated": "2020-01-13T16:17:03.806Z",
            "summary": "r rul",
            "start": {"date": "2020-01-6"},
            'organizer': {'email': self.env.user.email, 'self': True},
            "end": {"date": "2020-01-7"},
            'reminders': {'useDefault': True},
            "recurrence": ["RRULE:FREQ=WEEKLY;WKST=SU;COUNT=3;BYDAY=MO"],
        }, {
            "id": "%s_20200106" % recurrence_id,
            "status": "cancelled",
            "recurringEventId": "4c0de517evkk3ra294lmut57vm",
            'reminders': {'useDefault': True},
            "originalStartTime": {
                "date": "2020-01-06"
            }
        }])
        self.sync(events)
        recurrence = self.env['calendar.recurrence'].search([('google_id', '=', recurrence_id)])
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 2, "it should have created a recurrence with 2 events")
        self.assertEqual(events[0].start_date, date(2020, 1, 13))
        self.assertEqual(events[1].start_date, date(2020, 1, 20))
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrencde_first_updated(self):
        recurrence_id = "4c0de517evkk3ra294lmut57vm"
        events = GoogleEvent([{
            'id': recurrence_id,
            'recurrence': ['RRULE:FREQ=WEEKLY;WKST=SU;COUNT=3;BYDAY=WE'],
            'start': {'date': '2020-01-01'},
            'end': {'date': '2020-01-02'},
            'status': 'confirmed',
            'summary': 'rrule',
            'reminders': {'useDefault': True},
            'updated': self.now,
            'guestsCanModify': True,
        }, {
            'summary': 'edited',  # Name changed
            'id': '%s_20200101' % recurrence_id,
            'originalStartTime': {'date': '2020-01-01'},
            'recurringEventId': recurrence_id,
            'start': {'date': '2020-01-01'},
            'end': {'date': '2020-01-02'},
            'reminders': {'useDefault': True},
            'updated': self.now,
            'guestsCanModify': True,
        }])
        self.sync(events)
        recurrence = self.env['calendar.recurrence'].search([('google_id', '=', recurrence_id)])
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 3, "it should have created a recurrence with 3 events")
        self.assertEqual(events[0].name, 'edited')
        self.assertEqual(events[1].name, 'rrule')
        self.assertEqual(events[2].name, 'rrule')
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_existing_recurrence_first_updated(self):
        recurrence_id = "4c0de517evkk3ra294lmut57vm"
        base_event = self.env['calendar.event'].create({
            'name': 'coucou',
            'allday': True,
            'start': datetime(2020, 1, 6),
            'stop': datetime(2020, 1, 6),
            'need_sync': False,
        })
        recurrence = self.env['calendar.recurrence'].create({
            'google_id': recurrence_id,
            'rrule': 'FREQ=WEEKLY;WKST=SU;COUNT=3;BYDAY=MO',
            'need_sync': False,
            'base_event_id': base_event.id,
        })
        recurrence._apply_recurrence()
        values = [{
            'summary': 'edited',  # Name changed
            'id': '%s_20200106' % recurrence_id,
            'originalStartTime': {'date': '2020-01-06'},
            'recurringEventId': recurrence_id,
            'start': {'date': '2020-01-06'},
            'end': {'date': '2020-01-07'},
            'reminders': {'useDefault': True},
            'updated': self.now,
        }]
        self.env['calendar.event']._sync_google2odoo(GoogleEvent(values))
        recurrence = self.env['calendar.recurrence'].search([('google_id', '=', recurrence_id)])
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 3, "it should have created a recurrence with 3 events")
        self.assertEqual(events[0].name, 'edited')
        self.assertEqual(events[1].name, 'coucou')
        self.assertEqual(events[2].name, 'coucou')
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_outlier(self):
        recurrence_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        events = GoogleEvent([{
            'id': recurrence_id,
            'summary': 'Pricing new update',
            'recurrence': ['RRULE:FREQ=WEEKLY;WKST=SU;COUNT=3;BYDAY=MO'],
            'start': {'date': '2020-01-6'},
            'end': {'date': '2020-01-7'},
            'reminders': {'useDefault': True},
            'updated': self.now,
            'guestsCanModify': True,
        },
        {  # Third event has been moved
            'id': '%s_20200113' % recurrence_id,
            'summary': 'Pricing new update',
            'start': {'date': '2020-01-18'},
            'end': {'date': '2020-01-19'},
            'originalStartTime': {'date': '2020-01-13'},
            'reminders': {'useDefault': True},
            'updated': self.now,
            'guestsCanModify': True,
        }])
        self.sync(events)
        recurrence = self.env['calendar.recurrence'].search([('google_id', '=', recurrence_id)])
        self.assertTrue(recurrence, "it should have created a recurrence")
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 3, "it should have created a recurrence with 3 events")
        self.assertEqual(events[0].start_date, date(2020, 1, 6))
        self.assertEqual(events[1].start_date, date(2020, 1, 18), "It should not be in sync with the recurrence")
        self.assertEqual(events[2].start_date, date(2020, 1, 20))
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_moved(self):
        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        base_event = self.env['calendar.event'].create({
            'name': 'coucou',
            'allday': True,
            'start': datetime(2020, 1, 6),
            'stop': datetime(2020, 1, 6),
            'need_sync': False,
        })
        recurrence = self.env['calendar.recurrence'].create({
            'google_id': google_id,
            'rrule': 'FREQ=WEEKLY;COUNT=2;BYDAY=MO',
            'need_sync': False,
            'base_event_id': base_event.id,
            'calendar_event_ids': [(4, base_event.id)],
        })
        recurrence._apply_recurrence()
        values = {
            'id': google_id,
            'summary': 'coucou',
            'recurrence': ['RRULE:FREQ=WEEKLY;COUNT=2;BYDAY=WE'],  # Now wednesday
            'start': {'date': '2020-01-08'},
            'end': {'date': '2020-01-09'},
            'reminders': {'useDefault': True},
            "attendees": [
                {
                    "email": "odoobot@example.com", "responseStatus": "accepted",
                },
            ],
            'updated': self.now,
            'guestsCanModify': True,
        }
        self.env['calendar.recurrence']._sync_google2odoo(GoogleEvent([values]))
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 2)
        self.assertEqual(recurrence.rrule, 'RRULE:FREQ=WEEKLY;COUNT=2;BYDAY=WE')
        self.assertEqual(events[0].start_date, date(2020, 1, 8))
        self.assertEqual(events[1].start_date, date(2020, 1, 15))
        self.assertEqual(events[0].google_id, '%s_20200108' % google_id)
        self.assertEqual(events[1].google_id, '%s_20200115' % google_id)
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_name_updated(self):
        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        base_event = self.env['calendar.event'].create({
            'name': 'coucou',
            'allday': True,
            'start': datetime(2020, 1, 6),
            'stop': datetime(2020, 1, 6),
            'need_sync': False,
        })
        recurrence = self.env['calendar.recurrence'].create({
            'google_id': google_id,
            'rrule': 'FREQ=WEEKLY;COUNT=2;BYDAY=MO',
            'need_sync': False,
            'base_event_id': base_event.id,
            'calendar_event_ids': [(4, base_event.id)],
        })
        recurrence._apply_recurrence()

        values = {
            'id': google_id,
            'summary': 'coucou again',
            'recurrence': ['RRULE:FREQ=WEEKLY;COUNT=2;BYDAY=MO'],
            'start': {'date': '2020-01-06'},
            'end': {'date': '2020-01-07'},
            'reminders': {'useDefault': True},
            "attendees": [
                {
                    "email": "odoobot@example.com", "responseStatus": "accepted",
                },
            ],
            'updated': self.now,
        }
        self.env['calendar.recurrence']._sync_google2odoo(GoogleEvent([values]))
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 2)
        self.assertEqual(recurrence.rrule, 'RRULE:FREQ=WEEKLY;COUNT=2;BYDAY=MO')
        self.assertEqual(events.mapped('name'), ['coucou again', 'coucou again'])
        self.assertEqual(events[0].start_date, date(2020, 1, 6))
        self.assertEqual(events[1].start_date, date(2020, 1, 13))
        self.assertEqual(events[0].google_id, '%s_20200106' % google_id)
        self.assertEqual(events[1].google_id, '%s_20200113' % google_id)
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_write_with_outliers(self):
        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        base_event = self.env['calendar.event'].create({
            'name': 'coucou',
            'start': datetime(2021, 2, 15, 8, 0, 0),
            'stop': datetime(2021, 2, 15, 10, 0, 0),
            'need_sync': False,
        })
        recurrence = self.env['calendar.recurrence'].create({
            'google_id': google_id,
            'rrule': 'FREQ=WEEKLY;COUNT=3;BYDAY=MO',
            'need_sync': False,
            'base_event_id': base_event.id,
            'calendar_event_ids': [(4, base_event.id)],
        })
        recurrence._apply_recurrence()
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(events[0].google_id, '%s_20210215T080000Z' % google_id)
        self.assertEqual(events[1].google_id, '%s_20210222T080000Z' % google_id)
        self.assertEqual(events[2].google_id, '%s_20210301T080000Z' % google_id)
        # Modify start of one of the events.
        middle_event = recurrence.calendar_event_ids.filtered(lambda e: e.start == datetime(2021, 2, 22, 8, 0, 0))
        middle_event.write({
            'start': datetime(2021, 2, 22, 16, 0, 0),
            'need_sync': False,
        })

        values = {
            'id': google_id,
            'summary': 'coucou again',
            'recurrence': ['RRULE:FREQ=WEEKLY;COUNT=3;BYDAY=MO'],
            'start': {'dateTime': '2021-02-15T09:00:00+01:00', 'date': None},  # 8:00 UTC
            'end': {'dateTime': '2021-02-15-T11:00:00+01:00', 'date': None},
            'reminders': {'useDefault': True},
            "attendees": [
                {
                    "email": "odoobot@example.com", "responseStatus": "accepted",
                },
            ],
            'updated': self.now,
        }
        self.env['calendar.recurrence']._sync_google2odoo(GoogleEvent([values]))
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 3)
        self.assertEqual(recurrence.rrule, 'RRULE:FREQ=WEEKLY;COUNT=3;BYDAY=MO')
        self.assertEqual(events.mapped('name'), ['coucou again', 'coucou again', 'coucou again'])
        self.assertEqual(events[0].start, datetime(2021, 2, 15, 8, 0, 0))
        self.assertEqual(events[1].start, datetime(2021, 2, 22, 16, 0, 0))
        self.assertEqual(events[2].start, datetime(2021, 3, 1, 8, 0, 0))
        # the google_id of recurrent events should not be modified when events start is modified.
        # the original start date or datetime should always be present.
        self.assertEqual(events[0].google_id, '%s_20210215T080000Z' % google_id)
        self.assertEqual(events[1].google_id, '%s_20210222T080000Z' % google_id)
        self.assertEqual(events[2].google_id, '%s_20210301T080000Z' % google_id)
        self.assertGoogleAPINotCalled()


    @patch_api
    def test_recurrence_write_time_fields(self):
        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        base_event = self.env['calendar.event'].create({
            'name': 'coucou',
            'start': datetime(2021, 2, 15, 8, 0, 0),
            'stop': datetime(2021, 2, 15, 10, 0, 0),
            'need_sync': False,
        })
        recurrence = self.env['calendar.recurrence'].create({
            'google_id': google_id,
            'rrule': 'FREQ=WEEKLY;COUNT=3;BYDAY=MO',
            'need_sync': False,
            'base_event_id': base_event.id,
            'calendar_event_ids': [(4, base_event.id)],
        })
        recurrence._apply_recurrence()
        # Google modifies the start/stop of the base event
        # When the start/stop or all day values are updated, the recurrence should reapplied.

        values = {
            'id': google_id,
            'summary': "It's me again",
            'recurrence': ['RRULE:FREQ=WEEKLY;COUNT=4;BYDAY=MO'],
            'start': {'dateTime': '2021-02-15T12:00:00+01:00', 'date': None},  # 11:00 UTC
            'end': {'dateTime': '2021-02-15-T15:00:00+01:00', 'date': None},
            'reminders': {'useDefault': True},
            "attendees": [
                {
                    "email": "odoobot@example.com", "responseStatus": "accepted",
                },
            ],
            'updated': self.now,
            'guestsCanModify': True,
        }

        self.env['calendar.recurrence']._sync_google2odoo(GoogleEvent([values]))
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(events[0].start, datetime(2021, 2, 15, 11, 0, 0))
        self.assertEqual(events[1].start, datetime(2021, 2, 22, 11, 0, 0))
        self.assertEqual(events[2].start, datetime(2021, 3, 1, 11, 0, 0))
        self.assertEqual(events[3].start, datetime(2021, 3, 8, 11, 0, 0))
        # We ensure that our modifications are pushed
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_deleted(self):
        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        base_event = self.env['calendar.event'].create({
            'name': 'coucou',
            'start': datetime(2021, 2, 15, 8, 0, 0),
            'stop': datetime(2021, 2, 15, 10, 0, 0),
            'need_sync': False,
        })
        recurrence = self.env['calendar.recurrence'].create({
            'google_id': google_id,
            'rrule': 'FREQ=WEEKLY;COUNT=3;BYDAY=MO',
            'need_sync': False,
            'base_event_id': base_event.id,
            'calendar_event_ids': [(4, base_event.id)],
        })
        recurrence._apply_recurrence()
        events = recurrence.calendar_event_ids
        values = {
            'id': google_id,
            'status': 'cancelled',
        }
        self.sync(GoogleEvent([values]))
        self.assertFalse(recurrence.exists(), "The recurrence should be deleted")
        self.assertFalse(events.exists(), "All events should be deleted")
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_timezone(self):
        """ Ensure that the timezone of the base_event is saved on the recurrency
        Google save the TZ on the event and we save it on the recurrency.
        """
        recurrence_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        values = {
            'id': recurrence_id,
            'description': '',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Event with ',
            'visibility': 'public',
            'recurrence': ['RRULE:FREQ=WEEKLY;WKST=SU;COUNT=3;BYDAY=MO'],
            'reminders': {'useDefault': True},
            'start': {'dateTime': '2020-01-06T18:00:00+01:00', 'timeZone': 'Pacific/Auckland', 'date': None},
            'end': {'dateTime': '2020-01-06T19:00:00+01:00', 'timeZone': 'Pacific/Auckland', 'date': None},
        }
        self.env['calendar.recurrence']._sync_google2odoo(GoogleEvent([values]))
        recurrence = self.env['calendar.recurrence'].search([('google_id', '=', values.get('id'))])
        self.assertEqual(recurrence.event_tz, 'Pacific/Auckland', "The Google event Timezone should be saved on the recurrency")
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_no_duplicate(self):
        values = [
            {
                "attendees": [
                    {
                        "email": "myemail@exampl.com",
                        "responseStatus": "needsAction",
                        "self": True,
                    },
                    {"email": "jane.doe@example.com", "responseStatus": "needsAction"},
                    {
                        "email": "john.doe@example.com",
                        "organizer": True,
                        "responseStatus": "accepted",
                    },
                ],
                "created": "2023-02-20T11:45:07.000Z",
                "creator": {"email": "john.doe@example.com"},
                "end": {"dateTime": "2023-02-25T16:20:00+01:00", "timeZone": "Europe/Zurich"},
                "etag": '"4611038912699385"',
                "eventType": "default",
                "iCalUID": "9lxiofipomymx2yr1yt0hpep99@google.com",
                "id": "9lxiofipomymx2yr1yt0hpep99",
                "kind": "calendar#event",
                "organizer": {"email": "john.doe@example.com"},
                "recurrence": ["RRULE:FREQ=WEEKLY;BYDAY=SA"],
                "reminders": {"useDefault": True},
                "sequence": 0,
                "start": {"dateTime": "2023-02-25T15:30:00+01:00", "timeZone": "Europe/Zurich"},
                "status": "confirmed",
                "summary": "Weekly test",
                "updated": "2023-02-20T11:45:08.547Z",
                'guestsCanModify': True,
            },
            {
                "attendees": [
                    {
                        "email": "myemail@exampl.com",
                        "responseStatus": "needsAction",
                        "self": True,
                    },
                    {
                        "email": "jane.doe@example.com",
                        "organizer": True,
                        "responseStatus": "needsAction",
                    },
                    {"email": "john.doe@example.com", "responseStatus": "accepted"},
                ],
                "created": "2023-02-20T11:45:44.000Z",
                "creator": {"email": "john.doe@example.com"},
                "end": {"dateTime": "2023-02-26T15:20:00+01:00", "timeZone": "Europe/Zurich"},
                "etag": '"5534851880843722"',
                "eventType": "default",
                "iCalUID": "hhb5t0cffjkndvlg7i22f7byn1@google.com",
                "id": "hhb5t0cffjkndvlg7i22f7byn1",
                "kind": "calendar#event",
                "organizer": {"email": "jane.doe@example.com"},
                "recurrence": ["RRULE:FREQ=WEEKLY;BYDAY=SU"],
                "reminders": {"useDefault": True},
                "sequence": 0,
                "start": {"dateTime": "2023-02-26T14:30:00+01:00", "timeZone": "Europe/Zurich"},
                "status": "confirmed",
                "summary": "Weekly test 2",
                "updated": "2023-02-20T11:48:00.634Z",
                'guestsCanModify': True,
            },
        ]
        google_events = GoogleEvent(values)
        self.env['calendar.recurrence']._sync_google2odoo(google_events)
        no_duplicate_gevent = google_events.filter(lambda e: e.id == "9lxiofipomymx2yr1yt0hpep99")
        dt_start = datetime.fromisoformat(no_duplicate_gevent.start["dateTime"]).astimezone(pytz.utc).replace(tzinfo=None).replace(hour=0)
        dt_end = datetime.fromisoformat(no_duplicate_gevent.end["dateTime"]).astimezone(pytz.utc).replace(tzinfo=None).replace(hour=23)
        no_duplicate_event = self.env["calendar.event"].search(
            [
                ("name", "=", no_duplicate_gevent.summary),
                ("start", ">=", dt_start),
                ("stop", "<=", dt_end,)
            ]
        )
        self.assertEqual(len(no_duplicate_event), 1)

    @patch_api
    def test_recurrence_list_contains_more_items(self):
        recurrence_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        values = {
            'id': recurrence_id,
            'description': 'Small mini desc',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing new update',
            'visibility': 'public',
            'recurrence': ['EXDATE;TZID=Europe/Rome:20200113',
                           'RRULE;X-EVOLUTION-ENDDATE=20200120:FREQ=WEEKLY;COUNT=3;BYDAY=MO;X-RELATIVE=1'],
            'reminders': {'useDefault': True},
            'start': {'date': '2020-01-6'},
            'end': {'date': '2020-01-7'},
        }
        self.env['calendar.recurrence']._sync_google2odoo(GoogleEvent([values]))
        recurrence = self.env['calendar.recurrence'].search([('google_id', '=', values.get('id'))])
        self.assertTrue(recurrence, "it should have created a recurrence")
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 3, "it should have created a recurrence with 3 events")
        self.assertTrue(all(events.mapped('recurrency')))
        self.assertEqual(events[0].start_date, date(2020, 1, 6))
        self.assertEqual(events[1].start_date, date(2020, 1, 13))
        self.assertEqual(events[2].start_date, date(2020, 1, 20))
        self.assertEqual(events[0].stop_date, date(2020, 1, 6))
        self.assertEqual(events[1].stop_date, date(2020, 1, 13))
        self.assertEqual(events[2].stop_date, date(2020, 1, 20))
        self.assertEqual(events[0].google_id, '%s_20200106' % recurrence_id)
        self.assertEqual(events[1].google_id, '%s_20200113' % recurrence_id)
        self.assertEqual(events[2].google_id, '%s_20200120' % recurrence_id)
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_simple_event_into_recurrency(self):
        """ Synched single events should be converted in recurrency without problems"""
        google_id = 'aaaaaaaaaaaa'
        values = {
            'id': google_id,
            'description': 'Small mini desc',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing new update',
            'visibility': 'public',
            'attendees': [{
                'displayName': 'Mitchell Admin',
                'email': self.public_partner.email,
                'responseStatus': 'needsAction'
            }, ],
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2020-01-06T18:00:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
            'end': {
                'dateTime': '2020-01-13T19:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
        }
        self.env['calendar.event']._sync_google2odoo(GoogleEvent([values]))
        # The event is transformed into a recurrency on google
        values = {
            'id': google_id,
            'description': '',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Event with ',
            'visibility': 'public',
            'recurrence': ['RRULE:FREQ=WEEKLY;WKST=SU;COUNT=3;BYDAY=MO'],
            'reminders': {'useDefault': True},
            'start': {'dateTime': '2020-01-06T18:00:00+01:00', 'timeZone': 'Europe/Brussels', 'date': None},
            'end': {'dateTime': '2020-01-06T19:00:00+01:00', 'timeZone': 'Europe/Brussels', 'date': None},
        }
        recurrence = self.env['calendar.recurrence']._sync_google2odoo(GoogleEvent([values]))
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 3, "it should have created a recurrence with 3 events")
        event = self.env['calendar.event'].search([('google_id', '=', values.get('id'))])
        self.assertFalse(event.exists(), "The old event should not exits anymore")
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_reduced(self):
        # This test is a bit special because it's testing 2 sync processes. The
        # bug it's protecting against is cross-contamination when event dicts
        # are mutated in different ways during the call to
        # `_sync_google_calendar()`. If you want to do a new test, this one is
        # probably not the best example.
        google_id = "oj44nep1ldf8a3ll02uip0c9aa"
        with self.mock_datetime_and_now("2024-06-07"):
            # We start with an event with 2 repetitions
            values = [
                # Recurrence from day 7 changes
                {
                    "id": google_id,
                    "summary": "coucou",
                    "recurrence": [
                        "RRULE:FREQ=WEEKLY;WKST=MO;UNTIL=20240620T215959Z;BYDAY=FR"
                    ],
                    "start": {"dateTime": "2024-06-07T08:00:00+00:00"},
                    "end": {"dateTime": "2024-06-07T10:00:00+00:00"},
                    "reminders": {"useDefault": True},
                    "updated": self.now,
                    "attendees": [
                        {
                            "email": self.organizer_user.partner_id.email,
                            "responseStatus": "accepted",
                        },
                        {
                            "email": self.attendee_user.partner_id.email,
                            "responseStatus": "accepted",
                        },
                    ],
                },
                # Event details for day 7
                {
                    "id": "%s_20240607T080000Z" % google_id,
                    "summary": "coucou",
                    "start": {"dateTime": "2024-06-07T08:00:00+00:00"},
                    "end": {"dateTime": "2024-06-07T10:00:00+00:00"},
                    "reminders": {"useDefault": True},
                    "updated": self.now,
                    "recurringEventId": google_id,
                    "attendees": [
                        {
                            "email": self.organizer_user.partner_id.email,
                            "responseStatus": "accepted",
                        },
                        {
                            "email": self.attendee_user.partner_id.email,
                            "responseStatus": "accepted",
                        },
                    ],
                },
                # Event details for day 14
                {
                    "id": "%s_20240614T080000Z" % google_id,
                    "summary": "coucou",
                    "start": {"dateTime": "2024-06-14T08:00:00+00:00"},
                    "end": {"dateTime": "2024-06-14T10:00:00+00:00"},
                    "reminders": {"useDefault": True},
                    "updated": self.now,
                    "recurringEventId": google_id,
                    "attendees": [
                        {
                            "email": self.organizer_user.partner_id.email,
                            "responseStatus": "accepted",
                        },
                        {
                            "email": self.attendee_user.partner_id.email,
                            "responseStatus": "accepted",
                        },
                    ],
                },
            ]
            with patch.object(
                GoogleCalendarService,
                "get_events",
                return_value=(
                    GoogleEvent(values),
                    None,
                    [{"method": "popup", "minutes": 30}],
                ),
            ):
                self.attendee_user.sudo()._sync_google_calendar(self.google_service)
            events = self.env["calendar.event"].search(
                [("google_id", "like", google_id)]
            )
            self.assertEqual(len(events.exists()), 2)

        with self.mock_datetime_and_now("2024-06-10"):
            # From Google Calendar, they alter events from day 14 onwards and move
            # them 1h later. However, they regret and move them back 1h again.
            values = [
                # Recurrence from day 7 changes
                {
                    "id": google_id,
                    "summary": "coucou",
                    "recurrence": [
                        "RRULE:FREQ=WEEKLY;WKST=MO;UNTIL=20240613T215959Z;BYDAY=FR"
                    ],
                    "start": {"dateTime": "2024-06-07T08:00:00+00:00"},
                    "end": {"dateTime": "2024-06-07T10:00:00+00:00"},
                    "reminders": {"useDefault": True},
                    "updated": self.now,
                    "attendees": [
                        {
                            "email": self.organizer_user.partner_id.email,
                            "responseStatus": "accepted",
                        },
                        {
                            "email": self.attendee_user.partner_id.email,
                            "responseStatus": "accepted",
                        },
                    ],
                },
                # Event details for day 7
                {
                    "id": "%s_20240607T080000Z" % google_id,
                    "summary": "coucou",
                    "start": {"dateTime": "2024-06-07T08:00:00+00:00"},
                    "end": {"dateTime": "2024-06-07T10:00:00+00:00"},
                    "reminders": {"useDefault": True},
                    "updated": self.now,
                    "recurringEventId": google_id,
                    "attendees": [
                        {
                            "email": self.organizer_user.partner_id.email,
                            "responseStatus": "accepted",
                        },
                        {
                            "email": self.attendee_user.partner_id.email,
                            "responseStatus": "accepted",
                        },
                    ],
                },
                # Event details for day 14
                {
                    "id": "%s_20240614T080000Z" % google_id,
                    "summary": "coucou",
                    "start": {"dateTime": "2024-06-14T08:00:00+00:00"},
                    "end": {"dateTime": "2024-06-14T10:00:00+00:00"},
                    "reminders": {"useDefault": True},
                    "updated": self.now,
                    "recurringEventId": "%s_R20240614T080000" % google_id,
                    "attendees": [
                        {
                            "email": self.organizer_user.partner_id.email,
                            "responseStatus": "accepted",
                        },
                        {
                            "email": self.attendee_user.partner_id.email,
                            "responseStatus": "accepted",
                        },
                    ],
                },
                # New recurrence that starts on day 14
                {
                    "id": "%s_R20240614T080000" % google_id,
                    "summary": "coucou",
                    "start": {"dateTime": "2024-06-14T08:00:00+00:00"},
                    "end": {"dateTime": "2024-06-14T10:00:00+00:00"},
                    "recurrence": [
                        "RRULE:FREQ=WEEKLY;WKST=MO;UNTIL=20240620T215959Z;BYDAY=FR"
                    ],
                    "reminders": {"useDefault": True},
                    "updated": self.now,
                    "attendees": [
                        {
                            "email": self.organizer_user.partner_id.email,
                            "responseStatus": "accepted",
                        },
                        {
                            "email": self.attendee_user.partner_id.email,
                            "responseStatus": "accepted",
                        },
                    ],
                },
            ]
            # Then, Odoo syncs
            with patch.object(
                GoogleCalendarService,
                "get_events",
                return_value=(
                    GoogleEvent(values),
                    None,
                    [{"method": "popup", "minutes": 30}],
                ),
            ):
                self.attendee_user.sudo()._sync_google_calendar(self.google_service)
            events = self.env["calendar.event"].search(
                [("google_id", "like", google_id)]
            )
            self.assertEqual(len(events.exists()), 2)

    @patch_api
    def test_new_google_notifications(self):
        """ Event from Google should not create notifications and trigger. It ruins the perfs on large databases """
        cron_id = self.env.ref('calendar.ir_cron_scheduler_alarm').id
        triggers_before = self.env['ir.cron.trigger'].search([('cron_id', '=', cron_id)])
        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        start = datetime.today() + relativedelta(months=1, day=1, hours=1)
        end = datetime.today() + relativedelta(months=1, day=1, hours=2)
        updated = datetime.today() + relativedelta(minutes=1)
        values = {
            'id': google_id,
            'description': 'Small mini desc',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing new update',
            'visibility': 'public',
            'attendees': [{
                'displayName': 'Mitchell Admin',
                'email': self.public_partner.email,
                'responseStatus': 'needsAction'
            }, ],
            'reminders': {'overrides': [{"method": "email", "minutes": 10}], 'useDefault': False},
            'start': {
                'dateTime': pytz.utc.localize(start).isoformat(),
                'timeZone': 'Europe/Brussels',
                'date': None
            },
            'end': {
                'dateTime': pytz.utc.localize(end).isoformat(),
                'timeZone': 'Europe/Brussels',
                'date': None
            },
        }
        self.env['calendar.event']._sync_google2odoo(GoogleEvent([values]))
        triggers_after = self.env['ir.cron.trigger'].search([('cron_id', '=', cron_id)])
        new_triggers = triggers_after - triggers_before
        self.assertFalse(new_triggers, "The event should not be created with triggers.")

        # Event was created from Google and now it will be Updated from Google.
        # No further notifications should be created.
        values = {
            'id': google_id,
            'updated': pytz.utc.localize(updated).isoformat(),
            'description': 'New Super description',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing was not good, now it is correct',
            'visibility': 'public',
            'attendees': [{
                'displayName': 'Mitchell Admin',
                'email': self.public_partner.email,
                'responseStatus': 'needsAction'
            }, ],
            'reminders': {'overrides': [{"method": "email", "minutes": 10}], 'useDefault': False},
            'start': {
                'dateTime': pytz.utc.localize(start).isoformat(),
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
            'end': {
                'dateTime': pytz.utc.localize(end).isoformat(),
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
        }
        self.env['calendar.event']._sync_google2odoo(GoogleEvent([values]))
        triggers_after = self.env['ir.cron.trigger'].search([('cron_id', '=', cron_id)])
        new_triggers = triggers_after - triggers_before
        self.assertFalse(new_triggers, "The event should not be created with triggers.")
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_attendee_state(self):
        user = new_test_user(self.env, login='calendar-user')
        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        event = self.env['calendar.event'].with_user(user).create({
            'name': 'Event with me',
            'start': date(2020, 1, 6),
            'stop': date(2020, 1, 6),
            'google_id': google_id,
            'user_id': False,  # user is not owner
            'need_sync': False,
            'partner_ids': [(6, 0, user.partner_id.ids)],  # but user is attendee
        })
        self.assertEqual(event.attendee_ids.state, 'accepted')
        # The event is declined from Google
        values = {
            'id': google_id,
            'description': 'Changed my mind',
            "updated": self.now,
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': """I don't want to be with me anymore""",
            'attendees': [{
                'displayName': 'calendar-user (base.group_user)',
                'email': 'c.c@example.com',
                'responseStatus': 'declined'
            }, ],
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2020-01-13T16:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
            'end': {
                'dateTime': '2020-01-13T19:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None
            },
            'transparency': 'opaque',
        }
        self.env['calendar.event']._sync_google2odoo(GoogleEvent([values]))
        self.assertEqual(event.attendee_ids.state, 'declined')
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_attendees_same_event_both_share(self):
        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        other_user = new_test_user(self.env, login='calendar-user')
        event = self.env['calendar.event'].create({
            'name': 'coucou',
            'start': date(2020, 1, 6),
            'stop': date(2020, 1, 6),
            'allday': True,
            'google_id': google_id,
            'need_sync': False,
            'user_id': other_user.id,  # Not the current user
            'partner_ids': [(6, 0, [self.env.user.partner_id.id, other_user.partner_id.id], )]  # current user is attendee
        })
        event.write({'start': date(2020, 1, 7), 'stop': date(2020, 1, 8)})
        # To avoid 403 errors, we send a limited dictionnary when we don't have write access.
        # guestsCanModify property is not properly handled yet
        self.assertGoogleEventPatched(event.google_id, {
            'id': event.google_id,
            'start': {'date': str(event.start_date), 'dateTime': None},
            'end': {'date': str(event.stop_date + relativedelta(days=1)), 'dateTime': None},
            'summary': 'coucou',
            'description': '',
            'location': '',
            'guestsCanModify': True,
            'organizer': {'email': 'c.c@example.com', 'self': False},
            'attendees': [{'email': 'c.c@example.com', 'responseStatus': 'needsAction'},
                          {'email': 'odoobot@example.com', 'responseStatus': 'accepted'},],
            'extendedProperties': {'shared': {'%s_odoo_id' % self.env.cr.dbname: event.id,
                                              '%s_owner_id' % self.env.cr.dbname: other_user.id}},
            'reminders': {'overrides': [], 'useDefault': False},
            'transparency': 'opaque',
        }, timeout=3)

    @patch_api
    def test_attendee_recurrence_answer(self):
        """ Write on a recurrence to update all attendee answers """
        other_user = new_test_user(self.env, login='calendar-user')
        google_id = "aaaaaaaaaaa"
        base_event = self.env['calendar.event'].create({
            'name': 'coucou',
            'start': datetime(2021, 2, 15, 7, 0, 0),
            'stop': datetime(2021, 2, 15, 9, 0, 0),
            'event_tz': 'Europe/Brussels',
            'need_sync': False,
            'partner_ids': [(6, 0, [other_user.partner_id.id])]
        })
        recurrence = self.env['calendar.recurrence'].create({
            'google_id': google_id,
            'rrule': 'FREQ=WEEKLY;COUNT=3;BYDAY=MO',
            'need_sync': False,
            'base_event_id': base_event.id,
            'calendar_event_ids': [(4, base_event.id)],
        })
        recurrence._apply_recurrence()
        recurrence.calendar_event_ids.attendee_ids.state = 'accepted'
        values = {
            'id': google_id,
            "updated": self.now,
            'description': '',
            'attendees': [{'email': 'c.c@example.com', 'responseStatus': 'declined'}],
            'summary': 'coucou',
            # 'visibility': 'public',
            'recurrence': ['RRULE:FREQ=WEEKLY;COUNT=3;BYDAY=MO'],
            'reminders': {'useDefault': True},
            'start': {'dateTime': '2021-02-15T8:00:00+01:00', 'timeZone': 'Europe/Brussels', 'date': None},
            'end': {'dateTime': '2021-02-15T10:00:00+01:00', 'timeZone': 'Europe/Brussels', 'date': None},
        }
        self.env['calendar.recurrence']._sync_google2odoo(GoogleEvent([values]))
        attendee = recurrence.calendar_event_ids.attendee_ids.mapped('state')
        self.assertEqual(attendee, ['declined', 'declined', 'declined'], "All events should be declined")
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_creation_with_attendee_answer(self):
        """ Create a recurrence with predefined attendee answers """
        google_id = "aaaaaaaaaaa"
        values = {
            'id': google_id,
            "updated": self.now,
            'description': '',
            'attendees': [{'email': 'c.c@example.com', 'responseStatus': 'declined'}],
            'summary': 'coucou',
            # 'visibility': 'public',
            'recurrence': ['RRULE:FREQ=WEEKLY;COUNT=3;BYDAY=MO'],
            'reminders': {'useDefault': True},
            'start': {'dateTime': '2021-02-15T8:00:00+01:00', 'timeZone': 'Europe/Brussels', 'date': None},
            'end': {'dateTime': '2021-02-15T10:00:00+01:00', 'timeZone': 'Europe/Brussels', 'date': None},
            'guestsCanModify': True,
        }
        self.env['calendar.recurrence']._sync_google2odoo(GoogleEvent([values]))
        recurrence = self.env['calendar.recurrence'].search([('google_id', '=', google_id)])
        attendee = recurrence.calendar_event_ids.attendee_ids.mapped('state')
        self.assertEqual(attendee, ['declined', 'declined', 'declined'], "All events should be declined")
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_several_attendee_have_the_same_mail(self):
        """
        In google, One mail = One attendee but on Odoo, some partners could share the same mail
        This test checks that the deletion of such attendee has no harm: all attendee but the given mail are deleted.
        """
        partner1 = self.env['res.partner'].create({
            'name': 'joe',
            'email': 'dalton@example.com',
        })
        partner2 = self.env['res.partner'].create({
            'name': 'william',
            'email': 'dalton@example.com',
        })
        partner3 = self.env['res.partner'].create({
            'name': 'jack',
            'email': 'dalton@example.com',
        })
        partner4 = self.env['res.partner'].create({
            'name': 'averell',
            'email': 'dalton@example.com',
        })
        google_id = "aaaaaaaaaaaaaaaaa"
        event = self.env['calendar.event'].create({
            'name': 'coucou',
            'start': datetime(2020, 1, 13, 16, 0),
            'stop': datetime(2020, 1, 13, 20),
            'allday': False,
            'google_id': google_id,
            'need_sync': False,
            'user_id': self.env.user.partner_id.id,
            'partner_ids': [(6, 0, [self.env.user.partner_id.id, partner1.id, partner2.id, partner3.id, partner4.id],)]
            # current user is attendee
        })
        recurrence = self.env['calendar.recurrence'].create({
            'google_id': google_id,
            'rrule': 'FREQ=WEEKLY;COUNT=3;BYDAY=MO',
            'need_sync': False,
            'base_event_id': event.id,
            'calendar_event_ids': [(4, event.id)],
        })
        recurrence._apply_recurrence()
        recurrence.calendar_event_ids.attendee_ids.state = 'accepted'
        mails = sorted(set(event.attendee_ids.mapped('email')))
        self.assertEqual(mails, ['dalton@example.com', 'odoobot@example.com'])
        gevent = GoogleEvent([{
            'id': google_id,
            'description': 'coucou',
            "updated": self.now,
            'organizer': {'email': 'odoobot@example.com', 'self': True},
            'summary': False,
            'visibility': 'public',
            'attendees': [],
            'reminders': {'useDefault': True},
            'extendedProperties': {'shared': {'%s_odoo_id' % self.env.cr.dbname: event.id, }},
            'recurrence': ['RRULE:FREQ=WEEKLY;COUNT=3;BYDAY=MO'],
            'start': {
                'dateTime': '2020-01-13T16:00:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
            'end': {
                'dateTime': '2020-01-13T20:00:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None
            },
        }])
        self.sync(gevent)
        # User attendee removed but gevent owner might be added after synch.
        mails = event.attendee_ids.mapped('email')
        self.assertFalse(mails)

        self.assertGoogleAPINotCalled()

    def test_several_users_have_the_same_mail(self):
        # We want to chose the internal user
        user1 = new_test_user(self.env, login='test@example.com', groups='base.group_portal')
        user2 = new_test_user(self.env, login='calendar-user2')
        user2.partner_id.email = 'test@example.com'
        user1.partner_id.name = "A First in alphabet"
        user2.partner_id.name = "B Second in alphabet"
        values = {
            'id': "abcd",
            'description': 'coucou',
            "updated": self.now,
            'organizer': {'email': 'odoobot@example.com', 'self': True},
            'summary': False,
            'visibility': 'public',
            'attendees': [{'email': 'test@example.com', 'responseStatus': 'accepted'}, {'email': 'test2@example.com', 'responseStatus': 'accepted'}],
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2020-01-13T16:00:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
            'end': {
                'dateTime': '2020-01-13T20:00:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
        }
        event = self.env['calendar.event']._sync_google2odoo(GoogleEvent([values]))
        new_partner = self.env['res.partner'].search([('email', '=', 'test2@example.com')])
        self.assertEqual(event.partner_ids.ids, [user2.partner_id.id, new_partner.id], "The internal user should be chosen")

    @patch_api
    def test_event_with_meeting_url(self):
        values = {
            'id': 'oj44nep1ldf8a3ll02uip0c9aa',
            'description': 'Small mini desc',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing new update',
            'visibility': 'public',
            'attendees': [{
                'displayName': 'Mitchell Admin',
                'email': self.public_partner.email,
                'responseStatus': 'needsAction'
            },],
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2020-01-13T16:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
            'end': {
                'dateTime': '2020-01-13T19:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None
            },
            'conferenceData': {
                'entryPoints': [{
                    'entryPointType': 'video',
                    'uri': 'https://meet.google.com/odoo-random-test',
                    'label': 'meet.google.com/odoo-random-test'
                }, {
                    'entryPointType': 'more',
                    'uri':'https://tel.meet/odoo-random-test?pin=42424242424242',
                    'pin':'42424242424242'
                }]
            }
        }
        self.env['calendar.event']._sync_google2odoo(GoogleEvent([values]))
        event = self.env['calendar.event'].search([('google_id', '=', values.get('id'))])
        self.assertTrue(event, "It should have created an event")
        self.assertEqual(event.videocall_location, 'https://meet.google.com/odoo-random-test')
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_event_with_local_videocall(self):
        """This makes sure local video call is not discarded if google's meeting url is False"""
        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        event = self.env['calendar.event'].create({
            'name': 'coucou',
            'start': date(2020, 1, 6),
            'stop': date(2020, 1, 6),
            'google_id': google_id,
            'user_id': self.env.user.id,
            'need_sync': False,
            'partner_ids': [(6, 0, self.env.user.partner_id.ids)],
            'videocall_location': 'https://meet.google.com/odoo_local_videocall',
        })
        values = {
            'id': google_id,
            'status': 'confirmed',
            'description': 'Event without meeting url',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Event without meeting url',
            'visibility': 'public',
            'attendees': [{
                'displayName': 'Mitchell Admin',
                'email': self.public_partner.email,
                'responseStatus': 'needsAction'
            },],
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2020-01-13T16:55:00+01:00',
                'timeZone': 'Europe/Brussels'
            },
            'end': {
                'dateTime': '2020-01-13T19:55:00+01:00',
                'timeZone': 'Europe/Brussels'
            },
            'conferenceData': {
                'entryPoints': [{
                    'entryPointType': 'video',
                    'uri': False,
                    'label': 'no label'
                }]
            },
            'updated': self.now,
        }
        # make sure local video call is not discarded
        gevent = GoogleEvent([values])
        self.env['calendar.event']._sync_google2odoo(gevent)
        self.assertEqual(event.videocall_location, 'https://meet.google.com/odoo_local_videocall')

        # now google has meet URL and make sure local video call is updated accordingly
        values['conferenceData']['entryPoints'][0]['uri'] = 'https://meet.google.com/odoo-random-test'
        gevent = GoogleEvent([values])
        self.env['calendar.event']._sync_google2odoo(gevent)
        self.assertEqual(event.videocall_location, 'https://meet.google.com/odoo-random-test')
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_event_with_availability(self):
        values = {
            'id': 'oj44nep1ldf8a3ll02uip0c9aa',
            'description': 'Small mini desc',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing new update',
            'visibility': 'public',
            'attendees': [{
                'displayName': 'Mitchell Admin',
                'email': self.public_partner.email,
                'responseStatus': 'needsAction'
            },],
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2020-01-13T16:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
            'end': {
                'dateTime': '2020-01-13T19:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
            'transparency': 'transparent'
        }
        self.env['calendar.event']._sync_google2odoo(GoogleEvent([values]))
        event = self.env['calendar.event'].search([('google_id', '=', values.get('id'))])
        self.assertTrue(event, "It should have created an event")
        self.assertEqual(event.show_as, 'free')
        self.assertGoogleAPINotCalled

    @patch_api
    def test_private_partner_single_event(self):
        values = {
            'id': 'oj44nep1ldf8a3ll02uip0c9aa',
            'description': 'Small mini desc',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing new update',
            'visibility': 'public',
            'attendees': [{
                'displayName': 'Mitchell Admin',
                'email': self.public_partner.email,
                'responseStatus': 'needsAction'
            }, {
                'displayName': 'Attendee',
                'email': self.private_partner.email,
                'responseStatus': 'needsAction'
            }, ],
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2020-01-13T16:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
            'end': {
                'dateTime': '2020-01-13T19:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
        }

        self.env['calendar.event']._sync_google2odoo(GoogleEvent([values]))
        event = self.env['calendar.event'].search([('google_id', '=', values.get('id'))])
        private_attendee = event.attendee_ids.filtered(lambda e: e.email == self.private_partner.email)
        self.assertEqual(self.private_partner.id, private_attendee.partner_id.id)
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_private_contact(self):
        recurrence_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        values = {
            'id': recurrence_id,
            'description': 'Small mini desc',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing new update',
            'visibility': 'public',
            'attendees': [{
                'displayName': 'Attendee',
                'email': self.private_partner.email,
                'responseStatus': 'needsAction'
            }, ],
            'recurrence': ['RRULE:FREQ=WEEKLY;WKST=SU;COUNT=3;BYDAY=MO'],
            'reminders': {'useDefault': True},
            'start': {'date': '2020-01-6'},
            'end': {'date': '2020-01-7'},
        }
        self.env['calendar.recurrence']._sync_google2odoo(GoogleEvent([values]))
        recurrence = self.env['calendar.recurrence'].search([('google_id', '=', values.get('id'))])
        events = recurrence.calendar_event_ids
        private_attendees = events.mapped('attendee_ids').filtered(lambda e: e.email == self.private_partner.email)
        self.assertTrue(all([a.partner_id == self.private_partner for a in private_attendees]))
        self.assertTrue(all([a.partner_id.type != 'private' for a in private_attendees]))
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_alias_email_sync_recurrence(self):
        alias_model = self.env['ir.model'].search([('model', '=', 'calendar.event')])
        mail_alias = self.env['mail.alias'].create({'alias_name': 'sale', 'alias_model_id': alias_model.id})

        google_id = 'oj44nep1ldf8a3ll02uip0c9aa'
        base_event = self.env['calendar.event'].create({
            'name': 'coucou',
            'allday': True,
            'start': datetime(2020, 1, 6),
            'stop': datetime(2020, 1, 6),
            'need_sync': False,
            'user_id': self.env.uid
        })
        recurrence = self.env['calendar.recurrence'].create({
            'google_id': google_id,
            'rrule': 'FREQ=WEEKLY;COUNT=2;BYDAY=MO',
            'need_sync': False,
            'base_event_id': base_event.id,
            'calendar_event_ids': [(4, base_event.id)],
        })
        recurrence._apply_recurrence()
        values = {
            'id': google_id,
            'summary': 'coucou',
            'recurrence': ['RRULE:FREQ=WEEKLY;COUNT=2;BYDAY=MO'],
            'start': {'date': '2020-01-06'},
            'end': {'date': '2020-01-07'},
            'reminders': {'useDefault': True},
            "attendees": [
                {
                    "email": mail_alias.display_name,
                    "responseStatus": "accepted",
                },
            ],
            'updated': self.now,
        }
        self.env['calendar.recurrence']._sync_google2odoo(GoogleEvent([values]))
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 2)
        # Only the event organizer must remain as attendee.
        self.assertEqual(len(events.mapped('attendee_ids')), 1)
        self.assertEqual(events.mapped('attendee_ids')[0].partner_id, self.env.user.partner_id)
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_owner_only_new_google_event(self):
        values = {
            'id': 'oj44nep1ldf8a3ll02uip0c9aa',
            'description': 'Small mini desc',
            'organizer': {'email': 'odoocalendarref@gmail.com', 'self': True},
            'summary': 'Pricing new update',
            'visibility': 'public',
            'attendees': [],
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2020-01-13T16:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
            'end': {
                'dateTime': '2020-01-13T19:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
        }
        self.env['calendar.event']._sync_google2odoo(GoogleEvent([values]))
        event = self.env['calendar.event'].search([('google_id', '=', values.get('id'))])
        self.assertEqual(1, len(event.attendee_ids))
        self.assertEqual(event.partner_ids[0], event.attendee_ids[0].partner_id)
        self.assertEqual('accepted', event.attendee_ids[0].state)
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_partner_order(self):
        self.private_partner.email = "internal_user@odoo.com"
        self.private_partner.type = "contact"
        user = self.env['res.users'].create({
            'name': 'Test user Calendar',
            'login': self.private_partner.email,
            'partner_id': self.private_partner.id,
            'type': 'contact'
        })
        values = {
            'id': 'oj44nep1ldf8a3ll02uip0c9aa',
            'description': 'Small mini desc',
            'organizer': {'email': 'internal_user@odoo.com'},
            'summary': 'Pricing new update',
            'visibility': 'public',
            'attendees': [{
                'displayName': 'Mitchell Admin',
                'email': self.public_partner.email,
                'responseStatus': 'needsAction'
            }, {
                'displayName': 'Attendee',
                'email': self.private_partner.email,
                'responseStatus': 'needsAction',
                'self': True,
            }, ],
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2020-01-13T16:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
            'end': {
                'dateTime': '2020-01-13T19:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None
            },
        }

        self.env['calendar.event'].with_user(user)._sync_google2odoo(GoogleEvent([values]))
        event = self.env['calendar.event'].search([('google_id', '=', values.get('id'))])
        self.assertEqual(2, len(event.partner_ids), "Two attendees and two partners should be associated to the event")
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_range_start_date_in_other_dst_period(self):
        """
            It is possible to create recurring events that are in the same DST period
            but when calculating the start date for the range, it is possible to change the dst period.
            This results in a duplication of the basic event.
        """
        # DST change: 2023-03-26
        frequency = "MONTHLY"
        count = "1" # Just to go into the flow of the recurrence
        recurrence_id = "9lxiofipomymx2yr1yt0hpep99"
        google_value = [{
                "summary": "Start date in DST period",
                "id": recurrence_id,
                "creator": {"email": "john.doe@example.com"},
                "organizer": {"email": "john.doe@example.com"},
                "created": "2023-03-27T11:45:07.000Z",
                "start": {"dateTime": "2023-03-27T09:00:00+02:00", "timeZone": "Europe/Brussels"},
                "end": {"dateTime": "2023-03-27T10:00:00+02:00", "timeZone": "Europe/Brussels"},
                "recurrence": [f"RRULE:FREQ={frequency};COUNT={count}"],
                "reminders": {"useDefault": True},
                "updated": "2023-03-27T11:45:08.547Z",
                'guestsCanModify': True,
            }]
        google_event = GoogleEvent(google_value)
        self.env['calendar.recurrence']._sync_google2odoo(google_event)
        # Get the time slot of the day
        day_start = datetime.fromisoformat(google_event.start["dateTime"]).astimezone(pytz.utc).replace(tzinfo=None).replace(hour=0)
        day_end = datetime.fromisoformat(google_event.end["dateTime"]).astimezone(pytz.utc).replace(tzinfo=None).replace(hour=23)
        # Get created events
        day_events = self.env["calendar.event"].search(
            [
                ("name", "=", google_event.summary),
                ("start", ">=", day_start),
                ("stop", "<=", day_end)
            ]
        )
        self.assertGoogleAPINotCalled()
        # Check for non-duplication
        self.assertEqual(len(day_events), 1)

    @patch_api
    def test_recurrence_edit_specific_event(self):
        google_values = [
            {
                'kind': 'calendar#event',
                'etag': '"3367067678542000"',
                'id': '59orfkiunbn2vlp6c2tndq6ui0',
                'status': 'confirmed',
                'created': '2023-05-08T08:16:54.000Z',
                'updated': '2023-05-08T08:17:19.271Z',
                'summary': 'First title',
                'creator': {'email': 'john.doe@example.com', 'self': True},
                'organizer': {'email': 'john.doe@example.com', 'self': True},
                'start': {'dateTime': '2023-05-12T09:00:00+02:00', 'timeZone': 'Europe/Brussels', 'date': None},
                'end': {'dateTime': '2023-05-12T10:00:00+02:00', 'timeZone': 'Europe/Brussels', 'date': None},
                'recurrence': ['RRULE:FREQ=WEEKLY;WKST=SU;UNTIL=20230518T215959Z;BYDAY=FR'],
                'iCalUID': '59orfkiunbn2vlp6c2tndq6ui0@google.com',
                'reminders': {'useDefault': True},
            },
            {
                'kind': 'calendar#event',
                'etag': '"3367067678542000"',
                'id': '59orfkiunbn2vlp6c2tndq6ui0_R20230519T070000',
                'status': 'confirmed',
                'created': '2023-05-08T08:16:54.000Z',
                'updated': '2023-05-08T08:17:19.271Z',
                'summary': 'Second title',
                'creator': {'email': 'john.doe@example.com', 'self': True},
                'organizer': {'email': 'john.doe@example.com', 'self': True},
                'start': {'dateTime': '2023-05-19T09:00:00+02:00', 'timeZone': 'Europe/Brussels', 'date': None},
                'end': {'dateTime': '2023-05-19T10:00:00+02:00', 'timeZone': 'Europe/Brussels', 'date': None},
                'recurrence': ['RRULE:FREQ=WEEKLY;WKST=SU;COUNT=2;BYDAY=FR'],
                'iCalUID': '59orfkiunbn2vlp6c2tndq6ui0_R20230519T070000@google.com',
                'reminders': {'useDefault': True},
            },
            {
                'kind': 'calendar#event',
                'etag': '"3367067704194000"',
                'id': '59orfkiunbn2vlp6c2tndq6ui0_20230526T070000Z',
                'status': 'confirmed',
                'created': '2023-05-08T08:16:54.000Z',
                'updated': '2023-05-08T08:17:32.097Z',
                'summary': 'Second title',
                'creator': {'email': 'john.doe@example.com', 'self': True},
                'organizer': {'email': 'john.doe@example.com', 'self': True},
                'start': {'dateTime': '2023-05-26T08:00:00+02:00', 'timeZone': 'Europe/Brussels', 'date': None},
                'end': {'dateTime': '2023-05-26T09:00:00+02:00', 'timeZone': 'Europe/Brussels', 'date': None},
                'recurringEventId': '59orfkiunbn2vlp6c2tndq6ui0_R20230519T070000',
                'originalStartTime': {'dateTime': '2023-05-26T09:00:00+02:00', 'timeZone': 'Europe/Brussels'},
                'reminders': {'useDefault': True},
            }
        ]
        google_events = GoogleEvent(google_values)

        recurrent_events = google_events.filter(lambda e: e.is_recurrence())
        specific_event = google_events - recurrent_events
        # recurrence_event: 59orfkiunbn2vlp6c2tndq6ui0 and 59orfkiunbn2vlp6c2tndq6ui0_R20230519T070000
        # specific_event: 59orfkiunbn2vlp6c2tndq6ui0_20230526T070000Z

        # Range to check
        day_start = datetime.fromisoformat(specific_event.start["dateTime"]).astimezone(pytz.utc).replace(tzinfo=None).replace(hour=0)
        day_end = datetime.fromisoformat(specific_event.end["dateTime"]).astimezone(pytz.utc).replace(tzinfo=None).replace(hour=23)

        # Synchronize recurrent events
        self.env['calendar.recurrence']._sync_google2odoo(recurrent_events)
        events = self.env["calendar.event"].search(
            [
                ("name", "=", specific_event.summary),
                ("start", ">=", day_start),
                ("stop", "<=", day_end,)
            ]
        )
        self.assertEqual(len(events), 1)

        # Events:
        # 'First title' --> '59orfkiunbn2vlp6c2tndq6ui0_20230512T070000Z'
        # 'Second title' --> '59orfkiunbn2vlp6c2tndq6ui0_R20230519T070000_20230519T070000Z'
        # 'Second title' --> '59orfkiunbn2vlp6c2tndq6ui0_R20230519T070000_20230526T070000Z'

        # We want to apply change on '59orfkiunbn2vlp6c2tndq6ui0_R20230519T070000_20230526T070000Z'
        # with values from '59orfkiunbn2vlp6c2tndq6ui0_20230526T070000Z'

        # To match the google ids, we create a new event and delete the old one to avoid duplication

        # Synchronize specific event
        self.env['calendar.event']._sync_google2odoo(specific_event)
        events = self.env["calendar.event"].search(
            [
                ("name", "=", specific_event.summary),
                ("start", ">=", day_start),
                ("stop", "<=", day_end,)
            ]
        )
        self.assertEqual(len(events), 1)

        # Not call API
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_recurrence_edit_specific_event_backward_compatibility(self):
        """
            Check that the creation of full recurrence ids does not crash
            to avoid event duplication.
            Note 1:
                Not able to reproduce the payload in practice.
                However, it exists in production.
            Note 2:
                This is the same test as 'test_recurrence_edit_specific_event',
                with the range in 'recurringEventId' removed for the specific event.
        """
        google_values = [
            {
                'kind': 'calendar#event',
                'etag': '"3367067678542000"',
                'id': '59orfkiunbn2vlp6c2tndq6ui0',
                'status': 'confirmed',
                'created': '2023-05-08T08:16:54.000Z',
                'updated': '2023-05-08T08:17:19.271Z',
                'summary': 'First title',
                'creator': {'email': 'john.doe@example.com', 'self': True},
                'organizer': {'email': 'john.doe@example.com', 'self': True},
                'start': {'dateTime': '2023-05-12T09:00:00+02:00', 'timeZone': 'Europe/Brussels', 'date': None},
                'end': {'dateTime': '2023-05-12T10:00:00+02:00', 'timeZone': 'Europe/Brussels', 'date': None},
                'recurrence': ['RRULE:FREQ=WEEKLY;WKST=SU;UNTIL=20230518T215959Z;BYDAY=FR'],
                'iCalUID': '59orfkiunbn2vlp6c2tndq6ui0@google.com',
                'reminders': {'useDefault': True},
            },
            {
                'kind': 'calendar#event',
                'etag': '"3367067678542000"',
                'id': '59orfkiunbn2vlp6c2tndq6ui0_R20230519T070000',
                'status': 'confirmed',
                'created': '2023-05-08T08:16:54.000Z',
                'updated': '2023-05-08T08:17:19.271Z',
                'summary': 'Second title',
                'creator': {'email': 'john.doe@example.com', 'self': True},
                'organizer': {'email': 'john.doe@example.com', 'self': True},
                'start': {'dateTime': '2023-05-19T09:00:00+02:00', 'timeZone': 'Europe/Brussels', 'date': None},
                'end': {'dateTime': '2023-05-19T10:00:00+02:00', 'timeZone': 'Europe/Brussels', 'date': None},
                'recurrence': ['RRULE:FREQ=WEEKLY;WKST=SU;COUNT=2;BYDAY=FR'],
                'iCalUID': '59orfkiunbn2vlp6c2tndq6ui0_R20230519T070000@google.com',
                'reminders': {'useDefault': True},
            },
            {
                'kind': 'calendar#event',
                'etag': '"3367067704194000"',
                'id': '59orfkiunbn2vlp6c2tndq6ui0_20230526T070000Z',
                'status': 'confirmed',
                'created': '2023-05-08T08:16:54.000Z',
                'updated': '2023-05-08T08:17:32.097Z',
                'summary': 'Second title',
                'creator': {'email': 'john.doe@example.com', 'self': True},
                'organizer': {'email': 'john.doe@example.com', 'self': True},
                'start': {'dateTime': '2023-05-26T08:00:00+02:00', 'timeZone': 'Europe/Brussels', 'date': None},
                'end': {'dateTime': '2023-05-26T09:00:00+02:00', 'timeZone': 'Europe/Brussels', 'date': None},
                'recurringEventId': '59orfkiunbn2vlp6c2tndq6ui0', # Range removed
                'originalStartTime': {'dateTime': '2023-05-26T09:00:00+02:00', 'timeZone': 'Europe/Brussels'},
                'reminders': {'useDefault': True},
            }
        ]
        google_events = GoogleEvent(google_values)

        recurrent_events = google_events.filter(lambda e: e.is_recurrence())
        specific_event = google_events - recurrent_events
        # Range to check
        day_start = datetime.fromisoformat(specific_event.start["dateTime"]).astimezone(pytz.utc).replace(tzinfo=None).replace(hour=0)
        day_end = datetime.fromisoformat(specific_event.end["dateTime"]).astimezone(pytz.utc).replace(tzinfo=None).replace(hour=23)

        # Synchronize recurrent events
        self.env['calendar.recurrence']._sync_google2odoo(recurrent_events)
        events = self.env["calendar.event"].search(
            [
                ("name", "=", specific_event.summary),
                ("start", ">=", day_start),
                ("stop", "<=", day_end,)
            ]
        )
        self.assertEqual(len(events), 1)

        # Synchronize specific event
        self.env['calendar.event']._sync_google2odoo(specific_event)
        events = self.env["calendar.event"].search(
            [
                ("name", "=", specific_event.summary),
                ("start", ">=", day_start),
                ("stop", "<=", day_end,)
            ]
        )
        self.assertEqual(len(events), 2) # Two because in this case we does not detect the existing event
        # The stream is not blocking, but there is a duplicate

        # Not call API
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_event_guest_modify_permission(self):
        """
        'guestsCanModify' is a permission set on Google side to allow or forbid guests editing the event.
        This test states that Odoo Calendar:
        1. forbids the updates of non-editable events by guests.
        2. allows editable events being updated by guests.
        3. allows guests to stop and restart their synchronizations with Google Calendars.
        """
        guest_user = new_test_user(self.env, login='calendar-user')

        # Create an event editable only by the organizer. Guests can't modify it.
        not_editable_event_values = {
            'id': 'notEditableEventGoogleId',
            'guestsCanModify': False,
            'description': 'Editable only by organizer',
            'organizer': {'email': self.env.user.email, 'self': True},
            'summary': 'Editable only by organizer',
            'visibility': 'public',
            'attendees': [{
                'displayName': 'Guest User',
                'email': guest_user.email,
                'responseStatus': 'accepted'
            }],
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2023-07-05T16:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None
            },
            'end': {
                'dateTime': '2023-07-05T19:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None
            },
        }
        # Create an event editable by guests and organizer.
        editable_event_values = {
            'id': 'editableEventGoogleId',
            'guestsCanModify': True,
            'description': 'Editable by everyone',
            'organizer': {'email': self.env.user.email, 'self': True},
            'summary': 'Editable by everyone',
            'visibility': 'public',
            'attendees': [{
                'displayName': 'Guest User',
                'email': guest_user.email,
                'responseStatus': 'accepted'
            }],
            'reminders': {'useDefault': True},
            'start': {
                'dateTime': '2023-07-05T16:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
            'end': {
                'dateTime': '2023-07-05T19:55:00+01:00',
                'timeZone': 'Europe/Brussels',
                'date': None,
            },
        }
        # Sync events from Google to Odoo and get them after sync.
        self.env['calendar.event']._sync_google2odoo(GoogleEvent([not_editable_event_values, editable_event_values]))
        not_editable_event = self.env['calendar.event'].search([('google_id', '=', not_editable_event_values.get('id'))])
        editable_event = self.env['calendar.event'].search([('google_id', '=', editable_event_values.get('id'))])

        # Assert that event is created in Odoo with proper values for guests_readonly variable.
        self.assertFalse(editable_event.guests_readonly, "Value 'guestCanModify' received from Google must be True.")
        self.assertTrue(not_editable_event.guests_readonly, "Value 'guestCanModify' received from Google must be False.")

        # Assert that organizer can edit both events.
        self.assertTrue(editable_event.with_user(editable_event.user_id).write({'name': 'Edited by organizer!'}))
        self.assertTrue(not_editable_event.with_user(not_editable_event.user_id).write({'name': 'Edited by organizer!'}))

        # Assert that a validation error is raised when guest updates the not editable event.
        with self.assertRaises(ValidationError):
            self.assertTrue(not_editable_event.with_user(guest_user).write({'name': 'Edited by attendee!'}),
                            "Attendee shouldn't be able to modify event with 'guests_readonly' variable as 'True'.")

        # Assert that normal event can be edited by guest.
        self.assertTrue(editable_event.with_user(guest_user).write({'name': 'Edited by attendee!'}),
                        "Attendee should be able to modify event with 'guests_readonly' variable as 'False'.")

        # Assert that guest user can restart the synchronization of its calendar (containing non-editable events).
        guest_user.sudo().stop_google_synchronization()
        self.assertTrue(guest_user.google_synchronization_stopped)
        guest_user.sudo().restart_google_synchronization()
        self.assertFalse(guest_user.google_synchronization_stopped)

    @patch_api
    def test_attendee_status_is_not_updated_when_syncing_and_time_data_is_not_changed(self):
        recurrence_id = "aaaaaaaa"
        organizer = new_test_user(self.env, login="organizer")
        other_user = new_test_user(self.env, login='calendar_user')
        base_event = self.env['calendar.event'].with_user(organizer).create({
            'name': 'coucou',
            'start': datetime(2020, 1, 6, 9, 0),
            'stop': datetime(2020, 1, 6, 10, 0),
            'need_sync': False,
            'partner_ids': [Command.set([organizer.partner_id.id, other_user.partner_id.id])]
        })
        recurrence = self.env['calendar.recurrence'].with_user(organizer).create({
            'google_id': recurrence_id,
            'rrule': 'FREQ=DAILY;INTERVAL=1;COUNT=3',
            'need_sync': False,
            'base_event_id': base_event.id,
        })
        recurrence._apply_recurrence()

        self.assertTrue(all(len(event.attendee_ids) == 2 for event in recurrence.calendar_event_ids), 'should have 2 attendees in all recurring events')
        organizer_state = recurrence.calendar_event_ids.sorted('start')[0].attendee_ids.filtered(lambda attendee: attendee.partner_id.email == organizer.partner_id.email).state
        self.assertEqual(organizer_state, 'accepted', 'organizer should have accepted')
        values = [{
            'summary': 'coucou',
            'id': recurrence_id,
            'recurrence': ['RRULE:FREQ=DAILY;INTERVAL=1;COUNT=3'],
            'start': {'dateTime': '2020-01-06T10:00:00+01:00', 'date': None},
            'end': {'dateTime': '2020-01-06T11:00:00+01:00', 'date': None},
            'reminders': {'useDefault': True},
            'organizer': {'email': organizer.partner_id.email},
            'attendees': [{'email': organizer.partner_id.email, 'responseStatus': 'accepted'}, {'email': other_user.partner_id.email, 'responseStatus': 'accepted'}],
            'updated': self.now,
        }]
        self.env['calendar.recurrence'].with_user(other_user)._sync_google2odoo(GoogleEvent(values))
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 3, "it should have created a recurrence with 3 events")
        self.assertEqual(events[0].attendee_ids[0].state, 'accepted', 'after google sync, organizer should have accepted status still')
        self.assertGoogleAPINotCalled()

    @patch_api
    def test_create_event_with_default_and_undefined_privacy(self):
        """ Check if google events are created in Odoo when 'default' privacy setting is defined and also when it is not. """
        # Sync events from Google to Odoo after adding the privacy property.
        sample_event_values = {
            'summary': 'Test',
            'start': {'dateTime': '2020-01-06T10:00:00+01:00'},
            'end': {'dateTime': '2020-01-06T11:00:00+01:00'},
            'reminders': {'useDefault': True},
            'organizer': {'email': self.env.user.email},
            'attendees': [{'email': self.env.user.email, 'responseStatus': 'accepted'}],
            'updated': self.now,
        }
        undefined_privacy_event = {'id': 100, **sample_event_values}
        default_privacy_event = {'id': 200, 'privacy': 'default', **sample_event_values}
        self.env['calendar.event']._sync_google2odoo(GoogleEvent([undefined_privacy_event, default_privacy_event]))

        # Ensure that synced events have the correct privacy field in Odoo.
        undefined_privacy_odoo_event = self.env['calendar.event'].search([('google_id', '=', 1)])
        default_privacy_odoo_event = self.env['calendar.event'].search([('google_id', '=', 2)])
        self.assertFalse(undefined_privacy_odoo_event.privacy, "Event with undefined privacy must have False value in privacy field.")
        self.assertFalse(default_privacy_odoo_event.privacy, "Event with default privacy must have False value in privacy field.")

    @patch.object(GoogleCalendarService, 'get_events')
    def test_accepting_recurrent_event_with_this_event_option_synced_by_attendee(self, mock_get_events):
        """
        Test accepting a recurring event with the option "This event" on Google Calendar and syncing the attendee's calendar.
        Ensure that event is accepeted by attendee in Odoo.
        """
        recurrence_id = "abcd1"
        recurrence = self.generate_recurring_event(
            mock_dt="2024-04-20",
            google_id=recurrence_id,
            rrule="FREQ=DAILY;INTERVAL=1;COUNT=4",
            start=datetime(2024, 3, 20, 9, 0),
            stop=datetime(2024, 3, 20, 10, 0),
            partner_ids=[Command.set([self.organizer_user.partner_id.id, self.attendee_user.partner_id.id])],
        )
        google_events = self.google_respond_to_recurrent_event_with_option_this_event(recurrence, 2, 'accepted')
        mock_get_events.return_value = (
            GoogleEvent(google_events), None, [{'method': 'popup', 'minutes': 30}]
        )
        expected_states = ["needsAction", "needsAction", "accepted", "needsAction"]
        with self.mock_datetime_and_now("2024-04-22"):
            self.attendee_user.sudo()._sync_google_calendar(self.google_service)
            attendees = self.env['calendar.attendee'].search([
                ('partner_id', '=', self.attendee_user.partner_id.id)
            ]).sorted(key=lambda r: r.event_id.start)
            for i, expected_state in enumerate(expected_states):
                self.assertEqual(attendees[i].state, expected_state)

    @patch.object(GoogleCalendarService, 'get_events')
    def test_accepting_recurrent_event_with_this_event_option_synced_by_organizer(self, mock_get_events):
        """
        Test accepting a recurring event with the option "This event" on Google Calendar and syncing the organizer's calendar.
        Ensure that event is accepeted by attendee in Odoo.
        """
        recurrence_id = "abcd2"
        recurrence = self.generate_recurring_event(
            mock_dt="2024-04-20",
            google_id=recurrence_id,
            rrule="FREQ=DAILY;INTERVAL=1;COUNT=4",
            start=datetime(2024, 3, 20, 9, 0),
            stop=datetime(2024, 3, 20, 10, 0),
            partner_ids=[Command.set([self.organizer_user.partner_id.id, self.attendee_user.partner_id.id])],
        )
        google_events = self.google_respond_to_recurrent_event_with_option_this_event(recurrence, 2, 'accepted')
        mock_get_events.return_value = (
            GoogleEvent(google_events), None, [{'method': 'popup', 'minutes': 30}]
        )
        expected_states = ["needsAction", "needsAction", "accepted", "needsAction"]
        with self.mock_datetime_and_now("2024-04-22"):
            self.organizer_user.sudo()._sync_google_calendar(self.google_service)
            attendees = self.env['calendar.attendee'].search([
                ('partner_id', '=', self.attendee_user.partner_id.id)
            ]).sorted(key=lambda r: r.event_id.start)
            for i, expected_state in enumerate(expected_states):
                self.assertEqual(attendees[i].state, expected_state)

    @patch.object(GoogleCalendarService, 'get_events')
    def test_accepting_recurrent_event_with_all_events_option_synced_by_attendee(self, mock_get_events):
        """
        Test accepting a recurring event with the option "All events" on Google Calendar and syncing the attendee's calendar.
        Ensure that all events are accepeted by attendee in Odoo.
        """
        recurrence_id = "abcd3"
        recurrence = self.generate_recurring_event(
            mock_dt="2024-04-20",
            google_id=recurrence_id,
            rrule="FREQ=DAILY;INTERVAL=1;COUNT=4",
            start=datetime(2024, 3, 20, 9, 0),
            stop=datetime(2024, 3, 20, 10, 0),
            partner_ids=[Command.set([self.organizer_user.partner_id.id, self.attendee_user.partner_id.id])],
        )
        google_events = self.google_respond_to_recurrent_event_with_option_all_events(recurrence, "accepted")
        mock_get_events.return_value = (
            GoogleEvent(google_events), None, [{'method': 'popup', 'minutes': 30}]
        )
        expected_states = ["accepted", "accepted", "accepted", "accepted"]
        with self.mock_datetime_and_now("2024-04-22"):
            self.attendee_user.sudo()._sync_google_calendar(self.google_service)
            attendees = self.env['calendar.attendee'].search([
                ('partner_id', '=', self.attendee_user.partner_id.id)
            ]).sorted(key=lambda r: r.event_id.start)
            for i, expected_state in enumerate(expected_states):
                self.assertEqual(attendees[i].state, expected_state)

    @patch.object(GoogleCalendarService, 'get_events')
    def test_accepting_recurrent_event_with_all_events_option_synced_by_organizer(self, mock_get_events):
        """
        Test accepting a recurring event with the option "All events" on Google Calendar and syncing the organizer's calendar.
        Ensure that all events are accepeted by attendee in Odoo.
        """
        recurrence_id = "abcd4"
        recurrence = self.generate_recurring_event(
            mock_dt="2024-04-20",
            google_id=recurrence_id,
            rrule="FREQ=DAILY;INTERVAL=1;COUNT=4",
            start=datetime(2024, 3, 20, 9, 0),
            stop=datetime(2024, 3, 20, 10, 0),
            partner_ids=[Command.set([self.organizer_user.partner_id.id, self.attendee_user.partner_id.id])],
        )
        google_events = self.google_respond_to_recurrent_event_with_option_all_events(recurrence, "accepted")
        mock_get_events.return_value = (
            GoogleEvent(google_events), None, [{'method': 'popup', 'minutes': 30}]
        )
        expected_states = ["accepted", "accepted", "accepted", "accepted"]
        with self.mock_datetime_and_now("2024-04-22"):
            self.organizer_user.sudo()._sync_google_calendar(self.google_service)
            attendees = self.env['calendar.attendee'].search([
                ('partner_id', '=', self.attendee_user.partner_id.id)
            ]).sorted(key=lambda r: r.event_id.start)
            for i, expected_state in enumerate(expected_states):
                self.assertEqual(attendees[i].state, expected_state)

    @patch.object(GoogleCalendarService, 'get_events')
    def test_accepting_recurrent_event_with_following_events_option_synced_by_attendee(self, mock_get_events):
        """
        Test accepting a recurring event with the option "This and following events" on Google Calendar and syncing the attendee's calendar.
        Ensure that affected events are accepeted by attendee in Odoo.
        """
        recurrence_id = "abcd5"
        recurrence = self.generate_recurring_event(
            mock_dt="2024-04-20",
            google_id=recurrence_id,
            rrule="FREQ=DAILY;INTERVAL=1;COUNT=4",
            start=datetime(2024, 3, 20, 9, 0),
            stop=datetime(2024, 3, 20, 10, 0),
            partner_ids=[Command.set([self.organizer_user.partner_id.id, self.attendee_user.partner_id.id])],
        )
        google_events = self.google_respond_to_recurrent_event_with_option_following_events(
            recurrence=recurrence,
            event_index=2,
            response_status="accepted",
            rrule1="RRULE:FREQ=DAILY;UNTIL=20240321T215959Z",
            rrule2="RRULE:FREQ=DAILY;COUNT=2"
        )
        mock_get_events.return_value = (
            GoogleEvent(google_events), None, [{'method': 'popup', 'minutes': 30}]
        )
        expected_states = ["needsAction", "needsAction", "accepted", "accepted"]
        with self.mock_datetime_and_now("2024-04-22"):
            self.attendee_user.sudo()._sync_google_calendar(self.google_service)
            attendees = self.env['calendar.attendee'].search([
                ('partner_id', '=', self.attendee_user.partner_id.id)
            ]).sorted(key=lambda r: r.event_id.start)
            for i, expected_state in enumerate(expected_states):
                self.assertEqual(attendees[i].state, expected_state)

    @patch.object(GoogleCalendarService, 'get_events')
    def test_accepting_recurrent_event_with_all_following_option_synced_by_organizer(self, mock_get_events):
        """
        Test accepting a recurring event with the option "This and following events" on Google Calendar and syncing the organizer's calendar.
        Ensure that affected events are accepeted by attendee in Odoo.
        """
        recurrence_id = "abcd6"
        recurrence = self.generate_recurring_event(
            mock_dt="2024-04-20",
            google_id=recurrence_id,
            rrule="FREQ=DAILY;INTERVAL=1;COUNT=4",
            start=datetime(2024, 3, 20, 9, 0),
            stop=datetime(2024, 3, 20, 10, 0),
            partner_ids=[Command.set([self.organizer_user.partner_id.id, self.attendee_user.partner_id.id])],
        )
        google_events = self.google_respond_to_recurrent_event_with_option_following_events(
            recurrence=recurrence,
            event_index=2,
            response_status="accepted",
            rrule1="RRULE:FREQ=DAILY;UNTIL=20240321T215959Z",
            rrule2="RRULE:FREQ=DAILY;COUNT=2"
        )
        mock_get_events.return_value = (
            GoogleEvent(google_events), None, [{'method': 'popup', 'minutes': 30}]
        )
        expected_states = ["needsAction", "needsAction", "accepted", "accepted"]
        with self.mock_datetime_and_now("2024-04-22"):
            self.organizer_user.sudo()._sync_google_calendar(self.google_service)
            attendees = self.env['calendar.attendee'].search([
                ('partner_id', '=', self.attendee_user.partner_id.id)
            ]).sorted(key=lambda r: r.event_id.start)
            for i, expected_state in enumerate(expected_states):
                self.assertEqual(attendees[i].state, expected_state)

    @patch_api
    def test_keep_organizer_attendee_writing_recurrence_from_google(self):
        """
        When receiving recurrence updates from google in 'write_from_google', make
        sure the organizer is kept as attendee of the events. This will guarantee
        that the newly updated events will not disappear from the calendar view.
        """
        def check_organizer_as_single_attendee(self, recurrence, organizer):
            """ Ensure that the organizer is the single attendee of the recurrent events. """
            for event in recurrence.calendar_event_ids:
                self.assertTrue(len(event.attendee_ids) == 1, 'Should have only one attendee.')
                self.assertEqual(event.attendee_ids[0].partner_id, organizer.partner_id, 'The single attendee must be the organizer.')

        # Generate a regular recurrence with only the organizer as attendee.
        recurrence_id = "rec_id"
        recurrence = self.generate_recurring_event(
            mock_dt="2024-04-10",
            google_id=recurrence_id,
            rrule="FREQ=DAILY;INTERVAL=1;COUNT=4",
            start=datetime(2024, 4, 11, 9, 0),
            stop=datetime(2024, 4, 11, 10, 0),
            partner_ids=[Command.set([self.organizer_user.partner_id.id])],
        )
        check_organizer_as_single_attendee(self, recurrence, self.organizer_user)

        # Update the recurrence without specifying its attendees, the organizer must be kept as
        # attendee after processing it, thus the new events will be kept in its calendar view.
        values = [{
            'summary': 'updated_rec',
            'id': recurrence_id,
            'recurrence': ['RRULE:FREQ=DAILY;INTERVAL=1;COUNT=3'],
            'start': {'dateTime': '2024-04-13T8:00:00+01:00'},
            'end': {'dateTime': '2024-04-13T9:00:00+01:00'},
            'reminders': {'useDefault': True},
            'organizer': {'email': self.organizer_user.partner_id.email},
            'attendees': [],
            'updated': self.now,
        }]
        self.env['calendar.recurrence'].with_user(self.organizer_user)._sync_google2odoo(GoogleEvent(values))
        events = recurrence.calendar_event_ids.sorted('start')
        self.assertEqual(len(events), 3, "The new recurrence must have three events.")
        check_organizer_as_single_attendee(self, recurrence, self.organizer_user)
        self.assertGoogleAPINotCalled()