/** * 用户微信客户端。 */ "use strict"; let RedisClient = require('../../repository/redis/redis.client'); let RedisModel = require('../redis.model'); let ObjectUtil = require("../../util/object.util.js"); let ModelUtil = require('../../util/model.util'); let WechatSDK = require('../../util/wechat.sdk'); let PatientRepo = require('../../repository/oracle/patient.repo'); let TopicRepo = require("../../repository/oracle/topics.repo.js"); let ParticipantRepo = require("../../repository/oracle/participant.repo"); let redisConn = RedisClient.redisClient().connection; let clientCache = require('../socket.io/client.cache').clientCache(); let configFile = require('../../include/commons').CONFIG_FILE; let config = require('../../resources/config/' + configFile); let log = require("../../util/log.js"); let https = require('https'); let http = require('http'); let async = require('async'); let querystring = require('querystring'); let HlwyyWechatAssistantSDK = require("../../util/hlwyyWechatAssistant.sdk"); var reqq = require('request'); const CONTENT_TYPES = require('../../include/commons').CONTENT_TYPES; const SESSION_TYPES = require('../../include/commons').SESSION_TYPES; const SOCKET_TYPES = require('../../include/commons').SOCKET_TYPES; const REDIS_KEYS = require('../../include/commons').REDIS_KEYS; class WechatClient extends RedisModel { constructor() { super(); } /** * 取得用户微信端状态。若Redis中找不到,则从MySQL中查找。 * * @param userId * @param handler */ static getWechatStatus(userId, handler) { redisConn.hgetallAsync(RedisModel.makeRedisKey(REDIS_KEYS.UserWechatStatus, userId)) .then(function (status) { if (status == null) { PatientRepo.findWechatOpenId(userId, handler); } else { handler(null, {openid: status.openid}); } }) .catch(function (err) { handler(err, null); }); } /** * 向微信端用户发送消息。若用户微信端在线,通过Web Socket推送给患者,如果不在线则通过微信的模板消息。 * * 只推送文本、图片及语音消息 * * @param targetUserId * @param message 消息体 */ static sendMessage(targetUserId, targetUserName, message) { if (message&&(message.content_type == CONTENT_TYPES.PlainText || message.content_type == CONTENT_TYPES.Image || message.content_type == CONTENT_TYPES.Audio|| message.content_type == CONTENT_TYPES.PrescriptionBloodStatus || message.content_type == CONTENT_TYPES.PrescriptionFollowupContent || message.content_type == CONTENT_TYPES.ReservationDoorCardInfo || message.content_type == CONTENT_TYPES.ChangeDoorCardInfo || message.content_type == CONTENT_TYPES.ChangeDoorDoctor || message.content_type == CONTENT_TYPES.ChangeDoorPackageItems || message.content_type == CONTENT_TYPES.VideoAnswerStatus || message.content_type == CONTENT_TYPES.Screening || message.content_type == CONTENT_TYPES.PrescriptionReject || message.content_type == CONTENT_TYPES.PrescriptionSuggest || message.content_type == CONTENT_TYPES.ConsultSuggest || message.content_type == CONTENT_TYPES.PayMessage )) { let patientClient = clientCache.findById(targetUserId); let pc_patientClient = clientCache.findById("pcpatient_"+targetUserId); let doctorClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR); let pc_doctorClient = clientCache.findByIdAndType("pc_"+message.sender_id,SOCKET_TYPES.PC_DOCTOR); let pc_patient_system_Client = clientCache.findByIdAndType("pcpatient_system_"+targetUserId,SOCKET_TYPES.PC_PATIENT_SYSTEM); var count = 0; if (patientClient || pc_patientClient || pc_patient_system_Client) { if(patientClient){ log.warn("User's wechat endpoint is online, sending via web socket. User id: ", targetUserId); WechatClient.sendViaWebSocket(patientClient.socket, message); } if(pc_patientClient){ log.warn("User's pc endpoint is online, sending via web socket. User id: ", targetUserId); WechatClient.sendViaWebSocket(pc_patientClient.socket, message); } if(pc_patient_system_Client){ log.warn("User's pc systme endpoint is online, sending via web socket. User id: ", targetUserId); WechatClient.sendViaWebSocket(pc_patient_system_Client.socket, message); } if(doctorClient && (patientClient || pc_patientClient) ){ log.error("doctor sessionid "+doctorClient.sessionId); if(patientClient && patientClient.sessionId==doctorClient.sessionId){ log.error("patient sessionid "+patientClient.sessionId); //用户socket在线,推送给用户后,告知医生此消息已读 WechatClient.updateParticipantLastFetchTime(doctorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp)); WechatClient.sendReadDoctor(doctorClient.socket, message); } if(pc_patientClient && pc_patientClient.sessionId==doctorClient.sessionId){ log.error("pc_patient sessionid "+pc_patientClient.sessionId); //用户socket在线,推送给用户后,告知医生此消息已读 WechatClient.updateParticipantLastFetchTime(doctorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp)); WechatClient.sendReadDoctor(doctorClient.socket, message); } }else{ count++; } if(pc_doctorClient){ log.error("pc_doctor sessionid "+pc_doctorClient.sessionId); if(patientClient){ log.error("patient sessionid "+patientClient.sessionId); if(patientClient.sessionId==pc_doctorClient.sessionId){ //用户socket在线,推送给用户后,告知医生此消息已读 WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp)); WechatClient.sendReadDoctor(pc_doctorClient.socket, message); } } if(pc_patientClient){ log.error("pc_patient sessionid "+pc_patientClient.sessionId); if(pc_patientClient.sessionId==pc_doctorClient.sessionId){ //用户socket在线,推送给用户后,告知医生此消息已读 WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp)); WechatClient.sendReadDoctor(pc_doctorClient.socket, message); } } }else{ count++; } if(count==0){ log.error("doctor client not found"); } } else { log.info("User's wechat and pc endpoint is not online, sending via wechat template message. User id: ", targetUserId); var isSendWXTem = true;//是否发送微信模板 if(message.content_type == CONTENT_TYPES.PrescriptionBloodStatus||message.content_type == CONTENT_TYPES.PrescriptionFollowupContent){ var content = JSON.parse(message.content); if(content.isSendWxTemplate){ message.content = content.text; }else { isSendWXTem = false; } } if(isSendWXTem){ //发送第三方接口的微信模版消息 WechatClient.sendThirdMessageTemplate(targetUserId, targetUserName, message); //发送厦门i健康的微信模版消息 // WechatClient.sendViaMessageTemplate(targetUserId, targetUserName, message); } } } else if(message.content_type == CONTENT_TYPES.TopicEnd){ let patientClient = clientCache.findById(targetUserId); if(patientClient){//结束咨询的告知患者 WechatClient.sendViaWebSocket(patientClient.socket, message); } let pc_patientClient = clientCache.findById("pcpatient_"+targetUserId); if(pc_patientClient)//结束咨询的告知患者 { WechatClient.sendViaWebSocket(pc_patientClient.socket, message); } } }; static sendViaWebSocket(socket, message) { socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: message.content_type, content: message.content, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, sender_img : message.sender_img }); } static sendAllRead(doctorId,sessionId){ let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR); let pc_doctorClient = clientCache.findByIdAndType("pc_"+doctorId,SOCKET_TYPES.PC_DOCTOR); if(doctorClient){ if(doctorClient.sessionId==sessionId){ doctorClient.socket.emit('message',{ read:"all"}); }else{ log.warn(" doctor not in the same session "); } }else{ if(pc_doctorClient && pc_doctorClient.sessionId == sessionId){ pc_doctorClient.socket.emit('message',{ read:"all"}); }else{ log.warn(doctorId+" target doctor is not online!"); } } } static sendMucAllRead(doctorId,loginUserId,sessionId){ let loginClinet = clientCache.findByIdAndType(loginUserId,SOCKET_TYPES.DOCTOR); if(loginClinet){ //muc是医生来获取数据不能更新成已读 log.warn("type is muc login is doctor not send all read to other doctor!") return; } let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR); let pc_doctorClient = clientCache.findByIdAndType("pc_"+doctorId,SOCKET_TYPES.PC_DOCTOR); if(doctorClient){ if(doctorClient.sessionId==sessionId){ doctorClient.socket.emit('message',{ read:"all"}); }else{ log.warn(" doctor not in the same session "); } }else{ if(pc_doctorClient && pc_doctorClient.sessionId == sessionId){ pc_doctorClient.socket.emit('message',{ read:"all"}); }else{ log.warn(doctorId+" target doctor is not online!"); } } } static sendReadDoctor(socket, message) { socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: message.content_type, content: message.content, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, read:"one" }); } static sendReadDoctorByDoctorId(doctorId, message) { let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR); let pc_doctorClient = clientCache.findByIdAndType("pc_"+doctorId,SOCKET_TYPES.PC_DOCTOR); if(!doctorClient&&!pc_doctorClient){ log.warn("target doctor is not online!"); return; } let sendDoctorClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR); if(!sendDoctorClient){ sendDoctorClient = clientCache.findByIdAndType("pc_"+message.sender_id,SOCKET_TYPES.PC_DOCTOR); } var count = 0; if(doctorClient&&sendDoctorClient&&sendDoctorClient.sessionId==doctorClient.sessionId){ WechatClient.updateParticipantLastFetchTime(doctorClient.sessionId, doctorId, ObjectUtil.timestampToLong(message.timestamp)); sendDoctorClient.socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: message.content_type, content: message.content, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, read:"one" }); }else{ count++; } //发送pc版医生端 if(pc_doctorClient&&sendDoctorClient&&sendDoctorClient.sessionId==pc_doctorClient.sessionId){ WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, doctorId, ObjectUtil.timestampToLong(message.timestamp)); pc_doctorClient.socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: message.content_type, content: message.content, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, read:"one" }); }else{ count++; } if(count==2){ log.warn("doctor is not in the same session or is not online"); } } static sendSocketMessageToDoctor(doctorId, message) { let doctorClient = clientCache.findByIdAndType(doctorId,SOCKET_TYPES.DOCTOR); let pc_doctorClient = clientCache.findByIdAndType("pc_"+doctorId,SOCKET_TYPES.PC_DOCTOR); if(!doctorClient&&!pc_doctorClient){ log.warn("target doctor is not online!"); return; } // let sendClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR);//app医生发送的消息 // if(!sendClient){//pc医生发送的消息 // sendClient = clientCache.findByIdAndType("pc_"+message.sender_id,SOCKET_TYPES.PC_DOCTOR); // } // if(!sendClient){//居民发送的消息 // sendClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.PATIENT); // } var count = 0; if(doctorClient&&message.session_id==doctorClient.sessionId){ WechatClient.updateParticipantLastFetchTime(doctorClient.sessionId, doctorId, ObjectUtil.timestampToLong(message.timestamp)); doctorClient.socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: message.content_type, content: message.content, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, }); }else{ count++; } //发送pc端 - PC端消息不做sessionid的判断,前端自己判断消息归属于哪个会话,自行渲染--20191012-huangwenjie // if(pc_doctorClient&&message.session_id==pc_doctorClient.sessionId){ if(pc_doctorClient){ WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, doctorId, ObjectUtil.timestampToLong(message.timestamp)); pc_doctorClient.socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: message.content_type, content: message.content, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, }); }else{ count++; } if(count==2){ log.warn("doctor is not in the same session or is not online"); } } /** * 推送MDT,医生外层新消息 * @param doctorId * @param message */ static sendMDTSocketMessageToDoctor(doctorId, message) { // let doctorMDTClient = clientCache.findByIdAndType("pcim_"+doctorId,SOCKET_TYPES.PCIM_DOCTOR); let doctorSYSTEMClient = clientCache.findByIdAndType("pc_system_"+doctorId,SOCKET_TYPES.PC_DOCTOR_SYSTEM); let doctorAPPSYSTEMClient = clientCache.findByIdAndType("doctor_system_"+doctorId,SOCKET_TYPES.DOCTOR_SYSTEM); //外层 if(!doctorSYSTEMClient){ log.warn("target system doctor is not online!"); }else{ doctorSYSTEMClient.socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: 1, content: {"socket_sms_type":4}, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, patient_name:message.patient_name, patient_age:message.patient_age, patient_sex:message.patient_sex }); } if(!doctorAPPSYSTEMClient){ log.warn("target system app doctor is not online!"); }else{ doctorAPPSYSTEMClient.socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: 1, content: {"socket_sms_type":4}, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, patient_name:message.patient_name, patient_age:message.patient_age, patient_sex:message.patient_sex }); } } static sendPcImSocket(targetId, message, sessionType) { if (message.content_type == CONTENT_TYPES.PlainText || message.content_type == CONTENT_TYPES.Image || message.content_type == CONTENT_TYPES.Audio|| message.content_type == CONTENT_TYPES.Video|| message.content_type == CONTENT_TYPES.GoTo|| sessionType==SESSION_TYPES.SYSTEM) { let pcim_doctorClient = clientCache.findByIdAndType("pcim_"+targetId,SOCKET_TYPES.PCIM_DOCTOR); if(pcim_doctorClient) { let customData = { session_id: message.session_id||'', session_type: sessionType, from: message.sender_id|| '', data: message.content, business_type: message.business_type || 1 }; pcim_doctorClient.socket.emit('message', { session_id: message.session_id||'', session_type: sessionType, from: message.sender_id|| '', data: message.content, business_type: message.business_type || 1, sender_name: message.sender_name, content_type: message.content_type, content: message.content, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, patient_name:message.patient_name, patient_age:message.patient_age, patient_sex:message.patient_sex }); } } } static sendSocketMessageToPatient(patientId, message) { let patientClient = clientCache.findByIdAndType(patientId,SOCKET_TYPES.PATIENT); let pc_patientClient = clientCache.findByIdAndType("pcpatient_"+patientId,SOCKET_TYPES.PC_PATIENT); if(!patientClient&&!pc_patientClient){ log.warn("target patient is not online!"); return; } // let sendClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.DOCTOR);//app医生发送的消息 // if(!sendClient){//pc医生发送的消息 // sendClient = clientCache.findByIdAndType("pc_"+message.sender_id,SOCKET_TYPES.PC_DOCTOR); // } // if(!sendClient){//居民发送的消息 // sendClient = clientCache.findByIdAndType(message.sender_id,SOCKET_TYPES.PATIENT); // } var count = 0; if(patientClient&&message.session_id==patientClient.sessionId){ WechatClient.updateParticipantLastFetchTime(patientClient.sessionId, patientId, ObjectUtil.timestampToLong(message.timestamp)); patientClient.socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: message.content_type, content: message.content, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, }); }else{ count++; } //发送pc端 if(pc_patientClient&&message.session_id==pc_patientClient.sessionId){ WechatClient.updateParticipantLastFetchTime(pc_patientClient.sessionId, patientId, ObjectUtil.timestampToLong(message.timestamp)); pc_patientClient.socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: message.content_type, content: message.content, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, }); }else{ count++; } if(count==2){ log.warn("patient is not in the same session or is not online"); } } //推送居民、居民PC、医生、医生PC外层推送 static sendSystemSocketMessage(targetUserId, message) { //居民外层消息推送 let patientClient = clientCache.findByIdAndType("patient_system_"+targetUserId,SOCKET_TYPES.PATIENT_SYSTEM); let pc_patientClient = clientCache.findByIdAndType("pcpatient_system_"+targetUserId,SOCKET_TYPES.PC_PATIENT_SYSTEM); if(!patientClient&&!pc_patientClient){ log.warn("target patient systemt is not online!"); // return; } var patientcount = 0; if(patientClient&&message.session_id==patientClient.sessionId){ WechatClient.updateParticipantLastFetchTime(patientClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp)); patientClient.socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: message.content_type, content: message.content, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, }); }else{ patientcount++; } //发送pc端 if(pc_patientClient&&message.session_id==pc_patientClient.sessionId){ WechatClient.updateParticipantLastFetchTime(pc_patientClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp)); pc_patientClient.socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: message.content_type, content: message.content, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, }); }else{ patientcount++; } if(patientcount==2){ log.warn("patient system is not in the same session or is not online"); } //医生外层消息推送 let doctorClient = clientCache.findByIdAndType("doctor_system_"+targetUserId,SOCKET_TYPES.DOCTOR_SYSTEM); let pc_doctorClient = clientCache.findByIdAndType("pc_system_"+targetUserId,SOCKET_TYPES.PC_DOCTOR_SYSTEM); if(!doctorClient&&!pc_doctorClient){ log.warn("target doctor system is not online!"); // return; } var doctorcount = 0; if(doctorClient&&message.session_id==doctorClient.sessionId){ WechatClient.updateParticipantLastFetchTime(doctorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp)); doctorClient.socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: message.content_type, content: message.content, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, }); }else{ doctorcount++; } //发送pc端 - PC端消息不做sessionid的判断,前端自己判断消息归属于哪个会话,自行渲染--20191012-huangwenjie // if(pc_doctorClient&&message.session_id==pc_doctorClient.sessionId){ if(pc_doctorClient){ WechatClient.updateParticipantLastFetchTime(pc_doctorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp)); pc_doctorClient.socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: message.content_type, content: message.content, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, }); }else{ doctorcount++; } if(doctorcount==2){ log.warn("doctor system is not in the same session or is not online"); } } //推送托盘消息 static sendMDTSystemSocketMessage(targetUserId, message) { //居民外层消息推送 let mdtDcotorClient = clientCache.findByIdAndType("pcim_"+targetUserId,SOCKET_TYPES.PCIM_DOCTOR); if(!mdtDcotorClient){ log.warn("target mdt doctor is not online!"); } var mdtDoctorCount = 0; if(mdtDcotorClient&&message.session_id==mdtDcotorClient.sessionId){ WechatClient.updateParticipantLastFetchTime(mdtDcotorClient.sessionId, targetUserId, ObjectUtil.timestampToLong(message.timestamp)); mdtDcotorClient.socket.emit('message', { id: message.id, session_id: message.session_id, sender_id: message.sender_id, sender_name: message.sender_name, content_type: message.content_type, content: message.content, timestamp: ObjectUtil.timestampToLong(message.timestamp), type: message.content_type, // legacy support name: message.sender_name, }); }else{ mdtDoctorCount++; } if(mdtDoctorCount==2){ log.warn("doctor system is not in the same session or is not online"); } } /** * * 发送微信模板消息给居民 * * @param targetUserId * @param message */ static sendViaMessageTemplate(targetUserId, targetUserName, message) { async.waterfall([ // 获取微信openid function (callback) { PatientRepo.findWechatOpenIds(targetUserId, function (err, res) { if (err) { ModelUtil.logError("Get wechat openid failed", err); return; } var map = new Map(); res.forEach(function (participant) { let openid = participant.openid; if (targetUserId==participant.code) { if (!openid) { ModelUtil.logError("User haven't bound with wechat, user id: " + targetUserId); } map.set("openid",participant); }else { if(!map.has(openid)){ map.set(openid,participant); } } }) // // let openid = result && result.length > 0 ? result[0].openid : null; // if (!openid) { // ModelUtil.logError("User haven't bound with wechat, user id: " + targetUserId); // return; // } // // log.warn("Send via wechat message template, user id: " + targetUserId + ", openid: " + openid); callback(null, map); }); }, // 获取议题信息 function (map, callback) { TopicRepo.findLastTopicStatusAndType(message.session_id, function (err, res) { if (err) { ModelUtil.logError("Get topic failed", err); return; } if (!res || res.length == 0) { ModelUtil.logError("Unable to find session last topic"); return; } callback(null, map, message.sender_name, res[0]); }); }, // 发送消息 function (map, senderName, topic,callback) { let replyContent = message.content; switch (Number.parseInt(message.content_type)) { case CONTENT_TYPES.Image: replyContent = "[图片]"; break; case CONTENT_TYPES.Audio: replyContent = "[语音]"; break; default: break; } var patient = map.get("openid"); map.delete("openid"); let agent = topic.agent; let consultTitle = null; let description = null; let url = config.wechatConfig.baseUrl; switch (topic.type) { case 8: consultTitle = "续方"; description = "续方咨询"; url = url + "/wx/html/yszx/html/prescription-consulting.html"; case 11: consultTitle = "上门服务"; description = "上门服务咨询"; url = url + "wx/html/appoint_service/html/appoint-serviceDetail.html"; default: consultTitle = "健康"; description = topic.description; url = url + "/wx/html/yszx/html/consulting-doctor.html"; } if(agent){//代理人发起的议题 var agentOpenid = ""; if(map.size>0){ for(var key of map.keys()){ var member = map.get(key); if(agent == member.code){ agentOpenid = key; var openid = key; var first = "您的家人("+patient.name+")的"+consultTitle+"咨询有新的回复"; // 发送模板消息 WechatSDK.sendTemplateMessage({ touser: openid, name: member.name, patient: member.code, template_id: config.wechatConfig.template.consultTemplate, url: url + "?openid=" + openid + "&type="+topic.type+"&doctor="+message.sender_id+ "&consult=" + topic.id + "&toUser=" + member.code + "&toName=" + member.name+"&represented="+patient.code, data: { first: {value: first, color: "#000000"} , remark: {value: "", color: "#000000"} , keyword1: {value: description, color: "#000000"} , keyword2: {value: replyContent, color: "#000000"} , keyword3: {value: senderName, color: "#000000"} } }, function (err, res) { err ? log.error(err) : log.info(res); }); } } } if(patient.openid&&patient.openid!=agentOpenid){ var first = "您的"+consultTitle+"咨询有新的回复"; // 发送模板消息 WechatSDK.sendTemplateMessage({ touser: patient.openid, name: targetUserName, patient: targetUserId, template_id: config.wechatConfig.template.consultTemplate, url: url + "?openid=" + patient.openid +"&type="+topic.type+"&doctor="+message.sender_id+ "&consult=" + topic.id + "&toUser=" + targetUserId + "&toName=" + targetUserName+"&represented="+patient.code, data: { first: {value: first, color: "#000000"} , remark: {value: "", color: "#000000"} , keyword1: {value: description, color: "#000000"} , keyword2: {value: replyContent, color: "#000000"} , keyword3: {value: senderName, color: "#000000"} } }, function (err, res) { err ? log.error(err) : log.info(res); }); } }else {//自己发起的议题 // 发送模板消息 if(patient.openid){ WechatSDK.sendTemplateMessage({ touser: patient.openid, name: targetUserName, patient: targetUserId, template_id: config.wechatConfig.template.consultTemplate, url: url + "?openid=" + patient.openid +"&type="+topic.type+"&doctor="+message.sender_id+ "&consult=" + topic.id + "&toUser=" + targetUserId + "&toName=" + targetUserName+"&represented="+patient.code, data: { first: {value: "您的"+consultTitle+"咨询有新的回复", color: "#000000"} , remark: {value: "", color: "#000000"} , keyword1: {value: description, color: "#000000"} , keyword2: {value: replyContent, color: "#000000"} , keyword3: {value: senderName, color: "#000000"} } }, function (err, res) { err ? log.error(err) : log.info(res); }); } if(map.size>0){ for(var key of map.keys()){ if(!patient.openid||key!=patient.openid){ var member = map.get(key); var openid = key; var first = "您的家人("+patient.name+")的"+consultTitle+"咨询有新的回复"; // 发送模板消息 WechatSDK.sendTemplateMessage({ touser: openid, name: member.name, patient: member.code, template_id: config.wechatConfig.template.consultTemplate, url: url + "?openid=" + openid +"&type="+topic.type+"&doctor="+message.sender_id+ "&consult=" + topic.id + "&toUser=" + member.code + "&toName=" + member.name+"&represented="+patient.code, data: { first: {value: first, color: "#000000"} , remark: {value: "", color: "#000000"} , keyword1: {value: description, color: "#000000"} , keyword2: {value: replyContent, color: "#000000"} , keyword3: {value: senderName, color: "#000000"} } }, function (err, res) { err ? log.error(err) : log.info(res); }); } } } } callback(null, null); } ], function (err, res) { if (!err) { log.info("Send via wechat template message, DONE!"); } }); }; static updateParticipantLastFetchTime(sessionId, userId, score) { score = score + 1000; let participantsKey = RedisModel.makeRedisKey(REDIS_KEYS.SessionParticipants, sessionId); redisConn.zaddAsync(participantsKey, score, userId) .then(function (res) { ParticipantRepo.updateLastFetchTime(new Date(score), sessionId, userId, function (err, res) { if (err) { log.error("Update participant last fetch time failed: ", err); } }); }) .catch(function (err) { log.error("Update participant last fetch time failed: ", err); }); }; /** * 发送第三方接口的微信模版消息 * @param targetUserId * @param message */ static sendThirdMessageTemplate(targetUserId, targetUserName, message) { async.waterfall([ // 获取微信openid function (callback) { PatientRepo.findOne(targetUserId, function (err, res) { if (err) { ModelUtil.logError("Get wechat openid failed", err); return; } var map = new Map(); res.forEach(function (participant) { let openid = participant.openid; let idcard = participant.idcard; let mobile = participant.mobile; let name = participant.name; let id = participant.id; map.set("openid",openid); map.set("idcard",idcard); map.set("mobile",mobile); map.set("name",name); map.set("id",id); }) // // let openid = result && result.length > 0 ? result[0].openid : null; // if (!openid) { // ModelUtil.logError("User haven't bound with wechat, user id: " + targetUserId); // return; // } // // log.warn("Send via wechat message template, user id: " + targetUserId + ", openid: " + openid); callback(null, map); }); }, // 获取议题信息 function (map, callback) { TopicRepo.findLastTopicStatusAndType(message.session_id, function (err, res) { if (err) { ModelUtil.logError("Get topic failed", err); return; } if (!res || res.length == 0) { ModelUtil.logError("Unable to find session last topic"); return; } callback(null, map, message.sender_name, res[0]); }); }, // 发送消息 function (map, senderName, topic,callback) { let replyContent = message.content; switch (Number.parseInt(message.content_type)) { case CONTENT_TYPES.Image: replyContent = "[图片]"; break; case CONTENT_TYPES.Audio: replyContent = "[语音]"; break; default: break; } let consultTitle = null; let description = null; let url = config.thirdApiMessageConfig.baseUrl; switch (topic.type) { case 8: consultTitle = "续方"; description = "续方咨询"; url = url + "/wx/html/yszx/html/prescription-consulting.html"; case 11: consultTitle = "上门服务"; description = "上门服务咨询"; url = url + "wx/html/appoint_service/html/appoint-serviceDetail.html"; default: consultTitle = "咨询回复提醒"; description = topic.description; if("xmijk" == config.imClientType.id){ url = "https://zb.xmtyw.cn/ims-wx/index.html#/chatRoom?type="+topic.type+"&consultCode="+topic.id; }else if("zsyy" == config.imClientType.id){ url = "https://hlwyy.xmzsh.com/ims-wx/index.html#/chatRoom?type="+topic.type+"&consultCode="+topic.id; }else if("xm_ykyy_wx" == config.imClientType.id){ url = "https://intel.yanketong.com/ims-wx/index.html#/chatRoom?type="+topic.type+"&consultCode="+topic.id; }else{} } // 发送模板消息 if(map != null){ let userName = map.get("name"); let idCard = map.get("idcard"); let phone = map.get("mobile"); let title = consultTitle; let content = "您的咨询有新的回复"; let contentString = replyContent; // log.info("推送居民公众号:params:"+params) let params = 'senderName='+encodeURIComponent(senderName)+'&userName='+encodeURIComponent(userName)+'&idCard='+idCard+"&phone="+phone+'&title='+encodeURIComponent(consultTitle)+'&content='+encodeURIComponent(description)+'&contentString='+encodeURIComponent(contentString)+'&url='+encodeURIComponent(url); HlwyyWechatAssistantSDK.request(userName,idCard,phone,title,content,contentString,url,params, function (err, res) { // WlyyAssistantSDK.request('admin', '0a5c5258-8863-4b07-a3f9-88c768528ab4', '', 'admin_imei', '/doctor/feldsher/sendDoctorTemplate', param, function (err, res) { // WlyySDK.request('admin', '0a5c5258-8863-4b07-a3f9-88c768528ab4', '', 'admin_imei', '/doctor/feldsher/sendDoctorTemplate?' + params, 'GET', function (err, res) { if(err){ log.error(err); }else { log.info(res); } }); } callback(null, null); } ], function (err, res) { if (!err) { log.info("Send via wechat template message, DONE!"); } }); }; } module.exports = WechatClient;