123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716 |
- /**
- * Created by PC on 2018/5/29.
- */
- var express = require('express');
- var router = express.Router();
- var bodyParser = require('body-parser');
- var http=require("http");
- var async = require("async");
- var moment=require("moment");
- var sixtytwo = require('sixtytwo');
- var take=require("../models/T_token");
- var public=require("../common/public");
- var logs=require("../models/logs");
- var uploadLogs=require("../models/uploadLogs");
- var status=require("../models/t_status");
- // var processWarehouse=require("../models/t_processWarehouse");
- const random = require('random')
- var marketAnalysis=require("../models/t_marketAnalysis");
- var businessInfo=require("../models/t_businessInfo");
- var corporation = require("../models/t_corporation");
- router.use(bodyParser.json()); // for parsing application/json
- router.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
- var error = require("../models/error");
- // var public = require("../common/public");
- //公用修改单条数据方法
- function update(query,change,model,callback) {
- model.updateOne(query, {"$set": change}, function (err, doc) {
- if (err) {
- callback(error.validator('tips')[2]);//数据库链接失败
- // console.log(err)
- return;
- } else if (doc.n == 1 && doc.ok == 1) {//成功
- callback(error.operation('tips')[1]);
- return;
- } else {
- callback(error.operation('tips')[0]);
- return;
- }
- });
- }
- //公用修改多条数据方法
- function updateMore(query,change,model,callback) {
- model.updateMany(query, {"$set": change}, function (err, doc) {
- if (err) {
- callback(error.validator('tips')[2]);//数据库链接失败
- return;
- } else if (doc.n > 0 ) {//成功
- callback(error.operation('tips')[1]);
- return;
- } else {
- callback(error.operation('tips')[1]);
- return;
- }
- });
- }
- //公用查询方法,分页返回总数
- function search(num,page,screen,query,queryOr,sortKey,model,callback) {
- async.parallel({
- list:function (back) {
- model.find(query,screen)
- .skip(num*(page-1))
- .limit(num)
- .or(queryOr)
- .sort(sortKey)
- .exec(function (err,doc) {
- if(err){
- callback(error.operation('tips')[2]);
- return;
- }else{
- back(null,doc)
- }
- });
- },
- count:function (back) {
- // model.count(query)
- model.countDocuments(query)
- .or(queryOr)
- .exec(function (err,docs) {
- if (err){
- console.log(err);
- callback(error.operation('tips')[2]);
- return;
- }else {
- back(null,docs);
- }
- })
- }
- },function (errs,result) {
- if(errs){
- callback(error.operation('tips')[2]);
- return;
- }else {
- var back = public.setJson(error.operation('tips')[3],"count",result.count);
- back = public.setJson(back,"list",result.list);
- callback(back);
- }
- })
- }
- //公用详情方法
- function detail(query,model,callback) {
- model.findOne(query,function (err,doc) {
- if(err||doc===null){
- callback(error.operation('tips')[2]);
- return;
- }else {
- var back = public.setJson(error.operation('tips')[3],"data",doc);
- callback(back);
- return;
- }
- })
- }
- //用于获取中卫市平台的认证信息,获取token
- //username,password分别为市平台的用户名和密码
- function Authentication(callback){//data请求内容
- //第一步先判断表里有没有数据 如果数据为0 或者大于1 则不对 清空数据 后 从省平台获取toke 插入数据库,直接返回token(end) 如果为1条则什么都不做,
- //第二步数据已经有了,判断token是否过期,没过期 直接返回(end);过期的话更新update然后返回(end)
- take.find(function (err,doc) {
- if(err){
- //
- var result=public.setJson({"success":1},"data",err);
- callback(result)
- }else {
- if(doc.length != 1){
- take.remove(function (err) {
- //清空数据库然后获取token插入
- var data=JSON.stringify({"username":"zhongwei","password":"zhongwei123456"});
- var opt = {
- host:'218.95.173.130',
- port:'9000',
- method:'POST',
- path:'/auth/security/access_token',
- headers:{
- "Content-Type": 'application/json',
- "Content-Length": data.length
- }
- }
- var body = '';
- var token = ""
- var req = http.request(opt, function(res) {
- //console.log("Got response: " + res.statusCode);
- res.on('data',function(d){
- body += d;
- body=JSON.parse(body);
- token=body.TOKEN;
- if(body.STATUS_CODE==200&&token!=""){
- var result={
- "success":0,
- "data":
- {"token":token,"AUTH_ID":body.AUTH_ID}
- };
- callback(result)
- }
- else {
- var result=public.setJson({"success":1},"data","获取token失败");
- callback(result)
- }
- }).on('end', function(){
- // console.log(res.headers)
- var takeAdd = new take({
- token:token,//token
- AUTH_ID:body.AUTH_ID,
- username:"zhongwei",//用户名
- password:"zhongwei123456"//密码
- });
- takeAdd.save(function (err) {
- // if(err){
- // var result=public.setJson({"success":1},"data",err);
- // callback(result)
- // }else {
- // var result={
- // "success":0,
- // "data":
- // {"token":token,"AUTH_ID":body.AUTH_ID}
- // };
- // callback(result)
- // }
- console.log(err)
- })
- });
- }).on('error', function(e) {
- console.log("Got error: " + e.message);
- });
- req.write(data);
- req.end();
- })
- }else{
- //只有一条数据
- //判断token是否过期
- if(moment().valueOf() - doc[0].begintime >= 86400){//过期 86400000
- //重新获取
- var data=JSON.stringify({"username":"zhongwei","password":"zhongwei123456"});
- var opt = {
- host:'218.95.173.130',
- port:'9000',
- method:'POST',
- path:'/auth/security/access_token',
- headers:{
- "Content-Type": 'application/json',
- "Content-Length": data.length
- }
- }
- var body = '';
- var token = "";
- var req = http.request(opt, function(res) {
- //console.log("Got response: " + res.statusCode);
- res.on('data',function(d){
- body += d;
- body=JSON.parse(body);
- token=body.TOKEN;
- if(body.STATUS_CODE==200&&token!=""){
- var result={
- "success":0,
- "data":
- {"token":token,"AUTH_ID":body.AUTH_ID}
- };
- callback(result)
- }
- else {
- var result=public.setJson({"success":1},"data","获取token失败");
- callback(result)
- }
- }).on('end', function(){
- take.updateOne({username:doc[0].username},{"$set":{token:token,AUTH_ID:body.AUTH_ID,begintime:moment().valueOf()}},function (err) {
- })
- });
- }).on('error', function(e) {
- console.log("Got error: " + e.message);
- });
- req.write(data);
- req.end();
- }else {
- var result={
- "success":0,
- "data":
- {"token":doc[0].token,"AUTH_ID":doc[0].AUTH_ID}
- };
- callback(result)
- }
- }
- }
- })
- }
- //主体部分接口
- function MainInterface(data,token,callback){
- data["REQ_TIME"] = moment().format("YYYY-MM-DD HH:mm:ss"),
- data["REQ_ID"] = moment().format("YYYYMMDDHHmmss")+(sixtytwo.toString(moment().valueOf())).substr(0,6),
- data=JSON.stringify(data);
- data=data+token;
- var opt = {
- host: '218.95.173.130',
- port: '9000',
- method: 'POST',
- path: '/interface-web/upload',
- headers: {
- "Content-Type": 'application/json'
- }
- }
- var body='';
- var back = ""
- var req = http.request(opt, function(res) {
- res.on('data',function(chunk){
- body+=chunk;
- var result=body.substring(0,body.lastIndexOf("}")+1);
- var token=body.substring(body.lastIndexOf("}")+1);
- result=JSON.parse(result);
- // console.log(result)
- switch (result.STATUS_CODE){
- case 200:
- back=public.setJson({"success":200},"data",result);
- back.token=token;
- // callback(data);
- break;
- case 40109:
- back=public.setJson({"success":40109},"data",typeof (result.RESULT)=="undefined"?"认证失败":result.RESULT);
- // callback(data);
- break;
- case 40103:
- back=public.setJson({"success":40103},"data",typeof (result.RESULT)=="undefined"?"无权限访问":result.RESULT);
- // callback(data);
- break;
- case 40104:
- back=public.setJson({"success":40104},"data",typeof (result.RESULT)=="undefined"?"token已过期":result.RESULT)
- // callback(data);
- break;
- case 500:
- back=public.setJson({"success":500},"data",typeof (result.RESULT)=="undefined"?"服务器未响应":result.RESULT)
- // callback(data);
- break;
- default:
- back=public.setJson({"success":result.STATUS_CODE},"data",result.RESULT);
- // back=public.setJson({"success":result.STATUS_CODE},"result.STATUS_CODE",result);
- // callback(data);
- }
- }).on('end', function(){
- callback(back);
- });
- }).on('error', function(e) {
- console.log("Got error: " + e.message);
- });
- req.write(data);
- req.end();
- }
- //生成上传日志
- function createUpLogs(name,code,obj,back) {//上传时的传入值和返回值
- var logs = new uploadLogs({
- BIZ_TYPE:obj.BIZ_TYPE,//
- ENTERPRISE_CODE:code,
- ENTERPRISE_NAME:name,
- LIST:obj.PARAM.LIST,//
- success:back.success,//
- RESULT:back.data,//
- });
- switch (obj.BIZ_TYPE.trim()) {
- case "TRACE_SEED":case"TRACE_PESTICIDE":case"TRACE_CHEMICAL_FERTILIZER":
- case "TRACE_PLANT_INPUTS":case"TRACE_PLANT_GROUND":case"TRACE_WEATHER_DETAL":case"TRACE_PLANT_AREA":
- case"TRACE_PLANT":case"TRACE_PLANT_PROCESS":case"TRACE_PLANT_WATER":case"TRACE_PLANT_PERTICIDE":
- case"TRACE_HARVEST":case"TRACE_PLANT_TRAN":
- logs.TYPE="种殖";
- break;
- case "TRACE_BREED_SOURCE":case "TRACE_FEED":case "TRACE_REGISTRATION":case "TRACE_BREED_INPUTS":case "TRACE_FEED_SITE":
- case "TRACE_COLONY_HOUSE":case "TRACE_BREED":case "TRACE_BREED_PROCESS":case "TRACE_BREED_HARVEST":case "TRACE_BREED_TRAN":
- logs.TYPE="养殖";
- break;
- case"TRACE_PRODUCTION_MATERIALS":case"TRACE_PRODUCTION_INPUTS":case"TRACE_PRODUCTION":case"TRACE_PRODUCTION_PROCESS":
- case"TRACE_DETECTION":case"TRACE_PACKAGE_CODING":case"TRACE_PRODUCTION_TRAN":
- logs.TYPE="生产加工";
- break;
- case "TRACE_ANIMAL_IN":case "TRACE_QUARANTINE":case "TRACE_PRODUCT_PROCESS":case "TRACE_MEAT_OUT":
- logs.TYPE="屠宰";
- break;
- case "TRACE_MARKET_IN":case "TRACE_MARKET_DETECTION":case "TRACE_MARKET_TRAN":
- logs.TYPE="批发";
- break;
- case "TRACE_RECALL":case "TRACE_DEALING":
- logs.TYPE="召回";
- break;
- default:
- logs.TYPE="";
- }
- logs.save(function (err) {
- if(err){
- console.log(err);
- }
- })
- }
- //生成日志
- function createLogs(data,back,path,type) {
- var logAdd = new logs({
- ENTERPRISE_CODE:(typeof(data.ENTERPRISE_CODE)=="undefined")?(typeof(data.SOCIAL_CREDIT_CODE)=="undefined"?"":data.SOCIAL_CREDIT_CODE):(data.ENTERPRISE_CODE),//企业编码
- ENTERPRISE_NAME:(typeof(data.ENTERPRISE_NAME)=="undefined")?(""):(data.ENTERPRISE_NAME),//企业名称
- username:(typeof(data.username)=="undefined")?(""):(data.username),//用户名
- token:(typeof(data.accessToken)=="undefined")?(""):(data.accessToken),//token
- path:path,//接口路径
- type:type,//接口类型
- time:Date.now(),//时间
- data:data,//调用数据
- back:(typeof (back)=="undefined")?"":back,//返回数据
- success:(typeof (back)=="undefined")?99:back.success,//是否成功
- platform:(typeof(data.platform)=="undefined")?(""):(data.platform)//0后台管理 1手持机
- });
- logAdd.save(function (err) {
- if(err){
- console.log(err);
- }
- })
- }
- //生成各种批次码
- function batch(code,str) {
- // "1"+object.ENTERPRISE_CODE+"11"+moment().valueOf()+"E",//采购批次码
- switch (str){
- case "种植":
- return "1"+code+"11"+moment().valueOf()+"A";
- break;
- case "收获":
- return "1"+code+"11"+moment().valueOf()+"B";
- break;
- case "采购":
- return "1"+code+"11"+moment().valueOf()+"E";
- break;
- case "处理":
- return "1"+code+"20"+moment().valueOf()+"C";
- break;
- case "生产":
- return "1"+code+"20"+moment().valueOf()+"D";
- break;
- case "配送":
- return "1"+code+"60"+moment().valueOf()+"F";
- break;
- case "辅料":
- return "1"+code+"20"+moment().valueOf()+"G";
- break;
- default:
- return "1"+code+"20"+moment().valueOf()+"Z";//啥也不是
- }
- }
- //验证传入的RFID标签数组是否全部初始化,
- //返回未初始化的标签数组,或者空数组[]
- function RFID(arr,callback) {
- status.find({TAG_CODE:{"$in":arr}},function (err,doc) {
- if(err){
- callback(-1);
- }else {
- if(doc.length == arr.length){
- //标签全部激活,返回空数组
- callback ([]);
- }else {
- //标签部分激活,返回未激活标签数组
- var list = [];
- doc.forEach(function (item) {
- list.push(item.TAG_CODE);
- });
- callback(public.arrayCut(arr,list));
- }
- }
- });
- }
- //生成各种批次码
- //enterpriceCode 企业代码 18位 productCode 产品代码 8位 procedureCode 流通顺序码
- function traceCode(enterpriceCode,productCode,procedureCode,milSecond = 0) {
- var TraceTypeCode = "2"; //溯源码第一位为1
- var milSecond = milSecond == 0 ? moment().valueOf():milSecond;
- var seqCode = milSecond.toString().substr(5,8);
- productCode = "00000000";
- var traceCode = TraceTypeCode + enterpriceCode + productCode + procedureCode + moment().format('YYYYMMDD') + seqCode + random.int(0, 9);
- return traceCode;
- }
- //获取企业或个人token,不存入Token表
- function getToken(data,callback) {
- data=JSON.stringify(data);
- var opt = {
- host:'218.95.173.130',
- port:'9000',
- method:'POST',
- path:'/auth/security/access_token',
- headers:{
- "Content-Type": 'application/json',
- "Content-Length": data.length
- }
- };
- var body = '';
- var req = http.request(opt, function(res) {
- //console.log("Got response: " + res.statusCode);
- res.on('data',function(d){
- body += d;
- body=JSON.parse(body);
- var token=body.TOKEN;
- if(body.STATUS_CODE==200&&token!=""){
- //获取token成功
- var result=public.setJson({"success":0},"msg",token);
- callback(result)
- }
- else {
- var result=public.setJson({"success":1},"msg","获取token失败,msgCode:"+body.STATUS_CODE);
- callback(result)
- }
- }).on('end', function(){
- // console.log(res.headers)
- });
- }).on('error', function(e) {
- console.log("Got error: " + e.message);
- });
- req.write(data);
- req.end();
- }
- //交易信息添加到marketAnalysis表
- function marketAnalysisAdd(data,url){
- businessInfo.find({SUPPLY_SOCIAL_CREDIT_CODE:data.SUPPLY_SOCIAL_CREDIT_CODE},function (err,doc) {
- if(err){
- // console.log(err);
- createLogs(data,err,url,"POST")
- return;
- }else {
- // console.log(doc)
- corporation.find({SOCIAL_CREDIT_CODE:data.SOCIAL_CREDIT_CODE},function (errs,docs) {
- if(errs){
- createLogs(data,err,url,"POST")
- // console.log(errs)
- return;
- }
- else {
- // var area=(docs.length==0?"":docs[0].AREA_NAME).split("-")
- var area=((data.AREA_NAME===""||typeof data.AREA_NAME === "undefined")?"":data.AREA_NAME.split("-"));
- var marketAnalysisAdd=new marketAnalysis({
- apiName:data.apiName,//环节名称
- VARIETY_NAME:data.VARIETY_NAME,//品种名称
- ENTERPRISE_CODE:data.ENTERPRISE_CODE,//企业编码
- ENTERPRISE_NAME:data.ENTERPRISE_NAME,//企业名称
- shortname:((doc.length===0||docs.length===0)?"":(docs[0].shortname===""?"中宁国际":docs[0].shortname)),//企业简称 没找到为"",简称为空则默认商户,判断为"中宁国际"
- type:data.type,//类型
- DEST_NAME:area==""?"":area.join(""),//到达地区名称
- province:typeof (area[0])=="undefined"||area[0]?"":area[0],//采交省
- city:typeof (area[1])=="undefined"||area[1]?"":area[1],//采交市
- area:typeof (area[2])=="undefined"||(area[2])==""?"":(area[2]),//采交区
- areaCODE:(docs.length==0?"":docs[0].AREA_CODE),//采交区编码
- traders:(docs.length==0?"":docs[0].COMP_NAME),//采交主体名称
- tradersCode:data.tradersCode,//采交主体编码
- shortTraders:(docs.length==0?"":docs[0].shortname),//采交主体简称
- unit:data.unit,//单位 不是重量,是计量单位,比如盒
- SPECIFICATION:parseFloat(data.SPECIFICATION).toFixed(3),//规格
- totalWeight:parseFloat(data.totalWeight).toFixed(3),//总重
- price:parseFloat(data.PRICE).toFixed(3),//单价
- number:parseFloat(data.AMOUNT).toFixed(3),//数量
- total:parseFloat(data.total).toFixed(3),//总价
- year:parseInt(moment().format("YYYY")),//年
- month:parseInt(moment().format("MM")),//月
- day:parseInt(moment().format("DD")),//日
- username:data.username,//操作用户
- })
- marketAnalysisAdd.save(function (err) {
- if(err){
- // console.log(err)
- createLogs(data,err,url,"POST")
- return;
- }
- })
- }
- })
- }
- })
- }
- const nodemailer = require('nodemailer');
- var result = {
- success:0,//0成功 1不成功
- msg:""//提示消息
- };
- const msgRcv = require("../models/t_msgRcv");
- //发送问题清单 type 1 表示 email; type 2 表示 站内短信
- //address:type为2时平台账户;type为1时Email地址
- //sender:发送人姓名
- function sendByEmailOrSms(type,address,content,callback) {
- var mailAccount = 'bellinggg@163.com';
- if(type==1)
- {
- let transporter = nodemailer.createTransport({
- // host: 'smtp.ethereal.email',
- service: '163', // 使用了内置传输发送邮件 查看支持列表:https://nodemailer.com/smtp/well-known/
- port: 465, // SMTP 端口
- secureConnection: true, // 使用了 SSL
- auth: {
- user: mailAccount,
- // 这里密码不是qq密码,是你设置的smtp授权码
- pass: 'xb51105110',
- }
- });
- let mailOptions = {
- from: '"中卫重要产品溯源平台" <'+ mailAccount +'>', // sender address
- to: address, // list of receivers
- subject: '平台数据问题报告', // Subject line
- // 发送text或者html格式
- // text: 'Hello world?', // plain text body
- html: content // html body
- };
- // send mail with defined transport object
- transporter.sendMail(mailOptions, (error, info) => {
- if (error) {
- result.msg = error.response;
- result.success = 1;//发送失败
- callback(result);
- }
- else
- {
- result.msg = info.response;
- result.success = 0;//发送成功
- callback(result);
- }
- });
- }
- else if(type == 2)
- {
- var msgRcvAdd = new msgRcv(
- {
- smsID:"SMS-"+sixtytwo.toString(moment().valueOf()),//smsID
- sendName:"中卫重要产品溯源平台",//发送人
- rcvName:address,//接收人
- title:"平台数据问题报告",//发送标题
- content:content,//发送消息
- }
- )
- msgRcvAdd.save(function (err) {
- if(err)
- {
- result.msg = error;
- result.success = 1;
- callback(result);
- }
- else
- {
- result.msg = "站内短信发送成功!";
- result.success = 0;//发送成功
- callback(result);
- }
- })
- }
- }
- //将数组转化为表格内容
- function qListToArray(qlist)
- {
- var content = "<table border=\"1\">\n" +
- "<tr>\n" +
- " <th>接口路径</th>\n" +
- " <th>接口名称</th>\n" +
- " <th>接口类型</th>\n" +
- " <th>问题描述</th>\n" +
- " </tr>";
- qlist.forEach(function (items) {
- content += "<tr>";
- content += "<td>"+items.API+"</td>";
- content += "<td>"+items.apiName+"</td>";
- content += "<td>"+items.interfaceType+"</td>";
- var desc = "";
- for(var i = 0 ; i < items.desc.length; i++)
- {
- desc += items.desc[i] + "<br>";
- }
- content += "<td>"+desc+"</td>"+"</tr>";
- });
- content += "</table>";
- return content;
- }
- //sample:
- // var qlist = [
- // {
- // API:"test3",
- // apiName:"test2",
- // interfaceType:"test1",
- // desc:[
- // "q1","q2"
- // ]
- // },{
- // API:"tesddd3",
- // apiName:"teddst2",
- // interfaceType:"tesddt1",
- // desc:[
- // "dddq1","dddq2"
- // ]
- // }
- // ]
- //
- // // console.log( qListToArray(qlist))
- //
- // var content = qListToArray(qlist);
- //
- // console.log(content)
- //
- // sendByEmailOrSms(1,"11169031@qq.com",content,function (callback) {
- // console.log(callback)
- // })
- exports.marketAnalysisAdd=marketAnalysisAdd;
- exports.update = update;
- exports.updateMore = updateMore;
- exports.Authentication=Authentication;
- exports.MainInterface=MainInterface;
- exports.search=search;
- exports.detail=detail;
- exports.createLogs=createLogs;
- exports.batch=batch;
- exports.RFID=RFID;
- exports.traceCode=traceCode;
- exports.getToken=getToken;
- exports.createUpLogs=createUpLogs;
- exports.sendByEmailOrSms=sendByEmailOrSms;
- exports.qListToArray=qListToArray;
|