Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resolucion del examen #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const bodyParser = require("body-parser");
const morgan = require("morgan");
const mongoose = require("mongoose");
const config = require("./config");
const {responseHelpers} = require("./middleware");
const {responseHelpers, cacheMiddleware} = require("./middleware");
const routes = require("./routes");
require("./models");

Expand All @@ -20,9 +20,8 @@ app.use(morgan("dev"));

// Add response helpers
app.use(responseHelpers);

// Add cache middleware
// app.use(cacheMiddleware);
app.use(cacheMiddleware);

// Setup mongoose and load models
mongoose.Promise = global.Promise;
Expand Down
62 changes: 60 additions & 2 deletions controllers/billing.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module.exports = (mongoose) => {
const Course = mongoose.model("Course");
const Evaluation = mongoose.model("Evaluation");
const Student = mongoose.model("Student");

const request = require("request");
// para cada curso dame la evaluacion
// para cada evaluacion dame los aprobados
// para cada aprobado dame el precio del curso y el student
Expand Down Expand Up @@ -81,8 +81,66 @@ module.exports = (mongoose) => {
res.response500(err, "Courses couldn't be found!");
});
}
function requestChargeableStudents() {
return new Promise((resolve, reject) => {
request.get("http://localhost:8000/api/admin/billing/getChargeableStudents", (_, __, body) => {
let students = [];
try {
students = JSON.parse(body).data.studentsBillingInfo;
} catch (ex) {
reject(new Error("error"));
}
const studentsAfip = [];
students.forEach((student) => {
studentsAfip.push({nomYAp: `${student.firstName} ${student.lastName}`, dir: student.address.street1, importe: student.price});
});
resolve(studentsAfip);
});
});
}

function mapAFIPResponse(invoiceId, student) {
return {
BillingNumber: invoiceId,
FirstAndLastName: student.nomYAp,
address: student.dir,
price: student.importe
};
}

function createInvoice(data) {
return new Promise((resolve) => {
request.post("http://localhost:8000/api/afip", {json: data}, (_, resp, body) => {
if (resp.statusCode === 200) {
resolve(mapAFIPResponse(body.data.id, data));
} else {
resolve(createInvoice(data));
}
});
});
}

function requestInvoices(students) {
return Promise.all(students.map((student) => {
return createInvoice(student);
}));
}

async function getInvoices(req, res) {
requestChargeableStudents().then((students) => {
return requestInvoices(students);
})
.then((invoices) => {
res.response200(invoices);
})
.catch(() => {
res.response500("There was an error :(");
});
}


return {
getChargeableStudents
getChargeableStudents,
getInvoices
};
};
2 changes: 1 addition & 1 deletion controllers/courses.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module.exports = (mongoose) => {
var Course = mongoose.model("Course"),
filterFields = ["status"],
filterFields = ["status", "technologyId"],
sortFields = ["status"];

var buildFilterQuery = function(params) {
Expand Down
2 changes: 2 additions & 0 deletions controllers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ const CoursesController = require("./courses");
const StudentsController = require("./students");
const EvaluationsController = require("./evaluations");
const TechnologiesController = require("./technologies");
const StatsController = require("./stats");

module.exports = {
BillingController,
EvaluationsController,
CoursesController,
StudentsController,
StatsController,
TechnologiesController
};
55 changes: 55 additions & 0 deletions controllers/stats.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
module.exports = (mongoose) => {
const Evaluation = mongoose.model("Evaluation");
const Student = mongoose.model("Student");
const stateArray = {};
const addedStudents = [];

function addState(state, studentId) {
if (!addedStudents.includes(studentId.toString())) {
addedStudents.push(studentId.toString());
if (stateArray[state]) {
stateArray[state]++;
} else {
stateArray[state] = 1;
}
}
}

function addStudents(studentList) {
studentList.forEach((student) => {
addState(student.billingAddress.state, student._id);
});
return Promise.resolve(stateArray);
}

function getFailedNotes() {
return Evaluation.find()
.then((failedEvals) => {
const notes = failedEvals.reduce((fullNotes, evaluation) => {
return fullNotes.concat(evaluation.notes);
}, []).filter((note) => {
return note.status === "failed";
});

return Promise.all(notes);
});
}

function getStudentsFromNotes(notes) {
const students = notes.map((note) => {
return Student.findOne({_id: note.studentId});
});
return Promise.all(students);
}
function failuresByStates(req, res) {
getFailedNotes()
.then(getStudentsFromNotes)
.then(addStudents)
.then(res.response200);
}


return {
failuresByStates
};
};
32 changes: 32 additions & 0 deletions middleware/cacheMiddleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const excludedFromCache = [
"/api/admin/billing/getChargeableStudents"
];
const cache = {};

function isCached(req) {
return cache[req.url];
}
function getFromCache(req) {
return cache[req.url];
}

function removeFromCache(req) {
delete cache[req.url];
}
module.exports = (req, res, next) => {
if (excludedFromCache.includes(req.originalUrl)) {
return next();
}
if (req.method === "GET") {
if (isCached(req)) {
return res.response200(getFromCache(req), "Cached");
}
res.response200 = (data = {}, message = "ok") => {
cache[req.originalUrl] = data;
res.json({data, status: "success", message});
};
} else {
removeFromCache(req);
}
return next();
};
3 changes: 2 additions & 1 deletion middleware/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
const responseHelpers = require("./responseHelpers");
const cacheMiddleware = require("./cacheMiddleware");

module.exports = {responseHelpers};
module.exports = {responseHelpers, cacheMiddleware};
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"main": "app.js",
"scripts": {
"start": "node ./app.js",
"test": "NODE_ENV=test ./node_modules/mocha/bin/_mocha --timeout 1000 --exit"
"test": "NODE_ENV=test ./node_modules/mocha/bin/_mocha --timeout 100000 --exit"
},
"keywords": [
"exam",
Expand Down
10 changes: 9 additions & 1 deletion routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ const {
EvaluationsController,
CoursesController,
StudentsController,
TechnologiesController
TechnologiesController,
StatsController
} = require("./controllers");
const afipAPI = require("./services/afip-mock-api");

Expand All @@ -27,6 +28,7 @@ module.exports = (app, router) => {
const evaluationController = EvaluationsController(mongoose);
const technologyController = TechnologiesController(mongoose);
const billingController = BillingController(mongoose);
const statsController = StatsController(mongoose);

const controllers = [
{basePath: "/evaluations", controller: evaluationController},
Expand All @@ -37,11 +39,17 @@ module.exports = (app, router) => {

mapGenericControllerRoutes(controllers, router);

router.route("/stats/failuresByStates")
.get(statsController.failuresByStates);

router.route("/admin/billing/getChargeableStudents")
.get(billingController.getChargeableStudents);

router.route("/afip")
.post(afipAPI.getInvoice);

router.route("/admin/billing/getInvoices").get(
billingController.getInvoices
);
return router;
};
Loading