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 2 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'),
),
]
56 changes: 55 additions & 1 deletion db/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,12 @@
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


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


class Genre(models.Model):
Expand All @@ -17,7 +25,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 +58,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(User, on_delete=models.CASCADE)

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_movie: str = None
) -> QuerySet:
queryset = Movie.objects.all()

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

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
11 changes: 10 additions & 1 deletion 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 @@ -42,3 +42,12 @@ def update_movie_session(

def delete_movie_session_by_id(session_id: int) -> None:
MovieSession.objects.get(id=session_id).delete()
spa7id marked this conversation as resolved.
Show resolved Hide resolved


def get_taken_seats(movie_session_id: int) -> Ticket:
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
spa7id marked this conversation as resolved.
Show resolved Hide resolved
39 changes: 39 additions & 0 deletions services/order.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from django.contrib.auth import get_user_model
from django.db import transaction
from db.models import Ticket, Order, User


def create_order(tickets: list,
username: str,
date: str = None) -> Order:
with transaction.atomic():
# Перевірка на існування користувача
try:
user = get_user_model().objects.get(username=username)
except User.DoesNotExist:
raise ValueError("User does not exist")
spa7id marked this conversation as resolved.
Show resolved Hide resolved

order = Order.objects.create(user=user)
# Встановлення дати створення
if date:
order.created_at = date
order.save()

# Створення квитків
for ticket_data in tickets:
Ticket.objects.create(
order=order,
movie_session_id=ticket_data["movie_session"],
row=ticket_data["row"],
seat=ticket_data["seat"]
)
spa7id marked this conversation as resolved.
Show resolved Hide resolved

return order


spa7id marked this conversation as resolved.
Show resolved Hide resolved
def get_orders(username: str = None) -> Order:
if username:
user = User.objects.get(username=username)
spa7id marked this conversation as resolved.
Show resolved Hide resolved
return Order.objects.filter(user=user)
else:
return Order.objects.all()
spa7id marked this conversation as resolved.
Show resolved Hide resolved
50 changes: 50 additions & 0 deletions services/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
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 User.objects.get(id=user_id)
spa7id marked this conversation as resolved.
Show resolved Hide resolved


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",
]
9 changes: 5 additions & 4 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,14 +161,15 @@ def test_ticket_unique_constraint(tickets_data):


def test_movie_service_get_movies_with_title(movies_data):
assert list(get_movies(title="harry").values_list("title")) == [
assert list(get_movies(title_movie="harry").values_list("title")) == [
("Harry Potter 1",),
("Harry Potter 2",),
("Harry Potter 3",),
("Harry Kasparov: Documentary",),
]

assert list(get_movies(title="harry potter").values_list("title")) == [
assert list(get_movies(
title_movie="harry potter").values_list("title")) == [
("Harry Potter 1",),
("Harry Potter 2",),
("Harry Potter 3",),
Expand All @@ -177,10 +178,10 @@ def test_movie_service_get_movies_with_title(movies_data):

def test_movie_service_get_movies_with_full_data(movies_data):
assert list(get_movies(
genres_ids=[1, 2], actors_ids=[2, 3], title="matrix"
genres_ids=[1, 2], actors_ids=[2, 3], title_movie="matrix"
).values_list("title")) == [("Matrix",), ("Matrix 2",)]
assert list(get_movies(
genres_ids=[1, 2], actors_ids=[2, 3], title="batman"
genres_ids=[1, 2], actors_ids=[2, 3], title_movie="batman"
).values_list("title")) == [("Batman",)]


Expand Down
Loading