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