refactor: code clean-up

This commit is contained in:
Vlad Stan 2023-07-18 11:47:19 +03:00
parent 51f5f0cd1c
commit d810b7c5d5
4 changed files with 2 additions and 427 deletions

View file

@ -14,127 +14,5 @@
<product-card :product="item" @change-page="changePageS" @add-to-cart="addToCart" :is-stall="true"></product-card>
</div>
</div>
<!-- BEGIN CHECKOUT DIALOG -->
<q-dialog v-model="checkoutDialog.show" position="top">
<q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
<q-form @submit="placeOrder" class="q-gutter-md">
<q-input filled dense v-model.trim="checkoutDialog.data.username" label="Name (optional)"></q-input>
<q-expansion-item v-if="!account" dense dense-toggle expand-separator icon="person_off" label="Not logged in?">
<q-card>
<q-card-section>
It seems you haven't logged in. You can:
<ol>
<li>
enter your public and private keys below (to sign the order
message)
</li>
<li>use a Nostr Signer Extension (NIP07)</li>
<li>
fill out the required fields and with your public key,
download the order and send as a direct message to the
merchant on any Nostr client
</li>
</ol>
</q-card-section>
<q-card-actions align="right">
<q-btn v-if="hasNip07" unelevated @click="getFromExtension" color="primary"
label="Get from Extension"><q-tooltip>Use a Nostr browser extension</q-tooltip></q-btn>
<q-btn v-if="!this.account && !this.customerPubkey && !this.customerPrivkey" unelevated @click="makeLogin"
color="primary" label="Login"></q-btn>
</q-card-actions>
</q-card>
</q-expansion-item>
<q-input filled dense :readonly="Boolean(customerPubkey)" v-model.trim="checkoutDialog.data.pubkey"
label="Public key" hint="Enter your public key">
</q-input>
<q-input filled dense :readonly="Boolean(customerPrivkey)" :type="isPwd ? 'password' : 'text'"
v-if="!customerUseExtension" v-model.trim="checkoutDialog.data.privkey" label="Private key (optional)"
hint="Enter your private key">
<template v-slot:append>
<q-icon :name="isPwd ? 'visibility_off' : 'visibility'" class="cursor-pointer" @click="isPwd = !isPwd" />
</template>
</q-input>
<q-input filled dense v-model.trim="checkoutDialog.data.address" label="Address (optional)"
hint="If ordering a physical product make sure to fill this"></q-input>
<q-input v-model="checkoutDialog.data.email" filled dense type="email" label="Email (optional)"
hint="Merchant may not use email"></q-input>
<q-input v-model="checkoutDialog.data.message" filled dense type="text" label="Message (optional)"></q-input>
<p>Select the shipping zone:</p>
<div class="row q-mt-lg">
<q-select style="min-width: 200px" filled dense stack-label v-model="checkoutDialog.data.shippingzone"
emit-value map-options :options="stall.shipping.map(s => ({label: s.countries.toString(), value: s.id}))"
label="Shipping Zone" />
</div>
<div class="row q-mt-lg">
Total: {{ stall.currency != 'sat' ? getAmountFormated(finalCost,
stall.currency) : finalCost + 'sats' }}
</div>
<div class="row q-mt-lg">
<q-btn v-if="!customerUseExtension && !checkoutDialog.data.privkey" :loading="loading" unelevated
color="primary" :disable="checkoutDialog.data.shippingzone == null
|| checkoutDialog.data.pubkey == null" @click="downloadOrder">Download Order</q-btn>
<q-btn v-else :loading="loading" unelevated color="primary" :disable="checkoutDialog.data.shippingzone == null
|| checkoutDialog.data.pubkey == null" type="submit">Checkout</q-btn>
<q-btn v-close-popup flat @click="checkoutDialog = {show: false, data: {pubkey: null}}" color="grey"
class="q-ml-auto">Cancel</q-btn>
</div>
</q-form>
</q-card>
</q-dialog>
<!-- END CHECKOUT DIALOG -->
<!-- INVOICE DIALOG -->
<q-dialog v-model="qrCodeDialog.show" position="top" @hide="closeQrCodeDialog">
<q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
<div class="text-center q-mb-lg">
<div class="q-my-lg" v-if="qrCodeDialog.data.message">
<p>{{ qrCodeDialog.data.message }}</p>
</div>
<a v-else :href="'lightning:' + qrCodeDialog.data.payment_request">
<q-responsive :ratio="1" class="q-mx-xl">
<qrcode v-if="qrCodeDialog.data.payment_request" :value="qrCodeDialog.data.payment_request"
:options="{width: 340}" class="rounded-borders"></qrcode>
</q-responsive>
</a>
<q-inner-loading :showing="loading">
<q-spinner-puff size="50px" color="primary" />
</q-inner-loading>
</div>
<div class="row q-mt-lg">
<q-btn v-if="qrCodeDialog.data.payment_request" outline color="grey"
@click="copyText(qrCodeDialog.data.payment_request)">Copy invoice</q-btn>
<q-btn @click="closeQrCodeDialog" flat color="grey" class="q-ml-auto">Close</q-btn>
</div>
</q-card>
</q-dialog>
<!-- ORDER DOWNLOAD DIALOG -->
<q-dialog v-model="downloadOrderDialog.show" position="top">
<q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
<q-card-section>
<div class="text-h6">Order data</div>
<div class="text-subtitle1">Merchant pubkey</div>
<div class="text-subtitle2" @click="copyText(stall.pubkey)">
{{ `${stall.pubkey.slice(0,5)}...${stall.pubkey.slice(-5)}` }}
<sup>
<q-icon name="content_copy" style="color: #ccc; font-size: 1.2em" />
</sup>
<q-tooltip>Click to copy</q-tooltip>
</div>
<p>
Send the below code as a message, to the merchant pubkey, in any
Nostr client
</p>
</q-card-section>
<q-separator dark inset />
<q-card-section>
<pre
style="font-size: 0.65rem; overflow-x: auto"><code>{{JSON.stringify(downloadOrderDialog.data, null, 2)}}</code></pre>
</q-card-section>
<div class="row q-mt-lg">
<q-btn outline color="primary" @click="copyText(JSON.stringify(downloadOrderDialog.data))">Copy order</q-btn>
<q-btn v-close-popup flat color="grey" class="q-ml-auto">Close</q-btn>
</div>
</q-card>
</q-dialog>
</div>

View file

@ -6,50 +6,12 @@ async function customerStall(path) {
template,
props: [
'account',
'login-dialog',
'stall',
'products',
'stall-products',
'product-detail',
'change-page',
'relays',
'pool',
'styles'
],
data: function () {
return {
loading: false,
isPwd: true,
cart: {
total: 0,
size: 0,
products: new Map()
},
cartMenu: [],
hasNip07: false,
customerPubkey: null,
customerPrivkey: null,
customerUseExtension: null,
activeOrder: null,
banner: null,
checkoutDialog: {
show: false,
data: {
pubkey: null
}
},
qrCodeDialog: {
data: {
payment_request: null
},
dismissMsg: null,
show: false
},
downloadOrderDialog: {
show: false,
data: {}
}
}
},
computed: {
@ -58,14 +20,6 @@ async function customerStall(path) {
return this.products.find(p => p.id == this.productDetail)
}
},
finalCost() {
if (!this.checkoutDialog.data.shippingzone) return this.cart.total
let zoneCost = this.stall.shipping.find(
z => z.id == this.checkoutDialog.data.shippingzone
)
return +this.cart.total + zoneCost.cost
}
},
methods: {
changePageS(page, opts) {
@ -74,265 +28,10 @@ async function customerStall(path) {
}
this.$emit('change-page', page, opts)
},
makeLogin() {
this.resetCheckout()
this.$emit('login-dialog')
},
copyText: function (text) {
var notify = this.$q.notify
Quasar.utils.copyToClipboard(text).then(function () {
notify({
message: 'Copied to clipboard!',
position: 'bottom'
})
})
},
getAmountFormated(amount, unit = 'USD') {
return LNbits.utils.formatCurrency(amount, unit)
},
addToCart(item) {
this.$emit('add-to-cart', item)
},
resetCart() {
this.cart = {
total: 0,
size: 0,
products: new Map()
}
this.$q.localStorage.remove(`diagonAlley.carts.${this.stall.id}`)
},
async downloadOrder() {
let created_at = Math.floor(Date.now() / 1000)
let orderData = this.checkoutDialog.data
let orderObj = {
name: orderData?.username,
address: orderData.address,
message: orderData?.message,
contact: {
nostr: orderData.pubkey,
phone: null,
email: orderData?.email
},
items: Array.from(this.cart.products, p => {
return { product_id: p[0], quantity: p[1].quantity }
}),
shipping_id: orderData.shippingzone
}
orderObj.id = await hash(
[orderData.pubkey, created_at, JSON.stringify(orderObj)].join(':')
)
this.downloadOrderDialog.data = orderObj
this.downloadOrderDialog.show = true
this.resetCheckout()
this.resetCart()
},
async getFromExtension() {
this.customerPubkey = await window.nostr.getPublicKey()
this.customerUseExtension = true
this.checkoutDialog.data.pubkey = this.customerPubkey
},
checkLogIn() {
this.customerPubkey = this.account?.pubkey
this.customerPrivkey = this.account?.privkey
this.customerUseExtension = this.account?.useExtension
},
resetCheckout() {
this.loading = false
this.checkoutDialog = {
show: false,
data: {
pubkey: null
}
}
},
openQrCodeDialog() {
this.qrCodeDialog = {
data: {
payment_request: null,
message: null
},
dismissMsg: this.$q.notify({
message: 'Waiting for invoice from merchant...'
}),
show: true
}
},
closeQrCodeDialog() {
this.qrCodeDialog.show = false
this.qrCodeDialog.data = {
payment_request: null,
message: null
}
setTimeout(() => {
this.qrCodeDialog.dismissMsg()
}, 1000)
},
async placeOrder() {
this.loading = true
let orderData = this.checkoutDialog.data
let orderObj = {
name: orderData?.username,
address: orderData.address,
message: orderData?.message,
contact: {
nostr: this.customerPubkey,
phone: null,
email: orderData?.email
},
items: Array.from(this.cart.products, p => {
return { product_id: p[0], quantity: p[1].quantity }
}),
shipping_id: orderData.shippingzone,
type: 0
}
let created_at = Math.floor(Date.now() / 1000)
orderObj.id = await hash(
[this.customerPubkey, created_at, JSON.stringify(orderObj)].join(':')
)
this.activeOrder = orderObj.id
let event = {
...(await NostrTools.getBlankEvent()),
kind: 4,
created_at,
tags: [['p', this.stall.pubkey]],
pubkey: this.customerPubkey
}
if (this.customerPrivkey) {
event.content = await NostrTools.nip04.encrypt(
this.customerPrivkey,
this.stall.pubkey,
JSON.stringify(orderObj)
)
} else if (this.customerUseExtension && this.hasNip07) {
event.content = await window.nostr.nip04.encrypt(
this.stall.pubkey,
JSON.stringify(orderObj)
)
let userRelays = Object.keys(
(await window.nostr?.getRelays?.()) || []
)
if (userRelays.length != 0) {
userRelays.map(r => this.relays.add(r))
}
}
event.id = NostrTools.getEventHash(event)
if (this.customerPrivkey) {
event.sig = await NostrTools.signEvent(event, this.customerPrivkey)
} else if (this.customerUseExtension && this.hasNip07) {
event = await window.nostr.signEvent(event)
}
this.resetCheckout()
await this.sendOrder(event)
},
async sendOrder(order) {
let pub = this.pool.publish(Array.from(this.relays), order)
pub.on('ok', () => console.debug(`Order event was sent`))
pub.on('failed', error => console.error(error))
this.loading = false
this.resetCart()
this.openQrCodeDialog()
this.listenMessages()
},
async listenMessages() {
this.loading = true
try {
const filters = [
{
kinds: [4],
authors: [this.stall.pubkey]
},
{
kinds: [4],
'#p': [this.customerPubkey]
}
]
let relays = Array.from(this.relays)
let subs = this.pool.sub(relays, filters)
subs.on('event', async event => {
let mine = event.pubkey == this.customerPubkey
let sender = mine
? event.tags.find(([k, v]) => k === 'p' && v && v !== '')[1]
: event.pubkey
try {
let plaintext
if (this.customerPrivkey) {
plaintext = await NostrTools.nip04.decrypt(
this.customerPrivkey,
sender,
event.content
)
} else if (this.customerUseExtension && this.hasNip07) {
plaintext = await window.nostr.nip04.decrypt(
sender,
event.content
)
}
this.messageFilter(plaintext, cb => subs.unsub())
} catch {
console.debug('Unable to decrypt message! Probably not for us!')
}
})
} catch (err) {
console.error(`Error: ${err}`)
}
},
messageFilter(text, cb = () => { }) {
if (!isJson(text)) return
let json = JSON.parse(text)
if (json.id != this.activeOrder) return
if (json.payment_options) {
if (json.payment_options.length == 0 && json.message) {
this.loading = false
this.qrCodeDialog.data.message = json.message
return cb()
}
let payment_request = json.payment_options.find(o => o.type == 'ln')
.link
if (!payment_request) return
this.loading = false
this.qrCodeDialog.data.payment_request = payment_request
this.qrCodeDialog.dismissMsg = this.$q.notify({
timeout: 0,
message: 'Waiting for payment...'
})
} else if (json.paid) {
this.closeQrCodeDialog()
this.$q.notify({
type: 'positive',
message: 'Sats received, thanks!',
icon: 'thumb_up'
})
this.activeOrder = null
return cb()
} else {
return
}
}
},
created() {
this.checkLogIn()
let storedCart = this.$q.localStorage.getItem(
`diagonAlley.carts.${this.stall.id}`
)
if (storedCart) {
this.cart.total = storedCart.total
this.cart.size = storedCart.size
this.cart.products = new Map(Object.entries(storedCart.products))
this.cartMenu = Array.from(this.cart.products, item => {
return { id: item[0], ...item[1] }
})
}
setTimeout(() => {
if (window.nostr) {
this.hasNip07 = true
}
}, 1000)
}
})
}