Skip to content
31 changes: 18 additions & 13 deletions app/modules/amap/cruds_amap.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import logging
from collections.abc import Sequence
from datetime import date
from datetime import datetime

from sqlalchemy import delete, select, update
from sqlalchemy.ext.asyncio import AsyncSession
Expand Down Expand Up @@ -118,16 +118,6 @@ async def get_delivery_by_id(
return result.scalars().first()


async def is_there_a_delivery_on(db: AsyncSession, delivery_date: date) -> bool:
result = await db.execute(
select(models_amap.Delivery).where(
models_amap.Delivery.delivery_date == delivery_date,
models_amap.Delivery.status != DeliveryStatusType.archived,
),
)
return result.scalars().all() != []


async def create_delivery(
delivery: schemas_amap.DeliveryComplete,
db: AsyncSession,
Expand Down Expand Up @@ -248,6 +238,7 @@ async def get_products_of_order(
async def add_order_to_delivery(
db: AsyncSession,
order: schemas_amap.OrderComplete,
delivery: models_amap.Delivery,
):
db.add(
models_amap.Order(
Expand Down Expand Up @@ -358,7 +349,7 @@ async def add_cash(db: AsyncSession, user_id: str, amount: float):
await db.execute(
update(models_amap.Cash)
.where(models_amap.Cash.user_id == user_id)
.values(user_id=balance.user_id, balance=balance.balance + amount),
.values(balance=balance.balance + amount),
)
await db.flush()

Expand All @@ -372,7 +363,21 @@ async def remove_cash(db: AsyncSession, user_id: str, amount: float):
await db.execute(
update(models_amap.Cash)
.where(models_amap.Cash.user_id == user_id)
.values(user_id=balance.user_id, balance=balance.balance - amount),
.values(balance=balance.balance - amount),
)
await db.flush()


async def update_last_ordering_date(db: AsyncSession, user_id: str, date: datetime):
result = await db.execute(
select(models_amap.Cash).where(models_amap.Cash.user_id == user_id),
)
balance = result.scalars().first()
if balance is not None:
await db.execute(
update(models_amap.Cash)
.where(models_amap.Cash.user_id == user_id)
.values(last_order_date=date),
)
await db.flush()

Expand Down
76 changes: 55 additions & 21 deletions app/modules/amap/endpoints_amap.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,14 +196,6 @@ async def create_delivery(
status=DeliveryStatusType.creation,
**delivery.model_dump(),
)
if await cruds_amap.is_there_a_delivery_on(
db=db,
delivery_date=db_delivery.delivery_date,
):
raise HTTPException(
status_code=400,
detail="There is already a delivery planned that day.",
)

return await cruds_amap.create_delivery(delivery=db_delivery, db=db)

Expand Down Expand Up @@ -359,7 +351,14 @@ async def get_orders_from_delivery(
schemas_amap.ProductQuantity(**product.__dict__)
for product in order_content
]
res.append(schemas_amap.OrderReturn(productsdetail=products, **order.__dict__))
res.append(
schemas_amap.OrderReturn(
productsdetail=products,
delivery_date=delivery.delivery_date,
delivery_name=delivery.name,
**order.__dict__,
),
)
return res


Expand All @@ -384,7 +383,12 @@ async def get_order_by_id(
raise HTTPException(status_code=404, detail="Delivery not found")

products = await cruds_amap.get_products_of_order(db=db, order_id=order_id)
return schemas_amap.OrderReturn(productsdetail=products, **order.__dict__)
return schemas_amap.OrderReturn(
productsdetail=products,
delivery_name=order.delivery.name,
delivery_date=order.delivery.delivery_date,
**order.__dict__,
)


@module.router.post(
Expand Down Expand Up @@ -443,7 +447,6 @@ async def add_order_to_delievery(
order_id=order_id,
amount=amount,
ordering_date=ordering_date,
delivery_date=delivery.delivery_date,
**order.model_dump(),
)
balance: models_amap.Cash | None = await cruds_amap.get_cash_by_id(
Expand All @@ -453,12 +456,10 @@ async def add_order_to_delievery(

# If the balance does not exist, we create a new one with a balance of 0
if not balance:
new_cash_db = schemas_amap.CashDB(
balance = models_amap.Cash(
balance=0,
user_id=order.user_id,
)
balance = models_amap.Cash(
**new_cash_db.model_dump(),
last_order_date=ordering_date,
)
await cruds_amap.create_cash_of_user(
cash=balance,
Expand All @@ -469,7 +470,6 @@ async def add_order_to_delievery(
raise HTTPException(status_code=400, detail="You can't order nothing")

redis_key = "amap_" + order.user_id

if not isinstance(redis_client, Redis) or locker_get(
redis_client=redis_client,
key=redis_key,
Expand All @@ -481,21 +481,36 @@ async def add_order_to_delievery(
await cruds_amap.add_order_to_delivery(
order=db_order,
db=db,
delivery=delivery,
)
await cruds_amap.remove_cash(
db=db,
user_id=order.user_id,
amount=amount,
)

await cruds_amap.update_last_ordering_date(
db=db,
user_id=order.user_id,
date=ordering_date,
)

orderret = await cruds_amap.get_order_by_id(order_id=db_order.order_id, db=db)
productsret = await cruds_amap.get_products_of_order(db=db, order_id=order_id)

hyperion_amap_logger.info(
f"Add_order_to_delivery: An order has been created for user {order.user_id} for an amount of {amount}€. ({request_id})",
)
return schemas_amap.OrderReturn(productsdetail=productsret, **orderret.__dict__)

if orderret is None:
raise HTTPException(status_code=404, detail="added order not found")

return schemas_amap.OrderReturn(
productsdetail=productsret,
delivery_name=orderret.delivery.name,
delivery_date=orderret.delivery.delivery_date,
**orderret.__dict__,
)
finally:
locker_set(redis_client=redis_client, key=redis_key, lock=False)

Expand Down Expand Up @@ -584,7 +599,6 @@ async def edit_order_from_delivery(
raise HTTPException(status_code=404, detail="No cash found")

redis_key = "amap_" + previous_order.user_id

if not isinstance(redis_client, Redis) or locker_get(
redis_client=redis_client,
key=redis_key,
Expand All @@ -607,6 +621,12 @@ async def edit_order_from_delivery(
user_id=previous_order.user_id,
amount=previous_amount,
)
date = datetime.now(UTC)
await cruds_amap.update_last_ordering_date(
db=db,
user_id=previous_order.user_id,
date=date,
)
hyperion_amap_logger.info(
f"Edit_order: Order {order_id} has been edited for user {db_order.user_id}. Amount was {previous_amount}€, is now {amount}€. ({request_id})",
)
Expand Down Expand Up @@ -835,6 +855,7 @@ async def get_cash_by_id(
balance=0,
user_id=user_id,
user=schemas_users.CoreUserSimple(**user_db.__dict__),
last_order_date=datetime.now(UTC),
)

return cash
Expand Down Expand Up @@ -870,7 +891,11 @@ async def create_cash_of_user(
detail="This user already has a cash.",
)

cash_db = models_amap.Cash(user_id=user_id, balance=cash.balance)
cash_db = models_amap.Cash(
user_id=user_id,
balance=cash.balance,
last_order_date=datetime.now(UTC),
)

await cruds_amap.create_cash_of_user(
cash=cash_db,
Expand All @@ -890,7 +915,7 @@ async def create_cash_of_user(

message = Message(
title="AMAP - Solde mis à jour",
content=f"Votre nouveau solde est de {cash} €.",
content=f"Votre nouveau solde est de {cash.balance // 100}€{cash.balance % 100}.",
action_module="amap",
)
await notification_tool.send_notification_to_user(
Expand Down Expand Up @@ -967,7 +992,16 @@ async def get_orders_of_user(
db=db,
order_id=order.order_id,
)
res.append(schemas_amap.OrderReturn(productsdetail=products, **order.__dict__))
if order is None:
raise HTTPException(status_code=404, detail="at least one order not found")
res.append(
schemas_amap.OrderReturn(
productsdetail=products,
delivery_date=order.delivery.delivery_date,
delivery_name=order.delivery.name,
**order.__dict__,
),
)
return res


Expand Down
21 changes: 12 additions & 9 deletions app/modules/amap/factory_amap.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ class AmapFactory(Factory):
@classmethod
async def create_products(cls, db: AsyncSession):
# Generates sample products
products: dict[str, tuple[float, str]] = {
"banane": (5.0, "Fruits"),
"pomme": (6.0, "Fruits"),
"poire": (4.0, "Fruits"),
"kiwi": (3.0, "Fruits"),
"orange": (2.0, "Fruits"),
"carotte": (1.0, "Légumes"),
"tomate": (2.0, "Légumes"),
products: dict[str, tuple[int, str]] = {
"banane": (500, "Fruits"),
"pomme": (600, "Fruits"),
"poire": (400, "Fruits"),
"kiwi": (300, "Fruits"),
"orange": (200, "Fruits"),
"carotte": (100, "Légumes"),
"tomate": (200, "Légumes"),
}

for product_name, product_data in products.items():
Expand All @@ -45,6 +45,7 @@ async def create_delivery(cls, db: AsyncSession):
db=db,
delivery=schemas_amap.DeliveryComplete(
id=str(uuid.uuid4()),
name="Première livraison",
status=DeliveryStatusType.orderable,
delivery_date=(datetime.now(UTC) + timedelta(days=8)).date(),
products_ids=[product.id for product in products],
Expand All @@ -55,6 +56,7 @@ async def create_delivery(cls, db: AsyncSession):
db=db,
delivery=schemas_amap.DeliveryComplete(
id=str(uuid.uuid4()),
name="Deuxième livraison",
status=DeliveryStatusType.orderable,
delivery_date=(datetime.now(UTC) + timedelta(days=1)).date(),
products_ids=[product.id for product in products],
Expand All @@ -67,7 +69,8 @@ async def create_cash_of_user(cls, db: AsyncSession):
db=db,
cash=models_amap.Cash(
user_id=CoreUsersFactory.demo_users_id[0],
balance=100,
balance=10000,
last_order_date=datetime.now(UTC),
),
)

Expand Down
23 changes: 17 additions & 6 deletions app/modules/amap/models_amap.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,25 @@ class Product(Base):
index=True,
unique=True,
)
price: Mapped[float]
price: Mapped[int]
category: Mapped[str] = mapped_column(index=True)


class Delivery(Base):
__tablename__ = "amap_delivery"

id: Mapped[str] = mapped_column(primary_key=True, index=True)
name: Mapped[str] = mapped_column(unique=False)
delivery_date: Mapped[date] = mapped_column(
unique=False,
index=True,
)
status: Mapped[DeliveryStatusType] = mapped_column(String)
orders: Mapped[list["Order"]] = relationship("Order", init=False)
orders: Mapped[list["Order"]] = relationship(
"Order",
init=False,
back_populates="delivery",
)
products: Mapped[list[Product]] = relationship(
"Product",
secondary="amap_delivery_content",
Expand All @@ -76,10 +81,15 @@ class Order(Base):
index=True,
)
order_id: Mapped[str] = mapped_column(primary_key=True, index=True)
amount: Mapped[float]
amount: Mapped[int]
collection_slot: Mapped[AmapSlotType]
ordering_date: Mapped[datetime]
delivery_date: Mapped[date]
delivery: Mapped["Delivery"] = relationship(
"Delivery",
lazy="joined",
init=False,
back_populates="orders",
)
user: Mapped[CoreUser] = relationship(
"CoreUser",
init=False,
Expand All @@ -88,7 +98,7 @@ class Order(Base):
"Product",
secondary="amap_order_content",
viewonly=True,
default_factory=list,
init=False,
)


Expand All @@ -99,7 +109,8 @@ class Cash(Base):
ForeignKey("core_user.id"),
primary_key=True,
)
balance: Mapped[float]
balance: Mapped[int]
last_order_date: Mapped[datetime]
user: Mapped[CoreUser] = relationship("CoreUser", init=False)


Expand Down
Loading