Initial Commit
This commit is contained in:
175
.gitignore
vendored
Normal file
175
.gitignore
vendored
Normal file
@@ -0,0 +1,175 @@
|
||||
# ---> Python
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
#uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
||||
.pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
149
alembic.ini
Normal file
149
alembic.ini
Normal file
@@ -0,0 +1,149 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts.
|
||||
# this is typically a path given in POSIX (e.g. forward slashes)
|
||||
# format, relative to the token %(here)s which refers to the location of this
|
||||
# ini file
|
||||
script_location = %(here)s/alembic
|
||||
|
||||
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||
# Uncomment the line below if you want the files to be prepended with date and time
|
||||
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||
# for all available tokens
|
||||
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
|
||||
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory. for multiple paths, the path separator
|
||||
# is defined by "path_separator" below.
|
||||
prepend_sys_path = .
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the tzdata library which can be installed by adding
|
||||
# `alembic[tz]` to the pip requirements.
|
||||
# string value is passed to ZoneInfo()
|
||||
# leave blank for localtime
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; This defaults
|
||||
# to <script_location>/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path.
|
||||
# The path separator used here should be the separator specified by "path_separator"
|
||||
# below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
|
||||
|
||||
# path_separator; This indicates what character is used to split lists of file
|
||||
# paths, including version_locations and prepend_sys_path within configparser
|
||||
# files such as alembic.ini.
|
||||
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
|
||||
# to provide os-dependent path splitting.
|
||||
#
|
||||
# Note that in order to support legacy alembic.ini files, this default does NOT
|
||||
# take place if path_separator is not present in alembic.ini. If this
|
||||
# option is omitted entirely, fallback logic is as follows:
|
||||
#
|
||||
# 1. Parsing of the version_locations option falls back to using the legacy
|
||||
# "version_path_separator" key, which if absent then falls back to the legacy
|
||||
# behavior of splitting on spaces and/or commas.
|
||||
# 2. Parsing of the prepend_sys_path option falls back to the legacy
|
||||
# behavior of splitting on spaces, commas, or colons.
|
||||
#
|
||||
# Valid values for path_separator are:
|
||||
#
|
||||
# path_separator = :
|
||||
# path_separator = ;
|
||||
# path_separator = space
|
||||
# path_separator = newline
|
||||
#
|
||||
# Use os.pathsep. Default configuration used for new projects.
|
||||
path_separator = os
|
||||
|
||||
|
||||
# set to 'true' to search source files recursively
|
||||
# in each "version_locations" directory
|
||||
# new in Alembic version 1.10
|
||||
# recursive_version_locations = false
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
# database URL. This is consumed by the user-maintained env.py script only.
|
||||
# other means of configuring database URLs may be customized within the env.py
|
||||
# file.
|
||||
sqlalchemy.url = postgresql+asyncpg://postgres:HEXDEVFUCKINGSUCKS!@localhost:5432/postgres
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
|
||||
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||
# hooks = black
|
||||
# black.type = console_scripts
|
||||
# black.entrypoint = black
|
||||
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
|
||||
# hooks = ruff
|
||||
# ruff.type = module
|
||||
# ruff.module = ruff
|
||||
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Alternatively, use the exec runner to execute a binary found on your PATH
|
||||
# hooks = ruff
|
||||
# ruff.type = exec
|
||||
# ruff.executable = ruff
|
||||
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Logging configuration. This is also consumed by the user-maintained
|
||||
# env.py script only.
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARNING
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARNING
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
1
alembic/README
Normal file
1
alembic/README
Normal file
@@ -0,0 +1 @@
|
||||
Generic single-database configuration with an async dbapi.
|
||||
92
alembic/env.py
Normal file
92
alembic/env.py
Normal file
@@ -0,0 +1,92 @@
|
||||
import asyncio
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import pool
|
||||
from sqlalchemy.engine import Connection
|
||||
from sqlalchemy.ext.asyncio import async_engine_from_config
|
||||
|
||||
from alembic import context
|
||||
|
||||
from db.base import Base
|
||||
from db.models import * # noqa: F403
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
target_metadata = Base.metadata
|
||||
|
||||
# other values from the config, defined by the needs of env.py,
|
||||
# can be acquired:
|
||||
# my_important_option = config.get_main_option("my_important_option")
|
||||
# ... etc.
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def do_run_migrations(connection: Connection) -> None:
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
async def run_async_migrations() -> None:
|
||||
"""In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
|
||||
connectable = async_engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
async with connectable.connect() as connection:
|
||||
await connection.run_sync(do_run_migrations)
|
||||
|
||||
await connectable.dispose()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode."""
|
||||
|
||||
asyncio.run(run_async_migrations())
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
28
alembic/script.py.mako
Normal file
28
alembic/script.py.mako
Normal file
@@ -0,0 +1,28 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
${downgrades if downgrades else "pass"}
|
||||
101
alembic/versions/ad794cb94d9c_initial_migration.py
Normal file
101
alembic/versions/ad794cb94d9c_initial_migration.py
Normal file
@@ -0,0 +1,101 @@
|
||||
"""Initial Migration
|
||||
|
||||
Revision ID: ad794cb94d9c
|
||||
Revises:
|
||||
Create Date: 2026-01-30 21:38:15.534474
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "ad794cb94d9c"
|
||||
down_revision: Union[str, Sequence[str], None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table(
|
||||
"categories",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("name", sa.Text(), nullable=True),
|
||||
sa.Column("parent_id", sa.Integer(), nullable=True),
|
||||
sa.ForeignKeyConstraint(
|
||||
["parent_id"],
|
||||
["categories.id"],
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_table(
|
||||
"orders",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("customer", sa.BigInteger(), nullable=True),
|
||||
sa.Column(
|
||||
"status",
|
||||
postgresql.ENUM(
|
||||
"CREATED",
|
||||
"PAID",
|
||||
"IN_PROGRESS",
|
||||
"CANCELLED",
|
||||
"DRAFT",
|
||||
name="order_status",
|
||||
),
|
||||
nullable=False,
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_table(
|
||||
"products",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("category_id", sa.Integer(), nullable=True),
|
||||
sa.Column("name", sa.Text(), nullable=True),
|
||||
sa.Column("description", sa.Text(), nullable=True),
|
||||
sa.Column("search_vector", postgresql.TSVECTOR(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["category_id"],
|
||||
["categories.id"],
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
op.create_index(
|
||||
"idx_products_search",
|
||||
"products",
|
||||
["search_vector"],
|
||||
unique=False,
|
||||
postgresql_using="gin",
|
||||
)
|
||||
op.create_table(
|
||||
"order_items",
|
||||
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
|
||||
sa.Column("order_id", sa.Integer(), nullable=False),
|
||||
sa.Column("product_id", sa.Integer(), nullable=False),
|
||||
sa.Column("quantity", sa.Integer(), nullable=False),
|
||||
sa.ForeignKeyConstraint(
|
||||
["order_id"],
|
||||
["orders.id"],
|
||||
),
|
||||
sa.ForeignKeyConstraint(
|
||||
["product_id"],
|
||||
["products.id"],
|
||||
),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table("order_items")
|
||||
op.drop_index("idx_products_search", table_name="products", postgresql_using="gin")
|
||||
op.drop_table("products")
|
||||
op.drop_table("orders")
|
||||
op.drop_table("categories")
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Product search vector update trigger addition
|
||||
|
||||
Revision ID: af58496e0468
|
||||
Revises: ad794cb94d9c
|
||||
Create Date: 2026-01-30 21:39:39.839562
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "af58496e0468"
|
||||
down_revision: Union[str, Sequence[str], None] = "ad794cb94d9c"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
op.execute("""
|
||||
CREATE TRIGGER products_search_vector_update
|
||||
BEFORE INSERT OR UPDATE
|
||||
ON products
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION
|
||||
tsvector_update_trigger(
|
||||
search_vector,
|
||||
'pg_catalog.simple',
|
||||
name,
|
||||
description
|
||||
);
|
||||
""")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
op.execute("DROP TRIGGER IF EXISTS products_search_vector_update ON products;")
|
||||
12
config.py
Normal file
12
config.py
Normal file
@@ -0,0 +1,12 @@
|
||||
import os
|
||||
import logging
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(override=True)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
BOT_TOKEN = os.getenv("BOT_TOKEN", "")
|
||||
|
||||
POSTGRES_URL = os.getenv(
|
||||
"POSTGRES_URL", "postgresql+asyncpg://postgres:postgres@localhost:5432/postgres"
|
||||
)
|
||||
0
db/__init__.py
Normal file
0
db/__init__.py
Normal file
12
db/base.py
Normal file
12
db/base.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from config import POSTGRES_URL
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
engine = create_async_engine(POSTGRES_URL, echo=True)
|
||||
async_session = async_sessionmaker(engine, expire_on_commit=False)
|
||||
4
db/models/__init__.py
Normal file
4
db/models/__init__.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from .orders import Order, OrderItem, OrderStatus
|
||||
from .products import Product, Category
|
||||
|
||||
__all__ = ["Order", "OrderItem", "OrderStatus", "Product", "Category"]
|
||||
35
db/models/orders.py
Normal file
35
db/models/orders.py
Normal file
@@ -0,0 +1,35 @@
|
||||
import enum
|
||||
from typing import List, Optional
|
||||
from sqlalchemy import ForeignKey, BigInteger
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from sqlalchemy.dialects.postgresql import ENUM
|
||||
from db.base import Base
|
||||
|
||||
|
||||
class OrderStatus(enum.Enum):
|
||||
CREATED = "CREATED"
|
||||
PAID = "PAID"
|
||||
IN_PROGRESS = "IN_PROGRESS"
|
||||
CANCELLED = "CANCELLED"
|
||||
DRAFT = "DRAFT"
|
||||
|
||||
|
||||
class Order(Base):
|
||||
__tablename__ = "orders"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
customer: Mapped[Optional[int]] = mapped_column(BigInteger)
|
||||
status: Mapped[OrderStatus] = mapped_column(ENUM(OrderStatus, name="order_status"))
|
||||
|
||||
items: Mapped[List["OrderItem"]] = relationship("OrderItem", back_populates="order")
|
||||
|
||||
|
||||
class OrderItem(Base):
|
||||
__tablename__ = "order_items"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
order_id: Mapped[int] = mapped_column(ForeignKey("orders.id"))
|
||||
product_id: Mapped[int] = mapped_column(ForeignKey("products.id"))
|
||||
quantity: Mapped[int] = mapped_column(default=1)
|
||||
|
||||
order: Mapped["Order"] = relationship("Order", back_populates="items")
|
||||
30
db/models/products.py
Normal file
30
db/models/products.py
Normal file
@@ -0,0 +1,30 @@
|
||||
from typing import Optional
|
||||
from sqlalchemy import ForeignKey, Text, Index
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from sqlalchemy.dialects.postgresql import TSVECTOR
|
||||
from db.base import Base
|
||||
|
||||
|
||||
class Category(Base):
|
||||
__tablename__ = "categories"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
name: Mapped[Optional[str]] = mapped_column(Text)
|
||||
parent_id: Mapped[Optional[int]] = mapped_column(ForeignKey("categories.id"))
|
||||
|
||||
parent: Mapped["Category"] = relationship("Category", remote_side=[id])
|
||||
|
||||
|
||||
class Product(Base):
|
||||
__tablename__ = "products"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
|
||||
category_id: Mapped[Optional[int]] = mapped_column(ForeignKey("categories.id"))
|
||||
name: Mapped[Optional[str]] = mapped_column(Text)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text)
|
||||
|
||||
search_vector: Mapped[str] = mapped_column(TSVECTOR)
|
||||
|
||||
__table_args__ = (
|
||||
Index("idx_products_search", "search_vector", postgresql_using="gin"),
|
||||
)
|
||||
9
handlers/__init__.py
Normal file
9
handlers/__init__.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from aiogram import Dispatcher
|
||||
|
||||
from .client import router as client_router
|
||||
from .admins import router as admins_router
|
||||
|
||||
|
||||
def init_handlers(dp: Dispatcher):
|
||||
dp.include_router(client_router)
|
||||
dp.include_router(admins_router)
|
||||
9
handlers/admins.py
Normal file
9
handlers/admins.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from aiogram import Router
|
||||
from aiogram.types import Message
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
@router.message()
|
||||
async def echo(msg: Message):
|
||||
await msg.answer(msg.text)
|
||||
32
handlers/client.py
Normal file
32
handlers/client.py
Normal file
@@ -0,0 +1,32 @@
|
||||
from aiogram import Router
|
||||
from aiogram.types import Message
|
||||
from aiogram.filters import Command
|
||||
from aiogram.fsm.context import FSMContext
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from misc.kb import main_menu_kb
|
||||
from services.orders import OrderService
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
@router.message(Command("start"))
|
||||
async def main_menu(msg: Message, state: FSMContext):
|
||||
await state.clear()
|
||||
|
||||
await msg.answer(
|
||||
"hii!", reply_markup=await main_menu_kb(msg.from_user.id)
|
||||
) # TODO: Write a welcome message
|
||||
|
||||
|
||||
@router.message(Command("orders"))
|
||||
async def get_orders(
|
||||
msg: Message,
|
||||
state: FSMContext,
|
||||
order_service: OrderService,
|
||||
session: AsyncSession,
|
||||
):
|
||||
await state.clear()
|
||||
|
||||
count = await order_service.get_order_count(session, msg.from_user.id)
|
||||
await msg.answer(f"you have {count} orders.")
|
||||
40
main.py
Normal file
40
main.py
Normal file
@@ -0,0 +1,40 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from aiogram import Bot, Dispatcher
|
||||
|
||||
from config import BOT_TOKEN
|
||||
from handlers import init_handlers
|
||||
|
||||
from middlewares.di import DIMiddleware
|
||||
from middlewares.repository import RepositoryMiddleware
|
||||
from middlewares.session import DBSessionMiddleware
|
||||
from repositories.orders import OrderRepository
|
||||
from services import OrderService
|
||||
from db.base import async_session
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def main():
|
||||
dp = Dispatcher()
|
||||
|
||||
bot = Bot(token=BOT_TOKEN)
|
||||
|
||||
# DB services creation
|
||||
order_repository = OrderRepository()
|
||||
order_service = OrderService(order_repository)
|
||||
|
||||
# DI Middleware Init
|
||||
dp.message.middleware(DIMiddleware(order_service))
|
||||
dp.message.middleware(DBSessionMiddleware(async_session))
|
||||
dp.message.middleware(RepositoryMiddleware())
|
||||
|
||||
init_handlers(dp)
|
||||
|
||||
await dp.start_polling(bot)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
5
middlewares/__init__.py
Normal file
5
middlewares/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .di import DIMiddleware
|
||||
from .repository import RepositoryMiddleware
|
||||
from .session import DBSessionMiddleware
|
||||
|
||||
__all__ = ["DIMiddleware", "RepositoryMiddleware", "DBSessionMiddleware"]
|
||||
19
middlewares/di.py
Normal file
19
middlewares/di.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from aiogram import BaseMiddleware
|
||||
from typing import Any, Callable
|
||||
|
||||
from services.orders import OrderService
|
||||
|
||||
|
||||
class DIMiddleware(BaseMiddleware):
|
||||
def __init__(self, order_service: OrderService):
|
||||
self._order_service = order_service
|
||||
|
||||
async def __call__(
|
||||
self,
|
||||
handler: Callable,
|
||||
event: Any,
|
||||
data: dict[str, Any],
|
||||
) -> Any:
|
||||
data["order_service"] = self._order_service
|
||||
|
||||
return await handler(event, data)
|
||||
9
middlewares/repository.py
Normal file
9
middlewares/repository.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from aiogram import BaseMiddleware
|
||||
|
||||
from repositories.orders import OrderRepository
|
||||
|
||||
|
||||
class RepositoryMiddleware(BaseMiddleware):
|
||||
async def __call__(self, handler, event, data):
|
||||
data["order_repo"] = OrderRepository()
|
||||
return await handler(event, data)
|
||||
12
middlewares/session.py
Normal file
12
middlewares/session.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from aiogram import BaseMiddleware
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
|
||||
|
||||
class DBSessionMiddleware(BaseMiddleware):
|
||||
def __init__(self, session_factory: async_sessionmaker):
|
||||
self.session_factory = session_factory
|
||||
|
||||
async def __call__(self, handler, event, data):
|
||||
async with self.session_factory() as session:
|
||||
data["session"] = session
|
||||
return await handler(event, data)
|
||||
4
misc/kb/__init__.py
Normal file
4
misc/kb/__init__.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from misc.kb.admins import *
|
||||
from misc.kb.client import *
|
||||
|
||||
__all__ = ["admins", "client"]
|
||||
0
misc/kb/admins.py
Normal file
0
misc/kb/admins.py
Normal file
20
misc/kb/client.py
Normal file
20
misc/kb/client.py
Normal file
@@ -0,0 +1,20 @@
|
||||
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
|
||||
from aiogram.utils.keyboard import InlineKeyboardBuilder
|
||||
|
||||
|
||||
async def cart_btn(user_id: int) -> InlineKeyboardButton:
|
||||
return InlineKeyboardButton(
|
||||
text="🛒 Корзина ()", callback_data="cart"
|
||||
) # TODO: Database integration, get cart items count
|
||||
|
||||
|
||||
async def main_menu_kb(user_id: int) -> InlineKeyboardMarkup:
|
||||
return InlineKeyboardBuilder(
|
||||
[
|
||||
[
|
||||
InlineKeyboardButton(text="📦 Каталог", callback_data="catalogue"),
|
||||
InlineKeyboardButton(text="🔍", callback_data="find"),
|
||||
],
|
||||
[await cart_btn(user_id)],
|
||||
]
|
||||
).as_markup()
|
||||
1
postgresql.fish
Executable file
1
postgresql.fish
Executable file
@@ -0,0 +1 @@
|
||||
docker run --name test-postgres -e POSTGRES_PASSWORD=HEXDEVFUCKINGSUCKS! -p 5432:5432 -d postgres
|
||||
8
pyproject.toml
Normal file
8
pyproject.toml
Normal file
@@ -0,0 +1,8 @@
|
||||
[tool.black]
|
||||
line-length = 88
|
||||
target-version = ["py314"]
|
||||
|
||||
skip-string-normalization = false
|
||||
skip-magic-trailing-comma = false
|
||||
|
||||
preview = false
|
||||
0
repositories/__init__.py
Normal file
0
repositories/__init__.py
Normal file
21
repositories/orders.py
Normal file
21
repositories/orders.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy import select
|
||||
from typing import Optional, Union, List
|
||||
|
||||
from db.models import Order, OrderItem, OrderStatus
|
||||
|
||||
|
||||
class OrderRepository:
|
||||
async def get_order_by_id(
|
||||
self, session: AsyncSession, order_id: int
|
||||
) -> Optional[Order]:
|
||||
stmt = select(Order).where(Order.id == order_id)
|
||||
return await session.scalar(stmt)
|
||||
|
||||
async def get_orders_by_user(
|
||||
self, session: AsyncSession, user_id: int
|
||||
) -> list[Order]:
|
||||
stmt = select(Order).where(Order.customer == user_id)
|
||||
result = await session.scalars(stmt)
|
||||
|
||||
return list(result)
|
||||
7
requirements.txt
Normal file
7
requirements.txt
Normal file
@@ -0,0 +1,7 @@
|
||||
alembic
|
||||
aiogram
|
||||
python-dotenv
|
||||
black
|
||||
asyncpg
|
||||
sqlalchemy[asyncio]
|
||||
psycopg2
|
||||
3
services/__init__.py
Normal file
3
services/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from .orders import OrderService
|
||||
|
||||
__all__ = ["OrderService"]
|
||||
11
services/orders.py
Normal file
11
services/orders.py
Normal file
@@ -0,0 +1,11 @@
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from repositories.orders import OrderRepository
|
||||
|
||||
|
||||
class OrderService:
|
||||
def __init__(self, order_repo: OrderRepository):
|
||||
self.order_repo = order_repo
|
||||
|
||||
async def get_order_count(self, session: AsyncSession, user_id: int) -> int:
|
||||
orders = await self.order_repo.get_orders_by_user(session, user_id)
|
||||
return len(orders)
|
||||
Reference in New Issue
Block a user