Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var _ = require('lodash'),
- fs = require('fs'),
- path = require('path'),
- lights = require(path.resolve('./modules/lights/server/controllers/lights.server.controller')),
- catcher = require(path.resolve('./modules/admins/server/controllers/catcher.server.controller')),
- mongoose = require('mongoose'),
- moment = require('moment'),
- config = require(path.resolve('./config/config')),
- isapi = require('infusionsoft-api'),
- is = new isapi.DataContext('XXXXX', 'XXXXX'), //infusionsoft
- Trans = mongoose.model('Trans'),
- Coupon = mongoose.model('Coupon'),
- Light = mongoose.model('Light'),
- Space = mongoose.model('Space'),
- History = mongoose.model('History'),
- stripe = require('stripe')('xxxxx'),
- pdf = require('pdfkit'),
- async = require("async"),
- randomstring = require("randomstring"),
- easypost = require('node-easypost')('xxxxx'),
- AWS = require('aws-sdk'),
- emailjs = require('emailjs');
- AWS.config.region = 'us-west-2';
- AWS.config.update({
- accessKeyId: 'XXXX',
- secretAccessKey: 'xxxxx'
- });
- var s3 = new AWS.S3();
- var server = emailjs.server.connect({
- user: "support@diylightingsavings.com",
- password: "A1b2c3d4e5",
- host: "smtpout.secureserver.net",
- ssl: false,
- port: 80
- });
- var fromAddress = {
- name: "Spot Lighting Supplies",
- street1: "1200 Oregon Ave",
- //street2: "4th Floor",
- city: "Long Beach",
- state: "CA",
- zip: "90813",
- phone: "415-123-4567"
- };
- exports.final = function (req, res) {
- //req.user = req.body.saving.user; // the user we will buy for
- var rand = randomstring.generate(7);
- req.rand = rand;
- var parcel = calculteSize(req.saving.lights);
- var StripeObj = { // this is the Stripe Object
- currency: "usd",
- source: req.body.token, // obtained with Stripe.js
- description: "Infusionsoft ID: " + req.user.isId,
- shipping: {
- address : {
- line1: req.body.shipping.line1,
- line2: req.body.shipping.line2,
- state: req.body.shipping.state,
- city: req.body.shipping.city,
- postal_code: req.body.shipping.postal_code,
- country: "US",
- },
- name : req.body.shipping.firstName + " " + req.body.shipping.lastName
- }
- };
- updateUserInIs({
- Address2Street1: req.body.shipping.line1,
- Address2Street2: req.body.shipping.line2,
- State2: req.body.shipping.state,
- City2: req.body.shipping.city,
- PostalCode2: req.body.shipping.postal_code,
- EmailAddress2: req.body.shipping.email,
- Country2: "United States",
- Phone1: req.body.shipping.phone
- }, req.user.isId);
- StripeObj.receipt_email = req.body.shipping.email;
- shipping(req, function(shippingErr, shipping){ // calculate the shipping costs
- if(shippingErr){
- console.log("Shipment error");
- return status(200).send(shippingErr);
- } else {
- console.log("shipment succeed");
- }
- var totalShipping = 0; // add the shipping price
- for(var k in shipping){
- totalShipping += Number(lowerShiping(shipping[k]).rate);
- }
- catcher.catch({
- ip: req.userIp,
- user: req.user._id,
- label: "success",
- title: "Shipping rate for purchase",
- rand: rand,
- json: shipping
- });
- //console.log("total shipping costs: " + totalShipping);
- //console.log("coupon code: " + req.body.coupon);
- coupon(req.body.coupon, function(err, discount){
- var total;
- console.log(err, discount);
- var disc = 0;
- if(err){
- total = req.saving.price + totalShipping;
- } else {
- if(discount.value){
- //console.log("discount: ", discount);
- if(discount.type === 'Percentage' && (req.saving.price - ( req.saving.price * discount.value / 100 ) + totalShipping) > 200){
- disc = req.saving.price * discount.value / 100;
- total = req.saving.price - ( req.saving.price * discount.value / 100 ) + totalShipping;
- } else if(discount.type === 'Money' && (req.saving.price - discount.value + totalShipping) > 200){
- disc = discount.value;
- total = req.saving.price - discount.value + totalShipping;
- } else {
- total = req.saving.price + totalShipping;
- }
- } else {
- total = req.saving.price + totalShipping;
- }
- }
- console.log("Origin price: " + req.saving.price);
- console.log("discount: " + disc);
- console.log("shipping: " + totalShipping);
- console.log("toital: " + total);
- total = total.toFixed(2); // total price to charge the client
- total = Math.round( (total ) * 100 ); // this is the point where the amount is being transfered to cents
- StripeObj.amount = total;
- var labels = [];
- var tracking = [];
- var shippingIds = [];
- stripe.charges.create(StripeObj, function(errStripe, charge) { // then we charge the card!
- // change the Infusionsfot tag
- is.ContactService.addToGroup(req.user.isId,138).done(function(results){
- //console.log("Add buy tag: " + results);
- });
- if(errStripe){
- console.log("Stripe Error : " , errStripe);
- return res.status(200).send(errStripe);
- catcher.catch({
- ip: req.userIp,
- user: req.user._id,
- label: "fail",
- title: "Stripe fail",
- json: errStripe,
- rand: rand,
- alert: true
- });
- } else {
- console.log("Stripe succeed");
- res.status(200).json({statusCode: 200});
- catcher.catch({
- ip: req.userIp,
- user: req.user._id,
- label: "success",
- title: "Stripe success",
- json: charge,
- rand: rand
- });
- // and we continue:
- async.each(shipping, function(item, buyShipmentCb){
- buyShipping(item, function(errBuyShipping, shipment){ // then we buy the shipping
- if(errBuyShipping){
- console.log("error in buy shipping");
- console.log("erro in buy shipment: " ,errBuyShipping);
- catcher.catch({
- ip: req.userIp,
- user: req.user._id,
- label: "fail",
- title: "Fail to buy shipping",
- json: errBuyShipping,
- rand: rand,
- alert: true
- });
- return buyShipmentCb(errBuyShipping);
- } else {
- console.log("Shipment buy success");
- if(shipment.postage_label){
- labels.push(shipment.postage_label.label_url);
- } else{
- labels.push("No Label");
- }
- item.label = shipment.postage_label.label_url || "No label";
- catcher.catch({
- ip: req.userIp,
- user: req.user._id,
- label: "success",
- title: "Success buy shipping",
- json: item,
- rand: rand
- });
- buyShipmentCb(null);
- }
- shippingIds.push(shipment.id);
- //console.log("Buy shipping success! " , shipment.id);
- });
- }, function(errEach){
- if(errEach){
- console.log(errEach);
- } else {
- //console.log(shipping);
- var trans = new Trans({
- stripe: charge,
- saving: req.body.saving,
- tracking: tracking,
- label: labels,
- shippingId: shippingIds,
- rand: req.rand,
- user: req.user._id
- });
- trans.save(trans, function(errTrans, trans){ //save the info
- if(errTrans){
- console.log("error in save trans");
- catcher.catch({
- ip: req.userIp,
- user: req.user._id,
- label: "error",
- title: "Error in saving transaction",
- content: trans,
- json: errTrans,
- rand: rand
- });
- } else{
- console.log("transaction saved");
- recycle(rand, trans._id, req.user._id, req.saving.lights, total/100, function(){
- });
- }
- });
- catcher.catch({
- ip: req.userIp,
- user: req.user._id,
- label: "success",
- title: "Success in buy",
- json: trans,
- rand: rand
- });
- emailProcess(req, rand, labels, parcel, function(errEmail){ // and sending the email to the vendor
- if(errEmail){
- console.log("error in sending email");
- catcher.catch({
- ip: req.userIp,
- user: req.user._id,
- label: "error",
- title: "Error in sending email to vendor",
- content: labels,
- json: errEmail,
- rand: rand
- });
- } else {
- console.log("email sent");
- }
- });
- }
- });
- }
- });
- });
- });
- };
- exports.shipping = function (req, res) {
- console.log("Calculate shipping");
- shipping(req, function(err, shipping){
- if(err){
- console.log(err);
- return res.send(err);
- } else {
- //console.log("Shipping is done", shipping);
- }
- var total = 0;
- for(var k in shipping){
- var single = lowerShiping(shipping[k]);
- if(single !== false)
- total += Number(single.rate);
- //console.log(Number(lowerShiping(shipping[k]).rate));
- }
- if(total === 0){
- return res.send({message:"Error"});
- } else {
- return res.send({rate: total});
- }
- });
- };
- exports.email = function (req, res) {
- emailProcess(req, function(err){
- res.send();
- });
- };
- exports.parcel = function (req, res) {
- var re = calculteSize(req.saving.lights);
- res.send(re);
- };
- exports.findCoupon = function (req, res) {
- coupon(req.params.coupon ,function(err, coupon){
- if(err)
- res.send(err);
- else
- res.send(coupon);
- });
- };
- function coupon(name, callback){
- if(!name)
- return callback(true, null);
- Coupon.find({name : name, exp: {"$gte": new Date()}}, { exp :0, quantity:0, usage:0, limit:0, created:0, _id:0 }, function(err, doc){
- if(err || !doc.length){
- callback(err, null);
- } else {
- callback(null, doc[0]);
- }
- });
- }
- function Varify(toAddress, callback){
- easypost.Address.create(toAddress, function(err, toAddress) {
- toAddress.verify(function(err, response) {
- //console.log("varification:");
- //console.log(err, response);
- if (err) {
- console.log('Address is invalid.' , err);
- return callback(err);
- }
- else
- return callback(null);
- });
- });
- };
- function shippingFunction(toAddress, fromAddress, parcel, callback){
- easypost.Shipment.create({
- to_address: toAddress,
- from_address: fromAddress,
- parcel: parcel
- }, function(err, shipment) {
- //console.log(err, shipment);
- if(err)
- return callback(err,null);
- return callback(null, shipment);
- });
- }
- function buyShipping(shipment, callback){
- //console.log(shipment);
- shipment.buy({rate: shipment.lowestRate(['USPS'])}, function(err, shipment) {
- if(err){
- return callback(err, null);
- }
- return callback(null, shipment);
- });
- }
- function shipping(req, finalCb){
- var results = [];
- var toAddress = {
- name: req.body.shipping.firstName + " " + req.body.shipping.lastName,
- street1: req.body.shipping.line1,
- street2: req.body.shipping.line2,
- city: req.body.shipping.city,
- state: req.body.shipping.state,
- zip: req.body.shipping.postal_code,
- country: "US",
- phone: req.body.shipping.phone
- };
- //console.log("to address" , toAddress);
- Varify(toAddress, function(err){
- if(err){
- console.log("bad address");
- finalCb(err, null);
- return catcher.catch({
- ip: req.userIp,
- user: req.user._id,
- label: "fail",
- title: "Fail to varify address",
- json: err
- });
- } else {
- console.log("Adrress legit!");
- catcher.catch({
- ip: req.userIp,
- user: req.user._id,
- label: "success",
- title: "Succcess to varify address",
- json: err
- });
- }
- var parcel = calculteSize(req.saving.lights);
- //console.log(parcel);
- async.each(parcel, function(item, eachCb) {
- //console.log("each");
- shippingFunction(toAddress, fromAddress, item.dimensions, function(err, shipment){
- if(err){
- eachCb(err);
- } else {
- shipment.items = item;
- results.push(shipment);
- eachCb();
- }
- });
- }, function(err){
- //console.log("done generating the shipments");
- if(err){
- catcher.catch({
- ip: req.userIp,
- user: req.user._id,
- label: "fail",
- title: "Fail to generate shipping",
- json: err
- });
- console.log(err);
- return finalCb(err, null);
- } else {
- catcher.catch({
- ip: req.userIp,
- user: req.user._id,
- label: "success",
- title: "Success to create shipping",
- json: results
- });
- return finalCb(null, results);
- }
- });
- });
- };
- function lowerShiping(shipping){
- var low = 100000.00;
- var obj;
- if(shipping.rates.length === 0)
- return false;
- for(var k in shipping.rates){
- if(Number(shipping.rates[k].rate) < Number(low)){
- obj = shipping.rates[k];
- low = shipping.rates[k].rate;
- }
- }
- return obj;
- }
- function calculteSize(items){
- var bigBox = {
- length: 17,
- width: 17,
- height: 18
- };
- var smallBox = {
- length: 10,
- width: 10,
- height: 10
- };
- var maxSize = 18*17*17*0.8;
- var totalSize = 0;
- var boxes = [];
- var boxSize = 0;
- var boxWeight = 0;
- var boxObj = {arr:[]};
- for(var k in items){
- var tempQ = items[k].quatity;
- for(var p = 0 ; p < tempQ; p++){
- var tempS = items[k].replace.size;
- var tempW = items[k].replace.weight;
- if( (boxSize + tempS) < maxSize ){
- boxObj.arr.push(items[k]);
- boxSize += tempS;
- boxWeight += tempW;
- } else {
- //seal the old box
- boxObj.dimensions = bigBox;
- boxObj.dimensions.weight = boxWeight;
- boxObj.weight = boxWeight;
- boxObj.size = boxSize;
- boxes.push(boxObj);
- //open a new box
- var boxSize = 0;
- var boxWeight = 0;
- var boxObj = {arr:[]};
- //push the item to the new box
- boxObj.arr.push(items[k]);
- boxWeight += tempW;
- boxSize += tempS;
- }
- }
- if(Number(k) === items.length -1){
- boxObj.dimensions = bigBox;
- boxObj.dimensions.weight = boxWeight;
- boxObj.weight = boxWeight;
- boxObj.size = boxSize;
- boxes.push(boxObj);
- //resize the last box
- if(boxes[boxes.length-1].size < (10*10*10*0.8)){
- boxes[boxes.length-1].dimensions = smallBox;
- boxes[boxes.length-1].dimensions.weight = boxes[boxes.length-1].weight;
- }
- }
- }
- return boxes;
- // 2 obejects^
- }
- function LightsByRoom(list){
- var rooms = [];
- for(var k in list){
- var find = true;
- for(var i in rooms){
- if(rooms[i].id === list[k].space._id){
- rooms[i].lights.push(list[k]);
- find = false;
- continue;
- }
- }
- if(find){
- rooms.push({
- id: list[k].space._id,
- name: list[k].space.name,
- inout: list[k].space.inout,
- lights: [list[k]]
- });
- }
- }
- return rooms;
- };
- function emailProcess(req, rand, label, parcel, callback){
- //console.log("email process");
- var fullName = req.body.user.firstName + " " + req.body.user.lastName;
- async.parallel([
- function(callback) {
- //console.log("start PDF 1");
- userPdf(req.saving, rand, req.user.isId, function() {
- callback();
- });
- },
- function(callback) {
- //console.log("start PDF 2");
- vendorPdf(parcel, rand, fullName, callback);
- }
- ], function(err) {
- if(err)
- return callback(err);
- //console.log("pdf success!");
- email(rand,{toEmail: req.body.user.email, label: label, name: fullName}, function(err2){
- //console.log('Email Sent');
- return callback(err);
- });
- });
- }
- function email(rand, details, callback){
- var text = "DYI Lighting Savings \nShipping Labels: ";
- for(var k in details.label){
- text += details.label[k] + "\n";
- }
- text += '\nTransaction# : ' + rand + "\nName: " + details.name;
- server.send({
- text: text,
- from: "DIY Lighting Savings <support@diylightingsavings.com>",
- to: "bn.barak@gmail.com, maxpalacio@gmail.com, brennen@spot-lighting.com",
- subject: "DYI Lighting Savings #"+rand,
- attachment:
- [
- {path:"/tmp/User-" + rand + ".pdf", type:"application/pdf", name:"Instructions-" + rand + ".pdf"},
- {path:"/tmp/Vendor-" + rand + ".pdf", type:"application/pdf", name:"Vendor-" + rand +".pdf"}
- ]
- }, function(err, message) {
- //console.log(err || message);
- if(err)
- return callback(err);
- else
- return callback(null);
- });
- }
- function userPdf(saving, rand, isId, callback){
- var rooms = LightsByRoom(saving.lights);
- var doc = new pdf({"margins" : { // by default, all are 72
- "top": 72,
- "bottom": 0,
- "left": 72,
- "right": 72
- }});
- var v = 0;
- var pages = 0;
- var name = "/tmp/User-" + rand + ".pdf";
- doc.pipe(fs.createWriteStream(name));
- doc.rect(0,0,612,46).lineWidth(0).fill("#4CAF50");
- doc.fill("#fff");
- doc.text("DYI Lighting Saving", 20 ,20);
- doc.text("#" + rand, 300 ,20);
- doc.text(moment().format("MMM-DD-YYYY"), 470 ,20); V(80);
- doc.fill("#000").fontSize("20").text("Thank You for Choosing Lighting Savings", 130, v); V(40);
- doc.fill("#212121").fontSize("18").text("Follow the user instructions to start saving", 150, v); V(50);
- doc.fill("#000").fontSize("20").text("User Instructions", 20, v); V(30);
- for(var k in rooms){
- doc.fontSize(18).text("Room: ", 30, v); doc.fontSize(18).fill("#2E7D32").text(rooms[k].name, 90, v).fill("#000"); V(30);
- var lights = rooms[k].lights;
- for(var i in lights){
- doc.fontSize(14).text("Repalce - "+lights[i].name + " - with " + lights[i].replace.name , 40, v); V(20);
- }
- doc.strokeColor("#4CAF50").moveTo(40, v).lineTo(550,v).stroke() ; V(30);
- }
- footer();
- doc.end();
- doc.on('data', function (data) {
- //res.write(data);
- });
- doc.on('end', function(){
- var params = { Bucket: 'user-pdf', Body: fs.readFileSync(name), ACL: 'public-read', Key: "User-" + rand + ".pdf" };
- console.log("isId: ", isId);
- s3.upload(params, function(err, S3data) {
- console.log(err , S3data);
- is.ContactService.update(isId, {
- EmailAddress2: S3data.Location
- });
- callback();
- });
- });
- function V(i){
- if(i+v > 700 ){
- doc.rect(0,755,612,40).lineWidth(0).fill("#E0E0E0");
- doc.addPage();
- v = i;
- pages++;
- }
- v += i;
- }
- function footer(){
- doc.rect(0,755,612,40).lineWidth(0).fill("#E0E0E0");
- doc.fill("#000").text("All rights reserved © something 2016", 20 , 765);
- }
- };
- function vendorPdf(saving, rand, fullName, callback){
- var doc = new pdf({"margins" : { // by default, all are 72
- "top": 72,
- "bottom": 0,
- "left": 72,
- "right": 72
- }});
- var v = 0;
- var pages = 0;
- var name = "/tmp/Vendor-" + rand + ".pdf";
- doc.pipe(fs.createWriteStream(name));
- doc.rect(0,0,612,46).lineWidth(0).fill("#4CAF50");
- doc.fill("#fff");
- doc.text("DYI Lighting Saving", 20 ,20);
- doc.text(moment().format("MMM-DD-YYYY"), 470 ,20); V(80);
- //doc.fontSize(16).fill("#000").text("Client id: " + saving.user.isId || "" ,30 ,v); V(20);
- doc.fontSize(16).fill("#000").text("Transaction id: " + rand ,30 ,v); V(20);
- doc.fontSize(16).fill("#000").text("Full Name: " + fullName ,30 ,v); V(20);
- doc.fontSize(16).fill("#000").text("Products List", 30 ,v); V(30);
- for(var k in saving){
- var num = Number(k) +1;
- doc.fontSize(15).fill("#000").text("Box " +num, 30 ,v); V(20);
- doc.fontSize(14).fill("#000").text("# - Product Name - SK - Quantity", 30 ,v); V(20);
- for(var i in saving[k].arr){
- doc.fontSize(12).fill("#000").text(Number(i)+1 +" - " + saving[k].arr[i].replace.name + " - " + saving[k].arr[i].replace.sk + " - " + saving[k].arr[i].quatity, 30 ,v); V(20);
- }
- }
- doc.end();
- doc.on('data', function (data) {
- //res.write(data);
- });
- doc.on('end', function(){
- callback();
- //res.sendfile("out.pdf");
- });
- function V(i){
- if(i+v > 700 ){
- doc.rect(0,755,612,40).lineWidth(0).fill("#E0E0E0");
- doc.addPage();
- v = i;
- pages++;
- }
- v += i;
- }
- function footer(){
- doc.rect(0,755,612,40).lineWidth(0).fill("#E0E0E0");
- doc.fill("#000").text("All rights reserved © something 2016", 20 , 765);
- }
- }
- function recycle(rand, trans, user, lights, price, callback){
- var obj = {
- lights: [],
- rand: rand,
- transaction: trans,
- price: price,
- user: user
- };
- var arr = [];
- for(var k in lights){
- obj.lights.push({
- id: lights[k].option, // this is the reference to the option!!!!!
- price: lights[k].price / lights[k].quatity,
- quantity: lights[k].quatity,
- name: lights[k].name,
- spaceId: lights[k].space._id
- });
- Space.update({_id: lights[k].space._id}, {lock: true}, function(errLock, lock){
- console.log("Lock: " + lights[k].space._id);
- });
- }
- History(obj).save(function(err, history){
- console.log(err, history);
- });
- Light.remove({user: user}, function(err, docs){
- console.log("Remove lights from user after moving to history");
- console.log(err, docs);
- callback();
- });
- }
- function updateUserInIs(obj, isId){
- console.log(obj, isId);
- is.ContactService.update(isId, obj).done(function(results){
- console.log("Update Is: " + results);
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement