def sales_getproductdata(request): """ Process a get product data request from client :param request: The HTTP request, POST with with argument :type request: django.core.handlers.wsgi.WSGIRequest :returns: django.http.HttpResponse -- the result data in xml format """ sales_id = request.GET['id'] sl = SalesLeads.objects.get(id=sales_id) if (fullLeadAccess(request) or request.session['MHL_UserIDs']['MHLUser'] == sl.rep.pk): prods = SalesProduct.objects.filter(lead=sl.id) data = list(prods) for d in data: d.is_active = "1" if d.is_active == True else "0" resp = render_to_response('sales_getproductdata.xml', {'data': data, 'total': prods.count(), 'pos': 0}, mimetype='text/xml', context_instance=get_context(request)) else: resp = render_to_response('sales_getproductdata.xml', {'data': [], 'total': 0, 'pos': 0}, mimetype='text/xml', context_instance=get_context(request)) return resp
def cleanDB(request): context = get_context(request) if (settings.SERVER_ADDRESS == "www.mdcom.com"): return render_to_response('data_sanitation/production_error.html', context) if (not settings.DEBUG): raise Exception(_('Debug mode must be set to sanitize data')) context = get_context(request) if (request.method == "POST"): form = sanitationConfirmationForm(request.POST) if (form.is_valid()): # always run clean_MHLUsers first since other clean functions will # pull from the user's name clean_MHLUsers() clean_DoctorCom() clean_Billing() clean_Invites() clean_followup() else: form = sanitationConfirmationForm() context['form'] = form context['server_address'] = settings.SERVER_ADDRESS context['server_port'] = settings.SERVER_PORT return render_to_response('data_sanitation/confirmation.html', context)
def sales_getproductdata(request): """ Process a get product data request from client :param request: The HTTP request, POST with with argument :type request: django.core.handlers.wsgi.WSGIRequest :returns: django.http.HttpResponse -- the result data in xml format """ sales_id = request.GET['id'] sl = SalesLeads.objects.get(id=sales_id) if (fullLeadAccess(request) or request.session['MHL_UserIDs']['MHLUser'] == sl.rep.pk): prods = SalesProduct.objects.filter(lead=sl.id) data = list(prods) for d in data: d.is_active = "1" if d.is_active == True else "0" resp = render_to_response('sales_getproductdata.xml', { 'data': data, 'total': prods.count(), 'pos': 0 }, mimetype='text/xml', context_instance=get_context(request)) else: resp = render_to_response('sales_getproductdata.xml', { 'data': [], 'total': 0, 'pos': 0 }, mimetype='text/xml', context_instance=get_context(request)) return resp
def profile_edit_broker(request): broker = request.session['MHL_Users']['Broker'] context = get_context(request) #context['all_providers_box'] = box_all_providers() if (request.method == "POST"): old_url = None if broker.user.photo: old_url = broker.user.photo.name # First, deal with user form stuff if("old_password" in request.POST): password_form = ChangePasswordForm(broker.user, request.POST) broker_form = BrokerForm(instance=broker) user_form = BrokerUserForm(instance=broker.user) else: broker_form = BrokerForm(request.POST, instance=broker) user_form = BrokerUserForm(request.POST, request.FILES, instance=broker.user) password_form = ChangePasswordForm(broker.user) preference_form = PreferenceForm(request.POST, instance=broker.user) #user_form.save(commit=False) context['user'] = broker context['user_form'] = user_form context['broker_form'] = broker_form context['password_form'] = password_form context['preference_form'] = preference_form if(password_form.is_valid()): if(password_form.cleaned_data['old_password']): response = HttpResponseRedirect(reverse('MHLogin.MHLUsers.views.profile_view')) return change_pass(password_form, request, response) if (broker_form.is_valid() and user_form.is_valid() and preference_form.is_valid()): broker_form.save() user_form.save() mhluser = MHLUser.objects.get(id=broker.user.id) mhluser.time_setting = preference_form.cleaned_data['time_setting'] mhluser.time_zone = preference_form.cleaned_data['time_zone'] mhluser.save() context = get_context(request) new_url = None if broker.user.photo: new_url = broker.user.photo.name ImageHelper.generate_image(old_url, new_url) return HttpResponseRedirect(reverse('MHLogin.MHLUsers.views.profile_view')) else: context['user'] = broker context['user_form'] = BrokerUserForm(instance=broker.user) context['broker_form'] = BrokerForm(instance=broker) context['password_form'] = ChangePasswordForm(user=broker.user) context['preference_form'] = PreferenceForm(initial={'time_setting': broker.user.time_setting if broker.user.time_setting else 0, 'time_zone': broker.user.time_zone}) context['mobile_required'] = True from django import conf context['Language'] = LANGUAGE[conf.settings.FORCED_LANGUAGE_CODE] return render_to_response('Profile/profile_edit.html', context)
def profile_preference(request): context = get_context(request) mhluser = request.session['MHL_Users']['MHLUser'] if request.method == 'POST': if 'Provider' in request.session['MHL_Users']: form = PreferenceProviderForm(request.POST, instance=mhluser) else: form = PreferenceForm(request.POST, instance=mhluser) if form.is_valid(): form.save() # refresh context after saving context = get_context(request) context['flag'] = 1 else: if 'Provider' in request.session['MHL_Users']: form = PreferenceProviderForm( initial={ 'time_setting': mhluser.time_setting if mhluser.time_setting else 0, 'time_zone': mhluser.time_zone, 'refer_forward': mhluser.refer_forward }) else: form = PreferenceForm( initial={ 'time_setting': mhluser.time_setting if mhluser.time_setting else 0, 'time_zone': mhluser.time_zone }) context['flag'] = 0 context['form'] = form from django import conf context['Language'] = LANGUAGE[conf.settings.FORCED_LANGUAGE_CODE] practice = context['current_practice'] context['current_practice_time_zone'] = '' context['user_old_time_zone'] = mhluser.time_zone if practice and practice.time_zone: try: context['current_practice_time_zone'] = \ OLD_TIME_ZONES_MIGRATION[practice.time_zone] except: pass return render_to_response('Profile/profile_preference.html', context)
def main_broker(request, user): """Displays the broker's home page.""" context = get_context(request) context['auto_refresh_time'] = settings.MSGLIST_AUTOREFRESH_TIME context['user_type'] = 300 context['unread_msg_count'] = get_message_count(user.user, ('ANS', 'VM'), read_flag=False) community_physicians = get_community_providers_by_coords( user.user.lat, user.user.longit) set_providers_result(community_physicians, request) context['community_physicians'] = community_physicians context['mdcom_fwd'] = user.get_forward_voicemail_display() context['anssvc_fwd'] = user.get_forward_anssvc_display() context['mobile_phone'] = phone_formater(user.user.mobile_phone) context['office_phone'] = phone_formater(user.office_phone) context['other_phone'] = phone_formater(user.user.phone) context['mdcom_phone'] = phone_formater(user.mdcom_phone, display_provisionLink=True) context['zip'] = user.user.zip pend_assoc = Pending_Association.objects.filter( to_user=request.user).count() context['accept_invites_count'] = pend_assoc context['providers'] = community_physicians mhluser = request.session['MHL_Users']['MHLUser'] context['favorites'] = get_my_favorite(mhluser, can_send_refer=False) context['licensure_list'] = [('ALL', _('ALL'))] + list(STATE_CHOICES) return render_to_response('dashboard_broker.html', context)
def member_org_invite_incoming(request): context = get_context(request) if ('Office_Manager' in request.session['MHL_Users']): manager = request.session['MHL_Users']['Office_Manager'] # get_managed_practice can only get the root managed practices managed_organizations = get_managed_practice(manager.user) org_ids = [org.id for org in managed_organizations] pendings = Pending_Org_Association.objects.filter(to_practicelocation__id__in=org_ids).\ select_related('from_practicelocation', 'to_practicelocation') org_pendings = [ { 'pending_id': pending.id, 'sender_name': " ".join([pending.sender.first_name, pending.sender.last_name]), 'from_practicelocation_logo': ImageHelper.get_image_by_type( pending.from_practicelocation.practice_photo, "Middle", 'Practice', 'img_size_practice'), 'from_practicelocatin_type': pending.from_practicelocation.organization_type.name, 'from_practicelocation_name': pending.from_practicelocation.practice_name, 'to_practicelocation_name': pending.to_practicelocation.practice_name, 'to_practicelocatin_type': pending.to_practicelocation.organization_type.name, } for pending in pendings] org_pendings_ret = [ render_to_string('MHLOrganization/MemberOrg/invitation_notification.html', p) for p in org_pendings] return HttpResponse(json.dumps(org_pendings_ret), mimetype='application/json')
def logfile_view(request, logfile_id, root_path): """ return list of log file contents paged by main regexp""" context = get_context(request) manager = LogFilesManager() try: page = int(request.GET['page']) if 'page' in request.GET else 1 except ValueError: page = 1 files_tup = manager.list_logfiles() try: filename = files_tup[int(logfile_id)][0] except Exception as e: return HttpResponseBadRequest(str(e)) paginator = Paginator(manager.get_file_lines_count(open(filename, 'rb')), LOG_FILES_PAGINATE_LINES) paged_lines = paginator.page(page) first_line = paged_lines.object_list[0] if paged_lines.object_list else 0 paged_lines.object_list = manager.parse_log_file(filename, first_line) header_list = manager.compile_header_from_regexp() context['cl'] = LogFileChangeList(getattr(LogFiles, '_meta')) context['header_list'] = header_list context['file_name'] = filename context['file_id'] = logfile_id context['paginator'] = paged_lines context['page'] = page context['app_label'] = getattr(LogFiles, '_meta').app_label context['root_path'] = root_path context['title'] = 'Logfile contents' return render_to_response('logfile_change_form.html', context)
def refer_tracking(request): context = get_context(request) form_init_data = { 'period_from': date.today() + relativedelta(months=-1), 'period_to': date.today(), 'period_radio': '1', 'period_type': 9 } if (request.method == 'POST'): form = ReferTrackingForm(request.POST) if form.is_valid(): period_type = form.cleaned_data['period_type'] period_radio = form.cleaned_data['period_radio'] period_from = form.cleaned_data['period_from'] period_to = form.cleaned_data['period_to'] if (period_radio == '0'): period_from, period_to = get_peirod(period_type) form_init_data = { 'period_from': period_from, 'period_to': period_to, 'period_radio': period_radio, 'period_type': period_type } context['form'] = ReferTrackingForm(initial=form_init_data) return render_to_response('refer_tracking.html', context)
def sales_updateproductdata(request): """ Updates sales product data row and return status :param request: The HTTP request, POST with with argument :type request: django.core.handlers.wsgi.WSGIRequest :returns: django.http.HttpResponse -- the result data in xml format """ stat = request.GET['!nativeeditor_status'] if (stat == 'updated'): sp = SalesProduct.objects.get(id=request.GET['gr_id']) sp.is_active = False if request.GET['c0'] == "0" else True sp.quoted_price = request.GET['c3'] sp.save() resp = render_to_response('sales_updatedata.xml', { 'action': 'insert', 'tid': sp.id, 'sid': request.GET['gr_id'] }, mimetype='text/xml', context_instance=get_context(request)) else: errmsg = _("Unhandled stat: %s") % (stat) logger.warn(errmsg) resp = sale_error(request, errmsg) return resp
def reset_private_keys(request): """ This view takes the KMS administrator password, and for each user whose password was reset, generates new private keys. :param request: The HTTP request :type request: django.core.handlers.wsgi.WSGIRequest :returns: django.http.HttpResponse -- The webpage """ context, resp = get_context(request), None log_qs = PasswordResetLog.objects.filter(reset=True, resolved=False).values('user') reset_users = context['reset_users'] = MHLUser.objects.filter(pk__in=log_qs) if request.method == 'POST': form = context['form'] = PasswordForm(request.POST) if form.is_valid(): try: from MHLogin._admin_reset import ADMIN_RESET_ENCD_RSA creds = strengthen_key(form.cleaned_data['password']) admin_rsa = import_rsa(ADMIN_RESET_ENCD_RSA, creds) except ValueError: msg = _('Invalid password for admin reset key.') form._errors['password'] = form.error_class([msg]) else: for user in reset_users: reset_user_invalid_keys(user, admin_rsa) PasswordResetLog.objects.filter(reset=True, resolved=False, user=user).update(resolved=True, servicer=request.user, servicer_ip=request.META['REMOTE_ADDR'], resolution_timestamp=datetime.datetime.now()) resp = render_to_response('PrivateKeyResetComplete.html', context) else: context['form'] = PasswordForm() return resp or render_to_response('PrivateKeyReset.html', context)
def practice_edit_access_numbers(request): context = get_context(request) context['isClearData'] = 0 if ('Office_Manager' not in request.session['MHL_UserIDs']): raise Exception( _('Only Office Managers can edit practice access numbers')) staff = request.session['MHL_Users']['OfficeStaff'] practice = staff.current_practice context['access_numbers'] = practice.accessnumber_set.all() if (request.method == 'POST'): # p = request.POST if ('newnumber' in request.POST): addform = AccessNumberForm(request.POST) if (addform.is_valid()): number = addform.save(commit=False) number.practice = practice context['isClearData'] = 1 number.save() else: addform = AccessNumberForm() if ('delnumber' in request.POST): removeform = RemoveForm(request.POST, choices=[(n.id, n.id) for n in context['access_numbers'] ]) if (removeform.is_valid()): ids = removeform.cleaned_data['remove'] AccessNumber.objects.filter(practice=practice, id__in=ids).delete() else: addform = AccessNumberForm() context['addform'] = addform context['access_numbers'] = practice.accessnumber_set.all() return render_to_response("Profile/practice_edit_access.html", context)
def changepin(request): context = get_context(request) if (request.method == 'POST'): form = PinChangeForm(request.POST) form.user = request.user if (form.is_valid()): if 'Provider' in request.session['MHL_Users']: provider = Provider.objects.get(user__id=request.user.id) config = provider.vm_config.get() config.change_pin(request, new_pin=form.cleaned_data['pin1']) return render_to_response('Profile/changepinconfirmed.html', context) elif 'Broker' in request.session['MHL_Users']: broker = Broker.objects.get(user__id=request.user.id) config = broker.vm_config.get() config.change_pin(request, new_pin=form.cleaned_data['pin1']) return render_to_response('Profile/changepinconfirmed.html', context) #add by xlin 121119 to fix bug 855 that practice mgr can change pin elif 'OfficeStaff' in request.session['MHL_Users']: os = OfficeStaff.objects.get(user__id=request.user.id) practice = os.current_practice practice.pin = get_new_pin_hash(form.cleaned_data['pin1']) practice.save() return render_to_response( 'Profile/practicechangepinconfirmed.html', context) context['form'] = form if (not 'form' in context): context['form'] = PinChangeForm() if 'OfficeStaff' in request.session['MHL_Users']: return render_to_response('Profile/practicechangepin.html', context) return render_to_response('Profile/changepin.html', context)
def inviteHome(request): context = get_context(request) if (request.user.is_staff): invites = Invitation.objects.filter(sender=request.user, userType__in=(1, 2, 10)).all() context['user_is_staff'] = request.user.is_staff else: #context['outstandingInvites'] = Invitation.objects.filter(sender=request.user).all() #context['outstandingInvites'] = list(Invitation.objects.filter( # sender=request.session['MHL_UserIDs']['MHLUser'], assignPractice=None)) invites = Invitation.objects.filter( sender=request.session['MHL_UserIDs']['MHLUser'], userType__in=(1, 2, 10)) user = request.session['MHL_Users']['MHLUser'] practice = context['current_practice'] result = [] for invite in invites: obj = {} obj['recipient'] = invite.recipient invite_time = convert_dt_to_utz(invite.requestTimestamp, user, practice) obj['requestTimestamp'] = time_format(user, invite_time) obj['code'] = invite.code obj['sender'] = invite.sender obj['id'] = invite.id result.append(obj) context['outstandingInvites'] = result return render_to_response('Invites/inviteHome.html', context)
def broker_tracking(request): context = get_context(request) broker_user_id = None try: broker_user_id = request.GET['user_id'] context['broker_user_id'] = broker_user_id except: pass broker_from = broker_user_id or -1 broker_to = '' directions = 1 period_from = '' period_to = '' if (request.method == 'POST'): form = BrokerQueryForm(request.POST) if form.is_valid(): broker_from = int(form.cleaned_data['broker_from']) broker_to = form.cleaned_data['broker_to'] directions = int(form.cleaned_data['directions']) period_from = form.cleaned_data['period_from'] period_to = form.cleaned_data['period_to'] form_init_data = { 'directions': directions, 'broker_from': broker_from, 'broker_to': broker_to, 'period_from': period_from, 'period_to': period_to } context['form'] = BrokerQueryForm(initial=form_init_data) return render_to_response('broker_tracking.html', context)
def update_broker_invite(request, inviteID, isCancel=''): context = get_context(request) context['isCancel'] = isCancel err = '' if (request.method == 'POST'): invite = Invitation.objects.get(id=inviteID) if isCancel: # if (not invite.testFlag): # emailContext = dict() # emailContext['code'] = invite.code # emailContext['email'] = invite.recipient # msgBody = render_to_string('inviteRevokeEmail.html', emailContext) # send_mail('DoctorCom Invitation', msgBody, '*****@*****.**', # [invite.recipient], fail_silently=False) # invite.delete(canceller=request.user) invite.cancel_invitation() return HttpResponseRedirect( reverse('MHLogin.Administration.views_broker.broker_page')) else: # if (not invite.testFlag): # emailContext = dict() # invite.resend_invite() invite.resend_invite() if hasattr(invite, 'error'): err = invite.error else: return HttpResponseRedirect( reverse('MHLogin.Administration.views_broker.broker_page')) context['invite'] = Invitation.objects.get(id=inviteID) context['err'] = err return render_to_response('broker_invite_confirm.html', context)
def broker_page(request): context = get_context(request) now = datetime.datetime.now() day_latest = int( time.mktime((now - datetime.timedelta(days=30)).timetuple())) str_count_latest = 'SELECT COUNT(*) FROM Messaging_message WHERE Messaging_message.'\ 'sender_id = MHLUsers_broker.user_id and send_timestamp > %d' % day_latest broker_list = Broker.objects.extra(select={ 'count_all': 'SELECT COUNT(*) FROM Messaging_message WHERE '\ 'Messaging_message.sender_id = MHLUsers_broker.user_id', 'count_latest': str_count_latest }) context['broker_list'] = broker_list user = request.session['MHL_Users']['MHLUser'] practice = context['current_practice'] invites = Invitation.objects.filter(sender=request.user, userType=300).all() result = [] for invite in invites: obj = {} invite_time = convert_dt_to_utz(invite.requestTimestamp, user, practice) obj['requestTimestamp'] = time_format(user, invite_time) obj['recipient'] = invite.recipient obj['code'] = invite.code obj['id'] = invite.id result.append(obj) context['invitation_list'] = result return render_to_response('broker_list.html', context)
def practice_manage_holidays(request): if ('Office_Manager' in request.session['MHL_UserIDs']): context = get_context(request) else: raise Exception('Only Office Managers can view Office profile') # we need office staff model - to get office information, # but only office manager can change that info office_staff = request.session['MHL_Users']['OfficeStaff'] if (not office_staff): raise Exception(_('This user is NOT office staff')) #practiceLocationId = office_staff.current_practice.id practiceHolidayList = PracticeHolidays.objects.filter( practice_location=office_staff.current_practice.id) if (request.method == 'POST'): choices = [(holiday.id, holiday.id) for holiday in practiceHolidayList] removeform = RemoveForm(request.POST, choices) if (removeform.is_valid()): ids = removeform.cleaned_data['remove'] PracticeHolidays.objects.filter( id__in=ids, practice_location=office_staff.current_practice.id).delete() context['holidays'] = practiceHolidayList return render_to_response('Profile/practice_manage_holidays.html', context)
def newStaff(request): context = get_context(request) office_staff = request.session['MHL_Users']['OfficeStaff'] current_practice = office_staff.current_practice request.session['SELECTED_ORG_ID'] = current_practice.id showDialog = 0 username = "" if request.method == 'POST': staff_form = CreateOfficeStaffForm(request.POST, \ current_practice=current_practice, include_manager=False) mhluser_form = CreateMHLUserForm(request.POST, request.FILES) if staff_form.is_valid() and mhluser_form.is_valid(): # todo, using function createNewOfficeStaff in /mdcom/MHLogin/MHLUsers/utils_users.py # createNewOfficeStaff(mhluser_form, staff_form, office_staff) username = mhluser_form.cleaned_data['username'] mhluser = mhluser_form.save(commit=False) mhluser.is_active = 0 mhluser.address1 = current_practice.practice_address1 mhluser.address2 = current_practice.practice_address2 mhluser.city = current_practice.practice_city mhluser.state = current_practice.practice_state mhluser.zip = current_practice.practice_zip mhluser.lat = current_practice.practice_lat mhluser.longit = current_practice.practice_longit mhluser.save() staff = staff_form.save(commit=False) staff.user = mhluser staff.current_practice = current_practice staff.save() staff.practices.add(current_practice) staff.save() staff_type = staff_form.cleaned_data['staff_type'] if '3' == staff_type: nurse = Nurse(user=staff) nurse.save() elif '4' == staff_type: dietician = Dietician(user=staff) dietician.save() sendAccountActiveCode(request, 101) showDialog = 1 #return HttpResponseRedirect(reverse('MHLogin.MHLPractices.views.staffHome')) else: context['showDialog'] = showDialog context['user_form'] = mhluser_form context['staff_form'] = staff_form return render_to_response('Staff/newStaff.html', context) context['username'] = username context['showDialog'] = showDialog context['user_form'] = CreateMHLUserForm() context['staff_form'] = CreateOfficeStaffForm( current_practice=current_practice, include_manager=False) return render_to_response('Staff/newStaff.html', context)
def generate_photos(request): if (not settings.DEBUG): return HttpResponseRedirect( reverse('MHLogin.Administration.views.home')) context = get_context(request) # Generate photos for users who don't have photo users = MHLUser.objects.all() for user in users: if not user.photo or not user.photo.name: tf = generate_temp_file("/images/photos/user_test.jpg", user.username) user.photo.save("%s_%d.jpg" % (user.username, user.id), tf, save=True) user.save() log_str = 'Generate photo for %s' % (str(user)) logger.debug(log_str) print log_str # Generate logos for organizations who don't have logo orgs = PracticeLocation.objects.all() for org in orgs: if not org.practice_photo or not org.practice_photo.name: tf = generate_temp_file("/images/photos/organization_test.jpg", org.practice_name) org.practice_photo.save("%s_%d.jpg" % (org.practice_name, org.id), tf, save=True) org.save() log_str = 'Generate photo for %s' % (str(org)) logger.debug(log_str) print log_str return render_to_response('qa_tools/generate_photo_success.html', context)
def reset_user_password(request, user_pk): """ This view resets the given user's password. :param request: The HTTP request :type request: django.core.handlers.wsgi.WSGIRequest :param user_pk: user's ID (primary key) :type user_pk: int :returns: django.http.HttpResponse -- The webpage """ context = get_context(request) user = context['user'] = MHLUser.objects.get(pk=user_pk) if (request.method == 'POST'): form = context['form'] = PasswordChangeForm(request.POST) if (form.is_valid()): PasswordResetLog.objects.create(user=user, reset=True, requestor=request.user, requestor_ip=request.META['REMOTE_ADDR'], reset_ip=request.META['REMOTE_ADDR'], reset_timestamp=datetime.datetime.now()) # TODO: update when rm #2115 goes in generate_new_user_keys(user, form.cleaned_data['password1']) user.set_password(form.cleaned_data['password1']) user.save() return render_to_response('PasswordResetComplete.html', context) else: context['form'] = PasswordChangeForm() return render_to_response('PasswordReset.html', context)
def validationPage(request): if (request.method == 'POST'): # Reserved. Process special case: pager is blank. if not "pager" in request.POST or not request.POST["pager"]: if ('Provider' in request.session['MHL_Users']): Provider.objects.filter(id=request.user.id).update( pager_confirmed=False, pager='') elif ('OfficeStaff' in request.session['MHL_Users']): OfficeStaff.objects.filter(user__id=request.user.id).update( pager_confirmed=False, pager='') elif ('Broker' in request.session['MHL_Users']): Broker.objects.filter(user__id=request.user.id).update( pager_confirmed=False, pager='') if not "mobile_phone" in request.POST or not request.POST[ "mobile_phone"]: MHLUser.objects.filter(id=request.user.id).update( mobile_confirmed=False, mobile_phone='') return HttpResponseRedirect('/') user = getCurrentUserInfo(request) mhluser = request.session['MHL_Users']['MHLUser'] context = get_context(request) if not user or not user.needValidateContactInfo: return HttpResponseRedirect('/') context["form"] = ContactInfoForm(mhluser, user) context["mobile_required"] = 'Provider' in request.session['MHL_Users'] or \ 'Broker' in request.session['MHL_Users'] return render_to_response('Validates/validation.html', context)
def change_current_site(request): context = get_context(request) provider = user_is_provider(request.user) staffer = user_is_office_staff(request.user) if (provider): user = provider if (staffer): user = staffer sites = user.sites.all() if (request.method == "POST"): current = request.POST.get('id') form = CurrentSiteForm(sites, request.POST) context['site_form'] = form if (form.is_valid()): new_site_id = int(context['site_form'].cleaned_data['current']) if (new_site_id == 0): new_site = None else: site_ids = [site.id for site in sites] if (not new_site_id in site_ids): raise Exception(_("User tried to select site id ") + str(new_site_id) + _(", but isn't affiliated with that site.")) new_site = Site.objects.filter(id=new_site_id).all() if (new_site.count() != 1): raise Exception(_("Incorrect number of sites found for id ") + str(new_site_id)) new_site = new_site[0] user.current_site = new_site user.save() return HttpResponse(json.dumps({'status': 'ok'})) else: err_obj = { 'errors': form.errors, } return HttpResponseBadRequest(json.dumps(err_obj), mimetype='application/json')
def _denial_responder(self, logger, request): from time import time import random context = get_context(request) issue_code = ['ACD', str(int(time()) % 10000000)] if (request.user.is_authenticated()): issue_code.insert(1, str(request.user.pk)) msg = '%s/%s: ACCESS DENIED to user %s %s (pk=%s) from %s. request. META is \'%s\'' % \ (request.session.session_key, '-'.join(issue_code), request.user.first_name, request.user.last_name, request.user.pk, request.META['REMOTE_ADDR'], request.META) logger.error(msg) else: issue_code.insert(1, 'NA') msg = '%s/%s: ACCESS DENIED to anonymous user from %s. request.META is \'%s\'' % \ (request.session.session_key, '-'.join(issue_code), request.META['REMOTE_ADDR'], request.META) logger.error(msg) issue_code.append(str(random.randrange(100, 999))) context['issue_code'] = '-'.join(issue_code) subj = _('ACL Denial %(issue_code)s: %(path)s') % \ {'issue_code': '-'.join(issue_code), 'path': request.path} mail_admins(subj, msg, fail_silently=False) response = render_to_response('ACL/access_denied.html', context) response.status_code = 403 return response
def validationPage(request): if (request.method == 'POST'): # Reserved. Process special case: pager is blank. if not "pager" in request.POST or not request.POST["pager"]: if ('Provider' in request.session['MHL_Users']): Provider.objects.filter(id=request.user.id).update(pager_confirmed=False, pager='') elif ('OfficeStaff' in request.session['MHL_Users']): OfficeStaff.objects.filter(user__id=request.user.id).update(pager_confirmed=False, pager='') elif ('Broker' in request.session['MHL_Users']): Broker.objects.filter(user__id=request.user.id).update(pager_confirmed=False, pager='') if not "mobile_phone" in request.POST or not request.POST["mobile_phone"]: MHLUser.objects.filter(id=request.user.id).update(mobile_confirmed=False, mobile_phone='') return HttpResponseRedirect('/') user = getCurrentUserInfo(request) mhluser = request.session['MHL_Users']['MHLUser'] context = get_context(request) if not user or not user.needValidateContactInfo: return HttpResponseRedirect('/') context["form"] = ContactInfoForm(mhluser, user) context["mobile_required"] = 'Provider' in request.session['MHL_Users'] or \ 'Broker' in request.session['MHL_Users'] return render_to_response('Validates/validation.html', context)
def contact(request): context = get_context(request) if (request.POST): mDict = {} mDict['first_name'] = request.user.first_name mDict['last_name'] = request.user.last_name mDict['email'] = request.user.email mDict['message'] = request.POST['message'] mDict['call_back_number'] = request.POST['call_back_number'] mDict['sessionid'] = request.COOKIES['sessionid'] mDict['meta'] = request.META mDict['meta'].pop('HTTP_COOKIE') subject = "Support request from %s" % request.user.username msg = render_to_string('Support/supportemailtemplate.html', mDict) send_mail(subject, msg, request.user.email, settings.SUPPORT_RECIPIENTS, fail_silently=False) return render_to_response('Support/supportemailsentconfirmation.html', context) mhluser = request.session['MHL_Users']['MHLUser'] context["call_back_number"] = mhluser.mobile_phone return render_to_response('Support/contact.html', context)
def changepin(request): context = get_context(request) if (request.method == 'POST'): form = PinChangeForm(request.POST) form.user = request.user if (form.is_valid()): if 'Provider' in request.session['MHL_Users']: provider = Provider.objects.get(user__id=request.user.id) config = provider.vm_config.get() config.change_pin(request, new_pin=form.cleaned_data['pin1']) return render_to_response('Profile/changepinconfirmed.html', context) elif 'Broker' in request.session['MHL_Users']: broker = Broker.objects.get(user__id=request.user.id) config = broker.vm_config.get() config.change_pin(request, new_pin=form.cleaned_data['pin1']) return render_to_response('Profile/changepinconfirmed.html', context) #add by xlin 121119 to fix bug 855 that practice mgr can change pin elif 'OfficeStaff' in request.session['MHL_Users']: os = OfficeStaff.objects.get(user__id=request.user.id) practice = os.current_practice practice.pin = get_new_pin_hash(form.cleaned_data['pin1']) practice.save() return render_to_response('Profile/practicechangepinconfirmed.html', context) context['form'] = form if (not 'form' in context): context['form'] = PinChangeForm() if 'OfficeStaff' in request.session['MHL_Users']: return render_to_response('Profile/practicechangepin.html', context) return render_to_response('Profile/changepin.html', context)
def qa_tools(request): context = get_context(request) if (settings.DEBUG): start = 0 mobile_perm = Permission.objects.get_or_create(\ codename='access_smartphone', name='Can use smartphone app', content_type=ContentType.objects.get_for_model(MHLUser)) MHLUser.objects.update(mobile_phone='') MHLUser.objects.update(phone='') for u in MHLUser.objects.all(): u.mobile_phone = "%d%04d" % (800555, start) u.phone = "%d%04d" % (800333, start) start += 1 if '@' in u.email: u.email = u.email.split('@')[0] + str(start) + '@suzhoukda.com' u.mobile_confirmed = True u.user_permissions.add(mobile_perm[0]) u.save() return render_to_response('qa_tools/qa_tools_complete.html', context) return HttpResponseRedirect(reverse('MHLogin.Administration.views.home'))
def broker_tracking(request): context = get_context(request) broker_user_id = None try: broker_user_id = request.GET['user_id'] context['broker_user_id'] = broker_user_id except: pass broker_from = broker_user_id or - 1 broker_to = '' directions = 1 period_from = '' period_to = '' if (request.method == 'POST'): form = BrokerQueryForm(request.POST) if form.is_valid(): broker_from = int(form.cleaned_data['broker_from']) broker_to = form.cleaned_data['broker_to'] directions = int(form.cleaned_data['directions']) period_from = form.cleaned_data['period_from'] period_to = form.cleaned_data['period_to'] form_init_data = {'directions': directions, 'broker_from': broker_from, 'broker_to': broker_to, 'period_from': period_from, 'period_to': period_to} context['form'] = BrokerQueryForm(initial=form_init_data) return render_to_response('broker_tracking.html', context)
def account_history(request): """ Will create a list of every trasnaction that exist for the billing account of logged in user """ template_name = 'genbilling/account_history.html' context = get_context(request) context['no_account'] = False mhluser = MHLUser.objects.get(pk=request.user.pk) try: ostaff = OfficeStaff.objects.get(user=mhluser) omgr = Office_Manager.objects.get(user=ostaff, practice=ostaff.current_practice) except ObjectDoesNotExist: return err403(request) try: account = Account.objects.get(practice_group_new=\ omgr.practice.get_parent_org()) except ObjectDoesNotExist: context['no_account'] = True return render_to_response(template_name, context, context_instance=RequestContext(request)) transactions = AccountTransaction.objects.filter(account=account) context['account'] = account context['transactions'] = transactions return render_to_response(template_name, context, context_instance=RequestContext(request))
def invoice_list(request): """ Show invoices for desired period """ template_name = 'genbilling/invoice_list.html' context = get_context(request) context['no_invoices'] = True if 'begin_period' in request.POST: #get all invoices for the period transactions = AccountTransaction.objects.filter( period_start=request.POST['begin_period'], tx_type=0) if (len(transactions) > 0): #fill in account name for transaction in transactions: account = Account.objects.get(id=transaction.account_id) practice_group = PracticeLocation.objects.get( id=account.practice_group_new_id) transaction.customer = practice_group.description context['begin_period'] = request.POST['begin_period'] context['transactions'] = transactions context['no_invoices'] = False return render_to_response(template_name, context, context_instance=RequestContext(request))
def account_details(request): """ Show details for specific account """ template_name = 'genbilling/account_details.html' context = get_context(request) if 'practice_group_name' in request.POST: #get account info account = Account.objects.get(id=request.POST['practice_group_name']) practice_group = PracticeLocation.objects.get( id=account.practice_group_new_id) context['customer'] = practice_group.description context['owner'] = account.owner transactions = AccountTransaction.objects.filter( account=account).order_by('-id') subscriptions = Subscription.objects.filter( practice_group_new=practice_group) context['account'] = account context['transactions'] = transactions context['subscriptions'] = subscriptions return render_to_response(template_name, context, context_instance=RequestContext(request))
def DCom_SMS_test(request): log = DoctorComSMSTest() log.tester = MHLUser.objects.get(id=request.user.id) if (not log.tester.mobile_phone): return errlib.err500(request, err_msg="You need to have a mobile phone number " "in your profile to use this function.") log.save() # FIXME: # smsMsg = send_message('This is a DoctorCom SMS Test.', log.tester, log.tester) #c2cLog = None # if (smsMsg.__class__.__name__ == 'HttpResponse'): # # this is an error message from c2c_init # return c2cLog # # log.call = c2cLog log.save() context = get_context(request) context['test_type'] = 1 context['test_id'] = log.id context['form_action'] = reverse('MHLogin.tests.views.confirm_test',) return render_to_response("tests/confirm_test.html", context)
def proceed_save_refer(request): context = get_context(request) if not REFER_CACHE_SESSION_KEY in request.session\ or not request.session[REFER_CACHE_SESSION_KEY]: context['user_recipients'] = request.REQUEST.get( "user_recipients", None) # context['message'] = MESSAGE_REPEAT_COMMIT return render_to_response('DoctorCom/Messaging/refer_success.html', context) refer_data = request.session[REFER_CACHE_SESSION_KEY] file_list = None if "file_list" in refer_data and refer_data["file_list"]: file_list = refer_data["file_list"] recipient_id = refer_data["user_recipients"] recipient_provider = None try: recipient_provider = Provider.objects.get(pk=recipient_id) except: return err403(request, err_msg=_("This recipient is not a Provider.")) return save_refer(request, refer_data, recipient_provider, context, file_list=file_list)
def DCom_Page_test(request): log = DoctorComPagerTest() log.tester = Provider.objects.get(id=request.user.id) if (not log.tester.pager): return errlib.err500(request, err_msg="You need to have a pager number " "in your profile to use this function.") if (not log.tester.mobile_phone): return errlib.err500(request, err_msg="You need to have a mobile phone " "number in your profile to use this function.") log.save() pageLog = page_execute(request, log.tester, log.tester, log.tester.mobile_phone, test_flag=True) #pageLog = None if (pageLog.__class__.__name__ == 'HttpResponse'): # this is an error message return pageLog log.call = pageLog log.save() context = get_context(request) context['test_type'] = 2 context['test_id'] = log.id context['form_action'] = reverse('MHLogin.tests.views.confirm_test',) return render_to_response("tests/confirm_test.html", context)
def update_message(request, message_id): """update_message request: :param request: The HTTP update message request :type request: django.core.handlers.wsgi.WSGIRequest :param message_id: The message uuid :type message_id: uuid :returns: django.http.HttpResponse -- the JSON result in an HttpResonse object :raises: None """ if (request.method == 'GET'): request_data = request.GET form = UpdateMessageForm(request.GET) else: request_data = request.POST form = UpdateMessageForm(request.POST) if (not form.is_valid()): logger.error('%s: Invalid form data!' % (request.session.session_key,)) result = {'error': 'Invalid form data'} response = HttpResponse(json.dumps(result), mimetype='application/json') response.status_code = 400 return response context = get_context(request) user = request.session['MHL_Users']['MHLUser'] local_tz = getCurrentTimeZoneForUser(user, current_practice=context['current_practice']) result = update_message_status(request.user, message_id, request_data, is_treading=True, local_tz=local_tz) return HttpResponse(json.dumps(result)) # , mimetype='application/json')
def reset_user_password(request, user_pk): """ This view resets the given user's password. :param request: The HTTP request :type request: django.core.handlers.wsgi.WSGIRequest :param user_pk: user's ID (primary key) :type user_pk: int :returns: django.http.HttpResponse -- The webpage """ context = get_context(request) user = context['user'] = MHLUser.objects.get(pk=user_pk) if (request.method == 'POST'): form = context['form'] = PasswordChangeForm(request.POST) if (form.is_valid()): PasswordResetLog.objects.create( user=user, reset=True, requestor=request.user, requestor_ip=request.META['REMOTE_ADDR'], reset_ip=request.META['REMOTE_ADDR'], reset_timestamp=datetime.datetime.now()) # TODO: update when rm #2115 goes in generate_new_user_keys(user, form.cleaned_data['password1']) user.set_password(form.cleaned_data['password1']) user.save() return render_to_response('PasswordResetComplete.html', context) else: context['form'] = PasswordChangeForm() return render_to_response('PasswordReset.html', context)
def main_broker(request, user): """Displays the broker's home page.""" context = get_context(request) context['auto_refresh_time'] = settings.MSGLIST_AUTOREFRESH_TIME context['user_type'] = 300 context['unread_msg_count'] = get_message_count(user.user, ('ANS', 'VM'), read_flag=False) community_physicians = get_community_providers_by_coords(user.user.lat, user.user.longit) set_providers_result(community_physicians, request) context['community_physicians'] = community_physicians context['mdcom_fwd'] = user.get_forward_voicemail_display() context['anssvc_fwd'] = user.get_forward_anssvc_display() context['mobile_phone'] = phone_formater(user.user.mobile_phone) context['office_phone'] = phone_formater(user.office_phone) context['other_phone'] = phone_formater(user.user.phone) context['mdcom_phone'] = phone_formater(user.mdcom_phone, display_provisionLink=True) context['zip'] = user.user.zip pend_assoc = Pending_Association.objects.filter(to_user=request.user).count() context['accept_invites_count'] = pend_assoc context['providers'] = community_physicians mhluser = request.session['MHL_Users']['MHLUser'] context['favorites'] = get_my_favorite(mhluser, can_send_refer=False) context['licensure_list'] = [('ALL', _('ALL'))] + list(STATE_CHOICES) return render_to_response('dashboard_broker.html', context)
def doneFollowUp(request, followupID, offset, count): """ This function will toggle the state of the task as being done or not. It is used by an AJAX jQuery load method which updates the table that displays the follow up tasks. """ followup = get_object_or_404(FollowUps, id=followupID) offset = int(offset) count = int(count) if (followup.user != request.user): return err403(request, err_msg="You don't seem to own this follow-up item.") if (followup.deleted): raise Http404 if (followup.user == request.user): if (not followup.done and not followup.completion_date): followup.done = True followup.completion_date = datetime.datetime.today() elif (not followup.done and followup.completion_date): followup.done = True followup.completion_date = datetime.datetime.today() elif (followup.done): followup.done = False followup.completion_date = None followup.save() context = get_context(request) mhluser = request.session['MHL_Users']['MHLUser'] followup = get_followups(request.user, offset, count, mhluser, context['current_practice']) context['followups'] = followup[0] context['followup_count'] = followup[1] return render_to_response('FollowUp/donefollowup.html', context)
def profile_edit_sales(request): """ This function allows for salespersons to edit their profiles. """ context = get_context(request) # First, get the relevant user's profile. Everything requires it. user = MHLUser.objects.get(username=request.user) if (request.method == "POST"): # First, deal with user form stuff salesperson_form = SalesPersonForm(request.POST, request.FILES, instance=user) if (salesperson_form.is_valid()): salesperson_form.save() return HttpResponseRedirect( reverse('MHLogin.MHLUsers.Sales.views.profile')) else: # if not (user_form.is_valid()): context['user_form'] = salesperson_form else: # if (request.method != "POST"): context['user'] = user context['user_form'] = SalesPersonForm(instance=user) return render_to_response('sales_profile_edit.html', context)
def update_broker_invite(request, inviteID, isCancel=''): context = get_context(request) context['isCancel'] = isCancel err = '' if (request.method == 'POST'): invite = Invitation.objects.get(id=inviteID) if isCancel: # if (not invite.testFlag): # emailContext = dict() # emailContext['code'] = invite.code # emailContext['email'] = invite.recipient # msgBody = render_to_string('inviteRevokeEmail.html', emailContext) # send_mail('DoctorCom Invitation', msgBody, '*****@*****.**', # [invite.recipient], fail_silently=False) # invite.delete(canceller=request.user) invite.cancel_invitation() return HttpResponseRedirect(reverse('MHLogin.Administration.views_broker.broker_page')) else: # if (not invite.testFlag): # emailContext = dict() # invite.resend_invite() invite.resend_invite() if hasattr(invite, 'error'): err = invite.error else: return HttpResponseRedirect(reverse('MHLogin.Administration.views_broker.broker_page')) context['invite'] = Invitation.objects.get(id=inviteID) context['err'] = err return render_to_response('broker_invite_confirm.html', context)
def broker_page(request): context = get_context(request) now = datetime.datetime.now() day_latest = int(time.mktime((now - datetime.timedelta(days=30)).timetuple())) str_count_latest = 'SELECT COUNT(*) FROM Messaging_message WHERE Messaging_message.'\ 'sender_id = MHLUsers_broker.user_id and send_timestamp > %d' % day_latest broker_list = Broker.objects.extra(select={ 'count_all': 'SELECT COUNT(*) FROM Messaging_message WHERE '\ 'Messaging_message.sender_id = MHLUsers_broker.user_id', 'count_latest': str_count_latest }) context['broker_list'] = broker_list user = request.session['MHL_Users']['MHLUser'] practice = context['current_practice'] invites = Invitation.objects.filter(sender=request.user, userType=300).all() result = [] for invite in invites: obj = {} invite_time = convert_dt_to_utz(invite.requestTimestamp, user, practice) obj['requestTimestamp'] = time_format(user, invite_time) obj['recipient'] = invite.recipient obj['code'] = invite.code obj['id'] = invite.id result.append(obj) context['invitation_list'] = result return render_to_response('broker_list.html', context)
def practice_edit_access_numbers(request): context = get_context(request) context['isClearData'] = 0 if('Office_Manager' not in request.session['MHL_UserIDs']): raise Exception(_('Only Office Managers can edit practice access numbers')) staff = request.session['MHL_Users']['OfficeStaff'] practice = staff.current_practice context['access_numbers'] = practice.accessnumber_set.all() if(request.method == 'POST'): # p = request.POST if('newnumber' in request.POST): addform = AccessNumberForm(request.POST) if(addform.is_valid()): number = addform.save(commit=False) number.practice = practice context['isClearData'] = 1 number.save() else: addform = AccessNumberForm() if('delnumber' in request.POST): removeform = RemoveForm(request.POST, choices=[(n.id, n.id) for n in context['access_numbers']]) if(removeform.is_valid()): ids = removeform.cleaned_data['remove'] AccessNumber.objects.filter(practice=practice, id__in=ids).delete() else: addform = AccessNumberForm() context['addform'] = addform context['access_numbers'] = practice.accessnumber_set.all() return render_to_response("Profile/practice_edit_access.html", context)
def generate_photos(request): if (not settings.DEBUG): return HttpResponseRedirect(reverse('MHLogin.Administration.views.home')) context = get_context(request) # Generate photos for users who don't have photo users = MHLUser.objects.all() for user in users: if not user.photo or not user.photo.name: tf = generate_temp_file("/images/photos/user_test.jpg", user.username) user.photo.save("%s_%d.jpg" % (user.username, user.id), tf, save=True) user.save() log_str = 'Generate photo for %s' % (str(user)) logger.debug(log_str) print log_str # Generate logos for organizations who don't have logo orgs = PracticeLocation.objects.all() for org in orgs: if not org.practice_photo or not org.practice_photo.name: tf = generate_temp_file("/images/photos/organization_test.jpg", org.practice_name) org.practice_photo.save("%s_%d.jpg" % (org.practice_name, org.id), tf, save=True) org.save() log_str = 'Generate photo for %s' % (str(org)) logger.debug(log_str) print log_str return render_to_response('qa_tools/generate_photo_success.html', context)
def getDoctorNumber(request): context = get_context(request) uid = request.session['userID'] if request.method == 'POST': provider = Provider.objects.get(user__id=uid) form = LocalNumberForm(request.POST) if form.is_valid(): pin = request.POST['pin'] # LocalNumberForm, area_code, pin, mdcom_phone, mdcom_phone_sid mdcom_phone = form.mdcom_phone mdcom_phone_sid = form.mdcom_phone_sid provider.mdcom_phone = mdcom_phone provider.mdcom_phone_sid = mdcom_phone_sid #add doctorcom number if settings.CALL_ENABLE: user_type = ContentType.objects.get_for_model(provider) config = VMBox_Config.objects.get(owner_type=user_type, owner_id=provider.id) #config.change_pin(request, new_pin=pin) config.set_pin(pin) config.save() twilio_ConfigureProviderLocalNumber(provider, provider.mdcom_phone) request.session['userId'] = provider.id request.session['pin'] = pin provider.is_active = 1 provider.save() return HttpResponseRedirect(reverse(getDoctorNumberSucess)) context['form'] = form else: form = LocalNumberForm() context['form'] = form return render_to_response("Staff/get_doctor_number.html", context)
def practice_manage_holidays(request): if ('Office_Manager' in request.session['MHL_UserIDs']): context = get_context(request) else: raise Exception('Only Office Managers can view Office profile') # we need office staff model - to get office information, # but only office manager can change that info office_staff = request.session['MHL_Users']['OfficeStaff'] if (not office_staff): raise Exception(_('This user is NOT office staff')) #practiceLocationId = office_staff.current_practice.id practiceHolidayList = PracticeHolidays.objects.filter( practice_location=office_staff.current_practice.id) if(request.method == 'POST'): choices = [(holiday.id, holiday.id) for holiday in practiceHolidayList] removeform = RemoveForm(request.POST, choices) if (removeform.is_valid()): ids = removeform.cleaned_data['remove'] PracticeHolidays.objects.filter(id__in=ids, practice_location=office_staff.current_practice.id).delete() context['holidays'] = practiceHolidayList return render_to_response('Profile/practice_manage_holidays.html', context)
def newStaff(request): context = get_context(request) office_staff = request.session['MHL_Users']['OfficeStaff'] current_practice = office_staff.current_practice request.session['SELECTED_ORG_ID'] = current_practice.id showDialog = 0 username = "" if request.method == 'POST': staff_form = CreateOfficeStaffForm(request.POST, \ current_practice=current_practice, include_manager=False) mhluser_form = CreateMHLUserForm(request.POST, request.FILES) if staff_form.is_valid() and mhluser_form.is_valid(): # todo, using function createNewOfficeStaff in /mdcom/MHLogin/MHLUsers/utils_users.py # createNewOfficeStaff(mhluser_form, staff_form, office_staff) username = mhluser_form.cleaned_data['username'] mhluser = mhluser_form.save(commit=False) mhluser.is_active = 0 mhluser.address1 = current_practice.practice_address1 mhluser.address2 = current_practice.practice_address2 mhluser.city = current_practice.practice_city mhluser.state = current_practice.practice_state mhluser.zip = current_practice.practice_zip mhluser.lat = current_practice.practice_lat mhluser.longit = current_practice.practice_longit mhluser.save() staff = staff_form.save(commit=False) staff.user = mhluser staff.current_practice = current_practice staff.save() staff.practices.add(current_practice) staff.save() staff_type = staff_form.cleaned_data['staff_type'] if '3' == staff_type: nurse = Nurse(user=staff) nurse.save() elif '4' == staff_type: dietician = Dietician(user=staff) dietician.save() sendAccountActiveCode(request, 101) showDialog = 1 #return HttpResponseRedirect(reverse('MHLogin.MHLPractices.views.staffHome')) else: context['showDialog'] = showDialog context['user_form'] = mhluser_form context['staff_form'] = staff_form return render_to_response('Staff/newStaff.html', context) context['username'] = username context['showDialog'] = showDialog context['user_form'] = CreateMHLUserForm() context['staff_form'] = CreateOfficeStaffForm(current_practice=current_practice, include_manager=False) return render_to_response('Staff/newStaff.html', context)
def export_schedule_to_pdf(request, callgroup): from weasyprint import HTML context = get_context(request) context['site'] = callgroup.description month, year = int(request.GET.get('month', 1)), int(request.GET.get('year', 9999)) weekstart = int(request.GET.get('weekstart', 0)) monthstart = datetime.date(year, month, day=1) context['month'] = monthstart.strftime("%B %Y") monthstart = monthstart - datetime.timedelta(days=monthstart.day - 1) # make sure we start on a sunday (or monday if weekstart=1) monthstart = monthstart - datetime.timedelta(days=(monthstart.isoweekday() % 7)) + \ datetime.timedelta(weekstart) user = request.session['MHL_Users']['MHLUser'] context['weeks'] = generateOnCallList(callgroup, monthstart, weekstart, user) context['days'] = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] for _ in range(weekstart): context['days'].append(context['days'].pop(0)) # load template with context and static root for pdf renderer, generate pdf buffer static_root = settings.STATICFILES_DIRS[0] html = render_to_string('pdf_schedule.html', {'STATIC_ROOT': static_root}, context) weasyhtml = HTML(string=html) schedcss = join(static_root, 'css', 'pdf_schedule.css') pdf = weasyhtml.write_pdf(stylesheets=[schedcss]) # ,target='/tmp/test.pdf') # prepare response, append &nopdf to GET url for test response = HttpResponse(pdf, mimetype="application/pdf") response["Cache-Control"] = "no-cache" response["Accept-Ranges"] = "none" response["Content-Disposition"] = "attachment; filename=schedule-%d-%d.pdf" % (year, month) return response if 'nopdf' not in request.GET else \ render_to_response("pdf_schedule.html", context)
def cancelInvite(request, inviteID): context = get_context(request) if (request.method == 'POST'): invite = Invitation.objects.filter(id=inviteID) if invite: invite[0].cancel_invitation() # if (not invite.testFlag): # from django.template.loader import render_to_string # emailContext = dict() # emailContext['code'] = invite.code # emailContext['email'] = invite.recipient # msgBody = render_to_string('inviteRevokeEmail.html', emailContext) # send_mail(_('DoctorCom Invitation'), msgBody, '*****@*****.**', # [invite.recipient], fail_silently=False) # # invite.delete(canceller=request.user) return HttpResponseRedirect( reverse('MHLogin.Administration.views.inviteHome')) context['invite'] = Invitation.objects.get(id=inviteID) return render_to_response('inviteCancellationConfirm.html', context)
def addFollowUpAjax(request): context = get_context(request) count = int(request.POST['count']) if (request.method == "POST"): form = AddFollowUpForm(request.POST) task = request.POST['task'] if len(task.strip()) == 0: return err403(request, err_msg=_("The task is invalid.")) if (form.is_valid()): #raise Exception('foo') f_obj = form.save(commit=False) f_obj.user = request.user user = request.session['MHL_Users']['MHLUser'] practice = context['current_practice'] f_obj.due_date =convert_dt_to_stz(f_obj.due_date, user, practice) f_obj.save() else: field_errors = dict() for name in form._errors: field_errors[name] = [unicode(err) for err in form._errors[name]] non_field_errors = [unicode(err) for err in form.non_field_errors()] return_obj = dict() return_obj['error_type'] = 'form_validation' return_obj['non_field_errors'] = non_field_errors return_obj['field_errors'] = field_errors return HttpResponse(json.dumps(return_obj), mimetype="application/json", status=400) mhluser = request.session['MHL_Users']['MHLUser'] followup = get_followups(request.user, 0, count, mhluser, context['current_practice']) context['followups'] = followup[0] context['followup_count'] = followup[1] return render_to_response('FollowUp/donefollowup.html', context)
def getAssignPractice(request): context = get_context(request) if request.method == 'POST': form = GetAssignPracticeForm(request.POST) else: form = GetAssignPracticeForm(request.GET) context['form'] = form return render_to_response('get_assign_practice.html', context)
def getDoctorNumberSucess(request): context = get_context(request) userid = request.session.get('userId') context['pin'] = request.session.get('pin') code = Provider.objects.filter(id=userid)[0].mdcom_phone code = '(' + code[:3] + ') ' + code[3:6] + '-' + code[6:] context['area_code'] = code return render_to_response("Staff/sucessActive2.html", context)
def terms(request, show_accept=False): context = get_context(request) context['show_accept'] = show_accept if (show_accept): context['accept_form'] = ToSAcceptForm() context['reject_form'] = ToSRejectForm() return render_to_response('terms.html', context)