Blacked and isorted the python files
Prettied and eslinted the typescript/html files
This commit is contained in:
1 parent
b31db593c2
commit
d677cfb1ea
505 files changed
+7559
-5649
No files matched your search
@@ -1,3 +1,4 @@
|
||||
from barker.main import init
|
||||
|
||||
|
||||
init()
|
||||
@@ -1,7 +1,8 @@
|
||||
from dotenv import load_dotenv
|
||||
import secrets
|
||||
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from pydantic import BaseSettings, PostgresDsn, validator
|
||||
|
||||
|
||||
|
||||
@@ -1,23 +1,25 @@
|
||||
import uuid
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import List, Optional
|
||||
from jwt import PyJWTError
|
||||
|
||||
from fastapi import Depends, HTTPException, status, Security
|
||||
from fastapi.security import OAuth2PasswordBearer, SecurityScopes
|
||||
from pydantic import BaseModel, ValidationError
|
||||
from sqlalchemy.orm import Session
|
||||
from jose import jwt
|
||||
from jose.exceptions import ExpiredSignatureError
|
||||
|
||||
from barker.core.config import settings
|
||||
from barker.models.auth import User as UserModel, Client
|
||||
from ..db.session import SessionLocal
|
||||
from barker.models.auth import Client
|
||||
from barker.models.auth import User as UserModel
|
||||
from fastapi import Depends, HTTPException, Security, status
|
||||
from fastapi.security import OAuth2PasswordBearer, SecurityScopes
|
||||
from jose import jwt
|
||||
from jose.exceptions import ExpiredSignatureError
|
||||
from jwt import PyJWTError
|
||||
from pydantic import BaseModel, ValidationError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db.session import SessionLocal
|
||||
|
||||
# to get a string like this run:
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/token", scopes={})
|
||||
|
||||
|
||||
@@ -53,12 +55,20 @@ def create_access_token(*, data: dict, expires_delta: timedelta = None):
|
||||
else:
|
||||
expire = datetime.utcnow() + timedelta(minutes=15)
|
||||
to_encode.update({"exp": expire})
|
||||
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
encoded_jwt = jwt.encode(
|
||||
to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM
|
||||
)
|
||||
return encoded_jwt
|
||||
|
||||
|
||||
def get_user(username: str, id_: str, locked_out: bool, scopes: List[str]) -> UserToken:
|
||||
return UserToken(id_=uuid.UUID(id_), name=username, locked_out=locked_out, password="", permissions=scopes,)
|
||||
return UserToken(
|
||||
id_=uuid.UUID(id_),
|
||||
name=username,
|
||||
locked_out=locked_out,
|
||||
password="",
|
||||
permissions=scopes,
|
||||
)
|
||||
|
||||
|
||||
def authenticate_user(
|
||||
@@ -68,9 +78,15 @@ def authenticate_user(
|
||||
return user
|
||||
|
||||
|
||||
def client_allowed(user: UserModel, client_id: int, otp: Optional[int] = None, db: Session = None) -> (bool, int):
|
||||
client = db.query(Client).filter(Client.id == client_id).first() if client_id else None
|
||||
allowed = "clients" in set([p.name.replace(" ", "-").lower() for r in user.roles for p in r.permissions])
|
||||
def client_allowed(
|
||||
user: UserModel, client_id: int, otp: Optional[int] = None, db: Session = None
|
||||
) -> (bool, int):
|
||||
client = (
|
||||
db.query(Client).filter(Client.id == client_id).first() if client_id else None
|
||||
)
|
||||
allowed = "clients" in set(
|
||||
[p.name.replace(" ", "-").lower() for r in user.roles for p in r.permissions]
|
||||
)
|
||||
if allowed or True:
|
||||
return True, 0
|
||||
elif client is None:
|
||||
@@ -86,7 +102,10 @@ def client_allowed(user: UserModel, client_id: int, otp: Optional[int] = None, d
|
||||
return False, client.id
|
||||
|
||||
|
||||
async def get_current_user(security_scopes: SecurityScopes, token: str = Depends(oauth2_scheme),) -> UserToken:
|
||||
async def get_current_user(
|
||||
security_scopes: SecurityScopes,
|
||||
token: str = Depends(oauth2_scheme),
|
||||
) -> UserToken:
|
||||
if security_scopes.scopes:
|
||||
authenticate_value = f'Bearer scope="{security_scopes.scope_str}"'
|
||||
else:
|
||||
@@ -97,7 +116,9 @@ async def get_current_user(security_scopes: SecurityScopes, token: str = Depends
|
||||
headers={"WWW-Authenticate": authenticate_value},
|
||||
)
|
||||
try:
|
||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
payload = jwt.decode(
|
||||
token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
|
||||
)
|
||||
username: str = payload.get("sub")
|
||||
if username is None:
|
||||
raise credentials_exception
|
||||
|
||||
@@ -26,7 +26,9 @@ def get_finish_date(session):
|
||||
|
||||
def set_period(start, finish, session):
|
||||
session["start"] = start if isinstance(start, str) else start.strftime("%d-%b-%Y")
|
||||
session["finish"] = finish if isinstance(finish, str) else finish.strftime("%d-%b-%Y")
|
||||
session["finish"] = (
|
||||
finish if isinstance(finish, str) else finish.strftime("%d-%b-%Y")
|
||||
)
|
||||
|
||||
|
||||
def get_first_day(dt, d_years=0, d_months=0):
|
||||
|
||||
+16
-17
@@ -1,31 +1,30 @@
|
||||
# Import all the models, so that Base has them before being
|
||||
# imported by Alembic
|
||||
from barker.db.base_class import Base # noqa
|
||||
from brewman.models import (
|
||||
Client,
|
||||
user_group,
|
||||
role_group,
|
||||
User,
|
||||
LoginHistory,
|
||||
Role,
|
||||
Permission,
|
||||
Product,
|
||||
AttendanceType,
|
||||
CostCentre,
|
||||
Employee,
|
||||
from brewman.models import ( # noqa
|
||||
Account,
|
||||
AccountBase,
|
||||
AccountType,
|
||||
ProductGroup,
|
||||
Recipe,
|
||||
RecipeItem,
|
||||
Attendance,
|
||||
AttendanceType,
|
||||
Batch,
|
||||
Client,
|
||||
CostCentre,
|
||||
Employee,
|
||||
EmployeeBenefit,
|
||||
Fingerprint,
|
||||
Inventory,
|
||||
Journal,
|
||||
LoginHistory,
|
||||
Permission,
|
||||
Product,
|
||||
EmployeeBenefit,
|
||||
ProductGroup,
|
||||
Recipe,
|
||||
RecipeItem,
|
||||
Role,
|
||||
User,
|
||||
Voucher,
|
||||
VoucherType,
|
||||
) # noqa
|
||||
role_group,
|
||||
user_group,
|
||||
)
|
||||
@@ -1,6 +1,7 @@
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.schema import MetaData
|
||||
|
||||
|
||||
# Recommended naming convention used by Alembic, as various different database
|
||||
# providers will autogenerate vastly different names making migrations more
|
||||
# difficult. See: http://alembic.zzzcomputing.com/en/latest/naming.html
|
||||
|
||||
+112
-24
@@ -1,10 +1,19 @@
|
||||
import uuid
|
||||
|
||||
from barker.core.config import settings
|
||||
from barker.models import (
|
||||
Customer,
|
||||
DbSetting,
|
||||
ModifierCategory,
|
||||
Permission,
|
||||
Role,
|
||||
Section,
|
||||
SettleOption,
|
||||
User,
|
||||
)
|
||||
from brewman.db import base # noqa: F401
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from barker.core.config import settings
|
||||
from brewman.db import base # noqa: F401
|
||||
from barker.models import Permission, Section, ModifierCategory, SettleOption, Customer, DbSetting, Role, User
|
||||
|
||||
# make sure all SQL Alchemy models are imported (app.db.base) before initializing DB
|
||||
# otherwise, SQL Alchemy might fail to initialize relationships properly
|
||||
@@ -19,22 +28,75 @@ def init_db(db: Session) -> None:
|
||||
|
||||
prod = True
|
||||
if prod:
|
||||
db.add(Permission("Guest Book", uuid.UUID("7669dfc9-cc75-4e48-b267-145c8832a83c")))
|
||||
db.add(Permission("Printers", uuid.UUID("5b66c6f6-003a-4ef8-ba28-49b8ff1ac33c")))
|
||||
db.add(Permission("Sections", uuid.UUID("c973f32c-a37b-496a-8dc5-60d2e4c39e97")))
|
||||
db.add(Permission("Section Printers", uuid.UUID("7a04ba63-5d08-4078-9051-a6d91cce3e48"), ))
|
||||
db.add(
|
||||
Permission("Guest Book", uuid.UUID("7669dfc9-cc75-4e48-b267-145c8832a83c"))
|
||||
)
|
||||
db.add(
|
||||
Permission("Printers", uuid.UUID("5b66c6f6-003a-4ef8-ba28-49b8ff1ac33c"))
|
||||
)
|
||||
db.add(
|
||||
Permission("Sections", uuid.UUID("c973f32c-a37b-496a-8dc5-60d2e4c39e97"))
|
||||
)
|
||||
db.add(
|
||||
Permission(
|
||||
"Section Printers",
|
||||
uuid.UUID("7a04ba63-5d08-4078-9051-a6d91cce3e48"),
|
||||
)
|
||||
)
|
||||
else:
|
||||
add_permissions(db)
|
||||
|
||||
main_section = Section("Main", uuid.UUID("3f13f6e7-dc76-4fca-8fdb-b2bbf29b35df"))
|
||||
db.add(main_section)
|
||||
mcs = [
|
||||
ModifierCategory("Old Modifiers", 0, 0, True, 0, uuid.UUID("e046ad33-dc65-4c78-8833-c3d3538d44c0"), ),
|
||||
ModifierCategory("Bar Instructions", 0, 0, True, 0, uuid.UUID("b572f401-3c2f-48b9-8973-ada5a6e4d3a6"), ),
|
||||
ModifierCategory("Delivery", 0, 0, True, 0, uuid.UUID("caa72832-5034-405e-8442-68a8cc12ace9"), ),
|
||||
ModifierCategory("Kitchen Instructions", 0, 0, True, 0, uuid.UUID("d6a0595f-e209-42e4-bb12-b7499f9a9c4d"), ),
|
||||
ModifierCategory("Mixers", 0, 0, True, 0, uuid.UUID("60ca9122-adc5-463b-ad5f-33a68df8c3ae"), ),
|
||||
ModifierCategory("Pasta Sauce", 0, 0, True, 0, uuid.UUID("ef5b1a0b-5eb1-45ff-bd82-3209c8b888df"), ),
|
||||
ModifierCategory(
|
||||
"Old Modifiers",
|
||||
0,
|
||||
0,
|
||||
True,
|
||||
0,
|
||||
uuid.UUID("e046ad33-dc65-4c78-8833-c3d3538d44c0"),
|
||||
),
|
||||
ModifierCategory(
|
||||
"Bar Instructions",
|
||||
0,
|
||||
0,
|
||||
True,
|
||||
0,
|
||||
uuid.UUID("b572f401-3c2f-48b9-8973-ada5a6e4d3a6"),
|
||||
),
|
||||
ModifierCategory(
|
||||
"Delivery",
|
||||
0,
|
||||
0,
|
||||
True,
|
||||
0,
|
||||
uuid.UUID("caa72832-5034-405e-8442-68a8cc12ace9"),
|
||||
),
|
||||
ModifierCategory(
|
||||
"Kitchen Instructions",
|
||||
0,
|
||||
0,
|
||||
True,
|
||||
0,
|
||||
uuid.UUID("d6a0595f-e209-42e4-bb12-b7499f9a9c4d"),
|
||||
),
|
||||
ModifierCategory(
|
||||
"Mixers",
|
||||
0,
|
||||
0,
|
||||
True,
|
||||
0,
|
||||
uuid.UUID("60ca9122-adc5-463b-ad5f-33a68df8c3ae"),
|
||||
),
|
||||
ModifierCategory(
|
||||
"Pasta Sauce",
|
||||
0,
|
||||
0,
|
||||
True,
|
||||
0,
|
||||
uuid.UUID("ef5b1a0b-5eb1-45ff-bd82-3209c8b888df"),
|
||||
),
|
||||
]
|
||||
for item in mcs:
|
||||
db.add(item)
|
||||
@@ -53,7 +115,9 @@ def init_db(db: Session) -> None:
|
||||
]
|
||||
for option in options:
|
||||
db.add(option)
|
||||
db.add(Customer("", "Cash", "", "", uuid.UUID("2c716f4b-0736-429a-ad51-610d7c47cb5e")))
|
||||
db.add(
|
||||
Customer("", "Cash", "", "", uuid.UUID("2c716f4b-0736-429a-ad51-610d7c47cb5e"))
|
||||
)
|
||||
db.add(
|
||||
DbSetting(
|
||||
uuid.UUID("fb738ba2-a3c9-40ed-891c-b930e6454974"),
|
||||
@@ -83,21 +147,35 @@ def init_db(db: Session) -> None:
|
||||
def add_permissions(db: Session):
|
||||
permissions = [
|
||||
Permission("Accounts Audit", uuid.UUID("f30fd1fb-df09-46f5-8c5d-181fd46f38de")),
|
||||
Permission("Beer Consumption", uuid.UUID("efbb8f31-9631-4491-92f4-17cc98e6a0c0")),
|
||||
Permission(
|
||||
"Beer Consumption", uuid.UUID("efbb8f31-9631-4491-92f4-17cc98e6a0c0")
|
||||
),
|
||||
Permission("Bill Details", uuid.UUID("612bb529-b50d-4653-a1c0-ebb725c7d728")),
|
||||
Permission("Cashier Checkout", uuid.UUID("a86f8bcf-66f4-4c44-89e1-b714488b8331")),
|
||||
Permission(
|
||||
"Cashier Checkout", uuid.UUID("a86f8bcf-66f4-4c44-89e1-b714488b8331")
|
||||
),
|
||||
Permission("Change Rate", uuid.UUID("10c63aae-0e48-4e54-b3b8-dd8a80b88fbf")),
|
||||
Permission("Customers", uuid.UUID("e5fef133-cdbe-441f-bb54-1f0db0c5db79")),
|
||||
Permission("Discount", uuid.UUID("1f66f131-0105-4466-8f8e-21e0ccc2ac27")),
|
||||
Permission("Discount Report", uuid.UUID("0d8ba1d5-6731-417c-ab0e-be03cfdc96db")),
|
||||
Permission("Edit Printed Bill", uuid.UUID("4ff6cb0f-93cb-4760-8219-4de280eaa957")),
|
||||
Permission("Edit Printed Product", uuid.UUID("959713be-d753-4e14-8ecd-e27f33587499"),),
|
||||
Permission(
|
||||
"Discount Report", uuid.UUID("0d8ba1d5-6731-417c-ab0e-be03cfdc96db")
|
||||
),
|
||||
Permission(
|
||||
"Edit Printed Bill", uuid.UUID("4ff6cb0f-93cb-4760-8219-4de280eaa957")
|
||||
),
|
||||
Permission(
|
||||
"Edit Printed Product",
|
||||
uuid.UUID("959713be-d753-4e14-8ecd-e27f33587499"),
|
||||
),
|
||||
Permission("Guest Book", uuid.UUID("7669dfc9-cc75-4e48-b267-145c8832a83c")),
|
||||
Permission("Machines", uuid.UUID("f12b573f-edcb-490d-91c3-fa76f6502ffd")),
|
||||
Permission("Merge Kots", uuid.UUID("bed774e9-4857-43b0-a4af-40230c9eb5db")),
|
||||
Permission("Merge Tables", uuid.UUID("dfc493fb-ac14-4602-8596-f93f47b617de")),
|
||||
Permission("Modifiers", uuid.UUID("9dc82529-1e86-41b4-a152-eaea9f775fea")),
|
||||
Permission("Move Kot to New Table", uuid.UUID("5ed5796a-ca99-437f-8f67-483b1ade81ed"),),
|
||||
Permission(
|
||||
"Move Kot to New Table",
|
||||
uuid.UUID("5ed5796a-ca99-437f-8f67-483b1ade81ed"),
|
||||
),
|
||||
Permission("Move Table", uuid.UUID("cfdb69c9-d37a-40af-bef2-e29c04602543")),
|
||||
Permission("NC Product", uuid.UUID("54263587-773e-4cbb-b1e4-4e814141158e")),
|
||||
Permission("Open Bill", uuid.UUID("5811d233-a1ae-4d32-af52-cebbf46d274a")),
|
||||
@@ -116,7 +194,10 @@ def add_permissions(db: Session):
|
||||
Permission("Taxes", uuid.UUID("5c8fcdde-460d-4047-810f-e34fb899fadc")),
|
||||
Permission("Users", uuid.UUID("243447b8-b403-47e6-8b3d-8e76f4df44a9")),
|
||||
Permission("Void Bill", uuid.UUID("e3c76262-adc0-4936-8b4d-217c6292298b")),
|
||||
Permission("Void or Reprinted Bill Report", uuid.UUID("30c8e743-c710-42d7-843a-0b75543b3516"),),
|
||||
Permission(
|
||||
"Void or Reprinted Bill Report",
|
||||
uuid.UUID("30c8e743-c710-42d7-843a-0b75543b3516"),
|
||||
),
|
||||
Permission("Printers", uuid.UUID("5b66c6f6-003a-4ef8-ba28-49b8ff1ac33c")),
|
||||
Permission("Sections", uuid.UUID("c973f32c-a37b-496a-8dc5-60d2e4c39e97")),
|
||||
]
|
||||
@@ -137,12 +218,19 @@ def add_permissions(db: Session):
|
||||
]
|
||||
|
||||
roles[0].permissions = permissions
|
||||
roles[1].permissions = list(permissions[i] for i in [2, 3, 11, 18, 24, 25, 26, 30, 34])
|
||||
roles[1].permissions = list(
|
||||
permissions[i] for i in [2, 3, 11, 18, 24, 25, 26, 30, 34]
|
||||
)
|
||||
roles[2].permissions = list(permissions[i] for i in [26])
|
||||
roles[3].permissions = list(permissions[i] for i in [16])
|
||||
roles[4].permissions = list(permissions[i] for i in [20, 24, 27])
|
||||
roles[5].permissions = list(permissions[i] for i in [0, 2, 7, 11, 18, 22, 24, 25, 26, 34])
|
||||
roles[6].permissions = list(permissions[i] for i in [2, 3, 4, 5, 6, 8, 11, 14, 18, 22, 25, 26, 28, 29, 33, 34])
|
||||
roles[5].permissions = list(
|
||||
permissions[i] for i in [0, 2, 7, 11, 18, 22, 24, 25, 26, 34]
|
||||
)
|
||||
roles[6].permissions = list(
|
||||
permissions[i]
|
||||
for i in [2, 3, 4, 5, 6, 8, 11, 14, 18, 22, 25, 26, 28, 29, 33, 34]
|
||||
)
|
||||
roles[7].permissions = list(permissions[i] for i in [9, 12, 13, 15, 16])
|
||||
roles[8].permissions = list(permissions[i] for i in [21, 24])
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import logging
|
||||
|
||||
from barker.core.config import settings
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from barker.core.config import settings
|
||||
|
||||
logging.basicConfig()
|
||||
logging.getLogger("sqlalchemy.engine").setLevel(settings.LOG_LEVEL)
|
||||
|
||||
+48
-16
@@ -1,22 +1,26 @@
|
||||
import uvicorn
|
||||
|
||||
from fastapi import FastAPI
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
|
||||
from .core.config import settings
|
||||
from .db.base_class import Base
|
||||
from .db.session import engine
|
||||
from .routers import (
|
||||
guest_book,
|
||||
login,
|
||||
menu_category,
|
||||
modifier,
|
||||
modifier_category,
|
||||
printer,
|
||||
product,
|
||||
login,
|
||||
sale_category,
|
||||
section,
|
||||
section_printer,
|
||||
table,
|
||||
tax,
|
||||
)
|
||||
from .routers.auth import client, user, role
|
||||
from .routers.auth import client, role, user
|
||||
from .routers.reports import (
|
||||
beer_consumption_report,
|
||||
bill_settlement_report,
|
||||
@@ -24,13 +28,19 @@ from .routers.reports import (
|
||||
discount_report,
|
||||
product_sale_report,
|
||||
sale_report,
|
||||
tax_report
|
||||
tax_report,
|
||||
)
|
||||
from .routers.voucher import (
|
||||
change,
|
||||
merge_move,
|
||||
receive_payment,
|
||||
save,
|
||||
show,
|
||||
split,
|
||||
update,
|
||||
void,
|
||||
)
|
||||
from .routers.voucher import show, save, update, receive_payment, void, merge_move, split, change
|
||||
|
||||
from .db.base_class import Base
|
||||
from .core.config import settings
|
||||
from .db.session import engine
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
@@ -45,26 +55,48 @@ app.include_router(role.router, prefix="/api/roles", tags=["users"])
|
||||
app.include_router(user.router, prefix="/api/users", tags=["users"])
|
||||
|
||||
app.include_router(modifier.router, prefix="/api/modifiers", tags=["modifiers"])
|
||||
app.include_router(modifier_category.router, prefix="/api/modifier-categories", tags=["modifiers"])
|
||||
app.include_router(
|
||||
modifier_category.router, prefix="/api/modifier-categories", tags=["modifiers"]
|
||||
)
|
||||
|
||||
app.include_router(printer.router, prefix="/api/printers", tags=["printers"])
|
||||
|
||||
app.include_router(menu_category.router, prefix="/api/menu-categories", tags=["products"])
|
||||
app.include_router(
|
||||
menu_category.router, prefix="/api/menu-categories", tags=["products"]
|
||||
)
|
||||
app.include_router(product.router, prefix="/api/products", tags=["products"])
|
||||
app.include_router(sale_category.router, prefix="/api/sale-categories", tags=["products"])
|
||||
app.include_router(
|
||||
sale_category.router, prefix="/api/sale-categories", tags=["products"]
|
||||
)
|
||||
|
||||
app.include_router(section.router, prefix="/api/sections", tags=["sections"])
|
||||
app.include_router(section_printer.router, prefix="/api/section-printers", tags=["section-printers"])
|
||||
app.include_router(
|
||||
section_printer.router, prefix="/api/section-printers", tags=["section-printers"]
|
||||
)
|
||||
|
||||
app.include_router(tax.router, prefix="/api/taxes", tags=["taxes"])
|
||||
|
||||
app.include_router(table.router, prefix="/api/tables", tags=["tables"])
|
||||
|
||||
app.include_router(beer_consumption_report.router, prefix="/api/beer-consumption-report", tags=["reports"])
|
||||
app.include_router(bill_settlement_report.router, prefix="/api/bill-settlement-report", tags=["reports"])
|
||||
app.include_router(cashier_report.router, prefix="/api/cashier-report", tags=["reports"])
|
||||
app.include_router(discount_report.router, prefix="/api/discount-report", tags=["reports"])
|
||||
app.include_router(product_sale_report.router, prefix="/api/product-sale-report", tags=["reports"])
|
||||
app.include_router(
|
||||
beer_consumption_report.router,
|
||||
prefix="/api/beer-consumption-report",
|
||||
tags=["reports"],
|
||||
)
|
||||
app.include_router(
|
||||
bill_settlement_report.router,
|
||||
prefix="/api/bill-settlement-report",
|
||||
tags=["reports"],
|
||||
)
|
||||
app.include_router(
|
||||
cashier_report.router, prefix="/api/cashier-report", tags=["reports"]
|
||||
)
|
||||
app.include_router(
|
||||
discount_report.router, prefix="/api/discount-report", tags=["reports"]
|
||||
)
|
||||
app.include_router(
|
||||
product_sale_report.router, prefix="/api/product-sale-report", tags=["reports"]
|
||||
)
|
||||
app.include_router(sale_report.router, prefix="/api/sale-report", tags=["reports"])
|
||||
app.include_router(tax_report.router, prefix="/api/tax-report", tags=["reports"])
|
||||
|
||||
|
||||
@@ -1,6 +1,23 @@
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.orm import configure_mappers
|
||||
from sqlalchemy.orm import configure_mappers, sessionmaker
|
||||
|
||||
from .auth import Client, Permission, Role, User, role_permissions, user_roles
|
||||
from .master import (
|
||||
Customer,
|
||||
DbSetting,
|
||||
Device,
|
||||
FoodTable,
|
||||
MenuCategory,
|
||||
Modifier,
|
||||
ModifierCategory,
|
||||
Printer,
|
||||
Product,
|
||||
SaleCategory,
|
||||
Section,
|
||||
SectionPrinter,
|
||||
SettleOption,
|
||||
Tax,
|
||||
)
|
||||
|
||||
# import or define all models here to ensure they are attached to the
|
||||
# Base.metadata prior to any initialization routines
|
||||
@@ -15,30 +32,7 @@ from .voucher import (
|
||||
Voucher,
|
||||
VoucherType,
|
||||
)
|
||||
from .master import (
|
||||
Customer,
|
||||
DbSetting,
|
||||
Device,
|
||||
FoodTable,
|
||||
MenuCategory,
|
||||
Modifier,
|
||||
ModifierCategory,
|
||||
Printer,
|
||||
Product,
|
||||
Section,
|
||||
SectionPrinter,
|
||||
SaleCategory,
|
||||
SettleOption,
|
||||
Tax,
|
||||
)
|
||||
from .auth import (
|
||||
Client,
|
||||
Permission,
|
||||
Role,
|
||||
role_permissions,
|
||||
User,
|
||||
user_roles,
|
||||
)
|
||||
|
||||
|
||||
# run configure_mappers after defining all of the models to ensure
|
||||
# all relationships can be setup
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import random
|
||||
import string
|
||||
import uuid
|
||||
from hashlib import md5
|
||||
|
||||
from datetime import datetime
|
||||
from hashlib import md5
|
||||
|
||||
from sqlalchemy.schema import ForeignKey, Table
|
||||
from sqlalchemy import Column, Boolean, Unicode, Integer, DateTime, UniqueConstraint
|
||||
from sqlalchemy.orm import synonym, relationship, Session
|
||||
|
||||
from sqlalchemy import Boolean, Column, DateTime, Integer, Unicode, UniqueConstraint
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Session, relationship, synonym
|
||||
from sqlalchemy.schema import ForeignKey, Table
|
||||
|
||||
from .meta import Base
|
||||
|
||||
|
||||
@@ -25,7 +26,9 @@ class Client(Base):
|
||||
otp = Column("otp", Integer)
|
||||
creation_date = Column("creation_date", DateTime(timezone=True), nullable=False)
|
||||
|
||||
def __init__(self, id_=None, name=None, enabled=False, otp=None, creation_date=None):
|
||||
def __init__(
|
||||
self, id_=None, name=None, enabled=False, otp=None, creation_date=None
|
||||
):
|
||||
self.id = id_
|
||||
self.name = name
|
||||
self.enabled = enabled
|
||||
@@ -44,7 +47,9 @@ class Client(Base):
|
||||
def create(cls, db: Session):
|
||||
client_code = random.randint(1000, 9999)
|
||||
otp = random.randint(1000, 9999)
|
||||
name = "".join(random.choice(string.ascii_uppercase + string.digits) for x in range(6))
|
||||
name = "".join(
|
||||
random.choice(string.ascii_uppercase + string.digits) for x in range(6)
|
||||
)
|
||||
client = Client(client_code, name, False, otp)
|
||||
db.add(client)
|
||||
return client
|
||||
@@ -63,7 +68,12 @@ role_permissions = Table(
|
||||
"role_permissions",
|
||||
Base.metadata,
|
||||
Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4),
|
||||
Column("permission_id", UUID(as_uuid=True), ForeignKey("permissions.id"), nullable=False),
|
||||
Column(
|
||||
"permission_id",
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("permissions.id"),
|
||||
nullable=False,
|
||||
),
|
||||
Column("role_id", UUID(as_uuid=True), ForeignKey("roles.id"), nullable=False),
|
||||
UniqueConstraint("permission_id", "role_id"),
|
||||
)
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import (
|
||||
UniqueConstraint,
|
||||
Column,
|
||||
Unicode,
|
||||
Numeric,
|
||||
JSON,
|
||||
Boolean,
|
||||
Column,
|
||||
ForeignKey,
|
||||
Integer,
|
||||
case,
|
||||
JSON,
|
||||
Numeric,
|
||||
Table,
|
||||
Unicode,
|
||||
UniqueConstraint,
|
||||
case,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.ext.hybrid import hybrid_property
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from .meta import Base
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
|
||||
|
||||
class Customer(Base):
|
||||
__tablename__ = "customers"
|
||||
@@ -48,7 +50,9 @@ class FoodTable(Base):
|
||||
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
name = Column("name", Unicode(255), nullable=False, unique=True)
|
||||
seats = Column("seats", Integer, nullable=False)
|
||||
section_id = Column("section_id", UUID(as_uuid=True), ForeignKey("sections.id"), nullable=False)
|
||||
section_id = Column(
|
||||
"section_id", UUID(as_uuid=True), ForeignKey("sections.id"), nullable=False
|
||||
)
|
||||
is_active = Column("is_active", Boolean, nullable=False)
|
||||
sort_order = Column("sort_order", Integer, nullable=False)
|
||||
|
||||
@@ -59,7 +63,13 @@ class FoodTable(Base):
|
||||
return self.name
|
||||
|
||||
def __init__(
|
||||
self, name=None, seats=None, section_id=None, is_active=None, sort_order=0, id_=None,
|
||||
self,
|
||||
name=None,
|
||||
seats=None,
|
||||
section_id=None,
|
||||
is_active=None,
|
||||
sort_order=0,
|
||||
id_=None,
|
||||
):
|
||||
self.name = name
|
||||
self.seats = seats
|
||||
@@ -95,7 +105,9 @@ class MenuCategory(Base):
|
||||
is_fixture = Column("is_fixture", Boolean, nullable=False)
|
||||
sort_order = Column("sort_order", Integer, nullable=False)
|
||||
|
||||
def __init__(self, name, discount_limit, is_active, sort_order, is_fixture=False, id_=None):
|
||||
def __init__(
|
||||
self, name, discount_limit, is_active, sort_order, is_fixture=False, id_=None
|
||||
):
|
||||
self.name = name
|
||||
self.discount_limit = discount_limit
|
||||
self.is_active = is_active
|
||||
@@ -109,7 +121,9 @@ class SaleCategory(Base):
|
||||
|
||||
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
name = Column("name", Unicode(255), nullable=False, unique=True)
|
||||
tax_id = Column("tax_id", UUID(as_uuid=True), ForeignKey("taxes.id"), nullable=False)
|
||||
tax_id = Column(
|
||||
"tax_id", UUID(as_uuid=True), ForeignKey("taxes.id"), nullable=False
|
||||
)
|
||||
tax = relationship("Tax", foreign_keys=tax_id)
|
||||
|
||||
def __init__(self, name, tax_id=False, id_=None):
|
||||
@@ -125,8 +139,18 @@ class Product(Base):
|
||||
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
name = Column("name", Unicode(255), nullable=False)
|
||||
units = Column("units", Unicode(255), nullable=False)
|
||||
menu_category_id = Column("menu_category_id", UUID(as_uuid=True), ForeignKey("menu_categories.id"), nullable=False)
|
||||
sale_category_id = Column("sale_category_id", UUID(as_uuid=True), ForeignKey("sale_categories.id"), nullable=False)
|
||||
menu_category_id = Column(
|
||||
"menu_category_id",
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("menu_categories.id"),
|
||||
nullable=False,
|
||||
)
|
||||
sale_category_id = Column(
|
||||
"sale_category_id",
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("sale_categories.id"),
|
||||
nullable=False,
|
||||
)
|
||||
price = Column("price", Numeric, nullable=False)
|
||||
has_happy_hour = Column("has_happy_hour", Boolean, nullable=False)
|
||||
is_not_available = Column("is_not_available", Boolean, nullable=False)
|
||||
@@ -192,7 +216,12 @@ modifier_categories_products = Table(
|
||||
Base.metadata,
|
||||
Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4),
|
||||
Column("product_id", UUID(as_uuid=True), ForeignKey("products.id"), nullable=False),
|
||||
Column("modifier_categories_id", UUID(as_uuid=True), ForeignKey("modifier_categories.id"), nullable=False,),
|
||||
Column(
|
||||
"modifier_categories_id",
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("modifier_categories.id"),
|
||||
nullable=False,
|
||||
),
|
||||
UniqueConstraint("product_id", "modifier_categories_id"),
|
||||
)
|
||||
|
||||
@@ -208,7 +237,13 @@ class ModifierCategory(Base):
|
||||
sort_order = Column("sort_order", Integer, nullable=False)
|
||||
|
||||
def __init__(
|
||||
self, name=None, minimum=None, maximum=None, is_active=True, sort_order=0, id_=None,
|
||||
self,
|
||||
name=None,
|
||||
minimum=None,
|
||||
maximum=None,
|
||||
is_active=True,
|
||||
sort_order=0,
|
||||
id_=None,
|
||||
):
|
||||
self.id = id_
|
||||
self.name = name
|
||||
@@ -226,12 +261,23 @@ class Modifier(Base):
|
||||
show_in_bill = Column("show_in_bill", Boolean, nullable=False)
|
||||
price = Column("price", Numeric, nullable=False)
|
||||
is_active = Column("is_active", Boolean, nullable=False)
|
||||
modifier_category_id = Column("modifier_category_id", UUID(as_uuid=True), ForeignKey("modifier_categories.id"), nullable=False,)
|
||||
modifier_category_id = Column(
|
||||
"modifier_category_id",
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("modifier_categories.id"),
|
||||
nullable=False,
|
||||
)
|
||||
|
||||
modifier_category = relationship("ModifierCategory", backref="modifiers")
|
||||
|
||||
def __init__(
|
||||
self, name=None, show_in_bill=None, price=None, modifier_category_id=None, is_active=True, id_=None,
|
||||
self,
|
||||
name=None,
|
||||
show_in_bill=None,
|
||||
price=None,
|
||||
modifier_category_id=None,
|
||||
is_active=True,
|
||||
id_=None,
|
||||
):
|
||||
self.id = id_
|
||||
self.name = name
|
||||
@@ -270,7 +316,9 @@ class Device(Base):
|
||||
|
||||
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
name = Column("name", Unicode(255), unique=True, nullable=False)
|
||||
section_id = Column("section_id", UUID(as_uuid=True), ForeignKey("sections.id"), nullable=False)
|
||||
section_id = Column(
|
||||
"section_id", UUID(as_uuid=True), ForeignKey("sections.id"), nullable=False
|
||||
)
|
||||
|
||||
section = relationship("Section", foreign_keys=section_id)
|
||||
|
||||
@@ -300,16 +348,29 @@ class SectionPrinter(Base):
|
||||
__table_args__ = (UniqueConstraint("menu_category_id", "section_id"),)
|
||||
|
||||
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
menu_category_id = Column("menu_category_id", UUID(as_uuid=True), ForeignKey("menu_categories.id"))
|
||||
section_id = Column("section_id", UUID(as_uuid=True), ForeignKey("sections.id"), nullable=False)
|
||||
printer_id = Column("printer_id", UUID(as_uuid=True), ForeignKey("printers.id"), nullable=False)
|
||||
menu_category_id = Column(
|
||||
"menu_category_id", UUID(as_uuid=True), ForeignKey("menu_categories.id")
|
||||
)
|
||||
section_id = Column(
|
||||
"section_id", UUID(as_uuid=True), ForeignKey("sections.id"), nullable=False
|
||||
)
|
||||
printer_id = Column(
|
||||
"printer_id", UUID(as_uuid=True), ForeignKey("printers.id"), nullable=False
|
||||
)
|
||||
copies = Column("copies", Integer, nullable=False)
|
||||
|
||||
menu_category = relationship("MenuCategory", backref="section_printers")
|
||||
section = relationship("Section", backref="section_printers")
|
||||
printer = relationship("Printer", backref="section_printers")
|
||||
|
||||
def __init__(self, menu_category_id=None, section_id=None, printer_id=None, copies=None, id_=None):
|
||||
def __init__(
|
||||
self,
|
||||
menu_category_id=None,
|
||||
section_id=None,
|
||||
printer_id=None,
|
||||
copies=None,
|
||||
id_=None,
|
||||
):
|
||||
self.id = id_
|
||||
self.menu_category_id = menu_category_id
|
||||
self.section_id = section_id
|
||||
@@ -326,7 +387,14 @@ class SettleOption(Base):
|
||||
display_group = Column("display_group", Integer, nullable=False)
|
||||
is_print = Column("is_print", Boolean, nullable=False)
|
||||
|
||||
def __init__(self, name=None, show_in_choices=None, display_group=None, is_print=None, id_=None):
|
||||
def __init__(
|
||||
self,
|
||||
name=None,
|
||||
show_in_choices=None,
|
||||
display_group=None,
|
||||
is_print=None,
|
||||
id_=None,
|
||||
):
|
||||
self.id = id_
|
||||
self.name = name
|
||||
self.show_in_choices = show_in_choices
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.schema import MetaData
|
||||
|
||||
|
||||
# Recommended naming convention used by Alembic, as various different database
|
||||
# providers will autogenerate vastly different names making migrations more
|
||||
# difficult. See: http://alembic.zzzcomputing.com/en/latest/naming.html
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from datetime import timedelta, tzinfo, datetime
|
||||
from datetime import datetime, timedelta, tzinfo
|
||||
|
||||
|
||||
ZERO = timedelta(0)
|
||||
HOUR = timedelta(hours=1)
|
||||
|
||||
+133
-34
@@ -1,22 +1,24 @@
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy.ext.hybrid import hybrid_property
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
|
||||
from sqlalchemy import (
|
||||
Column,
|
||||
Integer,
|
||||
Boolean,
|
||||
Unicode,
|
||||
Column,
|
||||
DateTime,
|
||||
Numeric,
|
||||
ForeignKey,
|
||||
Integer,
|
||||
Numeric,
|
||||
Unicode,
|
||||
UniqueConstraint,
|
||||
case,
|
||||
)
|
||||
from sqlalchemy.orm import relationship, backref, synonym
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.ext.hybrid import hybrid_property
|
||||
from sqlalchemy.orm import backref, relationship, synonym
|
||||
|
||||
from .meta import Base
|
||||
|
||||
|
||||
@@ -31,7 +33,9 @@ class VoucherType(Enum):
|
||||
class GuestBook(Base):
|
||||
__tablename__ = "guest_book"
|
||||
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
customer_id = Column("customer_id", UUID(as_uuid=True), ForeignKey("customers.id"), nullable=False)
|
||||
customer_id = Column(
|
||||
"customer_id", UUID(as_uuid=True), ForeignKey("customers.id"), nullable=False
|
||||
)
|
||||
pax = Column("pax", Numeric, nullable=False)
|
||||
date = Column("creation_date", DateTime(timezone=True), nullable=False)
|
||||
|
||||
@@ -48,13 +52,26 @@ class GuestBook(Base):
|
||||
self.customer = customer
|
||||
|
||||
|
||||
|
||||
class Overview(Base):
|
||||
__tablename__ = "overview"
|
||||
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
voucher_id = Column("voucher_id", UUID(as_uuid=True), ForeignKey("vouchers.id"), nullable=False, unique=True)
|
||||
food_table_id = Column("food_table_id", UUID(as_uuid=True), ForeignKey("food_tables.id"), nullable=False, unique=True,)
|
||||
guest_book_id = Column("guest_book_id", UUID(as_uuid=True), ForeignKey("guest_book.id"), unique=True)
|
||||
voucher_id = Column(
|
||||
"voucher_id",
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("vouchers.id"),
|
||||
nullable=False,
|
||||
unique=True,
|
||||
)
|
||||
food_table_id = Column(
|
||||
"food_table_id",
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("food_tables.id"),
|
||||
nullable=False,
|
||||
unique=True,
|
||||
)
|
||||
guest_book_id = Column(
|
||||
"guest_book_id", UUID(as_uuid=True), ForeignKey("guest_book.id"), unique=True
|
||||
)
|
||||
status = Column("status", Unicode(255), nullable=False)
|
||||
|
||||
voucher = relationship("Voucher", backref=backref("status", uselist=False))
|
||||
@@ -74,8 +91,12 @@ class InventoryModifier(Base):
|
||||
__table_args__ = (UniqueConstraint("inventory_id", "modifier_id"),)
|
||||
|
||||
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
inventory_id = Column("inventory_id", UUID(as_uuid=True), ForeignKey("inventories.id"), nullable=False)
|
||||
modifier_id = Column("modifier_id", UUID(as_uuid=True), ForeignKey("modifiers.id"), nullable=False)
|
||||
inventory_id = Column(
|
||||
"inventory_id", UUID(as_uuid=True), ForeignKey("inventories.id"), nullable=False
|
||||
)
|
||||
modifier_id = Column(
|
||||
"modifier_id", UUID(as_uuid=True), ForeignKey("modifiers.id"), nullable=False
|
||||
)
|
||||
price = Column("price", Numeric, nullable=False)
|
||||
|
||||
inventory = relationship("Inventory", backref="modifiers")
|
||||
@@ -98,22 +119,42 @@ class Voucher(Base):
|
||||
kot_id = Column("kot_id", Numeric, nullable=False, unique=True)
|
||||
creation_date = Column("creation_date", DateTime(timezone=True), nullable=False)
|
||||
last_edit_date = Column("last_edit_date", DateTime(timezone=True), nullable=False)
|
||||
food_table_id = Column("food_table_id", UUID(as_uuid=True), ForeignKey("food_tables.id"), nullable=False)
|
||||
food_table_id = Column(
|
||||
"food_table_id",
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("food_tables.id"),
|
||||
nullable=False,
|
||||
)
|
||||
customer_id = Column("customer_id", UUID(as_uuid=True), ForeignKey("customers.id"))
|
||||
narration = Column("narration", Unicode(1000), nullable=False)
|
||||
reason = Column("reason", Unicode(255))
|
||||
_voucher_type = Column("voucher_type", Integer, nullable=False)
|
||||
user_id = Column("user_id", UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
|
||||
user_id = Column(
|
||||
"user_id", UUID(as_uuid=True), ForeignKey("users.id"), nullable=False
|
||||
)
|
||||
|
||||
user = relationship("User", backref="vouchers")
|
||||
food_table = relationship("FoodTable", backref="vouchers")
|
||||
customer = relationship("Customer", backref="vouchers")
|
||||
|
||||
kots = relationship("Kot", backref="voucher", cascade="delete, delete-orphan", cascade_backrefs=False,)
|
||||
kots = relationship(
|
||||
"Kot",
|
||||
backref="voucher",
|
||||
cascade="delete, delete-orphan",
|
||||
cascade_backrefs=False,
|
||||
)
|
||||
settlements = relationship(
|
||||
"Settlement", backref="voucher", cascade="delete, delete-orphan", cascade_backrefs=False,
|
||||
"Settlement",
|
||||
backref="voucher",
|
||||
cascade="delete, delete-orphan",
|
||||
cascade_backrefs=False,
|
||||
)
|
||||
reprints = relationship(
|
||||
"Reprint",
|
||||
backref="voucher",
|
||||
cascade="delete, delete-orphan",
|
||||
cascade_backrefs=False,
|
||||
)
|
||||
reprints = relationship("Reprint", backref="voucher", cascade="delete, delete-orphan", cascade_backrefs=False,)
|
||||
|
||||
def _get_voucher_type(self):
|
||||
return VoucherType(self._voucher_type)
|
||||
@@ -125,7 +166,15 @@ class Voucher(Base):
|
||||
voucher_type = synonym("_voucher_type", descriptor=voucher_type)
|
||||
|
||||
def __init__(
|
||||
self, date, pax, bill_id, kot_id, food_table_id, customer_id, voucher_type, user_id,
|
||||
self,
|
||||
date,
|
||||
pax,
|
||||
bill_id,
|
||||
kot_id,
|
||||
food_table_id,
|
||||
customer_id,
|
||||
voucher_type,
|
||||
user_id,
|
||||
):
|
||||
self.date = date
|
||||
self.pax = pax
|
||||
@@ -163,17 +212,36 @@ class Kot(Base):
|
||||
__tablename__ = "kots"
|
||||
|
||||
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
voucher_id = Column("voucher_id", UUID(as_uuid=True), ForeignKey("vouchers.id"), nullable=False, index=True)
|
||||
voucher_id = Column(
|
||||
"voucher_id",
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("vouchers.id"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
code = Column("code", Numeric, nullable=False, unique=True)
|
||||
food_table_id = Column("food_table_id", UUID(as_uuid=True), ForeignKey("food_tables.id"), nullable=False)
|
||||
food_table_id = Column(
|
||||
"food_table_id",
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("food_tables.id"),
|
||||
nullable=False,
|
||||
)
|
||||
date = Column("date", DateTime, nullable=False, index=True)
|
||||
user_id = Column("user_id", UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
|
||||
user_id = Column(
|
||||
"user_id", UUID(as_uuid=True), ForeignKey("users.id"), nullable=False
|
||||
)
|
||||
|
||||
user = relationship("User", backref="kots")
|
||||
food_table = relationship("FoodTable", backref="kots")
|
||||
|
||||
def __init__(
|
||||
self, voucher_id=None, code=None, food_table_id=None, date=None, user_id=None, id_=None,
|
||||
self,
|
||||
voucher_id=None,
|
||||
code=None,
|
||||
food_table_id=None,
|
||||
date=None,
|
||||
user_id=None,
|
||||
id_=None,
|
||||
):
|
||||
self.id = id_
|
||||
self.voucher_id = voucher_id
|
||||
@@ -188,7 +256,13 @@ class Settlement(Base):
|
||||
__table_args__ = (UniqueConstraint("voucher_id", "settled"),)
|
||||
|
||||
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
voucher_id = Column("voucher_id", UUID(as_uuid=True), ForeignKey("vouchers.id"), nullable=False, index=True)
|
||||
voucher_id = Column(
|
||||
"voucher_id",
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("vouchers.id"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
settled = Column("settled", ForeignKey("settle_options.id"), nullable=False)
|
||||
amount = Column("amount", Numeric, nullable=False)
|
||||
|
||||
@@ -206,8 +280,16 @@ class Reprint(Base):
|
||||
|
||||
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
date = Column("date", DateTime, nullable=False, index=True)
|
||||
voucher_id = Column("voucher_id", UUID(as_uuid=True), ForeignKey("vouchers.id"), nullable=False, index=True)
|
||||
user_id = Column("user_id", UUID(as_uuid=True), ForeignKey("users.id"), nullable=False)
|
||||
voucher_id = Column(
|
||||
"voucher_id",
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("vouchers.id"),
|
||||
nullable=False,
|
||||
index=True,
|
||||
)
|
||||
user_id = Column(
|
||||
"user_id", UUID(as_uuid=True), ForeignKey("users.id"), nullable=False
|
||||
)
|
||||
|
||||
user = relationship("User", backref="reprints")
|
||||
|
||||
@@ -220,16 +302,24 @@ class Reprint(Base):
|
||||
|
||||
class Inventory(Base):
|
||||
__tablename__ = "inventories"
|
||||
__table_args__ = (UniqueConstraint("kot_id", "product_id", "is_happy_hour", "price"),)
|
||||
__table_args__ = (
|
||||
UniqueConstraint("kot_id", "product_id", "is_happy_hour", "price"),
|
||||
)
|
||||
|
||||
id = Column("id", UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||
kot_id = Column("kot_id", UUID(as_uuid=True), ForeignKey("kots.id"), nullable=False, index=True)
|
||||
product_id = Column("product_id", UUID(as_uuid=True), ForeignKey("products.id"), nullable=False)
|
||||
kot_id = Column(
|
||||
"kot_id", UUID(as_uuid=True), ForeignKey("kots.id"), nullable=False, index=True
|
||||
)
|
||||
product_id = Column(
|
||||
"product_id", UUID(as_uuid=True), ForeignKey("products.id"), nullable=False
|
||||
)
|
||||
quantity = Column("quantity", Numeric)
|
||||
price = Column("price", Numeric)
|
||||
is_happy_hour = Column("is_happy_hour", Boolean, nullable=False)
|
||||
tax_rate = Column("tax_rate", Numeric)
|
||||
tax_id = Column("tax_id", UUID(as_uuid=True), ForeignKey("taxes.id"), nullable=False)
|
||||
tax_id = Column(
|
||||
"tax_id", UUID(as_uuid=True), ForeignKey("taxes.id"), nullable=False
|
||||
)
|
||||
discount = Column("discount", Numeric)
|
||||
sort_order = Column("sort_order", Numeric, nullable=False)
|
||||
|
||||
@@ -238,7 +328,16 @@ class Inventory(Base):
|
||||
product = relationship("Product", backref="inventories")
|
||||
|
||||
def __init__(
|
||||
self, kot_id, product_id, quantity, price, discount, is_hh, tax_id, tax_rate, sort_order,
|
||||
self,
|
||||
kot_id,
|
||||
product_id,
|
||||
quantity,
|
||||
price,
|
||||
discount,
|
||||
is_hh,
|
||||
tax_id,
|
||||
tax_rate,
|
||||
sort_order,
|
||||
):
|
||||
self.kot_id = kot_id
|
||||
self.product_id = product_id
|
||||
|
||||
@@ -1,3 +1,2 @@
|
||||
from barker.printing.bill import print_bill # noqa: F401
|
||||
from barker.printing.kot import print_kot # noqa: F401
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import uuid
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import List, Tuple
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from barker.models import SectionPrinter, Printer, Voucher, Inventory, DbSetting, VoucherType
|
||||
from barker.models import (
|
||||
DbSetting,
|
||||
Inventory,
|
||||
Printer,
|
||||
SectionPrinter,
|
||||
Voucher,
|
||||
VoucherType,
|
||||
)
|
||||
from barker.worker import sent_to_printer
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
|
||||
def print_bill(voucher_id: uuid.UUID, db: Session):
|
||||
@@ -22,7 +29,11 @@ def print_bill(voucher_id: uuid.UUID, db: Session):
|
||||
items_dict = {}
|
||||
tax = {}
|
||||
for i in [i for k in voucher.kots for i in k.inventories]:
|
||||
key = (i.product_id, i.is_happy_hour, tuple(m.modifier_id for m in i.modifiers if m.modifier.show_in_bill))
|
||||
key = (
|
||||
i.product_id,
|
||||
i.is_happy_hour,
|
||||
tuple(m.modifier_id for m in i.modifiers if m.modifier.show_in_bill),
|
||||
)
|
||||
if key in items_dict:
|
||||
items_dict[key].quantity += i.quantity
|
||||
else:
|
||||
@@ -35,9 +46,17 @@ def print_bill(voucher_id: uuid.UUID, db: Session):
|
||||
sent_to_printer.delay(data, printer.address, printer.cut_code)
|
||||
|
||||
|
||||
def design_bill(voucher: Voucher, items: List[Tuple[Inventory, Decimal]], tax: List[Tuple[str, Decimal]], db: Session):
|
||||
def design_bill(
|
||||
voucher: Voucher,
|
||||
items: List[Tuple[Inventory, Decimal]],
|
||||
tax: List[Tuple[str, Decimal]],
|
||||
db: Session,
|
||||
):
|
||||
# Header
|
||||
s = "\n\r" + db.query(DbSetting).filter(DbSetting.name == "Header").first().data['Text']
|
||||
s = (
|
||||
"\n\r"
|
||||
+ db.query(DbSetting).filter(DbSetting.name == "Header").first().data["Text"]
|
||||
)
|
||||
if voucher.voucher_type == VoucherType.REGULAR_BILL:
|
||||
s += "\n\r" + "Retail Invoice".center(42)
|
||||
s += "\n\r"
|
||||
@@ -55,8 +74,15 @@ def design_bill(voucher: Voucher, items: List[Tuple[Inventory, Decimal]], tax: L
|
||||
s += "\n\r" + "Qty. Particulars Price Amount"
|
||||
s += "\n\r" + "-" * 42
|
||||
for item in [i for i in items if i.quantity != 0]:
|
||||
name = "H H " + item.product.full_name if item.is_happy_hour else item.product.full_name
|
||||
s += "\n\r" + f"{item.quantity: >5.2f} {name:<22.22} {item.price: >6.2f} {item.price * item.quantity: >6.2f}"
|
||||
name = (
|
||||
"H H " + item.product.full_name
|
||||
if item.is_happy_hour
|
||||
else item.product.full_name
|
||||
)
|
||||
s += (
|
||||
"\n\r"
|
||||
+ f"{item.quantity: >5.2f} {name:<22.22} {item.price: >6.2f} {item.price * item.quantity: >6.2f}"
|
||||
)
|
||||
for m in [m for m in item.modifiers if m.modifier.show_in_bill]:
|
||||
s += f"\n\r -- {m.modifier.name: <38.38}"
|
||||
s += "\n\r" + "------------------------------------------"
|
||||
@@ -93,5 +119,8 @@ def design_bill(voucher: Voucher, items: List[Tuple[Inventory, Decimal]], tax: L
|
||||
s += "\n\r" + "-" * 42
|
||||
|
||||
s += "\n\r" + "Cashier : " + voucher.user.name
|
||||
s += "\n\r" + db.query(DbSetting).filter(DbSetting.name == "Footer").first().data['Text']
|
||||
s += (
|
||||
"\n\r"
|
||||
+ db.query(DbSetting).filter(DbSetting.name == "Footer").first().data["Text"]
|
||||
)
|
||||
return s
|
||||
@@ -1,23 +1,32 @@
|
||||
import uuid
|
||||
|
||||
from typing import List
|
||||
|
||||
from barker.models import Inventory, Kot, Printer, SectionPrinter, Voucher
|
||||
from barker.worker import sent_to_printer
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from barker.models import SectionPrinter, Printer, Voucher, Kot, Inventory
|
||||
from barker.worker import sent_to_printer
|
||||
|
||||
|
||||
def design_kot(voucher: Voucher, kot: Kot, items: List[Inventory], copy_number: int) -> str:
|
||||
def design_kot(
|
||||
voucher: Voucher, kot: Kot, items: List[Inventory], copy_number: int
|
||||
) -> str:
|
||||
s = (
|
||||
f"KOT / BOT".center(42)
|
||||
+ "\n\r" + f"Copy No. {copy_number}:".center(42)
|
||||
+ "\n\r" + "".ljust(42, "-")
|
||||
+ "\n\r" + f"KOT ID : K-{voucher.kot_id:>5}/S-{kot.code:>5} {kot.date:%d-%b-%Y %H:%M}"
|
||||
+ "\n\r" + f"Table No.: {voucher.food_table.name}"
|
||||
+ "\n\r" + "".ljust(42, "-")
|
||||
+ "\n\r" + " Qty. x Name "
|
||||
+ "\n\r" + "".ljust(42, "-")
|
||||
+ "\n\r"
|
||||
+ f"Copy No. {copy_number}:".center(42)
|
||||
+ "\n\r"
|
||||
+ "".ljust(42, "-")
|
||||
+ "\n\r"
|
||||
+ f"KOT ID : K-{voucher.kot_id:>5}/S-{kot.code:>5} {kot.date:%d-%b-%Y %H:%M}"
|
||||
+ "\n\r"
|
||||
+ f"Table No.: {voucher.food_table.name}"
|
||||
+ "\n\r"
|
||||
+ "".ljust(42, "-")
|
||||
+ "\n\r"
|
||||
+ " Qty. x Name "
|
||||
+ "\n\r"
|
||||
+ "".ljust(42, "-")
|
||||
)
|
||||
for item in items:
|
||||
name = (
|
||||
@@ -46,7 +55,8 @@ def print_kot(voucher_id: uuid.UUID, db: Session):
|
||||
SectionPrinter.menu_category_id == item.product.menu_category_id,
|
||||
SectionPrinter.menu_category_id == None,
|
||||
)
|
||||
).order_by(SectionPrinter.menu_category_id)
|
||||
)
|
||||
.order_by(SectionPrinter.menu_category_id)
|
||||
.first()
|
||||
)
|
||||
key = (printer.id, copies)
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.auth as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy import desc
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...schemas.auth import UserToken
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models.auth import Client
|
||||
import barker.schemas.auth as schemas
|
||||
from ...schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -41,7 +43,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -50,7 +53,9 @@ def update(
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["clients"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["clients"]),
|
||||
):
|
||||
try:
|
||||
item: Client = db.query(Client).filter(Client.id == id_).first()
|
||||
@@ -61,7 +66,8 @@ def delete(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -70,7 +76,8 @@ def delete(
|
||||
|
||||
@router.get("/list")
|
||||
async def show_list(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["clients"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["clients"]),
|
||||
):
|
||||
list_ = db.query(Client).order_by(Client.name).all()
|
||||
clients = []
|
||||
@@ -96,7 +103,9 @@ async def show_list(
|
||||
|
||||
@router.get("/{id_}")
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["clients"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["clients"]),
|
||||
):
|
||||
item: Client = db.query(Client).filter(Client.id == id_).first()
|
||||
return {
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import uuid
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.auth as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...schemas.auth import UserToken
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models.auth import Role, Permission
|
||||
import barker.schemas.auth as schemas
|
||||
from ...models.auth import Permission, Role
|
||||
from ...schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -25,7 +28,9 @@ def get_db():
|
||||
|
||||
@router.post("", response_model=schemas.Role)
|
||||
def save(
|
||||
data: schemas.RoleIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
data: schemas.RoleIn,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
try:
|
||||
item = Role(data.name)
|
||||
@@ -36,7 +41,8 @@ def save(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -59,7 +65,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -71,24 +78,30 @@ def add_permissions(role: Role, permissions: List[schemas.PermissionItem], db):
|
||||
gp = [p for p in role.permissions if p.id == permission.id_]
|
||||
gp = None if len(gp) == 0 else gp[0]
|
||||
if permission.enabled and gp is None:
|
||||
role.permissions.append(db.query(Permission).filter(Permission.id == permission.id_).one())
|
||||
role.permissions.append(
|
||||
db.query(Permission).filter(Permission.id == permission.id_).one()
|
||||
)
|
||||
elif not permission.enabled and gp:
|
||||
role.permissions.remove(gp)
|
||||
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
try:
|
||||
item: Role = db.query(Role).filter(Role.id == id_).first()
|
||||
if item is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Role not found",
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Role not found",
|
||||
)
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_501_NOT_IMPLEMENTED, detail="Role deletion not implemented",
|
||||
status_code=status.HTTP_501_NOT_IMPLEMENTED,
|
||||
detail="Role deletion not implemented",
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -97,20 +110,24 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
return role_info(None, db)
|
||||
|
||||
|
||||
@router.get("/list", response_model=List[schemas.RoleList])
|
||||
async def show_list(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
return [
|
||||
{
|
||||
"id": item.id,
|
||||
"name": item.name,
|
||||
"permissions": [p.name for p in sorted(item.permissions, key=lambda p: p.name)],
|
||||
"permissions": [
|
||||
p.name for p in sorted(item.permissions, key=lambda p: p.name)
|
||||
],
|
||||
}
|
||||
for item in db.query(Role).order_by(Role.name).all()
|
||||
]
|
||||
@@ -118,7 +135,9 @@ async def show_list(
|
||||
|
||||
@router.get("/{id_}", response_model=schemas.Role)
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
item: Role = db.query(Role).filter(Role.id == id_).first()
|
||||
return role_info(item, db)
|
||||
@@ -138,7 +157,11 @@ def role_info(item: Optional[Role], db):
|
||||
"id": item.id,
|
||||
"name": item.name,
|
||||
"permissions": [
|
||||
{"id": p.id, "name": p.name, "enabled": True if p in item.permissions else False,}
|
||||
{
|
||||
"id": p.id,
|
||||
"name": p.name,
|
||||
"enabled": True if p in item.permissions else False,
|
||||
}
|
||||
for p in db.query(Permission).order_by(Permission.name).all()
|
||||
],
|
||||
}
|
||||
@@ -1,15 +1,18 @@
|
||||
import uuid
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.auth as schemas
|
||||
|
||||
from barker.models.auth import Role, User
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...schemas.auth import UserToken
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from barker.models.auth import User, Role
|
||||
import barker.schemas.auth as schemas
|
||||
from ...schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -25,7 +28,9 @@ def get_db():
|
||||
|
||||
@router.post("", response_model=schemas.User)
|
||||
def save(
|
||||
data: schemas.UserIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
data: schemas.UserIn,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
try:
|
||||
item = User(name=data.name, password=data.password, locked_out=data.locked_out)
|
||||
@@ -36,7 +41,8 @@ def save(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -45,7 +51,8 @@ def save(
|
||||
|
||||
@router.get("/me", response_model=schemas.User)
|
||||
def show_me(
|
||||
db: Session = Depends(get_db), user: UserToken = Depends(get_user),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Depends(get_user),
|
||||
):
|
||||
item = db.query(User).filter(User.id == user.id_).first()
|
||||
return user_info(item, db, user)
|
||||
@@ -53,7 +60,9 @@ def show_me(
|
||||
|
||||
@router.put("/me", response_model=schemas.User)
|
||||
def update_me(
|
||||
data: schemas.UserIn, db: Session = Depends(get_db), user: UserToken = Depends(get_user),
|
||||
data: schemas.UserIn,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Depends(get_user),
|
||||
):
|
||||
try:
|
||||
item: User = db.query(User).filter(User.id == user.id_).first()
|
||||
@@ -68,7 +77,8 @@ def update_me(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -94,7 +104,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -113,17 +124,21 @@ def add_roles(user: User, roles: List[schemas.RoleItem], db: Session):
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
try:
|
||||
item: User = db.query(User).filter(User.id == id_).first()
|
||||
if item is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="User not found",
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="User not found",
|
||||
)
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_501_NOT_IMPLEMENTED, detail="User deletion not implemented",
|
||||
status_code=status.HTTP_501_NOT_IMPLEMENTED,
|
||||
detail="User deletion not implemented",
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -132,14 +147,16 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
return user_info(None, db, user)
|
||||
|
||||
|
||||
@router.get("/list", response_model=List[schemas.UserList])
|
||||
async def show_list(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
return [
|
||||
{
|
||||
@@ -153,13 +170,20 @@ async def show_list(
|
||||
|
||||
|
||||
@router.get("/active")
|
||||
async def show_active(db: Session = Depends(get_db), user: UserToken = Depends(get_user)):
|
||||
return [{"name": item.name} for item in db.query(User).filter(User.locked_out == False).order_by(User.name)]
|
||||
async def show_active(
|
||||
db: Session = Depends(get_db), user: UserToken = Depends(get_user)
|
||||
):
|
||||
return [
|
||||
{"name": item.name}
|
||||
for item in db.query(User).filter(User.locked_out == False).order_by(User.name)
|
||||
]
|
||||
|
||||
|
||||
@router.get("/{id_}", response_model=schemas.User)
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
item = db.query(User).filter(User.id == id_).first()
|
||||
return user_info(item, db, user)
|
||||
@@ -170,7 +194,10 @@ def user_info(item: Optional[User], db: Session, user: UserToken):
|
||||
return {
|
||||
"name": "",
|
||||
"lockedOut": False,
|
||||
"roles": [{"id": r.id, "name": r.name, "enabled": False} for r in db.query(Role).order_by(Role.name).all()],
|
||||
"roles": [
|
||||
{"id": r.id, "name": r.name, "enabled": False}
|
||||
for r in db.query(Role).order_by(Role.name).all()
|
||||
],
|
||||
}
|
||||
else:
|
||||
return {
|
||||
@@ -179,7 +206,11 @@ def user_info(item: Optional[User], db: Session, user: UserToken):
|
||||
"password": "",
|
||||
"lockedOut": item.locked_out,
|
||||
"roles": [
|
||||
{"id": r.id, "name": r.name, "enabled": True if r in item.roles else False}
|
||||
{
|
||||
"id": r.id,
|
||||
"name": r.name,
|
||||
"enabled": True if r in item.roles else False,
|
||||
}
|
||||
for r in db.query(Role).order_by(Role.name).all()
|
||||
]
|
||||
if "users" in user.permissions
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import uuid
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.master as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..schemas.auth import UserToken
|
||||
import barker.schemas.master as schemas
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models.master import Customer
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -25,17 +28,22 @@ def get_db():
|
||||
|
||||
@router.post("", response_model=schemas.Customer)
|
||||
def save(
|
||||
data: schemas.CustomerIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["customers"]),
|
||||
data: schemas.CustomerIn,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["customers"]),
|
||||
):
|
||||
try:
|
||||
item = Customer(company=data.company, name=data.name, phone=data.phone, address=data.address)
|
||||
item = Customer(
|
||||
company=data.company, name=data.name, phone=data.phone, address=data.address
|
||||
)
|
||||
db.add(item)
|
||||
db.commit()
|
||||
return customer_info(item)
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -60,7 +68,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -69,13 +78,16 @@ def update(
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["customers"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["customers"]),
|
||||
):
|
||||
try:
|
||||
item: Customer = db.query(Customer).filter(Customer.id == id_).first()
|
||||
if item is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Sale Category not found",
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Sale Category not found",
|
||||
)
|
||||
db.delete(item)
|
||||
db.commit()
|
||||
@@ -86,19 +98,24 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["customers"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["customers"]),
|
||||
):
|
||||
return customer_info(None)
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get_user)):
|
||||
return [customer_info(item) for item in db.query(Customer).order_by(Customer.name).all()]
|
||||
return [
|
||||
customer_info(item) for item in db.query(Customer).order_by(Customer.name).all()
|
||||
]
|
||||
|
||||
|
||||
@router.get("/{id_}")
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["customers"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["customers"]),
|
||||
):
|
||||
item: Customer = db.query(Customer).filter(Customer.id == id_).first()
|
||||
return customer_info(item)
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import uuid
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.master as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..schemas.auth import UserToken
|
||||
import barker.schemas.master as schemas
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models.master import Device
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -25,7 +28,9 @@ def get_db():
|
||||
|
||||
@router.post("", response_model=schemas.Device)
|
||||
def save(
|
||||
data: schemas.DeviceIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["devices"]),
|
||||
data: schemas.DeviceIn,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["devices"]),
|
||||
):
|
||||
try:
|
||||
item = Device(name=data.name, section_id=data.section.id_)
|
||||
@@ -35,7 +40,8 @@ def save(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -58,7 +64,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -67,7 +74,9 @@ def update(
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["devices"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["devices"]),
|
||||
):
|
||||
try:
|
||||
item: Device = db.query(Device).filter(Device.id == id_).first()
|
||||
@@ -77,7 +86,8 @@ def delete(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -86,7 +96,8 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["devices"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["devices"]),
|
||||
):
|
||||
return device_info(None)
|
||||
|
||||
@@ -98,7 +109,9 @@ def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get_user)
|
||||
|
||||
@router.get("/{id_}")
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["devices"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["devices"]),
|
||||
):
|
||||
item: Device = db.query(Device).filter(Device.id == id_).first()
|
||||
return device_info(item)
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
import uuid
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
from typing import Optional
|
||||
from datetime import date, timedelta, datetime
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
|
||||
import barker.schemas.master as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.config import settings
|
||||
from ..schemas.auth import UserToken
|
||||
import barker.schemas.master as schemas
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models.master import Customer
|
||||
from ..models.voucher import GuestBook
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -32,9 +36,16 @@ def save(
|
||||
user: UserToken = Security(get_user, scopes=["guest-book"]),
|
||||
):
|
||||
try:
|
||||
customer: Customer = db.query(Customer).filter(Customer.phone == data.phone).first()
|
||||
customer: Customer = (
|
||||
db.query(Customer).filter(Customer.phone == data.phone).first()
|
||||
)
|
||||
if customer is None:
|
||||
customer = Customer(company=data.company, name=data.name, phone=data.phone, address=data.address,)
|
||||
customer = Customer(
|
||||
company=data.company,
|
||||
name=data.name,
|
||||
phone=data.phone,
|
||||
address=data.address,
|
||||
)
|
||||
db.add(customer)
|
||||
else:
|
||||
customer.name = data.name or customer.name
|
||||
@@ -47,7 +58,8 @@ def save(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -73,7 +85,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -82,7 +95,9 @@ def update(
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["guest-book"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["guest-book"]),
|
||||
):
|
||||
try:
|
||||
item: GuestBook = db.query(GuestBook).filter(GuestBook.id == id_).first()
|
||||
@@ -92,7 +107,8 @@ def delete(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -101,13 +117,18 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["guest-book"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["guest-book"]),
|
||||
):
|
||||
return guest_book_info(None)
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
def show_list(q: Optional[str] = None, db: Session = Depends(get_db), user: UserToken = Depends(get_user)):
|
||||
def show_list(
|
||||
q: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Depends(get_user),
|
||||
):
|
||||
if q is None or q == "":
|
||||
q = date.today()
|
||||
else:
|
||||
@@ -115,11 +136,21 @@ def show_list(q: Optional[str] = None, db: Session = Depends(get_db), user: User
|
||||
list_ = (
|
||||
db.query(GuestBook)
|
||||
.filter(
|
||||
GuestBook.date >= q + timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES - settings.TIMEZONE_OFFSET_MINUTES)
|
||||
GuestBook.date
|
||||
>= q
|
||||
+ timedelta(
|
||||
minutes=settings.NEW_DAY_OFFSET_MINUTES
|
||||
- settings.TIMEZONE_OFFSET_MINUTES
|
||||
)
|
||||
)
|
||||
.filter(
|
||||
GuestBook.date
|
||||
< q + timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES - settings.TIMEZONE_OFFSET_MINUTES, days=1)
|
||||
< q
|
||||
+ timedelta(
|
||||
minutes=settings.NEW_DAY_OFFSET_MINUTES
|
||||
- settings.TIMEZONE_OFFSET_MINUTES,
|
||||
days=1,
|
||||
)
|
||||
)
|
||||
.order_by(GuestBook.date)
|
||||
.all()
|
||||
@@ -145,7 +176,9 @@ def show_list(q: Optional[str] = None, db: Session = Depends(get_db), user: User
|
||||
|
||||
@router.get("/{id_}")
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["guest-book"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["guest-book"]),
|
||||
):
|
||||
item: GuestBook = db.query(GuestBook).filter(GuestBook.id == id_).first()
|
||||
return guest_book_info(item)
|
||||
|
||||
@@ -1,29 +1,31 @@
|
||||
from datetime import timedelta
|
||||
|
||||
from barker.core.config import settings
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
Depends,
|
||||
HTTPException,
|
||||
status,
|
||||
Security,
|
||||
Cookie,
|
||||
Depends,
|
||||
Form,
|
||||
HTTPException,
|
||||
Response,
|
||||
Security,
|
||||
status,
|
||||
)
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.security import (
|
||||
Token,
|
||||
authenticate_user,
|
||||
client_allowed,
|
||||
create_access_token,
|
||||
get_current_active_user,
|
||||
client_allowed,
|
||||
)
|
||||
from barker.core.config import settings
|
||||
from ..db.session import SessionLocal
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@@ -54,21 +56,33 @@ async def login_for_access_token(
|
||||
allowed, c_id = client_allowed(user, client_id, otp, db)
|
||||
db.commit()
|
||||
if c_id and c_id != client_id:
|
||||
response.set_cookie(key="client_id", value=str(c_id), max_age=10 * 365 * 24 * 60 * 60)
|
||||
response.set_cookie(
|
||||
key="client_id", value=str(c_id), max_age=10 * 365 * 24 * 60 * 60
|
||||
)
|
||||
if not allowed:
|
||||
not_allowed_response = JSONResponse(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
content={"detail": "Client is not registered"},
|
||||
)
|
||||
not_allowed_response.set_cookie(key="client_id", value=str(c_id), max_age=10 * 365 * 24 * 60 * 60)
|
||||
not_allowed_response.set_cookie(
|
||||
key="client_id", value=str(c_id), max_age=10 * 365 * 24 * 60 * 60
|
||||
)
|
||||
return not_allowed_response
|
||||
access_token_expires = timedelta(minutes=settings.JWT_TOKEN_EXPIRE_MINUTES)
|
||||
access_token = create_access_token(
|
||||
data={
|
||||
"sub": user.name,
|
||||
"scopes": ["authenticated"]
|
||||
+ list(set([p.name.replace(" ", "-").lower() for r in user.roles for p in r.permissions])),
|
||||
+ list(
|
||||
set(
|
||||
[
|
||||
p.name.replace(" ", "-").lower()
|
||||
for r in user.roles
|
||||
for p in r.permissions
|
||||
]
|
||||
)
|
||||
),
|
||||
"userId": str(user.id),
|
||||
"lockedOut": user.locked_out,
|
||||
},
|
||||
@@ -81,7 +95,12 @@ async def login_for_access_token(
|
||||
async def refresh_token(user: UserToken = Security(get_current_active_user)):
|
||||
access_token_expires = timedelta(minutes=settings.JWT_TOKEN_EXPIRE_MINUTES)
|
||||
access_token = create_access_token(
|
||||
data={"sub": user.name, "scopes": user.permissions, "userId": str(user.id_), "lockedOut": user.locked_out,},
|
||||
data={
|
||||
"sub": user.name,
|
||||
"scopes": user.permissions,
|
||||
"userId": str(user.id_),
|
||||
"lockedOut": user.locked_out,
|
||||
},
|
||||
expires_delta=access_token_expires,
|
||||
)
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
||||
@@ -1,15 +1,18 @@
|
||||
import uuid
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.master as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..schemas.auth import UserToken
|
||||
import barker.schemas.master as schemas
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models.master import Product, MenuCategory
|
||||
from ..models.master import MenuCategory, Product
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -25,17 +28,25 @@ def get_db():
|
||||
|
||||
@router.post("", response_model=schemas.MenuCategory)
|
||||
def save(
|
||||
data: schemas.MenuCategoryIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]),
|
||||
data: schemas.MenuCategoryIn,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
try:
|
||||
item = MenuCategory(name=data.name, discount_limit=data.discount_limit, is_active=data.is_active, sort_order=0)
|
||||
item = MenuCategory(
|
||||
name=data.name,
|
||||
discount_limit=data.discount_limit,
|
||||
is_active=data.is_active,
|
||||
sort_order=0,
|
||||
)
|
||||
db.add(item)
|
||||
db.commit()
|
||||
return menu_category_info(item)
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -50,10 +61,13 @@ def update(
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
try:
|
||||
item: MenuCategory = db.query(MenuCategory).filter(MenuCategory.id == id_).first()
|
||||
item: MenuCategory = (
|
||||
db.query(MenuCategory).filter(MenuCategory.id == id_).first()
|
||||
)
|
||||
if item.is_fixture:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_423_LOCKED, detail=f"{item.name} is a fixture and cannot be edited or deleted.",
|
||||
status_code=status.HTTP_423_LOCKED,
|
||||
detail=f"{item.name} is a fixture and cannot be edited or deleted.",
|
||||
)
|
||||
item.name = data.name
|
||||
item.discount_limit = data.discount_limit
|
||||
@@ -63,7 +77,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -72,21 +87,28 @@ def update(
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
try:
|
||||
item: MenuCategory = db.query(MenuCategory).filter(MenuCategory.id == id_).first()
|
||||
item: MenuCategory = (
|
||||
db.query(MenuCategory).filter(MenuCategory.id == id_).first()
|
||||
)
|
||||
if item is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Menu Category not found",
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Menu Category not found",
|
||||
)
|
||||
elif item.is_fixture:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_423_LOCKED, detail=f"{item.name} is a fixture and cannot be edited or deleted.",
|
||||
status_code=status.HTTP_423_LOCKED,
|
||||
detail=f"{item.name} is a fixture and cannot be edited or deleted.",
|
||||
)
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_501_NOT_IMPLEMENTED, detail="Menu Category deletion not implemented",
|
||||
status_code=status.HTTP_501_NOT_IMPLEMENTED,
|
||||
detail="Menu Category deletion not implemented",
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -95,14 +117,21 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
return menu_category_info(None)
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get_user)):
|
||||
return [menu_category_info(item) for item in db.query(MenuCategory).order_by(MenuCategory.sort_order).order_by(MenuCategory.name).all()]
|
||||
return [
|
||||
menu_category_info(item)
|
||||
for item in db.query(MenuCategory)
|
||||
.order_by(MenuCategory.sort_order)
|
||||
.order_by(MenuCategory.name)
|
||||
.all()
|
||||
]
|
||||
|
||||
|
||||
@router.get("/sale-list")
|
||||
@@ -151,7 +180,9 @@ async def sale_list(
|
||||
|
||||
@router.get("/{id_}")
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
item: MenuCategory = db.query(MenuCategory).filter(MenuCategory.id == id_).first()
|
||||
return menu_category_info(item)
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import uuid
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.master as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..schemas.auth import UserToken
|
||||
import barker.schemas.master as schemas
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models.master import Modifier
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -25,7 +28,9 @@ def get_db():
|
||||
|
||||
@router.post("", response_model=schemas.Modifier)
|
||||
def save(
|
||||
data: schemas.ModifierIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
data: schemas.ModifierIn,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
):
|
||||
try:
|
||||
item = Modifier(
|
||||
@@ -41,7 +46,8 @@ def save(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -67,7 +73,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -76,7 +83,9 @@ def update(
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
):
|
||||
try:
|
||||
item: Modifier = db.query(Modifier).filter(Modifier.id == id_).first()
|
||||
@@ -86,7 +95,8 @@ def delete(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -95,19 +105,24 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
):
|
||||
return modifier_info(None)
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get_user)):
|
||||
return [modifier_info(item) for item in db.query(Modifier).order_by(Modifier.name).all()]
|
||||
return [
|
||||
modifier_info(item) for item in db.query(Modifier).order_by(Modifier.name).all()
|
||||
]
|
||||
|
||||
|
||||
@router.get("/{id_}")
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
):
|
||||
item: Modifier = db.query(Modifier).filter(Modifier.id == id_).first()
|
||||
return modifier_info(item)
|
||||
@@ -128,5 +143,8 @@ def modifier_info(item: Optional[Modifier]):
|
||||
"showInBill": item.show_in_bill,
|
||||
"price": item.price,
|
||||
"isActive": item.is_active,
|
||||
"modifierCategory": {"id": item.modifier_category.id, "name": item.modifier_category.name,},
|
||||
"modifierCategory": {
|
||||
"id": item.modifier_category.id,
|
||||
"name": item.modifier_category.name,
|
||||
},
|
||||
}
|
||||
@@ -1,16 +1,19 @@
|
||||
import uuid
|
||||
|
||||
from functools import reduce
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.master as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..schemas.auth import UserToken
|
||||
import barker.schemas.master as schemas
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models.master import ModifierCategory, MenuCategory, Product
|
||||
from ..models.master import MenuCategory, ModifierCategory, Product
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -31,7 +34,12 @@ def save(
|
||||
user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
):
|
||||
try:
|
||||
item = ModifierCategory(name=data.name, minimum=data.minimum, maximum=data.maximum, is_active=data.is_active)
|
||||
item = ModifierCategory(
|
||||
name=data.name,
|
||||
minimum=data.minimum,
|
||||
maximum=data.maximum,
|
||||
is_active=data.is_active,
|
||||
)
|
||||
db.add(item)
|
||||
add_products(item, data.menu_categories, db)
|
||||
db.commit()
|
||||
@@ -39,7 +47,8 @@ def save(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -54,7 +63,9 @@ def update(
|
||||
user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
):
|
||||
try:
|
||||
item: ModifierCategory = db.query(ModifierCategory).filter(ModifierCategory.id == id_).first()
|
||||
item: ModifierCategory = (
|
||||
db.query(ModifierCategory).filter(ModifierCategory.id == id_).first()
|
||||
)
|
||||
item.name = data.name
|
||||
item.minimum = data.minimum
|
||||
item.maximum = data.maximum
|
||||
@@ -65,7 +76,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -74,17 +86,22 @@ def update(
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
):
|
||||
try:
|
||||
item: ModifierCategory = db.query(ModifierCategory).filter(ModifierCategory.id == id_).first()
|
||||
item: ModifierCategory = (
|
||||
db.query(ModifierCategory).filter(ModifierCategory.id == id_).first()
|
||||
)
|
||||
db.delete(item)
|
||||
db.commit()
|
||||
return modifier_category_info(None, db=db)
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -93,14 +110,20 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
):
|
||||
return modifier_category_info(None, db=db)
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get_user)):
|
||||
list_ = db.query(ModifierCategory).order_by(ModifierCategory.sort_order).order_by(ModifierCategory.name).all()
|
||||
list_ = (
|
||||
db.query(ModifierCategory)
|
||||
.order_by(ModifierCategory.sort_order)
|
||||
.order_by(ModifierCategory.name)
|
||||
.all()
|
||||
)
|
||||
menu_categories = (
|
||||
db.query(MenuCategory)
|
||||
.join(MenuCategory.products)
|
||||
@@ -120,20 +143,30 @@ def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get_user)
|
||||
{
|
||||
"id": mc.id,
|
||||
"name": mc.name,
|
||||
"enabled": reduce(lambda x, y: x and (y in item.products), mc.products, True),
|
||||
"products": [{"id": p.id, "name": p.name} for p in mc.products if p in item.products],
|
||||
"enabled": reduce(
|
||||
lambda x, y: x and (y in item.products), mc.products, True
|
||||
),
|
||||
"products": [
|
||||
{"id": p.id, "name": p.name}
|
||||
for p in mc.products
|
||||
if p in item.products
|
||||
],
|
||||
}
|
||||
for mc in menu_categories
|
||||
],
|
||||
}
|
||||
modifier_category["menuCategories"] = [i for i in modifier_category["menuCategories"] if len(i["products"]) > 0]
|
||||
modifier_category["menuCategories"] = [
|
||||
i for i in modifier_category["menuCategories"] if len(i["products"]) > 0
|
||||
]
|
||||
modifier_categories.append(modifier_category)
|
||||
return modifier_categories
|
||||
|
||||
|
||||
@router.get("/for-product/{id_}")
|
||||
def for_product(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user),
|
||||
):
|
||||
product: Product = db.query(Product).filter(Product.id == id_).first()
|
||||
|
||||
@@ -145,7 +178,9 @@ def for_product(
|
||||
"maximum": item.maximum,
|
||||
"isActive": item.is_active,
|
||||
"modifiers": [
|
||||
{"id": m.id, "name": m.name, "price": m.price} for m in item.modifiers if m.is_active == True
|
||||
{"id": m.id, "name": m.name, "price": m.price}
|
||||
for m in item.modifiers
|
||||
if m.is_active == True
|
||||
],
|
||||
}
|
||||
for item in product.modifier_categories
|
||||
@@ -155,9 +190,13 @@ def for_product(
|
||||
|
||||
@router.get("/{id_}")
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["modifiers"]),
|
||||
):
|
||||
item: ModifierCategory = db.query(ModifierCategory).filter(ModifierCategory.id == id_).first()
|
||||
item: ModifierCategory = (
|
||||
db.query(ModifierCategory).filter(ModifierCategory.id == id_).first()
|
||||
)
|
||||
return modifier_category_info(item, db=db)
|
||||
|
||||
|
||||
@@ -180,7 +219,10 @@ def modifier_category_info(item: Optional[ModifierCategory], db: Session):
|
||||
"id": mc.id,
|
||||
"name": mc.name,
|
||||
"enabled": False,
|
||||
"products": [{"id": p.id, "name": p.name, "enabled": False} for p in mc.products],
|
||||
"products": [
|
||||
{"id": p.id, "name": p.name, "enabled": False}
|
||||
for p in mc.products
|
||||
],
|
||||
}
|
||||
for mc in menu_categories
|
||||
],
|
||||
@@ -198,7 +240,12 @@ def modifier_category_info(item: Optional[ModifierCategory], db: Session):
|
||||
"name": mc.name,
|
||||
"enabled": False,
|
||||
"products": [
|
||||
{"id": p.id, "name": p.name, "enabled": True if p in item.products else False} for p in mc.products
|
||||
{
|
||||
"id": p.id,
|
||||
"name": p.name,
|
||||
"enabled": True if p in item.products else False,
|
||||
}
|
||||
for p in mc.products
|
||||
],
|
||||
}
|
||||
for mc in menu_categories
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import uuid
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.master as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..schemas.auth import UserToken
|
||||
import barker.schemas.master as schemas
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models.master import Printer
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -25,7 +28,9 @@ def get_db():
|
||||
|
||||
@router.post("", response_model=schemas.Printer)
|
||||
def save(
|
||||
data: schemas.PrinterIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["printers"]),
|
||||
data: schemas.PrinterIn,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["printers"]),
|
||||
):
|
||||
try:
|
||||
item = Printer(name=data.name, address=data.address, cut_code=data.cut_code)
|
||||
@@ -35,7 +40,8 @@ def save(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -59,7 +65,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -68,7 +75,9 @@ def update(
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["printers"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["printers"]),
|
||||
):
|
||||
try:
|
||||
item: Printer = db.query(Printer).filter(Printer.id == id_).first()
|
||||
@@ -78,7 +87,8 @@ def delete(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -87,19 +97,24 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["printers"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["printers"]),
|
||||
):
|
||||
return printer_info(None)
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get_user)):
|
||||
return [printer_info(item) for item in db.query(Printer).order_by(Printer.name).all()]
|
||||
return [
|
||||
printer_info(item) for item in db.query(Printer).order_by(Printer.name).all()
|
||||
]
|
||||
|
||||
|
||||
@router.get("/{id_}")
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["printers"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["printers"]),
|
||||
):
|
||||
item: Printer = db.query(Printer).filter(Printer.id == id_).first()
|
||||
return printer_info(item)
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import uuid
|
||||
from typing import Optional, List
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
from typing import List, Optional
|
||||
|
||||
import barker.schemas.master as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..schemas.auth import UserToken
|
||||
import barker.schemas.master as schemas
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models.master import Product
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -25,8 +28,9 @@ def get_db():
|
||||
|
||||
@router.post("/list", response_model=List[schemas.Product])
|
||||
def sort_order(
|
||||
data: List[schemas.Product], db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
data: List[schemas.Product],
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
try:
|
||||
indexes = {}
|
||||
@@ -42,16 +46,19 @@ def sort_order(
|
||||
return [
|
||||
product_info(item)
|
||||
for item in db.query(Product)
|
||||
.order_by(Product.menu_category_id)
|
||||
.order_by(Product.sort_order)
|
||||
.order_by(Product.name)
|
||||
.options(joinedload(Product.menu_category), joinedload(Product.sale_category))
|
||||
.all()
|
||||
.order_by(Product.menu_category_id)
|
||||
.order_by(Product.sort_order)
|
||||
.order_by(Product.name)
|
||||
.options(
|
||||
joinedload(Product.menu_category), joinedload(Product.sale_category)
|
||||
)
|
||||
.all()
|
||||
]
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -60,7 +67,9 @@ def sort_order(
|
||||
|
||||
@router.post("", response_model=schemas.Product)
|
||||
def save(
|
||||
data: schemas.ProductIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]),
|
||||
data: schemas.ProductIn,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
try:
|
||||
item = Product(
|
||||
@@ -80,7 +89,8 @@ def save(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -110,7 +120,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -119,17 +130,21 @@ def update(
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
try:
|
||||
item: Product = db.query(Product).filter(Product.id == id_).first()
|
||||
if item is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Product not found",
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Product not found",
|
||||
)
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_501_NOT_IMPLEMENTED, detail="Product deletion not implemented",
|
||||
status_code=status.HTTP_501_NOT_IMPLEMENTED,
|
||||
detail="Product deletion not implemented",
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -138,7 +153,8 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
return product_info(None)
|
||||
|
||||
@@ -164,12 +180,20 @@ async def show_term(
|
||||
current_user: UserToken = Depends(get_user),
|
||||
):
|
||||
list_ = []
|
||||
for item in db.query(Product).filter(Product.is_active == a, Product.menu_category_id == mc).order_by(Product.sort_order, Product.name).all():
|
||||
for item in (
|
||||
db.query(Product)
|
||||
.filter(Product.is_active == a, Product.menu_category_id == mc)
|
||||
.order_by(Product.sort_order, Product.name)
|
||||
.all()
|
||||
):
|
||||
list_.append(
|
||||
{
|
||||
"id": item.id,
|
||||
"name": item.full_name,
|
||||
"saleCategory": {"id": item.sale_category_id, "name": item.sale_category.name, },
|
||||
"saleCategory": {
|
||||
"id": item.sale_category_id,
|
||||
"name": item.sale_category.name,
|
||||
},
|
||||
"tax": {
|
||||
"id": item.sale_category.tax_id,
|
||||
"name": item.sale_category.tax.name,
|
||||
@@ -187,7 +211,10 @@ async def show_term(
|
||||
{
|
||||
"id": item.id,
|
||||
"name": "H H " + item.full_name,
|
||||
"saleCategory": {"id": item.sale_category_id, "name": item.sale_category.name, },
|
||||
"saleCategory": {
|
||||
"id": item.sale_category_id,
|
||||
"name": item.sale_category.name,
|
||||
},
|
||||
"tax": {
|
||||
"id": item.sale_category.tax_id,
|
||||
"name": item.sale_category.tax.name,
|
||||
@@ -205,7 +232,9 @@ async def show_term(
|
||||
|
||||
@router.get("/{id_}")
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
item: Product = db.query(Product).filter(Product.id == id_).first()
|
||||
return product_info(item)
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
from datetime import datetime, timedelta, date
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from barker.core.config import settings
|
||||
from fastapi import APIRouter, Depends, Security
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.sql.expression import func
|
||||
|
||||
from barker.core.config import settings
|
||||
from ...models import Inventory, Product, Kot, Voucher, VoucherType
|
||||
from ...schemas.auth import UserToken
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import Inventory, Kot, Product, Voucher, VoucherType
|
||||
from ...schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -31,10 +32,14 @@ def beer_consumption(
|
||||
):
|
||||
start_date = date.today() if s is None else datetime.strptime(s, "%d-%b-%Y").date()
|
||||
finish_date = date.today() if f is None else datetime.strptime(f, "%d-%b-%Y").date()
|
||||
if (date.today() - start_date).days > 5 and "accounts-audit" not in user.permissions:
|
||||
if (
|
||||
date.today() - start_date
|
||||
).days > 5 and "accounts-audit" not in user.permissions:
|
||||
raise ValueError("Accounts Audit")
|
||||
|
||||
day = func.date_trunc("day", Voucher.date - timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES)).label("day")
|
||||
day = func.date_trunc(
|
||||
"day", Voucher.date - timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES)
|
||||
).label("day")
|
||||
sum_ = func.sum(Inventory.quantity * Product.quantity).label("sum")
|
||||
list_ = (
|
||||
db.query(day, Product.name, sum_)
|
||||
@@ -45,7 +50,11 @@ def beer_consumption(
|
||||
day >= start_date,
|
||||
day <= finish_date,
|
||||
Voucher.voucher_type.in_(
|
||||
[VoucherType.REGULAR_BILL.value, VoucherType.NO_CHARGE.value, VoucherType.STAFF.value,]
|
||||
[
|
||||
VoucherType.REGULAR_BILL.value,
|
||||
VoucherType.NO_CHARGE.value,
|
||||
VoucherType.STAFF.value,
|
||||
]
|
||||
),
|
||||
)
|
||||
.group_by(day, Product.name)
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
from datetime import datetime, timedelta, date
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from barker.core.config import settings
|
||||
from fastapi import APIRouter, Depends, Security
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from barker.core.config import settings
|
||||
from ...models import Voucher, VoucherType, Settlement, Reprint, SettleOption
|
||||
from ...schemas.auth import UserToken
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import Reprint, Settlement, SettleOption, Voucher, VoucherType
|
||||
from ...schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -30,7 +31,9 @@ def bill_details(
|
||||
):
|
||||
start_date = date.today() if s is None else datetime.strptime(s, "%d-%b-%Y").date()
|
||||
finish_date = date.today() if f is None else datetime.strptime(f, "%d-%b-%Y").date()
|
||||
if (date.today() - start_date).days > 5 and "accounts-audit" not in user.permissions:
|
||||
if (
|
||||
date.today() - start_date
|
||||
).days > 5 and "accounts-audit" not in user.permissions:
|
||||
raise ValueError("Accounts Audit")
|
||||
|
||||
return {
|
||||
@@ -85,8 +88,16 @@ def reprints(s: date, f: date, db: Session):
|
||||
"billId": item.voucher.full_bill_id,
|
||||
"settlement": f"Reprinted by {item.user.name}",
|
||||
"Amount": round(
|
||||
next(s.amount for s in item.voucher.settlements if s.settled == SettleOption.AMOUNT()) * -1, 2,
|
||||
next(
|
||||
s.amount
|
||||
for s in item.voucher.settlements
|
||||
if s.settled == SettleOption.AMOUNT()
|
||||
)
|
||||
* -1,
|
||||
2,
|
||||
),
|
||||
}
|
||||
for item in db.query(Reprint).filter(Reprint.date >= start_date, Reprint.date <= finish_date).all()
|
||||
for item in db.query(Reprint)
|
||||
.filter(Reprint.date >= start_date, Reprint.date <= finish_date)
|
||||
.all()
|
||||
]
|
||||
@@ -1,15 +1,17 @@
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, date
|
||||
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from fastapi import APIRouter, Depends, Security
|
||||
from sqlalchemy import distinct
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ...core.config import settings
|
||||
from ...models import Voucher, Settlement, User
|
||||
from ...schemas.auth import UserToken
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import Settlement, User, Voucher
|
||||
from ...schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -32,7 +34,9 @@ def active_cashiers(
|
||||
):
|
||||
start_date = date.today() if s is None else datetime.strptime(s, "%d-%b-%Y").date()
|
||||
finish_date = date.today() if f is None else datetime.strptime(f, "%d-%b-%Y").date()
|
||||
if (date.today() - start_date).days > 5 and "accounts-audit" not in user.permissions:
|
||||
if (
|
||||
date.today() - start_date
|
||||
).days > 5 and "accounts-audit" not in user.permissions:
|
||||
raise ValueError("Accounts Audit")
|
||||
|
||||
users = (
|
||||
@@ -40,8 +44,11 @@ def active_cashiers(
|
||||
.filter(
|
||||
User.id.in_(
|
||||
db.query(distinct(Voucher.user_id)).filter(
|
||||
Voucher.date >= start_date + timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES),
|
||||
Voucher.date <= finish_date + timedelta(days=1, minutes=settings.NEW_DAY_OFFSET_MINUTES),
|
||||
Voucher.date
|
||||
>= start_date + timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES),
|
||||
Voucher.date
|
||||
<= finish_date
|
||||
+ timedelta(days=1, minutes=settings.NEW_DAY_OFFSET_MINUTES),
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -62,15 +69,23 @@ def show_id(
|
||||
):
|
||||
start_date = date.today() if s is None else datetime.strptime(s, "%d-%b-%Y").date()
|
||||
finish_date = date.today() if f is None else datetime.strptime(f, "%d-%b-%Y").date()
|
||||
if (date.today() - start_date).days > 5 and "accounts-audit" not in user.permissions:
|
||||
if (
|
||||
date.today() - start_date
|
||||
).days > 5 and "accounts-audit" not in user.permissions:
|
||||
raise ValueError("Accounts Audit")
|
||||
|
||||
vouchers = (
|
||||
db.query(Voucher)
|
||||
.options(joinedload(Voucher.settlements, innerjoin=True).joinedload(Settlement.settle_option, innerjoin=True))
|
||||
.options(
|
||||
joinedload(Voucher.settlements, innerjoin=True).joinedload(
|
||||
Settlement.settle_option, innerjoin=True
|
||||
)
|
||||
)
|
||||
.filter(
|
||||
Voucher.date >= start_date + timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES),
|
||||
Voucher.date <= finish_date + timedelta(days=1, minutes=settings.NEW_DAY_OFFSET_MINUTES),
|
||||
Voucher.date
|
||||
>= start_date + timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES),
|
||||
Voucher.date
|
||||
<= finish_date + timedelta(days=1, minutes=settings.NEW_DAY_OFFSET_MINUTES),
|
||||
Voucher.user_id == id_,
|
||||
)
|
||||
.order_by(Voucher.voucher_type)
|
||||
@@ -112,7 +127,9 @@ def show_blank(
|
||||
):
|
||||
start_date = date.today() if s is None else datetime.strptime(s, "%d-%b-%Y").date()
|
||||
finish_date = date.today() if f is None else datetime.strptime(f, "%d-%b-%Y").date()
|
||||
if (date.today() - start_date).days > 5 and "accounts-audit" not in user.permissions:
|
||||
if (
|
||||
date.today() - start_date
|
||||
).days > 5 and "accounts-audit" not in user.permissions:
|
||||
raise ValueError("Accounts Audit")
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,14 +1,25 @@
|
||||
from datetime import datetime, timedelta, date
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from barker.core.config import settings
|
||||
from fastapi import APIRouter, Depends, Security
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from barker.core.config import settings
|
||||
from ...models import Voucher, VoucherType, Settlement, Reprint, SettleOption, Inventory, SaleCategory, Kot, Product
|
||||
from ...schemas.auth import UserToken
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import (
|
||||
Inventory,
|
||||
Kot,
|
||||
Product,
|
||||
Reprint,
|
||||
SaleCategory,
|
||||
Settlement,
|
||||
SettleOption,
|
||||
Voucher,
|
||||
VoucherType,
|
||||
)
|
||||
from ...schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -31,7 +42,9 @@ def discount_report_view(
|
||||
):
|
||||
start_date = date.today() if s is None else datetime.strptime(s, "%d-%b-%Y").date()
|
||||
finish_date = date.today() if f is None else datetime.strptime(f, "%d-%b-%Y").date()
|
||||
if (date.today() - start_date).days > 5 and "accounts-audit" not in user.permissions:
|
||||
if (
|
||||
date.today() - start_date
|
||||
).days > 5 and "accounts-audit" not in user.permissions:
|
||||
raise ValueError("Accounts Audit")
|
||||
|
||||
return {
|
||||
@@ -45,7 +58,9 @@ def discount_report(s: date, f: date, db: Session):
|
||||
start_date = s + timedelta(minutes=settings.NEW_DAY_OFFSET_MINUTES)
|
||||
finish_date = f + timedelta(days=1, minutes=settings.NEW_DAY_OFFSET_MINUTES)
|
||||
|
||||
amount = func.sum(Inventory.quantity * Inventory.effective_price * Inventory.discount).label("Amount")
|
||||
amount = func.sum(
|
||||
Inventory.quantity * Inventory.effective_price * Inventory.discount
|
||||
).label("Amount")
|
||||
list_ = (
|
||||
db.query(SaleCategory.name, amount)
|
||||
.join(Voucher.kots)
|
||||
@@ -56,7 +71,9 @@ def discount_report(s: date, f: date, db: Session):
|
||||
Inventory.discount != 0,
|
||||
Voucher.date >= start_date,
|
||||
Voucher.date <= finish_date,
|
||||
Voucher.voucher_type.in_([VoucherType.REGULAR_BILL.value, VoucherType.KOT.value]),
|
||||
Voucher.voucher_type.in_(
|
||||
[VoucherType.REGULAR_BILL.value, VoucherType.KOT.value]
|
||||
),
|
||||
)
|
||||
.group_by(SaleCategory.name)
|
||||
.order_by(SaleCategory.name)
|
||||
|
||||
@@ -1,16 +1,24 @@
|
||||
from datetime import datetime, timedelta, date
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from barker.core.config import settings
|
||||
from fastapi import APIRouter, Depends, Security
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from barker.core.config import settings
|
||||
from ...models import Voucher, VoucherType, Product, Inventory, Kot, SaleCategory, \
|
||||
MenuCategory
|
||||
from ...schemas import to_camel
|
||||
from ...schemas.auth import UserToken
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import (
|
||||
Inventory,
|
||||
Kot,
|
||||
MenuCategory,
|
||||
Product,
|
||||
SaleCategory,
|
||||
Voucher,
|
||||
VoucherType,
|
||||
)
|
||||
from ...schemas import to_camel
|
||||
from ...schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -33,7 +41,9 @@ def product_sale_report_view(
|
||||
):
|
||||
start_date = date.today() if s is None else datetime.strptime(s, "%d-%b-%Y").date()
|
||||
finish_date = date.today() if f is None else datetime.strptime(f, "%d-%b-%Y").date()
|
||||
if (date.today() - start_date).days > 5 and "accounts-audit" not in user.permissions:
|
||||
if (
|
||||
date.today() - start_date
|
||||
).days > 5 and "accounts-audit" not in user.permissions:
|
||||
raise ValueError("Accounts Audit")
|
||||
|
||||
return {
|
||||
@@ -49,7 +59,11 @@ def product_sale_report(s: date, f: date, db: Session):
|
||||
|
||||
list_ = (
|
||||
db.query(
|
||||
Product.id, Product.full_name, Voucher.voucher_type, Inventory.is_happy_hour, func.sum(Inventory.quantity),
|
||||
Product.id,
|
||||
Product.full_name,
|
||||
Voucher.voucher_type,
|
||||
Inventory.is_happy_hour,
|
||||
func.sum(Inventory.quantity),
|
||||
)
|
||||
.join(Inventory.kot)
|
||||
.join(Kot.voucher)
|
||||
@@ -76,8 +90,11 @@ def product_sale_report(s: date, f: date, db: Session):
|
||||
old[0][type_] = quantity
|
||||
else:
|
||||
info.append(
|
||||
{"id": id_, "name": "H H " + name if hh else name, "isHappyHour": hh, type_: quantity,}
|
||||
{
|
||||
"id": id_,
|
||||
"name": "H H " + name if hh else name,
|
||||
"isHappyHour": hh,
|
||||
type_: quantity,
|
||||
}
|
||||
)
|
||||
return info
|
||||
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
from datetime import datetime, timedelta, date
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from barker.core.config import settings
|
||||
from fastapi import APIRouter, Depends, Security
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from barker.core.config import settings
|
||||
from .tax_report import get_tax
|
||||
from ...models import Voucher, VoucherType, Settlement, SettleOption, Product, Inventory, Kot, SaleCategory
|
||||
from ...schemas.auth import UserToken
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import (
|
||||
Inventory,
|
||||
Kot,
|
||||
Product,
|
||||
SaleCategory,
|
||||
Settlement,
|
||||
SettleOption,
|
||||
Voucher,
|
||||
VoucherType,
|
||||
)
|
||||
from ...schemas.auth import UserToken
|
||||
from .tax_report import get_tax
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -32,7 +42,9 @@ def get_sale_analysis(
|
||||
):
|
||||
start_date = date.today() if s is None else datetime.strptime(s, "%d-%b-%Y").date()
|
||||
finish_date = date.today() if f is None else datetime.strptime(f, "%d-%b-%Y").date()
|
||||
if (date.today() - start_date).days > 5 and "accounts-audit" not in user.permissions:
|
||||
if (
|
||||
date.today() - start_date
|
||||
).days > 5 and "accounts-audit" not in user.permissions:
|
||||
raise ValueError("Accounts Audit")
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
from datetime import datetime, timedelta, date
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from barker.core.config import settings
|
||||
from fastapi import APIRouter, Depends, Security
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from barker.core.config import settings
|
||||
from ...models import Voucher, VoucherType, Inventory, Kot, Tax
|
||||
from ...schemas.auth import UserToken
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import Inventory, Kot, Tax, Voucher, VoucherType
|
||||
from ...schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -31,7 +32,9 @@ def get_tax_report(
|
||||
):
|
||||
start_date = date.today() if s is None else datetime.strptime(s, "%d-%b-%Y").date()
|
||||
finish_date = date.today() if f is None else datetime.strptime(f, "%d-%b-%Y").date()
|
||||
if (date.today() - start_date).days > 5 and "accounts-audit" not in user.permissions:
|
||||
if (
|
||||
date.today() - start_date
|
||||
).days > 5 and "accounts-audit" not in user.permissions:
|
||||
raise ValueError("Accounts Audit")
|
||||
|
||||
return {
|
||||
@@ -65,6 +68,11 @@ def get_tax(s: date, f: date, db: Session):
|
||||
.all()
|
||||
)
|
||||
return [
|
||||
{"name": "{0} - {1:.2%}".format(i[0], i[1]), "taxRate": i[1], "saleAmount": i[2], "amount": i[3],}
|
||||
{
|
||||
"name": "{0} - {1:.2%}".format(i[0], i[1]),
|
||||
"taxRate": i[1],
|
||||
"saleAmount": i[2],
|
||||
"amount": i[3],
|
||||
}
|
||||
for i in amounts
|
||||
]
|
||||
@@ -1,13 +1,17 @@
|
||||
import uuid
|
||||
|
||||
import transaction
|
||||
from pyramid.view import view_config
|
||||
|
||||
from barker.models import Reprint
|
||||
from pyramid.view import view_config
|
||||
|
||||
|
||||
@view_config(
|
||||
request_method="POST", route_name="v1_reprint", renderer="json", permission="Print Bill", trans=True,
|
||||
request_method="POST",
|
||||
route_name="v1_reprint",
|
||||
renderer="json",
|
||||
permission="Print Bill",
|
||||
trans=True,
|
||||
)
|
||||
def save(request):
|
||||
id_ = uuid.UUID(request.matchdict["id"])
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import uuid
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.auth as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..schemas.auth import UserToken
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models.auth import Role, Permission
|
||||
import barker.schemas.auth as schemas
|
||||
from ..models.auth import Permission, Role
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -25,7 +28,9 @@ def get_db():
|
||||
|
||||
@router.post("", response_model=schemas.Role)
|
||||
def save(
|
||||
data: schemas.RoleIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
data: schemas.RoleIn,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
try:
|
||||
item = Role(data.name)
|
||||
@@ -36,7 +41,8 @@ def save(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -59,7 +65,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -71,24 +78,30 @@ def add_permissions(role: Role, permissions: List[schemas.PermissionItem], db):
|
||||
gp = [p for p in role.permissions if p.id == permission.id_]
|
||||
gp = None if len(gp) == 0 else gp[0]
|
||||
if permission.enabled and gp is None:
|
||||
role.permissions.append(db.query(Permission).filter(Permission.id == permission.id_).one())
|
||||
role.permissions.append(
|
||||
db.query(Permission).filter(Permission.id == permission.id_).one()
|
||||
)
|
||||
elif not permission.enabled and gp:
|
||||
role.permissions.remove(gp)
|
||||
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
try:
|
||||
item: Role = db.query(Role).filter(Role.id == id_).first()
|
||||
if item is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Role not found",
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Role not found",
|
||||
)
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_501_NOT_IMPLEMENTED, detail="Role deletion not implemented",
|
||||
status_code=status.HTTP_501_NOT_IMPLEMENTED,
|
||||
detail="Role deletion not implemented",
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -97,20 +110,24 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
return role_info(None, db)
|
||||
|
||||
|
||||
@router.get("/list", response_model=List[schemas.RoleList])
|
||||
async def show_list(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
return [
|
||||
{
|
||||
"id": item.id,
|
||||
"name": item.name,
|
||||
"permissions": [p.name for p in sorted(item.permissions, key=lambda p: p.name)],
|
||||
"permissions": [
|
||||
p.name for p in sorted(item.permissions, key=lambda p: p.name)
|
||||
],
|
||||
}
|
||||
for item in db.query(Role).order_by(Role.name).all()
|
||||
]
|
||||
@@ -118,7 +135,9 @@ async def show_list(
|
||||
|
||||
@router.get("/{id_}", response_model=schemas.Role)
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["users"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["users"]),
|
||||
):
|
||||
item: Role = db.query(Role).filter(Role.id == id_).first()
|
||||
return role_info(item, db)
|
||||
@@ -138,7 +157,11 @@ def role_info(item: Optional[Role], db):
|
||||
"id": item.id,
|
||||
"name": item.name,
|
||||
"permissions": [
|
||||
{"id": p.id, "name": p.name, "enabled": True if p in item.permissions else False,}
|
||||
{
|
||||
"id": p.id,
|
||||
"name": p.name,
|
||||
"enabled": True if p in item.permissions else False,
|
||||
}
|
||||
for p in db.query(Permission).order_by(Permission.name).all()
|
||||
],
|
||||
}
|
||||
@@ -1,15 +1,18 @@
|
||||
import uuid
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.master as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..schemas.auth import UserToken
|
||||
import barker.schemas.master as schemas
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models.master import SaleCategory
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -25,7 +28,9 @@ def get_db():
|
||||
|
||||
@router.post("", response_model=schemas.SaleCategory)
|
||||
def save(
|
||||
data: schemas.SaleCategoryIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]),
|
||||
data: schemas.SaleCategoryIn,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
try:
|
||||
item = SaleCategory(name=data.name, tax_id=data.tax.id_)
|
||||
@@ -35,7 +40,8 @@ def save(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -50,7 +56,9 @@ def update(
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
try:
|
||||
item: SaleCategory = db.query(SaleCategory).filter(SaleCategory.id == id_).first()
|
||||
item: SaleCategory = (
|
||||
db.query(SaleCategory).filter(SaleCategory.id == id_).first()
|
||||
)
|
||||
item.name = data.name
|
||||
item.tax_id = data.tax.id_
|
||||
db.commit()
|
||||
@@ -58,7 +66,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -67,17 +76,23 @@ def update(
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
try:
|
||||
item: SaleCategory = db.query(SaleCategory).filter(SaleCategory.id == id_).first()
|
||||
item: SaleCategory = (
|
||||
db.query(SaleCategory).filter(SaleCategory.id == id_).first()
|
||||
)
|
||||
if item is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Sale Category not found",
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Sale Category not found",
|
||||
)
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_501_NOT_IMPLEMENTED, detail="Sale Category deletion not implemented",
|
||||
status_code=status.HTTP_501_NOT_IMPLEMENTED,
|
||||
detail="Sale Category deletion not implemented",
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -86,24 +101,33 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
return sale_category_info(None)
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get_user)):
|
||||
return [sale_category_info(item) for item in db.query(SaleCategory).order_by(SaleCategory.name).all()]
|
||||
return [
|
||||
sale_category_info(item)
|
||||
for item in db.query(SaleCategory).order_by(SaleCategory.name).all()
|
||||
]
|
||||
|
||||
|
||||
@router.get("/for-discount")
|
||||
def for_discount(db: Session = Depends(get_db), user: UserToken = Depends(get_user)):
|
||||
return [{"id": item.id, "name": item.name, "discount": 0} for item in db.query(SaleCategory).order_by(SaleCategory.name).all()]
|
||||
return [
|
||||
{"id": item.id, "name": item.name, "discount": 0}
|
||||
for item in db.query(SaleCategory).order_by(SaleCategory.name).all()
|
||||
]
|
||||
|
||||
|
||||
@router.get("/{id_}")
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["products"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["products"]),
|
||||
):
|
||||
item: SaleCategory = db.query(SaleCategory).filter(SaleCategory.id == id_).first()
|
||||
return sale_category_info(item)
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
import uuid
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.master as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..schemas.auth import UserToken
|
||||
import barker.schemas.master as schemas
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models.master import Section
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -25,7 +28,9 @@ def get_db():
|
||||
|
||||
@router.post("", response_model=schemas.Section)
|
||||
def save(
|
||||
data: schemas.SectionIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["sections"]),
|
||||
data: schemas.SectionIn,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["sections"]),
|
||||
):
|
||||
try:
|
||||
item = Section(name=data.name)
|
||||
@@ -35,7 +40,8 @@ def save(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -57,7 +63,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -66,7 +73,9 @@ def update(
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["sections"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["sections"]),
|
||||
):
|
||||
try:
|
||||
item: Section = db.query(Section).filter(Section.id == id_).first()
|
||||
@@ -76,7 +85,8 @@ def delete(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -85,19 +95,24 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["sections"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["sections"]),
|
||||
):
|
||||
return section_info(None)
|
||||
|
||||
|
||||
@router.get("/list")
|
||||
def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get_user)):
|
||||
return [section_info(item) for item in db.query(Section).order_by(Section.name).all()]
|
||||
return [
|
||||
section_info(item) for item in db.query(Section).order_by(Section.name).all()
|
||||
]
|
||||
|
||||
|
||||
@router.get("/{id_}")
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["sections"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["sections"]),
|
||||
):
|
||||
item: Section = db.query(Section).filter(Section.id == id_).first()
|
||||
return section_info(item)
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
import uuid
|
||||
from typing import Optional, List
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
from typing import List, Optional
|
||||
|
||||
import barker.schemas.master as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy import and_
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||
|
||||
from ..schemas.auth import UserToken
|
||||
import barker.schemas.master as schemas
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models.master import SectionPrinter, MenuCategory
|
||||
from ..models.master import MenuCategory, SectionPrinter
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -43,7 +46,9 @@ def save(
|
||||
pg_insert(SectionPrinter.__table__)
|
||||
.values(
|
||||
id=uuid.uuid4(),
|
||||
menu_category_id=mcs.menu_category.id_ if mcs.menu_category is not None else None,
|
||||
menu_category_id=mcs.menu_category.id_
|
||||
if mcs.menu_category is not None
|
||||
else None,
|
||||
section_id=id_,
|
||||
printer_id=mcs.printer.id_,
|
||||
copies=mcs.copies,
|
||||
@@ -60,7 +65,9 @@ def save(
|
||||
and_(
|
||||
SectionPrinter.section_id == id_,
|
||||
SectionPrinter.menu_category_id != None,
|
||||
~SectionPrinter.menu_category_id.in_([x for x in current if x is not None]),
|
||||
~SectionPrinter.menu_category_id.in_(
|
||||
[x for x in current if x is not None]
|
||||
),
|
||||
)
|
||||
)
|
||||
)
|
||||
@@ -70,7 +77,8 @@ def save(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -79,7 +87,9 @@ def save(
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["section-printers"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["section-printers"]),
|
||||
):
|
||||
try:
|
||||
SectionPrinter.__table__.delete(SectionPrinter.section_id == id_)
|
||||
@@ -88,7 +98,8 @@ def delete(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -97,14 +108,17 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["section-printers"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["section-printers"]),
|
||||
):
|
||||
return report(None, db)
|
||||
|
||||
|
||||
@router.get("/{id_}")
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["section-printers"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["section-printers"]),
|
||||
):
|
||||
return report(id_, db)
|
||||
|
||||
@@ -130,17 +144,27 @@ def show_id(
|
||||
|
||||
|
||||
def report(section_id: uuid.UUID, db: Session):
|
||||
menu_categories = db.query(MenuCategory.id, MenuCategory.name).filter(MenuCategory.is_active == True).order_by(MenuCategory.sort_order).all()
|
||||
menu_categories = (
|
||||
db.query(MenuCategory.id, MenuCategory.name)
|
||||
.filter(MenuCategory.is_active == True)
|
||||
.order_by(MenuCategory.sort_order)
|
||||
.all()
|
||||
)
|
||||
list_ = []
|
||||
for item in [(None,)] + menu_categories:
|
||||
mc = (
|
||||
db.query(SectionPrinter)
|
||||
.filter(SectionPrinter.section_id == section_id, SectionPrinter.menu_category_id == item[0])
|
||||
.filter(
|
||||
SectionPrinter.section_id == section_id,
|
||||
SectionPrinter.menu_category_id == item[0],
|
||||
)
|
||||
.first()
|
||||
)
|
||||
list_.append(
|
||||
{
|
||||
"menuCategory": {} if item[0] is None else {"id": item[0], "name": item[1]},
|
||||
"menuCategory": {}
|
||||
if item[0] is None
|
||||
else {"id": item[0], "name": item[1]},
|
||||
"printer": {} if mc is None else {"id": mc.printer_id},
|
||||
"copies": 0 if mc is None else mc.copies,
|
||||
}
|
||||
|
||||
@@ -3,10 +3,11 @@ import uuid
|
||||
from fastapi import APIRouter, Depends, Security
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..schemas.auth import UserToken
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models.master import DbSetting
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
import uuid
|
||||
from typing import Optional, List
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
from typing import List, Optional
|
||||
|
||||
import barker.schemas.master as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import Overview
|
||||
from ..schemas.auth import UserToken
|
||||
import barker.schemas.master as schemas
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models import Overview
|
||||
from ..models.master import FoodTable
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -26,7 +29,8 @@ def get_db():
|
||||
|
||||
@router.post("/list", response_model=List[schemas.Table])
|
||||
def sort_order(
|
||||
data: List[schemas.Table], db: Session = Depends(get_db),
|
||||
data: List[schemas.Table],
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["tables"]),
|
||||
):
|
||||
try:
|
||||
@@ -49,7 +53,8 @@ def sort_order(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -58,17 +63,25 @@ def sort_order(
|
||||
|
||||
@router.post("", response_model=schemas.Table)
|
||||
def save(
|
||||
data: schemas.TableIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["tables"]),
|
||||
data: schemas.TableIn,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["tables"]),
|
||||
):
|
||||
try:
|
||||
item = FoodTable(name=data.name, seats=data.seats, section_id=data.section.id_, is_active=data.is_active)
|
||||
item = FoodTable(
|
||||
name=data.name,
|
||||
seats=data.seats,
|
||||
section_id=data.section.id_,
|
||||
is_active=data.is_active,
|
||||
)
|
||||
db.add(item)
|
||||
db.commit()
|
||||
return food_table_info(item)
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -93,7 +106,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -102,7 +116,9 @@ def update(
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["tables"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["tables"]),
|
||||
):
|
||||
try:
|
||||
item: FoodTable = db.query(FoodTable).filter(FoodTable.id == id_).first()
|
||||
@@ -112,7 +128,8 @@ def delete(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -121,7 +138,8 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["tables"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["tables"]),
|
||||
):
|
||||
return food_table_info(None)
|
||||
|
||||
@@ -143,7 +161,12 @@ def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get_user)
|
||||
|
||||
@router.get("/running")
|
||||
def show_running(db: Session = Depends(get_db), user: UserToken = Depends(get_user)):
|
||||
list_ = db.query(FoodTable).filter(FoodTable.is_active == True).order_by(FoodTable.sort_order).all()
|
||||
list_ = (
|
||||
db.query(FoodTable)
|
||||
.filter(FoodTable.is_active == True)
|
||||
.order_by(FoodTable.sort_order)
|
||||
.all()
|
||||
)
|
||||
|
||||
food_tables = []
|
||||
for item in list_:
|
||||
@@ -169,7 +192,9 @@ def show_running(db: Session = Depends(get_db), user: UserToken = Depends(get_us
|
||||
|
||||
@router.get("/from-voucher/{id_}")
|
||||
def show_voucher(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user),
|
||||
):
|
||||
overview: Overview = db.query(Overview).filter(Overview.voucher_id == id_).first()
|
||||
if overview is not None:
|
||||
@@ -179,7 +204,9 @@ def show_voucher(
|
||||
|
||||
@router.get("/{id_}")
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["tables"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["tables"]),
|
||||
):
|
||||
item: FoodTable = db.query(FoodTable).filter(FoodTable.id == id_).first()
|
||||
return food_table_info(item)
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
import uuid
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.master as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..schemas.auth import UserToken
|
||||
import barker.schemas.master as schemas
|
||||
from ..core.security import get_current_active_user as get_user
|
||||
from ..db.session import SessionLocal
|
||||
from ..models.master import Tax
|
||||
from ..schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -26,7 +29,9 @@ def get_db():
|
||||
|
||||
@router.post("", response_model=schemas.Tax)
|
||||
def save(
|
||||
data: schemas.TaxIn, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["taxes"]),
|
||||
data: schemas.TaxIn,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["taxes"]),
|
||||
):
|
||||
try:
|
||||
item = Tax(name=data.name, rate=round(data.rate / Decimal(100), 4))
|
||||
@@ -36,7 +41,8 @@ def save(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -54,7 +60,8 @@ def update(
|
||||
item: Tax = db.query(Tax).filter(Tax.id == id_).first()
|
||||
if item.is_fixture:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_423_LOCKED, detail=f"{item.name} is a fixture and cannot be edited or deleted.",
|
||||
status_code=status.HTTP_423_LOCKED,
|
||||
detail=f"{item.name} is a fixture and cannot be edited or deleted.",
|
||||
)
|
||||
item.name = data.name
|
||||
item.rate = round(data.rate / Decimal(100), 4)
|
||||
@@ -63,7 +70,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -72,17 +80,21 @@ def update(
|
||||
|
||||
@router.delete("/{id_}")
|
||||
def delete(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["taxes"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["taxes"]),
|
||||
):
|
||||
try:
|
||||
item: Tax = db.query(Tax).filter(Tax.id == id_).first()
|
||||
if item is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Tax not found",
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Tax not found",
|
||||
)
|
||||
elif item.is_fixture:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_423_LOCKED, detail=f"{item.name} is a fixture and cannot be edited or deleted.",
|
||||
status_code=status.HTTP_423_LOCKED,
|
||||
detail=f"{item.name} is a fixture and cannot be edited or deleted.",
|
||||
)
|
||||
else:
|
||||
db.delete(item)
|
||||
@@ -95,7 +107,8 @@ def delete(
|
||||
|
||||
@router.get("")
|
||||
def show_blank(
|
||||
db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["taxes"]),
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["taxes"]),
|
||||
):
|
||||
return tax_info(None)
|
||||
|
||||
@@ -103,14 +116,21 @@ def show_blank(
|
||||
@router.get("/list")
|
||||
def show_list(db: Session = Depends(get_db), user: UserToken = Depends(get_user)):
|
||||
return [
|
||||
{"id": item.id, "name": item.name, "rate": item.rate, "isFixture": item.is_fixture}
|
||||
{
|
||||
"id": item.id,
|
||||
"name": item.name,
|
||||
"rate": item.rate,
|
||||
"isFixture": item.is_fixture,
|
||||
}
|
||||
for item in db.query(Tax).order_by(Tax.name).all()
|
||||
]
|
||||
|
||||
|
||||
@router.get("/{id_}")
|
||||
def show_id(
|
||||
id_: uuid.UUID, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["taxes"]),
|
||||
id_: uuid.UUID,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["taxes"]),
|
||||
):
|
||||
item: Tax = db.query(Tax).filter(Tax.id == id_).first()
|
||||
return tax_info(item)
|
||||
|
||||
@@ -1,22 +1,21 @@
|
||||
import uuid
|
||||
from typing import Optional, List
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from barker.models import (
|
||||
GuestBook,
|
||||
Overview,
|
||||
Settlement,
|
||||
SettleOption,
|
||||
Voucher,
|
||||
VoucherType,
|
||||
)
|
||||
from barker.schemas.receive_payment import ReceivePaymentItem as SettleSchema
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
from starlette import status
|
||||
|
||||
from barker.models import (
|
||||
VoucherType,
|
||||
Settlement,
|
||||
SettleOption,
|
||||
Voucher,
|
||||
Overview,
|
||||
GuestBook,
|
||||
)
|
||||
|
||||
from barker.schemas.receive_payment import ReceivePaymentItem as SettleSchema
|
||||
|
||||
|
||||
def get_tax(tax, voucher_type):
|
||||
if voucher_type in [VoucherType.STAFF, VoucherType.NO_CHARGE]:
|
||||
@@ -25,7 +24,8 @@ def get_tax(tax, voucher_type):
|
||||
return tax
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Unexpected Voucher Type",
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Unexpected Voucher Type",
|
||||
)
|
||||
|
||||
|
||||
@@ -56,31 +56,38 @@ def do_update_table(item: Voucher, guest_book: Optional[GuestBook], db: Session)
|
||||
item.status.status = status_
|
||||
|
||||
|
||||
def check_permissions(item: Optional[Voucher], voucher_type: VoucherType, permissions: List[str]):
|
||||
def check_permissions(
|
||||
item: Optional[Voucher], voucher_type: VoucherType, permissions: List[str]
|
||||
):
|
||||
if voucher_type == VoucherType.KOT and "print-kot" not in permissions:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="You are not allowed to print a kot",
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You are not allowed to print a kot",
|
||||
)
|
||||
if voucher_type != VoucherType.KOT and "print-bill" not in permissions:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="You are not allowed to print bill",
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You are not allowed to print bill",
|
||||
)
|
||||
|
||||
if item is None:
|
||||
return
|
||||
if item.voucher_type != VoucherType.KOT and "edit-printed-bill" not in permissions:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="You are not allowed to edit a printed bill",
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You are not allowed to edit a printed bill",
|
||||
)
|
||||
|
||||
if item.voucher_type != VoucherType.KOT and voucher_type == VoucherType.KOT:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="This Bill is already printed\nCannot add a Kot to it.",
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="This Bill is already printed\nCannot add a Kot to it.",
|
||||
)
|
||||
|
||||
if item.voucher_type == VoucherType.VOID:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail=f"This Bill is already void.\nReason: {item.reason}",
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"This Bill is already void.\nReason: {item.reason}",
|
||||
)
|
||||
|
||||
|
||||
@@ -101,7 +108,8 @@ def do_update_settlements(voucher: Voucher, others: List[SettleSchema], db: Sess
|
||||
unsettled = sum(x.amount for x in settlements)
|
||||
if len(others) and unsettled != 0: # This should not be allowed
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Payment received is not equal to bill amount",
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Payment received is not equal to bill amount",
|
||||
)
|
||||
if unsettled != 0:
|
||||
settlements.append(SettleSchema(id=SettleOption.UNSETTLED(), amount=unsettled))
|
||||
@@ -115,6 +123,8 @@ def do_update_settlements(voucher: Voucher, others: List[SettleSchema], db: Sess
|
||||
voucher.settlements.append(s)
|
||||
db.add(s)
|
||||
|
||||
for i in (i for i in voucher.settlements if i.settled not in [x.id_ for x in settlements]):
|
||||
for i in (
|
||||
i for i in voucher.settlements if i.settled not in [x.id_ for x in settlements]
|
||||
):
|
||||
voucher.settlements.remove(i)
|
||||
db.delete(i)
|
||||
@@ -1,22 +1,22 @@
|
||||
import uuid
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.voucher as schemas
|
||||
|
||||
from barker.schemas.receive_payment import ReceivePaymentItem as SettleSchema
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from .save import do_save
|
||||
from ...schemas.auth import UserToken
|
||||
import barker.schemas.voucher as schemas
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import Voucher, SettleOption, Overview, Reprint
|
||||
from ...routers.voucher import (
|
||||
do_update_settlements,
|
||||
get_guest_book,
|
||||
)
|
||||
from barker.schemas.receive_payment import ReceivePaymentItem as SettleSchema
|
||||
from ...models import Overview, Reprint, SettleOption, Voucher
|
||||
from ...routers.voucher import do_update_settlements, get_guest_book
|
||||
from ...schemas.auth import UserToken
|
||||
from .save import do_save
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -43,7 +43,12 @@ def change(
|
||||
old: Voucher = db.query(Voucher).filter(Voucher.id == id_).first()
|
||||
amount_changed: bool = old.amount != round(
|
||||
sum(
|
||||
Decimal((0 if i.is_happy_hour else i.price) * i.quantity * (1 - i.discount) * (1 + i.tax_rate))
|
||||
Decimal(
|
||||
(0 if i.is_happy_hour else i.price)
|
||||
* i.quantity
|
||||
* (1 - i.discount)
|
||||
* (1 + i.tax_rate)
|
||||
)
|
||||
for k in data.kots
|
||||
for i in k.inventories
|
||||
),
|
||||
@@ -60,7 +65,8 @@ def change(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -73,7 +79,12 @@ def reprint_bill(voucher_id: uuid.UUID, user_id: uuid.UUID, db: Session):
|
||||
|
||||
|
||||
def void_and_issue_new_bill(
|
||||
data: schemas.VoucherIn, u: bool, g: Optional[uuid.UUID], old: Voucher, db: Session, user: UserToken
|
||||
data: schemas.VoucherIn,
|
||||
u: bool,
|
||||
g: Optional[uuid.UUID],
|
||||
old: Voucher,
|
||||
db: Session,
|
||||
user: UserToken,
|
||||
):
|
||||
update_table = u
|
||||
guest_book = get_guest_book(g, db)
|
||||
@@ -81,11 +92,17 @@ def void_and_issue_new_bill(
|
||||
db.flush()
|
||||
old.void = True
|
||||
old.void_reason = f"Bill Discounted / Changed. New Bill ID is {item.full_bill_id}"
|
||||
do_update_settlements(old, [SettleSchema(id=SettleOption.VOID(), amount=round(old.amount))], db)
|
||||
do_update_settlements(
|
||||
old, [SettleSchema(id=SettleOption.VOID(), amount=round(old.amount))], db
|
||||
)
|
||||
|
||||
if update_table:
|
||||
if old.status is None:
|
||||
item.status = Overview(voucher_id=None, food_table_id=item.food_table_id, status="printed")
|
||||
item.status = Overview(
|
||||
voucher_id=None, food_table_id=item.food_table_id, status="printed"
|
||||
)
|
||||
db.add(item.status)
|
||||
else:
|
||||
db.query(Overview).filter(Overview.voucher_id == old.id).update({Overview.voucher_id: item.id})
|
||||
db.query(Overview).filter(Overview.voucher_id == old.id).update(
|
||||
{Overview.voucher_id: item.id}
|
||||
)
|
||||
@@ -1,22 +1,21 @@
|
||||
import uuid
|
||||
|
||||
from datetime import datetime
|
||||
from typing import List
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.merge_move as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...schemas.auth import UserToken
|
||||
import barker.schemas.merge_move as schemas
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import Voucher, Kot, Overview, Settlement
|
||||
from ...routers.voucher import (
|
||||
do_update_settlements,
|
||||
get_bill_id,
|
||||
do_update_table,
|
||||
)
|
||||
from ...models import Kot, Overview, Settlement, Voucher
|
||||
from ...routers.voucher import do_update_settlements, do_update_table, get_bill_id
|
||||
from ...schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -32,16 +31,21 @@ def get_db():
|
||||
|
||||
@router.post("/move-kot/merge")
|
||||
def merge_kot(
|
||||
data: schemas.MergeKot, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["merge-kots"]),
|
||||
data: schemas.MergeKot,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["merge-kots"]),
|
||||
):
|
||||
try:
|
||||
db.query(Kot).filter(Kot.id == data.kot_id).update({Kot.voucher_id: data.new_voucher_id})
|
||||
db.query(Kot).filter(Kot.id == data.kot_id).update(
|
||||
{Kot.voucher_id: data.new_voucher_id}
|
||||
)
|
||||
update_vouchers([data.voucher_id, data.new_voucher_id], db)
|
||||
db.commit()
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -80,7 +84,8 @@ def move_kot(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -89,18 +94,23 @@ def move_kot(
|
||||
|
||||
@router.post("/move-table/move")
|
||||
def move_table(
|
||||
data: schemas.MoveTable, db: Session = Depends(get_db), user: UserToken = Security(get_user, scopes=["move-table"]),
|
||||
data: schemas.MoveTable,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user, scopes=["move-table"]),
|
||||
):
|
||||
try:
|
||||
db.query(Overview).filter(Overview.voucher_id == data.voucher_id).update(
|
||||
{Overview.food_table_id: data.table_id}
|
||||
)
|
||||
db.query(Voucher).filter(Voucher.id == data.voucher_id).update({Voucher.food_table_id: data.table_id})
|
||||
db.query(Voucher).filter(Voucher.id == data.voucher_id).update(
|
||||
{Voucher.food_table_id: data.table_id}
|
||||
)
|
||||
db.commit()
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -114,7 +124,9 @@ def merge_table(
|
||||
user: UserToken = Security(get_user, scopes=["merge-tables"]),
|
||||
):
|
||||
try:
|
||||
db.query(Kot).filter(Kot.voucher_id == data.voucher_id).update({Kot.voucher_id: data.new_voucher_id})
|
||||
db.query(Kot).filter(Kot.voucher_id == data.voucher_id).update(
|
||||
{Kot.voucher_id: data.new_voucher_id}
|
||||
)
|
||||
db.query(Overview).filter(Overview.voucher_id == data.voucher_id).delete()
|
||||
db.query(Settlement).filter(Settlement.voucher_id == data.voucher_id).delete()
|
||||
db.query(Voucher).filter(Voucher.id == data.voucher_id).delete()
|
||||
@@ -123,7 +135,8 @@ def merge_table(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.receive_payment as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from . import do_update_settlements
|
||||
from ...schemas.auth import UserToken
|
||||
import barker.schemas.receive_payment as schemas
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import Voucher, VoucherType, SettleOption, Settlement, Overview
|
||||
from ...models import Overview, Settlement, SettleOption, Voucher, VoucherType
|
||||
from ...schemas.auth import UserToken
|
||||
from . import do_update_settlements
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -34,7 +36,10 @@ def update(
|
||||
try:
|
||||
update_table = u
|
||||
amounts = [
|
||||
j for j in data.amounts if j.amount != 0 and j.id_ not in [SettleOption.AMOUNT(), SettleOption.ROUND_OFF()]
|
||||
j
|
||||
for j in data.amounts
|
||||
if j.amount != 0
|
||||
and j.id_ not in [SettleOption.AMOUNT(), SettleOption.ROUND_OFF()]
|
||||
]
|
||||
for i in amounts:
|
||||
i.amount = round(i.amount, 0)
|
||||
@@ -52,7 +57,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
|
||||
@@ -1,26 +1,37 @@
|
||||
import uuid
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.voucher as schemas
|
||||
|
||||
from barker.printing import print_bill, print_kot
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...schemas.auth import UserToken
|
||||
import barker.schemas.voucher as schemas
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import Voucher, VoucherType, Kot, Product, Inventory, InventoryModifier, GuestBook
|
||||
from ...routers.voucher import (
|
||||
get_tax,
|
||||
do_update_settlements,
|
||||
get_bill_id,
|
||||
do_update_table,
|
||||
check_permissions,
|
||||
get_guest_book,
|
||||
from ...models import (
|
||||
GuestBook,
|
||||
Inventory,
|
||||
InventoryModifier,
|
||||
Kot,
|
||||
Product,
|
||||
Voucher,
|
||||
VoucherType,
|
||||
)
|
||||
from barker.printing import print_kot, print_bill
|
||||
from ...routers.voucher import (
|
||||
check_permissions,
|
||||
do_update_settlements,
|
||||
do_update_table,
|
||||
get_bill_id,
|
||||
get_guest_book,
|
||||
get_tax,
|
||||
)
|
||||
from ...schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -57,7 +68,8 @@ def save(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -120,6 +132,7 @@ def do_save(
|
||||
do_update_settlements(item, [], db)
|
||||
if len(item.kots) == 0 or len(item.kots[0].inventories) == 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Please add some products",
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Please add some products",
|
||||
)
|
||||
return item
|
||||
@@ -1,14 +1,16 @@
|
||||
import re
|
||||
import uuid
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...schemas.auth import UserToken
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import Voucher, Overview, FoodTable, GuestBook, VoucherType
|
||||
from ...models import FoodTable, GuestBook, Overview, Voucher, VoucherType
|
||||
from ...schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -24,7 +26,9 @@ def get_db():
|
||||
|
||||
@router.get("/from-id/{id_}")
|
||||
def from_id(
|
||||
id_: str, db: Session = Depends(get_db), user: UserToken = Security(get_user),
|
||||
id_: str,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user),
|
||||
):
|
||||
item: Voucher = db.query(Voucher).filter(Voucher.id == id_).first()
|
||||
return voucher_info(item)
|
||||
@@ -32,15 +36,26 @@ def from_id(
|
||||
|
||||
@router.get("/from-bill/{id_}")
|
||||
def from_bill(
|
||||
id_: str, db: Session = Depends(get_db), user: UserToken = Security(get_user),
|
||||
id_: str,
|
||||
db: Session = Depends(get_db),
|
||||
user: UserToken = Security(get_user),
|
||||
):
|
||||
item: Voucher = db.query(Voucher)
|
||||
if re.compile(r"^\d{2,}-\d{4}$").match(id_):
|
||||
item = item.filter(Voucher.bill_id == int(id_.replace("-", "")), Voucher.voucher_type.in_([1, 3]),)
|
||||
item = item.filter(
|
||||
Voucher.bill_id == int(id_.replace("-", "")),
|
||||
Voucher.voucher_type.in_([1, 3]),
|
||||
)
|
||||
elif re.compile(r"^NC-\d+$").match(id_):
|
||||
item = item.filter(Voucher.bill_id == int(id_.replace("NC-", "")), Voucher.voucher_type == 2,)
|
||||
item = item.filter(
|
||||
Voucher.bill_id == int(id_.replace("NC-", "")),
|
||||
Voucher.voucher_type == 2,
|
||||
)
|
||||
elif re.compile(r"^ST-\d+$").match(id_):
|
||||
item = item.filter(Voucher.bill_id == int(id_.replace("ST-", "")), Voucher.voucher_type == 4,)
|
||||
item = item.filter(
|
||||
Voucher.bill_id == int(id_.replace("ST-", "")),
|
||||
Voucher.voucher_type == 4,
|
||||
)
|
||||
item = item.first()
|
||||
if item is None:
|
||||
return {}
|
||||
@@ -56,10 +71,18 @@ def from_bill(
|
||||
user: UserToken = Security(get_user),
|
||||
):
|
||||
if v is not None:
|
||||
item = db.query(Overview).filter(Overview.voucher_id == v, Overview.food_table_id == id_,).first()
|
||||
item = (
|
||||
db.query(Overview)
|
||||
.filter(
|
||||
Overview.voucher_id == v,
|
||||
Overview.food_table_id == id_,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if item is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND, detail="Voucher not found",
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Voucher not found",
|
||||
)
|
||||
else:
|
||||
return voucher_info(item.voucher)
|
||||
@@ -84,7 +107,9 @@ def voucher_info(item: Voucher):
|
||||
"lastEditDateTip": item.last_edit_date.strftime("%d-%b-%Y %H:%M:%S"),
|
||||
"billId": item.full_bill_id,
|
||||
"table": {"id": item.food_table_id, "name": item.food_table.name},
|
||||
"customer": {"id": item.customer_id, "name": item.customer.name} if item.customer is not None else None,
|
||||
"customer": {"id": item.customer_id, "name": item.customer.name}
|
||||
if item.customer is not None
|
||||
else None,
|
||||
"settlements": [],
|
||||
"narration": item.narration,
|
||||
"reason": item.reason,
|
||||
@@ -108,7 +133,10 @@ def voucher_info(item: Voucher):
|
||||
"name": i.product.menu_category.name,
|
||||
"discountLimit": i.product.menu_category.discount_limit,
|
||||
},
|
||||
"saleCategory": {"id": i.product.sale_category_id, "name": i.product.sale_category.name,},
|
||||
"saleCategory": {
|
||||
"id": i.product.sale_category_id,
|
||||
"name": i.product.sale_category.name,
|
||||
},
|
||||
},
|
||||
"quantity": i.quantity,
|
||||
"price": i.price,
|
||||
@@ -117,7 +145,12 @@ def voucher_info(item: Voucher):
|
||||
"tax": {"id": i.tax_id, "name": i.tax.name},
|
||||
"discount": i.discount,
|
||||
"modifiers": [
|
||||
{"id": m.modifier.id, "name": m.modifier.name, "price": m.price,} for m in i.modifiers
|
||||
{
|
||||
"id": m.modifier.id,
|
||||
"name": m.modifier.name,
|
||||
"price": m.price,
|
||||
}
|
||||
for m in i.modifiers
|
||||
],
|
||||
}
|
||||
for i in k.inventories
|
||||
@@ -134,6 +167,8 @@ def voucher_blank(table: FoodTable, guest: Optional[GuestBook]):
|
||||
"pax": table.seats if guest is None else guest.pax,
|
||||
"table": {"id": table.id, "name": table.name},
|
||||
"voucherType": VoucherType.KOT.name,
|
||||
"customer": {"id": guest.customer_id, "name": guest.customer.name} if guest is not None else None,
|
||||
"customer": {"id": guest.customer_id, "name": guest.customer.name}
|
||||
if guest is not None
|
||||
else None,
|
||||
"kots": [],
|
||||
}
|
||||
@@ -1,24 +1,35 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
import barker.schemas.split as schemas
|
||||
|
||||
from barker.schemas.receive_payment import ReceivePaymentItem as SettleSchema
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...schemas.auth import UserToken
|
||||
import barker.schemas.split as schemas
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import Voucher, VoucherType, Kot, Inventory, InventoryModifier, SettleOption, Overview
|
||||
from ...routers.voucher import (
|
||||
do_update_settlements,
|
||||
get_bill_id,
|
||||
do_update_table,
|
||||
check_permissions,
|
||||
from ...models import (
|
||||
Inventory,
|
||||
InventoryModifier,
|
||||
Kot,
|
||||
Overview,
|
||||
SettleOption,
|
||||
Voucher,
|
||||
VoucherType,
|
||||
)
|
||||
from barker.schemas.receive_payment import ReceivePaymentItem as SettleSchema
|
||||
from ...routers.voucher import (
|
||||
check_permissions,
|
||||
do_update_settlements,
|
||||
do_update_table,
|
||||
get_bill_id,
|
||||
)
|
||||
from ...schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -46,19 +57,41 @@ def split(
|
||||
item: Voucher = db.query(Voucher).filter(Voucher.id == id_).first()
|
||||
item.void = True
|
||||
item.reason = "Bill Split"
|
||||
do_update_settlements(item, [SettleSchema(id=SettleOption.VOID(), amount=round(item.amount))], db)
|
||||
do_update_settlements(
|
||||
item, [SettleSchema(id=SettleOption.VOID(), amount=round(item.amount))], db
|
||||
)
|
||||
if update_table:
|
||||
db.query(Overview).filter(Overview.voucher_id == item.id).delete()
|
||||
check_permissions(None, item.voucher_type, user.permissions)
|
||||
|
||||
one_inventories = [i for k in item.kots for i in k.inventories if i.id in data.inventories]
|
||||
two_inventories = [i for k in item.kots for i in k.inventories if i.id not in data.inventories]
|
||||
one_inventories = [
|
||||
i for k in item.kots for i in k.inventories if i.id in data.inventories
|
||||
]
|
||||
two_inventories = [
|
||||
i for k in item.kots for i in k.inventories if i.id not in data.inventories
|
||||
]
|
||||
|
||||
one = save(one_inventories, now, item.voucher_type, 0, data.table_id, item.customer_id, user.id_, db,)
|
||||
one = save(
|
||||
one_inventories,
|
||||
now,
|
||||
item.voucher_type,
|
||||
0,
|
||||
data.table_id,
|
||||
item.customer_id,
|
||||
user.id_,
|
||||
db,
|
||||
)
|
||||
if update_table:
|
||||
do_update_table(one, None, db)
|
||||
two = save(
|
||||
two_inventories, now, item.voucher_type, item.pax, item.food_table_id, item.customer_id, user.id_, db,
|
||||
two_inventories,
|
||||
now,
|
||||
item.voucher_type,
|
||||
item.pax,
|
||||
item.food_table_id,
|
||||
item.customer_id,
|
||||
user.id_,
|
||||
db,
|
||||
)
|
||||
if update_table:
|
||||
do_update_table(two, None, db)
|
||||
@@ -66,7 +99,8 @@ def split(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
@@ -92,19 +126,26 @@ def save(
|
||||
for (product, happy_hour), (inventory, quantity) in product_quantities.items():
|
||||
if quantity < 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="Quantity of a product is negative",
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Quantity of a product is negative",
|
||||
)
|
||||
bill_id = get_bill_id(voucher_type, db)
|
||||
kot_id = db.query(func.coalesce(func.max(Voucher.kot_id), 0) + 1).scalar()
|
||||
|
||||
item: Voucher = Voucher(now, pax, bill_id, kot_id, table_id, customer_id, voucher_type, user_id)
|
||||
item: Voucher = Voucher(
|
||||
now, pax, bill_id, kot_id, table_id, customer_id, voucher_type, user_id
|
||||
)
|
||||
db.add(item)
|
||||
code = db.query(func.coalesce(func.max(Kot.code), 0) + 1).scalar()
|
||||
kot = Kot(item.id, code, item.food_table_id, item.date, item.user_id)
|
||||
item.kots.append(kot)
|
||||
db.add(kot) # Multiple inventories of the same product give a key error, but combining messes with modifiers, this
|
||||
db.add(
|
||||
kot
|
||||
) # Multiple inventories of the same product give a key error, but combining messes with modifiers, this
|
||||
# will get important when modifiers have a price.
|
||||
for index, (old_inventory, q) in enumerate([i for i in product_quantities.values() if i[1] != 0]):
|
||||
for index, (old_inventory, q) in enumerate(
|
||||
[i for i in product_quantities.values() if i[1] != 0]
|
||||
):
|
||||
inv = Inventory(
|
||||
kot.id,
|
||||
old_inventory.product_id,
|
||||
@@ -126,7 +167,8 @@ def save(
|
||||
|
||||
if len(kot.inventories) == 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail="No inventories selected",
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="No inventories selected",
|
||||
)
|
||||
db.flush()
|
||||
return item
|
||||
@@ -1,26 +1,29 @@
|
||||
import uuid
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
import barker.schemas.voucher as schemas
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ...printing import print_kot, print_bill
|
||||
from ...schemas.auth import UserToken
|
||||
import barker.schemas.voucher as schemas
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import Voucher, VoucherType, Kot, Product, Inventory, InventoryModifier
|
||||
from ...models import Inventory, InventoryModifier, Kot, Product, Voucher, VoucherType
|
||||
from ...printing import print_bill, print_kot
|
||||
from ...routers.voucher import (
|
||||
get_tax,
|
||||
do_update_settlements,
|
||||
get_bill_id,
|
||||
do_update_table,
|
||||
check_permissions,
|
||||
do_update_settlements,
|
||||
do_update_table,
|
||||
get_bill_id,
|
||||
get_guest_book,
|
||||
get_tax,
|
||||
)
|
||||
from ...schemas.auth import UserToken
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -75,7 +78,10 @@ def update(
|
||||
for i in k.inventories:
|
||||
i.tax_rate = get_tax(i.tax_rate, voucher_type)
|
||||
i.discount = next(
|
||||
round(inv.discount, 5) for ko in data.kots for inv in ko.inventories if inv.id_ == i.id
|
||||
round(inv.discount, 5)
|
||||
for ko in data.kots
|
||||
for inv in ko.inventories
|
||||
if inv.id_ == i.id
|
||||
)
|
||||
for k in (k for k in data.kots if k.id_ is None and len(k.inventories) > 0):
|
||||
need_to_print_kot = True
|
||||
@@ -114,7 +120,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, HTTPException, status, Depends, Security
|
||||
from barker.schemas.receive_payment import ReceivePaymentItem as SettleSchema
|
||||
from fastapi import APIRouter, Depends, HTTPException, Security, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from . import do_update_settlements
|
||||
from ...schemas.auth import UserToken
|
||||
from ...core.security import get_current_active_user as get_user
|
||||
from ...db.session import SessionLocal
|
||||
from ...models import Voucher, VoucherType, SettleOption, Overview
|
||||
from barker.schemas.receive_payment import ReceivePaymentItem as SettleSchema
|
||||
from ...models import Overview, SettleOption, Voucher, VoucherType
|
||||
from ...schemas.auth import UserToken
|
||||
from . import do_update_settlements
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -38,7 +39,9 @@ def update(
|
||||
item.reason = reason
|
||||
item.voucher_type = VoucherType.VOID
|
||||
|
||||
do_update_settlements(item, [SettleSchema(id=SettleOption.VOID(), amount=round(item.amount))], db)
|
||||
do_update_settlements(
|
||||
item, [SettleSchema(id=SettleOption.VOID(), amount=round(item.amount))], db
|
||||
)
|
||||
|
||||
if u: # Update table
|
||||
db.query(Overview).filter(Overview.voucher_id == item.id).delete()
|
||||
@@ -47,7 +50,8 @@ def update(
|
||||
except SQLAlchemyError as e:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e),
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=str(e),
|
||||
)
|
||||
except Exception:
|
||||
db.rollback()
|
||||
|
||||
+216
-54
@@ -10,15 +10,24 @@ def includeme(config):
|
||||
config.add_route("v1_devices_list", "/v1/devices")
|
||||
config.add_route("devices_new", "/devices/new")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="devices_new", request_method="GET", permission="Tables",
|
||||
"barker.views.home",
|
||||
route_name="devices_new",
|
||||
request_method="GET",
|
||||
permission="Tables",
|
||||
)
|
||||
config.add_route("devices_id", "/devices/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="devices_id", request_method="GET", permission="Tables",
|
||||
"barker.views.home",
|
||||
route_name="devices_id",
|
||||
request_method="GET",
|
||||
permission="Tables",
|
||||
)
|
||||
config.add_route("devices_list", "/devices")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="devices_list", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="devices_list",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
|
||||
config.add_route("v1_guest_book_new", "/v1/guest-book/new")
|
||||
@@ -26,15 +35,24 @@ def includeme(config):
|
||||
config.add_route("v1_guest_book_list", "/v1/guest-book")
|
||||
config.add_route("guest_book_new", "/guest-book/new")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="guest_book_new", request_method="GET", permission="Guest Book",
|
||||
"barker.views.home",
|
||||
route_name="guest_book_new",
|
||||
request_method="GET",
|
||||
permission="Guest Book",
|
||||
)
|
||||
config.add_route("guest_book_id", "/guest-book/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="guest_book_id", request_method="GET", permission="Guest Book",
|
||||
"barker.views.home",
|
||||
route_name="guest_book_id",
|
||||
request_method="GET",
|
||||
permission="Guest Book",
|
||||
)
|
||||
config.add_route("guest_book_list", "/guest-book")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="guest_book_list", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="guest_book_list",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
|
||||
config.add_route("v1_menu_categories_new", "/v1/menu-categories/new")
|
||||
@@ -42,15 +60,24 @@ def includeme(config):
|
||||
config.add_route("v1_menu_categories_list", "/v1/menu-categories")
|
||||
config.add_route("menu_categories_new", "/menu-categories/new")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="menu_categories_new", request_method="GET", permission="Products",
|
||||
"barker.views.home",
|
||||
route_name="menu_categories_new",
|
||||
request_method="GET",
|
||||
permission="Products",
|
||||
)
|
||||
config.add_route("menu_categories_id", "/menu-categories/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="menu_categories_id", request_method="GET", permission="Products",
|
||||
"barker.views.home",
|
||||
route_name="menu_categories_id",
|
||||
request_method="GET",
|
||||
permission="Products",
|
||||
)
|
||||
config.add_route("menu_categories_list", "/menu-categories")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="menu_categories_list", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="menu_categories_list",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
|
||||
config.add_route("v1_modifier_categories_new", "/v1/modifier-categories/new")
|
||||
@@ -58,15 +85,24 @@ def includeme(config):
|
||||
config.add_route("v1_modifier_categories_list", "/v1/modifier-categories")
|
||||
config.add_route("modifier_categories_new", "/modifier-categories/new")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="modifier_categories_new", request_method="GET", permission="Products",
|
||||
"barker.views.home",
|
||||
route_name="modifier_categories_new",
|
||||
request_method="GET",
|
||||
permission="Products",
|
||||
)
|
||||
config.add_route("modifier_categories_id", "/modifier-categories/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="modifier_categories_id", request_method="GET", permission="Products",
|
||||
"barker.views.home",
|
||||
route_name="modifier_categories_id",
|
||||
request_method="GET",
|
||||
permission="Products",
|
||||
)
|
||||
config.add_route("modifier_categories_list", "/modifier-categories")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="modifier_categories_list", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="modifier_categories_list",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
|
||||
config.add_route("v1_modifiers_new", "/v1/modifiers/new")
|
||||
@@ -74,15 +110,24 @@ def includeme(config):
|
||||
config.add_route("v1_modifiers_list", "/v1/modifiers")
|
||||
config.add_route("modifiers_new", "/modifiers/new")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="modifiers_new", request_method="GET", permission="Products",
|
||||
"barker.views.home",
|
||||
route_name="modifiers_new",
|
||||
request_method="GET",
|
||||
permission="Products",
|
||||
)
|
||||
config.add_route("modifiers_id", "/modifiers/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="modifiers_id", request_method="GET", permission="Products",
|
||||
"barker.views.home",
|
||||
route_name="modifiers_id",
|
||||
request_method="GET",
|
||||
permission="Products",
|
||||
)
|
||||
config.add_route("modifiers_list", "/modifiers")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="modifiers_list", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="modifiers_list",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
|
||||
config.add_route("v1_printers_new", "/v1/printers/new")
|
||||
@@ -90,15 +135,24 @@ def includeme(config):
|
||||
config.add_route("v1_printers_list", "/v1/printers")
|
||||
config.add_route("printers_new", "/printers/new")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="printers_new", request_method="GET", permission="Printers",
|
||||
"barker.views.home",
|
||||
route_name="printers_new",
|
||||
request_method="GET",
|
||||
permission="Printers",
|
||||
)
|
||||
config.add_route("printers_id", "/printers/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="printers_id", request_method="GET", permission="Printers",
|
||||
"barker.views.home",
|
||||
route_name="printers_id",
|
||||
request_method="GET",
|
||||
permission="Printers",
|
||||
)
|
||||
config.add_route("printers_list", "/printers")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="printers_list", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="printers_list",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
|
||||
config.add_route("v1_products_new", "/v1/products/new")
|
||||
@@ -106,15 +160,24 @@ def includeme(config):
|
||||
config.add_route("v1_products_list", "/v1/products")
|
||||
config.add_route("products_new", "/products/new")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="products_new", request_method="GET", permission="Products",
|
||||
"barker.views.home",
|
||||
route_name="products_new",
|
||||
request_method="GET",
|
||||
permission="Products",
|
||||
)
|
||||
config.add_route("products_id", "/products/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="products_id", request_method="GET", permission="Products",
|
||||
"barker.views.home",
|
||||
route_name="products_id",
|
||||
request_method="GET",
|
||||
permission="Products",
|
||||
)
|
||||
config.add_route("products_list", "/products")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="products_list", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="products_list",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
|
||||
config.add_route("v1_roles_new", "/v1/roles/new")
|
||||
@@ -122,15 +185,24 @@ def includeme(config):
|
||||
config.add_route("v1_roles_list", "/v1/roles")
|
||||
config.add_route("roles_new", "/roles/new")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="roles_new", request_method="GET", permission="Users",
|
||||
"barker.views.home",
|
||||
route_name="roles_new",
|
||||
request_method="GET",
|
||||
permission="Users",
|
||||
)
|
||||
config.add_route("roles_id", "/roles/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="roles_id", request_method="GET", permission="Users",
|
||||
"barker.views.home",
|
||||
route_name="roles_id",
|
||||
request_method="GET",
|
||||
permission="Users",
|
||||
)
|
||||
config.add_route("roles_list", "/roles")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="roles_list", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="roles_list",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
|
||||
config.add_route("v1_sale_categories_new", "/v1/sale-categories/new")
|
||||
@@ -138,26 +210,41 @@ def includeme(config):
|
||||
config.add_route("v1_sale_categories_list", "/v1/sale-categories")
|
||||
config.add_route("sale_categories_new", "/sale-categories/new")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="sale_categories_new", request_method="GET", permission="Products",
|
||||
"barker.views.home",
|
||||
route_name="sale_categories_new",
|
||||
request_method="GET",
|
||||
permission="Products",
|
||||
)
|
||||
config.add_route("sale_categories_id", "/sale-categories/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="sale_categories_id", request_method="GET", permission="Products",
|
||||
"barker.views.home",
|
||||
route_name="sale_categories_id",
|
||||
request_method="GET",
|
||||
permission="Products",
|
||||
)
|
||||
config.add_route("sale_categories_list", "/sale-categories")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="sale_categories_list", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="sale_categories_list",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
|
||||
config.add_route("v1_section_printers", "/v1/section-printers")
|
||||
config.add_route("v1_section_printers_id", "/v1/section-printers/{section_id}")
|
||||
config.add_route("section_printers_id", "/section-printers/{section_id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="section_printers_id", request_method="GET", permission="Tables",
|
||||
"barker.views.home",
|
||||
route_name="section_printers_id",
|
||||
request_method="GET",
|
||||
permission="Tables",
|
||||
)
|
||||
config.add_route("section_printers", "/section-printers")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="section_printers", request_method="GET", permission="Tables",
|
||||
"barker.views.home",
|
||||
route_name="section_printers",
|
||||
request_method="GET",
|
||||
permission="Tables",
|
||||
)
|
||||
|
||||
config.add_route("v1_sections_new", "/v1/sections/new")
|
||||
@@ -165,15 +252,24 @@ def includeme(config):
|
||||
config.add_route("v1_sections_list", "/v1/sections")
|
||||
config.add_route("sections_new", "/sections/new")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="sections_new", request_method="GET", permission="Tables",
|
||||
"barker.views.home",
|
||||
route_name="sections_new",
|
||||
request_method="GET",
|
||||
permission="Tables",
|
||||
)
|
||||
config.add_route("sections_id", "/sections/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="sections_id", request_method="GET", permission="Tables",
|
||||
"barker.views.home",
|
||||
route_name="sections_id",
|
||||
request_method="GET",
|
||||
permission="Tables",
|
||||
)
|
||||
config.add_route("sections_list", "/sections")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="sections_list", request_method="GET", permission="Tables",
|
||||
"barker.views.home",
|
||||
route_name="sections_list",
|
||||
request_method="GET",
|
||||
permission="Tables",
|
||||
)
|
||||
|
||||
config.add_route("v1_tables_new", "/v1/tables/new")
|
||||
@@ -181,15 +277,24 @@ def includeme(config):
|
||||
config.add_route("v1_tables_list", "/v1/tables")
|
||||
config.add_route("tables_new", "/tables/new")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="tables_new", request_method="GET", permission="Tables",
|
||||
"barker.views.home",
|
||||
route_name="tables_new",
|
||||
request_method="GET",
|
||||
permission="Tables",
|
||||
)
|
||||
config.add_route("tables_id", "/tables/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="tables_id", request_method="GET", permission="Tables",
|
||||
"barker.views.home",
|
||||
route_name="tables_id",
|
||||
request_method="GET",
|
||||
permission="Tables",
|
||||
)
|
||||
config.add_route("tables_list", "/tables")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="tables_list", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="tables_list",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
|
||||
config.add_route("v1_taxes_new", "/v1/taxes/new")
|
||||
@@ -197,15 +302,24 @@ def includeme(config):
|
||||
config.add_route("v1_taxes_list", "/v1/taxes")
|
||||
config.add_route("taxes_new", "/taxes/new")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="taxes_new", request_method="GET", permission="Taxes",
|
||||
"barker.views.home",
|
||||
route_name="taxes_new",
|
||||
request_method="GET",
|
||||
permission="Taxes",
|
||||
)
|
||||
config.add_route("taxes_id", "/taxes/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="taxes_id", request_method="GET", permission="Taxes",
|
||||
"barker.views.home",
|
||||
route_name="taxes_id",
|
||||
request_method="GET",
|
||||
permission="Taxes",
|
||||
)
|
||||
config.add_route("taxes_list", "/taxes")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="taxes_list", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="taxes_list",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
|
||||
config.add_route("v1_users_new", "/v1/users/new")
|
||||
@@ -213,15 +327,24 @@ def includeme(config):
|
||||
config.add_route("v1_users_list", "/v1/users")
|
||||
config.add_route("users_new", "/users/new")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="users_new", request_method="GET", permission="Users",
|
||||
"barker.views.home",
|
||||
route_name="users_new",
|
||||
request_method="GET",
|
||||
permission="Users",
|
||||
)
|
||||
config.add_route("users_id", "/users/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="users_id", request_method="GET", permission="Users",
|
||||
"barker.views.home",
|
||||
route_name="users_id",
|
||||
request_method="GET",
|
||||
permission="Users",
|
||||
)
|
||||
config.add_route("users_list", "/users")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="users_list", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="users_list",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
|
||||
config.add_route("v1_vouchers_new", "/v1/vouchers/new")
|
||||
@@ -229,11 +352,17 @@ def includeme(config):
|
||||
|
||||
config.add_route("sales", "/sales")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="sales", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="sales",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
config.add_route("sales_catch", "/sales/*rest")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="sales_catch", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="sales_catch",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
|
||||
config.add_route("v1_move_table", "/v1/move-table")
|
||||
@@ -243,46 +372,70 @@ def includeme(config):
|
||||
config.add_route("v1_cashier_report_id", "/v1/cashier-report/{id}")
|
||||
config.add_route("cashier_report_id", "/cashier-report/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="cashier_report_id", request_method="GET", permission="Cashier Checkout",
|
||||
"barker.views.home",
|
||||
route_name="cashier_report_id",
|
||||
request_method="GET",
|
||||
permission="Cashier Checkout",
|
||||
)
|
||||
config.add_route("v1_cashier_report", "/v1/cashier-report")
|
||||
config.add_route("cashier_report", "/cashier-report")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="cashier_report", request_method="GET", permission="Cashier Checkout",
|
||||
"barker.views.home",
|
||||
route_name="cashier_report",
|
||||
request_method="GET",
|
||||
permission="Cashier Checkout",
|
||||
)
|
||||
|
||||
config.add_route("v1_sale_report", "/v1/sale-report")
|
||||
config.add_route("sale_report", "/sale-report")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="sale_report", request_method="GET", permission="Sales Analysis",
|
||||
"barker.views.home",
|
||||
route_name="sale_report",
|
||||
request_method="GET",
|
||||
permission="Sales Analysis",
|
||||
)
|
||||
config.add_route("v1_tax_report", "/v1/tax-report")
|
||||
config.add_route("tax_report", "/tax-report")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="tax_report", request_method="GET", permission="Tax Analysis",
|
||||
"barker.views.home",
|
||||
route_name="tax_report",
|
||||
request_method="GET",
|
||||
permission="Tax Analysis",
|
||||
)
|
||||
|
||||
config.add_route("v1_product_sale_report", "/v1/product-sale-report")
|
||||
config.add_route("product_sale_report", "/product-sale-report")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="product_sale_report", request_method="GET", permission="Sales Detail",
|
||||
"barker.views.home",
|
||||
route_name="product_sale_report",
|
||||
request_method="GET",
|
||||
permission="Sales Detail",
|
||||
)
|
||||
config.add_route("v1_bill_settlement_report", "/v1/bill-settlement-report")
|
||||
config.add_route("bill_settlement_report", "/bill-settlement-report")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="bill_settlement_report", request_method="GET", permission="Bill Details",
|
||||
"barker.views.home",
|
||||
route_name="bill_settlement_report",
|
||||
request_method="GET",
|
||||
permission="Bill Details",
|
||||
)
|
||||
|
||||
config.add_route("v1_beer_consumption_report", "/v1/beer-consumption-report")
|
||||
config.add_route("beer_consumption_report", "/beer-consumption-report")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="beer_consumption_report", request_method="GET", permission="Beer Consumption",
|
||||
"barker.views.home",
|
||||
route_name="beer_consumption_report",
|
||||
request_method="GET",
|
||||
permission="Beer Consumption",
|
||||
)
|
||||
|
||||
config.add_route("v1_discount_report", "/v1/discount-report")
|
||||
config.add_route("discount_report", "/discount-report")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="discount_report", request_method="GET", permission="Discount Report",
|
||||
"barker.views.home",
|
||||
route_name="discount_report",
|
||||
request_method="GET",
|
||||
permission="Discount Report",
|
||||
)
|
||||
|
||||
# config.add_route("v1_bills_new", "/v1/bills/new")
|
||||
@@ -293,15 +446,24 @@ def includeme(config):
|
||||
config.add_route("v1_customers_list", "/v1/customers")
|
||||
config.add_route("customers_new", "/customers/new")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="customers_new", request_method="GET", permission="Customers",
|
||||
"barker.views.home",
|
||||
route_name="customers_new",
|
||||
request_method="GET",
|
||||
permission="Customers",
|
||||
)
|
||||
config.add_route("customers_id", "/customers/{id}")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="customers_id", request_method="GET", permission="Customers",
|
||||
"barker.views.home",
|
||||
route_name="customers_id",
|
||||
request_method="GET",
|
||||
permission="Customers",
|
||||
)
|
||||
config.add_route("customers_list", "/customers")
|
||||
config.add_view(
|
||||
"barker.views.home", route_name="customers_list", request_method="GET", permission="Authenticated",
|
||||
"barker.views.home",
|
||||
route_name="customers_list",
|
||||
request_method="GET",
|
||||
permission="Authenticated",
|
||||
)
|
||||
|
||||
config.add_route("v1_reprint", "/v1/reprint/{id}")
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import uuid
|
||||
from typing import List, Optional
|
||||
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel
|
||||
from typing import List, Optional
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class ClientIn(BaseModel):
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import uuid
|
||||
from typing import Optional, List
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from decimal import Decimal
|
||||
from typing import List, Optional
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from barker.schemas.product import ProductLink
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class CustomerIn(BaseModel):
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from barker.schemas.section import SectionLink
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class DeviceIn(BaseModel):
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import uuid
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from barker.schemas.customer import CustomerIn
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class GuestBookIn(CustomerIn):
|
||||
|
||||
@@ -1,24 +1,36 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, Field, validator
|
||||
from typing import Optional
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from barker.schemas.tax import TaxLink, TaxIn, Tax # noqa: F401
|
||||
from barker.schemas.sale_category import SaleCategoryLink, SaleCategoryIn, SaleCategory # noqa: F401
|
||||
from barker.schemas.customer import CustomerIn, Customer # noqa: F401
|
||||
from barker.schemas.guest_book import GuestBookIn, GuestBook # noqa: F401
|
||||
from barker.schemas.menu_category import MenuCategoryLink, MenuCategoryIn, MenuCategory # noqa: F401
|
||||
from barker.schemas.product import ProductLink, ProductIn, Product # noqa: F401
|
||||
from barker.schemas.modifier_category import ModifierCategoryLink, ModifierCategoryIn, ModifierCategory # noqa: F401
|
||||
from barker.schemas.modifier import ModifierLink, ModifierIn, Modifier # noqa: F401
|
||||
from barker.schemas.printer import PrinterLink, PrinterIn, Printer # noqa: F401
|
||||
from barker.schemas.section import SectionLink, SectionIn, Section # noqa: F401
|
||||
from barker.schemas.device import DeviceLink, DeviceIn, Device # noqa: F401
|
||||
from barker.schemas.customer import Customer, CustomerIn # noqa: F401
|
||||
from barker.schemas.device import Device, DeviceIn, DeviceLink # noqa: F401
|
||||
from barker.schemas.guest_book import GuestBook, GuestBookIn # noqa: F401
|
||||
from barker.schemas.menu_category import ( # noqa: F401
|
||||
MenuCategory,
|
||||
MenuCategoryIn,
|
||||
MenuCategoryLink,
|
||||
)
|
||||
from barker.schemas.modifier import Modifier, ModifierIn, ModifierLink # noqa: F401
|
||||
from barker.schemas.modifier_category import ( # noqa: F401
|
||||
ModifierCategory,
|
||||
ModifierCategoryIn,
|
||||
ModifierCategoryLink,
|
||||
)
|
||||
from barker.schemas.printer import Printer, PrinterIn, PrinterLink # noqa: F401
|
||||
from barker.schemas.product import Product, ProductIn, ProductLink # noqa: F401
|
||||
from barker.schemas.sale_category import ( # noqa: F401
|
||||
SaleCategory,
|
||||
SaleCategoryIn,
|
||||
SaleCategoryLink,
|
||||
)
|
||||
from barker.schemas.section import Section, SectionIn, SectionLink # noqa: F401
|
||||
from barker.schemas.section_printer import SectionPrinter # noqa: F401
|
||||
from barker.schemas.table import TableLink, TableIn, Table # noqa: F401
|
||||
from barker.schemas.table import Table, TableIn, TableLink # noqa: F401
|
||||
from barker.schemas.tax import Tax, TaxIn, TaxLink # noqa: F401
|
||||
from pydantic import BaseModel, Field, validator
|
||||
|
||||
|
||||
class AccountBase(BaseModel):
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import uuid
|
||||
from typing import Optional, List
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from decimal import Decimal
|
||||
from typing import List, Optional
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from barker.schemas.product import ProductLink
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class MenuCategoryIn(BaseModel):
|
||||
@@ -36,5 +36,3 @@ class MenuCategoryLink(BaseModel):
|
||||
|
||||
class Config:
|
||||
fields = {"id_": "id"}
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import uuid
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class MergeKot(BaseModel):
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from decimal import Decimal
|
||||
from typing import Optional
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from barker.schemas.modifier_category import ModifierCategoryLink
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ModifierIn(BaseModel):
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import uuid
|
||||
from typing import Optional, List
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import List, Optional
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from barker.schemas.menu_category import MenuCategoryLink
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ModifierCategoryIn(BaseModel):
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import uuid
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class PrinterIn(BaseModel):
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import uuid
|
||||
from typing import Optional, List
|
||||
|
||||
from decimal import Decimal
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import List, Optional
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from barker.schemas.sale_category import SaleCategoryLink
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ProductLink(BaseModel):
|
||||
@@ -16,7 +17,7 @@ class ProductLink(BaseModel):
|
||||
fields = {"id_": "id"}
|
||||
|
||||
|
||||
class MenuCategoryLink(BaseModel): # Hack to prevent circular error
|
||||
class MenuCategoryLink(BaseModel): # Hack to prevent circular error
|
||||
id_: uuid.UUID = Field(...)
|
||||
products: Optional[List[ProductLink]]
|
||||
|
||||
@@ -29,7 +30,7 @@ class ProductIn(BaseModel):
|
||||
units: str
|
||||
menu_category: MenuCategoryLink = Field(...)
|
||||
sale_category: SaleCategoryLink = Field(...)
|
||||
price: Decimal # = Field(ge=0, multiple_of=0.01, default=0)
|
||||
price: Decimal # = Field(ge=0, multiple_of=0.01, default=0)
|
||||
has_happy_hour: bool
|
||||
is_not_available: bool
|
||||
quantity: Decimal = Field(ge=0, multiple_of=0.01, default=0)
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import uuid
|
||||
from typing import Optional, List
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from decimal import Decimal
|
||||
from typing import List, Optional
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from barker.schemas.customer import CustomerLink
|
||||
@@ -10,6 +9,7 @@ from barker.schemas.modifier import ModifierLink
|
||||
from barker.schemas.product import ProductLink
|
||||
from barker.schemas.table import TableLink
|
||||
from barker.schemas.tax import TaxLink
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ReceivePaymentItem(BaseModel):
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import uuid
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from barker.schemas.tax import TaxLink
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class SaleCategoryIn(BaseModel):
|
||||
@@ -29,5 +29,3 @@ class SaleCategoryLink(BaseModel):
|
||||
|
||||
class Config:
|
||||
fields = {"id_": "id"}
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import uuid
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class SectionIn(BaseModel):
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import uuid
|
||||
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class MenuCategoryLink(BaseModel):
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import uuid
|
||||
|
||||
from typing import List
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class Split(BaseModel):
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from barker.schemas.section import SectionLink
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class TableIn(BaseModel):
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from decimal import Decimal
|
||||
from typing import Optional
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class TaxIn(BaseModel):
|
||||
@@ -33,5 +33,3 @@ class TaxLink(BaseModel):
|
||||
|
||||
class Config:
|
||||
fields = {"id_": "id"}
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import uuid
|
||||
from typing import Optional, List
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from decimal import Decimal
|
||||
from typing import List, Optional
|
||||
|
||||
from barker.schemas import to_camel
|
||||
from barker.schemas.customer import CustomerLink
|
||||
@@ -10,6 +9,7 @@ from barker.schemas.modifier import ModifierLink
|
||||
from barker.schemas.product import ProductLink
|
||||
from barker.schemas.table import TableLink
|
||||
from barker.schemas.tax import TaxLink
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class Inventory(BaseModel):
|
||||
|
||||
@@ -2,33 +2,25 @@ import os
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
import transaction
|
||||
from pyramid.paster import get_appsettings, setup_logging
|
||||
from pyramid.scripts.common import parse_vars
|
||||
|
||||
from barker.models import (
|
||||
Customer,
|
||||
DbSetting,
|
||||
ModifierCategory,
|
||||
Permission,
|
||||
Role,
|
||||
Section,
|
||||
SettleOption,
|
||||
User,
|
||||
get_engine,
|
||||
get_session_factory,
|
||||
get_tm_session,
|
||||
SettleOption,
|
||||
Role,
|
||||
Section,
|
||||
ModifierCategory,
|
||||
)
|
||||
|
||||
|
||||
def usage(argv):
|
||||
cmd = os.path.basename(argv[0])
|
||||
print("usage: %s <config_uri> [var=value]\n" '(example: "%s development.ini")' % (cmd, cmd))
|
||||
print(
|
||||
"usage: %s <config_uri> [var=value]\n"
|
||||
'(example: "%s development.ini")' % (cmd, cmd)
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def main(argv=sys.argv):
|
||||
with transaction.manager:
|
||||
|
||||
|
||||
|
||||
@@ -1,20 +1,6 @@
|
||||
import os
|
||||
import sys
|
||||
|
||||
from pyramid.paster import (
|
||||
get_appsettings,
|
||||
setup_logging,
|
||||
)
|
||||
|
||||
from pyramid.scripts.common import parse_vars
|
||||
|
||||
from barker.models.meta import Base
|
||||
from barker.models import (
|
||||
get_engine,
|
||||
get_session_factory,
|
||||
get_tm_session,
|
||||
)
|
||||
|
||||
from barker.models import (
|
||||
Client,
|
||||
Customer,
|
||||
@@ -35,23 +21,32 @@ from barker.models import (
|
||||
Product,
|
||||
Reprint,
|
||||
Role,
|
||||
role_permissions,
|
||||
SaleCategory,
|
||||
Section,
|
||||
SectionPrinter,
|
||||
SettleOption,
|
||||
Settlement,
|
||||
SettleOption,
|
||||
Tax,
|
||||
User,
|
||||
user_roles,
|
||||
Voucher,
|
||||
VoucherType,
|
||||
get_engine,
|
||||
get_session_factory,
|
||||
get_tm_session,
|
||||
role_permissions,
|
||||
user_roles,
|
||||
)
|
||||
from barker.models.meta import Base
|
||||
from pyramid.paster import get_appsettings, setup_logging
|
||||
from pyramid.scripts.common import parse_vars
|
||||
|
||||
|
||||
def usage(argv):
|
||||
cmd = os.path.basename(argv[0])
|
||||
print("usage: %s <config_uri> [var=value]\n" '(example: "%s development.ini")' % (cmd, cmd))
|
||||
print(
|
||||
"usage: %s <config_uri> [var=value]\n"
|
||||
'(example: "%s development.ini")' % (cmd, cmd)
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
from pyramid.events import subscriber, NewRequest
|
||||
from pyramid.httpexceptions import HTTPServiceUnavailable
|
||||
from barker.models.master import DbSetting
|
||||
from pyramid.events import NewRequest, subscriber
|
||||
from pyramid.httpexceptions import HTTPServiceUnavailable
|
||||
|
||||
|
||||
@subscriber(NewRequest)
|
||||
def maintenance_mode(event):
|
||||
maintenance = event.request.dbsession.query(DbSetting).filter(DbSetting.name == "Maintenance").first()
|
||||
if maintenance is not None and maintenance.data != event.request.authenticated_userid:
|
||||
maintenance = (
|
||||
event.request.dbsession.query(DbSetting)
|
||||
.filter(DbSetting.name == "Maintenance")
|
||||
.first()
|
||||
)
|
||||
if (
|
||||
maintenance is not None
|
||||
and maintenance.data != event.request.authenticated_userid
|
||||
):
|
||||
raise HTTPServiceUnavailable
|
||||
@@ -1,11 +1,13 @@
|
||||
import re
|
||||
import socket
|
||||
import sys
|
||||
|
||||
from celery import Celery
|
||||
from celery.utils.log import get_task_logger
|
||||
|
||||
|
||||
# Create the celery app and get the logger
|
||||
celery_app = Celery('tasks', broker='pyamqp://guest@localhost//')
|
||||
celery_app = Celery("tasks", broker="pyamqp://guest@localhost//")
|
||||
logger = get_task_logger(__name__)
|
||||
|
||||
|
||||
@@ -25,4 +27,5 @@ def sent_to_printer(data: str, address: str, cut_code: str):
|
||||
# finally:
|
||||
# s.close()
|
||||
|
||||
# celery --app=barker.worker.celery_app worker -c 2 --loglevel=INFO
|
||||
|
||||
# celery --app=barker.worker.celery_app worker -c 2 --loglevel=INFO
|
||||
@@ -1,107 +1,127 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
import { Routes, RouterModule } from '@angular/router';
|
||||
import {LoginComponent} from './auth/login/login.component';
|
||||
import {LogoutComponent} from './auth/logout/logout.component';
|
||||
import {HomeComponent} from './home/home.component';
|
||||
|
||||
import { LoginComponent } from './auth/login/login.component';
|
||||
import { LogoutComponent } from './auth/logout/logout.component';
|
||||
import { HomeComponent } from './home/home.component';
|
||||
|
||||
const routes: Routes = [
|
||||
{
|
||||
path: 'beer-consumption-report',
|
||||
loadChildren: () => import('./beer-consumption-report/beer-consumption-report.module').then(mod => mod.BeerConsumptionReportModule)
|
||||
loadChildren: () =>
|
||||
import('./beer-consumption-report/beer-consumption-report.module').then(
|
||||
(mod) => mod.BeerConsumptionReportModule,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'bill-settlement-report',
|
||||
loadChildren: () => import('./bill-settlement-report/bill-settlement-report.module').then(mod => mod.BillSettlementReportModule)
|
||||
loadChildren: () =>
|
||||
import('./bill-settlement-report/bill-settlement-report.module').then(
|
||||
(mod) => mod.BillSettlementReportModule,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'cashier-report',
|
||||
loadChildren: () => import('./cashier-report/cashier-report.module').then(mod => mod.CashierReportModule)
|
||||
loadChildren: () =>
|
||||
import('./cashier-report/cashier-report.module').then((mod) => mod.CashierReportModule),
|
||||
},
|
||||
{
|
||||
path: 'devices',
|
||||
loadChildren: () => import('./devices/devices.module').then(mod => mod.DevicesModule)
|
||||
loadChildren: () => import('./devices/devices.module').then((mod) => mod.DevicesModule),
|
||||
},
|
||||
{
|
||||
path: 'discount-report',
|
||||
loadChildren: () => import('./discount-report/discount-report.module').then(mod => mod.DiscountReportModule)
|
||||
loadChildren: () =>
|
||||
import('./discount-report/discount-report.module').then((mod) => mod.DiscountReportModule),
|
||||
},
|
||||
{
|
||||
path: 'guest-book',
|
||||
loadChildren: () => import('./guest-book/guest-book.module').then(mod => mod.GuestBookModule)
|
||||
loadChildren: () => import('./guest-book/guest-book.module').then((mod) => mod.GuestBookModule),
|
||||
},
|
||||
{
|
||||
path: 'modifiers',
|
||||
loadChildren: () => import('./modifiers/modifiers.module').then(mod => mod.ModifiersModule)
|
||||
loadChildren: () => import('./modifiers/modifiers.module').then((mod) => mod.ModifiersModule),
|
||||
},
|
||||
{
|
||||
path: 'modifier-categories',
|
||||
loadChildren: () => import('./modifier-categories/modifier-categories.module').then(mod => mod.ModifierCategoriesModule)
|
||||
loadChildren: () =>
|
||||
import('./modifier-categories/modifier-categories.module').then(
|
||||
(mod) => mod.ModifierCategoriesModule,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'printers',
|
||||
loadChildren: () => import('./printers/printers.module').then(mod => mod.PrintersModule)
|
||||
loadChildren: () => import('./printers/printers.module').then((mod) => mod.PrintersModule),
|
||||
},
|
||||
{
|
||||
path: 'products',
|
||||
loadChildren: () => import('./product/products.module').then(mod => mod.ProductsModule)
|
||||
loadChildren: () => import('./product/products.module').then((mod) => mod.ProductsModule),
|
||||
},
|
||||
{
|
||||
path: 'product-sale-report',
|
||||
loadChildren: () => import('./product-sale-report/product-sale-report.module').then(mod => mod.ProductSaleReportModule)
|
||||
loadChildren: () =>
|
||||
import('./product-sale-report/product-sale-report.module').then(
|
||||
(mod) => mod.ProductSaleReportModule,
|
||||
),
|
||||
},
|
||||
{
|
||||
path: 'menu-categories',
|
||||
loadChildren: () => import('./menu-category/menu-categories.module').then(mod => mod.MenuCategoriesModule)
|
||||
loadChildren: () =>
|
||||
import('./menu-category/menu-categories.module').then((mod) => mod.MenuCategoriesModule),
|
||||
},
|
||||
{
|
||||
path: 'roles',
|
||||
loadChildren: () => import('./roles/roles.module').then(mod => mod.RolesModule)
|
||||
loadChildren: () => import('./roles/roles.module').then((mod) => mod.RolesModule),
|
||||
},
|
||||
{
|
||||
path: 'sales',
|
||||
loadChildren: () => import('./sales/sales.module').then(mod => mod.SalesModule)
|
||||
loadChildren: () => import('./sales/sales.module').then((mod) => mod.SalesModule),
|
||||
},
|
||||
{
|
||||
path: 'sale-report',
|
||||
loadChildren: () => import('./sale-report/sale-report.module').then(mod => mod.SaleReportModule)
|
||||
loadChildren: () =>
|
||||
import('./sale-report/sale-report.module').then((mod) => mod.SaleReportModule),
|
||||
},
|
||||
{
|
||||
path: 'sale-categories',
|
||||
loadChildren: () => import('./sale-category/sale-categories.module').then(mod => mod.SaleCategoriesModule)
|
||||
loadChildren: () =>
|
||||
import('./sale-category/sale-categories.module').then((mod) => mod.SaleCategoriesModule),
|
||||
},
|
||||
{
|
||||
path: 'sections',
|
||||
loadChildren: () => import('./sections/sections.module').then(mod => mod.SectionsModule)
|
||||
loadChildren: () => import('./sections/sections.module').then((mod) => mod.SectionsModule),
|
||||
},
|
||||
{
|
||||
path: 'section-printers',
|
||||
loadChildren: () => import('./section-printers/section-printers.module').then(mod => mod.SectionPrintersModule)
|
||||
loadChildren: () =>
|
||||
import('./section-printers/section-printers.module').then((mod) => mod.SectionPrintersModule),
|
||||
},
|
||||
{
|
||||
path: 'tables',
|
||||
loadChildren: () => import('./tables/tables.module').then(mod => mod.TableModule)
|
||||
loadChildren: () => import('./tables/tables.module').then((mod) => mod.TableModule),
|
||||
},
|
||||
{
|
||||
path: 'taxes',
|
||||
loadChildren: () => import('./taxes/taxes.module').then(mod => mod.TaxesModule)
|
||||
loadChildren: () => import('./taxes/taxes.module').then((mod) => mod.TaxesModule),
|
||||
},
|
||||
{
|
||||
path: 'tax-report',
|
||||
loadChildren: () => import('./tax-report/tax-report.module').then(mod => mod.TaxReportModule)
|
||||
loadChildren: () => import('./tax-report/tax-report.module').then((mod) => mod.TaxReportModule),
|
||||
},
|
||||
{
|
||||
path: 'users',
|
||||
loadChildren: () => import('./users/users.module').then(mod => mod.UsersModule)
|
||||
loadChildren: () => import('./users/users.module').then((mod) => mod.UsersModule),
|
||||
},
|
||||
{path: 'login', component: LoginComponent},
|
||||
{path: 'logout', component: LogoutComponent},
|
||||
{path: '', component: HomeComponent},
|
||||
{ path: 'login', component: LoginComponent },
|
||||
{ path: 'logout', component: LogoutComponent },
|
||||
{ path: '', component: HomeComponent },
|
||||
];
|
||||
@NgModule({
|
||||
imports: [RouterModule.forRoot(routes,
|
||||
{
|
||||
onSameUrlNavigation: 'reload',
|
||||
})],
|
||||
exports: [RouterModule]
|
||||
imports: [
|
||||
RouterModule.forRoot(routes, {
|
||||
onSameUrlNavigation: 'reload',
|
||||
}),
|
||||
],
|
||||
exports: [RouterModule],
|
||||
})
|
||||
export class AppRoutingModule { }
|
||||
export class AppRoutingModule {}
|
||||
@@ -3,7 +3,7 @@ import { Component } from '@angular/core';
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
templateUrl: './app.component.html',
|
||||
styleUrls: ['./app.component.css']
|
||||
styleUrls: ['./app.component.css'],
|
||||
})
|
||||
export class AppComponent {
|
||||
title = 'bookie';
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import { BrowserModule } from '@angular/platform-browser';
|
||||
import { LOCALE_ID, NgModule } from '@angular/core';
|
||||
import { LayoutModule } from '@angular/cdk/layout';
|
||||
import { registerLocaleData } from '@angular/common';
|
||||
import { HttpClientModule } from '@angular/common/http';
|
||||
import enIN from '@angular/common/locales/en-IN';
|
||||
|
||||
import { AppRoutingModule } from './app-routing.module';
|
||||
import { AppComponent } from './app.component';
|
||||
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
|
||||
import { LOCALE_ID, NgModule } from '@angular/core';
|
||||
import { FlexLayoutModule } from '@angular/flex-layout';
|
||||
import { ReactiveFormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { MatDialogModule } from '@angular/material/dialog';
|
||||
@@ -17,27 +15,23 @@ import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatMenuModule } from '@angular/material/menu';
|
||||
import { MatSnackBarModule } from '@angular/material/snack-bar';
|
||||
import { LayoutModule } from '@angular/cdk/layout';
|
||||
import { LogoutComponent } from './auth/logout/logout.component';
|
||||
import { LoginComponent } from './auth/login/login.component';
|
||||
import { HomeComponent } from './home/home.component';
|
||||
import { CoreModule } from './core/core.module';
|
||||
import { ReactiveFormsModule } from '@angular/forms';
|
||||
import { SharedModule } from './shared/shared.module';
|
||||
import { FlexLayoutModule } from '@angular/flex-layout';
|
||||
import { MatToolbarModule } from '@angular/material/toolbar';
|
||||
import { BrowserModule } from '@angular/platform-browser';
|
||||
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
|
||||
|
||||
import { AppRoutingModule } from './app-routing.module';
|
||||
import { AppComponent } from './app.component';
|
||||
import { LoginComponent } from './auth/login/login.component';
|
||||
import { LogoutComponent } from './auth/logout/logout.component';
|
||||
import { CoreModule } from './core/core.module';
|
||||
import { HomeComponent } from './home/home.component';
|
||||
import { NavBarComponent } from './nav-bar/nav-bar.component';
|
||||
import { SharedModule } from './shared/shared.module';
|
||||
|
||||
registerLocaleData(enIN);
|
||||
|
||||
@NgModule({
|
||||
declarations: [
|
||||
AppComponent,
|
||||
LoginComponent,
|
||||
LogoutComponent,
|
||||
HomeComponent,
|
||||
NavBarComponent
|
||||
],
|
||||
declarations: [AppComponent, LoginComponent, LogoutComponent, HomeComponent, NavBarComponent],
|
||||
imports: [
|
||||
BrowserModule,
|
||||
AppRoutingModule,
|
||||
@@ -58,11 +52,9 @@ registerLocaleData(enIN);
|
||||
LayoutModule,
|
||||
ReactiveFormsModule,
|
||||
CoreModule,
|
||||
SharedModule
|
||||
SharedModule,
|
||||
],
|
||||
providers: [
|
||||
{provide: LOCALE_ID, useValue: 'en-IN'},
|
||||
],
|
||||
bootstrap: [AppComponent]
|
||||
providers: [{ provide: LOCALE_ID, useValue: 'en-IN' }],
|
||||
bootstrap: [AppComponent],
|
||||
})
|
||||
export class AppModule { }
|
||||
export class AppModule {}
|
||||
@@ -1,26 +1,27 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
|
||||
|
||||
import { AuthService } from './auth.service';
|
||||
import { ToasterService } from '../core/toaster.service';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AuthGuard implements CanActivate {
|
||||
constructor(
|
||||
private router: Router,
|
||||
private authService: AuthService,
|
||||
private toaster: ToasterService
|
||||
) {
|
||||
}
|
||||
private toaster: ToasterService,
|
||||
) {}
|
||||
|
||||
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
|
||||
const user = this.authService.user;
|
||||
const permission = (route.data['permission'] === undefined) ? route.data['permission'] : route.data['permission']
|
||||
.replace(/ /g, '-')
|
||||
.toLowerCase();
|
||||
const { user } = this.authService;
|
||||
const permission =
|
||||
route.data.permission === undefined
|
||||
? route.data.permission
|
||||
: route.data.permission.replace(/ /g, '-').toLowerCase();
|
||||
if (!user) {
|
||||
// not logged in so redirect to login page with the return url
|
||||
this.router.navigate(['/login'], {queryParams: {returnUrl: state.url}});
|
||||
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
|
||||
return false;
|
||||
}
|
||||
if (permission !== undefined && user.perms.indexOf(permission) === -1) {
|
||||
@@ -29,6 +30,5 @@ export class AuthGuard implements CanActivate {
|
||||
}
|
||||
// logged in so return true
|
||||
return true;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,16 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { BehaviorSubject, Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
|
||||
import { User } from '../core/user';
|
||||
import { environment } from '../../environments/environment';
|
||||
import { User } from '../core/user';
|
||||
|
||||
const loginUrl = '/token';
|
||||
const refreshUrl = '/refresh';
|
||||
const JWT_USER = 'JWT_USER';
|
||||
|
||||
@Injectable({providedIn: 'root'})
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AuthService {
|
||||
private currentUserSubject: BehaviorSubject<User>;
|
||||
public currentUser: Observable<User>;
|
||||
@@ -20,16 +20,37 @@ export class AuthService {
|
||||
this.currentUser = this.currentUserSubject.asObservable();
|
||||
}
|
||||
|
||||
static parseJwt(token): User {
|
||||
const base64Url = token.split('.')[1];
|
||||
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
|
||||
const jsonPayload = decodeURIComponent(
|
||||
atob(base64)
|
||||
.split('')
|
||||
.map((c) => `%${`00${c.charCodeAt(0).toString(16)}`.slice(-2)}`)
|
||||
.join(''),
|
||||
);
|
||||
|
||||
const decoded = JSON.parse(jsonPayload);
|
||||
return new User({
|
||||
id: decoded.userId,
|
||||
name: decoded.sub,
|
||||
lockedOut: decoded.lockedOut,
|
||||
perms: decoded.scopes,
|
||||
access_token: token,
|
||||
exp: decoded.exp,
|
||||
ver: decoded.ver,
|
||||
});
|
||||
}
|
||||
|
||||
checkStorage(): User {
|
||||
const existingToken: User = JSON.parse(localStorage.getItem(JWT_USER));
|
||||
if (existingToken === null || Date.now() > existingToken.exp * 1000) {
|
||||
localStorage.removeItem(JWT_USER);
|
||||
this.currentUserSubject = new BehaviorSubject<User>(null);
|
||||
return null;
|
||||
} else {
|
||||
this.currentUserSubject = new BehaviorSubject<User>(existingToken);
|
||||
return existingToken;
|
||||
}
|
||||
this.currentUserSubject = new BehaviorSubject<User>(existingToken);
|
||||
return existingToken;
|
||||
}
|
||||
|
||||
public get user(): User {
|
||||
@@ -57,37 +78,22 @@ export class AuthService {
|
||||
formData.append('password', password);
|
||||
formData.append('otp', otp);
|
||||
formData.append('grant_type', 'password');
|
||||
return this.http.post<any>(loginUrl, formData)
|
||||
.pipe(map(u => u.access_token))
|
||||
.pipe(map(u => this.parseJwt(u)))
|
||||
.pipe(map(user => {
|
||||
// store user details and jwt token in local storage to keep user logged in between page refreshes
|
||||
localStorage.setItem(JWT_USER, JSON.stringify(user));
|
||||
this.currentUserSubject.next(user);
|
||||
return user;
|
||||
}));
|
||||
}
|
||||
|
||||
parseJwt(token): User {
|
||||
const base64Url = token.split('.')[1];
|
||||
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
|
||||
const jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
|
||||
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
|
||||
}).join(''));
|
||||
|
||||
const decoded = JSON.parse(jsonPayload);
|
||||
return new User({
|
||||
id: decoded.userId,
|
||||
name: decoded.sub,
|
||||
lockedOut: decoded.lockedOut,
|
||||
perms: decoded.scopes,
|
||||
access_token: token,
|
||||
exp: decoded.exp
|
||||
});
|
||||
return this.http
|
||||
.post<any>(loginUrl, formData)
|
||||
.pipe(map((u) => u.access_token))
|
||||
.pipe(map((u) => AuthService.parseJwt(u)))
|
||||
.pipe(
|
||||
map((user) => {
|
||||
// store user details and jwt token in local storage to keep user logged in between page refreshes
|
||||
localStorage.setItem(JWT_USER, JSON.stringify(user));
|
||||
this.currentUserSubject.next(user);
|
||||
return user;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
needsRefreshing(): boolean {
|
||||
return Date.now() > (this.user.exp - (environment.ACCESS_TOKEN_REFRESH_MINUTES * 60)) * 1000;
|
||||
return Date.now() > (this.user.exp - environment.ACCESS_TOKEN_REFRESH_MINUTES * 60) * 1000;
|
||||
}
|
||||
|
||||
logout() {
|
||||
@@ -97,14 +103,17 @@ export class AuthService {
|
||||
}
|
||||
|
||||
refreshToken() {
|
||||
return this.http.post<any>(refreshUrl, {})
|
||||
.pipe(map(u => u.access_token))
|
||||
.pipe(map(u => this.parseJwt(u)))
|
||||
.pipe(map(user => {
|
||||
// store user details and jwt token in local storage to keep user logged in between page refreshes
|
||||
localStorage.setItem(JWT_USER, JSON.stringify(user));
|
||||
this.currentUserSubject.next(user);
|
||||
return user;
|
||||
}));
|
||||
return this.http
|
||||
.post<any>(refreshUrl, {})
|
||||
.pipe(map((u) => u.access_token))
|
||||
.pipe(map((u) => AuthService.parseJwt(u)))
|
||||
.pipe(
|
||||
map((user) => {
|
||||
// store user details and jwt token in local storage to keep user logged in between page refreshes
|
||||
localStorage.setItem(JWT_USER, JSON.stringify(user));
|
||||
this.currentUserSubject.next(user);
|
||||
return user;
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,29 +7,48 @@
|
||||
<div fxLayout="row" fxLayout.lt-md="column" fxLayoutGap="20px" fxLayoutGap.lt-md="0px">
|
||||
<mat-form-field fxFlex>
|
||||
<mat-label>Username</mat-label>
|
||||
<input matInput #nameElement placeholder="Username" formControlName="username">
|
||||
<input matInput #nameElement placeholder="Username" formControlName="username" />
|
||||
</mat-form-field>
|
||||
</div>
|
||||
<div fxLayout="row" fxLayout.lt-md="column" fxLayoutGap="20px" fxLayoutGap.lt-md="0px">
|
||||
<mat-form-field fxFlex>
|
||||
<mat-label>Password</mat-label>
|
||||
<input matInput placeholder="Password" formControlName="password" [type]="hide ? 'password' : 'text'"
|
||||
(keyup.enter)="login()">
|
||||
<mat-icon matSuffix (click)="hide = !hide">{{hide ? 'visibility' : 'visibility_off'}}</mat-icon>
|
||||
<input
|
||||
matInput
|
||||
placeholder="Password"
|
||||
formControlName="password"
|
||||
[type]="hide ? 'password' : 'text'"
|
||||
(keyup.enter)="login()"
|
||||
/>
|
||||
<mat-icon matSuffix (click)="hide = !hide">{{
|
||||
hide ? 'visibility' : 'visibility_off'
|
||||
}}</mat-icon>
|
||||
</mat-form-field>
|
||||
</div>
|
||||
<mat-divider></mat-divider>
|
||||
<h2 *ngIf="showOtp">Client ID: {{clientId}}</h2>
|
||||
<div fxLayout="row" fxLayout.lt-md="column" fxLayoutGap="20px" fxLayoutGap.lt-md="0px" *ngIf="showOtp">
|
||||
<h2 *ngIf="showOtp">Client ID: {{ clientId }}</h2>
|
||||
<div
|
||||
fxLayout="row"
|
||||
fxLayout.lt-md="column"
|
||||
fxLayoutGap="20px"
|
||||
fxLayoutGap.lt-md="0px"
|
||||
*ngIf="showOtp"
|
||||
>
|
||||
<mat-form-field fxFlex>
|
||||
<mat-label>Otp</mat-label>
|
||||
<input matInput placeholder="Otp" formControlName="otp">
|
||||
<input matInput placeholder="Otp" formControlName="otp" />
|
||||
</mat-form-field>
|
||||
</div>
|
||||
<div fxLayout="row" fxLayout.lt-md="column" fxLayoutGap="20px" fxLayoutGap.lt-md="0px" *ngIf="showOtp">
|
||||
<div
|
||||
fxLayout="row"
|
||||
fxLayout.lt-md="column"
|
||||
fxLayoutGap="20px"
|
||||
fxLayoutGap.lt-md="0px"
|
||||
*ngIf="showOtp"
|
||||
>
|
||||
<mat-form-field fxFlex>
|
||||
<mat-label>Client Name</mat-label>
|
||||
<input matInput placeholder="Client Name" formControlName="clientName">
|
||||
<input matInput placeholder="Client Name" formControlName="clientName" />
|
||||
</mat-form-field>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
|
||||
import { AuthService } from '../auth.service';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { ToasterService } from '../../core/toaster.service';
|
||||
import { FormBuilder, FormGroup } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
|
||||
import { ToasterService } from '../../core/toaster.service';
|
||||
import { CookieService } from '../../shared/cookie.service';
|
||||
import { AuthService } from '../auth.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-login',
|
||||
templateUrl: './login.component.html',
|
||||
styleUrls: ['./login.component.css']
|
||||
styleUrls: ['./login.component.css'],
|
||||
})
|
||||
export class LoginComponent implements OnInit, AfterViewInit {
|
||||
@ViewChild('nameElement', { static: true }) nameElement: ElementRef;
|
||||
@@ -18,12 +19,13 @@ export class LoginComponent implements OnInit, AfterViewInit {
|
||||
clientId: string;
|
||||
private returnUrl: string;
|
||||
|
||||
constructor(private route: ActivatedRoute,
|
||||
private auth: AuthService,
|
||||
private router: Router,
|
||||
private toaster: ToasterService,
|
||||
private cs: CookieService,
|
||||
private fb: FormBuilder
|
||||
constructor(
|
||||
private route: ActivatedRoute,
|
||||
private auth: AuthService,
|
||||
private router: Router,
|
||||
private toaster: ToasterService,
|
||||
private cs: CookieService,
|
||||
private fb: FormBuilder,
|
||||
) {
|
||||
this.hide = true;
|
||||
this.showOtp = false;
|
||||
@@ -34,12 +36,12 @@ export class LoginComponent implements OnInit, AfterViewInit {
|
||||
this.form = this.fb.group({
|
||||
username: '',
|
||||
password: '',
|
||||
otp: ''
|
||||
otp: '',
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
|
||||
this.returnUrl = this.route.snapshot.queryParams.returnUrl || '/';
|
||||
}
|
||||
|
||||
ngAfterViewInit() {
|
||||
@@ -50,22 +52,23 @@ export class LoginComponent implements OnInit, AfterViewInit {
|
||||
|
||||
login(): void {
|
||||
const formModel = this.form.value;
|
||||
const username = formModel.username;
|
||||
const password = formModel.password;
|
||||
const otp = formModel.otp;
|
||||
this.auth.login(username, password, otp)
|
||||
const { username } = formModel;
|
||||
const { password } = formModel;
|
||||
const { otp } = formModel;
|
||||
this.auth
|
||||
.login(username, password, otp)
|
||||
// .pipe(first())
|
||||
.subscribe(
|
||||
data => {
|
||||
() => {
|
||||
this.router.navigate([this.returnUrl]);
|
||||
},
|
||||
(error) => {
|
||||
if (error.status === 401 && 'Client is not registered' === error.error.detail) {
|
||||
if (error.status === 401 && error.error.detail === 'Client is not registered') {
|
||||
this.showOtp = true;
|
||||
this.clientId = this.cs.getCookie('client_id');
|
||||
}
|
||||
this.toaster.show('Danger', error.error.details);
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,15 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
import { AuthService } from '../auth.service';
|
||||
import { ToasterService } from '../../core/toaster.service';
|
||||
|
||||
@Component({
|
||||
selector: 'app-logout',
|
||||
template: ''
|
||||
template: '',
|
||||
})
|
||||
export class LogoutComponent implements OnInit {
|
||||
|
||||
constructor(private auth: AuthService) {
|
||||
}
|
||||
constructor(private auth: AuthService) {}
|
||||
|
||||
ngOnInit() {
|
||||
this.auth.logout();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
import { DataSource } from '@angular/cdk/collections';
|
||||
import { Observable, of as observableOf } from 'rxjs';
|
||||
import { BeerConsumptionReportItem } from './beer-consumption-report';
|
||||
|
||||
import { BeerConsumptionReportItem } from './beer-consumption-report-item';
|
||||
|
||||
export class BeerConsumptionReportDataSource extends DataSource<BeerConsumptionReportItem> {
|
||||
|
||||
constructor(public data: BeerConsumptionReportItem[]) {
|
||||
super();
|
||||
}
|
||||
@@ -13,6 +12,5 @@ export class BeerConsumptionReportDataSource extends DataSource<BeerConsumptionR
|
||||
return observableOf(this.data);
|
||||
}
|
||||
|
||||
disconnect() {
|
||||
}
|
||||
disconnect() {}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export class BeerConsumptionReportItem {
|
||||
date: string;
|
||||
name: string;
|
||||
quantity: number;
|
||||
}
|
||||
+9
-6
@@ -1,15 +1,18 @@
|
||||
import {inject, TestBed} from '@angular/core/testing';
|
||||
import { inject, TestBed } from '@angular/core/testing';
|
||||
|
||||
import {BeerConsumptionReportResolver} from './beer-consumption-report-resolver.service';
|
||||
import { BeerConsumptionReportResolver } from './beer-consumption-report-resolver.service';
|
||||
|
||||
describe('BeerConsumptionReportResolver', () => {
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [BeerConsumptionReportResolver]
|
||||
providers: [BeerConsumptionReportResolver],
|
||||
});
|
||||
});
|
||||
|
||||
it('should be created', inject([BeerConsumptionReportResolver], (service: BeerConsumptionReportResolver) => {
|
||||
expect(service).toBeTruthy();
|
||||
}));
|
||||
it('should be created', inject(
|
||||
[BeerConsumptionReportResolver],
|
||||
(service: BeerConsumptionReportResolver) => {
|
||||
expect(service).toBeTruthy();
|
||||
},
|
||||
));
|
||||
});
|
||||
@@ -1,18 +1,17 @@
|
||||
import {Injectable} from '@angular/core';
|
||||
import {ActivatedRouteSnapshot, Resolve, RouterStateSnapshot} from '@angular/router';
|
||||
import {Observable} from 'rxjs/internal/Observable';
|
||||
import {BeerConsumptionReport} from './beer-consumption-report';
|
||||
import {BeerConsumptionReportService} from './beer-consumption-report.service';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { ActivatedRouteSnapshot, Resolve } from '@angular/router';
|
||||
import { Observable } from 'rxjs/internal/Observable';
|
||||
|
||||
import { BeerConsumptionReport } from './beer-consumption-report';
|
||||
import { BeerConsumptionReportService } from './beer-consumption-report.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class BeerConsumptionReportResolver implements Resolve<BeerConsumptionReport> {
|
||||
constructor(private ser: BeerConsumptionReportService) {}
|
||||
|
||||
constructor(private ser: BeerConsumptionReportService) {
|
||||
}
|
||||
|
||||
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<BeerConsumptionReport> {
|
||||
resolve(route: ActivatedRouteSnapshot): Observable<BeerConsumptionReport> {
|
||||
const startDate = route.queryParamMap.get('startDate') || null;
|
||||
const finishDate = route.queryParamMap.get('finishDate') || null;
|
||||
return this.ser.get(startDate, finishDate);
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import {BeerConsumptionReportRoutingModule} from './beer-consumption-report-routing.module';
|
||||
import { BeerConsumptionReportRoutingModule } from './beer-consumption-report-routing.module';
|
||||
|
||||
describe('BeerConsumptionReportRoutingModule', () => {
|
||||
let pbeerConsumptionReportRoutingModule: BeerConsumptionReportRoutingModule;
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { NgModule } from '@angular/core';
|
||||
import { RouterModule, Routes } from '@angular/router';
|
||||
import { BeerConsumptionReportResolver } from './beer-consumption-report-resolver.service';
|
||||
|
||||
import { AuthGuard } from '../auth/auth-guard.service';
|
||||
|
||||
import { BeerConsumptionReportResolver } from './beer-consumption-report-resolver.service';
|
||||
import { BeerConsumptionReportComponent } from './beer-consumption-report.component';
|
||||
|
||||
const beerConsumptionReportRoutes: Routes = [
|
||||
@@ -11,27 +13,18 @@ const beerConsumptionReportRoutes: Routes = [
|
||||
component: BeerConsumptionReportComponent,
|
||||
canActivate: [AuthGuard],
|
||||
data: {
|
||||
permission: 'Beer Consumption Report'
|
||||
permission: 'Beer Consumption Report',
|
||||
},
|
||||
resolve: {
|
||||
info: BeerConsumptionReportResolver
|
||||
info: BeerConsumptionReportResolver,
|
||||
},
|
||||
runGuardsAndResolvers: 'always'
|
||||
}
|
||||
runGuardsAndResolvers: 'always',
|
||||
},
|
||||
];
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
CommonModule,
|
||||
RouterModule.forChild(beerConsumptionReportRoutes)
|
||||
|
||||
],
|
||||
exports: [
|
||||
RouterModule
|
||||
],
|
||||
providers: [
|
||||
BeerConsumptionReportResolver
|
||||
]
|
||||
imports: [CommonModule, RouterModule.forChild(beerConsumptionReportRoutes)],
|
||||
exports: [RouterModule],
|
||||
providers: [BeerConsumptionReportResolver],
|
||||
})
|
||||
export class BeerConsumptionReportRoutingModule {
|
||||
}
|
||||
export class BeerConsumptionReportRoutingModule {}
|
||||
@@ -7,17 +7,34 @@
|
||||
</mat-card-title-group>
|
||||
<mat-card-content>
|
||||
<form [formGroup]="form" fxLayout="column">
|
||||
<div fxLayout="row" fxLayout.lt-md="column" fxLayoutGap="20px" fxLayoutGap.lt-md="0px"
|
||||
fxLayoutAlign="space-around start">
|
||||
<div
|
||||
fxLayout="row"
|
||||
fxLayout.lt-md="column"
|
||||
fxLayoutGap="20px"
|
||||
fxLayoutGap.lt-md="0px"
|
||||
fxLayoutAlign="space-around start"
|
||||
>
|
||||
<mat-form-field fxFlex="40">
|
||||
<input matInput [matDatepicker]="startDate" (focus)="startDate.open()" placeholder="Start Date"
|
||||
formControlName="startDate" autocomplete="off">
|
||||
<input
|
||||
matInput
|
||||
[matDatepicker]="startDate"
|
||||
(focus)="startDate.open()"
|
||||
placeholder="Start Date"
|
||||
formControlName="startDate"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<mat-datepicker-toggle matSuffix [for]="startDate"></mat-datepicker-toggle>
|
||||
<mat-datepicker #startDate></mat-datepicker>
|
||||
</mat-form-field>
|
||||
<mat-form-field fxFlex="40">
|
||||
<input matInput [matDatepicker]="finishDate" (focus)="finishDate.open()" placeholder="Finish Date"
|
||||
formControlName="finishDate" autocomplete="off">
|
||||
<input
|
||||
matInput
|
||||
[matDatepicker]="finishDate"
|
||||
(focus)="finishDate.open()"
|
||||
placeholder="Finish Date"
|
||||
formControlName="finishDate"
|
||||
autocomplete="off"
|
||||
/>
|
||||
<mat-datepicker-toggle matSuffix [for]="finishDate"></mat-datepicker-toggle>
|
||||
<mat-datepicker #finishDate></mat-datepicker>
|
||||
</mat-form-field>
|
||||
@@ -25,33 +42,32 @@
|
||||
</div>
|
||||
</form>
|
||||
<mat-table #table [dataSource]="dataSource" aria-label="Elements">
|
||||
|
||||
<!-- Date Column -->
|
||||
<ng-container matColumnDef="date">
|
||||
<mat-header-cell *matHeaderCellDef>Time</mat-header-cell>
|
||||
<mat-cell *matCellDef="let row">{{row.date}}</mat-cell>
|
||||
<mat-cell *matCellDef="let row">{{ row.date }}</mat-cell>
|
||||
</ng-container>
|
||||
|
||||
<!-- Name Column -->
|
||||
<ng-container *ngFor="let col of (info.headers)" matColumnDef="{{col}}">
|
||||
<mat-header-cell *matHeaderCellDef class="right">{{col}}</mat-header-cell>
|
||||
<mat-cell *matCellDef="let row" class="right">{{row[col]}}</mat-cell>
|
||||
<ng-container *ngFor="let col of info.headers" matColumnDef="{{ col }}">
|
||||
<mat-header-cell *matHeaderCellDef class="right">{{ col }}</mat-header-cell>
|
||||
<mat-cell *matCellDef="let row" class="right">{{ row[col] }}</mat-cell>
|
||||
</ng-container>
|
||||
|
||||
<!-- <!– Name Column –>-->
|
||||
<!-- <ng-container matColumnDef="name">-->
|
||||
<!-- <mat-header-cell *matHeaderCellDef class="right">Name</mat-header-cell>-->
|
||||
<!-- <mat-cell *matCellDef="let row" class="right">{{row.name}}</mat-cell>-->
|
||||
<!-- </ng-container>-->
|
||||
<!-- <!– Name Column –>-->
|
||||
<!-- <ng-container matColumnDef="name">-->
|
||||
<!-- <mat-header-cell *matHeaderCellDef class="right">Name</mat-header-cell>-->
|
||||
<!-- <mat-cell *matCellDef="let row" class="right">{{row.name}}</mat-cell>-->
|
||||
<!-- </ng-container>-->
|
||||
|
||||
<!-- <!– Quantity Column –>-->
|
||||
<!-- <ng-container matColumnDef="quantity">-->
|
||||
<!-- <mat-header-cell *matHeaderCellDef class="right">Quantity</mat-header-cell>-->
|
||||
<!-- <mat-cell *matCellDef="let row" class="right">{{row.quantity | number:'1.2-2'}}</mat-cell>-->
|
||||
<!-- </ng-container>-->
|
||||
<!-- <!– Quantity Column –>-->
|
||||
<!-- <ng-container matColumnDef="quantity">-->
|
||||
<!-- <mat-header-cell *matHeaderCellDef class="right">Quantity</mat-header-cell>-->
|
||||
<!-- <mat-cell *matCellDef="let row" class="right">{{row.quantity | number:'1.2-2'}}</mat-cell>-->
|
||||
<!-- </ng-container>-->
|
||||
|
||||
<mat-header-row *matHeaderRowDef="(displayedColumns)"></mat-header-row>
|
||||
<mat-row *matRowDef="let row; columns: (displayedColumns);"></mat-row>
|
||||
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
|
||||
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
|
||||
</mat-table>
|
||||
</mat-card-content>
|
||||
</mat-card>
|
||||
@@ -1,6 +1,6 @@
|
||||
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
|
||||
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import {BeerConsumptionReportComponent} from './beer-consumption-report.component';
|
||||
import { BeerConsumptionReportComponent } from './beer-consumption-report.component';
|
||||
|
||||
describe('BeerConsumptionReportComponent', () => {
|
||||
let component: BeerConsumptionReportComponent;
|
||||
@@ -8,9 +8,8 @@ describe('BeerConsumptionReportComponent', () => {
|
||||
|
||||
beforeEach(async(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [BeerConsumptionReportComponent]
|
||||
})
|
||||
.compileComponents();
|
||||
declarations: [BeerConsumptionReportComponent],
|
||||
}).compileComponents();
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -2,14 +2,16 @@ import { Component, OnInit } from '@angular/core';
|
||||
import { FormBuilder, FormGroup } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import * as moment from 'moment';
|
||||
import { BeerConsumptionReportDataSource } from './beer-consumption-report-datasource';
|
||||
import { BeerConsumptionReport } from './beer-consumption-report';
|
||||
|
||||
import { ToCsvService } from '../shared/to-csv.service';
|
||||
|
||||
import { BeerConsumptionReport } from './beer-consumption-report';
|
||||
import { BeerConsumptionReportDataSource } from './beer-consumption-report-datasource';
|
||||
|
||||
@Component({
|
||||
selector: 'app-beer-consumption-report',
|
||||
templateUrl: './beer-consumption-report.component.html',
|
||||
styleUrls: ['./beer-consumption-report.component.css']
|
||||
styleUrls: ['./beer-consumption-report.component.css'],
|
||||
})
|
||||
export class BeerConsumptionReportComponent implements OnInit {
|
||||
dataSource: BeerConsumptionReportDataSource;
|
||||
@@ -19,28 +21,25 @@ export class BeerConsumptionReportComponent implements OnInit {
|
||||
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
|
||||
displayedColumns: string[] = ['date'];
|
||||
|
||||
|
||||
constructor(
|
||||
private route: ActivatedRoute,
|
||||
private router: Router,
|
||||
private fb: FormBuilder,
|
||||
private toCsv: ToCsvService
|
||||
private toCsv: ToCsvService,
|
||||
) {
|
||||
this.createForm();
|
||||
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.route.data
|
||||
.subscribe((data: { info: BeerConsumptionReport }) => {
|
||||
this.info = data.info;
|
||||
this.displayedColumns = ['date'].concat(this.info.headers);
|
||||
this.form.setValue({
|
||||
startDate: moment(this.info.startDate, 'DD-MMM-YYYY').toDate(),
|
||||
finishDate: moment(this.info.finishDate, 'DD-MMM-YYYY').toDate()
|
||||
});
|
||||
this.dataSource = new BeerConsumptionReportDataSource(this.info.data);
|
||||
this.route.data.subscribe((data: { info: BeerConsumptionReport }) => {
|
||||
this.info = data.info;
|
||||
this.displayedColumns = ['date'].concat(this.info.headers);
|
||||
this.form.setValue({
|
||||
startDate: moment(this.info.startDate, 'DD-MMM-YYYY').toDate(),
|
||||
finishDate: moment(this.info.finishDate, 'DD-MMM-YYYY').toDate(),
|
||||
});
|
||||
this.dataSource = new BeerConsumptionReportDataSource(this.info.data);
|
||||
});
|
||||
}
|
||||
|
||||
show() {
|
||||
@@ -48,15 +47,15 @@ export class BeerConsumptionReportComponent implements OnInit {
|
||||
this.router.navigate(['beer-consumption-report'], {
|
||||
queryParams: {
|
||||
startDate: info.startDate,
|
||||
finishDate: info.finishDate
|
||||
}
|
||||
finishDate: info.finishDate,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
createForm() {
|
||||
this.form = this.fb.group({
|
||||
startDate: '',
|
||||
finishDate: ''
|
||||
finishDate: '',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -65,18 +64,23 @@ export class BeerConsumptionReportComponent implements OnInit {
|
||||
|
||||
return {
|
||||
startDate: moment(formModel.startDate).format('DD-MMM-YYYY'),
|
||||
finishDate: moment(formModel.finishDate).format('DD-MMM-YYYY')
|
||||
finishDate: moment(formModel.finishDate).format('DD-MMM-YYYY'),
|
||||
};
|
||||
}
|
||||
|
||||
exportCsv() {
|
||||
const headers = this.info.headers.reduce((a, c) => {
|
||||
a[c] = c;
|
||||
return a
|
||||
}, {
|
||||
Date: 'date'
|
||||
const headers = this.info.headers.reduce(
|
||||
(a, c) => {
|
||||
a[c] = c;
|
||||
return a;
|
||||
},
|
||||
{
|
||||
Date: 'date',
|
||||
},
|
||||
);
|
||||
const csvData = new Blob([this.toCsv.toCsv(headers, this.info.data)], {
|
||||
type: 'text/csv;charset=utf-8;',
|
||||
});
|
||||
const csvData = new Blob([this.toCsv.toCsv(headers, this.info.data)], {type: 'text/csv;charset=utf-8;'});
|
||||
const link = document.createElement('a');
|
||||
link.href = window.URL.createObjectURL(csvData);
|
||||
link.setAttribute('download', 'beer-consumption-report.csv');
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {BeerConsumptionReportModule} from './beer-consumption-report.module';
|
||||
import { BeerConsumptionReportModule } from './beer-consumption-report.module';
|
||||
|
||||
describe('BeerConsumptionReportModule', () => {
|
||||
let pbeerConsumptionReportModule: BeerConsumptionReportModule;
|
||||
|
||||
@@ -1,22 +1,29 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
import { A11yModule } from '@angular/cdk/a11y';
|
||||
import { CdkTableModule } from '@angular/cdk/table';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { NgModule } from '@angular/core';
|
||||
import { FlexLayoutModule } from '@angular/flex-layout';
|
||||
import { ReactiveFormsModule } from '@angular/forms';
|
||||
import { MomentDateAdapter } from '@angular/material-moment-adapter';
|
||||
import { MatAutocompleteModule } from '@angular/material/autocomplete';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
import { MatCardModule } from '@angular/material/card';
|
||||
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE, MatNativeDateModule } from '@angular/material/core';
|
||||
import {
|
||||
DateAdapter,
|
||||
MAT_DATE_FORMATS,
|
||||
MAT_DATE_LOCALE,
|
||||
MatNativeDateModule,
|
||||
} from '@angular/material/core';
|
||||
import { MatDatepickerModule } from '@angular/material/datepicker';
|
||||
import { MatFormFieldModule } from '@angular/material/form-field';
|
||||
import { MatIconModule } from '@angular/material/icon';
|
||||
import { MatInputModule } from '@angular/material/input';
|
||||
import { MatTableModule } from '@angular/material/table';
|
||||
import { SharedModule} from '../shared/shared.module';
|
||||
import { ReactiveFormsModule } from '@angular/forms';
|
||||
import { CdkTableModule } from '@angular/cdk/table';
|
||||
|
||||
import { SharedModule } from '../shared/shared.module';
|
||||
|
||||
import { BeerConsumptionReportRoutingModule } from './beer-consumption-report-routing.module';
|
||||
import { BeerConsumptionReportComponent } from './beer-consumption-report.component';
|
||||
import { MomentDateAdapter } from '@angular/material-moment-adapter';
|
||||
import { A11yModule } from '@angular/cdk/a11y';
|
||||
import { FlexLayoutModule } from '@angular/flex-layout';
|
||||
|
||||
export const MY_FORMATS = {
|
||||
parse: {
|
||||
@@ -47,15 +54,12 @@ export const MY_FORMATS = {
|
||||
MatTableModule,
|
||||
ReactiveFormsModule,
|
||||
SharedModule,
|
||||
BeerConsumptionReportRoutingModule
|
||||
],
|
||||
declarations: [
|
||||
BeerConsumptionReportComponent
|
||||
BeerConsumptionReportRoutingModule,
|
||||
],
|
||||
declarations: [BeerConsumptionReportComponent],
|
||||
providers: [
|
||||
{provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
|
||||
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
|
||||
]
|
||||
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
|
||||
{ provide: MAT_DATE_FORMATS, useValue: MY_FORMATS },
|
||||
],
|
||||
})
|
||||
export class BeerConsumptionReportModule {
|
||||
}
|
||||
export class BeerConsumptionReportModule {}
|
||||
@@ -1,15 +1,18 @@
|
||||
import {inject, TestBed} from '@angular/core/testing';
|
||||
import { inject, TestBed } from '@angular/core/testing';
|
||||
|
||||
import {BeerConsumptionReportService} from './beer-consumption-report.service';
|
||||
import { BeerConsumptionReportService } from './beer-consumption-report.service';
|
||||
|
||||
describe('BeerConsumptionReportService', () => {
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [BeerConsumptionReportService]
|
||||
providers: [BeerConsumptionReportService],
|
||||
});
|
||||
});
|
||||
|
||||
it('should be created', inject([BeerConsumptionReportService], (service: BeerConsumptionReportService) => {
|
||||
expect(service).toBeTruthy();
|
||||
}));
|
||||
it('should be created', inject(
|
||||
[BeerConsumptionReportService],
|
||||
(service: BeerConsumptionReportService) => {
|
||||
expect(service).toBeTruthy();
|
||||
},
|
||||
));
|
||||
});
|
||||
@@ -1,36 +1,33 @@
|
||||
import { HttpClient, HttpParams } from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { catchError } from 'rxjs/operators';
|
||||
import { Observable } from 'rxjs/internal/Observable';
|
||||
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
|
||||
import { BeerConsumptionReport } from './beer-consumption-report';
|
||||
import { catchError } from 'rxjs/operators';
|
||||
|
||||
import { ErrorLoggerService } from '../core/error-logger.service';
|
||||
|
||||
const httpOptions = {
|
||||
headers: new HttpHeaders({'Content-Type': 'application/json'})
|
||||
};
|
||||
import { BeerConsumptionReport } from './beer-consumption-report';
|
||||
|
||||
const url = '/api/beer-consumption-report';
|
||||
const serviceName = 'BeerConsumptionReportService';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class BeerConsumptionReportService {
|
||||
|
||||
constructor(private http: HttpClient, private log: ErrorLoggerService) {
|
||||
}
|
||||
constructor(private http: HttpClient, private log: ErrorLoggerService) {}
|
||||
|
||||
get(startDate: string, finishDate): Observable<BeerConsumptionReport> {
|
||||
const options = {params: new HttpParams()};
|
||||
const options = { params: new HttpParams() };
|
||||
if (startDate !== null) {
|
||||
options.params = options.params.set('s', startDate);
|
||||
}
|
||||
if (finishDate !== null) {
|
||||
options.params = options.params.set('f', finishDate);
|
||||
}
|
||||
return <Observable<BeerConsumptionReport>>this.http.get<BeerConsumptionReport>(url, options)
|
||||
.pipe(
|
||||
catchError(this.log.handleError(serviceName, 'get'))
|
||||
);
|
||||
return <Observable<BeerConsumptionReport>>(
|
||||
this.http
|
||||
.get<BeerConsumptionReport>(url, options)
|
||||
.pipe(catchError(this.log.handleError(serviceName, 'get')))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,4 @@
|
||||
export class BeerConsumptionReportItem {
|
||||
date: string;
|
||||
name: string;
|
||||
quantity: number;
|
||||
}
|
||||
import { BeerConsumptionReportItem } from './beer-consumption-report-item';
|
||||
|
||||
export class BeerConsumptionReport {
|
||||
startDate: string;
|
||||
|
||||
Loaded 100 of 505 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user