feat(checkout): two-phase flow with QR + copy + external-wallet support
The previous all-in-one 'Pay & place order' button placed the
orders AND immediately auto-paid from the LNbits wallet, so the
bolt11 QR never rendered. Customers couldn't scan with their own
phone wallet (Phoenix, Wallet of Satoshi, etc.) — they were stuck
on the LNbits anon wallet by default.
Split into two distinct phases:
useCheckout (refactor):
- state.step: 'idle' → 'quoting' → 'placing' → 'placed' →
'paying' → 'paid' (or 'error')
- state.placedOrders: PlacedOrder[] survives across the two
phases, exposing each restaurant's { order, invoice }
- state.paidOrderIds: Set<string> tracks which orders the
customer auto-paid this session (external scans aren't in
this set; the CheckoutPage poller tracks those)
- placeOrders() — runs quote, balance precheck (warns only,
doesn't block — the customer might pay externally), places
orders, populates placedOrders
- payOrder(idx) — pays one bolt11 via POST /api/v1/payments
with the customer's wallets[0].adminkey
- payAll() — convenience: payOrder for each unpaid placed order
- reset() — clears state back to idle
CheckoutPage (rewrite):
Phase 1 (review): cart subtotal in menu currency + live
≈sat preview + 'Place order' CTA. Unchanged from before
except the CTA no longer also pays.
Phase 2 (pay): OrderInvoiceCard per placed order showing the
QR, amount, copy button, and expiry countdown. 'Pay from my
LNbits wallet' CTA wraps payAll(). The page also polls every
3s — when the extension's invoice listener flips an order to
'paid' (regardless of which wallet paid it — LNbits anon
auto-pay OR external scan), the badge flips, the cart bucket
for that restaurant clears, and once all placed orders are
paid, we redirect to /orders/<first-id> after a 1.2s success
splash.
Errors from auto-pay don't kill the flow — the QR stays
visible so the customer can fall back to an external wallet
scan.
This matches the typical restaurant UX: 'here's your bill,
scan or auto-pay' rather than 'we charged your wallet without
asking'. Verified: vue-tsc -b clean.
This commit is contained in:
parent
10abfca555
commit
705a94b475
2 changed files with 484 additions and 246 deletions
|
|
@ -1,25 +1,31 @@
|
|||
/**
|
||||
* useCheckout — orchestrates the place-order + pay-bolt11 sequence
|
||||
* for every restaurant currently in the cart.
|
||||
* useCheckout — drives the customer's place-and-pay flow against
|
||||
* the restaurant extension.
|
||||
*
|
||||
* v1 ships REST-only:
|
||||
* for each restaurant in the cart:
|
||||
* 1. quote (msat required)
|
||||
* 2. balance pre-check (sum across all restaurants)
|
||||
* 3. placeOrder → { order, invoice }
|
||||
* 4. WalletService.sendPayment(bolt11)
|
||||
* 1. quote (msat required)
|
||||
* 2. balance pre-check (sum across all restaurants in the cart)
|
||||
* 3. POST /orders → { order, invoice }
|
||||
* 4. (optional, customer choice) POST /api/v1/payments to settle
|
||||
* the bolt11 from the customer's LNbits wallet. They can also
|
||||
* skip this step and scan the QR with any other wallet — the
|
||||
* extension's invoice listener marks the order paid either way.
|
||||
*
|
||||
* The festival aggregator (aiolabs/restaurant#8) exercises this
|
||||
* same path with N > 1 restaurants in the cart. v1 happens to ship
|
||||
* a UI where N == 1, but the orchestration is multi-restaurant
|
||||
* already.
|
||||
* Split into two distinct actions so the UI can render the QR codes
|
||||
* between place and pay, giving the customer the option to scan
|
||||
* with an external wallet rather than auto-paying from LNbits:
|
||||
*
|
||||
* NIP-17 transport (aiolabs/restaurant#9) plugs in here later as a
|
||||
* `transport: 'rest' | 'nostr'` option that gift-wraps the
|
||||
* CreateOrder instead of POSTing it. The `buildCreateOrder`
|
||||
* helper is the single point both transports build through, so
|
||||
* adding loyalty (aiolabs/restaurant#5) is also a one-function
|
||||
* change rather than touching every call site.
|
||||
* placeOrders() — runs steps 1-3, populates `state.value.placedOrders`
|
||||
* payOrder(idx) — runs step 4 for one placed-order index
|
||||
*
|
||||
* The festival aggregator (aiolabs/restaurant#8) exercises this same
|
||||
* path with N > 1 restaurants in the cart. v1 happens to ship a UI
|
||||
* where N == 1, but the orchestration is multi-restaurant ready.
|
||||
*
|
||||
* NIP-17 transport (aiolabs/restaurant#9) plugs in via the
|
||||
* `buildCreateOrder` helper — single point both REST and Nostr
|
||||
* transports construct CreateOrder. Loyalty (#5) injects its
|
||||
* pass-through fields the same way.
|
||||
*/
|
||||
import { ref, type Ref } from 'vue'
|
||||
import { injectService, SERVICE_TOKENS } from '@/core/di-container'
|
||||
|
|
@ -42,28 +48,46 @@ export interface PlacedOrder {
|
|||
invoice: OrderInvoice | null
|
||||
}
|
||||
|
||||
export interface CheckoutResult {
|
||||
placedOrders: PlacedOrder[]
|
||||
paidPaymentHashes: string[]
|
||||
}
|
||||
|
||||
export interface CheckoutState {
|
||||
step: 'idle' | 'quoting' | 'placing' | 'paying' | 'done' | 'error'
|
||||
step:
|
||||
| 'idle'
|
||||
| 'quoting'
|
||||
| 'placing'
|
||||
| 'placed'
|
||||
| 'paying'
|
||||
| 'paid'
|
||||
| 'error'
|
||||
progress: { current: number; total: number }
|
||||
currentRestaurantSlug: string | null
|
||||
placedOrders: PlacedOrder[]
|
||||
/** Set of `placedOrders[i].order.id` that have been auto-paid
|
||||
* via LNbits in this session. External-wallet payments don't
|
||||
* populate this — they're detected via the per-order poller in
|
||||
* CheckoutPage. */
|
||||
paidOrderIds: Set<string>
|
||||
error: string | null
|
||||
}
|
||||
|
||||
export interface UseCheckoutReturn {
|
||||
state: Ref<CheckoutState>
|
||||
checkout: () => Promise<CheckoutResult>
|
||||
/** Run quote → balance precheck → POST /orders for every cart
|
||||
* bucket. Returns the placed orders (also persisted in state). */
|
||||
placeOrders: () => Promise<PlacedOrder[]>
|
||||
/** Pay one already-placed order's bolt11 from the customer's
|
||||
* LNbits wallet. Idempotent — calling twice on the same order
|
||||
* is a no-op after the first success. */
|
||||
payOrder: (placedIndex: number) => Promise<void>
|
||||
/** Pay every unpaid placed-order in sequence. Best-effort: if
|
||||
* one fails, earlier successes stay paid. */
|
||||
payAll: () => Promise<void>
|
||||
/** Reset to idle and drop placed/paid state. */
|
||||
reset: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* The single point CreateOrder is built — keeps loyalty (#5), NIP-17
|
||||
* transport (#9), and tip overrides one-place changes rather than
|
||||
* touching the whole flow. Today loyalty is unconfigured so the
|
||||
* extra block stays at its defaults.
|
||||
* touching the whole flow.
|
||||
*/
|
||||
function buildCreateOrder(
|
||||
restaurantId: string,
|
||||
|
|
@ -76,7 +100,6 @@ function buildCreateOrder(
|
|||
selected_modifiers: l.selected_modifiers,
|
||||
note: l.note ?? undefined,
|
||||
}))
|
||||
|
||||
// Loyalty (#5) future-extension point: when implemented, inject
|
||||
// { loyalty_credits_msat, loyalty_pubkey } into extra.fields here.
|
||||
return {
|
||||
|
|
@ -88,6 +111,17 @@ function buildCreateOrder(
|
|||
}
|
||||
}
|
||||
|
||||
function blankState(): CheckoutState {
|
||||
return {
|
||||
step: 'idle',
|
||||
progress: { current: 0, total: 0 },
|
||||
currentRestaurantSlug: null,
|
||||
placedOrders: [],
|
||||
paidOrderIds: new Set(),
|
||||
error: null,
|
||||
}
|
||||
}
|
||||
|
||||
export function useCheckout(): UseCheckoutReturn {
|
||||
const api = injectService<RestaurantAPI>(SERVICE_TOKENS.RESTAURANT_API)
|
||||
const cart = useCartStore()
|
||||
|
|
@ -95,9 +129,7 @@ export function useCheckout(): UseCheckoutReturn {
|
|||
|
||||
// We talk to LNbits's payments endpoint directly rather than
|
||||
// pulling in the whole `wallet` module — the restaurant-app
|
||||
// bundle is a customer surface, not a wallet UI, and `LnbitsAPI`
|
||||
// is already registered by base. The customer's adminkey lives
|
||||
// on AuthService.user.wallets[0].adminkey.
|
||||
// bundle is a customer surface, not a wallet UI.
|
||||
const apiBaseUrl =
|
||||
(
|
||||
appConfig.modules.restaurant as
|
||||
|
|
@ -105,52 +137,30 @@ export function useCheckout(): UseCheckoutReturn {
|
|||
| undefined
|
||||
)?.config?.apiBaseUrl || ''
|
||||
|
||||
async function payBolt11(bolt11: string, adminkey: string): Promise<void> {
|
||||
const response = await fetch(`${apiBaseUrl}/api/v1/payments`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Api-Key': adminkey,
|
||||
},
|
||||
body: JSON.stringify({ out: true, bolt11 }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
let detail = response.statusText
|
||||
try {
|
||||
const body = await response.json()
|
||||
if (body?.detail) detail = body.detail
|
||||
} catch {
|
||||
/* body wasn't JSON */
|
||||
}
|
||||
throw new Error(
|
||||
`Payment failed: ${response.status} ${detail}`
|
||||
)
|
||||
}
|
||||
const state = ref<CheckoutState>(blankState())
|
||||
|
||||
function reset(): void {
|
||||
state.value = blankState()
|
||||
}
|
||||
|
||||
const state = ref<CheckoutState>({
|
||||
step: 'idle',
|
||||
progress: { current: 0, total: 0 },
|
||||
currentRestaurantSlug: null,
|
||||
error: null,
|
||||
})
|
||||
// ----------------------------------------------------------------- //
|
||||
// place //
|
||||
// ----------------------------------------------------------------- //
|
||||
|
||||
async function checkout(): Promise<CheckoutResult> {
|
||||
async function placeOrders(): Promise<PlacedOrder[]> {
|
||||
const buckets = cart.restaurantsInCart.map((rid) => ({
|
||||
restaurantId: rid,
|
||||
restaurantSlug: cart.linesFor(rid)[0]?.restaurant_slug ?? '',
|
||||
lines: cart.linesFor(rid),
|
||||
}))
|
||||
|
||||
if (!buckets.length) {
|
||||
throw new Error('Cart is empty')
|
||||
}
|
||||
|
||||
state.value = {
|
||||
...blankState(),
|
||||
step: 'quoting',
|
||||
progress: { current: 0, total: buckets.length },
|
||||
currentRestaurantSlug: null,
|
||||
error: null,
|
||||
}
|
||||
|
||||
// 1. Quote per restaurant.
|
||||
|
|
@ -175,32 +185,23 @@ export function useCheckout(): UseCheckoutReturn {
|
|||
quotes.push({ ...b, msat: quote.required_msat })
|
||||
}
|
||||
|
||||
// 2. Pre-flight balance check using AuthService's cached wallet
|
||||
// balance (LNbits's user object carries balance_msat per wallet).
|
||||
// 2. Balance pre-check.
|
||||
const totalMsatRequired = quotes.reduce((s, q) => s + q.msat, 0)
|
||||
const wallet0 = user.value?.wallets?.[0]
|
||||
if (wallet0 && typeof wallet0.balance_msat === 'number') {
|
||||
if (wallet0.balance_msat < totalMsatRequired) {
|
||||
const needSat = Math.ceil(totalMsatRequired / 1000)
|
||||
const haveSat = Math.floor(wallet0.balance_msat / 1000)
|
||||
state.value = {
|
||||
step: 'error',
|
||||
progress: { current: 0, total: buckets.length },
|
||||
currentRestaurantSlug: null,
|
||||
error: `Insufficient balance. Need ${needSat} sat, have ${haveSat} sat.`,
|
||||
}
|
||||
throw new Error(state.value.error!)
|
||||
// Not fatal — the customer may still want to scan the QR
|
||||
// and pay from an external wallet. Surface a warning but
|
||||
// continue.
|
||||
console.warn(
|
||||
`[restaurant] LNbits wallet balance is below the cart total ` +
|
||||
`(have ${haveSat} sat, need ${needSat} sat). Auto-pay will ` +
|
||||
`fail; scan the QR with an external wallet to settle.`
|
||||
)
|
||||
}
|
||||
}
|
||||
if (!wallet0?.adminkey) {
|
||||
state.value = {
|
||||
step: 'error',
|
||||
progress: { current: 0, total: buckets.length },
|
||||
currentRestaurantSlug: null,
|
||||
error: 'No wallet available — please log in first.',
|
||||
}
|
||||
throw new Error(state.value.error!)
|
||||
}
|
||||
|
||||
// 3. Place orders.
|
||||
state.value.step = 'placing'
|
||||
|
|
@ -223,49 +224,86 @@ export function useCheckout(): UseCheckoutReturn {
|
|||
})
|
||||
}
|
||||
|
||||
// 4. Pay each bolt11 sequentially. If a payment fails, the
|
||||
// earlier successes are still placed-and-paid — best-effort
|
||||
// is the v1 model (see plan; HODL atomicity is a future
|
||||
// issue).
|
||||
state.value.step = 'paying'
|
||||
const paidHashes: string[] = []
|
||||
for (let i = 0; i < placed.length; i++) {
|
||||
const p = placed[i]
|
||||
state.value.currentRestaurantSlug = p.restaurantSlug
|
||||
state.value.progress = { current: i, total: placed.length }
|
||||
if (!p.invoice) continue // cash orders skip payment
|
||||
|
||||
try {
|
||||
await payBolt11(p.invoice.bolt11, wallet0.adminkey)
|
||||
if (p.invoice.payment_hash) {
|
||||
paidHashes.push(p.invoice.payment_hash)
|
||||
}
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
state.value = {
|
||||
step: 'error',
|
||||
progress: { current: i, total: placed.length },
|
||||
currentRestaurantSlug: p.restaurantSlug,
|
||||
error: msg,
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Clear the paid lines from the cart.
|
||||
for (const p of placed) {
|
||||
cart.clearRestaurant(p.restaurantId)
|
||||
}
|
||||
|
||||
state.value = {
|
||||
step: 'done',
|
||||
progress: { current: placed.length, total: placed.length },
|
||||
currentRestaurantSlug: null,
|
||||
error: null,
|
||||
}
|
||||
|
||||
return { placedOrders: placed, paidPaymentHashes: paidHashes }
|
||||
state.value.step = 'placed'
|
||||
state.value.placedOrders = placed
|
||||
state.value.currentRestaurantSlug = null
|
||||
return placed
|
||||
}
|
||||
|
||||
return { state, checkout }
|
||||
// ----------------------------------------------------------------- //
|
||||
// pay //
|
||||
// ----------------------------------------------------------------- //
|
||||
|
||||
async function payBolt11Raw(
|
||||
bolt11: string,
|
||||
adminkey: string
|
||||
): Promise<void> {
|
||||
const response = await fetch(`${apiBaseUrl}/api/v1/payments`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Api-Key': adminkey,
|
||||
},
|
||||
body: JSON.stringify({ out: true, bolt11 }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
let detail = response.statusText
|
||||
try {
|
||||
const body = await response.json()
|
||||
if (body?.detail) detail = body.detail
|
||||
} catch {
|
||||
/* body wasn't JSON */
|
||||
}
|
||||
throw new Error(`Payment failed: ${response.status} ${detail}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function payOrder(placedIndex: number): Promise<void> {
|
||||
const placed = state.value.placedOrders[placedIndex]
|
||||
if (!placed) throw new Error(`No placed order at index ${placedIndex}`)
|
||||
if (!placed.invoice) return // cash orders skip payment
|
||||
if (state.value.paidOrderIds.has(placed.order.id)) return // already paid
|
||||
|
||||
const adminkey = user.value?.wallets?.[0]?.adminkey
|
||||
if (!adminkey) {
|
||||
throw new Error('No wallet available — please log in first.')
|
||||
}
|
||||
|
||||
state.value.step = 'paying'
|
||||
state.value.currentRestaurantSlug = placed.restaurantSlug
|
||||
try {
|
||||
await payBolt11Raw(placed.invoice.bolt11, adminkey)
|
||||
// Set semantics keeps `paidOrderIds` from re-renders; rebuild
|
||||
// it on update so Vue picks up the change.
|
||||
state.value.paidOrderIds = new Set([
|
||||
...state.value.paidOrderIds,
|
||||
placed.order.id,
|
||||
])
|
||||
// Bump to 'paid' only when every placed order is paid.
|
||||
if (
|
||||
state.value.placedOrders.every((p) =>
|
||||
state.value.paidOrderIds.has(p.order.id)
|
||||
)
|
||||
) {
|
||||
state.value.step = 'paid'
|
||||
} else {
|
||||
state.value.step = 'placed'
|
||||
}
|
||||
} catch (err) {
|
||||
state.value.step = 'error'
|
||||
state.value.error = err instanceof Error ? err.message : String(err)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async function payAll(): Promise<void> {
|
||||
for (let i = 0; i < state.value.placedOrders.length; i++) {
|
||||
const p = state.value.placedOrders[i]
|
||||
if (!p.invoice) continue
|
||||
if (state.value.paidOrderIds.has(p.order.id)) continue
|
||||
await payOrder(i)
|
||||
}
|
||||
}
|
||||
|
||||
return { state, placeOrders, payOrder, payAll, reset }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,15 +1,40 @@
|
|||
<script setup lang="ts">
|
||||
/**
|
||||
* Review + pre-flight quote + place orders + pay bolt11s.
|
||||
* Two-phase checkout:
|
||||
*
|
||||
* Multi-restaurant ready (loops every restaurant in the cart) but
|
||||
* v1 typically has a single bucket. On success: clear cart, route
|
||||
* to /orders/<firstOrderId>. On failure: surface the error inline.
|
||||
* Phase 1 — Review:
|
||||
* · cart subtotal in the menu's declared currency (e.g. GTQ)
|
||||
* · live ≈sat preview from POST /orders/quote
|
||||
* · "Place order" CTA → useCheckout.placeOrders()
|
||||
*
|
||||
* Phase 2 — Pay:
|
||||
* · OrderInvoiceCard per placed order (QR + amount + copy +
|
||||
* expiry countdown)
|
||||
* · "Pay from my LNbits wallet" CTA → useCheckout.payAll()
|
||||
* · External-wallet scans are detected via per-order polling
|
||||
* (the extension's invoice listener flips the order to
|
||||
* paid the moment ANY pay path settles).
|
||||
* · When all placed orders show paid, auto-redirect to
|
||||
* /orders/<first-id>.
|
||||
*
|
||||
* Cart lines are cleared per restaurant as each order is observed
|
||||
* paid, so a partial-pay state can be re-checked-out without
|
||||
* duplicates.
|
||||
*/
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { ArrowLeft, Loader2, CheckCircle2, Zap } from 'lucide-vue-next'
|
||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
|
||||
import {
|
||||
ArrowLeft,
|
||||
CheckCircle2,
|
||||
Loader2,
|
||||
Zap,
|
||||
} from 'lucide-vue-next'
|
||||
import {
|
||||
Alert,
|
||||
AlertDescription,
|
||||
AlertTitle,
|
||||
} from '@/components/ui/alert'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Card,
|
||||
|
|
@ -18,8 +43,9 @@ import {
|
|||
CardTitle,
|
||||
} from '@/components/ui/card'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import OrderInvoiceCard from '../components/OrderInvoiceCard.vue'
|
||||
import { useCartStore } from '../stores/cart'
|
||||
import { useCheckout } from '../composables/useCheckout'
|
||||
import { useCheckout, type PlacedOrder } from '../composables/useCheckout'
|
||||
import {
|
||||
injectService,
|
||||
tryInjectService,
|
||||
|
|
@ -30,13 +56,13 @@ import type { RestaurantAPI } from '../services/RestaurantAPI'
|
|||
|
||||
const router = useRouter()
|
||||
const cart = useCartStore()
|
||||
const { state, checkout } = useCheckout()
|
||||
const { state, placeOrders, payAll, reset } = useCheckout()
|
||||
const storage = tryInjectService<StorageService>(SERVICE_TOKENS.STORAGE_SERVICE)
|
||||
const api = injectService<RestaurantAPI>(SERVICE_TOKENS.RESTAURANT_API)
|
||||
|
||||
const isSubmitting = computed(
|
||||
() => state.value.step !== 'idle' && state.value.step !== 'done' && state.value.step !== 'error'
|
||||
)
|
||||
// ----------------------------------------------------------------- //
|
||||
// review phase //
|
||||
// ----------------------------------------------------------------- //
|
||||
|
||||
function fmt(value: number, currency: string) {
|
||||
return `${new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(value)} ${currency}`
|
||||
|
|
@ -51,12 +77,7 @@ const buckets = computed(() =>
|
|||
}))
|
||||
)
|
||||
|
||||
/**
|
||||
* Live ≈sat preview: a single /orders/quote per restaurant the
|
||||
* moment the cart is loaded. Surfaces the actual Lightning amount
|
||||
* the customer will pay, separately from the menu-currency
|
||||
* subtotal. Recomputes whenever the cart changes.
|
||||
*/
|
||||
/** Live ≈sat preview: one /orders/quote per restaurant. */
|
||||
const previewSatPerRestaurant = ref<Record<string, number | null>>({})
|
||||
const previewSatTotal = computed<number | null>(() => {
|
||||
const vals = Object.values(previewSatPerRestaurant.value)
|
||||
|
|
@ -65,11 +86,13 @@ const previewSatTotal = computed<number | null>(() => {
|
|||
})
|
||||
|
||||
watch(
|
||||
() => cart.restaurantsInCart.map((rid) => ({
|
||||
rid,
|
||||
lines: cart.linesFor(rid),
|
||||
})),
|
||||
() =>
|
||||
cart.restaurantsInCart.map((rid) => ({
|
||||
rid,
|
||||
lines: cart.linesFor(rid),
|
||||
})),
|
||||
async (groups) => {
|
||||
if (state.value.step !== 'idle') return // freeze preview after place
|
||||
const next: Record<string, number | null> = {}
|
||||
for (const g of groups) {
|
||||
try {
|
||||
|
|
@ -83,9 +106,6 @@ watch(
|
|||
)
|
||||
next[g.rid] = Math.ceil(q.required_msat / 1000)
|
||||
} catch {
|
||||
// Best-effort preview only; if the quote endpoint hiccups
|
||||
// we just don't show the sat estimate. The real quote runs
|
||||
// again inside useCheckout when the customer clicks pay.
|
||||
next[g.rid] = null
|
||||
}
|
||||
}
|
||||
|
|
@ -94,24 +114,20 @@ watch(
|
|||
{ immediate: true, deep: true }
|
||||
)
|
||||
|
||||
const placedOrders = ref<
|
||||
Array<{ orderId: string; restaurantSlug: string; placedAt: number; totalMsat: number; restaurantId: string }>
|
||||
>([])
|
||||
// ----------------------------------------------------------------- //
|
||||
// place phase //
|
||||
// ----------------------------------------------------------------- //
|
||||
|
||||
onMounted(() => {
|
||||
// If cart is empty (e.g. user landed here via back/forward), kick
|
||||
// them to /cart rather than showing an empty screen.
|
||||
if (!buckets.value.length) {
|
||||
if (!buckets.value.length && !state.value.placedOrders.length) {
|
||||
router.replace('/cart')
|
||||
}
|
||||
})
|
||||
|
||||
async function placeOrder() {
|
||||
async function onPlaceOrder() {
|
||||
try {
|
||||
const result = await checkout()
|
||||
// Persist the placed orders so the OrdersListPage (commit 7)
|
||||
// can render them.
|
||||
const entries = result.placedOrders.map((p) => ({
|
||||
await placeOrders()
|
||||
const entries = state.value.placedOrders.map((p) => ({
|
||||
orderId: p.order.id,
|
||||
restaurantId: p.restaurantId,
|
||||
restaurantSlug: p.restaurantSlug,
|
||||
|
|
@ -120,22 +136,120 @@ async function placeOrder() {
|
|||
}))
|
||||
if (storage && entries.length) {
|
||||
const existing =
|
||||
storage.getUserData<typeof entries>('restaurant.lastOrders.v1', []) ||
|
||||
[]
|
||||
storage.getUserData<typeof entries>(
|
||||
'restaurant.lastOrders.v1',
|
||||
[]
|
||||
) || []
|
||||
const merged = [...entries, ...existing].slice(0, 50)
|
||||
storage.setUserData('restaurant.lastOrders.v1', merged)
|
||||
}
|
||||
placedOrders.value = entries
|
||||
// Land on the first order's status page.
|
||||
if (entries.length) {
|
||||
router.push(`/orders/${entries[0].orderId}`)
|
||||
}
|
||||
} catch (err) {
|
||||
// state.value.step === 'error' and state.value.error already set
|
||||
// by useCheckout. View renders it below.
|
||||
console.warn('Checkout failed:', err)
|
||||
state.value.step = 'error'
|
||||
state.value.error = err instanceof Error ? err.message : String(err)
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------- //
|
||||
// pay phase + poller //
|
||||
// ----------------------------------------------------------------- //
|
||||
|
||||
const liveStatusByOrderId = ref<Record<string, string>>({})
|
||||
|
||||
function statusOf(orderId: string): string {
|
||||
return (
|
||||
liveStatusByOrderId.value[orderId] ||
|
||||
state.value.placedOrders.find((p) => p.order.id === orderId)?.order
|
||||
.status ||
|
||||
'pending'
|
||||
)
|
||||
}
|
||||
|
||||
function isPaid(orderId: string): boolean {
|
||||
const s = statusOf(orderId)
|
||||
return ['paid', 'accepted', 'ready', 'completed'].includes(s)
|
||||
}
|
||||
|
||||
const allPaid = computed(() => {
|
||||
if (!state.value.placedOrders.length) return false
|
||||
return state.value.placedOrders.every((p) => isPaid(p.order.id))
|
||||
})
|
||||
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
function startPolling() {
|
||||
if (pollTimer) return
|
||||
pollTimer = setInterval(async () => {
|
||||
if (!state.value.placedOrders.length) return
|
||||
for (const p of state.value.placedOrders) {
|
||||
if (isPaid(p.order.id)) continue
|
||||
try {
|
||||
const fresh = await api.getOrder(p.order.id)
|
||||
liveStatusByOrderId.value = {
|
||||
...liveStatusByOrderId.value,
|
||||
[p.order.id]: fresh.order.status,
|
||||
}
|
||||
if (
|
||||
['paid', 'accepted', 'ready', 'completed'].includes(
|
||||
fresh.order.status
|
||||
)
|
||||
) {
|
||||
cart.clearRestaurant(p.restaurantId)
|
||||
}
|
||||
} catch {
|
||||
// transient — try again next tick
|
||||
}
|
||||
}
|
||||
}, 3000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) {
|
||||
clearInterval(pollTimer)
|
||||
pollTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
watch(allPaid, (paid) => {
|
||||
if (paid && state.value.placedOrders.length) {
|
||||
stopPolling()
|
||||
setTimeout(() => {
|
||||
const first = state.value.placedOrders[0]
|
||||
if (first) router.push(`/orders/${first.order.id}`)
|
||||
}, 1200)
|
||||
}
|
||||
})
|
||||
|
||||
watch(
|
||||
() => state.value.placedOrders.length,
|
||||
(n) => {
|
||||
if (n > 0) startPolling()
|
||||
else stopPolling()
|
||||
}
|
||||
)
|
||||
|
||||
onUnmounted(stopPolling)
|
||||
|
||||
const isPlacing = computed(() =>
|
||||
['quoting', 'placing'].includes(state.value.step)
|
||||
)
|
||||
const isPaying = computed(() => state.value.step === 'paying')
|
||||
|
||||
async function onPayAll() {
|
||||
state.value.error = null
|
||||
try {
|
||||
await payAll()
|
||||
} catch {
|
||||
// useCheckout sets state.error already.
|
||||
}
|
||||
}
|
||||
|
||||
function startOver() {
|
||||
reset()
|
||||
}
|
||||
|
||||
function buildOrderInvoice(p: PlacedOrder) {
|
||||
return p.invoice
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
|
@ -144,7 +258,7 @@ async function placeOrder() {
|
|||
variant="ghost"
|
||||
size="sm"
|
||||
class="mb-3"
|
||||
:disabled="isSubmitting"
|
||||
:disabled="isPlacing || isPaying"
|
||||
@click="router.back()"
|
||||
>
|
||||
<ArrowLeft class="mr-2 h-4 w-4" />
|
||||
|
|
@ -153,99 +267,185 @@ async function placeOrder() {
|
|||
|
||||
<h1 class="mb-4 text-2xl font-bold text-foreground">Checkout</h1>
|
||||
|
||||
<div class="space-y-4">
|
||||
<Card v-for="b in buckets" :key="b.restaurantId">
|
||||
<CardHeader class="flex flex-row items-baseline justify-between space-y-0">
|
||||
<CardTitle class="text-base">{{ b.restaurantSlug }}</CardTitle>
|
||||
<span class="font-mono text-sm text-primary">
|
||||
{{ b.total ? fmt(b.total.amount, b.total.currency) : '—' }}
|
||||
</span>
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-1">
|
||||
<div
|
||||
v-for="line in b.lines"
|
||||
:key="line.line_id"
|
||||
class="flex items-center justify-between text-sm"
|
||||
>
|
||||
<span class="text-foreground">
|
||||
{{ line.quantity }}× {{ line.name }}
|
||||
<span
|
||||
v-if="line.selected_modifiers.length"
|
||||
class="text-muted-foreground"
|
||||
>
|
||||
· {{ line.selected_modifiers.map((m) => m.name).join(', ') }}
|
||||
<!-- Phase 1 — Review (before orders are placed) -->
|
||||
<template v-if="!state.placedOrders.length">
|
||||
<div class="space-y-4">
|
||||
<Card v-for="b in buckets" :key="b.restaurantId">
|
||||
<CardHeader class="flex flex-row items-baseline justify-between space-y-0">
|
||||
<CardTitle class="text-base">{{ b.restaurantSlug }}</CardTitle>
|
||||
<span class="font-mono text-sm text-primary">
|
||||
{{ b.total ? fmt(b.total.amount, b.total.currency) : '—' }}
|
||||
</span>
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-1">
|
||||
<div
|
||||
v-for="line in b.lines"
|
||||
:key="line.line_id"
|
||||
class="flex items-center justify-between text-sm"
|
||||
>
|
||||
<span class="text-foreground">
|
||||
{{ line.quantity }}× {{ line.name }}
|
||||
<span
|
||||
v-if="line.selected_modifiers.length"
|
||||
class="text-muted-foreground"
|
||||
>
|
||||
· {{ line.selected_modifiers.map((m) => m.name).join(', ') }}
|
||||
</span>
|
||||
</span>
|
||||
</span>
|
||||
<span class="font-mono text-xs text-muted-foreground">
|
||||
{{ fmt(line.unit_price * line.quantity, line.currency) }}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="previewSatPerRestaurant[b.restaurantId] != null"
|
||||
class="mt-1 flex items-center justify-end gap-1 text-xs text-muted-foreground"
|
||||
>
|
||||
<Zap class="h-3 w-3" />
|
||||
≈ {{ new Intl.NumberFormat().format(previewSatPerRestaurant[b.restaurantId]!) }} sat
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Separator class="my-6" />
|
||||
|
||||
<div class="space-y-3">
|
||||
<div v-if="cart.grandTotal" class="flex items-baseline justify-between">
|
||||
<span class="text-sm text-muted-foreground">Total</span>
|
||||
<span class="font-mono text-xl font-bold text-foreground">
|
||||
{{ fmt(cart.grandTotal.amount, cart.grandTotal.currency) }}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="previewSatTotal != null"
|
||||
class="flex items-center justify-between rounded-lg border border-border bg-muted/40 px-3 py-2 text-sm"
|
||||
>
|
||||
<span class="inline-flex items-center gap-1 text-muted-foreground">
|
||||
<Zap class="h-3.5 w-3.5" />
|
||||
Pay in sats
|
||||
</span>
|
||||
<span class="font-mono font-semibold text-foreground">
|
||||
≈ {{ new Intl.NumberFormat().format(previewSatTotal) }} sat
|
||||
</span>
|
||||
<span class="font-mono text-xs text-muted-foreground">
|
||||
{{ fmt(line.unit_price * line.quantity, line.currency) }}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="previewSatPerRestaurant[b.restaurantId] != null"
|
||||
class="mt-1 flex items-center justify-end gap-1 text-xs text-muted-foreground"
|
||||
>
|
||||
<Zap class="h-3 w-3" />
|
||||
≈ {{ new Intl.NumberFormat().format(previewSatPerRestaurant[b.restaurantId]!) }} sat
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Alert v-if="state.step === 'error' && state.error" variant="destructive">
|
||||
<AlertTitle>Checkout failed</AlertTitle>
|
||||
<AlertDescription>{{ state.error }}</AlertDescription>
|
||||
</Alert>
|
||||
<Separator class="my-6" />
|
||||
|
||||
<Alert v-if="state.step === 'done'" class="border-emerald-500/40">
|
||||
<div class="space-y-3">
|
||||
<div v-if="cart.grandTotal" class="flex items-baseline justify-between">
|
||||
<span class="text-sm text-muted-foreground">Total</span>
|
||||
<span class="font-mono text-xl font-bold text-foreground">
|
||||
{{ fmt(cart.grandTotal.amount, cart.grandTotal.currency) }}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
v-if="previewSatTotal != null"
|
||||
class="flex items-center justify-between rounded-lg border border-border bg-muted/40 px-3 py-2 text-sm"
|
||||
>
|
||||
<span class="inline-flex items-center gap-1 text-muted-foreground">
|
||||
<Zap class="h-3.5 w-3.5" />
|
||||
Pay in sats
|
||||
</span>
|
||||
<span class="font-mono font-semibold text-foreground">
|
||||
≈ {{ new Intl.NumberFormat().format(previewSatTotal) }} sat
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<Alert
|
||||
v-if="state.step === 'error' && state.error"
|
||||
variant="destructive"
|
||||
>
|
||||
<AlertTitle>Couldn't place order</AlertTitle>
|
||||
<AlertDescription>{{ state.error }}</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Button
|
||||
size="lg"
|
||||
class="w-full"
|
||||
:disabled="isPlacing || !buckets.length"
|
||||
@click="onPlaceOrder"
|
||||
>
|
||||
<Loader2 v-if="isPlacing" class="mr-2 h-4 w-4 animate-spin" />
|
||||
<span v-if="state.step === 'quoting'">Quoting…</span>
|
||||
<span v-else-if="state.step === 'placing'">Placing orders…</span>
|
||||
<span v-else>Place order</span>
|
||||
</Button>
|
||||
<p
|
||||
v-if="isPlacing && state.currentRestaurantSlug"
|
||||
class="text-center text-xs text-muted-foreground"
|
||||
>
|
||||
{{ state.currentRestaurantSlug }} ({{ state.progress.current + 1 }} of {{ state.progress.total }})
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Phase 2 — Pay (orders placed, invoice(s) to settle) -->
|
||||
<template v-else>
|
||||
<Alert v-if="allPaid" class="mb-4 border-emerald-500/40">
|
||||
<CheckCircle2 class="h-4 w-4 text-emerald-500" />
|
||||
<AlertTitle>Order placed</AlertTitle>
|
||||
<AlertDescription>Redirecting to status…</AlertDescription>
|
||||
<AlertTitle>Payment received</AlertTitle>
|
||||
<AlertDescription>Redirecting to your order…</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Button
|
||||
size="lg"
|
||||
class="w-full"
|
||||
:disabled="isSubmitting || !buckets.length"
|
||||
@click="placeOrder"
|
||||
>
|
||||
<Loader2
|
||||
v-if="isSubmitting"
|
||||
class="mr-2 h-4 w-4 animate-spin"
|
||||
/>
|
||||
<span v-if="state.step === 'quoting'">Quoting…</span>
|
||||
<span v-else-if="state.step === 'placing'">Placing orders…</span>
|
||||
<span v-else-if="state.step === 'paying'">Paying invoices…</span>
|
||||
<span v-else-if="state.step === 'done'">Done</span>
|
||||
<span v-else>Pay & place order</span>
|
||||
</Button>
|
||||
<p
|
||||
v-if="isSubmitting && state.currentRestaurantSlug"
|
||||
class="text-center text-xs text-muted-foreground"
|
||||
>
|
||||
{{ state.currentRestaurantSlug }} ({{ state.progress.current + 1 }} of {{ state.progress.total }})
|
||||
<p v-if="!allPaid" class="mb-4 text-sm text-muted-foreground">
|
||||
Scan with any Lightning wallet, or tap the button below to
|
||||
pay from your LNbits wallet.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div
|
||||
v-for="placed in state.placedOrders"
|
||||
:key="placed.order.id"
|
||||
>
|
||||
<div class="mb-2 flex items-center justify-between">
|
||||
<span class="text-sm font-semibold text-foreground">
|
||||
{{ placed.restaurantSlug }}
|
||||
</span>
|
||||
<Badge
|
||||
:variant="isPaid(placed.order.id) ? 'default' : 'outline'"
|
||||
class="text-xs"
|
||||
>
|
||||
{{ statusOf(placed.order.id) }}
|
||||
</Badge>
|
||||
</div>
|
||||
<OrderInvoiceCard
|
||||
v-if="buildOrderInvoice(placed) && !isPaid(placed.order.id)"
|
||||
:invoice="buildOrderInvoice(placed)!"
|
||||
/>
|
||||
<Alert
|
||||
v-else-if="isPaid(placed.order.id)"
|
||||
class="border-emerald-500/40"
|
||||
>
|
||||
<CheckCircle2 class="h-4 w-4 text-emerald-500" />
|
||||
<AlertTitle>Paid</AlertTitle>
|
||||
<AlertDescription>
|
||||
<Button
|
||||
variant="link"
|
||||
class="h-auto p-0"
|
||||
@click="router.push(`/orders/${placed.order.id}`)"
|
||||
>
|
||||
View order →
|
||||
</Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
<Card v-else>
|
||||
<CardContent class="p-4 text-sm text-muted-foreground">
|
||||
No Lightning invoice — payment is handled out-of-band.
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator class="my-6" />
|
||||
|
||||
<div class="space-y-3">
|
||||
<Alert v-if="state.error" variant="destructive">
|
||||
<AlertTitle>Payment didn't go through</AlertTitle>
|
||||
<AlertDescription>
|
||||
{{ state.error }} You can still scan the QR with another
|
||||
wallet.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<Button
|
||||
v-if="!allPaid"
|
||||
size="lg"
|
||||
class="w-full"
|
||||
:disabled="isPaying"
|
||||
@click="onPayAll"
|
||||
>
|
||||
<Loader2 v-if="isPaying" class="mr-2 h-4 w-4 animate-spin" />
|
||||
<Zap v-else class="mr-2 h-4 w-4" />
|
||||
Pay from my LNbits wallet
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
v-if="!allPaid"
|
||||
variant="ghost"
|
||||
class="w-full text-xs text-muted-foreground"
|
||||
@click="startOver"
|
||||
>
|
||||
Cancel and start over
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
</main>
|
||||
</template>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue