commit 8e3dfd89b15b7666ca0db365a734dcf02902849c Author: Timofey Date: Thu May 15 18:26:23 2025 +0300 initiate drf app diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..481bfa5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,92 @@ +# Node modules +node_modules/ + +# Environment variables +.env +.env*.local +.env.production +*.env +.env.* + +# Debugging and logs +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Next.js build output +.next/ +out/ + +# Production build +/build + +# Coverage reports +coverage/ + +# Dependency management +.pnp/ +.pnp.js +yarn.lock + +# Local configuration +.vscode/ +.vercel/ +.idea/ +*.sublime-project +*.sublime-workspace + +# TypeScript build info +*.tsbuildinfo +next-env.d.ts + +# Misc +.DS_Store +Thumbs.db +*.pem + +# Byte-compiled Python files +__pycache__/ +*.py[cod] +*$py.class + +# Виртуальные окружения +venv/ +env/ +ENV/ +.venv +bin/ +local/ +.include/ +*.egg +*.egg-info/ +.eggs/ + +# Секретные ключи и конфигурации +*.env + +# Системные файлы +.DS_Store +Thumbs.db + +# Базы данных SQLite +db.sqlite3 +database + +# Static and media files +staticfiles/ +media/ + +# Миграции +*/migrations/*.pyc +*/migrations/*.py~ + +# Компиляция файлов +*.mo +*.pot + +# Docker файлы +*.pid +*.dockerignore +docker-compose.override.yml + +.DS_Store \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..761dbde --- /dev/null +++ b/README.md @@ -0,0 +1,97 @@ +# Trip with Benefits + +Это репозиторий сайта tripwb. Этот проект включает в себя фронтенд на Next.js и бэкенд на Django.py с базой данных PostgreSQL. + +## Описание + +Сайт приложения tripwb является аггрегатором для поиска и перевозки посылок + +## Технологии + +### Фронтенд + +- **Next.js** - библиотека для создания пользовательских интерфейсов. + +### Бэкенд + +- **Django.py** - веб-фреймворк для Python. +- **PostgreSQL** - реляционная база данных для хранения данных. + +## Установка + +### Предварительные требования + +Для запуска проекта вам потребуются: + +- Node.js (рекомендуется версия 20.x или выше) +- PostgreSQL (рекомендуется версия 12.x или выше) + +### Шаги для установки + +1. **Клонирование репозитория:** + + ```sh + git clone https://gitea.a3-global.com/sysadminix/tripwithbonus.git + cd tripwb + ``` + +2. **Установка зависимостей для фронтенда и бэкенда:** + + ```sh + cd frontend + npm install + + cd backend + pipenv shell + pipenv install + ``` + +3. **Настройка базы данных:** + + Создайте базу данных PostgreSQL и выполните миграции: + + ```sh + createdb tripwbDB + # Выполните миграции, если они имеются. В проекте откройте директорию backend + cd backend + python manage.py makemigrations + python manage.py migrate + ``` + +4. **Настройка переменных окружения:** + + Создайте файл `.env` в корневой директории и добавьте необходимые переменные окружения: + + ```env + # telegram data + BOT_TOKEN + CHAT_ID + + # database connection + + DB_USER + DB_HOST + DB_NAME + DB_PASSWORD + DB_PORT = 5432 + ``` + +5. **Локальная разработка:** + + Откройте два терминала или используйте вкладки в одном терминале. + + В первом терминале запустите бэкенд: + + ``` + cd backend + python manage.py runserver + ``` + + Во втором терминале запустите фронтенд: + + ``` + cd frontend + npm run dev + ``` + +Теперь проект будет доступен по адресу `http://localhost:3000`. diff --git a/backend/Pipfile b/backend/Pipfile new file mode 100644 index 0000000..1353773 --- /dev/null +++ b/backend/Pipfile @@ -0,0 +1,15 @@ +[[source]] +url = "https://pypi.org/simple" +verify_ssl = true +name = "pypi" + +[packages] +django = "*" +djangorestframework = "*" +python-dotenv = "*" +psycopg2 = "*" + +[dev-packages] + +[requires] +python_version = "3.12" diff --git a/backend/Pipfile.lock b/backend/Pipfile.lock new file mode 100644 index 0000000..2bb3134 --- /dev/null +++ b/backend/Pipfile.lock @@ -0,0 +1,81 @@ +{ + "_meta": { + "hash": { + "sha256": "b373803326406c6ad8118054bb515b95be11d1fba2e9252d0914839e5c6ed309" + }, + "pipfile-spec": 6, + "requires": { + "python_version": "3.12" + }, + "sources": [ + { + "name": "pypi", + "url": "https://pypi.org/simple", + "verify_ssl": true + } + ] + }, + "default": { + "asgiref": { + "hashes": [ + "sha256:3e1e3ecc849832fe52ccf2cb6686b7a55f82bb1d6aee72a58826471390335e47", + "sha256:c343bd80a0bec947a9860adb4c432ffa7db769836c64238fc34bdc3fec84d590" + ], + "markers": "python_version >= '3.8'", + "version": "==3.8.1" + }, + "django": { + "hashes": [ + "sha256:57fe1f1b59462caed092c80b3dd324fd92161b620d59a9ba9181c34746c97284", + "sha256:a9b680e84f9a0e71da83e399f1e922e1ab37b2173ced046b541c72e1589a5961" + ], + "index": "pypi", + "markers": "python_version >= '3.10'", + "version": "==5.2.1" + }, + "djangorestframework": { + "hashes": [ + "sha256:bea7e9f6b96a8584c5224bfb2e4348dfb3f8b5e34edbecb98da258e892089361", + "sha256:f022ff46613584de994c0c6a4aebbace5fd700555fbe9d33b865ebf173eba6c9" + ], + "index": "pypi", + "markers": "python_version >= '3.9'", + "version": "==3.16.0" + }, + "psycopg2": { + "hashes": [ + "sha256:0435034157049f6846e95103bd8f5a668788dd913a7c30162ca9503fdf542cb4", + "sha256:12ec0b40b0273f95296233e8750441339298e6a572f7039da5b260e3c8b60e11", + "sha256:47c4f9875125344f4c2b870e41b6aad585901318068acd01de93f3677a6522c2", + "sha256:4a579d6243da40a7b3182e0430493dbd55950c493d8c68f4eec0b302f6bbf20e", + "sha256:5df2b672140f95adb453af93a7d669d7a7bf0a56bcd26f1502329166f4a61716", + "sha256:65a63d7ab0e067e2cdb3cf266de39663203d38d6a8ed97f5ca0cb315c73fe067", + "sha256:88138c8dedcbfa96408023ea2b0c369eda40fe5d75002c0964c78f46f11fa442", + "sha256:91fd603a2155da8d0cfcdbf8ab24a2d54bca72795b90d2a3ed2b6da8d979dee2", + "sha256:9d5b3b94b79a844a986d029eee38998232451119ad653aea42bb9220a8c5066b", + "sha256:c6f7b8561225f9e711a9c47087388a97fdc948211c10a4bccbf0ba68ab7b3b5a" + ], + "index": "pypi", + "markers": "python_version >= '3.8'", + "version": "==2.9.10" + }, + "python-dotenv": { + "hashes": [ + "sha256:41f90bc6f5f177fb41f53e87666db362025010eb28f60a01c9143bfa33a2b2d5", + "sha256:d7c01d9e2293916c18baf562d95698754b0dbbb5e74d457c45d4f6561fb9d55d" + ], + "index": "pypi", + "markers": "python_version >= '3.9'", + "version": "==1.1.0" + }, + "sqlparse": { + "hashes": [ + "sha256:09f67787f56a0b16ecdbde1bfc7f5d9c3371ca683cfeaa8e6ff60b4807ec9272", + "sha256:cf2196ed3418f3ba5de6af7e82c694a9fbdbfecccdfc72e281548517081f16ca" + ], + "markers": "python_version >= '3.8'", + "version": "==0.5.3" + } + }, + "develop": {} +} diff --git a/backend/api/__init__.py b/backend/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/api/admin.py b/backend/api/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/backend/api/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/backend/api/apps.py b/backend/api/apps.py new file mode 100644 index 0000000..66656fd --- /dev/null +++ b/backend/api/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class ApiConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'api' diff --git a/backend/api/main/__init__.py b/backend/api/main/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/api/main/serializers.py b/backend/api/main/serializers.py new file mode 100644 index 0000000..560720e --- /dev/null +++ b/backend/api/main/serializers.py @@ -0,0 +1,9 @@ +from rest_framework import serializers + +from mainpage.models import FAQ + +class FAQMainSerializer(serializers.ModelSerializer): + class Meta: + model = FAQ + fields = "__all__" + \ No newline at end of file diff --git a/backend/api/main/views.py b/backend/api/main/views.py new file mode 100644 index 0000000..7b2cf38 --- /dev/null +++ b/backend/api/main/views.py @@ -0,0 +1,19 @@ +from rest_framework import status +from rest_framework.views import APIView +from rest_framework.response import Response +from api.utils.decorators import handle_exceptions + +from api.main.serializers import FAQMainSerializer +from mainpage.models import FAQ + +class FAQView(APIView): + @handle_exceptions + def get(self, request): + + faqs = FAQ.objects.all() + + data = { + 'faqs': FAQMainSerializer(faqs, many=True).data + } + + return Response(data, status=status.HTTP_200_OK) \ No newline at end of file diff --git a/backend/api/migrations/__init__.py b/backend/api/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/api/models.py b/backend/api/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/backend/api/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/backend/api/tests.py b/backend/api/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/backend/api/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/backend/api/urls.py b/backend/api/urls.py new file mode 100644 index 0000000..a19a301 --- /dev/null +++ b/backend/api/urls.py @@ -0,0 +1,7 @@ +from django.urls import path + +from api.main.views import FAQView + +urlpatterns = [ + path("v1/faq/", FAQView.as_view(), name='faqMain'), +] \ No newline at end of file diff --git a/backend/api/utils/decorators.py b/backend/api/utils/decorators.py new file mode 100644 index 0000000..367b7fa --- /dev/null +++ b/backend/api/utils/decorators.py @@ -0,0 +1,56 @@ +from functools import wraps +from rest_framework.response import Response +from rest_framework import status +from django.core.exceptions import ValidationError, PermissionDenied +from django.http import Http404 +from rest_framework.exceptions import APIException + +def handle_exceptions(func): + """ + Обработчик ошибок для API endpoints + Обрабатывает различные типы исключений и возвращает соответствующие HTTP статусы + Текущие обрабоки: + - Ошибки валидации - HTTP400 + - Объект не найден - HTTP404 + - Ошибки доступа - HTTP403 + - Обработки DRF исключений - вернется статус код от DRF + - Необработанные исключения - HTTP500 + """ + @wraps(func) + def wrapper(*args, **kwargs): + try: + return func(*args, **kwargs) + except ValidationError as e: + # ошибки валидации + return Response( + {"error": e.messages if hasattr(e, 'messages') else str(e)}, + status=status.HTTP_400_BAD_REQUEST + ) + except Http404 as e: + # объект не найден + return Response( + {"error": str(e) or "Запрашиваемый ресурс не найден"}, + status=status.HTTP_404_NOT_FOUND + ) + except PermissionDenied as e: + # ошибки доступа + return Response( + {"error": str(e) or "У вас нет прав для выполнения этого действия"}, + status=status.HTTP_403_FORBIDDEN + ) + except APIException as e: + # обработка DRF исключений + return Response( + {"error": str(e)}, + status=e.status_code + ) + except Exception as e: + # необработанные исключения + return Response( + { + "error": "Произошла внутренняя ошибка сервера", + "detail": str(e) + }, + status=status.HTTP_500_INTERNAL_SERVER_ERROR + ) + return wrapper diff --git a/backend/base/__init__.py b/backend/base/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/base/asgi.py b/backend/base/asgi.py new file mode 100644 index 0000000..71a4cef --- /dev/null +++ b/backend/base/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for base 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/5.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings') + +application = get_asgi_application() diff --git a/backend/base/settings.py b/backend/base/settings.py new file mode 100644 index 0000000..6b3ed4e --- /dev/null +++ b/backend/base/settings.py @@ -0,0 +1,114 @@ +import os +from pathlib import Path +from dotenv import load_dotenv + +BASE_DIR = Path(__file__).resolve().parent.parent +load_dotenv(dotenv_path=BASE_DIR / './.env') + + +SECRET_KEY = os.environ.get("SECRET_KEY") +DEBUG = os.environ.get("DEBUG_MODE") + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'api.apps.ApiConfig', + 'routes.apps.RoutesConfig', + 'mainpage.apps.MainpageConfig', + 'rest_framework', +] + +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 = 'base.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'base.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/5.2/ref/settings/#databases + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.postgresql", + "NAME": os.environ.get("DB_NAME"), + "USER": os.environ.get("DB_USER"), + "PASSWORD": os.environ.get("DB_PASSWORD"), + "HOST": os.environ.get("DB_HOST"), + "PORT": os.environ.get("DB_PORT"), + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.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/5.2/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/5.2/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/backend/base/urls.py b/backend/base/urls.py new file mode 100644 index 0000000..ab9a035 --- /dev/null +++ b/backend/base/urls.py @@ -0,0 +1,23 @@ +""" +URL configuration for base project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/5.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, include + +urlpatterns = [ + path('admin/', admin.site.urls), + path('api/', include('api.urls')), +] diff --git a/backend/base/wsgi.py b/backend/base/wsgi.py new file mode 100644 index 0000000..70ae90a --- /dev/null +++ b/backend/base/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for base 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/5.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings') + +application = get_wsgi_application() diff --git a/backend/mainpage/__init__.py b/backend/mainpage/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/mainpage/admin.py b/backend/mainpage/admin.py new file mode 100644 index 0000000..fa06e5c --- /dev/null +++ b/backend/mainpage/admin.py @@ -0,0 +1,4 @@ +from django.contrib import admin +from .models import FAQ + +admin.site.register(FAQ) diff --git a/backend/mainpage/apps.py b/backend/mainpage/apps.py new file mode 100644 index 0000000..2eb9b04 --- /dev/null +++ b/backend/mainpage/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class MainpageConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'mainpage' diff --git a/backend/mainpage/migrations/0001_initial.py b/backend/mainpage/migrations/0001_initial.py new file mode 100644 index 0000000..7816116 --- /dev/null +++ b/backend/mainpage/migrations/0001_initial.py @@ -0,0 +1,26 @@ +# Generated by Django 5.2.1 on 2025-05-15 14:16 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='FAQ', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=250)), + ('content', models.CharField(max_length=800)), + ], + options={ + 'verbose_name': 'FAQ', + 'verbose_name_plural': 'FAQs', + }, + ), + ] diff --git a/backend/mainpage/migrations/__init__.py b/backend/mainpage/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/mainpage/models.py b/backend/mainpage/models.py new file mode 100644 index 0000000..572d185 --- /dev/null +++ b/backend/mainpage/models.py @@ -0,0 +1,14 @@ +from django.db import models + +class FAQ (models.Model): + title = models.CharField(max_length=250) + content = models.CharField(max_length=800) + + class Meta: + verbose_name = 'FAQ' + verbose_name_plural = 'FAQs' + ordering = ['id'] + + def __str__(self): + return self.title + diff --git a/backend/mainpage/tests.py b/backend/mainpage/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/backend/mainpage/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/backend/manage.py b/backend/manage.py new file mode 100755 index 0000000..cd0be93 --- /dev/null +++ b/backend/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', 'base.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/backend/routes/__init__.py b/backend/routes/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/routes/admin.py b/backend/routes/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/backend/routes/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/backend/routes/apps.py b/backend/routes/apps.py new file mode 100644 index 0000000..c787c8e --- /dev/null +++ b/backend/routes/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class RoutesConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'routes' diff --git a/backend/routes/constants/routeChoices.py b/backend/routes/constants/routeChoices.py new file mode 100644 index 0000000..67f3312 --- /dev/null +++ b/backend/routes/constants/routeChoices.py @@ -0,0 +1,24 @@ +type_transport_choices = [ + ("road", "Авто"), + ("avia", "Авиа"), + ('both', "Любой"), +] + +transfer_location_choices = [ + ("airport", "В аэропорту"), + ("city", "По городу"), + ("other", "По договоренности") +] + +cargo_type_choices = [ + ("letter", "Письмо или Документы"), + ("package", "Посылка (до 30кг)"), + ("passenger", "Попутчик"), + ("parcel", "Бандероль (до 5кг)"), + ("cargo", "Груз (свыше 30 кг)"), +] + +owner_type_choices = [ + ("customer", "Заказчик"), + ("mover", "Перевозчик") +] \ No newline at end of file diff --git a/backend/routes/migrations/__init__.py b/backend/routes/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/backend/routes/models.py b/backend/routes/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/backend/routes/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/backend/routes/tests.py b/backend/routes/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/backend/routes/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/backend/routes/views.py b/backend/routes/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/backend/routes/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..10cf6aa --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,127 @@ +name: tripwb + +networks: + tripwb: + name: tripwb + driver: bridge + +services: + caddy: + image: caddy:alpine + container_name: tripwb-caddy-server + depends_on: + tripwb-backend-app: + condition: service_healthy + ports: + - 80:80 + - 443:443 + volumes: + - caddy-config:/config + - caddy-data:/data + - ./Caddyfile:/etc/caddy/Caddyfile:ro + networks: + - tripwb + + tripwb-frontend-app: + build: + context: frontend/ + # image: tripwb-frontend + container_name: tripwb-frontend-app + environment: + NEXT_PUBLIC_API_URL: ${NEXT_PUBLIC_API_URL} + NEXTAUTH_URL: ${NEXTAUTH_URL} + BACKEND_URL: ${BACKEND_URL} + env_file: + - .env + depends_on: + postgres: + condition: service_healthy + tripwb-backend-app: + condition: service_healthy + caddy: + condition: service_started + # ports: + # - 9000:3000 + networks: + - tripwb + tripwb-backend-app: + build: + context: backend/ + # image:tripwb-backend + container_name: tripwb-backend-app + environment: + SECRET_KEY: ${SECRET_KEY} + DEBUG_MODE: ${DEBUG_MODE} + API_KEY: ${API_KEY} + DB_USER: ${DB_USER} + DB_HOST: ${DB_HOST} + DB_NAME: ${DB_NAME} + DB_PASSWORD: ${DB_PASSWORD} + DB_PORT: ${DB_PORT} + healthcheck: + test: ['CMD', 'curl', '-s', '-o', '-f', 'http://tripwb-backend-app:8000'] + # interval: 5s + timeout: 5s + retries: 5 + env_file: + - .env + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + volumes: + - tripwb-backend-app-uploads:/root/tripwb/uploads + # ports: + # - 8000:8000 + networks: + - tripwb + + # pgadmin-app: + # image: dpage/pgadmin4 + # container_name: pgadmin-app + # environment: + # DB_PORT: ${DB_PORT} + # DB_HOST: ${DB_HOST} + # DB_NAME: ${DB_NAME} + # DB_PASSWORD: ${DB_PASSWORD} + # DB_USER: ${DB_USER} + # BOT_TOKEN: ${BOT_TOKEN} + # CHAT_ID: ${BOT_TOKEN} + # JWT_SECRET: ${BOT_TOKEN} + # NEXT_PUBLIC_API_URL: ${NEXT_PUBLIC_API_URL} + # PGADMIN_DEFAULT_EMAIL: timofey.syr17@gmail.com + # PGADMIN_DEFAULT_PASSWORD: passWoRd + # depends_on: + # postgres: + # condition: service_healthy + # ports: + # - 81:80 + # networks: + # - tripwb + postgres: + image: postgres:alpine + restart: always + container_name: tripwb-db + env_file: backend/.env + environment: + POSTGRES_USER: ${DB_USER} + POSTGRES_DB: ${DB_NAME} + POSTGRES_PASSWORD: ${DB_PASSWORD} + healthcheck: + test: [CMD-SHELL, "sh -c 'pg_isready -U ${DB_USER} -d ${DB_NAME}'"] + interval: 10s + timeout: 5s + retries: 5 + # ports: + # - 5432:5432 + volumes: + - pg-data:/var/lib/postgresql/data + networks: + - tripwb + +volumes: + pg-data: + caddy-config: + caddy-data: + tripwb-backend-app-uploads: diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..5ef6a52 --- /dev/null +++ b/frontend/.gitignore @@ -0,0 +1,41 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/versions + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# env files (can opt-in for committing if needed) +.env* + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts diff --git a/frontend/README.md b/frontend/README.md new file mode 100644 index 0000000..e215bc4 --- /dev/null +++ b/frontend/README.md @@ -0,0 +1,36 @@ +This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). + +## Getting Started + +First, run the development server: + +```bash +npm run dev +# or +yarn dev +# or +pnpm dev +# or +bun dev +``` + +Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. + +You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. + +This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. + +## Learn More + +To learn more about Next.js, take a look at the following resources: + +- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. +- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. + +You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! + +## Deploy on Vercel + +The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. + +Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. diff --git a/frontend/app/(urls)/search/components/SearchCard.tsx b/frontend/app/(urls)/search/components/SearchCard.tsx new file mode 100644 index 0000000..8a4a211 --- /dev/null +++ b/frontend/app/(urls)/search/components/SearchCard.tsx @@ -0,0 +1,308 @@ +import React from 'react' +import Image, { StaticImageData } from 'next/image' +import Button from '@/components/ui/Button' +import { SearchCardProps } from '@/app/types/index' + +const SearchCard = ({ + id, + username, + userImg, + start_point, + country_from, + country_from_icon, + country_from_code, + end_point, + country_to, + country_to_icon, + country_to_code, + cargo_type, + user_request, + user_comment, + moving_type, + estimated_date, + day_out, + day_in, +}: SearchCardProps) => { + const getUserRequestStyles = () => { + if (user_request === 'Нужен перевозчик') { + return 'text-[#065bff]' + } + return 'text-[#45c226]' + } + + const setMovingTypeIcon = () => { + if (moving_type === 'Авиатранспорт') { + return '/images/airplane.png' + } + return '/images/car.png' + } + + return ( + <> + {/* десктоп */} +
+
+
+
+
+ {username} +
+
+
{username}
+
|
+
+ {user_request} +
+
+ Тип посылки:{' '} + + {cargo_type} + +
+
+
+
+ +
+
+ {user_comment} +
+
+
+ Объявление № {id} +
+ +
+
+ {user_request === 'Нужен перевозчик' ? ( + Забрать из: + ) : ( + Выезжаю из: + )} +
+
+ {country_from_code} + + {country_from_code} + + + {start_point} / {country_from} + +
+ {user_request === 'Могу перевезти' && ( +
+ Отправление:{' '} + + {day_out?.toLocaleDateString()} + +
+ )} +
+
+ +
+
+ {moving_type} + route vector +
+
+ route vector +
+
+
+ + {user_request === 'Нужен перевозчик' && ( +
+ Дата доставки:{' '} + + {estimated_date.toLocaleDateString()} + +
+ )} +
+ +
+ {user_request === 'Нужен перевозчик' ? ( +
Доставить в:
+ ) : ( +
Прибываю в:
+ )} + +
+
+ {country_to_code} + + {country_to_code} + + + {end_point} / {country_to} + +
+ {user_request === 'Могу перевезти' && ( +
+ Прибытие:{' '} + + {day_in?.toLocaleDateString()} + +
+ )} +
+
+
+
+
+ + {/* мобилка */} +
+
+
+
+ {user_request} +
+
+ Тип посылки: {cargo_type} +
+
+
+
+ {username} +
+
+ {user_comment} +
+
+
+ Объявление № {id} +
+ + {user_request === 'Нужен перевозчик' ? ( + Забрать из: + ) : ( + Выезжаю из: + )} +
+
+
+ route vector +
+
+
+
+
+
+ {country_from_code} + + {country_from_code} + + + {start_point} / {country_from} + +
+ +
+
+ {moving_type} + route vector +
+
+
+ Дата доставки: {estimated_date.toLocaleDateString()} +
+
+ +
+ {user_request === 'Нужен перевозчик' ? ( +
Доставить в:
+ ) : ( +
Прибываю в:
+ )} + +
+ {country_to_code} + + {country_to_code} + + + {end_point} / {country_to} + +
+
+
+
+ {user_request === 'Могу перевезти' && ( +
+ Прибытие:{' '} + + {day_in?.toLocaleDateString()} + +
+ )} +
+
+ + ) +} + +export default SearchCard diff --git a/frontend/app/(urls)/search/page.tsx b/frontend/app/(urls)/search/page.tsx new file mode 100644 index 0000000..d357f65 --- /dev/null +++ b/frontend/app/(urls)/search/page.tsx @@ -0,0 +1,7 @@ +import React from 'react' + +const SearchPage = () => { + return
SearchPage
+} + +export default SearchPage diff --git a/frontend/app/favicon.ico b/frontend/app/favicon.ico new file mode 100644 index 0000000..718d6fe Binary files /dev/null and b/frontend/app/favicon.ico differ diff --git a/frontend/app/globals.css b/frontend/app/globals.css new file mode 100644 index 0000000..ac84c05 --- /dev/null +++ b/frontend/app/globals.css @@ -0,0 +1,27 @@ +@import 'tailwindcss'; + +:root { + --background: #eeebeb; + --foreground: #171717; +} + +@theme inline { + --color-background: var(--background); + --color-foreground: var(--foreground); + --font-sans: var(--font-geist-sans); + --font-mono: var(--font-geist-mono); + --color-orange: #ff613a; +} + +@media (prefers-color-scheme: light) { + :root { + --background: #eeebeb; + --foreground: #171717; + } +} + +body { + background: var(--background); + color: var(--foreground); + font-family: Arial, Helvetica, sans-serif; +} diff --git a/frontend/app/layout.tsx b/frontend/app/layout.tsx new file mode 100644 index 0000000..bbeb998 --- /dev/null +++ b/frontend/app/layout.tsx @@ -0,0 +1,37 @@ +import type { Metadata } from 'next' +import { Geist, Geist_Mono } from 'next/font/google' +import './globals.css' +import Header from '@/components/Header' +import Footer from '@/components/Footer' + +const geistSans = Geist({ + variable: '--font-geist-sans', + subsets: ['latin'], +}) + +const geistMono = Geist_Mono({ + variable: '--font-geist-mono', + subsets: ['latin'], +}) + +export const metadata: Metadata = { + title: 'Отправка посылок в любую точку мира | TripWB', + description: + 'Международная отправка посылок ✓ Отправка посылки в любую точку планеты ✓ Приемлемая цена отправки посылки ✓ Доставка в кратчайшие сроки ➡️ Обращайтесь к нам', +} + +export default function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode +}>) { + return ( + + +
+
{children}
+