diff --git a/R4C/R4C/__init__.py b/R4C/R4C/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/R4C/R4C/__pycache__/__init__.cpython-311.pyc b/R4C/R4C/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..e8893b7 Binary files /dev/null and b/R4C/R4C/__pycache__/__init__.cpython-311.pyc differ diff --git a/R4C/R4C/__pycache__/settings.cpython-311.pyc b/R4C/R4C/__pycache__/settings.cpython-311.pyc new file mode 100644 index 0000000..21b712d Binary files /dev/null and b/R4C/R4C/__pycache__/settings.cpython-311.pyc differ diff --git a/R4C/R4C/__pycache__/urls.cpython-311.pyc b/R4C/R4C/__pycache__/urls.cpython-311.pyc new file mode 100644 index 0000000..3a49673 Binary files /dev/null and b/R4C/R4C/__pycache__/urls.cpython-311.pyc differ diff --git a/R4C/R4C/__pycache__/wsgi.cpython-311.pyc b/R4C/R4C/__pycache__/wsgi.cpython-311.pyc new file mode 100644 index 0000000..05f68f8 Binary files /dev/null and b/R4C/R4C/__pycache__/wsgi.cpython-311.pyc differ diff --git a/R4C/R4C/asgi.py b/R4C/R4C/asgi.py new file mode 100644 index 0000000..38d534a --- /dev/null +++ b/R4C/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/R4C/settings.py b/R4C/R4C/settings.py new file mode 100644 index 0000000..d284f79 --- /dev/null +++ b/R4C/R4C/settings.py @@ -0,0 +1,123 @@ +""" +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/' diff --git a/R4C/R4C/urls.py b/R4C/R4C/urls.py new file mode 100644 index 0000000..2489036 --- /dev/null +++ b/R4C/R4C/urls.py @@ -0,0 +1,22 @@ +"""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')), +] diff --git a/R4C/R4C/wsgi.py b/R4C/R4C/wsgi.py new file mode 100644 index 0000000..385b51e --- /dev/null +++ b/R4C/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/R4C/README.md b/R4C/README.md new file mode 100644 index 0000000..eec0642 --- /dev/null +++ b/R4C/README.md @@ -0,0 +1,33 @@ +# 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/R4C/customers/__init__.py b/R4C/customers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/R4C/customers/__pycache__/__init__.cpython-311.pyc b/R4C/customers/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..9aec5c4 Binary files /dev/null and b/R4C/customers/__pycache__/__init__.cpython-311.pyc differ diff --git a/R4C/customers/__pycache__/admin.cpython-311.pyc b/R4C/customers/__pycache__/admin.cpython-311.pyc new file mode 100644 index 0000000..4fe1de6 Binary files /dev/null and b/R4C/customers/__pycache__/admin.cpython-311.pyc differ diff --git a/R4C/customers/__pycache__/apps.cpython-311.pyc b/R4C/customers/__pycache__/apps.cpython-311.pyc new file mode 100644 index 0000000..80a3757 Binary files /dev/null and b/R4C/customers/__pycache__/apps.cpython-311.pyc differ diff --git a/R4C/customers/__pycache__/models.cpython-311.pyc b/R4C/customers/__pycache__/models.cpython-311.pyc new file mode 100644 index 0000000..7d43a59 Binary files /dev/null and b/R4C/customers/__pycache__/models.cpython-311.pyc differ diff --git a/R4C/customers/admin.py b/R4C/customers/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/R4C/customers/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/R4C/customers/apps.py b/R4C/customers/apps.py new file mode 100644 index 0000000..01aabb7 --- /dev/null +++ b/R4C/customers/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class CustomersConfig(AppConfig): + name = 'customers' diff --git a/R4C/customers/migrations/0001_initial.py b/R4C/customers/migrations/0001_initial.py new file mode 100644 index 0000000..5331c2a --- /dev/null +++ b/R4C/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/R4C/customers/migrations/__init__.py b/R4C/customers/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/R4C/customers/migrations/__pycache__/0001_initial.cpython-311.pyc b/R4C/customers/migrations/__pycache__/0001_initial.cpython-311.pyc new file mode 100644 index 0000000..c842299 Binary files /dev/null and b/R4C/customers/migrations/__pycache__/0001_initial.cpython-311.pyc differ diff --git a/R4C/customers/migrations/__pycache__/__init__.cpython-311.pyc b/R4C/customers/migrations/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..0a67f23 Binary files /dev/null and b/R4C/customers/migrations/__pycache__/__init__.cpython-311.pyc differ diff --git a/R4C/customers/models.py b/R4C/customers/models.py new file mode 100644 index 0000000..9c2e650 --- /dev/null +++ b/R4C/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) diff --git a/R4C/customers/tests.py b/R4C/customers/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/R4C/customers/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/R4C/customers/views.py b/R4C/customers/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/R4C/customers/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/R4C/db.sqlite3 b/R4C/db.sqlite3 new file mode 100644 index 0000000..3e3effe Binary files /dev/null and b/R4C/db.sqlite3 differ diff --git a/R4C/manage.py b/R4C/manage.py new file mode 100644 index 0000000..5c81f95 --- /dev/null +++ b/R4C/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/R4C/orders/__init__.py b/R4C/orders/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/R4C/orders/__pycache__/__init__.cpython-311.pyc b/R4C/orders/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..0e6bab6 Binary files /dev/null and b/R4C/orders/__pycache__/__init__.cpython-311.pyc differ diff --git a/R4C/orders/__pycache__/admin.cpython-311.pyc b/R4C/orders/__pycache__/admin.cpython-311.pyc new file mode 100644 index 0000000..ae8c39a Binary files /dev/null and b/R4C/orders/__pycache__/admin.cpython-311.pyc differ diff --git a/R4C/orders/__pycache__/apps.cpython-311.pyc b/R4C/orders/__pycache__/apps.cpython-311.pyc new file mode 100644 index 0000000..ca04f21 Binary files /dev/null and b/R4C/orders/__pycache__/apps.cpython-311.pyc differ diff --git a/R4C/orders/__pycache__/models.cpython-311.pyc b/R4C/orders/__pycache__/models.cpython-311.pyc new file mode 100644 index 0000000..8deb4f0 Binary files /dev/null and b/R4C/orders/__pycache__/models.cpython-311.pyc differ diff --git a/R4C/orders/admin.py b/R4C/orders/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/R4C/orders/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/R4C/orders/apps.py b/R4C/orders/apps.py new file mode 100644 index 0000000..384ab43 --- /dev/null +++ b/R4C/orders/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class OrdersConfig(AppConfig): + name = 'orders' diff --git a/R4C/orders/migrations/0001_initial.py b/R4C/orders/migrations/0001_initial.py new file mode 100644 index 0000000..946436b --- /dev/null +++ b/R4C/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/R4C/orders/migrations/__init__.py b/R4C/orders/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/R4C/orders/migrations/__pycache__/0001_initial.cpython-311.pyc b/R4C/orders/migrations/__pycache__/0001_initial.cpython-311.pyc new file mode 100644 index 0000000..6758c16 Binary files /dev/null and b/R4C/orders/migrations/__pycache__/0001_initial.cpython-311.pyc differ diff --git a/R4C/orders/migrations/__pycache__/__init__.cpython-311.pyc b/R4C/orders/migrations/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..c4626d9 Binary files /dev/null and b/R4C/orders/migrations/__pycache__/__init__.cpython-311.pyc differ diff --git a/R4C/orders/models.py b/R4C/orders/models.py new file mode 100644 index 0000000..30b6bb4 --- /dev/null +++ b/R4C/orders/models.py @@ -0,0 +1,8 @@ +from django.db import models + +from customers.models import Customer + + +class Order(models.Model): + customer = models.ForeignKey(Customer,on_delete=models.CASCADE) + robot_serial = models.CharField(max_length=5,blank=False, null=False) diff --git a/R4C/orders/tests.py b/R4C/orders/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/R4C/orders/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/R4C/orders/views.py b/R4C/orders/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/R4C/orders/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/R4C/robots/__init__.py b/R4C/robots/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/R4C/robots/__pycache__/__init__.cpython-311.pyc b/R4C/robots/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..8a43144 Binary files /dev/null and b/R4C/robots/__pycache__/__init__.cpython-311.pyc differ diff --git a/R4C/robots/__pycache__/admin.cpython-311.pyc b/R4C/robots/__pycache__/admin.cpython-311.pyc new file mode 100644 index 0000000..01902ac Binary files /dev/null and b/R4C/robots/__pycache__/admin.cpython-311.pyc differ diff --git a/R4C/robots/__pycache__/apps.cpython-311.pyc b/R4C/robots/__pycache__/apps.cpython-311.pyc new file mode 100644 index 0000000..b4740dc Binary files /dev/null and b/R4C/robots/__pycache__/apps.cpython-311.pyc differ diff --git a/R4C/robots/__pycache__/models.cpython-311.pyc b/R4C/robots/__pycache__/models.cpython-311.pyc new file mode 100644 index 0000000..bbd75c1 Binary files /dev/null and b/R4C/robots/__pycache__/models.cpython-311.pyc differ diff --git a/R4C/robots/__pycache__/urls.cpython-311.pyc b/R4C/robots/__pycache__/urls.cpython-311.pyc new file mode 100644 index 0000000..61bfef5 Binary files /dev/null and b/R4C/robots/__pycache__/urls.cpython-311.pyc differ diff --git a/R4C/robots/__pycache__/views.cpython-311.pyc b/R4C/robots/__pycache__/views.cpython-311.pyc new file mode 100644 index 0000000..9ef31fe Binary files /dev/null and b/R4C/robots/__pycache__/views.cpython-311.pyc differ diff --git a/R4C/robots/admin.py b/R4C/robots/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/R4C/robots/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/R4C/robots/apps.py b/R4C/robots/apps.py new file mode 100644 index 0000000..bb0b6fe --- /dev/null +++ b/R4C/robots/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class RobotsConfig(AppConfig): + name = 'robots' diff --git a/R4C/robots/migrations/0001_initial.py b/R4C/robots/migrations/0001_initial.py new file mode 100644 index 0000000..a370215 --- /dev/null +++ b/R4C/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/R4C/robots/migrations/0002_robot_quantity.py b/R4C/robots/migrations/0002_robot_quantity.py new file mode 100644 index 0000000..cb55c45 --- /dev/null +++ b/R4C/robots/migrations/0002_robot_quantity.py @@ -0,0 +1,19 @@ +# Generated by Django 4.2.1 on 2023-09-24 16:59 + +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/R4C/robots/migrations/__init__.py b/R4C/robots/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/R4C/robots/migrations/__pycache__/0001_initial.cpython-311.pyc b/R4C/robots/migrations/__pycache__/0001_initial.cpython-311.pyc new file mode 100644 index 0000000..004db58 Binary files /dev/null and b/R4C/robots/migrations/__pycache__/0001_initial.cpython-311.pyc differ diff --git a/R4C/robots/migrations/__pycache__/0002_robot_quantity.cpython-311.pyc b/R4C/robots/migrations/__pycache__/0002_robot_quantity.cpython-311.pyc new file mode 100644 index 0000000..14546e0 Binary files /dev/null and b/R4C/robots/migrations/__pycache__/0002_robot_quantity.cpython-311.pyc differ diff --git a/R4C/robots/migrations/__pycache__/__init__.cpython-311.pyc b/R4C/robots/migrations/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..1546e07 Binary files /dev/null and b/R4C/robots/migrations/__pycache__/__init__.cpython-311.pyc differ diff --git a/R4C/robots/models.py b/R4C/robots/models.py new file mode 100644 index 0000000..651be59 --- /dev/null +++ b/R4C/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/R4C/robots/tests.py b/R4C/robots/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/R4C/robots/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/R4C/robots/urls.py b/R4C/robots/urls.py new file mode 100644 index 0000000..66df540 --- /dev/null +++ b/R4C/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/R4C/robots/views.py b/R4C/robots/views.py new file mode 100644 index 0000000..aecb981 --- /dev/null +++ b/R4C/robots/views.py @@ -0,0 +1,53 @@ +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 ['model', 'version', 'created']): + return JsonResponse({"error": "Некорректные входные данные"}, status=400) + + # Создание записи в базе данных + robot = Robot.objects.create( + model=data['model'], + version=data['version'], + created=data['created'] + ) + 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/R4C/tasks.md b/R4C/tasks.md new file mode 100644 index 0000000..8097cf8 --- /dev/null +++ b/R4C/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 diff --git a/README.md b/README.md deleted file mode 100644 index c037f11..0000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# Robots -Это заготовка для сервиса, который ведет учет произведенных роботов, а также выполняет некие операции связанные с этим процессом.