Skip to content

Commit

Permalink
Base code to force sign in dish (#287)
Browse files Browse the repository at this point in the history
  • Loading branch information
kwiskel authored Oct 10, 2024
1 parent 8148168 commit 024d250
Show file tree
Hide file tree
Showing 6 changed files with 205 additions and 69 deletions.
41 changes: 40 additions & 1 deletion app/src/admin/adminApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,20 @@ const adminApi = {
const transactions = response?.data.transactions
return transactions
},
getDishByQid: async function (token: string, qid: string) {
const response = await axios
.get(`${this.serverAddress}/api/dish?qid=${qid}}`, {
headers: headers(token),
})
.then((res) => {
return res
})
.catch((err) => {
console.error(`Failed to get dish using qid from database. ${err}.`)
})
const dish = response?.data.dish
return dish
},
getAllDishes: async function (token: string, withEmail?: boolean) {
const response = await axios
.get(`${this.serverAddress}/api/dish?all=true&transaction=true&withEmail=${withEmail?.toString()}`, {
Expand All @@ -48,7 +62,7 @@ const adminApi = {
return res
})
.catch((err) => {
console.log(`Failed to get dishes from database. ${err}.`)
console.error(`Failed to get dishes from database. ${err}.`)
})
const dishes = response?.data.dishes
return dishes
Expand Down Expand Up @@ -149,6 +163,31 @@ const adminApi = {
})
return response
},
returnDish: async function (token: string, qid: string) {
const response = await axios
.post(
`/api/dish/return`,
{
returned: {
condition: 'good',
},
// qid: qid,
},
{
headers: headers(token),
params: { qid: qid },
},
)
.then((res) => {
return res
})
.catch((err) => {
// eslint-disable-next-line no-console
console.error(`Failed to return dish. ${err}.`)
return err
})
return response
},

// deleteDishes: async function (token: string, dishIds: Array<string>) {
deleteDishes: async function (token: string, dishIds: GridRowId[]) {
Expand Down
7 changes: 4 additions & 3 deletions app/src/routes/borrow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,9 @@ const Borrow = () => {
<div>Successfully borrowed</div>
<div>Dish # {id} </div>
<div> </div>
<div>Please return your dish within two days to the nearest DishZero Return Station</div>

<div>
Please return your dish within two days to the nearest DishZero Return Station
</div>
</div>
</>
) : (
Expand Down Expand Up @@ -156,7 +157,7 @@ const Borrow = () => {
justifyContent: 'center',
backgroundColor: '#464646',
}}>
<AppHeader title={'Borrow Dishes'} className={'headerDiv'} />
<AppHeader title={'Borrow Dishes'} />

<div className="qr-body-wrapper">
<div className="b-text-wrapper">
Expand Down
187 changes: 142 additions & 45 deletions app/src/routes/return.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
RadioGroup,
Radio,
IconButton,
DialogContent,
} from '@mui/material'
import { useAuth } from '../contexts/AuthContext'
import { BallTriangle } from 'react-loader-spinner'
Expand All @@ -35,6 +36,12 @@ import ReportIcon from '../assets/megaphone.svg'
import ErrorIcon from '../assets/error_icon.svg'
import CloseIcon from '../assets/X_icon.svg'
import axios from 'axios'
import adminApi from '../admin/adminApi'
import { Dish, DishStatus } from '../admin/Dishes/constants'
import { Close } from '@mui/icons-material'
import CustomDialogTitle from '../admin/CustomDialogTitle'
import { theme } from 'antd'
import { useSnackbar } from 'notistack'

const PopUpModal = memo(({ dishType, error, message, reportToggle, qid, isMobile }) => {
let avatarIcon
Expand Down Expand Up @@ -123,6 +130,11 @@ const Return = ({ noTimer }) => {
const navigate = useNavigate()
const location = useLocation()

const [forceSignInDialog, setForceSignInDialog] = useState(false)
const [forceLoading, setForceLoading] = useState(false)

const { enqueueSnackbar } = useSnackbar()

/*const onScan = async (id: string) => {
setScanId(id);
let val = await DishAPI.updateDishReturn(id);
Expand Down Expand Up @@ -263,60 +275,124 @@ const Return = ({ noTimer }) => {
setQid(condition)
setIsLoading(true)

await axios
.get(`/api/dish`, {
headers: {
'x-api-key': `${process.env.REACT_APP_API_KEY}`,
'session-token': sessionToken,
},
baseURL: `${process.env.REACT_APP_BACKEND_ADDRESS}`,
params: { qid: condition },
})
.then(function (response) {
console.log(response)
setDishType(response.data.dish.type)
setDishID(response.data.dish.id)
})
.catch(function (error) {
console.log(error)
})
const dishData = (await adminApi.getDishByQid(sessionToken, condition)) as Dish
setDishID(dishData.id)
setDishType(dishData.type)

console.log(dishData)
// check if dish is borrowed
if (dishData.status == DishStatus.borrowed) {
// return the dish
await axios
.post(
`/api/dish/return`,
{
returned: {
condition: 'good',
},
},
{
headers: {
'x-api-key': `${process.env.REACT_APP_API_KEY}`,
'session-token': sessionToken,
'Content-Type': 'application/json',
},
params: { qid: condition },
baseURL: `${process.env.REACT_APP_BACKEND_ADDRESS}`,
},
)
.then(function (response) {
setError('')
setIsLoading(false)
setMessage('')
setPopUp(true)
})
.catch(function (error) {
// handle error
console.log(error.response.data.message)
setError(error.response.data.message)
setIsLoading(false)
setMessage('')
setPopUp(true)
})
} else {
// create a popup asking if they want to force sign out and sign in
setForceSignInDialog(true)
}

// get the dish
//let icon = eval(dishType + "Icon") Trying to create a dynamic variable which does work but does not properly reference the imported image variable.
//How are we gonna handle other dish types?
//setDishIcon(icon);

await axios
// Check if dish is signed out
}

const forceSignIn = async () => {
// sign out the dish
setForceLoading(true)
const response = (await axios
.post(
`/api/dish/return`,
{
returned: {
condition: 'good',
},
},
`${process.env.REACT_APP_BACKEND_ADDRESS}/api/dish/borrow`,
{},
{
headers: {
'x-api-key': `${process.env.REACT_APP_API_KEY}`,
'session-token': sessionToken,
'Content-Type': 'application/json',
},
params: { qid: condition },
baseURL: `${process.env.REACT_APP_BACKEND_ADDRESS}`,
headers: { 'x-api-key': `${process.env.REACT_APP_API_KEY}`, 'session-token': sessionToken },
params: { qid: qid, email: '[email protected]' },
},
)
.then(function (response) {
setError('')
setIsLoading(false)
setMessage('')
setPopUp(true)
})
.catch(function (error) {
// handle error
console.log(error.response.data.message)
setError(error.response.data.message)
setIsLoading(false)
setMessage('')
setPopUp(true)
.then((res) => {
console.log('res', res)
return res
})
.catch((err) => {
// eslint-disable-next-line no-console
console.error(`Failed to borrow dish ${err}.`)
return err
})) as any
console.log('response', response)

if (response && response.status != 200) {
enqueueSnackbar(`Failed to sign out the dish please try again: ${response.message}`, { variant: 'error' })
setForceLoading(false)
} else {
console.log('returning the dish')
// return the dish
// const response = (await adminApi.returnDish(sessionToken, qid)) as any
const response = (await axios
.post(
`/api/dish/return`,
{
returned: {
condition: 'good',
},
},
{
headers: {
'x-api-key': `${process.env.REACT_APP_API_KEY}`,
'session-token': sessionToken,
'Content-Type': 'application/json',
},
params: { qid: qid },
baseURL: `${process.env.REACT_APP_BACKEND_ADDRESS}`,
},
)
.then(function (response) {
setForceSignInDialog(false)
setError('')
setIsLoading(false)
setMessage('')
setPopUp(true)
})
.catch(function (error) {
// handle error
console.log(error.response.data.message)
setError(error.response.data.message)
setIsLoading(false)
setMessage('')
setPopUp(true)
})) as any
setForceLoading(false)
}
}

const reportToggle = () => {
Expand Down Expand Up @@ -372,7 +448,7 @@ const Return = ({ noTimer }) => {
{/* {isLoading ? ( */}
{/* <></> */}
{/* // ) : ( */}
<AppHeader title={'Return Dishes'} className={'headerDiv'} />
<AppHeader title={'Return Dishes'} />
{/* // )} */}
{/* {isLoading ? (
<Box
Expand Down Expand Up @@ -411,6 +487,27 @@ const Return = ({ noTimer }) => {
) : (
<></>
)}

<CustomDialogTitle
open={forceSignInDialog}
setOpen={setForceSignInDialog}
dialogTitle={'Dish is not signed out'}
loading={false}>
<DialogContent sx={{ minWidth: '420px', textAlign: 'center' }}>
<Typography variant="body1" fontWeight="bold" sx={{ mb: '1rem' }}>
This dish is not signed out. You can force sign in and sign out the dish.
</Typography>
<Button
variant="contained"
onClick={forceSignIn}
size="large"
color="error"
disabled={forceLoading}>
Force Sign In Dish
</Button>
</DialogContent>
</CustomDialogTitle>

<CameraInput
setLoading={setIsLoading}
isMobile={isMobile}
Expand Down
6 changes: 0 additions & 6 deletions app/src/styles/header.css

This file was deleted.

27 changes: 16 additions & 11 deletions app/src/widgets/appHeader.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import { Box, AppBar, Typography} from "@mui/material";
import React from 'react';
import { Box, AppBar, Typography } from '@mui/material'
import React from 'react'

interface Props {
title: string
}

export const AppHeader = (props) => {
return(
<div className={props.className}>
<Box sx={{flexGrow:1, position:'relative', height:'14vh'}}>
<AppBar position="static" sx={{backgroundColor:'#68B49A', height:'100%', alignItems:"center", justifyContent:"center"}}>
<Typography sx={{fontWeight:'500', fontSize:'20px', mb:'-24px'}}> {props.title} </Typography>
</AppBar>
</Box>
</div>
export const AppHeader = ({ title }: Props) => {
return (
<div style={{ height: '25%' }}>
<Box sx={{ flexGrow: 1, position: 'relative', height: '14vh' }}>
<AppBar
position="static"
sx={{ backgroundColor: '#68B49A', height: '100%', alignItems: 'center', justifyContent: 'center' }}>
<Typography sx={{ fontWeight: '500', fontSize: '20px', mb: '-24px' }}> {title} </Typography>
</AppBar>
</Box>
</div>
)
}
6 changes: 3 additions & 3 deletions backend/src/controllers/dish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {
} from '../services/dish'
import { CustomRequest } from '../middlewares/auth'
import Logger from '../utils/logger'
import { getUserById, verifyIfUserAdmin, verifyIfUserVolunteer } from '../services/users'
import { getUserByEmail, getUserById, verifyIfUserAdmin, verifyIfUserVolunteer } from '../services/users'
import {
registerTransaction,
getLatestTransactionByTstamp,
Expand Down Expand Up @@ -328,6 +328,7 @@ export const addDishType = async (req: Request, res: Response) => {

export const borrowDish = async (req: Request, res: Response) => {
let qid = req.query['qid']?.toString()
let email = req.query['email']?.toString()

// TODO: add support for dish_id

Expand Down Expand Up @@ -373,8 +374,7 @@ export const borrowDish = async (req: Request, res: Response) => {
})
return res.status(400).json({ error: 'operation_not_allowed', message: 'Dish already borrowed' })
}

const user = (await getUserById(userClaims.uid)) as User
const user = email ? ((await getUserByEmail(email!)) as User) : ((await getUserById(userClaims.uid)) as User)
let transaction: Transaction = {
dish: {
qid: associatedDish.qid,
Expand Down

0 comments on commit 024d250

Please sign in to comment.