From d9eb335ef3ec3974ae8315623224a7a2f68e79f8 Mon Sep 17 00:00:00 2001 From: tanshu Date: Mon, 2 Nov 2020 23:18:56 +0530 Subject: [PATCH] Blacked, isorted, etc the python file Was also moving the validation from schemas to models/validations --- brewman/brewman/core/security.py | 22 +- brewman/brewman/core/session.py | 4 +- brewman/brewman/db/base.py | 6 +- brewman/brewman/main.py | 56 +- brewman/brewman/models/__init__.py | 7 +- brewman/brewman/models/auth.py | 18 +- brewman/brewman/models/master.py | 54 +- brewman/brewman/models/operations.py | 133 ----- brewman/brewman/models/validations.py | 45 ++ brewman/brewman/models/voucher.py | 50 +- brewman/brewman/routers/__init__.py | 10 +- brewman/brewman/routers/account.py | 24 +- brewman/brewman/routers/account_types.py | 4 +- brewman/brewman/routers/attendance.py | 6 +- brewman/brewman/routers/attendance_report.py | 6 +- brewman/brewman/routers/auth/client.py | 11 +- brewman/brewman/routers/auth/role.py | 8 +- brewman/brewman/routers/auth/user.py | 11 +- brewman/brewman/routers/batch.py | 5 +- brewman/brewman/routers/credit_salary.py | 2 +- brewman/brewman/routers/db_image.py | 4 +- brewman/brewman/routers/db_integrity.py | 10 +- brewman/brewman/routers/employee.py | 20 +- .../brewman/routers/employee_attendance.py | 14 +- brewman/brewman/routers/employee_benefit.py | 76 +-- brewman/brewman/routers/fingerprint.py | 12 +- brewman/brewman/routers/incentive.py | 41 +- brewman/brewman/routers/issue.py | 24 +- brewman/brewman/routers/issue_grid.py | 8 +- brewman/brewman/routers/journal.py | 27 +- brewman/brewman/routers/login.py | 18 +- brewman/brewman/routers/product.py | 12 +- brewman/brewman/routers/purchase.py | 32 +- brewman/brewman/routers/purchase_return.py | 18 +- brewman/brewman/routers/rebase.py | 48 +- brewman/brewman/routers/recipe.py | 66 +-- .../brewman/routers/reports/balance_sheet.py | 8 +- .../brewman/routers/reports/closing_stock.py | 22 +- .../routers/reports/net_transactions.py | 4 +- .../brewman/routers/reports/product_ledger.py | 11 +- .../brewman/routers/reports/profit_loss.py | 10 +- brewman/brewman/routers/reports/purchases.py | 8 +- .../routers/reports/raw_material_cost.py | 20 +- brewman/brewman/routers/reports/reconcile.py | 10 +- .../brewman/routers/reports/stock_movement.py | 4 +- .../brewman/routers/reports/trial_balance.py | 4 +- brewman/brewman/routers/reports/unposted.py | 2 +- brewman/brewman/routers/reset_stock.py | 17 +- brewman/brewman/routers/voucher.py | 64 +- brewman/brewman/schemas/input.py | 44 +- brewman/brewman/schemas/voucher.py | 27 +- brewman/brewman/scripts/initializedb.py | 551 +++++++++--------- brewman/pyproject.toml | 4 +- overlord/src/app/payment/payment.component.ts | 9 - overlord/src/app/receipt/receipt.component.ts | 9 - overlord/src/environments/environment.ts | 2 +- 56 files changed, 562 insertions(+), 1180 deletions(-) delete mode 100644 brewman/brewman/models/operations.py create mode 100644 brewman/brewman/models/validations.py diff --git a/brewman/brewman/core/security.py b/brewman/brewman/core/security.py index 509db468..afb45a41 100644 --- a/brewman/brewman/core/security.py +++ b/brewman/brewman/core/security.py @@ -55,9 +55,7 @@ def create_access_token(*, data: dict, expires_delta: timedelta = None): else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode.update({"exp": expire}) - encoded_jwt = jwt.encode( - to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM - ) + encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM) return encoded_jwt @@ -78,15 +76,9 @@ def authenticate_user( return user -def client_allowed( - user: UserModel, client_id: int, otp: Optional[int] = None, db: Session = None -) -> (bool, int): - client = ( - db.query(Client).filter(Client.code == client_id).first() if client_id else None - ) - allowed = "clients" in set( - [p.name.replace(" ", "-").lower() for r in user.roles for p in r.permissions] - ) +def client_allowed(user: UserModel, client_id: int, otp: Optional[int] = None, db: Session = None) -> (bool, int): + client = db.query(Client).filter(Client.code == client_id).first() if client_id else None + allowed = "clients" in set([p.name.replace(" ", "-").lower() for r in user.roles for p in r.permissions]) if allowed: return True, 0 elif client is None: @@ -109,16 +101,14 @@ async def get_current_user( if security_scopes.scopes: authenticate_value = f'Bearer scope="{security_scopes.scope_str}"' else: - authenticate_value = f"Bearer" + authenticate_value = "Bearer" credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": authenticate_value}, ) try: - payload = jwt.decode( - token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM] - ) + payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]) username: str = payload.get("sub") if username is None: raise credentials_exception diff --git a/brewman/brewman/core/session.py b/brewman/brewman/core/session.py index 540d7105..13abcd87 100644 --- a/brewman/brewman/core/session.py +++ b/brewman/brewman/core/session.py @@ -26,9 +26,7 @@ def get_finish_date(session): def set_period(start, finish, session): session["start"] = start if isinstance(start, str) else start.strftime("%d-%b-%Y") - session["finish"] = ( - finish if isinstance(finish, str) else finish.strftime("%d-%b-%Y") - ) + session["finish"] = finish if isinstance(finish, str) else finish.strftime("%d-%b-%Y") def get_first_day(dt, d_years=0, d_months=0): diff --git a/brewman/brewman/db/base.py b/brewman/brewman/db/base.py index d78bb5d3..4df5f1f5 100644 --- a/brewman/brewman/db/base.py +++ b/brewman/brewman/db/base.py @@ -1,8 +1,8 @@ # Import all the models, so that Base has them before being # imported by Alembic -from brewman.db.base_class import Base # noqa -from brewman.models import Account # noqa -from brewman.models import ( +from brewman.db.base_class import Base # noqa: F401 +from brewman.models import Account # noqa: F401 +from brewman.models import ( # noqa: F401 AccountBase, AccountType, Attendance, diff --git a/brewman/brewman/main.py b/brewman/brewman/main.py index 3bd2ced1..39f561f3 100644 --- a/brewman/brewman/main.py +++ b/brewman/brewman/main.py @@ -68,28 +68,16 @@ app.include_router(login.router, tags=["login"]) app.include_router(account.router, prefix="/api/accounts", tags=["accounts"]) app.include_router(account_types.router, prefix="/api/account-types", tags=["accounts"]) app.include_router(attendance.router, prefix="/api/attendance", tags=["attendance"]) -app.include_router( - attendance_types.router, prefix="/api/attendance-types", tags=["attendance"] -) -app.include_router( - employee_attendance.router, prefix="/api/employee-attendance", tags=["attendance"] -) -app.include_router( - employee_attendance.router, prefix="/api/employee-attendance", tags=["attendance"] -) -app.include_router( - attendance_report.router, prefix="/attendance-report", tags=["attendance"] -) +app.include_router(attendance_types.router, prefix="/api/attendance-types", tags=["attendance"]) +app.include_router(employee_attendance.router, prefix="/api/employee-attendance", tags=["attendance"]) +app.include_router(employee_attendance.router, prefix="/api/employee-attendance", tags=["attendance"]) +app.include_router(attendance_report.router, prefix="/attendance-report", tags=["attendance"]) -app.include_router( - cost_centre.router, prefix="/api/cost-centres", tags=["cost-centres"] -) +app.include_router(cost_centre.router, prefix="/api/cost-centres", tags=["cost-centres"]) app.include_router(employee.router, prefix="/api/employees", tags=["employees"]) app.include_router(fingerprint.router, prefix="/api/fingerprint", tags=["employees"]) app.include_router(product.router, prefix="/api/products", tags=["products"]) -app.include_router( - product_group.router, prefix="/api/product-groups", tags=["products"] -) +app.include_router(product_group.router, prefix="/api/product-groups", tags=["products"]) app.include_router(recipe.router, prefix="/api/recipes", tags=["products"]) app.include_router(client.router, prefix="/api/clients", tags=["clients"]) @@ -102,23 +90,13 @@ app.include_router(profit_loss.router, prefix="/api/profit-loss", tags=["reports app.include_router(closing_stock.router, prefix="/api/closing-stock", tags=["reports"]) app.include_router(cash_flow.router, prefix="/api/cash-flow", tags=["reports"]) app.include_router(daybook.router, prefix="/api/daybook", tags=["reports"]) -app.include_router( - net_transactions.router, prefix="/api/net-transactions", tags=["reports"] -) -app.include_router( - product_ledger.router, prefix="/api/product-ledger", tags=["reports"] -) -app.include_router( - purchase_entries.router, prefix="/api/purchase-entries", tags=["reports"] -) +app.include_router(net_transactions.router, prefix="/api/net-transactions", tags=["reports"]) +app.include_router(product_ledger.router, prefix="/api/product-ledger", tags=["reports"]) +app.include_router(purchase_entries.router, prefix="/api/purchase-entries", tags=["reports"]) app.include_router(purchases.router, prefix="/api/purchases", tags=["reports"]) -app.include_router( - raw_material_cost.router, prefix="/api/raw-material-cost", tags=["reports"] -) +app.include_router(raw_material_cost.router, prefix="/api/raw-material-cost", tags=["reports"]) app.include_router(reconcile.router, prefix="/api/reconcile", tags=["reports"]) -app.include_router( - stock_movement.router, prefix="/api/stock-movement", tags=["reports"] -) +app.include_router(stock_movement.router, prefix="/api/stock-movement", tags=["reports"]) app.include_router(trial_balance.router, prefix="/api/trial-balance", tags=["reports"]) app.include_router(unposted.router, prefix="/api/unposted", tags=["reports"]) @@ -128,20 +106,14 @@ app.include_router(journal.router, prefix="/api/journal", tags=["vouchers"]) app.include_router(journal.router, prefix="/api/payment", tags=["vouchers"]) app.include_router(journal.router, prefix="/api/receipt", tags=["vouchers"]) app.include_router(purchase.router, prefix="/api/purchase", tags=["vouchers"]) -app.include_router( - purchase_return.router, prefix="/api/purchase-return", tags=["vouchers"] -) +app.include_router(purchase_return.router, prefix="/api/purchase-return", tags=["vouchers"]) app.include_router(issue.router, prefix="/api/issue", tags=["vouchers"]) -app.include_router( - employee_benefit.router, prefix="/api/employee-benefit", tags=["vouchers"] -) +app.include_router(employee_benefit.router, prefix="/api/employee-benefit", tags=["vouchers"]) app.include_router(incentive.router, prefix="/api/incentive", tags=["vouchers"]) app.include_router(credit_salary.router, prefix="/api/credit-salary", tags=["vouchers"]) app.include_router(voucher.router, prefix="/api", tags=["vouchers"]) -app.include_router( - lock_information.router, prefix="/api/lock-information", tags=["settings"] -) +app.include_router(lock_information.router, prefix="/api/lock-information", tags=["settings"]) app.include_router(maintenance.router, prefix="/api/maintenance", tags=["settings"]) app.include_router(db_integrity.router, prefix="/api/db-integrity", tags=["management"]) diff --git a/brewman/brewman/models/__init__.py b/brewman/brewman/models/__init__.py index a17277f6..746ad16f 100644 --- a/brewman/brewman/models/__init__.py +++ b/brewman/brewman/models/__init__.py @@ -1,4 +1,4 @@ -from .auth import ( +from .auth import ( # noqa: F401 Client, LoginHistory, Permission, @@ -7,7 +7,7 @@ from .auth import ( role_permission, user_role, ) -from .master import ( +from .master import ( # noqa: F401 Account, AccountBase, AccountType, @@ -19,14 +19,13 @@ from .master import ( Recipe, RecipeItem, ) -from .voucher import ( +from .voucher import ( # noqa: F401 Attendance, Batch, EmployeeBenefit, Fingerprint, Inventory, Journal, - Product, Voucher, VoucherType, ) diff --git a/brewman/brewman/models/auth.py b/brewman/brewman/models/auth.py index f3ebb26d..443b6340 100644 --- a/brewman/brewman/models/auth.py +++ b/brewman/brewman/models/auth.py @@ -7,7 +7,7 @@ from hashlib import md5 from sqlalchemy import Boolean, Column, DateTime, Integer, Unicode, UniqueConstraint from sqlalchemy.dialects.postgresql import UUID -from sqlalchemy.orm import Session, relationship, synonym +from sqlalchemy.orm import relationship, synonym from sqlalchemy.schema import ForeignKey, Table from .meta import Base @@ -42,18 +42,14 @@ class Client(Base): self.name = name self.enabled = enabled self.otp = otp - self.creation_date = ( - datetime.utcnow() if creation_date is None else creation_date - ) + self.creation_date = datetime.utcnow() if creation_date is None else creation_date self.id = id_ @classmethod def create(cls, dbsession): client_code = random.randint(1000, 9999) otp = random.randint(1000, 9999) - name = "".join( - random.choice(string.ascii_uppercase + string.digits) for x in range(6) - ) + name = "".join(random.choice(string.ascii_uppercase + string.digits) for x in range(6)) client = Client(client_code, name, False, otp) dbsession.add(client) return client @@ -122,12 +118,8 @@ class User(Base): class LoginHistory(Base): __tablename__ = "auth_login_history" __table_args__ = (UniqueConstraint("user_id", "client_id", "date"),) - id = Column( - "login_history_id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4 - ) - user_id = Column( - "user_id", UUID(as_uuid=True), ForeignKey("auth_users.id"), nullable=False - ) + id = Column("login_history_id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + user_id = Column("user_id", UUID(as_uuid=True), ForeignKey("auth_users.id"), nullable=False) client_id = Column( "client_id", UUID(as_uuid=True), diff --git a/brewman/brewman/models/master.py b/brewman/brewman/models/master.py index a0079275..af16728a 100644 --- a/brewman/brewman/models/master.py +++ b/brewman/brewman/models/master.py @@ -37,9 +37,7 @@ class Product(Base): ForeignKey("product_groups.id"), nullable=False, ) - account_id = Column( - "account_id", UUID(as_uuid=True), ForeignKey("accounts.id"), nullable=False - ) + account_id = Column("account_id", UUID(as_uuid=True), ForeignKey("accounts.id"), nullable=False) price = Column("cost_price", Numeric, nullable=False) sale_price = Column("sale_price", Numeric, nullable=False) is_active = Column("is_active", Boolean, nullable=False) @@ -50,9 +48,7 @@ class Product(Base): batches = relationship("Batch", backref="product") inventories = relationship("Inventory", backref="product") recipes = relationship("Recipe", backref="product") - account = relationship( - "Account", primaryjoin="Account.id==Product.account_id", backref="products" - ) + account = relationship("Account", primaryjoin="Account.id==Product.account_id", backref="products") def __init__( self, @@ -129,9 +125,7 @@ class Recipe(Base): __tablename__ = "recipes" id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) - product_id = Column( - "product_id", UUID(as_uuid=True), ForeignKey("products.id"), nullable=False - ) + product_id = Column("product_id", UUID(as_uuid=True), ForeignKey("products.id"), nullable=False) quantity = Column("quantity", Numeric, nullable=False) cost_price = Column("cost_price", Numeric, nullable=False) @@ -174,23 +168,15 @@ class RecipeItem(Base): __tablename__ = "recipe_items" __table_args__ = (UniqueConstraint("recipe_id", "product_id"),) - id = Column( - "recipe_item_id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4 - ) - recipe_id = Column( - "recipe_id", UUID(as_uuid=True), ForeignKey("recipes.id"), nullable=False - ) - product_id = Column( - "product_id", UUID(as_uuid=True), ForeignKey("products.id"), nullable=False - ) + id = Column("recipe_item_id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) + recipe_id = Column("recipe_id", UUID(as_uuid=True), ForeignKey("recipes.id"), nullable=False) + product_id = Column("product_id", UUID(as_uuid=True), ForeignKey("products.id"), nullable=False) quantity = Column("quantity", Integer, nullable=False) price = Column("price", Integer, nullable=False) product = relationship("Product") - def __init__( - self, recipe_id=None, product_id=None, quantity=None, price=None, id_=None - ): + def __init__(self, recipe_id=None, product_id=None, quantity=None, price=None, id_=None): self.recipe_id = recipe_id self.product_id = product_id self.quantity = quantity @@ -330,11 +316,7 @@ class AccountBase(Base): return query_.order_by(cls.name) def create(self, db: Session): - code = ( - db.query(func.max(AccountBase.code)) - .filter(AccountBase.type == self.type) - .one()[0] - ) + code = db.query(func.max(AccountBase.code)).filter(AccountBase.type == self.type).one()[0] self.code = 1 if code is None else code + 1 db.add(self) return self @@ -350,11 +332,7 @@ class AccountBase(Base): @classmethod def get_code(cls, type_, db: Session): - code = ( - db.query(func.max(AccountBase.code)) - .filter(AccountBase.type == type_) - .one()[0] - ) + code = db.query(func.max(AccountBase.code)).filter(AccountBase.type == type_).one()[0] return 1 if code is None else code + 1 @classmethod @@ -409,12 +387,8 @@ class Employee(AccountBase): joining_date = Column("joining_date", Date, nullable=False) leaving_date = Column("leaving_date", Date, nullable=True) - attendances = relationship( - "Attendance", backref="employee", cascade=None, cascade_backrefs=False - ) - fingerprints = relationship( - "Fingerprint", backref="employee", cascade=None, cascade_backrefs=False - ) + attendances = relationship("Attendance", backref="employee", cascade=None, cascade_backrefs=False) + fingerprints = relationship("Fingerprint", backref="employee", cascade=None, cascade_backrefs=False) def __init__( self, @@ -445,11 +419,7 @@ class Employee(AccountBase): ) def create(self, db: Session): - code = ( - db.query(func.max(AccountBase.code)) - .filter(AccountBase.type == self.type) - .one()[0] - ) + code = db.query(func.max(AccountBase.code)).filter(AccountBase.type == self.type).one()[0] self.code = 1 if code is None else code + 1 self.name += f" ({str(self.code)})" db.add(self) diff --git a/brewman/brewman/models/operations.py b/brewman/brewman/models/operations.py deleted file mode 100644 index a805361a..00000000 --- a/brewman/brewman/models/operations.py +++ /dev/null @@ -1,133 +0,0 @@ -from brewman.models.master import CostCentre -from fastapi import HTTPException, status - - -def validate(voucher): - journals_valid(voucher) - if voucher.type in [2, 3, 6]: - inventory_valid(voucher) - if voucher.id is None and voucher.type == 3: - # Issue - issue_new(voucher) - if voucher.id is None and voucher.type == 6: - # Purchase Return - purchase_return_new(voucher) - if voucher.id is not None and voucher.type == 3: - # Issue - issue_update(voucher) - if voucher.id is not None and voucher.type == 6: - # Purchase Return - purchase_return_update(voucher) - - -def check_batch_insert(voucher): - if voucher.type == 9: - raise HTTPException( - status_code=status.HTTP_410_GONE, - detail="Verification Vouchers have been disabled", - ) - if voucher.type == 6: - # Purchase Return - for item in voucher.inventories: - batch = item.batch - if batch.quantity_remaining < item.quantity: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"Quantity of {item.product.name} ({item.product.units}) cannot be more than {batch.quantity_remaining}", - ) - if voucher.type == 3: - # Issue - purchase = None - for item in voucher.journals: - if item.cost_centre_id == CostCentre.cost_centre_purchase(): - purchase = item - if purchase is None: - return - if purchase.debit == 1: - return - for item in voucher.inventories: - batch = item.batch - if batch.quantity_remaining < item.quantity: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"Quantity of {item.product.name} ({item.product.units}) cannot be more than {batch.quantity_remaining}", - ) - if voucher.type == 2: - # Purchase - pass - - -def issue_new(voucher): - consuming = filter( - lambda x: x.cost_centre_id == CostCentre.cost_centre_purchase(), - voucher.journals, - ) - if not len(consuming): - consuming = False - elif consuming[0].debit == 1: - consuming = False - else: - consuming = True - - if not consuming: - return - - for item in voucher.inventories: - batch = item.batch - if batch.quantity_remaining < item.quantity: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"Quantity of {item.product.name} ({item.product.units}) cannot be more than {batch.quantity_remaining}", - ) - - -def issue_update(voucher): - consuming = filter( - lambda x: x.cost_centre_id == CostCentre.cost_centre_purchase(), - voucher.journals, - ) - if not len(consuming): - consuming = False - elif consuming[0].debit == 1: - consuming == False - else: - consuming == True - - if not consuming: - return - - for item in voucher.inventories: - batch = item.batch - if batch.quantity_remaining < item.quantity: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"Quantity of {item.product.name} ({item.product.units}) cannot be more than {batch.quantity_remaining}", - ) - - -def purchase_return_new(voucher): - for item in voucher.inventories: - batch = item.batch - if batch.quantity_remaining < item.quantity: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"Quantity of {item.product.name} ({item.product.units}) cannot be more than {batch.quantity_remaining}", - ) - - -def purchase_return_update(voucher): - for item in voucher.inventories: - batch = item.batch - if batch.quantity_remaining < item.quantity: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"Quantity of {item.product.name} ({item.product.units}) cannot be more than {batch.quantity_remaining}", - ) - - -def batch_valid(voucher): - pass - - -def is_date_allowed(voucher): - pass diff --git a/brewman/brewman/models/validations.py b/brewman/brewman/models/validations.py new file mode 100644 index 00000000..13915fda --- /dev/null +++ b/brewman/brewman/models/validations.py @@ -0,0 +1,45 @@ +from typing import Union + +import brewman.schemas.input as schema_in +import brewman.schemas.voucher as schema + +from brewman.models import Voucher +from fastapi import HTTPException, status + + +def check_journals_are_valid(voucher: Voucher): + if len(voucher.journals) < 2: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Not enough journals", + ) + if sum(x.debit * round(x.amount, 2) for x in voucher.journals) != 0: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Journal amounts do no match", + ) + if len([x for x in voucher.journals if x.amount < 0]) > 0: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Journal amounts cannot be negative", + ) + journal_set = set(hash(x.account_id) ^ hash(x.cost_centre_id) for x in voucher.journals) + if len(voucher.journals) != len(journal_set): + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Duplicate journals are not allowed", + ) + + +def check_inventories_are_valid(voucher: Union[Voucher, schema.Voucher, schema_in.JournalIn]): + if len(voucher.inventories) < 1: + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Not enough inventories", + ) + product_set = set(x.product_id for x in voucher.inventories) + if len(voucher.inventories) != len(product_set): + raise HTTPException( + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, + detail="Duplicate journals are not allowed", + ) diff --git a/brewman/brewman/models/voucher.py b/brewman/brewman/models/voucher.py index eb378039..7df7de72 100644 --- a/brewman/brewman/models/voucher.py +++ b/brewman/brewman/models/voucher.py @@ -72,16 +72,12 @@ class Voucher(Base): creation_date = Column("creation_date", DateTime(timezone=True), nullable=False) last_edit_date = Column("last_edit_date", DateTime(timezone=True), nullable=False) _type = Column("voucher_type", Integer, nullable=False) - user_id = Column( - "user_id", UUID(as_uuid=True), ForeignKey("auth_users.id"), nullable=False - ) + user_id = Column("user_id", UUID(as_uuid=True), ForeignKey("auth_users.id"), nullable=False) posted = Column("is_posted", Boolean, nullable=False) poster_id = Column("poster_id", UUID(as_uuid=True), ForeignKey("auth_users.id")) user = relationship("User", primaryjoin="User.id==Voucher.user_id", cascade=None) - poster = relationship( - "User", primaryjoin="User.id==Voucher.poster_id", cascade=None - ) + poster = relationship("User", primaryjoin="User.id==Voucher.poster_id", cascade=None) journals = relationship( "Journal", @@ -164,9 +160,7 @@ class Journal(Base): nullable=False, index=True, ) - account_id = Column( - "account_id", UUID(as_uuid=True), ForeignKey("accounts.id"), nullable=False - ) + account_id = Column("account_id", UUID(as_uuid=True), ForeignKey("accounts.id"), nullable=False) cost_centre_id = Column( "cost_centre_id", UUID(as_uuid=True), @@ -205,12 +199,8 @@ class Journal(Base): class EmployeeBenefit(Base): __tablename__ = "employee_benefit" id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) - voucher_id = Column( - "voucher_id", UUID(as_uuid=True), ForeignKey("vouchers.id"), nullable=False - ) - journal_id = Column( - "journal_id", UUID(as_uuid=True), ForeignKey("journals.id"), nullable=False - ) + voucher_id = Column("voucher_id", UUID(as_uuid=True), ForeignKey("vouchers.id"), nullable=False) + journal_id = Column("journal_id", UUID(as_uuid=True), ForeignKey("journals.id"), nullable=False) gross_salary = Column("gross_salary", Integer) days_worked = Column("days_worked", Integer) esi_ee = Column("esi_employee", Integer) @@ -255,12 +245,8 @@ class EmployeeBenefit(Base): class Incentive(Base): __tablename__ = "incentives" id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) - voucher_id = Column( - "voucher_id", UUID(as_uuid=True), ForeignKey("vouchers.id"), nullable=False - ) - journal_id = Column( - "journal_id", UUID(as_uuid=True), ForeignKey("journals.id"), nullable=False - ) + voucher_id = Column("voucher_id", UUID(as_uuid=True), ForeignKey("vouchers.id"), nullable=False) + journal_id = Column("journal_id", UUID(as_uuid=True), ForeignKey("journals.id"), nullable=False) days_worked = Column("days_worked", Numeric(precision=5, scale=1), nullable=False) points = Column("points", Numeric(precision=5, scale=2), nullable=False) @@ -301,12 +287,8 @@ class Inventory(Base): nullable=False, index=True, ) - product_id = Column( - "product_id", UUID(as_uuid=True), ForeignKey("products.id"), nullable=False - ) - batch_id = Column( - "batch_id", UUID(as_uuid=True), ForeignKey("batches.id"), nullable=False - ) + product_id = Column("product_id", UUID(as_uuid=True), ForeignKey("products.id"), nullable=False) + batch_id = Column("batch_id", UUID(as_uuid=True), ForeignKey("batches.id"), nullable=False) quantity = Column("quantity", Numeric) rate = Column("rate", Numeric) tax = Column("tax", Numeric) @@ -352,17 +334,13 @@ class Batch(Base): id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) name = Column("name", Date, nullable=False) - product_id = Column( - "product_id", UUID(as_uuid=True), ForeignKey("products.id"), nullable=False - ) + product_id = Column("product_id", UUID(as_uuid=True), ForeignKey("products.id"), nullable=False) quantity_remaining = Column("quantity_remaining", Numeric) rate = Column("rate", Numeric) tax = Column("tax", Numeric) discount = Column("discount", Numeric) - inventories = relationship( - "Inventory", backref="batch", cascade=None, cascade_backrefs=False - ) + inventories = relationship("Inventory", backref="batch", cascade=None, cascade_backrefs=False) def __init__( self, @@ -386,9 +364,7 @@ class Batch(Base): self.product = product def amount(self): - return ( - self.quantity_remaining * self.rate * (1 + self.tax) * (1 - self.discount) - ) + return self.quantity_remaining * self.rate * (1 + self.tax) * (1 - self.discount) @classmethod def list(cls, q, include_nil, date, db: Session): @@ -446,7 +422,7 @@ class Attendance(Base): db.query(Attendance) .filter(Attendance.date == self.date) .filter(Attendance.employee_id == self.employee_id) - .filter(Attendance.is_valid == True) + .filter(Attendance.is_valid == True) # noqa: E712 .first() ) if old is None or old.attendance_type != self.attendance_type: diff --git a/brewman/brewman/routers/__init__.py b/brewman/brewman/routers/__init__.py index 6f8d7aa7..4ae5d60b 100644 --- a/brewman/brewman/routers/__init__.py +++ b/brewman/brewman/routers/__init__.py @@ -3,17 +3,11 @@ import uuid from datetime import date, timedelta from decimal import Decimal -from io import BytesIO from typing import Optional -from fastapi import APIRouter from sqlalchemy.orm import Session from ..models.master import DbSetting -from ..models.voucher import DbImage - - -router = APIRouter() def get_lock_info(db: Session) -> (Optional[date], Optional[date]): @@ -41,9 +35,7 @@ def get_lock_info(db: Session) -> (Optional[date], Optional[date]): def to_uuid(value): - p = re.compile( - "^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$" - ) + p = re.compile("^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$") return uuid.UUID(value) if p.match(value) else None diff --git a/brewman/brewman/routers/account.py b/brewman/brewman/routers/account.py index 6008bed7..d0a76be5 100644 --- a/brewman/brewman/routers/account.py +++ b/brewman/brewman/routers/account.py @@ -133,11 +133,7 @@ async def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get "costCentre": item.cost_centre.name, "isFixture": item.is_fixture, } - for item in db.query(Account) - .order_by(Account.type) - .order_by(Account.name) - .order_by(Account.code) - .all() + for item in db.query(Account).order_by(Account.type).order_by(Account.name).order_by(Account.code).all() ] @@ -190,11 +186,7 @@ def balance(id_: uuid.UUID, date, db: Session): if date is not None: bal = bal.filter(Voucher.date <= date) - bal = ( - bal.filter(Voucher.type != VoucherType.by_name("Issue").id) - .filter(Journal.account_id == id_) - .scalar() - ) + bal = bal.filter(Voucher.type != VoucherType.by_name("Issue").id).filter(Journal.account_id == id_).scalar() return 0 if bal is None else bal @@ -226,9 +218,7 @@ def account_info(item: Optional[Account]): def delete_with_data(account: Account, db: Session): - suspense_account = ( - db.query(Account).filter(Account.id == Account.suspense()).first() - ) + suspense_account = db.query(Account).filter(Account.id == Account.suspense()).first() query: List[Voucher] = ( db.query(Voucher) .options(joinedload_all(Voucher.journals, Journal.account, innerjoin=True)) @@ -250,13 +240,9 @@ def delete_with_data(account: Account, db: Session): else: if sus_jnl is None: acc_jnl.account = suspense_account - voucher.narration += ( - f"\nSuspense \u20B9{acc_jnl.amount:,.2f} is {account.name}" - ) + voucher.narration += f"\nSuspense \u20B9{acc_jnl.amount:,.2f} is {account.name}" else: - amount = (sus_jnl.debit * sus_jnl.amount) + ( - acc_jnl.debit * acc_jnl.amount - ) + amount = (sus_jnl.debit * sus_jnl.amount) + (acc_jnl.debit * acc_jnl.amount) db.delete(acc_jnl) if amount == 0: db.delete(sus_jnl) diff --git a/brewman/brewman/routers/account_types.py b/brewman/brewman/routers/account_types.py index d44de7dc..88c02f4c 100644 --- a/brewman/brewman/routers/account_types.py +++ b/brewman/brewman/routers/account_types.py @@ -14,6 +14,4 @@ router = APIRouter() @router.get("", response_model=List[schemas.AccountType]) def account_type_list(user: UserToken = Depends(get_user)): - return [ - schemas.AccountType(id=item.id, name=item.name) for item in AccountType.list() - ] + return [schemas.AccountType(id=item.id, name=item.name) for item in AccountType.list()] diff --git a/brewman/brewman/routers/attendance.py b/brewman/brewman/routers/attendance.py index 05be1c3c..ce8ae89c 100644 --- a/brewman/brewman/routers/attendance.py +++ b/brewman/brewman/routers/attendance.py @@ -29,9 +29,7 @@ def get_db() -> Session: @router.get("", response_model=schemas.Attendance) -def attendance_blank( - request: Request, user: UserToken = Security(get_user, scopes=["attendance"]) -): +def attendance_blank(request: Request, user: UserToken = Security(get_user, scopes=["attendance"])): return {"date": get_date(request.session), "body": []} @@ -70,7 +68,7 @@ def attendance_date_report(date_: date, db: Session): db.query(Attendance) .filter(Attendance.employee_id == item.id) .filter(Attendance.date == date_) - .filter(Attendance.is_valid == True) + .filter(Attendance.is_valid == True) # noqa: E712 .first() ) att = 0 if att is None else att.attendance_type diff --git a/brewman/brewman/routers/attendance_report.py b/brewman/brewman/routers/attendance_report.py index fca892f7..2ae91d56 100644 --- a/brewman/brewman/routers/attendance_report.py +++ b/brewman/brewman/routers/attendance_report.py @@ -41,9 +41,7 @@ def get_report( output, db, ) - headers = { - "Content-Disposition": "attachment; filename = 'attendance-record.csv'" - } + headers = {"Content-Disposition": "attachment; filename = 'attendance-record.csv'"} output.seek(0) return StreamingResponse(output, media_type="text/csv", headers=headers) finally: @@ -83,7 +81,7 @@ def attendance_record(start_date: date, finish_date: date, output, db: Session): db.query(Attendance) .filter(Attendance.employee_id == employee.id) .filter(Attendance.date == date_) - .filter(Attendance.is_valid == True) + .filter(Attendance.is_valid == True) # noqa: E712 .first() ) att = not_set if att is None else AttendanceType.by_id(att.attendance_type) diff --git a/brewman/brewman/routers/auth/client.py b/brewman/brewman/routers/auth/client.py index 16ee2237..fee90668 100644 --- a/brewman/brewman/routers/auth/client.py +++ b/brewman/brewman/routers/auth/client.py @@ -83,16 +83,9 @@ async def show_list( clients = [] for item in list_: last_login = ( - db.query(LoginHistory) - .filter(LoginHistory.client_id == item.id) - .order_by(desc(LoginHistory.date)) - .first() - ) - last_login = ( - "Never" - if last_login is None - else last_login.date.strftime("%d-%b-%Y %H:%M") + db.query(LoginHistory).filter(LoginHistory.client_id == item.id).order_by(desc(LoginHistory.date)).first() ) + last_login = "Never" if last_login is None else last_login.date.strftime("%d-%b-%Y %H:%M") clients.append( { "id": item.id, diff --git a/brewman/brewman/routers/auth/role.py b/brewman/brewman/routers/auth/role.py index cbfb4bb0..d32c8897 100644 --- a/brewman/brewman/routers/auth/role.py +++ b/brewman/brewman/routers/auth/role.py @@ -78,9 +78,7 @@ def add_permissions(role: Role, permissions: List[schemas.PermissionItem], db): gp = [p for p in role.permissions if p.id == permission.id_] gp = None if len(gp) == 0 else gp[0] if permission.enabled and gp is None: - role.permissions.append( - db.query(Permission).filter(Permission.id == permission.id_).one() - ) + role.permissions.append(db.query(Permission).filter(Permission.id == permission.id_).one()) elif not permission.enabled and gp: role.permissions.remove(gp) @@ -125,9 +123,7 @@ async def show_list( { "id": item.id, "name": item.name, - "permissions": [ - p.name for p in sorted(item.permissions, key=lambda p: p.name) - ], + "permissions": [p.name for p in sorted(item.permissions, key=lambda p: p.name)], } for item in db.query(Role).order_by(Role.name).all() ] diff --git a/brewman/brewman/routers/auth/user.py b/brewman/brewman/routers/auth/user.py index 55e3241c..76ad54a7 100644 --- a/brewman/brewman/routers/auth/user.py +++ b/brewman/brewman/routers/auth/user.py @@ -170,12 +170,10 @@ async def show_list( @router.get("/active") -async def show_active( - db: Session = Depends(get_db), user: UserToken = Depends(get_user) -): +async def show_active(db: Session = Depends(get_db), user: UserToken = Depends(get_user)): return [ {"name": item.name} - for item in db.query(User).filter(User.locked_out == False).order_by(User.name) + for item in db.query(User).filter(User.locked_out == False).order_by(User.name) # noqa: E712 ] @@ -194,10 +192,7 @@ def user_info(item: Optional[User], db: Session, user: UserToken): return { "name": "", "lockedOut": False, - "roles": [ - {"id": r.id, "name": r.name, "enabled": False} - for r in db.query(Role).order_by(Role.name).all() - ], + "roles": [{"id": r.id, "name": r.name, "enabled": False} for r in db.query(Role).order_by(Role.name).all()], } else: return { diff --git a/brewman/brewman/routers/batch.py b/brewman/brewman/routers/batch.py index 82b8aa02..9f94e1ed 100644 --- a/brewman/brewman/routers/batch.py +++ b/brewman/brewman/routers/batch.py @@ -32,7 +32,10 @@ def batch_term( date = None if not d else datetime.datetime.strptime(d, "%d-%b-%Y") list_ = [] for index, item in enumerate(Batch.list(q, include_nil=False, date=date, db=db)): - text = f"{item.product.name} ({item.product.units}) {item.quantity_remaining:.2f}@{item.rate:.2f} from {item.name.strftime('%d-%b-%Y')}" + text = ( + f"{item.product.name} ({item.product.units}) {item.quantity_remaining:.2f}@" + f"{item.rate:.2f} from {item.name.strftime('%d-%b-%Y')}" + ) list_.append( { "id": item.id, diff --git a/brewman/brewman/routers/credit_salary.py b/brewman/brewman/routers/credit_salary.py index 98bbce04..8486f8bb 100644 --- a/brewman/brewman/routers/credit_salary.py +++ b/brewman/brewman/routers/credit_salary.py @@ -70,7 +70,7 @@ def salary_journals(start_date: date, finish_date: date, db: Session): .filter(Attendance.employee_id == employee.id) .filter(Attendance.date >= start_date) .filter(Attendance.date <= finish_date) - .filter(Attendance.is_valid == True) + .filter(Attendance.is_valid == True) # noqa: E712 .all() ) att = sum(map(lambda x: AttendanceType.by_id(x.attendance_type).value, att)) diff --git a/brewman/brewman/routers/db_image.py b/brewman/brewman/routers/db_image.py index 54a56ed5..1f155f0b 100644 --- a/brewman/brewman/routers/db_image.py +++ b/brewman/brewman/routers/db_image.py @@ -5,14 +5,12 @@ from typing import List import brewman.schemas.voucher as output -from fastapi import APIRouter, Depends, Security +from fastapi import APIRouter, Depends from fastapi.responses import StreamingResponse from sqlalchemy.orm import Session -from ..core.security import get_user from ..db.session import SessionLocal from ..models.voucher import DbImage -from ..schemas.auth import UserToken router = APIRouter() diff --git a/brewman/brewman/routers/db_integrity.py b/brewman/brewman/routers/db_integrity.py index 423f8144..d5a24d92 100644 --- a/brewman/brewman/routers/db_integrity.py +++ b/brewman/brewman/routers/db_integrity.py @@ -40,13 +40,13 @@ def get_duplicate_attendances(db): partition_by=[Attendance.employee_id, Attendance.date], ) ) - .filter(Attendance.is_valid == True) + .filter(Attendance.is_valid == True) # noqa: E712 .subquery() ) query = ( db.query(func.count(Attendance.id)) .filter(~Attendance.id.in_(sub_query)) - .filter(Attendance.is_valid == True) + .filter(Attendance.is_valid == True) # noqa: E712 ) return query.scalar() @@ -60,9 +60,7 @@ def fix_duplicate_attendances(db): order_by=desc(Attendance.creation_date), ) ) - .filter(Attendance.is_valid == True) + .filter(Attendance.is_valid == True) # noqa: E712 .subquery() ) - db.query(Attendance).filter(~Attendance.id.in_(sub)).filter( - Attendance.is_valid == True - ).delete(False) + db.query(Attendance).filter(~Attendance.id.in_(sub)).filter(Attendance.is_valid == True).delete(False) # noqa: E712 diff --git a/brewman/brewman/routers/employee.py b/brewman/brewman/routers/employee.py index a2087b9d..42939c27 100644 --- a/brewman/brewman/routers/employee.py +++ b/brewman/brewman/routers/employee.py @@ -134,9 +134,7 @@ async def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get "isActive": item.is_active, "costCentre": item.cost_centre.name, "joiningDate": item.joining_date.strftime("%d-%b-%Y"), - "leavingDate": "" - if item.is_active - else item.leaving_date.strftime("%d-%b-%Y"), + "leavingDate": "" if item.is_active else item.leaving_date.strftime("%d-%b-%Y"), "isStarred": item.is_starred, } for item in db.query(Employee) @@ -207,9 +205,7 @@ def employee_info(id_, db): "salary": employee.salary, "points": employee.points, "joiningDate": employee.joining_date.strftime("%d-%b-%Y"), - "leavingDate": None - if employee.is_active - else employee.leaving_date.strftime("%d-%b-%Y"), + "leavingDate": None if employee.is_active else employee.leaving_date.strftime("%d-%b-%Y"), "costCentre": { "id": employee.cost_centre_id, "name": employee.cost_centre.name, @@ -220,9 +216,7 @@ def employee_info(id_, db): def delete_with_data(employee, db): - suspense_account = ( - db.query(Account).filter(Account.id == Account.suspense()).first() - ) + suspense_account = db.query(Account).filter(Account.id == Account.suspense()).first() query = ( db.query(Voucher) .options(joinedload_all(Voucher.journals, Journal.account, innerjoin=True)) @@ -244,13 +238,9 @@ def delete_with_data(employee, db): else: if sus_jnl is None: acc_jnl.account = suspense_account - voucher.narration += ( - f"\nSuspense \u20B9 {acc_jnl.amount:,.2f} is {employee.name}" - ) + voucher.narration += f"\nSuspense \u20B9 {acc_jnl.amount:,.2f} is {employee.name}" else: - amount = (sus_jnl.debit * sus_jnl.amount) + ( - acc_jnl.debit * acc_jnl.amount - ) + amount = (sus_jnl.debit * sus_jnl.amount) + (acc_jnl.debit * acc_jnl.amount) if acc_jnl.employee_benefit is not None: db.delete(acc_jnl.employee_benefit) db.delete(acc_jnl) diff --git a/brewman/brewman/routers/employee_attendance.py b/brewman/brewman/routers/employee_attendance.py index 82b65495..69575306 100644 --- a/brewman/brewman/routers/employee_attendance.py +++ b/brewman/brewman/routers/employee_attendance.py @@ -66,28 +66,22 @@ def employee_attendance_report( } start_date = datetime.strptime(start_date, "%d-%b-%Y").date() finish_date = datetime.strptime(finish_date, "%d-%b-%Y").date() - start_date = ( - employee.joining_date if employee.joining_date > start_date else start_date - ) + start_date = employee.joining_date if employee.joining_date > start_date else start_date finish_date = ( - employee.leaving_date - if not employee.is_active and employee.leaving_date < finish_date - else finish_date + employee.leaving_date if not employee.is_active and employee.leaving_date < finish_date else finish_date ) info["body"] = employee_attendance(employee, start_date, finish_date, db) return info -def employee_attendance( - employee: Employee, start_date: date, finish_date: date, db: Session -): +def employee_attendance(employee: Employee, start_date: date, finish_date: date, db: Session): list_ = [] for item in date_range(start_date, finish_date, inclusive=True): att = ( db.query(Attendance) .filter(Attendance.employee_id == employee.id) .filter(Attendance.date == item) - .filter(Attendance.is_valid == True) + .filter(Attendance.is_valid == True) # noqa: E712 .first() ) att = 0 if att is None else att.attendance_type diff --git a/brewman/brewman/routers/employee_benefit.py b/brewman/brewman/routers/employee_benefit.py index 8c3c489a..2baa26c9 100644 --- a/brewman/brewman/routers/employee_benefit.py +++ b/brewman/brewman/routers/employee_benefit.py @@ -15,6 +15,7 @@ from ..core.security import get_current_active_user as get_user from ..core.session import get_date, get_last_day, set_date from ..db.session import SessionLocal from ..models import AccountBase, Employee +from ..models.validations import check_journals_are_valid from ..models.voucher import EmployeeBenefit, Journal, Voucher, VoucherType from ..schemas.auth import UserToken from .db_image import save_files, update_files @@ -51,10 +52,9 @@ def save_route( dt = get_last_day(data.date_) days_in_month = dt.day item: Voucher = save(data, dt, user, db) - exp, total = save_employee_benefits( - item, data.employee_benefits, days_in_month, db - ) + exp, total = save_employee_benefits(item, data.employee_benefits, days_in_month, db) save_journals(item, exp, total, db) + check_journals_are_valid(item) save_files(item.id, i, t, db) db.commit() set_date(data.date_.strftime("%d-%b-%Y"), request.session) @@ -71,9 +71,7 @@ def save_route( raise -def save( - data: schema_in.EmployeeBenefitIn, date_: date, user: UserToken, db: Session -) -> Voucher: +def save(data: schema_in.EmployeeBenefitIn, date_: date, user: UserToken, db: Session) -> Voucher: check_voucher_lock_info(None, date_, db) voucher = Voucher( date=date_, @@ -97,12 +95,8 @@ def save_employee_benefits( account = db.query(Employee).filter(Employee.id == item.employee.id_).first() gross_salary = item.gross_salary days_worked = item.days_worked - esi_ee, esi_er, esi_both = esi_contribution( - gross_salary, days_worked, days_in_month - ) - pf_ee, pf_er, pf_both = pf_contribution( - gross_salary, days_worked, days_in_month - ) + esi_ee, esi_er, esi_both = esi_contribution(gross_salary, days_worked, days_in_month) + pf_ee, pf_er, pf_both = pf_contribution(gross_salary, days_worked, days_in_month) journal = Journal( amount=esi_ee + pf_ee, debit=1, @@ -128,11 +122,7 @@ def save_employee_benefits( def save_journals(voucher: Voucher, exp: int, total: int, db: Session): - account = ( - db.query(AccountBase) - .filter(AccountBase.id == AccountBase.esi_pf_expense()) - .first() - ) + account = db.query(AccountBase).filter(AccountBase.id == AccountBase.esi_pf_expense()).first() journal = Journal( amount=exp, debit=1, @@ -141,11 +131,7 @@ def save_journals(voucher: Voucher, exp: int, total: int, db: Session): ) db.add(journal) voucher.journals.append(journal) - account = ( - db.query(AccountBase) - .filter(AccountBase.id == AccountBase.esi_pf_payable()) - .first() - ) + account = db.query(AccountBase).filter(AccountBase.id == AccountBase.esi_pf_payable()).first() journal = Journal( amount=total, debit=-1, @@ -175,11 +161,9 @@ def update_route( status_code=status.HTTP_423_LOCKED, detail="Date Cannot be changed for Employee Benefit voucher!", ) - exp, total = update_employee_benefits( - item, data.employee_benefits, days_in_month, db - ) + exp, total = update_employee_benefits(item, data.employee_benefits, days_in_month, db) update_journals(item, exp, total) - # journals_valid(voucher) + check_journals_are_valid(item) update_files(item.id, data.files, i, t, db) db.commit() set_date(data.date_.strftime("%d-%b-%Y"), request.session) @@ -195,9 +179,7 @@ def update_route( raise -def update( - id_: uuid.UUID, data: schema_in.EmployeeBenefitIn, user: UserToken, db: Session -) -> Voucher: +def update(id_: uuid.UUID, data: schema_in.EmployeeBenefitIn, user: UserToken, db: Session) -> Voucher: voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_edit_allowed(voucher, user) @@ -229,20 +211,14 @@ def update_employee_benefits( if not found: voucher.employee_benefits.remove(item) voucher.journals.remove(item.journal) - new_exp, new_total = save_employee_benefits( - voucher, employee_benefits, days_in_month, db - ) + new_exp, new_total = save_employee_benefits(voucher, employee_benefits, days_in_month, db) return exp + new_exp, total + new_total def update_journals(voucher: Voucher, exp: int, total: int): - journal = next( - i for i in voucher.journals if i.account_id == AccountBase.esi_pf_expense() - ) + journal = next(i for i in voucher.journals if i.account_id == AccountBase.esi_pf_expense()) journal.amount = exp - journal = next( - i for i in voucher.journals if i.account_id == AccountBase.esi_pf_payable() - ) + journal = next(i for i in voucher.journals if i.account_id == AccountBase.esi_pf_payable()) journal.amount = total @@ -280,16 +256,8 @@ def esi_contribution(gross_salary, days_worked, days_in_month): limit = 21000 employee_rate = 0.0175 employer_rate = 0.0475 - employee = ( - 0 - if gross_salary > limit - else ceil(employee_rate * gross_salary * days_worked / days_in_month) - ) - employer = ( - 0 - if gross_salary > limit - else ceil(employer_rate * gross_salary * days_worked / days_in_month) - ) + employee = 0 if gross_salary > limit else ceil(employee_rate * gross_salary * days_worked / days_in_month) + employer = 0 if gross_salary > limit else ceil(employer_rate * gross_salary * days_worked / days_in_month) return employee, employer, employee + employer @@ -297,14 +265,6 @@ def pf_contribution(gross_salary, days_worked, days_in_month): limit = 15000 employee_rate = 0.12 employer_rate = 0.12 + 0.011 + 0.005 + 0.0001 - employee = ( - 0 - if gross_salary > limit - else ceil(employee_rate * gross_salary * days_worked / days_in_month) - ) - employer = ( - 0 - if gross_salary > limit - else ceil(employer_rate * gross_salary * days_worked / days_in_month) - ) + employee = 0 if gross_salary > limit else ceil(employee_rate * gross_salary * days_worked / days_in_month) + employer = 0 if gross_salary > limit else ceil(employer_rate * gross_salary * days_worked / days_in_month) return employee, employer, employee + employer diff --git a/brewman/brewman/routers/fingerprint.py b/brewman/brewman/routers/fingerprint.py index 10c2b25f..9a9dcb1c 100644 --- a/brewman/brewman/routers/fingerprint.py +++ b/brewman/brewman/routers/fingerprint.py @@ -74,9 +74,7 @@ def get_query(version): .on_conflict_do_nothing() ) else: - sel = select( - [bindparam("id"), bindparam("employee_id"), bindparam("date")] - ).where( + sel = select([bindparam("id"), bindparam("employee_id"), bindparam("date")]).where( ~exists([Fingerprint.id]).where( and_( Fingerprint.employee_id == bindparam("employee_id"), @@ -147,9 +145,7 @@ def get_prints(employee_id: uuid.UUID, date_: date, db: Session): db.query(Fingerprint) .filter(Fingerprint.employee_id == employee_id) .filter(Fingerprint.date >= datetime.combine(date_, time(hour=7))) - .filter( - Fingerprint.date < datetime.combine(date_ + timedelta(days=1), time(hour=7)) - ) + .filter(Fingerprint.date < datetime.combine(date_ + timedelta(days=1), time(hour=7))) .order_by(Fingerprint.date) .all() ) @@ -168,9 +164,7 @@ def get_prints(employee_id: uuid.UUID, date_: date, db: Session): time_worked = prints[1].date - prints[0].date hours_worked, full_day = working_hours(time_worked) elif len(prints) == 4: - time_worked = (prints[1].date - prints[0].date) + ( - prints[3].date - prints[2].date - ) + time_worked = (prints[1].date - prints[0].date) + (prints[3].date - prints[2].date) hours_worked, full_day = working_hours(time_worked) else: hours_worked, full_day = "Error", False diff --git a/brewman/brewman/routers/incentive.py b/brewman/brewman/routers/incentive.py index ba19b266..c0960627 100644 --- a/brewman/brewman/routers/incentive.py +++ b/brewman/brewman/routers/incentive.py @@ -16,6 +16,7 @@ from ..core.security import get_current_active_user as get_user from ..core.session import get_date, get_first_day, set_date from ..db.session import SessionLocal from ..models import Account, AttendanceType, Employee +from ..models.validations import check_journals_are_valid from ..models.voucher import Attendance, Incentive, Journal, Voucher, VoucherType from ..schemas.auth import UserToken from .voucher import ( @@ -47,13 +48,12 @@ def save_route( ): try: item: Voucher = save(data, user, db) - employees = get_employees( - get_first_day(data.date_), data.date_, data.incentives, None, db - ) + employees = get_employees(get_first_day(data.date_), data.date_, data.incentives, None, db) amount = balance(data.date_, None, db) * Decimal(0.9) # 10% for Deb Dip total_points = sum(e.points * e.days_worked for e in employees) point_value = round(amount / total_points, 2) save_incentives(item, employees, point_value, db) + check_journals_are_valid(item) db.commit() set_date(data.date_.strftime("%d-%b-%Y"), request.session) info = voucher_info(item, db) @@ -97,9 +97,7 @@ def save_incentives( account_id=item.employee_id, cost_centre_id=item.cost_centre_id, ) - inc = Incentive( - journal=journal, days_worked=item.days_worked, points=item.points - ) + inc = Incentive(journal=journal, days_worked=item.days_worked, points=item.points) voucher.journals.append(journal) voucher.incentives.append(inc) db.add(journal) @@ -107,9 +105,7 @@ def save_incentives( total_amount += item_amount sc = db.query(Account).filter(Account.id == Account.incentive_id()).first() - journal = Journal( - amount=total_amount, debit=1, account_id=sc.id, cost_centre_id=sc.cost_centre_id - ) + journal = Journal(amount=total_amount, debit=1, account_id=sc.id, cost_centre_id=sc.cost_centre_id) voucher.journals.append(journal) db.add(journal) @@ -124,13 +120,12 @@ def update_route( ): try: item: Voucher = update(id_, data, user, db) - employees = get_employees( - get_first_day(data.date_), data.date_, data.incentives, item.journals, db - ) + employees = get_employees(get_first_day(data.date_), data.date_, data.incentives, item.journals, db) amount = balance(data.date_, item.id, db) * Decimal(0.9) # 10% for Deb Dip total_points = sum(e.points * e.days_worked for e in employees) point_value = round(amount / total_points, 2) update_incentives(item, employees, point_value, db) + check_journals_are_valid(item) db.commit() set_date(request.session, data.date_) return voucher_info(item, db) @@ -145,9 +140,7 @@ def update_route( raise -def update( - id_: uuid.UUID, data: schema_in.IncentiveIn, user: UserToken, db: Session -) -> Voucher: +def update(id_: uuid.UUID, data: schema_in.IncentiveIn, user: UserToken, db: Session) -> Voucher: voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_edit_allowed(voucher, user) @@ -167,18 +160,14 @@ def update_incentives( ): total_amount = 0 for item in voucher.incentives: - employee = next( - e for e in employees if e.employee_id == item.journal.account_id - ) + employee = next(e for e in employees if e.employee_id == item.journal.account_id) item_amount = round(employee.points * employee.days_worked * point_value) item.days_worked = employee.days_worked item.points = employee.points item.journal.amount = item_amount total_amount += item_amount - journal = next( - j for j in voucher.journals if j.account_id == Account.incentive_id() - ) + journal = next(j for j in voucher.journals if j.account_id == Account.incentive_id()) journal.amount = total_amount @@ -239,12 +228,10 @@ def get_employees( .filter(Attendance.employee_id == employee.id) .filter(Attendance.date >= start_date) .filter(Attendance.date <= finish_date) - .filter(Attendance.is_valid == True) + .filter(Attendance.is_valid == True) # noqa: E712 .all() ) - att = 0.5 * round( - sum(map(lambda x: AttendanceType.by_id(x.attendance_type).value, att)) / 0.5 - ) + att = 0.5 * round(sum(map(lambda x: AttendanceType.by_id(x.attendance_type).value, att)) / 0.5) points = next(x for x in incentives if x.employee_id == employee.id).points details.append( schema_in.IncentiveEmployee( @@ -279,9 +266,7 @@ def check_if_employees_changed( json = set(x.employee_id for x in json) db = set(x.id for x in db) voucher = ( - set(x.account_id for x in voucher if x.account_id != Account.incentive_id()) - if voucher is not None - else None + set(x.account_id for x in voucher if x.account_id != Account.incentive_id()) if voucher is not None else None ) if voucher is None: if len(json ^ db) != 0: diff --git a/brewman/brewman/routers/issue.py b/brewman/brewman/routers/issue.py index 4c9e2bb7..6fc2842b 100644 --- a/brewman/brewman/routers/issue.py +++ b/brewman/brewman/routers/issue.py @@ -15,6 +15,7 @@ from ..core.security import get_current_active_user as get_user from ..core.session import get_date, set_date from ..db.session import SessionLocal from ..models import AccountBase, CostCentre +from ..models.validations import check_inventories_are_valid, check_journals_are_valid from ..models.voucher import Batch, Inventory, Journal, Voucher, VoucherType from ..schemas.auth import UserToken from .db_image import save_files, update_files @@ -50,7 +51,9 @@ def save_route( try: item, batch_consumed = save(data, user, db) amount = save_inventories(item, data.inventories, batch_consumed, db) + check_inventories_are_valid(item) save_journals(item, data.source, data.destination, amount, db) + check_journals_are_valid(item) save_files(item.id, i, t, db) db.commit() set_date(data.date_.strftime("%d-%b-%Y"), request.session) @@ -67,9 +70,7 @@ def save_route( raise -def save( - data: schema_in.IssueIn, user: UserToken, db: Session -) -> (Voucher, Optional[bool]): +def save(data: schema_in.IssueIn, user: UserToken, db: Session) -> (Voucher, Optional[bool]): check_voucher_lock_info(None, data.date_, db) voucher = Voucher( date=data.date_, @@ -172,7 +173,9 @@ def update_route( try: item, batch_consumed = update(id_, data, user, db) amount = update_inventories(item, data.inventories, batch_consumed, db) + check_inventories_are_valid(item) update_journals(item, data.source, data.destination, amount) + check_journals_are_valid(item) update_files(item.id, data.files, i, t, db) db.commit() set_date(data.date_.strftime("%d-%b-%Y"), request.session) @@ -189,9 +192,7 @@ def update_route( raise -def update( - id_: uuid.UUID, data: schema_in.IssueIn, user: UserToken, db: Session -) -> (Voucher, Optional[bool]): +def update(id_: uuid.UUID, data: schema_in.IssueIn, user: UserToken, db: Session) -> (Voucher, Optional[bool]): voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_edit_allowed(voucher, user) @@ -250,13 +251,11 @@ def update_inventories( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Product / Batch cannot be changed", ) - if ( - batch_consumed - and i.quantity - item.quantity > item.batch.quantity_remaining - ): + if batch_consumed and i.quantity - item.quantity > item.batch.quantity_remaining: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail=f"Maximum quantity available for {item.product.full_name} is {item.quantity + item.batch.quantity_remaining}", + detail=f"Maximum quantity available for {item.product.full_name} " + f"is {item.quantity + item.batch.quantity_remaining}", ) if item.batch.name > voucher.date: raise HTTPException( @@ -288,7 +287,8 @@ def update_inventories( if item.batch.quantity_remaining < item.quantity: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail=f"Product {item.product.name} cannot be removed, minimum quantity is {item.batch.quantity_remaining}", + detail=f"Product {item.product.name} cannot be removed," + f" minimum quantity is {item.batch.quantity_remaining}", ) item.batch.quantity_remaining -= item.quantity db.delete(item) diff --git a/brewman/brewman/routers/issue_grid.py b/brewman/brewman/routers/issue_grid.py index 60bc0e4e..09da3675 100644 --- a/brewman/brewman/routers/issue_grid.py +++ b/brewman/brewman/routers/issue_grid.py @@ -53,12 +53,8 @@ def get_grid(date, db): { "id": str(voucher.id), "amount": amount, - "source": [ - j.cost_centre.name for j in voucher.journals if j.debit == -1 - ], - "destination": [ - j.cost_centre.name for j in voucher.journals if j.debit == 1 - ], + "source": [j.cost_centre.name for j in voucher.journals if j.debit == -1], + "destination": [j.cost_centre.name for j in voucher.journals if j.debit == 1], } ) return list_ diff --git a/brewman/brewman/routers/journal.py b/brewman/brewman/routers/journal.py index e9efcb11..1407cea6 100644 --- a/brewman/brewman/routers/journal.py +++ b/brewman/brewman/routers/journal.py @@ -14,6 +14,7 @@ from ..core.security import get_current_active_user as get_user from ..core.session import get_date, set_date from ..db.session import SessionLocal from ..models import AccountBase +from ..models.validations import check_journals_are_valid from ..models.voucher import Journal, Voucher, VoucherType from ..schemas.auth import UserToken from .db_image import save_files, update_files @@ -49,6 +50,7 @@ def save_route( try: item: Voucher = save(data, user, db) db.flush() + check_journals_are_valid(item) save_files(item.id, i, t, db) db.commit() set_date(data.date_.strftime("%d-%b-%Y"), request.session) @@ -76,11 +78,9 @@ def save(data: schema_in.JournalIn, user: UserToken, db: Session) -> Voucher: ) db.add(voucher) for item in data.journals: - account: AccountBase = ( - db.query(AccountBase).filter(AccountBase.id == item.account.id_).first() - ) + account: AccountBase = db.query(AccountBase).filter(AccountBase.id == item.account.id_).first() journal = Journal( - amount=item.amount, + amount=round(item.amount, 2), debit=item.debit, account_id=account.id, cost_centre_id=account.cost_centre_id, @@ -102,6 +102,7 @@ def update_route( ): try: item: Voucher = update(id_, data, user, db) + check_journals_are_valid(item) update_files(item.id, data.files, i, t, db) db.commit() set_date(data.date_.strftime("%d-%b-%Y"), request.session) @@ -117,9 +118,7 @@ def update_route( raise -def update( - id_: uuid.UUID, data: schema_in.JournalIn, user: UserToken, db: Session -) -> Voucher: +def update(id_: uuid.UUID, data: schema_in.JournalIn, user: UserToken, db: Session) -> Voucher: voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_edit_allowed(voucher, user) @@ -136,14 +135,10 @@ def update( for j in range(len(data.journals), 0, -1): new_item = data.journals[j - 1] if new_item.id_ is not None and item.id == new_item.id_: - account = ( - db.query(AccountBase) - .filter(AccountBase.id == new_item.account.id_) - .first() - ) + account = db.query(AccountBase).filter(AccountBase.id == new_item.account.id_).first() found = True item.debit = new_item.debit - item.amount = new_item.amount + item.amount = round(new_item.amount, 2) item.account_id = account.id item.cost_centre_id = account.cost_centre_id data.journals.remove(new_item) @@ -151,12 +146,10 @@ def update( if not found: voucher.journals.remove(item) for new_item in data.journals: - account = ( - db.query(AccountBase).filter(AccountBase.id == new_item.account.id_).first() - ) + account = db.query(AccountBase).filter(AccountBase.id == new_item.account.id_).first() journal = Journal( amount=new_item.amount, - debit=new_item.debit, + debit=round(new_item.debit, 2), account_id=account.id, cost_centre_id=account.cost_centre_id, ) diff --git a/brewman/brewman/routers/login.py b/brewman/brewman/routers/login.py index cad9f4a9..4aa6332f 100644 --- a/brewman/brewman/routers/login.py +++ b/brewman/brewman/routers/login.py @@ -57,33 +57,21 @@ async def login_for_access_token( allowed, c_id = client_allowed(user, client_id, otp, db) db.commit() if c_id and c_id != client_id: - response.set_cookie( - key="client_id", value=str(c_id), max_age=10 * 365 * 24 * 60 * 60 - ) + response.set_cookie(key="client_id", value=str(c_id), max_age=10 * 365 * 24 * 60 * 60) if not allowed: not_allowed_response = JSONResponse( status_code=status.HTTP_401_UNAUTHORIZED, headers={"WWW-Authenticate": "Bearer"}, content={"detail": "Client is not registered"}, ) - not_allowed_response.set_cookie( - key="client_id", value=str(c_id), max_age=10 * 365 * 24 * 60 * 60 - ) + not_allowed_response.set_cookie(key="client_id", value=str(c_id), max_age=10 * 365 * 24 * 60 * 60) return not_allowed_response access_token_expires = timedelta(minutes=settings.JWT_TOKEN_EXPIRE_MINUTES) access_token = create_access_token( data={ "sub": user.name, "scopes": ["authenticated"] - + list( - set( - [ - p.name.replace(" ", "-").lower() - for r in user.roles - for p in r.permissions - ] - ) - ), + + list(set([p.name.replace(" ", "-").lower() for r in user.roles for p in r.permissions])), "userId": str(user.id), "lockedOut": user.locked_out, "ver": __version__.__version__, diff --git a/brewman/brewman/routers/product.py b/brewman/brewman/routers/product.py index 486160cb..0bcf4b67 100644 --- a/brewman/brewman/routers/product.py +++ b/brewman/brewman/routers/product.py @@ -232,9 +232,7 @@ def product_info(id_: Optional[uuid.UUID], db: Session): def delete_with_data(product: Product, db: Session): - suspense_product = ( - db.query(Product).filter(Product.id == Product.suspense()).first() - ) + suspense_product = db.query(Product).filter(Product.id == Product.suspense()).first() suspense_batch = db.query(Batch).filter(Batch.id == Batch.suspense()).first() query = ( db.query(Voucher) @@ -262,15 +260,11 @@ def delete_with_data(product: Product, db: Session): prod_inv.tax = 0 prod_inv.discount = 0 prod_inv.batch = suspense_batch - voucher.narration += ( - f"\nSuspense \u20B9{prod_inv.amount:,.2f} is {product.name}" - ) + voucher.narration += f"\nSuspense \u20B9{prod_inv.amount:,.2f} is {product.name}" else: sus_inv.quantity += prod_inv.amount db.delete(prod_inv) - voucher.narration += ( - f"\nDeleted \u20B9{prod_inv.amount:,.2f} of {product.name}" - ) + voucher.narration += f"\nDeleted \u20B9{prod_inv.amount:,.2f} of {product.name}" for batch in product.batches: db.delete(batch) db.delete(product) diff --git a/brewman/brewman/routers/purchase.py b/brewman/brewman/routers/purchase.py index ec602605..1faf5787 100644 --- a/brewman/brewman/routers/purchase.py +++ b/brewman/brewman/routers/purchase.py @@ -16,6 +16,7 @@ from ..core.security import get_current_active_user as get_user from ..core.session import get_date, set_date from ..db.session import SessionLocal from ..models import AccountBase, Product +from ..models.validations import check_inventories_are_valid, check_journals_are_valid from ..models.voucher import Batch, Inventory, Journal, Voucher, VoucherType from ..schemas.auth import UserToken from .db_image import save_files, update_files @@ -51,7 +52,9 @@ def save_route( try: item: Voucher = save(data, user, db) save_inventories(item, data.inventories, db) + check_inventories_are_valid(item) save_journals(item, data.vendor, db) + check_journals_are_valid(item) save_files(item.id, i, t, db) db.commit() set_date(data.date_.strftime("%d-%b-%Y"), request.session) @@ -81,13 +84,9 @@ def save(data: schema_in.PurchaseIn, user: UserToken, db: Session) -> Voucher: return voucher -def save_inventories( - voucher: Voucher, inventories: List[schema_in.Inventory], db: Session -): +def save_inventories(voucher: Voucher, inventories: List[schema_in.Inventory], db: Session): for item in inventories: - product: Product = ( - db.query(Product).filter(Product.id == item.product.id_).first() - ) + product: Product = db.query(Product).filter(Product.id == item.product.id_).first() batch = Batch( name=voucher.date, product=product, @@ -151,8 +150,9 @@ def update_route( try: item: Voucher = update(id_, data, user, db) update_inventory(item, data.inventories, db) + check_inventories_are_valid(item) update_journals(item, data.vendor, db) - # journals_valid(voucher) + check_journals_are_valid(item) update_files(item.id, data.files, i, t, db) db.commit() set_date(data.date_.strftime("%d-%b-%Y"), request.session) @@ -168,9 +168,7 @@ def update_route( raise -def update( - id_: uuid.UUID, data: schema_in.PurchaseIn, user: UserToken, db: Session -) -> Voucher: +def update(id_: uuid.UUID, data: schema_in.PurchaseIn, user: UserToken, db: Session) -> Voucher: voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_edit_allowed(voucher, user) @@ -183,20 +181,14 @@ def update( return voucher -def update_inventory( - voucher: Voucher, new_inventories: List[schema_in.Inventory], db: Session -): +def update_inventory(voucher: Voucher, new_inventories: List[schema_in.Inventory], db: Session): for it in range(len(voucher.inventories), 0, -1): item = voucher.inventories[it - 1] found = False for j in range(len(new_inventories), 0, -1): new_inventory = new_inventories[j - 1] if new_inventory.id_ == item.id: - product = ( - db.query(Product) - .filter(Product.id == new_inventory.product.id_) - .first() - ) + product = db.query(Product).filter(Product.id == new_inventory.product.id_).first() found = True if item.product_id != new_inventory.product.id_: raise HTTPException( @@ -244,9 +236,7 @@ def update_inventory( db.delete(item) voucher.inventories.remove(item) for new_inventory in new_inventories: - product = ( - db.query(Product).filter(Product.id == new_inventory.product.id_).first() - ) + product = db.query(Product).filter(Product.id == new_inventory.product.id_).first() batch = Batch( name=voucher.date, product_id=product.id, diff --git a/brewman/brewman/routers/purchase_return.py b/brewman/brewman/routers/purchase_return.py index 3a0ea568..cab85edf 100644 --- a/brewman/brewman/routers/purchase_return.py +++ b/brewman/brewman/routers/purchase_return.py @@ -15,6 +15,7 @@ from ..core.security import get_current_active_user as get_user from ..core.session import get_date, set_date from ..db.session import SessionLocal from ..models import AccountBase +from ..models.validations import check_inventories_are_valid, check_journals_are_valid from ..models.voucher import Batch, Inventory, Journal, Voucher, VoucherType from ..schemas.auth import UserToken from .db_image import save_files, update_files @@ -50,7 +51,9 @@ def save_route( try: item: Voucher = save(data, user, db) save_inventories(item, data.inventories, db) + check_inventories_are_valid(item) save_journals(item, data.vendor, db) + check_journals_are_valid(item) save_files(item.id, i, t, db) db.commit() set_date(data.date_.strftime("%d-%b-%Y"), request.session) @@ -80,9 +83,7 @@ def save(data: schema_in.PurchaseIn, user: UserToken, db: Session) -> Voucher: return voucher -def save_inventories( - voucher: Voucher, inventories: List[schema_in.Inventory], db: Session -): +def save_inventories(voucher: Voucher, inventories: List[schema_in.Inventory], db: Session): for item in inventories: batch = db.query(Batch).filter(Batch.id == item.batch.id_).first() @@ -151,8 +152,9 @@ def update_route( try: item: Voucher = update(id_, data, user, db) update_inventory(item, data.inventories, db) + check_inventories_are_valid(item) update_journals(item, data.vendor, db) - # journals_valid(voucher) + check_journals_are_valid(item) update_files(item.id, data.files, i, t, db) db.commit() set_date(data.date_.strftime("%d-%b-%Y"), request.session) @@ -168,9 +170,7 @@ def update_route( raise -def update( - id_: uuid.UUID, data: schema_in.PurchaseIn, user: UserToken, db: Session -) -> Voucher: +def update(id_: uuid.UUID, data: schema_in.PurchaseIn, user: UserToken, db: Session) -> Voucher: voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_edit_allowed(voucher, user) @@ -183,9 +183,7 @@ def update( return voucher -def update_inventory( - voucher: Voucher, new_inventories: List[schema_in.Inventory], db: Session -): +def update_inventory(voucher: Voucher, new_inventories: List[schema_in.Inventory], db: Session): for it in range(len(voucher.inventories), 0, -1): item = voucher.inventories[it - 1] found = False diff --git a/brewman/brewman/routers/rebase.py b/brewman/brewman/routers/rebase.py index b9720f71..d229154d 100644 --- a/brewman/brewman/routers/rebase.py +++ b/brewman/brewman/routers/rebase.py @@ -58,10 +58,7 @@ def rebase( def save_starred(date_: date, db: Session): - accounts = [ - i.id - for i in db.query(AccountBase.id).filter(AccountBase.is_starred == True).all() - ] + accounts = [i.id for i in db.query(AccountBase.id).filter(AccountBase.is_starred == True).all()] # noqa: E712 vouchers = [] query = ( db.query(Voucher) @@ -73,11 +70,7 @@ def save_starred(date_: date, db: Session): for voucher in query: vouchers.append(voucher.id) - others = [ - journal - for journal in voucher.journals - if journal.account_id not in accounts - ] + others = [journal for journal in voucher.journals if journal.account_id not in accounts] if len(others) == 0: continue amount = round(Decimal(sum(o.signed_amount for o in others)), 2) @@ -93,9 +86,7 @@ def save_starred(date_: date, db: Session): for other in others: if voucher.type != VoucherType.by_name("Opening Accounts").id: - voucher.narration += ( - f"\nSuspense \u20B9{other.amount:,.2f} is {other.account.name}" - ) + voucher.narration += f"\nSuspense \u20B9{other.amount:,.2f} is {other.account.name}" if other.employee_benefit: db.delete(other.employee_benefit) if other.incentive: @@ -114,7 +105,7 @@ def opening_accounts(date_: date, user_id: uuid.UUID, db: Session): db.query(AccountBase, sum_func) .join(Journal, Voucher.journals) .join(AccountBase, Journal.account) - .filter(AccountBase.is_starred == False) + .filter(AccountBase.is_starred == False) # noqa: E712 .filter(AccountBase.id != AccountBase.suspense()) .filter(Voucher.date < date_) .filter(Voucher.type != VoucherType.by_name("Issue").id) @@ -214,15 +205,9 @@ def delete_data(date_: date, vouchers: List[Voucher], db: Session): sub_query = db.query(sub_voucher.id).filter(sub_voucher.date < date_).subquery() db.execute(Inventory.__table__.delete(Inventory.voucher_id.in_(sub_query))) - db.execute( - EmployeeBenefit.__table__.delete(EmployeeBenefit.voucher_id.in_(sub_query)) - ) + db.execute(EmployeeBenefit.__table__.delete(EmployeeBenefit.voucher_id.in_(sub_query))) db.execute(Incentive.__table__.delete(Incentive.voucher_id.in_(sub_query))) - db.execute( - Journal.__table__.delete( - and_(Journal.voucher_id.in_(sub_query), ~Journal.voucher_id.in_(vouchers)) - ) - ) + db.execute(Journal.__table__.delete(and_(Journal.voucher_id.in_(sub_query), ~Journal.voucher_id.in_(vouchers)))) db.execute( DbImage.__table__.delete( and_( @@ -232,31 +217,23 @@ def delete_data(date_: date, vouchers: List[Voucher], db: Session): ) ) ) - db.execute( - Voucher.__table__.delete(and_(Voucher.date < date_, ~Voucher.id.in_(vouchers))) - ) + db.execute(Voucher.__table__.delete(and_(Voucher.date < date_, ~Voucher.id.in_(vouchers)))) def cleanup_lint(date_: date, db: Session): # Insert executes on the end so keep list of batches and journals - db.execute( - Batch.__table__.delete( - ~Batch.id.in_(db.query(distinct(Inventory.batch_id)).subquery()) - ) - ) + db.execute(Batch.__table__.delete(~Batch.id.in_(db.query(distinct(Inventory.batch_id)).subquery()))) db.execute(Fingerprint.__table__.delete(Fingerprint.date < date_)) db.execute(Attendance.__table__.delete(Attendance.date < date_)) db.execute( Employee.__table__.delete( and_( ~Employee.id.in_(db.query(distinct(Journal.account_id)).subquery()), - ~Employee.id.in_( - db.query(distinct(Fingerprint.employee_id)).subquery() - ), + ~Employee.id.in_(db.query(distinct(Fingerprint.employee_id)).subquery()), ~Employee.id.in_(db.query(distinct(Attendance.employee_id)).subquery()), Employee.id.in_( db.query(AccountBase.id) - .filter(AccountBase.is_fixture == False) + .filter(AccountBase.is_fixture == False) # noqa: E712 .filter(AccountBase.is_active == False) .filter(AccountBase.is_starred == False) .subquery() @@ -269,8 +246,7 @@ def cleanup_lint(date_: date, db: Session): AccountBase.__table__.delete( and_( ~AccountBase.id.in_(db.query(Employee.id).subquery()), - AccountBase.account_type - == Employee.__mapper_args__["polymorphic_identity"], + AccountBase.account_type == Employee.__mapper_args__["polymorphic_identity"], ) ) ) @@ -278,7 +254,7 @@ def cleanup_lint(date_: date, db: Session): Account.__table__.delete( and_( ~Account.id.in_(db.query(distinct(Journal.account_id)).subquery()), - Account.is_fixture == False, + Account.is_fixture == False, # noqa: E712 Account.is_starred == False, Account.account_type == Account.__mapper_args__["polymorphic_identity"], ) diff --git a/brewman/brewman/routers/recipe.py b/brewman/brewman/routers/recipe.py index b1131c03..4063da9a 100644 --- a/brewman/brewman/routers/recipe.py +++ b/brewman/brewman/routers/recipe.py @@ -20,21 +20,15 @@ router = APIRouter() def save(request): json = request.json_body recipe_product = ( - request.dbsession.query(Product) - .filter(Product.id == uuid.UUID(json["Product"]["ProductID"])) - .first() + request.dbsession.query(Product).filter(Product.id == uuid.UUID(json["Product"]["ProductID"])).first() ) try: - valid_from = datetime.date( - *(time.strptime(request.json_body["ValidFrom"], "%d-%b-%Y")[0:3]) - ) + valid_from = datetime.date(*(time.strptime(request.json_body["ValidFrom"], "%d-%b-%Y")[0:3])) except (ValueError, KeyError, TypeError): raise ValidationError("Valid From is not a valid date") try: - valid_to = datetime.date( - *(time.strptime(request.json_body["ValidTo"], "%d-%b-%Y")[0:3]) - ) + valid_to = datetime.date(*(time.strptime(request.json_body["ValidTo"], "%d-%b-%Y")[0:3])) except (ValueError, KeyError, TypeError): raise ValidationError("Valid To is not a valid date") @@ -67,25 +61,15 @@ def save(request): valid_to=valid_to, ) for item in json["RecipeItems"]: - product = ( - request.dbsession.query(Product) - .filter(Product.id == uuid.UUID(item["Product"]["ProductID"])) - .first() - ) + product = request.dbsession.query(Product).filter(Product.id == uuid.UUID(item["Product"]["ProductID"])).first() quantity = round(Decimal(item["Quantity"]), 2) if product.is_purchased: - ingredient_cost = get_purchased_product_cost( - product.id, valid_from, valid_to, request.dbsession - ) + ingredient_cost = get_purchased_product_cost(product.id, valid_from, valid_to, request.dbsession) else: - ingredient_cost = get_sub_product_cost( - product.id, valid_from, valid_to, request.dbsession - ) + ingredient_cost = get_sub_product_cost(product.id, valid_from, valid_to, request.dbsession) cost_per_unit = ingredient_cost / (product.fraction * product.product_yield) recipe_cost += cost_per_unit * quantity - recipe.recipe_items.append( - RecipeItem(None, product.id, quantity, ingredient_cost) - ) + recipe.recipe_items.append(RecipeItem(None, product.id, quantity, ingredient_cost)) recipe.cost_price = round(recipe_cost / recipe_quantity, 2) if recipe_product.is_sold: @@ -116,11 +100,7 @@ def save_recipe(recipe, dbsession): def get_purchased_product_cost(product_id, start_date, finish_date, dbsession): quantity_sum = func.sum(Journal.debit * Inventory.quantity).label("quantity") amount_sum = func.sum( - Journal.debit - * Inventory.quantity - * Inventory.rate - * (1 + Inventory.tax) - * (1 - Inventory.discount) + Journal.debit * Inventory.quantity * Inventory.rate * (1 + Inventory.tax) * (1 - Inventory.discount) ).label("amount") costing = ( dbsession.query(quantity_sum, amount_sum) @@ -178,20 +158,12 @@ def get_sub_product_cost(product_id, start_date, finish_date, dbsession): ) for item in old_recipe.recipe_items: if item.product.is_purchased: - ingredient_cost = get_purchased_product_cost( - item.product_id, start_date, finish_date, dbsession - ) + ingredient_cost = get_purchased_product_cost(item.product_id, start_date, finish_date, dbsession) else: - ingredient_cost = get_sub_product_cost( - item.product_id, start_date, finish_date, dbsession - ) - cost_per_unit = ingredient_cost / ( - item.product.fraction * item.product.product_yield - ) + ingredient_cost = get_sub_product_cost(item.product_id, start_date, finish_date, dbsession) + cost_per_unit = ingredient_cost / (item.product.fraction * item.product.product_yield) recipe_cost += cost_per_unit * item.quantity - recipe.recipe_items.append( - RecipeItem(None, item.product_id, item.quantity, ingredient_cost) - ) + recipe.recipe_items.append(RecipeItem(None, item.product_id, item.quantity, ingredient_cost)) recipe.cost_price = round(recipe_cost / old_recipe.quantity, 2) @@ -224,9 +196,7 @@ def update_old_rows(product_id, valid_from, valid_to, effective_date, dbsession) effective_from=effective_date, ) for ri in item.recipe_items: - recipe.recipe_items.append( - RecipeItem(None, ri.product_id, ri.quantity, ri.price) - ) + recipe.recipe_items.append(RecipeItem(None, ri.product_id, ri.quantity, ri.price)) new_recipes.append(recipe) if item.valid_to > valid_to: recipe = Recipe( @@ -239,9 +209,7 @@ def update_old_rows(product_id, valid_from, valid_to, effective_date, dbsession) effective_from=effective_date, ) for ri in item.recipe_items: - recipe.recipe_items.append( - RecipeItem(None, ri.product_id, ri.quantity, ri.price) - ) + recipe.recipe_items.append(RecipeItem(None, ri.product_id, ri.quantity, ri.price)) new_recipes.append(recipe) if item.effective_from == effective_date and item.effective_to is None: @@ -260,11 +228,7 @@ def update_old_rows(product_id, valid_from, valid_to, effective_date, dbsession) @router.delete("/{id}") # "Recipes" def delete(request): - recipe = ( - request.dbsession.query(Recipe) - .filter(Recipe.id == uuid.UUID(request.matchdict["id"])) - .first() - ) + recipe = request.dbsession.query(Recipe).filter(Recipe.id == uuid.UUID(request.matchdict["id"])).first() if len(recipe.product.recipes) > 1: request.dbsession.delete(recipe) else: diff --git a/brewman/brewman/routers/reports/balance_sheet.py b/brewman/brewman/routers/reports/balance_sheet.py index 6e1c6ece..81886f3d 100644 --- a/brewman/brewman/routers/reports/balance_sheet.py +++ b/brewman/brewman/routers/reports/balance_sheet.py @@ -72,9 +72,7 @@ def build_balance_sheet(date_: date, db: Session): } total_amount += closing_stock - report.append( - {"name": "Closing Stock", "subAmount": round(closing_stock, 2), "order": 20001} - ) + report.append({"name": "Closing Stock", "subAmount": round(closing_stock, 2), "order": 20001}) asset_group = AccountType.by_id(4) groups[asset_group.id] = { @@ -112,9 +110,7 @@ def build_balance_sheet(date_: date, db: Session): } ) if account_type.id in groups: - groups[account_type.id]["amount"] = round( - groups[account_type.id]["amount"] + amount, 2 - ) + groups[account_type.id]["amount"] = round(groups[account_type.id]["amount"] + amount, 2) else: groups[account_type.id] = { "group": account_type.name, diff --git a/brewman/brewman/routers/reports/closing_stock.py b/brewman/brewman/routers/reports/closing_stock.py index 44706cd4..e2a49697 100644 --- a/brewman/brewman/routers/reports/closing_stock.py +++ b/brewman/brewman/routers/reports/closing_stock.py @@ -49,9 +49,7 @@ def report_data( def build_report(date_: date, db: Session): - amount_sum = func.sum( - Journal.debit * Inventory.quantity * Inventory.rate * (1 + Inventory.tax) - ).label("amount") + amount_sum = func.sum(Journal.debit * Inventory.quantity * Inventory.rate * (1 + Inventory.tax)).label("amount") quantity_sum = func.sum(Journal.debit * Inventory.quantity).label("quantity") query = ( db.query(Product, quantity_sum, amount_sum) @@ -81,14 +79,7 @@ def build_report(date_: date, db: Session): def get_opening_stock(date_: date, db: Session): opening_stock = ( - db.query( - func.sum( - Inventory.quantity - * Inventory.rate - * (1 + Inventory.tax) - * Journal.debit - ) - ) + db.query(func.sum(Inventory.quantity * Inventory.rate * (1 + Inventory.tax) * Journal.debit)) .join(Journal.voucher) .join(Journal.account) .join(Voucher.inventories) @@ -101,14 +92,7 @@ def get_opening_stock(date_: date, db: Session): def get_closing_stock(date_, db: Session): closing_stock = ( - db.query( - func.sum( - Inventory.quantity - * Inventory.rate - * (1 + Inventory.tax) - * Journal.debit - ) - ) + db.query(func.sum(Inventory.quantity * Inventory.rate * (1 + Inventory.tax) * Journal.debit)) .join(Journal.voucher) .join(Journal.account) .join(Voucher.inventories) diff --git a/brewman/brewman/routers/reports/net_transactions.py b/brewman/brewman/routers/reports/net_transactions.py index 5297f5ff..162dfc2f 100644 --- a/brewman/brewman/routers/reports/net_transactions.py +++ b/brewman/brewman/routers/reports/net_transactions.py @@ -77,7 +77,5 @@ def build_report(start_date: date, finish_date: date, db: Session): for account, amount in query: if amount != 0: tag = "debit" if amount > 0 else "credit" - body.append( - {"type": account.type_object.name, "name": account.name, tag: amount} - ) + body.append({"type": account.type_object.name, "name": account.name, tag: amount}) return body diff --git a/brewman/brewman/routers/reports/product_ledger.py b/brewman/brewman/routers/reports/product_ledger.py index 4d761e53..c01807c9 100644 --- a/brewman/brewman/routers/reports/product_ledger.py +++ b/brewman/brewman/routers/reports/product_ledger.py @@ -68,13 +68,9 @@ def show_data( } -def build_report( - product_id: uuid.UUID, start_date: date, finish_date: date, db: Session -): +def build_report(product_id: uuid.UUID, start_date: date, finish_date: date, db: Session): body = [] - running_total_q, running_total_a, opening = opening_balance( - product_id, start_date, db - ) + running_total_q, running_total_a, opening = opening_balance(product_id, start_date, db) body.append(opening) query = ( @@ -121,8 +117,7 @@ def build_report( ], "type": VoucherType.by_id(row.Voucher.type).name, "narration": row.Voucher.narration, - "posted": row.Voucher.posted - or VoucherType.by_id(row.Voucher.type).name == "Issue", + "posted": row.Voucher.posted or VoucherType.by_id(row.Voucher.type).name == "Issue", "debitQuantity": debit_q, "debitAmount": debit_a, "creditQuantity": credit_q, diff --git a/brewman/brewman/routers/reports/profit_loss.py b/brewman/brewman/routers/reports/profit_loss.py index bcec6764..6b5e3b29 100644 --- a/brewman/brewman/routers/reports/profit_loss.py +++ b/brewman/brewman/routers/reports/profit_loss.py @@ -48,9 +48,7 @@ def report_data( db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["profit-&-loss"]), ): - body, footer = build_profit_loss( - datetime.strptime(start, "%d-%b-%Y"), datetime.strptime(finish, "%d-%b-%Y"), db - ) + body, footer = build_profit_loss(datetime.strptime(start, "%d-%b-%Y"), datetime.strptime(finish, "%d-%b-%Y"), db) set_period(start, finish, request.session) return { "startDate": start, @@ -61,7 +59,7 @@ def report_data( def build_profit_loss(start_date: date, finish_date: date, db: Session): - profit_type_list = [i.id for i in AccountType.list() if i.balance_sheet == False] + profit_type_list = [i.id for i in AccountType.list() if i.balance_sheet is False] report = [] groups = {} @@ -85,9 +83,7 @@ def build_profit_loss(start_date: date, finish_date: date, db: Session): closing_stock = get_closing_stock(finish_date, db) total_amount = (opening_stock - closing_stock) * -1 - report.append( - {"name": "Opening Stock", "amount": opening_stock * -1, "order": 200001} - ) + report.append({"name": "Opening Stock", "amount": opening_stock * -1, "order": 200001}) report.append({"name": "Closing Stock", "amount": closing_stock, "order": 290000}) purchase_group = AccountType.by_id(2) groups[purchase_group.id] = { diff --git a/brewman/brewman/routers/reports/purchases.py b/brewman/brewman/routers/reports/purchases.py index 7c25cb6a..3b46b36b 100644 --- a/brewman/brewman/routers/reports/purchases.py +++ b/brewman/brewman/routers/reports/purchases.py @@ -60,9 +60,7 @@ def report_data( def build_report(start_date, finish_date, db): body = [] quantity_sum = func.sum(Journal.debit * Inventory.quantity).label("quantity") - amount_sum = func.sum( - Journal.debit * Inventory.quantity * Inventory.rate * (1 + Inventory.tax) - ).label("amount") + amount_sum = func.sum(Journal.debit * Inventory.quantity * Inventory.rate * (1 + Inventory.tax)).label("amount") query = ( db.query(Product, quantity_sum, amount_sum) .join(Product.inventories) @@ -91,7 +89,5 @@ def build_report(start_date, finish_date, db): body.append(row) return ( body, - schemas.PurchasesItem( - name="Total", quantity=0, rate=0, url=[], amount=total_amount - ), + schemas.PurchasesItem(name="Total", quantity=0, rate=0, url=[], amount=total_amount), ) diff --git a/brewman/brewman/routers/reports/raw_material_cost.py b/brewman/brewman/routers/reports/raw_material_cost.py index 2a4b851c..dcf326a7 100644 --- a/brewman/brewman/routers/reports/raw_material_cost.py +++ b/brewman/brewman/routers/reports/raw_material_cost.py @@ -49,9 +49,7 @@ def report_data( db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["raw-material-cost"]), ): - body, footer = build_report( - datetime.strptime(s, "%d-%b-%Y"), datetime.strptime(f, "%d-%b-%Y"), db - ) + body, footer = build_report(datetime.strptime(s, "%d-%b-%Y"), datetime.strptime(f, "%d-%b-%Y"), db) set_period(s, f, request.session) return { "startDate": s, @@ -70,9 +68,7 @@ def report_id( db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["raw-material-cost"]), ): - body = build_report_id( - id_, datetime.strptime(s, "%d-%b-%Y"), datetime.strptime(f, "%d-%b-%Y"), db - ) + body = build_report_id(id_, datetime.strptime(s, "%d-%b-%Y"), datetime.strptime(f, "%d-%b-%Y"), db) set_period(s, f, request.session) return { "id": id_, @@ -84,12 +80,8 @@ def report_id( def build_report(start_date: date, finish_date: date, db: Session): body = [] - sum_issue = func.sum( - case([(AccountBase.type == 2, Journal.signed_amount)], else_=0) - ).label("issue") - sum_sale = func.sum( - case([(AccountBase.type == 3, Journal.signed_amount * -1)], else_=0) - ).label("sale") + sum_issue = func.sum(case([(AccountBase.type == 2, Journal.signed_amount)], else_=0)).label("issue") + sum_sale = func.sum(case([(AccountBase.type == 3, Journal.signed_amount * -1)], else_=0)).label("sale") query = ( db.query(CostCentre, sum_issue, sum_sale) @@ -125,9 +117,7 @@ def build_report(start_date: date, finish_date: date, db: Session): return body, {"name": "Total", "issue": issues, "sale": sales, "rmc": rmc} -def build_report_id( - cost_centre_id: uuid.UUID, start_date: date, finish_date: date, db: Session -): +def build_report_id(cost_centre_id: uuid.UUID, start_date: date, finish_date: date, db: Session): sum_quantity = func.sum(Inventory.quantity * Journal.debit).label("quantity") sum_net = func.sum(Inventory.rate * Inventory.quantity * Journal.debit).label("net") sum_gross = func.sum(Inventory.amount * Journal.debit).label("gross") diff --git a/brewman/brewman/routers/reports/reconcile.py b/brewman/brewman/routers/reports/reconcile.py index 2c088488..eab96502 100644 --- a/brewman/brewman/routers/reports/reconcile.py +++ b/brewman/brewman/routers/reports/reconcile.py @@ -72,10 +72,8 @@ def build_report(account_id, start_date, finish_date, db): or_( Voucher.is_reconciled == False, and_( - Voucher.reconcile_date - >= datetime.datetime.strptime(start_date, "%d-%b-%Y"), - Voucher.reconcile_date - <= datetime.datetime.strptime(finish_date, "%d-%b-%Y"), + Voucher.reconcile_date >= datetime.datetime.strptime(start_date, "%d-%b-%Y"), + Voucher.reconcile_date <= datetime.datetime.strptime(finish_date, "%d-%b-%Y"), ), ) ) @@ -124,9 +122,7 @@ def opening_balance(account_id, start_date, db): opening = ( db.query(func.sum(Journal.amount * Journal.debit)) .join(Journal.voucher) - .filter( - Voucher.reconcile_date < datetime.datetime.strptime(start_date, "%d-%b-%Y") - ) + .filter(Voucher.reconcile_date < datetime.datetime.strptime(start_date, "%d-%b-%Y")) .filter(Voucher.is_reconciled == True) .filter(Voucher.type != VoucherType.by_name("Issue").id) .filter(Journal.account_id == account_id) diff --git a/brewman/brewman/routers/reports/stock_movement.py b/brewman/brewman/routers/reports/stock_movement.py index 27029cc7..f256c473 100644 --- a/brewman/brewman/routers/reports/stock_movement.py +++ b/brewman/brewman/routers/reports/stock_movement.py @@ -47,9 +47,7 @@ def report_data( db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["stock-movement"]), ): - body = build_stock_movement( - datetime.strptime(start, "%d-%b-%Y"), datetime.strptime(finish, "%d-%b-%Y"), db - ) + body = build_stock_movement(datetime.strptime(start, "%d-%b-%Y"), datetime.strptime(finish, "%d-%b-%Y"), db) set_period(start, finish, request.session) return {"startDate": start, "finishDate": finish, "body": body} diff --git a/brewman/brewman/routers/reports/trial_balance.py b/brewman/brewman/routers/reports/trial_balance.py index 5b69e7ad..08c8f6b1 100644 --- a/brewman/brewman/routers/reports/trial_balance.py +++ b/brewman/brewman/routers/reports/trial_balance.py @@ -66,7 +66,5 @@ def build_report(date_: date, db: Session): for account, amount in query: if amount != 0: tag = "debit" if amount > 0 else "credit" - body.append( - {"type": account.type_object.name, "name": account.name, tag: amount} - ) + body.append({"type": account.type_object.name, "name": account.name, tag: amount}) return body diff --git a/brewman/brewman/routers/reports/unposted.py b/brewman/brewman/routers/reports/unposted.py index a462d502..315bc08e 100644 --- a/brewman/brewman/routers/reports/unposted.py +++ b/brewman/brewman/routers/reports/unposted.py @@ -38,7 +38,7 @@ def build_report(db: Session): query = ( db.query(Voucher) .options(joinedload_all(Voucher.journals, Journal.account, innerjoin=True)) - .filter(Voucher.posted == False) + .filter(Voucher.posted == False) # noqa: E712 .filter(Voucher.type != VoucherType.by_name("Issue").id) .order_by(Voucher.date) .order_by(Voucher.last_edit_date) diff --git a/brewman/brewman/routers/reset_stock.py b/brewman/brewman/routers/reset_stock.py index 03b0859f..c8836ff4 100644 --- a/brewman/brewman/routers/reset_stock.py +++ b/brewman/brewman/routers/reset_stock.py @@ -39,9 +39,7 @@ def rebase( detail="Reset cannot be after the stock date", ) - change = round(item.quantity, 2) - get_closing_stock( - product, item.stock_date, db=db - ) + change = round(item.quantity, 2) - get_closing_stock(product, item.stock_date, db=db) if change == 0: return {"No Change Needed"} final = get_closing_stock(product, db=db) @@ -75,12 +73,7 @@ def get_closing_stock(product, finish_date=None, db=None): def get_last_batch(product, db): - batch = ( - db.query(Batch) - .filter(Batch.product_id == product.id) - .order_by(Batch.name.desc()) - .first() - ) + batch = db.query(Batch).filter(Batch.product_id == product.id).order_by(Batch.name.desc()).first() if batch is None: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, @@ -91,11 +84,7 @@ def get_last_batch(product, db): def set_batches(batch, quantity, db): batch.quantity_remaining = quantity - batches = ( - db.query(Batch) - .filter(Batch.id != batch.id) - .filter(Batch.product_id == batch.product_id) - ) + batches = db.query(Batch).filter(Batch.id != batch.id).filter(Batch.product_id == batch.product_id) for item in batches: item.quantity_remaining = 0 pass diff --git a/brewman/brewman/routers/voucher.py b/brewman/brewman/routers/voucher.py index b73fe858..8caf24f6 100644 --- a/brewman/brewman/routers/voucher.py +++ b/brewman/brewman/routers/voucher.py @@ -72,10 +72,7 @@ def check_delete_permissions(voucher: Voucher, user: UserToken): status_code=status.HTTP_403_FORBIDDEN, detail="You are not allowed to edit posted vouchers", ) - elif ( - voucher.user_id != user.id_ - and "edit-other-user's-vouchers" not in user.permissions - ): + elif voucher.user_id != user.id_ and "edit-other-user's-vouchers" not in user.permissions: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You are not allowed to edit other user's vouchers", @@ -122,7 +119,8 @@ def delete_voucher( if item.batch.quantity_remaining < item.quantity: raise HTTPException( status_code=status.HTTP_423_LOCKED, - detail=f"Only {item.batch.quantity_remaining} of {item.product.name} remaining.\n So it cannot be deleted", + detail=f"Only {item.batch.quantity_remaining} of {item.product.name} remaining.\n" + f"So it cannot be deleted", ) item.batch.quantity_remaining -= item.quantity elif voucher.type == VoucherType.by_name("Purchase").id: @@ -212,9 +210,7 @@ def voucher_info(voucher, db): } ) for item in voucher.incentives: - employee = ( - db.query(Employee).filter(Employee.id == item.journal.account_id).first() - ) + employee = db.query(Employee).filter(Employee.id == item.journal.account_id).first() json_voucher["incentives"].append( { "employeeId": item.journal.account_id, @@ -226,11 +222,12 @@ def voucher_info(voucher, db): } ) if len(json_voucher["incentives"]) > 0: - json_voucher["incentive"] = next( - x.amount for x in voucher.journals if x.account_id == Account.incentive_id() - ) + json_voucher["incentive"] = next(x.amount for x in voucher.journals if x.account_id == Account.incentive_id()) for item in voucher.inventories: - text = f"{item.product.name} ({item.product.units}) {item.batch.quantity_remaining:.2f}@{item.batch.rate:.2f} from {item.batch.name.strftime('%d-%b-%Y')}" + text = ( + f"{item.product.name} ({item.product.units}) {item.batch.quantity_remaining:.2f}@" + f"{item.batch.rate:.2f} from {item.batch.name.strftime('%d-%b-%Y')}" + ) json_voucher["inventories"].append( { "id": item.id, @@ -281,7 +278,7 @@ def blank_voucher(info, db): if "date" not in info: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, - detail=f"Date cannot be null", + detail="Date cannot be null", ) json_voucher = { "type": type_, @@ -298,11 +295,7 @@ def blank_voucher(info, db): elif type_ == "Payment": account = None if info and "account" in info and info["account"]: - account = ( - db.query(AccountBase) - .filter(AccountBase.id == uuid.UUID(info["account"])) - .first() - ) + account = db.query(AccountBase).filter(AccountBase.id == uuid.UUID(info["account"])).first() if account is not None: account = {"id": account.id, "name": account.name} else: @@ -311,11 +304,7 @@ def blank_voucher(info, db): elif type_ == "Receipt": account = None if info and "account" in info and info["account"]: - account = ( - db.query(AccountBase) - .filter(AccountBase.id == uuid.UUID(info["account"])) - .first() - ) + account = db.query(AccountBase).filter(AccountBase.id == uuid.UUID(info["account"])).first() if account is not None: account = {"id": account.id, "name": account.name} else: @@ -325,9 +314,7 @@ def blank_voucher(info, db): json_voucher["vendor"] = AccountBase.local_purchase() elif type_ == "Purchase Return": - json_voucher["journals"].append( - {"account": AccountBase.local_purchase(), "amount": 0, "debit": 1} - ) + json_voucher["journals"].append({"account": AccountBase.local_purchase(), "amount": 0, "debit": 1}) elif type_ == "Issue": if "source" in info: json_voucher["source"] = {"id": info["source"]} @@ -340,9 +327,7 @@ def blank_voucher(info, db): elif type_ == "Employee Benefit": json_voucher["employeeBenefits"] = [] elif type_ == "Incentive": - json_voucher["incentives"], json_voucher["incentive"] = incentive_employees( - info["date"], db - ) + json_voucher["incentives"], json_voucher["incentive"] = incentive_employees(info["date"], db) else: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, @@ -372,7 +357,7 @@ def incentive_employees(date_, db: Session): .filter(Attendance.employee_id == employee.id) .filter(Attendance.date >= start_date) .filter(Attendance.date <= finish_date) - .filter(Attendance.is_valid == True) + .filter(Attendance.is_valid == True) # noqa: E712 .all() ) att = sum(map(lambda x: AttendanceType.by_id(x.attendance_type).value, att)) @@ -401,22 +386,12 @@ def incentive_employees(date_, db: Session): def check_voucher_lock_info(voucher_date: Optional[date], data_date: date, db: Session): start, finish = get_lock_info(db) - if ( - start is not None - and start > data_date - or voucher_date is not None - and start > voucher_date - ): + if start is not None and start > data_date or voucher_date is not None and start > voucher_date: raise HTTPException( status_code=status.HTTP_423_LOCKED, detail=f"Vouchers before {start.strftime('%d-%b-%Y')} have been locked.", ) - elif ( - finish is not None - and finish < data_date - or voucher_date is not None - and finish < voucher_date - ): + elif finish is not None and finish < data_date or voucher_date is not None and finish < voucher_date: raise HTTPException( status_code=status.HTTP_423_LOCKED, detail=f"Vouchers after {finish.strftime('%d-%b-%Y')} have been locked.", @@ -439,10 +414,7 @@ def check_voucher_edit_allowed(voucher: Voucher, user: UserToken): status_code=status.HTTP_403_FORBIDDEN, detail="You are not allowed to edit posted vouchers", ) - elif ( - voucher.user_id != user.id_ - and "edit-other-user's-vouchers" not in user.permissions - ): + elif voucher.user_id != user.id_ and "edit-other-user's-vouchers" not in user.permissions: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="You are not allowed to edit other user's vouchers", diff --git a/brewman/brewman/schemas/input.py b/brewman/brewman/schemas/input.py index 51d67192..e6331815 100644 --- a/brewman/brewman/schemas/input.py +++ b/brewman/brewman/schemas/input.py @@ -16,7 +16,6 @@ from brewman.schemas.voucher import ( ) from fastapi import Form from pydantic import BaseModel, Field, validator -from sqlalchemy.orm import Session class JournalIn(VoucherIn): @@ -36,23 +35,6 @@ class JournalIn(VoucherIn): return value return datetime.strptime(value, "%d-%b-%Y").date() - @validator("journals") - def validate_signed_amount(cls, value: List[Journal]): - if sum(x.debit * x.amount for x in value) != 0: - raise ValueError("Journal amounts do no match") - return value - - @validator("journals") - def is_distinct(cls, value: List[Journal]): - journal_set = set( - hash(x.account.id_) - ^ hash(None if x.cost_centre is None else x.cost_centre.id_) - for x in value - ) - if len(value) != len(journal_set): - raise ValueError("Duplicate journals") - return value - @classmethod def load_form(cls, data: str = Form(...)): json_data = json.loads(data) @@ -77,18 +59,6 @@ class PurchaseIn(VoucherIn): return value return datetime.strptime(value, "%d-%b-%Y").date() - @validator("inventories") # For Purchase, Issue and Return Vouchers - def validate_enough_inventories(cls, value: List[Inventory]): - if len(value) < 1: - raise ValueError("Not enough inventories") - return value - - @validator("inventories") # For Purchase, Issue and Return Vouchers - def validate_inventories_unique(cls, value: List[Inventory]): - if len(set(x.product.id_ for x in value)) != len(value): - raise ValueError("Duplicate products") - return value - @classmethod def load_form(cls, data: str = Form(...)): json_data = json.loads(data) @@ -114,19 +84,7 @@ class IssueIn(VoucherIn): return value return datetime.strptime(value, "%d-%b-%Y").date() - @validator("inventories") # For Purchase, Issue and Return Vouchers - def validate_enough_inventories(cls, value: List[Inventory]): - if len(value) < 1: - raise ValueError("Not enough inventories") - return value - - @validator("inventories") # For Purchase, Issue and Return Vouchers - def validate_inventories_unique(cls, value: List[Inventory]): - if len(set(x.product.id_ for x in value)) != len(value): - raise ValueError("Duplicate products") - return value - - @validator("destination") # For Purchase, Issue and Return Vouchers + @validator("destination") # For Purchase, Issue and Return Vouchers def source_destination_unique(cls, value: CostCentreLink, values): if value.id_ == values["source"].id_: raise ValueError("Source and destination cannot be the same") diff --git a/brewman/brewman/schemas/voucher.py b/brewman/brewman/schemas/voucher.py index a83e2e2a..5c9520d6 100644 --- a/brewman/brewman/schemas/voucher.py +++ b/brewman/brewman/schemas/voucher.py @@ -3,7 +3,7 @@ import uuid from datetime import date, datetime from decimal import Decimal -from typing import Any, List, Optional +from typing import List, Optional from brewman.schemas import to_camel from brewman.schemas.master import ( @@ -36,7 +36,7 @@ class UserLink(BaseModel): class Journal(BaseModel): id_: Optional[uuid.UUID] debit: int = Field(ge=-1, le=1, multiple_of=1) - amount: Decimal = Field(ge=0, multiple_of=0.01) + amount: Decimal = Field(ge=0) account: AccountLink cost_centre: Optional[CostCentreLink] @@ -164,29 +164,6 @@ class Voucher(VoucherIn): return value return datetime.strptime(value, "%d-%b-%Y").date() - # @validator("journals") - # def validate_enough_journals(cls, value: List[Journal]): - # if 0 < len(value) < 2: - # raise ValueError("Not enough journals") - # return value - # - @validator("journals") - def validate_signed_amount(cls, value: List[Journal]): - if sum(x.debit * x.amount for x in value) != 0: - raise ValueError("Journal amounts do no match") - return value - - @validator("journals") - def is_distinct(cls, value: List[Journal]): - journal_set = set( - hash(x.account.id_) - ^ hash(None if x.cost_centre is None else x.cost_centre.id_) - for x in value - ) - if len(value) != len(journal_set): - raise ValueError("Duplicate journals") - return value - class AttendanceType(BaseModel): id_: int diff --git a/brewman/brewman/scripts/initializedb.py b/brewman/brewman/scripts/initializedb.py index 50a22f3d..d5415053 100644 --- a/brewman/brewman/scripts/initializedb.py +++ b/brewman/brewman/scripts/initializedb.py @@ -1,290 +1,261 @@ -import os -import sys -import uuid - -import transaction - -from brewman.models.auth import ( - Client, - Group, - LoginHistory, - Role, - User, - role_group, - user_group, -) -from brewman.models.master import ( - Account, - AccountBase, - CostCentre, - DbSetting, - Employee, - Product, - ProductGroup, - Recipe, - RecipeItem, -) -from brewman.models.voucher import ( - Attendance, - Batch, - DbImage, - EmployeeBenefit, - Fingerprint, - Incentive, - Inventory, - Journal, - Product, - Voucher, -) -from pyramid.paster import get_appsettings, setup_logging -from pyramid.scripts.common import parse_vars - -from ..models import get_engine, get_session_factory, get_tm_session -from ..models.meta import Base - - -def usage(argv): - cmd = os.path.basename(argv[0]) - print( - "usage: %s [var=value]\n" - '(example: "%s development.ini")' % (cmd, cmd) - ) - sys.exit(1) - - -def main(argv=sys.argv): - if len(argv) < 2: - usage(argv) - config_uri = argv[1] - options = parse_vars(argv[2:]) - setup_logging(config_uri) - settings = get_appsettings(config_uri, options=options) - - engine = get_engine(settings) - Base.metadata.create_all(engine) - - session_factory = get_session_factory(engine) - - with transaction.manager: - dbsession = get_tm_session(session_factory, transaction.manager) - - user = User( - "Admin", "123456", False, uuid.UUID("8de98592-76d9-c74d-bb3f-d6184d388b5a") - ) - dbsession.add(user) - - groups = [ - Group("Owner", uuid.UUID("52e08c0c-048a-784f-be10-6e129ad4b5d4")), - Group("Accountant", uuid.UUID("bc4c2d23-437a-984d-abd4-7d5fce677547")), - Group( - "Accounts Manager", uuid.UUID("cfc44fa7-3392-5b45-b311-5959333f568f") - ), - ] - - for group in groups: - dbsession.add(group) - user.groups.append(group) - - roles = [ - Role("Attendance", uuid.UUID("09d05434-a09a-fa45-963b-769a2e3fc667")), - Role("Trial Balance", uuid.UUID("3b099fec-ddc5-4243-b30e-afb78d9ca14a")), - Role("Cash Flow", uuid.UUID("c4d3ae29-420b-ea4c-ae90-00a356263fd9")), - Role("Cost Centres", uuid.UUID("6fcc1a20-6aec-e840-b334-1632b34aeab8")), - Role("Users", uuid.UUID("c5b7d9d7-f178-0e45-8ea4-bf4e08ec901b")), - Role("Daybook", uuid.UUID("c3edb554-a057-8942-8030-37b8e926d583")), - Role( - "Edit Posted Vouchers", - uuid.UUID("d6675817-ddf5-bf40-9de6-fa223eb4aaa6"), - ), - Role("Employees", uuid.UUID("e4edd0ac-7f5d-e64d-8611-73fdc4cd8ba2")), - Role("Fingerprints", uuid.UUID("d9c45323-f997-ba46-9407-8a7145f0828b")), - Role("Issue", uuid.UUID("03b602eb-f58a-b94f-af58-8cb47d7849d0")), - Role("Journal", uuid.UUID("7661388f-62ce-1c41-8e0d-0326ee5d4018")), - Role("Accounts", uuid.UUID("f438262f-72dd-2f4e-9186-5abc3af44fba")), - Role("Product Ledger", uuid.UUID("018a2408-e804-1446-90c5-b015829da6ba")), - Role( - "Backdated Vouchers", uuid.UUID("b67b2062-5ca7-134f-8258-5d284dd92426") - ), - Role("Payment", uuid.UUID("f85c0b52-c3fd-7141-8957-7a56cdc014a4")), - Role("Post Vouchers", uuid.UUID("36e741da-1a57-b047-a59e-dcd58fcf4338")), - Role("Products", uuid.UUID("74fa6d21-eebb-e14c-8153-bebc57190ab4")), - Role("Product Groups", uuid.UUID("08413a22-cf88-fd43-b2b7-365d2951d99f")), - Role("Profit & Loss", uuid.UUID("0492ebb3-76f3-204e-ab94-bbfe880f0691")), - Role("Purchase", uuid.UUID("12335acb-8630-2d41-a191-1517c8d172de")), - Role("Purchase Entries", uuid.UUID("78a6422b-aa11-174c-9dfa-412a99e87e02")), - Role("Purchase Return", uuid.UUID("ab33196e-d9e4-114c-ac8c-997954363756")), - Role("Receipt", uuid.UUID("1f1ce53e-76ff-a346-974a-65db6f606e5f")), - Role("Recipes", uuid.UUID("ffb7fb65-d42c-424d-9ff1-45069e3b4a29")), - Role("Closing Stock", uuid.UUID("97515732-24e4-c94d-9585-d4bd7f6c7891")), - Role("Ledger", uuid.UUID("a2120944-243f-3f49-be57-0ad633ce4801")), - Role( - "Raw Material Cost", uuid.UUID("d462842b-baf1-2343-95e5-ffdba9bbc163") - ), - Role( - "Edit Other User's Vouchers", - uuid.UUID("a8328891-7ce2-a943-8c29-2eabc1ffeea3"), - ), - Role("Clients", uuid.UUID("cfad44f0-f2a9-7045-89d7-9019cf0f371a")), - Role("Employee Benefit", uuid.UUID("92d70e80-1c32-384d-959e-abf84b804696")), - Role("Messages", uuid.UUID("f586d128-b6d9-4090-a913-78fcbdb68e59")), - Role("Lock Date", uuid.UUID("d52de0be-9388-4b0b-a359-7e122ab6e53a")), - Role("Net Transactions", uuid.UUID("2c40f7cf-67fc-4efa-a670-8d16a2e7884d")), - Role("Balance Sheet", uuid.UUID("40deb018-b8f2-460a-88be-8972c9fcdf04")), - Role("Advanced Delete", uuid.UUID("197ebcd2-bc4a-4b65-a138-ce942ece32ea")), - Role("Rebase", uuid.UUID("de204a88-5f9d-4579-a2d6-aa2f25efde42")), - Role("Reset Stock", uuid.UUID("aecaf82f-aa41-4634-b754-0c1308b621b1")), - Role("Reconcile", uuid.UUID("a5cb51cb-e38e-4705-84a7-cc1e9a8b866b")), - Role("Stock Movement", uuid.UUID("20b707ee-2b59-41ad-be87-76d5fe1efca8")), - Role("Purchases", uuid.UUID("cf7019c8-3fd3-45b0-9a42-601029ce5b71")), - Role("Dashboard", uuid.UUID("53eecc09-bd06-4890-b6f5-6885dda762d4")), - Role("Incentive", uuid.UUID("99b56390-96c2-4f3d-8b0f-5ae3c868594f")), - Role("Maintenance", uuid.UUID("770532e4-21de-4712-8a6b-4ff9fd63a503")), - ] - - for role in roles: - dbsession.add(role) - groups[0].roles.append(role) - - cost_centres = [ - CostCentre( - "Overall", uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), True - ), - CostCentre( - "Purchase", uuid.UUID("7b845f95-dfef-fa4a-897c-f0baf15284a3"), True - ), - CostCentre( - "Kitchen", uuid.UUID("b2d398ce-e3cc-c542-9feb-5d7783e899df"), True - ), - ] - - for cost_centre in cost_centres: - dbsession.add(cost_centre) - - accounts = [ - Account( - 1, - "All Purchases", - 2, - False, - True, - False, - uuid.UUID("7b845f95-dfef-fa4a-897c-f0baf15284a3"), - uuid.UUID("240dd899-c413-854c-a7eb-67a29d154490"), - True, - ), - Account( - 1, - "Local Purchase", - 9, - False, - True, - False, - uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), - uuid.UUID("d2b75912-505f-2548-9093-466dfff6a0f9"), - True, - ), - Account( - 1, - "ESI/PF - Payable", - 11, - False, - True, - False, - uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), - uuid.UUID("42277912-cc18-854b-b134-9f4b00dba419"), - True, - ), - Account( - 2, - "ESI/PF - Expense", - 7, - False, - True, - False, - uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), - uuid.UUID("d2a1a286-e900-764b-a1a5-9f4b00dbb940"), - True, - ), - Account( - 1, - "Cash in Hand", - 1, - False, - True, - False, - uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), - uuid.UUID("ed2341bb-80b8-9649-90db-f9aaca183bb3"), - True, - ), - Account( - 1, - "Staff Salary", - 7, - False, - True, - False, - uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), - uuid.UUID("5c2b54d0-c174-004d-a0d5-92cdaadcefa7"), - True, - ), - Account( - 2, - "Incentives", - 11, - False, - True, - False, - uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), - uuid.UUID("b7eff754-e8ba-e047-ab06-9132c15c7640"), - True, - ), - Account( - 1, - "Suspense", - 4, - False, - True, - False, - uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), - uuid.UUID("3854e317-6f3b-5142-ab26-9c44d4cddd08"), - True, - ), - ] - - for account in accounts: - dbsession.add(account) - - product_group = ProductGroup( - "Suspense", uuid.UUID("ae59a20c-87bb-444a-8abb-915ad5e58b83"), True - ) - dbsession.add(product_group) - - dbsession.add( - ProductGroup( - "Semi", uuid.UUID("e6bf81b9-1e9b-499f-81d5-ab5662e9d9b1"), True - ) - ) - dbsession.add( - ProductGroup( - "Menu Items", uuid.UUID("dad46805-f577-4e5b-8073-9b788e0173fc"), True - ) - ) - - product = Product( - 1, - "Suspense", - "", - 1, - "", - 1, - uuid.UUID("ae59a20c-87bb-444a-8abb-915ad5e58b83"), - uuid.UUID("240dd899-c413-854c-a7eb-67a29d154490"), - 0, - 0, - False, - False, - False, - uuid.UUID("aa79a643-9ddc-4790-ac7f-a41f9efb4c15"), - True, - ) - dbsession.add(product) +# import os +# import sys +# import uuid +# +# from brewman.models.auth import ( +# Client, +# Role, +# LoginHistory, +# Permission, +# User, +# role_permission, +# user_role, +# ) +# from brewman.models.master import ( +# Account, +# AccountBase, +# CostCentre, +# DbSetting, +# Employee, +# Product, +# ProductGroup, +# Recipe, +# RecipeItem, +# ) +# from brewman.models.voucher import ( +# Attendance, +# Batch, +# DbImage, +# EmployeeBenefit, +# Fingerprint, +# Incentive, +# Inventory, +# Journal, +# Product, +# Voucher, +# ) +# from pyramid.paster import get_appsettings, setup_logging +# from pyramid.scripts.common import parse_vars +# +# from ..models import get_engine, get_session_factory, get_tm_session +# from ..models.meta import Base +# +# +# def usage(argv): +# cmd = os.path.basename(argv[0]) +# print("usage: %s [var=value]\n" '(example: "%s development.ini")' % (cmd, cmd)) +# sys.exit(1) +# +# +# def main(argv=sys.argv): +# if len(argv) < 2: +# usage(argv) +# config_uri = argv[1] +# options = parse_vars(argv[2:]) +# setup_logging(config_uri) +# settings = get_appsettings(config_uri, options=options) +# +# engine = get_engine(settings) +# Base.metadata.create_all(engine) +# +# session_factory = get_session_factory(engine) +# +# with transaction.manager: +# dbsession = get_tm_session(session_factory, transaction.manager) +# +# user = User("Admin", "123456", False, uuid.UUID("8de98592-76d9-c74d-bb3f-d6184d388b5a")) +# dbsession.add(user) +# +# groups = [ +# Group("Owner", uuid.UUID("52e08c0c-048a-784f-be10-6e129ad4b5d4")), +# Group("Accountant", uuid.UUID("bc4c2d23-437a-984d-abd4-7d5fce677547")), +# Group("Accounts Manager", uuid.UUID("cfc44fa7-3392-5b45-b311-5959333f568f")), +# ] +# +# for group in groups: +# dbsession.add(group) +# user.groups.append(group) +# +# roles = [ +# Role("Attendance", uuid.UUID("09d05434-a09a-fa45-963b-769a2e3fc667")), +# Role("Trial Balance", uuid.UUID("3b099fec-ddc5-4243-b30e-afb78d9ca14a")), +# Role("Cash Flow", uuid.UUID("c4d3ae29-420b-ea4c-ae90-00a356263fd9")), +# Role("Cost Centres", uuid.UUID("6fcc1a20-6aec-e840-b334-1632b34aeab8")), +# Role("Users", uuid.UUID("c5b7d9d7-f178-0e45-8ea4-bf4e08ec901b")), +# Role("Daybook", uuid.UUID("c3edb554-a057-8942-8030-37b8e926d583")), +# Role( +# "Edit Posted Vouchers", +# uuid.UUID("d6675817-ddf5-bf40-9de6-fa223eb4aaa6"), +# ), +# Role("Employees", uuid.UUID("e4edd0ac-7f5d-e64d-8611-73fdc4cd8ba2")), +# Role("Fingerprints", uuid.UUID("d9c45323-f997-ba46-9407-8a7145f0828b")), +# Role("Issue", uuid.UUID("03b602eb-f58a-b94f-af58-8cb47d7849d0")), +# Role("Journal", uuid.UUID("7661388f-62ce-1c41-8e0d-0326ee5d4018")), +# Role("Accounts", uuid.UUID("f438262f-72dd-2f4e-9186-5abc3af44fba")), +# Role("Product Ledger", uuid.UUID("018a2408-e804-1446-90c5-b015829da6ba")), +# Role("Backdated Vouchers", uuid.UUID("b67b2062-5ca7-134f-8258-5d284dd92426")), +# Role("Payment", uuid.UUID("f85c0b52-c3fd-7141-8957-7a56cdc014a4")), +# Role("Post Vouchers", uuid.UUID("36e741da-1a57-b047-a59e-dcd58fcf4338")), +# Role("Products", uuid.UUID("74fa6d21-eebb-e14c-8153-bebc57190ab4")), +# Role("Product Groups", uuid.UUID("08413a22-cf88-fd43-b2b7-365d2951d99f")), +# Role("Profit & Loss", uuid.UUID("0492ebb3-76f3-204e-ab94-bbfe880f0691")), +# Role("Purchase", uuid.UUID("12335acb-8630-2d41-a191-1517c8d172de")), +# Role("Purchase Entries", uuid.UUID("78a6422b-aa11-174c-9dfa-412a99e87e02")), +# Role("Purchase Return", uuid.UUID("ab33196e-d9e4-114c-ac8c-997954363756")), +# Role("Receipt", uuid.UUID("1f1ce53e-76ff-a346-974a-65db6f606e5f")), +# Role("Recipes", uuid.UUID("ffb7fb65-d42c-424d-9ff1-45069e3b4a29")), +# Role("Closing Stock", uuid.UUID("97515732-24e4-c94d-9585-d4bd7f6c7891")), +# Role("Ledger", uuid.UUID("a2120944-243f-3f49-be57-0ad633ce4801")), +# Role("Raw Material Cost", uuid.UUID("d462842b-baf1-2343-95e5-ffdba9bbc163")), +# Role( +# "Edit Other User's Vouchers", +# uuid.UUID("a8328891-7ce2-a943-8c29-2eabc1ffeea3"), +# ), +# Role("Clients", uuid.UUID("cfad44f0-f2a9-7045-89d7-9019cf0f371a")), +# Role("Employee Benefit", uuid.UUID("92d70e80-1c32-384d-959e-abf84b804696")), +# Role("Messages", uuid.UUID("f586d128-b6d9-4090-a913-78fcbdb68e59")), +# Role("Lock Date", uuid.UUID("d52de0be-9388-4b0b-a359-7e122ab6e53a")), +# Role("Net Transactions", uuid.UUID("2c40f7cf-67fc-4efa-a670-8d16a2e7884d")), +# Role("Balance Sheet", uuid.UUID("40deb018-b8f2-460a-88be-8972c9fcdf04")), +# Role("Advanced Delete", uuid.UUID("197ebcd2-bc4a-4b65-a138-ce942ece32ea")), +# Role("Rebase", uuid.UUID("de204a88-5f9d-4579-a2d6-aa2f25efde42")), +# Role("Reset Stock", uuid.UUID("aecaf82f-aa41-4634-b754-0c1308b621b1")), +# Role("Reconcile", uuid.UUID("a5cb51cb-e38e-4705-84a7-cc1e9a8b866b")), +# Role("Stock Movement", uuid.UUID("20b707ee-2b59-41ad-be87-76d5fe1efca8")), +# Role("Purchases", uuid.UUID("cf7019c8-3fd3-45b0-9a42-601029ce5b71")), +# Role("Dashboard", uuid.UUID("53eecc09-bd06-4890-b6f5-6885dda762d4")), +# Role("Incentive", uuid.UUID("99b56390-96c2-4f3d-8b0f-5ae3c868594f")), +# Role("Maintenance", uuid.UUID("770532e4-21de-4712-8a6b-4ff9fd63a503")), +# ] +# +# for role in roles: +# dbsession.add(role) +# groups[0].roles.append(role) +# +# cost_centres = [ +# CostCentre("Overall", uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), True), +# CostCentre("Purchase", uuid.UUID("7b845f95-dfef-fa4a-897c-f0baf15284a3"), True), +# CostCentre("Kitchen", uuid.UUID("b2d398ce-e3cc-c542-9feb-5d7783e899df"), True), +# ] +# +# for cost_centre in cost_centres: +# dbsession.add(cost_centre) +# +# accounts = [ +# Account( +# 1, +# "All Purchases", +# 2, +# False, +# True, +# False, +# uuid.UUID("7b845f95-dfef-fa4a-897c-f0baf15284a3"), +# uuid.UUID("240dd899-c413-854c-a7eb-67a29d154490"), +# True, +# ), +# Account( +# 1, +# "Local Purchase", +# 9, +# False, +# True, +# False, +# uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), +# uuid.UUID("d2b75912-505f-2548-9093-466dfff6a0f9"), +# True, +# ), +# Account( +# 1, +# "ESI/PF - Payable", +# 11, +# False, +# True, +# False, +# uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), +# uuid.UUID("42277912-cc18-854b-b134-9f4b00dba419"), +# True, +# ), +# Account( +# 2, +# "ESI/PF - Expense", +# 7, +# False, +# True, +# False, +# uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), +# uuid.UUID("d2a1a286-e900-764b-a1a5-9f4b00dbb940"), +# True, +# ), +# Account( +# 1, +# "Cash in Hand", +# 1, +# False, +# True, +# False, +# uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), +# uuid.UUID("ed2341bb-80b8-9649-90db-f9aaca183bb3"), +# True, +# ), +# Account( +# 1, +# "Staff Salary", +# 7, +# False, +# True, +# False, +# uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), +# uuid.UUID("5c2b54d0-c174-004d-a0d5-92cdaadcefa7"), +# True, +# ), +# Account( +# 2, +# "Incentives", +# 11, +# False, +# True, +# False, +# uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), +# uuid.UUID("b7eff754-e8ba-e047-ab06-9132c15c7640"), +# True, +# ), +# Account( +# 1, +# "Suspense", +# 4, +# False, +# True, +# False, +# uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), +# uuid.UUID("3854e317-6f3b-5142-ab26-9c44d4cddd08"), +# True, +# ), +# ] +# +# for account in accounts: +# dbsession.add(account) +# +# product_group = ProductGroup("Suspense", uuid.UUID("ae59a20c-87bb-444a-8abb-915ad5e58b83"), True) +# dbsession.add(product_group) +# +# dbsession.add(ProductGroup("Semi", uuid.UUID("e6bf81b9-1e9b-499f-81d5-ab5662e9d9b1"), True)) +# dbsession.add(ProductGroup("Menu Items", uuid.UUID("dad46805-f577-4e5b-8073-9b788e0173fc"), True)) +# +# product = Product( +# 1, +# "Suspense", +# "", +# 1, +# "", +# 1, +# uuid.UUID("ae59a20c-87bb-444a-8abb-915ad5e58b83"), +# uuid.UUID("240dd899-c413-854c-a7eb-67a29d154490"), +# 0, +# 0, +# False, +# False, +# False, +# uuid.UUID("aa79a643-9ddc-4790-ac7f-a41f9efb4c15"), +# True, +# ) +# dbsession.add(product) diff --git a/brewman/pyproject.toml b/brewman/pyproject.toml index a47d1c19..5476ce87 100644 --- a/brewman/pyproject.toml +++ b/brewman/pyproject.toml @@ -42,7 +42,7 @@ filter_files = true known_first_party = "poetry" [tool.black] -line-length = 88 +line-length = 120 include = '\.pyi?$' exclude = ''' /( @@ -58,4 +58,4 @@ exclude = ''' | dist | tests/.*/setup.py )/ -''' \ No newline at end of file +''' diff --git a/overlord/src/app/payment/payment.component.ts b/overlord/src/app/payment/payment.component.ts index 21e371c8..49255ecb 100644 --- a/overlord/src/app/payment/payment.component.ts +++ b/overlord/src/app/payment/payment.component.ts @@ -165,15 +165,6 @@ export class PaymentComponent implements OnInit, AfterViewInit, OnDestroy { this.resetAddRow(); this.updateView(); } - // - // rowAmount(amount: string = ''): number { - // try { - // amount = amount.replace(new RegExp('(₹[s]*)|(,)|(s)', 'g'), ''); - // return round(evaluate(amount), 2); - // } catch { - // return 0; - // } - // } resetAddRow() { this.form.get('addRow').reset({ diff --git a/overlord/src/app/receipt/receipt.component.ts b/overlord/src/app/receipt/receipt.component.ts index b8292424..66dd7f39 100644 --- a/overlord/src/app/receipt/receipt.component.ts +++ b/overlord/src/app/receipt/receipt.component.ts @@ -168,15 +168,6 @@ export class ReceiptComponent implements OnInit, AfterViewInit, OnDestroy { this.resetAddRow(); this.updateView(); } - // - // rowAmount(amount: string = ''): number { - // try { - // amount = amount.replace(new RegExp('(₹[s]*)|(,)|(s)', 'g'), ''); - // return round(evaluate(amount), 2); - // } catch { - // return 0; - // } - // } resetAddRow() { this.form.get('addRow').reset({ diff --git a/overlord/src/environments/environment.ts b/overlord/src/environments/environment.ts index bbb8d266..41f4d5ec 100644 --- a/overlord/src/environments/environment.ts +++ b/overlord/src/environments/environment.ts @@ -5,7 +5,7 @@ export const environment = { production: false, ACCESS_TOKEN_REFRESH_MINUTES: 10, // refresh token 10 minutes before expiry - version: '8.0.1', + version: '8.0.2', }; /*