diff --git a/barker/barker/core/config.py b/barker/barker/core/config.py index 65c19cd..12c33f4 100644 --- a/barker/barker/core/config.py +++ b/barker/barker/core/config.py @@ -16,7 +16,7 @@ class Settings(BaseSettings): PORT: int = 80 DEBUG: bool = False LOG_LEVEL: str = "NOTSET" - SQLALCHEMY_DATABASE_URI: str = None + SQLALCHEMY_DATABASE_URI: str = "" REDIS_HOST: str = "127.0.0.1" REDIS_PORT: int = 6379 diff --git a/barker/barker/core/security.py b/barker/barker/core/security.py index 3d2433a..bf65d43 100644 --- a/barker/barker/core/security.py +++ b/barker/barker/core/security.py @@ -1,7 +1,7 @@ import uuid from datetime import datetime, timedelta -from typing import List, Optional +from typing import List, Optional, Tuple from fastapi import Depends, HTTPException, Security, status from fastapi.security import OAuth2PasswordBearer, SecurityScopes @@ -9,6 +9,7 @@ from jose import jwt from jose.exceptions import ExpiredSignatureError from jwt import PyJWTError from pydantic import BaseModel, ValidationError +from sqlalchemy import select from sqlalchemy.orm import Session from ..core.config import settings @@ -28,7 +29,7 @@ class Token(BaseModel): class TokenData(BaseModel): - username: str = None + username: str = "" scopes: List[str] = [] @@ -64,8 +65,8 @@ def authenticate_user(username: str, password: str, db: Session) -> Optional[Use return user -def device_allowed(user: UserModel, device_id: Optional[uuid.UUID], db: Session = None) -> (bool, Device): - device: Device = db.query(Device).filter(Device.id == device_id).first() +def device_allowed(user: UserModel, device_id: Optional[uuid.UUID], db: Session = None) -> Tuple[bool, Device]: + device: Device = db.execute(select(Device).where(Device.id == device_id)).scalars().one_or_none() if device is None: device = Device.create(db) allowed = "add-devices" in set([p.name.replace(" ", "-").lower() for r in user.roles for p in r.permissions]) diff --git a/barker/barker/db/init_db.py b/barker/barker/db/init_db.py index 9af7d42..ee5a287 100644 --- a/barker/barker/db/init_db.py +++ b/barker/barker/db/init_db.py @@ -107,7 +107,7 @@ def init_db(db: Session) -> None: ] for option in options: db.add(option) - db.add(Customer("", "Cash", "", "", uuid.UUID("2c716f4b-0736-429a-ad51-610d7c47cb5e"))) + db.add(Customer("Cash", "", "", uuid.UUID("2c716f4b-0736-429a-ad51-610d7c47cb5e"))) db.add( DbSetting( uuid.UUID("fb738ba2-a3c9-40ed-891c-b930e6454974"), diff --git a/barker/barker/models/user.py b/barker/barker/models/user.py index 1fe0885..dab3122 100644 --- a/barker/barker/models/user.py +++ b/barker/barker/models/user.py @@ -5,7 +5,7 @@ from hashlib import md5 from barker.models.login_history import LoginHistory from barker.models.meta import Base from barker.models.user_roles import user_roles -from sqlalchemy import Boolean, Column, Unicode, desc, text +from sqlalchemy import Boolean, Column, Unicode, desc, select, text from sqlalchemy.dialects.postgresql import UUID from sqlalchemy.orm import Session, relationship, synonym @@ -46,7 +46,7 @@ class User(Base): def auth(cls, name: str, password: str, db: Session): if password is None: return None - user = db.query(User).filter(User.name.ilike(name)).first() + user = db.execute(select(User).where(User.name.ilike(name))).scalars().one_or_none() if not user: return None if user.password != encrypt(password) or user.locked_out: diff --git a/barker/barker/printing/bill.py b/barker/barker/printing/bill.py index 2354631..6555eeb 100644 --- a/barker/barker/printing/bill.py +++ b/barker/barker/printing/bill.py @@ -9,7 +9,7 @@ from typing import List, Tuple from arq import ArqRedis, create_pool from barker.core.config import settings -from sqlalchemy import and_, or_ +from sqlalchemy import and_, or_, select from sqlalchemy.orm import Session from ..core.arq import settings as redis_settings @@ -25,15 +25,14 @@ from . import currency_format, format_no_decimals def print_bill(voucher_id: uuid.UUID, db: Session): locale.setlocale(locale.LC_MONETARY, "en_IN") - voucher: Voucher = db.query(Voucher).filter(Voucher.id == voucher_id).first() + voucher: Voucher = db.execute(select(Voucher).where(Voucher.id == voucher_id)).scalar_one() - printer = ( - db.query(Printer) + printer = db.execute( + select(Printer) .join(SectionPrinter.printer) - .filter(SectionPrinter.section_id == voucher.food_table.section_id) - .filter(SectionPrinter.menu_category_id == None) # noqa: E711 - .first() - ) + .where(SectionPrinter.section_id == voucher.food_table.section_id) + .where(SectionPrinter.menu_category_id == None) # noqa: E711 + ).scalar_one() items_dict = {} tax = {} @@ -82,7 +81,7 @@ def design_bill( db: Session, ): # Header - s = "\n\r" + db.query(DbSetting).filter(DbSetting.name == "Header").first().data["Text"] + s = "\n\r" + db.execute(select(DbSetting).where(DbSetting.name == "Header")).scalar_one().data["Text"] if voucher.voucher_type == VoucherType.REGULAR_BILL: s += "\n\r" + "Retail Invoice".center(42) s += "\n\r" @@ -104,9 +103,8 @@ def design_bill( s += "\n\r" + "Qty. Particulars Price Amount" s += "\n\r" + "-" * 42 for item in [i for i in items if i.quantity != 0]: - product: ProductVersion = ( - db.query(ProductVersion) - .filter( + product: ProductVersion = db.execute( + select(ProductVersion).where( and_( ProductVersion.product_id == item.product_id, or_( @@ -119,8 +117,7 @@ def design_bill( ), ) ) - .first() - ) + ).scalar_one() name = "H H " + product.full_name if item.is_happy_hour else product.full_name s += ( f"\n\r" @@ -163,5 +160,5 @@ def design_bill( s += "\n\r" + "-" * 42 s += "\n\r" + "Cashier : " + voucher.user.name - s += "\n\r" + db.query(DbSetting).filter(DbSetting.name == "Footer").first().data["Text"] + s += "\n\r" + db.execute(select(DbSetting).where(DbSetting.name == "Footer")).scalar_one().data["Text"] return s diff --git a/barker/barker/printing/cashier_report.py b/barker/barker/printing/cashier_report.py index b14e137..905417f 100644 --- a/barker/barker/printing/cashier_report.py +++ b/barker/barker/printing/cashier_report.py @@ -6,6 +6,7 @@ from datetime import datetime, timedelta from arq import ArqRedis, create_pool from barker.schemas.cashier_report import CashierReport +from sqlalchemy import select from sqlalchemy.orm import Session from ..core.arq import settings as redis_settings @@ -19,14 +20,13 @@ from . import currency_format def print_cashier_report(report: CashierReport, device_id: uuid.UUID, db: Session): locale.setlocale(locale.LC_MONETARY, "en_IN") data = design_cashier_report(report) - section_id = db.query(Device.section_id).filter(Device.id == device_id).scalar() - printer = ( - db.query(Printer) + section_id = db.execute(select(Device.section_id).where(Device.id == device_id)).scalar_one() + printer = db.execute( + select(Printer) .join(SectionPrinter.printer) - .filter(SectionPrinter.section_id == section_id) - .filter(SectionPrinter.menu_category_id == None) # noqa: E711 - .first() - ) + .where(SectionPrinter.section_id == section_id) + .where(SectionPrinter.menu_category_id == None) # noqa: E711 + ).scalar_one() redis: ArqRedis = asyncio.run(create_pool(redis_settings)) asyncio.run( diff --git a/barker/barker/printing/discount_report.py b/barker/barker/printing/discount_report.py index 8b8f447..210992a 100644 --- a/barker/barker/printing/discount_report.py +++ b/barker/barker/printing/discount_report.py @@ -3,6 +3,7 @@ import locale import uuid from arq import ArqRedis, create_pool +from sqlalchemy import select from sqlalchemy.orm import Session from ..core.arq import settings as redis_settings @@ -16,14 +17,13 @@ from . import currency_format def print_discount_report(report: DiscountReport, device_id: uuid.UUID, db: Session): locale.setlocale(locale.LC_MONETARY, "en_IN") data = design_discount_report(report) - section_id = db.query(Device.section_id).filter(Device.id == device_id).scalar() - printer = ( - db.query(Printer) + section_id = db.execute(select(Device.section_id).where(Device.id == device_id)).scalar_one() + printer = db.execute( + select(Printer) .join(SectionPrinter.printer) - .filter(SectionPrinter.section_id == section_id) - .filter(SectionPrinter.menu_category_id == None) # noqa: E711 - .first() - ) + .where(SectionPrinter.section_id == section_id) + .where(SectionPrinter.menu_category_id == None) # noqa: E711 + ).scalar_one() redis: ArqRedis = asyncio.run(create_pool(redis_settings)) asyncio.run( diff --git a/barker/barker/printing/kot.py b/barker/barker/printing/kot.py index 89c8567..b0fe55d 100644 --- a/barker/barker/printing/kot.py +++ b/barker/barker/printing/kot.py @@ -6,7 +6,7 @@ from typing import List from arq import ArqRedis, create_pool from barker.core.config import settings -from sqlalchemy import and_, or_ +from sqlalchemy import and_, or_, select from sqlalchemy.orm import Session from ..core.arq import settings as redis_settings @@ -41,9 +41,8 @@ def design_kot(voucher: Voucher, kot: Kot, items: List[Inventory], copy_number: + "".ljust(42, "-") ) for item in items: - product: ProductVersion = ( - db.query(ProductVersion) - .filter( + product: ProductVersion = db.execute( + select(ProductVersion).where( and_( ProductVersion.product_id == item.product_id, or_( @@ -56,8 +55,7 @@ def design_kot(voucher: Voucher, kot: Kot, items: List[Inventory], copy_number: ), ) ) - .first() - ) + ).scalar_one() name = "H H " + product.full_name if item.is_happy_hour else product.full_name s += "\n\r" + f"{item.quantity:6.2} x {name:<33}" for m in item.modifiers: @@ -67,16 +65,15 @@ def design_kot(voucher: Voucher, kot: Kot, items: List[Inventory], copy_number: def print_kot(voucher_id: uuid.UUID, db: Session): - voucher: Voucher = db.query(Voucher).filter(Voucher.id == voucher_id).first() + voucher: Voucher = db.execute(select(Voucher).where(Voucher.id == voucher_id)).scalar_one() my_hash = {} kot: Kot = voucher.kots[-1] product_date = ( voucher.date + timedelta(minutes=settings.TIMEZONE_OFFSET_MINUTES - settings.NEW_DAY_OFFSET_MINUTES) ).date() for item in kot.inventories: - product: ProductVersion = ( - db.query(ProductVersion) - .filter( + product: ProductVersion = db.execute( + select(ProductVersion).where( and_( ProductVersion.product_id == item.product_id, or_( @@ -89,22 +86,20 @@ def print_kot(voucher_id: uuid.UUID, db: Session): ), ) ) - .first() - ) + ).scalar_one() - printer, copies = ( - db.query(Printer, SectionPrinter.copies) + printer, copies = db.execute( + select(Printer, SectionPrinter.copies) .join(SectionPrinter.printer) - .filter(SectionPrinter.section_id == voucher.food_table.section_id) - .filter( + .where(SectionPrinter.section_id == voucher.food_table.section_id) + .where( or_( SectionPrinter.menu_category_id == product.menu_category_id, SectionPrinter.menu_category_id == None, # noqa: E711 ) ) .order_by(SectionPrinter.menu_category_id) - .first() - ) + ).one() key = (printer.id, copies) if key not in my_hash: my_hash[key] = (printer, []) diff --git a/barker/barker/printing/sale_report.py b/barker/barker/printing/sale_report.py index 6f49ceb..dc21312 100644 --- a/barker/barker/printing/sale_report.py +++ b/barker/barker/printing/sale_report.py @@ -5,6 +5,7 @@ import uuid from datetime import datetime, timedelta from arq import ArqRedis, create_pool +from sqlalchemy import select from sqlalchemy.orm import Session from ..core.arq import settings as redis_settings @@ -19,14 +20,13 @@ from . import currency_format def print_sale_report(report: SaleReport, device_id: uuid.UUID, db: Session): locale.setlocale(locale.LC_MONETARY, "en_IN") data = design_sale_report(report) - section_id = db.query(Device.section_id).filter(Device.id == device_id).scalar() - printer = ( - db.query(Printer) + section_id = db.execute(select(Device.section_id).where(Device.id == device_id)).scalar_one() + printer = db.execute( + select(Printer) .join(SectionPrinter.printer) - .filter(SectionPrinter.section_id == section_id) - .filter(SectionPrinter.menu_category_id == None) # noqa: E711 - .first() - ) + .where(SectionPrinter.section_id == section_id) + .where(SectionPrinter.menu_category_id == None) # noqa: E711 + ).scalar_one() redis: ArqRedis = asyncio.run(create_pool(redis_settings)) asyncio.run( diff --git a/barker/barker/routers/guest_book.py b/barker/barker/routers/guest_book.py index a5bf7d2..df7065e 100644 --- a/barker/barker/routers/guest_book.py +++ b/barker/barker/routers/guest_book.py @@ -1,7 +1,7 @@ import uuid from datetime import date, datetime, timedelta -from typing import Optional +from typing import List, Optional import barker.schemas.guest_book as schemas @@ -104,17 +104,17 @@ def show_list( user: UserToken = Depends(get_user), ) -> schemas.GuestBookList: if q is None or q == "": - q = date.today() + d = date.today() else: - q = datetime.strptime(q, "%d-%b-%Y") + d = datetime.strptime(q, "%d-%b-%Y") list_ = ( select(GuestBook) .where( - GuestBook.date >= q + timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES - settings.TIMEZONE_OFFSET_MINUTES) + GuestBook.date >= d + timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES - settings.TIMEZONE_OFFSET_MINUTES) ) .where( GuestBook.date - < q + < d + timedelta( minutes=settings.NEW_DAY_OFFSET_MINUTES - settings.TIMEZONE_OFFSET_MINUTES, days=1, @@ -123,7 +123,7 @@ def show_list( .order_by(GuestBook.date) ) - guest_book = [] + guest_book: List[schemas.GuestBookListItem] = [] with SessionFuture() as db: for i, item in enumerate(db.execute(list_).scalars().all()): guest_book.insert( @@ -141,7 +141,7 @@ def show_list( tableName=None if item.status is None else item.status.food_table.name, ), ) - return schemas.GuestBookList(date=q, list=guest_book) + return schemas.GuestBookList(date=d, list=guest_book) @router.get("/{id_}", response_model=schemas.GuestBook) diff --git a/barker/barker/routers/modifier_category.py b/barker/barker/routers/modifier_category.py index 536314f..c03517b 100644 --- a/barker/barker/routers/modifier_category.py +++ b/barker/barker/routers/modifier_category.py @@ -136,28 +136,30 @@ def show_list(date_: date = Depends(effective_date), user: UserToken = Depends(g .scalars() .all() ) - modifier_categories = [] - for item in list_: - products = [x.id for x in item.products] - modifier_category = { - "id": item.id, - "name": item.name, - "minimum": item.minimum, - "maximum": item.maximum, - "isActive": item.is_active, - "menuCategories": [ - { - "id": mc.id, - "name": mc.name, - "enabled": reduce(lambda x, y: x and (y.product_id in products), mc.products, True), - "products": [{"id": p.id, "name": p.name} for p in mc.products if p.product_id in products], - } - for mc in menu_categories - ], - } - modifier_category["menuCategories"] = [i for i in modifier_category["menuCategories"] if len(i["products"]) > 0] - modifier_categories.append(modifier_category) - return modifier_categories + modifier_categories = [] + for item in list_: + products = [x.id for x in item.products] + modifier_category = { + "id": item.id, + "name": item.name, + "minimum": item.minimum, + "maximum": item.maximum, + "isActive": item.is_active, + "menuCategories": [ + { + "id": mc.id, + "name": mc.name, + "enabled": reduce(lambda x, y: x and (y.product_id in products), mc.products, True), + "products": [{"id": p.id, "name": p.name} for p in mc.products if p.product_id in products], + } + for mc in menu_categories + ], + } + modifier_category["menuCategories"] = [ + i for i in modifier_category["menuCategories"] if len(i["products"]) > 0 + ] + modifier_categories.append(modifier_category) + return modifier_categories @router.get("/for-product/{id_}") diff --git a/barker/barker/routers/reports/cashier_report.py b/barker/barker/routers/reports/cashier_report.py index 7855b60..43ed565 100644 --- a/barker/barker/routers/reports/cashier_report.py +++ b/barker/barker/routers/reports/cashier_report.py @@ -74,9 +74,9 @@ def show_id( user: UserToken = Security(get_user, scopes=["cashier-report"]), ) -> CashierReport: check_audit_permission(start_date, user.permissions) - user = UserLink(id=user.id_, name=user.name) + user_link = UserLink(id=user.id_, name=user.name) with SessionFuture() as db: - return get_id(id_, start_date, finish_date, user, db) + return get_id(id_, start_date, finish_date, user_link, db) def get_id(id_: uuid.UUID, start_date: date, finish_date: date, user: UserLink, db: Session) -> CashierReport: diff --git a/barker/barker/routers/role.py b/barker/barker/routers/role.py index 0cff42e..7929eeb 100644 --- a/barker/barker/routers/role.py +++ b/barker/barker/routers/role.py @@ -80,7 +80,7 @@ def delete_route( item: Role = db.execute(select(Role).where(Role.id == id_)).scalar_one() db.delete(item) db.commit() - return role_blank() + return role_blank(db) @router.get("", response_model=schemas.RoleBlank) diff --git a/barker/barker/routers/tax.py b/barker/barker/routers/tax.py index 0b45a05..beedc5d 100644 --- a/barker/barker/routers/tax.py +++ b/barker/barker/routers/tax.py @@ -142,7 +142,7 @@ def name_valid(name: str) -> bool: items = name.split(";") if len(items) == 1: return True - total = 0 + total = Decimal(0) for i, item in enumerate(it.strip() for it in items): match = re.match(r"(^.*)\s+\((.*?)/(.*?)\)[^(]*$", item) if not match or len(match.groups()) != 3: diff --git a/barker/barker/routers/update_product_prices.py b/barker/barker/routers/update_product_prices.py index ca6e2f5..dca262e 100644 --- a/barker/barker/routers/update_product_prices.py +++ b/barker/barker/routers/update_product_prices.py @@ -60,7 +60,7 @@ def get_update_product_prices_id( def update_product_prices_list( menu_category_id: Optional[uuid.UUID], date_: date, db: Session ) -> List[UpdateProductPricesItem]: - list_: List[ProductVersion] = ( + list_ = ( select(ProductVersion) .join(ProductVersion.menu_category) .where( diff --git a/barker/barker/routers/voucher/__init__.py b/barker/barker/routers/voucher/__init__.py index 17998e0..216f04f 100644 --- a/barker/barker/routers/voucher/__init__.py +++ b/barker/barker/routers/voucher/__init__.py @@ -88,7 +88,7 @@ def check_permissions(item: Optional[Voucher], voucher_type: VoucherType, permis ) -def get_guest_book(id_: uuid.UUID, db: Session): +def get_guest_book(id_: Optional[uuid.UUID], db: Session) -> Optional[GuestBook]: if id_ is None: return id_ return db.execute(select(GuestBook).where(GuestBook.id == id_)).scalar_one() diff --git a/barker/barker/routers/voucher/change.py b/barker/barker/routers/voucher/change.py index 43504a2..b8dd668 100644 --- a/barker/barker/routers/voucher/change.py +++ b/barker/barker/routers/voucher/change.py @@ -86,7 +86,10 @@ def void_and_issue_new_bill( if update_table: if old.status is None: - item.status = Overview(voucher_id=None, food_table_id=item.food_table_id, status="printed") + guest_book_id = None if guest_book is None else guest_book.id + item.status = Overview( + voucher_id=None, food_table_id=item.food_table_id, guest_book_id=guest_book_id, status="printed" + ) db.add(item.status) else: db.execute(update(Overview).where(Overview.voucher_id == old.id).values(voucher_id=item.id)) diff --git a/barker/barker/routers/voucher/save.py b/barker/barker/routers/voucher/save.py index effad49..34caa24 100644 --- a/barker/barker/routers/voucher/save.py +++ b/barker/barker/routers/voucher/save.py @@ -68,7 +68,7 @@ def save( def do_save( data: schemas.VoucherIn, voucher_type: VoucherType, - guest_book: GuestBook, + guest_book: Optional[GuestBook], db: Session, user: UserToken, ): diff --git a/barker/barker/schemas/menu_category.py b/barker/barker/schemas/menu_category.py index ee25db2..15569d9 100644 --- a/barker/barker/schemas/menu_category.py +++ b/barker/barker/schemas/menu_category.py @@ -38,7 +38,7 @@ class MenuCategoryBlank(MenuCategoryIn): class MenuCategoryLink(BaseModel): id_: uuid.UUID = Field(...) name: Optional[str] - products: Optional[List[ProductLink]] + products: List[ProductLink] class Config: fields = {"id_": "id"} diff --git a/barker/barker/schemas/modifier_category.py b/barker/barker/schemas/modifier_category.py index f69d44c..040aae7 100644 --- a/barker/barker/schemas/modifier_category.py +++ b/barker/barker/schemas/modifier_category.py @@ -13,7 +13,7 @@ class ModifierCategoryIn(BaseModel): minimum: int = Field(ge=0) maximum: Optional[int] = Field(ge=0) is_active: bool - menu_categories: Optional[List[MenuCategoryLink]] + menu_categories: List[MenuCategoryLink] class Config: anystr_strip_whitespace = True diff --git a/barker/barker/schemas/printer.py b/barker/barker/schemas/printer.py index 7057c90..029a0df 100644 --- a/barker/barker/schemas/printer.py +++ b/barker/barker/schemas/printer.py @@ -1,7 +1,5 @@ import uuid -from typing import Optional - from pydantic import BaseModel, Field from . import to_camel @@ -10,7 +8,7 @@ from . import to_camel class PrinterIn(BaseModel): name: str = Field(..., min_length=1) address: str = Field(..., min_length=1) - cut_code: Optional[str] + cut_code: str class Config: anystr_strip_whitespace = True diff --git a/barker/barker/schemas/user_token.py b/barker/barker/schemas/user_token.py index 420f7b2..481fa0a 100644 --- a/barker/barker/schemas/user_token.py +++ b/barker/barker/schemas/user_token.py @@ -8,6 +8,6 @@ from pydantic import BaseModel class UserToken(BaseModel): id_: uuid.UUID name: str - locked_out: bool = None + locked_out: bool = False password: str permissions: List[str] diff --git a/barker/barker/subscribers.py b/barker/barker/subscribers.py deleted file mode 100644 index 2eb99fb..0000000 --- a/barker/barker/subscribers.py +++ /dev/null @@ -1,10 +0,0 @@ -from barker.models.db_setting import DbSetting -from pyramid.events import NewRequest, subscriber -from pyramid.httpexceptions import HTTPServiceUnavailable - - -@subscriber(NewRequest) -def maintenance_mode(event): - maintenance = event.request.dbsession.query(DbSetting).filter(DbSetting.name == "Maintenance").first() - if maintenance is not None and maintenance.data != event.request.authenticated_userid: - raise HTTPServiceUnavailable