diff --git a/.github/actions/flutter-common/action.yml b/.github/actions/flutter-common/action.yml index 5592f5d51..20c5dc849 100644 --- a/.github/actions/flutter-common/action.yml +++ b/.github/actions/flutter-common/action.yml @@ -9,7 +9,7 @@ runs: uses: subosito/flutter-action@v2 with: channel: stable - flutter-version: 3.38.5 + flutter-version: 3.38.7 cache: true - name: Install Flutter dependencies diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml index 989036b0d..84e01dd5f 100644 --- a/.github/workflows/build-linux.yml +++ b/.github/workflows/build-linux.yml @@ -62,7 +62,7 @@ jobs: - name: Bump version and update manifest run: | - git clone https://github.com/TheAppgineer/flatpak-flutter.git --branch 0.7.5 ../flatpak-flutter + git clone https://github.com/TheAppgineer/flatpak-flutter.git --branch 0.11.0 ../flatpak-flutter pip install -r ../flatpak-flutter/requirements.txt python bump-wger-version.py ${{ inputs.ref }} ../flatpak-flutter/flatpak-flutter.py --app-module wger flatpak-flutter.json diff --git a/AUTHORS.md b/AUTHORS.md index e478e970a..12f2f5229 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -2,26 +2,58 @@ Thank you all for contributing to the project, you are true heroes! 🫶 -*Generated on 2025-11-10* +*Generated on 2026-01-18* --- ## Contributors -- thisisyoussef - [https://github.com/thisisyoussef](https://github.com/thisisyoussef) - Roland Geider - [https://github.com/rolandgeider](https://github.com/rolandgeider) -- Yashas H Majmudar - [https://github.com/yashas-hm](https://github.com/yashas-hm) - Github-actions - [https://github.com/invalid-email-address](https://github.com/invalid-email-address) +- unknown - [https://github.com/elias170105](https://github.com/elias170105) +- Diya Hituvalli - [https://github.com/dhituval](https://github.com/dhituval) +- dhituval - [https://github.com/dhituval](https://github.com/dhituval) +- john +- ImgBotApp - [https://github.com/ImgBotApp](https://github.com/ImgBotApp) +- DhruvSingh19 - [https://github.com/DhruvSingh19](https://github.com/DhruvSingh19) +- Anupthor007 - [https://github.com/Anupthor007](https://github.com/Anupthor007) +- lenka369 +- lenka369 - [https://github.com/lenka369](https://github.com/lenka369) +- Branislav Nohaj +- Branislav Nohaj - [https://github.com/Oknarb258](https://github.com/Oknarb258) +- Kyle Hekkers - [https://github.com/List0734](https://github.com/List0734) +- GhostInTheNN - [https://github.com/GhostInTheNN](https://github.com/GhostInTheNN) +- Arthur De Neyer - [https://github.com/GaecKo](https://github.com/GaecKo) +- Arthur De Neyer +- Max Pylypenko - [https://github.com/3mpee3mpee](https://github.com/3mpee3mpee) +- rishad.n - [https://github.com/rishadn-gif](https://github.com/rishadn-gif) +- Nelumbo Nucifera - [https://github.com/nelumboy](https://github.com/nelumboy) +- Patrik - [https://github.com/P4TR1K1305](https://github.com/P4TR1K1305) +- Iman Karimian - [https://github.com/IK7D3](https://github.com/IK7D3) +- Afzal Momin - [https://github.com/afzal09](https://github.com/afzal09) +- Ninguém Mesmo +- Dieter Plaetinck - [https://github.com/Dieterbe](https://github.com/Dieterbe) +- RahulShaw321 +- shravya - [https://github.com/shraavv](https://github.com/shraavv) +- kobo +- burny0202 - [https://github.com/Shininess8816](https://github.com/Shininess8816) +- Rohitdhall987 - [https://github.com/Rohitdhall987](https://github.com/Rohitdhall987) +- Yashas H Majmudar - [https://github.com/yashas-hm](https://github.com/yashas-hm) +- Yashas H Majmudar - [https://github.com/yashas-hm](https://github.com/yashas-hm) +- thisisyoussef - [https://github.com/thisisyoussef](https://github.com/thisisyoussef) +- Peter Thaler - Christijan - [https://github.com/ChrispyM](https://github.com/ChrispyM) - Jackpkn - [https://github.com/Jackpkn](https://github.com/Jackpkn) - sangharshdeveloper - [https://github.com/Sangharshdeveloper](https://github.com/Sangharshdeveloper) -- ImgBotApp - [https://github.com/ImgBotApp](https://github.com/ImgBotApp) -- தமிழ்நேரம் - [https://github.com/TamilNeram](https://github.com/TamilNeram) +- Ayush Sourav Jagaty - [https://github.com/AyushJagaty](https://github.com/AyushJagaty) +- eyjhb - [https://github.com/eyJhb](https://github.com/eyJhb) +- AyushJagaty - [https://github.com/AyushJagaty](https://github.com/AyushJagaty) +- Ayush Sourav Jagaty +- தமிழ்நேரம் - Xianglin Zeng - [https://github.com/FutureYL3](https://github.com/FutureYL3) - Arya Pratap Singh - [https://github.com/ARYPROGRAMMER](https://github.com/ARYPROGRAMMER) - ARYPROGRAMMER - [https://github.com/ARYPROGRAMMER](https://github.com/ARYPROGRAMMER) -- Dieter Plaetinck - [https://github.com/Dieterbe](https://github.com/Dieterbe) -- szalas - [https://github.com/szalas](https://github.com/szalas) +- szalas - dan - [https://github.com/sizzlesloth](https://github.com/sizzlesloth) - DVPeer - [https://github.com/Denpeer](https://github.com/Denpeer) - Marco Rimoldi - [https://github.com/marcor](https://github.com/marcor) @@ -33,7 +65,7 @@ Thank you all for contributing to the project, you are true heroes! 🫶 - Milksheyke - [https://github.com/sheyaln](https://github.com/sheyaln) - Abhishek Saini - [https://github.com/Abhisheksainii](https://github.com/Abhisheksainii) - dimii27 - [https://github.com/dimii27](https://github.com/dimii27) -- Antonis-geo - [https://github.com/Antonis-geo](https://github.com/Antonis-geo) +- Antonis-geo - artchiee - [https://github.com/artchiee](https://github.com/artchiee) - artchiee - [https://github.com/artchiee](https://github.com/artchiee) - Jigar Prajapati - [https://github.com/Jiggy9](https://github.com/Jiggy9) @@ -104,6 +136,7 @@ Thank you all for contributing to the project, you are true heroes! 🫶 - Jannik Norden - Allan Nordhøy - [https://github.com/comradekingu](https://github.com/comradekingu) - Stefano Rossi - [https://github.com/stefanorossiti](https://github.com/stefanorossiti) +- Dylan Aird - [https://github.com/Dolaned](https://github.com/Dolaned) ## Translators @@ -113,23 +146,28 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Arabic +- Jaafer Mahfoud - [https://github.com/mysterI0s](https://github.com/mysterI0s) +- Yrooma - [https://github.com/Yrooma](https://github.com/Yrooma) - Anonymous - [https://github.com/weblate](https://github.com/weblate) - Hanaa - [https://github.com/hn-n](https://github.com/hn-n) - Ahmed zein - [https://github.com/Ahmed-Zein](https://github.com/Ahmed-Zein) ### Catalan -- Zixu Sun - [https://github.com/ziixu](https://github.com/ziixu) - Anonymous - [https://github.com/weblate](https://github.com/weblate) +- Zixu Sun - [https://github.com/ziixu](https://github.com/ziixu) - guillem - [https://github.com/gbuendia](https://github.com/gbuendia) ### Chinese (Simplified Han script) +- KW Lam - [https://github.com/loksonlkw](https://github.com/loksonlkw) +- Wen QI - [https://github.com/kevinwenyu](https://github.com/kevinwenyu) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Herb Huang ### Chinese (Simplified) -- 纪颖志 - [https://github.com/jiyingzhi](https://github.com/jiyingzhi) +- 纪颖志 - [https://github.com/yingzhi0808](https://github.com/yingzhi0808) - Yi-Han Hsiung - [https://github.com/AaronHsiung](https://github.com/AaronHsiung) - Tsz Hong CHAN - [https://github.com/tomyan112](https://github.com/tomyan112) - Eddie Tang - [https://github.com/EDED2314](https://github.com/EDED2314) @@ -140,6 +178,9 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Chinese (Traditional Han script) +- Chia Wen Tsai - [https://github.com/cjwind](https://github.com/cjwind) +- Paulkit - [https://github.com/Paulkit](https://github.com/Paulkit) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Peter Dave Hello - [https://github.com/PeterDaveHello](https://github.com/PeterDaveHello) ### Chinese (Traditional) @@ -152,11 +193,14 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Croatian - Milo Ivir - [https://github.com/milotype](https://github.com/milotype) +- Neno Horvat - [https://github.com/ness993](https://github.com/ness993) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Roland Geider - [https://github.com/rolandgeider](https://github.com/rolandgeider) - SMilohanic - [https://github.com/sandimilohanic](https://github.com/sandimilohanic) ### Czech +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Fjuro - [https://github.com/Fjuro](https://github.com/Fjuro) - Fjuro - CaptainDolphy - [https://github.com/CaptainDolphy](https://github.com/CaptainDolphy) @@ -164,6 +208,7 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Dutch +- Floris C - Joey Haalboom - [https://github.com/JoeyHaalboom](https://github.com/JoeyHaalboom) ### English @@ -172,11 +217,22 @@ Thank you all for contributing to the project, you are true heroes! 🫶 - Allan Nordhøy - [https://github.com/comradekingu](https://github.com/comradekingu) - Roland Geider - [https://github.com/rolandgeider](https://github.com/rolandgeider) +### Filipino + +- john + ### French +- Benjamin Voisin - [https://github.com/benjamin-voisin](https://github.com/benjamin-voisin) +- Justin Pinheiro - [https://github.com/justin-pinheiro](https://github.com/justin-pinheiro) +- Paul Bonneau - [https://github.com/paulbonneau](https://github.com/paulbonneau) +- Martin Derleth +- Vocatis - [https://github.com/Vocatis](https://github.com/Vocatis) +- Kilian +- Enzo Besnainou +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - William - [https://github.com/WilliamR312](https://github.com/WilliamR312) - florent4014 - [https://github.com/florent4014](https://github.com/florent4014) -- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Xav Basco - David Olewski - [https://github.com/Arigowin](https://github.com/Arigowin) - yoyomax80400 - [https://github.com/yoyomax80400](https://github.com/yoyomax80400) @@ -190,9 +246,15 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### German -- kvnrmnn - [https://github.com/rmnn92](https://github.com/rmnn92) -- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Roland Geider - [https://github.com/rolandgeider](https://github.com/rolandgeider) +- Elias Lang - [https://github.com/elias170105](https://github.com/elias170105) +- Panoloo - [https://github.com/Panoloo](https://github.com/Panoloo) +- johannes heintz - [https://github.com/Randalix](https://github.com/Randalix) +- Tobias Maschek - [https://github.com/jemx](https://github.com/jemx) +- Richard Mrosk - [https://github.com/EtheriousNight](https://github.com/EtheriousNight) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) +- BlinderUhu - [https://github.com/BlinderUhu](https://github.com/BlinderUhu) +- kvnrmnn - [https://github.com/rmnn92](https://github.com/rmnn92) - Victor Jouhoff - [https://github.com/jouhoffv](https://github.com/jouhoffv) - m4skedbyte - Axel Steinbrecher @@ -207,12 +269,13 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Greek - Dimitrys Meliates -- Antonis-geo - [https://github.com/Antonis-geo](https://github.com/Antonis-geo) +- Antonis-geo ### Hebrew -- Anonymous - [https://github.com/weblate](https://github.com/weblate) +- Omer I.S - [https://github.com/omeritzics](https://github.com/omeritzics) - n,rdo +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Tomer Ben Rachel - [https://github.com/TomerPacific](https://github.com/TomerPacific) ### Hindi @@ -221,8 +284,14 @@ Thank you all for contributing to the project, you are true heroes! 🫶 - Anonymous - [https://github.com/weblate](https://github.com/weblate) - Debayan Sutradhar - [https://github.com/rnayabed](https://github.com/rnayabed) +### Hungarian + +- Greg + ### Indonesian +- Nurfitra Pujo Santiko - [https://github.com/NurfitraPujo](https://github.com/NurfitraPujo) +- Arga Pandika - [https://github.com/argakast](https://github.com/argakast) - aryakdaniswara - [https://github.com/aryakdaniswara](https://github.com/aryakdaniswara) - Anonymous - [https://github.com/weblate](https://github.com/weblate) - Debi Maulana Ahsan Halla @@ -230,9 +299,15 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Italian +- Alessio - [https://github.com/menitz](https://github.com/menitz) +- Federico - [https://github.com/FedericoVaga](https://github.com/FedericoVaga) +- Luca Galli - [https://github.com/Lvcaa](https://github.com/Lvcaa) +- clafalco - [https://github.com/clafalco](https://github.com/clafalco) +- adriano onorati - [https://github.com/banphi](https://github.com/banphi) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) +- Matteo Morari - [https://github.com/matteomorari](https://github.com/matteomorari) - Antenore Gatta - [https://github.com/antenore](https://github.com/antenore) - Gab Gat -- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Federico Pierantoni - [https://github.com/F3FFO](https://github.com/F3FFO) - oarion - [https://github.com/oarion](https://github.com/oarion) - Alessandro Faucci - [https://github.com/Dhy19971](https://github.com/Dhy19971) @@ -247,22 +322,36 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Japanese +- Ryohei Morimoto - [https://github.com/Ryohei-Caulked](https://github.com/Ryohei-Caulked) - Anonymous - [https://github.com/weblate](https://github.com/weblate) - Tsz Hong CHAN - [https://github.com/tomyan112](https://github.com/tomyan112) - sasukeiscool - [https://github.com/sasukeiscool](https://github.com/sasukeiscool) - yiter +### Korean + +- jyk0619 - [https://github.com/jyk0619](https://github.com/jyk0619) +- kobo + ### Norwegian Bokmål +- Morten R. Bjørklund - Roland Geider - [https://github.com/rolandgeider](https://github.com/rolandgeider) - Allan Nordhøy - [https://github.com/comradekingu](https://github.com/comradekingu) +### Persian + +- Mahmuoud Salehi + ### Polish +- saalaataa - [https://github.com/saalaataa](https://github.com/saalaataa) +- Kamil Maciąg +- Y - [https://github.com/dioxyg](https://github.com/dioxyg) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Karol Solecki - [https://github.com/karolsol](https://github.com/karolsol) - Piotr Strebski - [https://github.com/strebski](https://github.com/strebski) - Dawid Panyło -- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Marcin Schoenknecht - Patryk - [https://github.com/byakurau](https://github.com/byakurau) - Michał Homza - [https://github.com/HagiaHaya](https://github.com/HagiaHaya) @@ -270,8 +359,11 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Portuguese -- Edson Wolf - [https://github.com/edsonblwolf](https://github.com/edsonblwolf) +- Ninguém Mesmo +- caue Antunes Siqueira - [https://github.com/caue-siqueira](https://github.com/caue-siqueira) - Anonymous - [https://github.com/weblate](https://github.com/weblate) +- The_Quintino - [https://github.com/paqgamer](https://github.com/paqgamer) +- Edson Wolf - [https://github.com/edsonblwolf](https://github.com/edsonblwolf) - Wilton Rodrigues - Guilherme Salomão - [https://github.com/salomaoparkour](https://github.com/salomaoparkour) - Bruno de Moura - [https://github.com/bruunomooura](https://github.com/bruunomooura) @@ -283,9 +375,14 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Portuguese (Brazil) +- Diego Menezes +- Rafael Acurcio - [https://github.com/faellacurcio](https://github.com/faellacurcio) +- Marina Aranha - [https://github.com/mariaranha](https://github.com/mariaranha) +- faciolihenrique - [https://github.com/faciolihenrique](https://github.com/faciolihenrique) +- Jênisson Alves de Andrade +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Ricardo Lima - [https://github.com/rhrlima](https://github.com/rhrlima) - Clerton Araujo - [https://github.com/clertonraf](https://github.com/clertonraf) -- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Wilton Rodrigues - Nao interessa - Lucas Mezêncio - [https://github.com/lucasmezencio](https://github.com/lucasmezencio) @@ -295,15 +392,22 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Portuguese (Portugal) +- Ruben Sardinha +- Ninguém Mesmo +- FilipeAb - [https://github.com/FilipeAb](https://github.com/FilipeAb) - Anonymous - [https://github.com/weblate](https://github.com/weblate) ### Romanian +- Vlad Bejenaru - [https://github.com/vladbejenaru](https://github.com/vladbejenaru) - Bogdan Bujor - [https://github.com/qSharpy](https://github.com/qSharpy) - dimii27 - [https://github.com/dimii27](https://github.com/dimii27) ### Russian +- Iskander - [https://github.com/iskanderCabbie](https://github.com/iskanderCabbie) +- Aleksandr - [https://github.com/alexmikheen](https://github.com/alexmikheen) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Алексей Курышко - [https://github.com/alexkuryshko](https://github.com/alexkuryshko) - lightningcpu - [https://github.com/lightningcpu](https://github.com/lightningcpu) - Кирилл Александрович Злобин - [https://github.com/gungstarbeiter](https://github.com/gungstarbeiter) @@ -312,10 +416,24 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Serbian +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Mladen Trišić - [https://github.com/mtrisic](https://github.com/mtrisic) +### Slovak + +- Patrik - [https://github.com/P4TR1K1305](https://github.com/P4TR1K1305) + ### Spanish +- MarcMeRu11 - [https://github.com/marcmeru11](https://github.com/marcmeru11) +- v7mbz +- Pablo Sarabia Ortiz - [https://github.com/psarabiaortiz](https://github.com/psarabiaortiz) +- Daniel +- Alejandro Castro +- SirWerto +- Jose David Villegas (JoseDv1) - [https://github.com/JoseDv1](https://github.com/JoseDv1) +- Marco Diaz - [https://github.com/maditmx](https://github.com/maditmx) +- Oscar González - [https://github.com/ogrydc](https://github.com/ogrydc) - Anonymous - [https://github.com/weblate](https://github.com/weblate) - Roberto Iglesias - [https://github.com/iglesiasroberto14](https://github.com/iglesiasroberto14) - c06c3abb8f @@ -329,10 +447,16 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Tamil -- தமிழ்நேரம் - [https://github.com/TamilNeram](https://github.com/TamilNeram) +- தமிழ்நேரம் +- Anonymous - [https://github.com/weblate](https://github.com/weblate) + +### Thai + +- Wiputdanai Pinkaew (Kang) - [https://github.com/kknownn](https://github.com/kknownn) ### Turkish +- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Oğuz Ersen - [https://github.com/oersen](https://github.com/oersen) - Roland Geider - [https://github.com/rolandgeider](https://github.com/rolandgeider) - Cem Avcı - [https://github.com/cem256](https://github.com/cem256) @@ -342,10 +466,13 @@ Thank you all for contributing to the project, you are true heroes! 🫶 ### Ukrainian +- Максим Горпиніч - [https://github.com/maksim2005UKR](https://github.com/maksim2005UKR) +- Максим Горпиніч - [https://github.com/Maksim2005UA2](https://github.com/Maksim2005UA2) - Максим Горпиніч - [https://github.com/Maksim2005UA](https://github.com/Maksim2005UA) +- Anonymous - [https://github.com/weblate](https://github.com/weblate) +- Максим Горпиніч - Roland Geider - [https://github.com/rolandgeider](https://github.com/rolandgeider) - Максим Горпиніч -- Anonymous - [https://github.com/weblate](https://github.com/weblate) - Dan - [https://github.com/Kefir2105](https://github.com/Kefir2105) - Dan - Tymofii Lytvynenko diff --git a/Gemfile.lock b/Gemfile.lock index cf6854755..313cae7fe 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -8,8 +8,8 @@ GEM artifactory (3.0.17) atomos (0.1.3) aws-eventstream (1.4.0) - aws-partitions (1.1194.0) - aws-sdk-core (3.239.2) + aws-partitions (1.1203.0) + aws-sdk-core (3.241.3) aws-eventstream (~> 1, >= 1.3.0) aws-partitions (~> 1, >= 1.992.0) aws-sigv4 (~> 1.9) @@ -17,18 +17,18 @@ GEM bigdecimal jmespath (~> 1, >= 1.6.1) logger - aws-sdk-kms (1.118.0) - aws-sdk-core (~> 3, >= 3.239.1) + aws-sdk-kms (1.120.0) + aws-sdk-core (~> 3, >= 3.241.3) aws-sigv4 (~> 1.5) - aws-sdk-s3 (1.207.0) - aws-sdk-core (~> 3, >= 3.234.0) + aws-sdk-s3 (1.211.0) + aws-sdk-core (~> 3, >= 3.241.3) aws-sdk-kms (~> 1) aws-sigv4 (~> 1.5) aws-sigv4 (1.12.1) aws-eventstream (~> 1, >= 1.0.2) babosa (1.0.4) base64 (0.2.0) - bigdecimal (3.3.1) + bigdecimal (4.0.1) claide (1.1.0) colored (1.2) colored2 (3.1.2) @@ -61,7 +61,7 @@ GEM faraday-em_synchrony (1.0.1) faraday-excon (1.1.0) faraday-httpclient (1.0.1) - faraday-multipart (1.1.1) + faraday-multipart (1.2.0) multipart-post (~> 2.0) faraday-net_http (1.0.2) faraday-net_http_persistent (1.2.0) @@ -71,7 +71,7 @@ GEM faraday_middleware (1.2.1) faraday (~> 1.0) fastimage (2.4.0) - fastlane (2.229.1) + fastlane (2.230.0) CFPropertyList (>= 2.3, < 4.0.0) abbrev (~> 0.1.2) addressable (>= 2.8, < 3.0.0) @@ -100,6 +100,7 @@ GEM http-cookie (~> 1.0.5) json (< 3.0.0) jwt (>= 2.1.0, < 3) + logger (>= 1.6, < 2.0) mini_magick (>= 4.9.4, < 5.0.0) multipart-post (>= 2.0.0, < 3.0.0) mutex_m (~> 0.3.0) @@ -170,7 +171,7 @@ GEM logger (1.7.0) mini_magick (4.13.2) mini_mime (1.1.5) - multi_json (1.18.0) + multi_json (1.19.1) multipart-post (2.4.1) mutex_m (0.3.0) nanaimo (0.4.0) @@ -179,7 +180,7 @@ GEM optparse (0.8.1) os (1.1.4) plist (3.7.2) - public_suffix (7.0.0) + public_suffix (7.0.2) rake (13.3.1) representable (3.2.0) declarative (< 0.1.0) diff --git a/analysis_options.yaml b/analysis_options.yaml index 992b09c5d..79c8d7cad 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -14,18 +14,16 @@ analyzer: # Allow self-reference to deprecated members (we do this because otherwise we have # to annotate every member in every test, assert, etc, when we deprecate something) deprecated_member_use_from_same_package: ignore - # Ignore analyzer hints for updating pubspecs when using Future or - # Stream and not importing dart:async - # Please see https://github.com/flutter/flutter/pull/24528 for details. - sdk_version_async_exported_from_core: ignore - plugins: - - custom_lint + - riverpod_lint formatter: page_width: 100 trailing_commas: preserve +plugins: + riverpod_lint: 3.1.0 + linter: rules: # These rules are documented on and in the same order as diff --git a/flatpak/de.wger.flutter.metainfo.xml b/flatpak/de.wger.flutter.metainfo.xml index ab5aadb70..799b045ba 100755 --- a/flatpak/de.wger.flutter.metainfo.xml +++ b/flatpak/de.wger.flutter.metainfo.xml @@ -84,6 +84,30 @@ + + +

Bug fixes and improvements.

+
+ https://github.com/wger-project/flutter/releases/tag/1.10.0 +
+ + +

Bug fixes and improvements.

+
+ https://github.com/wger-project/flutter/releases/tag/1.9.6 +
+ + +

Bug fixes and improvements.

+
+ https://github.com/wger-project/flutter/releases/tag/1.9.5 +
+ + +

Bug fixes and improvements.

+
+ https://github.com/wger-project/flutter/releases/tag/1.9.4 +

Bug fixes and improvements.

diff --git a/ios/Gemfile.lock b/ios/Gemfile.lock index 5447a46b1..b05f5052b 100644 --- a/ios/Gemfile.lock +++ b/ios/Gemfile.lock @@ -9,24 +9,28 @@ GEM public_suffix (>= 2.0.2, < 7.0) artifactory (3.0.17) atomos (0.1.3) - aws-eventstream (1.3.0) - aws-partitions (1.1018.0) - aws-sdk-core (3.214.0) + aws-eventstream (1.4.0) + aws-partitions (1.1196.0) + aws-sdk-core (3.240.0) aws-eventstream (~> 1, >= 1.3.0) aws-partitions (~> 1, >= 1.992.0) aws-sigv4 (~> 1.9) + base64 + bigdecimal jmespath (~> 1, >= 1.6.1) - aws-sdk-kms (1.96.0) - aws-sdk-core (~> 3, >= 3.210.0) + logger + aws-sdk-kms (1.118.0) + aws-sdk-core (~> 3, >= 3.239.1) aws-sigv4 (~> 1.5) - aws-sdk-s3 (1.176.0) - aws-sdk-core (~> 3, >= 3.210.0) + aws-sdk-s3 (1.208.0) + aws-sdk-core (~> 3, >= 3.234.0) aws-sdk-kms (~> 1) aws-sigv4 (~> 1.5) - aws-sigv4 (1.10.1) + aws-sigv4 (1.12.1) aws-eventstream (~> 1, >= 1.0.2) babosa (1.0.4) base64 (0.2.0) + bigdecimal (4.0.1) claide (1.1.0) colored (1.2) colored2 (3.1.2) @@ -157,6 +161,7 @@ GEM json (2.9.0) jwt (2.9.3) base64 + logger (1.7.0) mini_magick (4.13.2) mini_mime (1.1.5) multi_json (1.15.0) diff --git a/lib/core/exceptions/http_exception.dart b/lib/core/exceptions/http_exception.dart index 948b8975e..73cbc24c0 100644 --- a/lib/core/exceptions/http_exception.dart +++ b/lib/core/exceptions/http_exception.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -43,7 +43,8 @@ class WgerHttpException implements Exception { final dynamic responseBody = response.body; final contentType = response.headers[HttpHeaders.contentTypeHeader]; - if (contentType != null && contentType.contains('text/html')) { + if ((contentType != null && contentType.contains('text/html')) || + responseBody.toString().contains('. - * Copyright (c) 2025 wger Team - * - * wger Workout Manager is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - // GENERATED CODE - DO NOT MODIFY BY HAND part of 'ingredients_database.dart'; diff --git a/lib/database/powersync/powersync.g.dart b/lib/database/powersync/powersync.g.dart index 33e6123b4..a975d0bf9 100644 --- a/lib/database/powersync/powersync.g.dart +++ b/lib/database/powersync/powersync.g.dart @@ -10,7 +10,7 @@ part of 'powersync.dart'; // ignore_for_file: type=lint, type=warning @ProviderFor(powerSyncInstance) -const powerSyncInstanceProvider = PowerSyncInstanceProvider._(); +final powerSyncInstanceProvider = PowerSyncInstanceProvider._(); final class PowerSyncInstanceProvider extends @@ -20,7 +20,7 @@ final class PowerSyncInstanceProvider FutureOr > with $FutureModifier, $FutureProvider { - const PowerSyncInstanceProvider._() + PowerSyncInstanceProvider._() : super( from: null, argument: null, @@ -49,11 +49,11 @@ final class PowerSyncInstanceProvider String _$powerSyncInstanceHash() => r'd4048d9589d6b975dfda0225c0e49af08f34edd0'; @ProviderFor(didCompleteSync) -const didCompleteSyncProvider = DidCompleteSyncFamily._(); +final didCompleteSyncProvider = DidCompleteSyncFamily._(); final class DidCompleteSyncProvider extends $FunctionalProvider with $Provider { - const DidCompleteSyncProvider._({ + DidCompleteSyncProvider._({ required DidCompleteSyncFamily super.from, required StreamPriority? super.argument, }) : super( @@ -107,7 +107,7 @@ String _$didCompleteSyncHash() => r'1b954d75f05194156411ecc9860788ba9b13c2c8'; final class DidCompleteSyncFamily extends $Family with $FunctionalFamilyOverride { - const DidCompleteSyncFamily._() + DidCompleteSyncFamily._() : super( retry: null, name: r'didCompleteSyncProvider', diff --git a/lib/helpers/errors.dart b/lib/helpers/errors.dart index af2501fed..eadb3a93c 100644 --- a/lib/helpers/errors.dart +++ b/lib/helpers/errors.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -51,8 +51,6 @@ void showHttpExceptionErrorDialog(WgerHttpException exception, {BuildContext? co return; } - final theme = Theme.of(dialogContext); - showDialog( context: dialogContext, builder: (ctx) => AlertDialog( diff --git a/lib/helpers/json.dart b/lib/helpers/json.dart index 91cd0756c..b0202ca3e 100644 --- a/lib/helpers/json.dart +++ b/lib/helpers/json.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2025 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -70,6 +70,14 @@ DateTime utcIso8601ToLocalDate(String dateTime) { return DateTime.parse(dateTime).toLocal(); } +DateTime? utcIso8601ToLocalDateNull(String? dateTime) { + if (dateTime == null) { + return null; + } + + return utcIso8601ToLocalDate(dateTime); +} + /* * Converts a time to a date object. * Needed e.g. when the wger api only sends a time but no date information. diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 1064ca94f..ca6eb4c0a 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -100,6 +100,7 @@ "@labelWorkoutPlan": { "description": "Title for screen workout plan" }, + "dashboardWidgets": "Dashboard widgets", "labelDashboard": "Dashboard", "@labelDashboard": { "description": "Title for screen dashboard" @@ -175,6 +176,7 @@ "slotEntryTypeTut": "Time under Tension", "slotEntryTypeIso": "Isometric hold", "slotEntryTypeJump": "Jump", + "trophies": "Trophies", "routines": "Routines", "newRoutine": "New routine", "noRoutines": "You have no routines", @@ -232,6 +234,16 @@ "@comment": { "description": "Comment, additional information" }, + "topSet": "Top set: {value}", + "@topSet": { + "description": "Value is a representation of the set, like '10 x 80kg'", + "type": "text", + "placeholders": { + "value": { + "type": "String" + } + } + }, "impressionGood": "Good", "impressionNeutral": "Neutral", "impressionBad": "Bad", @@ -262,6 +274,7 @@ }, "selectExercises": "If you want to do a superset you can search for several exercises, they will be grouped together", "@selectExercises": {}, + "personalRecords": "Personal records", "gymMode": "Gym mode", "@gymMode": { "description": "Label when starting the gym mode" @@ -590,6 +603,7 @@ "@newEntry": { "description": "Title when adding a new entry such as a weight or log entry" }, + "noTrophies": "You have no trophies yet", "noWeightEntries": "You have no weight entries", "@noWeightEntries": { "description": "Message shown when the user has no logged weight entries" diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 395cd1e2f..ed5075576 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -462,7 +462,7 @@ }, "logIngredient": "Registrar en el diario nutricional", "@logIngredient": {}, - "plateCalculatorNotDivisible": "No se puede obtener el peso con las placas disponbles", + "plateCalculatorNotDivisible": "No se puede obtener el peso con las placas disponibles", "@plateCalculatorNotDivisible": { "description": "Error message when the current weight is not reachable with plates (e.g. 33.1 kg)" }, @@ -1005,7 +1005,7 @@ "@goalTypeAdvanced": { "description": "added for localization of Class GoalType's filed advanced" }, - "indicatorRaw": "raw", + "indicatorRaw": "Bruto", "@indicatorRaw": { "description": "added for localization of Class Indicator's field text" }, @@ -1114,5 +1114,99 @@ "type": "String" } } - } + }, + "dayTypeCustom": "Personalizado", + "@dayTypeCustom": {}, + "dayTypeAmrap": "Tantas rondas como sea posible", + "@dayTypeAmrap": {}, + "dayTypeHiit": "Entrenamiento en intervalos de alta intensidad", + "@dayTypeHiit": {}, + "dayTypeEdt": "Entrenamiento de intensidad creciente", + "@dayTypeEdt": {}, + "dayTypeRft": "Rondas por tiempo", + "@dayTypeRft": {}, + "dayTypeAfap": "Tan rápido como sea posible", + "@dayTypeAfap": {}, + "slotEntryTypeNormal": "Normal", + "@slotEntryTypeNormal": {}, + "slotEntryTypeDropset": "Serie descendiente", + "@slotEntryTypeDropset": {}, + "slotEntryTypePartial": "Parcial", + "@slotEntryTypePartial": {}, + "slotEntryTypeForced": "Forzadas", + "@slotEntryTypeForced": {}, + "slotEntryTypeTut": "Tiempo bajo tensión", + "@slotEntryTypeTut": {}, + "slotEntryTypeIso": "Aguante isométrico", + "@slotEntryTypeIso": {}, + "slotEntryTypeJump": "Salto", + "@slotEntryTypeJump": {}, + "impressionGood": "Bien", + "@impressionGood": {}, + "impressionNeutral": "Neutral", + "@impressionNeutral": {}, + "impressionBad": "Mal", + "@impressionBad": {}, + "gymModeShowExercises": "Ver páginas de resumen de ejercicios", + "@gymModeShowExercises": {}, + "gymModeShowTimer": "Mostrar temporizador entre series", + "@gymModeShowTimer": {}, + "gymModeTimerType": "Tipo de temporizador", + "@gymModeTimerType": {}, + "gymModeTimerTypeHelText": "Si una serie tiene tiempo de pausa, siempre se usa una cuenta regresiva.", + "@gymModeTimerTypeHelText": {}, + "countdown": "Cuenta regresiva", + "@countdown": {}, + "stopwatch": "Cronómetro", + "@stopwatch": {}, + "gymModeDefaultCountdownTime": "Tiempo predeterminado de cuenta regresiva, en segundos", + "@gymModeDefaultCountdownTime": {}, + "gymModeNotifyOnCountdownFinish": "Notificar al terminar cuenta regresiva", + "@gymModeNotifyOnCountdownFinish": {}, + "duration": "Duración", + "@duration": {}, + "volume": "Volumen", + "@volume": { + "description": "The volume of a workout or set, i.e. weight x reps" + }, + "workoutCompleted": "Entrenamiento completado", + "@workoutCompleted": {}, + "formMinMaxValues": "Por favor introduce un número entre {min} y {max}", + "@formMinMaxValues": { + "description": "Error message when the user needs to enter a value between min and max", + "type": "text", + "placeholders": { + "min": { + "type": "int" + }, + "max": { + "type": "int" + } + } + }, + "superset": "Superserie", + "@superset": {}, + "endWorkout": "Finalizar entrenamiento", + "@endWorkout": { + "description": "Use the imperative, label on button to finish the current workout in gym mode" + }, + "durationHoursMinutes": "{hours}h {minutes}m", + "@durationHoursMinutes": { + "description": "A duration, in hours and minutes", + "type": "text", + "placeholders": { + "hours": { + "type": "int" + }, + "minutes": { + "type": "int" + } + } + }, + "dayTypeEnom": "Cada minuto, en el minuto", + "@dayTypeEnom": {}, + "dayTypeTabata": "Entrenamiento Tabata", + "@dayTypeTabata": {}, + "slotEntryTypeMyo": "Entrenamiento Myo", + "@slotEntryTypeMyo": {} } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 902d4c582..8a5cfc2ce 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -7,7 +7,7 @@ "@weight": { "description": "The weight of a workout log or body weight entry" }, - "confirmDelete": "Êtes-vous sûre de vouloir supprimer « {toDelete} » ?", + "confirmDelete": "Êtes-vous sûr de vouloir supprimer '{toDelete}' ?", "@confirmDelete": { "description": "Confirmation text before the user deletes an object", "type": "text", @@ -199,7 +199,7 @@ "@reset": { "description": "Button text allowing the user to reset the entered values to the default" }, - "useCustomServer": "Utiliser le serveur personnalisé", + "useCustomServer": "Utiliser un serveur personnalisé", "@useCustomServer": { "description": "Toggle button allowing users to switch between the default and a custom wger server" }, @@ -364,7 +364,7 @@ } } }, - "imageFormatNotSupportedDetail": "{imageFormat} non pris en charge", + "imageFormatNotSupportedDetail": "{imageFormat} pas encore pris en charge.", "@imageFormatNotSupportedDetail": { "description": "Label shown on the image preview container when image format is not supported", "type": "text", @@ -1126,5 +1126,63 @@ "enterTextInLanguage": "Veuillez saisir le texte dans la bonne langue !", "@enterTextInLanguage": {}, "endWorkout": "Terminer l'entraînement", - "@endWorkout": {} + "@endWorkout": {}, + "impressionGood": "Bonne", + "@impressionGood": {}, + "impressionNeutral": "Neutre", + "@impressionNeutral": {}, + "impressionBad": "Mauvaise", + "@impressionBad": {}, + "gymModeShowExercises": "Afficher les pages d'aperçu des exercices", + "@gymModeShowExercises": {}, + "gymModeShowTimer": "Afficher le chronomètre entre les séries", + "@gymModeShowTimer": {}, + "gymModeTimerType": "Type de chronomètre", + "@gymModeTimerType": {}, + "gymModeTimerTypeHelText": "Si une série a un temps de pause, un compte à rebours est toujours utilisé.", + "@gymModeTimerTypeHelText": {}, + "countdown": "Compte à rebours", + "@countdown": {}, + "stopwatch": "Chronomètre", + "@stopwatch": {}, + "gymModeDefaultCountdownTime": "Temps de compte à rebours par défaut, en secondes", + "@gymModeDefaultCountdownTime": {}, + "gymModeNotifyOnCountdownFinish": "Notifier à la fin du compte à rebours", + "@gymModeNotifyOnCountdownFinish": {}, + "duration": "Durée", + "@duration": {}, + "durationHoursMinutes": "{hours}h {minutes}m", + "@durationHoursMinutes": { + "description": "A duration, in hours and minutes", + "type": "text", + "placeholders": { + "hours": { + "type": "int" + }, + "minutes": { + "type": "int" + } + } + }, + "volume": "Volume", + "@volume": { + "description": "The volume of a workout or set, i.e. weight x reps" + }, + "workoutCompleted": "Entraînement terminé", + "@workoutCompleted": {}, + "formMinMaxValues": "Veuillez entrer une valeur entre {min} et {max}", + "@formMinMaxValues": { + "description": "Error message when the user needs to enter a value between min and max", + "type": "text", + "placeholders": { + "min": { + "type": "int" + }, + "max": { + "type": "int" + } + } + }, + "superset": "Superset", + "@superset": {} } diff --git a/lib/l10n/app_nl.arb b/lib/l10n/app_nl.arb index 6da9385a2..031e49e31 100644 --- a/lib/l10n/app_nl.arb +++ b/lib/l10n/app_nl.arb @@ -694,5 +694,551 @@ "toggleDetails": "Schakel details in", "@toggleDetails": { "description": "Switch to toggle detail / overview" - } + }, + "goToDetailPage": "Ga naar detail pagina", + "@goToDetailPage": {}, + "aboutWhySupportTitle": "Open Source & gratis te gebruiken ❤️", + "@aboutWhySupportTitle": {}, + "aboutDescription": "Bedankt voor het gebruiken van wger! wger is een collaboratief open source project, gemaakt door fitness fans van over de hele wereld.", + "@aboutDescription": { + "description": "Text in the about dialog" + }, + "aboutDonateTitle": "Maak een donatie", + "@aboutDonateTitle": {}, + "aboutDonateText": "Hoewel het project gratis is en dat ook altijd zal blijven, zijn de kosten voor het draaien van de server dat niet! De ontwikkeling vergt bovendien veel tijd en inzet van vrijwilligers. Uw bijdrage dekt deze kosten direct en helpt de betrouwbaarheid van de dienst te waarborgen.", + "@aboutDonateText": {}, + "aboutContributeTitle": "Bijdragen", + "@aboutContributeTitle": {}, + "aboutContributeText": "Alle soorten bijdragen zijn welkom. Of je nu ontwikkelaar bent, vertaler of gewoon een fitnessliefhebber, elke vorm van steun wordt gewaardeerd!", + "@aboutContributeText": {}, + "aboutBugsListTitle": "Meld een probleem of stel een functie voor", + "@aboutBugsListTitle": {}, + "aboutTranslationListTitle": "Vertaal de applicatie", + "@aboutTranslationListTitle": {}, + "aboutSourceListTitle": "Bekijk broncode", + "@aboutSourceListTitle": {}, + "aboutJoinCommunityTitle": "Sluit je aan bij de community", + "@aboutJoinCommunityTitle": {}, + "aboutMastodonTitle": "Mastodon", + "@aboutMastodonTitle": {}, + "aboutDiscordTitle": "Discord", + "@aboutDiscordTitle": {}, + "others": "Anderen", + "@others": {}, + "calendar": "Kalender", + "@calendar": {}, + "goToToday": "Ga naar vandaag", + "@goToToday": { + "description": "Label on button to jump back to 'today' in the calendar widget" + }, + "enterValue": "Voer een waarde in", + "@enterValue": { + "description": "Error message when the user hasn't entered a value on a required field" + }, + "selectEntry": "Selecteer een entry", + "@selectEntry": {}, + "selectExercise": "Selecteer een oefening", + "@selectExercise": { + "description": "Error message when the user hasn't selected an exercise in the form" + }, + "enterCharacters": "Voer tussen {min} en {max} tekens in", + "@enterCharacters": { + "description": "Error message when the user hasn't entered the correct number of characters in a form", + "type": "text", + "placeholders": { + "min": { + "type": "String" + }, + "max": { + "type": "String" + } + } + }, + "formMinMaxValues": "Voer een waarde tussen {min} en {max} in", + "@formMinMaxValues": { + "description": "Error message when the user needs to enter a value between min and max", + "type": "text", + "placeholders": { + "min": { + "type": "int" + }, + "max": { + "type": "int" + } + } + }, + "enterMinCharacters": "Voer minstens {min} tekens in", + "@enterMinCharacters": { + "description": "Error message when the user hasn't entered the minimum amount characters in a form", + "type": "text", + "placeholders": { + "min": { + "type": "String" + } + } + }, + "baseNameEnglish": "Alle oefeningen moeten een basisnaam in het Engels hebben", + "@baseNameEnglish": {}, + "nrOfSets": "Sets per oefening: {nrOfSets}", + "@nrOfSets": { + "description": "Label shown on the slider where the user selects the nr of sets", + "type": "text", + "placeholders": { + "nrOfSets": { + "type": "String" + } + } + }, + "setUnitsAndRir": "Stel eenheden en RiR in", + "@setUnitsAndRir": { + "description": "Label shown on the slider where the user can toggle showing units and RiR", + "type": "text" + }, + "enterValidNumber": "Voer een geldig nummer in", + "@enterValidNumber": { + "description": "Error message when the user has submitted an invalid number (e.g. '3,.,.,.')" + }, + "selectIngredient": "Selecteer een ingrediënt", + "@selectIngredient": { + "description": "Error message when the user hasn't selected an ingredient from the autocompleter" + }, + "recentlyUsedIngredients": "Recent toegevoegde ingrediënten", + "@recentlyUsedIngredients": { + "description": "A message when a user adds a new ingredient to a meal." + }, + "selectImage": "Selecteer een afbeelding", + "@selectImage": { + "description": "Label and error message when the user hasn't selected an image to save" + }, + "optionsLabel": "Opties", + "@optionsLabel": { + "description": "Label for the popup with general app options" + }, + "takePicture": "Neem een foto", + "@takePicture": {}, + "chooseFromLibrary": "Kies uit foto galerij", + "@chooseFromLibrary": {}, + "gallery": "Galerij", + "@gallery": {}, + "addImage": "Afbeelding toevoegen", + "@addImage": {}, + "dataCopied": "Gegevens gekopieerd naar een nieuw item", + "@dataCopied": { + "description": "Snackbar message to show on copying data to a new log entry" + }, + "appUpdateTitle": "Update vereist", + "@appUpdateTitle": {}, + "appUpdateContent": "Deze versie van de app is niet compatibel met de server, update uw applicatie.", + "@appUpdateContent": {}, + "productFound": "Product gevonden", + "@productFound": { + "description": "Header label for dialog when product is found with barcode" + }, + "productFoundDescription": "De barcode hoort bij dit product: {productName}. Wilt u doorgaan?", + "@productFoundDescription": { + "description": "Dialog info when product is found with barcode", + "type": "text", + "placeholders": { + "productName": { + "type": "String" + } + } + }, + "productNotFound": "Product niet gevonden", + "@productNotFound": { + "description": "Header label for dialog when product is not found with barcode" + }, + "productNotFoundDescription": "Het product met de gescande barcode {barcode} is niet gevonden in de wger database", + "@productNotFoundDescription": { + "description": "Dialog info when product is not found with barcode", + "type": "text", + "placeholders": { + "barcode": { + "type": "String" + } + } + }, + "scanBarcode": "Scan barcode", + "@scanBarcode": { + "description": "Label for scan barcode button" + }, + "close": "Sluiten", + "@close": { + "description": "Translation for close" + }, + "identicalExercisePleaseDiscard": "Als je een oefening ziet die identiek is aan degene die je toevoegt, gooi dan je concept weg en bewerk die oefening in plaats daarvan.", + "@identicalExercisePleaseDiscard": {}, + "checkInformationBeforeSubmitting": "Controleer of de ingevoerde gegevens correct zijn voordat u de oefening indient", + "@checkInformationBeforeSubmitting": {}, + "add_exercise_image_license": "Afbeeldingen moeten compatibel zijn met de CC BY SA-licentie. Upload bij twijfel alleen foto's die je zelf hebt gemaakt.", + "@add_exercise_image_license": {}, + "imageDetailsTitle": "Afbeeldingsdetails", + "@imageDetailsTitle": { + "description": "Title for image details form" + }, + "imageDetailsLicenseTitle": "Titel", + "@imageDetailsLicenseTitle": { + "description": "Label for image title field" + }, + "imageDetailsLicenseTitleHint": "Voer afbeeldingsnaam in", + "@imageDetailsLicenseTitleHint": { + "description": "Hint text for image title field" + }, + "imageDetailsSourceLink": "Link naar de bronwebsite", + "@imageDetailsSourceLink": { + "description": "Label for source link field" + }, + "author": "Auteur(s)", + "@author": {}, + "authorHint": "Voer auteursnaam in", + "@authorHint": { + "description": "Hint text for author field" + }, + "imageDetailsAuthorLink": "Link naar de website of het profiel van de auteur", + "@imageDetailsAuthorLink": { + "description": "Label for author link field" + }, + "imageDetailsDerivativeSource": "Link naar de originele bron, als dit een afgeleid werk is", + "@imageDetailsDerivativeSource": { + "description": "Label for derivative source field" + }, + "imageDetailsDerivativeHelp": "Hulptekst ter uitleg van afgeleide werken.", + "@imageDetailsDerivativeHelp": { + "description": "Helper text explaining derivative works" + }, + "imageDetailsImageType": "Afbeeldingstype", + "@imageDetailsImageType": { + "description": "Label for image type selector" + }, + "imageDetailsLicenseNotice": "Door deze afbeelding in te dienen, stemt u ermee in deze vrij te geven onder de CC-BY-SA-4-licentie. De afbeelding moet uw eigen werk zijn of de auteur moet deze hebben vrijgegeven onder een licentie die hiermee compatibel is.", + "@imageDetailsLicenseNotice": {}, + "imageDetailsLicenseNoticeLinkToLicense": "Zie licentie tekst.", + "@imageDetailsLicenseNoticeLinkToLicense": {}, + "imageFormatNotSupported": "{imageFormat} wordt niet ondersteund", + "@imageFormatNotSupported": { + "description": "Label shown on the error container when image format is not supported", + "type": "text", + "placeholders": { + "imageFormat": { + "type": "String" + } + } + }, + "imageFormatNotSupportedDetail": "Afbeeldingen met het formaat {imageFormat} worden nog niet ondersteund.", + "@imageFormatNotSupportedDetail": { + "description": "Label shown on the image preview container when image format is not supported", + "type": "text", + "placeholders": { + "imageFormat": { + "type": "String" + } + } + }, + "add": "toevoegen", + "@add": { + "description": "Add button text" + }, + "variations": "Variaties", + "@variations": { + "description": "Variations of one exercise (e.g. benchpress and benchpress narrow)" + }, + "alsoKnownAs": "Ook bekend als: {aliases}", + "@alsoKnownAs": { + "placeholders": { + "aliases": { + "type": "String" + } + }, + "description": "List of alternative names for an exercise" + }, + "verifiedEmail": "Geverifieerde email", + "@verifiedEmail": {}, + "unVerifiedEmail": "Niet-geverifieerde e-mail", + "@unVerifiedEmail": {}, + "verifiedEmailReason": "Je moet je e-mailadres verifiëren om oefeningen te kunnen doen", + "@verifiedEmailReason": {}, + "verifiedEmailInfo": "Er is een verificatiemail verzonden naar {email}", + "@verifiedEmailInfo": { + "placeholders": { + "email": { + "type": "String" + } + } + }, + "alternativeNames": "Alternatieve namen", + "@alternativeNames": {}, + "oneNamePerLine": "Een naam per lijn", + "@oneNamePerLine": {}, + "whatVariationsExist": "Welke varianten van deze oefening bestaan er, indien van toepassing?", + "@whatVariationsExist": {}, + "previous": "Vorige", + "@previous": {}, + "next": "Volgende", + "@next": {}, + "images": "Afbeeldingen", + "@images": {}, + "language": "Taal", + "@language": {}, + "addExercise": "Voeg oefening toe", + "@addExercise": {}, + "fitInWeek": "In week passen", + "@fitInWeek": {}, + "fitInWeekHelp": "Indien ingeschakeld, zullen de dagen zich herhalen in een wekelijkse cyclus; anders zullen de dagen elkaar opeenvolgend opvolgen, ongeacht het begin van een nieuwe week.", + "@fitInWeekHelp": {}, + "addSuperset": "Superset toevoegen", + "@addSuperset": {}, + "superset": "Superset", + "@superset": {}, + "setHasProgression": "Set heeft progressie", + "@setHasProgression": {}, + "setHasProgressionWarning": "Houd er rekening mee dat het momenteel niet mogelijk is om alle instellingen voor een set te bewerken in de mobiele app of om de automatische voortgang te configureren. Gebruik hiervoor voorlopig de webapp.", + "@setHasProgressionWarning": {}, + "setHasNoExercises": "Deze set heeft nog geen oefeningen!", + "@setHasNoExercises": {}, + "contributeExercise": "Draag een oefening bij", + "@contributeExercise": {}, + "translation": "Vertaling", + "@translation": {}, + "translateExercise": "Vertaal deze oefening", + "@translateExercise": {}, + "baseData": "Basics in Engels", + "@baseData": { + "description": "The base data for an exercise such as category, trained muscles, etc." + }, + "enterTextInLanguage": "Voer de tekst in de juiste taal in!", + "@enterTextInLanguage": {}, + "settingsTitle": "Instellingen", + "@settingsTitle": {}, + "settingsCacheTitle": "Cache", + "@settingsCacheTitle": {}, + "settingsExerciseCacheDescription": "Oefeningscache", + "@settingsExerciseCacheDescription": {}, + "settingsIngredientCacheDescription": "Ingrediënten cache", + "@settingsIngredientCacheDescription": {}, + "settingsCacheDeletedSnackbar": "Cache succesvol geleegd", + "@settingsCacheDeletedSnackbar": {}, + "aboutPageTitle": "Over ons & Support", + "@aboutPageTitle": {}, + "contributeExerciseWarning": "Je kunt alleen oefeningen bijdragen als je account ouder is dan {days} dagen en je e-mailadres is geverifieerd", + "@contributeExerciseWarning": { + "description": "Number of days before which a person can add exercise", + "placeholders": { + "days": { + "type": "String", + "example": "14" + } + } + }, + "simpleMode": "Eenvoudige modus", + "@simpleMode": {}, + "simpleModeHelp": "Verberg enkele van de meer geavanceerde instellingen tijdens het bewerken van oefeningen", + "@simpleModeHelp": {}, + "progressionRules": "Deze oefening heeft voortgangsregels en kan niet worden bewerkt in de mobiele app. Gebruik de webapplicatie om deze oefening te bewerken.", + "@progressionRules": {}, + "cacheWarning": "Vanwege de caching kan het even duren voordat de wijzigingen in de hele applicatie zichtbaar zijn.", + "@cacheWarning": {}, + "textPromptTitle": "Klaar om te starten?", + "@textPromptTitle": {}, + "textPromptSubheading": "Druk op de actieknop om te beginnen", + "@textPromptSubheading": {}, + "abs": "Buikspieren", + "@abs": { + "description": "Generated entry for translation for server strings" + }, + "arms": "Armen", + "@arms": { + "description": "Generated entry for translation for server strings" + }, + "back": "Rug", + "@back": { + "description": "Generated entry for translation for server strings" + }, + "barbell": "Barbell", + "@barbell": { + "description": "Generated entry for translation for server strings" + }, + "bench": "Bench", + "@bench": { + "description": "Generated entry for translation for server strings" + }, + "biceps": "Biceps", + "@biceps": { + "description": "Generated entry for translation for server strings" + }, + "body_weight": "Gewicht", + "@body_weight": { + "description": "Generated entry for translation for server strings" + }, + "calves": "Kuiten", + "@calves": { + "description": "Generated entry for translation for server strings" + }, + "cardio": "Cardio", + "@cardio": { + "description": "Generated entry for translation for server strings" + }, + "chest": "Borst", + "@chest": { + "description": "Generated entry for translation for server strings" + }, + "dumbbell": "Dumbbell", + "@dumbbell": { + "description": "Generated entry for translation for server strings" + }, + "glutes": "Glutes", + "@glutes": { + "description": "Generated entry for translation for server strings" + }, + "gym_mat": "Gym matje", + "@gym_mat": { + "description": "Generated entry for translation for server strings" + }, + "hamstrings": "Hamstrings", + "@hamstrings": { + "description": "Generated entry for translation for server strings" + }, + "incline_bench": "Incline bench", + "@incline_bench": { + "description": "Generated entry for translation for server strings" + }, + "kettlebell": "Kettlebell", + "@kettlebell": { + "description": "Generated entry for translation for server strings" + }, + "kilometers": "Kilometers", + "@kilometers": { + "description": "Generated entry for translation for server strings" + }, + "kilometers_per_hour": "Kilometers Per Uur", + "@kilometers_per_hour": { + "description": "Generated entry for translation for server strings" + }, + "lats": "Lats", + "@lats": { + "description": "Generated entry for translation for server strings" + }, + "legs": "Benen", + "@legs": { + "description": "Generated entry for translation for server strings" + }, + "lower_back": "Onderrug", + "@lower_back": { + "description": "Generated entry for translation for server strings" + }, + "max_reps": "Max Herhalingen", + "@max_reps": { + "description": "Generated entry for translation for server strings" + }, + "miles": "Miles", + "@miles": { + "description": "Generated entry for translation for server strings" + }, + "miles_per_hour": "Miles Per Uur", + "@miles_per_hour": { + "description": "Generated entry for translation for server strings" + }, + "minutes": "Minuten", + "@minutes": { + "description": "Generated entry for translation for server strings" + }, + "plates": "Platen", + "@plates": { + "description": "Generated entry for translation for server strings" + }, + "pull_up_bar": "Pull-up bar", + "@pull_up_bar": { + "description": "Generated entry for translation for server strings" + }, + "quads": "Quads", + "@quads": { + "description": "Generated entry for translation for server strings" + }, + "repetitions": "Herhalingen", + "@repetitions": { + "description": "Generated entry for translation for server strings" + }, + "resistance_band": "Weerstandsband", + "@resistance_band": { + "description": "Generated entry for translation for server strings" + }, + "sz_bar": "SZ-Bar", + "@sz_bar": { + "description": "Generated entry for translation for server strings" + }, + "seconds": "Seconden", + "@seconds": { + "description": "Generated entry for translation for server strings" + }, + "shoulders": "Schouders", + "@shoulders": { + "description": "Generated entry for translation for server strings" + }, + "swiss_ball": "Zwitserse Bal", + "@swiss_ball": { + "description": "Generated entry for translation for server strings" + }, + "triceps": "Triceps", + "@triceps": { + "description": "Generated entry for translation for server strings" + }, + "until_failure": "Tot Falen", + "@until_failure": { + "description": "Generated entry for translation for server strings" + }, + "kg": "kg", + "@kg": { + "description": "Generated entry for translation for server strings" + }, + "lb": "lb", + "@lb": { + "description": "Generated entry for translation for server strings" + }, + "none__bodyweight_exercise_": "geen (lichaamsgewicht)", + "@none__bodyweight_exercise_": { + "description": "Generated entry for translation for server strings" + }, + "log": "Vastleggen", + "@log": { + "description": "Log a specific meal (imperative form)" + }, + "done": "Klaar", + "@done": {}, + "overallChangeWeight": "Algemene verandering", + "@overallChangeWeight": { + "description": "Overall change in weight, added for localization" + }, + "goalTypeMeals": "Van maaltijden", + "@goalTypeMeals": { + "description": "added for localization of Class GoalType's filed meals" + }, + "goalTypeBasic": "Basic", + "@goalTypeBasic": { + "description": "added for localization of Class GoalType's filed basic" + }, + "goalTypeAdvanced": "Geavanceerd", + "@goalTypeAdvanced": { + "description": "added for localization of Class GoalType's filed advanced" + }, + "indicatorRaw": "rauw", + "@indicatorRaw": { + "description": "added for localization of Class Indicator's field text" + }, + "indicatorAvg": "gemiddeld", + "@indicatorAvg": { + "description": "added for localization of Class Indicator's field text" + }, + "endWorkout": "Beëindig workout", + "@endWorkout": { + "description": "Use the imperative, label on button to finish the current workout in gym mode" + }, + "themeMode": "Thema modus", + "@themeMode": {}, + "darkMode": "Altijd donkere modus", + "@darkMode": {}, + "lightMode": "Altijd lichte modus", + "@lightMode": {}, + "systemMode": "Systeem instellingen", + "@systemMode": {}, + "slotEntryTypeMyo": "Myo", + "@slotEntryTypeMyo": {} } diff --git a/lib/main.dart b/lib/main.dart index 1676e3240..21b2bf7c6 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * wger Workout Manager is distributed in the hope that it will be useful, + * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. @@ -35,7 +35,6 @@ import 'package:wger/providers/user.dart'; import 'package:wger/providers/wger_base_riverpod.dart'; import 'package:wger/screens/add_exercise_screen.dart'; import 'package:wger/screens/auth_screen.dart'; -import 'package:wger/screens/configure_plates_screen.dart'; import 'package:wger/screens/dashboard.dart'; import 'package:wger/screens/exercise_screen.dart'; import 'package:wger/screens/exercises_screen.dart'; @@ -54,7 +53,10 @@ import 'package:wger/screens/routine_edit_screen.dart'; import 'package:wger/screens/routine_list_screen.dart'; import 'package:wger/screens/routine_logs_screen.dart'; import 'package:wger/screens/routine_screen.dart'; +import 'package:wger/screens/settings_dashboard_widgets_screen.dart'; +import 'package:wger/screens/settings_plates_screen.dart'; import 'package:wger/screens/splash_screen.dart'; +import 'package:wger/screens/trophy_screen.dart'; import 'package:wger/screens/update_app_screen.dart'; import 'package:wger/screens/weight_screen.dart'; import 'package:wger/theme/theme.dart'; @@ -238,6 +240,9 @@ class MainApp extends StatelessWidget { SettingsPage.routeName: (ctx) => const SettingsPage(), LogOverviewPage.routeName: (ctx) => const LogOverviewPage(), ConfigurePlatesScreen.routeName: (ctx) => const ConfigurePlatesScreen(), + ConfigureDashboardWidgetsScreen.routeName: (ctx) => + const ConfigureDashboardWidgetsScreen(), + TrophyScreen.routeName: (ctx) => const TrophyScreen(), }, localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, diff --git a/lib/models/trophies/trophy.dart b/lib/models/trophies/trophy.dart new file mode 100644 index 000000000..d58f5512a --- /dev/null +++ b/lib/models/trophies/trophy.dart @@ -0,0 +1,66 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:json_annotation/json_annotation.dart'; + +part 'trophy.g.dart'; + +enum TrophyType { time, volume, count, sequence, date, pr, other } + +@JsonSerializable() +class Trophy { + @JsonKey(required: true) + final int id; + + @JsonKey(required: true) + final String uuid; + + @JsonKey(required: true) + final String name; + + @JsonKey(required: true) + final String description; + + @JsonKey(required: true) + final String image; + + @JsonKey(required: true, name: 'trophy_type') + final TrophyType type; + + @JsonKey(required: true, name: 'is_hidden') + final bool isHidden; + + @JsonKey(required: true, name: 'is_progressive') + final bool isProgressive; + + Trophy({ + required this.id, + required this.uuid, + required this.name, + required this.description, + required this.image, + required this.type, + required this.isHidden, + required this.isProgressive, + }); + + // Boilerplate + factory Trophy.fromJson(Map json) => _$TrophyFromJson(json); + + Map toJson() => _$TrophyToJson(this); +} diff --git a/lib/models/trophies/trophy.g.dart b/lib/models/trophies/trophy.g.dart new file mode 100644 index 000000000..23eb2a47a --- /dev/null +++ b/lib/models/trophies/trophy.g.dart @@ -0,0 +1,54 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'trophy.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +Trophy _$TrophyFromJson(Map json) { + $checkKeys( + json, + requiredKeys: const [ + 'id', + 'uuid', + 'name', + 'description', + 'image', + 'trophy_type', + 'is_hidden', + 'is_progressive', + ], + ); + return Trophy( + id: (json['id'] as num).toInt(), + uuid: json['uuid'] as String, + name: json['name'] as String, + description: json['description'] as String, + image: json['image'] as String, + type: $enumDecode(_$TrophyTypeEnumMap, json['trophy_type']), + isHidden: json['is_hidden'] as bool, + isProgressive: json['is_progressive'] as bool, + ); +} + +Map _$TrophyToJson(Trophy instance) => { + 'id': instance.id, + 'uuid': instance.uuid, + 'name': instance.name, + 'description': instance.description, + 'image': instance.image, + 'trophy_type': _$TrophyTypeEnumMap[instance.type]!, + 'is_hidden': instance.isHidden, + 'is_progressive': instance.isProgressive, +}; + +const _$TrophyTypeEnumMap = { + TrophyType.time: 'time', + TrophyType.volume: 'volume', + TrophyType.count: 'count', + TrophyType.sequence: 'sequence', + TrophyType.date: 'date', + TrophyType.pr: 'pr', + TrophyType.other: 'other', +}; diff --git a/lib/models/trophies/user_trophy.dart b/lib/models/trophies/user_trophy.dart new file mode 100644 index 000000000..8e1e7a816 --- /dev/null +++ b/lib/models/trophies/user_trophy.dart @@ -0,0 +1,62 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:json_annotation/json_annotation.dart'; +import 'package:wger/helpers/json.dart'; + +import 'trophy.dart'; +import 'user_trophy_context_data.dart'; + +part 'user_trophy.g.dart'; + +/// A trophy awarded to a user for achieving a specific milestone. + +@JsonSerializable() +class UserTrophy { + @JsonKey(required: true) + final int id; + + @JsonKey(required: true) + final Trophy trophy; + + @JsonKey(required: true, name: 'earned_at', fromJson: utcIso8601ToLocalDate) + final DateTime earnedAt; + + @JsonKey(required: true) + final num progress; + + @JsonKey(required: true, name: 'is_notified') + final bool isNotified; + + @JsonKey(required: true, name: 'context_data') + final ContextData? contextData; + + UserTrophy({ + required this.id, + required this.trophy, + required this.earnedAt, + required this.progress, + required this.isNotified, + this.contextData, + }); + + // Boilerplate + factory UserTrophy.fromJson(Map json) => _$UserTrophyFromJson(json); + + Map toJson() => _$UserTrophyToJson(this); +} diff --git a/lib/models/trophies/user_trophy.g.dart b/lib/models/trophies/user_trophy.g.dart new file mode 100644 index 000000000..97d9da440 --- /dev/null +++ b/lib/models/trophies/user_trophy.g.dart @@ -0,0 +1,40 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'user_trophy.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +UserTrophy _$UserTrophyFromJson(Map json) { + $checkKeys( + json, + requiredKeys: const [ + 'id', + 'trophy', + 'earned_at', + 'progress', + 'is_notified', + 'context_data', + ], + ); + return UserTrophy( + id: (json['id'] as num).toInt(), + trophy: Trophy.fromJson(json['trophy'] as Map), + earnedAt: utcIso8601ToLocalDate(json['earned_at'] as String), + progress: json['progress'] as num, + isNotified: json['is_notified'] as bool, + contextData: json['context_data'] == null + ? null + : ContextData.fromJson(json['context_data'] as Map), + ); +} + +Map _$UserTrophyToJson(UserTrophy instance) => { + 'id': instance.id, + 'trophy': instance.trophy, + 'earned_at': instance.earnedAt.toIso8601String(), + 'progress': instance.progress, + 'is_notified': instance.isNotified, + 'context_data': instance.contextData, +}; diff --git a/lib/models/trophies/user_trophy_context_data.dart b/lib/models/trophies/user_trophy_context_data.dart new file mode 100644 index 000000000..d114e1e1b --- /dev/null +++ b/lib/models/trophies/user_trophy_context_data.dart @@ -0,0 +1,75 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:json_annotation/json_annotation.dart'; +import 'package:wger/helpers/json.dart'; + +part 'user_trophy_context_data.g.dart'; + +/// A trophy awarded to a user for achieving a specific milestone. + +@JsonSerializable() +class ContextData { + @JsonKey(required: true, name: 'log_id') + final int logId; + + @JsonKey(required: true, fromJson: utcIso8601ToLocalDate) + final DateTime date; + + @JsonKey(required: true, name: 'session_id') + final int sessionId; + + @JsonKey(required: true, name: 'exercise_id') + final int exerciseId; + + @JsonKey(required: true, name: 'repetitions_unit_id') + final int repetitionsUnitId; + + @JsonKey(required: true) + final num repetitions; + + @JsonKey(required: true, name: 'weight_unit_id') + final int weightUnitId; + + @JsonKey(required: true) + final num weight; + + @JsonKey(required: true) + final int? iteration; + + @JsonKey(required: true, name: 'one_rep_max_estimate') + final num oneRepMaxEstimate; + + ContextData({ + required this.logId, + required this.date, + required this.sessionId, + required this.exerciseId, + required this.repetitionsUnitId, + required this.repetitions, + required this.weightUnitId, + required this.weight, + this.iteration, + required this.oneRepMaxEstimate, + }); + + // Boilerplate + factory ContextData.fromJson(Map json) => _$ContextDataFromJson(json); + + Map toJson() => _$ContextDataToJson(this); +} diff --git a/lib/models/trophies/user_trophy_context_data.g.dart b/lib/models/trophies/user_trophy_context_data.g.dart new file mode 100644 index 000000000..e1fcc63a4 --- /dev/null +++ b/lib/models/trophies/user_trophy_context_data.g.dart @@ -0,0 +1,50 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'user_trophy_context_data.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +ContextData _$ContextDataFromJson(Map json) { + $checkKeys( + json, + requiredKeys: const [ + 'log_id', + 'date', + 'session_id', + 'exercise_id', + 'repetitions_unit_id', + 'repetitions', + 'weight_unit_id', + 'weight', + 'iteration', + 'one_rep_max_estimate', + ], + ); + return ContextData( + logId: (json['log_id'] as num).toInt(), + date: utcIso8601ToLocalDate(json['date'] as String), + sessionId: (json['session_id'] as num).toInt(), + exerciseId: (json['exercise_id'] as num).toInt(), + repetitionsUnitId: (json['repetitions_unit_id'] as num).toInt(), + repetitions: json['repetitions'] as num, + weightUnitId: (json['weight_unit_id'] as num).toInt(), + weight: json['weight'] as num, + iteration: (json['iteration'] as num?)?.toInt(), + oneRepMaxEstimate: json['one_rep_max_estimate'] as num, + ); +} + +Map _$ContextDataToJson(ContextData instance) => { + 'log_id': instance.logId, + 'date': instance.date.toIso8601String(), + 'session_id': instance.sessionId, + 'exercise_id': instance.exerciseId, + 'repetitions_unit_id': instance.repetitionsUnitId, + 'repetitions': instance.repetitions, + 'weight_unit_id': instance.weightUnitId, + 'weight': instance.weight, + 'iteration': instance.iteration, + 'one_rep_max_estimate': instance.oneRepMaxEstimate, +}; diff --git a/lib/models/trophies/user_trophy_progression.dart b/lib/models/trophies/user_trophy_progression.dart new file mode 100644 index 000000000..6cf115ba2 --- /dev/null +++ b/lib/models/trophies/user_trophy_progression.dart @@ -0,0 +1,67 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:json_annotation/json_annotation.dart'; +import 'package:wger/helpers/json.dart'; +import 'package:wger/models/trophies/trophy.dart'; + +part 'user_trophy_progression.g.dart'; + +@JsonSerializable() +class UserTrophyProgression { + @JsonKey(required: true) + final Trophy trophy; + + @JsonKey(required: true, name: 'is_earned') + final bool isEarned; + + @JsonKey(required: true, name: 'earned_at', fromJson: utcIso8601ToLocalDateNull) + final DateTime? earnedAt; + + /// Progress towards earning the trophy (0-100%) + @JsonKey(required: true) + final num progress; + + /// Current value towards the trophy goal (e.g., number of workouts completed) + @JsonKey(required: true, name: 'current_value', fromJson: stringToNumNull) + num? currentValue; + + /// Target value to achieve the trophy goal + @JsonKey(required: true, name: 'target_value', fromJson: stringToNumNull) + num? targetValue; + + /// Human-readable progress display (e.g., "3 / 10" or "51%") + @JsonKey(required: true, name: 'progress_display') + String? progressDisplay; + + UserTrophyProgression({ + required this.trophy, + required this.isEarned, + required this.earnedAt, + required this.progress, + required this.currentValue, + required this.targetValue, + this.progressDisplay, + }); + + // Boilerplate + factory UserTrophyProgression.fromJson(Map json) => + _$UserTrophyProgressionFromJson(json); + + Map toJson() => _$UserTrophyProgressionToJson(this); +} diff --git a/lib/models/trophies/user_trophy_progression.g.dart b/lib/models/trophies/user_trophy_progression.g.dart new file mode 100644 index 000000000..de2a49e70 --- /dev/null +++ b/lib/models/trophies/user_trophy_progression.g.dart @@ -0,0 +1,45 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'user_trophy_progression.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +UserTrophyProgression _$UserTrophyProgressionFromJson( + Map json, +) { + $checkKeys( + json, + requiredKeys: const [ + 'trophy', + 'is_earned', + 'earned_at', + 'progress', + 'current_value', + 'target_value', + 'progress_display', + ], + ); + return UserTrophyProgression( + trophy: Trophy.fromJson(json['trophy'] as Map), + isEarned: json['is_earned'] as bool, + earnedAt: utcIso8601ToLocalDateNull(json['earned_at'] as String?), + progress: json['progress'] as num, + currentValue: stringToNumNull(json['current_value'] as String?), + targetValue: stringToNumNull(json['target_value'] as String?), + progressDisplay: json['progress_display'] as String?, + ); +} + +Map _$UserTrophyProgressionToJson( + UserTrophyProgression instance, +) => { + 'trophy': instance.trophy, + 'is_earned': instance.isEarned, + 'earned_at': instance.earnedAt?.toIso8601String(), + 'progress': instance.progress, + 'current_value': instance.currentValue, + 'target_value': instance.targetValue, + 'progress_display': instance.progressDisplay, +}; diff --git a/lib/models/workouts/log.dart b/lib/models/workouts/log.dart index 39bf65319..75b002feb 100644 --- a/lib/models/workouts/log.dart +++ b/lib/models/workouts/log.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -41,7 +41,7 @@ class Log { late Exercise exerciseObj; late int routineId; - late int? sessionId; + int? sessionId; int? iteration; int? slotEntryId; num? rir; @@ -49,13 +49,13 @@ class Log { num? repetitions; num? repetitionsTarget; - late int? repetitionsUnitId; - late RepetitionUnit? repetitionsUnitObj; + int? repetitionsUnitId; + RepetitionUnit? repetitionsUnitObj; - late num? weight; + num? weight; num? weightTarget; - late int? weightUnitId; - late WeightUnit? weightUnitObj; + int? weightUnitId; + WeightUnit? weightUnitObj; late DateTime date; @@ -68,20 +68,20 @@ class Log { this.repetitions, this.repetitionsTarget, this.repetitionsUnitId = REP_UNIT_REPETITIONS_ID, - required this.rir, + this.rir, this.rirTarget, this.weight, this.weightTarget, this.weightUnitId = WEIGHT_UNIT_KG, - required this.date, - }); + DateTime? date, + }) : date = date ?? DateTime.now(); - Log.fromSetConfigData(SetConfigData setConfig, , {int? routineId, this.iteration}) { + Log.fromSetConfigData(SetConfigData setConfig, {int? routineId, this.iteration}) { date = DateTime.now(); sessionId = null; slotEntryId = setConfig.slotEntryId; - exerciseBase = setConfig.exercise; + exercise = setConfig.exercise; weight = setConfig.weight; weightTarget = setConfig.weight; @@ -93,13 +93,57 @@ class Log { rir = setConfig.rir; rirTarget = setConfig.rir; - } if (routineId != null) { this.routineId = routineId; } } + Log copyWith({ + String? id, + int? exerciseId, + int? routineId, + int? sessionId, + int? iteration, + int? slotEntryId, + num? rir, + num? rirTarget, + num? repetitions, + num? repetitionsTarget, + int? repetitionsUnitId, + num? weight, + num? weightTarget, + int? weightUnitId, + DateTime? date, + }) { + final out = Log( + id: id ?? this.id, + exerciseId: exerciseId ?? this.exerciseId, + iteration: iteration ?? this.iteration, + slotEntryId: slotEntryId ?? this.slotEntryId, + routineId: routineId ?? this.routineId, + repetitions: repetitions ?? this.repetitions, + repetitionsTarget: repetitionsTarget ?? this.repetitionsTarget, + repetitionsUnitId: repetitionsUnitId ?? this.repetitionsUnitId, + rir: rir ?? this.rir, + rirTarget: rirTarget ?? this.rirTarget, + weight: weight ?? this.weight, + weightTarget: weightTarget ?? this.weightTarget, + weightUnitId: weightUnitId ?? this.weightUnitId, + date: date ?? this.date, + ); + + if (sessionId != null) { + out.sessionId = sessionId; + } + + out.exercise = exerciseObj; + out.repetitionUnit = repetitionsUnitObj; + out.weightUnitObj = weightUnitObj; + + return out; + } + WorkoutLogTableCompanion toCompanion({bool includeId = false}) { return WorkoutLogTableCompanion( id: includeId && id != null ? drift.Value(id!) : const drift.Value.absent(), diff --git a/lib/models/workouts/session.dart b/lib/models/workouts/session.dart index 3d6bd854f..5e28b2c01 100644 --- a/lib/models/workouts/session.dart +++ b/lib/models/workouts/session.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2025 wger Team + * Copyright (c) 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -21,6 +21,7 @@ import 'package:drift/drift.dart' as drift; import 'package:flutter/material.dart'; import 'package:logging/logging.dart'; import 'package:wger/database/powersync/database.dart'; +import 'package:wger/helpers/consts.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/exercises/exercise.dart'; import 'package:wger/models/workouts/log.dart'; diff --git a/lib/models/workouts/slot_data.g.dart b/lib/models/workouts/slot_data.g.dart index 589b2b999..756717e67 100644 --- a/lib/models/workouts/slot_data.g.dart +++ b/lib/models/workouts/slot_data.g.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 wger Team - * - * wger Workout Manager is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - // GENERATED CODE - DO NOT MODIFY BY HAND part of 'slot_data.dart'; diff --git a/lib/providers/auth.dart b/lib/providers/auth.dart index edb73a8d0..3f2e26fa8 100644 --- a/lib/providers/auth.dart +++ b/lib/providers/auth.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -58,7 +58,7 @@ class AuthProvider with ChangeNotifier { static const SERVER_VERSION_URL = 'version'; static const REGISTRATION_URL = 'register'; static const LOGIN_URL = 'login'; - static const TEST_URL = 'userprofile'; + static const USERPROFILE_URL = 'userprofile'; late http.Client client; @@ -150,7 +150,7 @@ class AuthProvider with ChangeNotifier { // Login using the API token if (apiToken != null && apiToken.isNotEmpty) { final response = await client.get( - makeUri(serverUrl, TEST_URL), + makeUri(serverUrl, USERPROFILE_URL), headers: { HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8', HttpHeaders.userAgentHeader: getAppNameHeader(), diff --git a/lib/providers/base_provider.dart b/lib/providers/base_provider.dart index dee257d75..041871aef 100644 --- a/lib/providers/base_provider.dart +++ b/lib/providers/base_provider.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -16,19 +16,27 @@ * along with this program. If not, see . */ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; +import 'dart:math' as math; import 'package:http/http.dart' as http; import 'package:http/http.dart'; +import 'package:logging/logging.dart'; import 'package:wger/core/exceptions/http_exception.dart'; import 'package:wger/providers/auth.dart'; import 'package:wger/providers/helpers.dart'; +/// initial delay for fetch retries, in milliseconds +const FETCH_INITIAL_DELAY = 250; + /// Base provider class. /// /// Provides a couple of comfort functions so we avoid a bit of boilerplate. class WgerBaseProvider { + final _logger = Logger('WgerBaseProvider'); + AuthProvider auth; late http.Client client; @@ -37,7 +45,7 @@ class WgerBaseProvider { this.client = client ?? http.Client(); } - Map getDefaultHeaders({bool includeAuth = false}) { + Map getDefaultHeaders({bool includeAuth = false, String? language}) { final out = { HttpHeaders.contentTypeHeader: 'application/json; charset=UTF-8', HttpHeaders.userAgentHeader: auth.getAppNameHeader(), @@ -47,6 +55,10 @@ class WgerBaseProvider { out[HttpHeaders.authorizationHeader] = 'Token ${auth.token}'; } + if (language != null) { + out[HttpHeaders.acceptLanguageHeader] = language; + } + return out; } @@ -56,31 +68,64 @@ class WgerBaseProvider { } /// Fetch and retrieve the overview list of objects, returns the JSON parsed response - Future fetch(Uri uri) async { - // Future | List> fetch(Uri uri) async { - // Send the request - final response = await client.get( - uri, - headers: getDefaultHeaders(includeAuth: true), - ); + /// with a simple retry mechanism for transient errors. + Future fetch( + Uri uri, { + int maxRetries = 3, + Duration initialDelay = const Duration(milliseconds: 250), + String? language, + }) async { + int attempt = 0; + final random = math.Random(); - // Something wrong with our request - if (response.statusCode >= 400) { - throw WgerHttpException(response); + Future wait(String reason) async { + final backoff = (initialDelay.inMilliseconds * math.pow(2, attempt - 1)).toInt(); + final jitter = random.nextInt((backoff * 0.25).toInt() + 1); // up to 25% jitter + final delay = backoff + jitter; + _logger.info('Retrying fetch for $uri, attempt $attempt (${delay}ms), reason: $reason'); + + await Future.delayed(Duration(milliseconds: delay)); } - // Process the response - return json.decode(utf8.decode(response.bodyBytes)) as dynamic; + while (true) { + try { + final response = await client + .get(uri, headers: getDefaultHeaders(includeAuth: true, language: language)) + .timeout(const Duration(seconds: 5)); + + if (response.statusCode >= 400) { + // Retry on server errors (5xx); e.g. 502 might be transient + if (response.statusCode >= 500 && attempt < maxRetries) { + attempt++; + await wait('status code ${response.statusCode}'); + continue; + } + throw WgerHttpException(response); + } + + return json.decode(utf8.decode(response.bodyBytes)) as dynamic; + } catch (e) { + final isRetryable = + e is SocketException || e is http.ClientException || e is TimeoutException; + if (isRetryable && attempt < maxRetries) { + attempt++; + await wait(e.toString()); + continue; + } + + rethrow; + } + } } /// Fetch and retrieve the overview list of objects, returns the JSON parsed response - Future> fetchPaginated(Uri uri) async { + Future> fetchPaginated(Uri uri, {String? language}) async { final out = []; var url = uri; var allPagesProcessed = false; while (!allPagesProcessed) { - final data = await fetch(url); + final data = await fetch(url, language: language); data['results'].forEach((e) => out.add(e)); diff --git a/lib/providers/body_weight.g.dart b/lib/providers/body_weight.g.dart index 65b8de2e0..95199c0e1 100644 --- a/lib/providers/body_weight.g.dart +++ b/lib/providers/body_weight.g.dart @@ -10,11 +10,11 @@ part of 'body_weight.dart'; // ignore_for_file: type=lint, type=warning @ProviderFor(WeightEntryNotifier) -const weightEntryProvider = WeightEntryNotifierProvider._(); +final weightEntryProvider = WeightEntryNotifierProvider._(); final class WeightEntryNotifierProvider extends $StreamNotifierProvider> { - const WeightEntryNotifierProvider._() + WeightEntryNotifierProvider._() : super( from: null, argument: null, @@ -40,7 +40,6 @@ abstract class _$WeightEntryNotifier extends $StreamNotifier> @$mustCallSuper @override void runBuild() { - final created = build(); final ref = this.ref as $Ref>, List>; final element = ref.element @@ -50,6 +49,6 @@ abstract class _$WeightEntryNotifier extends $StreamNotifier> Object?, Object? >; - element.handleValue(ref, created); + element.handleCreate(ref, build); } } diff --git a/lib/providers/core_data.g.dart b/lib/providers/core_data.g.dart index fc3b25926..df4157c51 100644 --- a/lib/providers/core_data.g.dart +++ b/lib/providers/core_data.g.dart @@ -10,12 +10,12 @@ part of 'core_data.dart'; // ignore_for_file: type=lint, type=warning @ProviderFor(languages) -const languagesProvider = LanguagesProvider._(); +final languagesProvider = LanguagesProvider._(); final class LanguagesProvider extends $FunctionalProvider>, List, Stream>> with $FutureModifier>, $StreamProvider> { - const LanguagesProvider._() + LanguagesProvider._() : super( from: null, argument: null, diff --git a/lib/providers/exercise_data.g.dart b/lib/providers/exercise_data.g.dart index 9bd977d35..74c421b6d 100644 --- a/lib/providers/exercise_data.g.dart +++ b/lib/providers/exercise_data.g.dart @@ -10,12 +10,12 @@ part of 'exercise_data.dart'; // ignore_for_file: type=lint, type=warning @ProviderFor(exercises) -const exercisesProvider = ExercisesProvider._(); +final exercisesProvider = ExercisesProvider._(); final class ExercisesProvider extends $FunctionalProvider>, List, Stream>> with $FutureModifier>, $StreamProvider> { - const ExercisesProvider._() + ExercisesProvider._() : super( from: null, argument: null, @@ -44,7 +44,7 @@ final class ExercisesProvider String _$exercisesHash() => r'3c3bf6b9c2d5d5e9ff2c7fa3776165724f006151'; @ProviderFor(exerciseCategories) -const exerciseCategoriesProvider = ExerciseCategoriesProvider._(); +final exerciseCategoriesProvider = ExerciseCategoriesProvider._(); final class ExerciseCategoriesProvider extends @@ -54,7 +54,7 @@ final class ExerciseCategoriesProvider Stream> > with $FutureModifier>, $StreamProvider> { - const ExerciseCategoriesProvider._() + ExerciseCategoriesProvider._() : super( from: null, argument: null, @@ -83,13 +83,13 @@ final class ExerciseCategoriesProvider String _$exerciseCategoriesHash() => r'0b43e83e3b68d18ae1319bcc9f553d2fed83e3f2'; @ProviderFor(exerciseEquipment) -const exerciseEquipmentProvider = ExerciseEquipmentProvider._(); +final exerciseEquipmentProvider = ExerciseEquipmentProvider._(); final class ExerciseEquipmentProvider extends $FunctionalProvider>, List, Stream>> with $FutureModifier>, $StreamProvider> { - const ExerciseEquipmentProvider._() + ExerciseEquipmentProvider._() : super( from: null, argument: null, @@ -118,12 +118,12 @@ final class ExerciseEquipmentProvider String _$exerciseEquipmentHash() => r'49e42160c8640d68fde7e9d9849f46a8cf6a10f9'; @ProviderFor(exerciseMuscles) -const exerciseMusclesProvider = ExerciseMusclesProvider._(); +final exerciseMusclesProvider = ExerciseMusclesProvider._(); final class ExerciseMusclesProvider extends $FunctionalProvider>, List, Stream>> with $FutureModifier>, $StreamProvider> { - const ExerciseMusclesProvider._() + ExerciseMusclesProvider._() : super( from: null, argument: null, diff --git a/lib/providers/exercise_state_notifier.g.dart b/lib/providers/exercise_state_notifier.g.dart index 4abeb903f..14c4e3ff1 100644 --- a/lib/providers/exercise_state_notifier.g.dart +++ b/lib/providers/exercise_state_notifier.g.dart @@ -10,12 +10,12 @@ part of 'exercise_state_notifier.dart'; // ignore_for_file: type=lint, type=warning @ProviderFor(exerciseStateReady) -const exerciseStateReadyProvider = ExerciseStateReadyProvider._(); +final exerciseStateReadyProvider = ExerciseStateReadyProvider._(); final class ExerciseStateReadyProvider extends $FunctionalProvider, void, FutureOr> with $FutureModifier, $FutureProvider { - const ExerciseStateReadyProvider._() + ExerciseStateReadyProvider._() : super( from: null, argument: null, @@ -43,11 +43,11 @@ final class ExerciseStateReadyProvider String _$exerciseStateReadyHash() => r'4ba35bfced32dc984ea363e2a103eb8660bb4487'; @ProviderFor(ExerciseStateNotifier) -const exerciseStateProvider = ExerciseStateNotifierProvider._(); +final exerciseStateProvider = ExerciseStateNotifierProvider._(); final class ExerciseStateNotifierProvider extends $NotifierProvider { - const ExerciseStateNotifierProvider._() + ExerciseStateNotifierProvider._() : super( from: null, argument: null, @@ -81,7 +81,6 @@ abstract class _$ExerciseStateNotifier extends $Notifier { @$mustCallSuper @override void runBuild() { - final created = build(); final ref = this.ref as $Ref; final element = ref.element @@ -91,6 +90,6 @@ abstract class _$ExerciseStateNotifier extends $Notifier { Object?, Object? >; - element.handleValue(ref, created); + element.handleCreate(ref, build); } } diff --git a/lib/providers/gym_log_state.dart b/lib/providers/gym_log_state.dart new file mode 100644 index 000000000..ec5e04521 --- /dev/null +++ b/lib/providers/gym_log_state.dart @@ -0,0 +1,48 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:clock/clock.dart'; +import 'package:logging/logging.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; +import 'package:wger/models/workouts/log.dart'; + +part 'gym_log_state.g.dart'; + +@Riverpod(keepAlive: true) +class GymLogNotifier extends _$GymLogNotifier { + final _logger = Logger('GymLogNotifier'); + + @override + Log? build() { + _logger.finer('Initializing GymLogNotifier'); + return null; + } + + void setLog(Log log) { + final newLog = log.copyWith(id: null, date: clock.now()); + state = newLog; + } + + void setWeight(num weight) { + state = state?.copyWith(weight: weight); + } + + void setRepetitions(num repetitions) { + state = state?.copyWith(repetitions: repetitions); + } +} diff --git a/lib/providers/gym_log_state.g.dart b/lib/providers/gym_log_state.g.dart new file mode 100644 index 000000000..ffedf6402 --- /dev/null +++ b/lib/providers/gym_log_state.g.dart @@ -0,0 +1,55 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'gym_log_state.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(GymLogNotifier) +final gymLogProvider = GymLogNotifierProvider._(); + +final class GymLogNotifierProvider extends $NotifierProvider { + GymLogNotifierProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'gymLogProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$gymLogNotifierHash(); + + @$internal + @override + GymLogNotifier create() => GymLogNotifier(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(Log? value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$gymLogNotifierHash() => r'5e166c827248e02d55279c7022a4c5a670e9b3dc'; + +abstract class _$GymLogNotifier extends $Notifier { + Log? build(); + @$mustCallSuper + @override + void runBuild() { + final ref = this.ref as $Ref; + final element = + ref.element as $ClassProviderElement, Log?, Object?, Object?>; + element.handleCreate(ref, build); + } +} diff --git a/lib/providers/gym_state.dart b/lib/providers/gym_state.dart index 949a753f8..882df3664 100644 --- a/lib/providers/gym_state.dart +++ b/lib/providers/gym_state.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2025 wger Team + * Copyright (c) 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -25,8 +25,10 @@ import 'package:wger/helpers/shared_preferences.dart'; import 'package:wger/helpers/uuid.dart'; import 'package:wger/models/exercises/exercise.dart'; import 'package:wger/models/workouts/day_data.dart'; +import 'package:wger/models/workouts/log.dart'; import 'package:wger/models/workouts/routine.dart'; import 'package:wger/models/workouts/set_config_data.dart'; +import 'package:wger/providers/gym_log_state.dart'; part 'gym_state.g.dart'; @@ -131,7 +133,11 @@ class SlotPageEntry { this.setConfigData, this.logDone = false, String? uuid, - }) : uuid = uuid ?? uuidV4(); + }) : assert( + type != SlotPageType.log || setConfigData != null, + 'You need to set setConfigData for SlotPageType.log', + ), + uuid = uuid ?? uuidV4(); SlotPageEntry copyWith({ String? uuid, @@ -481,7 +487,7 @@ class GymStateNotifier extends _$GymStateNotifier { pages.add(PageEntry(type: PageType.workoutSummary, pageIndex: pageIndex + 1)); state = state.copyWith(pages: pages); - print(readPageStructure()); + // print(readPageStructure()); _logger.finer('Initialized ${state.pages.length} pages'); } @@ -573,6 +579,17 @@ class GymStateNotifier extends _$GymStateNotifier { void setCurrentPage(int page) { state = state.copyWith(currentPage: page); + + // Ensure that there is a log entry for the current slot entry + final slotEntryPage = state.getSlotEntryPageByIndex(); + if (slotEntryPage == null || slotEntryPage.setConfigData == null) { + return; + } + + final log = Log.fromSetConfigData(slotEntryPage.setConfigData!); + log.routineId = state.routine.id!; + log.iteration = state.iteration; + ref.read(gymLogProvider.notifier).setLog(log); } void setShowExercisePages(bool value) { diff --git a/lib/providers/gym_state.g.dart b/lib/providers/gym_state.g.dart index 1ddf6b8b1..4239a5496 100644 --- a/lib/providers/gym_state.g.dart +++ b/lib/providers/gym_state.g.dart @@ -10,10 +10,10 @@ part of 'gym_state.dart'; // ignore_for_file: type=lint, type=warning @ProviderFor(GymStateNotifier) -const gymStateProvider = GymStateNotifierProvider._(); +final gymStateProvider = GymStateNotifierProvider._(); final class GymStateNotifierProvider extends $NotifierProvider { - const GymStateNotifierProvider._() + GymStateNotifierProvider._() : super( from: null, argument: null, @@ -40,14 +40,13 @@ final class GymStateNotifierProvider extends $NotifierProvider r'8474afce33638bf67570fd64b64e9b5d171804d3'; +String _$gymStateNotifierHash() => r'3a0bb78e9f7e682ba93a40a73b170126b5eb5ca9'; abstract class _$GymStateNotifier extends $Notifier { GymModeState build(); @$mustCallSuper @override void runBuild() { - final created = build(); final ref = this.ref as $Ref; final element = ref.element @@ -57,6 +56,6 @@ abstract class _$GymStateNotifier extends $Notifier { Object?, Object? >; - element.handleValue(ref, created); + element.handleCreate(ref, build); } } diff --git a/lib/providers/network_provider.g.dart b/lib/providers/network_provider.g.dart index c59fd43f3..0ac5578b7 100644 --- a/lib/providers/network_provider.g.dart +++ b/lib/providers/network_provider.g.dart @@ -10,10 +10,10 @@ part of 'network_provider.dart'; // ignore_for_file: type=lint, type=warning @ProviderFor(NetworkStatus) -const networkStatusProvider = NetworkStatusProvider._(); +final networkStatusProvider = NetworkStatusProvider._(); final class NetworkStatusProvider extends $NotifierProvider { - const NetworkStatusProvider._() + NetworkStatusProvider._() : super( from: null, argument: null, @@ -47,10 +47,9 @@ abstract class _$NetworkStatus extends $Notifier { @$mustCallSuper @override void runBuild() { - final created = build(); final ref = this.ref as $Ref; final element = ref.element as $ClassProviderElement, bool, Object?, Object?>; - element.handleValue(ref, created); + element.handleCreate(ref, build); } } diff --git a/lib/providers/routines.dart b/lib/providers/routines.dart index e16f1f120..b0e39f870 100644 --- a/lib/providers/routines.dart +++ b/lib/providers/routines.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by diff --git a/lib/providers/routines.g.dart b/lib/providers/routines.g.dart index f7173a40e..bb510ce7d 100644 --- a/lib/providers/routines.g.dart +++ b/lib/providers/routines.g.dart @@ -10,7 +10,7 @@ part of 'routines.dart'; // ignore_for_file: type=lint, type=warning @ProviderFor(routineWeightUnit) -const routineWeightUnitProvider = RoutineWeightUnitProvider._(); +final routineWeightUnitProvider = RoutineWeightUnitProvider._(); final class RoutineWeightUnitProvider extends @@ -20,7 +20,7 @@ final class RoutineWeightUnitProvider Stream> > with $FutureModifier>, $StreamProvider> { - const RoutineWeightUnitProvider._() + RoutineWeightUnitProvider._() : super( from: null, argument: null, @@ -49,7 +49,7 @@ final class RoutineWeightUnitProvider String _$routineWeightUnitHash() => r'4e2e7b9903338756f5196eaa1081696a59869e86'; @ProviderFor(routineRepetitionUnit) -const routineRepetitionUnitProvider = RoutineRepetitionUnitProvider._(); +final routineRepetitionUnitProvider = RoutineRepetitionUnitProvider._(); final class RoutineRepetitionUnitProvider extends @@ -59,7 +59,7 @@ final class RoutineRepetitionUnitProvider Stream> > with $FutureModifier>, $StreamProvider> { - const RoutineRepetitionUnitProvider._() + RoutineRepetitionUnitProvider._() : super( from: null, argument: null, @@ -88,10 +88,10 @@ final class RoutineRepetitionUnitProvider String _$routineRepetitionUnitHash() => r'7754a0197c3fed27feea2c6d33d5e5a5e1deab45'; @ProviderFor(RoutinesRiverpod) -const routinesRiverpodProvider = RoutinesRiverpodProvider._(); +final routinesRiverpodProvider = RoutinesRiverpodProvider._(); final class RoutinesRiverpodProvider extends $NotifierProvider { - const RoutinesRiverpodProvider._() + RoutinesRiverpodProvider._() : super( from: null, argument: null, @@ -125,7 +125,6 @@ abstract class _$RoutinesRiverpod extends $Notifier { @$mustCallSuper @override void runBuild() { - final created = build(); final ref = this.ref as $Ref; final element = ref.element @@ -135,17 +134,17 @@ abstract class _$RoutinesRiverpod extends $Notifier { Object?, Object? >; - element.handleValue(ref, created); + element.handleCreate(ref, build); } } @ProviderFor(routinesRepository) -const routinesRepositoryProvider = RoutinesRepositoryProvider._(); +final routinesRepositoryProvider = RoutinesRepositoryProvider._(); final class RoutinesRepositoryProvider extends $FunctionalProvider with $Provider { - const RoutinesRepositoryProvider._() + RoutinesRepositoryProvider._() : super( from: null, argument: null, diff --git a/lib/providers/trophies.dart b/lib/providers/trophies.dart new file mode 100644 index 000000000..19289af58 --- /dev/null +++ b/lib/providers/trophies.dart @@ -0,0 +1,179 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:logging/logging.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; +import 'package:wger/helpers/consts.dart'; +import 'package:wger/models/trophies/trophy.dart'; +import 'package:wger/models/trophies/user_trophy.dart'; +import 'package:wger/models/trophies/user_trophy_progression.dart'; +import 'package:wger/providers/wger_base_riverpod.dart'; + +import 'base_provider.dart'; + +part 'trophies.g.dart'; + +class TrophyState { + final _logger = Logger('TrophyState'); + + final List trophies; + final List userTrophies; + final List trophyProgression; + + TrophyState({ + this.trophies = const [], + this.userTrophies = const [], + this.trophyProgression = const [], + }); + + TrophyState copyWith({ + List? trophies, + List? userTrophies, + List? trophyProgression, + }) { + return TrophyState( + trophies: trophies ?? this.trophies, + userTrophies: userTrophies ?? this.userTrophies, + trophyProgression: trophyProgression ?? this.trophyProgression, + ); + } + + List get prTrophies => + userTrophies.where((t) => t.trophy.type == TrophyType.pr).toList(); + + List get nonPrTrophies => + userTrophies.where((t) => t.trophy.type != TrophyType.pr).toList(); +} + +class TrophyRepository { + final _logger = Logger('TrophyRepository'); + + final WgerBaseProvider base; + final trophiesPath = 'trophy'; + final userTrophiesPath = 'user-trophy'; + final userTrophyProgressionPath = 'trophy/progress'; + + TrophyRepository(this.base); + + Future> fetchTrophies({String? language}) async { + try { + final url = base.makeUrl(trophiesPath, query: {'limit': API_MAX_PAGE_SIZE}); + final trophyData = await base.fetchPaginated(url, language: language); + return trophyData.map((e) => Trophy.fromJson(e)).toList(); + } catch (e, stk) { + _logger.warning('Error fetching trophies:', e, stk); + return []; + } + } + + Future> fetchUserTrophies({ + Map? filterQuery, + String? language, + }) async { + final query = {'limit': API_MAX_PAGE_SIZE}; + if (filterQuery != null) { + query.addAll(filterQuery); + } + + try { + final url = base.makeUrl(userTrophiesPath, query: query); + final trophyData = await base.fetchPaginated(url, language: language); + return trophyData.map((e) => UserTrophy.fromJson(e)).toList(); + } catch (e, stk) { + _logger.warning('Error fetching user trophies:'); + _logger.warning(e); + _logger.warning(stk); + return []; + } + } + + Future> fetchProgression({ + Map? filterQuery, + String? language, + }) async { + try { + final url = base.makeUrl(userTrophyProgressionPath, query: filterQuery); + final List data = await base.fetch(url, language: language); + return data.map((e) => UserTrophyProgression.fromJson(e)).toList(); + } catch (e, stk) { + _logger.warning('Error fetching user trophy progression:', e, stk); + return []; + } + } + + List filterByType(List list, TrophyType type) => + list.where((t) => t.type == type).toList(); +} + +@riverpod +TrophyRepository trophyRepository(Ref ref) { + final base = ref.read(wgerBaseProvider); + return TrophyRepository(base); +} + +@Riverpod(keepAlive: true) +final class TrophyStateNotifier extends _$TrophyStateNotifier { + final _logger = Logger('TrophyStateNotifier'); + + @override + TrophyState build() { + return TrophyState(); + } + + Future fetchAll({String? language}) async { + await Future.wait([ + fetchTrophies(language: language), + fetchUserTrophies(language: language), + fetchTrophyProgression(language: language), + ]); + } + + /// Fetch all available trophies + Future> fetchTrophies({String? language}) async { + _logger.finer('Fetching trophies'); + + final repo = ref.read(trophyRepositoryProvider); + final result = await repo.fetchTrophies(language: language); + state = state.copyWith(trophies: result); + return result; + } + + /// Fetch trophies awarded to the user, excludes hidden trophies + Future> fetchUserTrophies({String? language}) async { + _logger.finer('Fetching user trophies'); + + final repo = ref.read(trophyRepositoryProvider); + final result = await repo.fetchUserTrophies( + filterQuery: {'trophy__is_hidden': 'false'}, //'trophy__is_repeatable': 'false' + language: language, + ); + state = state.copyWith(userTrophies: result); + return result; + } + + /// Fetch trophy progression for the user + Future> fetchTrophyProgression({String? language}) async { + _logger.finer('Fetching user trophy progression'); + + // Note that repeatable trophies are filtered out in the backend + final repo = ref.read(trophyRepositoryProvider); + final result = await repo.fetchProgression(language: language); + state = state.copyWith(trophyProgression: result); + return result; + } +} diff --git a/lib/providers/trophies.g.dart b/lib/providers/trophies.g.dart new file mode 100644 index 000000000..3f1ffecd2 --- /dev/null +++ b/lib/providers/trophies.g.dart @@ -0,0 +1,103 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'trophies.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(trophyRepository) +final trophyRepositoryProvider = TrophyRepositoryProvider._(); + +final class TrophyRepositoryProvider + extends $FunctionalProvider + with $Provider { + TrophyRepositoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'trophyRepositoryProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$trophyRepositoryHash(); + + @$internal + @override + $ProviderElement $createElement($ProviderPointer pointer) => + $ProviderElement(pointer); + + @override + TrophyRepository create(Ref ref) { + return trophyRepository(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(TrophyRepository value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$trophyRepositoryHash() => r'0699f0c0f7f324f3ba9b21420d9845a3e3096b61'; + +@ProviderFor(TrophyStateNotifier) +final trophyStateProvider = TrophyStateNotifierProvider._(); + +final class TrophyStateNotifierProvider + extends $NotifierProvider { + TrophyStateNotifierProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'trophyStateProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$trophyStateNotifierHash(); + + @$internal + @override + TrophyStateNotifier create() => TrophyStateNotifier(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(TrophyState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$trophyStateNotifierHash() => r'c80c732272cf843b698f28152f60b9a5f37ee449'; + +abstract class _$TrophyStateNotifier extends $Notifier { + TrophyState build(); + @$mustCallSuper + @override + void runBuild() { + final ref = this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + TrophyState, + Object?, + Object? + >; + element.handleCreate(ref, build); + } +} diff --git a/lib/providers/user.dart b/lib/providers/user.dart index 3765bfe26..5e4004e7e 100644 --- a/lib/providers/user.dart +++ b/lib/providers/user.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -17,7 +17,9 @@ */ import 'dart:async'; +import 'dart:convert'; +import 'package:collection/collection.dart'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:wger/helpers/consts.dart'; @@ -25,6 +27,39 @@ import 'package:wger/helpers/shared_preferences.dart'; import 'package:wger/models/user/profile.dart'; import 'package:wger/providers/base_provider.dart'; +enum DashboardWidget { + trophies('trophies'), + routines('routines'), + nutrition('nutrition'), + weight('weight'), + measurements('measurements'), + calendar('calendar'); + + final String value; + const DashboardWidget(this.value); + + static DashboardWidget? fromString(String s) { + for (final e in DashboardWidget.values) { + if (e.value == s) { + return e; + } + } + return null; + } +} + +class DashboardItem { + final DashboardWidget widget; + bool isVisible; + + DashboardItem(this.widget, {this.isVisible = true}); + + Map toJson() => { + 'widget': widget.value, + 'visible': isVisible, + }; +} + class UserProvider with ChangeNotifier { ThemeMode themeMode = ThemeMode.system; final WgerBaseProvider baseProvider; @@ -33,8 +68,10 @@ class UserProvider with ChangeNotifier { UserProvider(this.baseProvider, {SharedPreferencesAsync? prefs}) { this.prefs = prefs ?? PreferenceHelper.asyncPref; _loadThemeMode(); + _loadDashboardConfig(); } + static const String PREFS_DASHBOARD_CONFIG = 'dashboardConfig'; static const PROFILE_URL = 'userprofile'; static const VERIFY_EMAIL = 'verify-email'; @@ -45,15 +82,6 @@ class UserProvider with ChangeNotifier { profile = null; } - // // change the unit of plates - // void changeUnit({changeTo = 'kg'}) { - // if (changeTo == 'kg') { - // profile?.weightUnitStr = 'lb'; - // } else { - // profile?.weightUnitStr = 'kg'; - // } - // } - // Load theme mode from SharedPreferences Future _loadThemeMode() async { final prefsDarkMode = await prefs.getBool(PREFS_USER_DARK_THEME); @@ -67,6 +95,85 @@ class UserProvider with ChangeNotifier { notifyListeners(); } + // Dashboard configuration + List _dashboardItems = DashboardWidget.values + .map((w) => DashboardItem(w)) + .toList(); + + List get dashboardOrder => _dashboardItems.map((e) => e.widget).toList(); + + Future _loadDashboardConfig() async { + final jsonString = await prefs.getString(PREFS_DASHBOARD_CONFIG); + if (jsonString == null) { + notifyListeners(); + return; + } + + try { + final List decoded = jsonDecode(jsonString); + final List loaded = []; + + for (final item in decoded) { + final widget = DashboardWidget.fromString(item['widget']); + if (widget != null) { + loaded.add( + DashboardItem(widget, isVisible: item['visible'] as bool), + ); + } + } + + // Add any missing widgets (e.g. newly added features) + for (final widget in DashboardWidget.values) { + if (!loaded.any((item) => item.widget == widget)) { + // Try to insert at the original position defined in the enum + // taking into account the current size of the list + var index = DashboardWidget.values.indexOf(widget); + if (index > loaded.length) { + index = loaded.length; + } + loaded.insert(index, DashboardItem(widget)); + } + } + + _dashboardItems = loaded; + } catch (_) { + // parsing failed -> keep defaults + } + notifyListeners(); + } + + Future _saveDashboardConfig() async { + final serializable = _dashboardItems.map((e) => e.toJson()).toList(); + await prefs.setString(PREFS_DASHBOARD_CONFIG, jsonEncode(serializable)); + } + + bool isDashboardWidgetVisible(DashboardWidget key) { + final widget = _dashboardItems.firstWhereOrNull((e) => e.widget == key); + return widget == null || widget.isVisible; + } + + Future setDashboardWidgetVisible(DashboardWidget key, bool visible) async { + final item = _dashboardItems.firstWhereOrNull((e) => e.widget == key); + if (item == null) { + return; + } + + item.isVisible = visible; + await _saveDashboardConfig(); + notifyListeners(); + } + + Future setDashboardOrder(int oldIndex, int newIndex) async { + if (oldIndex < newIndex) { + newIndex -= 1; + } + final item = _dashboardItems.removeAt(oldIndex); + _dashboardItems.insert(newIndex, item); + + await _saveDashboardConfig(); + notifyListeners(); + } + // Change mode on switch button click void setThemeMode(ThemeMode mode) async { themeMode = mode; diff --git a/lib/providers/wger_base_riverpod.dart b/lib/providers/wger_base_riverpod.dart index b2a01d1f5..0c73cbd23 100644 --- a/lib/providers/wger_base_riverpod.dart +++ b/lib/providers/wger_base_riverpod.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2025 wger Team + * Copyright (c) 2025 - 2025 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by diff --git a/lib/providers/workout_logs.g.dart b/lib/providers/workout_logs.g.dart index 96962e07e..7d69be944 100644 --- a/lib/providers/workout_logs.g.dart +++ b/lib/providers/workout_logs.g.dart @@ -10,11 +10,11 @@ part of 'workout_logs.dart'; // ignore_for_file: type=lint, type=warning @ProviderFor(WorkoutLogNotifier) -const workoutLogProvider = WorkoutLogNotifierProvider._(); +final workoutLogProvider = WorkoutLogNotifierProvider._(); final class WorkoutLogNotifierProvider extends $StreamNotifierProvider> { - const WorkoutLogNotifierProvider._() + WorkoutLogNotifierProvider._() : super( from: null, argument: null, @@ -40,7 +40,6 @@ abstract class _$WorkoutLogNotifier extends $StreamNotifier> { @$mustCallSuper @override void runBuild() { - final created = build(); final ref = this.ref as $Ref>, List>; final element = ref.element @@ -50,6 +49,6 @@ abstract class _$WorkoutLogNotifier extends $StreamNotifier> { Object?, Object? >; - element.handleValue(ref, created); + element.handleCreate(ref, build); } } diff --git a/lib/providers/workout_session.g.dart b/lib/providers/workout_session.g.dart index ce8381de2..b5e843dc9 100644 --- a/lib/providers/workout_session.g.dart +++ b/lib/providers/workout_session.g.dart @@ -10,12 +10,12 @@ part of 'workout_session.dart'; // ignore_for_file: type=lint, type=warning @ProviderFor(sessionStateReady) -const sessionStateReadyProvider = SessionStateReadyProvider._(); +final sessionStateReadyProvider = SessionStateReadyProvider._(); final class SessionStateReadyProvider extends $FunctionalProvider, void, FutureOr> with $FutureModifier, $FutureProvider { - const SessionStateReadyProvider._() + SessionStateReadyProvider._() : super( from: null, argument: null, @@ -43,11 +43,11 @@ final class SessionStateReadyProvider String _$sessionStateReadyHash() => r'18a6a7239149a753760d90c35cfcb739aec8a631'; @ProviderFor(WorkoutSessionNotifier) -const workoutSessionProvider = WorkoutSessionNotifierProvider._(); +final workoutSessionProvider = WorkoutSessionNotifierProvider._(); final class WorkoutSessionNotifierProvider extends $StreamNotifierProvider> { - const WorkoutSessionNotifierProvider._() + WorkoutSessionNotifierProvider._() : super( from: null, argument: null, @@ -73,7 +73,6 @@ abstract class _$WorkoutSessionNotifier extends $StreamNotifier>, List>; final element = ref.element @@ -83,6 +82,6 @@ abstract class _$WorkoutSessionNotifier extends $StreamNotifier; - element.handleValue(ref, created); + element.handleCreate(ref, build); } } diff --git a/lib/screens/dashboard.dart b/lib/screens/dashboard.dart index a175a074f..8d9b18ffb 100644 --- a/lib/screens/dashboard.dart +++ b/lib/screens/dashboard.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -17,14 +17,16 @@ */ import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; import 'package:wger/helpers/material.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/providers/user.dart'; import 'package:wger/widgets/core/app_bar.dart'; import 'package:wger/widgets/dashboard/calendar.dart'; import 'package:wger/widgets/dashboard/widgets/measurements.dart'; -import 'package:wger/widgets/dashboard/widgets/network.dart'; import 'package:wger/widgets/dashboard/widgets/nutrition.dart'; import 'package:wger/widgets/dashboard/widgets/routines.dart'; +import 'package:wger/widgets/dashboard/widgets/trophies.dart'; import 'package:wger/widgets/dashboard/widgets/weight.dart'; class DashboardScreen extends StatelessWidget { @@ -32,10 +34,37 @@ class DashboardScreen extends StatelessWidget { static const routeName = '/dashboard'; + Widget _getDashboardWidget(DashboardWidget widget) { + // TODO: DashboardNetworkInfo(), + + switch (widget) { + case DashboardWidget.routines: + return const DashboardRoutineWidget(); + case DashboardWidget.weight: + return const DashboardWeightWidget(); + case DashboardWidget.measurements: + return const DashboardMeasurementWidget(); + case DashboardWidget.calendar: + return const DashboardCalendarWidget(); + case DashboardWidget.nutrition: + return const DashboardNutritionWidget(); + case DashboardWidget.trophies: + return const DashboardTrophiesWidget(); + } + /* + child: Column( + children: user.dashboardOrder + .where((w) => user.isDashboardWidgetVisible(w)) + .map(_getDashboardWidget) + .toList(), + */ + } + @override Widget build(BuildContext context) { final width = MediaQuery.sizeOf(context).width; final isMobile = width < MATERIAL_XS_BREAKPOINT; + final user = Provider.of(context); late final int crossAxisCount; if (width < MATERIAL_XS_BREAKPOINT) { @@ -48,30 +77,22 @@ class DashboardScreen extends StatelessWidget { crossAxisCount = 4; } - final items = [ - DashboardNetworkInfo(), - const DashboardRoutineWidget(), - const DashboardNutritionWidget(), - const DashboardWeightWidget(), - const DashboardMeasurementWidget(), - const DashboardCalendarWidget(), - ]; - return Scaffold( appBar: MainAppBar(AppLocalizations.of(context).labelDashboard), body: Center( child: ConstrainedBox( - constraints: BoxConstraints(maxWidth: MATERIAL_LG_BREAKPOINT.toDouble()), + constraints: const BoxConstraints(maxWidth: MATERIAL_LG_BREAKPOINT), child: isMobile ? ListView.builder( padding: const EdgeInsets.all(10), - itemBuilder: (context, index) => items[index], - itemCount: items.length, + itemBuilder: (context, index) => _getDashboardWidget(user.dashboardOrder[index]), + itemCount: user.dashboardOrder.length, ) : GridView.builder( padding: const EdgeInsets.all(10), - itemBuilder: (context, index) => SingleChildScrollView(child: items[index]), - itemCount: items.length, + itemBuilder: (context, index) => + SingleChildScrollView(child: _getDashboardWidget(user.dashboardOrder[index])), + itemCount: user.dashboardOrder.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: crossAxisCount, childAspectRatio: 0.7, diff --git a/lib/screens/home_tabs_screen.dart b/lib/screens/home_tabs_screen.dart index 4d1bdcf74..7408ac5b8 100644 --- a/lib/screens/home_tabs_screen.dart +++ b/lib/screens/home_tabs_screen.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020, wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -17,7 +17,7 @@ */ import 'package:flutter/material.dart'; -import 'package:flutter_riverpod/flutter_riverpod.dart' as riverpod; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:logging/logging.dart'; import 'package:provider/provider.dart'; @@ -30,6 +30,7 @@ import 'package:wger/providers/gallery.dart'; import 'package:wger/providers/measurement.dart'; import 'package:wger/providers/nutrition.dart'; import 'package:wger/providers/routines.dart'; +import 'package:wger/providers/trophies.dart'; import 'package:wger/providers/user.dart'; import 'package:wger/providers/workout_logs.dart'; import 'package:wger/providers/workout_session.dart'; @@ -39,11 +40,11 @@ import 'package:wger/screens/nutritional_plans_screen.dart'; import 'package:wger/screens/routine_list_screen.dart'; import 'package:wger/screens/weight_screen.dart'; -class EagerInitialization extends riverpod.ConsumerWidget { +class EagerInitialization extends ConsumerWidget { const EagerInitialization(); @override - Widget build(BuildContext context, riverpod.WidgetRef ref) { + Widget build(BuildContext context, WidgetRef ref) { // TODO: do we need all of these here? ref.watch(exerciseStateProvider); ref.watch(workoutSessionProvider); @@ -56,7 +57,7 @@ class EagerInitialization extends riverpod.ConsumerWidget { } } -class HomeTabsScreen extends riverpod.ConsumerStatefulWidget { +class HomeTabsScreen extends ConsumerStatefulWidget { final _logger = Logger('HomeTabsScreen'); HomeTabsScreen(); @@ -67,9 +68,9 @@ class HomeTabsScreen extends riverpod.ConsumerStatefulWidget { _HomeTabsScreenState createState() => _HomeTabsScreenState(); } -class _HomeTabsScreenState extends riverpod.ConsumerState +class _HomeTabsScreenState extends ConsumerState with SingleTickerProviderStateMixin { - late Future _initialData; + Future? _initialData; bool _errorHandled = false; int _selectedIndex = 0; bool _isWideScreen = false; @@ -77,7 +78,6 @@ class _HomeTabsScreenState extends riverpod.ConsumerState @override void initState() { super.initState(); - // Loading data here, since the build method can be called more than once _initialData = _loadEntries(); } @@ -88,6 +88,7 @@ class _HomeTabsScreenState extends riverpod.ConsumerState final size = MediaQuery.sizeOf(context); _isWideScreen = size.width > MATERIAL_XS_BREAKPOINT; + _initialData ??= _loadEntries(); } void _onItemTapped(int index) { @@ -106,7 +107,9 @@ class _HomeTabsScreenState extends riverpod.ConsumerState /// Load initial data from the server Future _loadEntries() async { + final languageCode = Localizations.localeOf(context).languageCode; final authProvider = context.read(); + final trophyNotifier = ref.read(trophyStateProvider.notifier); if (!authProvider.dataInit) { final nutritionPlansProvider = context.read(); @@ -150,6 +153,7 @@ class _HomeTabsScreenState extends riverpod.ConsumerState nutritionPlansProvider.fetchAndSetAllPlansSparse(), routinesProvider.fetchAllRoutinesSparse(), measurementProvider.fetchAndSetAllCategoriesAndEntries(), + trophyNotifier.fetchAll(language: languageCode), ]); // diff --git a/lib/screens/routine_logs_screen.dart b/lib/screens/routine_logs_screen.dart index 16ff916ea..6858955ab 100644 --- a/lib/screens/routine_logs_screen.dart +++ b/lib/screens/routine_logs_screen.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * wger Workout Manager is distributed in the hope that it will be useful, + * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. diff --git a/lib/screens/settings_dashboard_widgets_screen.dart b/lib/screens/settings_dashboard_widgets_screen.dart new file mode 100644 index 000000000..d3be77718 --- /dev/null +++ b/lib/screens/settings_dashboard_widgets_screen.dart @@ -0,0 +1,38 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:wger/core/wide_screen_wrapper.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/widgets/core/settings/dashboard_visibility.dart'; + +class ConfigureDashboardWidgetsScreen extends StatelessWidget { + static const routeName = '/ConfigureDashboardWidgetScreen'; + + const ConfigureDashboardWidgetsScreen({super.key}); + + @override + Widget build(BuildContext context) { + final i18n = AppLocalizations.of(context); + + return Scaffold( + appBar: AppBar(title: Text(i18n.dashboardWidgets)), + body: const WidescreenWrapper(child: SettingsDashboardVisibility()), + ); + } +} diff --git a/lib/screens/configure_plates_screen.dart b/lib/screens/settings_plates_screen.dart similarity index 100% rename from lib/screens/configure_plates_screen.dart rename to lib/screens/settings_plates_screen.dart diff --git a/lib/screens/trophy_screen.dart b/lib/screens/trophy_screen.dart new file mode 100644 index 000000000..5df5344be --- /dev/null +++ b/lib/screens/trophy_screen.dart @@ -0,0 +1,37 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:wger/core/wide_screen_wrapper.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/widgets/core/app_bar.dart'; +import 'package:wger/widgets/trophies/trophies_overview.dart'; + +class TrophyScreen extends StatelessWidget { + const TrophyScreen(); + + static const routeName = '/trophies'; + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: EmptyAppBar(AppLocalizations.of(context).trophies), + body: const WidescreenWrapper(child: TrophiesOverview()), + ); + } +} diff --git a/lib/widgets/core/app_bar.dart b/lib/widgets/core/app_bar.dart index 9072d0b68..f93c32a3f 100644 --- a/lib/widgets/core/app_bar.dart +++ b/lib/widgets/core/app_bar.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -27,6 +27,7 @@ import 'package:wger/providers/gallery.dart'; import 'package:wger/providers/nutrition.dart'; import 'package:wger/providers/user.dart'; import 'package:wger/screens/form_screen.dart'; +import 'package:wger/screens/settings_dashboard_widgets_screen.dart'; import 'package:wger/widgets/core/about.dart'; import 'package:wger/widgets/core/settings.dart'; import 'package:wger/widgets/user/forms.dart'; @@ -77,6 +78,12 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget { return AppBar( title: Text(_title), actions: [ + IconButton( + icon: const Icon(Icons.widgets_outlined), + onPressed: () { + Navigator.of(context).pushNamed(ConfigureDashboardWidgetsScreen.routeName); + }, + ), statusIcon, IconButton( icon: const Icon(Icons.settings), @@ -84,66 +91,7 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget { return showDialog( context: context, builder: (BuildContext context) { - return AlertDialog( - title: Text(AppLocalizations.of(context).optionsLabel), - actions: [ - TextButton( - child: Text( - MaterialLocalizations.of(context).closeButtonLabel, - ), - onPressed: () => Navigator.of(context).pop(), - ), - ], - contentPadding: EdgeInsets.zero, - content: Column( - mainAxisSize: MainAxisSize.min, - children: [ - ListTile( - //dense: true, - leading: const Icon(Icons.person), - title: Text(AppLocalizations.of(context).userProfile), - onTap: () => Navigator.pushNamed( - context, - FormScreen.routeName, - arguments: FormScreenArguments( - AppLocalizations.of(context).userProfile, - UserProfileForm( - context.read().profile!, - ), - ), - ), - ), - ListTile( - leading: const Icon(Icons.settings), - onTap: () => Navigator.of(context).pushNamed(SettingsPage.routeName), - title: Text(AppLocalizations.of(context).settingsTitle), - ), - ListTile( - leading: const Icon(Icons.info), - onTap: () => Navigator.of(context).pushNamed(AboutPage.routeName), - title: Text(AppLocalizations.of(context).aboutPageTitle), - ), - const Divider(), - ListTile( - //dense: true, - leading: const Icon(Icons.exit_to_app), - title: Text(AppLocalizations.of(context).logout), - onTap: () { - final auth = context.read(); - auth.logout(); - // ref.read(routinesChangeProvider).clear(); - context.read().clear(); - // ref.read(bodyWeightStateProvider.notifier).clear(); - context.read().clear(); - context.read().clear(); - - Navigator.of(context).pop(); - Navigator.of(context).pushReplacementNamed('/'); - }, - ), - ], - ), - ); + return const MainSettingsDialog(); }, ); }, @@ -156,6 +104,73 @@ class MainAppBar extends ConsumerWidget implements PreferredSizeWidget { Size get preferredSize => const Size.fromHeight(kToolbarHeight); } +class MainSettingsDialog extends StatelessWidget { + const MainSettingsDialog({super.key}); + + @override + Widget build(BuildContext context) { + return AlertDialog( + title: Text(AppLocalizations.of(context).optionsLabel), + actions: [ + TextButton( + child: Text( + MaterialLocalizations.of(context).closeButtonLabel, + ), + onPressed: () => Navigator.of(context).pop(), + ), + ], + contentPadding: EdgeInsets.zero, + content: Column( + mainAxisSize: MainAxisSize.min, + children: [ + ListTile( + //dense: true, + leading: const Icon(Icons.person), + title: Text(AppLocalizations.of(context).userProfile), + onTap: () => Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + AppLocalizations.of(context).userProfile, + UserProfileForm( + context.read().profile!, + ), + ), + ), + ), + ListTile( + leading: const Icon(Icons.settings), + onTap: () => Navigator.of(context).pushNamed(SettingsPage.routeName), + title: Text(AppLocalizations.of(context).settingsTitle), + ), + ListTile( + leading: const Icon(Icons.info), + onTap: () => Navigator.of(context).pushNamed(AboutPage.routeName), + title: Text(AppLocalizations.of(context).aboutPageTitle), + ), + const Divider(), + ListTile( + //dense: true, + leading: const Icon(Icons.exit_to_app), + title: Text(AppLocalizations.of(context).logout), + onTap: () { + context.read().logout(); + // context.read().clear(); + context.read().clear(); + // context.read().clear(); + context.read().clear(); + context.read().clear(); + + Navigator.of(context).pop(); + Navigator.of(context).pushReplacementNamed('/'); + }, + ), + ], + ), + ); + } +} + /// App bar that only displays a title class EmptyAppBar extends StatelessWidget implements PreferredSizeWidget { final String _title; diff --git a/lib/widgets/core/settings.dart b/lib/widgets/core/settings.dart index 5a7d608e9..ed0ee757a 100644 --- a/lib/widgets/core/settings.dart +++ b/lib/widgets/core/settings.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) wger Team + * Copyright (c) 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * wger Workout Manager is distributed in the hope that it will be useful, + * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. @@ -16,11 +16,10 @@ * along with this program. If not, see . */ -//import 'package:drift/drift.dart'; import 'package:flutter/material.dart'; import 'package:wger/core/wide_screen_wrapper.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; -import 'package:wger/screens/configure_plates_screen.dart'; +import 'package:wger/screens/settings_plates_screen.dart'; import 'package:wger/widgets/core/settings/ingredient_cache.dart'; import 'package:wger/widgets/core/settings/theme.dart'; diff --git a/lib/widgets/core/settings/dashboard_visibility.dart b/lib/widgets/core/settings/dashboard_visibility.dart new file mode 100644 index 000000000..a86b8d5f2 --- /dev/null +++ b/lib/widgets/core/settings/dashboard_visibility.dart @@ -0,0 +1,80 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/providers/user.dart'; + +class SettingsDashboardVisibility extends StatelessWidget { + const SettingsDashboardVisibility({super.key}); + + @override + Widget build(BuildContext context) { + final i18n = AppLocalizations.of(context); + + String getTitle(DashboardWidget w) { + switch (w) { + case DashboardWidget.routines: + return i18n.routines; + case DashboardWidget.weight: + return i18n.weight; + case DashboardWidget.measurements: + return i18n.measurements; + case DashboardWidget.calendar: + return i18n.calendar; + case DashboardWidget.nutrition: + return i18n.nutritionalPlans; + case DashboardWidget.trophies: + return i18n.trophies; + } + } + + return Consumer( + builder: (context, user, _) { + return ReorderableListView( + physics: const NeverScrollableScrollPhysics(), + buildDefaultDragHandles: false, + onReorder: user.setDashboardOrder, + children: user.dashboardOrder.asMap().entries.map((entry) { + final index = entry.key; + final w = entry.value; + + return ListTile( + key: ValueKey(w), + title: Text(getTitle(w)), + leading: IconButton( + icon: user.isDashboardWidgetVisible(w) + ? const Icon(Icons.visibility) + : const Icon(Icons.visibility_off, color: Colors.grey), + onPressed: () => user.setDashboardWidgetVisible( + w, + !user.isDashboardWidgetVisible(w), + ), + ), + trailing: ReorderableDragStartListener( + index: index, + child: const Icon(Icons.drag_handle), + ), + ); + }).toList(), + ); + }, + ); + } +} diff --git a/lib/widgets/dashboard/calendar.dart b/lib/widgets/dashboard/calendar.dart index 88ef13968..a4f8a425b 100644 --- a/lib/widgets/dashboard/calendar.dart +++ b/lib/widgets/dashboard/calendar.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * wger Workout Manager is distributed in the hope that it will be useful, + * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. @@ -169,10 +169,7 @@ class _DashboardCalendarWidgetState extends riverpod.ConsumerState( - context, - listen: false, - ); + final nutritionProvider = context.read(); for (final plan in nutritionProvider.items) { for (final entry in plan.logEntriesValues.entries) { final date = DateFormatLists.format(entry.key); diff --git a/lib/widgets/dashboard/widgets/nothing_found.dart b/lib/widgets/dashboard/widgets/nothing_found.dart index 326d34175..86afc1405 100644 --- a/lib/widgets/dashboard/widgets/nothing_found.dart +++ b/lib/widgets/dashboard/widgets/nothing_found.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * wger Workout Manager is distributed in the hope that it will be useful, + * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. @@ -22,10 +22,10 @@ import 'package:wger/theme/theme.dart'; class NothingFound extends StatelessWidget { final String _title; - final String _titleForm; - final Widget _form; + final String? _titleForm; + final Widget? _form; - const NothingFound(this._title, this._titleForm, this._form); + const NothingFound(this._title, [this._titleForm, this._form]); @override Widget build(BuildContext context) { @@ -35,21 +35,22 @@ class NothingFound extends StatelessWidget { mainAxisAlignment: MainAxisAlignment.center, children: [ Text(_title), - IconButton( - iconSize: 30, - icon: const Icon(Icons.add_box, color: wgerPrimaryButtonColor), - onPressed: () { - Navigator.pushNamed( - context, - FormScreen.routeName, - arguments: FormScreenArguments( - _titleForm, - hasListView: true, - _form, - ), - ); - }, - ), + if (_titleForm != null && _form != null) + IconButton( + iconSize: 30, + icon: const Icon(Icons.add_box, color: wgerPrimaryButtonColor), + onPressed: () { + Navigator.pushNamed( + context, + FormScreen.routeName, + arguments: FormScreenArguments( + _titleForm, + hasListView: true, + _form, + ), + ); + }, + ), ], ), ); diff --git a/lib/widgets/dashboard/widgets/routines.dart b/lib/widgets/dashboard/widgets/routines.dart index d3aaa3fbb..5784ece20 100644 --- a/lib/widgets/dashboard/widgets/routines.dart +++ b/lib/widgets/dashboard/widgets/routines.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * wger Workout Manager is distributed in the hope that it will be useful, + * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. @@ -58,7 +58,7 @@ class _DashboardRoutineWidgetState extends ConsumerState ), subtitle: Text( _hasContent - ? '${dateFormat.format(routine!.start)} - ${dateFormat.format(routine!.end)}' + ? '${dateFormat.format(routine!.start)} - ${dateFormat.format(routine.end)}' : '', ), leading: Icon( diff --git a/lib/widgets/dashboard/widgets/trophies.dart b/lib/widgets/dashboard/widgets/trophies.dart new file mode 100644 index 000000000..42e1cfd4f --- /dev/null +++ b/lib/widgets/dashboard/widgets/trophies.dart @@ -0,0 +1,142 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2020 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/models/trophies/trophy.dart'; +import 'package:wger/providers/trophies.dart'; +import 'package:wger/screens/trophy_screen.dart'; + +class DashboardTrophiesWidget extends ConsumerWidget { + const DashboardTrophiesWidget(); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final trophiesState = ref.read(trophyStateProvider); + final i18n = AppLocalizations.of(context); + + return Card( + color: Colors.transparent, + shadowColor: Colors.transparent, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (trophiesState.nonPrTrophies.isEmpty) + Card( + child: Column( + children: [ + ListTile( + title: Text( + i18n.trophies, + style: Theme.of(context).textTheme.headlineSmall, + ), + // leading: Icon(Icons.widgets_outlined), + ), + Padding( + padding: const EdgeInsets.all(8.0), + child: Text( + i18n.noTrophies, + style: Theme.of(context).textTheme.bodyMedium, + ), + ), + ], + ), + ) + else + SizedBox( + height: 140, + child: ListView.separated( + padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0), + scrollDirection: Axis.horizontal, + itemCount: trophiesState.nonPrTrophies.length, + separatorBuilder: (context, index) => const SizedBox(width: 12), + itemBuilder: (context, index) { + final userTrophy = trophiesState.nonPrTrophies[index]; + + return SizedBox( + width: 220, + child: TrophyCard(trophy: userTrophy.trophy), + ); + }, + ), + ), + ], + ), + ); + } +} + +class TrophyCard extends StatelessWidget { + const TrophyCard({ + super.key, + required this.trophy, + }); + + final Trophy trophy; + + @override + Widget build(BuildContext context) { + return Card.filled( + child: InkWell( + onTap: () { + Navigator.of(context).pushNamed(TrophyScreen.routeName); + }, + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + CircleAvatar( + radius: 30, + backgroundImage: NetworkImage(trophy.image), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + trophy.name, + style: Theme.of(context).textTheme.titleMedium, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 4), + Text( + trophy.description, + style: Theme.of(context).textTheme.bodySmall, + maxLines: 3, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + ], + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/widgets/dashboard/widgets/weight.dart b/lib/widgets/dashboard/widgets/weight.dart index 5856720ee..bef398f31 100644 --- a/lib/widgets/dashboard/widgets/weight.dart +++ b/lib/widgets/dashboard/widgets/weight.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * wger Workout Manager is distributed in the hope that it will be useful, + * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. diff --git a/lib/widgets/routines/forms/routine.dart b/lib/widgets/routines/forms/routine.dart index 3762cec02..cf67bf664 100644 --- a/lib/widgets/routines/forms/routine.dart +++ b/lib/widgets/routines/forms/routine.dart @@ -1,7 +1,25 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:intl/intl.dart'; -import 'package:wger/exceptions/http_exception.dart'; +import 'package:wger/core/exceptions/http_exception.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/errors.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; diff --git a/lib/widgets/routines/gym_mode/log_page.dart b/lib/widgets/routines/gym_mode/log_page.dart index 38a5c644c..804933826 100644 --- a/lib/widgets/routines/gym_mode/log_page.dart +++ b/lib/widgets/routines/gym_mode/log_page.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -25,10 +25,11 @@ import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/workouts/log.dart'; import 'package:wger/models/workouts/set_config_data.dart'; import 'package:wger/models/workouts/slot_entry.dart'; +import 'package:wger/providers/gym_log_state.dart'; import 'package:wger/providers/gym_state.dart'; import 'package:wger/providers/plate_weights.dart'; import 'package:wger/providers/workout_logs.dart'; -import 'package:wger/screens/configure_plates_screen.dart'; +import 'package:wger/screens/settings_plates_screen.dart'; import 'package:wger/widgets/core/core.dart'; import 'package:wger/widgets/core/progress_indicator.dart'; import 'package:wger/widgets/routines/forms/reps_unit.dart'; @@ -37,75 +38,37 @@ import 'package:wger/widgets/routines/forms/weight_unit.dart'; import 'package:wger/widgets/routines/gym_mode/navigation.dart'; import 'package:wger/widgets/routines/plate_calculator.dart'; -class LogPage extends ConsumerStatefulWidget { +class LogPage extends ConsumerWidget { final _logger = Logger('LogPage'); final PageController _controller; - LogPage(this._controller); - - @override - _LogPageState createState() => _LogPageState(); -} - -class _LogPageState extends ConsumerState { final GlobalKey<_LogFormWidgetState> _logFormKey = GlobalKey<_LogFormWidgetState>(); - late FocusNode focusNode; - // Persistent log and current slot-page id to avoid recreating the Log on rebuilds - Log? _currentLog; - String? _currentSlotPageUuid; - @override - void initState() { - super.initState(); - focusNode = FocusNode(); - } - - @override - void dispose() { - focusNode.dispose(); - super.dispose(); - } - - @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { final theme = Theme.of(context); - final state = ref.watch(gymStateProvider); + final gymState = ref.watch(gymStateProvider); final languageCode = Localizations.localeOf(context).languageCode; - final page = state.getPageByIndex(); + final page = gymState.getPageByIndex(); if (page == null) { - widget._logger.info( - 'getPageByIndex for ${state.currentPage} returned null, showing empty container.', + _logger.info( + 'getPageByIndex for ${gymState.currentPage} returned null, showing empty container.', ); return Container(); } - final slotEntryPage = state.getSlotEntryPageByIndex(); + final slotEntryPage = gymState.getSlotEntryPageByIndex(); if (slotEntryPage == null) { - widget._logger.info( - 'getSlotPageByIndex for ${state.currentPage} returned null, showing empty container', + _logger.info( + 'getSlotPageByIndex for ${gymState.currentPage} returned null, showing empty container', ); return Container(); } - final setConfigData = slotEntryPage.setConfigData!; - // Create a Log only when the slot page changed or none exists yet - if (_currentLog == null || _currentSlotPageUuid != slotEntryPage.uuid) { - _currentLog = Log.fromSetConfigData(setConfigData) - ..routineId = state.routine.id! - ..iteration = state.iteration; - _currentSlotPageUuid = slotEntryPage.uuid; - } else { - // Update routine/iteration if needed without creating a new Log - _currentLog! - ..routineId = state.routine.id! - ..iteration = state.iteration; - } - - final log = _currentLog!; + final log = ref.watch(gymLogProvider); // Mark done sets final decorationStyle = slotEntryPage.logDone @@ -115,8 +78,8 @@ class _LogPageState extends ConsumerState { return Column( children: [ NavigationHeader( - log.exerciseObj.getTranslation(languageCode).name, - widget._controller, + log!.exerciseObj.getTranslation(languageCode).name, + _controller, ), Container( @@ -162,16 +125,9 @@ class _LogPageState extends ConsumerState { Text(slotEntryPage.setConfigData!.comment, textAlign: TextAlign.center), const SizedBox(height: 10), Expanded( - child: (state.routine.filterLogsByExercise(log.exerciseId).isNotEmpty) + child: (gymState.routine.filterLogsByExercise(log.exerciseId).isNotEmpty) ? LogsPastLogsWidget( - log: log, - pastLogs: state.routine.filterLogsByExercise(log.exerciseId), - onCopy: (pastLog) { - _logFormKey.currentState?.copyFromPastLog(pastLog); - }, - setStateCallback: (fn) { - setState(fn); - }, + pastLogs: gymState.routine.filterLogsByExercise(log.exerciseId), ) : Container(), ), @@ -184,16 +140,15 @@ class _LogPageState extends ConsumerState { child: Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: LogFormWidget( - controller: widget._controller, + controller: _controller, configData: setConfigData, - log: log, - focusNode: focusNode, + // log: log!, key: _logFormKey, ), ), ), ), - NavigationFooter(widget._controller), + NavigationFooter(_controller), ], ); } @@ -253,68 +208,62 @@ class LogsPlatesWidget extends ConsumerWidget { } } -class LogsRepsWidget extends StatelessWidget { - final TextEditingController controller; - final SetConfigData configData; - final FocusNode focusNode; - final Log log; - final void Function(VoidCallback fn) setStateCallback; - +class LogsRepsWidget extends ConsumerWidget { final _logger = Logger('LogsRepsWidget'); + final num valueChange; + LogsRepsWidget({ super.key, - required this.controller, - required this.configData, - required this.focusNode, - required this.log, - required this.setStateCallback, - }); + num? valueChange, + }) : valueChange = valueChange ?? 1; @override - Widget build(BuildContext context) { - final repsValueChange = configData.repetitionsRounding ?? 1; + Widget build(BuildContext context, WidgetRef ref) { final numberFormat = NumberFormat.decimalPattern(Localizations.localeOf(context).toString()); - final i18n = AppLocalizations.of(context); + final logNotifier = ref.read(gymLogProvider.notifier); + final log = ref.watch(gymLogProvider); + + final currentReps = log?.repetitions; + final repText = currentReps != null ? numberFormat.format(currentReps) : ''; + return Row( children: [ + // "Quick-remove" button IconButton( icon: const Icon(Icons.remove, color: Colors.black), onPressed: () { - final currentValue = numberFormat.tryParse(controller.text) ?? 0; - final newValue = currentValue - repsValueChange; - if (newValue >= 0) { - setStateCallback(() { - log.repetitions = newValue; - controller.text = numberFormat.format(newValue); - }); + final base = currentReps ?? 0; + final newValue = base - valueChange; + if (newValue >= 0 && log != null) { + logNotifier.setRepetitions(newValue); } }, ), + + // Text field Expanded( child: TextFormField( decoration: InputDecoration(labelText: i18n.repetitions), enabled: true, - controller: controller, + key: ValueKey('reps-field-$repText'), + initialValue: repText, keyboardType: textInputTypeDecimal, - focusNode: focusNode, onChanged: (value) { try { final newValue = numberFormat.parse(value); - setStateCallback(() { - log.repetitions = newValue; - }); + logNotifier.setRepetitions(newValue); } on FormatException catch (error) { - _logger.fine('Error parsing repetitions: $error'); + _logger.finer('Error parsing repetitions: $error'); } }, onSaved: (newValue) { - _logger.info('Saving new reps value: $newValue'); - setStateCallback(() { - log.repetitions = numberFormat.parse(newValue!); - }); + if (newValue == null || log == null) { + return; + } + logNotifier.setRepetitions(numberFormat.parse(newValue)); }, validator: (value) { if (numberFormat.tryParse(value ?? '') == null) { @@ -324,19 +273,15 @@ class LogsRepsWidget extends StatelessWidget { }, ), ), + + // "Quick-add" button IconButton( icon: const Icon(Icons.add, color: Colors.black), onPressed: () { - final value = controller.text.isNotEmpty ? controller.text : '0'; - - try { - final newValue = numberFormat.parse(value) + repsValueChange; - setStateCallback(() { - log.repetitions = newValue; - controller.text = numberFormat.format(newValue); - }); - } on FormatException catch (error) { - _logger.fine('Error parsing reps during quick-add: $error'); + final base = currentReps ?? 0; + final newValue = base + valueChange; + if (newValue >= 0 && log != null) { + logNotifier.setRepetitions(newValue); } }, ), @@ -346,76 +291,62 @@ class LogsRepsWidget extends StatelessWidget { } class LogsWeightWidget extends ConsumerWidget { - final TextEditingController controller; - final SetConfigData configData; - final FocusNode focusNode; - final Log log; - final void Function(VoidCallback fn) setStateCallback; - final _logger = Logger('LogsWeightWidget'); + final num valueChange; + LogsWeightWidget({ super.key, - required this.controller, - required this.configData, - required this.focusNode, - required this.log, - required this.setStateCallback, - }); + num? valueChange, + }) : valueChange = valueChange ?? 1.25; @override Widget build(BuildContext context, WidgetRef ref) { - final weightValueChange = configData.weightRounding ?? 1.25; final numberFormat = NumberFormat.decimalPattern(Localizations.localeOf(context).toString()); final i18n = AppLocalizations.of(context); + final plateProvider = ref.read(plateCalculatorProvider.notifier); + final logProvider = ref.read(gymLogProvider.notifier); + final log = ref.watch(gymLogProvider); + + final currentWeight = log?.weight; + final weightText = currentWeight != null ? numberFormat.format(currentWeight) : ''; + return Row( children: [ IconButton( + // "Quick-remove" button icon: const Icon(Icons.remove, color: Colors.black), onPressed: () { - try { - final newValue = numberFormat.parse(controller.text) - weightValueChange; - if (newValue > 0) { - setStateCallback(() { - log.weight = newValue; - controller.text = numberFormat.format(newValue); - ref - .read(plateCalculatorProvider.notifier) - .setWeight( - controller.text == '' ? 0 : newValue, - ); - }); - } - } on FormatException catch (error) { - _logger.fine('Error parsing weight during quick-remove: $error'); + final base = currentWeight ?? 0; + final newValue = base - valueChange; + if (newValue >= 0 && log != null) { + logProvider.setWeight(newValue); } }, ), + + // Text field Expanded( child: TextFormField( + key: ValueKey('weight-field-$weightText'), decoration: InputDecoration(labelText: i18n.weight), - controller: controller, + initialValue: weightText, keyboardType: textInputTypeDecimal, onChanged: (value) { try { final newValue = numberFormat.parse(value); - setStateCallback(() { - log.weight = newValue; - ref - .read(plateCalculatorProvider.notifier) - .setWeight( - controller.text == '' ? 0 : numberFormat.parse(controller.text), - ); - }); + plateProvider.setWeight(newValue); + logProvider.setWeight(newValue); } on FormatException catch (error) { - _logger.fine('Error parsing weight: $error'); + _logger.finer('Error parsing weight: $error'); } }, onSaved: (newValue) { - setStateCallback(() { - log.weight = numberFormat.parse(newValue!); - }); + if (newValue == null || log == null) { + return; + } + logProvider.setWeight(numberFormat.parse(newValue)); }, validator: (value) { if (numberFormat.tryParse(value ?? '') == null) { @@ -425,24 +356,15 @@ class LogsWeightWidget extends ConsumerWidget { }, ), ), + + // "Quick-add" button IconButton( icon: const Icon(Icons.add, color: Colors.black), onPressed: () { - final value = controller.text.isNotEmpty ? controller.text : '0'; - - try { - final newValue = numberFormat.parse(value) + weightValueChange; - setStateCallback(() { - log.weight = newValue; - controller.text = numberFormat.format(newValue); - ref - .read(plateCalculatorProvider.notifier) - .setWeight( - controller.text == '' ? 0 : newValue, - ); - }); - } on FormatException catch (error) { - _logger.fine('Error parsing weight during quick-add: $error'); + final base = currentWeight ?? 0; + final newValue = base + valueChange; + if (log != null) { + logProvider.setWeight(newValue); } }, ), @@ -451,22 +373,19 @@ class LogsWeightWidget extends ConsumerWidget { } } -class LogsPastLogsWidget extends StatelessWidget { - final Log log; +class LogsPastLogsWidget extends ConsumerWidget { final List pastLogs; - final void Function(Log pastLog) onCopy; - final void Function(VoidCallback fn) setStateCallback; const LogsPastLogsWidget({ super.key, - required this.log, required this.pastLogs, - required this.onCopy, - required this.setStateCallback, }); @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { + final logProvider = ref.read(gymLogProvider.notifier); + final dateFormat = DateFormat.yMd(Localizations.localeOf(context).languageCode); + return Container( padding: const EdgeInsets.symmetric(vertical: 8), child: ListView( @@ -480,25 +399,16 @@ class LogsPastLogsWidget extends StatelessWidget { return ListTile( key: ValueKey('past-log-${pastLog.id}'), title: Text(pastLog.repTextNoNl(context)), - subtitle: Text( - DateFormat.yMd(Localizations.localeOf(context).languageCode).format(pastLog.date), - ), + subtitle: Text(dateFormat.format(pastLog.date)), trailing: const Icon(Icons.copy), onTap: () { - setStateCallback(() { - log.rir = pastLog.rir; - log.repetitionUnit = pastLog.repetitionsUnitObj; - log.weightUnit = pastLog.weightUnitObj; - - onCopy(pastLog); - - ScaffoldMessenger.of(context).hideCurrentSnackBar(); - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text(AppLocalizations.of(context).dataCopied), - ), - ); - }); + logProvider.setLog(pastLog); + ScaffoldMessenger.of(context).hideCurrentSnackBar(); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(AppLocalizations.of(context).dataCopied), + ), + ); }, contentPadding: const EdgeInsets.symmetric(horizontal: 40), ); @@ -514,15 +424,11 @@ class LogFormWidget extends ConsumerStatefulWidget { final PageController controller; final SetConfigData configData; - final Log log; - final FocusNode focusNode; LogFormWidget({ super.key, required this.controller, required this.configData, - required this.log, - required this.focusNode, }); @override @@ -533,117 +439,12 @@ class _LogFormWidgetState extends ConsumerState { final _form = GlobalKey(); var _detailed = false; bool _isSaving = false; - late Log _log; - - late final TextEditingController _repetitionsController; - late final TextEditingController _weightController; - - @override - void initState() { - super.initState(); - - _log = widget.log; - _repetitionsController = TextEditingController(); - _weightController = TextEditingController(); - - WidgetsBinding.instance.addPostFrameCallback((_) { - _syncControllersWithWidget(); - }); - } - - @override - void didUpdateWidget(covariant LogFormWidget oldWidget) { - super.didUpdateWidget(oldWidget); - - // If the log or config changed, update internal _log and controllers - if (oldWidget.log != widget.log || oldWidget.configData != widget.configData) { - _log = widget.log; - _syncControllersWithWidget(); - } - } - - void _syncControllersWithWidget() { - final locale = Localizations.localeOf(context).toString(); - final numberFormat = NumberFormat.decimalPattern(locale); - - // Priority: current log -> config defaults -> empty - try { - _repetitionsController.text = widget.log.repetitions != null - ? numberFormat.format(widget.log.repetitions) - : (widget.configData.repetitions != null - ? numberFormat.format(widget.configData.repetitions) - : ''); - - _weightController.text = widget.log.weight != null - ? numberFormat.format(widget.log.weight) - : (widget.configData.weight != null ? numberFormat.format(widget.configData.weight) : ''); - } on Exception catch (e) { - // Defensive fallback: set empty strings if formatting fails - widget._logger.warning('Error syncing controllers: $e'); - _repetitionsController.text = ''; - _weightController.text = ''; - } - } - - @override - void dispose() { - _repetitionsController.dispose(); - _weightController.dispose(); - super.dispose(); - } - - void copyFromPastLog(Log pastLog) { - final locale = Localizations.localeOf(context).toString(); - final numberFormat = NumberFormat.decimalPattern(locale); - - setState(() { - _repetitionsController.text = pastLog.repetitions != null - ? numberFormat.format(pastLog.repetitions) - : ''; - widget._logger.finer('Setting log repetitions to ${_repetitionsController.text}'); - - _weightController.text = pastLog.weight != null ? numberFormat.format(pastLog.weight) : ''; - widget._logger.finer('Setting log weight to ${_weightController.text}'); - - _log.repetitions = pastLog.repetitions; - _log.weight = pastLog.weight; - _log.rir = pastLog.rir; - if (pastLog.repetitionsUnitObj != null) { - _log.repetitionUnit = pastLog.repetitionsUnitObj; - } - if (pastLog.weightUnitObj != null) { - _log.weightUnit = pastLog.weightUnitObj; - } - - widget._logger.finer( - 'Copied to _log: repetitions=${_log.repetitions}, weight=${_log.weight}, repetitionsUnitId=${_log.repetitionsUnitId}, weightUnitId=${_log.weightUnitId}, rir=${_log.rir}', - ); - - // Update plate calculator using the value currently visible in the controllers - try { - final weightValue = _weightController.text.isEmpty - ? 0 - : numberFormat.parse(_weightController.text); - ref.read(plateCalculatorProvider.notifier).setWeight(weightValue); - } catch (e) { - widget._logger.fine('Error updating plate calculator: $e'); - } - }); - - // Ensure subsequent syncs (e.g., didUpdateWidget) don't overwrite these values - WidgetsBinding.instance.addPostFrameCallback((_) { - if (!mounted) { - return; - } - - _syncControllersWithWidget(); - }); - } @override Widget build(BuildContext context) { final i18n = AppLocalizations.of(context); final logProvider = ref.watch(workoutLogProvider.notifier); + final log = ref.watch(gymLogProvider); return Form( key: _form, @@ -661,26 +462,14 @@ class _LogFormWidgetState extends ConsumerState { Flexible( child: LogsRepsWidget( key: const ValueKey('logs-reps-widget'), - controller: _repetitionsController, - configData: widget.configData, - focusNode: widget.focusNode, - log: _log, - setStateCallback: (fn) { - setState(fn); - }, + valueChange: widget.configData.repetitionsRounding, ), ), const SizedBox(width: 8), Flexible( child: LogsWeightWidget( key: const ValueKey('logs-weight-widget'), - controller: _weightController, - configData: widget.configData, - focusNode: widget.focusNode, - log: _log, - setStateCallback: (fn) { - setState(fn); - }, + valueChange: widget.configData.weightRounding, ), ), ], @@ -692,20 +481,14 @@ class _LogFormWidgetState extends ConsumerState { Flexible( child: LogsRepsWidget( key: const ValueKey('logs-reps-widget'), - controller: _repetitionsController, - configData: widget.configData, - focusNode: widget.focusNode, - log: _log, - setStateCallback: (fn) { - setState(fn); - }, + valueChange: widget.configData.repetitionsRounding, ), ), const SizedBox(width: 8), Flexible( child: RepetitionUnitInputWidget( key: const ValueKey('repetition-unit-input-widget'), - _log.repetitionsUnitId, + log!.repetitionsUnitId, onChanged: (v) => {}, ), ), @@ -719,19 +502,13 @@ class _LogFormWidgetState extends ConsumerState { Flexible( child: LogsWeightWidget( key: const ValueKey('logs-weight-widget'), - controller: _weightController, - configData: widget.configData, - focusNode: widget.focusNode, - log: _log, - setStateCallback: (fn) { - setState(fn); - }, + valueChange: widget.configData.weightRounding, ), ), const SizedBox(width: 8), Flexible( child: WeightUnitInputWidget( - _log.weightUnitId, + log!.weightUnitId, onChanged: (v) => {}, key: const ValueKey('weight-unit-input-widget'), ), @@ -742,13 +519,9 @@ class _LogFormWidgetState extends ConsumerState { if (_detailed) RiRInputWidget( key: const ValueKey('rir-input-widget'), - _log.rir, + log!.rir, onChanged: (value) { - if (value == '') { - _log.rir = null; - } else { - _log.rir = num.parse(value); - } + log.rir = value == '' ? null : num.parse(value); }, ), SwitchListTile( @@ -779,7 +552,7 @@ class _LogFormWidgetState extends ConsumerState { final gymState = ref.read(gymStateProvider); final gymProvider = ref.read(gymStateProvider.notifier); - logProvider.addEntry(_log); + logProvider.addEntry(log!); final page = gymState.getSlotEntryPageByIndex()!; gymProvider.markSlotPageAsDone(page.uuid, isDone: true); diff --git a/lib/widgets/routines/gym_mode/navigation.dart b/lib/widgets/routines/gym_mode/navigation.dart index d2572b52f..9639c3d05 100644 --- a/lib/widgets/routines/gym_mode/navigation.dart +++ b/lib/widgets/routines/gym_mode/navigation.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * wger Workout Manager is distributed in the hope that it will be useful, + * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. @@ -28,7 +28,12 @@ class NavigationHeader extends StatelessWidget { final String _title; final bool showEndWorkoutButton; - const NavigationHeader(this._title, this._controller, {this.showEndWorkoutButton = true}); + const NavigationHeader( + this._title, + this._controller, { + this.showEndWorkoutButton = true, + super.key, + }); @override Widget build(BuildContext context) { diff --git a/lib/widgets/routines/gym_mode/session_page.dart b/lib/widgets/routines/gym_mode/session_page.dart index f1789a87c..6e3b1284e 100644 --- a/lib/widgets/routines/gym_mode/session_page.dart +++ b/lib/widgets/routines/gym_mode/session_page.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -19,14 +19,12 @@ import 'package:clock/clock.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; -import 'package:provider/provider.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/helpers/date.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; -import 'package:wger/models/workouts/routine.dart'; import 'package:wger/models/workouts/session.dart'; import 'package:wger/providers/gym_state.dart'; -import 'package:wger/providers/routines.dart'; +import 'package:wger/providers/workout_session.dart'; import 'package:wger/widgets/routines/forms/session.dart'; import 'package:wger/widgets/routines/gym_mode/navigation.dart'; @@ -41,7 +39,7 @@ class SessionPage extends ConsumerStatefulWidget { class _SessionPageState extends ConsumerState { late Future _initData; - late Routine _routine; + List sessions = []; @override void initState() { @@ -50,8 +48,7 @@ class _SessionPageState extends ConsumerState { } Future _reloadRoutineData() async { - final gymState = ref.read(gymStateProvider); - _routine = await context.read().fetchAndSetRoutineFull(gymState.routine.id!); + sessions = await ref.read(workoutSessionProvider.future); } @override @@ -71,18 +68,16 @@ class _SessionPageState extends ConsumerState { } else if (snapshot.hasError) { return Center(child: Text('Error: ${snapshot.error}')); } else { - final session = _routine.sessions - .map((sessionApi) => sessionApi.session) - .firstWhere( - (s) => s.date.isSameDayAs(clock.now()), - orElse: () => WorkoutSession( - dayId: gymState.dayId, - date: clock.now(), - routineId: gymState.routine.id, - timeStart: gymState.startTime, - timeEnd: TimeOfDay.fromDateTime(clock.now()), - ), - ); + final session = sessions.firstWhere( + (s) => s.date.isSameDayAs(clock.now()) && s.routineId == gymState.routine.id, + orElse: () => WorkoutSession( + dayId: gymState.dayId, + date: clock.now(), + routineId: gymState.routine.id, + timeStart: gymState.startTime, + timeEnd: TimeOfDay.fromDateTime(clock.now()), + ), + ); return Column( children: [ @@ -90,7 +85,7 @@ class _SessionPageState extends ConsumerState { Padding( padding: const EdgeInsets.symmetric(horizontal: 15), child: SessionForm( - gymState.routine.id, + gymState.routine.id!, onSaved: () => widget._controller.nextPage( duration: DEFAULT_ANIMATION_DURATION, curve: DEFAULT_ANIMATION_CURVE, diff --git a/lib/widgets/routines/gym_mode/summary.dart b/lib/widgets/routines/gym_mode/summary.dart index 4b021ac3b..044ac35cc 100644 --- a/lib/widgets/routines/gym_mode/summary.dart +++ b/lib/widgets/routines/gym_mode/summary.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020, 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -23,10 +23,12 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:logging/logging.dart'; import 'package:wger/helpers/date.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/models/trophies/user_trophy.dart'; import 'package:wger/models/workouts/routine.dart'; import 'package:wger/models/workouts/session.dart'; import 'package:wger/providers/gym_state.dart'; import 'package:wger/providers/routines.dart'; +import 'package:wger/providers/trophies.dart'; import 'package:wger/widgets/core/progress_indicator.dart'; import 'package:wger/widgets/routines/gym_mode/navigation.dart'; @@ -35,7 +37,6 @@ import '../logs/muscle_groups.dart'; class WorkoutSummary extends ConsumerStatefulWidget { final _logger = Logger('WorkoutSummary'); - final PageController _controller; WorkoutSummary(this._controller); @@ -47,26 +48,39 @@ class WorkoutSummary extends ConsumerStatefulWidget { class _WorkoutSummaryState extends ConsumerState { late Future _initData; late Routine _routine; + bool _didInit = false; @override void initState() { super.initState(); - _initData = _reloadRoutineData(); } - Future _reloadRoutineData() async { + @override + void didChangeDependencies() { + super.didChangeDependencies(); + if (!_didInit) { + final languageCode = Localizations.localeOf(context).languageCode; + _initData = _reloadRoutineData(languageCode); + _didInit = true; + } + } + + Future _reloadRoutineData(String languageCode) async { widget._logger.fine('Loading routine data'); final gymState = ref.read(gymStateProvider); _routine = await ref .read(routinesRiverpodProvider.notifier) - .fetchAndSetRoutineFull( - gymState.routine.id!, - ); + .fetchAndSetRoutineFull(gymState.routine.id!); + + final trophyNotifier = ref.read(trophyStateProvider.notifier); + await trophyNotifier.fetchUserTrophies(language: languageCode); } @override Widget build(BuildContext context) { + final trophyState = ref.watch(trophyStateProvider); + return Column( children: [ NavigationHeader( @@ -81,13 +95,18 @@ class _WorkoutSummaryState extends ConsumerState { if (snapshot.connectionState == ConnectionState.waiting) { return const BoxedProgressIndicator(); } else if (snapshot.hasError) { - return Center(child: Text('Error: ${snapshot.error}: ${snapshot.stackTrace}')); + widget._logger.warning(snapshot.error); + widget._logger.warning(snapshot.stackTrace); + return Center(child: Text('Error: ${snapshot.error}')); } else if (snapshot.connectionState == ConnectionState.done) { - return WorkoutSessionStats( - _routine.sessions.firstWhereOrNull( - (s) => s.date.isSameDayAs(clock.now()), - ), + final session = _routine.sessions.firstWhereOrNull( + (s) => s.date.isSameDayAs(clock.now()), ); + final userTrophies = trophyState.prTrophies + .where((t) => t.contextData?.sessionId.toString() == session?.id) + .toList(); + + return WorkoutSessionStats(session, userTrophies); } return const Center(child: Text('Unexpected state!')); @@ -103,19 +122,18 @@ class _WorkoutSummaryState extends ConsumerState { class WorkoutSessionStats extends ConsumerWidget { final _logger = Logger('WorkoutSessionStats'); final WorkoutSession? _session; + final List _userPrTrophies; - WorkoutSessionStats(this._session, {super.key}); + WorkoutSessionStats(this._session, this._userPrTrophies, {super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final i18n = AppLocalizations.of(context); + final theme = Theme.of(context); if (_session == null) { return Center( - child: Text( - 'Nothing logged yet.', - style: Theme.of(context).textTheme.titleMedium, - ), + child: Text('Nothing logged yet.', style: Theme.of(context).textTheme.titleMedium), ); } @@ -159,16 +177,19 @@ class WorkoutSessionStats extends ConsumerWidget { ), ], ), - // const SizedBox(height: 16), - // InfoCard( - // title: 'Personal Records', - // value: prCount.toString(), - // color: theme.colorScheme.tertiaryContainer, - // ), + if (_userPrTrophies.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 10), + child: InfoCard( + title: i18n.personalRecords, + value: _userPrTrophies.length.toString(), + color: theme.colorScheme.tertiaryContainer, + ), + ), const SizedBox(height: 10), MuscleGroupsCard(_session.logs), const SizedBox(height: 10), - ExercisesCard(_session), + ExercisesCard(_session, _userPrTrophies), FilledButton( onPressed: () { ref.read(gymStateProvider.notifier).clear(); diff --git a/lib/widgets/routines/logs/day_logs_container.dart b/lib/widgets/routines/logs/day_logs_container.dart index c2881f3d3..1399b689c 100644 --- a/lib/widgets/routines/logs/day_logs_container.dart +++ b/lib/widgets/routines/logs/day_logs_container.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020, 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -17,31 +17,52 @@ */ import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:wger/helpers/date.dart'; import 'package:wger/helpers/errors.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/workouts/routine.dart'; +import 'package:wger/providers/trophies.dart'; +import '../gym_mode/summary.dart'; import 'exercise_log_chart.dart'; import 'muscle_groups.dart'; import 'session_info.dart'; -class DayLogWidget extends StatelessWidget { +class DayLogWidget extends ConsumerWidget { final DateTime _date; final Routine _routine; const DayLogWidget(this._date, this._routine); @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { + final i18n = AppLocalizations.of(context); + final theme = Theme.of(context); + final trophyState = ref.read(trophyStateProvider); + final session = _routine.sessions.firstWhere( (s) => s.date.isSameDayAs(_date), ); final exercises = session.exercises; + final prTrophies = trophyState.prTrophies + .where((t) => t.contextData?.sessionId.toString() == session.id) + .toList(); + return Column( spacing: 10, children: [ Card(child: SessionInfo(session)), + if (prTrophies.isNotEmpty) + SizedBox( + width: double.infinity, + child: InfoCard( + title: i18n.personalRecords, + value: prTrophies.length.toString(), + color: theme.colorScheme.tertiaryContainer, + ), + ), MuscleGroupsCard(session.logs), Column( @@ -66,7 +87,17 @@ class DayLogWidget extends StatelessWidget { (log) => Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Text(log.repTextNoNl(context)), + Row( + children: [ + if (prTrophies.any((t) => t.contextData?.logId == log.id)) + Icon( + Icons.emoji_events, + color: theme.colorScheme.primary, + size: 20, + ), + Text(log.repTextNoNl(context)), + ], + ), IconButton( icon: const Icon(Icons.delete), key: ValueKey('delete-log-${log.id}'), diff --git a/lib/widgets/routines/logs/exercises_expansion_card.dart b/lib/widgets/routines/logs/exercises_expansion_card.dart index ed33327e9..b92b503d3 100644 --- a/lib/widgets/routines/logs/exercises_expansion_card.dart +++ b/lib/widgets/routines/logs/exercises_expansion_card.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020, 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -20,13 +20,15 @@ import 'package:flutter/material.dart'; import 'package:wger/helpers/i18n.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/exercises/exercise.dart'; +import 'package:wger/models/trophies/user_trophy.dart'; import 'package:wger/models/workouts/log.dart'; import 'package:wger/models/workouts/session.dart'; class ExercisesCard extends StatelessWidget { final WorkoutSession session; + final List userPrTrophies; - const ExercisesCard(this.session, {super.key}); + const ExercisesCard(this.session, this.userPrTrophies, {super.key}); @override Widget build(BuildContext context) { @@ -44,7 +46,11 @@ class ExercisesCard extends StatelessWidget { const SizedBox(height: 16), ...exercises.map((exercise) { final logs = session.logs.where((log) => log.exerciseId == exercise.id).toList(); - return _ExerciseExpansionTile(exercise: exercise, logs: logs); + return _ExerciseExpansionTile( + exercise: exercise, + logs: logs, + userPrTrophies: userPrTrophies, + ); }), ], ), @@ -57,8 +63,10 @@ class _ExerciseExpansionTile extends StatelessWidget { const _ExerciseExpansionTile({ required this.exercise, required this.logs, + required this.userPrTrophies, }); + final List userPrTrophies; final Exercise exercise; final List logs; @@ -66,6 +74,7 @@ class _ExerciseExpansionTile extends StatelessWidget { Widget build(BuildContext context) { final languageCode = Localizations.localeOf(context).languageCode; final theme = Theme.of(context); + final i18n = AppLocalizations.of(context); final topSet = logs.isEmpty ? null @@ -77,21 +86,21 @@ class _ExerciseExpansionTile extends StatelessWidget { return ExpansionTile( // leading: const Icon(Icons.fitness_center), title: Text(exercise.getTranslation(languageCode).name, style: theme.textTheme.titleMedium), - subtitle: Text('Top set: $topSetWeight $topSetWeightUnit'), - children: logs.map((log) => _SetDataRow(log: log)).toList(), + subtitle: Text(i18n.topSet('$topSetWeight $topSetWeightUnit')), + children: logs.map((log) => _SetDataRow(log: log, userPrTrophies: userPrTrophies)).toList(), ); } } class _SetDataRow extends StatelessWidget { - const _SetDataRow({required this.log}); + const _SetDataRow({required this.log, required this.userPrTrophies}); final Log log; + final List userPrTrophies; @override Widget build(BuildContext context) { final theme = Theme.of(context); - final i18n = AppLocalizations.of(context); return Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), @@ -103,6 +112,8 @@ class _SetDataRow extends StatelessWidget { log.repTextNoNl(context), style: theme.textTheme.bodyMedium, ), + if (userPrTrophies.any((trophy) => trophy.contextData?.logId == log.id)) + Icon(Icons.emoji_events, color: theme.colorScheme.primary, size: 20), // if (log.volume() > 0) // Text( // '${log.volume().toStringAsFixed(0)} ${getServerStringTranslation(log.weightUnitObj!.name, context)}', diff --git a/lib/widgets/routines/logs/log_overview_routine.dart b/lib/widgets/routines/logs/log_overview_routine.dart index 3329b8a9e..5989f195a 100644 --- a/lib/widgets/routines/logs/log_overview_routine.dart +++ b/lib/widgets/routines/logs/log_overview_routine.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2025 wger Team + * Copyright (c) 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * wger Workout Manager is distributed in the hope that it will be useful, + * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. @@ -18,20 +18,26 @@ import 'package:clock/clock.dart'; import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:table_calendar/table_calendar.dart'; import 'package:wger/helpers/consts.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/workouts/routine.dart'; +import 'package:wger/providers/trophies.dart'; import 'package:wger/theme/theme.dart'; import 'package:wger/widgets/routines/logs/day_logs_container.dart'; -class WorkoutLogs extends StatelessWidget { +class WorkoutLogs extends ConsumerWidget { final Routine _routine; const WorkoutLogs(this._routine); @override - Widget build(BuildContext context) { + Widget build(BuildContext context, WidgetRef ref) { + final languageCode = Localizations.localeOf(context).languageCode; + final trophyNotifier = ref.read(trophyStateProvider.notifier); + trophyNotifier.fetchUserTrophies(language: languageCode); + return ListView( padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 8), children: [ diff --git a/lib/widgets/trophies/trophies_overview.dart b/lib/widgets/trophies/trophies_overview.dart new file mode 100644 index 000000000..4f37f087e --- /dev/null +++ b/lib/widgets/trophies/trophies_overview.dart @@ -0,0 +1,179 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 - 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:wger/helpers/material.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/models/trophies/user_trophy_progression.dart'; +import 'package:wger/providers/trophies.dart'; + +class TrophiesOverview extends ConsumerWidget { + const TrophiesOverview({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final trophyState = ref.watch(trophyStateProvider); + final i18n = AppLocalizations.of(context); + + // Responsive grid: determine columns based on screen width + final width = MediaQuery.widthOf(context); + int crossAxisCount = 1; + if (width <= MATERIAL_XS_BREAKPOINT) { + crossAxisCount = 2; + } else if (width > MATERIAL_XS_BREAKPOINT && width < MATERIAL_MD_BREAKPOINT) { + crossAxisCount = 3; + } else if (width >= MATERIAL_MD_BREAKPOINT && width < MATERIAL_LG_BREAKPOINT) { + crossAxisCount = 4; + } else { + crossAxisCount = 5; + } + + // If empty, show placeholder + if (trophyState.trophyProgression.isEmpty) { + return Center( + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Text( + i18n.noTrophies, + style: Theme.of(context).textTheme.bodyLarge, + textAlign: TextAlign.center, + ), + ), + ); + } + + return RepaintBoundary( + child: GridView.builder( + padding: const EdgeInsets.all(12), + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: crossAxisCount, + ), + key: const ValueKey('trophy-grid'), + itemCount: trophyState.trophyProgression.length, + itemBuilder: (context, index) { + return _TrophyCardImage(userProgression: trophyState.trophyProgression[index]); + }, + ), + ); + } +} + +class _TrophyCardImage extends StatelessWidget { + final UserTrophyProgression userProgression; + + const _TrophyCardImage({required this.userProgression}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colorScheme = theme.colorScheme; + + final double progress = (userProgression.progress.toDouble() / 100.0).clamp(0.0, 1.0); + + return Opacity( + opacity: userProgression.isEarned ? 1.0 : 0.5, + child: Card( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: BorderSide( + color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.18), + width: userProgression.isEarned ? 1.2 : 0, + ), + ), + child: Stack( + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 6.0), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + SizedBox( + width: 70, + height: 70, + child: ClipOval( + child: Image.network( + userProgression.trophy.image, + fit: BoxFit.cover, + errorBuilder: (context, error, stackTrace) => Center( + child: Icon(Icons.emoji_events, size: 28, color: colorScheme.primary), + ), + ), + ), + ), + + Text( + userProgression.trophy.name, + style: theme.textTheme.titleSmall?.copyWith(fontWeight: FontWeight.w600), + textAlign: TextAlign.center, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 4), + + Text( + userProgression.trophy.description, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.textTheme.bodySmall?.color, + ), + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 8), + + if (userProgression.trophy.isProgressive && !userProgression.isEarned) + Tooltip( + message: 'Progress: ${userProgression.progressDisplay}', + child: SizedBox( + height: 6, + child: ClipRRect( + borderRadius: BorderRadius.circular(6), + child: LinearProgressIndicator( + value: progress, + minHeight: 6, + valueColor: AlwaysStoppedAnimation(colorScheme.primary), + backgroundColor: colorScheme.onSurface.withAlpha((0.06 * 255).round()), + ), + ), + ), + ), + ], + ), + ), + if (userProgression.isEarned) + Positioned( + top: 6, + right: 6, + child: Container( + width: 28, + height: 28, + decoration: const BoxDecoration( + color: Colors.green, + shape: BoxShape.circle, + ), + child: const Icon(Icons.check, size: 16, color: Colors.white), + ), + ), + ], + ), + ), + ); + } +} diff --git a/pubspec.lock b/pubspec.lock index 15e9cd85f..fcb321108 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -25,14 +25,6 @@ packages: url: "https://pub.dev" source: hosted version: "0.1.11" - analyzer_plugin: - dependency: transitive - description: - name: analyzer_plugin - sha256: "08cfefa90b4f4dd3b447bda831cecf644029f9f8e22820f6ee310213ebe2dd53" - url: "https://pub.dev" - source: hosted - version: "0.13.10" archive: dependency: transitive description: @@ -193,14 +185,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.4" - ci: - dependency: transitive - description: - name: ci - sha256: "145d095ce05cddac4d797a158bc4cf3b6016d1fe63d8c3d2fbd7212590adca13" - url: "https://pub.dev" - source: hosted - version: "0.1.0" cider: dependency: "direct dev" description: @@ -313,38 +297,6 @@ packages: url: "https://pub.dev" source: hosted version: "1.0.8" - custom_lint: - dependency: "direct dev" - description: - name: custom_lint - sha256: "751ee9440920f808266c3ec2553420dea56d3c7837dd2d62af76b11be3fcece5" - url: "https://pub.dev" - source: hosted - version: "0.8.1" - custom_lint_builder: - dependency: transitive - description: - name: custom_lint_builder - sha256: "1128db6f58e71d43842f3b9be7465c83f0c47f4dd8918f878dd6ad3b72a32072" - url: "https://pub.dev" - source: hosted - version: "0.8.1" - custom_lint_core: - dependency: transitive - description: - name: custom_lint_core - sha256: "85b339346154d5646952d44d682965dfe9e12cae5febd706f0db3aa5010d6423" - url: "https://pub.dev" - source: hosted - version: "0.8.1" - custom_lint_visitor: - dependency: transitive - description: - name: custom_lint_visitor - sha256: "91f2a81e9f0abb4b9f3bb529f78b6227ce6050300d1ae5b1e2c69c66c7a566d8" - url: "https://pub.dev" - source: hosted - version: "1.0.0+8.4.0" dart_style: dependency: transitive description: @@ -389,10 +341,10 @@ packages: dependency: "direct main" description: name: equatable - sha256: "567c64b3cb4cf82397aac55f4f0cbd3ca20d77c6c03bedbc4ceaddc08904aef7" + sha256: "3e0141505477fd8ad55d6eb4e7776d3fe8430be8e497ccb1521370c3f21a3e2b" url: "https://pub.dev" source: hosted - version: "2.0.7" + version: "2.0.8" fake_async: dependency: transitive description: @@ -572,10 +524,10 @@ packages: dependency: "direct main" description: name: flutter_riverpod - sha256: "9e2d6907f12cc7d23a846847615941bddee8709bf2bfd274acdf5e80bcf22fde" + sha256: "38ec6c303e2c83ee84512f5fc2a82ae311531021938e63d7137eccc107bf3c02" url: "https://pub.dev" source: hosted - version: "3.0.3" + version: "3.1.0" flutter_staggered_grid_view: dependency: "direct main" description: @@ -687,14 +639,6 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.2" - hotreloader: - dependency: transitive - description: - name: hotreloader - sha256: bc167a1163807b03bada490bfe2df25b0d744df359227880220a5cbd04e5734b - url: "https://pub.dev" - source: hosted - version: "4.3.0" html: dependency: transitive description: @@ -1160,26 +1104,26 @@ packages: dependency: "direct main" description: name: powersync - sha256: "6856132dcb41a7fa35721d616f4256a9b923be2041ddf186f7c8eea11518cada" + sha256: "5023a9a68ea2f01f1fdf7c05c84ea7f966574a84a5ee368cde2570497ae51e0f" url: "https://pub.dev" source: hosted - version: "1.16.2" + version: "1.17.0" powersync_core: dependency: transitive description: name: powersync_core - sha256: b984a813621c6e13a101bf1b178751eae9061da3c3dcca2bbcf447293efbfd27 + sha256: "20ff37895eff15c8f9791c76b90364c4a1cb18c55dc50d96024e44507d435e2e" url: "https://pub.dev" source: hosted - version: "1.6.2" + version: "1.7.0" powersync_flutter_libs: dependency: transitive description: name: powersync_flutter_libs - sha256: "75810a25439ddab613dbb88311c2fcad809376711a991469c05124cecc09d2e1" + sha256: cf039113be13ecb6a9fa9831415436526a40ac6461babcb904a759140b1776d9 url: "https://pub.dev" source: hosted - version: "0.4.13" + version: "0.4.14" process: dependency: transitive description: @@ -1248,50 +1192,34 @@ packages: dependency: transitive description: name: riverpod - sha256: c406de02bff19d920b832bddfb8283548bfa05ce41c59afba57ce643e116aa59 + sha256: "16ff608d21e8ea64364f2b7c049c94a02ab81668f78845862b6e88b71dd4935a" url: "https://pub.dev" source: hosted - version: "3.0.3" + version: "3.1.0" riverpod_analyzer_utils: dependency: transitive description: name: riverpod_analyzer_utils - sha256: a0f68adb078b790faa3c655110a017f9a7b7b079a57bbd40f540e80dce5fcd29 + sha256: "947b05d04c52a546a2ac6b19ef2a54b08520ff6bdf9f23d67957a4c8df1c3bc0" url: "https://pub.dev" source: hosted - version: "1.0.0-dev.7" + version: "1.0.0-dev.8" riverpod_annotation: dependency: "direct main" description: name: riverpod_annotation - sha256: "7230014155777fc31ba3351bc2cb5a3b5717b11bfafe52b1553cb47d385f8897" + sha256: cc1474bc2df55ec3c1da1989d139dcef22cd5e2bd78da382e867a69a8eca2e46 url: "https://pub.dev" source: hosted - version: "3.0.3" + version: "4.0.0" riverpod_generator: dependency: "direct dev" description: name: riverpod_generator - sha256: "49894543a42cf7a9954fc4e7366b6d3cb2e6ec0fa07775f660afcdd92d097702" + sha256: e43b1537229cc8f487f09b0c20d15dba840acbadcf5fc6dad7ad5e8ab75950dc url: "https://pub.dev" source: hosted - version: "3.0.3" - riverpod_lint: - dependency: "direct dev" - description: - name: riverpod_lint - sha256: "7ef9c43469e9b5ac4e4c3b24d7c30642e47ce1b12cd7dcdd643534db0a72ed13" - url: "https://pub.dev" - source: hosted - version: "3.0.3" - rxdart: - dependency: transitive - description: - name: rxdart - sha256: "5c3004a4a8dbb94bd4bf5412a4def4acdaa12e12f269737a5751369e12d1a962" - url: "https://pub.dev" - source: hosted - version: "0.28.0" + version: "4.0.0+1" shared_preferences: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index fd81e7143..1dfb79b8e 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -21,7 +21,7 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev # - the version number is taken from the git tag vX.Y.Z # - the build number is computed by reading the last one from the play store # and increasing by one -version: 1.9.3+130 +version: 1.10.0+170 environment: sdk: '>=3.8.0 <4.0.0' @@ -37,7 +37,7 @@ dependencies: collection: ^1.18.0 cupertino_icons: ^1.0.8 drift: ^2.30.0 - equatable: ^2.0.7 + equatable: ^2.0.8 fl_chart: ^1.1.1 flex_color_scheme: ^8.3.1 flutter_html: ^3.0.0 @@ -66,13 +66,13 @@ dependencies: version: ^3.0.2 video_player: ^2.10.1 logging: ^1.3.0 - flutter_riverpod: ^3.0.3 + flutter_riverpod: ^3.1.0 + riverpod_annotation: ^4.0.0 drift_sqlite_async: ^0.2.5 - riverpod_annotation: ^3.0.3 stream_transform: ^2.1.1 state_notifier: ^1.0.0 connectivity_plus: ^7.0.0 - powersync: ^1.16.2 + powersync: ^1.17.0 dev_dependencies: flutter_test: @@ -88,9 +88,7 @@ dev_dependencies: mockito: ^5.4.4 network_image_mock: ^2.1.1 shared_preferences_platform_interface: ^2.0.0 - riverpod_generator: ^3.0.3 - riverpod_lint: ^3.0.3 - custom_lint: ^0.8.0 + riverpod_generator: ^4.0.0+1 # Script to read out unused translations #translations_cleaner: ^0.0.5 diff --git a/test/core/http_exception_test.dart b/test/core/http_exception_test.dart index 26b7a7541..30ae455c8 100644 --- a/test/core/http_exception_test.dart +++ b/test/core/http_exception_test.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020 - 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -25,20 +25,24 @@ import 'package:wger/core/exceptions/http_exception.dart'; void main() { group('WgerHttpException', () { test('parses valid JSON response', () { + // Arrange final resp = http.Response( '{"foo":"bar"}', 400, headers: {HttpHeaders.contentTypeHeader: 'application/json'}, ); + // Act final ex = WgerHttpException(resp); + // Assert expect(ex.type, ErrorType.json); expect(ex.errors['foo'], 'bar'); expect(ex.toString(), contains('WgerHttpException')); }); test('falls back on malformed JSON', () { + // Arrange const body = '{"foo":'; final resp = http.Response( body, @@ -46,13 +50,16 @@ void main() { headers: {HttpHeaders.contentTypeHeader: 'application/json'}, ); + // Act final ex = WgerHttpException(resp); + // Assert expect(ex.type, ErrorType.json); expect(ex.errors['unknown_error'], body); }); - test('detects HTML response', () { + test('detects HTML response from headers', () { + // Arrange const body = 'Error'; final resp = http.Response( body, @@ -60,16 +67,39 @@ void main() { headers: {HttpHeaders.contentTypeHeader: 'text/html; charset=utf-8'}, ); + // Act final ex = WgerHttpException(resp); + // Assert + expect(ex.type, ErrorType.html); + expect(ex.htmlError, body); + }); + + test('detects HTML response from content', () { + // Arrange + const body = 'Error'; + final resp = http.Response( + body, + 500, + headers: {HttpHeaders.contentTypeHeader: 'text/foo; charset=utf-8'}, + ); + + // Act + final ex = WgerHttpException(resp); + + // Assert expect(ex.type, ErrorType.html); expect(ex.htmlError, body); }); test('fromMap sets errors and type', () { + // Arrange final map = {'field': 'value'}; + + // Act final ex = WgerHttpException.fromMap(map); + // Assert expect(ex.type, ErrorType.json); expect(ex.errors, map); }); diff --git a/test/core/settings_dashboard_visibility_test.dart b/test/core/settings_dashboard_visibility_test.dart new file mode 100644 index 000000000..1aedab97e --- /dev/null +++ b/test/core/settings_dashboard_visibility_test.dart @@ -0,0 +1,117 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; +import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/providers/base_provider.dart'; +import 'package:wger/providers/user.dart'; +import 'package:wger/widgets/core/settings/dashboard_visibility.dart'; + +import 'settings_dashboard_visibility_test.mocks.dart'; + +@GenerateMocks([WgerBaseProvider]) +void main() { + late UserProvider userProvider; + late MockWgerBaseProvider mockBaseProvider; + + setUp(() { + SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); + mockBaseProvider = MockWgerBaseProvider(); + userProvider = UserProvider(mockBaseProvider); + }); + + Widget createWidget() { + return ChangeNotifierProvider.value( + value: userProvider, + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SettingsDashboardVisibility(), + ), + ), + ); + } + + testWidgets('renders list of dashboard widgets', (tester) async { + await tester.pumpWidget(createWidget()); + await tester.pumpAndSettle(); + + // Verify all items are present + expect(find.byType(ListTile), findsNWidgets(DashboardWidget.values.length)); + expect(find.text('Routines'), findsOneWidget); + }); + + testWidgets('toggle visibility updates provider', (tester) async { + await tester.pumpWidget(createWidget()); + await tester.pumpAndSettle(); + + // Routines should be visible initally (default is true) + expect(userProvider.isDashboardWidgetVisible(DashboardWidget.routines), true); + + // Find the visibility icon for Routines + final routineTile = find.byKey(const ValueKey(DashboardWidget.routines)); + final iconBtn = find.descendant(of: routineTile, matching: find.byType(IconButton)); + + // Check icon is 'visibility' + expect(find.descendant(of: iconBtn, matching: find.byIcon(Icons.visibility)), findsOneWidget); + + // Tap to toggle + await tester.tap(iconBtn); + await tester.pump(); // re-render + + // Check provider state + expect(userProvider.isDashboardWidgetVisible(DashboardWidget.routines), false); + + // Check icon is 'visibility_off' + expect( + find.descendant(of: iconBtn, matching: find.byIcon(Icons.visibility_off)), + findsOneWidget, + ); + }); + + // Reordering test is a bit flaky without full drag setup, but we can try + testWidgets('dragging reorders items', (tester) async { + await tester.pumpWidget(createWidget()); + await tester.pumpAndSettle(); + + // Initial order: trophies, routines, nutrition, weight... + expect(userProvider.dashboardOrder[0], DashboardWidget.trophies); + expect(userProvider.dashboardOrder[1], DashboardWidget.routines); + + // Find drag handle for Trophies (index 0) + final handleFinder = find.byIcon(Icons.drag_handle); + final firstHandle = handleFinder.at(0); + + // Drag first item down + await tester.drag(firstHandle, const Offset(0, 100)); // Drag down enough to swap + await tester.pumpAndSettle(); + + // Verify order changed + // 100px drag seems to skip 2 items (trophies moves to index 2) + // [routines, nutrition, trophies, ...] + expect(userProvider.dashboardOrder[0], DashboardWidget.routines); + expect(userProvider.dashboardOrder[1], DashboardWidget.nutrition); + expect(userProvider.dashboardOrder[2], DashboardWidget.trophies); + }); +} diff --git a/test/core/settings_dashboard_visibility_test.mocks.dart b/test/core/settings_dashboard_visibility_test.mocks.dart new file mode 100644 index 000000000..bc9ac783c --- /dev/null +++ b/test/core/settings_dashboard_visibility_test.mocks.dart @@ -0,0 +1,182 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/core/settings_dashboard_visibility_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i5; + +import 'package:http/http.dart' as _i3; +import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/providers/auth.dart' as _i2; +import 'package:wger/providers/base_provider.dart' as _i4; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { + _FakeClient_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeUri_2 extends _i1.SmartFake implements Uri { + _FakeUri_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { + _FakeResponse_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +/// A class which mocks [WgerBaseProvider]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { + MockWgerBaseProvider() { + _i1.throwOnMissingStub(this); + } + + @override + _i2.AuthProvider get auth => + (super.noSuchMethod( + Invocation.getter(#auth), + returnValue: _FakeAuthProvider_0(this, Invocation.getter(#auth)), + ) + as _i2.AuthProvider); + + @override + _i3.Client get client => + (super.noSuchMethod( + Invocation.getter(#client), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), + ) + as _i3.Client); + + @override + set auth(_i2.AuthProvider? value) => super.noSuchMethod( + Invocation.setter(#auth, value), + returnValueForMissingStub: null, + ); + + @override + set client(_i3.Client? value) => super.noSuchMethod( + Invocation.setter(#client, value), + returnValueForMissingStub: null, + ); + + @override + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => + (super.noSuchMethod( + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + #language: language, + }), + returnValue: {}, + ) + as Map); + + @override + Uri makeUrl( + String? path, { + int? id, + String? objectMethod, + Map? query, + }) => + (super.noSuchMethod( + Invocation.method( + #makeUrl, + [path], + {#id: id, #objectMethod: objectMethod, #query: query}, + ), + returnValue: _FakeUri_2( + this, + Invocation.method( + #makeUrl, + [path], + {#id: id, #objectMethod: objectMethod, #query: query}, + ), + ), + ) + as Uri); + + @override + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => + (super.noSuchMethod( + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), + returnValue: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => + (super.noSuchMethod( + Invocation.method(#fetchPaginated, [uri], {#language: language}), + returnValue: _i5.Future>.value([]), + ) + as _i5.Future>); + + @override + _i5.Future> post(Map? data, Uri? uri) => + (super.noSuchMethod( + Invocation.method(#post, [data, uri]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future> patch( + Map? data, + Uri? uri, + ) => + (super.noSuchMethod( + Invocation.method(#patch, [data, uri]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future<_i3.Response> deleteRequest(String? url, int? id) => + (super.noSuchMethod( + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#deleteRequest, [url, id]), + ), + ), + ) + as _i5.Future<_i3.Response>); +} diff --git a/test/core/settings_test.dart b/test/core/settings_test.dart index b66e19c12..28e4072e0 100644 --- a/test/core/settings_test.dart +++ b/test/core/settings_test.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * wger Workout Manager is distributed in the hope that it will be useful, + * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. @@ -45,6 +45,9 @@ void main() { setUp(() { when(mockUserProvider.themeMode).thenReturn(ThemeMode.system); + when( + mockSharedPreferences.getString(UserProvider.PREFS_DASHBOARD_CONFIG), + ).thenAnswer((_) async => null); when(mockNutritionProvider.ingredients).thenReturn([ingredient1, ingredient2]); }); @@ -76,18 +79,23 @@ void main() { group('Theme settings', () { test('Default theme is system', () async { when(mockSharedPreferences.getBool(PREFS_USER_DARK_THEME)).thenAnswer((_) async => null); - final userProvider = await UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); + final userProvider = UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); + await Future.delayed(const Duration(milliseconds: 50)); // wait for async prefs load expect(userProvider.themeMode, ThemeMode.system); }); test('Loads light theme', () async { when(mockSharedPreferences.getBool(PREFS_USER_DARK_THEME)).thenAnswer((_) async => false); - final userProvider = await UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); + final userProvider = UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); + await Future.delayed(const Duration(milliseconds: 50)); // wait for async prefs load expect(userProvider.themeMode, ThemeMode.light); }); test('Saves theme to prefs', () { when(mockSharedPreferences.getBool(any)).thenAnswer((_) async => null); + when( + mockSharedPreferences.getString('dashboardWidgetVisibility'), + ).thenAnswer((_) async => null); final userProvider = UserProvider(MockWgerBaseProvider(), prefs: mockSharedPreferences); userProvider.setThemeMode(ThemeMode.dark); verify(mockSharedPreferences.setBool(PREFS_USER_DARK_THEME, true)).called(1); diff --git a/test/core/settings_test.mocks.dart b/test/core/settings_test.mocks.dart index 62f24f472..57f6bc5a6 100644 --- a/test/core/settings_test.mocks.dart +++ b/test/core/settings_test.mocks.dart @@ -487,6 +487,14 @@ class MockUserProvider extends _i1.Mock implements _i14.UserProvider { ) as _i8.SharedPreferencesAsync); + @override + List<_i14.DashboardWidget> get dashboardOrder => + (super.noSuchMethod( + Invocation.getter(#dashboardOrder), + returnValue: <_i14.DashboardWidget>[], + ) + as List<_i14.DashboardWidget>); + @override set themeMode(_i15.ThemeMode? value) => super.noSuchMethod( Invocation.setter(#themeMode, value), @@ -515,6 +523,35 @@ class MockUserProvider extends _i1.Mock implements _i14.UserProvider { returnValueForMissingStub: null, ); + @override + bool isDashboardWidgetVisible(_i14.DashboardWidget? key) => + (super.noSuchMethod( + Invocation.method(#isDashboardWidgetVisible, [key]), + returnValue: false, + ) + as bool); + + @override + _i12.Future setDashboardWidgetVisible( + _i14.DashboardWidget? key, + bool? visible, + ) => + (super.noSuchMethod( + Invocation.method(#setDashboardWidgetVisible, [key, visible]), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), + ) + as _i12.Future); + + @override + _i12.Future setDashboardOrder(int? oldIndex, int? newIndex) => + (super.noSuchMethod( + Invocation.method(#setDashboardOrder, [oldIndex, newIndex]), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), + ) + as _i12.Future); + @override void setThemeMode(_i15.ThemeMode? mode) => super.noSuchMethod( Invocation.method(#setThemeMode, [mode]), @@ -610,10 +647,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -644,17 +685,30 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { as Uri); @override - _i12.Future fetch(Uri? uri) => + _i12.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i12.Future.value(), ) as _i12.Future); @override - _i12.Future> fetchPaginated(Uri? uri) => + _i12.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i12.Future>.value([]), ) as _i12.Future>); diff --git a/test/core/validators_test.mocks.dart b/test/core/validators_test.mocks.dart index d7e3c1ac4..f6139a553 100644 --- a/test/core/validators_test.mocks.dart +++ b/test/core/validators_test.mocks.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 wger Team - * - * wger Workout Manager is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - // Mocks generated by Mockito 5.4.6 from annotations // in wger/test/core/validators_test.dart. // Do not manually edit this file. @@ -422,6 +404,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get dashboardWidgets => + (super.noSuchMethod( + Invocation.getter(#dashboardWidgets), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#dashboardWidgets), + ), + ) + as String); + @override String get labelDashboard => (super.noSuchMethod( @@ -785,6 +778,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get trophies => + (super.noSuchMethod( + Invocation.getter(#trophies), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#trophies), + ), + ) + as String); + @override String get routines => (super.noSuchMethod( @@ -1114,6 +1118,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get personalRecords => + (super.noSuchMethod( + Invocation.getter(#personalRecords), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#personalRecords), + ), + ) + as String); + @override String get gymMode => (super.noSuchMethod( @@ -2192,6 +2207,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String get noTrophies => + (super.noSuchMethod( + Invocation.getter(#noTrophies), + returnValue: _i3.dummyValue( + this, + Invocation.getter(#noTrophies), + ), + ) + as String); + @override String get noWeightEntries => (super.noSuchMethod( @@ -3850,6 +3876,17 @@ class MockAppLocalizations extends _i1.Mock implements _i2.AppLocalizations { ) as String); + @override + String topSet(String? value) => + (super.noSuchMethod( + Invocation.method(#topSet, [value]), + returnValue: _i3.dummyValue( + this, + Invocation.method(#topSet, [value]), + ), + ) + as String); + @override String durationHoursMinutes(int? hours, int? minutes) => (super.noSuchMethod( diff --git a/test/exercises/contribute_exercise_image_test.mocks.dart b/test/exercises/contribute_exercise_image_test.mocks.dart index c3685ed3e..58b8b260c 100644 --- a/test/exercises/contribute_exercise_image_test.mocks.dart +++ b/test/exercises/contribute_exercise_image_test.mocks.dart @@ -368,10 +368,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -402,17 +406,30 @@ class MockWgerBaseProvider extends _i1.Mock implements _i2.WgerBaseProvider { as Uri); @override - _i14.Future fetch(Uri? uri) => + _i14.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i14.Future.value(), ) as _i14.Future); @override - _i14.Future> fetchPaginated(Uri? uri) => + _i14.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i14.Future>.value([]), ) as _i14.Future>); diff --git a/test/exercises/contribute_exercise_test.mocks.dart b/test/exercises/contribute_exercise_test.mocks.dart index 65ccd2b5c..767f4410a 100644 --- a/test/exercises/contribute_exercise_test.mocks.dart +++ b/test/exercises/contribute_exercise_test.mocks.dart @@ -360,6 +360,14 @@ class MockUserProvider extends _i1.Mock implements _i15.UserProvider { ) as _i4.SharedPreferencesAsync); + @override + List<_i15.DashboardWidget> get dashboardOrder => + (super.noSuchMethod( + Invocation.getter(#dashboardOrder), + returnValue: <_i15.DashboardWidget>[], + ) + as List<_i15.DashboardWidget>); + @override set themeMode(_i16.ThemeMode? value) => super.noSuchMethod( Invocation.setter(#themeMode, value), @@ -388,6 +396,35 @@ class MockUserProvider extends _i1.Mock implements _i15.UserProvider { returnValueForMissingStub: null, ); + @override + bool isDashboardWidgetVisible(_i15.DashboardWidget? key) => + (super.noSuchMethod( + Invocation.method(#isDashboardWidgetVisible, [key]), + returnValue: false, + ) + as bool); + + @override + _i13.Future setDashboardWidgetVisible( + _i15.DashboardWidget? key, + bool? visible, + ) => + (super.noSuchMethod( + Invocation.method(#setDashboardWidgetVisible, [key, visible]), + returnValue: _i13.Future.value(), + returnValueForMissingStub: _i13.Future.value(), + ) + as _i13.Future); + + @override + _i13.Future setDashboardOrder(int? oldIndex, int? newIndex) => + (super.noSuchMethod( + Invocation.method(#setDashboardOrder, [oldIndex, newIndex]), + returnValue: _i13.Future.value(), + returnValueForMissingStub: _i13.Future.value(), + ) + as _i13.Future); + @override void setThemeMode(_i16.ThemeMode? mode) => super.noSuchMethod( Invocation.method(#setThemeMode, [mode]), diff --git a/test/gallery/gallery_form_test.mocks.dart b/test/gallery/gallery_form_test.mocks.dart index e14d78381..5e0488962 100644 --- a/test/gallery/gallery_form_test.mocks.dart +++ b/test/gallery/gallery_form_test.mocks.dart @@ -141,10 +141,14 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { as _i6.Future); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -175,17 +179,30 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { as Uri); @override - _i6.Future fetch(Uri? uri) => + _i6.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i6.Future.value(), ) as _i6.Future); @override - _i6.Future> fetchPaginated(Uri? uri) => + _i6.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i6.Future>.value([]), ) as _i6.Future>); diff --git a/test/gallery/gallery_screen_test.mocks.dart b/test/gallery/gallery_screen_test.mocks.dart index d1ab1318c..9b6edcbd7 100644 --- a/test/gallery/gallery_screen_test.mocks.dart +++ b/test/gallery/gallery_screen_test.mocks.dart @@ -141,10 +141,14 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { as _i6.Future); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -175,17 +179,30 @@ class MockGalleryProvider extends _i1.Mock implements _i4.GalleryProvider { as Uri); @override - _i6.Future fetch(Uri? uri) => + _i6.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i6.Future.value(), ) as _i6.Future); @override - _i6.Future> fetchPaginated(Uri? uri) => + _i6.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i6.Future>.value([]), ) as _i6.Future>); diff --git a/test/measurements/measurement_provider_test.mocks.dart b/test/measurements/measurement_provider_test.mocks.dart index ef362a877..b5127325c 100644 --- a/test/measurements/measurement_provider_test.mocks.dart +++ b/test/measurements/measurement_provider_test.mocks.dart @@ -78,10 +78,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -112,17 +116,30 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future> fetchPaginated(Uri? uri) => + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i5.Future>.value([]), ) as _i5.Future>); diff --git a/test/nutrition/nutritional_plan_screen_test.mocks.dart b/test/nutrition/nutritional_plan_screen_test.mocks.dart index 82fcab798..72612c37a 100644 --- a/test/nutrition/nutritional_plan_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plan_screen_test.mocks.dart @@ -90,10 +90,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -124,17 +128,30 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future> fetchPaginated(Uri? uri) => + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i5.Future>.value([]), ) as _i5.Future>); diff --git a/test/nutrition/nutritional_plans_screen_test.mocks.dart b/test/nutrition/nutritional_plans_screen_test.mocks.dart index 3c55e0068..3fff04e82 100644 --- a/test/nutrition/nutritional_plans_screen_test.mocks.dart +++ b/test/nutrition/nutritional_plans_screen_test.mocks.dart @@ -325,10 +325,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i8.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -359,17 +363,30 @@ class MockWgerBaseProvider extends _i1.Mock implements _i8.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future> fetchPaginated(Uri? uri) => + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i5.Future>.value([]), ) as _i5.Future>); diff --git a/test/providers/base_provider.dart b/test/providers/base_provider.dart new file mode 100644 index 000000000..203973c3e --- /dev/null +++ b/test/providers/base_provider.dart @@ -0,0 +1,135 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:wger/core/exceptions/http_exception.dart'; +import 'package:wger/providers/base_provider.dart'; + +import '../utils.dart'; +import 'base_provider.mocks.dart'; + +@GenerateMocks([Client]) +void main() { + final Uri testUri = Uri(scheme: 'https', host: 'localhost', path: 'api/v2/test/'); + + test('Retry on SocketException then succeeds', () async { + // Arrange + final mockClient = MockClient(); + var callCount = 0; + when(mockClient.get(testUri, headers: anyNamed('headers'))).thenAnswer((_) { + if (callCount == 0) { + callCount++; + return Future.error(const SocketException('conn fail')); + } + return Future.value(Response('{"ok": true}', 200)); + }); + + // Act + final provider = WgerBaseProvider(testAuthProvider, mockClient); + final result = await provider.fetch(testUri, initialDelay: const Duration(milliseconds: 1)); + + // Assert + expect(result, isA()); + expect(result['ok'], isTrue); + verify(mockClient.get(testUri, headers: anyNamed('headers'))).called(2); + }); + + test('Retry on 5xx then succeeds', () async { + // Arrange + final mockClient = MockClient(); + var callCount = 0; + when(mockClient.get(testUri, headers: anyNamed('headers'))).thenAnswer((_) { + if (callCount == 0) { + callCount++; + return Future.value(Response('{"msg":"error"}', 502)); + } + return Future.value(Response('{"ok": true}', 200)); + }); + + // Act + final provider = WgerBaseProvider(testAuthProvider, mockClient); + final result = await provider.fetch(testUri, initialDelay: const Duration(milliseconds: 1)); + + // Assert + expect(result, isA()); + expect(result['ok'], isTrue); + verify(mockClient.get(testUri, headers: anyNamed('headers'))).called(2); + }); + + test('Do not retry on 4xx client error', () async { + // Arrange + final mockClient = MockClient(); + when( + mockClient.get(testUri, headers: anyNamed('headers')), + ).thenAnswer((_) => Future.value(Response('{"error":"bad"}', 400))); + + // Act + final provider = WgerBaseProvider(testAuthProvider, mockClient); + + // Assert + await expectLater( + provider.fetch(testUri, initialDelay: const Duration(milliseconds: 1)), + throwsA(isA()), + ); + verify(mockClient.get(testUri, headers: anyNamed('headers'))).called(1); + }); + + test('Exceed max retries and rethrow after retries', () async { + // Arrange + final mockClient = MockClient(); + when( + mockClient.get(testUri, headers: anyNamed('headers')), + ).thenAnswer((_) => Future.error(ClientException('conn fail'))); + + // Act + final provider = WgerBaseProvider(testAuthProvider, mockClient); + dynamic caught; + try { + await provider.fetch(testUri, initialDelay: const Duration(milliseconds: 1)); + } catch (e) { + caught = e; + } + + // Assert + expect(caught, isA()); + // initial try + 3 retries = 4 calls + verify(mockClient.get(testUri, headers: anyNamed('headers'))).called(4); + }); + + test('Request succeeds without retries', () async { + // Arrange + final mockClient = MockClient(); + when( + mockClient.get(testUri, headers: anyNamed('headers')), + ).thenAnswer((_) => Future.value(Response('{"ok": true}', 200))); + + // Act + final provider = WgerBaseProvider(testAuthProvider, mockClient); + final result = await provider.fetch(testUri); + + // Assert + expect(result, isA()); + expect(result['ok'], isTrue); + verify(mockClient.get(testUri, headers: anyNamed('headers'))).called(1); + }); +} diff --git a/test/providers/base_provider.mocks.dart b/test/providers/base_provider.mocks.dart new file mode 100644 index 000000000..5111102b5 --- /dev/null +++ b/test/providers/base_provider.mocks.dart @@ -0,0 +1,218 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/providers/base_provider.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i3; +import 'dart:convert' as _i4; +import 'dart:typed_data' as _i6; + +import 'package:http/http.dart' as _i2; +import 'package:mockito/mockito.dart' as _i1; +import 'package:mockito/src/dummies.dart' as _i5; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +class _FakeResponse_0 extends _i1.SmartFake implements _i2.Response { + _FakeResponse_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeStreamedResponse_1 extends _i1.SmartFake implements _i2.StreamedResponse { + _FakeStreamedResponse_1(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +/// A class which mocks [Client]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockClient extends _i1.Mock implements _i2.Client { + MockClient() { + _i1.throwOnMissingStub(this); + } + + @override + _i3.Future<_i2.Response> head(Uri? url, {Map? headers}) => + (super.noSuchMethod( + Invocation.method(#head, [url], {#headers: headers}), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method(#head, [url], {#headers: headers}), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> get(Uri? url, {Map? headers}) => + (super.noSuchMethod( + Invocation.method(#get, [url], {#headers: headers}), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method(#get, [url], {#headers: headers}), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> post( + Uri? url, { + Map? headers, + Object? body, + _i4.Encoding? encoding, + }) => + (super.noSuchMethod( + Invocation.method( + #post, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #post, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> put( + Uri? url, { + Map? headers, + Object? body, + _i4.Encoding? encoding, + }) => + (super.noSuchMethod( + Invocation.method( + #put, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #put, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> patch( + Uri? url, { + Map? headers, + Object? body, + _i4.Encoding? encoding, + }) => + (super.noSuchMethod( + Invocation.method( + #patch, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #patch, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future<_i2.Response> delete( + Uri? url, { + Map? headers, + Object? body, + _i4.Encoding? encoding, + }) => + (super.noSuchMethod( + Invocation.method( + #delete, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + returnValue: _i3.Future<_i2.Response>.value( + _FakeResponse_0( + this, + Invocation.method( + #delete, + [url], + {#headers: headers, #body: body, #encoding: encoding}, + ), + ), + ), + ) + as _i3.Future<_i2.Response>); + + @override + _i3.Future read(Uri? url, {Map? headers}) => + (super.noSuchMethod( + Invocation.method(#read, [url], {#headers: headers}), + returnValue: _i3.Future.value( + _i5.dummyValue( + this, + Invocation.method(#read, [url], {#headers: headers}), + ), + ), + ) + as _i3.Future); + + @override + _i3.Future<_i6.Uint8List> readBytes( + Uri? url, { + Map? headers, + }) => + (super.noSuchMethod( + Invocation.method(#readBytes, [url], {#headers: headers}), + returnValue: _i3.Future<_i6.Uint8List>.value(_i6.Uint8List(0)), + ) + as _i3.Future<_i6.Uint8List>); + + @override + _i3.Future<_i2.StreamedResponse> send(_i2.BaseRequest? request) => + (super.noSuchMethod( + Invocation.method(#send, [request]), + returnValue: _i3.Future<_i2.StreamedResponse>.value( + _FakeStreamedResponse_1( + this, + Invocation.method(#send, [request]), + ), + ), + ) + as _i3.Future<_i2.StreamedResponse>); + + @override + void close() => super.noSuchMethod( + Invocation.method(#close, []), + returnValueForMissingStub: null, + ); +} diff --git a/test/providers/plate_calculator_test.mocks.dart b/test/providers/plate_calculator_test.mocks.dart index 1036371df..9b3fed8e4 100644 --- a/test/providers/plate_calculator_test.mocks.dart +++ b/test/providers/plate_calculator_test.mocks.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 wger Team - * - * wger Workout Manager is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - // Mocks generated by Mockito 5.4.6 from annotations // in wger/test/providers/plate_calculator_test.dart. // Do not manually edit this file. diff --git a/test/routine/gym_mode/gym_mode_test.dart b/test/routine/gym_mode/gym_mode_test.dart index 278cf9bd7..48aec7896 100644 --- a/test/routine/gym_mode/gym_mode_test.dart +++ b/test/routine/gym_mode/gym_mode_test.dart @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2020, 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -81,12 +81,10 @@ void main() { (WidgetTester tester) async { await withClock(Clock.fixed(DateTime(2025, 3, 29, 14, 33)), () async { await tester.pumpWidget(renderGymMode()); - await tester.pumpAndSettle(); await tester.tap(find.byType(TextButton)); - await tester.pumpAndSettle(); - //await tester.ensureVisible(find.byKey(Key(key as String))); + // // Start page // @@ -278,6 +276,7 @@ void main() { expect(find.byIcon(Icons.chevron_right), findsNothing); }); }, + tags: ['golden'], semanticsEnabled: false, ); } diff --git a/test/routine/routine_logs_screen_test.dart b/test/routine/routine_logs_screen_test.dart index 78e327042..81cff1b3b 100644 --- a/test/routine/routine_logs_screen_test.dart +++ b/test/routine/routine_logs_screen_test.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2025 wger Team + * Copyright (c) 2020 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * wger Workout Manager is distributed in the hope that it will be useful, + * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. @@ -24,19 +24,22 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; +import 'package:provider/provider.dart'; import 'package:wger/l10n/generated/app_localizations.dart'; import 'package:wger/models/workouts/routine.dart'; import 'package:wger/providers/network_provider.dart'; import 'package:wger/providers/routines.dart'; +import 'package:wger/providers/trophies.dart'; import 'package:wger/providers/workout_log_repository.dart'; import 'package:wger/screens/routine_logs_screen.dart'; import 'package:wger/screens/routine_screen.dart'; import 'package:wger/widgets/routines/logs/log_overview_routine.dart'; import '../../test_data/routines.dart'; +import '../test_data/trophies.dart'; import 'routine_logs_screen_test.mocks.dart'; -@GenerateMocks([WorkoutLogRepository]) +@GenerateMocks([TrophyRepository, WorkoutLogRepository]) void main() { late Routine routine; final mockWorkoutLogRepository = MockWorkoutLogRepository(); @@ -51,6 +54,14 @@ void main() { Widget renderWidget({locale = 'en', isOnline = true}) { final key = GlobalKey(); + final mockRepository = MockTrophyRepository(); + when( + mockRepository.fetchUserTrophies( + filterQuery: anyNamed('filterQuery'), + language: anyNamed('language'), + ), + ).thenAnswer((_) async => getUserTrophies()); + final container = ProviderContainer.test( overrides: [ networkStatusProvider.overrideWithValue(isOnline), @@ -60,25 +71,32 @@ void main() { container.read(routinesRiverpodProvider.notifier).state = RoutinesState(routines: [routine]); - return UncontrolledProviderScope( - container: container, - child: MaterialApp( - locale: Locale(locale), - localizationsDelegates: AppLocalizations.localizationsDelegates, - supportedLocales: AppLocalizations.supportedLocales, - navigatorKey: key, - home: TextButton( - onPressed: () => key.currentState!.push( - MaterialPageRoute( - settings: RouteSettings(arguments: routine.id), - builder: (_) => const WorkoutLogsScreen(), + return ProviderScope( + overrides: [ + networkStatusProvider.overrideWithValue(isOnline), + workoutLogRepositoryProvider.overrideWithValue(mockWorkoutLogRepository), + trophyRepositoryProvider.overrideWithValue(mockRepository), + ], + child: ChangeNotifierProvider( + create: (context) => mockRoutinesProvider, + child: MaterialApp( + locale: Locale(locale), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + navigatorKey: key, + home: TextButton( + onPressed: () => key.currentState!.push( + MaterialPageRoute( + settings: RouteSettings(arguments: routine.id), + builder: (_) => const WorkoutLogsScreen(), + ), ), + child: const SizedBox(), ), - child: const SizedBox(), + routes: { + RoutineScreen.routeName: (ctx) => const WorkoutLogsScreen(), + }, ), - routes: { - RoutineScreen.routeName: (ctx) => const WorkoutLogsScreen(), - }, ), ); } diff --git a/test/routine/routine_logs_screen_test.mocks.dart b/test/routine/routine_logs_screen_test.mocks.dart index e07a1600a..217e3cf5a 100644 --- a/test/routine/routine_logs_screen_test.mocks.dart +++ b/test/routine/routine_logs_screen_test.mocks.dart @@ -3,11 +3,17 @@ // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i3; +import 'dart:async' as _i5; import 'package:mockito/mockito.dart' as _i1; -import 'package:wger/models/workouts/log.dart' as _i4; -import 'package:wger/providers/workout_log_repository.dart' as _i2; +import 'package:mockito/src/dummies.dart' as _i4; +import 'package:wger/models/trophies/trophy.dart' as _i6; +import 'package:wger/models/trophies/user_trophy.dart' as _i7; +import 'package:wger/models/trophies/user_trophy_progression.dart' as _i8; +import 'package:wger/models/workouts/log.dart' as _i10; +import 'package:wger/providers/base_provider.dart' as _i2; +import 'package:wger/providers/trophies.dart' as _i3; +import 'package:wger/providers/workout_log_repository.dart' as _i9; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values @@ -24,46 +30,152 @@ import 'package:wger/providers/workout_log_repository.dart' as _i2; // ignore_for_file: subtype_of_sealed_class // ignore_for_file: invalid_use_of_internal_member +class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { + _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) + : super(parent, parentInvocation); +} + +/// A class which mocks [TrophyRepository]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockTrophyRepository extends _i1.Mock implements _i3.TrophyRepository { + MockTrophyRepository() { + _i1.throwOnMissingStub(this); + } + + @override + _i2.WgerBaseProvider get base => + (super.noSuchMethod( + Invocation.getter(#base), + returnValue: _FakeWgerBaseProvider_0( + this, + Invocation.getter(#base), + ), + ) + as _i2.WgerBaseProvider); + + @override + String get trophiesPath => + (super.noSuchMethod( + Invocation.getter(#trophiesPath), + returnValue: _i4.dummyValue( + this, + Invocation.getter(#trophiesPath), + ), + ) + as String); + + @override + String get userTrophiesPath => + (super.noSuchMethod( + Invocation.getter(#userTrophiesPath), + returnValue: _i4.dummyValue( + this, + Invocation.getter(#userTrophiesPath), + ), + ) + as String); + + @override + String get userTrophyProgressionPath => + (super.noSuchMethod( + Invocation.getter(#userTrophyProgressionPath), + returnValue: _i4.dummyValue( + this, + Invocation.getter(#userTrophyProgressionPath), + ), + ) + as String); + + @override + _i5.Future> fetchTrophies({String? language}) => + (super.noSuchMethod( + Invocation.method(#fetchTrophies, [], {#language: language}), + returnValue: _i5.Future>.value(<_i6.Trophy>[]), + ) + as _i5.Future>); + + @override + _i5.Future> fetchUserTrophies({ + Map? filterQuery, + String? language, + }) => + (super.noSuchMethod( + Invocation.method(#fetchUserTrophies, [], { + #filterQuery: filterQuery, + #language: language, + }), + returnValue: _i5.Future>.value( + <_i7.UserTrophy>[], + ), + ) + as _i5.Future>); + + @override + _i5.Future> fetchProgression({ + Map? filterQuery, + String? language, + }) => + (super.noSuchMethod( + Invocation.method(#fetchProgression, [], { + #filterQuery: filterQuery, + #language: language, + }), + returnValue: _i5.Future>.value( + <_i8.UserTrophyProgression>[], + ), + ) + as _i5.Future>); + + @override + List<_i6.Trophy> filterByType(List<_i6.Trophy>? list, _i6.TrophyType? type) => + (super.noSuchMethod( + Invocation.method(#filterByType, [list, type]), + returnValue: <_i6.Trophy>[], + ) + as List<_i6.Trophy>); +} + /// A class which mocks [WorkoutLogRepository]. /// /// See the documentation for Mockito's code generation for more information. -class MockWorkoutLogRepository extends _i1.Mock implements _i2.WorkoutLogRepository { +class MockWorkoutLogRepository extends _i1.Mock implements _i9.WorkoutLogRepository { MockWorkoutLogRepository() { _i1.throwOnMissingStub(this); } @override - _i3.Stream> watchAllDrift() => + _i5.Stream> watchAllDrift() => (super.noSuchMethod( Invocation.method(#watchAllDrift, []), - returnValue: _i3.Stream>.empty(), + returnValue: _i5.Stream>.empty(), ) - as _i3.Stream>); + as _i5.Stream>); @override - _i3.Future deleteLocalDrift(String? id) => + _i5.Future deleteLocalDrift(String? id) => (super.noSuchMethod( Invocation.method(#deleteLocalDrift, [id]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), ) - as _i3.Future); + as _i5.Future); @override - _i3.Future updateLocalDrift(_i4.Log? log) => + _i5.Future updateLocalDrift(_i10.Log? log) => (super.noSuchMethod( Invocation.method(#updateLocalDrift, [log]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), ) - as _i3.Future); + as _i5.Future); @override - _i3.Future addLocalDrift(_i4.Log? log) => + _i5.Future addLocalDrift(_i10.Log? log) => (super.noSuchMethod( Invocation.method(#addLocalDrift, [log]), - returnValue: _i3.Future.value(), - returnValueForMissingStub: _i3.Future.value(), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), ) - as _i3.Future); + as _i5.Future); } diff --git a/test/routine/routines_provider_repository_test.mocks.dart b/test/routine/routines_provider_repository_test.mocks.dart index 8c84a6aea..adba45635 100644 --- a/test/routine/routines_provider_repository_test.mocks.dart +++ b/test/routine/routines_provider_repository_test.mocks.dart @@ -78,10 +78,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -112,17 +116,30 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future> fetchPaginated(Uri? uri) => + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i5.Future>.value([]), ) as _i5.Future>); diff --git a/test/test_data/trophies.dart b/test/test_data/trophies.dart new file mode 100644 index 000000000..8fc13d286 --- /dev/null +++ b/test/test_data/trophies.dart @@ -0,0 +1,85 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:wger/models/trophies/trophy.dart'; +import 'package:wger/models/trophies/user_trophy.dart'; +import 'package:wger/models/trophies/user_trophy_progression.dart'; + +List getTestTrophies() { + return [ + Trophy( + id: 1, + uuid: '31a71d9a-bf26-4f18-b82f-afefe6f50df2', + name: 'New Year, New Me', + description: 'Work out on January 1st', + image: 'https://example.com/5362e55b-eaf1-4e34-9ef8-661538a3bdd9.png', + type: TrophyType.date, + isHidden: false, + isProgressive: false, + ), + Trophy( + id: 2, + uuid: 'b605b6a1-953d-41fb-87c9-a2f88b5f5907', + name: 'Unstoppable', + description: 'Maintain a 30-day workout streak', + image: 'https://example.com/b605b6a1-953d-41fb-87c9-a2f88b5f5907.png', + type: TrophyType.sequence, + isHidden: false, + isProgressive: true, + ), + ]; +} + +List getUserTrophyProgression() { + final trophies = getTestTrophies(); + + return [ + UserTrophyProgression( + trophy: trophies[0], + progress: 100, + isEarned: true, + earnedAt: DateTime(2025, 12, 20), + currentValue: null, + targetValue: null, + progressDisplay: null, + ), + UserTrophyProgression( + trophy: trophies[1], + progress: 40, + isEarned: false, + earnedAt: null, + currentValue: 12, + targetValue: 30, + progressDisplay: '12 / 30', + ), + ]; +} + +List getUserTrophies() { + final trophies = getTestTrophies(); + + return [ + UserTrophy( + id: 4, + earnedAt: DateTime(2025, 12, 20), + isNotified: true, + progress: 100, + trophy: trophies[0], + ), + ]; +} diff --git a/test/trophies/models/trophy_test.dart b/test/trophies/models/trophy_test.dart new file mode 100644 index 000000000..3285b589b --- /dev/null +++ b/test/trophies/models/trophy_test.dart @@ -0,0 +1,72 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/models/trophies/trophy.dart'; + +void main() { + group('Trophy model', () { + final sampleJson = { + 'id': 1, + 'uuid': '550e8400-e29b-41d4-a716-446655440000', + 'name': 'First Steps', + 'description': 'Awarded for the first workout', + 'image': 'https://example.org/trophy.png', + 'trophy_type': 'count', + 'is_hidden': false, + 'is_progressive': true, + }; + + test('fromJson creates valid Trophy instance', () { + final trophy = Trophy.fromJson(sampleJson); + + expect(trophy.id, 1); + expect(trophy.uuid, '550e8400-e29b-41d4-a716-446655440000'); + expect(trophy.name, 'First Steps'); + expect(trophy.description, 'Awarded for the first workout'); + expect(trophy.image, 'https://example.org/trophy.png'); + expect(trophy.type, TrophyType.count); + expect(trophy.isHidden, isFalse); + expect(trophy.isProgressive, isTrue); + }); + + test('toJson returns expected map', () { + final trophy = Trophy( + id: 2, + uuid: '00000000-0000-0000-0000-000000000000', + name: 'Progressor', + description: 'Progressive trophy', + image: 'https://example.org/prog.png', + type: TrophyType.time, + isHidden: true, + isProgressive: false, + ); + + final json = trophy.toJson(); + + expect(json['id'], 2); + expect(json['uuid'], '00000000-0000-0000-0000-000000000000'); + expect(json['name'], 'Progressor'); + expect(json['description'], 'Progressive trophy'); + expect(json['image'], 'https://example.org/prog.png'); + expect(json['trophy_type'], 'time'); + expect(json['is_hidden'], true); + expect(json['is_progressive'], false); + }); + }); +} diff --git a/test/trophies/models/user_trophy_progression_test.dart b/test/trophies/models/user_trophy_progression_test.dart new file mode 100644 index 000000000..ccbb1d06a --- /dev/null +++ b/test/trophies/models/user_trophy_progression_test.dart @@ -0,0 +1,97 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter_test/flutter_test.dart'; +import 'package:wger/models/trophies/trophy.dart'; +import 'package:wger/models/trophies/user_trophy_progression.dart'; + +void main() { + group('UserTrophyProgression model', () { + final trophyJson = { + 'id': 1, + 'uuid': '550e8400-e29b-41d4-a716-446655440000', + 'name': 'First Steps', + 'description': 'Awarded for the first workout', + 'image': 'https://example.org/trophy.png', + 'trophy_type': 'count', + 'is_hidden': false, + 'is_progressive': true, + }; + + final trophyProgressionJson = { + 'trophy': trophyJson, + 'is_earned': false, + 'earned_at': '2020-01-02T15:04:05Z', + 'progress': 42.5, + 'current_value': '12.5', + 'target_value': '100', + 'progress_display': '12.5/100', + }; + + test('fromJson creates valid UserTrophyProgression instance', () { + final utp = UserTrophyProgression.fromJson(trophyProgressionJson); + + expect(utp.trophy.id, 1); + expect(utp.trophy.uuid, '550e8400-e29b-41d4-a716-446655440000'); + expect(utp.isEarned, isFalse); + + final expectedEarnedAt = DateTime.parse('2020-01-02T15:04:05Z').toLocal(); + expect(utp.earnedAt, expectedEarnedAt); + + expect(utp.progress, 42.5); + expect(utp.currentValue, 12.5); + expect(utp.targetValue, 100); + expect(utp.progressDisplay, '12.5/100'); + }); + + test('toJson returns expected map', () { + final trophy = Trophy( + id: 2, + uuid: '00000000-0000-0000-0000-000000000000', + name: 'Progressor', + description: 'Progressive trophy', + image: 'https://example.org/prog.png', + type: TrophyType.time, + isHidden: true, + isProgressive: false, + ); + + final earnedAt = DateTime.parse('2020-01-02T15:04:05Z').toLocal(); + + final utp = UserTrophyProgression( + trophy: trophy, + isEarned: true, + earnedAt: earnedAt, + progress: 75, + currentValue: 75, + targetValue: 100, + progressDisplay: '75/100', + ); + + final json = utp.toJson(); + + expect(json['trophy'], same(trophy)); + expect(json['is_earned'], true); + expect(json['earned_at'], earnedAt.toIso8601String()); + expect(json['progress'], 75); + expect(json['current_value'], 75); + expect(json['target_value'], 100); + expect(json['progress_display'], '75/100'); + }); + }); +} diff --git a/test/trophies/provider/trophies_provider_test.dart b/test/trophies/provider/trophies_provider_test.dart new file mode 100644 index 000000000..456a806a5 --- /dev/null +++ b/test/trophies/provider/trophies_provider_test.dart @@ -0,0 +1,99 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2025 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter_test/flutter_test.dart'; +import 'package:mockito/annotations.dart'; +import 'package:mockito/mockito.dart'; +import 'package:wger/providers/base_provider.dart'; +import 'package:wger/providers/trophies.dart'; + +import 'trophies_provider_test.mocks.dart'; + +const trophyJson = { + 'id': 1, + 'uuid': '550e8400-e29b-41d4-a716-446655440000', + 'name': 'First Steps', + 'description': 'Awarded for the first workout', + 'image': 'https://example.org/trophy.png', + 'trophy_type': 'count', + 'is_hidden': false, + 'is_progressive': true, +}; + +@GenerateMocks([WgerBaseProvider]) +void main() { + group('Trophy repository', () { + test('fetches list of trophies', () async { + // Arrange + final mockBase = MockWgerBaseProvider(); + when(mockBase.fetchPaginated(any)).thenAnswer((_) async => [trophyJson]); + when( + mockBase.makeUrl( + any, + id: anyNamed('id'), + objectMethod: anyNamed('objectMethod'), + query: anyNamed('query'), + ), + ).thenReturn(Uri.parse('https://example.org/trophies')); + final repository = TrophyRepository(mockBase); + + // Act + final result = await repository.fetchTrophies(); + + // Assert + expect(result, isA()); + expect(result, hasLength(1)); + final trophy = result.first; + expect(trophy.id, 1); + expect(trophy.name, 'First Steps'); + expect(trophy.type.toString(), contains('count')); + }); + + test('fetches list of user trophy progression', () async { + // Arrange + final progressionJson = { + 'trophy': trophyJson, + 'is_earned': true, + 'earned_at': '2020-01-02T15:04:05Z', + 'progress': 42.5, + 'current_value': '12.5', + 'target_value': '100', + 'progress_display': '12.5/100', + }; + + final mockBase = MockWgerBaseProvider(); + when(mockBase.fetch(any)).thenAnswer((_) async => [progressionJson]); + when(mockBase.makeUrl(any)).thenReturn(Uri.parse('https://example.org/user_progressions')); + final repository = TrophyRepository(mockBase); + + // Act + final result = await repository.fetchProgression(); + + // Assert + expect(result, isA()); + expect(result, hasLength(1)); + final p = result.first; + expect(p.isEarned, isTrue); + expect(p.progress, 42.5); + expect(p.currentValue, 12.5); + expect(p.progressDisplay, '12.5/100'); + + verify(mockBase.fetch(any)).called(1); + }); + }); +} diff --git a/test/trophies/provider/trophies_provider_test.mocks.dart b/test/trophies/provider/trophies_provider_test.mocks.dart new file mode 100644 index 000000000..15b59d6e6 --- /dev/null +++ b/test/trophies/provider/trophies_provider_test.mocks.dart @@ -0,0 +1,182 @@ +// Mocks generated by Mockito 5.4.6 from annotations +// in wger/test/trophies/provider/trophies_provider_test.dart. +// Do not manually edit this file. + +// ignore_for_file: no_leading_underscores_for_library_prefixes +import 'dart:async' as _i5; + +import 'package:http/http.dart' as _i3; +import 'package:mockito/mockito.dart' as _i1; +import 'package:wger/providers/auth.dart' as _i2; +import 'package:wger/providers/base_provider.dart' as _i4; + +// ignore_for_file: type=lint +// ignore_for_file: avoid_redundant_argument_values +// ignore_for_file: avoid_setters_without_getters +// ignore_for_file: comment_references +// ignore_for_file: deprecated_member_use +// ignore_for_file: deprecated_member_use_from_same_package +// ignore_for_file: implementation_imports +// ignore_for_file: invalid_use_of_visible_for_testing_member +// ignore_for_file: must_be_immutable +// ignore_for_file: prefer_const_constructors +// ignore_for_file: unnecessary_parenthesis +// ignore_for_file: camel_case_types +// ignore_for_file: subtype_of_sealed_class +// ignore_for_file: invalid_use_of_internal_member + +class _FakeAuthProvider_0 extends _i1.SmartFake implements _i2.AuthProvider { + _FakeAuthProvider_0(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeClient_1 extends _i1.SmartFake implements _i3.Client { + _FakeClient_1(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeUri_2 extends _i1.SmartFake implements Uri { + _FakeUri_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +class _FakeResponse_3 extends _i1.SmartFake implements _i3.Response { + _FakeResponse_3(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); +} + +/// A class which mocks [WgerBaseProvider]. +/// +/// See the documentation for Mockito's code generation for more information. +class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { + MockWgerBaseProvider() { + _i1.throwOnMissingStub(this); + } + + @override + _i2.AuthProvider get auth => + (super.noSuchMethod( + Invocation.getter(#auth), + returnValue: _FakeAuthProvider_0(this, Invocation.getter(#auth)), + ) + as _i2.AuthProvider); + + @override + _i3.Client get client => + (super.noSuchMethod( + Invocation.getter(#client), + returnValue: _FakeClient_1(this, Invocation.getter(#client)), + ) + as _i3.Client); + + @override + set auth(_i2.AuthProvider? value) => super.noSuchMethod( + Invocation.setter(#auth, value), + returnValueForMissingStub: null, + ); + + @override + set client(_i3.Client? value) => super.noSuchMethod( + Invocation.setter(#client, value), + returnValueForMissingStub: null, + ); + + @override + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => + (super.noSuchMethod( + Invocation.method(#getDefaultHeaders, [], { + #includeAuth: includeAuth, + #language: language, + }), + returnValue: {}, + ) + as Map); + + @override + Uri makeUrl( + String? path, { + int? id, + String? objectMethod, + Map? query, + }) => + (super.noSuchMethod( + Invocation.method( + #makeUrl, + [path], + {#id: id, #objectMethod: objectMethod, #query: query}, + ), + returnValue: _FakeUri_2( + this, + Invocation.method( + #makeUrl, + [path], + {#id: id, #objectMethod: objectMethod, #query: query}, + ), + ), + ) + as Uri); + + @override + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => + (super.noSuchMethod( + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), + returnValue: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => + (super.noSuchMethod( + Invocation.method(#fetchPaginated, [uri], {#language: language}), + returnValue: _i5.Future>.value([]), + ) + as _i5.Future>); + + @override + _i5.Future> post(Map? data, Uri? uri) => + (super.noSuchMethod( + Invocation.method(#post, [data, uri]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future> patch( + Map? data, + Uri? uri, + ) => + (super.noSuchMethod( + Invocation.method(#patch, [data, uri]), + returnValue: _i5.Future>.value( + {}, + ), + ) + as _i5.Future>); + + @override + _i5.Future<_i3.Response> deleteRequest(String? url, int? id) => + (super.noSuchMethod( + Invocation.method(#deleteRequest, [url, id]), + returnValue: _i5.Future<_i3.Response>.value( + _FakeResponse_3( + this, + Invocation.method(#deleteRequest, [url, id]), + ), + ), + ) + as _i5.Future<_i3.Response>); +} diff --git a/test/trophies/widgets/dashboard_trophies_widget_test.dart b/test/trophies/widgets/dashboard_trophies_widget_test.dart new file mode 100644 index 000000000..d8549d92c --- /dev/null +++ b/test/trophies/widgets/dashboard_trophies_widget_test.dart @@ -0,0 +1,79 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:network_image_mock/network_image_mock.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/providers/trophies.dart'; +import 'package:wger/widgets/dashboard/widgets/trophies.dart'; + +import '../../test_data/trophies.dart'; + +void main() { + Future pumpOverview(WidgetTester tester, [List overrides = const []]) async { + await tester.pumpWidget( + ProviderScope( + overrides: overrides, + child: const MaterialApp( + locale: Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: DashboardTrophiesWidget(), + ), + ), + ), + ); + } + + group('DashboardTrophiesWidget tests', () { + testWidgets('shows trophies', (WidgetTester tester) async { + // Act + await mockNetworkImagesFor(() async { + await pumpOverview( + tester, + [ + trophyStateProvider.overrideWithValue( + TrophyState( + userTrophies: getUserTrophies(), + trophies: getTestTrophies(), + ), + ), + ], + ); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('New Year, New Me'), findsOneWidget); + }); + }); + + testWidgets('handles empty results', (WidgetTester tester) async { + // Act + await pumpOverview(tester); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('Trophies'), findsOneWidget); + expect(find.text('You have no trophies yet'), findsOneWidget); + }); + }); +} diff --git a/test/trophies/widgets/trophies_overview_test.dart b/test/trophies/widgets/trophies_overview_test.dart new file mode 100644 index 000000000..1a843a213 --- /dev/null +++ b/test/trophies/widgets/trophies_overview_test.dart @@ -0,0 +1,62 @@ +/* + * This file is part of wger Workout Manager . + * Copyright (c) 2026 wger Team + * + * wger Workout Manager is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:network_image_mock/network_image_mock.dart'; +import 'package:wger/l10n/generated/app_localizations.dart'; +import 'package:wger/providers/trophies.dart'; +import 'package:wger/widgets/trophies/trophies_overview.dart'; + +import '../../test_data/trophies.dart'; + +void main() { + testWidgets('TrophiesOverview shows trophies', (WidgetTester tester) async { + // Act + await mockNetworkImagesFor(() async { + await tester.pumpWidget( + ProviderScope( + overrides: [ + trophyStateProvider.overrideWithValue( + TrophyState( + trophyProgression: getUserTrophyProgression(), + userTrophies: getUserTrophies(), + trophies: getTestTrophies(), + ), + ), + ], + child: const MaterialApp( + locale: Locale('en'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: TrophiesOverview()), + ), + ), + ); + await tester.pumpAndSettle(); + + // Assert + expect(find.text('New Year, New Me'), findsOneWidget); + expect(find.text('Work out on January 1st'), findsOneWidget); + + expect(find.text('Unstoppable'), findsOneWidget); + expect(find.text('Maintain a 30-day workout streak'), findsOneWidget); + }); + }); +} diff --git a/test/user/provider_test.dart b/test/user/provider_test.dart index 8297b3308..c5a9206e3 100644 --- a/test/user/provider_test.dart +++ b/test/user/provider_test.dart @@ -1,13 +1,13 @@ /* * This file is part of wger Workout Manager . - * Copyright (C) 2020, 2021 wger Team + * Copyright (c) 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * - * wger Workout Manager is distributed in the hope that it will be useful, + * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. @@ -21,6 +21,7 @@ import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; import 'package:wger/providers/base_provider.dart'; @@ -51,7 +52,6 @@ void main() { ); setUp(() { - /// Replacement for SharedPreferences.setMockInitialValues() SharedPreferencesAsyncPlatform.instance = InMemorySharedPreferencesAsync.empty(); mockWgerBaseProvider = MockWgerBaseProvider(); userProvider = UserProvider(mockWgerBaseProvider); @@ -103,4 +103,87 @@ void main() { verify(userProvider.baseProvider.fetch(tEmailVerifyUri)); }); }); + + group('dashboard config', () { + test('initial config should be default (all visible, default order)', () { + expect(userProvider.dashboardOrder.length, 6); + + expect( + userProvider.dashboardOrder, + orderedEquals([ + DashboardWidget.trophies, + DashboardWidget.routines, + DashboardWidget.nutrition, + DashboardWidget.weight, + DashboardWidget.measurements, + DashboardWidget.calendar, + ]), + ); + expect(userProvider.isDashboardWidgetVisible(DashboardWidget.routines), true); + }); + + test('toggling visibility should update state', () async { + // act + await userProvider.setDashboardWidgetVisible(DashboardWidget.routines, false); + + // assert + expect(userProvider.isDashboardWidgetVisible(DashboardWidget.routines), false); + + // re-enable + await userProvider.setDashboardWidgetVisible(DashboardWidget.routines, true); + expect(userProvider.isDashboardWidgetVisible(DashboardWidget.routines), true); + }); + + test('reordering should update order', () async { + // arrange + final initialFirst = userProvider.dashboardOrder[0]; + final initialSecond = userProvider.dashboardOrder[1]; + + // act: move first to second position + // oldIndex: 0, newIndex: 2 (because insert is before index) + await userProvider.setDashboardOrder(0, 2); + + // assert + expect(userProvider.dashboardOrder[0], initialSecond); + expect(userProvider.dashboardOrder[1], initialFirst); + }); + + test('should load config from prefs', () async { + // arrange + final prefs = SharedPreferencesAsync(); + final customConfig = [ + {'widget': 'nutrition', 'visible': true}, + {'widget': 'routines', 'visible': false}, + ]; + await prefs.setString( + UserProvider.PREFS_DASHBOARD_CONFIG, + jsonEncode(customConfig), + ); + + // act + final newProvider = UserProvider(mockWgerBaseProvider, prefs: prefs); + await Future.delayed(const Duration(milliseconds: 100)); // wait for async prefs load + + // assert + // Loaded: [nutrition, routines] + // Missing: trophies (0), weight (3), measurements (4), calendar (5) + // 1. trophies (index 0) inserted at 0 -> [trophies, nutrition, routines] + // 2. weight (index 3) inserted at 3 -> [trophies, nutrition, routines, weight] + + expect(newProvider.dashboardOrder[0], DashboardWidget.trophies); + expect(newProvider.dashboardOrder[1], DashboardWidget.nutrition); + expect(newProvider.dashboardOrder[2], DashboardWidget.routines); + expect(newProvider.dashboardOrder[3], DashboardWidget.weight); + + // Check visibility + expect(newProvider.isDashboardWidgetVisible(DashboardWidget.nutrition), true); + expect(newProvider.isDashboardWidgetVisible(DashboardWidget.routines), false); + + // Missing items should be visible by default + expect( + newProvider.isDashboardWidgetVisible(DashboardWidget.weight), + true, + ); + }); + }); } diff --git a/test/user/provider_test.mocks.dart b/test/user/provider_test.mocks.dart index b8fce543f..d16a2200c 100644 --- a/test/user/provider_test.mocks.dart +++ b/test/user/provider_test.mocks.dart @@ -1,21 +1,3 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 wger Team - * - * wger Workout Manager is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - // Mocks generated by Mockito 5.4.6 from annotations // in wger/test/user/provider_test.dart. // Do not manually edit this file. @@ -96,10 +78,14 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { ); @override - Map getDefaultHeaders({bool? includeAuth = false}) => + Map getDefaultHeaders({ + bool? includeAuth = false, + String? language, + }) => (super.noSuchMethod( Invocation.method(#getDefaultHeaders, [], { #includeAuth: includeAuth, + #language: language, }), returnValue: {}, ) @@ -130,17 +116,30 @@ class MockWgerBaseProvider extends _i1.Mock implements _i4.WgerBaseProvider { as Uri); @override - _i5.Future fetch(Uri? uri) => + _i5.Future fetch( + Uri? uri, { + int? maxRetries = 3, + Duration? initialDelay = const Duration(milliseconds: 250), + String? language, + }) => (super.noSuchMethod( - Invocation.method(#fetch, [uri]), + Invocation.method( + #fetch, + [uri], + { + #maxRetries: maxRetries, + #initialDelay: initialDelay, + #language: language, + }, + ), returnValue: _i5.Future.value(), ) as _i5.Future); @override - _i5.Future> fetchPaginated(Uri? uri) => + _i5.Future> fetchPaginated(Uri? uri, {String? language}) => (super.noSuchMethod( - Invocation.method(#fetchPaginated, [uri]), + Invocation.method(#fetchPaginated, [uri], {#language: language}), returnValue: _i5.Future>.value([]), ) as _i5.Future>); diff --git a/test/weight/weight_screen_test.mocks.dart b/test/weight/weight_screen_test.mocks.dart index 01ae2ed55..2508c22e7 100644 --- a/test/weight/weight_screen_test.mocks.dart +++ b/test/weight/weight_screen_test.mocks.dart @@ -106,6 +106,14 @@ class MockUserProvider extends _i1.Mock implements _i9.UserProvider { ) as _i3.SharedPreferencesAsync); + @override + List<_i9.DashboardWidget> get dashboardOrder => + (super.noSuchMethod( + Invocation.getter(#dashboardOrder), + returnValue: <_i9.DashboardWidget>[], + ) + as List<_i9.DashboardWidget>); + @override set themeMode(_i10.ThemeMode? value) => super.noSuchMethod( Invocation.setter(#themeMode, value), @@ -134,6 +142,35 @@ class MockUserProvider extends _i1.Mock implements _i9.UserProvider { returnValueForMissingStub: null, ); + @override + bool isDashboardWidgetVisible(_i9.DashboardWidget? key) => + (super.noSuchMethod( + Invocation.method(#isDashboardWidgetVisible, [key]), + returnValue: false, + ) + as bool); + + @override + _i12.Future setDashboardWidgetVisible( + _i9.DashboardWidget? key, + bool? visible, + ) => + (super.noSuchMethod( + Invocation.method(#setDashboardWidgetVisible, [key, visible]), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), + ) + as _i12.Future); + + @override + _i12.Future setDashboardOrder(int? oldIndex, int? newIndex) => + (super.noSuchMethod( + Invocation.method(#setDashboardOrder, [oldIndex, newIndex]), + returnValue: _i12.Future.value(), + returnValueForMissingStub: _i12.Future.value(), + ) + as _i12.Future); + @override void setThemeMode(_i10.ThemeMode? mode) => super.noSuchMethod( Invocation.method(#setThemeMode, [mode]), diff --git a/test/widgets/routines/gym_mode/log_page_test.dart b/test/widgets/routines/gym_mode/log_page_test.dart.TODO similarity index 95% rename from test/widgets/routines/gym_mode/log_page_test.dart rename to test/widgets/routines/gym_mode/log_page_test.dart.TODO index 45526e7f4..cf1c8eaa8 100644 --- a/test/widgets/routines/gym_mode/log_page_test.dart +++ b/test/widgets/routines/gym_mode/log_page_test.dart.TODO @@ -1,6 +1,6 @@ /* * This file is part of wger Workout Manager . - * Copyright (c) 2025 - 2025 wger Team + * Copyright (c) 2025 - 2026 wger Team * * wger Workout Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by @@ -30,7 +30,6 @@ import 'package:wger/models/workouts/day_data.dart'; import 'package:wger/models/workouts/log.dart'; import 'package:wger/models/workouts/set_config_data.dart'; import 'package:wger/models/workouts/slot_data.dart'; -import 'package:wger/providers/exercises.dart'; import 'package:wger/providers/gym_state.dart'; import 'package:wger/providers/routines.dart'; import 'package:wger/widgets/routines/gym_mode/log_page.dart'; @@ -128,6 +127,7 @@ void main() { // Act notifier.calculatePages(); + notifier.setCurrentPage(2); // Assert expect(notifier.state.getSlotEntryPageByIndex()!.type, SlotPageType.log); @@ -159,6 +159,7 @@ void main() { iteration: 1, ); notifier.calculatePages(); + notifier.setCurrentPage(2); // Act // Log page is at index 2 @@ -197,6 +198,7 @@ void main() { iteration: 1, ); notifier.calculatePages(); + notifier.setCurrentPage(2); notifier.state = notifier.state.copyWith(currentPage: 2); final mockRoutines = MockRoutinesProvider(); @@ -206,14 +208,14 @@ void main() { final editableFields = find.byType(EditableText); expect(editableFields, findsWidgets); - await tester.enterText(editableFields.at(0), '7'); - await tester.enterText(editableFields.at(1), '77'); + await tester.enterText(editableFields.at(0), '12'); // Reps + await tester.enterText(editableFields.at(1), '34'); // Weight await tester.pumpAndSettle(); Log? capturedLog; when(mockRoutines.addLog(any)).thenAnswer((invocation) async { capturedLog = invocation.positionalArguments[0] as Log; - capturedLog!.id = 42; + capturedLog!.id = '42'; return capturedLog!; }); @@ -226,8 +228,8 @@ void main() { // Assert verify(mockRoutines.addLog(any)).called(1); expect(capturedLog, isNotNull); - expect(capturedLog!.repetitions, equals(7)); - expect(capturedLog!.weight, equals(77)); + expect(capturedLog!.repetitions, equals(12)); + expect(capturedLog!.weight, equals(34)); final currentSlotPage = notifier.state.getSlotEntryPageByIndex()!; expect(capturedLog!.slotEntryId, equals(currentSlotPage.setConfigData!.slotEntryId)); diff --git a/test/widgets/routines/gym_mode/log_page_test.mocks.dart b/test/widgets/routines/gym_mode/log_page_test.mocks.dart deleted file mode 100644 index 500c61d8d..000000000 --- a/test/widgets/routines/gym_mode/log_page_test.mocks.dart +++ /dev/null @@ -1,1069 +0,0 @@ -/* - * This file is part of wger Workout Manager . - * Copyright (c) 2025 wger Team - * - * wger Workout Manager is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - */ - -// Mocks generated by Mockito 5.4.6 from annotations -// in wger/test/widgets/routines/gym_mode/log_page_test.dart. -// Do not manually edit this file. - -// ignore_for_file: no_leading_underscores_for_library_prefixes -import 'dart:async' as _i19; -import 'dart:ui' as _i20; - -import 'package:mockito/mockito.dart' as _i1; -import 'package:mockito/src/dummies.dart' as _i23; -import 'package:wger/database/exercises/exercise_database.dart' as _i3; -import 'package:wger/models/exercises/category.dart' as _i5; -import 'package:wger/models/exercises/equipment.dart' as _i6; -import 'package:wger/models/exercises/exercise.dart' as _i4; -import 'package:wger/models/exercises/language.dart' as _i8; -import 'package:wger/models/exercises/muscle.dart' as _i7; -import 'package:wger/models/workouts/base_config.dart' as _i15; -import 'package:wger/models/workouts/day.dart' as _i12; -import 'package:wger/models/workouts/day_data.dart' as _i22; -import 'package:wger/models/workouts/log.dart' as _i17; -import 'package:wger/models/workouts/repetition_unit.dart' as _i10; -import 'package:wger/models/workouts/routine.dart' as _i11; -import 'package:wger/models/workouts/session.dart' as _i16; -import 'package:wger/models/workouts/slot.dart' as _i13; -import 'package:wger/models/workouts/slot_entry.dart' as _i14; -import 'package:wger/models/workouts/weight_unit.dart' as _i9; -import 'package:wger/providers/base_provider.dart' as _i2; -import 'package:wger/providers/exercises.dart' as _i18; -import 'package:wger/providers/routines.dart' as _i21; - -// ignore_for_file: type=lint -// ignore_for_file: avoid_redundant_argument_values -// ignore_for_file: avoid_setters_without_getters -// ignore_for_file: comment_references -// ignore_for_file: deprecated_member_use -// ignore_for_file: deprecated_member_use_from_same_package -// ignore_for_file: implementation_imports -// ignore_for_file: invalid_use_of_visible_for_testing_member -// ignore_for_file: must_be_immutable -// ignore_for_file: prefer_const_constructors -// ignore_for_file: unnecessary_parenthesis -// ignore_for_file: camel_case_types -// ignore_for_file: subtype_of_sealed_class -// ignore_for_file: invalid_use_of_internal_member - -class _FakeWgerBaseProvider_0 extends _i1.SmartFake implements _i2.WgerBaseProvider { - _FakeWgerBaseProvider_0(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -class _FakeExerciseDatabase_1 extends _i1.SmartFake implements _i3.ExerciseDatabase { - _FakeExerciseDatabase_1(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -class _FakeExercise_2 extends _i1.SmartFake implements _i4.Exercise { - _FakeExercise_2(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeExerciseCategory_3 extends _i1.SmartFake implements _i5.ExerciseCategory { - _FakeExerciseCategory_3(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -class _FakeEquipment_4 extends _i1.SmartFake implements _i6.Equipment { - _FakeEquipment_4(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeMuscle_5 extends _i1.SmartFake implements _i7.Muscle { - _FakeMuscle_5(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeLanguage_6 extends _i1.SmartFake implements _i8.Language { - _FakeLanguage_6(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeWeightUnit_7 extends _i1.SmartFake implements _i9.WeightUnit { - _FakeWeightUnit_7(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeRepetitionUnit_8 extends _i1.SmartFake implements _i10.RepetitionUnit { - _FakeRepetitionUnit_8(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -class _FakeRoutine_9 extends _i1.SmartFake implements _i11.Routine { - _FakeRoutine_9(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeDay_10 extends _i1.SmartFake implements _i12.Day { - _FakeDay_10(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeSlot_11 extends _i1.SmartFake implements _i13.Slot { - _FakeSlot_11(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeSlotEntry_12 extends _i1.SmartFake implements _i14.SlotEntry { - _FakeSlotEntry_12(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeBaseConfig_13 extends _i1.SmartFake implements _i15.BaseConfig { - _FakeBaseConfig_13(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -class _FakeWorkoutSession_14 extends _i1.SmartFake implements _i16.WorkoutSession { - _FakeWorkoutSession_14(Object parent, Invocation parentInvocation) - : super(parent, parentInvocation); -} - -class _FakeLog_15 extends _i1.SmartFake implements _i17.Log { - _FakeLog_15(Object parent, Invocation parentInvocation) : super(parent, parentInvocation); -} - -/// A class which mocks [ExercisesProvider]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockExercisesProvider extends _i1.Mock implements _i18.ExercisesProvider { - MockExercisesProvider() { - _i1.throwOnMissingStub(this); - } - - @override - _i2.WgerBaseProvider get baseProvider => - (super.noSuchMethod( - Invocation.getter(#baseProvider), - returnValue: _FakeWgerBaseProvider_0( - this, - Invocation.getter(#baseProvider), - ), - ) - as _i2.WgerBaseProvider); - - @override - _i3.ExerciseDatabase get database => - (super.noSuchMethod( - Invocation.getter(#database), - returnValue: _FakeExerciseDatabase_1( - this, - Invocation.getter(#database), - ), - ) - as _i3.ExerciseDatabase); - - @override - List<_i4.Exercise> get exercises => - (super.noSuchMethod( - Invocation.getter(#exercises), - returnValue: <_i4.Exercise>[], - ) - as List<_i4.Exercise>); - - @override - List<_i4.Exercise> get filteredExercises => - (super.noSuchMethod( - Invocation.getter(#filteredExercises), - returnValue: <_i4.Exercise>[], - ) - as List<_i4.Exercise>); - - @override - Map> get exerciseByVariation => - (super.noSuchMethod( - Invocation.getter(#exerciseByVariation), - returnValue: >{}, - ) - as Map>); - - @override - List<_i5.ExerciseCategory> get categories => - (super.noSuchMethod( - Invocation.getter(#categories), - returnValue: <_i5.ExerciseCategory>[], - ) - as List<_i5.ExerciseCategory>); - - @override - List<_i7.Muscle> get muscles => - (super.noSuchMethod( - Invocation.getter(#muscles), - returnValue: <_i7.Muscle>[], - ) - as List<_i7.Muscle>); - - @override - List<_i6.Equipment> get equipment => - (super.noSuchMethod( - Invocation.getter(#equipment), - returnValue: <_i6.Equipment>[], - ) - as List<_i6.Equipment>); - - @override - List<_i8.Language> get languages => - (super.noSuchMethod( - Invocation.getter(#languages), - returnValue: <_i8.Language>[], - ) - as List<_i8.Language>); - - @override - set database(_i3.ExerciseDatabase? value) => super.noSuchMethod( - Invocation.setter(#database, value), - returnValueForMissingStub: null, - ); - - @override - set exercises(List<_i4.Exercise>? value) => super.noSuchMethod( - Invocation.setter(#exercises, value), - returnValueForMissingStub: null, - ); - - @override - set filteredExercises(List<_i4.Exercise>? newFilteredExercises) => super.noSuchMethod( - Invocation.setter(#filteredExercises, newFilteredExercises), - returnValueForMissingStub: null, - ); - - @override - set languages(List<_i8.Language>? languages) => super.noSuchMethod( - Invocation.setter(#languages, languages), - returnValueForMissingStub: null, - ); - - @override - bool get hasListeners => - (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) as bool); - - @override - _i19.Future setFilters(_i18.Filters? newFilters) => - (super.noSuchMethod( - Invocation.method(#setFilters, [newFilters]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - void initFilters() => super.noSuchMethod( - Invocation.method(#initFilters, []), - returnValueForMissingStub: null, - ); - - @override - _i19.Future findByFilters() => - (super.noSuchMethod( - Invocation.method(#findByFilters, []), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - void clear() => super.noSuchMethod( - Invocation.method(#clear, []), - returnValueForMissingStub: null, - ); - - @override - _i4.Exercise findExerciseById(int? id) => - (super.noSuchMethod( - Invocation.method(#findExerciseById, [id]), - returnValue: _FakeExercise_2( - this, - Invocation.method(#findExerciseById, [id]), - ), - ) - as _i4.Exercise); - - @override - List<_i4.Exercise> findExercisesByVariationId( - int? variationId, { - int? exerciseIdToExclude, - }) => - (super.noSuchMethod( - Invocation.method( - #findExercisesByVariationId, - [variationId], - {#exerciseIdToExclude: exerciseIdToExclude}, - ), - returnValue: <_i4.Exercise>[], - ) - as List<_i4.Exercise>); - - @override - _i5.ExerciseCategory findCategoryById(int? id) => - (super.noSuchMethod( - Invocation.method(#findCategoryById, [id]), - returnValue: _FakeExerciseCategory_3( - this, - Invocation.method(#findCategoryById, [id]), - ), - ) - as _i5.ExerciseCategory); - - @override - _i6.Equipment findEquipmentById(int? id) => - (super.noSuchMethod( - Invocation.method(#findEquipmentById, [id]), - returnValue: _FakeEquipment_4( - this, - Invocation.method(#findEquipmentById, [id]), - ), - ) - as _i6.Equipment); - - @override - _i7.Muscle findMuscleById(int? id) => - (super.noSuchMethod( - Invocation.method(#findMuscleById, [id]), - returnValue: _FakeMuscle_5( - this, - Invocation.method(#findMuscleById, [id]), - ), - ) - as _i7.Muscle); - - @override - _i8.Language findLanguageById(int? id) => - (super.noSuchMethod( - Invocation.method(#findLanguageById, [id]), - returnValue: _FakeLanguage_6( - this, - Invocation.method(#findLanguageById, [id]), - ), - ) - as _i8.Language); - - @override - _i19.Future fetchAndSetCategoriesFromApi() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetCategoriesFromApi, []), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future fetchAndSetMusclesFromApi() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetMusclesFromApi, []), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future fetchAndSetEquipmentsFromApi() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetEquipmentsFromApi, []), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future fetchAndSetLanguagesFromApi() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetLanguagesFromApi, []), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future fetchAndSetAllExercises() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetAllExercises, []), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future<_i4.Exercise?> fetchAndSetExercise(int? exerciseId) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetExercise, [exerciseId]), - returnValue: _i19.Future<_i4.Exercise?>.value(), - ) - as _i19.Future<_i4.Exercise?>); - - @override - _i19.Future<_i4.Exercise> handleUpdateExerciseFromApi( - _i3.ExerciseDatabase? database, - int? exerciseId, - ) => - (super.noSuchMethod( - Invocation.method(#handleUpdateExerciseFromApi, [ - database, - exerciseId, - ]), - returnValue: _i19.Future<_i4.Exercise>.value( - _FakeExercise_2( - this, - Invocation.method(#handleUpdateExerciseFromApi, [ - database, - exerciseId, - ]), - ), - ), - ) - as _i19.Future<_i4.Exercise>); - - @override - _i19.Future initCacheTimesLocalPrefs({dynamic forceInit = false}) => - (super.noSuchMethod( - Invocation.method(#initCacheTimesLocalPrefs, [], { - #forceInit: forceInit, - }), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future clearAllCachesAndPrefs() => - (super.noSuchMethod( - Invocation.method(#clearAllCachesAndPrefs, []), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future fetchAndSetInitialData() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetInitialData, []), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future setExercisesFromDatabase( - _i3.ExerciseDatabase? database, { - bool? forceDeleteCache = false, - }) => - (super.noSuchMethod( - Invocation.method( - #setExercisesFromDatabase, - [database], - {#forceDeleteCache: forceDeleteCache}, - ), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future updateExerciseCache(_i3.ExerciseDatabase? database) => - (super.noSuchMethod( - Invocation.method(#updateExerciseCache, [database]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future fetchAndSetMuscles(_i3.ExerciseDatabase? database) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetMuscles, [database]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future fetchAndSetCategories(_i3.ExerciseDatabase? database) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetCategories, [database]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future fetchAndSetLanguages(_i3.ExerciseDatabase? database) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetLanguages, [database]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future fetchAndSetEquipments(_i3.ExerciseDatabase? database) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetEquipments, [database]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future> searchExercise( - String? name, { - String? languageCode = 'en', - bool? searchEnglish = false, - }) => - (super.noSuchMethod( - Invocation.method( - #searchExercise, - [name], - {#languageCode: languageCode, #searchEnglish: searchEnglish}, - ), - returnValue: _i19.Future>.value( - <_i4.Exercise>[], - ), - ) - as _i19.Future>); - - @override - void addListener(_i20.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#addListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void removeListener(_i20.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#removeListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void dispose() => super.noSuchMethod( - Invocation.method(#dispose, []), - returnValueForMissingStub: null, - ); - - @override - void notifyListeners() => super.noSuchMethod( - Invocation.method(#notifyListeners, []), - returnValueForMissingStub: null, - ); -} - -/// A class which mocks [RoutinesProvider]. -/// -/// See the documentation for Mockito's code generation for more information. -class MockRoutinesProvider extends _i1.Mock implements _i21.RoutinesProvider { - MockRoutinesProvider() { - _i1.throwOnMissingStub(this); - } - - @override - _i2.WgerBaseProvider get baseProvider => - (super.noSuchMethod( - Invocation.getter(#baseProvider), - returnValue: _FakeWgerBaseProvider_0( - this, - Invocation.getter(#baseProvider), - ), - ) - as _i2.WgerBaseProvider); - - @override - List<_i11.Routine> get items => - (super.noSuchMethod( - Invocation.getter(#items), - returnValue: <_i11.Routine>[], - ) - as List<_i11.Routine>); - - @override - List<_i9.WeightUnit> get weightUnits => - (super.noSuchMethod( - Invocation.getter(#weightUnits), - returnValue: <_i9.WeightUnit>[], - ) - as List<_i9.WeightUnit>); - - @override - _i9.WeightUnit get defaultWeightUnit => - (super.noSuchMethod( - Invocation.getter(#defaultWeightUnit), - returnValue: _FakeWeightUnit_7( - this, - Invocation.getter(#defaultWeightUnit), - ), - ) - as _i9.WeightUnit); - - @override - List<_i10.RepetitionUnit> get repetitionUnits => - (super.noSuchMethod( - Invocation.getter(#repetitionUnits), - returnValue: <_i10.RepetitionUnit>[], - ) - as List<_i10.RepetitionUnit>); - - @override - _i10.RepetitionUnit get defaultRepetitionUnit => - (super.noSuchMethod( - Invocation.getter(#defaultRepetitionUnit), - returnValue: _FakeRepetitionUnit_8( - this, - Invocation.getter(#defaultRepetitionUnit), - ), - ) - as _i10.RepetitionUnit); - - @override - set activeRoutine(_i11.Routine? value) => super.noSuchMethod( - Invocation.setter(#activeRoutine, value), - returnValueForMissingStub: null, - ); - - @override - set weightUnits(List<_i9.WeightUnit>? weightUnits) => super.noSuchMethod( - Invocation.setter(#weightUnits, weightUnits), - returnValueForMissingStub: null, - ); - - @override - set repetitionUnits(List<_i10.RepetitionUnit>? repetitionUnits) => super.noSuchMethod( - Invocation.setter(#repetitionUnits, repetitionUnits), - returnValueForMissingStub: null, - ); - - @override - bool get hasListeners => - (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false) as bool); - - @override - void clear() => super.noSuchMethod( - Invocation.method(#clear, []), - returnValueForMissingStub: null, - ); - - @override - _i9.WeightUnit findWeightUnitById(int? id) => - (super.noSuchMethod( - Invocation.method(#findWeightUnitById, [id]), - returnValue: _FakeWeightUnit_7( - this, - Invocation.method(#findWeightUnitById, [id]), - ), - ) - as _i9.WeightUnit); - - @override - _i10.RepetitionUnit findRepetitionUnitById(int? id) => - (super.noSuchMethod( - Invocation.method(#findRepetitionUnitById, [id]), - returnValue: _FakeRepetitionUnit_8( - this, - Invocation.method(#findRepetitionUnitById, [id]), - ), - ) - as _i10.RepetitionUnit); - - @override - List<_i11.Routine> getPlans() => - (super.noSuchMethod( - Invocation.method(#getPlans, []), - returnValue: <_i11.Routine>[], - ) - as List<_i11.Routine>); - - @override - _i11.Routine findById(int? id) => - (super.noSuchMethod( - Invocation.method(#findById, [id]), - returnValue: _FakeRoutine_9( - this, - Invocation.method(#findById, [id]), - ), - ) - as _i11.Routine); - - @override - int findIndexById(int? id) => - (super.noSuchMethod( - Invocation.method(#findIndexById, [id]), - returnValue: 0, - ) - as int); - - @override - _i19.Future fetchAndSetAllRoutinesFull() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetAllRoutinesFull, []), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future fetchAndSetAllRoutinesSparse() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetAllRoutinesSparse, []), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future setExercisesAndUnits( - List<_i22.DayData>? entries, { - Map? exercises, - }) => - (super.noSuchMethod( - Invocation.method( - #setExercisesAndUnits, - [entries], - {#exercises: exercises}, - ), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future<_i11.Routine> fetchAndSetRoutineSparse(int? planId) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetRoutineSparse, [planId]), - returnValue: _i19.Future<_i11.Routine>.value( - _FakeRoutine_9( - this, - Invocation.method(#fetchAndSetRoutineSparse, [planId]), - ), - ), - ) - as _i19.Future<_i11.Routine>); - - @override - _i19.Future<_i11.Routine> fetchAndSetRoutineFull(int? routineId) => - (super.noSuchMethod( - Invocation.method(#fetchAndSetRoutineFull, [routineId]), - returnValue: _i19.Future<_i11.Routine>.value( - _FakeRoutine_9( - this, - Invocation.method(#fetchAndSetRoutineFull, [routineId]), - ), - ), - ) - as _i19.Future<_i11.Routine>); - - @override - _i19.Future<_i11.Routine> addRoutine(_i11.Routine? routine) => - (super.noSuchMethod( - Invocation.method(#addRoutine, [routine]), - returnValue: _i19.Future<_i11.Routine>.value( - _FakeRoutine_9(this, Invocation.method(#addRoutine, [routine])), - ), - ) - as _i19.Future<_i11.Routine>); - - @override - _i19.Future editRoutine(_i11.Routine? routine) => - (super.noSuchMethod( - Invocation.method(#editRoutine, [routine]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future deleteRoutine(int? id) => - (super.noSuchMethod( - Invocation.method(#deleteRoutine, [id]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future fetchAndSetRepetitionUnits() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetRepetitionUnits, []), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future fetchAndSetWeightUnits() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetWeightUnits, []), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future fetchAndSetUnits() => - (super.noSuchMethod( - Invocation.method(#fetchAndSetUnits, []), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future<_i12.Day> addDay(_i12.Day? day) => - (super.noSuchMethod( - Invocation.method(#addDay, [day]), - returnValue: _i19.Future<_i12.Day>.value( - _FakeDay_10(this, Invocation.method(#addDay, [day])), - ), - ) - as _i19.Future<_i12.Day>); - - @override - _i19.Future editDay(_i12.Day? day) => - (super.noSuchMethod( - Invocation.method(#editDay, [day]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future editDays(List<_i12.Day>? days) => - (super.noSuchMethod( - Invocation.method(#editDays, [days]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future deleteDay(int? dayId) => - (super.noSuchMethod( - Invocation.method(#deleteDay, [dayId]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future<_i13.Slot> addSlot(_i13.Slot? slot, int? routineId) => - (super.noSuchMethod( - Invocation.method(#addSlot, [slot, routineId]), - returnValue: _i19.Future<_i13.Slot>.value( - _FakeSlot_11( - this, - Invocation.method(#addSlot, [slot, routineId]), - ), - ), - ) - as _i19.Future<_i13.Slot>); - - @override - _i19.Future deleteSlot(int? slotId, int? routineId) => - (super.noSuchMethod( - Invocation.method(#deleteSlot, [slotId, routineId]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future editSlot(_i13.Slot? slot, int? routineId) => - (super.noSuchMethod( - Invocation.method(#editSlot, [slot, routineId]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future editSlots(List<_i13.Slot>? slots, int? routineId) => - (super.noSuchMethod( - Invocation.method(#editSlots, [slots, routineId]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future<_i14.SlotEntry> addSlotEntry( - _i14.SlotEntry? entry, - int? routineId, - ) => - (super.noSuchMethod( - Invocation.method(#addSlotEntry, [entry, routineId]), - returnValue: _i19.Future<_i14.SlotEntry>.value( - _FakeSlotEntry_12( - this, - Invocation.method(#addSlotEntry, [entry, routineId]), - ), - ), - ) - as _i19.Future<_i14.SlotEntry>); - - @override - _i19.Future deleteSlotEntry(int? id, int? routineId) => - (super.noSuchMethod( - Invocation.method(#deleteSlotEntry, [id, routineId]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future editSlotEntry(_i14.SlotEntry? entry, int? routineId) => - (super.noSuchMethod( - Invocation.method(#editSlotEntry, [entry, routineId]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - String getConfigUrl(_i14.ConfigType? type) => - (super.noSuchMethod( - Invocation.method(#getConfigUrl, [type]), - returnValue: _i23.dummyValue( - this, - Invocation.method(#getConfigUrl, [type]), - ), - ) - as String); - - @override - _i19.Future<_i15.BaseConfig> editConfig( - _i15.BaseConfig? config, - _i14.ConfigType? type, - ) => - (super.noSuchMethod( - Invocation.method(#editConfig, [config, type]), - returnValue: _i19.Future<_i15.BaseConfig>.value( - _FakeBaseConfig_13( - this, - Invocation.method(#editConfig, [config, type]), - ), - ), - ) - as _i19.Future<_i15.BaseConfig>); - - @override - _i19.Future<_i15.BaseConfig> addConfig( - _i15.BaseConfig? config, - _i14.ConfigType? type, - ) => - (super.noSuchMethod( - Invocation.method(#addConfig, [config, type]), - returnValue: _i19.Future<_i15.BaseConfig>.value( - _FakeBaseConfig_13( - this, - Invocation.method(#addConfig, [config, type]), - ), - ), - ) - as _i19.Future<_i15.BaseConfig>); - - @override - _i19.Future deleteConfig(int? id, _i14.ConfigType? type) => - (super.noSuchMethod( - Invocation.method(#deleteConfig, [id, type]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future handleConfig( - _i14.SlotEntry? entry, - num? value, - _i14.ConfigType? type, - ) => - (super.noSuchMethod( - Invocation.method(#handleConfig, [entry, value, type]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - _i19.Future> fetchSessionData() => - (super.noSuchMethod( - Invocation.method(#fetchSessionData, []), - returnValue: _i19.Future>.value( - <_i16.WorkoutSession>[], - ), - ) - as _i19.Future>); - - @override - _i19.Future<_i16.WorkoutSession> addSession( - _i16.WorkoutSession? session, - int? routineId, - ) => - (super.noSuchMethod( - Invocation.method(#addSession, [session, routineId]), - returnValue: _i19.Future<_i16.WorkoutSession>.value( - _FakeWorkoutSession_14( - this, - Invocation.method(#addSession, [session, routineId]), - ), - ), - ) - as _i19.Future<_i16.WorkoutSession>); - - @override - _i19.Future<_i16.WorkoutSession> editSession(_i16.WorkoutSession? session) => - (super.noSuchMethod( - Invocation.method(#editSession, [session]), - returnValue: _i19.Future<_i16.WorkoutSession>.value( - _FakeWorkoutSession_14( - this, - Invocation.method(#editSession, [session]), - ), - ), - ) - as _i19.Future<_i16.WorkoutSession>); - - @override - _i19.Future<_i17.Log> addLog(_i17.Log? log) => - (super.noSuchMethod( - Invocation.method(#addLog, [log]), - returnValue: _i19.Future<_i17.Log>.value( - _FakeLog_15(this, Invocation.method(#addLog, [log])), - ), - ) - as _i19.Future<_i17.Log>); - - @override - _i19.Future deleteLog(int? logId, int? routineId) => - (super.noSuchMethod( - Invocation.method(#deleteLog, [logId, routineId]), - returnValue: _i19.Future.value(), - returnValueForMissingStub: _i19.Future.value(), - ) - as _i19.Future); - - @override - void addListener(_i20.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#addListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void removeListener(_i20.VoidCallback? listener) => super.noSuchMethod( - Invocation.method(#removeListener, [listener]), - returnValueForMissingStub: null, - ); - - @override - void dispose() => super.noSuchMethod( - Invocation.method(#dispose, []), - returnValueForMissingStub: null, - ); - - @override - void notifyListeners() => super.noSuchMethod( - Invocation.method(#notifyListeners, []), - returnValueForMissingStub: null, - ); -}