Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Let users submit ingredients to the database

Roland Geider05e5293e0d06
diff --git a/wger/exercises/models.py b/wger/exercises/models.py
index 20b2b87f9..7d0c4ba00 100644
--- a/wger/exercises/models.py
+++ b/wger/exercises/models.py
@@ -113,6 +113,10 @@ EXERCISE_STATUS = (
(EXERCISE_STATUS_SYSTEM, _('System exercise')),
)
+EXERCISE_STATUS_OK = (EXERCISE_STATUS_ACCEPTED,
+ EXERCISE_STATUS_ADMIN,
+ EXERCISE_STATUS_SYSTEM)
+
class Exercise(models.Model):
'''
diff --git a/wger/exercises/sitemap.py b/wger/exercises/sitemap.py
index 5ac52792a..1da481a15 100644
--- a/wger/exercises/sitemap.py
+++ b/wger/exercises/sitemap.py
@@ -16,6 +16,7 @@
from django.contrib.sitemaps import Sitemap
from wger.exercises.models import Exercise
+from wger.exercises.models import EXERCISE_STATUS_OK
from wger.utils.language import load_language
@@ -24,4 +25,5 @@ class ExercisesSitemap(Sitemap):
priority = 0.5
def items(self):
- return Exercise.objects.filter(category__language=load_language())
+ return (Exercise.objects.filter(category__language=load_language())
+ .filter(status__in=EXERCISE_STATUS_OK))
diff --git a/wger/exercises/templates/exercise/form.html b/wger/exercises/templates/exercise/form.html
index 45570aa14..c3ab64a48 100644
--- a/wger/exercises/templates/exercise/form.html
+++ b/wger/exercises/templates/exercise/form.html
@@ -6,7 +6,7 @@
appreciated!{% endblocktrans %}</strong></p>
<p>{% blocktrans %}After you submit the form, the administrators will be notified.
-Once the exercise is reviewed, it will be added to the database. Till this happens,
+Once it is reviewed, it will be added to the database. Till this happens,
it will not be visible in the overview or the search. In case you added your email
when you registered, you will get notified when the process is completed sucessfully.{% endblocktrans %}</p>
{% endif %}
\ No newline at end of file
diff --git a/wger/exercises/views/exercises.py b/wger/exercises/views/exercises.py
index bd1d04976..96ffbafcc 100644
--- a/wger/exercises/views/exercises.py
+++ b/wger/exercises/views/exercises.py
@@ -50,6 +50,7 @@ from wger.exercises.models import EXERCISE_STATUS_ACCEPTED
from wger.exercises.models import EXERCISE_STATUS_DECLINED
from wger.exercises.models import EXERCISE_STATUS_ADMIN
from wger.exercises.models import EXERCISE_STATUS_SYSTEM
+from wger.exercises.models import EXERCISE_STATUS_OK
from wger.utils.generic_views import YamlFormMixin
from wger.utils.generic_views import YamlDeleteMixin
@@ -59,14 +60,7 @@ from wger.utils.constants import EMAIL_FROM
logger = logging.getLogger('workout_manager.custom')
-allowed_status = (EXERCISE_STATUS_ACCEPTED,
- EXERCISE_STATUS_ADMIN,
- EXERCISE_STATUS_SYSTEM)
-
-# ************************
-# Exercises
-# ************************
def overview(request):
'''
Overview with all exercises
@@ -76,9 +70,9 @@ def overview(request):
template_data = {}
template_data.update(csrf(request))
- categories = ExerciseCategory.objects.filter(language=language.id,
- exercise__status__in=allowed_status
- ).distinct()
+ categories = (ExerciseCategory.objects.filter(language=language.id)
+ .filter(exercise__status__in=EXERCISE_STATUS_OK)
+ .distinct())
template_data['categories'] = categories
return render_to_response('overview.html',
@@ -317,11 +311,11 @@ def search(request):
# Perform the search
q = request.GET.get('term', '')
user_language = load_language()
- exercises = Exercise.objects.filter(name__icontains=q,
- category__language_id=user_language,
- status__in=allowed_status)\
- .order_by('category__name', 'name')\
- .distinct()
+ exercises = (Exercise.objects.filter(name__icontains=q)
+ .filter(category__language_id=user_language)
+ .filter(status__in=EXERCISE_STATUS_OK)
+ .order_by('category__name', 'name')
+ .distinct())
# AJAX-request, this comes from the autocompleter. Create a list and send
# it back as JSON
diff --git a/wger/manager/templates/template.html b/wger/manager/templates/template.html
index 0321d337a..32fe2958c 100644
--- a/wger/manager/templates/template.html
+++ b/wger/manager/templates/template.html
@@ -141,6 +141,7 @@
<li><a href="{% url 'ingredient-list' %}">{% trans "Ingredient overview" %}</a></li>
{% if perms.exercises %}
<li><a href="{% url 'weight-unit-list' %}">{% trans "Ingredient weight units" %}</a></li>
+ <li><a href="{% url 'ingredient-pending' %}">{% trans "Ingredients pending review" %}</a></li>
{% endif %}
</ul>
</li>
diff --git a/wger/manager/tests/sitemap.py b/wger/manager/tests/sitemap.py
index c4ccb1079..738393b5e 100644
--- a/wger/manager/tests/sitemap.py
+++ b/wger/manager/tests/sitemap.py
@@ -28,4 +28,4 @@ class SitemapTestCase(WorkoutManagerTestCase):
response = self.client.get(reverse('sitemap'))
self.assertEqual(response.status_code, 200)
- self.assertEqual(len(response.context['urlset']), 14)
+ self.assertEqual(len(response.context['urlset']), 13)
diff --git a/wger/nutrition/fixtures/test-ingredients.json b/wger/nutrition/fixtures/test-ingredients.json
index c65924bb3..e959c3271 100644
--- a/wger/nutrition/fixtures/test-ingredients.json
+++ b/wger/nutrition/fixtures/test-ingredients.json
@@ -3,6 +3,8 @@
"pk": 1,
"model": "nutrition.ingredient",
"fields": {
+ "status": "5",
+ "user": null,
"update_date": "2013-02-12",
"creation_date": "2013-01-01",
"name": "Test ingredient 1",
@@ -21,6 +23,8 @@
"pk": 2,
"model": "nutrition.ingredient",
"fields": {
+ "status": "5",
+ "user": null,
"name": "Ingredient, test, 2, organic, raw",
"creation_date": "2013-01-01",
"language": 2,
@@ -38,6 +42,8 @@
"pk": 3,
"model": "nutrition.ingredient",
"fields": {
+ "status": "5",
+ "user": null,
"update_date": "2013-03-22",
"creation_date": "2013-02-03",
"name": "Bachelor chow, now with flavour!",
@@ -56,6 +62,8 @@
"pk": 4,
"model": "nutrition.ingredient",
"fields": {
+ "status": "5",
+ "user": null,
"creation_date": "2013-04-05",
"name": "Slurm",
"language": 2,
@@ -73,6 +81,8 @@
"pk": 5,
"model": "nutrition.ingredient",
"fields": {
+ "status": "5",
+ "user": null,
"creation_date": "2013-04-05",
"name": "Another tasty ingredient",
"language": 2,
@@ -90,6 +100,8 @@
"pk": 6,
"model": "nutrition.ingredient",
"fields": {
+ "status": "5",
+ "user": null,
"creation_date": "2013-04-05",
"name": "Raw ingredient",
"language": 2,
@@ -103,6 +115,25 @@
"carbohydrates": "5.0"
}
},
+ {
+ "pk": 7,
+ "model": "nutrition.ingredient",
+ "fields": {
+ "status": "1",
+ "user": 2,
+ "creation_date": "2013-04-05",
+ "name": "Pending ingredient",
+ "language": 2,
+ "sodium": "2.1",
+ "energy": 180,
+ "fat": "2",
+ "carbohydrates_sugar": "4",
+ "fat_saturated": "0",
+ "fibres": "20",
+ "protein": "10",
+ "carbohydrates": "5.0"
+ }
+ },
{
"pk": 1,
"model": "nutrition.ingredientweightunit",
diff --git a/wger/nutrition/models.py b/wger/nutrition/models.py
index b7c401096..8607e9718 100644
--- a/wger/nutrition/models.py
+++ b/wger/nutrition/models.py
@@ -109,14 +109,46 @@ class Ingredient(models.Model):
ENERGY_APPROXIMATION = 15
'''
How much the calculated energy from protein, etc. can deviate from the
- energy amount given.
+ energy amount given (in percent).
'''
+ INGREDIENT_STATUS_PENDING = '1'
+ INGREDIENT_STATUS_ACCEPTED = '2'
+ INGREDIENT_STATUS_DECLINED = '3'
+ INGREDIENT_STATUS_ADMIN = '4'
+ INGREDIENT_STATUS_SYSTEM = '5'
+
+ INGREDIENT_STATUS_OK = (INGREDIENT_STATUS_ACCEPTED,
+ INGREDIENT_STATUS_ADMIN,
+ INGREDIENT_STATUS_SYSTEM)
+
+ INGREDIENT_STATUS = (
+ (INGREDIENT_STATUS_PENDING, _('Pending')),
+ (INGREDIENT_STATUS_ACCEPTED, _('Accepted')),
+ (INGREDIENT_STATUS_DECLINED, _('Declined')),
+ (INGREDIENT_STATUS_ADMIN, _('Submitted by administrator')),
+ (INGREDIENT_STATUS_SYSTEM, _('System ingredient')),
+ )
+
# Metaclass to set some other properties
class Meta:
ordering = ["name", ]
language = models.ForeignKey(Language, verbose_name=_('Language'))
+
+ user = models.ForeignKey(User,
+ verbose_name=_('User'),
+ null=True,
+ blank=True,
+ editable=False)
+ '''The user that submitted the exercise'''
+
+ status = models.CharField(max_length=2,
+ choices=INGREDIENT_STATUS,
+ default=INGREDIENT_STATUS_PENDING,
+ editable=False)
+ '''The status of an ingredient'''
+
creation_date = models.DateField(_('Date'), auto_now_add=True)
update_date = models.DateField(_('Date'),
default=datetime.date.today,
@@ -186,7 +218,7 @@ class Ingredient(models.Model):
- 1g of protein: 4kcal
- 1g of carbohydrates: 4kcal
- 1g of fat: 9kcal
-
+
The sum is then compared to the given total energy, with ENERGY_APPROXIMATION
percent tolerance.
'''
diff --git a/wger/nutrition/sitemap.py b/wger/nutrition/sitemap.py
index e9d3ad724..295c201ef 100644
--- a/wger/nutrition/sitemap.py
+++ b/wger/nutrition/sitemap.py
@@ -25,4 +25,5 @@ class NutritionSitemap(Sitemap):
priority = 0.5
def items(self):
- return Ingredient.objects.filter(language=load_language())
+ return (Ingredient.objects.filter(language=load_language())
+ .filter(status__in=Ingredient.INGREDIENT_STATUS_OK))
diff --git a/wger/nutrition/templates/ingredient/form.html b/wger/nutrition/templates/ingredient/form.html
new file mode 100644
index 000000000..5891a06ec
--- /dev/null
+++ b/wger/nutrition/templates/ingredient/form.html
@@ -0,0 +1,12 @@
+{% load i18n %}
+
+{% if not perms.exercises %}
+<h3>{% trans "Submitting an ingredient" %}</h3>
+<p><strong>{% blocktrans %}Thank you for submitting an ingredient. This is much
+appreciated!{% endblocktrans %}</strong></p>
+
+<p>{% blocktrans %}After you submit the form, the administrators will be notified.
+Once it is reviewed, it will be added to the database. Till this happens,
+it will not be visible in the overview or the search. In case you added your email
+when you registered, you will get notified when the process is completed sucessfully.{% endblocktrans %}</p>
+{% endif %}
\ No newline at end of file
diff --git a/wger/nutrition/templates/ingredient/overview.html b/wger/nutrition/templates/ingredient/overview.html
index 35769cdf4..04a6e1e91 100644
--- a/wger/nutrition/templates/ingredient/overview.html
+++ b/wger/nutrition/templates/ingredient/overview.html
@@ -67,8 +67,8 @@ $(document).ready(function() {
</form>
</div>
-{% if perms.exercises %}
-<h3>{% trans "Options" %}</h3>
+{% if user.is_authenticated and not user.get_profile.is_temporary %}
+<h3>{% trans "Add ingredient" %}</h3>
<p>
<a href="{% url 'ingredient-add' %}">
<img src="{% static 'images/icons/new.svg' %}"
diff --git a/wger/nutrition/templates/ingredient/pending.html b/wger/nutrition/templates/ingredient/pending.html
new file mode 100644
index 000000000..d301ceb88
--- /dev/null
+++ b/wger/nutrition/templates/ingredient/pending.html
@@ -0,0 +1,38 @@
+{% extends "base.html" %}
+{% load url from future %}
+{% load i18n %}
+{% load staticfiles %}
+{% load manager_extras %}
+
+{% block title %}{% trans "Pending ingredient" %}{% endblock %}
+
+
+{% block content %}
+
+<table>
+<thead>
+<tr>
+ <th>{% trans "Submission date" %}</th>
+ <th>{% trans "Name" %}</th>
+ <th>{% trans "User" %}</th>
+</tr>
+</thead>
+<tbody>
+{% for ingredient in ingredient_list %}
+<tr>
+ <td>
+ {{ingredient.creation_date}}
+ </td>
+ <td><a href="{{ ingredient.get_absolute_url }}">{{ingredient.name}}</a></td>
+ <td>{{ingredient.user.username}}</td>
+</tr>
+{% empty %}
+<tr>
+ <td colspan="2">{% trans "No pending ingredients at the moment" %}</td>
+</tr>
+{% endfor %}
+</tbody>
+
+</table>
+<div style="padding-top:3em;"></div>
+{% endblock %}
\ No newline at end of file
diff --git a/wger/nutrition/templates/ingredient/view.html b/wger/nutrition/templates/ingredient/view.html
index fc956858b..5c6e20209 100644
--- a/wger/nutrition/templates/ingredient/view.html
+++ b/wger/nutrition/templates/ingredient/view.html
@@ -55,6 +55,57 @@ $(document).ready(function() {
{% block content %}
+
+{% if ingredient.status == INGREDIENT_STATUS_PENDING %}
+<div class="alert">
+<h3>{% trans "Ingredient is pending review" %}</h3>
+<p>{% blocktrans %}This user submitted ingredient is pending a decision to be
+included in the database. Till then, it will not be shown in the overview or
+the search.{% endblocktrans %}
+{% if perms.exercises %}
+{% trans "Please select one of the options below." %}
+{% endif %}
+</p>
+
+{% if perms.exercises %}
+<div class="ym-grid linearize-level-1">
+ <div class="ym-g50 ym-gl">
+ <div class="ym-gbox-left">
+ <div class="alert alert-success">
+ <a href="{% url 'ingredient-accept' ingredient.id %}">
+ <img src="{% static 'images/icons/status-on.svg' %}"
+ width="32"
+ height="32"
+ alt="{% trans 'Accept' %}">
+ {% trans "Accept" %}
+ </a>
+ </div>
+ </div>
+ </div>
+ <div class="ym-g50 ym-gl">
+ <div class="ym-gbox-left">
+ <div class="alert alert-error">
+ <a href="{% url 'ingredient-decline' ingredient.id %}">
+ <img src="{% static 'images/icons/status-off.svg' %}"
+ width="32"
+ height="32"
+ alt="{% trans 'Decline' %}">
+ {% trans "Decline" %}
+ </a>
+ </div>
+ </div>
+ </div>
+</div>
+{% endif %}
+
+</div>
+
+{% endif %} {# end ingredient is pending review #}
+
+
+
+
+
<div itemscope itemtype="http://schema.org/NutritionInformation">
<meta itemprop="name" content="{{ingredient.name}}" />
@@ -175,6 +226,17 @@ $(document).ready(function() {
{% block sidebar %}
+
+{% if ingredient.status == INGREDIENT_STATUS_ACCEPTED %}
+<div class="alert" style="margin-top:1em;">
+<h3>{% trans "User submitted ingredient" %}</h3>
+{% with username=ingredient.user.username %}
+<p>{% blocktrans %}This exercise was submitted by <strong>{{username}}</strong>.{% endblocktrans %}
+{% endwith %}
+</div>
+{% endif %}
+
+
{% if perms.exercises %}
<h3>{% trans "Options" %}</h3>
diff --git a/wger/nutrition/tests/__init__.py b/wger/nutrition/tests/__init__.py
index 2a40c9312..37fbcdc1d 100644
--- a/wger/nutrition/tests/__init__.py
+++ b/wger/nutrition/tests/__init__.py
@@ -3,6 +3,7 @@ from wger.nutrition.tests.copy_plan import *
from wger.nutrition.tests.pdf import *
from wger.nutrition.tests.nutritional_calculations import *
from wger.nutrition.tests.ingredient import *
+from wger.nutrition.tests.submitted_ingredient import *
from wger.nutrition.tests.ingredient_overview import *
from wger.nutrition.tests.meal import *
from wger.nutrition.tests.meal_item import *
diff --git a/wger/nutrition/tests/ingredient.py b/wger/nutrition/tests/ingredient.py
index b941287ce..f34051ce2 100644
--- a/wger/nutrition/tests/ingredient.py
+++ b/wger/nutrition/tests/ingredient.py
@@ -74,7 +74,8 @@ class AddIngredientTestCase(WorkoutManagerAddTestCase):
object_class = Ingredient
url = 'ingredient-add'
- pk = 7
+ pk = 8
+ user_fail = False
data = {'name': 'A new ingredient',
'sodium': 2,
'energy': 200,
@@ -87,11 +88,16 @@ class AddIngredientTestCase(WorkoutManagerAddTestCase):
def post_test_hook(self):
'''
- Test that the creation date is correctly set
+ Test that the creation date and the status are correctly set
'''
+ #print self.current_user
if self.current_user == 'admin':
- ingredient = Ingredient.objects.get(pk=7)
+ ingredient = Ingredient.objects.get(pk=self.pk)
self.assertEqual(ingredient.creation_date, datetime.date.today())
+ self.assertEqual(ingredient.status, Ingredient.INGREDIENT_STATUS_ADMIN)
+ elif self.current_user == 'test':
+ ingredient = Ingredient.objects.get(pk=self.pk)
+ self.assertEqual(ingredient.status, Ingredient.INGREDIENT_STATUS_PENDING)
class IngredientDetailTestCase(WorkoutManagerTestCase):
@@ -116,9 +122,11 @@ class IngredientDetailTestCase(WorkoutManagerTestCase):
if editor:
self.assertContains(response, 'Edit ingredient')
self.assertContains(response, 'Delete ingredient')
+ self.assertContains(response, 'pending review')
else:
self.assertNotContains(response, 'Edit ingredient')
self.assertNotContains(response, 'Delete ingredient')
+ self.assertNotContains(response, 'pending review')
# Non-existent ingredients throw a 404.
response = self.client.get(reverse('wger.nutrition.views.ingredient.view',
@@ -167,6 +175,11 @@ class IngredientSearchTestCase(WorkoutManagerTestCase):
'Ingredient, test, 2, organic, raw')
self.assertEqual(response.context['ingredients'][1].name, 'Test ingredient 1')
+ # Search for an ingredient pending review (0 hits, "Pending ingredient")
+ response = self.client.get(reverse('ingredient-search'), {'term': 'Pending'})
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(len(response.context['ingredients']), 0)
+
# AJAX-Search
kwargs = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
response = self.client.get(reverse('ingredient-search'), {'term': 'test'}, **kwargs)
@@ -176,6 +189,12 @@ class IngredientSearchTestCase(WorkoutManagerTestCase):
self.assertEqual(result[0]['value'], 'Ingredient, test, 2, organic, raw')
self.assertEqual(result[1]['value'], 'Test ingredient 1')
+ # AJAX Search for an ingredient pending review (0 hits, "Pending ingredient")
+ response = self.client.get(reverse('ingredient-search'), {'term': 'Pending'}, **kwargs)
+ self.assertEqual(response.status_code, 200)
+ result = json.loads(response.content)
+ self.assertEqual(len(result), 0)
+
def test_search_ingredient_anonymous(self):
'''
Test searching for an ingredient by an anonymous user
diff --git a/wger/nutrition/tests/ingredient_overview.py b/wger/nutrition/tests/ingredient_overview.py
index 36e34078e..94b895d5c 100644
--- a/wger/nutrition/tests/ingredient_overview.py
+++ b/wger/nutrition/tests/ingredient_overview.py
@@ -50,14 +50,12 @@ class OverviewPlanTestCase(WorkoutManagerTestCase):
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.context['ingredients_list']), PAGINATION_OBJECTS_PER_PAGE)
- response = self.client.get(reverse('ingredient-list'),
- {'page': 2})
+ response = self.client.get(reverse('ingredient-list'), {'page': 2})
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.context['ingredients_list']), PAGINATION_OBJECTS_PER_PAGE)
- rest_ingredients = Ingredient.objects.count() - 2 * PAGINATION_OBJECTS_PER_PAGE
- response = self.client.get(reverse('ingredient-list'),
- {'page': 3})
+ rest_ingredients = 6
+ response = self.client.get(reverse('ingredient-list'), {'page': 3})
self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.context['ingredients_list']), rest_ingredients)
@@ -72,3 +70,53 @@ class OverviewPlanTestCase(WorkoutManagerTestCase):
response = self.client.get(reverse('ingredient-list'), {'page': 'foobar'})
self.assertEqual(response.status_code, 404)
+
+ def ingredient_overview(self, logged_in=True, demo=False, admin=False):
+ '''
+ Helper function to test the ingredient overview page
+ '''
+
+ # Page exists
+ response = self.client.get(reverse('ingredient-list'))
+ self.assertEqual(response.status_code, 200)
+
+ # No ingredients pending review
+ self.assertNotContains(response, 'Pending ingredient')
+
+ # Only authorized users see the edit links
+ if logged_in and not demo:
+ self.assertContains(response, 'Add ingredient')
+
+ if logged_in and demo:
+ self.assertNotContains(response, 'Add ingredient')
+
+ def test_ingredient_index_editor(self):
+ '''
+ Tests the ingredient overview page as a logged in user with editor rights
+ '''
+
+ self.user_login('admin')
+ self.ingredient_overview(admin=True)
+
+ def test_ingredient_index_non_editor(self):
+ '''
+ Tests the overview overview page as a logged in user without editor rights
+ '''
+
+ self.user_login('test')
+ self.ingredient_overview()
+
+ def test_ingredient_index_demo_user(self):
+ '''
+ Tests the overview overview page as a logged in demo user
+ '''
+
+ self.user_login('demo')
+ self.ingredient_overview(demo=True)
+
+ def test_ingredient_index_logged_out(self):
+ '''
+ Tests the overview overview page as an anonymous (logged out) user
+ '''
+
+ self.ingredient_overview(logged_in=False)
diff --git a/wger/nutrition/tests/submitted_ingredient.py b/wger/nutrition/tests/submitted_ingredient.py
new file mode 100644
index 000000000..f4c762338
--- /dev/null
+++ b/wger/nutrition/tests/submitted_ingredient.py
@@ -0,0 +1,205 @@
+# This file is part of Workout Manager.
+#
+# 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.
+#
+# 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 General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public License
+
+import json
+
+from django.core import mail
+from django.core.urlresolvers import reverse
+
+from wger.nutrition.models import Ingredient
+
+from wger.manager.tests.testcase import WorkoutManagerTestCase
+from wger.manager.tests.testcase import WorkoutManagerDeleteTestCase
+
+
+class IngredientsPendingTestCase(WorkoutManagerTestCase):
+ '''
+ Tests the pending ingredients overview page
+ '''
+
+ def pending_overview(self, fail=False):
+ '''
+ Helper function
+ '''
+ response = self.client.get(reverse('ingredient-pending'))
+ if not fail:
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(len(response.context['ingredient_list']), 1)
+ else:
+ self.assertEqual(response.status_code, 302)
+
+ def test_pending_overview_admin(self):
+ '''
+ Tests the pending exercises overview page as an admin user
+ '''
+
+ self.user_login('admin')
+ self.pending_overview()
+
+ def test_pending_overview_user(self):
+ '''
+ Tests the pending exercises overview page as a regular user
+ '''
+
+ self.user_login('test')
+ self.pending_overview(fail=True)
+
+ def test_pending_overview_logged_out(self):
+ '''
+ Tests the pending exercises overview page as a logged out user
+ '''
+
+ self.pending_overview(fail=True)
+
+
+class IngredientsPendingDetailTestCase(WorkoutManagerTestCase):
+ '''
+ Tests the detail page of a pending ingredient
+ '''
+
+ def pending_view(self, fail=False):
+ '''
+ Helper function
+ '''
+ response = self.client.get(reverse('wger.nutrition.views.ingredient.view',
+ kwargs={'id': 7}))
+ self.assertContains(response, 'pending review')
+
+ if not fail:
+ self.assertEqual(response.status_code, 200)
+ self.assertContains(response, 'Please select one of the options below')
+ self.assertContains(response, 'Accept')
+ self.assertContains(response, 'Decline')
+ else:
+ self.assertNotContains(response, 'Please select one of the options below')
+ self.assertNotContains(response, 'Accept')
+ self.assertNotContains(response, 'Decline')
+
+ def test_pending_view_admin(self):
+ '''
+ Tests the detail page of a pending exercise as an admin user
+ '''
+
+ self.user_login('admin')
+ self.pending_view()
+
+ def test_pending_view_user(self):
+ '''
+ Tests the detail page of a pending exercise as a regular user
+ '''
+
+ self.user_login('test')
+ self.pending_view(fail=True)
+
+ def test_pending_view_logged_out(self):
+ '''
+ Tests the detail page of a pending exercise as a logged out user
+ '''
+
+ self.pending_view(fail=True)
+
+
+class IngredientAcceptTestCase(WorkoutManagerTestCase):
+ '''
+ Tests accepting a user submitted ingredient
+ '''
+
+ def accept(self, fail=False):
+ '''
+ Helper function
+ '''
+ ingredient = Ingredient.objects.get(pk=7)
+ self.assertEqual(ingredient.status, Ingredient.INGREDIENT_STATUS_PENDING)
+ response = self.client.get(reverse('ingredient-accept', kwargs={'pk': 7}))
+ ingredient = Ingredient.objects.get(pk=7)
+ self.assertEqual(response.status_code, 302)
+
+ if not fail:
+ self.assertEqual(ingredient.status, Ingredient.INGREDIENT_STATUS_ACCEPTED)
+ response = self.client.get(response['Location'])
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(len(mail.outbox), 1)
+ else:
+ self.assertEqual(ingredient.status, Ingredient.INGREDIENT_STATUS_PENDING)
+ self.assertEqual(len(mail.outbox), 0)
+
+ def test_accept_admin(self):
+ '''
+ Tests accepting a user submitted ingredient as an admin user
+ '''
+
+ self.user_login('admin')
+ self.accept(fail=False)
+
+ def test_accept_user(self):
+ '''
+ Tests accepting a user submitted ingredient as a regular user
+ '''
+
+ self.user_login('test')
+ self.accept(fail=True)
+
+ def test_accept_logged_out(self):
+ '''
+ Tests accepting a user submitted ingredient as a logged out user
+ '''
+
+ self.accept(fail=True)
+
+
+class IngredientRejectTestCase(WorkoutManagerTestCase):
+ '''
+ Tests rejecting a user submitted ingredient
+ '''
+
+ def reject(self, fail=False):
+ '''
+ Helper function
+ '''
+ ingredient = Ingredient.objects.get(pk=7)
+ self.assertEqual(ingredient.status, Ingredient.INGREDIENT_STATUS_PENDING)
+ response = self.client.get(reverse('ingredient-decline', kwargs={'pk': 7}))
+ ingredient = Ingredient.objects.get(pk=7)
+ self.assertEqual(response.status_code, 302)
+
+ if not fail:
+ self.assertEqual(ingredient.status, Ingredient.INGREDIENT_STATUS_DECLINED)
+ response = self.client.get(response['Location'])
+ self.assertEqual(response.status_code, 200)
+
+ else:
+ self.assertEqual(ingredient.status, Ingredient.INGREDIENT_STATUS_PENDING)
+
+ def test_reject_admin(self):
+ '''
+ Tests rejecting a user submitted ingredient as an admin user
+ '''
+
+ self.user_login('admin')
+ self.reject()
+
+ def test_reject_user(self):
+ '''
+ Tests rejecting a user submitted ingredient as a regular user
+ '''
+
+ self.user_login('test')
+ self.reject(fail=True)
+
+ def test_reject_logged_out(self):
+ '''
+ Tests rejecting a user submitted ingredient as a logged out user
+ '''
+
+ self.reject(fail=True)
diff --git a/wger/nutrition/urls.py b/wger/nutrition/urls.py
index 783724aa3..8df971416 100644
--- a/wger/nutrition/urls.py
+++ b/wger/nutrition/urls.py
@@ -52,11 +52,20 @@ urlpatterns = patterns('wger.nutrition.views',
permission_required('nutrition.change_ingredient')(ingredient.IngredientEditView.as_view()),
name='ingredient-edit'),
url(r'^ingredient/add/$',
- permission_required('nutrition.add_ingredient')(ingredient.IngredientCreateView.as_view()),
+ login_required(ingredient.IngredientCreateView.as_view()),
name='ingredient-add'),
url(r'^ingredient/overview/$',
ingredient.IngredientListView.as_view(),
name='ingredient-list'),
+ url(r'^pending/$',
+ permission_required('nutrition.change_ingredient')(ingredient.PendingIngredientListView.as_view()),
+ name='ingredient-pending'),
+ url(r'^(?P<pk>\d+)/accept/$',
+ 'ingredient.accept',
+ name='ingredient-accept'),
+ url(r'^(?P<pk>\d+)/decline/$',
+ 'ingredient.decline',
+ name='ingredient-decline'),
url(r'^ingredient/(?P<id>\d+)/view/$', 'ingredient.view'),
url(r'^ingredient/(?P<id>\d+)/view/(?P<slug>[-\w]+)/$', 'ingredient.view'),
url(r'^ingredient/search/$',
diff --git a/wger/nutrition/views/ingredient.py b/wger/nutrition/views/ingredient.py
index f0b01825d..9caf650a6 100644
--- a/wger/nutrition/views/ingredient.py
+++ b/wger/nutrition/views/ingredient.py
@@ -24,10 +24,13 @@ from django.shortcuts import get_object_or_404
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import HttpResponseForbidden
+from django.core import mail
from django.core.context_processors import csrf
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
+from django.contrib.auth.decorators import permission_required
from django.contrib.auth.decorators import login_required
+from django.contrib import messages
from django.utils.translation import ugettext as _
from django.utils.translation import ugettext_lazy
@@ -57,6 +60,7 @@ from wger.utils import helpers
from wger.utils.generic_views import YamlFormMixin
from wger.utils.generic_views import YamlDeleteMixin
from wger.utils.constants import PAGINATION_OBJECTS_PER_PAGE
+from wger.utils.constants import EMAIL_FROM
from wger.utils.language import load_language
from wger.utils.language import load_ingredient_languages
@@ -84,7 +88,9 @@ class IngredientListView(ListView):
native language, see load_ingredient_languages)
'''
languages = load_ingredient_languages(self.request)
- return Ingredient.objects.filter(language__in=languages).only('id', 'name')
+ return (Ingredient.objects.filter(language__in=languages)
+ .filter(status__in=Ingredient.INGREDIENT_STATUS_OK)
+ .only('id', 'name'))
def view(request, id, slug=None):
@@ -92,6 +98,8 @@ def view(request, id, slug=None):
ingredient = get_object_or_404(Ingredient, pk=id)
template_data['ingredient'] = ingredient
+ template_data['INGREDIENT_STATUS_PENDING'] = Ingredient.INGREDIENT_STATUS_PENDING
+ template_data['INGREDIENT_STATUS_ACCEPTED'] = Ingredient.INGREDIENT_STATUS_ACCEPTED
template_data['form'] = UnitChooserForm(data={'ingredient_id': ingredient.id,
'amount': 100,
'unit': None})
@@ -156,11 +164,92 @@ class IngredientCreateView(YamlFormMixin, CreateView):
form_class = IngredientForm
title = ugettext_lazy('Add a new ingredient')
form_action = reverse_lazy('ingredient-add')
+ sidebar = 'ingredient/form.html'
def form_valid(self, form):
+
+ # set the submitter, if admin, set approrpiate status
+ form.instance.user = self.request.user
+ if self.request.user.has_perm('nutrition.add_ingredient'):
+ form.instance.status = Ingredient.INGREDIENT_STATUS_ADMIN
+ else:
+ subject = _('New user submitted ingredient')
+ message = _('''The user {0} submitted a new ingredient "{1}".'''.format(
+ self.request.user.username, form.instance.name))
+ mail.mail_admins(_('New user submitted ingredient'),
+ message,
+ fail_silently=True)
+
form.instance.language = load_language()
return super(IngredientCreateView, self).form_valid(form)
+ def dispatch(self, request, *args, **kwargs):
+ '''
+ Demo users can't submit ingredients
+ '''
+ if request.user.get_profile().is_temporary:
+ return HttpResponseForbidden()
+ return super(IngredientCreateView, self).dispatch(request, *args, **kwargs)
+
+
+class PendingIngredientListView(ListView):
+ '''
+ List all ingredients pending review
+ '''
+
+ model = Ingredient
+ template_name = 'ingredient/pending.html'
+ context_object_name = 'ingredient_list'
+
+ def get_queryset(self):
+ '''
+ Only show ingredients pending review
+ '''
+ return Ingredient.objects.filter(status=Ingredient.INGREDIENT_STATUS_PENDING)
+
+
+@permission_required('nutrition.add_ingredient')
+def accept(request, pk):
+ '''
+ Accepts a pending user submitted ingredient
+ '''
+ ingredient = get_object_or_404(Ingredient, pk=pk)
+ ingredient.status = Ingredient.INGREDIENT_STATUS_ACCEPTED
+ ingredient.save()
+ messages.success(request, _('Ingredient was sucessfully added to the general database'))
+
+ # Notify the user if possible
+ if ingredient.user.email:
+ url = request.build_absolute_uri(ingredient.get_absolute_url())
+ subject = _('Ingredient was sucessfully added to the general database')
+ message = _("Your ingredient '{0}' was successfully added to the general database.\n"
+ "\n"
+ "It is now available on the ingredient and muscle overview and can be\n"
+ "added to nutritional plans. You can access it on this address:\n"
+ "{1}\n"
+ "\n"
+ "Thank you for contributing and making this site better!\n"
+ " the wger.de team".format(ingredient.name, url))
+ mail.send_mail(subject,
+ message,
+ EMAIL_FROM,
+ [ingredient.user.email],
+ fail_silently=True)
+
+ return HttpResponseRedirect(ingredient.get_absolute_url())
+
+
+@permission_required('nutrition.add_ingredient')
+def decline(request, pk):
+ '''
+ Declines and deletes a pending user submitted ingredient
+ '''
+ ingredient = get_object_or_404(Ingredient, pk=pk)
+ ingredient.status = Ingredient.INGREDIENT_STATUS_DECLINED
+ ingredient.save()
+ messages.success(request, _('Ingredient was sucessfully marked as rejected'))
+ return HttpResponseRedirect(ingredient.get_absolute_url())
+
def search(request):
'''
@@ -174,7 +263,9 @@ def search(request):
# Perform the search
q = request.GET.get('term', '')
- ingredients = Ingredient.objects.filter(name__icontains=q, language__in=languages)
+ ingredients = Ingredient.objects.filter(name__icontains=q,
+ language__in=languages,
+ status__in=Ingredient.INGREDIENT_STATUS_OK)
# AJAX-request, this comes from the autocompleter. Create a list and send it back as JSON
if request.is_ajax():
diff --git a/wger/software/templates/changelog.html b/wger/software/templates/changelog.html
index a1f5537e8..406bb6bf0 100644
--- a/wger/software/templates/changelog.html
+++ b/wger/software/templates/changelog.html
@@ -11,7 +11,7 @@
<h4>2013-XX-XX</h4>
<ul>
- <li>Regular users can suggest exercises to be included in the general list</li>
+ <li>Regular users can submit exercises and ingredients to be included in the general list</li>
<li>Add more 'human' units to ingredients like '1 cup' or '1 slice'</li>
<li>Add nutritional values calculator on the ingredient detail page</li>
<li>Several bugfixes</li>