コード例 #1
0
def _set_staff_list(staff, current_user, strip_staff_mobile=True, strip_staff_pager=True):
	"""
	Returns staff response data.
	:param users: is a list of Provider/OfficeStaff/OfficeManager.
	:param current_user: current_user is an instance of Provider/OfficeStaff.
	pass strip_staff_mobile=True if you want all office staff users(exclude managers and above they) to come back without a mobile phone number defined. This is useful if you don't want the u to seem call-able.

	
	pass strip_staff_pager=True if you want all office staff users(exclude managers and above they) to come back without a pager number defined. This is useful if you don't want the u to seem call-able.

	:returns: user list.
	"""
#	current_user_mobile = getCurrentUserMobile(current_user)
	current_user_mobile = current_user.user.mobile_phone
	object_ids = get_my_favorite_ids(current_user.user, object_type_flag=OBJECT_TYPE_FLAG_MHLUSER)
	user_list = []
	for s in staff:
		if (s.__class__.__name__ == 'Office_Manager'):
			user_info = {
					'id': s.user.user.id,
					'first_name': s.user.user.first_name,
					'last_name': s.user.user.last_name,
					'staff_type': _('Office Manager'),
					'has_mobile': bool(s.user.user.mobile_phone) and bool(current_user_mobile) and settings.CALL_ENABLE,
					'has_pager': bool(s.user.pager) and settings.CALL_ENABLE,
					'thumbnail': ImageHelper.get_image_by_type(s.user.user.photo, "Small", "Staff"),
					'user_photo_m': ImageHelper.get_image_by_type(s.user.user.photo, "Middle", "Staff"),
					'practice_photo': ImageHelper.get_image_by_type(s.user.current_practice.practice_photo, "Large", "Practice") \
						if s.user.current_practice else "",
					'prefer_logo': get_prefer_logo(s.user.user.id, current_practice=s.user.current_practice),
					'is_favorite': s.user.user.id in object_ids,
					'fullname':get_fullname(s.user.user)
				}
		else:
			user_info = {
					'id': s.user.id,
					'first_name': s.user.first_name,
					'last_name': s.user.last_name,
					'staff_type': _('Office Staff'),
					'has_mobile': not strip_staff_mobile and bool(s.user.mobile_phone) and bool(current_user_mobile) and settings.CALL_ENABLE,
					'has_pager': not strip_staff_pager and bool(s.pager) and settings.CALL_ENABLE,
					'thumbnail': ImageHelper.get_image_by_type(s.user.photo, "Small", "Staff"),
					'user_photo_m': ImageHelper.get_image_by_type(s.user.photo, "Middle", "Staff"),
					'practice_photo': ImageHelper.get_image_by_type(s.current_practice.practice_photo, "Large", "Practice") \
						if s.current_practice else "",
					'prefer_logo': get_prefer_logo(s.user.id, current_practice=s.current_practice),
					'is_favorite': s.user.id in object_ids,
					'fullname':get_fullname(s.user)
				}

			# TODO: Clean me up once we refactor the user classes.
			try:
				nurse = Nurse.objects.get(user=s)
				user_info['thumbnail'] = ImageHelper.get_image_by_type(s.user.photo, "Small", "Nurse")
				user_info['user_photo_m'] = ImageHelper.get_image_by_type(s.user.photo, "Middle", "Nurse"),
			except Nurse.DoesNotExist:
				pass
		user_list.append(user_info)
	return sorted_uses(user_list)
コード例 #2
0
ファイル: decorators.py プロジェクト: DongHuaLu/mdcom
def appendSettingInfoToResponse(request, resp):
	if hasattr(resp, "content") and resp.content:
		try:
			response = json.loads(resp.content)
			response = setSystemInfoToResponse(response)
			settings_json = response["settings"]
			mhluser = request.user
			user_type = int(request.user_type)
			role_user = request.role_user
			if mhluser:
				settings_json['current_time_zone'] = getCurrentTimeZoneForUser(mhluser, role_user)
				settings_json['time_setting'] = mhluser.time_setting if mhluser.time_setting else 0

				default_picture_type = "Provider"
				if USER_TYPE_DOCTOR != user_type:
					default_picture_type = "Staff"
					if Nurse.objects.filter(user=role_user).exists():
						default_picture_type = "Nurse"
				settings_json['user_photo_m'] = ImageHelper.get_image_by_type(
					mhluser.photo, "Middle", default_picture_type)
				settings_json['real_name'] = get_fullname(mhluser)
				settings_json['prefer_logo'] = get_prefer_logo(mhluser.id)

			return resp.__class__(content=json.dumps(response), mimetype='application/json')
		except ValueError:
			pass
	return resp
コード例 #3
0
def appendSettingInfoToResponse(request, resp):
    if hasattr(resp, "content") and resp.content:
        try:
            response = json.loads(resp.content)
            response = setSystemInfoToResponse(response)
            settings_json = response["settings"]
            mhluser = request.user
            user_type = int(request.user_type)
            role_user = request.role_user
            if mhluser:
                settings_json['current_time_zone'] = getCurrentTimeZoneForUser(
                    mhluser, role_user)
                settings_json[
                    'time_setting'] = mhluser.time_setting if mhluser.time_setting else 0

                default_picture_type = "Provider"
                if USER_TYPE_DOCTOR != user_type:
                    default_picture_type = "Staff"
                    if Nurse.objects.filter(user=role_user).exists():
                        default_picture_type = "Nurse"
                settings_json['user_photo_m'] = ImageHelper.get_image_by_type(
                    mhluser.photo, "Middle", default_picture_type)
                settings_json['real_name'] = get_fullname(mhluser)
                settings_json['prefer_logo'] = get_prefer_logo(mhluser.id)

            return resp.__class__(content=json.dumps(response),
                                  mimetype='application/json')
        except ValueError:
            pass
    return resp
コード例 #4
0
def _set_providers_list(providers, current_user, has_specialty=True):
	"""
	Returns org members response data.
	:param providers: is a list of Physician/NP_PA.
	:param current_user: current_user is an instance of Provider/OfficeStaff.
	:returns: user list.
	"""
	object_ids = get_my_favorite_ids(current_user.user, object_type_flag=OBJECT_TYPE_FLAG_MHLUSER)
#	current_user_mobile = getCurrentUserMobile(current_user)
	current_user_mobile = current_user.user.mobile_phone
	user_list = []
	for p in providers:
		user_info = {
				'id': p.user.user.id,
				'first_name': p.user.first_name,
				'last_name': p.user.last_name,
				'specialty': '',
				'has_mobile': bool(p.user.user.mobile_phone) and bool(current_user_mobile) and settings.CALL_ENABLE,
				'has_pager': bool(p.user.pager) and settings.CALL_ENABLE,
				'thumbnail': ImageHelper.get_image_by_type(p.user.user.photo, "Small", "Provider"),
				'user_photo_m': ImageHelper.get_image_by_type(p.user.user.photo, "Middle", "Provider"),
				'practice_photo': ImageHelper.get_image_by_type(p.user.current_practice.practice_photo, "Large", "Practice") \
						if p.user.current_practice else "",
				'prefer_logo': get_prefer_logo(p.user.user.id, current_practice=p.user.current_practice),
				'is_favorite': p.user.user.id in object_ids,
				'fullname': get_fullname(p.user)
			}
		if ('specialty' in dir(p) and p.specialty and has_specialty):
			user_info['specialty'] = p.get_specialty_display()
		if NP_PA.active_objects.filter(user=p.user):
			user_info['specialty'] = 'NP/PA/Midwife'

		user_list.append(user_info)
	return sorted_uses(user_list)
コード例 #5
0
def _set_org_members_list(users, current_user):
	"""
	Returns org members response data.
	:param users: is a list of Provider/OfficeStaff.
	:param current_user: current_user is an instance of Provider/OfficeStaff.
	:returns: user list.
	"""
	object_ids = get_my_favorite_ids(current_user.user, object_type_flag=OBJECT_TYPE_FLAG_MHLUSER)
#	current_user_mobile = getCurrentUserMobile(current_user)
	current_user_mobile = current_user.user.mobile_phone
#	current_user_pager = current_user.pager
	user_list = []
	for u in users:
		prefer_logo = get_prefer_logo(u.user.id, current_practice=u.current_practice)
		user_info = {
				'id': u.user.id,
				'first_name': u.user.first_name,
				'last_name': u.user.last_name,
				'specialty': '',
				'has_mobile': bool(u.user.mobile_phone) and bool(current_user_mobile) and settings.CALL_ENABLE,
				'has_pager': bool(u.pager) and settings.CALL_ENABLE,
				'practice_photo': ImageHelper.get_image_by_type(u.current_practice.practice_photo, "Large", "Practice") \
					if u.current_practice else "",
				'practice_photo_m': ImageHelper.get_image_by_type(u.current_practice.practice_photo, "Middle", "Practice") \
					if u.current_practice else "",
				'prefer_logo': prefer_logo,
				'is_favorite': u.user.id in object_ids,
				'fullname':get_fullname(u.user)
			}

		if(u.__class__.__name__ == 'OfficeStaff'):
			user_info["user_type"] = _('Office Staff')
			user_info["thumbnail"] = ImageHelper.get_image_by_type(u.user.photo, "Small", "Staff")
			user_info["user_photo_m"] = ImageHelper.get_image_by_type(u.user.photo, "Middle", "Staff")
			if Office_Manager.objects.filter(user=u).exists():
				user_info["user_type"] = _('Office Manager')
			else:
				# TODO: Clean me up once we refactor the u classes.
				try:
					nurse = Nurse.objects.get(user=u)
					user_info['thumbnail'] = ImageHelper.get_image_by_type(u.user.photo, "Small", "Nurse")
					user_info['user_photo_m'] = ImageHelper.get_image_by_type(u.user.photo, "Middle", "Nurse")
				except Nurse.DoesNotExist:
					pass

		elif(u.__class__.__name__ == 'Provider'):
			user_info["user_type"] = _('Provider')
			user_info["thumbnail"] = ImageHelper.get_image_by_type(u.user.photo, "Small", "Provider")
			user_info["user_photo_m"] = ImageHelper.get_image_by_type(u.user.photo, "Middle", "Provider")
			# TODO: Clean me up once we refactor the u classes.
			try:
				p = Physician.objects.get(user=u)
				user_info['specialty'] = p.get_specialty_display()
			except Physician.DoesNotExist:
				pass

		user_list.append(user_info)
	return sorted_uses(user_list)
コード例 #6
0
ファイル: views_users.py プロジェクト: cnzhuran/mdcom
def user_search(request):
	""" Query MHLUser by name (first and/or last) returning Providers and Staff """
	if (request.method != 'POST'):
		return err_GE002()
	form = UserSearchForm(request.POST)
	if (not form.is_valid()):
		return err_GE031(form)

	curr_mobile = request.role_user.user.mobile_phone
	object_ids = get_my_favorite_ids(request.user, OBJECT_TYPE_FLAG_MHLUSER)

	limit = form.cleaned_data['limit'] if 'limit' in form.cleaned_data else None
	qry = generate_name_query(form.cleaned_data['name'])
	user_qry = search_mhluser(qry, limit=limit)
	response = {'data': {'count': 0, 'results': []}, 'warnings': {}}

	provs = Provider.objects.filter(user__in=user_qry)
	staffs = OfficeStaff.objects.filter(user__in=user_qry)
	phys = Physician.objects.filter(user__in=provs)
	provs = {prov.user_id: prov for prov in provs}
	staffs = {staf.user_id: staf for staf in staffs}
	phys = {phy.user_id: phy for phy in phys}
	for user in user_qry:
		prov = provs[user.id] if user.id in provs else None
		staf = staffs[user.id] if user.id in staffs else None
		if not (staf or prov):
			continue  # only include staff/providers
		phy = phys[prov.id] if prov and prov.id in phys else None
		pract = (prov and prov.current_practice) or (staf and staf.current_practice)
		pphoto = pract and pract.practice_photo
		response['data']['results'].append({
			'id': user.id,
			'first_name': user.first_name,
			'last_name': user.last_name,
			'has_mobile': True if user.mobile_phone and curr_mobile else False,
			'has_pager': True if (prov and prov.pager) or (staf and staf.pager) else False,
			'thumbnail': get_image_by_type(user.photo, "Small", "Provider"),
			'user_photo_m': get_image_by_type(user.photo, "Middle", "Provider"),
			'practice_photo': get_image_by_type(pphoto, "Large", "Practice"), 
			'prefer_logo': get_prefer_logo(user.id, pract) if pract else '',
			'is_favorite': user.id in object_ids,
			'specialty': phy.get_specialty_display() if phy else '',
			'fullname':get_fullname(user)
		})
		response['data']['count'] += 1

	return HttpResponse(content=json.dumps(response), mimetype='application/json')
コード例 #7
0
ファイル: views_device.py プロジェクト: cnzhuran/mdcom
def associate(request):
    logger.debug(''.join(
        [str(request.session.session_key), '-Request: ',
         str(request)]))
    if (request.method == 'GET'):
        logger.debug(''.join(
            [str(request.session.session_key), '-Returning GE002!!!']))
        return err_GE002()
    form = AssociationForm(request.POST, auto_id=False)
    if (not form.is_valid()):
        return err_GE031(form)

    # Consider the compatibility, use the key: "allow_staff_login" -- it's optional,
    # distinguish different client version
    allow_staff_login = False
    if "allow_staff_login" in form.cleaned_data and form.cleaned_data[
            "allow_staff_login"]:
        allow_staff_login = True

    user = authenticate(username=form.cleaned_data['username'],
                        password=form.cleaned_data['password'])
    if (not user):
        err_obj = {
            'errno': 'DM001',
            'descr': _('Username or password incorrect.'),
        }
        return HttpResponseBadRequest(content=json.dumps(err_obj),
                                      mimetype='application/json')
    # TESTING_KMS_INTEGRATION check if user is g'fathered
    uprivs = UserPrivateKey.objects.filter(user=user,
                                           credtype=CRED_WEBAPP,
                                           gfather=True)
    if uprivs.exists():
        recrypt_keys(uprivs, settings.SECRET_KEY,
                     form.cleaned_data['password'])

    if (not user.is_active):
        return err_DM002()

    # Okay, everything checks out. Now check that the user is a Provider or Practice Manager
    providers = Provider.objects.filter(user=user.id)
    staff = OfficeStaff.objects.filter(user__pk=user.id)

    mobile_phone = ''
    mdcom_number = ''
    utype = None
    if providers and len(providers) > 0:
        utype = USER_TYPE_DOCTOR
        mdcom_number = providers[0].mdcom_phone
        mobile_phone = providers[0].user.mobile_phone
    elif staff and len(staff) > 0:
        staff = staff[0]

        if not staff_is_active(staff):
            return err_DM002()

        if not staff.user.has_perm('MHLUsers.access_smartphone'):
            return err_DM005()

        utype = USER_TYPE_OFFICE_STAFF
        manager_practice = staff.current_practice
        if manager_practice:
            mdcom_number = manager_practice.mdcom_phone
        mobile_phone = staff.user.mobile_phone

        if Office_Manager.objects.filter(user=staff).exists():
            utype = USER_TYPE_OFFICE_MANAGER
        else:
            if not allow_staff_login:
                return err_DM020()
    else:
        return err_DM020()

    # When user login from app, clean some assn, such as:
    #	1. Other user's assn in the same app client.
    #	2. Same user's assn in other app client.
    #		But, one user can login one mobile device and one tablet at the same time.
    # Now, the platform is only three options iPhone, Android, iPad.
    # If available platform options changed, please change the following logic.
    platform = form.cleaned_data['platform']
    old_assns = None
    if platform in ('iPhone', 'Android'):
        old_assns = SmartPhoneAssn.objects.filter(
            Q(device_serial=form.cleaned_data['device_id'])
            | Q(user__pk=user.pk, platform__in=('iPhone', 'Android')))
    else:
        old_assns = SmartPhoneAssn.objects.filter(
            Q(device_serial=form.cleaned_data['device_id'])
            | Q(user__pk=user.pk, platform='iPad'))
    if (old_assns and old_assns.exists()):
        for old_assn in old_assns:
            old_assn.dissociate(request, True)

    # get/set up all necessary crypto values.
    password = form.cleaned_data[
        'password']  # key strengthened below in different way
    local, remote = split_user_key(password)
    # NOTE: splitkey result reversed compared to web, but we should be
    # OK as long as whatever deemed remote is not stored server side.
    db_key = os.urandom(32)
    xor = XOR.new(base64.b64decode(remote))
    dbsplit = base64.b64encode(xor.encrypt(db_key))

    # Next, create the association object
    assn = SmartPhoneAssn(
        user_id=user.pk,
        device_serial=form.cleaned_data['device_id'],
        version=form.cleaned_data['app_version'],
        platform=platform,
        user_type=utype,
    )
    if ('name' in form.cleaned_data):
        assn.name = form.cleaned_data['name']
    assn.save(request)
    assn.update_secret(local, password)
    assn.update_db_secret(dbsplit, db_key)

    response = {
        'data': {
            'mdcom_id': assn.device_id,
            'secret': remote,
            'mdcom_number': mdcom_number,
            'mobile_phone': mobile_phone,
            'user_id': user.pk,
            # about the number of user_type, please read USER_TYPE_CHOICES
            # in the MHLogin.utils.contants.py
            'user_type': utype,
            'gcm_project_id': settings.GCM_PROJECT_ID,
            'call_available': settings.CALL_ENABLE and bool(mobile_phone)
        },
        'warnings': {},
    }

    setSystemInfoToResponse(response)
    response["settings"]['prefer_logo'] = get_prefer_logo(user.pk)
    return HttpResponse(content=json.dumps(response),
                        mimetype='application/json')
コード例 #8
0
ファイル: utils.py プロジェクト: cnzhuran/mdcom
def get_my_favorite(owner,
                    object_type_flag=None,
                    html=False,
                    can_send_refer=True,
                    show_picture=False):
    """ Get my favorite list.
	:param owner: is an instance of MHLUser
	:param object_type_flag: the flag of favorite object, refer to OBJECT_TYPE_FLAG_OPTS.
	:param html: return style: if html is True, then return favorite list as html style.
	:param can_send_refer: whether can send refer
	:param show_picture: whether show picture in list
	:returns: list of favorite or html string
	"""
    if not owner or not isinstance(owner, MHLUser):
        raise ValueError

    current_user_mobile = owner.mobile_phone
    q_t = Q(owner=owner)
    if object_type_flag:
        object_type_flag = int(object_type_flag)
        type = OBJECT_TYPE_FLAGS[object_type_flag]
        q_t = q_t & Q(object_type__model=type)
    favorites = Favorite.objects.filter(q_t).select_related("object_type")

    providers = Provider.objects.all().select_related("user",
                                                      "current_practice")
    provider_dict = _user_list_to_dict(providers)
    #	physician_user_ids = Physician.objects.all().values_list('user_id', flat=True)
    #	nppa_user_ids = NP_PA.objects.all().values_list('user_id', flat=True)

    staffs = OfficeStaff.objects.all().select_related("user",
                                                      "current_practice")
    staff_dict = _user_list_to_dict(staffs)

    manager_ids = Office_Manager.active_objects.all().values_list(
        'user_id', 'practice')
    manager_user_ids = []
    manager_practice_ids = []
    for ids in manager_ids:
        manager_user_ids.append(ids[0])
        manager_practice_ids.append(ids[1])

    nurse_user_ids = Nurse.objects.all().values_list('user_id', flat=True)
    #	dietician_user_ids = Dietician.objects.all().values_list('user_id', flat=True)

    ret_favorites = []
    for fav in favorites:
        try:
            obj = fav.object
            if not obj:
                continue
            obj_id = fav.object_id
            object_type_flag = OBJECT_TYPES[fav.object_type.model]
            object_name = ''
            object_name_web_display = ''
            object_type_display = ''
            photo = ''
            photo_m = ''
            prefer_logo = ''
            call_available = False
            msg_available = False
            pager_available = False
            refer_available = False
            refer_displayable = False
            current_practice = None

            if OBJECT_TYPE_FLAG_MHLUSER == object_type_flag:
                object_name_web_display = object_name = get_fullname(obj)
                object_type_display = _("User")
                call_available = bool(obj.mobile_phone) and bool(
                    current_user_mobile) and settings.CALL_ENABLE
                msg_available = True
                if obj_id in provider_dict:
                    object_type_display = _("Provider")
                    if show_picture:
                        photo = ImageHelper.get_image_by_type(
                            obj.photo, "Small", "Provider")
                        photo_m = ImageHelper.get_image_by_type(
                            obj.photo, "Middle", "Provider")
                    data = provider_dict[obj_id]

                    refer_available = data["has_practice"]
                    refer_displayable = can_send_refer
                    pager_available = bool(
                        data["pager"]) and settings.CALL_ENABLE
                    current_practice = data["current_practice"]

                elif obj_id in staff_dict:
                    object_type_display = _('Office Staff')
                    if show_picture:
                        photo = ImageHelper.get_image_by_type(
                            obj.photo, "Small", "Staff")
                        photo_m = ImageHelper.get_image_by_type(
                            obj.photo, "Middle", "Staff")

                    data = staff_dict[obj_id]
                    if data['id'] in manager_user_ids:
                        object_type_display = _('Office Manager')
                    elif data['id'] in nurse_user_ids:
                        if show_picture:
                            photo = ImageHelper.get_image_by_type(
                                obj.photo, "Small", "Nurse")
                            photo_m = ImageHelper.get_image_by_type(
                                obj.photo, "Middle", "Nurse")

                    pager_available = bool(
                        data["pager"]) and settings.CALL_ENABLE
                    current_practice = data["current_practice"]
                if show_picture:
                    prefer_logo = get_prefer_logo(
                        obj_id, current_practice=current_practice)

            elif OBJECT_TYPE_FLAG_ORG == object_type_flag:
                object_name_web_display = object_name = obj.practice_name
                object_type_display = _("Organization")
                if obj.organization_type and obj.organization_type.name:
                    object_type_display = obj.organization_type.name
                if show_picture:
                    photo = ImageHelper.get_image_by_type(
                        obj.practice_photo, "Large", 'Practice',
                        'img_size_practice')
                    photo_m = ImageHelper.get_image_by_type(
                        obj.practice_photo, "Middle", 'Practice',
                        'img_size_practice')
                call_available = (bool(obj.backline_phone) or bool(obj.practice_phone))\
                     and bool(current_user_mobile)\
                     and settings.CALL_ENABLE
                msg_available = obj_id in manager_practice_ids

            ret_favorites.append({
                "object_name": object_name,
                "object_name_web_display": object_name_web_display,
                "object_type_flag": object_type_flag,
                "object_type_display": object_type_display,
                "object_id": fav.object_id,
                "photo": photo,
                "photo_m": photo_m,
                "prefer_logo": prefer_logo,
                "call_available": call_available,
                "msg_available": msg_available,
                "pager_available": pager_available,
                "refer_available": refer_available,
                "refer_displayable": refer_displayable
            })

        except KeyError:
            pass

    ret_favorites = sorted(ret_favorites,
                           key=lambda item: item['object_name'].lower())
    if html:
        favorite_dict = {"favorites": ret_favorites}
        return render_to_string('my_favorite.html', favorite_dict)

    return ret_favorites
コード例 #9
0
ファイル: utils.py プロジェクト: DongHuaLu/mdcom
def get_my_favorite(owner, object_type_flag=None, html=False, can_send_refer=True,
				show_picture=False):
	""" Get my favorite list.
	:param owner: is an instance of MHLUser
	:param object_type_flag: the flag of favorite object, refer to OBJECT_TYPE_FLAG_OPTS.
	:param html: return style: if html is True, then return favorite list as html style.
	:param can_send_refer: whether can send refer
	:param show_picture: whether show picture in list
	:returns: list of favorite or html string
	"""
	if not owner or not isinstance(owner, MHLUser):
		raise ValueError

	current_user_mobile = owner.mobile_phone
	q_t = Q(owner=owner)
	if object_type_flag:
		object_type_flag = int(object_type_flag)
		type = OBJECT_TYPE_FLAGS[object_type_flag]
		q_t = q_t & Q(object_type__model=type)
	favorites = Favorite.objects.filter(q_t).select_related("object_type")

	providers = Provider.objects.all().select_related("user", "current_practice")
	provider_dict = _user_list_to_dict(providers)
#	physician_user_ids = Physician.objects.all().values_list('user_id', flat=True)
#	nppa_user_ids = NP_PA.objects.all().values_list('user_id', flat=True)

	staffs = OfficeStaff.objects.all().select_related("user", "current_practice")
	staff_dict = _user_list_to_dict(staffs)

	manager_ids = Office_Manager.active_objects.all().values_list('user_id', 'practice')
	manager_user_ids = []
	manager_practice_ids = []
	for ids in manager_ids:
		manager_user_ids.append(ids[0])
		manager_practice_ids.append(ids[1])

	nurse_user_ids = Nurse.objects.all().values_list('user_id', flat=True)
#	dietician_user_ids = Dietician.objects.all().values_list('user_id', flat=True)

	ret_favorites = []
	for fav in favorites:
		try:
			obj = fav.object
			if not obj:
				continue
			obj_id = fav.object_id
			object_type_flag = OBJECT_TYPES[fav.object_type.model]
			object_name = ''
			object_name_web_display = ''
			object_type_display = ''
			photo = ''
			photo_m = ''
			prefer_logo = ''
			call_available = False
			msg_available = False
			pager_available = False
			refer_available = False
			refer_displayable = False
			current_practice = None

			if OBJECT_TYPE_FLAG_MHLUSER == object_type_flag:
				object_name_web_display = object_name = get_fullname(obj)
				object_type_display = _("User")
				call_available = bool(obj.mobile_phone) and bool(current_user_mobile) and settings.CALL_ENABLE
				msg_available = True
				if obj_id in provider_dict:
					object_type_display = _("Provider")
					if show_picture:
						photo = ImageHelper.get_image_by_type(obj.photo, "Small", "Provider")
						photo_m = ImageHelper.get_image_by_type(obj.photo, "Middle", "Provider")
					data = provider_dict[obj_id]

					refer_available = data["has_practice"]
					refer_displayable = can_send_refer
					pager_available = bool(data["pager"]) and settings.CALL_ENABLE
					current_practice = data["current_practice"]

				elif obj_id in staff_dict:
					object_type_display = _('Office Staff')
					if show_picture:
						photo = ImageHelper.get_image_by_type(obj.photo, "Small", "Staff")
						photo_m = ImageHelper.get_image_by_type(obj.photo, "Middle", "Staff")

					data = staff_dict[obj_id]
					if data['id'] in manager_user_ids:
						object_type_display = _('Office Manager')
					elif data['id'] in nurse_user_ids:
						if show_picture:
							photo = ImageHelper.get_image_by_type(obj.photo, "Small", "Nurse")
							photo_m = ImageHelper.get_image_by_type(obj.photo, "Middle", "Nurse")

					pager_available = bool(data["pager"]) and settings.CALL_ENABLE
					current_practice = data["current_practice"]
				if show_picture:
					prefer_logo = get_prefer_logo(obj_id, current_practice = current_practice)

			elif OBJECT_TYPE_FLAG_ORG == object_type_flag:
				object_name_web_display = object_name = obj.practice_name
				object_type_display = _("Organization")
				if obj.organization_type and obj.organization_type.name:
					object_type_display = obj.organization_type.name 
				if show_picture:
					photo = ImageHelper.get_image_by_type(obj.practice_photo, 
						"Large", 'Practice', 'img_size_practice')
					photo_m = ImageHelper.get_image_by_type(obj.practice_photo,
						"Middle", 'Practice', 'img_size_practice')
				call_available = (bool(obj.backline_phone) or bool(obj.practice_phone))\
									and bool(current_user_mobile)\
									and settings.CALL_ENABLE
				msg_available = obj_id in manager_practice_ids

			ret_favorites.append({
				"object_name": object_name,
				"object_name_web_display": object_name_web_display,
				"object_type_flag": object_type_flag,
				"object_type_display": object_type_display,
				"object_id": fav.object_id,
				"photo": photo,
				"photo_m": photo_m,
				"prefer_logo": prefer_logo,
				"call_available": call_available,
				"msg_available": msg_available,
				"pager_available": pager_available,
				"refer_available": refer_available,
				"refer_displayable": refer_displayable
			})

		except KeyError:
			pass

	ret_favorites = sorted(ret_favorites, key=lambda item: item['object_name'].lower())
	if html:
		favorite_dict = {"favorites": ret_favorites}
		return render_to_string('my_favorite.html', favorite_dict)

	return ret_favorites
コード例 #10
0
ファイル: templates.py プロジェクト: DongHuaLu/mdcom
def processor(request, activeApp=None):
	"""Creates a dictionary complete with standard MyHealth template definitions."""
	context = {}

	mobile_device_check(request, context)

	context['debug'] = settings.DEBUG
	context['DEBUG'] = settings.DEBUG

	context['SERVER_ADDRESS'] = settings.SERVER_ADDRESS
	context['SERVER_PROTOCOL'] = settings.SERVER_PROTOCOL
	context['SERVERVERSION'] = "v%s" % '.'.join(__version__.split('.')[0:3])

	if (not 'MHL_UserIDs' in request.session or not 'MHL_Users' in request.session):
		return context

	# Get user types
	context['sender_types'] = request.session['MHL_UserIDs']

	if request and request.user.is_authenticated():
		# initialize to defaults
		context['current_site'] = ""
		context['current_practice'] = None
		context['current_time_zone'] = ""

		context['schedule_time_setting'] = 1

		if ('Provider' in request.session['MHL_Users']):
			provider = request.session['MHL_Users']['Provider']
			user = provider
			context['user_is_provider'] = True
			context['current_site'] = provider.current_site
			context['practice'] = provider.practices.filter(\
				organization_type__pk=RESERVED_ORGANIZATION_TYPE_ID_PRACTICE)
			current_practice = provider.current_practice
			if current_practice and current_practice.organization_type\
				and RESERVED_ORGANIZATION_TYPE_ID_PRACTICE == current_practice.organization_type.id:
				context['current_practice'] = current_practice
			context['unread_msg_count'] = provider.vm_msgs.filter(read_flag=False).count()
			sites = user.sites.all()
			if (user.current_site):
				current_site = {'current': user.current_site.id}
				context['site_form'] = CurrentSiteForm(sites, initial=current_site)
			else:
				context['site_form'] = CurrentSiteForm(sites)
		#inna - add some info for office manager	
		if ('OfficeStaff' in request.session['MHL_Users']):
			#add by xlin in 20120328 to fix bug 580 that current site not show
			context['current_site'] = request.session['MHL_Users']['OfficeStaff'].current_site

			if ('OfficeStaff' in request.session['MHL_Users']):
				staff = request.session['MHL_Users']['OfficeStaff']
				user = staff
				context['current_practice'] = request.\
					session['MHL_Users']['OfficeStaff'].current_practice
				context['current_practice_can_have_any_staff'] = \
						context['current_practice'] and\
						context['current_practice'].can_have_any_staff()
				context['current_practice_can_have_any_provider'] = \
						context['current_practice'] and\
						context['current_practice'].can_have_any_provider()

			if  ('Office_Manager' in request.session['MHL_UserIDs']):
				context['user_is_office_manager'] = True
				office_staff = request.session['MHL_Users']['OfficeStaff']
				user = office_staff
				context['managed_practices'] = get_managed_practice(office_staff)
			else:
				context['user_is_office_staff'] = True
			sites = user.sites.all()
			if (user.current_site):
				current_site = {
								'current': user.current_site.id,
						}
				context['site_form'] = CurrentSiteForm(sites, initial=current_site)
			else:
				context['site_form'] = CurrentSiteForm(sites)

		context['mhl_user_displayName'] = get_fullname(request.session['MHL_Users']['MHLUser'])
		current_time_zone_key = getCurrentTimeZoneForUser(
				request.session['MHL_Users']['MHLUser'],
				current_practice=context['current_practice'])
		context['current_time_zone'] = getDisplayedTimeZone(current_time_zone_key)

		#add by xlin 121017 for todo1045
		if request.session['MHL_Users']['MHLUser'].time_setting:
			context['schedule_time_setting'] = 0
		else:
			context['schedule_time_setting'] = 1

		# TODO, if dcAdmin need custom_logo, remove the limitation.
		if "dcAdmin" not in request.path_info:
			context['prefer_logo'] = get_prefer_logo(request.session['MHL_Users']['MHLUser'].id)

		current_practice = context['current_practice']
		context['can_have_answering_service'] = False
		context["current_organization_type"] = ""
		if current_practice:
			context['can_have_answering_service'] = current_practice.\
				get_setting_attr('can_have_answering_service')
			context["current_organization_type"] = get_org_type_name(current_practice)

	return context
コード例 #11
0
ファイル: views_device.py プロジェクト: DongHuaLu/mdcom
def associate(request):
	logger.debug(''.join([str(request.session.session_key), '-Request: ', str(request)]))
	if (request.method == 'GET'):
		logger.debug(''.join([str(request.session.session_key), '-Returning GE002!!!']))
		return err_GE002()
	form = AssociationForm(request.POST, auto_id=False)
	if (not form.is_valid()):
		return err_GE031(form)

	# Consider the compatibility, use the key: "allow_staff_login" -- it's optional,
	# distinguish different client version
	allow_staff_login = False
	if "allow_staff_login" in form.cleaned_data and form.cleaned_data["allow_staff_login"]:
		allow_staff_login = True

	user = authenticate(username=form.cleaned_data['username'],
				password=form.cleaned_data['password'])
	if (not user):
		err_obj = {
			'errno': 'DM001',
			'descr': _('Username or password incorrect.'),
		}
		return HttpResponseBadRequest(content=json.dumps(err_obj), mimetype='application/json')
	# TESTING_KMS_INTEGRATION check if user is g'fathered
	uprivs = UserPrivateKey.objects.filter(user=user, credtype=CRED_WEBAPP, gfather=True)
	if uprivs.exists():
		recrypt_keys(uprivs, settings.SECRET_KEY, form.cleaned_data['password'])

	if (not user.is_active):
		return err_DM002()

	# Okay, everything checks out. Now check that the user is a Provider or Practice Manager
	providers = Provider.objects.filter(user=user.id)
	staff = OfficeStaff.objects.filter(user__pk=user.id)

	mobile_phone = ''
	mdcom_number = ''
	utype = None
	if providers and len(providers) > 0:
		utype = USER_TYPE_DOCTOR
		mdcom_number = providers[0].mdcom_phone
		mobile_phone = providers[0].user.mobile_phone
	elif staff and len(staff) > 0:
		staff = staff[0]

		if not staff_is_active(staff):
			return err_DM002()

		if not staff.user.has_perm('MHLUsers.access_smartphone'):
			return err_DM005()

		utype = USER_TYPE_OFFICE_STAFF
		manager_practice = staff.current_practice
		if manager_practice:
			mdcom_number = manager_practice.mdcom_phone
		mobile_phone = staff.user.mobile_phone

		if Office_Manager.objects.filter(user=staff).exists():
			utype = USER_TYPE_OFFICE_MANAGER
		else:
			if not allow_staff_login:
				return err_DM020()
	else:
		return err_DM020()

	# When user login from app, clean some assn, such as:
	#	1. Other user's assn in the same app client.
	#	2. Same user's assn in other app client.
	#		But, one user can login one mobile device and one tablet at the same time.
	# Now, the platform is only three options iPhone, Android, iPad. 
	# If available platform options changed, please change the following logic.
	platform = form.cleaned_data['platform']
	old_assns = None
	if platform in ('iPhone', 'Android'):
		old_assns = SmartPhoneAssn.objects.filter(Q(device_serial=form.cleaned_data['device_id']) | 
			Q(user__pk=user.pk, platform__in=('iPhone', 'Android')))
	else:
		old_assns = SmartPhoneAssn.objects.filter(Q(device_serial=form.cleaned_data['device_id']) | 
			Q(user__pk=user.pk, platform='iPad'))
	if (old_assns and old_assns.exists()):
		for old_assn in old_assns:
			old_assn.dissociate(request, True)

	# get/set up all necessary crypto values.
	password = form.cleaned_data['password']  # key strengthened below in different way
	local, remote = split_user_key(password)
	# NOTE: splitkey result reversed compared to web, but we should be
	# OK as long as whatever deemed remote is not stored server side.
	db_key = os.urandom(32)
	xor = XOR.new(base64.b64decode(remote))
	dbsplit = base64.b64encode(xor.encrypt(db_key))

	# Next, create the association object
	assn = SmartPhoneAssn(
			user_id=user.pk,
			device_serial=form.cleaned_data['device_id'],
			version=form.cleaned_data['app_version'],
			platform=platform,
			user_type=utype,
		)
	if ('name' in form.cleaned_data):
		assn.name = form.cleaned_data['name']
	assn.save(request)
	assn.update_secret(local, password)
	assn.update_db_secret(dbsplit, db_key)

	response = {
		'data': {
				'mdcom_id': assn.device_id,
				'secret': remote,
				'mdcom_number': mdcom_number,
				'mobile_phone': mobile_phone,
				'user_id': user.pk,
				# about the number of user_type, please read USER_TYPE_CHOICES 
				# in the MHLogin.utils.contants.py 
				'user_type': utype,
				'gcm_project_id': settings.GCM_PROJECT_ID,
				'call_available': settings.CALL_ENABLE and bool(mobile_phone)
			},
		'warnings': {},
	}

	setSystemInfoToResponse(response)
	response["settings"]['prefer_logo'] = get_prefer_logo(user.pk)
	return HttpResponse(content=json.dumps(response), mimetype='application/json')
コード例 #12
0
ファイル: templates.py プロジェクト: cnzhuran/mdcom
def processor(request, activeApp=None):
    """Creates a dictionary complete with standard MyHealth template definitions."""
    context = {}

    mobile_device_check(request, context)

    context['debug'] = settings.DEBUG
    context['DEBUG'] = settings.DEBUG

    context['SERVER_ADDRESS'] = settings.SERVER_ADDRESS
    context['SERVER_PROTOCOL'] = settings.SERVER_PROTOCOL
    context['SERVERVERSION'] = "v%s" % '.'.join(__version__.split('.')[0:3])

    if (not 'MHL_UserIDs' in request.session
            or not 'MHL_Users' in request.session):
        return context

    # Get user types
    context['sender_types'] = request.session['MHL_UserIDs']

    if request and request.user.is_authenticated():
        # initialize to defaults
        context['current_site'] = ""
        context['current_practice'] = None
        context['current_time_zone'] = ""

        context['schedule_time_setting'] = 1

        if ('Provider' in request.session['MHL_Users']):
            provider = request.session['MHL_Users']['Provider']
            user = provider
            context['user_is_provider'] = True
            context['current_site'] = provider.current_site
            context['practice'] = provider.practices.filter(\
             organization_type__pk=RESERVED_ORGANIZATION_TYPE_ID_PRACTICE)
            current_practice = provider.current_practice
            if current_practice and current_practice.organization_type\
             and RESERVED_ORGANIZATION_TYPE_ID_PRACTICE == current_practice.organization_type.id:
                context['current_practice'] = current_practice
            context['unread_msg_count'] = provider.vm_msgs.filter(
                read_flag=False).count()
            sites = user.sites.all()
            if (user.current_site):
                current_site = {'current': user.current_site.id}
                context['site_form'] = CurrentSiteForm(sites,
                                                       initial=current_site)
            else:
                context['site_form'] = CurrentSiteForm(sites)
        #inna - add some info for office manager
        if ('OfficeStaff' in request.session['MHL_Users']):
            #add by xlin in 20120328 to fix bug 580 that current site not show
            context['current_site'] = request.session['MHL_Users'][
                'OfficeStaff'].current_site

            if ('OfficeStaff' in request.session['MHL_Users']):
                staff = request.session['MHL_Users']['OfficeStaff']
                user = staff
                context['current_practice'] = request.\
                 session['MHL_Users']['OfficeStaff'].current_practice
                context['current_practice_can_have_any_staff'] = \
                  context['current_practice'] and\
                  context['current_practice'].can_have_any_staff()
                context['current_practice_can_have_any_provider'] = \
                  context['current_practice'] and\
                  context['current_practice'].can_have_any_provider()

            if ('Office_Manager' in request.session['MHL_UserIDs']):
                context['user_is_office_manager'] = True
                office_staff = request.session['MHL_Users']['OfficeStaff']
                user = office_staff
                context['managed_practices'] = get_managed_practice(
                    office_staff)
            else:
                context['user_is_office_staff'] = True
            sites = user.sites.all()
            if (user.current_site):
                current_site = {
                    'current': user.current_site.id,
                }
                context['site_form'] = CurrentSiteForm(sites,
                                                       initial=current_site)
            else:
                context['site_form'] = CurrentSiteForm(sites)

        context['mhl_user_displayName'] = get_fullname(
            request.session['MHL_Users']['MHLUser'])
        current_time_zone_key = getCurrentTimeZoneForUser(
            request.session['MHL_Users']['MHLUser'],
            current_practice=context['current_practice'])
        context['current_time_zone'] = getDisplayedTimeZone(
            current_time_zone_key)

        #add by xlin 121017 for todo1045
        if request.session['MHL_Users']['MHLUser'].time_setting:
            context['schedule_time_setting'] = 0
        else:
            context['schedule_time_setting'] = 1

        # TODO, if dcAdmin need custom_logo, remove the limitation.
        if "dcAdmin" not in request.path_info:
            context['prefer_logo'] = get_prefer_logo(
                request.session['MHL_Users']['MHLUser'].id)

        current_practice = context['current_practice']
        context['can_have_answering_service'] = False
        context["current_organization_type"] = ""
        if current_practice:
            context['can_have_answering_service'] = current_practice.\
             get_setting_attr('can_have_answering_service')
            context["current_organization_type"] = get_org_type_name(
                current_practice)

    return context