order paying works

This commit is contained in:
Tiago vasconcelos 2022-08-19 11:19:45 +01:00
parent e76c23b096
commit a5c6b1135c
5 changed files with 123 additions and 78 deletions

View file

@ -275,6 +275,21 @@ async def get_diagonalley_order(order_id: str) -> Optional[Orders]:
) )
return Orders(**row) if row else None return Orders(**row) if row else None
async def get_diagonalley_order_invoiceid(invoice_id: str) -> Optional[Orders]:
row = await db.fetchone(
"SELECT * FROM diagonalley.orders WHERE invoiceid = ?", (invoice_id,)
)
return Orders(**row) if row else None
async def set_diagonalley_order_paid(payment_hash: str) -> Orders:
await db.execute(
"""
UPDATE diagonalley.orders
SET paid = true
WHERE invoiceid = ?
""",
(payment_hash,),
)
async def get_diagonalley_orders(wallet_ids: Union[str, List[str]]) -> List[Orders]: async def get_diagonalley_orders(wallet_ids: Union[str, List[str]]) -> List[Orders]:
if isinstance(wallet_ids, str): if isinstance(wallet_ids, str):

View file

@ -1,8 +1,12 @@
import asyncio import asyncio
from loguru import logger
from lnbits.core.models import Payment from lnbits.core.models import Payment
from lnbits.tasks import register_invoice_listener from lnbits.tasks import register_invoice_listener
from .crud import get_diagonalley_order_invoiceid, set_diagonalley_order_paid
async def wait_for_paid_invoices(): async def wait_for_paid_invoices():
invoice_queue = asyncio.Queue() invoice_queue = asyncio.Queue()
@ -14,6 +18,21 @@ async def wait_for_paid_invoices():
async def on_invoice_paid(payment: Payment) -> None: async def on_invoice_paid(payment: Payment) -> None:
if payment.extra.get("tag") != "diagonalley":
return
order = await get_diagonalley_order_invoiceid(payment.payment_hash)
if not order:
logger.error("this should never happen", payment)
return
# set order as paid
await set_diagonalley_order_paid(payment.payment_hash)
# deduct items sold from stock
# TODO
""" """
if "lnticket" != payment.extra.get("tag"): if "lnticket" != payment.extra.get("tag"):
# not a lnticket invoice # not a lnticket invoice

View file

@ -220,25 +220,41 @@
<q-dialog <q-dialog
v-model="qrCodeDialog.show" v-model="qrCodeDialog.show"
position="top" position="top"
@hide="qrCodeDialog.show = false" @hide="closeQrCodeDialog"
> >
<q-card class="q-pa-lg q-pt-xl lnbits__dialog-card text-center"> <q-card
<a :href="'lightning:' + qrCodeDialog.data.payment_request"> v-if="!qrCodeDialog.data.payment_request"
<q-responsive :ratio="1" class="q-mx-xs"> class="q-pa-lg q-pt-xl lnbits__dialog-card"
<qrcode >
:value="qrCodeDialog.data.payment_request" </q-card>
:options="{width: 400}" <q-card v-else class="q-pa-lg q-pt-xl lnbits__dialog-card">
class="rounded-borders" <div class="text-center q-mb-lg">
></qrcode> <a :href="'lightning:' + qrCodeDialog.data.payment_request">
</q-responsive> <q-responsive :ratio="1" class="q-mx-xl">
</a> <qrcode
<br /> :value="qrCodeDialog.data.payment_request"
<q-btn :options="{width: 340}"
outline class="rounded-borders"
color="grey" ></qrcode>
@click="copyText('lightning:' + qrCodeDialog.data.payment_request, 'Invoice copied to clipboard!')" </q-responsive>
>Copy Invoice</q-btn </a>
> </div>
<div class="row q-mt-lg">
<q-btn
outline
color="grey"
@click="copyText(qrCodeDialog.data.payment_request)"
>Copy invoice</q-btn
>
<q-btn
@click="closeQrCodeDialog"
v-close-popup
flat
color="grey"
class="q-ml-auto"
>Close</q-btn
>
</div>
</q-card> </q-card>
</q-dialog> </q-dialog>
</div> </div>
@ -252,9 +268,6 @@
return { return {
stall: null, stall: null,
products: [], products: [],
wallet: {
inkey: null
},
searchText: null, searchText: null,
cart: { cart: {
total: 0, total: 0,
@ -271,8 +284,7 @@
payment_request: null payment_request: null
}, },
show: false show: false
}, }
cancelListener: () => {}
} }
}, },
computed: { computed: {
@ -297,6 +309,10 @@
} }
}, },
methods: { methods: {
closeQrCodeDialog() {
this.qrCodeDialog.dismissMsg()
this.qrCodeDialog.show = false
},
resetCart() { resetCart() {
this.cart = { this.cart = {
total: 0, total: 0,
@ -341,16 +357,10 @@
return {product_id: p[0], quantity: p[1].quantity} return {product_id: p[0], quantity: p[1].quantity}
}) })
} }
LNbits.api LNbits.api
.request( .request('POST', '/diagonalley/api/v1/orders', null, data)
'POST',
'/diagonalley/api/v1/orders',
this.wallet.inkey,
data
)
.then(res => { .then(res => {
this.checkoutDialog = {show: false} this.checkoutDialog = {show: false, data: {}}
return res.data return res.data
}) })
@ -358,48 +368,46 @@
this.qrCodeDialog.data = data this.qrCodeDialog.data = data
this.qrCodeDialog.show = true this.qrCodeDialog.show = true
qrCodeDialog.dismissMsg = this.$q.notify({ this.qrCodeDialog.dismissMsg = this.$q.notify({
timeout: 0, timeout: 0,
message: 'Waiting for payment...' message: 'Waiting for payment...'
}) })
return data
})
.then(data => {
this.qrCodeDialog.paymentChecker = setInterval(() => {
LNbits.api
.request(
'GET',
`/diagonalley/api/v1/orders/payments/${this.qrCodeDialog.data.payment_hash}`
)
.then(res => {
if (res.data.paid) {
this.$q.notify({
type: 'positive',
message: 'Sats received, thanks!',
icon: 'thumb_up'
})
clearInterval(this.qrCodeDialog.paymentChecker)
this.resetCart()
this.closeQrCodeDialog()
}
})
.catch(error => {
console.error(error)
LNbits.utils.notifyApiError(error)
})
}, 3000)
})
.catch(error => {
console.error(error)
LNbits.utils.notifyApiError(error)
}) })
.catch(error => LNbits.utils.notifyApiError(error))
return
},
startPaymentNotifier() {
this.cancelListener()
this.cancelListener = LNbits.events.onInvoicePaid(
this.wallet,
payment => {
this.qrCodeDialog = {
show: false,
data: {
payment_request: null
}
}
this.checkoutDialog = {data: {}}
this.resetCart()
this.$q.notify({
type: 'positive',
message: 'Sent, thank you!',
icon: 'thumb_up'
})
}
)
} }
}, },
created() { created() {
this.stall = JSON.parse('{{ stall | tojson }}') this.stall = JSON.parse('{{ stall | tojson }}')
this.products = JSON.parse('{{ products | tojson }}') this.products = JSON.parse('{{ products | tojson }}')
this.wallet.inkey = '{{ inkey }}'
this.startPaymentNotifier()
//let stall_ids = new Set()
//this.products.map(p => stall_ids.add(p.stall))
console.log(this.stall, this.products) console.log(this.stall, this.products)
} }
@ -410,13 +418,3 @@
} }
</style> </style>
{% endblock %} {% endblock %}
<!-- <pre id="json"></pre>
<script>
document.getElementById('json').innerHTML = JSON.stringify(
'{{ stall }}',
null,
2
)
</script> -->

View file

@ -33,15 +33,12 @@ async def index(request: Request, user: User = Depends(check_user_exists)):
async def display(request: Request, stall_id): async def display(request: Request, stall_id):
stall = await get_diagonalley_stall(stall_id) stall = await get_diagonalley_stall(stall_id)
products = await get_diagonalley_products(stall_id) products = await get_diagonalley_products(stall_id)
wallet = await get_wallet(stall.wallet)
zones = [] zones = []
for id in stall.shippingzones.split(","): for id in stall.shippingzones.split(","):
z = await get_diagonalley_zone(id) z = await get_diagonalley_zone(id)
z = z.dict() z = z.dict()
zones.append({"label": z["countries"], "cost": z["cost"], "value": z["id"]}) zones.append({"label": z["countries"], "cost": z["cost"], "value": z["id"]})
logger.debug(f"ZONES {zones}")
if not stall: if not stall:
raise HTTPException( raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Stall does not exist." status_code=HTTPStatus.NOT_FOUND, detail="Stall does not exist."
@ -57,7 +54,6 @@ async def display(request: Request, stall_id):
"request": request, "request": request,
"stall": stall, "stall": stall,
"products": [product.dict() for product in products], "products": [product.dict() for product in products],
"inkey": wallet.inkey,
}, },
) )

View file

@ -10,6 +10,7 @@ from starlette.exceptions import HTTPException
from lnbits.core.crud import get_user from lnbits.core.crud import get_user
from lnbits.core.services import create_invoice from lnbits.core.services import create_invoice
from lnbits.core.views.api import api_payment
from lnbits.decorators import ( from lnbits.decorators import (
WalletTypeInfo, WalletTypeInfo,
get_key_type, get_key_type,
@ -33,6 +34,7 @@ from .crud import (
get_diagonalley_markets, get_diagonalley_markets,
get_diagonalley_order, get_diagonalley_order,
get_diagonalley_order_details, get_diagonalley_order_details,
get_diagonalley_order_invoiceid,
get_diagonalley_orders, get_diagonalley_orders,
get_diagonalley_product, get_diagonalley_product,
get_diagonalley_products, get_diagonalley_products,
@ -270,6 +272,21 @@ async def api_diagonalley_order_create(data: createOrder):
# return order.dict() # return order.dict()
@diagonalley_ext.get("/api/v1/orders/payments/{payment_hash}")
async def api_diagonalley_check_payment(payment_hash: str):
order = await get_diagonalley_order_invoiceid(payment_hash)
if not order:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Order does not exist."
)
try:
status = await api_payment(payment_hash)
except Exception as exc:
logger.error(exc)
return {"paid": False}
return status
@diagonalley_ext.delete("/api/v1/orders/{order_id}") @diagonalley_ext.delete("/api/v1/orders/{order_id}")
async def api_diagonalley_order_delete( async def api_diagonalley_order_delete(
order_id: str, wallet: WalletTypeInfo = Depends(get_key_type) order_id: str, wallet: WalletTypeInfo = Depends(get_key_type)