Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/develop' into orderCancel
Browse files Browse the repository at this point in the history
  • Loading branch information
timsu92 committed Aug 23, 2023
2 parents af82994 + fe9a5bb commit 5067424
Show file tree
Hide file tree
Showing 19 changed files with 338 additions and 74 deletions.
51 changes: 51 additions & 0 deletions backend/controller/reservation/orderToIn.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@

import { hasOrder, changeOrdertoIn, changeOrdertoWait } from '../../model/reserveModel.js';

function ReqIsNumber(s) {
return parseFloat(s).toString() !== "NaN";
}

export async function changeOrderStatus(req, res) {
try {
const { restaurantId, tableId, reservationId, phone } = req.body;
console.log(restaurantId)
console.log(tableId)
console.log(reservationId)
console.log(phone)

if (!restaurantId || !phone || !phone.startsWith('09') || !ReqIsNumber(restaurantId)) {
return res.status(400).json({ error: 'Wrong format in request body.' });
}
const phoneNum = parseInt(phone, 10);
const isOrdered = await hasOrder(restaurantId,phoneNum);

if (!isOrdered) {
return res.status(404).json({
error: 'Phone not found in orderList.',
});
}


if (tableId !== null) {
const orderstatusIn = await changeOrdertoIn(restaurantId, phoneNum, tableId)
console.log(orderstatusIn);
if(orderstatusIn === null ){
return res.status(404).json({ error: 'No data found' });
}
return res.status(200).json({ data: {orderId:orderstatusIn} })
}

if (reservationId !== null) {
const orderstatusWait = await changeOrdertoWait(restaurantId, phoneNum, reservationId)
console.log(orderstatusWait);
if(orderstatusWait === null ){
return res.status(404).json({ error: 'No data found' });
}
return res.status(200).json({ data: {orderId:orderstatusWait} })
}

} catch (error) {
console.error('Error in tableCancel:', error);
return res.status(500).json({ error: 'Internal server error' });
}
}
27 changes: 14 additions & 13 deletions backend/controller/reservation/reserve.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,59 +4,60 @@ import {insertReservation} from '../../model/reserveModel.js';
import {updateTableVacancy} from '../../model/reserveModel.js';
import {checkExistingReservation} from '../../model/reserveModel.js';
import {getWaitCount} from '../../model/reserveModel.js';

import {hasOrder} from '../../model/reserveModel.js';


export async function reservationReserve(req, res) {
try {
const { restaurantId, headcount, name, gender, phone } = req.body;

// Check if request body is missing
if (!restaurantId || !headcount || !name || !gender || !phone||!phone.startsWith('09')) {
return res.status(400).json({ error: 'Missing request body fields.' });
}

const phoneNum = parseInt(phone, 10);


const isTable = await checkExistingTable(phoneNum);
const isTable = await checkExistingTable(restaurantId, phoneNum);
if (isTable) {
console.log("you alreayd have a seat, you can't reserve again!");
return res.status(400).json({ error: 'You already have an existing seat.' });
return res.status(400).json({ error: 'You already have an existing seat in this restaurant.' });
}
console.log("you don't have a seat!, I will check if you have a reservation");
const isReserve = await checkExistingReservation(phoneNum);
const isReserve = await checkExistingReservation(restaurantId,phoneNum);
if (isReserve) {
console.log("you already have a reservation in this restaurant");
return res.status(400).json({ error: 'You already have an reservation.' });
return res.status(400).json({ error: 'You already have an reservation in this restaurant.' });
}
console.log("you don't have a reservation in this restaurant");


const isVacancy = await hasVacancy(restaurantId, headcount);
console.log(`isVancy is ${isVacancy}`);
console.log(`!isVancy is ${!isVacancy}`);
if (isVacancy) {
console.log("there is vancancy")
const updateTableId = await updateTableVacancy(phoneNum,headcount);
console.log("Good, you already have a seat");

console.log("Good, you already have a seat in this restaurant");

const isOrdered = await hasOrder(restaurantId,phoneNum);

return res.status(200).json({data:{
"tableId": updateTableId,
"reservationId":null,
"reservationCount": null,
"order" : isOrdered
}});

}
console.log("there is no vancancy")
const isOrdered = await hasOrder(restaurantId,phoneNum);


const inserReservationId = await insertReservation(phone, headcount, restaurantId);
const reserveCount = await getWaitCount(restaurantId);
console.log(`Sorry, you need to wait a while...${reserveCount}`);
console.log(`Sorry, you need to wait a while...for${reserveCount}`);
return res.status(200).json({data:{
"tableId": null,
"reservationId": inserReservationId,
"reservationCount": reserveCount,
"order" : isOrdered
}});

} catch (error) {
Expand Down
8 changes: 8 additions & 0 deletions backend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { restaurantList } from './controller/restaurant/list.js';
import { restaurantProfile } from './controller/restaurant/profile.js';
import { reservationReserve } from './controller/reservation/reserve.js';
import { reservationPending } from './controller/reservation/pending.js';
import { changeOrderStatus } from './controller/reservation/orderToIn.js';
import { reservationCancel } from './controller/reservation/reserveCancel.js';
import { restaurantVacancy } from './controller/restaurant/vacancy.js';
import { menuSearch } from './controller/menu/search.js';
Expand All @@ -24,6 +25,9 @@ import { orderCancel } from './controller/order/cancel.js';






/*************************
* global config
*************************/
Expand Down Expand Up @@ -81,6 +85,10 @@ app.post(`/api/${process.env.apiVer}/orders/request`, orderRequest);
app.get(`/api/${process.env.apiVer}/orders/pending`, orderPending);
app.get(`/api/${process.env.apiVer}/orders/detail`, orderDetail);
app.get(`/api/${process.env.apiVer}/orders/order`, OrderSummary);
app.post(`/api/${process.env.apiVer}/reservations/orderstatus`, changeOrderStatus);






Expand Down
95 changes: 91 additions & 4 deletions backend/model/reserveModel.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { pool } from './util.js';


export async function checkExistingTable(phone) {
export async function checkExistingTable(restaurantId,phone) {
try {
const [rows] = await pool.query('SELECT * FROM tableList WHERE phone = ?', [phone]);
const [rows] = await pool.query('SELECT * FROM tableList WHERE restaurantId=? AND phone = ?', [restaurantId,phone]);
console.log('Query result:', rows);
return rows.length > 0;
} catch (error) {
Expand All @@ -12,9 +12,9 @@ export async function checkExistingTable(phone) {
}
}

export async function checkExistingReservation(phone) {
export async function checkExistingReservation(restaurantId,phone) {
try {
const [rows] = await pool.query('SELECT * FROM Reservation WHERE phone = ?', [phone]);
const [rows] = await pool.query('SELECT * FROM Reservation WHERE restaurantId=? AND phone = ?', [restaurantId,phone]);
console.log('checkExistingReservation result:', rows);
return rows.length > 0;
} catch (error) {
Expand Down Expand Up @@ -78,3 +78,90 @@ export async function getWaitCount(restaurantId) {
throw error;
}
}


export async function hasOrder(restaurantId,phoneNum) {
try {
const [res] = await pool.query(
'SELECT id FROM OrderList WHERE restaurantId = ? AND phone = ? AND reservationId IS NULL AND tableId IS NULL',
[restaurantId, phoneNum]
);
console.log(`result of return ${res.length}`);
return res.length > 0;
} catch (error) {
console.error('Error in checkhasOrder:', error);
throw error;
}
}

export async function changeOrdertoIn(restaurantId, phoneNum, tableId) {
const connection = await pool.getConnection();

try {
await connection.beginTransaction();

const [orderRows] = await connection.query(
'SELECT id FROM OrderList WHERE restaurantId = ? AND phone = ? AND reservationId IS NULL AND tableId IS NULL',
[restaurantId, phoneNum]
);

if (orderRows.length > 0) {
const orderId = orderRows[0].id;

await connection.query(
'UPDATE OrderList SET tableId = ? WHERE id = ?',
[tableId, orderId]
);
await connection.commit();
return orderId;
}
await connection.commit();
return null;

} catch (error) {
await connection.rollback();
console.error('Error in changeOrdertoIn:', error);
throw error;
} finally {
connection.release();
}
}



export async function changeOrdertoWait(restaurantId, phoneNum, reservationId) {
const connection = await pool.getConnection();

try {
await connection.beginTransaction();

const [orderRows] = await connection.query(
'SELECT id FROM OrderList WHERE restaurantId = ? AND phone = ? AND reservationId IS NULL AND tableId IS NULL',

[restaurantId, phoneNum]
);

if (orderRows.length > 0) {
const orderId = orderRows[0].id;

await connection.query(
'UPDATE OrderList SET reservationId = ? WHERE id = ?',
[reservationId, orderId]
);
await connection.commit();
return orderId;
}

await connection.commit();
return null;

} catch (error) {
await connection.rollback();
console.error('Error in changeOrdertoWait:', error);
throw error;
} finally {
connection.release();
}
}


7 changes: 5 additions & 2 deletions frontend/src/components/Alert/Alert.module.scss
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
justify-content: center;
align-items: center;
gap: 10px;
padding: 10px 0;
}
.overlay {
position: absolute;
Expand All @@ -29,15 +30,17 @@
}
.title {
color: #000;
font-family: Inter;
font-size: 18px;
font-style: normal;
font-weight: 700;
line-height: normal;
width: 80%;
display: flex;
align-items: center;
justify-content: center;
}
.context {
color: var(--unnamed, #959595);
font-family: Inter;
font-size: 16px;
font-style: normal;
font-weight: 400;
Expand Down
43 changes: 39 additions & 4 deletions frontend/src/hook/useCancel.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Cookies from 'js-cookie'

const useCancel = ({ phone, restaurantId }) => {
const useCancel = ({ phone, restaurantId, orderId }) => {
// const restaurantId = parseInt(Cookies.get('restaurantsId'))
// const phone = Cookies.get('phone')

Expand Down Expand Up @@ -31,7 +31,7 @@ const useCancel = ({ phone, restaurantId }) => {
Cookies.remove('tableId')
setTimeout(() => {
window.location.reload()
}, 100)
}, 50)
}
if (!response.ok) {
throw new Error('Network response was not ok')
Expand Down Expand Up @@ -67,15 +67,50 @@ const useCancel = ({ phone, restaurantId }) => {
Cookies.remove('tableId')
setTimeout(() => {
window.location.reload()
}, 100)
}, 50)
}
console.log('取消訂位 response: ', response.json())
} catch (error) {
console.error('Error fetching data:', error)
}
}

return { cancleReservation, cancleBooking }
async function cancleToGo() {
//外帶
try {
const response = await fetch(
`https://107.22.142.48/api/1.0/orders/${orderId}/cancel`,
{
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
phone: phone
})
}
)
if (!response.ok) {
throw new Error('Network response was not ok')
}
if (response.ok) {
// Cookies.remove('reservationId')
// Cookies.remove('isReserved')
// Cookies.remove('isEatHere')
// Cookies.remove('userGender')
// Cookies.remove('userName')
// Cookies.remove('phone')
// Cookies.remove('tableId')
setTimeout(() => {
window.location.reload()
}, 50)
}
console.log('取消外帶 response: ', response.json())
} catch (error) {
console.error('Error fetching data:', error)
}
}
return { cancleReservation, cancleBooking, cancleToGo }
}

export default useCancel
Loading

0 comments on commit 5067424

Please sign in to comment.