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
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
use std::collections::{HashMap, HashSet, VecDeque};
use std::num::NonZeroU32;
use anyhow::{Context, bail};
use bon::Builder;
use chrono::{DateTime, Utc};
use uuid::Uuid;
use crate::{
duration::NonNegativeDuration,
identifiable,
money::MultiCurrencyAmount,
resources::{Purchase, Resource},
stakeholders::Stakeholder,
task::Task,
};
#[derive(Debug, Default, Builder)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[builder(on(String, into))]
/// Represents a project with a name and a list of resources.
pub struct Project {
/// The name of the project.
name: String,
/// The description of the project.
description: Option<String>,
/// The start date of the project.
start_date: Option<DateTime<Utc>>,
/// The end date of the project.
end_date: Option<DateTime<Utc>>,
/// The tasks associated with the project, in the order they were added.
#[builder(default)]
tasks: Vec<Task>,
/// Successor relationships for the time-relationship DAG.
#[builder(default)]
succ: HashMap<Uuid, Vec<(Uuid, TimeRelationship)>>,
/// Predecessor relationships for the time-relationship DAG.
#[builder(default)]
pred: HashMap<Uuid, Vec<(Uuid, TimeRelationship)>>,
/// Subtask tree: parent -> children.
#[builder(default)]
children: HashMap<Uuid, Vec<Uuid>>,
/// Subtask tree: child -> parent.
#[builder(default)]
parent_of: HashMap<Uuid, Uuid>,
/// The resources the project pays for, in the order they were added. One-time purchase
/// costs are recorded here; tasks engage them via [`Self::assign_resource`].
#[builder(default)]
resources: Vec<Resource>,
/// The list of stakeholders associated with the project.
#[builder(default)]
stakeholders: Vec<Stakeholder>,
}
#[derive(Debug, Default, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// The predecessor - successor relationship between tasks.
pub enum TimeRelationship {
/// The predecessor has to start for the successor to finish.
StartToFinish,
/// The predecessor has to finish for the successor to finish.
FinishToFinish,
#[default]
/// The predecessor has to finish for the successor to start.
FinishToStart,
/// The predecessor has to start for the successor to start.
StartToStart,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
/// The direction of a relationship update.
pub enum RelDir {
/// Update the predecessors of a task.
Predecessors,
/// Update the successors of a task.
Successors,
}
impl Project {
/// Creates a new project with the given name.
///
/// # Arguments
///
/// * `name` - The name of the project.
///
/// # Returns
///
/// A new `Project` instance.
///
/// # Example
///
/// ```
/// use planter_core::project::Project;
///
/// let project = Project::new("World domination");
/// assert_eq!(project.name(), "World domination");
/// ```
#[must_use]
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
..Default::default()
}
}
/// Returns the name of the project.
///
/// # Example
///
/// ```
/// use planter_core::project::Project;
///
/// let project = Project::new("World domination");
/// assert_eq!(project.name(), "World domination");
/// ```
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
/// Returns the description of the project.
///
/// # Example
///
/// ```
/// use planter_core::project::Project;
///
/// let project = Project::new("World domination");
/// assert_eq!(project.description(), None);
/// ```
#[must_use]
pub fn description(&self) -> Option<&str> {
self.description.as_deref()
}
/// Adds a task to the project and returns its stable [`Uuid`].
///
/// Adding a task whose id already exists in the project replaces it in place, without
/// duplicating its slot in [`Self::tasks`].
///
/// # Arguments
///
/// * `task` - The task to add to the project.
///
/// # Returns
///
/// The stable [`Uuid`] assigned to the task.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let id = project.add_task(Task::new("Become world leader"));
/// assert_eq!(project.tasks().count(), 1);
/// ```
pub fn add_task(&mut self, task: Task) -> Uuid {
let id = task.id();
identifiable::upsert(&mut self.tasks, task);
id
}
/// Inserts a new task as a sibling right before `sibling_id` in the task order.
/// If the sibling has a parent, the new task becomes a child of the same parent. This only
/// ever inserts a new task, it never moves an existing one.
///
/// # Errors
///
/// Returns an error if `sibling_id` doesn't exist, or if `task`'s id is already used by
/// another task in the project.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let a = project.add_task(Task::new("Build an army"));
/// let b = project.add_task(Task::new("Train troops"));
/// let c = project.add_sibling_before(Task::new("Gather allies"), b).unwrap();
///
/// let ids: Vec<_> = project.tasks().map(|t| t.id()).collect();
/// assert_eq!(ids, vec![a, c, b]);
/// ```
pub fn add_sibling_before(&mut self, task: Task, sibling_id: Uuid) -> anyhow::Result<Uuid> {
let id = task.id();
identifiable::insert_before(&mut self.tasks, task, sibling_id)?;
if let Some(&parent_id) = self.parent_of.get(&sibling_id) {
self.attach_child(parent_id, id);
}
Ok(id)
}
/// Inserts a new task as a sibling right after `sibling_id` in the task order.
/// If the sibling has a parent, the new task becomes a child of the same parent. This only
/// ever inserts a new task, it never moves an existing one.
///
/// # Errors
///
/// Returns an error if `sibling_id` doesn't exist, or if `task`'s id is already used by
/// another task in the project.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let a = project.add_task(Task::new("Build an army"));
/// let b = project.add_task(Task::new("Train troops"));
/// let c = project.add_sibling_after(Task::new("Gather allies"), a).unwrap();
///
/// let ids: Vec<_> = project.tasks().map(|t| t.id()).collect();
/// assert_eq!(ids, vec![a, c, b]);
/// ```
pub fn add_sibling_after(&mut self, task: Task, sibling_id: Uuid) -> anyhow::Result<Uuid> {
let id = task.id();
identifiable::insert_after(&mut self.tasks, task, sibling_id)?;
if let Some(&parent_id) = self.parent_of.get(&sibling_id) {
self.attach_child(parent_id, id);
}
Ok(id)
}
/// Deletes a task and all references to it from the project. Any direct
/// subtasks of the removed task are promoted to the removed task's own
/// parent (or to top-level, if it had none).
///
/// # Arguments
///
/// * `id` - The [`Uuid`] of the task to remove.
///
/// # Errors
/// Returns an error if the task doesn't exist.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let id = project.add_task(Task::new("Become world leader"));
/// assert_eq!(project.tasks().count(), 1);
/// assert!(project.rm_task(id).is_ok());
/// assert_eq!(project.tasks().count(), 0);
/// ```
pub fn rm_task(&mut self, id: Uuid) -> anyhow::Result<Task> {
let task = identifiable::remove_by_id(&mut self.tasks, id)
.context("Tried removing a non existing task")?;
// Remove all time relationships involving this task.
for (succ, _) in self.succ.remove(&id).into_iter().flatten() {
if let Some(preds) = self.pred.get_mut(&succ) {
preds.retain(|(p, _)| *p != id);
}
}
for (pred_, _) in self.pred.remove(&id).into_iter().flatten() {
if let Some(succs) = self.succ.get_mut(&pred_) {
succs.retain(|(s, _)| *s != id);
}
}
// Remove subtask relationships. `id`'s own parent link is dropped, and any direct
// children of `id` are promoted to `id`'s former parent (or to top-level if it had
// none), via the same [`Self::detach_child`]/[`Self::attach_child`] pair
// [`Self::add_subtask`] and [`Self::remove_subtask`] use.
let former_parent = self.detach_child(id);
if let Some(children) = self.children.remove(&id) {
for child in children {
match former_parent {
Some(parent) => self.attach_child(parent, child),
None => {
self.parent_of.remove(&child);
}
}
}
}
Ok(task)
}
/// Gets a reference to the task with the given [`Uuid`].
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let id = project.add_task(Task::new("Become world leader"));
/// assert_eq!(project.task(id).unwrap().name(), "Become world leader");
/// ```
#[must_use]
pub fn task(&self, id: Uuid) -> Option<&Task> {
identifiable::find(&self.tasks, id)
}
/// Internal handle used to implement the `edit_task_*` methods below and other mutations
/// that need direct field access. Not exposed publicly: every public edit goes through a
/// method here that knows what else (ancestor sync, and so on) needs to happen alongside it.
fn task_mut(&mut self, id: Uuid) -> Option<&mut Task> {
identifiable::find_mut(&mut self.tasks, id)
}
/// Returns the tasks of the project in insertion order.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// project.add_task(Task::new("Become world leader"));
/// assert_eq!(project.tasks().count(), 1);
/// ```
pub fn tasks(&self) -> impl Iterator<Item = &Task> {
self.tasks.iter()
}
/// Adds a relationship between tasks, where one is the predecessor and the other a successor.
///
/// # Arguments
///
/// * `predecessor` - The [`Uuid`] of the predecessor task.
/// * `successor` - The [`Uuid`] of the successor task.
/// * `kind` - The type of relationship.
///
/// # Errors
/// Returns an error if either task doesn't exist, if the relationship already exists, if
/// the relationship would create a cycle, or if one task is a subtask ancestor/descendant
/// of the other.
///
/// # Example
///
/// ```
/// use planter_core::{project::{Project, TimeRelationship}, task::Task};
///
/// let mut project = Project::new("World domination");
/// let pred = project.add_task(Task::new("Get rich"));
/// let succ = project.add_task(Task::new("Become world leader"));
/// project.add_time_relationship(pred, succ, TimeRelationship::default());
///
/// assert_eq!(project.successors(pred).next().unwrap().name(), "Become world leader")
/// ```
pub fn add_time_relationship(
&mut self,
predecessor: Uuid,
successor: Uuid,
kind: TimeRelationship,
) -> anyhow::Result<()> {
if !identifiable::contains(&self.tasks, predecessor)
|| !identifiable::contains(&self.tasks, successor)
{
bail!("Task not found");
}
if self
.succ
.get(&predecessor)
.map(|e| e.iter().any(|(s, _)| *s == successor))
.unwrap_or(false)
{
bail!("Relationship between tasks already exists");
}
self.validate_edge(predecessor, successor)?;
self.add_one_edge(predecessor, successor, kind);
Ok(())
}
/// Checks that adding a predecessor -> successor edge is legal: neither task is the other's
/// subtask ancestor/descendant, and the edge wouldn't create a cycle. Shared by
/// [`Self::add_time_relationship`] and [`Self::update_relationships`], which both add edges
/// one at a time and need the same guard before each.
fn validate_edge(&self, predecessor: Uuid, successor: Uuid) -> anyhow::Result<()> {
self.reject_ancestor_descendant_pair(predecessor, successor)?;
if self.would_cycle(successor, predecessor) {
bail!("A cycle was detected between tasks {predecessor} and {successor}");
}
Ok(())
}
/// Removes a relationship between tasks.
///
/// # Arguments
///
/// * `predecessor` - The [`Uuid`] of the predecessor task.
/// * `successor` - The [`Uuid`] of the successor task.
///
/// # Errors
/// Returns an error if no relationship exists between the tasks.
///
/// # Example
///
/// ```
/// use planter_core::{project::{Project, TimeRelationship}, task::Task};
///
/// let mut project = Project::new("World domination");
/// let pred = project.add_task(Task::new("Get rich"));
/// let succ = project.add_task(Task::new("Become world leader"));
/// project.add_time_relationship(pred, succ, TimeRelationship::default());
/// project.rm_time_relationship(pred, succ).unwrap();
///
/// assert_eq!(project.successors(pred).count(), 0);
/// ```
pub fn rm_time_relationship(
&mut self,
predecessor: Uuid,
successor: Uuid,
) -> anyhow::Result<()> {
let exists = self
.succ
.get(&predecessor)
.map(|e| e.iter().any(|(s, _)| *s == successor))
.unwrap_or(false);
if !exists {
bail!("Tried to remove a relationship that doesn't exist");
}
self.remove_one_edge(predecessor, successor);
Ok(())
}
/// Gets the successors of a given task.
///
/// # Example
///
/// ```
/// use planter_core::{project::{Project, TimeRelationship}, task::Task};
///
/// let mut project = Project::new("World domination");
/// let pred = project.add_task(Task::new("Get rich"));
/// let succ = project.add_task(Task::new("Become world leader"));
/// project.add_time_relationship(pred, succ, TimeRelationship::default());
///
/// assert_eq!(project.successors(pred).next().unwrap().name(), "Become world leader")
/// ```
pub fn successors(&self, id: Uuid) -> impl Iterator<Item = &Task> {
self.succ
.get(&id)
.into_iter()
.flatten()
.filter_map(move |(succ_id, _)| identifiable::find(&self.tasks, *succ_id))
}
/// Gets the [`Uuid`]s of all successors for a given task.
///
/// # Example
///
/// ```
/// use planter_core::{project::{Project, TimeRelationship}, task::Task};
///
/// let mut project = Project::new("World domination");
/// let pred = project.add_task(Task::new("Get rich"));
/// let succ = project.add_task(Task::new("Become world leader"));
/// project.add_time_relationship(pred, succ, TimeRelationship::default());
///
/// assert_eq!(project.successors_ids(pred).next().unwrap(), succ)
/// ```
pub fn successors_ids(&self, id: Uuid) -> impl Iterator<Item = Uuid> {
self.succ
.get(&id)
.into_iter()
.flatten()
.map(|(succ_id, _)| *succ_id)
}
/// Gets the predecessors of a given task.
///
/// # Example
///
/// ```
/// use planter_core::{project::{Project, TimeRelationship}, task::Task};
///
/// let mut project = Project::new("World domination");
/// let pred = project.add_task(Task::new("Get rich"));
/// let succ = project.add_task(Task::new("Become world leader"));
/// project.add_time_relationship(pred, succ, TimeRelationship::default());
///
/// assert_eq!(project.predecessors(succ).next().unwrap().name(), "Get rich")
/// ```
pub fn predecessors(&self, id: Uuid) -> impl Iterator<Item = &Task> {
self.pred
.get(&id)
.into_iter()
.flatten()
.filter_map(move |(pred_id, _)| identifiable::find(&self.tasks, *pred_id))
}
/// Gets the [`Uuid`]s of all predecessors for a given task.
///
/// # Example
///
/// ```
/// use planter_core::{project::{Project, TimeRelationship}, task::Task};
///
/// let mut project = Project::new("World domination");
/// let pred = project.add_task(Task::new("Get rich"));
/// let succ = project.add_task(Task::new("Become world leader"));
/// project.add_time_relationship(pred, succ, TimeRelationship::default());
///
/// assert_eq!(project.predecessors_ids(succ).next().unwrap(), pred)
/// ```
pub fn predecessors_ids(&self, id: Uuid) -> impl Iterator<Item = Uuid> {
self.pred
.get(&id)
.into_iter()
.flatten()
.map(|(pred_id, _)| *pred_id)
}
/// Sets the predecessors or successors of a task to exactly the given set of tasks.
///
/// # Arguments
///
/// * `task_id` - The [`Uuid`] of the task whose relationships need updating.
/// * `ids` - The tasks to set as predecessors or successors.
/// * `dir` - Whether to update predecessors or successors.
/// * `kind` - The type of time relationship.
///
/// # Errors
///
/// Returns an error if:
/// * Any task doesn't exist.
/// * The update would create a cycle.
/// * Any id in `ids` is a subtask ancestor/descendant of `task_id`.
///
/// # Example
///
/// ```
/// use planter_core::{project::{Project, RelDir, TimeRelationship}, task::Task};
///
/// let mut project = Project::new("World domination");
/// let id0 = project.add_task(Task::new("Become world leader"));
/// let id1 = project.add_task(Task::new("Get rich"));
/// let id2 = project.add_task(Task::new("Be evil"));
///
/// project.update_relationships(id2, &[id0, id1], RelDir::Predecessors, TimeRelationship::FinishToStart).unwrap();
/// assert_eq!(project.predecessors(id2).count(), 2);
/// ```
pub fn update_relationships(
&mut self,
task_id: Uuid,
ids: &[Uuid],
dir: RelDir,
kind: TimeRelationship,
) -> anyhow::Result<()> {
if !identifiable::contains(&self.tasks, task_id) {
bail!("Task {task_id} doesn't exist");
}
for &id in ids {
if !identifiable::contains(&self.tasks, id) {
bail!("Task {id} doesn't exist");
}
}
let old: HashSet<Uuid> = match dir {
RelDir::Predecessors => self.predecessors_ids(task_id).collect(),
RelDir::Successors => self.successors_ids(task_id).collect(),
};
let new: HashSet<Uuid> = ids.iter().copied().collect();
let to_add: Vec<Uuid> = ids.iter().filter(|i| !old.contains(i)).copied().collect();
let to_remove: Vec<Uuid> = old.iter().filter(|i| !new.contains(i)).copied().collect();
let mut added = Vec::new();
for &i in &to_add {
let (pred, succ) = match dir {
RelDir::Predecessors => (i, task_id),
RelDir::Successors => (task_id, i),
};
if let Err(e) = self.validate_edge(pred, succ) {
for &(p, s) in &added {
self.remove_one_edge(p, s);
}
return Err(e);
}
self.add_one_edge(pred, succ, kind);
added.push((pred, succ));
}
for &i in &to_remove {
let (pred, succ) = match dir {
RelDir::Predecessors => (i, task_id),
RelDir::Successors => (task_id, i),
};
self.remove_one_edge(pred, succ);
}
Ok(())
}
/// Moves `id` right after `after_id` in the global task order, affecting display order.
///
/// # Errors
///
/// Returns an error if `id` or `after_id` doesn't exist, or if they're the same task (there's
/// nothing to move relative to).
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let a = project.add_task(Task::new("Build an army"));
/// let b = project.add_task(Task::new("Train troops"));
/// let c = project.add_task(Task::new("Gather allies"));
/// project.move_task_after(c, a).unwrap();
///
/// let ids: Vec<_> = project.tasks().map(|t| t.id()).collect();
/// assert_eq!(ids, vec![a, c, b]);
/// ```
pub fn move_task_after(&mut self, id: Uuid, after_id: Uuid) -> anyhow::Result<()> {
identifiable::move_after(&mut self.tasks, id, after_id)
}
/// Adds a subtask to a given task, marking the child as a component of the parent.
/// The parent task is completed when all children are completed.
///
/// # Arguments
///
/// * `parent_id` - The [`Uuid`] of the parent task.
/// * `child_id` - The [`Uuid`] of the child subtask.
///
/// # Errors
///
/// Returns an error if either task doesn't exist.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let parent = project.add_task(Task::new("Build a house"));
/// let child1 = project.add_task(Task::new("Lay foundations"));
/// let child2 = project.add_task(Task::new("Build roof"));
///
/// project.add_subtask(parent, child1).unwrap();
/// project.add_subtask(parent, child2).unwrap();
/// assert_eq!(project.subtasks(parent).count(), 2);
/// ```
pub fn add_subtask(&mut self, parent_id: Uuid, child_id: Uuid) -> anyhow::Result<()> {
if !identifiable::contains(&self.tasks, parent_id)
|| !identifiable::contains(&self.tasks, child_id)
{
bail!("Task not found");
}
if parent_id == child_id {
bail!("A task cannot be a subtask of itself");
}
// No-op if already a child of this parent.
if self.parent_of.get(&child_id) == Some(&parent_id) {
return Ok(());
}
// Reject if parent is already a descendant of child (cycle).
let mut current = parent_id;
while let Some(&ancestor) = self.parent_of.get(¤t) {
if ancestor == child_id {
bail!("Cannot make a task a subtask of one of its own descendants");
}
current = ancestor;
}
// Remove from any existing parent first.
self.detach_child(child_id);
self.attach_child(parent_id, child_id);
Ok(())
}
/// Removes `child_id`'s parent link, if it has one, and cleans up the former parent's
/// children list too (dropping the entry entirely once it's empty). Returns the former
/// parent, or `None` if `child_id` wasn't anyone's subtask.
fn detach_child(&mut self, child_id: Uuid) -> Option<Uuid> {
let parent = self.parent_of.remove(&child_id)?;
if let Some(children) = self.children.get_mut(&parent) {
children.retain(|c| *c != child_id);
if children.is_empty() {
self.children.remove(&parent);
}
}
Some(parent)
}
/// Records `child_id` as a subtask of `parent_id`. Doesn't check for an existing parent
/// link; call [`Self::detach_child`] first if `child_id` might already have one.
fn attach_child(&mut self, parent_id: Uuid, child_id: Uuid) {
self.children.entry(parent_id).or_default().push(child_id);
self.parent_of.insert(child_id, parent_id);
}
/// Removes a subtask relationship, promoting the child back to a top-level task.
///
/// # Errors
///
/// Returns an error if the task is not a subtask.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let army = project.add_task(Task::new("Build an army"));
/// let supplies = project.add_task(Task::new("Gather supplies"));
/// project.add_subtask(army, supplies).unwrap();
/// assert!(project.task_parent(supplies).is_some());
///
/// project.remove_subtask(supplies).unwrap();
/// assert!(project.task_parent(supplies).is_none());
/// ```
pub fn remove_subtask(&mut self, child_id: Uuid) -> anyhow::Result<()> {
self.detach_child(child_id)
.context("Task is not a subtask")?;
Ok(())
}
/// Returns the parent [`Uuid`] of a subtask, or `None` if the task is at root level.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let army = project.add_task(Task::new("Build an army"));
/// let supplies = project.add_task(Task::new("Gather supplies"));
///
/// assert!(project.task_parent(supplies).is_none());
///
/// project.add_subtask(army, supplies).unwrap();
/// assert_eq!(project.task_parent(supplies), Some(army));
/// ```
pub fn task_parent(&self, child_id: Uuid) -> Option<Uuid> {
self.parent_of.get(&child_id).copied()
}
/// Gets the [`Uuid`]s of all subtasks of the given task.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let parent = project.add_task(Task::new("Build a house"));
/// let child = project.add_task(Task::new("Lay foundations"));
/// assert_eq!(project.subtasks(parent).count(), 0);
///
/// project.add_subtask(parent, child).unwrap();
/// assert_eq!(project.subtasks(parent).count(), 1);
/// ```
pub fn subtasks(&self, parent_id: Uuid) -> impl Iterator<Item = Uuid> + '_ {
self.children.get(&parent_id).into_iter().flatten().copied()
}
/// Expands `parent_id`'s own start/finish to encompass its direct children's. Only ever
/// expands outward, never contracts, and has no effect if no child has start/finish dates.
/// One level only: called by [`Self::sync_ancestors`] once per ancestor, walking up to the
/// root, so a chain of parents all end up covering their descendants' dates.
///
/// # Errors
///
/// Returns an error if `parent_id` doesn't exist.
fn sync_parent_dates(&mut self, parent_id: Uuid) -> anyhow::Result<()> {
let earliest_start = self
.subtasks(parent_id)
.filter_map(|child_id| self.task(child_id).and_then(|t| t.start()))
.min();
let latest_finish = self
.subtasks(parent_id)
.filter_map(|child_id| self.task(child_id).and_then(|t| t.finish()))
.max();
if earliest_start.is_none() && latest_finish.is_none() {
return Ok(());
}
let parent = self.task_mut(parent_id).context("Parent task not found")?;
if let Some(start) = earliest_start
&& parent.start().is_none_or(|ps| start < ps)
{
let _ = parent.edit_start(start);
}
if let Some(finish) = latest_finish
&& parent.finish().is_none_or(|pf| finish > pf)
{
let _ = parent.edit_finish(finish);
}
Ok(())
}
/// Rolls a task's start/finish dates up through every ancestor, from its immediate parent to
/// the root. Called automatically by [`Self::edit_task_start`], [`Self::edit_task_finish`],
/// and [`Self::edit_task_duration`]; a top-level task with no parent is a no-op.
fn sync_ancestors(&mut self, task_id: Uuid) {
let mut current = task_id;
while let Some(parent_id) = self.task_parent(current) {
// Infallible here: `task_parent` only ever returns ids of tasks that exist.
let _ = self.sync_parent_dates(parent_id);
current = parent_id;
}
}
/// Sets a task's start date, then rolls the change up through every ancestor so each one's
/// own start/finish keeps covering all of its descendants. If the task has a finish date
/// earlier than `start`, the finish date is pulled forward to match it instead of leaving a
/// negative duration.
///
/// # Errors
///
/// Returns an error if `id` doesn't exist.
///
/// # Example
///
/// ```
/// use chrono::Utc;
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let army = project.add_task(Task::new("Build an army"));
/// let supplies = project.add_task(Task::new("Gather supplies"));
/// project.add_subtask(army, supplies).unwrap();
///
/// let now = Utc::now();
/// project.edit_task_start(supplies, now).unwrap();
///
/// // `army`'s own start followed along automatically, no separate step needed.
/// assert_eq!(project.task(army).unwrap().start(), Some(now));
/// ```
pub fn edit_task_start(&mut self, id: Uuid, start: DateTime<Utc>) -> anyhow::Result<()> {
self.task_mut(id)
.context("Task not found")?
.edit_start(start)?;
self.sync_ancestors(id);
Ok(())
}
/// Sets a task's finish date, then rolls the change up through every ancestor so each one's
/// own start/finish keeps covering all of its descendants. If the task has a start date
/// later than `finish`, the start date is pulled back to match it instead of leaving a
/// negative duration.
///
/// # Errors
///
/// Returns an error if `id` doesn't exist.
///
/// # Example
///
/// ```
/// use chrono::Utc;
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let army = project.add_task(Task::new("Build an army"));
/// let supplies = project.add_task(Task::new("Gather supplies"));
/// project.add_subtask(army, supplies).unwrap();
///
/// let now = Utc::now();
/// project.edit_task_finish(supplies, now).unwrap();
///
/// assert_eq!(project.task(army).unwrap().finish(), Some(now));
/// ```
pub fn edit_task_finish(&mut self, id: Uuid, finish: DateTime<Utc>) -> anyhow::Result<()> {
self.task_mut(id)
.context("Task not found")?
.edit_finish(finish)?;
self.sync_ancestors(id);
Ok(())
}
/// Sets a task's duration, then rolls the change up through every ancestor so each one's
/// own start/finish keeps covering all of its descendants.
///
/// # Errors
///
/// Returns an error if `id` doesn't exist.
///
/// # Example
///
/// ```
/// use chrono::Duration;
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let task_id = project.add_task(Task::new("Build an army"));
/// project.edit_task_duration(task_id, Duration::hours(4).try_into().unwrap()).unwrap();
/// assert!(project.task(task_id).unwrap().duration().is_some());
/// ```
pub fn edit_task_duration(
&mut self,
id: Uuid,
duration: NonNegativeDuration,
) -> anyhow::Result<()> {
self.task_mut(id)
.context("Task not found")?
.edit_duration(duration);
self.sync_ancestors(id);
Ok(())
}
/// Edits a task's name.
///
/// # Errors
///
/// Returns an error if `id` doesn't exist.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let id = project.add_task(Task::new("Become world leader"));
/// project.edit_task_name(id, "Become world's biggest loser").unwrap();
/// assert_eq!(project.task(id).unwrap().name(), "Become world's biggest loser");
/// ```
pub fn edit_task_name(&mut self, id: Uuid, name: impl Into<String>) -> anyhow::Result<()> {
self.task_mut(id).context("Task not found")?.edit_name(name);
Ok(())
}
/// Edits a task's description.
///
/// # Errors
///
/// Returns an error if `id` doesn't exist.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let id = project.add_task(Task::new("Become world leader"));
/// project.edit_task_description(id, "Step one of the plan").unwrap();
/// assert_eq!(project.task(id).unwrap().description(), Some("Step one of the plan"));
/// ```
pub fn edit_task_description(
&mut self,
id: Uuid,
description: impl Into<String>,
) -> anyhow::Result<()> {
self.task_mut(id)
.context("Task not found")?
.edit_description(description);
Ok(())
}
/// Clears a task's description, setting it to `None`.
///
/// # Errors
///
/// Returns an error if `id` doesn't exist.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let id = project.add_task(Task::new("Become world leader"));
/// project.edit_task_description(id, "Step one of the plan").unwrap();
///
/// project.clear_task_description(id).unwrap();
/// assert!(project.task(id).unwrap().description().is_none());
/// ```
pub fn clear_task_description(&mut self, id: Uuid) -> anyhow::Result<()> {
self.task_mut(id)
.context("Task not found")?
.clear_description();
Ok(())
}
/// Toggles a task's completed status.
///
/// # Errors
///
/// Returns an error if `id` doesn't exist.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let id = project.add_task(Task::new("Become world leader"));
/// assert!(!project.task(id).unwrap().completed());
///
/// project.toggle_task_completed(id).unwrap();
/// assert!(project.task(id).unwrap().completed());
/// ```
pub fn toggle_task_completed(&mut self, id: Uuid) -> anyhow::Result<()> {
self.task_mut(id)
.context("Task not found")?
.toggle_completed();
Ok(())
}
/// Returns the start date of the project.
///
/// # Example
///
/// ```
/// use planter_core::project::Project;
/// use chrono::Utc;
///
/// let start_date = Utc::now();
/// let project = Project::builder().name("World domination").start_date(start_date).build();
/// assert_eq!(project.start_date(), Some(start_date));
/// ```
#[must_use]
pub const fn start_date(&self) -> Option<DateTime<Utc>> {
self.start_date
}
/// Returns the end date of the project.
///
/// # Example
///
/// ```
/// use planter_core::project::Project;
/// use chrono::Utc;
///
/// let mut project = Project::new("World domination");
/// assert!(project.end_date().is_none());
/// let end_date = Utc::now();
/// project.set_end_date(end_date);
/// assert_eq!(project.end_date(), Some(end_date));
/// ```
#[must_use]
pub const fn end_date(&self) -> Option<DateTime<Utc>> {
self.end_date
}
/// Sets the end date of the project.
///
/// # Example
///
/// ```
/// use planter_core::project::Project;
/// use chrono::Utc;
///
/// let mut project = Project::new("World domination");
/// let end_date = Utc::now();
/// project.set_end_date(end_date);
/// assert_eq!(project.end_date(), Some(end_date));
/// ```
pub const fn set_end_date(&mut self, end_date: DateTime<Utc>) {
self.end_date = Some(end_date);
}
/// Adds a resource to the project's pool and returns its stable [`Uuid`]. One-time purchase
/// costs belong on the [`Resource`] itself (via [`Resource::add_purchase`]), recorded once
/// regardless of how many tasks engage it via [`Self::assign_resource`].
///
/// Adding a resource whose id already exists in the pool replaces it in place, without
/// duplicating its slot in [`Self::resources`].
///
/// # Arguments
///
/// * `resource` - The resource to add to the project.
///
/// # Example
///
/// ```
/// use planter_core::{resources::Resource, project::Project};
///
/// let mut project = Project::new("World domination");
/// project.add_resource(Resource::new("Stimpack".parse().unwrap()));
/// assert_eq!(project.resources().count(), 1);
/// ```
pub fn add_resource(&mut self, resource: Resource) -> Uuid {
let id = resource.id();
identifiable::upsert(&mut self.resources, resource);
id
}
/// Get a reference to a resource in the project, by its stable [`Uuid`].
///
/// # Example
///
/// ```
/// use planter_core::{resources::Resource, project::Project};
///
/// let mut project = Project::new("World domination");
/// let id = project.add_resource(Resource::new("Stimpack".parse().unwrap()));
///
/// assert!(project.resource(id).is_some());
/// ```
#[must_use]
pub fn resource(&self, id: Uuid) -> Option<&Resource> {
identifiable::find(&self.resources, id)
}
/// Remove a resource from the project, by its stable [`Uuid`]. Any task assignments that
/// referred to it are dropped too, so no task is left pointing at a resource that no longer
/// exists. The returned `(task_id, quantity)` pairs record what those were, so a caller
/// that wants to undo the removal can restore them with [`Self::assign_resource_units`].
///
/// # Errors
///
/// Returns an error if `id` doesn't refer to a resource in [`Self::resources`].
///
/// # Example
///
/// ```
/// use planter_core::{resources::Resource, project::Project};
///
/// let mut project = Project::new("World domination");
/// let id = project.add_resource(Resource::new("Stimpack".parse().unwrap()));
///
/// assert!(project.resource(id).is_some());
/// project.rm_resource(id).unwrap();
/// assert!(project.resource(id).is_none());
/// assert!(project.rm_resource(id).is_err());
/// ```
pub fn rm_resource(&mut self, id: Uuid) -> anyhow::Result<(Resource, Vec<(Uuid, u32)>)> {
let resource =
identifiable::remove_by_id(&mut self.resources, id).context("Resource not found")?;
let assignments = self
.tasks
.iter_mut()
.filter_map(|task| task.unassign(id).map(|quantity| (task.id(), quantity)))
.collect();
Ok((resource, assignments))
}
/// Get a mutable reference to a resource in the project, by its stable [`Uuid`].
///
/// # Example
///
/// ```
/// use planter_core::{resources::Resource, project::Project};
///
/// let mut project = Project::new("World domination");
/// let id = project.add_resource(Resource::new("Crobwar".parse().unwrap()));
///
/// // Fixing a typo in a resource's title:
/// project.resource_mut(id).unwrap().set_title("Crowbar".parse().unwrap());
/// assert_eq!(project.resource(id).unwrap().title(), "Crowbar");
/// ```
#[must_use]
pub fn resource_mut(&mut self, id: Uuid) -> Option<&mut Resource> {
identifiable::find_mut(&mut self.resources, id)
}
/// Returns the list of resources in the project.
///
/// # Example
///
/// ```
/// use planter_core::{resources::Resource, project::Project};
///
/// let mut project = Project::new("World domination");
/// project.add_resource(Resource::new("Crowbar".parse().unwrap()));
/// assert_eq!(project.resources().count(), 1);
/// ```
pub fn resources(&self) -> impl Iterator<Item = &Resource> {
self.resources.iter()
}
/// Records a [`Purchase`] against a resource in the project's pool, returning its
/// [`Purchase::id`]. The project-level counterpart to [`Resource::add_purchase`].
///
/// # Errors
///
/// Returns an error if `resource_id` doesn't refer to a resource in [`Self::resources`].
///
/// # Example
///
/// ```
/// use planter_core::{resources::{Purchase, Resource}, project::Project, money::{Money, Currency}};
///
/// let mut project = Project::new("Build");
/// let stimpack = project.add_resource(Resource::new("Stimpack".parse().unwrap()));
/// project.add_purchase(
/// stimpack,
/// Purchase::builder().quantity(10).unit_price(Money::from_minor_units(400, Currency::EUR)).build(),
/// ).unwrap();
/// assert_eq!(project.resource(stimpack).unwrap().purchases().count(), 1);
/// ```
pub fn add_purchase(&mut self, resource_id: Uuid, purchase: Purchase) -> anyhow::Result<Uuid> {
Ok(self
.resource_mut(resource_id)
.context("Resource not found")?
.add_purchase(purchase))
}
/// Removes a resource's purchase by id, returning it. The project-level counterpart to
/// [`Resource::rm_purchase`].
///
/// # Errors
///
/// Returns an error if `resource_id` doesn't refer to a resource in [`Self::resources`], or
/// if that resource has no purchase with `purchase_id`.
pub fn rm_purchase(
&mut self,
resource_id: Uuid,
purchase_id: Uuid,
) -> anyhow::Result<Purchase> {
self.resource_mut(resource_id)
.context("Resource not found")?
.rm_purchase(purchase_id)
.context("Purchase not found")
}
/// Mutable access to one of a resource's purchases, for editing it in place. The
/// project-level counterpart to [`Resource::purchase_mut`].
///
/// # Errors
///
/// Returns an error if `resource_id` doesn't refer to a resource in [`Self::resources`], or
/// if that resource has no purchase with `purchase_id`.
///
/// # Example
///
/// ```
/// use planter_core::{resources::{Purchase, Resource}, project::Project, money::{Money, Currency}};
///
/// let mut project = Project::new("Build");
/// let stimpack = project.add_resource(Resource::new("Stimpack".parse().unwrap()));
/// let purchase = project.add_purchase(
/// stimpack,
/// Purchase::builder().quantity(10).unit_price(Money::from_minor_units(400, Currency::EUR)).build(),
/// ).unwrap();
/// project.purchase_mut(stimpack, purchase).unwrap().set_unit_price(Money::from_minor_units(420, Currency::EUR));
/// assert_eq!(
/// project.resource(stimpack).unwrap().purchases().next().unwrap().unit_price(),
/// Money::from_minor_units(420, Currency::EUR),
/// );
/// ```
pub fn purchase_mut(
&mut self,
resource_id: Uuid,
purchase_id: Uuid,
) -> anyhow::Result<&mut Purchase> {
self.resource_mut(resource_id)
.context("Resource not found")?
.purchase_mut(purchase_id)
.context("Purchase not found")
}
/// Records that `task_id` engages one unit of `resource_id`, checking that both the task and
/// the resource exist in the project. For more than one unit, use
/// [`Self::assign_resource_units`].
///
/// A task engages any given resource at most once: a second call for the same resource
/// replaces the quantity.
///
/// # Errors
///
/// Returns an error if `task_id` doesn't refer to a task in the project, or if
/// `resource_id` doesn't refer to a resource in [`Self::resources`].
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task, resources::Resource};
///
/// let mut project = Project::new("World domination");
/// let task_id = project.add_task(Task::new("Find a crowbar"));
/// let resource_id = project.add_resource(Resource::new("Crowbar".parse().unwrap()));
///
/// project.assign_resource(task_id, resource_id).unwrap();
/// assert_eq!(project.task(task_id).unwrap().assignments().count(), 1);
/// ```
pub fn assign_resource(&mut self, task_id: Uuid, resource_id: Uuid) -> anyhow::Result<()> {
self.assign_resource_units(task_id, resource_id, NonZeroU32::MIN)
}
/// Records that `task_id` engages `units` of `resource_id`, checking that both the task and
/// the resource exist in the project.
///
/// A task engages any given resource at most once: a second call for the same resource
/// replaces the quantity. `units` is how many of the resource the task draws at once, e.g.
/// 2 of a 4-person crew, or 3 units of a material. To remove an assignment, use
/// [`Self::unassign_resource`] instead of trying to assign zero units.
///
/// # Errors
///
/// Returns an error if `task_id` doesn't refer to a task in the project, or if
/// `resource_id` doesn't refer to a resource in [`Self::resources`].
pub fn assign_resource_units(
&mut self,
task_id: Uuid,
resource_id: Uuid,
units: NonZeroU32,
) -> anyhow::Result<()> {
if !identifiable::contains(&self.resources, resource_id) {
bail!("Resource {resource_id} not found in the project's pool");
}
let task = self.task_mut(task_id).context("Task not found")?;
task.assign(resource_id, units);
Ok(())
}
/// Removes `task_id`'s assignment for `resource_id`, returning the quantity it engaged. The
/// counterpart to [`Self::assign_resource`].
///
/// # Errors
///
/// Returns an error if `task_id` doesn't refer to a task in the project, or if the task
/// didn't engage `resource_id`.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task, resources::Resource};
/// use std::num::NonZeroU32;
///
/// let mut project = Project::new("World domination");
/// let task_id = project.add_task(Task::new("Find a stimpack"));
/// let resource_id = project.add_resource(Resource::new("Stimpack".parse().unwrap()));
/// project.assign_resource_units(task_id, resource_id, NonZeroU32::new(5).unwrap()).unwrap();
///
/// assert_eq!(project.unassign_resource(task_id, resource_id).unwrap(), 5);
/// assert!(project.unassign_resource(task_id, resource_id).is_err());
/// assert_eq!(project.task(task_id).unwrap().assignments().count(), 0);
/// ```
pub fn unassign_resource(&mut self, task_id: Uuid, resource_id: Uuid) -> anyhow::Result<u32> {
self.task_mut(task_id)
.context("Task not found")?
.unassign(resource_id)
.context("Resource not assigned to task")
}
/// Sums the project's total cost: every resource's one-time
/// [`purchase_cost`](Resource::purchase_cost), plus, for every task, each assignment's
/// hourly cost over the task's duration (see [`Self::task_cost`]).
///
/// Each amount is priced in its resource's own currency; amounts in different currencies are
/// kept as separate entries, never combined. Arithmetic saturates instead of overflowing.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// project.add_task(Task::new("Become world leader"));
/// assert!(project.total_cost().is_empty());
/// ```
#[must_use]
pub fn total_cost(&self) -> MultiCurrencyAmount {
let purchases: MultiCurrencyAmount =
self.resources.iter().map(Resource::purchase_cost).sum();
let usage: MultiCurrencyAmount = self.tasks().map(|task| task.cost(&self.resources)).sum();
purchases + usage
}
/// The cost of a single task: each assignment's `hourly_rate * hours * quantity`, priced in
/// the resource's own currency and grouped into a [`MultiCurrencyAmount`]. A resource with
/// no rate, or an assignment whose resource isn't in the project, contributes nothing.
/// One-time purchase costs aren't counted here; those belong to the resource.
///
/// # Errors
///
/// Returns an error if `task_id` doesn't refer to a task in the project.
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task};
///
/// let mut project = Project::new("World domination");
/// let task_id = project.add_task(Task::new("Become world leader"));
/// assert!(project.task_cost(task_id).unwrap().is_empty());
/// ```
pub fn task_cost(&self, task_id: Uuid) -> anyhow::Result<MultiCurrencyAmount> {
Ok(self
.task(task_id)
.context("Task not found")?
.cost(&self.resources))
}
/// The total a single resource has cost the project: its one-time
/// [`purchase_cost`](Resource::purchase_cost) plus its hourly cost across every task that
/// engages it.
///
/// Summing this over every resource gives the same figure as [`Self::total_cost`].
///
/// # Errors
///
/// Returns an error if `resource_id` doesn't refer to a resource in [`Self::resources`].
///
/// # Example
///
/// ```
/// use planter_core::{project::Project, task::Task, resources::{Purchase, Resource}, money::{Currency, Money}};
/// use chrono::Duration;
///
/// let mut project = Project::new("Build");
/// let digger_id = project.add_resource(
/// Resource::new("Crowbar".parse().unwrap()).at_hourly_rate(Money::from_minor_units(30, Currency::EUR)),
/// );
/// project.add_purchase(
/// digger_id,
/// Purchase::builder().quantity(1).unit_price(Money::from_minor_units(1_000, Currency::EUR)).build(),
/// ).unwrap();
///
/// let task_id = project.add_task(Task::new("Dig"));
/// project.edit_task_duration(task_id, Duration::hours(4).try_into().unwrap()).unwrap();
/// project.assign_resource(task_id, digger_id).unwrap();
///
/// // 1000 purchased + 30 * 4h used
/// assert_eq!(
/// project.resource_cost(digger_id).unwrap().in_currency(Currency::EUR),
/// Some(Money::from_minor_units(1_120, Currency::EUR)),
/// );
/// ```
pub fn resource_cost(&self, resource_id: Uuid) -> anyhow::Result<MultiCurrencyAmount> {
let resource = self.resource(resource_id).context("Resource not found")?;
let usage: MultiCurrencyAmount = self
.tasks()
.filter_map(|task| {
let quantity = task.assignment(resource_id)?;
resource.usage_cost(task.duration_hours(), quantity)
})
.sum();
Ok(resource.purchase_cost() + usage)
}
/// Adds a stakeholder to the project.
///
/// # Arguments
///
/// * `stakeholder` - The stakeholder to add to the project.
///
/// # Example
///
/// ```
/// use planter_core::{stakeholders::Stakeholder, project::Project, person::Person};
///
/// let mut project = Project::new("World domination");
/// let person = Person::new("Margherita", "Hack").unwrap();
/// project.add_stakeholder(Stakeholder::Individual {
/// person,
/// description: None,
/// });
/// assert_eq!(project.stakeholders().len(), 1);
/// ```
pub fn add_stakeholder(&mut self, stakeholder: Stakeholder) {
self.stakeholders.push(stakeholder);
}
/// Returns a reference to the list of stakeholders associated with the project.
///
/// # Example
///
/// ```
/// use planter_core::{stakeholders::Stakeholder, project::Project, person::Person};
///
/// let mut project = Project::new("World domination");
/// let person = Person::new("Margherita", "Hack").unwrap();
/// project.add_stakeholder(Stakeholder::Individual {
/// person,
/// description: None,
/// });
/// assert_eq!(project.stakeholders().len(), 1);
/// ```
#[must_use]
pub fn stakeholders(&self) -> &[Stakeholder] {
&self.stakeholders
}
/// Removes a stakeholder from the project by index.
///
/// # Arguments
///
/// * `index` - The index of the stakeholder to remove.
///
/// # Returns
///
/// The removed stakeholder, or `None` if the index is out of bounds.
///
/// # Example
///
/// ```
/// use planter_core::{stakeholders::Stakeholder, project::Project, person::Person};
///
/// let mut project = Project::new("World domination");
/// let person = Person::new("Margherita", "Hack").unwrap();
/// project.add_stakeholder(Stakeholder::Individual { person, description: None });
/// assert_eq!(project.stakeholders().len(), 1);
/// let removed = project.rm_stakeholder(0);
/// assert!(removed.is_some());
/// assert_eq!(project.stakeholders().len(), 0);
/// ```
#[must_use]
pub fn rm_stakeholder(&mut self, index: usize) -> Option<Stakeholder> {
if index < self.stakeholders.len() {
Some(self.stakeholders.remove(index))
} else {
None
}
}
/// Rejects adding a time relationship between `a` and `b` if one is a subtask
/// ancestor/descendant of the other. Shared by [`Self::add_time_relationship`] and
/// [`Self::update_relationships`] so both public entry points enforce the same invariant.
///
/// # Errors
/// Returns an error if `a` is an ancestor of `b`, or vice versa.
fn reject_ancestor_descendant_pair(&self, a: Uuid, b: Uuid) -> anyhow::Result<()> {
if self.is_ancestor(a, b) || self.is_ancestor(b, a) {
bail!(
"Cannot add a predecessor/successor relationship between an ancestor and a descendant"
);
}
Ok(())
}
/// Returns `true` if `ancestor_id` is an ancestor of `descendant_id` in the task tree.
fn is_ancestor(&self, ancestor_id: Uuid, descendant_id: Uuid) -> bool {
let mut seen = HashSet::new();
let mut current = descendant_id;
while let Some(parent) = self.task_parent(current) {
if !seen.insert(parent) {
break;
}
if parent == ancestor_id {
return true;
}
current = parent;
}
false
}
/// BFS from `from` following successors. Returns `true` if `to` is reachable.
fn would_cycle(&self, from: Uuid, to: Uuid) -> bool {
let mut seen = HashSet::new();
let mut q = VecDeque::new();
q.push_back(from);
while let Some(v) = q.pop_front() {
if v == to {
return true;
}
if seen.insert(v)
&& let Some(succs) = self.succ.get(&v)
{
for (s, _) in succs {
q.push_back(*s);
}
}
}
false
}
fn add_one_edge(&mut self, pred: Uuid, succ: Uuid, kind: TimeRelationship) {
self.succ.entry(pred).or_default().push((succ, kind));
self.pred.entry(succ).or_default().push((pred, kind));
}
fn remove_one_edge(&mut self, pred: Uuid, succ: Uuid) {
if let Some(entries) = self.succ.get_mut(&pred) {
entries.retain(|(s, _)| *s != succ);
if entries.is_empty() {
self.succ.remove(&pred);
}
}
if let Some(entries) = self.pred.get_mut(&succ) {
entries.retain(|(p, _)| *p != pred);
if entries.is_empty() {
self.pred.remove(&succ);
}
}
}
}
#[cfg(test)]
/// Utilities to test `[Project]`
pub mod test_utils {
use proptest::{collection, prelude::*};
use crate::task::{Task, test_utils::task_strategy};
use super::{Project, RelDir, TimeRelationship};
const MAX_TASKS: usize = 100;
const MIN_TASKS: usize = 5;
/// Generate a random amount of randomly generated `[Tasks]`.
pub fn tasks_strategy() -> impl Strategy<Value = Vec<Task>> {
collection::vec(task_strategy(), MIN_TASKS..MAX_TASKS)
}
/// Generate a random `[Project]` with a linear chain of time relationships.
pub fn project_graph_strategy() -> impl Strategy<Value = Project> {
(".*", tasks_strategy()).prop_map(|(n, tasks)| {
let mut project = Project::builder().name(n).build();
let mut ids = Vec::new();
for task in tasks {
ids.push(project.add_task(task));
}
let mut previous = None;
for ¤t in &ids {
if let Some(prev) = previous {
project
.update_relationships(
prev,
&[current],
RelDir::Successors,
TimeRelationship::FinishToStart,
)
.unwrap();
}
previous = Some(current);
}
project
})
}
/// Generate a random `[Project]` with no time relationships.
pub fn project_strategy() -> impl Strategy<Value = Project> {
(".*", tasks_strategy()).prop_map(|(n, tasks)| {
let mut project = Project::builder().name(n).build();
for task in tasks {
project.add_task(task);
}
project
})
}
}
#[cfg(test)]
mod tests {
use proptest::prelude::*;
use rand::{RngExt, rng};
use chrono::Utc;
use std::num::NonZeroU32;
use uuid::Uuid;
use crate::{
money::{Currency, Money, MultiCurrencyAmount},
person::Person,
project::{
Project, RelDir, TimeRelationship,
test_utils::{project_graph_strategy, project_strategy},
},
resources::{Purchase, Resource},
stakeholders::Stakeholder,
task::Task,
};
/// Shorthand for a non-zero assignment quantity in tests.
fn nz(n: u32) -> std::num::NonZeroU32 {
std::num::NonZeroU32::new(n).unwrap()
}
fn task_ids(project: &Project) -> Vec<Uuid> {
project.tasks().map(|t| t.id()).collect()
}
proptest! {
#[test]
fn update_relationships_predecessor_rejects_circular_graphs(mut project in project_graph_strategy()) {
let ids = task_ids(&project);
if ids.len() < 2 { return Ok(()); }
let last = *ids.last().unwrap();
assert!(project.update_relationships(ids[0], &[last], RelDir::Predecessors, TimeRelationship::FinishToStart).is_err());
}
#[test]
fn update_relationships_rejects_circular_graphs(mut project in project_graph_strategy()) {
let ids = task_ids(&project);
if ids.len() < 2 { return Ok(()); }
let last = *ids.last().unwrap();
assert!(project.update_relationships(last, &[ids[0]], RelDir::Successors, TimeRelationship::FinishToStart).is_err());
}
#[test]
fn update_relationships_rejects_non_existent_ids(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.is_empty() { return Ok(()); }
let fake = Uuid::new_v4();
assert!(project.update_relationships(ids[0], &[fake], RelDir::Predecessors, TimeRelationship::FinishToStart).is_err());
assert!(project.update_relationships(ids[0], &[fake], RelDir::Successors, TimeRelationship::FinishToStart).is_err());
}
#[test]
fn update_relationships_predecessor_removes_them_if_input_is_empty(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 2 { return Ok(()); }
let mut rng = rng();
let idx1 = rng.random_range(0..ids.len());
let mut idx2 = idx1;
while idx2 == idx1 {
idx2 = rng.random_range(0..ids.len());
}
project.update_relationships(ids[idx1], &[ids[idx2]], RelDir::Predecessors, TimeRelationship::FinishToStart).unwrap();
project.update_relationships(ids[idx1], &[], RelDir::Predecessors, TimeRelationship::FinishToStart).unwrap();
assert_eq!(project.predecessors(ids[idx1]).count(), 0);
}
#[test]
fn update_relationships_predecessor_removes_ids_not_present_in_input(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 3 { return Ok(()); }
let mut rng = rng();
let idx1 = rng.random_range(0..ids.len());
let mut idx2 = idx1;
let mut idx3 = idx1;
while idx2 == idx1 {
idx2 = rng.random_range(0..ids.len());
}
while idx3 == idx1 || idx3 == idx2 {
idx3 = rng.random_range(0..ids.len());
}
project.update_relationships(ids[idx1], &[ids[idx2], ids[idx3]], RelDir::Predecessors, TimeRelationship::FinishToStart).unwrap();
project.update_relationships(ids[idx1], &[ids[idx2]], RelDir::Predecessors, TimeRelationship::FinishToStart).unwrap();
let mut predecessors = project.predecessors(ids[idx1]);
assert_eq!(predecessors.next().map(|t| t.name()), project.task(ids[idx2]).map(|t| t.name()));
assert!(predecessors.next().is_none());
}
#[test]
fn update_relationships_predecessor_works(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 2 { return Ok(()); }
let mut rng = rng();
let idx1 = rng.random_range(0..ids.len());
let mut idx2 = idx1;
while idx2 == idx1 {
idx2 = rng.random_range(0..ids.len());
}
project.update_relationships(ids[idx1], &[ids[idx2]], RelDir::Predecessors, TimeRelationship::FinishToStart).unwrap();
assert_eq!(project.predecessors(ids[idx1]).count(), 1);
assert_eq!(
project.predecessors(ids[idx1]).next().map(|t| t.name()),
project.task(ids[idx2]).map(|t| t.name())
);
}
#[test]
fn update_relationships_works(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 2 { return Ok(()); }
let mut rng = rng();
let idx1 = rng.random_range(0..ids.len());
let mut idx2 = idx1;
while idx2 == idx1 {
idx2 = rng.random_range(0..ids.len());
}
project.update_relationships(ids[idx1], &[ids[idx2]], RelDir::Successors, TimeRelationship::FinishToStart).unwrap();
let mut successors = project.successors(ids[idx1]);
assert_eq!(successors.next().map(|t| t.name()), project.task(ids[idx2]).map(|t| t.name()));
assert!(successors.next().is_none());
}
#[test]
fn update_relationships_removes_them_if_input_is_empty(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 2 { return Ok(()); }
let mut rng = rng();
let idx1 = rng.random_range(0..ids.len());
let mut idx2 = idx1;
while idx2 == idx1 {
idx2 = rng.random_range(0..ids.len());
}
project.update_relationships(ids[idx1], &[ids[idx2]], RelDir::Successors, TimeRelationship::FinishToStart).unwrap();
project.update_relationships(ids[idx1], &[], RelDir::Successors, TimeRelationship::FinishToStart).unwrap();
assert_eq!(project.successors(ids[idx1]).count(), 0);
}
#[test]
fn update_relationships_removes_ids_not_present_in_input(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 3 { return Ok(()); }
let mut rng = rng();
let idx1 = rng.random_range(0..ids.len());
let mut idx2 = idx1;
let mut idx3 = idx1;
while idx2 == idx1 {
idx2 = rng.random_range(0..ids.len());
}
while idx3 == idx1 || idx3 == idx2 {
idx3 = rng.random_range(0..ids.len());
}
project.update_relationships(ids[idx1], &[ids[idx2], ids[idx3]], RelDir::Successors, TimeRelationship::FinishToStart).unwrap();
project.update_relationships(ids[idx1], &[ids[idx2]], RelDir::Successors, TimeRelationship::FinishToStart).unwrap();
let mut successors = project.successors(ids[idx1]);
assert_eq!(successors.next().map(|t| t.name()), project.task(ids[idx2]).map(|t| t.name()));
assert!(successors.next().is_none());
}
}
#[test]
fn update_relationships_rolls_back_partial_additions_on_cycle() {
let mut project = Project::new("test");
let a = project.add_task(Task::new("A"));
let b = project.add_task(Task::new("B"));
let c = project.add_task(Task::new("C"));
let d = project.add_task(Task::new("D"));
project
.add_time_relationship(a, b, TimeRelationship::FinishToStart)
.unwrap();
project
.add_time_relationship(b, c, TimeRelationship::FinishToStart)
.unwrap();
project
.add_time_relationship(c, d, TimeRelationship::FinishToStart)
.unwrap();
let old_preds: Vec<Uuid> = project.predecessors_ids(c).collect();
assert_eq!(old_preds, vec![b]);
let result = project.update_relationships(
c,
&[a, d],
RelDir::Predecessors,
TimeRelationship::FinishToStart,
);
assert!(result.is_err());
let preds: Vec<Uuid> = project.predecessors_ids(c).collect();
assert_eq!(
preds,
vec![b],
"predecessors should be unchanged after rollback"
);
assert!(
!project.predecessors_ids(c).any(|i| i == a),
"partially-added edge a→c should have been rolled back"
);
}
#[test]
fn update_relationships_handles_overlap() {
let mut project = Project::new("test");
let a = project.add_task(Task::new("A"));
let b = project.add_task(Task::new("B"));
let c = project.add_task(Task::new("C"));
let d = project.add_task(Task::new("D"));
project
.update_relationships(
c,
&[a, b],
RelDir::Predecessors,
TimeRelationship::FinishToStart,
)
.unwrap();
let preds: Vec<Uuid> = project.predecessors_ids(c).collect();
assert!(preds.contains(&a), "should contain a, got {preds:?}");
assert!(preds.contains(&b), "should contain b, got {preds:?}");
project
.update_relationships(
c,
&[b, d],
RelDir::Predecessors,
TimeRelationship::FinishToStart,
)
.unwrap();
let preds: Vec<Uuid> = project.predecessors_ids(c).collect();
assert!(preds.contains(&b));
assert!(preds.contains(&d));
assert!(!preds.contains(&a));
}
#[test]
fn assign_resource_rejects_unknown_task_or_resource() {
let mut project = Project::new("test");
let task_id = project.add_task(Task::new("Dig foundation"));
let resource_id = project.add_resource(Resource::new("Crowbar".parse().unwrap()));
// Unknown resource.
assert!(project.assign_resource(task_id, Uuid::new_v4()).is_err());
// Unknown task.
assert!(
project
.assign_resource(Uuid::new_v4(), resource_id)
.is_err()
);
// Both known.
assert!(project.assign_resource(task_id, resource_id).is_ok());
assert_eq!(project.task(task_id).unwrap().assignments().count(), 1);
}
#[test]
fn task_cost_and_resource_cost_error_for_unknown_ids() {
let project = Project::new("test");
assert!(project.task_cost(Uuid::new_v4()).is_err());
assert!(project.resource_cost(Uuid::new_v4()).is_err());
}
#[test]
fn unassign_resource_removes_the_assignment_or_errors() {
let mut project = Project::new("test");
let task_id = project.add_task(Task::new("Dig"));
let id = project.add_resource(Resource::new("Crowbar".parse().unwrap()));
project.assign_resource_units(task_id, id, nz(3)).unwrap();
assert_eq!(project.unassign_resource(task_id, id).unwrap(), 3);
assert_eq!(project.task(task_id).unwrap().assignments().count(), 0);
// Second call: task exists but no longer engages the resource.
assert!(project.unassign_resource(task_id, id).is_err());
// Unknown task.
assert!(project.unassign_resource(Uuid::new_v4(), id).is_err());
}
#[test]
fn assigning_a_resource_a_task_already_engages_replaces_it() {
let mut project = Project::new("test");
let task_id = project.add_task(Task::new("Dig"));
let id = project.add_resource(Resource::new("Crowbar".parse().unwrap()));
project.assign_resource_units(task_id, id, nz(2)).unwrap();
project.assign_resource(task_id, id).unwrap();
let assignments: Vec<_> = project.task(task_id).unwrap().assignments().collect();
assert_eq!(assignments, vec![(id, 1)]);
}
#[test]
fn rm_resource_drops_dangling_assignments() {
let mut project = Project::new("test");
let task_id = project.add_task(Task::new("Find a crowbar"));
let crowbar_id = project.add_resource(Resource::new("Crowbar".parse().unwrap()));
let stimpack_id = project.add_resource(Resource::new("Stimpack".parse().unwrap()));
project.assign_resource(task_id, crowbar_id).unwrap();
project.assign_resource(task_id, stimpack_id).unwrap();
assert_eq!(project.task(task_id).unwrap().assignments().count(), 2);
let (_, dropped_assignments) = project.rm_resource(crowbar_id).unwrap();
assert_eq!(dropped_assignments, vec![(task_id, 1)]);
let remaining: Vec<_> = project.task(task_id).unwrap().assignments().collect();
assert_eq!(remaining, vec![(stimpack_id, 1)]);
}
#[test]
fn rm_resource_lets_a_caller_restore_its_assignments() {
let mut project = Project::new("test");
let task_id = project.add_task(Task::new("Dig"));
let crowbar_id = project.add_resource(Resource::new("Crowbar".parse().unwrap()));
project
.assign_resource_units(task_id, crowbar_id, nz(3))
.unwrap();
let (removed, dropped_assignments) = project.rm_resource(crowbar_id).unwrap();
let restored_id = project.add_resource(removed);
for (task_id, quantity) in dropped_assignments {
project
.assign_resource_units(
task_id,
restored_id,
std::num::NonZeroU32::new(quantity).unwrap(),
)
.unwrap();
}
assert_eq!(
project.task(task_id).unwrap().assignment(restored_id),
Some(3)
);
}
#[test]
fn resources_are_iterated_in_insertion_order() {
let mut project = Project::new("test");
let a = project.add_resource(Resource::new("Crowbar".parse().unwrap()));
let b = project.add_resource(Resource::new("Stimpack".parse().unwrap()));
let c = project.add_resource(Resource::new("Excavator".parse().unwrap()));
let ids: Vec<_> = project.resources().map(Resource::id).collect();
assert_eq!(ids, vec![a, b, c]);
}
#[test]
fn add_resource_with_an_existing_id_replaces_it_in_place() {
let mut project = Project::new("test");
let resource = Resource::new("Crowbar".parse().unwrap());
let id = project.add_resource(resource.clone());
let mut updated = resource;
updated.set_title("Renamed crowbar".parse().unwrap());
let same_id = project.add_resource(updated);
assert_eq!(same_id, id);
assert_eq!(project.resources().count(), 1);
assert_eq!(project.resource(id).unwrap().title(), "Renamed crowbar");
}
#[test]
fn add_task_with_an_existing_id_replaces_it_in_place() {
let mut project = Project::new("test");
let task = Task::new("Dig");
let id = project.add_task(task.clone());
let mut updated = task;
updated.edit_name("Dig deeper");
let same_id = project.add_task(updated);
assert_eq!(same_id, id);
assert_eq!(project.tasks().count(), 1);
assert_eq!(project.task(id).unwrap().name(), "Dig deeper");
}
#[test]
fn a_resource_can_be_retitled_in_place_without_disturbing_assignments() {
let mut project = Project::new("test");
let task_id = project.add_task(Task::new("Find a crowbar"));
let id = project.add_resource(Resource::new("Crobwar".parse().unwrap()));
project.assign_resource(task_id, id).unwrap();
project
.resource_mut(id)
.unwrap()
.set_title("Crowbar".parse().unwrap());
assert_eq!(project.resource(id).unwrap().title(), "Crowbar");
// The assignment is untouched: it never encoded the title.
assert_eq!(project.task(task_id).unwrap().assignments().count(), 1);
}
fn name_strategy() -> impl Strategy<Value = String> {
r"[a-zA-Z0-9]{1,30}"
}
proptest! {
#[test]
fn task_add_rm_lifecycle(mut project in project_strategy()) {
let initial_count = project.tasks().count();
let id = project.add_task(Task::new("new task"));
assert_eq!(project.tasks().count(), initial_count + 1);
project.rm_task(id).unwrap();
assert_eq!(project.tasks().count(), initial_count);
for task in project.tasks() {
assert_ne!(task.name(), "new task");
}
}
#[test]
fn rm_task_cleans_subtask_relationships(name in name_strategy()) {
let mut project = Project::new(name);
let parent = project.add_task(Task::new("parent"));
let child = project.add_task(Task::new("child"));
project.add_subtask(parent, child).unwrap();
assert_eq!(project.subtasks(parent).collect::<Vec<_>>(), vec![child]);
project.rm_task(parent).unwrap();
assert!(project.subtasks(parent).next().is_none());
// The removed task had no parent of its own, so its orphaned
// child is promoted to top-level rather than left dangling.
assert!(project.task_parent(child).is_none());
}
#[test]
fn rm_task_promotes_orphaned_children_to_grandparent(name in name_strategy()) {
let mut project = Project::new(name);
let grandparent = project.add_task(Task::new("grandparent"));
let parent = project.add_task(Task::new("parent"));
let child = project.add_task(Task::new("child"));
project.add_subtask(grandparent, parent).unwrap();
project.add_subtask(parent, child).unwrap();
project.rm_task(parent).unwrap();
assert_eq!(project.task_parent(child), Some(grandparent));
assert!(project.subtasks(grandparent).collect::<Vec<_>>().contains(&child));
}
#[test]
fn resource_add_rm_lifecycle(name in name_strategy()) {
let mut project = Project::new(name);
assert_eq!(project.resources().count(), 0);
let stimpack_id = project.add_resource(Resource::new("Stimpack".parse().unwrap()));
assert_eq!(project.resources().count(), 1);
let crowbar_id = project.add_resource(Resource::new("Crowbar".parse().unwrap()));
assert_eq!(project.resources().count(), 2);
let (removed, _) = project.rm_resource(stimpack_id).unwrap();
assert_eq!(removed.title(), "Stimpack");
assert_eq!(project.resources().count(), 1);
assert_eq!(project.resource(crowbar_id).unwrap().title(), "Crowbar");
}
#[test]
fn total_cost_is_purchases_plus_task_usage(
rate1 in 0u64..1000, hours1 in 0i64..1000, qty in 0u32..1000, unit_price in 0u64..1000,
rate2 in 0u64..1000, hours2 in 0i64..1000,
) {
let mut project = Project::new("test");
let intern1_id = project.add_resource(Resource::new("Intern".parse().unwrap()).at_hourly_rate(Money::from_minor_units(rate1, Currency::EUR)));
let intern2_id = project.add_resource(Resource::new("Intern".parse().unwrap()).at_hourly_rate(Money::from_minor_units(rate2, Currency::EUR)));
// A material's purchase cost is counted once, at the project level. A task drawing
// on it adds nothing.
let mut material = Resource::new("Stimpack".parse().unwrap());
material.add_purchase(Purchase::builder().quantity(qty).unit_price(Money::from_minor_units(unit_price, Currency::EUR)).build());
let material_id = project.add_resource(material);
let mut task1 = Task::new("task 1");
task1.edit_duration(chrono::Duration::hours(hours1).try_into().unwrap());
task1.assign(intern1_id, nz(1));
if let Some(qty) = NonZeroU32::new(qty) {
task1.assign(material_id, qty);
}
let mut task2 = Task::new("task 2");
task2.edit_duration(chrono::Duration::hours(hours2).try_into().unwrap());
task2.assign(intern2_id, nz(1));
project.add_task(task1);
project.add_task(task2);
let hours1_u64 = u64::try_from(hours1).unwrap();
let hours2_u64 = u64::try_from(hours2).unwrap();
let expected: MultiCurrencyAmount =
Money::from_minor_units(rate1 * hours1_u64 + rate2 * hours2_u64 + u64::from(qty) * unit_price, Currency::EUR).into();
assert_eq!(project.total_cost(), expected);
// total_cost decomposes two ways, both equal to it.
let task_ids: Vec<_> = project.tasks().map(|t| t.id()).collect();
let resource_ids: Vec<_> = project.resources().map(|r| r.id()).collect();
let by_task_and_purchases: MultiCurrencyAmount = task_ids
.iter()
.map(|&id| project.task_cost(id).unwrap())
.chain(project.resources().map(Resource::purchase_cost))
.sum();
assert_eq!(by_task_and_purchases, expected);
let by_resource: MultiCurrencyAmount = resource_ids
.iter()
.map(|&id| project.resource_cost(id).unwrap())
.sum();
assert_eq!(by_resource, expected);
}
#[test]
fn total_cost_keeps_different_resource_currencies_separate(
rate1 in 1u64..1000, hours1 in 1i64..1000,
rate2 in 1u64..1000, hours2 in 1i64..1000,
) {
let mut project = Project::new("test");
let intern1_id = project.add_resource(Resource::new("Intern".parse().unwrap()).at_hourly_rate(Money::from_minor_units(rate1, Currency::EUR)));
let intern2_id = project.add_resource(
Resource::new("Intern".parse().unwrap())
.at_hourly_rate(Money::from_minor_units(rate2, Currency::USD)),
);
let mut task1 = Task::new("task 1");
task1.edit_duration(chrono::Duration::hours(hours1).try_into().unwrap());
task1.assign(intern1_id, nz(1));
let mut task2 = Task::new("task 2");
task2.edit_duration(chrono::Duration::hours(hours2).try_into().unwrap());
task2.assign(intern2_id, nz(1));
project.add_task(task1);
project.add_task(task2);
let total = project.total_cost();
assert_eq!(total.iter().count(), 2);
assert_eq!(total.in_currency(Currency::EUR), Some(Money::from_minor_units(rate1 * u64::try_from(hours1).unwrap(), Currency::EUR)));
assert_eq!(
total.in_currency(Currency::USD),
Some(Money::from_minor_units(rate2 * u64::try_from(hours2).unwrap(), Currency::USD)),
);
}
#[test]
fn stakeholder_add_increases_count(name in name_strategy(), first in "[a-zA-Z]{1,50}", last in "[a-zA-Z]{1,50}") {
let mut project = Project::new(name);
let p = Person::new(&first, &last).unwrap();
project.add_stakeholder(Stakeholder::Individual { person: p, description: None });
assert_eq!(project.stakeholders().len(), 1);
}
#[test]
fn rm_stakeholder_removes_and_returns(name in name_strategy(), first in "[a-zA-Z]{1,50}", last in "[a-zA-Z]{1,50}") {
let mut project = Project::new(name);
let p = Person::new(&first, &last).unwrap();
project.add_stakeholder(Stakeholder::Individual { person: p.clone(), description: None });
assert_eq!(project.stakeholders().len(), 1);
let removed = project.rm_stakeholder(0);
assert!(removed.is_some());
assert_eq!(project.stakeholders().len(), 0);
assert!(project.rm_stakeholder(0).is_none());
}
#[test]
fn add_time_relationship_works(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 2 { return Ok(()); }
let mut rng = rand::rng();
let p = rng.random_range(0..ids.len());
let mut s = p;
while s == p {
s = rng.random_range(0..ids.len());
}
project.add_time_relationship(ids[p], ids[s], TimeRelationship::FinishToStart).unwrap();
let succs: Vec<_> = project.successors_ids(ids[p]).collect();
assert!(succs.contains(&ids[s]), "successors({}) should contain {}", ids[p], ids[s]);
let preds: Vec<_> = project.predecessors_ids(ids[s]).collect();
assert!(preds.contains(&ids[p]), "predecessors({}) should contain {}", ids[s], ids[p]);
}
#[test]
fn add_time_relationship_rejects_duplicate(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 2 { return Ok(()); }
let mut rng = rand::rng();
let p = rng.random_range(0..ids.len());
let mut s = p;
while s == p {
s = rng.random_range(0..ids.len());
}
project.add_time_relationship(ids[p], ids[s], TimeRelationship::FinishToStart).unwrap();
assert!(
project.add_time_relationship(ids[p], ids[s], TimeRelationship::FinishToStart).is_err(),
"duplicate edge should be rejected"
);
}
#[test]
fn rm_time_relationship_works(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 2 { return Ok(()); }
let mut rng = rand::rng();
let p = rng.random_range(0..ids.len());
let mut s = p;
while s == p {
s = rng.random_range(0..ids.len());
}
project.add_time_relationship(ids[p], ids[s], TimeRelationship::FinishToStart).unwrap();
project.rm_time_relationship(ids[p], ids[s]).unwrap();
let succs: Vec<_> = project.successors_ids(ids[p]).collect();
assert!(!succs.contains(&ids[s]), "successors({}) should not contain {}", ids[p], ids[s]);
}
#[test]
fn add_subtask_works(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 2 { return Ok(()); }
let mut rng = rand::rng();
let p = rng.random_range(0..ids.len());
let mut c = p;
while c == p {
c = rng.random_range(0..ids.len());
}
project.add_subtask(ids[p], ids[c]).unwrap();
assert!(project.subtasks(ids[p]).any(|s| s == ids[c]), "subtasks({}) should contain {}", ids[p], ids[c]);
}
#[test]
fn a_resource_keeps_its_id_and_purchases_across_a_retitle(res_title in name_strategy(), qty in 1u32..1000, price in 1u64..1000) {
let mut project = Project::new("project");
let mut resource = Resource::new(res_title.parse().unwrap());
resource.add_purchase(
Purchase::builder()
.quantity(qty)
.unit_price(Money::from_minor_units(price, Currency::USD))
.build(),
);
let id = project.add_resource(resource);
let retitled = format!("{res_title} (updated)");
project.resource_mut(id).unwrap().set_title(retitled.parse().unwrap());
let resource = project.resource(id).unwrap();
assert_eq!(resource.id(), id);
assert_eq!(
resource.purchases().next().unwrap().unit_price(),
Money::from_minor_units(price, Currency::USD),
);
assert_eq!(resource.purchases().count(), 1);
assert_eq!(resource.purchases().next().unwrap().quantity(), qty);
assert_eq!(resource.title(), retitled);
}
#[test]
fn add_subtask_rejects_invalid_ids(name in name_strategy()) {
let mut project = Project::new(name);
let task = project.add_task(Task::new("only task"));
let fake = Uuid::new_v4();
assert!(project.subtasks(fake).next().is_none());
assert!(project.add_subtask(fake, task).is_err());
assert!(project.add_subtask(task, fake).is_err());
}
#[test]
fn rm_time_relationship_rejects_invalid_ids(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.is_empty() { return Ok(()); }
let fake = Uuid::new_v4();
assert!(project.rm_time_relationship(ids[0], fake).is_err());
assert!(project.rm_time_relationship(fake, ids[0]).is_err());
}
#[test]
fn rm_task_rejects_invalid_id(name in name_strategy()) {
let mut project = Project::new(name);
let fake = Uuid::new_v4();
assert!(project.rm_task(fake).is_err());
}
#[test]
fn total_cost_counts_a_personnel_resource_with_a_rate(name in name_strategy(), rate in 0u64..1000, hours in 0i64..1000) {
let mut project = Project::new(name);
let consultant_id = project.add_resource(
Resource::new("Margherita Hack".parse().unwrap())
.with_contact(Stakeholder::individual(Person::new("Margherita", "Hack").unwrap(), None))
.at_hourly_rate(Money::from_minor_units(rate, Currency::EUR)),
);
let task_id = project.add_task(Task::new("Consult"));
project
.edit_task_duration(task_id, chrono::Duration::hours(hours).try_into().unwrap())
.unwrap();
project.assign_resource(task_id, consultant_id).unwrap();
let expected = Money::from_minor_units(rate * u64::try_from(hours).unwrap(), Currency::EUR);
assert_eq!(project.total_cost(), expected.into());
}
}
#[test]
fn total_cost_is_zero_for_empty_project() {
let project = Project::new("test");
assert!(project.total_cost().is_empty());
}
#[test]
fn add_time_relationship_rejects_ancestor_descendant_pair() {
let mut project = Project::new("test");
let parent = project.add_task(Task::new("parent"));
let child = project.add_task(Task::new("child"));
project.add_subtask(parent, child).unwrap();
assert!(
project
.add_time_relationship(parent, child, TimeRelationship::FinishToStart)
.is_err(),
"should reject a time relationship between a task and its own subtask descendant"
);
assert!(
project
.add_time_relationship(child, parent, TimeRelationship::FinishToStart)
.is_err(),
"should reject a time relationship between a task and its own subtask ancestor"
);
}
#[test]
fn add_time_relationship_rejects_invalid_ids() {
let mut project = Project::new("test");
let task = project.add_task(Task::new("task"));
let fake = Uuid::new_v4();
assert!(
project
.add_time_relationship(fake, task, TimeRelationship::FinishToStart)
.is_err()
);
assert!(
project
.add_time_relationship(task, fake, TimeRelationship::FinishToStart)
.is_err()
);
}
#[test]
fn add_sibling_before_rejects_an_unknown_sibling() {
let mut project = Project::new("World domination");
let a = project.add_task(Task::new("Build an army"));
let fake = Uuid::new_v4();
assert!(
project
.add_sibling_before(Task::new("Train troops"), fake)
.is_err()
);
assert_eq!(project.tasks().map(|t| t.id()).collect::<Vec<_>>(), vec![a]);
}
#[test]
fn add_sibling_before_rejects_an_id_already_in_the_project() {
let mut project = Project::new("World domination");
let a = project.add_task(Task::new("Build an army"));
let existing = project.task(a).unwrap().clone();
assert!(project.add_sibling_before(existing, a).is_err());
assert_eq!(project.tasks().count(), 1);
}
#[test]
fn add_sibling_after_rejects_an_id_already_in_the_project() {
let mut project = Project::new("World domination");
let a = project.add_task(Task::new("Build an army"));
let existing = project.task(a).unwrap().clone();
assert!(project.add_sibling_after(existing, a).is_err());
assert_eq!(project.tasks().count(), 1);
}
#[test]
fn move_task_after_rejects_nonexistent_ids() {
let mut project = Project::new("World domination");
let a = project.add_task(Task::new("Build an army"));
let fake = Uuid::new_v4();
assert!(project.move_task_after(fake, a).is_err());
assert!(project.move_task_after(a, fake).is_err());
}
#[test]
fn move_task_after_rejects_self() {
let mut project = Project::new("World domination");
let a = project.add_task(Task::new("Build an army"));
assert!(project.move_task_after(a, a).is_err());
}
#[test]
fn remove_subtask_rejects_non_subtask() {
let mut project = Project::new("World domination");
let task = project.add_task(Task::new("Do something"));
assert!(project.remove_subtask(task).is_err());
}
proptest! {
#[test]
fn add_sibling_before_inserts_correctly(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 2 { return Ok(()); }
let mut rng = rand::rng();
let idx = rng.random_range(0..ids.len());
let sibling_id = ids[idx];
let new_id = project.add_sibling_before(Task::new("Minion"), sibling_id).unwrap();
let ordered_ids: Vec<Uuid> = project.tasks().map(|t| t.id()).collect();
let new_pos = ordered_ids.iter().position(|&id| id == new_id).unwrap();
let sibling_pos = ordered_ids.iter().position(|&id| id == sibling_id).unwrap();
assert_eq!(new_pos, sibling_pos - 1);
}
#[test]
fn add_sibling_after_inserts_correctly(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 2 { return Ok(()); }
let mut rng = rand::rng();
let idx = rng.random_range(0..ids.len());
let sibling_id = ids[idx];
let new_id = project.add_sibling_after(Task::new("Minion"), sibling_id).unwrap();
let ordered_ids: Vec<Uuid> = project.tasks().map(|t| t.id()).collect();
let new_pos = ordered_ids.iter().position(|&id| id == new_id).unwrap();
let sibling_pos = ordered_ids.iter().position(|&id| id == sibling_id).unwrap();
assert_eq!(new_pos, sibling_pos + 1);
}
#[test]
fn add_sibling_inherits_parent(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 3 { return Ok(()); }
let mut rng = rand::rng();
let parent_idx = rng.random_range(0..ids.len());
let child_idx = rng.random_range(0..ids.len());
if parent_idx == child_idx { return Ok(()); }
project.add_subtask(ids[parent_idx], ids[child_idx]).unwrap();
let new_id = project
.add_sibling_before(Task::new("Minion"), ids[child_idx])
.unwrap();
assert_eq!(project.task_parent(new_id), Some(ids[parent_idx]));
let children: Vec<Uuid> = project.subtasks(ids[parent_idx]).collect();
assert!(children.contains(&new_id));
}
#[test]
fn move_task_after_reorders_correctly(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 3 { return Ok(()); }
let mut rng = rand::rng();
let idx = rng.random_range(0..ids.len());
let mut after_idx = rng.random_range(0..ids.len());
while after_idx == idx {
after_idx = rng.random_range(0..ids.len());
}
project.move_task_after(ids[idx], ids[after_idx]).unwrap();
let new_ids: Vec<Uuid> = project.tasks().map(|t| t.id()).collect();
let task_pos = new_ids.iter().position(|&id| id == ids[idx]).unwrap();
let after_pos = new_ids.iter().position(|&id| id == ids[after_idx]).unwrap();
assert_eq!(task_pos, after_pos + 1);
}
#[test]
fn remove_subtask_promotes_to_top_level(mut project in project_strategy()) {
let ids = task_ids(&project);
if ids.len() < 2 { return Ok(()); }
let mut rng = rand::rng();
let parent_idx = rng.random_range(0..ids.len());
let child_idx = rng.random_range(0..ids.len());
if parent_idx == child_idx { return Ok(()); }
project.add_subtask(ids[parent_idx], ids[child_idx]).unwrap();
assert!(project.task_parent(ids[child_idx]).is_some());
project.remove_subtask(ids[child_idx]).unwrap();
assert!(project.task_parent(ids[child_idx]).is_none());
assert!(project.subtasks(ids[parent_idx]).next().is_none());
}
#[test]
fn editing_a_childs_dates_expands_its_ancestors(
mut project in project_strategy(),
start_offset in 0..1_000_000i64,
finish_offset in 0..1_000_000i64,
) {
let ids = task_ids(&project);
if ids.len() < 3 { return Ok(()); }
let mut rng = rand::rng();
let parent_idx = rng.random_range(0..ids.len());
let child1_idx = rng.random_range(0..ids.len());
let child2_idx = rng.random_range(0..ids.len());
if child1_idx == parent_idx || child2_idx == parent_idx || child1_idx == child2_idx {
return Ok(());
}
project.add_subtask(ids[parent_idx], ids[child1_idx]).unwrap();
project.add_subtask(ids[parent_idx], ids[child2_idx]).unwrap();
let now = Utc::now();
let child1_start = now - chrono::Duration::milliseconds(start_offset);
let child2_finish = now + chrono::Duration::milliseconds(finish_offset);
project.edit_task_start(ids[child1_idx], child1_start).unwrap();
project.edit_task_finish(ids[child2_idx], child2_finish).unwrap();
assert_eq!(project.task(ids[parent_idx]).unwrap().start(), Some(child1_start));
assert_eq!(project.task(ids[parent_idx]).unwrap().finish(), Some(child2_finish));
}
}
#[test]
fn ancestor_sync_has_no_effect_when_child_has_no_dates() {
let mut project = Project::new("World domination");
let army = project.add_task(Task::new("Build an army"));
let supplies = project.add_task(Task::new("Gather supplies"));
project.add_subtask(army, supplies).unwrap();
let now = Utc::now();
project.edit_task_start(army, now).unwrap();
assert_eq!(project.task(army).unwrap().start(), Some(now));
assert!(project.task(army).unwrap().finish().is_none());
}
}
#[cfg(all(test, feature = "serde"))]
mod serde_tests {
use proptest::prelude::*;
use crate::project::Project;
use crate::project::test_utils::project_strategy;
proptest! {
#[test]
fn serde_roundtrip(p in project_strategy()) {
let json = serde_json::to_string(&p).unwrap();
let deserialized: Project = serde_json::from_str(&json).unwrap();
let json2 = serde_json::to_string(&deserialized).unwrap();
let v1: serde_json::Value = serde_json::from_str(&json).unwrap();
let v2: serde_json::Value = serde_json::from_str(&json2).unwrap();
assert_eq!(v1, v2, "serde roundtrip must produce equivalent JSON");
}
}
}