generated from niqzart/python-template
-
Notifications
You must be signed in to change notification settings - Fork 0
[4108] Сервис подписок: админка промокодов #72
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
sipmine
wants to merge
1
commit into
staging
Choose a base branch
from
feat/subscription-service
base: staging
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| """promocodes | ||
|
|
||
| Revision ID: 056 | ||
| Revises: 055 | ||
| Create Date: 2026-01-14 13:05:54.325494 | ||
|
|
||
| """ | ||
|
|
||
| from typing import Sequence, Union | ||
|
|
||
| import sqlalchemy as sa | ||
|
|
||
| from alembic import op | ||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision: str = "056" | ||
| down_revision: Union[str, None] = "055" | ||
| branch_labels: Union[str, Sequence[str], None] = None | ||
| depends_on: Union[str, Sequence[str], None] = None | ||
|
|
||
|
|
||
| def upgrade() -> None: | ||
| # ### commands auto generated by Alembic - please adjust! ### | ||
| op.create_table( | ||
| "promocodes", | ||
| sa.Column("id", sa.Integer(), nullable=False), | ||
| sa.Column("title", sa.String(length=100), nullable=False), | ||
| sa.Column("code", sa.String(length=10), nullable=False), | ||
| sa.Column("valid_from", sa.DateTime(timezone=True), nullable=True), | ||
| sa.Column("valid_until", sa.DateTime(timezone=True), nullable=True), | ||
| sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), | ||
| sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False), | ||
| sa.PrimaryKeyConstraint("id", name=op.f("pk_promocodes")), | ||
| schema="xi_back_2", | ||
| ) | ||
| op.create_index( | ||
| op.f("ix_xi_back_2_promocodes_code"), | ||
| "promocodes", | ||
| ["code"], | ||
| unique=True, | ||
| schema="xi_back_2", | ||
| ) | ||
| # ### end Alembic commands ### | ||
|
|
||
|
|
||
| def downgrade() -> None: | ||
| # ### commands auto generated by Alembic - please adjust! ### | ||
| op.drop_index( | ||
| op.f("ix_xi_back_2_promocodes_code"), | ||
| table_name="promocodes", | ||
| schema="xi_back_2", | ||
| ) | ||
| op.drop_table("promocodes", schema="xi_back_2") | ||
| # ### end Alembic commands ### |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| from app.subscriptions.main import api_router | ||
|
|
||
| __all__ = ["api_router"] |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| from typing import Annotated | ||
|
|
||
| from fastapi import Depends, Path | ||
| from starlette import status | ||
|
|
||
| from app.common.fastapi_ext import Responses, with_responses | ||
| from app.subscriptions.models.promocodes_db import Promocode | ||
|
|
||
|
|
||
| class PromocodeResponses(Responses): | ||
| PROMOCODE_NOT_FOUND = status.HTTP_404_NOT_FOUND, "Promocode not found" | ||
|
|
||
|
|
||
| @with_responses(PromocodeResponses) | ||
| async def get_promocode_by_id( | ||
| promocode_id: Annotated[int, Path()], | ||
| ) -> Promocode: | ||
| promocode = await Promocode.find_first_by_id(promocode_id) | ||
| if promocode is None: | ||
| raise PromocodeResponses.PROMOCODE_NOT_FOUND | ||
| return promocode | ||
|
|
||
|
|
||
| PromocodeByID = Annotated[Promocode, Depends(get_promocode_by_id)] | ||
|
|
||
|
|
||
| @with_responses(PromocodeResponses) | ||
| async def get_promocode_by_code( | ||
| code: Annotated[str, Path()], | ||
| ) -> Promocode: | ||
| promocode = await Promocode.find_first_by_kwargs(code=code) | ||
| if promocode is None: | ||
| raise PromocodeResponses.PROMOCODE_NOT_FOUND | ||
| return promocode | ||
|
|
||
|
|
||
| PromocodeByCode = Annotated[Promocode, Depends(get_promocode_by_code)] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| from collections.abc import AsyncIterator | ||
| from contextlib import asynccontextmanager | ||
| from typing import Any | ||
|
|
||
| from app.common.dependencies.api_key_dep import APIKeyProtection | ||
| from app.common.dependencies.authorization_dep import ProxyAuthorized | ||
| from app.common.dependencies.mub_dep import MUBProtection | ||
| from app.common.fastapi_ext import APIRouterExt | ||
| from app.subscriptions.routes import promocodes_mub | ||
|
|
||
| outside_router = APIRouterExt(prefix="/api/public/subscription-service") | ||
|
|
||
| authorized_router = APIRouterExt( | ||
| dependencies=[ProxyAuthorized], | ||
| prefix="/api/protected/subscription-service", | ||
| ) | ||
|
|
||
| mub_router = APIRouterExt( | ||
| dependencies=[MUBProtection], | ||
| prefix="/mub/subscription-service", | ||
| ) | ||
| mub_router.include_router(promocodes_mub.router) | ||
|
|
||
| internal_router = APIRouterExt( | ||
| dependencies=[APIKeyProtection], | ||
| prefix="/internal/subscription-service", | ||
| ) | ||
|
|
||
|
|
||
| @asynccontextmanager | ||
| async def lifespan(_: Any) -> AsyncIterator[None]: | ||
| yield | ||
|
|
||
|
|
||
| api_router = APIRouterExt(lifespan=lifespan) | ||
| api_router.include_router(outside_router) | ||
| api_router.include_router(authorized_router) | ||
| api_router.include_router(mub_router) | ||
| api_router.include_router(internal_router) |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| from datetime import datetime | ||
| from typing import Annotated | ||
|
|
||
| from pydantic import AwareDatetime, Field | ||
| from pydantic_marshals.sqlalchemy import MappedModel | ||
| from sqlalchemy import DateTime, String, select | ||
| from sqlalchemy.orm import Mapped, mapped_column | ||
|
|
||
| from app.common.config import Base | ||
| from app.common.sqlalchemy_ext import db | ||
| from app.common.utils.datetime import datetime_utc_now | ||
|
|
||
|
|
||
| class Promocode(Base): | ||
| __tablename__ = "promocodes" | ||
|
|
||
| id: Mapped[int] = mapped_column(primary_key=True) | ||
|
|
||
| title: Mapped[str] = mapped_column(String(100)) | ||
| code: Mapped[str] = mapped_column(String(10), index=True, unique=True) | ||
|
|
||
| valid_from: Mapped[datetime | None] = mapped_column( | ||
| DateTime(timezone=True), default=None | ||
| ) | ||
| valid_until: Mapped[datetime | None] = mapped_column( | ||
| DateTime(timezone=True), default=None | ||
| ) | ||
|
|
||
| created_at: Mapped[datetime] = mapped_column( | ||
| DateTime(timezone=True), default=datetime_utc_now | ||
| ) | ||
| updated_at: Mapped[datetime] = mapped_column( | ||
| DateTime(timezone=True), default=datetime_utc_now | ||
| ) | ||
|
|
||
| TitleType = Annotated[str, Field(min_length=1, max_length=100)] | ||
| CodeType = Annotated[str, Field(min_length=1, max_length=10)] | ||
|
|
||
| InputSchema = MappedModel.create( | ||
| columns=[ | ||
| (title, TitleType), | ||
| (code, CodeType), | ||
| (valid_from, AwareDatetime | None), | ||
| (valid_until, AwareDatetime | None), | ||
| ] | ||
| ) | ||
| ResponseSchema = InputSchema.extend( | ||
| columns=[id, (created_at, AwareDatetime), (updated_at, AwareDatetime)] | ||
| ) | ||
|
|
||
| @classmethod | ||
| async def is_present_by_code(cls, code: str) -> bool: | ||
| return await db.is_present(select(cls).filter_by(code=code)) |
Empty file.
ByrDen marked this conversation as resolved.
Show resolved
Hide resolved
ByrDen marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| from collections.abc import Sequence | ||
| from typing import Annotated, Self | ||
|
|
||
| from fastapi import Query | ||
| from pydantic import model_validator | ||
| from starlette import status | ||
|
|
||
| from app.common.fastapi_ext import APIRouterExt, Responses | ||
| from app.common.utils.datetime import datetime_utc_now | ||
| from app.subscriptions.dependencies.promocodes_dep import PromocodeByCode, PromocodeByID | ||
| from app.subscriptions.models.promocodes_db import Promocode | ||
|
|
||
| router = APIRouterExt(tags=["promocodes mub"]) | ||
|
|
||
|
|
||
| @router.get( | ||
| "/promocodes/", | ||
| response_model=list[Promocode.ResponseSchema], | ||
| summary="List paginated promocodes", | ||
| ) | ||
| async def list_promocodes( | ||
| offset: Annotated[int, Query(ge=0)] = 0, | ||
| limit: Annotated[int, Query(ge=1, le=100)] = 100, | ||
| ) -> Sequence[Promocode]: | ||
| return await Promocode.find_paginated_by_kwargs( | ||
| offset, limit, Promocode.created_at.desc() | ||
| ) | ||
|
|
||
|
|
||
| class PromocodeInputSchema(Promocode.InputSchema): | ||
| @model_validator(mode="after") | ||
| def validate_promocode_valid_from_and_until_date(self) -> Self: | ||
| if ( | ||
| self.valid_from is not None and self.valid_until is not None | ||
| ) and self.valid_from >= self.valid_until: | ||
| raise ValueError("the end date cannot be earlier than the start date") | ||
| return self | ||
|
|
||
|
|
||
| class PromocodeConflictResponses(Responses): | ||
| PROMOCODE_ALREADY_EXISTS = status.HTTP_409_CONFLICT, "Promocode already exists" | ||
|
|
||
|
|
||
| @router.post( | ||
| "/promocodes/", | ||
| status_code=status.HTTP_201_CREATED, | ||
| response_model=Promocode.ResponseSchema, | ||
| responses=PromocodeConflictResponses.responses(), | ||
| summary="Create a new promocode", | ||
| ) | ||
| async def create_promocode(data: PromocodeInputSchema) -> Promocode: | ||
| if await Promocode.is_present_by_code(code=data.code): | ||
| raise PromocodeConflictResponses.PROMOCODE_ALREADY_EXISTS | ||
| return await Promocode.create(**data.model_dump()) | ||
|
|
||
|
|
||
| @router.get( | ||
| "/promocodes/by-id/{promocode_id}/", | ||
| response_model=Promocode.ResponseSchema, | ||
| summary="Retrieve any promocode by id", | ||
| ) | ||
| async def retrieve_promocode_by_id(promocode: PromocodeByID) -> Promocode: | ||
| return promocode | ||
|
|
||
|
|
||
| @router.get( | ||
| "/promocodes/by-code/{code}/", | ||
| response_model=Promocode.ResponseSchema, | ||
| summary="Retrieve any promocode by code", | ||
| ) | ||
| async def retrieve_promocode_by_code(promocode: PromocodeByCode) -> Promocode: | ||
| return promocode | ||
|
|
||
|
|
||
| @router.put( | ||
| "/promocodes/{promocode_id}/", | ||
| response_model=Promocode.ResponseSchema, | ||
| responses=PromocodeConflictResponses.responses(), | ||
ByrDen marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| summary="Update any promocode by id", | ||
| ) | ||
| async def put_promocode( | ||
| promocode: PromocodeByID, | ||
| data: PromocodeInputSchema, | ||
| ) -> Promocode: | ||
| if data.code != promocode.code and await Promocode.is_present_by_code( | ||
| code=data.code | ||
| ): | ||
| raise PromocodeConflictResponses.PROMOCODE_ALREADY_EXISTS | ||
| promocode.update(**data.model_dump(), updated_at=datetime_utc_now()) | ||
| return promocode | ||
|
|
||
|
|
||
| @router.delete( | ||
| "/promocodes/{promocode_id}/", | ||
| status_code=status.HTTP_204_NO_CONTENT, | ||
| summary="Delete any promocode by id", | ||
| ) | ||
| async def delete_promocode(promocode: PromocodeByID) -> None: | ||
| await promocode.delete() | ||
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import pytest | ||
| from faker import Faker | ||
|
|
||
| from app.subscriptions.models.promocodes_db import Promocode | ||
| from tests.common.active_session import ActiveSession | ||
| from tests.common.types import AnyJSON | ||
| from tests.subscriptions import factories | ||
|
|
||
|
|
||
| @pytest.fixture() | ||
| async def promocode(active_session: ActiveSession, faker: Faker) -> Promocode: | ||
| async with active_session(): | ||
| return await Promocode.create( | ||
| **factories.LimitedPromocodeInputFactory.build_python( | ||
| code=faker.pystr(min_chars=10, max_chars=10), | ||
| ) | ||
| ) | ||
|
|
||
|
|
||
| @pytest.fixture() | ||
| async def promocode_data(promocode: Promocode) -> AnyJSON: | ||
| return Promocode.ResponseSchema.model_validate(promocode).model_dump(mode="json") | ||
|
|
||
|
|
||
| @pytest.fixture() | ||
| async def other_promocode(active_session: ActiveSession, faker: Faker) -> Promocode: | ||
| async with active_session(): | ||
| return await Promocode.create( | ||
| **factories.LimitedPromocodeInputFactory.build_python( | ||
| code=faker.pystr(min_chars=9, max_chars=9), | ||
| ) | ||
| ) | ||
|
Comment on lines
10
to
32
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. issue: нет гарантии, что у promocode и other_promocode не совпадут поля |
||
|
|
||
|
|
||
| @pytest.fixture() | ||
| async def deleted_promocode( | ||
| active_session: ActiveSession, promocode: Promocode | ||
| ) -> Promocode: | ||
| async with active_session(): | ||
| await promocode.delete() | ||
| return promocode | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.