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..29d91e9 100644 --- a/models.py +++ b/models.py @@ -30,8 +30,17 @@ 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] + sync_from_nostr = False class PartialMerchant(BaseModel): @@ -40,7 +49,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 +83,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): @@ -124,6 +167,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, @@ -203,6 +247,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, 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() 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/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..cc76cd6 100644 --- a/static/components/merchant-details/merchant-details.html +++ b/static/components/merchant-details/merchant-details.html @@ -24,11 +24,27 @@ > - + - Delete Merchant + Republish to Nostr Delete all stalls, products and ordersRepublish all stalls, products and orders to Nostr + + + + + Delete from DB + Delete all stalls, products and orders from database + + + + + 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 1327ba5..9a63d40 100644 --- a/static/components/merchant-details/merchant-details.js +++ b/static/components/merchant-details/merchant-details.js @@ -15,7 +15,25 @@ async function merchantDetails(path) { this.showKeys = !this.showKeys this.$emit('show-keys', this.showKeys) }, - deleteMerchant: function () { + + republishMerchantData: async function () { + try { + await LNbits.api.request( + 'PUT', + `/nostrmarket/api/v1/merchant/${this.merchantId}/nostr`, + this.adminkey + ) + 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 .confirmDialog( ` @@ -30,7 +48,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 +59,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 75e6f01..58b2c5c 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" >
diff --git a/views_api.py b/views_api.py index cefac0a..e7bc07c 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, @@ -64,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 ######################################## @@ -147,6 +148,58 @@ 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, + 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, True) + 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 +619,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(