general fixes, prop passing and shopping cart (doesn't send dm)

This commit is contained in:
Tiago Vasconcelos 2023-03-04 19:49:58 +00:00
parent f71b9f56d9
commit 52f8dead0e
11 changed files with 355 additions and 96 deletions

View file

@ -10,13 +10,20 @@
<q-breadcrumbs-el :label="stall.name" icon="widgets"></q-breadcrumbs-el>
</q-breadcrumbs>
<q-toolbar-title></q-toolbar-title>
<shopping-cart></shopping-cart>
<shopping-cart
:cart="cart"
:cart-menu="cartMenu"
@remove-from-cart="removeFromCart"
@reset-cart="resetCart"
@open-checkout="checkoutDialog.show = true"
></shopping-cart>
</q-toolbar>
<div class="row">
<product-detail
class="col-12"
v-if="productDetail && product"
:product="product"
@add-to-cart="addToCart"
></product-detail>
<div class="col-12 q-my-lg">
<q-separator></q-separator>
@ -28,7 +35,102 @@
v-for="(item, idx) in products"
:key="idx"
>
<product-card :product="item" @change-page="changePageS"></product-card>
<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-input
filled
dense
v-model.trim="checkoutDialog.data.pubkey"
label="Public key"
>
</q-input>
<q-input
filled
dense
readonly
hint="This your key pair! Don't lose it!"
v-if="checkoutDialog.data.privkey"
v-model="checkoutDialog.data.privkey"
>
</q-input>
<div class="row">
<div class="col-5">
<q-btn unelevated @click="generateKeyPair" color="primary"
>Generate key pair</q-btn
>
</div>
<div class="col-5" v-if="hasNip07">
<q-btn unelevated @click="getPubkey" color="primary"
>Get from Extension</q-btn
>
</div>
</div>
<q-input
filled
dense
v-model.trim="checkoutDialog.data.address"
label="Address"
></q-input>
<q-input
v-model="checkoutDialog.data.email"
filled
dense
type="email"
label="Email *optional"
hint="Merchant may not use email"
></q-input>
<p>Select the shipping zone:</p>
<div class="row q-mt-lg">
<q-option-group
:options="stall.shipping.map(s => ({label: s.countries.toString(), value: s.id}))"
type="radio"
emit-value
v-model="checkoutDialog.data.shippingzone"
/>
</div>
<div class="row q-mt-lg">
Total: {{ stall.currency != 'sat' ? getAmountFormated(finalCost) :
finalCost + 'sats' }}
<span v-if="stall.currency != 'sat'" class="q-ml-sm text-grey-6"
>({{ getValueInSats(finalCost) }} sats)</span
>
</div>
<div class="row q-mt-lg">
<q-btn
unelevated
color="primary"
:disable="checkoutDialog.data.address == null
|| checkoutDialog.data.shippingzone == 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 -->
</div>

View file

@ -10,23 +10,184 @@ async function customerStall(path) {
'products',
'exchange-rates',
'product-detail',
'change-page'
'change-page',
'relays'
],
data: function () {
return {}
return {
cart: {
total: 0,
size: 0,
products: new Map()
},
cartMenu: [],
hasNip07: false,
checkoutDialog: {
show: false,
data: {
pubkey: null
}
},
qrCodeDialog: {
data: {
payment_request: null
},
show: false
}
}
},
computed: {
product() {
if (this.productDetail) {
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) {
this.$emit('change-page', page, opts)
},
getValueInSats(amount, unit = 'USD') {
if (!this.exchangeRates) return 0
return Math.ceil(
(amount / this.exchangeRates[`BTC${unit}`][unit]) * 1e8
)
},
getAmountFormated(amount, unit = 'USD') {
return LNbits.utils.formatCurrency(amount, unit)
},
addToCart(item) {
console.log('add to cart', item)
let prod = this.cart.products
if (prod.has(item.id)) {
let qty = prod.get(item.id).quantity
prod.set(item.id, {
...prod.get(item.id),
quantity: qty + 1
})
} else {
prod.set(item.id, {
name: item.name,
quantity: 1,
price: item.price,
image: item?.images[0] || null
})
}
this.$q.notify({
type: 'positive',
message: `${item.name} added to cart`,
icon: 'thumb_up'
})
this.cart.products = prod
this.updateCart(+item.price)
},
removeFromCart(item) {
this.cart.products.delete(item.id)
this.updateCart(+item.price, true)
},
updateCart(price, del = false) {
console.log(this.cart, this.cartMenu)
if (del) {
this.cart.total -= price
this.cart.size--
} else {
this.cart.total += price
this.cart.size++
}
this.cartMenu = Array.from(this.cart.products, item => {
return {id: item[0], ...item[1]}
})
console.log(this.cart, this.cartMenu)
},
resetCart() {
this.cart = {
total: 0,
size: 0,
products: new Map()
}
},
async getPubkey() {
try {
this.checkoutDialog.data.pubkey = await window.nostr.getPublicKey()
this.checkoutDialog.data.privkey = null
} catch (err) {
console.error(
`Failed to get a public key from a Nostr extension: ${err}`
)
}
},
generateKeyPair() {
let sk = NostrTools.generatePrivateKey()
let pk = NostrTools.getPublicKey(sk)
this.checkoutDialog.data.pubkey = pk
this.checkoutDialog.data.privkey = sk
},
placeOrder() {
LNbits.utils
.confirmDialog(
`Send the order to the merchant? You should receive a message with the payment details.`
)
.onOk(async () => {
let orderData = this.checkoutDialog.data
let content = {
name: orderData?.username,
description: null,
address: orderData.address,
message: null,
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}
})
}
let event = {
kind: 4,
created_at: Math.floor(Date.now() / 1000),
tags: [],
content: await window.nostr.nip04.encrypt(
orderData.pubkey,
content
),
pubkey: orderData.pubkey
}
event.id = NostrTools.getEventHash(event)
if (orderData.privkey) {
event.sig = NostrTools.signEvent(event, orderData.privkey)
} else if (this.hasNip07) {
await window.nostr.signEvent(event)
}
await this.sendOrder(event)
})
},
async sendOrder(order) {
const pool = new NostrTools.SimplePool()
let relays = Array.from(this.relays)
let pubs = await pool.publish(relays, order)
pubs.on('ok', relay => {
console.log(`${relay.url} has accepted our event`)
})
pubs.on('failed', reason => {
console.log(`failed to publish to ${reason}`)
})
}
},
created() {}
created() {
setTimeout(() => {
if (window.nostr) {
this.hasNip07 = true
}
}, 1000)
}
})
}

View file

@ -9,6 +9,22 @@
></q-img>
<q-card-section class="q-pb-xs q-pt-md">
<q-btn
v-if="isStall"
round
:disabled="product.quantity < 1"
color="primary"
icon="shopping_cart"
size="lg"
style="
position: absolute;
top: 0;
right: 0;
transform: translate(-50%, -50%);
"
@click="$emit('add-to-cart', product)"
><q-tooltip> Add to cart </q-tooltip></q-btn
>
<div class="row no-wrap items-center">
<div class="col text-subtitle2 ellipsis-2-lines">{{ product.name }}</div>
</div>

View file

@ -4,7 +4,7 @@ async function productCard(path) {
name: 'product-card',
template,
props: ['product', 'change-page'],
props: ['product', 'change-page', 'add-to-cart', 'is-stall'],
data: function () {
return {}
},

View file

@ -17,6 +17,11 @@
style="/*background-size: contain; background-repeat: no-repeat*/"
></q-carousel-slide>
</q-carousel>
<q-img
v-if="!product.images"
src="/nostrmarket/static/images/placeholder.png"
:ratio="16/9"
></q-img>
</div>
</div>
<div class="col-lg-7 col-md-7 col-sm-12 col-xs-12">
@ -47,7 +52,7 @@
</span>
<span
class="q-ml-md text-caption text-green-8 text-weight-bolder q-mt-md"
>{{ product.amount > 0 ? 'In stock.' : 'Out of stock.' }}</span
>{{ product.quantity > 0 ? 'In stock.' : 'Out of stock.' }}</span
>
</div>
<div class="q-mt-md">
@ -56,12 +61,13 @@
color="primary"
icon="shopping_cart"
label="Add to cart"
@click="$emit('add-to-cart', product)"
/>
<q-btn
class="q-mt-md q-ml-md"
color="primary"
icon="shopping_cart"
label="Buy now"
icon="share"
label="Share"
/>
</div>
</div>

View file

@ -4,23 +4,14 @@ async function productDetail(path) {
name: 'product-detail',
template,
props: ['product'],
props: ['product', 'add-to-cart'],
data: function () {
return {
slide: 1
}
},
computed: {
win_width() {
return this.$q.screen.width - 59
},
win_height() {
return this.$q.screen.height - 0
}
},
computed: {},
methods: {},
created() {
console.log('ping')
}
created() {}
})
}

View file

@ -1 +1,51 @@
<q-btn dense round flat icon="shopping_cart" class="q-ml-md"></q-btn>
<q-btn dense round flat icon="shopping_cart">
<q-badge v-if="cart.size" color="red" class="text-bold" floating>
{{ cart.size }}
</q-badge>
<q-menu v-if="cart.size">
<q-list style="min-width: 100px">
<q-item :key="p.id" v-for="p in cartMenu">
<q-item-section side>
<span>{{p.quantity}} x </span>
</q-item-section>
<q-item-section avatar v-if="p.image">
<q-avatar color="primary">
<img size="sm" :src="p.image" />
</q-avatar>
</q-item-section>
<q-item-section>
<q-item-label>{{ p.name }}</q-item-label>
</q-item-section>
<q-item-section side>
<span>
{{p.currency != 'sat' ? p.formatedPrice : p.price + 'sats'}}
<q-btn
class="q-ml-md"
round
color="red"
size="xs"
icon="close"
@click="$emit('remove-from-cart', p)"
/>
</span>
</q-item-section>
</q-item>
<q-separator />
</q-list>
<div class="row q-pa-md q-gutter-md">
<q-btn
color="primary"
icon-right="checkout"
label="Checkout"
@click="$emit('open-checkout')"
></q-btn>
<q-btn
class="q-ml-lg"
flat
color="primary"
label="Reset"
@click="$emit('reset-cart')"
></q-btn></div></q-menu
></q-btn>

View file

@ -5,7 +5,7 @@ async function shoppingCart(path) {
name: 'shopping-cart',
template,
props: [],
props: ['cart', 'cart-menu', 'remove-from-cart', 'reset-cart'],
data: function () {
return {}
},

View file

@ -1,20 +1,13 @@
const market = async () => {
Vue.component(VueQrcode.name, VueQrcode)
const nostr = window.NostrTools
const NostrTools = window.NostrTools
const defaultRelays = [
'wss://relay.damus.io',
'wss://relay.snort.social',
'wss://nos.lol',
'wss://nostr.wine',
'wss://relay.nostr.bg',
'wss://nostr-pub.wellorder.net',
'wss://nostr-pub.semisol.dev',
'wss://eden.nostr.land',
'wss://nostr.mom',
'wss://nostr.fmt.wiz.biz',
'wss://nostr.zebedee.cloud',
'wss://nostr.rocks'
'wss://nostr.zebedee.cloud'
]
const eventToObj = event => {
event.content = JSON.parse(event.content)
@ -128,7 +121,7 @@ const market = async () => {
},
methods: {
naddr() {
let naddr = nostr.nip19.naddrEncode({
let naddr = NostrTools.nip19.naddrEncode({
identifier: '1234',
pubkey:
'c1415f950a1e3431de2bc5ee35144639e2f514cf158279abff9ed77d50118796',
@ -139,7 +132,7 @@ const market = async () => {
},
async initNostr() {
this.$q.loading.show()
const pool = new nostr.SimplePool()
const pool = new NostrTools.SimplePool()
let relays = Array.from(this.relays)
let products = new Map()
let stalls = new Map()
@ -243,7 +236,7 @@ const market = async () => {
let regExp = /^#([0-9a-f]{3}){1,2}$/i
if (pubkey.startsWith('n')) {
try {
let {type, data} = nostr.nip19.decode(pubkey)
let {type, data} = NostrTools.nip19.decode(pubkey)
if (type === 'npub') pubkey = data
else if (type === 'nprofile') {
pubkey = data.pubkey

View file

@ -145,6 +145,7 @@
:products="filterProducts"
:exchange-rates="exchangeRates"
:product-detail="activeProduct"
:relays="relays"
@change-page="navigateTo"
></customer-stall>
<customer-market

View file

@ -1,61 +0,0 @@
{% extends "public.html" %} {% block page %}
<div class="row q-mb-md"></div>
{% endblock %} {% block scripts %}
<script src="https://unpkg.com/nostr-tools/lib/nostr.bundle.js"></script>
<script>
const nostr = window.NostrTools
const defaultRelays = [
'wss://relay.damus.io',
'wss://relay.snort.social',
'wss://nos.lol',
'wss://nostr.wine',
'wss://relay.nostr.bg',
'wss://nostr-pub.wellorder.net',
'wss://nostr-pub.semisol.dev',
'wss://eden.nostr.land',
'wss://nostr.mom',
'wss://nostr.fmt.wiz.biz',
'wss://nostr.zebedee.cloud'
]
const mapProductsItems = obj => {
obj.price = parseFloat((obj.price / 100).toFixed(2))
return obj
}
Vue.component(VueQrcode.name, VueQrcode)
new Vue({
el: '#vue',
mixins: [windowMixin],
data: function () {
return {}
},
async created() {
this.stallId = JSON.parse('{{ stall_id }}')
await initNostr()
//this.products = JSON.parse('{{ products | tojson }}')
//this.unit = this.stall.currency
/*if (this.unit != 'sat') {
this.products = this.products.map(mapProductsItems)
}
await this.getRates()
setInterval(this.getRates, 300000)*/
},
methods: {
async initNostr() {
this.pool = new nostr.SimplePool()
this.relays = new Set(defaultRelays)
await this.pool
.get(Array.from(this.relays), {
kinds: [30023],
limit: 1,
'#d': [this.stallId]
})
.then(event => {
console.log(event)
})
}
}
})
</script>
{% endblock %}