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
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]:
if isinstance(wallet_ids, str):

View file

@ -1,8 +1,12 @@
import asyncio
from loguru import logger
from lnbits.core.models import Payment
from lnbits.tasks import register_invoice_listener
from .crud import get_diagonalley_order_invoiceid, set_diagonalley_order_paid
async def wait_for_paid_invoices():
invoice_queue = asyncio.Queue()
@ -14,6 +18,21 @@ async def wait_for_paid_invoices():
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"):
# not a lnticket invoice

View file

@ -220,25 +220,41 @@
<q-dialog
v-model="qrCodeDialog.show"
position="top"
@hide="qrCodeDialog.show = false"
@hide="closeQrCodeDialog"
>
<q-card class="q-pa-lg q-pt-xl lnbits__dialog-card text-center">
<a :href="'lightning:' + qrCodeDialog.data.payment_request">
<q-responsive :ratio="1" class="q-mx-xs">
<qrcode
:value="qrCodeDialog.data.payment_request"
:options="{width: 400}"
class="rounded-borders"
></qrcode>
</q-responsive>
</a>
<br />
<q-btn
outline
color="grey"
@click="copyText('lightning:' + qrCodeDialog.data.payment_request, 'Invoice copied to clipboard!')"
>Copy Invoice</q-btn
>
<q-card
v-if="!qrCodeDialog.data.payment_request"
class="q-pa-lg q-pt-xl lnbits__dialog-card"
>
</q-card>
<q-card v-else class="q-pa-lg q-pt-xl lnbits__dialog-card">
<div class="text-center q-mb-lg">
<a :href="'lightning:' + qrCodeDialog.data.payment_request">
<q-responsive :ratio="1" class="q-mx-xl">
<qrcode
:value="qrCodeDialog.data.payment_request"
:options="{width: 340}"
class="rounded-borders"
></qrcode>
</q-responsive>
</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-dialog>
</div>
@ -252,9 +268,6 @@
return {
stall: null,
products: [],
wallet: {
inkey: null
},
searchText: null,
cart: {
total: 0,
@ -271,8 +284,7 @@
payment_request: null
},
show: false
},
cancelListener: () => {}
}
}
},
computed: {
@ -297,6 +309,10 @@
}
},
methods: {
closeQrCodeDialog() {
this.qrCodeDialog.dismissMsg()
this.qrCodeDialog.show = false
},
resetCart() {
this.cart = {
total: 0,
@ -341,16 +357,10 @@
return {product_id: p[0], quantity: p[1].quantity}
})
}
LNbits.api
.request(
'POST',
'/diagonalley/api/v1/orders',
this.wallet.inkey,
data
)
.request('POST', '/diagonalley/api/v1/orders', null, data)
.then(res => {
this.checkoutDialog = {show: false}
this.checkoutDialog = {show: false, data: {}}
return res.data
})
@ -358,48 +368,46 @@
this.qrCodeDialog.data = data
this.qrCodeDialog.show = true
qrCodeDialog.dismissMsg = this.$q.notify({
this.qrCodeDialog.dismissMsg = this.$q.notify({
timeout: 0,
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() {
this.stall = JSON.parse('{{ stall | 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)
}
@ -410,13 +418,3 @@
}
</style>
{% 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):
stall = await get_diagonalley_stall(stall_id)
products = await get_diagonalley_products(stall_id)
wallet = await get_wallet(stall.wallet)
zones = []
for id in stall.shippingzones.split(","):
z = await get_diagonalley_zone(id)
z = z.dict()
zones.append({"label": z["countries"], "cost": z["cost"], "value": z["id"]})
logger.debug(f"ZONES {zones}")
if not stall:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Stall does not exist."
@ -57,7 +54,6 @@ async def display(request: Request, stall_id):
"request": request,
"stall": stall,
"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.services import create_invoice
from lnbits.core.views.api import api_payment
from lnbits.decorators import (
WalletTypeInfo,
get_key_type,
@ -33,6 +34,7 @@ from .crud import (
get_diagonalley_markets,
get_diagonalley_order,
get_diagonalley_order_details,
get_diagonalley_order_invoiceid,
get_diagonalley_orders,
get_diagonalley_product,
get_diagonalley_products,
@ -270,6 +272,21 @@ async def api_diagonalley_order_create(data: createOrder):
# 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}")
async def api_diagonalley_order_delete(
order_id: str, wallet: WalletTypeInfo = Depends(get_key_type)