@aglyn/plugins-commerce 1.20.3 → 1.21.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.
- package/package.json +13 -13
- package/src/lib/components/cart.js +106 -9
- package/src/lib/components/cart.js.map +1 -1
- package/src/lib/components/console/catalog-organization-card.component.js +81 -30
- package/src/lib/components/console/catalog-organization-card.component.js.map +1 -1
- package/src/lib/components/console/discounts-card.component.js +28 -3
- package/src/lib/components/console/discounts-card.component.js.map +1 -1
- package/src/lib/components/console/local-delivery-settings-card.component.js +23 -7
- package/src/lib/components/console/local-delivery-settings-card.component.js.map +1 -1
- package/src/lib/components/console/product-editor-dialog.component.js +61 -44
- package/src/lib/components/console/product-editor-dialog.component.js.map +1 -1
- package/src/lib/components/console/products-hub-card.component.js +32 -4
- package/src/lib/components/console/products-hub-card.component.js.map +1 -1
- package/src/lib/components/console/quote-settings-card.component.js +20 -6
- package/src/lib/components/console/quote-settings-card.component.js.map +1 -1
- package/src/lib/components/console/reservations-card.component.js +28 -2
- package/src/lib/components/console/reservations-card.component.js.map +1 -1
- package/src/lib/components/console/return-settings-card.component.js +28 -15
- package/src/lib/components/console/return-settings-card.component.js.map +1 -1
- package/src/lib/components/console/shipping-settings-card.component.js +23 -8
- package/src/lib/components/console/shipping-settings-card.component.js.map +1 -1
- package/src/lib/components/console/store-settings-card.component.js +27 -11
- package/src/lib/components/console/store-settings-card.component.js.map +1 -1
- package/src/lib/components/console/suppliers-card.component.js +38 -13
- package/src/lib/components/console/suppliers-card.component.js.map +1 -1
- package/src/lib/components/console/tax-settings-card.component.js +25 -10
- package/src/lib/components/console/tax-settings-card.component.js.map +1 -1
- package/src/lib/server/cart.js +57 -0
- package/src/lib/server/cart.js.map +1 -1
- package/src/lib/server/pos-terminal.js +2 -2
- package/src/lib/server/pos-terminal.js.map +1 -1
- package/src/lib/transfer/product-transfer.js +15 -1
- package/src/lib/transfer/product-transfer.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/quote-settings-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\n'use client'\n\nimport * as CommerceModel from '../../model'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore, useFirestoreDoc, writeGuardedBySeed } from '@aglyn/tenant-feature-instance'\nimport {\n Box,\n Button,\n Divider,\n FormControlLabel,\n FormHelperText,\n Stack,\n Switch,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport { doc, setDoc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\n\nexport interface QuoteSettingsCardProps {\n hostId: string\n}\n\n/** The card's settings as the form holds them. */\ninterface QuoteSettingsDraft {\n requireProofApproval: boolean\n requireProofSignIn: boolean\n /** As typed; blanks are dropped when saved. */\n approvalStatements: string[]\n}\n\n/**\n * The store's quote defaults, on `hosts/{hostId}/settings/store` under\n * `quotes`: whether a new quote starts out asking the customer to approve the\n * proof before they can pay (AGL-4093), whether it starts out asking a\n * customer with a site account to sign in to see the proof (AGL-4206), and\n * what every customer ticks before Approve works (AGL-4206). Each quote keeps\n * its own switches; the statements are the store's, read when the customer\n * opens the quote.\n */\nexport function QuoteSettingsCard(props: QuoteSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const {\n data: store,\n status,\n // The switches are seeded from this document; a seed the server never\n // confirmed must not be written back over the saved settings (AGL-1358).\n fromCache,\n listen,\n } = useFirestoreDoc<any>(() => doc(firestore, 'hosts', hostId, 'settings', 'store'), [firestore, hostId])\n const saved: QuoteSettingsDraft = {\n requireProofApproval: CommerceModel.quoteRequiresProofApprovalByDefault(store?.quotes),\n requireProofSignIn: CommerceModel.quoteRequiresProofSignInByDefault(store?.quotes),\n approvalStatements: CommerceModel.quoteApprovalStatements(store?.quotes),\n }\n const [draft, setDraft] = useState<QuoteSettingsDraft | null>(null)\n const form = draft ?? saved\n const [busy, setBusy] = useState(false)\n const loading = status === 'loading'\n const edit = (patch: Partial<QuoteSettingsDraft>) => setDraft({ ...form, ...patch })\n const statements = form.approvalStatements\n const cleaned = CommerceModel.cleanQuoteApprovalStatements(statements)\n\n const save = useCallback(async () => {\n const current: CommerceModel.QuoteStoreSettings = {\n requireProofApproval: form.requireProofApproval,\n requireProofSignIn: form.requireProofSignIn,\n approvalStatements: CommerceModel.cleanQuoteApprovalStatements(form.approvalStatements),\n }\n setBusy(true)\n try {\n const verdict = await writeGuardedBySeed(\n { subject: 'quote settings', unreadable: status === 'error', fromCache, listen },\n async () => {\n await setDoc(doc(firestore, 'hosts', hostId, 'settings', 'store'), { quotes: current }, { merge: true })\n },\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, { variant: 'warning', persist: false })\n }\n setDraft(null)\n enqueueSnackbar('Quote settings saved', { variant: 'success', persist: false })\n } finally {\n setBusy(false)\n }\n }, [form, firestore, hostId, status, fromCache, listen, enqueueSnackbar])\n\n return (\n <CardDisplay\n header={'Quotes'}\n help={pluginDocsHelp('quotes', {\n anchor: '#quote-defaults',\n title: 'Quotes',\n excerpt: 'What every new quote starts with, and what customers confirm before they approve a proof.',\n })}\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={busy || draft === null || loading || cleaned.length === 0}\n onClick={() => void save()}\n >\n {'Save'}\n </Button>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n <Stack spacing={0.5}>\n <FormControlLabel\n control={\n <Switch\n checked={form.requireProofApproval}\n disabled={busy || loading}\n onChange={(event) => edit({ requireProofApproval: event.target.checked })}\n />\n }\n label=\"Customers approve the proof before they can pay\"\n />\n <FormControlLabel\n control={\n <Switch\n checked={form.requireProofSignIn}\n disabled={busy || loading}\n onChange={(event) => edit({ requireProofSignIn: event.target.checked })}\n />\n }\n label=\"Customers sign in to see and approve proofs\"\n />\n <FormHelperText>\n {'New quotes start with these settings, and you can change them on each quote. Signing in applies to a ' +\n 'customer with an account on your site; a customer without one, like a phone or walk-in customer, keeps ' +\n 'using the private link.'}\n </FormHelperText>\n </Stack>\n\n <Divider />\n\n <Stack spacing={1.5}>\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Before a customer approves a proof'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'They tick each of these, then type their name. The quote keeps what they confirmed, with their name and the time.'}\n </Typography>\n </Stack>\n {statements.map((statement, index) => (\n <Stack key={index} direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <TextField\n fullWidth\n size=\"small\"\n multiline\n label={`Statement ${index + 1}`}\n value={statement}\n disabled={busy || loading}\n onChange={(event) =>\n edit({ approvalStatements: statements.map((entry, at) => (at === index ? event.target.value : entry)) })\n }\n slotProps={{ htmlInput: { maxLength: CommerceModel.QUOTE_MAX_APPROVAL_STATEMENT } }}\n />\n <Tooltip title={statements.length <= 1 ? 'Customers confirm at least one statement' : ''}>\n <span>\n <Button\n size=\"small\"\n aria-label={`Remove statement ${index + 1}`}\n disabled={busy || loading || statements.length <= 1}\n onClick={() => edit({ approvalStatements: statements.filter((_entry, at) => at !== index) })}\n sx={{ mt: 0.5 }}\n >\n {'Remove'}\n </Button>\n </span>\n </Tooltip>\n </Stack>\n ))}\n {cleaned.length === 0 ? (\n <FormHelperText error>{'Write at least one statement for customers to confirm.'}</FormHelperText>\n ) : null}\n <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={busy || loading || statements.length >= CommerceModel.QUOTE_MAX_APPROVAL_STATEMENTS}\n onClick={() => edit({ approvalStatements: [...statements, ''] })}\n >\n {'Add a statement'}\n </Button>\n <Button\n size=\"small\"\n disabled={busy || loading}\n onClick={() => edit({ approvalStatements: [...CommerceModel.QUOTE_DEFAULT_APPROVAL_STATEMENTS] })}\n >\n {'Use the suggested statements'}\n </Button>\n </Box>\n </Stack>\n </Stack>\n </CardDisplay>\n )\n}\nQuoteSettingsCard.displayName = 'QuoteSettingsCard'\n\nexport default QuoteSettingsCard\n"],"names":["CommerceModel","pluginDocsHelp","CardDisplay","useSnackbar","useFirestore","useFirestoreDoc","writeGuardedBySeed","Box","Button","Divider","FormControlLabel","FormHelperText","Stack","Switch","TextField","Tooltip","Typography","doc","setDoc","useCallback","useState","QuoteSettingsCard","props","hostId","firestore","enqueueSnackbar","data","store","status","fromCache","listen","saved","requireProofApproval","quoteRequiresProofApprovalByDefault","quotes","requireProofSignIn","quoteRequiresProofSignInByDefault","approvalStatements","quoteApprovalStatements","draft","setDraft","form","busy","setBusy","loading","edit","patch","statements","cleaned","cleanQuoteApprovalStatements","save","current","verdict","subject","unreadable","merge","ok","message","variant","persist","header","help","anchor","title","excerpt","HeaderProps","action","size","disabled","length","onClick","contentGutterX","contentGutterY","spacing","control","checked","onChange","event","target","label","color","map","statement","index","direction","sx","alignItems","fullWidth","multiline","value","entry","at","slotProps","htmlInput","maxLength","QUOTE_MAX_APPROVAL_STATEMENT","span","aria-label","filter","_entry","mt","error","display","gap","flexWrap","QUOTE_MAX_APPROVAL_STATEMENTS","QUOTE_DEFAULT_APPROVAL_STATEMENTS","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;AAEA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,cAAc,QAAQ,eAAc;AAC7C,SAASC,WAAW,QAAQ,uBAAsB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AOA,OAAOR;oDAAO;gDAC1FE,IAAI;oDAAEe,IAAI;gDAAI;0DAEb;;;;;+BAtBGjB;wBA4BbnC,QAAQqB,MAAM,KAAK,kBAClB,KAAC1D;4BAAe0F,KAAK;sCAAE;6BACrB;sCACJ,MAAC9F;4BAAI8E,IAAI;gCAAEiB,SAAS;gCAAQC,KAAK;gCAAGC,UAAU;4BAAO;;8CACnD,KAAChG;oCACC2D,MAAK;oCACLT,SAAQ;oCACRU,UAAU1B,QAAQE,WAAWG,WAAWsB,MAAM,IAAIrE,cAAcyG,6BAA6B;oCAC7FnC,SAAS,IAAMzB,KAAK;4CAAER,oBAAoB;mDAAIU;gDAAY;6CAAG;wCAAC;8CAE7D;;8CAEH,KAACvC;oCACC2D,MAAK;oCACLC,UAAU1B,QAAQE;oCAClB0B,SAAS,IAAMzB,KAAK;4CAAER,oBAAoB;mDAAIrC,cAAc0G,iCAAiC;6CAAC;wCAAC;8CAE9F;;;;;;;;;AAOf;AACArF,kBAAkBsF,WAAW,GAAG;AAEhC,eAAetF,kBAAiB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/plugins/commerce/src/lib/components/console/quote-settings-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\n'use client'\n\nimport * as CommerceModel from '../../model'\nimport { pluginDocsHelp } from '@aglyn/aglyn'\nimport { CardDisplay } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useFirestore, useFirestoreDoc, writeGuardedBySeed } from '@aglyn/tenant-feature-instance'\nimport {\n Box,\n Button,\n Divider,\n FormControlLabel,\n FormHelperText,\n Stack,\n Switch,\n TextField,\n Tooltip,\n Typography,\n} from '@mui/material'\nimport { doc, setDoc } from 'firebase/firestore'\nimport { useCallback, useState } from 'react'\nimport {\n isSeedChecking,\n seedCheckingText,\n useSeedEdits,\n} from '@aglyn/tenant-feature-instance/hooks/use-seed-edits'\n\nexport interface QuoteSettingsCardProps {\n hostId: string\n}\n\n/** The card's settings as the form holds them. */\ninterface QuoteSettingsDraft {\n requireProofApproval: boolean\n requireProofSignIn: boolean\n /** As typed; blanks are dropped when saved. */\n approvalStatements: string[]\n}\n\n/**\n * The store's quote defaults, on `hosts/{hostId}/settings/store` under\n * `quotes`: whether a new quote starts out asking the customer to approve the\n * proof before they can pay (AGL-4093), whether it starts out asking a\n * customer with a site account to sign in to see the proof (AGL-4206), and\n * what every customer ticks before Approve works (AGL-4206). Each quote keeps\n * its own switches; the statements are the store's, read when the customer\n * opens the quote.\n */\nexport function QuoteSettingsCard(props: QuoteSettingsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { enqueueSnackbar } = useSnackbar()\n const {\n data: store,\n status,\n // The switches are seeded from this document; a seed the server never\n // confirmed must not be written back over the saved settings (AGL-1358).\n fromCache,\n listen,\n } = useFirestoreDoc<any>(() => doc(firestore, 'hosts', hostId, 'settings', 'store'), [firestore, hostId])\n const saved: QuoteSettingsDraft = {\n requireProofApproval: CommerceModel.quoteRequiresProofApprovalByDefault(store?.quotes),\n requireProofSignIn: CommerceModel.quoteRequiresProofSignInByDefault(store?.quotes),\n approvalStatements: CommerceModel.quoteApprovalStatements(store?.quotes),\n }\n // What was typed, kept as edits over the saved settings, and Save held\n // until the server has confirmed them (AGL-4047).\n const edits = useSeedEdits<QuoteSettingsDraft>(saved)\n const form = edits.values\n const checking = isSeedChecking({ fromCache, unreadable: status === 'error' })\n const [busy, setBusy] = useState(false)\n const loading = status === 'loading'\n const edit = (patch: Partial<QuoteSettingsDraft>) => edits.edit(patch)\n const statements = form.approvalStatements\n const cleaned = CommerceModel.cleanQuoteApprovalStatements(statements)\n\n const save = useCallback(async () => {\n const current: CommerceModel.QuoteStoreSettings = {\n requireProofApproval: form.requireProofApproval,\n requireProofSignIn: form.requireProofSignIn,\n approvalStatements: CommerceModel.cleanQuoteApprovalStatements(form.approvalStatements),\n }\n const written = edits.edits\n setBusy(true)\n try {\n const verdict = await writeGuardedBySeed(\n { subject: 'quote settings', unreadable: status === 'error', fromCache, listen },\n async () => {\n await setDoc(doc(firestore, 'hosts', hostId, 'settings', 'store'), { quotes: current }, { merge: true })\n },\n )\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, { variant: 'warning', persist: false })\n }\n edits.settle(written)\n enqueueSnackbar('Quote settings saved', { variant: 'success', persist: false })\n } finally {\n setBusy(false)\n }\n }, [form, edits, firestore, hostId, status, fromCache, listen, enqueueSnackbar])\n\n return (\n <CardDisplay\n header={'Quotes'}\n help={pluginDocsHelp('quotes', {\n anchor: '#quote-defaults',\n title: 'Quotes',\n excerpt: 'What every new quote starts with, and what customers confirm before they approve a proof.',\n })}\n HeaderProps={{\n action: (\n <Button\n size=\"small\"\n variant=\"contained\"\n disabled={busy || !edits.dirty || checking || loading || cleaned.length === 0}\n onClick={() => void save()}\n >\n {'Save'}\n </Button>\n ),\n }}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={2}>\n {edits.dirty && checking ? (\n <Typography variant=\"body2\" color=\"text.secondary\" role=\"status\">\n {seedCheckingText('quote settings')}\n </Typography>\n ) : null}\n <Stack spacing={0.5}>\n <FormControlLabel\n control={\n <Switch\n checked={form.requireProofApproval}\n disabled={busy || loading}\n onChange={(event) => edit({ requireProofApproval: event.target.checked })}\n />\n }\n label=\"Customers approve the proof before they can pay\"\n />\n <FormControlLabel\n control={\n <Switch\n checked={form.requireProofSignIn}\n disabled={busy || loading}\n onChange={(event) => edit({ requireProofSignIn: event.target.checked })}\n />\n }\n label=\"Customers sign in to see and approve proofs\"\n />\n <FormHelperText>\n {'New quotes start with these settings, and you can change them on each quote. Signing in applies to a ' +\n 'customer with an account on your site; a customer without one, like a phone or walk-in customer, keeps ' +\n 'using the private link.'}\n </FormHelperText>\n </Stack>\n\n <Divider />\n\n <Stack spacing={1.5}>\n <Stack spacing={0.5}>\n <Typography variant=\"subtitle2\">{'Before a customer approves a proof'}</Typography>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'They tick each of these, then type their name. The quote keeps what they confirmed, with their name and the time.'}\n </Typography>\n </Stack>\n {statements.map((statement, index) => (\n <Stack key={index} direction=\"row\" spacing={1} sx={{ alignItems: 'flex-start' }}>\n <TextField\n fullWidth\n size=\"small\"\n multiline\n label={`Statement ${index + 1}`}\n value={statement}\n disabled={busy || loading}\n onChange={(event) =>\n edit({ approvalStatements: statements.map((entry, at) => (at === index ? event.target.value : entry)) })\n }\n slotProps={{ htmlInput: { maxLength: CommerceModel.QUOTE_MAX_APPROVAL_STATEMENT } }}\n />\n <Tooltip title={statements.length <= 1 ? 'Customers confirm at least one statement' : ''}>\n <span>\n <Button\n size=\"small\"\n aria-label={`Remove statement ${index + 1}`}\n disabled={busy || loading || statements.length <= 1}\n onClick={() => edit({ approvalStatements: statements.filter((_entry, at) => at !== index) })}\n sx={{ mt: 0.5 }}\n >\n {'Remove'}\n </Button>\n </span>\n </Tooltip>\n </Stack>\n ))}\n {cleaned.length === 0 ? (\n <FormHelperText error>{'Write at least one statement for customers to confirm.'}</FormHelperText>\n ) : null}\n <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>\n <Button\n size=\"small\"\n variant=\"outlined\"\n disabled={busy || loading || statements.length >= CommerceModel.QUOTE_MAX_APPROVAL_STATEMENTS}\n onClick={() => edit({ approvalStatements: [...statements, ''] })}\n >\n {'Add a statement'}\n </Button>\n <Button\n size=\"small\"\n disabled={busy || loading}\n onClick={() => edit({ approvalStatements: [...CommerceModel.QUOTE_DEFAULT_APPROVAL_STATEMENTS] })}\n >\n {'Use the suggested statements'}\n </Button>\n </Box>\n </Stack>\n </Stack>\n </CardDisplay>\n )\n}\nQuoteSettingsCard.displayName = 'QuoteSettingsCard'\n\nexport default QuoteSettingsCard\n"],"names":["CommerceModel","pluginDocsHelp","CardDisplay","useSnackbar","useFirestore","useFirestoreDoc","writeGuardedBySeed","Box","Button","Divider","FormControlLabel","FormHelperText","Stack","Switch","TextField","Tooltip","Typography","doc","setDoc","useCallback","useState","isSeedChecking","seedCheckingText","useSeedEdits","QuoteSettingsCard","props","hostId","firestore","enqueueSnackbar","data","store","status","fromCache","listen","saved","requireProofApproval","quoteRequiresProofApprovalByDefault","quotes","requireProofSignIn","quoteRequiresProofSignInByDefault","approvalStatements","quoteApprovalStatements","edits","form","values","checking","unreadable","busy","setBusy","loading","edit","patch","statements","cleaned","cleanQuoteApprovalStatements","save","current","written","verdict","subject","merge","ok","message","variant","persist","settle","header","help","anchor","title","excerpt","HeaderProps","action","size","disabled","dirty","length","onClick","contentGutterX","contentGutterY","spacing","color","role","control","checked","onChange","event","target","label","map","statement","index","direction","sx","alignItems","fullWidth","multiline","value","entry","at","slotProps","htmlInput","maxLength","QUOTE_MAX_APPROVAL_STATEMENT","span","aria-label","filter","_entry","mt","error","display","gap","flexWrap","QUOTE_MAX_APPROVAL_STATEMENTS","QUOTE_DEFAULT_APPROVAL_STATEMENTS","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;AAEA,YAAYA,mBAAmB,uBAAa;AAC5C,SAASC,cAAc,QAAQ,eAAc;AAC7C,SAASC,WAAW,QAAQ,uBAAsB;AAClD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,YAAY,EAAEC,eAAe,EAAEC,kBAAkB,QAAQ,iCAAgC;AAClG,SACEC,GAAG,EACHC,MAAM,EACNC,OAAO,EACPC,gBAAgB,EAChBC,cAAc,EACdC,KAAK,EACLC,MAAM,EACNC,SAAS,EACTC,OAAO,EACPC,UAAU,QACL,gBAAe;AACtB,SAASC,GAAG,EA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DAClDC,SAAS,IAAM3B,KAAK;wDAAEV,oBAAoBY,WAAWsD,MAAM,CAAC,CAACC,QAAQR,KAAOA,OAAOR;oDAAO;gDAC1FE,IAAI;oDAAEe,IAAI;gDAAI;0DAEb;;;;;+BAtBGjB;wBA4BbtC,QAAQuB,MAAM,KAAK,kBAClB,KAACjE;4BAAekG,KAAK;sCAAE;6BACrB;sCACJ,MAACtG;4BAAIsF,IAAI;gCAAEiB,SAAS;gCAAQC,KAAK;gCAAGC,UAAU;4BAAO;;8CACnD,KAACxG;oCACCiE,MAAK;oCACLV,SAAQ;oCACRW,UAAU3B,QAAQE,WAAWG,WAAWwB,MAAM,IAAI5E,cAAciH,6BAA6B;oCAC7FpC,SAAS,IAAM3B,KAAK;4CAAEV,oBAAoB;mDAAIY;gDAAY;6CAAG;wCAAC;8CAE7D;;8CAEH,KAAC5C;oCACCiE,MAAK;oCACLC,UAAU3B,QAAQE;oCAClB4B,SAAS,IAAM3B,KAAK;4CAAEV,oBAAoB;mDAAIxC,cAAckH,iCAAiC;6CAAC;wCAAC;8CAE9F;;;;;;;;;AAOf;AACA1F,kBAAkB2F,WAAW,GAAG;AAEhC,eAAe3F,kBAAiB"}
|
|
@@ -31,6 +31,8 @@ import { authorizedFetch } from "@aglyn/shared-util-http/authorized-token";
|
|
|
31
31
|
import { PrerequisiteNotice } from "@aglyn/shared-ui-jsx/components/prerequisite-notice.component";
|
|
32
32
|
import { useFirestoreCollection, usePagedCollection, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
|
|
33
33
|
import { pluginDocsHelp } from "@aglyn/aglyn";
|
|
34
|
+
import { isSeedChecking, seedCheckingText } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
|
|
35
|
+
import { useSeedDraft } from "@aglyn/tenant-feature-instance/hooks/use-seed-draft";
|
|
34
36
|
/** A stay's guest count after booking (AGL-4043), loaded the first time it opens. */ const ReservationGuestsDialog = /*#__PURE__*/ lazy(()=>import("./reservation-guests-dialog.component.js"));
|
|
35
37
|
/** The statuses whose guest count staff can still change. */ const GUESTS_OPEN_STATUSES = [
|
|
36
38
|
'pending',
|
|
@@ -182,7 +184,21 @@ const nightLabel = (dayMs)=>new Date(dayMs).toLocaleDateString('en-US', {
|
|
|
182
184
|
}, [
|
|
183
185
|
resourceDocs
|
|
184
186
|
]);
|
|
185
|
-
|
|
187
|
+
/*
|
|
188
|
+
* The dialog's draft, kept as EDITS over the resource as the list has it
|
|
189
|
+
* now (AGL-4047): opened from the cache's row, the server's copy replaces
|
|
190
|
+
* it under every field nobody touched (`blocks` among them), and Save is
|
|
191
|
+
* held until it has.
|
|
192
|
+
*/ const [resourceDraft, setResourceDraft] = useSeedDraft((opened)=>{
|
|
193
|
+
const row = opened.id ? resourceDocs == null ? void 0 : resourceDocs.find((resource)=>resource.$id === opened.id) : undefined;
|
|
194
|
+
return row ? _extends({
|
|
195
|
+
id: row.$id
|
|
196
|
+
}, row) : undefined;
|
|
197
|
+
});
|
|
198
|
+
const resourceChecking = Boolean(resourceDraft == null ? void 0 : resourceDraft.id) && isSeedChecking({
|
|
199
|
+
fromCache: resourcesFromCache,
|
|
200
|
+
unreadable: resourcesStatus === 'error'
|
|
201
|
+
});
|
|
186
202
|
const [walkIn, setWalkIn] = useState(null);
|
|
187
203
|
const [walkInBusy, setWalkInBusy] = useState(false);
|
|
188
204
|
/** The stay whose guests are being changed (AGL-4043). */ const [guestsFor, setGuestsFor] = useState(null);
|
|
@@ -262,6 +278,7 @@ const nightLabel = (dayMs)=>new Date(dayMs).toLocaleDateString('en-US', {
|
|
|
262
278
|
persist: false
|
|
263
279
|
});
|
|
264
280
|
}, [
|
|
281
|
+
setResourceDraft,
|
|
265
282
|
resourceDraft,
|
|
266
283
|
firestore,
|
|
267
284
|
hostId,
|
|
@@ -857,6 +874,15 @@ const nightLabel = (dayMs)=>new Date(dayMs).toLocaleDateString('en-US', {
|
|
|
857
874
|
}),
|
|
858
875
|
/*#__PURE__*/ _jsxs(DialogActions, {
|
|
859
876
|
children: [
|
|
877
|
+
resourceChecking ? /*#__PURE__*/ _jsx(Typography, {
|
|
878
|
+
variant: "body2",
|
|
879
|
+
color: "text.secondary",
|
|
880
|
+
role: "status",
|
|
881
|
+
sx: {
|
|
882
|
+
mr: 'auto'
|
|
883
|
+
},
|
|
884
|
+
children: seedCheckingText('resource')
|
|
885
|
+
}) : null,
|
|
860
886
|
/*#__PURE__*/ _jsx(Button, {
|
|
861
887
|
onClick: ()=>setResourceDraft(null),
|
|
862
888
|
children: 'Cancel'
|
|
@@ -864,7 +890,7 @@ const nightLabel = (dayMs)=>new Date(dayMs).toLocaleDateString('en-US', {
|
|
|
864
890
|
/*#__PURE__*/ _jsx(Button, {
|
|
865
891
|
variant: "contained",
|
|
866
892
|
color: "primary",
|
|
867
|
-
disabled: !(resourceDraft == null ? void 0 : (_resourceDraft_name = resourceDraft.name) == null ? void 0 : _resourceDraft_name.trim()) || !(((_ref10 = resourceDraft == null ? void 0 : resourceDraft.nightlyRateUsd) != null ? _ref10 : 0) > 0) || Boolean(unitsProblem(resourceDraft == null ? void 0 : resourceDraft.units)) || Boolean(fewLeftAtProblem(resourceDraft == null ? void 0 : resourceDraft.fewLeftAt)),
|
|
893
|
+
disabled: resourceChecking || !(resourceDraft == null ? void 0 : (_resourceDraft_name = resourceDraft.name) == null ? void 0 : _resourceDraft_name.trim()) || !(((_ref10 = resourceDraft == null ? void 0 : resourceDraft.nightlyRateUsd) != null ? _ref10 : 0) > 0) || Boolean(unitsProblem(resourceDraft == null ? void 0 : resourceDraft.units)) || Boolean(fewLeftAtProblem(resourceDraft == null ? void 0 : resourceDraft.fewLeftAt)),
|
|
868
894
|
onClick: handleResourceSave,
|
|
869
895
|
children: 'Save'
|
|
870
896
|
})
|
|
@@ -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'\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 const [resourceDraft, setResourceDraft] = useState<\n (Partial<CommerceModel.HostResource> & { id: string | null }) | null\n >(null)\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 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 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 <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 }\n onClick={handleResourceSave}\n >\n {'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","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","walkIn","setWalkIn","walkInBusy","setWalkInBusy","guestsFor","setGuestsFor","handleResourceSave","trim","nightlyRateUsd","seeded","id","_syntheticId","fields","resourceFewLeftAt","verdict","subject","unreadable","Boolean","createResourceUid","merge","ok","message","variant","persist","handleStatus","reservation","handleWalkIn","checkIn","checkOut","find","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","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","type","inputLabel","shrink","resourceGuestCeiling","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,YAAYA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;0CAEP,KAAC7L;gCACC2M,OAAM;gCACN+B,KAAK,YAAExH,0BAAAA,OAAQgC,MAAM,qBAAI;gCACzByF,UAAU,CAACC,QACTzH,UAAU,CAAC0H,OACTA,OAAO,aAAKA;4CAAM3F,QAAQ0F,MAAME,MAAM,CAACJ,KAAK,CAACrB,OAAO,CAAC,OAAO;6CAAQwB;gCAGxEI,YAAY,CAAC,gBAAgB,EAAE/P,cAAc8Q,oBAAoB,CAC/D,CAACpL,uBAAAA,eAAgB,EAAE,EAAEmE,IAAI,CAAC,CAACC,OAAcA,KAAKvC,GAAG,MAAKS,0BAAAA,OAAQV,UAAU,IACxE,mEAAmE,CAAC;gCACtEqF,MAAK;gCACLqD,WAAW;oCAAEC,WAAW;wCAAEC,WAAW;oCAAU;gCAAE;;;;kCAGrD,MAACzP;;0CACC,KAACH;gCAAOuM,SAAS,IAAM5E,UAAU;0CAAQ;;0CACzC,KAAC3H;gCACCgJ,SAAQ;gCACRoD,OAAM;gCACNE,UACE1E,cACA,EAACF,0BAAAA,OAAQV,UAAU,KACnB,EAACU,0BAAAA,OAAQ2B,OAAO,KAChB,EAAC3B,0BAAAA,OAAQ4B,QAAQ;gCAEnBiD,SAASnD;0CAER;;;;;;;;AAMb;AACA7E,iBAAiBkM,WAAW,GAAG;AAE/B,eAAelM,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 isSeedChecking,\n seedCheckingText,\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 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 resourceChecking ||\n !resourceDraft?.name?.trim() ||\n !((resourceDraft?.nightlyRateUsd ?? 0) > 0) ||\n Boolean(unitsProblem(resourceDraft?.units)) ||\n Boolean(fewLeftAtProblem(resourceDraft?.fewLeftAt))\n }\n onClick={handleResourceSave}\n >\n {'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","isSeedChecking","seedCheckingText","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","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","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,mBAAmB,EAAEC,OAAO,QAAQ,iCAAgC;AAC3F,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAASC,kBAAkB,QAAQ,gEAA+D;AAClG,SACEC,sBAAsB,EACtBC,kBAAkB,EAClBC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,cAAc,QAAQ,eAAc;AAC7C,SACEC,cAAc,EACdC,gBAAgB,QACX,sDAAqD;AAC5D,SAASC,YAAY,QAAQ,sDAAqD;AAelF,mFAAmF,GACnF,MAA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AE,EAAEyC,IAAI,CAAC,CAAC8B,OAAcA,KAAK1C,GAAG,MAAKgB,0BAAAA,OAAQjB,UAAU,IACxE,mEAAmE,CAAC;gCACtEwF,MAAK;gCACLqD,WAAW;oCAAEC,WAAW;wCAAEC,WAAW;oCAAU;gCAAE;;;;kCAGrD,MAAC/P;;0CACC,KAACH;gCAAO6M,SAAS,IAAMxE,UAAU;0CAAQ;;0CACzC,KAACrI;gCACCuJ,SAAQ;gCACRmD,OAAM;gCACNE,UACEtE,cACA,EAACF,0BAAAA,OAAQjB,UAAU,KACnB,EAACiB,0BAAAA,OAAQwB,OAAO,KAChB,EAACxB,0BAAAA,OAAQyB,QAAQ;gCAEnBgD,SAASlD;0CAER;;;;;;;;AAMb;AACAjF,iBAAiBuM,WAAW,GAAG;AAE/B,eAAevM,iBAAgB"}
|
|
@@ -14,17 +14,17 @@
|
|
|
14
14
|
* See the License for the specific language governing permissions and
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/ 'use client';
|
|
17
|
-
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
18
17
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
19
18
|
import * as CommerceModel from "../../model/index.js";
|
|
20
19
|
import { CardDisplay } from "@aglyn/shared-ui-jsx";
|
|
21
20
|
import { useSnackbar } from "@aglyn/shared-ui-snackstack";
|
|
22
|
-
import { Button, Checkbox, FormControlLabel, FormGroup, FormLabel, Stack, Switch, TextField } from "@mui/material";
|
|
21
|
+
import { Button, Checkbox, FormControlLabel, FormGroup, FormLabel, Stack, Switch, TextField, Typography } from "@mui/material";
|
|
23
22
|
import { doc } from "firebase/firestore";
|
|
24
|
-
import { useCallback, useMemo
|
|
23
|
+
import { useCallback, useMemo } from "react";
|
|
25
24
|
import { useFirestore, useFirestoreDoc, useUser, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
|
|
26
25
|
import { pluginDocsHelp } from "@aglyn/aglyn";
|
|
27
26
|
import { writeSiteWideChange } from "@aglyn/tenant-feature-instance/hooks/helpers/site-wide-change";
|
|
27
|
+
import { isSeedChecking, seedCheckingText, useSeedEdits } from "@aglyn/tenant-feature-instance/hooks/use-seed-edits";
|
|
28
28
|
const PRODUCT_TYPE_LABELS = {
|
|
29
29
|
physical: 'Physical products',
|
|
30
30
|
digital: 'Digital products',
|
|
@@ -48,20 +48,25 @@ const PRODUCT_TYPE_LABELS = {
|
|
|
48
48
|
firestore,
|
|
49
49
|
hostId
|
|
50
50
|
]);
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
if (draft) return draft;
|
|
54
|
-
const saved = CommerceModel.readReturnSettings(store == null ? void 0 : store.returns);
|
|
51
|
+
const saved = useMemo(()=>{
|
|
52
|
+
const stored = CommerceModel.readReturnSettings(store == null ? void 0 : store.returns);
|
|
55
53
|
return {
|
|
56
|
-
enabled:
|
|
57
|
-
windowDays: String(
|
|
58
|
-
eligibleTypes:
|
|
54
|
+
enabled: stored.enabled,
|
|
55
|
+
windowDays: String(stored.windowDays),
|
|
56
|
+
eligibleTypes: stored.eligibleTypes
|
|
59
57
|
};
|
|
60
58
|
}, [
|
|
61
|
-
draft,
|
|
62
59
|
store
|
|
63
60
|
]);
|
|
64
|
-
|
|
61
|
+
// What was typed, kept as edits over the saved settings, and Save held
|
|
62
|
+
// until the server has confirmed them (AGL-4047).
|
|
63
|
+
const form = useSeedEdits(saved);
|
|
64
|
+
const current = form.values;
|
|
65
|
+
const update = (patch)=>form.edit(patch);
|
|
66
|
+
const checking = isSeedChecking({
|
|
67
|
+
fromCache: storeFromCache,
|
|
68
|
+
unreadable: storeStatus === 'error'
|
|
69
|
+
});
|
|
65
70
|
const days = Number(current.windowDays);
|
|
66
71
|
const daysValid = current.windowDays.trim() !== '' && Number.isInteger(days) && days >= 0 && days <= CommerceModel.RETURN_WINDOW_MAX_DAYS;
|
|
67
72
|
const toggleType = (type, on)=>update({
|
|
@@ -72,6 +77,7 @@ const PRODUCT_TYPE_LABELS = {
|
|
|
72
77
|
});
|
|
73
78
|
const handleSave = useCallback(async ()=>{
|
|
74
79
|
if (!daysValid) return;
|
|
80
|
+
const written = form.edits;
|
|
75
81
|
const verdict = await writeGuardedBySeed({
|
|
76
82
|
subject: 'return settings',
|
|
77
83
|
unreadable: storeStatus === 'error',
|
|
@@ -103,12 +109,13 @@ const PRODUCT_TYPE_LABELS = {
|
|
|
103
109
|
persist: false
|
|
104
110
|
});
|
|
105
111
|
}
|
|
106
|
-
|
|
112
|
+
form.settle(written);
|
|
107
113
|
enqueueSnackbar('Return settings saved', {
|
|
108
114
|
variant: 'success',
|
|
109
115
|
persist: false
|
|
110
116
|
});
|
|
111
117
|
}, [
|
|
118
|
+
form,
|
|
112
119
|
daysValid,
|
|
113
120
|
storeStatus,
|
|
114
121
|
storeFromCache,
|
|
@@ -180,13 +187,19 @@ const PRODUCT_TYPE_LABELS = {
|
|
|
180
187
|
variant: "contained",
|
|
181
188
|
color: "primary",
|
|
182
189
|
size: "small",
|
|
183
|
-
disabled: !
|
|
190
|
+
disabled: !form.dirty || checking || !daysValid,
|
|
184
191
|
onClick: handleSave,
|
|
185
192
|
sx: {
|
|
186
193
|
alignSelf: 'flex-start'
|
|
187
194
|
},
|
|
188
195
|
children: 'Save return settings'
|
|
189
|
-
})
|
|
196
|
+
}),
|
|
197
|
+
form.dirty && checking ? /*#__PURE__*/ _jsx(Typography, {
|
|
198
|
+
variant: "body2",
|
|
199
|
+
color: "text.secondary",
|
|
200
|
+
role: "status",
|
|
201
|
+
children: seedCheckingText('return settings')
|
|
202
|
+
}) : null
|
|
190
203
|
]
|
|
191
204
|
})
|
|
192
205
|
});
|