Changeset cfc16a3


Ignore:
Timestamp:
03/03/24 10:52:49 (15 months ago)
Author:
Aleksandar Panovski <apano77@…>
Branches:
main
Children:
c63036a
Parents:
75f5086
Message:

RetaurantServiceImpl problemi
isAvailable od tableEntity...

Files:
3 added
10 edited

Legend:

Unmodified
Added
Removed
  • my-react-app/src/App.js

    r75f5086 rcfc16a3  
    22import Customers from './components/Customers';
    33import Layout from "./components/Layout";
    4 import React, {useEffect, useState} from 'react';
     4import React, {useContext, useEffect, useState} from 'react';
    55import CustomerFormContainer from "./components/CustomerFormContainer";
    66import CustomerDetails from "./components/CustomerDetails";
     
    1212import ReservationEdit from "./components/ReservationEdit";
    1313import axios from "axios";
     14import { CuisineContext } from './components/CuisineContext';
    1415
    1516const App = () => {
     
    4546    const [timeSlots, setTimeSlots] = useState([]);
    4647
     48    const cuisineTypes = useContext(CuisineContext);
     49
    4750    useEffect(() => {
    4851        if (date) {
     
    8285    }, [date]);
    8386
    84 
    8587    const handleDateChange = (e) => {
    8688        setDate(e.target.value);
     
    102104        e.preventDefault();
    103105        const [year, month, day] = date.split("-");
    104 
    105106        let formattedDateTime;
    106         const [selectedHours, selectedMinutes] = selectedTime.split(":");
    107         // Check if selectedHours and selectedMinutes are valid numbers
    108         if (!isNaN(selectedHours) && !isNaN(selectedMinutes)) {
    109             const dateTime = new Date(Date.UTC(year, month - 1, day, selectedHours, selectedMinutes));
    110             formattedDateTime = dateTime.toISOString().slice(0, 16).replace('T', ' ');
     107
     108        if (selectedTime) {
     109            const [selectedHours, selectedMinutes] = selectedTime.split(":");
     110            // Check if selectedHours and selectedMinutes are valid numbers
     111            if (!isNaN(selectedHours) && !isNaN(selectedMinutes)) {
     112                const dateTime = new Date(Date.UTC(year, month - 1, day, selectedHours, selectedMinutes));
     113                formattedDateTime = dateTime.toISOString().slice(0, 16).replace('T', ' ');
     114            }
    111115        } else {
    112             // Default values if selectedTime is not valid
     116            // Find the first available time slot after the current time
    113117            const now = new Date();
    114             let defaultTime;
    115             if (now.getHours() >= 9 && now.getHours() <= 23) {
    116                 defaultTime = now;
    117             } else {
    118                 defaultTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 9, 0); // Set to 09:00 if current time is before 09:00
    119             }
    120             const dateTime = new Date(Date.UTC(year, month - 1, day, defaultTime.getHours(), defaultTime.getMinutes()));
    121             formattedDateTime = dateTime.toISOString().slice(0, 16).replace('T', ' ');
     118            const currentTime = now.getHours() * 60 + now.getMinutes(); // Current time in minutes
     119            const nextSlot = timeSlots.find(slot => {
     120                const [hours, minutes] = slot.split(":");
     121                const slotTime = parseInt(hours) * 60 + parseInt(minutes); // Time of the slot in minutes
     122                return slotTime > currentTime;
     123            });
     124
     125            // If no slot is found after the current time, use the first slot of the day
     126            formattedDateTime = nextSlot ? `${date} ${nextSlot}` : `${date} ${timeSlots[0]}`;
    122127        }
    123128
     
    128133        };
    129134
    130         console.log("pecatam data pod mene")
    131         console.log(data)
     135        console.log("Data to be submitted:");
     136        console.log(data);
    132137
    133138        try {
     
    141146    };
    142147
     148    const handleSearchByCuisine = async (cuisine) => {
     149        const cuisineName = cuisine.replace('Searching by cuisine: ', '');
     150        try {
     151            const response = await axios.post(`http://localhost:8080/api/search/shortcut/${cuisineName}`, cuisineName);
     152            // Handle the response as needed
     153            console.log(response.data); // Log the response data, for example
     154        } catch (error) {
     155            console.error('Error searching by cuisine:', error);
     156            // Handle errors, such as displaying an error message to the user
     157        }
     158    };
    143159
    144160
     
    154170    return (
    155171        <div className="container">
    156             <h2>Home</h2>
    157             <p>Welcome to My Awesome App!</p>
     172            <h2 className="display-1">Rezerviraj masa</h2>
    158173            <form className="row g-2 align-items-center" onSubmit={handleSubmit}>
    159174                <div className="col-auto">
     
    189204                    <button className="btn btn-outline-success" type="submit">Search</button>
    190205                </div>
     206                <form>
     207                    <div className="mb-3">
     208                        <h2 className="display-2">Search by cuisine type</h2>
     209                        <ul className="list-group">
     210                            {cuisineTypes.map((cuisine, index) => (
     211                                <li key={index} className="list-group-item">
     212                                    <button type="button" className="btn btn-outline-primary"
     213                                            onClick={() => handleSearchByCuisine(cuisine)}>
     214                                        {cuisine}
     215                                    </button>
     216                                </li>
     217                            ))}
     218                        </ul>
     219                    </div>
     220                </form>
     221
     222
    191223            </form>
    192224        </div>
  • my-react-app/src/components/Customers.js

    r75f5086 rcfc16a3  
    3535            await axios.delete(`http://localhost:8080/api/customers/delete/${customerId}`);
    3636            setCustomers(customers.filter(customer => customer.customerID !== customerId));
    37             alert('Reservation canceled successfully');
     37            window.location.reload();
    3838        } catch (error) {
    3939            console.error("Error + " + error);
    40             alert("An error occurred while deleting");
    4140        }
    4241    }
  • my-react-app/src/components/Restaurants.js

    r75f5086 rcfc16a3  
    1 import React, { useState, useEffect } from 'react';
    2 import axios from 'axios';
     1import React, {useState, useEffect, useContext} from 'react';
    32import 'bootstrap/dist/css/bootstrap.min.css';
    43import StarRating from './StarRating';
    54import { useNavigate } from 'react-router-dom';
     5import {RestaurantContext} from "./RestaurantContext";
    66
    77const Restaurants = () => {
    88    const [restaurants, setRestaurants] = useState([]);
    99    const navigate = useNavigate();
     10    const restaurantContext = useContext(RestaurantContext);
    1011
    1112    useEffect(() => {
    12         const fetchRestaurants = async () => {
    13             try {
    14                 const response = await axios.get('http://localhost:8080/api/restaurants');
    15                 setRestaurants(response.data);
    16             } catch (error) {
    17                 console.error('Error fetching restaurants:', error);
    18             }
    19         };
    20 
    21         fetchRestaurants();
    22     }, []);
     13        setRestaurants(restaurantContext.restaurants);
     14    }, [restaurantContext]);
    2315
    2416    const handleDetailClick = (restaurantId) => {
     
    9890                                </div>
    9991                            </div>
    100                             <button onClick={() => handleDetailClick(restaurant.restaurantId)} className="btn btn-primary">View Details</button>
     92                            <button onClick={() => handleDetailClick(restaurant.restaurantId)}
     93                                    className="btn btn-primary">View Details
     94                            </button>
    10195                        </div>
    10296                    </div>
  • my-react-app/src/index.js

    r75f5086 rcfc16a3  
    33import './index.css';
    44import App from './App';
     5import { CuisineProvider } from './components/CuisineContext';
     6import {RestaurantProvider} from "./components/RestaurantContext";
    57
    68const root = ReactDOM.createRoot(document.getElementById('root'));
    79root.render(
    8   <React.StrictMode>
    9     <App />
    10   </React.StrictMode>
     10    <React.StrictMode>
     11        <CuisineProvider>
     12            <RestaurantProvider>
     13                <App />
     14            </RestaurantProvider>
     15        </CuisineProvider>
     16    </React.StrictMode>
    1117);
  • src/main/java/com/example/rezevirajmasa/demo/model/Reservation.java

    r75f5086 rcfc16a3  
    4848//    private BigDecimal totalAmount;//rezervacija so depozit ako e
    4949
    50     @Column(name = "Pa`ymentStatus", length = 20, nullable = false, columnDefinition = "VARCHAR default 'Unpaid'")
     50    @Column(name = "PaymentStatus", length = 20, nullable = false, columnDefinition = "VARCHAR default 'Unpaid'")
    5151    private String paymentStatus;
    5252
  • src/main/java/com/example/rezevirajmasa/demo/repository/RestaurantRepository.java

    r75f5086 rcfc16a3  
    44import com.example.rezevirajmasa.demo.model.TableEntity;
    55import org.springframework.data.jpa.repository.JpaRepository;
     6import org.springframework.data.jpa.repository.Query;
    67
    78import java.util.List;
     
    910public interface RestaurantRepository extends JpaRepository<Restaurant, Long> {
    1011    List<Restaurant> findAllByNameLike(String search);
    11     List<Restaurant> findAllByCuisineTypeLike(String search);
     12    List<Restaurant> findAllByCuisineTypeContaining(String search);
     13    @Query("SELECT DISTINCT r.cuisineType FROM Restaurant r")
     14    List<String> findAllCuisineTypes();
     15    List<Restaurant> findAllByCuisineType(String cuisine);
    1216}
  • src/main/java/com/example/rezevirajmasa/demo/repository/TableRepository.java

    r75f5086 rcfc16a3  
    1414//    @Query("SELECT t FROM TableEntity t JOIN FETCH t.restaurant WHERE t.id = :id")
    1515//    TableEntity findTableEntityByIdWithRestaurant(@Param("id") Long id);
    16     List<TableEntity> findAllByTimeSlotsContainingAndCapacity(LocalDateTime timeSlot, Integer partySize);
     16    List<TableEntity> findAllByTimeSlotsContainingAndCapacityGreaterThanEqual(LocalDateTime timeSlot, Integer partySize);
    1717}
  • src/main/java/com/example/rezevirajmasa/demo/service/RestaurantService.java

    r75f5086 rcfc16a3  
    2222    public List<Restaurant> findRestaurantsByDateTimeAndPartySize(LocalDateTime dateTime, int partySize, String search);
    2323    public List<Restaurant> findRestaurantsBySearchParams(LocalDateTime dateTime, int partySize, String search);
     24    public List<String> findALlCuisineTypes();
     25    List<Restaurant> findRestaurantsByCuisineType(String param);
    2426}
  • src/main/java/com/example/rezevirajmasa/demo/service/impl/RestaurantServiceImpl.java

    r75f5086 rcfc16a3  
    168168    @Override
    169169    public List<Restaurant> findRestaurantsBySearchParams(LocalDateTime dateTime, int partySize, String search) {
    170         if (!search.isEmpty()) {
    171             List<Restaurant> restaurantList = null;
    172             if (!restaurantRepository.findAllByNameLike(search).isEmpty()) {
    173                 restaurantList = restaurantRepository.findAllByNameLike(search);
    174             } else {
    175                 restaurantList = restaurantRepository.findAllByCuisineTypeLike(search);
     170        if (search == null || search.isEmpty()) {
     171            List<TableEntity> tableEntities = tableRepository.findAllByTimeSlotsContainingAndCapacityGreaterThanEqual(dateTime, partySize);
     172            return tableEntities.stream()
     173                    .map(TableEntity::getRestaurant)
     174                    .distinct()
     175                    .collect(Collectors.toList());
     176        } else {
     177            List<Restaurant> restaurantList = restaurantRepository.findAllByNameLike(search);
     178            if (restaurantList.isEmpty()) {
     179                restaurantList = restaurantRepository.findAllByCuisineTypeContaining(search);
    176180            }
    177181            return restaurantList;
    178         } else {
    179             List<TableEntity> tableEntities = tableRepository.findAllByTimeSlotsContainingAndCapacity(dateTime, partySize);
    180             return tableEntities.stream()
    181                     .map(TableEntity::getRestaurant)
    182                     .distinct()  // To avoid duplicates in case one restaurant has multiple tables
    183                     .collect(Collectors.toList());
    184182        }
    185183    }
     184
     185    @Override
     186    public List<String> findALlCuisineTypes() {
     187        return restaurantRepository.findAllCuisineTypes();
     188    }
     189
     190    @Override
     191    public List<Restaurant> findRestaurantsByCuisineType(String param) {
     192        return restaurantRepository.findAllByCuisineType(param);
     193    }
    186194}
  • src/main/java/com/example/rezevirajmasa/demo/web/rest/testController.java

    r75f5086 rcfc16a3  
    1717import java.util.List;
    1818import java.util.Map;
     19import java.util.Optional;
    1920
    2021@CrossOrigin(origins = "http://localhost:3000/")
     
    5253    @PostMapping("/api/search")
    5354    public ResponseEntity<List<Restaurant>> searchRestaurants(@RequestBody Map<String, Object> requestData) {
    54         String dateTime = (String) requestData.get("dateTime");
    55         Integer partySize = (Integer) requestData.get("partySize");
    56         String search = (String) requestData.get("search");
     55        Optional<String> dateTimeOptional = Optional.ofNullable((String) requestData.get("dateTime"));
     56        int partySize = Integer.parseInt(requestData.get("partySize").toString());
     57        Optional<String> searchOptional = Optional.ofNullable((String) requestData.get("search"));
    5758
    58         // Now proceed with parsing dateTime and performing the search based on the received parameters
     59        String dateTime = dateTimeOptional.orElse(null);
     60        String search = searchOptional.orElse(null);
    5961
    6062        LocalDateTime parsedDateTime = null;
     
    6769
    6870        return new ResponseEntity<List<Restaurant>>(filteredRestaurants, HttpStatus.OK);
     71    }
     72
     73    @PostMapping("/api/search/shortcut/{param}")
     74    public ResponseEntity<List<Restaurant>> searchByCuisineTypeShortcut(@PathVariable String param) {
     75        List<Restaurant> filteredRestaurants;
     76        if(param != null && !param.isEmpty()) {
     77            filteredRestaurants = restaurantService.findRestaurantsByCuisineType(param);
     78        } else {
     79            filteredRestaurants = restaurantService.listall();
     80        }
     81        return new ResponseEntity<List<Restaurant>>(filteredRestaurants, HttpStatus.OK);
     82    }
     83
     84    @GetMapping("/api/cuisineTypes")
     85    public ResponseEntity<List<String>> getAllCuisineTypes() {
     86        List<String> cuisineTypes = restaurantService.findALlCuisineTypes();
     87        return new ResponseEntity<>(cuisineTypes, HttpStatus.OK);
    6988    }
    7089
Note: See TracChangeset for help on using the changeset viewer.