diff --git a/brewman/core/security.py b/brewman/core/security.py index c71e28a4..509db468 100644 --- a/brewman/core/security.py +++ b/brewman/core/security.py @@ -55,7 +55,9 @@ 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 @@ -76,9 +78,15 @@ 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: @@ -108,7 +116,9 @@ async def get_current_user( 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/core/session.py b/brewman/core/session.py index 13abcd87..540d7105 100644 --- a/brewman/core/session.py +++ b/brewman/core/session.py @@ -26,7 +26,9 @@ 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/main.py b/brewman/main.py index 39f561f3..3bd2ced1 100644 --- a/brewman/main.py +++ b/brewman/main.py @@ -68,16 +68,28 @@ 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"]) @@ -90,13 +102,23 @@ 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"]) @@ -106,14 +128,20 @@ 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/models/auth.py b/brewman/models/auth.py index a1e0ad4b..f3ebb26d 100644 --- a/brewman/models/auth.py +++ b/brewman/models/auth.py @@ -42,14 +42,18 @@ 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 @@ -118,9 +122,18 @@ 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) - client_id = Column("client_id", UUID(as_uuid=True), ForeignKey("auth_clients.client_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), + ForeignKey("auth_clients.client_id"), + nullable=False, + ) date = Column("date", DateTime(timezone=True), nullable=False) def __init__(self, user_id=None, client_id=None, date=None, id_=None): diff --git a/brewman/models/master.py b/brewman/models/master.py index 603073c2..83c49d47 100644 --- a/brewman/models/master.py +++ b/brewman/models/master.py @@ -37,7 +37,9 @@ 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) @@ -48,7 +50,9 @@ 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, @@ -125,7 +129,9 @@ 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) @@ -168,15 +174,23 @@ 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 @@ -257,7 +271,12 @@ class AccountBase(Base): is_starred = Column("is_starred", Boolean, nullable=False) is_active = Column("is_active", Boolean, nullable=False) is_reconcilable = Column("is_reconcilable", Boolean, nullable=False) - cost_centre_id = Column("cost_centre_id", UUID(as_uuid=True), ForeignKey("cost_centres.id"), nullable=False) + cost_centre_id = Column( + "cost_centre_id", + UUID(as_uuid=True), + ForeignKey("cost_centres.id"), + nullable=False, + ) is_fixture = Column("is_fixture", Boolean, nullable=False) __mapper_args__ = {"polymorphic_on": account_type} @@ -311,7 +330,11 @@ 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 @@ -327,7 +350,11 @@ 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 @@ -382,8 +409,12 @@ 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, @@ -414,7 +445,11 @@ 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/models/voucher.py b/brewman/models/voucher.py index 23f5dfc0..b701b12d 100644 --- a/brewman/models/voucher.py +++ b/brewman/models/voucher.py @@ -72,12 +72,16 @@ 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", @@ -153,9 +157,22 @@ class Journal(Base): id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) debit = Column("debit", Integer) amount = Column("amount", Numeric) - voucher_id = Column("voucher_id", UUID(as_uuid=True), ForeignKey("vouchers.id"), nullable=False, index=True) - 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), ForeignKey("cost_centres.id"), nullable=False) + voucher_id = Column( + "voucher_id", + UUID(as_uuid=True), + ForeignKey("vouchers.id"), + nullable=False, + index=True, + ) + 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), + ForeignKey("cost_centres.id"), + nullable=False, + ) voucher = relationship("Voucher", back_populates="journals") account = relationship("AccountBase", back_populates="journals") @@ -188,8 +205,12 @@ 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) @@ -234,8 +255,12 @@ 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) @@ -269,9 +294,19 @@ class Inventory(Base): __tablename__ = "inventories" __table_args__ = (UniqueConstraint("voucher_id", "batch_id"),) 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, 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) + voucher_id = Column( + "voucher_id", + UUID(as_uuid=True), + ForeignKey("vouchers.id"), + 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 + ) quantity = Column("quantity", Numeric) rate = Column("rate", Numeric) tax = Column("tax", Numeric) @@ -317,13 +352,17 @@ 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, @@ -347,7 +386,9 @@ 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, name, include_nil, date, db: Session): diff --git a/brewman/routers/__init__.py b/brewman/routers/__init__.py index da49efcf..6f8d7aa7 100644 --- a/brewman/routers/__init__.py +++ b/brewman/routers/__init__.py @@ -41,7 +41,9 @@ 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/routers/account.py b/brewman/routers/account.py index 46f0a126..57ececbd 100644 --- a/brewman/routers/account.py +++ b/brewman/routers/account.py @@ -133,7 +133,11 @@ 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() ] @@ -187,7 +191,11 @@ 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 @@ -219,7 +227,9 @@ 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)) @@ -241,9 +251,13 @@ 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/routers/account_types.py b/brewman/routers/account_types.py index 88c02f4c..d44de7dc 100644 --- a/brewman/routers/account_types.py +++ b/brewman/routers/account_types.py @@ -14,4 +14,6 @@ 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/routers/attendance.py b/brewman/routers/attendance.py index 19bba8a0..05be1c3c 100644 --- a/brewman/routers/attendance.py +++ b/brewman/routers/attendance.py @@ -29,7 +29,9 @@ 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": []} diff --git a/brewman/routers/attendance_report.py b/brewman/routers/attendance_report.py index 3e0d5dca..fca892f7 100644 --- a/brewman/routers/attendance_report.py +++ b/brewman/routers/attendance_report.py @@ -41,7 +41,9 @@ 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: diff --git a/brewman/routers/auth/client.py b/brewman/routers/auth/client.py index fee90668..16ee2237 100644 --- a/brewman/routers/auth/client.py +++ b/brewman/routers/auth/client.py @@ -83,9 +83,16 @@ 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() + 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") ) - 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/routers/auth/role.py b/brewman/routers/auth/role.py index 1a1a46be..ccd0182f 100644 --- a/brewman/routers/auth/role.py +++ b/brewman/routers/auth/role.py @@ -78,7 +78,9 @@ 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) @@ -123,7 +125,9 @@ 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/routers/auth/user.py b/brewman/routers/auth/user.py index 89b91405..55e3241c 100644 --- a/brewman/routers/auth/user.py +++ b/brewman/routers/auth/user.py @@ -170,8 +170,13 @@ async def show_list( @router.get("/active") -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)] +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) + ] @router.get("/{id_}", response_model=schemas.User) @@ -189,7 +194,10 @@ 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/routers/batch.py b/brewman/routers/batch.py index 2f4f9db9..3491fc6e 100644 --- a/brewman/routers/batch.py +++ b/brewman/routers/batch.py @@ -32,7 +32,9 @@ def batch_term( filter_ = q if q is not None and q.strip() != "" else None date = None if not d else datetime.datetime.strptime(d, "%d-%b-%Y") list_ = [] - for index, item in enumerate(Batch.list(filter_, include_nil=False, date=date, db=db)): + for index, item in enumerate( + Batch.list(filter_, 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')}" list_.append( { diff --git a/brewman/routers/db_integrity.py b/brewman/routers/db_integrity.py index 5c720db4..423f8144 100644 --- a/brewman/routers/db_integrity.py +++ b/brewman/routers/db_integrity.py @@ -44,7 +44,9 @@ def get_duplicate_attendances(db): .subquery() ) query = ( - db.query(func.count(Attendance.id)).filter(~Attendance.id.in_(sub_query)).filter(Attendance.is_valid == True) + db.query(func.count(Attendance.id)) + .filter(~Attendance.id.in_(sub_query)) + .filter(Attendance.is_valid == True) ) return query.scalar() @@ -61,4 +63,6 @@ def fix_duplicate_attendances(db): .filter(Attendance.is_valid == True) .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) diff --git a/brewman/routers/employee.py b/brewman/routers/employee.py index 42939c27..a2087b9d 100644 --- a/brewman/routers/employee.py +++ b/brewman/routers/employee.py @@ -134,7 +134,9 @@ 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) @@ -205,7 +207,9 @@ 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, @@ -216,7 +220,9 @@ 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)) @@ -238,9 +244,13 @@ 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/routers/employee_attendance.py b/brewman/routers/employee_attendance.py index e4d6e153..82b65495 100644 --- a/brewman/routers/employee_attendance.py +++ b/brewman/routers/employee_attendance.py @@ -66,15 +66,21 @@ 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 = ( diff --git a/brewman/routers/employee_benefit.py b/brewman/routers/employee_benefit.py index eb0a1cc3..8c3c489a 100644 --- a/brewman/routers/employee_benefit.py +++ b/brewman/routers/employee_benefit.py @@ -51,7 +51,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) save_files(item.id, i, t, db) db.commit() @@ -69,7 +71,9 @@ 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_, @@ -93,8 +97,12 @@ 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, @@ -120,7 +128,11 @@ 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, @@ -129,7 +141,11 @@ 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, @@ -159,7 +175,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) update_files(item.id, data.files, i, t, db) @@ -177,7 +195,9 @@ 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) @@ -209,14 +229,20 @@ 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 @@ -254,8 +280,16 @@ 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 @@ -263,6 +297,14 @@ 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/routers/fingerprint.py b/brewman/routers/fingerprint.py index 60f2fc83..10c2b25f 100644 --- a/brewman/routers/fingerprint.py +++ b/brewman/routers/fingerprint.py @@ -32,7 +32,9 @@ def get_db() -> Session: @router.post("") def upload_prints( - db: Session = Depends(get_db), fingerprints: UploadFile = File(None), user: UserToken = Depends(get_user) + db: Session = Depends(get_db), + fingerprints: UploadFile = File(None), + user: UserToken = Depends(get_user), ): try: start, finish = get_lock_info(db) @@ -72,7 +74,9 @@ 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"), @@ -143,7 +147,9 @@ 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() ) @@ -162,7 +168,9 @@ 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/routers/incentive.py b/brewman/routers/incentive.py index b236337e..ba19b266 100644 --- a/brewman/routers/incentive.py +++ b/brewman/routers/incentive.py @@ -47,7 +47,9 @@ 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) @@ -95,7 +97,9 @@ 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) @@ -103,7 +107,9 @@ 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) @@ -118,7 +124,9 @@ 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) @@ -137,7 +145,9 @@ 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) @@ -157,14 +167,18 @@ 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 @@ -228,7 +242,9 @@ def get_employees( .filter(Attendance.is_valid == True) .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( @@ -263,7 +279,9 @@ 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/routers/issue.py b/brewman/routers/issue.py index 6dec34ef..4c9e2bb7 100644 --- a/brewman/routers/issue.py +++ b/brewman/routers/issue.py @@ -67,7 +67,9 @@ 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_, @@ -187,7 +189,9 @@ 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) @@ -246,7 +250,10 @@ 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}", diff --git a/brewman/routers/issue_grid.py b/brewman/routers/issue_grid.py index 09da3675..60bc0e4e 100644 --- a/brewman/routers/issue_grid.py +++ b/brewman/routers/issue_grid.py @@ -53,8 +53,12 @@ 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/routers/journal.py b/brewman/routers/journal.py index d9692994..e9efcb11 100644 --- a/brewman/routers/journal.py +++ b/brewman/routers/journal.py @@ -76,7 +76,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, debit=item.debit, @@ -115,7 +117,9 @@ 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) @@ -132,7 +136,11 @@ def update(id_: uuid.UUID, data: schema_in.JournalIn, user: UserToken, db: Sessi 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 @@ -143,7 +151,9 @@ def update(id_: uuid.UUID, data: schema_in.JournalIn, user: UserToken, db: Sessi 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, diff --git a/brewman/routers/login.py b/brewman/routers/login.py index b6fc90fa..a7643930 100644 --- a/brewman/routers/login.py +++ b/brewman/routers/login.py @@ -56,21 +56,33 @@ 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, }, diff --git a/brewman/routers/product.py b/brewman/routers/product.py index 0bcf4b67..486160cb 100644 --- a/brewman/routers/product.py +++ b/brewman/routers/product.py @@ -232,7 +232,9 @@ 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) @@ -260,11 +262,15 @@ 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/routers/purchase.py b/brewman/routers/purchase.py index af91f07a..ec602605 100644 --- a/brewman/routers/purchase.py +++ b/brewman/routers/purchase.py @@ -81,9 +81,13 @@ 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, @@ -164,7 +168,9 @@ 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) @@ -177,14 +183,20 @@ def update(id_: uuid.UUID, data: schema_in.PurchaseIn, user: UserToken, db: Sess 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( @@ -232,7 +244,9 @@ def update_inventory(voucher: Voucher, new_inventories: List[schema_in.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/routers/purchase_return.py b/brewman/routers/purchase_return.py index f1dc3743..3a0ea568 100644 --- a/brewman/routers/purchase_return.py +++ b/brewman/routers/purchase_return.py @@ -80,7 +80,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: batch = db.query(Batch).filter(Batch.id == item.batch.id_).first() @@ -166,7 +168,9 @@ 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) @@ -179,7 +183,9 @@ def update(id_: uuid.UUID, data: schema_in.PurchaseIn, user: UserToken, db: Sess 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/routers/rebase.py b/brewman/routers/rebase.py index cd47e9e6..b9720f71 100644 --- a/brewman/routers/rebase.py +++ b/brewman/routers/rebase.py @@ -58,7 +58,10 @@ 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() + ] vouchers = [] query = ( db.query(Voucher) @@ -70,7 +73,11 @@ 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) @@ -86,7 +93,9 @@ 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: @@ -205,9 +214,15 @@ 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_( @@ -217,19 +232,27 @@ 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) @@ -246,7 +269,8 @@ 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"], ) ) ) diff --git a/brewman/routers/recipe.py b/brewman/routers/recipe.py index 4063da9a..b1131c03 100644 --- a/brewman/routers/recipe.py +++ b/brewman/routers/recipe.py @@ -20,15 +20,21 @@ 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") @@ -61,15 +67,25 @@ 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: @@ -100,7 +116,11 @@ 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) @@ -158,12 +178,20 @@ 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) @@ -196,7 +224,9 @@ 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( @@ -209,7 +239,9 @@ 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: @@ -228,7 +260,11 @@ 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/routers/reports/balance_sheet.py b/brewman/routers/reports/balance_sheet.py index 81886f3d..6e1c6ece 100644 --- a/brewman/routers/reports/balance_sheet.py +++ b/brewman/routers/reports/balance_sheet.py @@ -72,7 +72,9 @@ 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] = { @@ -110,7 +112,9 @@ 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/routers/reports/closing_stock.py b/brewman/routers/reports/closing_stock.py index e2a49697..44706cd4 100644 --- a/brewman/routers/reports/closing_stock.py +++ b/brewman/routers/reports/closing_stock.py @@ -49,7 +49,9 @@ 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) @@ -79,7 +81,14 @@ 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) @@ -92,7 +101,14 @@ 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/routers/reports/net_transactions.py b/brewman/routers/reports/net_transactions.py index 162dfc2f..5297f5ff 100644 --- a/brewman/routers/reports/net_transactions.py +++ b/brewman/routers/reports/net_transactions.py @@ -77,5 +77,7 @@ 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/routers/reports/product_ledger.py b/brewman/routers/reports/product_ledger.py index c01807c9..4d761e53 100644 --- a/brewman/routers/reports/product_ledger.py +++ b/brewman/routers/reports/product_ledger.py @@ -68,9 +68,13 @@ 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 = ( @@ -117,7 +121,8 @@ def build_report(product_id: uuid.UUID, start_date: date, finish_date: date, db: ], "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/routers/reports/profit_loss.py b/brewman/routers/reports/profit_loss.py index adf28a7c..bcec6764 100644 --- a/brewman/routers/reports/profit_loss.py +++ b/brewman/routers/reports/profit_loss.py @@ -48,7 +48,9 @@ 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, @@ -83,7 +85,9 @@ 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/routers/reports/purchases.py b/brewman/routers/reports/purchases.py index 3b46b36b..7c25cb6a 100644 --- a/brewman/routers/reports/purchases.py +++ b/brewman/routers/reports/purchases.py @@ -60,7 +60,9 @@ 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) @@ -89,5 +91,7 @@ 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/routers/reports/raw_material_cost.py b/brewman/routers/reports/raw_material_cost.py index dcf326a7..2a4b851c 100644 --- a/brewman/routers/reports/raw_material_cost.py +++ b/brewman/routers/reports/raw_material_cost.py @@ -49,7 +49,9 @@ 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, @@ -68,7 +70,9 @@ 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_, @@ -80,8 +84,12 @@ 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) @@ -117,7 +125,9 @@ 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/routers/reports/reconcile.py b/brewman/routers/reports/reconcile.py index eab96502..2c088488 100644 --- a/brewman/routers/reports/reconcile.py +++ b/brewman/routers/reports/reconcile.py @@ -72,8 +72,10 @@ 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"), ), ) ) @@ -122,7 +124,9 @@ 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/routers/reports/stock_movement.py b/brewman/routers/reports/stock_movement.py index f256c473..27029cc7 100644 --- a/brewman/routers/reports/stock_movement.py +++ b/brewman/routers/reports/stock_movement.py @@ -47,7 +47,9 @@ 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/routers/reports/trial_balance.py b/brewman/routers/reports/trial_balance.py index 08c8f6b1..5b69e7ad 100644 --- a/brewman/routers/reports/trial_balance.py +++ b/brewman/routers/reports/trial_balance.py @@ -66,5 +66,7 @@ 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/routers/reset_stock.py b/brewman/routers/reset_stock.py index c8836ff4..03b0859f 100644 --- a/brewman/routers/reset_stock.py +++ b/brewman/routers/reset_stock.py @@ -39,7 +39,9 @@ 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) @@ -73,7 +75,12 @@ 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, @@ -84,7 +91,11 @@ 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/routers/voucher.py b/brewman/routers/voucher.py index b0098916..b73fe858 100644 --- a/brewman/routers/voucher.py +++ b/brewman/routers/voucher.py @@ -72,7 +72,10 @@ 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", @@ -209,7 +212,9 @@ 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, @@ -221,7 +226,9 @@ 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')}" json_voucher["inventories"].append( @@ -291,7 +298,11 @@ 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: @@ -300,7 +311,11 @@ 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: @@ -310,7 +325,9 @@ 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"]} @@ -323,7 +340,9 @@ 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, @@ -382,12 +401,22 @@ 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.", @@ -410,7 +439,10 @@ 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/schemas/input.py b/brewman/schemas/input.py index 0511ee5f..51d67192 100644 --- a/brewman/schemas/input.py +++ b/brewman/schemas/input.py @@ -45,7 +45,9 @@ class JournalIn(VoucherIn): @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 + 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") diff --git a/brewman/schemas/voucher.py b/brewman/schemas/voucher.py index 1250996a..a83e2e2a 100644 --- a/brewman/schemas/voucher.py +++ b/brewman/schemas/voucher.py @@ -179,7 +179,9 @@ class Voucher(VoucherIn): @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 + 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") diff --git a/brewman/scripts/initializedb.py b/brewman/scripts/initializedb.py index eab64512..50a22f3d 100644 --- a/brewman/scripts/initializedb.py +++ b/brewman/scripts/initializedb.py @@ -45,7 +45,10 @@ 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)) + print( + "usage: %s [var=value]\n" + '(example: "%s development.ini")' % (cmd, cmd) + ) sys.exit(1) @@ -65,13 +68,17 @@ def main(argv=sys.argv): with transaction.manager: dbsession = get_tm_session(session_factory, transaction.manager) - user = User("Admin", "123456", False, uuid.UUID("8de98592-76d9-c74d-bb3f-d6184d388b5a")) + 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")), + Group( + "Accounts Manager", uuid.UUID("cfc44fa7-3392-5b45-b311-5959333f568f") + ), ] for group in groups: @@ -95,7 +102,9 @@ def main(argv=sys.argv): 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( + "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")), @@ -108,7 +117,9 @@ def main(argv=sys.argv): 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( + "Raw Material Cost", uuid.UUID("d462842b-baf1-2343-95e5-ffdba9bbc163") + ), Role( "Edit Other User's Vouchers", uuid.UUID("a8328891-7ce2-a943-8c29-2eabc1ffeea3"), @@ -135,9 +146,15 @@ def main(argv=sys.argv): 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), + 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: @@ -237,11 +254,21 @@ def main(argv=sys.argv): for account in accounts: dbsession.add(account) - product_group = ProductGroup("Suspense", uuid.UUID("ae59a20c-87bb-444a-8abb-915ad5e58b83"), True) + 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)) + 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,