Exemplo n.º 1
0
def disease_aggregates(request):
    """
    Disease Aggregates Report
    """
    if not request.datespan.is_valid():
        messages.error(request, request.datespan.get_validation_reason())
        return render_to_response(request, "reports/pi_report.html",
                              {"show_dates": True, "report": None})
                               
                                   
    clinic_id = request.GET.get("clinic", None)
    slug = "disease_aggregate"
    results = _pi_results(slug, request.datespan.startdate, request.datespan.enddate,
                          clinic_id)
    
    main_clinic = Location.objects.get(slug=clinic_id) if clinic_id else None
    report = AggregateReport.from_view_results(slug, results)
    
    return render_to_response(request, "reports/pi_report.html",
                              {"show_dates": False, 
                               "hide_districts": True, 
                               "main_clinic": main_clinic,
                               "clinics": clinics_for_view(),
                               "districts": districts_for_view(),
                               "view_slug": slug,
                               "report": report})
Exemplo n.º 2
0
def resend_confirmation(request):
    dom_req = None
    try:
        dom_req = RegistrationRequest.get_request_for_username(request.user.username)
    except Exception:
        pass


    if not dom_req:
        inactive_domains_for_user = Domain.active_for_user(request.user, is_active=False)
        if len(inactive_domains_for_user) > 0:
            for domain in inactive_domains_for_user:
                domain.is_active = True
                domain.save()
        return redirect('domain_select')

    if request.method == 'POST': # If the form has been submitted...
        try:
            send_domain_registration_email(dom_req.new_user_username, dom_req.domain, dom_req.activation_guid)
        except Exception:
            vals = {'error_msg':'There was a problem with your request',
                    'error_details':sys.exc_info(),
                    'show_homepage_link': 1 }
            return render_to_response(request, 'error.html', vals)
        else:
            vals = dict(alert_message="An email has been sent to %s." % dom_req.new_user_username, requested_domain=dom_req.domain)
            return render_to_response(request, 'registration/confirmation_sent.html', vals)

    vals = dict(requested_domain=dom_req.domain)
    return render_to_response(request, 'registration/confirmation_resend.html', vals)
Exemplo n.º 3
0
def register_domain(request):
    is_new = False
    referer_url = request.GET.get('referer', '')

    active_domains_for_user = Domain.active_for_user(request.user)
    if len(active_domains_for_user) <= 0 and not request.user.is_superuser:
        is_new = True
        domains_for_user = Domain.active_for_user(request.user, is_active=False)
        if len(domains_for_user) > 0:
            vals = dict(requested_domain=domains_for_user[0])
            return render_to_response(request, 'registration/confirmation_waiting.html', vals)

    if request.method == 'POST': # If the form has been submitted...
        nextpage = request.POST.get('next')
        org = request.POST.get('org')
        form = DomainRegistrationForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            reqs_today = RegistrationRequest.get_requests_today()
            max_req = settings.DOMAIN_MAX_REGISTRATION_REQUESTS_PER_DAY
            if reqs_today >= max_req:
                vals = {'error_msg':'Number of domains requested today exceeds limit ('+str(max_req)+') - contact Dimagi',
                        'show_homepage_link': 1 }
                return render_to_response(request, 'error.html', vals)

            request_new_domain(request, form, org, is_new)
            requested_domain = form.cleaned_data['domain_name']
            if is_new:
                vals = dict(alert_message="An email has been sent to %s." % request.user.username, requested_domain=requested_domain)
                return render_to_response(request, 'registration/confirmation_sent.html', vals)
            else:
                messages.success(request, '<strong>The project {project_name} was successfully created!</strong> An email has been sent to {username} for your records.'.format(
                    username=request.user.username,
                    project_name=requested_domain
                ), extra_tags="html")

                if nextpage:
                    return HttpResponseRedirect(nextpage)
                if referer_url:
                    return redirect(referer_url)
                return HttpResponseRedirect(reverse("domain_homepage", args=[requested_domain]))
        else:
            if nextpage:
#                messages.error(request, "The new project could not be created! Please make sure to fill out all fields of the form.")
                return orgs_landing(request, org, form=form)
    else:
        form = DomainRegistrationForm() # An unbound form

    vals = dict(form=form, is_new=is_new)

    return render_to_response(request, 'registration/domain_request.html', vals)
Exemplo n.º 4
0
def accept_invitation(request, domain, invitation_id):
    if request.GET.get('switch') == 'true':
        logout(request)
        return redirect_to_login(request.path)
    if request.GET.get('create') == 'true':
        logout(request)
        return HttpResponseRedirect(request.path)
    invitation = Invitation.get(invitation_id)
    assert(invitation.domain == domain)
    if invitation.is_accepted:
        messages.error(request, "Sorry that invitation has already been used up. "
                       "If you feel this is a mistake please ask the inviter for "
                       "another invitation.")
        return HttpResponseRedirect(reverse("login"))
    if request.user.is_authenticated():
        # if you are already authenticated, just add the domain to your
        # list of domains
        if request.couch_user.username != invitation.email:
            messages.error(request, "The invited user %s and your user %s do not match!" % (invitation.email, request.couch_user.username))

        if request.method == "POST":
            couch_user = CouchUser.from_django_user(request.user)
            couch_user.add_domain_membership(domain=domain)
            couch_user.set_role(domain, invitation.role)
            couch_user.save()
            invitation.is_accepted = True
            invitation.save()
            messages.success(request, "You have been added to the %s domain" % domain)
            return HttpResponseRedirect(reverse("domain_homepage", args=[domain,]))
        else:
            return render_to_response(request, 'users/accept_invite.html', {'domain': domain,
                                                                            "invited_user": invitation.email if request.couch_user.username != invitation.email else ""})
    else:
        # if you're not authenticated we need you to fill out your information
        if request.method == "POST":
            form = NewWebUserRegistrationForm(request.POST)
            if form.is_valid():
                user = activate_new_user(form, is_domain_admin=False, domain=invitation.domain)
                user.set_role(domain, invitation.role)
                user.save()
                invitation.is_accepted = True
                invitation.save()
                messages.success(request, "User account for %s created! You may now login." % form.cleaned_data["email"])
                return HttpResponseRedirect(reverse("login"))
        else:
            form = NewWebUserRegistrationForm(initial={'email': invitation.email})

        return render_to_response(request, "users/accept_invite.html", {"form": form})
Exemplo n.º 5
0
def add_sample(request, domain, sample_id=None):
    sample = None
    if sample_id is not None:
        sample = SurveySample.get(sample_id)
    
    if request.method == "POST":
        form = SurveySampleForm(request.POST)
        if form.is_valid():
            name            = form.cleaned_data.get("name")
            sample_contacts = form.cleaned_data.get("sample_contacts")
            
            if sample is None:
                sample = SurveySample (
                    domain = domain,
                    name = name,
                    contacts = sample_contacts
                )
            else:
                sample.name = name
                sample.contacts = sample_contacts
            sample.save()
            return HttpResponseRedirect(reverse("sample_list", args=[domain]))
    else:
        initial = {}
        if sample is not None:
            initial["name"] = sample.name
            initial["sample_contacts"] = sample.contacts
        form = SurveySampleForm(initial=initial)
    
    context = {
        "domain" : domain,
        "form" : form,
        "sample_id" : sample_id
    }
    return render_to_response(request, "reminders/partial/add_sample.html", context)
Exemplo n.º 6
0
def add_survey(request, domain, survey_id=None):
    survey = None
    if survey_id is not None:
        survey = Survey.get(survey_id)
    
    if request.method == "POST":
        form = SurveyForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data.get("name")
            waves = form.cleaned_data.get("waves")
            followups = form.cleaned_data.get("followups")
            samples = form.cleaned_data.get("samples")
            send_automatically = form.cleaned_data.get("send_automatically")
            send_followup = form.cleaned_data.get("send_followup")
            
            if survey is None:
                survey = Survey (
                    domain = domain,
                    name = name,
                    waves = waves,
                    followups = followups,
                    samples = samples,
                    send_automatically = send_automatically,
                    send_followup = send_followup
                )
            else:
                survey.name = name
                survey.waves = waves
                survey.followups = followups
                survey.samples = samples
                survey.send_automatically = send_automatically
                survey.send_followup = send_followup
            survey.save()
            return HttpResponseRedirect(reverse("survey_list", args=[domain]))
    else:
        initial = {}
        if survey is not None:
            initial["name"] = survey.name
            initial["waves"] = survey.waves
            initial["followups"] = survey.followups
            initial["samples"] = survey.samples
            initial["send_automatically"] = survey.send_automatically
            initial["send_followup"] = survey.send_followup
        form = SurveyForm(initial=initial)
    
    form_list = get_form_list(domain)
    form_list.insert(0, {"code":"--choose--", "name":"-- Choose --"})
    sample_list = get_sample_list(domain)
    sample_list.insert(0, {"code":"--choose--", "name":"-- Choose --"})
    
    context = {
        "domain" : domain,
        "survey_id" : survey_id,
        "form" : form,
        "form_list" : form_list,
        "sample_list" : sample_list,
        "method_list" : SURVEY_METHOD_LIST,
        "user_list" : CommCareUser.by_domain(domain),
    }
    return render_to_response(request, "reminders/partial/add_survey.html", context)
Exemplo n.º 7
0
def manage_multimedia(request, domain):
    media = request.project.all_media()
    if request.method == "POST":
        for m_file in media:
            if '%s_tags' % m_file._id in request.POST:
                m_file.tags[domain] = request.POST.get('%s_tags' % m_file._id, '').split(' ')

            if domain not in m_file.shared_by and request.POST.get('%s_shared' % m_file._id, False):
                m_file.shared_by.append(domain)
            elif domain in m_file.shared_by and not request.POST.get('%s_shared' % m_file._id, False):
                m_file.shared_by.remove(domain)

            if '%s_license' % m_file._id in request.POST:
                m_file.licenses[domain] = request.POST.get('%s_license' % m_file._id, 'public')
            m_file.save()
        messages.success(request, "Multimedia updated successfully!")

    return render_to_response(request, 'domain/admin/media_manager.html', {'domain': domain,
        'media': [{
            'license': m.licenses.get(domain, 'public'),
            'shared': domain in m.shared_by,
            'url': m.url(),
            'm_id': m._id,
            'tags': m.tags.get(domain, []),
            'type': m.doc_type
                   } for m in media],
        'licenses': LICENSES.items()
                                                                     })
Exemplo n.º 8
0
def case_details(request, domain, case_id):
    timezone = util.get_timezone(request.couch_user.user_id, domain)

    try:
        case = CommCareCase.get(case_id)
        report_name = 'Details for Case "%s"' % case.name
    except ResourceNotFound:
        messages.info(request, "Sorry, we couldn't find that case. If you think this is a mistake plase report an issue.")
        return HttpResponseRedirect(inspect.SubmitHistory.get_url(domain))


    form_lookups = dict((form.get_id,
                         "%s: %s" % (form.received_on.date(), 
                                     xmlns_to_name(domain, form.xmlns, get_app_id(form)))) \
                        for form in case.get_forms())
    return render_to_response(request, "reports/reportdata/case_details.html", {
        "domain": domain,
        "case_id": case_id,
        "form_lookups": form_lookups,
        "slug":inspect.CaseListReport.slug,
        "report": dict(
            name=report_name,
            slug=inspect.CaseListReport.slug,
            is_async=False,
        ),
        "layout_flush_content": True,
        "timezone": timezone
    })
Exemplo n.º 9
0
def list_chws(request):
    """
    List chws
    """
    chws = CommunityHealthWorker.view("chw/by_clinic", include_docs=True)
    return render_to_response(request, "chw/chw_list.html",
                              {"chws": chws})
Exemplo n.º 10
0
def invite_web_user(request, domain, template="users/invite_web_user.html"):
    role_choices = UserRole.role_choices(domain)
    if request.method == "POST":
        form = AdminInvitesUserForm(request.POST,
            excluded_emails=[user.username for user in WebUser.by_domain(domain)],
            role_choices=role_choices
        )
        if form.is_valid():
            data = form.cleaned_data
            # create invitation record
            data["invited_by"] = request.couch_user.user_id
            data["invited_on"] = datetime.utcnow()
            data["domain"] = domain
            invite = Invitation(**data)
            invite.save()
            invite.send_activation_email()
            messages.success(request, "Invitation sent to %s" % invite.email)
            return HttpResponseRedirect(reverse("web_users", args=[domain]))
    else:
        form = AdminInvitesUserForm(role_choices=role_choices)
    context = _users_context(request, domain)
    context.update(
        registration_form=form
    )
    return render_to_response(request, template, context)
Exemplo n.º 11
0
def power_down(req):
    if settings.BHOMA_CAN_POWER_DOWN_SERVER:
        shutdown(settings.SHUTDOWN_DELAY)
        return render_to_response(req, "touchscreen/shutdown.html", {
                'buffer': settings.SHUTDOWN_BUFFER, 'timeout': settings.SHUTDOWN_TIMEOUT})
    else:
        raise Exception('server does not support remote shutdown')
Exemplo n.º 12
0
def case_list(request, domain):
    
    apps = filter(lambda app: app.doc_type == "Application",
                  ApplicationBase.view('app_manager/applications_brief', 
                                       startkey=[domain], endkey=[domain, {}]))
    
    user_id = request.REQUEST.get("user_id", request.couch_user.get_id)
    app_id = request.REQUEST.get("app_id", "")
    module_id = int(request.REQUEST.get("module_id", "0"))
    language = request.REQUEST.get("language", "en")
    
    if not app_id and apps:
        app_id = apps[0].get_id
    
    if app_id:
        app = Application.get(app_id)
        case_short = app.modules[module_id].get_detail("case_short")
        case_long = app.modules[module_id].get_detail("case_long")
    else:
        case_short=""
        case_long=""
    
    return render_to_response(request, "cloudcare/list_cases.html", 
                              {"domain": domain,
                               "language": language,
                               "user_id": user_id,
                               "apps": apps,
                               "case_short": json.dumps(case_short._doc),
                               "case_long": json.dumps(case_long._doc),
                               "cases": json.dumps(get_owned_cases(domain, user_id),
                                                   default=json_handler)})
Exemplo n.º 13
0
def app_list(request, domain, urlPath):
    preview = string_to_boolean(request.REQUEST.get("preview", "false"))
    language = request.couch_user.language or "en"
    
    def _app_latest_build_json(app_id):
        build = ApplicationBase.view('app_manager/saved_app',
                                     startkey=[domain, app["_id"], {}],
                                     endkey=[domain, app["_id"]],
                                     descending=True,
                                     limit=1).one()
        return build._doc if build else None
                                     
    if not preview:
        apps = get_cloudcare_apps(domain)
        # replace the apps with the last build of each app
        apps = [_app_latest_build_json(app["_id"])for app in apps]
    
    else:
        apps = ApplicationBase.view('app_manager/applications_brief', startkey=[domain], endkey=[domain, {}])
        apps = [app._doc for app in apps if app and app.application_version == "2.0"]
    
    # trim out empty apps
    apps = filter(lambda app: app, apps)
    return render_to_response(request, "cloudcare/cloudcare_home.html", 
                              {"domain": domain,
                               "language": language,
                               "apps": json.dumps(apps),
                               "apps_raw": apps,
                               "preview": preview,
                               "maps_api_key": settings.GMAPS_API_KEY })
Exemplo n.º 14
0
def single_patient(request, patient_id):
    patient = loader.get_patient(patient_id)
    xforms = CXFormInstance.view("patient/xforms", key=patient.get_id, include_docs=True)
    encounter_types = get_encounters(patient)
    options = TouchscreenOptions.default()
    # TODO: are we upset about how this breaks MVC?
    options.nextbutton.show  = False
    options.backbutton = ButtonOptions(text="BACK", 
                                       link=reverse("patient_select"))
    
    encounters = sorted(patient.encounters, key=lambda encounter: encounter.visit_date, reverse=True)
    # TODO: figure out a way to do this more centrally
    # Inject cases into encounters so we can show them linked in the view
    for encounter in patient.encounters:
        if encounter.get_xform():
            encounter.dynamic_data["classification"] = get_classification(encounter.get_xform().namespace)
            encounter.dynamic_data["cases"] = []
            for case in patient.cases:
                if case.encounter_id == encounter.get_id:
                    encounter.dynamic_data["cases"].append(case)
        
    
    return render_to_response(request, "patient/single_patient_touchscreen.html", 
                              {"patient": patient,
                               "encounters": encounters,
                               "xforms": xforms,
                               "encounter_types": encounter_types,
                               "options": options })
Exemplo n.º 15
0
def export_data(request):
    # HACK this is hardcoded to something in the DB
    export_group = GroupExportConfiguration.get("export_all_forms") 
    return render_to_response(request, "patient/export_data.html",
                              {"clinic_encounters": CLINIC_ENCOUNTERS,
                               "chw_encounters": CHW_ENCOUNTERS,
                               "group": export_group})
Exemplo n.º 16
0
def orgs_team_members(request, org, team_id, template="orgs/orgs_team_members.html"):
    #organization and teams
    organization = Organization.get_by_name(org)
    teams = Team.get_by_org(org)
    current_domains = Domain.get_by_organization(org)

    #check that the team exists
    team = Team.get(team_id)
    if team is None:
        raise Http404("Group %s does not exist" % team_id)

    #inspect the members of the team
    member_ids = team.get_member_ids()
    members = WebUser.view("_all_docs", keys=member_ids, include_docs=True).all()
    members.sort(key=lambda user: user.username)

    #inspect the domains of the team
    domain_names = team.get_domains()
    domains = list()
    for name in domain_names:
        domains.append([Domain.get_by_name(name), team.role_label(domain=name)])

    all_org_domains = Domain.get_by_organization(org)
    non_domains = [domain for domain in all_org_domains if domain.name not in domain_names]

    all_org_member_ids = organization.members
    all_org_members = WebUser.view("_all_docs", keys=all_org_member_ids, include_docs=True).all()
    non_members = [member for member in all_org_members if member.user_id not in member_ids]

    vals = dict(org=organization, team=team, teams=teams, members=members, nonmembers=non_members, domains=current_domains, team_domains=domains, team_nondomains=non_domains)
    return render_to_response(request, template, vals)
Exemplo n.º 17
0
def upload(request, domain, app_id):
    app = get_app(domain, app_id)
    DNS_name = "http://"+Site.objects.get(id = settings.SITE_ID).domain
    return render_to_response(request, "hqmedia/bulk_upload.html",
            {"domain": domain,
             "app": app,
             "DNS_name": DNS_name})
Exemplo n.º 18
0
def scheduled_reminders(request, domain, template="reminders/partial/scheduled_reminders.html"):
    reminders = CaseReminderHandler.get_all_reminders(domain)
    dates = []
    now = datetime.utcnow()
    today = now.date()
    if reminders:
        start_date = reminders[0].next_fire.date()
        if today < start_date:
            start_date = today
        end_date = reminders[-1].next_fire.date()
    else:
        start_date = end_date = today
    # make sure start date is a Monday and enddate is a Sunday
    start_date -= timedelta(days=start_date.weekday())
    end_date += timedelta(days=6-end_date.weekday())
    while start_date <= end_date:
        dates.append(start_date)
        start_date += timedelta(days=1)

    return render_to_response(request, template, {
        'domain': domain,
        'reminders': reminders,
        'dates': dates,
        'today': today,
        'now': now,
    })
Exemplo n.º 19
0
def touchscreen_login(request):
    '''Login to bhoma via touchscreen'''
    if request.method == "POST":
        data = json.loads(request.POST.get('result'))
        if not data:
            return HttpResponseRedirect('/')  #TODO: where should this go? some sort of 'welcome' screen?

        username = data.get("username")
        password = data.get("password")
        user = authenticate(username=username, password=password)
        if user is None:
            # HACK try lowercase
            user = authenticate(username=username, password=password.lower())
        if user is not None:
            if user.is_active:
                login(request, user)
                return HttpResponseRedirect(reverse("landing_page"))
            else:
                return HttpResponseNotAllowed("Sorry %s's account has been disabled" % username)
        else:
            return HttpResponseForbidden("Sorry that wasn't the right username or password")

    return render_to_response(request, "bhoma_touchscreen.html", 
                              {'form': {'name':  'login', 
                                        'wfobj': 'wfLogin'}, 
                               'mode':  'workflow',
                               'dynamic_scripts': ["%swebapp/javascripts/login.js" % \
                                                   settings.STATIC_URL,] })
Exemplo n.º 20
0
def commcare_version_report(request, template="hqadmin/commcare_version.html"):
    apps = get_db().view("app_manager/applications_brief").all()
    menu = CommCareBuildConfig.fetch().menu
    builds = [item.build.to_string() for item in menu]
    by_build = dict([(item.build.to_string(), {"label": item.label, "apps": []}) for item in menu])

    for app in apps:
        app = app["value"]
        app["id"] = app["_id"]
        if app.get("build_spec"):
            build_spec = BuildSpec.wrap(app["build_spec"])
            build = build_spec.to_string()
            if by_build.has_key(build):
                by_build[build]["apps"].append(app)
            else:
                by_build[build] = {"label": build_spec.get_label(), "apps": [app]}
                builds.append(build)

    tables = []
    for build in builds:
        by_build[build]["build"] = build
        tables.append(by_build[build])
    context = get_hqadmin_base_context(request)
    context.update({"tables": tables})
    context["hide_filters"] = True
    return render_to_response(request, template, context)
Exemplo n.º 21
0
def message_log_report(request):
    show_dates = True

    datespan = request.datespan
    domains = Domain.get_all()
    for dom in domains:
        dom.sms_incoming = SMSLog.count_incoming_by_domain(dom.name, datespan.startdate_param, datespan.enddate_param)
        dom.sms_outgoing = SMSLog.count_outgoing_by_domain(dom.name, datespan.startdate_param, datespan.enddate_param)
        dom.sms_total = SMSLog.count_by_domain(dom.name, datespan.startdate_param, datespan.enddate_param)

    context = get_hqadmin_base_context(request)

    headers = DataTablesHeader(
        DataTablesColumn("Domain"),
        DataTablesColumn("Incoming Messages", sort_type=DTSortType.NUMERIC),
        DataTablesColumn("Outgoing Messages", sort_type=DTSortType.NUMERIC),
        DataTablesColumn("Total Messages", sort_type=DTSortType.NUMERIC),
    )
    context["headers"] = headers
    context["aoColumns"] = headers.render_aoColumns

    context.update({"domains": domains, "show_dates": show_dates, "datespan": datespan})

    context["layout_flush_content"] = True
    return render_to_response(request, "hqadmin/message_log_report.html", context)
Exemplo n.º 22
0
def domain_list(request):
    # one wonders if this will eventually have to paginate
    domains = Domain.get_all()
    all_stats = _all_domain_stats()
    for dom in domains:
        dom.web_users = int(all_stats["web_users"][dom.name])
        dom.commcare_users = int(all_stats["commcare_users"][dom.name])
        dom.cases = int(all_stats["cases"][dom.name])
        dom.forms = int(all_stats["forms"][dom.name])
        dom.admins = [
            row["doc"]["email"]
            for row in get_db().view("users/admins_by_domain", key=dom.name, reduce=False, include_docs=True).all()
        ]

    context = get_hqadmin_base_context(request)
    context.update({"domains": domains})
    context["layout_flush_content"] = True

    headers = DataTablesHeader(
        DataTablesColumn("Domain"),
        DataTablesColumn("# Web Users", sort_type=DTSortType.NUMERIC),
        DataTablesColumn("# Mobile Workers", sort_type=DTSortType.NUMERIC),
        DataTablesColumn("# Cases", sort_type=DTSortType.NUMERIC),
        DataTablesColumn("# Submitted Forms", sort_type=DTSortType.NUMERIC),
        DataTablesColumn("Domain Admins"),
    )
    context["headers"] = headers
    context["aoColumns"] = headers.render_aoColumns
    return render_to_response(request, "hqadmin/domain_list.html", context)
Exemplo n.º 23
0
def commcare_users(request, domain, template="users/commcare_users.html"):
    show_inactive = json.loads(request.GET.get('show_inactive', 'false'))
    sort_by = request.GET.get('sortBy', 'abc')
    cannot_share = json.loads(request.GET.get('cannot_share', 'false'))
    show_more_columns = request.GET.get('show_more_columns') is not None
    context = _users_context(request, domain)
    if cannot_share:
        users = CommCareUser.cannot_share(domain)
    else:
        users = CommCareUser.by_domain(domain)
        if show_inactive:
            users.extend(CommCareUser.by_domain(domain, is_active=False))

    if sort_by == 'forms':
        users.sort(key=lambda user: -user.form_count)

    context.update({
        'commcare_users': users,
        'groups': Group.get_case_sharing_groups(domain),
        'show_case_sharing': request.project.case_sharing_included(),
        'show_inactive': show_inactive,
        'cannot_share': cannot_share,
        'show_more_columns': show_more_columns or cannot_share,
    })
    return render_to_response(request, template, context)
Exemplo n.º 24
0
def register_org(request, template="registration/org_request.html"):
    referer_url = request.GET.get('referer', '')
    if request.method == "POST":
        form = OrganizationRegistrationForm(request.POST, request.FILES)
        if form.is_valid():
            name = form.cleaned_data["org_name"]
            title = form.cleaned_data["org_title"]
            email = form.cleaned_data["email"]
            url = form.cleaned_data["url"]
            location = form.cleaned_data["location"]
            logo = form.cleaned_data["logo"]
            if logo:
                logo_filename = logo.name
            else:
                logo_filename = ''

            org = Organization(name=name, title=title, location=location, email=email, url=url, logo_filename=logo_filename)
            org.save()
            if logo:
                org.put_attachment(content=logo.read(), name=logo.name)

            if referer_url:
                return redirect(referer_url)
            return HttpResponseRedirect(reverse("orgs_landing", args=[name]))
    else:
        form = OrganizationRegistrationForm() # An unbound form

    vals = dict(form=form)
    return render_to_response(request, template, vals)
Exemplo n.º 25
0
def single(request, chw_id):
    """
    Single CHW
    """
    chw = CommunityHealthWorker.get(chw_id)
    return render_to_response(request, "chw/single_chw.html", 
                              {"chw": chw }) 
Exemplo n.º 26
0
def add_scheduled_report(request, user_id):
    recipient = User.objects.get(pk=user_id)
    if request.method == "POST":
        report_id = request.POST["report_id"]
        hour = request.POST["hour"]
        day = request.POST["day"]
        if day=="all":
            report = DailyReportSubscription()
        elif day=="first":
            report = MonthlyReportSubscription()
            report.day_of_month = 1
        else:
            report = WeeklyReportSubscription()
            report.day_of_week = int(day)
        report.hours = int(hour)
        report.report = SchedulableReport.objects.get(pk=report_id)
        # not generic
        location_code = request.POST["location_code"]
        report.view_args = {'location_code':location_code}

        report.save()
        report.users.add(recipient)
        report.save()
        messages.success(request, "New scheduled report added!")
        return HttpResponseRedirect(reverse("email_reports"))
    context = {}
    context.update({"hours": [(val, "%s:00" % val) for val in range(24)],
                    "days":  [(val, calendar.day_name[val]) for val in range(7)],
                    "reports": SchedulableReport.objects.all()})
    # here we get less generic : b
    context['locations'] = Location.objects.all()
    context['recipient'] = recipient
    return render_to_response(request, "reports/add_scheduled_report.html", context)
Exemplo n.º 27
0
def appstore(request, template="appstore/appstore_base.html", sort_by=None):
    page = int(request.GET.get('page', 1))
    include_unapproved = (request.user.is_superuser and request.GET.get('unapproved', False))
    if not sort_by:
        results = Domain.published_snapshots(include_unapproved=include_unapproved, page=page, per_page=PER_PAGE)
        more_pages = page * PER_PAGE < results.total_rows and len(results) == PER_PAGE # hacky way to deal with approved vs unapproved
    else:
        total_results = Domain.published_snapshots(include_unapproved=include_unapproved)
        if sort_by == 'best':
            results = Domain.popular_sort(total_results, page)
            #more_pages = page * PER_PAGE < total_results and page <= 10
        elif sort_by == 'hits':
            results = Domain.hit_sort(total_results, page)
            #more_pages = page * PER_PAGE < len(total_results) and page <= 10
        more_pages = page * PER_PAGE < total_results.total_rows and len(results) == PER_PAGE # hacky way to deal with approved vs unapproved
    average_ratings = list()
    for result in results:
        average_ratings.append([result.name, Review.get_average_rating_by_app(result.original_doc)])

    return render_to_response(request, template, _appstore_context({
        'apps': results,
        'average_ratings': average_ratings,
        'page': page,
        'prev_page': (page-1),
        'next_page': (page+1),
        'more_pages': more_pages,
        'sort_by': sort_by,
        'include_unapproved': include_unapproved
    }))
Exemplo n.º 28
0
def select( request, 
            redirect_field_name = REDIRECT_FIELD_NAME,
            domain_select_template = 'domain/select.html' ):
    
    domains_for_user = Domain.active_for_user(request.user)
    if not domains_for_user:
        return redirect('registration_domain')
    
    redirect_to = request.REQUEST.get(redirect_field_name, '')    
    if request.method == 'POST': # If the form has been submitted...        
        form = DomainSelectionForm(domain_list=domains_for_user,
                                   data=request.POST) # A form bound to the POST data
                     
        if form.is_valid():
            # We've just checked the submitted data against a freshly-retrieved set of domains
            # associated with the user. It's safe to set the domain in the sesssion (and we'll
            # check again on views validated with the domain-checking decorator)
            form.save(request) # Needs request because it saves domain in session
    
            #  Weak attempt to give user a good UX - make sure redirect_to isn't garbage.
            domain = form.cleaned_data['domain_list'].name
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = reverse('domain_homepage', args=[domain])
            return HttpResponseRedirect(redirect_to) # Redirect after POST
    else:
        # An unbound form
        form = DomainSelectionForm( domain_list=domains_for_user ) 

    vals = dict( next = redirect_to,
                 form = form )

    return render_to_response(request, domain_select_template, vals)
Exemplo n.º 29
0
def list_reminders(request, domain, template="reminders/partial/list_reminders.html"):
    handlers = CaseReminderHandler.get_handlers(domain=domain).all()
    print handlers
    return render_to_response(request, template, {
        'domain': domain,
        'reminder_handlers': handlers
    })
Exemplo n.º 30
0
def delete_all_data(request, domain, template="cleanup/delete_all_data.html"):
    if request.method == 'GET':
        return render_to_response(request, template, {
            'domain': domain
        })
    xforms = XFormInstance.view('reports/all_submissions',
        startkey=[domain],
        endkey=[domain, {}],
        include_docs=True,
        reduce=False
    )
    cases = CommCareCase.view('case/by_date_modified',
        startkey=[domain, {}, {}],
        endkey=[domain, {}, {}, {}],
        include_docs=True,
        reduce=False
    )
    suffix = DELETED_SUFFIX
    deletion_id = random_hex()
    for thing_list in (xforms, cases):
        for thing in thing_list:
            thing.doc_type += suffix
            thing['-deletion_id'] = deletion_id
            thing.save()
    return HttpResponseRedirect(reverse('homepage'))