add currency option

This commit is contained in:
Tiago Vasconcelos 2022-12-22 18:26:34 +00:00
parent c412371ee6
commit b1473fc1a4
5 changed files with 122 additions and 2 deletions

View file

@ -9,6 +9,7 @@ from lnbits.settings import WALLET
from . import db from . import db
from .models import ( from .models import (
ShopSettings,
ChatMessage, ChatMessage,
CreateChatMessage, CreateChatMessage,
CreateMarket, CreateMarket,
@ -443,3 +444,24 @@ async def get_shop_chat_by_merchant(ids: List[str]) -> List[ChatMessage]:
(*ids,), (*ids,),
) )
return [ChatMessage(**row) for row in rows] return [ChatMessage(**row) for row in rows]
async def get_shop_settings(user) -> Optional[ShopSettings]:
row = await db.fetchone("SELECT * FROM shop.settings WHERE 'user = ?", (user,))
return ShopSettings(**row) if row else None
async def set_shop_settings(user: str, data) -> Optional[ShopSettings]:
await db.execute(
f"""
UPDATE shop.settings
SET currency = ?, fiat_base_multiplier = ?
WHERE 'user' = ?;
""",
(
data.currency,
data.fiat_base_multiplier,
user,
),
)

View file

@ -1,4 +1,17 @@
async def m001_initial(db): async def m001_initial(db):
"""
Initial Shop settings table.
"""
await db.execute(
"""
CREATE TABLE shop.settings (
"user" TEXT PRIMARY KEY,
currency TEXT DEFAULT 'sat',
fiat_base_multiplier INTEGER DEFAULT 1
);
"""
)
""" """
Initial stalls table. Initial stalls table.
""" """

View file

@ -4,6 +4,17 @@ from fastapi.param_functions import Query
from pydantic import BaseModel from pydantic import BaseModel
class ShopSettings(BaseModel):
user: str
currency: str
fiat_base_multiplier: int
class SetSettings(BaseModel):
currency: str
fiat_base_multiplier: int = Query(100, ge=1)
class Stalls(BaseModel): class Stalls(BaseModel):
id: str id: str
wallet: str wallet: str

View file

@ -4,7 +4,7 @@
{% include "shop/_dialogs.html" %} {% include "shop/_dialogs.html" %}
<div class="col-12 col-md-8 col-lg-7 q-gutter-y-md"> <div class="col-12 col-md-8 col-lg-7 q-gutter-y-md">
<q-card> <q-card>
<q-card-section> <q-card-section class="q-gutter-sm row">
<q-btn unelevated color="primary" @click="zoneDialog.show = true" <q-btn unelevated color="primary" @click="zoneDialog.show = true"
>+ Shipping Zone<q-tooltip> Create a shipping zone </q-tooltip></q-btn >+ Shipping Zone<q-tooltip> Create a shipping zone </q-tooltip></q-btn
> >
@ -42,8 +42,18 @@
@click="errorMessage('First set shipping zone(s), then create a stall.')" @click="errorMessage('First set shipping zone(s), then create a stall.')"
>+ Product <q-tooltip> List a product </q-tooltip></q-btn >+ Product <q-tooltip> List a product </q-tooltip></q-btn
> >
<q-select
style="width: 100px"
filled
dense
v-model="currencies.unit"
type="text"
label="Unit"
:options="currencies.units"
@input="(value) => setCurrency(value)"
></q-select>
<q-btn <q-btn
class="float-right" class="q-ml-auto"
unelevated unelevated
flat flat
color="primary" color="primary"
@ -237,6 +247,10 @@
}, },
keys: null, keys: null,
diagonAlley: false, diagonAlley: false,
currencies: {
units: ['sat'],
unit: 'sat'
},
products: [], products: [],
orders: [], orders: [],
stalls: [], stalls: [],
@ -523,6 +537,29 @@
toggleDA(value, evt) { toggleDA(value, evt) {
this.$q.localStorage.set(`lnbits.DAmode`, value) this.$q.localStorage.set(`lnbits.DAmode`, value)
}, },
setCurrency(v) {
let data = {
currency: v,
fiat_base_multiplier: this.currencies.unit != 'sat' ? 100 : 1
}
LNbits.api
.request(
'PUT',
'/shop/api/v1/settings',
this.g.user.wallets[0].adminkey,
data
)
.then(response => {
this.$q.notify({
type: 'positive',
message: `Currency changed`,
icon: 'check'
})
})
.catch(error => {
LNbits.utils.notifyApiError(error)
})
},
shopDataDownload() { shopDataDownload() {
const removeClone = obj => { const removeClone = obj => {
delete obj._data delete obj._data
@ -1320,6 +1357,16 @@
} }
this.ws = ws this.ws = ws
},
async getCurrencies() {
await LNbits.api
.request('GET', '/shop/api/v1/currencies')
.then(response => {
this.currencies.units = ['sat', ...response.data]
})
.catch(err => {
LNbits.utils.notifyApiError(err)
})
} }
}, },
async created() { async created() {
@ -1329,6 +1376,7 @@
this.onboarding.showAgain = showOnboard || false this.onboarding.showAgain = showOnboard || false
this.diagonAlley = this.diagonAlley =
this.$q.localStorage.getItem('lnbits.DAmode') || false this.$q.localStorage.getItem('lnbits.DAmode') || false
await this.getCurrencies()
this.getStalls() this.getStalls()
this.getProducts() this.getProducts()
this.getZones() this.getZones()

View file

@ -9,6 +9,7 @@ from fastapi.params import Depends
from loguru import logger from loguru import logger
from secp256k1 import PrivateKey, PublicKey from secp256k1 import PrivateKey, PublicKey
from starlette.exceptions import HTTPException from starlette.exceptions import HTTPException
from lnbits.utils.exchange_rates import currencies, get_fiat_rate_satoshis
from lnbits.core.crud import get_user from lnbits.core.crud import get_user
from lnbits.core.services import create_invoice from lnbits.core.services import create_invoice
@ -23,6 +24,8 @@ from lnbits.helpers import urlsafe_short_hash
from . import db, shop_ext from . import db, shop_ext
from .crud import ( from .crud import (
set_shop_settings,
get_shop_settings,
create_shop_market, create_shop_market,
create_shop_market_stalls, create_shop_market_stalls,
create_shop_order, create_shop_order,
@ -58,6 +61,7 @@ from .crud import (
update_shop_zone, update_shop_zone,
) )
from .models import ( from .models import (
SetSettings,
CreateMarket, CreateMarket,
Orders, Orders,
Products, Products,
@ -452,3 +456,25 @@ async def api_get_latest_chat_msg(room_name: str, all_messages: bool = Query(Fal
messages = await get_shop_latest_chat_messages(room_name) messages = await get_shop_latest_chat_messages(room_name)
return messages return messages
@shop_ext.get("/api/v1/currencies")
async def api_list_currencies_available():
return list(currencies.keys())
@shop_ext.get("/api/v1/settings")
async def api_get_settings(wallet: WalletTypeInfo = Depends(require_admin_key)):
user = wallet.wallet.user
settings = await get_shop_settings(user)
return settings
@shop_ext.put("/api/v1/settings")
async def api_set_settings(
data: SetSettings, wallet: WalletTypeInfo = Depends(require_admin_key)
):
user = wallet.wallet.user
return await set_shop_settings(user, data)