this repo has no description
at main 14 kB view raw
1import Head from 'next/head' 2import Image from 'next/image' 3import styles from '@/styles/Home.module.css' 4import { useEffect, useState } from 'react' 5import Card from '@mui/material/Card'; 6import CardActions from '@mui/material/CardActions'; 7import CardContent from '@mui/material/CardContent'; 8import CardMedia from '@mui/material/CardMedia'; 9import Button from '@mui/material/Button'; 10import Typography from '@mui/material/Typography'; 11import DeleteIcon from '@mui/icons-material/Delete'; 12import { IconButton, ToggleButton, ToggleButtonGroup } from '@mui/material'; 13import { Menu } from '@material-ui/icons'; 14import useDynamicRefs from 'use-dynamic-refs'; 15import { useSession } from 'next-auth/react'; 16 17export default function PurchasePage() { 18 19 const { data: session } = useSession() 20 21 let [menu, setMenu] = useState({}) 22 23 let [cart, setCart] = useState({}) 24 25 let [variationSelector, setVariationSelector] = useState({}) 26 27 const [getRef, setRef] = useDynamicRefs(); 28 29 function confirmOrder() { 30 let finalCartFull = {...cart}; 31 let finalCart = {} 32 // console.log(finalCart) 33 Object.keys(finalCartFull).forEach((category, categoryIdx) => { 34 finalCart[category] = {} 35 // console.log(finalCart[category]) 36 Object.keys(finalCartFull[category]).forEach((itemName, itemIdx) => { 37 // console.log(JSON.stringify(finalCartFull[category][itemName]) == "[]") 38 if(JSON.stringify(finalCartFull[category][itemName]) == "[]") { 39 return; 40 } 41 finalCart[category][itemName] = finalCartFull[category][itemName] 42 // console.log(`${category}: ${itemName}`) 43 }) 44 }) 45 46 Object.keys(finalCart).forEach((category, idx) => { 47 if(JSON.stringify(finalCart[category]) == "{}") { 48 delete finalCart[category] 49 } 50 }) 51 52 console.log(finalCart) 53 } 54 55 async function getMenu() { 56 let res = await fetch(`/api/data`, { 57 method: 'GET' 58 }) 59 60 let jsonResponse = await res.json() 61 62 setMenu(JSON.parse(JSON.stringify(jsonResponse))); 63 64 let variation = {} 65 let carttemp = {} 66 67 Object.keys(jsonResponse).forEach((category, idx) => { 68 variation[category] = {} 69 carttemp[category] = {} 70 jsonResponse[category].forEach((item, idx2) => { 71 carttemp[category][item["name"]] = [] 72 if(item["variations"].length > 0) { 73 variation[category][item["name"]] = item["variations"][0] 74 } 75 }) 76 }) 77 78 setVariationSelector(variation) 79 setCart(carttemp) 80 // console.log(variation) 81 82 83 } 84 85 function addToCartItem(item, category) { 86 let carttemp = {...cart}; 87 carttemp[category][item].push(variationSelector[category][item]) 88 setCart(carttemp) 89 } 90 91 function removeCartItem(item, category, index) { 92 let carttemp = {...cart}; 93 carttemp[category][item].splice(index, 1) 94 setCart(carttemp) 95 } 96 97 function addToCartItemVariation(item, category, variation) { 98 let carttemp = {...cart}; 99 carttemp[category][item].push(variation) 100 setCart(carttemp) 101 } 102 103 function removeCartItemVariation(item, category, variation) { 104 let carttemp = {...cart}; 105 let setidx = -1; 106 cart[category][item].forEach((val, idx) => { 107 if(val == variation) { 108 setidx = idx; 109 return; 110 } 111 }) 112 if(setidx != -1) { 113 carttemp[category][item].splice(setidx, 1) 114 } 115 setCart(carttemp) 116 } 117 118 function getAmountOfItemsWithVariation(item, category, variation) { 119 let amount = 0 120 cart[category][item].forEach((item, idx) => { 121 if(item == variation) { 122 amount++; 123 } 124 }) 125 return amount 126 } 127 128 function getCartItem(item, category) { 129 return cart[category][item] 130 } 131 132 function getCategoryWithItem(item) { 133 // console.log(Object.keys(cart)) 134 Object.keys(menu).forEach((category) => { 135 menu[category].forEach((val) => { 136 // console.log(`${item} ${val["name"]}`) 137 if(val["name"] == item) { 138 console.log(`${category} || ${item} || ${val["name"]}`) 139 return category 140 } 141 }) 142 }) 143 } 144 145 function getVariationSelectorValue(item, category) { 146 return variationSelector[category][item] 147 } 148 149 function setVariationSelectorValue(item, category, value) { 150 if(value == undefined) { 151 return; 152 } 153 154 let variation = {...variationSelector}; 155 variation[category][item] = value; 156 setVariationSelector(variation); 157 } 158 159 function getCartAsList() { 160 let cartList = [] 161 Object.keys(cart).forEach((category, idx) => { 162 Object.keys(cart[category]).forEach((itemName) => { 163 let cartItem = cart[category][itemName] 164 if(JSON.stringify(cartItem) == "[]") { 165 return; 166 } 167 cartList.push({ 168 "menu": menu[category].find((e) => e.name == itemName), 169 "cart": cartItem, 170 "category": category, 171 "item": itemName 172 }) 173 }) 174 }) 175 return cartList 176 } 177 178 function getTotalPrice() { 179 let totalPrice = 0.0 180 Object.keys(cart).forEach((category, idx) => { 181 Object.keys(cart[category]).forEach((itemName) => { 182 let cartItem = cart[category][itemName] 183 if(JSON.stringify(cartItem) == "[]") { 184 return; 185 } 186 let menuItem = menu[category].find((e) => e.name == itemName) 187 cartItem.forEach(() => { 188 totalPrice += parseFloat(menuItem["price"]) 189 }) 190 }) 191 }) 192 return totalPrice 193 } 194 195 196 197 useEffect(() => { 198 getMenu(); 199 }, []) 200 201 let [linkMenu, setLinkMenu] = useState(false) 202 203 return ( 204 <> 205 <Head> 206 <title>McDonalds</title> 207 <meta name="description" content="Generated by create next app" /> 208 <meta name="viewport" content="width=device-width, initial-scale=1" /> 209 <link rel="icon" href="/favicon.ico" /> 210 </Head> 211 <Button variant="contained" className={styles.menu_icon} onClick={() => setLinkMenu(!linkMenu)}> 212 <Menu style={{fontSize: 24}} /> 213 </Button> 214 { 215 linkMenu ? 216 <div className={styles.link_menu}> 217 { 218 Object.keys(menu).map((category, idx) => { 219 return ( 220 <div key={category + idx} onClick={() => getRef(category).current.scrollIntoView({ behavior: 'smooth' } ) }> 221 {category} 222 </div> 223 ) 224 }) 225 } 226 227 <div style={{display: "flex", flexDirection: "row"}}> 228 <div onClick={() => getRef("checkout").current.scrollIntoView({ behavior: 'smooth' })}> 229 Checkout 230 </div> 231 <div style={{position: "absolute", transform: "translateX(-50%)", right: 0, textAlign: "right", color: "gray", marginTop: 0}}> 232 {session.user.name} 233 </div> 234 </div> 235 </div> : "" 236 237 } 238 <main className={styles.main}> 239 { 240 Object.keys(menu).map((val, idx) => { 241 return ( 242 <div key={val}> 243 <h1 ref={setRef(val)} className={styles.h1}>{val}</h1> 244 <ul className={styles.card_container}> 245 { 246 menu[val].map((val2) => { 247 // console.log(val2) 248 return <div className={styles.card} key={val+val2["name"]} > 249 <Card sx={{minHeight: 420, position: "relative"}}> 250 <CardMedia 251 sx={{ height: 300, marginTop: "-120px"}} 252 image={val2["image"]} 253 title={val2["name"]} 254 /> 255 <CardContent> 256 <Typography gutterBottom variant="h5" component="div"> {/*för att få alla cards lika stora >> height={"7ch"}*/} 257 {val2["name"]} 258 </Typography> 259 <Typography gutterBottom variant="h6" component="div" fontSize={18} className={styles.info_container}> 260 <div>{val2["price"]} kr</div> 261 { val2["url"] != "" ? 262 <a className={styles.more_info} href={val2["url"]}>Mer info</a> 263 : "" } 264 </Typography> 265 </CardContent> 266 <div className={styles.card_actions} > 267 {/* { 268 getCartItem(val2["name"], val).map((cartItem, cartItemIdx) => { 269 return ( 270 <Button variant="outlined" size="large" fullWidth onClick={() => removeCartItem(val2["name"], val, cartItemIdx)}>{val2["name"] + (cartItem != undefined ? " (" + cartItem + ")" : "")}</Button> 271 ) 272 }) 273 } */} 274 { 275 <ToggleButtonGroup 276 color="primary" 277 exclusive 278 aria-label="Platform" 279 fullWidth 280 onChange={(e, alignement) => { 281 setVariationSelectorValue(val2["name"], val, alignement) 282 }} 283 value={getVariationSelectorValue(val2["name"], val)} 284 sx={val2["variations"].length != 0 ? {visibility: "shown"} : {}} 285 > 286 {val2["variations"].map((vari) => { 287 return( 288 <ToggleButton key={val + val2["name"] + vari} value={vari}>{vari}</ToggleButton> 289 ); 290 })} 291 </ToggleButtonGroup> 292 } 293 <Button sx={{marginTop: "auto", width: 225}} variant="contained" size="large" fullWidth onClick={() => addToCartItem(val2["name"], val)}>Add</Button> 294 </div> 295 </Card> 296 </div> 297 }) 298 } 299 </ul> 300 </div>); 301 }) 302 } 303 <div className={styles.spacer}></div> 304 <h1 ref={setRef("checkout")} className={styles.h1}>Checkout</h1> 305 <table> 306 <thead> 307 <tr> 308 <th> 309 Artikel 310 </th> 311 <th> 312 Mängd 313 </th> 314 <th> 315 Pris 316 </th> 317 </tr> 318 </thead> 319 <tbody> 320 { 321 getCartAsList().map((item, idx) => { 322 // console.log(`${item.menu.variations.length} vari`) 323 if(item.menu.variations.length == 0) { 324 return ( 325 <tr key={idx}> 326 <td> 327 {item["menu"]["name"]} 328 </td> 329 <td> 330 <button onClick={() => console.log(cart)}>a</button> 331 <button onClick={() => removeCartItem(item["menu"]["name"], item["category"], 0)}>-</button> 332 {item["cart"].length} 333 <button onClick={() => addToCartItem(item["menu"]["name"], item["category"])}>+</button> 334 </td> 335 <td> 336 {parseFloat(item["menu"]["price"]) * item["cart"].length} kr 337 </td> 338 </tr> 339 ) 340 } 341 342 return item["menu"]["variations"].map((variation, variationIdx) => { 343 if(getAmountOfItemsWithVariation(item["menu"]["name"], item["category"], variation) == 0) { 344 console.log('asd') 345 return; 346 } 347 return ( 348 <tr key={variation + item["menu"]["name"]}> 349 <td> 350 {item["menu"]["name"]} ({variation}) 351 </td> 352 <td> 353 <div className={styles.reciept_div}> 354 <button onClick={() => console.log(item)}>a</button> 355 <button onClick={() => removeCartItemVariation(item["menu"]["name"], item["category"], variation)}>-</button> 356 <div> 357 {getAmountOfItemsWithVariation(item["menu"]["name"], item["category"], variation)} 358 </div> 359 <button onClick={() => addToCartItemVariation(item["menu"]["name"], item["category"], variation)}>+</button> 360 </div> 361 </td> 362 <td> 363 {parseFloat(item["menu"]["price"]) * getAmountOfItemsWithVariation(item["menu"]["name"], item["category"], variation)} kr 364 </td> 365 </tr> 366 ) 367 }) 368 }) 369 } 370 </tbody> 371 </table> 372 <div className={styles.h1}> 373 <div> 374 Total Price: <b>{getTotalPrice()} kr</b> 375 </div> 376 <div style={{color: "gray`"}}> 377 (Priset kan variera lite) 378 </div> 379 <Button variant="contained" size="large" className={styles.confirm_button} disabled={JSON.stringify(getCartAsList()) == "[]" ? true : false} onClick={() => confirmOrder()}>Confirm Order</Button> 380 </div> 381 <div className={styles.footer}></div> 382 </main> 383 </> 384 ) 385}