diff --git a/.gitignore b/.gitignore index 4d29575..755bd2e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,8 +2,11 @@ # dependencies /node_modules +!pdf-generator/node_modules/ /.pnp .pnp.js +/package-lock.json +/yarn.lock # testing /coverage diff --git a/.serverless/meta.json b/.serverless/meta.json new file mode 100644 index 0000000..5d70c10 --- /dev/null +++ b/.serverless/meta.json @@ -0,0 +1,18 @@ +{ + "unknown": { + "versionSfCore": null, + "versionFramework": "4.4.6", + "isWithinCompose": false, + "composeOrgName": null, + "composeServiceName": null, + "command": [], + "options": {}, + "error": null, + "machineId": "55ce82351452d045dae40665b323edd6", + "serviceProviderAwsCfStackId": null, + "serviceProviderAwsCfStackCreated": null, + "serviceProviderAwsCfStackUpdated": null, + "serviceProviderAwsCfStackStatus": null, + "serviceProviderAwsCfStackOutputs": null + } +} \ No newline at end of file diff --git a/package.json b/package.json index 085994c..f61e0b9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,7 @@ { "name": "entrega1", "private": true, + "type": "module", "dependencies": { "@auth0/auth0-react": "^2.2.4", "@svgr/webpack": "^8.1.0", @@ -10,9 +11,10 @@ "axios": "^1.7.7", "react": "^18.3.1", "react-dom": "^18.3.1", - "react-scripts": "^5.0.1", "resolve-url-loader": "^5.0.0", "svgo": "^3.3.2", + "react-scripts": "5.0.1", + "serverless": "^4.4.6", "web-vitals": "^2.1.4" }, "scripts": { diff --git a/pdf-generator/.gitignore b/pdf-generator/.gitignore new file mode 100644 index 0000000..95716b2 --- /dev/null +++ b/pdf-generator/.gitignore @@ -0,0 +1,3 @@ +node_modules +.serverless +/yarn.lock diff --git a/pdf-generator/README.md b/pdf-generator/README.md new file mode 100644 index 0000000..2f7bf87 --- /dev/null +++ b/pdf-generator/README.md @@ -0,0 +1,76 @@ + + +# Serverless Framework Node Express API on AWS + +This template demonstrates how to develop and deploy a simple Node Express API service running on AWS Lambda using the Serverless Framework. + +This template configures a single function, `api`, which is responsible for handling all incoming requests using the `httpApi` event. To learn more about `httpApi` event configuration options, please refer to [httpApi event docs](https://www.serverless.com/framework/docs/providers/aws/events/http-api/). As the event is configured in a way to accept all incoming requests, the Express.js framework is responsible for routing and handling requests internally. This implementation uses the `serverless-http` package to transform the incoming event request payloads to payloads compatible with Express.js. To learn more about `serverless-http`, please refer to the [serverless-http README](https://github.com/dougmoscrop/serverless-http). + +## Usage + +### Deployment + +Install dependencies with: + +``` +npm install +``` + +and then deploy with: + +``` +serverless deploy +``` + +After running deploy, you should see output similar to: + +``` +Deploying "aws-node-express-api" to stage "dev" (us-east-1) + +✔ Service deployed to stack aws-node-express-api-dev (96s) + +endpoint: ANY - https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com +functions: + api: aws-node-express-api-dev-api (2.3 kB) +``` + +_Note_: In current form, after deployment, your API is public and can be invoked by anyone. For production deployments, you might want to configure an authorizer. For details on how to do that, refer to [`httpApi` event docs](https://www.serverless.com/framework/docs/providers/aws/events/http-api/). + +### Invocation + +After successful deployment, you can call the created application via HTTP: + +``` +curl https://xxxxxxx.execute-api.us-east-1.amazonaws.com/ +``` + +Which should result in the following response: + +```json +{ "message": "Hello from root!" } +``` + +### Local development + +The easiest way to develop and test your function is to use the `dev` command: + +``` +serverless dev +``` + +This will start a local emulator of AWS Lambda and tunnel your requests to and from AWS Lambda, allowing you to interact with your function as if it were running in the cloud. + +Now you can invoke the function as before, but this time the function will be executed locally. Now you can develop your function locally, invoke it, and see the results immediately without having to re-deploy. + +When you are done developing, don't forget to run `serverless deploy` to deploy the function to the cloud. diff --git a/pdf-generator/handler.js b/pdf-generator/handler.js new file mode 100644 index 0000000..26815e7 --- /dev/null +++ b/pdf-generator/handler.js @@ -0,0 +1,53 @@ +const serverless = require("serverless-http"); +const express = require("express"); +const AWS = require("aws-sdk"); +const { PDFDocument } = require("pdf-lib"); + +const app = express(); +const S3 = new AWS.S3(); + +app.use(express.json()); + +app.post("/generate", async (req, res) => { + try { + const { userData, matchData } = req.body; + + if (!userData || !matchData) { + return res.status(400).json({ message: "Datos incompletos" }); + } + + const { home, away } = matchData.teams; + + const pdfDoc = await PDFDocument.create(); + const page = pdfDoc.addPage([600, 400]); + + page.drawText(`Usuario: ${userData.name}`, { x: 50, y: 330 }); + page.drawText(`Correo: ${userData.email}`, { x: 50, y: 310 }); + page.drawText(`Partido:`, { x: 50, y: 290 }); + page.drawText(`Equipo Local: ${home.name}`, { x: 50, y: 270 }); + page.drawText(`Equipo Visitante: ${away.name}`, { x: 50, y: 250 }); + page.drawText(`Fecha del Partido: ${matchData.date}`, { x: 50, y: 230 }); + page.drawText(`Monto de la compra: ${matchData.amount}`, { x: 50, y: 210 }); + + const pdfBytes = await pdfDoc.save(); + + const params = { + Bucket: 'node-craft', + Key: `boletas/${userData.name}_${Date.now()}.pdf`, + Body: Buffer.from(pdfBytes), + ContentType: 'application/pdf', + }; + + const data = await S3.upload(params).promise(); + + res.status(200).json({ + message: "Boleta generada con éxito", + pdfUrl: data.Location + }); + } catch (error) { + console.error("Error:", error); + res.status(500).json({ message: "Error generando la boleta", error }); + } +}); + +module.exports.handler = serverless(app); diff --git a/pdf-generator/package.json b/pdf-generator/package.json new file mode 100644 index 0000000..bf7e656 --- /dev/null +++ b/pdf-generator/package.json @@ -0,0 +1,11 @@ +{ + "name": "pdf-generator", + "version": "1.0.0", + "description": "", + "dependencies": { + "aws-sdk": "^2.1691.0", + "express": "^4.19.2", + "pdf-lib": "^1.17.1", + "serverless-http": "^3.2.0" + } +} diff --git a/pdf-generator/serverless.yml b/pdf-generator/serverless.yml new file mode 100644 index 0000000..2492b79 --- /dev/null +++ b/pdf-generator/serverless.yml @@ -0,0 +1,22 @@ +org: kev123 +service: pdf-generator + +provider: + name: aws + runtime: nodejs20.x + region: us-east-1 + + iamRoleStatements: + - Effect: "Allow" + Action: + - "s3:PutObject" + - "s3:GetObject" + Resource: "arn:aws:s3:::node-craft/*" + +functions: + api: + handler: handler.handler + events: + - httpApi: + path: /generate + method: post \ No newline at end of file diff --git a/src/App.css b/src/App.css index 45682e3..12bf472 100644 --- a/src/App.css +++ b/src/App.css @@ -12,7 +12,6 @@ .App-header { display: flex; - flex-direction: column; align-items: center; justify-content: center; padding: 20px; diff --git a/src/App.js b/src/App.js index 98af548..2a893e6 100644 --- a/src/App.js +++ b/src/App.js @@ -2,6 +2,7 @@ import './App.css'; import React, { useState, useEffect, useCallback } from 'react'; import axios from 'axios'; import { useAuth0 } from '@auth0/auth0-react'; +import { generateInvoice } from './services/invoiceService.js'; function App() { const { loginWithRedirect, logout, isAuthenticated, user, getAccessTokenSilently } = useAuth0(); @@ -187,9 +188,28 @@ function App() { if (response.data.error) { alert(response.data.error); } else { - alert('Compra exitosa. Ubicación de la solicitud: ' + response.data.location.city); - fetchUser(); - fetchFixtures(); + + // Agregado generación de boleta post compra + const userData = { + name: user.nickname, + email: user.email + }; + + const matchData = { + teams: fixture.teams, + date: fixture.date, + amount: cost // El valor depende de la cantidad + }; + + // Se genera el URL de la boleta y además se informa la ubicación + try { + const pdfUrl = await generateInvoice(userData, matchData); + alert(`Compra exitosa. Descarga tu boleta aquí: ${pdfUrl}. Ubicación: ${response.data.location.city}`); + fetchUser(); + fetchFixtures(); + } catch (error) { + alert('Error generando la boleta.'); + } } } catch (error) { setShowProcessingModal(false); diff --git a/src/index.js b/src/index.js index 624a539..bc4304c 100644 --- a/src/index.js +++ b/src/index.js @@ -13,6 +13,7 @@ root.render( domain={process.env.REACT_APP_AUTH0_DOMAIN} clientId={process.env.REACT_APP_AUTH0_CLIENT_ID} redirectUri={window.location.origin} + audience="https://api.nodecraft.me" > diff --git a/src/services/invoiceService.js b/src/services/invoiceService.js new file mode 100644 index 0000000..36f6af1 --- /dev/null +++ b/src/services/invoiceService.js @@ -0,0 +1,40 @@ +import axios from 'axios'; + +export const generateInvoice = async (userData, matchData) => { + try { + + const response = await axios.post('https://axp8mrrbk1.execute-api.us-east-1.amazonaws.com/generate', { + userData: { + name: userData.name, + email: userData.email + }, + matchData: { + teams: { + home: { + id: matchData.teams.home.id, + name: matchData.teams.home.name, + logo: matchData.teams.home.logo, + winner: matchData.teams.home.winner + }, + away: { + id: matchData.teams.away.id, + name: matchData.teams.away.name, + logo: matchData.teams.away.logo, + winner: matchData.teams.away.winner + } + }, + date: matchData.date, + amount: matchData.amount + } + }); + + if (response.data && response.data.pdfUrl) { + return response.data.pdfUrl; + } else { + throw new Error('Error generando la boleta'); + } + } catch (error) { + console.error('Error generando la boleta:', error); + throw error; + } +}; diff --git a/yarn.lock b/yarn.lock index 80354e3..da3818d 100644 --- a/yarn.lock +++ b/yarn.lock @@ -10301,3 +10301,4 @@ yocto-queue@^0.1.0: version "0.1.0" resolved "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz" integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q== +