Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🚧 notification model and signals for wishlist feature #233

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ and this project adheres to

- Allow on-demand page size on the order and enrollment endpoints
- Add yarn cli to generate joanie api client in TypeScript
- Add model and endpoints for wishlist feature

### Removed

Expand Down
13 changes: 13 additions & 0 deletions src/backend/joanie/core/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,3 +394,16 @@ class AddressAdmin(admin.ModelAdmin):
"is_main",
"owner",
)


@admin.register(models.CourseWish)
class CourseWishAdmin(admin.ModelAdmin):
"""Admin class for the CourseWish model"""

list_display = (
"course",
"owner",
)
readonly_fields = (
"id",
)
46 changes: 46 additions & 0 deletions src/backend/joanie/core/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,3 +417,49 @@ def download(self, request, pk=None): # pylint: disable=no-self-use, invalid-na
response["Content-Disposition"] = f"attachment; filename={pk}.pdf;"

return response


class CourseWishViewSet(
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
mixins.CreateModelMixin,
mixins.DestroyModelMixin,
viewsets.GenericViewSet,
):
"""
API view allows to get all wishlists or create a new one for a user.

GET /api/wishlist/
Return list of all wishes for a user

GET /api/wishlist/?course_code=<course_code>
Return list of wishes for a user filter by the course_code

GET /api/wishlist/<course_wish_id>/
Return selected wish

POST /api/wishlist/ with expected data:
- course: str course_code
Return new wish just created

DELETE /api/wishlist/<course_wish_id>/
Delete selected wish
"""

lookup_field = "id"
serializer_class = serializers.CourseWishSerializer
permission_classes = [permissions.IsAuthenticated]

def get_queryset(self):
"""Custom queryset to get user wishlist"""
user = User.update_or_create_from_request_user(request_user=self.request.user)
queryset = user.wishlist.all()
course_code = self.request.query_params.get("course_code")
if course_code is not None:
queryset = queryset.filter(course__code=course_code)
return queryset

def perform_create(self, serializer):
"""Create a new wish for user authenticated"""
user = User.update_or_create_from_request_user(request_user=self.request.user)
serializer.save(owner=user)
15 changes: 15 additions & 0 deletions src/backend/joanie/core/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,21 @@ def ready(self):
sender=models.CourseRun,
dispatch_uid="save_course_run",
)
post_save.connect(
signals.post_save_course_run_notification,
sender=models.CourseRun,
dispatch_uid="post_save_course_run_notification",
)
post_save.connect(
signals.post_save_product_target_course_relation_notification,
sender=models.ProductTargetCourseRelation,
dispatch_uid="post_save_product_target_course_relation_notification",
)
m2m_changed.connect(
signals.post_add_m2m_product_target_course_notification,
sender=models.Product.target_courses.through,
dispatch_uid="post_add_m2m_product_target_course_notification",
)
post_save.connect(
signals.on_save_product_target_course_relation,
sender=models.ProductTargetCourseRelation,
Expand Down
27 changes: 27 additions & 0 deletions src/backend/joanie/core/factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from django.conf import settings
from django.contrib.auth.hashers import make_password
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone as django_timezone

import factory.fuzzy
Expand Down Expand Up @@ -390,3 +391,29 @@ def certificate_definition(self):
Return the order product certificate definition.
"""
return self.order.product.certificate_definition


class CourseWishFactory(factory.django.DjangoModelFactory):
"""A factory to create an user wish"""

class Meta:
model = models.CourseWish

course = factory.SubFactory(CourseFactory)
owner = factory.SubFactory(UserFactory)


class NotificationFactory(factory.django.DjangoModelFactory):
"""A factory to create an user wish"""

class Meta:
model = models.Notification
exclude = ['notif_subject, notif_object']

owner = factory.SubFactory(UserFactory)

notif_subject_id = factory.SelfAttribute('notif_subject.id')
notif_subject_ctype = factory.LazyAttribute(lambda o: ContentType.objects.get_for_model(o.notif_subject))

notif_object_id = factory.SelfAttribute('notif_object.id')
notif_object_ctype = factory.LazyAttribute(lambda o: ContentType.objects.get_for_model(o.notif_object))
72 changes: 72 additions & 0 deletions src/backend/joanie/core/migrations/0002_coursewish.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Generated by Django 4.0.10 on 2023-02-23 06:39

import uuid

import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("core", "0001_initial"),
]

operations = [
migrations.CreateModel(
name="CourseWish",
fields=[
(
"id",
models.UUIDField(
default=uuid.uuid4,
editable=False,
help_text="primary key for the record as UUID",
primary_key=True,
serialize=False,
verbose_name="id",
),
),
(
"created_on",
models.DateTimeField(
auto_now_add=True,
help_text="date and time at which a record was created",
verbose_name="created on",
),
),
(
"updated_on",
models.DateTimeField(
auto_now=True,
help_text="date and time at which a record was last updated",
verbose_name="updated on",
),
),
(
"course",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="wished_in_wishlists",
to="core.course",
verbose_name="Course",
),
),
(
"owner",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
related_name="wishlists",
to=settings.AUTH_USER_MODEL,
verbose_name="Owner",
),
),
],
options={
"verbose_name": "Course Wish",
"verbose_name_plural": "Course Wishes",
"db_table": "joanie_course_wish",
"unique_together": {("owner", "course")},
},
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Generated by Django 4.0.10 on 2023-02-24 16:37

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid


class Migration(migrations.Migration):

dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('core', '0002_coursewish'),
]

operations = [
migrations.AlterField(
model_name='courserun',
name='is_listed',
field=models.BooleanField(default=False, help_text='If checked the course run will be included in the list of course runs available for enrollment on the related course page.', verbose_name='is listed'),
),
migrations.CreateModel(
name='Notification',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, help_text='primary key for the record as UUID', primary_key=True, serialize=False, verbose_name='id')),
('created_on', models.DateTimeField(auto_now_add=True, help_text='date and time at which a record was created', verbose_name='created on')),
('updated_on', models.DateTimeField(auto_now=True, help_text='date and time at which a record was last updated', verbose_name='updated on')),
('notif_subject_id', models.UUIDField()),
('notif_object_id', models.UUIDField()),
('action_type', models.CharField(choices=[('EMAIL', 'Send an email')], default='EMAIL', max_length=10, verbose_name='Type of action')),
('notified_at', models.DateTimeField(blank=True, editable=False, help_text='date and time at which an email has been sent to the user', null=True, verbose_name='Notified at')),
('notif_object_ctype', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='object_ctype_of_notifications', to='contenttypes.contenttype')),
('notif_subject_ctype', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='subject_ctype_of_notifications', to='contenttypes.contenttype')),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'Notification',
'verbose_name_plural': 'Notifications',
'db_table': 'joanie_notification',
'ordering': ('owner', 'notified_at'),
},
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Generated by Django 4.0.10 on 2023-02-27 15:55

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('core', '0003_alter_courserun_is_listed_notification'),
]

operations = [
migrations.RenameField(
model_name='notification',
old_name='action_type',
new_name='notif_type',
),
migrations.AlterField(
model_name='notification',
name='notif_object_ctype',
field=models.ForeignKey(limit_choices_to=models.Q(models.Q(('app_label', 'core'), ('model', 'producttargetcourserelation')), models.Q(('app_label', 'core'), ('model', 'courserun')), models.Q(('app_label', 'core'), ('model', 'product')), _connector='OR'), on_delete=django.db.models.deletion.CASCADE, related_name='object_ctype_of_notifications', to='contenttypes.contenttype'),
),
migrations.AlterField(
model_name='notification',
name='notif_subject_ctype',
field=models.ForeignKey(limit_choices_to=models.Q(models.Q(('app_label', 'core'), ('model', 'coursewish')), models.Q(('app_label', 'core'), ('model', 'enrollment')), _connector='OR'), on_delete=django.db.models.deletion.CASCADE, related_name='subject_ctype_of_notifications', to='contenttypes.contenttype'),
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 4.0.10 on 2023-02-28 09:42

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('core', '0004_rename_action_type_notification_notif_type_and_more'),
]

operations = [
migrations.AddField(
model_name='notification',
name='action',
field=models.CharField(choices=[('ADD', 'added'), ('CREATE', 'created')], default='CREATE', max_length=10, verbose_name='Action on the object of notification'),
),
migrations.AlterField(
model_name='notification',
name='notif_type',
field=models.CharField(choices=[('EMAIL', 'Send an email')], default='EMAIL', max_length=10, verbose_name='Type of notification'),
),
]
2 changes: 2 additions & 0 deletions src/backend/joanie/core/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@
from .certifications import *
from .courses import *
from .products import *
from .wishlist import *
from .notifications import *
4 changes: 3 additions & 1 deletion src/backend/joanie/core/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import uuid
from itertools import chain

from django.contrib.contenttypes.fields import GenericForeignKey
from django.db import models
from django.utils.translation import gettext_lazy as _

Expand Down Expand Up @@ -52,7 +53,8 @@ def to_dict(self):
opts = self._meta
data = {}
for field in chain(opts.concrete_fields, opts.private_fields):
data[field.name] = field.value_from_object(self)
if not isinstance(field, GenericForeignKey):
data[field.name] = field.value_from_object(self)
for field in opts.many_to_many:
data[field.name] = [related.id for related in field.value_from_object(self)]
return data
Loading