Skip to content
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

Добавление софт делитов в принтер #87

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""Add is_deleted field to UnionMember table

Revision ID: 120e06710249
Revises: a68c6bb2972c
Create Date: 2024-10-25 16:40:35.109586

"""

import sqlalchemy as sa
from alembic import op


# revision identifiers, used by Alembic.
revision = '120e06710249'
down_revision = 'a68c6bb2972c'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.alter_column('file', 'source', existing_type=sa.VARCHAR(), nullable=False)
op.add_column('union_member', sa.Column('is_deleted', sa.Boolean(), nullable=True))
op.execute(f'UPDATE "union_member" SET is_deleted = False')
op.alter_column('union_member', sa.Column('is_deleted', sa.Boolean(), nullable=False))
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('union_member', 'is_deleted')
op.alter_column('file', 'source', existing_type=sa.VARCHAR(), nullable=True)
# ### end Alembic commands ###
4 changes: 4 additions & 0 deletions print_service/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ class TerminalTokenNotFound(ObjectNotFound):
pass


class UserIsDeleted(Exception):
pass


class TerminalQRNotFound(ObjectNotFound):
pass

Expand Down
13 changes: 11 additions & 2 deletions print_service/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class UnionMember(Model):
surname: Mapped[str] = mapped_column(String, nullable=False)
union_number: Mapped[str] = mapped_column(String, nullable=True)
student_number: Mapped[str] = mapped_column(String, nullable=True)
is_deleted: Mapped[bool] = mapped_column(Boolean, nullable=True, default=False)

files: Mapped[list[File]] = relationship('File', back_populates='owner')
print_facts: Mapped[list[PrintFact]] = relationship('PrintFact', back_populates='owner')
Expand All @@ -44,7 +45,11 @@ class File(Model):
number_of_pages: Mapped[int] = Column(Integer)
source: Mapped[str] = Column(String, default='unknown', nullable=False)

owner: Mapped[UnionMember] = relationship('UnionMember', back_populates='files')
owner: Mapped[UnionMember] = relationship(
'UnionMember',
primaryjoin="and_(File.owner_id==UnionMember.id, not_(UnionMember.is_deleted))",
back_populates='files',
)
print_facts: Mapped[list[PrintFact]] = relationship('PrintFact', back_populates='file')

@property
Expand Down Expand Up @@ -87,6 +92,10 @@ class PrintFact(Model):
owner_id: Mapped[int] = Column(Integer, ForeignKey('union_member.id'), nullable=False)
created_at: Mapped[datetime] = Column(DateTime, nullable=False, default=datetime.utcnow)

owner: Mapped[UnionMember] = relationship('UnionMember', back_populates='print_facts')
owner: Mapped[UnionMember] = relationship(
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved
'UnionMember',
primaryjoin="and_(PrintFact.owner_id == UnionMember.id, not_(UnionMember.is_deleted))",
back_populates='print_facts',
)
file: Mapped[File] = relationship('File', back_populates='print_facts')
sheets_used: Mapped[int] = Column(Integer)
11 changes: 11 additions & 0 deletions print_service/routes/exc_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
TooManyPages,
UnionStudentDuplicate,
UnprocessableFileInstance,
UserIsDeleted,
UserNotFound,
)
from print_service.routes.base import app
Expand Down Expand Up @@ -75,6 +76,16 @@ async def terminal_not_found_by_qr(req: starlette.requests.Request, exc: Termina
)


@app.exception_handler(UserIsDeleted)
async def user_is_deleted(req: starlette.requests.Request, exc: TerminalTokenNotFound):
return JSONResponse(
content=StatusResponseModel(
status="Error", message="User is deleted", ru="Пользователь удалён из базы"
).model_dump(),
status_code=410,
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved
)


@app.exception_handler(TerminalTokenNotFound)
async def terminal_not_found_by_token(req: starlette.requests.Request, exc: TerminalTokenNotFound):
return JSONResponse(
Expand Down
7 changes: 7 additions & 0 deletions print_service/routes/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
TooLargeSize,
TooManyPages,
UnprocessableFileInstance,
UserIsDeleted,
UserNotFound,
)
from print_service.models import File as FileModel
Expand Down Expand Up @@ -105,6 +106,7 @@ class ReceiveOutput(BaseModel):
responses={
403: {'model': StatusResponseModel, 'detail': 'User error'},
500: {'model': StatusResponseModel, 'detail': 'PIN generate error'},
410: {'model': StatusResponseModel, 'detail': 'User is deleted'},
},
response_model=SendOutput,
)
Expand All @@ -123,6 +125,9 @@ async def send(inp: SendInput, settings: Settings = Depends(get_settings)):
),
func.upper(UnionMember.surname) == inp.surname.upper(),
).one_or_none()
if user:
if user.is_deleted:
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved
raise UserIsDeleted()
if not user:
raise NotInUnion()
try:
Expand Down Expand Up @@ -179,6 +184,7 @@ async def upload_file(
.order_by(FileModel.created_at.desc())
.one_or_none()
)

if not file_model:
await file.close()
raise PINNotFound(pin)
Expand Down Expand Up @@ -249,6 +255,7 @@ async def update_file_options(
.order_by(FileModel.created_at.desc())
.one_or_none()
)

print(options)
if not file_model:
raise PINNotFound(pin)
Expand Down
16 changes: 11 additions & 5 deletions print_service/routes/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from sqlalchemy import and_, func, or_

from print_service import __version__
from print_service.exceptions import UnionStudentDuplicate, UserNotFound
from print_service.exceptions import UnionStudentDuplicate, UserIsDeleted, UserNotFound
from print_service.models import UnionMember
from print_service.schema import BaseModel
from print_service.settings import get_settings
Expand Down Expand Up @@ -40,9 +40,7 @@ class UpdateUserList(BaseModel):
@router.get(
'/is_union_member',
status_code=202,
responses={
404: {'detail': 'User not found'},
},
responses={404: {'detail': 'User not found'}, 410: {'detail': 'User is deleted'}},
)
async def check_union_member(
surname: constr(strip_whitespace=True, to_upper=True, min_length=1),
Expand All @@ -61,7 +59,9 @@ async def check_union_member(
),
func.upper(UnionMember.surname) == surname,
).one_or_none()

if user:
if user.is_deleted:
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved
raise UserIsDeleted()
if v == '1':
return bool(user)

Expand Down Expand Up @@ -110,16 +110,22 @@ def update_list(
.one_or_none()
)

if db_user:
if db_user.is_deleted:
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved
raise UserIsDeleted()

if db_user:
db_user.surname = user.username
db_user.union_number = user.union_number
db_user.student_number = user.student_number
db_user.is_deleted = False
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved
else:
db.session.add(
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved
UnionMember(
surname=user.username,
union_number=user.union_number,
student_number=user.student_number,
is_deleted=False,
DaymasS marked this conversation as resolved.
Show resolved Hide resolved
)
)
db.session.flush()
Expand Down
1 change: 1 addition & 0 deletions print_service/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def get_file(dbsession, pin: str or list[str]):
.order_by(FileModel.created_at.desc())
.all()
)

if len(pin) != len(files):
raise FileNotFound(len(pin) - len(files))

Expand Down
7 changes: 7 additions & 0 deletions tests/test_routes/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ def union_member_user(dbsession):
dbsession.commit()


@pytest.fixture(scope='function')
def add_is_deleted_flag(dbsession):
db_user = dbsession.query(UnionMember).filter(UnionMember.id == 42).one_or_none()
db_user.is_deleted = True
dbsession.commit()
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved


@pytest.fixture(scope='function')
def uploaded_file_db(dbsession, union_member_user, client):
body = {
Expand Down
12 changes: 12 additions & 0 deletions tests/test_routes/test_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,18 @@ def test_post_success(union_member_user, client, dbsession):
dbsession.commit()


def test_post_is_deleted(client, union_member_user, add_is_deleted_flag):
body = {
"surname": union_member_user['surname'],
"number": union_member_user['union_number'],
"filename": "filename.pdf",
"source": "webapp",
"options": {"pages": "", "copies": 1, "two_sided": False},
}
res = client.post(url, data=json.dumps(body))
assert res.status_code == status.HTTP_410_GONE


def test_post_unauthorized_user(client):
body = {
"surname": 'surname',
Expand Down
23 changes: 23 additions & 0 deletions tests/test_routes/test_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,15 @@ def test_get_not_found(client):
assert res.status_code == status.HTTP_404_NOT_FOUND


def test_get_is_deleted(client, union_member_user, add_is_deleted_flag):
params = {
'surname': 'test',
'number': '6666667',
}
res = client.get(url, params=params)
assert res.status_code == status.HTTP_410_GONE


def test_post_success(client, dbsession):
body = {
'users': [
Expand All @@ -49,6 +58,20 @@ def test_post_success(client, dbsession):
dbsession.commit()


def test_post_is_deleted(client, union_member_user, add_is_deleted_flag):
body = {
'users': [
{
'username': 'new_test',
'union_number': '6666667',
'student_number': '13033224',
}
],
}
res = client.post(url, data=json.dumps(body))
assert res.status_code == status.HTTP_410_GONE


@pytest.mark.parametrize(
'users',
[
Expand Down
Loading