/** * * User: Martin Donnelly * Date: 2016-03-15 * Time: 14:04 * */ 'use strict'; var $V = require('node-validator'); var mdErrors = require('./md-errors'); var newId = require('uuid-pure').newId; var $U = require('md-utils'); module.exports = function(db) { var module = {}; module.sqlInsertCompany = function(data) { return new Promise(function(resolve, reject) { db.proc('upsert_company',data) .then(()=> { console.log('+sqlInsertCompany OK'); return resolve('ok'); }) .catch((err)=> { console.log('+sqlInsertCompany failed'); console.log(err); return reject(err); }); }); }; module.sqlGetSimpleCompany = function(id) { return new Promise(function(resolve, reject) { //db.oneOrNone('select *, company_name company-name from company where cid=$1;', [id]) db.oneOrNone('select company.* from company where cid=$1;', [id]) .then(function(d) { console.log(d); return resolve(d); }) .catch((err)=> { console.log(err); return reject(err); }); }); }; module.addNewCompany = function(data) { return new Promise((resolve, reject) => { let _data; _data = $U.cloneTrim(data); _data = $U.sanitiseObj(_data, {company_name: true, address1: true, address2: true, address3: true, town: false, county: false, pcontact: true, ocontact: true,mobile: true}); if (_data.hasOwnProperty('company_name') && (_data.company_name.length === 0)) { return reject(mdErrors.error(1100)); } if ([ _data.address1, _data.address2, _data.address3 ].join('').trim().length === 0) { return reject(mdErrors.error(1101)); } if ([_data.town, _data.county].join('').trim().length === 0) { return reject(mdErrors.error(1102)); } var pcv = $V.checkPostCode(_data.postcode); if (pcv === '') { return reject(mdErrors.error(1103)); } else { _data.postcode = pcv; } _data.pcontact = $V.validatePhone(_data.pcontact); _data.ocontact = $V.validatePhone(_data.ocontact); _data.mobile = $V.validatePhone(_data.mobile); if ([ _data.pcontact, _data.ocontact, _data.mobile ].join('').trim().length === 0) { return reject(mdErrors.error(1104)); } if (_data.email.length === 0 || !$V.Email(_data.email)) { return reject(mdErrors.error(1105)); } if (typeof _data.cid === 'undefined' || _data.cid === null) { _data.cid = newId(); } const sqlData = [_data.cid, _data.company_name, _data.address1, _data.address2, _data.address3, _data.town, _data.county, _data.postcode, _data.country, _data.pcontact, _data.ocontact, _data.mobile, _data.email]; this.sqlInsertCompany(sqlData) .then(function(d) { console.log('Inserted'); console.log(d); return resolve({cid: _data.cid}); }) .catch(function(err) { console.log('Failed to insert'); return reject(err); }); }); }; return module; };