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(
"SELECT * FROM diagonalley.stalls WHERE id = ?", (stall_id,)
)
print("ROW", row)
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):
q = "\n".join(
@ -413,7 +426,6 @@ async def update_diagonalley_market(market_id):
async def create_chat_message(data: CreateChatMessage):
print("DATA", data)
await db.execute(
"""
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})",
(*ids,),
)
print(ids, q, rows)
return [ChatMessage(**row) for row in rows]

View file

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

View file

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

View file

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

View file

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

View file

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