Bläddra i källkod

Merge branch 'dev' of http://192.168.1.220:10080/Amoy/im.doctor into dev

Sand 8 år sedan
förälder
incheckning
d3f9354bdf

+ 1 - 1
src/doctor/app.js

@ -45,7 +45,7 @@ app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/favicon.ico', null));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

+ 72 - 1
src/doctor/endpoints/chats.endpoint.js

@ -209,6 +209,19 @@ router.get(APIv1.Chats.ListWithDoctor, function (req, res) {
    doctor.getChatListWithDoctor(userId);
});
router.get(APIv1.Chats.MsgAmount, function (req, res) {
    let userId = req.query.user_id;
    if (userId === null) {
        throw {httpStatus: 406, message: 'Missing fields.'};
    }
    let doctor = new Doctor();
    controllerUtil.regModelEventHandler(doctor, res);
    doctor.getChatListMsgAmount(userId);
});
/**
 * 获取最近聊天对象:包括患者,医生与讨论组。客户端自行根据需要提取患者、医生或讨论组数据。
 *
@ -505,11 +518,30 @@ router.get(APIv1.Chats.SearchAboutPatientList, function (req, res) {
    search.searchAboutPatientList(userId, keyword,groupId,type);
});
/**
 * http://192.168.131.107:3000/api/v1/chats/search/patient/all?user_id=D2016008240003&keyword=f&type=2&user_role=3
 * 患者消息查询查看更多
 */
router.get(APIv1.Chats.SearchAbountPatientMore, function (req, res) {
    var userId = req.query.user_id;
    var keyword = req.query.keyword;
    var type = req.query.type;
    var userRole= req.query.user_role;
    if (!userId) throw {httpStatus: 406, message: "Missing fields: user_id."};
    if (!keyword) throw {httpStatus: 406, message: "Missing fields: keyword."};
    if (!type) throw {httpStatus: 406, message: "Missing fields: type."};
    if (!userRole) throw {httpStatus: 406, message: "Missing fields: userRole."};
    let search = new Search();
    controllerUtil.regModelEventHandler(search, res);
    search.searchAboutPatientAll(userId,userRole, keyword,type);
});
/**
 * 搜索医生相关的数据,包括医生信息与相关的聊天记录,包括私信与群信。
 *
 * 请求URL:
 *  /search/doctor?user_id=5fa5e88f7a4111e69f7c005056850d66&keyword=丘
 *  /search/doctor?user_id=D2016008240003&keyword=黄
 *
 * 参数:
 *  keywords: 关键词
@ -526,6 +558,45 @@ router.get(APIv1.Chats.SearchAboutDoctor, function (req, res) {
    search.searchAboutDoctor(userId, keyword);
});
/**
 * http://192.168.131.107:3000/api/v1/chats/search/doctor/list?user_id=D2016008240003&keyword=%E9%BB%84&type=2
 * 医生搜索查看更多
 * type = 1 查询聊过的医生
 * type = 2 查询群组标题和人员包含的群聊
 * type = 3 查询聊天关键字
 */
router.get(APIv1.Chats.SearchAboutDoctorList, function (req, res) {
    let userId = req.query.user_id;
    let keyword = req.query.keyword;
    let type = req.query.type;
    if (!userId) throw {httpStatus: 406, message: "Missing fields: user_id."};
    if (!keyword) throw {httpStatus: 406, message: "Missing fields: keyword."};
    if (!type) throw {httpStatus: 406, message: "Missing fields: type."};
    let search = new Search();
    controllerUtil.regModelEventHandler(search, res);
    search.searchDoctorMore(userId, keyword,type);
});
/**
 * 查询医生聊天记录详情(单个聊天记录包含关键字的)
 *http://192.168.131.107:3000/api/v1/chats/search/doctor/content/list?user_id=D2016008240003&keyword=f&type=2&groupcode=0381288df51b434795b6946bb63d90b8
 */
router.get(APIv1.Chats.SearchAbountDoctorContentDetail, function (req, res) {
    let userId = req.query.user_id;
    let keyword = req.query.keyword;
    let type = req.query.type;
    let groupcode = req.query.groupcode;
    if (!userId) throw {httpStatus: 406, message: "Missing fields: user_id."};
    if (!keyword) throw {httpStatus: 406, message: "Missing fields: keyword."};
    if (!type) throw {httpStatus: 406, message: "Missing fields: type."};
    if (!groupcode) throw {httpStatus: 406, message: "Missing fields: groupcode."};
    let search = new Search();
    controllerUtil.regModelEventHandler(search, res);
    search.searchDoctorContentDetail(userId, keyword,groupcode,type);
});
/**
 * 获取单条消息。

+ 4 - 2
src/doctor/include/endpoints.js

@ -16,12 +16,14 @@ const APIv1 = {
        List: "/list",
        ListWithPatient: "/list/patient",
        ListWithDoctor: "/list/doctor",
        MsgAmount:"/msg/amount",
        Recent: '/recent',
        SearchAboutPatient: '/search/patient',
        SearchAboutPatientList:'/search/patient/list',
        SearchAbountPatientMore:'/search/patient/all',
        SearchAboutDoctor: '/search/doctor',
        SearchAboutDoctorList: '/search/doctor/list',
        SearchAbountDoctorContentDetail:'/search/doctor/content/list',
        // 所有未读消息数
        UnreadMsgCount: '/unread_count',

+ 64 - 1
src/doctor/models/doctor.js

@ -431,6 +431,69 @@ class Doctor extends BaseModel {
        });
    }
    /**
     * 获取与医生,患者的聊天列表,包括:点对点,参与的讨论组。消息数量
     *
     * @param userId
     */
    getChatListMsgAmount(userId) {
        let self = this;
        let chats = {doctor: {}, patient: {}};
        // 先获取医生间的私聊
        pmRepo.findAllP2PWithDoctor(userId, function (err, doctors) {
            if (err) {
                modelUtil.emitDbError(self.eventEmitter, 'Get chat list with doctor failed', err);
                return;
            }
            var amount = 0;
            for (let i = 0; i < doctors.length; i++) {
                let doctor = doctors[i];
                amount = doctor.new_msg_count+amount;
            }
            // 再获取医生间的组
            gmRepo.findAllGroupsWithDoctor(userId, function (err, groups) {
                if (err) {
                    modelUtil.emitDbError(self.eventEmitter, 'Get group list with doctor failed', err);
                    return;
                }
                for (let i = 0; i < groups.length; i++) {
                    let group = groups[i];
                    amount =   group.new_msg_count+amount;
                }
                chats.doctor = amount;
                var patientAmount =0;
                //获取患者记录数量
                pmRepo.findAllP2PWithPatient(userId, function (err, patients) {
                    if (err) {
                        modelUtil.emitDbError(self.eventEmitter, 'Get chat list with patient failed', err);
                        return;
                    }
                    for (let i = 0; i < patients.length; i++) {
                             let patient = patients[i];
                             patientAmount =patientAmount+ patient.new_msg_count;
                    }
                    //获取患者记录数量
                    gmRepo.findAllGroupsWithPatient(userId, function (err, groups) {
                        if (err) {
                            modelUtil.emitDbError(self.eventEmitter, 'Get group list with patient failed', err);
                            return;
                        }
                        for (let i = 0; i < groups.length; i++) {
                            let group = groups[i];
                            // 过滤掉医生间的求助团队
                            if (group.group_type === 2) continue;
                            patientAmount = patientAmount+ group.new_msg_count;
                        }
                        chats.patient = patientAmount;
                        modelUtil.emitData(self.eventEmitter, chats);
                    });
                });
            });
        });
    }
    /**
     * 获取与指定用户的聊天记录。
     *
@ -445,7 +508,7 @@ class Doctor extends BaseModel {
    getPrivateMessages(userId, peerId, contentType, msgStartId, msgEndId, count, closedInterval) {
        let self = this;
        pmRepo.findAllMessages(userId, peerId, contentType === undefined ? "1,2,3,5,6" : contentType, msgStartId, msgEndId, count, closedInterval, function (err, rows) {
        pmRepo.findAllMessages(userId, peerId, contentType === undefined ? "1,2,3,4,5,6" : contentType, msgStartId, msgEndId, count, closedInterval, function (err, rows) {
            if (err) {
                modelUtil.emitDbError(self.eventEmitter, 'Get private message failed', err);
                return;

+ 51 - 1
src/doctor/models/patient.js

@ -22,7 +22,10 @@ const CONTENT_TYPES = require('../include/commons').CONTENT_TYPE;
let clientCache = require('./socket.io/client.cache').clientCache();
class Patient extends BaseModel{
let doctorRepo = require('../repository/doctor.repo');
let wechatUtil = require('../util/wechatUtil');
class Patient extends BaseModel {
    constructor() {
        super();
    }
@ -80,6 +83,7 @@ class Patient extends BaseModel{
                let patientClient = clientCache.findById(message.to);
                if (!patientClient) {
                    log.warn("User is not online, user id: ", message.to);
                    self.sendConsultWechatReplyTempMsg(message);
                    return;
                }
@ -97,6 +101,52 @@ class Patient extends BaseModel{
            });
        });
    };
    /**
     * 发送微信模板消息给居民
     *
     * @param message
     */
    sendConsultWechatReplyTempMsg(message) {
        // 推送微信模板消息
        patientRepo.getPatientOpenid(message.to, function (err, result) {
            if (err) {
                modelUtil.emitDbError(self.eventEmitter, "get patient openid failed", err);
                return;
            }
            var openid = result && result.length > 0 ? result[0].openid : "";
            if (openid) {
                doctorRepo.getDoctorInfo(message.from, function (err, result) {
                    if (err) {
                        modelUtil.emitDbError(self.eventEmitter, "get doctor info failed", err);
                        return;
                    }
                    if (result && result.length > 0) {
                        var name = result[0].name;
                        var msg = {
                            touser: openid,
                            template_id: config.wechatConfig.template.consultTemplate,
                            url: config.wechatConfig.baseUrl + "/wx/html/yszx/html/consulting-doctor.html?openid=" + openid +
                            "&consult=" + "" + "&toUser=" + message.to,
                            data: {
                                first: {value: "您的健康咨询有新的回复", color: "#000000"}
                                , remark: {value: "", color: "#000000"}
                                , keyword1: {value: "XXXX咨询", color: "#000000"}
                                , keyword2: {value: "XXXX回复", color: "#000000"}
                                , keyword3: {value: name, color: "#000000"}
                            }
                        };
                        wechatUtil.sendWxTemplateMessage(msg);
                    }
                });
            } else {
                modelUtil.logError("patient does not bind wechat", err);
            }
        });
    };
}
module.exports = Patient;

+ 235 - 88
src/doctor/models/search.js

@ -36,18 +36,98 @@ class Search extends BaseModel{
                return;
            }
            var data = {patients: [], chats: []};
            var data = {patients: [],group:[], chats: []};
            for (var i = 0; i < patients.length; ++i) {
                var patient = patients[i];
                data.patients.push({
                var p ={};
                console.log(patient.code);
                p= {
                    code: patient.code,
                    name: patient.name,
                    sex: patient.sex,
                    birthday: objectUtil.timestampToLong(patient.birthday),
                    avatar: patient.photo === null ? "" : patient.photo
                });
                }
                data.patients.push(p);
            }
            searchRepo.searchGroupPatients(userId, keyword, function (err, groups) {
                if (err) {
                    modelUtil.emitDbError(self.eventEmitter, "Search talk group failed", err);
                    return;
                }
                var group = null;
                for (var i = 0; i < groups.length; ++i) {
                    var t = groups[i];
                    group = {
                        code: t.code,
                        name: t.name,
                        members: t.con,
                    };
                    data.group.push(group);
                }
                searchRepo.searchPatientPM(userId, keyword, function (err, chats) {
                    if (err) {
                        log.error("Search patient on private messages failed: ", err);
                        res.status(500).send({message: "Search patient on private messages failed."});
                        return;
                    }
                    for (var i = 0; i < chats.length; ++i) {
                        var lastPatient = {code: '', name: '', sex: '', avatar: '',amount:'',content:'',chat:'',type:''};
                        var chat = chats[i];
                        console.log(JSON.stringify(chat));
                        lastPatient.code = chat.code;
                        lastPatient.name = chat.name;
                        lastPatient.sex = chat.sex;
                        lastPatient.birthday = objectUtil.timestampToLong(chat.birthday);
                        lastPatient.avatar = chat.photo === null ? "" : chat.photo;
                        lastPatient.amount = chat.amount;
                        lastPatient.chat = chat.chat;
                        lastPatient.content = chat.content;
                        lastPatient.type = chat.type;
                        lastPatient.msg_id =chat.msg_id;
                        data.chats.push(lastPatient);
                    }
                    modelUtil.emitData(self.eventEmitter, data);
                });
            });
        });
    }
    /**
     * 患者查询查看更多1.患者 2.内容 3.群组
     * @param userId
     * @param userRole
     * @param keyword
     * @param type
     */
    searchAboutPatientAll(userId, userRole, keyword,type) {
        let self = this;
        var data = [];
        if(type==1){
            searchRepo.searchPatients(userId, userRole, keyword, function (err, patients) {
                if (err) {
                    log.error("Search patient on basic information failed: ", err);
                    res.status(500).send({message: "Search patient on basic information failed."});
                    return;
                }
                for (var i = 0; i < patients.length; ++i) {
                    var patient = patients[i];
                    data.push({
                        code: patient.code,
                        name: patient.name,
                        sex: patient.sex,
                        birthday: objectUtil.timestampToLong(patient.birthday),
                        avatar: patient.photo === null ? "" : patient.photo
                    });
                }
                modelUtil.emitData(self.eventEmitter, data);
            });
        }
        if(type==3){
            searchRepo.searchPatientPM(userId, keyword, function (err, chats) {
                if (err) {
                    log.error("Search patient on private messages failed: ", err);
@ -55,11 +135,9 @@ class Search extends BaseModel{
                    res.status(500).send({message: "Search patient on private messages failed."});
                    return;
                }
                for (var i = 0; i < chats.length; ++i) {
                    var lastPatient = {code: '', name: '', sex: '', avatar: '',amount:'',content:'',chat:'',type:''};
                    var chat = chats[i];
                    console.log(JSON.stringify(chat));
                    lastPatient.code = chat.code;
                    lastPatient.name = chat.name;
                    lastPatient.sex = chat.sex;
@ -69,11 +147,30 @@ class Search extends BaseModel{
                    lastPatient.chat = chat.chat;
                    lastPatient.content = chat.content;
                    lastPatient.type = chat.type;
                    data.chats.push(lastPatient);
                    data.push(lastPatient);
                }
                modelUtil.emitData(self.eventEmitter, data);
            });
        });
        }
        if(type==2){
            searchRepo.searchGroupPatients(userId, keyword, function (err, groups) {
                if (err) {
                    modelUtil.emitDbError(self.eventEmitter, "Search talk group failed", err);
                    return;
                }
                var group = null;
                for (var i = 0; i < groups.length; ++i) {
                    var t = groups[i];
                    group = {
                        code: t.code,
                        name: t.name,
                        members: t.con,
                    };
                    data.push(group);
                }
                modelUtil.emitData(self.eventEmitter, data);
            });
        }
    }
    /**
@ -89,7 +186,7 @@ class Search extends BaseModel{
        searchRepo.searchPatientPMList(userId, keyword,groupId,type, function (err, chats) {
            var data = [];
            if (err) {
                log.error("Search patient on private messages failed: ", err);
                log.error("Search searchPatientPMList on private messages failed: ", err);
                res.status(500).send({message: "Search patient on private messages failed."});
                return;
            }
@ -103,6 +200,7 @@ class Search extends BaseModel{
                lastPatient.avatar = chat.photo === null ? "" : chat.photo;
                lastPatient.chat = chat.chat;
                lastPatient.content=chat.content;
                lastPatient.msg_id=chat.msg_id;
                data.push(lastPatient);
            }
            modelUtil.emitData(self.eventEmitter, data);
@ -115,117 +213,166 @@ class Search extends BaseModel{
     */
    searchAboutDoctor(userId, keyword) {
        let self = this;
        searchRepo.searchDoctors(userId, keyword, function (err, doctors) {
        //搜索单对单医生聊天
        searchRepo.searchP2Pdoctors(userId, keyword, function (err, doctors) {
            if (err) {
                modelUtil.emitDbError(self.eventEmitter, "Search doctor on basic information failed", err);
                return;
            }
            let data = {doctors: [], groups: [], chats: {doctors: [], groups: []}};
            for (let i = 0; i < doctors.length; ++i) {
                let doctor = doctors[i];
            var data = {doctors: [], groups: [],content:[]};
            for (var i = 0; i < doctors.length; ++i) {
                var doctor = doctors[i];
                data.doctors.push({
                    code: doctor.code,
                    name: doctor.name,
                    hospitalName:doctor.hospital_name,
                    sex: doctor.sex,
                    avatar: doctor.photo === null ? "" : doctor.photo
                });
            }
            // 搜索讨论组名称及成员名称
            searchRepo.searchGroups(userId, keyword, function (err, groups) {
            // 搜索讨论组名称及成员名称(讨论组)
            searchRepo.searchGroupDoctors(userId, keyword, function (err, groups) {
                if (err) {
                    modelUtil.emitDbError(self.eventEmitter, "Search talk group failed", err);
                    return;
                }
                let lastGroupCode = '';
                let lastGroup = null;
                for (let i = 0; i < groups.length; ++i) {
                    let group = groups[i];
                    if (lastGroupCode !== group.code) {
                        lastGroupCode = group.code;
                        lastGroup = {
                            code: group.code,
                            name: group.name,
                            type: GROUP_TYPE.DiscussionGroup,
                            members: []
                var group = null;
                for (var i = 0; i < groups.length; ++i) {
                        var t = groups[i];
                        group = {
                            code: t.code,
                            name: t.name,
                            members: t.con,
                            groupType:t.group_type
                        };
                        data.groups.push(lastGroup);
                    }
                    lastGroup.members.push({
                        code: group.member_code,
                        name: group.member_name
                    });
                        data.groups.push(group);
                }
                // 搜索医生间的私信
                searchRepo.searchDoctorMessages(userId, keyword, function (err, messages) {
                searchRepo.searchDoctorsContent(userId, keyword, function (err, messages) {
                    if (err) {
                        modelUtil.emitDbError(self.eventEmitter, "Search doctor private messages failed", err);
                        return;
                    }
                    var message = null;
                    for (var i = 0; i < messages.length; ++i) {
                        var t = messages[i];
                        message = {
                            code: t.code,
                            name: t.name,
                            amount: t.amount,
                            content:t.content,
                            type:t.type,
                            msg_id:t.msg_id,
                            groupType:t.group_type
                    let lastDoctor;
                    let lastDoctorCode = '';
                    for (let i = 0; i < messages.length; ++i) {
                        let message = messages[i];
                        if (lastDoctorCode !== message.code) {
                            lastDoctorCode = message.code;
                            lastDoctor = {
                                code: message.code,
                                name: message.name,
                                photo: message.photo === null ? "" : message.photo,
                                messages: []
                            };
                            data.chats.doctors.push(lastDoctor);
                        }
                        lastDoctor.messages.push({
                            id: message.msg_id,
                            content: message.content
                        });
                        };
                        data.content.push(message);
                    }
                    // 搜索医生间的讨论组消息
                    searchRepo.searchGroupMessages(userId, keyword, function (err, messages) {
                        if (err) {
                            modelUtil.emitDbError(self.eventEmitter, "Search doctor group messages failed", err);
                            return;
                        }
                        // g.code, g.name, gm.msg_id, gm.content
                        let lastGroup;
                        let lastGroupCode = '';
                        for (let i = 0; i < messages.length; ++i) {
                            let message = messages[i];
                            if (lastGroupCode !== message.code) {
                                lastGroupCode = message.code;
                                lastGroup = {
                                    code: message.code,
                                    name: message.name,
                                    messages: []
                                };
                                data.chats.groups.push(lastGroup);
                            }
                            lastGroup.messages.push({
                                id: message.msg_id,
                                content: message.content
                            });
                        }
                        modelUtil.emitData(self.eventEmitter, data);
                    modelUtil.emitData(self.eventEmitter, data);
                    });
                });
            });
        });
    }
    searchDoctorMore(userId,keyword,type){
        let self = this;
        var data = [];
        if(type==1){
            searchRepo.searchP2Pdoctors(userId, keyword, function (err, doctors) {
                if (err) {
                    modelUtil.emitDbError(self.eventEmitter, "Search doctor on basic information failed", err);
                    return;
                }
                for (var i = 0; i < doctors.length; ++i) {
                    var doctor = doctors[i];
                    data.push({
                        code: doctor.code,
                        name: doctor.name,
                        hospitalName:doctor.name,
                        sex: doctor.sex,
                        avatar: doctor.photo === null ? "" : doctor.photo
                    });
                }
                modelUtil.emitData(self.eventEmitter, data);
            });
        }else if(type==2){
            searchRepo.searchGroupDoctors(userId, keyword, function (err, groups) {
                if (err) {
                    modelUtil.emitDbError(self.eventEmitter, "Search talk group failed", err);
                    return;
                }
                var group = null;
                for (var i = 0; i < groups.length; ++i) {
                    var t = groups[i];
                    group = {
                        code: t.code,
                        name: t.name,
                        members: t.con,
                        groupType:t.group_type
                    };
                    data.push(group);
                }
                modelUtil.emitData(self.eventEmitter, data);
            });
        }else if(type==3){
            searchRepo.searchDoctorsContent(userId, keyword, function (err, messages) {
                if (err) {
                    modelUtil.emitDbError(self.eventEmitter, "Search doctor private messages failed", err);
                    return;
                }
                var message = null;
                for (var i = 0; i < messages.length; ++i) {
                    var t = messages[i];
                    message = {
                        code: t.code,
                        name: t.name,
                        amount: t.amount,
                        content:t.content,
                        type:t.type,
                        msg_id:t.msg_id,
                        groupType:t.group_type
                    };
                    data.push(message);
                }
                modelUtil.emitData(self.eventEmitter, data);
            });
        }
    }
    /**
     * 搜索医生聊天详情
     * @param userId 当前医生ID
     * @param keyword 关键字
     * @param groupcode 群组code
     * @param type type =1 p2p type = 2群组
     */
    searchDoctorContentDetail(userId,keyword,groupcode,type){
            let self = this;
            var data = [];
            searchRepo.searchDoctorsContentDetail(userId, keyword,groupcode,type, function (err, doctors) {
                if (err) {
                    modelUtil.emitDbError(self.eventEmitter, "Search doctor on basic information failed", err);
                    return;
                }
                for (var i = 0; i < doctors.length; ++i) {
                    var doctor = doctors[i];
                    data.push({
                        code: doctor.code,
                        name: doctor.name,
                        content:doctor.content,
                        msg_id:t.msg_id,
                        groupType:t.group_type
                    });
                }
                modelUtil.emitData(self.eventEmitter, data);
            });
    }
}
module.exports = Search;

+ 8 - 0
src/doctor/repository/doctor.repo.js

@ -62,3 +62,11 @@ exports.updateStatus = function(userId, status, handler) {
        "handler": handler
    });
};
exports.getDoctorInfo = function (code, handler) {
    wlyyRepo.execQuery({
        "sql":"select code,name from wlyy_doctor where code = ? ",
        "args":[code],
        "handler":handler
    });
};

+ 10 - 0
src/doctor/repository/patient.repo.js

@ -16,4 +16,14 @@ exports.isPatientCode = function (code, handler) {
        "args": [],
        "handler": handler
    });
};
exports.getPatientOpenid = function (code, handler) {
    var sql = "select openid from wlyy_patient where code = ? ";
    wlyyDb.execQuery({
        "sql": sql,
        "args": [code],
        "handler": handler
    });
};

Filskillnaden har hållts tillbaka eftersom den är för stor
+ 122 - 11
src/doctor/repository/search.repo.js


+ 34 - 0
src/doctor/repository/wechat.token.repo.js

@ -0,0 +1,34 @@
/**
 * 微信AccessToken
 *
 * Created by lyr-pc on 2016/11/25.
 */
"use strict";
var log = require('../util/log');
var wlyyDb = require('./database/wlyy.db');
/**
 * 获取微信AccessToken
 *
 * @param handler 回调函数
 */
exports.getAccessToken = function(handler) {
    wlyyDb.execQuery({
        "sql":"select p.* from wx_access_token p order by p.add_timestamp desc limit 0,1"
        ,"handler":handler
    });
};
/**
 * 保存AccessToken
 *
 * @param accessToken 微信AccessToken
 * @param hanlder 回调函数
 */
exports.saveAccessToken = function(accessToken,handler) {
    wlyyDb.execQuery({
        "sql":"insert into wx_access_token (access_token,add_timestamp,expires_in,czrq) values (?,?,?,?)"
        ,"args":accessToken
        ,"handler":handler
    });
}

+ 19 - 5
src/doctor/resources/config/config.dev.js

@ -40,10 +40,22 @@ let geTuiConfig = {
// AppStore版的推送App配置
let geTuiAppStoreCfg = {
    HOST : 'https://api.getui.com/apiex.htm',
    APPID : 'H6FYbDejks6VjMmW3uH7V6',
    APPKEY : '0PFWlKmLBN9YzhCfFWVgYA',
    MASTERSECRET : 'pvjCGtRZJx9SRVODkxc816'
    HOST: 'https://api.getui.com/apiex.htm',
    APPID: 'H6FYbDejks6VjMmW3uH7V6',
    APPKEY: '0PFWlKmLBN9YzhCfFWVgYA',
    MASTERSECRET: 'pvjCGtRZJx9SRVODkxc816'
};
// 微信配置
let wechatConfig = {
    appId: 'wxd03f859efdf0873d'
    , appSecret: '2935b54b53a957d9516c920a544f2537'
    , token: '27eb3bb24f149a7760cf1bb154b08040'
    , baseUrl: 'weixin.xmtyw.cn/wlyy'
    , template: {
        // 咨询回复模板
        consultTemplate: 'qSOW0DBxO3qEBm4ucG0Ial0jxsOyD7_f2TFK5e-mQEc'
    }
};
exports.app = 'IM.Server';
@ -59,4 +71,6 @@ exports.imDbConfig = imDbConfig;
exports.geTuiConfig = geTuiConfig;
exports.geTuiAppStoreCfg = geTuiAppStoreCfg;
exports.wlyyServerConfig = wlyyServerConfig;
exports.transServerConfig = transServerConfig;
exports.transServerConfig = transServerConfig;
exports.wechatConfig = wechatConfig;

+ 16 - 4
src/doctor/resources/config/config.prod.js

@ -26,10 +26,10 @@ let geTuiConfig = {
//AppStore版的推送App配置
let geTuiAppStoreCfg = {
    HOST : 'https://api.getui.com/apiex.htm',
    APPID : 'H6FYbDejks6VjMmW3uH7V6',
    APPKEY : '0PFWlKmLBN9YzhCfFWVgYA',
    MASTERSECRET : 'pvjCGtRZJx9SRVODkxc816'
    HOST: 'https://api.getui.com/apiex.htm',
    APPID: 'H6FYbDejks6VjMmW3uH7V6',
    APPKEY: '0PFWlKmLBN9YzhCfFWVgYA',
    MASTERSECRET: 'pvjCGtRZJx9SRVODkxc816'
};
// 三师后台
@ -44,6 +44,18 @@ let transServerConfig = {
    port: 3030
};
// 微信配置
let wechatConfig = {
    appId: 'wxad04e9c4c5255acf'
    , appSecret: 'ae77c48ccf1af5d07069f5153d1ac8d3'
    , token: '27eb3bb24f149a7760cf1bb154b08040'
    , baseUrl: 'www.xmtyw.cn/wlyy'
    , template: {
        // 咨询回复模板
        consultTemplate: '0mF_vHj-ILx8EH8DwzmAi7LqzjqYiU9IrSRRmziTZyc'
    }
};
exports.app = 'im.server';
exports.version = '1.2.5.20161107';
exports.debug = true;

+ 17 - 5
src/doctor/resources/config/config.test.js

@ -26,10 +26,10 @@ let geTuiConfig = {
//AppStore版的推送App配置
let geTuiAppStoreCfg = {
    HOST : 'https://api.getui.com/apiex.htm',
    APPID : 'H6FYbDejks6VjMmW3uH7V6',
    APPKEY : '0PFWlKmLBN9YzhCfFWVgYA',
    MASTERSECRET : 'pvjCGtRZJx9SRVODkxc816'
    HOST: 'https://api.getui.com/apiex.htm',
    APPID: 'H6FYbDejks6VjMmW3uH7V6',
    APPKEY: '0PFWlKmLBN9YzhCfFWVgYA',
    MASTERSECRET: 'pvjCGtRZJx9SRVODkxc816'
};
// 三师后台
@ -44,13 +44,25 @@ let transServerConfig = {
    port: 8000
};
// 微信配置
let wechatConfig = {
    appId: 'wx1f129f7b51701428'
    , appSecret: '988f005d8309ed1795939e0f042431fb'
    , token: '27eb3bb24f149a7760cf1bb154b08040'
    , baseUrl: 'ehr.yihu.com/wlyy'
    , template: {
        // 咨询回复模板
        consultTemplate: '-dr4QNyFoRvVsf8uWxXMC1dRyjwnbUuJwJ21vBLhf18'
    }
};
exports.app = 'im.server';
exports.version = '1.2.5.20161107';
exports.debug = true;
exports.serverPort = 3000;
exports.sessionExpire = 1800;
exports.showSQL= true;
exports.showSQL = true;
exports.wlyyDbConfig = wlyyDbConfig;
exports.imDbConfig = imDbConfig;

+ 149 - 0
src/doctor/util/wechatUtil.js

@ -0,0 +1,149 @@
/**
 * 微信工具类
 *
 * Created by lyr-pc on 2016/11/25.
 */
"use strict"
var log = require('./log');
var configFile = require('../include/commons').CONFIG_FILE;
var config = require('../resources/config/' + configFile);
var wxTokenRepo = require('../repository/wechat.token.repo.js');
var https = require('https');
/**
 * 发送微信模板消息
 *
 * @param message {"touser":"","template_id":"","url":"","data":{"firts":{"value":"","color":""}}}
 */
function sendWxTemplateMessage(message, handler) {
    getWxAccessToken(function (err, token) {
        if (err) {
            log.error("get access_token failed:" + err);
            return;
        }
        var opt = {
            host: 'api.weixin.qq.com',
            path: '/cgi-bin/message/template/send?access_token=' + token,
            method: 'POST'
        };
        var msg = JSON.stringify(message);
        log.info("sending wechat template message:" + msg);
        // 发送模板消息
        var req = https.request(opt, function (res) {
            res.setEncoding('utf8');
            var data = "";
            res.on('data', (d) => {
                data += d;
            });
            res.on('end', () => {
                var result = JSON.parse(data);
                if (result && result.errcode === 0) {
                    log.info("send wechat template message success:" + msg);
                    if (handler) {
                        handler(null, result);
                    }
                } else {
                    log.error("send wechat template message failed:" + msg);
                    if (handler) {
                        handler(result, null);
                    }
                }
            });
            res.on('error', function (err) {
                log.error('send wechat template message failed: ' + err.message);
                if (handler) {
                    handler(err, null);
                }
            });
        }).on('error', (e) => {
            log.error("send wechat template message failed:" + e.message);
            if (handler) {
                handler(e, null);
            }
        });
        req.end(msg);
    });
};
/**
 * 获取微信access_token
 *
 * @param handler 回调函数
 */
function getWxAccessToken(handler) {
    wxTokenRepo.getAccessToken(function (err, result) {
        if (err) {
            log.error("get wechat accessToken failed", err);
            return;
        }
        var data = result && result.length > 0 ? result[0] : null;
        var accessToken = "";
        if (data) {
            // 判断access_token是否有效
            if ((new Date().getTime() - data.add_timestamp) < (data.expires_in * 1000)) {
                accessToken = data.access_token;
            }
        }
        // access_token为空时从微信重新获取并执行回调,否则直接执行回调
        if (!accessToken) {
            var token_url = "https://api.weixin.qq.com/cgi-bin/token?";
            var params = "grant_type=client_credential&appid=" + config.wechatConfig.appId
                + "&secret=" + config.wechatConfig.appSecret;
            // 从微信获取access_token
            https.get(token_url + params, function (res) {
                var data = '';
                res.on('data', (d) => {
                    data += d;
                });
                res.on('end', () => {
                    data = data ? JSON.parse(data) : {};
                    if (data.access_token) {
                        accessToken = data.access_token;
                        var expiresIn = data.expires_in;
                        if (handler) {
                            // 执行回调
                            handler(null, accessToken);
                        }
                        var tokenData = [accessToken, new Date().getTime(), expiresIn, new Date()];
                        // 保存access_token
                        wxTokenRepo.saveAccessToken(tokenData, function (err, result) {
                            if (err) {
                                log.error("insert wechat access_token failed:" + err.message);
                            }
                        })
                    } else {
                        log.error("get wechat access_token failed:" + data);
                        if (handler) {
                            // 执行回调
                            handler(data, null);
                        }
                    }
                });
            }).on('error', (e) => {
                log.error("get wechat access_token from wechat failed:" + e.message);
                if (handler) {
                    // 执行回调
                    handler(e, null);
                }
            });
        } else {
            if (handler) {
                // 执行回调
                handler(null, accessToken);
            }
        }
    });
};
exports.sendWxTemplateMessage = sendWxTemplateMessage;
exports.getWxAccessToken = getWxAccessToken;