Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add Phase 6: Management Commands & Data Loading
Jeremy73fd2fec6743
diff --git a/package-lock.json b/package-lock.jsonindex bc225b079..838e04c4c 100644--- a/package-lock.json+++ b/package-lock.json@@ -52,6 +52,7 @@"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/code-frame": "^7.27.1","@babel/generator": "^7.28.5",@@ -384,6 +385,7 @@"integrity": "sha512-O000MLDBDdk/EohJPFUqvnp4qnHeYkVP5B0xEG0D/L7cOKP9kefu2DXn8dj74cQfsEzUqh+sr1RzFqiL1o+PpA==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/runtime": "^7.18.3","@emotion/babel-plugin": "^11.13.5",@@ -430,6 +432,7 @@"integrity": "sha512-qEEJt42DuToa3gurlH4Qqc1kVpNq8wO8cJtDzU46TjlzWjDlsVyevtYCRijVq3SrHsROS+gVQ8Fnea108GnKzw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/runtime": "^7.18.3","@emotion/babel-plugin": "^11.13.5",@@ -492,7 +495,6 @@"os": ["aix"],- "peer": true,"engines": {"node": ">=18"}@@ -510,7 +512,6 @@"os": ["android"],- "peer": true,"engines": {"node": ">=18"}@@ -528,7 +529,6 @@"os": ["android"],- "peer": true,"engines": {"node": ">=18"}@@ -546,7 +546,6 @@"os": ["android"],- "peer": true,"engines": {"node": ">=18"}@@ -564,7 +563,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">=18"}@@ -582,7 +580,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": ">=18"}@@ -600,7 +597,6 @@"os": ["freebsd"],- "peer": true,"engines": {"node": ">=18"}@@ -618,7 +614,6 @@"os": ["freebsd"],- "peer": true,"engines": {"node": ">=18"}@@ -636,7 +631,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -654,7 +648,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -672,7 +665,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -690,7 +682,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -708,7 +699,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -726,7 +716,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -744,7 +733,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -762,7 +750,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -780,7 +767,6 @@"os": ["linux"],- "peer": true,"engines": {"node": ">=18"}@@ -798,7 +784,6 @@"os": ["netbsd"],- "peer": true,"engines": {"node": ">=18"}@@ -816,7 +801,6 @@"os": ["netbsd"],- "peer": true,"engines": {"node": ">=18"}@@ -834,7 +818,6 @@"os": ["openbsd"],- "peer": true,"engines": {"node": ">=18"}@@ -852,7 +835,6 @@"os": ["openbsd"],- "peer": true,"engines": {"node": ">=18"}@@ -870,7 +852,6 @@"os": ["openharmony"],- "peer": true,"engines": {"node": ">=18"}@@ -888,7 +869,6 @@"os": ["sunos"],- "peer": true,"engines": {"node": ">=18"}@@ -906,7 +886,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">=18"}@@ -924,7 +903,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">=18"}@@ -942,7 +920,6 @@"os": ["win32"],- "peer": true,"engines": {"node": ">=18"}@@ -1104,6 +1081,7 @@"integrity": "sha512-8VVxFmp1GIm9PpmnQoCoYo0UWHoOrdA57tDL62vkpzEgvb/d71Wsbv4FRg7r1Gyx7PuSo0tflH34cdl/NvfHNQ==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/runtime": "^7.28.4","@mui/core-downloads-tracker": "^7.3.5",@@ -1217,6 +1195,7 @@"integrity": "sha512-yPaf5+gY3v80HNkJcPi6WT+r9ebeM4eJzrREXPxMt7pNTV/1eahyODO4fbH3Qvd8irNxDFYn5RQ3idHW55rA6g==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/runtime": "^7.28.4","@mui/private-theming": "^7.3.5",@@ -1458,6 +1437,7 @@"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz","integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==","license": "MIT",+ "peer": true,"funding": {"type": "opencollective","url": "https://opencollective.com/popperjs"@@ -1509,8 +1489,7 @@"optional": true,"os": ["android"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-android-arm64": {"version": "4.53.3",@@ -1524,8 +1503,7 @@"optional": true,"os": ["android"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-darwin-arm64": {"version": "4.53.3",@@ -1539,8 +1517,7 @@"optional": true,"os": ["darwin"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-darwin-x64": {"version": "4.53.3",@@ -1554,8 +1531,7 @@"optional": true,"os": ["darwin"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-freebsd-arm64": {"version": "4.53.3",@@ -1569,8 +1545,7 @@"optional": true,"os": ["freebsd"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-freebsd-x64": {"version": "4.53.3",@@ -1584,8 +1559,7 @@"optional": true,"os": ["freebsd"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-arm-gnueabihf": {"version": "4.53.3",@@ -1599,8 +1573,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-arm-musleabihf": {"version": "4.53.3",@@ -1614,8 +1587,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-arm64-gnu": {"version": "4.53.3",@@ -1629,8 +1601,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-arm64-musl": {"version": "4.53.3",@@ -1644,8 +1615,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-loong64-gnu": {"version": "4.53.3",@@ -1659,8 +1629,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-ppc64-gnu": {"version": "4.53.3",@@ -1674,8 +1643,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-riscv64-gnu": {"version": "4.53.3",@@ -1689,8 +1657,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-riscv64-musl": {"version": "4.53.3",@@ -1704,8 +1671,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-s390x-gnu": {"version": "4.53.3",@@ -1719,8 +1685,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-x64-gnu": {"version": "4.53.3",@@ -1734,8 +1699,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-linux-x64-musl": {"version": "4.53.3",@@ -1749,8 +1713,7 @@"optional": true,"os": ["linux"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-openharmony-arm64": {"version": "4.53.3",@@ -1764,8 +1727,7 @@"optional": true,"os": ["openharmony"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-win32-arm64-msvc": {"version": "4.53.3",@@ -1779,8 +1741,7 @@"optional": true,"os": ["win32"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-win32-ia32-msvc": {"version": "4.53.3",@@ -1794,8 +1755,7 @@"optional": true,"os": ["win32"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-win32-x64-gnu": {"version": "4.53.3",@@ -1809,8 +1769,7 @@"optional": true,"os": ["win32"- ],- "peer": true+ ]},"node_modules/@rollup/rollup-win32-x64-msvc": {"version": "4.53.3",@@ -1824,8 +1783,7 @@"optional": true,"os": ["win32"- ],- "peer": true+ ]},"node_modules/@standard-schema/spec": {"version": "1.0.0",@@ -1991,8 +1949,7 @@"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz","integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==","dev": true,- "license": "MIT",- "peer": true+ "license": "MIT"},"node_modules/@types/hoist-non-react-statics": {"version": "3.3.7",@@ -2194,6 +2151,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"baseline-browser-mapping": "^2.8.25","caniuse-lite": "^1.0.30001754",@@ -2675,7 +2633,6 @@"dev": true,"hasInstallScript": true,"license": "MIT",- "peer": true,"bin": {"esbuild": "bin/esbuild"},@@ -2753,7 +2710,6 @@"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==","dev": true,"license": "MIT",- "peer": true,"engines": {"node": ">=12.0.0"},@@ -2857,7 +2813,6 @@"os": ["darwin"],- "peer": true,"engines": {"node": "^8.16.0 || ^10.6.0 || >=11.0.0"}@@ -3059,6 +3014,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"@babel/runtime": "^7.28.4"},@@ -3156,7 +3112,8 @@"version": "3.7.1","resolved": "https://registry.npmjs.org/jquery/-/jquery-3.7.1.tgz","integrity": "sha512-m4avr8yL8kmFN8psrbFFFmB/If14iN5o9nw/NgnnM+kybDJpRsAynV2BsfpTYrTRysYUdADVD7CkUUizgkpLfg==",- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/js-tokens": {"version": "4.0.0",@@ -3248,6 +3205,7 @@"integrity": "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"}@@ -3324,7 +3282,6 @@}],"license": "MIT",- "peer": true,"bin": {"nanoid": "bin/nanoid.cjs"},@@ -3471,7 +3428,6 @@}],"license": "MIT",- "peer": true,"dependencies": {"nanoid": "^3.3.11","picocolors": "^1.1.1",@@ -3537,6 +3493,7 @@"integrity": "sha512-UlbRu4cAiGaIewkPyiRGJk0imDN2T3JjieT6spoL2UeSf5od4n5LB/mQ4ejmxhCFT1tYe8IvaFulzynWovsEFQ==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"scheduler": "^0.27.0"},@@ -3584,7 +3541,8 @@"resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.0.tgz","integrity": "sha512-x3Ax3kNSMIIkyVYhWPyO09bu0uttcAIoecO/um/rKGQ4EltYWVYtyiGkS/3xMynrbVQdS69Jhlv8FXUEZehlzA==","dev": true,- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/react-redux": {"version": "9.2.0",@@ -3742,7 +3700,8 @@"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz","integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==","dev": true,- "license": "MIT"+ "license": "MIT",+ "peer": true},"node_modules/redux-thunk": {"version": "3.1.0",@@ -3798,7 +3757,6 @@"integrity": "sha512-w8GmOxZfBmKknvdXU1sdM9NHcoQejwF/4mNgj2JuEEdRaHwwF12K7e9eXn1nLZ07ad+du76mkVsyeb2rKGllsA==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@types/estree": "1.0.8"},@@ -3892,7 +3850,6 @@"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==","dev": true,"license": "BSD-3-Clause",- "peer": true,"engines": {"node": ">=0.10.0"}@@ -3944,7 +3901,6 @@"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"fdir": "^6.5.0","picomatch": "^4.0.3"@@ -4017,6 +3973,7 @@"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==","dev": true,"license": "Apache-2.0",+ "peer": true,"bin": {"tsc": "bin/tsc","tsserver": "bin/tsserver"@@ -4227,21 +4184,6 @@"dev": true,"license": "ISC"},- "node_modules/yaml": {- "version": "2.8.1",- "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.8.1.tgz",- "integrity": "sha512-lcYcMxX2PO9XMGvAJkJ3OsNMw+/7FKes7/hgerGUYWIoWu5j/+YQqcZr5JnPZWzOsEBgMbSbiSTn/dv/69Mkpw==",- "dev": true,- "license": "ISC",- "optional": true,- "peer": true,- "bin": {- "yaml": "bin.mjs"- },- "engines": {- "node": ">= 14.6"- }- },"node_modules/yup": {"version": "1.7.1","resolved": "https://registry.npmjs.org/yup/-/yup-1.7.1.tgz",diff --git a/wger/trophies/fixtures/initial_trophies.json b/wger/trophies/fixtures/initial_trophies.jsonnew file mode 100644index 000000000..cbeef12ff--- /dev/null+++ b/wger/trophies/fixtures/initial_trophies.json@@ -0,0 +1,137 @@+[+ {+ "model": "trophies.trophy",+ "pk": 1,+ "fields": {+ "name": "Beginner",+ "description": "Complete your first workout",+ "trophy_type": "count",+ "checker_class": "count_based",+ "checker_params": {"count": 1},+ "is_hidden": false,+ "is_progressive": false,+ "is_active": true,+ "order": 1+ }+ },+ {+ "model": "trophies.trophy",+ "pk": 2,+ "fields": {+ "name": "Unstoppable",+ "description": "Maintain a 30-day workout streak",+ "trophy_type": "sequence",+ "checker_class": "streak",+ "checker_params": {"days": 30},+ "is_hidden": false,+ "is_progressive": true,+ "is_active": true,+ "order": 2+ }+ },+ {+ "model": "trophies.trophy",+ "pk": 3,+ "fields": {+ "name": "Weekend Warrior",+ "description": "Work out on Saturday and Sunday for 4 consecutive weekends",+ "trophy_type": "sequence",+ "checker_class": "weekend_warrior",+ "checker_params": {"weekends": 4},+ "is_hidden": false,+ "is_progressive": true,+ "is_active": true,+ "order": 3+ }+ },+ {+ "model": "trophies.trophy",+ "pk": 4,+ "fields": {+ "name": "Lifter",+ "description": "Lift a cumulative total of 5,000 kg",+ "trophy_type": "volume",+ "checker_class": "volume",+ "checker_params": {"kg": 5000},+ "is_hidden": false,+ "is_progressive": true,+ "is_active": true,+ "order": 4+ }+ },+ {+ "model": "trophies.trophy",+ "pk": 5,+ "fields": {+ "name": "Atlas",+ "description": "Lift a cumulative total of 100,000 kg",+ "trophy_type": "volume",+ "checker_class": "volume",+ "checker_params": {"kg": 100000},+ "is_hidden": false,+ "is_progressive": true,+ "is_active": true,+ "order": 5+ }+ },+ {+ "model": "trophies.trophy",+ "pk": 6,+ "fields": {+ "name": "Early Bird",+ "description": "Complete a workout before 6:00 AM",+ "trophy_type": "time",+ "checker_class": "time_based",+ "checker_params": {"before": "06:00"},+ "is_hidden": false,+ "is_progressive": false,+ "is_active": true,+ "order": 6+ }+ },+ {+ "model": "trophies.trophy",+ "pk": 7,+ "fields": {+ "name": "Night Owl",+ "description": "Complete a workout after 9:00 PM",+ "trophy_type": "time",+ "checker_class": "time_based",+ "checker_params": {"after": "21:00"},+ "is_hidden": false,+ "is_progressive": false,+ "is_active": true,+ "order": 7+ }+ },+ {+ "model": "trophies.trophy",+ "pk": 8,+ "fields": {+ "name": "New Year, New Me",+ "description": "Work out on January 1st",+ "trophy_type": "date",+ "checker_class": "date_based",+ "checker_params": {"month": 1, "day": 1},+ "is_hidden": false,+ "is_progressive": false,+ "is_active": true,+ "order": 8+ }+ },+ {+ "model": "trophies.trophy",+ "pk": 9,+ "fields": {+ "name": "Phoenix",+ "description": "Return to training after being inactive for 30 days",+ "trophy_type": "other",+ "checker_class": "inactivity_return",+ "checker_params": {"inactive_days": 30},+ "is_hidden": true,+ "is_progressive": false,+ "is_active": true,+ "order": 9+ }+ }+]diff --git a/wger/trophies/management/commands/evaluate_trophies.py b/wger/trophies/management/commands/evaluate_trophies.pynew file mode 100644index 000000000..d1a3cdb20--- /dev/null+++ b/wger/trophies/management/commands/evaluate_trophies.py@@ -0,0 +1,148 @@+# This file is part of wger Workout Manager <https://github.com/wger-project>.+# Copyright (C) 2013 - 2021 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,+# 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 <http://www.gnu.org/licenses/>.++# Django+from django.contrib.auth.models import User+from django.core.management.base import (+ BaseCommand,+ CommandError,+)++# wger+from wger.trophies.models import Trophy+from wger.trophies.services.trophy import TrophyService+++class Command(BaseCommand):+ """+ Manually trigger trophy evaluation for users.++ This command allows administrators to evaluate trophies for specific+ users, specific trophies, or all trophies for all users.+ """++ help = 'Evaluate trophies for users'++ def add_arguments(self, parser):+ parser.add_argument(+ '--user',+ type=str,+ dest='username',+ help='Username of the user to evaluate trophies for',+ )++ parser.add_argument(+ '--trophy',+ type=int,+ dest='trophy_id',+ help='ID of a specific trophy to evaluate',+ )++ parser.add_argument(+ '--all',+ action='store_true',+ dest='all',+ default=False,+ help='Evaluate all trophies for all active users',+ )++ parser.add_argument(+ '--force-reevaluate',+ action='store_true',+ dest='force_reevaluate',+ default=False,+ help='Re-evaluate all trophies, including already earned ones',+ )++ def handle(self, **options):+ """+ Process the trophy evaluation based on provided options.+ """+ verbosity = int(options['verbosity'])+ username = options['username']+ trophy_id = options['trophy_id']+ evaluate_all = options['all']+ force_reevaluate = options['force_reevaluate']++ # Validate that at least one option is provided+ if not username and not trophy_id and not evaluate_all:+ raise CommandError(+ 'Please specify --user, --trophy, or --all. See help for details.'+ )++ # Case 1: Evaluate for a specific user+ if username:+ try:+ user = User.objects.get(username=username)+ except User.DoesNotExist:+ raise CommandError(f'User "{username}" does not exist')++ if verbosity >= 1:+ self.stdout.write(f'Evaluating trophies for user: {username}')++ awarded = TrophyService.evaluate_all_trophies(user)++ if verbosity >= 2:+ for user_trophy in awarded:+ self.stdout.write(+ self.style.SUCCESS(+ f'✓ Awarded trophy "{user_trophy.trophy.name}" to {username}'+ )+ )++ if verbosity >= 1:+ self.stdout.write(+ self.style.SUCCESS(+ f'\nEvaluation complete: {len(awarded)} trophy(ies) awarded'+ )+ )++ # Case 2: Evaluate a specific trophy for all users (or force re-evaluation)+ elif trophy_id or evaluate_all or force_reevaluate:+ trophy_ids = None+ if trophy_id:+ # Validate trophy exists+ try:+ trophy = Trophy.objects.get(id=trophy_id)+ trophy_ids = [trophy_id]++ if verbosity >= 1:+ self.stdout.write(+ f'Evaluating trophy "{trophy.name}" for all users'+ )+ except Trophy.DoesNotExist:+ raise CommandError(f'Trophy with ID {trophy_id} does not exist')+ else:+ if verbosity >= 1:+ self.stdout.write('Evaluating all trophies for all users')++ # Use the reevaluate service method+ results = TrophyService.reevaluate_trophies(+ trophy_ids=trophy_ids,+ user_ids=None, # All active users+ )++ if verbosity >= 1:+ self.stdout.write(+ self.style.SUCCESS(+ f'\nEvaluation complete:\n'+ f' Users checked: {results["users_checked"]}\n'+ f' Trophies awarded: {results["trophies_awarded"]}'+ )+ )++ # Case 3: Force re-evaluation (handled above)+ # The force_reevaluate flag is implicit in using reevaluate_trophies methoddiff --git a/wger/trophies/management/commands/load_trophies.py b/wger/trophies/management/commands/load_trophies.pynew file mode 100644index 000000000..c1cb0c74d--- /dev/null+++ b/wger/trophies/management/commands/load_trophies.py@@ -0,0 +1,196 @@+# This file is part of wger Workout Manager <https://github.com/wger-project>.+# Copyright (C) 2013 - 2021 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,+# 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 <http://www.gnu.org/licenses/>.++# Django+from django.core.management.base import BaseCommand+from django.utils.translation import gettext_lazy as _++# wger+from wger.trophies.models import Trophy+++class Command(BaseCommand):+ """+ Load initial trophy definitions into the database.++ This command is idempotent - it can be run multiple times safely.+ Existing trophies with the same name will be updated, not duplicated.+ """++ help = 'Load initial trophy definitions into the database'++ def add_arguments(self, parser):+ parser.add_argument(+ '--update',+ action='store_true',+ dest='update',+ default=False,+ help='Update existing trophies if they already exist',+ )++ def handle(self, **options):+ """+ Load the initial trophy definitions.+ """+ verbosity = int(options['verbosity'])+ update_existing = options['update']++ # Define the initial trophies+ trophies_data = [+ {+ 'name': _('Beginner'),+ 'description': _('Complete your first workout'),+ 'trophy_type': Trophy.TYPE_COUNT,+ 'checker_class': 'count_based',+ 'checker_params': {'count': 1},+ 'is_hidden': False,+ 'is_progressive': False,+ 'order': 1,+ },+ {+ 'name': _('Unstoppable'),+ 'description': _('Maintain a 30-day workout streak'),+ 'trophy_type': Trophy.TYPE_SEQUENCE,+ 'checker_class': 'streak',+ 'checker_params': {'days': 30},+ 'is_hidden': False,+ 'is_progressive': True,+ 'order': 2,+ },+ {+ 'name': _('Weekend Warrior'),+ 'description': _('Work out on Saturday and Sunday for 4 consecutive weekends'),+ 'trophy_type': Trophy.TYPE_SEQUENCE,+ 'checker_class': 'weekend_warrior',+ 'checker_params': {'weekends': 4},+ 'is_hidden': False,+ 'is_progressive': True,+ 'order': 3,+ },+ {+ 'name': _('Lifter'),+ 'description': _('Lift a cumulative total of 5,000 kg'),+ 'trophy_type': Trophy.TYPE_VOLUME,+ 'checker_class': 'volume',+ 'checker_params': {'kg': 5000},+ 'is_hidden': False,+ 'is_progressive': True,+ 'order': 4,+ },+ {+ 'name': _('Atlas'),+ 'description': _('Lift a cumulative total of 100,000 kg'),+ 'trophy_type': Trophy.TYPE_VOLUME,+ 'checker_class': 'volume',+ 'checker_params': {'kg': 100000},+ 'is_hidden': False,+ 'is_progressive': True,+ 'order': 5,+ },+ {+ 'name': _('Early Bird'),+ 'description': _('Complete a workout before 6:00 AM'),+ 'trophy_type': Trophy.TYPE_TIME,+ 'checker_class': 'time_based',+ 'checker_params': {'before': '06:00'},+ 'is_hidden': False,+ 'is_progressive': False,+ 'order': 6,+ },+ {+ 'name': _('Night Owl'),+ 'description': _('Complete a workout after 9:00 PM'),+ 'trophy_type': Trophy.TYPE_TIME,+ 'checker_class': 'time_based',+ 'checker_params': {'after': '21:00'},+ 'is_hidden': False,+ 'is_progressive': False,+ 'order': 7,+ },+ {+ 'name': _('New Year, New Me'),+ 'description': _('Work out on January 1st'),+ 'trophy_type': Trophy.TYPE_DATE,+ 'checker_class': 'date_based',+ 'checker_params': {'month': 1, 'day': 1},+ 'is_hidden': False,+ 'is_progressive': False,+ 'order': 8,+ },+ {+ 'name': _('Phoenix'),+ 'description': _('Return to training after being inactive for 30 days'),+ 'trophy_type': Trophy.TYPE_OTHER,+ 'checker_class': 'inactivity_return',+ 'checker_params': {'inactive_days': 30},+ 'is_hidden': True,+ 'is_progressive': False,+ 'order': 9,+ },+ ]++ created_count = 0+ updated_count = 0+ skipped_count = 0++ for trophy_data in trophies_data:+ # Convert lazy translation to string for database lookup+ name = str(trophy_data['name'])++ # Check if trophy already exists+ existing = Trophy.objects.filter(name=name).first()++ if existing:+ if update_existing:+ # Update existing trophy+ for key, value in trophy_data.items():+ if key != 'name': # Don't update the name+ setattr(existing, key, value)+ existing.save()+ updated_count += 1++ if verbosity >= 2:+ self.stdout.write(+ self.style.SUCCESS(f'✓ Updated trophy: {name}')+ )+ else:+ skipped_count += 1++ if verbosity >= 2:+ self.stdout.write(+ self.style.WARNING(f'- Skipped existing trophy: {name}')+ )+ else:+ # Create new trophy+ Trophy.objects.create(**trophy_data)+ created_count += 1++ if verbosity >= 2:+ self.stdout.write(+ self.style.SUCCESS(f'+ Created trophy: {name}')+ )++ # Summary+ if verbosity >= 1:+ self.stdout.write(+ self.style.SUCCESS(+ f'\nTrophy loading complete:\n'+ f' Created: {created_count}\n'+ f' Updated: {updated_count}\n'+ f' Skipped: {skipped_count}\n'+ f' Total: {len(trophies_data)}'+ )+ )diff --git a/wger/trophies/management/commands/recalculate_statistics.py b/wger/trophies/management/commands/recalculate_statistics.pynew file mode 100644index 000000000..50624f31a--- /dev/null+++ b/wger/trophies/management/commands/recalculate_statistics.py@@ -0,0 +1,164 @@+# This file is part of wger Workout Manager <https://github.com/wger-project>.+# Copyright (C) 2013 - 2021 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,+# 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 <http://www.gnu.org/licenses/>.++# Standard Library+from datetime import timedelta++# Django+from django.conf import settings+from django.contrib.auth.models import User+from django.core.management.base import (+ BaseCommand,+ CommandError,+)+from django.utils import timezone++# wger+from wger.trophies.services.statistics import UserStatisticsService+++class Command(BaseCommand):+ """+ Recalculate user statistics from workout history.++ This command performs a full recalculation of UserStatistics for+ specified users by analyzing their complete workout history.+ """++ help = 'Recalculate user statistics from workout history'++ def add_arguments(self, parser):+ parser.add_argument(+ '--user',+ type=str,+ dest='username',+ help='Username of the user to recalculate statistics for',+ )++ parser.add_argument(+ '--all',+ action='store_true',+ dest='all',+ default=False,+ help='Recalculate statistics for all users',+ )++ parser.add_argument(+ '--active-only',+ action='store_true',+ dest='active_only',+ default=False,+ help='Only process users who logged in recently (with --all)',+ )++ def handle(self, **options):+ """+ Process the statistics recalculation based on provided options.+ """+ verbosity = int(options['verbosity'])+ username = options['username']+ recalculate_all = options['all']+ active_only = options['active_only']++ # Validate that at least one option is provided+ if not username and not recalculate_all:+ raise CommandError(+ 'Please specify --user or --all. See help for details.'+ )++ # Case 1: Recalculate for a specific user+ if username:+ try:+ user = User.objects.get(username=username)+ except User.DoesNotExist:+ raise CommandError(f'User "{username}" does not exist')++ if verbosity >= 1:+ self.stdout.write(f'Recalculating statistics for user: {username}')++ stats = UserStatisticsService.update_statistics(user)++ if verbosity >= 2:+ self.stdout.write(+ self.style.SUCCESS(+ f'\n✓ Statistics updated:\n'+ f' Total workouts: {stats.total_workouts}\n'+ f' Total weight lifted: {stats.total_weight_lifted} kg\n'+ f' Current streak: {stats.current_streak} days\n'+ f' Longest streak: {stats.longest_streak} days\n'+ f' Weekend streak: {stats.weekend_workout_streak} weekends'+ )+ )++ if verbosity >= 1:+ self.stdout.write(+ self.style.SUCCESS(f'\nRecalculation complete for {username}')+ )++ # Case 2: Recalculate for all users+ elif recalculate_all:+ # Get users to process+ users = User.objects.all()++ if active_only:+ # Only process users who logged in recently+ inactive_days = settings.WGER_SETTINGS.get('TROPHIES_INACTIVE_USER_DAYS', 30)+ inactive_threshold = timezone.now() - timedelta(days=inactive_days)+ users = users.filter(last_login__gte=inactive_threshold)++ if verbosity >= 1:+ self.stdout.write(+ f'Recalculating statistics for active users '+ f'(logged in within {inactive_days} days)'+ )+ else:+ if verbosity >= 1:+ self.stdout.write('Recalculating statistics for all users')++ total_users = users.count()+ processed = 0+ errors = 0++ for user in users:+ try:+ UserStatisticsService.update_statistics(user)+ processed += 1++ if verbosity >= 2:+ self.stdout.write(+ self.style.SUCCESS(f'✓ Processed: {user.username}')+ )+ elif verbosity >= 1 and processed % 100 == 0:+ self.stdout.write(f' Processed {processed}/{total_users} users...')++ except Exception as e:+ errors += 1+ if verbosity >= 1:+ self.stdout.write(+ self.style.ERROR(+ f'✗ Error processing {user.username}: {str(e)}'+ )+ )++ if verbosity >= 1:+ self.stdout.write(+ self.style.SUCCESS(+ f'\nRecalculation complete:\n'+ f' Total users: {total_users}\n'+ f' Processed: {processed}\n'+ f' Errors: {errors}'+ )+ )