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

solution #940

Open
wants to merge 4 commits into
base: master
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Generated by Django 4.0.2 on 2024-11-10 15:20

from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone


class Migration(migrations.Migration):

dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
('db', '0001_initial'),
]

operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
spa7id marked this conversation as resolved.
Show resolved Hide resolved
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
spa7id marked this conversation as resolved.
Show resolved Hide resolved
),
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
spa7id marked this conversation as resolved.
Show resolved Hide resolved
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['-created_at'],
},
),
migrations.AlterField(
model_name='movie',
name='actors',
field=models.ManyToManyField(related_name='movies', to='db.Actor'),
),
migrations.AlterField(
model_name='movie',
name='genres',
field=models.ManyToManyField(related_name='movies', to='db.Genre'),
),
migrations.AlterField(
model_name='movie',
name='title',
field=models.CharField(db_index=True, max_length=255),
),
migrations.AlterField(
model_name='moviesession',
name='cinema_hall',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='movie_sessions', to='db.cinemahall'),
),
migrations.AlterField(
model_name='moviesession',
name='movie',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='movie_sessions', to='db.movie'),
),
migrations.CreateModel(
name='Ticket',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('row', models.IntegerField()),
('seat', models.IntegerField()),
('movie_session', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='db.moviesession')),
('order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='db.order')),
],
),
migrations.AddConstraint(
model_name='ticket',
constraint=models.UniqueConstraint(fields=('row', 'seat', 'movie_session'), name='unique_ticket_per_session'),
),
]
58 changes: 57 additions & 1 deletion db/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
from django.contrib.auth.models import AbstractUser
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import DateTimeField, ForeignKey, IntegerField, \
UniqueConstraint

import settings


class User(AbstractUser):
...
spa7id marked this conversation as resolved.
Show resolved Hide resolved


class Genre(models.Model):
Expand All @@ -17,7 +27,7 @@ def __str__(self) -> str:


class Movie(models.Model):
title = models.CharField(max_length=255)
title = models.CharField(max_length=255, db_index=True)
description = models.TextField()
actors = models.ManyToManyField(to=Actor, related_name="movies")
genres = models.ManyToManyField(to=Genre, related_name="movies")
Expand Down Expand Up @@ -50,3 +60,49 @@ class MovieSession(models.Model):

def __str__(self) -> str:
return f"{self.movie.title} {str(self.show_time)}"


class Order(models.Model):
created_at = DateTimeField(auto_now_add=True)
user = ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
spa7id marked this conversation as resolved.
Show resolved Hide resolved

def __str__(self) -> str:
return f"{self.created_at}"

class Meta:
ordering = ["-created_at"]


class Ticket(models.Model):
movie_session = ForeignKey(MovieSession, on_delete=models.CASCADE)
order = ForeignKey(Order, on_delete=models.CASCADE)
row = IntegerField()
seat = IntegerField()

def __str__(self) -> str:
return (f"{self.movie_session.movie.title}"
f" {self.movie_session.show_time}"
f" (row: {self.row}, seat: {self.seat})")

def clean(self) -> None:
if not (1 <= self.row <= self.movie_session.cinema_hall.rows):
raise ValidationError(
{"row": ["row number must be in available range: (1, rows): "
f"(1, {self.movie_session.cinema_hall.rows})"]}
)
if not (1 <= self.seat <= self.movie_session.cinema_hall.seats_in_row):
raise ValidationError(
{"seat": ["seat number must be in available range: "
"(1, seats_in_row): (1, "
f"{self.movie_session.cinema_hall.seats_in_row})"]}
)

def save(self, *args, **kwargs) -> None:
self.full_clean()
return super().save(*args, **kwargs)

class Meta:
constraints = [
UniqueConstraint(fields=["row", "seat", "movie_session"],
name="unique_ticket_per_session")
]
27 changes: 16 additions & 11 deletions services/movie.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
from django.db.models import QuerySet

from django.db import transaction
from db.models import Movie


def get_movies(
genres_ids: list[int] = None,
actors_ids: list[int] = None,
spa7id marked this conversation as resolved.
Show resolved Hide resolved
title: str = None
) -> QuerySet:
queryset = Movie.objects.all()

if title is not None:
queryset = queryset.filter(title__icontains=title)

if genres_ids:
queryset = queryset.filter(genres__id__in=genres_ids)

Expand All @@ -28,13 +32,14 @@ def create_movie(
genres_ids: list = None,
actors_ids: list = None,
) -> Movie:
movie = Movie.objects.create(
title=movie_title,
description=movie_description,
)
if genres_ids:
movie.genres.set(genres_ids)
if actors_ids:
movie.actors.set(actors_ids)

return movie
with transaction.atomic():
movie = Movie.objects.create(
title=movie_title,
description=movie_description,
)
if genres_ids:
movie.genres.set(genres_ids)
if actors_ids:
movie.actors.set(actors_ids)

return movie
16 changes: 14 additions & 2 deletions services/movie_session.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.db.models import QuerySet

from db.models import MovieSession
from db.models import MovieSession, Ticket


def create_movie_session(
Expand Down Expand Up @@ -41,4 +41,16 @@ def update_movie_session(


def delete_movie_session_by_id(session_id: int) -> None:
MovieSession.objects.get(id=session_id).delete()
try:
MovieSession.objects.get(id=session_id).delete()
except MovieSession.DoesNotExist:
raise ValueError(f"MovieSession with id {session_id} does not exist")


def get_taken_seats(movie_session_id: int) -> list[dict]:
spa7id marked this conversation as resolved.
Show resolved Hide resolved
tickets = Ticket.objects.filter(movie_session_id=movie_session_id)

taken_seats = [{"row": ticket.row, "seat": ticket.seat} for ticket in
tickets]

return taken_seats
51 changes: 51 additions & 0 deletions services/order.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from django.contrib.auth import get_user_model
from django.db.models import QuerySet
from django.shortcuts import get_object_or_404
from django.db import transaction
from db.models import Ticket, Order, User, MovieSession
from django.core.exceptions import ValidationError


def create_order(tickets: list, username: str, date: str = None) -> Order:
with transaction.atomic():
user = get_object_or_404(get_user_model(), username=username)

order = Order.objects.create(user=user)

if date:
try:
order.created_at = date
order.save()
spa7id marked this conversation as resolved.
Show resolved Hide resolved
except ValidationError:
raise ValueError(
f"Invalid date format for order creation: {date}"
)

for ticket_data in tickets:
if not MovieSession.objects.filter(
id=ticket_data["movie_session"]
).exists():
raise ValueError(
f"MS with id {ticket_data['movie_session']} does not exist"
)

ticket_objects = [
Ticket(
order=order,
movie_session_id=ticket_data["movie_session"],
row=ticket_data["row"],
seat=ticket_data["seat"]
)
for ticket_data in tickets
]

Ticket.objects.bulk_create(ticket_objects)

return order


spa7id marked this conversation as resolved.
Show resolved Hide resolved
def get_orders(username: str = None) -> QuerySet[Order]:
if username:
user = get_object_or_404(User, username=username)
return Order.objects.filter(user=user)
return Order.objects.all()
52 changes: 52 additions & 0 deletions services/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from django.shortcuts import get_object_or_404

from db.models import User


def create_user(username: str,
password: str,
email: str = None,
first_name: str = None,
last_name: str = None) -> User:

user_data = {
"username": username,
"password": password
}
if email:
user_data["email"] = email
if first_name:
user_data["first_name"] = first_name
if last_name:
user_data["last_name"] = last_name

some_user = User.objects.create_user(**user_data)
spa7id marked this conversation as resolved.
Show resolved Hide resolved
spa7id marked this conversation as resolved.
Show resolved Hide resolved
return some_user


def get_user(user_id: int) -> User:
return get_object_or_404(User, id=user_id)


def update_user(user_id: int,
username: str = None,
password: str = None,
email: str = None,
first_name: str = None,
last_name: str = None) -> User:
updated_user = User.objects.get(id=user_id)
spa7id marked this conversation as resolved.
Show resolved Hide resolved
spa7id marked this conversation as resolved.
Show resolved Hide resolved

if username:
updated_user.username = username
if email:
updated_user.email = email
if first_name:
updated_user.first_name = first_name
if last_name:
updated_user.last_name = last_name
if password:
updated_user.set_password(password)

updated_user.save()

return updated_user
4 changes: 4 additions & 0 deletions settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
}
}

AUTH_USER_MODEL = "db.User"

LANGUAGE_CODE = "en-us"

TIME_ZONE = "Europe/Kiev"
Expand All @@ -25,4 +27,6 @@

INSTALLED_APPS = [
"db",
"django.contrib.auth",
"django.contrib.contenttypes",
]
3 changes: 2 additions & 1 deletion tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,8 @@ def test_movie_service_get_movies_with_title(movies_data):
("Harry Kasparov: Documentary",),
]

assert list(get_movies(title="harry potter").values_list("title")) == [
assert list(get_movies(
title="harry potter").values_list("title")) == [
("Harry Potter 1",),
("Harry Potter 2",),
("Harry Potter 3",),
Expand Down
Loading