Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c3c68bc9da | ||
|
|
95deb47765 | ||
|
|
b25a5cfcf6 | ||
|
|
0e2397a813 | ||
|
|
f363418c05 | ||
|
|
0275b66a89 | ||
|
|
c680fd647d | ||
|
|
cfc9874517 | ||
|
|
62cd151fd6 | ||
|
|
a4d0aa5db8 | ||
|
|
77630781d7 | ||
|
|
59da350cc9 | ||
|
|
5708f0707d | ||
|
|
7ba0bf5e70 | ||
|
|
aeeaed9609 |
@@ -10,15 +10,16 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.head_ref }}
|
||||
ref: ${{ github.event.pull_request.head.repo.full_name == github.repository && github.head_ref || github.event.pull_request.head.sha }}
|
||||
- uses: lnbits/lnbits/.github/actions/prepare@dev
|
||||
with:
|
||||
python-version: "3.10"
|
||||
node-version: "24.x"
|
||||
npm: true
|
||||
- run: make bundle
|
||||
- name: Commit and push bundle changes
|
||||
- name: Build and commit bundle (same-repo PR)
|
||||
if: github.event.pull_request.head.repo.full_name == github.repository
|
||||
run: |
|
||||
make bundle
|
||||
git config user.name "alan"
|
||||
git config user.email "alan@lnbits.com"
|
||||
git add lnbits/static
|
||||
@@ -27,3 +28,6 @@ jobs:
|
||||
fi
|
||||
git commit -m "chore: make bundle [skip ci]"
|
||||
git push
|
||||
- name: Check bundle is up-to-date (fork PR)
|
||||
if: github.event.pull_request.head.repo.full_name != github.repository
|
||||
run: make checkbundle
|
||||
|
||||
@@ -16,6 +16,7 @@ from ..models import (
|
||||
PaymentFilters,
|
||||
PaymentHistoryPoint,
|
||||
PaymentsStatusCount,
|
||||
PaymentTotalBreakdown,
|
||||
PaymentWalletStats,
|
||||
)
|
||||
|
||||
@@ -428,6 +429,44 @@ async def get_payment_count_stats(
|
||||
return data
|
||||
|
||||
|
||||
async def get_wallet_payment_total_breakdown(
|
||||
wallet_id: str,
|
||||
conn: Connection | None = None,
|
||||
) -> list[PaymentTotalBreakdown]:
|
||||
wallet = await get_wallet(wallet_id, conn=conn)
|
||||
if not wallet or not wallet.can_view_payments:
|
||||
return []
|
||||
|
||||
values = {"wallet_id": wallet.source_wallet_id}
|
||||
data = await (conn or db).fetchall(
|
||||
query=f"""
|
||||
SELECT tag,
|
||||
CASE
|
||||
WHEN fiat_provider IS NOT NULL
|
||||
OR checking_id LIKE 'fiat_%'
|
||||
OR extra LIKE '%"fiat_payment_request"%'
|
||||
OR extra LIKE '%"fiat_amount"%'
|
||||
THEN true
|
||||
ELSE false
|
||||
END AS is_fiat,
|
||||
COUNT(*) AS payments_count,
|
||||
SUM(amount - ABS(fee)) AS total
|
||||
FROM apipayments
|
||||
WHERE wallet_id = :wallet_id
|
||||
AND (
|
||||
status = '{PaymentState.SUCCESS}'
|
||||
OR (amount < 0 AND status = '{PaymentState.PENDING}')
|
||||
)
|
||||
GROUP BY tag, is_fiat
|
||||
ORDER BY tag
|
||||
""", # noqa: S608
|
||||
values=values,
|
||||
model=PaymentTotalBreakdown,
|
||||
)
|
||||
|
||||
return data
|
||||
|
||||
|
||||
async def get_daily_stats(
|
||||
filters: Filters[PaymentFilters] | None = None,
|
||||
user_id: str | None = None,
|
||||
|
||||
@@ -23,6 +23,7 @@ from .payments import (
|
||||
PaymentHistoryPoint,
|
||||
PaymentsStatusCount,
|
||||
PaymentState,
|
||||
PaymentTotalBreakdown,
|
||||
PaymentWalletStats,
|
||||
SettleInvoice,
|
||||
UpdatePaymentExtra,
|
||||
@@ -83,6 +84,7 @@ __all__ = [
|
||||
"PaymentFilters",
|
||||
"PaymentHistoryPoint",
|
||||
"PaymentState",
|
||||
"PaymentTotalBreakdown",
|
||||
"PaymentWalletStats",
|
||||
"PaymentsStatusCount",
|
||||
"RegisterUser",
|
||||
|
||||
@@ -220,6 +220,13 @@ class PaymentWalletStats(BaseModel):
|
||||
balance: float = 0
|
||||
|
||||
|
||||
class PaymentTotalBreakdown(BaseModel):
|
||||
tag: str | None = None
|
||||
is_fiat: bool = False
|
||||
payments_count: int = 0
|
||||
total: int = 0
|
||||
|
||||
|
||||
class PaymentDailyStats(BaseModel):
|
||||
date: datetime
|
||||
balance: float = 0
|
||||
|
||||
@@ -8,7 +8,7 @@ import httpx
|
||||
from loguru import logger
|
||||
|
||||
from lnbits.core.crud import get_wallet
|
||||
from lnbits.core.crud.payments import create_payment
|
||||
from lnbits.core.crud.payments import create_payment, update_payment
|
||||
from lnbits.core.models import CreatePayment, Payment, PaymentState
|
||||
from lnbits.core.models.misc import SimpleStatus
|
||||
from lnbits.db import Connection
|
||||
@@ -57,6 +57,8 @@ async def check_fiat_status(payment: Payment) -> FiatPaymentStatus:
|
||||
fiat_status = await fiat_provider.get_invoice_status(checking_id)
|
||||
|
||||
if fiat_status.success:
|
||||
payment.status = PaymentState.SUCCESS.value
|
||||
await update_payment(payment)
|
||||
await handle_fiat_payment_confirmation(payment)
|
||||
|
||||
# notify receivers asynchronously
|
||||
|
||||
@@ -129,15 +129,6 @@ async def create_fiat_invoice(
|
||||
if not fiat_provider_name:
|
||||
raise ValueError("Fiat provider is required for fiat invoices.")
|
||||
if not settings.is_fiat_provider_enabled(fiat_provider_name):
|
||||
funding_source = get_funding_source()
|
||||
if funding_source.__class__.__name__ == "LNbitsWallet":
|
||||
fiat_invoice = await create_wallet_invoice(wallet_id, invoice_data)
|
||||
fiat_invoice.fiat_provider = fiat_provider_name
|
||||
fiat_invoice.extra["fiat_checking_id"] = fiat_invoice.checking_id
|
||||
# TODO: move to payment
|
||||
fiat_invoice.extra["fiat_payment_request"] = fiat_invoice.payment_request
|
||||
|
||||
return fiat_invoice
|
||||
raise ValueError(
|
||||
f"Fiat provider '{fiat_provider_name}' is not enabled.",
|
||||
)
|
||||
@@ -228,7 +219,6 @@ async def create_wallet_invoice(wallet_id: str, data: CreateInvoice) -> Payment:
|
||||
payment_hash=data.payment_hash,
|
||||
labels=data.labels,
|
||||
external_id=data.external_id,
|
||||
fiat_provider=data.fiat_provider,
|
||||
conn=conn,
|
||||
)
|
||||
|
||||
@@ -271,7 +261,6 @@ async def create_invoice(
|
||||
payment_hash: str | None = None,
|
||||
labels: list[str] | None = None,
|
||||
external_id: str | None = None,
|
||||
fiat_provider: str | None = None,
|
||||
conn: Connection | None = None,
|
||||
) -> Payment:
|
||||
if not amount > 0:
|
||||
@@ -332,9 +321,6 @@ async def create_invoice(
|
||||
description_hash=description_hash,
|
||||
unhashed_description=unhashed_description,
|
||||
expiry=expiry or settings.lightning_invoice_expiry,
|
||||
fiat_provider=fiat_provider,
|
||||
currency=currency if currency != "sat" else None,
|
||||
fiat_amount=amount if currency != "sat" else None,
|
||||
)
|
||||
if (
|
||||
not invoice_response.ok
|
||||
@@ -346,8 +332,6 @@ async def create_invoice(
|
||||
status="pending",
|
||||
)
|
||||
invoice = bolt11_decode(invoice_response.payment_request)
|
||||
extra["fiat_provider"] = fiat_provider
|
||||
extra["fiat_payment_request"] = invoice_response.fiat_payment_request
|
||||
|
||||
create_payment_model = CreatePayment(
|
||||
wallet_id=user_wallet.source_wallet_id,
|
||||
|
||||
@@ -14,6 +14,7 @@ from lnurl import url_decode
|
||||
from lnbits import bolt11
|
||||
from lnbits.core.crud.payments import (
|
||||
get_payment_count_stats,
|
||||
get_wallet_payment_total_breakdown,
|
||||
get_wallets_stats,
|
||||
update_payment,
|
||||
)
|
||||
@@ -31,6 +32,7 @@ from lnbits.core.models import (
|
||||
PaymentDailyStats,
|
||||
PaymentFilters,
|
||||
PaymentHistoryPoint,
|
||||
PaymentTotalBreakdown,
|
||||
PaymentWalletStats,
|
||||
SettleInvoice,
|
||||
SimpleStatus,
|
||||
@@ -131,6 +133,17 @@ async def api_payments_counting_stats(
|
||||
return await get_payment_count_stats(count_by, filters=filters, user_id=for_user_id)
|
||||
|
||||
|
||||
@payment_router.get(
|
||||
"/stats/breakdown",
|
||||
name="Get wallet payment total breakdown",
|
||||
response_model=list[PaymentTotalBreakdown],
|
||||
)
|
||||
async def api_payments_total_breakdown(
|
||||
key_info: BaseWalletTypeInfo = Depends(require_base_invoice_key),
|
||||
):
|
||||
return await get_wallet_payment_total_breakdown(key_info.wallet.id)
|
||||
|
||||
|
||||
@payment_router.get(
|
||||
"/stats/wallets",
|
||||
name="Get payments history for all users",
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+10
-10
File diff suppressed because one or more lines are too long
@@ -175,6 +175,9 @@ window._lnbitsApi = {
|
||||
wallet.inkey
|
||||
)
|
||||
},
|
||||
getPaymentTotalBreakdown(wallet) {
|
||||
return this.request('get', '/api/v1/payments/stats/breakdown', wallet.inkey)
|
||||
},
|
||||
getPayment(wallet, paymentHash) {
|
||||
return this.request('get', '/api/v1/payments/' + paymentHash, wallet.inkey)
|
||||
},
|
||||
|
||||
@@ -27,6 +27,14 @@ const DynamicComponent = {
|
||||
name: r.name,
|
||||
component: async () => {
|
||||
await LNbits.utils.loadTemplate(r.template)
|
||||
if (r.i18n) {
|
||||
const locale =
|
||||
window.i18n?.global?.locale?.value ??
|
||||
window.i18n?.global?.locale ??
|
||||
window.g.locale ??
|
||||
'en'
|
||||
await LNbits.utils.loadExtI18n(r.i18n, locale)
|
||||
}
|
||||
await LNbits.utils.loadScript(r.component)
|
||||
return window[r.name]
|
||||
}
|
||||
@@ -151,6 +159,30 @@ window.i18n = new VueI18n.createI18n({
|
||||
fallbackLocale: 'en',
|
||||
messages: window.localisation
|
||||
})
|
||||
;(function () {
|
||||
let _applying = false
|
||||
let _target = null
|
||||
Vue.watch(
|
||||
() => window.i18n.global.locale,
|
||||
async (locale, prevLocale) => {
|
||||
if (_applying || !LNbits.utils._extI18nDirs.size) return
|
||||
_target = locale
|
||||
_applying = true
|
||||
window.i18n.global.locale = prevLocale
|
||||
_applying = false
|
||||
await Promise.all(
|
||||
[...LNbits.utils._extI18nDirs].map(dir =>
|
||||
LNbits.utils.loadExtI18n(dir, locale)
|
||||
)
|
||||
)
|
||||
if (_target !== locale) return
|
||||
_applying = true
|
||||
window.i18n.global.locale = locale
|
||||
_applying = false
|
||||
},
|
||||
{flush: 'sync'}
|
||||
)
|
||||
})()
|
||||
|
||||
window.app.mixin({
|
||||
data() {
|
||||
|
||||
@@ -48,6 +48,13 @@ window.PageWallet = {
|
||||
hasNfc: false,
|
||||
nfcReaderAbortController: null,
|
||||
formattedFiatAmount: 0,
|
||||
totalBreakdown: {
|
||||
show: false,
|
||||
loading: false,
|
||||
rows: [],
|
||||
selectedTypes: ['bitcoin', 'fiat'],
|
||||
selectedTags: []
|
||||
},
|
||||
paymentFilter: {
|
||||
'status[ne]': 'failed'
|
||||
},
|
||||
@@ -84,9 +91,116 @@ window.PageWallet = {
|
||||
},
|
||||
formattedSatAmount() {
|
||||
return LNbits.utils.formatMsat(this.receive.amountMsat) + ' sat'
|
||||
},
|
||||
totalBreakdownTags() {
|
||||
const tags = this.totalBreakdown.rows.map(row => row.tag || null)
|
||||
return [...new Set(tags)].sort((a, b) =>
|
||||
this.totalBreakdownTagLabel(a).localeCompare(
|
||||
this.totalBreakdownTagLabel(b)
|
||||
)
|
||||
)
|
||||
},
|
||||
hasFiatTotalBreakdown() {
|
||||
return this.totalBreakdown.rows.some(row => row.is_fiat)
|
||||
},
|
||||
selectedTotalBreakdownRows() {
|
||||
return this.totalBreakdown.rows.filter(row => {
|
||||
const type = row.is_fiat ? 'fiat' : 'bitcoin'
|
||||
return (
|
||||
this.totalBreakdown.selectedTypes.includes(type) &&
|
||||
this.totalBreakdown.selectedTags.includes(
|
||||
this.totalBreakdownTagKey(row.tag)
|
||||
)
|
||||
)
|
||||
})
|
||||
},
|
||||
selectedTotalBreakdownMsat() {
|
||||
return this.selectedTotalBreakdownRows.reduce(
|
||||
(total, row) => total + row.total,
|
||||
0
|
||||
)
|
||||
},
|
||||
selectedTotalBreakdownSat() {
|
||||
return Math.round(this.selectedTotalBreakdownMsat / 1000)
|
||||
},
|
||||
selectedTotalBreakdownCount() {
|
||||
return this.selectedTotalBreakdownRows.reduce(
|
||||
(total, row) => total + row.payments_count,
|
||||
0
|
||||
)
|
||||
},
|
||||
formattedTotalBreakdown() {
|
||||
return this.utils.formatBalance(
|
||||
this.selectedTotalBreakdownSat,
|
||||
this.g.denomination
|
||||
)
|
||||
},
|
||||
formattedTotalBreakdownFiat() {
|
||||
if (!this.g.fiatTracking) return null
|
||||
const amount =
|
||||
(this.selectedTotalBreakdownSat / 100000000) * this.g.exchangeRate
|
||||
return LNbits.utils.formatCurrency(amount, this.g.wallet.currency)
|
||||
},
|
||||
primaryTotalBreakdownValue() {
|
||||
if (this.g.isFiatPriority && this.g.fiatTracking) {
|
||||
return this.formattedTotalBreakdownFiat || this.formattedTotalBreakdown
|
||||
}
|
||||
return this.formattedTotalBreakdown
|
||||
},
|
||||
secondaryTotalBreakdownValue() {
|
||||
if (!this.g.fiatTracking) return null
|
||||
if (this.g.isFiatPriority) {
|
||||
return this.formattedTotalBreakdown
|
||||
}
|
||||
return this.formattedTotalBreakdownFiat
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
showWalletTotalBreakdown() {
|
||||
this.totalBreakdown.show = true
|
||||
if (!this.totalBreakdown.rows.length) {
|
||||
this.fetchTotalBreakdown()
|
||||
}
|
||||
},
|
||||
fetchTotalBreakdown() {
|
||||
this.totalBreakdown.loading = true
|
||||
LNbits.api
|
||||
.getPaymentTotalBreakdown(this.g.wallet)
|
||||
.then(response => {
|
||||
this.totalBreakdown.rows = response.data
|
||||
this.totalBreakdown.selectedTypes = ['bitcoin', 'fiat']
|
||||
this.totalBreakdown.selectedTags = this.totalBreakdownTags.map(
|
||||
this.totalBreakdownTagKey
|
||||
)
|
||||
this.totalBreakdown.loading = false
|
||||
})
|
||||
.catch(err => {
|
||||
this.totalBreakdown.loading = false
|
||||
LNbits.utils.notifyApiError(err)
|
||||
})
|
||||
},
|
||||
totalBreakdownTagLabel(tag) {
|
||||
return tag || 'No tag'
|
||||
},
|
||||
totalBreakdownTagKey(tag) {
|
||||
return tag || '__untagged__'
|
||||
},
|
||||
totalBreakdownTagCount(tag) {
|
||||
return this.totalBreakdown.rows
|
||||
.filter(row => (row.tag || null) === tag)
|
||||
.reduce((total, row) => total + row.payments_count, 0)
|
||||
},
|
||||
totalBreakdownTagMsat(tag) {
|
||||
return this.totalBreakdown.rows
|
||||
.filter(row => (row.tag || null) === tag)
|
||||
.reduce((total, row) => total + row.total, 0)
|
||||
},
|
||||
formatTotalBreakdownMsat(msat) {
|
||||
return this.utils.formatBalance(
|
||||
Math.round(msat / 1000),
|
||||
this.g.denomination
|
||||
)
|
||||
},
|
||||
handleSendLnurl(lnurl) {
|
||||
this.parse.data.request = lnurl
|
||||
this.parse.show = true
|
||||
|
||||
@@ -323,6 +323,20 @@ window._lnbitsUtils = {
|
||||
converter.setOption('simpleLineBreaks', true)
|
||||
return converter.makeHtml(text)
|
||||
},
|
||||
_extI18nDirs: new Set(),
|
||||
_extI18nLoaded: {},
|
||||
loadExtI18n(dir, locale) {
|
||||
this._extI18nDirs.add(dir)
|
||||
const loaded = (this._extI18nLoaded[dir] ??= {})
|
||||
if (loaded[locale]) return loaded[locale]
|
||||
loaded[locale] = this.loadScript(`${dir}/${locale}.js`).catch(() => {
|
||||
if (locale !== 'en') {
|
||||
loaded['en'] ??= this.loadScript(`${dir}/en.js`).catch(() => {})
|
||||
return loaded['en']
|
||||
}
|
||||
})
|
||||
return loaded[locale]
|
||||
},
|
||||
async decryptLnurlPayAES(success_action, preimage) {
|
||||
let keyb = new Uint8Array(
|
||||
preimage.match(/[\da-f]{2}/gi).map(h => parseInt(h, 16))
|
||||
|
||||
@@ -28,7 +28,13 @@
|
||||
<div class="col-7">
|
||||
<div class="row">
|
||||
<div class="col-auto">
|
||||
<div class="text-h3 q-my-none full-width">
|
||||
<div
|
||||
class="text-h3 q-my-none full-width cursor-pointer"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
@click="showWalletTotalBreakdown"
|
||||
@keyup.enter="showWalletTotalBreakdown"
|
||||
>
|
||||
<strong
|
||||
v-text="
|
||||
utils.formatBalance(g.wallet.sat, g.denomination)
|
||||
@@ -77,7 +83,11 @@
|
||||
<div class="col-auto">
|
||||
<div
|
||||
v-if="g.fiatTracking"
|
||||
class="text-h3 q-my-none text-no-wrap"
|
||||
class="text-h3 q-my-none text-no-wrap cursor-pointer"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
@click="showWalletTotalBreakdown"
|
||||
@keyup.enter="showWalletTotalBreakdown"
|
||||
>
|
||||
<strong v-text="formattedFiatAmount"></strong>
|
||||
</div>
|
||||
@@ -228,6 +238,113 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<q-dialog v-model="totalBreakdown.show" position="top">
|
||||
<q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
|
||||
<q-card-section>
|
||||
<div class="row items-start q-mb-md">
|
||||
<div class="col">
|
||||
<div
|
||||
class="text-h4 text-bold"
|
||||
v-text="primaryTotalBreakdownValue"
|
||||
></div>
|
||||
<div
|
||||
v-if="secondaryTotalBreakdownValue"
|
||||
class="text-h6 text-italic"
|
||||
style="opacity: 0.75"
|
||||
v-text="secondaryTotalBreakdownValue"
|
||||
></div>
|
||||
<div
|
||||
class="text-caption text-grey-5"
|
||||
v-text="selectedTotalBreakdownCount + ' payments'"
|
||||
></div>
|
||||
</div>
|
||||
<q-btn
|
||||
flat
|
||||
dense
|
||||
round
|
||||
color="grey"
|
||||
icon="refresh"
|
||||
:loading="totalBreakdown.loading"
|
||||
@click="fetchTotalBreakdown"
|
||||
>
|
||||
<q-tooltip>Refresh</q-tooltip>
|
||||
</q-btn>
|
||||
</div>
|
||||
|
||||
<q-inner-loading :showing="totalBreakdown.loading"></q-inner-loading>
|
||||
|
||||
<div v-if="hasFiatTotalBreakdown" class="q-mb-md">
|
||||
<q-checkbox
|
||||
v-model="totalBreakdown.selectedTypes"
|
||||
val="bitcoin"
|
||||
label="Bitcoin"
|
||||
></q-checkbox>
|
||||
<q-checkbox
|
||||
v-model="totalBreakdown.selectedTypes"
|
||||
val="fiat"
|
||||
label="Fiat"
|
||||
></q-checkbox>
|
||||
</div>
|
||||
|
||||
<q-separator v-if="hasFiatTotalBreakdown" class="q-mb-md"></q-separator>
|
||||
|
||||
<div style="max-height: min(52vh, 420px); overflow-y: auto">
|
||||
<q-list dense>
|
||||
<q-item
|
||||
v-for="tag in totalBreakdownTags"
|
||||
:key="totalBreakdownTagKey(tag)"
|
||||
tag="label"
|
||||
v-ripple
|
||||
>
|
||||
<q-item-section side>
|
||||
<q-checkbox
|
||||
v-model="totalBreakdown.selectedTags"
|
||||
:val="totalBreakdownTagKey(tag)"
|
||||
></q-checkbox>
|
||||
</q-item-section>
|
||||
<q-item-section>
|
||||
<q-item-label>
|
||||
<q-badge
|
||||
v-if="tag"
|
||||
color="yellow"
|
||||
text-color="black"
|
||||
v-text="'#' + tag"
|
||||
></q-badge>
|
||||
<span v-else v-text="totalBreakdownTagLabel(tag)"></span>
|
||||
</q-item-label>
|
||||
<q-item-label
|
||||
caption
|
||||
v-text="totalBreakdownTagCount(tag) + ' payments'"
|
||||
></q-item-label>
|
||||
</q-item-section>
|
||||
<q-item-section side>
|
||||
<span
|
||||
v-text="formatTotalBreakdownMsat(totalBreakdownTagMsat(tag))"
|
||||
></span>
|
||||
</q-item-section>
|
||||
</q-item>
|
||||
</q-list>
|
||||
</div>
|
||||
|
||||
<div v-if="!totalBreakdown.loading && !totalBreakdown.rows.length">
|
||||
<q-banner class="bg-transparent text-grey-5">
|
||||
No completed payments.
|
||||
</q-banner>
|
||||
</div>
|
||||
|
||||
<div class="row q-mt-md">
|
||||
<q-btn
|
||||
v-close-popup
|
||||
flat
|
||||
color="grey"
|
||||
class="q-ml-auto"
|
||||
:label="$t('close')"
|
||||
></q-btn>
|
||||
</div>
|
||||
</q-card-section>
|
||||
</q-card>
|
||||
</q-dialog>
|
||||
|
||||
<q-dialog v-model="receive.show" position="top" @hide="onReceiveDialogHide">
|
||||
<q-card
|
||||
v-if="!receive.paymentReq"
|
||||
|
||||
@@ -30,7 +30,6 @@ class InvoiceResponse(NamedTuple):
|
||||
ok: bool
|
||||
checking_id: str | None = None # payment_hash, rpc_id
|
||||
payment_request: str | None = None
|
||||
fiat_payment_request: str | None = None
|
||||
error_message: str | None = None
|
||||
preimage: str | None = None
|
||||
fee_msat: int | None = None
|
||||
|
||||
@@ -78,28 +78,17 @@ class LNbitsWallet(Wallet):
|
||||
data: dict = {"out": False, "amount": amount, "memo": memo or ""}
|
||||
if kwargs.get("expiry"):
|
||||
data["expiry"] = kwargs["expiry"]
|
||||
if kwargs.get("fiat_provider"):
|
||||
if "currency" not in kwargs or "fiat_amount" not in kwargs:
|
||||
return InvoiceResponse(
|
||||
ok=False,
|
||||
error_message="Fiat provider requires "
|
||||
"'currency' and 'fiat_amount' parameters.",
|
||||
)
|
||||
data["amount"] = kwargs["fiat_amount"]
|
||||
data["unit"] = kwargs["currency"]
|
||||
data["fiat_provider"] = kwargs["fiat_provider"]
|
||||
|
||||
if description_hash:
|
||||
data["description_hash"] = description_hash.hex()
|
||||
if unhashed_description:
|
||||
data["unhashed_description"] = unhashed_description.hex()
|
||||
|
||||
try:
|
||||
print(f"Creating invoice with data: {data}")
|
||||
r = await self.client.post(url="/api/v1/payments", json=data, timeout=30)
|
||||
r = await self.client.post(url="/api/v1/payments", json=data)
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
|
||||
# Backwards compatibility for pre-v1 which used the key "payment_request"
|
||||
payment_str = data.get("bolt11") or data.get("payment_request")
|
||||
if r.is_error or not payment_str:
|
||||
error_message = data["detail"] if "detail" in data else r.text
|
||||
@@ -111,7 +100,6 @@ class LNbitsWallet(Wallet):
|
||||
ok=True,
|
||||
checking_id=data["checking_id"],
|
||||
payment_request=payment_str,
|
||||
fiat_payment_request=data.get("payment_request"),
|
||||
preimage=data.get("preimage"),
|
||||
)
|
||||
except json.JSONDecodeError:
|
||||
@@ -123,11 +111,6 @@ class LNbitsWallet(Wallet):
|
||||
return InvoiceResponse(
|
||||
ok=False, error_message="Server error: 'missing required fields'"
|
||||
)
|
||||
except httpx.HTTPStatusError as exc:
|
||||
logger.warning(exc.response.text)
|
||||
return InvoiceResponse(
|
||||
ok=False, error_message=f"Unable to connect to {self.endpoint}."
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning(exc)
|
||||
return InvoiceResponse(
|
||||
@@ -230,7 +213,6 @@ class LNbitsWallet(Wallet):
|
||||
logger.info("connected to LNbits fundingsource websocket.")
|
||||
while settings.lnbits_running:
|
||||
message = await ws.recv()
|
||||
print(f"### Received message from websocket: {message}")
|
||||
message_dict = json.loads(message)
|
||||
if (
|
||||
message_dict
|
||||
|
||||
@@ -117,11 +117,12 @@ class PhoenixdWallet(Wallet):
|
||||
# PhoenixD description limited to 128 characters
|
||||
if description_hash:
|
||||
data["descriptionHash"] = description_hash.hex()
|
||||
elif unhashed_description:
|
||||
data["descriptionHash"] = hashlib.sha256(
|
||||
unhashed_description
|
||||
).hexdigest()
|
||||
else:
|
||||
desc = memo
|
||||
if desc is None and unhashed_description:
|
||||
desc = unhashed_description.decode()
|
||||
desc = desc or ""
|
||||
desc = memo or ""
|
||||
if len(desc) > 128:
|
||||
data["descriptionHash"] = hashlib.sha256(desc.encode()).hexdigest()
|
||||
else:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "lnbits"
|
||||
version = "1.5.5-rc2"
|
||||
version = "1.5.5-rc3"
|
||||
requires-python = ">=3.10,<3.13"
|
||||
description = "LNbits, free and open-source Lightning wallet and accounts system."
|
||||
authors = [{ name = "Alan Bits", email = "alan@lnbits.com" }]
|
||||
|
||||
@@ -6,11 +6,16 @@ import pytest
|
||||
from fastapi import HTTPException
|
||||
from pydantic import ValidationError
|
||||
|
||||
from lnbits.core.crud.payments import create_payment, get_payment, get_payments
|
||||
from lnbits.core.crud.payments import (
|
||||
create_payment,
|
||||
get_payment,
|
||||
get_payments,
|
||||
update_payment,
|
||||
)
|
||||
from lnbits.core.models import Account, CreateInvoice, PaymentFilters, PaymentState
|
||||
from lnbits.core.models.payments import CancelInvoice, CreatePayment, SettleInvoice
|
||||
from lnbits.core.models.users import AccountId
|
||||
from lnbits.core.models.wallets import KeyType, WalletTypeInfo
|
||||
from lnbits.core.models.wallets import BaseWalletTypeInfo, KeyType, WalletTypeInfo
|
||||
from lnbits.core.services.payments import create_wallet_invoice
|
||||
from lnbits.core.services.users import create_user_account
|
||||
from lnbits.core.views.payment_api import (
|
||||
@@ -20,6 +25,7 @@ from lnbits.core.views.payment_api import (
|
||||
api_payments_daily_stats,
|
||||
api_payments_fee_reserve,
|
||||
api_payments_settle,
|
||||
api_payments_total_breakdown,
|
||||
api_payments_wallets_stats,
|
||||
)
|
||||
from lnbits.db import Filter, Filters
|
||||
@@ -146,6 +152,61 @@ async def test_payment_external_id_is_stored_and_validated():
|
||||
CreateInvoice(out=False, amount=21, external_id="provider payment 123")
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_payment_api_total_breakdown_groups_wallet_tags_and_fiat():
|
||||
first_user = await create_user_account(
|
||||
Account(
|
||||
id=uuid4().hex,
|
||||
username=f"user_{uuid4().hex[:8]}",
|
||||
email=f"user_{uuid4().hex[:8]}@lnbits.com",
|
||||
)
|
||||
)
|
||||
second_user = await create_user_account(
|
||||
Account(
|
||||
id=uuid4().hex,
|
||||
username=f"user_{uuid4().hex[:8]}",
|
||||
email=f"user_{uuid4().hex[:8]}@lnbits.com",
|
||||
)
|
||||
)
|
||||
first_wallet = first_user.wallets[0]
|
||||
second_wallet = second_user.wallets[0]
|
||||
|
||||
await _create_payment(first_wallet.id, amount_msat=2_000, tag="coffee")
|
||||
await _create_payment(
|
||||
first_wallet.id,
|
||||
amount_msat=4_000,
|
||||
tag="coffee",
|
||||
fiat_provider="stripe",
|
||||
extra={"fiat_payment_request": "https://stripe.test/session"},
|
||||
)
|
||||
await _create_payment(first_wallet.id, amount_msat=-1_000)
|
||||
await _create_payment(second_wallet.id, amount_msat=8_000, tag="books")
|
||||
|
||||
breakdown = await api_payments_total_breakdown(
|
||||
BaseWalletTypeInfo(key_type=KeyType.invoice, wallet=first_wallet)
|
||||
)
|
||||
|
||||
assert any(
|
||||
item.tag == "coffee"
|
||||
and item.is_fiat is False
|
||||
and item.total == 2_000
|
||||
and item.payments_count == 1
|
||||
for item in breakdown
|
||||
)
|
||||
assert any(
|
||||
item.tag == "coffee"
|
||||
and item.is_fiat is True
|
||||
and item.total == 4_000
|
||||
and item.payments_count == 1
|
||||
for item in breakdown
|
||||
)
|
||||
assert any(
|
||||
item.tag is None and item.is_fiat is False and item.total == -1_000
|
||||
for item in breakdown
|
||||
)
|
||||
assert all(item.tag != "books" for item in breakdown)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_payment_api_fee_reserve_and_hold_invoice_actions(mocker):
|
||||
user = await create_user_account(
|
||||
@@ -383,8 +444,13 @@ async def _create_payment(
|
||||
status: PaymentState = PaymentState.SUCCESS,
|
||||
payment_hash: str | None = None,
|
||||
tag: str | None = None,
|
||||
fiat_provider: str | None = None,
|
||||
extra: dict | None = None,
|
||||
) -> str:
|
||||
checking_id = f"checking_{uuid4().hex[:8]}"
|
||||
payment_extra = extra or {}
|
||||
if tag:
|
||||
payment_extra["tag"] = tag
|
||||
await create_payment(
|
||||
checking_id=checking_id,
|
||||
data=CreatePayment(
|
||||
@@ -393,8 +459,12 @@ async def _create_payment(
|
||||
bolt11=f"bolt11_{checking_id}",
|
||||
amount_msat=amount_msat,
|
||||
memo=f"payment_{checking_id}",
|
||||
extra={"tag": tag} if tag else {},
|
||||
extra=payment_extra,
|
||||
),
|
||||
status=status,
|
||||
)
|
||||
if fiat_provider:
|
||||
payment = await get_payment(checking_id)
|
||||
payment.fiat_provider = fiat_provider
|
||||
await update_payment(payment)
|
||||
return checking_id
|
||||
|
||||
@@ -8,7 +8,7 @@ from unittest.mock import AsyncMock
|
||||
import pytest
|
||||
from pytest_mock.plugin import MockerFixture
|
||||
|
||||
from lnbits.core.crud.payments import get_payments
|
||||
from lnbits.core.crud.payments import get_payment, get_payments
|
||||
from lnbits.core.crud.users import get_user
|
||||
from lnbits.core.crud.wallets import create_wallet
|
||||
from lnbits.core.models.payments import CreateInvoice, Payment, PaymentState
|
||||
@@ -1752,6 +1752,51 @@ async def test_check_fiat_status_handles_internal_states(mocker: MockerFixture):
|
||||
assert queue_put.await_count == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_check_fiat_status_persists_successful_payment(
|
||||
to_wallet: Wallet, settings: Settings, mocker: MockerFixture
|
||||
):
|
||||
settings.stripe_enabled = True
|
||||
settings.stripe_api_secret_key = "mock_sk_test_4eC39HqLyjWDarjtT1zdp7dc"
|
||||
settings.stripe_limits.service_min_amount_sats = 0
|
||||
settings.stripe_limits.service_max_amount_sats = 0
|
||||
settings.stripe_limits.service_fee_wallet_id = None
|
||||
settings.stripe_limits.service_faucet_wallet_id = None
|
||||
|
||||
invoice_data = CreateInvoice(
|
||||
unit="USD", amount=1.0, memo="Test", fiat_provider="stripe"
|
||||
)
|
||||
fiat_mock_response = FiatInvoiceResponse(
|
||||
ok=True,
|
||||
checking_id=f"session_paid_{get_random_string(10)}",
|
||||
payment_request="https://stripe.com/pay/session_paid",
|
||||
)
|
||||
mocker.patch(
|
||||
"lnbits.fiat.StripeWallet.create_invoice",
|
||||
AsyncMock(return_value=fiat_mock_response),
|
||||
)
|
||||
mocker.patch(
|
||||
"lnbits.utils.exchange_rates.get_fiat_rate_satoshis",
|
||||
AsyncMock(return_value=1000),
|
||||
)
|
||||
payment = await payments.create_fiat_invoice(to_wallet.id, invoice_data)
|
||||
assert payment.status == PaymentState.PENDING
|
||||
|
||||
mocker.patch(
|
||||
"lnbits.fiat.StripeWallet.get_invoice_status",
|
||||
AsyncMock(return_value=FiatPaymentStatus(paid=True)),
|
||||
)
|
||||
queue_put = mocker.patch("lnbits.tasks.internal_invoice_queue.put", AsyncMock())
|
||||
|
||||
status = await check_fiat_status(payment)
|
||||
|
||||
assert status.success is True
|
||||
assert payment.status == PaymentState.SUCCESS
|
||||
updated_payment = await get_payment(payment.checking_id)
|
||||
assert updated_payment.status == PaymentState.SUCCESS
|
||||
queue_put.assert_awaited_once_with(payment.checking_id)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_verify_paypal_webhook_requires_configuration(settings: Settings):
|
||||
settings.paypal_webhook_id = None
|
||||
|
||||
Reference in New Issue
Block a user