Blacked all files

This commit is contained in:
tanshu committed 2020-10-07 22:29:24 +05:30
1 parent 37910b71be
commit 7463846282
45 files changed
+711 -205

No files matched your search

+15 -5
View File
@@ -55,7 +55,9 @@ def create_access_token(*, data: dict, expires_delta: timedelta = None):
else: else:
expire = datetime.utcnow() + timedelta(minutes=15) expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire}) 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 return encoded_jwt
@@ -76,9 +78,15 @@ def authenticate_user(
return user return user
def client_allowed(user: UserModel, client_id: int, otp: Optional[int] = None, db: Session = None) -> (bool, int): def client_allowed(
client = db.query(Client).filter(Client.code == client_id).first() if client_id else None user: UserModel, client_id: int, otp: Optional[int] = None, db: Session = None
allowed = "clients" in set([p.name.replace(" ", "-").lower() for r in user.roles for p in r.permissions]) ) -> (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: if allowed:
return True, 0 return True, 0
elif client is None: elif client is None:
@@ -108,7 +116,9 @@ async def get_current_user(
headers={"WWW-Authenticate": authenticate_value}, headers={"WWW-Authenticate": authenticate_value},
) )
try: 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") username: str = payload.get("sub")
if username is None: if username is None:
raise credentials_exception raise credentials_exception
+3 -1
View File
@@ -26,7 +26,9 @@ def get_finish_date(session):
def set_period(start, finish, session): def set_period(start, finish, session):
session["start"] = start if isinstance(start, str) else start.strftime("%d-%b-%Y") 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): def get_first_day(dt, d_years=0, d_months=0):
+42 -14
View File
@@ -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.router, prefix="/api/accounts", tags=["accounts"])
app.include_router(account_types.router, prefix="/api/account-types", 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.router, prefix="/api/attendance", tags=["attendance"])
app.include_router(attendance_types.router, prefix="/api/attendance-types", tags=["attendance"]) app.include_router(
app.include_router(employee_attendance.router, prefix="/api/employee-attendance", tags=["attendance"]) attendance_types.router, prefix="/api/attendance-types", 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(
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(employee.router, prefix="/api/employees", tags=["employees"])
app.include_router(fingerprint.router, prefix="/api/fingerprint", 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.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(recipe.router, prefix="/api/recipes", tags=["products"])
app.include_router(client.router, prefix="/api/clients", tags=["clients"]) 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(closing_stock.router, prefix="/api/closing-stock", tags=["reports"])
app.include_router(cash_flow.router, prefix="/api/cash-flow", 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(daybook.router, prefix="/api/daybook", tags=["reports"])
app.include_router(net_transactions.router, prefix="/api/net-transactions", tags=["reports"]) app.include_router(
app.include_router(product_ledger.router, prefix="/api/product-ledger", tags=["reports"]) net_transactions.router, prefix="/api/net-transactions", tags=["reports"]
app.include_router(purchase_entries.router, prefix="/api/purchase-entries", 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(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(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(trial_balance.router, prefix="/api/trial-balance", tags=["reports"])
app.include_router(unposted.router, prefix="/api/unposted", 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/payment", tags=["vouchers"])
app.include_router(journal.router, prefix="/api/receipt", 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.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(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(incentive.router, prefix="/api/incentive", tags=["vouchers"])
app.include_router(credit_salary.router, prefix="/api/credit-salary", 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(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(maintenance.router, prefix="/api/maintenance", tags=["settings"])
app.include_router(db_integrity.router, prefix="/api/db-integrity", tags=["management"]) app.include_router(db_integrity.router, prefix="/api/db-integrity", tags=["management"])
+18 -5
View File
@@ -42,14 +42,18 @@ class Client(Base):
self.name = name self.name = name
self.enabled = enabled self.enabled = enabled
self.otp = otp 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_ self.id = id_
@classmethod @classmethod
def create(cls, dbsession): def create(cls, dbsession):
client_code = random.randint(1000, 9999) client_code = random.randint(1000, 9999)
otp = 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) client = Client(client_code, name, False, otp)
dbsession.add(client) dbsession.add(client)
return client return client
@@ -118,9 +122,18 @@ class User(Base):
class LoginHistory(Base): class LoginHistory(Base):
__tablename__ = "auth_login_history" __tablename__ = "auth_login_history"
__table_args__ = (UniqueConstraint("user_id", "client_id", "date"),) __table_args__ = (UniqueConstraint("user_id", "client_id", "date"),)
id = Column("login_history_id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) id = Column(
user_id = Column("user_id", UUID(as_uuid=True), ForeignKey("auth_users.id"), nullable=False) "login_history_id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4
client_id = Column("client_id", UUID(as_uuid=True), ForeignKey("auth_clients.client_id"), nullable=False) )
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) date = Column("date", DateTime(timezone=True), nullable=False)
def __init__(self, user_id=None, client_id=None, date=None, id_=None): def __init__(self, user_id=None, client_id=None, date=None, id_=None):
+48 -13
View File
@@ -37,7 +37,9 @@ class Product(Base):
ForeignKey("product_groups.id"), ForeignKey("product_groups.id"),
nullable=False, 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) price = Column("cost_price", Numeric, nullable=False)
sale_price = Column("sale_price", Numeric, nullable=False) sale_price = Column("sale_price", Numeric, nullable=False)
is_active = Column("is_active", Boolean, nullable=False) is_active = Column("is_active", Boolean, nullable=False)
@@ -48,7 +50,9 @@ class Product(Base):
batches = relationship("Batch", backref="product") batches = relationship("Batch", backref="product")
inventories = relationship("Inventory", backref="product") inventories = relationship("Inventory", backref="product")
recipes = relationship("Recipe", 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__( def __init__(
self, self,
@@ -125,7 +129,9 @@ class Recipe(Base):
__tablename__ = "recipes" __tablename__ = "recipes"
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) 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) quantity = Column("quantity", Numeric, nullable=False)
cost_price = Column("cost_price", Numeric, nullable=False) cost_price = Column("cost_price", Numeric, nullable=False)
@@ -168,15 +174,23 @@ class RecipeItem(Base):
__tablename__ = "recipe_items" __tablename__ = "recipe_items"
__table_args__ = (UniqueConstraint("recipe_id", "product_id"),) __table_args__ = (UniqueConstraint("recipe_id", "product_id"),)
id = Column("recipe_item_id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) id = Column(
recipe_id = Column("recipe_id", UUID(as_uuid=True), ForeignKey("recipes.id"), nullable=False) "recipe_item_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) )
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) quantity = Column("quantity", Integer, nullable=False)
price = Column("price", Integer, nullable=False) price = Column("price", Integer, nullable=False)
product = relationship("Product") 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.recipe_id = recipe_id
self.product_id = product_id self.product_id = product_id
self.quantity = quantity self.quantity = quantity
@@ -257,7 +271,12 @@ class AccountBase(Base):
is_starred = Column("is_starred", Boolean, nullable=False) is_starred = Column("is_starred", Boolean, nullable=False)
is_active = Column("is_active", Boolean, nullable=False) is_active = Column("is_active", Boolean, nullable=False)
is_reconcilable = Column("is_reconcilable", 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) is_fixture = Column("is_fixture", Boolean, nullable=False)
__mapper_args__ = {"polymorphic_on": account_type} __mapper_args__ = {"polymorphic_on": account_type}
@@ -311,7 +330,11 @@ class AccountBase(Base):
return query_.order_by(cls.name) return query_.order_by(cls.name)
def create(self, db: Session): 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.code = 1 if code is None else code + 1
db.add(self) db.add(self)
return self return self
@@ -327,7 +350,11 @@ class AccountBase(Base):
@classmethod @classmethod
def get_code(cls, type_, db: Session): 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 return 1 if code is None else code + 1
@classmethod @classmethod
@@ -382,8 +409,12 @@ class Employee(AccountBase):
joining_date = Column("joining_date", Date, nullable=False) joining_date = Column("joining_date", Date, nullable=False)
leaving_date = Column("leaving_date", Date, nullable=True) leaving_date = Column("leaving_date", Date, nullable=True)
attendances = relationship("Attendance", backref="employee", cascade=None, cascade_backrefs=False) attendances = relationship(
fingerprints = relationship("Fingerprint", backref="employee", cascade=None, cascade_backrefs=False) "Attendance", backref="employee", cascade=None, cascade_backrefs=False
)
fingerprints = relationship(
"Fingerprint", backref="employee", cascade=None, cascade_backrefs=False
)
def __init__( def __init__(
self, self,
@@ -414,7 +445,11 @@ class Employee(AccountBase):
) )
def create(self, db: Session): 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.code = 1 if code is None else code + 1
self.name += f" ({str(self.code)})" self.name += f" ({str(self.code)})"
db.add(self) db.add(self)
+56 -15
View File
@@ -72,12 +72,16 @@ class Voucher(Base):
creation_date = Column("creation_date", DateTime(timezone=True), nullable=False) creation_date = Column("creation_date", DateTime(timezone=True), nullable=False)
last_edit_date = Column("last_edit_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) _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) posted = Column("is_posted", Boolean, nullable=False)
poster_id = Column("poster_id", UUID(as_uuid=True), ForeignKey("auth_users.id")) poster_id = Column("poster_id", UUID(as_uuid=True), ForeignKey("auth_users.id"))
user = relationship("User", primaryjoin="User.id==Voucher.user_id", cascade=None) 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( journals = relationship(
"Journal", "Journal",
@@ -153,9 +157,22 @@ class Journal(Base):
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
debit = Column("debit", Integer) debit = Column("debit", Integer)
amount = Column("amount", Numeric) amount = Column("amount", Numeric)
voucher_id = Column("voucher_id", UUID(as_uuid=True), ForeignKey("vouchers.id"), nullable=False, index=True) voucher_id = Column(
account_id = Column("account_id", UUID(as_uuid=True), ForeignKey("accounts.id"), nullable=False) "voucher_id",
cost_centre_id = Column("cost_centre_id", UUID(as_uuid=True), ForeignKey("cost_centres.id"), nullable=False) 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") voucher = relationship("Voucher", back_populates="journals")
account = relationship("AccountBase", back_populates="journals") account = relationship("AccountBase", back_populates="journals")
@@ -188,8 +205,12 @@ class Journal(Base):
class EmployeeBenefit(Base): class EmployeeBenefit(Base):
__tablename__ = "employee_benefit" __tablename__ = "employee_benefit"
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) 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) voucher_id = Column(
journal_id = Column("journal_id", UUID(as_uuid=True), ForeignKey("journals.id"), nullable=False) "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) gross_salary = Column("gross_salary", Integer)
days_worked = Column("days_worked", Integer) days_worked = Column("days_worked", Integer)
esi_ee = Column("esi_employee", Integer) esi_ee = Column("esi_employee", Integer)
@@ -234,8 +255,12 @@ class EmployeeBenefit(Base):
class Incentive(Base): class Incentive(Base):
__tablename__ = "incentives" __tablename__ = "incentives"
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) 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) voucher_id = Column(
journal_id = Column("journal_id", UUID(as_uuid=True), ForeignKey("journals.id"), nullable=False) "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) days_worked = Column("days_worked", Numeric(precision=5, scale=1), nullable=False)
points = Column("points", Numeric(precision=5, scale=2), nullable=False) points = Column("points", Numeric(precision=5, scale=2), nullable=False)
@@ -269,9 +294,19 @@ class Inventory(Base):
__tablename__ = "inventories" __tablename__ = "inventories"
__table_args__ = (UniqueConstraint("voucher_id", "batch_id"),) __table_args__ = (UniqueConstraint("voucher_id", "batch_id"),)
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) 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) voucher_id = Column(
product_id = Column("product_id", UUID(as_uuid=True), ForeignKey("products.id"), nullable=False) "voucher_id",
batch_id = Column("batch_id", UUID(as_uuid=True), ForeignKey("batches.id"), nullable=False) 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) quantity = Column("quantity", Numeric)
rate = Column("rate", Numeric) rate = Column("rate", Numeric)
tax = Column("tax", 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) id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
name = Column("name", Date, nullable=False) 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) quantity_remaining = Column("quantity_remaining", Numeric)
rate = Column("rate", Numeric) rate = Column("rate", Numeric)
tax = Column("tax", Numeric) tax = Column("tax", Numeric)
discount = Column("discount", 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__( def __init__(
self, self,
@@ -347,7 +386,9 @@ class Batch(Base):
self.product = product self.product = product
def amount(self): 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 @classmethod
def list(cls, name, include_nil, date, db: Session): def list(cls, name, include_nil, date, db: Session):
+3 -1
View File
@@ -41,7 +41,9 @@ def get_lock_info(db: Session) -> (Optional[date], Optional[date]):
def to_uuid(value): 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 return uuid.UUID(value) if p.match(value) else None
+19 -5
View File
@@ -133,7 +133,11 @@ async def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get
"costCentre": item.cost_centre.name, "costCentre": item.cost_centre.name,
"isFixture": item.is_fixture, "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: if date is not None:
bal = bal.filter(Voucher.date <= date) 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 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): 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] = ( query: List[Voucher] = (
db.query(Voucher) db.query(Voucher)
.options(joinedload_all(Voucher.journals, Journal.account, innerjoin=True)) .options(joinedload_all(Voucher.journals, Journal.account, innerjoin=True))
@@ -241,9 +251,13 @@ def delete_with_data(account: Account, db: Session):
else: else:
if sus_jnl is None: if sus_jnl is None:
acc_jnl.account = suspense_account 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: 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) db.delete(acc_jnl)
if amount == 0: if amount == 0:
db.delete(sus_jnl) db.delete(sus_jnl)
+3 -1
View File
@@ -14,4 +14,6 @@ router = APIRouter()
@router.get("", response_model=List[schemas.AccountType]) @router.get("", response_model=List[schemas.AccountType])
def account_type_list(user: UserToken = Depends(get_user)): 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()
]
+3 -1
View File
@@ -29,7 +29,9 @@ def get_db() -> Session:
@router.get("", response_model=schemas.Attendance) @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": []} return {"date": get_date(request.session), "body": []}
+3 -1
View File
@@ -41,7 +41,9 @@ def get_report(
output, output,
db, db,
) )
headers = {"Content-Disposition": "attachment; filename = 'attendance-record.csv'"} headers = {
"Content-Disposition": "attachment; filename = 'attendance-record.csv'"
}
output.seek(0) output.seek(0)
return StreamingResponse(output, media_type="text/csv", headers=headers) return StreamingResponse(output, media_type="text/csv", headers=headers)
finally: finally:
+9 -2
View File
@@ -83,9 +83,16 @@ async def show_list(
clients = [] clients = []
for item in list_: for item in list_:
last_login = ( 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( clients.append(
{ {
"id": item.id, "id": item.id,
+6 -2
View File
@@ -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 = [p for p in role.permissions if p.id == permission.id_]
gp = None if len(gp) == 0 else gp[0] gp = None if len(gp) == 0 else gp[0]
if permission.enabled and gp is None: 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: elif not permission.enabled and gp:
role.permissions.remove(gp) role.permissions.remove(gp)
@@ -123,7 +125,9 @@ async def show_list(
{ {
"id": item.id, "id": item.id,
"name": item.name, "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() for item in db.query(Role).order_by(Role.name).all()
] ]
+11 -3
View File
@@ -170,8 +170,13 @@ async def show_list(
@router.get("/active") @router.get("/active")
async def show_active(db: Session = Depends(get_db), user: UserToken = Depends(get_user)): async def show_active(
return [{"name": item.name} for item in db.query(User).filter(User.locked_out == False).order_by(User.name)] 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) @router.get("/{id_}", response_model=schemas.User)
@@ -189,7 +194,10 @@ def user_info(item: Optional[User], db: Session, user: UserToken):
return { return {
"name": "", "name": "",
"lockedOut": False, "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: else:
return { return {
+3 -1
View File
@@ -32,7 +32,9 @@ def batch_term(
filter_ = q if q is not None and q.strip() != "" else None 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") date = None if not d else datetime.datetime.strptime(d, "%d-%b-%Y")
list_ = [] 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')}" text = f"{item.product.name} ({item.product.units}) {item.quantity_remaining:.2f}@{item.rate:.2f} from {item.name.strftime('%d-%b-%Y')}"
list_.append( list_.append(
{ {
+6 -2
View File
@@ -44,7 +44,9 @@ def get_duplicate_attendances(db):
.subquery() .subquery()
) )
query = ( 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() return query.scalar()
@@ -61,4 +63,6 @@ def fix_duplicate_attendances(db):
.filter(Attendance.is_valid == True) .filter(Attendance.is_valid == True)
.subquery() .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)
+15 -5
View File
@@ -134,7 +134,9 @@ async def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get
"isActive": item.is_active, "isActive": item.is_active,
"costCentre": item.cost_centre.name, "costCentre": item.cost_centre.name,
"joiningDate": item.joining_date.strftime("%d-%b-%Y"), "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, "isStarred": item.is_starred,
} }
for item in db.query(Employee) for item in db.query(Employee)
@@ -205,7 +207,9 @@ def employee_info(id_, db):
"salary": employee.salary, "salary": employee.salary,
"points": employee.points, "points": employee.points,
"joiningDate": employee.joining_date.strftime("%d-%b-%Y"), "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": { "costCentre": {
"id": employee.cost_centre_id, "id": employee.cost_centre_id,
"name": employee.cost_centre.name, "name": employee.cost_centre.name,
@@ -216,7 +220,9 @@ def employee_info(id_, db):
def delete_with_data(employee, 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 = ( query = (
db.query(Voucher) db.query(Voucher)
.options(joinedload_all(Voucher.journals, Journal.account, innerjoin=True)) .options(joinedload_all(Voucher.journals, Journal.account, innerjoin=True))
@@ -238,9 +244,13 @@ def delete_with_data(employee, db):
else: else:
if sus_jnl is None: if sus_jnl is None:
acc_jnl.account = suspense_account 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: 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: if acc_jnl.employee_benefit is not None:
db.delete(acc_jnl.employee_benefit) db.delete(acc_jnl.employee_benefit)
db.delete(acc_jnl) db.delete(acc_jnl)
+9 -3
View File
@@ -66,15 +66,21 @@ def employee_attendance_report(
} }
start_date = datetime.strptime(start_date, "%d-%b-%Y").date() start_date = datetime.strptime(start_date, "%d-%b-%Y").date()
finish_date = datetime.strptime(finish_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 = ( 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) info["body"] = employee_attendance(employee, start_date, finish_date, db)
return info 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_ = [] list_ = []
for item in date_range(start_date, finish_date, inclusive=True): for item in date_range(start_date, finish_date, inclusive=True):
att = ( att = (
+57 -15
View File
@@ -51,7 +51,9 @@ def save_route(
dt = get_last_day(data.date_) dt = get_last_day(data.date_)
days_in_month = dt.day days_in_month = dt.day
item: Voucher = save(data, dt, user, db) 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_journals(item, exp, total, db)
save_files(item.id, i, t, db) save_files(item.id, i, t, db)
db.commit() db.commit()
@@ -69,7 +71,9 @@ def save_route(
raise 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) check_voucher_lock_info(None, date_, db)
voucher = Voucher( voucher = Voucher(
date=date_, date=date_,
@@ -93,8 +97,12 @@ def save_employee_benefits(
account = db.query(Employee).filter(Employee.id == item.employee.id_).first() account = db.query(Employee).filter(Employee.id == item.employee.id_).first()
gross_salary = item.gross_salary gross_salary = item.gross_salary
days_worked = item.days_worked days_worked = item.days_worked
esi_ee, esi_er, esi_both = esi_contribution(gross_salary, days_worked, days_in_month) esi_ee, esi_er, esi_both = esi_contribution(
pf_ee, pf_er, pf_both = pf_contribution(gross_salary, days_worked, days_in_month) gross_salary, days_worked, days_in_month
)
pf_ee, pf_er, pf_both = pf_contribution(
gross_salary, days_worked, days_in_month
)
journal = Journal( journal = Journal(
amount=esi_ee + pf_ee, amount=esi_ee + pf_ee,
debit=1, debit=1,
@@ -120,7 +128,11 @@ def save_employee_benefits(
def save_journals(voucher: Voucher, exp: int, total: int, db: Session): 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( journal = Journal(
amount=exp, amount=exp,
debit=1, debit=1,
@@ -129,7 +141,11 @@ def save_journals(voucher: Voucher, exp: int, total: int, db: Session):
) )
db.add(journal) db.add(journal)
voucher.journals.append(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( journal = Journal(
amount=total, amount=total,
debit=-1, debit=-1,
@@ -159,7 +175,9 @@ def update_route(
status_code=status.HTTP_423_LOCKED, status_code=status.HTTP_423_LOCKED,
detail="Date Cannot be changed for Employee Benefit voucher!", 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) update_journals(item, exp, total)
# journals_valid(voucher) # journals_valid(voucher)
update_files(item.id, data.files, i, t, db) update_files(item.id, data.files, i, t, db)
@@ -177,7 +195,9 @@ def update_route(
raise 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() voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first()
check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_lock_info(voucher.date, data.date_, db)
check_voucher_edit_allowed(voucher, user) check_voucher_edit_allowed(voucher, user)
@@ -209,14 +229,20 @@ def update_employee_benefits(
if not found: if not found:
voucher.employee_benefits.remove(item) voucher.employee_benefits.remove(item)
voucher.journals.remove(item.journal) 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 return exp + new_exp, total + new_total
def update_journals(voucher: Voucher, exp: int, total: int): 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.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 journal.amount = total
@@ -254,8 +280,16 @@ def esi_contribution(gross_salary, days_worked, days_in_month):
limit = 21000 limit = 21000
employee_rate = 0.0175 employee_rate = 0.0175
employer_rate = 0.0475 employer_rate = 0.0475
employee = 0 if gross_salary > limit else ceil(employee_rate * gross_salary * days_worked / days_in_month) employee = (
employer = 0 if gross_salary > limit else ceil(employer_rate * gross_salary * days_worked / days_in_month) 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 return employee, employer, employee + employer
@@ -263,6 +297,14 @@ def pf_contribution(gross_salary, days_worked, days_in_month):
limit = 15000 limit = 15000
employee_rate = 0.12 employee_rate = 0.12
employer_rate = 0.12 + 0.011 + 0.005 + 0.0001 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) employee = (
employer = 0 if gross_salary > limit else ceil(employer_rate * gross_salary * days_worked / days_in_month) 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 return employee, employer, employee + employer
+12 -4
View File
@@ -32,7 +32,9 @@ def get_db() -> Session:
@router.post("") @router.post("")
def upload_prints( 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: try:
start, finish = get_lock_info(db) start, finish = get_lock_info(db)
@@ -72,7 +74,9 @@ def get_query(version):
.on_conflict_do_nothing() .on_conflict_do_nothing()
) )
else: 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( ~exists([Fingerprint.id]).where(
and_( and_(
Fingerprint.employee_id == bindparam("employee_id"), Fingerprint.employee_id == bindparam("employee_id"),
@@ -143,7 +147,9 @@ def get_prints(employee_id: uuid.UUID, date_: date, db: Session):
db.query(Fingerprint) db.query(Fingerprint)
.filter(Fingerprint.employee_id == employee_id) .filter(Fingerprint.employee_id == employee_id)
.filter(Fingerprint.date >= datetime.combine(date_, time(hour=7))) .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) .order_by(Fingerprint.date)
.all() .all()
) )
@@ -162,7 +168,9 @@ def get_prints(employee_id: uuid.UUID, date_: date, db: Session):
time_worked = prints[1].date - prints[0].date time_worked = prints[1].date - prints[0].date
hours_worked, full_day = working_hours(time_worked) hours_worked, full_day = working_hours(time_worked)
elif len(prints) == 4: 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) hours_worked, full_day = working_hours(time_worked)
else: else:
hours_worked, full_day = "Error", False hours_worked, full_day = "Error", False
+27 -9
View File
@@ -47,7 +47,9 @@ def save_route(
): ):
try: try:
item: Voucher = save(data, user, db) 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 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) total_points = sum(e.points * e.days_worked for e in employees)
point_value = round(amount / total_points, 2) point_value = round(amount / total_points, 2)
@@ -95,7 +97,9 @@ def save_incentives(
account_id=item.employee_id, account_id=item.employee_id,
cost_centre_id=item.cost_centre_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.journals.append(journal)
voucher.incentives.append(inc) voucher.incentives.append(inc)
db.add(journal) db.add(journal)
@@ -103,7 +107,9 @@ def save_incentives(
total_amount += item_amount total_amount += item_amount
sc = db.query(Account).filter(Account.id == Account.incentive_id()).first() 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) voucher.journals.append(journal)
db.add(journal) db.add(journal)
@@ -118,7 +124,9 @@ def update_route(
): ):
try: try:
item: Voucher = update(id_, data, user, db) 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 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) total_points = sum(e.points * e.days_worked for e in employees)
point_value = round(amount / total_points, 2) point_value = round(amount / total_points, 2)
@@ -137,7 +145,9 @@ def update_route(
raise 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() voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first()
check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_lock_info(voucher.date, data.date_, db)
check_voucher_edit_allowed(voucher, user) check_voucher_edit_allowed(voucher, user)
@@ -157,14 +167,18 @@ def update_incentives(
): ):
total_amount = 0 total_amount = 0
for item in voucher.incentives: 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_amount = round(employee.points * employee.days_worked * point_value)
item.days_worked = employee.days_worked item.days_worked = employee.days_worked
item.points = employee.points item.points = employee.points
item.journal.amount = item_amount item.journal.amount = item_amount
total_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 journal.amount = total_amount
@@ -228,7 +242,9 @@ def get_employees(
.filter(Attendance.is_valid == True) .filter(Attendance.is_valid == True)
.all() .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 points = next(x for x in incentives if x.employee_id == employee.id).points
details.append( details.append(
schema_in.IncentiveEmployee( schema_in.IncentiveEmployee(
@@ -263,7 +279,9 @@ def check_if_employees_changed(
json = set(x.employee_id for x in json) json = set(x.employee_id for x in json)
db = set(x.id for x in db) db = set(x.id for x in db)
voucher = ( 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 voucher is None:
if len(json ^ db) != 0: if len(json ^ db) != 0:
+10 -3
View File
@@ -67,7 +67,9 @@ def save_route(
raise 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) check_voucher_lock_info(None, data.date_, db)
voucher = Voucher( voucher = Voucher(
date=data.date_, date=data.date_,
@@ -187,7 +189,9 @@ def update_route(
raise 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() voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first()
check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_lock_info(voucher.date, data.date_, db)
check_voucher_edit_allowed(voucher, user) check_voucher_edit_allowed(voucher, user)
@@ -246,7 +250,10 @@ def update_inventories(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Product / Batch cannot be changed", 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( raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 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} is {item.quantity + item.batch.quantity_remaining}",
+6 -2
View File
@@ -53,8 +53,12 @@ def get_grid(date, db):
{ {
"id": str(voucher.id), "id": str(voucher.id),
"amount": amount, "amount": amount,
"source": [j.cost_centre.name for j in voucher.journals if j.debit == -1], "source": [
"destination": [j.cost_centre.name for j in voucher.journals if j.debit == 1], 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_ return list_
+14 -4
View File
@@ -76,7 +76,9 @@ def save(data: schema_in.JournalIn, user: UserToken, db: Session) -> Voucher:
) )
db.add(voucher) db.add(voucher)
for item in data.journals: 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( journal = Journal(
amount=item.amount, amount=item.amount,
debit=item.debit, debit=item.debit,
@@ -115,7 +117,9 @@ def update_route(
raise 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() voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first()
check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_lock_info(voucher.date, data.date_, db)
check_voucher_edit_allowed(voucher, user) 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): for j in range(len(data.journals), 0, -1):
new_item = data.journals[j - 1] new_item = data.journals[j - 1]
if new_item.id_ is not None and item.id == new_item.id_: 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 found = True
item.debit = new_item.debit item.debit = new_item.debit
item.amount = new_item.amount 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: if not found:
voucher.journals.remove(item) voucher.journals.remove(item)
for new_item in data.journals: 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( journal = Journal(
amount=new_item.amount, amount=new_item.amount,
debit=new_item.debit, debit=new_item.debit,
+15 -3
View File
@@ -56,21 +56,33 @@ async def login_for_access_token(
allowed, c_id = client_allowed(user, client_id, otp, db) allowed, c_id = client_allowed(user, client_id, otp, db)
db.commit() db.commit()
if c_id and c_id != client_id: 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: if not allowed:
not_allowed_response = JSONResponse( not_allowed_response = JSONResponse(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
headers={"WWW-Authenticate": "Bearer"}, headers={"WWW-Authenticate": "Bearer"},
content={"detail": "Client is not registered"}, 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 return not_allowed_response
access_token_expires = timedelta(minutes=settings.JWT_TOKEN_EXPIRE_MINUTES) access_token_expires = timedelta(minutes=settings.JWT_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token( access_token = create_access_token(
data={ data={
"sub": user.name, "sub": user.name,
"scopes": ["authenticated"] "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), "userId": str(user.id),
"lockedOut": user.locked_out, "lockedOut": user.locked_out,
}, },
+9 -3
View File
@@ -232,7 +232,9 @@ def product_info(id_: Optional[uuid.UUID], db: Session):
def delete_with_data(product: Product, 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() suspense_batch = db.query(Batch).filter(Batch.id == Batch.suspense()).first()
query = ( query = (
db.query(Voucher) db.query(Voucher)
@@ -260,11 +262,15 @@ def delete_with_data(product: Product, db: Session):
prod_inv.tax = 0 prod_inv.tax = 0
prod_inv.discount = 0 prod_inv.discount = 0
prod_inv.batch = suspense_batch 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: else:
sus_inv.quantity += prod_inv.amount sus_inv.quantity += prod_inv.amount
db.delete(prod_inv) 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: for batch in product.batches:
db.delete(batch) db.delete(batch)
db.delete(product) db.delete(product)
+20 -6
View File
@@ -81,9 +81,13 @@ def save(data: schema_in.PurchaseIn, user: UserToken, db: Session) -> Voucher:
return 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: 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( batch = Batch(
name=voucher.date, name=voucher.date,
product=product, product=product,
@@ -164,7 +168,9 @@ def update_route(
raise 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() voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first()
check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_lock_info(voucher.date, data.date_, db)
check_voucher_edit_allowed(voucher, user) 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 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): for it in range(len(voucher.inventories), 0, -1):
item = voucher.inventories[it - 1] item = voucher.inventories[it - 1]
found = False found = False
for j in range(len(new_inventories), 0, -1): for j in range(len(new_inventories), 0, -1):
new_inventory = new_inventories[j - 1] new_inventory = new_inventories[j - 1]
if new_inventory.id_ == item.id: 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 found = True
if item.product_id != new_inventory.product.id_: if item.product_id != new_inventory.product.id_:
raise HTTPException( raise HTTPException(
@@ -232,7 +244,9 @@ def update_inventory(voucher: Voucher, new_inventories: List[schema_in.Inventory
db.delete(item) db.delete(item)
voucher.inventories.remove(item) voucher.inventories.remove(item)
for new_inventory in new_inventories: 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( batch = Batch(
name=voucher.date, name=voucher.date,
product_id=product.id, product_id=product.id,
+9 -3
View File
@@ -80,7 +80,9 @@ def save(data: schema_in.PurchaseIn, user: UserToken, db: Session) -> Voucher:
return 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: for item in inventories:
batch = db.query(Batch).filter(Batch.id == item.batch.id_).first() batch = db.query(Batch).filter(Batch.id == item.batch.id_).first()
@@ -166,7 +168,9 @@ def update_route(
raise 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() voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first()
check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_lock_info(voucher.date, data.date_, db)
check_voucher_edit_allowed(voucher, user) 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 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): for it in range(len(voucher.inventories), 0, -1):
item = voucher.inventories[it - 1] item = voucher.inventories[it - 1]
found = False found = False
+33 -9
View File
@@ -58,7 +58,10 @@ def rebase(
def save_starred(date_: date, db: Session): 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 = [] vouchers = []
query = ( query = (
db.query(Voucher) db.query(Voucher)
@@ -70,7 +73,11 @@ def save_starred(date_: date, db: Session):
for voucher in query: for voucher in query:
vouchers.append(voucher.id) 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: if len(others) == 0:
continue continue
amount = round(Decimal(sum(o.signed_amount for o in others)), 2) 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: for other in others:
if voucher.type != VoucherType.by_name("Opening Accounts").id: 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: if other.employee_benefit:
db.delete(other.employee_benefit) db.delete(other.employee_benefit)
if other.incentive: 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() 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(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(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( db.execute(
DbImage.__table__.delete( DbImage.__table__.delete(
and_( 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): def cleanup_lint(date_: date, db: Session):
# Insert executes on the end so keep list of batches and journals # 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(Fingerprint.__table__.delete(Fingerprint.date < date_))
db.execute(Attendance.__table__.delete(Attendance.date < date_)) db.execute(Attendance.__table__.delete(Attendance.date < date_))
db.execute( db.execute(
Employee.__table__.delete( Employee.__table__.delete(
and_( and_(
~Employee.id.in_(db.query(distinct(Journal.account_id)).subquery()), ~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(distinct(Attendance.employee_id)).subquery()),
Employee.id.in_( Employee.id.in_(
db.query(AccountBase.id) db.query(AccountBase.id)
@@ -246,7 +269,8 @@ def cleanup_lint(date_: date, db: Session):
AccountBase.__table__.delete( AccountBase.__table__.delete(
and_( and_(
~AccountBase.id.in_(db.query(Employee.id).subquery()), ~AccountBase.id.in_(db.query(Employee.id).subquery()),
AccountBase.account_type == Employee.__mapper_args__["polymorphic_identity"], AccountBase.account_type
== Employee.__mapper_args__["polymorphic_identity"],
) )
) )
) )
+51 -15
View File
@@ -20,15 +20,21 @@ router = APIRouter()
def save(request): def save(request):
json = request.json_body json = request.json_body
recipe_product = ( 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: 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): except (ValueError, KeyError, TypeError):
raise ValidationError("Valid From is not a valid date") raise ValidationError("Valid From is not a valid date")
try: 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): except (ValueError, KeyError, TypeError):
raise ValidationError("Valid To is not a valid date") raise ValidationError("Valid To is not a valid date")
@@ -61,15 +67,25 @@ def save(request):
valid_to=valid_to, valid_to=valid_to,
) )
for item in json["RecipeItems"]: 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) quantity = round(Decimal(item["Quantity"]), 2)
if product.is_purchased: 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: 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) cost_per_unit = ingredient_cost / (product.fraction * product.product_yield)
recipe_cost += cost_per_unit * quantity 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) recipe.cost_price = round(recipe_cost / recipe_quantity, 2)
if recipe_product.is_sold: 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): def get_purchased_product_cost(product_id, start_date, finish_date, dbsession):
quantity_sum = func.sum(Journal.debit * Inventory.quantity).label("quantity") quantity_sum = func.sum(Journal.debit * Inventory.quantity).label("quantity")
amount_sum = func.sum( 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") ).label("amount")
costing = ( costing = (
dbsession.query(quantity_sum, amount_sum) 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: for item in old_recipe.recipe_items:
if item.product.is_purchased: 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: else:
ingredient_cost = get_sub_product_cost(item.product_id, start_date, finish_date, dbsession) ingredient_cost = get_sub_product_cost(
cost_per_unit = ingredient_cost / (item.product.fraction * item.product.product_yield) 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_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) 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, effective_from=effective_date,
) )
for ri in item.recipe_items: 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) new_recipes.append(recipe)
if item.valid_to > valid_to: if item.valid_to > valid_to:
recipe = Recipe( recipe = Recipe(
@@ -209,7 +239,9 @@ def update_old_rows(product_id, valid_from, valid_to, effective_date, dbsession)
effective_from=effective_date, effective_from=effective_date,
) )
for ri in item.recipe_items: 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) new_recipes.append(recipe)
if item.effective_from == effective_date and item.effective_to is None: 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" @router.delete("/{id}") # "Recipes"
def delete(request): 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: if len(recipe.product.recipes) > 1:
request.dbsession.delete(recipe) request.dbsession.delete(recipe)
else: else:
+6 -2
View File
@@ -72,7 +72,9 @@ def build_balance_sheet(date_: date, db: Session):
} }
total_amount += closing_stock 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) asset_group = AccountType.by_id(4)
groups[asset_group.id] = { groups[asset_group.id] = {
@@ -110,7 +112,9 @@ def build_balance_sheet(date_: date, db: Session):
} }
) )
if account_type.id in groups: 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: else:
groups[account_type.id] = { groups[account_type.id] = {
"group": account_type.name, "group": account_type.name,
+19 -3
View File
@@ -49,7 +49,9 @@ def report_data(
def build_report(date_: date, db: Session): 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") quantity_sum = func.sum(Journal.debit * Inventory.quantity).label("quantity")
query = ( query = (
db.query(Product, quantity_sum, amount_sum) 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): def get_opening_stock(date_: date, db: Session):
opening_stock = ( 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.voucher)
.join(Journal.account) .join(Journal.account)
.join(Voucher.inventories) .join(Voucher.inventories)
@@ -92,7 +101,14 @@ def get_opening_stock(date_: date, db: Session):
def get_closing_stock(date_, db: Session): def get_closing_stock(date_, db: Session):
closing_stock = ( 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.voucher)
.join(Journal.account) .join(Journal.account)
.join(Voucher.inventories) .join(Voucher.inventories)
+3 -1
View File
@@ -77,5 +77,7 @@ def build_report(start_date: date, finish_date: date, db: Session):
for account, amount in query: for account, amount in query:
if amount != 0: if amount != 0:
tag = "debit" if amount > 0 else "credit" 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 return body
+8 -3
View File
@@ -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 = [] 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) body.append(opening)
query = ( 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, "type": VoucherType.by_id(row.Voucher.type).name,
"narration": row.Voucher.narration, "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, "debitQuantity": debit_q,
"debitAmount": debit_a, "debitAmount": debit_a,
"creditQuantity": credit_q, "creditQuantity": credit_q,
+6 -2
View File
@@ -48,7 +48,9 @@ def report_data(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: UserToken = Security(get_user, scopes=["profit-&-loss"]), 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) set_period(start, finish, request.session)
return { return {
"startDate": start, "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) closing_stock = get_closing_stock(finish_date, db)
total_amount = (opening_stock - closing_stock) * -1 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}) report.append({"name": "Closing Stock", "amount": closing_stock, "order": 290000})
purchase_group = AccountType.by_id(2) purchase_group = AccountType.by_id(2)
groups[purchase_group.id] = { groups[purchase_group.id] = {
+6 -2
View File
@@ -60,7 +60,9 @@ def report_data(
def build_report(start_date, finish_date, db): def build_report(start_date, finish_date, db):
body = [] body = []
quantity_sum = func.sum(Journal.debit * Inventory.quantity).label("quantity") 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 = ( query = (
db.query(Product, quantity_sum, amount_sum) db.query(Product, quantity_sum, amount_sum)
.join(Product.inventories) .join(Product.inventories)
@@ -89,5 +91,7 @@ def build_report(start_date, finish_date, db):
body.append(row) body.append(row)
return ( return (
body, 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
),
) )
+15 -5
View File
@@ -49,7 +49,9 @@ def report_data(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: UserToken = Security(get_user, scopes=["raw-material-cost"]), 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) set_period(s, f, request.session)
return { return {
"startDate": s, "startDate": s,
@@ -68,7 +70,9 @@ def report_id(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: UserToken = Security(get_user, scopes=["raw-material-cost"]), 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) set_period(s, f, request.session)
return { return {
"id": id_, "id": id_,
@@ -80,8 +84,12 @@ def report_id(
def build_report(start_date: date, finish_date: date, db: Session): def build_report(start_date: date, finish_date: date, db: Session):
body = [] body = []
sum_issue = func.sum(case([(AccountBase.type == 2, Journal.signed_amount)], else_=0)).label("issue") sum_issue = func.sum(
sum_sale = func.sum(case([(AccountBase.type == 3, Journal.signed_amount * -1)], else_=0)).label("sale") 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 = ( query = (
db.query(CostCentre, sum_issue, sum_sale) 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} 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_quantity = func.sum(Inventory.quantity * Journal.debit).label("quantity")
sum_net = func.sum(Inventory.rate * Inventory.quantity * Journal.debit).label("net") sum_net = func.sum(Inventory.rate * Inventory.quantity * Journal.debit).label("net")
sum_gross = func.sum(Inventory.amount * Journal.debit).label("gross") sum_gross = func.sum(Inventory.amount * Journal.debit).label("gross")
+7 -3
View File
@@ -72,8 +72,10 @@ def build_report(account_id, start_date, finish_date, db):
or_( or_(
Voucher.is_reconciled == False, Voucher.is_reconciled == False,
and_( and_(
Voucher.reconcile_date >= datetime.datetime.strptime(start_date, "%d-%b-%Y"), Voucher.reconcile_date
Voucher.reconcile_date <= datetime.datetime.strptime(finish_date, "%d-%b-%Y"), >= 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 = ( opening = (
db.query(func.sum(Journal.amount * Journal.debit)) db.query(func.sum(Journal.amount * Journal.debit))
.join(Journal.voucher) .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.is_reconciled == True)
.filter(Voucher.type != VoucherType.by_name("Issue").id) .filter(Voucher.type != VoucherType.by_name("Issue").id)
.filter(Journal.account_id == account_id) .filter(Journal.account_id == account_id)
+3 -1
View File
@@ -47,7 +47,9 @@ def report_data(
db: Session = Depends(get_db), db: Session = Depends(get_db),
user: UserToken = Security(get_user, scopes=["stock-movement"]), 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) set_period(start, finish, request.session)
return {"startDate": start, "finishDate": finish, "body": body} return {"startDate": start, "finishDate": finish, "body": body}
+3 -1
View File
@@ -66,5 +66,7 @@ def build_report(date_: date, db: Session):
for account, amount in query: for account, amount in query:
if amount != 0: if amount != 0:
tag = "debit" if amount > 0 else "credit" 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 return body
+14 -3
View File
@@ -39,7 +39,9 @@ def rebase(
detail="Reset cannot be after the stock date", 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: if change == 0:
return {"No Change Needed"} return {"No Change Needed"}
final = get_closing_stock(product, db=db) 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): 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: if batch is None:
raise HTTPException( raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
@@ -84,7 +91,11 @@ def get_last_batch(product, db):
def set_batches(batch, quantity, db): def set_batches(batch, quantity, db):
batch.quantity_remaining = quantity 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: for item in batches:
item.quantity_remaining = 0 item.quantity_remaining = 0
pass pass
+42 -10
View File
@@ -72,7 +72,10 @@ def check_delete_permissions(voucher: Voucher, user: UserToken):
status_code=status.HTTP_403_FORBIDDEN, status_code=status.HTTP_403_FORBIDDEN,
detail="You are not allowed to edit posted vouchers", 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( raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, status_code=status.HTTP_403_FORBIDDEN,
detail="You are not allowed to edit other user's vouchers", 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: 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( json_voucher["incentives"].append(
{ {
"employeeId": item.journal.account_id, "employeeId": item.journal.account_id,
@@ -221,7 +226,9 @@ def voucher_info(voucher, db):
} }
) )
if len(json_voucher["incentives"]) > 0: 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: 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}@{item.batch.rate:.2f} from {item.batch.name.strftime('%d-%b-%Y')}"
json_voucher["inventories"].append( json_voucher["inventories"].append(
@@ -291,7 +298,11 @@ def blank_voucher(info, db):
elif type_ == "Payment": elif type_ == "Payment":
account = None account = None
if info and "account" in info and info["account"]: 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: if account is not None:
account = {"id": account.id, "name": account.name} account = {"id": account.id, "name": account.name}
else: else:
@@ -300,7 +311,11 @@ def blank_voucher(info, db):
elif type_ == "Receipt": elif type_ == "Receipt":
account = None account = None
if info and "account" in info and info["account"]: 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: if account is not None:
account = {"id": account.id, "name": account.name} account = {"id": account.id, "name": account.name}
else: else:
@@ -310,7 +325,9 @@ def blank_voucher(info, db):
json_voucher["vendor"] = AccountBase.local_purchase() json_voucher["vendor"] = AccountBase.local_purchase()
elif type_ == "Purchase Return": 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": elif type_ == "Issue":
if "source" in info: if "source" in info:
json_voucher["source"] = {"id": info["source"]} json_voucher["source"] = {"id": info["source"]}
@@ -323,7 +340,9 @@ def blank_voucher(info, db):
elif type_ == "Employee Benefit": elif type_ == "Employee Benefit":
json_voucher["employeeBenefits"] = [] json_voucher["employeeBenefits"] = []
elif type_ == "Incentive": 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: else:
raise HTTPException( raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND, 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): def check_voucher_lock_info(voucher_date: Optional[date], data_date: date, db: Session):
start, finish = get_lock_info(db) 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( raise HTTPException(
status_code=status.HTTP_423_LOCKED, status_code=status.HTTP_423_LOCKED,
detail=f"Vouchers before {start.strftime('%d-%b-%Y')} have been 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( raise HTTPException(
status_code=status.HTTP_423_LOCKED, status_code=status.HTTP_423_LOCKED,
detail=f"Vouchers after {finish.strftime('%d-%b-%Y')} have been 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, status_code=status.HTTP_403_FORBIDDEN,
detail="You are not allowed to edit posted vouchers", 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( raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, status_code=status.HTTP_403_FORBIDDEN,
detail="You are not allowed to edit other user's vouchers", detail="You are not allowed to edit other user's vouchers",
+3 -1
View File
@@ -45,7 +45,9 @@ class JournalIn(VoucherIn):
@validator("journals") @validator("journals")
def is_distinct(cls, value: List[Journal]): def is_distinct(cls, value: List[Journal]):
journal_set = set( 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): if len(value) != len(journal_set):
raise ValueError("Duplicate journals") raise ValueError("Duplicate journals")
+3 -1
View File
@@ -179,7 +179,9 @@ class Voucher(VoucherIn):
@validator("journals") @validator("journals")
def is_distinct(cls, value: List[Journal]): def is_distinct(cls, value: List[Journal]):
journal_set = set( 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): if len(value) != len(journal_set):
raise ValueError("Duplicate journals") raise ValueError("Duplicate journals")
+38 -11
View File
@@ -45,7 +45,10 @@ from ..models.meta import Base
def usage(argv): def usage(argv):
cmd = os.path.basename(argv[0]) cmd = os.path.basename(argv[0])
print("usage: %s <config_uri> [var=value]\n" '(example: "%s development.ini")' % (cmd, cmd)) print(
"usage: %s <config_uri> [var=value]\n"
'(example: "%s development.ini")' % (cmd, cmd)
)
sys.exit(1) sys.exit(1)
@@ -65,13 +68,17 @@ def main(argv=sys.argv):
with transaction.manager: with transaction.manager:
dbsession = get_tm_session(session_factory, 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) dbsession.add(user)
groups = [ groups = [
Group("Owner", uuid.UUID("52e08c0c-048a-784f-be10-6e129ad4b5d4")), Group("Owner", uuid.UUID("52e08c0c-048a-784f-be10-6e129ad4b5d4")),
Group("Accountant", uuid.UUID("bc4c2d23-437a-984d-abd4-7d5fce677547")), 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: for group in groups:
@@ -95,7 +102,9 @@ def main(argv=sys.argv):
Role("Journal", uuid.UUID("7661388f-62ce-1c41-8e0d-0326ee5d4018")), Role("Journal", uuid.UUID("7661388f-62ce-1c41-8e0d-0326ee5d4018")),
Role("Accounts", uuid.UUID("f438262f-72dd-2f4e-9186-5abc3af44fba")), Role("Accounts", uuid.UUID("f438262f-72dd-2f4e-9186-5abc3af44fba")),
Role("Product Ledger", uuid.UUID("018a2408-e804-1446-90c5-b015829da6ba")), 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("Payment", uuid.UUID("f85c0b52-c3fd-7141-8957-7a56cdc014a4")),
Role("Post Vouchers", uuid.UUID("36e741da-1a57-b047-a59e-dcd58fcf4338")), Role("Post Vouchers", uuid.UUID("36e741da-1a57-b047-a59e-dcd58fcf4338")),
Role("Products", uuid.UUID("74fa6d21-eebb-e14c-8153-bebc57190ab4")), 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("Recipes", uuid.UUID("ffb7fb65-d42c-424d-9ff1-45069e3b4a29")),
Role("Closing Stock", uuid.UUID("97515732-24e4-c94d-9585-d4bd7f6c7891")), Role("Closing Stock", uuid.UUID("97515732-24e4-c94d-9585-d4bd7f6c7891")),
Role("Ledger", uuid.UUID("a2120944-243f-3f49-be57-0ad633ce4801")), 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( Role(
"Edit Other User's Vouchers", "Edit Other User's Vouchers",
uuid.UUID("a8328891-7ce2-a943-8c29-2eabc1ffeea3"), uuid.UUID("a8328891-7ce2-a943-8c29-2eabc1ffeea3"),
@@ -135,9 +146,15 @@ def main(argv=sys.argv):
groups[0].roles.append(role) groups[0].roles.append(role)
cost_centres = [ cost_centres = [
CostCentre("Overall", uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), True), CostCentre(
CostCentre("Purchase", uuid.UUID("7b845f95-dfef-fa4a-897c-f0baf15284a3"), True), "Overall", uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), True
CostCentre("Kitchen", uuid.UUID("b2d398ce-e3cc-c542-9feb-5d7783e899df"), 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: for cost_centre in cost_centres:
@@ -237,11 +254,21 @@ def main(argv=sys.argv):
for account in accounts: for account in accounts:
dbsession.add(account) 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(product_group)
dbsession.add(ProductGroup("Semi", uuid.UUID("e6bf81b9-1e9b-499f-81d5-ab5662e9d9b1"), True)) dbsession.add(
dbsession.add(ProductGroup("Menu Items", uuid.UUID("dad46805-f577-4e5b-8073-9b788e0173fc"), True)) 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( product = Product(
1, 1,