def ovc_home(request): """Some default page for Server Errors.""" try: rid = 0 reqid = request.GET.get('id', '') offset = request.GET.get('offset', '') limit = request.GET.get('limit', '') if reqid and offset and limit: rid = 2 if request.method == 'POST' or rid: aid = request.POST.get('id') act_id = int(aid) if aid else 0 action_id = rid if rid else act_id if action_id in [1, 2, 3]: msg, chs = manage_checkins(request, rid) results = {'status': 0, 'message': msg, 'checkins': chs} if rid == 2: results = chs return JsonResponse(results, content_type='application/json', safe=False) form = OVCSearchForm(data=request.POST) ovcs = search_ovc(request) check_fields = ['sex_id'] vals = get_dict(field_name=check_fields) return render(request, 'ovc/home.html', {'form': form, 'ovcs': ovcs, 'vals': vals}) form = OVCSearchForm() return render(request, 'ovc/home.html', {'form': form, 'status': 200}) except Exception, e: raise e
def settings_duplicates(request): """Method to do pivot reports.""" try: duplicates = get_duplicates(request) check_fields = ['sex_id', 'case_category_id'] vals = get_dict(field_name=check_fields) if request.method == 'POST': action = request.POST.get('action_id') action_id = int(action) if action else 0 if action_id == 2: # Remove duplicates res = remove_duplicates(request) else: res = handle_duplicates(request) status = res['status'] msg = res['message'] results = {"status": status, "message": msg} return JsonResponse(results, content_type='application/json', safe=False) return render(request, 'settings/duplicates.html', { 'results': duplicates, 'vals': vals }) except Exception as e: raise e else: pass
def process_integration(request, case_id): """Method to process case.""" try: case = OVCBasicCRS.objects.get(case_id=case_id, is_void=False) county_code = int(case.county) const_code = int(case.constituency) county_id, const_id = 0, 0 crs_id = str(case_id).replace('-', '') user_counties, user_geos = get_person_geo(request) # Get person orgs ou_ids = get_person_orgs(request) if request.method == 'POST': response = handle_integration(request, case, case_id) print(response) check_fields = ['sex_id', 'case_category_id', 'case_reporter_id', 'family_status_id', 'household_economics', 'risk_level_id', 'mental_condition_id', 'perpetrator_status_id', 'other_condition_id', 'physical_condition_id', 'yesno_id'] vals = get_dict(field_name=check_fields) category = OVCBasicCategory.objects.filter( case_id=case_id, is_void=False) person = OVCBasicPerson.objects.filter(case_id=case_id, is_void=False) # Attached Geos and Org Units for the user # ou_ids = [] org_id = request.session.get('ou_primary', 0) ou_ids.append(org_id) ou_attached = request.session.get('ou_attached', 0) user_level = request.session.get('user_level', 0) user_type = request.session.get('user_type', 0) print(org_id, ou_attached, user_level, user_type) # person_id = request.user.reg_person_id county = SetupGeography.objects.filter( area_code=county_code, area_type_id='GPRV') for c in county: county_id = c.area_id # Get constituency constituency = SetupGeography.objects.filter( area_code=const_code, area_type_id='GDIS') for c in constituency: const_id = c.area_id ous = RegOrgUnit.objects.filter(is_void=False) counties = SetupGeography.objects.filter(area_type_id='GPRV') if user_counties: counties = counties.filter(area_id__in=user_counties) if request.user.is_superuser: all_ou_ids = ['TNGD'] ous = ous.filter(org_unit_type_id__in=all_ou_ids) geos = SetupGeography.objects.filter( area_type_id='GDIS', parent_area_id=county_id) else: ous = ous.filter(id__in=ou_ids) geos = SetupGeography.objects.filter( area_type_id='GDIS', parent_area_id=county_id) return render(request, 'management/integration_process.html', {'form': {}, 'case': case, 'vals': vals, 'category': category, 'person': person, 'geos': geos, 'ous': ous, 'counties': counties, 'county_id': county_id, 'const_id': const_id, 'crs_id': crs_id})
def hh_manage(request, hhid): """Some default page for Server Errors.""" try: check_fields = ['hiv_status_id', 'immunization_status_id'] vals = get_dict(field_name=check_fields) hhmembers = OVCHHMembers.objects.filter( is_void=False, house_hold_id=hhid).order_by("-hh_head") return render(request, 'ovc/household.html', {'status': 200, 'hhmembers': hhmembers, 'vals': vals}) except Exception, e: print "error getting hh members - %s" % (str(e)) raise e
def ovc_home(request): """Some default page for Server Errors.""" try: if request.method == 'POST': form = OVCSearchForm(data=request.POST) ovcs = search_ovc(request) check_fields = ['sex_id'] vals = get_dict(field_name=check_fields) return render(request, 'ovc/home.html', { 'form': form, 'ovcs': ovcs, 'vals': vals }) form = OVCSearchForm() return render(request, 'ovc/home.html', {'form': form, 'status': 200}) except Exception, e: raise e
def ovc_register(request, id): """Some default page for Server Errors.""" try: ovc_id = int(id) ovc = get_ovcdetails(ovc_id) params, gparams = {}, {} initial = {} # Details child = RegPerson.objects.get(is_void=False, id=id) # Get guardians guardians = RegPersonsGuardians.objects.filter( is_void=False, child_person_id=child.id) # Get siblings siblings = RegPersonsSiblings.objects.filter(is_void=False, child_person_id=child.id) print 'p', params, 'gp', gparams guids, chids = [], [] for guardian in guardians: guids.append(guardian.guardian_person_id) guids.append(child.id) for sibling in siblings: chids.append(sibling.sibling_person_id) pids = {'guids': guids, 'chids': chids} print pids # Existing extids = RegPersonsExternalIds.objects.filter(person_id__in=guids) for extid in extids: if extid.person_id == child.id: params[extid.identifier_type_id] = extid.identifier else: gkey = '%s_%s' % (extid.person_id, extid.identifier_type_id) gparams[gkey] = extid.identifier if request.method == 'POST': form = OVCRegistrationForm(guids=pids, data=request.POST) print request.POST ovc_registration(request, ovc_id) msg = "OVC Registration completed successfully" messages.info(request, msg) url = reverse('ovc_view', kwargs={'id': ovc_id}) return HttpResponseRedirect(url) else: cbo_id = ovc.child_cbo_id cbo_uid = gen_cbo_id(cbo_id, ovc_id) initial['cbo_uid'] = cbo_uid initial['cbo_id'] = cbo_id initial['cbo_uid_check'] = cbo_uid if 'ISOV' in params: initial['bcert_no'] = params['ISOV'] initial['has_bcert'] = 'on' form = OVCRegistrationForm(guids=pids, initial=initial) # Check users changing ids in urls ovc_detail = get_hh_members(ovc_id) if ovc_detail: msg = "OVC already registered. Visit edit page." messages.error(request, msg) url = reverse('ovc_view', kwargs={'id': ovc_id}) return HttpResponseRedirect(url) # Class levels levels = {} levels["SLNS"] = [] levels["SLEC"] = [ "BABY,Baby Class", "MIDC,Middle Class", "PREU,Pre-Unit" ] levels["SLPR"] = [ "CLS1,Class 1", "CLS2,Class 2", "CLS3,Class 3", "CLS4,Class 4", "CLS5,Class 5", "CLS6,Class 6", "CLS7,Class 7", "CLS8,Class 8" ] levels["SLSE"] = [ "FOM1,Form 1", "FOM2,Form 2", "FOM3,Form 3", "FOM4,Form 4", "FOM5,Form 5", "FOM6,Form 6" ] levels["SLUN"] = [ "YER1,Year 1", "YER2,Year 2", "YER3,Year 3", "YER4,Year 4", "YER5,Year 5", "YER6,Year 6" ] levels["SLTV"] = [ "TVC1,Year 1", "TVC2,Year 2", "TVC3,Year 3", "TVC4,Year 4", "TVC5,Year 5" ] # Re-usable values check_fields = ['relationship_type_id'] vals = get_dict(field_name=check_fields) return render( request, 'ovc/register_child.html', { 'form': form, 'status': 200, 'child': child, 'guardians': guardians, 'siblings': siblings, 'vals': vals, 'extids': gparams, 'ovc': ovc, 'levels': levels }) except Exception, e: print "error with OVC registration - %s" % (str(e)) raise e
def ovc_view(request, id): """Some default page for Server Errors.""" try: if request.method == 'POST': chs = '' org_unit_id = None ovc_id = request.POST.get('ovc_id') aid = request.POST.get('id') action_id = int(aid) if aid else 0 user_id = request.user.id if action_id == 1: msg = 'OVC checked in successfully.' if 'ou_primary' in request.session: ou_id = request.session['ou_primary'] org_unit_id = int(ou_id) if ou_id else None checkin, created = OVCCheckin.objects.update_or_create( person_id=ovc_id, user_id=user_id, defaults={ 'person_id': ovc_id, 'user_id': user_id, 'org_unit_id': org_unit_id }, ) elif action_id == 2: chs, cnt = get_checkins(user_id) msg = 'OVC checked in returned %s results.' % (cnt) results = {'status': 0, 'message': msg, 'checkins': chs} return JsonResponse(results, content_type='application/json', safe=False) ovc_id = int(id) child = RegPerson.objects.get(is_void=False, id=ovc_id) creg = OVCRegistration.objects.get(is_void=False, person_id=ovc_id) params = {} gparams = {} # Get guardians guardians = RegPersonsGuardians.objects.filter( is_void=False, child_person_id=child.id) guids = [] for guardian in guardians: guids.append(guardian.guardian_person_id) guids.append(child.id) extids = RegPersonsExternalIds.objects.filter(person_id__in=guids) for extid in extids: if extid.person_id == child.id: params[extid.identifier_type_id] = extid.identifier else: gkey = '%s_%s' % (extid.person_id, extid.identifier_type_id) gparams[gkey] = extid.identifier # Health details health = {} if creg.hiv_status == 'HSTP': health = get_health(ovc_id) # School details school = {} if creg.school_level != 'SLNS': school = get_school(ovc_id) # Get siblings siblings = RegPersonsSiblings.objects.filter(is_void=False, child_person_id=child.id) # Get services servs = {'FSAM': 'f1a', 'FCSI': 'fcsi', 'FHSA': 'fhva'} services = {'f1a': 0, 'fcsi': 0, 'fhva': 0} sqs = OVCCareEvents.objects.filter( is_void=False, person_id=child.id).values('event_type_id').annotate( total=Count('event_type_id')).order_by('total') for serv in sqs: item = serv['event_type_id'] item_count = serv['total'] if item in servs: item_key = servs[item] services[item_key] = item_count # Get house hold hhold = OVCHHMembers.objects.get(is_void=False, person_id=child.id) # Get HH members hhid = hhold.house_hold_id hhmqs = OVCHHMembers.objects.filter( is_void=False, house_hold_id=hhid).order_by("-hh_head") hhmembers = hhmqs.exclude(person_id=child.id) # Re-usable values check_fields = [ 'relationship_type_id', 'school_level_id', 'hiv_status_id', 'immunization_status_id', 'art_status_id', 'school_type_id', 'class_level_id' ] vals = get_dict(field_name=check_fields) return render( request, 'ovc/view_child.html', { 'status': 200, 'child': child, 'params': params, 'guardians': guardians, 'siblings': siblings, 'vals': vals, 'hhold': hhold, 'creg': creg, 'extids': gparams, 'health': health, 'hhmembers': hhmembers, 'school': school, 'services': services }) except Exception, e: print "error with OVC viewing - %s" % (str(e)) raise e
def ovc_edit(request, id): """Some default page for Server Errors.""" try: ovc_id = int(id) date_reg = None if request.method == 'POST': ovc_registration(request, ovc_id, 1) # Save external ids from here msg = "OVC Registration details edited successfully" messages.info(request, msg) url = reverse('ovc_view', kwargs={'id': ovc_id}) return HttpResponseRedirect(url) child = RegPerson.objects.get(is_void=False, id=ovc_id) creg = OVCRegistration.objects.get(is_void=False, person_id=ovc_id) bcert = 'on' if creg.has_bcert else '' disb = 'on' if creg.is_disabled else '' exited = '' if creg.is_active else 'on' reg_date = creg.registration_date child.caretaker = creg.caretaker_id child.cbo = creg.child_cbo.org_unit_name child.chv_name = creg.child_chv.full_name params = {} gparams = {} siblings = 0 # Get house hold hhold = OVCHHMembers.objects.get(is_void=False, person_id=child.id) hhid = hhold.house_hold_id hhmqs = OVCHHMembers.objects.filter( is_void=False, house_hold_id=hhid).order_by("-hh_head") # add caregivers hiv status hhmembers = hhmqs.exclude(person_id=child.id) # Get guardians and siblings ids guids, chids = [], [] ctaker = 0 for hh_member in hhmembers: member_type = hh_member.member_type member_head = hh_member.hh_head if member_head: ctaker = hh_member.person_id if member_type == 'TBVC' or member_type == 'TOVC': chids.append(hh_member.person_id) siblings += 1 else: guids.append(hh_member.person_id) guids.append(child.id) pids = {'guids': guids, 'chids': chids} extids = RegPersonsExternalIds.objects.filter(person_id__in=guids) for extid in extids: if extid.person_id == child.id: params[extid.identifier_type_id] = extid.identifier else: gkey = '%s_%s' % (extid.person_id, extid.identifier_type_id) gparams[gkey] = extid.identifier # Get health information ccc_no, date_linked, art_status = '', '', '' facility_id, facility = '', '' if creg.hiv_status == 'HSTP': health = get_health(ovc_id) ccc_no = health.ccc_number date_linked = health.date_linked.strftime('%d-%b-%Y') art_status = health.art_status facility_id = health.facility_id facility = health.facility.facility_name # Get School information sch_class, sch_adm_type = '', '' school_id, school = '', '' if creg.school_level != 'SLNS': school = get_school(ovc_id) if school: sch_class = school.school_class sch_adm_type = school.admission_type school_id = school.school_id school = school.school.school_name bcert_no = params['ISOV'] if 'ISOV' in params else '' ncpwd_no = params['IPWD'] if 'IPWD' in params else '' # Eligibility criterias = OVCEligibility.objects.filter( is_void=False, person_id=child.id).values_list('criteria', flat=True) if reg_date: date_reg = reg_date.strftime('%d-%b-%Y') all_values = { 'reg_date': date_reg, 'cbo_uid': creg.org_unique_id, 'cbo_uid_check': creg.org_unique_id, 'has_bcert': bcert, 'disb': disb, 'bcert_no': bcert_no, 'ncpwd_no': ncpwd_no, 'immunization': creg.immunization_status, 'school_level': creg.school_level, 'facility': facility, 'facility_id': facility_id, 'school_class': sch_class, 'school_name': school, 'school_id': school_id, 'admission_type': sch_adm_type, 'hiv_status': creg.hiv_status, 'link_date': date_linked, 'ccc_number': ccc_no, 'art_status': art_status, 'eligibility': criterias, 'is_exited': exited, 'exit_reason': creg.exit_reason } form = OVCRegistrationForm(guids=pids, data=all_values) for hhm in hhmembers: status_id = 'status_%s' % (hhm.person_id) all_values['a%s' % (status_id)] = hhm.member_alive all_values['g%s' % (status_id)] = hhm.hiv_status all_values['sg%s' % (status_id)] = hhm.hiv_status # Class levels levels = {} levels["SLNS"] = [] levels["SLEC"] = [ "BABY,Baby Class", "MIDC,Middle Class", "PREU,Pre-Unit" ] levels["SLPR"] = [ "CLS1,Class 1", "CLS2,Class 2", "CLS3,Class 3", "CLS4,Class 4", "CLS5,Class 5", "CLS6,Class 6", "CLS7,Class 7", "CLS8,Class 8" ] levels["SLSE"] = [ "FOM1,Form 1", "FOM2,Form 2", "FOM3,Form 3", "FOM4,Form 4", "FOM5,Form 5", "FOM6,Form 6" ] levels["SLUN"] = [ "YER1,Year 1", "YER2,Year 2", "YER3,Year 3", "YER4,Year 4", "YER5,Year 5", "YER6,Year 6" ] levels["SLTV"] = [ "TVC1,Year 1", "TVC2,Year 2", "TVC3,Year 3", "TVC4,Year 4", "TVC5,Year 5" ] # Re-usable values check_fields = ['relationship_type_id'] vals = get_dict(field_name=check_fields) return render( request, 'ovc/edit_child.html', { 'form': form, 'status': 200, 'child': child, 'vals': vals, 'hhold': hhold, 'extids': gparams, 'hhmembers': hhmembers, 'levels': levels, 'sch_class': sch_class, 'siblings': siblings, 'ctaker': ctaker }) except Exception, e: print "error with OVC editing - %s" % (str(e)) raise e
def home(request): """Some default page for the home page / Dashboard.""" my_dates, my_cvals = [], [] my_ovals, my_kvals = [], [] my_dvals = [] try: dash = dashboard() start_date = datetime.now() - timedelta(days=21) summary = {} summary['org_units'] = '{:,}'.format(dash['org_units']) summary['children'] = '{:,}'.format(dash['children']) summary['guardians'] = '{:,}'.format(dash['guardian']) summary['workforce'] = '{:,}'.format(dash['workforce_members']) summary['cases'] = '{:,}'.format(dash['case_records']) summary['pending'] = '{:08}'.format(dash['pending_cases']) # OVC care odash = ovc_dashboard(request) ovc = {} ovc['org_units'] = '{:,}'.format(odash['org_units']) ovc['children'] = '{:,}'.format(odash['children']) ovc['children_all'] = '{:,}'.format(odash['children_all']) ovc['guardians'] = '{:,}'.format(odash['guardian']) ovc['workforce'] = '{:,}'.format(odash['workforce_members']) ovc['cases'] = '{:,}'.format(odash['case_records']) ovc['pending'] = '{:08}'.format(odash['pending_cases']) ovc['household'] = 0 child_regs = dash['child_regs'] ovc_regs = dash['ovc_regs'] case_regs = dash['case_regs'] case_cats = dash['case_cats'] for date in range(0, 22, 2): end_date = start_date + timedelta(days=date) show_date = datetime.strftime(end_date, "%d-%b-%y") final_date = str(show_date).replace(' ', ' ') my_dates.append("[%s, '%s']" % (date, final_date)) for vl in range(1, 22): t_date = start_date + timedelta(days=vl) s_date = datetime.strftime(t_date, "%d-%b-%y") k_count = child_regs[s_date] if s_date in child_regs else 0 o_count = ovc_regs[s_date] if s_date in ovc_regs else 0 c_count = case_regs[s_date] if s_date in case_regs else 0 my_cvals.append("[%s, %s]" % (vl, c_count)) my_kvals.append("[%s, %s]" % (vl, k_count)) my_ovals.append("[%s, %s]" % (vl, o_count)) dates = ', '.join(my_dates) kvals = ', '.join(my_kvals) cvals = ', '.join(my_cvals) ovals = ', '.join(my_ovals) my_dvals, cnt = [], 0 colors = [ '#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33' ] reg_ovc = request.session.get('reg_ovc', 0) ovc_criterias = False total_ovc = odash['children_all'] if reg_ovc and total_ovc > 0: # Eligibility criteria ovc_criterias = True other_case = 0 cat_name = "Missing Criteria" cat_data = total_ovc cnt = 0 my_data = '{label: "%s", data: %s, color: "%s"}' % ( cat_name, cat_data, colors[cnt]) my_dvals.append(my_data) else: # Case category names cnames = get_dict(field_name=['case_category_id']) other_case = 0 for case_cat in case_cats: cat_id = case_cat['case_category'] cat_data = case_cat['unit_count'] if cnt > 4: other_case += cat_data else: cnm = cnames[cat_id] if cat_id in cnames else cat_id cat_name = cnm[:16] + ' ...' if len(cnm) > 16 else cnm my_data = '{label: "%s", data: %s, color: "%s"}' % ( cat_name, cat_data, colors[cnt]) my_dvals.append(my_data) cnt += 1 if not case_cats and not ovc_criterias: my_dvals.append('{label: "No data", data: 0, color: "#fd8d3c"}') if other_case > 0: my_dvals.append('{label: "Others", data: %s, color: "#fb9a99"}' % (other_case)) dvals = ', '.join(my_dvals) return render( request, 'dashboard.html', { 'status': 200, 'dates': dates, 'kvals': kvals, 'dvals': dvals, 'cvals': cvals, 'data': summary, 'ovals': ovals, 'ovc': ovc }) except Exception, e: print 'dashboard error - %s' % (str(e)) raise e
def ovc_view(request, id): """Some default page for Server Errors.""" try: aid = 0 reqid = request.GET.get('id', '') offset = request.GET.get('offset', '') limit = request.GET.get('limit', '') if reqid and offset and limit: aid = 2 if request.method == 'POST' or aid: msg, chs = manage_checkins(request, aid) results = {'status': 0, 'message': msg, 'checkins': chs} if aid == 2: results = chs return JsonResponse(results, content_type='application/json', safe=False) ovc_id = int(id) child = RegPerson.objects.get(is_void=False, id=ovc_id) creg = OVCRegistration.objects.get(is_void=False, person_id=ovc_id) days = 0 if not creg.is_active and creg.exit_date: edate = creg.exit_date tdate = date.today() days = (tdate - edate).days print 'exit days', days allow_edit = False if days > 90 else True params = {} gparams = {} # Get guardians guardians = RegPersonsGuardians.objects.filter( is_void=False, child_person_id=child.id) guids = [] for guardian in guardians: guids.append(guardian.guardian_person_id) guids.append(child.id) extids = RegPersonsExternalIds.objects.filter( person_id__in=guids) for extid in extids: if extid.person_id == child.id: params[extid.identifier_type_id] = extid.identifier else: gkey = '%s_%s' % (extid.person_id, extid.identifier_type_id) gparams[gkey] = extid.identifier # Health details health = {} if creg.hiv_status == 'HSTP': health = get_health(ovc_id) # School details school = {} if creg.school_level != 'SLNS': school = get_school(ovc_id) # Get house hold hhold = OVCHHMembers.objects.get( is_void=False, person_id=child.id) # Get HH members hhid = hhold.house_hold_id hhmqs = OVCHHMembers.objects.filter( is_void=False, house_hold_id=hhid).order_by("-hh_head") hhmembers = hhmqs.exclude(person_id=child.id) # Viral load vload = OVCViralload.objects.filter( is_void=False, person_id=ovc_id).order_by("-viral_date")[:1] vl_sup, v_val, v_dt = 'Missing', None, None if vload: for vl in vload: v_val = vl.viral_load v_dt = vl.viral_date vl_sup = 'YES' if not v_val or v_val < 1000 else 'NO' # Get siblings siblings = RegPersonsSiblings.objects.filter( is_void=False, child_person_id=child.id) # Get services servs = {'FSAM': 'f1a', 'FCSI': 'fcsi', 'FHSA': 'fhva'} services = {'f1a': 0, 'fcsi': 0, 'fhva': 0} sqs = OVCCareEvents.objects.filter( Q(person_id=child.id) | Q(house_hold_id=hhid)) sqs = sqs.filter(is_void=False).values( 'event_type_id').annotate( total=Count('event_type_id')).order_by('total') for serv in sqs: item = serv['event_type_id'] item_count = serv['total'] if item in servs: item_key = servs[item] services[item_key] = item_count # Re-usable values check_fields = ['relationship_type_id', 'school_level_id', 'hiv_status_id', 'immunization_status_id', 'art_status_id', 'school_type_id', 'class_level_id'] vals = get_dict(field_name=check_fields) return render(request, 'ovc/view_child.html', {'status': 200, 'child': child, 'params': params, 'guardians': guardians, 'siblings': siblings, 'vals': vals, 'hhold': hhold, 'creg': creg, 'extids': gparams, 'health': health, 'hhmembers': hhmembers, 'school': school, 'services': services, 'allow_edit': allow_edit, 'suppression': vl_sup}) except Exception, e: print "error with OVC viewing - %s" % (str(e)) raise e
from django.utils import timezone from django.contrib.auth.models import Group from dateutil.relativedelta import relativedelta from cpovc_main.functions import get_dict from cpovc_registry.models import AppUser, RegOrgUnit from cpovc_main.models import SetupGeography, SchoolList from cpovc_auth.models import CPOVCRole register = template.Library() # Declare Constants For Lookups check_fields = [ 'intervention_id', 'case_category_id', 'event_place_id', 'case_nature_id', 'core_item_id' ] vals = get_dict(field_name=check_fields) @register.filter(name='gen_value') def gen_value(value, args): if value in args: return args[value] else: return value @register.filter(name='gen_username') def gen_username(value): username = None if value: app_users = AppUser.objects.filter(id=value)
def generate_form(request, response, doc_id, case): """Method to generate form.""" try: # Settings child_id = case.person_id case_id = case.case_id_id check_fields = [ 'case_reporter_id', 'identifier_type_id', 'religion_type_id', 'tribe_category_id', 'event_place_id', 'perpetrator_status_id', 'relationship_type_id', 'case_category_id' ] vals = get_dict(field_name=check_fields) case_serial = case.case_id.case_serial sub_county = case.report_subcounty.area_name county_id = case.report_subcounty.parent_area_id case_open_date = case.case_id.date_case_opened case_date = str(case_open_date.strftime('%d %b, %Y')) # County county = get_area(county_id) # Org Unit org_unit = case.report_orgunit.org_unit_name # Reporter reporter_address = case.case_id.case_reporter_contacts reporter_fname = case.case_id.case_reporter_first_name reporter_sname = case.case_id.case_reporter_surname reporter_oname = case.case_id.case_reporter_other_names roname = reporter_oname if reporter_oname else '' rsname = reporter_sname if reporter_sname else '' rfname = reporter_fname if reporter_fname else '' reporter_names = '%s %s %s' % (rfname, rsname, roname) # Perpetrator perp_status = case.case_id.perpetrator_status perp_relation = param_val(case.case_id.perpetrator_relationship_type, vals) perpetrator_relation = perp_relation if perp_relation else '' print('PERP', perp_status) if perp_status == 'PKNW': perp_fname = case.case_id.perpetrator_first_name perp_sname = case.case_id.perpetrator_surname perp_oname = case.case_id.perpetrator_other_names poname = perp_oname if perp_oname else '' psname = perp_sname if perp_sname else '' pfname = perp_fname if perp_fname else '' perpetrator = '%s %s %s' % (pfname, psname, poname) else: perpetrator = param_val(perp_status, vals) reporter_type = param_val(case.case_id.case_reporter, vals) reporter_tel = reporter_address if reporter_address else 'N/A' risk_level = case.case_id.risk_level case_remarks = case.case_id.case_remarks case_info = case_remarks if case_remarks else '' # Child details ovc_fname = case.case_id.person.first_name ovc_onames = case.case_id.person.other_names ovc_sname = case.case_id.person.surname ovc_oname = ovc_onames if ovc_onames else '' child_name = '%s %s %s (%s)' % (ovc_fname, ovc_sname, ovc_oname, str(child_id)) ovc_sex = case.case_id.person.sex_id dob = case.case_id.person.date_of_birth ovc_dob = str(dob.strftime('%d %b, %Y')) if dob else 'N/A' # Geo child_sub_county, child_ward, child_county_id = 'N/A', 'N/A', 0 child_geos = RegPersonsGeo.objects.filter(person_id=child_id, is_void=False) for child_geo in child_geos: area_id = child_geo.area_id if area_id > 337: child_ward = child_geo.area.area_name else: child_sub_county = child_geo.area.area_name child_county_id = child_geo.area.parent_area_id area_type = child_geo.area_type print('A TYPE', area_type) child_county = get_area(child_county_id) # Siblings siblings, sid = {}, 0 child_siblings = RegPersonsSiblings.objects.filter( child_person_id=child_id) for cs in child_siblings: sid += 1 sib_id = str(cs.sibling_person_id) dob = cs.sibling_person.date_of_birth ssex = 'Male' if cs.sibling_person.sex_id == 'SMAL' else 'Female' sdob = str(dob.strftime('%d %b, %Y')) if dob else 'N/A' child_sib = { 'name': str(cs.sibling_person.first_name), 'dob': sdob, 'sex': ssex, 'remark': sib_id } siblings[sid] = child_sib if sid < 8: for i in range(sid + 1, 9): siblings[i] = {'name': '', 'dob': '', 'sex': '', 'remark': ''} # Caregivers / Parents cgnt = 0 pts = {'name': 'N/A', 'dob': '', 'idno': ''} ptf = {'name': 'N/A', 'dob': '', 'idno': ''} cgs = {'name': 'N/A', 'dob': '', 'idno': ''} cgf = {'name': 'N/A', 'dob': '', 'idno': ''} parents, guardians = {1: pts, 2: ptf}, {1: cgs, 2: cgf} caregivers = RegPersonsGuardians.objects.filter( child_person_id=child_id) for caregiver in caregivers: relation = caregiver.relationship cg_fname = caregiver.guardian_person.first_name cg_sname = caregiver.guardian_person.surname cg_name = '%s %s' % (str(cg_fname), str(cg_sname)) cg_dob = caregiver.guardian_person.date_of_birth if relation == 'CGPM': parents[2]['name'] = cg_name parents[2]['dob'] = cg_dob elif relation == 'CGPF': parents[1]['name'] = cg_name parents[1]['dob'] = cg_dob else: cgnt += 1 guardians[cgnt]['name'] = cg_name guardians[cgnt]['relation'] = relation guardians[cgnt]['dob'] = cg_dob # Child external ids extids = RegPersonsExternalIds.objects.filter(person_id=child_id, is_void=False) tribe, religion, bcert = '', '', 'ANNO' for extid in extids: if extid.identifier_type_id == 'ITRB': tribe = param_val(extid.identifier, vals) if extid.identifier_type_id == 'IREL': religion = extid.identifier if extid.identifier_type_id == 'RGBC': bcert = 'AYES' # Get medical meds = OVCMedical.objects.get(case_id_id=case_id) phy_cond = meds.physical_condition mental_cond = meds.mental_condition other_cond = meds.other_condition # Case details case_datas = OVCCaseCategory.objects.filter(case_id_id=case_id) for case_data in case_datas: case_date = str(case_data.date_of_event.strftime('%d %b, %Y')) case_place = param_val(case_data.place_of_event, vals) case_category = param_val(case_data.case_category, vals) case_nature = case_data.case_nature # Family status family_status = '' family_statuses = OVCFamilyStatus.objects.filter(case_id_id=case_id, is_void=False) for fstatus in family_statuses: family_status = str(fstatus.family_status) # HES hes_status = '' hess = OVCEconomicStatus.objects.filter(case_id_id=case_id, is_void=False) for hes in hess: hes_status = str(hes.household_economic_status) print(hes_status) # Dates todate = datetime.now() reporter_name = reporter_names.replace(' ', ' ').capitalize() doc_date = str(todate.strftime('%d %b, %Y')) ovc_data = { 'org_unit': org_unit, 'child_name': child_name.replace(' ', ' '), 'tribe': tribe, 'religion': religion, 'case_date': case_date, 'reporter_address': 'N/A', 'reporter_tel': reporter_tel, 'reporter_type': reporter_type, 'reporter_names': reporter_name, 'ovc_dob': ovc_dob, 'document_date': doc_date, 'parents': parents, 'caregivers': guardians, 'registration_date': 'Jan 20, 2017', 'county': county, 'sub_county': sub_county, 'sex': ovc_sex, 'institution': org_unit, 'case_serial': case_serial, 'phy_cond': phy_cond, 'mental_cond': mental_cond, 'other_cond': other_cond, 'bcert': bcert, 'case_date': case_date, 'case_place': case_place, 'hes_status': hes_status, 'perpetrator': perpetrator.capitalize(), 'perpetrator_relation': perpetrator_relation, 'case_category': case_category, 'case_nature': case_nature, 'family_status': family_status, 'risk_level': risk_level, 'child_county': child_county, 'case_remarks': case_info, 'child_ward': child_ward, 'child_sub_county': child_sub_county } services = { 'service_date': 'Jan 10, 2017', 'service_type': 'SERVICE', 'service_name': 'description' } ovc_items = {'services': services, 'siblings': siblings} print(ovc_data) print(ovc_items) generate_crs(response, ovc_data, ovc_items) except Exception as e: print('error generating document - %s' % (str(e))) raise e else: pass
def home(request): """Some default page for the home page / Dashboard.""" my_dates, my_cvals = [], [] my_ovals, my_kvals = [], [] my_dvals = [] try: dash = dashboard(request) start_date = datetime.now() - timedelta(days=21) summary = {} summary['org_units'] = '{:,}'.format(dash['org_units']) summary['children'] = '{:,}'.format(dash['children']) summary['guardians'] = '{:,}'.format(dash['guardian']) summary['workforce'] = '{:,}'.format(dash['workforce_members']) summary['cases'] = '{:,}'.format(dash['case_records']) summary['pending'] = '{:08}'.format(dash['pending_cases']) summary['inst_girls'] = '{:,}'.format(dash['inst_pop']['G']) summary['inst_boys'] = '{:,}'.format(dash['inst_pop']['B']) pcases = float(dash['pending_cases']) tcases = float(dash['case_records']) intervens = (pcases / tcases) if tcases > 0 else 0 interven = int(intervens * 100) summary['interven'] = interven # OVC care odash = ovc_dashboard(request) ovc = {} ovc['org_units'] = '{:,}'.format(odash['org_units']) ovc['children'] = '{:,}'.format(odash['children']) ovc['children_all'] = '{:,}'.format(odash['children_all']) ovc['guardians'] = '{:,}'.format(odash['guardian']) ovc['workforce'] = '{:,}'.format(odash['workforce_members']) ovc['cases'] = '{:,}'.format(odash['case_records']) ovc['pending'] = '{:08}'.format(odash['pending_cases']) child_regs = dash['child_regs'] ovc_regs = dash['ovc_regs'] case_regs = dash['case_regs'] case_cats = dash['case_cats'] cmax = 0 for date in range(0, 22, 2): end_date = start_date + timedelta(days=date) show_date = datetime.strftime(end_date, "%d-%b-%y") final_date = str(show_date).replace(' ', ' ') my_dates.append("[%s, '%s']" % (date, final_date)) for vl in range(1, 22): t_date = start_date + timedelta(days=vl) s_date = datetime.strftime(t_date, "%d-%b-%y") k_count = child_regs[s_date] if s_date in child_regs else 0 o_count = ovc_regs[s_date] if s_date in ovc_regs else 0 c_count = case_regs[s_date] if s_date in case_regs else 0 my_cvals.append("[%s, %s]" % (vl, c_count)) my_kvals.append("[%s, %s]" % (vl, k_count)) my_ovals.append("[%s, %s]" % (vl, o_count)) if k_count > cmax: cmax = k_count dates = ', '.join(my_dates) kvals = ', '.join(my_kvals) cvals = ', '.join(my_cvals) ovals = ', '.join(my_ovals) my_dvals, cnt = [], 0 colors = [ '#e41a1c', '#377eb8', '#4daf4a', '#984ea3', '#ff7f00', '#ffff33' ] # Case category names cat_names = get_dict(field_name=['case_category_id']) other_case = 0 for case_cat in case_cats: cat_id = case_cat['case_category'] cat_data = case_cat['unit_count'] if cnt > 4: other_case += cat_data else: cname = cat_names[cat_id] if cat_id in cat_names else cat_id cat_name = cname[:16] + ' ...' if len(cname) > 16 else cname my_data = '{label: "%s", data: %s, color: "%s"}' % ( cat_name, cat_data, colors[cnt]) my_dvals.append(my_data) cnt += 1 if not case_cats: my_dvals.append('{label: "No data", data: 0, color: "#fd8d3c"}') if other_case > 0: my_dvals.append('{label: "Others", data: %s, color: "#fb9a99"}' % (other_case)) dvals = ', '.join(my_dvals) inst_list = ['TNAP', 'TNRH', 'TNRS', 'TNRR', 'TNRB', 'TNRC'] sections = {} sections['SCCP'] = 'Child Protection' sections['SCPD'] = 'Planning and Development' sections['SCSI'] = 'Strategic Intervention' sections['SCCS'] = 'Community Child Support' sections['SAFC'] = 'Alternative Family Care' sections['SCIN'] = 'Institutions' sections['STIP'] = 'CTiP' cmax = 50 if cmax < 50 else cmax xmax = int(math.ceil(cmax / 100.0)) * 100 section_id = request.session.get('section_id', 'XXXX') section = sections[section_id] if section_id in sections else '' ext_ids = get_person_external_ids(request) alt_phone = ext_ids['CPHM'] if 'CPHM' in ext_ids else '' return render( request, 'dashboard.html', { 'status': 200, 'dates': dates, 'kvals': kvals, 'dvals': dvals, 'cvals': cvals, 'data': summary, 'ovals': ovals, 'ovc': ovc, 'inst_list': inst_list, 'section': section, 'xmax': xmax, 'alt_phone': alt_phone }) except Exception as e: print('dashboard error - %s' % (str(e))) raise e
def se_data(request): """Main home method and view.""" try: cases = [] ou_ids = [] org_unit = request.GET.get('org_unit') county = request.GET.get('county') persons = RegPersonsOrgUnits.objects.filter( is_void=False, date_delinked__isnull=True) check_fields = ['wdn_cadre_type_id', 'vol_cadre_type', 'sw_cadre_type_id', 'scc_cadre_type_id', 'po_cadre_type_id', 'pm_cadre_type_id', 'pa_cadre_type_id', 'cle_cadre_type_id', 'ogo_cadre_type_id', 'nct_cadre_type_id', 'mng_cadre_type_id', 'me_cadre_type_id', 'ict_cadre_type_id', 'hsm_cadre_type_id', 'hou_cadre_type_id', 'hos_cadre_type_id', 'dir_cadre_type_id', 'ddr_cadre_type_id', 'cc_cadre_type_id', 'cadre_type_id', 'adm_cadre_type_id'] vals = get_dict(field_name=check_fields) county_id = int(county) if county else 0 if org_unit: print('OU', org_unit) persons = persons.filter(org_unit_id=org_unit) # Get Geo Locations for pers in persons: if pers.org_unit_id not in ou_ids: ou_ids.append(pers.org_unit_id) ous = {} geos = RegOrgUnitGeography.objects.filter( is_void=False, org_unit_id__in=ou_ids, area_id__lt=338) for geo in geos: if county_id > 0: if county_id == int(geo.area.parent_area_id): ous[geo.org_unit_id] = geo.area.parent_area_id else: ous[geo.org_unit_id] = geo.area.parent_area_id if county_id > 0: persons = persons.filter(org_unit_id__in=ous) for person in persons: fname = person.person.first_name sname = person.person.surname o_name = person.person.other_names oname = ' %s' % o_name if o_name else '' sex = 'Male' if person.person.sex_id == 'SMAL' else 'Female' did = person.person.designation ou_id = person.org_unit_id cid = ous[ou_id] if ou_id in ous else None ccd = str(cid).zfill(3) if cid else None cname = PARAMS[ccd] if cid else None des = vals[did] if did in vals else 'N/A' age = person.person.years dob = str(person.person.date_of_birth) dt = {"cpims_id": person.person_id} dt['age'] = 'N/A' if dob == '1900-01-01' else age dt['designation'] = des dt['sex'] = sex dt['dob'] = dob dt['county'] = cname if cname else 'N/A' dt['org_unit'] = person.org_unit.org_unit_name dt['names'] = '%s %s%s' % (fname, sname, oname) cases.append(dt) result = {"data": cases} return JsonResponse(result, content_type='application/json', safe=False) except Exception as e: print('error - %s' % (e)) raise e else: pass
def integration_home(request): """Method to do pivot reports.""" try: persons = {} categories = {} case_data = {} case_ids = [] user_id = request.user.id form = CaseLoad(request.user) user_counties, user_geos = get_person_geo(request) print('Geos', user_counties, user_geos) rm_fields = ['is_void', 'account', 'case_serial'] check_fields = ['sex_id', 'case_category_id', 'case_reporter_id', 'family_status_id', 'household_economics', 'risk_level_id', 'mental_condition_id', 'perpetrator_status_id', 'other_condition_id', 'physical_condition_id', 'yesno_id'] vals = get_dict(field_name=check_fields) if request.method == 'POST': item_id = request.POST.get('item_id') case = OVCBasicCRS.objects.get( case_id=item_id, is_void=False) cdata = model_to_dict(case) for cd in cdata: cdt = cdata[cd] if len(str(cdt)) < 6 and cdt in vals: cdt = vals[cdt] if cdt and cd not in rm_fields: case_data[cd] = cdt if cdt and (cd == 'county' or cd == 'constituency'): cid = 'GPRV' if cd == 'county' else 'GDIS' cd_name = '%s name' % (cd) geo = get_geo(int(cdt), cid) if geo: geo_name = geo.area_name case_data[cd_name] = geo_name results = {'status': 0, 'message': 'Successful', 'dates': '', 'data': case_data} return JsonResponse(results, content_type='application/json', safe=False) cases = OVCBasicCRS.objects.filter( is_void=False).order_by('-timestamp_created') if not request.user.is_superuser: if request.user.username == 'vurugumapper': cases = cases.filter(account_id=user_id) else: cases = cases.filter(county__in=user_counties) for cs in cases: case_ids.append(cs.case_id) case_cats = OVCBasicCategory.objects.filter( is_void=False, case_id__in=case_ids) case_pers = OVCBasicPerson.objects.filter( is_void=False, case_id__in=case_ids) for ccat in case_cats: categories[ccat.case_id] = ccat for cpers in case_pers: pers_type = cpers.person_type if pers_type == 'PTCH': persons[cpers.case_id] = cpers for c in cases: cid = c.case_id category = categories[cid] if cid in categories else None child = persons[cid] if cid in persons else None setattr(c, 'category', category) setattr(c, 'child', child) return render(request, 'management/integration.html', {'form': form, 'cases': cases, 'vals': vals}) except Exception as e: print(e) raise e else: pass