diff --git a/.github/workflows/asw2122.yml b/.github/workflows/asw2122.yml index be5f522..68b025d 100644 --- a/.github/workflows/asw2122.yml +++ b/.github/workflows/asw2122.yml @@ -91,7 +91,7 @@ jobs: user: ${{ secrets.DEPLOY_USER }} key: ${{ secrets.DEPLOY_KEY }} command: | - wget https://raw.githubusercontent.com/Arquisoft/dede_es1a/Ignacio_BaseDeDatos/docker-compose-deploy.yml -O docker-compose.yml + wget https://raw.githubusercontent.com/Arquisoft/dede_es1a/master/docker-compose-deploy.yml -O docker-compose.yml docker-compose stop docker-compose rm -f docker-compose pull diff --git a/restapi/api.ts b/restapi/api.ts index f0a7795..03bafc2 100644 --- a/restapi/api.ts +++ b/restapi/api.ts @@ -1,10 +1,11 @@ + import express, { Request, Response, Router } from 'express'; import {check} from 'express-validator'; -import { addOrder, findOrdersByUserEmail, getDeliveryCosts } from './controllers/OrderController'; +import { addOrder, findOrdersByUserEmail, getBestSeller, getDeliveryCosts } from './controllers/OrderController'; + import {findRocks, addRock, deleteRock, findRocksSedimentary, findRocksMetamorphic, findRocksFiery, findByCritery, findRocksById} from './controllers/RockController'; import {findUsers, addUser, deleteUser, loginUser, logout} from './controllers/UserController'; -const User = require("./models/User"); -const Rock = require("./models/Rock"); + const api:Router = express.Router() @@ -46,4 +47,6 @@ api.post("/orders/add", addOrder); api.post("/orders/deliveryCosts", getDeliveryCosts) +api.get("/orders/bestSeller", getBestSeller); + export default api; \ No newline at end of file diff --git a/restapi/controllers/OrderController.ts b/restapi/controllers/OrderController.ts index 2cef1d4..fcf15ec 100644 --- a/restapi/controllers/OrderController.ts +++ b/restapi/controllers/OrderController.ts @@ -7,6 +7,7 @@ const options = { const geocoder = NodeGeocoder(options); const Order = require("../models/Order"); +const Rock = require("../models/Rock"); export const findOrdersByUserEmail = async (req:Request, res:Response) => { @@ -51,6 +52,28 @@ export const addOrder = async (req:Request, res:Response): Promise => { }; + export const getBestSeller = async (req:Request, res:Response): Promise => { + + const order = await Order.distinct("productName"); + + let num = 0; + let aux; + let aux2; + + for (let i =0; i < order.length; i++){ + aux= await Order.find({productName :order[i]}); + if (aux.length > num){ + num = aux.length; + aux2 = aux[0].productName; + } + } + + let bestSeller = await Rock.find({name: aux2}); + res.setHeader('Content-Type', 'application/json'); + res.status(200); + res.send(bestSeller); + + } export const getDeliveryCosts = async (req:Request, res:Response) : Promise =>{ @@ -60,7 +83,6 @@ export const addOrder = async (req:Request, res:Response): Promise => { let string = JSON.stringify(addressCordinates); let objectValue = JSON.parse(string); - console.log(addressCordinates); let latitudeAddress = objectValue[0].latitude let longitudeAddress = objectValue[0].longitude diff --git a/restapi/controllers/UserController.ts b/restapi/controllers/UserController.ts index 255de0c..9e7b8e4 100644 --- a/restapi/controllers/UserController.ts +++ b/restapi/controllers/UserController.ts @@ -1,7 +1,6 @@ -import express, { Request, Response, Router } from 'express'; +import { Request, Response } from 'express'; const User = require("../models/User"); -const mongoose = require("mongoose"); const crypto = require("crypto"); const jwt = require("jsonwebtoken"); @@ -95,7 +94,7 @@ export const loginUser = async (req: Request, res: Response): Promise => { //autenticado: true, // token: token //}); - res.send(req.session.usuario); + res.send(); } } diff --git a/restapi/tests/api.test.ts b/restapi/tests/api.test.ts index c94c723..16087d5 100644 --- a/restapi/tests/api.test.ts +++ b/restapi/tests/api.test.ts @@ -321,7 +321,6 @@ describe('product ', () => { const response: Response = await request(app).get("/api/rocks/list/critery") .send({critery : {name : "prueba"}}) .set('Accept', 'application/json'); - expect(response.body[0].name).toBe("prueba"); expect(response.statusCode).toBe(200); }); @@ -343,6 +342,12 @@ describe('product ', () => { expect(response.statusCode).toBe(200); }); + it('can be listed by id', async () => { + const response: Response = await request(app).get("/api/rocks/" + "prueba3") + expect(response.body[0].rockId).toBe("prueba3"); + expect(response.statusCode).toBe(200); + }); + it('can be deleted', async () => { const response: Response = await request(app).post("/api/rocks/delete") .send({ rockId: "prueba" }) @@ -374,21 +379,29 @@ describe('order ', () => { send({ orderId: "prueba", userEmail: "prueba", + productId: "prueba", price: 3, - productId: "prueba" + productName: "prueba", + productType: "prueba" }) .set('Accept', 'application/json') expect(response.statusCode).toBe(200); }); it('can be listed', async () => { - const response: Response = await request(app).get("/api/orders/userList") + const response: Response = await request(app).get("/api/orders/userList/" + "prueba") .send({userEmail : "prueba"}) .set('Accept', 'application/json'); expect(response.body[0].userEmail).toBe("prueba"); expect(response.statusCode).toBe(200); }); + it('cant be listed', async () => { + const response: Response = await request(app).get("/api/orders/userList/") + .set('Accept', 'application/json'); + expect(response.statusCode).toBe(404); + }); + it('can obtain deliveryCosts', async () => { const response: Response = await request(app).post("/api/orders/deliveryCosts") .send({address : "Palmira Villa, Oviedo"}) diff --git a/webapp/src/api/api.ts b/webapp/src/api/api.ts index 3667324..921697f 100644 --- a/webapp/src/api/api.ts +++ b/webapp/src/api/api.ts @@ -99,4 +99,18 @@ export async function getOrders(): Promise{ const apiEndPoint= process.env.REACT_APP_API_URI || 'http://localhost:5000/api' let response = await fetch(apiEndPoint + "/orders/userList/" + sessionStorage.getItem("userLogged")); return response.json(); +} + +export async function addOrder(order:Order):Promise{ + const apiEndPoint= process.env.REACT_APP_API_URI || 'http://localhost:5000/api' + let response = await fetch(apiEndPoint+'/orders/add', { + method: 'POST', + headers: {'Content-Type':'application/json'}, + body: JSON.stringify({'userEmail':order.userEmail, 'price':order.price, 'productId':order.productId, + 'productName':order.productName, 'productType': order.productType}) + }); + if (response.status===200) + return true; + else + return false; } \ No newline at end of file diff --git a/webapp/src/components/Login.tsx b/webapp/src/components/Login.tsx index 0e636d3..d83d4d6 100644 --- a/webapp/src/components/Login.tsx +++ b/webapp/src/components/Login.tsx @@ -40,24 +40,24 @@ function EmailForm(): JSX.Element { const handleLogin = (email: String, pass: String) => { - axios.post("http://localhost:5000/user/login", { "email": email, "password": pass }) - .then(res => { - if (res.status == 201) { - Swal.fire({ - title: "Sesión iniciada", - icon: "success" - }).then(() => { - console.log(res.data) - localStorage.setItem('token', res.data.token); - window.location.assign("/products"); - }); - } else { - Swal.fire({ - title: "Creedenciales incorrectos", - text: "El usuario o contraseña son incorrectos, vuelva a introducirlos", - icon: "error", - footer: '¿No tienes cuenta? Registrate ahora!' - }); + axios.post(("http://localhost:5000/api/user/login"|| process.env.REACT_APP_API_URI +"/users/login"),{"email":email,"password":pass}) + .then(res => { + if(res.status == 201){ + Swal.fire({ + title: "Sesión iniciada", + icon: "success" + }).then(() => { + console.log(res.data) + localStorage.setItem('token',res.data.token); + window.location.assign("/products"); + }); + }else{ + Swal.fire({ + title: "Creedenciales incorrectos", + text: "El usuario o contraseña son incorrectos, vuelva a introducirlos", + icon: "error", + footer: '¿No tienes cuenta? Registrate ahora!' + }); } }) } @@ -77,9 +77,9 @@ function EmailForm(): JSX.Element { } else { setNotificationStatus(true); - setNotification({ - severity: 'error', - message: 'There\'s been an error in the register proccess.' + setNotification({ + severity:'error', + message:'El usuario o contraseña son incorrectos, vuelva a introducirlos' }); } } diff --git a/webapp/src/components/payment/PaymentPage.tsx b/webapp/src/components/payment/PaymentPage.tsx index 474c7e7..12cd19b 100644 --- a/webapp/src/components/payment/PaymentPage.tsx +++ b/webapp/src/components/payment/PaymentPage.tsx @@ -8,7 +8,7 @@ import { CardContent, Typography } from '@mui/material'; import { North } from '@mui/icons-material'; import { useState, useEffect } from 'react'; import { Rock } from '../../shared/shareddtypes'; -import { getDeliveryCosts } from '../../api/api'; +import { addOrder, getDeliveryCosts } from '../../api/api'; import { findConfigFile } from 'typescript'; import PaymentSummary from './PaymentSummary'; import CartItem from '../CartItem'; @@ -90,11 +90,42 @@ const PaymentPage: React.FC = ({cartContent, setNewCart}) => { return } + function getUserEmail() { + const userEmail = sessionStorage.getItem("userLogged"); + + if (userEmail) + return userEmail; + else + return ""; + + } + + const addOrders = async (rock:Rock) => { + let rockId = rock.rockId; + let price = rock.price; + let name = rock.name; + let type = rock.type; + console.log(getUserEmail()); + await addOrder({ userEmail: getUserEmail(), price: price, productId: rockId, productName: name, productType: type, orderId: "", date: new Date}); + } + const handlePay = () => { setNewCart(true); - //TODO: añadir a bd - alert("Pagado -> no se añade bd"); + + if(sessionStorage.getItem("userLogged")){ + cartContent.forEach(function(rock){ + + for (let i = 0; i< rock.quantityCart; i++){ + addOrders(rock); + } + }); + alert("Su pedido ha sido realizado correctamente"); + }else{ + alert("Se ha producido un error en la creación de su pedido"); + } } + + return (
diff --git a/webapp/src/shared/shareddtypes.ts b/webapp/src/shared/shareddtypes.ts index 2247fa4..fd7ef16 100644 --- a/webapp/src/shared/shareddtypes.ts +++ b/webapp/src/shared/shareddtypes.ts @@ -8,6 +8,7 @@ export type User = { }; export type Rock = { id:React.Key; + rockId:string; name: string; img: string; price: number;