Exemple #1
0
def practiceManageLogic(request):
    user_type = int(request.user_type)
    role_user = request.role_user
    if (request.method != 'POST'):
        # Get the user's current practices, and list them.
        practices = role_user.practices.filter(\
          organization_type__id=RESERVED_ORGANIZATION_TYPE_ID_PRACTICE)
        if USER_TYPE_OFFICE_MANAGER == user_type:
            practices = get_managed_practice(role_user)

        practices = [[p.id, p.practice_name] for p in practices]
        current_practice = role_user.current_practice
        if ('pk' in dir(current_practice)):
            current_practice = current_practice.pk
            data = {
                'practices': practices,
                'current_practice': current_practice,
            }
        return HttpJSONSuccessResponse(data=data)

    # office staff can't change current practice
    if USER_TYPE_OFFICE_STAFF == user_type:
        return err403(request)

    form = SetPracticeForm(request.POST, user_type=user_type)
    if (not form.is_valid()):
        return err_GE031(form)

    new_practice = form.cleaned_data['current_practice']
    if (new_practice == None):
        # Clearing the current practice.
        role_user.current_practice = None
        role_user.save()
        data = {
            'providers': [],
            'staff': [],
        }
        return HttpJSONSuccessResponse(data=data)
    if (new_practice in role_user.practices.values_list('id', flat=True)):
        # great, do the change.
        role_user.current_practice_id = new_practice
        role_user.save()
        data = {
            'providers': getPracticeProviders(new_practice)['users'],
            'staff': getPracticeStaff(new_practice)['users'],
        }
        return HttpJSONSuccessResponse(data=data)

    err_obj = {
        'errno': 'AM001',
        'descr': _('Invalid practice selection.'),
    }
    return HttpResponseBadRequest(content=json.dumps(err_obj),
                                  mimetype='application/json')
Exemple #2
0
def brokerEditProfileLogic(request):
    if (request.method != 'POST'):
        return err_GE002()

    old_url = None
    broker = request.role_user
    if broker.user.photo:
        old_url = broker.user.photo.name

    broker_form = BrokerForm(request.POST, instance=broker)
    if not broker_form.is_valid():
        return err_GE031(broker_form)

    user_form = BrokerUserForm(request.POST,
                               request.FILES,
                               instance=broker.user)
    if not user_form.is_valid():
        return err_GE031(user_form)

    broker_form.save()
    user_form.save()

    new_url = None
    if broker.user.photo:
        new_url = broker.user.photo.name
    ImageHelper.generate_image(old_url, new_url)

    return HttpJSONSuccessResponse()
Exemple #3
0
	def testCreateOfficeStaff(self):
		data = {
			'username':get_random_username(),
			'first_name':'c',
			'last_name':'tian',
			'mobile_phone':9001111111,
			'gender':'M',
			'email':'*****@*****.**',
			'lat':0.0, 
			'longit':0.0, 
			'address1':'address1', 
			'address2':'address2', 
			'city':'Chicago', 
			'state':'IL', 
			'zip':60601,
			'user_type':1,
			'office_lat':41.885805,
			'office_longit':-87.6229106,
			'staff_type':3,
		}

		response = self.client.post(reverse('MHLogin.api.v1.views_users.createOfficeStaff'), data, **self.extra)
		self.assertEqual(response.status_code, 200, response.status_code)
		self.assertEqual(response.content, HttpJSONSuccessResponse().content, response.status_code)

		response = self.client.post(reverse('MHLogin.api.v1.views_users.createOfficeStaff'), **self.extra)
		self.assertEqual(json.loads(response.content)['errno'], 'GE031', response.status_code)
	
		response = self.client.get(reverse('MHLogin.api.v1.views_users.createOfficeStaff'), data, **self.extra)
		self.assertEqual(response.content, err_GE002().content, response.status_code)
Exemple #4
0
def composeReferLogic(request, api_secret=None, ss=None):
    if (request.method != 'POST'):
        return err_GE002()

    form = MessageReferForm(request.POST, request.FILES)
    if (not form.is_valid()):
        return err_GE031(form)

    sender = request.user
    sender_role_user = request.role_user
    subject = u'Refer'
    body = form.cleaned_data['reason_of_refer']
    recipients = form.cleaned_data['user_recipients']
    attachments = []
    if ('attachments' in request.FILES):
        attachments = request.FILES.getlist('attachments')

    createNewMessage(request,
                     sender,
                     sender_role_user,
                     recipients,
                     body,
                     ccs=None,
                     subject=subject,
                     uploads=attachments,
                     file_data_list=None,
                     refer_data=form.cleaned_data,
                     api_secret=api_secret,
                     ss=ss)
    return HttpJSONSuccessResponse()
Exemple #5
0
def deleteMessageLogic(request, message_id):
    msgs = list(
        MessageBodyUserStatus.objects.filter(
            user=request.user,
            delete_flag=False,
            msg_body__message__uuid=message_id))
    # Integrity check.
    if (len(msgs) > 1):
        # shouldn't be possible!
        mail_admins(
            'Duplicate message ID', ' '.join([
                'server: ', settings.SERVER_ADDRESS, '\n',
                'The message id with uuid', message_id, 'has returned with',
                'more than one Message!\nAt: ',
                str(inspect.getfile(inspect.currentframe())), ':',
                str(inspect.currentframe().f_back.f_lineno)
            ]))
    elif (len(msgs) == 0):
        raise Http404

    status = msgs[0]
    status.delete_flag = True
    if (not status.delete_timestamp):
        status.delete_timestamp = int(time.time())
    status.save()
    return HttpJSONSuccessResponse()
Exemple #6
0
def siteManageLogic(request):
    user = request.role_user
    if (request.method != 'POST'):
        # Get the user's current practices, and list them.
        sites = user.sites.values('id', 'name')
        sites = [[s['id'], s['name']] for s in sites]
        current_site = user.current_site
        if ('pk' in dir(current_site)):
            current_site = current_site.pk
            data = {
                'sites': sites,
                'current_site': current_site,
            }
        return HttpJSONSuccessResponse(data=data)

    form = SetSiteForm(request.POST)
    if (not form.is_valid()):
        return err_GE031(form)

    new_site = form.cleaned_data['current_site']
    if (new_site == None):
        # Clearing the current site.
        user.current_site = None
        user.save()
        data = {
            'providers': [],
            'staff': [],
            'med_students': [],
        }
        return HttpJSONSuccessResponse(data=data)
    if (new_site in user.sites.values_list('id', flat=True)):
        # great, do the change.
        user.current_site_id = new_site
        user.save()
        data = {
            'med_students': getSiteStudents(new_site)['users'],
            'providers': getSiteProviders(new_site)['users'],
            'staff': getSiteStaff(new_site)['users'],
        }
        return HttpJSONSuccessResponse(data=data)

    err_obj = {
        'errno': 'AM001',
        'descr': _('Invalid site selection.'),
    }
    return HttpResponseBadRequest(content=json.dumps(err_obj),
                                  mimetype='application/json')
Exemple #7
0
def changePasswordLogic(request):
    if (request.method != 'POST'):
        return err_GE002()
    form = ChangePasswordForm(request.mhluser, request.POST)
    if (not form.is_valid()):
        return err_GE031(form)
    change_pass_common(form, request)
    return HttpJSONSuccessResponse()
Exemple #8
0
def updateTaskLogic(request, task_id):
	if (request.method != 'POST'):
		return err_GE002()
	form = UpdateTaskForm(request.POST)
	if (not form.is_valid()):
		return err_GE031(form)

	updateFollowUp(form.cleaned_data, task_id, request.mhluser.id)
	return HttpJSONSuccessResponse()
Exemple #9
0
def listTasksLogic(request):
	if (request.method != 'POST'):
		return err_GE002()
	form = TaskListForm(request.POST)
	if (not form.is_valid()):
		return err_GE031(form)

	data = getFollowUpList(form.cleaned_data, request.mhluser.id)
	return HttpJSONSuccessResponse(data=data)
Exemple #10
0
def practiceSearch(request):
	if (request.method != 'POST'):
		return err_GE002()
	form = PracticeSearchForm(request.POST)
	if (not form.is_valid()):
		return err_GE031(form)

	data = getPracticeList(form.cleaned_data, org_type_id=RESERVED_ORGANIZATION_TYPE_ID_PRACTICE)
	return HttpJSONSuccessResponse(data=data)
Exemple #11
0
def createProvider(request):
	if (request.method != 'POST'):
		return err_GE002()
	form = CreateProviderForm(request.POST)
	if (not form.is_valid()):
		return err_GE031(form)

	createNewProvider(form, request.role_user)
	return HttpJSONSuccessResponse()
Exemple #12
0
def searchStaff(request):
	if (request.method != 'POST'):
		return err_GE002()
	form = StaffSearchForm(request.POST)
	if (not form.is_valid()):
		return err_GE031(form)

	data = getStaffList(form.cleaned_data)
	return HttpJSONSuccessResponse(data=data)
Exemple #13
0
def callFwdPrefsLogic(request):
    mhluser = request.mhluser
    role_user = request.role_user
    user_type = request.user_type
    if 100 == user_type:
        return err_DM020()

    if (request.method == 'GET'):
        choices = ['Voicemail']
        if (mhluser.mobile_phone):
            choices.append('Mobile')
        if (role_user.office_phone):
            choices.append('Office')
        if (mhluser.phone):
            choices.append('Other')

        data = {
            'choices': choices,
            'current': role_user.get_forward_voicemail_display()
        }
        return HttpJSONSuccessResponse(data=data)

    form = GetFwdPrefsForm(request.POST)
    if (not form.is_valid()):
        return err_GE031(form)

    choice = form.cleaned_data['forward']
    if (choice == 'Mobile'):
        if (not mhluser.mobile_phone):
            return _err_AM010()
        role_user.forward_voicemail = "MO"
    elif (choice == 'Office'):
        if (not role_user.office_phone):
            return _err_AM010()
        role_user.forward_voicemail = "OF"
    elif (choice == 'Other'):
        if (not mhluser.phone):
            return _err_AM010()
        role_user.forward_voicemail = "OT"
    else:
        role_user.forward_voicemail = "VM"

    role_user.save()
    return HttpJSONSuccessResponse()
Exemple #14
0
def newTaskLogic(request):
	if (request.method != 'POST'):
		return err_GE002()
	form = NewTaskForm(request.POST)
	if (not form.is_valid()):
		return err_GE031(form)

	task = createFollowUp(form.cleaned_data, request.mhluser.id)
	data = {'id': task.id}
	return HttpJSONSuccessResponse(data=data)
Exemple #15
0
def getDComNumberLogic(request):
    role_user = request.role_user
    user_type = request.user_type
    number = ''
    if 100 == user_type or 300 == user_type:
        manager_practice = role_user.current_practice
        if manager_practice:
            number = manager_practice.mdcom_phone
    else:
        number = role_user.mdcom_phone
    data = {"number": number}
    return HttpJSONSuccessResponse(data=data)
Exemple #16
0
def createOfficeStaff(request):
	if (request.method != 'POST'):
		return err_GE002()

	staff_form = CreateOfficeStaffForm(request.POST)
	mhluser_form = CreateMHLUserForm(request.POST, request.FILES)
	if (not mhluser_form.is_valid()):
		return err_GE031(mhluser_form)
	if (not staff_form.is_valid()):
		return err_GE031(staff_form)

	createNewOfficeStaff(mhluser_form, staff_form, request.role_user)
	return HttpJSONSuccessResponse()
Exemple #17
0
def createBroker(request):
	if (request.method != 'POST'):
		return err_GE002()

	broker_form = CreateBrokerForm(request.POST)
	mhluser_form = CreateBrokerMHLUserForm(request.POST, request.FILES)
	if (not mhluser_form.is_valid()):
		return err_GE031(mhluser_form)
	if (not broker_form.is_valid()):
		return err_GE031(broker_form)

	createNewBroker(mhluser_form, broker_form, request.role_user)
	return HttpJSONSuccessResponse()
Exemple #18
0
def getMobilePhoneLogic(request):
    mobile_phone = ''
    mobile_confirmed = ''
    mhluser = request.mhluser
    if mhluser:
        mobile_phone = mhluser.mobile_phone
        mobile_confirmed = mhluser.mobile_confirmed

        data = {
            'mobile_phone': mobile_phone,
            'mobile_confirmed': mobile_confirmed
        }
    return HttpJSONSuccessResponse(data=data)
Exemple #19
0
def updateMobilePhoneLogic(request):
    if (request.method != 'POST'):
        return err_GE002()
    form = UpdateMobileForm(request.POST)
    if (not form.is_valid()):
        return err_GE031(form)
    mhluser_id = request.mhluser.id
    mobile_phone = form.cleaned_data["mobile_phone"]
    if has_mhluser_with_mobile_phone(mobile_phone, mhluser_id):
        return err_AM020()

    MHLUser.objects.filter(id=mhluser_id).update(mobile_phone=mobile_phone)
    return HttpJSONSuccessResponse()
Exemple #20
0
def markMessageLogic(request, read_flag=True):
    if (request.method != 'POST'):
        return err_GE002()
    form = MsgBatchIDForm(request.POST)
    if (not form.is_valid()):
        return err_GE031(form)
    read_timestamp = 0
    if read_flag:
        read_timestamp = int(time.time())
    message_ids = form.cleaned_data['message_ids']
    MessageBodyUserStatus.objects.filter(user=request.user,
     read_flag=not read_flag, msg_body__message__uuid__in=message_ids).\
      update(read_flag=read_flag, read_timestamp=read_timestamp)
    return HttpJSONSuccessResponse()
Exemple #21
0
def providerEditProfileLogic(request):
    if (request.method != 'POST'):
        return err_GE002()
    provider = request.role_user
    phys = Physician.objects.filter(user=provider)
    if phys and len(phys):
        phys = phys[0]
    else:
        phys = None

    old_url = None
    if provider.photo:
        old_url = provider.photo.name
    provider_form = ProviderForm(data=request.POST,
                                 files=request.FILES,
                                 instance=provider)
    if (not provider_form.is_valid()):
        return err_GE031(provider_form)

    physician_form = None
    if (phys):
        physician_form = PhysicianForm(request.POST, instance=phys)
        if (not physician_form.is_valid()):
            return err_GE031(physician_form)

    provider = provider_form.save(commit=False)
    provider.lat = provider_form.cleaned_data['lat']
    provider.longit = provider_form.cleaned_data['longit']
    provider.licensure_states = provider_form.cleaned_data['licensure_states']
    #add by xlin in 20120611 for issue897 that add city, address, zip into database
    provider.address1 = provider_form.cleaned_data['address1']
    provider.address2 = provider_form.cleaned_data['address2']
    provider.city = provider_form.cleaned_data['city']
    provider.state = provider_form.cleaned_data['state']
    provider.zip = provider_form.cleaned_data['zip']
    provider.save()
    if (physician_form):
        physician_form.save()

    new_url = None
    if provider.photo:
        new_url = provider.photo.name

    #thumbnail creating code moved from here to save method of provider mode
    #use common method to generate
    ImageHelper.generate_image(old_url, new_url)

    return HttpJSONSuccessResponse()
Exemple #22
0
def updateReferLogic(request, refer_id):
    """
	update_refer

	:param request: Recipient info
	:type request: django.core.handlers.wsgi.WSGIRequest
	:param refer_id: The refferal's id
	:type refer_id: uuid
	:returns: {
		'data': {},
		'warnings': {},
		}
	"""
    if (request.method != 'POST'):
        return err_GE002()
    form = ReferEditForm(request.POST)
    if (not form.is_valid()):
        return err_GE031(form)

    updateRefer(request, form, refer_id)
    return HttpJSONSuccessResponse()
Exemple #23
0
def getReceivedMessagesLogic(request, return_python=False):
    """
	Gets a list of the received message headers.

	If return_python is true, this will just return the object that would have
	been converted to JSON format.
	"""

    if (request.method != 'POST'):
        return err_GE002()
    form = MsgListForm(request.POST)
    if (not form.is_valid()):
        return err_GE031(form)
    data = getReceivedMessageListData(request.user, form.cleaned_data)

    if (return_python):
        return {
            'data': data,
            'warnings': {},
        }
    return HttpJSONSuccessResponse(data=data)
Exemple #24
0
def officeStaffEditProfileLogic(request):
    if (request.method != 'POST'):
        return err_GE002()

    staff = request.role_user
    old_url = None
    if staff.user.photo:
        old_url = staff.user.photo.name

    staff_form = OfficeStaffForm(request.POST, instance=staff)
    if not staff_form.is_valid():
        return err_GE031(staff_form)

    user_form = UserForm(request.POST, request.FILES, instance=staff.user)
    if not user_form.is_valid():
        return err_GE031(user_form)

    user_form.save(commit=False)
    staff_form.save()
    new_url = None
    if staff.user.photo:
        new_url = staff.user.photo.name
    ImageHelper.generate_image(old_url, new_url)
    return HttpJSONSuccessResponse()
Exemple #25
0
def composeMessageLogic(request, recipients_together=True, ss=None):
    if (request.method != 'POST'):
        return err_GE002()
    form = MsgCompositionForm(request.POST)
    if (not form.is_valid()):
        return err_GE031(form)

    sender = request.user
    sender_role_user = request.role_user
    subject = form.cleaned_data['subject']
    body = form.cleaned_data['body']
    recipients = []
    form.cleaned_data['recipients']
    if 'recipients' in form.cleaned_data and len(
            form.cleaned_data['recipients']) > 0:
        recipients = form.cleaned_data['recipients']

    elif 'practice_recipients' in form.cleaned_data and \
      len(form.cleaned_data['practice_recipients']) > 0:
        recipients = form.cleaned_data['practice_recipients']

    ccs = []
    if 'ccs' in form.cleaned_data and len(form.cleaned_data['ccs']) > 0:
        ccs = form.cleaned_data['ccs']

    attachments = []
    if ('attachment' in request.FILES):
        attachments = request.FILES.getlist('attachment')

    attachment_count = len(attachments)
    if not sendMessageCheck(sender, attachment_count, recipients, ccs):
        return HttpJSONErrorResponse(errno='MS002')
    exist_attchments = None
    if 'message_id' in form.cleaned_data and form.cleaned_data['message_id']\
     and 'attachment_ids' in form.cleaned_data and \
      len(form.cleaned_data['attachment_ids']) > 0:
        exist_attchments = {
            "message_id": form.cleaned_data['message_id'],
            "attachment_ids": form.cleaned_data['attachment_ids']
        }
    exist_refer = None
    if 'message_id' in form.cleaned_data and form.cleaned_data['message_id'] \
     and 'refer_id' in form.cleaned_data and form.cleaned_data['refer_id']:
        exist_refer = {
            "message_id": form.cleaned_data['message_id'],
            "refer_id": form.cleaned_data['refer_id']
        }

    thread_uuid = None
    if 'thread_uuid' in form.cleaned_data and form.cleaned_data['thread_uuid']:
        thread_uuid = form.cleaned_data['thread_uuid']

    if recipients_together:
        createNewMessage(request,
                         sender,
                         sender_role_user,
                         recipients,
                         body,
                         ccs=ccs,
                         subject=subject,
                         uploads=attachments,
                         exist_attchments=exist_attchments,
                         exist_refer=exist_refer,
                         thread_uuid=thread_uuid,
                         ss=ss)
    else:
        createNewADS(request,
                     sender,
                     sender_role_user,
                     recipients,
                     body,
                     subject=subject,
                     uploads=attachments)

    return HttpJSONSuccessResponse()
Exemple #26
0
def deleteTaskLogic(request, task_id):
	deleteFollowUp(task_id, request.mhluser.id)
	return HttpJSONSuccessResponse()
Exemple #27
0
def localOffice(request):
	data = None
	if request.role_user and hasattr(request.role_user, "current_practice")\
		and request.role_user.current_practice:
		data = getLocalOffice(request.role_user.current_practice)
	return HttpJSONSuccessResponse(data=data)
Exemple #28
0
def brokerProfileLogic(request):
    if (request.method != 'POST'):
        return HttpJSONSuccessResponse(
            data=brokerProfileView(request.role_user))
    else:
        return brokerEditProfileLogic(request)
Exemple #29
0
def getMessageLogic(request, message_id, ss=None):
    if (request.method != 'POST'):
        return err_GE002()

    msgs = list(
        MessageBodyUserStatus.objects.filter(
            user=request.user,
            delete_flag=False,
            msg_body__message__uuid=message_id).order_by(
                '-msg_body__message__send_timestamp').select_related(
                    'msg_body', 'msg_body__message',
                    'msg_body__message__sender'))

    # Integrity check.
    if (len(msgs) > 1):
        # shouldn't be possible!
        mail_admins(
            'Duplicate message ID', ' '.join([
                'server: ', settings.SERVER_ADDRESS, '\n',
                'The message id with uuid', message_id, 'has returned with',
                'more than one Message!\nAt: ',
                str(inspect.getfile(inspect.currentframe())), ':',
                str(inspect.currentframe().f_back.f_lineno)
            ]))
    if (len(msgs) == 0):
        raise Http404

    local_tz = timezone(settings.TIME_ZONE)
    status_obj = msgs[0]

    body = None
    try:
        # Get/set up data for KMS.
        request.session['key'] = request.device_assn.secret
        body = read_message(request, status_obj.msg_body, ss=ss)
    except KeyInvalidException:
        return err_GE021()

    if not body:
        return err_GE021()
    current_user = request.mhluser
    current_user_mobile = current_user.mobile_phone
    msg = status_obj.msg_body.message
    recipients = MessageRecipient.objects.filter(message__uuid=message_id).\
     select_related('user').only('user__first_name', 'user__last_name')
    ccs = MessageCC.objects.filter(message__uuid=message_id).\
     select_related('user').only('user__first_name', 'user__last_name')

    attachments = MessageAttachment.objects.filter(message=msg)

    ccs = MessageCC.objects.filter(message__uuid=message_id).select_related('user').\
     only('user__first_name', 'user__last_name', 'message')
    user = request.mhluser
    local_tz = getCurrentTimeZoneForUser(user)
    data = {
      'body': body,
      'timestamp': formatTimeSetting(user, msg.send_timestamp,
             local_tz),

      'sender': {
         'name': ' '.join([
           msg.sender.first_name, msg.sender.last_name]) \
            if msg.sender else "System Message",
         'id': msg.sender.id if msg.sender else 0,
        },
      'recipients': [{
         'name': ' '.join([
           u.user.first_name, u.user.last_name]),
         'id': u.user.id,
         } for u in recipients],
      'ccs': [{
         'name': ' '.join([
           u.user.first_name, u.user.last_name]),
         'id': u.user.id,
         } for u in ccs],
      'attachments': [
        {
         'id': att.uuid,
         'filename': _get_attachment_filename(request, att, ss=ss),
         'filesize': att.size,
         'suffix':att.suffix,
        } for att in attachments],
      'message_type': msg.message_type if msg.message_type else 'NM',
      'callback_number': msg.callback_number,
      'callback_available': settings.CALL_ENABLE and bool(msg.callback_number)
       and bool(current_user_mobile),
      'urgent': bool(msg.urgent),
      'resolution_flag': bool(msg._resolved_by_id),
      'refer': _get_refer_from_mbus(status_obj, logo_size="Large"),
      'thread_uuid': msg.thread_uuid
     }
    return HttpJSONSuccessResponse(data=data)
Exemple #30
0
def officeStaffProfileLogic(request):
    if (request.method != 'POST'):
        return HttpJSONSuccessResponse(
            data=officeStaffProfileView(request.role_user))
    else:
        return officeStaffEditProfileLogic(request)