def registration(req, pk=None):
    contact = None

    if pk is not None:
        contact = get_object_or_404(
            Contact, pk=pk)

    if req.method == "POST":
        if req.POST["submit"] == "Delete Contact":
            contact.delete()
            return HttpResponseRedirect(
                reverse(registration))

        else:
            form = ContactForm(
                instance=contact,
                data=req.POST)

            if form.is_valid():
                contact = form.save()
                return HttpResponseRedirect(
                    reverse(registration))

    else:
        form = ContactForm(
            instance=contact)

    return render_to_response(req,
        "registration/dashboard.html", {
            "contacts_table": ContactTable(Contact.objects.all(), request=req),
            "contact_form": form,
            "contact": contact
        })
def message_tester(req, identity):
    if req.method == "POST":
        form = forms.MessageForm(req.POST)
        if form.is_valid():
            cd = form.cleaned_data
            utils.send_test_message(**cd)
            return _redirect(cd["identity"])

    else:
        form = forms.MessageForm({
            "identity": identity })

    # attempt to fetch the message log from the router, but don't expode
    # if it's not available. (the router probably just isn't running.)
    try:
        router_available = True
        message_log = utils.get_message_log()

    except RouterNotResponding:
        router_available = False
        message_log = None

    return render_to_response(
        req, "httptester/index.html", {
            "router_available": router_available,
            "message_log": message_log,
            "message_form": form, })
Exemple #3
0
def mwana_alerts(request):
    transport_time = get_from_request(request, "input_transport_time")
    retrieving_time = get_from_request(request, "input_retrieving_time")
    notifying_time = get_from_request(request, "input_notifying_time")
    lab_processing_days = get_from_request(request, "input_lab_processing_days")
    lab_sending_days = get_from_request(request, "input_lab_sending_days")

    alerter = Alerter()
    transport_time, not_sending_dbs_alerts = alerter.get_districts_not_sending_dbs_alerts(transport_time)
    retrieving_time, not_retrieving_results = alerter.get_clinics_not_retriving_results_alerts(retrieving_time)
    notifying_time, not_notifying_or_using_results = alerter.get_clinics_not_sending_dbs_alerts(notifying_time)

    lab_processing_days, not_processing_dbs = alerter.get_labs_not_processing_dbs_alerts(lab_processing_days)

    lab_sending_days, not_sending_dbs = alerter.get_labs_not_sending_payloads_alerts(lab_sending_days)

    return render_to_response(
        request,
        "alerts/alerts.html",
        {
            "not_sending_dbs_alerts": not_sending_dbs_alerts,
            "transport_time": transport_time,
            "not_retrieving_results": not_retrieving_results,
            "retrieving_time": retrieving_time,
            "not_notifying_or_using_results": not_notifying_or_using_results,
            "notifying_time": notifying_time,
            "not_processing_dbs": not_processing_dbs,
            "lab_processing_days": lab_processing_days,
            "not_sending_dbs": not_sending_dbs,
            "lab_sending_days": lab_sending_days,
            "days": range(1, 60),
        },
    )
Exemple #4
0
def request_details(request, request_pk):
    """Supply request details view"""
    sreq = get_object_or_404(SupplyRequest, id=request_pk)
    
    if request.method == "POST":
        original_status = sreq.status
        form = SupplyRequestForm(request.POST, instance=sreq)
        if form.is_valid():
            sreq = form.save(commit=False)
            sreq.modified = datetime.utcnow()
            sreq.save()
            if sreq.status != original_status and \
               sreq.requested_by and \
               sreq.requested_by.default_connection:
                # if the status has changed, let's send a message
                # to the original requester so they know things are 
                # proceeding.
                text = ("Your request for more %(supply)s at %(loc)s has been updated! " +\
                        "The new status is: %(status)s.") % \
                            {"supply": sreq.type.name, 
                             "loc":    sreq.location.name, 
                             "status": sreq.get_status_display().upper()}
                send_message(sreq.requested_by.default_connection, text)

            return web_message(request,
                               "Supply request %d status set to %s" % \
                               (sreq.pk, sreq.get_status_display()),
                               link=reverse("supply_dashboard"))
        
    elif request.method == "GET":
        form = SupplyRequestForm(instance=sreq)
    
    return render_to_response(request, "supply/single_request.html", 
                                  {"sreq": sreq, "form": form})
def view_location(req, location_code, location_type_slug):
    location = get_object_or_404(Location, slug=location_code)
    loc_type = get_object_or_404(LocationType, exists_in=location)
    locations = loc_type.location_set.all().order_by("slug")

    return render_to_response(req,
        "locations/dashboard.html", {
            "locations": locations })
def message_log(req):
    message_table = MessagelogTable(request=req)
    message_table.paginate(QuerySetPaginator, MESSAGES_PER_PAGE,
                           page=req.GET.get('page', 1))
    return render_to_response(req,
        "messagelog/index.html", {
            "messages": message_table,
        })
Exemple #7
0
def dashboard(request):
    """Supply dashboard"""
    active_requests = SupplyRequest.active().order_by("-created").order_by("location")
    locations = set((req.location for req in active_requests))
    for location in locations:
        location.active_requests = active_requests.filter(location=location)
    return render_to_response(request, "supply/dashboard.html", 
                              {"active_requests": active_requests,
                               "locations": locations })
Exemple #8
0
def location_details(request, location_pk):
    """Supply location details view"""
    loc = get_object_or_404(Location.objects.select_related(depth=3),
                            pk=location_pk)

    # this is sneaky, but allows us to access this list from
    # template tags without doing extra querying.
    loc.active_requests = SupplyRequest.active().filter(location=loc)
    return render_to_response(request, "supply/single_location.html",
                              {"location": loc})
Exemple #9
0
def location_details(request, location_pk):
    """Supply location details view"""
    loc = get_object_or_404(Location.objects.select_related(depth=3), 
                            pk=location_pk)
    
    # this is sneaky, but allows us to access this list from
    # template tags without doing extra querying.
    loc.active_requests = SupplyRequest.active().filter(location=loc)
    return render_to_response(request, "supply/single_location.html", 
                              {"location": loc} )
Exemple #10
0
def patient_update (request, patid):
    patient = get_object_or_404(Registration, patient_id=patid)
    form = PatientForm(instance=patient)
    
    sent = SentNotif.objects.filter(patient_id=patient)
    patient.notifications = ', '.join(str(d) for d in sorted([s.day for s in sent])) if len(sent) > 0 else 'none sent yet'
    annotate_patient(patient)

    return render_to_response(request, 'circumcision/patient.html',
            {'px': patient, 'pat_form': form})
Exemple #11
0
def dashboard(request):
    """Supply dashboard"""
    active_requests = SupplyRequest.active().order_by("-created").order_by(
        "location")
    locations = set((req.location for req in active_requests))
    for location in locations:
        location.active_requests = active_requests.filter(location=location)
    return render_to_response(request, "supply/dashboard.html", {
        "active_requests": active_requests,
        "locations": locations
    })
def locations(req, location_uid=None):
    view_location = None

    if location_uid is not None:
        view_location = Location.get_for_uid(
            location_uid)

    if req.method == "POST":
        model_class = utils.get_model(req.POST["type"])
        form_class = utils.form_for_model(model_class)
        model = None

        if req.POST.get("id", None):
            model = get_object_or_404(
                model_class, pk=req.POST["id"])

            if req.POST["submit"] == "Delete":
                model.delete()
                return HttpResponseRedirect(
                    reverse(view_location))

        form = form_class(instance=model, data=req.POST)

        if form.is_valid():
            model = form.save()

            if req.POST.get("parent_type", None) and req.POST.get("parent_id", None):
                parent_class = utils.get_model(req.POST["parent_type"])
                parent = get_object_or_404(parent_class, pk=req.POST["parent_id"])
                model.parent = parent
                model.save()

            return HttpResponseRedirect(
                reverse(locations, args=(model.uid,)))

    types = [
        LocationTypeStub(type, req, view_location)
        for type in Location.subclasses()]

    return render_to_response(req,
        "locations/dashboard.html", {
            "breadcrumbs": _breadcrumbs(view_location),
            "location": view_location,
            "location_types": types,

            # from rapidsms.contrib.locations.settings
            "default_latitude":  settings.MAP_DEFAULT_LATITUDE,
            "default_longitude": settings.MAP_DEFAULT_LONGITUDE,

            # if there are no locationtypes, then we should display a
            # big error, since this app is useless without them.
            "no_location_types": (len(types) == 0)
         }
     )
def registration(req, pk=None):
    contact = None

    if pk is not None:
        contact = get_object_or_404(
            Contact, pk=pk)

    if req.method == "POST":
        if req.POST["submit"] == "Delete Contact":
            contact.delete()
            return HttpResponseRedirect(
                reverse(registration))

        else:
            form = ContactForm(
                instance=contact,
                data=req.POST)

            if form.is_valid():
                contact = form.save()
                return HttpResponseRedirect(
                    reverse(registration))

    else:
        form = ContactForm(
            instance=contact)

    class ContactRow(ModelRow):

        # add an 'url' attribute; a link to the edit page, with the same
        # GET parameters as the current view. this lets us persist the
        # pagination params (page=, per-page=), maintaining the current
        # state of the contacts list (on the left).
        def url(self):
            u = reverse(registration, args=[self.data.pk])
            if req.GET: u += "?%s" % req.GET.urlencode()
            return u

        # add an 'is_active' attr, to highlight the row that we're
        # currently editing (if any) in the form to the right.
        def is_active(self):
            return self.data == contact

    return render_to_response(req,
        "registration/dashboard.html", {
            "contacts": ContactTable(request=req, row_class=ContactRow),
            "contact_form": form,
            "contact": contact
        })
def edit(request, pk, template="scheduler/edit.html"):
    context = {}
    schedule = get_object_or_404(EventSchedule, id=pk)
    if request.method == 'POST':
        form = ScheduleForm(request.POST, instance=schedule)
        if form.is_valid():
            form.save()
            context['status'] = _("Schedule '%(name)s' successfully updated" % \
                                {'name':schedule.callback} )
        else:
            context['errors'] = form.errors
    else:
        form = ScheduleForm(instance=schedule)
    context['form'] = form
    context['schedule'] = schedule
    return render_to_response(request, template, context)    
Exemple #15
0
def patient_list (request):

    #handle submission for updating a patient (from /patient/xxx/)
    patient_id = None
    if request.method == 'POST' and 'patient_id' in request.POST:
        patient_id = request.POST['patient_id']
    save_msg = None
    if patient_id != None:
        form = PatientForm(request.POST, instance=Registration.objects.get(patient_id=patient_id))
        if form.is_valid():
            form.save()
            save_msg = 'Successfully updated patient %s' % patient_id
        else:
            save_msg = 'Unable to update patient %s! %s' % (patient_id, form.errors)
    
    regs = load_patients()
    return render_to_response(request, 'circumcision/overview.html',
            {'days': config.notification_days, 'patients': paginated(request, regs), 'save_msg': save_msg, 'qt': util.reg_totals(regs)})
def view_location_type(req, location_type_slug):

    # look up the location type by the slug
    # (maybe not as concise as the 
    loc_type = get_object_or_404(
        LocationType,
        slug=location_type_slug)

    # prefetch all locations in this loc_type,
    # since we're going to plot them ALL on the
    # google map whether or not they're visible
    all_locations = list(loc_type.locations.all().order_by("code"))

    return render_to_response(req,
        "locations/view_location_type.html", {
            "active_location_type_tab": loc_type.pk,
            "locations": paginated(req, all_locations, prefix="loc", wrapper=with_related_objects),
            "relations": related_objects(Location),
            "all_locations": all_locations,
            "location_type": loc_type })
def edit_location(req, location_type_slug, location_pk):
    loc_type = get_object_or_404(LocationType, slug=location_type_slug)
    location = get_object_or_404(Location, pk=location_pk)

    if req.method == "GET":
        return render_to_response(req,
            "locations/location_form.html", {
                "active_location_type_tab": loc_type.pk,
                "location": location,

                # redirect back to this view to save (below)
                "save_url": reverse("edit_location", kwargs={
                    "location_type_slug": location_type_slug,
                    "location_pk": location_pk }),

            # is the map visible? default to 0 (hidden)
            # since the map makes everything very slow
            "show_map": int(req.GET.get("map", 0)) })

    elif req.method == "POST":
        # if DELETE was clicked... delete
        # the object, then and redirect
        if req.POST.get("delete", ""):
            pk = location.pk
            location.delete()

            return web_message(req,
                "Location %d deleted" % (pk),
                link=reverse("locations_dashboard"))

        # otherwise, just update the object
        # and display the success message
        else:
            
            location = update_via_querydict(location, req.POST)
            location.save()

            return web_message(req,
                "Location %d saved" % (location.pk),
                link=reverse("locations_dashboard"))
def dashboard(req, location_pk=None):
    
    # to avoid the breadcrumb trail being empty browsing the entire
    # world, hard-code the first item. TODO: configure via settings.
    breadcrumbs = [("Planet Earth", reverse(dashboard))]

    # if a location was given, we will display its sub-locations via its
    # sub-locationtypes.
    if location_pk is not None:
        location = get_object_or_404(Location, pk=location_pk)
        location_form = LocationForm(instance=location)

        # add each ancestor to the breadcrumbs.
        for loc in location.path:
            url = reverse(dashboard, args=(loc.pk,))
            breadcrumbs.append((loc.name, url))

    # no location is fine; we're browing the entire world. the top-level
    # location types will be returned by filter(exists_in=None).
    else:
        location = None
        location_form = None

    # build a list of [sub-]locationtypes with their locations, to avoid
    # having to invoke the ORM from the template (which is foul).
    locations_data = [
        (x, Location.objects.filter(type=x))
        for x in LocationType.objects.filter(exists_in=location)
    ]

    return render_to_response(req,
        "locations/dashboard.html", {
            "breadcrumbs": breadcrumbs,
            "locations_data": locations_data,
            "location_form": location_form,
            "location": location
         }
     )
def add_location(req, location_type_slug):
    loc_type = get_object_or_404(LocationType, slug=location_type_slug)

    if req.method == "GET":
        return render_to_response(req,
            "locations/location_form.html", {
                "active_location_type_tab": loc_type.pk,

                # redirect back to this view to save (below)
                "save_url": reverse("add_location", kwargs={
                    "location_type_slug": location_type_slug}),

                # is the map visible? default to 1 (visible),
                # since i almost always want to set the location
                "show_map": int(req.GET.get("map", 1)) })

    elif req.method == "POST":
        location = insert_via_querydict(Location, req.POST, { "type": loc_type })
        location.save()
        
        return web_message(req,
            "Location %d saved" % (location.pk),
            link=reverse("locations_dashboard"))
Exemple #20
0
def request_details(request, request_pk):
    """Supply request details view"""
    sreq = get_object_or_404(SupplyRequest, id=request_pk)

    if request.method == "POST":
        original_status = sreq.status
        form = SupplyRequestForm(request.POST, instance=sreq)
        if form.is_valid():
            sreq = form.save(commit=False)
            sreq.modified = datetime.utcnow()
            sreq.save()
            if sreq.status != original_status and \
               sreq.requested_by and \
               sreq.requested_by.default_connection:
                # if the status has changed, let's send a message
                # to the original requester so they know things are
                # proceeding.
                text = ("Your request for more %(supply)s at %(loc)s has been updated! " +\
                        "The new status is: %(status)s.") % \
                            {"supply": sreq.type.name,
                             "loc":    sreq.location.name,
                             "status": sreq.get_status_display().upper()}
                send_message(sreq.requested_by.default_connection, text)

            return web_message(request,
                               "Supply request %d status set to %s" % \
                               (sreq.pk, sreq.get_status_display()),
                               link=reverse("supply_dashboard"))

    elif request.method == "GET":
        form = SupplyRequestForm(instance=sreq)

    return render_to_response(request, "supply/single_request.html", {
        "sreq": sreq,
        "form": form
    })
Exemple #21
0
def mwana_alerts(request):
    transport_time = get_from_request(request, 'input_transport_time')
    retrieving_time = get_from_request(request, 'input_retrieving_time')
    notifying_time = get_from_request(request, 'input_notifying_time')
    lab_processing_days = get_from_request(request,
                                           'input_lab_processing_days')
    lab_sending_days = get_from_request(request, 'input_lab_sending_days')

    alerter = Alerter()
    transport_time, not_sending_dbs_alerts = \
        alerter.get_districts_not_sending_dbs_alerts(transport_time)
    retrieving_time, not_retrieving_results = \
        alerter.get_clinics_not_retriving_results_alerts(retrieving_time)
    notifying_time, not_notifying_or_using_results = \
        alerter.get_clinics_not_sending_dbs_alerts(notifying_time)

    lab_processing_days, not_processing_dbs = \
        alerter.get_labs_not_processing_dbs_alerts(lab_processing_days)

    lab_sending_days, not_sending_dbs = \
        alerter.get_labs_not_sending_payloads_alerts(lab_sending_days)

    return render_to_response(
        request, 'alerts/alerts.html', {
            'not_sending_dbs_alerts': not_sending_dbs_alerts,
            'transport_time': transport_time,
            'not_retrieving_results': not_retrieving_results,
            'retrieving_time': retrieving_time,
            'not_notifying_or_using_results': not_notifying_or_using_results,
            'notifying_time': notifying_time,
            'not_processing_dbs': not_processing_dbs,
            'lab_processing_days': lab_processing_days,
            'not_sending_dbs': not_sending_dbs,
            'lab_sending_days': lab_sending_days,
            'days': range(1, 60),
        })
Exemple #22
0
def dashboard(request):
    locations = Location.objects.all()
    return render_to_response(request, "labresults/dashboard.html",
                              {"locations": locations })
Exemple #23
0
def mwana_reports (request):
#    , startdate=datetime.today().date()-timedelta(days=30),
#                    enddate=datetime.today().date(
    from mwana.apps.reports.webreports.reportcreator import Results160Reports
   
    today = datetime.today().date()
    try:
        startdate1 = text_date(request.REQUEST['startdate'])
    except (KeyError, ValueError, IndexError):
        startdate1 = today -timedelta(days=30)

    try:
        enddate1 = text_date(request.REQUEST['enddate'])
    except (KeyError, ValueError, IndexError):
        enddate1 = datetime.today().date()
    startdate = min(startdate1, enddate1, datetime.today().date())
    enddate = min(max(enddate1, startdate1), datetime.today().date())
    
    r = Results160Reports()
    res = r.dbs_sent_results_report(startdate, enddate)

    min_processing_time, max_processing_time, num_of_dbs_processed, \
    num_facs_processing, processing_time =\
    r.dbs_avg_processing_time_report(startdate, enddate)

    min_entering_time, max_entering_time, num_of_rsts_entered, \
    num_facs_entering, entering_time =\
    r.dbs_avg_entering_time_report(startdate, enddate)

    min_retrieval_time, max_retrieval_time, num_of_dbs_retrieved, \
    num_facs_retrieving, retrieval_time =\
    r.dbs_avg_retrieval_time_report(startdate, enddate)

    min_turnaround_time, max_turnaround_time, num_of_rsts, num_of_facilities,\
    turnaround_time = r.dbs_avg_turnaround_time_report(startdate, enddate)

    min_transport_time, max_transport_time, num_of_dbs, num_of_facs,\
    transport_time = r.dbs_avg_transport_time_report(startdate, enddate)

    samples_reported = r.dbs_sample_notifications_report(startdate, enddate)

    samples_at_lab = r.dbs_samples_at_lab_report(startdate, enddate)

    pending = r.dbs_pending_results_report(startdate, enddate)

    payloads = r.dbs_payloads_report(startdate, enddate)

    births = r.reminders_patient_events_report(startdate, enddate)

    single_bar_length, tt_in_graph, graph = r.dbs_graph_data(startdate, enddate)

    percent_positive_country, percent_negative_country, percent_rejected_country\
                , percent_positive_provinces, percent_negative_provinces\
                , percent_rejected_provinces, total_dbs, months_reporting,\
                days_reporting, year_reporting =r.dbs_positivity_data()

    return render_to_response(request, 'labresults/reports.html',
                                {'startdate':startdate,
                                'enddate':enddate,
                                'today':today,
                                'sent_results_rpt':res,
                                'turnaround_time_rpt':turnaround_time,
                                'min_turnaround_time':min_turnaround_time,
                                'max_turnaround_time':max_turnaround_time,
                                'num_of_results':num_of_rsts,
                                'num_of_facilities':num_of_facilities,
                                'processing_time_rpt':processing_time,
                                'min_processing_time':min_processing_time,
                                'max_processing_time':max_processing_time,
                                'num_of_dbs_processed':num_of_dbs_processed,
                                'num_facs_processing':num_facs_processing,
                                'retrieval_time_rpt':retrieval_time,
                                'min_retrieving_time':min_retrieval_time,
                                'max_retrieving_time':max_retrieval_time,
                                'num_of_dbs_retrieved':num_of_dbs_retrieved,
                                'num_facs_retrieving':num_facs_retrieving,
                                'entering_time_rpt':entering_time,
                                'min_entering_time':min_entering_time,
                                'max_entering_time':max_entering_time,
                                'num_of_rsts_entered':num_of_rsts_entered,
                                'num_facs_entering':num_facs_entering,
                                'transport_time_rpt':transport_time,
                                'min_transport_time':min_transport_time,
                                'max_transport_time':max_transport_time,
                                'num_of_dbs':num_of_dbs,
                                'num_of_facs':num_of_facs,
                                'samples_reported_rpt':samples_reported,
                                'samples_at_lab_rpt':samples_at_lab,
                                'pending_results':pending,
                                'payloads_rpt':payloads,
                                'births_rpt':births,
                                'formattedtoday':today.strftime("%d %b %Y"),
                                'formattedtime':datetime.today().strftime("%I:%M %p"),
                                'graph':graph,
                                'single_bar_length':single_bar_length,
                                'tt_in_graph':tt_in_graph,
                                'percent_positive_country':percent_positive_country,
                                'percent_negative_country':percent_negative_country,
                                'percent_rejected_country':percent_rejected_country,
                                'percent_positive_provinces':percent_positive_provinces,
                                'percent_negative_provinces':percent_negative_provinces,
                                'percent_rejected_provinces':percent_rejected_provinces,
                                'total_dbs':total_dbs,
                                'months_reporting':months_reporting,
                                'days_reporting':days_reporting,
                                'year_reporting':year_reporting,
                                })
Exemple #24
0
def log_viewer (request, daysback='7', source_filter=''):
    try:
        daysback = int(daysback)
    except ValueError:
        #todo: return error - parameter is not an int
        pass

    if daysback <= 0 or daysback >= 10000:
        #todo: return error - parameter out of range
        pass

    #get log records to display - any log entry in a payload that was received in the past N days
    cutoff_date = (datetime.now() - timedelta(days=daysback))
    payloads = labresults.Payload.objects.filter(incoming_date__gte=cutoff_date)
    logs = labresults.LabLog.objects.filter(payload__in=payloads)

    #extract displayable info from log records, remove duplicate (re-sent) entries
    log_info = {}
    meta_logs = [] #meta logs are log messages related to logging itself; they have no line numbers or timestamps
    for log_record in logs:
        if log_record.message == None:
            #skip log entries that weren't parseable
            continue

        if not log_record.payload.source.startswith(source_filter):
            continue

        log_entry = {
            'line': log_record.line,
            'timestamp': log_record.timestamp,
            'level': log_record.level,
            'message': log_record.message,
            'received_on': log_record.payload.incoming_date,
            'received_from': log_record.payload.source,
            'version': log_record.payload.version,
        }
        log_uid = (log_entry['line'], log_entry['timestamp'])

        if log_entry['line'] == -1:
            meta_logs.append(log_entry)
        elif log_uid in log_info:
            if log_entry['received_on'] < log_info[log_uid]['received_on']:
                #save the earliest 'received on' date for re-sent entries
                log_info[log_uid] = log_entry
        else:
            log_info[log_uid] = log_entry
    log_entries = log_info.values()
    log_entries.extend(meta_logs)

    #sort records into chronological order (best-faith effort)
    lines = set(lg['line'] for lg in log_entries)
    #if log entry buffer contains both high- and low-numbered lines, log file rotation may have occurred recently
    wraparound = len(lines | set(range(0, 500))) > 0 and (max(lines) if lines else 0) >= log_rotation_threshold
    #if multiple log messages have the same line #, could suggest the log file was recently erased
    collisions = any(len([lg for lg in log_entries if lg['line'] == ln]) > 1 for ln in lines if ln != -1)
    log_entries.sort(cmp=lambda x, y: log_cmp(x, y, wraparound))

    #format information for display
    log_display_items = []
    for le in log_entries:
        ldi = {
            'type': 'log',
            'line': le['line'],
            'timestamp': '%s.%03d' % (le['timestamp'].strftime('%Y-%m-%d %H:%M:%S'), le['timestamp'].microsecond / 1000),
            'level': level_abbr(le['level']),
            'message': le['message'],
            'received_on': le['received_on'],
            'received_from': recvd_from(le['received_from'], le['version'])
        }

        if ldi['line'] == -1:
            ldi['type'] = 'meta-log'
        elif len(log_display_items) > 0:
            prev_line = log_display_items[-1]['line']
            if prev_line != -1:
                expected_next_line = prev_line + len(log_display_items[-1]['message'].split('\n'))
                cur_line = le['line']

                if cur_line > expected_next_line:
                    log_display_items.append({'type': 'alert', 'message': 'missing log entries (%d lines)' % (cur_line - expected_next_line)})
                elif cur_line < expected_next_line:
                    log_display_items.append({'type': 'alert', 'message': 'logfile rotation (?)'})

        log_display_items.append(ldi)

    return render_to_response(request, 'labresults/logview.html',
                              {'display_info': log_display_items, 'collisions': collisions,
                               'days': daysback, 'source': source_filter})
def messaging(req):
    return render_to_response(req,
        "messaging/dashboard.html", {
            "people": paginated(req, Contact.objects.all()),
            "filters": filters.fetch()
        })
Exemple #26
0
def log_viewer(request, daysback='7', source_filter=''):
    try:
        daysback = int(daysback)
    except ValueError:
        #todo: return error - parameter is not an int
        pass

    if daysback <= 0 or daysback >= 10000:
        #todo: return error - parameter out of range
        pass

    #get log records to display - any log entry in a payload that was received in the past N days
    cutoff_date = (datetime.now() - timedelta(days=daysback))
    payloads = labresults.Payload.objects.filter(
        incoming_date__gte=cutoff_date)
    logs = labresults.LabLog.objects.filter(payload__in=payloads)

    #extract displayable info from log records, remove duplicate (re-sent) entries
    log_info = {}
    meta_logs = [
    ]  #meta logs are log messages related to logging itself; they have no line numbers or timestamps
    for log_record in logs:
        if log_record.message == None:
            #skip log entries that weren't parseable
            continue

        if not log_record.payload.source.startswith(source_filter):
            continue

        log_entry = {
            'line': log_record.line,
            'timestamp': log_record.timestamp,
            'level': log_record.level,
            'message': log_record.message,
            'received_on': log_record.payload.incoming_date,
            'received_from': log_record.payload.source,
            'version': log_record.payload.version,
        }
        log_uid = (log_entry['line'], log_entry['timestamp'])

        if log_entry['line'] == -1:
            meta_logs.append(log_entry)
        elif log_uid in log_info:
            if log_entry['received_on'] < log_info[log_uid]['received_on']:
                #save the earliest 'received on' date for re-sent entries
                log_info[log_uid] = log_entry
        else:
            log_info[log_uid] = log_entry
    log_entries = log_info.values()
    log_entries.extend(meta_logs)

    #sort records into chronological order (best-faith effort)
    lines = set(lg['line'] for lg in log_entries)
    #if log entry buffer contains both high- and low-numbered lines, log file rotation may have occurred recently
    wraparound = len(lines | set(range(0, 500))) > 0 and (
        max(lines) if lines else 0) >= log_rotation_threshold
    #if multiple log messages have the same line #, could suggest the log file was recently erased
    collisions = any(
        len([lg for lg in log_entries if lg['line'] == ln]) > 1 for ln in lines
        if ln != -1)
    log_entries.sort(cmp=lambda x, y: log_cmp(x, y, wraparound))

    #format information for display
    log_display_items = []
    for le in log_entries:
        ldi = {
            'type':
            'log',
            'line':
            le['line'],
            'timestamp':
            '%s.%03d' % (le['timestamp'].strftime('%Y-%m-%d %H:%M:%S'),
                         le['timestamp'].microsecond / 1000),
            'level':
            level_abbr(le['level']),
            'message':
            le['message'],
            'received_on':
            le['received_on'],
            'received_from':
            recvd_from(le['received_from'], le['version'])
        }

        if ldi['line'] == -1:
            ldi['type'] = 'meta-log'
        elif len(log_display_items) > 0:
            prev_line = log_display_items[-1]['line']
            if prev_line != -1:
                expected_next_line = prev_line + len(
                    log_display_items[-1]['message'].split('\n'))
                cur_line = le['line']

                if cur_line > expected_next_line:
                    log_display_items.append({
                        'type':
                        'alert',
                        'message':
                        'missing log entries (%d lines)' %
                        (cur_line - expected_next_line)
                    })
                elif cur_line < expected_next_line:
                    log_display_items.append({
                        'type': 'alert',
                        'message': 'logfile rotation (?)'
                    })

        log_display_items.append(ldi)

    return render_to_response(
        request, 'labresults/logview.html', {
            'display_info': log_display_items,
            'collisions': collisions,
            'days': daysback,
            'source': source_filter
        })
Exemple #27
0
def mwana_reports(request):
    #    , startdate=datetime.today().date()-timedelta(days=30),
    #                    enddate=datetime.today().date(
    from mwana.apps.reports.webreports.reportcreator import Results160Reports

    today = datetime.today().date()
    try:
        startdate1 = text_date(request.REQUEST['startdate'])
    except (KeyError, ValueError, IndexError):
        startdate1 = today - timedelta(days=30)

    try:
        enddate1 = text_date(request.REQUEST['enddate'])
    except (KeyError, ValueError, IndexError):
        enddate1 = datetime.today().date()
    startdate = min(startdate1, enddate1, datetime.today().date())
    enddate = min(max(enddate1, startdate1), datetime.today().date())

    r = Results160Reports()
    res = r.dbs_sent_results_report(startdate, enddate)

    min_processing_time, max_processing_time, num_of_dbs_processed, \
    num_facs_processing, processing_time =\
    r.dbs_avg_processing_time_report(startdate, enddate)

    min_entering_time, max_entering_time, num_of_rsts_entered, \
    num_facs_entering, entering_time =\
    r.dbs_avg_entering_time_report(startdate, enddate)

    min_retrieval_time, max_retrieval_time, num_of_dbs_retrieved, \
    num_facs_retrieving, retrieval_time =\
    r.dbs_avg_retrieval_time_report(startdate, enddate)

    min_turnaround_time, max_turnaround_time, num_of_rsts, num_of_facilities,\
    turnaround_time = r.dbs_avg_turnaround_time_report(startdate, enddate)

    min_transport_time, max_transport_time, num_of_dbs, num_of_facs,\
    transport_time = r.dbs_avg_transport_time_report(startdate, enddate)

    samples_reported = r.dbs_sample_notifications_report(startdate, enddate)

    samples_at_lab = r.dbs_samples_at_lab_report(startdate, enddate)

    pending = r.dbs_pending_results_report(startdate, enddate)

    payloads = r.dbs_payloads_report(startdate, enddate)

    births = r.reminders_patient_events_report(startdate, enddate)

    single_bar_length, tt_in_graph, graph = r.dbs_graph_data(
        startdate, enddate)

    percent_positive_country, percent_negative_country, percent_rejected_country\
                , percent_positive_provinces, percent_negative_provinces\
                , percent_rejected_provinces, total_dbs, months_reporting,\
                days_reporting, year_reporting =r.dbs_positivity_data()

    return render_to_response(
        request, 'labresults/reports.html', {
            'startdate': startdate,
            'enddate': enddate,
            'today': today,
            'sent_results_rpt': res,
            'turnaround_time_rpt': turnaround_time,
            'min_turnaround_time': min_turnaround_time,
            'max_turnaround_time': max_turnaround_time,
            'num_of_results': num_of_rsts,
            'num_of_facilities': num_of_facilities,
            'processing_time_rpt': processing_time,
            'min_processing_time': min_processing_time,
            'max_processing_time': max_processing_time,
            'num_of_dbs_processed': num_of_dbs_processed,
            'num_facs_processing': num_facs_processing,
            'retrieval_time_rpt': retrieval_time,
            'min_retrieving_time': min_retrieval_time,
            'max_retrieving_time': max_retrieval_time,
            'num_of_dbs_retrieved': num_of_dbs_retrieved,
            'num_facs_retrieving': num_facs_retrieving,
            'entering_time_rpt': entering_time,
            'min_entering_time': min_entering_time,
            'max_entering_time': max_entering_time,
            'num_of_rsts_entered': num_of_rsts_entered,
            'num_facs_entering': num_facs_entering,
            'transport_time_rpt': transport_time,
            'min_transport_time': min_transport_time,
            'max_transport_time': max_transport_time,
            'num_of_dbs': num_of_dbs,
            'num_of_facs': num_of_facs,
            'samples_reported_rpt': samples_reported,
            'samples_at_lab_rpt': samples_at_lab,
            'pending_results': pending,
            'payloads_rpt': payloads,
            'births_rpt': births,
            'formattedtoday': today.strftime("%d %b %Y"),
            'formattedtime': datetime.today().strftime("%I:%M %p"),
            'graph': graph,
            'single_bar_length': single_bar_length,
            'tt_in_graph': tt_in_graph,
            'percent_positive_country': percent_positive_country,
            'percent_negative_country': percent_negative_country,
            'percent_rejected_country': percent_rejected_country,
            'percent_positive_provinces': percent_positive_provinces,
            'percent_negative_provinces': percent_negative_provinces,
            'percent_rejected_provinces': percent_rejected_provinces,
            'total_dbs': total_dbs,
            'months_reporting': months_reporting,
            'days_reporting': days_reporting,
            'year_reporting': year_reporting,
        })
Exemple #28
0
def dashboard(request):
    locations = Location.objects.all()
    return render_to_response(request, "labresults/dashboard.html",
                              {"locations": locations})
Exemple #29
0
def dashboard(req):
    return render_to_response(req, "dashboard.html")
def index(request, template="scheduler/index.html"):
    context = {}
    schedules = EventSchedule.objects.all()
    context['schedules'] = paginated(request, schedules)
    return render_to_response(request, template, context)
def message_log(req):
    return render_to_response(req,
        "messagelog/index.html", {
            "messages_table": MessageTable(Message.objects.all(), request=req)
        })