Example #1
0
def generate_restore_payload(user, restore_id):
    try:
        last_sync = None
        if restore_id:
            try:
                last_sync = SyncLog.get(restore_id)
            except Exception:
                logging.error("Request for bad sync log %s by %s, ignoring..." % (restore_id, user))
        
        username = user.username
        chw_id = user.get_profile().chw_id
        if not chw_id:
            raise Exception("No linked chw found for %s" % username)
        
        chw = CommunityHealthWorker.get(chw_id)
        last_seq = get_db().info()["update_seq"]
        cases_to_send = get_open_cases_to_send(chw.current_clinic_id, 
                                               chw.current_clinic_zone, 
                                               last_sync)
        case_xml_blocks = [xml.get_case_xml(case, create) for case, create in cases_to_send]
        
        # save the case blocks
        for case, _ in cases_to_send:
            case.save()
        
        saved_case_ids = [case.case_id for case, _ in cases_to_send]
        # create a sync log for this
        last_sync_id = last_sync.get_id if last_sync is not None else None
        
        # change 5/28/2011, always sync reg xml to phone
        reg_xml = xml.get_registration_xml(chw)
        synclog = SyncLog(chw_id=chw_id, last_seq=last_seq,
                          clinic_id=chw.current_clinic_id,
                          date=datetime.utcnow(), 
                          previous_log_id=last_sync_id,
                          cases=saved_case_ids)
        synclog.save()
                                             
        yield xml.RESTOREDATA_TEMPLATE % {"registration": reg_xml, 
                                          "restore_id": synclog.get_id, 
                                          "case_list": "".join(case_xml_blocks)}
    except Exception, e:
        logging.exception("problem restoring: %s" % user.username)
        raise
Example #2
0
def logs(request):
    # TODO: pagination, etc.
    logs = get_db().view("phone/sync_logs_by_chw", group=True, group_level=1).all()
    for log in logs:
        [chw_id] = log["key"]
        try:
            chw = CommunityHealthWorker.get(chw_id)
        except ResourceNotFound:
            chw = None
        log["chw"] = chw
        # get last sync:
        log["last_sync"] = SyncLog.last_for_chw(chw_id)
                                  
    return render_to_response(request, "phone/sync_logs.html", 
                              {"sync_data": logs})
 def handle(self, *args, **options):
     if len(args) != 0:
         raise CommandError('Usage: manage.py add_clinic_ids_to_sync_logs')
     
     for sl in SyncLog.view("phone/sync_logs_by_chw", reduce=False, 
                             include_docs=True):
         try:
             chw = CommunityHealthWorker.get(sl.chw_id)
         except ResourceNotFound:
             chw = None
         if not chw:
             print "failed to update %s" % sl
             continue
         sl.clinic_id = chw.current_clinic_id
         sl.save()
                     
Example #4
0
def restore_caseless(request):
    
    restore_id_from_request = lambda req: req.GET.get("since")
    restore_id = restore_id_from_request(request)
    last_sync = None
    if restore_id:
        try:
            last_sync = SyncLog.get(restore_id)
        except Exception:
            logging.error("Request for bad sync log %s by %s, ignoring..." % (restore_id, request.user))
    
    username = request.user.username
    chw_id = request.user.get_profile().chw_id
    if not chw_id:
        raise Exception("No linked chw found for %s" % username)
    chw = CommunityHealthWorker.get(chw_id)
    
    last_seq = 0 # hackity hack
    # create a sync log for this
    if last_sync == None:
        reg_xml = xml.get_registration_xml(chw)
        synclog = SyncLog(chw_id=chw_id, last_seq=last_seq,
                          clinic_id=chw.current_clinic_id,
                          date=datetime.utcnow(), previous_log_id=None,
                          cases=[])
        synclog.save()
    else:
        reg_xml = "" # don't sync registration after initial sync
        synclog = SyncLog(chw_id=chw_id, last_seq=last_seq,
                          date=datetime.utcnow(),
                          clinic_id=chw.current_clinic_id,
                          previous_log_id=last_sync.get_id,
                          cases=[])
        synclog.save()
                                         
    to_return = xml.RESTOREDATA_TEMPLATE % {"registration": reg_xml, 
                                            "restore_id": synclog.get_id, 
                                            "case_list": ""}
    return HttpResponse(to_return, mimetype="text/xml")
Example #5
0
def sync_logs_for_chw(chw_id):
    logs = SyncLog.view("phone/sync_logs_by_chw", reduce=False, startkey=[chw_id], endkey=[chw_id, {}], include_docs=True)
    return render_to_string("phone/partials/sync_log_for_chw_table.html", 
                            {"sync_data": logs})
    
Example #6
0
def chw_dashboard_summary(clinic_dict):
    
    def _status_from_last_sync(last_sync):
        diff = datetime.utcnow() - last_sync.date if last_sync else None
        if not diff or diff > timedelta(days=5):
            return "bad"
        elif diff > timedelta(days=3):
            return "warn"
        else:
            return "good"
        
    def _fmt_hh_visits(num_visits, chw):
        ret = {}
        ret["count"] = num_visits
        
        zone = chw.get_zone()
        # > 100% of quota for the month in 30 days: green
        # 50 - 100% of quota for the month in 30 days: yellow
        # < 50% of quota for the month in 30 days: red
        # the quota is # of hh's in the zone / 3
        if zone:
            ret["households"] = zone.households
            ret["percent"] = float(100) * float(num_visits) / float(zone.households)  
            if num_visits > zone.households / 3:
                ret["status"] = "good"
            elif num_visits > zone.households / (2 * 3):
                ret["status"] = "warn"
            else: 
                ret["status"] = "bad"
        else:
            ret["percent"] = "?"
            ret["households"] = "?"
            ret["status"] = "unknown"
        return ret
    
    def _status_from_ref_visits(ref_visits):
        if ref_visits > 2:
            return "good"
        elif ref_visits > 0:
            return "warn"
        else: 
            return "bad"
        
    def _status_from_overdue_fus(fus):
        if fus > 2:
            return "bad"
        elif fus > 0:
            return "warn"
        else: 
            return "good"
        
    chws = filter(lambda chw: chw.user and chw.user.is_active,
                  CommunityHealthWorker.view("chw/by_clinic", key=clinic_dict["id"],
                                             include_docs=True).all())
    if chws:
        clinic_dict["active"] = True
        clinic_dict["chws"] = []
        for chw in chws:
            
            chw_dict = {
                "id":   chw.get_id,
                "name": chw.formatted_name,
                "zone": chw.current_clinic_zone 
            }
            # Metrics per CHW:
            # - date/time of last sync
            last_sync = SyncLog.view("phone/sync_logs_by_chw", reduce=False, 
                                     startkey=[chw.get_id, {}], endkey=[chw.get_id], 
                                     include_docs=True, limit=1, descending=True).one()
            chw_dict["last_sync"] = fmt_time(last_sync.date) if last_sync else None
            chw_dict["last_sync_status"] = _status_from_last_sync(last_sync)
            
            end = datetime.today() + timedelta(days=1)
            start = end - timedelta(days=30)
            
            # - current outstanding follow ups
            # Any follow up assigned to the CHW's clinic/zone that is past due
            # and not closed. This is different from the PI in that it won't
            # check whether or not the CHW has had that case sync down to their
            # phone or not.
            # This is much faster to calculate than anything else.
            res = get_db().view("centralreports/cases_due",
                                startkey=[chw.current_clinic_id, chw.current_clinic_zone, 0],
                                endkey=[chw.current_clinic_id, chw.current_clinic_zone, 
                                        end.year, end.month - 1, end.day],
                                reduce=True).one()
            chw_dict["overdue_fus"] = res["value"] if res else 0
            chw_dict["overdue_fus_status"] = _status_from_overdue_fus(chw_dict["overdue_fus"])
                        
            # - visits performed
            chw_dict["hh_visits"] = _fmt_hh_visits(forms_submitted\
                (chw.get_id, config.CHW_HOUSEHOLD_SURVEY_NAMESPACE,
                 start, end), chw)
            
            # - referrals made
            chw_dict["ref_visits"] = forms_submitted\
                (chw.get_id, config.CHW_REFERRAL_NAMESPACE,
                 start, end)
            chw_dict["ref_visits_status"] = _status_from_ref_visits(chw_dict["ref_visits"])
            
            clinic_dict["chws"].append(chw_dict)
        
        # sort
        clinic_dict["chws"].sort(key=lambda k: k['zone'])
            
    return clinic_dict