From 260bea9ccf463d6af383d3782ba245f9d722a5ac Mon Sep 17 00:00:00 2001 From: Vlad Stan Date: Thu, 23 Mar 2023 09:47:40 +0200 Subject: [PATCH 1/6] fix: clear merchant screen on delete --- static/js/index.js | 6 ++++++ templates/nostrmarket/index.html | 1 + 2 files changed, 7 insertions(+) diff --git a/static/js/index.js b/static/js/index.js index 75e6f01..12c354e 100644 --- a/static/js/index.js +++ b/static/js/index.js @@ -59,6 +59,12 @@ const merchant = async () => { toggleMerchantKeys: function (value) { this.showKeys = value }, + handleMerchantDeleted: function() { + this.merchant = null + this.shippingZones = [] + this.activeChatCustomer = '' + this.showKeys = false + }, createMerchant: async function (privateKey) { try { const pubkey = nostr.getPublicKey(privateKey) diff --git a/templates/nostrmarket/index.html b/templates/nostrmarket/index.html index 1d89485..94aa403 100644 --- a/templates/nostrmarket/index.html +++ b/templates/nostrmarket/index.html @@ -12,6 +12,7 @@ :inkey="g.user.wallets[0].inkey" :adminkey="g.user.wallets[0].adminkey" @show-keys="toggleMerchantKeys" + @merchant-deleted="handleMerchantDeleted" >
From 05ecc65e5a5959f07875b7d8c788209753507c80 Mon Sep 17 00:00:00 2001 From: Vlad Stan Date: Thu, 23 Mar 2023 11:14:34 +0200 Subject: [PATCH 2/6] feat: allow delete merchant from `nostr` --- crud.py | 14 ++++++ models.py | 46 ++++++++++++++++++- .../customer-stall/customer-stall.js | 5 +- .../merchant-details/merchant-details.html | 14 ++++-- .../merchant-details/merchant-details.js | 28 ++++++++++- static/js/index.js | 2 +- views_api.py | 43 ++++++++++++++++- 7 files changed, 141 insertions(+), 11 deletions(-) diff --git a/crud.py b/crud.py index a939f52..2029a2e 100644 --- a/crud.py +++ b/crud.py @@ -7,6 +7,7 @@ from . import db from .models import ( DirectMessage, Merchant, + MerchantConfig, Order, PartialDirectMessage, PartialMerchant, @@ -35,6 +36,19 @@ async def create_merchant(user_id: str, m: PartialMerchant) -> Merchant: return merchant +async def update_merchant( + user_id: str, merchant_id: str, config: MerchantConfig +) -> Optional[Merchant]: + await db.execute( + f""" + UPDATE nostrmarket.merchants SET meta = ? + WHERE id = ? AND user_id = ? + """, + (json.dumps(config.dict()), merchant_id, user_id), + ) + return await get_merchant(user_id, merchant_id) + + async def get_merchant(user_id: str, merchant_id: str) -> Optional[Merchant]: row = await db.fetchone( """SELECT * FROM nostrmarket.merchants WHERE user_id = ? AND id = ?""", diff --git a/models.py b/models.py index 379d3f8..9c82306 100644 --- a/models.py +++ b/models.py @@ -30,8 +30,16 @@ class Nostrable: ######################################## MERCHANT ######################################## -class MerchantConfig(BaseModel): + + +class MerchantProfile(BaseModel): name: Optional[str] + about: Optional[str] + picture: Optional[str] + + +class MerchantConfig(MerchantProfile): + event_id: Optional[str] class PartialMerchant(BaseModel): @@ -40,7 +48,7 @@ class PartialMerchant(BaseModel): config: MerchantConfig = MerchantConfig() -class Merchant(PartialMerchant): +class Merchant(PartialMerchant, Nostrable): id: str def sign_hash(self, hash: bytes) -> str: @@ -74,6 +82,40 @@ class Merchant(PartialMerchant): merchant.config = MerchantConfig(**json.loads(row["meta"])) return merchant + def to_nostr_event(self, pubkey: str) -> NostrEvent: + content = { + "name": self.config.name, + "about": self.config.about, + "picture": self.config.picture, + } + event = NostrEvent( + pubkey=pubkey, + created_at=round(time.time()), + kind=0, + tags=[], + content=json.dumps(content, separators=(",", ":"), ensure_ascii=False), + ) + event.id = event.event_id + + return event + + def to_nostr_delete_event(self, pubkey: str) -> NostrEvent: + content = { + "name": f"{self.config.name} (deleted)", + "about": "Merchant Deleted", + "picture": "", + } + delete_event = NostrEvent( + pubkey=pubkey, + created_at=round(time.time()), + kind=0, + tags=[], + content=json.dumps(content, separators=(",", ":"), ensure_ascii=False), + ) + delete_event.id = delete_event.event_id + + return delete_event + ######################################## ZONES ######################################## class PartialZone(BaseModel): diff --git a/static/components/customer-stall/customer-stall.js b/static/components/customer-stall/customer-stall.js index 2b4090d..f9e82ea 100644 --- a/static/components/customer-stall/customer-stall.js +++ b/static/components/customer-stall/customer-stall.js @@ -354,8 +354,9 @@ async function customerStall(path) { this.qrCodeDialog.data.message = json.message return cb() } - let payment_request = json.payment_options.find(o => o.type == 'ln') - .link + 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 diff --git a/static/components/merchant-details/merchant-details.html b/static/components/merchant-details/merchant-details.html index 0d8e1ec..2485447 100644 --- a/static/components/merchant-details/merchant-details.html +++ b/static/components/merchant-details/merchant-details.html @@ -24,11 +24,19 @@ > - + - Delete Merchant + Delete Merchant from DB Delete all stalls, products and ordersDelete all stalls, products and orders from database + + + + + Delete Merchant from Nostr + Delete all stalls, products and orders from Nostr diff --git a/static/components/merchant-details/merchant-details.js b/static/components/merchant-details/merchant-details.js index 1327ba5..297ce36 100644 --- a/static/components/merchant-details/merchant-details.js +++ b/static/components/merchant-details/merchant-details.js @@ -15,7 +15,7 @@ async function merchantDetails(path) { this.showKeys = !this.showKeys this.$emit('show-keys', this.showKeys) }, - deleteMerchant: function () { + deleteMerchantTables: function () { LNbits.utils .confirmDialog( ` @@ -30,7 +30,6 @@ async function merchantDetails(path) { '/nostrmarket/api/v1/merchant/' + this.merchantId, this.adminkey ) - // todo: refresh parent page this.$emit('merchant-deleted', this.merchantId) this.$q.notify({ type: 'positive', @@ -42,6 +41,31 @@ async function merchantDetails(path) { LNbits.utils.notifyApiError(error) } }) + }, + deleteMerchantFromNostr: function () { + LNbits.utils + .confirmDialog( + ` + Do you want to remove the merchant from Nostr? + ` + ) + .onOk(async () => { + try { + await LNbits.api.request( + 'DELETE', + `/nostrmarket/api/v1/merchant/${this.merchantId}/nostr`, + this.adminkey + ) + this.$q.notify({ + type: 'positive', + message: 'Merchant Deleted from Nostr', + timeout: 5000 + }) + } catch (error) { + console.warn(error) + LNbits.utils.notifyApiError(error) + } + }) } }, created: async function () {} diff --git a/static/js/index.js b/static/js/index.js index 12c354e..58b2c5c 100644 --- a/static/js/index.js +++ b/static/js/index.js @@ -59,7 +59,7 @@ const merchant = async () => { toggleMerchantKeys: function (value) { this.showKeys = value }, - handleMerchantDeleted: function() { + handleMerchantDeleted: function () { this.merchant = null this.shippingZones = [] this.activeChatCustomer = '' diff --git a/views_api.py b/views_api.py index cefac0a..df436aa 100644 --- a/views_api.py +++ b/views_api.py @@ -45,6 +45,7 @@ from .crud import ( get_stalls, get_zone, get_zones, + update_merchant, update_order_shipped_status, update_product, update_stall, @@ -147,6 +148,44 @@ async def api_delete_merchant( ) +@nostrmarket_ext.delete("/api/v1/merchant/{merchant_id}/nostr") +async def api_delete_merchant( + merchant_id: str, + wallet: WalletTypeInfo = Depends(require_admin_key), +): + + try: + merchant = await get_merchant_for_user(wallet.wallet.user) + assert merchant, "Merchant cannot be found" + assert merchant.id == merchant_id, "Wrong merchant ID" + + stalls = await get_stalls(merchant.id) + for stall in stalls: + products = await get_products(merchant.id, stall.id) + for product in products: + event = await sign_and_send_to_nostr(merchant, product, True) + product.config.event_id = event.id + await update_product(merchant.id, product) + event = await sign_and_send_to_nostr(merchant, stall, True) + stall.config.event_id = event.id + await update_stall(merchant.id, stall) + event = await sign_and_send_to_nostr(merchant, merchant, True) + merchant.config.event_id = event.id + await update_merchant(wallet.wallet.user, merchant.id, merchant.config) + + except AssertionError as ex: + raise HTTPException( + status_code=HTTPStatus.BAD_REQUEST, + detail=str(ex), + ) + except Exception as ex: + logger.warning(ex) + raise HTTPException( + status_code=HTTPStatus.INTERNAL_SERVER_ERROR, + detail="Cannot get merchant", + ) + + ######################################## ZONES ######################################## @@ -566,7 +605,9 @@ async def api_delete_product( ) await delete_product(merchant.id, product_id) - await sign_and_send_to_nostr(merchant, product, True) + event = await sign_and_send_to_nostr(merchant, product, True) + product.config.event_id = event.id + await update_product(merchant.id, product) except AssertionError as ex: raise HTTPException( From ccb32dba99a61945a3578d57c333f6533d9d5f8a Mon Sep 17 00:00:00 2001 From: Vlad Stan Date: Thu, 23 Mar 2023 14:33:05 +0200 Subject: [PATCH 3/6] feat: part: republish to nostr --- .../merchant-details/merchant-details.html | 12 +++++++-- .../merchant-details/merchant-details.js | 25 +++++++++++++++++++ views_api.py | 1 - 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/static/components/merchant-details/merchant-details.html b/static/components/merchant-details/merchant-details.html index 2485447..802a31f 100644 --- a/static/components/merchant-details/merchant-details.html +++ b/static/components/merchant-details/merchant-details.html @@ -24,9 +24,17 @@ > + + + Republish to Nostr + Republish all stalls, products and orders to Nostr + + - Delete Merchant from DB + Delete from DB Delete all stalls, products and orders from database @@ -34,7 +42,7 @@ - Delete Merchant from Nostr + Delete from Nostr Delete all stalls, products and orders from Nostr diff --git a/static/components/merchant-details/merchant-details.js b/static/components/merchant-details/merchant-details.js index 297ce36..d190249 100644 --- a/static/components/merchant-details/merchant-details.js +++ b/static/components/merchant-details/merchant-details.js @@ -15,6 +15,31 @@ async function merchantDetails(path) { this.showKeys = !this.showKeys this.$emit('show-keys', this.showKeys) }, + + republishMerchantData: function () { + LNbits.utils + .confirmDialog( + `You are about to republish to Nostr` + ) + .onOk(async () => { + try { + await LNbits.api.request( + 'PATCH', + `/nostrmarket/api/v1/merchant/${this.merchantId}/nostr`, + this.adminkey + ) + this.$emit('merchant-deleted', this.merchantId) + this.$q.notify({ + type: 'positive', + message: 'Merchant Deleted', + timeout: 5000 + }) + } catch (error) { + console.warn(error) + LNbits.utils.notifyApiError(error) + } + }) + }, deleteMerchantTables: function () { LNbits.utils .confirmDialog( diff --git a/views_api.py b/views_api.py index df436aa..2e209df 100644 --- a/views_api.py +++ b/views_api.py @@ -153,7 +153,6 @@ async def api_delete_merchant( merchant_id: str, wallet: WalletTypeInfo = Depends(require_admin_key), ): - try: merchant = await get_merchant_for_user(wallet.wallet.user) assert merchant, "Merchant cannot be found" From 5694c4112f7e6cbd6ce973ebe26e15b83eb7fc79 Mon Sep 17 00:00:00 2001 From: Vlad Stan Date: Thu, 23 Mar 2023 15:41:43 +0200 Subject: [PATCH 4/6] feat: send `id` in event content --- models.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/models.py b/models.py index 9c82306..355128a 100644 --- a/models.py +++ b/models.py @@ -166,6 +166,7 @@ class Stall(PartialStall, Nostrable): def to_nostr_event(self, pubkey: str) -> NostrEvent: content = { + "id": self.id, "name": self.name, "description": self.config.description, "currency": self.currency, @@ -245,6 +246,7 @@ class Product(PartialProduct, Nostrable): def to_nostr_event(self, pubkey: str) -> NostrEvent: content = { + "id": self.id, "stall_id": self.stall_id, "name": self.name, "description": self.config.description, From 13150f6360276d0f6ea648a8432a51acbdfe059f Mon Sep 17 00:00:00 2001 From: Vlad Stan Date: Fri, 24 Mar 2023 14:52:34 +0200 Subject: [PATCH 5/6] feat: republish to nostr --- services.py | 21 ++++++++++ .../merchant-details/merchant-details.html | 2 +- .../merchant-details/merchant-details.js | 37 +++++++---------- views_api.py | 41 +++++++++++++------ 4 files changed, 65 insertions(+), 36 deletions(-) diff --git a/services.py b/services.py index 2bf3f01..63e715a 100644 --- a/services.py +++ b/services.py @@ -12,11 +12,14 @@ from .crud import ( get_merchant_by_pubkey, get_order, get_order_by_event_id, + get_products, get_products_by_ids, + get_stalls, get_wallet_for_product, update_order_paid_status, update_product, update_product_quantity, + update_stall, ) from .helpers import order_from_json from .models import ( @@ -88,6 +91,24 @@ async def create_new_order( ) +async def update_merchant_to_nostr( + merchant: Merchant, delete_merchant=False +) -> Merchant: + stalls = await get_stalls(merchant.id) + for stall in stalls: + products = await get_products(merchant.id, stall.id) + for product in products: + event = await sign_and_send_to_nostr(merchant, product, delete_merchant) + product.config.event_id = event.id + await update_product(merchant.id, product) + event = await sign_and_send_to_nostr(merchant, stall, delete_merchant) + stall.config.event_id = event.id + await update_stall(merchant.id, stall) + event = await sign_and_send_to_nostr(merchant, merchant, delete_merchant) + merchant.config.event_id = event.id + return merchant + + async def sign_and_send_to_nostr( merchant: Merchant, n: Nostrable, delete=False ) -> NostrEvent: diff --git a/static/components/merchant-details/merchant-details.html b/static/components/merchant-details/merchant-details.html index 802a31f..cc76cd6 100644 --- a/static/components/merchant-details/merchant-details.html +++ b/static/components/merchant-details/merchant-details.html @@ -24,7 +24,7 @@ > - + Republish to Nostr { - try { - await LNbits.api.request( - 'PATCH', - `/nostrmarket/api/v1/merchant/${this.merchantId}/nostr`, - this.adminkey - ) - this.$emit('merchant-deleted', this.merchantId) - this.$q.notify({ - type: 'positive', - message: 'Merchant Deleted', - timeout: 5000 - }) - } catch (error) { - console.warn(error) - LNbits.utils.notifyApiError(error) - } + this.$q.notify({ + type: 'positive', + message: 'Merchant data republished to Nostr', + timeout: 5000 }) + } catch (error) { + console.warn(error) + LNbits.utils.notifyApiError(error) + } }, deleteMerchantTables: function () { LNbits.utils diff --git a/views_api.py b/views_api.py index 2e209df..e7bc07c 100644 --- a/views_api.py +++ b/views_api.py @@ -65,7 +65,7 @@ from .models import ( Stall, Zone, ) -from .services import sign_and_send_to_nostr +from .services import sign_and_send_to_nostr, update_merchant_to_nostr ######################################## MERCHANT ######################################## @@ -148,6 +148,32 @@ async def api_delete_merchant( ) +@nostrmarket_ext.put("/api/v1/merchant/{merchant_id}/nostr") +async def api_republish_merchant( + merchant_id: str, + wallet: WalletTypeInfo = Depends(require_admin_key), +): + try: + merchant = await get_merchant_for_user(wallet.wallet.user) + assert merchant, "Merchant cannot be found" + assert merchant.id == merchant_id, "Wrong merchant ID" + + merchant = await update_merchant_to_nostr(merchant) + await update_merchant(wallet.wallet.user, merchant.id, merchant.config) + + except AssertionError as ex: + raise HTTPException( + status_code=HTTPStatus.BAD_REQUEST, + detail=str(ex), + ) + except Exception as ex: + logger.warning(ex) + raise HTTPException( + status_code=HTTPStatus.INTERNAL_SERVER_ERROR, + detail="Cannot get merchant", + ) + + @nostrmarket_ext.delete("/api/v1/merchant/{merchant_id}/nostr") async def api_delete_merchant( merchant_id: str, @@ -158,18 +184,7 @@ async def api_delete_merchant( assert merchant, "Merchant cannot be found" assert merchant.id == merchant_id, "Wrong merchant ID" - stalls = await get_stalls(merchant.id) - for stall in stalls: - products = await get_products(merchant.id, stall.id) - for product in products: - event = await sign_and_send_to_nostr(merchant, product, True) - product.config.event_id = event.id - await update_product(merchant.id, product) - event = await sign_and_send_to_nostr(merchant, stall, True) - stall.config.event_id = event.id - await update_stall(merchant.id, stall) - event = await sign_and_send_to_nostr(merchant, merchant, True) - merchant.config.event_id = event.id + merchant = await update_merchant_to_nostr(merchant, True) await update_merchant(wallet.wallet.user, merchant.id, merchant.config) except AssertionError as ex: From c6bca39df81c28dececa9b75902e632ef91a605c Mon Sep 17 00:00:00 2001 From: Vlad Stan Date: Fri, 24 Mar 2023 15:10:30 +0200 Subject: [PATCH 6/6] feat: stubs for sync from nostr --- models.py | 1 + nostr/nostr_client.py | 15 +++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/models.py b/models.py index 355128a..29d91e9 100644 --- a/models.py +++ b/models.py @@ -40,6 +40,7 @@ class MerchantProfile(BaseModel): class MerchantConfig(MerchantProfile): event_id: Optional[str] + sync_from_nostr = False class PartialMerchant(BaseModel): diff --git a/nostr/nostr_client.py b/nostr/nostr_client.py index 6a29d2c..a2a936c 100644 --- a/nostr/nostr_client.py +++ b/nostr/nostr_client.py @@ -81,10 +81,25 @@ class NostrClient: ["REQ", f"direct-messages-out:{public_key}", out_messages_filter] ) + async def subscribe_to_merchant_events(self, public_key: str, since: int): + stall_filter = {"kind": 30017, "authors": [public_key]} + product_filter = {"kind": 30018, "authors": [public_key]} + + await self.send_req_queue.put( + ["REQ", f"stall-events:{public_key}", stall_filter] + ) + await self.send_req_queue.put( + ["REQ", f"product-events:{public_key}", product_filter] + ) + async def unsubscribe_from_direct_messages(self, public_key: str): await self.send_req_queue.put(["CLOSE", f"direct-messages-in:{public_key}"]) await self.send_req_queue.put(["CLOSE", f"direct-messages-out:{public_key}"]) + async def unsubscribe_from_merchant_events(self, public_key: str): + await self.send_req_queue.put(["CLOSE", f"stall-events:{public_key}"]) + await self.send_req_queue.put(["CLOSE", f"product-events:{public_key}"]) + def stop(self): try: self.ws.close()