feat: create order on DM

This commit is contained in:
Vlad Stan 2023-03-06 15:03:02 +02:00
parent cec7d2ee25
commit d0471744e0
8 changed files with 246 additions and 71 deletions

View file

@ -5,6 +5,7 @@ from typing import List, Optional
from fastapi import Depends
from fastapi.exceptions import HTTPException
from loguru import logger
from lnbits.core import create_invoice
from lnbits.decorators import (
WalletTypeInfo,
@ -17,6 +18,7 @@ from lnbits.utils.exchange_rates import currencies
from . import nostrmarket_ext
from .crud import (
create_merchant,
create_order,
create_product,
create_stall,
create_zone,
@ -26,8 +28,10 @@ from .crud import (
get_merchant_for_user,
get_product,
get_products,
get_products_by_ids,
get_stall,
get_stalls,
get_wallet_for_product,
get_zone,
get_zones,
update_product,
@ -37,7 +41,9 @@ from .crud import (
from .models import (
Merchant,
Nostrable,
Order,
PartialMerchant,
PartialOrder,
PartialProduct,
PartialStall,
PartialZone,
@ -101,7 +107,7 @@ async def api_get_zones(wallet: WalletTypeInfo = Depends(get_key_type)) -> List[
@nostrmarket_ext.post("/api/v1/zone")
async def api_create_zone(
data: PartialZone, wallet: WalletTypeInfo = Depends(get_key_type)
data: PartialZone, wallet: WalletTypeInfo = Depends(require_admin_key)
):
try:
zone = await create_zone(wallet.wallet.user, data)
@ -418,6 +424,50 @@ async def api_delete_product(
)
######################################## ORDERS ########################################
@nostrmarket_ext.post("/api/v1/order")
async def api_create_order(
data: PartialOrder, wallet: WalletTypeInfo = Depends(require_admin_key)
):
try:
data.id = data.id or data.event_id
wallet_id = await get_wallet_for_product(data.items[0].product_id)
assert wallet_id, "Missing wallet for order `{data.id}`"
product_ids = [p.product_id for p in data.items]
products = await get_products_by_ids(wallet.wallet.user, product_ids)
product_prices = {}
for p in products:
product_prices[p.id] = p
amount: float = 0 # todo
for item in data.items:
amount += item.quantity * product_prices[item.product_id].price
payment_hash, payment_request = await create_invoice(
wallet_id=wallet_id,
amount=round(amount),
memo=f"Order '{data.id}' for pubkey '{data.pubkey}'",
extra={
"tag": "nostrmarket",
"order_id": data.id,
}
)
order = Order(**data.dict(), invoice_id=payment_hash, total=100)
await create_order(wallet.wallet.user, order)
except Exception as ex:
logger.warning(ex)
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail="Cannot create order",
)
######################################## OTHER ########################################