Merge pull request #39 from lnbits/fix_images

feat: add more images for product
This commit is contained in:
Vlad Stan 2023-04-03 18:37:01 +03:00 committed by GitHub
commit 6dcd416e93
8 changed files with 51 additions and 73 deletions

View file

@ -258,7 +258,7 @@ async def create_product(merchant_id: str, data: PartialProduct) -> Product:
await db.execute(
f"""
INSERT INTO nostrmarket.products (merchant_id, id, stall_id, name, image, price, quantity, category_list, meta)
INSERT INTO nostrmarket.products (merchant_id, id, stall_id, name, price, quantity, image_urls, category_list, meta)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
@ -266,9 +266,9 @@ async def create_product(merchant_id: str, data: PartialProduct) -> Product:
product_id,
data.stall_id,
data.name,
data.image,
data.price,
data.quantity,
json.dumps(data.images),
json.dumps(data.categories),
json.dumps(data.config.dict()),
),
@ -283,14 +283,14 @@ async def update_product(merchant_id: str, product: Product) -> Product:
await db.execute(
f"""
UPDATE nostrmarket.products set name = ?, image = ?, price = ?, quantity = ?, category_list = ?, meta = ?
UPDATE nostrmarket.products set name = ?, price = ?, quantity = ?, image_urls = ?, category_list = ?, meta = ?
WHERE merchant_id = ? AND id = ?
""",
(
product.name,
product.image,
product.price,
product.quantity,
json.dumps(product.images),
json.dumps(product.categories),
json.dumps(product.config.dict()),
merchant_id,

View file

@ -43,7 +43,7 @@ async def m001_initial(db):
id TEXT PRIMARY KEY,
stall_id TEXT NOT NULL,
name TEXT NOT NULL,
image TEXT,
image_urls TEXT DEFAULT '[]',
price REAL NOT NULL,
quantity INTEGER NOT NULL,
category_list TEXT DEFAULT '[]',

View file

@ -217,30 +217,11 @@ class PartialProduct(BaseModel):
stall_id: str
name: str
categories: List[str] = []
image: Optional[str]
images: List[str] = []
price: float
quantity: int
config: ProductConfig = ProductConfig()
def validate_product(self):
if self.image:
image_is_url = self.image.startswith("https://") or self.image.startswith(
"http://"
)
if not image_is_url:
def size(b64string):
return int((len(b64string) * 3) / 4 - b64string.count("=", -2))
image_size = size(self.image) / 1024
if image_size > 100:
raise ValueError(
f"""
Image size is too big, {int(image_size)}Kb.
Max: 100kb, Compress the image at https://tinypng.com, or use an URL."""
)
class Product(PartialProduct, Nostrable):
id: str
@ -251,7 +232,7 @@ class Product(PartialProduct, Nostrable):
"stall_id": self.stall_id,
"name": self.name,
"description": self.config.description,
"image": self.image,
"images": self.images,
"currency": self.config.currency,
"price": self.price,
"quantity": self.quantity,
@ -285,6 +266,7 @@ class Product(PartialProduct, Nostrable):
def from_row(cls, row: Row) -> "Product":
product = cls(**dict(row))
product.config = ProductConfig(**json.loads(row["meta"]))
product.images = json.loads(row["image_urls"])
product.categories = json.loads(row["category_list"])
return product

View file

@ -1,6 +1,6 @@
<q-card class="card--product">
<q-img
:src="product.image ? product.image : '/nostrmarket/static/images/placeholder.png'"
:src="product.images ? product.images[0] : '/nostrmarket/static/images/placeholder.png'"
alt="Product Image"
loading="lazy"
spinner-color="white"

View file

@ -226,43 +226,28 @@
label="Categories (Hit Enter to add)"
placeholder="crafts,robots,etc"
></q-select>
<q-toggle
:label="`${productDialog.url ? 'Insert image URL' : 'Upload image file'}`"
v-model="productDialog.url"
></q-toggle>
<q-input
v-if="productDialog.url"
filled
dense
v-model.trim="productDialog.data.image"
@keydown.enter="addProductImage"
type="url"
label="Image URL"
></q-input>
<q-file
v-else
class="q-pr-md"
filled
dense
capture="environment"
accept="image/jpeg, image/png"
:max-file-size="3*1024**2"
label="Small image (optional)"
clearable
@input="imageAdded"
@clear="imageCleared"
>
<template v-if="productDialog.data.image" v-slot:before>
<img style="height: 1em" :src="productDialog.data.image" />
</template>
<template v-if="productDialog.data.image" v-slot:append>
<q-icon
name="cancel"
@click.stop.prevent="imageCleared"
class="cursor-pointer"
/>
</template>
</q-file>
<q-btn @click="addProductImage" dense flat icon="add"></q-btn
></q-input>
<q-chip
v-for="imageUrl in productDialog.data.images"
:key="imageUrl"
removable
@remove="removeProductImage(imageUrl)"
color="primary"
text-color="white"
>
<span v-text="imageUrl.split('/').pop()"></span>
</q-chip>
<q-input
filled
dense

View file

@ -27,6 +27,7 @@ async function stallDetails(path) {
id: null,
name: '',
categories: [],
images: [],
image: null,
price: 0,
@ -170,22 +171,23 @@ async function stallDetails(path) {
}
})
},
imageAdded(file) {
const image = new Image()
image.src = URL.createObjectURL(file)
image.onload = async () => {
let fit = imgSizeFit(image)
let canvas = document.createElement('canvas')
canvas.setAttribute('width', fit.width)
canvas.setAttribute('height', fit.height)
output = await pica.resize(image, canvas)
this.productDialog.data.image = output.toDataURL('image/jpeg', 0.4)
this.productDialog = {...this.productDialog}
addProductImage: function () {
if (!isValidImageUrl(this.productDialog.data.image)) {
this.$q.notify({
type: 'warning',
message: 'Not a valid image URL',
timeout: 5000
})
return
}
},
imageCleared() {
this.productDialog.data.images.push(this.productDialog.data.image)
this.productDialog.data.image = null
this.productDialog = {...this.productDialog}
},
removeProductImage: function (imageUrl) {
const index = this.productDialog.data.images.indexOf(imageUrl)
if (index !== -1) {
this.productDialog.data.images.splice(index, 1)
}
},
getProducts: async function () {
try {
@ -205,7 +207,7 @@ async function stallDetails(path) {
id: this.productDialog.data.id,
name: this.productDialog.data.name,
image: this.productDialog.data.image,
images: this.productDialog.data.images,
price: this.productDialog.data.price,
quantity: this.productDialog.data.quantity,
categories: this.productDialog.data.categories,
@ -294,6 +296,7 @@ async function stallDetails(path) {
description: '',
categories: [],
image: null,
images: [],
price: 0,
quantity: 0,
config: {

View file

@ -111,3 +111,13 @@ function timeFromNow(time) {
// Return time from now data
return `${tfn.time} ${tfn.unitOfTime}`
}
function isValidImageUrl(string) {
let url
try {
url = new URL(string)
} catch (_) {
return false
}
return url.protocol === 'http:' || url.protocol === 'https:'
}

View file

@ -518,7 +518,6 @@ async def api_create_product(
wallet: WalletTypeInfo = Depends(require_admin_key),
) -> Product:
try:
data.validate_product()
merchant = await get_merchant_for_user(wallet.wallet.user)
assert merchant, "Merchant cannot be found"
@ -557,7 +556,6 @@ async def api_update_product(
if product_id != product.id:
raise ValueError("Bad product ID")
product.validate_product()
merchant = await get_merchant_for_user(wallet.wallet.user)
assert merchant, "Merchant cannot be found"