@aglyn/plugins-commerce 1.31.0 → 1.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/README.md +4 -0
  2. package/package.json +13 -13
  3. package/src/lib/components/cart.js +35 -15
  4. package/src/lib/components/cart.js.map +1 -1
  5. package/src/lib/components/commerce-console-page.js +6 -0
  6. package/src/lib/components/commerce-console-page.js.map +1 -1
  7. package/src/lib/components/console/currencies-card.component.d.ts +21 -0
  8. package/src/lib/components/console/currencies-card.component.js +408 -0
  9. package/src/lib/components/console/currencies-card.component.js.map +1 -0
  10. package/src/lib/components/console/product-add-ons-fields.component.d.ts +13 -0
  11. package/src/lib/components/console/product-add-ons-fields.component.js +74 -2
  12. package/src/lib/components/console/product-add-ons-fields.component.js.map +1 -1
  13. package/src/lib/components/console/product-editor-dialog.component.js +42 -1
  14. package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
  15. package/src/lib/components/console/product-fixed-prices-fields.component.d.ts +25 -0
  16. package/src/lib/components/console/product-fixed-prices-fields.component.js +112 -0
  17. package/src/lib/components/console/product-fixed-prices-fields.component.js.map +1 -0
  18. package/src/lib/components/console/reservations-card.component.js +32 -15
  19. package/src/lib/components/console/reservations-card.component.js.map +1 -1
  20. package/src/lib/components/console/shipping-settings-card.component.js +100 -1
  21. package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
  22. package/src/lib/components/console/store-settings-card.component.js +1 -1
  23. package/src/lib/components/console/store-settings-card.component.js.map +1 -1
  24. package/src/lib/components/console/use-currency-setup.d.ts +20 -0
  25. package/src/lib/components/console/use-currency-setup.js +61 -0
  26. package/src/lib/components/console/use-currency-setup.js.map +1 -0
  27. package/src/lib/components/currency-selector.d.ts +36 -0
  28. package/src/lib/components/currency-selector.js +157 -0
  29. package/src/lib/components/currency-selector.js.map +1 -0
  30. package/src/lib/components/product-add-ons.d.ts +9 -1
  31. package/src/lib/components/product-add-ons.js +8 -4
  32. package/src/lib/components/product-add-ons.js.map +1 -1
  33. package/src/lib/components/product-choice-cards.d.ts +13 -1
  34. package/src/lib/components/product-choice-cards.js +5 -4
  35. package/src/lib/components/product-choice-cards.js.map +1 -1
  36. package/src/lib/components/product-detail.d.ts +8 -0
  37. package/src/lib/components/product-detail.js +38 -11
  38. package/src/lib/components/product-detail.js.map +1 -1
  39. package/src/lib/components/product-grid.d.ts +2 -0
  40. package/src/lib/components/product-grid.js +22 -9
  41. package/src/lib/components/product-grid.js.map +1 -1
  42. package/src/lib/components/related-products.js +6 -2
  43. package/src/lib/components/related-products.js.map +1 -1
  44. package/src/lib/components/shopper-currency.d.ts +108 -0
  45. package/src/lib/components/shopper-currency.js +262 -0
  46. package/src/lib/components/shopper-currency.js.map +1 -0
  47. package/src/lib/components/wishlist.js +7 -1
  48. package/src/lib/components/wishlist.js.map +1 -1
  49. package/src/lib/declarations.server.js +39 -0
  50. package/src/lib/declarations.server.js.map +1 -1
  51. package/src/lib/model/commerce-currency-setup.d.ts +79 -0
  52. package/src/lib/model/commerce-currency-setup.js +124 -0
  53. package/src/lib/model/commerce-currency-setup.js.map +1 -0
  54. package/src/lib/model/commerce-currency.d.ts +215 -0
  55. package/src/lib/model/commerce-currency.js +511 -0
  56. package/src/lib/model/commerce-currency.js.map +1 -0
  57. package/src/lib/model/commerce-orders.d.ts +17 -0
  58. package/src/lib/model/commerce-orders.js +10 -5
  59. package/src/lib/model/commerce-orders.js.map +1 -1
  60. package/src/lib/model/commerce-record-routes.js +26 -1
  61. package/src/lib/model/commerce-record-routes.js.map +1 -1
  62. package/src/lib/model/commerce-reservations.d.ts +6 -0
  63. package/src/lib/model/commerce-reservations.js.map +1 -1
  64. package/src/lib/model/commerce-shipping.d.ts +22 -1
  65. package/src/lib/model/commerce-shipping.js +31 -2
  66. package/src/lib/model/commerce-shipping.js.map +1 -1
  67. package/src/lib/model/commerce.d.ts +6 -0
  68. package/src/lib/model/commerce.js.map +1 -1
  69. package/src/lib/model/index.d.ts +2 -0
  70. package/src/lib/model/index.js +2 -0
  71. package/src/lib/model/index.js.map +1 -1
  72. package/src/lib/model/order-figures.js +9 -2
  73. package/src/lib/model/order-figures.js.map +1 -1
  74. package/src/lib/model/product-modifiers.d.ts +5 -0
  75. package/src/lib/model/product-modifiers.js.map +1 -1
  76. package/src/lib/server/billing-webhook.js +37 -24
  77. package/src/lib/server/billing-webhook.js.map +1 -1
  78. package/src/lib/server/cart-checkout.js +67 -11
  79. package/src/lib/server/cart-checkout.js.map +1 -1
  80. package/src/lib/server/cart.d.ts +12 -0
  81. package/src/lib/server/cart.js +50 -4
  82. package/src/lib/server/cart.js.map +1 -1
  83. package/src/lib/server/catalog.d.ts +5 -0
  84. package/src/lib/server/catalog.js +7 -0
  85. package/src/lib/server/catalog.js.map +1 -1
  86. package/src/lib/server/checkout.js +48 -12
  87. package/src/lib/server/checkout.js.map +1 -1
  88. package/src/lib/server/currency.d.ts +93 -0
  89. package/src/lib/server/currency.js +182 -0
  90. package/src/lib/server/currency.js.map +1 -0
  91. package/src/lib/server/order-notifications.js +4 -2
  92. package/src/lib/server/order-notifications.js.map +1 -1
  93. package/src/lib/server/product.d.ts +9 -0
  94. package/src/lib/server/product.js +12 -0
  95. package/src/lib/server/product.js.map +1 -1
  96. package/src/lib/server/refund.js +3 -3
  97. package/src/lib/server/refund.js.map +1 -1
  98. package/src/lib/server/site-chat-tools.d.ts +22 -0
  99. package/src/lib/server/site-chat-tools.js +369 -0
  100. package/src/lib/server/site-chat-tools.js.map +1 -0
  101. package/src/lib/server/site-chat-visitor.d.ts +24 -0
  102. package/src/lib/server/site-chat-visitor.js +39 -0
  103. package/src/lib/server/site-chat-visitor.js.map +1 -0
  104. package/src/lib/server/site-offers.d.ts +31 -0
  105. package/src/lib/server/site-offers.js +91 -0
  106. package/src/lib/server/site-offers.js.map +1 -0
  107. package/src/lib/server/stays-site-search.d.ts +20 -0
  108. package/src/lib/server/stays-site-search.js +78 -0
  109. package/src/lib/server/stays-site-search.js.map +1 -0
  110. package/src/lib/server.js +20 -0
  111. package/src/lib/server.js.map +1 -1
  112. package/src/lib/site-chat-tool-definitions.d.ts +26 -0
  113. package/src/lib/site-chat-tool-definitions.js +141 -0
  114. package/src/lib/site-chat-tool-definitions.js.map +1 -0
  115. package/src/lib/site.js +8 -0
  116. package/src/lib/site.js.map +1 -1
  117. package/src/lib/subprocessors.js +7 -0
  118. package/src/lib/subprocessors.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/reservations-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport * as CommerceModel from '../../model'\nimport { reservationPermissionRefusal } from '../../model/plugin-permissions'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n deleteDoc,\n doc,\n getDocs,\n limit,\n orderBy,\n query,\n setDoc,\n updateDoc,\n where,\n} from 'firebase/firestore'\nimport { lazy, Suspense, useCallback, useMemo, useState } from 'react'\nimport { useFirestore, useMerchantPayments, useUser } from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { PrerequisiteNotice } from '@aglyn/shared-ui-jsx/components/prerequisite-notice.component'\nimport {\n useFirestoreCollection,\n usePagedCollection,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n heldSaveLabel,\n isSeedChecking,\n seedCheckingText,\n useHeldSave,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { useSeedDraft } from '@aglyn/tenant-feature-instance/hooks/use-seed-draft'\n\nexport interface ReservationsCardProps {\n hostId: string\n /**\n * \"Manage reservations\" (`commerce.reservations`, AGL-4047) on this site:\n * edit, cancel and check out stays and change what can be booked. The rules\n * decide it; this only disables the controls with the reason. Absent reads\n * as held, so a surface that does not pass it shows the card as before.\n */\n canManage?: boolean\n /** \"Book walk-ins and change guests\" (`commerce.walkIns`), which the routes ask. */\n canWalkIn?: boolean\n}\n\n/** A stay's guest count after booking (AGL-4043), loaded the first time it opens. */\nconst ReservationGuestsDialog = lazy(() => import('./reservation-guests-dialog.component'))\n\n/** The statuses whose guest count staff can still change. */\nconst GUESTS_OPEN_STATUSES = ['pending', 'confirmed', 'checked_in']\n\nconst STATUS_COLOR: Record<\n string,\n 'default' | 'success' | 'warning' | 'error' | 'info'\n> = {\n pending: 'warning',\n confirmed: 'info',\n checked_in: 'success',\n checked_out: 'default',\n cancelled: 'default',\n no_show: 'error',\n}\n\nconst usd = (cents: number | undefined) =>\n `$${((cents ?? 0) / 100).toFixed(2)}`\nconst day = (dayMs: number | undefined) =>\n dayMs ? new Date(dayMs).toISOString().slice(0, 10) : '—'\nconst nightLabel = (dayMs: number) =>\n new Date(dayMs).toLocaleDateString('en-US', {\n weekday: 'short',\n month: 'short',\n day: 'numeric',\n timeZone: 'UTC',\n })\n\n/** The Reservations card's look-ahead for a several-unit resource. */\nconst UNITS_LOOKAHEAD_NIGHTS = 14\n\n/** The desk's calendar day as the UTC-midnight `dayMs` stays are stored in. */\nfunction localTodayDayMs(): number {\n const now = new Date()\n return Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())\n}\n\n/** The units field's problem, or null when the typed value is a valid count. */\nfunction unitsProblem(units: number | undefined): string | null {\n if (units === undefined) return null\n if (\n !Number.isInteger(units) ||\n units < 1 ||\n units > CommerceModel.MAX_RESOURCE_UNITS\n ) {\n return `A whole number from 1 to ${CommerceModel.MAX_RESOURCE_UNITS}`\n }\n return null\n}\n\n/**\n * The \"Only N left\" field's problem (AGL-4044), or null when the typed value\n * is a valid threshold: 0 (never) up to the most units a resource can hold.\n */\nfunction fewLeftAtProblem(fewLeftAt: number | undefined): string | null {\n if (fewLeftAt === undefined) return null\n if (\n !Number.isInteger(fewLeftAt) ||\n fewLeftAt < 0 ||\n fewLeftAt > CommerceModel.MAX_RESOURCE_UNITS\n ) {\n return `A whole number from 0 to ${CommerceModel.MAX_RESOURCE_UNITS}`\n }\n return null\n}\n\n/**\n * Reservations console (AGL-311): resources CRUD (nightly pricing,\n * seasons via multipliers, deposits) plus the reservations list with\n * check-in/out, no-show, cancel, and walk-in creation. The storefront\n * widget books against the same docs.\n */\nexport function ReservationsCard(props: ReservationsCardProps) {\n const { hostId, canManage = true, canWalkIn = true } = props\n // The permissions this member lacks here, named, for the line under the\n // card's actions (AGL-4047): a disabled control says why.\n const missing = [\n ...(canManage ? [] : [reservationPermissionRefusal('commerce.reservations')]),\n ...(canWalkIn ? [] : [reservationPermissionRefusal('commerce.walkIns')]),\n ]\n // Every reservation is paid when it is booked, so a store that cannot\n // charge turns each guest away; the card says so up front.\n const payments = useMerchantPayments(hostId)\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const {\n data: resourceDocs,\n status: resourcesStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing spreads a whole stored resource into\n * `resourceDraft` and writes all of it back, so `merge: true` protects\n * nothing. `blocks` is the field that costs more than money: it is the\n * manually blocked date ranges `isRangeAvailable` reads, so a cached seed\n * re-opens dates that were closed and lets the next guest book a room\n * that is already spoken for.\n */\n fromCache: resourcesFromCache,\n listen: resourcesListen,\n } = useFirestoreCollection<any>(\n () => query(collection(firestore, 'hosts', hostId, 'resources'), limit(50)),\n [firestore, hostId],\n { idField: '$id' },\n )\n /*\n * Ordered by the server, and a growing window rather than a fixed 300.\n *\n * `limit(300)` carried no `orderBy`, so Firestore returned DOCUMENT-ID\n * order and the client sort below arranged that pseudo-random sample by\n * check-in. The ordering is unchanged — earliest check-in first, exactly\n * what the sort did — it is now the QUERY's, so the window is the real\n * front of the list and the rest can be reached.\n */\n const {\n rows: reservations,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n } = usePagedCollection<any>(\n (pageLimit) =>\n query(\n collection(firestore, 'hosts', hostId, 'reservations'),\n orderBy('checkInDayMs', 'asc'),\n limit(pageLimit),\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n /*\n * Units left on each of the next nights, for resources with several units\n * (AGL-4044). One listen across the site's resources, on the stays that\n * have not ended, nearest check-out first: a range and an order on the same\n * field, which Firestore's automatic single-field index serves. Not read at\n * all while every resource has one unit, so a cabin-only site pays nothing.\n *\n * The 500 cap is the booking door's: it can only leave out stays that end\n * after 500 others that are all still running, which would be a stay far\n * past the two weeks this draws.\n */\n const hasSeveralUnits = (resourceDocs ?? []).some(\n (resource: any) => CommerceModel.resourceUnits(resource) > 1,\n )\n const todayDayMs = localTodayDayMs()\n const { data: currentStays } = useFirestoreCollection<any>(\n () =>\n hasSeveralUnits\n ? query(\n collection(firestore, 'hosts', hostId, 'reservations'),\n where('checkOutDayMs', '>', todayDayMs),\n orderBy('checkOutDayMs'),\n limit(500),\n )\n : null,\n [firestore, hostId, hasSeveralUnits, todayDayMs],\n { idField: '$id' },\n )\n const unitsAhead = useMemo(() => {\n const byResource: Record<string, CommerceModel.ResourceNightUnits[]> = {}\n if (!hasSeveralUnits) return byResource\n const nowMs = Date.now()\n for (const resource of resourceDocs ?? []) {\n if (CommerceModel.resourceUnits(resource) === 1) continue\n const stays = (currentStays ?? [])\n .filter((stay: any) => stay.resourceId === resource.$id)\n .map((stay: any) => ({\n checkInDayMs: Number(stay.checkInDayMs),\n checkOutDayMs: Number(stay.checkOutDayMs),\n status: stay.status as CommerceModel.ReservationStatus,\n createdAtMs: Number(stay.createdAtMs ?? 0),\n }))\n byResource[resource.$id] = CommerceModel.unitsLeftByNight(\n resource,\n stays,\n todayDayMs,\n UNITS_LOOKAHEAD_NIGHTS,\n nowMs,\n )\n }\n return byResource\n }, [hasSeveralUnits, resourceDocs, currentStays, todayDayMs])\n\n const resourceNames = useMemo(() => {\n const map: Record<string, string> = {}\n for (const resource of resourceDocs ?? []) {\n map[resource.$id] = resource.name\n }\n return map\n }, [resourceDocs])\n\n /*\n * The dialog's draft, kept as EDITS over the resource as the list has it\n * now (AGL-4047): opened from the cache's row, the server's copy replaces\n * it under every field nobody touched (`blocks` among them), and Save is\n * held until it has.\n */\n const [resourceDraft, setResourceDraft] = useSeedDraft<\n Partial<CommerceModel.HostResource> & { id: string | null }\n >((opened) => {\n const row = opened.id\n ? resourceDocs?.find((resource: any) => resource.$id === opened.id)\n : undefined\n return row ? { id: row.$id, ...row } : undefined\n })\n const resourceChecking =\n Boolean(resourceDraft?.id) &&\n isSeedChecking({\n fromCache: resourcesFromCache,\n unreadable: resourcesStatus === 'error',\n })\n const [walkIn, setWalkIn] = useState<{\n resourceId: string\n checkIn: string\n checkOut: string\n guestName: string\n /** How many guests (AGL-4043); '' sends none. */\n guests: string\n /** One walk-in attempt: a retry of it finds its own stay (AGL-4046). */\n attemptId: string\n } | null>(null)\n const [walkInBusy, setWalkInBusy] = useState(false)\n /** The stay whose guests are being changed (AGL-4043). */\n const [guestsFor, setGuestsFor] = useState<string | null>(null)\n\n const handleResourceSave = useCallback(async () => {\n if (!resourceDraft?.name?.trim() || !(resourceDraft.nightlyRateUsd! > 0)) {\n return\n }\n /**\n * `$id` comes off with `id` (AGL-1374).\n *\n * The editor is seeded `{ id: resource.$id, ...resource }`, and that\n * spread carries the listener's SYNTHETIC `$id` — `idField: '$id'`\n * stamps the document id onto the in-memory row, where nothing persists\n * it. Destructuring only `id` left `$id` in `data`, so every save wrote\n * it into the stored document as a real field. Nothing reads it; it is\n * the listener's bookkeeping leaking into storage, and once there no\n * reader can tell it from a field the card meant to write.\n */\n if (unitsProblem(resourceDraft.units)) return\n if (fewLeftAtProblem(resourceDraft.fewLeftAt)) return\n const seeded = resourceDraft as typeof resourceDraft & { $id?: string }\n const { id, $id: _syntheticId, units, fewLeftAt, ...fields } = seeded\n // Units are written as the count the model reads (AGL-4044), and a\n // cleared field as 1 rather than left out: `merge: true` would otherwise\n // keep a stored 12 the merchant just removed. The \"Only N left\" threshold\n // the same way: a cleared field is written as the default it reads as.\n const data = {\n ...fields,\n ...('units' in seeded ? { units: CommerceModel.resourceUnits({ units }) } : {}),\n ...('fewLeftAt' in seeded\n ? { fewLeftAt: CommerceModel.resourceFewLeftAt({ fewLeftAt }) }\n : {}),\n }\n /**\n * Refuse an EDIT whose seed the server never confirmed (AGL-1358).\n * `data` is the whole stored row spread out of the listener, so\n * `merge: true` has nothing left to protect — every field is present,\n * `blocks` and the seasonal multipliers included.\n *\n * Only the edit path. A NEW resource is built from defaults at a fresh\n * uid and can overwrite nothing, and the first snapshot of any listener\n * is `fromCache: true`, so guarding a create would refuse a save that was\n * never unsafe.\n *\n * The guard WRAPS the write — an early return is a shape you can keep\n * while losing the protection.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'resource',\n unreadable: Boolean(id) && resourcesStatus === 'error',\n fromCache: Boolean(id) && resourcesFromCache,\n listen: resourcesListen,\n },\n async () => {\n await setDoc(\n doc(\n firestore,\n 'hosts',\n hostId,\n 'resources',\n id ?? Aglyn.createResourceUid(),\n ),\n {\n ...data,\n name: resourceDraft.name!.trim().slice(0, 120),\n },\n { merge: true },\n )\n },\n )\n // Before `setResourceDraft(null)`, so a refusal keeps the dialog open\n // with what was typed.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setResourceDraft(null)\n enqueueSnackbar('Resource saved', { variant: 'success', persist: false })\n }, [\n setResourceDraft,\n resourceDraft,\n firestore,\n hostId,\n enqueueSnackbar,\n resourcesStatus,\n resourcesFromCache,\n resourcesListen,\n ])\n\n const handleStatus = useCallback(\n (reservation: any, status: CommerceModel.ReservationStatus) => async () => {\n await updateDoc(\n doc(firestore, 'hosts', hostId, 'reservations', reservation.$id),\n { status },\n )\n },\n [firestore, hostId],\n )\n\n const handleWalkIn = useCallback(async () => {\n if (!walkIn?.resourceId || !walkIn.checkIn || !walkIn.checkOut) return\n const resource = (resourceDocs ?? []).find(\n (item: any) => item.$id === walkIn.resourceId,\n ) as CommerceModel.HostResource | undefined\n if (!resource) return\n const checkInDayMs = Date.parse(`${walkIn.checkIn}T00:00:00Z`)\n const checkOutDayMs = Date.parse(`${walkIn.checkOut}T00:00:00Z`)\n const guests = walkIn.guests.trim() ? Number(walkIn.guests) : undefined\n const guestsProblem = CommerceModel.reservationGuestsProblem(guests, resource)\n if (guestsProblem) {\n return void enqueueSnackbar(guestsProblem, { variant: 'warning', persist: false })\n }\n /*\n * The stay is priced FIRST, and its `problem` stops the walk-in: the quote\n * is the one rule for what can be booked (no nights, under the minimum\n * stay), shared with the booking widget and both native apps. Ignoring it\n * wrote a confirmed zero-night, $0 stay for a check-out on the arrival\n * day (AGL-3794).\n */\n const quote = CommerceModel.computeReservationQuote(\n resource,\n checkInDayMs,\n checkOutDayMs,\n )\n if (quote.problem) {\n return void enqueueSnackbar(quote.problem, {\n variant: 'warning',\n persist: false,\n })\n }\n /*\n * Every stay of THIS resource that ends after the walk-in arrives — the\n * same query `reserve.ts` checks a booking against, on the composite it\n * already has (AGL-3321). This used to test the rows on the card's\n * current page, so a stay on the next page did not block the dates and\n * the desk could double-book the room.\n */\n const overlapping = await getDocs(\n query(\n collection(firestore, 'hosts', hostId, 'reservations'),\n where('resourceId', '==', walkIn.resourceId),\n where('checkOutDayMs', '>', checkInDayMs),\n orderBy('checkOutDayMs'),\n limit(500),\n ),\n ).catch(() => null)\n if (!overlapping) {\n return void enqueueSnackbar('Could not check those dates — try again', {\n variant: 'warning',\n persist: false,\n })\n }\n // `createdAtMs` carried through because the pending hold lapses on it\n // (`reservationHoldsDates`). Dropping it made every unpaid `pending` row\n // block forever, so the front desk was refused a walk-in into a room that\n // an abandoned online checkout had left empty.\n const existing = overlapping.docs\n .map((snapshot) => snapshot.data() as any)\n .map((item: any) => ({\n checkInDayMs: item.checkInDayMs,\n checkOutDayMs: item.checkOutDayMs,\n status: item.status,\n createdAtMs: item.createdAtMs,\n }))\n // Count-based for a several-unit resource (AGL-4044): the walk-in takes\n // any unit that is free on every night, and is refused only when some\n // night has none left.\n if (\n !CommerceModel.isRangeAvailable(resource, existing, checkInDayMs, checkOutDayMs)\n ) {\n const message =\n CommerceModel.resourceUnits(resource) > 1\n ? 'Every unit is taken on at least one of those nights'\n : 'Those dates are taken'\n return void enqueueSnackbar(message, {\n variant: 'warning',\n persist: false,\n })\n }\n /*\n * The check above is the instant answer; the WRITE goes through\n * `/api/commerce/reservations/walk-in` (AGL-4046), which re-asks the same\n * question inside the transaction that books the stay. A client\n * read-then-write let two staff on two devices both take the last unit.\n */\n setWalkInBusy(true)\n try {\n const response = await authorizedFetch(\n user,\n '/api/commerce/reservations/walk-in',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId,\n resourceId: walkIn.resourceId,\n checkInDayMs,\n checkOutDayMs,\n guestName: walkIn.guestName || undefined,\n ...(guests !== undefined ? { guests } : {}),\n reservationId: walkIn.attemptId,\n }),\n },\n )\n const answer = await response.json().catch(() => ({}))\n if (!response.ok) {\n return void enqueueSnackbar(\n answer?.error ?? 'Could not reserve the walk-in — try again',\n {\n variant: response.status === 409 || response.status === 400\n ? 'warning'\n : 'error',\n persist: false,\n },\n )\n }\n } catch {\n return void enqueueSnackbar('Could not reserve the walk-in — try again', {\n variant: 'error',\n persist: false,\n })\n } finally {\n setWalkInBusy(false)\n }\n setWalkIn(null)\n enqueueSnackbar('Walk-in reserved — collect payment at POS', {\n variant: 'success',\n persist: false,\n })\n }, [walkIn, resourceDocs, firestore, hostId, user, enqueueSnackbar])\n\n // A press while Save is held is kept, and saves once confirmed (AGL-4047).\n const resourceHeld = useHeldSave(handleResourceSave, {\n checking: resourceChecking,\n subject: 'resource',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\n\n return (\n <CardDisplay\n header={'Reservations'}\n help={pluginDocsHelp('pos', { anchor: '#reservations' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {payments.blocked ? (\n <PrerequisiteNotice severity=\"warning\" href={payments.href ?? undefined} actionLabel=\"Open Payments\">\n {`${payments.reason ?? ''} Guests pay when they reserve, so they can't reserve until it is set up.`}\n </PrerequisiteNotice>\n ) : null}\n <Typography variant=\"subtitle2\">{'Resources'}</Typography>\n {(resourceDocs ?? []).map((resource: any) => (\n <Stack key={resource.$id} spacing={0.5}>\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {[\n resource.name,\n `$${resource.nightlyRateUsd}/night`,\n ...(CommerceModel.resourceUnits(resource) > 1\n ? [`${CommerceModel.resourceUnits(resource)} units`]\n : []),\n ].join(' · ')}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`id: ${resource.$id}`}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n disabled={!canManage}\n onClick={() => setResourceDraft({ id: resource.$id, ...resource })}\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n disabled={!canManage}\n onClick={async () => {\n const confirmed = await confirm({\n title: 'Remove this resource?',\n description:\n 'Existing reservations keep their records; the widget ' +\n 'stops accepting new stays.',\n confirmationText: 'Remove',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await deleteDoc(\n doc(firestore, 'hosts', hostId, 'resources', resource.$id),\n )\n }}\n >\n {'Remove'}\n </Button>\n </Stack>\n {unitsAhead[resource.$id] ? (\n <Stack\n direction=\"row\"\n useFlexGap\n aria-label={`Units left on the next ${UNITS_LOOKAHEAD_NIGHTS} nights`}\n sx={{ flexWrap: 'wrap', gap: 0.5 }}\n >\n {unitsAhead[resource.$id].map((night) => (\n <Chip\n key={night.dayMs}\n size=\"small\"\n variant=\"outlined\"\n color={\n night.unitsLeft === 0\n ? 'error'\n : night.unitsLeft <=\n CommerceModel.resourceFewLeftAt(resource)\n ? 'warning'\n : 'default'\n }\n label={`${nightLabel(night.dayMs)} · ${night.unitsLeft} of ${night.units} left`}\n />\n ))}\n </Stack>\n ) : null}\n </Stack>\n ))}\n <Stack direction=\"row\" spacing={1}>\n <Button\n size=\"small\"\n disabled={!canManage}\n onClick={() =>\n setResourceDraft({\n id: null,\n name: '',\n nightlyRateUsd: 100,\n depositPct: 30,\n minNights: 1,\n })\n }\n >\n {'Add resource'}\n </Button>\n <Button\n size=\"small\"\n disabled={!canWalkIn || (resourceDocs?.length ?? 0) === 0}\n onClick={() =>\n setWalkIn({\n resourceId: resourceDocs?.[0]?.$id ?? '',\n checkIn: '',\n checkOut: '',\n guestName: '',\n guests: '',\n attemptId: Aglyn.createResourceUid(),\n })\n }\n >\n {'Walk-in'}\n </Button>\n </Stack>\n {missing.map((reason) => (\n <Typography key={reason} variant=\"caption\" color=\"text.secondary\">\n {reason}\n </Typography>\n ))}\n\n <Typography variant=\"subtitle2\" sx={{ mt: 1 }}>\n {'Upcoming & recent stays'}\n </Typography>\n {reservations.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Reservations from the widget (and walk-ins) appear here.'}\n </Typography>\n ) : (\n reservations.map((reservation: any) => (\n <Stack\n key={reservation.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {`${resourceNames[reservation.resourceId] ?? '?'} · ` +\n `${day(reservation.checkInDayMs)} → ${day(reservation.checkOutDayMs)}`}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {[\n reservation.guestName ?? reservation.guestEmail ?? 'Guest',\n ...(reservation.guests\n ? [`${CommerceModel.reservationGuests(reservation)} guest${CommerceModel.reservationGuests(reservation) === 1 ? '' : 's'}`]\n : []),\n `${usd(reservation.paidCents)} / ${usd(reservation.totalCents)} paid`,\n ].join(' · ')}\n </Typography>\n </Stack>\n <Chip\n label={String(reservation.status).replace('_', ' ')}\n size=\"small\"\n variant=\"outlined\"\n color={STATUS_COLOR[reservation.status] ?? 'default'}\n />\n {reservation.status === 'confirmed' ? (\n <>\n <Button size=\"small\" disabled={!canManage} onClick={handleStatus(reservation, 'checked_in')}>\n {'Check in'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n disabled={!canManage}\n onClick={handleStatus(reservation, 'no_show')}\n >\n {'No-show'}\n </Button>\n </>\n ) : null}\n {reservation.status === 'checked_in' ? (\n <Button\n size=\"small\"\n disabled={!canManage}\n onClick={async () => {\n // Folio settlement (AGL-317): surface unpaid room\n // charges before the guest leaves.\n const folio = (reservation.folio ?? []) as Array<{\n amountCents: number\n }>\n const folioCents = folio.reduce(\n (sum, entry) => sum + (entry.amountCents ?? 0),\n 0,\n )\n const balanceCents =\n (reservation.totalCents ?? 0) -\n (reservation.paidCents ?? 0)\n if (folioCents > 0 || balanceCents > 0) {\n const confirmed = await confirm({\n title: 'Check out with open balance?',\n description:\n `${folioCents > 0 ? `Room charges: ${usd(folioCents)} (already recorded as paid POS orders). ` : ''}` +\n `${balanceCents > 0 ? `Stay balance due: ${usd(balanceCents)} — collect at the register.` : ''}`,\n confirmationText: 'Check out',\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n }\n await handleStatus(reservation, 'checked_out')()\n }}\n >\n {'Check out'}\n </Button>\n ) : null}\n {GUESTS_OPEN_STATUSES.includes(reservation.status) ? (\n <Button size=\"small\" disabled={!canWalkIn} onClick={() => setGuestsFor(reservation.$id)}>\n {'Guests'}\n </Button>\n ) : null}\n {['pending', 'confirmed'].includes(reservation.status) ? (\n <Button\n size=\"small\"\n color=\"error\"\n disabled={!canManage}\n onClick={handleStatus(reservation, 'cancelled')}\n >\n {'Cancel'}\n </Button>\n ) : null}\n </Stack>\n ))\n )}\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={reservations.length}\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n </Stack>\n\n {guestsFor ? (\n <Suspense fallback={null}>\n <ReservationGuestsDialog\n reservationId={guestsFor}\n hostId={hostId}\n onClose={() => setGuestsFor(null)}\n onDone={(answer) => {\n setGuestsFor(null)\n enqueueSnackbar(\n answer.unchanged\n ? `Still ${answer.guests} guest${answer.guests === 1 ? '' : 's'}`\n : `Guests changed to ${answer.guests}`,\n { variant: 'success', persist: false },\n )\n }}\n />\n </Suspense>\n ) : null}\n\n <Dialog\n open={Boolean(resourceDraft)}\n onClose={() => setResourceDraft(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>\n {resourceDraft?.id ? 'Edit resource' : 'New resource'}\n </DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <TextField\n label=\"Name\"\n value={resourceDraft?.name ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev ? { ...prev, name: event.target.value } : prev,\n )\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n placeholder=\"Lakeside cabin\"\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Spots or units available\"\n placeholder=\"1\"\n value={resourceDraft?.units ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n units:\n event.target.value.replace(/\\D/g, '') === ''\n ? undefined\n : Number(event.target.value.replace(/\\D/g, '')),\n }\n : prev,\n )\n }\n error={Boolean(unitsProblem(resourceDraft?.units))}\n helperText={\n unitsProblem(resourceDraft?.units) ??\n 'How many identical ones you have, like 12 RV hookups'\n }\n size=\"small\"\n fullWidth\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n <TextField\n label=\"Sleeps\"\n value={resourceDraft?.capacity ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n capacity:\n Math.round(Number(event.target.value)) || undefined,\n }\n : prev,\n )\n }\n helperText=\"Guests per unit, for display\"\n size=\"small\"\n fullWidth\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n </Stack>\n {CommerceModel.resourceUnits(resourceDraft) > 1 ? (\n <TextField\n label=\"Show “Only N left” at\"\n placeholder={String(CommerceModel.FEW_UNITS_LEFT)}\n value={resourceDraft?.fewLeftAt ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n fewLeftAt:\n event.target.value.replace(/\\D/g, '') === ''\n ? undefined\n : Number(event.target.value.replace(/\\D/g, '')),\n }\n : prev,\n )\n }\n error={Boolean(fewLeftAtProblem(resourceDraft?.fewLeftAt))}\n helperText={\n fewLeftAtProblem(resourceDraft?.fewLeftAt) ??\n 'The booking widget says “Only 2 left” once this many or fewer are free on a night. 0 never shows it.'\n }\n size=\"small\"\n fullWidth\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n ) : null}\n <TextField\n select\n label=\"At check-in\"\n value={resourceDraft?.checkInPerGuest ? 'guest' : 'stay'}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev ? { ...prev, checkInPerGuest: event.target.value === 'guest' } : prev,\n )\n }\n helperText=\"One per guest gives each guest their own check-in and wristband. The check-in screen can set every stay at once.\"\n size=\"small\"\n fullWidth\n >\n <MenuItem value=\"stay\">{'One check-in per stay'}</MenuItem>\n <MenuItem value=\"guest\">{'One check-in per guest'}</MenuItem>\n </TextField>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Nightly rate ($)\"\n value={resourceDraft?.nightlyRateUsd ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n nightlyRateUsd: Number(event.target.value) || 0,\n }\n : prev,\n )\n }\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Weekend ×\"\n placeholder=\"1\"\n value={resourceDraft?.weekendMultiplier ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n weekendMultiplier:\n Number(event.target.value) || undefined,\n }\n : prev,\n )\n }\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n </Stack>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Min nights\"\n value={resourceDraft?.minNights ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n minNights:\n Math.round(Number(event.target.value)) || undefined,\n }\n : prev,\n )\n }\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n <TextField\n label=\"Deposit %\"\n placeholder=\"100 = pay in full\"\n value={resourceDraft?.depositPct ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n depositPct:\n Math.round(Number(event.target.value)) || undefined,\n }\n : prev,\n )\n }\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n <TextField\n label=\"Free cancel (hrs)\"\n value={resourceDraft?.cancellationHours ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n cancellationHours:\n Math.round(Number(event.target.value)) || undefined,\n }\n : prev,\n )\n }\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n </Stack>\n </DialogContent>\n <DialogActions>\n {resourceChecking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\" sx={{ mr: 'auto' }}>\n {seedCheckingText('resource')}\n </Typography>\n ) : null}\n <Button onClick={() => setResourceDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n !resourceDraft?.name?.trim() ||\n !((resourceDraft?.nightlyRateUsd ?? 0) > 0) ||\n Boolean(unitsProblem(resourceDraft?.units)) ||\n Boolean(fewLeftAtProblem(resourceDraft?.fewLeftAt)) ||\n resourceHeld.saving\n }\n onClick={resourceHeld.press}\n >\n {heldSaveLabel(resourceHeld, 'Save')}\n </Button>\n </DialogActions>\n </Dialog>\n\n <Dialog\n open={Boolean(walkIn)}\n onClose={() => setWalkIn(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{'Walk-in reservation'}</DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <TextField\n label=\"Resource\"\n value={walkIn?.resourceId ?? ''}\n onChange={(event) =>\n setWalkIn((prev) =>\n prev ? { ...prev, resourceId: event.target.value } : prev,\n )\n }\n size=\"small\"\n select\n sx={{ mt: 1 }}\n >\n {(resourceDocs ?? []).map((resource: any) => (\n <MenuItem key={resource.$id} value={resource.$id}>\n {resource.name}\n </MenuItem>\n ))}\n </TextField>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Check-in\"\n type=\"date\"\n value={walkIn?.checkIn ?? ''}\n onChange={(event) =>\n setWalkIn((prev) =>\n prev ? { ...prev, checkIn: event.target.value } : prev,\n )\n }\n size=\"small\"\n fullWidth\n slotProps={{ inputLabel: { shrink: true } }}\n />\n <TextField\n label=\"Check-out\"\n type=\"date\"\n value={walkIn?.checkOut ?? ''}\n onChange={(event) =>\n setWalkIn((prev) =>\n prev ? { ...prev, checkOut: event.target.value } : prev,\n )\n }\n size=\"small\"\n fullWidth\n slotProps={{ inputLabel: { shrink: true } }}\n />\n </Stack>\n <TextField\n label=\"Guest name\"\n value={walkIn?.guestName ?? ''}\n onChange={(event) =>\n setWalkIn((prev) =>\n prev ? { ...prev, guestName: event.target.value } : prev,\n )\n }\n size=\"small\"\n />\n <TextField\n label=\"Guests\"\n value={walkIn?.guests ?? ''}\n onChange={(event) =>\n setWalkIn((prev) =>\n prev ? { ...prev, guests: event.target.value.replace(/\\D/g, '') } : prev,\n )\n }\n helperText={`Optional, up to ${CommerceModel.resourceGuestCeiling(\n (resourceDocs ?? []).find((item: any) => item.$id === walkIn?.resourceId),\n )}. Each guest gets a check-in when the stay is checked in per guest.`}\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setWalkIn(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n walkInBusy ||\n !walkIn?.resourceId ||\n !walkIn?.checkIn ||\n !walkIn?.checkOut\n }\n onClick={handleWalkIn}\n >\n {'Reserve'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nReservationsCard.displayName = 'ReservationsCard'\n\nexport default ReservationsCard\n"],"names":["Aglyn","CommerceModel","reservationPermissionRefusal","CardDisplay","useConfirmationContext","ListPagination","useSnackbar","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Typography","collection","deleteDoc","doc","getDocs","limit","orderBy","query","setDoc","updateDoc","where","lazy","Suspense","useCallback","useMemo","useState","useFirestore","useMerchantPayments","useUser","authorizedFetch","PrerequisiteNotice","useFirestoreCollection","usePagedCollection","writeGuardedBySeed","pluginDocsHelp","heldSaveLabel","isSeedChecking","seedCheckingText","useHeldSave","useSeedDraft","ReservationGuestsDialog","GUESTS_OPEN_STATUSES","STATUS_COLOR","pending","confirmed","checked_in","checked_out","cancelled","no_show","usd","cents","toFixed","day","dayMs","Date","toISOString","slice","nightLabel","toLocaleDateString","weekday","month","timeZone","UNITS_LOOKAHEAD_NIGHTS","localTodayDayMs","now","UTC","getFullYear","getMonth","getDate","unitsProblem","units","undefined","Number","isInteger","MAX_RESOURCE_UNITS","fewLeftAtProblem","fewLeftAt","ReservationsCard","props","payments","resourceDraft","hostId","canManage","canWalkIn","missing","firestore","data","user","enqueueSnackbar","confirm","resourceDocs","status","resourcesStatus","fromCache","resourcesFromCache","listen","resourcesListen","idField","rows","reservations","hasMore","page","setPage","pageSize","setPageSize","pageLimit","hasSeveralUnits","some","resource","resourceUnits","todayDayMs","currentStays","unitsAhead","byResource","nowMs","stays","filter","stay","resourceId","$id","map","checkInDayMs","checkOutDayMs","createdAtMs","unitsLeftByNight","resourceNames","name","setResourceDraft","opened","row","id","find","resourceChecking","Boolean","unreadable","walkIn","setWalkIn","walkInBusy","setWalkInBusy","guestsFor","setGuestsFor","handleResourceSave","trim","nightlyRateUsd","seeded","_syntheticId","fields","resourceFewLeftAt","verdict","subject","createResourceUid","merge","ok","message","variant","persist","handleStatus","reservation","handleWalkIn","checkIn","checkOut","item","parse","guests","guestsProblem","reservationGuestsProblem","quote","computeReservationQuote","problem","overlapping","catch","existing","docs","snapshot","isRangeAvailable","response","method","headers","body","JSON","stringify","guestName","reservationId","attemptId","answer","json","error","resourceHeld","checking","onRefused","header","help","anchor","contentGutterX","contentGutterY","spacing","blocked","severity","href","actionLabel","reason","direction","sx","alignItems","flex","minWidth","noWrap","join","color","size","disabled","onClick","title","description","confirmationText","confirmationButtonProps","then","useFlexGap","aria-label","flexWrap","gap","night","unitsLeft","label","depositPct","minNights","length","mt","guestEmail","reservationGuests","paidCents","totalCents","String","replace","folio","folioCents","reduce","sum","entry","amountCents","balanceCents","includes","rowCount","onPageChange","onPageSizeChange","fallback","onClose","onDone","unchanged","open","maxWidth","fullWidth","display","flexDirection","value","onChange","event","prev","target","autoFocus","placeholder","helperText","slotProps","htmlInput","inputMode","capacity","Math","round","FEW_UNITS_LEFT","select","checkInPerGuest","weekendMultiplier","cancellationHours","role","mr","saving","press","type","inputLabel","shrink","resourceGuestCeiling","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;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,OAAQjB,UAAU,IACxE,mEAAmE,CAAC;gCACtE2F,MAAK;gCACLqD,WAAW;oCAAEC,WAAW;wCAAEC,WAAW;oCAAU;gCAAE;;;;kCAGrD,MAACpQ;;0CACC,KAACH;gCAAOkN,SAAS,IAAM3E,UAAU;0CAAQ;;0CACzC,KAACvI;gCACCyJ,SAAQ;gCACRsD,OAAM;gCACNE,UACEzE,cACA,EAACF,0BAAAA,OAAQjB,UAAU,KACnB,EAACiB,0BAAAA,OAAQwB,OAAO,KAChB,EAACxB,0BAAAA,OAAQyB,QAAQ;gCAEnBmD,SAASrD;0CAER;;;;;;;;AAMb;AACAjF,iBAAiB4M,WAAW,GAAG;AAE/B,eAAe5M,iBAAgB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/reservations-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport * as Aglyn from '@aglyn/aglyn'\nimport * as CommerceModel from '../../model'\nimport { reservationPermissionRefusal } from '../../model/plugin-permissions'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n Button,\n Chip,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n deleteDoc,\n doc,\n getDocs,\n limit,\n orderBy,\n query,\n setDoc,\n updateDoc,\n where,\n} from 'firebase/firestore'\nimport { lazy, Suspense, useCallback, useMemo, useState } from 'react'\nimport { useFirestore, useMerchantPayments, useUser } from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { PrerequisiteNotice } from '@aglyn/shared-ui-jsx/components/prerequisite-notice.component'\nimport {\n useFirestoreCollection,\n usePagedCollection,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport {\n heldSaveLabel,\n isSeedChecking,\n seedCheckingText,\n useHeldSave,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\nimport { useSeedDraft } from '@aglyn/tenant-feature-instance/hooks/use-seed-draft'\n\nexport interface ReservationsCardProps {\n hostId: string\n /**\n * \"Manage reservations\" (`commerce.reservations`, AGL-4047) on this site:\n * edit, cancel and check out stays and change what can be booked. The rules\n * decide it; this only disables the controls with the reason. Absent reads\n * as held, so a surface that does not pass it shows the card as before.\n */\n canManage?: boolean\n /** \"Book walk-ins and change guests\" (`commerce.walkIns`), which the routes ask. */\n canWalkIn?: boolean\n}\n\n/** A stay's guest count after booking (AGL-4043), loaded the first time it opens. */\nconst ReservationGuestsDialog = lazy(() => import('./reservation-guests-dialog.component'))\n\n/** The statuses whose guest count staff can still change. */\nconst GUESTS_OPEN_STATUSES = ['pending', 'confirmed', 'checked_in']\n\nconst STATUS_COLOR: Record<\n string,\n 'default' | 'success' | 'warning' | 'error' | 'info'\n> = {\n pending: 'warning',\n confirmed: 'info',\n checked_in: 'success',\n checked_out: 'default',\n cancelled: 'default',\n no_show: 'error',\n}\n\nconst usd = (cents: number | undefined) =>\n `$${((cents ?? 0) / 100).toFixed(2)}`\nconst day = (dayMs: number | undefined) =>\n dayMs ? new Date(dayMs).toISOString().slice(0, 10) : '—'\nconst nightLabel = (dayMs: number) =>\n new Date(dayMs).toLocaleDateString('en-US', {\n weekday: 'short',\n month: 'short',\n day: 'numeric',\n timeZone: 'UTC',\n })\n\n/** The Reservations card's look-ahead for a several-unit resource. */\nconst UNITS_LOOKAHEAD_NIGHTS = 14\n\n/** The desk's calendar day as the UTC-midnight `dayMs` stays are stored in. */\nfunction localTodayDayMs(): number {\n const now = new Date()\n return Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())\n}\n\n/** The units field's problem, or null when the typed value is a valid count. */\nfunction unitsProblem(units: number | undefined): string | null {\n if (units === undefined) return null\n if (\n !Number.isInteger(units) ||\n units < 1 ||\n units > CommerceModel.MAX_RESOURCE_UNITS\n ) {\n return `A whole number from 1 to ${CommerceModel.MAX_RESOURCE_UNITS}`\n }\n return null\n}\n\n/**\n * The \"Only N left\" field's problem (AGL-4044), or null when the typed value\n * is a valid threshold: 0 (never) up to the most units a resource can hold.\n */\nfunction fewLeftAtProblem(fewLeftAt: number | undefined): string | null {\n if (fewLeftAt === undefined) return null\n if (\n !Number.isInteger(fewLeftAt) ||\n fewLeftAt < 0 ||\n fewLeftAt > CommerceModel.MAX_RESOURCE_UNITS\n ) {\n return `A whole number from 0 to ${CommerceModel.MAX_RESOURCE_UNITS}`\n }\n return null\n}\n\n/**\n * Reservations console (AGL-311): resources CRUD (nightly pricing,\n * seasons via multipliers, deposits) plus the reservations list with\n * check-in/out, no-show, cancel, and walk-in creation. The storefront\n * widget books against the same docs.\n */\nexport function ReservationsCard(props: ReservationsCardProps) {\n const { hostId, canManage = true, canWalkIn = true } = props\n // The permissions this member lacks here, named, for the line under the\n // card's actions (AGL-4047): a disabled control says why.\n const missing = [\n ...(canManage ? [] : [reservationPermissionRefusal('commerce.reservations')]),\n ...(canWalkIn ? [] : [reservationPermissionRefusal('commerce.walkIns')]),\n ]\n // Every reservation is paid when it is booked, so a store that cannot\n // charge turns each guest away; the card says so up front.\n const payments = useMerchantPayments(hostId)\n const firestore = useFirestore()\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n const {\n data: resourceDocs,\n status: resourcesStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing spreads a whole stored resource into\n * `resourceDraft` and writes all of it back, so `merge: true` protects\n * nothing. `blocks` is the field that costs more than money: it is the\n * manually blocked date ranges `isRangeAvailable` reads, so a cached seed\n * re-opens dates that were closed and lets the next guest book a room\n * that is already spoken for.\n */\n fromCache: resourcesFromCache,\n listen: resourcesListen,\n } = useFirestoreCollection<any>(\n () => query(collection(firestore, 'hosts', hostId, 'resources'), limit(50)),\n [firestore, hostId],\n { idField: '$id' },\n )\n /*\n * Ordered by the server, and a growing window rather than a fixed 300.\n *\n * `limit(300)` carried no `orderBy`, so Firestore returned DOCUMENT-ID\n * order and the client sort below arranged that pseudo-random sample by\n * check-in. The ordering is unchanged — earliest check-in first, exactly\n * what the sort did — it is now the QUERY's, so the window is the real\n * front of the list and the rest can be reached.\n */\n const {\n rows: reservations,\n hasMore,\n page,\n setPage,\n pageSize,\n setPageSize,\n } = usePagedCollection<any>(\n (pageLimit) =>\n query(\n collection(firestore, 'hosts', hostId, 'reservations'),\n orderBy('checkInDayMs', 'asc'),\n limit(pageLimit),\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n /*\n * Units left on each of the next nights, for resources with several units\n * (AGL-4044). One listen across the site's resources, on the stays that\n * have not ended, nearest check-out first: a range and an order on the same\n * field, which Firestore's automatic single-field index serves. Not read at\n * all while every resource has one unit, so a cabin-only site pays nothing.\n *\n * The 500 cap is the booking door's: it can only leave out stays that end\n * after 500 others that are all still running, which would be a stay far\n * past the two weeks this draws.\n */\n const hasSeveralUnits = (resourceDocs ?? []).some(\n (resource: any) => CommerceModel.resourceUnits(resource) > 1,\n )\n const todayDayMs = localTodayDayMs()\n const { data: currentStays } = useFirestoreCollection<any>(\n () =>\n hasSeveralUnits\n ? query(\n collection(firestore, 'hosts', hostId, 'reservations'),\n where('checkOutDayMs', '>', todayDayMs),\n orderBy('checkOutDayMs'),\n limit(500),\n )\n : null,\n [firestore, hostId, hasSeveralUnits, todayDayMs],\n { idField: '$id' },\n )\n const unitsAhead = useMemo(() => {\n const byResource: Record<string, CommerceModel.ResourceNightUnits[]> = {}\n if (!hasSeveralUnits) return byResource\n const nowMs = Date.now()\n for (const resource of resourceDocs ?? []) {\n if (CommerceModel.resourceUnits(resource) === 1) continue\n const stays = (currentStays ?? [])\n .filter((stay: any) => stay.resourceId === resource.$id)\n .map((stay: any) => ({\n checkInDayMs: Number(stay.checkInDayMs),\n checkOutDayMs: Number(stay.checkOutDayMs),\n status: stay.status as CommerceModel.ReservationStatus,\n createdAtMs: Number(stay.createdAtMs ?? 0),\n }))\n byResource[resource.$id] = CommerceModel.unitsLeftByNight(\n resource,\n stays,\n todayDayMs,\n UNITS_LOOKAHEAD_NIGHTS,\n nowMs,\n )\n }\n return byResource\n }, [hasSeveralUnits, resourceDocs, currentStays, todayDayMs])\n\n const resourceNames = useMemo(() => {\n const map: Record<string, string> = {}\n for (const resource of resourceDocs ?? []) {\n map[resource.$id] = resource.name\n }\n return map\n }, [resourceDocs])\n\n /*\n * The dialog's draft, kept as EDITS over the resource as the list has it\n * now (AGL-4047): opened from the cache's row, the server's copy replaces\n * it under every field nobody touched (`blocks` among them), and Save is\n * held until it has.\n */\n const [resourceDraft, setResourceDraft] = useSeedDraft<\n Partial<CommerceModel.HostResource> & { id: string | null }\n >((opened) => {\n const row = opened.id\n ? resourceDocs?.find((resource: any) => resource.$id === opened.id)\n : undefined\n return row ? { id: row.$id, ...row } : undefined\n })\n const resourceChecking =\n Boolean(resourceDraft?.id) &&\n isSeedChecking({\n fromCache: resourcesFromCache,\n unreadable: resourcesStatus === 'error',\n })\n const [walkIn, setWalkIn] = useState<{\n resourceId: string\n checkIn: string\n checkOut: string\n guestName: string\n /** How many guests (AGL-4043); '' sends none. */\n guests: string\n /** One walk-in attempt: a retry of it finds its own stay (AGL-4046). */\n attemptId: string\n } | null>(null)\n const [walkInBusy, setWalkInBusy] = useState(false)\n /** The stay whose guests are being changed (AGL-4043). */\n const [guestsFor, setGuestsFor] = useState<string | null>(null)\n\n const handleResourceSave = useCallback(async () => {\n if (!resourceDraft?.name?.trim() || !(resourceDraft.nightlyRateUsd! > 0)) {\n return\n }\n /**\n * `$id` comes off with `id` (AGL-1374).\n *\n * The editor is seeded `{ id: resource.$id, ...resource }`, and that\n * spread carries the listener's SYNTHETIC `$id` — `idField: '$id'`\n * stamps the document id onto the in-memory row, where nothing persists\n * it. Destructuring only `id` left `$id` in `data`, so every save wrote\n * it into the stored document as a real field. Nothing reads it; it is\n * the listener's bookkeeping leaking into storage, and once there no\n * reader can tell it from a field the card meant to write.\n */\n if (unitsProblem(resourceDraft.units)) return\n if (fewLeftAtProblem(resourceDraft.fewLeftAt)) return\n const seeded = resourceDraft as typeof resourceDraft & { $id?: string }\n const { id, $id: _syntheticId, units, fewLeftAt, ...fields } = seeded\n // Units are written as the count the model reads (AGL-4044), and a\n // cleared field as 1 rather than left out: `merge: true` would otherwise\n // keep a stored 12 the merchant just removed. The \"Only N left\" threshold\n // the same way: a cleared field is written as the default it reads as.\n const data = {\n ...fields,\n ...('units' in seeded ? { units: CommerceModel.resourceUnits({ units }) } : {}),\n ...('fewLeftAt' in seeded\n ? { fewLeftAt: CommerceModel.resourceFewLeftAt({ fewLeftAt }) }\n : {}),\n // A path as typed (`cabins/lakeside `), stored as the site path it\n // names; cleared, an empty string, which search reads as no page.\n ...('pagePath' in seeded\n ? {\n pagePath: (() => {\n const text = String(fields.pagePath ?? '').trim().split(/[?#]/)[0]\n if (!text || text.startsWith('//')) return ''\n return text.startsWith('/') ? text : `/${text}`\n })(),\n }\n : {}),\n }\n /**\n * Refuse an EDIT whose seed the server never confirmed (AGL-1358).\n * `data` is the whole stored row spread out of the listener, so\n * `merge: true` has nothing left to protect — every field is present,\n * `blocks` and the seasonal multipliers included.\n *\n * Only the edit path. A NEW resource is built from defaults at a fresh\n * uid and can overwrite nothing, and the first snapshot of any listener\n * is `fromCache: true`, so guarding a create would refuse a save that was\n * never unsafe.\n *\n * The guard WRAPS the write — an early return is a shape you can keep\n * while losing the protection.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'resource',\n unreadable: Boolean(id) && resourcesStatus === 'error',\n fromCache: Boolean(id) && resourcesFromCache,\n listen: resourcesListen,\n },\n async () => {\n await setDoc(\n doc(\n firestore,\n 'hosts',\n hostId,\n 'resources',\n id ?? Aglyn.createResourceUid(),\n ),\n {\n ...data,\n name: resourceDraft.name!.trim().slice(0, 120),\n },\n { merge: true },\n )\n },\n )\n // Before `setResourceDraft(null)`, so a refusal keeps the dialog open\n // with what was typed.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setResourceDraft(null)\n enqueueSnackbar('Resource saved', { variant: 'success', persist: false })\n }, [\n setResourceDraft,\n resourceDraft,\n firestore,\n hostId,\n enqueueSnackbar,\n resourcesStatus,\n resourcesFromCache,\n resourcesListen,\n ])\n\n const handleStatus = useCallback(\n (reservation: any, status: CommerceModel.ReservationStatus) => async () => {\n await updateDoc(\n doc(firestore, 'hosts', hostId, 'reservations', reservation.$id),\n { status },\n )\n },\n [firestore, hostId],\n )\n\n const handleWalkIn = useCallback(async () => {\n if (!walkIn?.resourceId || !walkIn.checkIn || !walkIn.checkOut) return\n const resource = (resourceDocs ?? []).find(\n (item: any) => item.$id === walkIn.resourceId,\n ) as CommerceModel.HostResource | undefined\n if (!resource) return\n const checkInDayMs = Date.parse(`${walkIn.checkIn}T00:00:00Z`)\n const checkOutDayMs = Date.parse(`${walkIn.checkOut}T00:00:00Z`)\n const guests = walkIn.guests.trim() ? Number(walkIn.guests) : undefined\n const guestsProblem = CommerceModel.reservationGuestsProblem(guests, resource)\n if (guestsProblem) {\n return void enqueueSnackbar(guestsProblem, { variant: 'warning', persist: false })\n }\n /*\n * The stay is priced FIRST, and its `problem` stops the walk-in: the quote\n * is the one rule for what can be booked (no nights, under the minimum\n * stay), shared with the booking widget and both native apps. Ignoring it\n * wrote a confirmed zero-night, $0 stay for a check-out on the arrival\n * day (AGL-3794).\n */\n const quote = CommerceModel.computeReservationQuote(\n resource,\n checkInDayMs,\n checkOutDayMs,\n )\n if (quote.problem) {\n return void enqueueSnackbar(quote.problem, {\n variant: 'warning',\n persist: false,\n })\n }\n /*\n * Every stay of THIS resource that ends after the walk-in arrives — the\n * same query `reserve.ts` checks a booking against, on the composite it\n * already has (AGL-3321). This used to test the rows on the card's\n * current page, so a stay on the next page did not block the dates and\n * the desk could double-book the room.\n */\n const overlapping = await getDocs(\n query(\n collection(firestore, 'hosts', hostId, 'reservations'),\n where('resourceId', '==', walkIn.resourceId),\n where('checkOutDayMs', '>', checkInDayMs),\n orderBy('checkOutDayMs'),\n limit(500),\n ),\n ).catch(() => null)\n if (!overlapping) {\n return void enqueueSnackbar('Could not check those dates — try again', {\n variant: 'warning',\n persist: false,\n })\n }\n // `createdAtMs` carried through because the pending hold lapses on it\n // (`reservationHoldsDates`). Dropping it made every unpaid `pending` row\n // block forever, so the front desk was refused a walk-in into a room that\n // an abandoned online checkout had left empty.\n const existing = overlapping.docs\n .map((snapshot) => snapshot.data() as any)\n .map((item: any) => ({\n checkInDayMs: item.checkInDayMs,\n checkOutDayMs: item.checkOutDayMs,\n status: item.status,\n createdAtMs: item.createdAtMs,\n }))\n // Count-based for a several-unit resource (AGL-4044): the walk-in takes\n // any unit that is free on every night, and is refused only when some\n // night has none left.\n if (\n !CommerceModel.isRangeAvailable(resource, existing, checkInDayMs, checkOutDayMs)\n ) {\n const message =\n CommerceModel.resourceUnits(resource) > 1\n ? 'Every unit is taken on at least one of those nights'\n : 'Those dates are taken'\n return void enqueueSnackbar(message, {\n variant: 'warning',\n persist: false,\n })\n }\n /*\n * The check above is the instant answer; the WRITE goes through\n * `/api/commerce/reservations/walk-in` (AGL-4046), which re-asks the same\n * question inside the transaction that books the stay. A client\n * read-then-write let two staff on two devices both take the last unit.\n */\n setWalkInBusy(true)\n try {\n const response = await authorizedFetch(\n user,\n '/api/commerce/reservations/walk-in',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n hostId,\n resourceId: walkIn.resourceId,\n checkInDayMs,\n checkOutDayMs,\n guestName: walkIn.guestName || undefined,\n ...(guests !== undefined ? { guests } : {}),\n reservationId: walkIn.attemptId,\n }),\n },\n )\n const answer = await response.json().catch(() => ({}))\n if (!response.ok) {\n return void enqueueSnackbar(\n answer?.error ?? 'Could not reserve the walk-in — try again',\n {\n variant: response.status === 409 || response.status === 400\n ? 'warning'\n : 'error',\n persist: false,\n },\n )\n }\n } catch {\n return void enqueueSnackbar('Could not reserve the walk-in — try again', {\n variant: 'error',\n persist: false,\n })\n } finally {\n setWalkInBusy(false)\n }\n setWalkIn(null)\n enqueueSnackbar('Walk-in reserved — collect payment at POS', {\n variant: 'success',\n persist: false,\n })\n }, [walkIn, resourceDocs, firestore, hostId, user, enqueueSnackbar])\n\n // A press while Save is held is kept, and saves once confirmed (AGL-4047).\n const resourceHeld = useHeldSave(handleResourceSave, {\n checking: resourceChecking,\n subject: 'resource',\n onRefused: (message) => enqueueSnackbar(message, { variant: 'warning', persist: false }),\n })\n\n return (\n <CardDisplay\n header={'Reservations'}\n help={pluginDocsHelp('pos', { anchor: '#reservations' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n {payments.blocked ? (\n <PrerequisiteNotice severity=\"warning\" href={payments.href ?? undefined} actionLabel=\"Open Payments\">\n {`${payments.reason ?? ''} Guests pay when they reserve, so they can't reserve until it is set up.`}\n </PrerequisiteNotice>\n ) : null}\n <Typography variant=\"subtitle2\">{'Resources'}</Typography>\n {(resourceDocs ?? []).map((resource: any) => (\n <Stack key={resource.$id} spacing={0.5}>\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {[\n resource.name,\n `$${resource.nightlyRateUsd}/night`,\n ...(CommerceModel.resourceUnits(resource) > 1\n ? [`${CommerceModel.resourceUnits(resource)} units`]\n : []),\n ].join(' · ')}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`id: ${resource.$id}`}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n disabled={!canManage}\n onClick={() => setResourceDraft({ id: resource.$id, ...resource })}\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n disabled={!canManage}\n onClick={async () => {\n const confirmed = await confirm({\n title: 'Remove this resource?',\n description:\n 'Existing reservations keep their records; the widget ' +\n 'stops accepting new stays.',\n confirmationText: 'Remove',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await deleteDoc(\n doc(firestore, 'hosts', hostId, 'resources', resource.$id),\n )\n }}\n >\n {'Remove'}\n </Button>\n </Stack>\n {unitsAhead[resource.$id] ? (\n <Stack\n direction=\"row\"\n useFlexGap\n aria-label={`Units left on the next ${UNITS_LOOKAHEAD_NIGHTS} nights`}\n sx={{ flexWrap: 'wrap', gap: 0.5 }}\n >\n {unitsAhead[resource.$id].map((night) => (\n <Chip\n key={night.dayMs}\n size=\"small\"\n variant=\"outlined\"\n color={\n night.unitsLeft === 0\n ? 'error'\n : night.unitsLeft <=\n CommerceModel.resourceFewLeftAt(resource)\n ? 'warning'\n : 'default'\n }\n label={`${nightLabel(night.dayMs)} · ${night.unitsLeft} of ${night.units} left`}\n />\n ))}\n </Stack>\n ) : null}\n </Stack>\n ))}\n <Stack direction=\"row\" spacing={1}>\n <Button\n size=\"small\"\n disabled={!canManage}\n onClick={() =>\n setResourceDraft({\n id: null,\n name: '',\n nightlyRateUsd: 100,\n depositPct: 30,\n minNights: 1,\n })\n }\n >\n {'Add resource'}\n </Button>\n <Button\n size=\"small\"\n disabled={!canWalkIn || (resourceDocs?.length ?? 0) === 0}\n onClick={() =>\n setWalkIn({\n resourceId: resourceDocs?.[0]?.$id ?? '',\n checkIn: '',\n checkOut: '',\n guestName: '',\n guests: '',\n attemptId: Aglyn.createResourceUid(),\n })\n }\n >\n {'Walk-in'}\n </Button>\n </Stack>\n {missing.map((reason) => (\n <Typography key={reason} variant=\"caption\" color=\"text.secondary\">\n {reason}\n </Typography>\n ))}\n\n <Typography variant=\"subtitle2\" sx={{ mt: 1 }}>\n {'Upcoming & recent stays'}\n </Typography>\n {reservations.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Reservations from the widget (and walk-ins) appear here.'}\n </Typography>\n ) : (\n reservations.map((reservation: any) => (\n <Stack\n key={reservation.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {`${resourceNames[reservation.resourceId] ?? '?'} · ` +\n `${day(reservation.checkInDayMs)} → ${day(reservation.checkOutDayMs)}`}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {[\n reservation.guestName ?? reservation.guestEmail ?? 'Guest',\n ...(reservation.guests\n ? [`${CommerceModel.reservationGuests(reservation)} guest${CommerceModel.reservationGuests(reservation) === 1 ? '' : 's'}`]\n : []),\n `${usd(reservation.paidCents)} / ${usd(reservation.totalCents)} paid`,\n ].join(' · ')}\n </Typography>\n </Stack>\n <Chip\n label={String(reservation.status).replace('_', ' ')}\n size=\"small\"\n variant=\"outlined\"\n color={STATUS_COLOR[reservation.status] ?? 'default'}\n />\n {reservation.status === 'confirmed' ? (\n <>\n <Button size=\"small\" disabled={!canManage} onClick={handleStatus(reservation, 'checked_in')}>\n {'Check in'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n disabled={!canManage}\n onClick={handleStatus(reservation, 'no_show')}\n >\n {'No-show'}\n </Button>\n </>\n ) : null}\n {reservation.status === 'checked_in' ? (\n <Button\n size=\"small\"\n disabled={!canManage}\n onClick={async () => {\n // Folio settlement (AGL-317): surface unpaid room\n // charges before the guest leaves.\n const folio = (reservation.folio ?? []) as Array<{\n amountCents: number\n }>\n const folioCents = folio.reduce(\n (sum, entry) => sum + (entry.amountCents ?? 0),\n 0,\n )\n const balanceCents =\n (reservation.totalCents ?? 0) -\n (reservation.paidCents ?? 0)\n if (folioCents > 0 || balanceCents > 0) {\n const confirmed = await confirm({\n title: 'Check out with open balance?',\n description:\n `${folioCents > 0 ? `Room charges: ${usd(folioCents)} (already recorded as paid POS orders). ` : ''}` +\n `${balanceCents > 0 ? `Stay balance due: ${usd(balanceCents)} — collect at the register.` : ''}`,\n confirmationText: 'Check out',\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n }\n await handleStatus(reservation, 'checked_out')()\n }}\n >\n {'Check out'}\n </Button>\n ) : null}\n {GUESTS_OPEN_STATUSES.includes(reservation.status) ? (\n <Button size=\"small\" disabled={!canWalkIn} onClick={() => setGuestsFor(reservation.$id)}>\n {'Guests'}\n </Button>\n ) : null}\n {['pending', 'confirmed'].includes(reservation.status) ? (\n <Button\n size=\"small\"\n color=\"error\"\n disabled={!canManage}\n onClick={handleStatus(reservation, 'cancelled')}\n >\n {'Cancel'}\n </Button>\n ) : null}\n </Stack>\n ))\n )}\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={reservations.length}\n hasMore={hasMore}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n </Stack>\n\n {guestsFor ? (\n <Suspense fallback={null}>\n <ReservationGuestsDialog\n reservationId={guestsFor}\n hostId={hostId}\n onClose={() => setGuestsFor(null)}\n onDone={(answer) => {\n setGuestsFor(null)\n enqueueSnackbar(\n answer.unchanged\n ? `Still ${answer.guests} guest${answer.guests === 1 ? '' : 's'}`\n : `Guests changed to ${answer.guests}`,\n { variant: 'success', persist: false },\n )\n }}\n />\n </Suspense>\n ) : null}\n\n <Dialog\n open={Boolean(resourceDraft)}\n onClose={() => setResourceDraft(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>\n {resourceDraft?.id ? 'Edit resource' : 'New resource'}\n </DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <TextField\n label=\"Name\"\n value={resourceDraft?.name ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev ? { ...prev, name: event.target.value } : prev,\n )\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n placeholder=\"Lakeside cabin\"\n />\n {/* Where a site search result for the stay opens (AGL-4252). */}\n <TextField\n label=\"Page on your site\"\n value={resourceDraft?.pagePath ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev ? { ...prev, pagePath: event.target.value.slice(0, 300) } : prev,\n )\n }\n size=\"small\"\n placeholder=\"/cabins/lakeside\"\n helperText=\"The page that holds this stay's booking widget. Site search links there.\"\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Spots or units available\"\n placeholder=\"1\"\n value={resourceDraft?.units ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n units:\n event.target.value.replace(/\\D/g, '') === ''\n ? undefined\n : Number(event.target.value.replace(/\\D/g, '')),\n }\n : prev,\n )\n }\n error={Boolean(unitsProblem(resourceDraft?.units))}\n helperText={\n unitsProblem(resourceDraft?.units) ??\n 'How many identical ones you have, like 12 RV hookups'\n }\n size=\"small\"\n fullWidth\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n <TextField\n label=\"Sleeps\"\n value={resourceDraft?.capacity ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n capacity:\n Math.round(Number(event.target.value)) || undefined,\n }\n : prev,\n )\n }\n helperText=\"Guests per unit, for display\"\n size=\"small\"\n fullWidth\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n </Stack>\n {CommerceModel.resourceUnits(resourceDraft) > 1 ? (\n <TextField\n label=\"Show “Only N left” at\"\n placeholder={String(CommerceModel.FEW_UNITS_LEFT)}\n value={resourceDraft?.fewLeftAt ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n fewLeftAt:\n event.target.value.replace(/\\D/g, '') === ''\n ? undefined\n : Number(event.target.value.replace(/\\D/g, '')),\n }\n : prev,\n )\n }\n error={Boolean(fewLeftAtProblem(resourceDraft?.fewLeftAt))}\n helperText={\n fewLeftAtProblem(resourceDraft?.fewLeftAt) ??\n 'The booking widget says “Only 2 left” once this many or fewer are free on a night. 0 never shows it.'\n }\n size=\"small\"\n fullWidth\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n ) : null}\n <TextField\n select\n label=\"At check-in\"\n value={resourceDraft?.checkInPerGuest ? 'guest' : 'stay'}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev ? { ...prev, checkInPerGuest: event.target.value === 'guest' } : prev,\n )\n }\n helperText=\"One per guest gives each guest their own check-in and wristband. The check-in screen can set every stay at once.\"\n size=\"small\"\n fullWidth\n >\n <MenuItem value=\"stay\">{'One check-in per stay'}</MenuItem>\n <MenuItem value=\"guest\">{'One check-in per guest'}</MenuItem>\n </TextField>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Nightly rate ($)\"\n value={resourceDraft?.nightlyRateUsd ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n nightlyRateUsd: Number(event.target.value) || 0,\n }\n : prev,\n )\n }\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n <TextField\n label=\"Weekend ×\"\n placeholder=\"1\"\n value={resourceDraft?.weekendMultiplier ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n weekendMultiplier:\n Number(event.target.value) || undefined,\n }\n : prev,\n )\n }\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'decimal' } }}\n />\n </Stack>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Min nights\"\n value={resourceDraft?.minNights ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n minNights:\n Math.round(Number(event.target.value)) || undefined,\n }\n : prev,\n )\n }\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n <TextField\n label=\"Deposit %\"\n placeholder=\"100 = pay in full\"\n value={resourceDraft?.depositPct ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n depositPct:\n Math.round(Number(event.target.value)) || undefined,\n }\n : prev,\n )\n }\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n <TextField\n label=\"Free cancel (hrs)\"\n value={resourceDraft?.cancellationHours ?? ''}\n onChange={(event) =>\n setResourceDraft((prev) =>\n prev\n ? {\n ...prev,\n cancellationHours:\n Math.round(Number(event.target.value)) || undefined,\n }\n : prev,\n )\n }\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n </Stack>\n </DialogContent>\n <DialogActions>\n {resourceChecking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\" sx={{ mr: 'auto' }}>\n {seedCheckingText('resource')}\n </Typography>\n ) : null}\n <Button onClick={() => setResourceDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n !resourceDraft?.name?.trim() ||\n !((resourceDraft?.nightlyRateUsd ?? 0) > 0) ||\n Boolean(unitsProblem(resourceDraft?.units)) ||\n Boolean(fewLeftAtProblem(resourceDraft?.fewLeftAt)) ||\n resourceHeld.saving\n }\n onClick={resourceHeld.press}\n >\n {heldSaveLabel(resourceHeld, 'Save')}\n </Button>\n </DialogActions>\n </Dialog>\n\n <Dialog\n open={Boolean(walkIn)}\n onClose={() => setWalkIn(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{'Walk-in reservation'}</DialogTitle>\n <DialogContent sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>\n <TextField\n label=\"Resource\"\n value={walkIn?.resourceId ?? ''}\n onChange={(event) =>\n setWalkIn((prev) =>\n prev ? { ...prev, resourceId: event.target.value } : prev,\n )\n }\n size=\"small\"\n select\n sx={{ mt: 1 }}\n >\n {(resourceDocs ?? []).map((resource: any) => (\n <MenuItem key={resource.$id} value={resource.$id}>\n {resource.name}\n </MenuItem>\n ))}\n </TextField>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Check-in\"\n type=\"date\"\n value={walkIn?.checkIn ?? ''}\n onChange={(event) =>\n setWalkIn((prev) =>\n prev ? { ...prev, checkIn: event.target.value } : prev,\n )\n }\n size=\"small\"\n fullWidth\n slotProps={{ inputLabel: { shrink: true } }}\n />\n <TextField\n label=\"Check-out\"\n type=\"date\"\n value={walkIn?.checkOut ?? ''}\n onChange={(event) =>\n setWalkIn((prev) =>\n prev ? { ...prev, checkOut: event.target.value } : prev,\n )\n }\n size=\"small\"\n fullWidth\n slotProps={{ inputLabel: { shrink: true } }}\n />\n </Stack>\n <TextField\n label=\"Guest name\"\n value={walkIn?.guestName ?? ''}\n onChange={(event) =>\n setWalkIn((prev) =>\n prev ? { ...prev, guestName: event.target.value } : prev,\n )\n }\n size=\"small\"\n />\n <TextField\n label=\"Guests\"\n value={walkIn?.guests ?? ''}\n onChange={(event) =>\n setWalkIn((prev) =>\n prev ? { ...prev, guests: event.target.value.replace(/\\D/g, '') } : prev,\n )\n }\n helperText={`Optional, up to ${CommerceModel.resourceGuestCeiling(\n (resourceDocs ?? []).find((item: any) => item.$id === walkIn?.resourceId),\n )}. Each guest gets a check-in when the stay is checked in per guest.`}\n size=\"small\"\n slotProps={{ htmlInput: { inputMode: 'numeric' } }}\n />\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setWalkIn(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={\n walkInBusy ||\n !walkIn?.resourceId ||\n !walkIn?.checkIn ||\n !walkIn?.checkOut\n }\n onClick={handleWalkIn}\n >\n {'Reserve'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nReservationsCard.displayName = 'ReservationsCard'\n\nexport default ReservationsCard\n"],"names":["Aglyn","CommerceModel","reservationPermissionRefusal","CardDisplay","useConfirmationContext","ListPagination","useSnackbar","Button","Chip","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Typography","collection","deleteDoc","doc","getDocs","limit","orderBy","query","setDoc","updateDoc","where","lazy","Suspense","useCallback","useMemo","useState","useFirestore","useMerchantPayments","useUser","authorizedFetch","PrerequisiteNotice","useFirestoreCollection","usePagedCollection","writeGuardedBySeed","pluginDocsHelp","heldSaveLabel","isSeedChecking","seedCheckingText","useHeldSave","useSeedDraft","ReservationGuestsDialog","GUESTS_OPEN_STATUSES","STATUS_COLOR","pending","confirmed","checked_in","checked_out","cancelled","no_show","usd","cents","toFixed","day","dayMs","Date","toISOString","slice","nightLabel","toLocaleDateString","weekday","month","timeZone","UNITS_LOOKAHEAD_NIGHTS","localTodayDayMs","now","UTC","getFullYear","getMonth","getDate","unitsProblem","units","undefined","Number","isInteger","MAX_RESOURCE_UNITS","fewLeftAtProblem","fewLeftAt","ReservationsCard","props","payments","resourceDraft","hostId","canManage","canWalkIn","missing","firestore","data","user","enqueueSnackbar","confirm","resourceDocs","status","resourcesStatus","fromCache","resourcesFromCache","listen","resourcesListen","idField","rows","reservations","hasMore","page","setPage","pageSize","setPageSize","pageLimit","hasSeveralUnits","some","resource","resourceUnits","todayDayMs","currentStays","unitsAhead","byResource","nowMs","stays","filter","stay","resourceId","$id","map","checkInDayMs","checkOutDayMs","createdAtMs","unitsLeftByNight","resourceNames","name","setResourceDraft","opened","row","id","find","resourceChecking","Boolean","unreadable","walkIn","setWalkIn","walkInBusy","setWalkInBusy","guestsFor","setGuestsFor","handleResourceSave","trim","nightlyRateUsd","seeded","_syntheticId","fields","resourceFewLeftAt","pagePath","text","String","split","startsWith","verdict","subject","createResourceUid","merge","ok","message","variant","persist","handleStatus","reservation","handleWalkIn","checkIn","checkOut","item","parse","guests","guestsProblem","reservationGuestsProblem","quote","computeReservationQuote","problem","overlapping","catch","existing","docs","snapshot","isRangeAvailable","response","method","headers","body","JSON","stringify","guestName","reservationId","attemptId","answer","json","error","resourceHeld","checking","onRefused","header","help","anchor","contentGutterX","contentGutterY","spacing","blocked","severity","href","actionLabel","reason","direction","sx","alignItems","flex","minWidth","noWrap","join","color","size","disabled","onClick","title","description","confirmationText","confirmationButtonProps","then","useFlexGap","aria-label","flexWrap","gap","night","unitsLeft","label","depositPct","minNights","length","mt","guestEmail","reservationGuests","paidCents","totalCents","replace","folio","folioCents","reduce","sum","entry","amountCents","balanceCents","includes","rowCount","onPageChange","onPageSizeChange","fallback","onClose","onDone","unchanged","open","maxWidth","fullWidth","display","flexDirection","value","onChange","event","prev","target","autoFocus","placeholder","helperText","slotProps","htmlInput","inputMode","capacity","Math","round","FEW_UNITS_LEFT","select","checkInPerGuest","weekendMultiplier","cancellationHours","role","mr","saving","press","type","inputLabel","shrink","resourceGuestCeiling","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,YAAYA,WAAW,eAAc;AACrC,YAAYC,mBAAmB,uBAAa;AAC5C,SAASC,4BAA4B,QAAQ,oCAAgC;AAC7E,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,MAAM,EACNC,IAAI,EACJC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,SAAS,EACTC,GAAG,EACHC,OAAO,EACPC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,KAAK,QACA,qBAAoB;AAC3B,SAASC,IAAI,EAAEC,QAAQ,EAAEC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtE,SAASC,YAAY,EAAEC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U,IACxE,mEAAmE,CAAC;gCACtEgG,MAAK;gCACLoD,WAAW;oCAAEC,WAAW;wCAAEC,WAAW;oCAAU;gCAAE;;;;kCAGrD,MAACxQ;;0CACC,KAACH;gCAAOuN,SAAS,IAAMhF,UAAU;0CAAQ;;0CACzC,KAACvI;gCACC8J,SAAQ;gCACRsD,OAAM;gCACNE,UACE9E,cACA,EAACF,0BAAAA,OAAQjB,UAAU,KACnB,EAACiB,0BAAAA,OAAQ6B,OAAO,KAChB,EAAC7B,0BAAAA,OAAQ8B,QAAQ;gCAEnBmD,SAASrD;0CAER;;;;;;;;AAMb;AACAtF,iBAAiBgN,WAAW,GAAG;AAE/B,eAAehN,iBAAgB"}
@@ -28,6 +28,7 @@ import { useFirestore, useUser } from "@aglyn/tenant-feature-instance";
28
28
  import { useFirestoreDoc, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
29
29
  import { pluginDocsHelp } from "@aglyn/aglyn";
30
30
  import { heldSaveLabel, isSeedChecking, seedCheckingText, useHeldSave, useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
31
+ import { useCurrencySetup } from "./use-currency-setup.js";
31
32
  /** Every country checkout can ship to, plus rest of world, for a zone. */ const ZONE_COUNTRY_OPTIONS = [
32
33
  '*',
33
34
  ...[
@@ -122,6 +123,12 @@ function zoneCountryLabel(code) {
122
123
  user
123
124
  ]);
124
125
  const update = (patch)=>form.edit(patch);
126
+ /*
127
+ * The store's other currencies (AGL-4248), from the same settings doc, and
128
+ * the day's rates for the converted figure each blank field stands for.
129
+ */ const { rates: fxRates } = useCurrencySetup(hostId);
130
+ const storeBase = CommerceModel.storeBaseCurrency(store);
131
+ const otherCurrencies = CommerceModel.otherStoreCurrencies(store == null ? void 0 : store.currencies, storeBase);
125
132
  const updateZone = (index, patch)=>{
126
133
  var _current_zones;
127
134
  const zones = [
@@ -162,6 +169,29 @@ function zoneCountryLabel(code) {
162
169
  rates
163
170
  });
164
171
  };
172
+ /**
173
+ * One rate's price, or free-over threshold, in another currency
174
+ * (AGL-4248). Blank is converted from the store-currency figure, and drops
175
+ * the key: an emptied map is removed rather than stored as `undefined`.
176
+ */ const updateRateCurrency = (index, field, code, raw)=>{
177
+ var _current_rates;
178
+ var _current_rates1;
179
+ const rate = (_current_rates1 = current.rates) == null ? void 0 : _current_rates1[index];
180
+ if (!rate) return;
181
+ const major = CommerceModel.parseMajorInput(raw);
182
+ if (major === null) return;
183
+ const map = CommerceModel.withCurrencyAmount(rate[field], code, major === undefined ? undefined : CommerceModel.majorToMinor(major, code));
184
+ const next = _extends({}, rate);
185
+ if (map) next[field] = map;
186
+ else delete next[field];
187
+ const rates = [
188
+ ...(_current_rates = current.rates) != null ? _current_rates : []
189
+ ];
190
+ rates[index] = next;
191
+ update({
192
+ rates
193
+ });
194
+ };
165
195
  const handleSave = useCallback(async ()=>{
166
196
  /**
167
197
  * Refuse a save whose seed the server never confirmed (AGL-1358).
@@ -453,7 +483,15 @@ function zoneCountryLabel(code) {
453
483
  }
454
484
  }) : null
455
485
  ]
456
- }) : /*#__PURE__*/ _jsxs(Stack, {
486
+ }) : null,
487
+ (rate.kind === 'flat' || rate.kind === 'free_over') && otherCurrencies.length ? /*#__PURE__*/ _jsx(RateCurrencyFields, {
488
+ rate: rate,
489
+ base: storeBase,
490
+ currencies: otherCurrencies,
491
+ rates: fxRates,
492
+ onChange: (field, code, raw)=>updateRateCurrency(index, field, code, raw)
493
+ }) : null,
494
+ rate.kind === 'carrier' || rate.kind === 'flat' || rate.kind === 'free_over' ? null : /*#__PURE__*/ _jsxs(Stack, {
457
495
  spacing: 1,
458
496
  sx: {
459
497
  pl: 2
@@ -755,5 +793,66 @@ export default ShippingSettingsCard;
755
793
  ]
756
794
  });
757
795
  }
796
+ /**
797
+ * A flat or free-over rate in each other currency the store sells in
798
+ * (AGL-4248). A blank field is converted at the day's rate, and shows the
799
+ * converted figure as its placeholder; a typed one is charged as typed.
800
+ */ function RateCurrencyFields(props) {
801
+ const { rate, base, currencies, rates, onChange } = props;
802
+ const converted = (minor, entry)=>minor == null ? '' : CommerceModel.minorToInput(CommerceModel.amountMinorIn(minor, base, entry, rates), entry.code);
803
+ return /*#__PURE__*/ _jsxs(Stack, {
804
+ spacing: 1,
805
+ sx: {
806
+ pl: 2
807
+ },
808
+ children: [
809
+ /*#__PURE__*/ _jsx(Typography, {
810
+ variant: "caption",
811
+ color: "text.secondary",
812
+ children: 'In other currencies. Leave one blank to convert it from the price above.'
813
+ }),
814
+ currencies.map((entry)=>{
815
+ var _rate_amountCents;
816
+ var _rate_amountsByCurrency, _rate_freeOverByCurrency;
817
+ return /*#__PURE__*/ _jsxs(Stack, {
818
+ direction: "row",
819
+ spacing: 1,
820
+ children: [
821
+ /*#__PURE__*/ _jsx(TextField, {
822
+ label: `Price (${entry.code})`,
823
+ defaultValue: CommerceModel.minorToInput((_rate_amountsByCurrency = rate.amountsByCurrency) == null ? void 0 : _rate_amountsByCurrency[entry.code], entry.code),
824
+ placeholder: converted((_rate_amountCents = rate.amountCents) != null ? _rate_amountCents : 0, entry),
825
+ onBlur: (event)=>onChange('amountsByCurrency', entry.code, event.target.value),
826
+ size: "small",
827
+ sx: {
828
+ width: 140
829
+ },
830
+ slotProps: {
831
+ htmlInput: {
832
+ inputMode: 'decimal'
833
+ }
834
+ }
835
+ }, `${rate.id}-amount-${entry.code}`),
836
+ rate.kind === 'free_over' ? /*#__PURE__*/ _jsx(TextField, {
837
+ label: `Free at subtotal (${entry.code})`,
838
+ defaultValue: CommerceModel.minorToInput((_rate_freeOverByCurrency = rate.freeOverByCurrency) == null ? void 0 : _rate_freeOverByCurrency[entry.code], entry.code),
839
+ placeholder: converted(rate.freeOverCents, entry),
840
+ onBlur: (event)=>onChange('freeOverByCurrency', entry.code, event.target.value),
841
+ size: "small",
842
+ sx: {
843
+ width: 190
844
+ },
845
+ slotProps: {
846
+ htmlInput: {
847
+ inputMode: 'decimal'
848
+ }
849
+ }
850
+ }, `${rate.id}-free-${entry.code}`) : null
851
+ ]
852
+ }, entry.code);
853
+ })
854
+ ]
855
+ });
856
+ }
758
857
 
759
858
  //# sourceMappingURL=shipping-settings-card.component.js.map