Beispiel #1
0
def PracticeIVR_LeaveRegularMsg_New(request):
	"""
	3 steps:
	1. get callback number
	2. get message (recording) from caller
	3. Sends office manager text message, in attachment there is voice file of recording
	"""
	callEnded = _checkCallbackDuration(request, False)  # if someone hangs up, we still want to keep processing
	logger.debug('%s: PracticeIVR_LeaveRegularMsg_New state %s' %
		(request.session.session_key, request.session['ivr2_state']))
	if ('ivr2_sub_state' not in request.session):
		# first time around
		request.session['ivr2_sub_state'] = 'PracticeIVR_LeaveRegularMsg_Start'
	else:
		logger.debug('%s: PracticeIVR_LeaveRegularMsg_New sub_state %s' %
			(request.session.session_key, request.session['ivr2_sub_state']))
	# we have recording, or callback number or we are in the GetMsg sub_state
	if ('ivr2_Record_recording' in request.session or 
		('ivr2_only_callbacknumber' in request.session and 
			request.session['ivr2_only_callbacknumber'] == True) or
		request.session['ivr2_sub_state'] == 'PracticeIVR_LeaveRegularMsg_GetMsg'):
		# final or third iteration - get and send message
		del request.session['ivr2_sub_state']
		# get a list of all office managers for this practice
		mgrs = get_all_practice_managers(request.session['practice_id'])
		# after unique'ifying save_answering_service_message() expects recips
		# as a list, see https://redmine.mdcom.com/issues/1374 for details
		_copyStateVariables(request)
		save_answering_service_message(request, False, list(set(m.user for m in mgrs)))
		r = twilio.Response()
		r.append(tts(_('Your message have been sent. Good Buy')))
		r.append(twilio.Hangup())
		return HttpResponse(str(r), mimetype=settings.TWILIO_RESPONSE_MIMETYPE)
	if (request.session['ivr2_sub_state'] == 'PracticeIVR_LeaveRegularMsg_Start'):
		# first iteration, getCallBackNumber
		request.session['ivr2_sub_state'] = 'PracticeIVR_LeaveRegularMsg_GetCallback'
		request.session['ivr2_returnOnHangup'] = \
			'MHLogin.DoctorCom.IVR.views_practice_v2.PracticeIVR_LeaveRegularMsg_New'
		return getCallBackNumberNew(request)
	elif request.session['ivr2_sub_state'] == 'PracticeIVR_LeaveRegularMsg_GetCallback':
		# second iteration, get Message recording
		request.session['ivr2_sub_state'] = 'PracticeIVR_LeaveRegularMsg_GetMsg'
		request.session['ivr2_Record_maxLength'] = 600  # 10 minutes
		request.session['ivr2_Record_leadSilence'] = 2
		request.session['ivr2_Record_promptOnce'] = True
		request.session['ivr2_Record_prompt_str'] = 'Please say your \
			non urgent message after the beep. Please state your name and \
			speak clearly. Press pound when finished.'
		request.session['ivr2_returnOnHangup'] = \
			'MHLogin.DoctorCom.IVR.views_practice_v2.PracticeIVR_LeaveRegularMsg_New'
		request.session.modified = True
		# Pass off the recording action to the getRecording function.
		return getQuickRecordingNew(request)
	else:
		# should never get here with unknown state
		logger.info('%s: PracticeIVR_LeaveRegularMsg_New called with state %s' % (
			request.session.session_key, request.session['ivr2_state']))
		request.session['ivr2_state'] = 'PracticeIVR_LeaveRegularMsg_New'
		return PracticeIVR_LeaveRegularMsg_New(request)
Beispiel #2
0
def PracticeIVR_LeaveRegularMsg(request):
	"""
	Sends office manager text message, in attachment there is voice file of recording
	"""		
	if 'CallStatus' in request.POST:
		logger.debug('%s: Into LeaveTextMsg with call status %s' % (
				request.session.session_key, request.POST['CallStatus']))
	if('CallStatus' in request.POST and request.POST['CallStatus'] == 'completed'):
		try:
			callSID = request.POST['CallSid']
			auth, uri, = client.auth, client.account_uri
			resp = make_twilio_request('GET', uri + '/Calls/%s' % callSID, auth=auth)
			content = json.loads(resp.content)
			log = callLog.objects.get(callSID=callSID)
			log.call_duration = content['TwilioResponse']['Call']['Duration']
			log.save()
		except TwilioRestException as tre:
			logger.critical('Unable to get call status: %s' % tre.msg)
		except ObjectDoesNotExist as odne:
			logger.warning('Call log does not exist for sid: %s. Caller may have '
				'hung up shortly after Twilio starts call process.' % str(odne))

	#if already got recording - this must be second ittiration	
	if ('ivr_makeRecording_recording' in request.session or 
			request.session['ivr_only_callbacknumber'] == True):
		# get a list of all office managers for this practice
		mgrs = get_all_practice_managers(request.session['practice_id'])

		# after unique'ifying save_answering_service_message() expects recips 
		# as a list, see https://redmine.mdcom.com/issues/1374 for details
		save_answering_service_message(request, False, list(set(m.user for m in mgrs)))

		r = twilio.Response()
		r.append(tts(_('Your message have been sent. Good Buy')))
		r.append(twilio.Hangup())
		return HttpResponse(str(r), mimetype=settings.TWILIO_RESPONSE_MIMETYPE)
	else:
		# first or second iteration, get call back number and message recoding
		if ('ivr_makeRecording_callbacknumber' in request.session):	
			# get recording for non urgent message
			request.session['ivr_makeRecording_maxLength'] = 600  # 10 minutes
			request.session['ivr_makeRecording_leadSilence'] = 2
			request.session['ivr_makeRecording_promptOnce'] = True
			request.session['ivr_makeRecording_prompt'] = tts(_('Please say your '
					'non urgent message after the beep. Please state your name and '
					'speak clearly. Press pound when finished.'))
			request.session['ivr_makeRecording_returnOnHangup'] = \
				'MHLogin.DoctorCom.IVR.views_practice.PracticeIVR_LeaveRegularMsg'
			request.session['ivr_call_stack'].append('PracticeIVR_LeaveRegularMsg')
			request.session.modified = True

			# Pass off the recording action to the getRecording function.
			return getQuickRecording(request)
		else:	 
			#get call back number
			request.session['ivr_call_stack'].append('PracticeIVR_LeaveRegularMsg')
			request.session['ivr_callback_returnOnHangup'] = \
				'MHLogin.DoctorCom.IVR.views_practice.PracticeIVR_LeaveRegularMsg'
			return getCallBackNumber(request)
Beispiel #3
0
def send_mail_to_org_manager(org, subject, body_template_file, body_context):
	mgrs = get_all_practice_managers(org)
	for mgr in mgrs:
		body_context.update({
				'manager_fullname': get_fullname(mgr.user)
			})
		body = render_to_string(body_template_file, body_context)
		send_mail(
				subject,
				body,
				settings.SERVER_EMAIL,
				[mgr.user.email],
				fail_silently=False
			)
Beispiel #4
0
def removeProviderPractice(request):
	if (request.method == 'POST'):
		form = AssociationProviderIdForm(request.POST)
	else:
		form = AssociationProviderIdForm(request.GET)

	if (not form.is_valid()):
		return HttpResponse(json.dumps({'err': _('The data is error. Please '
						'refresh page again.')}), mimetype='application/json')

	prov_id = form.cleaned_data['prov_id']

	#get managers' practice, and practices call group
	office_staff = request.session['MHL_Users']['OfficeStaff']
	practice = office_staff.current_practice
	call_group = practice.call_group

	current_date = datetime.datetime.now()
	two_weeks_date = current_date + datetime.timedelta(days=15)

	#get provider to be removed
	provider = Provider.objects.get(user=prov_id)
	user = provider.user

	#if schedule exists in next two weeks massage managers, so they can cover gaps
	events_set = EventEntry.objects.filter(callGroup=call_group, oncallPerson=user, 
			eventStatus=1, endDate__gt=current_date)
	#raise Exception('return set is', events_set, practice, user)

	if (events_set.count() > 0):

		subject = 'DoctorCom: Gaps in On Call Schedule'
		body = _("""Dear Manager,

%(first_name)s %(last_name)s has removed %(user)s from %(practice_name)s. %(user)s was 
removed from the on-call schedule, creating gaps in coverage. Please update your 
on-call schedule to fill these gaps.

Best,
DoctorCom Staff""") \
		% {
			'first_name': request.user.first_name,
			'last_name': request.user.last_name,
			'user': provider.user,
			'practice_name': practice.practice_name
		}
			#work around message_managers fails to message:

			#message_managers(request, practice, subject,
			#				body, 
			#	practice_name=practice.practice_name,
			#	manager_name=request.user.first_name,
			#	manager_name_last=request.user.last_name,
			#	provider_name=provider.user
			#	)

		#get a list of all office managers for this practice
		OfficeManagers = get_all_practice_managers(practice.id)
		#this will be message for office managers, next key makes sms not being sent out with
		#message-becasue office managers do not have to carry cell phones, dahsboard only
		request.session['answering_service'] = 'yes'

		#create message object
		msg = Message(sender=None, sender_site=None, subject=subject)
		msg.save()

		msg_body = msg.save_body(body)

		#create list of recepients - all office manager of the practice in question
		for OfficeStaff in OfficeManagers:
			MessageRecipient(message=msg, user=OfficeStaff.user).save()

		msg.send(request, msg_body)

		#send email as well to all managers
		mail_managers(practice, subject, body)

	today = datetime.date.today()
	#remove from schedule - mark as deleted
	EventEntry.objects.filter(callGroup=call_group, oncallPerson=user, 
		startDate__gte=today).update(eventStatus=0, lastupdate=current_date)
	EventEntry.objects.filter(callGroup=call_group, oncallPerson=user, 
		endDate__gte=today, startDate__lt=today).update(endDate=today, lastupdate=current_date)

	CallGroupMember.objects.filter(call_group=call_group, member=user).delete()

	#remove from provider
	if (provider.current_practice == practice):
		provider.current_practice = None
		provider.save()

	provider.practices.remove(practice)

	return HttpResponse(json.dumps('ok'), mimetype='application/json')
Beispiel #5
0
def removePractice(request):
    if (request.method == 'POST'):
        form = PractIdAssociationForm(request.POST)
    else:
        form = PractIdAssociationForm(request.GET)

    if (not form.is_valid()):
        return HttpResponse(json.dumps(['err',
                                        'A server error has occurred.']),
                            mimetype='application/json')

    pract_id = form.cleaned_data['pract_id']
    current_date = datetime.datetime.now()
    two_weeks_date = current_date + datetime.timedelta(days=15)

    user = request.user
    provider = request.session['MHL_Users']['Provider']
    practice = PracticeLocation.objects.get(pk=pract_id)

    #remove from call group for this practice
    #if schedule exists in next two weeks massage managers, so they can cover gaps
    if practice.call_group:
        call_group = practice.call_group
        events_set = EventEntry.objects.filter(callGroup=call_group,
                                               oncallPerson=user,
                                               eventStatus=1,
                                               endDate__range=(current_date,
                                                               two_weeks_date))
    else:
        call_group = practice.call_groups.all()
        events_set = EventEntry.objects.filter(callGroup__in=call_group,
                                               oncallPerson=user,
                                               eventStatus=1,
                                               endDate__range=(current_date,
                                                               two_weeks_date))
    if (events_set.count() > 0):

        subject = _('DoctorCom: Gaps in On Call Schedule')
        body = """Dear Manager,

%(user)s has left %(practice_name)s. %(user)s was removed from the on-call schedule, 
creating gaps in coverage. Please update your on-call schedule to fill these gaps.

Best,
DoctorCom Staff""" % {
            'user': provider.user,
            'practice_name': practice.practice_name
        }

        #get a list of all office managers for this practice
        OfficeManagers = get_all_practice_managers(practice.id)
        #this will be message for office managers, next key makes sms not being sent out
        #with message-becasue office managers do not have to carry cell phones, dahsboard only
        request.session['answering_service'] = _('yes')

        #create message object
        msg = Message(sender=None, sender_site=None, subject=subject)
        msg.save()

        msg_body = msg.save_body(body)

        #create list of recepients - all office manager of the practice in question
        for OfficeStaff in OfficeManagers:
            MessageRecipient(message=msg, user=OfficeStaff.user).save()

        msg.send(request, msg_body)

        #send email as well to all managers
        mail_managers(practice, subject, body)

    #remove from schedule - mark as deleted
    if practice.call_group:
        CallGroupMember.objects.filter(call_group=call_group,
                                       member=user).delete()
        EventEntry.objects.filter(callGroup=call_group,
                                  oncallPerson=user,
                                  endDate__gte=current_date).update(
                                      eventStatus=0, lastupdate=current_date)
    else:
        CallGroupMember.objects.filter(call_group__in=call_group,
                                       member=user).delete()
        EventEntry.objects.filter(callGroup__in=call_group,
                                  oncallPerson=user,
                                  endDate__gte=current_date).update(
                                      eventStatus=0, lastupdate=current_date)

    #remove from provider
    if (provider.current_practice == practice):
        provider.current_practice = None
        provider.save()

    provider.practices.remove(practice)

    # send notification to related users
    thread.start_new_thread(notify_user_tab_changed, (provider.user.id, ))

    return HttpResponse(json.dumps(['err', 'No errors.']),
                        mimetype='application/json')
Beispiel #6
0
def addAssociationForPractice(request):
    user = request.user

    if (request.method == 'POST'):
        form = PractIdAssociationForm(request.POST)
    else:
        form = PractIdAssociationForm(request.GET)

    if (not form.is_valid()):
        return HttpResponse(json.dumps(_('A server error has occurred.')))

    pract_id = form.cleaned_data['pract_id']
    #get practice
    practice = PracticeLocation.objects.get(pk=pract_id)
    #check if manager sent association request to this provider already
    ret_set = Pending_Association.objects.filter(to_user=user,
                                                 practice_location=pract_id)
    if (ret_set.count() > 0):
        return HttpResponse(json.dumps(['duplicate'
                                        ]))  # , mimetype='application/json')

    #get practices Managers
    OfficeManagers = get_all_practice_managers(pract_id)
    if (len(OfficeManagers) == 0):
        raise Exception(' '.join([
            _('Practice with id'),
            str(pract_id),
            _('doesn\'t seem to have any managers!')
        ]))

    association = Pending_Association()
    created_time = datetime.datetime.now()

    association.from_user_id = user.id
    association.to_user_id = OfficeManagers[0].user.id
    association.practice_location_id = practice.id
    association.created_time = created_time
    association.resent_time = created_time
    association.save()

    log_association = Log_Association()

    log_association.association_id = association.id
    log_association.from_user_id = association.from_user_id
    log_association.to_user_id = association.to_user_id
    log_association.practice_location_id = association.practice_location.id
    log_association.action_user_id = request.user.id
    log_association.action = 'CRE'
    log_association.created_time = created_time

    log_association.save()

    #now let's mail all managers invitaion request
    mail_managers(practice,
                  _('DoctorCom: Request To Join Practice'),
                  """Dear Manager,

{{provider_name}} {{provider_name_last}} wants to join {{practice_name}}.

Please log into DoctorCom to view and accept the request. You can also accept 
the request by clicking https://{{server_address}}/Practice/Staff/

Best,
DoctorCom Staff
""",
                  practice_name=practice.practice_name,
                  provider_name=request.user.first_name,
                  provider_name_last=request.user.last_name,
                  server_address=settings.SERVER_ADDRESS)

    return HttpResponse(json.dumps('ok'))  # , mimetype='application/json')
Beispiel #7
0
def removePractice(request):
	if (request.method == 'POST'):
		form = PractIdAssociationForm(request.POST)
	else:
		form = PractIdAssociationForm(request.GET)

	if (not form.is_valid()):
		return HttpResponse(json.dumps(['err', 'A server error has occurred.']), 
						mimetype='application/json')

	pract_id = form.cleaned_data['pract_id']
	current_date = datetime.datetime.now()
	two_weeks_date = current_date + datetime.timedelta(days=15)

	user = request.user
	provider = request.session['MHL_Users']['Provider']
	practice = PracticeLocation.objects.get(pk=pract_id)

	#remove from call group for this practice
	#if schedule exists in next two weeks massage managers, so they can cover gaps
	if practice.call_group:
		call_group = practice.call_group
		events_set = EventEntry.objects.filter(callGroup=call_group, 
			oncallPerson=user, eventStatus=1, endDate__range=(current_date, two_weeks_date))
	else:
		call_group = practice.call_groups.all()
		events_set = EventEntry.objects.filter(callGroup__in=call_group, 
			oncallPerson=user, eventStatus=1, endDate__range=(current_date, two_weeks_date))
	if (events_set.count() > 0):	

		subject = _('DoctorCom: Gaps in On Call Schedule')
		body = """Dear Manager,

%(user)s has left %(practice_name)s. %(user)s was removed from the on-call schedule, 
creating gaps in coverage. Please update your on-call schedule to fill these gaps.

Best,
DoctorCom Staff""" % {'user': provider.user, 'practice_name': practice.practice_name}

		#get a list of all office managers for this practice
		OfficeManagers = get_all_practice_managers(practice.id)
		#this will be message for office managers, next key makes sms not being sent out 
		#with message-becasue office managers do not have to carry cell phones, dahsboard only
		request.session['answering_service'] = _('yes')

		#create message object		
		msg = Message(sender=None, sender_site=None, subject=subject)
		msg.save()

		msg_body = msg.save_body(body)

		#create list of recepients - all office manager of the practice in question
		for OfficeStaff in OfficeManagers:
			MessageRecipient(message=msg, user=OfficeStaff.user).save()

		msg.send(request, msg_body)

		#send email as well to all managers
		mail_managers(practice, subject, body)

	#remove from schedule - mark as deleted	
	if practice.call_group:
		CallGroupMember.objects.filter(call_group=call_group, member=user).delete()
		EventEntry.objects.filter(callGroup=call_group, oncallPerson=user, 
			endDate__gte=current_date).update(eventStatus=0, lastupdate=current_date)
	else:
		CallGroupMember.objects.filter(call_group__in=call_group, member=user).delete()
		EventEntry.objects.filter(callGroup__in=call_group, oncallPerson=user, 
			endDate__gte=current_date).update(eventStatus=0, lastupdate=current_date)

	#remove from provider
	if (provider.current_practice == practice):
		provider.current_practice = None
		provider.save()

	provider.practices.remove(practice)

	# send notification to related users
	thread.start_new_thread(notify_user_tab_changed, (provider.user.id,))

	return HttpResponse(json.dumps(['err', 'No errors.']), mimetype='application/json')
Beispiel #8
0
def addAssociationForPractice(request):
	user = request.user

	if (request.method == 'POST'):
		form = PractIdAssociationForm(request.POST)
	else:
		form = PractIdAssociationForm(request.GET)	

	if (not form.is_valid()):
		return HttpResponse(json.dumps(_('A server error has occurred.')))

	pract_id = form.cleaned_data['pract_id']
	#get practice
	practice = PracticeLocation.objects.get(pk=pract_id)
	#check if manager sent association request to this provider already
	ret_set = Pending_Association.objects.filter(to_user=user, practice_location=pract_id)
	if (ret_set.count() > 0):
		return HttpResponse(json.dumps(['duplicate']))  # , mimetype='application/json')

	#get practices Managers
	OfficeManagers = get_all_practice_managers(pract_id)
	if (len(OfficeManagers) == 0):
		raise Exception(' '.join([_('Practice with id'), str(pract_id),
				_('doesn\'t seem to have any managers!')]))

	association = Pending_Association()
	created_time = datetime.datetime.now()

	association.from_user_id = user.id
	association.to_user_id = OfficeManagers[0].user.id
	association.practice_location_id = practice.id
	association.created_time = created_time
	association.resent_time = created_time
	association.save()

	log_association = Log_Association()

	log_association.association_id = association.id
	log_association.from_user_id = association.from_user_id
	log_association.to_user_id = association.to_user_id
	log_association.practice_location_id = association.practice_location.id
	log_association.action_user_id = request.user.id
	log_association.action = 'CRE'
	log_association.created_time = created_time

	log_association.save()

	#now let's mail all managers invitaion request
	mail_managers(practice,
					_('DoctorCom: Request To Join Practice'),
					"""Dear Manager,

{{provider_name}} {{provider_name_last}} wants to join {{practice_name}}.

Please log into DoctorCom to view and accept the request. You can also accept 
the request by clicking https://{{server_address}}/Practice/Staff/

Best,
DoctorCom Staff
""",

				practice_name=practice.practice_name,
				provider_name=request.user.first_name,
				provider_name_last=request.user.last_name,
				server_address=settings.SERVER_ADDRESS
				)

	return HttpResponse(json.dumps('ok'))  # , mimetype='application/json')
Beispiel #9
0
def PracticeIVR_LeaveUrgentMsg_New(request):
	"""
	This lets caller leave an urgent message for a practice in foll steps:
	1. get callback number
	2. Records a voicemail message for the doctor on call
	3. leave notification to the doctor based on preferences.
	"""
	# TODO:
	# Update this code so that users can hit the pound key to pop back and log
	# into their own voicemail box.
	requestDataDict = {"GET": request.GET, "POST": request.POST}[request.method]
	logger.debug('%s: PracticeIVR_LeaveUrgentMsg_New state %s POST data is %s' % (
		request.session.session_key, request.session['ivr2_state'], str(request.POST)))
	# if caller hangs up, we still continue
	if ('ivr2_sub_state' not in request.session):
		request.session['ivr2_sub_state'] = 'PracticeIVR_LeaveUrgentMsg_Start'
	else:
		logger.debug('%s: PracticeIVR_LeaveUrgentMsg_New sub_state %s' % (
			request.session.session_key, request.session['ivr2_sub_state']))

	callEnded = _checkCallbackDuration(request, False)
	if (callEnded):
		logger.debug('%s: PracticeIVR_LeaveUrgentMsg_New caller hung up. State %s' % (
			request.session.session_key, request.session.get('ivr2_sub_state', 'None')))
		# we deal with leftover recording or , if any
		if (request.session['ivr2_sub_state'] == 'PracticeIVR_LeaveUrgentMsg_GetMsg' or
			'ivr2_Record_recording' in request.session or
			('ivr2_only_callbacknumber' in request.session and
				request.session['ivr2_only_callbacknumber'] == True)):
			# send msg to office managers
			del request.session['ivr2_sub_state']
			provider = Provider.objects.get(id=_getRecentOncallProviderId(request))
			logger.debug('%s: PracticeIVR_LeaveUrgentMsg_New caller hung up -- saving urgent msg for %s' % (
				request.session.session_key, provider))
			config = None
			config_complete = provider.vm_config.count() == 1 and provider.vm_config.get().config_complete
			if (config_complete):
				config = provider.vm_config.get()
			mgrs = get_all_practice_managers(request.session['practice_id'])
			_copyStateVariables(request)
			save_answering_service_message(request, True, [provider],
				list(set(m.user for m in mgrs)))
	else:
		if (request.session['ivr2_sub_state'] == 'PracticeIVR_LeaveUrgentMsg_Start'):
			# step 1: get callback number
			request.session['ivr2_sub_state'] = 'PracticeIVR_LeaveUrgentMsg_GetCallback'
			request.session['ivr2_returnOnHangup'] = \
				'MHLogin.DoctorCom.IVR.views_practice_v2.PracticeIVR_LeaveUrgentMsg_New'
			return getCallBackNumberNew(request)

		elif request.session['ivr2_sub_state'] == 'PracticeIVR_LeaveUrgentMsg_GetCallback':
			# step 2: after getting callback number, we get caller's message
			request.session['ivr2_sub_state'] = 'PracticeIVR_LeaveUrgentMsg_GetMsg'
			request.session['ivr2_Record_prompt_str'] = 'Please say your message \
					for the doctor on call after the beep. Press pound when finished.'
			request.session['ivr2_Record_maxLength'] = 600  # 10 minutes
			request.session['ivr2_Record_leadSilence'] = 2
			request.session['ivr2_Record_promptOnce'] = True
			request.session['ivr2_returnOnHangup'] = \
				'MHLogin.DoctorCom.IVR.views_practice_v2.PracticeIVR_LeaveUrgentMsg_New'
			request.session.modified = True
			# Pass off the recording action to the getRecording function.
			return getQuickRecordingNew(request)

		elif (request.session['ivr2_sub_state'] == 'PracticeIVR_LeaveUrgentMsg_GetMsg' or
			'ivr2_Record_recording' in request.session or
			('ivr2_only_callbacknumber' in request.session and
				request.session['ivr2_only_callbacknumber'] == True)):
			# step 3 - send msg to office managers
			del request.session['ivr2_sub_state']
			provider = Provider.objects.get(id=_getRecentOncallProviderId(request))
			logger.debug('%s: PracticeIVR_LeaveUrgentMsg_New saving urgent msg for %s' % (
				request.session.session_key, provider))
			config = None
			config_complete = provider.vm_config.count() == 1 and provider.vm_config.get().config_complete
			if (config_complete):
				config = provider.vm_config.get()
			mgrs = get_all_practice_managers(request.session['practice_id'])
			_copyStateVariables(request)
			save_answering_service_message(request, True, [provider],
				list(set(m.user for m in mgrs)))

			#if pager number is entered, also page call back number
			r = twilio.Response()
			r.append(tts(_('Your message has been sent. Good bye')))
			r.append(twilio.Hangup())
			return HttpResponse(str(r), mimetype=settings.TWILIO_RESPONSE_MIMETYPE)
		else:  # should not get here
			logger.debug('%s: Into PracticeIVR_LeaveUrgentMsg_New with invalid ivr2_state %s' %
				(request.session.session_key, request.session['ivr2_state']))
			request.session['ivr2_state'] = 'PracticeIVR_LeaveUrgentMsg_New'
			return PracticeIVR_LeaveUrgentMsg_New(request)
Beispiel #10
0
def resolve_download_failure(failure_record):
    url = failure_record.recording_url
    request = _FauxRequest()
    request.REQUEST = {"CallSid": failure_record.call_sid}
    request.session['ivr_makeRecording_recording'] = url
    request.session.session_key = ''

    wav_data, metadata = _download_recording(request)
    metadata = json.dumps(metadata)
    if (not wav_data):
        log = AnsSvcDLFailureActivityLog(call_sid=failure_record.call_sid,
                                         action='FAI')
        log.save()
        return False

    log = AnsSvcDLFailureActivityLog(call_sid=failure_record.call_sid,
                                     action='SUC')
    log.save()

    managers = get_all_practice_managers(failure_record.practice_id)

    msg = Message(sender=None,
                  sender_site=None,
                  subject='Answering Service - Recording Retrieved')
    msg.save()

    if (managers):
        # Assign all practice managers as recipients of this message.
        for staffer in managers:
            MessageRecipient(message=msg, user=staffer.user).save()
    else:
        #if this was a voicemail on a provider number
        error_msg = Message.objects.get(uuid=failure_record.error_message_uuid)
        recipients = error_msg.recipients.all()
        for user in recipients:
            MessageRecipient(message=msg, user=user).save()

    body = _('We were able to successfully retrieve a recording we had trouble '
     'downloading earlier today (callback number %(callbacknumber)s with '
     'ID %(call_sid)s). Please see the attached recording.\nAgain, we apologize '
     'for any inconvenience and thank you for your patience.\nDoctorCom Staff') % \
     {'callbacknumber': failure_record.callback_number, 'call_sid': failure_record.call_sid}

    body = msg.save_body(body)

    attachment = encrypt_object(
        MessageAttachment, {
            'message': msg,
            'size': len(wav_data),
            'encrypted': True,
            'metadata': metadata
        })
    attachment.encrypt_url(None, ''.join(['file://', attachment.uuid]))
    attachment.encrypt_filename(
        None, ''.join(['call_from_', failure_record.callback_number, '.mp3']))
    attachment.encrypt_file(None, [wav_data])
    if (not USE_MP3):
        attachment.suffix = 'wav'
        attachment.content_type = 'audio/wav'
    else:
        attachment.suffix = 'mp3'
        attachment.content_type = 'audio/mp3'

    attachment.save()
    attachments = [attachment]

    request.session['answering_service'] = 'yes'
    # Send the message
    msg.send(request, body, attachments)

    failure_record.mark_resolved(msg)
    return True
Beispiel #11
0
def PracticeIVR_LeaveUrgentMsg(request):
	"""
	Records a voicemail message for the doctor on call
	and leave notification to the doctor based on preferences.
	"""
	# TODO: Update this code so that users can hit the pound key to pop 
	# back and log into their own voicemail box.
	if('CallStatus' in request.POST and request.POST['CallStatus'] == 'completed'):
		try:
			callSID = request.POST['CallSid']
			auth, uri, = client.auth, client.account_uri
			resp = make_twilio_request('GET', uri + '/Calls/%s' % callSID, auth=auth)
			content = json.loads(resp.content)
			log = callLog.objects.get(callSID=callSID)
			log.call_duration = content['TwilioResponse']['Call']['Duration']
			log.save()
		except TwilioRestException as tre:
			logger.critical('Unable to get call status: %s' % tre.msg)
		except ObjectDoesNotExist as odne:
			logger.warning('Call log does not exist for sid: %s.' % str(odne))

	logger.debug('%s: Into PracticeIVR_LeaveUrgentMsg with call status %s' %
				(request.session.session_key, request.POST['CallStatus']))

	if ('ivr_makeRecording_callbacknumber' in request.session):
		callback = request.session['ivr_makeRecording_callbacknumber']

	provider = _getRecentOncallProvider(request)
	# TODO: we do nothing with config
	config = None
	config_complete = provider.vm_config.count() == 1 and provider.vm_config.get().config_complete
	if (config_complete):
		config = provider.vm_config.get()

	if ('ivr_makeRecording_recording' in request.session or 
			request.session['ivr_only_callbacknumber'] == True):
		if (request.session['ivr_only_callbacknumber'] == False):
			mgrs = get_all_practice_managers(request.session['practice_id'])
			# after unique'ifying save_answering_service_message() expects recips 
			# as a list, see https://redmine.mdcom.com/issues/1374 for details
			save_answering_service_message(request, True, [provider], 
										list(set(m.user for m in mgrs)))
			#this is calling doctor on call we keep events for that even if called 
			#via answering service, just like doctor com does
			# Cleanup
			del request.session['ivr_makeRecording_recording']
		else:
			if('CallStatus' in request.POST and request.POST['CallStatus'] == 'completed'):
				mgrs = get_all_practice_managers(request.session['practice_id'])
				# after unique'ifying save_answering_service_message() expects recips 
				# as a list, see https://redmine.mdcom.com/issues/1374 for details
				save_answering_service_message(request, True, [provider], 
											list(set(m.user for m in mgrs)))

		# Notify the user, always by sms, but provider better have mobile phone
		if (provider.mobile_phone):
			if (request.session['ivr_only_callbacknumber'] == False):
				body = render_to_string('DoctorCom/IVR/voicemail_sms.txt', {
						#'caller': '(%s) %s-%s'%(request.session['Caller'][:3], 
						#request.session['Caller'][3:6], request.session['Caller'][6:]),
						'caller': '%s' % (request.session['ivr_makeRecording_callbacknumber']),
						})
			else:
				if ('ivr_no_pound' in request.session and request.session['ivr_no_pound'] == True):
					body = _("You have a new call from DoctorCom. Caller hung up from "
						"CONFIRMED number %s") % (request.session['ivr_makeRecording_callbacknumber'])
				else:
					body = _("You have a new call from DoctorCom. Caller hung up "
							"from unconfirmed number %s") % \
								(request.session['ivr_makeRecording_callbacknumber'])
			# TODO: we do nothing with body, sms send?
		# if pager number is entered, also page call back number
		r = twilio.Response()
		r.append(tts(_('Your message has been sent. Good bye')))
		r.append(twilio.Hangup())
		return HttpResponse(str(r), mimetype=settings.TWILIO_RESPONSE_MIMETYPE)

	if ('ivr_makeRecording_callbacknumber' in request.session):	
		request.session['ivr_makeRecording_prompt'] = tts(_('Please say your message '
				'for the doctor on call after the beep. Press pound when finished.'))

		request.session['ivr_makeRecording_maxLength'] = 600  # 10 minutes
		request.session['ivr_makeRecording_leadSilence'] = 2
		request.session['ivr_makeRecording_promptOnce'] = True

		request.session['ivr_makeRecording_returnOnHangup'] = \
			'MHLogin.DoctorCom.IVR.views_practice.PracticeIVR_LeaveUrgentMsg'
		request.session['ivr_call_stack'].append('PracticeIVR_LeaveUrgentMsg')
		request.session.modified = True

		# Pass off the recording action to the getRecording function.
		return getQuickRecording(request)

	#get call back number
	request.session['ivr_call_stack'].append('PracticeIVR_LeaveUrgentMsg')
	request.session['ivr_callback_returnOnHangup'] = \
		'MHLogin.DoctorCom.IVR.views_practice.PracticeIVR_LeaveUrgentMsg'
	return getCallBackNumber(request)