clean up and add pubkey to order

This commit is contained in:
Tiago Vasconcelos 2022-11-11 12:11:14 +00:00
parent f3fc1e4a2b
commit 82e887b7a8
6 changed files with 109 additions and 94 deletions

View file

@ -192,7 +192,6 @@ async def get_diagonalley_stall(stall_id: str) -> Optional[Stalls]:
row = await db.fetchone( row = await db.fetchone(
"SELECT * FROM diagonalley.stalls WHERE id = ?", (stall_id,) "SELECT * FROM diagonalley.stalls WHERE id = ?", (stall_id,)
) )
print("ROW", row)
return Stalls(**row) if row else None return Stalls(**row) if row else None
@ -305,6 +304,20 @@ async def set_diagonalley_order_paid(payment_hash: str) -> Orders:
) )
async def set_diagonalley_order_pubkey(payment_hash: str, pubkey: str):
await db.execute(
"""
UPDATE diagonalley.orders
SET pubkey = ?
WHERE invoiceid = ?
""",
(
pubkey,
payment_hash,
),
)
async def update_diagonalley_product_stock(products): async def update_diagonalley_product_stock(products):
q = "\n".join( q = "\n".join(
@ -413,7 +426,6 @@ async def update_diagonalley_market(market_id):
async def create_chat_message(data: CreateChatMessage): async def create_chat_message(data: CreateChatMessage):
print("DATA", data)
await db.execute( await db.execute(
""" """
INSERT INTO diagonalley.messages (msg, pubkey, id_conversation) INSERT INTO diagonalley.messages (msg, pubkey, id_conversation)
@ -452,5 +464,4 @@ async def get_diagonalley_chat_by_merchant(ids: List[str]) -> List[ChatMessage]:
f"SELECT * FROM diagonalley.messages WHERE id_conversation IN ({q})", f"SELECT * FROM diagonalley.messages WHERE id_conversation IN ({q})",
(*ids,), (*ids,),
) )
print(ids, q, rows)
return [ChatMessage(**row) for row in rows] return [ChatMessage(**row) for row in rows]

View file

@ -80,9 +80,7 @@ class Notifier:
"""Notifier""" """Notifier"""
d = json.loads(message) d = json.loads(message)
d["room_name"] = room_name d["room_name"] = room_name
print("hey", d)
db_msg = CreateChatMessage.parse_obj(d) db_msg = CreateChatMessage.parse_obj(d)
print("NOT:", db_msg)
await create_chat_message(data=db_msg) await create_chat_message(data=db_msg)
remaining_sessions = [] remaining_sessions = []

View file

@ -859,9 +859,10 @@
<q-card-section> <q-card-section>
<q-select <q-select
v-model="customerKey" v-model="customerKey"
:options="Object.keys(messages)" :options="Object.keys(messages).map(k => ({label: `${k.slice(0, 25)}...`, value: k}))"
label="Customers" label="Customers"
@input="chatRoom(customerKey)" @input="chatRoom(customerKey)"
emit-value
></q-select> ></q-select>
</q-card-section> </q-card-section>
<div class="chat-container q-pa-md" ref="chatCard"> <div class="chat-container q-pa-md" ref="chatCard">
@ -1787,7 +1788,6 @@
.then(response => { .then(response => {
if (response.data) { if (response.data) {
this.markets = response.data.map(mapMarkets) this.markets = response.data.map(mapMarkets)
// console.log(this.markets)
} }
}) })
.catch(error => { .catch(error => {
@ -1904,7 +1904,7 @@
LNbits.utils.notifyApiError(error) LNbits.utils.notifyApiError(error)
}) })
}, },
createOrder: function () { /*createOrder: function () {
var data = { var data = {
address: this.orderDialog.data.address, address: this.orderDialog.data.address,
email: this.orderDialog.data.email, email: this.orderDialog.data.email,
@ -1929,7 +1929,7 @@
.catch(function (error) { .catch(function (error) {
LNbits.utils.notifyApiError(error) LNbits.utils.notifyApiError(error)
}) })
}, },*/
deleteOrder: function (orderId) { deleteOrder: function (orderId) {
var self = this var self = this
var order = _.findWhere(self.orders, {id: orderId}) var order = _.findWhere(self.orders, {id: orderId})
@ -1941,7 +1941,7 @@
.request( .request(
'DELETE', 'DELETE',
'/diagonalley/api/v1/orders/' + orderId, '/diagonalley/api/v1/orders/' + orderId,
_.findWhere(self.g.user.wallets, {id: order.wallet}).inkey _.findWhere(self.g.user.wallets, {id: order.wallet}).adminkey
) )
.then(function (response) { .then(function (response) {
self.orders = _.reject(self.orders, function (obj) { self.orders = _.reject(self.orders, function (obj) {
@ -1961,7 +1961,6 @@
this.g.user.wallets[0].inkey this.g.user.wallets[0].inkey
) )
.then(response => { .then(response => {
console.log(response.data)
this.orders = _.reject(this.orders, obj => { this.orders = _.reject(this.orders, obj => {
return obj.id == order_id return obj.id == order_id
}) })
@ -1987,7 +1986,6 @@
.then(res => { .then(res => {
this.messages = _.groupBy(res.data, 'id_conversation') this.messages = _.groupBy(res.data, 'id_conversation')
this.checkUnreadMessages() this.checkUnreadMessages()
console.log('Get new messages!')
}) })
.catch(error => { .catch(error => {
LNbits.utils.notifyApiError(error) LNbits.utils.notifyApiError(error)
@ -2005,7 +2003,6 @@
] ]
} }
} }
//console.log({chat})
this.$q.localStorage.set(`lnbits.diagonalley.${this.g.user.id}`, { this.$q.localStorage.set(`lnbits.diagonalley.${this.g.user.id}`, {
...data, ...data,
chat chat
@ -2031,7 +2028,6 @@
} else { } else {
this.$set(this.orders[idx], 'unread', false) this.$set(this.orders[idx], 'unread', false)
} }
console.log('Order:', this.orders[idx])
} }
}, },
clearMessage() { clearMessage() {
@ -2122,6 +2118,11 @@
}) })
</script> </script>
<style scoped> <style scoped>
.q-field__native span{
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.chat-container { .chat-container {
position: relative; position: relative;
display: grid; display: grid;

View file

@ -68,10 +68,11 @@
dense dense
emit-value emit-value
v-model="selectedOrder" v-model="selectedOrder"
:options="Object.keys(user.orders)" :options="Object.keys(user.orders).map(o => ({label: `${o.slice(0, 25)}...`, value: o}))"
label="Order" label="Order"
hint="Select an order from this merchant" hint="Select an order from this merchant"
@input="val => { changeOrder() }" @input="val => { changeOrder() }"
emit-value
></q-select> ></q-select>
</q-form> </q-form>
</q-card-section> </q-card-section>
@ -224,7 +225,9 @@
selectedOrder: null, selectedOrder: null,
products: [], products: [],
orders: [], orders: [],
user: null, user: {
keys: {}
},
keysDialog: { keysDialog: {
show: false, show: false,
data: {} data: {}
@ -291,18 +294,18 @@
this.user = null this.user = null
}) })
}, },
async generateKeys() { async generateKeys(payment_hash) {
await LNbits.api return await LNbits.api
.request('GET', '/diagonalley/api/v1/keys', null) .request('GET', `/diagonalley/api/v1/keys/${payment_hash}`, null)
.then(response => { .then(response => {
if (response.data) { if (response.data) {
let data = { let data = {
keys: { keys: {
privatekey: response.data.privkey, privatekey: response.data.privkey,
publickey: response.data.pubkey publickey: response.data.pubkey
}
} }
this.user = data }
this.user.keys = data.keys
return return
} }
}) })
@ -385,37 +388,39 @@
} }
}) })
let data = this.$q.localStorage.getItem(`lnbits.diagonalley.data`) let data = this.$q.localStorage.getItem(`lnbits.diagonalley.data`) || false
try { if (data) {
if (data) { this.user = data
this.user = data //add chat key (merchant pubkey) if not set
//add chat key (merchant pubkey) if not set if (!this.user.orders[`${order_id}`]) {
if (!this.user.orders[`${order_id}`]) { this.$set(this.user.orders, order_id, this.products)
this.$set(this.user.orders, order_id, this.products) }
} } else {
} else { // generate keys
// generate keys this.generateKeys(order_id)
await this.generateKeys() // populate user data
// populate user data this.user.orders = {
this.user.orders = { [`${order_id}`]: this.products
[`${order_id}`]: this.products
}
} }
this.selectedOrder = order_id
await this.getMessages(order_id)
this.$q.localStorage.set(`lnbits.diagonalley.data`, this.user)
this.startChat(order_id)
} catch (e) {
console.error(e)
} }
this.selectedOrder = order_id
await this.getMessages(order_id)
this.$q.localStorage.set(`lnbits.diagonalley.data`, this.user)
this.startChat(order_id)
} }
}) })
</script> </script>
<style scoped> <style scoped>
.q-field__native span{
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.chat-container { .chat-container {
position: relative; position: relative;
display: grid; display: grid;

View file

@ -357,7 +357,6 @@
this.cartMenu = Array.from(this.cart.products, item => { this.cartMenu = Array.from(this.cart.products, item => {
return {id: item[0], ...item[1]} return {id: item[0], ...item[1]}
}) })
console.log(this.cartMenu, this.cart)
}, },
getPubkey() { getPubkey() {
let data = this.$q.localStorage.getItem(`lnbits.diagonalley.data`) let data = this.$q.localStorage.getItem(`lnbits.diagonalley.data`)
@ -446,7 +445,6 @@
this.stall = JSON.parse('{{ stall | tojson }}') this.stall = JSON.parse('{{ stall | tojson }}')
this.products = JSON.parse('{{ products | tojson }}') this.products = JSON.parse('{{ products | tojson }}')
console.log(this.stall, this.products)
} }
}) })
</script> </script>

View file

@ -55,6 +55,7 @@ from .crud import (
update_diagonalley_product, update_diagonalley_product,
update_diagonalley_stall, update_diagonalley_stall,
update_diagonalley_zone, update_diagonalley_zone,
set_diagonalley_order_pubkey,
) )
from .models import ( from .models import (
CreateMarket, CreateMarket,
@ -202,7 +203,6 @@ async def api_diagonalley_stall_create(
if stall_id: if stall_id:
stall = await get_diagonalley_stall(stall_id) stall = await get_diagonalley_stall(stall_id)
print("ID", stall_id)
if not stall: if not stall:
return {"message": "Withdraw stall does not exist."} return {"message": "Withdraw stall does not exist."}
@ -306,7 +306,7 @@ async def api_diagonalley_check_payment(payment_hash: str):
@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(require_admin_key)
): ):
order = await get_diagonalley_order(order_id) order = await get_diagonalley_order(order_id)
@ -364,7 +364,6 @@ async def api_diagonalley_stall_products(
rows = await db.fetchone( rows = await db.fetchone(
"SELECT * FROM diagonalley.stalls WHERE id = ?", (stall_id,) "SELECT * FROM diagonalley.stalls WHERE id = ?", (stall_id,)
) )
print(rows[1])
if not rows: if not rows:
return {"message": "Stall does not exist."} return {"message": "Stall does not exist."}
@ -393,44 +392,44 @@ async def api_diagonalley_stall_checkshipped(
###Place order ###Place order
@diagonalley_ext.post("/api/v1/stall/order/{stall_id}") # @diagonalley_ext.post("/api/v1/stall/order/{stall_id}")
async def api_diagonalley_stall_order( # async def api_diagonalley_stall_order(
stall_id, data: createOrder, wallet: WalletTypeInfo = Depends(get_key_type) # stall_id, data: createOrder, wallet: WalletTypeInfo = Depends(get_key_type)
): # ):
product = await get_diagonalley_product(data.productid) # product = await get_diagonalley_product(data.productid)
shipping = await get_diagonalley_stall(stall_id) # shipping = await get_diagonalley_stall(stall_id)
if data.shippingzone == 1: # if data.shippingzone == 1:
shippingcost = shipping.zone1cost # missing in model # shippingcost = shipping.zone1cost # missing in model
else: # else:
shippingcost = shipping.zone2cost # missing in model # shippingcost = shipping.zone2cost # missing in model
checking_id, payment_request = await create_invoice( # checking_id, payment_request = await create_invoice(
wallet_id=product.wallet, # wallet_id=product.wallet,
amount=shippingcost + (data.quantity * product.price), # amount=shippingcost + (data.quantity * product.price),
memo=shipping.wallet, # memo=shipping.wallet,
) # )
selling_id = urlsafe_b64encode(uuid4().bytes_le).decode("utf-8") # selling_id = urlsafe_b64encode(uuid4().bytes_le).decode("utf-8")
await db.execute( # await db.execute(
""" # """
INSERT INTO diagonalley.orders (id, productid, wallet, product, quantity, shippingzone, address, email, invoiceid, paid, shipped) # INSERT INTO diagonalley.orders (id, productid, wallet, product, quantity, shippingzone, address, email, invoiceid, paid, shipped)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) # VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", # """,
( # (
selling_id, # selling_id,
data.productid, # data.productid,
product.wallet, # doesn't exist in model # product.wallet, # doesn't exist in model
product.product, # product.product,
data.quantity, # data.quantity,
data.shippingzone, # data.shippingzone,
data.address, # data.address,
data.email, # data.email,
checking_id, # checking_id,
False, # False,
False, # False,
), # ),
) # )
return {"checking_id": checking_id, "payment_request": payment_request} # return {"checking_id": checking_id, "payment_request": payment_request}
## ##
@ -482,13 +481,16 @@ async def api_diagonalley_stall_create(
## KEYS ## KEYS
@diagonalley_ext.get("/api/v1/keys") @diagonalley_ext.get("/api/v1/keys/{payment_hash}")
async def api_diagonalley_generate_keys(): async def api_diagonalley_generate_keys(payment_hash: str):
private_key = PrivateKey() private_key = PrivateKey()
public_key = private_key.pubkey.serialize().hex() public_key = private_key.pubkey.serialize().hex()
while not public_key.startswith("02"): while not public_key.startswith("02"):
private_key = PrivateKey() private_key = PrivateKey()
public_key = private_key.pubkey.serialize().hex() public_key = private_key.pubkey.serialize().hex()
# set pubkey in order
await set_diagonalley_order_pubkey(payment_hash, pubkey=public_key[2:])
return {"privkey": private_key.serialize(), "pubkey": public_key[2:]} return {"privkey": private_key.serialize(), "pubkey": public_key[2:]}