State Management & RoomPrices

- Added zustand for global state management.
- New Component - NumberSelector.
- Implement Prices API.
This commit is contained in:
2024-05-09 18:32:18 +02:00
parent d6a9ac8d7c
commit 630d5cb708
11 changed files with 2333 additions and 40 deletions
+37 -1
View File
@@ -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
View File
@@ -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
View File
File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 96 KiB

+16 -1
View File
@@ -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) {
@@ -15,4 +15,19 @@ export function useAPIRoomAvailability(filter: AvailabilityFilter | null) {
isLoading,
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
}
}
+71 -29
View File
@@ -1,21 +1,51 @@
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";
function RoomBooking({ roomCategoryId, availableAmount }: { roomCategoryId: number, availableAmount: number }) {
const [selectedAmount, setSelectedAmount] = useState<number>(0);
const currentDates: DateRange = useAppStore((state) => (state.searchFilter.dateRange));
function onSelectedAmountUpdate(guestNumber: number, newCount: number) {
console.log("Room " + roomCategoryId + " Guestnumber: " + guestNumber + " Count: " + newCount);
setSelectedAmount(newCount);
}
const canAddMore: boolean = availableAmount > selectedAmount;
//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 +64,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>
<TableCell>{el.guestNumber}</TableCell>
<TableCell>{el.price / 100} €</TableCell>
<TableCell>
<NumberSelector updateCount={(count) => onSelectedAmountUpdate(el.guestNumber, count)} 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 +113,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: {selectedAmount}</p>
</CardContent>
</Card>
);
@@ -9,6 +9,7 @@ import { useState } from "react";
import { SearchFilter } from "@/model/SearchFilter";
import { DateRange } from "react-day-picker";
import { useToast } from "../ui/use-toast";
import { useAppStore } from "@/store";
type funOnSearchClick = (newFilter: SearchFilter) => void;
@@ -16,10 +17,14 @@ export function SearchFilterCard({ onSearchClick }: { onSearchClick?: funOnSearc
const { toast } = useToast();
//Local Filter state.
const [searchFilter, setSearchFilter] = useState<SearchFilter>({
dateRange: { from: new Date() }
})
//App filter. Updated on btSearchClick.
const setAppSearchFilter = useAppStore((state) => (state.setSearchFilter));
// Validate and call callback on btSearch click.
//TODOME: Add data validations and show messages.
const btSearchClick = () => {
@@ -41,6 +46,7 @@ export function SearchFilterCard({ onSearchClick }: { onSearchClick?: funOnSearc
}
if (onSearchClick) {
setAppSearchFilter(searchFilter);
onSearchClick(searchFilter);
}
}
+5 -2
View File
@@ -10,9 +10,12 @@ function AppHeader() {
<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>
<div className="flex flex-row items-center gap-2">
<img src="public/SR2.svg" className="w-[64px]"></img>
<Typography variant={"largeText"}>Somnia Rooms</Typography>
</div>
<Button variant="ghost">
<BookmarkIcon/>
<BookmarkIcon />
<Typography variant={"largeText"}>Reservar</Typography>
</Button>
<ModeToggle />
+33
View File
@@ -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>
)
}
+5
View File
@@ -5,6 +5,11 @@ export type RoomAvailabity = {
availability: number
}
export type RoomPrice = {
guestNumber: number,
price: number
}
export type AvailabilityRequest = {
filter: AvailabilityFilter
}
+21 -6
View File
@@ -7,22 +7,37 @@ 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"
//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 [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);
setIsSearched(true);
}
//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);
const isLoading = isLoadingAvailability;
+16
View File
@@ -0,0 +1,16 @@
import { create } from 'zustand'
import { SearchFilter } from './model/SearchFilter'
interface AppState {
searchFilter: SearchFilter
setSearchFilter: (newFilter: SearchFilter) => void
}
const defaultSearchFilter: SearchFilter = {
dateRange: { from: new Date() }
}
export const useAppStore = create<AppState>()((set) => ({
searchFilter: defaultSearchFilter,
setSearchFilter: (newFilter) => set(() => ({ searchFilter: newFilter }))
}))