Saturday, 16 April 2016

package com.gb.md.common

class SMS {
Long accountId
String message
Long mobileNumber
String status

static constraints = {
accountId nullable:true
}

static mapping = {
message type: 'text'
}

}

======================================================================================================================================

package com.gb.md.common

import org.springframework.context.i18n.LocaleContextHolder as LCH

class MassCommunicationController extends BaseController{

def messageSource
def smsService
def mailService

def sendSMS(mobileNumber,message){
   //println "------mobileNumber  "+mobileNumber+" message "+message
def sendStatus = "Not Sent"
def userName = messageSource.getMessage('com.gb.md.sms.userName',null,LCH.getLocale())
def password = messageSource.getMessage('com.gb.md.sms.password',null,LCH.getLocale())
def senderId = messageSource.getMessage('com.gb.md.sms.senderId',null,LCH.getLocale())
def parameters =  [to:mobileNumber, sender:senderId, message: message,userName:userName,password:password]
//connection opened
def connection = smsService.urlConnection(messageSource.getMessage('com.gb.md.sms.sendUrl',null,LCH.getLocale()),parameters)
parameters = "username="+userName+"&password="+password+"&to="+mobileNumber+"&from="+senderId+"&message="+message
def sendSms = true
def checkMap = checkSMSCredentials()
sendSms = checkMap.get('result')
//println "----- "+sendSms
if(userName && senderId && password && sendSms) sendStatus = smsService.writeStream(connection,parameters)
//println "send status : "+sendStatus
(sendStatus.trim().equalsIgnoreCase("Message GID=<br />ID=") || sendStatus.trim() == "" || sendStatus == 'Invalid user credentials' || sendStatus.trim() == "Not Sent") ? (sendStatus="Not Sent") : (sendStatus="Sent")

def smsObj = new SMS(
status:sendStatus,
   message:message,
   mobileNumber:mobileNumber
   )

smsObj.accountId = session?.loggedInUser?.account?.id
if(sendStatus=="Sent" && checkMap.get('updateSmsAccount')){

def obj = SMSAccount.findByAccountId(smsObj.accountId)
obj.remainingSms -= (Math.ceil(message.toString().length() / (messageSource.getMessage('com.gb.md.sms.maxcount',null,LCH.getLocale()) as int)))
obj.save(flush:true)
}

smsObj.save(flush:true)
return sendStatus
}

def getSMSCount(params){
def userName = messageSource.getMessage('com.gb.md.sms.userName',null,LCH.getLocale())
def password = messageSource.getMessage('com.gb.md.sms.password',null,LCH.getLocale())
def parameters = "username="+userName+"&password="+password
def connection = smsService.urlConnection(messageSource.getMessage('com.gb.md.sms.sendUrl',null,LCH.getLocale()),null)
return smsService.writeStream(connection,parameters)
}

def checkSMSCredentials(){
def map = [:]
try{
if(session?.loggedInUser == null || session?.loggedInUser?.accountRoles?.role?.id < 4){
map.put('result',true)
}
else if(session?.loggedInUser && session?.loggedInUser?.user?.status == 'Waiting For Verification Code'){
map.put('result',true)
}
else if(session?.loggedInUser?.user?.status == 'Active' && session?.loggedInUser?.user?.approval && session?.loggedInUser?.accountRoles?.role?.id > 3){
def smsAccount = SMSAccount.findByAccountId(session?.loggedInUser?.account?.id)
if(!getAuthorizationByAccount()?.generalSms){
map.put('result',false)
}
else if(smsAccount && smsAccount?.remainingSms == 0){
map.put('result',false)
map.put('msg','SMS credits not available')
}
else{
map.put('result',true)
map.put('updateSmsAccount',true)
}
}
else{
map.put('result',false)
}
}
catch(Exception e){
println e.printStackTrace()
}
return map
}

def sendEmail(toMail,sub,bodyData) {
try{
def roleId
if(session?.loggedInUser != null)  roleId = session?.loggedInUser?.accountRoles?.role?.id
if(toMail.toString().length() == 0) {
toMail = 'vamsikrishna@greenbuds.co.in'
sub = 'Exception from meedcotor'
}
if(session.loggedInUser == null || (((roleId == 4 || roleId == 8 || roleId == 9)) && getAuthorizationByAccount()?.generalEmail) || roleId==5 || roleId==7 || roleId==2 || roleId==3  ){
mailService.sendMail {
from messageSource.getMessage('com.gb.md.mail.from',null,LCH.getLocale())
to toMail
subject sub
body bodyData
}
}
}
catch(Exception e){
println e.printStackTrace()
}
}

def sendEmailTemplate(toMail,template,sub,params){
try{
def roleId
def frommail = messageSource.getMessage('com.gb.md.mail.from',null,LCH.getLocale())
def checkPrevilige = false
//@janaki
if(params.doctorMailId) frommail = params.doctorMailId
if(params.action == "sendMessages"){
frommail = params.frommail
sub = params.sub
}

if(toMail.toString().length() == 0) {
toMail = 'vamsikrishna@greenbuds.co.in'
sub = 'Exception from meedcotor'
}
if(session?.loggedInUser != null) roleId = session?.loggedInUser?.accountRoles?.role?.id
if(roleId == 4 || roleId == 8 || roleId == 9){
if(params.source == 'Appointments') checkPrevilige = getAuthorizationByAccount()?.appointmentEmail
else checkPrevilige = getAuthorizationByAccount()?.generalEmail
}
if(session.loggedInUser == null || checkPrevilige || roleId==5 || roleId==7 || roleId==2 || roleId==3 ){
mailService.sendMail {
multipart true
to toMail
from frommail
subject sub
html  g.render( template: template,params:params)
}
}
}
catch(Exception e){
println e.printStackTrace()
}
}

def sendEmailWithAttachment(params){
try{
def file = params.file
mailService.sendMail {
multipart true
to params.toMail
from params.fromMail
subject params.mailSubject
body "You can find the Invoice Receipt"
attachBytes "${file}.pdf", 'application/pdf', new File(servletContext.getRealPath("/reports1/${file}.pdf")).readBytes()
}
}
catch(Exception e){
println e.printStackTrace()
}
}
}

==============================================================================================

package com.gb.md.common

import com.gb.md.common.BaseService
import org.springframework.context.i18n.LocaleContextHolder as LCH

/**
 *
 * @author acheemakurthi
 *
 */
class SmsService extends BaseService{

def messageSource

SmsService(){
super(SMS.class)
}

/**
* responsible to open the connection to sms service
* @return urlConnection
*/
def urlConnection(smsUrl, properties = null){
// Client Meedoctor Url
// http://sms.meedoctor.in/api/sendmsg.php?user=meedoctor1&pass=meedoctor&sender=MEEDOC&phone=9299452498&text=hisms&priority=sdnd&stype=normal
HttpURLConnection urlConnection = null;
def userName = messageSource.getMessage('com.gb.md.sms.userName',null,LCH.getLocale())
def password = messageSource.getMessage('com.gb.md.sms.password',null,LCH.getLocale())
def parameters = ""
if(properties){
parameters = "username=$userName&password=$password&to=${properties.to}&from=${properties.sender}&message=${properties.message}"
}
else parameters = "username=$userName&password=$password"
def mainUrl = smsUrl + parameters
URL url = new URL(mainUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
return urlConnection
}

/**
* Give the response of an action
* @param connection
* @return
*/
def readStream(connection){
BufferedReader buff = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
String respons = "";
while ((line = buff.readLine()) != null) {
respons = respons + line;
}
buff.close();
return respons
}

/**
* Connecting to the link
* @param connection
* @param data
* @return
*/
def writeStream(connection, data = null){
BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());
out.write(data.getBytes());
out.flush();
out.close();
readStream(connection)
}
}

==================================================================================================================================================

package com.gb.md.common

import groovy.sql.Sql

import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit

import org.springframework.context.i18n.LocaleContextHolder as LCH

class NotificationService extends BaseService{
def mailService
def dataSource
def messageSource
def smsService

def scheduleForVaccination(){
Runnable runnable = new Runnable() {
public void run() {
vaccinationDetails()
aboutToExpire()
accountExpired()
}
};
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor()
service.scheduleAtFixedRate(runnable, 0, 24, TimeUnit.HOURS);
}

def vaccinationDetails(){
def sql = new Sql(dataSource)
def childs = sql.rows("select * from child_details ch")
childs.each{
def vaccinationDetails = []
def sdfFormat = new SimpleDateFormat('yyyy-MM-dd');
def date = sdfFormat.format(new Date())
vaccinationDetails = sql.rows("select * from vaccination_details vd where vd.alert_date like '"+date+" 00:00:00"+"' ")
def patient = sql.rows("select * from registration r where r.account_id = "+it.created_by+"")
if(it.sms == true){
vaccinationDetails.each{vd->
if(vd.alert_status){
def smsChk = true
def sms = new SMS()
sms.mobileNumber = patient[0].mobile as Long
def message = "Hi "+patient[0].user_name+", This Is the Vaccination Notification For Your Child: Vaccination Name : "+vd.vaccination+" , Vaccination Date : "+vd?.alert_date
sms.message = message
def sendStatus = ""
def parameters =  [to:sms.mobileNumber, sender:messageSource.getMessage('com.gb.md.sms.senderId',null,LCH.getLocale()).toString(), message:sms.message] //grailsApplication.config.app.sms.senderId
//connection opened
def connection = smsService.urlConnection(messageSource.getMessage('com.gb.md.sms.sendUrl',null,LCH.getLocale()),parameters)
parameters = "&to="+patient[0].mobile+"&sender="+messageSource.getMessage('com.gb.md.sms.senderId',null,LCH.getLocale()).toString()+"&message="+message //grailsApplication.config.app.sms.senderId
(sendStatus.trim().equalsIgnoreCase("Message GID=<br />ID=") || sendStatus.trim() == "") ? (sms.status="Not Sent") : (sms.status="Sent")
smsService.save(sms)
}
}
}
if(it.email == true){
vaccinationDetails.each{vd->
if(vd.alert_status){
sendEmailTemplate(patient[0].email,'/modules/patient/facesheet/vaccination/_vaccineNotificationTemplate',"Vaccination Alert",patient,vd,false)
}
}
}
if(it.phone_call == true){
def user =  sql.rows("select r.email from registration r where r.id = 2")
vaccinationDetails.each{vd->
if(vd.alert_status){
sendEmailTemplate(user.email,'/modules/patient/facesheet/vaccination/_vaccineNotificationTemplate',"Vaccination Alert",patient,vd,true)
}
}
}
}

sql.close()
}

/**
* Notify users about account expire with in 7 days through email
* @return
*/
def aboutToExpire(){
def sql = new Sql(dataSource)
def users = sql.rows("select r.*  from registration r where r.expiry_date between CURDATE() and DATE_ADD(CURDATE(), INTERVAL 7 DAY)")
users.each{
if(it.email){
def msg = "Your account is about to expire on"+" "+it.expiry_date
//sendEmail(it.email,"Account Expiry Alert",msg)
def map = [:]
map.put("expire", msg)
sendNotificationEmailTemplate(it.email,'/mailtemplates/_accountExpireTemplate',"Account Expiry Alert",map)
}
}
sql.close()
}

/**
* To Send Email on account expiry
* @return
*/
def accountExpired(){
def sql = new Sql(dataSource)
def users = sql.rows("select r.*  from registration r where Date(r.expiry_date) <= CURDATE()")
users.each{
if(it.email){
def msg = "Your account has been expired Please contact admin "
//sendEmail(it.email,"Account Expired!",msg)
def map = [:]
map.put("expired", msg)
sendNotificationEmailTemplate(it.email,'/mailtemplates/_accountExpireTemplate',"Account Expired Alert",map)

}
}
sql.close()
}

def sendEmailTemplate(toMail,view,sub,patient,vd,check){
mailService.sendMail {
multipart true
to toMail
from messageSource.getMessage('com.gb.md.mail.from',null,LCH.getLocale())
subject sub
body  ( view: view,model:[patient:patient,vd:vd,check:check])
}
}

def sendNotificationEmailTemplate(toMail,view,sub,map){
mailService.sendMail {
multipart true
to toMail
from messageSource.getMessage('com.gb.md.mail.from',null,LCH.getLocale())
subject sub
body  ( view: view,model:[map:map])
}
}

/**
* send email without template
* @param toMail
* @param sub
* @param msg
* @return
*/
def sendEmail(toMail,sub,msg){
mailService.sendMail {
multipart true
to toMail
from messageSource.getMessage('com.gb.md.mail.from',null,LCH.getLocale())
subject sub
body "NOTE : "+msg
}
}

/**
* @janaki
*/
def getAlerts(){
Runnable runnable = new Runnable() {
public void run() {
alertDetails()
followUp()
remainders()
}
};

ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor()
service.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.MINUTES);
}

/**
* @janaki
*/
def alertDetails(){
def sdfFormat = new SimpleDateFormat('yyyy-MM-dd HH:mm');
def date = sdfFormat.format(new Date())
def sql = new Sql(dataSource)
def alertDetails = []
def map = [:]
alertDetails = sql.rows("select  al.email as emailstatus,al.sms,al.alert_message alertMessage,r.account_id as accountId,r.email as email,r.mobile,al.alert_time as alertTime,r.user_name as userName from alerts al,registration r where al.created_by = r.account_id and al.alert_time like '"+date+":00' ")
if(alertDetails){
alertDetails.each{
def accountId = it.accountId as Long
//for sending email
if(it.emailstatus == true){
//sendEmail(it.email,"Alert",it.alertMessage)
map.put("userName", "Hello "+it.userName+" this is your alert mail")
map.put("alertTime", it.alertTime)
map.put("alertMessage",it.alertMessage)
sendNotificationEmailTemplate(it.email,'/mailtemplates/_alertTemplate',"Your Alert",map)
}
// for sending SMS
if(it.sms == true){
def smscount = sql.rows("select * from smsaccount a where a.account_id = "+accountId)

if(smscount[0][3] > 0){
def smsChk = true
def sms = new SMS()
sms.mobileNumber = it.mobile as Long
sms.message = it.alertMessage
def message = it.alertMessage
def sendStatus = ""
def parameters =  [to:sms.mobileNumber, sender:messageSource.getMessage('com.gb.md.sms.senderId',null,LCH.getLocale()).toString(), message:sms.message] //grailsApplication.config.app.sms.senderId
//connection opened
def connection = smsService.urlConnection(messageSource.getMessage('com.gb.md.sms.sendUrl',null,LCH.getLocale()),parameters)
parameters = "&to="+it.mobile+"&sender="+messageSource.getMessage('com.gb.md.sms.senderId',null,LCH.getLocale()).toString()+"&message="+message //grailsApplication.config.app.sms.senderId
sendStatus = smsService.writeStream(connection,parameters)
(sendStatus.trim().equalsIgnoreCase("Message GID=<br />ID=") || sendStatus.trim() == "" || sendStatus == 'Invalid user credentials') ? (sms.status="Not Sent") : (sms.status="Sent")
smsService.save(sms)
//update the remaining sms count
if(sms.status == 'Sent') {
def msgcount = (Math.ceil(sms.message.toString().length() / (messageSource.getMessage('com.gb.md.sms.maxcount',null,LCH.getLocale()) as int)))
sql.executeUpdate("update smsaccount a set a.remaining_sms = a.remaining_sms - "+msgcount+"  where a.account_id = "+accountId)
}
else{
}
}
}
}
}
sql.close()
}

/**
* Janaki for followUp
* @return
*/
def followUp(){
def sdfFormat = new SimpleDateFormat('yyyy-MM-dd HH:mm');
def date = sdfFormat.format(new Date())
def sql = new Sql(dataSource)
def map = [:]
def followupDetails = []
def qury = "SELECT fp.follow_date as followDate,fpt.name as followName,fp.created_by as accountId,fp.patient_id,fp.patient_name as patientName,dp.email as patientEmail,fp.comments,r.user_name as doctorName,pf.fname as firstName,pf.lname as lastName,cd.clinic_name as clinicName,a.followup_sms as fpsms,a.followup_email as fpemail,"+
"cd.clinic_addr as clinicAddress,c.name as cityName,s.name as stateName,cd.phone,cd.mobile FROM follow_up fp, follow_up_type fpt,doctor_patients dp,registration r,authorization_rules a,"+
"clinic_details cd,professional_details pf,cities c,state s WHERE fp.created_by = dp.doctor_account_id AND fp.`status` = '1' AND fpt.`status` = '1' AND r.account_id = fpt.doctor_id AND a.account_id = fp.created_by and "+
"fp.patient_id = dp.patient_id AND pf.account_id = r.account_id AND c.state_id = s.id and c.id = cd.clinic_city_id and cd.id = fp.clinic_id and cd.account_id = fpt.doctor_id and fp.follow_date LIKE '"+date+":00' "
followupDetails = sql.rows(qury)

if(followupDetails){
followupDetails.each{
//for sending email
//sendEmail(it.email,"followup","hello this is general mails")
if(it.fpemail == true) {
map.put("patientName", "Hello "+it.patientName+" this is your FollowUp mail")
map.put("followDate", it.followDate)
map.put("followName",it.followName)
map.put("comments", it.comments)
map.put("doctorName",it.firstName+" "+it.lastName)
map.put("clinicName", it.clinicName)
map.put("clinicAddress",it.clinicAddress)
map.put("city", it.cityName)
map.put("state",it.stateName)
map.put("phone", it.phone)
//map.put("mobile", it.mobile)
sendNotificationEmailTemplate(it.patientEmail,'/mailtemplates/_followUpEmailTemplate',"Patient FollowUp",map)

}

if(it.fpsms == true) {
def smscount = SMSAccount.findByAccountId(it.accountId)
if(smscount.remainingSms > 0){
def smsChk = true
   def sms = new SMS()
   sms.mobileNumber = it.mobile as Long
   sms.message = 'Note :Patient Name:'+it.patientName+',followup Date:'+it.followDate+',Follow Name:'+it.followName+',Comments:'+it.comments+',Doctor Name:'+it.doctorName
   def message = 'Note :Patient Name:'+it.patientName+',followup Date:'+it.followDate+',Follow Name:'+it.followName+',Comments:'+it.comments+',Doctor Name:'+it.doctorName
   def sendStatus = ""
   def parameters =  [to:sms.mobileNumber, sender:messageSource.getMessage('com.gb.md.sms.senderId',null,LCH.getLocale()).toString(), message:sms.message] //grailsApplication.config.app.sms.senderId
   //connection opened
    def connection = smsService.urlConnection(messageSource.getMessage('com.gb.md.sms.sendUrl',null,LCH.getLocale()),parameters)
   parameters = "&to="+it.mobile+"&sender="+messageSource.getMessage('com.gb.md.sms.senderId',null,LCH.getLocale()).toString()+"&message="+message //grailsApplication.config.app.sms.senderId
   (sendStatus.trim().equalsIgnoreCase("Message GID=<br />ID=") || sendStatus.trim() == "") ? (sms.status="Not Sent") : (sms.status="Sent")
   smsService.save(sms)
   //update the remaining sms count
  if(sms.status == 'Sent') {
smscount.remainingSms--
smscount.save(flush:true)
  }
 else{
 }
}
}
}
}
sql.close()
}

def remainders(){
def sdfFormat = new SimpleDateFormat('dd/MM/yyyy HH:mm');
def currentdate = sdfFormat.format(new Date())
Date date1 = sdfFormat.parse(currentdate)
def curdatemilliseconds = date1.getTime()
def sql = new Sql(dataSource)
def remainders = sql.rows("select  r.event_name as eventName,r.event_type as eventType,rg.email,rg.user_name as userName from  events r,registration rg  where r.event_type = 'Remainders' and (r.start_time-19800000) = '"+curdatemilliseconds+"' and r.account_id = rg.account_id")
if(remainders){
remainders.each{rt->
sendNotificationEmailTemplate(rt.email,'/mailtemplates/_remainderTemplate',"Doctor Remainder",rt)
}
}
sql.close()
}

}

=========================================================================================================================================================

In Build Config

compile ":uploadr:1.0.0"

display image:

<img src="<g:createLink controller="doctors" action="viewImage" params='[img: "${clinic?.pic1}"]'/>"  class="img-responsive" style="height: 100px;"/>

<input  type="file" name="pic1" id="clinicpic1">

$("#clinicpic1").change(function(){
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageForPic1;
reader.readAsDataURL(this.files[0]);
}
});


$('#clinicpic1').fileupload({
   url:"${request.getContextPath()}/settings/upload",
   formData: {accountId: $('#accountId').val(), clinicId: $('#doc_clinicId').val(), pic:'pic1'},
   dataType: 'json',
   maxNumberOfFiles: 1,
   maxFileSize: 5000000, // 5 MB
   previewMaxWidth: 250,
   previewMaxHeight: 250,
   add: function (e, data) {
    data.submit().success(function (result, textStatus, jqXHR) {
$('.pull-right .alert').addClass('alert-success').show().empty().html('Successfully Uploaded!').fadeOut(3000)            
       }).error(function (jqXHR, textStatus, errorThrown) {
        $('.pull-right .alert').addClass('alert-danger').show().empty().html('Upload Failed!').fadeOut(3000)
       }).complete(function (result, textStatus, jqXHR) {
});
},
   drop: function (e, data) {
    e.preventDefault();
    //disabling drag and drop
   }
});

def viewImage(){
try{
def file = new File(params.img)
def img = file.bytes
response.contentType = 'image/jpg,image/png' // or the appropriate image content type
response.outputStream << img
response.outputStream.flush()
}catch(Exception e){
}
}
=========================================================================================================================================================

//upload pics for clinics
def upload(){
def file
if(params.pic == 'pic1') file = request.getFile('pic1')
if(params.pic == 'pic2') file = request.getFile('pic2')
if(params.pic == 'pic3') file = request.getFile('pic3')
if(params.pic == 'pic4') file = request.getFile('pic4')
if(params.pic == 'pic5') file = request.getFile('pic5')
if(params.pic == 'pic6') file = request.getFile('pic6')
if(params.pic == 'pic7') file = request.getFile('pic7')
if(params.pic == 'clinicLogo') file = request.getFile('clinicLogo')

if(file.empty) {
render (status: 500, text: 'File is empty')
return
}
String extractedName = FilenameUtils.removeExtension(file.originalFilename);
String extension = FilenameUtils.getExtension(file.originalFilename);
def fileName = extractedName  + "." + extension
def storage = messageSource.getMessage('com.gb.md.clinicpicloaction',null,LCH.getLocale()).toString()+params.clinicId
def folder = new File(storage)
def imagePath = storage+'/'+params.pic+'.'+extension

if( !folder.exists())  folder.mkdirs()
if(extension) file.transferTo(new File(imagePath))

def clinic = ClinicDetails.get(params.clinicId as Long)
if(params.pic == 'pic1') clinic.pic1 = imagePath
if(params.pic == 'pic2') clinic.pic2 = imagePath
if(params.pic == 'pic3') clinic.pic3 = imagePath
if(params.pic == 'pic4') clinic.pic4 = imagePath
if(params.pic == 'pic5') clinic.pic5 = imagePath
if(params.pic == 'pic6') clinic.pic6 = imagePath
if(params.pic == 'pic7') clinic.pic7 = imagePath
if(params.pic == 'clinicLogo') clinic.clinicLogo = imagePath

clinic.save(flush:true)
render ([clinic:clinic] as JSON)
}

http://grandhivamsikrishna.blogspot.in/2016/02/static-file-download-in-grails.html

No comments:

Post a Comment