Skip to content

Commit

Permalink
Merge branch 'develop' into Valentin_Interfaz2
Browse files Browse the repository at this point in the history
  • Loading branch information
valydumitru01 committed May 1, 2022
2 parents 3bb339a + 765a464 commit d0e4439
Show file tree
Hide file tree
Showing 9 changed files with 118 additions and 35 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/asw2122.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 6 additions & 3 deletions restapi/api.ts
Original file line number Diff line number Diff line change
@@ -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()
Expand Down Expand Up @@ -46,4 +47,6 @@ api.post("/orders/add", addOrder);

api.post("/orders/deliveryCosts", getDeliveryCosts)

api.get("/orders/bestSeller", getBestSeller);

export default api;
24 changes: 23 additions & 1 deletion restapi/controllers/OrderController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -51,6 +52,28 @@ export const addOrder = async (req:Request, res:Response): Promise<any> => {

};

export const getBestSeller = async (req:Request, res:Response): Promise<any> => {

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<any> =>{

Expand All @@ -60,7 +83,6 @@ export const addOrder = async (req:Request, res:Response): Promise<any> => {

let string = JSON.stringify(addressCordinates);
let objectValue = JSON.parse(string);
console.log(addressCordinates);
let latitudeAddress = objectValue[0].latitude
let longitudeAddress = objectValue[0].longitude

Expand Down
5 changes: 2 additions & 3 deletions restapi/controllers/UserController.ts
Original file line number Diff line number Diff line change
@@ -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");

Expand Down Expand Up @@ -95,7 +94,7 @@ export const loginUser = async (req: Request, res: Response): Promise<any> => {
//autenticado: true,
// token: token
//});
res.send(req.session.usuario);
res.send();
}
}

Expand Down
19 changes: 16 additions & 3 deletions restapi/tests/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

Expand All @@ -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" })
Expand Down Expand Up @@ -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"})
Expand Down
14 changes: 14 additions & 0 deletions webapp/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,4 +99,18 @@ export async function getOrders(): Promise<Order[]>{
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<boolean>{
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;
}
42 changes: 21 additions & 21 deletions webapp/src/components/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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: '<a href ="/signup">¿No tienes cuenta? Registrate ahora!</a>'
});
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: '<a href ="/signup">¿No tienes cuenta? Registrate ahora!</a>'
});
}
})
}
Expand All @@ -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'
});
}
}
Expand Down
37 changes: 34 additions & 3 deletions webapp/src/components/payment/PaymentPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -90,11 +90,42 @@ const PaymentPage: React.FC<Props> = ({cartContent, setNewCart}) => {
return <PaymentSummary cartContent={cartContent} simplificate={(!isLoggedPod)}></PaymentSummary>
}

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 (
<div className='PaymentProcess-payment' >
Expand Down
1 change: 1 addition & 0 deletions webapp/src/shared/shareddtypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export type User = {
};
export type Rock = {
id:React.Key;
rockId:string;
name: string;
img: string;
price: number;
Expand Down

0 comments on commit d0e4439

Please sign in to comment.