Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5676262692 | ||
|
|
d3358c7c58 | ||
|
|
4e825c7ca7 | ||
|
|
b83af1b872 | ||
|
|
f8365e05af | ||
|
|
0039b09d98 | ||
|
|
e9b67efd46 | ||
|
|
0047099742 | ||
|
|
c753d1e9fa | ||
|
|
fe7122b107 | ||
|
|
630d5cb708 |
@@ -2,3 +2,5 @@ node_modules
|
||||
build
|
||||
.dockerignore
|
||||
Dockerfile
|
||||
.env
|
||||
.env.local
|
||||
@@ -0,0 +1,3 @@
|
||||
# App config Variables (Will be visible by client):
|
||||
VITE_BACKEND_HOST=SOMNIAROOMS_BACKEND_HOST
|
||||
VITE_BACKEND_PORT=SOMNIAROOMS_BACKEND_PORT
|
||||
@@ -0,0 +1,23 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request: ~
|
||||
workflow_dispatch: ~
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
|
||||
lint:
|
||||
name: Docker Lint
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Lint Dockerfile
|
||||
uses: hadolint/[email protected]
|
||||
@@ -0,0 +1,45 @@
|
||||
name: Publish_on_Tag
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- devbuild_*
|
||||
workflow_dispatch: ~
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build and Push
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
with:
|
||||
platforms: arm64
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to local registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{vars.REGISTRY_INSTANCE}}
|
||||
username: ${{gitea.repository_owner}}
|
||||
password: ${{secrets.REGISTRY_TOKEN}} # It should be a user/org token with package perms.
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{vars.REGISTRY_INSTANCE}}/somnia/somniaroomsapp:devbuild
|
||||
target: final-prod
|
||||
platforms: linux/amd64,linux/arm64
|
||||
secrets: |
|
||||
GIT_AUTH_TOKEN=${{secrets.REGISTRY_TOKEN}}
|
||||
+4
-2
@@ -14,11 +14,13 @@ CMD ["npm", "run", "dev"]
|
||||
|
||||
# Build app for production.
|
||||
FROM app-base as builder
|
||||
RUN npm ci
|
||||
RUN npm run build
|
||||
RUN npm ci && npm run build
|
||||
|
||||
# production environment
|
||||
FROM nginx:stable-alpine as final-prod
|
||||
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||
COPY /public /usr/share/nginx/html/public
|
||||
COPY scripts/env.sh /docker-entrypoint.d/env.sh
|
||||
EXPOSE 80
|
||||
RUN chmod +x /docker-entrypoint.d/env.sh
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
|
||||
@@ -31,3 +31,30 @@ docker build -t somniarooms-app:prod --target final-prod .
|
||||
```
|
||||
docker run -d -it -p 8080:80 --name somniarooms-app somniarooms-app:prod
|
||||
```
|
||||
|
||||
**Docker run with env vars:**
|
||||
```
|
||||
docker run -d -it -p 8080:80 --name somniarooms-app -e SOMNIAROOMS_BACKEND_HOST=https://somniaapi.example.org/ -e SOMNIAROOMS_BACKEND_PORT=443 somniarooms-app:prod
|
||||
```
|
||||
|
||||
## Env Vars.
|
||||
As this is distributed as a docker image ready to use, you must set some env variables to configure the app:
|
||||
|
||||
| Var | Default Value | Description |
|
||||
| :------------------------: | :----------------------------: | :------------------------------------------------------------------------------------------: |
|
||||
| `SOMNIAROOMS_BACKEND_HOST` | https://somniaapi.example.org/ | Host where uses can connect to the SomniaRoom API. API endpoint should be reachble for uses. |
|
||||
| `SOMNIAROOMS_BACKEND_PORT` | 443 | Port to SomniarRooms API. |
|
||||
|
||||
## .env files
|
||||
|
||||
This project uses .env files to configure the app. As Vite only supports compile-time vars, we use some tricks to allow setting variables from container env variables.
|
||||
|
||||
### .env
|
||||
Contains default values. It is just an example configuration.
|
||||
|
||||
For development is recomended to create a `.env.local` file based on `.env`.
|
||||
|
||||
### .env.production
|
||||
Set varibles to certains placeholder, that are replace on container startup.
|
||||
|
||||
(We are using this solution: https://stackoverflow.com/a/77454537)
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<link rel="icon" type="image/svg+xml" href="/SR2.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Vite + React + TS</title>
|
||||
</head>
|
||||
|
||||
Generated
+37
-1
@@ -27,7 +27,8 @@
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.23.0",
|
||||
"swr": "^2.2.5",
|
||||
"tailwind-merge": "^2.3.0"
|
||||
"tailwind-merge": "^2.3.0",
|
||||
"zustand": "^4.5.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.12.8",
|
||||
@@ -5044,6 +5045,41 @@
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/zustand": {
|
||||
"version": "4.5.2",
|
||||
"resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.2.tgz",
|
||||
"integrity": "sha512-2cN1tPkDVkwCy5ickKrI7vijSjPksFRfqS6237NzT0vqSsztTNnQdHw9mmN7uBdk3gceVXU0a+21jFzFzAc9+g==",
|
||||
"dependencies": {
|
||||
"use-sync-external-store": "1.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.7.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": ">=16.8",
|
||||
"immer": ">=9.0.6",
|
||||
"react": ">=16.8"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"immer": {
|
||||
"optional": true
|
||||
},
|
||||
"react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/zustand/node_modules/use-sync-external-store": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz",
|
||||
"integrity": "sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==",
|
||||
"peerDependencies": {
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -29,7 +29,8 @@
|
||||
"react-dom": "^18.2.0",
|
||||
"react-router-dom": "^6.23.0",
|
||||
"swr": "^2.2.5",
|
||||
"tailwind-merge": "^2.3.0"
|
||||
"tailwind-merge": "^2.3.0",
|
||||
"zustand": "^4.5.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.12.8",
|
||||
|
||||
+2121
File diff suppressed because it is too large
Load Diff
|
After Width: | Height: | Size: 96 KiB |
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
for i in $(env | grep SOMNIAROOMS_)
|
||||
do
|
||||
key=$(echo $i | cut -d '=' -f 1)
|
||||
value=$(echo $i | cut -d '=' -f 2-)
|
||||
echo $key=$value
|
||||
# sed All files
|
||||
# find /usr/share/nginx/html -type f -exec sed -i "s|${key}|${value}|g" '{}' +
|
||||
|
||||
# sed JS and CSS only
|
||||
find /usr/share/nginx/html -type f \( -name '*.js' -o -name '*.css' \) -exec sed -i "s|${key}|${value}|g" '{}' +
|
||||
done
|
||||
@@ -0,0 +1,19 @@
|
||||
import { NewBooking, NewBookingResponse } from "@/model/Bookings";
|
||||
import { fetcherWithFilter } from "./backend";
|
||||
|
||||
export async function APISendCreateBooking(bookingData: NewBooking | null) {
|
||||
|
||||
if (!bookingData) {
|
||||
return {
|
||||
bookingResponse: null,
|
||||
isError: true
|
||||
}
|
||||
}
|
||||
|
||||
const rs = await fetcherWithFilter<NewBookingResponse>("/api/booking/create", bookingData);
|
||||
|
||||
return {
|
||||
bookingResponse: rs,
|
||||
isError: false
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { fetcherUnwraperWithFilter } from "./backend";
|
||||
import useSWR from 'swr';
|
||||
import { AvailabilityFilter, AvailabilityRequest, RoomAvailabity } from "@/model/RoomSearch";
|
||||
import { AvailabilityFilter, AvailabilityRequest, FareFilter, FareRequest, RoomAvailabity, RoomPrice } from "@/model/RoomSearch";
|
||||
|
||||
export function useAPIRoomAvailability(filter: AvailabilityFilter | null) {
|
||||
|
||||
@@ -16,3 +16,18 @@ export function useAPIRoomAvailability(filter: AvailabilityFilter | null) {
|
||||
isError: error
|
||||
}
|
||||
}
|
||||
|
||||
export function useAPIRoomPrices(filter: FareFilter | null) {
|
||||
|
||||
const request: FareRequest | null = filter ? {
|
||||
filter: filter
|
||||
} : null;
|
||||
|
||||
const { data, isLoading, error } = useSWR(request ? ['/api/search/fares', request] : null, ([url, request]) => fetcherUnwraperWithFilter<RoomPrice[]>(url, request))
|
||||
|
||||
return {
|
||||
roomPriceList: data,
|
||||
isLoading,
|
||||
isError: error
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,70 @@
|
||||
import { useAPIRoomCategoryId } from "@/api/api-roomCategories"
|
||||
import { Card, CardContent, CardHeader } from "../ui/card"
|
||||
import { useState } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Typography } from "../ui/typography";
|
||||
import { Button } from "../ui/button";
|
||||
import { RoomCategoryPhoto } from "@/model/RoomCategory";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
|
||||
import { Skeleton } from "../ui/skeleton";
|
||||
import { useAppStore } from "@/store";
|
||||
import { DateRange } from "react-day-picker";
|
||||
import { FareFilter } from "@/model/RoomSearch";
|
||||
import { useAPIRoomPrices } from "@/api/api-roomSearch";
|
||||
import { NumberSelector } from "../ui/number-selector";
|
||||
import { NewBookingRoom } from "@/model/Bookings";
|
||||
|
||||
function RoomBooking({ roomCategoryId, availableAmount }: { roomCategoryId: number, availableAmount: number }) {
|
||||
|
||||
const [selectedAmount, setSelectedAmount] = useState<number>(0);
|
||||
const [selectedAmount, setSelectedAmount] = useState<Map<number, number>>(new Map());
|
||||
|
||||
const currentDates: DateRange = useAppStore((state) => (state.searchFilter.dateRange));
|
||||
const addNewRoom = useAppStore((state) => (state.addNewBookingRoom));
|
||||
|
||||
function onSelectedAmountUpdate(guestNumber: number, newCount: number, price: number) {
|
||||
console.log("Room " + roomCategoryId + " Guestnumber: " + guestNumber + " Count: " + newCount);
|
||||
|
||||
const newAmountMap = new Map(selectedAmount);
|
||||
newAmountMap.set(guestNumber, newCount);
|
||||
setSelectedAmount(newAmountMap)
|
||||
|
||||
const newRoom: NewBookingRoom = {
|
||||
roomCategory: roomCategoryId,
|
||||
guestNumber: guestNumber,
|
||||
amount: newCount,
|
||||
price: price
|
||||
};
|
||||
addNewRoom(newRoom);
|
||||
}
|
||||
|
||||
const totalSelected = () => {
|
||||
let sum = 0;
|
||||
selectedAmount.forEach((v) => sum += v)
|
||||
return sum;
|
||||
};
|
||||
const canAddMore: boolean = availableAmount > totalSelected();
|
||||
|
||||
//This seems a little bit overkill, but IDK.
|
||||
const fareFilter: FareFilter | null = useMemo(
|
||||
() => {
|
||||
if (currentDates && currentDates.from && currentDates.to) {
|
||||
const filter: FareFilter = {
|
||||
startDate: currentDates.from?.toDateString(),
|
||||
endDate: currentDates.to?.toDateString(),
|
||||
roomCategory: roomCategoryId
|
||||
}
|
||||
return filter;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
[currentDates, roomCategoryId]
|
||||
);
|
||||
|
||||
const { roomCategory, isLoading: isLoadingCategory, isError: isErrorCategory } = useAPIRoomCategoryId(roomCategoryId);
|
||||
const { roomPriceList, isLoading: isLoadingPrices, isError: isErrorPrices } = useAPIRoomPrices(fareFilter);
|
||||
|
||||
|
||||
//TODOME: Gestionar también los estados al cargar los precios.
|
||||
const isLoading = isLoadingCategory;
|
||||
const isError = isErrorCategory;
|
||||
const isLoading = isLoadingCategory || isLoadingPrices;
|
||||
const isError = isErrorCategory || isErrorPrices;
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
@@ -34,6 +83,41 @@ function RoomBooking({ roomCategoryId, availableAmount }: { roomCategoryId: numb
|
||||
<img src={mainPhoto.path} alt={mainPhoto.altText} className="rounded-md mx-0 px-0"></img>
|
||||
);
|
||||
|
||||
const hasPrices = roomPriceList != null && roomPriceList?.length > 0;
|
||||
let priceTable = null;
|
||||
if (hasPrices) {
|
||||
const tableRows = roomPriceList?.map((el) => {
|
||||
return (
|
||||
<TableRow key={el.guestNumber}>
|
||||
<TableCell>{el.guestNumber}</TableCell>
|
||||
<TableCell>{el.price / 100} €</TableCell>
|
||||
<TableCell>
|
||||
<NumberSelector updateCount={(count) => onSelectedAmountUpdate(el.guestNumber, count, el.price)} addEnabled={canAddMore}></NumberSelector>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
});
|
||||
|
||||
priceTable = (
|
||||
<>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Guest number</TableHead>
|
||||
<TableHead>Price</TableHead>
|
||||
<TableHead>Amount</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{isLoadingPrices ? <Skeleton className="w-[80%] h-[100%]" /> : tableRows}
|
||||
</TableBody>
|
||||
</Table>
|
||||
<p>Rooms Available: {availableAmount}</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -48,33 +132,10 @@ function RoomBooking({ roomCategoryId, availableAmount }: { roomCategoryId: numb
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Guest number</TableHead>
|
||||
<TableHead>Price</TableHead>
|
||||
<TableHead>Amount</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableCell>1</TableCell>
|
||||
<TableCell>25€</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex flex-row">
|
||||
<Button
|
||||
onClick={() => setSelectedAmount(selectedAmount - 1)}>-</Button>
|
||||
<p className="mx-2">{selectedAmount}</p>
|
||||
<Button
|
||||
onClick={() => setSelectedAmount(selectedAmount + 1)}>+</Button>
|
||||
</div></TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
{hasPrices ? priceTable : <Typography variant={"largeText"}>No Prices available</Typography>}
|
||||
<div>
|
||||
<p>Available: {availableAmount}</p>
|
||||
<p>Selected: {selectedAmount}</p>
|
||||
</div>
|
||||
<p>Selected: {totalSelected()}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
@@ -5,20 +5,33 @@ import 'react-day-picker/dist/style.css';
|
||||
import { DatePickerWithRange } from "../ui/dateRange-picker";
|
||||
import { Button } from "../ui/button";
|
||||
import { SearchIcon } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { SearchFilter } from "@/model/SearchFilter";
|
||||
import { DateRange } from "react-day-picker";
|
||||
import { useToast } from "../ui/use-toast";
|
||||
import { useAppStore } from "@/store";
|
||||
import { useLocation } from "react-router-dom";
|
||||
|
||||
type funOnSearchClick = (newFilter: SearchFilter) => void;
|
||||
|
||||
export function SearchFilterCard({ onSearchClick }: { onSearchClick?: funOnSearchClick }) {
|
||||
|
||||
const { toast } = useToast();
|
||||
//App filter. Updated on btSearchClick.
|
||||
const appSearchFilter = useAppStore((state) => (state.searchFilter));
|
||||
const setAppSearchFilter = useAppStore((state) => (state.setSearchFilter));
|
||||
|
||||
const [searchFilter, setSearchFilter] = useState<SearchFilter>({
|
||||
dateRange: { from: new Date() }
|
||||
})
|
||||
//Local Filter state.
|
||||
const [searchFilter, setSearchFilter] = useState<SearchFilter>(appSearchFilter)
|
||||
|
||||
//On location change, try to load searchFilter from state.
|
||||
//FIXME: Si llegamos sin state, hay que borrar el state global...
|
||||
const location = useLocation();
|
||||
useEffect(() => {
|
||||
setSearchFilter(location.state);
|
||||
}, [location]);
|
||||
|
||||
|
||||
const { toast } = useToast();
|
||||
|
||||
// Validate and call callback on btSearch click.
|
||||
//TODOME: Add data validations and show messages.
|
||||
@@ -41,6 +54,7 @@ export function SearchFilterCard({ onSearchClick }: { onSearchClick?: funOnSearc
|
||||
}
|
||||
|
||||
if (onSearchClick) {
|
||||
setAppSearchFilter(searchFilter);
|
||||
onSearchClick(searchFilter);
|
||||
}
|
||||
}
|
||||
@@ -55,13 +69,27 @@ export function SearchFilterCard({ onSearchClick }: { onSearchClick?: funOnSearc
|
||||
console.log("SearchFilterCard filter UPDATED");
|
||||
}
|
||||
|
||||
const datePickerElement = searchFilter == null ? (
|
||||
<DatePickerWithRange
|
||||
updateDateRange={updateDateRange}
|
||||
allowPast={false}>
|
||||
</DatePickerWithRange>
|
||||
) : (
|
||||
<DatePickerWithRange
|
||||
updateDateRange={updateDateRange}
|
||||
allowPast={false}
|
||||
startDate={searchFilter.dateRange.from}
|
||||
endDate={searchFilter.dateRange.to}>
|
||||
</DatePickerWithRange>
|
||||
);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="p-0 m-0 mb-5">
|
||||
<Typography variant={"h2"} as="h1" className="mx-5 py-2">Reserva ahora</Typography>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<DatePickerWithRange updateDateRange={updateDateRange}></DatePickerWithRange>
|
||||
{datePickerElement}
|
||||
<Separator className="my-4" />
|
||||
<Button size={"lg"} onClick={btSearchClick}>
|
||||
<SearchIcon className="text-primary-foreground me-2" />
|
||||
|
||||
@@ -1,19 +1,26 @@
|
||||
import { BookmarkIcon } from "@radix-ui/react-icons"
|
||||
import { ModeToggle } from "./mode-toggle"
|
||||
import { Button } from "./ui/button"
|
||||
import { Card, CardContent } from "./ui/card"
|
||||
import { Typography } from "./ui/typography"
|
||||
import { Link } from "react-router-dom"
|
||||
import { BookAIcon, HomeIcon } from "lucide-react"
|
||||
|
||||
function AppHeader() {
|
||||
|
||||
return (
|
||||
<Card className="flex items-center mx-10 my-4">
|
||||
<CardContent className="w-full">
|
||||
<div className="flex justify-around">
|
||||
<Typography variant={"largeText"}>Hostal del Val</Typography>
|
||||
<Button variant="ghost">
|
||||
<BookmarkIcon/>
|
||||
<Typography variant={"largeText"}>Reservar</Typography>
|
||||
<CardContent className="w-full py-2">
|
||||
<div className="flex justify-around items-center">
|
||||
<div className="flex flex-row items-center gap-2 relative">
|
||||
<img src="public/SR2.svg" className="w-[64px]"></img>
|
||||
<Typography variant={"largeText"}>Somnia Rooms</Typography>
|
||||
<a href="https://duck.com" className="absolute w-[100%] h-[100%]"></a>
|
||||
</div>
|
||||
<Button variant="ghost" className="h-15">
|
||||
<Link to={`home`}><HomeIcon className="mx-auto" />Home</Link>
|
||||
</Button>
|
||||
<Button variant="ghost" className="h-15">
|
||||
<Link to={`search`}><BookAIcon className="mx-auto" />Reservar</Link>
|
||||
</Button>
|
||||
<ModeToggle />
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { useAppStore } from "@/store"
|
||||
import { Card, CardContent, CardHeader } from "../ui/card"
|
||||
import { Typography } from "../ui/typography"
|
||||
import { differenceInDays } from "date-fns";
|
||||
import { Separator } from "../ui/separator";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../ui/table";
|
||||
import { Button } from "../ui/button";
|
||||
|
||||
type OnBookingClickFunction = () => void;
|
||||
type BookingDetailsModes = "Book" | "View"
|
||||
|
||||
export function BookingDetails({ onBookingConfirm, mode }: { onBookingConfirm?: OnBookingClickFunction, mode: BookingDetailsModes }) {
|
||||
|
||||
const bookingData = useAppStore((state) => state.newBookingData);
|
||||
|
||||
const onBtBookingClick = () => {
|
||||
if (onBookingConfirm) {
|
||||
onBookingConfirm();
|
||||
}
|
||||
}
|
||||
|
||||
if (!bookingData || bookingData.rooms.length <= 0) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<Typography variant={"h2"} as="h2">Your Booking</Typography>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Typography variant={"h3"}>No rooms added yet</Typography>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
const roomList = bookingData.rooms.map((room) => {
|
||||
return (
|
||||
<TableRow key={room.roomCategory + "_" + room.guestNumber}>
|
||||
<TableCell>{room.roomCategory}</TableCell>
|
||||
<TableCell>{room.guestNumber}</TableCell>
|
||||
<TableCell>{room.amount}</TableCell>
|
||||
<TableCell>{room.price / 100} €</TableCell>
|
||||
<TableCell>{(room.price * room.amount) / 100} €</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})
|
||||
|
||||
|
||||
const roomTable = (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Room</TableHead>
|
||||
<TableHead>Guests</TableHead>
|
||||
<TableHead>Quantity</TableHead>
|
||||
<TableHead>Unit price</TableHead>
|
||||
<TableHead>Total price</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{roomList}
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
|
||||
|
||||
const totalPrice = bookingData.rooms.reduce((acc, room) => (acc + (room.price * room.amount)), 0);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<Typography variant={"h2"} as="h2">Your Booking</Typography>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Typography variant={"h3"}>Your Dates</Typography>
|
||||
<Typography variant={"largeText"}>
|
||||
Arrival: {bookingData.arrivalDate.toLocaleDateString()} -
|
||||
Departure: {bookingData.departureDate.toLocaleDateString()} <br></br>
|
||||
Number of nights: {differenceInDays(bookingData.departureDate, bookingData.arrivalDate)}
|
||||
</Typography>
|
||||
<Separator className="my-2"></Separator>
|
||||
<Typography variant={"h3"}>Your Rooms</Typography>
|
||||
{roomTable}
|
||||
<Separator className="my-2"></Separator>
|
||||
<Typography variant={"h3"}>Total Price</Typography>
|
||||
<Typography variant={"h3"}>{totalPrice / 100} €</Typography>
|
||||
{
|
||||
mode == "Book" &&
|
||||
<Button className="my-2" onClick={onBtBookingClick}>
|
||||
<Typography variant={"largeText"} className="text-primary-foreground">Book it!</Typography>
|
||||
</Button>
|
||||
}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
import * as React from "react"
|
||||
import { ChevronLeftIcon, ChevronRightIcon } from "@radix-ui/react-icons"
|
||||
import { DayPicker } from "react-day-picker"
|
||||
@@ -59,8 +58,8 @@ function Calendar({
|
||||
...classNames,
|
||||
}}
|
||||
components={{
|
||||
IconLeft: ({ ...props }) => <ChevronLeftIcon className="h-4 w-4" />,
|
||||
IconRight: ({ ...props }) => <ChevronRightIcon className="h-4 w-4" />,
|
||||
IconLeft: () => <ChevronLeftIcon className="h-4 w-4" />,
|
||||
IconRight: () => <ChevronRightIcon className="h-4 w-4" />,
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
|
||||
@@ -18,12 +18,15 @@ import { Typography } from "./typography"
|
||||
export type UpdateRangeFunction = (newRange: DateRange) => void;
|
||||
|
||||
export function DatePickerWithRange({
|
||||
className, updateDateRange
|
||||
}: { className?: React.HTMLAttributes<HTMLDivElement> | undefined, updateDateRange: UpdateRangeFunction | undefined }) {
|
||||
className, updateDateRange, startDate, endDate, allowPast = true
|
||||
}: {
|
||||
className?: React.HTMLAttributes<HTMLDivElement> | undefined, updateDateRange: UpdateRangeFunction | undefined,
|
||||
startDate?: Date, endDate?: Date, allowPast?: boolean
|
||||
}) {
|
||||
// Date Range State.
|
||||
const [dateRange, setDateRange] = React.useState<DateRange | undefined>({
|
||||
from: undefined,
|
||||
to: undefined,
|
||||
from: startDate,
|
||||
to: endDate,
|
||||
});
|
||||
|
||||
//TODOME: Si el día es mods.outside, navegar al mes correspondiente.
|
||||
@@ -61,6 +64,11 @@ export function DatePickerWithRange({
|
||||
beforeAndSelected = [beforeMatcher, dateMatcher];
|
||||
}
|
||||
|
||||
let pastMatcher: DateBefore | undefined = undefined;
|
||||
if (!allowPast) {
|
||||
pastMatcher = { before: new Date() };
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("grid gap-x-2 grid-cols-2 grid-rows-2", className)}>
|
||||
<Typography variant={"largeText"} as="p">Desde</Typography>
|
||||
@@ -91,6 +99,7 @@ export function DatePickerWithRange({
|
||||
selected={dateRange?.from}
|
||||
onDayClick={handleDayClickFrom}
|
||||
numberOfMonths={1}
|
||||
disabled={pastMatcher}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useState } from "react"
|
||||
import { Button } from "./button";
|
||||
import { Typography } from "./typography";
|
||||
|
||||
|
||||
export type UpdateSelectedNumberFunction = (newCount: number) => void;
|
||||
|
||||
export function NumberSelector(
|
||||
{ updateCount, addEnabled = true, allowNegative = false }:
|
||||
{ updateCount: UpdateSelectedNumberFunction, addEnabled?: boolean, allowNegative?: boolean }) {
|
||||
|
||||
const [count, setCount] = useState<number>(0);
|
||||
|
||||
const counterUpdated = (newAmount: number) => {
|
||||
setCount(newAmount);
|
||||
|
||||
if (updateCount != undefined) {
|
||||
updateCount(newAmount);
|
||||
}
|
||||
}
|
||||
|
||||
const minusDisabled = (!allowNegative && count <= 0)
|
||||
|
||||
return (
|
||||
<div className="flex flex-row items-center gap-2">
|
||||
<Button disabled={minusDisabled}
|
||||
onClick={() => counterUpdated(count - 1)}>-</Button>
|
||||
<Typography variant={"largeText"} className="mx-2">{count}</Typography>
|
||||
<Button disabled={!addEnabled}
|
||||
onClick={() => counterUpdated(count + 1)}>+</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import Root from './routes/Root';
|
||||
import ErrorPage from './error-page';
|
||||
import Homepage from './routes/home-page';
|
||||
import SearchPage from './routes/search-page';
|
||||
import BookPage from './routes/book-page';
|
||||
import SuccessPage from './routes/success-page';
|
||||
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
@@ -13,6 +15,10 @@ const router = createBrowserRouter([
|
||||
element: <Root />,
|
||||
errorElement: <ErrorPage />,
|
||||
children: [
|
||||
{
|
||||
path: "/",
|
||||
element: <Homepage />
|
||||
},
|
||||
{
|
||||
path: "/home",
|
||||
element: <Homepage />
|
||||
@@ -20,11 +26,21 @@ const router = createBrowserRouter([
|
||||
{
|
||||
path: "/search",
|
||||
element: <SearchPage />
|
||||
},
|
||||
{
|
||||
path: "/book",
|
||||
element: <BookPage />
|
||||
},
|
||||
{
|
||||
path: "/success",
|
||||
element: <SuccessPage />
|
||||
}
|
||||
]
|
||||
},
|
||||
]);
|
||||
|
||||
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<RouterProvider router={router} />
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
|
||||
export type NewBooking = {
|
||||
arrivalDate: Date,
|
||||
departureDate: Date,
|
||||
customerDetails: NewBookingCustomerDetails,
|
||||
rooms: NewBookingRoom[]
|
||||
};
|
||||
|
||||
export type NewBookingCustomerDetails = {
|
||||
name: string | null,
|
||||
surname: string | null,
|
||||
email: string | null,
|
||||
phoneNumber: string | null
|
||||
};
|
||||
|
||||
export type NewBookingRoom = {
|
||||
roomCategory: number,
|
||||
guestNumber: number,
|
||||
amount: number,
|
||||
price: number
|
||||
};
|
||||
|
||||
export type NewBookingResponse = {
|
||||
refNumber: number,
|
||||
}
|
||||
@@ -5,6 +5,11 @@ export type RoomAvailabity = {
|
||||
availability: number
|
||||
}
|
||||
|
||||
export type RoomPrice = {
|
||||
guestNumber: number,
|
||||
price: number
|
||||
}
|
||||
|
||||
export type AvailabilityRequest = {
|
||||
filter: AvailabilityFilter
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { APISendCreateBooking } from "@/api/api-booking"
|
||||
import { BookingDetails } from "@/components/booking/booking-details"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Label } from "@/components/ui/label"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { useToast } from "@/components/ui/use-toast"
|
||||
import { useAppStore } from "@/store"
|
||||
import { ChangeEvent, useState } from "react"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
|
||||
enum PageState {
|
||||
noData, showForm, sending, created, error
|
||||
}
|
||||
|
||||
|
||||
function BookPage() {
|
||||
const [pageState, setPageState] = useState<PageState>(PageState.showForm);
|
||||
const bookingData = useAppStore((state) => state.newBookingData)
|
||||
const setCustomerData = useAppStore((state) => state.setBookingCustomer);
|
||||
const { toast } = useToast();
|
||||
const navigate = useNavigate();
|
||||
|
||||
if (!bookingData || !bookingData.customerDetails) {
|
||||
return (
|
||||
<Typography variant={"h2"}>You must select some rooms...</Typography>
|
||||
)
|
||||
}
|
||||
|
||||
function handleOnChange(e: ChangeEvent<HTMLInputElement>) {
|
||||
if (bookingData == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const newCustomerData = bookingData.customerDetails;
|
||||
|
||||
switch (e.target.name) {
|
||||
case "name":
|
||||
newCustomerData.name = e.target.value;
|
||||
break;
|
||||
case "surname":
|
||||
newCustomerData.surname = e.target.value;
|
||||
break;
|
||||
case "email":
|
||||
newCustomerData.email = e.target.value;
|
||||
break;
|
||||
case "phoneNumber":
|
||||
newCustomerData.phoneNumber = e.target.value;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
setCustomerData(newCustomerData);
|
||||
}
|
||||
|
||||
function handleOnBookingSubmit() {
|
||||
const customerDetails = bookingData?.customerDetails;
|
||||
|
||||
if (!customerDetails ||
|
||||
customerDetails.name == "" || customerDetails.surname == "" || customerDetails.phoneNumber == "" || customerDetails.email == "") {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Uh oh! You must fill all fields.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setPageState(PageState.sending);
|
||||
console.log(bookingData);
|
||||
|
||||
sendCreateRequest();
|
||||
}
|
||||
|
||||
const sendCreateRequest = async () => {
|
||||
const rs = await APISendCreateBooking(bookingData);
|
||||
if (rs.isError) {
|
||||
setPageState(PageState.error);
|
||||
} else {
|
||||
navigate("/success", { state: rs.bookingResponse })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
<Typography variant={"h1"}>Booking Details</Typography>
|
||||
<Separator className="my-10" />
|
||||
<div>
|
||||
<Typography variant={"h3"}>Personal Details</Typography>
|
||||
<div>
|
||||
<div>
|
||||
<Label htmlFor="name">Name</Label>
|
||||
<Input type="text" name="name" id="name" placeholder="Name" value={bookingData.customerDetails.name ?? ""}
|
||||
onChange={handleOnChange} />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="surname">Surname</Label>
|
||||
<Input type="text" name="surname" id="surname" placeholder="Surname" value={bookingData.customerDetails.surname ?? ""}
|
||||
onChange={handleOnChange} />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="email">Email</Label>
|
||||
<Input type="email" name="email" id="email" placeholder="Email" value={bookingData.customerDetails.email ?? ""}
|
||||
onChange={handleOnChange} />
|
||||
</div>
|
||||
<div>
|
||||
<Label htmlFor="phone">Phone Number</Label>
|
||||
<Input type="tel" name="phoneNumber" id="phone" placeholder="Number" value={bookingData.customerDetails.phoneNumber ?? ""}
|
||||
onChange={handleOnChange} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Separator className="my-10" />
|
||||
<BookingDetails mode="View"></BookingDetails>
|
||||
<Separator className="my-10" />
|
||||
<Button onClick={handleOnBookingSubmit} disabled={pageState == PageState.sending}>
|
||||
<Typography variant={"h3"} className="text-primary-foreground">Book it now!</Typography>
|
||||
</Button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export default BookPage
|
||||
@@ -6,10 +6,17 @@ import { Separator } from "@/components/ui/separator"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { RoomCategory } from "@/model/RoomCategory"
|
||||
import { SearchFilter } from "@/model/SearchFilter"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
|
||||
function Homepage() {
|
||||
|
||||
const { roomCategoryList, isLoading, isError } = useAPIRoomCategories();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const onBtSearchClick = (filter: SearchFilter) => {
|
||||
navigate("/search", {state: filter})
|
||||
}
|
||||
|
||||
const roomList = roomCategoryList?.map((element: RoomCategory) => {
|
||||
return (
|
||||
@@ -19,9 +26,9 @@ function Homepage() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<Typography variant={"h1"}>Hostal del Val</Typography>
|
||||
<Typography variant={"h1"}>Somnia Rooms</Typography>
|
||||
<Separator className="my-10" />
|
||||
<SearchFilterCard />
|
||||
<SearchFilterCard onSearchClick={onBtSearchClick}/>
|
||||
<Separator className="my-10" />
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{roomList}
|
||||
|
||||
@@ -2,26 +2,55 @@ import { useAPIRoomAvailability } from "@/api/api-roomSearch"
|
||||
import RoomBooking from "@/components/Rooms/room-booking"
|
||||
import { SearchFilterCard } from "@/components/Search/SearchFilterCard"
|
||||
import BackendConnectionStatus from "@/components/backend-conection-status"
|
||||
import { BookingDetails } from "@/components/booking/booking-details"
|
||||
import { Separator } from "@/components/ui/separator"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { AvailabilityFilter } from "@/model/RoomSearch"
|
||||
import { SearchFilter } from "@/model/SearchFilter"
|
||||
import { useState } from "react"
|
||||
import { useAppStore } from "@/store"
|
||||
import { useMemo, useState } from "react"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
|
||||
//TODOME: Igual podemos crear un StateMachine conjunta para los siguiente estados de la página: Sin Buscar, Sin disponibilidad, error, cargando.
|
||||
function SearchPage() {
|
||||
|
||||
const [availabilityFilter, setAvailabilityFilter] = useState<AvailabilityFilter>();
|
||||
//const [availabilityFilter, setAvailabilityFilter] = useState<AvailabilityFilter>();
|
||||
const searchFilter = useAppStore((state) => (state.searchFilter));
|
||||
const resetBooking = useAppStore((state) => (state.resetBookingState));
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [isSearched, setIsSearched] = useState<boolean>(false);
|
||||
|
||||
const onBtSearchClick = (newFilter: SearchFilter) => {
|
||||
setAvailabilityFilter({
|
||||
startDate: newFilter.dateRange.from?.toDateString() ?? "",
|
||||
endDate: newFilter.dateRange.to?.toDateString() ?? ""
|
||||
});
|
||||
console.log("onBtSearchClick: ");
|
||||
console.log(newFilter);
|
||||
|
||||
if (newFilter.dateRange && newFilter.dateRange.from && newFilter.dateRange.to) {
|
||||
setIsSearched(true);
|
||||
|
||||
resetBooking(newFilter.dateRange.from, newFilter.dateRange.to);
|
||||
}
|
||||
}
|
||||
|
||||
const onBookingContinue = () => {
|
||||
navigate("/book");
|
||||
}
|
||||
|
||||
//This seems a little bit overkill, but IDK.
|
||||
const availabilityFilter: AvailabilityFilter | null = useMemo(
|
||||
() => {
|
||||
if (searchFilter && searchFilter.dateRange && searchFilter.dateRange.from && searchFilter.dateRange.to) {
|
||||
const newAvailabilityFilter: AvailabilityFilter = {
|
||||
startDate: searchFilter.dateRange.from.toDateString(),
|
||||
endDate: searchFilter.dateRange.to.toDateString()
|
||||
};
|
||||
return newAvailabilityFilter;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
[searchFilter]
|
||||
);
|
||||
|
||||
const { roomAvailabilityList, isLoading: isLoadingAvailability, isError: isErrorAvailability } = useAPIRoomAvailability(availabilityFilter ?? null);
|
||||
|
||||
@@ -56,7 +85,7 @@ function SearchPage() {
|
||||
{hasRooms ? roomList : (isSearched && noRoomsAvailable)}
|
||||
</div>
|
||||
<Separator className="my-10" />
|
||||
<RoomBooking key={99} availableAmount={5} roomCategoryId={6} />
|
||||
<BookingDetails onBookingConfirm={onBookingContinue} mode={"Book"}></BookingDetails>
|
||||
<Separator className="my-10" />
|
||||
<BackendConnectionStatus isLoading={isLoading} isError={isError} />
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Card, CardContent, CardHeader } from "@/components/ui/card"
|
||||
import { Typography } from "@/components/ui/typography"
|
||||
import { NewBookingResponse } from "@/model/Bookings"
|
||||
import { useAppStore } from "@/store"
|
||||
import { addDays } from "date-fns"
|
||||
import { useEffect, useState } from "react"
|
||||
import { useLocation, useNavigate } from "react-router-dom"
|
||||
|
||||
function SuccessPage() {
|
||||
|
||||
const [pageState, setPageState] = useState<NewBookingResponse|null>(null)
|
||||
const resetBookingState = useAppStore((state) => state.resetBookingState);
|
||||
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
if(location.state == null) {
|
||||
navigate("/home");
|
||||
}
|
||||
setPageState(location.state);
|
||||
|
||||
}, [location, navigate])
|
||||
|
||||
const handleBtBackClick = () => {
|
||||
resetBookingState(new Date(), addDays(new Date(), 2));
|
||||
navigate("/home");
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<Typography variant={"h2"}>Booking Completed</Typography>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Typography variant={"largeText"}>Booking ref: {pageState?.refNumber}</Typography>
|
||||
<Button className="my-4" onClick={handleBtBackClick}>
|
||||
<Typography variant={"largeText"} className="text-primary-foreground">Go Back</Typography>
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
export default SuccessPage
|
||||
@@ -0,0 +1,95 @@
|
||||
import { create } from 'zustand'
|
||||
import { SearchFilter } from './model/SearchFilter'
|
||||
import { NewBooking, NewBookingCustomerDetails, NewBookingRoom } from './model/Bookings'
|
||||
|
||||
interface AppState {
|
||||
searchFilter: SearchFilter
|
||||
setSearchFilter: (newFilter: SearchFilter) => void
|
||||
newBookingData: NewBooking | null
|
||||
setNewBooking: (newBooking: NewBooking) => void
|
||||
resetBookingState: (arrival: Date, departure: Date) => void
|
||||
addNewBookingRoom: (newRoom: NewBookingRoom) => void
|
||||
setBookingCustomer: (newCustomer: NewBookingCustomerDetails) => void
|
||||
}
|
||||
|
||||
const defaultSearchFilter: SearchFilter = {
|
||||
dateRange: { from: new Date() }
|
||||
}
|
||||
|
||||
const defaultNewBooking: NewBooking = {
|
||||
arrivalDate: new Date(),
|
||||
departureDate: new Date(),
|
||||
customerDetails: {
|
||||
name: null,
|
||||
surname: null,
|
||||
email: null,
|
||||
phoneNumber: null
|
||||
},
|
||||
rooms: []
|
||||
}
|
||||
|
||||
function getDefaultBookingData(arrivalDate: Date, departureDate: Date) {
|
||||
return {
|
||||
...defaultNewBooking,
|
||||
arrivalDate: arrivalDate,
|
||||
departureDate: departureDate
|
||||
}
|
||||
}
|
||||
|
||||
function addNewBookingRoomToCurrentState(newRoom: NewBookingRoom, currentState: NewBooking | null): NewBooking | null {
|
||||
|
||||
if (currentState == null) {
|
||||
return currentState;
|
||||
}
|
||||
|
||||
//Remove rooms with "same key".
|
||||
const filteredRooms = currentState.rooms.filter((room) => {
|
||||
const diffRoom = room.roomCategory != newRoom.roomCategory;
|
||||
const diffAmount = room.guestNumber != newRoom.guestNumber;
|
||||
if(diffRoom || (!diffRoom && diffAmount)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})
|
||||
console.log(filteredRooms);
|
||||
|
||||
if (newRoom.amount > 0) {
|
||||
filteredRooms.push(newRoom);
|
||||
}
|
||||
|
||||
|
||||
const newState: NewBooking = {
|
||||
...currentState,
|
||||
rooms: filteredRooms ?? []
|
||||
}
|
||||
|
||||
console.log("AddRoomNewState:");
|
||||
console.log(newState);
|
||||
|
||||
return newState;
|
||||
}
|
||||
|
||||
function setBookingCustomer(newCustomer: NewBookingCustomerDetails, currentState: NewBooking | null) {
|
||||
if(currentState == null) {
|
||||
return currentState;
|
||||
}
|
||||
|
||||
const newState: NewBooking = {
|
||||
...currentState,
|
||||
customerDetails: newCustomer
|
||||
};
|
||||
return newState;
|
||||
}
|
||||
|
||||
export const useAppStore = create<AppState>()((set) => ({
|
||||
searchFilter: defaultSearchFilter,
|
||||
setSearchFilter: (newFilter) => set(() => ({ searchFilter: newFilter })),
|
||||
newBookingData: null,
|
||||
setNewBooking: (newBooking) => set(() => ({ newBookingData: newBooking })),
|
||||
resetBookingState: (arrival, departure) =>
|
||||
set(() => ({ newBookingData: getDefaultBookingData(arrival, departure) })),
|
||||
addNewBookingRoom: (newRoom: NewBookingRoom) =>
|
||||
set((state) => ({ newBookingData: addNewBookingRoomToCurrentState(newRoom, state.newBookingData) })),
|
||||
setBookingCustomer: (newCustomer: NewBookingCustomerDetails) =>
|
||||
set((state) => ({newBookingData: setBookingCustomer(newCustomer, state.newBookingData)}))
|
||||
}))
|
||||
Reference in New Issue
Block a user