From e61cf400597212ed46a3ea91b614226d16ee942b Mon Sep 17 00:00:00 2001 From: AhmedTechno93 Date: Wed, 10 Nov 2021 00:33:28 +0300 Subject: [PATCH] Solve task --- apidemo/apidemo/__init__.py | 0 apidemo/apidemo/asgi.py | 16 +++++ apidemo/apidemo/settings.py | 125 ++++++++++++++++++++++++++++++++++++ apidemo/apidemo/urls.py | 21 ++++++ apidemo/apidemo/wsgi.py | 16 +++++ apidemo/manage.py | 22 +++++++ commerce/controllers.py | 119 +++++++++++++++++++++++++++++++--- commerce/schemas.py | 26 +++++++- config/urls.py | 3 +- 9 files changed, 336 insertions(+), 12 deletions(-) create mode 100644 apidemo/apidemo/__init__.py create mode 100644 apidemo/apidemo/asgi.py create mode 100644 apidemo/apidemo/settings.py create mode 100644 apidemo/apidemo/urls.py create mode 100644 apidemo/apidemo/wsgi.py create mode 100644 apidemo/manage.py diff --git a/apidemo/apidemo/__init__.py b/apidemo/apidemo/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/apidemo/apidemo/asgi.py b/apidemo/apidemo/asgi.py new file mode 100644 index 0000000..9146400 --- /dev/null +++ b/apidemo/apidemo/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for apidemo 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.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'apidemo.settings') + +application = get_asgi_application() diff --git a/apidemo/apidemo/settings.py b/apidemo/apidemo/settings.py new file mode 100644 index 0000000..323a0a5 --- /dev/null +++ b/apidemo/apidemo/settings.py @@ -0,0 +1,125 @@ +""" +Django settings for apidemo project. + +Generated by 'django-admin startproject' using Django 3.2.8. + +For more information on this file, see +https://docs.djangoproject.com/en/3.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/3.2/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-74t6!kljb2-eedr%($6$@)4_pdz21p+rsg^$5t#rs7d8&c104f' + +# 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', +] + +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 = 'apidemo.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 = 'apidemo.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/3.2/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/3.2/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.2/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.2/howto/static-files/ + +STATIC_URL = '/static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/apidemo/apidemo/urls.py b/apidemo/apidemo/urls.py new file mode 100644 index 0000000..a4ba4fd --- /dev/null +++ b/apidemo/apidemo/urls.py @@ -0,0 +1,21 @@ +"""apidemo URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/3.2/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 + +urlpatterns = [ + path('admin/', admin.site.urls), +] diff --git a/apidemo/apidemo/wsgi.py b/apidemo/apidemo/wsgi.py new file mode 100644 index 0000000..7e5c68e --- /dev/null +++ b/apidemo/apidemo/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for apidemo 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.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'apidemo.settings') + +application = get_wsgi_application() diff --git a/apidemo/manage.py b/apidemo/manage.py new file mode 100644 index 0000000..871903f --- /dev/null +++ b/apidemo/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'apidemo.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/commerce/controllers.py b/commerce/controllers.py index 0d8791b..099654e 100644 --- a/commerce/controllers.py +++ b/commerce/controllers.py @@ -1,19 +1,19 @@ from typing import List - +import random, string from django.contrib.auth.models import User from django.db.models import Q from django.shortcuts import get_object_or_404 from ninja import Router from pydantic import UUID4 -from commerce.models import Product, Category, City, Vendor, Item -from commerce.schemas import MessageOut, ProductOut, CitiesOut, CitySchema, VendorOut, ItemOut, ItemSchema, ItemCreate +from commerce.models import Address,Product, Category, City, Vendor, Item,Order,OrderStatus +from commerce.schemas import AddressSchema, AddressesOut, CheckoutSchema, MessageOut, ProductOut, CitiesOut, CitySchema, VendorOut, ItemOut, ItemSchema, ItemCreate products_controller = Router(tags=['products']) address_controller = Router(tags=['addresses']) vendor_controller = Router(tags=['vendors']) order_controller = Router(tags=['orders']) - +city_controller = Router(tags=['cities']) @vendor_controller.get('', response=List[VendorOut]) def list_vendors(request): @@ -109,7 +109,7 @@ def list_products( """ -@address_controller.get('') +@city_controller.get('') def list_addresses(request): pass @@ -119,7 +119,7 @@ def list_addresses(request): # return Category.objects.all() -@address_controller.get('cities', response={ +@city_controller.get('cities', response={ 200: List[CitiesOut], 404: MessageOut }) @@ -132,7 +132,7 @@ def list_cities(request): return 404, {'detail': 'No cities found'} -@address_controller.get('cities/{id}', response={ +@city_controller.get('cities/{id}', response={ 200: CitiesOut, 404: MessageOut }) @@ -140,7 +140,7 @@ def retrieve_city(request, id: UUID4): return get_object_or_404(City, id=id) -@address_controller.post('cities', response={ +@city_controller.post('cities', response={ 201: CitiesOut, 400: MessageOut }) @@ -150,7 +150,7 @@ def create_city(request, city_in: CitySchema): return 201, city -@address_controller.put('cities/{id}', response={ +@city_controller.put('cities/{id}', response={ 200: CitiesOut, 400: MessageOut }) @@ -161,7 +161,7 @@ def update_city(request, id: UUID4, city_in: CitySchema): return 200, city -@address_controller.delete('cities/{id}', response={ +@city_controller.delete('cities/{id}', response={ 204: MessageOut }) def delete_city(request, id: UUID4): @@ -220,3 +220,102 @@ def delete_item(request, id: UUID4): item.delete() return 204, {'detail': 'Item deleted!'} +def generate_ref_code(): + return ''.join(random.sample(string.ascii_letters + string.digits, 6)) +@order_controller.post('create-order', response=MessageOut) +def create_order(request): + ''' + * add items and mark (ordered) field as True + * add ref_number + * add NEW status + * calculate the total + ''' + order_qs = Order.objects.create( + user=User.objects.first(), + status=OrderStatus.objects.get(is_default=True), + ref_code=generate_ref_code(), + ordered=False, + ) + user_items = Item.objects.filter(user=User.objects.first()).filter(ordered=False) + order_qs.items.add(*user_items) + order_qs.total = order_qs.order_total + user_items.update(ordered=True) + order_qs.save() + + return {'detail': 'order created successfully'} + + + + + + +############ Adresses CRUD +@order_controller.post('/orders/item/{id}/increase-quantity', response={ + 200: MessageOut, +}) +def increase_item_quantity(request, id: UUID4): + item = get_object_or_404(Item, id=id, user=User.objects.first()) + item.item_qty += 1 + item.save() + + return 200, {'detail': 'Item quantity increased successfully!'} + + + +@address_controller.get('addresses', response={ + 200: List[AddressesOut], + 404: MessageOut +}) +def list_addresses(request): + addresses_qs = Address.objects.all() + + if addresses_qs: + return addresses_qs + + return 404, {'detail': 'No addresses found'} + + +@address_controller.get('addresses/{id}', response={ + 200: AddressesOut, + 404: MessageOut +}) +def retrieve_address(request, id: UUID4): + return get_object_or_404(Address, id=id) + + +@address_controller.post('addresses', response={ + 200: MessageOut, + 400: MessageOut +}) +def create_address(request, address_in: AddressSchema): + Address.objects.create(**address_in.dict() , user=User.objects.first()) + return 200, {'detail': 'Added successfully'} + + +@address_controller.put('addresses/{id}', response={ + 200: AddressSchema, + 400: MessageOut +}) +def update_address(request, id: UUID4, address_in: AddressSchema): + address = get_object_or_404(Address, id=id) + for key, value in address_in.items(): + setattr(address, key, value) + return 200, address + + +@address_controller.delete('addresses/{id}', response={ + 204: MessageOut +}) +def delete_address(request, id: UUID4): + address = get_object_or_404(Address, id=id) + address.delete() + return 204, {'detail': ''} + + +@order_controller.put('/api/orders/checkout/{id}', response=MessageOut) + +def checkout(request, id: UUID4, checkout_in: CheckoutSchema): + order = get_object_or_404(Order, id=id) + for key, value in checkout_in.items(): + setattr(order, key, value) + return {'detail': 'order checkout successfully'} \ No newline at end of file diff --git a/commerce/schemas.py b/commerce/schemas.py index 5b7d0d4..909a373 100644 --- a/commerce/schemas.py +++ b/commerce/schemas.py @@ -4,7 +4,7 @@ from ninja.orm import create_schema from pydantic import UUID4 -from commerce.models import Product, Merchant +from commerce.models import Address,Product, Merchant class MessageOut(Schema): @@ -90,3 +90,27 @@ class ItemCreate(Schema): class ItemOut(UUIDSchema, ItemSchema): pass + +class UserOut(UUIDSchema): + username:str + last_name:str + email:str + is_staff:str + is_active:str + + +class AddressSchema(Schema): + city_id:UUID4 + work_address:bool + address1:str + address2:str + phone:str + + +class AddressesOut(UUIDSchema , AddressSchema): + pass + + +class CheckoutSchema(Schema): + note: str = None + address: UUID4 \ No newline at end of file diff --git a/config/urls.py b/config/urls.py index fea5e70..c717323 100644 --- a/config/urls.py +++ b/config/urls.py @@ -18,13 +18,14 @@ from django.urls import path from ninja import NinjaAPI -from commerce.controllers import products_controller, address_controller, vendor_controller, order_controller +from commerce.controllers import products_controller, address_controller, vendor_controller, order_controller,city_controller from config import settings api = NinjaAPI() api.add_router('products', products_controller) api.add_router('addresses', address_controller) +api.add_router('cities', city_controller) api.add_router('vendors', vendor_controller) api.add_router('orders', order_controller)