Merge pull request #5 from lnbits/products_to_nostr

Products to nostr
This commit is contained in:
Vlad Stan 2023-03-03 11:38:51 +02:00 committed by GitHub
commit 6bb6a9d02a
7 changed files with 164 additions and 52 deletions

12
crud.py
View file

@ -197,7 +197,7 @@ async def create_product(user_id: str, data: PartialProduct) -> Product:
await db.execute( await db.execute(
f""" f"""
INSERT INTO nostrmarket.products (user_id, id, stall_id, name, category_list, description, images, price, quantity) INSERT INTO nostrmarket.products (user_id, id, stall_id, name, images, price, quantity, category_list, meta)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""", """,
( (
@ -205,11 +205,11 @@ async def create_product(user_id: str, data: PartialProduct) -> Product:
product_id, product_id,
data.stall_id, data.stall_id,
data.name, data.name,
json.dumps(data.categories),
data.description,
data.image, data.image,
data.price, data.price,
data.quantity, data.quantity,
json.dumps(data.categories),
json.dumps(data.config.dict()),
), ),
) )
product = await get_product(user_id, product_id) product = await get_product(user_id, product_id)
@ -222,16 +222,16 @@ async def update_product(user_id: str, product: Product) -> Product:
await db.execute( await db.execute(
f""" f"""
UPDATE nostrmarket.products set name = ?, category_list = ?, description = ?, images = ?, price = ?, quantity = ? UPDATE nostrmarket.products set name = ?, images = ?, price = ?, quantity = ?, category_list = ?, meta = ?
WHERE user_id = ? AND id = ? WHERE user_id = ? AND id = ?
""", """,
( (
product.name, product.name,
json.dumps(product.categories),
product.description,
product.image, product.image,
product.price, product.price,
product.quantity, product.quantity,
json.dumps(product.categories),
json.dumps(product.config.dict()),
user_id, user_id,
product.id, product.id,
), ),

View file

@ -37,17 +37,17 @@ async def m001_initial(db):
Initial products table. Initial products table.
""" """
await db.execute( await db.execute(
f""" """
CREATE TABLE nostrmarket.products ( CREATE TABLE nostrmarket.products (
user_id TEXT NOT NULL, user_id TEXT NOT NULL,
id TEXT PRIMARY KEY, id TEXT PRIMARY KEY,
stall_id TEXT NOT NULL, stall_id TEXT NOT NULL,
name TEXT NOT NULL, name TEXT NOT NULL,
category_list TEXT DEFAULT '[]',
description TEXT,
images TEXT DEFAULT '[]', images TEXT DEFAULT '[]',
price REAL NOT NULL, price REAL NOT NULL,
quantity INTEGER NOT NULL quantity INTEGER NOT NULL,
category_list TEXT DEFAULT '[]',
meta TEXT NOT NULL DEFAULT '{}'
); );
""" """
) )

View file

@ -1,5 +1,6 @@
import json import json
import time import time
from abc import abstractmethod
from sqlite3 import Row from sqlite3 import Row
from typing import List, Optional from typing import List, Optional
@ -8,6 +9,18 @@ from pydantic import BaseModel
from .helpers import sign_message_hash from .helpers import sign_message_hash
from .nostr.event import NostrEvent from .nostr.event import NostrEvent
######################################## NOSTR ########################################
class Nostrable:
@abstractmethod
def to_nostr_event(self, pubkey: str) -> NostrEvent:
pass
@abstractmethod
def to_nostr_delete_event(self, pubkey: str) -> NostrEvent:
pass
######################################## MERCHANT ######################################## ######################################## MERCHANT ########################################
class MerchantConfig(BaseModel): class MerchantConfig(BaseModel):
@ -77,7 +90,7 @@ class PartialStall(BaseModel):
) )
class Stall(PartialStall): class Stall(PartialStall, Nostrable):
id: str id: str
def to_nostr_event(self, pubkey: str) -> NostrEvent: def to_nostr_event(self, pubkey: str) -> NostrEvent:
@ -90,7 +103,7 @@ class Stall(PartialStall):
event = NostrEvent( event = NostrEvent(
pubkey=pubkey, pubkey=pubkey,
created_at=round(time.time()), created_at=round(time.time()),
kind=30005, kind=30017,
tags=[["d", self.id]], tags=[["d", self.id]],
content=json.dumps(content, separators=(",", ":"), ensure_ascii=False), content=json.dumps(content, separators=(",", ":"), ensure_ascii=False),
) )
@ -121,14 +134,20 @@ class Stall(PartialStall):
######################################## STALLS ######################################## ######################################## STALLS ########################################
class ProductConfig(BaseModel):
event_id: Optional[str]
description: Optional[str]
currency: Optional[str]
class PartialProduct(BaseModel): class PartialProduct(BaseModel):
stall_id: str stall_id: str
name: str name: str
categories: List[str] = [] categories: List[str] = []
description: Optional[str]
image: Optional[str] image: Optional[str]
price: float price: float
quantity: int quantity: int
config: ProductConfig = ProductConfig()
def validate_product(self): def validate_product(self):
if self.image: if self.image:
@ -150,15 +169,16 @@ class PartialProduct(BaseModel):
) )
class Product(PartialProduct): class Product(PartialProduct, Nostrable):
id: str id: str
def to_nostr_event(self, pubkey: str) -> NostrEvent: def to_nostr_event(self, pubkey: str) -> NostrEvent:
content = { content = {
"stall_id": self.stall_id, "stall_id": self.stall_id,
"name": self.name, "name": self.name,
"description": self.description, "description": self.config.description,
"image": self.image, "image": self.image,
"currency": self.config.currency,
"price": self.price, "price": self.price,
"quantity": self.quantity, "quantity": self.quantity,
} }
@ -167,7 +187,7 @@ class Product(PartialProduct):
event = NostrEvent( event = NostrEvent(
pubkey=pubkey, pubkey=pubkey,
created_at=round(time.time()), created_at=round(time.time()),
kind=30005, kind=30018,
tags=[["d", self.id]] + categories, tags=[["d", self.id]] + categories,
content=json.dumps(content, separators=(",", ":"), ensure_ascii=False), content=json.dumps(content, separators=(",", ":"), ensure_ascii=False),
) )
@ -175,8 +195,21 @@ class Product(PartialProduct):
return event return event
def to_nostr_delete_event(self, pubkey: str) -> NostrEvent:
delete_event = NostrEvent(
pubkey=pubkey,
created_at=round(time.time()),
kind=5,
tags=[["e", self.config.event_id]],
content=f"Product '{self.name}' deleted",
)
delete_event.id = delete_event.event_id
return delete_event
@classmethod @classmethod
def from_row(cls, row: Row) -> "Product": def from_row(cls, row: Row) -> "Product":
product = cls(**dict(row)) product = cls(**dict(row))
product.config = ProductConfig(**json.loads(row["meta"]))
product.categories = json.loads(row["category_list"]) product.categories = json.loads(row["category_list"])
return product return product

View file

@ -10,7 +10,7 @@ from .event import NostrEvent
async def publish_nostr_event(e: NostrEvent): async def publish_nostr_event(e: NostrEvent):
url = url_for("/nostrclient/api/v1/publish", external=True) url = url_for("/nostrclient/api/v1/publish", external=True)
data = dict(e) data = dict(e)
print("### published", dict(data)) # print("### published", dict(data))
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
try: try:
await client.post( await client.post(

View file

@ -7,6 +7,20 @@
<q-tab-panels v-model="tab"> <q-tab-panels v-model="tab">
<q-tab-panel name="info"> <q-tab-panel name="info">
<div v-if="stall"> <div v-if="stall">
<div class="row items-center no-wrap q-mb-md">
<div class="col-3 q-pr-lg">ID:</div>
<div class="col-6 col-sm-8 q-pr-lg">
<q-input
filled
dense
readonly
disabled
v-model.trim="stall.id"
type="text"
></q-input>
</div>
<div class="col-3 col-sm-1"></div>
</div>
<div class="row items-center no-wrap q-mb-md"> <div class="row items-center no-wrap q-mb-md">
<div class="col-3 q-pr-lg">Name:</div> <div class="col-3 q-pr-lg">Name:</div>
<div class="col-6 col-sm-8 q-pr-lg"> <div class="col-6 col-sm-8 q-pr-lg">
@ -161,7 +175,7 @@
</div> </div>
</q-td> </q-td>
<q-td key="description" :props="props"> <q-td key="description" :props="props">
{{props.row.description}} {{props.row.config.description}}
</q-td> </q-td>
</q-tr> </q-tr>
</template> </template>
@ -187,7 +201,7 @@
<q-input <q-input
filled filled
dense dense
v-model.trim="productDialog.data.description" v-model.trim="productDialog.data.config.description"
label="Description" label="Description"
></q-input> ></q-input>
<q-select <q-select

View file

@ -26,11 +26,14 @@ async function stallDetails(path) {
data: { data: {
id: null, id: null,
name: '', name: '',
description: '',
categories: [], categories: [],
image: null, image: null,
price: 0, price: 0,
quantity: 0
quantity: 0,
config: {
description: ''
}
} }
}, },
productsFilter: '', productsFilter: '',
@ -190,7 +193,7 @@ async function stallDetails(path) {
try { try {
const {data} = await LNbits.api.request( const {data} = await LNbits.api.request(
'GET', 'GET',
'/nostrmarket/api/v1/product/' + this.stall.id, '/nostrmarket/api/v1/stall/product/' + this.stall.id,
this.inkey this.inkey
) )
this.products = data this.products = data
@ -205,12 +208,12 @@ async function stallDetails(path) {
stall_id: this.stall.id, stall_id: this.stall.id,
id: this.productDialog.data.id, id: this.productDialog.data.id,
name: this.productDialog.data.name, name: this.productDialog.data.name,
description: this.productDialog.data.description,
categories: this.productDialog.data.categories,
image: this.productDialog.data.image, image: this.productDialog.data.image,
price: this.productDialog.data.price, price: this.productDialog.data.price,
quantity: this.productDialog.data.quantity quantity: this.productDialog.data.quantity,
categories: this.productDialog.data.categories,
config: this.productDialog.data.config
} }
this.productDialog.showDialog = false this.productDialog.showDialog = false
if (this.productDialog.data.id) { if (this.productDialog.data.id) {
@ -296,7 +299,10 @@ async function stallDetails(path) {
categories: [], categories: [],
image: null, image: null,
price: 0, price: 0,
quantity: 0 quantity: 0,
config: {
description: ''
}
} }
this.productDialog.showDialog = true this.productDialog.showDialog = true
} }

View file

@ -12,6 +12,7 @@ from lnbits.decorators import (
require_admin_key, require_admin_key,
require_invoice_key, require_invoice_key,
) )
from lnbits.extensions.nostrmarket.nostr.event import NostrEvent
from lnbits.utils.exchange_rates import currencies from lnbits.utils.exchange_rates import currencies
from . import nostrmarket_ext from . import nostrmarket_ext
@ -24,6 +25,7 @@ from .crud import (
delete_stall, delete_stall,
delete_zone, delete_zone,
get_merchant_for_user, get_merchant_for_user,
get_product,
get_products, get_products,
get_stall, get_stall,
get_stalls, get_stalls,
@ -35,6 +37,7 @@ from .crud import (
) )
from .models import ( from .models import (
Merchant, Merchant,
Nostrable,
PartialMerchant, PartialMerchant,
PartialProduct, PartialProduct,
PartialStall, PartialStall,
@ -169,15 +172,9 @@ async def api_create_stall(
try: try:
data.validate_stall() data.validate_stall()
print("### stall", json.dumps(data.dict()))
merchant = await get_merchant_for_user(wallet.wallet.user)
assert merchant, "Cannot find merchat for stall"
stall = await create_stall(wallet.wallet.user, data=data) stall = await create_stall(wallet.wallet.user, data=data)
event = stall.to_nostr_event(merchant.public_key) event = await sign_and_send_to_nostr(wallet.wallet.user, stall)
event.sig = merchant.sign_hash(bytes.fromhex(event.id))
await publish_nostr_event(event)
stall.config.event_id = event.id stall.config.event_id = event.id
await update_stall(wallet.wallet.user, stall) await update_stall(wallet.wallet.user, stall)
@ -204,18 +201,13 @@ async def api_update_stall(
try: try:
data.validate_stall() data.validate_stall()
merchant = await get_merchant_for_user(wallet.wallet.user)
assert merchant, "Cannot find merchat for stall"
event = data.to_nostr_event(merchant.public_key)
event.sig = merchant.sign_hash(bytes.fromhex(event.id))
data.config.event_id = event.id
# data.config.event_created_at =
stall = await update_stall(wallet.wallet.user, data) stall = await update_stall(wallet.wallet.user, data)
assert stall, "Cannot update stall" assert stall, "Cannot update stall"
await publish_nostr_event(event) event = await sign_and_send_to_nostr(wallet.wallet.user, stall)
stall.config.event_id = event.id
await update_stall(wallet.wallet.user, stall)
return stall return stall
except HTTPException as ex: except HTTPException as ex:
@ -266,6 +258,22 @@ async def api_get_stalls(wallet: WalletTypeInfo = Depends(get_key_type)):
) )
@nostrmarket_ext.get("/api/v1/stall/product/{stall_id}")
async def api_get_stall_products(
stall_id: str,
wallet: WalletTypeInfo = Depends(require_invoice_key),
):
try:
products = await get_products(wallet.wallet.user, stall_id)
return products
except Exception as ex:
logger.warning(ex)
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail="Cannot get stall products",
)
@nostrmarket_ext.delete("/api/v1/stall/{stall_id}") @nostrmarket_ext.delete("/api/v1/stall/{stall_id}")
async def api_delete_stall( async def api_delete_stall(
stall_id: str, wallet: WalletTypeInfo = Depends(require_admin_key) stall_id: str, wallet: WalletTypeInfo = Depends(require_admin_key)
@ -278,15 +286,12 @@ async def api_delete_stall(
detail="Stall does not exist.", detail="Stall does not exist.",
) )
merchant = await get_merchant_for_user(wallet.wallet.user)
assert merchant, "Cannot find merchat for stall"
await delete_stall(wallet.wallet.user, stall_id) await delete_stall(wallet.wallet.user, stall_id)
delete_event = stall.to_nostr_delete_event(merchant.public_key) event = await sign_and_send_to_nostr(wallet.wallet.user, stall, True)
delete_event.sig = merchant.sign_hash(bytes.fromhex(delete_event.id))
await publish_nostr_event(delete_event) stall.config.event_id = event.id
await update_stall(wallet.wallet.user, stall)
except HTTPException as ex: except HTTPException as ex:
raise ex raise ex
@ -308,8 +313,18 @@ async def api_create_product(
) -> Product: ) -> Product:
try: try:
data.validate_product() data.validate_product()
stall = await get_stall(wallet.wallet.user, data.stall_id)
assert stall, "Stall missing for product"
data.config.currency = stall.currency
product = await create_product(wallet.wallet.user, data=data) product = await create_product(wallet.wallet.user, data=data)
event = await sign_and_send_to_nostr(wallet.wallet.user, product)
product.config.event_id = event.id
await update_product(wallet.wallet.user, product)
return product return product
except ValueError as ex: except ValueError as ex:
raise HTTPException( raise HTTPException(
@ -331,9 +346,22 @@ async def api_update_product(
wallet: WalletTypeInfo = Depends(require_admin_key), wallet: WalletTypeInfo = Depends(require_admin_key),
) -> Product: ) -> Product:
try: try:
if product_id != product.id:
raise ValueError("Bad product ID")
product.validate_product() product.validate_product()
stall = await get_stall(wallet.wallet.user, product.stall_id)
assert stall, "Stall missing for product"
product.config.currency = stall.currency
product = await update_product(wallet.wallet.user, product) product = await update_product(wallet.wallet.user, product)
event = await sign_and_send_to_nostr(wallet.wallet.user, product)
product.config.event_id = event.id
await update_product(wallet.wallet.user, product)
return product return product
except ValueError as ex: except ValueError as ex:
raise HTTPException( raise HTTPException(
@ -348,13 +376,13 @@ async def api_update_product(
) )
@nostrmarket_ext.get("/api/v1/product/{stall_id}") @nostrmarket_ext.get("/api/v1/product/{product_id}")
async def api_get_product( async def api_get_product(
stall_id: str, product_id: str,
wallet: WalletTypeInfo = Depends(require_invoice_key), wallet: WalletTypeInfo = Depends(require_invoice_key),
): ) -> Optional[Product]:
try: try:
products = await get_products(wallet.wallet.user, stall_id) products = await get_product(wallet.wallet.user, product_id)
return products return products
except Exception as ex: except Exception as ex:
logger.warning(ex) logger.warning(ex)
@ -370,7 +398,18 @@ async def api_delete_product(
wallet: WalletTypeInfo = Depends(require_admin_key), wallet: WalletTypeInfo = Depends(require_admin_key),
): ):
try: try:
product = await get_product(wallet.wallet.user, product_id)
if not product:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Product does not exist.",
)
await delete_product(wallet.wallet.user, product_id) await delete_product(wallet.wallet.user, product_id)
await sign_and_send_to_nostr(wallet.wallet.user, product, True)
except HTTPException as ex:
raise ex
except Exception as ex: except Exception as ex:
logger.warning(ex) logger.warning(ex)
raise HTTPException( raise HTTPException(
@ -385,3 +424,23 @@ async def api_delete_product(
@nostrmarket_ext.get("/api/v1/currencies") @nostrmarket_ext.get("/api/v1/currencies")
async def api_list_currencies_available(): async def api_list_currencies_available():
return list(currencies.keys()) return list(currencies.keys())
######################################## HELPERS ########################################
async def sign_and_send_to_nostr(
user_id: str, n: Nostrable, delete=False
) -> NostrEvent:
merchant = await get_merchant_for_user(user_id)
assert merchant, "Cannot find merchant!"
event = (
n.to_nostr_delete_event(merchant.public_key)
if delete
else n.to_nostr_event(merchant.public_key)
)
event.sig = merchant.sign_hash(bytes.fromhex(event.id))
await publish_nostr_event(event)
return event