diff --git a/README.md b/README.md index 62dc8dc5..3cb1c6b9 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,30 @@ # gm-backend +## Build + +1. ``git clone ssh://git@gl.id-east.ru:222/gm/gm-backend.git`` +1. ``cd ./gm-backend`` +1. ``git checkout develop`` +1. ``docker-compose build`` +1. First start database: ``docker-compose up db`` +1. ``docker-compose up -d`` +### Migrate data + +1.Connect to container with django ``docker exec -it gm-backend_gm_app_1 bash`` + +#### In docker container(django) + +1. Migrate ``python manage.py migrate`` +1. Create super-user ``python manage.py createsuperuser`` + +Backend is available at localhost:8000 or 0.0.0.0:8000 + +URL for admin http://0.0.0.0:8000/admin +URL for swagger http://0.0.0.0:8000/docs/ +URL for redocs http://0.0.0.0:8000/redocs/ + +## Start and stop backend containers + +Demonize start ``docker-compose up -d`` +Stop ``docker-compose down`` +Stop and remove volumes ``docker-compose down -v`` \ No newline at end of file diff --git a/apps/account/admin.py b/apps/account/admin.py index 8429952f..651e5a5a 100644 --- a/apps/account/admin.py +++ b/apps/account/admin.py @@ -2,10 +2,19 @@ from django.contrib import admin from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.utils.translation import ugettext_lazy as _ - from account import models +@admin.register(models.Role) +class RoleAdmin(admin.ModelAdmin): + list_display = ['role', 'country'] + + +@admin.register(models.UserRole) +class UserRoleAdmin(admin.ModelAdmin): + list_display = ['user', 'role', 'establishment'] + + @admin.register(models.User) class UserAdmin(BaseUserAdmin): """User model admin settings.""" diff --git a/apps/account/migrations/0009_auto_20191011_1123.py b/apps/account/migrations/0009_auto_20191011_1123.py new file mode 100644 index 00000000..f1ec87f9 --- /dev/null +++ b/apps/account/migrations/0009_auto_20191011_1123.py @@ -0,0 +1,48 @@ +# Generated by Django 2.2.4 on 2019-10-11 11:23 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone + + +class Migration(migrations.Migration): + + dependencies = [ + ('location', '0011_country_languages'), + ('account', '0008_auto_20190912_1325'), + ] + + operations = [ + migrations.CreateModel( + name='Role', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created', models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name='Date created')), + ('modified', models.DateTimeField(auto_now=True, verbose_name='Date updated')), + ('role', models.PositiveIntegerField(choices=[(1, 'Standard user'), (2, 'Comments moderator')], verbose_name='Role')), + ('country', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='location.Country', verbose_name='Country')), + ], + options={ + 'abstract': False, + }, + ), + migrations.CreateModel( + name='UserRole', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created', models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name='Date created')), + ('modified', models.DateTimeField(auto_now=True, verbose_name='Date updated')), + ('role', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='account.Role', verbose_name='Role')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='User')), + ], + options={ + 'abstract': False, + }, + ), + migrations.AddField( + model_name='user', + name='roles', + field=models.ManyToManyField(through='account.UserRole', to='account.Role', verbose_name='Roles'), + ), + ] diff --git a/apps/account/migrations/0009_user_unconfirmed_email.py b/apps/account/migrations/0009_user_unconfirmed_email.py new file mode 100644 index 00000000..6aaf3a6a --- /dev/null +++ b/apps/account/migrations/0009_user_unconfirmed_email.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-10-10 14:40 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('account', '0008_auto_20190912_1325'), + ] + + operations = [ + migrations.AddField( + model_name='user', + name='unconfirmed_email', + field=models.EmailField(blank=True, default=None, max_length=254, null=True, verbose_name='unconfirmed email'), + ), + ] diff --git a/apps/account/migrations/0010_user_password_confirmed.py b/apps/account/migrations/0010_user_password_confirmed.py new file mode 100644 index 00000000..5f369f3c --- /dev/null +++ b/apps/account/migrations/0010_user_password_confirmed.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-10-10 17:21 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('account', '0009_user_unconfirmed_email'), + ] + + operations = [ + migrations.AddField( + model_name='user', + name='password_confirmed', + field=models.BooleanField(default=True, verbose_name='is new password confirmed'), + ), + ] diff --git a/apps/account/migrations/0011_merge_20191014_0839.py b/apps/account/migrations/0011_merge_20191014_0839.py new file mode 100644 index 00000000..653f39b7 --- /dev/null +++ b/apps/account/migrations/0011_merge_20191014_0839.py @@ -0,0 +1,14 @@ +# Generated by Django 2.2.4 on 2019-10-14 08:39 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('account', '0009_auto_20191011_1123'), + ('account', '0010_user_password_confirmed'), + ] + + operations = [ + ] diff --git a/apps/account/migrations/0011_merge_20191014_1258.py b/apps/account/migrations/0011_merge_20191014_1258.py new file mode 100644 index 00000000..cee0a824 --- /dev/null +++ b/apps/account/migrations/0011_merge_20191014_1258.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-10-14 12:58 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('account', '0009_auto_20191011_1123'), + ('account', '0010_user_password_confirmed'), + ] + + operations = [ + migrations.RemoveField( + model_name='user', + name='password_confirmed', + ), + ] diff --git a/apps/account/migrations/0012_merge_20191015_0708.py b/apps/account/migrations/0012_merge_20191015_0708.py new file mode 100644 index 00000000..91dba02e --- /dev/null +++ b/apps/account/migrations/0012_merge_20191015_0708.py @@ -0,0 +1,14 @@ +# Generated by Django 2.2.4 on 2019-10-15 07:08 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('account', '0011_merge_20191014_0839'), + ('account', '0011_merge_20191014_1258'), + ] + + operations = [ + ] diff --git a/apps/account/migrations/0013_auto_20191016_0810.py b/apps/account/migrations/0013_auto_20191016_0810.py new file mode 100644 index 00000000..72955cee --- /dev/null +++ b/apps/account/migrations/0013_auto_20191016_0810.py @@ -0,0 +1,30 @@ +# Generated by Django 2.2.4 on 2019-10-16 08:10 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0033_auto_20191003_0943_squashed_0034_auto_20191003_1036'), + ('account', '0012_merge_20191015_0708'), + ] + + operations = [ + migrations.AddField( + model_name='userrole', + name='establishment', + field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='establishment.Establishment', verbose_name='Establishment'), + ), + migrations.AlterField( + model_name='role', + name='country', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='location.Country', verbose_name='Country'), + ), + migrations.AlterField( + model_name='role', + name='role', + field=models.PositiveIntegerField(choices=[(1, 'Standard user'), (2, 'Comments moderator'), (3, 'Country admin'), (4, 'Content page manager'), (5, 'Establishment manager')], verbose_name='Role'), + ), + ] diff --git a/apps/account/models.py b/apps/account/models.py index 81ade4fc..a9f739bd 100644 --- a/apps/account/models.py +++ b/apps/account/models.py @@ -13,11 +13,42 @@ from django.utils.translation import ugettext_lazy as _ from rest_framework.authtoken.models import Token from authorization.models import Application +from establishment.models import Establishment +from location.models import Country from utils.models import GMTokenGenerator from utils.models import ImageMixin, ProjectBaseMixin, PlatformMixin from utils.tokens import GMRefreshToken +class Role(ProjectBaseMixin): + """Base Role model.""" + STANDARD_USER = 1 + COMMENTS_MODERATOR = 2 + COUNTRY_ADMIN = 3 + CONTENT_PAGE_MANAGER = 4 + ESTABLISHMENT_MANAGER = 5 + REVIEWER_MANGER = 6 + RESTAURANT_REVIEWER = 7 + + ROLE_CHOICES = ( + (STANDARD_USER, 'Standard user'), + (COMMENTS_MODERATOR, 'Comments moderator'), + (COUNTRY_ADMIN, 'Country admin'), + (CONTENT_PAGE_MANAGER, 'Content page manager'), + (ESTABLISHMENT_MANAGER, 'Establishment manager'), + (REVIEWER_MANGER, 'Reviewer manager'), + (RESTAURANT_REVIEWER, 'Restaurant reviewer') + ) + role = models.PositiveIntegerField(verbose_name=_('Role'), choices=ROLE_CHOICES, + null=False, blank=False) + country = models.ForeignKey(Country, verbose_name=_('Country'), + null=True, blank=True, on_delete=models.SET_NULL) + # is_list = models.BooleanField(verbose_name=_('list'), default=True, null=False) + # is_create = models.BooleanField(verbose_name=_('create'), default=False, null=False) + # is_update = models.BooleanField(verbose_name=_('update'), default=False, null=False) + # is_delete = models.BooleanField(verbose_name=_('delete'), default=False, null=False) + + class UserManager(BaseUserManager): """Extended manager for User model.""" @@ -60,6 +91,7 @@ class User(AbstractUser): blank=True, null=True, default=None) email = models.EmailField(_('email address'), blank=True, null=True, default=None) + unconfirmed_email = models.EmailField(_('unconfirmed email'), blank=True, null=True, default=None) email_confirmed = models.BooleanField(_('email status'), default=False) newsletter = models.NullBooleanField(default=True) @@ -67,6 +99,7 @@ class User(AbstractUser): USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] + roles = models.ManyToManyField(Role, verbose_name=_('Roles'), through='UserRole') objects = UserManager.from_queryset(UserQuerySet)() class Meta: @@ -112,6 +145,9 @@ class User(AbstractUser): def confirm_email(self): """Method to confirm user email address""" + if self.unconfirmed_email is not None: + self.email = self.unconfirmed_email + self.unconfirmed_email = None self.email_confirmed = True self.save() @@ -195,3 +231,11 @@ class User(AbstractUser): return render_to_string( template_name=settings.CHANGE_EMAIL_TEMPLATE, context=context) + + +class UserRole(ProjectBaseMixin): + """UserRole model.""" + user = models.ForeignKey(User, verbose_name=_('User'), on_delete=models.CASCADE) + role = models.ForeignKey(Role, verbose_name=_('Role'), on_delete=models.SET_NULL, null=True) + establishment = models.ForeignKey(Establishment, verbose_name=_('Establishment'), + on_delete=models.SET_NULL, null=True, blank=True) \ No newline at end of file diff --git a/apps/account/serializers/back.py b/apps/account/serializers/back.py new file mode 100644 index 00000000..c1a1c6d4 --- /dev/null +++ b/apps/account/serializers/back.py @@ -0,0 +1,21 @@ +"""Back account serializers""" +from rest_framework import serializers +from account import models + + +class RoleSerializer(serializers.ModelSerializer): + class Meta: + model = models.Role + fields = [ + 'role', + 'country' + ] + + +class UserRoleSerializer(serializers.ModelSerializer): + class Meta: + model = models.UserRole + fields = [ + 'user', + 'role' + ] \ No newline at end of file diff --git a/apps/account/serializers/common.py b/apps/account/serializers/common.py index d5f89526..ad232eae 100644 --- a/apps/account/serializers/common.py +++ b/apps/account/serializers/common.py @@ -1,5 +1,6 @@ """Common account serializers""" from django.conf import settings +from django.utils.translation import gettext_lazy as _ from django.contrib.auth import password_validation as password_validators from fcm_django.models import FCMDevice from rest_framework import exceptions @@ -60,9 +61,12 @@ class UserSerializer(serializers.ModelSerializer): def update(self, instance, validated_data): """Override update method""" + old_email = instance.email instance = super().update(instance, validated_data) if 'email' in validated_data: instance.email_confirmed = False + instance.email = old_email + instance.unconfirmed_email = validated_data['email'] instance.save() # Send verification link on user email for change email address if settings.USE_CELERY: @@ -76,27 +80,52 @@ class UserSerializer(serializers.ModelSerializer): return instance +class UserBaseSerializer(serializers.ModelSerializer): + """Serializer is used to display brief information about the user.""" + + fullname = serializers.CharField(source='get_full_name', read_only=True) + + class Meta: + """Meta class.""" + + model = models.User + fields = ( + 'fullname', + 'cropped_image_url', + 'image_url', + ) + read_only_fields = fields + + class ChangePasswordSerializer(serializers.ModelSerializer): """Serializer for model User.""" password = serializers.CharField(write_only=True) + old_password = serializers.CharField(write_only=True) class Meta: """Meta class""" model = models.User - fields = ('password', ) + fields = ( + 'password', + 'old_password', + ) def validate(self, attrs): """Override validate method""" password = attrs.get('password') + old_password = attrs.get('old_password') try: + # Check old password + if not self.instance.check_password(raw_password=old_password): + raise serializers.ValidationError(_('Old password mismatch.')) # Compare new password with the old ones if self.instance.check_password(raw_password=password): - raise utils_exceptions.PasswordsAreEqual() + raise serializers.ValidationError(_('Password is already in use')) # Validate password password_validators.validate_password(password=password) except serializers.ValidationError as e: - raise serializers.ValidationError(str(e)) + raise serializers.ValidationError({'detail': e.detail}) else: return attrs @@ -146,38 +175,6 @@ class ChangeEmailSerializer(serializers.ModelSerializer): return instance -class ConfirmEmailSerializer(serializers.ModelSerializer): - """Confirm user email serializer""" - x = serializers.CharField(default=None) - - class Meta: - """Meta class""" - model = models.User - fields = ( - 'email', - ) - - def validate(self, attrs): - """Override validate method""" - email_confirmed = self.instance.email_confirmed - if email_confirmed: - raise utils_exceptions.EmailConfirmedError() - - return attrs - - def update(self, instance, validated_data): - """ - Override update method - """ - - # Send verification link on user email for change email address - if settings.USE_CELERY: - tasks.confirm_new_email_address.delay(instance.id) - else: - tasks.confirm_new_email_address(instance.id) - return instance - - # Firebase Cloud Messaging serializers class FCMDeviceSerializer(serializers.ModelSerializer): """FCM Device model serializer""" diff --git a/apps/news/serializers/__init__.py b/apps/account/tests/__init__.py similarity index 100% rename from apps/news/serializers/__init__.py rename to apps/account/tests/__init__.py diff --git a/apps/account/tests/tests_back.py b/apps/account/tests/tests_back.py new file mode 100644 index 00000000..8adc6b35 --- /dev/null +++ b/apps/account/tests/tests_back.py @@ -0,0 +1,81 @@ +from rest_framework.test import APITestCase +from rest_framework import status +from authorization.tests.tests_authorization import get_tokens_for_user +from django.urls import reverse +from http.cookies import SimpleCookie +from location.models import Country +from account.models import Role, User, UserRole + +class RoleTests(APITestCase): + def setUp(self): + self.data = get_tokens_for_user() + self.client.cookies = SimpleCookie( + {'access_token': self.data['tokens'].get('access_token'), + 'refresh_token': self.data['tokens'].get('access_token')}) + + def test_role_get(self): + url = reverse('back:account:role-list-create') + response = self.client.get(url) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_role_post(self): + url = reverse('back:account:role-list-create') + country = Country.objects.create( + name='{"ru-RU":"Russia"}', + code='23', + low_price=15, + high_price=150000 + ) + country.save() + + data = { + "role": 2, + "country": country.pk + } + response = self.client.post(url, data=data, format='json') + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + +class UserRoleTests(APITestCase): + def setUp(self): + self.data = get_tokens_for_user() + self.client.cookies = SimpleCookie( + {'access_token': self.data['tokens'].get('access_token'), + 'refresh_token': self.data['tokens'].get('access_token')}) + + self.country_ru = Country.objects.create( + name='{"ru-RU":"Russia"}', + code='23', + low_price=15, + high_price=150000 + ) + self.country_ru.save() + + self.country_en = Country.objects.create( + name='{"en-GB":"England"}', + code='25', + low_price=15, + high_price=150000 + ) + self.country_en.save() + + self.role = Role.objects.create( + role=2, + country=self.country_ru + ) + self.role.save() + + self.user_test = User.objects.create_user(username='test', + email='testemail@mail.com', + password='passwordtest') + + def test_user_role_post(self): + url = reverse('back:account:user-role-list-create') + + data = { + "user": self.user_test.id, + "role": self.role.id + } + + response = self.client.post(url, data=data, format='json') + self.assertEqual(response.status_code, status.HTTP_201_CREATED) diff --git a/apps/account/tests/tests_common.py b/apps/account/tests/tests_common.py new file mode 100644 index 00000000..dea807c4 --- /dev/null +++ b/apps/account/tests/tests_common.py @@ -0,0 +1,78 @@ +from rest_framework.test import APITestCase +from rest_framework import status +from authorization.tests.tests_authorization import get_tokens_for_user +from http.cookies import SimpleCookie +from account.models import User +from django.urls import reverse + + +class AccountUserTests(APITestCase): + def setUp(self): + self.data = get_tokens_for_user() + + def test_user_url(self): + url = reverse('web:account:user-retrieve-update') + response = self.client.get(url) + self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) + + self.client.cookies = SimpleCookie( + {'access_token': self.data['tokens'].get('access_token'), + 'refresh_token': self.data['tokens'].get('access_token')}) + + response = self.client.get(url) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + data = { + "username": self.data["username"], + "first_name": "Test first name", + "last_name": "Test last name", + "cropped_image_url": "http://localhost/image/cropped.png", + "image_url": "http://localhost/image/avatar.png", + "email": "sedragurdatest@desoz.com", + "newsletter": self.data["newsletter"] + } + response = self.client.patch(url, data=data, format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + data["email"] = "sedragurdatest2@desoz.com" + + response = self.client.put(url, data=data, format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + +class AccountChangePasswordTests(APITestCase): + def setUp(self): + self.data = get_tokens_for_user() + + def test_change_password(self): + data = { + "old_password": self.data["password"], + "password": "new password" + } + url = reverse('web:account:change-password') + + response = self.client.patch(url, data=data, format='json') + self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) + + self.client.cookies = SimpleCookie( + {'access_token': self.data['tokens'].get('access_token'), + 'refresh_token': self.data['tokens'].get('access_token')}) + + response = self.client.patch(url, data=data, format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + +class AccountChangePasswordTests(APITestCase): + def setUp(self): + self.data = get_tokens_for_user() + + def test_confirm_email(self): + user = User.objects.get(email=self.data["email"]) + token = user.confirm_email_token + uidb64 = user.get_user_uidb64 + url = reverse('web:account:confirm-email', kwargs={ + 'uidb64': uidb64, + 'token': token + }) + response = self.client.get(url) + self.assertEqual(response.status_code, status.HTTP_200_OK) diff --git a/apps/account/tests/tests_web.py b/apps/account/tests/tests_web.py new file mode 100644 index 00000000..a3d93f4e --- /dev/null +++ b/apps/account/tests/tests_web.py @@ -0,0 +1,49 @@ +from rest_framework.test import APITestCase +from rest_framework import status +from authorization.tests.tests_authorization import get_tokens_for_user +from django.urls import reverse +from account.models import User + + +class AccountResetPassWordTests(APITestCase): + + def setUp(self): + self.data = get_tokens_for_user() + + def test_reset_password(self): + url = reverse('web:account:password-reset') + data = { + "username_or_email": self.data["email"] + } + response = self.client.post(url, data=data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + data = { + "username_or_email": self.data["username"] + } + response = self.client.post(url, data=data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + +class AccountResetPassWordTests(APITestCase): + + def setUp(self): + self.data = get_tokens_for_user() + + def test_reset_password_confirm(self): + data ={ + "password": "newpasswordnewpassword" + } + user = User.objects.get(email=self.data["email"]) + token = user.reset_password_token + uidb64 = user.get_user_uidb64 + + url = reverse('web:account:password-reset-confirm', kwargs={ + 'uidb64': uidb64, + 'token': token + }) + response = self.client.patch(url, data=data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + + diff --git a/apps/account/urls/back.py b/apps/account/urls/back.py new file mode 100644 index 00000000..ee2e4148 --- /dev/null +++ b/apps/account/urls/back.py @@ -0,0 +1,12 @@ +"""Back account URLs""" +from django.urls import path + +from account.views import back as views + +app_name = 'account' + +urlpatterns = [ + path('role/', views.RoleLstView.as_view(), name='role-list-create'), + path('user-role/', views.UserRoleLstView.as_view(), name='user-role-list-create'), + +] diff --git a/apps/account/urls/common.py b/apps/account/urls/common.py index 34583010..4ea2af66 100644 --- a/apps/account/urls/common.py +++ b/apps/account/urls/common.py @@ -8,5 +8,6 @@ app_name = 'account' urlpatterns = [ path('user/', views.UserRetrieveUpdateView.as_view(), name='user-retrieve-update'), path('change-password/', views.ChangePasswordView.as_view(), name='change-password'), + path('email/confirm/', views.SendConfirmationEmailView.as_view(), name='send-confirm-email'), path('email/confirm///', views.ConfirmEmailView.as_view(), name='confirm-email'), ] diff --git a/apps/account/views/back.py b/apps/account/views/back.py new file mode 100644 index 00000000..8799f915 --- /dev/null +++ b/apps/account/views/back.py @@ -0,0 +1,13 @@ +from rest_framework import generics +from account.serializers import back as serializers +from account import models + + +class RoleLstView(generics.ListCreateAPIView): + serializer_class = serializers.RoleSerializer + queryset = models.Role.objects.all() + + +class UserRoleLstView(generics.ListCreateAPIView): + serializer_class = serializers.UserRoleSerializer + queryset = models.Role.objects.all() \ No newline at end of file diff --git a/apps/account/views/common.py b/apps/account/views/common.py index ab62343f..d29ce2bb 100644 --- a/apps/account/views/common.py +++ b/apps/account/views/common.py @@ -1,4 +1,5 @@ """Common account views""" +from django.conf import settings from django.utils.encoding import force_text from django.utils.http import urlsafe_base64_decode from fcm_django.models import FCMDevice @@ -9,6 +10,7 @@ from rest_framework.response import Response from account import models from account.serializers import common as serializers +from authorization.tasks import send_confirm_email from utils import exceptions as utils_exceptions from utils.models import GMTokenGenerator from utils.views import JWTGenericViewMixin @@ -38,19 +40,26 @@ class ChangePasswordView(generics.GenericAPIView): return Response(status=status.HTTP_200_OK) -class SendConfirmationEmailView(JWTGenericViewMixin): +class SendConfirmationEmailView(generics.GenericAPIView): """Confirm email view.""" - serializer_class = serializers.ConfirmEmailSerializer - queryset = models.User.objects.all() - def patch(self, request, *args, **kwargs): - """Implement PATCH-method""" - # Get user instance - instance = self.request.user + def post(self, request, *args, **kwargs): + """Override create method""" + user = self.request.user + country_code = self.request.country_code - serializer = self.get_serializer(data=request.data, instance=instance) - serializer.is_valid(raise_exception=True) - serializer.save() + if user.email_confirmed: + raise utils_exceptions.EmailConfirmedError() + + # Send verification link on user email for change email address + if settings.USE_CELERY: + send_confirm_email.delay( + user_id=user.id, + country_code=country_code) + else: + send_confirm_email( + user_id=user.id, + country_code=country_code) return Response(status=status.HTTP_200_OK) diff --git a/apps/account/views/web.py b/apps/account/views/web.py index 897c955e..9f2ebcfd 100644 --- a/apps/account/views/web.py +++ b/apps/account/views/web.py @@ -40,8 +40,7 @@ class PasswordResetConfirmView(JWTGenericViewMixin): queryset = models.User.objects.active() def get_object(self): - """Override get_object method - """ + """Override get_object method""" queryset = self.filter_queryset(self.get_queryset()) uidb64 = self.kwargs.get('uidb64') diff --git a/apps/advertisement/migrations/0002_auto_20190917_1307.py b/apps/advertisement/migrations/0002_auto_20190917_1307.py index 178d0f3a..6604a979 100644 --- a/apps/advertisement/migrations/0002_auto_20190917_1307.py +++ b/apps/advertisement/migrations/0002_auto_20190917_1307.py @@ -4,6 +4,20 @@ from django.db import migrations, models import uuid +def fill_uuid(apps, schemaeditor): + Advertisement = apps.get_model('advertisement', 'Advertisement') + for a in Advertisement.objects.all(): + a.uuid = uuid.uuid4() + a.save() + + +def fill_block_level(apps, schemaeditor): + Advertisement = apps.get_model('advertisement', 'Advertisement') + for a in Advertisement.objects.all(): + a.block_level = '' + a.save() + + class Migration(migrations.Migration): dependencies = [ @@ -23,6 +37,12 @@ class Migration(migrations.Migration): field=models.ManyToManyField(to='translation.Language'), ), migrations.AddField( + model_name='advertisement', + name='uuid', + field=models.UUIDField(default=uuid.uuid4, editable=False), + ), + migrations.RunPython(fill_uuid, migrations.RunPython.noop), + migrations.AlterField( model_name='advertisement', name='uuid', field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True), @@ -32,8 +52,14 @@ class Migration(migrations.Migration): name='block_level', ), migrations.AddField( + model_name='advertisement', + name='block_level', + field=models.CharField(blank=True, null=True, max_length=10, verbose_name='Block level') + ), + migrations.RunPython(fill_block_level, migrations.RunPython.noop), + migrations.AlterField( model_name='advertisement', name='block_level', field=models.CharField(max_length=10, verbose_name='Block level') - ) + ), ] diff --git a/apps/authorization/serializers/common.py b/apps/authorization/serializers/common.py index 5d8bb3a8..ed68ba9f 100644 --- a/apps/authorization/serializers/common.py +++ b/apps/authorization/serializers/common.py @@ -4,7 +4,7 @@ from django.contrib.auth import authenticate from django.contrib.auth import password_validation as password_validators from django.db.models import Q from rest_framework import serializers -from rest_framework import validators as rest_validators +from rest_framework.generics import get_object_or_404 from account import models as account_models from authorization import tasks @@ -81,7 +81,6 @@ class LoginByUsernameOrEmailSerializer(SourceSerializerMixin, """Serializer for login user""" # REQUEST username_or_email = serializers.CharField(write_only=True) - password = serializers.CharField(write_only=True) # For cookie properties (Max-Age) remember = serializers.BooleanField(write_only=True) @@ -101,21 +100,24 @@ class LoginByUsernameOrEmailSerializer(SourceSerializerMixin, 'refresh_token', 'access_token', ) + extra_kwargs = { + 'password': {'write_only': True} + } def validate(self, attrs): """Override validate method""" username_or_email = attrs.pop('username_or_email') password = attrs.pop('password') user_qs = account_models.User.objects.filter(Q(username=username_or_email) | - (Q(email=username_or_email))) + Q(email=username_or_email)) if not user_qs.exists(): - raise utils_exceptions.UserNotFoundError() + raise utils_exceptions.WrongAuthCredentials() else: user = user_qs.first() authentication = authenticate(username=user.get_username(), password=password) if not authentication: - raise utils_exceptions.UserNotFoundError() + raise utils_exceptions.WrongAuthCredentials() self.instance = user return attrs @@ -127,10 +129,6 @@ class LoginByUsernameOrEmailSerializer(SourceSerializerMixin, return super().to_representation(instance) -class LogoutSerializer(SourceSerializerMixin): - """Serializer for Logout endpoint.""" - - class RefreshTokenSerializer(SourceSerializerMixin): """Serializer for refresh token view""" refresh_token = serializers.CharField(read_only=True) @@ -169,7 +167,3 @@ class RefreshTokenSerializer(SourceSerializerMixin): class OAuth2Serialzier(SourceSerializerMixin): """Serializer OAuth2 authorization""" token = serializers.CharField(max_length=255) - - -class OAuth2LogoutSerializer(SourceSerializerMixin): - """Serializer for logout""" diff --git a/apps/authorization/tasks.py b/apps/authorization/tasks.py index 9947c2a3..cb186142 100644 --- a/apps/authorization/tasks.py +++ b/apps/authorization/tasks.py @@ -1,7 +1,8 @@ """Authorization app celery tasks.""" import logging -from django.utils.translation import gettext_lazy as _ + from celery import shared_task +from django.utils.translation import gettext_lazy as _ from account import models as account_models @@ -10,12 +11,12 @@ logger = logging.getLogger(__name__) @shared_task -def send_confirm_email(user_id, country_code): +def send_confirm_email(user_id: int, country_code: str): """Send verification email to user.""" try: obj = account_models.User.objects.get(id=user_id) obj.send_email(subject=_('Email confirmation'), message=obj.confirm_email_template(country_code)) - except: + except Exception as e: logger.error(f'METHOD_NAME: {send_confirm_email.__name__}\n' - f'DETAIL: Exception occurred for user: {user_id}') + f'DETAIL: user {user_id}, - {e}') diff --git a/apps/news/views/__init__.py b/apps/authorization/tests/__init__.py similarity index 100% rename from apps/news/views/__init__.py rename to apps/authorization/tests/__init__.py diff --git a/apps/authorization/tests/tests.py b/apps/authorization/tests/tests.py deleted file mode 100644 index 839af828..00000000 --- a/apps/authorization/tests/tests.py +++ /dev/null @@ -1,25 +0,0 @@ -from rest_framework.test import APITestCase -from account.models import User -# Create your tests here. - - -class AuthorizationTests(APITestCase): - - def setUp(self): - self.username = 'sedragurda' - self.password = 'sedragurdaredips19' - self.email = 'sedragurda@desoz.com' - self.newsletter = True - self.user = User.objects.create_user(username=self.username, email=self.email, password=self.password) - self.tokkens = User.create_jwt_tokens(self.user) - - def LoginTests(self): - data ={ - 'username_or_email': self.username, - 'password': self.password, - 'remember': True - } - response = self.client.post('/api/auth/login/', data=data) - self.assertEqual(response.data['access_token'], self.tokkens.get('access_token')) - self.assertEqual(response.data['refresh_token'], self.tokkens.get('refresh_token')) - diff --git a/apps/authorization/tests/tests_authorization.py b/apps/authorization/tests/tests_authorization.py new file mode 100644 index 00000000..a6a49ea5 --- /dev/null +++ b/apps/authorization/tests/tests_authorization.py @@ -0,0 +1,39 @@ +from rest_framework.test import APITestCase +from account.models import User +from django.urls import reverse +# Create your tests here. + + +def get_tokens_for_user( + username='sedragurda', password='sedragurdaredips19', email='sedragurda@desoz.com'): + + user = User.objects.create_user(username=username, email=email, password=password) + tokens = User.create_jwt_tokens(user) + + return { + "username": username, + "password": password, + "email": email, + "newsletter": True, + "user": user, + "tokens": tokens + } + + +class AuthorizationTests(APITestCase): + + def setUp(self): + data = get_tokens_for_user() + self.username = data["username"] + self.password = data["password"] + + def LoginTests(self): + data ={ + 'username_or_email': self.username, + 'password': self.password, + 'remember': True + } + response = self.client.post(reverse('auth:authorization:login'), data=data) + self.assertEqual(response.data['access_token'], self.tokens.get('access_token')) + self.assertEqual(response.data['refresh_token'], self.tokens.get('refresh_token')) + diff --git a/apps/authorization/views/common.py b/apps/authorization/views/common.py index 4231ed7a..0b1a58e0 100644 --- a/apps/authorization/views/common.py +++ b/apps/authorization/views/common.py @@ -27,24 +27,6 @@ from utils.permissions import IsAuthenticatedAndTokenIsValid from utils.views import JWTGenericViewMixin -# Mixins -# JWTAuthView mixin -class JWTAuthViewMixin(JWTGenericViewMixin): - """Mixin for authentication views""" - - def post(self, request, *args, **kwargs): - """Implement POST method""" - serializer = self.get_serializer(data=request.data) - serializer.is_valid(raise_exception=True) - response = Response(serializer.data, status=status.HTTP_200_OK) - access_token = serializer.data.get('access_token') - refresh_token = serializer.data.get('refresh_token') - return self._put_cookies_in_response( - cookies=self._put_data_in_cookies(access_token=access_token, - refresh_token=refresh_token), - response=response) - - # OAuth2 class BaseOAuth2ViewMixin(generics.GenericAPIView): """BaseMixin for classic auth views""" @@ -112,6 +94,7 @@ class OAuth2SignUpView(OAuth2ViewMixin, JWTGenericViewMixin): # Preparing request data serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) + request_data = self.prepare_request_data(serializer.validated_data) source = serializer.validated_data.get('source') request_data.update({ @@ -144,7 +127,8 @@ class OAuth2SignUpView(OAuth2ViewMixin, JWTGenericViewMixin): status=status.HTTP_200_OK) return self._put_cookies_in_response( cookies=self._put_data_in_cookies(access_token=access_token, - refresh_token=refresh_token), + refresh_token=refresh_token, + permanent=True), response=response) @@ -195,7 +179,7 @@ class ConfirmationEmailView(JWTGenericViewMixin): # Login by username|email + password -class LoginByUsernameOrEmailView(JWTAuthViewMixin): +class LoginByUsernameOrEmailView(JWTGenericViewMixin): """Login by email and password""" permission_classes = (permissions.AllowAny,) serializer_class = serializers.LoginByUsernameOrEmailSerializer @@ -204,10 +188,12 @@ class LoginByUsernameOrEmailView(JWTAuthViewMixin): """Implement POST method""" serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) + response = Response(serializer.data, status=status.HTTP_200_OK) access_token = serializer.data.get('access_token') refresh_token = serializer.data.get('refresh_token') is_permanent = serializer.validated_data.get('remember') + return self._put_cookies_in_response( cookies=self._put_data_in_cookies(access_token=access_token, refresh_token=refresh_token, @@ -242,9 +228,11 @@ class RefreshTokenView(JWTGenericViewMixin): def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) + response = Response(serializer.data, status=status.HTTP_201_CREATED) access_token = serializer.data.get('access_token') refresh_token = serializer.data.get('refresh_token') + return self._put_cookies_in_response( cookies=self._put_data_in_cookies(access_token=access_token, refresh_token=refresh_token), diff --git a/apps/news/serializers/web.py b/apps/booking/__init__.py similarity index 100% rename from apps/news/serializers/web.py rename to apps/booking/__init__.py diff --git a/apps/booking/admin.py b/apps/booking/admin.py new file mode 100644 index 00000000..3eb9d180 --- /dev/null +++ b/apps/booking/admin.py @@ -0,0 +1,8 @@ +from django.contrib import admin + +from booking.models import models + + +@admin.register(models.Booking) +class BookingModelAdmin(admin.ModelAdmin): + """Model admin for model Comment""" \ No newline at end of file diff --git a/apps/booking/apps.py b/apps/booking/apps.py new file mode 100644 index 00000000..5319bb5b --- /dev/null +++ b/apps/booking/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig +from django.utils.translation import ugettext_lazy as _ + + +class BookingConfig(AppConfig): + name = 'booking' + verbose_name = _('Booking') diff --git a/apps/booking/migrations/0001_initial_squashed_0010_auto_20190920_1206.py b/apps/booking/migrations/0001_initial_squashed_0010_auto_20190920_1206.py new file mode 100644 index 00000000..33131471 --- /dev/null +++ b/apps/booking/migrations/0001_initial_squashed_0010_auto_20190920_1206.py @@ -0,0 +1,37 @@ +# Generated by Django 2.2.4 on 2019-10-03 10:38 + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone + + +class Migration(migrations.Migration): + + replaces = [('booking', '0001_initial'), ('booking', '0002_booking_user'), ('booking', '0003_auto_20190916_1533'), ('booking', '0004_auto_20190916_1646'), ('booking', '0005_auto_20190918_1308'), ('booking', '0006_booking_country_code'), ('booking', '0007_booking_booking_id'), ('booking', '0008_auto_20190919_2008'), ('booking', '0009_booking_user'), ('booking', '0010_auto_20190920_1206')] + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Booking', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created', models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name='Date created')), + ('modified', models.DateTimeField(auto_now=True, verbose_name='Date updated')), + ('type', models.CharField(choices=[('L', 'Lastable'), ('G', 'GuestOnline')], max_length=2, verbose_name='Guestonline or Lastable')), + ('booking_user_locale', models.CharField(default='en', max_length=10, verbose_name='booking locale')), + ('restaurant_id', models.PositiveIntegerField(default=None, verbose_name='booking service establishment id')), + ('pending_booking_id', models.TextField(default=None, verbose_name='external service pending booking')), + ('booking_id', models.TextField(db_index=True, default=None, null=True, verbose_name='external service booking id')), + ('user', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='bookings', to=settings.AUTH_USER_MODEL, verbose_name='booking owner')), + ], + options={ + 'abstract': False, + 'verbose_name': 'Booking', + 'verbose_name_plural': 'Booking', + }, + ), + ] diff --git a/apps/booking/migrations/0002_auto_20191003_1601.py b/apps/booking/migrations/0002_auto_20191003_1601.py new file mode 100644 index 00000000..7f3814cd --- /dev/null +++ b/apps/booking/migrations/0002_auto_20191003_1601.py @@ -0,0 +1,22 @@ +# Generated by Django 2.2.4 on 2019-10-03 16:01 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('booking', '0001_initial_squashed_0010_auto_20190920_1206'), + ] + + operations = [ + migrations.RemoveField( + model_name='booking', + name='restaurant_id', + ), + migrations.AddField( + model_name='booking', + name='restaurant_id', + field=models.TextField(default=None, verbose_name='booking service establishment id'), + ), + ] diff --git a/apps/news/views/web.py b/apps/booking/migrations/__init__.py similarity index 100% rename from apps/news/views/web.py rename to apps/booking/migrations/__init__.py diff --git a/apps/booking/models/__init__.py b/apps/booking/models/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/booking/models/models.py b/apps/booking/models/models.py new file mode 100644 index 00000000..41cfc6d7 --- /dev/null +++ b/apps/booking/models/models.py @@ -0,0 +1,67 @@ +from django.db import models +from django.utils.translation import gettext_lazy as _ +from rest_framework import serializers +from utils.models import ProjectBaseMixin +from booking.models.services import LastableService, GuestonlineService +from account.models import User + + +class BookingManager(models.QuerySet): + def by_user(self, user: User): + return self.filter(user=user) + + +class Booking(ProjectBaseMixin): + LASTABLE = 'L' + GUESTONLINE = 'G' + AVAILABLE_SERVICES = ( + (LASTABLE, 'Lastable'), + (GUESTONLINE, 'GuestOnline') + ) + type = models.CharField(max_length=2, choices=AVAILABLE_SERVICES, verbose_name=_('Guestonline or Lastable')) + restaurant_id = models.TextField(verbose_name=_('booking service establishment id'), default=None) + booking_user_locale = models.CharField(verbose_name=_('booking locale'), default='en', max_length=10) + pending_booking_id = models.TextField(verbose_name=_('external service pending booking'), default=None) + booking_id = models.TextField(verbose_name=_('external service booking id'), default=None, null=True, + db_index=True, ) + user = models.ForeignKey( + 'account.User', verbose_name=_('booking owner'), null=True, + related_name='bookings', + blank=True, default=None, on_delete=models.CASCADE) + objects = BookingManager.as_manager() + + @property + def accept_email_spam(self): + return False + + @property + def accept_sms_spam(self): + return False + + @classmethod + def get_service_by_type(cls, type): + if type == cls.GUESTONLINE: + return GuestonlineService() + elif type == cls.LASTABLE: + return LastableService() + else: + return None + + @classmethod + def get_booking_id_by_type(cls, establishment, type): + if type == cls.GUESTONLINE: + return establishment.guestonline_id + elif type == cls.LASTABLE: + return establishment.lastable_id + else: + return None + + def delete(self, using=None, keep_parents=False): + service = self.get_service_by_type(self.type) + if not service.cancel_booking(self.booking_id): + raise serializers.ValidationError(detail='Something went wrong! Unable to cancel.') + super().delete(using, keep_parents) + + class Meta: + verbose_name = _('Booking') + verbose_name_plural = _('Booking') diff --git a/apps/booking/models/services.py b/apps/booking/models/services.py new file mode 100644 index 00000000..a3ee17ea --- /dev/null +++ b/apps/booking/models/services.py @@ -0,0 +1,166 @@ +from abc import ABC, abstractmethod +import json +import requests +from django.conf import settings +from rest_framework import status +import booking.models.models as models +from rest_framework import serializers + + +class AbstractBookingService(ABC): + """ Abstract class for Guestonline && Lastable booking services""" + + def __init__(self, service): + self.service = None + self.response = None + if service not in [models.Booking.LASTABLE, models.Booking.GUESTONLINE]: + raise Exception('Service %s is not implemented yet' % service) + self.service = service + if service == models.Booking.GUESTONLINE: + self.token = settings.GUESTONLINE_TOKEN + self.url = settings.GUESTONLINE_SERVICE + elif service == models.Booking.LASTABLE: + self.token = settings.LASTABLE_TOKEN + self.url = settings.LASTABLE_SERVICE + + @staticmethod + def get_certain_keys(d: dict, keys_to_preserve: set) -> dict: + """ Helper """ + return {key: d[key] for key in d.keys() & keys_to_preserve} + + @abstractmethod + def check_whether_booking_available(self, restaurant_id, date): + """ checks whether booking is available """ + if date is None: + raise serializers.ValidationError(detail='date query param is required') + + @abstractmethod + def cancel_booking(self, payload): + """ cancels booking and returns the result """ + pass + + @abstractmethod + def create_booking(self, payload): + """ returns pending booking id if created. otherwise False """ + pass + + @abstractmethod + def update_booking(self, payload): + """ updates pending booking with contacts """ + pass + + @abstractmethod + def get_common_headers(self): + pass + + @abstractmethod + def get_booking_details(self, payload): + """ fetches booking details from external service """ + pass + + +class GuestonlineService(AbstractBookingService): + def __init__(self): + super().__init__(models.Booking.GUESTONLINE) + + def get_common_headers(self): + return {'X-Token': self.token, 'Content-type': 'application/json', 'Accept': 'application/json'} + + def check_whether_booking_available(self, restaurant_id, date: str): + super().check_whether_booking_available(restaurant_id, date) + url = f'{self.url}v1/runtime_services' + params = {'restaurant_id': restaurant_id, 'date': date, 'expands[]': 'table_availabilities'} + r = requests.get(url, headers=self.get_common_headers(), params=params) + if not status.is_success(r.status_code): + return False + response = json.loads(r.content)['runtime_services'] + keys_to_preserve = {'left_seats', 'table_availabilities', 'closed', 'start_time', 'end_time', 'last_booking'} + response = map(lambda x: self.get_certain_keys(x, keys_to_preserve), response) + self.response = response + return True + + def commit_booking(self, payload): + url = f'{self.url}v1/pending_bookings/{payload}/commit' + r = requests.put(url, headers=self.get_common_headers()) + self.response = json.loads(r.content) + if status.is_success(r.status_code) and self.response is None: + raise serializers.ValidationError(detail='Booking already committed.') + return status.is_success(r.status_code) + + def update_booking(self, payload): + booking_id = payload.pop('pending_booking_id') + url = f'{self.url}v1/pending_bookings/{booking_id}' + payload['lastname'] = payload.pop('last_name') + payload['firstname'] = payload.pop('first_name') + payload['mobile_phone'] = payload.pop('phone') + headers = self.get_common_headers() + r = requests.put(url, headers=headers, data=json.dumps({'contact_info': payload})) + return status.is_success(r.status_code) + + def create_booking(self, payload): + url = f'{self.url}v1/pending_bookings' + payload['hour'] = payload.pop('booking_time') + payload['persons'] = payload.pop('booked_persons_number') + payload['date'] = payload.pop('booking_date') + r = requests.post(url, headers=self.get_common_headers(), data=json.dumps(payload)) + return json.loads(r.content)['id'] if status.is_success(r.status_code) else False + + def cancel_booking(self, payload): + url = f'{self.url}v1/pending_bookings/{payload}' + r = requests.delete(url, headers=self.get_common_headers()) + return status.is_success(r.status_code) + + def get_booking_details(self, payload): + url = f'{self.url}v1/bookings/{payload}' + r = requests.get(url, headers=self.get_common_headers()) + return json.loads(r.content) + + +class LastableService(AbstractBookingService): + def __init__(self): + super().__init__(models.Booking.LASTABLE) + self.proxies = { + 'http': settings.LASTABLE_PROXY, + 'https': settings.LASTABLE_PROXY, + } + + def create_booking(self, payload): + url = f'{self.url}v1/partner/orders' + payload['places'] = payload.pop('booked_persons_number') + payload['hour'] = payload.pop('booking_time') + payload['firstName'] = payload.pop('first_name') + payload['lastName'] = payload.pop('last_name') + r = requests.post(url, headers=self.get_common_headers(), proxies=self.proxies, data=json.dumps(payload)) + return json.loads(r.content)['data']['_id'] if status.is_success(r.status_code) else False + + def get_common_headers(self): + return {'Authorization': f'Bearer {self.token}', 'Content-type': 'application/json', + 'Accept': 'application/json'} + + def check_whether_booking_available(self, restaurant_id, date): + super().check_whether_booking_available(restaurant_id, date) + url = f'{self.url}v1/restaurant/{restaurant_id}/offers' + r = requests.get(url, headers=self.get_common_headers(), proxies=self.proxies) + response = json.loads(r.content).get('data') + if not status.is_success(r.status_code) or not response: + return False + self.response = response + return True + + def commit_booking(self, payload): + """ Lastable service has no pending booking to commit """ + return False + + def update_booking(self, payload): + """ Lastable service has no pending booking to update """ + return False + + def cancel_booking(self, payload): + url = f'{self.url}v1/partner/orders/{payload}' + r = requests.delete(url, headers=self.get_common_headers(), proxies=self.proxies) + return status.is_success(r.status_code) + + def get_booking_details(self, payload): + url = f'{self.url}v1/partner/orders/{payload}' + r = requests.get(url, headers=self.get_common_headers(), proxies=self.proxies) + return json.loads(r.content) diff --git a/apps/booking/serializers/__init__.py b/apps/booking/serializers/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/booking/serializers/web.py b/apps/booking/serializers/web.py new file mode 100644 index 00000000..1094aef8 --- /dev/null +++ b/apps/booking/serializers/web.py @@ -0,0 +1,64 @@ +from rest_framework import serializers +from booking.models import models + + +class BookingSerializer(serializers.ModelSerializer): + class Meta: + model = models.Booking + fields = ( + 'id', + 'type', + ) + + +class CheckBookingSerializer(serializers.ModelSerializer): + available = serializers.BooleanField() + type = serializers.ChoiceField(choices=models.Booking.AVAILABLE_SERVICES, allow_null=True) + details = serializers.DictField() + + class Meta: + model = models.Booking + fields = ( + 'available', + 'type', + 'details', + ) + + +class PendingBookingSerializer(serializers.ModelSerializer): + restaurant_id = serializers.CharField() + booking_id = serializers.CharField(allow_null=True, allow_blank=True) + id = serializers.ReadOnlyField() + user = serializers.ReadOnlyField() + + class Meta: + model = models.Booking + fields = ( + 'id', + 'type', + 'restaurant_id', + 'booking_id', + 'pending_booking_id', + 'user', + ) + + +class UpdateBookingSerializer(serializers.ModelSerializer): + id = serializers.ReadOnlyField() + + class Meta: + model = models.Booking + fields = ('booking_id', 'id') + + +class GetBookingSerializer(serializers.ModelSerializer): + details = serializers.SerializerMethodField() + + def get_details(self, obj): + booking = self.instance + service = booking.get_service_by_type(booking.type) + return service.get_booking_details(booking.booking_id) + + class Meta: + model = models.Booking + fields = '__all__' diff --git a/apps/account/tests.py b/apps/booking/tests.py similarity index 100% rename from apps/account/tests.py rename to apps/booking/tests.py diff --git a/apps/booking/urls.py b/apps/booking/urls.py new file mode 100644 index 00000000..900ec8cb --- /dev/null +++ b/apps/booking/urls.py @@ -0,0 +1,14 @@ +"""Booking app urls.""" +from django.urls import path +from booking import views + +app = 'booking' + +urlpatterns = [ + path('/check/', views.CheckWhetherBookingAvailable.as_view(), name='booking-check'), + path('/create/', views.CreatePendingBooking.as_view(), name='create-pending-booking'), + path('/', views.UpdatePendingBooking.as_view(), name='update-pending-booking'), + path('/cancel/', views.CancelBooking.as_view(), name='cancel-existing-booking'), + path('last/', views.LastBooking.as_view(), name='last_booking-for-authorizer-user'), + path('retrieve//', views.GetBookingById.as_view(), name='retrieves-booking-by-id'), +] diff --git a/apps/booking/views.py b/apps/booking/views.py new file mode 100644 index 00000000..dfa64bb9 --- /dev/null +++ b/apps/booking/views.py @@ -0,0 +1,118 @@ +from rest_framework import generics, permissions, status, serializers + +from django.shortcuts import get_object_or_404 +from establishment.models import Establishment +from booking.models.models import Booking, GuestonlineService, LastableService +from rest_framework.response import Response +from booking.serializers.web import (PendingBookingSerializer, + UpdateBookingSerializer, GetBookingSerializer, CheckBookingSerializer) + + +class CheckWhetherBookingAvailable(generics.GenericAPIView): + """ Checks which service to use if establishmend is managed by any """ + + permission_classes = (permissions.AllowAny,) + serializer_class = CheckBookingSerializer + pagination_class = None + + def get(self, request, *args, **kwargs): + is_booking_available = False + establishment = get_object_or_404(Establishment, pk=kwargs['establishment_id']) + service = None + date = request.query_params.get('date') + g_service = GuestonlineService() + l_service = LastableService() + if (not establishment.lastable_id is None) and l_service \ + .check_whether_booking_available(establishment.lastable_id, date): + is_booking_available = True + service = l_service + service.service_id = establishment.lastable_id + elif (not establishment.guestonline_id is None) and g_service \ + .check_whether_booking_available(establishment.guestonline_id, date): + is_booking_available = True + service = g_service + service.service_id = establishment.guestonline_id + + response = { + 'available': is_booking_available, + 'type': service.service if service else None, + } + response.update({'details': service.response} if service and service.response else {}) + return Response(data=response, status=200) + + +class CreatePendingBooking(generics.CreateAPIView): + """ Creates pending booking """ + permission_classes = (permissions.AllowAny,) + serializer_class = PendingBookingSerializer + + def post(self, request, *args, **kwargs): + data = request.data.copy() + if data.get('type') == Booking.LASTABLE and data.get("offer_id") is None: + raise serializers.ValidationError(detail='Offer_id is required field for Lastable service') + establishment = get_object_or_404(Establishment, pk=kwargs['establishment_id']) + data['restaurant_id'] = Booking.get_booking_id_by_type(establishment, data.get('type')) + service = Booking.get_service_by_type(request.data.get('type')) + data['user'] = request.user.pk if request.user else None + service_to_keys = { + Booking.GUESTONLINE: {'restaurant_id', 'booking_time', 'booking_date', 'booked_persons_number', }, + Booking.LASTABLE: {'booking_time', 'booked_persons_number', 'offer_id', 'email', 'phone', + 'first_name', 'last_name', }, + } + data['pending_booking_id'] = service.create_booking( + service.get_certain_keys(data.copy(), service_to_keys[data.get('type')])) + if not data['pending_booking_id']: + return Response(status=status.HTTP_403_FORBIDDEN, data='Unable to create booking') + data['booking_id'] = data['pending_booking_id'] if data.get('type') == Booking.LASTABLE else None + serializer = self.get_serializer(data=data) + serializer.is_valid(raise_exception=True) + serializer.save() + return Response(status=status.HTTP_201_CREATED, data=serializer.data) + + +class UpdatePendingBooking(generics.UpdateAPIView): + """ Update pending booking with contacts """ + queryset = Booking.objects.all() + permission_classes = (permissions.AllowAny,) + serializer_class = UpdateBookingSerializer + + def patch(self, request, *args, **kwargs): + instance = self.get_object() + data = request.data.copy() + service = Booking.get_service_by_type(instance.type) + data['pending_booking_id'] = instance.pending_booking_id + service.update_booking(service.get_certain_keys(data, { + 'email', 'phone', 'last_name', 'first_name', 'country_code', 'pending_booking_id', + })) + service.commit_booking(data['pending_booking_id']) + data = { + 'booking_id': service.response.get('id'), + 'id': instance.pk, + } + serializer = self.get_serializer(data=data) + serializer.is_valid(raise_exception=True) + serializer.update(instance, data) + return Response(status=status.HTTP_200_OK, data=serializer.data) + + +class CancelBooking(generics.DestroyAPIView): + """ Cancel existing booking """ + queryset = Booking.objects.all() + permission_classes = (permissions.AllowAny,) + + +class LastBooking(generics.RetrieveAPIView): + """ Get last booking by user credentials """ + permission_classes = (permissions.IsAuthenticated,) + serializer_class = GetBookingSerializer + lookup_field = None + + def get_object(self): + return Booking.objects.by_user(self.request.user).latest('modified') + + +class GetBookingById(generics.RetrieveAPIView): + """ Returns booking by its id""" + permission_classes = (permissions.AllowAny,) + serializer_class = GetBookingSerializer + queryset = Booking.objects.all() diff --git a/apps/collection/admin.py b/apps/collection/admin.py index 3d0a8e3c..2e2c22e2 100644 --- a/apps/collection/admin.py +++ b/apps/collection/admin.py @@ -8,11 +8,6 @@ class CollectionAdmin(admin.ModelAdmin): """Collection admin.""" -@admin.register(models.CollectionItem) -class CollectionItemAdmin(admin.ModelAdmin): - """CollectionItem admin.""" - - @admin.register(models.Guide) class GuideAdmin(admin.ModelAdmin): """Guide admin.""" diff --git a/apps/collection/migrations/0009_delete_collectionitem.py b/apps/collection/migrations/0009_delete_collectionitem.py new file mode 100644 index 00000000..ea8fca72 --- /dev/null +++ b/apps/collection/migrations/0009_delete_collectionitem.py @@ -0,0 +1,16 @@ +# Generated by Django 2.2.4 on 2019-09-20 08:55 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('collection', '0008_auto_20190916_1158'), + ] + + operations = [ + migrations.DeleteModel( + name='CollectionItem', + ), + ] diff --git a/apps/collection/migrations/0010_collection_description.py b/apps/collection/migrations/0010_collection_description.py new file mode 100644 index 00000000..b66d8156 --- /dev/null +++ b/apps/collection/migrations/0010_collection_description.py @@ -0,0 +1,19 @@ +# Generated by Django 2.2.4 on 2019-09-20 09:27 + +from django.db import migrations +import utils.models + + +class Migration(migrations.Migration): + + dependencies = [ + ('collection', '0009_delete_collectionitem'), + ] + + operations = [ + migrations.AddField( + model_name='collection', + name='description', + field=utils.models.TJSONField(blank=True, default=None, help_text='{"en-GB":"some text"}', null=True, verbose_name='description'), + ), + ] diff --git a/apps/collection/migrations/0011_auto_20190920_1059.py b/apps/collection/migrations/0011_auto_20190920_1059.py new file mode 100644 index 00000000..ac3c21c5 --- /dev/null +++ b/apps/collection/migrations/0011_auto_20190920_1059.py @@ -0,0 +1,22 @@ +# Generated by Django 2.2.4 on 2019-09-20 10:59 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('collection', '0010_collection_description'), + ] + + operations = [ + migrations.RemoveField( + model_name='collection', + name='image', + ), + migrations.AddField( + model_name='collection', + name='image_url', + field=models.URLField(blank=True, default=None, null=True, verbose_name='Image URL path'), + ), + ] diff --git a/apps/collection/migrations/0012_auto_20190923_1340.py b/apps/collection/migrations/0012_auto_20190923_1340.py new file mode 100644 index 00000000..50725597 --- /dev/null +++ b/apps/collection/migrations/0012_auto_20190923_1340.py @@ -0,0 +1,19 @@ +# Generated by Django 2.2.4 on 2019-09-23 13:40 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('collection', '0011_auto_20190920_1059'), + ] + + operations = [ + migrations.AlterField( + model_name='guide', + name='parent', + field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='collection.Guide', verbose_name='parent'), + ), + ] diff --git a/apps/collection/migrations/0013_collection_slug.py b/apps/collection/migrations/0013_collection_slug.py new file mode 100644 index 00000000..cf7f5929 --- /dev/null +++ b/apps/collection/migrations/0013_collection_slug.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-09-24 08:06 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('collection', '0012_auto_20190923_1340'), + ] + + operations = [ + migrations.AddField( + model_name='collection', + name='slug', + field=models.SlugField(null=True, unique=True, verbose_name='Collection slug'), + ), + ] diff --git a/apps/collection/migrations/0014_auto_20191022_1242.py b/apps/collection/migrations/0014_auto_20191022_1242.py new file mode 100644 index 00000000..d70c0cfa --- /dev/null +++ b/apps/collection/migrations/0014_auto_20191022_1242.py @@ -0,0 +1,23 @@ +# Generated by Django 2.2.4 on 2019-10-22 12:42 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('collection', '0013_collection_slug'), + ] + + operations = [ + migrations.AlterField( + model_name='collection', + name='end', + field=models.DateTimeField(blank=True, default=None, null=True, verbose_name='end'), + ), + migrations.AlterField( + model_name='guide', + name='end', + field=models.DateTimeField(blank=True, default=None, null=True, verbose_name='end'), + ), + ] diff --git a/apps/collection/models.py b/apps/collection/models.py index 3ef4d0bf..e7c930c3 100644 --- a/apps/collection/models.py +++ b/apps/collection/models.py @@ -1,10 +1,12 @@ -from django.contrib.postgres.fields import JSONField from django.contrib.contenttypes.fields import ContentType -from django.contrib.contenttypes import fields as generic +from django.contrib.postgres.fields import JSONField from django.db import models from django.utils.translation import gettext_lazy as _ -from utils.models import ProjectBaseMixin, ImageMixin +from utils.models import ProjectBaseMixin, URLImageMixin +from utils.models import TJSONField +from utils.models import TranslatedFieldsMixin +from utils.querysets import RelatedObjectsCountMixin # Mixins @@ -20,7 +22,8 @@ class CollectionNameMixin(models.Model): class CollectionDateMixin(models.Model): """CollectionDate mixin""" start = models.DateTimeField(_('start')) - end = models.DateTimeField(_('end')) + end = models.DateTimeField(blank=True, null=True, default=None, + verbose_name=_('end')) class Meta: """Meta class""" @@ -28,7 +31,7 @@ class CollectionDateMixin(models.Model): # Models -class CollectionQuerySet(models.QuerySet): +class CollectionQuerySet(RelatedObjectsCountMixin): """QuerySet for model Collection""" def by_country_code(self, code): @@ -40,7 +43,8 @@ class CollectionQuerySet(models.QuerySet): return self.filter(is_publish=True) -class Collection(ProjectBaseMixin, CollectionNameMixin, CollectionDateMixin): +class Collection(ProjectBaseMixin, CollectionNameMixin, CollectionDateMixin, + TranslatedFieldsMixin, URLImageMixin): """Collection model.""" ORDINARY = 0 # Ordinary collection POP = 1 # POP collection @@ -53,9 +57,6 @@ class Collection(ProjectBaseMixin, CollectionNameMixin, CollectionDateMixin): collection_type = models.PositiveSmallIntegerField(choices=COLLECTION_TYPES, default=ORDINARY, verbose_name=_('Collection type')) - image = models.ForeignKey( - 'gallery.Image', null=True, blank=True, default=None, - verbose_name=_('Collection image'), on_delete=models.CASCADE) is_publish = models.BooleanField( default=False, verbose_name=_('Publish status')) on_top = models.BooleanField( @@ -65,6 +66,11 @@ class Collection(ProjectBaseMixin, CollectionNameMixin, CollectionDateMixin): block_size = JSONField( _('collection block properties'), null=True, blank=True, default=None, help_text='{"width": "250px", "height":"250px"}') + description = TJSONField( + _('description'), null=True, blank=True, + default=None, help_text='{"en-GB":"some text"}') + slug = models.SlugField(max_length=50, unique=True, + verbose_name=_('Collection slug'), editable=True, null=True) objects = CollectionQuerySet.as_manager() @@ -78,26 +84,6 @@ class Collection(ProjectBaseMixin, CollectionNameMixin, CollectionDateMixin): return f'{self.name}' -class CollectionItemQuerySet(models.QuerySet): - """QuerySet for model CollectionItem.""" - - def by_collection(self, collection_id): - """Filter by collection id""" - return self.filter(collection=collection_id) - - -class CollectionItem(ProjectBaseMixin): - """CollectionItem model.""" - collection = models.ForeignKey( - Collection, verbose_name=_('collection'), on_delete=models.CASCADE) - content_type = models.ForeignKey(ContentType, default=None, - null=True, blank=True, on_delete=models.CASCADE) - object_id = models.PositiveIntegerField(default=None, null=True, blank=True) - content_object = generic.GenericForeignKey('content_type', 'object_id') - - objects = CollectionItemQuerySet.as_manager() - - class GuideQuerySet(models.QuerySet): """QuerySet for Guide.""" @@ -109,7 +95,9 @@ class GuideQuerySet(models.QuerySet): class Guide(ProjectBaseMixin, CollectionNameMixin, CollectionDateMixin): """Guide model.""" parent = models.ForeignKey( - 'self', verbose_name=_('parent'), on_delete=models.CASCADE) + 'self', verbose_name=_('parent'), on_delete=models.CASCADE, + null=True, blank=True, default=None + ) advertorials = JSONField( _('advertorials'), null=True, blank=True, default=None, help_text='{"key":"value"}') diff --git a/apps/collection/serializers/common.py b/apps/collection/serializers/common.py index 87bf7802..78612a55 100644 --- a/apps/collection/serializers/common.py +++ b/apps/collection/serializers/common.py @@ -1,19 +1,32 @@ from rest_framework import serializers from collection import models -from gallery import models as gallery_models from location import models as location_models -class CollectionSerializer(serializers.ModelSerializer): - """Collection serializer""" +class CollectionBaseSerializer(serializers.ModelSerializer): + """Collection base serializer""" # RESPONSE - image_url = serializers.ImageField(source='image.image') + description_translated = serializers.CharField(read_only=True, allow_null=True) + class Meta: + model = models.Collection + fields = [ + 'id', + 'name', + 'description_translated', + 'image_url', + 'slug', + ] + + +class CollectionSerializer(CollectionBaseSerializer): + """Collection serializer""" # COMMON block_size = serializers.JSONField() is_publish = serializers.BooleanField() on_top = serializers.BooleanField() + slug = serializers.SlugField(allow_blank=False, required=True, max_length=50) # REQUEST start = serializers.DateTimeField(write_only=True) @@ -21,19 +34,12 @@ class CollectionSerializer(serializers.ModelSerializer): country = serializers.PrimaryKeyRelatedField( queryset=location_models.Country.objects.all(), write_only=True) - image = serializers.PrimaryKeyRelatedField( - queryset=gallery_models.Image.objects.all(), - write_only=True) class Meta: model = models.Collection - fields = [ - 'id', - 'name', + fields = CollectionBaseSerializer.Meta.fields + [ 'start', 'end', - 'image', - 'image_url', 'is_publish', 'on_top', 'country', @@ -41,18 +47,6 @@ class CollectionSerializer(serializers.ModelSerializer): ] -class CollectionItemSerializer(serializers.ModelSerializer): - """CollectionItem serializer""" - class Meta: - model = models.CollectionItem - fields = [ - 'id', - 'collection', - 'content_type', - 'object_id', - ] - - class GuideSerializer(serializers.ModelSerializer): """Guide serializer""" class Meta: diff --git a/apps/collection/tests.py b/apps/collection/tests.py index 7ce503c2..b2b8231b 100644 --- a/apps/collection/tests.py +++ b/apps/collection/tests.py @@ -1,3 +1,112 @@ -from django.test import TestCase +import json +import pytz +from datetime import datetime +from http.cookies import SimpleCookie -# Create your tests here. +from rest_framework import status +from rest_framework.test import APITestCase + +from account.models import User +from collection.models import Collection, Guide +from establishment.models import Establishment, EstablishmentType +from location.models import Country + + +class BaseTestCase(APITestCase): + + def setUp(self): + self.username = 'sedragurda' + self.password = 'sedragurdaredips19' + self.email = 'sedragurda@desoz.com' + self.newsletter = True + self.user = User.objects.create_user( + username=self.username, email=self.email, password=self.password) + # get tokens + tokens = User.create_jwt_tokens(self.user) + self.client.cookies = SimpleCookie( + {'access_token': tokens.get('access_token'), + 'refresh_token': tokens.get('refresh_token'), + 'country_code': 'en'}) + + +class CollectionListTests(BaseTestCase): + def test_collection_list_Read(self): + response = self.client.get('/api/web/collections/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + +class CollectionDetailTests(BaseTestCase): + + def setUp(self): + super().setUp() + + # country = Country.objects.first() + # if not country: + country = Country.objects.create( + name=json.dumps({"en-GB": "Test country"}), + code="en" + ) + country.save() + + self.collection = Collection.objects.create( + name='Test collection', + is_publish=True, + start=datetime.now(pytz.utc), + end=datetime.now(pytz.utc), + country=country, + slug='test-collection-slug', + ) + + self.collection.save() + + def test_collection_detail_Read(self): + response = self.client.get(f'/api/web/collections/{self.collection.slug}/establishments/?country_code=en', + format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + +class CollectionGuideTests(CollectionDetailTests): + + def test_guide_list_Read(self): + response = self.client.get('/api/web/collections/guides/', format='json') + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + + +class CollectionGuideDetailTests(CollectionDetailTests): + + def setUp(self): + super().setUp() + self.guide = Guide.objects.create( + collection=self.collection, + start=datetime.now(pytz.utc), + end=datetime.now(pytz.utc) + ) + self.guide.save() + + def test_guide_detail_Read(self): + response = self.client.get(f'/api/web/collections/guides/{self.guide.id}/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + +class CollectionWebHomeTests(CollectionDetailTests): + def setUp(self): + super().setUp() + self.establishment_type = EstablishmentType.objects.create(name="Test establishment type") + + for i in range(1, 5): + setattr(self, f"establishment{i}", + Establishment.objects.create( + name=f"Test establishment {i}", + establishment_type_id=self.establishment_type.id, + is_publish=True, + slug=f"test-establishment-{i}" + ) + ) + + getattr(self, f"establishment{i}").collections.add(self.collection) + + def test_collection_list_filter(self): + response = self.client.get('/api/web/collections/?country_code=en', format='json') + data = response.json() + self.assertIn('count', data) + self.assertGreater(data['count'], 0) diff --git a/apps/collection/urls/common.py b/apps/collection/urls/common.py index 4396bff4..36801ac5 100644 --- a/apps/collection/urls/common.py +++ b/apps/collection/urls/common.py @@ -6,12 +6,10 @@ from collection.views import common as views app_name = 'collection' urlpatterns = [ - path('', views.CollectionListView.as_view(), name='list'), - path('/', views.CollectionRetrieveView.as_view(), name='detail'), - - path('items/', views.CollectionItemListView.as_view(), name='collection-items-list'), - path('items//', views.CollectionItemRetrieveView.as_view(), - name='collection-items-detail'), + path('', views.CollectionHomePageView.as_view(), name='list'), + path('/', views.CollectionDetailView.as_view(), name='detail'), + path('/establishments/', views.CollectionEstablishmentListView.as_view(), + name='detail'), path('guides/', views.GuideListView.as_view(), name='guides-list'), path('guides//', views.GuideRetrieveView.as_view(), name='guides-detail'), diff --git a/apps/collection/views/common.py b/apps/collection/views/common.py index af7c4849..5bf8f70e 100644 --- a/apps/collection/views/common.py +++ b/apps/collection/views/common.py @@ -2,6 +2,9 @@ from rest_framework import generics from rest_framework import permissions from collection import models +from utils.pagination import ProjectPageNumberPagination +from django.shortcuts import get_object_or_404 +from establishment.serializers import EstablishmentBaseSerializer from collection.serializers import common as serializers @@ -9,13 +12,14 @@ from collection.serializers import common as serializers class CollectionViewMixin(generics.GenericAPIView): """Mixin for Collection view""" model = models.Collection - queryset = models.Collection.objects.all() + permission_classes = (permissions.AllowAny,) + serializer_class = serializers.CollectionSerializer - -class CollectionItemViewMixin(generics.GenericAPIView): - """Mixin for CollectionItem view""" - model = models.CollectionItem - queryset = models.CollectionItem.objects.all() + def get_queryset(self): + """Override get_queryset method.""" + return models.Collection.objects.published() \ + .by_country_code(code=self.request.country_code) \ + .order_by('-on_top', '-modified') class GuideViewMixin(generics.GenericAPIView): @@ -27,35 +31,42 @@ class GuideViewMixin(generics.GenericAPIView): # Views # Collections class CollectionListView(CollectionViewMixin, generics.ListAPIView): - """List Collection view""" - pagination_class = None - permission_classes = (permissions.AllowAny,) - serializer_class = serializers.CollectionSerializer + """List Collection view.""" + + +class CollectionHomePageView(CollectionListView): + """Collection list view for home page.""" def get_queryset(self): - """Override get_queryset method""" - return models.Collection.objects.published()\ - .by_country_code(code=self.request.country_code)\ - .order_by('-on_top', '-created') + """Override get_queryset.""" + return super(CollectionHomePageView, self).get_queryset() \ + .filter_all_related_gt(3) -class CollectionRetrieveView(CollectionViewMixin, generics.RetrieveAPIView): - """Retrieve Collection view""" - permission_classes = (permissions.AllowAny,) - serializer_class = serializers.CollectionSerializer +class CollectionDetailView(CollectionViewMixin, generics.RetrieveAPIView): + """Retrieve detail of Collection instance.""" + lookup_field = 'slug' + serializer_class = serializers.CollectionBaseSerializer -# CollectionItem -class CollectionItemListView(CollectionItemViewMixin, generics.ListAPIView): - """List CollectionItem view""" - permission_classes = (permissions.AllowAny,) - serializer_class = serializers.CollectionItemSerializer +class CollectionEstablishmentListView(CollectionListView): + """Retrieve list of establishment for collection.""" + lookup_field = 'slug' + pagination_class = ProjectPageNumberPagination + serializer_class = EstablishmentBaseSerializer + def get_queryset(self): + """ + Override get_queryset method. + """ + queryset = super(CollectionEstablishmentListView, self).get_queryset() + # Perform the lookup filtering. + collection = get_object_or_404(queryset, slug=self.kwargs['slug']) -class CollectionItemRetrieveView(CollectionItemViewMixin, generics.RetrieveAPIView): - """Retrieve CollectionItem view""" - permission_classes = (permissions.AllowAny,) - serializer_class = serializers.CollectionItemSerializer + # May raise a permission denied + self.check_object_permissions(self.request, collection) + + return collection.establishments.all() # Guide diff --git a/apps/comment/migrations/0002_comment_language.py b/apps/comment/migrations/0002_comment_language.py new file mode 100644 index 00000000..4b0b9ab7 --- /dev/null +++ b/apps/comment/migrations/0002_comment_language.py @@ -0,0 +1,20 @@ +# Generated by Django 2.2.4 on 2019-10-10 11:46 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('translation', '0003_auto_20190901_1032'), + ('comment', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='comment', + name='language', + field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='translation.Language', verbose_name='Locale'), + ), + ] diff --git a/apps/comment/migrations/0003_auto_20191015_0704.py b/apps/comment/migrations/0003_auto_20191015_0704.py new file mode 100644 index 00000000..09296253 --- /dev/null +++ b/apps/comment/migrations/0003_auto_20191015_0704.py @@ -0,0 +1,24 @@ +# Generated by Django 2.2.4 on 2019-10-15 07:04 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('location', '0012_data_migrate'), + ('comment', '0002_comment_language'), + ] + + operations = [ + migrations.RemoveField( + model_name='comment', + name='language', + ), + migrations.AddField( + model_name='comment', + name='country', + field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='location.Country', verbose_name='Country'), + ), + ] diff --git a/apps/comment/models.py b/apps/comment/models.py index fe781d4d..55c7802e 100644 --- a/apps/comment/models.py +++ b/apps/comment/models.py @@ -6,6 +6,8 @@ from django.utils.translation import gettext_lazy as _ from account.models import User from utils.models import ProjectBaseMixin from utils.querysets import ContentTypeQuerySetMixin +from translation.models import Language +from location.models import Country class CommentQuerySet(ContentTypeQuerySetMixin): @@ -41,6 +43,8 @@ class Comment(ProjectBaseMixin): content_object = generic.GenericForeignKey('content_type', 'object_id') objects = CommentQuerySet.as_manager() + country = models.ForeignKey(Country, verbose_name=_('Country'), + on_delete=models.SET_NULL, null=True) class Meta: """Meta class""" diff --git a/apps/comment/serializers/back.py b/apps/comment/serializers/back.py new file mode 100644 index 00000000..d0cd47c8 --- /dev/null +++ b/apps/comment/serializers/back.py @@ -0,0 +1,9 @@ +"""Comment app common serializers.""" +from comment import models +from rest_framework import serializers + + +class CommentBaseSerializer(serializers.ModelSerializer): + class Meta: + model = models.Comment + fields = ('id', 'text', 'mark', 'user') \ No newline at end of file diff --git a/apps/comment/tests.py b/apps/comment/tests.py index a39b155a..9b060f4e 100644 --- a/apps/comment/tests.py +++ b/apps/comment/tests.py @@ -1 +1,107 @@ -# Create your tests here. +from utils.tests.tests_permissions import BasePermissionTests +from rest_framework import status +from authorization.tests.tests_authorization import get_tokens_for_user +from django.urls import reverse +from django.contrib.contenttypes.models import ContentType +from http.cookies import SimpleCookie +from account.models import Role, User, UserRole +from comment.models import Comment + + +class CommentModeratorPermissionTests(BasePermissionTests): + def setUp(self): + super().setUp() + + self.role = Role.objects.create( + role=2, + country=self.country_ru + ) + self.role.save() + + self.moderator = User.objects.create_user(username='moderator', + email='moderator@mail.com', + password='passwordmoderator') + + self.userRole = UserRole.objects.create( + user=self.moderator, + role=self.role + ) + self.userRole.save() + + content_type = ContentType.objects.get(app_label='location', model='country') + + self.user_test = get_tokens_for_user() + self.comment = Comment.objects.create(text='Test comment', mark=1, + user=self.user_test["user"], + object_id= self.country_ru.pk, + content_type_id=content_type.id, + country=self.country_ru + ) + self.comment.save() + self.url = reverse('back:comment:comment-crud', kwargs={"id": self.comment.id}) + + + def test_put_moderator(self): + tokens = User.create_jwt_tokens(self.moderator) + self.client.cookies = SimpleCookie( + {'access_token': tokens.get('access_token'), + 'refresh_token': tokens.get('access_token')}) + + data = { + "id": self.comment.id, + "text": "test text moderator", + "mark": 1, + "user": self.moderator.id + } + + response = self.client.put(self.url, data=data, format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_get(self): + response = self.client.get(self.url, format='json') + self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) + + def test_put_other_user(self): + other_user = User.objects.create_user(username='test', + email='test@mail.com', + password='passwordtest') + + tokens = User.create_jwt_tokens(other_user) + + self.client.cookies = SimpleCookie( + {'access_token': tokens.get('access_token'), + 'refresh_token': tokens.get('access_token')}) + + data = { + "id": self.comment.id, + "text": "test text moderator", + "mark": 1, + "user": other_user.id + } + + response = self.client.put(self.url, data=data, format='json') + self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) + + def test_put_super_user(self): + super_user = User.objects.create_user(username='super', + email='super@mail.com', + password='passwordtestsuper', + is_superuser=True) + + tokens = User.create_jwt_tokens(super_user) + + self.client.cookies = SimpleCookie( + {'access_token': tokens.get('access_token'), + 'refresh_token': tokens.get('access_token')}) + + data = { + "id": self.comment.id, + "text": "test text moderator", + "mark": 1, + "user": super_user.id + } + + response = self.client.put(self.url, data=data, format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + diff --git a/apps/comment/urls/back.py b/apps/comment/urls/back.py new file mode 100644 index 00000000..214eab48 --- /dev/null +++ b/apps/comment/urls/back.py @@ -0,0 +1,11 @@ +"""Back comment URLs""" +from django.urls import path + +from comment.views import back as views + +app_name = 'comment' + +urlpatterns = [ + path('', views.CommentLstView.as_view(), name='comment-list-create'), + path('/', views.CommentRUDView.as_view(), name='comment-crud'), +] diff --git a/apps/comment/views/back.py b/apps/comment/views/back.py new file mode 100644 index 00000000..2895fdbe --- /dev/null +++ b/apps/comment/views/back.py @@ -0,0 +1,19 @@ +from rest_framework import generics, permissions +from comment.serializers import back as serializers +from comment import models +from utils.permissions import IsCommentModerator, IsCountryAdmin + + +class CommentLstView(generics.ListCreateAPIView): + """Comment list create view.""" + serializer_class = serializers.CommentBaseSerializer + queryset = models.Comment.objects.all() + permission_classes = [permissions.IsAuthenticatedOrReadOnly,] + + +class CommentRUDView(generics.RetrieveUpdateDestroyAPIView): + """Comment RUD view.""" + serializer_class = serializers.CommentBaseSerializer + queryset = models.Comment.objects.all() + permission_classes = [IsCountryAdmin|IsCommentModerator] + lookup_field = 'id' diff --git a/apps/establishment/admin.py b/apps/establishment/admin.py index f95dd5c8..50c21b90 100644 --- a/apps/establishment/admin.py +++ b/apps/establishment/admin.py @@ -5,7 +5,7 @@ from django.utils.translation import gettext_lazy as _ from comment.models import Comment from establishment import models -from main.models import Award, MetaDataContent +from main.models import Award from review import models as review_models @@ -24,11 +24,6 @@ class AwardInline(GenericTabularInline): extra = 0 -class MetaDataContentInline(GenericTabularInline): - model = MetaDataContent - extra = 0 - - class ContactPhoneInline(admin.TabularInline): """Contact phone inline admin.""" model = models.ContactPhone @@ -56,8 +51,7 @@ class EstablishmentAdmin(admin.ModelAdmin): """Establishment admin.""" list_display = ['id', '__str__', 'image_tag', ] inlines = [ - AwardInline, MetaDataContentInline, - ContactPhoneInline, ContactEmailInline, + AwardInline, ContactPhoneInline, ContactEmailInline, ReviewInline, CommentInline] @@ -84,4 +78,4 @@ class MenuAdmin(admin.ModelAdmin): """Get user's short name.""" return obj.category_translated - category_translated.short_description = _('category') \ No newline at end of file + category_translated.short_description = _('category') diff --git a/apps/establishment/filters.py b/apps/establishment/filters.py index 51b207dc..20ece644 100644 --- a/apps/establishment/filters.py +++ b/apps/establishment/filters.py @@ -10,6 +10,10 @@ class EstablishmentFilter(filters.FilterSet): tag_id = filters.NumberFilter(field_name='tags__metadata__id',) award_id = filters.NumberFilter(field_name='awards__id',) search = filters.CharFilter(method='search_text') + est_type = filters.ChoiceFilter(choices=models.EstablishmentType.INDEX_NAME_TYPES, + method='by_type') + est_subtype = filters.ChoiceFilter(choices=models.EstablishmentSubType.INDEX_NAME_TYPES, + method='by_subtype') class Meta: """Meta class.""" @@ -19,6 +23,8 @@ class EstablishmentFilter(filters.FilterSet): 'tag_id', 'award_id', 'search', + 'est_type', + 'est_subtype', ) def search_text(self, queryset, name, value): @@ -26,3 +32,23 @@ class EstablishmentFilter(filters.FilterSet): if value not in EMPTY_VALUES: return queryset.search(value, locale=self.request.locale) return queryset + + def by_type(self, queryset, name, value): + return queryset.by_type(value) + + def by_subtype(self, queryset, name, value): + return queryset.by_subtype(value) + + +class EstablishmentTypeTagFilter(filters.FilterSet): + """Establishment tag filter set.""" + + type_id = filters.NumberFilter(field_name='id') + + class Meta: + """Meta class.""" + + model = models.EstablishmentType + fields = ( + 'type_id', + ) diff --git a/apps/establishment/migrations/0020_auto_20190916_1532.py b/apps/establishment/migrations/0020_auto_20190916_1532.py new file mode 100644 index 00000000..d22fad07 --- /dev/null +++ b/apps/establishment/migrations/0020_auto_20190916_1532.py @@ -0,0 +1,23 @@ +# Generated by Django 2.2.4 on 2019-09-16 15:32 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0019_establishment_is_publish'), + ] + + operations = [ + migrations.AddField( + model_name='establishment', + name='guestonline_id', + field=models.PositiveIntegerField(blank=True, default=None, null=True, verbose_name='guestonline id'), + ), + migrations.AddField( + model_name='establishment', + name='lastable_id', + field=models.PositiveIntegerField(blank=True, default=None, null=True, verbose_name='lastable id'), + ), + ] diff --git a/apps/establishment/migrations/0024_establishment_collections.py b/apps/establishment/migrations/0024_establishment_collections.py new file mode 100644 index 00000000..b801ce3d --- /dev/null +++ b/apps/establishment/migrations/0024_establishment_collections.py @@ -0,0 +1,19 @@ +# Generated by Django 2.2.4 on 2019-09-20 08:55 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('collection', '0009_delete_collectionitem'), + ('establishment', '0023_merge_20190919_1136'), + ] + + operations = [ + migrations.AddField( + model_name='establishment', + name='collections', + field=models.ManyToManyField(related_name='establishments', to='collection.Collection', verbose_name='Collections'), + ), + ] diff --git a/apps/establishment/migrations/0025_merge_20190920_1012.py b/apps/establishment/migrations/0025_merge_20190920_1012.py new file mode 100644 index 00000000..b8821b76 --- /dev/null +++ b/apps/establishment/migrations/0025_merge_20190920_1012.py @@ -0,0 +1,14 @@ +# Generated by Django 2.2.4 on 2019-09-20 10:12 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0024_establishment_collections'), + ('establishment', '0024_merge_20190919_1456'), + ] + + operations = [ + ] diff --git a/apps/establishment/migrations/0026_establishment_preview_image_url.py b/apps/establishment/migrations/0026_establishment_preview_image_url.py new file mode 100644 index 00000000..c398737e --- /dev/null +++ b/apps/establishment/migrations/0026_establishment_preview_image_url.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-09-20 10:16 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0025_merge_20190920_1012'), + ] + + operations = [ + migrations.AddField( + model_name='establishment', + name='preview_image_url', + field=models.URLField(blank=True, default=None, null=True, verbose_name='Preview image URL path'), + ), + ] diff --git a/apps/establishment/migrations/0027_auto_20190920_1120.py b/apps/establishment/migrations/0027_auto_20190920_1120.py new file mode 100644 index 00000000..974b8093 --- /dev/null +++ b/apps/establishment/migrations/0027_auto_20190920_1120.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-09-20 11:20 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0026_establishment_preview_image_url'), + ] + + operations = [ + migrations.AlterField( + model_name='establishment', + name='collections', + field=models.ManyToManyField(blank=True, default=None, null=True, related_name='establishments', to='collection.Collection', verbose_name='Collections'), + ), + ] diff --git a/apps/establishment/migrations/0028_auto_20190920_1205.py b/apps/establishment/migrations/0028_auto_20190920_1205.py new file mode 100644 index 00000000..abdd4d7f --- /dev/null +++ b/apps/establishment/migrations/0028_auto_20190920_1205.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-09-20 12:05 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0027_auto_20190920_1120'), + ] + + operations = [ + migrations.AlterField( + model_name='establishment', + name='collections', + field=models.ManyToManyField(blank=True, default=None, related_name='establishments', to='collection.Collection', verbose_name='Collections'), + ), + ] diff --git a/apps/establishment/migrations/0029_establishment_name_transliterated.py b/apps/establishment/migrations/0029_establishment_name_transliterated.py new file mode 100644 index 00000000..54fb4ea0 --- /dev/null +++ b/apps/establishment/migrations/0029_establishment_name_transliterated.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-09-23 09:20 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0028_auto_20190920_1205'), + ] + + operations = [ + migrations.AddField( + model_name='establishment', + name='name_transliterated', + field=models.CharField(default='', max_length=255, verbose_name='Transliterated name'), + ), + ] diff --git a/apps/establishment/migrations/0030_auto_20190923_1340.py b/apps/establishment/migrations/0030_auto_20190923_1340.py new file mode 100644 index 00000000..9599b200 --- /dev/null +++ b/apps/establishment/migrations/0030_auto_20190923_1340.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-09-23 13:40 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0029_establishment_name_transliterated'), + ] + + operations = [ + migrations.RenameField( + model_name='establishment', + old_name='name_transliterated', + new_name='name_translated', + ), + ] diff --git a/apps/establishment/migrations/0031_establishment_slug.py b/apps/establishment/migrations/0031_establishment_slug.py new file mode 100644 index 00000000..2ff68380 --- /dev/null +++ b/apps/establishment/migrations/0031_establishment_slug.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-09-24 08:06 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0030_auto_20190923_1340'), + ] + + operations = [ + migrations.AddField( + model_name='establishment', + name='slug', + field=models.SlugField(null=True, unique=True, verbose_name='Establishment slug'), + ), + ] diff --git a/apps/establishment/migrations/0032_establishmenttag_establishmenttypetagcategory.py b/apps/establishment/migrations/0032_establishmenttag_establishmenttypetagcategory.py new file mode 100644 index 00000000..ec9966d8 --- /dev/null +++ b/apps/establishment/migrations/0032_establishmenttag_establishmenttypetagcategory.py @@ -0,0 +1,35 @@ +# Generated by Django 2.2.4 on 2019-10-09 07:15 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0031_establishment_slug'), + ] + + operations = [ + migrations.CreateModel( + name='EstablishmentTag', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ], + options={ + 'verbose_name': 'establishment tag', + 'verbose_name_plural': 'establishment tags', + }, + ), + migrations.CreateModel( + name='EstablishmentTypeTagCategory', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('establishment_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tag_categories', to='establishment.EstablishmentType', verbose_name='establishment type')), + ], + options={ + 'verbose_name': 'establishment type tag categories', + 'verbose_name_plural': 'establishment type tag categories', + }, + ), + ] diff --git a/apps/establishment/migrations/0032_merge_20191001_1530.py b/apps/establishment/migrations/0032_merge_20191001_1530.py new file mode 100644 index 00000000..d0448141 --- /dev/null +++ b/apps/establishment/migrations/0032_merge_20191001_1530.py @@ -0,0 +1,14 @@ +# Generated by Django 2.2.4 on 2019-10-01 15:30 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0020_auto_20190916_1532'), + ('establishment', '0031_establishment_slug'), + ] + + operations = [ + ] diff --git a/apps/establishment/migrations/0033_auto_20191003_0943_squashed_0034_auto_20191003_1036.py b/apps/establishment/migrations/0033_auto_20191003_0943_squashed_0034_auto_20191003_1036.py new file mode 100644 index 00000000..48a0fa8d --- /dev/null +++ b/apps/establishment/migrations/0033_auto_20191003_0943_squashed_0034_auto_20191003_1036.py @@ -0,0 +1,24 @@ +# Generated by Django 2.2.4 on 2019-10-03 10:40 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + replaces = [('establishment', '0033_auto_20191003_0943'), ('establishment', '0034_auto_20191003_1036')] + + dependencies = [ + ('establishment', '0032_merge_20191001_1530'), + ] + + operations = [ + migrations.RemoveField( + model_name='establishment', + name='lastable_id', + ), + migrations.AddField( + model_name='establishment', + name='lastable_id', + field=models.TextField(blank=True, default=None, null=True, unique=True, verbose_name='lastable id'), + ), + ] diff --git a/apps/establishment/migrations/0033_auto_20191009_0715.py b/apps/establishment/migrations/0033_auto_20191009_0715.py new file mode 100644 index 00000000..5df367d6 --- /dev/null +++ b/apps/establishment/migrations/0033_auto_20191009_0715.py @@ -0,0 +1,30 @@ +# Generated by Django 2.2.4 on 2019-10-09 07:15 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('tag', '0001_initial'), + ('establishment', '0032_establishmenttag_establishmenttypetagcategory'), + ] + + operations = [ + migrations.AddField( + model_name='establishmenttypetagcategory', + name='tag_category', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='est_type_tag_categories', to='tag.TagCategory', verbose_name='tag category'), + ), + migrations.AddField( + model_name='establishmenttag', + name='establishment', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tags', to='establishment.Establishment', verbose_name='establishment'), + ), + migrations.AddField( + model_name='establishmenttag', + name='tag', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tags', to='tag.Tag', verbose_name='tag'), + ), + ] diff --git a/apps/establishment/migrations/0034_merge_20191009_1457.py b/apps/establishment/migrations/0034_merge_20191009_1457.py new file mode 100644 index 00000000..945860f7 --- /dev/null +++ b/apps/establishment/migrations/0034_merge_20191009_1457.py @@ -0,0 +1,14 @@ +# Generated by Django 2.2.4 on 2019-10-09 14:57 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0033_auto_20191009_0715'), + ('establishment', '0033_auto_20191003_0943_squashed_0034_auto_20191003_1036'), + ] + + operations = [ + ] diff --git a/apps/establishment/migrations/0035_establishmentsubtypetagcategory.py b/apps/establishment/migrations/0035_establishmentsubtypetagcategory.py new file mode 100644 index 00000000..6a85fca7 --- /dev/null +++ b/apps/establishment/migrations/0035_establishmentsubtypetagcategory.py @@ -0,0 +1,27 @@ +# Generated by Django 2.2.4 on 2019-10-11 10:47 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('tag', '0002_auto_20191009_1408'), + ('establishment', '0034_merge_20191009_1457'), + ] + + operations = [ + migrations.CreateModel( + name='EstablishmentSubTypeTagCategory', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('establishment_subtype', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tag_categories', to='establishment.EstablishmentSubType', verbose_name='establishment subtype')), + ('tag_category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='est_subtype_tag_categories', to='tag.TagCategory', verbose_name='tag category')), + ], + options={ + 'verbose_name': 'establishment subtype tag categories', + 'verbose_name_plural': 'establishment subtype tag categories', + }, + ), + ] diff --git a/apps/establishment/migrations/0036_auto_20191011_1356.py b/apps/establishment/migrations/0036_auto_20191011_1356.py new file mode 100644 index 00000000..c2eb2e4e --- /dev/null +++ b/apps/establishment/migrations/0036_auto_20191011_1356.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-10-11 13:56 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0035_establishmentsubtypetagcategory'), + ] + + operations = [ + migrations.AlterField( + model_name='establishment', + name='establishment_subtypes', + field=models.ManyToManyField(blank=True, related_name='subtype_establishment', to='establishment.EstablishmentSubType', verbose_name='subtype'), + ), + ] diff --git a/apps/establishment/migrations/0037_auto_20191015_1404.py b/apps/establishment/migrations/0037_auto_20191015_1404.py new file mode 100644 index 00000000..971970e2 --- /dev/null +++ b/apps/establishment/migrations/0037_auto_20191015_1404.py @@ -0,0 +1,54 @@ +# Generated by Django 2.2.4 on 2019-10-15 14:04 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('tag', '0002_auto_20191009_1408'), + ('establishment', '0036_auto_20191011_1356'), + ] + + operations = [ + migrations.RemoveField( + model_name='establishmenttag', + name='establishment', + ), + migrations.RemoveField( + model_name='establishmenttag', + name='tag', + ), + migrations.RemoveField( + model_name='establishmenttypetagcategory', + name='establishment_type', + ), + migrations.RemoveField( + model_name='establishmenttypetagcategory', + name='tag_category', + ), + migrations.AddField( + model_name='establishment', + name='tags', + field=models.ManyToManyField(related_name='establishments', to='tag.Tag', verbose_name='Tag'), + ), + migrations.AddField( + model_name='establishmentsubtype', + name='tag_categories', + field=models.ManyToManyField(related_name='establishment_subtypes', to='tag.TagCategory', verbose_name='Tag'), + ), + migrations.AddField( + model_name='establishmenttype', + name='tag_categories', + field=models.ManyToManyField(related_name='establishment_types', to='tag.TagCategory', verbose_name='Tag'), + ), + migrations.DeleteModel( + name='EstablishmentSubTypeTagCategory', + ), + migrations.DeleteModel( + name='EstablishmentTag', + ), + migrations.DeleteModel( + name='EstablishmentTypeTagCategory', + ), + ] diff --git a/apps/establishment/migrations/0038_establishmenttype_index_name.py b/apps/establishment/migrations/0038_establishmenttype_index_name.py new file mode 100644 index 00000000..5f9d5879 --- /dev/null +++ b/apps/establishment/migrations/0038_establishmenttype_index_name.py @@ -0,0 +1,35 @@ +# Generated by Django 2.2.4 on 2019-10-16 11:33 + +from django.db import migrations, models + + +def fill_establishment_type(apps, schema_editor): + # We can't import the Person model directly as it may be a newer + # version than this migration expects. We use the historical version. + EstablishmentType = apps.get_model('establishment', 'EstablishmentType') + for n, et in enumerate(EstablishmentType.objects.all()): + et.index_name = f'Type {n}' + et.save() + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0037_auto_20191015_1404'), + ] + + operations = [ + migrations.AddField( + model_name='establishmenttype', + name='index_name', + field=models.CharField(blank=True, db_index=True, max_length=50, null=True, unique=True, default=None, verbose_name='Index name'), + ), + migrations.RunPython(fill_establishment_type, migrations.RunPython.noop), + migrations.AlterField( + model_name='establishmenttype', + name='index_name', + field=models.CharField(choices=[('restaurant', 'Restaurant'), ('artisan', 'Artisan'), + ('producer', 'Producer')], db_index=True, max_length=50, + unique=True, verbose_name='Index name'), + ), + ] diff --git a/apps/establishment/migrations/0039_establishmentsubtype_index_name.py b/apps/establishment/migrations/0039_establishmentsubtype_index_name.py new file mode 100644 index 00000000..a29b1ae0 --- /dev/null +++ b/apps/establishment/migrations/0039_establishmentsubtype_index_name.py @@ -0,0 +1,35 @@ +# Generated by Django 2.2.4 on 2019-10-18 13:47 + +from django.db import migrations, models + + +def fill_establishment_subtype(apps, schema_editor): + # We can't import the Person model directly as it may be a newer + # version than this migration expects. We use the historical version. + EstablishmentSubType = apps.get_model('establishment', 'EstablishmentSubType') + for n, et in enumerate(EstablishmentSubType.objects.all()): + et.index_name = f'Type {n}' + et.save() + + +class Migration(migrations.Migration): + + dependencies = [ + ('establishment', '0038_establishmenttype_index_name'), + ] + + operations = [ + migrations.AddField( + model_name='establishmentsubtype', + name='index_name', + field=models.CharField(blank=True, db_index=True, max_length=50, null=True, unique=True, default=None, verbose_name='Index name'), + ), + migrations.RunPython(fill_establishment_subtype, migrations.RunPython.noop), + migrations.AlterField( + model_name='establishmentsubtype', + name='index_name', + field=models.CharField(choices=[('winery', 'Winery'), ], db_index=True, max_length=50, + unique=True, verbose_name='Index name'), + ), + + ] diff --git a/apps/establishment/models.py b/apps/establishment/models.py index 298b32ff..4f7a73a5 100644 --- a/apps/establishment/models.py +++ b/apps/establishment/models.py @@ -1,20 +1,23 @@ """Establishment models.""" from functools import reduce -from django.contrib.gis.db.models.functions import Distance -from django.contrib.gis.measure import Distance as DistanceMeasure -from django.contrib.gis.geos import Point +from django.conf import settings from django.contrib.contenttypes import fields as generic +from django.contrib.gis.db.models.functions import Distance +from django.contrib.gis.geos import Point +from django.contrib.gis.measure import Distance as DistanceMeasure from django.core.exceptions import ValidationError from django.db import models +from django.db.models import When, Case, F, ExpressionWrapper, Subquery, Q from django.utils import timezone from django.utils.translation import gettext_lazy as _ from phonenumber_field.modelfields import PhoneNumberField -from location.models import Address from collection.models import Collection +from location.models import Address +from main.models import Award from review.models import Review -from utils.models import (ProjectBaseMixin, ImageMixin, TJSONField, URLImageMixin, +from utils.models import (ProjectBaseMixin, TJSONField, URLImageMixin, TranslatedFieldsMixin, BaseAttributes) @@ -24,9 +27,26 @@ class EstablishmentType(TranslatedFieldsMixin, ProjectBaseMixin): STR_FIELD_NAME = 'name' + # INDEX NAME CHOICES + RESTAURANT = 'restaurant' + ARTISAN = 'artisan' + PRODUCER = 'producer' + + INDEX_NAME_TYPES = ( + (RESTAURANT, _('Restaurant')), + (ARTISAN, _('Artisan')), + (PRODUCER, _('Producer')), + ) + name = TJSONField(blank=True, null=True, default=None, verbose_name=_('Description'), help_text='{"en-GB":"some text"}') + index_name = models.CharField(max_length=50, choices=INDEX_NAME_TYPES, + unique=True, db_index=True, + verbose_name=_('Index name')) use_subtypes = models.BooleanField(_('Use subtypes'), default=True) + tag_categories = models.ManyToManyField('tag.TagCategory', + related_name='establishment_types', + verbose_name=_('Tag')) class Meta: """Meta class.""" @@ -48,11 +68,24 @@ class EstablishmentSubTypeManager(models.Manager): class EstablishmentSubType(ProjectBaseMixin, TranslatedFieldsMixin): """Establishment type model.""" + # INDEX NAME CHOICES + WINERY = 'winery' + + INDEX_NAME_TYPES = ( + (WINERY, _('Winery')), + ) + name = TJSONField(blank=True, null=True, default=None, verbose_name=_('Description'), help_text='{"en-GB":"some text"}') + index_name = models.CharField(max_length=50, choices=INDEX_NAME_TYPES, + unique=True, db_index=True, + verbose_name=_('Index name')) establishment_type = models.ForeignKey(EstablishmentType, on_delete=models.CASCADE, verbose_name=_('Type')) + tag_categories = models.ManyToManyField('tag.TagCategory', + related_name='establishment_subtypes', + verbose_name=_('Tag')) objects = EstablishmentSubTypeManager() @@ -70,6 +103,20 @@ class EstablishmentSubType(ProjectBaseMixin, TranslatedFieldsMixin): class EstablishmentQuerySet(models.QuerySet): """Extended queryset for Establishment model.""" + def with_base_related(self): + """Return qs with related objects.""" + return self.select_related('address', 'establishment_type').\ + prefetch_related('tags') + + def with_extended_related(self): + return self.select_related('establishment_type').\ + prefetch_related('establishment_subtypes', 'awards', 'schedule', + 'phones').\ + prefetch_actual_employees() + + def with_type_related(self): + return self.prefetch_related('establishment_subtypes') + def search(self, value, locale=None): """Search text in JSON fields.""" if locale is not None: @@ -81,6 +128,16 @@ class EstablishmentQuerySet(models.QuerySet): else: return self.none() + # def es_search(self, value, locale=None): + # """Search text via ElasticSearch.""" + # from search_indexes.documents import EstablishmentDocument + # search = EstablishmentDocument.search().filter( + # Elastic_Q('match', name=value) | + # Elastic_Q('match', **{f'description.{locale}': value}) + # ).execute() + # ids = [result.meta.id for result in search] + # return self.filter(id__in=ids) + def by_country_code(self, code): """Return establishments by country code""" return self.filter(address__city__country__code=code) @@ -91,29 +148,20 @@ class EstablishmentQuerySet(models.QuerySet): """ return self.filter(is_publish=True) - def annotate_distance(self, point: Point): + def has_published_reviews(self): + """ + Return QuerySet establishments with published reviews. + """ + return self.filter(reviews__status=Review.READY,) + + def annotate_distance(self, point: Point = None): """ Return QuerySet with annotated field - distance Description: """ - return self.annotate(distance=models.Value( - DistanceMeasure(Distance('address__coordinates', point, srid=4236)).m, - output_field=models.FloatField())) - - def annotate_distance_mark(self): - """ - Return QuerySet with annotated field - distance_mark. - Required fields: distance. - Description: - If the radius of the establishments in QuerySet does not exceed 500 meters, - then distance_mark is set to 0.6, otherwise 0. - """ - return self.annotate(distance_mark=models.Case( - models.When(distance__lte=500, - then=0.6), - default=0, - output_field=models.FloatField())) + return self.annotate(distance=Distance('address__coordinates', point, + srid=settings.GEO_DEFAULT_SRID)) def annotate_intermediate_public_mark(self): """ @@ -122,72 +170,66 @@ class EstablishmentQuerySet(models.QuerySet): If establishments in collection POP and its mark is null, then intermediate_mark is set to 10; """ - return self.annotate(intermediate_public_mark=models.Case( - models.When( - collections__collection__collection_type=Collection.POP, + return self.annotate(intermediate_public_mark=Case( + When( + collections__collection_type=Collection.POP, public_mark__isnull=True, - then=10 + then=settings.DEFAULT_ESTABLISHMENT_PUBLIC_MARK ), default='public_mark', output_field=models.FloatField())) - def annotate_additional_mark(self, public_mark: float): + def annotate_mark_similarity(self, mark): """ - Return QuerySet with annotated field - additional_mark. - Required fields: intermediate_public_mark + Return a QuerySet with annotated field - mark_similarity Description: - IF - establishments public_mark + 3 > compared establishment public_mark - OR - establishments public_mark - 3 > compared establishment public_mark, - THEN - additional_mark is set to 0.4, - ELSE - set to 0. + Similarity mark determined by comparison with compared establishment mark """ - return self.annotate(additional_mark=models.Case( - models.When( - models.Q(intermediate_public_mark__lte=public_mark + 3) | - models.Q(intermediate_public_mark__lte=public_mark - 3), - then=0.4), - default=0, - output_field=models.FloatField())) + return self.annotate(mark_similarity=ExpressionWrapper( + mark - F('intermediate_public_mark'), + output_field=models.FloatField() + )) - def annotate_total_mark(self): - """ - Return QuerySet with annotated field - total_mark. - Required fields: distance_mark, additional_mark. - Fields - Description: - Annotated field is obtained by formula: - (distance + additional marks) * intermediate_public_mark. - """ - return self.annotate( - total_mark=(models.F('distance_mark') + models.F('additional_mark')) * - models.F('intermediate_public_mark')) - - def similar(self, establishment_pk: int): + def similar(self, establishment_slug: str): """ Return QuerySet with objects that similar to Establishment. - :param establishment_pk: integer + :param establishment_slug: str Establishment slug """ - establishment_qs = Establishment.objects.filter(pk=establishment_pk) + establishment_qs = self.filter(slug=establishment_slug, + public_mark__isnull=False) if establishment_qs.exists(): establishment = establishment_qs.first() - return self.exclude(pk=establishment_pk) \ - .filter(is_publish=True, - image__isnull=False, - reviews__isnull=False, - reviews__status=Review.READY, - public_mark__gte=10) \ - .annotate_distance(point=establishment.address.coordinates) \ - .annotate_distance_mark() \ + subquery_filter_by_distance = Subquery( + self.exclude(slug=establishment_slug) + .filter(image_url__isnull=False, public_mark__gte=10) + .has_published_reviews() + .annotate_distance(point=establishment.location) + .order_by('distance')[:settings.LIMITING_QUERY_NUMBER] + .values('id') + ) + return self.filter(id__in=subquery_filter_by_distance) \ .annotate_intermediate_public_mark() \ - .annotate_additional_mark(public_mark=establishment.public_mark) \ - .annotate_total_mark() + .annotate_mark_similarity(mark=establishment.public_mark) \ + .order_by('mark_similarity') \ + .distinct('mark_similarity', 'id') else: return self.none() + def last_reviewed(self, point: Point): + """ + Return QuerySet with last reviewed establishments. + :param point: location Point object, needs to ordering + """ + subquery_filter_by_distance = Subquery( + self.filter(image_url__isnull=False, public_mark__gte=10) + .has_published_reviews() + .annotate_distance(point=point) + .order_by('distance')[:settings.LIMITING_QUERY_NUMBER] + .values('id') + ) + return self.filter(id__in=subquery_filter_by_distance) \ + .order_by('-reviews__published_at') + def prefetch_actual_employees(self): """Prefetch actual employees.""" return self.prefetch_related( @@ -201,10 +243,10 @@ class EstablishmentQuerySet(models.QuerySet): favorite_establishments = [] if user.is_authenticated: favorite_establishments = user.favorites.by_content_type(app_label='establishment', - model='establishment')\ + model='establishment') \ .values_list('object_id', flat=True) - return self.annotate(in_favorites=models.Case( - models.When( + return self.annotate(in_favorites=Case( + When( id__in=favorite_establishments, then=True), default=False, @@ -219,16 +261,41 @@ class EstablishmentQuerySet(models.QuerySet): :return: all establishments within the specified radius of specified point :param unit: length unit e.g. m, km. Default is 'm'. """ - - from django.contrib.gis.measure import Distance kwargs = {unit: radius} - return self.filter(address__coordinates__distance_lte=(center, Distance(**kwargs))) + return self.filter(address__coordinates__distance_lte=(center, DistanceMeasure(**kwargs))) + + def artisans(self): + """Return artisans.""" + return self.filter(establishment_type__index_name=EstablishmentType.ARTISAN) + + def producers(self): + """Return producers.""" + return self.filter(establishment_type__index_name=EstablishmentType.PRODUCER) + + def restaurants(self): + """Return restaurants.""" + return self.filter(establishment_type__index_name=EstablishmentType.RESTAURANT) + + def wineries(self): + """Return wineries.""" + return self.producers().filter( + establishment_subtypes__index_name=EstablishmentSubType.WINERY) + + def by_type(self, value): + """Return QuerySet with type by value.""" + return self.filter(establishment_type__index_name=value) + + def by_subtype(self, value): + """Return QuerySet with subtype by value.""" + return self.filter(establishment_subtypes__index_name=value) class Establishment(ProjectBaseMixin, URLImageMixin, TranslatedFieldsMixin): """Establishment model.""" name = models.CharField(_('name'), max_length=255, default='') + name_translated = models.CharField(_('Transliterated name'), + max_length=255, default='') description = TJSONField(blank=True, null=True, default=None, verbose_name=_('description'), help_text='{"en-GB":"some text"}') @@ -243,6 +310,7 @@ class Establishment(ProjectBaseMixin, URLImageMixin, TranslatedFieldsMixin): on_delete=models.PROTECT, verbose_name=_('type')) establishment_subtypes = models.ManyToManyField(EstablishmentSubType, + blank=True, related_name='subtype_establishment', verbose_name=_('subtype')) address = models.ForeignKey(Address, blank=True, null=True, default=None, @@ -259,6 +327,10 @@ class Establishment(ProjectBaseMixin, URLImageMixin, TranslatedFieldsMixin): verbose_name=_('Twitter URL')) lafourchette = models.URLField(blank=True, null=True, default=None, verbose_name=_('Lafourchette URL')) + guestonline_id = models.PositiveIntegerField(blank=True, verbose_name=_('guestonline id'), + null=True, default=None,) + lastable_id = models.TextField(blank=True, verbose_name=_('lastable id'), unique=True, + null=True, default=None,) booking = models.URLField(blank=True, null=True, default=None, verbose_name=_('Booking URL')) is_publish = models.BooleanField(default=False, verbose_name=_('Publish status')) @@ -269,13 +341,26 @@ class Establishment(ProjectBaseMixin, URLImageMixin, TranslatedFieldsMixin): # help_text=_('Holidays closing date from')) # holidays_to = models.DateTimeField(verbose_name=_('Holidays to'), # help_text=_('Holidays closing date to')) - awards = generic.GenericRelation(to='main.Award') - tags = generic.GenericRelation(to='main.MetaDataContent') - reviews = generic.GenericRelation(to='review.Review') - comments = generic.GenericRelation(to='comment.Comment') transportation = models.TextField(blank=True, null=True, default=None, verbose_name=_('Transportation')) - collections = generic.GenericRelation(to='collection.CollectionItem') + collections = models.ManyToManyField(to='collection.Collection', + related_name='establishments', + blank=True, default=None, + verbose_name=_('Collections')) + preview_image_url = models.URLField(verbose_name=_('Preview image URL path'), + blank=True, null=True, default=None) + slug = models.SlugField(unique=True, max_length=50, null=True, + verbose_name=_('Establishment slug'), editable=True) + + awards = generic.GenericRelation(to='main.Award', related_query_name='establishment') + # todo: remove after data merge + # tags = generic.GenericRelation(to='main.MetaDataContent') + tags = models.ManyToManyField('tag.Tag', related_name='establishments', + verbose_name=_('Tag')) + old_tags = generic.GenericRelation(to='main.MetaDataContent') + reviews = generic.GenericRelation(to='review.Review') + comments = generic.GenericRelation(to='comment.Comment') + favorites = generic.GenericRelation(to='favorites.Favorites') objects = EstablishmentQuerySet.as_manager() @@ -303,12 +388,12 @@ class Establishment(ProjectBaseMixin, URLImageMixin, TranslatedFieldsMixin): return country.low_price, country.high_price # todo: make via prefetch - @property - def subtypes(self): - return EstablishmentSubType.objects.filter( - subtype_establishment=self, - establishment_type=self.establishment_type, - establishment_type__use_subtypes=True) + # @property + # def subtypes(self): + # return EstablishmentSubType.objects.filter( + # subtype_establishment=self, + # establishment_type=self.establishment_type, + # establishment_type__use_subtypes=True) def set_establishment_type(self, establishment_type): self.establishment_type = establishment_type @@ -320,6 +405,12 @@ class Establishment(ProjectBaseMixin, URLImageMixin, TranslatedFieldsMixin): raise ValidationError('Establishment type of subtype does not match') self.establishment_subtypes.add(establishment_subtype) + @property + def vintage_year(self): + last_review = self.reviews.by_status(Review.READY).last() + if last_review: + return last_review.vintage + @property def best_price_menu(self): return 150 @@ -333,6 +424,38 @@ class Establishment(ProjectBaseMixin, URLImageMixin, TranslatedFieldsMixin): return [{'id': tag.metadata.id, 'label': tag.metadata.label} for tag in self.tags.all()] + @property + def last_published_review(self): + """Return last published review""" + return self.reviews.published()\ + .order_by('-published_at').first() + + @property + def location(self): + """ + Return Point object of establishment location + """ + return self.address.coordinates + + @property + def the_most_recent_award(self): + return Award.objects.filter(Q(establishment=self) | Q(employees__establishments=self)).latest( + field_name='vintage_year') + + @property + def country_id(self): + """ + Return Country id of establishment location + """ + return self.address.country_id + + @property + def establishment_id(self): + """ + Return establishment id of establishment location + """ + return self.id + class Position(BaseAttributes, TranslatedFieldsMixin): """Position model.""" @@ -386,8 +509,8 @@ class Employee(BaseAttributes): verbose_name=_('User')) name = models.CharField(max_length=255, verbose_name=_('Last name')) establishments = models.ManyToManyField(Establishment, related_name='employees', - through=EstablishmentEmployee) - awards = generic.GenericRelation(to='main.Award') + through=EstablishmentEmployee,) + awards = generic.GenericRelation(to='main.Award', related_query_name='employees') tags = generic.GenericRelation(to='main.MetaDataContent') class Meta: @@ -428,6 +551,7 @@ class ContactEmail(models.Model): def __str__(self): return f'{self.email}' + # # class Wine(TranslatedFieldsMixin, models.Model): # """Wine model.""" @@ -466,6 +590,10 @@ class Plate(TranslatedFieldsMixin, models.Model): menu = models.ForeignKey( 'establishment.Menu', verbose_name=_('menu'), on_delete=models.CASCADE) + @property + def establishment_id(self): + return self.menu.establishment.id + class Meta: verbose_name = _('plate') verbose_name_plural = _('plates') @@ -501,3 +629,4 @@ class SocialNetwork(models.Model): def __str__(self): return self.title + diff --git a/apps/establishment/serializers/back.py b/apps/establishment/serializers/back.py index caa13742..59725710 100644 --- a/apps/establishment/serializers/back.py +++ b/apps/establishment/serializers/back.py @@ -1,13 +1,12 @@ -import json from rest_framework import serializers from establishment import models -from timetable.models import Timetable from establishment.serializers import ( EstablishmentBaseSerializer, PlateSerializer, ContactEmailsSerializer, - ContactPhonesSerializer, SocialNetworkRelatedSerializers, EstablishmentDetailSerializer -) + ContactPhonesSerializer, SocialNetworkRelatedSerializers, + EstablishmentTypeBaseSerializer) from main.models import Currency +from utils.decorators import with_base_attributes class EstablishmentListCreateSerializer(EstablishmentBaseSerializer): @@ -20,6 +19,8 @@ class EstablishmentListCreateSerializer(EstablishmentBaseSerializer): phones = ContactPhonesSerializer(read_only=True, many=True, ) emails = ContactEmailsSerializer(read_only=True, many=True, ) socials = SocialNetworkRelatedSerializers(read_only=True, many=True, ) + slug = serializers.SlugField(required=True, allow_blank=False, max_length=50) + type = EstablishmentTypeBaseSerializer(source='establishment_type', read_only=True) class Meta: model = models.Establishment @@ -34,7 +35,43 @@ class EstablishmentListCreateSerializer(EstablishmentBaseSerializer): 'type_id', 'type', 'socials', - 'image_url' + 'image_url', + 'slug', + # TODO: check in admin filters + 'is_publish', + 'guestonline_id', + 'lastable_id', + ] + + +class EstablishmentRUDSerializer(EstablishmentBaseSerializer): + """Establishment create serializer""" + + type_id = serializers.PrimaryKeyRelatedField( + source='establishment_type', + queryset=models.EstablishmentType.objects.all(), write_only=True + ) + phones = ContactPhonesSerializer(read_only=False, many=True, ) + emails = ContactEmailsSerializer(read_only=False, many=True, ) + socials = SocialNetworkRelatedSerializers(read_only=False, many=True, ) + type = EstablishmentTypeBaseSerializer(source='establishment_type') + + class Meta: + model = models.Establishment + fields = [ + 'id', + 'name', + 'website', + 'phones', + 'emails', + 'price_level', + 'toque_number', + 'type_id', + 'type', + 'socials', + 'image_url', + # TODO: check in admin filters + 'is_publish' ] @@ -52,13 +89,15 @@ class SocialNetworkSerializers(serializers.ModelSerializer): class PlatesSerializers(PlateSerializer): """Social network serializers.""" - name = serializers.JSONField() + currency_id = serializers.PrimaryKeyRelatedField( source='currency', queryset=Currency.objects.all(), write_only=True ) class Meta: + """Meta class.""" + model = models.Plate fields = PlateSerializer.Meta.fields + [ 'name', @@ -89,7 +128,10 @@ class ContactEmailBackSerializers(PlateSerializer): ] +# TODO: test decorator +@with_base_attributes class EmployeeBackSerializers(serializers.ModelSerializer): + """Social network serializers.""" class Meta: model = models.Employee @@ -97,4 +139,4 @@ class EmployeeBackSerializers(serializers.ModelSerializer): 'id', 'user', 'name' - ] \ No newline at end of file + ] diff --git a/apps/establishment/serializers/common.py b/apps/establishment/serializers/common.py index 956130d6..389d0d1c 100644 --- a/apps/establishment/serializers/common.py +++ b/apps/establishment/serializers/common.py @@ -1,16 +1,19 @@ """Establishment serializers.""" +from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from comment import models as comment_models from comment.serializers import common as comment_serializers from establishment import models from favorites.models import Favorites -from location.serializers import AddressSerializer -from main.models import MetaDataContent -from main.serializers import MetaDataContentSerializer, AwardSerializer, CurrencySerializer +from location.serializers import AddressBaseSerializer +from main.serializers import AwardSerializer, CurrencySerializer from review import models as review_models +from tag.serializers import TagBaseSerializer from timetable.serialziers import ScheduleRUDSerializer from utils import exceptions as utils_exceptions +from utils.serializers import ProjectModelSerializer +from utils.serializers import TranslatedField class ContactPhonesSerializer(serializers.ModelSerializer): @@ -42,9 +45,9 @@ class SocialNetworkRelatedSerializers(serializers.ModelSerializer): ] -class PlateSerializer(serializers.ModelSerializer): +class PlateSerializer(ProjectModelSerializer): - name_translated = serializers.CharField(allow_null=True, read_only=True) + name_translated = TranslatedField() currency = CurrencySerializer(read_only=True) class Meta: @@ -57,9 +60,8 @@ class PlateSerializer(serializers.ModelSerializer): ] -class MenuSerializers(serializers.ModelSerializer): +class MenuSerializers(ProjectModelSerializer): plates = PlateSerializer(read_only=True, many=True, source='plate_set') - category = serializers.JSONField() category_translated = serializers.CharField(read_only=True) class Meta: @@ -73,9 +75,8 @@ class MenuSerializers(serializers.ModelSerializer): ] -class MenuRUDSerializers(serializers.ModelSerializer): +class MenuRUDSerializers(ProjectModelSerializer): plates = PlateSerializer(read_only=True, many=True, source='plate_set') - category = serializers.JSONField() class Meta: model = models.Menu @@ -87,30 +88,6 @@ class MenuRUDSerializers(serializers.ModelSerializer): ] -class EstablishmentTypeSerializer(serializers.ModelSerializer): - """Serializer for EstablishmentType model.""" - - name_translated = serializers.CharField(allow_null=True) - - class Meta: - """Meta class.""" - - model = models.EstablishmentType - fields = ('id', 'name_translated') - - -class EstablishmentSubTypeSerializer(serializers.ModelSerializer): - """Serializer for EstablishmentSubType models.""" - - name_translated = serializers.CharField(allow_null=True) - - class Meta: - """Meta class.""" - - model = models.EstablishmentSubType - fields = ('id', 'name_translated') - - class ReviewSerializer(serializers.ModelSerializer): """Serializer for model Review.""" text_translated = serializers.CharField(read_only=True) @@ -123,6 +100,45 @@ class ReviewSerializer(serializers.ModelSerializer): ) +class EstablishmentTypeBaseSerializer(serializers.ModelSerializer): + """Serializer for EstablishmentType model.""" + name_translated = TranslatedField() + + class Meta: + """Meta class.""" + model = models.EstablishmentType + fields = [ + 'id', + 'name', + 'name_translated', + 'use_subtypes' + ] + extra_kwargs = { + 'name': {'write_only': True}, + 'use_subtypes': {'write_only': True}, + } + + +class EstablishmentSubTypeBaseSerializer(serializers.ModelSerializer): + """Serializer for EstablishmentSubType models.""" + + name_translated = TranslatedField() + + class Meta: + """Meta class.""" + model = models.EstablishmentSubType + fields = [ + 'id', + 'name', + 'name_translated', + 'establishment_type' + ] + extra_kwargs = { + 'name': {'write_only': True}, + 'establishment_type': {'write_only': True} + } + + class EstablishmentEmployeeSerializer(serializers.ModelSerializer): """Serializer for actual employees.""" @@ -139,13 +155,14 @@ class EstablishmentEmployeeSerializer(serializers.ModelSerializer): fields = ('id', 'name', 'position_translated', 'awards', 'priority') -class EstablishmentBaseSerializer(serializers.ModelSerializer): +class EstablishmentBaseSerializer(ProjectModelSerializer): """Base serializer for Establishment model.""" - type = EstablishmentTypeSerializer(source='establishment_type', read_only=True) - subtypes = EstablishmentSubTypeSerializer(many=True) - address = AddressSerializer() - tags = MetaDataContentSerializer(many=True) - preview_image = serializers.SerializerMethodField() + + preview_image = serializers.URLField(source='preview_image_url') + slug = serializers.SlugField(allow_blank=False, required=True, max_length=50) + address = AddressBaseSerializer() + in_favorites = serializers.BooleanField(allow_null=True) + tags = TagBaseSerializer(read_only=True, many=True) class Meta: """Meta class.""" @@ -154,62 +171,45 @@ class EstablishmentBaseSerializer(serializers.ModelSerializer): fields = [ 'id', 'name', + 'name_translated', 'price_level', 'toque_number', 'public_mark', - 'type', - 'subtypes', + 'slug', 'preview_image', + 'in_favorites', 'address', 'tags', ] - def get_preview_image(self, obj): - """Get preview image""" - return obj.get_full_image_url(request=self.context.get('request'), - thumbnail_key='establishment_preview') - -class EstablishmentListSerializer(EstablishmentBaseSerializer): +class EstablishmentDetailSerializer(EstablishmentBaseSerializer): """Serializer for Establishment model.""" - # Annotated fields - in_favorites = serializers.BooleanField(allow_null=True) - class Meta: - """Meta class.""" - - model = models.Establishment - fields = EstablishmentBaseSerializer.Meta.fields + [ - 'in_favorites', - ] - - -class EstablishmentDetailSerializer(EstablishmentListSerializer): - """Serializer for Establishment model.""" - description_translated = serializers.CharField(allow_null=True) + description_translated = TranslatedField() + image = serializers.URLField(source='image_url') + type = EstablishmentTypeBaseSerializer(source='establishment_type', read_only=True) + subtypes = EstablishmentSubTypeBaseSerializer(many=True, source='establishment_subtypes') awards = AwardSerializer(many=True) schedule = ScheduleRUDSerializer(many=True, allow_null=True) - phones = ContactPhonesSerializer(read_only=True, many=True, ) - emails = ContactEmailsSerializer(read_only=True, many=True, ) - review = serializers.SerializerMethodField() + phones = ContactPhonesSerializer(read_only=True, many=True) + emails = ContactEmailsSerializer(read_only=True, many=True) + review = ReviewSerializer(source='last_published_review', allow_null=True) employees = EstablishmentEmployeeSerializer(source='actual_establishment_employees', many=True) menu = MenuSerializers(source='menu_set', many=True, read_only=True) - preview_image = serializers.SerializerMethodField() - best_price_menu = serializers.DecimalField(max_digits=14, decimal_places=2, read_only=True) best_price_carte = serializers.DecimalField(max_digits=14, decimal_places=2, read_only=True) + vintage_year = serializers.ReadOnlyField() - in_favorites = serializers.SerializerMethodField() - - class Meta: + class Meta(EstablishmentBaseSerializer.Meta): """Meta class.""" - model = models.Establishment - fields = EstablishmentListSerializer.Meta.fields + [ + fields = EstablishmentBaseSerializer.Meta.fields + [ 'description_translated', - 'price_level', 'image', + 'subtypes', + 'type', 'awards', 'schedule', 'website', @@ -225,23 +225,9 @@ class EstablishmentDetailSerializer(EstablishmentListSerializer): 'best_price_menu', 'best_price_carte', 'transportation', + 'vintage_year', ] - def get_review(self, obj): - """Serializer method for getting last published review""" - return ReviewSerializer(obj.reviews.by_status(status=review_models.Review.READY) - .order_by('-published_at').first()).data - - def get_in_favorites(self, obj): - """Get in_favorites status flag""" - user = self.context.get('request').user - if user.is_authenticated: - return obj.id in user.favorites.by_content_type(app_label='establishment', - model='establishment')\ - .values_list('object_id', flat=True) - else: - return False - class EstablishmentCommentCreateSerializer(comment_serializers.CommentSerializer): """Create comment serializer""" @@ -262,10 +248,10 @@ class EstablishmentCommentCreateSerializer(comment_serializers.CommentSerializer def validate(self, attrs): """Override validate method""" # Check establishment object - establishment_id = self.context.get('request').parser_context.get('kwargs').get('pk') - establishment_qs = models.Establishment.objects.filter(id=establishment_id) + establishment_slug = self.context.get('request').parser_context.get('kwargs').get('slug') + establishment_qs = models.Establishment.objects.filter(slug=establishment_slug) if not establishment_qs.exists(): - return serializers.ValidationError() + raise serializers.ValidationError({'detail': _('Establishment not found.')}) attrs['establishment'] = establishment_qs.first() return attrs @@ -311,20 +297,22 @@ class EstablishmentFavoritesCreateSerializer(serializers.ModelSerializer): def validate(self, attrs): """Override validate method""" # Check establishment object - establishment_id = self.context.get('request').parser_context.get('kwargs').get('pk') - establishment_qs = models.Establishment.objects.filter(id=establishment_id) + establishment_slug = self.context.get('request').parser_context.get('kwargs').get('slug') + establishment_qs = models.Establishment.objects.filter(slug=establishment_slug) - # Check establishment obj by pk from lookup_kwarg + # Check establishment obj by slug from lookup_kwarg if not establishment_qs.exists(): - return serializers.ValidationError() + raise serializers.ValidationError({'detail': _('Object not found.')}) + else: + establishment = establishment_qs.first() # Check existence in favorites if self.get_user().favorites.by_content_type(app_label='establishment', model='establishment')\ - .by_object_id(object_id=establishment_id).exists(): + .by_object_id(object_id=establishment.id).exists(): raise utils_exceptions.FavoritesError() - attrs['establishment'] = establishment_qs.first() + attrs['establishment'] = establishment return attrs def create(self, validated_data, *args, **kwargs): @@ -335,17 +323,3 @@ class EstablishmentFavoritesCreateSerializer(serializers.ModelSerializer): }) return super().create(validated_data) - -class EstablishmentTagListSerializer(serializers.ModelSerializer): - """List establishment tag serializer.""" - id = serializers.IntegerField(source='metadata.id') - label_translated = serializers.CharField( - source='metadata.label_translated', read_only=True, allow_null=True) - - class Meta: - """Meta class.""" - model = MetaDataContent - fields = [ - 'id', - 'label_translated', - ] diff --git a/apps/establishment/tests.py b/apps/establishment/tests.py index b64a971c..a1d8fcb5 100644 --- a/apps/establishment/tests.py +++ b/apps/establishment/tests.py @@ -1,27 +1,106 @@ +import json from rest_framework.test import APITestCase from account.models import User from rest_framework import status from http.cookies import SimpleCookie -from establishment.models import Employee +from main.models import Currency +from establishment.models import Establishment, EstablishmentType, Menu # Create your tests here. +from translation.models import Language +from account.models import Role, UserRole +from location.models import Country, Address, City, Region class BaseTestCase(APITestCase): - def setUp(self): self.username = 'sedragurda' self.password = 'sedragurdaredips19' self.email = 'sedragurda@desoz.com' self.newsletter = True - self.user = User.objects.create_user(username=self.username, email=self.email, password=self.password) + self.user = User.objects.create_user( + username=self.username, email=self.email, password=self.password) #get tokkens tokkens = User.create_jwt_tokens(self.user) - self.client.cookies = SimpleCookie({'access_token': tokkens.get('access_token'), - 'refresh_token': tokkens.get('refresh_token')}) + self.client.cookies = SimpleCookie( + {'access_token': tokkens.get('access_token'), + 'refresh_token': tokkens.get('refresh_token')}) + + self.establishment_type = EstablishmentType.objects.create(name="Test establishment type") + + # Create lang object + self.lang = Language.objects.get( + title='Russia', + locale='ru-RU' + ) + + self.country_ru = Country.objects.get( + name={"en-GB": "Russian"} + ) + + self.region = Region.objects.create(name='Moscow area', code='01', + country=self.country_ru) + self.region.save() + + self.city = City.objects.create(name='Mosocow', code='01', + region=self.region, country=self.country_ru) + self.city.save() + + self.address = Address.objects.create(city=self.city, street_name_1='Krasnaya', + number=2, postal_code='010100') + self.address.save() + + self.role = Role.objects.create(role=Role.ESTABLISHMENT_MANAGER) + self.role.save() + + self.establishment = Establishment.objects.create( + name="Test establishment", + establishment_type_id=self.establishment_type.id, + is_publish=True, + slug="test", + address=self.address + ) + + self.establishment.save() + + self.user_role = UserRole.objects.create(user=self.user, role=self.role, + establishment=self.establishment) + self.user_role.save() + + +class EstablishmentBTests(BaseTestCase): + def test_establishment_CRUD(self): + params = {'page': 1, 'page_size': 1,} + response = self.client.get('/api/back/establishments/', params, format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + data = { + 'name': 'Test establishment', + 'type_id': self.establishment_type.id, + 'is_publish': True, + 'slug': 'test-establishment-slug' + } + + response = self.client.post('/api/back/establishments/', data=data, format='json') + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + response = self.client.get(f'/api/back/establishments/{self.establishment.id}/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + update_data = { + 'name': 'Test new establishment' + } + + response = self.client.patch(f'/api/back/establishments/{self.establishment.id}/', + data=update_data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.delete(f'/api/back/establishments/{self.establishment.id}/', + format='json') + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) class EmployeeTests(BaseTestCase): - def test_employee_CRD(self): + def test_employee_CRUD(self): response = self.client.get('/api/back/establishments/employees/', format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) @@ -36,9 +115,284 @@ class EmployeeTests(BaseTestCase): response = self.client.get('/api/back/establishments/employees/1/', format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) + update_data = { + 'name': 'Test new name' + } + + response = self.client.patch('/api/back/establishments/employees/1/', data=update_data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + response = self.client.delete('/api/back/establishments/employees/1/', format='json') self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) +# Class to test childs +class ChildTestCase(BaseTestCase): + def setUp(self): + super().setUp() + +# Test childs +class EmailTests(ChildTestCase): + def setUp(self): + super().setUp() + + def test_get(self): + response = self.client.get('/api/back/establishments/emails/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_post(self): + data = { + 'email': "test@test.com", + 'establishment': self.establishment.id + } + + response = self.client.post('/api/back/establishments/emails/', data=data) + self.id_email = response.json()['id'] + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + def test_get_by_pk(self): + self.test_post() + response = self.client.get(f'/api/back/establishments/emails/{self.id_email}/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_patch(self): + self.test_post() + + update_data = { + 'email': 'testnew@test.com' + } + + response = self.client.patch(f'/api/back/establishments/emails/{self.id_email}/', + data=update_data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_email_CRUD(self): + self.test_post() + response = self.client.delete(f'/api/back/establishments/emails/{self.id_email}/') + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) +class PhoneTests(ChildTestCase): + def test_phone_CRUD(self): + response = self.client.get('/api/back/establishments/phones/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + data = { + 'phone': "+79999999999", + 'establishment': self.establishment.id + } + + response = self.client.post('/api/back/establishments/phones/', data=data) + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + response = self.client.get('/api/back/establishments/phones/1/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + update_data = { + 'phone': '+79999999998' + } + + response = self.client.patch('/api/back/establishments/phones/1/', data=update_data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.delete('/api/back/establishments/phones/1/') + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) + + +class SocialTests(ChildTestCase): + def test_social_CRUD(self): + response = self.client.get('/api/back/establishments/socials/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + data = { + 'title': "Test social", + 'url': 'https://testsocial.com', + 'establishment': self.establishment.id + } + + response = self.client.post('/api/back/establishments/socials/', data=data) + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + response = self.client.get('/api/back/establishments/socials/1/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + update_data = { + 'title': 'Test new social' + } + + response = self.client.patch('/api/back/establishments/socials/1/', data=update_data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.delete('/api/back/establishments/socials/1/') + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) + + +class PlateTests(ChildTestCase): + def test_plate_CRUD(self): + response = self.client.get('/api/back/establishments/plates/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + menu = Menu.objects.create( + category=json.dumps({"en-GB": "Test category"}), + establishment=self.establishment + ) + currency = Currency.objects.create(name="Test currency") + + data = { + 'name': json.dumps({"en-GB": "Test plate"}), + 'establishment': self.establishment.id, + 'price': 10, + 'menu': menu.id, + 'currency_id': currency.id + } + + response = self.client.post('/api/back/establishments/plates/', data=data) + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + response = self.client.get('/api/back/establishments/plates/1/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + update_data = { + 'name': json.dumps({"en-GB": "Test new plate"}) + } + + response = self.client.patch('/api/back/establishments/plates/1/', data=update_data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.delete('/api/back/establishments/plates/1/') + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) + + +class MenuTests(ChildTestCase): + def test_menu_CRUD(self): + response = self.client.get('/api/back/establishments/menus/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + data = { + 'category': json.dumps({"en-GB": "Test category"}), + 'establishment': self.establishment.id + } + + response = self.client.post('/api/back/establishments/menus/', data=data) + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + response = self.client.get('/api/back/establishments/menus/1/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + update_data = { + 'category': json.dumps({"en-GB": "Test new category"}) + } + + response = self.client.patch('/api/back/establishments/menus/1/', data=update_data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.delete('/api/back/establishments/menus/1/') + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) + + +class EstablishmentShedulerTests(ChildTestCase): + def test_shedule_CRUD(self): + data = { + 'weekday': 1 + } + response = self.client.post(f'/api/back/establishments/{self.establishment.id}/schedule/', data=data) + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + response = self.client.get(f'/api/back/establishments/{self.establishment.id}/schedule/1/') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + update_data = { + 'weekday': 2 + } + + response = self.client.patch(f'/api/back/establishments/{self.establishment.id}/schedule/1/', data=update_data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.delete(f'/api/back/establishments/{self.establishment.id}/schedule/1/') + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) + + +# Web tests +class EstablishmentWebTests(BaseTestCase): + + def test_establishment_Read(self): + params = {'page': 1, 'page_size': 1,} + response = self.client.get('/api/web/establishments/', params, format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + +class EstablishmentWebTagTests(BaseTestCase): + + def test_tag_Read(self): + response = self.client.get('/api/web/establishments/tags/', format='json') + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + + +class EstablishmentWebSlugTests(ChildTestCase): + + def test_slug_Read(self): + response = self.client.get(f'/api/web/establishments/slug/{self.establishment.slug}/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + +class EstablishmentWebSimilarTests(ChildTestCase): + + def test_similar_Read(self): + response = self.client.get(f'/api/web/establishments/slug/{self.establishment.slug}/similar/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + +class EstablishmentWebCommentsTests(ChildTestCase): + + def test_comments_CRUD(self): + + response = self.client.get(f'/api/web/establishments/slug/{self.establishment.slug}/comments/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + data = { + 'text': 'test', + 'user': self.user.id, + 'mark': 4 + } + + response = self.client.post(f'/api/web/establishments/slug/{self.establishment.slug}/comments/create/', + data=data) + + comment = response.json() + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + response = self.client.get(f'/api/web/establishments/slug/{self.establishment.slug}/comments/{comment["id"]}/', + format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + update_data = { + 'text': 'Test new establishment' + } + + response = self.client.patch(f'/api/web/establishments/slug/{self.establishment.slug}/comments/{comment["id"]}/', + data=update_data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.delete( + f'/api/web/establishments/slug/{self.establishment.slug}/comments/{comment["id"]}/', + format='json') + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) + + +class EstablishmentWebFavoriteTests(ChildTestCase): + + def test_favorite_CR(self): + data = { + "user": self.user.id, + "object_id": self.establishment.id + } + + response = self.client.post(f'/api/web/establishments/slug/{self.establishment.slug}/favorites/', + data=data) + + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + response = self.client.delete( + f'/api/web/establishments/slug/{self.establishment.slug}/favorites/', + format='json') + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) diff --git a/apps/establishment/urls/back.py b/apps/establishment/urls/back.py index 9c0aac73..6a12e792 100644 --- a/apps/establishment/urls/back.py +++ b/apps/establishment/urls/back.py @@ -9,7 +9,7 @@ app_name = 'establishment' urlpatterns = [ path('', views.EstablishmentListCreateView.as_view(), name='list'), - path('/', views.EstablishmentRetrieveView.as_view(), name='detail'), + path('/', views.EstablishmentRUDView.as_view(), name='detail'), path('/schedule//', views.EstablishmentScheduleRUDView.as_view(), name='schedule-rud'), path('/schedule/', views.EstablishmentScheduleCreateView.as_view(), @@ -17,7 +17,7 @@ urlpatterns = [ path('menus/', views.MenuListCreateView.as_view(), name='menu-list'), path('menus//', views.MenuRUDView.as_view(), name='menu-rud'), path('plates/', views.PlateListCreateView.as_view(), name='plates'), - path('plates//', views.PlateListCreateView.as_view(), name='plate-rud'), + path('plates//', views.PlateRUDView.as_view(), name='plate-rud'), path('socials/', views.SocialListCreateView.as_view(), name='socials'), path('socials//', views.SocialRUDView.as_view(), name='social-rud'), path('phones/', views.PhonesListCreateView.as_view(), name='phones'), @@ -26,4 +26,8 @@ urlpatterns = [ path('emails//', views.EmailRUDView.as_view(), name='emails-rud'), path('employees/', views.EmployeeListCreateView.as_view(), name='employees'), path('employees//', views.EmployeeRUDView.as_view(), name='employees-rud'), -] \ No newline at end of file + path('types/', views.EstablishmentTypeListCreateView.as_view(), name='type-list'), + path('types//', views.EstablishmentTypeRUDView.as_view(), name='type-rud'), + path('subtypes/', views.EstablishmentSubtypeListCreateView.as_view(), name='subtype-list'), + path('subtypes//', views.EstablishmentSubtypeRUDView.as_view(), name='subtype-rud'), +] diff --git a/apps/establishment/urls/common.py b/apps/establishment/urls/common.py index 3fdd46d3..8d9453c1 100644 --- a/apps/establishment/urls/common.py +++ b/apps/establishment/urls/common.py @@ -7,14 +7,16 @@ app_name = 'establishment' urlpatterns = [ path('', views.EstablishmentListView.as_view(), name='list'), - path('tags/', views.EstablishmentTagListView.as_view(), name='tags'), - path('/', views.EstablishmentRetrieveView.as_view(), name='detail'), - path('/similar/', views.EstablishmentSimilarListView.as_view(), name='similar'), - path('/comments/', views.EstablishmentCommentListView.as_view(), name='list-comments'), - path('/comments/create/', views.EstablishmentCommentCreateView.as_view(), + path('recent-reviews/', views.EstablishmentRecentReviewListView.as_view(), + name='recent-reviews'), + # path('wineries/', views.WineriesListView.as_view(), name='wineries-list'), + path('slug//', views.EstablishmentRetrieveView.as_view(), name='detail'), + path('slug//similar/', views.EstablishmentSimilarListView.as_view(), name='similar'), + path('slug//comments/', views.EstablishmentCommentListView.as_view(), name='list-comments'), + path('slug//comments/create/', views.EstablishmentCommentCreateView.as_view(), name='create-comment'), - path('/comments//', views.EstablishmentCommentRUDView.as_view(), + path('slug//comments//', views.EstablishmentCommentRUDView.as_view(), name='rud-comment'), - path('/favorites/', views.EstablishmentFavoritesCreateDestroyView.as_view(), - name='add-favorites') + path('slug//favorites/', views.EstablishmentFavoritesCreateDestroyView.as_view(), + name='add-to-favorites') ] diff --git a/apps/establishment/urls/web.py b/apps/establishment/urls/web.py index b732d171..b4d1942d 100644 --- a/apps/establishment/urls/web.py +++ b/apps/establishment/urls/web.py @@ -4,4 +4,4 @@ from establishment.urls.common import urlpatterns as common_urlpatterns urlpatterns = [] -urlpatterns.extend(common_urlpatterns) \ No newline at end of file +urlpatterns.extend(common_urlpatterns) diff --git a/apps/establishment/views/back.py b/apps/establishment/views/back.py index aa52caec..e490d576 100644 --- a/apps/establishment/views/back.py +++ b/apps/establishment/views/back.py @@ -1,28 +1,73 @@ """Establishment app views.""" - +from django.shortcuts import get_object_or_404 from rest_framework import generics -from establishment import models -from establishment import serializers -from establishment.views.common import EstablishmentMixin +from utils.permissions import IsCountryAdmin, IsEstablishmentManager +from establishment import models, serializers +from timetable.serialziers import ScheduleRUDSerializer, ScheduleCreateSerializer -class EstablishmentListCreateView(EstablishmentMixin, generics.ListCreateAPIView): +class EstablishmentMixinViews: + """Establishment mixin.""" + + def get_queryset(self): + """Overrided method 'get_queryset'.""" + return models.Establishment.objects.published().with_base_related() + + +class EstablishmentListCreateView(EstablishmentMixinViews, generics.ListCreateAPIView): """Establishment list/create view.""" queryset = models.Establishment.objects.all() serializer_class = serializers.EstablishmentListCreateSerializer + permission_classes = [IsCountryAdmin|IsEstablishmentManager] + + +class EstablishmentRUDView(generics.RetrieveUpdateDestroyAPIView): + queryset = models.Establishment.objects.all() + serializer_class = serializers.EstablishmentRUDSerializer + permission_classes = [IsCountryAdmin|IsEstablishmentManager] + + +class EstablishmentScheduleRUDView(generics.RetrieveUpdateDestroyAPIView): + """Establishment schedule RUD view""" + serializer_class = ScheduleRUDSerializer + + def get_object(self): + """ + Returns the object the view is displaying. + """ + establishment_pk = self.kwargs['pk'] + schedule_id = self.kwargs['schedule_id'] + + establishment = get_object_or_404(klass=models.Establishment.objects.all(), + pk=establishment_pk) + schedule = get_object_or_404(klass=establishment.schedule, + id=schedule_id) + + # May raise a permission denied + self.check_object_permissions(self.request, establishment) + self.check_object_permissions(self.request, schedule) + + return schedule + + +class EstablishmentScheduleCreateView(generics.CreateAPIView): + """Establishment schedule Create view""" + serializer_class = ScheduleCreateSerializer class MenuListCreateView(generics.ListCreateAPIView): """Menu list create view.""" serializer_class = serializers.MenuSerializers queryset = models.Menu.objects.all() + permission_classes = [IsEstablishmentManager] class MenuRUDView(generics.RetrieveUpdateDestroyAPIView): """Menu RUD view.""" serializer_class = serializers.MenuRUDSerializers queryset = models.Menu.objects.all() + permission_classes = [IsEstablishmentManager] class SocialListCreateView(generics.ListCreateAPIView): @@ -30,12 +75,14 @@ class SocialListCreateView(generics.ListCreateAPIView): serializer_class = serializers.SocialNetworkSerializers queryset = models.SocialNetwork.objects.all() pagination_class = None + permission_classes = [IsEstablishmentManager] class SocialRUDView(generics.RetrieveUpdateDestroyAPIView): """Social RUD view.""" serializer_class = serializers.SocialNetworkSerializers queryset = models.SocialNetwork.objects.all() + permission_classes = [IsEstablishmentManager] class PlateListCreateView(generics.ListCreateAPIView): @@ -43,12 +90,14 @@ class PlateListCreateView(generics.ListCreateAPIView): serializer_class = serializers.PlatesSerializers queryset = models.Plate.objects.all() pagination_class = None + permission_classes = [IsEstablishmentManager] class PlateRUDView(generics.RetrieveUpdateDestroyAPIView): """Social RUD view.""" serializer_class = serializers.PlatesSerializers queryset = models.Plate.objects.all() + permission_classes = [IsEstablishmentManager] class PhonesListCreateView(generics.ListCreateAPIView): @@ -56,12 +105,14 @@ class PhonesListCreateView(generics.ListCreateAPIView): serializer_class = serializers.ContactPhoneBackSerializers queryset = models.ContactPhone.objects.all() pagination_class = None + permission_classes = [IsEstablishmentManager] class PhonesRUDView(generics.RetrieveUpdateDestroyAPIView): """Social RUD view.""" serializer_class = serializers.ContactPhoneBackSerializers queryset = models.ContactPhone.objects.all() + permission_classes = [IsEstablishmentManager] class EmailListCreateView(generics.ListCreateAPIView): @@ -69,12 +120,14 @@ class EmailListCreateView(generics.ListCreateAPIView): serializer_class = serializers.ContactEmailBackSerializers queryset = models.ContactEmail.objects.all() pagination_class = None + permission_classes = [IsEstablishmentManager] class EmailRUDView(generics.RetrieveUpdateDestroyAPIView): """Social RUD view.""" serializer_class = serializers.ContactEmailBackSerializers queryset = models.ContactEmail.objects.all() + permission_classes = [IsEstablishmentManager] class EmployeeListCreateView(generics.ListCreateAPIView): @@ -83,7 +136,34 @@ class EmployeeListCreateView(generics.ListCreateAPIView): queryset = models.Employee.objects.all() pagination_class = None -class EmployeeRUDView(generics.RetrieveDestroyAPIView): + +class EmployeeRUDView(generics.RetrieveUpdateDestroyAPIView): """Social RUD view.""" serializer_class = serializers.EmployeeBackSerializers - queryset = models.Employee.objects.all() \ No newline at end of file + queryset = models.Employee.objects.all() + + +class EstablishmentTypeListCreateView(generics.ListCreateAPIView): + """Establishment type list/create view.""" + serializer_class = serializers.EstablishmentTypeBaseSerializer + queryset = models.EstablishmentType.objects.all() + pagination_class = None + + +class EstablishmentTypeRUDView(generics.RetrieveUpdateDestroyAPIView): + """Establishment type retrieve/update/destroy view.""" + serializer_class = serializers.EstablishmentTypeBaseSerializer + queryset = models.EstablishmentType.objects.all() + + +class EstablishmentSubtypeListCreateView(generics.ListCreateAPIView): + """Establishment subtype list/create view.""" + serializer_class = serializers.EstablishmentSubTypeBaseSerializer + queryset = models.EstablishmentSubType.objects.all() + pagination_class = None + + +class EstablishmentSubtypeRUDView(generics.RetrieveUpdateDestroyAPIView): + """Establishment subtype retrieve/update/destroy view.""" + serializer_class = serializers.EstablishmentSubTypeBaseSerializer + queryset = models.EstablishmentSubType.objects.all() diff --git a/apps/establishment/views/common.py b/apps/establishment/views/common.py index b57d6ef6..e69de29b 100644 --- a/apps/establishment/views/common.py +++ b/apps/establishment/views/common.py @@ -1,16 +0,0 @@ -"""Establishment app views.""" - -from rest_framework import permissions - -from establishment import models - - -class EstablishmentMixin: - """Establishment mixin.""" - - permission_classes = (permissions.AllowAny,) - - def get_queryset(self): - """Overrided method 'get_queryset'.""" - return models.Establishment.objects.published() \ - .prefetch_actual_employees() diff --git a/apps/establishment/views/web.py b/apps/establishment/views/web.py index 73c1621d..8ee9ddf7 100644 --- a/apps/establishment/views/web.py +++ b/apps/establishment/views/web.py @@ -1,68 +1,113 @@ """Establishment app views.""" - +from django.conf import settings +from django.contrib.gis.geos import Point from django.shortcuts import get_object_or_404 from rest_framework import generics, permissions from comment import models as comment_models from establishment import filters from establishment import models, serializers -from establishment.views import EstablishmentMixin +from main import methods from main.models import MetaDataContent -from timetable.serialziers import ScheduleRUDSerializer, ScheduleCreateSerializer +from utils.pagination import EstablishmentPortionPagination +from utils.permissions import IsCountryAdmin + +class EstablishmentMixinView: + """Establishment mixin.""" + + permission_classes = (permissions.AllowAny,) + + def get_queryset(self): + """Overridden method 'get_queryset'.""" + return models.Establishment.objects.published() \ + .with_base_related() \ + .annotate_in_favorites(self.request.user) -class EstablishmentListView(EstablishmentMixin, generics.ListAPIView): +class EstablishmentListView(EstablishmentMixinView, generics.ListAPIView): """Resource for getting a list of establishments.""" - serializer_class = serializers.EstablishmentListSerializer + filter_class = filters.EstablishmentFilter + serializer_class = serializers.EstablishmentBaseSerializer def get_queryset(self): """Overridden method 'get_queryset'.""" qs = super(EstablishmentListView, self).get_queryset() - return qs.by_country_code(code=self.request.country_code) \ - .annotate_in_favorites(user=self.request.user) + if self.request.country_code: + qs = qs.by_country_code(self.request.country_code) + return qs + + +class EstablishmentRetrieveView(EstablishmentMixinView, generics.RetrieveAPIView): + """Resource for getting a establishment.""" + + lookup_field = 'slug' + serializer_class = serializers.EstablishmentDetailSerializer + + def get_queryset(self): + return super().get_queryset().with_extended_related() + + +class EstablishmentRecentReviewListView(EstablishmentListView): + """List view for last reviewed establishments.""" + + pagination_class = EstablishmentPortionPagination + + def get_queryset(self): + """Overridden method 'get_queryset'.""" + qs = super().get_queryset() + user_ip = methods.get_user_ip(self.request) + query_params = self.request.query_params + if 'longitude' in query_params and 'latitude' in query_params: + longitude, latitude = query_params.get('longitude'), query_params.get('latitude') + else: + longitude, latitude = methods.determine_coordinates(user_ip) + if not longitude or not latitude: + return qs.none() + point = Point(x=float(longitude), y=float(latitude), srid=settings.GEO_DEFAULT_SRID) + return qs.last_reviewed(point=point) class EstablishmentSimilarListView(EstablishmentListView): """Resource for getting a list of establishments.""" - serializer_class = serializers.EstablishmentListSerializer + + serializer_class = serializers.EstablishmentBaseSerializer + pagination_class = EstablishmentPortionPagination def get_queryset(self): """Override get_queryset method""" qs = super().get_queryset() - return qs.similar(establishment_pk=self.kwargs.get('pk'))\ - .order_by('-total_mark')[:13] - - -class EstablishmentRetrieveView(EstablishmentMixin, generics.RetrieveAPIView): - """Resource for getting a establishment.""" - serializer_class = serializers.EstablishmentDetailSerializer + return qs.similar(establishment_slug=self.kwargs.get('slug')) class EstablishmentTypeListView(generics.ListAPIView): """Resource for getting a list of establishment types.""" permission_classes = (permissions.AllowAny,) - serializer_class = serializers.EstablishmentTypeSerializer + serializer_class = serializers.EstablishmentTypeBaseSerializer queryset = models.EstablishmentType.objects.all() class EstablishmentCommentCreateView(generics.CreateAPIView): """View for create new comment.""" + lookup_field = 'slug' serializer_class = serializers.EstablishmentCommentCreateSerializer queryset = comment_models.Comment.objects.all() class EstablishmentCommentListView(generics.ListAPIView): """View for return list of establishment comments.""" + permission_classes = (permissions.AllowAny,) serializer_class = serializers.EstablishmentCommentCreateSerializer def get_queryset(self): """Override get_queryset method""" + + establishment = get_object_or_404(models.Establishment, slug=self.kwargs['slug']) return comment_models.Comment.objects.by_content_type(app_label='establishment', model='establishment')\ - .by_object_id(object_id=self.kwargs.get('pk'))\ + .by_object_id(object_id=establishment.pk)\ .order_by('-created') @@ -76,17 +121,9 @@ class EstablishmentCommentRUDView(generics.RetrieveUpdateDestroyAPIView): Returns the object the view is displaying. """ queryset = self.filter_queryset(self.get_queryset()) - lookup_url_kwargs = ('pk', 'comment_id') - - assert lookup_url_kwargs not in self.kwargs.keys(), ( - 'Expected view %s to be called with a URL keyword argument ' - 'named "%s". Fix your URL conf, or set the `.lookup_field` ' - 'attribute on the view correctly.' % - (self.__class__.__name__, lookup_url_kwargs) - ) establishment_obj = get_object_or_404(queryset, - pk=self.kwargs['pk']) + slug=self.kwargs['slug']) comment_obj = get_object_or_404(establishment_obj.comments.by_user(self.request.user), pk=self.kwargs['comment_id']) @@ -99,93 +136,52 @@ class EstablishmentCommentRUDView(generics.RetrieveUpdateDestroyAPIView): class EstablishmentFavoritesCreateDestroyView(generics.CreateAPIView, generics.DestroyAPIView): """View for create/destroy establishment from favorites.""" serializer_class = serializers.EstablishmentFavoritesCreateSerializer + lookup_field = 'slug' def get_object(self): """ Returns the object the view is displaying. """ - lookup_url_kwargs = ('pk',) - assert lookup_url_kwargs not in self.kwargs.keys(), ( - 'Expected view %s to be called with a URL keyword argument ' - 'named "%s". Fix your URL conf, or set the `.lookup_field` ' - 'attribute on the view correctly.' % - (self.__class__.__name__, lookup_url_kwargs) - ) - + establishment_obj = get_object_or_404(models.Establishment, + slug=self.kwargs['slug']) obj = get_object_or_404( - self.request.user.favorites.by_user(user=self.request.user) - .by_content_type(app_label='establishment', + self.request.user.favorites.by_content_type(app_label='establishment', model='establishment') - .by_object_id(object_id=self.kwargs['pk'])) + .by_object_id(object_id=establishment_obj.pk)) # May raise a permission denied self.check_object_permissions(self.request, obj) return obj -class EstablishmentNearestRetrieveView(EstablishmentMixin, generics.ListAPIView): +class EstablishmentNearestRetrieveView(EstablishmentListView, generics.ListAPIView): """Resource for getting list of nearest establishments.""" - serializer_class = serializers.EstablishmentListSerializer + + serializer_class = serializers.EstablishmentBaseSerializer filter_class = filters.EstablishmentFilter def get_queryset(self): - """Overrided method 'get_queryset'.""" - from django.contrib.gis.geos import Point + """Overridden method 'get_queryset'.""" + # todo: latitude and longitude + lat = self.request.query_params.get('lat') + lon = self.request.query_params.get('lon') + radius = self.request.query_params.get('radius') + unit = self.request.query_params.get('unit') - center = Point(float(self.request.query_params["lat"]), float(self.request.query_params["lon"])) - radius = float(self.request.query_params["radius"]) - unit = self.request.query_params.get("unit", None) - by_distance_from_point_kwargs = {"center": center, "radius": radius, "unit": unit} - return super(EstablishmentNearestRetrieveView, self).get_queryset() \ - .by_distance_from_point(**{k: v for k, v in by_distance_from_point_kwargs.items() if v is not None}) \ - .by_country_code(code=self.request.country_code) \ - .annotate_in_favorites(user=self.request.user) + qs = super(EstablishmentNearestRetrieveView, self).get_queryset() + if lat and lon and radius and unit: + center = Point(float(lat), float(lon)) + filter_kwargs = {'center': center, 'radius': float(radius), 'unit': unit} + return qs.by_distance_from_point(**{k: v for k, v in filter_kwargs.items() + if v is not None}) + return qs -class EstablishmentTagListView(generics.ListAPIView): - """List view for establishment tags.""" - serializer_class = serializers.EstablishmentTagListSerializer - permission_classes = (permissions.AllowAny,) - pagination_class = None - - def get_queryset(self): - """Override get_queryset method""" - return MetaDataContent.objects.by_content_type(app_label='establishment', - model='establishment')\ - .distinct('metadata__label') - - -class EstablishmentScheduleRUDView(generics.RetrieveUpdateDestroyAPIView): - """Establishment schedule RUD view""" - serializer_class = ScheduleRUDSerializer - - def get_object(self): - """ - Returns the object the view is displaying. - """ - lookup_url_kwargs = ('pk', 'schedule_id') - - assert lookup_url_kwargs not in self.kwargs.keys(), ( - 'Expected view %s to be called with a URL keyword argument ' - 'named "%s". Fix your URL conf, or set the `.lookup_field` ' - 'attribute on the view correctly.' % - (self.__class__.__name__, lookup_url_kwargs) - ) - - establishment_pk = self.kwargs['pk'] - schedule_id = self.kwargs['schedule_id'] - - establishment = get_object_or_404(klass=models.Establishment.objects.all(), - pk=establishment_pk) - schedule = get_object_or_404(klass=establishment.schedule, - id=schedule_id) - - # May raise a permission denied - self.check_object_permissions(self.request, establishment) - self.check_object_permissions(self.request, schedule) - - return schedule - - -class EstablishmentScheduleCreateView(generics.CreateAPIView): - """Establishment schedule Create view""" - serializer_class = ScheduleCreateSerializer +# Wineries +# todo: find out about difference between subtypes data +# class WineriesListView(EstablishmentListView): +# """Return list establishments with type Wineries""" +# +# def get_queryset(self): +# """Overridden get_queryset method.""" +# qs = super(WineriesListView, self).get_queryset() +# return qs.with_type_related().wineries() diff --git a/apps/favorites/serializers.py b/apps/favorites/serializers.py index d4485c54..bf0db4fb 100644 --- a/apps/favorites/serializers.py +++ b/apps/favorites/serializers.py @@ -2,16 +2,3 @@ from .models import Favorites from rest_framework import serializers from establishment.serializers import EstablishmentBaseSerializer - - -class FavoritesEstablishmentListSerializer(serializers.ModelSerializer): - """Serializer for model Favorites""" - detail = EstablishmentBaseSerializer(source='content_object') - - class Meta: - """Meta class.""" - model = Favorites - fields = ( - 'id', - 'detail', - ) diff --git a/apps/favorites/tests.py b/apps/favorites/tests.py index a39b155a..99b01444 100644 --- a/apps/favorites/tests.py +++ b/apps/favorites/tests.py @@ -1 +1,54 @@ # Create your tests here. +from http.cookies import SimpleCookie +from django.contrib.contenttypes.models import ContentType + +from rest_framework.test import APITestCase +from rest_framework import status + +from account.models import User +from favorites.models import Favorites +from establishment.models import Establishment, EstablishmentType, EstablishmentSubType +from news.models import NewsType, News + + +class BaseTestCase(APITestCase): + + def setUp(self): + self.username = 'sedragurda' + self.password = 'sedragurdaredips19' + self.email = 'sedragurda@desoz.com' + self.user = User.objects.create_user(username=self.username, email=self.email, password=self.password) + tokkens = User.create_jwt_tokens(self.user) + self.client.cookies = SimpleCookie({'access_token': tokkens.get('access_token'), + 'refresh_token': tokkens.get('refresh_token')}) + + self.test_news_type = NewsType.objects.create(name="Test news type") + self.test_news = News.objects.create(created_by=self.user, modified_by=self.user, title={"en-GB": "Test news"}, + news_type=self.test_news_type, + description={"en-GB": "Description test news"}, + playlist=1, start="2020-12-03 12:00:00", end="2020-12-13 12:00:00", + state=News.PUBLISHED, slug='test-news') + + self.test_content_type = ContentType.objects.get(app_label="news", model="news") + + self.test_favorites = Favorites.objects.create(user=self.user, content_type=self.test_content_type, + object_id=self.test_news.id) + + self.test_establishment_type = EstablishmentType.objects.create(name={"en-GB": "test establishment type"}, + use_subtypes=False) + + self.test_establishment = Establishment.objects.create(name="test establishment", + description={"en-GB": "description of test establishment"}, + establishment_type=self.test_establishment_type, + is_publish=True) + # value for GenericRelation(reverse side) field must be iterable + # value for GenericRelation(reverse side) field must be assigned through "set" method of field + self.test_establishment.favorites.set([self.test_favorites]) + + +class FavoritesTestCase(BaseTestCase): + + def test_func(self): + response = self.client.get("/api/web/favorites/establishments/") + print(response.json()) + self.assertEqual(response.status_code, status.HTTP_200_OK) \ No newline at end of file diff --git a/apps/favorites/urls.py b/apps/favorites/urls.py index 80498e65..bd0c1d16 100644 --- a/apps/favorites/urls.py +++ b/apps/favorites/urls.py @@ -8,5 +8,4 @@ app_name = 'favorites' urlpatterns = [ path('establishments/', views.FavoritesEstablishmentListView.as_view(), name='establishment-list'), - path('remove//', views.FavoritesDestroyView.as_view(), name='remove-from-favorites'), ] diff --git a/apps/favorites/views.py b/apps/favorites/views.py index c35edcf5..5d99ed4b 100644 --- a/apps/favorites/views.py +++ b/apps/favorites/views.py @@ -1,25 +1,24 @@ """Views for app favorites.""" from rest_framework import generics -from .serializers import FavoritesEstablishmentListSerializer +from establishment.models import Establishment +from establishment.serializers import EstablishmentBaseSerializer from .models import Favorites class FavoritesBaseView(generics.GenericAPIView): """Base view for Favorites.""" + def get_queryset(self): """Override get_queryset method.""" return Favorites.objects.by_user(self.request.user) -class FavoritesEstablishmentListView(FavoritesBaseView, generics.ListAPIView): +class FavoritesEstablishmentListView(generics.ListAPIView): """List views for favorites""" - serializer_class = FavoritesEstablishmentListSerializer + + serializer_class = EstablishmentBaseSerializer def get_queryset(self): """Override get_queryset method""" - return super().get_queryset().by_content_type(app_label='establishment', - model='establishment') - - -class FavoritesDestroyView(FavoritesBaseView, generics.DestroyAPIView): - """Destroy view for favorites""" + return Establishment.objects.filter(favorites__user=self.request.user)\ + .order_by('-favorites') diff --git a/apps/gallery/views.py b/apps/gallery/views.py index 109a01ef..8a9195c3 100644 --- a/apps/gallery/views.py +++ b/apps/gallery/views.py @@ -1,6 +1,5 @@ from rest_framework import generics -from utils.permissions import IsAuthenticatedAndTokenIsValid from . import models, serializers @@ -9,4 +8,3 @@ class ImageUploadView(generics.CreateAPIView): model = models.Image queryset = models.Image.objects.all() serializer_class = serializers.ImageSerializer - permission_classes = (IsAuthenticatedAndTokenIsValid, ) diff --git a/apps/location/migrations/0011_country_languages.py b/apps/location/migrations/0011_country_languages.py new file mode 100644 index 00000000..629f76bc --- /dev/null +++ b/apps/location/migrations/0011_country_languages.py @@ -0,0 +1,19 @@ +# Generated by Django 2.2.4 on 2019-10-10 12:22 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('translation', '0003_auto_20190901_1032'), + ('location', '0010_auto_20190904_0711'), + ] + + operations = [ + migrations.AddField( + model_name='country', + name='languages', + field=models.ManyToManyField(to='translation.Language', verbose_name='Languages'), + ), + ] diff --git a/apps/location/migrations/0012_data_migrate.py b/apps/location/migrations/0012_data_migrate.py new file mode 100644 index 00000000..b61c43df --- /dev/null +++ b/apps/location/migrations/0012_data_migrate.py @@ -0,0 +1,25 @@ +from django.db import migrations, connection +import os + + +class Migration(migrations.Migration): + # Check migration + def load_data_from_sql(apps, schema_editor): + file_path = os.path.join(os.path.dirname(__file__), 'migrate_lang.sql') + sql_statement = open(file_path).read() + with connection.cursor() as c: + c.execute(sql_statement) + + def revert_data(apps, schema_editor): + file_path = os.path.join(os.path.dirname(__file__), 'remigrate_lang.sql') + sql_statement = open(file_path).read() + with connection.cursor() as c: + c.execute(sql_statement) + + dependencies = [ + ('location', '0011_country_languages'), + ] + + operations = [ + migrations.RunPython(load_data_from_sql, revert_data), + ] diff --git a/apps/location/migrations/migrate_lang.sql b/apps/location/migrations/migrate_lang.sql new file mode 100644 index 00000000..c3b716b1 --- /dev/null +++ b/apps/location/migrations/migrate_lang.sql @@ -0,0 +1,382 @@ +SET search_path TO gm, public; + +CREATE TABLE codelang ( + code varchar(100) NULL, + country varchar(10000) NULL +); + + +INSERT INTO codelang (code,country) VALUES +('af','Afrikaans') +,('af-ZA','Afrikaans (South Africa)') +,('ar','Arabic') +,('ar-AE','Arabic (U.A.E.)') +,('ar-BH','Arabic (Bahrain)') +,('ar-DZ','Arabic (Algeria)') +,('ar-EG','Arabic (Egypt)') +,('ar-IQ','Arabic (Iraq)') +,('ar-JO','Arabic (Jordan)') +,('ar-KW','Arabic (Kuwait)') +; +INSERT INTO codelang (code,country) VALUES +('ar-LB','Arabic (Lebanon)') +,('ar-LY','Arabic (Libya)') +,('ar-MA','Arabic (Morocco)') +,('ar-OM','Arabic (Oman)') +,('ar-QA','Arabic (Qatar)') +,('ar-SA','Arabic (Saudi Arabia)') +,('ar-SY','Arabic (Syria)') +,('ar-TN','Arabic (Tunisia)') +,('ar-YE','Arabic (Yemen)') +,('az','Azeri (Latin)') +; +INSERT INTO codelang (code,country) VALUES +('az-AZ','Azeri (Latin) (Azerbaijan)') +,('az-AZ','Azeri (Cyrillic) (Azerbaijan)') +,('be','Belarusian') +,('be-BY','Belarusian (Belarus)') +,('bg','Bulgarian') +,('bg-BG','Bulgarian (Bulgaria)') +,('bs-BA','Bosnian (Bosnia and Herzegovina)') +,('ca','Catalan') +,('ca-ES','Catalan (Spain)') +,('cs','Czech') +; +INSERT INTO codelang (code,country) VALUES +('cs-CZ','Czech (Czech Republic)') +,('cy','Welsh') +,('cy-GB','Welsh (United Kingdom)') +,('da','Danish') +,('da-DK','Danish (Denmark)') +,('de','German') +,('de-AT','German (Austria)') +,('de-CH','German (Switzerland)') +,('de-DE','German (Germany)') +,('de-LI','German (Liechtenstein)') +; +INSERT INTO codelang (code,country) VALUES +('de-LU','German (Luxembourg)') +,('dv','Divehi') +,('dv-MV','Divehi (Maldives)') +,('el','Greek') +,('el-GR','Greek (Greece)') +,('en','English') +,('en-AU','English (Australia)') +,('en-BZ','English (Belize)') +,('en-CA','English (Canada)') +,('en-CB','English (Caribbean)') +; +INSERT INTO codelang (code,country) VALUES +('en-GB','English (United Kingdom)') +,('en-IE','English (Ireland)') +,('en-JM','English (Jamaica)') +,('en-NZ','English (New Zealand)') +,('en-PH','English (Republic of the Philippines)') +,('en-TT','English (Trinidad and Tobago)') +,('en-US','English (United States)') +,('en-ZA','English (South Africa)') +,('en-ZW','English (Zimbabwe)') +,('eo','Esperanto') +; +INSERT INTO codelang (code,country) VALUES +('es','Spanish') +,('es-AR','Spanish (Argentina)') +,('es-BO','Spanish (Bolivia)') +,('es-CL','Spanish (Chile)') +,('es-CO','Spanish (Colombia)') +,('es-CR','Spanish (Costa Rica)') +,('es-DO','Spanish (Dominican Republic)') +,('es-EC','Spanish (Ecuador)') +,('es-ES','Spanish (Spain)') +; +INSERT INTO codelang (code,country) VALUES +('es-GT','Spanish (Guatemala)') +,('es-HN','Spanish (Honduras)') +,('es-MX','Spanish (Mexico)') +,('es-NI','Spanish (Nicaragua)') +,('es-PA','Spanish (Panama)') +,('es-PE','Spanish (Peru)') +,('es-PR','Spanish (Puerto Rico)') +,('es-PY','Spanish (Paraguay)') +,('es-SV','Spanish (El Salvador)') +,('es-UY','Spanish (Uruguay)') +; +INSERT INTO codelang (code,country) VALUES +('es-VE','Spanish (Venezuela)') +,('et','Estonian') +,('et-EE','Estonian (Estonia)') +,('eu','Basque') +,('eu-ES','Basque (Spain)') +,('fa','Farsi') +,('fa-IR','Farsi (Iran)') +,('fi','Finnish') +,('fi-FI','Finnish (Finland)') +,('fo','Faroese') +; +INSERT INTO codelang (code,country) VALUES +('fo-FO','Faroese (Faroe Islands)') +,('fr','French') +,('fr-BE','French (Belgium)') +,('fr-CA','French (Canada)') +,('fr-CH','French (Switzerland)') +,('fr-FR','French (France)') +,('fr-LU','French (Luxembourg)') +,('fr-MC','French (Principality of Monaco)') +,('gl','Galician') +,('gl-ES','Galician (Spain)') +; +INSERT INTO codelang (code,country) VALUES +('gu','Gujarati') +,('gu-IN','Gujarati (India)') +,('he','Hebrew') +,('he-IL','Hebrew (Israel)') +,('hi','Hindi') +,('hi-IN','Hindi (India)') +,('hr','Croatian') +,('hr-BA','Croatian (Bosnia and Herzegovina)') +,('hr-HR','Croatian (Croatia)') +,('hu','Hungarian') +; +INSERT INTO codelang (code,country) VALUES +('hu-HU','Hungarian (Hungary)') +,('hy','Armenian') +,('hy-AM','Armenian (Armenia)') +,('id','Indonesian') +,('id-ID','Indonesian (Indonesia)') +,('is','Icelandic') +,('is-IS','Icelandic (Iceland)') +,('it','Italian') +,('it-CH','Italian (Switzerland)') +,('it-IT','Italian (Italy)') +; +INSERT INTO codelang (code,country) VALUES +('ja','Japanese') +,('ja-JP','Japanese (Japan)') +,('ka','Georgian') +,('ka-GE','Georgian (Georgia)') +,('kk','Kazakh') +,('kk-KZ','Kazakh (Kazakhstan)') +,('kn','Kannada') +,('kn-IN','Kannada (India)') +,('ko','Korean') +,('ko-KR','Korean (Korea)') +; +INSERT INTO codelang (code,country) VALUES +('kok','Konkani') +,('kok-IN','Konkani (India)') +,('ky','Kyrgyz') +,('ky-KG','Kyrgyz (Kyrgyzstan)') +,('lt','Lithuanian') +,('lt-LT','Lithuanian (Lithuania)') +,('lv','Latvian') +,('lv-LV','Latvian (Latvia)') +,('mi','Maori') +,('mi-NZ','Maori (New Zealand)') +; +INSERT INTO codelang (code,country) VALUES +('mk','FYRO Macedonian') +,('mk-MK','FYRO Macedonian (Former Yugoslav Republic of Macedonia)') +,('mn','Mongolian') +,('mn-MN','Mongolian (Mongolia)') +,('mr','Marathi') +,('mr-IN','Marathi (India)') +,('ms','Malay') +,('ms-BN','Malay (Brunei Darussalam)') +,('ms-MY','Malay (Malaysia)') +,('mt','Maltese') +; +INSERT INTO codelang (code,country) VALUES +('mt-MT','Maltese (Malta)') +,('nb','Norwegian (Bokm?l)') +,('nb-NO','Norwegian (Bokm?l) (Norway)') +,('nl','Dutch') +,('nl-BE','Dutch (Belgium)') +,('nl-NL','Dutch (Netherlands)') +,('nn-NO','Norwegian (Nynorsk) (Norway)') +,('ns','Northern Sotho') +,('ns-ZA','Northern Sotho (South Africa)') +,('pa','Punjabi') +; +INSERT INTO codelang (code,country) VALUES +('pa-IN','Punjabi (India)') +,('pl','Polish') +,('pl-PL','Polish (Poland)') +,('ps','Pashto') +,('ps-AR','Pashto (Afghanistan)') +,('pt','Portuguese') +,('pt-BR','Portuguese (Brazil)') +,('pt-PT','Portuguese (Portugal)') +,('qu','Quechua') +,('qu-BO','Quechua (Bolivia)') +; +INSERT INTO codelang (code,country) VALUES +('qu-EC','Quechua (Ecuador)') +,('qu-PE','Quechua (Peru)') +,('ro','Romanian') +,('ro-RO','Romanian (Romania)') +,('ru','Russian') +,('ru-RU','Russian (Russia)') +,('sa','Sanskrit') +,('sa-IN','Sanskrit (India)') +,('se','Sami (Northern)') +,('se-FI','Sami (Northern) (Finland)') +; +INSERT INTO codelang (code,country) VALUES +('se-FI','Sami (Skolt) (Finland)') +,('se-FI','Sami (Inari) (Finland)') +,('se-NO','Sami (Northern) (Norway)') +,('se-NO','Sami (Lule) (Norway)') +,('se-NO','Sami (Southern) (Norway)') +,('se-SE','Sami (Northern) (Sweden)') +,('se-SE','Sami (Lule) (Sweden)') +,('se-SE','Sami (Southern) (Sweden)') +,('sk','Slovak') +,('sk-SK','Slovak (Slovakia)') +; +INSERT INTO codelang (code,country) VALUES +('sl','Slovenian') +,('sl-SI','Slovenian (Slovenia)') +,('sq','Albanian') +,('sq-AL','Albanian (Albania)') +,('sr-BA','Serbian (Latin) (Bosnia and Herzegovina)') +,('sr-BA','Serbian (Cyrillic) (Bosnia and Herzegovina)') +,('sr-SP','Serbian (Latin) (Serbia and Montenegro)') +,('sr-SP','Serbian (Cyrillic) (Serbia and Montenegro)') +,('sv','Swedish') +,('sv-FI','Swedish (Finland)') +; +INSERT INTO codelang (code,country) VALUES +('sv-SE','Swedish (Sweden)') +,('sw','Swahili') +,('sw-KE','Swahili (Kenya)') +,('syr','Syriac') +,('syr-SY','Syriac (Syria)') +,('ta','Tamil') +,('ta-IN','Tamil (India)') +,('te','Telugu') +,('te-IN','Telugu (India)') +,('th','Thai') +; +INSERT INTO codelang (code,country) VALUES +('th-TH','Thai (Thailand)') +,('tl','Tagalog') +,('tl-PH','Tagalog (Philippines)') +,('tn','Tswana') +,('tn-ZA','Tswana (South Africa)') +,('tr','Turkish') +,('tr-TR','Turkish (Turkey)') +,('tt','Tatar') +,('tt-RU','Tatar (Russia)') +,('ts','Tsonga') +; +INSERT INTO codelang (code,country) VALUES +('uk','Ukrainian') +,('uk-UA','Ukrainian (Ukraine)') +,('ur','Urdu') +,('ur-PK','Urdu (Islamic Republic of Pakistan)') +,('uz','Uzbek (Latin)') +,('uz-UZ','Uzbek (Latin) (Uzbekistan)') +,('uz-UZ','Uzbek (Cyrillic) (Uzbekistan)') +,('vi','Vietnamese') +,('vi-VN','Vietnamese (Viet Nam)') +,('xh','Xhosa') +; +INSERT INTO codelang (code,country) VALUES +('xh-ZA','Xhosa (South Africa)') +,('zh','Chinese') +,('zh-CN','Chinese (S)') +,('zh-HK','Chinese (Hong Kong)') +,('zh-MO','Chinese (Macau)') +,('zh-SG','Chinese (Singapore)') +,('zh-TW','Chinese (T)') +,('zu','Zulu') +,('zu-ZA','Zulu (South Africa)') +; +/***************************/ +-- Manual migrate + +CREATE TABLE country_code ( + code varchar(100) NULL, + country varchar(10000) NULL +); + +insert into country_code(code, country) +select distinct + t.code, + coalesce( + case when length(t.country_name2) = 1 then null else t.country_name2 end, + case when length(t.contry_name1) = 1 then null else t.contry_name1 end, + t.country + ) as country +from +( + select trim(c.code) as code, + substring(trim(c.country) from '\((.+)\)') as contry_name1, + substring( + substring(trim(c.country) from '\((.+)\)') + from '\((.*)$') as country_name2, + trim(c.country) as country + from codelang as c +) t; + +commit; + +--delete from location_country as lc + +INSERT INTO location_country +(code, "name", low_price, high_price, created, modified) +select distinct + lpad((row_number() over (order by t.country asc))::text, 3, '0') as code, + jsonb_build_object('en-GB', t.country), + 0 as low_price, + 100 as high_price, + now() as created, + now() as modified +from +( + select + distinct c.country + from country_code c +) t +; + +commit; + +--delete from translation_language as tl; + +INSERT INTO translation_language +(title, locale) +select + distinct + t.country as title, + t.code as locale +from +( + select + distinct c.country, c.code + from country_code c +) t +; + +commit; + + +--delete from location_country_languages + +INSERT INTO location_country_languages +(country_id, language_id) +select lc.id as country_id, + l.id as language_id +from location_country as lc +join ( + select tl.*, '"'||tl.title||'"' as country + from translation_language as tl +) l on l.country = (lc."name"::json->'en-GB')::text +; + +commit; + +drop table country_code; +drop table codelang; + +commit; \ No newline at end of file diff --git a/apps/location/migrations/remigrate_lang.sql b/apps/location/migrations/remigrate_lang.sql new file mode 100644 index 00000000..160ac93e --- /dev/null +++ b/apps/location/migrations/remigrate_lang.sql @@ -0,0 +1,391 @@ +SET search_path TO gm, public; + +CREATE TABLE codelang ( + code varchar(100) NULL, + country varchar(10000) NULL +); + + +INSERT INTO codelang (code,country) VALUES +('af','Afrikaans') +,('af-ZA','Afrikaans (South Africa)') +,('ar','Arabic') +,('ar-AE','Arabic (U.A.E.)') +,('ar-BH','Arabic (Bahrain)') +,('ar-DZ','Arabic (Algeria)') +,('ar-EG','Arabic (Egypt)') +,('ar-IQ','Arabic (Iraq)') +,('ar-JO','Arabic (Jordan)') +,('ar-KW','Arabic (Kuwait)') +; +INSERT INTO codelang (code,country) VALUES +('ar-LB','Arabic (Lebanon)') +,('ar-LY','Arabic (Libya)') +,('ar-MA','Arabic (Morocco)') +,('ar-OM','Arabic (Oman)') +,('ar-QA','Arabic (Qatar)') +,('ar-SA','Arabic (Saudi Arabia)') +,('ar-SY','Arabic (Syria)') +,('ar-TN','Arabic (Tunisia)') +,('ar-YE','Arabic (Yemen)') +,('az','Azeri (Latin)') +; +INSERT INTO codelang (code,country) VALUES +('az-AZ','Azeri (Latin) (Azerbaijan)') +,('az-AZ','Azeri (Cyrillic) (Azerbaijan)') +,('be','Belarusian') +,('be-BY','Belarusian (Belarus)') +,('bg','Bulgarian') +,('bg-BG','Bulgarian (Bulgaria)') +,('bs-BA','Bosnian (Bosnia and Herzegovina)') +,('ca','Catalan') +,('ca-ES','Catalan (Spain)') +,('cs','Czech') +; +INSERT INTO codelang (code,country) VALUES +('cs-CZ','Czech (Czech Republic)') +,('cy','Welsh') +,('cy-GB','Welsh (United Kingdom)') +,('da','Danish') +,('da-DK','Danish (Denmark)') +,('de','German') +,('de-AT','German (Austria)') +,('de-CH','German (Switzerland)') +,('de-DE','German (Germany)') +,('de-LI','German (Liechtenstein)') +; +INSERT INTO codelang (code,country) VALUES +('de-LU','German (Luxembourg)') +,('dv','Divehi') +,('dv-MV','Divehi (Maldives)') +,('el','Greek') +,('el-GR','Greek (Greece)') +,('en','English') +,('en-AU','English (Australia)') +,('en-BZ','English (Belize)') +,('en-CA','English (Canada)') +,('en-CB','English (Caribbean)') +; +INSERT INTO codelang (code,country) VALUES +('en-GB','English (United Kingdom)') +,('en-IE','English (Ireland)') +,('en-JM','English (Jamaica)') +,('en-NZ','English (New Zealand)') +,('en-PH','English (Republic of the Philippines)') +,('en-TT','English (Trinidad and Tobago)') +,('en-US','English (United States)') +,('en-ZA','English (South Africa)') +,('en-ZW','English (Zimbabwe)') +,('eo','Esperanto') +; +INSERT INTO codelang (code,country) VALUES +('es','Spanish') +,('es-AR','Spanish (Argentina)') +,('es-BO','Spanish (Bolivia)') +,('es-CL','Spanish (Chile)') +,('es-CO','Spanish (Colombia)') +,('es-CR','Spanish (Costa Rica)') +,('es-DO','Spanish (Dominican Republic)') +,('es-EC','Spanish (Ecuador)') +,('es-ES','Spanish (Castilian)') +,('es-ES','Spanish (Spain)') +; +INSERT INTO codelang (code,country) VALUES +('es-GT','Spanish (Guatemala)') +,('es-HN','Spanish (Honduras)') +,('es-MX','Spanish (Mexico)') +,('es-NI','Spanish (Nicaragua)') +,('es-PA','Spanish (Panama)') +,('es-PE','Spanish (Peru)') +,('es-PR','Spanish (Puerto Rico)') +,('es-PY','Spanish (Paraguay)') +,('es-SV','Spanish (El Salvador)') +,('es-UY','Spanish (Uruguay)') +; +INSERT INTO codelang (code,country) VALUES +('es-VE','Spanish (Venezuela)') +,('et','Estonian') +,('et-EE','Estonian (Estonia)') +,('eu','Basque') +,('eu-ES','Basque (Spain)') +,('fa','Farsi') +,('fa-IR','Farsi (Iran)') +,('fi','Finnish') +,('fi-FI','Finnish (Finland)') +,('fo','Faroese') +; +INSERT INTO codelang (code,country) VALUES +('fo-FO','Faroese (Faroe Islands)') +,('fr','French') +,('fr-BE','French (Belgium)') +,('fr-CA','French (Canada)') +,('fr-CH','French (Switzerland)') +,('fr-FR','French (France)') +,('fr-LU','French (Luxembourg)') +,('fr-MC','French (Principality of Monaco)') +,('gl','Galician') +,('gl-ES','Galician (Spain)') +; +INSERT INTO codelang (code,country) VALUES +('gu','Gujarati') +,('gu-IN','Gujarati (India)') +,('he','Hebrew') +,('he-IL','Hebrew (Israel)') +,('hi','Hindi') +,('hi-IN','Hindi (India)') +,('hr','Croatian') +,('hr-BA','Croatian (Bosnia and Herzegovina)') +,('hr-HR','Croatian (Croatia)') +,('hu','Hungarian') +; +INSERT INTO codelang (code,country) VALUES +('hu-HU','Hungarian (Hungary)') +,('hy','Armenian') +,('hy-AM','Armenian (Armenia)') +,('id','Indonesian') +,('id-ID','Indonesian (Indonesia)') +,('is','Icelandic') +,('is-IS','Icelandic (Iceland)') +,('it','Italian') +,('it-CH','Italian (Switzerland)') +,('it-IT','Italian (Italy)') +; +INSERT INTO codelang (code,country) VALUES +('ja','Japanese') +,('ja-JP','Japanese (Japan)') +,('ka','Georgian') +,('ka-GE','Georgian (Georgia)') +,('kk','Kazakh') +,('kk-KZ','Kazakh (Kazakhstan)') +,('kn','Kannada') +,('kn-IN','Kannada (India)') +,('ko','Korean') +,('ko-KR','Korean (Korea)') +; +INSERT INTO codelang (code,country) VALUES +('kok','Konkani') +,('kok-IN','Konkani (India)') +,('ky','Kyrgyz') +,('ky-KG','Kyrgyz (Kyrgyzstan)') +,('lt','Lithuanian') +,('lt-LT','Lithuanian (Lithuania)') +,('lv','Latvian') +,('lv-LV','Latvian (Latvia)') +,('mi','Maori') +,('mi-NZ','Maori (New Zealand)') +; +INSERT INTO codelang (code,country) VALUES +('mk','FYRO Macedonian') +,('mk-MK','FYRO Macedonian (Former Yugoslav Republic of Macedonia)') +,('mn','Mongolian') +,('mn-MN','Mongolian (Mongolia)') +,('mr','Marathi') +,('mr-IN','Marathi (India)') +,('ms','Malay') +,('ms-BN','Malay (Brunei Darussalam)') +,('ms-MY','Malay (Malaysia)') +,('mt','Maltese') +; +INSERT INTO codelang (code,country) VALUES +('mt-MT','Maltese (Malta)') +,('nb','Norwegian (Bokm?l)') +,('nb-NO','Norwegian (Bokm?l) (Norway)') +,('nl','Dutch') +,('nl-BE','Dutch (Belgium)') +,('nl-NL','Dutch (Netherlands)') +,('nn-NO','Norwegian (Nynorsk) (Norway)') +,('ns','Northern Sotho') +,('ns-ZA','Northern Sotho (South Africa)') +,('pa','Punjabi') +; +INSERT INTO codelang (code,country) VALUES +('pa-IN','Punjabi (India)') +,('pl','Polish') +,('pl-PL','Polish (Poland)') +,('ps','Pashto') +,('ps-AR','Pashto (Afghanistan)') +,('pt','Portuguese') +,('pt-BR','Portuguese (Brazil)') +,('pt-PT','Portuguese (Portugal)') +,('qu','Quechua') +,('qu-BO','Quechua (Bolivia)') +; +INSERT INTO codelang (code,country) VALUES +('qu-EC','Quechua (Ecuador)') +,('qu-PE','Quechua (Peru)') +,('ro','Romanian') +,('ro-RO','Romanian (Romania)') +,('ru','Russian') +,('ru-RU','Russian (Russia)') +,('sa','Sanskrit') +,('sa-IN','Sanskrit (India)') +,('se','Sami (Northern)') +,('se-FI','Sami (Northern) (Finland)') +; +INSERT INTO codelang (code,country) VALUES +('se-FI','Sami (Skolt) (Finland)') +,('se-FI','Sami (Inari) (Finland)') +,('se-NO','Sami (Northern) (Norway)') +,('se-NO','Sami (Lule) (Norway)') +,('se-NO','Sami (Southern) (Norway)') +,('se-SE','Sami (Northern) (Sweden)') +,('se-SE','Sami (Lule) (Sweden)') +,('se-SE','Sami (Southern) (Sweden)') +,('sk','Slovak') +,('sk-SK','Slovak (Slovakia)') +; +INSERT INTO codelang (code,country) VALUES +('sl','Slovenian') +,('sl-SI','Slovenian (Slovenia)') +,('sq','Albanian') +,('sq-AL','Albanian (Albania)') +,('sr-BA','Serbian (Latin) (Bosnia and Herzegovina)') +,('sr-BA','Serbian (Cyrillic) (Bosnia and Herzegovina)') +,('sr-SP','Serbian (Latin) (Serbia and Montenegro)') +,('sr-SP','Serbian (Cyrillic) (Serbia and Montenegro)') +,('sv','Swedish') +,('sv-FI','Swedish (Finland)') +; +INSERT INTO codelang (code,country) VALUES +('sv-SE','Swedish (Sweden)') +,('sw','Swahili') +,('sw-KE','Swahili (Kenya)') +,('syr','Syriac') +,('syr-SY','Syriac (Syria)') +,('ta','Tamil') +,('ta-IN','Tamil (India)') +,('te','Telugu') +,('te-IN','Telugu (India)') +,('th','Thai') +; +INSERT INTO codelang (code,country) VALUES +('th-TH','Thai (Thailand)') +,('tl','Tagalog') +,('tl-PH','Tagalog (Philippines)') +,('tn','Tswana') +,('tn-ZA','Tswana (South Africa)') +,('tr','Turkish') +,('tr-TR','Turkish (Turkey)') +,('tt','Tatar') +,('tt-RU','Tatar (Russia)') +,('ts','Tsonga') +; +INSERT INTO codelang (code,country) VALUES +('uk','Ukrainian') +,('uk-UA','Ukrainian (Ukraine)') +,('ur','Urdu') +,('ur-PK','Urdu (Islamic Republic of Pakistan)') +,('uz','Uzbek (Latin)') +,('uz-UZ','Uzbek (Latin) (Uzbekistan)') +,('uz-UZ','Uzbek (Cyrillic) (Uzbekistan)') +,('vi','Vietnamese') +,('vi-VN','Vietnamese (Viet Nam)') +,('xh','Xhosa') +; +INSERT INTO codelang (code,country) VALUES +('xh-ZA','Xhosa (South Africa)') +,('zh','Chinese') +,('zh-CN','Chinese (S)') +,('zh-HK','Chinese (Hong Kong)') +,('zh-MO','Chinese (Macau)') +,('zh-SG','Chinese (Singapore)') +,('zh-TW','Chinese (T)') +,('zu','Zulu') +,('zu-ZA','Zulu (South Africa)') +; +/***************************/ +-- Manual migrate + +CREATE TABLE country_code ( + code varchar(100) NULL, + country varchar(10000) NULL +); + +insert into country_code(code, country) +select distinct + t.code, + coalesce( + case when length(t.country_name2) = 1 then null else t.country_name2 end, + case when length(t.contry_name1) = 1 then null else t.contry_name1 end, + t.country + ) as country +from +( + select trim(c.code) as code, + substring(trim(c.country) from '\((.+)\)') as contry_name1, + substring( + substring(trim(c.country) from '\((.+)\)') + from '\((.*)$') as country_name2, + trim(c.country) as country + from codelang as c +) t; + +commit; + + +delete from location_country_languages as lcl +where lcl.country_id in +( + select + lc.id + from + ( + select + lpad((row_number() over (order by t.country asc))::text, 3, '0') as code, + jsonb_build_object('en-GB', t.country) as "name" + from + ( + select + distinct c.country + from country_code c + ) t + ) d + join location_country lc on lc.code = d.code and d."name"=lc."name" +) +; +commit; + + +delete from location_country as lcl +where lcl.id in +( + select + lc.id + from + ( + select + lpad((row_number() over (order by t.country asc))::text, 3, '0') as code, + jsonb_build_object('en-GB', t.country) as "name" + from + ( + select + distinct c.country + from country_code c + ) t + ) d + join location_country lc on lc.code = d.code and d."name"=lc."name" +) +; + +commit; + + +delete from translation_language tl +where tl.id in +( + SELECT tl.id + FROM + ( + select + distinct c.country, c.code + from country_code c + ) t + JOIN translation_language tl ON tl.locale = t.code and tl.title = t.country +); + +commit; + +drop table country_code; +drop table codelang; + +commit; \ No newline at end of file diff --git a/apps/location/models.py b/apps/location/models.py index 7084385f..2b7aa363 100644 --- a/apps/location/models.py +++ b/apps/location/models.py @@ -6,6 +6,7 @@ from django.db.transaction import on_commit from django.dispatch import receiver from django.utils.translation import gettext_lazy as _ from utils.models import ProjectBaseMixin, SVGImageMixin, TranslatedFieldsMixin, TJSONField +from translation.models import Language class Country(TranslatedFieldsMixin, SVGImageMixin, ProjectBaseMixin): @@ -18,6 +19,11 @@ class Country(TranslatedFieldsMixin, SVGImageMixin, ProjectBaseMixin): code = models.CharField(max_length=255, unique=True, verbose_name=_('Code')) low_price = models.IntegerField(default=25, verbose_name=_('Low price')) high_price = models.IntegerField(default=50, verbose_name=_('High price')) + languages = models.ManyToManyField(Language, verbose_name=_('Languages')) + + @property + def country_id(self): + return self.id class Meta: """Meta class.""" @@ -71,6 +77,7 @@ class City(models.Model): class Address(models.Model): + """Address model.""" city = models.ForeignKey(City, verbose_name=_('city'), on_delete=models.CASCADE) street_name_1 = models.CharField( @@ -98,17 +105,21 @@ class Address(models.Model): @property def latitude(self): - return self.coordinates.y + return self.coordinates.y if self.coordinates else float(0) @property def longitude(self): - return self.coordinates.x + return self.coordinates.x if self.coordinates else float(0) @property def location_field_indexing(self): return {'lat': self.latitude, 'lon': self.longitude} + @property + def country_id(self): + return self.city.country_id + # todo: Make recalculate price levels @receiver(post_save, sender=Country) diff --git a/apps/location/serializers/back.py b/apps/location/serializers/back.py index f3b36e64..f25aacf6 100644 --- a/apps/location/serializers/back.py +++ b/apps/location/serializers/back.py @@ -1,11 +1,8 @@ -from django.contrib.gis.geos import Point -from rest_framework import serializers - from location import models from location.serializers import common -class AddressCreateSerializer(common.AddressSerializer): +class AddressCreateSerializer(common.AddressDetailSerializer): """Address create serializer.""" diff --git a/apps/location/serializers/common.py b/apps/location/serializers/common.py index 63fe39e1..87d0df4e 100644 --- a/apps/location/serializers/common.py +++ b/apps/location/serializers/common.py @@ -1,7 +1,9 @@ +"""Location app common serializers.""" from django.contrib.gis.geos import Point +from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers - from location import models +from utils.serializers import TranslatedField class CountrySerializer(serializers.ModelSerializer): @@ -20,6 +22,18 @@ class CountrySerializer(serializers.ModelSerializer): ] +class CountrySimpleSerializer(serializers.ModelSerializer): + """Simple country serializer.""" + + name_translated = TranslatedField() + + class Meta: + """Meta class.""" + + model = models.Country + fields = ('id', 'code', 'name_translated') + + class RegionSerializer(serializers.ModelSerializer): """Region serializer""" @@ -70,47 +84,67 @@ class CitySerializer(serializers.ModelSerializer): ] -class AddressSerializer(serializers.ModelSerializer): - """Address serializer.""" - city_id = serializers.PrimaryKeyRelatedField( - source='city', - queryset=models.City.objects.all()) - city = CitySerializer(read_only=True) - geo_lon = serializers.FloatField(allow_null=True) - geo_lat = serializers.FloatField(allow_null=True) +class AddressBaseSerializer(serializers.ModelSerializer): + """Serializer for address obj in related objects.""" + + latitude = serializers.FloatField(allow_null=True) + longitude = serializers.FloatField(allow_null=True) + + # todo: remove this fields (backward compatibility) + geo_lon = serializers.FloatField(source='longitude', allow_null=True, + read_only=True) + geo_lat = serializers.FloatField(source='latitude', allow_null=True, + read_only=True) class Meta: + """Meta class.""" + model = models.Address - fields = [ + fields = ( 'id', - 'city_id', - 'city', 'street_name_1', 'street_name_2', 'number', 'postal_code', + 'latitude', + 'longitude', + + # todo: remove this fields (backward compatibility) 'geo_lon', - 'geo_lat' - ] + 'geo_lat', + ) + + def validate_latitude(self, value): + if -90 <= value <= 90: + return value + raise serializers.ValidationError(_('Invalid value')) + + def validate_longitude(self, value): + if -180 <= value <= 180: + return value + raise serializers.ValidationError(_('Invalid value')) def validate(self, attrs): - # if geo_lat and geo_lon was sent - geo_lat = attrs.pop('geo_lat') if 'geo_lat' in attrs else None - geo_lon = attrs.pop('geo_lon') if 'geo_lon' in attrs else None - - if geo_lat and geo_lon: - # Point(longitude, latitude) - attrs['coordinates'] = Point(geo_lat, geo_lon) + # validate coordinates + latitude = attrs.pop('latitude', None) + longitude = attrs.pop('longitude', None) + if latitude is not None and longitude is not None: + attrs['coordinates'] = Point(longitude, latitude) return attrs - def to_representation(self, instance): - """Override to_representation method""" - if instance.coordinates and isinstance(instance.coordinates, Point): - # Point(longitude, latitude) - setattr(instance, 'geo_lat', instance.coordinates.x) - setattr(instance, 'geo_lon', instance.coordinates.y) - else: - setattr(instance, 'geo_lat', float(0)) - setattr(instance, 'geo_lon', float(0)) - return super().to_representation(instance) +class AddressDetailSerializer(AddressBaseSerializer): + """Address serializer.""" + + city_id = serializers.PrimaryKeyRelatedField( + source='city', write_only=True, + queryset=models.City.objects.all()) + city = CitySerializer(read_only=True) + + class Meta(AddressBaseSerializer.Meta): + """Meta class.""" + + fields = AddressBaseSerializer.Meta.fields + ( + 'city_id', + 'city', + ) diff --git a/apps/location/tests.py b/apps/location/tests.py index 7ce503c2..cb574036 100644 --- a/apps/location/tests.py +++ b/apps/location/tests.py @@ -1,3 +1,245 @@ -from django.test import TestCase +import json -# Create your tests here. +from rest_framework.test import APITestCase +from account.models import User +from rest_framework import status +from http.cookies import SimpleCookie + +from location.models import City, Region, Country, Language +from django.contrib.gis.geos import Point +from account.models import Role, UserRole + + +class BaseTestCase(APITestCase): + def setUp(self): + self.username = 'sedragurda' + self.password = 'sedragurdaredips19' + self.email = 'sedragurda@desoz.com' + self.newsletter = True + self.user = User.objects.create_user( + username=self.username, email=self.email, password=self.password) + + # get tokens + + # self.user.is_superuser = True + # self.user.save() + + tokkens = User.create_jwt_tokens(self.user) + self.client.cookies = SimpleCookie( + {'access_token': tokkens.get('access_token'), + 'refresh_token': tokkens.get('refresh_token')}) + + self.lang = Language.objects.get( + title='Russia', + locale='ru-RU' + ) + + self.country_ru = Country.objects.get( + name={"en-GB": "Russian"} + ) + + self.role = Role.objects.create(role=Role.COUNTRY_ADMIN, + country=self.country_ru) + self.role.save() + + self.user_role = UserRole.objects.create(user=self.user, role=self.role) + + self.user_role.save() + + +class CountryTests(BaseTestCase): + def setUp(self): + super().setUp() + + def test_country_CRUD(self): + data = { + 'name': {"ru-RU": "NewCountry"}, + 'code': 'test1' + } + + response = self.client.post('/api/back/location/countries/', data=data, format='json') + response_data = response.json() + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + country = Country.objects.get(pk=response_data["id"]) + role = Role.objects.create(role=Role.COUNTRY_ADMIN, country=country) + role.save() + + user_role = UserRole.objects.create(user=self.user, role=role) + + user_role.save() + + response = self.client.get('/api/back/location/countries/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.get(f'/api/back/location/countries/{response_data["id"]}/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + update_data = { + 'name': json.dumps({"en-GB": "Test new country"}) + } + + response = self.client.patch(f'/api/back/location/countries/{response_data["id"]}/', data=update_data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.delete(f'/api/back/location/countries/{response_data["id"]}/', format='json') + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) + + +class RegionTests(BaseTestCase): + + def setUp(self): + super().setUp() + self.country = Country.objects.create( + name=json.dumps({"en-GB": "Test country"}), + code="test" + ) + + role = Role.objects.create(role=Role.COUNTRY_ADMIN, country=self.country) + role.save() + + user_role = UserRole.objects.create(user=self.user, role=role) + + user_role.save() + + + def test_region_CRUD(self): + response = self.client.get('/api/back/location/regions/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + data = { + 'name': 'Test country', + 'code': 'test', + 'country_id': self.country.id + } + + response = self.client.post('/api/back/location/regions/', data=data, format='json') + response_data = response.json() + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + response = self.client.get(f'/api/back/location/regions/{response_data["id"]}/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + update_data = { + 'name': json.dumps({"en-GB": "Test new country"}) + } + + response = self.client.patch(f'/api/back/location/regions/{response_data["id"]}/', data=update_data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.delete(f'/api/back/location/regions/{response_data["id"]}/', format='json') + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) + + +class CityTests(BaseTestCase): + + def setUp(self): + super().setUp() + + self.country = Country.objects.create( + name=json.dumps({"en-GB": "Test country"}), + code="test" + ) + + self.region = Region.objects.create( + name="Test region", + code="812", + country=self.country + ) + + role = Role.objects.create(role=Role.COUNTRY_ADMIN, country=self.country) + role.save() + + user_role = UserRole.objects.create(user=self.user, role=role) + + user_role.save() + + def test_city_CRUD(self): + response = self.client.get('/api/back/location/cities/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + data = { + 'name': 'Test country', + 'code': 'test', + 'country_id': self.country.id, + 'region_id': self.region.id + } + + response = self.client.post('/api/back/location/cities/', data=data, format='json') + response_data = response.json() + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + response = self.client.get(f'/api/back/location/cities/{response_data["id"]}/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + update_data = { + 'name': json.dumps({"en-GB": "Test new country"}) + } + + response = self.client.patch(f'/api/back/location/cities/{response_data["id"]}/', data=update_data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.delete(f'/api/back/location/cities/{response_data["id"]}/', format='json') + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) + + +class AddressTests(BaseTestCase): + + def setUp(self): + super().setUp() + + + self.country = Country.objects.create( + name=json.dumps({"en-GB": "Test country"}), + code="test" + ) + + self.region = Region.objects.create( + name="Test region", + code="812", + country=self.country + ) + + self.city = City.objects.create( + name="Test region", + code="812", + region=self.region, + country=self.country + ) + + role = Role.objects.create(role=Role.COUNTRY_ADMIN, country=self.country) + role.save() + + user_role = UserRole.objects.create(user=self.user, role=role) + + user_role.save() + + def test_address_CRUD(self): + response = self.client.get('/api/back/location/addresses/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + data = { + 'city_id': self.city.id, + 'number': '+79999999', + "latitude": 37.0625, + "longitude": -95.677068, + "geo_lon": -95.677068, + "geo_lat": 37.0625 + } + + response = self.client.post('/api/back/location/addresses/', data=data, format='json') + response_data = response.json() + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + response = self.client.get(f'/api/back/location/addresses/{response_data["id"]}/', format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + + update_data = { + 'number': '+79999991' + } + + response = self.client.patch(f'/api/back/location/addresses/{response_data["id"]}/', data=update_data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.delete(f'/api/back/location/addresses/{response_data["id"]}/', format='json') + self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) diff --git a/apps/location/urls/web.py b/apps/location/urls/web.py index cac89037..e86a3992 100644 --- a/apps/location/urls/web.py +++ b/apps/location/urls/web.py @@ -1,7 +1,6 @@ """Location app web urlconf.""" from location.urls.common import urlpatterns as common_urlpatterns - urlpatterns = [] -urlpatterns.extend(common_urlpatterns) \ No newline at end of file +urlpatterns.extend(common_urlpatterns) diff --git a/apps/location/views/back.py b/apps/location/views/back.py index 69ec28bc..cb8246a4 100644 --- a/apps/location/views/back.py +++ b/apps/location/views/back.py @@ -1,53 +1,59 @@ """Location app views.""" from rest_framework import generics -from rest_framework import permissions from location import models, serializers from location.views import common - +from utils.permissions import IsCountryAdmin # Address class AddressListCreateView(common.AddressViewMixin, generics.ListCreateAPIView): """Create view for model Address.""" - serializer_class = serializers.AddressSerializer + serializer_class = serializers.AddressDetailSerializer queryset = models.Address.objects.all() + permission_classes = [IsCountryAdmin] class AddressRUDView(common.AddressViewMixin, generics.RetrieveUpdateDestroyAPIView): """RUD view for model Address.""" - serializer_class = serializers.AddressSerializer + serializer_class = serializers.AddressDetailSerializer queryset = models.Address.objects.all() + permission_classes = [IsCountryAdmin] # City class CityListCreateView(common.CityViewMixin, generics.ListCreateAPIView): """Create view for model City.""" serializer_class = serializers.CitySerializer - + permission_classes = [IsCountryAdmin] class CityRUDView(common.CityViewMixin, generics.RetrieveUpdateDestroyAPIView): """RUD view for model City.""" serializer_class = serializers.CitySerializer + permission_classes = [IsCountryAdmin] # Region class RegionListCreateView(common.RegionViewMixin, generics.ListCreateAPIView): """Create view for model Region""" serializer_class = serializers.RegionSerializer - + permission_classes = [IsCountryAdmin] class RegionRUDView(common.RegionViewMixin, generics.RetrieveUpdateDestroyAPIView): """Retrieve view for model Region""" serializer_class = serializers.RegionSerializer + permission_classes = [IsCountryAdmin] # Country -class CountryListCreateView(common.CountryViewMixin, generics.ListCreateAPIView): +class CountryListCreateView(generics.ListCreateAPIView): """List/Create view for model Country.""" + queryset = models.Country.objects.all() serializer_class = serializers.CountryBackSerializer pagination_class = None + permission_classes = [IsCountryAdmin] - -class CountryRUDView(common.CountryViewMixin, generics.RetrieveUpdateDestroyAPIView): +class CountryRUDView(generics.RetrieveUpdateDestroyAPIView): """RUD view for model Country.""" serializer_class = serializers.CountryBackSerializer + permission_classes = [IsCountryAdmin] + queryset = models.Country.objects.all() \ No newline at end of file diff --git a/apps/location/views/common.py b/apps/location/views/common.py index 6bc332ad..792fce91 100644 --- a/apps/location/views/common.py +++ b/apps/location/views/common.py @@ -100,17 +100,17 @@ class CityUpdateView(CityViewMixin, generics.UpdateAPIView): # Address class AddressCreateView(AddressViewMixin, generics.CreateAPIView): """Create view for model Address""" - serializer_class = serializers.AddressSerializer + serializer_class = serializers.AddressDetailSerializer class AddressRetrieveView(AddressViewMixin, generics.RetrieveAPIView): """Retrieve view for model Address""" - serializer_class = serializers.AddressSerializer + serializer_class = serializers.AddressDetailSerializer class AddressListView(AddressViewMixin, generics.ListAPIView): """List view for model Address""" permission_classes = (permissions.AllowAny, ) - serializer_class = serializers.AddressSerializer + serializer_class = serializers.AddressDetailSerializer diff --git a/apps/main/admin.py b/apps/main/admin.py index bdbfe46e..f14a3470 100644 --- a/apps/main/admin.py +++ b/apps/main/admin.py @@ -25,22 +25,6 @@ class AwardAdmin(admin.ModelAdmin): # list_display_links = ['id', '__str__'] -@admin.register(models.MetaData) -class MetaDataAdmin(admin.ModelAdmin): - """MetaData admin.""" - - -@admin.register(models.MetaDataCategory) -class MetaDataCategoryAdmin(admin.ModelAdmin): - """MetaData admin.""" - list_display = ['id', 'country', 'content_type'] - - -@admin.register(models.MetaDataContent) -class MetaDataContentAdmin(admin.ModelAdmin): - """MetaDataContent admin""" - - @admin.register(models.Currency) class CurrencContentAdmin(admin.ModelAdmin): """CurrencContent admin""" diff --git a/apps/main/methods.py b/apps/main/methods.py index 3d4349e4..845a99a4 100644 --- a/apps/main/methods.py +++ b/apps/main/methods.py @@ -1,9 +1,12 @@ """Main app methods.""" import logging +from typing import Tuple, Optional + from django.conf import settings from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception -from main import models +from geoip2.models import City +from main import models logger = logging.getLogger(__name__) @@ -32,12 +35,24 @@ def determine_country_code(ip_addr): country_code = geoip.country_code(ip_addr) country_code = country_code.lower() except GeoIP2Exception as ex: - logger.error(f'GEOIP Exception: {ex}') + logger.info(f'GEOIP Exception: {ex}. ip: {ip_addr}') except Exception as ex: logger.error(f'GEOIP Base exception: {ex}') return country_code +def determine_coordinates(ip_addr: str) -> Tuple[Optional[float], Optional[float]]: + if ip_addr: + try: + geoip = GeoIP2() + return geoip.coords(ip_addr) + except GeoIP2Exception as ex: + logger.warning(f'GEOIP Exception: {ex}. ip: {ip_addr}') + except Exception as ex: + logger.warning(f'GEOIP Base exception: {ex}') + return None, None + + def determine_user_site_url(country_code): """Determine user's site url.""" try: @@ -59,3 +74,12 @@ def determine_user_site_url(country_code): return site.site_url +def determine_user_city(ip_addr: str) -> Optional[City]: + try: + geoip = GeoIP2() + return geoip.city(ip_addr) + except GeoIP2Exception as ex: + logger.warning(f'GEOIP Exception: {ex}. ip: {ip_addr}') + except Exception as ex: + logger.warning(f'GEOIP Base exception: {ex}') + return None diff --git a/apps/main/migrations/0017_feature_route.py b/apps/main/migrations/0017_feature_route.py new file mode 100644 index 00000000..0b0f46bb --- /dev/null +++ b/apps/main/migrations/0017_feature_route.py @@ -0,0 +1,19 @@ +# Generated by Django 2.2.4 on 2019-10-07 14:39 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('main', '0016_merge_20190919_0954'), + ] + + operations = [ + migrations.AddField( + model_name='feature', + name='route', + field=models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.PROTECT, to='main.Page'), + ), + ] diff --git a/apps/main/migrations/0018_feature_source.py b/apps/main/migrations/0018_feature_source.py new file mode 100644 index 00000000..cf94cad2 --- /dev/null +++ b/apps/main/migrations/0018_feature_source.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-10-07 14:51 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('main', '0017_feature_route'), + ] + + operations = [ + migrations.AddField( + model_name='feature', + name='source', + field=models.PositiveSmallIntegerField(choices=[(0, 'Mobile'), (1, 'Web'), (2, 'All')], default=0, verbose_name='Source'), + ), + ] diff --git a/apps/main/models.py b/apps/main/models.py index fcf8667b..46598257 100644 --- a/apps/main/models.py +++ b/apps/main/models.py @@ -1,19 +1,23 @@ """Main app models.""" +from typing import Iterable + from django.conf import settings from django.contrib.contenttypes import fields as generic +from django.contrib.contenttypes.models import ContentType from django.contrib.postgres.fields import JSONField from django.db import models +from django.db.models import Q from django.utils.translation import gettext_lazy as _ -from django.contrib.contenttypes.models import ContentType from advertisement.models import Advertisement +from configuration.models import TranslationSettings from location.models import Country from main import methods from review.models import Review from utils.models import (ProjectBaseMixin, TJSONField, - TranslatedFieldsMixin, ImageMixin) + TranslatedFieldsMixin, ImageMixin, PlatformMixin) from utils.querysets import ContentTypeQuerySetMixin -from configuration.models import TranslationSettings + # # @@ -109,7 +113,6 @@ class SiteSettingsQuerySet(models.QuerySet): class SiteSettings(ProjectBaseMixin): - subdomain = models.CharField(max_length=255, db_index=True, unique=True, verbose_name=_('Subdomain')) country = models.OneToOneField(Country, on_delete=models.PROTECT, @@ -150,7 +153,8 @@ class SiteSettings(ProjectBaseMixin): @property def published_sitefeatures(self): - return self.sitefeature_set.filter(published=True) + return self.sitefeature_set\ + .filter(Q(published=True) and Q(feature__source__in=[PlatformMixin.WEB, PlatformMixin.ALL])) @property def site_url(self): @@ -159,11 +163,27 @@ class SiteSettings(ProjectBaseMixin): domain=settings.SITE_DOMAIN_URI) -class Feature(ProjectBaseMixin): +class Page(models.Model): + """Page model.""" + + page_name = models.CharField(max_length=255, unique=True) + advertisements = models.ManyToManyField(Advertisement) + + class Meta: + """Meta class.""" + verbose_name = _('Page') + verbose_name_plural = _('Pages') + + def __str__(self): + return f'{self.page_name}' + + +class Feature(ProjectBaseMixin, PlatformMixin): """Feature model.""" slug = models.CharField(max_length=255, unique=True) priority = models.IntegerField(unique=True, null=True, default=None) + route = models.ForeignKey(Page, on_delete=models.PROTECT, null=True, default=None) site_settings = models.ManyToManyField(SiteSettings, through='SiteFeature') class Meta: @@ -181,6 +201,12 @@ class SiteFeatureQuerySet(models.QuerySet): def published(self, switcher=True): return self.filter(published=switcher) + def by_country_code(self, country_code: str): + return self.filter(site_settings__country__code=country_code) + + def by_sources(self, sources: Iterable[int]): + return self.filter(feature__source__in=sources) + class SiteFeature(ProjectBaseMixin): """SiteFeature model.""" @@ -318,9 +344,9 @@ class Carousel(models.Model): @property def vintage_year(self): if hasattr(self.content_object, 'reviews'): - review_qs = self.content_object.reviews.by_status(Review.READY) - if review_qs.exists(): - return review_qs.last().vintage + last_review = self.content_object.reviews.by_status(Review.READY).last() + if last_review: + return last_review.vintage @property def toque_number(self): @@ -333,27 +359,21 @@ class Carousel(models.Model): return self.content_object.public_mark @property - def image(self): - if hasattr(self.content_object.image, 'url'): - return self.content_object.image - if hasattr(self.content_object.image.image, 'url'): - return self.content_object.image.image + def image_url(self): + if hasattr(self.content_object, 'image_url'): + return self.content_object.image_url + + @property + def slug(self): + if hasattr(self.content_object, 'slug'): + return self.content_object.slug + + @property + def the_most_recent_award(self): + if hasattr(self.content_object, 'the_most_recent_award'): + return self.content_object.the_most_recent_award @property def model_name(self): - return self.content_object.__class__.__name__ - - -class Page(models.Model): - """Page model.""" - - page_name = models.CharField(max_length=255, unique=True) - advertisements = models.ManyToManyField(Advertisement) - - class Meta: - """Meta class.""" - verbose_name = _('Page') - verbose_name_plural = _('Pages') - - def __str__(self): - return f'{self.page_name}' + if hasattr(self.content_object, 'establishment_type'): + return self.content_object.establishment_type.name_translated diff --git a/apps/main/serializers.py b/apps/main/serializers.py index 607e3a30..d425016d 100644 --- a/apps/main/serializers.py +++ b/apps/main/serializers.py @@ -1,9 +1,10 @@ """Main app serializers.""" from rest_framework import serializers - from advertisement.serializers.web import AdvertisementSerializer from location.serializers import CountrySerializer from main import models +from establishment.models import Establishment +from utils.serializers import TranslatedField class FeatureSerializer(serializers.ModelSerializer): @@ -24,6 +25,8 @@ class SiteFeatureSerializer(serializers.ModelSerializer): id = serializers.IntegerField(source='feature.id') slug = serializers.CharField(source='feature.slug') priority = serializers.IntegerField(source='feature.priority') + route = serializers.CharField(source='feature.route.page_name') + source = serializers.IntegerField(source='feature.source') class Meta: """Meta class.""" @@ -31,7 +34,9 @@ class SiteFeatureSerializer(serializers.ModelSerializer): fields = ('main', 'id', 'slug', - 'priority' + 'priority', + 'route', + 'source' ) @@ -109,16 +114,16 @@ class AwardSerializer(AwardBaseSerializer): class MetaDataContentSerializer(serializers.ModelSerializer): - id = serializers.IntegerField(source='metadata.id', read_only=True, ) - label_translated = serializers.CharField( - source='metadata.label_translated', read_only=True, allow_null=True) + """MetaData content serializer.""" + + id = serializers.IntegerField(source='metadata.id', read_only=True) + label_translated = TranslatedField(source='metadata.label_translated') class Meta: + """Meta class.""" + model = models.MetaDataContent - fields = [ - 'id', - 'label_translated', - ] + fields = ('id', 'label_translated') class CurrencySerializer(serializers.ModelSerializer): @@ -136,11 +141,12 @@ class CarouselListSerializer(serializers.ModelSerializer): """Serializer for retrieving list of carousel items.""" model_name = serializers.CharField() name = serializers.CharField() - toque_number = serializers.CharField() - public_mark = serializers.CharField() - image = serializers.ImageField() + toque_number = serializers.IntegerField() + public_mark = serializers.IntegerField() + image = serializers.URLField(source='image_url') awards = AwardBaseSerializer(many=True) vintage_year = serializers.IntegerField() + last_award = AwardBaseSerializer(source='the_most_recent_award', allow_null=True) class Meta: """Meta class.""" @@ -154,6 +160,8 @@ class CarouselListSerializer(serializers.ModelSerializer): 'public_mark', 'image', 'vintage_year', + 'last_award', + 'slug', ] diff --git a/apps/main/urls.py b/apps/main/urls.py deleted file mode 100644 index a74c0b49..00000000 --- a/apps/main/urls.py +++ /dev/null @@ -1,14 +0,0 @@ -"""Main app urls.""" -from django.urls import path -from main import views - -app = 'main' - -urlpatterns = [ - path('determine-site/', views.DetermineSiteView.as_view(), name='determine-site'), - path('sites/', views.SiteListView.as_view(), name='site-list'), - path('site-settings//', views.SiteSettingsView.as_view(), name='site-settings'), - path('awards/', views.AwardView.as_view(), name='awards_list'), - path('awards//', views.AwardRetrieveView.as_view(), name='awards_retrieve'), - path('carousel/', views.CarouselListView.as_view(), name='carousel-list'), -] \ No newline at end of file diff --git a/apps/main/urls/__init__.py b/apps/main/urls/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/main/urls/common.py b/apps/main/urls/common.py new file mode 100644 index 00000000..bac16add --- /dev/null +++ b/apps/main/urls/common.py @@ -0,0 +1,12 @@ +"""Main app urls.""" +from django.urls import path +from main.views.common import * + +app = 'main' + +common_urlpatterns = [ + path('awards/', AwardView.as_view(), name='awards_list'), + path('awards//', AwardRetrieveView.as_view(), name='awards_retrieve'), + path('carousel/', CarouselListView.as_view(), name='carousel-list'), +path('determine-location/', DetermineLocation.as_view(), name='determine-location') +] diff --git a/apps/main/urls/mobile.py b/apps/main/urls/mobile.py new file mode 100644 index 00000000..b0383d4e --- /dev/null +++ b/apps/main/urls/mobile.py @@ -0,0 +1,11 @@ +from main.urls.common import common_urlpatterns + +from django.urls import path + +from main.views.mobile import FeaturesView + +urlpatterns = [ + path('features/', FeaturesView.as_view(), name='features'), +] + +urlpatterns.extend(common_urlpatterns) diff --git a/apps/main/urls/web.py b/apps/main/urls/web.py new file mode 100644 index 00000000..2126b0c0 --- /dev/null +++ b/apps/main/urls/web.py @@ -0,0 +1,11 @@ +from main.urls.common import common_urlpatterns +from django.urls import path + +from main.views.web import DetermineSiteView, SiteListView, SiteSettingsView + +urlpatterns = [ + path('determine-site/', DetermineSiteView.as_view(), name='determine-site'), + path('sites/', SiteListView.as_view(), name='site-list'), + path('site-settings//', SiteSettingsView.as_view(), name='site-settings'), ] + +urlpatterns.extend(common_urlpatterns) diff --git a/apps/main/views/__init__.py b/apps/main/views/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/main/views.py b/apps/main/views/common.py similarity index 73% rename from apps/main/views.py rename to apps/main/views/common.py index d7d1fa2c..e6fd3444 100644 --- a/apps/main/views.py +++ b/apps/main/views/common.py @@ -1,39 +1,11 @@ """Main app views.""" +from django.http import Http404 from rest_framework import generics, permissions from rest_framework.response import Response + from main import methods, models, serializers -from utils.serializers import EmptySerializer -class DetermineSiteView(generics.GenericAPIView): - """Determine user's site.""" - - permission_classes = (permissions.AllowAny,) - serializer_class = EmptySerializer - - def get(self, request, *args, **kwargs): - user_ip = methods.get_user_ip(request) - country_code = methods.determine_country_code(user_ip) - url = methods.determine_user_site_url(country_code) - return Response(data={'url': url}) - - -class SiteSettingsView(generics.RetrieveAPIView): - """Site settings View.""" - - lookup_field = 'subdomain' - permission_classes = (permissions.AllowAny,) - queryset = models.SiteSettings.objects.all() - serializer_class = serializers.SiteSettingsSerializer - - -class SiteListView(generics.ListAPIView): - """Site settings View.""" - - pagination_class = None - permission_classes = (permissions.AllowAny,) - queryset = models.SiteSettings.objects.with_country() - serializer_class = serializers.SiteSerializer # # class FeatureViewMixin: # """Feature view mixin.""" @@ -70,13 +42,14 @@ class SiteListView(generics.ListAPIView): # class SiteFeaturesRUDView(SiteFeaturesViewMixin, # generics.RetrieveUpdateDestroyAPIView): # """Site features RUD.""" +from utils.serializers import EmptySerializer class AwardView(generics.ListAPIView): """Awards list view.""" serializer_class = serializers.AwardSerializer queryset = models.Award.objects.all() - permission_classes = (permissions.AllowAny, ) + permission_classes = (permissions.AllowAny,) class AwardRetrieveView(generics.RetrieveAPIView): @@ -90,5 +63,22 @@ class CarouselListView(generics.ListAPIView): """Return list of carousel items.""" queryset = models.Carousel.objects.all() serializer_class = serializers.CarouselListSerializer - permission_classes = (permissions.AllowAny, ) + permission_classes = (permissions.AllowAny,) pagination_class = None + + +class DetermineLocation(generics.GenericAPIView): + """Determine user's location.""" + + permission_classes = (permissions.AllowAny,) + serializer_class = EmptySerializer + + def get(self, request, *args, **kwargs): + user_ip = methods.get_user_ip(request) + longitude, latitude = methods.determine_coordinates(user_ip) + city = methods.determine_user_city(user_ip) + if longitude and latitude and city: + return Response(data={'latitude': latitude, 'longitude': longitude, 'city': city}) + else: + raise Http404 + diff --git a/apps/main/views/mobile.py b/apps/main/views/mobile.py new file mode 100644 index 00000000..b992dbb8 --- /dev/null +++ b/apps/main/views/mobile.py @@ -0,0 +1,16 @@ +from rest_framework import generics, permissions + +from main import models, serializers +from utils.models import PlatformMixin + + +class FeaturesView(generics.ListAPIView): + pagination_class = None + permission_classes = (permissions.AllowAny,) + serializer_class = serializers.SiteFeatureSerializer + + def get_queryset(self): + return models.SiteFeature.objects\ + .prefetch_related('feature', 'feature__route') \ + .by_country_code(self.request.country_code) \ + .by_sources([PlatformMixin.ALL, PlatformMixin.MOBILE]) diff --git a/apps/main/views/web.py b/apps/main/views/web.py new file mode 100644 index 00000000..e1dc32ef --- /dev/null +++ b/apps/main/views/web.py @@ -0,0 +1,38 @@ +from typing import Iterable + +from rest_framework import generics, permissions + +from utils.serializers import EmptySerializer +from rest_framework.response import Response +from main import methods, models, serializers + + +class DetermineSiteView(generics.GenericAPIView): + """Determine user's site.""" + + permission_classes = (permissions.AllowAny,) + serializer_class = EmptySerializer + + def get(self, request, *args, **kwargs): + user_ip = methods.get_user_ip(request) + country_code = methods.determine_country_code(user_ip) + url = methods.determine_user_site_url(country_code) + return Response(data={'url': url}) + + +class SiteSettingsView(generics.RetrieveAPIView): + """Site settings View.""" + + lookup_field = 'subdomain' + permission_classes = (permissions.AllowAny,) + queryset = models.SiteSettings.objects.all() + serializer_class = serializers.SiteSettingsSerializer + + +class SiteListView(generics.ListAPIView): + """Site settings View.""" + + pagination_class = None + permission_classes = (permissions.AllowAny,) + queryset = models.SiteSettings.objects.with_country() + serializer_class = serializers.SiteSerializer diff --git a/apps/news/admin.py b/apps/news/admin.py index 7cbfb049..5d7f79f0 100644 --- a/apps/news/admin.py +++ b/apps/news/admin.py @@ -1,5 +1,6 @@ from django.contrib import admin from news import models +from .tasks import send_email_with_news @admin.register(models.NewsType) @@ -9,6 +10,17 @@ class NewsTypeAdmin(admin.ModelAdmin): list_display_links = ['id', 'name'] +def send_email_action(modeladmin, request, queryset): + news_ids = list(queryset.values_list("id", flat=True)) + + send_email_with_news.delay(news_ids) + + + +send_email_action.short_description = "Send the selected news by email" + + @admin.register(models.News) class NewsAdmin(admin.ModelAdmin): """News admin.""" + actions = [send_email_action] diff --git a/apps/news/migrations/0010_auto_20190923_1131.py b/apps/news/migrations/0010_auto_20190923_1131.py new file mode 100644 index 00000000..0bd6fd24 --- /dev/null +++ b/apps/news/migrations/0010_auto_20190923_1131.py @@ -0,0 +1,54 @@ +# Generated by Django 2.2.4 on 2019-09-23 11:31 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('news', '0009_auto_20190901_1032'), + ] + + operations = [ + migrations.AddField( + model_name='news', + name='author', + field=models.CharField(blank=True, default=None, max_length=255, null=True, verbose_name='Author'), + ), + migrations.AddField( + model_name='news', + name='image_url', + field=models.URLField(blank=True, default=None, null=True, verbose_name='Image URL path'), + ), + migrations.AddField( + model_name='news', + name='preview_image_url', + field=models.URLField(blank=True, default=None, null=True, verbose_name='Preview image URL path'), + ), + migrations.AlterField( + model_name='news', + name='address', + field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='location.Address', verbose_name='address'), + ), + migrations.AlterField( + model_name='news', + name='country', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='location.Country', verbose_name='country'), + ), + migrations.AlterField( + model_name='news', + name='end', + field=models.DateTimeField(verbose_name='End'), + ), + migrations.AlterField( + model_name='news', + name='news_type', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='news.NewsType', verbose_name='news type'), + ), + migrations.AlterField( + model_name='news', + name='start', + field=models.DateTimeField(verbose_name='Start'), + ), + ] diff --git a/apps/news/migrations/0011_auto_20190923_1134.py b/apps/news/migrations/0011_auto_20190923_1134.py new file mode 100644 index 00000000..6e457b80 --- /dev/null +++ b/apps/news/migrations/0011_auto_20190923_1134.py @@ -0,0 +1,28 @@ +# Generated by Django 2.2.4 on 2019-09-23 11:34 + +from django.db import migrations +from django.conf import settings + + +def copy_image_links(apps, schemaeditor): + News = apps.get_model('news', 'News') + for news in News.objects.all(): + if news.image: + news.image_url = f'{settings.SCHEMA_URI}://{settings.DOMAIN_URI}{news.image.image.url}' + news.save() + + +class Migration(migrations.Migration): + + dependencies = [ + ('news', '0010_auto_20190923_1131'), + ] + + operations = [ + migrations.RunPython(copy_image_links, migrations.RunPython.noop), + + migrations.RemoveField( + model_name='news', + name='image', + ), + ] diff --git a/apps/news/migrations/0012_auto_20190923_1416.py b/apps/news/migrations/0012_auto_20190923_1416.py new file mode 100644 index 00000000..2a59e2b0 --- /dev/null +++ b/apps/news/migrations/0012_auto_20190923_1416.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-09-23 14:16 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('news', '0011_auto_20190923_1134'), + ] + + operations = [ + migrations.AlterField( + model_name='news', + name='end', + field=models.DateTimeField(blank=True, default=None, null=True, verbose_name='End'), + ), + ] diff --git a/apps/news/migrations/0013_auto_20190924_0806.py b/apps/news/migrations/0013_auto_20190924_0806.py new file mode 100644 index 00000000..efd81652 --- /dev/null +++ b/apps/news/migrations/0013_auto_20190924_0806.py @@ -0,0 +1,20 @@ +# Generated by Django 2.2.4 on 2019-09-24 08:06 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('gallery', '0001_initial'), + ('news', '0012_auto_20190923_1416'), + ] + + operations = [ + migrations.AddField( + model_name='news', + name='slug', + field=models.SlugField(null=True, unique=True, verbose_name='News slug'), + ), + ] diff --git a/apps/news/migrations/0014_auto_20190927_0845.py b/apps/news/migrations/0014_auto_20190927_0845.py new file mode 100644 index 00000000..5a2b35fb --- /dev/null +++ b/apps/news/migrations/0014_auto_20190927_0845.py @@ -0,0 +1,22 @@ +# Generated by Django 2.2.4 on 2019-09-27 08:45 +from django.db import migrations +from django.core.validators import EMPTY_VALUES + + +def fill_slug(apps,schemaeditor): + News = apps.get_model('news', 'News') + for news in News.objects.all(): + if news.slug in EMPTY_VALUES: + news.slug = f'Slug_{news.id}' + news.save() + + +class Migration(migrations.Migration): + + dependencies = [ + ('news', '0013_auto_20190924_0806'), + ] + + operations = [ + migrations.RunPython(fill_slug, migrations.RunPython.noop) + ] diff --git a/apps/news/migrations/0015_auto_20190927_0853.py b/apps/news/migrations/0015_auto_20190927_0853.py new file mode 100644 index 00000000..e756e2e5 --- /dev/null +++ b/apps/news/migrations/0015_auto_20190927_0853.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-09-27 08:53 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('news', '0014_auto_20190927_0845'), + ] + + operations = [ + migrations.AlterField( + model_name='news', + name='slug', + field=models.SlugField(unique=True, verbose_name='News slug'), + ), + ] diff --git a/apps/news/migrations/0016_news_template.py b/apps/news/migrations/0016_news_template.py new file mode 100644 index 00000000..f85959ba --- /dev/null +++ b/apps/news/migrations/0016_news_template.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-09-27 13:54 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('news', '0015_auto_20190927_0853'), + ] + + operations = [ + migrations.AddField( + model_name='news', + name='template', + field=models.PositiveIntegerField(choices=[(0, 'newspaper'), (1, 'main.pdf.erb'), (2, 'main')], default=0), + ), + ] diff --git a/apps/news/migrations/0016_remove_news_author.py b/apps/news/migrations/0016_remove_news_author.py new file mode 100644 index 00000000..31ad12bb --- /dev/null +++ b/apps/news/migrations/0016_remove_news_author.py @@ -0,0 +1,17 @@ +# Generated by Django 2.2.4 on 2019-09-27 13:49 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('news', '0015_auto_20190927_0853'), + ] + + operations = [ + migrations.RemoveField( + model_name='news', + name='author', + ), + ] diff --git a/apps/news/migrations/0017_auto_20190927_1403.py b/apps/news/migrations/0017_auto_20190927_1403.py new file mode 100644 index 00000000..1886dcec --- /dev/null +++ b/apps/news/migrations/0017_auto_20190927_1403.py @@ -0,0 +1,22 @@ +# Generated by Django 2.2.4 on 2019-09-27 14:03 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('news', '0016_news_template'), + ] + + operations = [ + migrations.RemoveField( + model_name='news', + name='is_publish', + ), + migrations.AddField( + model_name='news', + name='state', + field=models.PositiveSmallIntegerField(choices=[(0, 'Waiting'), (1, 'Hidden'), (2, 'Published'), (3, 'Published exclusive')], default=0, verbose_name='State'), + ), + ] diff --git a/apps/news/migrations/0018_merge_20190927_1432.py b/apps/news/migrations/0018_merge_20190927_1432.py new file mode 100644 index 00000000..c4654943 --- /dev/null +++ b/apps/news/migrations/0018_merge_20190927_1432.py @@ -0,0 +1,14 @@ +# Generated by Django 2.2.4 on 2019-09-27 14:32 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('news', '0017_auto_20190927_1403'), + ('news', '0016_remove_news_author'), + ] + + operations = [ + ] diff --git a/apps/news/migrations/0019_news_author.py b/apps/news/migrations/0019_news_author.py new file mode 100644 index 00000000..41985255 --- /dev/null +++ b/apps/news/migrations/0019_news_author.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-09-27 15:32 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('news', '0018_merge_20190927_1432'), + ] + + operations = [ + migrations.AddField( + model_name='news', + name='author', + field=models.CharField(blank=True, default=None, max_length=255, null=True, verbose_name='Author'), + ), + ] diff --git a/apps/news/migrations/0020_remove_news_author.py b/apps/news/migrations/0020_remove_news_author.py new file mode 100644 index 00000000..95f376c9 --- /dev/null +++ b/apps/news/migrations/0020_remove_news_author.py @@ -0,0 +1,17 @@ +# Generated by Django 2.2.4 on 2019-10-02 09:18 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('news', '0019_news_author'), + ] + + operations = [ + migrations.RemoveField( + model_name='news', + name='author', + ), + ] diff --git a/apps/news/migrations/0021_auto_20191009_1408.py b/apps/news/migrations/0021_auto_20191009_1408.py new file mode 100644 index 00000000..81a4d7fa --- /dev/null +++ b/apps/news/migrations/0021_auto_20191009_1408.py @@ -0,0 +1,24 @@ +# Generated by Django 2.2.4 on 2019-10-09 14:08 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('tag', '0002_auto_20191009_1408'), + ('news', '0020_remove_news_author'), + ] + + operations = [ + migrations.AddField( + model_name='news', + name='tags', + field=models.ManyToManyField(related_name='news', to='tag.Tag', verbose_name='Tags'), + ), + migrations.AddField( + model_name='newstype', + name='tag_categories', + field=models.ManyToManyField(related_name='news_types', to='tag.TagCategory'), + ), + ] diff --git a/apps/news/migrations/0022_auto_20191021_1306.py b/apps/news/migrations/0022_auto_20191021_1306.py new file mode 100644 index 00000000..de8747f5 --- /dev/null +++ b/apps/news/migrations/0022_auto_20191021_1306.py @@ -0,0 +1,57 @@ +# Generated by Django 2.2.4 on 2019-10-21 13:06 + +from django.db import migrations, models +import django.db.models.deletion +import django.utils.timezone +import utils.models + + +class Migration(migrations.Migration): + + dependencies = [ + ('location', '0012_data_migrate'), + ('news', '0021_auto_20191009_1408'), + ] + + operations = [ + migrations.CreateModel( + name='NewsBanner', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created', models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name='Date created')), + ('modified', models.DateTimeField(auto_now=True, verbose_name='Date updated')), + ('title', utils.models.TJSONField(blank=True, default=None, help_text='{"en-GB":"some text"}', null=True, verbose_name='title')), + ('image_url', models.URLField(blank=True, default=None, null=True, verbose_name='Image URL path')), + ('content_url', models.URLField(blank=True, default=None, null=True, verbose_name='Content URL path')), + ], + options={ + 'abstract': False, + }, + bases=(models.Model, utils.models.TranslatedFieldsMixin), + ), + migrations.CreateModel( + name='Agenda', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created', models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name='Date created')), + ('modified', models.DateTimeField(auto_now=True, verbose_name='Date updated')), + ('event_datetime', models.DateTimeField(default=django.utils.timezone.now, editable=False, verbose_name='Event datetime')), + ('content', utils.models.TJSONField(blank=True, default=None, help_text='{"en-GB":"some text"}', null=True, verbose_name='content')), + ('address', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='location.Address', verbose_name='address')), + ], + options={ + 'abstract': False, + }, + bases=(models.Model, utils.models.TranslatedFieldsMixin), + ), + migrations.AddField( + model_name='news', + name='agenda', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='news.Agenda', verbose_name='agenda'), + ), + migrations.AddField( + model_name='news', + name='banner', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='news.NewsBanner', verbose_name='banner'), + ), + ] diff --git a/apps/news/models.py b/apps/news/models.py index 3be34261..0460174a 100644 --- a/apps/news/models.py +++ b/apps/news/models.py @@ -1,83 +1,199 @@ """News app models.""" from django.db import models +from django.contrib.contenttypes import fields as generic +from django.utils import timezone from django.utils.translation import gettext_lazy as _ from rest_framework.reverse import reverse - -from utils.models import BaseAttributes, TJSONField, TranslatedFieldsMixin +from utils.models import BaseAttributes, TJSONField, TranslatedFieldsMixin, ProjectBaseMixin +from rating.models import Rating class NewsType(models.Model): """NewsType model.""" + name = models.CharField(_('name'), max_length=250) + tag_categories = models.ManyToManyField('tag.TagCategory', + related_name='news_types') class Meta: + """Meta class.""" + verbose_name_plural = _('news types') verbose_name = _('news type') def __str__(self): + """Overrided __str__ method.""" return self.name class NewsQuerySet(models.QuerySet): """QuerySet for model News""" + + def rating_value(self): + return self.annotate(rating=models.Count('ratings__ip', distinct=True)) + + def with_base_related(self): + """Return qs with related objects.""" + return self.select_related('news_type', 'country').prefetch_related('tags') + + def with_extended_related(self): + """Return qs with related objects.""" + return self.select_related('created_by', 'agenda', 'banner') + def by_type(self, news_type): """Filter News by type""" return self.filter(news_type__name=news_type) + def by_tags(self, tags): + return self.filter(tags__in=tags) + def by_country_code(self, code): """Filter collection by country code.""" return self.filter(country__code=code) def published(self): """Return only published news""" - return self.filter(is_publish=True) + now = timezone.now() + return self.filter(models.Q(models.Q(end__gte=now) | + models.Q(end__isnull=True)), + state__in=self.model.PUBLISHED_STATES, start__lte=now) + + # todo: filter by best score + # todo: filter by country? + def should_read(self, news): + return self.model.objects.exclude(pk=news.pk).published(). \ + with_base_related().by_type(news.news_type).distinct().order_by('?') + + def same_theme(self, news): + return self.model.objects.exclude(pk=news.pk).published(). \ + with_base_related().by_type(news.news_type). \ + by_tags(news.tags.all()).distinct().order_by('-start') + + +class Agenda(ProjectBaseMixin, TranslatedFieldsMixin): + """News agenda model""" + + event_datetime = models.DateTimeField(default=timezone.now, editable=False, + verbose_name=_('Event datetime')) + address = models.ForeignKey('location.Address', blank=True, null=True, + default=None, verbose_name=_('address'), + on_delete=models.SET_NULL) + content = TJSONField(blank=True, null=True, default=None, + verbose_name=_('content'), + help_text='{"en-GB":"some text"}') + + +class NewsBanner(ProjectBaseMixin, TranslatedFieldsMixin): + """News banner model""" + title = TJSONField(blank=True, null=True, default=None, + verbose_name=_('title'), + help_text='{"en-GB":"some text"}') + image_url = models.URLField(verbose_name=_('Image URL path'), + blank=True, null=True, default=None) + content_url = models.URLField(verbose_name=_('Content URL path'), + blank=True, null=True, default=None) class News(BaseAttributes, TranslatedFieldsMixin): """News model.""" - image = models.ForeignKey( - 'gallery.Image', null=True, blank=True, default=None, - verbose_name=_('News image'), on_delete=models.CASCADE) - news_type = models.ForeignKey( - NewsType, verbose_name=_('news type'), on_delete=models.CASCADE) + STR_FIELD_NAME = 'title' - title = TJSONField( - _('title'), null=True, blank=True, - default=None, help_text='{"en-GB":"some text"}') - subtitle = TJSONField( - _('subtitle'), null=True, blank=True, - default=None, help_text='{"en-GB":"some text"}' + # TEMPLATE CHOICES + NEWSPAPER = 0 + MAIN_PDF_ERB = 1 + MAIN = 2 + + TEMPLATE_CHOICES = ( + (NEWSPAPER, 'newspaper'), + (MAIN_PDF_ERB, 'main.pdf.erb'), + (MAIN, 'main'), ) - description = TJSONField( - _('description'), null=True, blank=True, - default=None, help_text='{"en-GB":"some text"}' + + # STATE CHOICES + WAITING = 0 + HIDDEN = 1 + PUBLISHED = 2 + PUBLISHED_EXCLUSIVE = 3 + + PUBLISHED_STATES = [PUBLISHED, PUBLISHED_EXCLUSIVE] + + STATE_CHOICES = ( + (WAITING, _('Waiting')), + (HIDDEN, _('Hidden')), + (PUBLISHED, _('Published')), + (PUBLISHED_EXCLUSIVE, _('Published exclusive')), ) - start = models.DateTimeField(_('start')) - end = models.DateTimeField(_('end')) + + news_type = models.ForeignKey(NewsType, on_delete=models.PROTECT, + verbose_name=_('news type')) + title = TJSONField(blank=True, null=True, default=None, + verbose_name=_('title'), + help_text='{"en-GB":"some text"}') + subtitle = TJSONField(blank=True, null=True, default=None, + verbose_name=_('subtitle'), + help_text='{"en-GB":"some text"}') + description = TJSONField(blank=True, null=True, default=None, + verbose_name=_('description'), + help_text='{"en-GB":"some text"}') + start = models.DateTimeField(verbose_name=_('Start')) + end = models.DateTimeField(blank=True, null=True, default=None, + verbose_name=_('End')) + slug = models.SlugField(unique=True, max_length=50, + verbose_name=_('News slug')) playlist = models.IntegerField(_('playlist')) - address = models.ForeignKey( - 'location.Address', verbose_name=_('address'), blank=True, - null=True, default=None, on_delete=models.CASCADE) - is_publish = models.BooleanField( - default=False, verbose_name=_('Publish status')) - country = models.ForeignKey( - 'location.Country', blank=True, null=True, - verbose_name=_('country'), on_delete=models.CASCADE) - is_highlighted = models.BooleanField( - default=False, verbose_name=_('Is highlighted')) + state = models.PositiveSmallIntegerField(default=WAITING, choices=STATE_CHOICES, + verbose_name=_('State')) + is_highlighted = models.BooleanField(default=False, + verbose_name=_('Is highlighted')) # TODO: metadata_keys - описание ключей для динамического построения полей метаданных # TODO: metadata_values - Описание значений для динамических полей из MetadataKeys + image_url = models.URLField(blank=True, null=True, default=None, + verbose_name=_('Image URL path')) + preview_image_url = models.URLField(blank=True, null=True, default=None, + verbose_name=_('Preview image URL path')) + template = models.PositiveIntegerField(choices=TEMPLATE_CHOICES, default=NEWSPAPER) + address = models.ForeignKey('location.Address', blank=True, null=True, + default=None, verbose_name=_('address'), + on_delete=models.SET_NULL) + country = models.ForeignKey('location.Country', blank=True, null=True, + on_delete=models.SET_NULL, + verbose_name=_('country')) + tags = models.ManyToManyField('tag.Tag', related_name='news', + verbose_name=_('Tags')) + ratings = generic.GenericRelation(Rating) + + agenda = models.ForeignKey('news.Agenda', blank=True, null=True, + on_delete=models.SET_NULL, + verbose_name=_('agenda')) + + banner = models.ForeignKey('news.NewsBanner', blank=True, null=True, + on_delete=models.SET_NULL, + verbose_name=_('banner')) objects = NewsQuerySet.as_manager() class Meta: + """Meta class.""" + verbose_name = _('news') verbose_name_plural = _('news') def __str__(self): - return f'news: {self.id}' + return f'news: {self.slug}' + + @property + def is_publish(self): + return self.state in self.PUBLISHED_STATES @property def web_url(self): - return reverse('web:news:rud', kwargs={'pk': self.pk}) + return reverse('web:news:rud', kwargs={'slug': self.slug}) + + @property + def should_read(self): + return self.__class__.objects.should_read(self)[:3] + + @property + def same_theme(self): + return self.__class__.objects.same_theme(self)[:3] diff --git a/apps/news/serializers.py b/apps/news/serializers.py new file mode 100644 index 00000000..10662880 --- /dev/null +++ b/apps/news/serializers.py @@ -0,0 +1,162 @@ +"""News app common serializers.""" +from rest_framework import serializers +from account.serializers.common import UserBaseSerializer +from location import models as location_models +from location.serializers import CountrySimpleSerializer, AddressBaseSerializer +from news import models +from tag.serializers import TagBaseSerializer +from utils.serializers import TranslatedField, ProjectModelSerializer + + +class AgendaSerializer(ProjectModelSerializer): + event_datetime = serializers.DateTimeField() + address = AddressBaseSerializer() + content_translated = TranslatedField() + + class Meta: + """Meta class.""" + + model = models.Agenda + fields = ( + 'id', + 'event_datetime', + 'address', + 'content_translated' + ) + + +class NewsBannerSerializer(ProjectModelSerializer): + title_translated = TranslatedField() + image_url = serializers.URLField() + content_url = serializers.URLField() + + class Meta: + """Meta class.""" + + model = models.NewsBanner + fields = ( + 'id', + 'title_translated', + 'image_url', + 'content_url' + ) + + +class NewsTypeSerializer(serializers.ModelSerializer): + """News type serializer.""" + + class Meta: + """Meta class.""" + + model = models.NewsType + fields = ('id', 'name') + + +class NewsBaseSerializer(ProjectModelSerializer): + """Base serializer for News model.""" + + # read only fields + title_translated = TranslatedField(source='title') + subtitle_translated = TranslatedField() + + # related fields + news_type = NewsTypeSerializer(read_only=True) + tags = TagBaseSerializer(read_only=True, many=True) + + class Meta: + """Meta class.""" + + model = models.News + fields = ( + 'id', + 'title_translated', + 'subtitle_translated', + 'is_highlighted', + 'image_url', + 'preview_image_url', + 'news_type', + 'tags', + 'slug', + ) + + +class NewsDetailSerializer(NewsBaseSerializer): + """News detail serializer.""" + + description_translated = TranslatedField() + country = CountrySimpleSerializer(read_only=True) + author = UserBaseSerializer(source='created_by', read_only=True) + state_display = serializers.CharField(source='get_state_display', + read_only=True) + + class Meta(NewsBaseSerializer.Meta): + """Meta class.""" + + fields = NewsBaseSerializer.Meta.fields + ( + 'description_translated', + 'start', + 'end', + 'playlist', + 'is_publish', + 'state', + 'state_display', + 'author', + 'country', + ) + + +class NewsDetailWebSerializer(NewsDetailSerializer): + """News detail serializer for web users..""" + + same_theme = NewsBaseSerializer(many=True, read_only=True) + should_read = NewsBaseSerializer(many=True, read_only=True) + agenda = AgendaSerializer() + banner = NewsBannerSerializer() + + class Meta(NewsDetailSerializer.Meta): + """Meta class.""" + + fields = NewsDetailSerializer.Meta.fields + ( + 'same_theme', + 'should_read', + 'agenda', + 'banner' + ) + + +class NewsBackOfficeBaseSerializer(NewsBaseSerializer): + """News back office base serializer.""" + + class Meta(NewsBaseSerializer.Meta): + """Meta class.""" + + fields = NewsBaseSerializer.Meta.fields + ( + 'title', + 'subtitle', + ) + + +class NewsBackOfficeDetailSerializer(NewsBackOfficeBaseSerializer, + NewsDetailSerializer): + """News detail serializer for back-office users.""" + + news_type_id = serializers.PrimaryKeyRelatedField( + source='news_type', write_only=True, + queryset=models.NewsType.objects.all()) + country_id = serializers.PrimaryKeyRelatedField( + source='country', write_only=True, + queryset=location_models.Country.objects.all()) + template_display = serializers.CharField(source='get_template_display', + read_only=True) + + class Meta(NewsBackOfficeBaseSerializer.Meta, NewsDetailSerializer.Meta): + """Meta class.""" + + fields = NewsBackOfficeBaseSerializer.Meta.fields + \ + NewsDetailSerializer.Meta.fields + ( + 'description', + 'news_type_id', + 'country_id', + 'template', + 'template_display', + ) diff --git a/apps/news/serializers/common.py b/apps/news/serializers/common.py deleted file mode 100644 index b64a7fc9..00000000 --- a/apps/news/serializers/common.py +++ /dev/null @@ -1,76 +0,0 @@ -"""News app common serializers.""" -from rest_framework import serializers -from gallery import models as gallery_models -from location.models import Address -from location.serializers import AddressSerializer -from news import models - - -class NewsTypeSerializer(serializers.ModelSerializer): - """News type serializer.""" - class Meta: - model = models.NewsType - fields = [ - 'id', - 'name' - ] - - -class NewsSerializer(serializers.ModelSerializer): - """News serializer.""" - - address = AddressSerializer() - title_translated = serializers.CharField(read_only=True, allow_null=True) - subtitle_translated = serializers.CharField(read_only=True, allow_null=True) - description_translated = serializers.CharField(read_only=True, allow_null=True) - image_url = serializers.ImageField(source='image.image', allow_null=True) - - class Meta: - model = models.News - fields = [ - 'id', - 'news_type', - 'start', - 'end', - 'playlist', - 'address', - 'is_highlighted', - 'image_url', - # Localized fields - 'title_translated', - 'subtitle_translated', - 'description_translated', - ] - - -class NewsCreateUpdateSerializer(NewsSerializer): - """News update serializer.""" - title = serializers.JSONField() - subtitle = serializers.JSONField() - description = serializers.JSONField() - image = serializers.PrimaryKeyRelatedField( - queryset=gallery_models.Image.objects.all(), required=True,) - news_type = serializers.PrimaryKeyRelatedField( - queryset=models.NewsType.objects.all(), write_only=True) - address = serializers.PrimaryKeyRelatedField( - queryset=Address.objects.all(), write_only=True) - - class Meta: - model = models.News - read_only_fields = [ - 'id' - ] - fields = [ - 'id', - 'news_type', - 'title', - 'subtitle', - 'description', - 'start', - 'end', - 'playlist', - 'address', - 'image', - 'is_publish', - 'country' - ] diff --git a/apps/news/tasks.py b/apps/news/tasks.py new file mode 100644 index 00000000..7ff4d504 --- /dev/null +++ b/apps/news/tasks.py @@ -0,0 +1,43 @@ +from datetime import datetime + +from celery import shared_task +from django.core.mail import send_mail +from notification.models import Subscriber +from news import models +from django.template.loader import render_to_string, get_template +from django.conf import settings +from smtplib import SMTPException +from django.core.validators import EMPTY_VALUES +from main.models import SiteSettings + + +@shared_task +def send_email_with_news(news_ids): + subscribers = Subscriber.objects.filter(state=Subscriber.USABLE) + sent_news = models.News.objects.filter(id__in=news_ids) + htmly = get_template(settings.NEWS_EMAIL_TEMPLATE) + year = datetime.now().year + socials = list(SiteSettings.objects.with_country()) + socials = dict(zip(map(lambda s: s.country.code, socials), socials)) + for s in subscribers: + socials_for_subscriber = socials.get(s.country_code) + try: + for n in sent_news: + context = {"title": n.title.get(s.locale), + "subtitle": n.subtitle.get(s.locale), + "description": n.description.get(s.locale), + "code": s.update_code, + "image_url": n.image_url if n.image_url not in EMPTY_VALUES else None, + "domain_uri": settings.DOMAIN_URI, + "slug": n.slug, + "country_code": s.country_code, + "twitter_page_url": socials_for_subscriber.twitter_page_url if socials_for_subscriber else '#', + "instagram_page_url": socials_for_subscriber.instagram_page_url if socials_for_subscriber else '#', + "facebook_page_url": socials_for_subscriber.facebook_page_url if socials_for_subscriber else '#', + "send_to": s.send_to, + "year": year} + send_mail("G&M News", render_to_string(settings.NEWS_EMAIL_TEMPLATE, context), + settings.EMAIL_HOST_USER, [s.send_to], fail_silently=False, + html_message=htmly.render(context)) + except SMTPException: + continue diff --git a/apps/news/tests.py b/apps/news/tests.py index 7ce503c2..b4e2b296 100644 --- a/apps/news/tests.py +++ b/apps/news/tests.py @@ -1,3 +1,94 @@ -from django.test import TestCase +from django.urls import reverse +from http.cookies import SimpleCookie +from rest_framework.test import APITestCase +from rest_framework import status +from datetime import datetime, timedelta + +from news.models import NewsType, News +from account.models import User, Role, UserRole +from translation.models import Language +from location.models import Country # Create your tests here. + + +class BaseTestCase(APITestCase): + + def setUp(self): + self.username = 'sedragurda' + self.password = 'sedragurdaredips19' + self.email = 'sedragurda@desoz.com' + self.user = User.objects.create_user(username=self.username, email=self.email, password=self.password) + #get tokkens + tokkens = User.create_jwt_tokens(self.user) + self.client.cookies = SimpleCookie({'access_token': tokkens.get('access_token'), + 'refresh_token': tokkens.get('refresh_token')}) + self.test_news_type = NewsType.objects.create(name="Test news type") + + self.lang = Language.objects.get( + title='Russia', + locale='ru-RU' + ) + + self.country_ru = Country.objects.get( + name={"en-GB": "Russian"} + ) + + role = Role.objects.create( + role=Role.CONTENT_PAGE_MANAGER, + country=self.country_ru + ) + role.save() + + user_role = UserRole.objects.create( + user=self.user, + role=role + ) + user_role.save() + + self.test_news = News.objects.create(created_by=self.user, modified_by=self.user, + title={"en-GB": "Test news"}, + news_type=self.test_news_type, + description={"en-GB": "Description test news"}, + playlist=1, start=datetime.now() + timedelta(hours=-2), + end=datetime.now() + timedelta(hours=2), + state=News.PUBLISHED, slug='test-news-slug', + country=self.country_ru) + +class NewsTestCase(BaseTestCase): + def setUp(self): + super().setUp() + + def test_web_news(self): + response = self.client.get("/api/web/news/") + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.get(f"/api/web/news/slug/{self.test_news.slug}/") + self.assertEqual(response.status_code, status.HTTP_200_OK) + + response = self.client.get("/api/web/news/types/") + self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_news_back_detail(self): + response = self.client.get(f"/api/back/news/{self.test_news.id}/") + self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_news_list_back(self): + response = self.client.get("/api/back/news/") + self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_news_back_detail_put(self): + # retrieve-update-destroy + url = reverse('back:news:retrieve-update-destroy', kwargs={'pk': self.test_news.id}) + data = { + 'id': self.test_news.id, + 'description': {"en-GB": "Description test news!"}, + 'slug': self.test_news.slug, + 'start': self.test_news.start, + 'playlist': self.test_news.playlist, + 'news_type_id':self.test_news.news_type_id, + 'country_id': self.country_ru.id + } + + response = self.client.put(url, data=data, format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) \ No newline at end of file diff --git a/apps/news/urls/back.py b/apps/news/urls/back.py new file mode 100644 index 00000000..8522592e --- /dev/null +++ b/apps/news/urls/back.py @@ -0,0 +1,11 @@ +"""News app urlpatterns for backoffice""" +from django.urls import path +from news import views + +app_name = 'news' + +urlpatterns = [ + path('', views.NewsBackOfficeLCView.as_view(), name='list-create'), + path('/', views.NewsBackOfficeRUDView.as_view(), + name='retrieve-update-destroy'), +] \ No newline at end of file diff --git a/apps/news/urls/web.py b/apps/news/urls/web.py index 1dbcc0fe..80fcf072 100644 --- a/apps/news/urls/web.py +++ b/apps/news/urls/web.py @@ -1,12 +1,11 @@ -"""Location app urlconf.""" +"""News app urlconf.""" from django.urls import path - -from news.views import common +from news import views app_name = 'news' urlpatterns = [ - path('', common.NewsListView.as_view(), name='list'), - path('/', common.NewsDetailView.as_view(), name='rud'), - path('type/', common.NewsTypeListView.as_view(), name='type'), + path('', views.NewsListView.as_view(), name='list'), + path('types/', views.NewsTypeListView.as_view(), name='type'), + path('slug//', views.NewsDetailView.as_view(), name='rud'), ] diff --git a/apps/news/views.py b/apps/news/views.py new file mode 100644 index 00000000..78a3502b --- /dev/null +++ b/apps/news/views.py @@ -0,0 +1,87 @@ +"""News app views.""" +from django.shortcuts import get_object_or_404 +from rest_framework import generics, permissions +from news import filters, models, serializers +from rating.tasks import add_rating +from utils.permissions import IsCountryAdmin, IsContentPageManager + + +class NewsMixinView: + """News mixin.""" + + permission_classes = (permissions.AllowAny, ) + serializer_class = serializers.NewsBaseSerializer + + def get_queryset(self, *args, **kwargs): + """Override get_queryset method.""" + qs = models.News.objects.published().with_base_related()\ + .order_by('-is_highlighted', '-created') + if self.request.country_code: + qs = qs.by_country_code(self.request.country_code) + return qs + + +class NewsListView(NewsMixinView, generics.ListAPIView): + """News list view.""" + + filter_class = filters.NewsListFilterSet + + +class NewsDetailView(NewsMixinView, generics.RetrieveAPIView): + """News detail view.""" + + lookup_field = 'slug' + serializer_class = serializers.NewsDetailWebSerializer + + def get_queryset(self): + """Override get_queryset method.""" + return super().get_queryset().with_extended_related() + + +class NewsTypeListView(generics.ListAPIView): + """NewsType list view.""" + + pagination_class = None + permission_classes = (permissions.AllowAny, ) + queryset = models.NewsType.objects.all() + serializer_class = serializers.NewsTypeSerializer + + +class NewsBackOfficeMixinView: + """News back office mixin view.""" + + permission_classes = (permissions.IsAuthenticated,) + queryset = models.News.objects.with_base_related() \ + .order_by('-is_highlighted', '-created') + + +class NewsBackOfficeLCView(NewsBackOfficeMixinView, + generics.ListCreateAPIView): + """Resource for a list of news for back-office users.""" + + serializer_class = serializers.NewsBackOfficeBaseSerializer + create_serializers_class = serializers.NewsBackOfficeDetailSerializer + permission_classes = [IsCountryAdmin|IsContentPageManager] + + def get_serializer_class(self): + """Override serializer class.""" + if self.request.method == 'POST': + return self.create_serializers_class + return super().get_serializer_class() + + def get_queryset(self): + """Override get_queryset method.""" + return super().get_queryset().with_extended_related() + + +class NewsBackOfficeRUDView(NewsBackOfficeMixinView, + generics.RetrieveUpdateDestroyAPIView): + """Resource for detailed information about news for back-office users.""" + + serializer_class = serializers.NewsBackOfficeDetailSerializer + permission_classes = [IsCountryAdmin|IsContentPageManager] + + def get(self, request, pk, *args, **kwargs): + add_rating(remote_addr=request.META.get('REMOTE_ADDR'), + pk=pk, model='news', app_label='news') + return self.retrieve(request, *args, **kwargs) diff --git a/apps/news/views/common.py b/apps/news/views/common.py index cf3c7e29..e69de29b 100644 --- a/apps/news/views/common.py +++ b/apps/news/views/common.py @@ -1,38 +0,0 @@ -"""News app common app.""" -from rest_framework import generics, permissions - -from news import filters, models -from news.serializers import common as serializers -from utils.views import JWTGenericViewMixin - - -class NewsMixin: - """News mixin.""" - - permission_classes = (permissions.AllowAny, ) - serializer_class = serializers.NewsSerializer - - def get_queryset(self, *args, **kwargs): - """Override get_queryset method""" - return models.News.objects.published() \ - .by_country_code(code=self.request.country_code) \ - .order_by('-is_highlighted', '-created') - - -class NewsListView(NewsMixin, generics.ListAPIView): - """News list view.""" - - filter_class = filters.NewsListFilterSet - - -class NewsDetailView(NewsMixin, JWTGenericViewMixin, generics.RetrieveAPIView): - """News detail view.""" - - -class NewsTypeListView(generics.ListAPIView): - """NewsType list view.""" - - serializer_class = serializers.NewsTypeSerializer - permission_classes = (permissions.AllowAny, ) - pagination_class = None - queryset = models.NewsType.objects.all() diff --git a/apps/notification/tests.py b/apps/notification/tests.py new file mode 100644 index 00000000..d78c7fca --- /dev/null +++ b/apps/notification/tests.py @@ -0,0 +1,116 @@ +from http.cookies import SimpleCookie + +from django.test import TestCase +from rest_framework.test import APITestCase +from rest_framework import status + +from account.models import User +from notification.models import Subscriber + + +class BaseTestCase(APITestCase): + + def setUp(self): + self.username = 'sedragurda' + self.password = 'sedragurdaredips19' + self.email = 'sedragurda@desoz.com' + self.user = User.objects.create_user(username=self.username, email=self.email, password=self.password) + # get tokkens + tokkens = User.create_jwt_tokens(self.user) + self.client.cookies = SimpleCookie({'access_token': tokkens.get('access_token'), + 'refresh_token': tokkens.get('refresh_token')}) + + +class NotificationAnonSubscribeTestCase(APITestCase): + + def test_subscribe(self): + + test_data = { + "email": "test@email.com", + "state": 1 + } + + response = self.client.post("/api/web/notifications/subscribe/", data=test_data, format="json") + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(response.json()["email"], test_data["email"]) + self.assertEqual(response.json()["state"], test_data["state"]) + + +class NotificationSubscribeTestCase(BaseTestCase): + + def setUp(self): + super().setUp() + + self.test_data = { + "email": self.email, + "state": 1 + } + + def test_subscribe(self): + + response = self.client.post("/api/web/notifications/subscribe/", data=self.test_data, format="json") + + self.assertEqual(response.status_code, status.HTTP_200_OK) + self.assertEqual(response.json()["email"], self.email) + self.assertEqual(response.json()["state"], self.test_data["state"]) + + def test_subscribe_info_auth_user(self): + + Subscriber.objects.create(user=self.user, email=self.email, state=1) + + response = self.client.get("/api/web/notifications/subscribe-info/", data=self.test_data, format="json") + + self.assertEqual(response.status_code, status.HTTP_200_OK) + + +class NotificationSubscribeInfoTestCase(APITestCase): + + def test_subscribe_info(self): + + self.username = 'sedragurda' + self.password = 'sedragurdaredips19' + self.email = 'sedragurda@desoz.com' + self.user = User.objects.create_user(username=self.username, email=self.email, password=self.password) + + test_subscriber = Subscriber.objects.create(user=self.user, email=self.email, state=1) + + response = self.client.get(f"/api/web/notifications/subscribe-info/{test_subscriber.update_code}/") + + self.assertEqual(response.status_code, status.HTTP_200_OK) + + +class NotificationUnsubscribeAuthUserTestCase(BaseTestCase): + + def test_unsubscribe_auth_user(self): + + Subscriber.objects.create(user=self.user, email=self.email, state=1) + + self.test_data = { + "email": self.email, + "state": 1 + } + + response = self.client.patch("/api/web/notifications/unsubscribe/", data=self.test_data, format="json") + + self.assertEqual(response.status_code, status.HTTP_200_OK) + + +class NotificationUnsubscribeTestCase(APITestCase): + + def test_unsubscribe(self): + self.username = 'sedragurda' + self.password = 'sedragurdaredips19' + self.email = 'sedragurda@desoz.com' + self.user = User.objects.create_user(username=self.username, email=self.email, password=self.password) + + self.test_data = { + "email": self.email, + "state": 1 + } + + test_subscriber = Subscriber.objects.create(user=self.user, email=self.email, state=1) + + response = self.client.patch(f"/api/web/notifications/unsubscribe/{test_subscriber.update_code}/", + data=self.test_data, format="json") + + self.assertEqual(response.status_code, status.HTTP_200_OK) diff --git a/apps/notification/urls/common.py b/apps/notification/urls/common.py index df43c805..842aa642 100644 --- a/apps/notification/urls/common.py +++ b/apps/notification/urls/common.py @@ -2,6 +2,7 @@ from django.urls import path from notification.views import common +app_name = "notification" urlpatterns = [ path('subscribe/', common.SubscribeView.as_view(), name='subscribe'), diff --git a/apps/partner/tests.py b/apps/partner/tests.py index a39b155a..494e7f7e 100644 --- a/apps/partner/tests.py +++ b/apps/partner/tests.py @@ -1 +1,16 @@ # Create your tests here. +from rest_framework.test import APITestCase +from rest_framework import status + +from partner.models import Partner + + +class PartnerTestCase(APITestCase): + + def setUp(self): + self.test_url = "www.example.com" + self.test_partner = Partner.objects.create(url=self.test_url) + + def test_partner_list(self): + response = self.client.get("/api/web/partner/") + self.assertEqual(response.status_code, status.HTTP_200_OK) diff --git a/apps/product/urls/back.py b/apps/product/urls/back.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/product/views/back.py b/apps/product/views/back.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/rating/__init__.py b/apps/rating/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/rating/admin.py b/apps/rating/admin.py new file mode 100644 index 00000000..151f406b --- /dev/null +++ b/apps/rating/admin.py @@ -0,0 +1,11 @@ +from django.contrib import admin +from rating import models +from rating import tasks + +@admin.register(models.Rating) +class RatingAdmin(admin.ModelAdmin): + """Rating type admin conf.""" + list_display = ['name', 'ip'] + list_display_links = ['name'] + + diff --git a/apps/rating/apps.py b/apps/rating/apps.py new file mode 100644 index 00000000..6f17a343 --- /dev/null +++ b/apps/rating/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class RatingConfig(AppConfig): + name = 'rating' diff --git a/apps/rating/migrations/0001_initial.py b/apps/rating/migrations/0001_initial.py new file mode 100644 index 00000000..03165670 --- /dev/null +++ b/apps/rating/migrations/0001_initial.py @@ -0,0 +1,28 @@ +# Generated by Django 2.2.4 on 2019-10-02 11:32 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('contenttypes', '0002_remove_content_type_name'), + ] + + operations = [ + migrations.CreateModel( + name='Rating', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('object_id', models.PositiveIntegerField()), + ('ip', models.GenericIPAddressField(verbose_name='ip')), + ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')), + ], + options={ + 'verbose_name': 'rating', + }, + ), + ] diff --git a/apps/rating/migrations/0002_auto_20191004_0928.py b/apps/rating/migrations/0002_auto_20191004_0928.py new file mode 100644 index 00000000..a172c6f1 --- /dev/null +++ b/apps/rating/migrations/0002_auto_20191004_0928.py @@ -0,0 +1,22 @@ +# Generated by Django 2.2.4 on 2019-10-04 09:28 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('contenttypes', '0002_remove_content_type_name'), + ('rating', '0001_initial'), + ] + + operations = [ + migrations.AlterModelOptions( + name='rating', + options={}, + ), + migrations.AlterUniqueTogether( + name='rating', + unique_together={('ip', 'object_id', 'content_type')}, + ), + ] diff --git a/apps/rating/migrations/__init__.py b/apps/rating/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/rating/models.py b/apps/rating/models.py new file mode 100644 index 00000000..e1dcec86 --- /dev/null +++ b/apps/rating/models.py @@ -0,0 +1,22 @@ +from django.contrib.contenttypes.fields import GenericForeignKey +from django.contrib.contenttypes.models import ContentType +from django.db import models +from django.utils.translation import gettext_lazy as _ + + +class Rating(models.Model): + content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) + object_id = models.PositiveIntegerField() + content_object = GenericForeignKey('content_type', 'object_id') + ip = models.GenericIPAddressField(verbose_name=_('ip')) + + class Meta: + unique_together = ('ip', 'object_id', 'content_type') + + @property + def name(self): + # Check if Generic obj has name or title + if hasattr(self.content_object, 'name'): + return self.content_object.name + if hasattr(self.content_object, 'title'): + return self.content_object.title_translated diff --git a/apps/rating/tasks.py b/apps/rating/tasks.py new file mode 100644 index 00000000..5c2653a0 --- /dev/null +++ b/apps/rating/tasks.py @@ -0,0 +1,18 @@ +from celery import shared_task +from rating.models import Rating +from django.contrib.contenttypes.models import ContentType + + +def add_rating(remote_addr, pk, model, app_label): + add.apply_async( + (remote_addr, pk, model, app_label), countdown=60 * 60 + ) + + +@shared_task +def add(remote_addr, pk, model, app_label): + content_type = ContentType.objects.get(app_label=app_label, model=model) + Rating.objects.get_or_create( + ip=remote_addr, object_id=pk, content_type=content_type) + + diff --git a/apps/rating/tests.py b/apps/rating/tests.py new file mode 100644 index 00000000..7ce503c2 --- /dev/null +++ b/apps/rating/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/apps/rating/views.py b/apps/rating/views.py new file mode 100644 index 00000000..91ea44a2 --- /dev/null +++ b/apps/rating/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/apps/recipe/tests.py b/apps/recipe/tests.py new file mode 100644 index 00000000..d0a17a36 --- /dev/null +++ b/apps/recipe/tests.py @@ -0,0 +1,33 @@ +from http.cookies import SimpleCookie + + +from rest_framework.test import APITestCase +from rest_framework import status + +from account.models import User +from recipe.models import Recipe + + +class BaseTestCase(APITestCase): + + def setUp(self): + self.username = 'sedragurda' + self.password = 'sedragurdaredips19' + self.email = 'sedragurda@desoz.com' + self.user = User.objects.create_user(username=self.username, email=self.email, password=self.password) + tokkens = User.create_jwt_tokens(self.user) + self.client.cookies = SimpleCookie({'access_token': tokkens.get('access_token'), + 'refresh_token': tokkens.get('refresh_token')}) + self.test_recipe = Recipe.objects.create(title={"en-GB": "test title"}, description={"en-GB": "test description"}, + state=2, author="Test Author", created_by=self.user, + modified_by=self.user) + + def test_recipe_list(self): + response = self.client.get("/api/web/recipes/") + self.assertEqual(response.status_code, status.HTTP_200_OK) + + def test_recipe_detail(self): + print(self.test_recipe.id) + response = self.client.get(f"/api/web/recipes/{self.test_recipe.id}/") + print(response.json()) + self.assertEqual(response.status_code, status.HTTP_200_OK) diff --git a/apps/review/migrations/0004_review_country.py b/apps/review/migrations/0004_review_country.py new file mode 100644 index 00000000..1d4173e0 --- /dev/null +++ b/apps/review/migrations/0004_review_country.py @@ -0,0 +1,20 @@ +# Generated by Django 2.2.4 on 2019-10-17 12:17 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('location', '0012_data_migrate'), + ('review', '0003_review_text'), + ] + + operations = [ + migrations.AddField( + model_name='review', + name='country', + field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='country', to='location.Country', verbose_name='Country'), + ), + ] diff --git a/apps/review/models.py b/apps/review/models.py index d0076f68..4c7f3385 100644 --- a/apps/review/models.py +++ b/apps/review/models.py @@ -23,6 +23,10 @@ class ReviewQuerySet(models.QuerySet): """Filter by status""" return self.filter(status=status) + def published(self): + """Return published reviews""" + return self.filter(status=Review.READY) + class Review(BaseAttributes, TranslatedFieldsMixin): """Review model""" @@ -61,6 +65,9 @@ class Review(BaseAttributes, TranslatedFieldsMixin): validators=[MinValueValidator(1900), MaxValueValidator(2100)]) + country = models.ForeignKey('location.Country', on_delete=models.CASCADE, + related_name='country', verbose_name=_('Country'), + null=True) objects = ReviewQuerySet.as_manager() class Meta: diff --git a/apps/review/serializers/back.py b/apps/review/serializers/back.py new file mode 100644 index 00000000..3e816394 --- /dev/null +++ b/apps/review/serializers/back.py @@ -0,0 +1,18 @@ +"""Review app common serializers.""" +from review import models +from rest_framework import serializers + + +class ReviewBaseSerializer(serializers.ModelSerializer): + class Meta: + model = models.Review + fields = ('id', + 'reviewer', + 'text', + 'language', + 'status', + 'child', + 'published_at', + 'vintage', + 'country' + ) \ No newline at end of file diff --git a/apps/review/urls/back.py b/apps/review/urls/back.py new file mode 100644 index 00000000..84ca49f3 --- /dev/null +++ b/apps/review/urls/back.py @@ -0,0 +1,11 @@ +"""Back review URLs""" +from django.urls import path + +from review.views import back as views + +app_name = 'review' + +urlpatterns = [ + path('', views.ReviewLstView.as_view(), name='review-list-create'), + path('/', views.ReviewRUDView.as_view(), name='review-crud'), +] diff --git a/apps/review/views/back.py b/apps/review/views/back.py new file mode 100644 index 00000000..2b4288d2 --- /dev/null +++ b/apps/review/views/back.py @@ -0,0 +1,19 @@ +from rest_framework import generics, permissions +from review.serializers import back as serializers +from review import models +from utils.permissions import IsReviewerManager, IsRestaurantReviewer + + +class ReviewLstView(generics.ListCreateAPIView): + """Comment list create view.""" + serializer_class = serializers.ReviewBaseSerializer + queryset = models.Review.objects.all() + permission_classes = [permissions.IsAuthenticatedOrReadOnly,] + + +class ReviewRUDView(generics.RetrieveUpdateDestroyAPIView): + """Comment RUD view.""" + serializer_class = serializers.ReviewBaseSerializer + queryset = models.Review.objects.all() + permission_classes = [IsReviewerManager|IsRestaurantReviewer] + lookup_field = 'id' diff --git a/apps/search_indexes/documents/establishment.py b/apps/search_indexes/documents/establishment.py index 8c96066e..c30d4c58 100644 --- a/apps/search_indexes/documents/establishment.py +++ b/apps/search_indexes/documents/establishment.py @@ -14,30 +14,29 @@ EstablishmentIndex.settings(number_of_shards=1, number_of_replicas=1) class EstablishmentDocument(Document): """Establishment document.""" + preview_image = fields.KeywordField(attr='preview_image_url') description = fields.ObjectField(attr='description_indexing', properties=OBJECT_FIELD_PROPERTIES) establishment_type = fields.ObjectField( properties={ 'id': fields.IntegerField(), 'name': fields.ObjectField(attr='name_indexing', - properties=OBJECT_FIELD_PROPERTIES) + properties=OBJECT_FIELD_PROPERTIES), }) establishment_subtypes = fields.ObjectField( properties={ 'id': fields.IntegerField(), 'name': fields.ObjectField(attr='name_indexing', - properties=OBJECT_FIELD_PROPERTIES) + properties={ + 'id': fields.IntegerField(), + }), }, multi=True) tags = fields.ObjectField( properties={ - 'id': fields.IntegerField(attr='metadata.id'), - 'label': fields.ObjectField(attr='metadata.label_indexing', + 'id': fields.IntegerField(attr='id'), + 'label': fields.ObjectField(attr='label_indexing', properties=OBJECT_FIELD_PROPERTIES), - 'category': fields.ObjectField(attr='metadata.category', - properties={ - 'id': fields.IntegerField(), - }) }, multi=True) address = fields.ObjectField( @@ -50,7 +49,9 @@ class EstablishmentDocument(Document): fields={'raw': fields.KeywordField()} ), 'number': fields.IntegerField(), - 'location': fields.GeoPointField(attr='location_field_indexing'), + 'postal_code': fields.KeywordField(), + 'coordinates': fields.GeoPointField(attr='location_field_indexing'), + # todo: remove if not used 'city': fields.ObjectField( properties={ 'id': fields.IntegerField(), @@ -68,12 +69,13 @@ class EstablishmentDocument(Document): ), } ) - collections = fields.ObjectField( - properties={ - 'id': fields.IntegerField(attr='collection.id'), - 'collection_type': fields.IntegerField(attr='collection.collection_type'), - }, - multi=True) + # todo: need to fix + # collections = fields.ObjectField( + # properties={ + # 'id': fields.IntegerField(attr='collection.id'), + # 'collection_type': fields.IntegerField(attr='collection.collection_type'), + # }, + # multi=True) class Django: @@ -81,8 +83,11 @@ class EstablishmentDocument(Document): fields = ( 'id', 'name', - 'toque_number', + 'name_translated', 'price_level', + 'toque_number', + 'public_mark', + 'slug', ) def get_queryset(self): diff --git a/apps/search_indexes/documents/news.py b/apps/search_indexes/documents/news.py index bf67a0f6..99071e53 100644 --- a/apps/search_indexes/documents/news.py +++ b/apps/search_indexes/documents/news.py @@ -13,18 +13,24 @@ NewsIndex.settings(number_of_shards=1, number_of_replicas=1) class NewsDocument(Document): """News document.""" - news_type = fields.NestedField(properties={ - 'id': fields.IntegerField(), - 'name': fields.KeywordField() - }) - title = fields.ObjectField(properties=OBJECT_FIELD_PROPERTIES) - subtitle = fields.ObjectField(properties=OBJECT_FIELD_PROPERTIES) - description = fields.ObjectField(properties=OBJECT_FIELD_PROPERTIES) - country = fields.NestedField(properties={ - 'id': fields.IntegerField(), - 'code': fields.KeywordField() - }) + news_type = fields.ObjectField(properties={'id': fields.IntegerField(), + 'name': fields.KeywordField()}) + title = fields.ObjectField(attr='title_indexing', + properties=OBJECT_FIELD_PROPERTIES) + subtitle = fields.ObjectField(attr='subtitle_indexing', + properties=OBJECT_FIELD_PROPERTIES) + description = fields.ObjectField(attr='description_indexing', + properties=OBJECT_FIELD_PROPERTIES) + country = fields.ObjectField(properties={'id': fields.IntegerField(), + 'code': fields.KeywordField()}) web_url = fields.KeywordField(attr='web_url') + tags = fields.ObjectField( + properties={ + 'id': fields.IntegerField(attr='id'), + 'label': fields.ObjectField(attr='label_indexing', + properties=OBJECT_FIELD_PROPERTIES), + }, + multi=True) class Django: @@ -32,17 +38,24 @@ class NewsDocument(Document): fields = ( 'id', 'playlist', + 'start', + 'end', + 'slug', + 'state', + 'is_highlighted', + 'image_url', + 'preview_image_url', + 'template', ) related_models = [models.NewsType] def get_queryset(self): - return super().get_queryset().published() + return super().get_queryset().published().with_base_related() - def prepare_title(self, instance): - return instance.title - - def prepare_subtitle(self, instance): - return instance.subtitle - - def prepare_description(self, instance): - return instance.description + def get_instances_from_related(self, related_instance): + """If related_models is set, define how to retrieve the Car instance(s) from the related model. + The related_models option should be used with caution because it can lead in the index + to the updating of a lot of items. + """ + if isinstance(related_instance, models.NewsType): + return related_instance.news_set.all() diff --git a/apps/search_indexes/serializers.py b/apps/search_indexes/serializers.py index e6950bdd..18a1e240 100644 --- a/apps/search_indexes/serializers.py +++ b/apps/search_indexes/serializers.py @@ -1,16 +1,42 @@ """Search indexes serializers.""" from rest_framework import serializers from django_elasticsearch_dsl_drf.serializers import DocumentSerializer +from news.serializers import NewsTypeSerializer from search_indexes.documents import EstablishmentDocument, NewsDocument from search_indexes.utils import get_translated_value +class TagsDocumentSerializer(serializers.Serializer): + """Tags serializer for ES Document.""" + + id = serializers.IntegerField() + label_translated = serializers.SerializerMethodField() + + def get_label_translated(self, obj): + return get_translated_value(obj.label) + + +class AddressDocumentSerializer(serializers.Serializer): + """Address serializer for ES Document.""" + + id = serializers.IntegerField() + street_name_1 = serializers.CharField() + street_name_2 = serializers.CharField() + number = serializers.IntegerField() + postal_code = serializers.CharField() + latitude = serializers.FloatField(allow_null=True, source='coordinates.lat') + longitude = serializers.FloatField(allow_null=True, source='coordinates.lon') + geo_lon = serializers.FloatField(allow_null=True, source='coordinates.lon') + geo_lat = serializers.FloatField(allow_null=True, source='coordinates.lat') + + class NewsDocumentSerializer(DocumentSerializer): """News document serializer.""" title_translated = serializers.SerializerMethodField(allow_null=True) subtitle_translated = serializers.SerializerMethodField(allow_null=True) - description_translated = serializers.SerializerMethodField(allow_null=True) + news_type = NewsTypeSerializer() + tags = TagsDocumentSerializer(many=True) class Meta: """Meta class.""" @@ -18,13 +44,14 @@ class NewsDocumentSerializer(DocumentSerializer): document = NewsDocument fields = ( 'id', - 'title', - 'subtitle', - 'description', - 'web_url', 'title_translated', 'subtitle_translated', - 'description_translated', + 'is_highlighted', + 'image_url', + 'preview_image_url', + 'news_type', + 'tags', + 'slug', ) @staticmethod @@ -35,16 +62,12 @@ class NewsDocumentSerializer(DocumentSerializer): def get_subtitle_translated(obj): return get_translated_value(obj.subtitle) - @staticmethod - def get_description_translated(obj): - return get_translated_value(obj.description) - -# todo: country_name_translated class EstablishmentDocumentSerializer(DocumentSerializer): """Establishment document serializer.""" - description_translated = serializers.SerializerMethodField(allow_null=True) + address = AddressDocumentSerializer() + tags = TagsDocumentSerializer(many=True) class Meta: """Meta class.""" @@ -53,18 +76,40 @@ class EstablishmentDocumentSerializer(DocumentSerializer): fields = ( 'id', 'name', - 'description', - 'public_mark', - 'toque_number', + 'name_translated', 'price_level', - 'description_translated', - 'tags', + 'toque_number', + 'public_mark', + 'slug', + 'preview_image', 'address', - 'collections', - 'establishment_type', - 'establishment_subtypes', + 'tags', + # 'collections', + # 'establishment_type', + # 'establishment_subtypes', ) - @staticmethod - def get_description_translated(obj): - return get_translated_value(obj.description) + + # def to_representation(self, instance): + # ret = super().to_representation(instance) + # dict_merge = lambda a, b: a.update(b) or a + # + # ret['tags'] = map(lambda tag: dict_merge(tag, {'label_translated': get_translated_value(tag.pop('label'))}), + # ret['tags']) + # ret['establishment_subtypes'] = map( + # lambda subtype: dict_merge(subtype, {'name_translated': get_translated_value(subtype.pop('name'))}), + # ret['establishment_subtypes']) + # if ret.get('establishment_type'): + # ret['establishment_type']['name_translated'] = get_translated_value(ret['establishment_type'].pop('name')) + # if ret.get('address'): + # ret['address']['city']['country']['name_translated'] = get_translated_value( + # ret['address']['city']['country'].pop('name')) + # location = ret['address'].pop('location') + # if location: + # ret['address']['geo_lon'] = location['lon'] + # ret['address']['geo_lat'] = location['lat'] + # + # ret['type'] = ret.pop('establishment_type') + # ret['subtypes'] = ret.pop('establishment_subtypes') + # + # return ret \ No newline at end of file diff --git a/apps/search_indexes/signals.py b/apps/search_indexes/signals.py index 2c04b6c6..77660a2c 100644 --- a/apps/search_indexes/signals.py +++ b/apps/search_indexes/signals.py @@ -1,5 +1,5 @@ """Search indexes app signals.""" -from django.db.models.signals import post_save, post_delete +from django.db.models.signals import post_save from django.dispatch import receiver from django_elasticsearch_dsl.registries import registry @@ -17,17 +17,61 @@ def update_document(sender, **kwargs): address__city__country=instance) for establishment in establishments: registry.update(establishment) - if model_name == 'city': establishments = Establishment.objects.filter( address__city=instance) for establishment in establishments: registry.update(establishment) - if model_name == 'address': establishments = Establishment.objects.filter( address=instance) for establishment in establishments: registry.update(establishment) -# todo: delete document + if app_label == 'establishment': + # todo: remove after migration + from establishment import models as establishment_models + if model_name == 'establishmenttype': + if isinstance(instance, establishment_models.EstablishmentType): + establishments = Establishment.objects.filter( + establishment_type=instance) + for establishment in establishments: + registry.update(establishment) + if model_name == 'establishmentsubtype': + if instance(instance, establishment_models.EstablishmentSubType): + establishments = Establishment.objects.filter( + establishment_subtypes=instance) + for establishment in establishments: + registry.update(establishment) + + if app_label == 'tag': + if model_name == 'tag': + establishments = Establishment.objects.filter(tags=instance) + for establishment in establishments: + registry.update(establishment) + + +@receiver(post_save) +def update_news(sender, **kwargs): + from news.models import News + app_label = sender._meta.app_label + model_name = sender._meta.model_name + instance = kwargs['instance'] + + if app_label == 'location': + if model_name == 'country': + qs = News.objects.filter(country=instance) + for news in qs: + registry.update(news) + + if app_label == 'news': + if model_name == 'newstype': + qs = News.objects.filter(news_type=instance) + for news in qs: + registry.update(news) + + if app_label == 'tag': + if model_name == 'tag': + qs = News.objects.filter(tags=instance) + for news in qs: + registry.update(news) diff --git a/apps/search_indexes/urls.py b/apps/search_indexes/urls.py index 60b05fb5..549e569d 100644 --- a/apps/search_indexes/urls.py +++ b/apps/search_indexes/urls.py @@ -4,7 +4,10 @@ from search_indexes import views router = routers.SimpleRouter() -router.register(r'news', views.NewsDocumentViewSet, basename='news') +# router.register(r'news', views.NewsDocumentViewSet, basename='news') # temporarily disabled router.register(r'establishments', views.EstablishmentDocumentViewSet, basename='establishment') +router.register(r'mobile/establishments', views.EstablishmentDocumentViewSet, basename='establishment-mobile') +router.register(r'news', views.NewsDocumentViewSet, basename='news') urlpatterns = router.urls + diff --git a/apps/search_indexes/utils.py b/apps/search_indexes/utils.py index 93be9e81..0c1dd187 100644 --- a/apps/search_indexes/utils.py +++ b/apps/search_indexes/utils.py @@ -17,4 +17,6 @@ def get_translated_value(value): return None elif not isinstance(value, dict): field_dict = value.to_dict() + elif isinstance(value, dict): + field_dict = value return field_dict.get(get_current_language()) diff --git a/apps/search_indexes/views.py b/apps/search_indexes/views.py index 1547fd9d..50c32fc7 100644 --- a/apps/search_indexes/views.py +++ b/apps/search_indexes/views.py @@ -1,46 +1,59 @@ """Search indexes app views.""" from rest_framework import permissions from django_elasticsearch_dsl_drf import constants -from django_elasticsearch_dsl_drf.filter_backends import (FilteringFilterBackend, - GeoSpatialFilteringFilterBackend) +from django_elasticsearch_dsl_drf.filter_backends import ( + FilteringFilterBackend, + GeoSpatialFilteringFilterBackend +) from django_elasticsearch_dsl_drf.viewsets import BaseDocumentViewSet -from django_elasticsearch_dsl_drf.pagination import PageNumberPagination from search_indexes import serializers, filters from search_indexes.documents import EstablishmentDocument, NewsDocument +from utils.pagination import ProjectPageNumberPagination class NewsDocumentViewSet(BaseDocumentViewSet): """News document ViewSet.""" document = NewsDocument - lookup_field = 'id' - pagination_class = PageNumberPagination + lookup_field = 'slug' + pagination_class = ProjectPageNumberPagination permission_classes = (permissions.AllowAny,) serializer_class = serializers.NewsDocumentSerializer ordering = ('id',) filter_backends = [ filters.CustomSearchFilterBackend, + FilteringFilterBackend, ] - search_fields = ( - 'title', - 'subtitle', - 'description', - ) + search_fields = { + 'title': {'fuzziness': 'auto:3,4'}, + 'subtitle': {'fuzziness': 'auto'}, + 'description': {'fuzziness': 'auto'}, + } translated_search_fields = ( 'title', 'subtitle', 'description', ) + filter_fields = { + 'tag': { + 'field': 'tags.id', + 'lookups': [ + constants.LOOKUP_QUERY_IN, + ] + }, + 'slug': 'slug', + } + class EstablishmentDocumentViewSet(BaseDocumentViewSet): """Establishment document ViewSet.""" document = EstablishmentDocument - lookup_field = 'id' - pagination_class = PageNumberPagination + lookup_field = 'slug' + pagination_class = ProjectPageNumberPagination permission_classes = (permissions.AllowAny,) serializer_class = serializers.EstablishmentDocumentSerializer ordering = ('id',) @@ -51,15 +64,20 @@ class EstablishmentDocumentViewSet(BaseDocumentViewSet): GeoSpatialFilteringFilterBackend, ] - search_fields = ( - 'name', - 'description', - ) + search_fields = { + 'name': {'fuzziness': 'auto:3,4'}, + 'name_translated': {'fuzziness': 'auto:3,4'}, + 'description': {'fuzziness': 'auto'}, + } translated_search_fields = ( 'description', ) filter_fields = { - 'tag': 'tags.id', + 'slug': 'slug', + 'tag': { + 'field': 'tags.id', + 'lookups': [constants.LOOKUP_QUERY_IN] + }, 'toque_number': { 'field': 'toque_number', 'lookups': [ @@ -107,7 +125,7 @@ class EstablishmentDocumentViewSet(BaseDocumentViewSet): geo_spatial_filter_fields = { 'location': { - 'field': 'address.location', + 'field': 'address.coordinates', 'lookups': [ constants.LOOKUP_FILTER_GEO_BOUNDING_BOX, ] diff --git a/apps/tag/__init__.py b/apps/tag/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/tag/admin.py b/apps/tag/admin.py new file mode 100644 index 00000000..ea7f9394 --- /dev/null +++ b/apps/tag/admin.py @@ -0,0 +1,12 @@ +from django.contrib import admin +from .models import Tag, TagCategory + + +@admin.register(Tag) +class TagAdmin(admin.ModelAdmin): + """Admin model for model Tag.""" + + +@admin.register(TagCategory) +class TagCategoryAdmin(admin.ModelAdmin): + """Admin model for model TagCategory.""" diff --git a/apps/tag/apps.py b/apps/tag/apps.py new file mode 100644 index 00000000..a1cce249 --- /dev/null +++ b/apps/tag/apps.py @@ -0,0 +1,7 @@ +from django.apps import AppConfig +from django.utils.translation import gettext_lazy as _ + + +class TagConfig(AppConfig): + name = 'tag' + verbose_name = _('tag') diff --git a/apps/tag/filters.py b/apps/tag/filters.py new file mode 100644 index 00000000..8816f820 --- /dev/null +++ b/apps/tag/filters.py @@ -0,0 +1,42 @@ +"""Tag app filters.""" +from django_filters import rest_framework as filters +from establishment.models import EstablishmentType +from tag import models + + +class TagCategoryFilterSet(filters.FilterSet): + """TagCategory filterset.""" + + # Object type choices + NEWS = 'news' + ESTABLISHMENT = 'establishment' + + TYPE_CHOICES = ( + (NEWS, 'News'), + (ESTABLISHMENT, 'Establishment'), + ) + + type = filters.MultipleChoiceFilter(choices=TYPE_CHOICES, + method='filter_by_type') + + establishment_type = filters.ChoiceFilter( + choices=EstablishmentType.INDEX_NAME_TYPES, + method='by_establishment_type') + + class Meta: + """Meta class.""" + + model = models.TagCategory + fields = ('type', + 'establishment_type', ) + + def filter_by_type(self, queryset, name, value): + if self.NEWS in value: + queryset = queryset.for_news() + if self.ESTABLISHMENT in value: + queryset = queryset.for_establishments() + return queryset + + # todo: filter by establishment type + def by_establishment_type(self, queryset, name, value): + return queryset.by_establishment_type(value) diff --git a/apps/tag/migrations/0001_initial.py b/apps/tag/migrations/0001_initial.py new file mode 100644 index 00000000..543eb035 --- /dev/null +++ b/apps/tag/migrations/0001_initial.py @@ -0,0 +1,44 @@ +# Generated by Django 2.2.4 on 2019-10-09 07:15 + +from django.db import migrations, models +import django.db.models.deletion +import utils.models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('location', '0010_auto_20190904_0711'), + ] + + operations = [ + migrations.CreateModel( + name='TagCategory', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('label', utils.models.TJSONField(blank=True, default=None, help_text='{"en-GB":"some text"}', null=True, verbose_name='label')), + ('public', models.BooleanField(default=False)), + ('country', models.ForeignKey(default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to='location.Country')), + ], + options={ + 'verbose_name': 'tag category', + 'verbose_name_plural': 'tag categories', + }, + bases=(utils.models.TranslatedFieldsMixin, models.Model), + ), + migrations.CreateModel( + name='Tag', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('label', utils.models.TJSONField(blank=True, default=None, help_text='{"en-GB":"some text"}', null=True, verbose_name='label')), + ('category', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='tags', to='tag.TagCategory', verbose_name='category')), + ], + options={ + 'verbose_name': 'tag', + 'verbose_name_plural': 'tags', + }, + bases=(utils.models.TranslatedFieldsMixin, models.Model), + ), + ] diff --git a/apps/tag/migrations/0002_auto_20191009_1408.py b/apps/tag/migrations/0002_auto_20191009_1408.py new file mode 100644 index 00000000..472d9596 --- /dev/null +++ b/apps/tag/migrations/0002_auto_20191009_1408.py @@ -0,0 +1,27 @@ +# Generated by Django 2.2.4 on 2019-10-09 14:08 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('tag', '0001_initial'), + ] + + operations = [ + migrations.AlterModelOptions( + name='tag', + options={'verbose_name': 'Tag', 'verbose_name_plural': 'Tags'}, + ), + migrations.AlterModelOptions( + name='tagcategory', + options={'verbose_name': 'Tag category', 'verbose_name_plural': 'Tag categories'}, + ), + migrations.AlterField( + model_name='tag', + name='category', + field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='tags', to='tag.TagCategory', verbose_name='Category'), + ), + ] diff --git a/apps/tag/migrations/0003_auto_20191018_0758.py b/apps/tag/migrations/0003_auto_20191018_0758.py new file mode 100644 index 00000000..3814d05a --- /dev/null +++ b/apps/tag/migrations/0003_auto_20191018_0758.py @@ -0,0 +1,19 @@ +# Generated by Django 2.2.4 on 2019-10-18 07:58 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('tag', '0002_auto_20191009_1408'), + ] + + operations = [ + migrations.AlterField( + model_name='tag', + name='category', + field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='tags', to='tag.TagCategory', verbose_name='Category'), + ), + ] diff --git a/apps/tag/migrations/0004_tag_priority.py b/apps/tag/migrations/0004_tag_priority.py new file mode 100644 index 00000000..3e7a6d7f --- /dev/null +++ b/apps/tag/migrations/0004_tag_priority.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-10-21 13:46 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('tag', '0003_auto_20191018_0758'), + ] + + operations = [ + migrations.AddField( + model_name='tag', + name='priority', + field=models.IntegerField(default=None, null=True, unique=True), + ), + ] diff --git a/apps/tag/migrations/__init__.py b/apps/tag/migrations/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/tag/models.py b/apps/tag/models.py new file mode 100644 index 00000000..44eacddc --- /dev/null +++ b/apps/tag/models.py @@ -0,0 +1,86 @@ +"""Tag app models.""" +from django.db import models +from django.utils.translation import gettext_lazy as _ +from configuration.models import TranslationSettings +from utils.models import TJSONField, TranslatedFieldsMixin + + +class Tag(TranslatedFieldsMixin, models.Model): + """Tag model.""" + + label = TJSONField(blank=True, null=True, default=None, + verbose_name=_('label'), + help_text='{"en-GB":"some text"}') + category = models.ForeignKey('TagCategory', on_delete=models.CASCADE, + null=True, related_name='tags', + verbose_name=_('Category')) + priority = models.IntegerField(unique=True, null=True, default=None) + + class Meta: + """Meta class.""" + + verbose_name = _('Tag') + verbose_name_plural = _('Tags') + + def __str__(self): + label = 'None' + lang = TranslationSettings.get_solo().default_language + if self.label and lang in self.label: + label = self.label[lang] + return f'id:{self.id}-{label}' + + +class TagCategoryQuerySet(models.QuerySet): + """Extended queryset for TagCategory model.""" + + def with_base_related(self): + """Select related objects.""" + return self.prefetch_related('tags') + + def with_extended_related(self): + """Select related objects.""" + return self.select_related('country') + + def for_news(self): + """Select tag categories for news.""" + return self.filter(news_types__isnull=True) + + def for_establishments(self): + """Select tag categories for establishments.""" + return self.filter(models.Q(establishment_types__isnull=False) | + models.Q(establishment_subtypes__isnull=False)) + + def by_establishment_type(self, index_name): + """Filter by establishment type index name.""" + return self.filter(establishment_types__index_name=index_name) + + def with_tags(self, switcher=True): + """Filter by existing tags.""" + return self.filter(tags__isnull=not switcher) + + +class TagCategory(TranslatedFieldsMixin, models.Model): + """Tag base category model.""" + + label = TJSONField(blank=True, null=True, default=None, + verbose_name=_('label'), + help_text='{"en-GB":"some text"}') + country = models.ForeignKey('location.Country', + on_delete=models.SET_NULL, null=True, + default=None) + public = models.BooleanField(default=False) + + objects = TagCategoryQuerySet.as_manager() + + class Meta: + """Meta class.""" + + verbose_name = _('Tag category') + verbose_name_plural = _('Tag categories') + + def __str__(self): + label = 'None' + lang = TranslationSettings.get_solo().default_language + if self.label and lang in self.label: + label = self.label[lang] + return f'id:{self.id}-{label}' diff --git a/apps/tag/serializers.py b/apps/tag/serializers.py new file mode 100644 index 00000000..6ee55c84 --- /dev/null +++ b/apps/tag/serializers.py @@ -0,0 +1,167 @@ +"""Tag serializers.""" +from rest_framework import serializers +from establishment.models import (Establishment, EstablishmentType, + EstablishmentSubType) +from news.models import News, NewsType +from tag import models +from utils.exceptions import (ObjectAlreadyAdded, BindingObjectNotFound, + RemovedBindingObjectNotFound) +from utils.serializers import TranslatedField + + +class TagBaseSerializer(serializers.ModelSerializer): + """Serializer for model Tag.""" + + label_translated = TranslatedField() + + class Meta: + """Meta class.""" + + model = models.Tag + fields = ( + 'id', + 'label_translated', + ) + + +class TagBackOfficeSerializer(TagBaseSerializer): + """Serializer for Tag model for Back office users.""" + + class Meta(TagBaseSerializer.Meta): + """Meta class.""" + + fields = TagBaseSerializer.Meta.fields + ( + 'label', + 'category' + ) + + +class TagCategoryBaseSerializer(serializers.ModelSerializer): + """Serializer for model TagCategory.""" + + label_translated = TranslatedField() + tags = TagBaseSerializer(many=True, read_only=True) + + class Meta: + """Meta class.""" + + model = models.TagCategory + fields = ( + 'id', + 'label_translated', + 'tags' + ) + + +class TagCategoryBackOfficeDetailSerializer(TagCategoryBaseSerializer): + """Tag Category detail serializer for back-office users.""" + + country_translated = TranslatedField(source='country.name_translated') + + class Meta(TagCategoryBaseSerializer.Meta): + """Meta class.""" + + fields = TagCategoryBaseSerializer.Meta.fields + ( + 'label', + 'country', + 'country_translated', + ) + + +class TagBindObjectSerializer(serializers.Serializer): + """Serializer for binding tag category and objects""" + + ESTABLISHMENT = 'establishment' + NEWS = 'news' + + TYPE_CHOICES = ( + (ESTABLISHMENT, 'Establishment type'), + (NEWS, 'News type'), + ) + + type = serializers.ChoiceField(TYPE_CHOICES) + object_id = serializers.IntegerField() + + def validate(self, attrs): + view = self.context.get('view') + request = self.context.get('request') + + obj_type = attrs.get('type') + obj_id = attrs.get('object_id') + + tag = view.get_object() + attrs['tag'] = tag + + if obj_type == self.ESTABLISHMENT: + establishment = Establishment.objects.filter(pk=obj_id).first() + if not establishment: + raise BindingObjectNotFound() + if request.method == 'POST' and tag.establishments.filter( + pk=establishment.pk).exists(): + raise ObjectAlreadyAdded() + if request.method == 'DELETE' and not tag.establishments.filter( + pk=establishment.pk).exists(): + raise RemovedBindingObjectNotFound() + attrs['related_object'] = establishment + elif obj_type == self.NEWS: + news = News.objects.filter(pk=obj_id).first() + if not news: + raise BindingObjectNotFound() + if request.method == 'POST' and tag.news.filter(pk=news.pk).exists(): + raise ObjectAlreadyAdded() + if request.method == 'DELETE' and not tag.news.filter( + pk=news.pk).exists(): + raise RemovedBindingObjectNotFound() + attrs['related_object'] = news + return attrs + + +class TagCategoryBindObjectSerializer(serializers.Serializer): + """Serializer for binding tag category and objects""" + + ESTABLISHMENT_TYPE = 'establishment_type' + NEWS_TYPE = 'news_type' + + TYPE_CHOICES = ( + (ESTABLISHMENT_TYPE, 'Establishment type'), + (NEWS_TYPE, 'News type'), + ) + + type = serializers.ChoiceField(TYPE_CHOICES) + object_id = serializers.IntegerField() + + def validate(self, attrs): + view = self.context.get('view') + request = self.context.get('request') + + obj_type = attrs.get('type') + obj_id = attrs.get('object_id') + + tag_category = view.get_object() + attrs['tag_category'] = tag_category + + if obj_type == self.ESTABLISHMENT_TYPE: + establishment_type = EstablishmentType.objects.filter(pk=obj_id).\ + first() + if not establishment_type: + raise BindingObjectNotFound() + if request.method == 'POST' and tag_category.establishment_types.\ + filter(pk=establishment_type.pk).exists(): + raise ObjectAlreadyAdded() + if request.method == 'DELETE' and not tag_category.\ + establishment_types.filter(pk=establishment_type.pk).\ + exists(): + raise RemovedBindingObjectNotFound() + attrs['related_object'] = establishment_type + elif obj_type == self.NEWS_TYPE: + news_type = NewsType.objects.filter(pk=obj_id).first() + if not news_type: + raise BindingObjectNotFound() + if request.method == 'POST' and tag_category.news_types.\ + filter(pk=news_type.pk).exists(): + raise ObjectAlreadyAdded() + if request.method == 'DELETE' and not tag_category.news_types.\ + filter(pk=news_type.pk).exists(): + raise RemovedBindingObjectNotFound() + attrs['related_object'] = news_type + return attrs diff --git a/apps/tag/tests.py b/apps/tag/tests.py new file mode 100644 index 00000000..7ce503c2 --- /dev/null +++ b/apps/tag/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/apps/tag/urls/__init__.py b/apps/tag/urls/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/tag/urls/back.py b/apps/tag/urls/back.py new file mode 100644 index 00000000..03733297 --- /dev/null +++ b/apps/tag/urls/back.py @@ -0,0 +1,11 @@ +"""Urlconf for app tag.""" +from rest_framework.routers import SimpleRouter +from tag import views + +app_name = 'tag' + +router = SimpleRouter() +router.register(r'categories', views.TagCategoryBackOfficeViewSet) +router.register(r'', views.TagBackOfficeViewSet) + +urlpatterns = router.urls diff --git a/apps/tag/urls/web.py b/apps/tag/urls/web.py new file mode 100644 index 00000000..c99253eb --- /dev/null +++ b/apps/tag/urls/web.py @@ -0,0 +1,16 @@ +"""Tag app urlpatterns web users.""" +from rest_framework.routers import SimpleRouter +from tag import views + + +app_name = 'tag' + +router = SimpleRouter() +router.register(r'categories', views.TagCategoryViewSet) + +urlpatterns = [ + +] + +urlpatterns += router.urls + diff --git a/apps/tag/views.py b/apps/tag/views.py new file mode 100644 index 00000000..2a0ff0f5 --- /dev/null +++ b/apps/tag/views.py @@ -0,0 +1,111 @@ +"""Tag views.""" +from rest_framework import viewsets, mixins, status +from rest_framework.decorators import action +from rest_framework.response import Response +from tag import filters, models, serializers +from rest_framework import permissions + + +# User`s views & viewsets +class TagCategoryViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): + """ViewSet for TagCategory model.""" + + filterset_class = filters.TagCategoryFilterSet + pagination_class = None + permission_classes = (permissions.AllowAny, ) + queryset = models.TagCategory.objects.with_tags().with_base_related().\ + distinct() + serializer_class = serializers.TagCategoryBaseSerializer + + +# BackOffice user`s views & viewsets +class BindObjectMixin: + """Bind object mixin.""" + + def get_serializer_class(self): + if self.action == 'bind_object': + return self.bind_object_serializer_class + return self.serializer_class + + def perform_binding(self, serializer): + raise NotImplemented + + def perform_unbinding(self, serializer): + raise NotImplemented + + @action(methods=['post', 'delete'], detail=True, url_path='bind-object') + def bind_object(self, request, pk=None): + serializer = self.get_serializer(data=request.data) + serializer.is_valid(raise_exception=True) + if request.method == 'POST': + self.perform_binding(serializer) + return Response(serializer.data, status=status.HTTP_201_CREATED) + elif request.method == 'DELETE': + self.perform_unbinding(serializer) + return Response(status=status.HTTP_204_NO_CONTENT) + + +class TagBackOfficeViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, + mixins.UpdateModelMixin, mixins.DestroyModelMixin, + BindObjectMixin, viewsets.GenericViewSet): + """List/create tag view.""" + + pagination_class = None + permission_classes = (permissions.IsAuthenticated, ) + queryset = models.Tag.objects.all() + serializer_class = serializers.TagBackOfficeSerializer + bind_object_serializer_class = serializers.TagBindObjectSerializer + + def perform_binding(self, serializer): + data = serializer.validated_data + tag = data.pop('tag') + obj_type = data.get('type') + related_object = data.get('related_object') + if obj_type == self.bind_object_serializer_class.ESTABLISHMENT: + tag.establishments.add(related_object) + elif obj_type == self.bind_object_serializer_class.NEWS: + tag.news.add(related_object) + + def perform_unbinding(self, serializer): + data = serializer.validated_data + tag = data.pop('tag') + obj_type = data.get('type') + related_object = data.get('related_object') + if obj_type == self.bind_object_serializer_class.ESTABLISHMENT: + tag.establishments.remove(related_object) + elif obj_type == self.bind_object_serializer_class.NEWS: + tag.news.remove(related_object) + + +class TagCategoryBackOfficeViewSet(mixins.CreateModelMixin, + mixins.UpdateModelMixin, + mixins.DestroyModelMixin, + mixins.RetrieveModelMixin, + BindObjectMixin, + TagCategoryViewSet): + """ViewSet for TagCategory model for BackOffice users.""" + + permission_classes = (permissions.IsAuthenticated, ) + queryset = TagCategoryViewSet.queryset.with_extended_related() + serializer_class = serializers.TagCategoryBackOfficeDetailSerializer + bind_object_serializer_class = serializers.TagCategoryBindObjectSerializer + + def perform_binding(self, serializer): + data = serializer.validated_data + tag_category = data.pop('tag_category') + obj_type = data.get('type') + related_object = data.get('related_object') + if obj_type == self.bind_object_serializer_class.ESTABLISHMENT_TYPE: + tag_category.establishment_types.add(related_object) + elif obj_type == self.bind_object_serializer_class.NEWS_TYPE: + tag_category.news_types.add(related_object) + + def perform_unbinding(self, serializer): + data = serializer.validated_data + tag_category = data.pop('tag_category') + obj_type = data.get('type') + related_object = data.get('related_object') + if obj_type == self.bind_object_serializer_class.ESTABLISHMENT_TYPE: + tag_category.establishment_types.remove(related_object) + elif obj_type == self.bind_object_serializer_class.NEWS_TYPE: + tag_category.news_types.remove(related_object) diff --git a/apps/timetable/migrations/0003_auto_20191003_0943.py b/apps/timetable/migrations/0003_auto_20191003_0943.py new file mode 100644 index 00000000..4c5a22b4 --- /dev/null +++ b/apps/timetable/migrations/0003_auto_20191003_0943.py @@ -0,0 +1,17 @@ +# Generated by Django 2.2.4 on 2019-10-03 09:43 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('timetable', '0002_auto_20190919_1124'), + ] + + operations = [ + migrations.AlterModelOptions( + name='timetable', + options={'ordering': ['weekday'], 'verbose_name': 'Timetable', 'verbose_name_plural': 'Timetables'}, + ), + ] diff --git a/apps/timetable/models.py b/apps/timetable/models.py index e1e7fae7..53670d02 100644 --- a/apps/timetable/models.py +++ b/apps/timetable/models.py @@ -36,3 +36,4 @@ class Timetable(ProjectBaseMixin): """Meta class.""" verbose_name = _('Timetable') verbose_name_plural = _('Timetables') + ordering = ['weekday'] diff --git a/apps/translation/migrations/0004_auto_20191018_0832.py b/apps/translation/migrations/0004_auto_20191018_0832.py new file mode 100644 index 00000000..d2d26a2b --- /dev/null +++ b/apps/translation/migrations/0004_auto_20191018_0832.py @@ -0,0 +1,18 @@ +# Generated by Django 2.2.4 on 2019-10-18 08:32 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('translation', '0003_auto_20190901_1032'), + ] + + operations = [ + migrations.AlterField( + model_name='language', + name='locale', + field=models.CharField(max_length=10, unique=True, verbose_name='Locale identifier'), + ), + ] diff --git a/apps/translation/migrations/0005_auto_20191021_1201.py b/apps/translation/migrations/0005_auto_20191021_1201.py new file mode 100644 index 00000000..61cc3294 --- /dev/null +++ b/apps/translation/migrations/0005_auto_20191021_1201.py @@ -0,0 +1,22 @@ +# Generated by Django 2.2.4 on 2019-10-21 12:01 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('translation', '0004_auto_20191018_0832'), + ] + + operations = [ + migrations.AlterField( + model_name='language', + name='locale', + field=models.CharField(max_length=10, verbose_name='Locale identifier'), + ), + migrations.AlterUniqueTogether( + name='language', + unique_together={('title', 'locale')}, + ), + ] diff --git a/apps/translation/models.py b/apps/translation/models.py index 42530965..cb0729ea 100644 --- a/apps/translation/models.py +++ b/apps/translation/models.py @@ -32,6 +32,7 @@ class Language(models.Model): verbose_name = _('Language') verbose_name_plural = _('Languages') + unique_together = ('title', 'locale') def __str__(self): """String method""" diff --git a/apps/utils/authentication.py b/apps/utils/authentication.py index 044d6d75..e8375ffe 100644 --- a/apps/utils/authentication.py +++ b/apps/utils/authentication.py @@ -23,14 +23,24 @@ class GMJWTAuthentication(JWTAuthentication): """ def authenticate(self, request): - token = get_token_from_cookies(request) - if token is None: + try: + token = get_token_from_cookies(request) + # Return non-authorized user if token not in cookies + assert token + + raw_token = self.get_raw_token(token) + # Return non-authorized user if cant get raw token + assert raw_token + + validated_token = self.get_validated_token(raw_token) + user = self.get_user(validated_token) + + # Check record in DB + token_is_valid = user.access_tokens.valid() \ + .by_jti(jti=validated_token.payload.get('jti')) + assert token_is_valid.exists() + except: + # Return non-authorized user if token is invalid or raised an error when run checks. return None - - raw_token = self.get_raw_token(token) - if raw_token is None: - return None - - validated_token = self.get_validated_token(raw_token) - - return self.get_user(validated_token), None + else: + return user, None diff --git a/apps/utils/decorators.py b/apps/utils/decorators.py new file mode 100644 index 00000000..c48a26c7 --- /dev/null +++ b/apps/utils/decorators.py @@ -0,0 +1,21 @@ + +def with_base_attributes(cls): + + def validate(self, data): + user = None + request = self.context.get("request") + + if request and hasattr(request, "user"): + user = request.user + + if user is not None: + data.update({'modified_by': user}) + + if not self.instance: + data.update({'created_by': user}) + + return data + + setattr(cls, "validate", validate) + + return cls diff --git a/apps/utils/exceptions.py b/apps/utils/exceptions.py index df9c2c27..37786ce7 100644 --- a/apps/utils/exceptions.py +++ b/apps/utils/exceptions.py @@ -1,5 +1,5 @@ from django.utils.translation import gettext_lazy as _ -from rest_framework import exceptions, status +from rest_framework import exceptions, serializers, status class ProjectBaseException(exceptions.APIException): @@ -123,7 +123,7 @@ class WrongAuthCredentials(AuthErrorMixin): """ The exception should be raised when credentials is not valid for this user """ - default_detail = _('Wrong authorization credentials') + default_detail = _('Incorrect login or password.') class FavoritesError(exceptions.APIException): @@ -142,3 +142,24 @@ class PasswordResetRequestExistedError(exceptions.APIException): """ status_code = status.HTTP_400_BAD_REQUEST default_detail = _('Password reset request is already exists and valid.') + + +class ObjectAlreadyAdded(serializers.ValidationError): + """ + The exception must be thrown if the object has already been added to the + list. + """ + + default_detail = _('Object has already been added.') + + +class BindingObjectNotFound(serializers.ValidationError): + """The exception must be thrown if the object not found.""" + + default_detail = _('Binding object not found.') + + +class RemovedBindingObjectNotFound(serializers.ValidationError): + """The exception must be thrown if the object not found.""" + + default_detail = _('Removed binding object not found.') diff --git a/apps/utils/middleware.py b/apps/utils/middleware.py index 7203127c..f3936169 100644 --- a/apps/utils/middleware.py +++ b/apps/utils/middleware.py @@ -19,6 +19,7 @@ def parse_cookies(get_response): cookie_dict = request.COOKIES # processing locale cookie locale = get_locale(cookie_dict) + # todo: don't use DB!!! Use cache if not Language.objects.filter(locale=locale).exists(): locale = TranslationSettings.get_solo().default_language translation.activate(locale) @@ -31,14 +32,3 @@ def parse_cookies(get_response): response = get_response(request) return response return middleware - - -class CORSMiddleware: - """Added parameter {Access-Control-Allow-Origin: *} to response""" - def __init__(self, get_response): - self.get_response = get_response - - def __call__(self, request): - response = self.get_response(request) - response["Access-Control-Allow-Origin"] = '*' - return response diff --git a/apps/utils/models.py b/apps/utils/models.py index 632cf4a2..4e6df35e 100644 --- a/apps/utils/models.py +++ b/apps/utils/models.py @@ -10,6 +10,8 @@ from django.utils.translation import ugettext_lazy as _, get_language from easy_thumbnails.fields import ThumbnailerImageField from utils.methods import image_path, svg_image_path from utils.validators import svg_image_validator +from django.db.models.fields import Field +from django.core import exceptions class ProjectBaseMixin(models.Model): @@ -26,6 +28,10 @@ class ProjectBaseMixin(models.Model): abstract = True +def valid(value): + print("Run") + + class TJSONField(JSONField): """Overrided JsonField.""" @@ -52,6 +58,7 @@ def translate_field(self, field_name): if isinstance(field, dict): return field.get(to_locale(get_language())) return None + return translate @@ -70,6 +77,7 @@ def index_field(self, field_name): for key, value in field.items(): setattr(obj, key, value) return obj + return index @@ -236,7 +244,8 @@ class LocaleManagerMixin(models.Manager): queryset = self.filter(**filters) # Prepare field for annotator - localized_fields = {f'{field}_{prefix}': KeyTextTransform(f'{locale}', field) for field in fields} + localized_fields = {f'{field}_{prefix}': KeyTextTransform(f'{locale}', field) for field in + fields} # Annotate them for _ in fields: @@ -245,7 +254,6 @@ class LocaleManagerMixin(models.Manager): class GMTokenGenerator(PasswordResetTokenGenerator): - CHANGE_EMAIL = 0 RESET_PASSWORD = 1 CHANGE_PASSWORD = 2 @@ -268,10 +276,10 @@ class GMTokenGenerator(PasswordResetTokenGenerator): """ fields = [str(timestamp), str(user.is_active), str(user.pk)] if self.purpose == self.CHANGE_EMAIL or \ - self.purpose == self.CONFIRM_EMAIL: + self.purpose == self.CONFIRM_EMAIL: fields.extend([str(user.email_confirmed), str(user.email)]) elif self.purpose == self.RESET_PASSWORD or \ - self.purpose == self.CHANGE_PASSWORD: + self.purpose == self.CHANGE_PASSWORD: fields.append(str(user.password)) return fields diff --git a/apps/utils/pagination.py b/apps/utils/pagination.py index 85bd293c..2c9e92e5 100644 --- a/apps/utils/pagination.py +++ b/apps/utils/pagination.py @@ -1,6 +1,8 @@ """Pagination settings.""" from base64 import b64encode from urllib import parse as urlparse + +from django.conf import settings from rest_framework.pagination import PageNumberPagination, CursorPagination @@ -44,3 +46,10 @@ class ProjectMobilePagination(ProjectPageNumberPagination): if not self.page.has_previous(): return None return self.page.previous_page_number() + + +class EstablishmentPortionPagination(ProjectMobilePagination): + """ + Pagination for app establishments with limit page size equal to 12 + """ + page_size = settings.LIMITING_OUTPUT_OBJECTS diff --git a/apps/utils/permissions.py b/apps/utils/permissions.py index 09b24ecd..45d978a0 100644 --- a/apps/utils/permissions.py +++ b/apps/utils/permissions.py @@ -1,12 +1,15 @@ """Project custom permissions""" -from rest_framework.permissions import BasePermission +from django.contrib.contenttypes.models import ContentType + +from rest_framework import permissions from rest_framework_simplejwt.tokens import AccessToken +from account.models import UserRole, Role from authorization.models import JWTRefreshToken from utils.tokens import GMRefreshToken -class IsAuthenticatedAndTokenIsValid(BasePermission): +class IsAuthenticatedAndTokenIsValid(permissions.BasePermission): """ Check if user has a valid token and authenticated """ @@ -24,7 +27,7 @@ class IsAuthenticatedAndTokenIsValid(BasePermission): return False -class IsRefreshTokenValid(BasePermission): +class IsRefreshTokenValid(permissions.BasePermission): """ Check if user has a valid refresh token and authenticated """ @@ -38,3 +41,158 @@ class IsRefreshTokenValid(BasePermission): return refresh_token_qs.exists() else: return False + + def has_object_permission(self, request, view, obj): + # Read permissions are allowed to any request, + # so we'll always allow GET, HEAD or OPTIONS requests. + if request.method in permissions.SAFE_METHODS or \ + obj.user == request.user or request.user.is_superuser: + return True + return False + + +class IsGuest(permissions.IsAuthenticatedOrReadOnly): + """ + Object-level permission to only allow owners of an object to edit it. + """ + def has_permission(self, request, view): + return request.user.is_authenticated + + def has_object_permission(self, request, view, obj): + + rules = [ + request.user.is_superuser, + request.method in permissions.SAFE_METHODS + ] + return any(rules) + + +class IsStandardUser(IsGuest): + """ + Object-level permission to only allow owners of an object to edit it. + Assumes the model instance has an `owner` attribute. + """ + def has_object_permission(self, request, view, obj): + # Read permissions are allowed to any request + rules = [ + super().has_object_permission(request, view, obj) + ] + + if hasattr(obj, 'user'): + rules = [ + obj.user == request.user and obj.user.email_confirmed, + super().has_object_permission(request, view, obj) + ] + + return any(rules) + + +class IsContentPageManager(IsStandardUser): + """ + Object-level permission to only allow owners of an object to edit it. + Assumes the model instance has an `owner` attribute. + """ + def has_object_permission(self, request, view, obj): + # Read permissions are allowed to any request. + + role = Role.objects.filter(role=Role.CONTENT_PAGE_MANAGER, + country_id=obj.country_id)\ + .first() # 'Comments moderator' + + rules = [ + UserRole.objects.filter(user=request.user, role=role).exists(), + # and obj.user != request.user, + super().has_object_permission(request, view, obj) + ] + return any(rules) + + +class IsCountryAdmin(IsStandardUser): + """ + Object-level permission to only allow owners of an object to edit it. + Assumes the model instance has an `owner` attribute. + """ + def has_object_permission(self, request, view, obj): + # Read permissions are allowed to any request. + role = Role.objects.filter(role=Role.COUNTRY_ADMIN, + country_id=obj.country_id) \ + .first() # 'Comments moderator' + + rules = [ + UserRole.objects.filter(user=request.user, role=role).exists(), + super().has_object_permission(request, view, obj), + ] + + return any(rules) + + +class IsCommentModerator(IsStandardUser): + """ + Object-level permission to only allow owners of an object to edit it. + Assumes the model instance has an `owner` attribute. + """ + def has_object_permission(self, request, view, obj): + # Read permissions are allowed to any request. + role = Role.objects.filter(role=Role.COMMENTS_MODERATOR, + country_id=obj.country_id)\ + .first() # 'Comments moderator' + + rules = [ + UserRole.objects.filter(user=request.user, role=role).exists() and + obj.user != request.user, + super().has_object_permission(request, view, obj) + ] + return any(rules) + + +class IsEstablishmentManager(IsStandardUser): + + def has_object_permission(self, request, view, obj): + role = Role.objects.filter(role=Role.ESTABLISHMENT_MANAGER)\ + .first() # 'Comments moderator' + + rules = [ + UserRole.objects.filter(user=request.user, role=role, + establishment_id=obj.establishment_id + ).exists(), + super().has_object_permission(request, view, obj) + ] + + return any(rules) + + +class IsReviewerManager(IsStandardUser): + + def has_object_permission(self, request, view, obj): + + role = Role.objects.filter(role=Role.REVIEWER_MANGER, + country_id=obj.country_id)\ + .first() + + rules = [ + UserRole.objects.filter(user=request.user, role=role).exists(), + super().has_object_permission(request, view, obj) + ] + + return any(rules) + + +class IsRestaurantReviewer(IsStandardUser): + + def has_object_permission(self, request, view, obj): + + content_type = ContentType.objects.get(app_lable='establishment', + model='establishment') + + role = Role.objects.filter(role=Role.RESTAURANT_REVIEWER, + country=obj.country_id).first() + + rules = [ + obj.content_type_id == content_type.id and + UserRole.objects.filter(user=request.user, role=role, + establishment_id=obj.object_id + ).exists(), + super().has_object_permission(request, view, obj) + ] + + return any(rules) diff --git a/apps/utils/querysets.py b/apps/utils/querysets.py index f25507f7..bf2816f2 100644 --- a/apps/utils/querysets.py +++ b/apps/utils/querysets.py @@ -1,6 +1,8 @@ """Utils QuerySet Mixins""" from django.db import models - +from django.db.models import Q, Sum, F +from functools import reduce +from operator import add from utils.methods import get_contenttype @@ -15,3 +17,40 @@ class ContentTypeQuerySetMixin(models.QuerySet): """Filter QuerySet by ContentType.""" return self.filter(content_type=get_contenttype(app_label=app_label, model=model)) + + +class RelatedObjectsCountMixin(models.QuerySet): + """QuerySet for ManyToMany related count filter""" + + def _get_related_objects_names(self): + """Get all related objects (with reversed)""" + related_objects_names = [] + + for related_object in self.model._meta.related_objects: + if isinstance(related_object, models.ManyToManyRel): + related_objects_names.append(related_object.name) + + return related_objects_names + + def _annotate_related_objects_count(self): + """Annotate all related objects to queryset""" + annotations = {} + for related_object in self._get_related_objects_names(): + annotations[f"{related_object}_count"] = models.Count(f"{related_object}") + + return self.annotate(**annotations) + + def filter_related_gt(self, count): + """QuerySet filter by related objects count""" + q_objects = Q() + for related_object in self._get_related_objects_names(): + q_objects.add(Q(**{f"{related_object}_count__gt": count}), Q.OR) + + return self._annotate_related_objects_count().filter(q_objects) + + def filter_all_related_gt(self, count): + """Queryset filter by all related objects count""" + exp =reduce(add, [F(f"{related_object}_count") for related_object in self._get_related_objects_names()]) + return self._annotate_related_objects_count()\ + .annotate(all_related_count=exp)\ + .filter(all_related_count__gt=count) diff --git a/apps/utils/serializers.py b/apps/utils/serializers.py index 33463ebe..90efea00 100644 --- a/apps/utils/serializers.py +++ b/apps/utils/serializers.py @@ -1,7 +1,8 @@ """Utils app serializer.""" +from django.core import exceptions from rest_framework import serializers - -from utils.models import PlatformMixin +from utils import models +from translation.models import Language class EmptySerializer(serializers.Serializer): @@ -10,6 +11,44 @@ class EmptySerializer(serializers.Serializer): class SourceSerializerMixin(serializers.Serializer): """Base authorization serializer mixin""" - source = serializers.ChoiceField(choices=PlatformMixin.SOURCES, - default=PlatformMixin.WEB, + source = serializers.ChoiceField(choices=models.PlatformMixin.SOURCES, + default=models.PlatformMixin.WEB, write_only=True) + + +class TranslatedField(serializers.CharField): + """Translated field.""" + + def __init__(self, allow_null=True, required=False, read_only=True, + **kwargs): + super().__init__(allow_null=allow_null, required=required, + read_only=read_only, **kwargs) + + +# todo: view validation in more detail +def validate_tjson(value): + if not isinstance(value, dict): + raise exceptions.ValidationError( + 'invalid_json', + code='invalid_json', + params={'value': value}, + ) + is_lang = Language.objects.filter(locale__in=value.keys()).exists() + if not is_lang: + raise exceptions.ValidationError( + 'invalid_translated_keys', + code='invalid_translated_keys', + params={'value': value}, + ) + + +class TJSONField(serializers.JSONField): + """Custom serializer's JSONField for model's TJSONField.""" + + validators = [validate_tjson] + + +class ProjectModelSerializer(serializers.ModelSerializer): + """Overrided ModelSerializer.""" + + serializers.ModelSerializer.serializer_field_mapping[models.TJSONField] = TJSONField diff --git a/apps/utils/tests/__init__.py b/apps/utils/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/apps/utils/tests/tests_json_field.py b/apps/utils/tests/tests_json_field.py new file mode 100644 index 00000000..c0207def --- /dev/null +++ b/apps/utils/tests/tests_json_field.py @@ -0,0 +1,37 @@ +from django.test import TestCase +from translation.models import Language +from django.core import exceptions +from utils.serializers import validate_tjson + + +class ValidJSONTest(TestCase): + + def test_valid_json(self): + lang = Language.objects.create(title='English', locale='en-GB') + lang.save() + + data = 'str' + + with self.assertRaises(exceptions.ValidationError) as err: + validate_tjson(data) + + self.assertEqual(err.exception.code, 'invalid_json') + + data = { + "string": "value" + } + + with self.assertRaises(exceptions.ValidationError) as err: + validate_tjson(data) + + self.assertEqual(err.exception.code, 'invalid_translated_keys') + + data = { + "en-GB": "English" + } + + try: + validate_tjson(data) + self.assertTrue(True) + except exceptions.ValidationError: + self.assert_(False, "Test json translated FAILED") \ No newline at end of file diff --git a/apps/utils/tests/tests_permissions.py b/apps/utils/tests/tests_permissions.py new file mode 100644 index 00000000..edc1a5d7 --- /dev/null +++ b/apps/utils/tests/tests_permissions.py @@ -0,0 +1,18 @@ +from rest_framework.test import APITestCase +from location.models import Country +from translation.models import Language + + +class BasePermissionTests(APITestCase): + def setUp(self): + self.lang = Language.objects.get( + title='Russia', + locale='ru-RU' + ) + + self.country_ru = Country.objects.get( + name={"en-GB": "Russian"} + ) + + + diff --git a/apps/utils/tests/tests_translated.py b/apps/utils/tests/tests_translated.py new file mode 100644 index 00000000..c6a990c0 --- /dev/null +++ b/apps/utils/tests/tests_translated.py @@ -0,0 +1,125 @@ +import pytz +from datetime import datetime, timedelta + +from rest_framework.test import APITestCase +from rest_framework import status +from http.cookies import SimpleCookie + +from account.models import User +from news.models import News, NewsType + +from establishment.models import Establishment, EstablishmentType, Employee + + +class BaseTestCase(APITestCase): + + def setUp(self): + + self.username = 'sedragurda' + self.password = 'sedragurdaredips19' + self.email = 'sedragurda@desoz.com' + self.newsletter = True + self.user = User.objects.create_user( + username=self.username, email=self.email, password=self.password) + + # get tokkens + tokkens = User.create_jwt_tokens(self.user) + self.client.cookies = SimpleCookie( + {'access_token': tokkens.get('access_token'), + 'refresh_token': tokkens.get('refresh_token'), + 'locale': "en" + }) + + +class TranslateFieldTests(BaseTestCase): + + def setUp(self): + super().setUp() + + self.news_type = NewsType.objects.create(name="Test news type") + self.news_type.save() + + self.news_item = News.objects.create( + created_by=self.user, + modified_by=self.user, + title={ + "en-GB": "Test news item", + "ru-RU": "Тестовая новость" + }, + description={"en-GB": "Test description"}, + playlist=1, + start=datetime.now(pytz.utc) + timedelta(hours=-13), + end=datetime.now(pytz.utc) + timedelta(hours=13), + news_type=self.news_type, + slug='test', + state=News.PUBLISHED, + ) + self.news_item.save() + + def test_model_field(self): + self.assertTrue(hasattr(self.news_item, "title_translated")) + + + def test_read_locale(self): + response = self.client.get(f"/api/web/news/slug/{self.news_item.slug}/", format='json') + self.assertEqual(response.status_code, status.HTTP_200_OK) + news_data = response.json() + + self.assertIn("title_translated", news_data) + + self.assertIn("Test news item", news_data['title_translated']) + + +class BaseAttributeTests(BaseTestCase): + + def setUp(self): + super().setUp() + + self.establishment_type = EstablishmentType.objects.create(name="Test establishment type") + self.establishment = Establishment.objects.create( + name="Test establishment", + establishment_type_id=self.establishment_type.id, + is_publish=True + ) + + def test_base_attr_api(self): + data = { + 'user': self.user.id, + 'name': 'Test name' + } + + response = self.client.post('/api/back/establishments/employees/', data=data) + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + response_data = response.json() + self.assertIn("id", response_data) + self.assertIsInstance(response_data['id'], int) + + employee = Employee.objects.get(id=response_data['id']) + + self.assertEqual(self.user, employee.created_by) + self.assertEqual(self.user, employee.modified_by) + + modify_user = User.objects.create_user( + username='sedragurda2', + password='sedragurdaredips192', + email='sedragurda2@desoz.com', + ) + + modify_tokkens = User.create_jwt_tokens(modify_user) + self.client.cookies = SimpleCookie( + {'access_token': modify_tokkens.get('access_token'), + 'refresh_token': modify_tokkens.get('refresh_token'), + 'locale': "en" + }) + + update_data = { + 'name': 'Test new name' + } + + response = self.client.patch(f'/api/back/establishments/employees/{employee.pk}/', data=update_data) + self.assertEqual(response.status_code, status.HTTP_200_OK) + + employee.refresh_from_db() + self.assertEqual(modify_user, employee.modified_by) + self.assertEqual(self.user, employee.created_by) diff --git a/docker-compose.yml b/docker-compose.yml index 3fb05f98..3b446101 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -12,10 +12,9 @@ services: - POSTGRES_DB=postgres ports: - "5436:5432" - networks: - - db-net volumes: - gm-db:/var/lib/postgresql/data/ + elasticsearch: image: elasticsearch:7.3.1 volumes: @@ -28,13 +27,19 @@ services: - "ES_JAVA_OPTS=-Xms512m -Xmx512m" - discovery.type=single-node - xpack.security.enabled=false - networks: - - app-net - # RabbitMQ - rabbitmq: - image: rabbitmq:latest + + # Redis + redis: + image: redis:2.8.23 ports: - - "5672:5672" + - "6379:6379" + + # RabbitMQ + #rabbitmq: + # image: rabbitmq:latest + # ports: + # - "5672:5672" + # Celery worker: build: . @@ -50,7 +55,9 @@ services: - .:/code links: - db - - rabbitmq +# - rabbitmq + - redis + worker_beat: build: . command: ./run_celery_beat.sh @@ -65,7 +72,8 @@ services: - .:/code links: - db - - rabbitmq +# - rabbitmq + - redis # App: G&M gm_app: build: . @@ -79,23 +87,17 @@ services: - DB_PASSWORD=postgres depends_on: - db - - rabbitmq +# - rabbitmq + - redis - worker - worker_beat - elasticsearch - networks: - - app-net - - db-net volumes: - .:/code - gm-media:/media-data ports: - "8000:8000" -networks: - app-net: - db-net: - volumes: gm-db: name: gm-db diff --git a/project/locale/ru/LC_MESSAGES/django.po b/project/locale/ru/LC_MESSAGES/django.po new file mode 100644 index 00000000..8092593a --- /dev/null +++ b/project/locale/ru/LC_MESSAGES/django.po @@ -0,0 +1,3091 @@ +# SOME DESCRIPTIVE TITLE. +# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER +# This file is distributed under the same license as the PACKAGE package. +# FIRST AUTHOR , YEAR. +# +#, fuzzy +msgid "" +msgstr "" +"Project-Id-Version: PACKAGE VERSION\n" +"Report-Msgid-Bugs-To: \n" +"POT-Creation-Date: 2019-10-17 13:52+0000\n" +"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" +"Last-Translator: FULL NAME \n" +"Language-Team: LANGUAGE \n" +"Language: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n" +"%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n" +"%100>=11 && n%100<=14)? 2 : 3);\n" + +#: apps/account/admin.py:30 +msgid "Personal info" +msgstr "" + +#: apps/account/admin.py:34 +msgid "Subscription" +msgstr "" + +#: apps/account/admin.py:39 +msgid "Important dates" +msgstr "" + +#: apps/account/admin.py:40 +msgid "Permissions" +msgstr "" + +#: apps/account/admin.py:59 apps/location/models.py:18 +#: venv/lib/python3.6/site-packages/fcm_django/models.py:14 +msgid "Name" +msgstr "" + +#: apps/account/apps.py:7 +msgid "Account" +msgstr "" + +#: apps/account/forms.py:15 +msgid "The two password fields didn't match." +msgstr "" + +#: apps/account/forms.py:16 +msgid "Password already in use." +msgstr "" + +#: apps/account/forms.py:19 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_change_form.html:50 +msgid "New password" +msgstr "" + +#: apps/account/forms.py:25 +msgid "New password confirmation" +msgstr "" + +#: apps/account/models.py:31 apps/account/models.py:227 +msgid "Role" +msgstr "" + +#: apps/account/models.py:33 apps/location/models.py:28 apps/main/models.py:117 +msgid "Country" +msgstr "" + +#: apps/account/models.py:76 apps/news/models.py:126 apps/utils/models.py:194 +msgid "Image URL path" +msgstr "" + +#: apps/account/models.py:78 +msgid "Cropped image URL path" +msgstr "" + +#: apps/account/models.py:80 +msgid "email address" +msgstr "" + +#: apps/account/models.py:82 +msgid "unconfirmed email" +msgstr "" + +#: apps/account/models.py:83 +msgid "email status" +msgstr "" + +#: apps/account/models.py:90 +msgid "Roles" +msgstr "" + +#: apps/account/models.py:95 apps/account/models.py:226 +#: apps/comment/models.py:38 apps/establishment/models.py:435 +#: apps/favorites/models.py:23 apps/notification/models.py:79 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/object_history.html:30 +msgid "User" +msgstr "" + +#: apps/account/models.py:96 +msgid "Users" +msgstr "" + +#: apps/account/serializers/common.py:121 +msgid "Old password mismatch." +msgstr "" + +#: apps/account/serializers/common.py:124 apps/utils/exceptions.py:103 +msgid "Password is already in use" +msgstr "" + +#: apps/account/tasks.py:18 +msgid "Password resetting" +msgstr "" + +#: apps/account/tasks.py:31 apps/account/tasks.py:43 +msgid "Validate new email address" +msgstr "" + +#: apps/advertisement/apps.py:7 +msgid "advertisement" +msgstr "" + +#: apps/advertisement/models.py:15 +msgid "Ad URL" +msgstr "" + +#: apps/advertisement/models.py:16 +msgid "Block width" +msgstr "" + +#: apps/advertisement/models.py:17 +msgid "Block height" +msgstr "" + +#: apps/advertisement/models.py:18 +msgid "Block level" +msgstr "" + +#: apps/advertisement/models.py:22 apps/advertisement/models.py:23 +msgid "Advertisement" +msgstr "" + +#: apps/authorization/apps.py:8 +msgid "Authorization" +msgstr "" + +#: apps/authorization/models.py:86 +msgid "Expiration datetime" +msgstr "" + +#: apps/authorization/models.py:94 +msgid "Access token" +msgstr "" + +#: apps/authorization/models.py:95 +msgid "Access tokens" +msgstr "" + +#: apps/authorization/models.py:154 +msgid "Refresh token" +msgstr "" + +#: apps/authorization/models.py:155 +msgid "Refresh tokens" +msgstr "" + +#: apps/authorization/tasks.py:18 +msgid "Email confirmation" +msgstr "" + +#: apps/authorization/views/common.py:40 +msgid "Application is not found" +msgstr "" + +#: apps/authorization/views/common.py:50 +msgid "Not found an application with this source" +msgstr "" + +#: apps/booking/apps.py:7 apps/booking/models/models.py:66 +#: apps/booking/models/models.py:67 +msgid "Booking" +msgstr "" + +#: apps/booking/models/models.py:21 +msgid "Guestonline or Lastable" +msgstr "" + +#: apps/booking/models/models.py:22 +msgid "booking service establishment id" +msgstr "" + +#: apps/booking/models/models.py:23 +msgid "booking locale" +msgstr "" + +#: apps/booking/models/models.py:24 +msgid "external service pending booking" +msgstr "" + +#: apps/booking/models/models.py:25 +msgid "external service booking id" +msgstr "" + +#: apps/booking/models/models.py:28 +msgid "booking owner" +msgstr "" + +#: apps/collection/apps.py:7 apps/collection/models.py:80 +#: apps/collection/models.py:106 +msgid "collection" +msgstr "" + +#: apps/collection/models.py:17 apps/establishment/models.py:241 +#: apps/establishment/models.py:504 apps/location/models.py:34 +#: apps/location/models.py:55 apps/main/models.py:227 apps/main/models.py:278 +#: apps/news/models.py:14 +msgid "name" +msgstr "" + +#: apps/collection/models.py:26 +msgid "start" +msgstr "" + +#: apps/collection/models.py:27 +msgid "end" +msgstr "" + +#: apps/collection/models.py:54 +msgid "Ordinary" +msgstr "" + +#: apps/collection/models.py:55 +msgid "Pop" +msgstr "" + +#: apps/collection/models.py:60 +msgid "Collection type" +msgstr "" + +#: apps/collection/models.py:62 apps/establishment/models.py:280 +msgid "Publish status" +msgstr "" + +#: apps/collection/models.py:64 +msgid "Position on top" +msgstr "" + +#: apps/collection/models.py:66 apps/location/models.py:40 +#: apps/location/models.py:60 apps/main/models.py:226 apps/news/models.py:135 +msgid "country" +msgstr "" + +#: apps/collection/models.py:68 +msgid "collection block properties" +msgstr "" + +#: apps/collection/models.py:71 apps/establishment/models.py:245 +#: apps/establishment/models.py:507 apps/news/models.py:111 +msgid "description" +msgstr "" + +#: apps/collection/models.py:74 +msgid "Collection slug" +msgstr "" + +#: apps/collection/models.py:81 +msgid "collections" +msgstr "" + +#: apps/collection/models.py:99 +msgid "parent" +msgstr "" + +#: apps/collection/models.py:103 +msgid "advertorials" +msgstr "" + +#: apps/collection/models.py:112 +msgid "guide" +msgstr "" + +#: apps/collection/models.py:113 +msgid "guides" +msgstr "" + +#: apps/comment/apps.py:7 +msgid "comment" +msgstr "" + +#: apps/comment/apps.py:8 +msgid "comments" +msgstr "" + +#: apps/comment/models.py:32 +msgid "Comment text" +msgstr "" + +#: apps/comment/models.py:34 +msgid "Mark" +msgstr "" + +#: apps/comment/models.py:44 +msgid "Locale" +msgstr "" + +#: apps/comment/models.py:48 +msgid "Comment" +msgstr "" + +#: apps/comment/models.py:49 +msgid "Comments" +msgstr "" + +#: apps/configuration/apps.py:7 +msgid "configuration" +msgstr "" + +#: apps/configuration/models.py:9 +msgid "default language" +msgstr "" + +#: apps/establishment/admin.py:87 apps/establishment/models.py:529 +#: apps/main/models.py:248 +msgid "category" +msgstr "" + +#: apps/establishment/apps.py:8 apps/establishment/models.py:310 +#: apps/establishment/models.py:418 +msgid "Establishment" +msgstr "" + +#: apps/establishment/models.py:30 apps/establishment/models.py:54 +#: apps/establishment/models.py:391 apps/recipe/models.py:52 +msgid "Description" +msgstr "" + +#: apps/establishment/models.py:32 +msgid "Use subtypes" +msgstr "" + +#: apps/establishment/models.py:37 +msgid "Establishment type" +msgstr "" + +#: apps/establishment/models.py:38 +msgid "Establishment types" +msgstr "" + +#: apps/establishment/models.py:58 +msgid "Type" +msgstr "" + +#: apps/establishment/models.py:65 +msgid "Establishment subtype" +msgstr "" + +#: apps/establishment/models.py:66 +msgid "Establishment subtypes" +msgstr "" + +#: apps/establishment/models.py:70 +msgid "Establishment type is not use subtypes." +msgstr "" + +#: apps/establishment/models.py:242 +msgid "Transliterated name" +msgstr "" + +#: apps/establishment/models.py:249 +msgid "public mark" +msgstr "" + +#: apps/establishment/models.py:252 +msgid "toque number" +msgstr "" + +#: apps/establishment/models.py:256 +msgid "type" +msgstr "" + +#: apps/establishment/models.py:259 +msgid "subtype" +msgstr "" + +#: apps/establishment/models.py:262 apps/news/models.py:131 +msgid "address" +msgstr "" + +#: apps/establishment/models.py:265 +msgid "price level" +msgstr "" + +#: apps/establishment/models.py:267 +msgid "Web site URL" +msgstr "" + +#: apps/establishment/models.py:269 +msgid "Facebook URL" +msgstr "" + +#: apps/establishment/models.py:271 +msgid "Twitter URL" +msgstr "" + +#: apps/establishment/models.py:273 +msgid "Lafourchette URL" +msgstr "" + +#: apps/establishment/models.py:274 +msgid "guestonline id" +msgstr "" + +#: apps/establishment/models.py:276 +msgid "lastable id" +msgstr "" + +#: apps/establishment/models.py:279 +msgid "Booking URL" +msgstr "" + +#: apps/establishment/models.py:282 +msgid "Establishment schedule" +msgstr "" + +#: apps/establishment/models.py:289 +msgid "Transportation" +msgstr "" + +#: apps/establishment/models.py:293 +msgid "Collections" +msgstr "" + +#: apps/establishment/models.py:294 apps/news/models.py:128 +msgid "Preview image URL path" +msgstr "" + +#: apps/establishment/models.py:297 +msgid "Establishment slug" +msgstr "" + +#: apps/establishment/models.py:311 +msgid "Establishments" +msgstr "" + +#: apps/establishment/models.py:399 apps/establishment/models.py:425 +msgid "Position" +msgstr "" + +#: apps/establishment/models.py:400 +msgid "Positions" +msgstr "" + +#: apps/establishment/models.py:420 apps/establishment/models.py:445 +msgid "Employee" +msgstr "" + +#: apps/establishment/models.py:421 +msgid "From date" +msgstr "" + +#: apps/establishment/models.py:423 +msgid "To date" +msgstr "" + +#: apps/establishment/models.py:436 +msgid "Last name" +msgstr "" + +#: apps/establishment/models.py:446 +msgid "Employees" +msgstr "" + +#: apps/establishment/models.py:460 +msgid "contact phone" +msgstr "" + +#: apps/establishment/models.py:461 +msgid "contact phones" +msgstr "" + +#: apps/establishment/models.py:474 +msgid "contact email" +msgstr "" + +#: apps/establishment/models.py:475 +msgid "contact emails" +msgstr "" + +#: apps/establishment/models.py:510 +msgid "price" +msgstr "" + +#: apps/establishment/models.py:511 +msgid "is signature plate" +msgstr "" + +#: apps/establishment/models.py:513 apps/main/models.py:281 +msgid "currency" +msgstr "" + +#: apps/establishment/models.py:516 apps/establishment/models.py:536 +#: apps/establishment/models.py:537 +msgid "menu" +msgstr "" + +#: apps/establishment/models.py:519 +msgid "plate" +msgstr "" + +#: apps/establishment/models.py:520 +msgid "plates" +msgstr "" + +#: apps/establishment/models.py:532 apps/establishment/models.py:542 +msgid "establishment" +msgstr "" + +#: apps/establishment/models.py:544 apps/main/models.py:207 +#: apps/news/models.py:105 +msgid "title" +msgstr "" + +#: apps/establishment/models.py:545 +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:2234 +msgid "URL" +msgstr "" + +#: apps/establishment/models.py:548 +msgid "social network" +msgstr "" + +#: apps/establishment/models.py:549 +msgid "social networks" +msgstr "" + +#: apps/establishment/serializers/common.py:237 +#: apps/timetable/serialziers.py:47 +msgid "Establishment not found." +msgstr "" + +#: apps/establishment/serializers/common.py:288 +msgid "Object not found." +msgstr "" + +#: apps/favorites/apps.py:7 apps/favorites/models.py:32 +#: apps/favorites/models.py:33 +msgid "Favorites" +msgstr "" + +#: apps/gallery/apps.py:7 +msgid "gallery" +msgstr "" + +#: apps/gallery/models.py:12 +msgid "Image file" +msgstr "" + +#: apps/gallery/models.py:16 apps/utils/models.py:147 apps/utils/models.py:176 +#: apps/utils/models.py:207 +#: venv/lib/python3.6/site-packages/django/db/models/fields/files.py:360 +msgid "Image" +msgstr "" + +#: apps/gallery/models.py:17 +msgid "Images" +msgstr "" + +#: apps/location/admin.py:28 apps/main/apps.py:8 apps/main/models.py:191 +msgid "Main" +msgstr "" + +#: apps/location/admin.py:31 +msgid "Location" +msgstr "" + +#: apps/location/admin.py:34 +msgid "Address detail" +msgstr "" + +#: apps/location/apps.py:7 +msgid "location" +msgstr "" + +#: apps/location/models.py:19 +msgid "Code" +msgstr "" + +#: apps/location/models.py:20 +msgid "Low price" +msgstr "" + +#: apps/location/models.py:21 +msgid "High price" +msgstr "" + +#: apps/location/models.py:22 apps/translation/models.py:34 +msgid "Languages" +msgstr "" + +#: apps/location/models.py:27 +msgid "Countries" +msgstr "" + +#: apps/location/models.py:35 apps/location/models.py:56 +msgid "code" +msgstr "" + +#: apps/location/models.py:37 apps/location/models.py:58 +msgid "parent region" +msgstr "" + +#: apps/location/models.py:45 +msgid "regions" +msgstr "" + +#: apps/location/models.py:46 +msgid "region" +msgstr "" + +#: apps/location/models.py:63 apps/location/models.py:85 +msgid "postal code" +msgstr "" + +#: apps/location/models.py:63 apps/location/models.py:86 +msgid "Ex.: 350018" +msgstr "" + +#: apps/location/models.py:65 +msgid "is island" +msgstr "" + +#: apps/location/models.py:68 +msgid "cities" +msgstr "" + +#: apps/location/models.py:69 apps/location/models.py:78 +msgid "city" +msgstr "" + +#: apps/location/models.py:80 +msgid "street name 1" +msgstr "" + +#: apps/location/models.py:82 +msgid "street name 2" +msgstr "" + +#: apps/location/models.py:83 +msgid "number" +msgstr "" + +#: apps/location/models.py:88 +msgid "Coordinates" +msgstr "" + +#: apps/location/models.py:93 apps/location/models.py:94 +msgid "Address" +msgstr "" + +#: apps/location/serializers/common.py:120 +#: apps/location/serializers/common.py:125 +msgid "Invalid value" +msgstr "" + +#: apps/main/models.py:114 +msgid "Subdomain" +msgstr "" + +#: apps/main/models.py:119 +msgid "Default site" +msgstr "" + +#: apps/main/models.py:121 +msgid "Pinterest page URL" +msgstr "" + +#: apps/main/models.py:123 +msgid "Twitter page URL" +msgstr "" + +#: apps/main/models.py:125 +msgid "Facebook page URL" +msgstr "" + +#: apps/main/models.py:127 +msgid "Instagram page URL" +msgstr "" + +#: apps/main/models.py:129 +msgid "Contact email" +msgstr "" + +#: apps/main/models.py:131 +msgid "Config" +msgstr "" + +#: apps/main/models.py:133 +msgid "AD config" +msgstr "" + +#: apps/main/models.py:140 +msgid "Site setting" +msgstr "" + +#: apps/main/models.py:141 +msgid "Site settings" +msgstr "" + +#: apps/main/models.py:171 +msgid "Feature" +msgstr "" + +#: apps/main/models.py:172 +msgid "Features" +msgstr "" + +#: apps/main/models.py:190 apps/news/models.py:98 apps/recipe/models.py:42 +msgid "Published" +msgstr "" + +#: apps/main/models.py:198 +msgid "Site feature" +msgstr "" + +#: apps/main/models.py:199 +msgid "Site features" +msgstr "" + +#: apps/main/models.py:209 +msgid "vintage year" +msgstr "" + +#: apps/main/models.py:245 +msgid "label" +msgstr "" + +#: apps/main/models.py:251 apps/main/models.py:252 +msgid "metadata" +msgstr "" + +#: apps/main/models.py:282 +msgid "currencies" +msgstr "" + +#: apps/main/models.py:302 apps/main/models.py:303 +msgid "Carousel" +msgstr "" + +#: apps/main/models.py:365 apps/translation/models.py:49 +msgid "Page" +msgstr "" + +#: apps/main/models.py:366 +msgid "Pages" +msgstr "" + +#: apps/news/apps.py:7 apps/news/models.py:145 apps/news/models.py:146 +msgid "news" +msgstr "" + +#: apps/news/models.py:19 +msgid "news types" +msgstr "" + +#: apps/news/models.py:20 apps/news/models.py:103 +msgid "news type" +msgstr "" + +#: apps/news/models.py:96 apps/recipe/models.py:40 +msgid "Waiting" +msgstr "" + +#: apps/news/models.py:97 apps/recipe/models.py:41 +msgid "Hidden" +msgstr "" + +#: apps/news/models.py:99 apps/recipe/models.py:43 +msgid "Published exclusive" +msgstr "" + +#: apps/news/models.py:108 +msgid "subtitle" +msgstr "" + +#: apps/news/models.py:113 +msgid "Start" +msgstr "" + +#: apps/news/models.py:115 +msgid "End" +msgstr "" + +#: apps/news/models.py:117 +msgid "News slug" +msgstr "" + +#: apps/news/models.py:118 +msgid "playlist" +msgstr "" + +#: apps/news/models.py:120 apps/notification/models.py:89 +#: apps/recipe/models.py:55 +msgid "State" +msgstr "" + +#: apps/news/models.py:122 +msgid "Is highlighted" +msgstr "" + +#: apps/notification/apps.py:7 +msgid "notification" +msgstr "" + +#: apps/notification/models.py:73 +msgid "Unusable" +msgstr "" + +#: apps/notification/models.py:74 +msgid "Usable" +msgstr "" + +#: apps/notification/models.py:81 +msgid "Email" +msgstr "" + +#: apps/notification/models.py:83 +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1891 +msgid "IP address" +msgstr "" + +#: apps/notification/models.py:85 +msgid "Country code" +msgstr "" + +#: apps/notification/models.py:87 apps/translation/models.py:26 +msgid "Locale identifier" +msgstr "" + +#: apps/notification/models.py:91 +msgid "Token" +msgstr "" + +#: apps/notification/models.py:98 +msgid "Subscriber" +msgstr "" + +#: apps/notification/models.py:99 +msgid "Subscribers" +msgstr "" + +#: apps/notification/serializers/common.py:29 +msgid "Does not match user email" +msgstr "" + +#: apps/notification/serializers/common.py:32 +#: venv/lib/python3.6/site-packages/django/forms/fields.py:53 +msgid "This field is required." +msgstr "" + +#: apps/partner/apps.py:7 apps/partner/models.py:12 +msgid "partner" +msgstr "" + +#: apps/partner/models.py:9 +msgid "Partner URL" +msgstr "" + +#: apps/partner/models.py:13 +msgid "partners" +msgstr "" + +#: apps/products/apps.py:8 +msgid "products" +msgstr "" + +#: apps/rating/models.py:11 +msgid "ip" +msgstr "" + +#: apps/recipe/apps.py:8 +msgid "RecipeConfig" +msgstr "" + +#: apps/recipe/models.py:48 +msgid "Title" +msgstr "" + +#: apps/recipe/models.py:50 +msgid "Subtitle" +msgstr "" + +#: apps/recipe/models.py:57 +msgid "Author" +msgstr "" + +#: apps/recipe/models.py:58 apps/recipe/models.py:60 +msgid "Published at" +msgstr "" + +#: apps/recipe/models.py:61 apps/recipe/models.py:63 +msgid "Published scheduled at" +msgstr "" + +#: apps/recipe/models.py:70 +msgid "Recipe" +msgstr "" + +#: apps/recipe/models.py:71 +msgid "Recipes" +msgstr "" + +#: apps/review/apps.py:7 +msgid "reviews" +msgstr "" + +#: apps/review/models.py:37 +msgid "To investigate" +msgstr "" + +#: apps/review/models.py:38 +msgid "To review" +msgstr "" + +#: apps/review/models.py:39 +msgid "Ready" +msgstr "" + +#: apps/review/models.py:45 +msgid "Reviewer" +msgstr "" + +#: apps/review/models.py:47 +msgid "text" +msgstr "" + +#: apps/review/models.py:55 +msgid "Review language" +msgstr "" + +#: apps/review/models.py:60 +msgid "Child review" +msgstr "" + +#: apps/review/models.py:61 +msgid "Publish datetime" +msgstr "" + +#: apps/review/models.py:63 +msgid "Review published datetime" +msgstr "" + +#: apps/review/models.py:64 +msgid "Year of review" +msgstr "" + +#: apps/review/models.py:72 +msgid "Review" +msgstr "" + +#: apps/review/models.py:73 +msgid "Reviews" +msgstr "" + +#: apps/search_indexes/apps.py:7 +msgid "Search indexes" +msgstr "" + +#: apps/timetable/apps.py:7 +msgid "timetable" +msgstr "" + +#: apps/timetable/models.py:18 +#: venv/lib/python3.6/site-packages/django/utils/dates.py:6 +msgid "Monday" +msgstr "" + +#: apps/timetable/models.py:19 +#: venv/lib/python3.6/site-packages/django/utils/dates.py:6 +msgid "Tuesday" +msgstr "" + +#: apps/timetable/models.py:20 +#: venv/lib/python3.6/site-packages/django/utils/dates.py:6 +msgid "Wednesday" +msgstr "" + +#: apps/timetable/models.py:21 +#: venv/lib/python3.6/site-packages/django/utils/dates.py:6 +msgid "Thursday" +msgstr "" + +#: apps/timetable/models.py:22 +#: venv/lib/python3.6/site-packages/django/utils/dates.py:6 +msgid "Friday" +msgstr "" + +#: apps/timetable/models.py:23 +#: venv/lib/python3.6/site-packages/django/utils/dates.py:7 +msgid "Saturday" +msgstr "" + +#: apps/timetable/models.py:24 +#: venv/lib/python3.6/site-packages/django/utils/dates.py:7 +msgid "Sunday" +msgstr "" + +#: apps/timetable/models.py:26 +msgid "Week day" +msgstr "" + +#: apps/timetable/models.py:28 +msgid "Lunch start time" +msgstr "" + +#: apps/timetable/models.py:29 +msgid "Lunch end time" +msgstr "" + +#: apps/timetable/models.py:30 +msgid "Dinner start time" +msgstr "" + +#: apps/timetable/models.py:31 +msgid "Dinner end time" +msgstr "" + +#: apps/timetable/models.py:32 +msgid "Opening time" +msgstr "" + +#: apps/timetable/models.py:33 +msgid "Closed time" +msgstr "" + +#: apps/timetable/models.py:37 +msgid "Timetable" +msgstr "" + +#: apps/timetable/models.py:38 +msgid "Timetables" +msgstr "" + +#: apps/translation/apps.py:7 +msgid "Translation" +msgstr "" + +#: apps/translation/models.py:24 +msgid "Language title" +msgstr "" + +#: apps/translation/models.py:33 +msgid "Language" +msgstr "" + +#: apps/translation/models.py:51 +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:2075 +msgid "Text" +msgstr "" + +#: apps/translation/models.py:59 apps/translation/models.py:60 +msgid "Site interface dictionary" +msgstr "" + +#: apps/utils/exceptions.py:8 +msgid "Bad request" +msgstr "" + +#: apps/utils/exceptions.py:27 +msgid "Service is temporarily unavailable" +msgstr "" + +#: apps/utils/exceptions.py:32 +msgid "User not found" +msgstr "" + +#: apps/utils/exceptions.py:38 +#, python-format +msgid "Unable to send message to mailbox %s" +msgstr "" + +#: apps/utils/exceptions.py:53 +#, python-format +msgid "Locale not found in database (%s)" +msgstr "" + +#: apps/utils/exceptions.py:68 +msgid "Wrong username" +msgstr "" + +#: apps/utils/exceptions.py:76 +msgid "Not valid token" +msgstr "" + +#: apps/utils/exceptions.py:83 +msgid "Not valid access token" +msgstr "" + +#: apps/utils/exceptions.py:90 +msgid "Not valid refresh token" +msgstr "" + +#: apps/utils/exceptions.py:95 +msgid "OAuth2 Error" +msgstr "" + +#: apps/utils/exceptions.py:111 +msgid "Email address is already confirmed" +msgstr "" + +#: apps/utils/exceptions.py:119 +msgid "Image invalid input." +msgstr "" + +#: apps/utils/exceptions.py:126 +msgid "Incorrect login or password." +msgstr "Неправильный логин или пароль." + +#: apps/utils/exceptions.py:135 +msgid "Item is already in favorites." +msgstr "" + +#: apps/utils/exceptions.py:144 +msgid "Password reset request is already exists and valid." +msgstr "" + +#: apps/utils/models.py:21 +msgid "Date created" +msgstr "" + +#: apps/utils/models.py:23 +msgid "Date updated" +msgstr "" + +#: apps/utils/models.py:126 +msgid "created by" +msgstr "" + +#: apps/utils/models.py:130 +msgid "modified by" +msgstr "" + +#: apps/utils/models.py:186 +msgid "SVG image" +msgstr "" + +#: apps/utils/models.py:219 +msgid "Mobile" +msgstr "" + +#: apps/utils/models.py:220 +msgid "Web" +msgstr "" + +#: apps/utils/models.py:221 +msgid "All" +msgstr "" + +#: apps/utils/models.py:224 +msgid "Source" +msgstr "" + +#: project/templates/account/change_email.html:2 +#, python-format +msgid "" +"You're receiving this email because you want to change email address at " +"%(site_name)s." +msgstr "" + +#: project/templates/account/change_email.html:4 +msgid "Please go to the following page for confirmation new email address:" +msgstr "" + +#: project/templates/account/change_email.html:8 +#: project/templates/account/password_reset_email.html:8 +#: project/templates/authorization/confirm_email.html:7 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_email.html:10 +msgid "Thanks for using our site!" +msgstr "" + +#: project/templates/account/change_email.html:10 +#: project/templates/account/password_reset_email.html:10 +#: project/templates/authorization/confirm_email.html:9 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_email.html:12 +#, python-format +msgid "The %(site_name)s team" +msgstr "" + +#: project/templates/account/password_reset_email.html:2 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_email.html:2 +#, python-format +msgid "" +"You're receiving this email because you requested a password reset for your " +"user account at %(site_name)s." +msgstr "" + +#: project/templates/account/password_reset_email.html:4 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_email.html:4 +msgid "Please go to the following page and choose a new password:" +msgstr "" + +#: project/templates/authorization/confirm_email.html:2 +#, python-format +msgid "" +"You're receiving this email because you trying to register new account at " +"%(site_name)s." +msgstr "" + +#: project/templates/authorization/confirm_email.html:4 +msgid "Please confirm your email address to complete the registration:" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/404.html:4 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/404.html:8 +msgid "Page not found" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/404.html:10 +msgid "We're sorry, but the requested page could not be found." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/500.html:6 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/app_index.html:10 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/auth/user/change_password.html:19 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base.html:163 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_form.html:22 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_list.html:32 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/delete_confirmation.html:14 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/delete_selected_confirmation.html:15 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/object_history.html:7 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_change_done.html:7 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_change_form.html:12 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_complete.html:7 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_confirm.html:7 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_done.html:7 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_form.html:7 +#: venv/lib/python3.6/site-packages/solo/templates/admin/solo/change_form.html:7 +#: venv/lib/python3.6/site-packages/solo/templates/admin/solo/object_history.html:6 +msgid "Home" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/500.html:7 +msgid "Server error" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/500.html:11 +msgid "Server error (500)" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/500.html:14 +msgid "Server Error (500)" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/500.html:15 +msgid "" +"There's been an error. It's been reported to the site administrators via " +"email and should be fixed shortly. Thanks for your patience." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/actions.html:7 +msgid "Run the selected action" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/actions.html:7 +msgid "Go" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/actions.html:19 +msgid "Click here to select the objects across all pages" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/actions.html:19 +#, python-format +msgid "Select all %(total_count)s %(module_name)s" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/actions.html:21 +msgid "Clear selection" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/auth/user/add_form.html:7 +msgid "" +"First, enter a username and password. Then, you'll be able to edit more user " +"options." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/auth/user/add_form.html:10 +msgid "Enter a username and password." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/auth/user/change_password.html:31 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/auth/user/change_password.html:75 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base.html:143 +msgid "Change password" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/auth/user/change_password.html:44 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_form.html:65 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_list.html:58 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/login.html:44 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_change_form.html:31 +msgid "Please correct the error below." +msgid_plural "Please correct the errors below." +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/auth/user/change_password.html:44 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_form.html:65 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_change_form.html:31 +msgid "Please correct the errors below." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/auth/user/change_password.html:50 +#, python-format +msgid "Enter a new password for the user %(username)s." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/auth/user/change_password.html:60 +msgid "Password" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/auth/user/change_password.html:68 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_change_form.html:57 +msgid "Password (again)" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/auth/user/change_password.html:69 +msgid "Enter the same password as above, for verification." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base.html:72 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base.html:116 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base.html:119 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base_site.html:9 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/login.html:31 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/login.html:36 +msgid "Django administration" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base.html:81 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:52 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:58 +#, python-format +msgid "Models in the %(name)s application" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base.html:87 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base.html:93 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:143 +msgid "You don't have permission to edit anything." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base.html:138 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base.html:152 +msgid "Documentation" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base.html:147 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base.html:154 +msgid "Log out" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base.html:173 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_list.html:57 +msgid "Close" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/base_site.html:4 +msgid "Django site admin" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_form.html:39 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:65 +msgid "Add" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_form.html:114 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_form.html:116 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/object_history.html:18 +#: venv/lib/python3.6/site-packages/solo/templates/admin/solo/change_form.html:14 +#: venv/lib/python3.6/site-packages/solo/templates/admin/solo/object_history.html:9 +msgid "History" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_form.html:121 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_form.html:123 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/edit_inline/stacked.html:24 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/edit_inline/tabular.html:37 +#: venv/lib/python3.6/site-packages/solo/templates/admin/solo/change_form.html:15 +msgid "View on site" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_list.html:47 +msgid "Filter" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_list.html:81 +#, python-format +msgid "Add %(name)s" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_list.html:143 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/submit_line.html:5 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/submit_line.html:7 +msgid "Save" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_list_results.html:13 +msgid "Remove from sorting" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_list_results.html:16 +#, python-format +msgid "Sorting priority: %(priority_number)s" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/change_list_results.html:17 +msgid "Toggle sorting" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/delete_confirmation.html:25 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/submit_line.html:34 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/submit_line.html:36 +#: venv/lib/python3.6/site-packages/django/forms/formsets.py:375 +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_confirm_delete.html:13 +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_detail.html:38 +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/authorized-token-delete.html:7 +msgid "Delete" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/delete_confirmation.html:34 +#, python-format +msgid "" +"Deleting the %(object_name)s '%(escaped_object)s' would result in deleting " +"related objects, but your account doesn't have permission to delete the " +"following types of objects:" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/delete_confirmation.html:48 +#, python-format +msgid "" +"Deleting the %(object_name)s '%(escaped_object)s' would require deleting the " +"following protected related objects:" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/delete_confirmation.html:62 +#, python-format +msgid "" +"Are you sure you want to delete the %(object_name)s \"%(escaped_object)s\"? " +"All of the following related items will be deleted:" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/delete_confirmation.html:70 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/delete_confirmation.html:72 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/delete_selected_confirmation.html:74 +msgid "Yes, I'm sure" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/delete_selected_confirmation.html:23 +msgid "Delete multiple objects" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/delete_selected_confirmation.html:32 +#, python-format +msgid "" +"Deleting the selected %(objects_name)s would result in deleting related " +"objects, but your account doesn't have permission to delete the following " +"types of objects:" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/delete_selected_confirmation.html:46 +#, python-format +msgid "" +"Deleting the selected %(objects_name)s would require deleting the following " +"protected related objects:" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/delete_selected_confirmation.html:60 +#, python-format +msgid "" +"Are you sure you want to delete the selected %(objects_name)s? All of the " +"following objects and their related items will be deleted:" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/edit_inline/tabular.html:22 +msgid "Delete?" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/filter.html:2 +#, python-format +msgid " By %(filter_title)s " +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/includes/object_delete_summary.html:2 +msgid "Summary" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:18 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:21 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:22 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:31 +msgid "Apps" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:37 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:71 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/search_form.html:11 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/search_form.html:13 +msgid "Search" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:42 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/object_history.html:31 +msgid "Action" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:67 +msgid "View" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:69 +#: venv/lib/python3.6/site-packages/django/forms/widgets.py:397 +msgid "Change" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:84 +msgid "Recent actions" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:89 +msgid "None available" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/index.html:115 +msgid "Unknown content" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/invalid_setup.html:5 +msgid "" +"Something's wrong with your database installation. Make sure the appropriate " +"database tables have been created, and make sure the database is readable by " +"the appropriate user." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/login.html:21 +#, python-format +msgid "" +"You are authenticated as %(username)s, but are not authorized to access this " +"page. Would you like to login to a different account?" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/login.html:85 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_complete.html:23 +msgid "Log in" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/login.html:96 +msgid "Forgotten your password or username?" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/object_history.html:29 +msgid "Date/time" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/object_history.html:45 +msgid "" +"This object doesn't have a change history. It probably wasn't added via this " +"admin site." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/pagination.html:19 +msgid "Show all" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/popup_response.html:3 +msgid "Popup closing..." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/related_widget_wrapper.html:9 +#, python-format +msgid "Change selected %(model)s" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/related_widget_wrapper.html:16 +#, python-format +msgid "Add another %(model)s" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/related_widget_wrapper.html:23 +#, python-format +msgid "Delete selected %(model)s" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/search_form.html:4 +#, python-format +msgid "%(counter)s result" +msgid_plural "%(counter)s results" +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/search_form.html:4 +#, python-format +msgid "%(full_result_count)s total" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/submit_line.html:12 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/submit_line.html:14 +msgid "Save as new" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/submit_line.html:19 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/submit_line.html:21 +msgid "Save and add another" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/submit_line.html:26 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/admin/submit_line.html:28 +msgid "Save and continue editing" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/logged_out.html:18 +msgid "Thanks for spending some quality time with the Web site today." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/logged_out.html:20 +msgid "Log in again" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_change_done.html:10 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_change_form.html:15 +msgid "Password change" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_change_done.html:20 +msgid "Your password was changed." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_change_form.html:37 +msgid "" +"Please enter your old password, for security's sake, and then enter your new " +"password twice so we can verify you typed it in correctly." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_change_form.html:43 +msgid "Old password" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_change_form.html:66 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_confirm.html:46 +msgid "Change my password" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_complete.html:10 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_done.html:10 +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_form.html:10 +msgid "Password reset" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_complete.html:20 +msgid "Your password has been set. You may go ahead and log in now." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_confirm.html:10 +msgid "Password reset confirmation" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_confirm.html:24 +msgid "" +"Please enter your new password twice so we can verify you typed it in " +"correctly." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_confirm.html:30 +msgid "New password:" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_confirm.html:37 +msgid "Confirm password:" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_confirm.html:55 +msgid "" +"The password reset link was invalid, possibly because it has already been " +"used. Please request a new password reset." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_done.html:19 +msgid "" +"We've emailed you instructions for setting your password. You should be " +"receiving them shortly." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_done.html:21 +msgid "" +"If you don't receive an email, please make sure you've entered the address " +"you registered with, and check your spam folder." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_email.html:8 +msgid "Your username, in case you've forgotten:" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_form.html:23 +msgid "" +"Forgotten your password? Enter your email address below, and we'll email " +"instructions for setting a new one." +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_form.html:29 +msgid "Email address:" +msgstr "" + +#: venv/lib/python3.6/site-packages/bootstrap_admin/templates/registration/password_reset_form.html:38 +msgid "Reset my password" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/contrib/messages/apps.py:7 +msgid "Messages" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/contrib/sitemaps/apps.py:7 +msgid "Site Maps" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/contrib/staticfiles/apps.py:9 +msgid "Static Files" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/contrib/syndication/apps.py:7 +msgid "Syndication" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/paginator.py:45 +msgid "That page number is not an integer" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/paginator.py:47 +msgid "That page number is less than 1" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/paginator.py:52 +msgid "That page contains no results" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:31 +msgid "Enter a valid value." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:102 +#: venv/lib/python3.6/site-packages/django/forms/fields.py:658 +msgid "Enter a valid URL." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:154 +msgid "Enter a valid integer." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:165 +msgid "Enter a valid email address." +msgstr "" + +#. Translators: "letters" means latin letters: a-z and A-Z. +#: venv/lib/python3.6/site-packages/django/core/validators.py:239 +msgid "" +"Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:246 +msgid "" +"Enter a valid 'slug' consisting of Unicode letters, numbers, underscores, or " +"hyphens." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:255 +#: venv/lib/python3.6/site-packages/django/core/validators.py:275 +msgid "Enter a valid IPv4 address." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:260 +#: venv/lib/python3.6/site-packages/django/core/validators.py:276 +msgid "Enter a valid IPv6 address." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:270 +#: venv/lib/python3.6/site-packages/django/core/validators.py:274 +msgid "Enter a valid IPv4 or IPv6 address." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:304 +msgid "Enter only digits separated by commas." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:310 +#, python-format +msgid "Ensure this value is %(limit_value)s (it is %(show_value)s)." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:342 +#, python-format +msgid "Ensure this value is less than or equal to %(limit_value)s." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:351 +#, python-format +msgid "Ensure this value is greater than or equal to %(limit_value)s." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:361 +#, python-format +msgid "" +"Ensure this value has at least %(limit_value)d character (it has " +"%(show_value)d)." +msgid_plural "" +"Ensure this value has at least %(limit_value)d characters (it has " +"%(show_value)d)." +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:376 +#, python-format +msgid "" +"Ensure this value has at most %(limit_value)d character (it has " +"%(show_value)d)." +msgid_plural "" +"Ensure this value has at most %(limit_value)d characters (it has " +"%(show_value)d)." +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:395 +#: venv/lib/python3.6/site-packages/django/forms/fields.py:290 +#: venv/lib/python3.6/site-packages/django/forms/fields.py:325 +msgid "Enter a number." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:397 +#, python-format +msgid "Ensure that there are no more than %(max)s digit in total." +msgid_plural "Ensure that there are no more than %(max)s digits in total." +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:402 +#, python-format +msgid "Ensure that there are no more than %(max)s decimal place." +msgid_plural "Ensure that there are no more than %(max)s decimal places." +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:407 +#, python-format +msgid "" +"Ensure that there are no more than %(max)s digit before the decimal point." +msgid_plural "" +"Ensure that there are no more than %(max)s digits before the decimal point." +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:469 +#, python-format +msgid "" +"File extension '%(extension)s' is not allowed. Allowed extensions are: " +"'%(allowed_extensions)s'." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/core/validators.py:521 +msgid "Null characters are not allowed." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/base.py:1162 +#: venv/lib/python3.6/site-packages/django/forms/models.py:756 +msgid "and" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/base.py:1164 +#, python-format +msgid "%(model_name)s with this %(field_labels)s already exists." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:104 +#, python-format +msgid "Value %(value)r is not a valid choice." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:105 +msgid "This field cannot be null." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:106 +msgid "This field cannot be blank." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:107 +#, python-format +msgid "%(model_name)s with this %(field_label)s already exists." +msgstr "" + +#. Translators: The 'lookup_type' is one of 'date', 'year' or 'month'. +#. Eg: "Title must be unique for pub_date year" +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:111 +#, python-format +msgid "" +"%(field_label)s must be unique for %(date_field_label)s %(lookup_type)s." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:128 +#, python-format +msgid "Field of type: %(field_type)s" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:899 +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1766 +msgid "Integer" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:903 +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1764 +#, python-format +msgid "'%(value)s' value must be an integer." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:978 +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1844 +msgid "Big (8 byte) integer" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:990 +#, python-format +msgid "'%(value)s' value must be either True or False." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:991 +#, python-format +msgid "'%(value)s' value must be either True, False, or None." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:993 +msgid "Boolean (Either True or False)" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1034 +#, python-format +msgid "String (up to %(max_length)s)" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1098 +msgid "Comma-separated integers" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1147 +#, python-format +msgid "" +"'%(value)s' value has an invalid date format. It must be in YYYY-MM-DD " +"format." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1149 +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1292 +#, python-format +msgid "" +"'%(value)s' value has the correct format (YYYY-MM-DD) but it is an invalid " +"date." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1152 +msgid "Date (without time)" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1290 +#, python-format +msgid "" +"'%(value)s' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[." +"uuuuuu]][TZ] format." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1294 +#, python-format +msgid "" +"'%(value)s' value has the correct format (YYYY-MM-DD HH:MM[:ss[.uuuuuu]]" +"[TZ]) but it is an invalid date/time." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1298 +msgid "Date (with time)" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1446 +#, python-format +msgid "'%(value)s' value must be a decimal number." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1448 +msgid "Decimal number" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1587 +#, python-format +msgid "" +"'%(value)s' value has an invalid format. It must be in [DD] [HH:[MM:]]ss[." +"uuuuuu] format." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1590 +msgid "Duration" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1640 +msgid "Email address" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1663 +msgid "File path" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1729 +#, python-format +msgid "'%(value)s' value must be a float." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1731 +msgid "Floating point number" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1860 +msgid "IPv4 address" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1971 +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1972 +#, python-format +msgid "'%(value)s' value must be either None, True or False." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:1974 +msgid "Boolean (Either True, False or None)" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:2009 +msgid "Positive integer" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:2022 +msgid "Positive small integer" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:2036 +#, python-format +msgid "Slug (up to %(max_length)s)" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:2068 +msgid "Small integer" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:2103 +#, python-format +msgid "" +"'%(value)s' value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] " +"format." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:2105 +#, python-format +msgid "" +"'%(value)s' value has the correct format (HH:MM[:ss[.uuuuuu]]) but it is an " +"invalid time." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:2108 +msgid "Time" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:2256 +msgid "Raw binary data" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:2306 +#, python-format +msgid "'%(value)s' is not a valid UUID." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/__init__.py:2308 +msgid "Universally unique identifier" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/files.py:221 +msgid "File" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/related.py:778 +#, python-format +msgid "%(model)s instance with %(field)s %(value)r does not exist." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/related.py:780 +msgid "Foreign Key (type determined by related field)" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/related.py:1007 +msgid "One-to-one relationship" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/related.py:1057 +#, python-format +msgid "%(from)s-%(to)s relationship" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/related.py:1058 +#, python-format +msgid "%(from)s-%(to)s relationships" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/db/models/fields/related.py:1100 +msgid "Many-to-many relationship" +msgstr "" + +#. Translators: If found as last label character, these punctuation +#. characters will prevent the default label_suffix to be appended to the label +#: venv/lib/python3.6/site-packages/django/forms/boundfield.py:146 +msgid ":?.!" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:245 +msgid "Enter a whole number." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:396 +#: venv/lib/python3.6/site-packages/django/forms/fields.py:1126 +msgid "Enter a valid date." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:420 +#: venv/lib/python3.6/site-packages/django/forms/fields.py:1127 +msgid "Enter a valid time." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:442 +msgid "Enter a valid date/time." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:471 +msgid "Enter a valid duration." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:472 +#, python-brace-format +msgid "The number of days must be between {min_days} and {max_days}." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:532 +msgid "No file was submitted. Check the encoding type on the form." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:533 +msgid "No file was submitted." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:534 +msgid "The submitted file is empty." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:536 +#, python-format +msgid "Ensure this filename has at most %(max)d character (it has %(length)d)." +msgid_plural "" +"Ensure this filename has at most %(max)d characters (it has %(length)d)." +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:539 +msgid "Please either submit a file or check the clear checkbox, not both." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:600 +msgid "" +"Upload a valid image. The file you uploaded was either not an image or a " +"corrupted image." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:762 +#: venv/lib/python3.6/site-packages/django/forms/fields.py:852 +#: venv/lib/python3.6/site-packages/django/forms/models.py:1270 +#, python-format +msgid "Select a valid choice. %(value)s is not one of the available choices." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:853 +#: venv/lib/python3.6/site-packages/django/forms/fields.py:968 +#: venv/lib/python3.6/site-packages/django/forms/models.py:1269 +msgid "Enter a list of values." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:969 +msgid "Enter a complete value." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/fields.py:1185 +msgid "Enter a valid UUID." +msgstr "" + +#. Translators: This is the default suffix added to form field labels +#: venv/lib/python3.6/site-packages/django/forms/forms.py:86 +msgid ":" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/forms.py:212 +#, python-format +msgid "(Hidden field %(name)s) %(error)s" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/formsets.py:91 +msgid "ManagementForm data is missing or has been tampered with" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/formsets.py:338 +#, python-format +msgid "Please submit %d or fewer forms." +msgid_plural "Please submit %d or fewer forms." +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/forms/formsets.py:345 +#, python-format +msgid "Please submit %d or more forms." +msgid_plural "Please submit %d or more forms." +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/forms/formsets.py:371 +#: venv/lib/python3.6/site-packages/django/forms/formsets.py:373 +msgid "Order" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/models.py:751 +#, python-format +msgid "Please correct the duplicate data for %(field)s." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/models.py:755 +#, python-format +msgid "Please correct the duplicate data for %(field)s, which must be unique." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/models.py:761 +#, python-format +msgid "" +"Please correct the duplicate data for %(field_name)s which must be unique " +"for the %(lookup)s in %(date_field)s." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/models.py:770 +msgid "Please correct the duplicate values below." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/models.py:1091 +msgid "The inline value did not match the parent instance." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/models.py:1158 +msgid "Select a valid choice. That choice is not one of the available choices." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/models.py:1272 +#, python-format +msgid "\"%(pk)s\" is not a valid value." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/utils.py:162 +#, python-format +msgid "" +"%(datetime)s couldn't be interpreted in time zone %(current_timezone)s; it " +"may be ambiguous or it may not exist." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/widgets.py:395 +msgid "Clear" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/widgets.py:396 +msgid "Currently" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/widgets.py:711 +msgid "Unknown" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/widgets.py:712 +msgid "Yes" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/forms/widgets.py:713 +msgid "No" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/template/defaultfilters.py:788 +msgid "yes,no,maybe" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/template/defaultfilters.py:817 +#: venv/lib/python3.6/site-packages/django/template/defaultfilters.py:834 +#, python-format +msgid "%(size)d byte" +msgid_plural "%(size)d bytes" +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/template/defaultfilters.py:836 +#, python-format +msgid "%s KB" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/template/defaultfilters.py:838 +#, python-format +msgid "%s MB" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/template/defaultfilters.py:840 +#, python-format +msgid "%s GB" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/template/defaultfilters.py:842 +#, python-format +msgid "%s TB" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/template/defaultfilters.py:844 +#, python-format +msgid "%s PB" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dateformat.py:62 +msgid "p.m." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dateformat.py:63 +msgid "a.m." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dateformat.py:68 +msgid "PM" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dateformat.py:69 +msgid "AM" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dateformat.py:150 +msgid "midnight" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dateformat.py:152 +msgid "noon" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:10 +msgid "Mon" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:10 +msgid "Tue" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:10 +msgid "Wed" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:10 +msgid "Thu" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:10 +msgid "Fri" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:11 +msgid "Sat" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:11 +msgid "Sun" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:14 +msgid "January" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:14 +msgid "February" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:14 +msgid "March" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:14 +msgid "April" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:14 +msgid "May" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:14 +msgid "June" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:15 +msgid "July" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:15 +msgid "August" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:15 +msgid "September" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:15 +msgid "October" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:15 +msgid "November" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:16 +msgid "December" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:19 +msgid "jan" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:19 +msgid "feb" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:19 +msgid "mar" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:19 +msgid "apr" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:19 +msgid "may" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:19 +msgid "jun" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:20 +msgid "jul" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:20 +msgid "aug" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:20 +msgid "sep" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:20 +msgid "oct" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:20 +msgid "nov" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:20 +msgid "dec" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:23 +msgctxt "abbrev. month" +msgid "Jan." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:24 +msgctxt "abbrev. month" +msgid "Feb." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:25 +msgctxt "abbrev. month" +msgid "March" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:26 +msgctxt "abbrev. month" +msgid "April" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:27 +msgctxt "abbrev. month" +msgid "May" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:28 +msgctxt "abbrev. month" +msgid "June" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:29 +msgctxt "abbrev. month" +msgid "July" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:30 +msgctxt "abbrev. month" +msgid "Aug." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:31 +msgctxt "abbrev. month" +msgid "Sept." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:32 +msgctxt "abbrev. month" +msgid "Oct." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:33 +msgctxt "abbrev. month" +msgid "Nov." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:34 +msgctxt "abbrev. month" +msgid "Dec." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:37 +msgctxt "alt. month" +msgid "January" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:38 +msgctxt "alt. month" +msgid "February" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:39 +msgctxt "alt. month" +msgid "March" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:40 +msgctxt "alt. month" +msgid "April" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:41 +msgctxt "alt. month" +msgid "May" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:42 +msgctxt "alt. month" +msgid "June" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:43 +msgctxt "alt. month" +msgid "July" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:44 +msgctxt "alt. month" +msgid "August" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:45 +msgctxt "alt. month" +msgid "September" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:46 +msgctxt "alt. month" +msgid "October" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:47 +msgctxt "alt. month" +msgid "November" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/dates.py:48 +msgctxt "alt. month" +msgid "December" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/ipv6.py:8 +msgid "This is not a valid IPv6 address." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/text.py:67 +#, python-format +msgctxt "String to return when truncating text" +msgid "%(truncated_text)s…" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/text.py:233 +msgid "or" +msgstr "" + +#. Translators: This string is used as a separator between list elements +#: venv/lib/python3.6/site-packages/django/utils/text.py:252 +#: venv/lib/python3.6/site-packages/django/utils/timesince.py:83 +msgid ", " +msgstr "" + +#: venv/lib/python3.6/site-packages/django/utils/timesince.py:9 +#, python-format +msgid "%d year" +msgid_plural "%d years" +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/utils/timesince.py:10 +#, python-format +msgid "%d month" +msgid_plural "%d months" +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/utils/timesince.py:11 +#, python-format +msgid "%d week" +msgid_plural "%d weeks" +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/utils/timesince.py:12 +#, python-format +msgid "%d day" +msgid_plural "%d days" +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/utils/timesince.py:13 +#, python-format +msgid "%d hour" +msgid_plural "%d hours" +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/utils/timesince.py:14 +#, python-format +msgid "%d minute" +msgid_plural "%d minutes" +msgstr[0] "" +msgstr[1] "" + +#: venv/lib/python3.6/site-packages/django/utils/timesince.py:72 +msgid "0 minutes" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/csrf.py:110 +msgid "Forbidden" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/csrf.py:111 +msgid "CSRF verification failed. Request aborted." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/csrf.py:115 +msgid "" +"You are seeing this message because this HTTPS site requires a 'Referer " +"header' to be sent by your Web browser, but none was sent. This header is " +"required for security reasons, to ensure that your browser is not being " +"hijacked by third parties." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/csrf.py:120 +msgid "" +"If you have configured your browser to disable 'Referer' headers, please re-" +"enable them, at least for this site, or for HTTPS connections, or for 'same-" +"origin' requests." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/csrf.py:124 +msgid "" +"If you are using the tag or " +"including the 'Referrer-Policy: no-referrer' header, please remove them. The " +"CSRF protection requires the 'Referer' header to do strict referer checking. " +"If you're concerned about privacy, use alternatives like for links to third-party sites." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/csrf.py:132 +msgid "" +"You are seeing this message because this site requires a CSRF cookie when " +"submitting forms. This cookie is required for security reasons, to ensure " +"that your browser is not being hijacked by third parties." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/csrf.py:137 +msgid "" +"If you have configured your browser to disable cookies, please re-enable " +"them, at least for this site, or for 'same-origin' requests." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/csrf.py:142 +msgid "More information is available with DEBUG=True." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/generic/dates.py:41 +msgid "No year specified" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/generic/dates.py:61 +#: venv/lib/python3.6/site-packages/django/views/generic/dates.py:111 +#: venv/lib/python3.6/site-packages/django/views/generic/dates.py:208 +msgid "Date out of range" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/generic/dates.py:90 +msgid "No month specified" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/generic/dates.py:142 +msgid "No day specified" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/generic/dates.py:188 +msgid "No week specified" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/generic/dates.py:338 +#: venv/lib/python3.6/site-packages/django/views/generic/dates.py:367 +#, python-format +msgid "No %(verbose_name_plural)s available" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/generic/dates.py:589 +#, python-format +msgid "" +"Future %(verbose_name_plural)s not available because %(class_name)s." +"allow_future is False." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/generic/dates.py:623 +#, python-format +msgid "Invalid date string '%(datestr)s' given format '%(format)s'" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/generic/detail.py:54 +#, python-format +msgid "No %(verbose_name)s found matching the query" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/generic/list.py:67 +msgid "Page is not 'last', nor can it be converted to an int." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/generic/list.py:72 +#, python-format +msgid "Invalid page (%(page_number)s): %(message)s" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/generic/list.py:154 +#, python-format +msgid "Empty list and '%(class_name)s.allow_empty' is False." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/static.py:40 +msgid "Directory indexes are not allowed here." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/static.py:42 +#, python-format +msgid "\"%(path)s\" does not exist" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/static.py:80 +#, python-format +msgid "Index of %(directory)s" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/templates/default_urlconf.html:6 +msgid "Django: the Web framework for perfectionists with deadlines." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/templates/default_urlconf.html:345 +#, python-format +msgid "" +"View release notes for Django %(version)s" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/templates/default_urlconf.html:367 +msgid "The install worked successfully! Congratulations!" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/templates/default_urlconf.html:368 +#, python-format +msgid "" +"You are seeing this page because DEBUG=True is in your settings file and you have not configured any " +"URLs." +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/templates/default_urlconf.html:383 +msgid "Django Documentation" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/templates/default_urlconf.html:384 +msgid "Topics, references, & how-to's" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/templates/default_urlconf.html:395 +msgid "Tutorial: A Polling App" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/templates/default_urlconf.html:396 +msgid "Get started with Django" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/templates/default_urlconf.html:407 +msgid "Django Community" +msgstr "" + +#: venv/lib/python3.6/site-packages/django/views/templates/default_urlconf.html:408 +msgid "Connect, get help, or contribute" +msgstr "" + +#: venv/lib/python3.6/site-packages/easy_select2/forms.py:7 +msgid "" +"Hold down \"Control\", or \"Command\" on a Mac, to select more than one." +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/admin.py:64 +#, python-format +msgid "Some messages were sent: %s" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/admin.py:66 +#, python-format +msgid "All messages were sent: %s" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/admin.py:72 +#, python-format +msgid "Some messages failed to send. %d devices were marked as inactive." +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/admin.py:80 +msgid "Send test notification" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/admin.py:85 +msgid "Send test notification in bulk" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/admin.py:90 +msgid "Send test data message" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/admin.py:96 +msgid "Send test data message in bulk" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/admin.py:101 +msgid "Enable selected devices" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/admin.py:106 +msgid "Disable selected devices" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/apps.py:7 +msgid "FCM Django" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/fields.py:52 +msgid "Enter a valid hexadecimal number" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/models.py:19 +msgid "Is active" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/models.py:20 +msgid "Inactive devices will not be sent notifications" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/models.py:25 +msgid "Creation date" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/models.py:161 +msgid "Device ID" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/models.py:162 +msgid "Unique device identifier" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/models.py:165 +msgid "Registration token" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/models.py:171 +#: venv/lib/python3.6/site-packages/fcm_django/models.py:255 +msgid "FCM device" +msgstr "" + +#: venv/lib/python3.6/site-packages/fcm_django/models.py:256 +msgid "FCM devices" +msgstr "" + +#: venv/lib/python3.6/site-packages/kombu/transport/qpid.py:1301 +#, python-format +msgid "Attempting to connect to qpid with SASL mechanism %s" +msgstr "" + +#: venv/lib/python3.6/site-packages/kombu/transport/qpid.py:1306 +#, python-format +msgid "Connected to qpid with SASL mechanism %s" +msgstr "" + +#: venv/lib/python3.6/site-packages/kombu/transport/qpid.py:1324 +#, python-format +msgid "Unable to connect to qpid with SASL mechanism %s" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/models.py:41 +msgid "Confidential" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/models.py:42 +msgid "Public" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/models.py:50 +msgid "Authorization code" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/models.py:51 +msgid "Implicit" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/models.py:52 +msgid "Resource owner password-based" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/models.py:53 +msgid "Client credentials" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/models.py:67 +msgid "Allowed URIs list, space separated" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/models.py:143 +#, python-brace-format +msgid "Unauthorized redirect scheme: {scheme}" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/models.py:148 +#, python-brace-format +msgid "redirect_uris cannot be empty with grant_type {grant_type}" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/oauth2_validators.py:166 +msgid "The access token is invalid." +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/oauth2_validators.py:171 +msgid "The access token has expired." +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/oauth2_validators.py:176 +msgid "The access token is valid but does not have enough scope." +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_confirm_delete.html:6 +msgid "Are you sure to delete the application" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_confirm_delete.html:12 +msgid "Cancel" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_detail.html:10 +msgid "Client id" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_detail.html:15 +msgid "Client secret" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_detail.html:20 +msgid "Client type" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_detail.html:25 +msgid "Authorization Grant Type" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_detail.html:30 +msgid "Redirect Uris" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_detail.html:36 +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_form.html:35 +msgid "Go Back" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_detail.html:37 +msgid "Edit" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_form.html:9 +msgid "Edit application" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_list.html:6 +msgid "Your applications" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_list.html:16 +msgid "No applications defined" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_list.html:16 +msgid "Click here" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_list.html:16 +msgid "if you want to register a new one" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/application_registration_form.html:5 +msgid "Register a new application" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/authorize.html:8 +msgid "Authorize" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/authorize.html:17 +msgid "Application requires following permissions" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/authorized-token-delete.html:6 +msgid "Are you sure you want to delete this token?" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/authorized-tokens.html:6 +msgid "Tokens" +msgstr "" + +#: venv/lib/python3.6/site-packages/oauth2_provider/templates/oauth2_provider/authorized-tokens.html:19 +msgid "There are no authorized tokens yet." +msgstr "" + +#: venv/lib/python3.6/site-packages/solo/admin.py:53 +#, python-format +msgid "%(obj)s was changed successfully." +msgstr "" + +#: venv/lib/python3.6/site-packages/solo/admin.py:55 +msgid "You may edit it again below." +msgstr "" + +#: venv/lib/python3.6/site-packages/solo/templatetags/solo_tags.py:22 +#, python-format +msgid "" +"Templatetag requires the model dotted path: 'app_label.ModelName'. Received " +"'%s'." +msgstr "" + +#: venv/lib/python3.6/site-packages/solo/templatetags/solo_tags.py:28 +#, python-format +msgid "" +"Could not get the model name '%(model)s' from the application named '%(app)s'" +msgstr "" diff --git a/project/settings/base.py b/project/settings/base.py index 77701c8f..72fbd05f 100644 --- a/project/settings/base.py +++ b/project/settings/base.py @@ -55,6 +55,7 @@ PROJECT_APPS = [ 'advertisement.apps.AdvertisementConfig', 'account.apps.AccountConfig', 'authorization.apps.AuthorizationConfig', + 'booking.apps.BookingConfig', 'collection.apps.CollectionConfig', 'establishment.apps.EstablishmentConfig', 'gallery.apps.GalleryConfig', @@ -72,6 +73,8 @@ PROJECT_APPS = [ 'review.apps.ReviewConfig', 'comment.apps.CommentConfig', 'favorites.apps.FavoritesConfig', + 'rating.apps.RatingConfig', + 'tag.apps.TagConfig', ] EXTERNAL_APPS = [ @@ -263,6 +266,13 @@ SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email', } +# Booking API configuration +GUESTONLINE_SERVICE = 'https://api-preprod.guestonline.fr/' +GUESTONLINE_TOKEN = 'iiReiYpyojshpPjpmczS' +LASTABLE_SERVICE = 'http://34.251.84.222/' +LASTABLE_TOKEN = '6dfc608ce5e494' +LASTABLE_PROXY = 'socks5://octopod:adgjmptw@94.177.171.154:2080' + # SMS Settings SMS_EXPIRATION = 5 SMS_SEND_DELAY = 30 @@ -275,15 +285,15 @@ SMS_CODE_SHOW = False # SMSC Settings SMS_SERVICE = 'http://smsc.ru/sys/send.php' -SMS_LOGIN = 'GM2019' -SMS_PASSWORD = '}#6%Qe7CYG7n' +SMS_LOGIN = os.environ.get('SMS_LOGIN') +SMS_PASSWORD = os.environ.get('SMS_PASSWORD') SMS_SENDER = 'GM' # EMAIL EMAIL_USE_TLS = True -EMAIL_HOST = 'smtp.gmail.com' -EMAIL_HOST_USER = 'anatolyfeteleu@gmail.com' -EMAIL_HOST_PASSWORD = 'nggrlnbehzksgmbt' +EMAIL_HOST = 'smtp.mandrillapp.com' +EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') +EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASSWORD') EMAIL_PORT = 587 # Django Rest Swagger @@ -309,7 +319,10 @@ REDOC_SETTINGS = { } # CELERY -BROKER_URL = 'amqp://rabbitmq:5672' +# RabbitMQ +# BROKER_URL = 'amqp://rabbitmq:5672' +# Redis +BROKER_URL = 'redis://localhost:6379/1' CELERY_RESULT_BACKEND = BROKER_URL CELERY_BROKER_URL = BROKER_URL CELERY_ACCEPT_CONTENT = ['application/json'] @@ -328,15 +341,30 @@ FCM_DJANGO_SETTINGS = { # Thumbnail settings THUMBNAIL_ALIASES = { - '': { - 'tiny': {'size': (100, 0), }, - 'small': {'size': (480, 0), }, - 'middle': {'size': (700, 0), }, - 'large': {'size': (1500, 0), }, - 'default': {'size': (300, 200), 'crop': True}, - 'gallery': {'size': (240, 160), 'crop': True}, - 'establishment_preview': {'size': (300, 280), 'crop': True}, - } + 'news_preview': { + 'web': {'size': (300, 260), } + }, + 'news_promo_horizontal': { + 'web': {'size': (1900, 600), }, + 'mobile': {'size': (375, 260), }, + }, + 'news_tile_horizontal': { + 'web': {'size': (300, 275), }, + 'mobile': {'size': (343, 180), }, + }, + 'news_tile_vertical': { + 'web': {'size': (300, 380), }, + }, + 'news_highlight_vertical': { + 'web': {'size': (460, 630), }, + }, + 'news_editor': { + 'web': {'size': (940, 430), }, # при загрузке через контент эдитор + 'mobile': {'size': (343, 260), }, # через контент эдитор в мобильном браузерe + }, + 'avatar_comments': { + 'web': {'size': (116, 116), }, + }, } # Password reset @@ -383,6 +411,7 @@ PASSWORD_RESET_TIMEOUT_DAYS = 1 RESETTING_TOKEN_TEMPLATE = 'account/password_reset_email.html' CHANGE_EMAIL_TEMPLATE = 'account/change_email.html' CONFIRM_EMAIL_TEMPLATE = 'authorization/confirm_email.html' +NEWS_EMAIL_TEMPLATE = "news/news_email.html" # COOKIES @@ -413,3 +442,14 @@ SOLO_CACHE_TIMEOUT = 300 SITE_REDIRECT_URL_UNSUBSCRIBE = '/unsubscribe/' SITE_NAME = 'Gault & Millau' + +# Used in annotations for establishments. +DEFAULT_ESTABLISHMENT_PUBLIC_MARK = 10 +# Limit output objects (see in pagination classes). +LIMITING_OUTPUT_OBJECTS = 12 +# Need to restrict objects to sort (3 times more then expected). +LIMITING_QUERY_NUMBER = LIMITING_OUTPUT_OBJECTS * 3 + +# GEO +# A Spatial Reference System Identifier +GEO_DEFAULT_SRID = 4326 diff --git a/project/settings/development.py b/project/settings/development.py index a7c8d9fd..ff80b492 100644 --- a/project/settings/development.py +++ b/project/settings/development.py @@ -24,7 +24,7 @@ ELASTICSEARCH_DSL = { ELASTICSEARCH_INDEX_NAMES = { - 'search_indexes.documents.news': 'development_news', + 'search_indexes.documents.news': 'development_news', # temporarily disabled 'search_indexes.documents.establishment': 'development_establishment', } diff --git a/project/settings/local.py b/project/settings/local.py index febe4dd4..31fe88c2 100644 --- a/project/settings/local.py +++ b/project/settings/local.py @@ -1,11 +1,12 @@ """Local settings.""" from .base import * +import sys ALLOWED_HOSTS = ['*', ] SEND_SMS = False SMS_CODE_SHOW = True -USE_CELERY = False +USE_CELERY = True SCHEMA_URI = 'http' DEFAULT_SUBDOMAIN = 'www' @@ -13,7 +14,10 @@ SITE_DOMAIN_URI = 'testserver.com:8000' DOMAIN_URI = '0.0.0.0:8000' # CELERY -BROKER_URL = 'amqp://rabbitmq:5672' +# RabbitMQ +# BROKER_URL = 'amqp://rabbitmq:5672' +# Redis +BROKER_URL = 'redis://redis:6379/1' CELERY_RESULT_BACKEND = BROKER_URL CELERY_BROKER_URL = BROKER_URL @@ -64,6 +68,10 @@ ELASTICSEARCH_DSL = { ELASTICSEARCH_INDEX_NAMES = { - 'search_indexes.documents.news': 'local_news', - 'search_indexes.documents.establishment': 'local_establishment', -} \ No newline at end of file + # 'search_indexes.documents.news': 'local_news', + 'search_indexes.documents.establishment': 'local_establishment', +} + +TESTING = sys.argv[1:2] == ['test'] +if TESTING: + ELASTICSEARCH_INDEX_NAMES = {} diff --git a/project/settings/production.py b/project/settings/production.py index e491a1fb..5682a59d 100644 --- a/project/settings/production.py +++ b/project/settings/production.py @@ -1,2 +1,9 @@ """Production settings.""" from .base import * + +# Booking API configuration +GUESTONLINE_SERVICE = 'https://api.guestonline.fr/' +GUESTONLINE_TOKEN = '' +LASTABLE_SERVICE = '' +LASTABLE_TOKEN = '' +LASTABLE_PROXY = '' \ No newline at end of file diff --git a/project/settings/stage.py b/project/settings/stage.py index 59fc78ed..c0d6fdb1 100644 --- a/project/settings/stage.py +++ b/project/settings/stage.py @@ -22,6 +22,6 @@ ELASTICSEARCH_DSL = { ELASTICSEARCH_INDEX_NAMES = { - 'search_indexes.documents.news': 'stage_news', + # 'search_indexes.documents.news': 'stage_news', #temporarily disabled 'search_indexes.documents.establishment': 'stage_establishment', } diff --git a/project/templates/account/change_email.html b/project/templates/account/change_email.html index 0a257ed6..6b74d970 100644 --- a/project/templates/account/change_email.html +++ b/project/templates/account/change_email.html @@ -3,7 +3,7 @@ {% trans "Please go to the following page for confirmation new email address:" %} -https://{{ country_code }}.{{ domain_uri }}/registered/{{ uidb64 }}/{{ token }}/ +https://{{ country_code }}.{{ domain_uri }}/change-email-confirm/{{ uidb64 }}/{{ token }}/ {% trans "Thanks for using our site!" %} diff --git a/project/templates/news/news_email.html b/project/templates/news/news_email.html new file mode 100644 index 00000000..d14bd898 --- /dev/null +++ b/project/templates/news/news_email.html @@ -0,0 +1,79 @@ + + + + + + + + {{ title }} + + +
+ +
+ + +
+
+
+
+
+ + +
+
+ {{ title }} +
+ {% if not image_url is None %} +
+ +
+ {% endif %} +
+ {{ description | safe }} +
+ + + +
+ +
+ This email has been sent to {{ send_to }} , + click here to unsubscribe +
+ +
+
+
+ + diff --git a/project/urls/back.py b/project/urls/back.py index 5a64b955..40b3415a 100644 --- a/project/urls/back.py +++ b/project/urls/back.py @@ -3,8 +3,13 @@ from django.urls import path, include app_name = 'back' urlpatterns = [ - path('gallery/', include(('gallery.urls', 'gallery'), - namespace='gallery')), + path('account/', include('account.urls.back')), + path('comment/', include('comment.urls.back')), path('establishments/', include('establishment.urls.back')), + path('gallery/', include(('gallery.urls', 'gallery'), namespace='gallery')), path('location/', include('location.urls.back')), -] \ No newline at end of file + path('news/', include('news.urls.back')), + path('review/', include('review.urls.back')), + path('tags/', include(('tag.urls.back', 'tag'), namespace='tag')), +] + diff --git a/project/urls/mobile.py b/project/urls/mobile.py index 0bcbd31c..0bea5305 100644 --- a/project/urls/mobile.py +++ b/project/urls/mobile.py @@ -4,6 +4,7 @@ app_name = 'mobile' urlpatterns = [ path('establishments/', include('establishment.urls.mobile')), + path('main/', include('main.urls.mobile')) # path('account/', include('account.urls.web')), # path('advertisement/', include('advertisement.urls.web')), # path('collection/', include('collection.urls.web')), diff --git a/project/urls/web.py b/project/urls/web.py index 18bb8fd9..872f0b9f 100644 --- a/project/urls/web.py +++ b/project/urls/web.py @@ -19,15 +19,18 @@ app_name = 'web' urlpatterns = [ path('account/', include('account.urls.web')), + path('booking/', include('booking.urls')), path('re_blocks/', include('advertisement.urls.web')), - path('collection/', include('collection.urls.web')), + path('collections/', include('collection.urls.web')), path('establishments/', include('establishment.urls.web')), path('news/', include('news.urls.web')), - path('notifications/', include('notification.urls.web')), + path('notifications/', include(('notification.urls.web', "notification"), + namespace='notification')), path('partner/', include('partner.urls.web')), path('location/', include('location.urls.web')), - path('main/', include('main.urls')), + path('main/', include('main.urls.web')), path('recipes/', include('recipe.urls.web')), + path('tags/', include('tag.urls.web')), path('translation/', include('translation.urls')), path('comments/', include('comment.urls.web')), path('favorites/', include('favorites.urls')), diff --git a/requirements/base.txt b/requirements/base.txt index 25749c4b..5c734322 100644 --- a/requirements/base.txt +++ b/requirements/base.txt @@ -9,13 +9,12 @@ fcm-django django-easy-select2 bootstrap-admin drf-yasg==1.16.0 +PySocks!=1.5.7,>=1.5.6; djangorestframework==3.9.4 markdown django-filter==2.1.0 djangorestframework-xml -celery -amqp>=2.4.0 geoip2==2.9.0 django-phonenumber-field[phonenumbers]==2.1.0 @@ -32,4 +31,9 @@ djangorestframework-simplejwt==4.3.0 django-elasticsearch-dsl>=7.0.0,<8.0.0 django-elasticsearch-dsl-drf==0.20.2 -sentry-sdk==0.11.2 \ No newline at end of file +sentry-sdk==0.11.2 + +# temp solution +redis==3.2.0 +amqp>=2.4.0 +celery==4.3.0rc2 \ No newline at end of file