diff --git a/R4C/__init__.py b/R4C/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/R4C/__pycache__/__init__.cpython-311.pyc b/R4C/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..e8893b7 Binary files /dev/null and b/R4C/__pycache__/__init__.cpython-311.pyc differ diff --git a/R4C/__pycache__/settings.cpython-311.pyc b/R4C/__pycache__/settings.cpython-311.pyc new file mode 100644 index 0000000..04a23e3 Binary files /dev/null and b/R4C/__pycache__/settings.cpython-311.pyc differ diff --git a/R4C/__pycache__/urls.cpython-311.pyc b/R4C/__pycache__/urls.cpython-311.pyc new file mode 100644 index 0000000..d292d57 Binary files /dev/null and b/R4C/__pycache__/urls.cpython-311.pyc differ diff --git a/R4C/__pycache__/wsgi.cpython-311.pyc b/R4C/__pycache__/wsgi.cpython-311.pyc new file mode 100644 index 0000000..05f68f8 Binary files /dev/null and b/R4C/__pycache__/wsgi.cpython-311.pyc differ diff --git a/R4C/asgi.py b/R4C/asgi.py new file mode 100644 index 0000000..38d534a --- /dev/null +++ b/R4C/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for R4C project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'R4C.settings') + +application = get_asgi_application() diff --git a/R4C/settings.py b/R4C/settings.py new file mode 100644 index 0000000..45cfde8 --- /dev/null +++ b/R4C/settings.py @@ -0,0 +1,132 @@ +""" +Django settings for R4C project. + +Generated by 'django-admin startproject' using Django 3.0.9. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.0/ref/settings/ +""" + +import os + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'mztx@x_-=gfhc9xs@bm58m&@3pc7##opo14zob!(l2tus05+jo' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'customers', + 'orders', + 'robots' +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'R4C.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'R4C.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/3.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + } +} + + +# Password validation +# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/3.0/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/3.0/howto/static-files/ + +STATIC_URL = '/static/' + +#Email settings +EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' +EMAIL_HOST = 'smtp.gmail.com' +EMAIL_PORT = 587 # для использования TLS, 465 для SSL +EMAIL_USE_TLS = True +EMAIL_USE_SSL = False +EMAIL_HOST_USER = '' +EMAIL_HOST_PASSWORD = '' diff --git a/R4C/urls.py b/R4C/urls.py new file mode 100644 index 0000000..66842dd --- /dev/null +++ b/R4C/urls.py @@ -0,0 +1,23 @@ +"""R4C URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.0/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path +from django.urls import path, include +urlpatterns = [ + path('admin/', admin.site.urls), + path('robots/',include('robots.urls')), + path('orders/',include('orders.urls')), +] diff --git a/R4C/wsgi.py b/R4C/wsgi.py new file mode 100644 index 0000000..385b51e --- /dev/null +++ b/R4C/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for R4C project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'R4C.settings') + +application = get_wsgi_application() diff --git a/README.md b/README.md index c037f11..eec0642 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,33 @@ -# Robots -Это заготовка для сервиса, который ведет учет произведенных роботов, а также выполняет некие операции связанные с этим процессом. +# R4C - Robots for consumers + +## Небольшая предыстория. +Давным-давно, в далёкой-далёкой галактике, была компания производящая различных +роботов. + +Каждый робот(**Robot**) имел определенную модель выраженную двух-символьной +последовательностью(например R2). Одновременно с этим, модель имела различные +версии(например D2). Напоминает популярный телефон различных моделей(11,12,13...) и его версии +(X,XS,Pro...). Вне компании роботов чаще всего называли по серийному номеру, объединяя модель и версию(например R2-D2). + +Также у компании были покупатели(**Customer**) которые периодически заказывали того или иного робота. + +Когда роботов не было в наличии - заказы покупателей(**Order**) попадали в список ожидания. + +--- +## Что делает данный код? +Это заготовка для сервиса, который ведет учет произведенных роботов,а также +выполняет некие операции связанные с этим процессом. + +Сервис нацелен на удовлетворение потребностей трёх категорий пользователей: +- Технические специалисты компании. Они будут присылать информацию +- Менеджмент компании. Они будут запрашивать информацию +- Клиенты. Им будут отправляться информация +___ + +## Как с этим работать? +- Создать для этого проекта репозиторий на GitHub +- Открыть данный проект в редакторе/среде разработки которую вы используете +- Ознакомиться с задачами в файле tasks.md +- Написать понятный и поддерживаемый код для каждой задачи +- Сделать по 1 отдельному PR с решением для каждой задачи +- Прислать ссылку на своё решение \ No newline at end of file diff --git a/customers/__init__.py b/customers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/customers/__pycache__/__init__.cpython-311.pyc b/customers/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..9aec5c4 Binary files /dev/null and b/customers/__pycache__/__init__.cpython-311.pyc differ diff --git a/customers/__pycache__/admin.cpython-311.pyc b/customers/__pycache__/admin.cpython-311.pyc new file mode 100644 index 0000000..4fe1de6 Binary files /dev/null and b/customers/__pycache__/admin.cpython-311.pyc differ diff --git a/customers/__pycache__/apps.cpython-311.pyc b/customers/__pycache__/apps.cpython-311.pyc new file mode 100644 index 0000000..80a3757 Binary files /dev/null and b/customers/__pycache__/apps.cpython-311.pyc differ diff --git a/customers/__pycache__/models.cpython-311.pyc b/customers/__pycache__/models.cpython-311.pyc new file mode 100644 index 0000000..e6217db Binary files /dev/null and b/customers/__pycache__/models.cpython-311.pyc differ diff --git a/customers/admin.py b/customers/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/customers/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/customers/apps.py b/customers/apps.py new file mode 100644 index 0000000..01aabb7 --- /dev/null +++ b/customers/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class CustomersConfig(AppConfig): + name = 'customers' diff --git a/customers/migrations/0001_initial.py b/customers/migrations/0001_initial.py new file mode 100644 index 0000000..5331c2a --- /dev/null +++ b/customers/migrations/0001_initial.py @@ -0,0 +1,21 @@ +# Generated by Django 3.0.9 on 2023-01-30 06:40 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Customer', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('email', models.CharField(max_length=255)), + ], + ), + ] diff --git a/customers/migrations/0002_customer_name_alter_customer_email.py b/customers/migrations/0002_customer_name_alter_customer_email.py new file mode 100644 index 0000000..61f1e89 --- /dev/null +++ b/customers/migrations/0002_customer_name_alter_customer_email.py @@ -0,0 +1,23 @@ +# Generated by Django 4.2.1 on 2023-09-29 11:29 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('customers', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='customer', + name='name', + field=models.CharField(default='NoName', max_length=255), + ), + migrations.AlterField( + model_name='customer', + name='email', + field=models.CharField(max_length=255, unique=True), + ), + ] diff --git a/customers/migrations/__init__.py b/customers/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/customers/migrations/__pycache__/0001_initial.cpython-311.pyc b/customers/migrations/__pycache__/0001_initial.cpython-311.pyc new file mode 100644 index 0000000..c842299 Binary files /dev/null and b/customers/migrations/__pycache__/0001_initial.cpython-311.pyc differ diff --git a/customers/migrations/__pycache__/0002_customer_name_alter_customer_email.cpython-311.pyc b/customers/migrations/__pycache__/0002_customer_name_alter_customer_email.cpython-311.pyc new file mode 100644 index 0000000..29dab90 Binary files /dev/null and b/customers/migrations/__pycache__/0002_customer_name_alter_customer_email.cpython-311.pyc differ diff --git a/customers/migrations/__pycache__/__init__.cpython-311.pyc b/customers/migrations/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..0a67f23 Binary files /dev/null and b/customers/migrations/__pycache__/__init__.cpython-311.pyc differ diff --git a/customers/models.py b/customers/models.py new file mode 100644 index 0000000..33db289 --- /dev/null +++ b/customers/models.py @@ -0,0 +1,5 @@ +from django.db import models + +class Customer(models.Model): + email = models.CharField(max_length=255,blank=False, null=False,unique=True) + name = models.CharField(max_length=255,default='NoName') diff --git a/customers/tests.py b/customers/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/customers/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/customers/views.py b/customers/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/customers/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/db.sqlite3 b/db.sqlite3 new file mode 100644 index 0000000..2c76697 Binary files /dev/null and b/db.sqlite3 differ diff --git a/manage.py b/manage.py new file mode 100644 index 0000000..5c81f95 --- /dev/null +++ b/manage.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'R4C.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/orders/__init__.py b/orders/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/orders/__pycache__/__init__.cpython-311.pyc b/orders/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..0e6bab6 Binary files /dev/null and b/orders/__pycache__/__init__.cpython-311.pyc differ diff --git a/orders/__pycache__/admin.cpython-311.pyc b/orders/__pycache__/admin.cpython-311.pyc new file mode 100644 index 0000000..ae8c39a Binary files /dev/null and b/orders/__pycache__/admin.cpython-311.pyc differ diff --git a/orders/__pycache__/apps.cpython-311.pyc b/orders/__pycache__/apps.cpython-311.pyc new file mode 100644 index 0000000..ca04f21 Binary files /dev/null and b/orders/__pycache__/apps.cpython-311.pyc differ diff --git a/orders/__pycache__/models.cpython-311.pyc b/orders/__pycache__/models.cpython-311.pyc new file mode 100644 index 0000000..65799fb Binary files /dev/null and b/orders/__pycache__/models.cpython-311.pyc differ diff --git a/orders/__pycache__/urls.cpython-311.pyc b/orders/__pycache__/urls.cpython-311.pyc new file mode 100644 index 0000000..29f43e5 Binary files /dev/null and b/orders/__pycache__/urls.cpython-311.pyc differ diff --git a/orders/__pycache__/views.cpython-311.pyc b/orders/__pycache__/views.cpython-311.pyc new file mode 100644 index 0000000..ace3f73 Binary files /dev/null and b/orders/__pycache__/views.cpython-311.pyc differ diff --git a/orders/admin.py b/orders/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/orders/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/orders/apps.py b/orders/apps.py new file mode 100644 index 0000000..384ab43 --- /dev/null +++ b/orders/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class OrdersConfig(AppConfig): + name = 'orders' diff --git a/orders/migrations/0001_initial.py b/orders/migrations/0001_initial.py new file mode 100644 index 0000000..946436b --- /dev/null +++ b/orders/migrations/0001_initial.py @@ -0,0 +1,24 @@ +# Generated by Django 3.0.9 on 2023-01-30 06:40 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('customers', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Order', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('robot_serial', models.CharField(max_length=5)), + ('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='customers.Customer')), + ], + ), + ] diff --git a/orders/migrations/0002_remove_order_robot_serial_order_robot_and_more.py b/orders/migrations/0002_remove_order_robot_serial_order_robot_and_more.py new file mode 100644 index 0000000..1fbd465 --- /dev/null +++ b/orders/migrations/0002_remove_order_robot_serial_order_robot_and_more.py @@ -0,0 +1,40 @@ +# Generated by Django 4.2.1 on 2023-09-29 11:29 + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('robots', '0002_robot_quantity'), + ('customers', '0002_customer_name_alter_customer_email'), + ('orders', '0001_initial'), + ] + + operations = [ + migrations.RemoveField( + model_name='order', + name='robot_serial', + ), + migrations.AddField( + model_name='order', + name='robot', + field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='robot_order', to='robots.robot'), + ), + migrations.AlterField( + model_name='order', + name='customer', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='customer_order', to='customers.customer'), + ), + migrations.CreateModel( + name='WaitlistOrder', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('model', models.CharField(max_length=255)), + ('version', models.CharField(max_length=255)), + ('is_backordered', models.BooleanField()), + ('customer', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='customer_waitlist_order', to='customers.customer')), + ], + ), + ] diff --git a/orders/migrations/__init__.py b/orders/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/orders/migrations/__pycache__/0001_initial.cpython-311.pyc b/orders/migrations/__pycache__/0001_initial.cpython-311.pyc new file mode 100644 index 0000000..6758c16 Binary files /dev/null and b/orders/migrations/__pycache__/0001_initial.cpython-311.pyc differ diff --git a/orders/migrations/__pycache__/0002_remove_order_robot_serial_order_robot_and_more.cpython-311.pyc b/orders/migrations/__pycache__/0002_remove_order_robot_serial_order_robot_and_more.cpython-311.pyc new file mode 100644 index 0000000..205e657 Binary files /dev/null and b/orders/migrations/__pycache__/0002_remove_order_robot_serial_order_robot_and_more.cpython-311.pyc differ diff --git a/orders/migrations/__pycache__/0002_waitlistorder_remove_order_robot_serial_order_robot_and_more.cpython-311.pyc b/orders/migrations/__pycache__/0002_waitlistorder_remove_order_robot_serial_order_robot_and_more.cpython-311.pyc new file mode 100644 index 0000000..caa3d74 Binary files /dev/null and b/orders/migrations/__pycache__/0002_waitlistorder_remove_order_robot_serial_order_robot_and_more.cpython-311.pyc differ diff --git a/orders/migrations/__pycache__/__init__.cpython-311.pyc b/orders/migrations/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..c4626d9 Binary files /dev/null and b/orders/migrations/__pycache__/__init__.cpython-311.pyc differ diff --git a/orders/models.py b/orders/models.py new file mode 100644 index 0000000..167540f --- /dev/null +++ b/orders/models.py @@ -0,0 +1,14 @@ +from django.db import models +from customers.models import Customer +from robots.models import Robot +from customers.models import Customer + +class Order(models.Model): + customer = models.ForeignKey(Customer,on_delete=models.CASCADE,related_name='customer_order') + robot = models.ForeignKey(Robot, on_delete=models.CASCADE,related_name='robot_order',null=True) + +class WaitlistOrder(models.Model): + customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='customer_waitlist_order',null=True) + model = models.CharField(max_length=255) + version = models.CharField(max_length=255) + is_backordered = models.BooleanField() \ No newline at end of file diff --git a/orders/tests.py b/orders/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/orders/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/orders/urls.py b/orders/urls.py new file mode 100644 index 0000000..11322fa --- /dev/null +++ b/orders/urls.py @@ -0,0 +1,7 @@ +from django.urls import path +from . import views + +urlpatterns = [ + path('api/robot/', views.order_robot_endpoint, name='order_robot_endpoint'), + path('api/robot/appear/', views.robot_appear, name='robot_appear'), +] \ No newline at end of file diff --git a/orders/views.py b/orders/views.py new file mode 100644 index 0000000..cc8d750 --- /dev/null +++ b/orders/views.py @@ -0,0 +1,71 @@ +from django.shortcuts import render +from django.http import JsonResponse +from django.views.decorators.csrf import csrf_exempt +import json +from .models import Order,Robot,Customer,WaitlistOrder +from django.core.mail import send_mail + +@csrf_exempt +#End-point заказа робота заказчиком +def order_robot_endpoint(request): + if request.method == 'POST': + data = json.loads(request.body) + + # Валидация данных + if not all(key in data for key in ['model', 'version','customer_name', 'customer_email']): + return JsonResponse({"error": "Некорректные входные данные"}, status=400) + + # Получение или создание клиента + customer, created = Customer.objects.get_or_create( + name=data['customer_name'], + email=data['customer_email'] + ) + + # Проверка наличия робота + try: + robot = Robot.objects.get(model=data['model'], version=data['version']) + # Создание заказа + order = Order.objects.create( + customer=customer, + robot=robot + ) + return JsonResponse({"message": "Успешно создано!"}) + except Robot.DoesNotExist: + # Создание списка ожидания, если робота не существует + waitlist = WaitlistOrder.objects.create( + customer=customer, + model=data['model'], + version=data['version'], + is_backordered=True + ) + return JsonResponse({"error": "Робот не найден, но ваш заказ добавлен в список ожидания"}, status=404) + + return JsonResponse({"error": "Метод не поддерживается"}, status=405) + +@csrf_exempt +#Функция,вызываемая при появлении робота +def robot_appear(request): + # Получаем все заказы, которые находятся в режиме ожидания + waitlist_orders = WaitlistOrder.objects.filter(is_backordered=True) + + for order in waitlist_orders: + # Проверяем наличие робота + robot_available = Robot.objects.filter(model=order.model, version=order.version).exists() + + if robot_available: + # Отправляем уведомление клиенту + send_mail( + 'Робот в наличии!', + f'Добрый день!\nНедавно вы интересовались нашим роботом модели {order.model}, версии {order.version}.\nЭтот робот теперь в наличии. Если вам подходит этот вариант - пожалуйста, свяжитесь с нами.', + 'alexej.ivanov1084736@gmail.com', + [order.customer.email], + fail_silently=False, + ) + # Обновляем статус заказа + order.is_backordered = False + order.save() + + else: + return JsonResponse({"error": "Робот опять не найден"}, status=404) + + return JsonResponse({"message": "Уведомления отправлены"}) \ No newline at end of file diff --git a/robots/__init__.py b/robots/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/robots/__pycache__/__init__.cpython-311.pyc b/robots/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..8a43144 Binary files /dev/null and b/robots/__pycache__/__init__.cpython-311.pyc differ diff --git a/robots/__pycache__/admin.cpython-311.pyc b/robots/__pycache__/admin.cpython-311.pyc new file mode 100644 index 0000000..01902ac Binary files /dev/null and b/robots/__pycache__/admin.cpython-311.pyc differ diff --git a/robots/__pycache__/apps.cpython-311.pyc b/robots/__pycache__/apps.cpython-311.pyc new file mode 100644 index 0000000..b4740dc Binary files /dev/null and b/robots/__pycache__/apps.cpython-311.pyc differ diff --git a/robots/__pycache__/models.cpython-311.pyc b/robots/__pycache__/models.cpython-311.pyc new file mode 100644 index 0000000..1676680 Binary files /dev/null and b/robots/__pycache__/models.cpython-311.pyc differ diff --git a/robots/__pycache__/urls.cpython-311.pyc b/robots/__pycache__/urls.cpython-311.pyc new file mode 100644 index 0000000..92b5891 Binary files /dev/null and b/robots/__pycache__/urls.cpython-311.pyc differ diff --git a/robots/__pycache__/views.cpython-311.pyc b/robots/__pycache__/views.cpython-311.pyc new file mode 100644 index 0000000..cf507ad Binary files /dev/null and b/robots/__pycache__/views.cpython-311.pyc differ diff --git a/robots/admin.py b/robots/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/robots/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/robots/apps.py b/robots/apps.py new file mode 100644 index 0000000..bb0b6fe --- /dev/null +++ b/robots/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class RobotsConfig(AppConfig): + name = 'robots' diff --git a/robots/migrations/0001_initial.py b/robots/migrations/0001_initial.py new file mode 100644 index 0000000..a370215 --- /dev/null +++ b/robots/migrations/0001_initial.py @@ -0,0 +1,24 @@ +# Generated by Django 3.0.9 on 2023-01-30 06:40 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Robot', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('serial', models.CharField(max_length=5)), + ('model', models.CharField(max_length=2)), + ('version', models.CharField(max_length=2)), + ('created', models.DateTimeField()), + ], + ), + ] diff --git a/robots/migrations/0002_robot_quantity.py b/robots/migrations/0002_robot_quantity.py new file mode 100644 index 0000000..10b09aa --- /dev/null +++ b/robots/migrations/0002_robot_quantity.py @@ -0,0 +1,19 @@ +# Generated by Django 4.2.1 on 2023-09-29 11:29 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('robots', '0001_initial'), + ] + + operations = [ + migrations.AddField( + model_name='robot', + name='quantity', + field=models.PositiveIntegerField(default=0), + preserve_default=False, + ), + ] diff --git a/robots/migrations/__init__.py b/robots/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/robots/migrations/__pycache__/0001_initial.cpython-311.pyc b/robots/migrations/__pycache__/0001_initial.cpython-311.pyc new file mode 100644 index 0000000..004db58 Binary files /dev/null and b/robots/migrations/__pycache__/0001_initial.cpython-311.pyc differ diff --git a/robots/migrations/__pycache__/0002_robot_quantity.cpython-311.pyc b/robots/migrations/__pycache__/0002_robot_quantity.cpython-311.pyc new file mode 100644 index 0000000..3b0bcc7 Binary files /dev/null and b/robots/migrations/__pycache__/0002_robot_quantity.cpython-311.pyc differ diff --git a/robots/migrations/__pycache__/__init__.cpython-311.pyc b/robots/migrations/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..1546e07 Binary files /dev/null and b/robots/migrations/__pycache__/__init__.cpython-311.pyc differ diff --git a/robots/models.py b/robots/models.py new file mode 100644 index 0000000..651be59 --- /dev/null +++ b/robots/models.py @@ -0,0 +1,9 @@ +from django.db import models + + +class Robot(models.Model): + serial = models.CharField(max_length=5, blank=False, null=False) + model = models.CharField(max_length=2, blank=False, null=False) + version = models.CharField(max_length=2, blank=False, null=False) + created = models.DateTimeField(blank=False, null=False) + quantity = models.PositiveIntegerField() diff --git a/robots/tests.py b/robots/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/robots/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/robots/urls.py b/robots/urls.py new file mode 100644 index 0000000..66df540 --- /dev/null +++ b/robots/urls.py @@ -0,0 +1,8 @@ +# urls.py +from django.urls import path +from . import views + +urlpatterns = [ + path('api/robot/', views.robot_endpoint, name='robot_endpoint'), + path('download/', views.generate_excel, name='generate_excel'), +] \ No newline at end of file diff --git a/robots/views.py b/robots/views.py new file mode 100644 index 0000000..633804a --- /dev/null +++ b/robots/views.py @@ -0,0 +1,54 @@ +from django.shortcuts import render +from django.http import JsonResponse +from django.views.decorators.csrf import csrf_exempt +import json +from .models import Robot +import openpyxl +from django.http import HttpResponse +import datetime +from django.utils import timezone + +@csrf_exempt +def robot_endpoint(request): + if request.method == 'POST': + data = json.loads(request.body) + + # Валидация данных + if not all(key in data for key in ['serial','model', 'version', 'created','quantity']): + return JsonResponse({"error": "Некорректные входные данные"}, status=400) + + # Создание записи в базе данных + robot = Robot.objects.create( + model=data['model'], + version=data['version'], + created=data['created'], + quantity=data['quantity'] + ) + return JsonResponse({"message": "Успешно создано!"}) + return JsonResponse({"error": "Метод не поддерживается"}, status=405) + +def generate_excel(request): + # Создание новой книги Excel + wb = openpyxl.Workbook() + # Вычисляем дату, начиная с которой будем фильтровать записи (7 дней назад от текущей даты) + week_ago = timezone.now() - datetime.timedelta(days=7) + + # Получаем уникальные модели роботов, произведенные за последние 7 дней + models = Robot.objects.filter(created__gte=week_ago).values_list('model', flat=True).distinct() + + # Для каждой уникальной модели создаем новую страницу в Excel + for model in models: + ws = wb.create_sheet(title=model) # Создание новой страницы с названием модели + ws.append(['Модель', 'Версия', 'Количество за неделю']) # Добавление заголовков + + # Добавление данных о каждом роботе данной модели + for robot in Robot.objects.filter(model=model,created__gte=week_ago): + ws.append([robot.model, robot.version, robot.quantity]) + + # Подготовка HTTP-ответа с файлом Excel + response = HttpResponse(content_type='application/ms-excel') + response['Content-Disposition'] = 'attachment; filename="robots_summary.xlsx"' + + # Сохранение книги Excel в ответ + wb.save(response) + return response \ No newline at end of file diff --git a/tasks.md b/tasks.md new file mode 100644 index 0000000..8097cf8 --- /dev/null +++ b/tasks.md @@ -0,0 +1,50 @@ +# Task 1. От технического специалиста компании. +Создать API-endpoint, принимающий и обрабатывающий информацию в формате JSON. +В результате web-запроса на этот endpoint, в базе данных появляется запись +отражающая информацию о произведенном на заводе роботе. + +_**Примечание от старшего технического специалиста**_: +Дополнительно предусмотреть валидацию входных данных, на соответствие существующим в системе моделям. + +Пример входных данных: + +```{"model":"R2","version":"D2","created":"2022-12-31 23:59:59"}``` + +```{"model":"13","version":"XS","created":"2023-01-01 00:00:00"}``` + +```{"model":"X5","version":"LT","created":"2023-01-01 00:00:01"}``` + + +# Task 2. От директора компании +**User Story**: Я как директор хочу иметь возможность скачать по прямой ссылке Excel-файл со сводкой по суммарным показателям производства роботов за последнюю неделю. + +_**Примечание от менеджера**_. Файл должен включать в себя несколько страниц, на каждой из которых представлена информация об одной модели, но с детализацией по версии. + +Схематично для случая с моделью "R2": + +``` + __________________________________ +|Модель|Версия|Количество за неделю| + __________________________________ +| R2 | D2 | 32 | + __________________________________ +| R2 | A1 | 41 | + ... + ... + ... +| R2 | С8 | 99 | + ... +``` + +# Task 3. От клиента компании. +**Job story**: Если я оставляю заказ на робота, и его нет в наличии, я готов подождать до момента появления робота. После чего, пожалуйста пришлите мне письмо. + +_**Примечание от менеджера**_: Письмо должно быть следующего формата +``` +Добрый день! +Недавно вы интересовались нашим роботом модели X, версии Y. +Этот робот теперь в наличии. Если вам подходит этот вариант - пожалуйста, свяжитесь с нами +``` +где Х и Y это соответственно модель и версия робота. + +_**Примечание от старшего технического специалиста**_: Постарайтесь не переопределять встроенные методы модели. Также стремитесь не смешивать контексты обработки данных и бизнес-логику. Рекомендуется использовать механизм сигналов предусмотренный в фреймворке. \ No newline at end of file