mirror of
				https://gitlab.crans.org/bde/nk20
				synced 2025-10-26 13:33:19 +01:00 
			
		
		
		
	Compare commits
	
		
			957 Commits
		
	
	
		
			v1.0.2
			...
			round_tran
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
|  | d17ab26f2f | ||
|  | 297f289d7e | ||
|  | 034ad9a4ce | ||
|  | 897d37f74d | ||
|  | 42fb0aa2d6 | ||
|  | 4bc43ec3cb | ||
|  | 00737da69f | ||
|  | 6eb192b823 | ||
|  | 0934b8fa34 | ||
|  | bcd6444ff2 | ||
|  | 2a638e7b32 | ||
|  | 7633c9ab4b | ||
|  | bb06206a9b | ||
|  | 55be3c9836 | ||
|  | 2ac19ab7be | ||
|  | 7d359dec13 | ||
|  | 1015a5dba1 | ||
|  | 8f9f650826 | ||
|  | 99a90867cc | ||
|  | 0d69695b00 | ||
|  | 92f6d11cb5 | ||
|  | 1fdb30d7d2 | ||
|  | 6975ed6df6 | ||
|  | 4da87872bd | ||
|  | c25f6ca2c1 | ||
|  | 4d567cdcc7 | ||
|  | 61057b71ba | ||
|  | 80f28aa771 | ||
|  | f13a44702a | ||
|  | 85b857976a | ||
|  | 0c259155a8 | ||
|  | 4a9b7c1312 | ||
|  | 74f9c53c18 | ||
|  | b10b2fb3b6 | ||
|  | 4fa8ef4b56 | ||
|  | 68e5f280b4 | ||
|  | 251bb933da | ||
|  | 4fbbfd2365 | ||
|  | 0ac719b1f6 | ||
|  | e55a6ae407 | ||
|  | 59a502d624 | ||
|  | 312ab6dac4 | ||
|  | cf53b480db | ||
|  | d1aa1edd09 | ||
|  | d6f9a9c5b0 | ||
|  | fc0071144e | ||
|  | 573f2d8a22 | ||
|  | da30382f41 | ||
|  | 8e98d62b69 | ||
|  | 3b7f8b87c4 | ||
|  | 023fc1db84 | ||
|  | d50bb2134a | ||
|  | 0992a8a7ee | ||
|  | 97597eb103 | ||
|  | bfa5734d55 | ||
|  | 296d021d54 | ||
|  | 6e348b995b | ||
|  | 12477b33cb | ||
|  | adc925e4b1 | ||
|  | 8c3ae338ea | ||
|  | c66cc14576 | ||
|  | db4d0dd83a | ||
|  | 2af671d61a | ||
|  | 4c3b714b56 | ||
|  | 1274315cde | ||
|  | 4975c1ab6f | ||
|  | 61999a31a5 | ||
|  | b217f7ceec | ||
|  | 2755a5f7ab | ||
|  | 9ab4df94e6 | ||
|  | edb6abfff5 | ||
|  | ea8fcad8b5 | ||
|  | 03c1bb41b6 | ||
|  | 9e700fd3de | ||
|  | 67b936ae98 | ||
|  | ac56700705 | ||
|  | f64138605d | ||
|  | 40922843f8 | ||
|  | 57f43a8700 | ||
|  | a72572ded6 | ||
|  | e6839a1079 | ||
|  | ab9abc8520 | ||
|  | 249b797d5a | ||
|  | 65dd42fc97 | ||
|  | 3ebadf34bc | ||
|  | f03c13a4b8 | ||
|  | b1fa1c2cdd | ||
|  | a273dc3eef | ||
|  | 852651d126 | ||
|  | 3af35dc0fc | ||
|  | 4380414c6b | ||
|  | a94c937c6a | ||
|  | 0a261e6ad5 | ||
|  | ab9329f62b | ||
|  | b97b79e2ea | ||
|  | 483ea26f02 | ||
|  | 695ce63e08 | ||
|  | 79f50c27f1 | ||
|  | 5989721bc9 | ||
|  | bcc3e7cc53 | ||
|  | 608804db30 | ||
|  | 6f4fbecdd0 | ||
|  | 82a06c29dd | ||
|  | cf9d208586 | ||
|  | 432f50e49a | ||
|  | c7bd733911 | ||
|  | 883589e08c | ||
|  | f6ad6197de | ||
|  | c36f8c25a2 | ||
|  | 8783a63d7f | ||
|  | 4cc43fe4b6 | ||
|  | b7c0986a5f | ||
|  | 85ea43a7cf | ||
|  | f54dd30482 | ||
|  | 6c7d86185a | ||
|  | 7eafe33945 | ||
|  | 6edef619aa | ||
|  | 8a1f30ebe2 | ||
|  | b2c6b0e85d | ||
|  | 1567bc6ce5 | ||
|  | c411197af3 | ||
|  | bc517f02e5 | ||
|  | e83ee8015f | ||
|  | c26534b6b7 | ||
|  | cdc6f0a3f8 | ||
|  | c153d5f10a | ||
|  | 3f76ca6472 | ||
|  | 5c5f579729 | ||
|  | a6df0e7c69 | ||
|  | 763535bea4 | ||
|  | df0d886db9 | ||
|  | 092cc37320 | ||
|  | 16b55e23af | ||
|  | 97621e8704 | ||
|  | cf4c23d1ac | ||
|  | d71105976f | ||
|  | 89cc03141b | ||
|  | 6822500fdc | ||
|  | 63f6528adc | ||
|  | 40ac1daece | ||
|  | e617048332 | ||
|  | 9eb6edb37d | ||
|  | 70a57bf02d | ||
|  | 02453e07ba | ||
|  | 4479e8f97a | ||
|  | a351415494 | ||
|  | 16cfaa809a | ||
|  | f2cd0b6d36 | ||
|  | a2e2ff5fa9 | ||
|  | 53d0480a12 | ||
|  | ff812a028c | ||
|  | 136f636fda | ||
|  | 5a8acbde00 | ||
|  | f60dc8cfa0 | ||
|  | 067dd6f9d1 | ||
|  | 7b1e32e514 | ||
|  | e88dbfd597 | ||
|  | 3d34270959 | ||
|  | 3bb99671ec | ||
|  | 0d69383dfd | ||
|  | 7b9ff119e8 | ||
|  | 108a56745c | ||
|  | 9643d7652b | ||
|  | fadb289ed7 | ||
|  | 905fc6e7cc | ||
|  | cdd81c1444 | ||
|  | 4afafceba1 | ||
|  | 3065eacc96 | ||
|  | 71ef3aedd8 | ||
|  | 0cf11c6348 | ||
|  | 70abd0f490 | ||
|  | 4445dd4a96 | ||
|  | 03932672f3 | ||
|  | dc6a40de02 | ||
|  | d58a299a8b | ||
|  | ad0a219ed3 | ||
|  | c4404ef995 | ||
|  | b4f3a158a6 | ||
|  | f0e9a7d3dc | ||
|  | a2b42c5329 | ||
|  | 6d6583bfe6 | ||
|  | 485d093002 | ||
|  | ff4353d344 | ||
|  | a90f45bd8b | ||
|  | 10c22ccc53 | ||
|  | 6969cee0f3 | ||
|  | ddeada200b | ||
|  | 8e2b24b2da | ||
|  | bd76c280ec | ||
|  | ca0a95ba9e | ||
|  | 614f76e699 | ||
|  | a5815f0bc7 | ||
|  | 84e9fea15f | ||
|  | b7a660ee40 | ||
|  | b9ebb1718a | ||
|  | 7ba5c76a89 | ||
|  | 702ddb5679 | ||
|  | 93aed87265 | ||
|  | 60355196ce | ||
|  | 9bffb32a5e | ||
|  | 5ef019c5c2 | ||
|  | 8da62e62fb | ||
|  | 56a43396d4 | ||
|  | 7966d6f397 | ||
|  | cb61c511ce | ||
|  | 25bfa575ed | ||
|  | e21d9fcfbe | ||
|  | b293904525 | ||
|  | bd7e6b8ad4 | ||
|  | a208a4fa25 | ||
|  | 4799b2c52d | ||
|  | 562dcfb908 | ||
|  | 12ef258ff0 | ||
|  | 2ae32ee3b6 | ||
|  | ec1bd45481 | ||
|  | 370a9a069e | ||
|  | 7f0a3784e9 | ||
|  | 36f4adf2e7 | ||
|  | ae7d5d5489 | ||
|  | 434097aba4 | ||
|  | a0ebf8658d | ||
|  | 423454ba5d | ||
|  | 3ccb31639c | ||
|  | 5fb12a1388 | ||
|  | fe029893b0 | ||
|  | 767e98c2a3 | ||
|  | 1bdad76fe9 | ||
|  | 0196db7fff | ||
|  | 1f53ad4407 | ||
|  | 018f6e3f13 | ||
|  | 9752a030d9 | ||
|  | b27bdb090d | ||
|  | 55a0fbb6cb | ||
|  | c356534309 | ||
|  | 51315a0555 | ||
|  | e5f9fe2cf5 | ||
|  | 6c63c6417c | ||
|  | 4563b2b640 | ||
|  | c630a3fbd5 | ||
|  | 79b8ebeca4 | ||
|  | dc14ba0101 | ||
|  | 6028bfeb56 | ||
|  | bd9773a8af | ||
|  | cdeb76d9f8 | ||
|  | ac4574200d | ||
|  | b17d31e8ee | ||
|  | 30d27459dd | ||
|  | 333f7aa284 | ||
|  | 587314e03c | ||
|  | 9f888a5281 | ||
|  | 88b1a25ca0 | ||
|  | 8cb50f58f2 | ||
|  | 041a8f20a9 | ||
|  | b1ffb28532 | ||
|  | 6225fb51f1 | ||
|  | 1dd74e8024 | ||
|  | 1af9f5f23c | ||
|  | 83d5a7ceff | ||
|  | a7cba0a4a3 | ||
|  | ccd9a66ab9 | ||
|  | c7a92fa4b2 | ||
|  | 5f1b698d58 | ||
|  | 0a5368d23f | ||
|  | 26b351a51c | ||
|  | 1836677c47 | ||
|  | e7a98c86f0 | ||
|  | eb5044490b | ||
|  | 983d7ec052 | ||
|  | dc56deaf85 | ||
|  | 19d1ecfc66 | ||
|  | 694f54e1c4 | ||
|  | b0c3eee699 | ||
|  | cd942779ca | ||
|  | 0d0fdef363 | ||
|  | 7ed544b3ac | ||
|  | 821efbf78b | ||
|  | a209e0d366 | ||
|  | ef485e0628 | ||
|  | 1481aa0635 | ||
|  | 867bf9fd25 | ||
|  | 47fda0ea36 | ||
|  | 623290827a | ||
|  | a87ce625f3 | ||
|  | 3559787fa7 | ||
|  | bd6ed27ae5 | ||
|  | 43dc676747 | ||
|  | caaeab6b0b | ||
|  | 54ba786884 | ||
|  | 80e109114f | ||
|  | 787005e60d | ||
|  | 414e103686 | ||
|  | 942d887c2e | ||
|  | a63c34fe37 | ||
|  | 2be6133458 | ||
|  | 7975fe47a6 | ||
|  | 476fbceeea | ||
|  | 8fbaa0bdc8 | ||
|  | a0de63effd | ||
|  | 09fb1d227e | ||
|  | 2e27d4f05c | ||
|  | 5d16dc4e7d | ||
|  | 3c34033bf5 | ||
|  | 131f508433 | ||
|  | c1a353963a | ||
|  | 178ce2b579 | ||
|  | 9162319734 | ||
|  | 5d2a8e9b79 | ||
|  | 33c94d0720 | ||
|  | 5040e8e8ea | ||
|  | c5697c4cb4 | ||
|  | e188c5a153 | ||
|  | 94e1fdc93a | ||
|  | d1ef367bab | ||
|  | 0fbb19c5fd | ||
|  | 21cbf2b21a | ||
|  | 185a2cabf2 | ||
|  | 7552e55c8d | ||
|  | 361de9f8b4 | ||
|  | e2426bd6a6 | ||
|  | 7fea619a9f | ||
|  | 7b5eefcc0a | ||
|  | e4aa16986f | ||
|  | b92e6e4e10 | ||
|  | dd675b3676 | ||
|  | f50849b4f8 | ||
|  | 73ff35c232 | ||
|  | a5df98224f | ||
|  | 2cb9ac8735 | ||
|  | 35d4849a28 | ||
|  | 96539d262f | ||
|  | 946674f59b | ||
|  | a201d8376a | ||
|  | a21b9275ea | ||
|  | d4e85e8215 | ||
|  | 7af2ebba40 | ||
|  | bd94400883 | ||
|  | 5558341c8c | ||
|  | 35ef82223c | ||
|  | 9ccac36831 | ||
|  | 2e71ce05a9 | ||
|  | f2cb10b69f | ||
|  | 24c4edf2e3 | ||
|  | 213e9a8b12 | ||
|  | 2c56178b15 | ||
|  | 48a5b04579 | ||
|  | 2ab5c4082a | ||
|  | 053225c6dc | ||
|  | ac7b86651d | ||
|  | 21f5a5d566 | ||
|  | ff9c78ed4e | ||
|  | 1e121297d1 | ||
|  | 549f56dc0b | ||
|  | debeb33d46 | ||
|  | 6d7076b03e | ||
|  | 196df1e775 | ||
|  | 28117c8c61 | ||
|  | 0d9891fbd8 | ||
|  | 4be4a18dd1 | ||
|  | 27b00ba4f0 | ||
|  | 3fcbb4f310 | ||
|  | d1c9a2a7f1 | ||
|  | a673fd6871 | ||
|  | a324d3a892 | ||
|  | 951ba74f8f | ||
|  | abc4f14bd1 | ||
|  | 47138bafd4 | ||
|  | a3920fcae3 | ||
|  | ae4213d087 | ||
|  | b2b1f03b46 | ||
|  | 1c5ed2bd3f | ||
|  | a7e87ea639 | ||
|  | cbf92651f0 | ||
|  | 12c93ff9da | ||
|  | 354c79bb82 | ||
|  | 1ea7b3dda1 | ||
|  | 35ffbfcf55 | ||
|  | 162371042c | ||
|  | 581715d804 | ||
|  | c7c6f0350f | ||
|  | 9d1024024b | ||
| d595d908c6 | |||
| 734f5b242d | |||
| b0c7d43a50 | |||
|  | 6f67d2c629 | ||
|  | 4b97ab2e2a | ||
|  | dcfd0167e7 | ||
|  | 50a680eed2 | ||
|  | 226a2a6357 | ||
|  | 48462f2ffc | ||
|  | 260513ae3b | ||
|  | 210a3cc93c | ||
|  | 896095a44c | ||
|  | 3f997f94fa | ||
|  | 0801ad64ae | ||
|  | 64bd5ed546 | ||
|  | 4c390dce17 | ||
|  | adacc293f5 | ||
|  | 968fa64d37 | ||
|  | a481adbae4 | ||
|  | 4de2e987ef | ||
|  | 9e6342c929 | ||
|  | 74de358953 | ||
|  | 7322d55789 | ||
| 1a258dfe9e | |||
|  | b8f81048a5 | ||
|  | af819f45a1 | ||
|  | 076d065ffa | ||
|  | 2da77d9c17 | ||
|  | 01584d6330 | ||
|  | 4c0a5922c4 | ||
|  | f90b28fc7c | ||
|  | bbbdcc7247 | ||
|  | 925e0f26f5 | ||
|  | feeb99041f | ||
|  | c912383f86 | ||
|  | 32830e43fd | ||
|  | 11c6a6fa7a | ||
|  | 201d6b114a | ||
|  | 19e77df299 | ||
|  | 5fd6ec5668 | ||
|  | 10a01c5bc2 | ||
|  | 989905ea64 | ||
|  | 0218d43a17 | ||
|  | 5d30b0e819 | ||
|  | ec759dd3c0 | ||
|  | 2eb965291d | ||
|  | 7f182ee2ee | ||
|  | 3132aa4c38 | ||
|  | c7eb774859 | ||
|  | 32f8d285b3 | ||
|  | 050256ea13 | ||
|  | 7afd15b1cc | ||
|  | 258361f116 | ||
|  | a307530579 | ||
|  | 5de930bf40 | ||
|  | f7ebe0e99b | ||
|  | 73de6e2176 | ||
|  | 201611b105 | ||
|  | 40c239e9da | ||
|  | 2aaab2b454 | ||
|  | fc088dec86 | ||
|  | 2d60f1fd7b | ||
|  | 7b48b09329 | ||
|  | ffac940511 | ||
|  | 50f98fd5ad | ||
|  | 402e19d1ce | ||
|  | 0b0394b61f | ||
|  | 98422d8259 | ||
|  | 29509b5b26 | ||
|  | 0d64ad31e0 | ||
|  | 5781cbd6a5 | ||
|  | 5295e61a00 | ||
|  | e79ed6226a | ||
|  | 68152e6354 | ||
|  | 6c61daf1c5 | ||
|  | b8cc297baf | ||
|  | cd8224f2e0 | ||
|  | 3c882a7854 | ||
|  | 357e1bbaa2 | ||
|  | f5c4c58525 | ||
|  | dafb602b08 | ||
|  | 5b377e6a75 | ||
|  | 28bd62531e | ||
|  | b3a31c27a5 | ||
|  | c7a8e6a1a5 | ||
|  | 546a3a72b1 | ||
|  | 2e5664f79d | ||
|  | e367666fe9 | ||
|  | 04a9b3daf0 | ||
|  | d1df8f3eac | ||
|  | a5221f66ef | ||
|  | 7d59cd6cd2 | ||
|  | 96215cc1ff | ||
|  | b7a71d911d | ||
|  | 2ee7f41dfe | ||
|  | fb3337966e | ||
|  | 0db0474217 | ||
|  | 2b3eb15f59 | ||
|  | 399a32bece | ||
|  | 82fea65b5e | ||
|  | abc88d0118 | ||
|  | b6b81a8b8f | ||
|  | d228dbf225 | ||
|  | a6b479db19 | ||
|  | 048d251f75 | ||
|  | 7b11cb0797 | ||
|  | 516a7f4be5 | ||
|  | 2f8c9b54e7 | ||
|  | e9f18c3ed9 | ||
|  | ff3c30517e | ||
|  | f481ea6acb | ||
|  | 802fd8c2d7 | ||
|  | 5209a586a9 | ||
|  | 24f54ac876 | ||
|  | 988b4c9e88 | ||
|  | e32c267995 | ||
|  | 5e39209ab1 | ||
|  | 08b2fabe07 | ||
|  | 405479e5ad | ||
|  | 0cc130092f | ||
|  | ff6e207512 | ||
|  | 0f1e4d2e60 | ||
|  | 6255bcbbb1 | ||
|  | d82a1001c4 | ||
|  | 31a54482f0 | ||
|  | 4ee02345d4 | ||
|  | 422c087d17 | ||
|  | 30d6e2c95e | ||
|  | f3a3f07e38 | ||
|  | a5e802f370 | ||
|  | 540f3bc354 | ||
|  | 2d19457506 | ||
|  | 72786d0d2b | ||
|  | f099cbc879 | ||
|  | 977eb7c0d4 | ||
|  | d81b1f2710 | ||
|  | 6a69590a82 | ||
|  | 7afc583282 | ||
|  | 4fb0b7d736 | ||
|  | 18a5b65a1c | ||
|  | f545af4977 | ||
|  | 103e2d0635 | ||
|  | aedf0e87ba | ||
|  | dab45b5fd4 | ||
|  | b3353b563c | ||
|  | 6bc52be707 | ||
|  | 834d68fe35 | ||
|  | c6a2849d35 | ||
|  | 4ab22c92b3 | ||
|  | c328c1457c | ||
|  | 96da7d01ae | ||
|  | d27f942339 | ||
|  | 738d6c932d | ||
|  | 1760196578 | ||
|  | 13b9b6edea | ||
|  | e06e3b2972 | ||
|  | 9596aa7b8c | ||
|  | ba0d64f0d4 | ||
|  | 8d17801e28 | ||
|  | 609362c4f8 | ||
|  | 03d2d5f03e | ||
|  | d2057a9f45 | ||
|  | b6e68eeebe | ||
|  | 6410542027 | ||
|  | 6b1cd3ba7a | ||
|  | 9f114b8ca2 | ||
|  | e0132b6dc8 | ||
|  | f1cc82fab3 | ||
|  | 644cf14c4b | ||
|  | f19a489313 | ||
|  | dedd6c69cc | ||
|  | b42f5afeab | ||
|  | 31e67ae3f6 | ||
|  | b08da7a727 | ||
|  | 451aa64f33 | ||
|  | 3c99b0f3e9 | ||
|  | 201a179947 | ||
|  | 96784aee3b | ||
|  | 981c4d0300 | ||
|  | 11223430fd | ||
|  | 7aeb977e72 | ||
|  | 52fef1df42 | ||
|  | 16f8a60a3f | ||
|  | 2839d3de1e | ||
|  | 30afa6da0a | ||
|  | 84fc77696f | ||
|  | 19fc620d1f | ||
|  | d5819ac562 | ||
|  | a79df8f1f6 | ||
|  | 364b18e188 | ||
|  | 10a883b2e5 | ||
|  | 1410ab6c4f | ||
|  | 623dd61be6 | ||
|  | 48a0a87e7c | ||
|  | 563f525b11 | ||
|  | 63c1d74f1a | ||
|  | c42fb380a6 | ||
|  | c636d52a73 | ||
|  | 6a9021ec14 | ||
|  | 9c9149b53a | ||
|  | cb74311e7b | ||
|  | 9d7dd566c9 | ||
|  | 6bceb394c5 | ||
|  | 62cf8f9d84 | ||
|  | 9944ebcaad | ||
|  | 8537f043f7 | ||
|  | 2dd1c3fb89 | ||
|  | c8665c5798 | ||
|  | e9f1b6f52d | ||
|  | 1d95ae4810 | ||
|  | c89a95f8d2 | ||
|  | 73640b1dfa | ||
|  | 84b16ab603 | ||
|  | 6a1b51dbbf | ||
|  | c441a43a8b | ||
|  | 87f3b51b04 | ||
|  | 0a853fd3e6 | ||
|  | c429734810 | ||
|  | 5d759111b6 | ||
|  | 70baf7566c | ||
|  | eb355f547c | ||
|  | 7068170f18 | ||
|  | 45ee9a8941 | ||
|  | 454ea19603 | ||
| 5a77a66391 | |||
|  | 761fc170eb | ||
|  | ac23d7eb54 | ||
|  | 40e7415062 | ||
|  | 319405d2b1 | ||
|  | 633ab88b04 | ||
|  | e29b42eecc | ||
|  | dc69faaf1d | ||
|  | 442a5c5e36 | ||
|  | 7ab0fec3bc | ||
|  | bd4fb23351 | ||
|  | ee22e9b3b6 | ||
|  | 19ae616fb4 | ||
|  | b7657ec362 | ||
|  | 4d03d9460d | ||
| 3633f66a87 | |||
| d43fbe7ac6 | |||
|  | df5f9b5f1e | ||
| 4161248bff | |||
| 58136f3c48 | |||
| d9b4e0a9a9 | |||
| 8563a8d235 | |||
| 5f69232560 | |||
| d3273e9ee2 | |||
| 4e30f805a7 | |||
| 546e422e64 | |||
| 9048a416df | |||
| 8578bd743c | |||
| 45a10dad00 | |||
| 18a1282773 | |||
| 132afc3d15 | |||
| 6bf16a181a | |||
| e20df82346 | |||
| 1eb72044c2 | |||
| f88eae924c | |||
| 4b6e3ba546 | |||
| bf0fe3479f | |||
| 45ba4f9537 | |||
| b204805ce2 | |||
| 2f28e34cec | |||
| 9c8ea2cd41 | |||
| 41289857b2 | |||
| 28a8792c9f | |||
| 58cafad032 | |||
| 7848cd9cc2 | |||
| d18ccfac23 | |||
|  | e479e1e3a4 | ||
|  | 82b0c83b1f | ||
| 38ca414ef6 | |||
| fd811053c7 | |||
| 9d386d1ecf | |||
|  | 0bd447b608 | ||
|  | 3f3c93d928 | ||
|  | 340c90f5d3 | ||
| ca2b9f061c | |||
| a05dfcbf3d | |||
| ba3c0fb18d | |||
| ab69963ea1 | |||
| 654c01631a | |||
| d94cc2a7ad | |||
| 69bb38297f | |||
| 9628560d64 | |||
| df3bb71357 | |||
| 2a216fd994 | |||
| 8dd2619013 | |||
| 62431a4910 | |||
|  | 946bc1e497 | ||
| d4896bfd76 | |||
| 23f46cc598 | |||
| d1a9f21b56 | |||
| d809b2595a | |||
| 97803ac983 | |||
| b951c4aa05 | |||
| 69b3d2ac9c | |||
| f29054558a | |||
| 11dd8adbb7 | |||
| d437f2bdbd | |||
| ac8453b04c | |||
|  | 6b4d18f4b3 | ||
|  | 668cfa71a7 | ||
| 161db0b00b | |||
| 8638c16b34 | |||
| 9583cec3ff | |||
| 1ef25924a0 | |||
| e89383e3f4 | |||
| 79a116d9c6 | |||
| aa75ce5c7a | |||
| a3a9dfc812 | |||
| 76531595ad | |||
| a0b920ac94 | |||
| ab2e580e68 | |||
| 0234f19a33 | |||
| 1a4b7c83e8 | |||
| 4c17e2a92b | |||
| e68afc7d0a | |||
| c6e3b54f94 | |||
| 7e6a14296a | |||
| 780f78b385 | |||
| 4e3c32eb5e | |||
| ef118c2445 | |||
| 600ba15faa | |||
| 944bb127e2 | |||
| f6d042c998 | |||
| bb9a0a2593 | |||
| 61feac13c7 | |||
| 81e708a7e3 | |||
| 3532846c87 | |||
| 49551e88f8 | |||
| db936bf75a | |||
| 5828a20383 | |||
| cea3138daf | |||
| fb98d9cd8b | |||
| 0dd3da5c01 | |||
| af4be98b5b | |||
| be6059eba6 | |||
| 5793b83de7 | |||
| 2c02c747f4 | |||
| a78f3b7caa | |||
| 1ee40cb94e | |||
| bd035744a4 | |||
| 7edd622755 | |||
| 8fd5b6ee01 | |||
| 03411ac9bd | |||
| d965732b65 | |||
| 048266ed61 | |||
| b27341009e | |||
| da1e15c5e6 | |||
| 4b03a78ad6 | |||
| fb6e3c3de0 | |||
| 391f3bde8f | |||
| ad04e45992 | |||
| 4e1ba1447a | |||
| b646f549d6 | |||
| ba9ef0371a | |||
| 881cd88f48 | |||
| b4ed354b73 | |||
| e5051ab018 | |||
| bb69627ac5 | |||
| ffaa020310 | |||
| 6d2b7054e2 | |||
| d888d5863a | |||
| dbc7b3444b | |||
| f25eb1d2c5 | |||
| a2a749e1ca | |||
| 5bf6a5501d | |||
| 9523b5f05f | |||
| 5eb3ffca66 | |||
| 9930c48253 | |||
| d902e63a0c | |||
| 48b0bade51 | |||
| f75dbc4525 | |||
| fbf64db16e | |||
| a3fd8ba063 | |||
| 9b26207515 | |||
| 7ea36a5415 | |||
| 898f6d52bf | |||
| 8be16e7b58 | |||
| ea092803d7 | |||
| 5e9f36ef1a | |||
| b4d87bc6b5 | |||
| dd639d829e | |||
| 7b809ff3a6 | |||
| d36edfc063 | |||
| cf87da096f | |||
| e452b7acbf | |||
| 74ab4df9fe | |||
| 451851c955 | |||
| 789ca149af | |||
| 7d3f1930b8 | |||
| e8f4ca1e09 | |||
| 733f145be3 | |||
| 48c37353ea | |||
| 8056dc096d | |||
| 6d5b69cd26 | |||
| a7bdffd71a | |||
| 0887e4bbde | |||
| 199f4ca1f2 | |||
| 802a6c68cb | |||
| 41a0b3a1c1 | |||
| aa35724be2 | |||
| 9086d33158 | |||
| 43d214b982 | |||
| b93e4a8d11 | |||
| b9a9704061 | |||
| fee52f326a | |||
| 317966d5c1 | |||
| 9f0a22d3d1 | |||
| a5ecdd100c | |||
| f60691846b | |||
| d5ecb72a71 | |||
| 8cf9dfb9b9 | |||
| c3ab61bd04 | |||
| 0b4b6dcb3e | |||
| 0d5f6c0332 | |||
| 7b28938cde | |||
| 35ffb36fbd | |||
|  | 08ba0b263a | ||
|  | c4c4e9594f | ||
|  | 4166823d55 | ||
|  | dc0f3dbcef | ||
|  | 4583958f50 | ||
|  | b3abe9ab18 | ||
|  | 27f23b48b6 | ||
|  | 67e170d4a6 | ||
|  | 8f895dc4d7 | ||
|  | 1187577728 | ||
|  | 8a58af3b31 | ||
|  | 0c23625147 | ||
|  | 21219b9c62 | ||
|  | 5ab8beecef | ||
|  | 1ca5133026 | ||
|  | 93bc6bb245 | ||
|  | 952c4383e7 | ||
| 15dd2b8f0c | |||
| c540b6334c | |||
|  | bab394908d | ||
| 0b93968b9e | |||
| 97375ef6c0 | |||
| 36cfcd533f | |||
| 21dbc53615 | |||
| e6f10ebdac | |||
| 47968844ce | |||
| a435460e29 | |||
| b7c4360108 | |||
|  | 8d8c417c50 | ||
| 2b189af25b | |||
| 5a07c8a94f | |||
| 6cc1857eb6 | |||
| 601534d610 | |||
| c271593839 | |||
| f351794aa0 | |||
| 2793fee58c | |||
| 7a715df121 | |||
| 9308878054 | |||
| b5ccf5b800 | |||
| 5e63254439 | |||
| da96506218 | |||
| b4714b896a | |||
| cdb2647a4d | |||
| cc12e3ec63 | |||
| be168c5ada | |||
| b46ae6f856 | |||
| ec0bcbf015 | |||
| 81303b8ef8 | |||
| 910b98fefc | |||
| 5a7a219ba8 | |||
| 116451603c | |||
| b2437ef9b5 | |||
| d8c9618772 | |||
| c825dee95a | |||
| 73d27e820b | |||
| 40e1b42078 | |||
| 72806f0ace | |||
| b244e01231 | |||
| 76d1784aea | |||
| 56c5fa4057 | |||
| b5ef937a03 | |||
| e95a8b6e18 | |||
| 635adf1360 | |||
| d5a9bf175f | |||
| b597a6ac5b | |||
|  | a704b92c3d | ||
| 53090b1a21 | |||
| c49af0b83a | |||
| 5a05997d9d | |||
|  | c109cd3ddd | ||
|  | 84304971d7 | ||
| b8b781f9a2 | |||
| 002128eed2 | |||
| 8d71783c42 | |||
|  | a6f23df7d5 | ||
|  | d9c97628e2 | ||
|  | 893534955d | ||
|  | dfbf9972c2 | ||
|  | b5f3b3ffc1 | ||
|  | 3aad4e7398 | ||
|  | b4a1b513cc | ||
| c0c64f225c | |||
|  | 9d8f47115c | ||
|  | f4156f1b94 | ||
|  | e60994e065 | ||
|  | 801f711994 | ||
|  | e4568b410f | ||
| c8f7986d5a | |||
|  | d3a9c442a5 | ||
|  | 016ab5a9c9 | ||
|  | 7866ab7ec0 | ||
|  | f570ff3cd5 | ||
|  | 6b2638c271 | ||
|  | 5cb4183e9f | ||
|  | 3a20555663 | ||
|  | 95be0042e9 | ||
|  | 48880e7fd3 | ||
|  | e0030771e4 | ||
|  | d47799e6ee | ||
|  | eae091625a | ||
|  | aceb77ffb9 | ||
|  | 338c94ed05 | ||
|  | 290848f904 | ||
|  | 72dca54bbf | ||
|  | 117d9da3ba | ||
|  | 37efebe85b | ||
|  | 3af2ec71b6 | ||
|  | 0b4a95525b | ||
|  | af664e481f | ||
|  | 0171f16311 | ||
|  | 296b94d237 | ||
|  | 4942553335 | ||
|  | c1efb87180 | ||
|  | 72eead8595 | ||
|  | ade7e583e5 | ||
| 4a8a101822 | |||
| dd2cfa6327 | |||
| 2adf84b7fc | |||
|  | 2f54e64ea2 | ||
|  | 8434c0062c | ||
|  | 6d976f32bf | ||
|  | b9d49d53f2 | ||
|  | 23243e09bb | ||
|  | 2682e9a610 | ||
|  | 5635598bbc | ||
|  | b58a0c43cd | ||
|  | e1f647bd02 | ||
|  | 39fd3a2471 | ||
|  | 1072e227b8 | ||
|  | cbf7e6fe6c | ||
|  | 950922d041 | ||
|  | 78fe070cd3 | ||
|  | 51d5733578 | ||
|  | 7bd895c1df | ||
|  | e5e94c52f2 | ||
|  | 051591cb7a | ||
|  | 0e7390b669 | ||
|  | fe4363b83d | ||
|  | 6e80016b38 | ||
|  | 08e50ffc22 | ||
|  | 9cb65277f3 | ||
|  | 224a0fdd8c | ||
|  | 6dc7604e90 | ||
|  | cb7f3c9f18 | ||
|  | f910feca9e | ||
|  | 91f784872c | ||
|  | b655135a42 | ||
|  | 58aa4983e3 | ||
|  | 6cc3cf4174 | ||
|  | 2097e67321 | ||
|  | d773303d18 | ||
|  | 3cabcf40e7 | ||
|  | bf29efda0a | ||
|  | ceccba0d71 | ||
|  | 3eced33082 | ||
|  | acb3fb4a91 | ||
|  | 420a24ebac | 
| @@ -10,7 +10,6 @@ DJANGO_SECRET_KEY=CHANGE_ME | ||||
| DJANGO_SETTINGS_MODULE=note_kfet.settings | ||||
| CONTACT_EMAIL=tresorerie.bde@localhost | ||||
| NOTE_URL=localhost | ||||
| DOMAIN=localhost | ||||
|  | ||||
| # Config for mails. Only used in production | ||||
| NOTE_MAIL=notekfet@localhost | ||||
| @@ -22,3 +21,6 @@ EMAIL_PASSWORD=CHANGE_ME | ||||
| # Wiki configuration | ||||
| WIKI_USER=NoteKfet2020 | ||||
| WIKI_PASSWORD= | ||||
|  | ||||
| # OIDC | ||||
| OIDC_RSA_PRIVATE_KEY=CHANGE_ME | ||||
|   | ||||
							
								
								
									
										7
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										7
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							| @@ -42,8 +42,15 @@ map.json | ||||
| backups/ | ||||
| /static/ | ||||
| /media/ | ||||
| /tmp/ | ||||
|  | ||||
| # Virtualenv | ||||
| env/ | ||||
| venv/ | ||||
| db.sqlite3 | ||||
| shell.nix | ||||
|  | ||||
| # ansibles customs host | ||||
| ansible/host_vars/*.yaml | ||||
| !ansible/host_vars/bde* | ||||
| ansible/hosts | ||||
|   | ||||
| @@ -1,30 +1,16 @@ | ||||
| stages: | ||||
|   - test | ||||
|   - quality-assurance | ||||
|   - docs | ||||
|  | ||||
| # Also fetch submodules | ||||
| variables: | ||||
|   GIT_SUBMODULE_STRATEGY: recursive | ||||
|  | ||||
| # Debian Buster | ||||
| py37-django22: | ||||
| # Ubuntu 22.04 | ||||
| py310-django52: | ||||
|   stage: test | ||||
|   image: debian:buster-backports | ||||
|   before_script: | ||||
|     - > | ||||
|         apt-get update && | ||||
|         apt-get install --no-install-recommends -t buster-backports -y | ||||
|         python3-django python3-django-crispy-forms | ||||
|         python3-django-extensions python3-django-filters python3-django-polymorphic | ||||
|         python3-djangorestframework python3-django-oauth-toolkit python3-psycopg2 python3-pil | ||||
|         python3-babel python3-lockfile python3-pip python3-phonenumbers python3-memcache | ||||
|         python3-bs4 python3-setuptools tox texlive-xetex | ||||
|   script: tox -e py37-django22 | ||||
|  | ||||
| # Ubuntu 20.04 | ||||
| py38-django22: | ||||
|   stage: test | ||||
|   image: ubuntu:20.04 | ||||
|   image: ubuntu:22.04 | ||||
|   before_script: | ||||
|     # Fix tzdata prompt | ||||
|     - ln -sf /usr/share/zoneinfo/Europe/Paris /etc/localtime && echo Europe/Paris > /etc/timezone | ||||
| @@ -36,14 +22,43 @@ py38-django22: | ||||
|         python3-djangorestframework python3-django-oauth-toolkit python3-psycopg2 python3-pil | ||||
|         python3-babel python3-lockfile python3-pip python3-phonenumbers python3-memcache | ||||
|         python3-bs4 python3-setuptools tox texlive-xetex | ||||
|   script: tox -e py38-django22 | ||||
|   script: tox -e py310-django52 | ||||
|  | ||||
| # Debian Bookworm | ||||
| py311-django52: | ||||
|   stage: test | ||||
|   image: debian:bookworm | ||||
|   before_script: | ||||
|     - > | ||||
|         apt-get update && | ||||
|         apt-get install --no-install-recommends -y | ||||
|         python3-django python3-django-crispy-forms | ||||
|         python3-django-extensions python3-django-filters python3-django-polymorphic | ||||
|         python3-djangorestframework python3-django-oauth-toolkit python3-psycopg2 python3-pil | ||||
|         python3-babel python3-lockfile python3-pip python3-phonenumbers python3-memcache | ||||
|         python3-bs4 python3-setuptools tox texlive-xetex | ||||
|   script: tox -e py311-django52 | ||||
|  | ||||
| linters: | ||||
|   stage: quality-assurance | ||||
|   image: debian:buster-backports | ||||
|   image: debian:bookworm | ||||
|   before_script: | ||||
|     - apt-get update && apt-get install -y tox | ||||
|   script: tox -e linters | ||||
|  | ||||
|   # Be nice to new contributors, but please use `tox` | ||||
|   allow_failure: true | ||||
|  | ||||
| # Compile documentation | ||||
| documentation: | ||||
|   stage: docs | ||||
|   image: sphinxdoc/sphinx | ||||
|   before_script: | ||||
|     - pip install sphinx-rtd-theme | ||||
|     - cd docs | ||||
|   script: | ||||
|     - make dirhtml | ||||
|   artifacts: | ||||
|     paths: | ||||
|       - docs/_build | ||||
|     expire_in: 1 day | ||||
|   | ||||
							
								
								
									
										2
									
								
								.gitmodules
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										2
									
								
								.gitmodules
									
									
									
									
										vendored
									
									
								
							| @@ -1,3 +1,3 @@ | ||||
| [submodule "apps/scripts"] | ||||
| 	path = apps/scripts | ||||
| 	url = https://gitlab.crans.org/bde/nk20-scripts.git | ||||
| 	url = https://gitlab.crans.org/bde/nk20-scripts | ||||
|   | ||||
							
								
								
									
										55
									
								
								README.md
									
									
									
									
									
								
							
							
						
						
									
										55
									
								
								README.md
									
									
									
									
									
								
							| @@ -1,8 +1,8 @@ | ||||
| # NoteKfet 2020 | ||||
|  | ||||
| [](https://www.gnu.org/licenses/gpl-3.0.txt) | ||||
| [](https://gitlab.crans.org/bde/nk20/commits/master) | ||||
| [](https://gitlab.crans.org/bde/nk20/commits/master) | ||||
| [](https://gitlab.crans.org/bde/nk20/commits/main) | ||||
| [](https://gitlab.crans.org/bde/nk20/commits/main) | ||||
|  | ||||
| ## Table des matières | ||||
|  | ||||
| @@ -55,10 +55,16 @@ Bien que cela permette de créer une instance sur toutes les distributions, | ||||
|     (env)$ ./manage.py makemigrations | ||||
|     (env)$ ./manage.py migrate | ||||
|     (env)$ ./manage.py loaddata initial | ||||
|     (env)$ ./manage.py createsuperuser  # Création d'un utilisateur initial | ||||
|     (env)$ ./manage.py createsuperuser  # Création d'un⋅e utilisateur⋅rice initial | ||||
|     ``` | ||||
|  | ||||
| 6.  Enjoy : | ||||
| 6. (Optionnel) **Création d'une clé privée OpenID Connect** | ||||
|  | ||||
| Pour activer le support d'OpenID Connect, il faut générer une clé privée, par | ||||
| exemple avec openssl (`openssl genrsa -out oidc.key 4096`), et copier la clé dans .env dans le champ | ||||
| `OIDC_RSA_PRIVATE_KEY`. | ||||
|  | ||||
| 7.  Enjoy : | ||||
|  | ||||
|     ```bash | ||||
|     (env)$ ./manage.py runserver 0.0.0.0:8000 | ||||
| @@ -69,13 +75,31 @@ accessible depuis l'ensemble de votre réseau, pratique pour tester le rendu | ||||
| de la note sur un téléphone ! | ||||
|  | ||||
| ## Installation d'une instance de production | ||||
| Pour déployer facilement la note il est possible d'utiliser le playbook Ansible (sinon vous pouvez toujours le faire a la main, voir plus bas). | ||||
| ### Avec ansible | ||||
| Il vous faudra un serveur sous debian ou ubuntu connecté à internet et que vous souhaiterez accéder à cette instance de la note sur `note.nomdedomaine.tld`. | ||||
|  | ||||
| 0. Installer Ansible sur votre machine personnelle. | ||||
|  | ||||
| 0. (bis) cloner le dépot sur votre machine personelle. | ||||
|  | ||||
| 1.  Copier le fichier `ansible/host_example` | ||||
| ``` bash | ||||
| $ cp ansible/hosts_example ansible/hosts | ||||
| ``` | ||||
| et ajouter sous [dev] et/ou [prod] les serveurs sur lesquels vous souhaitez installer la note. | ||||
| 2.  Créer un fichier `ansible/host_vars/<note.nomdedomaine.tld.yaml>` sur le modèle des fichiers existants dans `ansible/hosts` et compléter les variables nécessaires. | ||||
|  | ||||
| 3. lancer `ansible/base.yaml -l <nomdedomaine.tld.yaml>` | ||||
| 4. Aller vous faire un café, ca peux durer un moment. | ||||
|  | ||||
| ### Installation manuelle | ||||
|  | ||||
| **En production on souhaite absolument utiliser les modules Python packagées dans le gestionnaire de paquet.** | ||||
| Cela permet de mettre à jour facilement les dépendances critiques telles que Django. | ||||
|  | ||||
| L'installation d'une instance de production néccessite **une installation de Debian Buster ou d'Ubuntu 20.04**. | ||||
|  | ||||
| Pour aller vite vous pouvez lancer le Playbook Ansible fournit dans ce dépôt en l'adaptant. | ||||
| Sinon vous pouvez suivre les étapes décrites ci-dessous. | ||||
|  | ||||
| 0.  Sous Debian Buster, **activer Debian Backports.** En effet Django 2.2 LTS n'est que disponible dans les backports. | ||||
| @@ -210,7 +234,13 @@ Sinon vous pouvez suivre les étapes décrites ci-dessous. | ||||
|         (env)$ ./manage.py check # pas de bêtise qui traine | ||||
|         (env)$ ./manage.py migrate | ||||
|  | ||||
| 7.  *Enjoy \o/* | ||||
| 7. **Création d'une clé privée OpenID Connect** | ||||
|  | ||||
| Pour activer le support d'OpenID Connect, il faut générer une clé privée, par | ||||
| exemple avec openssl (`openssl genrsa -out oidc.key 4096`), et renseigner le champ | ||||
| `OIDC_RSA_PRIVATE_KEY` dans le .env (par défaut `/var/secrets/oidc.key`). | ||||
|  | ||||
| 8.  *Enjoy \o/* | ||||
|  | ||||
| ### Installation avec Docker | ||||
|  | ||||
| @@ -261,20 +291,25 @@ Le cahier des charges initial est disponible [sur le Wiki Crans](https://wiki.cr | ||||
| La documentation des classes et fonctions est directement dans le code et est explorable à partir de la partie documentation de l'interface d'administration de Django. | ||||
| **Commentez votre code !** | ||||
|  | ||||
| La documentation plus haut niveau sur le développement est disponible sur [le Wiki associé au dépôt Git](https://gitlab.crans.org/bde/nk20/-/wikis/home). | ||||
| La documentation plus haut niveau sur le développement et sur l'utilisation | ||||
| est disponible sur <https://note.crans.org/doc> et également dans le dossier `docs`. | ||||
|  | ||||
| ## FAQ | ||||
|  | ||||
| ### Regénérer les fichiers de traduction | ||||
|  | ||||
| Pour regénérer les traductions vous pouvez vous placer à la racine du projet et lancer le script `makemessages`. Il faut penser à ignorer les dossiers ne contenant pas notre code, dont le virtualenv. | ||||
| Pour regénérer les traductions vous pouvez vous placer à la racine du projet et lancer le script `makemessages`. | ||||
| Il faut penser à ignorer les dossiers ne contenant pas notre code, dont le virtualenv. | ||||
| De plus, il faut aussi extraire les variables des fichiers JavaScript. | ||||
|  | ||||
| ```bash | ||||
| django-admin makemessages -i env | ||||
| python3 manage.py makemessages -i env | ||||
| python3 manage.py makemessages -i env -e js -d djangojs | ||||
| ``` | ||||
|  | ||||
| Une fois les fichiers édités, vous pouvez compiler les nouvelles traductions avec | ||||
|  | ||||
| ```bash | ||||
| django-admin compilemessages | ||||
| python3 manage.py compilemessages | ||||
| python3 manage.py compilejsmessages | ||||
| ``` | ||||
|   | ||||
| @@ -7,7 +7,7 @@ | ||||
|       prompt: "Password of the database (leave it blank to skip database init)" | ||||
|       private: yes | ||||
|   vars: | ||||
|     mirror: deb.debian.org | ||||
|     mirror: eclats.crans.org | ||||
|   roles: | ||||
|     - 1-apt-basic | ||||
|     - 2-nk20 | ||||
| @@ -16,3 +16,4 @@ | ||||
|     - 5-nginx | ||||
|     - 6-psql | ||||
|     - 7-postinstall | ||||
|     - 8-docs | ||||
|   | ||||
| @@ -1,5 +0,0 @@ | ||||
| --- | ||||
| note: | ||||
|   server_name: note-beta.crans.org | ||||
|   git_branch: beta | ||||
|   cron_enabled: false | ||||
| @@ -2,4 +2,6 @@ | ||||
| note: | ||||
|   server_name: note-dev.crans.org | ||||
|   git_branch: beta | ||||
|   serve_static: false | ||||
|   cron_enabled: false | ||||
|   email: notekfet2020@lists.crans.org | ||||
| @@ -1,5 +1,7 @@ | ||||
| --- | ||||
| note: | ||||
|   server_name: note.crans.org | ||||
|   git_branch: master | ||||
|   git_branch: main | ||||
|   serve_static: true | ||||
|   cron_enabled: true | ||||
|   email: notekfet2020@lists.crans.org | ||||
|   | ||||
| @@ -1,6 +1,5 @@ | ||||
| [dev] | ||||
| bde3-virt.adh.crans.org | ||||
| bde-nk20-beta.adh.crans.org | ||||
| bde-note-dev.adh.crans.org | ||||
| 
 | ||||
| [prod] | ||||
| bde-note.adh.crans.org | ||||
| @@ -1,13 +1,15 @@ | ||||
| --- | ||||
| - name: Add buster-backports to apt sources | ||||
| - name: Add buster-backports to apt sources if needed | ||||
|   apt_repository: | ||||
|     repo: deb http://{{ mirror }}/debian buster-backports main | ||||
|     state: present | ||||
|   when: | ||||
|     - ansible_distribution == "Debian" | ||||
|     - ansible_distribution_major_version | int == 10 | ||||
|  | ||||
| - name: Install note_kfet APT dependencies | ||||
|   apt: | ||||
|     update_cache: true | ||||
|     default_release: buster-backports | ||||
|     install_recommends: false | ||||
|     name: | ||||
|       # Common tools | ||||
|   | ||||
| @@ -16,7 +16,7 @@ | ||||
|  | ||||
| - name: Use default env vars (should be updated!) | ||||
|   template: | ||||
|     src: "env_example" | ||||
|     src: "env.j2" | ||||
|     dest: "/var/www/note_kfet/.env" | ||||
|     mode: 0644 | ||||
|     force: false | ||||
| @@ -36,3 +36,13 @@ | ||||
|     dest: /etc/cron.d/note | ||||
|     owner: root | ||||
|     group: root | ||||
|  | ||||
| - name: Set default directory to /var/www/note_kfet | ||||
|   lineinfile: | ||||
|     path: /etc/skel/.bashrc | ||||
|     line: 'cd /var/www/note_kfet' | ||||
|  | ||||
| - name: Automatically source Python virtual environment | ||||
|   lineinfile: | ||||
|     path: /etc/skel/.bashrc | ||||
|     line: 'source /var/www/note_kfet/env/bin/activate' | ||||
|   | ||||
							
								
								
									
										23
									
								
								ansible/roles/2-nk20/templates/env.j2
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										23
									
								
								ansible/roles/2-nk20/templates/env.j2
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,23 @@ | ||||
| DJANGO_APP_STAGE=prod | ||||
| # Only used in dev mode, change to "postgresql" if you want to use PostgreSQL in dev | ||||
| DJANGO_DEV_STORE_METHOD=sqlite | ||||
| DJANGO_DB_HOST=localhost | ||||
| DJANGO_DB_NAME=note_db | ||||
| DJANGO_DB_USER=note | ||||
| DJANGO_DB_PASSWORD={{ DB_PASSWORD }} | ||||
| DJANGO_DB_PORT= | ||||
| DJANGO_SECRET_KEY=CHANGE_ME | ||||
| DJANGO_SETTINGS_MODULE=note_kfet.settings | ||||
| CONTACT_EMAIL=tresorerie.bde@localhost | ||||
| NOTE_URL= {{note.server_name}} | ||||
|  | ||||
| # Config for mails. Only used in production | ||||
| NOTE_MAIL=notekfet@localhost | ||||
| EMAIL_HOST=smtp.localhost | ||||
| EMAIL_PORT=25 | ||||
| EMAIL_USER=notekfet@localhost | ||||
| EMAIL_PASSWORD=CHANGE_ME | ||||
|  | ||||
| # Wiki configuration | ||||
| WIKI_USER=NoteKfet2020 | ||||
| WIKI_PASSWORD= | ||||
| @@ -9,6 +9,11 @@ | ||||
|   retries: 3 | ||||
|   until: pkg_result is succeeded | ||||
|  | ||||
| - name: Check if certificate already exists. | ||||
|   stat: | ||||
|     path: /etc/letsencrypt/live/{{note.server_name}}/cert.pem | ||||
|   register: letsencrypt_cert | ||||
|  | ||||
| - name: Create /etc/letsencrypt/conf.d | ||||
|   file: | ||||
|     path: /etc/letsencrypt/conf.d | ||||
| @@ -19,3 +24,17 @@ | ||||
|     src: "letsencrypt/conf.d/nk20.ini.j2" | ||||
|     dest: "/etc/letsencrypt/conf.d/nk20.ini" | ||||
|     mode: 0644 | ||||
|  | ||||
| - name: Stop services to allow certbot to generate a cert. | ||||
|   service: | ||||
|     name: nginx | ||||
|     state: stopped | ||||
|  | ||||
| - name: Generate new certificate if one doesn't exist. | ||||
|   shell: "certbot certonly --non-interactive --agree-tos --config /etc/letsencrypt/conf.d/nk20.ini -d {{note.server_name}}" | ||||
|   when: letsencrypt_cert.stat.exists == False | ||||
|  | ||||
| - name: Restart services to allow certbot to generate a cert. | ||||
|   service: | ||||
|     name: nginx | ||||
|     state: started | ||||
|   | ||||
| @@ -10,7 +10,7 @@ rsa-key-size = 4096 | ||||
| # server = https://acme-staging.api.letsencrypt.org/directory | ||||
|  | ||||
| # Uncomment and update to register with the specified e-mail address | ||||
| email = notekfet2020@lists.crans.org | ||||
| email = {{ note.email }} | ||||
|  | ||||
| # Uncomment to use a text interface instead of ncurses | ||||
| text = True | ||||
|   | ||||
| @@ -1,5 +1,5 @@ | ||||
| # the upstream component nginx needs to connect to | ||||
| upstream note{ | ||||
| upstream note { | ||||
|     server unix:///var/www/note_kfet/note_kfet.sock; # file socket | ||||
| } | ||||
|  | ||||
| @@ -41,6 +41,7 @@ server { | ||||
|     # max upload size | ||||
|     client_max_body_size 75M;   # adjust to taste | ||||
|  | ||||
| {% if note.serve_static %} | ||||
|     # Django media | ||||
|     location /media  { | ||||
|         alias /var/www/note_kfet/media;  # your Django project's media files - amend as required | ||||
| @@ -50,6 +51,11 @@ server { | ||||
|         alias /var/www/note_kfet/static; # your Django project's static files - amend as required | ||||
|     } | ||||
|  | ||||
| {% endif %} | ||||
|     location /doc { | ||||
|         alias /var/www/documentation;    # The documentation of the project | ||||
|     } | ||||
|  | ||||
|     # Finally, send all non-media requests to the Django server. | ||||
|     location / { | ||||
|         uwsgi_pass note; | ||||
|   | ||||
| @@ -11,14 +11,14 @@ | ||||
|   until: pkg_result is succeeded | ||||
|  | ||||
| - name: Create role note | ||||
|   when: "DB_PASSWORD|bool"    # If the password is not defined, skip the installation | ||||
|   when: DB_PASSWORD|length > 0 # If the password is not defined, skip the installation | ||||
|   postgresql_user: | ||||
|     name: note | ||||
|     password: "{{ DB_PASSWORD }}" | ||||
|   become_user: postgres | ||||
|  | ||||
| - name: Create NK20 database | ||||
|   when: "DB_PASSWORD|bool" | ||||
|   when: DB_PASSWORD|length >0 | ||||
|   postgresql_db: | ||||
|     name: note_db | ||||
|     owner: note | ||||
|   | ||||
| @@ -1,4 +1,10 @@ | ||||
| --- | ||||
| - name: Collect static files | ||||
|   command: /var/www/note_kfet/env/bin/python manage.py collectstatic --noinput | ||||
|   args: | ||||
|     chdir: /var/www/note_kfet | ||||
|   become_user: www-data | ||||
|  | ||||
| - name: Migrate Django database | ||||
|   command: /var/www/note_kfet/env/bin/python manage.py migrate | ||||
|   args: | ||||
| @@ -11,14 +17,14 @@ | ||||
|     chdir: /var/www/note_kfet | ||||
|   become_user: www-data | ||||
|  | ||||
| - name: Compile JavaScript messages | ||||
|   command: /var/www/note_kfet/env/bin/python manage.py compilejsmessages | ||||
|   args: | ||||
|     chdir: /var/www/note_kfet | ||||
|   become_user: www-data | ||||
|  | ||||
| - name: Install initial fixtures | ||||
|   command: /var/www/note_kfet/env/bin/python manage.py loaddata initial | ||||
|   args: | ||||
|     chdir: /var/www/note_kfet | ||||
|   become_user: postgres | ||||
|  | ||||
| - name: Collect static files | ||||
|   command: /var/www/note_kfet/env/bin/python manage.py collectstatic --noinput | ||||
|   args: | ||||
|     chdir: /var/www/note_kfet | ||||
|   become_user: www-data | ||||
|   | ||||
							
								
								
									
										20
									
								
								ansible/roles/8-docs/tasks/main.yml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										20
									
								
								ansible/roles/8-docs/tasks/main.yml
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,20 @@ | ||||
| --- | ||||
| - name: Install Sphinx and RTD theme | ||||
|   pip: | ||||
|     requirements: /var/www/note_kfet/docs/requirements.txt | ||||
|     virtualenv: /var/www/note_kfet/env | ||||
|     virtualenv_command: /usr/bin/python3 -m venv | ||||
|     virtualenv_site_packages: true | ||||
|   become_user: www-data | ||||
|  | ||||
| - name: Create documentation directory with good permissions | ||||
|   file: | ||||
|     path: /var/www/documentation | ||||
|     state: directory | ||||
|     owner: www-data | ||||
|     group: www-data | ||||
|     mode: u=rwx,g=rwxs,o=rx | ||||
|  | ||||
| - name: Build HTML documentation | ||||
|   command: /var/www/note_kfet/env/bin/sphinx-build -b dirhtml /var/www/note_kfet/docs/ /var/www/documentation/ | ||||
|   become_user: www-data | ||||
| @@ -1,4 +1,4 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| default_app_config = 'activity.apps.ActivityConfig' | ||||
|   | ||||
| @@ -1,11 +1,11 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from django.contrib import admin | ||||
| from note_kfet.admin import admin_site | ||||
|  | ||||
| from .forms import GuestForm | ||||
| from .models import Activity, ActivityType, Entry, Guest | ||||
| from .models import Activity, ActivityType, Entry, Guest, Opener | ||||
|  | ||||
|  | ||||
| @admin.register(Activity, site=admin_site) | ||||
| @@ -35,7 +35,7 @@ class GuestAdmin(admin.ModelAdmin): | ||||
|     """ | ||||
|     Admin customisation for Guest | ||||
|     """ | ||||
|     list_display = ('last_name', 'first_name', 'activity', 'inviter') | ||||
|     list_display = ('last_name', 'first_name', 'school', 'activity', 'inviter') | ||||
|     form = GuestForm | ||||
|  | ||||
|  | ||||
| @@ -45,3 +45,11 @@ class EntryAdmin(admin.ModelAdmin): | ||||
|     Admin customisation for Entry | ||||
|     """ | ||||
|     list_display = ('note', 'activity', 'time', 'guest') | ||||
|  | ||||
|  | ||||
| @admin.register(Opener, site=admin_site) | ||||
| class OpenerAdmin(admin.ModelAdmin): | ||||
|     """ | ||||
|     Admin customisation for Opener | ||||
|     """ | ||||
|     list_display = ('activity', 'opener') | ||||
|   | ||||
| @@ -1,9 +1,11 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from django.utils.translation import gettext_lazy as _ | ||||
| from rest_framework import serializers | ||||
| from rest_framework.validators import UniqueTogetherValidator | ||||
|  | ||||
| from ..models import Activity, ActivityType, Entry, Guest, GuestTransaction | ||||
| from ..models import Activity, ActivityType, Entry, Guest, GuestTransaction, Opener | ||||
|  | ||||
|  | ||||
| class ActivityTypeSerializer(serializers.ModelSerializer): | ||||
| @@ -59,3 +61,17 @@ class GuestTransactionSerializer(serializers.ModelSerializer): | ||||
|     class Meta: | ||||
|         model = GuestTransaction | ||||
|         fields = '__all__' | ||||
|  | ||||
|  | ||||
| class OpenerSerializer(serializers.ModelSerializer): | ||||
|     """ | ||||
|     REST API Serializer for Openers. | ||||
|     The djangorestframework plugin will analyse the model `Opener` and parse all fields in the API. | ||||
|     """ | ||||
|  | ||||
|     class Meta: | ||||
|         model = Opener | ||||
|         fields = '__all__' | ||||
|         validators = [UniqueTogetherValidator( | ||||
|             queryset=Opener.objects.all(), fields=("opener", "activity"), | ||||
|             message=_("This opener already exists"))] | ||||
|   | ||||
| @@ -1,7 +1,7 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from .views import ActivityTypeViewSet, ActivityViewSet, EntryViewSet, GuestViewSet | ||||
| from .views import ActivityTypeViewSet, ActivityViewSet, EntryViewSet, GuestViewSet, OpenerViewSet | ||||
|  | ||||
|  | ||||
| def register_activity_urls(router, path): | ||||
| @@ -12,3 +12,4 @@ def register_activity_urls(router, path): | ||||
|     router.register(path + '/type', ActivityTypeViewSet) | ||||
|     router.register(path + '/guest', GuestViewSet) | ||||
|     router.register(path + '/entry', EntryViewSet) | ||||
|     router.register(path + '/opener', OpenerViewSet) | ||||
|   | ||||
| @@ -1,12 +1,15 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from api.filters import RegexSafeSearchFilter | ||||
| from api.viewsets import ReadProtectedModelViewSet | ||||
| from django.core.exceptions import ValidationError | ||||
| from django_filters.rest_framework import DjangoFilterBackend | ||||
| from rest_framework.filters import SearchFilter | ||||
| from rest_framework.response import Response | ||||
| from rest_framework import status | ||||
|  | ||||
| from .serializers import ActivitySerializer, ActivityTypeSerializer, EntrySerializer, GuestSerializer | ||||
| from ..models import Activity, ActivityType, Entry, Guest | ||||
| from .serializers import ActivitySerializer, ActivityTypeSerializer, EntrySerializer, GuestSerializer, OpenerSerializer | ||||
| from ..models import Activity, ActivityType, Entry, Guest, Opener | ||||
|  | ||||
|  | ||||
| class ActivityTypeViewSet(ReadProtectedModelViewSet): | ||||
| @@ -15,10 +18,10 @@ class ActivityTypeViewSet(ReadProtectedModelViewSet): | ||||
|     The djangorestframework plugin will get all `ActivityType` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/activity/type/ | ||||
|     """ | ||||
|     queryset = ActivityType.objects.all() | ||||
|     queryset = ActivityType.objects.order_by('id') | ||||
|     serializer_class = ActivityTypeSerializer | ||||
|     filter_backends = [DjangoFilterBackend] | ||||
|     filterset_fields = ['name', 'can_invite', ] | ||||
|     filterset_fields = ['name', 'manage_entries', 'can_invite', 'guest_entry_fee', ] | ||||
|  | ||||
|  | ||||
| class ActivityViewSet(ReadProtectedModelViewSet): | ||||
| @@ -27,10 +30,16 @@ class ActivityViewSet(ReadProtectedModelViewSet): | ||||
|     The djangorestframework plugin will get all `Activity` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/activity/activity/ | ||||
|     """ | ||||
|     queryset = Activity.objects.all() | ||||
|     queryset = Activity.objects.order_by('id') | ||||
|     serializer_class = ActivitySerializer | ||||
|     filter_backends = [DjangoFilterBackend] | ||||
|     filterset_fields = ['name', 'description', 'activity_type', ] | ||||
|     filter_backends = [DjangoFilterBackend, RegexSafeSearchFilter] | ||||
|     filterset_fields = ['name', 'description', 'activity_type', 'location', 'creater', 'organizer', 'attendees_club', | ||||
|                         'date_start', 'date_end', 'valid', 'open', ] | ||||
|     search_fields = ['$name', '$description', '$location', '$creater__last_name', '$creater__first_name', | ||||
|                      '$creater__email', '$creater__note__alias__name', '$creater__note__alias__normalized_name', | ||||
|                      '$organizer__name', '$organizer__email', '$organizer__note__alias__name', | ||||
|                      '$organizer__note__alias__normalized_name', '$attendees_club__name', '$attendees_club__email', | ||||
|                      '$attendees_club__note__alias__name', '$attendees_club__note__alias__normalized_name', ] | ||||
|  | ||||
|  | ||||
| class GuestViewSet(ReadProtectedModelViewSet): | ||||
| @@ -39,10 +48,13 @@ class GuestViewSet(ReadProtectedModelViewSet): | ||||
|     The djangorestframework plugin will get all `Guest` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/activity/guest/ | ||||
|     """ | ||||
|     queryset = Guest.objects.all() | ||||
|     queryset = Guest.objects.order_by('id') | ||||
|     serializer_class = GuestSerializer | ||||
|     filter_backends = [SearchFilter] | ||||
|     search_fields = ['$last_name', '$first_name', '$inviter__alias__name', '$inviter__alias__normalized_name', ] | ||||
|     filter_backends = [DjangoFilterBackend, RegexSafeSearchFilter] | ||||
|     filterset_fields = ['activity', 'activity__name', 'last_name', 'first_name', 'school', 'inviter', 'inviter__alias__name', | ||||
|                         'inviter__alias__normalized_name', ] | ||||
|     search_fields = ['$activity__name', '$last_name', '$first_name', '$school', '$inviter__user__email', '$inviter__alias__name', | ||||
|                      '$inviter__alias__normalized_name', ] | ||||
|  | ||||
|  | ||||
| class EntryViewSet(ReadProtectedModelViewSet): | ||||
| @@ -51,7 +63,38 @@ class EntryViewSet(ReadProtectedModelViewSet): | ||||
|     The djangorestframework plugin will get all `Entry` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/activity/entry/ | ||||
|     """ | ||||
|     queryset = Entry.objects.all() | ||||
|     queryset = Entry.objects.order_by('id') | ||||
|     serializer_class = EntrySerializer | ||||
|     filter_backends = [SearchFilter] | ||||
|     search_fields = ['$last_name', '$first_name', '$inviter__alias__name', '$inviter__alias__normalized_name', ] | ||||
|     filter_backends = [DjangoFilterBackend, RegexSafeSearchFilter] | ||||
|     filterset_fields = ['activity', 'time', 'note', 'guest', ] | ||||
|     search_fields = ['$activity__name', '$note__user__email', '$note__alias__name', '$note__alias__normalized_name', | ||||
|                      '$guest__last_name', '$guest__first_name', ] | ||||
|  | ||||
|  | ||||
| class OpenerViewSet(ReadProtectedModelViewSet): | ||||
|     """ | ||||
|     REST Opener View set. | ||||
|     The djangorestframework plugin will get all `Opener` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/activity/opener/ | ||||
|     """ | ||||
|     queryset = Opener.objects | ||||
|     serializer_class = OpenerSerializer | ||||
|     filter_backends = [RegexSafeSearchFilter, DjangoFilterBackend] | ||||
|     search_fields = ['$opener__alias__name', '$opener__alias__normalized_name', | ||||
|                      '$activity__name'] | ||||
|     filterset_fields = ['opener', 'opener__noteuser__user', 'activity'] | ||||
|  | ||||
|     def get_serializer_class(self): | ||||
|         serializer_class = self.serializer_class | ||||
|         if self.request.method in ['PUT', 'PATCH']: | ||||
|             # opener-activity can't change | ||||
|             serializer_class.Meta.read_only_fields = ('opener', 'acitivity',) | ||||
|         return serializer_class | ||||
|  | ||||
|     def destroy(self, request, *args, **kwargs): | ||||
|         instance = self.get_object() | ||||
|         try: | ||||
|             self.perform_destroy(instance) | ||||
|         except ValidationError as e: | ||||
|             return Response({e.code: str(e)}, status.HTTP_400_BAD_REQUEST) | ||||
|         return Response(status=status.HTTP_204_NO_CONTENT) | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from django.apps import AppConfig | ||||
|   | ||||
| @@ -6,7 +6,7 @@ | ||||
|             "name": "Pot", | ||||
|             "manage_entries": true, | ||||
|             "can_invite": true, | ||||
|             "guest_entry_fee": 500 | ||||
|             "guest_entry_fee": 1000 | ||||
|         } | ||||
|     }, | ||||
|     { | ||||
| @@ -28,5 +28,25 @@ | ||||
|             "can_invite": false, | ||||
|             "guest_entry_fee": 0 | ||||
|         } | ||||
|     }, | ||||
|     { | ||||
|         "model": "activity.activitytype", | ||||
|         "pk": 5, | ||||
|         "fields": { | ||||
|             "name": "Soir\u00e9e avec entrées", | ||||
|             "manage_entries": true, | ||||
|             "can_invite": false, | ||||
|             "guest_entry_fee": 0 | ||||
|         } | ||||
|     }, | ||||
|     { | ||||
|         "model": "activity.activitytype", | ||||
|         "pk": 7, | ||||
|         "fields": { | ||||
|             "name": "Soir\u00e9e avec invitations", | ||||
|             "manage_entries": true, | ||||
|             "can_invite": true, | ||||
|             "guest_entry_fee": 0 | ||||
|         } | ||||
|     } | ||||
| ] | ||||
|   | ||||
| @@ -1,17 +1,18 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from datetime import timedelta | ||||
| from random import shuffle | ||||
|  | ||||
| from bootstrap_datepicker_plus.widgets import DateTimePickerInput | ||||
| from django import forms | ||||
| from django.contrib.contenttypes.models import ContentType | ||||
| from django.utils import timezone | ||||
| from django.utils.translation import gettext_lazy as _ | ||||
| from member.models import Club | ||||
| from note.models import Note, NoteUser | ||||
| from note_kfet.inputs import Autocomplete, DateTimePickerInput | ||||
| from note_kfet.middlewares import get_current_authenticated_user | ||||
| from note_kfet.inputs import Autocomplete | ||||
| from note_kfet.middlewares import get_current_request | ||||
| from permission.backends import PermissionBackend | ||||
|  | ||||
| from .models import Activity, Guest | ||||
| @@ -24,10 +25,16 @@ class ActivityForm(forms.ModelForm): | ||||
|         self.fields["attendees_club"].initial = Club.objects.get(name="Kfet") | ||||
|         self.fields["attendees_club"].widget.attrs["placeholder"] = "Kfet" | ||||
|         clubs = list(Club.objects.filter(PermissionBackend | ||||
|                                          .filter_queryset(get_current_authenticated_user(), Club, "view")).all()) | ||||
|                                          .filter_queryset(get_current_request(), Club, "view")).all()) | ||||
|         shuffle(clubs) | ||||
|         self.fields["organizer"].widget.attrs["placeholder"] = ", ".join(club.name for club in clubs[:4]) + ", ..." | ||||
|  | ||||
|     def clean_organizer(self): | ||||
|         organizer = self.cleaned_data['organizer'] | ||||
|         if not organizer.note.is_active: | ||||
|             self.add_error('organizer', _('The note of this club is inactive.')) | ||||
|         return organizer | ||||
|  | ||||
|     def clean_date_end(self): | ||||
|         date_end = self.cleaned_data["date_end"] | ||||
|         date_start = self.cleaned_data["date_start"] | ||||
| @@ -37,7 +44,7 @@ class ActivityForm(forms.ModelForm): | ||||
|  | ||||
|     class Meta: | ||||
|         model = Activity | ||||
|         exclude = ('creater', 'valid', 'open', ) | ||||
|         exclude = ('creater', 'valid', 'open', 'opener', ) | ||||
|         widgets = { | ||||
|             "organizer": Autocomplete( | ||||
|                 model=Club, | ||||
| @@ -100,7 +107,7 @@ class GuestForm(forms.ModelForm): | ||||
|  | ||||
|     class Meta: | ||||
|         model = Guest | ||||
|         fields = ('last_name', 'first_name', 'inviter', ) | ||||
|         fields = ('last_name', 'first_name', 'school', 'inviter', ) | ||||
|         widgets = { | ||||
|             "inviter": Autocomplete( | ||||
|                 NoteUser, | ||||
|   | ||||
							
								
								
									
										18
									
								
								apps/activity/migrations/0003_auto_20240323_1422.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										18
									
								
								apps/activity/migrations/0003_auto_20240323_1422.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,18 @@ | ||||
| # Generated by Django 2.2.28 on 2024-03-23 13:22 | ||||
|  | ||||
| from django.db import migrations, models | ||||
|  | ||||
|  | ||||
| class Migration(migrations.Migration): | ||||
|  | ||||
|     dependencies = [ | ||||
|         ('activity', '0002_auto_20200904_2341'), | ||||
|     ] | ||||
|  | ||||
|     operations = [ | ||||
|         migrations.AlterField( | ||||
|             model_name='activity', | ||||
|             name='description', | ||||
|             field=models.TextField(blank=True, default='', verbose_name='description'), | ||||
|         ), | ||||
|     ] | ||||
							
								
								
									
										28
									
								
								apps/activity/migrations/0004_opener.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										28
									
								
								apps/activity/migrations/0004_opener.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,28 @@ | ||||
| # Generated by Django 2.2.28 on 2024-08-01 12:36 | ||||
|  | ||||
| from django.db import migrations, models | ||||
| import django.db.models.deletion | ||||
|  | ||||
|  | ||||
| class Migration(migrations.Migration): | ||||
|  | ||||
|     dependencies = [ | ||||
|         ('note', '0006_trust'), | ||||
|         ('activity', '0003_auto_20240323_1422'), | ||||
|     ] | ||||
|  | ||||
|     operations = [ | ||||
|         migrations.CreateModel( | ||||
|             name='Opener', | ||||
|             fields=[ | ||||
|                 ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), | ||||
|                 ('activity', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='opener', to='activity.Activity', verbose_name='activity')), | ||||
|                 ('opener', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='activity_responsible', to='note.Note', verbose_name='opener')), | ||||
|             ], | ||||
|             options={ | ||||
|                 'verbose_name': 'opener', | ||||
|                 'verbose_name_plural': 'openers', | ||||
|                 'unique_together': {('opener', 'activity')}, | ||||
|             }, | ||||
|         ), | ||||
|     ] | ||||
| @@ -0,0 +1,24 @@ | ||||
| # Generated by Django 4.2.15 on 2024-08-28 08:00 | ||||
|  | ||||
| from django.db import migrations, models | ||||
| import django.db.models.deletion | ||||
|  | ||||
|  | ||||
| class Migration(migrations.Migration): | ||||
|  | ||||
|     dependencies = [ | ||||
|         ('note', '0006_trust'), | ||||
|         ('activity', '0004_opener'), | ||||
|     ] | ||||
|  | ||||
|     operations = [ | ||||
|         migrations.AlterModelOptions( | ||||
|             name='opener', | ||||
|             options={'verbose_name': 'Opener', 'verbose_name_plural': 'Openers'}, | ||||
|         ), | ||||
|         migrations.AlterField( | ||||
|             model_name='opener', | ||||
|             name='opener', | ||||
|             field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='activity_responsible', to='note.note', verbose_name='Opener'), | ||||
|         ), | ||||
|     ] | ||||
							
								
								
									
										18
									
								
								apps/activity/migrations/0006_guest_school.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										18
									
								
								apps/activity/migrations/0006_guest_school.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,18 @@ | ||||
| # Generated by Django 4.2.20 on 2025-03-25 09:58 | ||||
|  | ||||
| from django.db import migrations, models | ||||
|  | ||||
|  | ||||
| class Migration(migrations.Migration): | ||||
|     dependencies = [ | ||||
|         ("activity", "0005_alter_opener_options_alter_opener_opener"), | ||||
|     ] | ||||
|  | ||||
|     operations = [ | ||||
|         migrations.AddField( | ||||
|             model_name="guest", | ||||
|             name="school", | ||||
|             field=models.CharField(default="", max_length=255, verbose_name="school"), | ||||
|             preserve_default=False, | ||||
|         ), | ||||
|     ] | ||||
							
								
								
									
										19
									
								
								apps/activity/migrations/0007_alter_guest_activity.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										19
									
								
								apps/activity/migrations/0007_alter_guest_activity.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,19 @@ | ||||
| # Generated by Django 4.2.20 on 2025-05-08 19:07 | ||||
|  | ||||
| from django.db import migrations, models | ||||
| import django.db.models.deletion | ||||
|  | ||||
|  | ||||
| class Migration(migrations.Migration): | ||||
|  | ||||
|     dependencies = [ | ||||
|         ('activity', '0006_guest_school'), | ||||
|     ] | ||||
|  | ||||
|     operations = [ | ||||
|         migrations.AlterField( | ||||
|             model_name='guest', | ||||
|             name='activity', | ||||
|             field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='+', to='activity.activity'), | ||||
|         ), | ||||
|     ] | ||||
| @@ -1,4 +1,4 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| import os | ||||
| @@ -11,7 +11,7 @@ from django.db import models, transaction | ||||
| from django.db.models import Q | ||||
| from django.utils import timezone | ||||
| from django.utils.translation import gettext_lazy as _ | ||||
| from note.models import NoteUser, Transaction | ||||
| from note.models import NoteUser, Transaction, Note | ||||
| from rest_framework.exceptions import ValidationError | ||||
|  | ||||
|  | ||||
| @@ -66,6 +66,8 @@ class Activity(models.Model): | ||||
|  | ||||
|     description = models.TextField( | ||||
|         verbose_name=_('description'), | ||||
|         blank=True, | ||||
|         default="", | ||||
|     ) | ||||
|  | ||||
|     location = models.CharField( | ||||
| @@ -123,6 +125,14 @@ class Activity(models.Model): | ||||
|         verbose_name=_('open'), | ||||
|     ) | ||||
|  | ||||
|     class Meta: | ||||
|         verbose_name = _("activity") | ||||
|         verbose_name_plural = _("activities") | ||||
|         unique_together = ("name", "date_start", "date_end",) | ||||
|  | ||||
|     def __str__(self): | ||||
|         return self.name | ||||
|  | ||||
|     @transaction.atomic | ||||
|     def save(self, *args, **kwargs): | ||||
|         """ | ||||
| @@ -144,14 +154,6 @@ class Activity(models.Model): | ||||
|                 if settings.DATABASES["default"]["ENGINE"] == 'django.db.backends.postgresql' else refresh_activities() | ||||
|         return ret | ||||
|  | ||||
|     def __str__(self): | ||||
|         return self.name | ||||
|  | ||||
|     class Meta: | ||||
|         verbose_name = _("activity") | ||||
|         verbose_name_plural = _("activities") | ||||
|         unique_together = ("name", "date_start", "date_end",) | ||||
|  | ||||
|  | ||||
| class Entry(models.Model): | ||||
|     """ | ||||
| @@ -199,7 +201,8 @@ class Entry(models.Model): | ||||
|     def save(self, *args, **kwargs): | ||||
|         qs = Entry.objects.filter(~Q(pk=self.pk), activity=self.activity, note=self.note, guest=self.guest) | ||||
|         if qs.exists(): | ||||
|             raise ValidationError(_("Already entered on ") + _("{:%Y-%m-%d %H:%M:%S}").format(qs.get().time, )) | ||||
|             raise ValidationError(_("Already entered on ") | ||||
|                                   + _("{:%Y-%m-%d %H:%M:%S}").format(timezone.localtime(qs.get().time), )) | ||||
|  | ||||
|         if self.guest: | ||||
|             self.note = self.guest.inviter | ||||
| @@ -231,7 +234,7 @@ class Guest(models.Model): | ||||
|     """ | ||||
|     activity = models.ForeignKey( | ||||
|         Activity, | ||||
|         on_delete=models.PROTECT, | ||||
|         on_delete=models.CASCADE, | ||||
|         related_name='+', | ||||
|     ) | ||||
|  | ||||
| @@ -245,6 +248,11 @@ class Guest(models.Model): | ||||
|         verbose_name=_("first name"), | ||||
|     ) | ||||
|  | ||||
|     school = models.CharField( | ||||
|         max_length=255, | ||||
|         verbose_name=_("school"), | ||||
|     ) | ||||
|  | ||||
|     inviter = models.ForeignKey( | ||||
|         NoteUser, | ||||
|         on_delete=models.PROTECT, | ||||
| @@ -252,14 +260,13 @@ class Guest(models.Model): | ||||
|         verbose_name=_("inviter"), | ||||
|     ) | ||||
|  | ||||
|     @property | ||||
|     def has_entry(self): | ||||
|         try: | ||||
|             if self.entry: | ||||
|                 return True | ||||
|             return False | ||||
|         except AttributeError: | ||||
|             return False | ||||
|     class Meta: | ||||
|         verbose_name = _("guest") | ||||
|         verbose_name_plural = _("guests") | ||||
|         unique_together = ("activity", "last_name", "first_name", ) | ||||
|  | ||||
|     def __str__(self): | ||||
|         return self.first_name + " " + self.last_name | ||||
|  | ||||
|     @transaction.atomic | ||||
|     def save(self, force_insert=False, force_update=False, using=None, update_fields=None): | ||||
| @@ -290,13 +297,14 @@ class Guest(models.Model): | ||||
|  | ||||
|         return super().save(force_insert, force_update, using, update_fields) | ||||
|  | ||||
|     def __str__(self): | ||||
|         return self.first_name + " " + self.last_name | ||||
|  | ||||
|     class Meta: | ||||
|         verbose_name = _("guest") | ||||
|         verbose_name_plural = _("guests") | ||||
|         unique_together = ("activity", "last_name", "first_name", ) | ||||
|     @property | ||||
|     def has_entry(self): | ||||
|         try: | ||||
|             if self.entry: | ||||
|                 return True | ||||
|             return False | ||||
|         except AttributeError: | ||||
|             return False | ||||
|  | ||||
|  | ||||
| class GuestTransaction(Transaction): | ||||
| @@ -308,3 +316,31 @@ class GuestTransaction(Transaction): | ||||
|     @property | ||||
|     def type(self): | ||||
|         return _('Invitation') | ||||
|  | ||||
|  | ||||
| class Opener(models.Model): | ||||
|     """ | ||||
|     Allow the user to make activity entries without more rights | ||||
|     """ | ||||
|     activity = models.ForeignKey( | ||||
|         Activity, | ||||
|         on_delete=models.CASCADE, | ||||
|         related_name='opener', | ||||
|         verbose_name=_('activity') | ||||
|     ) | ||||
|  | ||||
|     opener = models.ForeignKey( | ||||
|         Note, | ||||
|         on_delete=models.CASCADE, | ||||
|         related_name='activity_responsible', | ||||
|         verbose_name=_('Opener') | ||||
|     ) | ||||
|  | ||||
|     class Meta: | ||||
|         verbose_name = _("Opener") | ||||
|         verbose_name_plural = _("Openers") | ||||
|         unique_together = ("opener", "activity") | ||||
|  | ||||
|     def __str__(self): | ||||
|         return _("{opener} is opener of activity {acivity}").format( | ||||
|             opener=str(self.opener), acivity=str(self.activity)) | ||||
|   | ||||
							
								
								
									
										57
									
								
								apps/activity/static/activity/js/opener.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										57
									
								
								apps/activity/static/activity/js/opener.js
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,57 @@ | ||||
| /** | ||||
|  * On form submit, add a new opener | ||||
|  */ | ||||
| function form_create_opener (e) { | ||||
|   // Do not submit HTML form | ||||
|   e.preventDefault() | ||||
|  | ||||
|   // Get data and send to API | ||||
|   const formData = new FormData(e.target) | ||||
|   $.getJSON('/api/note/alias/'+formData.get('opener') + '/', | ||||
|     function (opener_alias) { | ||||
|       create_opener(formData.get('activity'), opener_alias.note) | ||||
|     }).fail(function (xhr, _textStatus, _error) { | ||||
|         errMsg(xhr.responseJSON) | ||||
|     }) | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Add an opener between an activity and a user | ||||
|  * @param activity:Integer activity id | ||||
|  * @param opener:Integer user note id | ||||
|  */ | ||||
| function create_opener(activity, opener) { | ||||
|   $.post('/api/activity/opener/', { | ||||
|       activity: activity, | ||||
|       opener: opener, | ||||
|       csrfmiddlewaretoken: CSRF_TOKEN | ||||
|   }).done(function () { | ||||
|   // Reload tables | ||||
|   $('#opener_table').load(location.pathname + ' #opener_table') | ||||
|     addMsg(gettext('Opener successfully added'), 'success') | ||||
|   }).fail(function (xhr, _textStatus, _error) { | ||||
|     errMsg(xhr.responseJSON) | ||||
|   }) | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * On click of "delete", delete the opener | ||||
|  * @param button_id:Integer Opener id to remove | ||||
|  */ | ||||
| function delete_button (button_id) { | ||||
|   $.ajax({ | ||||
|     url: '/api/activity/opener/' + button_id + '/', | ||||
|     method: 'DELETE', | ||||
|     headers: { 'X-CSRFTOKEN': CSRF_TOKEN } | ||||
|   }).done(function () { | ||||
|     addMsg(gettext('Opener successfully deleted'), 'success') | ||||
|     $('#opener_table').load(location.pathname + ' #opener_table') | ||||
|   }).fail(function (xhr, _textStatus, _error) { | ||||
|     errMsg(xhr.responseJSON) | ||||
|   }) | ||||
| } | ||||
|  | ||||
| $(document).ready(function () { | ||||
|   // Attach event | ||||
|   document.getElementById('form_opener').addEventListener('submit', form_create_opener) | ||||
| }) | ||||
| @@ -1,13 +1,17 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from django.utils import timezone | ||||
| from django.utils.html import format_html | ||||
| from django.utils.html import escape | ||||
| from django.utils.safestring import mark_safe | ||||
| from django.utils.translation import gettext_lazy as _ | ||||
| from note_kfet.middlewares import get_current_request | ||||
| import django_tables2 as tables | ||||
| from django_tables2 import A | ||||
| from permission.backends import PermissionBackend | ||||
| from note.templatetags.pretty_money import pretty_money | ||||
|  | ||||
| from .models import Activity, Entry, Guest | ||||
| from .models import Activity, Entry, Guest, Opener | ||||
|  | ||||
|  | ||||
| class ActivityTable(tables.Table): | ||||
| @@ -47,13 +51,13 @@ class GuestTable(tables.Table): | ||||
|         } | ||||
|         model = Guest | ||||
|         template_name = 'django_tables2/bootstrap4.html' | ||||
|         fields = ("last_name", "first_name", "inviter", ) | ||||
|         fields = ("last_name", "first_name", "inviter", "school") | ||||
|  | ||||
|     def render_entry(self, record): | ||||
|         if record.has_entry: | ||||
|             return str(_("Entered on ") + str(_("{:%Y-%m-%d %H:%M:%S}").format(record.entry.time, ))) | ||||
|         return format_html('<button id="{id}" class="btn btn-danger btn-sm" onclick="remove_guest(this.id)"> ' | ||||
|                            '{delete_trans}</button>'.format(id=record.id, delete_trans=_("remove").capitalize())) | ||||
|             return str(_("Entered on ") + str(_("{:%Y-%m-%d %H:%M:%S}").format(timezone.localtime(record.entry.time)))) | ||||
|         return mark_safe('<button id="{id}" class="btn btn-danger btn-sm" onclick="remove_guest(this.id)"> ' | ||||
|                          '{delete_trans}</button>'.format(id=record.id, delete_trans=_("remove").capitalize())) | ||||
|  | ||||
|  | ||||
| def get_row_class(record): | ||||
| @@ -91,7 +95,7 @@ class EntryTable(tables.Table): | ||||
|         if hasattr(record, 'username'): | ||||
|             username = record.username | ||||
|             if username != value: | ||||
|                 return format_html(value + " <em>aka.</em> " + username) | ||||
|                 return mark_safe(escape(value) + " <em>aka.</em> " + escape(username)) | ||||
|         return value | ||||
|  | ||||
|     def render_balance(self, value): | ||||
| @@ -111,3 +115,34 @@ class EntryTable(tables.Table): | ||||
|             'data-last-name': lambda record: record.last_name, | ||||
|             'data-first-name': lambda record: record.first_name, | ||||
|         } | ||||
|  | ||||
|  | ||||
| # function delete_button(id) provided in template file | ||||
| DELETE_TEMPLATE = """ | ||||
|     <button id="{{ record.pk }}" class="btn btn-danger btn-sm" onclick="delete_button(this.id)"> {{ delete_trans }}</button> | ||||
| """ | ||||
|  | ||||
|  | ||||
| class OpenerTable(tables.Table): | ||||
|     class Meta: | ||||
|         attrs = { | ||||
|             'class': 'table table condensed table-striped', | ||||
|             'id': "opener_table" | ||||
|         } | ||||
|         model = Opener | ||||
|         fields = ("opener",) | ||||
|         template_name = 'django_tables2/bootstrap4.html' | ||||
|  | ||||
|     show_header = False | ||||
|     opener = tables.Column(attrs={'td': {'class': 'text-center'}}) | ||||
|  | ||||
|     delete_col = tables.TemplateColumn( | ||||
|         template_code=DELETE_TEMPLATE, | ||||
|         extra_context={"delete_trans": _('Delete')}, | ||||
|         attrs={ | ||||
|             'td': { | ||||
|                 'class': lambda record: 'col-sm-1' | ||||
|                 + (' d-none' if not PermissionBackend.check_perm( | ||||
|                     get_current_request(), "activity.delete_opener", record) | ||||
|                    else '')}}, | ||||
|         verbose_name=_("Delete"),) | ||||
|   | ||||
| @@ -4,11 +4,31 @@ SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endcomment %} | ||||
| {% load i18n perms %} | ||||
| {% load render_table from django_tables2 %} | ||||
| {% load static django_tables2 i18n %} | ||||
|  | ||||
| {% block content %} | ||||
| <h1 class="text-white">{{ title }}</h1> | ||||
| {% include "activity/includes/activity_info.html" %} | ||||
|  | ||||
| {% if activity.activity_type.manage_entries and ".change__opener"|has_perm:activity %} | ||||
|     <div class="card bg-white mb-3"> | ||||
|         <h3 class="card-header text-center"> | ||||
|             {% trans "Openers" %} | ||||
|         </h3> | ||||
|         <div class="card-body"> | ||||
|             <form class="input-group" method="POST" id="form_opener"> | ||||
|                 {% csrf_token %} | ||||
|                 <input type="hidden" name="activity" value="{{ object.pk }}"> | ||||
|                 {%include "autocomplete_model.html" %} | ||||
|                 <div class="input-group-append"> | ||||
|                     <input type="submit" class="btn btn-success" value="{% trans "Add" %}"> | ||||
|                 </div> | ||||
|             </form> | ||||
|         </div> | ||||
|         {% render_table opener %} | ||||
|     </div> | ||||
| {% endif %} | ||||
|  | ||||
| {% if guests.data %} | ||||
| <div class="card bg-white mb-3"> | ||||
|     <h3 class="card-header text-center"> | ||||
| @@ -22,6 +42,8 @@ SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endblock %} | ||||
|  | ||||
| {% block extrajavascript %} | ||||
| <script src="{% static "activity/js/opener.js" %}"></script> | ||||
| <script src="{% static "js/autocomplete_model.js" %}"></script> | ||||
| <script> | ||||
|     function remove_guest(guest_id) { | ||||
|         $.ajax({ | ||||
| @@ -30,7 +52,7 @@ SPDX-License-Identifier: GPL-3.0-or-later | ||||
|          headers: {"X-CSRFTOKEN": CSRF_TOKEN} | ||||
|      }) | ||||
|       .done(function() { | ||||
|           addMsg('Invité supprimé','success'); | ||||
|           addMsg('{% trans "Guest deleted" %}', 'success'); | ||||
|           $("#guests_table").load(location.pathname + " #guests_table"); | ||||
|       }) | ||||
|       .fail(function(xhr, textStatus, error) { | ||||
| @@ -73,5 +95,23 @@ SPDX-License-Identifier: GPL-3.0-or-later | ||||
|             errMsg(xhr.responseJSON); | ||||
|         }); | ||||
|     }); | ||||
|     $("#delete_activity").click(function () { | ||||
|         if (!confirm("{% trans 'Are you sure you want to delete this activity?' %}")) { | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         $.ajax({ | ||||
|             url: "/api/activity/activity/{{ activity.pk }}/", | ||||
|             type: "DELETE", | ||||
|             headers: { | ||||
|                 "X-CSRFTOKEN": CSRF_TOKEN | ||||
|             } | ||||
|         }).done(function () { | ||||
|             addMsg("{% trans 'Activity deleted' %}", "success"); | ||||
|             window.location.href = "/activity/";  // Redirige vers la liste des activités | ||||
|         }).fail(function (xhr) { | ||||
|             errMsg(xhr.responseJSON); | ||||
|         }); | ||||
|     }); | ||||
| </script> | ||||
| {% endblock %} | ||||
|   | ||||
| @@ -63,7 +63,12 @@ SPDX-License-Identifier: GPL-3.0-or-later | ||||
|         refreshBalance(); | ||||
|     } | ||||
|  | ||||
|     alias_obj.keyup(reloadTable); | ||||
|     alias_obj.keyup(function(event) { | ||||
|         let code = event.originalEvent.keyCode | ||||
|         if (65 <= code <= 122 || code === 13) { | ||||
|             debounce(reloadTable)() | ||||
|         } | ||||
|     }); | ||||
|  | ||||
|     $(document).ready(init); | ||||
|  | ||||
| @@ -86,10 +91,10 @@ SPDX-License-Identifier: GPL-3.0-or-later | ||||
|                 }).done(function () { | ||||
|                     if (target.hasClass("table-info")) | ||||
|                         addMsg( | ||||
|                             "Entrée effectuée, mais attention : la personne n'est plus adhérente Kfet.", | ||||
|                             "{% trans "Entry done, but caution: the user is not a Kfet member." %}", | ||||
|                             "warning", 10000); | ||||
|                     else | ||||
|                         addMsg("Entrée effectuée !", "success", 4000); | ||||
|                         addMsg("Entry made!", "success", 4000); | ||||
|                     reloadTable(true); | ||||
|                 }).fail(function (xhr) { | ||||
|                     errMsg(xhr.responseJSON, 4000); | ||||
| @@ -121,10 +126,10 @@ SPDX-License-Identifier: GPL-3.0-or-later | ||||
|                     }).done(function () { | ||||
|                         if (target.hasClass("table-info")) | ||||
|                             addMsg( | ||||
|                                 "Entrée effectuée, mais attention : la personne n'est plus adhérente Kfet.", | ||||
|                                 "{% trans "Entry done, but caution: the user is not a Kfet member." %}", | ||||
|                                 "warning", 10000); | ||||
|                         else | ||||
|                             addMsg("Entrée effectuée !", "success", 4000); | ||||
|                             addMsg("{% trans "Entry done!" %}", "success", 4000); | ||||
|                         reloadTable(true); | ||||
|                     }).fail(function (xhr) { | ||||
|                         errMsg(xhr.responseJSON, 4000); | ||||
|   | ||||
| @@ -17,4 +17,27 @@ SPDX-License-Identifier: GPL-3.0-or-later | ||||
|     </form> | ||||
|   </div> | ||||
| </div> | ||||
| {% endblock %} | ||||
| {% endblock %} | ||||
|  | ||||
| {% block extrajavascript %} | ||||
| <script> | ||||
|   var date_end = document.getElementById("id_date_end"); | ||||
|   var date_start = document.getElementById("id_date_start"); | ||||
|  | ||||
|   function update_date_end (){ | ||||
|     if(date_end.value=="" || date_end.value<date_start.value){ | ||||
|       date_end.value = date_start.value; | ||||
|     }; | ||||
|   }; | ||||
|  | ||||
|   function update_date_start (){ | ||||
|     if(date_start.value=="" || date_end.value<date_start.value){ | ||||
|       date_start.value = date_end.value; | ||||
|     }; | ||||
|   }; | ||||
|  | ||||
|   date_start.addEventListener('focusout', update_date_end); | ||||
|   date_end.addEventListener('focusout', update_date_start); | ||||
|    | ||||
| </script> | ||||
| {% endblock %} | ||||
|   | ||||
| @@ -46,4 +46,4 @@ SPDX-License-Identifier: GPL-3.0-or-later | ||||
|     </h3> | ||||
|     {% render_table table %} | ||||
| </div> | ||||
| {% endblock %} | ||||
| {% endblock %} | ||||
|   | ||||
| @@ -70,7 +70,10 @@ SPDX-License-Identifier: GPL-3.0-or-later | ||||
|             {% if ".change_"|has_perm:activity %} | ||||
|                 <a class="btn btn-primary btn-sm my-1" href="{% url 'activity:activity_update' pk=activity.pk %}" data-turbolinks="false"> {% trans "edit"|capfirst %}</a> | ||||
|             {% endif %} | ||||
|             {% if activity.activity_type.can_invite and not activity_started %} | ||||
|             {% if not activity.valid and ".delete_"|has_perm:activity %} | ||||
|                 <a class="btn btn-danger btn-sm my-1" id="delete_activity"> {% trans "delete"|capfirst %} </a> | ||||
|             {% endif %} | ||||
|             {% if activity.activity_type.can_invite and not activity_started and activity.valid %} | ||||
|                 <a class="btn btn-primary btn-sm my-1" href="{% url 'activity:activity_invite' pk=activity.pk %}" data-turbolinks="false"> {% trans "Invite" %}</a> | ||||
|             {% endif %} | ||||
|         {% endif %} | ||||
|   | ||||
| @@ -1,15 +1,18 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from datetime import timedelta | ||||
|  | ||||
| from api.tests import TestAPI | ||||
| from django.contrib.auth.models import User | ||||
| from django.test import TestCase | ||||
| from django.urls import reverse | ||||
| from django.utils import timezone | ||||
| from activity.models import Activity, ActivityType, Guest, Entry | ||||
| from member.models import Club | ||||
|  | ||||
| from ..api.views import ActivityTypeViewSet, ActivityViewSet, EntryViewSet, GuestViewSet | ||||
| from ..models import Activity, ActivityType, Guest, Entry | ||||
|  | ||||
|  | ||||
| class TestActivities(TestCase): | ||||
|     """ | ||||
| @@ -47,6 +50,7 @@ class TestActivities(TestCase): | ||||
|             inviter=self.user.note, | ||||
|             last_name="GUEST", | ||||
|             first_name="Guest", | ||||
|             school="School", | ||||
|         ) | ||||
|  | ||||
|     def test_activity_list(self): | ||||
| @@ -153,6 +157,7 @@ class TestActivities(TestCase): | ||||
|             inviter=self.user.note.id, | ||||
|             last_name="GUEST2", | ||||
|             first_name="Guest", | ||||
|             school="School", | ||||
|         )) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
| @@ -164,6 +169,7 @@ class TestActivities(TestCase): | ||||
|             inviter=self.user.note.id, | ||||
|             last_name="GUEST2", | ||||
|             first_name="Guest", | ||||
|             school="School", | ||||
|         )) | ||||
|         self.assertRedirects(response, reverse("activity:activity_detail", args=(self.activity.pk,)), 302, 200) | ||||
|  | ||||
| @@ -173,3 +179,59 @@ class TestActivities(TestCase): | ||||
|         """ | ||||
|         response = self.client.get(reverse("activity:calendar_ics")) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
|  | ||||
| class TestActivityAPI(TestAPI): | ||||
|     def setUp(self) -> None: | ||||
|         super().setUp() | ||||
|  | ||||
|         self.activity = Activity.objects.create( | ||||
|             name="Activity", | ||||
|             description="This is a test activity\non two very very long lines\nbecause this is very important.", | ||||
|             location="Earth", | ||||
|             activity_type=ActivityType.objects.get(name="Pot"), | ||||
|             creater=self.user, | ||||
|             organizer=Club.objects.get(name="Kfet"), | ||||
|             attendees_club=Club.objects.get(name="Kfet"), | ||||
|             date_start=timezone.now(), | ||||
|             date_end=timezone.now() + timedelta(days=2), | ||||
|             valid=True, | ||||
|         ) | ||||
|  | ||||
|         self.guest = Guest.objects.create( | ||||
|             activity=self.activity, | ||||
|             inviter=self.user.note, | ||||
|             last_name="GUEST", | ||||
|             first_name="Guest", | ||||
|             school="School", | ||||
|         ) | ||||
|  | ||||
|         self.entry = Entry.objects.create( | ||||
|             activity=self.activity, | ||||
|             note=self.user.note, | ||||
|             guest=self.guest, | ||||
|         ) | ||||
|  | ||||
|     def test_activity_api(self): | ||||
|         """ | ||||
|         Load Activity API page and test all filters and permissions | ||||
|         """ | ||||
|         self.check_viewset(ActivityViewSet, "/api/activity/activity/") | ||||
|  | ||||
|     def test_activity_type_api(self): | ||||
|         """ | ||||
|         Load ActivityType API page and test all filters and permissions | ||||
|         """ | ||||
|         self.check_viewset(ActivityTypeViewSet, "/api/activity/type/") | ||||
|  | ||||
|     def test_entry_api(self): | ||||
|         """ | ||||
|         Load Entry API page and test all filters and permissions | ||||
|         """ | ||||
|         self.check_viewset(EntryViewSet, "/api/activity/entry/") | ||||
|  | ||||
|     def test_guest_api(self): | ||||
|         """ | ||||
|         Load Guest API page and test all filters and permissions | ||||
|         """ | ||||
|         self.check_viewset(GuestViewSet, "/api/activity/guest/") | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from django.urls import path | ||||
| @@ -15,4 +15,5 @@ urlpatterns = [ | ||||
|     path('<int:pk>/update/', views.ActivityUpdateView.as_view(), name='activity_update'), | ||||
|     path('new/', views.ActivityCreateView.as_view(), name='activity_create'), | ||||
|     path('calendar.ics', views.CalendarView.as_view(), name='calendar_ics'), | ||||
|     path('<int:pk>/delete', views.ActivityDeleteView.as_view(), name='delete_activity'), | ||||
| ] | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from hashlib import md5 | ||||
| @@ -9,7 +9,7 @@ from django.contrib.contenttypes.models import ContentType | ||||
| from django.core.exceptions import PermissionDenied | ||||
| from django.db import transaction | ||||
| from django.db.models import F, Q | ||||
| from django.http import HttpResponse | ||||
| from django.http import HttpResponse, JsonResponse | ||||
| from django.urls import reverse_lazy | ||||
| from django.utils import timezone | ||||
| from django.utils.decorators import method_decorator | ||||
| @@ -17,14 +17,16 @@ from django.utils.translation import gettext_lazy as _ | ||||
| from django.views import View | ||||
| from django.views.decorators.cache import cache_page | ||||
| from django.views.generic import DetailView, TemplateView, UpdateView | ||||
| from django_tables2.views import SingleTableView | ||||
| from django.views.generic.list import ListView | ||||
| from django_tables2.views import MultiTableMixin, SingleTableMixin | ||||
| from api.viewsets import is_regex | ||||
| from note.models import Alias, NoteSpecial, NoteUser | ||||
| from permission.backends import PermissionBackend | ||||
| from permission.views import ProtectQuerysetMixin, ProtectedCreateView | ||||
|  | ||||
| from .forms import ActivityForm, GuestForm | ||||
| from .models import Activity, Entry, Guest | ||||
| from .tables import ActivityTable, EntryTable, GuestTable | ||||
| from .models import Activity, Entry, Guest, Opener | ||||
| from .tables import ActivityTable, EntryTable, GuestTable, OpenerTable | ||||
|  | ||||
|  | ||||
| class ActivityCreateView(ProtectQuerysetMixin, ProtectedCreateView): | ||||
| @@ -57,36 +59,44 @@ class ActivityCreateView(ProtectQuerysetMixin, ProtectedCreateView): | ||||
|         return reverse_lazy('activity:activity_detail', kwargs={"pk": self.object.pk}) | ||||
|  | ||||
|  | ||||
| class ActivityListView(ProtectQuerysetMixin, LoginRequiredMixin, SingleTableView): | ||||
| class ActivityListView(ProtectQuerysetMixin, LoginRequiredMixin, MultiTableMixin, ListView): | ||||
|     """ | ||||
|     Displays all Activities, and classify if they are on-going or upcoming ones. | ||||
|     """ | ||||
|     model = Activity | ||||
|     table_class = ActivityTable | ||||
|     ordering = ('-date_start',) | ||||
|     tables = [ | ||||
|         lambda data: ActivityTable(data, prefix="all-"), | ||||
|         lambda data: ActivityTable(data, prefix="upcoming-"), | ||||
|     ] | ||||
|     extra_context = {"title": _("Activities")} | ||||
|  | ||||
|     def get_queryset(self): | ||||
|         return super().get_queryset().distinct() | ||||
|     def get_queryset(self, **kwargs): | ||||
|         return super().get_queryset(**kwargs).distinct() | ||||
|  | ||||
|     def get_tables_data(self): | ||||
|         # first table = all activities, second table = upcoming | ||||
|         return [ | ||||
|             self.get_queryset().order_by("-date_start"), | ||||
|             Activity.objects.filter(date_end__gt=timezone.now()) | ||||
|                             .filter(PermissionBackend.filter_queryset(self.request, Activity, "view")) | ||||
|                             .distinct() | ||||
|                             .order_by("date_start") | ||||
|         ] | ||||
|  | ||||
|     def get_context_data(self, **kwargs): | ||||
|         context = super().get_context_data(**kwargs) | ||||
|  | ||||
|         upcoming_activities = Activity.objects.filter(date_end__gt=timezone.now()) | ||||
|         context['upcoming'] = ActivityTable( | ||||
|             data=upcoming_activities.filter(PermissionBackend.filter_queryset(self.request.user, Activity, "view")), | ||||
|             prefix='upcoming-', | ||||
|         ) | ||||
|         tables = context["tables"] | ||||
|         for name, table in zip(["table", "upcoming"], tables): | ||||
|             context[name] = table | ||||
|  | ||||
|         started_activities = Activity.objects\ | ||||
|             .filter(PermissionBackend.filter_queryset(self.request.user, Activity, "view"))\ | ||||
|             .filter(open=True, valid=True).all() | ||||
|         started_activities = self.get_queryset().filter(open=True, valid=True).distinct().all() | ||||
|         context["started_activities"] = started_activities | ||||
|  | ||||
|         return context | ||||
|  | ||||
|  | ||||
| class ActivityDetailView(ProtectQuerysetMixin, LoginRequiredMixin, DetailView): | ||||
| class ActivityDetailView(ProtectQuerysetMixin, LoginRequiredMixin, MultiTableMixin, DetailView): | ||||
|     """ | ||||
|     Shows details about one activity. Add guest to context | ||||
|     """ | ||||
| @@ -94,15 +104,40 @@ class ActivityDetailView(ProtectQuerysetMixin, LoginRequiredMixin, DetailView): | ||||
|     context_object_name = "activity" | ||||
|     extra_context = {"title": _("Activity detail")} | ||||
|  | ||||
|     tables = [ | ||||
|         lambda data: GuestTable(data, prefix="guests-"), | ||||
|         lambda data: OpenerTable(data, prefix="opener-"), | ||||
|     ] | ||||
|  | ||||
|     def get_tables_data(self): | ||||
|         return [ | ||||
|             Guest.objects.filter(activity=self.object) | ||||
|                          .filter(PermissionBackend.filter_queryset(self.request, Guest, "view")), | ||||
|             self.object.opener.filter(activity=self.object) | ||||
|                               .filter(PermissionBackend.filter_queryset(self.request, Opener, "view")), | ||||
|         ] | ||||
|  | ||||
|     def get_context_data(self, **kwargs): | ||||
|         context = super().get_context_data() | ||||
|  | ||||
|         table = GuestTable(data=Guest.objects.filter(activity=self.object) | ||||
|                            .filter(PermissionBackend.filter_queryset(self.request.user, Guest, "view"))) | ||||
|         context["guests"] = table | ||||
|         tables = context["tables"] | ||||
|         for name, table in zip(["guests", "opener"], tables): | ||||
|             context[name] = table | ||||
|  | ||||
|         context["activity_started"] = timezone.now() > timezone.localtime(self.object.date_start) | ||||
|  | ||||
|         context["widget"] = { | ||||
|             "name": "opener", | ||||
|             "resetable": True, | ||||
|             "attrs": { | ||||
|                 "class": "autocomplete form-control", | ||||
|                 "id": "opener", | ||||
|                 "api_url": "/api/note/alias/?note__polymorphic_ctype__model=noteuser", | ||||
|                 "name_field": "name", | ||||
|                 "placeholder": "" | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         return context | ||||
|  | ||||
|  | ||||
| @@ -118,6 +153,34 @@ class ActivityUpdateView(ProtectQuerysetMixin, LoginRequiredMixin, UpdateView): | ||||
|         return reverse_lazy('activity:activity_detail', kwargs={"pk": self.kwargs["pk"]}) | ||||
|  | ||||
|  | ||||
| class ActivityDeleteView(View): | ||||
|     """ | ||||
|     Deletes an Activity | ||||
|     """ | ||||
|     def delete(self, request, pk): | ||||
|         try: | ||||
|             activity = Activity.objects.get(pk=pk) | ||||
|             activity.delete() | ||||
|             return JsonResponse({"message": "Activity deleted"}) | ||||
|         except Activity.DoesNotExist: | ||||
|             return JsonResponse({"error": "Activity not found"}, status=404) | ||||
|  | ||||
|     def dispatch(self, *args, **kwargs): | ||||
|         """ | ||||
|         Don't display the delete button if the user has no right to delete. | ||||
|         """ | ||||
|         if not self.request.user.is_authenticated: | ||||
|             return self.handle_no_permission() | ||||
|  | ||||
|         activity = Activity.objects.get(pk=self.kwargs["pk"]) | ||||
|         if not PermissionBackend.check_perm(self.request, "activity.delete_activity", activity): | ||||
|             raise PermissionDenied(_("You are not allowed to delete this activity.")) | ||||
|  | ||||
|         if activity.valid: | ||||
|             raise PermissionDenied(_("This activity is valid.")) | ||||
|         return super().dispatch(*args, **kwargs) | ||||
|  | ||||
|  | ||||
| class ActivityInviteView(ProtectQuerysetMixin, ProtectedCreateView): | ||||
|     """ | ||||
|     Invite a Guest, The rules to invites someone are defined in `forms:activity.GuestForm` | ||||
| @@ -133,6 +196,7 @@ class ActivityInviteView(ProtectQuerysetMixin, ProtectedCreateView): | ||||
|             activity=activity, | ||||
|             first_name="", | ||||
|             last_name="", | ||||
|             school="", | ||||
|             inviter=self.request.user.note, | ||||
|         ) | ||||
|  | ||||
| @@ -144,36 +208,41 @@ class ActivityInviteView(ProtectQuerysetMixin, ProtectedCreateView): | ||||
|  | ||||
|     def get_form(self, form_class=None): | ||||
|         form = super().get_form(form_class) | ||||
|         form.activity = Activity.objects.filter(PermissionBackend.filter_queryset(self.request.user, Activity, "view"))\ | ||||
|             .get(pk=self.kwargs["pk"]) | ||||
|         form.activity = Activity.objects.filter(PermissionBackend.filter_queryset(self.request, Activity, "view"))\ | ||||
|             .filter(pk=self.kwargs["pk"]).first() | ||||
|         form.fields["inviter"].initial = self.request.user.note | ||||
|         return form | ||||
|  | ||||
|     @transaction.atomic | ||||
|     def form_valid(self, form): | ||||
|         form.instance.activity = Activity.objects\ | ||||
|             .filter(PermissionBackend.filter_queryset(self.request.user, Activity, "view")).get(pk=self.kwargs["pk"]) | ||||
|             .filter(PermissionBackend.filter_queryset(self.request, Activity, "view")).get(pk=self.kwargs["pk"]) | ||||
|         return super().form_valid(form) | ||||
|  | ||||
|     def get_success_url(self, **kwargs): | ||||
|         return reverse_lazy('activity:activity_detail', kwargs={"pk": self.kwargs["pk"]}) | ||||
|  | ||||
|  | ||||
| class ActivityEntryView(LoginRequiredMixin, TemplateView): | ||||
| class ActivityEntryView(LoginRequiredMixin, SingleTableMixin, TemplateView): | ||||
|     """ | ||||
|     Manages entry to an activity | ||||
|     """ | ||||
|     template_name = "activity/activity_entry.html" | ||||
|  | ||||
|     table_class = EntryTable | ||||
|  | ||||
|     def dispatch(self, request, *args, **kwargs): | ||||
|         """ | ||||
|         Don't display the entry interface if the user has no right to see it (no right to add an entry for itself), | ||||
|         it is closed or doesn't manage entries. | ||||
|         """ | ||||
|         if not self.request.user.is_authenticated: | ||||
|             return self.handle_no_permission() | ||||
|  | ||||
|         activity = Activity.objects.get(pk=self.kwargs["pk"]) | ||||
|  | ||||
|         sample_entry = Entry(activity=activity, note=self.request.user.note) | ||||
|         if not PermissionBackend.check_perm(self.request.user, "activity.add_entry", sample_entry): | ||||
|         if not PermissionBackend.check_perm(self.request, "activity.add_entry", sample_entry): | ||||
|             raise PermissionDenied(_("You are not allowed to display the entry interface for this activity.")) | ||||
|  | ||||
|         if not activity.activity_type.manage_entries: | ||||
| @@ -191,22 +260,25 @@ class ActivityEntryView(LoginRequiredMixin, TemplateView): | ||||
|         guest_qs = Guest.objects\ | ||||
|             .annotate(balance=F("inviter__balance"), note_name=F("inviter__user__username"))\ | ||||
|             .filter(activity=activity)\ | ||||
|             .filter(PermissionBackend.filter_queryset(self.request.user, Guest, "view"))\ | ||||
|             .order_by('last_name', 'first_name').distinct() | ||||
|             .filter(PermissionBackend.filter_queryset(self.request, Guest, "view"))\ | ||||
|             .order_by('last_name', 'first_name') | ||||
|  | ||||
|         if "search" in self.request.GET and self.request.GET["search"]: | ||||
|             pattern = self.request.GET["search"] | ||||
|             if pattern[0] != "^": | ||||
|                 pattern = "^" + pattern | ||||
|  | ||||
|             # Check if this is a valid regex. If not, we won't check regex | ||||
|             valid_regex = is_regex(pattern) | ||||
|             suffix = "__iregex" if valid_regex else "__istartswith" | ||||
|             pattern = "^" + pattern if valid_regex and pattern[0] != "^" else pattern | ||||
|             guest_qs = guest_qs.filter( | ||||
|                 Q(first_name__iregex=pattern) | ||||
|                 | Q(last_name__iregex=pattern) | ||||
|                 | Q(inviter__alias__name__iregex=pattern) | ||||
|                 | Q(inviter__alias__normalized_name__iregex=Alias.normalize(pattern)) | ||||
|                 Q(**{f"first_name{suffix}": pattern}) | ||||
|                 | Q(**{f"last_name{suffix}": pattern}) | ||||
|                 | Q(**{f"inviter__alias__name{suffix}": pattern}) | ||||
|                 | Q(**{f"inviter__alias__normalized_name{suffix}": Alias.normalize(pattern)}) | ||||
|             ) | ||||
|         else: | ||||
|             guest_qs = guest_qs.none() | ||||
|         return guest_qs | ||||
|         return guest_qs.distinct() | ||||
|  | ||||
|     def get_invited_note(self, activity): | ||||
|         """ | ||||
| @@ -222,23 +294,26 @@ class ActivityEntryView(LoginRequiredMixin, TemplateView): | ||||
|         # Keep only users that have a note | ||||
|         note_qs = note_qs.filter(note__noteuser__isnull=False) | ||||
|  | ||||
|         # Keep only members | ||||
|         # Keep only valid members | ||||
|         note_qs = note_qs.filter( | ||||
|             note__noteuser__user__memberships__club=activity.attendees_club, | ||||
|             note__noteuser__user__memberships__date_start__lte=timezone.now(), | ||||
|             note__noteuser__user__memberships__date_end__gte=timezone.now(), | ||||
|         ) | ||||
|             note__noteuser__user__memberships__date_end__gte=timezone.now()).exclude(note__inactivity_reason='forced') | ||||
|  | ||||
|         # Filter with permission backend | ||||
|         note_qs = note_qs.filter(PermissionBackend.filter_queryset(self.request.user, Alias, "view")) | ||||
|         note_qs = note_qs.filter(PermissionBackend.filter_queryset(self.request, Alias, "view")) | ||||
|  | ||||
|         if "search" in self.request.GET and self.request.GET["search"]: | ||||
|             pattern = self.request.GET["search"] | ||||
|  | ||||
|             # Check if this is a valid regex. If not, we won't check regex | ||||
|             valid_regex = is_regex(pattern) | ||||
|             suffix = "__iregex" if valid_regex else "__icontains" | ||||
|             note_qs = note_qs.filter( | ||||
|                 Q(note__noteuser__user__first_name__iregex=pattern) | ||||
|                 | Q(note__noteuser__user__last_name__iregex=pattern) | ||||
|                 | Q(name__iregex=pattern) | ||||
|                 | Q(normalized_name__iregex=Alias.normalize(pattern)) | ||||
|                 Q(**{f"note__noteuser__user__first_name{suffix}": pattern}) | ||||
|                 | Q(**{f"note__noteuser__user__last_name{suffix}": pattern}) | ||||
|                 | Q(**{f"name{suffix}": pattern}) | ||||
|                 | Q(**{f"normalized_name{suffix}": Alias.normalize(pattern)}) | ||||
|             ) | ||||
|         else: | ||||
|             note_qs = note_qs.none() | ||||
| @@ -250,15 +325,9 @@ class ActivityEntryView(LoginRequiredMixin, TemplateView): | ||||
|             if settings.DATABASES[note_qs.db]["ENGINE"] == 'django.db.backends.postgresql' else note_qs.distinct()[:20] | ||||
|         return note_qs | ||||
|  | ||||
|     def get_context_data(self, **kwargs): | ||||
|         """ | ||||
|         Query the list of Guest and Note to the activity and add information to makes entry with JS. | ||||
|         """ | ||||
|         context = super().get_context_data(**kwargs) | ||||
|  | ||||
|         activity = Activity.objects.filter(PermissionBackend.filter_queryset(self.request.user, Activity, "view"))\ | ||||
|     def get_table_data(self): | ||||
|         activity = Activity.objects.filter(PermissionBackend.filter_queryset(self.request, Activity, "view"))\ | ||||
|             .distinct().get(pk=self.kwargs["pk"]) | ||||
|         context["activity"] = activity | ||||
|  | ||||
|         matched = [] | ||||
|  | ||||
| @@ -271,8 +340,17 @@ class ActivityEntryView(LoginRequiredMixin, TemplateView): | ||||
|             note.activity = activity | ||||
|             matched.append(note) | ||||
|  | ||||
|         table = EntryTable(data=matched) | ||||
|         context["table"] = table | ||||
|         return matched | ||||
|  | ||||
|     def get_context_data(self, **kwargs): | ||||
|         """ | ||||
|         Query the list of Guest and Note to the activity and add information to makes entry with JS. | ||||
|         """ | ||||
|         context = super().get_context_data(**kwargs) | ||||
|  | ||||
|         activity = Activity.objects.filter(PermissionBackend.filter_queryset(self.request, Activity, "view"))\ | ||||
|             .distinct().get(pk=self.kwargs["pk"]) | ||||
|         context["activity"] = activity | ||||
|  | ||||
|         context["entries"] = Entry.objects.filter(activity=activity) | ||||
|  | ||||
| @@ -280,10 +358,10 @@ class ActivityEntryView(LoginRequiredMixin, TemplateView): | ||||
|         context["noteuser_ctype"] = ContentType.objects.get_for_model(NoteUser).pk | ||||
|         context["notespecial_ctype"] = ContentType.objects.get_for_model(NoteSpecial).pk | ||||
|  | ||||
|         activities_open = Activity.objects.filter(open=True).filter( | ||||
|             PermissionBackend.filter_queryset(self.request.user, Activity, "view")).distinct().all() | ||||
|         activities_open = Activity.objects.filter(open=True, activity_type__manage_entries=True).filter( | ||||
|             PermissionBackend.filter_queryset(self.request, Activity, "view")).distinct().all() | ||||
|         context["activities_open"] = [a for a in activities_open | ||||
|                                       if PermissionBackend.check_perm(self.request.user, | ||||
|                                       if PermissionBackend.check_perm(self.request, | ||||
|                                                                       "activity.add_entry", | ||||
|                                                                       Entry(activity=a, note=self.request.user.note,))] | ||||
|  | ||||
| @@ -314,8 +392,8 @@ X-WR-CALNAME:Kfet Calendar | ||||
| NAME:Kfet Calendar | ||||
| CALSCALE:GREGORIAN | ||||
| BEGIN:VTIMEZONE | ||||
| TZID:Europe/Berlin | ||||
| X-LIC-LOCATION:Europe/Berlin | ||||
| TZID:Europe/Paris | ||||
| X-LIC-LOCATION:Europe/Paris | ||||
| BEGIN:DAYLIGHT | ||||
| TZOFFSETFROM:+0100 | ||||
| TZOFFSETTO:+0200 | ||||
| @@ -337,10 +415,10 @@ END:VTIMEZONE | ||||
| DTSTAMP:{"{:%Y%m%dT%H%M%S}".format(activity.date_start)}Z | ||||
| UID:{md5((activity.name + "$" + str(activity.id) + str(activity.date_start)).encode("UTF-8")).hexdigest()} | ||||
| SUMMARY;CHARSET=UTF-8:{self.multilines(activity.name, 75, 22)} | ||||
| DTSTART;TZID=Europe/Berlin:{"{:%Y%m%dT%H%M%S}".format(activity.date_start)} | ||||
| DTEND;TZID=Europe/Berlin:{"{:%Y%m%dT%H%M%S}".format(activity.date_end)} | ||||
| DTSTART:{"{:%Y%m%dT%H%M%S}Z".format(activity.date_start)} | ||||
| DTEND:{"{:%Y%m%dT%H%M%S}Z".format(activity.date_end)} | ||||
| LOCATION:{self.multilines(activity.location, 75, 9) if activity.location else "Kfet"} | ||||
| DESCRIPTION;CHARSET=UTF-8:""" + self.multilines(activity.description.replace("\n", "\\n"), 75, 26) + """ | ||||
| DESCRIPTION;CHARSET=UTF-8:""" + self.multilines(activity.description.replace("\n", "\\n"), 75, 26) + f""" | ||||
|  -- {activity.organizer.name} | ||||
| END:VEVENT | ||||
| """ | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| default_app_config = 'api.apps.APIConfig' | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from django.apps import AppConfig | ||||
|   | ||||
							
								
								
									
										42
									
								
								apps/api/filters.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										42
									
								
								apps/api/filters.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,42 @@ | ||||
| import re | ||||
| from functools import lru_cache | ||||
|  | ||||
| from rest_framework.filters import SearchFilter | ||||
|  | ||||
|  | ||||
| class RegexSafeSearchFilter(SearchFilter): | ||||
|     @lru_cache | ||||
|     def validate_regex(self, search_term) -> bool: | ||||
|         try: | ||||
|             re.compile(search_term) | ||||
|             return True | ||||
|         except re.error: | ||||
|             return False | ||||
|  | ||||
|     def get_search_fields(self, view, request): | ||||
|         """ | ||||
|         Ensure that given regex are valid. | ||||
|         If not, we consider that the user is trying to search by substring. | ||||
|         """ | ||||
|         search_fields = super().get_search_fields(view, request) | ||||
|         search_terms = self.get_search_terms(request) | ||||
|  | ||||
|         for search_term in search_terms: | ||||
|             if not self.validate_regex(search_term): | ||||
|                 # Invalid regex. We assume we don't query by regex but by substring. | ||||
|                 search_fields = [f.replace('$', '') for f in search_fields] | ||||
|                 break | ||||
|  | ||||
|         return search_fields | ||||
|  | ||||
|     def get_search_terms(self, request): | ||||
|         """ | ||||
|         Ensure that search field is a valid regex query. If not, we remove extra characters. | ||||
|         """ | ||||
|         terms = super().get_search_terms(request) | ||||
|         if not all(self.validate_regex(term) for term in terms): | ||||
|             # Invalid regex. If a ^ is prefixed to the search term, we remove it. | ||||
|             terms = [term[1:] if term[0] == '^' else term for term in terms] | ||||
|             # Same for dollars. | ||||
|             terms = [term[:-1] if term[-1] == '$' else term for term in terms] | ||||
|         return terms | ||||
							
								
								
									
										5
									
								
								apps/api/pagination.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										5
									
								
								apps/api/pagination.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,5 @@ | ||||
| from rest_framework.pagination import PageNumberPagination | ||||
|  | ||||
|  | ||||
| class CustomPagination(PageNumberPagination): | ||||
|     page_size_query_param = 'page_size' | ||||
| @@ -1,13 +1,20 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
|  | ||||
| from django.contrib.contenttypes.models import ContentType | ||||
| from django.contrib.auth.models import User | ||||
| from rest_framework.serializers import ModelSerializer | ||||
| from django.utils import timezone | ||||
| from rest_framework import serializers | ||||
| from member.api.serializers import ProfileSerializer, MembershipSerializer | ||||
| from member.models import Membership | ||||
| from note.api.serializers import NoteSerializer | ||||
| from note.models import Alias | ||||
| from note_kfet.middlewares import get_current_request | ||||
| from permission.backends import PermissionBackend | ||||
|  | ||||
|  | ||||
| class UserSerializer(ModelSerializer): | ||||
| class UserSerializer(serializers.ModelSerializer): | ||||
|     """ | ||||
|     REST API Serializer for Users. | ||||
|     The djangorestframework plugin will analyse the model `User` and parse all fields in the API. | ||||
| @@ -22,7 +29,7 @@ class UserSerializer(ModelSerializer): | ||||
|         ) | ||||
|  | ||||
|  | ||||
| class ContentTypeSerializer(ModelSerializer): | ||||
| class ContentTypeSerializer(serializers.ModelSerializer): | ||||
|     """ | ||||
|     REST API Serializer for Users. | ||||
|     The djangorestframework plugin will analyse the model `User` and parse all fields in the API. | ||||
| @@ -31,3 +38,54 @@ class ContentTypeSerializer(ModelSerializer): | ||||
|     class Meta: | ||||
|         model = ContentType | ||||
|         fields = '__all__' | ||||
|  | ||||
|  | ||||
| class OAuthSerializer(serializers.ModelSerializer): | ||||
|     """ | ||||
|     Informations that are transmitted by OAuth. | ||||
|     For now, this includes user, profile and valid memberships. | ||||
|     This should be better managed later. | ||||
|     """ | ||||
|     normalized_name = serializers.SerializerMethodField() | ||||
|  | ||||
|     profile = serializers.SerializerMethodField() | ||||
|  | ||||
|     note = serializers.SerializerMethodField() | ||||
|  | ||||
|     memberships = serializers.SerializerMethodField() | ||||
|  | ||||
|     def get_normalized_name(self, obj): | ||||
|         return Alias.normalize(obj.username) | ||||
|  | ||||
|     def get_profile(self, obj): | ||||
|         # Display the profile of the user only if we have rights to see it. | ||||
|         return ProfileSerializer().to_representation(obj.profile) \ | ||||
|             if PermissionBackend.check_perm(get_current_request(), 'member.view_profile', obj.profile) else None | ||||
|  | ||||
|     def get_note(self, obj): | ||||
|         # Display the note of the user only if we have rights to see it. | ||||
|         return NoteSerializer().to_representation(obj.note) \ | ||||
|             if PermissionBackend.check_perm(get_current_request(), 'note.view_note', obj.note) else None | ||||
|  | ||||
|     def get_memberships(self, obj): | ||||
|         # Display only memberships that we are allowed to see. | ||||
|         return serializers.ListSerializer(child=MembershipSerializer()).to_representation( | ||||
|             obj.memberships.filter(date_start__lte=timezone.now(), date_end__gte=timezone.now()) | ||||
|                            .filter(PermissionBackend.filter_queryset(get_current_request(), Membership, 'view'))) | ||||
|  | ||||
|     class Meta: | ||||
|         model = User | ||||
|         fields = ( | ||||
|             'id', | ||||
|             'username', | ||||
|             'normalized_name', | ||||
|             'first_name', | ||||
|             'last_name', | ||||
|             'email', | ||||
|             'is_superuser', | ||||
|             'is_active', | ||||
|             'is_staff', | ||||
|             'profile', | ||||
|             'note', | ||||
|             'memberships', | ||||
|         ) | ||||
|   | ||||
							
								
								
									
										241
									
								
								apps/api/tests.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										241
									
								
								apps/api/tests.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,241 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| import json | ||||
| from datetime import datetime, date | ||||
| from decimal import Decimal | ||||
| from urllib.parse import quote_plus | ||||
| from warnings import warn | ||||
|  | ||||
| from django.contrib.auth.models import User | ||||
| from django.contrib.contenttypes.models import ContentType | ||||
| from django.db.models.fields.files import ImageFieldFile | ||||
| from django.test import TestCase | ||||
| from django_filters.rest_framework import DjangoFilterBackend | ||||
| from phonenumbers import PhoneNumber | ||||
| from rest_framework.filters import OrderingFilter | ||||
| from api.filters import RegexSafeSearchFilter | ||||
| from member.models import Membership, Club | ||||
| from note.models import NoteClub, NoteUser, Alias, Note | ||||
| from permission.models import PermissionMask, Permission, Role | ||||
|  | ||||
| from .viewsets import ContentTypeViewSet, UserViewSet | ||||
|  | ||||
|  | ||||
| class TestAPI(TestCase): | ||||
|     """ | ||||
|     Load API pages and check that filters are working. | ||||
|     """ | ||||
|     fixtures = ('initial', ) | ||||
|  | ||||
|     def setUp(self) -> None: | ||||
|         self.user = User.objects.create_superuser( | ||||
|             username="adminapi", | ||||
|             password="adminapi", | ||||
|             email="adminapi@example.com", | ||||
|             last_name="Admin", | ||||
|             first_name="Admin", | ||||
|         ) | ||||
|         self.client.force_login(self.user) | ||||
|  | ||||
|         sess = self.client.session | ||||
|         sess["permission_mask"] = 42 | ||||
|         sess.save() | ||||
|  | ||||
|     def check_viewset(self, viewset, url): | ||||
|         """ | ||||
|         This function should be called inside a unit test. | ||||
|         This loads the viewset and for each filter entry, it checks that the filter is running good. | ||||
|         """ | ||||
|         resp = self.client.get(url + "?format=json") | ||||
|         self.assertEqual(resp.status_code, 200) | ||||
|  | ||||
|         model = viewset.serializer_class.Meta.model | ||||
|  | ||||
|         if not model.objects.exists():  # pragma: no cover | ||||
|             warn(f"Warning: unable to test API filters for the model {model._meta.verbose_name} " | ||||
|                  "since there is no instance of it.") | ||||
|             return | ||||
|  | ||||
|         if hasattr(viewset, "filter_backends"): | ||||
|             backends = viewset.filter_backends | ||||
|             obj = model.objects.last() | ||||
|  | ||||
|             if DjangoFilterBackend in backends: | ||||
|                 # Specific search | ||||
|                 for field in viewset.filterset_fields: | ||||
|                     obj = self.fix_note_object(obj, field) | ||||
|  | ||||
|                     value = self.get_value(obj, field) | ||||
|                     if value is None:  # pragma: no cover | ||||
|                         warn(f"Warning: the filter {field} for the model {model._meta.verbose_name} " | ||||
|                              "has not been tested.") | ||||
|                         continue | ||||
|                     resp = self.client.get(url + f"?format=json&{field}={quote_plus(str(value))}") | ||||
|                     self.assertEqual(resp.status_code, 200, f"The filter {field} for the model " | ||||
|                                                             f"{model._meta.verbose_name} does not work. " | ||||
|                                                             f"Given parameter: {value}") | ||||
|                     content = json.loads(resp.content) | ||||
|                     self.assertGreater(content["count"], 0, f"The filter {field} for the model " | ||||
|                                                             f"{model._meta.verbose_name} does not work. " | ||||
|                                                             f"Given parameter: {value}") | ||||
|  | ||||
|             if OrderingFilter in backends: | ||||
|                 # Ensure that ordering is working well | ||||
|                 for field in viewset.ordering_fields: | ||||
|                     resp = self.client.get(url + f"?ordering={field}") | ||||
|                     self.assertEqual(resp.status_code, 200) | ||||
|                     resp = self.client.get(url + f"?ordering=-{field}") | ||||
|                     self.assertEqual(resp.status_code, 200) | ||||
|  | ||||
|             if RegexSafeSearchFilter in backends: | ||||
|                 # Basic search | ||||
|                 for field in viewset.search_fields: | ||||
|                     obj = self.fix_note_object(obj, field) | ||||
|  | ||||
|                     if field[0] == '$' or field[0] == '=': | ||||
|                         field = field[1:] | ||||
|                     value = self.get_value(obj, field) | ||||
|                     if value is None:  # pragma: no cover | ||||
|                         warn(f"Warning: the filter {field} for the model {model._meta.verbose_name} " | ||||
|                              "has not been tested.") | ||||
|                         continue | ||||
|                     resp = self.client.get(url + f"?format=json&search={quote_plus(str(value))}") | ||||
|                     self.assertEqual(resp.status_code, 200, f"The filter {field} for the model " | ||||
|                                                             f"{model._meta.verbose_name} does not work. " | ||||
|                                                             f"Given parameter: {value}") | ||||
|                     content = json.loads(resp.content) | ||||
|                     self.assertGreater(content["count"], 0, f"The filter {field} for the model " | ||||
|                                                             f"{model._meta.verbose_name} does not work. " | ||||
|                                                             f"Given parameter: {value}") | ||||
|  | ||||
|             self.check_permissions(url, obj) | ||||
|  | ||||
|     def check_permissions(self, url, obj): | ||||
|         """ | ||||
|         Check that permissions are working | ||||
|         """ | ||||
|         # Drop rights | ||||
|         self.user.is_superuser = False | ||||
|         self.user.save() | ||||
|         sess = self.client.session | ||||
|         sess["permission_mask"] = 0 | ||||
|         sess.save() | ||||
|  | ||||
|         # Delete user permissions | ||||
|         for m in Membership.objects.filter(user=self.user).all(): | ||||
|             m.roles.clear() | ||||
|             m.save() | ||||
|  | ||||
|         # Create a new role, which will have the checking permission | ||||
|         role = Role.objects.get_or_create(name="β-tester")[0] | ||||
|         role.permissions.clear() | ||||
|         role.save() | ||||
|         membership = Membership.objects.get_or_create(user=self.user, club=Club.objects.get(name="BDE"))[0] | ||||
|         membership.roles.set([role]) | ||||
|         membership.save() | ||||
|  | ||||
|         # Ensure that the access to the object is forbidden without permission | ||||
|         resp = self.client.get(url + f"{obj.pk}/") | ||||
|         self.assertEqual(resp.status_code, 404, f"Mysterious access to {url}{obj.pk}/ for {obj}") | ||||
|  | ||||
|         obj.refresh_from_db() | ||||
|  | ||||
|         # There are problems with polymorphism | ||||
|         if isinstance(obj, Note) and hasattr(obj, "note_ptr"): | ||||
|             obj = obj.note_ptr | ||||
|  | ||||
|         mask = PermissionMask.objects.get(rank=0) | ||||
|  | ||||
|         for field in obj._meta.fields: | ||||
|             # Build permission query | ||||
|             value = self.get_value(obj, field.name) | ||||
|             if isinstance(value, date) or isinstance(value, datetime): | ||||
|                 value = value.isoformat() | ||||
|             elif isinstance(value, ImageFieldFile): | ||||
|                 value = value.name | ||||
|             elif isinstance(value, Decimal): | ||||
|                 value = str(value) | ||||
|             query = json.dumps({field.name: value}) | ||||
|  | ||||
|             # Create sample permission | ||||
|             permission = Permission.objects.get_or_create( | ||||
|                 model=ContentType.objects.get_for_model(obj._meta.model), | ||||
|                 query=query, | ||||
|                 mask=mask, | ||||
|                 type="view", | ||||
|                 permanent=False, | ||||
|                 description=f"Can view {obj._meta.verbose_name}", | ||||
|             )[0] | ||||
|             role.permissions.set([permission]) | ||||
|             role.save() | ||||
|  | ||||
|             # Check that the access is possible | ||||
|             resp = self.client.get(url + f"{obj.pk}/") | ||||
|             self.assertEqual(resp.status_code, 200, f"Permission {permission.query} is not working " | ||||
|                                                     f"for the model {obj._meta.verbose_name}") | ||||
|  | ||||
|         # Restore rights | ||||
|         self.user.is_superuser = True | ||||
|         self.user.save() | ||||
|         sess = self.client.session | ||||
|         sess["permission_mask"] = 42 | ||||
|         sess.save() | ||||
|  | ||||
|     @staticmethod | ||||
|     def get_value(obj, key: str): | ||||
|         """ | ||||
|         Resolve the queryset filter to get the Python value of an object. | ||||
|         """ | ||||
|         if hasattr(obj, "all"): | ||||
|             # obj is a RelatedManager | ||||
|             obj = obj.last() | ||||
|  | ||||
|         if obj is None:  # pragma: no cover | ||||
|             return None | ||||
|  | ||||
|         if '__' not in key: | ||||
|             obj = getattr(obj, key) | ||||
|             if hasattr(obj, "pk"): | ||||
|                 return obj.pk | ||||
|             elif hasattr(obj, "all"): | ||||
|                 if not obj.exists():  # pragma: no cover | ||||
|                     return None | ||||
|                 return obj.last().pk | ||||
|             elif isinstance(obj, bool): | ||||
|                 return int(obj) | ||||
|             elif isinstance(obj, datetime): | ||||
|                 return obj.isoformat() | ||||
|             elif isinstance(obj, PhoneNumber): | ||||
|                 return obj.raw_input | ||||
|             return obj | ||||
|  | ||||
|         key, remaining = key.split('__', 1) | ||||
|         return TestAPI.get_value(getattr(obj, key), remaining) | ||||
|  | ||||
|     @staticmethod | ||||
|     def fix_note_object(obj, field): | ||||
|         """ | ||||
|         When querying an object that has a noteclub or a noteuser field, | ||||
|         ensure that the object has a good value. | ||||
|         """ | ||||
|         if isinstance(obj, Alias): | ||||
|             if "noteuser" in field: | ||||
|                 return NoteUser.objects.last().alias.last() | ||||
|             elif "noteclub" in field: | ||||
|                 return NoteClub.objects.last().alias.last() | ||||
|         elif isinstance(obj, Note): | ||||
|             if "noteuser" in field: | ||||
|                 return NoteUser.objects.last() | ||||
|             elif "noteclub" in field: | ||||
|                 return NoteClub.objects.last() | ||||
|         return obj | ||||
|  | ||||
|  | ||||
| class TestBasicAPI(TestAPI): | ||||
|     def test_user_api(self): | ||||
|         """ | ||||
|         Load the user page. | ||||
|         """ | ||||
|         self.check_viewset(ContentTypeViewSet, "/api/models/") | ||||
|         self.check_viewset(UserViewSet, "/api/user/") | ||||
| @@ -1,10 +1,12 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from django.conf import settings | ||||
| from django.conf.urls import url, include | ||||
| from django.conf.urls import include | ||||
| from django.urls import re_path | ||||
| from rest_framework import routers | ||||
|  | ||||
| from .views import UserInformationView | ||||
| from .viewsets import ContentTypeViewSet, UserViewSet | ||||
|  | ||||
| # Routers provide an easy way of automatically determining the URL conf. | ||||
| @@ -13,39 +15,52 @@ router = routers.DefaultRouter() | ||||
| router.register('models', ContentTypeViewSet) | ||||
| router.register('user', UserViewSet) | ||||
|  | ||||
| if "member" in settings.INSTALLED_APPS: | ||||
|     from member.api.urls import register_members_urls | ||||
|     register_members_urls(router, 'members') | ||||
|  | ||||
| if "member" in settings.INSTALLED_APPS: | ||||
| if "activity" in settings.INSTALLED_APPS: | ||||
|     from activity.api.urls import register_activity_urls | ||||
|     register_activity_urls(router, 'activity') | ||||
|  | ||||
| if "note" in settings.INSTALLED_APPS: | ||||
|     from note.api.urls import register_note_urls | ||||
|     register_note_urls(router, 'note') | ||||
| if "family" in settings.INSTALLED_APPS: | ||||
|     from family.api.urls import register_family_urls | ||||
|     register_family_urls(router, 'family') | ||||
|  | ||||
| if "treasury" in settings.INSTALLED_APPS: | ||||
|     from treasury.api.urls import register_treasury_urls | ||||
|     register_treasury_urls(router, 'treasury') | ||||
|  | ||||
| if "permission" in settings.INSTALLED_APPS: | ||||
|     from permission.api.urls import register_permission_urls | ||||
|     register_permission_urls(router, 'permission') | ||||
| if "food" in settings.INSTALLED_APPS: | ||||
|     from food.api.urls import register_food_urls | ||||
|     register_food_urls(router, 'food') | ||||
|  | ||||
| if "logs" in settings.INSTALLED_APPS: | ||||
|     from logs.api.urls import register_logs_urls | ||||
|     register_logs_urls(router, 'logs') | ||||
|  | ||||
| if "member" in settings.INSTALLED_APPS: | ||||
|     from member.api.urls import register_members_urls | ||||
|     register_members_urls(router, 'members') | ||||
|  | ||||
| if "note" in settings.INSTALLED_APPS: | ||||
|     from note.api.urls import register_note_urls | ||||
|     register_note_urls(router, 'note') | ||||
|  | ||||
| if "permission" in settings.INSTALLED_APPS: | ||||
|     from permission.api.urls import register_permission_urls | ||||
|     register_permission_urls(router, 'permission') | ||||
|  | ||||
| if "treasury" in settings.INSTALLED_APPS: | ||||
|     from treasury.api.urls import register_treasury_urls | ||||
|     register_treasury_urls(router, 'treasury') | ||||
|  | ||||
| if "wei" in settings.INSTALLED_APPS: | ||||
|     from wei.api.urls import register_wei_urls | ||||
|     register_wei_urls(router, 'wei') | ||||
|  | ||||
| if "wrapped" in settings.INSTALLED_APPS: | ||||
|     from wrapped.api.urls import register_wrapped_urls | ||||
|     register_wrapped_urls(router, 'wrapped') | ||||
|  | ||||
| app_name = 'api' | ||||
|  | ||||
| # Wire up our API using automatic URL routing. | ||||
| # Additionally, we include login URLs for the browsable API. | ||||
| urlpatterns = [ | ||||
|     url('^', include(router.urls)), | ||||
|     url('^api-auth/', include('rest_framework.urls', namespace='rest_framework')), | ||||
|     re_path('^', include(router.urls)), | ||||
|     re_path('^me/', UserInformationView.as_view()), | ||||
|     re_path('^api-auth/', include('rest_framework.urls', namespace='rest_framework')), | ||||
| ] | ||||
|   | ||||
							
								
								
									
										20
									
								
								apps/api/views.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										20
									
								
								apps/api/views.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,20 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from django.contrib.auth.models import User | ||||
| from rest_framework.generics import RetrieveAPIView | ||||
|  | ||||
| from .serializers import OAuthSerializer | ||||
|  | ||||
|  | ||||
| class UserInformationView(RetrieveAPIView): | ||||
|     """ | ||||
|     These fields are give to OAuth authenticators. | ||||
|     """ | ||||
|     serializer_class = OAuthSerializer | ||||
|  | ||||
|     def get_queryset(self): | ||||
|         return User.objects.filter(pk=self.request.user.pk) | ||||
|  | ||||
|     def get_object(self): | ||||
|         return self.request.user | ||||
| @@ -1,6 +1,8 @@ | ||||
| # Copyright (C) 2018-2020 by BDE ENS Paris-Saclay | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| import re | ||||
|  | ||||
| from django.contrib.contenttypes.models import ContentType | ||||
| from django_filters.rest_framework import DjangoFilterBackend | ||||
| from django.db.models import Q | ||||
| @@ -8,12 +10,20 @@ from django.conf import settings | ||||
| from django.contrib.auth.models import User | ||||
| from rest_framework.viewsets import ReadOnlyModelViewSet, ModelViewSet | ||||
| from permission.backends import PermissionBackend | ||||
| from note_kfet.middlewares import get_current_session | ||||
| from note.models import Alias | ||||
|  | ||||
| from .filters import RegexSafeSearchFilter | ||||
| from .serializers import UserSerializer, ContentTypeSerializer | ||||
|  | ||||
|  | ||||
| def is_regex(pattern): | ||||
|     try: | ||||
|         re.compile(pattern) | ||||
|         return True | ||||
|     except (re.error, TypeError): | ||||
|         return False | ||||
|  | ||||
|  | ||||
| class ReadProtectedModelViewSet(ModelViewSet): | ||||
|     """ | ||||
|     Protect a ModelViewSet by filtering the objects that the user cannot see. | ||||
| @@ -24,9 +34,7 @@ class ReadProtectedModelViewSet(ModelViewSet): | ||||
|         self.model = ContentType.objects.get_for_model(self.serializer_class.Meta.model).model_class() | ||||
|  | ||||
|     def get_queryset(self): | ||||
|         user = self.request.user | ||||
|         get_current_session().setdefault("permission_mask", 42) | ||||
|         return self.queryset.filter(PermissionBackend.filter_queryset(user, self.model, "view")).distinct() | ||||
|         return self.queryset.filter(PermissionBackend.filter_queryset(self.request, self.model, "view")).distinct() | ||||
|  | ||||
|  | ||||
| class ReadOnlyProtectedModelViewSet(ReadOnlyModelViewSet): | ||||
| @@ -39,21 +47,20 @@ class ReadOnlyProtectedModelViewSet(ReadOnlyModelViewSet): | ||||
|         self.model = ContentType.objects.get_for_model(self.serializer_class.Meta.model).model_class() | ||||
|  | ||||
|     def get_queryset(self): | ||||
|         user = self.request.user | ||||
|         get_current_session().setdefault("permission_mask", 42) | ||||
|         return self.queryset.filter(PermissionBackend.filter_queryset(user, self.model, "view")).distinct() | ||||
|         return self.queryset.filter(PermissionBackend.filter_queryset(self.request, self.model, "view")).distinct() | ||||
|  | ||||
|  | ||||
| class UserViewSet(ReadProtectedModelViewSet): | ||||
|     """ | ||||
|     REST API View set. | ||||
|     The djangorestframework plugin will get all `User` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/users/ | ||||
|     then render it on /api/user/ | ||||
|     """ | ||||
|     queryset = User.objects.all() | ||||
|     queryset = User.objects | ||||
|     serializer_class = UserSerializer | ||||
|     filter_backends = [DjangoFilterBackend] | ||||
|     filterset_fields = ['id', 'username', 'first_name', 'last_name', 'email', 'is_superuser', 'is_staff', 'is_active', ] | ||||
|     filterset_fields = ['id', 'username', 'first_name', 'last_name', 'email', 'is_superuser', 'is_staff', 'is_active', | ||||
|                         'note__alias__name', 'note__alias__normalized_name', ] | ||||
|  | ||||
|     def get_queryset(self): | ||||
|         queryset = super().get_queryset() | ||||
| @@ -63,34 +70,38 @@ class UserViewSet(ReadProtectedModelViewSet): | ||||
|  | ||||
|         if "search" in self.request.GET: | ||||
|             pattern = self.request.GET["search"] | ||||
|             # Check if this is a valid regex. If not, we won't check regex | ||||
|             valid_regex = is_regex(pattern) | ||||
|             suffix = "__iregex" if valid_regex else "__istartswith" | ||||
|             prefix = "^" if valid_regex else "" | ||||
|  | ||||
|             # Filter with different rules | ||||
|             # We use union-all to keep each filter rule sorted in result | ||||
|             queryset = queryset.filter( | ||||
|                 # Match without normalization | ||||
|                 note__alias__name__iregex="^" + pattern | ||||
|                 Q(**{f"note__alias__name{suffix}": prefix + pattern}) | ||||
|             ).union( | ||||
|                 queryset.filter( | ||||
|                     # Match with normalization | ||||
|                     Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern)) | ||||
|                     & ~Q(note__alias__name__iregex="^" + pattern) | ||||
|                     Q(**{f"note__alias__normalized_name{suffix}": prefix + Alias.normalize(pattern)}) | ||||
|                     & ~Q(**{f"note__alias__name{suffix}": prefix + pattern}) | ||||
|                 ), | ||||
|                 all=True, | ||||
|             ).union( | ||||
|                 queryset.filter( | ||||
|                     # Match on lower pattern | ||||
|                     Q(note__alias__normalized_name__iregex="^" + pattern.lower()) | ||||
|                     & ~Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern)) | ||||
|                     & ~Q(note__alias__name__iregex="^" + pattern) | ||||
|                     Q(**{f"note__alias__normalized_name{suffix}": prefix + pattern.lower()}) | ||||
|                     & ~Q(**{f"note__alias__normalized_name{suffix}": prefix + Alias.normalize(pattern)}) | ||||
|                     & ~Q(**{f"note__alias__name{suffix}": prefix + pattern}) | ||||
|                 ), | ||||
|                 all=True, | ||||
|             ).union( | ||||
|                 queryset.filter( | ||||
|                     # Match on firstname or lastname | ||||
|                     (Q(last_name__iregex="^" + pattern) | Q(first_name__iregex="^" + pattern)) | ||||
|                     & ~Q(note__alias__normalized_name__iregex="^" + pattern.lower()) | ||||
|                     & ~Q(note__alias__normalized_name__iregex="^" + Alias.normalize(pattern)) | ||||
|                     & ~Q(note__alias__name__iregex="^" + pattern) | ||||
|                     (Q(**{f"last_name{suffix}": prefix + pattern}) | Q(**{f"first_name{suffix}": prefix + pattern})) | ||||
|                     & ~Q(**{f"note__alias__normalized_name{suffix}": prefix + pattern.lower()}) | ||||
|                     & ~Q(**{f"note__alias__normalized_name{suffix}": prefix + Alias.normalize(pattern)}) | ||||
|                     & ~Q(**{f"note__alias__name{suffix}": prefix + pattern}) | ||||
|                 ), | ||||
|                 all=True, | ||||
|             ) | ||||
| @@ -106,7 +117,10 @@ class ContentTypeViewSet(ReadOnlyModelViewSet): | ||||
|     """ | ||||
|     REST API View set. | ||||
|     The djangorestframework plugin will get all `User` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/users/ | ||||
|     then render it on /api/models/ | ||||
|     """ | ||||
|     queryset = ContentType.objects.all() | ||||
|     queryset = ContentType.objects.order_by('id') | ||||
|     serializer_class = ContentTypeSerializer | ||||
|     filter_backends = [DjangoFilterBackend, RegexSafeSearchFilter] | ||||
|     filterset_fields = ['id', 'app_label', 'model', ] | ||||
|     search_fields = ['$app_label', '$model', ] | ||||
|   | ||||
							
								
								
									
										0
									
								
								apps/family/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										0
									
								
								apps/family/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
								
								
									
										0
									
								
								apps/family/api/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										0
									
								
								apps/family/api/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
								
								
									
										46
									
								
								apps/family/api/serializers.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										46
									
								
								apps/family/api/serializers.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,46 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from rest_framework import serializers | ||||
|  | ||||
| from ..models import Family, FamilyMembership, Challenge, Achievement | ||||
|  | ||||
|  | ||||
| class FamilySerializer(serializers.ModelSerializer): | ||||
|     """ | ||||
|     REST API Serializer for Family. | ||||
|     The djangorestframework plugin will analyse the model `Family` and parse all fields in the API. | ||||
|     """ | ||||
|     class Meta: | ||||
|         model = Family | ||||
|         fields = '__all__' | ||||
|  | ||||
|  | ||||
| class FamilyMembershipSerializer(serializers.ModelSerializer): | ||||
|     """ | ||||
|     REST API Serializer for FamilyMembership. | ||||
|     The djangorestframework plugin will analyse the model `FamilyMembership` and parse all fields in the API. | ||||
|     """ | ||||
|     class Meta: | ||||
|         model = FamilyMembership | ||||
|         fields = '__all__' | ||||
|  | ||||
|  | ||||
| class ChallengeSerializer(serializers.ModelSerializer): | ||||
|     """ | ||||
|     REST API Serializer for Challenge. | ||||
|     The djangorestframework plugin will analyse the model `Challenge` and parse all fields in the API. | ||||
|     """ | ||||
|     class Meta: | ||||
|         model = Challenge | ||||
|         fields = '__all__' | ||||
|  | ||||
|  | ||||
| class AchievementSerializer(serializers.ModelSerializer): | ||||
|     """ | ||||
|     REST API Serializer for Achievement. | ||||
|     The djangorestframework plugin will analyse the model `Achievement` and parse all fields in the API. | ||||
|     """ | ||||
|     class Meta: | ||||
|         model = Achievement | ||||
|         fields = '__all__' | ||||
							
								
								
									
										20
									
								
								apps/family/api/urls.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										20
									
								
								apps/family/api/urls.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,20 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
| from django.urls import path | ||||
|  | ||||
| from .views import FamilyViewSet, FamilyMembershipViewSet, ChallengeViewSet, AchievementViewSet, BatchAchievementsAPIView | ||||
|  | ||||
|  | ||||
| def register_family_urls(router, path): | ||||
|     """ | ||||
|     Configure router for Family REST API | ||||
|     """ | ||||
|     router.register(path + '/family', FamilyViewSet) | ||||
|     router.register(path + '/familymembership', FamilyMembershipViewSet) | ||||
|     router.register(path + '/challenge', ChallengeViewSet) | ||||
|     router.register(path + '/achievement', AchievementViewSet) | ||||
|  | ||||
|  | ||||
| urlpatterns = [ | ||||
|     path('achievements/batch/', BatchAchievementsAPIView.as_view(), name='batch_achievements') | ||||
| ] | ||||
							
								
								
									
										98
									
								
								apps/family/api/views.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										98
									
								
								apps/family/api/views.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,98 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from api.viewsets import ReadProtectedModelViewSet | ||||
| from django_filters.rest_framework import DjangoFilterBackend | ||||
| from api.filters import RegexSafeSearchFilter | ||||
| from rest_framework.views import APIView | ||||
| from rest_framework.permissions import IsAuthenticated | ||||
| from rest_framework.response import Response | ||||
| from rest_framework import status | ||||
|  | ||||
| from .serializers import FamilySerializer, FamilyMembershipSerializer, ChallengeSerializer, AchievementSerializer | ||||
| from ..models import Family, FamilyMembership, Challenge, Achievement | ||||
|  | ||||
|  | ||||
| class FamilyViewSet(ReadProtectedModelViewSet): | ||||
|     """ | ||||
|     REST API View set. | ||||
|     The djangorestframework plugin will get all `Family` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/family/family/ | ||||
|     """ | ||||
|     queryset = Family.objects.order_by('id') | ||||
|     serializer_class = FamilySerializer | ||||
|     filter_backends = [DjangoFilterBackend, RegexSafeSearchFilter] | ||||
|     filterset_fields = ['name', 'description', 'score', 'rank', ] | ||||
|     search_fields = ['$name', '$description', ] | ||||
|  | ||||
|  | ||||
| class FamilyMembershipViewSet(ReadProtectedModelViewSet): | ||||
|     """ | ||||
|     REST API View set. | ||||
|     The djangorestframework plugin will get all `FamilyMembership` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/family/familymembership/ | ||||
|     """ | ||||
|     queryset = FamilyMembership.objects.order_by('id') | ||||
|     serializer_class = FamilyMembershipSerializer | ||||
|     filter_backends = [DjangoFilterBackend, RegexSafeSearchFilter] | ||||
|     filterset_fields = ['user__username', 'user__first_name', 'user__last_name', 'user__email', 'user__note__alias__name', | ||||
|                         'user__note__alias__normalized_name', 'family__name', 'family__description', 'year', ] | ||||
|     search_fields = ['$user__username', '$user__first_name', '$user__last_name', '$user__email', '$user__note__alias__name', | ||||
|                      '$user__note__alias__normalized_name', '$family__name', '$family__description', '$year', ] | ||||
|  | ||||
|  | ||||
| class ChallengeViewSet(ReadProtectedModelViewSet): | ||||
|     """ | ||||
|     REST API View set. | ||||
|     The djangorestframework plugin will get all `Challenge` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/family/challenge/ | ||||
|     """ | ||||
|     queryset = Challenge.objects.order_by('id') | ||||
|     serializer_class = ChallengeSerializer | ||||
|     filter_backends = [DjangoFilterBackend, RegexSafeSearchFilter] | ||||
|     filterset_fields = ['name', 'description', 'points', ] | ||||
|     search_fields = ['$name', '$description', '$points', ] | ||||
|  | ||||
|  | ||||
| class AchievementViewSet(ReadProtectedModelViewSet): | ||||
|     """ | ||||
|     REST API View set. | ||||
|     The djangorestframework plugin will get all `Achievement` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/family/achievement/ | ||||
|     """ | ||||
|     queryset = Achievement.objects.order_by('id') | ||||
|     serializer_class = AchievementSerializer | ||||
|     filter_backends = [DjangoFilterBackend, RegexSafeSearchFilter] | ||||
|     filterset_fields = ['family__name', 'family__description', 'challenge__name', 'challenge__description', 'obtained_at', 'valid', ] | ||||
|     search_fields = ['$family__name', '$family__description', '$challenge__name', '$challenge__description', ] | ||||
|  | ||||
|  | ||||
| class BatchAchievementsAPIView(APIView): | ||||
|     permission_classes = [IsAuthenticated] | ||||
|  | ||||
|     def post(self, request, format=None): | ||||
|         family_ids = request.data.get('families') | ||||
|         challenge_ids = request.data.get('challenges') | ||||
|         families = Family.objects.filter(id__in=family_ids) | ||||
|         challenges = Challenge.objects.filter(id__in=challenge_ids) | ||||
|         results = [] | ||||
|         for family in families: | ||||
|             for challenge in challenges: | ||||
|                 a, created = Achievement.objects.get_or_create(family=family, challenge=challenge) | ||||
|                 if created: | ||||
|                     results.append({ | ||||
|                         'family': family.name, | ||||
|                         'challenge': challenge.name, | ||||
|                         'status': 'created' | ||||
|                     }) | ||||
|                 else: | ||||
|                     results.append({ | ||||
|                         'family': family.name, | ||||
|                         'challenge': challenge.name, | ||||
|                         'status': 'existed', | ||||
|                     }) | ||||
|         for family in families: | ||||
|             family.update_score() | ||||
|         Family.update_ranking() | ||||
|  | ||||
|         return Response({'results': results}, status=status.HTTP_201_CREATED) | ||||
							
								
								
									
										11
									
								
								apps/family/apps.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										11
									
								
								apps/family/apps.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,11 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
|  | ||||
| from django.utils.translation import gettext_lazy as _ | ||||
| from django.apps import AppConfig | ||||
|  | ||||
|  | ||||
| class FamilyConfig(AppConfig): | ||||
|     name = 'family' | ||||
|     verbose_name = _('family') | ||||
							
								
								
									
										44
									
								
								apps/family/forms.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										44
									
								
								apps/family/forms.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,44 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from django import forms | ||||
| from django.forms.widgets import NumberInput | ||||
| from note_kfet.inputs import Autocomplete | ||||
|  | ||||
| from .models import Challenge, FamilyMembership, User, Family | ||||
|  | ||||
|  | ||||
| class ChallengeForm(forms.ModelForm): | ||||
|     """ | ||||
|     To update a challenge | ||||
|     """ | ||||
|     class Meta: | ||||
|         model = Challenge | ||||
|         fields = ('name', 'description', 'points',) | ||||
|         widgets = { | ||||
|             "points": NumberInput() | ||||
|         } | ||||
|  | ||||
|  | ||||
| class FamilyForm(forms.ModelForm): | ||||
|     class Meta: | ||||
|         model = Family | ||||
|         fields = ('name', 'description', ) | ||||
|  | ||||
|  | ||||
| class FamilyMembershipForm(forms.ModelForm): | ||||
|     class Meta: | ||||
|         model = FamilyMembership | ||||
|         fields = ('user', ) | ||||
|  | ||||
|         widgets = { | ||||
|             "user": | ||||
|                 Autocomplete( | ||||
|                     User, | ||||
|                     attrs={ | ||||
|                         'api_url': '/api/user/', | ||||
|                         'name_field': 'username', | ||||
|                         'placeholder': 'Nom ...', | ||||
|                     }, | ||||
|                 ) | ||||
|         } | ||||
							
								
								
									
										73
									
								
								apps/family/migrations/0001_initial.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										73
									
								
								apps/family/migrations/0001_initial.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,73 @@ | ||||
| # Generated by Django 4.2.21 on 2025-07-06 16:07 | ||||
|  | ||||
| from django.conf import settings | ||||
| from django.db import migrations, models | ||||
| import django.db.models.deletion | ||||
| import django.utils.timezone | ||||
|  | ||||
|  | ||||
| class Migration(migrations.Migration): | ||||
|  | ||||
|     initial = True | ||||
|  | ||||
|     dependencies = [ | ||||
|         migrations.swappable_dependency(settings.AUTH_USER_MODEL), | ||||
|     ] | ||||
|  | ||||
|     operations = [ | ||||
|         migrations.CreateModel( | ||||
|             name='Challenge', | ||||
|             fields=[ | ||||
|                 ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), | ||||
|                 ('name', models.CharField(max_length=255, verbose_name='name')), | ||||
|                 ('description', models.CharField(max_length=255, verbose_name='description')), | ||||
|                 ('points', models.PositiveIntegerField(verbose_name='points')), | ||||
|                 ('obtained', models.PositiveIntegerField(default=0, verbose_name='obtained')), | ||||
|             ], | ||||
|             options={ | ||||
|                 'verbose_name': 'challenge', | ||||
|                 'verbose_name_plural': 'challenges', | ||||
|             }, | ||||
|         ), | ||||
|         migrations.CreateModel( | ||||
|             name='Family', | ||||
|             fields=[ | ||||
|                 ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), | ||||
|                 ('name', models.CharField(max_length=255, unique=True, verbose_name='name')), | ||||
|                 ('description', models.CharField(max_length=255, verbose_name='description')), | ||||
|                 ('score', models.PositiveIntegerField(default=0, verbose_name='score')), | ||||
|                 ('rank', models.PositiveIntegerField(verbose_name='rank')), | ||||
|             ], | ||||
|             options={ | ||||
|                 'verbose_name': 'Family', | ||||
|                 'verbose_name_plural': 'Families', | ||||
|             }, | ||||
|         ), | ||||
|         migrations.CreateModel( | ||||
|             name='Achievement', | ||||
|             fields=[ | ||||
|                 ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), | ||||
|                 ('obtained_at', models.DateTimeField(default=django.utils.timezone.now, verbose_name='obtained at')), | ||||
|                 ('challenge', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='family.challenge')), | ||||
|                 ('family', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='family.family', verbose_name='family')), | ||||
|             ], | ||||
|             options={ | ||||
|                 'verbose_name': 'achievement', | ||||
|                 'verbose_name_plural': 'achievements', | ||||
|             }, | ||||
|         ), | ||||
|         migrations.CreateModel( | ||||
|             name='FamilyMembership', | ||||
|             fields=[ | ||||
|                 ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), | ||||
|                 ('year', models.PositiveIntegerField(default=2025, verbose_name='year')), | ||||
|                 ('family', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='members', to='family.family', verbose_name='family')), | ||||
|                 ('user', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='family_memberships', to=settings.AUTH_USER_MODEL, verbose_name='user')), | ||||
|             ], | ||||
|             options={ | ||||
|                 'verbose_name': 'family membership', | ||||
|                 'verbose_name_plural': 'family memberships', | ||||
|                 'unique_together': {('user', 'year')}, | ||||
|             }, | ||||
|         ), | ||||
|     ] | ||||
							
								
								
									
										18
									
								
								apps/family/migrations/0002_family_display_image.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										18
									
								
								apps/family/migrations/0002_family_display_image.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,18 @@ | ||||
| # Generated by Django 4.2.23 on 2025-07-17 15:28 | ||||
|  | ||||
| from django.db import migrations, models | ||||
|  | ||||
|  | ||||
| class Migration(migrations.Migration): | ||||
|  | ||||
|     dependencies = [ | ||||
|         ('family', '0001_initial'), | ||||
|     ] | ||||
|  | ||||
|     operations = [ | ||||
|         migrations.AddField( | ||||
|             model_name='family', | ||||
|             name='display_image', | ||||
|             field=models.ImageField(default='pic/default.png', max_length=255, upload_to='pic/', verbose_name='display image'), | ||||
|         ), | ||||
|     ] | ||||
| @@ -0,0 +1,24 @@ | ||||
| # Generated by Django 5.2.4 on 2025-07-21 21:02 | ||||
|  | ||||
| import django.db.models.deletion | ||||
| from django.db import migrations, models | ||||
|  | ||||
|  | ||||
| class Migration(migrations.Migration): | ||||
|  | ||||
|     dependencies = [ | ||||
|         ('family', '0002_family_display_image'), | ||||
|     ] | ||||
|  | ||||
|     operations = [ | ||||
|         migrations.AddField( | ||||
|             model_name='achievement', | ||||
|             name='valid', | ||||
|             field=models.BooleanField(default=False, verbose_name='valid'), | ||||
|         ), | ||||
|         migrations.AlterField( | ||||
|             model_name='familymembership', | ||||
|             name='family', | ||||
|             field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='memberships', to='family.family', verbose_name='family'), | ||||
|         ), | ||||
|     ] | ||||
							
								
								
									
										17
									
								
								apps/family/migrations/0004_remove_challenge_obtained.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										17
									
								
								apps/family/migrations/0004_remove_challenge_obtained.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,17 @@ | ||||
| # Generated by Django 5.2.4 on 2025-07-22 14:33 | ||||
|  | ||||
| from django.db import migrations | ||||
|  | ||||
|  | ||||
| class Migration(migrations.Migration): | ||||
|  | ||||
|     dependencies = [ | ||||
|         ('family', '0003_achievement_valid_alter_familymembership_family'), | ||||
|     ] | ||||
|  | ||||
|     operations = [ | ||||
|         migrations.RemoveField( | ||||
|             model_name='challenge', | ||||
|             name='obtained', | ||||
|         ), | ||||
|     ] | ||||
| @@ -0,0 +1,17 @@ | ||||
| # Generated by Django 5.2.4 on 2025-08-13 20:26 | ||||
|  | ||||
| from django.db import migrations | ||||
|  | ||||
|  | ||||
| class Migration(migrations.Migration): | ||||
|  | ||||
|     dependencies = [ | ||||
|         ('family', '0004_remove_challenge_obtained'), | ||||
|     ] | ||||
|  | ||||
|     operations = [ | ||||
|         migrations.AlterUniqueTogether( | ||||
|             name='achievement', | ||||
|             unique_together={('challenge', 'family')}, | ||||
|         ), | ||||
|     ] | ||||
							
								
								
									
										0
									
								
								apps/family/migrations/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										0
									
								
								apps/family/migrations/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
								
								
									
										207
									
								
								apps/family/models.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										207
									
								
								apps/family/models.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,207 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from django.db import models, transaction | ||||
| from django.utils import timezone | ||||
| from django.contrib.auth.models import User | ||||
| from django.urls import reverse_lazy | ||||
| from django.utils.translation import gettext_lazy as _ | ||||
|  | ||||
|  | ||||
| class Family(models.Model): | ||||
|     name = models.CharField( | ||||
|         max_length=255, | ||||
|         verbose_name=_('name'), | ||||
|         unique=True, | ||||
|     ) | ||||
|  | ||||
|     description = models.CharField( | ||||
|         max_length=255, | ||||
|         verbose_name=_('description'), | ||||
|     ) | ||||
|  | ||||
|     score = models.PositiveIntegerField( | ||||
|         verbose_name=_('score'), | ||||
|         default=0, | ||||
|     ) | ||||
|  | ||||
|     rank = models.PositiveIntegerField( | ||||
|         verbose_name=_('rank'), | ||||
|     ) | ||||
|  | ||||
|     display_image = models.ImageField( | ||||
|         verbose_name=_('display image'), | ||||
|         max_length=255, | ||||
|         blank=False, | ||||
|         null=False, | ||||
|         upload_to='pic/', | ||||
|         default='pic/default.png' | ||||
|     ) | ||||
|  | ||||
|     class Meta: | ||||
|         verbose_name = _('Family') | ||||
|         verbose_name_plural = _('Families') | ||||
|  | ||||
|     def __str__(self): | ||||
|         return self.name | ||||
|  | ||||
|     def get_absolute_url(self): | ||||
|         return reverse_lazy('family:family_detail', args=(self.pk,)) | ||||
|  | ||||
|     def update_score(self, *args, **kwargs): | ||||
|         challenge_set = Challenge.objects.select_for_update().filter(achievement__family=self, achievement__valid=True) | ||||
|         points_sum = challenge_set.aggregate(models.Sum("points")) | ||||
|         self.score = points_sum["points__sum"] if points_sum["points__sum"] else 0 | ||||
|         self.save() | ||||
|         self.update_ranking() | ||||
|  | ||||
|     @staticmethod | ||||
|     def update_ranking(*args, **kwargs): | ||||
|         """ | ||||
|         Update ranking when adding or removing points | ||||
|         """ | ||||
|         family_set = Family.objects.select_for_update().all().order_by("-score") | ||||
|         for i in range(family_set.count()): | ||||
|             if i == 0 or family_set[i].score != family_set[i - 1].score: | ||||
|                 new_rank = i + 1 | ||||
|             family = family_set[i] | ||||
|             family.rank = new_rank | ||||
|             family._force_save = True | ||||
|             family.save() | ||||
|  | ||||
|     def save(self, *args, **kwargs): | ||||
|         if self.rank is None: | ||||
|             last_family = Family.objects.order_by("rank").last() | ||||
|             if last_family is None or last_family.score > self.score: | ||||
|                 self.rank = Family.objects.count() + 1 | ||||
|             else: | ||||
|                 self.rank = last_family.rank | ||||
|         super().save(*args, **kwargs) | ||||
|  | ||||
|  | ||||
| class FamilyMembership(models.Model): | ||||
|     user = models.OneToOneField( | ||||
|         User, | ||||
|         on_delete=models.PROTECT, | ||||
|         related_name=_('family_memberships'), | ||||
|         verbose_name=_('user'), | ||||
|     ) | ||||
|  | ||||
|     family = models.ForeignKey( | ||||
|         Family, | ||||
|         on_delete=models.PROTECT, | ||||
|         related_name=_('memberships'), | ||||
|         verbose_name=_('family'), | ||||
|     ) | ||||
|  | ||||
|     year = models.PositiveIntegerField( | ||||
|         verbose_name=_('year'), | ||||
|         default=timezone.now().year, | ||||
|     ) | ||||
|  | ||||
|     class Meta: | ||||
|         unique_together = ('user', 'year',) | ||||
|         verbose_name = _('family membership') | ||||
|         verbose_name_plural = _('family memberships') | ||||
|  | ||||
|     def __str__(self): | ||||
|         return _('Family membership of {user} to {family}').format(user=self.user.username, family=self.family.name, ) | ||||
|  | ||||
|  | ||||
| class Challenge(models.Model): | ||||
|     name = models.CharField( | ||||
|         max_length=255, | ||||
|         verbose_name=_('name'), | ||||
|     ) | ||||
|  | ||||
|     description = models.CharField( | ||||
|         max_length=255, | ||||
|         verbose_name=_('description'), | ||||
|     ) | ||||
|  | ||||
|     points = models.PositiveIntegerField( | ||||
|         verbose_name=_('points'), | ||||
|     ) | ||||
|  | ||||
|     @property | ||||
|     def obtained(self): | ||||
|         achievements = Achievement.objects.filter(challenge=self, valid=True) | ||||
|         return achievements.count() | ||||
|  | ||||
|     def __str__(self): | ||||
|         return self.name | ||||
|  | ||||
|     def get_absolute_url(self): | ||||
|         return reverse_lazy('family:challenge_detail', args=(self.pk,)) | ||||
|  | ||||
|     @transaction.atomic | ||||
|     def save(self, *args, **kwargs): | ||||
|         super().save(*args, **kwargs) | ||||
|         # Update families who already obtained this challenge | ||||
|         achievements = Achievement.objects.filter(challenge=self) | ||||
|         for achievement in achievements: | ||||
|             achievement.save() | ||||
|  | ||||
|     class Meta: | ||||
|         verbose_name = _('challenge') | ||||
|         verbose_name_plural = _('challenges') | ||||
|  | ||||
|  | ||||
| class Achievement(models.Model): | ||||
|     challenge = models.ForeignKey( | ||||
|         Challenge, | ||||
|         on_delete=models.PROTECT, | ||||
|  | ||||
|     ) | ||||
|     family = models.ForeignKey( | ||||
|         Family, | ||||
|         on_delete=models.PROTECT, | ||||
|         verbose_name=_('family'), | ||||
|     ) | ||||
|  | ||||
|     obtained_at = models.DateTimeField( | ||||
|         verbose_name=_('obtained at'), | ||||
|         default=timezone.now, | ||||
|     ) | ||||
|  | ||||
|     valid = models.BooleanField( | ||||
|         verbose_name=_('valid'), | ||||
|         default=False, | ||||
|     ) | ||||
|  | ||||
|     class Meta: | ||||
|         unique_together = ('challenge', 'family',) | ||||
|         verbose_name = _('achievement') | ||||
|         verbose_name_plural = _('achievements') | ||||
|  | ||||
|     def __str__(self): | ||||
|         return _('Challenge {challenge} carried out by Family {family}').format(challenge=self.challenge.name, family=self.family.name, ) | ||||
|  | ||||
|     @transaction.atomic | ||||
|     def save(self, *args, update_score=True, **kwargs): | ||||
|         """ | ||||
|         When saving, also grants points to the family | ||||
|         """ | ||||
|         self.family = Family.objects.select_for_update().get(pk=self.family_id) | ||||
|         self.challenge = Challenge.objects.select_for_update().get(pk=self.challenge_id) | ||||
|  | ||||
|         super().save(*args, **kwargs) | ||||
|  | ||||
|         if update_score: | ||||
|             self.family.refresh_from_db() | ||||
|             self.family.update_score() | ||||
|  | ||||
|     @transaction.atomic | ||||
|     def delete(self, *args, **kwargs): | ||||
|         """ | ||||
|         When deleting, also removes points from the family | ||||
|         """ | ||||
|         # Get the family and challenge before deletion | ||||
|         self.family = Family.objects.select_for_update().get(pk=self.family_id) | ||||
|  | ||||
|         # Delete the achievement | ||||
|         super().delete(*args, **kwargs) | ||||
|  | ||||
|         # Remove points from the family | ||||
|         self.family.refresh_from_db() | ||||
|         self.family.update_score() | ||||
							
								
								
									
										
											BIN
										
									
								
								apps/family/static/family/img/default_picture.png
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										
											BIN
										
									
								
								apps/family/static/family/img/default_picture.png
									
									
									
									
									
										Normal file
									
								
							
										
											Binary file not shown.
										
									
								
							| After Width: | Height: | Size: 4.0 KiB | 
							
								
								
									
										411
									
								
								apps/family/static/family/js/achievements.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										411
									
								
								apps/family/static/family/js/achievements.js
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,411 @@ | ||||
| // Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| // SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| // When a transaction is performed, lock the interface to prevent spam clicks. | ||||
| var LOCK = false | ||||
|  | ||||
| /** | ||||
|  * Refresh the history table on the consumptions page. | ||||
|  */ | ||||
| function refreshHistory () { | ||||
|   $('#history').load('/family/manage/ #history') | ||||
| } | ||||
|  | ||||
| $(document).ready(function () { | ||||
|   // If hash of a category in the URL, then select this category | ||||
|   // else select the first one | ||||
|   if (location.hash) { | ||||
|     $("a[href='" + location.hash + "']").tab('show') | ||||
|   } else { | ||||
|     $("a[data-toggle='tab']").first().tab('show') | ||||
|   } | ||||
|  | ||||
|   // When selecting a category, change URL | ||||
|   $(document.body).on('click', "a[data-toggle='tab']", function () { | ||||
|     location.hash = this.getAttribute('href') | ||||
|   }) | ||||
|  | ||||
| }) | ||||
|  | ||||
| notes = [] | ||||
| notes_display = [] | ||||
| buttons = [] | ||||
|  | ||||
| // When the user searches an alias, we update the auto-completion | ||||
| autoCompleteFamily('note', 'note_list', notes, notes_display, | ||||
|   'note', 'user_note', 'profile_pic', function () { | ||||
|     return true | ||||
|   }) | ||||
|  | ||||
| /** | ||||
|  * Add a transaction from a button. | ||||
|  * @param fam Where the money goes | ||||
|  * @param amount The price of the item | ||||
|  * @param type The type of the transaction (content type id for RecurrentTransaction) | ||||
|  * @param category_id The category identifier | ||||
|  * @param category_name The category name | ||||
|  * @param template_id The identifier of the button | ||||
|  * @param template_name The name of  the button | ||||
|  */ | ||||
| function addChallenge (id, name, amount) { | ||||
|   var challenge = null | ||||
|   /** Ajout de 1 à chaque clic d'un bouton déjà choisi  */ | ||||
|   buttons.forEach(function (b) { | ||||
|     if (b.id === id) { | ||||
|       challenge = b | ||||
|     } | ||||
|   }) | ||||
|   if (challenge == null) { | ||||
|     challenge = { | ||||
|       id: id, | ||||
|       name: name, | ||||
|     } | ||||
|     buttons.push(challenge) | ||||
|   } | ||||
|  | ||||
|   const dc_obj = true | ||||
|    | ||||
|     const list = 'consos_list' | ||||
|     let html = '' | ||||
|     buttons.forEach(function (challenge) { | ||||
|       html += li('conso_button_' + challenge.id, challenge.name) | ||||
|     }) | ||||
|     document.getElementById(list).innerHTML = html | ||||
|  | ||||
|     buttons.forEach((button) => { | ||||
|       document.getElementById(`conso_button_${button.id}`).addEventListener('click', () => { | ||||
|         if (LOCK) { return } | ||||
|         removeNote(button, 'conso_button', buttons, list)() | ||||
|       }) | ||||
|     }) | ||||
|  | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Reset the page as its initial state. | ||||
|  */ | ||||
| function reset () { | ||||
|   notes_display.length = 0 | ||||
|   notes.length = 0 | ||||
|   buttons.length = 0 | ||||
|   document.getElementById('note_list').innerHTML = '' | ||||
|   document.getElementById('consos_list').innerHTML = '' | ||||
|   document.getElementById('note').value = '' | ||||
|   document.getElementById('note').dataset.originTitle = '' | ||||
|   $('#note').tooltip('hide') | ||||
|   document.getElementById('profile_pic').src = '/static/member/img/default_picture.png' | ||||
|   document.getElementById('profile_pic_link').href = '#' | ||||
|   refreshHistory() | ||||
|   LOCK = false | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Apply all transactions: all notes in `notes` buy each item in `buttons` | ||||
|  */ | ||||
| function consumeAll () { | ||||
|   if (LOCK) { return } | ||||
|   LOCK = true | ||||
|  | ||||
|   let error = false | ||||
|  | ||||
|   if (notes_display.length === 0) { | ||||
|     // ... gestion erreur ... | ||||
|     error = true | ||||
|   } | ||||
|   if (buttons.length === 0) { | ||||
|     // ... gestion erreur ... | ||||
|     error = true | ||||
|   } | ||||
|   if (error) { | ||||
|     LOCK = false | ||||
|     return | ||||
|   } | ||||
|   // Récupérer les IDs des familles et des challenges | ||||
|   const family_ids = notes_display.map(fam => fam.id) | ||||
|   const challenge_ids = buttons.map(chal => chal.id) | ||||
|  | ||||
|   $.ajax({ | ||||
|     url: '/family/api/family/achievements/batch/', | ||||
|     type: 'POST', | ||||
|     data: JSON.stringify({ | ||||
|       families: family_ids, | ||||
|       challenges: challenge_ids | ||||
|     }), | ||||
|     contentType: 'application/json', | ||||
|     headers: { | ||||
|       'X-CSRFToken': CSRF_TOKEN | ||||
|     }, | ||||
|     success: function (data) { | ||||
|       reset() | ||||
|       data.results.forEach(function (result) { | ||||
|         if (result.status === 'created') { | ||||
|           addMsg( | ||||
|             interpolate(gettext('Invalid achievement for challenge %s ' + | ||||
|             'and family %s created.'), [result.challenge, result.family]), | ||||
|             'success', | ||||
|             5000 | ||||
|           ) | ||||
|         } else { | ||||
|           addMsg( | ||||
|             interpolate(gettext('An achievement for challenge %s ' + | ||||
|             'and family %s already exists.'), [result.challenge, result.family]), | ||||
|             'danger', | ||||
|             8000 | ||||
|           ) | ||||
|         } | ||||
|       }) | ||||
|     } | ||||
|   }) | ||||
| } | ||||
|  | ||||
|  | ||||
| var searchbar = document.getElementById("search-input") | ||||
| var search_results = document.getElementById("search-results") | ||||
|  | ||||
| var old_pattern = null; | ||||
| var firstMatch = null; | ||||
| /** | ||||
|  * Updates the button search tab | ||||
|  * @param force Forces the update even if the pattern didn't change | ||||
|  */ | ||||
| function updateSearch(force = false) { | ||||
|   let pattern = searchbar.value | ||||
|   if (pattern === "") | ||||
|     firstMatch = null; | ||||
|   if ((pattern === old_pattern || pattern === "") && !force) | ||||
|     return; | ||||
|   firstMatch = null; | ||||
|   const re = new RegExp(pattern, "i"); | ||||
|   Array.from(search_results.children).forEach(function(b) { | ||||
|     if (re.test(b.innerText)) { | ||||
|       b.hidden = false; | ||||
|       if (firstMatch === null) { | ||||
|         firstMatch = b; | ||||
|       } | ||||
|     } else | ||||
|       b.hidden = true; | ||||
|   }); | ||||
| } | ||||
|  | ||||
| searchbar.addEventListener("input", function (e) { | ||||
|   debounce(updateSearch)() | ||||
| }); | ||||
| searchbar.addEventListener("keyup", function (e) { | ||||
|   if (firstMatch && e.key === "Enter") | ||||
|     firstMatch.click() | ||||
| }); | ||||
|  | ||||
| function createshiny() { | ||||
|   const list_btn = document.querySelectorAll('.btn-outline-dark') | ||||
|   const shiny_class = list_btn[Math.floor(Math.random() * list_btn.length)].classList | ||||
|   shiny_class.replace('btn-outline-dark', 'btn-outline-dark-shiny') | ||||
| } | ||||
| createshiny() | ||||
|  | ||||
|  | ||||
|  | ||||
|  | ||||
|  | ||||
| /** | ||||
|  * Query the 20 first matched notes with a given pattern | ||||
|  * @param pattern The pattern that is queried | ||||
|  * @param fun For each found note with the matched alias `alias`, fun(note, alias) is called. | ||||
|  */ | ||||
| function getMatchedFamilies (pattern, fun) { | ||||
|   $.getJSON('/api/family/family/?format=json&alias=' + pattern + '&search=family', fun) | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Generate a <li> entry with a given id and text | ||||
|  */ | ||||
| function li (id, text, extra_css) { | ||||
|   return '<li class="list-group-item py-1 px-2 d-flex justify-content-between align-items-center text-truncate ' + | ||||
|         (extra_css || '') + '"' + ' id="' + id + '">' + text + '</li>\n' | ||||
| } | ||||
|  | ||||
|  | ||||
| /** | ||||
|  * Génère un champ d'auto-complétion pour rechercher une famille par son nom (version simplifiée sans alias) | ||||
|  * @param field_id L'identifiant du champ texte où le nom est saisi | ||||
|  * @param family_list_id L'identifiant du bloc div où les familles sélectionnées sont affichées | ||||
|  * @param families Un tableau contenant les objets famille sélectionnés | ||||
|  * @param families_display Un tableau contenant les infos des familles sélectionnées : [nom, id, objet famille, quantité] | ||||
|  * @param family_prefix Le préfixe des <li> pour les familles sélectionnées | ||||
|  * @param user_family_field L'identifiant du champ qui affiche la famille survolée (optionnel) | ||||
|  * @param profile_pic_field L'identifiant du champ qui affiche la photo de la famille survolée (optionnel) | ||||
|  * @param family_click Fonction appelée lors du clic sur un nom. Si elle existe et ne retourne pas true, la famille n'est pas affichée. | ||||
|  */ | ||||
| function autoCompleteFamily(field_id, family_list_id, families, families_display, family_prefix = 'family', user_family_field = null, profile_pic_field = null, family_click = null) { | ||||
|   const field = $('#' + field_id) | ||||
|   // Configuration du tooltip | ||||
|   field.tooltip({ | ||||
|     html: true, | ||||
|     placement: 'bottom', | ||||
|     title: 'Chargement...', | ||||
|     trigger: 'manual', | ||||
|     container: field.parent(), | ||||
|     fallbackPlacement: 'clockwise' | ||||
|   }) | ||||
|  | ||||
|   // Masquer le tooltip lors d'un clic ailleurs | ||||
|   $(document).click(function (e) { | ||||
|     if (!e.target.id.startsWith(family_prefix)) { | ||||
|       field.tooltip('hide') | ||||
|     } | ||||
|   }) | ||||
|  | ||||
|   let old_pattern = null | ||||
|  | ||||
|   // Réinitialiser la recherche au clic | ||||
|   field.click(function () { | ||||
|     field.tooltip('hide') | ||||
|     field.removeClass('is-invalid') | ||||
|     field.val('') | ||||
|     old_pattern = '' | ||||
|   }) | ||||
|  | ||||
|   // Sur "Entrée", sélectionner la première famille | ||||
|   field.keypress(function (event) { | ||||
|     if (event.originalEvent.charCode === 13 && families.length > 0) { | ||||
|       const li_obj = field.parent().find('ul li').first() | ||||
|       displayFamily(families[0], families[0].name, user_family_field, profile_pic_field) | ||||
|       li_obj.trigger('click') | ||||
|     } | ||||
|   }) | ||||
|  | ||||
|   // Mise à jour des suggestions lors de la saisie | ||||
|   field.keyup(function (e) { | ||||
|     field.removeClass('is-invalid') | ||||
|  | ||||
|     if (e.originalEvent.charCode === 13) { return } | ||||
|  | ||||
|     const pattern = field.val() | ||||
|  | ||||
|     if (pattern === old_pattern) { return } | ||||
|     old_pattern = pattern | ||||
|     families.length = 0 | ||||
|  | ||||
|     if (pattern === '') { | ||||
|       field.tooltip('hide') | ||||
|       families.length = 0 | ||||
|       return | ||||
|     } | ||||
|  | ||||
|     // Appel à l'API pour récupérer les familles correspondantes | ||||
|     $.getJSON('/api/family/family/?format=json&search=' + pattern, | ||||
|       function (results) { | ||||
|         if (pattern !== $('#' + field_id).val()) { return } | ||||
|  | ||||
|         let matched_html = '<ul class="list-group list-group-flush">' | ||||
|         results.results.forEach(function (family) { | ||||
|           matched_html += li(family_prefix + '_' + family.id, | ||||
|             family.name, | ||||
|             '') | ||||
|           families.push(family) | ||||
|         }) | ||||
|         matched_html += '</ul>' | ||||
|  | ||||
|         field.attr('data-original-title', matched_html).tooltip('show') | ||||
|  | ||||
|         results.results.forEach(function (family) { | ||||
|           const family_obj = $('#' + family_prefix + '_' + family.id) | ||||
|           family_obj.hover(function () { | ||||
|             displayFamily(family, family.name, user_family_field, profile_pic_field) | ||||
|           }) | ||||
|           family_obj.click(function () { | ||||
|             var disp = null | ||||
|             families_display.forEach(function (d) { | ||||
|               if (d.id === family.id) { | ||||
|                 disp = d | ||||
|               } | ||||
|             }) | ||||
|             if (disp == null) { | ||||
|               disp = { | ||||
|                 name: family.name, | ||||
|                 id: family.id, | ||||
|                 family: family, | ||||
|               } | ||||
|               families_display.push(disp) | ||||
|             } | ||||
|  | ||||
|             if (family_click && !family_click()) { return } | ||||
|  | ||||
|             const family_list = $('#' + family_list_id) | ||||
|             let html = '' | ||||
|             families_display.forEach(function (disp) { | ||||
|               html += li(family_prefix + '_' + disp.id, | ||||
|                 disp.name, | ||||
|                 '') | ||||
|             }) | ||||
|  | ||||
|             family_list.html(html) | ||||
|             field.tooltip('update') | ||||
|  | ||||
|             families_display.forEach(function (disp) { | ||||
|               const line_obj = $('#' + family_prefix + '_' + disp.id) | ||||
|               line_obj.hover(function () { | ||||
|                 displayFamily(disp.family, disp.name, user_family_field, profile_pic_field) | ||||
|               }) | ||||
|               line_obj.click(removeFamily(disp, family_prefix, families_display, family_list_id, user_family_field, | ||||
|                 profile_pic_field)) | ||||
|             }) | ||||
|           }) | ||||
|         }) | ||||
|       }) | ||||
|   }) | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Affiche le nom et la photo d'une famille | ||||
|  * @param family L'objet famille à afficher | ||||
|  * @param user_family_field L'identifiant du champ où afficher le nom (optionnel) | ||||
|  * @param profile_pic_field L'identifiant du champ où afficher la photo (optionnel) | ||||
|  */ | ||||
| function displayFamily(family, user_family_field = null, profile_pic_field = null) { | ||||
|   if (!family.display_image) { | ||||
|     family.display_image = '/static/member/img/default_picture.png' | ||||
|   } | ||||
|   if (user_family_field !== null) { | ||||
|     $('#' + user_family_field).removeAttr('class') | ||||
|     $('#' + user_family_field).text(family.name) | ||||
|     if (profile_pic_field != null) { | ||||
|       $('#' + profile_pic_field).attr('src', family.display_image) | ||||
|       // Si tu veux un lien vers la page famille : | ||||
|       $('#' + profile_pic_field + '_link').attr('href', '/family/detail/' + family.id + '/') | ||||
|     } | ||||
|   } | ||||
| } | ||||
|  | ||||
|  | ||||
| /** | ||||
|  * Retire une famille de la liste sélectionnée. | ||||
|  * @param d La famille à retirer | ||||
|  * @param family_prefix Le préfixe des <li> | ||||
|  * @param families_display Le tableau des familles sélectionnées | ||||
|  * @param family_list_id L'id du bloc où sont affichées les familles | ||||
|  * @param user_family_field Champ d'affichage (optionnel) | ||||
|  * @param profile_pic_field Champ photo (optionnel) | ||||
|  * @returns une fonction compatible avec les événements jQuery | ||||
|  */ | ||||
| function removeFamily(d, family_prefix, families_display, family_list_id, user_family_field = null, profile_pic_field = null) { | ||||
|   return function () { | ||||
|     const new_families_display = [] | ||||
|     let html = '' | ||||
|     families_display.forEach(function (disp) { | ||||
|     }) | ||||
|  | ||||
|     families_display.length = 0 | ||||
|     new_families_display.forEach(function (disp) { | ||||
|       families_display.push(disp) | ||||
|     }) | ||||
|  | ||||
|     $('#' + family_list_id).html(html) | ||||
|     families_display.forEach(function (disp) { | ||||
|       const obj = $('#' + family_prefix + '_' + disp.id) | ||||
|       obj.click(removeFamily(disp, family_prefix, families_display, family_list_id, user_family_field, profile_pic_field)) | ||||
|       obj.hover(function () { | ||||
|         displayFamily(disp.family, user_family_field, profile_pic_field) | ||||
|       }) | ||||
|     }) | ||||
|   } | ||||
| } | ||||
							
								
								
									
										149
									
								
								apps/family/tables.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										149
									
								
								apps/family/tables.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,149 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| import django_tables2 as tables | ||||
| from django.utils.html import format_html | ||||
| from django.utils.translation import gettext_lazy as _ | ||||
| from django_tables2 import A | ||||
| from django.urls import reverse, reverse_lazy | ||||
| from note_kfet.middlewares import get_current_request | ||||
| from permission.backends import PermissionBackend | ||||
|  | ||||
| from .models import Achievement, Challenge, Family, FamilyMembership | ||||
|  | ||||
|  | ||||
| class FamilyTable(tables.Table): | ||||
|     """ | ||||
|     List all families | ||||
|     """ | ||||
|  | ||||
|     description = tables.Column(verbose_name=_("Description")) | ||||
|  | ||||
|     class Meta: | ||||
|         attrs = { | ||||
|             'class': 'table table-condensed table-striped table-hover' | ||||
|         } | ||||
|         model = Family | ||||
|         template_name = 'django_tables2/bootstrap4.html' | ||||
|         fields = ('name', 'score', 'rank',) | ||||
|         order_by = ('rank',) | ||||
|         row_attrs = { | ||||
|             'class': 'table-row', | ||||
|             'data-href': lambda record: reverse('family:family_detail', args=[record.pk]), | ||||
|             'style': 'cursor:pointer', | ||||
|         } | ||||
|  | ||||
|  | ||||
| class ChallengeTable(tables.Table): | ||||
|     """ | ||||
|     List all challenges | ||||
|     """ | ||||
|  | ||||
|     name = tables.Column(verbose_name=_("Name")) | ||||
|     description = tables.Column(verbose_name=_("Description")) | ||||
|     points = tables.Column(verbose_name=_("Points")) | ||||
|  | ||||
|     class Meta: | ||||
|         attrs = { | ||||
|             'class': 'table table-condensed table-striped table-hover' | ||||
|         } | ||||
|         order_by = ('id',) | ||||
|         model = Challenge | ||||
|         template_name = 'django_tables2/bootstrap4.html' | ||||
|         fields = ('name', 'description', 'points',) | ||||
|         row_attrs = { | ||||
|             'class': 'table-row', | ||||
|             'data-href': lambda record: reverse('family:challenge_detail', args=[record.pk]), | ||||
|             'style': 'cursor:pointer', | ||||
|         } | ||||
|  | ||||
|  | ||||
| class FamilyMembershipTable(tables.Table): | ||||
|     """ | ||||
|     List all family memberships. | ||||
|     """ | ||||
|  | ||||
|     def render_user(self, value): | ||||
|         # Display user's name, clickable if permission is granted | ||||
|         s = value.username | ||||
|         if PermissionBackend.check_perm(get_current_request(), "auth.view_user", value): | ||||
|             s = format_html("<a href='{url}'>{name}</a>", | ||||
|                             url=reverse_lazy('member:user_detail', kwargs={"pk": value.pk}), name=s) | ||||
|         return s | ||||
|  | ||||
|     class Meta: | ||||
|         attrs = { | ||||
|             'class': 'table table-condensed table-striped', | ||||
|             'style': 'table-layout: fixed;' | ||||
|         } | ||||
|         template_name = 'django_tables2/bootstrap4.html' | ||||
|         fields = ('user',) | ||||
|         model = FamilyMembership | ||||
|  | ||||
|  | ||||
| class AchievementTable(tables.Table): | ||||
|     """ | ||||
|     List recent achievements. | ||||
|     """ | ||||
|  | ||||
|     challenge = tables.Column(verbose_name=_("Challenge")) | ||||
|  | ||||
|     validate = tables.LinkColumn( | ||||
|         'family:achievement_validate', | ||||
|         args=[A('id')], | ||||
|         verbose_name=_("Validate"), | ||||
|         text=_("Validate"), | ||||
|         orderable=False, | ||||
|         attrs={ | ||||
|             'th': { | ||||
|                 'id': 'validate-achievement-header' | ||||
|             }, | ||||
|             'a': { | ||||
|                 'class': 'btn btn-success', | ||||
|                 'data-type': 'validate-achievement' | ||||
|             } | ||||
|         }, | ||||
|     ) | ||||
|  | ||||
|     delete = tables.LinkColumn( | ||||
|         'family:achievement_delete', | ||||
|         args=[A('id')], | ||||
|         verbose_name=_("Delete"), | ||||
|         text=_("Delete"), | ||||
|         orderable=False, | ||||
|         attrs={ | ||||
|             'th': { | ||||
|                 'id': 'delete-achievement-header' | ||||
|             }, | ||||
|             'a': { | ||||
|                 'class': 'btn btn-danger', | ||||
|                 'data-type': 'delete-achievement' | ||||
|             } | ||||
|         }, | ||||
|     ) | ||||
|  | ||||
|     class Meta: | ||||
|         attrs = { | ||||
|             'class': 'table table-condensed table-striped table-hover' | ||||
|         } | ||||
|         model = Achievement | ||||
|         fields = ('family', 'challenge', 'challenge__points', 'obtained_at', 'valid') | ||||
|         template_name = 'django_tables2/bootstrap4.html' | ||||
|         order_by = ('-obtained_at',) | ||||
|  | ||||
|  | ||||
| class FamilyAchievementTable(tables.Table): | ||||
|     """ | ||||
|     Table des défis réalisés par une famille spécifique. | ||||
|     """ | ||||
|  | ||||
|     challenge = tables.Column(verbose_name=_("Challenge")) | ||||
|  | ||||
|     class Meta: | ||||
|         model = Achievement | ||||
|         template_name = 'django_tables2/bootstrap4.html' | ||||
|         fields = ('challenge', 'challenge__points', 'obtained_at', 'valid') | ||||
|         attrs = { | ||||
|             'class': 'table table-condensed table-striped table-hover' | ||||
|         } | ||||
|         order_by = ('-obtained_at',) | ||||
							
								
								
									
										25
									
								
								apps/family/templates/family/achievement_confirm_delete.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										25
									
								
								apps/family/templates/family/achievement_confirm_delete.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,25 @@ | ||||
| {% extends "base.html" %} | ||||
| {% comment %} | ||||
| SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endcomment %} | ||||
| {% load i18n crispy_forms_tags %} | ||||
|  | ||||
| {% block content %} | ||||
|     <div class="card bg-light"> | ||||
|         <div class="card-header text-center"> | ||||
|             <h4>{% trans "Delete achievement" %}</h4> | ||||
|         </div> | ||||
|             <div class="card-body"> | ||||
|                 <div class="alert alert-warning"> | ||||
|                     {% blocktrans %}Are you sure you want to delete this achievement? This action can't be undone.{% endblocktrans %} | ||||
|                 </div> | ||||
|             </div> | ||||
|         <div class="card-footer text-center"> | ||||
|             <form method="post"> | ||||
|                 {% csrf_token %} | ||||
|                 <a class="btn btn-primary" href="{% url 'family:achievement_list' %}">{% trans "Return to achievements list" %}</a> | ||||
|                 <button class="btn btn-danger" type="submit">{% trans "Delete" %}</button> | ||||
|             </form> | ||||
|         </div> | ||||
|     </div> | ||||
| {% endblock %} | ||||
| @@ -0,0 +1,28 @@ | ||||
| {% extends "base.html" %} | ||||
| {% comment %} | ||||
| SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endcomment %} | ||||
| {% load i18n crispy_forms_tags %} | ||||
|  | ||||
| {% block content %} | ||||
|     <div class="card bg-light"> | ||||
|         <div class="card-header text-center"> | ||||
|             <h4>{% trans "Validate achievement" %}</h4> | ||||
|         </div> | ||||
|             <div class="card-body"> | ||||
|                 <div class="alert alert-warning"> | ||||
|                     {% blocktrans %}Are you sure you want to validate this achievement? This action can't be undone.{% endblocktrans %} | ||||
|                 </div> | ||||
|             </div> | ||||
|         <div class="card-footer text-center"> | ||||
|             <form method="post"> | ||||
|                 {% csrf_token %} | ||||
|                 <a class="btn btn-primary" href="{% url 'family:achievement_list' %}">{% trans "Return to achievements list" %}</a> | ||||
|                 <form method="post" action="{% url 'family:achievement_validate' pk %}"> | ||||
|                     {% csrf_token %} | ||||
|                     <button type="submit" class="btn btn-success">{% trans "Validate" %}</button> | ||||
|                 </form> | ||||
|             </form> | ||||
|         </div> | ||||
|     </div> | ||||
| {% endblock %} | ||||
							
								
								
									
										33
									
								
								apps/family/templates/family/achievement_list.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										33
									
								
								apps/family/templates/family/achievement_list.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,33 @@ | ||||
| {% extends "base.html" %} | ||||
| {% comment %} | ||||
| Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endcomment %} | ||||
| {% load i18n django_tables2 %} | ||||
|  | ||||
| {% block content %} | ||||
|  | ||||
| <div class="card mb-4" id="history"> | ||||
|     <div class="card-header"> | ||||
|         <p class="card-text font-weight-bold"> | ||||
|             {% trans "Invalid achievements history" %} | ||||
|         </p> | ||||
|         <a class="btn btn-sm btn-primary mx-2" href="{% url "family:manage" %}"> | ||||
|             {% trans "Return to management page" %} | ||||
|         </a> | ||||
|     </div> | ||||
|     {% render_table invalid %} | ||||
| </div> | ||||
|  | ||||
| <div class="card mb-4" id="history"> | ||||
|     <div class="card-header"> | ||||
|         <p class="card-text font-weight-bold"> | ||||
|             {% trans "Valid achievements history" %} | ||||
|         </p> | ||||
|         <a class="btn btn-sm btn-primary mx-2" href="{% url "family:manage" %}"> | ||||
|             {% trans "Return to management page" %} | ||||
|         </a> | ||||
|     </div> | ||||
|     {% render_table valid %} | ||||
| </div> | ||||
| {% endblock %} | ||||
							
								
								
									
										60
									
								
								apps/family/templates/family/add_member.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										60
									
								
								apps/family/templates/family/add_member.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,60 @@ | ||||
| {% extends "family/base.html" %} | ||||
| {% comment %} | ||||
| SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endcomment %} | ||||
| {% load crispy_forms_tags i18n pretty_money %} | ||||
|  | ||||
| {% block profile_content %} | ||||
| <div class="card bg-light"> | ||||
|     <h3 class="card-header text-center"> | ||||
|         {{ title }} | ||||
|     </h3> | ||||
|     <div class="card-body"> | ||||
|          | ||||
|         <form method="post" action=""> | ||||
|             {% csrf_token %} | ||||
|             {{ form|crispy }} | ||||
|             <button class="btn btn-primary" type="submit">{% trans "Submit" %}</button> | ||||
|         </form> | ||||
|     </div> | ||||
| </div> | ||||
| {% endblock %} | ||||
|  | ||||
| {% block extrajavascript %} | ||||
| <script> | ||||
|     function autocompleted(user) { | ||||
|         $("#id_last_name").val(user.last_name); | ||||
|         $("#id_first_name").val(user.first_name); | ||||
|         $.getJSON("/api/members/profile/" + user.id + "/", function (profile) { | ||||
|             let fee = profile.paid ? "{{ club.membership_fee_paid }}" : "{{ club.membership_fee_unpaid }}"; | ||||
|             $("#id_credit_amount").val((Number(fee) / 100).toFixed(2)); | ||||
|         }); | ||||
|     } | ||||
|  | ||||
|     soge_field = $("#id_soge"); | ||||
|  | ||||
|     function fillFields() { | ||||
|         let checked = soge_field.is(':checked'); | ||||
|         if (!checked) { | ||||
|             $("input").attr('disabled', false); | ||||
|             $("#id_user").attr('disabled', true); | ||||
|             $("select").attr('disabled', false); | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         let credit_type = $("#id_credit_type"); | ||||
|         credit_type.attr('disabled', true); | ||||
|         credit_type.val(4); | ||||
|  | ||||
|         let credit_amount = $("#id_credit_amount"); | ||||
|         credit_amount.attr('disabled', true); | ||||
|         credit_amount.val('{{ total_fee }}'); | ||||
|  | ||||
|         let bank = $("#id_bank"); | ||||
|         bank.attr('disabled', true); | ||||
|         bank.val('Société générale'); | ||||
|     } | ||||
|  | ||||
|     soge_field.change(fillFields); | ||||
| </script> | ||||
| {% endblock %} | ||||
							
								
								
									
										52
									
								
								apps/family/templates/family/base.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										52
									
								
								apps/family/templates/family/base.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,52 @@ | ||||
| {% extends "base.html" %} | ||||
| {% comment %} | ||||
| SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endcomment %} | ||||
| {% load i18n perms %} | ||||
|  | ||||
| {# Use a fluid-width container #} | ||||
| {% block containertype %}container-fluid{% endblock %} | ||||
|  | ||||
| {% block content %} | ||||
| <div class="row mt-4"> | ||||
|     <div class="col-xl-4"> | ||||
|         {% block profile_info %} | ||||
|         <div class="card bg-light" id="card-infos"> | ||||
|             <h4 class="card-header text-center"> | ||||
|                 {{ family.name }} | ||||
|             </h4> | ||||
|             <div class="text-center"> | ||||
|                 <a href="{% url 'family:update_pic' family.pk  %}"> | ||||
|                     <img src="{{ family.display_image.url }}" class="img-thumbnail mt-2"> | ||||
|                 </a> | ||||
|             </div> | ||||
|             <div class="card-body" id="profile_infos"> | ||||
|                 {% include "family/family_info.html" %} | ||||
|             </div> | ||||
|             <div class="card-footer"> | ||||
|                 {% if can_add_members %} | ||||
|                 <a class="btn btn-sm btn-success" href="{% url 'family:family_add_member' family_pk=family.pk %}" | ||||
|                    data-turbolinks="false"> {% trans "Add member" %}</a> | ||||
|                 {% endif %} | ||||
|                 {% if ".change_"|has_perm:family %} | ||||
|                 <a class="btn btn-sm btn-secondary" href="{% url 'family:family_update' pk=family.pk %}" | ||||
|                    data-turbolinks="false"> | ||||
|                     <i class="fa fa-edit"></i> {% trans 'Update Profile' %} | ||||
|                 </a> | ||||
|                 {% endif %} | ||||
|                 {% url 'family:family_detail' family.pk as family_detail_url %} | ||||
|                 {% if request.path_info != family_detail_url %} | ||||
|                 <a class="btn btn-sm btn-primary" href="{{ family_detail_url }}">{% trans 'View Profile' %}</a> | ||||
|                 {% endif %} | ||||
|                 <a class="btn btn-sm btn-primary" href="{% url "family:family_list" %}"> | ||||
|                     {% trans "Return to the family list" %} | ||||
|                   </a> | ||||
|             </div> | ||||
|         </div> | ||||
|         {% endblock %} | ||||
|     </div> | ||||
|     <div class="col-xl-8"> | ||||
|         {% block profile_content %}{% endblock %} | ||||
|     </div> | ||||
| </div> | ||||
| {% endblock %} | ||||
							
								
								
									
										36
									
								
								apps/family/templates/family/challenge_detail.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										36
									
								
								apps/family/templates/family/challenge_detail.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,36 @@ | ||||
| {% extends "base.html" %} | ||||
| {% comment %} | ||||
| Copyright (C) by BDE ENS Paris-Saclay | ||||
| SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endcomment %} | ||||
| {% load i18n crispy_forms_tags %} | ||||
|  | ||||
| {% block content %} | ||||
| <div class="card bg-white mb-3"> | ||||
|   <h3 class="card-header text-center"> | ||||
|     {{ title }} {{ challenge.name }} | ||||
|   </h3> | ||||
|   <div class="card-body"> | ||||
|     <ul> | ||||
|       {% for field, value in fields %} | ||||
|       <li> {{ field }} : {{ value }}</li> | ||||
|       {% endfor %} | ||||
|       <li> {% trans "Obtained by " %} {{obtained}} | ||||
|         {% if obtained > 1 %} | ||||
|           {% trans "families" %} | ||||
|         {% else %} | ||||
|           {% trans "family" %} | ||||
|         {% endif %} | ||||
|       </li> | ||||
|     </ul> | ||||
|       <a class="btn btn-sm btn-primary" href="{% url "family:challenge_list" %}"> | ||||
|         {% trans "Return to the challenge list" %} | ||||
|       </a> | ||||
|       {% if update %} | ||||
|       <a class="btn btn-sm btn-secondary" href="{% url "family:challenge_update" pk=challenge.pk %}"> | ||||
|         {% trans "Update" %} | ||||
|       </a> | ||||
|       {% endif %} | ||||
|   </div> | ||||
| </div> | ||||
| {% endblock %} | ||||
							
								
								
									
										21
									
								
								apps/family/templates/family/challenge_form.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								apps/family/templates/family/challenge_form.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,21 @@ | ||||
| {% extends "base.html" %} | ||||
| {% comment %} | ||||
| Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endcomment %} | ||||
| {% load i18n crispy_forms_tags %} | ||||
|  | ||||
| {% block content %} | ||||
| <div class="card bg-white mb-3"> | ||||
|   <h3 class="card-header text-center"> | ||||
|     {{ title }} | ||||
|   </h3> | ||||
|   <div class="card-body" id="form"> | ||||
|     <form method="post"> | ||||
|       {% csrf_token %} | ||||
|       {{ form | crispy }} | ||||
|       <button class="btn btn-primary" type="submit">{% trans "Submit"%}</button> | ||||
|     </form> | ||||
|   </div> | ||||
| </div> | ||||
| {% endblock %} | ||||
							
								
								
									
										42
									
								
								apps/family/templates/family/challenge_list.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										42
									
								
								apps/family/templates/family/challenge_list.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,42 @@ | ||||
| {% extends "base.html" %} | ||||
| {% comment %} | ||||
| Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endcomment %} | ||||
| {% load render_table from django_tables2 %} | ||||
| {% load i18n %} | ||||
|  | ||||
| {% block content %} | ||||
| <div class="row"> | ||||
|     <div class="col-xl-12"> | ||||
|         <div class="btn-group btn-group-toggle" style="width: 100%; padding: 0 0 2em 0"> | ||||
|             <a href="{% url "family:family_list" %}" class="btn btn-sm btn-outline-primary"> | ||||
|                 {% trans "Families" %} | ||||
|             </a> | ||||
|             <a href="#" class="btn btn-sm btn-outline-primary active"> | ||||
|                 {% trans "Challenges" %} | ||||
|             </a> | ||||
|             {% if can_manage %} | ||||
|             <a href="{% url "family:manage" %}" class="btn btn-sm btn-outline-primary"> | ||||
|                 {% trans "Manage" %} | ||||
|             </a> | ||||
|             {% endif %} | ||||
|         </div> | ||||
|     </div> | ||||
| </div> | ||||
|  | ||||
| <div class="card bg-white mb-3"> | ||||
|     <h3 class="card-header text-center"> | ||||
|         {{ title }} | ||||
|     </h3> | ||||
|     {% render_table table %} | ||||
| </div> | ||||
| {% endblock %} | ||||
|  | ||||
| {% block extrajavascript %} | ||||
| <script type="text/javascript"> | ||||
|     $(".table-row").click(function () { | ||||
|             window.document.location = $(this).data("href"); | ||||
|         }); | ||||
| </script> | ||||
| {% endblock %} | ||||
							
								
								
									
										29
									
								
								apps/family/templates/family/family_detail.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										29
									
								
								apps/family/templates/family/family_detail.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,29 @@ | ||||
| {% extends "family/base.html" %} | ||||
| {% comment %} | ||||
| Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endcomment %} | ||||
| {% load render_table from django_tables2 %} | ||||
| {% load i18n perms %} | ||||
|  | ||||
| {% block profile_content %} | ||||
| {% if member_list.data %} | ||||
| <div class="card"> | ||||
|     <div class="card-header position-relative" id="clubListHeading"> | ||||
|         <i class="fa fa-users"></i> {% trans "Family members" %} | ||||
|     </div> | ||||
|     {% render_table member_list %} | ||||
| </div> | ||||
|  | ||||
| <div class="my-4"></div> | ||||
| {% endif %} | ||||
|  | ||||
| {% if achievement_list.data %} | ||||
| <div class="card"> | ||||
|     <div class="card-header position-relative"> | ||||
|         <i class="fa fa-trophy"></i> {% trans "Completed challenges" %} | ||||
|     </div> | ||||
|     {% render_table achievement_list %} | ||||
| </div> | ||||
| {% endif %} | ||||
| {% endblock %} | ||||
							
								
								
									
										21
									
								
								apps/family/templates/family/family_form.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								apps/family/templates/family/family_form.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,21 @@ | ||||
| {% extends "base.html" %} | ||||
| {% comment %} | ||||
| Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endcomment %} | ||||
| {% load i18n crispy_forms_tags %} | ||||
|  | ||||
| {% block content %} | ||||
| <div class="card bg-white mb-3"> | ||||
|   <h3 class="card-header text-center"> | ||||
|     {{ title }} | ||||
|   </h3> | ||||
|   <div class="card-body" id="form"> | ||||
|     <form method="post"> | ||||
|       {% csrf_token %} | ||||
|       {{ form | crispy }} | ||||
|       <button class="btn btn-primary" type="submit">{% trans "Submit"%}</button> | ||||
|     </form> | ||||
|   </div> | ||||
| </div> | ||||
| {% endblock %} | ||||
							
								
								
									
										15
									
								
								apps/family/templates/family/family_info.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										15
									
								
								apps/family/templates/family/family_info.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,15 @@ | ||||
| {% load i18n pretty_money perms %} | ||||
|  | ||||
| <dl class="row"> | ||||
|     <dt class="col-xl-6">{% trans 'name'|capfirst %}</dt> | ||||
|     <dd class="col-xl-6">{{ family.name }}</dd> | ||||
|  | ||||
|     <dt class="col-xl-6">{% trans 'description'|capfirst %}</dt> | ||||
|     <dd class="col-xl-6">{{ family.description }}</dd> | ||||
|  | ||||
|     <dt class="col-xl-6">{% trans 'score'|capfirst %}</dt> | ||||
|     <dd class="col-xl-6">{{ family.score }}</dd> | ||||
|  | ||||
|     <dt class="col-xl-6">{% trans 'rank'|capfirst %}</dt> | ||||
|     <dd class="col-xl-6">{{ family.rank }}</dd> | ||||
| </dl> | ||||
							
								
								
									
										43
									
								
								apps/family/templates/family/family_list.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										43
									
								
								apps/family/templates/family/family_list.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,43 @@ | ||||
| {% extends "base.html" %} | ||||
| {% comment %} | ||||
| Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endcomment %} | ||||
| {% load render_table from django_tables2 %} | ||||
| {% load i18n %} | ||||
|  | ||||
| {% block content %} | ||||
| <div class="row"> | ||||
|     <div class="col-xl-12"> | ||||
|         <div class="btn-group btn-group-toggle" style="width: 100%; padding: 0 0 2em 0"> | ||||
|             <a href="#" class="btn btn-sm btn-outline-primary active"> | ||||
|                 {% trans "Families" %} | ||||
|             </a> | ||||
|             <a href="{% url "family:challenge_list" %}" class="btn btn-sm btn-outline-primary"> | ||||
|                 {% trans "Challenges" %} | ||||
|             </a> | ||||
|             {% if can_manage %} | ||||
|             <a href="{% url "family:manage" %}" class="btn btn-sm btn-outline-primary"> | ||||
|                 {% trans "Manage" %} | ||||
|             </a> | ||||
|             {% endif %} | ||||
|         </div> | ||||
|     </div> | ||||
| </div> | ||||
|  | ||||
| <div class="card bg-white mb-3"> | ||||
|     <h3 class="card-header text-center"> | ||||
|         {{ title }} | ||||
|     </h3> | ||||
|     {% render_table table %} | ||||
| </div> | ||||
|  | ||||
| {% endblock %} | ||||
|  | ||||
| {% block extrajavascript %} | ||||
| <script type="text/javascript"> | ||||
|     $(".table-row").click(function () { | ||||
|             window.document.location = $(this).data("href"); | ||||
|         }); | ||||
| </script> | ||||
| {% endblock %} | ||||
							
								
								
									
										287
									
								
								apps/family/templates/family/manage.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										287
									
								
								apps/family/templates/family/manage.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,287 @@ | ||||
| {% extends "base.html" %} | ||||
| {% comment %} | ||||
| Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endcomment %} | ||||
| {% load i18n static django_tables2 %} | ||||
|  | ||||
| {% block containertype %}container-fluid{% endblock %} | ||||
|  | ||||
| {% block content %} | ||||
| <div class="row"> | ||||
|     <div class="col-xl-12"> | ||||
|         <div class="btn-group btn-group-toggle" style="width: 100%; padding: 0 0 2em 0"> | ||||
|             <a href="{% url "family:family_list" %}" class="btn btn-sm btn-outline-primary"> | ||||
|                 {% trans "Families" %} | ||||
|             </a> | ||||
|             <a href="{% url "family:challenge_list" %}" class="btn btn-sm btn-outline-primary"> | ||||
|                 {% trans "Challenges" %} | ||||
|             </a> | ||||
|             <a href="#" class="btn btn-sm btn-outline-primary active"> | ||||
|                 {% trans "Manage" %} | ||||
|             </a> | ||||
|         </div> | ||||
|     </div> | ||||
| </div> | ||||
|  | ||||
| <div class="row mb-3"> | ||||
|     <div class='col-sm-5 col-xl-6' id="infos_div"> | ||||
|         {% if can_add_achievement %} | ||||
|         <div class="row justify-content-center justify-content-md-end"> | ||||
|             {# Family details column #} | ||||
|             <div class="col picture-col"> | ||||
|                 <div class="card bg-light mb-4 text-center"> | ||||
|                     <a id="profile_pic_link" href="#"> | ||||
|                         <img src="{% static "member/img/default_picture.png" %}" id="profile_pic" alt="" class="card-img-top d-none d-sm-block"> | ||||
|                     </a> | ||||
|                     <div class="card-body text-center text-break p-2"> | ||||
|                         <span id="user_note"><i class="small">{% trans "Please select a family" %}</i></span> | ||||
|                     </div> | ||||
|                 </div> | ||||
|             </div> | ||||
|  | ||||
|             {# Family selection column #} | ||||
|             <div class="col-xl" id="user_select_div"> | ||||
|                 <div class="card bg-light border-success mb-4"> | ||||
|                     <div class="card-header"> | ||||
|                         <p class="card-text font-weight-bold"> | ||||
|                             {% trans "Families" %} | ||||
|                         </p> | ||||
|                     </div> | ||||
|                     <div class="card-body p-0" style="min-height:125px;"> | ||||
|                         <ul class="list-group list-group-flush" id="note_list"></ul> | ||||
|                     </div> | ||||
|                     {# User search with autocompletion #} | ||||
|                     <div class="card-footer"> | ||||
|                         <input class="form-control mx-auto d-block mb-2" placeholder="{% trans "Name" %}" type="text" id="note" autofocus /> | ||||
|                         {% if user_family %} | ||||
|                         <button class="btn btn-sm btn-secondary btn-block" id="select_my_family"> | ||||
|                             {% trans "Select my family" %} ({{ user_family.name }}) | ||||
|                         </button> | ||||
|                         {% endif %} | ||||
|                     </div> | ||||
|                 </div> | ||||
|             </div> | ||||
|  | ||||
|             {# Summary of challenges and validate button #} | ||||
|             <div class="col-xl-5" id="consos_list_div"> | ||||
|                 <div class="card bg-light border-info mb-4"> | ||||
|                     <div class="card-header"> | ||||
|                         <p class="card-text font-weight-bold"> | ||||
|                             {% trans "Challenges" %} | ||||
|                         </p> | ||||
|                     </div> | ||||
|                     <div class="card-body p-0" style="min-height:125px;"> | ||||
|                         <ul class="list-group list-group-flush" id="consos_list"></ul> | ||||
|                     </div> | ||||
|                     <div class="card-footer text-center"> | ||||
|                         <span id="consume_all" class="btn btn-primary"> | ||||
|                             {% trans "Validate!" %} | ||||
|                         </span> | ||||
|                     </div> | ||||
|                 </div> | ||||
|             </div> | ||||
|         </div> | ||||
|         {% endif %} | ||||
|  | ||||
|         {# Create family/challenge buttons #} | ||||
|         {% if can_add_family or can_add_challenge %} | ||||
|         <div class="card bg-light border-success mb-4"> | ||||
|           <h3 class="card-header font-weight-bold text-center"> | ||||
|               {% trans "Create a family or challenge" %} | ||||
|           </h3> | ||||
|         <div class="card-body text-center"> | ||||
|             {% if can_add_family %} | ||||
|             <a class="btn btn-sm btn-primary mx-2" href="{% url "family:family_create" %}"> | ||||
|                 {% trans "Add a family" %} | ||||
|             </a> | ||||
|             {% endif %} | ||||
|             {% if can_add_challenge %} | ||||
|             <a class="btn btn-sm btn-primary mx-2" href="{% url "family:challenge_create" %}"> | ||||
|                 {% trans "Add a challenge" %} | ||||
|             </a> | ||||
|             {% endif %} | ||||
|         </div> | ||||
|         </div> | ||||
|         {% endif %} | ||||
|     </div> | ||||
|  | ||||
|     {# Buttons column #} | ||||
|     <div class="col"> | ||||
|         {% if can_add_achievement %} | ||||
|         <div class="card bg-light border-primary text-center mb-4"> | ||||
|             {# Tabs for list and search #} | ||||
|             <div class="card-header"> | ||||
|                 <ul class="nav nav-tabs nav-fill card-header-tabs"> | ||||
|                     <li class="nav-item"> | ||||
|                         <a class="nav-link font-weight-bold" data-toggle="tab" href="#list"> | ||||
|                             {% trans "List" %} | ||||
|                         </a> | ||||
|                     </li> | ||||
|                     <li class="nav-item"> | ||||
|                         <a class="nav-link font-weight-bold" data-toggle="tab" href="#search"> | ||||
|                             {% trans "Search" %} | ||||
|                         </a> | ||||
|                     </li> | ||||
|                 </ul> | ||||
|             </div> | ||||
|  | ||||
|             {# Tabs content #} | ||||
|             <div class="card-body"> | ||||
|                 <div class="tab-content"> | ||||
|                     <div class="tab-pane" id="list"> | ||||
|                         <div class="d-inline-flex flex-wrap justify-content-center"> | ||||
|                             {% for challenge in all_challenges %} | ||||
|                                     <button class="btn btn-outline-dark rounded-0 flex-fill" | ||||
|                                             id="challenge{{ challenge.id }}" name="button" value="{{ challenge.name }}"> | ||||
|                                         {{ challenge.name }} ({{ challenge.points }} {% trans "points" %}) | ||||
|                                     </button> | ||||
|                             {% endfor %} | ||||
|                         </div> | ||||
|                     </div> | ||||
|                     <div class="tab-pane" id="search"> | ||||
|                         <input class="form-control mx-auto d-block mb-3" placeholder="{% trans "Search challenge..." %}" type="search" id="search-input"/> | ||||
|                         <div class="d-inline-flex flex-wrap justify-content-center" id="search-results"> | ||||
|                             {% for challenge in all_challenges %} | ||||
|                                     <button class="btn btn-outline-dark rounded-0 flex-fill" hidden | ||||
|                                             id="search_challenge{{ challenge.id }}" name="button" value="{{ challenge.name }}"> | ||||
|                                             {{ challenge.name }} ({{ challenge.points }} {% trans "points" %}) | ||||
|                                     </button> | ||||
|                             {% endfor %} | ||||
|                         </div> | ||||
|                     </div> | ||||
|                 </div> | ||||
|             </div> | ||||
|  | ||||
|         </div> | ||||
|         {% endif %} | ||||
|     </div> | ||||
| </div> | ||||
|  | ||||
| {# achievement history #} | ||||
| {% if table.data %} | ||||
|     <div class="card"> | ||||
|         <div class="card-header position-relative" id="historyListHeading"> | ||||
|             <a class="stretched-link font-weight-bold"  | ||||
|                 href="{% url 'family:achievement_list' %}" > | ||||
|                 {% trans "Recent achievements history" %} | ||||
|             </a> | ||||
|         </div> | ||||
|         <div id="history"> | ||||
|             {% render_table table %} | ||||
|         </div> | ||||
|     </div> | ||||
|  | ||||
|         <!-- Popup de validation --> | ||||
|     <div class="modal fade" id="validationModal" tabindex="-1" role="dialog" aria-labelledby="validationModalLabel" aria-hidden="true"> | ||||
|     <div class="modal-dialog modal-dialog-centered" role="document"> | ||||
|         <div class="modal-content border-success"> | ||||
|         <div class="modal-header bg-success text-white"> | ||||
|             <h5 class="modal-title" id="validationModalLabel">{% trans "Confirmation" %}</h5> | ||||
|             <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"> | ||||
|             <span aria-hidden="true">×</span> | ||||
|             </button> | ||||
|         </div> | ||||
|         <div class="modal-body"> | ||||
|                 <p><strong>{% trans "Are you sure you want to validate this challenge?" %}</strong></p> | ||||
|                 <p>{% trans "To have your challenge officially validated, please send a message with:" %}</p> | ||||
|                 <ul> | ||||
|                 <li>{% trans "The name of the family" %}</li> | ||||
|                 <li>{% trans "The name of the challenge" %}</li> | ||||
|                 <li>{% trans "A photo or video as proof" %}</li> | ||||
|                 </ul> | ||||
|                 <p> | ||||
|                 <strong>{% trans "Send it via WhatsApp to:" %}</strong> | ||||
|                 {% if phone_numbers %}" | ||||
|                 {% for num in phone_numbers %} | ||||
|                     <a href="https://wa.me/{{ num }}" target="_blank">{{ num }}</a>{% if not forloop.last %}, {% endif %} | ||||
|                 {% endfor %} | ||||
|                 {% endif %} | ||||
|                 </p> | ||||
|         </div> | ||||
|         <div class="modal-footer"> | ||||
|             <button type="button" class="btn btn-primary" data-dismiss="modal">{% trans "OK" %}</button> | ||||
|         </div> | ||||
|         </div> | ||||
|     </div> | ||||
|     </div> | ||||
| {% endif %} | ||||
| {% endblock %} | ||||
|  | ||||
|  | ||||
|  | ||||
| {% block extrajavascript %} | ||||
|     <script type="text/javascript" src="{% static "family/js/achievements.js" %}"></script> | ||||
|     <script type="text/javascript"> | ||||
|         {% for challenge in all_challenges %} | ||||
|         document.getElementById("challenge{{ challenge.id }}").addEventListener("click", function() { | ||||
|             addChallenge({{ challenge.id}}, "{{ challenge.name|escapejs }}", {{ challenge.points }}); | ||||
|         }); | ||||
|         {% endfor %} | ||||
|      | ||||
|         {% for challenge in all_challenges %} | ||||
|             document.getElementById("search_challenge{{ challenge.id }}").addEventListener("click", function() { | ||||
|                 addChallenge({{ challenge.id}}, "{{ challenge.name|escapejs }}", {{ challenge.points }}); | ||||
|             }); | ||||
|         {% endfor %}  | ||||
|     </script> | ||||
|     <script> | ||||
|         document.getElementById("consume_all").addEventListener("click", function () { | ||||
|             $('#validationModal').modal('show'); | ||||
|         }); | ||||
|  | ||||
|         $('#validationModal .btn-primary').on('click', function () { | ||||
|             consumeAll(); | ||||
|         }); | ||||
|          | ||||
|         {% if user_family %} | ||||
|         document.getElementById("select_my_family").addEventListener("click", function () { | ||||
|             // Simulate selecting the user's family | ||||
|             var userFamily = { | ||||
|                 id: {{ user_family.id }}, | ||||
|                 name: "{{ user_family.name|escapejs }}", | ||||
|                 display_image: "{{ user_family.display_image.url|default:'/static/member/img/default_picture.png'|escapejs }}" | ||||
|             }; | ||||
|              | ||||
|             // Check if family is already selected | ||||
|             var alreadySelected = false; | ||||
|             notes_display.forEach(function (d) { | ||||
|                 if (d.id === userFamily.id) { | ||||
|                     alreadySelected = true; | ||||
|                 } | ||||
|             }); | ||||
|              | ||||
|             if (!alreadySelected) { | ||||
|                 // Add the family to the selected families | ||||
|                 var disp = { | ||||
|                     name: userFamily.name, | ||||
|                     id: userFamily.id, | ||||
|                     family: userFamily, | ||||
|                 }; | ||||
|                 notes_display.push(disp); | ||||
|                  | ||||
|                 // Update the display | ||||
|                 const family_list = $('#note_list'); | ||||
|                 let html = ''; | ||||
|                 notes_display.forEach(function (disp) { | ||||
|                     html += li('note_' + disp.id, disp.name, ''); | ||||
|                 }); | ||||
|                  | ||||
|                 family_list.html(html); | ||||
|                  | ||||
|                 // Add click handlers for removal | ||||
|                 notes_display.forEach(function (disp) { | ||||
|                     const line_obj = $('#note_' + disp.id); | ||||
|                     line_obj.hover(function () { | ||||
|                         displayFamily(disp.family, disp.name, 'user_note', 'profile_pic'); | ||||
|                     }); | ||||
|                     line_obj.click(removeFamily(disp, 'note', notes_display, 'note_list', 'user_note', 'profile_pic')); | ||||
|                 }); | ||||
|                  | ||||
|                 // Display the family info | ||||
|                 displayFamily(userFamily, userFamily.name, 'user_note', 'profile_pic'); | ||||
|             } | ||||
|         }); | ||||
|         {% endif %} | ||||
|     </script> | ||||
| {% endblock %} | ||||
							
								
								
									
										118
									
								
								apps/family/templates/family/picture_update.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										118
									
								
								apps/family/templates/family/picture_update.html
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,118 @@ | ||||
| {% extends "family/base.html" %} | ||||
| {% comment %} | ||||
| SPDX-License-Identifier: GPL-3.0-or-later | ||||
| {% endcomment %} | ||||
| {% load i18n crispy_forms_tags %} | ||||
|  | ||||
| {% block profile_content %} | ||||
| <div class="card bg-light"> | ||||
|   <h3 class="card-header text-center"> | ||||
|     {{ title }} | ||||
|   </h3> | ||||
|   <div class="card-body"> | ||||
|     <div class="text-center"> | ||||
|       <form method="post" enctype="multipart/form-data" id="formUpload"> | ||||
|         {% csrf_token %} | ||||
|         {{ form |crispy }} | ||||
|         {% if user.note.display_image != "pic/default.png" %} | ||||
|           <input type="submit" class="btn btn-primary" value="{% trans "Remove" %}"> | ||||
|         {% endif %} | ||||
|       </form> | ||||
|     </div> | ||||
|     <!-- MODAL TO CROP THE IMAGE --> | ||||
|     <div class="modal fade" id="modalCrop" data-backdrop="static"> | ||||
|       <div class="modal-dialog"> | ||||
|         <div class="modal-content"> | ||||
|             <div class="modal-body-wrapper" style="width: 500px; height: 500px; padding: 16px;"> | ||||
|               <div class="modal-body" style="width: 100%; height: 100%; padding: 0"> | ||||
|                 <img src="" id="modal-image" style="display: block; max-width: 100%;"> | ||||
|               </div> | ||||
|             </div> | ||||
|           <div class="modal-footer"> | ||||
|             <div class="btn-group pull-left" role="group"> | ||||
|               <button type="button" class="btn btn-default" id="js-zoom-in"> | ||||
|                 <span class="glyphicon glyphicon-zoom-in"></span> | ||||
|               </button> | ||||
|               <button type="button" class="btn btn-default js-zoom-out"> | ||||
|                 <span class="glyphicon glyphicon-zoom-out"></span> | ||||
|               </button> | ||||
|             </div> | ||||
|             <button type="button" class="btn btn-default" data-dismiss="modal">{% trans "Nevermind" %}</button> | ||||
|             <button type="button" class="btn btn-primary js-crop-and-upload">{% trans "Crop and upload" %}</button> | ||||
|           </div> | ||||
|         </div> | ||||
|       </div> | ||||
|     </div> | ||||
|   </div> | ||||
| </div> | ||||
| {% endblock %} | ||||
|  | ||||
| {% block extracss %} | ||||
| <link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.min.css" rel="stylesheet"> | ||||
| {% endblock %} | ||||
|  | ||||
| {% block extrajavascript%} | ||||
| <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.min.js"></script> | ||||
| <script src="https://cdn.jsdelivr.net/npm/jquery-cropper@1.0.1/dist/jquery-cropper.min.js"></script> | ||||
| <script> | ||||
|   $(function () { | ||||
|  | ||||
|     /* SCRIPT TO OPEN THE MODAL WITH THE PREVIEW */ | ||||
|     $("#id_image").change(function (e) { | ||||
|       if (this.files && this.files[0]) { | ||||
|         // Check the image size | ||||
|         if (this.files[0].size > 2*1024*1024) { | ||||
|           alert("Ce fichier est trop volumineux.") | ||||
| 	} else { | ||||
|           // Read the selected image file | ||||
|           var reader = new FileReader(); | ||||
|           reader.onload = function (e) { | ||||
|             $("#modal-image").attr("src", e.target.result); | ||||
|             $("#modalCrop").modal("show"); | ||||
|           } | ||||
|           reader.readAsDataURL(this.files[0]); | ||||
|         } | ||||
|       } | ||||
|     }); | ||||
|  | ||||
|     /* SCRIPTS TO HANDLE THE CROPPER BOX */ | ||||
|     var $image = $("#modal-image"); | ||||
|     var cropBoxData; | ||||
|     var canvasData; | ||||
|     $("#modalCrop").on("shown.bs.modal", function () { | ||||
|       $image.cropper({ | ||||
|         viewMode: 1, | ||||
|         aspectRatio: 1 / 1, | ||||
|         minCropBoxWidth: 200, | ||||
|         minCropBoxHeight: 200, | ||||
|         ready: function () { | ||||
|           $image.cropper("setCanvasData", canvasData); | ||||
|           $image.cropper("setCropBoxData", cropBoxData); | ||||
|         } | ||||
|       }); | ||||
|     }).on("hidden.bs.modal", function () { | ||||
|       cropBoxData = $image.cropper("getCropBoxData"); | ||||
|       canvasData = $image.cropper("getCanvasData"); | ||||
|       $image.cropper("destroy"); | ||||
|     }); | ||||
|  | ||||
|     $(".js-zoom-in").click(function () { | ||||
|       $image.cropper("zoom", 0.1); | ||||
|     }); | ||||
|  | ||||
|     $(".js-zoom-out").click(function () { | ||||
|       $image.cropper("zoom", -0.1); | ||||
|     }); | ||||
|  | ||||
|     /* SCRIPT TO COLLECT THE DATA AND POST TO THE SERVER */ | ||||
|     $(".js-crop-and-upload").click(function () { | ||||
|       var cropData = $image.cropper("getData"); | ||||
|       $("#id_x").val(cropData["x"]); | ||||
|       $("#id_y").val(cropData["y"]); | ||||
|       $("#id_height").val(cropData["height"]); | ||||
|       $("#id_width").val(cropData["width"]); | ||||
|       $("#formUpload").submit(); | ||||
|     }); | ||||
|   }); | ||||
| </script> | ||||
| {% endblock %} | ||||
							
								
								
									
										0
									
								
								apps/family/tests/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										0
									
								
								apps/family/tests/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
								
								
									
										328
									
								
								apps/family/tests/test_family.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										328
									
								
								apps/family/tests/test_family.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,328 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| import os | ||||
|  | ||||
| from api.tests import TestAPI | ||||
| from django.contrib.auth.models import User | ||||
| from django.core.files.uploadedfile import SimpleUploadedFile | ||||
| from django.test import TestCase | ||||
| from rest_framework.test import APITestCase | ||||
| from django.urls import reverse | ||||
| from django.utils import timezone | ||||
|  | ||||
| from ..api.views import FamilyViewSet, FamilyMembershipViewSet, ChallengeViewSet, AchievementViewSet | ||||
| from ..models import Family, FamilyMembership, Challenge, Achievement | ||||
|  | ||||
|  | ||||
| class TestFamily(TestCase): | ||||
|     """ | ||||
|     Test family | ||||
|     """ | ||||
|  | ||||
|     def setUp(self): | ||||
|         self.user = User.objects.create_superuser( | ||||
|             username='admintoto', | ||||
|             password='toto1234', | ||||
|             email='toto@example.com', | ||||
|         ) | ||||
|         self.client.force_login(self.user) | ||||
|  | ||||
|         sess = self.client.session | ||||
|         sess['permission_mask'] = 42 | ||||
|         sess.save() | ||||
|  | ||||
|         self.family = Family.objects.create( | ||||
|             name='Test family', | ||||
|             description='', | ||||
|         ) | ||||
|  | ||||
|         self.challenge = Challenge.objects.create( | ||||
|             name='Test challenge', | ||||
|             description='', | ||||
|             points=100, | ||||
|         ) | ||||
|  | ||||
|         self.achievement = Achievement.objects.create( | ||||
|             family=self.family, | ||||
|             challenge=self.challenge, | ||||
|             valid=False, | ||||
|         ) | ||||
|  | ||||
|     def test_family_list(self): | ||||
|         """ | ||||
|         Test display family list | ||||
|         """ | ||||
|         response = self.client.get(reverse("family:family_list")) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
|     def test_family_create(self): | ||||
|         """ | ||||
|         Test create a family | ||||
|         """ | ||||
|         response = self.client.get(reverse("family:family_create")) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
|         response = self.client.post(reverse("family:family_create"), data={ | ||||
|             "name": "Family toto", | ||||
|             "description": "A test family", | ||||
|         }) | ||||
|         self.assertTrue(Family.objects.filter(name="Family toto").exists()) | ||||
|         self.assertRedirects(response, reverse("family:manage"), 302, 200) | ||||
|  | ||||
|     def test_family_detail(self): | ||||
|         """ | ||||
|         Test display the detail of a family | ||||
|         """ | ||||
|         response = self.client.get(reverse("family:family_detail", args=(self.family.pk,))) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
|     def test_family_update(self): | ||||
|         """ | ||||
|         Test update a family | ||||
|         """ | ||||
|         response = self.client.get(reverse("family:family_update", args=(self.family.pk,))) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
|         response = self.client.post(reverse("family:family_update", args=(self.family.pk,)), data=dict( | ||||
|             name="Toto family updated", | ||||
|             description="A larger description for the test family" | ||||
|         )) | ||||
|         self.assertRedirects(response, self.family.get_absolute_url(), 302, 200) | ||||
|         self.assertTrue(Family.objects.filter(name="Toto family updated").exists()) | ||||
|  | ||||
|     def test_family_update_picture(self): | ||||
|         """ | ||||
|         Test update the picture of a family | ||||
|         """ | ||||
|         response = self.client.get(reverse("family:update_pic", args=(self.family.pk,))) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
|         old_pic = self.family.display_image | ||||
|  | ||||
|         with open("apps/family/static/family/img/default_picture.png", "rb") as f: | ||||
|             image = SimpleUploadedFile("image.png", f.read(), "image/png") | ||||
|             response = self.client.post(reverse("family:update_pic", args=(self.family.pk,)), dict( | ||||
|                 image=image, | ||||
|                 x=0, | ||||
|                 y=0, | ||||
|                 width=200, | ||||
|                 height=200, | ||||
|             )) | ||||
|             self.assertRedirects(response, self.family.get_absolute_url(), 302, 200) | ||||
|  | ||||
|         self.family.refresh_from_db() | ||||
|         self.assertTrue(os.path.exists(self.family.display_image.path)) | ||||
|         os.remove(self.family.display_image.path) | ||||
|  | ||||
|         self.family.display_image = old_pic | ||||
|         self.family.save() | ||||
|  | ||||
|     def test_family_add_member(self): | ||||
|         """ | ||||
|         Test add memberships to a family | ||||
|         """ | ||||
|         response = self.client.get(reverse("family:family_add_member", args=(self.family.pk,))) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
|         user = User.objects.create(username="totototo") | ||||
|         user.profile.registration_valid = True | ||||
|         user.profile.email_confirmed = True | ||||
|         user.profile.save() | ||||
|         user.save() | ||||
|  | ||||
|         response = self.client.post(reverse("family:family_add_member", args=(self.family.pk,)), data=dict( | ||||
|             user=user.pk, | ||||
|         )) | ||||
|         self.assertRedirects(response, self.family.get_absolute_url(), 302, 200) | ||||
|  | ||||
|         self.assertTrue(FamilyMembership.objects.filter(user=user, family=self.family, year=timezone.now().year).exists()) | ||||
|  | ||||
|     def test_challenge_list(self): | ||||
|         """ | ||||
|         Test display challenge list | ||||
|         """ | ||||
|         response = self.client.get(reverse('family:challenge_list')) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
|     def test_challenge_create(self): | ||||
|         """ | ||||
|         Test create a challenge | ||||
|         """ | ||||
|         response = self.client.get(reverse("family:challenge_create")) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
|         response = self.client.post(reverse("family:challenge_create"), data={ | ||||
|             "name": "Challenge for toto", | ||||
|             "description": "A test challenge", | ||||
|             "points": 50, | ||||
|         }) | ||||
|         self.assertTrue(Challenge.objects.filter(name="Challenge for toto").exists()) | ||||
|         self.assertRedirects(response, reverse("family:manage"), 302, 200) | ||||
|  | ||||
|     def test_challenge_detail(self): | ||||
|         """ | ||||
|         Test display the detail of a challenge | ||||
|         """ | ||||
|         response = self.client.get(reverse("family:challenge_detail", args=(self.challenge.pk,))) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
|     def test_challenge_update(self): | ||||
|         """ | ||||
|         Test update a challenge | ||||
|         """ | ||||
|         response = self.client.get(reverse("family:challenge_update", args=(self.challenge.pk,))) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
|         response = self.client.post(reverse("family:challenge_update", args=(self.challenge.pk,)), data=dict( | ||||
|             name="Challenge updated", | ||||
|             description="Another description", | ||||
|             points=10, | ||||
|         )) | ||||
|         self.assertRedirects(response, self.challenge.get_absolute_url(), 302, 200) | ||||
|         self.assertTrue(Challenge.objects.filter(name="Challenge updated").exists()) | ||||
|  | ||||
|     def test_render_manage_page(self): | ||||
|         """ | ||||
|         Test render manage page | ||||
|         """ | ||||
|         response = self.client.get(reverse("family:manage")) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
|     def test_validate_achievement(self): | ||||
|         """ | ||||
|         Test validate an achievement | ||||
|         """ | ||||
|         old_family_score = self.family.score | ||||
|  | ||||
|         response = self.client.get(reverse("family:achievement_validate", args=(self.achievement.pk,))) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
|         response = self.client.post(reverse("family:achievement_validate", args=(self.achievement.pk,))) | ||||
|         self.assertRedirects(response, reverse("family:achievement_list"), 302, 200) | ||||
|  | ||||
|         self.achievement.refresh_from_db() | ||||
|         self.assertIs(self.achievement.valid, True) | ||||
|  | ||||
|         self.family.refresh_from_db() | ||||
|         self.assertEqual(self.family.score, old_family_score + self.achievement.challenge.points) | ||||
|  | ||||
|     def test_delete_achievement(self): | ||||
|         """ | ||||
|         Test delete an achievement | ||||
|         """ | ||||
|         response = self.client.get(reverse("family:achievement_delete", args=(self.achievement.pk,))) | ||||
|         self.assertEqual(response.status_code, 200) | ||||
|  | ||||
|         response = self.client.delete(reverse("family:achievement_delete", args=(self.achievement.pk,))) | ||||
|         self.assertRedirects(response, reverse("family:achievement_list"), 302, 200) | ||||
|         self.assertFalse(Achievement.objects.filter(pk=self.achievement.pk).exists()) | ||||
|  | ||||
|  | ||||
| class TestBatchAchievements(APITestCase): | ||||
|     def setUp(self): | ||||
|         self.user = User.objects.create_superuser( | ||||
|             username='admintoto', | ||||
|             password='toto1234', | ||||
|             email='toto@example.com', | ||||
|         ) | ||||
|         self.client.force_login(self.user) | ||||
|  | ||||
|         sess = self.client.session | ||||
|         sess['permission_mask'] = 42 | ||||
|         sess.save() | ||||
|  | ||||
|         self.families = [ | ||||
|             Family.objects.create(name=f'Famille {i}', description='') for i in range(2) | ||||
|         ] | ||||
|         self.challenges = [ | ||||
|             Challenge.objects.create(name=f'Challenge {i}', description='', points=50) for i in range(3) | ||||
|         ] | ||||
|  | ||||
|         self.achievement = Achievement.objects.create( | ||||
|             family=self.families[0], | ||||
|             challenge=self.challenges[0], | ||||
|             valid=False, | ||||
|         ) | ||||
|  | ||||
|         self.url = reverse("family:api:batch_achievements") | ||||
|  | ||||
|     def test_batch_achievement_creation(self): | ||||
|         family_ids = [f.id for f in self.families] | ||||
|         challenge_ids = [c.id for c in self.challenges] | ||||
|         response = self.client.post( | ||||
|             self.url, | ||||
|             data={ | ||||
|                 'families': family_ids, | ||||
|                 'challenges': challenge_ids | ||||
|             }, | ||||
|             format='json' | ||||
|         ) | ||||
|  | ||||
|         self.assertEqual(response.status_code, 201) | ||||
|         for result in response.data['results']: | ||||
|             if result['family'] == self.families[0].name and result['challenge'] == self.challenges[0].name: | ||||
|                 self.assertEqual(result['status'], 'existed') | ||||
|             else: | ||||
|                 self.assertEqual(result['status'], 'created') | ||||
|  | ||||
|         expected_count = len(family_ids) * len(challenge_ids) | ||||
|         self.assertEqual(Achievement.objects.count(), expected_count) | ||||
|  | ||||
|         # Check that correct couples family/challenge exist | ||||
|         for f in self.families: | ||||
|             for c in self.challenges: | ||||
|                 self.assertTrue( | ||||
|                     Achievement.objects.filter(family=f, challenge=c).exists() | ||||
|                 ) | ||||
|  | ||||
|  | ||||
| class TestFamilyAPI(TestAPI): | ||||
|     def setUp(self): | ||||
|         super().setUp() | ||||
|  | ||||
|         self.family = Family.objects.create( | ||||
|             name='Test family', | ||||
|             description='', | ||||
|         ) | ||||
|  | ||||
|         self.familymembership = FamilyMembership.objects.create( | ||||
|             user=self.user, | ||||
|             family=self.family, | ||||
|         ) | ||||
|  | ||||
|         self.challenge = Challenge.objects.create( | ||||
|             name='Test challenge', | ||||
|             description='', | ||||
|             points=100, | ||||
|         ) | ||||
|  | ||||
|         self.achievement = Achievement.objects.create( | ||||
|             family=self.family, | ||||
|             challenge=self.challenge, | ||||
|             valid=False, | ||||
|         ) | ||||
|  | ||||
|     def test_family_api(self): | ||||
|         """ | ||||
|         Load Family API page and test all filters and permissions | ||||
|         """ | ||||
|         self.check_viewset(FamilyViewSet, '/api/family/family/') | ||||
|  | ||||
|     def test_familymembership_api(self): | ||||
|         """ | ||||
|         Load FamilyMembership API page and test all filters and permissions | ||||
|         """ | ||||
|         self.check_viewset(FamilyMembershipViewSet, '/api/family/familymembership/') | ||||
|  | ||||
|     def test_challenge_api(self): | ||||
|         """ | ||||
|         Load Challenge API page and test all filters and permissions | ||||
|         """ | ||||
|         self.check_viewset(ChallengeViewSet, '/api/family/challenge/') | ||||
|  | ||||
|     def test_achievement_api(self): | ||||
|         """ | ||||
|         Load Achievement API page and test all filters and permissions | ||||
|         """ | ||||
|         self.check_viewset(AchievementViewSet, '/api/family/achievement/') | ||||
							
								
								
									
										25
									
								
								apps/family/urls.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										25
									
								
								apps/family/urls.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,25 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from django.urls import path, include | ||||
|  | ||||
| from . import views | ||||
|  | ||||
| app_name = 'family' | ||||
| urlpatterns = [ | ||||
|     path('list/', views.FamilyListView.as_view(), name="family_list"), | ||||
|     path('create/', views.FamilyCreateView.as_view(), name="family_create"), | ||||
|     path('<int:pk>/detail/', views.FamilyDetailView.as_view(), name="family_detail"), | ||||
|     path('<int:pk>/update/', views.FamilyUpdateView.as_view(), name="family_update"), | ||||
|     path('<int:pk>/update_pic/', views.FamilyPictureUpdateView.as_view(), name="update_pic"), | ||||
|     path('<int:family_pk>/add_member/', views.FamilyAddMemberView.as_view(), name="family_add_member"), | ||||
|     path('challenge/list/', views.ChallengeListView.as_view(), name="challenge_list"), | ||||
|     path('challenge/create/', views.ChallengeCreateView.as_view(), name="challenge_create"), | ||||
|     path('challenge/<int:pk>/detail/', views.ChallengeDetailView.as_view(), name="challenge_detail"), | ||||
|     path('challenge/<int:pk>/update/', views.ChallengeUpdateView.as_view(), name="challenge_update"), | ||||
|     path('manage/', views.FamilyManageView.as_view(), name="manage"), | ||||
|     path('achievement/list/', views.AchievementListView.as_view(), name="achievement_list"), | ||||
|     path('achievement/<int:pk>/validate/', views.AchievementValidateView.as_view(), name="achievement_validate"), | ||||
|     path('achievement/<int:pk>/delete/', views.AchievementDeleteView.as_view(), name="achievement_delete"), | ||||
|     path('api/family/', include(('family.api.urls', 'family_api'), namespace='api')), | ||||
| ] | ||||
							
								
								
									
										469
									
								
								apps/family/views.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										469
									
								
								apps/family/views.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,469 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from datetime import date | ||||
|  | ||||
| from django.conf import settings | ||||
| from django.shortcuts import redirect | ||||
| from django.contrib.auth.mixins import LoginRequiredMixin | ||||
| from django.core.exceptions import PermissionDenied | ||||
| from django.db import transaction | ||||
| from django.views.generic import DetailView, UpdateView, ListView | ||||
| from django.views.generic.edit import DeleteView, FormMixin | ||||
| from django.views.generic.base import TemplateView | ||||
| from django.utils.translation import gettext_lazy as _ | ||||
| from django_tables2 import SingleTableView, MultiTableMixin | ||||
| from permission.backends import PermissionBackend | ||||
| from permission.views import ProtectQuerysetMixin, ProtectedCreateView | ||||
| from django.urls import reverse_lazy | ||||
| from member.forms import ImageForm | ||||
| import phonenumbers | ||||
|  | ||||
| from .models import Family, Challenge, FamilyMembership, User, Achievement | ||||
| from .tables import FamilyTable, ChallengeTable, FamilyMembershipTable, AchievementTable, FamilyAchievementTable | ||||
| from .forms import ChallengeForm, FamilyMembershipForm, FamilyForm | ||||
|  | ||||
|  | ||||
| class FamilyCreateView(ProtectQuerysetMixin, ProtectedCreateView): | ||||
|     """ | ||||
|     Create family | ||||
|     """ | ||||
|     model = Family | ||||
|     extra_context = {"title": _('Create family')} | ||||
|     form_class = FamilyForm | ||||
|  | ||||
|     def get_sample_object(self): | ||||
|         return Family( | ||||
|             name="", | ||||
|             description="Sample family", | ||||
|             score=0, | ||||
|             rank=0, | ||||
|         ) | ||||
|  | ||||
|     def get_success_url(self): | ||||
|         self.object.refresh_from_db() | ||||
|         return reverse_lazy("family:manage") | ||||
|  | ||||
|  | ||||
| class FamilyListView(ProtectQuerysetMixin, LoginRequiredMixin, SingleTableView): | ||||
|     """ | ||||
|     List existing Families | ||||
|     """ | ||||
|     model = Family | ||||
|     table_class = FamilyTable | ||||
|     extra_context = {"title": _('Families list')} | ||||
|  | ||||
|     def get_context_data(self, **kwargs): | ||||
|         context = super().get_context_data(**kwargs) | ||||
|  | ||||
|         fake_family = Family(name="", description="") | ||||
|         fake_challenge = Challenge(name="", description="", points=0) | ||||
|         can_add_family = PermissionBackend.check_perm(self.request, "family.add_family", fake_family) | ||||
|         can_add_challenge = PermissionBackend.check_perm(self.request, "family.add_challenge", fake_challenge) | ||||
|  | ||||
|         if Family.objects.exists() and Challenge.objects.exists(): | ||||
|             fake_achievement = Achievement(family=Family.objects.first(), challenge=Challenge.objects.first(), valid=False) | ||||
|             can_add_achievement = PermissionBackend.check_perm(self.request, "family.add_achievement", fake_achievement) | ||||
|         else: | ||||
|             can_add_achievement = False | ||||
|  | ||||
|         context["can_manage"] = can_add_family or can_add_challenge or can_add_achievement | ||||
|  | ||||
|         return context | ||||
|  | ||||
|  | ||||
| class FamilyDetailView(ProtectQuerysetMixin, LoginRequiredMixin, DetailView): | ||||
|     """ | ||||
|     Display details of a family | ||||
|     """ | ||||
|     model = Family | ||||
|     context_object_name = "family" | ||||
|     extra_context = {"title": _('Family detail')} | ||||
|  | ||||
|     def get_context_data(self, **kwargs): | ||||
|         """ | ||||
|         Add members list | ||||
|         """ | ||||
|         context = super().get_context_data(**kwargs) | ||||
|  | ||||
|         family = self.object | ||||
|  | ||||
|         # member list | ||||
|         family_member = FamilyMembership.objects.filter( | ||||
|             family=family, | ||||
|             year=date.today().year, | ||||
|         ).filter(PermissionBackend.filter_queryset(self.request, FamilyMembership, "view"))\ | ||||
|             .order_by("user__username") | ||||
|         family_member = family_member.distinct("user__username")\ | ||||
|             if settings.DATABASES["default"]["ENGINE"] == 'django.db.backends.postgresql' else family_member | ||||
|  | ||||
|         membership_table = FamilyMembershipTable(data=family_member, prefix="membership-") | ||||
|         membership_table.paginate(per_page=5, page=self.request.GET.get('membership-page', 1)) | ||||
|         context['member_list'] = membership_table | ||||
|  | ||||
|         # Check if the user has the right to create a membership, to display the button. | ||||
|         empty_membership = FamilyMembership( | ||||
|             family=family, | ||||
|             user=User.objects.first(), | ||||
|             year=date.today().year, | ||||
|         ) | ||||
|         context["can_add_members"] = PermissionBackend()\ | ||||
|             .has_perm(self.request.user, "family.add_membership", empty_membership) | ||||
|  | ||||
|         # Défis réalisé par la famille | ||||
|         achievements = Achievement.objects.filter(family=family) | ||||
|         achievements_table = FamilyAchievementTable(data=achievements, prefix="achievement-") | ||||
|         achievements_table.paginate(per_page=5, page=self.request.GET.get('achievement-page', 1)) | ||||
|         context["achievement_list"] = achievements_table | ||||
|  | ||||
|         return context | ||||
|  | ||||
|  | ||||
| class FamilyUpdateView(ProtectQuerysetMixin, LoginRequiredMixin, UpdateView): | ||||
|     """ | ||||
|     Update the information of a family. | ||||
|     """ | ||||
|     model = Family | ||||
|     context_object_name = "family" | ||||
|     form_class = FamilyForm | ||||
|     extra_context = {"title": _('Update family')} | ||||
|  | ||||
|     def get_success_url(self): | ||||
|         return reverse_lazy('family:family_detail', kwargs={'pk': self.object.pk}) | ||||
|  | ||||
|  | ||||
| class FamilyPictureUpdateView(ProtectQuerysetMixin, LoginRequiredMixin, FormMixin, DetailView): | ||||
|     """ | ||||
|     Update profile picture of the family | ||||
|     """ | ||||
|     model = Family | ||||
|     extra_context = {"title": _("Update family picture")} | ||||
|     template_name = 'family/picture_update.html' | ||||
|     form_class = ImageForm | ||||
|  | ||||
|     def get_context_data(self, **kwargs): | ||||
|         context = super().get_context_data(**kwargs) | ||||
|         context['form'] = self.form_class(self.request.POST, self.request.FILES) | ||||
|         return context | ||||
|  | ||||
|     def get_success_url(self): | ||||
|         """Redirect to family page after upload""" | ||||
|         return reverse_lazy('family:family_detail', kwargs={'pk': self.object.pk}) | ||||
|  | ||||
|     def post(self, request, *args, **kwargs): | ||||
|         form = self.get_form() | ||||
|         self.object = self.get_object() | ||||
|         return self.form_valid(form) if form.is_valid() else self.form_invalid(form) | ||||
|  | ||||
|     @transaction.atomic | ||||
|     def form_valid(self, form): | ||||
|         """ | ||||
|         Save the image | ||||
|         """ | ||||
|         image = form.cleaned_data['image'] | ||||
|  | ||||
|         if image is None: | ||||
|             image = "pic/default.png" | ||||
|         else: | ||||
|             # Rename as PNG or GIF | ||||
|             extension = image.name.split(".")[-1] | ||||
|             if extension == "gif": | ||||
|                 image.name = "{}_pic.gif".format(self.object.pk) | ||||
|             else: | ||||
|                 image.name = "{}_pic.png".format(self.object.pk) | ||||
|  | ||||
|         # Save | ||||
|         self.object.display_image = image | ||||
|         self.object.save() | ||||
|         return super().form_valid(form) | ||||
|  | ||||
|  | ||||
| class FamilyAddMemberView(ProtectQuerysetMixin, ProtectedCreateView): | ||||
|     """ | ||||
|     Add a membership to a family | ||||
|     """ | ||||
|     model = FamilyMembership | ||||
|     form_class = FamilyMembershipForm | ||||
|     template_name = 'family/add_member.html' | ||||
|     extra_context = {"title": _("Add a new member to the family")} | ||||
|  | ||||
|     def get_sample_object(self): | ||||
|         if "family_pk" in self.kwargs: | ||||
|             family = Family.objects.get(pk=self.kwargs["family_pk"]) | ||||
|         else: | ||||
|             family = FamilyMembership.objects.get(pk=self.kwargs["pk"]).family | ||||
|         return FamilyMembership( | ||||
|             user=self.request.user, | ||||
|             family=family, | ||||
|             year=date.today().year, | ||||
|         ) | ||||
|  | ||||
|     def get_context_data(self, **kwargs): | ||||
|         context = super().get_context_data(**kwargs) | ||||
|  | ||||
|         family = Family.objects.filter(PermissionBackend.filter_queryset(self.request, Family, "view"))\ | ||||
|             .get(pk=self.kwargs['family_pk']) | ||||
|  | ||||
|         context['family'] = family | ||||
|  | ||||
|         return context | ||||
|  | ||||
|     @transaction.atomic | ||||
|     def form_valid(self, form): | ||||
|         """ | ||||
|         Create family membership, check that everythinf is good | ||||
|         """ | ||||
|         family = Family.objects.filter(PermissionBackend.filter_queryset(self.request, Family, "view")) \ | ||||
|             .get(pk=self.kwargs["family_pk"]) | ||||
|  | ||||
|         form.instance.family = family | ||||
|  | ||||
|         return super().form_valid(form) | ||||
|  | ||||
|     def get_success_url(self): | ||||
|         return reverse_lazy('family:family_detail', kwargs={'pk': self.object.family.id}) | ||||
|  | ||||
|  | ||||
| class ChallengeCreateView(ProtectQuerysetMixin, ProtectedCreateView): | ||||
|     """ | ||||
|     Create challenge | ||||
|     """ | ||||
|     model = Challenge | ||||
|     extra_context = {"title": _('Create challenge')} | ||||
|     form_class = ChallengeForm | ||||
|  | ||||
|     def get_sample_object(self): | ||||
|         return Challenge( | ||||
|             name="", | ||||
|             description="Sample challenge", | ||||
|             points=0, | ||||
|         ) | ||||
|  | ||||
|     def get_success_url(self): | ||||
|         return reverse_lazy('family:manage') | ||||
|  | ||||
|  | ||||
| class ChallengeListView(ProtectQuerysetMixin, LoginRequiredMixin, SingleTableView): | ||||
|     """ | ||||
|     List all challenges | ||||
|     """ | ||||
|     model = Challenge | ||||
|     table_class = ChallengeTable | ||||
|     extra_context = {"title": _('Challenges list')} | ||||
|  | ||||
|     def get_context_data(self, **kwargs): | ||||
|         context = super().get_context_data(**kwargs) | ||||
|  | ||||
|         fake_family = Family(name="", description="") | ||||
|         fake_challenge = Challenge(name="", description="", points=0) | ||||
|         can_add_family = PermissionBackend.check_perm(self.request, "family.add_family", fake_family) | ||||
|         can_add_challenge = PermissionBackend.check_perm(self.request, "family.add_challenge", fake_challenge) | ||||
|  | ||||
|         if Family.objects.exists() and Challenge.objects.exists(): | ||||
|             fake_achievement = Achievement(family=Family.objects.first(), challenge=Challenge.objects.first(), valid=False) | ||||
|             can_add_achievement = PermissionBackend.check_perm(self.request, "family.add_achievement", fake_achievement) | ||||
|         else: | ||||
|             can_add_achievement = False | ||||
|  | ||||
|         context["can_manage"] = can_add_family or can_add_challenge or can_add_achievement | ||||
|  | ||||
|         return context | ||||
|  | ||||
|  | ||||
| class ChallengeDetailView(ProtectQuerysetMixin, LoginRequiredMixin, DetailView): | ||||
|     """ | ||||
|     Display details of a challenge | ||||
|     """ | ||||
|     model = Challenge | ||||
|     context_object_name = "challenge" | ||||
|     extra_context = {"title": _('Details of:')} | ||||
|  | ||||
|     def get_context_data(self, **kwargs): | ||||
|         context = super().get_context_data(**kwargs) | ||||
|         fields = ["name", "description", "points",] | ||||
|  | ||||
|         fields = dict([(field, getattr(self.object, field)) for field in fields]) | ||||
|  | ||||
|         context["fields"] = [( | ||||
|             Challenge._meta.get_field(field).verbose_name.capitalize(), | ||||
|             value) for field, value in fields.items()] | ||||
|         context["obtained"] = self.object.obtained | ||||
|         context["update"] = PermissionBackend.check_perm(self.request, "family.change_challenge") | ||||
|  | ||||
|         return context | ||||
|  | ||||
|  | ||||
| class ChallengeUpdateView(ProtectQuerysetMixin, LoginRequiredMixin, UpdateView): | ||||
|     """ | ||||
|     Update the information of a challenge | ||||
|     """ | ||||
|     model = Challenge | ||||
|     context_object_name = "challenge" | ||||
|     extra_context = {"title": _('Update challenge')} | ||||
|     form_class = ChallengeForm | ||||
|  | ||||
|     def get_success_url(self, **kwargs): | ||||
|         self.object.refresh_from_db() | ||||
|         return reverse_lazy('family:challenge_detail', kwargs={'pk': self.object.pk}) | ||||
|  | ||||
|  | ||||
| class FamilyManageView(ProtectQuerysetMixin, LoginRequiredMixin, SingleTableView): | ||||
|     """ | ||||
|     Manage families and challenges | ||||
|     """ | ||||
|     model = Achievement | ||||
|     template_name = 'family/manage.html' | ||||
|     table_class = AchievementTable | ||||
|     extra_context = {'title': _('Manage families and challenges')} | ||||
|  | ||||
|     def dispatch(self, request, *args, **kwargs): | ||||
|         # Check that the user is authenticated | ||||
|         if not request.user.is_authenticated: | ||||
|             return self.handle_no_permission() | ||||
|  | ||||
|         perm = PermissionBackend.has_model_perm(self.request, Achievement(), "add") | ||||
|         perm = perm or PermissionBackend.has_model_perm(self.request, Challenge(), "add") | ||||
|         perm = perm or PermissionBackend.has_model_perm(self.request, Family(), "add") | ||||
|         if not perm: | ||||
|             raise PermissionDenied(_("You are not able to manage families and challenges.")) | ||||
|         return super().dispatch(request, *args, **kwargs) | ||||
|  | ||||
|     def get_queryset(self, **kwargs): | ||||
|         # retrieves only Transaction that user has the right to see. | ||||
|         return Achievement.objects.filter( | ||||
|             PermissionBackend.filter_queryset(self.request, Achievement, "view") | ||||
|         ).order_by("-obtained_at").all() | ||||
|  | ||||
|     def get_context_data(self, **kwargs): | ||||
|         context = super().get_context_data(**kwargs) | ||||
|  | ||||
|         context['all_challenges'] = Challenge.objects.filter( | ||||
|             PermissionBackend.filter_queryset(self.request, Challenge, "view") | ||||
|         ).order_by('name') | ||||
|  | ||||
|         context["can_add_family"] = PermissionBackend.has_model_perm(self.request, Family(), "add") | ||||
|         context["can_add_challenge"] = PermissionBackend.has_model_perm(self.request, Challenge(), "add") | ||||
|         context["can_add_achievement"] = PermissionBackend.has_model_perm(self.request, Achievement(), "add") | ||||
|  | ||||
|         # Get the user's family if they have one | ||||
|         try: | ||||
|             user_family_membership = FamilyMembership.objects.get(user=self.request.user) | ||||
|             context["user_family"] = user_family_membership.family | ||||
|         except FamilyMembership.DoesNotExist: | ||||
|             context["user_family"] = None | ||||
|  | ||||
|         phone_numbers = [ | ||||
|             u.profile.phone_number for u in User.objects.filter( | ||||
|                 memberships__roles__id=35, | ||||
|                 memberships__date_end__gte=date.today(), | ||||
|                 profile__phone_number__isnull=False | ||||
|             ).distinct() | ||||
|         ] | ||||
|         formatted_phone_numbers = [phonenumbers.format_number(num, phonenumbers.PhoneNumberFormat.INTERNATIONAL) for num in phone_numbers if num] | ||||
|         context["phone_numbers"] = formatted_phone_numbers | ||||
|  | ||||
|         return context | ||||
|  | ||||
|     def get_table(self, **kwargs): | ||||
|         table = super().get_table(**kwargs) | ||||
|         table.exclude = ('delete', 'validate',) | ||||
|         table.orderable = False | ||||
|         return table | ||||
|  | ||||
|     def get_table_data(self, **kwargs): | ||||
|         qs = super().get_queryset(**kwargs) | ||||
|  | ||||
|         qs = qs.filter(PermissionBackend.filter_queryset(self.request, Achievement, "view")) | ||||
|  | ||||
|         return qs | ||||
|  | ||||
|  | ||||
| class AchievementListView(ProtectQuerysetMixin, LoginRequiredMixin, MultiTableMixin, ListView): | ||||
|     """ | ||||
|     List all achievements | ||||
|     """ | ||||
|     model = Achievement | ||||
|     tables = [AchievementTable, AchievementTable, ] | ||||
|     extra_context = {'title': _('Achievement list')} | ||||
|  | ||||
|     def dispatch(self, request, *args, **kwargs): | ||||
|         if not request.user.is_authenticated: | ||||
|             return self.handle_no_permission() | ||||
|  | ||||
|         if not PermissionBackend.has_model_perm(self.request, Achievement(), "change"): | ||||
|             raise PermissionDenied(_("You are not able to see the achievement validation interface.")) | ||||
|         return super().dispatch(request, *args, **kwargs) | ||||
|  | ||||
|     def get_tables(self, **kwargs): | ||||
|         tables = super().get_tables(**kwargs) | ||||
|  | ||||
|         tables[0].prefix = 'invalid-' | ||||
|         tables[1].prefix = 'valid-' | ||||
|         tables[1].exclude = ('validate', 'delete',) | ||||
|  | ||||
|         return tables | ||||
|  | ||||
|     def get_tables_data(self): | ||||
|         table_valid = self.get_queryset().filter(valid=True) | ||||
|         table_invalid = self.get_queryset().filter(valid=False) | ||||
|         return [table_invalid, table_valid, ] | ||||
|  | ||||
|     def get_context_data(self, **kwargs): | ||||
|         context = super().get_context_data(**kwargs) | ||||
|  | ||||
|         tables = context['tables'] | ||||
|  | ||||
|         context['invalid'] = tables[0] | ||||
|         context['valid'] = tables[1] | ||||
|         return context | ||||
|  | ||||
|  | ||||
| class AchievementValidateView(ProtectQuerysetMixin, LoginRequiredMixin, TemplateView): | ||||
|     """ | ||||
|     Validate an achievement obtained by a family | ||||
|     """ | ||||
|     template_name = 'family/achievement_confirm_validate.html' | ||||
|  | ||||
|     def dispatch(self, request, *args, **kwargs): | ||||
|         if not request.user.is_authenticated: | ||||
|             return self.handle_no_permission() | ||||
|  | ||||
|         fake_achievement = Achievement( | ||||
|             family=Family.objects.first(), | ||||
|             challenge=Challenge.objects.first(), | ||||
|             valid=False, | ||||
|         ) | ||||
|         if not PermissionBackend.check_perm(self.request, "family.change_achievement_valid", fake_achievement): | ||||
|             raise PermissionDenied() | ||||
|         return super().dispatch(request, *args, **kwargs) | ||||
|  | ||||
|     def post(self, request, pk): | ||||
|         achievement = Achievement.objects.get(pk=pk) | ||||
|  | ||||
|         achievement.valid = True | ||||
|         achievement.save() | ||||
|  | ||||
|         return redirect(reverse_lazy('family:achievement_list')) | ||||
|  | ||||
|  | ||||
| class AchievementDeleteView(ProtectQuerysetMixin, LoginRequiredMixin, DeleteView): | ||||
|     """ | ||||
|     Delete an Achievement | ||||
|     """ | ||||
|     model = Achievement | ||||
|  | ||||
|     def dispatch(self, request, *args, **kwargs): | ||||
|         if not request.user.is_authenticated: | ||||
|             return self.handle_no_permission() | ||||
|  | ||||
|         fake_achievement = Achievement( | ||||
|             family=Family.objects.first(), | ||||
|             challenge=Challenge.objects.first(), | ||||
|             valid=False, | ||||
|         ) | ||||
|         if not PermissionBackend.check_perm(self.request, "family.change_achievement_valid", fake_achievement): | ||||
|             raise PermissionDenied() | ||||
|         return super().dispatch(request, *args, **kwargs) | ||||
|  | ||||
|     def get_success_url(self): | ||||
|         return reverse_lazy('family:achievement_list') | ||||
							
								
								
									
										0
									
								
								apps/food/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										0
									
								
								apps/food/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
								
								
									
										59
									
								
								apps/food/admin.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										59
									
								
								apps/food/admin.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,59 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from django.contrib import admin | ||||
| from polymorphic.admin import PolymorphicChildModelAdmin, PolymorphicParentModelAdmin | ||||
| from note_kfet.admin import admin_site | ||||
|  | ||||
| from .models import Allergen, Food, BasicFood, TransformedFood, QRCode | ||||
|  | ||||
|  | ||||
| @admin.register(Allergen, site=admin_site) | ||||
| class AllergenAdmin(admin.ModelAdmin): | ||||
|     """ | ||||
|     Admin customisation for Allergen | ||||
|     """ | ||||
|     ordering = ['name'] | ||||
|  | ||||
|  | ||||
| @admin.register(Food, site=admin_site) | ||||
| class FoodAdmin(PolymorphicParentModelAdmin): | ||||
|     """ | ||||
|     Admin customisation for Food | ||||
|     """ | ||||
|     child_models = (Food, BasicFood, TransformedFood) | ||||
|     list_display = ('name', 'expiry_date', 'owner', 'is_ready') | ||||
|     list_filter = ('is_ready', 'end_of_life') | ||||
|     search_fields = ['name'] | ||||
|     ordering = ['expiry_date', 'name'] | ||||
|  | ||||
|  | ||||
| @admin.register(BasicFood, site=admin_site) | ||||
| class BasicFood(PolymorphicChildModelAdmin): | ||||
|     """ | ||||
|     Admin customisation for BasicFood | ||||
|     """ | ||||
|     list_display = ('name', 'expiry_date', 'date_type', 'owner', 'is_ready') | ||||
|     list_filter = ('is_ready', 'date_type', 'end_of_life') | ||||
|     search_fields = ['name'] | ||||
|     ordering = ['expiry_date', 'name'] | ||||
|  | ||||
|  | ||||
| @admin.register(TransformedFood, site=admin_site) | ||||
| class TransformedFood(PolymorphicChildModelAdmin): | ||||
|     """ | ||||
|     Admin customisation for TransformedFood | ||||
|     """ | ||||
|     list_display = ('name', 'expiry_date', 'shelf_life', 'owner', 'is_ready') | ||||
|     list_filter = ('is_ready', 'end_of_life', 'shelf_life') | ||||
|     search_fields = ['name'] | ||||
|     ordering = ['expiry_date', 'name'] | ||||
|  | ||||
|  | ||||
| @admin.register(QRCode, site=admin_site) | ||||
| class QRCodeAdmin(admin.ModelAdmin): | ||||
|     """ | ||||
|     Admin customisation for QRCode | ||||
|     """ | ||||
|     list_diplay = ('qr_code_number', 'food_container') | ||||
|     search_fields = ['food_container__name'] | ||||
							
								
								
									
										0
									
								
								apps/food/api/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										0
									
								
								apps/food/api/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
								
								
									
										56
									
								
								apps/food/api/serializers.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										56
									
								
								apps/food/api/serializers.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,56 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from rest_framework import serializers | ||||
|  | ||||
| from ..models import Allergen, Food, BasicFood, TransformedFood, QRCode | ||||
|  | ||||
|  | ||||
| class AllergenSerializer(serializers.ModelSerializer): | ||||
|     """ | ||||
|     REST API Serializer for Allergen. | ||||
|     The djangorestframework plugin will analyse the model `Allergen` and parse all fields in the API. | ||||
|     """ | ||||
|     class Meta: | ||||
|         model = Allergen | ||||
|         fields = '__all__' | ||||
|  | ||||
|  | ||||
| class FoodSerializer(serializers.ModelSerializer): | ||||
|     """ | ||||
|     REST API Serializer for Food. | ||||
|     The djangorestframework plugin will analyse the model `Food` and parse all fields in the API. | ||||
|     """ | ||||
|     class Meta: | ||||
|         model = Food | ||||
|         fields = '__all__' | ||||
|  | ||||
|  | ||||
| class BasicFoodSerializer(serializers.ModelSerializer): | ||||
|     """ | ||||
|     REST API Serializer for BasicFood. | ||||
|     The djangorestframework plugin will analyse the model `BasicFood` and parse all fields in the API. | ||||
|     """ | ||||
|     class Meta: | ||||
|         model = BasicFood | ||||
|         fields = '__all__' | ||||
|  | ||||
|  | ||||
| class TransformedFoodSerializer(serializers.ModelSerializer): | ||||
|     """ | ||||
|     REST API Serializer for TransformedFood. | ||||
|     The djangorestframework plugin will analyse the model `TransformedFood` and parse all fields in the API. | ||||
|     """ | ||||
|     class Meta: | ||||
|         model = TransformedFood | ||||
|         fields = '__all__' | ||||
|  | ||||
|  | ||||
| class QRCodeSerializer(serializers.ModelSerializer): | ||||
|     """ | ||||
|     REST API Serializer for QRCode. | ||||
|     The djangorestframework plugin will analyse the model `QRCode` and parse all fields in the API. | ||||
|     """ | ||||
|     class Meta: | ||||
|         model = QRCode | ||||
|         fields = '__all__' | ||||
							
								
								
									
										15
									
								
								apps/food/api/urls.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										15
									
								
								apps/food/api/urls.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,15 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from .views import AllergenViewSet, FoodViewSet, BasicFoodViewSet, TransformedFoodViewSet, QRCodeViewSet | ||||
|  | ||||
|  | ||||
| def register_food_urls(router, path): | ||||
|     """ | ||||
|     Configure router for Food REST API. | ||||
|     """ | ||||
|     router.register(path + '/allergen', AllergenViewSet) | ||||
|     router.register(path + '/food', FoodViewSet) | ||||
|     router.register(path + '/basicfood', BasicFoodViewSet) | ||||
|     router.register(path + '/transformedfood', TransformedFoodViewSet) | ||||
|     router.register(path + '/qrcode', QRCodeViewSet) | ||||
							
								
								
									
										74
									
								
								apps/food/api/views.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										74
									
								
								apps/food/api/views.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,74 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from api.viewsets import ReadProtectedModelViewSet | ||||
| from django_filters.rest_framework import DjangoFilterBackend | ||||
| from rest_framework.filters import SearchFilter | ||||
|  | ||||
| from .serializers import AllergenSerializer, FoodSerializer, BasicFoodSerializer, TransformedFoodSerializer, QRCodeSerializer | ||||
| from ..models import Allergen, Food, BasicFood, TransformedFood, QRCode | ||||
|  | ||||
|  | ||||
| class AllergenViewSet(ReadProtectedModelViewSet): | ||||
|     """ | ||||
|     REST API View set. | ||||
|     The djangorestframework plugin will get all `Allergen` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/food/allergen/ | ||||
|     """ | ||||
|     queryset = Allergen.objects.order_by('id') | ||||
|     serializer_class = AllergenSerializer | ||||
|     filter_backends = [DjangoFilterBackend, SearchFilter] | ||||
|     filterset_fields = ['name', ] | ||||
|     search_fields = ['$name', ] | ||||
|  | ||||
|  | ||||
| class FoodViewSet(ReadProtectedModelViewSet): | ||||
|     """ | ||||
|     REST API View set. | ||||
|     The djangorestframework plugin will get all `Food` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/food/food/ | ||||
|     """ | ||||
|     queryset = Food.objects.order_by('id') | ||||
|     serializer_class = FoodSerializer | ||||
|     filter_backends = [DjangoFilterBackend, SearchFilter] | ||||
|     filterset_fields = ['name', ] | ||||
|     search_fields = ['$name', ] | ||||
|  | ||||
|  | ||||
| class BasicFoodViewSet(ReadProtectedModelViewSet): | ||||
|     """ | ||||
|     REST API View set. | ||||
|     The djangorestframework plugin will get all `BasicFood` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/food/basicfood/ | ||||
|     """ | ||||
|     queryset = BasicFood.objects.order_by('id') | ||||
|     serializer_class = BasicFoodSerializer | ||||
|     filter_backends = [DjangoFilterBackend, SearchFilter] | ||||
|     filterset_fields = ['name', ] | ||||
|     search_fields = ['$name', ] | ||||
|  | ||||
|  | ||||
| class TransformedFoodViewSet(ReadProtectedModelViewSet): | ||||
|     """ | ||||
|     REST API View set. | ||||
|     The djangorestframework plugin will get all `TransformedFood` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/food/transformedfood/ | ||||
|     """ | ||||
|     queryset = TransformedFood.objects.order_by('id') | ||||
|     serializer_class = TransformedFoodSerializer | ||||
|     filter_backends = [DjangoFilterBackend, SearchFilter] | ||||
|     filterset_fields = ['name', ] | ||||
|     search_fields = ['$name', ] | ||||
|  | ||||
|  | ||||
| class QRCodeViewSet(ReadProtectedModelViewSet): | ||||
|     """ | ||||
|     REST API View set. | ||||
|     The djangorestframework plugin will get all `QRCode` objects, serialize it to JSON with the given serializer, | ||||
|     then render it on /api/food/qrcode/ | ||||
|     """ | ||||
|     queryset = QRCode.objects.order_by('id') | ||||
|     serializer_class = QRCodeSerializer | ||||
|     filter_backends = [DjangoFilterBackend, SearchFilter] | ||||
|     filterset_fields = ['qr_code_number', ] | ||||
|     search_fields = ['$qr_code_number', ] | ||||
							
								
								
									
										11
									
								
								apps/food/apps.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										11
									
								
								apps/food/apps.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,11 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
|  | ||||
| from django.utils.translation import gettext_lazy as _ | ||||
| from django.apps import AppConfig | ||||
|  | ||||
|  | ||||
| class FoodkfetConfig(AppConfig): | ||||
|     name = 'food' | ||||
|     verbose_name = _('food') | ||||
							
								
								
									
										100
									
								
								apps/food/fixtures/initial.json
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										100
									
								
								apps/food/fixtures/initial.json
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,100 @@ | ||||
| [ | ||||
|     { | ||||
| 	"model": "food.allergen", | ||||
| 	"pk": 1, | ||||
| 	"fields": { | ||||
| 	    "name": "Lait" | ||||
| 	} | ||||
|     }, | ||||
|     { | ||||
| 	"model": "food.allergen", | ||||
| 	"pk": 2, | ||||
| 	"fields": { | ||||
| 	    "name": "Oeufs" | ||||
| 	} | ||||
|     }, | ||||
|     { | ||||
| 	"model": "food.allergen", | ||||
| 	"pk": 3, | ||||
| 	"fields": { | ||||
| 	    "name": "Gluten" | ||||
| 	} | ||||
|     }, | ||||
|     { | ||||
| 	"model": "food.allergen", | ||||
| 	"pk": 4, | ||||
| 	"fields": { | ||||
| 	    "name": "Fruits à coques" | ||||
| 	} | ||||
|     }, | ||||
|     { | ||||
| 	"model": "food.allergen", | ||||
| 	"pk": 5, | ||||
| 	"fields": { | ||||
| 	    "name": "Arachides" | ||||
| 	} | ||||
|     }, | ||||
|     { | ||||
| 	"model": "food.allergen", | ||||
| 	"pk": 6, | ||||
| 	"fields": { | ||||
| 	    "name": "Sésame" | ||||
| 	} | ||||
|     }, | ||||
|     { | ||||
| 	"model": "food.allergen", | ||||
| 	"pk": 7, | ||||
| 	"fields": { | ||||
| 	    "name": "Soja" | ||||
| 	} | ||||
|     }, | ||||
|     { | ||||
| 	"model": "food.allergen", | ||||
| 	"pk": 8, | ||||
| 	"fields": { | ||||
| 	    "name": "Céleri" | ||||
| 	} | ||||
|     }, | ||||
|     { | ||||
| 	"model": "food.allergen", | ||||
| 	"pk": 9, | ||||
| 	"fields": { | ||||
| 	    "name": "Lupin" | ||||
| 	} | ||||
|     }, | ||||
|     { | ||||
| 	"model": "food.allergen", | ||||
| 	"pk": 10, | ||||
| 	"fields": { | ||||
| 	    "name": "Moutarde" | ||||
| 	} | ||||
|     }, | ||||
|     { | ||||
| 	"model": "food.allergen", | ||||
| 	"pk": 11, | ||||
| 	"fields": { | ||||
| 	    "name": "Sulfites" | ||||
| 	} | ||||
|     }, | ||||
|     { | ||||
| 	"model": "food.allergen", | ||||
| 	"pk": 12, | ||||
| 	"fields": { | ||||
| 	    "name": "Crustacés" | ||||
| 	} | ||||
|     }, | ||||
|     { | ||||
| 	"model": "food.allergen", | ||||
| 	"pk": 13, | ||||
| 	"fields": { | ||||
| 	    "name": "Mollusques" | ||||
| 	} | ||||
|     }, | ||||
|     { | ||||
| 	"model": "food.allergen", | ||||
| 	"pk": 14, | ||||
| 	"fields": { | ||||
| 	    "name": "Poissons" | ||||
| 	} | ||||
|     } | ||||
| ] | ||||
							
								
								
									
										187
									
								
								apps/food/forms.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										187
									
								
								apps/food/forms.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,187 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from random import shuffle | ||||
|  | ||||
| from bootstrap_datepicker_plus.widgets import DateTimePickerInput | ||||
| from django import forms | ||||
| from django.forms.widgets import NumberInput | ||||
| from django.utils.translation import gettext_lazy as _ | ||||
| from member.models import Club | ||||
| from note_kfet.inputs import Autocomplete | ||||
| from note_kfet.middlewares import get_current_request | ||||
| from permission.backends import PermissionBackend | ||||
|  | ||||
| from .models import Food, BasicFood, TransformedFood, QRCode | ||||
|  | ||||
|  | ||||
| class QRCodeForms(forms.ModelForm): | ||||
|     """ | ||||
|     Form for create QRCode for container | ||||
|     """ | ||||
|     def __init__(self, *args, **kwargs): | ||||
|         super().__init__(*args, **kwargs) | ||||
|         self.fields['food_container'].queryset = self.fields['food_container'].queryset.filter( | ||||
|             end_of_life__isnull=True, | ||||
|             polymorphic_ctype__model='transformedfood', | ||||
|         ).filter(PermissionBackend.filter_queryset( | ||||
|             get_current_request(), | ||||
|             TransformedFood, | ||||
|             "view", | ||||
|         )) | ||||
|  | ||||
|     class Meta: | ||||
|         model = QRCode | ||||
|         fields = ('food_container',) | ||||
|  | ||||
|  | ||||
| class BasicFoodForms(forms.ModelForm): | ||||
|     """ | ||||
|     Form for add basicfood | ||||
|     """ | ||||
|     def __init__(self, *args, **kwargs): | ||||
|         super().__init__(*args, **kwargs) | ||||
|         self.fields['name'].widget.attrs.update({"autofocus": "autofocus"}) | ||||
|         self.fields['name'].required = True | ||||
|         self.fields['owner'].required = True | ||||
|  | ||||
|         # Some example | ||||
|         self.fields['name'].widget.attrs.update({"placeholder": _("Pasta METRO 5kg")}) | ||||
|         clubs = list(Club.objects.filter(PermissionBackend.filter_queryset(get_current_request(), Club, "change")).all()) | ||||
|         shuffle(clubs) | ||||
|         self.fields['owner'].widget.attrs["placeholder"] = ", ".join(club.name for club in clubs[:4]) + ", ..." | ||||
|         self.fields['order'].widget.attrs["placeholder"] = _("Specific order given to GCKs") | ||||
|  | ||||
|     class Meta: | ||||
|         model = BasicFood | ||||
|         fields = ('name', 'owner', 'date_type', 'expiry_date', 'allergens', 'order',) | ||||
|         widgets = { | ||||
|             "owner": Autocomplete( | ||||
|                 model=Club, | ||||
|                 attrs={"api_url": "/api/members/club/"}, | ||||
|             ), | ||||
|             "expiry_date": DateTimePickerInput(), | ||||
|         } | ||||
|  | ||||
|  | ||||
| class TransformedFoodForms(forms.ModelForm): | ||||
|     """ | ||||
|     Form for add transformedfood | ||||
|     """ | ||||
|     def __init__(self, *args, **kwargs): | ||||
|         super().__init__(*args, **kwargs) | ||||
|         self.fields['name'].required = True | ||||
|         self.fields['owner'].required = True | ||||
|  | ||||
|         # Some example | ||||
|         self.fields['name'].widget.attrs.update({"placeholder": _("Lasagna")}) | ||||
|         clubs = list(Club.objects.filter(PermissionBackend.filter_queryset(get_current_request(), Club, "change")).all()) | ||||
|         shuffle(clubs) | ||||
|         self.fields['owner'].widget.attrs["placeholder"] = ", ".join(club.name for club in clubs[:4]) + ", ..." | ||||
|         self.fields['order'].widget.attrs["placeholder"] = _("Specific order given to GCKs") | ||||
|  | ||||
|     class Meta: | ||||
|         model = TransformedFood | ||||
|         fields = ('name', 'owner', 'order',) | ||||
|         widgets = { | ||||
|             "owner": Autocomplete( | ||||
|                 model=Club, | ||||
|                 attrs={"api_url": "/api/members/club/"}, | ||||
|             ), | ||||
|         } | ||||
|  | ||||
|  | ||||
| class BasicFoodUpdateForms(forms.ModelForm): | ||||
|     """ | ||||
|     Form for update basicfood object | ||||
|     """ | ||||
|     class Meta: | ||||
|         model = BasicFood | ||||
|         fields = ('name', 'owner', 'date_type', 'expiry_date', 'end_of_life', 'is_ready', 'order', 'allergens') | ||||
|         widgets = { | ||||
|             "owner": Autocomplete( | ||||
|                 model=Club, | ||||
|                 attrs={"api_url": "/api/members/club/"}, | ||||
|             ), | ||||
|             "expiry_date": DateTimePickerInput(), | ||||
|         } | ||||
|  | ||||
|  | ||||
| class TransformedFoodUpdateForms(forms.ModelForm): | ||||
|     """ | ||||
|     Form for update transformedfood object | ||||
|     """ | ||||
|     def __init__(self, *args, **kwargs): | ||||
|         super().__init__(*args, **kwargs) | ||||
|         self.fields['shelf_life'].label = _('Shelf life (in hours)') | ||||
|  | ||||
|     class Meta: | ||||
|         model = TransformedFood | ||||
|         fields = ('name', 'owner', 'end_of_life', 'is_ready', 'order', 'shelf_life') | ||||
|         widgets = { | ||||
|             "owner": Autocomplete( | ||||
|                 model=Club, | ||||
|                 attrs={"api_url": "/api/members/club/"}, | ||||
|             ), | ||||
|             "expiry_date": DateTimePickerInput(), | ||||
|             "shelf_life": NumberInput(), | ||||
|         } | ||||
|  | ||||
|  | ||||
| class AddIngredientForms(forms.ModelForm): | ||||
|     """ | ||||
|     Form for add an ingredient | ||||
|     """ | ||||
|     fully_used = forms.BooleanField() | ||||
|     fully_used.initial = True | ||||
|     fully_used.required = False | ||||
|     fully_used.label = _("Fully used") | ||||
|  | ||||
|     def __init__(self, *args, **kwargs): | ||||
|         super().__init__(*args, **kwargs) | ||||
|         # TODO find a better way to get pk (be not url scheme dependant) | ||||
|         pk = get_current_request().path.split('/')[-1] | ||||
|         self.fields['ingredients'].queryset = self.fields['ingredients'].queryset.filter( | ||||
|             polymorphic_ctype__model="transformedfood", | ||||
|             is_ready=False, | ||||
|             end_of_life='', | ||||
|         ).filter(PermissionBackend.filter_queryset(get_current_request(), Food, "change")).exclude(pk=pk) | ||||
|  | ||||
|     class Meta: | ||||
|         model = TransformedFood | ||||
|         fields = ('ingredients',) | ||||
|  | ||||
|  | ||||
| class ManageIngredientsForm(forms.Form): | ||||
|     """ | ||||
|     Form to manage ingredient | ||||
|     """ | ||||
|     fully_used = forms.BooleanField() | ||||
|     fully_used.initial = True | ||||
|     fully_used.required = True | ||||
|     fully_used.label = _('Fully used') | ||||
|  | ||||
|     name = forms.CharField() | ||||
|     name.widget = Autocomplete( | ||||
|         model=Food, | ||||
|         resetable=True, | ||||
|         attrs={"api_url": "/api/food/food", | ||||
|                "class": "autocomplete"}, | ||||
|     ) | ||||
|     name.label = _('Name') | ||||
|  | ||||
|     qrcode = forms.IntegerField() | ||||
|     qrcode.widget = Autocomplete( | ||||
|         model=QRCode, | ||||
|         resetable=True, | ||||
|         attrs={"api_url": "/api/food/qrcode/", | ||||
|                "name_field": "qr_code_number", | ||||
|                "class": "autocomplete"}, | ||||
|     ) | ||||
|     qrcode.label = _('QR code number') | ||||
|  | ||||
|  | ||||
| ManageIngredientsFormSet = forms.formset_factory( | ||||
|     ManageIngredientsForm, | ||||
|     extra=1, | ||||
| ) | ||||
							
								
								
									
										199
									
								
								apps/food/migrations/0001_initial.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										199
									
								
								apps/food/migrations/0001_initial.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,199 @@ | ||||
| # Generated by Django 4.2.20 on 2025-04-17 21:43 | ||||
|  | ||||
| import datetime | ||||
| from django.db import migrations, models | ||||
| import django.db.models.deletion | ||||
| import django.utils.timezone | ||||
|  | ||||
|  | ||||
| class Migration(migrations.Migration): | ||||
|     initial = True | ||||
|  | ||||
|     dependencies = [ | ||||
|         ("contenttypes", "0002_remove_content_type_name"), | ||||
|         ("member", "0013_auto_20240801_1436"), | ||||
|     ] | ||||
|  | ||||
|     operations = [ | ||||
|         migrations.CreateModel( | ||||
|             name="Allergen", | ||||
|             fields=[ | ||||
|                 ( | ||||
|                     "id", | ||||
|                     models.AutoField( | ||||
|                         auto_created=True, | ||||
|                         primary_key=True, | ||||
|                         serialize=False, | ||||
|                         verbose_name="ID", | ||||
|                     ), | ||||
|                 ), | ||||
|                 ("name", models.CharField(max_length=255, verbose_name="name")), | ||||
|             ], | ||||
|             options={ | ||||
|                 "verbose_name": "Allergen", | ||||
|                 "verbose_name_plural": "Allergens", | ||||
|             }, | ||||
|         ), | ||||
|         migrations.CreateModel( | ||||
|             name="Food", | ||||
|             fields=[ | ||||
|                 ( | ||||
|                     "id", | ||||
|                     models.AutoField( | ||||
|                         auto_created=True, | ||||
|                         primary_key=True, | ||||
|                         serialize=False, | ||||
|                         verbose_name="ID", | ||||
|                     ), | ||||
|                 ), | ||||
|                 ("name", models.CharField(max_length=255, verbose_name="name")), | ||||
|                 ("expiry_date", models.DateTimeField(verbose_name="expiry date")), | ||||
|                 ( | ||||
|                     "end_of_life", | ||||
|                     models.CharField(max_length=255, verbose_name="end of life"), | ||||
|                 ), | ||||
|                 ( | ||||
|                     "is_ready", | ||||
|                     models.BooleanField(max_length=255, verbose_name="is ready"), | ||||
|                 ), | ||||
|                 ("order", models.CharField(max_length=255, verbose_name="order")), | ||||
|                 ( | ||||
|                     "allergens", | ||||
|                     models.ManyToManyField( | ||||
|                         blank=True, to="food.allergen", verbose_name="allergens" | ||||
|                     ), | ||||
|                 ), | ||||
|                 ( | ||||
|                     "owner", | ||||
|                     models.ForeignKey( | ||||
|                         on_delete=django.db.models.deletion.PROTECT, | ||||
|                         related_name="+", | ||||
|                         to="member.club", | ||||
|                         verbose_name="owner", | ||||
|                     ), | ||||
|                 ), | ||||
|                 ( | ||||
|                     "polymorphic_ctype", | ||||
|                     models.ForeignKey( | ||||
|                         editable=False, | ||||
|                         null=True, | ||||
|                         on_delete=django.db.models.deletion.CASCADE, | ||||
|                         related_name="polymorphic_%(app_label)s.%(class)s_set+", | ||||
|                         to="contenttypes.contenttype", | ||||
|                     ), | ||||
|                 ), | ||||
|             ], | ||||
|             options={ | ||||
|                 "verbose_name": "Food", | ||||
|                 "verbose_name_plural": "Foods", | ||||
|             }, | ||||
|         ), | ||||
|         migrations.CreateModel( | ||||
|             name="BasicFood", | ||||
|             fields=[ | ||||
|                 ( | ||||
|                     "food_ptr", | ||||
|                     models.OneToOneField( | ||||
|                         auto_created=True, | ||||
|                         on_delete=django.db.models.deletion.CASCADE, | ||||
|                         parent_link=True, | ||||
|                         primary_key=True, | ||||
|                         serialize=False, | ||||
|                         to="food.food", | ||||
|                     ), | ||||
|                 ), | ||||
|                 ( | ||||
|                     "arrival_date", | ||||
|                     models.DateTimeField( | ||||
|                         default=django.utils.timezone.now, verbose_name="arrival date" | ||||
|                     ), | ||||
|                 ), | ||||
|                 ( | ||||
|                     "date_type", | ||||
|                     models.CharField( | ||||
|                         choices=[("DLC", "DLC"), ("DDM", "DDM")], max_length=255 | ||||
|                     ), | ||||
|                 ), | ||||
|             ], | ||||
|             options={ | ||||
|                 "verbose_name": "Basic food", | ||||
|                 "verbose_name_plural": "Basic foods", | ||||
|             }, | ||||
|             bases=("food.food",), | ||||
|         ), | ||||
|         migrations.CreateModel( | ||||
|             name="QRCode", | ||||
|             fields=[ | ||||
|                 ( | ||||
|                     "id", | ||||
|                     models.AutoField( | ||||
|                         auto_created=True, | ||||
|                         primary_key=True, | ||||
|                         serialize=False, | ||||
|                         verbose_name="ID", | ||||
|                     ), | ||||
|                 ), | ||||
|                 ( | ||||
|                     "qr_code_number", | ||||
|                     models.PositiveIntegerField( | ||||
|                         unique=True, verbose_name="qr code number" | ||||
|                     ), | ||||
|                 ), | ||||
|                 ( | ||||
|                     "food_container", | ||||
|                     models.ForeignKey( | ||||
|                         on_delete=django.db.models.deletion.CASCADE, | ||||
|                         related_name="QR_code", | ||||
|                         to="food.food", | ||||
|                         verbose_name="food container", | ||||
|                     ), | ||||
|                 ), | ||||
|             ], | ||||
|             options={ | ||||
|                 "verbose_name": "QR-code", | ||||
|                 "verbose_name_plural": "QR-codes", | ||||
|             }, | ||||
|         ), | ||||
|         migrations.CreateModel( | ||||
|             name="TransformedFood", | ||||
|             fields=[ | ||||
|                 ( | ||||
|                     "food_ptr", | ||||
|                     models.OneToOneField( | ||||
|                         auto_created=True, | ||||
|                         on_delete=django.db.models.deletion.CASCADE, | ||||
|                         parent_link=True, | ||||
|                         primary_key=True, | ||||
|                         serialize=False, | ||||
|                         to="food.food", | ||||
|                     ), | ||||
|                 ), | ||||
|                 ( | ||||
|                     "creation_date", | ||||
|                     models.DateTimeField( | ||||
|                         default=django.utils.timezone.now, verbose_name="creation date" | ||||
|                     ), | ||||
|                 ), | ||||
|                 ( | ||||
|                     "shelf_life", | ||||
|                     models.DurationField( | ||||
|                         default=datetime.timedelta(days=3), verbose_name="shelf life" | ||||
|                     ), | ||||
|                 ), | ||||
|                 ( | ||||
|                     "ingredients", | ||||
|                     models.ManyToManyField( | ||||
|                         blank=True, | ||||
|                         related_name="transformed_ingredient_inv", | ||||
|                         to="food.food", | ||||
|                         verbose_name="transformed ingredient", | ||||
|                     ), | ||||
|                 ), | ||||
|             ], | ||||
|             options={ | ||||
|                 "verbose_name": "Transformed food", | ||||
|                 "verbose_name_plural": "Transformed foods", | ||||
|             }, | ||||
|             bases=("food.food",), | ||||
|         ), | ||||
|     ] | ||||
							
								
								
									
										0
									
								
								apps/food/migrations/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										0
									
								
								apps/food/migrations/__init__.py
									
									
									
									
									
										Normal file
									
								
							
							
								
								
									
										286
									
								
								apps/food/models.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										286
									
								
								apps/food/models.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,286 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| from datetime import timedelta | ||||
|  | ||||
| from django.db import models, transaction | ||||
| from django.utils import timezone | ||||
| from django.utils.translation import gettext_lazy as _ | ||||
| from polymorphic.models import PolymorphicModel | ||||
| from member.models import Club | ||||
|  | ||||
|  | ||||
| class Allergen(models.Model): | ||||
|     """ | ||||
|     Allergen and alimentary restrictions | ||||
|     """ | ||||
|     name = models.CharField( | ||||
|         verbose_name=_('name'), | ||||
|         max_length=255, | ||||
|     ) | ||||
|  | ||||
|     class Meta: | ||||
|         verbose_name = _("Allergen") | ||||
|         verbose_name_plural = _("Allergens") | ||||
|  | ||||
|     def __str__(self): | ||||
|         return self.name | ||||
|  | ||||
|  | ||||
| class Food(PolymorphicModel): | ||||
|     """ | ||||
|     Describe any type of food | ||||
|     """ | ||||
|     name = models.CharField( | ||||
|         verbose_name=_("name"), | ||||
|         max_length=255, | ||||
|     ) | ||||
|  | ||||
|     owner = models.ForeignKey( | ||||
|         Club, | ||||
|         on_delete=models.PROTECT, | ||||
|         related_name='+', | ||||
|         verbose_name=_('owner'), | ||||
|     ) | ||||
|  | ||||
|     allergens = models.ManyToManyField( | ||||
|         Allergen, | ||||
|         blank=True, | ||||
|         verbose_name=_('allergens'), | ||||
|     ) | ||||
|  | ||||
|     expiry_date = models.DateTimeField( | ||||
|         verbose_name=_('expiry date'), | ||||
|         null=False, | ||||
|     ) | ||||
|  | ||||
|     end_of_life = models.CharField( | ||||
|         blank=True, | ||||
|         verbose_name=_('end of life'), | ||||
|         max_length=255, | ||||
|     ) | ||||
|  | ||||
|     is_ready = models.BooleanField( | ||||
|         verbose_name=_('is ready'), | ||||
|         max_length=255, | ||||
|     ) | ||||
|  | ||||
|     order = models.CharField( | ||||
|         blank=True, | ||||
|         verbose_name=_('order'), | ||||
|         max_length=255, | ||||
|     ) | ||||
|  | ||||
|     def __str__(self): | ||||
|         return self.name | ||||
|  | ||||
|     @transaction.atomic | ||||
|     def update_allergens(self): | ||||
|         # update parents | ||||
|         for parent in self.transformed_ingredient_inv.iterator(): | ||||
|             old_allergens = list(parent.allergens.all()).copy() | ||||
|             parent.allergens.clear() | ||||
|             for child in parent.ingredients.iterator(): | ||||
|                 if child.pk != self.pk: | ||||
|                     parent.allergens.set(parent.allergens.union(child.allergens.all())) | ||||
|             parent.allergens.set(parent.allergens.union(self.allergens.all())) | ||||
|             if old_allergens != list(parent.allergens.all()): | ||||
|                 parent.save(old_allergens=old_allergens) | ||||
|  | ||||
|     def update_expiry_date(self): | ||||
|         # update parents | ||||
|         for parent in self.transformed_ingredient_inv.iterator(): | ||||
|             old_expiry_date = parent.expiry_date | ||||
|             parent.expiry_date = parent.shelf_life + parent.creation_date | ||||
|             for child in parent.ingredients.iterator(): | ||||
|                 if (child.pk != self.pk | ||||
|                     and not (child.polymorphic_ctype.model == 'basicfood' | ||||
|                              and child.date_type == 'DDM')): | ||||
|                     parent.expiry_date = min(parent.expiry_date, child.expiry_date) | ||||
|  | ||||
|             if self.polymorphic_ctype.model == 'basicfood' and self.date_type == 'DLC': | ||||
|                 parent.expiry_date = min(parent.expiry_date, self.expiry_date) | ||||
|             if old_expiry_date != parent.expiry_date: | ||||
|                 parent.save() | ||||
|  | ||||
|     class Meta: | ||||
|         verbose_name = _('Food') | ||||
|         verbose_name_plural = _('Foods') | ||||
|  | ||||
|  | ||||
| class BasicFood(Food): | ||||
|     """ | ||||
|     A basic food is a food directly buy and stored | ||||
|     """ | ||||
|     arrival_date = models.DateTimeField( | ||||
|         default=timezone.now, | ||||
|         verbose_name=_('arrival date'), | ||||
|     ) | ||||
|  | ||||
|     date_type = models.CharField( | ||||
|         max_length=255, | ||||
|         choices=( | ||||
|             ("DLC", "DLC"), | ||||
|             ("DDM", "DDM"), | ||||
|         ) | ||||
|     ) | ||||
|  | ||||
|     @transaction.atomic | ||||
|     def save(self, force_insert=False, force_update=False, using=None, update_fields=None, **kwargs): | ||||
|         created = self.pk is None | ||||
|         if not created: | ||||
|             # Check if important fields are updated | ||||
|             old_food = Food.objects.select_for_update().get(pk=self.pk) | ||||
|             if not hasattr(self, "_force_save"): | ||||
|                 # Allergens | ||||
|  | ||||
|                 if ('old_allergens' in kwargs | ||||
|                         and list(self.allergens.all()) != kwargs['old_allergens']): | ||||
|                     self.update_allergens() | ||||
|  | ||||
|                 # Expiry date | ||||
|                 if ((self.expiry_date != old_food.expiry_date | ||||
|                         and self.date_type == 'DLC') | ||||
|                         or old_food.date_type != self.date_type): | ||||
|                     self.update_expiry_date() | ||||
|  | ||||
|         return super().save(force_insert, force_update, using, update_fields) | ||||
|  | ||||
|     @staticmethod | ||||
|     def get_lastests_objects(number, distinct_field, order_by_field): | ||||
|         """ | ||||
|         Get the last object with distinct field and ranked with order_by | ||||
|         This methods exist because we can't distinct with one field and | ||||
|         order with another | ||||
|         """ | ||||
|         foods = BasicFood.objects.order_by(order_by_field).all() | ||||
|         field = [] | ||||
|         for food in foods: | ||||
|             if getattr(food, distinct_field) in field: | ||||
|                 continue | ||||
|             else: | ||||
|                 field.append(getattr(food, distinct_field)) | ||||
|                 number -= 1 | ||||
|                 yield food | ||||
|             if not number: | ||||
|                 return | ||||
|  | ||||
|     class Meta: | ||||
|         verbose_name = _('Basic food') | ||||
|         verbose_name_plural = _('Basic foods') | ||||
|  | ||||
|     def __str__(self): | ||||
|         return self.name | ||||
|  | ||||
|  | ||||
| class TransformedFood(Food): | ||||
|     """ | ||||
|     A transformed food is a food with ingredients | ||||
|     """ | ||||
|     creation_date = models.DateTimeField( | ||||
|         default=timezone.now, | ||||
|         verbose_name=_('creation date'), | ||||
|     ) | ||||
|  | ||||
|     # Without microbiological analyzes, the storage time is 3 days | ||||
|     shelf_life = models.DurationField( | ||||
|         default=timedelta(days=3), | ||||
|         verbose_name=_('shelf life'), | ||||
|     ) | ||||
|  | ||||
|     ingredients = models.ManyToManyField( | ||||
|         Food, | ||||
|         blank=True, | ||||
|         symmetrical=False, | ||||
|         related_name='transformed_ingredient_inv', | ||||
|         verbose_name=_('transformed ingredient'), | ||||
|     ) | ||||
|  | ||||
|     def check_cycle(self, ingredients, origin, checked): | ||||
|         for ingredient in ingredients: | ||||
|             if ingredient == origin: | ||||
|                 # We break the cycle | ||||
|                 self.ingredients.remove(ingredient) | ||||
|             if ingredient.polymorphic_ctype.model == 'transformedfood' and ingredient not in checked: | ||||
|                 ingredient.check_cycle(ingredient.ingredients.all(), origin, checked) | ||||
|                 checked.append(ingredient) | ||||
|  | ||||
|     @transaction.atomic | ||||
|     def save(self, force_insert=False, force_update=False, using=None, update_fields=None, **kwargs): | ||||
|         created = self.pk is None | ||||
|         if not created: | ||||
|             # Check if important fields are updated | ||||
|             update = {'allergens': False, 'expiry_date': False} | ||||
|             old_food = Food.objects.select_for_update().get(pk=self.pk) | ||||
|             if not hasattr(self, "_force_save"): | ||||
|                 # Allergens | ||||
|                 # Unfortunately with the many-to-many relation we can't access | ||||
|                 # to old allergens | ||||
|                 if ('old_allergens' in kwargs | ||||
|                         and list(self.allergens.all()) != kwargs['old_allergens']): | ||||
|                     update['allergens'] = True | ||||
|  | ||||
|                 # Expiry date | ||||
|                 update['expiry_date'] = (self.shelf_life != old_food.shelf_life | ||||
|                                          or self.creation_date != old_food.creation_date) | ||||
|                 if update['expiry_date']: | ||||
|                     self.expiry_date = self.creation_date + self.shelf_life | ||||
|                 # Unfortunately with the set method ingredients are already save, | ||||
|                 # we check cycle after if possible | ||||
|                 if ('old_ingredients' in kwargs | ||||
|                         and list(self.ingredients.all()) != list(kwargs['old_ingredients'])): | ||||
|                     update['allergens'] = True | ||||
|                     update['expiry_date'] = True | ||||
|  | ||||
|                     # it's preferable to keep a queryset but we allow list too | ||||
|                     if type(kwargs['old_ingredients']) is list: | ||||
|                         kwargs['old_ingredients'] = Food.objects.filter( | ||||
|                             pk__in=[food.pk for food in kwargs['old_ingredients']]) | ||||
|                     self.check_cycle(self.ingredients.all().difference(kwargs['old_ingredients']), self, []) | ||||
|                 if update['allergens']: | ||||
|                     self.update_allergens() | ||||
|                 if update['expiry_date']: | ||||
|                     self.update_expiry_date() | ||||
|  | ||||
|         if created: | ||||
|             self.expiry_date = self.shelf_life + self.creation_date | ||||
|  | ||||
|             # We save here because we need pk for many-to-many relation | ||||
|             super().save(force_insert, force_update, using, update_fields) | ||||
|  | ||||
|             for child in self.ingredients.iterator(): | ||||
|                 self.allergens.set(self.allergens.union(child.allergens.all())) | ||||
|                 if not (child.polymorphic_ctype.model == 'basicfood' and child.date_type == 'DDM'): | ||||
|                     self.expiry_date = min(self.expiry_date, child.expiry_date) | ||||
|         return super().save(force_insert, force_update, using, update_fields) | ||||
|  | ||||
|     class Meta: | ||||
|         verbose_name = _('Transformed food') | ||||
|         verbose_name_plural = _('Transformed foods') | ||||
|  | ||||
|     def __str__(self): | ||||
|         return self.name | ||||
|  | ||||
|  | ||||
| class QRCode(models.Model): | ||||
|     """ | ||||
|     QR-code for register food | ||||
|     """ | ||||
|     qr_code_number = models.PositiveIntegerField( | ||||
|         unique=True, | ||||
|         verbose_name=_('qr code number'), | ||||
|     ) | ||||
|  | ||||
|     food_container = models.ForeignKey( | ||||
|         Food, | ||||
|         on_delete=models.CASCADE, | ||||
|         related_name='QR_code', | ||||
|         verbose_name=_('food container'), | ||||
|     ) | ||||
|  | ||||
|     class Meta: | ||||
|         verbose_name = _('QR-code') | ||||
|         verbose_name_plural = _('QR-codes') | ||||
|  | ||||
|     def __str__(self): | ||||
|         return _('QR-code number') + ' ' + str(self.qr_code_number) | ||||
							
								
								
									
										21
									
								
								apps/food/tables.py
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										21
									
								
								apps/food/tables.py
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,21 @@ | ||||
| # Copyright (C) 2018-2025 by BDE ENS Paris-Saclay | ||||
| # SPDX-License-Identifier: GPL-3.0-or-later | ||||
|  | ||||
| import django_tables2 as tables | ||||
|  | ||||
| from .models import Food | ||||
|  | ||||
|  | ||||
| class FoodTable(tables.Table): | ||||
|     """ | ||||
|     List all foods. | ||||
|     """ | ||||
|     class Meta: | ||||
|         model = Food | ||||
|         template_name = 'django_tables2/bootstrap4.html' | ||||
|         fields = ('name', 'owner', 'allergens', 'expiry_date') | ||||
|         row_attrs = { | ||||
|             'class': 'table-row', | ||||
|             'data-href': lambda record: 'detail/' + str(record.pk), | ||||
|             'style': 'cursor:pointer', | ||||
|         } | ||||
Some files were not shown because too many files have changed in this diff Show More
		Reference in New Issue
	
	Block a user