require('dotenv').config(); var express = require('express'); var bodyparser = require('body-parser'); var path = require('path'); const async = require('async'); const { sign } = require('jsonwebtoken'); const { checkToken } = require('../auth/token_validation'); var msg91_templateID="61d28c1778947f078d22b313"; var msg91_authkey="154257AQ8i7Tb161d288f4P1"; var devicee_access_check="sThis mobile number is register on another device please check"; const http = require("https"); var app = express(); var db= require('../lib/db'); const multer = require('multer'); const { monitorEventLoopDelay } = require('perf_hooks'); const { notEqual } = require('assert'); const { json } = require('body-parser'); app.use(bodyparser.json()); //mongo connect var MongoClients=require('mongodb').MongoClient; var url='mongodb://localhost:27017'; function listcalllog(userId,api,viewedId){ MongoClients.connect(url,function(err,mdb) { var dbmy=mdb.db('cma_api'); var mydata={userId: userId,api:api,date: Date(),viewedId:viewedId}; dbmy.collection('cmalog').insertOne(mydata,function(err,res){ mdb.close();}) }); } //1.getotp app.post('/getOtp',function(requ,res){ var mob =requ.body.mobile; var ccode =requ.body.countryCode; var mobwithccode = ccode + mob; let sql = "SELECT * FROM register WHERE mobile="+requ.body.mobile; let date_ob = new Date(); let date = ("0" + date_ob.getDate()).slice(-2); let month = ("0" + (date_ob.getMonth() + 1)).slice(-2); let year = date_ob.getFullYear(); let hours = date_ob.getHours(); let minutes = date_ob.getMinutes(); let seconds = date_ob.getSeconds(); var currentdatetime=year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds; let query = db.query(sql,(err, results) => { if(err) throw err if(results.length > 0 ){ const options = { "method": "GET", "hostname": "api.msg91.com", "port": null, "path": "/api/v5/otp?template_id="+msg91_templateID+"&mobile="+mobwithccode+"&authkey="+msg91_authkey+"&otp_length=6", "headers": { "Content-Type": "application/json" } }; const req = http.request(options, function (res) { const chunks = []; res.on("data", function (chunk) { chunks.push(chunk); }); res.on("end", function () { const body = Buffer.concat(chunks); console.log(body.toString()); }); }); req.write("{\"Value1\":\"Param1\",\"Value2\":\"Param2\",\"Value3\":\"Param3\"}"); req.end(); } else { let data= { mobile: requ.body.mobile, country_code:requ.body.countryCode, created:currentdatetime } let sqlin = "INSERT INTO register SET ?"; let query = db.query(sqlin,data,(err, results) => { if(err) throw err const options = { "method": "GET", "hostname": "api.msg91.com", "port": null, "path": "/api/v5/otp?template_id="+msg91_templateID+"&mobile="+mobwithccode+"&authkey="+msg91_authkey+"&otp_length=6", "headers": { "Content-Type": "application/json" } }; const req = http.request(options, function (res) { const chunks = []; res.on("data", function (chunk) { chunks.push(chunk); }); res.on("end", function () { const body = Buffer.concat(chunks); console.log(body.toString()); }); }); req.write("{\"Value1\":\"Param1\",\"Value2\":\"Param2\",\"Value3\":\"Param3\"}"); req.end(); }); } var responseMsg="OTP Sent to your Mobile Number"; var response_code="1"; res.send(JSON.stringify({ "code":response_code,"message":responseMsg})); }); }); //================================= //2.verifyotp app.post('/verifyOtp',function(requ,rese){ let bufferObjmob = Buffer.from(requ.body.mobile, "base64"); let mobile = bufferObjmob.toString("utf8"); let bufferObjotp = Buffer.from(requ.body.otp, "base64"); let otp = bufferObjotp.toString("utf8"); let sql = "SELECT * FROM register WHERE mobile="+mobile; let date_ob = new Date(); let date = ("0" + date_ob.getDate()).slice(-2); let month = ("0" + (date_ob.getMonth() + 1)).slice(-2); let year = date_ob.getFullYear(); let hours = date_ob.getHours(); let minutes = date_ob.getMinutes(); let seconds = date_ob.getSeconds(); var currentdatetime=year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds; let query = db.query(sql,(err, results) => { if(err) throw err if(results.length>0) { var userId=results[0]["id"]; var ccode=results[0]["country_code"]; var mobwithccode = ccode + mobile; const options = { "method": "GET", "hostname": "api.msg91.com", "port": null, "path": "/api/v5/otp/verify?authkey="+msg91_authkey+"&mobile="+mobwithccode+"&otp="+otp+"", "headers": {} }; const req = http.request(options, function (res) { const chunks = []; res.on("data", function (chunk) { chunks.push(chunk); }); res.on("end", function () { const body = Buffer.concat(chunks); var finalresult=body.toString(); var jsonParsedArray = JSON.parse(finalresult); var alertinfo=jsonParsedArray["message"]; var alerttype=jsonParsedArray["type"]; if(alerttype=="success"){ var sql = "UPDATE register SET mobile_verification ="+otp+" ,mobile_verify_status =1 ,device_type="+requ.body.deviceType+" ,device_token="+requ.body.deviceToken+",device_unique_id='"+requ.body.deviceId+"' WHERE id=" +userId; var response_code="2"; const jsonwebtoken= sign({mobile:requ.body.mobile,userId:userId,deviceId:requ.body.deviceId},process.env.JWT_SECRET_KEY); let query = db.query(sql,(err, result) => { if(err) throw err rese.send(JSON.stringify({ "code":response_code,"message":alertinfo,"userId": userId,"token":jsonwebtoken})); }); } else { var sql = "UPDATE register SET mobile_verification ="+otp+" WHERE id=" +userId; var response_code="3"; let query = db.query(sql,(err, result) => { if(err) throw err rese.send(JSON.stringify({ "code":response_code,"message":alertinfo,"userId": userId})); }); } }); }); req.write("{\"Value1\":\"Param1\",\"Value2\":\"Param2\",\"Value3\":\"Param3\"}"); req.end(); } }); }); //========================= //3.resend app.post('/resendOtp',function(requ,rese){ let sql = "SELECT * FROM register WHERE mobile="+requ.body.mobile; let date_ob = new Date(); let date = ("0" + date_ob.getDate()).slice(-2); let month = ("0" + (date_ob.getMonth() + 1)).slice(-2); let year = date_ob.getFullYear(); let hours = date_ob.getHours(); let minutes = date_ob.getMinutes(); let seconds = date_ob.getSeconds(); var currentdatetime=year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds; let query = db.query(sql,(err, results) => { if(err) throw err if(results.length > 0 ){ var userId=results[0]["id"]; var ccode=results[0]["country_code"]; var mobwithccode = ccode + requ.body.mobile; const options = { "method": "GET", "hostname": "api.msg91.com", "port": null, "path": "/api/v5/otp/retry?authkey="+msg91_authkey+"&retrytype=text&mobile="+mobwithccode+"", "headers": {} }; const req = http.request(options, function (res) { const chunks = []; res.on("data", function (chunk) { chunks.push(chunk); }); res.on("end", function () { const body = Buffer.concat(chunks); var finalresult=body.toString(); var jsonParsedArray = JSON.parse(finalresult); var alertinfo=jsonParsedArray["message"]; var alerttype=jsonParsedArray["type"]; var response_code="4"; rese.send(JSON.stringify({ "code":response_code,"message":alertinfo})); }); }); req.write("{\"Value1\":\"Param1\",\"Value2\":\"Param2\",\"Value3\":\"Param3\"}"); req.end(); } }); }); //================================= //4. List Plans app.get('/listPlans',checkToken,function(req,res){ let sql = "SELECT * FROM register WHERE id="+req.body.userId+" and device_unique_id='"+req.body.deviceId+"'"; let query = db.query(sql,(err, results) => { if(err) throw err if(results.length > 0 ){ var trialused=results[0]["trial_status"]; if(trialused=="0") { let sqlp = "SELECT * FROM plan WHERE status=1"; let query = db.query(sqlp,(err, results) => { var response_code="1"; var response_msg="Success"; if(err) throw err res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": results})); }); } else { let sqlp = "SELECT * FROM plan WHERE status=1 and user_type!=1"; //user_type 1->free,0->payment let query = db.query(sqlp,(err, results) => { var response_code="1"; var response_msg="Success"; if(err) throw err res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": results})); }); } } else { var response_code="2"; var response_msg=devicee_access_check; res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": ""})); } }); listcalllog(req.body.userId,'listPlans'); }); //======================== //5.subscribe plans app.post('/subscribePlans',checkToken,function(req,res){ let date_ob = new Date(); let date = ("0" + date_ob.getDate()).slice(-2); let month = ("0" + (date_ob.getMonth() + 1)).slice(-2); let year = date_ob.getFullYear(); let hours = date_ob.getHours(); let minutes = date_ob.getMinutes(); let seconds = date_ob.getSeconds(); let sql1 = "SELECT * FROM plan WHERE status=1"; let query = db.query(sql1,(err, resultss) => { if(err) throw err if(resultss.length > 0 ){ for(let n in resultss) { var numrow=resultss[n]; var days=numrow.days; var planId=numrow.id; var planName=numrow.name; var userType=numrow.user_type; //1-freeplan,2-payment var last = new Date(date_ob.getTime() + (days * 24 * 60 * 60 * 1000)); var eday =last.getDate(); var emonth=last.getMonth()+1; var eyear=last.getFullYear(); //plan start & end var currentdatetime=year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds; var plan_end_date=eyear + "-" + emonth + "-" + eday + " " + hours + ":" + minutes + ":" + seconds; var plid=req.body.planType; if(plid==planId) { if(userType=="1"){ var sql = "UPDATE register SET status=2, trial_status=1,plan_type ="+plid+" ,plan_start ='"+currentdatetime+"' , plan_end ='"+plan_end_date+"' WHERE mobile=" +req.body.mobile; } else { var sql = "UPDATE register SET status=2,plan_type ="+plid+" ,plan_start ='"+currentdatetime+"' , plan_end ='"+plan_end_date+"' WHERE mobile=" +req.body.mobile; } var response_code = "1"; var response_msg = ""+planName+" Subscribed Successfully"; let querys = db.query(sql,(err, resultss) => { if(err) throw err res.send(JSON.stringify({ "code":response_code,"message":response_msg,"planId":plid})); }); } } } }); listcalllog(req.body.userId,'subscribePlans'); }); //================== //6.News app.get('/listNews',checkToken,function(req,res){ let sql = "SELECT * FROM news WHERE status=1 ORDER BY id DESC"; let query = db.query(sql,(err, results) => { if(results.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": results})); }); listcalllog(req.body.userId,'listNews'); }); //======================= //7.categories app.get('/listCategories',checkToken,function(req,res){ let sql = "SELECT * FROM category WHERE status=1"; let query = db.query(sql,(err, results) => { var process=results; let finalresult=[]; async.eachSeries( process, (resulta,callback) => { var CID=resulta.id; let sql1 = "SELECT id FROM product WHERE category_id="+CID; db.query(sql1, (err, res) => { if(err) throw err; let sql2 = "SELECT DISTINCT mp.market_id as marketCount FROM product as p left join market_product as mp on mp.product_id=p.id WHERE category_id="+CID; db.query(sql2, (err, marCount) => { if(err) throw err; resulta.marketsCounts=marCount.length; }); resulta.varietiesCounts=res.length; let resultupdated=resulta; finalresult.push(resultupdated); callback(null,resultupdated); }); }, (err)=>{ if(err) throw err; var response_code="1"; var response_msg="success"; res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": finalresult})); }, ); }); listcalllog(req.body.userId,'listCategories'); }); //================================= //8.markets app.get('/listMarkets',checkToken,function(req,res){ let sql = "SELECT m.id,m.location,m.city,m.state,m.country,m.product_id,m.category_id,m.created,m.updated,m.status,m.created_by,m.name as marketName,ca.name as categoryName,c.name as cityName,cn.name as countryName,s.name as stateName FROM market as m LEFT JOIN cities as c ON c.id=m.city LEFT JOIN countries as cn ON cn.id=m.country LEFT JOIN states as s ON s.id=m.state LEFT JOIN category as ca on ca.id=m.category_id WHERE m.status=1"; let query = db.query(sql,(err, results) => { if(results.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": results})); }); listcalllog(req.body.userId,'listMarkets'); }); //==================== //9.Detailed category info app.get('/categoryDetail/:categoryId',checkToken,(req, res) => { let sql="SELECT * FROM product WHERE category_id="+req.params.categoryId+" and status=1" let query = db.query(sql, (err, resultss) => { if(err) throw err; if(resultss.length > 0 ){ var process=resultss; let finalresult=[]; async.eachSeries( process, (result,callback) => { var PID=result.id; let sql1 = "SELECT DISTINCT market_id as marketCount FROM market_product WHERE product_id="+PID; db.query(sql1, (err, marCount) => { var marketCounts=marCount.length; result.marketCounts=marketCounts; let resultupdated=result; finalresult.push(resultupdated); callback(null,resultupdated); }); }, (err)=>{ if(err) throw err; var response_code="1"; var response_msg="success"; res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": finalresult})); }, ); } else { var response_code="0"; var response_msg="No Data"; res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": finalresult})); } }); listcalllog(req.body.userId,'categoryDetail',req.params.categoryId); }); //========================== //10.Total items from market app.get('/totalItemFromMarket',checkToken,function(req,res){ let sql = "SELECT count(id)as marketItemCount FROM product_price WHERE created_date > DATE_SUB(NOW(), INTERVAL 1 WEEK) and status=1"; let query = db.query(sql,(err, results) => { if(results.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": results})); }); }); //========================== //8. Recent News app.get('/recentNewsCount',checkToken,function(req,res){ let sql = "SELECT count(id)as recentNews FROM news WHERE created_date > DATE_SUB(NOW(), INTERVAL 1 WEEK) and status=1"; let query = db.query(sql,(err, results) => { if(results.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": results})); }); }); //========================== //11. statewise product with price using product id app.get('/statewiseProduct/:productId',checkToken,function(req,res){ let sql = "SELECT DISTINCT s.name as stateName, s.id FROM market as m inner join states as s on s.id=m.state where m.status=1"; let query = db.query(sql, (err, resultss) => { if(err) throw err; var process=resultss; let finalresult=[]; async.eachSeries( process, (result,callback) => { var SID=result.id; let sql1 = "SELECT pp.created_date,m.name as marketName,pp.price,pp.units,me.name as measurement from product_price as pp left join market as m on m.id=pp.market_id left join product as p on p.id=pp.product_id left join measurement as me on me.id=pp.measurement WHERE m.state="+SID+" and pp.status=1 and pp.product_id="+req.params.productId; db.query(sql1, (err, priceinfo) => { if(err) throw err; result.priceinfo=priceinfo; let resultupdated=result; finalresult.push(resultupdated); callback(null,resultupdated); }); }, (err)=>{ if(err) throw err; res.send(JSON.stringify({"code":"1","message":"success","data": finalresult})); }, ); }); }); //============================== //12.News category app.get('/listNewsCategory',checkToken,function(req,res){ let sql = "SELECT * FROM news_category WHERE status=1 ORDER BY id DESC"; let query = db.query(sql,(err, resultss) => { if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); listcalllog(req.body.userId,'listNewsCategory'); }); //========================== //13.This week filter app.get('/thisweekNews',checkToken,function(req,res){ let sql = "SELECT * FROM news WHERE created_date > DATE_SUB(NOW(), INTERVAL 1 WEEK) and status=1"; let query = db.query(sql,(err, resultss) => { if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); }); //================================== //14.next week filter app.get('/nextweekNews',checkToken,function(req,res){ let sql = "SELECT * FROM news WHERE created_date >= DATE_ADD(NOW(), INTERVAL 1 WEEK) and status=1"; let query = db.query(sql,(err, resultss) => { if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); }); //========================== //15.last month filter app.get('/lastmonthNews',checkToken,function(req,res){ let sql = "SELECT * FROM news WHERE YEAR(created_date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(created_date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH) and status=1"; let query = db.query(sql,(err, resultss) => { if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); }); //================= //16.custom range filter app.get('/customrangeNews/:startDate/:endDate',checkToken,function(req,res){ let sql = "select * from news where created_date between '"+req.params.startDate+"' and '"+req.params.endDate+"' and status=1"; let query = db.query(sql,(err, resultss) => { if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); }); //============== //17.particular news category app.get('/listNewsCategory/:newsCatId',checkToken,function(req,res){ let sql = "SELECT * FROM news where categories="+req.params.newsCatId+" and status=1"; let query = db.query(sql,(err, resultss) => { if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); listcalllog(req.body.userId,'listNewsCategory',req.params.newsCatId); }); //======================= //18.particular news details app.get('/listNews/:newsId',checkToken,function(req,res){ let sql = "SELECT * FROM news where id="+req.params.newsId+" and status=1"; let query = db.query(sql,(err, resultss) => { if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); listcalllog(req.body.userId,'listNews',req.params.newsId); }); //====================== //19.price graph using productid & marketid app.get('/weeklyPriceGraph/:marketId/:productId',checkToken,function(req,res){ let sql = "SELECT * FROM product_price where created_date >= DATE_SUB(NOW(), INTERVAL 1 WEEK) and product_id="+req.params.productId+" AND market_id="+req.params.marketId+" and status=1"; let query = db.query(sql,(err, resultss) => { if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); }); //================= //20.price graph using productid & marketid //lastmonth app.get('/monthlyPriceGraph/:marketId/:productId',checkToken,function(req,res){ let sql = "SELECT * FROM product_price where YEAR(created_date) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(created_date) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH) and product_id="+req.params.productId+" AND market_id="+req.params.marketId+" and status=1"; let query = db.query(sql,(err, resultss) => { if(err) throw err if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); }); //===================== //21.price graph using productid & marketid==>pending app.get('/statewisePriceGraph/:stateId/:productId',checkToken,function(req,res){ let sql = "SELECT pp.*,m.name as marketName FROM product_price as pp left join market as m on m.id=pp.market_id where pp.product_id="+req.params.productId+" AND m.state="+req.params.stateId+" and pp.status=1"; let query = db.query(sql,(err, results) => { if(results.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": results})); }); }); //============================== //22.show user profile app.get('/viewUserProfile',checkToken,function(req,res){ let sql = "SELECT pc.id as locationId,pc.pincode,pc.region,pc.taluk,pc.district,pc.state,r.*,p.name as planName FROM register as r inner join plan as p on p.id=r.plan_type left join pincodes as pc on pc.id=r.location where r.id="+req.body.userId+""; let query = db.query(sql,(err, resultss) => { if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); }); //================= //23.edit user profile app.get('/editUserProfile',checkToken,function(req,res){ var data={ name:req.body.fullName, location:req.body.location, email:req.body.email } let sql = "UPDATE register SET ? WHERE id=" +req.body.userId; let query = db.query(sql,data,(err, resultss) => { if(err) throw err var response_code="1"; var response_msg="Updated Successfully"; res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); }); //================ //24.get location by using pincode app.get('/getLocByPincode',checkToken,function(req,res){ let sql = "SELECT * FROM pincodes WHERE pincode like '"+req.body.pincode+"%'"; let query = db.query(sql,(err, resultss) => { if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); }); //================ //25.get location by using region app.get('/getLocByRegion',checkToken,function(req,res){ let sql = "SELECT * FROM pincodes WHERE region like '"+req.body.region+"%'"; console.log(sql); let query = db.query(sql,(err, resultss) => { if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); }); //================ //=========================================================== //************BUY & SELL***************************************** */ //============================================================= //=========BUY========== //1.list all seller product category to buyer screeen app.get('/buysellCategory',checkToken,function(req,res){ let sql = "SELECT * FROM buysell_category WHERE status=1"; let query = db.query(sql,(err, resultss) => { if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); }); //=================================== //2.list all seller products to buyer screeen app.get('/buyProducts',checkToken,function(req,res){ let sql = "SELECT sp.*,bsc.name as categoryname,bspm.name as productname,bspm.image,m.name as unitname,p.region as areaname FROM seller_products as sp left join buysell_category as bsc on bsc.id=sp.cat_id left join buysell_product_master as bspm on bspm.id=sp.product left join measurement as m on m.id=sp.unit left join pincodes as p on p.id=sp.area WHERE sp.status=1"; let query = db.query(sql,(err, results) => { if (err) throw err; if(results.length>0) { var finalresult=[]; async.eachSeries(results,(finres,callback)=> { var unitname=finres.unitname; var uniprice_per_unittname=finres.price_per_unit; var singleprice=uniprice_per_unittname+"/"+unitname; finres.singleprice=singleprice; let resultupdated=finres; finalresult.push(resultupdated); callback(null,resultupdated); }, (err)=>{ if(err) throw err; res.send(JSON.stringify({"code":"1","message":"success","data": finalresult})); } ); } else { res.send(JSON.stringify({"code":"0","message":"No data"})); } }); }); //==================== //3.list particular seller products to buyer screeen app.get('/buyProducts/:categoryId',checkToken,function(req,res){ let sql = "SELECT sp.*,bsc.name as categoryname,bspm.name as productname,bspm.image,m.name as unitname,p.region as areaname FROM seller_products as sp left join buysell_category as bsc on bsc.id=sp.cat_id left join buysell_product_master as bspm on bspm.id=sp.product left join measurement as m on m.id=sp.unit left join pincodes as p on p.id=sp.area WHERE sp.status=1 and sp.cat_id="+req.params.categoryId; let query = db.query(sql,(err, results) => { if (err) throw err; if(results.length>0) { var finalresult=[]; async.eachSeries(results,(finres,callback)=> { var unitname=finres.unitname; var uniprice_per_unittname=finres.price_per_unit; var singleprice=uniprice_per_unittname+"/"+unitname; finres.singleprice=singleprice; let resultupdated=finres; finalresult.push(resultupdated); callback(null,resultupdated); }, (err)=>{ if(err) throw err; res.send(JSON.stringify({"code":"1","message":"success","data": finalresult})); } ); } else { res.send(JSON.stringify({"code":"0","message":"No data"})); } }); }); //================== //4.buy filters app.get('/buyFilter',checkToken,function(req,res){ let sql = "SELECT sp.*,bsc.name as categoryname,bspm.name as productname,bspm.image,m.name as unitname,p.region as areaname FROM seller_products as sp left join buysell_category as bsc on bsc.id=sp.cat_id left join buysell_product_master as bspm on bspm.id=sp.product left join measurement as m on m.id=sp.unit left join pincodes as p on p.id=sp.area WHERE sp.status=1 and sp.product="+req.body.productId+" and sp.area="+req.body.area+" and sp.qty >= "+req.body.qtyFrom+" AND sp.qty <= "+req.body.qtyTo+" and sp.price_per_unit >= "+req.body.priceFrom+" AND sp.price_per_unit <= "+req.body.priceTo; let query = db.query(sql,(err, results) => { if (err) throw err; if(results.length>0) { var finalresult=[]; async.eachSeries(results,(finres,callback)=> { var unitname=finres.unitname; var uniprice_per_unittname=finres.price_per_unit; var singleprice=uniprice_per_unittname+"/"+unitname; finres.singleprice=singleprice; let resultupdated=finres; finalresult.push(resultupdated); callback(null,resultupdated); }, (err)=>{ if(err) throw err; res.send(JSON.stringify({"code":"1","message":"success","data": finalresult})); } ); } else { res.send(JSON.stringify({"code":"0","message":"No data"})); } }); }); //======================== //5.view particular product to buyer app.get('/viewbuyProduct/:bPPrimaryId',checkToken,function(req,res){ let sql = "SELECT sp.*,p.region as location,bspm.name as productname,bspm.image,m.name as unitname,r.name as sellername FROM seller_products as sp left join buysell_product_master as bspm on bspm.id=sp.product left join measurement as m on m.id=sp.unit left join register as r on r.id=sp.seller left join pincodes as p on p.id=sp.area WHERE sp.status=1 and sp.id="+req.params.bPPrimaryId; let query = db.query(sql,(err, resultss) => { if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); }); //================= //6.view particular product images app.get('/viewProductImages/:bPPrimaryId',checkToken,function(req,res){ let sql = "SELECT image from seller_product_images where status=1 and seller_product_primary_id="+req.params.bPPrimaryId; let query = db.query(sql,(err, resultss) => { if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); }); //========================= //7.add buyer products app.post('/buyerRequestProduct',checkToken,function(req,res){ let data= { buyer:req.body.sessionid, cat_id: req.body.categoryId, product:req.body.productId, qty:req.body.qty, unit:req.body.unitId, price_per_unit:req.body.pricePerUnit, area:req.body.area, valid_date:req.body.validDate, about_product:req.body.about, status:1, created_by:req.body.sessionid } let sql = "INSERT INTO buyer_products SET ?"; let query = db.query(sql,data,(err, results) => { if(err) throw err res.send(JSON.stringify({ "code":"1","message":"success","data": results})); }); }); //=================== //8.myrequest Page for buyer app.get('/myRequest/:userId',checkToken,function(req,res){ let sql = "SELECT bp.*,bsc.name as categoryname,bspm.name as productname,bspm.image,m.name as unitname,p.region as areaname FROM buyer_products as bp left join buysell_category as bsc on bsc.id=bp.cat_id left join buysell_product_master as bspm on bspm.id=bp.product left join measurement as m on m.id=bp.unit left join pincodes as p on p.id=bp.area WHERE bp.status!=0 and bp.buyer="+req.params.userId; let query = db.query(sql,(err, results) => { if (err) throw err; if(results.length>0) { var finalresult=[]; async.eachSeries(results,(finres,callback)=> { var unitname=finres.unitname; var uniprice_per_unittname=finres.price_per_unit; var pro_status=finres.status; if(pro_status=="1"){ var productStatus="Requested";} if(pro_status=="2"){ var productStatus="Completed";} if(pro_status=="3"){ var productStatus="Expired";} var singleprice=uniprice_per_unittname+"/"+unitname; finres.singleprice=singleprice; finres.productStatus=productStatus; let resultupdated=finres; finalresult.push(resultupdated); callback(null,resultupdated); }, (err)=>{ if(err) throw err; res.send(JSON.stringify({"code":"1","message":"success","data": finalresult})); } ); } else { res.send(JSON.stringify({"code":"0","message":"No data"})); } }); }); //================= //9.change completed and deleted app.put('/changeRequest/:bPPrimaryId',checkToken,function(req,res){ let data = { status:req.body.status} let sql = "UPDATE buyer_products SET ? WHERE id="+req.params.bPPrimaryId+""; let query = db.query(sql,data, (err, results) => { if(err) throw err; if(req.body.status=="0") { var message="Deleted successfully"; } if(req.body.status=="2") { var message="Updated successfully"; } res.send(JSON.stringify({ "code":"1","message":message})); }); }); //================= //10.edit myrequest app.put('/editRequest/:bPPrimaryId',checkToken,function(req,res){ let data = { qty:req.body.qty, unit:req.body.unitId, price_per_unit:req.body.pricePerUnit, area:req.body.area, about_product:req.body.about } let sql = "UPDATE buyer_products SET ? WHERE id="+req.params.bPPrimaryId+""; let query = db.query(sql,data, (err, results) => { if(err) throw err; res.send(JSON.stringify({ "code":"1","message":"Updated successfully"})); }); }); //===================== //=========SELL======================== //1.list all buyer products to seller screeen app.get('/sellProducts',checkToken,function(req,res){ let sql = "SELECT bp.*,bsc.name as categoryname,bspm.name as productname,bspm.image,m.name as unitname,p.region as areaname FROM buyer_products as bp left join buysell_category as bsc on bsc.id=bp.cat_id left join buysell_product_master as bspm on bspm.id=bp.product left join measurement as m on m.id=bp.unit left join pincodes as p on p.id=bp.area WHERE bp.status=1"; let query = db.query(sql,(err, results) => { if (err) throw err; if(results.length>0) { var finalresult=[]; async.eachSeries(results,(finres,callback)=> { var unitname=finres.unitname; var uniprice_per_unittname=finres.price_per_unit; var singleprice=uniprice_per_unittname+"/"+unitname; finres.singleprice=singleprice; let resultupdated=finres; finalresult.push(resultupdated); callback(null,resultupdated); }, (err)=>{ if(err) throw err; res.send(JSON.stringify({"code":"1","message":"success","data": finalresult})); } ); } else { res.send(JSON.stringify({"code":"0","message":"No data"})); } }); }); //======================== //2.get particular buyer products to seller screeen app.get('/sellProducts/:categoryId',checkToken,function(req,res){ let sql = "SELECT bp.*,bsc.name as categoryname,bspm.name as productname,bspm.image,m.name as unitname,p.region as areaname FROM buyer_products as bp left join buysell_category as bsc on bsc.id=bp.cat_id left join buysell_product_master as bspm on bspm.id=bp.product left join measurement as m on m.id=bp.unit left join pincodes as p on p.id=bp.area WHERE bp.status=1 and bp.cat_id="+req.params.categoryId; let query = db.query(sql,(err, results) => { if (err) throw err; if(results.length>0) { var finalresult=[]; async.eachSeries(results,(finres,callback)=> { var unitname=finres.unitname; var uniprice_per_unittname=finres.price_per_unit; var singleprice=uniprice_per_unittname+"/"+unitname; finres.singleprice=singleprice; let resultupdated=finres; finalresult.push(resultupdated); callback(null,resultupdated); }, (err)=>{ if(err) throw err; res.send(JSON.stringify({"code":"1","message":"success","data": finalresult})); } ); } else { res.send(JSON.stringify({"code":"0","message":"No data"})); } }); }); //================== //3.sell filters app.get('/sellFilter',checkToken,function(req,res){ let sql = "SELECT bp.*,bsc.name as categoryname,bspm.name as productname,bspm.image,m.name as unitname,p.region as areaname FROM buyer_products as bp left join buysell_category as bsc on bsc.id=bp.cat_id left join buysell_product_master as bspm on bspm.id=bp.product left join measurement as m on m.id=bp.unit left join pincodes as p on p.id=bp.area WHERE bp.status=1 and bp.product="+req.body.productId+" and bp.area="+req.body.area+" and bp.qty >= "+req.body.qtyFrom+" AND bp.qty <= "+req.body.qtyTo+" and bp.price_per_unit >= "+req.body.priceFrom+" AND bp.price_per_unit <= "+req.body.priceTo; let query = db.query(sql,(err, results) => { if (err) throw err; if(results.length>0) { var finalresult=[]; async.eachSeries(results,(finres,callback)=> { var unitname=finres.unitname; var uniprice_per_unittname=finres.price_per_unit; var singleprice=uniprice_per_unittname+"/"+unitname; finres.singleprice=singleprice; let resultupdated=finres; finalresult.push(resultupdated); callback(null,resultupdated); }, (err)=>{ if(err) throw err; res.send(JSON.stringify({"code":"1","message":"success","data": finalresult})); } ); } else { res.send(JSON.stringify({"code":"0","message":"No data"})); } }); }); //======================== //4.view particular product to seller app.get('/viewsellProduct/:bPPrimaryId',checkToken,function(req,res){ let sql = "SELECT bp.*,p.region as location,bspm.name as productname,bspm.image,m.name as unitname,r.name as sellername FROM buyer_products as bp left join buysell_product_master as bspm on bspm.id=bp.product left join measurement as m on m.id=bp.unit left join register as r on r.id=bp.buyer left join pincodes as p on p.id=bp.area WHERE bp.status=1 and bp.id="+req.params.bPPrimaryId; let query = db.query(sql,(err, resultss) => { console.log(sql); if(resultss.length > 0 ){ var response_code="1"; var response_msg="Success"; } else { var response_code="0"; var response_msg="No Data"; } res.send(JSON.stringify({ "code":response_code,"message":response_msg,"data": resultss})); }); }); //================= //5.add seller products app.post('/sellerRequestProduct',checkToken,function(req,res){ let data= { seller:req.body.sessionid, cat_id: req.body.categoryId, product:req.body.productId, qty:req.body.qty, unit:req.body.unitId, price_per_unit:req.body.pricePerUnit, area:req.body.area, valid_date:req.body.validDate, about_product:req.body.about, status:1, created_by:req.body.sessionid } let sql = "INSERT INTO seller_products SET ?"; let query = db.query(sql,data,(err, results) => { if(err) throw err res.send(JSON.stringify({ "code":"1","message":"success","data": results})); }); }); const filestorageengines=multer.diskStorage({ destination:(req,file,cb)=>{ cb(null,"./uploads"); }, filename: (req,file,cb)=> { cb(null,"pr-"+Date.now()+ path.extname(file.originalname)); } }); const uploaded=multer({ storage:filestorageengines }); app.post('/insertImages/:primaryId',uploaded.array('productImages'),function(req,res){ req.files.forEach(function(value, key) { let data= { seller_product_primary_id:req.params.primaryId, status: 1, created_by: req.body.sessionid, image: value.filename } let sql = "INSERT INTO seller_product_images SET ?"; let query = db.query(sql,data,(err, results) => { if(err) throw err res.send(JSON.stringify({ "code":"1","message":"success","data": results})); }); }) }); //====================== //6.myrequest Page for seller app.get('/myRequestSeller/:userId',checkToken,function(req,res){ let sql = "SELECT sp.*,bsc.name as categoryname,bspm.name as productname,bspm.image,m.name as unitname,p.region as areaname FROM seller_products as sp left join buysell_category as bsc on bsc.id=sp.cat_id left join buysell_product_master as bspm on bspm.id=sp.product left join measurement as m on m.id=sp.unit left join pincodes as p on p.id=sp.area WHERE sp.status!=0 and sp.seller="+req.params.userId; let query = db.query(sql,(err, results) => { if (err) throw err; if(results.length>0) { var finalresult=[]; async.eachSeries(results,(finres,callback)=> { var unitname=finres.unitname; var uniprice_per_unittname=finres.price_per_unit; var pro_status=finres.status; if(pro_status=="1"){ var productStatus="Requested";} if(pro_status=="2"){ var productStatus="Completed";} if(pro_status=="3"){ var productStatus="Expired";} var singleprice=uniprice_per_unittname+"/"+unitname; finres.singleprice=singleprice; finres.productStatus=productStatus; let resultupdated=finres; finalresult.push(resultupdated); callback(null,resultupdated); }, (err)=>{ if(err) throw err; res.send(JSON.stringify({"code":"1","message":"success","data": finalresult})); } ); } else { res.send(JSON.stringify({"code":"0","message":"No data"})); } }); }); //================= //7.change completed and deleted for seller app.put('/changeRequestSeller/:bPPrimaryId',checkToken,function(req,res){ let data = { status:req.body.status} let sql = "UPDATE seller_products SET ? WHERE id="+req.params.bPPrimaryId+""; let query = db.query(sql,data, (err, results) => { if(err) throw err; if(req.body.status=="0") { var message="Deleted successfully"; } if(req.body.status=="2") { var message="Updated successfully"; } res.send(JSON.stringify({ "code":"1","message":message})); }); }); //================= //8.edit myrequest app.put('/editRequestSeller/:bPPrimaryId',checkToken,function(req,res){ let data = { qty:req.body.qty, unit:req.body.unitId, price_per_unit:req.body.pricePerUnit, area:req.body.area, about_product:req.body.about } let sql = "UPDATE seller_products SET ? WHERE id="+req.params.bPPrimaryId+""; let query = db.query(sql,data, (err, results) => { if(err) throw err; res.send(JSON.stringify({ "code":"1","message":"Updated successfully"})); }); }); //===================== //=========================================================== //************API END***************************************** */ //============================================================= //================================================================================================== //| | //| API CRUD FOR CATEGORY | //| | //================================================================================================== //====================================== //upload image const filestorageengine=multer.diskStorage({ destination:(req,file,cb)=>{ cb(null,"./uploads"); }, filename: (req,file,cb)=> { console.log(file); cb(null,"ca-"+Date.now()+ path.extname(file.originalname)); } }); const upload=multer({ storage:filestorageengine }); //2.Create all categories app.post('/insertCategories',upload.single('categoryImages'),function(req,res){ let data= { name: req.body.categoryName, description:req.body.categoryDescription, status:req.body.categoryStatus, added_date:Date.now(), created_by:req.body.sessionid, image:req.file.filename } let sql = "INSERT INTO category SET ?"; let query = db.query(sql,data,(err, results) => { if(err) throw err res.send(JSON.stringify({ "data": results})); }); }); //=========================================== //3.Detailed category info app.get('/showCategories/:categoryId',(req, res) => { let sql = "SELECT * FROM category WHERE id="+req.params.categoryId; let query = db.query(sql, (err, results) => { if(err) throw err; res.send(JSON.stringify({ "data": results})); }); }); //=========================================== //4.Update category info //upload image const filestorageEngine=multer.diskStorage({ destination:(req,file,cb)=>{ cb(null,"./uploads"); }, filename: (req,file,cb)=> { cb(null,"ca-"+Date.now()+ path.extname(file.originalname)); } }); const uploads=multer({ storage:filestorageEngine }); app.put('/updateCategories/(:categoryId)',uploads.single('categoryImages'),function(req,res){ let new_image=""; if(req.file){ new_image=req.file.filename; } let data = { name: req.body.categoryName, description:req.body.categoryDescription, status:req.body.categoryStatus, added_date:Date.now(), created_by:req.body.sessionid, image:new_image }; let sql = "UPDATE category SET ? WHERE id=" +req.params.categoryId; let query = db.query(sql,data,(err, results) => { if(err) throw err res.send(JSON.stringify({ "data": results})); }); }); //============================================================= //5.Delete category app.put('/deleteCategories/:categoryId',(req, res) => { let data = { status:0 }; let sql = "UPDATE category SET ? WHERE id="+req.params.categoryId+""; let query = db.query(sql,data, (err, results) => { if(err) throw err; res.send(JSON.stringify({ "data": results})); }); }); //=============================================================== //================================================================================================== //| | //| API CRUD FOR Markets | //| | //================================================================================================== //1.List Markets //=============================================== //2.Create all markets app.post('/insertMarkets',function(reqs, res) { let datas = { name: reqs.body.marketName, location: reqs.body.marketLocation, city: reqs.body.marketCity, state: reqs.body.marketState, country: reqs.body.marketCountry, category_id: reqs.body.marketCategory_id, created: Date.now(), status: reqs.body.marketStatus, created_by: reqs.body.marketCreated_by }; let sql = "INSERT INTO market SET ?"; let query = db.query(sql, datas,(err, results) => { if(err) throw err; res.send(JSON.stringify({ "data": results})); }); }); //================================================================== //3.Detailed market info app.get('/showMarkets/:marketId',function(req, res) { let sql = "SELECT m.id,m.location,m.city,m.state,m.country,m.product_id,m.category_id,m.created,m.updated,m.status,m.created_by,m.name as marketName,ca.name as categoryName,c.name as cityName,cn.name as countryName,s.name as stateName FROM market as m LEFT JOIN cities as c ON c.id=m.city LEFT JOIN countries as cn ON cn.id=m.country LEFT JOIN states as s ON s.id=m.state LEFT JOIN category as ca on ca.id=m.category_id WHERE m.status=1 AND m.id="+req.params.marketId; let query = db.query(sql, (err, results) => { if(err) throw err; res.send(JSON.stringify({ "data": results})); }); }); //====================================================================== //4.Update market info app.put('/updatemarkets/(:marketId)',function(req,res){ let datas = { name: req.body.marketName, location: req.body.marketLocation, city: req.body.marketCity, state: req.body.marketState, country: req.body.marketCountry, category_id: req.body.marketCategory_id, created: Date.now(), status: req.body.marketStatus, created_by: req.body.marketCreated_by }; let sql = "UPDATE market SET ? WHERE id=" +req.params.marketId; let query = db.query(sql,datas,(err, results) => { if(err) throw err res.send(JSON.stringify({ "data": results})); }); }); //========================================================= //5.Delete market app.put('/deletemarkets/:markerId',(req, res) => { let data = { status:0 }; let sql = "UPDATE market SET ? WHERE id="+req.params.markerId+""; let query = db.query(sql,data, (err, results) => { if(err) throw err; res.send(JSON.stringify({ "data": results})); }); }); //========================================================== //================================================================================================== //| | //| API CRUD FOR Plans | //| | //================================================================================================== //================================================ //2. Create all plans app.post('/insertPlans',function(reqs, res) { let datas = { name: reqs.body.planName, user_type: reqs.body.planUser_type, amount: reqs.body.planAmount, days: reqs.body.planDays, advertisement: reqs.body.planAdvertisement, description: reqs.body.planDescription, employee_id: reqs.body.planEmployee_id, status: reqs.body.planStatus, create_date: Date.now() }; let sql = "INSERT INTO plan SET ?"; let query = db.query(sql, datas,(err, results) => { if(err) throw err; res.send(JSON.stringify({ "data": results})); }); }); //================================================================== //3.Detailed plan info app.get('/showPlans/:planId',function(req, res) { let sql = "SELECT * FROM plan WHERE status=1 AND id="+req.params.planId; let query = db.query(sql, (err, results) => { if(err) throw err; res.send(JSON.stringify({ "data": results})); }); }); //====================================================================== //4.Update plan info app.put('/updatePlans/(:planId)',function(reqs,res){ let datas = { name: reqs.body.planName, user_type: reqs.body.planUser_type, amount: reqs.body.planAmount, days: reqs.body.planDays, advertisement: reqs.body.planAdvertisement, description: reqs.body.planDescription, employee_id: reqs.body.planEmployee_id, status: reqs.body.planStatus, create_date: Date.now() }; let sql = "UPDATE plan SET ? WHERE id=" +reqs.params.planId; let query = db.query(sql,datas,(err, results) => { if(err) throw err res.send(JSON.stringify({ "data": results})); }); }); //========================================================= //5.Delete plan app.put('/deletePlans/:planId',(req, res) => { let data = { status:0 }; let sql = "UPDATE plan SET ? WHERE id="+req.params.planId+""; let query = db.query(sql,data, (err, results) => { if(err) throw err; res.send(JSON.stringify({ "data": results})); }); }); //========================================================== //================================================================================================== //| | //| API CRUD FOR cities | //| | //================================================================================================== //1. List cities app.get('/getCities',function(req,res){ let sql = "SELECT * FROM cities"; let query = db.query(sql,(err, results) => { if(err) throw err res.send(JSON.stringify({ "data": results})); }); }); //=============================== //================================================================================================== //| | //| API CRUD FOR country | //| | //================================================================================================== //1. List country app.get('/getCountries',function(req,res){ let sql = "SELECT * FROM countries"; let query = db.query(sql,(err, results) => { if(err) throw err res.send(JSON.stringify({ "data": results})); }); }); //=============================== //================================================================================================== //| | //| API CRUD FOR state | //| | //================================================================================================== //1. List state app.get('/getStates',function(req,res){ let sql = "SELECT s.*,c.name as countryName FROM states as s LEFT JOIN countries as c on c.id=s.country_id"; let query = db.query(sql,(err, results) => { if(err) throw err res.send(JSON.stringify({ "data": results})); }); }); //=============================== //================================================================================================== //| | //| API CRUD FOR measurements | //| | //================================================================================================== //1. List measurements app.get('/getMeasurements',function(req,res){ let sql = "SELECT * FROM measurement WHERE status=1"; let query = db.query(sql,(err, results) => { if(err) throw err res.send(JSON.stringify({ "data": results})); }); }); //================================================================================================== //| | //| API CRUD FOR role | //| | //================================================================================================== //1. List role app.get('/getRoles',function(req,res){ let sql = "SELECT * FROM role WHERE role_status=1"; let query = db.query(sql,(err, results) => { if(err) throw err res.send(JSON.stringify({ "data": results})); }); }); app.listen(process.env.PORT,()=>{console.log(process.env.PORT);}); module.exports = app;