From 1c2c98e7b587002264a25ca0d0c49b9a25e94aed Mon Sep 17 00:00:00 2001 From: tanshu Date: Sun, 31 May 2020 14:41:11 +0530 Subject: [PATCH] Blacked all lines with -l 120 --- alembic/env.py | 16 +- .../versions/0bf3d70ee7de_initial_commit.py | 580 ++++++++++-------- .../eed0b382c287_lowercase_fastapi.py | 329 +++++----- brewman/core/config.py | 2 +- brewman/core/security.py | 20 +- brewman/core/session.py | 8 +- brewman/db/init_db.py | 4 +- brewman/db/session.py | 2 +- brewman/main.py | 56 +- brewman/models/__init__.py | 2 +- brewman/models/auth.py | 20 +- brewman/models/master.py | 51 +- brewman/models/operations.py | 15 +- brewman/models/voucher.py | 91 +-- brewman/routers/__init__.py | 4 +- brewman/routers/account.py | 62 +- brewman/routers/account_types.py | 5 +- brewman/routers/attendance.py | 12 +- brewman/routers/attendance_report.py | 9 +- brewman/routers/auth/client.py | 28 +- brewman/routers/auth/role.py | 47 +- brewman/routers/auth/user.py | 60 +- brewman/routers/batch.py | 16 +- brewman/routers/cost_centre.py | 29 +- brewman/routers/credit_salary.py | 19 +- brewman/routers/db_image.py | 10 +- brewman/routers/db_integrity.py | 13 +- brewman/routers/employee.py | 69 +-- brewman/routers/employee_attendance.py | 17 +- brewman/routers/employee_benefit.py | 120 +--- brewman/routers/fingerprint.py | 21 +- brewman/routers/incentive.py | 73 +-- brewman/routers/issue.py | 64 +- brewman/routers/issue_grid.py | 13 +- brewman/routers/journal.py | 42 +- brewman/routers/lock_information.py | 7 +- brewman/routers/login.py | 38 +- brewman/routers/maintenance.py | 4 +- brewman/routers/product.py | 39 +- brewman/routers/product_group.py | 29 +- brewman/routers/purchase.py | 70 +-- brewman/routers/purchase_return.py | 64 +- brewman/routers/rebase.py | 64 +- brewman/routers/recipe.py | 72 +-- brewman/routers/reports/balance_sheet.py | 19 +- brewman/routers/reports/cash_flow.py | 25 +- brewman/routers/reports/closing_stock.py | 30 +- brewman/routers/reports/daybook.py | 5 +- brewman/routers/reports/ledger.py | 5 +- brewman/routers/reports/net_transactions.py | 9 +- brewman/routers/reports/product_ledger.py | 32 +- brewman/routers/reports/profit_loss.py | 13 +- brewman/routers/reports/purchase_entries.py | 6 +- brewman/routers/reports/purchases.py | 17 +- brewman/routers/reports/raw_material_cost.py | 13 +- brewman/routers/reports/reconcile.py | 15 +- brewman/routers/reports/stock_movement.py | 9 +- brewman/routers/reports/trial_balance.py | 20 +- brewman/routers/reports/unposted.py | 6 +- brewman/routers/reset_stock.py | 42 +- brewman/schemas/__init__.py | 2 - brewman/schemas/input.py | 4 +- brewman/schemas/voucher.py | 4 +- brewman/scripts/initializedb.py | 59 +- 64 files changed, 924 insertions(+), 1727 deletions(-) diff --git a/alembic/env.py b/alembic/env.py index e50938cb..8f6bb580 100644 --- a/alembic/env.py +++ b/alembic/env.py @@ -7,13 +7,14 @@ from alembic import context from brewman.core.config import settings logging.basicConfig() -logging.getLogger('sqlalchemy.engine').setLevel(settings.ALEMBIC_LOG_LEVEL) -logging.getLogger('alembic').setLevel(settings.ALEMBIC_LOG_LEVEL) +logging.getLogger("sqlalchemy.engine").setLevel(settings.ALEMBIC_LOG_LEVEL) +logging.getLogger("alembic").setLevel(settings.ALEMBIC_LOG_LEVEL) # Interpret the config file for Python logging. # This line sets up loggers basically. -from brewman.models.auth import User # noqa +from brewman.models.auth import User # noqa + target_metadata = User.metadata # other values from the config, defined by the needs of env.py, @@ -40,7 +41,7 @@ def run_migrations_offline(): target_metadata=target_metadata, literal_binds=True, dialect_opts={"paramstyle": "named"}, - compare_type=True + compare_type=True, ) with context.begin_transaction(): @@ -54,13 +55,10 @@ def run_migrations_online(): and associate a connection with the context. """ - connectable = create_engine(settings.SQLALCHEMY_DATABASE_URI, poolclass=pool.NullPool, ) + connectable = create_engine(settings.SQLALCHEMY_DATABASE_URI, poolclass=pool.NullPool,) with connectable.connect() as connection: - context.configure( - connection=connection, target_metadata=target_metadata, - compare_type=True - ) + context.configure(connection=connection, target_metadata=target_metadata, compare_type=True) with context.begin_transaction(): context.run_migrations() diff --git a/alembic/versions/0bf3d70ee7de_initial_commit.py b/alembic/versions/0bf3d70ee7de_initial_commit.py index 22df82de..1467f828 100644 --- a/alembic/versions/0bf3d70ee7de_initial_commit.py +++ b/alembic/versions/0bf3d70ee7de_initial_commit.py @@ -10,7 +10,7 @@ import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. -revision = '0bf3d70ee7de' +revision = "0bf3d70ee7de" down_revision = None branch_labels = None depends_on = None @@ -18,297 +18,347 @@ depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.create_table('auth_clients', - sa.Column('client_id', postgresql.UUID(), nullable=False), - sa.Column('code', sa.Integer(), nullable=False), - sa.Column('name', sa.Unicode(length=255), nullable=False), - sa.Column('enabled', sa.Boolean(), nullable=False), - sa.Column('otp', sa.Integer(), nullable=True), - sa.Column('creation_date', sa.DateTime(timezone=True), nullable=False), - sa.PrimaryKeyConstraint('client_id', name=op.f('pk_auth_clients')), - sa.UniqueConstraint('code', name=op.f('uq_auth_clients_code')), - sa.UniqueConstraint('name', name=op.f('uq_auth_clients_name')) + op.create_table( + "auth_clients", + sa.Column("client_id", postgresql.UUID(), nullable=False), + sa.Column("code", sa.Integer(), nullable=False), + sa.Column("name", sa.Unicode(length=255), nullable=False), + sa.Column("enabled", sa.Boolean(), nullable=False), + sa.Column("otp", sa.Integer(), nullable=True), + sa.Column("creation_date", sa.DateTime(timezone=True), nullable=False), + sa.PrimaryKeyConstraint("client_id", name=op.f("pk_auth_clients")), + sa.UniqueConstraint("code", name=op.f("uq_auth_clients_code")), + sa.UniqueConstraint("name", name=op.f("uq_auth_clients_name")), ) - op.create_table('auth_groups', - sa.Column('GroupID', postgresql.UUID(), nullable=False), - sa.Column('Name', sa.Unicode(length=255), nullable=True), - sa.PrimaryKeyConstraint('GroupID', name=op.f('pk_auth_groups')), - sa.UniqueConstraint('Name', name=op.f('uq_auth_groups_Name')) + op.create_table( + "auth_groups", + sa.Column("GroupID", postgresql.UUID(), nullable=False), + sa.Column("Name", sa.Unicode(length=255), nullable=True), + sa.PrimaryKeyConstraint("GroupID", name=op.f("pk_auth_groups")), + sa.UniqueConstraint("Name", name=op.f("uq_auth_groups_Name")), ) - op.create_table('auth_roles', - sa.Column('RoleID', postgresql.UUID(), nullable=False), - sa.Column('Name', sa.Unicode(length=255), nullable=True), - sa.PrimaryKeyConstraint('RoleID', name=op.f('pk_auth_roles')), - sa.UniqueConstraint('Name', name=op.f('uq_auth_roles_Name')) + op.create_table( + "auth_roles", + sa.Column("RoleID", postgresql.UUID(), nullable=False), + sa.Column("Name", sa.Unicode(length=255), nullable=True), + sa.PrimaryKeyConstraint("RoleID", name=op.f("pk_auth_roles")), + sa.UniqueConstraint("Name", name=op.f("uq_auth_roles_Name")), ) - op.create_table('auth_users', - sa.Column('UserID', postgresql.UUID(), nullable=False), - sa.Column('Name', sa.Unicode(length=255), nullable=True), - sa.Column('Password', sa.Unicode(length=60), nullable=True), - sa.Column('LockedOut', sa.Boolean(), nullable=True), - sa.PrimaryKeyConstraint('UserID', name=op.f('pk_auth_users')), - sa.UniqueConstraint('Name', name=op.f('uq_auth_users_Name')) + op.create_table( + "auth_users", + sa.Column("UserID", postgresql.UUID(), nullable=False), + sa.Column("Name", sa.Unicode(length=255), nullable=True), + sa.Column("Password", sa.Unicode(length=60), nullable=True), + sa.Column("LockedOut", sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint("UserID", name=op.f("pk_auth_users")), + sa.UniqueConstraint("Name", name=op.f("uq_auth_users_Name")), ) - op.create_table('cost_centres', - sa.Column('CostCentreID', postgresql.UUID(), nullable=False), - sa.Column('Name', sa.Unicode(length=255), nullable=True), - sa.Column('IsFixture', sa.Boolean(), nullable=False), - sa.PrimaryKeyConstraint('CostCentreID', name=op.f('pk_cost_centres')), - sa.UniqueConstraint('Name', name=op.f('uq_cost_centres_Name')) + op.create_table( + "cost_centres", + sa.Column("CostCentreID", postgresql.UUID(), nullable=False), + sa.Column("Name", sa.Unicode(length=255), nullable=True), + sa.Column("IsFixture", sa.Boolean(), nullable=False), + sa.PrimaryKeyConstraint("CostCentreID", name=op.f("pk_cost_centres")), + sa.UniqueConstraint("Name", name=op.f("uq_cost_centres_Name")), ) - op.create_table('images', - sa.Column('id', postgresql.UUID(), nullable=False), - sa.Column('resource_id', postgresql.UUID(), nullable=False), - sa.Column('resource_type', sa.Unicode(length=255), nullable=False), - sa.Column('image', postgresql.BYTEA(), nullable=False), - sa.Column('thumbnail', postgresql.BYTEA(), nullable=False), - sa.Column('creation_date', sa.DateTime(timezone=True), nullable=False), - sa.PrimaryKeyConstraint('id', name=op.f('pk_images')) + op.create_table( + "images", + sa.Column("id", postgresql.UUID(), nullable=False), + sa.Column("resource_id", postgresql.UUID(), nullable=False), + sa.Column("resource_type", sa.Unicode(length=255), nullable=False), + sa.Column("image", postgresql.BYTEA(), nullable=False), + sa.Column("thumbnail", postgresql.BYTEA(), nullable=False), + sa.Column("creation_date", sa.DateTime(timezone=True), nullable=False), + sa.PrimaryKeyConstraint("id", name=op.f("pk_images")), ) - op.create_table('product_groups', - sa.Column('ProductGroupID', postgresql.UUID(), nullable=False), - sa.Column('Name', sa.Unicode(length=255), nullable=True), - sa.Column('IsFixture', sa.Boolean(), nullable=False), - sa.PrimaryKeyConstraint('ProductGroupID', name=op.f('pk_product_groups')), - sa.UniqueConstraint('Name', name=op.f('uq_product_groups_Name')) + op.create_table( + "product_groups", + sa.Column("ProductGroupID", postgresql.UUID(), nullable=False), + sa.Column("Name", sa.Unicode(length=255), nullable=True), + sa.Column("IsFixture", sa.Boolean(), nullable=False), + sa.PrimaryKeyConstraint("ProductGroupID", name=op.f("pk_product_groups")), + sa.UniqueConstraint("Name", name=op.f("uq_product_groups_Name")), ) - op.create_table('settings', - sa.Column('SettingID', postgresql.UUID(), nullable=False), - sa.Column('Name', sa.Unicode(length=255), nullable=False), - sa.Column('Data', sa.PickleType(), nullable=True), - sa.PrimaryKeyConstraint('SettingID', name=op.f('pk_settings')), - sa.UniqueConstraint('Name', name=op.f('uq_settings_Name')) + op.create_table( + "settings", + sa.Column("SettingID", postgresql.UUID(), nullable=False), + sa.Column("Name", sa.Unicode(length=255), nullable=False), + sa.Column("Data", sa.PickleType(), nullable=True), + sa.PrimaryKeyConstraint("SettingID", name=op.f("pk_settings")), + sa.UniqueConstraint("Name", name=op.f("uq_settings_Name")), ) - op.create_table('accounts', - sa.Column('id', postgresql.UUID(), nullable=False), - sa.Column('code', sa.Integer(), nullable=False), - sa.Column('name', sa.Unicode(length=255), nullable=False), - sa.Column('type', sa.Integer(), nullable=False), - sa.Column('account_type', sa.Unicode(length=50), nullable=False), - sa.Column('is_starred', sa.Boolean(), nullable=False), - sa.Column('is_active', sa.Boolean(), nullable=False), - sa.Column('is_reconcilable', sa.Boolean(), nullable=False), - sa.Column('cost_centre_id', postgresql.UUID(), nullable=False), - sa.Column('is_fixture', sa.Boolean(), nullable=False), - sa.ForeignKeyConstraint(['cost_centre_id'], ['cost_centres.CostCentreID'], name=op.f('fk_accounts_cost_centre_id_cost_centres')), - sa.PrimaryKeyConstraint('id', name=op.f('pk_accounts')), - sa.UniqueConstraint('name', name=op.f('uq_accounts_name')) + op.create_table( + "accounts", + sa.Column("id", postgresql.UUID(), nullable=False), + sa.Column("code", sa.Integer(), nullable=False), + sa.Column("name", sa.Unicode(length=255), nullable=False), + sa.Column("type", sa.Integer(), nullable=False), + sa.Column("account_type", sa.Unicode(length=50), nullable=False), + sa.Column("is_starred", sa.Boolean(), nullable=False), + sa.Column("is_active", sa.Boolean(), nullable=False), + sa.Column("is_reconcilable", sa.Boolean(), nullable=False), + sa.Column("cost_centre_id", postgresql.UUID(), nullable=False), + sa.Column("is_fixture", sa.Boolean(), nullable=False), + sa.ForeignKeyConstraint( + ["cost_centre_id"], ["cost_centres.CostCentreID"], name=op.f("fk_accounts_cost_centre_id_cost_centres"), + ), + sa.PrimaryKeyConstraint("id", name=op.f("pk_accounts")), + sa.UniqueConstraint("name", name=op.f("uq_accounts_name")), ) - op.create_table('auth_login_history', - sa.Column('login_history_id', postgresql.UUID(), nullable=False), - sa.Column('user_id', postgresql.UUID(), nullable=False), - sa.Column('client_id', postgresql.UUID(), nullable=False), - sa.Column('date', sa.DateTime(timezone=True), nullable=False), - sa.ForeignKeyConstraint(['client_id'], ['auth_clients.client_id'], name=op.f('fk_auth_login_history_client_id_auth_clients')), - sa.ForeignKeyConstraint(['user_id'], ['auth_users.UserID'], name=op.f('fk_auth_login_history_user_id_auth_users')), - sa.PrimaryKeyConstraint('login_history_id', name=op.f('pk_auth_login_history')), - sa.UniqueConstraint('user_id', 'client_id', 'date', name=op.f('uq_auth_login_history_user_id')) + op.create_table( + "auth_login_history", + sa.Column("login_history_id", postgresql.UUID(), nullable=False), + sa.Column("user_id", postgresql.UUID(), nullable=False), + sa.Column("client_id", postgresql.UUID(), nullable=False), + sa.Column("date", sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint( + ["client_id"], ["auth_clients.client_id"], name=op.f("fk_auth_login_history_client_id_auth_clients"), + ), + sa.ForeignKeyConstraint( + ["user_id"], ["auth_users.UserID"], name=op.f("fk_auth_login_history_user_id_auth_users"), + ), + sa.PrimaryKeyConstraint("login_history_id", name=op.f("pk_auth_login_history")), + sa.UniqueConstraint("user_id", "client_id", "date", name=op.f("uq_auth_login_history_user_id")), ) - op.create_table('auth_rolegroups', - sa.Column('RoleGroupID', postgresql.UUID(), nullable=False), - sa.Column('RoleID', postgresql.UUID(), nullable=True), - sa.Column('GroupID', postgresql.UUID(), nullable=True), - sa.ForeignKeyConstraint(['GroupID'], ['auth_groups.GroupID'], name=op.f('fk_auth_rolegroups_GroupID_auth_groups')), - sa.ForeignKeyConstraint(['RoleID'], ['auth_roles.RoleID'], name=op.f('fk_auth_rolegroups_RoleID_auth_roles')), - sa.PrimaryKeyConstraint('RoleGroupID', name=op.f('pk_auth_rolegroups')) + op.create_table( + "auth_rolegroups", + sa.Column("RoleGroupID", postgresql.UUID(), nullable=False), + sa.Column("RoleID", postgresql.UUID(), nullable=True), + sa.Column("GroupID", postgresql.UUID(), nullable=True), + sa.ForeignKeyConstraint( + ["GroupID"], ["auth_groups.GroupID"], name=op.f("fk_auth_rolegroups_GroupID_auth_groups"), + ), + sa.ForeignKeyConstraint(["RoleID"], ["auth_roles.RoleID"], name=op.f("fk_auth_rolegroups_RoleID_auth_roles"),), + sa.PrimaryKeyConstraint("RoleGroupID", name=op.f("pk_auth_rolegroups")), ) - op.create_table('auth_usergroups', - sa.Column('UserGroupID', postgresql.UUID(), nullable=False), - sa.Column('UserID', postgresql.UUID(), nullable=True), - sa.Column('GroupID', postgresql.UUID(), nullable=True), - sa.ForeignKeyConstraint(['GroupID'], ['auth_groups.GroupID'], name=op.f('fk_auth_usergroups_GroupID_auth_groups')), - sa.ForeignKeyConstraint(['UserID'], ['auth_users.UserID'], name=op.f('fk_auth_usergroups_UserID_auth_users')), - sa.PrimaryKeyConstraint('UserGroupID', name=op.f('pk_auth_usergroups')) + op.create_table( + "auth_usergroups", + sa.Column("UserGroupID", postgresql.UUID(), nullable=False), + sa.Column("UserID", postgresql.UUID(), nullable=True), + sa.Column("GroupID", postgresql.UUID(), nullable=True), + sa.ForeignKeyConstraint( + ["GroupID"], ["auth_groups.GroupID"], name=op.f("fk_auth_usergroups_GroupID_auth_groups"), + ), + sa.ForeignKeyConstraint(["UserID"], ["auth_users.UserID"], name=op.f("fk_auth_usergroups_UserID_auth_users"),), + sa.PrimaryKeyConstraint("UserGroupID", name=op.f("pk_auth_usergroups")), ) - op.create_table('vouchers', - sa.Column('VoucherID', postgresql.UUID(), nullable=False), - sa.Column('date', sa.DateTime(), nullable=False), - sa.Column('narration', sa.Unicode(length=1000), nullable=False), - sa.Column('is_reconciled', sa.Boolean(), nullable=False), - sa.Column('reconcile_date', sa.DateTime(), nullable=False), - sa.Column('is_starred', sa.Boolean(), nullable=False), - sa.Column('creation_date', sa.DateTime(timezone=True), nullable=False), - sa.Column('last_edit_date', sa.DateTime(timezone=True), nullable=False), - sa.Column('voucher_type', sa.Integer(), nullable=False), - sa.Column('user_id', postgresql.UUID(), nullable=False), - sa.Column('is_posted', sa.Boolean(), nullable=False), - sa.Column('poster_id', postgresql.UUID(), nullable=True), - sa.ForeignKeyConstraint(['poster_id'], ['auth_users.UserID'], name=op.f('fk_vouchers_poster_id_auth_users')), - sa.ForeignKeyConstraint(['user_id'], ['auth_users.UserID'], name=op.f('fk_vouchers_user_id_auth_users')), - sa.PrimaryKeyConstraint('VoucherID', name=op.f('pk_vouchers')) + op.create_table( + "vouchers", + sa.Column("VoucherID", postgresql.UUID(), nullable=False), + sa.Column("date", sa.DateTime(), nullable=False), + sa.Column("narration", sa.Unicode(length=1000), nullable=False), + sa.Column("is_reconciled", sa.Boolean(), nullable=False), + sa.Column("reconcile_date", sa.DateTime(), nullable=False), + sa.Column("is_starred", sa.Boolean(), nullable=False), + sa.Column("creation_date", sa.DateTime(timezone=True), nullable=False), + sa.Column("last_edit_date", sa.DateTime(timezone=True), nullable=False), + sa.Column("voucher_type", sa.Integer(), nullable=False), + sa.Column("user_id", postgresql.UUID(), nullable=False), + sa.Column("is_posted", sa.Boolean(), nullable=False), + sa.Column("poster_id", postgresql.UUID(), nullable=True), + sa.ForeignKeyConstraint(["poster_id"], ["auth_users.UserID"], name=op.f("fk_vouchers_poster_id_auth_users"),), + sa.ForeignKeyConstraint(["user_id"], ["auth_users.UserID"], name=op.f("fk_vouchers_user_id_auth_users"),), + sa.PrimaryKeyConstraint("VoucherID", name=op.f("pk_vouchers")), ) - op.create_index(op.f('ix_vouchers_date'), 'vouchers', ['date'], unique=False) - op.create_table('employees', - sa.Column('id', postgresql.UUID(), nullable=False), - sa.Column('Designation', sa.Unicode(length=255), nullable=True), - sa.Column('Salary', sa.Integer(), nullable=True), - sa.Column('ServicePoints', sa.Numeric(precision=5, scale=2), nullable=True), - sa.Column('JoiningDate', sa.DateTime(), nullable=True), - sa.Column('LeavingDate', sa.DateTime(), nullable=True), - sa.ForeignKeyConstraint(['id'], ['accounts.id'], name=op.f('fk_employees_id_accounts')), - sa.PrimaryKeyConstraint('id', name=op.f('pk_employees')) + op.create_index(op.f("ix_vouchers_date"), "vouchers", ["date"], unique=False) + op.create_table( + "employees", + sa.Column("id", postgresql.UUID(), nullable=False), + sa.Column("Designation", sa.Unicode(length=255), nullable=True), + sa.Column("Salary", sa.Integer(), nullable=True), + sa.Column("ServicePoints", sa.Numeric(precision=5, scale=2), nullable=True), + sa.Column("JoiningDate", sa.DateTime(), nullable=True), + sa.Column("LeavingDate", sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(["id"], ["accounts.id"], name=op.f("fk_employees_id_accounts")), + sa.PrimaryKeyConstraint("id", name=op.f("pk_employees")), ) - op.create_table('journals', - sa.Column('JournalID', postgresql.UUID(), nullable=False), - sa.Column('Debit', sa.Integer(), nullable=True), - sa.Column('Amount', sa.Numeric(), nullable=True), - sa.Column('VoucherID', postgresql.UUID(), nullable=False), - sa.Column('account_id', postgresql.UUID(), nullable=False), - sa.Column('CostCentreID', postgresql.UUID(), nullable=False), - sa.ForeignKeyConstraint(['CostCentreID'], ['cost_centres.CostCentreID'], name=op.f('fk_journals_CostCentreID_cost_centres')), - sa.ForeignKeyConstraint(['VoucherID'], ['vouchers.VoucherID'], name=op.f('fk_journals_VoucherID_vouchers')), - sa.ForeignKeyConstraint(['account_id'], ['accounts.id'], name=op.f('fk_journals_account_id_accounts')), - sa.PrimaryKeyConstraint('JournalID', name=op.f('pk_journals')) + op.create_table( + "journals", + sa.Column("JournalID", postgresql.UUID(), nullable=False), + sa.Column("Debit", sa.Integer(), nullable=True), + sa.Column("Amount", sa.Numeric(), nullable=True), + sa.Column("VoucherID", postgresql.UUID(), nullable=False), + sa.Column("account_id", postgresql.UUID(), nullable=False), + sa.Column("CostCentreID", postgresql.UUID(), nullable=False), + sa.ForeignKeyConstraint( + ["CostCentreID"], ["cost_centres.CostCentreID"], name=op.f("fk_journals_CostCentreID_cost_centres"), + ), + sa.ForeignKeyConstraint(["VoucherID"], ["vouchers.VoucherID"], name=op.f("fk_journals_VoucherID_vouchers"),), + sa.ForeignKeyConstraint(["account_id"], ["accounts.id"], name=op.f("fk_journals_account_id_accounts"),), + sa.PrimaryKeyConstraint("JournalID", name=op.f("pk_journals")), ) - op.create_index(op.f('ix_journals_VoucherID'), 'journals', ['VoucherID'], unique=False) - op.create_table('products', - sa.Column('ProductID', postgresql.UUID(), nullable=False), - sa.Column('Code', sa.Integer(), nullable=True), - sa.Column('Name', sa.Unicode(length=255), nullable=False), - sa.Column('Units', sa.Unicode(length=255), nullable=False), - sa.Column('Fraction', sa.Numeric(), nullable=False), - sa.Column('FractionUnits', sa.Unicode(length=255), nullable=False), - sa.Column('ProductYield', sa.Numeric(), nullable=False), - sa.Column('ProductGroupID', postgresql.UUID(), nullable=False), - sa.Column('account_id', postgresql.UUID(), nullable=False), - sa.Column('cost_price', sa.Numeric(), nullable=False), - sa.Column('sale_price', sa.Numeric(), nullable=False), - sa.Column('IsActive', sa.Boolean(), nullable=False), - sa.Column('IsFixture', sa.Boolean(), nullable=False), - sa.Column('is_purchased', sa.Boolean(), nullable=False), - sa.Column('is_sold', sa.Boolean(), nullable=False), - sa.ForeignKeyConstraint(['ProductGroupID'], ['product_groups.ProductGroupID'], name=op.f('fk_products_ProductGroupID_product_groups')), - sa.ForeignKeyConstraint(['account_id'], ['accounts.id'], name=op.f('fk_products_account_id_accounts')), - sa.PrimaryKeyConstraint('ProductID', name=op.f('pk_products')), - sa.UniqueConstraint('Code', name=op.f('uq_products_Code')), - sa.UniqueConstraint('Name', 'Units', name=op.f('uq_products_Name')) + op.create_index(op.f("ix_journals_VoucherID"), "journals", ["VoucherID"], unique=False) + op.create_table( + "products", + sa.Column("ProductID", postgresql.UUID(), nullable=False), + sa.Column("Code", sa.Integer(), nullable=True), + sa.Column("Name", sa.Unicode(length=255), nullable=False), + sa.Column("Units", sa.Unicode(length=255), nullable=False), + sa.Column("Fraction", sa.Numeric(), nullable=False), + sa.Column("FractionUnits", sa.Unicode(length=255), nullable=False), + sa.Column("ProductYield", sa.Numeric(), nullable=False), + sa.Column("ProductGroupID", postgresql.UUID(), nullable=False), + sa.Column("account_id", postgresql.UUID(), nullable=False), + sa.Column("cost_price", sa.Numeric(), nullable=False), + sa.Column("sale_price", sa.Numeric(), nullable=False), + sa.Column("IsActive", sa.Boolean(), nullable=False), + sa.Column("IsFixture", sa.Boolean(), nullable=False), + sa.Column("is_purchased", sa.Boolean(), nullable=False), + sa.Column("is_sold", sa.Boolean(), nullable=False), + sa.ForeignKeyConstraint( + ["ProductGroupID"], + ["product_groups.ProductGroupID"], + name=op.f("fk_products_ProductGroupID_product_groups"), + ), + sa.ForeignKeyConstraint(["account_id"], ["accounts.id"], name=op.f("fk_products_account_id_accounts"),), + sa.PrimaryKeyConstraint("ProductID", name=op.f("pk_products")), + sa.UniqueConstraint("Code", name=op.f("uq_products_Code")), + sa.UniqueConstraint("Name", "Units", name=op.f("uq_products_Name")), ) - op.create_table('attendances', - sa.Column('AttendanceID', postgresql.UUID(), nullable=False), - sa.Column('EmployeeID', postgresql.UUID(), nullable=True), - sa.Column('Date', sa.DateTime(), nullable=True), - sa.Column('AttendanceType', sa.Integer(), nullable=True), - sa.Column('Amount', sa.Numeric(), nullable=True), - sa.Column('CreationDate', sa.DateTime(timezone=True), nullable=True), - sa.Column('UserID', postgresql.UUID(), nullable=True), - sa.Column('IsValid', sa.Boolean(), nullable=True), - sa.ForeignKeyConstraint(['EmployeeID'], ['employees.id'], name=op.f('fk_attendances_EmployeeID_employees')), - sa.ForeignKeyConstraint(['UserID'], ['auth_users.UserID'], name=op.f('fk_attendances_UserID_auth_users')), - sa.PrimaryKeyConstraint('AttendanceID', name=op.f('pk_attendances')) + op.create_table( + "attendances", + sa.Column("AttendanceID", postgresql.UUID(), nullable=False), + sa.Column("EmployeeID", postgresql.UUID(), nullable=True), + sa.Column("Date", sa.DateTime(), nullable=True), + sa.Column("AttendanceType", sa.Integer(), nullable=True), + sa.Column("Amount", sa.Numeric(), nullable=True), + sa.Column("CreationDate", sa.DateTime(timezone=True), nullable=True), + sa.Column("UserID", postgresql.UUID(), nullable=True), + sa.Column("IsValid", sa.Boolean(), nullable=True), + sa.ForeignKeyConstraint(["EmployeeID"], ["employees.id"], name=op.f("fk_attendances_EmployeeID_employees"),), + sa.ForeignKeyConstraint(["UserID"], ["auth_users.UserID"], name=op.f("fk_attendances_UserID_auth_users"),), + sa.PrimaryKeyConstraint("AttendanceID", name=op.f("pk_attendances")), ) - op.create_table('batches', - sa.Column('BatchID', postgresql.UUID(), nullable=False), - sa.Column('Name', sa.DateTime(), nullable=True), - sa.Column('ProductID', postgresql.UUID(), nullable=False), - sa.Column('QuantityRemaining', sa.Numeric(), nullable=True), - sa.Column('Rate', sa.Numeric(), nullable=True), - sa.Column('Tax', sa.Numeric(), nullable=True), - sa.Column('Discount', sa.Numeric(), nullable=True), - sa.ForeignKeyConstraint(['ProductID'], ['products.ProductID'], name=op.f('fk_batches_ProductID_products')), - sa.PrimaryKeyConstraint('BatchID', name=op.f('pk_batches')) + op.create_table( + "batches", + sa.Column("BatchID", postgresql.UUID(), nullable=False), + sa.Column("Name", sa.DateTime(), nullable=True), + sa.Column("ProductID", postgresql.UUID(), nullable=False), + sa.Column("QuantityRemaining", sa.Numeric(), nullable=True), + sa.Column("Rate", sa.Numeric(), nullable=True), + sa.Column("Tax", sa.Numeric(), nullable=True), + sa.Column("Discount", sa.Numeric(), nullable=True), + sa.ForeignKeyConstraint(["ProductID"], ["products.ProductID"], name=op.f("fk_batches_ProductID_products"),), + sa.PrimaryKeyConstraint("BatchID", name=op.f("pk_batches")), ) - op.create_table('fingerprints', - sa.Column('FingerprintID', postgresql.UUID(), nullable=False), - sa.Column('EmployeeID', postgresql.UUID(), nullable=True), - sa.Column('Date', sa.DateTime(), nullable=True), - sa.ForeignKeyConstraint(['EmployeeID'], ['employees.id'], name=op.f('fk_fingerprints_EmployeeID_employees')), - sa.PrimaryKeyConstraint('FingerprintID', name=op.f('pk_fingerprints')) + op.create_table( + "fingerprints", + sa.Column("FingerprintID", postgresql.UUID(), nullable=False), + sa.Column("EmployeeID", postgresql.UUID(), nullable=True), + sa.Column("Date", sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(["EmployeeID"], ["employees.id"], name=op.f("fk_fingerprints_EmployeeID_employees"),), + sa.PrimaryKeyConstraint("FingerprintID", name=op.f("pk_fingerprints")), ) - op.create_table('recipes', - sa.Column('recipe_id', postgresql.UUID(), nullable=False), - sa.Column('product_id', postgresql.UUID(), nullable=False), - sa.Column('quantity', sa.Numeric(), nullable=False), - sa.Column('cost_price', sa.Numeric(), nullable=False), - sa.Column('sale_price', sa.Numeric(), nullable=False), - sa.Column('notes', sa.Unicode(length=255), nullable=True), - sa.Column('valid_from', sa.Date(), nullable=False), - sa.Column('valid_to', sa.Date(), nullable=False), - sa.Column('effective_from', sa.Date(), nullable=False), - sa.Column('effective_to', sa.Date(), nullable=True), - sa.ForeignKeyConstraint(['product_id'], ['products.ProductID'], name=op.f('fk_recipes_product_id_products')), - sa.PrimaryKeyConstraint('recipe_id', name=op.f('pk_recipes')) + op.create_table( + "recipes", + sa.Column("recipe_id", postgresql.UUID(), nullable=False), + sa.Column("product_id", postgresql.UUID(), nullable=False), + sa.Column("quantity", sa.Numeric(), nullable=False), + sa.Column("cost_price", sa.Numeric(), nullable=False), + sa.Column("sale_price", sa.Numeric(), nullable=False), + sa.Column("notes", sa.Unicode(length=255), nullable=True), + sa.Column("valid_from", sa.Date(), nullable=False), + sa.Column("valid_to", sa.Date(), nullable=False), + sa.Column("effective_from", sa.Date(), nullable=False), + sa.Column("effective_to", sa.Date(), nullable=True), + sa.ForeignKeyConstraint(["product_id"], ["products.ProductID"], name=op.f("fk_recipes_product_id_products"),), + sa.PrimaryKeyConstraint("recipe_id", name=op.f("pk_recipes")), ) - op.create_table('salary_deductions', - sa.Column('SalaryDeductionID', postgresql.UUID(), nullable=False), - sa.Column('VoucherID', postgresql.UUID(), nullable=False), - sa.Column('JournalID', postgresql.UUID(), nullable=False), - sa.Column('GrossSalary', sa.Integer(), nullable=True), - sa.Column('DaysWorked', sa.Integer(), nullable=True), - sa.Column('EsiEmployee', sa.Integer(), nullable=True), - sa.Column('PfEmployee', sa.Integer(), nullable=True), - sa.Column('EsiEmployer', sa.Integer(), nullable=True), - sa.Column('PfEmployer', sa.Integer(), nullable=True), - sa.ForeignKeyConstraint(['JournalID'], ['journals.JournalID'], name=op.f('fk_salary_deductions_JournalID_journals')), - sa.ForeignKeyConstraint(['VoucherID'], ['vouchers.VoucherID'], name=op.f('fk_salary_deductions_VoucherID_vouchers')), - sa.PrimaryKeyConstraint('SalaryDeductionID', name=op.f('pk_salary_deductions')) + op.create_table( + "salary_deductions", + sa.Column("SalaryDeductionID", postgresql.UUID(), nullable=False), + sa.Column("VoucherID", postgresql.UUID(), nullable=False), + sa.Column("JournalID", postgresql.UUID(), nullable=False), + sa.Column("GrossSalary", sa.Integer(), nullable=True), + sa.Column("DaysWorked", sa.Integer(), nullable=True), + sa.Column("EsiEmployee", sa.Integer(), nullable=True), + sa.Column("PfEmployee", sa.Integer(), nullable=True), + sa.Column("EsiEmployer", sa.Integer(), nullable=True), + sa.Column("PfEmployer", sa.Integer(), nullable=True), + sa.ForeignKeyConstraint( + ["JournalID"], ["journals.JournalID"], name=op.f("fk_salary_deductions_JournalID_journals"), + ), + sa.ForeignKeyConstraint( + ["VoucherID"], ["vouchers.VoucherID"], name=op.f("fk_salary_deductions_VoucherID_vouchers"), + ), + sa.PrimaryKeyConstraint("SalaryDeductionID", name=op.f("pk_salary_deductions")), ) - op.create_table('service_charges', - sa.Column('id', postgresql.UUID(), nullable=False), - sa.Column('voucher_id', postgresql.UUID(), nullable=False), - sa.Column('journal_id', postgresql.UUID(), nullable=False), - sa.Column('days_worked', sa.Integer(), nullable=False), - sa.Column('points', sa.Numeric(precision=5, scale=2), nullable=False), - sa.ForeignKeyConstraint(['journal_id'], ['journals.JournalID'], name=op.f('fk_service_charges_journal_id_journals')), - sa.ForeignKeyConstraint(['voucher_id'], ['vouchers.VoucherID'], name=op.f('fk_service_charges_voucher_id_vouchers')), - sa.PrimaryKeyConstraint('id', name=op.f('pk_service_charges')) + op.create_table( + "service_charges", + sa.Column("id", postgresql.UUID(), nullable=False), + sa.Column("voucher_id", postgresql.UUID(), nullable=False), + sa.Column("journal_id", postgresql.UUID(), nullable=False), + sa.Column("days_worked", sa.Integer(), nullable=False), + sa.Column("points", sa.Numeric(precision=5, scale=2), nullable=False), + sa.ForeignKeyConstraint( + ["journal_id"], ["journals.JournalID"], name=op.f("fk_service_charges_journal_id_journals"), + ), + sa.ForeignKeyConstraint( + ["voucher_id"], ["vouchers.VoucherID"], name=op.f("fk_service_charges_voucher_id_vouchers"), + ), + sa.PrimaryKeyConstraint("id", name=op.f("pk_service_charges")), ) - op.create_table('inventories', - sa.Column('InventoryID', postgresql.UUID(), nullable=False), - sa.Column('VoucherID', postgresql.UUID(), nullable=False), - sa.Column('ProductID', postgresql.UUID(), nullable=False), - sa.Column('BatchID', postgresql.UUID(), nullable=False), - sa.Column('Quantity', sa.Numeric(), nullable=True), - sa.Column('Rate', sa.Numeric(), nullable=True), - sa.Column('Tax', sa.Numeric(), nullable=True), - sa.Column('Discount', sa.Numeric(), nullable=True), - sa.ForeignKeyConstraint(['BatchID'], ['batches.BatchID'], name=op.f('fk_inventories_BatchID_batches')), - sa.ForeignKeyConstraint(['ProductID'], ['products.ProductID'], name=op.f('fk_inventories_ProductID_products')), - sa.ForeignKeyConstraint(['VoucherID'], ['vouchers.VoucherID'], name=op.f('fk_inventories_VoucherID_vouchers')), - sa.PrimaryKeyConstraint('InventoryID', name=op.f('pk_inventories')), - sa.UniqueConstraint('VoucherID', 'BatchID', name=op.f('uq_inventories_VoucherID')) + op.create_table( + "inventories", + sa.Column("InventoryID", postgresql.UUID(), nullable=False), + sa.Column("VoucherID", postgresql.UUID(), nullable=False), + sa.Column("ProductID", postgresql.UUID(), nullable=False), + sa.Column("BatchID", postgresql.UUID(), nullable=False), + sa.Column("Quantity", sa.Numeric(), nullable=True), + sa.Column("Rate", sa.Numeric(), nullable=True), + sa.Column("Tax", sa.Numeric(), nullable=True), + sa.Column("Discount", sa.Numeric(), nullable=True), + sa.ForeignKeyConstraint(["BatchID"], ["batches.BatchID"], name=op.f("fk_inventories_BatchID_batches"),), + sa.ForeignKeyConstraint(["ProductID"], ["products.ProductID"], name=op.f("fk_inventories_ProductID_products"),), + sa.ForeignKeyConstraint(["VoucherID"], ["vouchers.VoucherID"], name=op.f("fk_inventories_VoucherID_vouchers"),), + sa.PrimaryKeyConstraint("InventoryID", name=op.f("pk_inventories")), + sa.UniqueConstraint("VoucherID", "BatchID", name=op.f("uq_inventories_VoucherID")), ) - op.create_index(op.f('ix_inventories_VoucherID'), 'inventories', ['VoucherID'], unique=False) - op.create_table('recipe_items', - sa.Column('recipe_item_id', postgresql.UUID(), nullable=False), - sa.Column('recipe_id', postgresql.UUID(), nullable=False), - sa.Column('product_id', postgresql.UUID(), nullable=False), - sa.Column('quantity', sa.Integer(), nullable=False), - sa.Column('price', sa.Integer(), nullable=False), - sa.ForeignKeyConstraint(['product_id'], ['products.ProductID'], name=op.f('fk_recipe_items_product_id_products')), - sa.ForeignKeyConstraint(['recipe_id'], ['recipes.recipe_id'], name=op.f('fk_recipe_items_recipe_id_recipes')), - sa.PrimaryKeyConstraint('recipe_item_id', name=op.f('pk_recipe_items')), - sa.UniqueConstraint('recipe_id', 'product_id', name=op.f('uq_recipe_items_recipe_id')) + op.create_index(op.f("ix_inventories_VoucherID"), "inventories", ["VoucherID"], unique=False) + op.create_table( + "recipe_items", + sa.Column("recipe_item_id", postgresql.UUID(), nullable=False), + sa.Column("recipe_id", postgresql.UUID(), nullable=False), + sa.Column("product_id", postgresql.UUID(), nullable=False), + sa.Column("quantity", sa.Integer(), nullable=False), + sa.Column("price", sa.Integer(), nullable=False), + sa.ForeignKeyConstraint( + ["product_id"], ["products.ProductID"], name=op.f("fk_recipe_items_product_id_products"), + ), + sa.ForeignKeyConstraint(["recipe_id"], ["recipes.recipe_id"], name=op.f("fk_recipe_items_recipe_id_recipes"),), + sa.PrimaryKeyConstraint("recipe_item_id", name=op.f("pk_recipe_items")), + sa.UniqueConstraint("recipe_id", "product_id", name=op.f("uq_recipe_items_recipe_id")), ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('recipe_items') - op.drop_index(op.f('ix_inventories_VoucherID'), table_name='inventories') - op.drop_table('inventories') - op.drop_table('service_charges') - op.drop_table('salary_deductions') - op.drop_table('recipes') - op.drop_table('fingerprints') - op.drop_table('batches') - op.drop_table('attendances') - op.drop_table('products') - op.drop_index(op.f('ix_journals_VoucherID'), table_name='journals') - op.drop_table('journals') - op.drop_table('employees') - op.drop_index(op.f('ix_vouchers_date'), table_name='vouchers') - op.drop_table('vouchers') - op.drop_table('auth_usergroups') - op.drop_table('auth_rolegroups') - op.drop_table('auth_login_history') - op.drop_table('accounts') - op.drop_table('settings') - op.drop_table('product_groups') - op.drop_table('images') - op.drop_table('cost_centres') - op.drop_table('auth_users') - op.drop_table('auth_roles') - op.drop_table('auth_groups') - op.drop_table('auth_clients') + op.drop_table("recipe_items") + op.drop_index(op.f("ix_inventories_VoucherID"), table_name="inventories") + op.drop_table("inventories") + op.drop_table("service_charges") + op.drop_table("salary_deductions") + op.drop_table("recipes") + op.drop_table("fingerprints") + op.drop_table("batches") + op.drop_table("attendances") + op.drop_table("products") + op.drop_index(op.f("ix_journals_VoucherID"), table_name="journals") + op.drop_table("journals") + op.drop_table("employees") + op.drop_index(op.f("ix_vouchers_date"), table_name="vouchers") + op.drop_table("vouchers") + op.drop_table("auth_usergroups") + op.drop_table("auth_rolegroups") + op.drop_table("auth_login_history") + op.drop_table("accounts") + op.drop_table("settings") + op.drop_table("product_groups") + op.drop_table("images") + op.drop_table("cost_centres") + op.drop_table("auth_users") + op.drop_table("auth_roles") + op.drop_table("auth_groups") + op.drop_table("auth_clients") # ### end Alembic commands ### diff --git a/alembic/versions/eed0b382c287_lowercase_fastapi.py b/alembic/versions/eed0b382c287_lowercase_fastapi.py index a6176996..41444994 100644 --- a/alembic/versions/eed0b382c287_lowercase_fastapi.py +++ b/alembic/versions/eed0b382c287_lowercase_fastapi.py @@ -11,206 +11,235 @@ from sqlalchemy import table, column, select from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. -revision = 'eed0b382c287' -down_revision = '0bf3d70ee7de' +revision = "eed0b382c287" +down_revision = "0bf3d70ee7de" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### - op.drop_table('msg_subscribers') - op.drop_table('msg_posts') - op.drop_table('msg_threadtags') - op.drop_table('msg_threads') - op.drop_table('msg_tags') + op.drop_table("msg_subscribers") + op.drop_table("msg_posts") + op.drop_table("msg_threadtags") + op.drop_table("msg_threads") + op.drop_table("msg_tags") - op.rename_table('auth_roles', 'auth_permissions') + op.rename_table("auth_roles", "auth_permissions") with op.batch_alter_table("auth_permissions") as batch_op: - batch_op.alter_column('RoleID', new_column_name='id') - batch_op.alter_column('Name', new_column_name='name') + batch_op.alter_column("RoleID", new_column_name="id") + batch_op.alter_column("Name", new_column_name="name") - op.rename_table('auth_groups', 'auth_roles') + op.rename_table("auth_groups", "auth_roles") with op.batch_alter_table("auth_roles") as batch_op: - batch_op.alter_column('GroupID', new_column_name='id') - batch_op.alter_column('Name', new_column_name='name') + batch_op.alter_column("GroupID", new_column_name="id") + batch_op.alter_column("Name", new_column_name="name") - op.rename_table('auth_rolegroups', 'role_permissions') + op.rename_table("auth_rolegroups", "role_permissions") with op.batch_alter_table("role_permissions") as batch_op: - batch_op.alter_column('RoleGroupID', new_column_name='id') - batch_op.alter_column('RoleID', new_column_name='permission_id') - batch_op.alter_column('GroupID', new_column_name='role_id') + batch_op.alter_column("RoleGroupID", new_column_name="id") + batch_op.alter_column("RoleID", new_column_name="permission_id") + batch_op.alter_column("GroupID", new_column_name="role_id") - op.rename_table('auth_usergroups', 'user_roles') + op.rename_table("auth_usergroups", "user_roles") with op.batch_alter_table("user_roles") as batch_op: - batch_op.alter_column('UserGroupID', new_column_name='id') - batch_op.alter_column('UserID', new_column_name='user_id') - batch_op.alter_column('GroupID', new_column_name='role_id') + batch_op.alter_column("UserGroupID", new_column_name="id") + batch_op.alter_column("UserID", new_column_name="user_id") + batch_op.alter_column("GroupID", new_column_name="role_id") with op.batch_alter_table("attendances") as batch_op: - batch_op.alter_column('Amount', new_column_name='amount') - batch_op.alter_column('UserID', new_column_name='user_id') - batch_op.alter_column('AttendanceType', new_column_name='attendance_type') - batch_op.alter_column('CreationDate', new_column_name='creation_date') - batch_op.alter_column('Date', new_column_name='date', type_=sa.Date(), nullable=False) - batch_op.alter_column('EmployeeID', new_column_name='employee_id') - batch_op.alter_column('AttendanceID', new_column_name='id') - batch_op.alter_column('IsValid', new_column_name='is_valid') + batch_op.alter_column("Amount", new_column_name="amount") + batch_op.alter_column("UserID", new_column_name="user_id") + batch_op.alter_column("AttendanceType", new_column_name="attendance_type") + batch_op.alter_column("CreationDate", new_column_name="creation_date") + batch_op.alter_column("Date", new_column_name="date", type_=sa.Date(), nullable=False) + batch_op.alter_column("EmployeeID", new_column_name="employee_id") + batch_op.alter_column("AttendanceID", new_column_name="id") + batch_op.alter_column("IsValid", new_column_name="is_valid") with op.batch_alter_table("auth_users") as batch_op: - batch_op.alter_column('UserID', new_column_name='id') - batch_op.alter_column('Name', new_column_name='username') - batch_op.alter_column('Password', new_column_name='password') - batch_op.alter_column('LockedOut', new_column_name='disabled') + batch_op.alter_column("UserID", new_column_name="id") + batch_op.alter_column("Name", new_column_name="username") + batch_op.alter_column("Password", new_column_name="password") + batch_op.alter_column("LockedOut", new_column_name="disabled") with op.batch_alter_table("batches") as batch_op: - batch_op.alter_column('BatchID', new_column_name='id') - batch_op.alter_column('Discount', new_column_name='discount') - batch_op.alter_column('Name', new_column_name='name', type_=sa.Date(), nullable=False) - batch_op.alter_column('ProductID', new_column_name='product_id') - batch_op.alter_column('QuantityRemaining', new_column_name='quantity_remaining') - batch_op.alter_column('Rate', new_column_name='rate') - batch_op.alter_column('Tax', new_column_name='tax') + batch_op.alter_column("BatchID", new_column_name="id") + batch_op.alter_column("Discount", new_column_name="discount") + batch_op.alter_column("Name", new_column_name="name", type_=sa.Date(), nullable=False) + batch_op.alter_column("ProductID", new_column_name="product_id") + batch_op.alter_column("QuantityRemaining", new_column_name="quantity_remaining") + batch_op.alter_column("Rate", new_column_name="rate") + batch_op.alter_column("Tax", new_column_name="tax") with op.batch_alter_table("cost_centres") as batch_op: - batch_op.alter_column('CostCentreID', new_column_name='id') - batch_op.alter_column('Name', new_column_name='name') - batch_op.alter_column('IsFixture', new_column_name='is_fixture') + batch_op.alter_column("CostCentreID", new_column_name="id") + batch_op.alter_column("Name", new_column_name="name") + batch_op.alter_column("IsFixture", new_column_name="is_fixture") with op.batch_alter_table("product_groups") as batch_op: - batch_op.alter_column('ProductGroupID', new_column_name='id') - batch_op.alter_column('Name', new_column_name='name') - batch_op.alter_column('IsFixture', new_column_name='is_fixture') + batch_op.alter_column("ProductGroupID", new_column_name="id") + batch_op.alter_column("Name", new_column_name="name") + batch_op.alter_column("IsFixture", new_column_name="is_fixture") with op.batch_alter_table("inventories") as batch_op: - batch_op.alter_column('InventoryID', new_column_name='id') - batch_op.alter_column('BatchID', new_column_name='batch_id') - batch_op.alter_column('Discount', new_column_name='discount') - batch_op.alter_column('ProductID', new_column_name='product_id') - batch_op.alter_column('Quantity', new_column_name='quantity') - batch_op.alter_column('Rate', new_column_name='rate') - batch_op.alter_column('Tax', new_column_name='tax') - batch_op.alter_column('VoucherID', new_column_name='voucher_id') + batch_op.alter_column("InventoryID", new_column_name="id") + batch_op.alter_column("BatchID", new_column_name="batch_id") + batch_op.alter_column("Discount", new_column_name="discount") + batch_op.alter_column("ProductID", new_column_name="product_id") + batch_op.alter_column("Quantity", new_column_name="quantity") + batch_op.alter_column("Rate", new_column_name="rate") + batch_op.alter_column("Tax", new_column_name="tax") + batch_op.alter_column("VoucherID", new_column_name="voucher_id") with op.batch_alter_table("journals") as batch_op: - batch_op.alter_column('Amount', new_column_name='amount') - batch_op.alter_column('CostCentreID', new_column_name='cost_centre_id') - batch_op.alter_column('Debit', new_column_name='debit') - batch_op.alter_column('JournalID', new_column_name='id') - batch_op.alter_column('VoucherID', new_column_name='voucher_id') + batch_op.alter_column("Amount", new_column_name="amount") + batch_op.alter_column("CostCentreID", new_column_name="cost_centre_id") + batch_op.alter_column("Debit", new_column_name="debit") + batch_op.alter_column("JournalID", new_column_name="id") + batch_op.alter_column("VoucherID", new_column_name="voucher_id") with op.batch_alter_table("fingerprints") as batch_op: - batch_op.alter_column('FingerprintID', new_column_name='id') - batch_op.alter_column('Date', new_column_name='date') - batch_op.alter_column('EmployeeID', new_column_name='employee_id') + batch_op.alter_column("FingerprintID", new_column_name="id") + batch_op.alter_column("Date", new_column_name="date") + batch_op.alter_column("EmployeeID", new_column_name="employee_id") with op.batch_alter_table("products") as batch_op: - batch_op.alter_column('ProductID', new_column_name='id') - batch_op.alter_column('Code', new_column_name='code') - batch_op.alter_column('Fraction', new_column_name='fraction') - batch_op.alter_column('FractionUnits', new_column_name='fraction_units') - batch_op.alter_column('IsActive', new_column_name='is_active') - batch_op.alter_column('IsFixture', new_column_name='is_fixture') - batch_op.alter_column('Name', new_column_name='name') - batch_op.alter_column('ProductGroupID', new_column_name='product_group_id') - batch_op.alter_column('ProductYield', new_column_name='product_yield') - batch_op.alter_column('Units', new_column_name='units') + batch_op.alter_column("ProductID", new_column_name="id") + batch_op.alter_column("Code", new_column_name="code") + batch_op.alter_column("Fraction", new_column_name="fraction") + batch_op.alter_column("FractionUnits", new_column_name="fraction_units") + batch_op.alter_column("IsActive", new_column_name="is_active") + batch_op.alter_column("IsFixture", new_column_name="is_fixture") + batch_op.alter_column("Name", new_column_name="name") + batch_op.alter_column("ProductGroupID", new_column_name="product_group_id") + batch_op.alter_column("ProductYield", new_column_name="product_yield") + batch_op.alter_column("Units", new_column_name="units") with op.batch_alter_table("recipes") as batch_op: - batch_op.alter_column('recipe_id', new_column_name='id') + batch_op.alter_column("recipe_id", new_column_name="id") - op.rename_table('salary_deductions', 'employee_benefit') + op.rename_table("salary_deductions", "employee_benefit") with op.batch_alter_table("employee_benefit") as batch_op: - batch_op.alter_column('SalaryDeductionID', new_column_name='id') - batch_op.alter_column('DaysWorked', new_column_name='days_worked') - batch_op.alter_column('EsiEmployee', new_column_name='esi_employee') - batch_op.alter_column('EsiEmployer', new_column_name='esi_employer') - batch_op.alter_column('GrossSalary', new_column_name='gross_salary') - batch_op.alter_column('JournalID', new_column_name='journal_id') - batch_op.alter_column('PfEmployee', new_column_name='pf_employee') - batch_op.alter_column('PfEmployer', new_column_name='pf_employer') - batch_op.alter_column('VoucherID', new_column_name='voucher_id') + batch_op.alter_column("SalaryDeductionID", new_column_name="id") + batch_op.alter_column("DaysWorked", new_column_name="days_worked") + batch_op.alter_column("EsiEmployee", new_column_name="esi_employee") + batch_op.alter_column("EsiEmployer", new_column_name="esi_employer") + batch_op.alter_column("GrossSalary", new_column_name="gross_salary") + batch_op.alter_column("JournalID", new_column_name="journal_id") + batch_op.alter_column("PfEmployee", new_column_name="pf_employee") + batch_op.alter_column("PfEmployer", new_column_name="pf_employer") + batch_op.alter_column("VoucherID", new_column_name="voucher_id") with op.batch_alter_table("vouchers") as batch_op: - batch_op.alter_column('VoucherID', new_column_name='id') - batch_op.alter_column('date', type_=sa.Date(), nullable=False) - batch_op.alter_column('reconcile_date', type_=sa.Date(), nullable=False) + batch_op.alter_column("VoucherID", new_column_name="id") + batch_op.alter_column("date", type_=sa.Date(), nullable=False) + batch_op.alter_column("reconcile_date", type_=sa.Date(), nullable=False) - op.rename_table('service_charges', 'incentives') + op.rename_table("service_charges", "incentives") with op.batch_alter_table("employees") as batch_op: - batch_op.alter_column('Designation', new_column_name='designation', nullable=False) - batch_op.alter_column('Salary', new_column_name='salary', nullable=False) - batch_op.alter_column('ServicePoints', new_column_name='points', nullable=False) - batch_op.alter_column('JoiningDate', new_column_name='joining_date', type_=sa.Date(), nullable=False) - batch_op.alter_column('LeavingDate', new_column_name='leaving_date', type_=sa.Date(), nullable=True) + batch_op.alter_column("Designation", new_column_name="designation", nullable=False) + batch_op.alter_column("Salary", new_column_name="salary", nullable=False) + batch_op.alter_column("ServicePoints", new_column_name="points", nullable=False) + batch_op.alter_column( + "JoiningDate", new_column_name="joining_date", type_=sa.Date(), nullable=False, + ) + batch_op.alter_column( + "LeavingDate", new_column_name="leaving_date", type_=sa.Date(), nullable=True, + ) with op.batch_alter_table("settings") as batch_op: - batch_op.alter_column('SettingID', new_column_name='id') - batch_op.alter_column('Name', new_column_name='name') - batch_op.alter_column('Data', new_column_name='data') + batch_op.alter_column("SettingID", new_column_name="id") + batch_op.alter_column("Name", new_column_name="name") + batch_op.alter_column("Data", new_column_name="data") + op.create_unique_constraint(op.f("uq_accounts_name"), "accounts", ["name"]) + op.drop_constraint("accounts_name_key", "accounts", type_="unique") + op.create_unique_constraint(op.f("uq_auth_clients_code"), "auth_clients", ["code"]) + op.create_unique_constraint(op.f("uq_auth_clients_name"), "auth_clients", ["name"]) + op.drop_constraint("auth_clients_Code_key", "auth_clients", type_="unique") + op.drop_constraint("auth_clients_Name_key", "auth_clients", type_="unique") + op.create_unique_constraint( + op.f("uq_auth_login_history_user_id"), "auth_login_history", ["user_id", "client_id", "date"], + ) + op.drop_constraint( + "auth_login_history_user_id_client_id_date_key", "auth_login_history", type_="unique", + ) + op.create_unique_constraint(op.f("uq_auth_permissions_name"), "auth_permissions", ["name"]) + op.drop_constraint("auth_roles_Name_key", "auth_permissions", type_="unique") + op.create_unique_constraint(op.f("uq_auth_roles_name"), "auth_roles", ["name"]) + op.drop_constraint("auth_groups_Name_key", "auth_roles", type_="unique") + op.create_unique_constraint(op.f("uq_auth_users_username"), "auth_users", ["username"]) + op.drop_constraint("auth_users_Name_key", "auth_users", type_="unique") + op.create_unique_constraint(op.f("uq_cost_centres_name"), "cost_centres", ["name"]) + op.drop_constraint("entities_costcenters_Name_key", "cost_centres", type_="unique") + op.drop_constraint("uq_employee_id_date", "fingerprints", type_="unique") + op.create_index(op.f("ix_inventories_voucher_id"), "inventories", ["voucher_id"], unique=False) + op.create_unique_constraint(op.f("uq_inventories_voucher_id"), "inventories", ["voucher_id", "batch_id"]) + op.drop_index("ix_inventories_VoucherID", table_name="inventories") + op.create_index(op.f("ix_journals_voucher_id"), "journals", ["voucher_id"], unique=False) + op.drop_index("ix_journals_VoucherID", table_name="journals") + op.create_unique_constraint(op.f("uq_product_groups_name"), "product_groups", ["name"]) + op.drop_constraint("entities_productgroups_Name_key", "product_groups", type_="unique") + op.create_unique_constraint(op.f("uq_products_code"), "products", ["code"]) + op.create_unique_constraint(op.f("uq_products_name"), "products", ["name", "units"]) + op.drop_constraint("products_Code_key", "products", type_="unique") + op.drop_constraint("products_Name_Units_key", "products", type_="unique") + op.create_unique_constraint(op.f("uq_recipe_items_recipe_id"), "recipe_items", ["recipe_id", "product_id"]) + op.drop_constraint("recipe_items_recipe_id_product_id_key", "recipe_items", type_="unique") + op.create_unique_constraint(op.f("uq_settings_name"), "settings", ["name"]) + op.drop_constraint("settings_Name_key", "settings", type_="unique") + op.create_index(op.f("ix_vouchers_date"), "vouchers", ["date"], unique=False) + op.create_foreign_key( + "fk_incentives_journal_id_journals", "incentives", "journals", ["journal_id"], ["id"], + ) + op.create_foreign_key( + "fk_incentives_voucher_id_vouchers", "incentives", "vouchers", ["voucher_id"], ["id"], + ) + op.drop_constraint("service_charges_journal_id_fkey", "incentives", type_="foreignkey") + op.drop_constraint("service_charges_voucher_id_fkey", "incentives", type_="foreignkey") + op.create_foreign_key( + "fk_employee_benefit_journal_id_journals", "employee_benefit", "journals", ["journal_id"], ["id"], + ) + op.create_foreign_key( + "fk_employee_benefit_voucher_id_vouchers", "employee_benefit", "vouchers", ["voucher_id"], ["id"], + ) + op.drop_constraint( + "entities_salarydeductions_JournalID_fkey", "employee_benefit", type_="foreignkey", + ) + op.drop_constraint("salary_deductions_VoucherID_fkey", "employee_benefit", type_="foreignkey") - op.create_unique_constraint(op.f('uq_accounts_name'), 'accounts', ['name']) - op.drop_constraint('accounts_name_key', 'accounts', type_='unique') - op.create_unique_constraint(op.f('uq_auth_clients_code'), 'auth_clients', ['code']) - op.create_unique_constraint(op.f('uq_auth_clients_name'), 'auth_clients', ['name']) - op.drop_constraint('auth_clients_Code_key', 'auth_clients', type_='unique') - op.drop_constraint('auth_clients_Name_key', 'auth_clients', type_='unique') - op.create_unique_constraint(op.f('uq_auth_login_history_user_id'), 'auth_login_history', ['user_id', 'client_id', 'date']) - op.drop_constraint('auth_login_history_user_id_client_id_date_key', 'auth_login_history', type_='unique') - op.create_unique_constraint(op.f('uq_auth_permissions_name'), 'auth_permissions', ['name']) - op.drop_constraint('auth_roles_Name_key', 'auth_permissions', type_='unique') - op.create_unique_constraint(op.f('uq_auth_roles_name'), 'auth_roles', ['name']) - op.drop_constraint('auth_groups_Name_key', 'auth_roles', type_='unique') - op.create_unique_constraint(op.f('uq_auth_users_username'), 'auth_users', ['username']) - op.drop_constraint('auth_users_Name_key', 'auth_users', type_='unique') - op.create_unique_constraint(op.f('uq_cost_centres_name'), 'cost_centres', ['name']) - op.drop_constraint('entities_costcenters_Name_key', 'cost_centres', type_='unique') - op.drop_constraint('uq_employee_id_date', 'fingerprints', type_='unique') - op.create_index(op.f('ix_inventories_voucher_id'), 'inventories', ['voucher_id'], unique=False) - op.create_unique_constraint(op.f('uq_inventories_voucher_id'), 'inventories', ['voucher_id', 'batch_id']) - op.drop_index('ix_inventories_VoucherID', table_name='inventories') - op.create_index(op.f('ix_journals_voucher_id'), 'journals', ['voucher_id'], unique=False) - op.drop_index('ix_journals_VoucherID', table_name='journals') - op.create_unique_constraint(op.f('uq_product_groups_name'), 'product_groups', ['name']) - op.drop_constraint('entities_productgroups_Name_key', 'product_groups', type_='unique') - op.create_unique_constraint(op.f('uq_products_code'), 'products', ['code']) - op.create_unique_constraint(op.f('uq_products_name'), 'products', ['name', 'units']) - op.drop_constraint('products_Code_key', 'products', type_='unique') - op.drop_constraint('products_Name_Units_key', 'products', type_='unique') - op.create_unique_constraint(op.f('uq_recipe_items_recipe_id'), 'recipe_items', ['recipe_id', 'product_id']) - op.drop_constraint('recipe_items_recipe_id_product_id_key', 'recipe_items', type_='unique') - op.create_unique_constraint(op.f('uq_settings_name'), 'settings', ['name']) - op.drop_constraint('settings_Name_key', 'settings', type_='unique') - op.create_index(op.f('ix_vouchers_date'), 'vouchers', ['date'], unique=False) - op.create_foreign_key('fk_incentives_journal_id_journals', 'incentives', 'journals', ['journal_id'], ['id']) - op.create_foreign_key('fk_incentives_voucher_id_vouchers', 'incentives', 'vouchers', ['voucher_id'], ['id']) - op.drop_constraint('service_charges_journal_id_fkey', 'incentives', type_='foreignkey') - op.drop_constraint('service_charges_voucher_id_fkey', 'incentives', type_='foreignkey') - op.create_foreign_key('fk_employee_benefit_journal_id_journals', 'employee_benefit', 'journals', ['journal_id'], ['id']) - op.create_foreign_key('fk_employee_benefit_voucher_id_vouchers', 'employee_benefit', 'vouchers', ['voucher_id'], ['id']) - op.drop_constraint('entities_salarydeductions_JournalID_fkey', 'employee_benefit', type_='foreignkey') - op.drop_constraint('salary_deductions_VoucherID_fkey', 'employee_benefit', type_='foreignkey') - - permission = table('auth_permissions', column('id', postgresql.UUID()), column('name', sa.String)) - op.execute(permission.update().where(permission.c.name == op.inline_literal('Service Charge')).values({'name': op.inline_literal('Incentive')})) - op.execute(permission.update().where(permission.c.name == op.inline_literal('Salary Deduction')).values({'name': op.inline_literal('Employee Benefit')})) - account = table('accounts', column('name', sa.String)) - op.execute(account.update().where(account.c.name == op.inline_literal('Service Charges')).values({'name': op.inline_literal('Incentives')})) + permission = table("auth_permissions", column("id", postgresql.UUID()), column("name", sa.String)) + op.execute( + permission.update() + .where(permission.c.name == op.inline_literal("Service Charge")) + .values({"name": op.inline_literal("Incentive")}) + ) + op.execute( + permission.update() + .where(permission.c.name == op.inline_literal("Salary Deduction")) + .values({"name": op.inline_literal("Employee Benefit")}) + ) + account = table("accounts", column("name", sa.String)) + op.execute( + account.update() + .where(account.c.name == op.inline_literal("Service Charges")) + .values({"name": op.inline_literal("Incentives")}) + ) # Remove unneeded Payment and Receipt permissions - permission = table('auth_permissions', column('id', postgresql.UUID()), column('name', sa.String)) - role_permission = table('role_permissions', column('permission_id', postgresql.UUID()), column('role_id', postgresql.UUID())) + permission = table("auth_permissions", column("id", postgresql.UUID()), column("name", sa.String)) + role_permission = table( + "role_permissions", column("permission_id", postgresql.UUID()), column("role_id", postgresql.UUID()), + ) op.execute( role_permission.delete().where( - role_permission.c.permission_id.in_(select([permission.c.id], permission.c.name.in_(['Payment', 'Receipt']))) - ) - ) - op.execute( - permission.delete().where( - permission.c.name.in_(['Payment', 'Receipt']) + role_permission.c.permission_id.in_( + select([permission.c.id], permission.c.name.in_(["Payment", "Receipt"])) + ) ) ) + op.execute(permission.delete().where(permission.c.name.in_(["Payment", "Receipt"]))) ### end Alembic commands ### diff --git a/brewman/core/config.py b/brewman/core/config.py index 17c9d131..e7caa39b 100644 --- a/brewman/core/config.py +++ b/brewman/core/config.py @@ -37,7 +37,7 @@ class Settings(BaseSettings): class Config: case_sensitive = True - env_file = '.env' + env_file = ".env" load_dotenv() diff --git a/brewman/core/security.py b/brewman/core/security.py index 1410354e..c557b6b3 100644 --- a/brewman/core/security.py +++ b/brewman/core/security.py @@ -58,13 +58,7 @@ def create_access_token(*, data: dict, expires_delta: timedelta = None): def get_user(username: str, id_: str, locked_out: bool, scopes: List[str]) -> UserToken: - return UserToken( - id_=uuid.UUID(id_), - name=username, - locked_out=locked_out, - password="", - permissions=scopes, - ) + return UserToken(id_=uuid.UUID(id_), name=username, locked_out=locked_out, password="", permissions=scopes,) def authenticate_user( @@ -76,13 +70,7 @@ def authenticate_user( def client_allowed(user: UserModel, client_id: int, otp: Optional[int] = None, db: Session = None) -> (bool, int): client = db.query(Client).filter(Client.code == client_id).first() if client_id else None - allowed = "clients" in set( - [ - p.name.replace(" ", "-").lower() - for r in user.roles - for p in r.permissions - ] - ) + allowed = "clients" in set([p.name.replace(" ", "-").lower() for r in user.roles for p in r.permissions]) if allowed: return True, 0 elif client is None: @@ -98,9 +86,7 @@ def client_allowed(user: UserModel, client_id: int, otp: Optional[int] = None, d return False, client.code -async def get_current_user( - security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme), -) -> UserToken: +async def get_current_user(security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme),) -> UserToken: if security_scopes.scopes: authenticate_value = f'Bearer scope="{security_scopes.scope_str}"' else: diff --git a/brewman/core/session.py b/brewman/core/session.py index 201987f3..13abcd87 100644 --- a/brewman/core/session.py +++ b/brewman/core/session.py @@ -25,12 +25,8 @@ def get_finish_date(session): def set_period(start, finish, session): - session["start"] = ( - start if isinstance(start, str) else start.strftime("%d-%b-%Y") - ) - session["finish"] = ( - finish if isinstance(finish, str) else finish.strftime("%d-%b-%Y") - ) + session["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") def get_first_day(dt, d_years=0, d_months=0): diff --git a/brewman/db/init_db.py b/brewman/db/init_db.py index 4f52d64a..555e1466 100644 --- a/brewman/db/init_db.py +++ b/brewman/db/init_db.py @@ -18,8 +18,6 @@ def init_db(db: Session) -> None: user = crud.user.get_by_email(db, email=settings.FIRST_SUPERUSER) if not user: user_in = schemas.UserCreate( - email=settings.FIRST_SUPERUSER, - password=settings.FIRST_SUPERUSER_PASSWORD, - is_superuser=True, + email=settings.FIRST_SUPERUSER, password=settings.FIRST_SUPERUSER_PASSWORD, is_superuser=True, ) user = crud.user.create(db, obj_in=user_in) # noqa: F841 diff --git a/brewman/db/session.py b/brewman/db/session.py index 85d781f3..f16541f1 100644 --- a/brewman/db/session.py +++ b/brewman/db/session.py @@ -5,6 +5,6 @@ from sqlalchemy.orm import sessionmaker from brewman.core.config import settings logging.basicConfig() -logging.getLogger('sqlalchemy.engine').setLevel(settings.LOG_LEVEL) +logging.getLogger("sqlalchemy.engine").setLevel(settings.LOG_LEVEL) engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, pool_pre_ping=True) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) diff --git a/brewman/main.py b/brewman/main.py index 1b8f2f60..80de10c7 100644 --- a/brewman/main.py +++ b/brewman/main.py @@ -67,28 +67,16 @@ app.include_router(login.router, tags=["login"]) app.include_router(account.router, prefix="/api/accounts", tags=["accounts"]) app.include_router(account_types.router, prefix="/api/account-types", tags=["accounts"]) app.include_router(attendance.router, prefix="/api/attendance", tags=["attendance"]) -app.include_router( - attendance_types.router, prefix="/api/attendance-types", tags=["attendance"] -) -app.include_router( - employee_attendance.router, prefix="/api/employee-attendance", tags=["attendance"] -) -app.include_router( - employee_attendance.router, prefix="/api/employee-attendance", tags=["attendance"] -) -app.include_router( - attendance_report.router, prefix="/attendance-report", tags=["attendance"] -) +app.include_router(attendance_types.router, prefix="/api/attendance-types", tags=["attendance"]) +app.include_router(employee_attendance.router, prefix="/api/employee-attendance", tags=["attendance"]) +app.include_router(employee_attendance.router, prefix="/api/employee-attendance", tags=["attendance"]) +app.include_router(attendance_report.router, prefix="/attendance-report", tags=["attendance"]) -app.include_router( - cost_centre.router, prefix="/api/cost-centres", tags=["cost-centres"] -) +app.include_router(cost_centre.router, prefix="/api/cost-centres", tags=["cost-centres"]) app.include_router(employee.router, prefix="/api/employees", tags=["employees"]) app.include_router(fingerprint.router, prefix="/api/fingerprint", tags=["employees"]) app.include_router(product.router, prefix="/api/products", tags=["products"]) -app.include_router( - product_group.router, prefix="/api/product-groups", tags=["products"] -) +app.include_router(product_group.router, prefix="/api/product-groups", tags=["products"]) app.include_router(recipe.router, prefix="/api/recipes", tags=["products"]) app.include_router(client.router, prefix="/api/clients", tags=["clients"]) @@ -101,23 +89,13 @@ app.include_router(profit_loss.router, prefix="/api/profit-loss", tags=["reports app.include_router(closing_stock.router, prefix="/api/closing-stock", tags=["reports"]) app.include_router(cash_flow.router, prefix="/api/cash-flow", tags=["reports"]) app.include_router(daybook.router, prefix="/api/daybook", tags=["reports"]) -app.include_router( - net_transactions.router, prefix="/api/net-transactions", tags=["reports"] -) -app.include_router( - product_ledger.router, prefix="/api/product-ledger", tags=["reports"] -) -app.include_router( - purchase_entries.router, prefix="/api/purchase-entries", tags=["reports"] -) +app.include_router(net_transactions.router, prefix="/api/net-transactions", tags=["reports"]) +app.include_router(product_ledger.router, prefix="/api/product-ledger", tags=["reports"]) +app.include_router(purchase_entries.router, prefix="/api/purchase-entries", tags=["reports"]) app.include_router(purchases.router, prefix="/api/purchases", tags=["reports"]) -app.include_router( - raw_material_cost.router, prefix="/api/raw-material-cost", tags=["reports"] -) +app.include_router(raw_material_cost.router, prefix="/api/raw-material-cost", tags=["reports"]) app.include_router(reconcile.router, prefix="/api/reconcile", tags=["reports"]) -app.include_router( - stock_movement.router, prefix="/api/stock-movement", tags=["reports"] -) +app.include_router(stock_movement.router, prefix="/api/stock-movement", tags=["reports"]) app.include_router(trial_balance.router, prefix="/api/trial-balance", tags=["reports"]) app.include_router(unposted.router, prefix="/api/unposted", tags=["reports"]) @@ -127,20 +105,14 @@ app.include_router(journal.router, prefix="/api/journal", tags=["vouchers"]) app.include_router(journal.router, prefix="/api/payment", tags=["vouchers"]) app.include_router(journal.router, prefix="/api/receipt", tags=["vouchers"]) app.include_router(purchase.router, prefix="/api/purchase", tags=["vouchers"]) -app.include_router( - purchase_return.router, prefix="/api/purchase-return", tags=["vouchers"] -) +app.include_router(purchase_return.router, prefix="/api/purchase-return", tags=["vouchers"]) app.include_router(issue.router, prefix="/api/issue", tags=["vouchers"]) -app.include_router( - employee_benefit.router, prefix="/api/employee-benefit", tags=["vouchers"] -) +app.include_router(employee_benefit.router, prefix="/api/employee-benefit", tags=["vouchers"]) app.include_router(incentive.router, prefix="/api/incentive", tags=["vouchers"]) app.include_router(credit_salary.router, prefix="/api/credit-salary", tags=["vouchers"]) app.include_router(voucher.router, prefix="/api", tags=["vouchers"]) -app.include_router( - lock_information.router, prefix="/api/lock-information", tags=["settings"] -) +app.include_router(lock_information.router, prefix="/api/lock-information", tags=["settings"]) app.include_router(maintenance.router, prefix="/api/maintenance", tags=["settings"]) app.include_router(db_integrity.router, prefix="/api/db-integrity", tags=["management"]) diff --git a/brewman/models/__init__.py b/brewman/models/__init__.py index a2d6c410..feabb067 100644 --- a/brewman/models/__init__.py +++ b/brewman/models/__init__.py @@ -5,7 +5,7 @@ from .auth import ( User, LoginHistory, Role, - Permission + Permission, ) from .master import ( Product, diff --git a/brewman/models/auth.py b/brewman/models/auth.py index d74e91e3..f9180574 100644 --- a/brewman/models/auth.py +++ b/brewman/models/auth.py @@ -29,30 +29,20 @@ class Client(Base): login_history = relationship("LoginHistory", backref="client") def __init__( - self, - code=None, - name=None, - enabled=False, - otp=None, - creation_date=None, - id_=None, + self, code=None, name=None, enabled=False, otp=None, creation_date=None, id_=None, ): self.code = code self.name = name self.enabled = enabled self.otp = otp - self.creation_date = ( - datetime.utcnow() if creation_date is None else creation_date - ) + self.creation_date = datetime.utcnow() if creation_date is None else creation_date self.id = id_ @classmethod def create(cls, dbsession): client_code = random.randint(1000, 9999) otp = random.randint(1000, 9999) - name = "".join( - random.choice(string.ascii_uppercase + string.digits) for x in range(6) - ) + name = "".join(random.choice(string.ascii_uppercase + string.digits) for x in range(6)) client = Client(client_code, name, False, otp) dbsession.add(client) return client @@ -123,9 +113,7 @@ class LoginHistory(Base): __table_args__ = (UniqueConstraint("user_id", "client_id", "date"),) id = Column("login_history_id", GUID(), primary_key=True, default=uuid.uuid4) user_id = Column("user_id", GUID(), ForeignKey("auth_users.id"), nullable=False) - client_id = Column( - "client_id", GUID(), ForeignKey("auth_clients.client_id"), nullable=False - ) + client_id = Column("client_id", GUID(), ForeignKey("auth_clients.client_id"), nullable=False) date = Column("date", DateTime(timezone=True), nullable=False) def __init__(self, user_id=None, client_id=None, date=None, id_=None): diff --git a/brewman/models/master.py b/brewman/models/master.py index 0dbb3131..61ba86c0 100644 --- a/brewman/models/master.py +++ b/brewman/models/master.py @@ -31,9 +31,7 @@ class Product(Base): fraction = Column("fraction", Numeric, nullable=False) fraction_units = Column("fraction_units", Unicode(255), nullable=False) product_yield = Column("product_yield", Numeric, nullable=False) - product_group_id = Column( - "product_group_id", GUID(), ForeignKey("product_groups.id"), nullable=False, - ) + product_group_id = Column("product_group_id", GUID(), ForeignKey("product_groups.id"), nullable=False,) account_id = Column("account_id", GUID(), ForeignKey("accounts.id"), nullable=False) price = Column("cost_price", Numeric, nullable=False) sale_price = Column("sale_price", Numeric, nullable=False) @@ -45,9 +43,7 @@ class Product(Base): batches = relationship("Batch", backref="product") inventories = relationship("Inventory", backref="product") recipes = relationship("Recipe", backref="product") - account = relationship( - "Account", primaryjoin="Account.id==Product.account_id", backref="products" - ) + account = relationship("Account", primaryjoin="Account.id==Product.account_id", backref="products") def __init__( self, @@ -178,9 +174,7 @@ class RecipeItem(Base): product = relationship("Product") - def __init__( - self, recipe_id=None, product_id=None, quantity=None, price=None, id=None - ): + def __init__(self, recipe_id=None, product_id=None, quantity=None, price=None, id=None): self.recipe_id = recipe_id self.product_id = product_id self.quantity = quantity @@ -261,9 +255,7 @@ class AccountBase(Base): is_starred = Column("is_starred", Boolean, nullable=False) is_active = Column("is_active", Boolean, nullable=False) is_reconcilable = Column("is_reconcilable", Boolean, nullable=False) - cost_centre_id = Column( - "cost_centre_id", GUID(), ForeignKey("cost_centres.id"), nullable=False - ) + cost_centre_id = Column("cost_centre_id", GUID(), ForeignKey("cost_centres.id"), nullable=False) is_fixture = Column("is_fixture", Boolean, nullable=False) __mapper_args__ = {"polymorphic_on": account_type} @@ -317,11 +309,7 @@ class AccountBase(Base): return query_.order_by(cls.name) def create(self, dbsession): - code = ( - dbsession.query(func.max(AccountBase.code)) - .filter(AccountBase.type == self.type) - .one()[0] - ) + code = dbsession.query(func.max(AccountBase.code)).filter(AccountBase.type == self.type).one()[0] if code is None: self.code = 1 else: @@ -343,11 +331,7 @@ class AccountBase(Base): @classmethod def get_code(cls, type, dbsession): - code = ( - dbsession.query(func.max(AccountBase.code)) - .filter(AccountBase.type == type) - .one()[0] - ) + code = dbsession.query(func.max(AccountBase.code)).filter(AccountBase.type == type).one()[0] return 1 if code is None else code + 1 @classmethod @@ -402,12 +386,8 @@ class Employee(AccountBase): joining_date = Column("joining_date", Date, nullable=False) leaving_date = Column("leaving_date", Date, nullable=True) - attendances = relationship( - "Attendance", backref="employee", cascade=None, cascade_backrefs=False - ) - fingerprints = relationship( - "Fingerprint", backref="employee", cascade=None, cascade_backrefs=False - ) + attendances = relationship("Attendance", backref="employee", cascade=None, cascade_backrefs=False) + fingerprints = relationship("Fingerprint", backref="employee", cascade=None, cascade_backrefs=False) def __init__( self, @@ -438,11 +418,7 @@ class Employee(AccountBase): ) def create(self, dbsession): - code = ( - dbsession.query(func.max(AccountBase.code)) - .filter(AccountBase.type == self.type) - .one()[0] - ) + code = dbsession.query(func.max(AccountBase.code)).filter(AccountBase.type == self.type).one()[0] if code is None: self.code = 1 else: @@ -505,14 +481,7 @@ class AttendanceType: class AccountType: def __init__( - self, - id, - name, - balance_sheet=None, - debit=None, - cash_flow_classification=None, - order=None, - show_in_list=None, + self, id, name, balance_sheet=None, debit=None, cash_flow_classification=None, order=None, show_in_list=None, ): self.id = id self.name = name diff --git a/brewman/models/operations.py b/brewman/models/operations.py index e826b391..a4149ca1 100644 --- a/brewman/models/operations.py +++ b/brewman/models/operations.py @@ -24,8 +24,7 @@ def validate(voucher): def check_batch_insert(voucher): if voucher.type == 9: raise HTTPException( - status_code=status.HTTP_410_GONE, - detail="Verification Vouchers have been disabled", + status_code=status.HTTP_410_GONE, detail="Verification Vouchers have been disabled", ) if voucher.type == 6: # Purchase Return @@ -59,10 +58,7 @@ def check_batch_insert(voucher): def issue_new(voucher): - consuming = filter( - lambda x: x.cost_centre_id == CostCentre.cost_centre_purchase(), - voucher.journals, - ) + consuming = filter(lambda x: x.cost_centre_id == CostCentre.cost_centre_purchase(), voucher.journals,) if not len(consuming): consuming = False elif consuming[0].debit == 1: @@ -83,10 +79,7 @@ def issue_new(voucher): def issue_update(voucher): - consuming = filter( - lambda x: x.cost_centre_id == CostCentre.cost_centre_purchase(), - voucher.journals, - ) + consuming = filter(lambda x: x.cost_centre_id == CostCentre.cost_centre_purchase(), voucher.journals,) if not len(consuming): consuming = False elif consuming[0].debit == 1: @@ -131,4 +124,4 @@ def batch_valid(voucher): def is_date_allowed(voucher): - pass \ No newline at end of file + pass diff --git a/brewman/models/voucher.py b/brewman/models/voucher.py index 9a73d8bc..a3f488a8 100644 --- a/brewman/models/voucher.py +++ b/brewman/models/voucher.py @@ -77,35 +77,19 @@ class Voucher(Base): poster_id = Column("poster_id", GUID(), ForeignKey("auth_users.id")) user = relationship("User", primaryjoin="User.id==Voucher.user_id", cascade=None) - poster = relationship( - "User", primaryjoin="User.id==Voucher.poster_id", cascade=None - ) + poster = relationship("User", primaryjoin="User.id==Voucher.poster_id", cascade=None) journals = relationship( - "Journal", - back_populates="voucher", - cascade="delete, delete-orphan", - cascade_backrefs=False, + "Journal", back_populates="voucher", cascade="delete, delete-orphan", cascade_backrefs=False, ) inventories = relationship( - "Inventory", - back_populates="voucher", - cascade="delete, delete-orphan", - cascade_backrefs=False, + "Inventory", back_populates="voucher", cascade="delete, delete-orphan", cascade_backrefs=False, ) employee_benefits = relationship( - "EmployeeBenefit", - backref="voucher", - cascade="delete, delete-orphan", - cascade_backrefs=False, - ) - incentives = relationship( - "Incentive", - backref="voucher", - cascade="delete, delete-orphan", - cascade_backrefs=False, + "EmployeeBenefit", backref="voucher", cascade="delete, delete-orphan", cascade_backrefs=False, ) + incentives = relationship("Incentive", backref="voucher", cascade="delete, delete-orphan", cascade_backrefs=False,) def _get_type(self): return self._type @@ -155,13 +139,9 @@ class Journal(Base): id = Column("id", GUID(), primary_key=True, default=uuid.uuid4) debit = Column("debit", Integer) amount = Column("amount", Numeric) - voucher_id = Column( - "voucher_id", GUID(), ForeignKey("vouchers.id"), nullable=False, index=True - ) + voucher_id = Column("voucher_id", GUID(), ForeignKey("vouchers.id"), nullable=False, index=True) account_id = Column("account_id", GUID(), ForeignKey("accounts.id"), nullable=False) - cost_centre_id = Column( - "cost_centre_id", GUID(), ForeignKey("cost_centres.id"), nullable=False - ) + cost_centre_id = Column("cost_centre_id", GUID(), ForeignKey("cost_centres.id"), nullable=False) voucher = relationship("Voucher", back_populates="journals") account = relationship("AccountBase", back_populates="journals") @@ -175,13 +155,7 @@ class Journal(Base): return self.name def __init__( - self, - id_=None, - debit=None, - amount=None, - voucher_id=None, - account_id=None, - cost_centre_id=None, + self, id_=None, debit=None, amount=None, voucher_id=None, account_id=None, cost_centre_id=None, ): self.id = id_ self.debit = debit @@ -204,10 +178,7 @@ class EmployeeBenefit(Base): pf_er = Column("pf_employer", Integer) journal = relationship( - Journal, - backref=backref("employee_benefit", uselist=False), - cascade=None, - cascade_backrefs=False, + Journal, backref=backref("employee_benefit", uselist=False), cascade=None, cascade_backrefs=False, ) def __init__( @@ -244,21 +215,10 @@ class Incentive(Base): days_worked = Column("days_worked", Numeric(precision=5, scale=1), nullable=False) points = Column("points", Numeric(precision=5, scale=2), nullable=False) - journal = relationship( - Journal, - backref=backref("incentive", uselist=False), - cascade=None, - cascade_backrefs=False, - ) + journal = relationship(Journal, backref=backref("incentive", uselist=False), cascade=None, cascade_backrefs=False,) def __init__( - self, - id_=None, - voucher_id=None, - journal_id=None, - journal=None, - days_worked=None, - points=None, + self, id_=None, voucher_id=None, journal_id=None, journal=None, days_worked=None, points=None, ): self.id = id_ self.voucher_id = voucher_id @@ -273,9 +233,7 @@ class Inventory(Base): __tablename__ = "inventories" __table_args__ = (UniqueConstraint("voucher_id", "batch_id"),) id = Column("id", GUID(), primary_key=True, default=uuid.uuid4) - voucher_id = Column( - "voucher_id", GUID(), ForeignKey("vouchers.id"), nullable=False, index=True - ) + voucher_id = Column("voucher_id", GUID(), ForeignKey("vouchers.id"), nullable=False, index=True) product_id = Column("product_id", GUID(), ForeignKey("products.id"), nullable=False) batch_id = Column("batch_id", GUID(), ForeignKey("batches.id"), nullable=False) quantity = Column("quantity", Numeric) @@ -327,19 +285,10 @@ class Batch(Base): tax = Column("tax", Numeric) discount = Column("discount", Numeric) - inventories = relationship( - "Inventory", backref="batch", cascade=None, cascade_backrefs=False - ) + inventories = relationship("Inventory", backref="batch", cascade=None, cascade_backrefs=False) def __init__( - self, - name=None, - product_id=None, - quantity_remaining=None, - rate=None, - tax=None, - discount=None, - product=None, + self, name=None, product_id=None, quantity_remaining=None, rate=None, tax=None, discount=None, product=None, ): self.name = name self.product_id = product_id @@ -352,9 +301,7 @@ class Batch(Base): self.product = product def amount(self): - return ( - self.quantity_remaining * self.rate * (1 + self.tax) * (1 - self.discount) - ) + return self.quantity_remaining * self.rate * (1 + self.tax) * (1 - self.discount) @classmethod def list(cls, name, include_nil, date, db: Session): @@ -445,13 +392,7 @@ class DbImage(Base): creation_date = Column("creation_date", DateTime(timezone=True), nullable=False) def __init__( - self, - resource_id=None, - resource_type=None, - image=None, - thumbnail=None, - creation_date=None, - id_=None, + self, resource_id=None, resource_type=None, image=None, thumbnail=None, creation_date=None, id_=None, ): self.resource_id = resource_id self.resource_type = resource_type diff --git a/brewman/routers/__init__.py b/brewman/routers/__init__.py index 0fd8e94b..79b4aff5 100644 --- a/brewman/routers/__init__.py +++ b/brewman/routers/__init__.py @@ -40,9 +40,7 @@ def get_lock_info(db: Session) -> (Optional[date], Optional[date]): def to_uuid(value): - p = re.compile( - "^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$" - ) + p = re.compile("^[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$") return uuid.UUID(value) if p.match(value) else None diff --git a/brewman/routers/account.py b/brewman/routers/account.py index 0d23f4cd..aff83a5c 100644 --- a/brewman/routers/account.py +++ b/brewman/routers/account.py @@ -29,9 +29,7 @@ def get_db() -> Session: @router.post("", response_model=schemas.Account) def save( - data: schemas.AccountIn, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["accounts"]), + data: schemas.AccountIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["accounts"]), ): try: item = Account( @@ -47,14 +45,12 @@ def save( except SQLAlchemyError as e: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=str(e), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e), ) except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -69,8 +65,7 @@ def update( item: Account = db.query(Account).filter(Account.id == id_).first() if item.is_fixture: raise HTTPException( - status_code=status.HTTP_423_LOCKED, - detail=f"{item.name} is a fixture and cannot be edited or deleted.", + status_code=status.HTTP_423_LOCKED, detail=f"{item.name} is a fixture and cannot be edited or deleted.", ) if not item.type == data.type: item.code = Account.get_code(data.type, db) @@ -90,16 +85,13 @@ def update( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @router.delete("/{id}") def delete( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["accounts"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["accounts"]), ): account: Account = db.query(Account).filter(Account.id == id_).first() can_delete, reason = account.can_delete("advanced-delete" in user.permissions) @@ -110,14 +102,13 @@ def delete( else: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Cannot delete account because {reason}", + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Cannot delete account because {reason}", ) @router.get("") def show_blank( - db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["accounts"]) + db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["accounts"]), ): return account_info(None) @@ -161,10 +152,7 @@ async def show_term( @router.get("/{id_}/balance") async def show_balance( - id_: uuid.UUID, - d: str = None, - db: Session = Depends(get_db), - user: UserToken = Depends(get_user), + id_: uuid.UUID, d: str = None, db: Session = Depends(get_db), user: UserToken = Depends(get_user), ): date = None if d is None or d == "" else datetime.strptime(d, "%d-%b-%Y") return {"date": balance(id_, date, db), "total": balance(id_, None, db)} @@ -172,9 +160,7 @@ async def show_balance( @router.get("/{id_}") def show_id( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["accounts"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["accounts"]), ): item: Account = db.query(Account).filter(Account.id == id_).first() return account_info(item) @@ -189,11 +175,7 @@ def balance(id_: uuid.UUID, date, db: Session): if date is not None: bal = bal.filter(Voucher.date <= date) - bal = ( - bal.filter(Voucher.type != VoucherType.by_name("Issue").id) - .filter(Journal.account_id == id_) - .scalar() - ) + bal = bal.filter(Voucher.type != VoucherType.by_name("Issue").id).filter(Journal.account_id == id_).scalar() return 0 if bal is None else bal @@ -217,17 +199,12 @@ def account_info(item: Optional[Account]): "isReconcilable": item.is_reconcilable, "isStarred": item.is_starred, "isFixture": item.is_fixture, - "costCentre": { - "id": item.cost_centre_id, - "name": item.cost_centre.name, - }, + "costCentre": {"id": item.cost_centre_id, "name": item.cost_centre.name,}, } def delete_with_data(account: Account, db: Session): - suspense_account = ( - db.query(Account).filter(Account.id == Account.suspense()).first() - ) + suspense_account = db.query(Account).filter(Account.id == Account.suspense()).first() query: List[Voucher] = ( db.query(Voucher) .options(joinedload_all(Voucher.journals, Journal.account, innerjoin=True)) @@ -249,13 +226,9 @@ def delete_with_data(account: Account, db: Session): else: if sus_jnl is None: acc_jnl.account = suspense_account - voucher.narration += ( - f"\nSuspense \u20B9{acc_jnl.amount:,.2f} is {account.name}" - ) + voucher.narration += f"\nSuspense \u20B9{acc_jnl.amount:,.2f} is {account.name}" else: - amount = (sus_jnl.debit * sus_jnl.amount) + ( - acc_jnl.debit * acc_jnl.amount - ) + amount = (sus_jnl.debit * sus_jnl.amount) + (acc_jnl.debit * acc_jnl.amount) db.delete(acc_jnl) if amount == 0: db.delete(sus_jnl) @@ -263,9 +236,6 @@ def delete_with_data(account: Account, db: Session): sus_jnl.amount = abs(amount) sus_jnl.debit = -1 if amount < 0 else 1 voucher.narration += f"\nDeleted \u20B9{acc_jnl.amount * acc_jnl.debit:,.2f} of {account.name}" - if voucher.type in ( - VoucherType.by_name("Payment").id, - VoucherType.by_name("Receipt").id, - ): + if voucher.type in (VoucherType.by_name("Payment").id, VoucherType.by_name("Receipt").id,): voucher.type = VoucherType.by_name("Journal") db.delete(account) diff --git a/brewman/routers/account_types.py b/brewman/routers/account_types.py index a065e823..940ba529 100644 --- a/brewman/routers/account_types.py +++ b/brewman/routers/account_types.py @@ -11,7 +11,4 @@ router = APIRouter() @router.get("", response_model=List[schemas.AccountType]) def account_type_list(user: UserToken = Depends(get_user)): - return [ - schemas.AccountType(id=item.id, name=item.name) - for item in AccountType.list() - ] + return [schemas.AccountType(id=item.id, name=item.name) for item in AccountType.list()] diff --git a/brewman/routers/attendance.py b/brewman/routers/attendance.py index b6846926..f1f94bfe 100644 --- a/brewman/routers/attendance.py +++ b/brewman/routers/attendance.py @@ -27,9 +27,7 @@ def get_db() -> Session: @router.get("", response_model=schemas.Attendance) -def attendance_blank( - request: Request, user: UserToken = Security(get_user, scopes=["attendance"]) -): +def attendance_blank(request: Request, user: UserToken = Security(get_user, scopes=["attendance"])): return {"date": get_date(request.session), "body": []} @@ -97,10 +95,7 @@ def save( for item in data.body: if item.attendance_type.id_ != 0: attendance = Attendance( - employee_id=item.id_, - date=att_date, - attendance_type=item.attendance_type.id_, - user_id=user.id_, + employee_id=item.id_, date=att_date, attendance_type=item.attendance_type.id_, user_id=user.id_, ) attendance.create(db) db.commit() @@ -113,8 +108,7 @@ def save( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) diff --git a/brewman/routers/attendance_report.py b/brewman/routers/attendance_report.py index 2e7db516..cb70742c 100644 --- a/brewman/routers/attendance_report.py +++ b/brewman/routers/attendance_report.py @@ -33,14 +33,9 @@ def get_report( try: output = io.StringIO() attendance_record( - datetime.strptime(s, "%d-%b-%Y"), - datetime.strptime(f, "%d-%b-%Y"), - output, - db, + datetime.strptime(s, "%d-%b-%Y"), datetime.strptime(f, "%d-%b-%Y"), output, db, ) - headers = { - "Content-Disposition": "attachment; filename = 'attendance-record.csv'" - } + headers = {"Content-Disposition": "attachment; filename = 'attendance-record.csv'"} output.seek(0) return StreamingResponse(output, media_type="text/csv", headers=headers) finally: diff --git a/brewman/routers/auth/client.py b/brewman/routers/auth/client.py index 41c5cb05..ad009bff 100644 --- a/brewman/routers/auth/client.py +++ b/brewman/routers/auth/client.py @@ -47,16 +47,13 @@ def update( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @router.delete("/{id_}") def delete( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["clients"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["clients"]), ): try: item: Client = db.query(Client).filter(Client.id == id_).first() @@ -72,30 +69,21 @@ def delete( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @router.get("/list") async def show_list( - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["clients"]), + db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["clients"]), ): list_ = db.query(Client).order_by(Client.name).all() clients = [] for item in list_: last_login = ( - db.query(LoginHistory) - .filter(LoginHistory.client_id == item.id) - .order_by(desc(LoginHistory.date)) - .first() - ) - last_login = ( - "Never" - if last_login is None - else last_login.date.strftime("%d-%b-%Y %H:%M") + db.query(LoginHistory).filter(LoginHistory.client_id == item.id).order_by(desc(LoginHistory.date)).first() ) + last_login = "Never" if last_login is None else last_login.date.strftime("%d-%b-%Y %H:%M") clients.append( { "id": item.id, @@ -112,9 +100,7 @@ async def show_list( @router.get("/{id_}") def show_id( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["clients"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["clients"]), ): item: Client = db.query(Client).filter(Client.id == id_).first() return { diff --git a/brewman/routers/auth/role.py b/brewman/routers/auth/role.py index 0e8c6d5d..e8c152aa 100644 --- a/brewman/routers/auth/role.py +++ b/brewman/routers/auth/role.py @@ -26,9 +26,7 @@ def get_db(): @router.post("", response_model=schemas.Role) def save( - data: schemas.RoleIn, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["users"]), + data: schemas.RoleIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]), ): try: item = Role(data.name) @@ -44,8 +42,7 @@ def save( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -70,8 +67,7 @@ def update( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -80,59 +76,48 @@ def add_permissions(role: Role, permissions: List[schemas.PermissionItem], db): gp = [p for p in role.permissions if p.id == permission.id_] gp = None if len(gp) == 0 else gp[0] if permission.enabled and gp is None: - role.permissions.append( - db.query(Permission).filter(Permission.id == permission.id_).one() - ) + role.permissions.append(db.query(Permission).filter(Permission.id == permission.id_).one()) elif not permission.enabled and gp: role.permissions.remove(gp) @router.delete("/{id_}") def delete( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["users"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]), ): try: item: Role = db.query(Role).filter(Role.id == id_).first() if item is None: raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="Role not found", + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Role not found", ) else: raise HTTPException( - status_code=status.HTTP_501_NOT_IMPLEMENTED, - detail="Role deletion not implemented", + status_code=status.HTTP_501_NOT_IMPLEMENTED, detail="Role deletion not implemented", ) except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @router.get("") def show_blank( - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["users"]), + db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]), ): return role_info(None, db) @router.get("/list", response_model=List[schemas.RoleList]) async def show_list( - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["users"]), + db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]), ): return [ { "id": item.id, "name": item.name, - "permissions": [ - p.name for p in sorted(item.permissions, key=lambda p: p.name) - ], + "permissions": [p.name for p in sorted(item.permissions, key=lambda p: p.name)], } for item in db.query(Role).order_by(Role.name).all() ] @@ -140,9 +125,7 @@ async def show_list( @router.get("/{id_}", response_model=schemas.Role) def show_id( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["users"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]), ): item: Role = db.query(Role).filter(Role.id == id_).first() return role_info(item, db) @@ -162,11 +145,7 @@ def role_info(item: Optional[Role], db): "id": item.id, "name": item.name, "permissions": [ - { - "id": p.id, - "name": p.name, - "enabled": True if p in item.permissions else False, - } + {"id": p.id, "name": p.name, "enabled": True if p in item.permissions else False,} for p in db.query(Permission).order_by(Permission.name).all() ], } diff --git a/brewman/routers/auth/user.py b/brewman/routers/auth/user.py index 3fafa64b..89d8f37b 100644 --- a/brewman/routers/auth/user.py +++ b/brewman/routers/auth/user.py @@ -26,9 +26,7 @@ def get_db(): @router.post("", response_model=schemas.User) def save( - data: schemas.UserIn, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["users"]), + data: schemas.UserIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]), ): try: item = User(name=data.name, password=data.password, locked_out=data.locked_out) @@ -44,8 +42,7 @@ def save( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -59,9 +56,7 @@ def show_me( @router.put("/me", response_model=schemas.User) def update_me( - data: schemas.UserIn, - db: Session = Depends(get_db), - user: UserToken = Depends(get_user), + data: schemas.UserIn, db: Session = Depends(get_db), user: UserToken = Depends(get_user), ): try: item: User = db.query(User).filter(User.id == user.id_).first() @@ -81,8 +76,7 @@ def update_me( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -110,8 +104,7 @@ def update( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -127,42 +120,35 @@ def add_roles(user: User, roles: List[schemas.RoleItem], db: Session): @router.delete("/{id_}") def delete( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["users"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]), ): try: item: User = db.query(User).filter(User.id == id_).first() if item is None: raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="User not found", + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="User not found", ) else: raise HTTPException( - status_code=status.HTTP_501_NOT_IMPLEMENTED, - detail="User deletion not implemented", + status_code=status.HTTP_501_NOT_IMPLEMENTED, detail="User deletion not implemented", ) except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @router.get("") def show_blank( - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["users"]), + db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]), ): return user_info(None, db, user) @router.get("/list", response_model=List[schemas.UserList]) async def show_list( - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["users"]), + db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]), ): return [ { @@ -176,20 +162,13 @@ async def show_list( @router.get("/active") -async def show_active( - db: Session = Depends(get_db), user: UserToken = Depends(get_user) -): - return [ - {"name": item.name} - for item in db.query(User).filter(User.locked_out == False).order_by(User.name) - ] +async def show_active(db: Session = Depends(get_db), user: UserToken = Depends(get_user)): + return [{"name": item.name} for item in db.query(User).filter(User.locked_out == False).order_by(User.name)] @router.get("/{id_}", response_model=schemas.User) def show_id( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["users"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]), ): item = db.query(User).filter(User.id == id_).first() return user_info(item, db, user) @@ -200,10 +179,7 @@ def user_info(item: Optional[User], db: Session, user: UserToken): return { "name": "", "lockedOut": False, - "roles": [ - {"id": r.id, "name": r.name, "enabled": False} - for r in db.query(Role).order_by(Role.name).all() - ], + "roles": [{"id": r.id, "name": r.name, "enabled": False} for r in db.query(Role).order_by(Role.name).all()], } else: return { @@ -212,11 +188,7 @@ def user_info(item: Optional[User], db: Session, user: UserToken): "password": "", "lockedOut": item.locked_out, "roles": [ - { - "id": r.id, - "name": r.name, - "enabled": True if r in item.roles else False, - } + {"id": r.id, "name": r.name, "enabled": True if r in item.roles else False,} for r in db.query(Role).order_by(Role.name).all() ] if "advanced-delete" in user.permissions diff --git a/brewman/routers/batch.py b/brewman/routers/batch.py index 2b87a5bb..1774963c 100644 --- a/brewman/routers/batch.py +++ b/brewman/routers/batch.py @@ -22,18 +22,12 @@ def get_db() -> Session: @router.get("") def batch_term( - q: str, - c: int = None, - d: str = None, - db: Session = Depends(get_db), - current_user: UserToken = Depends(get_user), + q: str, c: int = None, d: str = None, db: Session = Depends(get_db), current_user: UserToken = Depends(get_user), ): filter_ = q if q is not None and q.strip() != "" else None date = None if not d else datetime.datetime.strptime(d, "%d-%b-%Y") list_ = [] - for index, item in enumerate( - Batch.list(filter_, include_nil=False, date=date, dbsession=db) - ): + for index, item in enumerate(Batch.list(filter_, include_nil=False, date=date, dbsession=db)): text = f"{item.product.name} ({item.product.units}) {item.quantity_remaining:.2f}@{item.rate:.2f} from {item.name.strftime('%d-%b-%Y')}" list_.append( { @@ -43,11 +37,7 @@ def batch_term( "rate": item.rate, "tax": item.tax, "discount": item.discount, - "product": { - "id": item.product.id, - "name": item.product.name, - "units": item.product.units, - }, + "product": {"id": item.product.id, "name": item.product.name, "units": item.product.units,}, } ) if c is not None and index == c - 1: diff --git a/brewman/routers/cost_centre.py b/brewman/routers/cost_centre.py index 090b1789..27d5603d 100644 --- a/brewman/routers/cost_centre.py +++ b/brewman/routers/cost_centre.py @@ -43,8 +43,7 @@ def save( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -59,8 +58,7 @@ def update( item = db.query(CostCentre).filter(CostCentre.id == id_).first() if item.is_fixture: raise HTTPException( - status_code=status.HTTP_423_LOCKED, - detail=f"{item.name} is a fixture and cannot be edited or deleted.", + status_code=status.HTTP_423_LOCKED, detail=f"{item.name} is a fixture and cannot be edited or deleted.", ) item.name = data.name db.commit() @@ -73,16 +71,13 @@ def update( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @router.delete("/{id_}") def delete( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["cost-centres"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["cost-centres"]), ): try: item = db.query(CostCentre).filter(CostCentre.id == id_).first() @@ -93,26 +88,22 @@ def delete( ) elif item.is_fixture: raise HTTPException( - status_code=status.HTTP_423_LOCKED, - detail=f"{item.name} is a fixture and cannot be edited or deleted.", + status_code=status.HTTP_423_LOCKED, detail=f"{item.name} is a fixture and cannot be edited or deleted.", ) else: raise HTTPException( - status_code=status.HTTP_501_NOT_IMPLEMENTED, - detail="Cost Centre deletion not implemented", + status_code=status.HTTP_501_NOT_IMPLEMENTED, detail="Cost Centre deletion not implemented", ) except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @router.get("") def show_blank( - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["cost-centres"]), + db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["cost-centres"]), ): return cost_centre_info(None) @@ -127,9 +118,7 @@ async def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get @router.get("/{id_}", response_model=schemas.CostCentre) def show_id( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["cost-centres"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["cost-centres"]), ): item = db.query(CostCentre).filter(CostCentre.id == id_).first() return cost_centre_info(item) diff --git a/brewman/routers/credit_salary.py b/brewman/routers/credit_salary.py index 3b52ec55..dca18f5c 100644 --- a/brewman/routers/credit_salary.py +++ b/brewman/routers/credit_salary.py @@ -77,25 +77,12 @@ def salary_journals(start_date: date, finish_date: date, db: Session): if att != 0: amount += att journals.append( - Journal( - amount=att, - debit=-1, - account_id=employee.id, - cost_centre_id=employee.cost_centre_id, - ) + Journal(amount=att, debit=-1, account_id=employee.id, cost_centre_id=employee.cost_centre_id,) ) salary = db.query(Account).filter(Account.id == Account.salary_id()).first() if amount == 0: raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="No salaries to credit", + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="No salaries to credit", ) - journals.append( - Journal( - amount=amount, - debit=1, - account_id=salary.id, - cost_centre_id=salary.cost_centre_id, - ) - ) + journals.append(Journal(amount=amount, debit=1, account_id=salary.id, cost_centre_id=salary.cost_centre_id,)) return journals diff --git a/brewman/routers/db_image.py b/brewman/routers/db_image.py index 7fce33e0..05f28e12 100644 --- a/brewman/routers/db_image.py +++ b/brewman/routers/db_image.py @@ -25,11 +25,7 @@ def get_db() -> Session: @router.get("/{id_}/{type_}") -def db_image( - id_: uuid.UUID, - type_: str, - db: Session = Depends(get_db) -): +def db_image(id_: uuid.UUID, type_: str, db: Session = Depends(get_db)): item = db.query(DbImage).filter(DbImage.id == id_).first() if type_ == "thumbnail": item = BytesIO(item.thumbnail) @@ -45,7 +41,9 @@ def save_files(voucher_id: uuid.UUID, i: List[bytes], t: List[bytes], db: Sessio db.add(DbImage(voucher_id, "voucher", i[index], t[index])) -def update_files(voucher_id: uuid.UUID, data: List[output.ImageUpload], i: List[bytes], t: List[bytes], db: Session): +def update_files( + voucher_id: uuid.UUID, data: List[output.ImageUpload], i: List[bytes], t: List[bytes], db: Session, +): i = i or [] t = t or [] old = [f.id_ for f in data if f.id_] diff --git a/brewman/routers/db_integrity.py b/brewman/routers/db_integrity.py index e5bfd978..f66b13c3 100644 --- a/brewman/routers/db_integrity.py +++ b/brewman/routers/db_integrity.py @@ -38,18 +38,13 @@ def post_check_db(db: Session = Depends(get_db), user: UserToken = Security(get_ def get_duplicate_attendances(db): sub_query = ( db.query( - over( - distinct(func.first_value(Attendance.id)), - partition_by=[Attendance.employee_id, Attendance.date], - ) + over(distinct(func.first_value(Attendance.id)), partition_by=[Attendance.employee_id, Attendance.date],) ) .filter(Attendance.is_valid == True) .subquery() ) query = ( - db.query(func.count(Attendance.id)) - .filter(~Attendance.id.in_(sub_query)) - .filter(Attendance.is_valid == True) + db.query(func.count(Attendance.id)).filter(~Attendance.id.in_(sub_query)).filter(Attendance.is_valid == True) ) return query.scalar() @@ -66,6 +61,4 @@ def fix_duplicate_attendances(db): .filter(Attendance.is_valid == True) .subquery() ) - db.query(Attendance).filter(~Attendance.id.in_(sub)).filter( - Attendance.is_valid == True - ).delete(False) + db.query(Attendance).filter(~Attendance.id.in_(sub)).filter(Attendance.is_valid == True).delete(False) diff --git a/brewman/routers/employee.py b/brewman/routers/employee.py index 27a48081..2113593d 100644 --- a/brewman/routers/employee.py +++ b/brewman/routers/employee.py @@ -28,9 +28,7 @@ def get_db(): @router.post("", response_model=schemas.Employee) def save( - data: schemas.EmployeeIn, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["employees"]), + data: schemas.EmployeeIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["employees"]), ): try: item = Employee( @@ -54,8 +52,7 @@ def save( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -70,8 +67,7 @@ def update( item: Employee = db.query(Employee).filter(Employee.id == id_).first() if item.is_fixture: raise HTTPException( - status_code=status.HTTP_423_LOCKED, - detail=f"{item.name} is a fixture and cannot be edited or deleted.", + status_code=status.HTTP_423_LOCKED, detail=f"{item.name} is a fixture and cannot be edited or deleted.", ) item.name = data.name item.cost_centre_id = data.cost_centre.id_ @@ -92,16 +88,13 @@ def update( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @router.delete("/{id_}") def delete( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["employees"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["employees"]), ): employee: Employee = db.query(Employee).filter(Employee.id == id_).first() can_delete, reason = employee.can_delete("advanced-delete" in user.permissions) @@ -112,15 +105,13 @@ def delete( else: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Cannot delete account because {reason}", + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Cannot delete account because {reason}", ) @router.get("") def show_blank( - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["employees"]), + db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["employees"]), ): return employee_info(None, db) @@ -138,10 +129,8 @@ async def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get "isActive": item.is_active, "costCentre": item.cost_centre.name, "joiningDate": item.joining_date.strftime("%d-%b-%Y"), - "leavingDate": "" - if item.is_active - else item.leaving_date.strftime("%d-%b-%Y"), - "isStarred": item.is_starred + "leavingDate": "" if item.is_active else item.leaving_date.strftime("%d-%b-%Y"), + "isStarred": item.is_starred, } for item in db.query(Employee) .order_by(desc(Employee.is_active)) @@ -154,10 +143,7 @@ async def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get @router.get("/query") async def show_term( - q: str, - c: int = None, - db: Session = Depends(get_db), - current_user: UserToken = Depends(get_user), + q: str, c: int = None, db: Session = Depends(get_db), current_user: UserToken = Depends(get_user), ): list_ = [] for index, item in enumerate(AccountBase.query(q=q, type_=10, db=db)): @@ -166,10 +152,7 @@ async def show_term( "id": item.id, "name": item.name, "designation": item.designation, - "costCentre": { - "id": item.cost_centre.id, - "name": item.cost_centre.name, - }, + "costCentre": {"id": item.cost_centre.id, "name": item.cost_centre.name,}, } ) if c is not None and index == c - 1: @@ -179,9 +162,7 @@ async def show_term( @router.get("/{id_}") def show_id( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["employees"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["employees"]), ): return employee_info(id_, db) @@ -208,22 +189,15 @@ def employee_info(id_, db): "salary": employee.salary, "points": employee.points, "joiningDate": employee.joining_date.strftime("%d-%b-%Y"), - "leavingDate": None - if employee.is_active - else employee.leaving_date.strftime("%d-%b-%Y"), - "costCentre": { - "id": employee.cost_centre_id, - "name": employee.cost_centre.name, - }, + "leavingDate": None if employee.is_active else employee.leaving_date.strftime("%d-%b-%Y"), + "costCentre": {"id": employee.cost_centre_id, "name": employee.cost_centre.name,}, "isFixture": employee.is_fixture, } return employee def delete_with_data(employee, db): - suspense_account = ( - db.query(Account).filter(Account.id == Account.suspense()).first() - ) + suspense_account = db.query(Account).filter(Account.id == Account.suspense()).first() query = ( db.query(Voucher) .options(joinedload_all(Voucher.journals, Journal.account, innerjoin=True)) @@ -245,13 +219,9 @@ def delete_with_data(employee, db): else: if sus_jnl is None: acc_jnl.account = suspense_account - voucher.narration += ( - f"\nSuspense \u20B9 {acc_jnl.amount:,.2f} is {employee.name}" - ) + voucher.narration += f"\nSuspense \u20B9 {acc_jnl.amount:,.2f} is {employee.name}" else: - amount = (sus_jnl.debit * sus_jnl.amount) + ( - acc_jnl.debit * acc_jnl.amount - ) + amount = (sus_jnl.debit * sus_jnl.amount) + (acc_jnl.debit * acc_jnl.amount) if acc_jnl.employee_benefit is not None: db.delete(acc_jnl.employee_benefit) db.delete(acc_jnl) @@ -261,10 +231,7 @@ def delete_with_data(employee, db): sus_jnl.amount = abs(amount) sus_jnl.debit = -1 if amount < 0 else 1 voucher.narration += f"\nDeleted \u20B9 {acc_jnl.amount * acc_jnl.debit:,.2f} of {employee.name}" - if voucher.type in ( - VoucherType.by_name("Payment").id, - VoucherType.by_name("Receipt").id, - ): + if voucher.type in (VoucherType.by_name("Payment").id, VoucherType.by_name("Receipt").id,): voucher.type = VoucherType.by_name("Journal") for fingerprint in employee.fingerprints: db.delete(fingerprint) diff --git a/brewman/routers/employee_attendance.py b/brewman/routers/employee_attendance.py index ac3e0993..8db2e8f0 100644 --- a/brewman/routers/employee_attendance.py +++ b/brewman/routers/employee_attendance.py @@ -63,21 +63,15 @@ def employee_attendance_report( } start_date = datetime.strptime(start_date, "%d-%b-%Y").date() finish_date = datetime.strptime(finish_date, "%d-%b-%Y").date() - start_date = ( - employee.joining_date if employee.joining_date > start_date else start_date - ) + start_date = employee.joining_date if employee.joining_date > start_date else start_date finish_date = ( - employee.leaving_date - if not employee.is_active and employee.leaving_date < finish_date - else finish_date + employee.leaving_date if not employee.is_active and employee.leaving_date < finish_date else finish_date ) info["body"] = employee_attendance(employee, start_date, finish_date, db) return info -def employee_attendance( - employee: Employee, start_date: date, finish_date: date, db: Session -): +def employee_attendance(employee: Employee, start_date: date, finish_date: date, db: Session): list_ = [] for item in date_range(start_date, finish_date, inclusive=True): att = ( @@ -119,10 +113,7 @@ def save_employee_attendance( attendance_type = item.attendance_type.id_ if attendance_type != 0: attendance = Attendance( - employee_id=employee.id, - date=item.date_, - attendance_type=attendance_type, - user_id=user.id_, + employee_id=employee.id, date=item.date_, attendance_type=attendance_type, user_id=user.id_, ) attendance.create(db) db.commit() diff --git a/brewman/routers/employee_benefit.py b/brewman/routers/employee_benefit.py index a7aa0280..2057f310 100644 --- a/brewman/routers/employee_benefit.py +++ b/brewman/routers/employee_benefit.py @@ -61,9 +61,7 @@ def save_route( dt = get_last_day(data.date_) days_in_month = dt.day item: Voucher = save(data, dt, user, db) - exp, total = save_employee_benefits( - item, data.employee_benefits, days_in_month, db - ) + exp, total = save_employee_benefits(item, data.employee_benefits, days_in_month, db) save_journals(item, exp, total, db) save_files(item.id, i, t, db) db.commit() @@ -78,14 +76,11 @@ def save_route( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) -def save( - data: schema_in.EmployeeBenefitIn, date_: date, user: UserToken, db: Session -) -> Voucher: +def save(data: schema_in.EmployeeBenefitIn, date_: date, user: UserToken, db: Session) -> Voucher: check_voucher_lock_info(None, date_, db) voucher = Voucher( date=date_, @@ -99,28 +94,16 @@ def save( def save_employee_benefits( - voucher: Voucher, - employee_benefits: List[schema_in.EmployeeBenefit], - days_in_month: int, - db: Session, + voucher: Voucher, employee_benefits: List[schema_in.EmployeeBenefit], days_in_month: int, db: Session, ): total_exp, total_total = 0, 0 for item in employee_benefits: account = db.query(Employee).filter(Employee.id == item.employee.id_).first() gross_salary = item.gross_salary days_worked = item.days_worked - esi_ee, esi_er, esi_both = esi_contribution( - gross_salary, days_worked, days_in_month - ) - pf_ee, pf_er, pf_both = pf_contribution( - gross_salary, days_worked, days_in_month - ) - journal = Journal( - amount=esi_ee + pf_ee, - debit=1, - account_id=account.id, - cost_centre_id=account.cost_centre_id, - ) + esi_ee, esi_er, esi_both = esi_contribution(gross_salary, days_worked, days_in_month) + pf_ee, pf_er, pf_both = pf_contribution(gross_salary, days_worked, days_in_month) + journal = Journal(amount=esi_ee + pf_ee, debit=1, account_id=account.id, cost_centre_id=account.cost_centre_id,) sd = EmployeeBenefit( journal=journal, gross_salary=gross_salary, @@ -140,30 +123,12 @@ def save_employee_benefits( def save_journals(voucher: Voucher, exp: int, total: int, db: Session): - account = ( - db.query(AccountBase) - .filter(AccountBase.id == AccountBase.esi_pf_expense()) - .first() - ) - journal = Journal( - amount=exp, - debit=1, - account_id=account.id, - cost_centre_id=account.cost_centre_id, - ) + account = db.query(AccountBase).filter(AccountBase.id == AccountBase.esi_pf_expense()).first() + journal = Journal(amount=exp, debit=1, account_id=account.id, cost_centre_id=account.cost_centre_id,) db.add(journal) voucher.journals.append(journal) - account = ( - db.query(AccountBase) - .filter(AccountBase.id == AccountBase.esi_pf_payable()) - .first() - ) - journal = Journal( - amount=total, - debit=-1, - account_id=account.id, - cost_centre_id=account.cost_centre_id, - ) + account = db.query(AccountBase).filter(AccountBase.id == AccountBase.esi_pf_payable()).first() + journal = Journal(amount=total, debit=-1, account_id=account.id, cost_centre_id=account.cost_centre_id,) db.add(journal) voucher.journals.append(journal) @@ -184,9 +149,7 @@ def update_route( item: Voucher = update(id_, data, user, db) if dt != item.date: raise ValueError("Date Cannot be changed for Employee Benefit voucher!") - exp, total = update_employee_benefits( - item, data.employee_benefits, days_in_month, db - ) + exp, total = update_employee_benefits(item, data.employee_benefits, days_in_month, db) update_journals(item, exp, total) # journals_valid(voucher) update_files(item.id, data.files, i, t, db) @@ -201,14 +164,11 @@ def update_route( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) -def update( - id_: uuid.UUID, data: schema_in.EmployeeBenefitIn, user: UserToken, db: Session -) -> Voucher: +def update(id_: uuid.UUID, data: schema_in.EmployeeBenefitIn, user: UserToken, db: Session) -> Voucher: voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_edit_allowed(voucher, user) @@ -221,10 +181,7 @@ def update( def update_employee_benefits( - voucher: Voucher, - employee_benefits: List[schema_in.EmployeeBenefit], - days_in_month: int, - db: Session, + voucher: Voucher, employee_benefits: List[schema_in.EmployeeBenefit], days_in_month: int, db: Session, ): exp, total = 0, 0 for i in range(len(voucher.employee_benefits), 0, -1): @@ -240,28 +197,20 @@ def update_employee_benefits( if not found: voucher.employee_benefits.remove(item) voucher.journals.remove(item.journal) - new_exp, new_total = save_employee_benefits( - voucher, employee_benefits, days_in_month, db - ) + new_exp, new_total = save_employee_benefits(voucher, employee_benefits, days_in_month, db) return exp + new_exp, total + new_total def update_journals(voucher: Voucher, exp: int, total: int): - journal = next( - i for i in voucher.journals if i.account_id == AccountBase.esi_pf_expense() - ) + journal = next(i for i in voucher.journals if i.account_id == AccountBase.esi_pf_expense()) journal.amount = exp - journal = next( - i for i in voucher.journals if i.account_id == AccountBase.esi_pf_payable() - ) + journal = next(i for i in voucher.journals if i.account_id == AccountBase.esi_pf_payable()) journal.amount = total @router.get("/{id_}", response_model=output.Voucher) def get_id( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["employee-benefit"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["employee-benefit"]), ): try: item: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() @@ -274,16 +223,13 @@ def get_id( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @router.get("", response_model=output.Voucher) def show_blank( - request: Request, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["employee-benefit"]), + request: Request, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["employee-benefit"]), ): additional_info = {"date": get_date(request.session), "type": "Employee Benefit"} return blank_voucher(additional_info, db) @@ -293,16 +239,8 @@ def esi_contribution(gross_salary, days_worked, days_in_month): limit = 21000 employee_rate = 0.0175 employer_rate = 0.0475 - employee = ( - 0 - if gross_salary > limit - else ceil(employee_rate * gross_salary * days_worked / days_in_month) - ) - employer = ( - 0 - if gross_salary > limit - else ceil(employer_rate * gross_salary * days_worked / days_in_month) - ) + employee = 0 if gross_salary > limit else ceil(employee_rate * gross_salary * days_worked / days_in_month) + employer = 0 if gross_salary > limit else ceil(employer_rate * gross_salary * days_worked / days_in_month) return employee, employer, employee + employer @@ -310,14 +248,6 @@ def pf_contribution(gross_salary, days_worked, days_in_month): limit = 15000 employee_rate = 0.12 employer_rate = 0.12 + 0.011 + 0.005 + 0.0001 - employee = ( - 0 - if gross_salary > limit - else ceil(employee_rate * gross_salary * days_worked / days_in_month) - ) - employer = ( - 0 - if gross_salary > limit - else ceil(employer_rate * gross_salary * days_worked / days_in_month) - ) + employee = 0 if gross_salary > limit else ceil(employee_rate * gross_salary * days_worked / days_in_month) + employer = 0 if gross_salary > limit else ceil(employer_rate * gross_salary * days_worked / days_in_month) return employee, employer, employee + employer diff --git a/brewman/routers/fingerprint.py b/brewman/routers/fingerprint.py index c1b7c44e..1370a2a9 100644 --- a/brewman/routers/fingerprint.py +++ b/brewman/routers/fingerprint.py @@ -40,23 +40,14 @@ def get_query(version): return ( pg_insert(Fingerprint) .values( - { - "FingerprintID": bindparam("id"), - "EmployeeID": bindparam("employee_id"), - "Date": bindparam("date"), - } + {"FingerprintID": bindparam("id"), "EmployeeID": bindparam("employee_id"), "Date": bindparam("date"),} ) .on_conflict_do_nothing() ) else: - sel = select( - [bindparam("id"), bindparam("employee_id"), bindparam("date")] - ).where( + sel = select([bindparam("id"), bindparam("employee_id"), bindparam("date")]).where( ~exists([Fingerprint.id]).where( - and_( - Fingerprint.employee_id == bindparam("employee_id"), - Fingerprint.date == bindparam("date"), - ) + and_(Fingerprint.employee_id == bindparam("employee_id"), Fingerprint.date == bindparam("date"),) ) ) return Fingerprint.__table__.insert().from_select( @@ -95,11 +86,7 @@ def fp(file_data, employees): date = datetime.datetime.strptime(row[date_column], date_format) if employee_code in employees.keys(): fingerprints.append( - { - "id": uuid.uuid4(), - "employee_id": employees[employee_code], - "date": date, - } + {"id": uuid.uuid4(), "employee_id": employees[employee_code], "date": date,} ) except ValueError: continue diff --git a/brewman/routers/incentive.py b/brewman/routers/incentive.py index 4c64a535..913dc8ff 100644 --- a/brewman/routers/incentive.py +++ b/brewman/routers/incentive.py @@ -57,9 +57,7 @@ def save_route( ): try: item: Voucher = save(data, user, db) - employees = get_employees( - get_first_day(data.date_), data.date_, data.incentives, None, db - ) + employees = get_employees(get_first_day(data.date_), data.date_, data.incentives, None, db) amount = balance(data.date_, None, db) * Decimal(0.9) # 10% for Deb Dip total_points = sum(e.points * e.days_worked for e in employees) point_value = round(amount / total_points, 2) @@ -76,8 +74,7 @@ def save_route( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -95,23 +92,15 @@ def save(data: schema_in.IncentiveIn, user: UserToken, db: Session) -> Voucher: def save_incentives( - voucher: Voucher, - employees: List[schema_in.IncentiveEmployee], - point_value: Decimal, - db: Session, + voucher: Voucher, employees: List[schema_in.IncentiveEmployee], point_value: Decimal, db: Session, ): total_amount = 0 for item in employees: item_amount = round(item.points * item.days_worked * point_value) journal = Journal( - amount=item_amount, - debit=-1, - account_id=item.employee_id, - cost_centre_id=item.cost_centre_id, - ) - inc = Incentive( - journal=journal, days_worked=item.days_worked, points=item.points + amount=item_amount, debit=-1, account_id=item.employee_id, cost_centre_id=item.cost_centre_id, ) + inc = Incentive(journal=journal, days_worked=item.days_worked, points=item.points) voucher.journals.append(journal) voucher.incentives.append(inc) db.add(journal) @@ -119,9 +108,7 @@ def save_incentives( total_amount += item_amount sc = db.query(Account).filter(Account.id == Account.incentive_id()).first() - journal = Journal( - amount=total_amount, debit=1, account_id=sc.id, cost_centre_id=sc.cost_centre_id - ) + journal = Journal(amount=total_amount, debit=1, account_id=sc.id, cost_centre_id=sc.cost_centre_id) voucher.journals.append(journal) db.add(journal) @@ -136,9 +123,7 @@ def update_route( ): try: item: Voucher = update(id_, data, user, db) - employees = get_employees( - get_first_day(data.date_), data.date_, data.incentives, item.journals, db - ) + employees = get_employees(get_first_day(data.date_), data.date_, data.incentives, item.journals, db) amount = balance(data.date_, item.id, db) * Decimal(0.9) # 10% for Deb Dip total_points = sum(e.points * e.days_worked for e in employees) point_value = round(amount / total_points, 2) @@ -154,14 +139,11 @@ def update_route( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) -def update( - id_: uuid.UUID, data: schema_in.IncentiveIn, user: UserToken, db: Session -) -> Voucher: +def update(id_: uuid.UUID, data: schema_in.IncentiveIn, user: UserToken, db: Session) -> Voucher: voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_edit_allowed(voucher, user) @@ -174,33 +156,24 @@ def update( def update_incentives( - voucher: Voucher, - employees: List[schema_in.IncentiveEmployee], - point_value: Decimal, - db: Session, + voucher: Voucher, employees: List[schema_in.IncentiveEmployee], point_value: Decimal, db: Session, ): total_amount = 0 for item in voucher.incentives: - employee = next( - e for e in employees if e.employee_id == item.journal.account_id - ) + employee = next(e for e in employees if e.employee_id == item.journal.account_id) item_amount = round(employee.points * employee.days_worked * point_value) item.days_worked = employee.days_worked item.points = employee.points item.journal.amount = item_amount total_amount += item_amount - journal = next( - j for j in voucher.journals if j.account_id == Account.incentive_id() - ) + journal = next(j for j in voucher.journals if j.account_id == Account.incentive_id()) journal.amount = total_amount @router.get("/{id_}", response_model=output.Voucher) def get_id( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["incentive"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["incentive"]), ): try: item: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() @@ -213,8 +186,7 @@ def get_id( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -258,16 +230,11 @@ def get_employees( .filter(Attendance.is_valid == True) .all() ) - att = 0.5 * round( - sum(map(lambda x: AttendanceType.by_id(x.attendance_type).value, att)) / 0.5 - ) + att = 0.5 * round(sum(map(lambda x: AttendanceType.by_id(x.attendance_type).value, att)) / 0.5) points = next(x for x in incentives if x.employee_id == employee.id).points details.append( schema_in.IncentiveEmployee( - employee_id=employee.id, - cost_centre_id=employee.cost_centre_id, - days_worked=att, - points=points, + employee_id=employee.id, cost_centre_id=employee.cost_centre_id, days_worked=att, points=points, ) ) return details @@ -288,16 +255,12 @@ def balance(date_: date, voucher_id: Optional[uuid.UUID], db: Session): def check_if_employees_changed( - json: List[schema_in.Incentive], - db: List[Employee], - voucher: Optional[List[Journal]], + json: List[schema_in.Incentive], db: List[Employee], voucher: Optional[List[Journal]], ): json = set(x.employee_id for x in json) db = set(x.id for x in db) voucher = ( - set(x.account_id for x in voucher if x.account_id != Account.incentive_id()) - if voucher is not None - else None + set(x.account_id for x in voucher if x.account_id != Account.incentive_id()) if voucher is not None else None ) if voucher is None: if len(json ^ db) != 0: diff --git a/brewman/routers/issue.py b/brewman/routers/issue.py index 98cf91d8..3ad075db 100644 --- a/brewman/routers/issue.py +++ b/brewman/routers/issue.py @@ -70,14 +70,11 @@ def save_route( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) -def save( - data: schema_in.IssueIn, user: UserToken, db: Session -) -> (Voucher, Optional[bool]): +def save(data: schema_in.IssueIn, user: UserToken, db: Session) -> (Voucher, Optional[bool]): check_voucher_lock_info(None, data.date_, db) voucher = Voucher( date=data.date_, @@ -89,8 +86,7 @@ def save( db.add(voucher) if data.source.id_ == data.destination.id_: raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="Source cannot be the same as destination", + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Source cannot be the same as destination", ) if data.source.id_ == CostCentre.cost_centre_purchase(): batch_consumed = True @@ -102,10 +98,7 @@ def save( def save_inventories( - voucher: Voucher, - inventories: List[schema_in.Inventory], - batch_consumed: Optional[bool], - db: Session, + voucher: Voucher, inventories: List[schema_in.Inventory], batch_consumed: Optional[bool], db: Session, ) -> Decimal: amount: Decimal = Decimal(0) for item in inventories: @@ -149,18 +142,8 @@ def save_journals( amount: Decimal, db: Session, ): - s = Journal( - debit=-1, - account_id=AccountBase.all_purchases(), - amount=amount, - cost_centre_id=source.id_, - ) - d = Journal( - debit=1, - account_id=AccountBase.all_purchases(), - amount=amount, - cost_centre_id=destination.id_, - ) + s = Journal(debit=-1, account_id=AccountBase.all_purchases(), amount=amount, cost_centre_id=source.id_,) + d = Journal(debit=1, account_id=AccountBase.all_purchases(), amount=amount, cost_centre_id=destination.id_,) voucher.journals.append(s) db.add(s) voucher.journals.append(d) @@ -194,14 +177,11 @@ def update_route( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) -def update( - id_: uuid.UUID, data: schema_in.IssueIn, user: UserToken, db: Session -) -> (Voucher, Optional[bool]): +def update(id_: uuid.UUID, data: schema_in.IssueIn, user: UserToken, db: Session) -> (Voucher, Optional[bool]): voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_edit_allowed(voucher, user) @@ -234,17 +214,13 @@ def update( if new_batch_consumed != old_batch_consumed: raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="Purchase cost centre cannot be changed", + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Purchase cost centre cannot be changed", ) return voucher, new_batch_consumed def update_inventories( - voucher: Voucher, - inventories: List[schema_in.Inventory], - batch_consumed: Optional[bool], - db: Session, + voucher: Voucher, inventories: List[schema_in.Inventory], batch_consumed: Optional[bool], db: Session, ): amount: Decimal = Decimal(0) for it in range(len(voucher.inventories), 0, -1): @@ -257,13 +233,9 @@ def update_inventories( found = True if item.batch_id != batch.id: raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="Product / Batch cannot be changed", + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Product / Batch cannot be changed", ) - if ( - batch_consumed - and i.quantity - item.quantity > item.batch.quantity_remaining - ): + if batch_consumed and i.quantity - item.quantity > item.batch.quantity_remaining: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=f"Maximum quantity available for {item.product.full_name} is {item.quantity + item.batch.quantity_remaining}", @@ -308,10 +280,7 @@ def update_inventories( def update_journals( - voucher: Voucher, - source: schema_in.CostCentreLink, - destination: schema_in.CostCentreLink, - amount: Decimal, + voucher: Voucher, source: schema_in.CostCentreLink, destination: schema_in.CostCentreLink, amount: Decimal, ): for i in range(len(voucher.journals), 0, -1): item = voucher.journals[i - 1] @@ -325,9 +294,7 @@ def update_journals( @router.get("/{id_}", response_model=output.Voucher) def get_id( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["issue"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["issue"]), ): try: item: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() @@ -340,8 +307,7 @@ def get_id( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) diff --git a/brewman/routers/issue_grid.py b/brewman/routers/issue_grid.py index 26834bdc..7eddbd27 100644 --- a/brewman/routers/issue_grid.py +++ b/brewman/routers/issue_grid.py @@ -24,10 +24,7 @@ def get_db() -> Session: @router.get("/{date}") def grid_date( - date: str, - request: Request, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["issue"]), + date: str, request: Request, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["issue"]), ): date = datetime.strptime(date, "%d-%b-%Y") return get_grid(date, db) @@ -53,12 +50,8 @@ def get_grid(date, db): { "id": str(voucher.id), "amount": amount, - "source": [ - j.cost_centre.name for j in voucher.journals if j.debit == -1 - ], - "destination": [ - j.cost_centre.name for j in voucher.journals if j.debit == 1 - ], + "source": [j.cost_centre.name for j in voucher.journals if j.debit == -1], + "destination": [j.cost_centre.name for j in voucher.journals if j.debit == 1], } ) return list_ diff --git a/brewman/routers/journal.py b/brewman/routers/journal.py index 24cada14..131e7505 100644 --- a/brewman/routers/journal.py +++ b/brewman/routers/journal.py @@ -79,14 +79,9 @@ def save(data: schema_in.JournalIn, user: UserToken, db: Session) -> Voucher: ) db.add(voucher) for item in data.journals: - account: AccountBase = db.query(AccountBase).filter( - AccountBase.id == item.account.id_ - ).first() + account: AccountBase = db.query(AccountBase).filter(AccountBase.id == item.account.id_).first() journal = Journal( - amount=item.amount, - debit=item.debit, - account_id=account.id, - cost_centre_id=account.cost_centre_id, + amount=item.amount, debit=item.debit, account_id=account.id, cost_centre_id=account.cost_centre_id, ) voucher.journals.append(journal) db.add(journal) @@ -117,14 +112,11 @@ def update_route( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) -def update( - id_: uuid.UUID, data: schema_in.JournalIn, user: UserToken, db: Session -) -> Voucher: +def update(id_: uuid.UUID, data: schema_in.JournalIn, user: UserToken, db: Session) -> Voucher: voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_edit_allowed(voucher, user) @@ -141,11 +133,7 @@ def update( for j in range(len(data.journals), 0, -1): new_item = data.journals[j - 1] if new_item.id_ is not None and item.id == new_item.id_: - account = ( - db.query(AccountBase) - .filter(AccountBase.id == new_item.account.id_) - .first() - ) + account = db.query(AccountBase).filter(AccountBase.id == new_item.account.id_).first() found = True item.debit = new_item.debit item.amount = new_item.amount @@ -156,14 +144,9 @@ def update( if not found: voucher.journals.remove(item) for new_item in data.journals: - account = ( - db.query(AccountBase).filter(AccountBase.id == new_item.account.id_).first() - ) + account = db.query(AccountBase).filter(AccountBase.id == new_item.account.id_).first() journal = Journal( - amount=new_item.amount, - debit=new_item.debit, - account_id=account.id, - cost_centre_id=account.cost_centre_id, + amount=new_item.amount, debit=new_item.debit, account_id=account.id, cost_centre_id=account.cost_centre_id, ) db.add(journal) voucher.journals.append(journal) @@ -172,9 +155,7 @@ def update( @router.get("/{id_}", response_model=output.Voucher) def get_id( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["journal"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["journal"]), ): try: item: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() @@ -194,8 +175,7 @@ def get_id( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -206,9 +186,9 @@ def show_blank( db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["journal"]), ): - if request.scope.get('path') == '/api/payment': + if request.scope.get("path") == "/api/payment": type_ = "Payment" - elif request.scope.get('path') == '/api/receipt': + elif request.scope.get("path") == "/api/receipt": type_ = "Receipt" else: type_ = "Journal" diff --git a/brewman/routers/lock_information.py b/brewman/routers/lock_information.py index 3bb699db..15fe4a0a 100644 --- a/brewman/routers/lock_information.py +++ b/brewman/routers/lock_information.py @@ -25,9 +25,7 @@ def get_db() -> Session: @router.post("", response_model=LockInformation) def post( - data_in: LockInformation, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["lock-date"]), + data_in: LockInformation, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["lock-date"]), ): data = { "Start": {"Locked": data_in.lock_older}, @@ -59,8 +57,7 @@ def post( @router.delete("") def delete( - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["lock-date"]), + db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["lock-date"]), ): lock_date = db.query(DbSetting).filter(DbSetting.name == "Lock Info").first() if lock_date is not None and lock_date.data is not None: diff --git a/brewman/routers/login.py b/brewman/routers/login.py index ed71bea8..fc266484 100644 --- a/brewman/routers/login.py +++ b/brewman/routers/login.py @@ -1,13 +1,24 @@ from datetime import timedelta -from fastapi import APIRouter, Depends, HTTPException, status, Security, Cookie, Form, Response +from fastapi import ( + APIRouter, + Depends, + HTTPException, + status, + Security, + Cookie, + Form, + Response, +) from fastapi.security import OAuth2PasswordRequestForm from fastapi.responses import JSONResponse from sqlalchemy.orm import Session from ..core.security import ( Token, authenticate_user, - create_access_token, get_current_active_user, client_allowed, + create_access_token, + get_current_active_user, + client_allowed, ) from brewman.core.config import settings from ..db.session import SessionLocal @@ -48,7 +59,7 @@ async def login_for_access_token( not_allowed_response = JSONResponse( status_code=status.HTTP_401_UNAUTHORIZED, 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) return not_allowed_response @@ -57,15 +68,7 @@ async def login_for_access_token( data={ "sub": user.name, "scopes": ["authenticated"] - + list( - set( - [ - p.name.replace(" ", "-").lower() - for r in user.roles - for p in r.permissions - ] - ) - ), + + list(set([p.name.replace(" ", "-").lower() for r in user.roles for p in r.permissions])), "userId": str(user.id), "lockedOut": user.locked_out, }, @@ -75,17 +78,10 @@ async def login_for_access_token( @router.post("/refresh", response_model=Token) -async def refresh_token( - user: UserToken = Security(get_current_active_user) -): +async def refresh_token(user: UserToken = Security(get_current_active_user)): access_token_expires = timedelta(minutes=settings.JWT_TOKEN_EXPIRE_MINUTES) access_token = create_access_token( - data={ - "sub": user.name, - "scopes": user.permissions, - "userId": str(user.id_), - "lockedOut": user.locked_out, - }, + data={"sub": user.name, "scopes": user.permissions, "userId": str(user.id_), "lockedOut": user.locked_out,}, expires_delta=access_token_expires, ) return {"access_token": access_token, "token_type": "bearer"} diff --git a/brewman/routers/maintenance.py b/brewman/routers/maintenance.py index d6af5d45..e303df28 100644 --- a/brewman/routers/maintenance.py +++ b/brewman/routers/maintenance.py @@ -34,9 +34,7 @@ def get_maintenance( @router.post("", response_model=Maintenance) def set_maintenance( - data: Maintenance, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["maintenance"]), + data: Maintenance, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["maintenance"]), ): maintenance = db.query(DbSetting).filter(DbSetting.name == "Maintenance").first() if data.enabled is False and maintenance is not None: diff --git a/brewman/routers/product.py b/brewman/routers/product.py index ea9e2e53..7d5cadbf 100644 --- a/brewman/routers/product.py +++ b/brewman/routers/product.py @@ -28,9 +28,7 @@ def get_db(): @router.post("/", response_model=schemas.Product) def save( - data: schemas.ProductIn, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["products"]), + data: schemas.ProductIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]), ): try: item = Product( @@ -57,8 +55,7 @@ def save( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -73,8 +70,7 @@ def update( item: Product = db.query(Product).filter(Product.id == id_).first() if item.is_fixture: raise HTTPException( - status_code=status.HTTP_423_LOCKED, - detail=f"{item.name} is a fixture and cannot be edited or deleted.", + status_code=status.HTTP_423_LOCKED, detail=f"{item.name} is a fixture and cannot be edited or deleted.", ) item.name = data.name item.units = data.units @@ -98,16 +94,13 @@ def update( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @router.delete("/{id_}") def delete( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["products"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]), ): product: Product = db.query(Product).filter(Product.id == id_).first() can_delete, reason = product.can_delete("advanced-delete" in user.permissions) @@ -119,15 +112,13 @@ def delete( else: db.abort() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Cannot delete account because {reason}", + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=f"Cannot delete account because {reason}", ) @router.get("/") # "Products" def show_blank( - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["products"]), + db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]), ): return product_info(None, db) @@ -195,9 +186,7 @@ async def show_term( @router.get("/{id_}") def show_id( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["accounts"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["accounts"]), ): return product_info(id_, db) @@ -234,9 +223,7 @@ def product_info(id_: Optional[uuid.UUID], db: Session): def delete_with_data(product: Product, db: Session): - suspense_product = ( - db.query(Product).filter(Product.id == Product.suspense()).first() - ) + suspense_product = db.query(Product).filter(Product.id == Product.suspense()).first() suspense_batch = db.query(Batch).filter(Batch.id == Batch.suspense()).first() query = ( db.query(Voucher) @@ -264,15 +251,11 @@ def delete_with_data(product: Product, db: Session): prod_inv.tax = 0 prod_inv.discount = 0 prod_inv.batch = suspense_batch - voucher.narration += ( - f"\nSuspense \u20B9{prod_inv.amount:,.2f} is {product.name}" - ) + voucher.narration += f"\nSuspense \u20B9{prod_inv.amount:,.2f} is {product.name}" else: sus_inv.quantity += prod_inv.amount db.delete(prod_inv) - voucher.narration += ( - f"\nDeleted \u20B9{prod_inv.amount:,.2f} of {product.name}" - ) + voucher.narration += f"\nDeleted \u20B9{prod_inv.amount:,.2f} of {product.name}" for batch in product.batches: db.delete(batch) db.delete(product) diff --git a/brewman/routers/product_group.py b/brewman/routers/product_group.py index fd1cbae0..3a2f5b0e 100644 --- a/brewman/routers/product_group.py +++ b/brewman/routers/product_group.py @@ -43,8 +43,7 @@ def save( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -59,8 +58,7 @@ def update( item = db.query(ProductGroup).filter(ProductGroup.id == id_).first() if item.is_fixture: raise HTTPException( - status_code=status.HTTP_423_LOCKED, - detail=f"{item.name} is a fixture and cannot be edited or deleted.", + status_code=status.HTTP_423_LOCKED, detail=f"{item.name} is a fixture and cannot be edited or deleted.", ) item.name = data.name db.commit() @@ -73,16 +71,13 @@ def update( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @router.delete("/{id_}") def delete( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["product-groups"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["product-groups"]), ): try: item = db.query(ProductGroup).filter(ProductGroup.id == id_).first() @@ -93,26 +88,22 @@ def delete( ) elif item.is_fixture: raise HTTPException( - status_code=status.HTTP_423_LOCKED, - detail=f"{item.name} is a fixture and cannot be edited or deleted.", + status_code=status.HTTP_423_LOCKED, detail=f"{item.name} is a fixture and cannot be edited or deleted.", ) else: raise HTTPException( - status_code=status.HTTP_501_NOT_IMPLEMENTED, - detail="Product Group deletion not implemented", + status_code=status.HTTP_501_NOT_IMPLEMENTED, detail="Product Group deletion not implemented", ) except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @router.get("") def show_blank( - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["product-groups"]), + db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["product-groups"]), ): return product_group_info(None, db) @@ -127,9 +118,7 @@ async def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get @router.get("/{id_}", response_model=schemas.ProductGroup) def show_id( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["product-groups"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["product-groups"]), ): item = db.query(ProductGroup).filter(ProductGroup.id == id_).first() return product_group_info(item, db) diff --git a/brewman/routers/purchase.py b/brewman/routers/purchase.py index 7851a841..4bbb87dc 100644 --- a/brewman/routers/purchase.py +++ b/brewman/routers/purchase.py @@ -70,8 +70,7 @@ def save_route( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -88,13 +87,9 @@ def save(data: schema_in.PurchaseIn, user: UserToken, db: Session) -> Voucher: return voucher -def save_inventories( - voucher: Voucher, inventories: List[schema_in.Inventory], db: Session -): +def save_inventories(voucher: Voucher, inventories: List[schema_in.Inventory], db: Session): for item in inventories: - product: Product = db.query(Product).filter( - Product.id == item.product.id_ - ).first() + product: Product = db.query(Product).filter(Product.id == item.product.id_).first() batch = Batch( name=voucher.date, product=product, @@ -129,17 +124,9 @@ def save_journals(voucher: Voucher, ven: schema_in.AccountLink, db: Session): journals[account.id].amount += round(item.amount, 2) else: journals[account.id] = Journal( - debit=1, - cost_centre_id=account.cost_centre_id, - account_id=account.id, - amount=round(item.amount, 2), + debit=1, cost_centre_id=account.cost_centre_id, account_id=account.id, amount=round(item.amount, 2), ) - journals[vendor.id] = Journal( - debit=-1, - cost_centre_id=vendor.cost_centre_id, - account_id=vendor.id, - amount=amount, - ) + journals[vendor.id] = Journal(debit=-1, cost_centre_id=vendor.cost_centre_id, account_id=vendor.id, amount=amount,) for item in journals.values(): voucher.journals.append(item) db.add(item) @@ -172,14 +159,11 @@ def update_route( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) -def update( - id_: uuid.UUID, data: schema_in.PurchaseIn, user: UserToken, db: Session -) -> Voucher: +def update(id_: uuid.UUID, data: schema_in.PurchaseIn, user: UserToken, db: Session) -> Voucher: voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_edit_allowed(voucher, user) @@ -192,25 +176,18 @@ def update( return voucher -def update_inventory( - voucher: Voucher, new_inventories: List[schema_in.Inventory], db: Session -): +def update_inventory(voucher: Voucher, new_inventories: List[schema_in.Inventory], db: Session): for it in range(len(voucher.inventories), 0, -1): item = voucher.inventories[it - 1] found = False for j in range(len(new_inventories), 0, -1): new_inventory = new_inventories[j - 1] if new_inventory.id_: - product = ( - db.query(Product) - .filter(Product.id == new_inventory.product.id_) - .first() - ) + product = db.query(Product).filter(Product.id == new_inventory.product.id_).first() found = True if item.product_id != new_inventory.product.id_: raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="Product cannot be changed", + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Product cannot be changed", ) old_quantity = round(Decimal(item.quantity), 2) quantity_remaining = round(Decimal(item.batch.quantity_remaining), 2) @@ -253,9 +230,7 @@ def update_inventory( db.delete(item) voucher.inventories.remove(item) for new_inventory in new_inventories: - product = ( - db.query(Product).filter(Product.id == new_inventory.product.id_).first() - ) + product = db.query(Product).filter(Product.id == new_inventory.product.id_).first() batch = Batch( name=voucher.date, product_id=product.id, @@ -293,17 +268,9 @@ def update_journals(voucher: Voucher, ven: schema_in.AccountLink, db): journals[account.id].amount += item.amount else: journals[account.id] = Journal( - debit=1, - cost_centre_id=account.cost_centre_id, - account_id=account.id, - amount=item.amount, + debit=1, cost_centre_id=account.cost_centre_id, account_id=account.id, amount=item.amount, ) - journals[vendor.id] = Journal( - debit=-1, - cost_centre_id=vendor.cost_centre_id, - account_id=vendor.id, - amount=amount, - ) + journals[vendor.id] = Journal(debit=-1, cost_centre_id=vendor.cost_centre_id, account_id=vendor.id, amount=amount,) for i in range(len(voucher.journals), 0, -1): item = voucher.journals[i - 1] if item.account_id in journals: @@ -322,9 +289,7 @@ def update_journals(voucher: Voucher, ven: schema_in.AccountLink, db): @router.get("/{id_}", response_model=output.Voucher) def get_id( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["purchase"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["purchase"]), ): try: item: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() @@ -337,16 +302,13 @@ def get_id( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @router.get("", response_model=output.Voucher) def show_blank( - request: Request, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["purchase"]), + request: Request, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["purchase"]), ): additional_info = {"date": get_date(request.session), "type": "Purchase"} return blank_voucher(additional_info, db) diff --git a/brewman/routers/purchase_return.py b/brewman/routers/purchase_return.py index ba839ecd..fb9028c5 100644 --- a/brewman/routers/purchase_return.py +++ b/brewman/routers/purchase_return.py @@ -69,8 +69,7 @@ def save_route( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @@ -87,18 +86,14 @@ def save(data: schema_in.PurchaseIn, user: UserToken, db: Session) -> Voucher: return voucher -def save_inventories( - voucher: Voucher, inventories: List[schema_in.Inventory], db: Session -): +def save_inventories(voucher: Voucher, inventories: List[schema_in.Inventory], db: Session): for item in inventories: batch = db.query(Batch).filter(Batch.id == item.batch.id_).first() if item.quantity > batch.quantity_remaining: raise ValueError(f"Maximum quantity is {batch.quantity_remaining}.") if batch.name > voucher.date: - raise ValueError( - f"Return date cannot be before {batch.product.name.strftime('%d-%b-%Y')}" - ) + raise ValueError(f"Return date cannot be before {batch.product.name.strftime('%d-%b-%Y')}") batch.quantity_remaining -= item.quantity @@ -125,17 +120,9 @@ def save_journals(voucher: Voucher, ven: schema_in.AccountLink, db: Session): journals[account.id].amount += round(item.amount, 2) else: journals[account.id] = Journal( - debit=-1, - cost_centre_id=account.cost_centre_id, - account_id=account.id, - amount=round(item.amount, 2), + debit=-1, cost_centre_id=account.cost_centre_id, account_id=account.id, amount=round(item.amount, 2), ) - journals[vendor.id] = Journal( - debit=1, - cost_centre_id=vendor.cost_centre_id, - account_id=vendor.id, - amount=amount, - ) + journals[vendor.id] = Journal(debit=1, cost_centre_id=vendor.cost_centre_id, account_id=vendor.id, amount=amount,) for item in journals.values(): voucher.journals.append(item) db.add(item) @@ -168,14 +155,11 @@ def update_route( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) -def update( - id_: uuid.UUID, data: schema_in.PurchaseIn, user: UserToken, db: Session -) -> Voucher: +def update(id_: uuid.UUID, data: schema_in.PurchaseIn, user: UserToken, db: Session) -> Voucher: voucher: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() check_voucher_lock_info(voucher.date, data.date_, db) check_voucher_edit_allowed(voucher, user) @@ -188,9 +172,7 @@ def update( return voucher -def update_inventory( - voucher: Voucher, new_inventories: List[schema_in.Inventory], db: Session -): +def update_inventory(voucher: Voucher, new_inventories: List[schema_in.Inventory], db: Session): for it in range(len(voucher.inventories), 0, -1): item = voucher.inventories[it - 1] found = False @@ -200,8 +182,7 @@ def update_inventory( found = True if item.product_id != new_inventory.product.id_: raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="Product cannot be changed", + status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Product cannot be changed", ) old_quantity = round(Decimal(item.quantity), 2) quantity_remaining = round(Decimal(item.batch.quantity_remaining), 2) @@ -211,9 +192,7 @@ def update_inventory( detail=f"{old_quantity + quantity_remaining} is the maximum for {item.product.full_name}.", ) if item.batch.name > voucher.date: - raise ValueError( - f"Voucher cannot be before {item.product.name.strftime('%d-%b-%Y')}" - ) + raise ValueError(f"Voucher cannot be before {item.product.name.strftime('%d-%b-%Y')}") item.batch.quantity_remaining -= new_inventory.quantity - old_quantity item.quantity = new_inventory.quantity new_inventories.remove(new_inventory) @@ -236,17 +215,9 @@ def update_journals(voucher: Voucher, ven: schema_in.AccountLink, db): journals[account.id].amount += item.amount else: journals[account.id] = Journal( - debit=-1, - cost_centre_id=account.cost_centre_id, - account_id=account.id, - amount=item.amount, + debit=-1, cost_centre_id=account.cost_centre_id, account_id=account.id, amount=item.amount, ) - journals[vendor.id] = Journal( - debit=1, - cost_centre_id=vendor.cost_centre_id, - account_id=vendor.id, - amount=amount, - ) + journals[vendor.id] = Journal(debit=1, cost_centre_id=vendor.cost_centre_id, account_id=vendor.id, amount=amount,) for i in range(len(voucher.journals), 0, -1): item = voucher.journals[i - 1] if item.account_id in journals: @@ -265,9 +236,7 @@ def update_journals(voucher: Voucher, ven: schema_in.AccountLink, db): @router.get("/{id_}", response_model=output.Voucher) def get_id( - id_: uuid.UUID, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["purchase-return"]), + id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["purchase-return"]), ): try: item: Voucher = db.query(Voucher).filter(Voucher.id == id_).first() @@ -280,16 +249,13 @@ def get_id( except Exception: db.rollback() raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=traceback.format_exc(), + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=traceback.format_exc(), ) @router.get("", response_model=output.Voucher) def show_blank( - request: Request, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["purchase-return"]), + request: Request, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["purchase-return"]), ): additional_info = {"date": get_date(request.session), "type": "Purchase"} return blank_voucher(additional_info, db) diff --git a/brewman/routers/rebase.py b/brewman/routers/rebase.py index 272569d4..37915d37 100644 --- a/brewman/routers/rebase.py +++ b/brewman/routers/rebase.py @@ -32,9 +32,7 @@ def get_db() -> Session: @router.post("/{date_}") def rebase( - date_: str, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["rebase"]), + date_: str, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["rebase"]), ): # request.dbsession.execute('SET statement_timeout TO 300000;') # 5 minutes date_ = datetime.strptime(date_, "%d-%b-%Y") @@ -59,12 +57,7 @@ def rebase( def save_starred(date_: date, db: Session): - accounts = [ - i.id - for i in db.query(AccountBase.id) - .filter(AccountBase.is_starred == True) - .all() - ] + accounts = [i.id for i in db.query(AccountBase.id).filter(AccountBase.is_starred == True).all()] vouchers = [] query = ( db.query(Voucher) @@ -76,11 +69,7 @@ def save_starred(date_: date, db: Session): for voucher in query: vouchers.append(voucher.id) - others = [ - journal - for journal in voucher.journals - if journal.account_id not in accounts - ] + others = [journal for journal in voucher.journals if journal.account_id not in accounts] if len(others) == 0: continue amount = round(Decimal(sum(o.signed_amount for o in others)), 2) @@ -208,22 +197,12 @@ def opening_batches(date_: date, user_id: uuid.UUID, db: Session): def delete_data(date_: date, vouchers: List[Voucher], db: Session): sub_voucher = aliased(Voucher) - 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( - EmployeeBenefit.__table__.delete(EmployeeBenefit.voucher_id.in_(sub_query)) - ) - db.execute( - Incentive.__table__.delete(Incentive.voucher_id.in_(sub_query)) - ) - db.execute( - Journal.__table__.delete( - and_(Journal.voucher_id.in_(sub_query), ~Journal.voucher_id.in_(vouchers)) - ) - ) + db.execute(EmployeeBenefit.__table__.delete(EmployeeBenefit.voucher_id.in_(sub_query))) + db.execute(Incentive.__table__.delete(Incentive.voucher_id.in_(sub_query))) + db.execute(Journal.__table__.delete(and_(Journal.voucher_id.in_(sub_query), ~Journal.voucher_id.in_(vouchers)))) db.execute( DbImage.__table__.delete( and_( @@ -233,32 +212,20 @@ def delete_data(date_: date, vouchers: List[Voucher], db: Session): ) ) ) - db.execute( - Voucher.__table__.delete(and_(Voucher.date < date_, ~Voucher.id.in_(vouchers))) - ) + db.execute(Voucher.__table__.delete(and_(Voucher.date < date_, ~Voucher.id.in_(vouchers)))) def cleanup_lint(date_: date, db: Session): # Insert executes on the end so keep list of batches and journals - db.execute( - Batch.__table__.delete( - ~Batch.id.in_(db.query(distinct(Inventory.batch_id)).subquery()) - ) - ) + db.execute(Batch.__table__.delete(~Batch.id.in_(db.query(distinct(Inventory.batch_id)).subquery()))) db.execute(Fingerprint.__table__.delete(Fingerprint.date < date_)) db.execute(Attendance.__table__.delete(Attendance.date < date_)) db.execute( Employee.__table__.delete( and_( - ~Employee.id.in_( - db.query(distinct(Journal.account_id)).subquery() - ), - ~Employee.id.in_( - db.query(distinct(Fingerprint.employee_id)).subquery() - ), - ~Employee.id.in_( - db.query(distinct(Attendance.employee_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(Attendance.employee_id)).subquery()), Employee.id.in_( db.query(AccountBase.id) .filter(AccountBase.is_fixture == False) @@ -274,17 +241,14 @@ def cleanup_lint(date_: date, db: Session): AccountBase.__table__.delete( and_( ~AccountBase.id.in_(db.query(Employee.id).subquery()), - AccountBase.account_type - == Employee.__mapper_args__["polymorphic_identity"], + AccountBase.account_type == Employee.__mapper_args__["polymorphic_identity"], ) ) ) db.execute( Account.__table__.delete( and_( - ~Account.id.in_( - db.query(distinct(Journal.account_id)).subquery() - ), + ~Account.id.in_(db.query(distinct(Journal.account_id)).subquery()), Account.is_fixture == False, Account.is_starred == False, Account.account_type == Account.__mapper_args__["polymorphic_identity"], diff --git a/brewman/routers/recipe.py b/brewman/routers/recipe.py index dbed394b..e6a2734c 100644 --- a/brewman/routers/recipe.py +++ b/brewman/routers/recipe.py @@ -21,21 +21,15 @@ router = APIRouter() def save(request): json = request.json_body recipe_product = ( - request.dbsession.query(Product) - .filter(Product.id == uuid.UUID(json["Product"]["ProductID"])) - .first() + request.dbsession.query(Product).filter(Product.id == uuid.UUID(json["Product"]["ProductID"])).first() ) try: - valid_from = datetime.date( - *(time.strptime(request.json_body["ValidFrom"], "%d-%b-%Y")[0:3]) - ) + valid_from = datetime.date(*(time.strptime(request.json_body["ValidFrom"], "%d-%b-%Y")[0:3])) except (ValueError, KeyError, TypeError): raise ValidationError("Valid From is not a valid date") try: - valid_to = datetime.date( - *(time.strptime(request.json_body["ValidTo"], "%d-%b-%Y")[0:3]) - ) + valid_to = datetime.date(*(time.strptime(request.json_body["ValidTo"], "%d-%b-%Y")[0:3])) except (ValueError, KeyError, TypeError): raise ValidationError("Valid To is not a valid date") @@ -68,25 +62,15 @@ def save(request): valid_to=valid_to, ) for item in json["RecipeItems"]: - product = ( - request.dbsession.query(Product) - .filter(Product.id == uuid.UUID(item["Product"]["ProductID"])) - .first() - ) + product = request.dbsession.query(Product).filter(Product.id == uuid.UUID(item["Product"]["ProductID"])).first() quantity = round(Decimal(item["Quantity"]), 2) if product.is_purchased: - ingredient_cost = get_purchased_product_cost( - product.id, valid_from, valid_to, request.dbsession - ) + ingredient_cost = get_purchased_product_cost(product.id, valid_from, valid_to, request.dbsession) else: - ingredient_cost = get_sub_product_cost( - product.id, valid_from, valid_to, request.dbsession - ) + ingredient_cost = get_sub_product_cost(product.id, valid_from, valid_to, request.dbsession) cost_per_unit = ingredient_cost / (product.fraction * product.product_yield) recipe_cost += cost_per_unit * quantity - recipe.recipe_items.append( - RecipeItem(None, product.id, quantity, ingredient_cost) - ) + recipe.recipe_items.append(RecipeItem(None, product.id, quantity, ingredient_cost)) recipe.cost_price = round(recipe_cost / recipe_quantity, 2) if recipe_product.is_sold: @@ -102,11 +86,7 @@ def save_recipe(recipe, dbsession): product = dbsession.query(Product).filter(Product.id == recipe.product_id).first() product.price = recipe.cost_price update_old_rows( - recipe.product_id, - recipe.valid_from, - recipe.valid_to, - recipe.effective_from, - dbsession, + recipe.product_id, recipe.valid_from, recipe.valid_to, recipe.effective_from, dbsession, ) dbsession.add(recipe) for item in recipe.recipe_items: @@ -117,11 +97,7 @@ def save_recipe(recipe, dbsession): def get_purchased_product_cost(product_id, start_date, finish_date, dbsession): quantity_sum = func.sum(Journal.debit * Inventory.quantity).label("quantity") amount_sum = func.sum( - Journal.debit - * Inventory.quantity - * Inventory.rate - * (1 + Inventory.tax) - * (1 - Inventory.discount) + Journal.debit * Inventory.quantity * Inventory.rate * (1 + Inventory.tax) * (1 - Inventory.discount) ).label("amount") costing = ( dbsession.query(quantity_sum, amount_sum) @@ -179,20 +155,12 @@ def get_sub_product_cost(product_id, start_date, finish_date, dbsession): ) for item in old_recipe.recipe_items: if item.product.is_purchased: - ingredient_cost = get_purchased_product_cost( - item.product_id, start_date, finish_date, dbsession - ) + ingredient_cost = get_purchased_product_cost(item.product_id, start_date, finish_date, dbsession) else: - ingredient_cost = get_sub_product_cost( - item.product_id, start_date, finish_date, dbsession - ) - cost_per_unit = ingredient_cost / ( - item.product.fraction * item.product.product_yield - ) + ingredient_cost = get_sub_product_cost(item.product_id, start_date, finish_date, dbsession) + cost_per_unit = ingredient_cost / (item.product.fraction * item.product.product_yield) recipe_cost += cost_per_unit * item.quantity - recipe.recipe_items.append( - RecipeItem(None, item.product_id, item.quantity, ingredient_cost) - ) + recipe.recipe_items.append(RecipeItem(None, item.product_id, item.quantity, ingredient_cost)) recipe.cost_price = round(recipe_cost / old_recipe.quantity, 2) @@ -225,9 +193,7 @@ def update_old_rows(product_id, valid_from, valid_to, effective_date, dbsession) effective_from=effective_date, ) for ri in item.recipe_items: - recipe.recipe_items.append( - RecipeItem(None, ri.product_id, ri.quantity, ri.price) - ) + recipe.recipe_items.append(RecipeItem(None, ri.product_id, ri.quantity, ri.price)) new_recipes.append(recipe) if item.valid_to > valid_to: recipe = Recipe( @@ -240,9 +206,7 @@ def update_old_rows(product_id, valid_from, valid_to, effective_date, dbsession) effective_from=effective_date, ) for ri in item.recipe_items: - recipe.recipe_items.append( - RecipeItem(None, ri.product_id, ri.quantity, ri.price) - ) + recipe.recipe_items.append(RecipeItem(None, ri.product_id, ri.quantity, ri.price)) new_recipes.append(recipe) if item.effective_from == effective_date and item.effective_to is None: @@ -261,11 +225,7 @@ def update_old_rows(product_id, valid_from, valid_to, effective_date, dbsession) @router.delete("/{id}") # "Recipes" def delete(request): - recipe = ( - request.dbsession.query(Recipe) - .filter(Recipe.id == uuid.UUID(request.matchdict["id"])) - .first() - ) + recipe = request.dbsession.query(Recipe).filter(Recipe.id == uuid.UUID(request.matchdict["id"])).first() if len(recipe.product.recipes) > 1: request.dbsession.delete(recipe) else: diff --git a/brewman/routers/reports/balance_sheet.py b/brewman/routers/reports/balance_sheet.py index f97534af..84c4a260 100644 --- a/brewman/routers/reports/balance_sheet.py +++ b/brewman/routers/reports/balance_sheet.py @@ -32,8 +32,7 @@ def get_db() -> Session: @router.get("", response_model=schemas.BalanceSheet) def report_blank( - request: Request, - user: UserToken = Security(get_user, scopes=["balance-sheet"]), + request: Request, user: UserToken = Security(get_user, scopes=["balance-sheet"]), ): return {"date": get_finish_date(request.session), "body": [], "footer": None} @@ -59,11 +58,7 @@ def build_balance_sheet(date_: date, db: Session): net_profit = round(get_accumulated_profit(date_, db), 2) - closing_stock total_amount = net_profit report.append( - { - "name": "Net Loss" if net_profit >= 0 else "Net Profit", - "subAmount": round(net_profit, 2), - "order": 79000, - } + {"name": "Net Loss" if net_profit >= 0 else "Net Profit", "subAmount": round(net_profit, 2), "order": 79000,} ) capital_group = AccountType.by_id(5) @@ -74,9 +69,7 @@ def build_balance_sheet(date_: date, db: Session): } total_amount += closing_stock - report.append( - {"name": "Closing Stock", "subAmount": round(closing_stock, 2), "order": 20001} - ) + report.append({"name": "Closing Stock", "subAmount": round(closing_stock, 2), "order": 20001}) asset_group = AccountType.by_id(4) groups[asset_group.id] = { @@ -107,11 +100,7 @@ def build_balance_sheet(date_: date, db: Session): if amount != 0: counter += 1 report.append( - { - "name": account.name, - "subAmount": round(amount, 2), - "order": account_type.order + counter, - } + {"name": account.name, "subAmount": round(amount, 2), "order": account_type.order + counter,} ) if account_type.id in groups: groups[account_type.id]["amount"] = round(groups[account_type.id]["amount"] + amount, 2) diff --git a/brewman/routers/reports/cash_flow.py b/brewman/routers/reports/cash_flow.py index 8fbbfa1f..1f78b7ed 100644 --- a/brewman/routers/reports/cash_flow.py +++ b/brewman/routers/reports/cash_flow.py @@ -31,8 +31,7 @@ def get_db() -> Session: @router.get("", response_model=schemas.CashFlow) def report_blank( - request: Request, - user: UserToken = Security(get_user, scopes=["cash-flow"]), + request: Request, user: UserToken = Security(get_user, scopes=["cash-flow"]), ): return { "startDate": get_start_date(request.session), @@ -111,11 +110,7 @@ def build_report(start_date, finish_date, db): lt = AccountType.by_id(account_type) total_amount += amount * -1 cf[lt.cash_flow_classification.lower()].append( - { - "name": lt.name, - "url": ['/', 'cash-flow', str(lt.id)], - "amount": amount * -1, - } + {"name": lt.name, "url": ["/", "cash-flow", str(lt.id)], "amount": amount * -1,} ) opening = ( @@ -141,14 +136,8 @@ def build_report(start_date, finish_date, db): return ( cf, [ - { - "name": "Net increase in cash and cash equivalents", - "amount": total_amount, - }, - { - "name": "Cash and cash equivalents at beginning of period", - "amount": opening, - }, + {"name": "Net increase in cash and cash equivalents", "amount": total_amount,}, + {"name": "Cash and cash equivalents at beginning of period", "amount": opening,}, {"name": "Cash and cash equivalents at end of period", "amount": closing}, ], ) @@ -185,11 +174,7 @@ def build_report_id(account_type, start_date, finish_date, db): for account, amount in query: total_amount += amount * -1 details.append( - { - "name": account.name, - "url": ['/', 'ledger', str(account.id)], - "amount": amount * -1, - } + {"name": account.name, "url": ["/", "ledger", str(account.id)], "amount": amount * -1,} ) return details, [{"name": "total", "amount": total_amount}] diff --git a/brewman/routers/reports/closing_stock.py b/brewman/routers/reports/closing_stock.py index 240fe6c5..029295b4 100644 --- a/brewman/routers/reports/closing_stock.py +++ b/brewman/routers/reports/closing_stock.py @@ -30,8 +30,7 @@ def get_db() -> Session: @router.get("", response_model=schemas.ClosingStock) def report_blank( - request: Request, - user: UserToken = Security(get_user, scopes=["closing-stock"]), + request: Request, user: UserToken = Security(get_user, scopes=["closing-stock"]), ): return {"date": get_finish_date(request.session), "body": []} @@ -44,13 +43,14 @@ def report_data( user: UserToken = Security(get_user, scopes=["closing-stock"]), ): set_period(get_start_date(request.session), date_, request.session) - return {"date": date_, "body": build_report(datetime.strptime(date_, "%d-%b-%Y").date(), db)} + return { + "date": date_, + "body": build_report(datetime.strptime(date_, "%d-%b-%Y").date(), db), + } def build_report(date_: date, db: Session): - amount_sum = func.sum( - Journal.debit * Inventory.quantity * Inventory.rate * (1 + Inventory.tax) - ).label("amount") + amount_sum = func.sum(Journal.debit * Inventory.quantity * Inventory.rate * (1 + Inventory.tax)).label("amount") quantity_sum = func.sum(Journal.debit * Inventory.quantity).label("quantity") query = ( db.query(Product, quantity_sum, amount_sum) @@ -80,14 +80,7 @@ def build_report(date_: date, db: Session): def get_opening_stock(date_: date, db: Session): opening_stock = ( - db.query( - func.sum( - Inventory.quantity - * Inventory.rate - * (1 + Inventory.tax) - * Journal.debit - ) - ) + db.query(func.sum(Inventory.quantity * Inventory.rate * (1 + Inventory.tax) * Journal.debit)) .join(Journal.voucher) .join(Journal.account) .join(Voucher.inventories) @@ -100,14 +93,7 @@ def get_opening_stock(date_: date, db: Session): def get_closing_stock(date_, db: Session): closing_stock = ( - db.query( - func.sum( - Inventory.quantity - * Inventory.rate - * (1 + Inventory.tax) - * Journal.debit - ) - ) + db.query(func.sum(Inventory.quantity * Inventory.rate * (1 + Inventory.tax) * Journal.debit)) .join(Journal.voucher) .join(Journal.account) .join(Voucher.inventories) diff --git a/brewman/routers/reports/daybook.py b/brewman/routers/reports/daybook.py index 1f252001..6294d2b7 100644 --- a/brewman/routers/reports/daybook.py +++ b/brewman/routers/reports/daybook.py @@ -28,8 +28,7 @@ def get_db() -> Session: @router.get("", response_model=schemas.Daybook) def report_blank( - request: Request, - user: UserToken = Security(get_user, scopes=["daybook"]), + request: Request, user: UserToken = Security(get_user, scopes=["daybook"]), ): return { "startDate": get_start_date(request.session), @@ -84,7 +83,7 @@ def build_report(start_date, finish_date, db): { "id": voucher.id, "date": voucher.date.strftime("%d-%b-%Y"), - "url": ['/', VoucherType.by_id(voucher.type).name.replace(" ", "-").lower(), str(voucher.id)], + "url": ["/", VoucherType.by_id(voucher.type).name.replace(" ", "-").lower(), str(voucher.id),], "type": VoucherType.by_id(voucher.type).name, "narration": voucher.narration, "posted": voucher.posted, diff --git a/brewman/routers/reports/ledger.py b/brewman/routers/reports/ledger.py index 7e3aadb1..17e505f8 100644 --- a/brewman/routers/reports/ledger.py +++ b/brewman/routers/reports/ledger.py @@ -31,8 +31,7 @@ def get_db() -> Session: @router.get("", response_model=schemas.Ledger) def show_blank( - request: Request, - user: UserToken = Security(get_user, scopes=["ledger"]), + request: Request, user: UserToken = Security(get_user, scopes=["ledger"]), ): return { "startDate": get_start_date(request.session), @@ -104,7 +103,7 @@ def build_report(account_id, start_date, finish_date, db): "id": voucher.id, "date": voucher.date.strftime("%d-%b-%Y"), "name": name, - "url": ['/', VoucherType.by_id(voucher.type).name.replace(" ", "-").lower(), str(voucher.id)], + "url": ["/", VoucherType.by_id(voucher.type).name.replace(" ", "-").lower(), str(voucher.id),], "type": VoucherType.by_id(voucher.type).name, "narration": voucher.narration, "debit": debit, diff --git a/brewman/routers/reports/net_transactions.py b/brewman/routers/reports/net_transactions.py index 0fb9366d..4277a046 100644 --- a/brewman/routers/reports/net_transactions.py +++ b/brewman/routers/reports/net_transactions.py @@ -30,8 +30,7 @@ def get_db() -> Session: @router.get("", response_model=schemas.NetTransactions) def show_blank( - request: Request, - user: UserToken = Security(get_user, scopes=["net-transactions"]), + request: Request, user: UserToken = Security(get_user, scopes=["net-transactions"]), ): return { "startDate": get_start_date(request.session), @@ -52,7 +51,7 @@ def show_data( return { "startDate": start, "finishDate": finish, - "body": build_report(datetime.strptime(start, "%d-%b-%Y"), datetime.strptime(finish, "%d-%b-%Y"), db), + "body": build_report(datetime.strptime(start, "%d-%b-%Y"), datetime.strptime(finish, "%d-%b-%Y"), db,), } @@ -75,7 +74,5 @@ def build_report(start_date: date, finish_date: date, db: Session): for account, amount in query: if amount != 0: tag = "debit" if amount > 0 else "credit" - body.append( - {"type": account.type_object.name, "name": account.name, tag: amount} - ) + body.append({"type": account.type_object.name, "name": account.name, tag: amount}) return body diff --git a/brewman/routers/reports/product_ledger.py b/brewman/routers/reports/product_ledger.py index 354dc66e..be2e6ae4 100644 --- a/brewman/routers/reports/product_ledger.py +++ b/brewman/routers/reports/product_ledger.py @@ -54,10 +54,7 @@ def show_data( start_date = s if s is not None else get_start_date(request.session) finish_date = f if f is not None else get_finish_date(request.session) body = build_report( - product.id, - datetime.strptime(start_date, "%d-%b-%Y"), - datetime.strptime(finish_date, "%d-%b-%Y"), - db, + product.id, datetime.strptime(start_date, "%d-%b-%Y"), datetime.strptime(finish_date, "%d-%b-%Y"), db, ) set_period(start_date, finish_date, request.session) return { @@ -68,21 +65,14 @@ def show_data( } -def build_report( - product_id: uuid.UUID, start_date: date, finish_date: date, db: Session -): +def build_report(product_id: uuid.UUID, start_date: date, finish_date: date, db: Session): body = [] - running_total_q, running_total_a, opening = opening_balance( - product_id, start_date, db - ) + running_total_q, running_total_a, opening = opening_balance(product_id, start_date, db) body.append(opening) query = ( db.query(Voucher, Inventory, Journal) - .options( - joinedload(Journal.account, innerjoin=True), - joinedload(Journal.cost_centre, innerjoin=True), - ) + .options(joinedload(Journal.account, innerjoin=True), joinedload(Journal.cost_centre, innerjoin=True),) .filter(Voucher.id == Inventory.voucher_id) .filter(Voucher.id == Journal.voucher_id) .filter(Inventory.product_id == product_id) @@ -114,15 +104,10 @@ def build_report( "id": row.Voucher.id, "date": row.Voucher.date.strftime("%d-%b-%Y"), "name": name, - "url": [ - "/", - VoucherType.by_id(row.Voucher.type).name.replace(" ", "-").lower(), - str(row.Voucher.id), - ], + "url": ["/", VoucherType.by_id(row.Voucher.type).name.replace(" ", "-").lower(), str(row.Voucher.id),], "type": VoucherType.by_id(row.Voucher.type).name, "narration": row.Voucher.narration, - "posted": row.Voucher.posted - or VoucherType.by_id(row.Voucher.type).name == "Issue", + "posted": row.Voucher.posted or VoucherType.by_id(row.Voucher.type).name == "Issue", "debitQuantity": debit_q, "debitAmount": debit_a, "creditQuantity": credit_q, @@ -137,10 +122,7 @@ def build_report( def opening_balance(product_id: uuid.UUID, start_date: date, db: Session): quantity, amount = ( - db.query( - func.sum(Inventory.quantity * Journal.debit), - func.sum(Inventory.amount * Journal.debit), - ) + db.query(func.sum(Inventory.quantity * Journal.debit), func.sum(Inventory.amount * Journal.debit),) .join(Inventory.voucher) .join(Voucher.journals) .filter(Voucher.id == Inventory.voucher_id) diff --git a/brewman/routers/reports/profit_loss.py b/brewman/routers/reports/profit_loss.py index da20c441..8fd8b021 100644 --- a/brewman/routers/reports/profit_loss.py +++ b/brewman/routers/reports/profit_loss.py @@ -31,8 +31,7 @@ def get_db() -> Session: @router.get("", response_model=schemas.ProfitLoss) def report_blank( - request: Request, - user: UserToken = Security(get_user, scopes=["profit-&-loss"]), + request: Request, user: UserToken = Security(get_user, scopes=["profit-&-loss"]), ): return { "startDate": get_start_date(request.session), @@ -85,9 +84,7 @@ def build_profit_loss(start_date: date, finish_date: date, db: Session): closing_stock = get_closing_stock(finish_date, db) total_amount = (opening_stock - closing_stock) * -1 - report.append( - {"name": "Opening Stock", "amount": opening_stock * -1, "order": 200001} - ) + report.append({"name": "Opening Stock", "amount": opening_stock * -1, "order": 200001}) report.append({"name": "Closing Stock", "amount": closing_stock, "order": 290000}) purchase_group = AccountType.by_id(2) groups[purchase_group.id] = { @@ -106,11 +103,7 @@ def build_profit_loss(start_date: date, finish_date: date, db: Session): if amount != 0: counter += 10 report.append( - { - "name": account.name, - "amount": amount, - "order": account_type.order + counter, - } + {"name": account.name, "amount": amount, "order": account_type.order + counter,} ) if account_type.id in groups: groups[account_type.id]["total"] += amount diff --git a/brewman/routers/reports/purchase_entries.py b/brewman/routers/reports/purchase_entries.py index d16c7735..dfab8f18 100644 --- a/brewman/routers/reports/purchase_entries.py +++ b/brewman/routers/reports/purchase_entries.py @@ -70,11 +70,7 @@ def build_report(start_date: date, finish_date, db): row = { "date": voucher.date.strftime("%d-%b-%Y"), "supplier": journal.account.name, - "url": [ - "/", - VoucherType.by_id(voucher.type).name.replace(" ", "-").lower(), - str(voucher.id), - ], + "url": ["/", VoucherType.by_id(voucher.type).name.replace(" ", "-").lower(), str(voucher.id),], "product": item.product.full_name, "quantity": item.quantity, "rate": item.rate, diff --git a/brewman/routers/reports/purchases.py b/brewman/routers/reports/purchases.py index 4e5d1b8d..edab0bf4 100644 --- a/brewman/routers/reports/purchases.py +++ b/brewman/routers/reports/purchases.py @@ -34,10 +34,7 @@ def report_blank( request: Request, user: UserToken = Security(get_user, scopes=["purchases"]), ): return schemas.Purchases( - startDate=get_start_date(request.session), - finishDate=get_finish_date(request.session), - body=[], - footer=None, + startDate=get_start_date(request.session), finishDate=get_finish_date(request.session), body=[], footer=None, ) @@ -51,17 +48,13 @@ def report_data( ): body, footer = build_report(start, finish, db) set_period(start, finish, request.session) - return schemas.Purchases( - startDate=start, finishDate=finish, body=body, footer=footer, - ) + return schemas.Purchases(startDate=start, finishDate=finish, body=body, footer=footer,) def build_report(start_date, finish_date, db): body = [] quantity_sum = func.sum(Journal.debit * Inventory.quantity).label("quantity") - amount_sum = func.sum( - Journal.debit * Inventory.quantity * Inventory.rate * (1 + Inventory.tax) - ).label("amount") + amount_sum = func.sum(Journal.debit * Inventory.quantity * Inventory.rate * (1 + Inventory.tax)).label("amount") query = ( db.query(Product, quantity_sum, amount_sum) .join(Product.inventories) @@ -90,7 +83,5 @@ def build_report(start_date, finish_date, db): body.append(row) return ( body, - schemas.PurchasesItem( - name="Total", quantity=0, rate=0, url=[], amount=total_amount - ), + schemas.PurchasesItem(name="Total", quantity=0, rate=0, url=[], amount=total_amount), ) diff --git a/brewman/routers/reports/raw_material_cost.py b/brewman/routers/reports/raw_material_cost.py index ae25d09c..b4684e6b 100644 --- a/brewman/routers/reports/raw_material_cost.py +++ b/brewman/routers/reports/raw_material_cost.py @@ -31,8 +31,7 @@ def get_db() -> Session: @router.get("", response_model=schemas.RawMaterialCost) def report_blank( - request: Request, - user: UserToken = Security(get_user, scopes=["raw-material-cost"]), + request: Request, user: UserToken = Security(get_user, scopes=["raw-material-cost"]), ): return { "startDate": get_start_date(request.session), @@ -81,12 +80,8 @@ def report_id( def build_report(start_date: date, finish_date: date, db: Session): body = [] - sum_issue = func.sum( - case([(AccountBase.type == 2, Journal.signed_amount)], else_=0) - ).label("issue") - sum_sale = func.sum( - case([(AccountBase.type == 3, Journal.signed_amount * -1)], else_=0) - ).label("sale") + sum_issue = func.sum(case([(AccountBase.type == 2, Journal.signed_amount)], else_=0)).label("issue") + sum_sale = func.sum(case([(AccountBase.type == 3, Journal.signed_amount * -1)], else_=0)).label("sale") query = ( db.query(CostCentre, sum_issue, sum_sale) @@ -114,7 +109,7 @@ def build_report(start_date: date, finish_date: date, db: Session): "issue": issue, "sale": sale, "rmc": rmc, - "url": ['/', 'raw-material-cost', str(cost_centre.id)], + "url": ["/", "raw-material-cost", str(cost_centre.id)], } ) diff --git a/brewman/routers/reports/reconcile.py b/brewman/routers/reports/reconcile.py index ccf1c7c9..26604ae7 100644 --- a/brewman/routers/reports/reconcile.py +++ b/brewman/routers/reports/reconcile.py @@ -31,8 +31,7 @@ def get_db() -> Session: @router.get("") def show_blank( - request: Request, - user: UserToken = Security(get_user, scopes=["reconcile"]), + request: Request, user: UserToken = Security(get_user, scopes=["reconcile"]), ): return { "startDate": get_start_date(request.session), @@ -60,7 +59,7 @@ def show_data( "startDate": start_date, "finishDate": finish_date, "account": {"id": account.id, "name": account.name}, - "body": body + "body": body, } @@ -76,10 +75,8 @@ def build_report(account_id, start_date, finish_date, db): or_( Voucher.is_reconciled == False, and_( - Voucher.reconcile_date - >= datetime.datetime.strptime(start_date, "%d-%b-%Y"), - Voucher.reconcile_date - <= datetime.datetime.strptime(finish_date, "%d-%b-%Y"), + Voucher.reconcile_date >= datetime.datetime.strptime(start_date, "%d-%b-%Y"), + Voucher.reconcile_date <= datetime.datetime.strptime(finish_date, "%d-%b-%Y"), ), ) ) @@ -128,9 +125,7 @@ def opening_balance(account_id, start_date, db): opening = ( db.query(func.sum(Journal.amount * Journal.debit)) .join(Journal.voucher) - .filter( - Voucher.reconcile_date < datetime.datetime.strptime(start_date, "%d-%b-%Y") - ) + .filter(Voucher.reconcile_date < datetime.datetime.strptime(start_date, "%d-%b-%Y")) .filter(Voucher.is_reconciled == True) .filter(Voucher.type != VoucherType.by_name("Issue").id) .filter(Journal.account_id == account_id) diff --git a/brewman/routers/reports/stock_movement.py b/brewman/routers/reports/stock_movement.py index ee090ef4..78f1016f 100644 --- a/brewman/routers/reports/stock_movement.py +++ b/brewman/routers/reports/stock_movement.py @@ -31,8 +31,7 @@ def get_db() -> Session: @router.get("", response_model=schemas.StockMovement) def report_blank( - request: Request, - user: UserToken = Security(get_user, scopes=["stock-movement"]), + request: Request, user: UserToken = Security(get_user, scopes=["stock-movement"]), ): return { "startDate": get_start_date(request.session), @@ -73,7 +72,7 @@ def build_stock_movement(start_date: date, finish_date: date, db: Session): "name": product.full_name, "group": product.product_group.name, "opening": Decimal(round(quantity, 2)), - "url": ['/', 'product-ledger', str(product.id)], + "url": ["/", "product-ledger", str(product.id)], } purchases = ( db.query(Product, quantity_sum) @@ -96,7 +95,7 @@ def build_stock_movement(start_date: date, finish_date: date, db: Session): "name": product.full_name, "group": product.product_group.name, "purchase": Decimal(round(quantity, 2)), - "url": ['/', 'product-ledger', str(product.id)], + "url": ["/", "product-ledger", str(product.id)], } issues = ( db.query(Product, quantity_sum) @@ -119,7 +118,7 @@ def build_stock_movement(start_date: date, finish_date: date, db: Session): "name": product.full_name, "group": product.product_group.name, "issue": Decimal(round(quantity * -1, 2)), - "url": ['/', 'product-ledger', str(product.id)], + "url": ["/", "product-ledger", str(product.id)], } list_ = [value for key, value in dict_.items()] diff --git a/brewman/routers/reports/trial_balance.py b/brewman/routers/reports/trial_balance.py index d24ed002..e38738e8 100644 --- a/brewman/routers/reports/trial_balance.py +++ b/brewman/routers/reports/trial_balance.py @@ -30,21 +30,23 @@ def get_db() -> Session: @router.get("", response_model=schemas.TrialBalance) def report_blank( - request: Request, - user: UserToken = Security(get_user, scopes=["trial-balance"]), + request: Request, user: UserToken = Security(get_user, scopes=["trial-balance"]), ): return {"date": get_finish_date(request.session), "body": []} @router.get("/{date_}", response_model=schemas.TrialBalance) def report_data( - date_: str, - request: Request, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["trial-balance"]), + date_: str, + request: Request, + db: Session = Depends(get_db), + user: UserToken = Security(get_user, scopes=["trial-balance"]), ): set_period(get_start_date(request.session), date_, request.session) - return {"date": date_, "body": build_report(datetime.strptime(date_, "%d-%b-%Y"), db)} + return { + "date": date_, + "body": build_report(datetime.strptime(date_, "%d-%b-%Y"), db), + } def build_report(date_: date, db: Session): @@ -65,7 +67,5 @@ def build_report(date_: date, db: Session): for account, amount in query: if amount != 0: tag = "debit" if amount > 0 else "credit" - body.append( - {"type": account.type_object.name, "name": account.name, tag: amount} - ) + body.append({"type": account.type_object.name, "name": account.name, tag: amount}) return body diff --git a/brewman/routers/reports/unposted.py b/brewman/routers/reports/unposted.py index d1bf3b16..25fb0301 100644 --- a/brewman/routers/reports/unposted.py +++ b/brewman/routers/reports/unposted.py @@ -23,9 +23,7 @@ def get_db() -> Session: @router.get("", response_model=List[schemas.Unposted]) def report_data( - request: Request, - db: Session = Depends(get_db), - user: UserToken = Security(get_user, scopes=["post-vouchers"]), + request: Request, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["post-vouchers"]), ): return build_report(db) @@ -62,7 +60,7 @@ def build_report(db: Session): { "id": voucher.id, "date": voucher.date.strftime("%d-%b-%Y"), - "url": ['/', VoucherType.by_id(voucher.type).name.replace(" ", "-").lower(), str(voucher.id)], + "url": ["/", VoucherType.by_id(voucher.type).name.replace(" ", "-").lower(), str(voucher.id),], "type": VoucherType.by_id(voucher.type).name, "narration": voucher.narration, "debitName": name_debit, diff --git a/brewman/routers/reset_stock.py b/brewman/routers/reset_stock.py index 2d9631e7..c56be587 100644 --- a/brewman/routers/reset_stock.py +++ b/brewman/routers/reset_stock.py @@ -46,9 +46,7 @@ def rebase( if reset_date > stock_date: raise ValueError("Reset cannot be after the stock date") - change = quantity - get_closing_stock( - product, stock_date, db=db - ) + change = quantity - get_closing_stock(product, stock_date, db=db) if change == 0: return {"No Change Needed"} final = get_closing_stock(product, db=db) @@ -79,38 +77,22 @@ def get_closing_stock(product, finish_date=None, db=None): def get_last_batch(product, db): - batch = ( - db.query(Batch) - .filter(Batch.product_id == product.id) - .order_by(Batch.name.desc()) - .first() - ) + batch = db.query(Batch).filter(Batch.product_id == product.id).order_by(Batch.name.desc()).first() if batch is None: - raise ValueError( - "Details for the product exist. Just add a purchase entry" - ) + raise ValueError("Details for the product exist. Just add a purchase entry") return batch def set_batches(batch, quantity, db): batch.quantity_remaining = quantity - batches = ( - db.query(Batch) - .filter(Batch.id != batch.id) - .filter(Batch.product_id == batch.product_id) - ) + batches = db.query(Batch).filter(Batch.id != batch.id).filter(Batch.product_id == batch.product_id) for item in batches: item.quantity_remaining = 0 pass def create_voucher(batch, quantity, date_, user_id, db): - voucher = Voucher( - date=date_, - narration="Product Reset", - user_id=user_id, - type_=VoucherType.by_name("Issue"), - ) + voucher = Voucher(date=date_, narration="Product Reset", user_id=user_id, type_=VoucherType.by_name("Issue"),) db.add(voucher) if quantity > 0: @@ -132,19 +114,9 @@ def create_voucher(batch, quantity, date_, user_id, db): db.add(inventory) amount = round(inventory.amount, 2) - source = Journal( - debit=-1, - account_id=AccountBase.all_purchases(), - amount=amount, - cost_centre_id=source, - ) + source = Journal(debit=-1, account_id=AccountBase.all_purchases(), amount=amount, cost_centre_id=source,) voucher.journals.append(source) db.add(source) - destination = Journal( - debit=1, - account_id=AccountBase.all_purchases(), - amount=amount, - cost_centre_id=destination, - ) + destination = Journal(debit=1, account_id=AccountBase.all_purchases(), amount=amount, cost_centre_id=destination,) voucher.journals.append(destination) db.add(destination) diff --git a/brewman/schemas/__init__.py b/brewman/schemas/__init__.py index 8bb04775..2a02c89c 100644 --- a/brewman/schemas/__init__.py +++ b/brewman/schemas/__init__.py @@ -1,5 +1,3 @@ def to_camel(string: str) -> str: first, *others = string.split("_") return "".join([first] + [word.capitalize() for word in others]) - - diff --git a/brewman/schemas/input.py b/brewman/schemas/input.py index 219793b9..d786da2d 100644 --- a/brewman/schemas/input.py +++ b/brewman/schemas/input.py @@ -45,9 +45,7 @@ class JournalIn(VoucherIn): @validator("journals") def is_distinct(cls, value: List[Journal]): journal_set = set( - hash(x.account.id_) - ^ hash(None if x.cost_centre is None else x.cost_centre.id_) - for x in value + hash(x.account.id_) ^ hash(None if x.cost_centre is None else x.cost_centre.id_) for x in value ) if len(value) != len(journal_set): raise ValueError("Duplicate journals") diff --git a/brewman/schemas/voucher.py b/brewman/schemas/voucher.py index a71dcb7b..ee9874bf 100644 --- a/brewman/schemas/voucher.py +++ b/brewman/schemas/voucher.py @@ -179,9 +179,7 @@ class Voucher(VoucherIn): @validator("journals") def is_distinct(cls, value: List[Journal]): journal_set = set( - hash(x.account.id_) - ^ hash(None if x.cost_centre is None else x.cost_centre.id_) - for x in value + hash(x.account.id_) ^ hash(None if x.cost_centre is None else x.cost_centre.id_) for x in value ) if len(value) != len(journal_set): raise ValueError("Duplicate journals") diff --git a/brewman/scripts/initializedb.py b/brewman/scripts/initializedb.py index 33f7b033..f5bfbaa1 100644 --- a/brewman/scripts/initializedb.py +++ b/brewman/scripts/initializedb.py @@ -45,10 +45,7 @@ from brewman.models.voucher import ( def usage(argv): cmd = os.path.basename(argv[0]) - print( - "usage: %s [var=value]\n" - '(example: "%s development.ini")' % (cmd, cmd) - ) + print("usage: %s [var=value]\n" '(example: "%s development.ini")' % (cmd, cmd)) sys.exit(1) @@ -68,17 +65,13 @@ def main(argv=sys.argv): with transaction.manager: dbsession = get_tm_session(session_factory, transaction.manager) - user = User( - "Admin", "123456", False, uuid.UUID("8de98592-76d9-c74d-bb3f-d6184d388b5a") - ) + user = User("Admin", "123456", False, uuid.UUID("8de98592-76d9-c74d-bb3f-d6184d388b5a")) dbsession.add(user) groups = [ Group("Owner", uuid.UUID("52e08c0c-048a-784f-be10-6e129ad4b5d4")), Group("Accountant", uuid.UUID("bc4c2d23-437a-984d-abd4-7d5fce677547")), - Group( - "Accounts Manager", uuid.UUID("cfc44fa7-3392-5b45-b311-5959333f568f") - ), + Group("Accounts Manager", uuid.UUID("cfc44fa7-3392-5b45-b311-5959333f568f")), ] for group in groups: @@ -92,19 +85,14 @@ def main(argv=sys.argv): Role("Cost Centres", uuid.UUID("6fcc1a20-6aec-e840-b334-1632b34aeab8")), Role("Users", uuid.UUID("c5b7d9d7-f178-0e45-8ea4-bf4e08ec901b")), Role("Daybook", uuid.UUID("c3edb554-a057-8942-8030-37b8e926d583")), - Role( - "Edit Posted Vouchers", - uuid.UUID("d6675817-ddf5-bf40-9de6-fa223eb4aaa6"), - ), + Role("Edit Posted Vouchers", uuid.UUID("d6675817-ddf5-bf40-9de6-fa223eb4aaa6"),), Role("Employees", uuid.UUID("e4edd0ac-7f5d-e64d-8611-73fdc4cd8ba2")), Role("Fingerprints", uuid.UUID("d9c45323-f997-ba46-9407-8a7145f0828b")), Role("Issue", uuid.UUID("03b602eb-f58a-b94f-af58-8cb47d7849d0")), Role("Journal", uuid.UUID("7661388f-62ce-1c41-8e0d-0326ee5d4018")), Role("Accounts", uuid.UUID("f438262f-72dd-2f4e-9186-5abc3af44fba")), Role("Product Ledger", uuid.UUID("018a2408-e804-1446-90c5-b015829da6ba")), - Role( - "Backdated Vouchers", uuid.UUID("b67b2062-5ca7-134f-8258-5d284dd92426") - ), + Role("Backdated Vouchers", uuid.UUID("b67b2062-5ca7-134f-8258-5d284dd92426")), Role("Payment", uuid.UUID("f85c0b52-c3fd-7141-8957-7a56cdc014a4")), Role("Post Vouchers", uuid.UUID("36e741da-1a57-b047-a59e-dcd58fcf4338")), Role("Products", uuid.UUID("74fa6d21-eebb-e14c-8153-bebc57190ab4")), @@ -117,13 +105,8 @@ def main(argv=sys.argv): Role("Recipes", uuid.UUID("ffb7fb65-d42c-424d-9ff1-45069e3b4a29")), Role("Closing Stock", uuid.UUID("97515732-24e4-c94d-9585-d4bd7f6c7891")), Role("Ledger", uuid.UUID("a2120944-243f-3f49-be57-0ad633ce4801")), - Role( - "Raw Material Cost", uuid.UUID("d462842b-baf1-2343-95e5-ffdba9bbc163") - ), - Role( - "Edit Other User's Vouchers", - uuid.UUID("a8328891-7ce2-a943-8c29-2eabc1ffeea3"), - ), + Role("Raw Material Cost", uuid.UUID("d462842b-baf1-2343-95e5-ffdba9bbc163")), + Role("Edit Other User's Vouchers", uuid.UUID("a8328891-7ce2-a943-8c29-2eabc1ffeea3"),), Role("Clients", uuid.UUID("cfad44f0-f2a9-7045-89d7-9019cf0f371a")), Role("Employee Benefit", uuid.UUID("92d70e80-1c32-384d-959e-abf84b804696")), Role("Messages", uuid.UUID("f586d128-b6d9-4090-a913-78fcbdb68e59")), @@ -146,15 +129,9 @@ def main(argv=sys.argv): groups[0].roles.append(role) cost_centres = [ - CostCentre( - "Overall", uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), True - ), - CostCentre( - "Purchase", uuid.UUID("7b845f95-dfef-fa4a-897c-f0baf15284a3"), True - ), - CostCentre( - "Kitchen", uuid.UUID("b2d398ce-e3cc-c542-9feb-5d7783e899df"), True - ), + CostCentre("Overall", uuid.UUID("36f59436-522a-0746-ae94-e0f746bf6c0d"), True), + CostCentre("Purchase", uuid.UUID("7b845f95-dfef-fa4a-897c-f0baf15284a3"), True), + CostCentre("Kitchen", uuid.UUID("b2d398ce-e3cc-c542-9feb-5d7783e899df"), True), ] for cost_centre in cost_centres: @@ -254,21 +231,11 @@ def main(argv=sys.argv): for account in accounts: dbsession.add(account) - product_group = ProductGroup( - "Suspense", uuid.UUID("ae59a20c-87bb-444a-8abb-915ad5e58b83"), True - ) + product_group = ProductGroup("Suspense", uuid.UUID("ae59a20c-87bb-444a-8abb-915ad5e58b83"), True) dbsession.add(product_group) - dbsession.add( - ProductGroup( - "Semi", uuid.UUID("e6bf81b9-1e9b-499f-81d5-ab5662e9d9b1"), True - ) - ) - dbsession.add( - ProductGroup( - "Menu Items", uuid.UUID("dad46805-f577-4e5b-8073-9b788e0173fc"), True - ) - ) + dbsession.add(ProductGroup("Semi", uuid.UUID("e6bf81b9-1e9b-499f-81d5-ab5662e9d9b1"), True)) + dbsession.add(ProductGroup("Menu Items", uuid.UUID("dad46805-f577-4e5b-8073-9b788e0173fc"), True)) product = Product( 1,